lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
lain/src/buffer.rs
Mrmaxmeier/lain
f4ae991c30abda5860ff7ac3933d91cc62e9c2a1
use crate::traits::*; use crate::types::UnsafeEnum; use byteorder::{ByteOrder, WriteBytesExt}; use paste::paste; use std::io::Write; impl<T> SerializedSize for [T] where T: SerializedSize, { #[inline] default fn serialized_size(&self) -> usize { trace!("using default serialized_size for array"); if self.is_empty() { return 0; } let size = self .iter() .map(SerializedSize::serialized_size) .fold(0, |sum, i| sum + i); size } #[inline] fn min_nonzero_elements_size() -> usize { T::min_nonzero_elements_size() } #[inline] fn max_default_object_size() -> usize { T::max_default_object_size() } } macro_rules! impl_serialized_size_array { ( $($size:expr),* ) => { $( impl<T> SerializedSize for [T; $size] where T: SerializedSize { #[inline] fn serialized_size(&self) -> usize { trace!("using default serialized_size for array"); if $size == 0 { return 0; } let size = self .iter() .map(SerializedSize::serialized_size) .fold(0, |sum, i| sum + i); size } #[inline] fn min_nonzero_elements_size() -> usize { T::min_nonzero_elements_size() * $size } #[inline] fn max_default_object_size() -> usize { T::max_default_object_size() * $size } } )* } } impl_serialized_size_array!( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 ); impl<T> SerializedSize for Vec<T> where T: SerializedSize, { #[inline] fn serialized_size(&self) -> usize { trace!("getting serialized size for Vec"); if self.is_empty() { trace!("returning 0 since there's no elements"); return 0; } let size = self.iter().map(SerializedSize::serialized_size).sum(); trace!("size is 0x{:02X}", size); size } #[inline] fn min_nonzero_elements_size() -> usize { T::min_nonzero_elements_size() } #[inline] fn max_default_object_size() -> usize { T::max_default_object_size() } } impl SerializedSize for str { #[inline] fn serialized_size(&self) -> usize { trace!("getting serialized size of str"); self.len() } #[inline] fn min_nonzero_elements_size() -> usize { 1 } #[inline] fn max_default_object_size() -> usize { 1 } } impl SerializedSize for String { #[inline] fn serialized_size(&self) -> usize { trace!("getting serialized size of String"); self.len() } #[inline] fn min_nonzero_elements_size() -> usize { 1 } #[inline] fn max_default_object_size() -> usize { 1 } } impl<T> BinarySerialize for Vec<T> where T: BinarySerialize, { fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { let inner_ref: &[T] = self.as_ref(); inner_ref.binary_serialize::<_, E>(buffer) } } impl BinarySerialize for bool { #[inline(always)] default fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { let value = unsafe { *((self as *const bool) as *const u8) }; buffer.write_u8(value).unwrap(); std::mem::size_of::<u8>() } } impl BinarySerialize for i8 { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { buffer.write_i8(*self as i8).unwrap(); std::mem::size_of::<i8>() } } impl BinarySerialize for u8 { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { buffer.write_u8(*self as u8).unwrap(); std::mem::size_of::<u8>() } } impl BinarySerialize for [u8] { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { buffer.write(&self).unwrap() } } impl<T> BinarySerialize for [T] where T: BinarySerialize, { #[inline(always)] default fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { let mut bytes_written = 0; for item in self.iter() { bytes_written += item.binary_serialize::<W, E>(buffer); } bytes_written } } impl<T, const N: usize> BinarySerialize for [T; N] where T: BinarySerialize, { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { self.as_ref().binary_serialize::<W, E>(buffer) } } impl<T, I> BinarySerialize for UnsafeEnum<T, I> where T: BinarySerialize, I: BinarySerialize + Clone, { default fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { match *self { UnsafeEnum::Invalid(ref value) => value.binary_serialize::<_, E>(buffer), UnsafeEnum::Valid(ref value) => value.binary_serialize::<_, E>(buffer), } } } impl BinarySerialize for String { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { self.as_bytes().binary_serialize::<_, E>(buffer) } } impl BinarySerialize for &str { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { self.as_bytes().binary_serialize::<_, E>(buffer) } } impl BinarySerialize for *const std::ffi::c_void { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { #[cfg(target_pointer_width = "64")] let numeric_ptr = *self as u64; #[cfg(target_pointer_width = "32")] let numeric_ptr = *self as u32; #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))] panic!("unsupported pointer width"); numeric_ptr.binary_serialize::<_, E>(buffer) } } impl BinarySerialize for *mut std::ffi::c_void { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { let const_ptr = *self as *const std::ffi::c_void; BinarySerialize::binary_serialize::<_, E>(&const_ptr, buffer) } } impl<T> BinarySerialize for Option<T> where T: BinarySerialize, { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { if let Some(ref inner) = self { BinarySerialize::binary_serialize::<_, E>(inner, buffer) } else { 0 } } } impl<T> BinarySerialize for Box<T> where T: BinarySerialize, { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { BinarySerialize::binary_serialize::<_, E>(self.as_ref(), buffer) } } macro_rules! impl_binary_serialize { ( $($name:ident),* ) => { $( impl BinarySerialize for $name { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { paste! { buffer.[<write_ $name>]::<E>(*self as $name).unwrap(); } std::mem::size_of::<$name>() } } )* } } impl_binary_serialize!(i64, u64, i32, u32, i16, u16, f32, f64); macro_rules! impl_serialized_size { ( $($name:ident),* ) => { $( impl SerializedSize for $name { #[inline(always)] fn serialized_size(&self) -> usize { std::mem::size_of::<$name>() } #[inline] fn min_nonzero_elements_size() -> usize { std::mem::size_of::<$name>() } #[inline] fn max_default_object_size() -> usize { std::mem::size_of::<$name>() } } )* } } impl_serialized_size!(i64, u64, i32, u32, i16, u16, f32, f64, u8, i8, bool); impl<T, U> SerializedSize for T where T: ToPrimitive<Output = U>, { #[inline] default fn serialized_size(&self) -> usize { std::mem::size_of::<U>() } #[inline] default fn min_nonzero_elements_size() -> usize { std::mem::size_of::<U>() } #[inline] default fn max_default_object_size() -> usize { std::mem::size_of::<U>() } default fn min_enum_variant_size(&self) -> usize { std::mem::size_of::<U>() } } impl SerializedSize for &str { #[inline] fn serialized_size(&self) -> usize { self.len() } #[inline] fn min_nonzero_elements_size() -> usize { 1 } #[inline] fn max_default_object_size() -> usize { 1 } } impl SerializedSize for *const std::ffi::c_void { #[inline] fn serialized_size(&self) -> usize { std::mem::size_of::<usize>() } #[inline] fn min_nonzero_elements_size() -> usize { std::mem::size_of::<usize>() } #[inline] fn max_default_object_size() -> usize { std::mem::size_of::<usize>() } } impl SerializedSize for *mut std::ffi::c_void { #[inline] fn serialized_size(&self) -> usize { std::mem::size_of::<usize>() } #[inline] fn min_nonzero_elements_size() -> usize { std::mem::size_of::<usize>() } #[inline] fn max_default_object_size() -> usize { std::mem::size_of::<usize>() } } impl<T> SerializedSize for Option<T> where T: SerializedSize, { #[inline] fn serialized_size(&self) -> usize { if let Some(ref inner) = self { inner.serialized_size(); } 0 } #[inline] fn min_nonzero_elements_size() -> usize { T::min_nonzero_elements_size() } #[inline] fn max_default_object_size() -> usize { T::max_default_object_size() } }
use crate::traits::*; use crate::types::UnsafeEnum; use byteorder::{ByteOrder, WriteBytesExt}; use paste::paste; use std::io::Write; impl<T> SerializedSize for [T] where T: SerializedSize, { #[inline] default fn serialized_size(&self) -> usize { trace!("using default serialized_size for array"); if self.is_empty() { return 0; } let size = self .iter() .map(SerializedSize::serialized_size) .fold(0, |sum, i| sum + i); size } #[inline] fn min_nonzero_elements_size() -> usize { T::min_nonzero_elements_size() } #[inline] fn max_default_object_size() -> usize { T::max_default_object_size() } } macro_rules! impl_serialized_size_array { ( $($size:expr),* ) => { $( impl<T> SerializedSize for [T; $size] where T: SerializedSize { #[inline] fn serialized_size(&self) -> usize { trace!("using default serialized_size for array"); if $size == 0 { return 0; } let size = self .iter() .map(SerializedSize::serialized_size) .fold(0, |sum, i| sum + i); size } #[inline] fn min_nonzero_elements_size() -> usize { T::min_nonzero_elements_size() * $size } #[inline] fn max_default_object_size() -> usize { T::max_default_object_size() * $size } } )* } } impl_serialized_size_array!( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 ); impl<T> SerializedSize for Vec<T> where T: SerializedSize, { #[inline] fn serialized_size(&self) -> usize { trace!("getting serialized size for Vec"); if self.is_empty() { trace!("returning 0 since there's no elements"); return 0; } let size = self.iter().map(SerializedSize::serialized_size).sum(); trace!("size is 0x{:02X}", size); size } #[inline] fn min_nonzero_elements_size() -> usize { T::min_nonzero_elements_size() } #[inline] fn max_default_object_size() -> usize { T::max_default_object_size() } } impl SerializedSize for str { #[inline] fn serialized_size(&self) -> usize { trace!("getting serialized size of str"); self.len() } #[inline] fn min_nonzero_elements_size() -> usize { 1 } #[inline] fn max_default_object_size() -> usize { 1 } } impl SerializedSize for String { #[inline] fn serialized_size(&self) -> usize { trace!("getting serialized size of String"); self.len() } #[inline] fn min_nonzero_elements_size() -> usize { 1 } #[inline] fn max_default_object_size() -> usize { 1 } } impl<T> BinarySerialize for Vec<T> where T: BinarySerialize, { fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { let inner_ref: &[T] = self.as_ref(); inner_ref.binary_serialize::<_, E>(buffer) } } impl BinarySerialize for bool { #[inline(always)] default fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { let value = unsafe { *((self as *const bool) as *const u8) }; buffer.write_u8(value).unwrap(); std::mem::size_of::<u8>() } } impl BinarySerialize for i8 { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { buffer.write_i8(*self as i8).unwrap(); std::mem::size_of::<i8>() } } impl BinarySerialize for u8 { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { buffer.write_u8(*self as u8).unwrap(); std::mem::size_of::<u8>() } } impl BinarySerialize for [u8] { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { buffer.write(&self).unwrap() } } impl<T> BinarySerialize for [T] where T: BinarySerialize, { #[inline(always)] default fn binary_
} impl<T, const N: usize> BinarySerialize for [T; N] where T: BinarySerialize, { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { self.as_ref().binary_serialize::<W, E>(buffer) } } impl<T, I> BinarySerialize for UnsafeEnum<T, I> where T: BinarySerialize, I: BinarySerialize + Clone, { default fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { match *self { UnsafeEnum::Invalid(ref value) => value.binary_serialize::<_, E>(buffer), UnsafeEnum::Valid(ref value) => value.binary_serialize::<_, E>(buffer), } } } impl BinarySerialize for String { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { self.as_bytes().binary_serialize::<_, E>(buffer) } } impl BinarySerialize for &str { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { self.as_bytes().binary_serialize::<_, E>(buffer) } } impl BinarySerialize for *const std::ffi::c_void { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { #[cfg(target_pointer_width = "64")] let numeric_ptr = *self as u64; #[cfg(target_pointer_width = "32")] let numeric_ptr = *self as u32; #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))] panic!("unsupported pointer width"); numeric_ptr.binary_serialize::<_, E>(buffer) } } impl BinarySerialize for *mut std::ffi::c_void { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { let const_ptr = *self as *const std::ffi::c_void; BinarySerialize::binary_serialize::<_, E>(&const_ptr, buffer) } } impl<T> BinarySerialize for Option<T> where T: BinarySerialize, { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { if let Some(ref inner) = self { BinarySerialize::binary_serialize::<_, E>(inner, buffer) } else { 0 } } } impl<T> BinarySerialize for Box<T> where T: BinarySerialize, { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { BinarySerialize::binary_serialize::<_, E>(self.as_ref(), buffer) } } macro_rules! impl_binary_serialize { ( $($name:ident),* ) => { $( impl BinarySerialize for $name { #[inline(always)] fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { paste! { buffer.[<write_ $name>]::<E>(*self as $name).unwrap(); } std::mem::size_of::<$name>() } } )* } } impl_binary_serialize!(i64, u64, i32, u32, i16, u16, f32, f64); macro_rules! impl_serialized_size { ( $($name:ident),* ) => { $( impl SerializedSize for $name { #[inline(always)] fn serialized_size(&self) -> usize { std::mem::size_of::<$name>() } #[inline] fn min_nonzero_elements_size() -> usize { std::mem::size_of::<$name>() } #[inline] fn max_default_object_size() -> usize { std::mem::size_of::<$name>() } } )* } } impl_serialized_size!(i64, u64, i32, u32, i16, u16, f32, f64, u8, i8, bool); impl<T, U> SerializedSize for T where T: ToPrimitive<Output = U>, { #[inline] default fn serialized_size(&self) -> usize { std::mem::size_of::<U>() } #[inline] default fn min_nonzero_elements_size() -> usize { std::mem::size_of::<U>() } #[inline] default fn max_default_object_size() -> usize { std::mem::size_of::<U>() } default fn min_enum_variant_size(&self) -> usize { std::mem::size_of::<U>() } } impl SerializedSize for &str { #[inline] fn serialized_size(&self) -> usize { self.len() } #[inline] fn min_nonzero_elements_size() -> usize { 1 } #[inline] fn max_default_object_size() -> usize { 1 } } impl SerializedSize for *const std::ffi::c_void { #[inline] fn serialized_size(&self) -> usize { std::mem::size_of::<usize>() } #[inline] fn min_nonzero_elements_size() -> usize { std::mem::size_of::<usize>() } #[inline] fn max_default_object_size() -> usize { std::mem::size_of::<usize>() } } impl SerializedSize for *mut std::ffi::c_void { #[inline] fn serialized_size(&self) -> usize { std::mem::size_of::<usize>() } #[inline] fn min_nonzero_elements_size() -> usize { std::mem::size_of::<usize>() } #[inline] fn max_default_object_size() -> usize { std::mem::size_of::<usize>() } } impl<T> SerializedSize for Option<T> where T: SerializedSize, { #[inline] fn serialized_size(&self) -> usize { if let Some(ref inner) = self { inner.serialized_size(); } 0 } #[inline] fn min_nonzero_elements_size() -> usize { T::min_nonzero_elements_size() } #[inline] fn max_default_object_size() -> usize { T::max_default_object_size() } }
serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize { let mut bytes_written = 0; for item in self.iter() { bytes_written += item.binary_serialize::<W, E>(buffer); } bytes_written }
function_block-function_prefixed
[ { "content": "fn bench_serialize_1000(c: &mut Criterion) {\n\n let struct_size = std::mem::size_of::<NestedStruct>();\n\n let function_name = format!(\n\n \"serialize BigEndian with struct of size 0x{:X}\",\n\n struct_size\n\n );\n\n\n\n let nested = TestStruct {\n\n single_byte: 0,\n\n bitfield_1: 0,\n\n bitfield_2: 2,\n\n bitfield_3: 1,\n\n bitfield_4: 0,\n\n bitfield_5: 3,\n\n uint32: 0xFFEEDDCC,\n\n short: 0xAAFF,\n\n end_byte: 0x1,\n\n };\n\n\n\n let parent = NestedStruct {\n", "file_path": "testsuite/benches/benchmark_serialization_throughput.rs", "rank": 0, "score": 170212.68804234962 }, { "content": "fn serialized_size_enum(\n\n variants: &[Variant],\n\n cont_ident: &syn::Ident,\n\n size: Option<usize>,\n\n min_size: Option<usize>,\n\n) -> SerializedSizeBodies {\n\n let match_arms = serialized_size_enum_visitor(\n\n variants,\n\n cont_ident,\n\n SerializedSizeVisitorType::SerializedSize,\n\n );\n\n let nonzero_variants = serialized_size_enum_visitor(\n\n variants,\n\n cont_ident,\n\n SerializedSizeVisitorType::MinNonzeroElements,\n\n );\n\n let max_obj = serialized_size_enum_visitor(\n\n variants,\n\n cont_ident,\n\n SerializedSizeVisitorType::MaxDefaultObjectSize,\n", "file_path": "lain_derive/src/serialize.rs", "rank": 1, "score": 160995.60854891158 }, { "content": "fn field_serialized_size(\n\n field: &Field,\n\n name_prefix: &'static str,\n\n is_destructured: bool,\n\n visitor_type: SerializedSizeVisitorType,\n\n) -> (TokenStream, String, TokenStream) {\n\n let ty = &field.ty;\n\n let field_ident_string = match field.member {\n\n syn::Member::Named(ref ident) => ident.to_string(),\n\n syn::Member::Unnamed(ref idx) => idx.index.to_string(),\n\n };\n\n\n\n let value_ident =\n\n TokenStream::from_str(&format!(\"{}{}\", name_prefix, field_ident_string)).unwrap();\n\n let borrow = if is_destructured {\n\n TokenStream::new()\n\n } else {\n\n quote! {&}\n\n };\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 2, "score": 160995.60854891158 }, { "content": "fn serialized_size_body(\n\n cont: &Container,\n\n size: Option<usize>,\n\n min_size: Option<usize>,\n\n) -> SerializedSizeBodies {\n\n if let Some(size) = size.clone() {\n\n let size_tokens = quote! {#size};\n\n\n\n return SerializedSizeBodies {\n\n serialized_size: size_tokens.clone(),\n\n min_nonzero_elements_size: size_tokens.clone(),\n\n max_default_object_size: size_tokens.clone(),\n\n min_enum_variant_size: size_tokens.clone(),\n\n };\n\n }\n\n\n\n match cont.data {\n\n Data::Enum(ref variants) if variants[0].style != Style::Unit => {\n\n serialized_size_enum(variants, &cont.ident, size, min_size)\n\n }\n", "file_path": "lain_derive/src/serialize.rs", "rank": 3, "score": 160995.60854891158 }, { "content": "fn serialized_size_struct(fields: &[Field]) -> SerializedSizeBodies {\n\n let serialized_size =\n\n serialized_size_struct_visitor(fields, SerializedSizeVisitorType::SerializedSize);\n\n\n\n let min_nonzero =\n\n serialized_size_struct_visitor(fields, SerializedSizeVisitorType::MinNonzeroElements);\n\n\n\n let max_default =\n\n serialized_size_struct_visitor(fields, SerializedSizeVisitorType::MaxDefaultObjectSize);\n\n\n\n SerializedSizeBodies {\n\n serialized_size: quote! {0 #(+#serialized_size)* },\n\n min_nonzero_elements_size: quote! { 0 #(+#min_nonzero)* },\n\n max_default_object_size: quote! {0 #(+#max_default)*},\n\n min_enum_variant_size: quote! {Self::min_nonzero_elements_size()},\n\n }\n\n}\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 4, "score": 158925.02978669992 }, { "content": "fn serialized_size_enum_visitor(\n\n variants: &[Variant],\n\n cont_ident: &syn::Ident,\n\n visitor_type: SerializedSizeVisitorType,\n\n) -> Vec<TokenStream> {\n\n let match_arms = variants\n\n .iter()\n\n .map(|variant| {\n\n let variant_ident = &variant.ident;\n\n let full_ident = quote! {#cont_ident::#variant_ident};\n\n\n\n // TODO BUGBUG: need to decouple BinarySerialize from NewFuzzed to not hit this case with mixed unit/struct enum\n\n if variant.fields.is_empty() {\n\n return match visitor_type {\n\n SerializedSizeVisitorType::SerializedSize\n\n | SerializedSizeVisitorType::MinEnumVariantSize => {\n\n quote_spanned! { variant.original.span() =>\n\n #full_ident => {\n\n 0\n\n }\n", "file_path": "lain_derive/src/serialize.rs", "rank": 5, "score": 156759.32407616824 }, { "content": "fn serialized_size_struct_visitor(\n\n fields: &[Field],\n\n visitor_type: SerializedSizeVisitorType,\n\n) -> Vec<TokenStream> {\n\n fields\n\n .iter()\n\n .map(|field| {\n\n let (_field_ident, _field_ident_string, serialized_size) =\n\n field_serialized_size(field, \"self.\", false, visitor_type);\n\n\n\n serialized_size\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 6, "score": 156759.32407616824 }, { "content": "fn binary_serialize_struct_visitor(fields: &[Field]) -> Vec<TokenStream> {\n\n fields\n\n .iter()\n\n .map(|field| {\n\n let (_field_ident, _field_ident_string, serializer) =\n\n field_serializer(field, \"self.\", false);\n\n\n\n serializer\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 7, "score": 153365.41173799708 }, { "content": "fn serialized_size_unit_enum(cont_ident: &syn::Ident) -> SerializedSizeBodies {\n\n let size = quote! {\n\n std::mem::size_of::<<#cont_ident as _lain::traits::ToPrimitive>::Output>()\n\n };\n\n\n\n SerializedSizeBodies {\n\n serialized_size: size.clone(),\n\n min_nonzero_elements_size: size.clone(),\n\n max_default_object_size: size.clone(),\n\n min_enum_variant_size: size,\n\n }\n\n}\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 8, "score": 149179.26963525027 }, { "content": "/// Shrinks a `Vec`.\n\n/// This will randomly select to resize by a factor of 1/4, 1/2, 3/4, or a fixed number of bytes\n\n/// in the range of [1, 8]. Elements may be removed randomly from the beginning or end of the the vec\n\nfn shrink_vec<T, R: Rng>(vec: &mut Vec<T>, mutator: &mut Mutator<R>) {\n\n if vec.is_empty() {\n\n return;\n\n }\n\n\n\n let resize_count = VecResizeCount::new_fuzzed(mutator, None);\n\n let mut num_elements = match resize_count {\n\n VecResizeCount::Quarter => vec.len() / 4,\n\n VecResizeCount::Half => vec.len() / 2,\n\n VecResizeCount::ThreeQuarters => vec.len() - (vec.len() / 4),\n\n VecResizeCount::FixedBytes => mutator.gen_range(1, 9),\n\n VecResizeCount::AllBytes => vec.len(),\n\n };\n\n\n\n if num_elements == 0 {\n\n num_elements = mutator.gen_range(0, vec.len() + 1);\n\n }\n\n\n\n num_elements = std::cmp::min(num_elements, vec.len());\n\n\n", "file_path": "lain/src/mutatable.rs", "rank": 9, "score": 145906.43972948522 }, { "content": "pub fn hexdump(data: &[u8]) -> String {\n\n let mut ret = \"------\".to_string();\n\n for i in 0..16 {\n\n ret += &format!(\"{:02X} \", i);\n\n }\n\n\n\n let mut ascii = String::new();\n\n for (i, b) in data.iter().enumerate() {\n\n if i % 16 == 0 {\n\n ret += &format!(\"\\t{}\", ascii);\n\n ascii.clear();\n\n ret += &format!(\"\\n{:04X}:\", i);\n\n }\n\n\n\n ret += &format!(\" {:02X}\", b);\n\n // this is the printable ASCII range\n\n if *b >= 0x20 && *b <= 0x7f {\n\n ascii.push(*b as char);\n\n } else {\n\n ascii.push('.');\n", "file_path": "lain/src/lib.rs", "rank": 10, "score": 143945.16096333138 }, { "content": "/// Grows a `Vec`.\n\n/// This will randomly select to grow by a factor of 1/4, 1/2, 3/4, or a fixed number of bytes\n\n/// in the range of [1, 8]. Elements may be added randomly to the beginning or end of the the vec\n\nfn grow_vec<T: NewFuzzed + SerializedSize, R: Rng>(\n\n vec: &mut Vec<T>,\n\n mutator: &mut Mutator<R>,\n\n mut max_size: Option<usize>,\n\n) {\n\n let resize_count = VecResizeCount::new_fuzzed(mutator, None);\n\n let mut num_elements = if vec.is_empty() {\n\n mutator.gen_range(1, 9)\n\n } else {\n\n match resize_count {\n\n VecResizeCount::Quarter => vec.len() / 4,\n\n VecResizeCount::Half => vec.len() / 2,\n\n VecResizeCount::ThreeQuarters => vec.len() - (vec.len() / 4),\n\n VecResizeCount::FixedBytes => mutator.gen_range(1, 9),\n\n VecResizeCount::AllBytes => {\n\n mutator.gen_range(1, vec.len() + 1)\n\n }\n\n }\n\n };\n\n\n", "file_path": "lain/src/mutatable.rs", "rank": 11, "score": 140156.517742415 }, { "content": "fn field_serializer(\n\n field: &Field,\n\n name_prefix: &'static str,\n\n is_destructured: bool,\n\n) -> (TokenStream, String, TokenStream) {\n\n let ty = &field.ty;\n\n let field_ident_string = match field.member {\n\n syn::Member::Named(ref ident) => ident.to_string(),\n\n syn::Member::Unnamed(ref idx) => idx.index.to_string(),\n\n };\n\n\n\n let value_ident =\n\n TokenStream::from_str(&format!(\"{}{}\", name_prefix, field_ident_string)).unwrap();\n\n let borrow = if is_destructured {\n\n TokenStream::new()\n\n } else {\n\n quote! {&}\n\n };\n\n\n\n let endian = if field.attrs.big_endian() {\n", "file_path": "lain_derive/src/serialize.rs", "rank": 12, "score": 133926.68300759696 }, { "content": "pub fn expand_binary_serialize(input: &syn::DeriveInput) -> Result<TokenStream, Vec<syn::Error>> {\n\n let ctx = Ctxt::new();\n\n\n\n let cont = match Container::from_ast(&ctx, input, Derive::NewFuzzed) {\n\n Some(cont) => cont,\n\n None => return Err(ctx.check().unwrap_err()),\n\n };\n\n\n\n ctx.check()?;\n\n\n\n let ident = &cont.ident;\n\n let ident_as_string = ident.to_string();\n\n let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();\n\n\n\n let serialize_body = binary_serialize_body(&cont);\n\n let SerializedSizeBodies {\n\n serialized_size,\n\n min_nonzero_elements_size,\n\n max_default_object_size,\n\n min_enum_variant_size,\n", "file_path": "lain_derive/src/serialize.rs", "rank": 13, "score": 130591.65128550818 }, { "content": "fn binary_serialize_enum_visitor(\n\n variants: &[Variant],\n\n cont_ident: &syn::Ident,\n\n) -> Vec<TokenStream> {\n\n let match_arms = variants\n\n .iter()\n\n .map(|variant| {\n\n let variant_ident = &variant.ident;\n\n let full_ident = quote! {#cont_ident::#variant_ident};\n\n let mut field_identifiers = vec![];\n\n\n\n // TODO BUGBUG: need to decouple BinarySerialize from NewFuzzed to not hit this case with mixed unit/struct enum\n\n if variant.fields.is_empty() {\n\n return quote_spanned! { variant.original.span() =>\n\n #full_ident => {\n\n // do nothing for #full_ident\n\n }\n\n };\n\n }\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 14, "score": 127518.78511819264 }, { "content": "fn is_primitive_path(path: &syn::Path, primitive: &str) -> bool {\n\n path.leading_colon.is_none()\n\n && path.segments.len() == 1\n\n && path.segments[0].ident == primitive\n\n && path.segments[0].arguments.is_empty()\n\n}\n", "file_path": "lain_derive/src/internals/ast.rs", "rank": 15, "score": 123073.38841000095 }, { "content": "fn bench_default_1000(c: &mut Criterion) {\n\n let struct_size = std::mem::size_of::<NestedStruct>();\n\n let function_name = format!(\"bench_default_1000 struct of size 0x{:X}\", struct_size);\n\n\n\n c.bench(\n\n function_name.as_ref(),\n\n Benchmark::new(\"fuzz\", move |b| {\n\n b.iter(|| {\n\n let s = NestedStruct::default();\n\n black_box(s);\n\n });\n\n })\n\n .throughput(Throughput::Bytes(struct_size as u32)),\n\n );\n\n}\n\n\n\ncriterion_group!(\n\n benches,\n\n bench_new_fuzzed_1000,\n\n bench_default_1000,\n\n bench_in_place_mutation\n\n);\n\ncriterion_main!(benches);\n", "file_path": "testsuite/benches/benchmark_generating_fuzzed_struct.rs", "rank": 16, "score": 119539.43740381958 }, { "content": "pub fn is_primitive_type(ty: &syn::Type, primitive: &str) -> bool {\n\n match *ty {\n\n syn::Type::Path(ref ty) => ty.qself.is_none() && is_primitive_path(&ty.path, primitive),\n\n _ => false,\n\n }\n\n}\n\n\n", "file_path": "lain_derive/src/internals/ast.rs", "rank": 17, "score": 117951.29809986768 }, { "content": "fn binary_serialize_body(cont: &Container) -> TokenStream {\n\n match cont.data {\n\n Data::Enum(ref variants) if variants[0].style != Style::Unit => {\n\n binary_serialize_enum(variants, &cont.ident)\n\n }\n\n Data::Enum(ref _variants) => binary_serialize_unit_enum(&cont.ident),\n\n Data::Struct(Style::Struct, ref fields) | Data::Struct(Style::Tuple, ref fields) => {\n\n binary_serialize_struct(fields)\n\n }\n\n Data::Struct(Style::Unit, ref _fields) => TokenStream::new(),\n\n }\n\n}\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 18, "score": 114411.98084756162 }, { "content": "fn binary_serialize_struct(fields: &[Field]) -> TokenStream {\n\n let serializers = binary_serialize_struct_visitor(fields);\n\n\n\n quote! {\n\n let mut bitfield: u64 = 0;\n\n\n\n #(#serializers)*\n\n }\n\n}\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 19, "score": 114411.98084756162 }, { "content": "struct SerializedSizeBodies {\n\n serialized_size: TokenStream,\n\n min_nonzero_elements_size: TokenStream,\n\n max_default_object_size: TokenStream,\n\n min_enum_variant_size: TokenStream,\n\n}\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 20, "score": 110415.23719621557 }, { "content": "#[derive(Copy, Clone, PartialEq)]\n\nenum SerializedSizeVisitorType {\n\n SerializedSize,\n\n MinNonzeroElements,\n\n MaxDefaultObjectSize,\n\n MinEnumVariantSize,\n\n}\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 21, "score": 107278.50657342415 }, { "content": "fn binary_serialize_unit_enum(cont_ident: &syn::Ident) -> TokenStream {\n\n quote! {\n\n bytes_written += <<#cont_ident as _lain::traits::ToPrimitive>::Output>::binary_serialize::<_, E>(&self.to_primitive(), buffer);\n\n }\n\n}\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 22, "score": 106184.51712010652 }, { "content": "fn binary_serialize_enum(variants: &[Variant], cont_ident: &syn::Ident) -> TokenStream {\n\n let match_arms = binary_serialize_enum_visitor(variants, cont_ident);\n\n\n\n quote! {\n\n let mut bitfield: u64 = 0;\n\n\n\n match *self {\n\n #(#match_arms)*\n\n }\n\n }\n\n}\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 23, "score": 102184.78251276206 }, { "content": "/// Wraps the code in a dummy const object. See https://github.com/serde-rs/serde/issues/159#issuecomment-214002626\n\npub fn wrap_in_const(trait_: &str, ty: &Ident, code: TokenStream) -> TokenStream {\n\n let dummy_const = Ident::new(\n\n &format!(\"_IMPL_{}_FOR_{}\", trait_, unraw(ty)),\n\n Span::call_site(),\n\n );\n\n\n\n let use_lain = quote! {\n\n #[allow(unknown_lints)]\n\n #[cfg_attr(feature = \"cargo-clippy\", allow(useless_attribute))]\n\n #[allow(rust_2018_idioms)]\n\n use ::lain as _lain;\n\n };\n\n\n\n quote! {\n\n #[allow(clippy)]\n\n #[allow(unknown_lints)]\n\n #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]\n\n const #dummy_const: () = {\n\n #use_lain\n\n #code\n\n };\n\n }\n\n}\n", "file_path": "lain_derive/src/dummy.rs", "rank": 24, "score": 95167.00850519196 }, { "content": "/// A trait to represent the output size (in bytes) of an object when serialized to binary.\n\npub trait SerializedSize {\n\n /// Serialized size in bytes of this data type\n\n fn serialized_size(&self) -> usize;\n\n\n\n /// Minimum size in bytes of this data type. This is useful for determining\n\n /// the smallest size that a data type with a dynamic-sized member (e.g. Vec or String)\n\n /// may be\n\n fn min_nonzero_elements_size() -> usize;\n\n\n\n /// Maximum size in bytes of this data type with *the minimum amount of elements*. This is useful\n\n /// for determining the maximum size that a data type with a dynamic-sized member (e.g. Vec or String)\n\n /// may be within an enum with struct members.\n\n fn max_default_object_size() -> usize {\n\n Self::min_nonzero_elements_size()\n\n }\n\n\n\n /// Minimum size of the selected enum variant.\n\n fn min_enum_variant_size(&self) -> usize {\n\n Self::min_nonzero_elements_size()\n\n }\n\n}\n\n\n", "file_path": "lain/src/traits.rs", "rank": 25, "score": 94122.69817879262 }, { "content": "fn bench_in_place_mutation(c: &mut Criterion) {\n\n let struct_size = std::mem::size_of::<NestedStruct>();\n\n let function_name = format!(\"bench_in_place_mutation struct of size 0x{:X}\", struct_size);\n\n\n\n c.bench(\n\n function_name.as_ref(),\n\n Benchmark::new(\"fuzz\", move |b| {\n\n let mut mutator = Mutator::new(lain::rand::rngs::SmallRng::from_seed([0u8; 16]));\n\n let mut s = NestedStruct::new_fuzzed(&mut mutator, None);\n\n b.iter(|| {\n\n let mut s = s.clone();\n\n let state = mutator.get_corpus_state();\n\n s.mutate(&mut mutator, None);\n\n black_box(&s);\n\n mutator.set_corpus_state(state);\n\n });\n\n })\n\n .throughput(Throughput::Bytes(struct_size as u32)),\n\n );\n\n}\n\n\n", "file_path": "testsuite/benches/benchmark_generating_fuzzed_struct.rs", "rank": 26, "score": 90353.45266443415 }, { "content": "fn bench_new_fuzzed_1000(c: &mut Criterion) {\n\n let struct_size = std::mem::size_of::<NestedStruct>();\n\n let function_name = format!(\"bench_new_fuzzed struct of size 0x{:X}\", struct_size);\n\n\n\n c.bench(\n\n function_name.as_ref(),\n\n Benchmark::new(\"fuzz\", move |b| {\n\n let mut mutator = Mutator::new(lain::rand::rngs::SmallRng::from_seed([0u8; 16]));\n\n b.iter(|| {\n\n let s = NestedStruct::new_fuzzed(&mut mutator, None);\n\n black_box(s);\n\n });\n\n })\n\n .throughput(Throughput::Bytes(struct_size as u32)),\n\n );\n\n}\n\n\n", "file_path": "testsuite/benches/benchmark_generating_fuzzed_struct.rs", "rank": 27, "score": 90353.45266443415 }, { "content": "pub fn unraw(ident: &Ident) -> String {\n\n ident.to_string().trim_start_matches(\"r#\").to_owned()\n\n}\n\n\n\n/// Represents field attribute information\n\npub struct Field {\n\n bits: Option<usize>,\n\n bit_shift: Option<usize>,\n\n bitfield_type: Option<syn::Type>,\n\n min: Option<TokenStream>,\n\n max: Option<TokenStream>,\n\n ignore: bool,\n\n ignore_chance: Option<f64>,\n\n initializer: Option<TokenStream>,\n\n little_endian: bool,\n\n big_endian: bool,\n\n weight_to: Option<WeightTo>,\n\n is_last_field: bool,\n\n}\n\n\n", "file_path": "lain_derive/src/internals/attr.rs", "rank": 28, "score": 89715.34280745775 }, { "content": "fn mutatable_struct_visitor(fields: &[Field]) -> Vec<TokenStream> {\n\n fields\n\n .iter()\n\n .map(|field| {\n\n let (_field_ident, _field_ident_string, initializer) =\n\n field_mutator(field, \"self.\", false);\n\n\n\n quote! {\n\n #initializer\n\n }\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "lain_derive/src/mutations.rs", "rank": 29, "score": 85597.08526824898 }, { "content": "fn decrement_max_size(field: &Field, value_ident: &TokenStream) -> TokenStream {\n\n let ty = field.ty;\n\n let _field_ident_string = match field.member {\n\n syn::Member::Named(ref ident) => ident.to_string(),\n\n syn::Member::Unnamed(ref idx) => idx.index.to_string(),\n\n };\n\n\n\n let ty_size = quote! {\n\n (<#ty>::max_default_object_size() as isize)\n\n };\n\n\n\n let ty_string = quote! {#ty}.to_string();\n\n\n\n quote! {\n\n _lain::log::trace!(\"{} is variable size? {}\", #ty_string, <#ty>::is_variable_size());\n\n\n\n if let Some(ref mut max_size) = max_size {\n\n // we only subtract off the difference between the object's allocated size\n\n // and its min size.\n\n let size_delta = (#value_ident.serialized_size() as isize) - #ty_size;\n", "file_path": "lain_derive/src/mutations.rs", "rank": 30, "score": 83206.54952854551 }, { "content": "fn struct_field_constraints(field: &Field, for_mutation: bool) -> TokenStream {\n\n let attrs = &field.attrs;\n\n if !for_mutation {\n\n if attrs.ignore() || (attrs.initializer().is_some() && !attrs.ignore_chance().is_some()) {\n\n return TokenStream::new();\n\n }\n\n }\n\n\n\n if attrs.min().is_some() || attrs.max().is_some() || attrs.bits().is_some() {\n\n let min: TokenStream;\n\n let max: TokenStream;\n\n\n\n if let Some(bits) = attrs.bits() {\n\n // TODO: maybe refactor attributes so that they can retain original span\n\n let bitfield_max = syn::LitInt::new(\n\n 2_u64.pow(bits as u32),\n\n syn::IntSuffix::None,\n\n Span::call_site(),\n\n );\n\n max = quote! {Some(#bitfield_max)};\n", "file_path": "lain_derive/src/mutations.rs", "rank": 31, "score": 82223.30055199866 }, { "content": "fn mutatable_decrement_max_size(field: &Field, value_ident: &TokenStream) -> TokenStream {\n\n let ty = field.ty;\n\n let _field_ident_string = match field.member {\n\n syn::Member::Named(ref ident) => ident.to_string(),\n\n syn::Member::Unnamed(ref idx) => idx.index.to_string(),\n\n };\n\n\n\n let ty_size = quote! {\n\n previous_size as isize\n\n };\n\n\n\n let ty_string = quote! {#ty}.to_string();\n\n\n\n quote! {\n\n _lain::log::trace!(\"{} is variable size? {}\", #ty_string, <#ty>::is_variable_size());\n\n\n\n if mutated {\n\n if let Some(ref mut max_size) = max_size {\n\n // we only subtract off the difference between the object's allocated size\n\n // and its min size.\n", "file_path": "lain_derive/src/mutations.rs", "rank": 32, "score": 81225.32477296786 }, { "content": "#[proc_macro_derive(BinarySerialize, attributes(lain))]\n\npub fn binary_serialize(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n serialize::expand_binary_serialize(&input)\n\n .unwrap_or_else(to_compile_errors)\n\n .into()\n\n}\n\n\n\n/// Automatically implements [trait@lain::traits::Mutatable] with basic\n\n/// randomization\n\n///\n\n/// # Notes\n\n///\n\n/// - Any bitfields will automatically be set within the appropriate ranges.\n\n/// - Min/max values for primitives can be specified using `#[lain(min = 10, max = 20)]`.\n\n/// - Fields can be ignored using #[lain(ignore)].\n\n/// - Custom initializers can be specified using #[lain(initializer = \"my_initializer_func()\")]\n\n///\n\n/// # Example\n\n///\n\n/// ```compile_fail\n", "file_path": "lain_derive/src/lib.rs", "rank": 33, "score": 79760.36013168652 }, { "content": "fn to_compile_errors(errors: Vec<syn::Error>) -> proc_macro2::TokenStream {\n\n let compile_errors = errors.iter().map(syn::Error::to_compile_error);\n\n quote!(#(#compile_errors)*)\n\n}\n\n\n\n/// Implements [rand::distributions::Standard] for enums that derive this trait.\n\n/// This will allow you to use `rand::gen()` to randomly select an enum value.\n\n/// # Example\n\n///\n\n/// ```compile_fail\n\n/// extern crate rand;\n\n///\n\n/// #[derive(NewFuzzed)]\n\n/// enum Foo {\n\n/// Bar,\n\n/// Baz,\n\n/// }\n\n///\n\n/// let choice: Foo = rand::gen();\n\n/// ```\n", "file_path": "lain_derive/src/lib.rs", "rank": 34, "score": 78166.3617015838 }, { "content": "fn respan_token_tree(mut token: TokenTree, span: Span) -> TokenTree {\n\n if let TokenTree::Group(ref mut g) = token {\n\n *g = Group::new(g.delimiter(), respan_token_stream(g.stream().clone(), span));\n\n }\n\n token.set_span(span);\n\n token\n\n}\n", "file_path": "lain_derive/src/internals/attr.rs", "rank": 35, "score": 75782.93186399862 }, { "content": "fn mutatable_enum_visitor(variants: &[Variant], cont_ident: &syn::Ident) -> Vec<TokenStream> {\n\n let match_arms = variants\n\n .iter()\n\n .filter_map(|variant| {\n\n // if variant.attrs.ignore() {\n\n // return None;\n\n // }\n\n\n\n let variant_ident = &variant.ident;\n\n let full_ident = quote! {#cont_ident::#variant_ident};\n\n let mut field_identifiers = vec![];\n\n\n\n let field_mutators: Vec<TokenStream> = variant\n\n .fields\n\n .iter()\n\n .map(|field| {\n\n let (value_ident, _field_ident_string, initializer) =\n\n field_mutator(field, \"__field\", true);\n\n field_identifiers.push(quote_spanned! { field.member.span() => #value_ident });\n\n\n", "file_path": "lain_derive/src/mutations.rs", "rank": 36, "score": 73656.28966513606 }, { "content": "pub fn get_lit_str<'a>(\n\n cx: &Ctxt,\n\n attr_name: Symbol,\n\n meta_item_name: Symbol,\n\n lit: &'a syn::Lit,\n\n) -> Result<&'a syn::LitStr, ()> {\n\n if let syn::Lit::Str(ref lit) = *lit {\n\n Ok(lit)\n\n } else {\n\n cx.error_spanned_by(\n\n lit,\n\n format!(\n\n \"expected lain {} attribute to be a string: `{} = \\\"...\\\"`\",\n\n attr_name, meta_item_name\n\n ),\n\n );\n\n Err(())\n\n }\n\n}\n\n\n", "file_path": "lain_derive/src/internals/attr.rs", "rank": 37, "score": 73316.04528254544 }, { "content": "fn gen_struct_new_fuzzed_impl(\n\n name: &syn::Ident,\n\n fields: &[FuzzerObjectStructField],\n\n) -> TokenStream {\n\n let mut generate_arms = vec![];\n\n let mut generate_linear = vec![];\n\n\n\n for (i, f) in fields.iter().enumerate() {\n\n let span = f.field.span();\n\n let ty = &f.field.ty;\n\n\n\n let mut field_mutation_tokens = TokenStream::new();\n\n let ident = &f.field.ident;\n\n\n\n // If the field is ignored, return the default value\n\n if f.ignore {\n\n field_mutation_tokens.extend(quote_spanned! { span =>\n\n let value = <#ty>::default();\n\n });\n\n }\n", "file_path": "lain_derive/src/new_fuzzed_old.rs", "rank": 38, "score": 73081.5861771204 }, { "content": "fn new_fuzzed_struct_visitor(fields: &[Field], cont_ident: &syn::Ident) -> Vec<TokenStream> {\n\n fields\n\n .iter()\n\n .map(|field| {\n\n let (field_ident, _field_ident_string, initializer) = field_initializer(field, \"self\");\n\n let ty = &field.ty;\n\n let member = &field.member;\n\n\n\n quote! {\n\n #initializer\n\n\n\n let field_offset = _lain::field_offset::offset_of!(#cont_ident => #member).get_byte_offset() as isize;\n\n\n\n unsafe {\n\n let field_ptr = (uninit_struct_ptr as *mut u8).offset(field_offset) as *mut #ty;\n\n\n\n std::ptr::write(field_ptr, #field_ident);\n\n }\n\n }\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "lain_derive/src/mutations.rs", "rank": 39, "score": 72417.05781268768 }, { "content": "/// Gets the meta items for #[weight()] attributes\n\nfn get_weighted_metadata(attr: &syn::Attribute) -> Option<Vec<syn::NestedMeta>> {\n\n get_attribute_metadata(\"weight\", &attr)\n\n}\n\n\n", "file_path": "lain_derive/src/new_fuzzed_old.rs", "rank": 40, "score": 72417.05781268768 }, { "content": "fn fuzzer_routine<R: Rng>(mutator: &mut Mutator<R>, thread_context: &mut FuzzerThreadContext, _global_context: Option<Arc<RwLock<GlobalContext>>>) -> Result<(), ()> {\n\n // TODO: we have overhead here of re-estabilishing the connection every time\n\n let mut stream = TcpStream::connect(\"127.0.0.1:8080\").expect(\"server isn't running. possible crash?\");\n\n\n\n let packet = match thread_context.last_packet {\n\n Some(ref mut last_packet) => {\n\n last_packet.mutate(mutator, None);\n\n last_packet\n\n }\n\n _ => {\n\n mutator.begin_new_corpus();\n\n\n\n thread_context.last_packet = Some(PacketData::new_fuzzed(mutator, None));\n\n thread_context.last_packet.as_mut().unwrap()\n\n }\n\n };\n\n\n\n let mut serialized_data = Vec::with_capacity(packet.serialized_size());\n\n packet.binary_serialize::<_, LittleEndian>(&mut serialized_data);\n\n\n", "file_path": "examples/example_fuzzer/src/main.rs", "rank": 41, "score": 69687.44228710765 }, { "content": "pub fn get_lain_meta_items(attr: &syn::Attribute) -> Option<Vec<syn::NestedMeta>> {\n\n if attr.path == LAIN {\n\n match attr.interpret_meta() {\n\n Some(List(ref meta)) => Some(meta.nested.iter().cloned().collect()),\n\n _ => {\n\n // TODO: produce an error\n\n None\n\n }\n\n }\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "lain_derive/src/internals/attr.rs", "rank": 42, "score": 69638.30221762264 }, { "content": "fn struct_from_ast<'a>(cx: &Ctxt, fields: &'a syn::Fields) -> (Style, Vec<Field<'a>>) {\n\n match *fields {\n\n syn::Fields::Named(ref fields) => (Style::Struct, fields_from_ast(cx, &fields.named)),\n\n syn::Fields::Unnamed(ref fields) => (Style::Tuple, fields_from_ast(cx, &fields.unnamed)),\n\n syn::Fields::Unit => (Style::Unit, Vec::new()),\n\n }\n\n}\n\n\n", "file_path": "lain_derive/src/internals/ast.rs", "rank": 43, "score": 69452.85318377063 }, { "content": "pub fn expand_mutatable(input: &syn::DeriveInput) -> Result<TokenStream, Vec<syn::Error>> {\n\n let ctx = Ctxt::new();\n\n\n\n let cont = match Container::from_ast(&ctx, input, Derive::Mutatable) {\n\n Some(cont) => cont,\n\n None => return Err(ctx.check().unwrap_err()),\n\n };\n\n\n\n ctx.check()?;\n\n\n\n let ident = &cont.ident;\n\n let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();\n\n\n\n let body = mutatable_body(&cont);\n\n let lain = cont.attrs.lain_path();\n\n\n\n let ident_str = ident.to_string();\n\n\n\n let impl_block = quote! {\n\n #[allow(clippy)]\n", "file_path": "lain_derive/src/mutations.rs", "rank": 44, "score": 69371.32032516671 }, { "content": "fn parse_lit_str<T>(s: &syn::LitStr) -> parse::Result<T>\n\nwhere\n\n T: Parse,\n\n{\n\n let tokens = spanned_tokens(s)?;\n\n syn::parse2(tokens)\n\n}\n\n\n", "file_path": "lain_derive/src/internals/attr.rs", "rank": 45, "score": 68714.57512679207 }, { "content": "pub fn expand_new_fuzzed(input: &syn::DeriveInput) -> Result<TokenStream, Vec<syn::Error>> {\n\n let ctx = Ctxt::new();\n\n\n\n let cont = match Container::from_ast(&ctx, input, Derive::BinarySerialize) {\n\n Some(cont) => cont,\n\n None => return Err(ctx.check().unwrap_err()),\n\n };\n\n\n\n ctx.check()?;\n\n\n\n let ident = &cont.ident;\n\n let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();\n\n\n\n let body = new_fuzzed_body(&cont);\n\n let lain = cont.attrs.lain_path();\n\n\n\n let impl_block = quote! {\n\n #[allow(clippy)]\n\n #[allow(unknown_lints)]\n\n #[automatically_derived]\n", "file_path": "lain_derive/src/mutations.rs", "rank": 46, "score": 68199.27757744443 }, { "content": " } = serialized_size_body(\n\n &cont,\n\n cont.attrs.serialized_size(),\n\n cont.attrs.min_serialized_size(),\n\n );\n\n\n\n let lain = cont.attrs.lain_path();\n\n\n\n let impl_block = quote! {\n\n #[allow(clippy)]\n\n #[allow(unknown_lints)]\n\n #[automatically_derived]\n\n impl #impl_generics #lain::traits::BinarySerialize for #ident #ty_generics #where_clause {\n\n fn binary_serialize<W: std::io::Write, E: #lain::byteorder::ByteOrder>(&self, buffer: &mut W) -> usize {\n\n use #lain::traits::SerializedSize;\n\n use #lain::byteorder::{LittleEndian, BigEndian, WriteBytesExt};\n\n\n\n let mut bytes_written = 0;\n\n\n\n #serialize_body\n", "file_path": "lain_derive/src/serialize.rs", "rank": 47, "score": 68018.1337701415 }, { "content": " #[inline]\n\n fn serialized_size(&self) -> usize {\n\n use #lain::traits::SerializedSize;\n\n #lain::log::debug!(\"getting serialized size of {}\", #ident_as_string);\n\n let size = #serialized_size;\n\n\n\n // let size = if size < Self::min_nonzero_elements_size() {\n\n // Self::min_nonzero_elements_size()\n\n // } else {\n\n // size\n\n // };\n\n #lain::log::debug!(\"size of {} is 0x{:02X}\", #ident_as_string, size);\n\n\n\n return size;\n\n }\n\n\n\n #[inline]\n\n fn min_nonzero_elements_size() -> usize {\n\n #min_nonzero_elements_size\n\n }\n", "file_path": "lain_derive/src/serialize.rs", "rank": 48, "score": 68017.81364754541 }, { "content": "\n\n #[inline]\n\n fn max_default_object_size() -> usize {\n\n #max_default_object_size\n\n }\n\n\n\n #[inline]\n\n fn min_enum_variant_size(&self) -> usize {\n\n #min_enum_variant_size\n\n }\n\n }\n\n };\n\n\n\n let data = dummy::wrap_in_const(\"BINARYSERIALIZE\", ident, impl_block);\n\n\n\n Ok(data)\n\n}\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 49, "score": 68009.73557476579 }, { "content": "\n\n if bytes_written < self.serialized_size() {\n\n let padding_bytes = std::cmp::max(self.serialized_size(), Self::min_nonzero_elements_size()) - bytes_written;\n\n if padding_bytes != 0 {\n\n let null = 0x0u8;\n\n for _i in 0..padding_bytes {\n\n bytes_written += null.binary_serialize::<_, E>(buffer);\n\n }\n\n }\n\n }\n\n\n\n bytes_written\n\n }\n\n }\n\n\n\n // TODO: Split this into its own derive\n\n #[allow(clippy)]\n\n #[allow(unknown_lints)]\n\n #[automatically_derived]\n\n impl #impl_generics #lain::traits::SerializedSize for #ident #ty_generics #where_clause {\n", "file_path": "lain_derive/src/serialize.rs", "rank": 50, "score": 68009.32919134019 }, { "content": " }\n\n }\n\n _ => quote_spanned! { variant.original.span() =>\n\n 0\n\n },\n\n };\n\n }\n\n\n\n let mut field_identifiers = vec![];\n\n\n\n let field_sizes: Vec<TokenStream> = variant\n\n .fields\n\n .iter()\n\n .map(|field| {\n\n let (value_ident, _field_ident_string, field_size) =\n\n field_serialized_size(field, \"__field\", true, visitor_type);\n\n field_identifiers.push(quote_spanned! { field.member.span() => #value_ident });\n\n\n\n field_size\n\n })\n", "file_path": "lain_derive/src/serialize.rs", "rank": 51, "score": 68007.84846323436 }, { "content": " } else {\n\n match visitor_type {\n\n SerializedSizeVisitorType::SerializedSize => {\n\n quote_spanned! { field.original.span() => _lain::traits::SerializedSize::serialized_size(#borrow#value_ident)}\n\n }\n\n SerializedSizeVisitorType::MinNonzeroElements\n\n | SerializedSizeVisitorType::MinEnumVariantSize => match ty {\n\n syn::Type::Path(ref p)\n\n if p.path.segments[0].ident == \"Vec\" && field.attrs.min().is_some() =>\n\n {\n\n let min = field.attrs.min().unwrap();\n\n quote_spanned! { field.original.span() => <#ty>::min_nonzero_elements_size() * #min }\n\n }\n\n _ => {\n\n quote_spanned! { field.original.span() => (<#ty>::min_nonzero_elements_size() ) }\n\n }\n\n },\n\n SerializedSizeVisitorType::MaxDefaultObjectSize => match ty {\n\n syn::Type::Path(ref p)\n\n if p.path.segments[0].ident == \"Vec\" && field.attrs.min().is_some() =>\n", "file_path": "lain_derive/src/serialize.rs", "rank": 52, "score": 68006.39106172246 }, { "content": " quote_spanned! { field.original.span() => #borrow#value_ident}\n\n };\n\n\n\n // kind of a hack but only emit the size of the bitfield for the first element\n\n if bits + bit_shift == type_total_bits || is_last_field {\n\n match visitor_type {\n\n SerializedSizeVisitorType::SerializedSize => {\n\n quote_spanned! {field.original.span() => _lain::traits::SerializedSize::serialized_size(#bitfield_value)}\n\n }\n\n SerializedSizeVisitorType::MinNonzeroElements\n\n | SerializedSizeVisitorType::MinEnumVariantSize => {\n\n quote_spanned! {field.original.span() => <#bitfield_type>::min_nonzero_elements_size()}\n\n }\n\n SerializedSizeVisitorType::MaxDefaultObjectSize => {\n\n quote_spanned! {field.original.span() => <#bitfield_type>::max_default_object_size()}\n\n }\n\n }\n\n } else {\n\n quote! {0 /* bitfield */}\n\n }\n", "file_path": "lain_derive/src/serialize.rs", "rank": 53, "score": 68006.15846235013 }, { "content": " quote! {*[#(#nonzero_variants,)*].iter().min_by(|a, b| a.cmp(b)).unwrap()}\n\n };\n\n\n\n let max_default = quote! {*[#(#max_obj,)*].iter().max_by(|a, b| a.cmp(b)).unwrap()};\n\n\n\n let min_variant = quote! {\n\n match *self {\n\n #(#min_variant)*\n\n }\n\n };\n\n\n\n SerializedSizeBodies {\n\n serialized_size,\n\n min_nonzero_elements_size: min_nonzero,\n\n max_default_object_size: max_default,\n\n min_enum_variant_size: min_variant,\n\n }\n\n}\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 54, "score": 68005.74317384076 }, { "content": "\n\n bitfield_setter\n\n } else {\n\n if let syn::Type::Array(ref _a) = ty {\n\n // TODO: Change this once const generics are stabilized\n\n quote_spanned! { field.original.span() =>\n\n bytes_written += #value_ident.binary_serialize::<_, #endian>(buffer);\n\n }\n\n } else {\n\n quote_spanned! { field.original.span() =>\n\n bytes_written += <#ty>::binary_serialize::<_, #endian>(#borrow#value_ident, buffer);\n\n }\n\n }\n\n };\n\n\n\n (value_ident, field_ident_string, serialize_stmts)\n\n}\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 55, "score": 68004.87461058897 }, { "content": " {\n\n let min = field\n\n .attrs\n\n .min()\n\n .map(|min| {\n\n if min.to_string() == \"0\" {\n\n quote! {1}\n\n } else {\n\n min.clone()\n\n }\n\n })\n\n .unwrap_or(quote! {1});\n\n quote_spanned! { field.original.span() => <#ty>::max_default_object_size() * #min }\n\n }\n\n _ => {\n\n quote_spanned! { field.original.span() => (<#ty>::max_default_object_size() ) }\n\n }\n\n },\n\n }\n\n };\n\n\n\n (value_ident, field_ident_string, serialized_size_stmts)\n\n}\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 56, "score": 68003.28270087807 }, { "content": " let field_serializers: Vec<TokenStream> = variant\n\n .fields\n\n .iter()\n\n .map(|field| {\n\n let (value_ident, _field_ident_string, initializer) =\n\n field_serializer(field, \"__field\", true);\n\n field_identifiers.push(quote_spanned! { field.member.span() => #value_ident });\n\n\n\n initializer\n\n })\n\n .collect();\n\n\n\n let match_arm = quote! {\n\n #full_ident(#(ref #field_identifiers,)*) => {\n\n #(#field_serializers)*\n\n }\n\n };\n\n\n\n match_arm\n\n })\n\n .collect();\n\n\n\n match_arms\n\n}\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 57, "score": 68002.99245391549 }, { "content": " Data::Enum(ref _variants) => serialized_size_unit_enum(&cont.ident),\n\n Data::Struct(Style::Struct, ref fields) | Data::Struct(Style::Tuple, ref fields) => {\n\n serialized_size_struct(fields)\n\n }\n\n Data::Struct(Style::Unit, ref _fields) => {\n\n let zero_size = quote! {0};\n\n SerializedSizeBodies {\n\n serialized_size: zero_size.clone(),\n\n min_nonzero_elements_size: zero_size.clone(),\n\n max_default_object_size: zero_size.clone(),\n\n min_enum_variant_size: zero_size,\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 58, "score": 68001.44065401207 }, { "content": " );\n\n let min_variant = serialized_size_enum_visitor(\n\n variants,\n\n cont_ident,\n\n SerializedSizeVisitorType::MinEnumVariantSize,\n\n );\n\n\n\n let serialized_size = if let Some(size) = size {\n\n quote! {#size}\n\n } else {\n\n quote! {\n\n match *self {\n\n #(#match_arms)*\n\n }\n\n }\n\n };\n\n\n\n let min_nonzero = if let Some(min_size) = min_size {\n\n quote! {#min_size}\n\n } else {\n", "file_path": "lain_derive/src/serialize.rs", "rank": 59, "score": 67997.50055950416 }, { "content": " let serialized_size_stmts = if let Some(bits) = field.attrs.bits() {\n\n let bit_shift = field.attrs.bit_shift().unwrap();\n\n let bitfield_type = field.attrs.bitfield_type().unwrap_or(&field.ty);\n\n let is_last_field = field.attrs.is_last_field();\n\n\n\n let type_total_bits = if is_primitive_type(bitfield_type, \"u8\") {\n\n 8\n\n } else if is_primitive_type(&bitfield_type, \"u16\") {\n\n 16\n\n } else if is_primitive_type(&bitfield_type, \"u32\") {\n\n 32\n\n } else if is_primitive_type(&bitfield_type, \"u64\") {\n\n 64\n\n } else {\n\n panic!(\"got to field_serialize_size with an unsupported bitfield type `{}`. ensure that checks in ast code are correct\", bitfield_type.into_token_stream());\n\n };\n\n\n\n let bitfield_value = if field.attrs.bitfield_type().is_some() {\n\n quote_spanned! {field.original.span() => #borrow#value_ident.to_primitive()}\n\n } else {\n", "file_path": "lain_derive/src/serialize.rs", "rank": 60, "score": 67997.3632435341 }, { "content": " 32\n\n } else if is_primitive_type(&bitfield_type, \"u64\") {\n\n 64\n\n } else {\n\n panic!(\"got to field_serialize with an unsupported bitfield type `{}`. ensure that checks in ast code are correct\", bitfield_type.into_token_stream());\n\n };\n\n\n\n let bitfield_value = if field.attrs.bitfield_type().is_some() {\n\n quote_spanned! {field.ty.span() => #value_ident.to_primitive()}\n\n } else {\n\n quote_spanned! {field.original.span() => #value_ident}\n\n };\n\n\n\n let mut bitfield_setter = quote_spanned! { field.ty.span() =>\n\n bitfield |= ((#bitfield_value as #bitfield_type & #bit_mask as #bitfield_type) << #bit_shift) as u64;\n\n };\n\n\n\n if bits + bit_shift == type_total_bits || is_last_field {\n\n bitfield_setter.extend(quote_spanned!{field.ty.span() => bytes_written += <#bitfield_type>::binary_serialize::<_, #endian>(&(bitfield as #bitfield_type), buffer);});\n\n }\n", "file_path": "lain_derive/src/serialize.rs", "rank": 61, "score": 67997.03696372743 }, { "content": " .collect();\n\n\n\n match visitor_type {\n\n SerializedSizeVisitorType::SerializedSize\n\n | SerializedSizeVisitorType::MinEnumVariantSize => {\n\n quote_spanned! { variant.original.span() =>\n\n #full_ident(#(ref #field_identifiers,)*) => {\n\n 0 #(+#field_sizes)*\n\n }\n\n }\n\n }\n\n _ => quote_spanned! { variant.original.span() =>\n\n 0 #(+#field_sizes)*\n\n },\n\n }\n\n })\n\n .collect();\n\n\n\n match_arms\n\n}\n", "file_path": "lain_derive/src/serialize.rs", "rank": 62, "score": 67996.9842722276 }, { "content": "use proc_macro2::TokenStream;\n\nuse quote::{quote, quote_spanned};\n\nuse std::str::FromStr;\n\nuse syn::export::quote::ToTokens;\n\nuse syn::spanned::Spanned;\n\n\n\nuse crate::dummy;\n\nuse crate::internals::ast::{is_primitive_type, Container, Data, Field, Style, Variant};\n\nuse crate::internals::{Ctxt, Derive};\n\n\n", "file_path": "lain_derive/src/serialize.rs", "rank": 63, "score": 67993.1335504449 }, { "content": " quote! {_lain::byteorder::BigEndian}\n\n } else if field.attrs.little_endian() {\n\n quote! {_lain::byteorder::LittleEndian}\n\n } else {\n\n // inherit\n\n quote! {E}\n\n };\n\n\n\n let serialize_stmts = if let Some(bits) = field.attrs.bits() {\n\n let bit_mask = 2_u64.pow(bits as u32) - 1;\n\n let bit_shift = field.attrs.bit_shift().unwrap();\n\n let is_last_field = field.attrs.is_last_field();\n\n\n\n let bitfield_type = field.attrs.bitfield_type().unwrap_or(&field.ty);\n\n\n\n let type_total_bits = if is_primitive_type(bitfield_type, \"u8\") {\n\n 8\n\n } else if is_primitive_type(&bitfield_type, \"u16\") {\n\n 16\n\n } else if is_primitive_type(&bitfield_type, \"u32\") {\n", "file_path": "lain_derive/src/serialize.rs", "rank": 64, "score": 67992.6886219446 }, { "content": "fn fields_from_ast<'a>(cx: &Ctxt, fields: &'a Punctuated<syn::Field, Token![,]>) -> Vec<Field<'a>> {\n\n let mut bitfield_bits = 0;\n\n\n\n let mut fields: Vec<Field<'a>> = fields\n\n .iter()\n\n .enumerate()\n\n .map(|(i, field)| {\n\n let mut field = Field {\n\n member: match field.ident {\n\n Some(ref ident) => syn::Member::Named(ident.clone()),\n\n None => syn::Member::Unnamed(i.into()),\n\n },\n\n attrs: attr::Field::from_ast(cx, field),\n\n ty: &field.ty,\n\n original: field,\n\n };\n\n\n\n if let Some(bits) = field.attrs.bits() {\n\n field.attrs.set_bit_shift(bitfield_bits);\n\n bitfield_bits += bits;\n", "file_path": "lain_derive/src/internals/ast.rs", "rank": 65, "score": 67072.62452072586 }, { "content": " test1: 0xAABBCCDD,\n\n nested,\n\n test2: 0x00112233,\n\n ..Default::default()\n\n };\n\n\n\n c.bench(\n\n function_name.as_ref(),\n\n Benchmark::new(\"serialize\", move |b| {\n\n let mut buffer = Vec::with_capacity(struct_size);\n\n b.iter(|| {\n\n parent.binary_serialize::<_, BigEndian>(&mut buffer);\n\n black_box(&buffer);\n\n buffer.clear();\n\n });\n\n })\n\n .throughput(Throughput::Bytes(struct_size as u32)),\n\n );\n\n}\n\n\n\ncriterion_group!(benches, bench_serialize_1000);\n\ncriterion_main!(benches);\n", "file_path": "testsuite/benches/benchmark_serialization_throughput.rs", "rank": 66, "score": 65164.691976532835 }, { "content": "#![feature(specialization)]\n\n\n\n#[macro_use]\n\nextern crate criterion;\n\n#[macro_use]\n\nextern crate lain;\n\n\n\nuse criterion::*;\n\n\n\nuse lain::byteorder::BigEndian;\n\nuse lain::prelude::*;\n\n\n\n#[derive(Debug, Default, Clone, Mutatable, BinarySerialize)]\n\npub struct NestedStruct {\n\n test1: u32,\n\n nested: TestStruct,\n\n test2: u32,\n\n test3: u32,\n\n test4: u32,\n\n test5: u32,\n", "file_path": "testsuite/benches/benchmark_serialization_throughput.rs", "rank": 67, "score": 65150.438085719274 }, { "content": " test6: u32,\n\n test7: u32,\n\n test8: u8,\n\n test9: u16,\n\n test10: u64,\n\n test11: [u8; 32],\n\n}\n\n\n\n#[derive(Debug, Default, Clone, Mutatable, BinarySerialize)]\n\npub struct TestStruct {\n\n single_byte: u8,\n\n\n\n #[lain(bits = 1)]\n\n bitfield_1: u8,\n\n #[lain(bits = 2)]\n\n bitfield_2: u8,\n\n #[lain(bits = 1)]\n\n bitfield_3: u8,\n\n #[lain(bits = 1)]\n\n bitfield_4: u8,\n\n #[lain(bits = 3)]\n\n bitfield_5: u8,\n\n\n\n uint32: u32,\n\n\n\n short: u16,\n\n end_byte: u8,\n\n}\n\n\n", "file_path": "testsuite/benches/benchmark_serialization_throughput.rs", "rank": 68, "score": 65150.43252311641 }, { "content": "fn variable_size_object_helper(input: &DeriveInput) -> TokenStream {\n\n // TODO: refactor this to use the same pattern as Mutatable/NewFuzzed introduced\n\n // in v0.2.0\n\n let imp: TokenStream;\n\n\n\n match input.data {\n\n Data::Enum(ref data) => {\n\n let mut simple_variants = true;\n\n for variant in &data.variants {\n\n match variant.fields {\n\n Fields::Unit => {\n\n continue;\n\n }\n\n _ => {\n\n simple_variants = false;\n\n }\n\n }\n\n }\n\n\n\n imp = if simple_variants {\n", "file_path": "lain_derive/src/lib.rs", "rank": 69, "score": 64883.460193281615 }, { "content": "/// Represents a data typethat can be pushed to a byte buffer in a constant,\n\n/// predetermined way.\n\npub trait BinarySerialize {\n\n /// Pushes all fields in `self` to a buffer\n\n fn binary_serialize<W: Write, E: ByteOrder>(&self, buffer: &mut W) -> usize;\n\n}\n\n\n", "file_path": "lain/src/traits.rs", "rank": 70, "score": 62525.0778304373 }, { "content": "fn gen_struct_mutate_impl(fields: &[FuzzerObjectStructField]) -> TokenStream {\n\n let mutation_parts: Vec<TokenStream> = fields\n\n .iter()\n\n .map(|f| {\n\n let mut field_mutation_tokens = TokenStream::new();\n\n let span = f.field.span();\n\n let ty = &f.field.ty;\n\n let ident = &f.field.ident;\n\n let ident_str = ident.as_ref().unwrap().to_string();\n\n let weighted = &f.weighted;\n\n\n\n let default_constraints = if f.min.is_some() || f.max.is_some() {\n\n let min = f\n\n .min\n\n .as_ref()\n\n .map(|v| quote! {Some(#v)})\n\n .unwrap_or_else(|| quote! {None});\n\n let max = f\n\n .max\n\n .as_ref()\n", "file_path": "lain_derive/src/fuzzerobject.rs", "rank": 71, "score": 62146.2367556045 }, { "content": "fn spanned_tokens(s: &syn::LitStr) -> parse::Result<TokenStream> {\n\n let stream = syn::parse_str(&s.value())?;\n\n Ok(respan_token_stream(stream, s.span()))\n\n}\n\n\n", "file_path": "lain_derive/src/internals/attr.rs", "rank": 72, "score": 60493.653689931896 }, { "content": "#[proc_macro_derive(ToPrimitiveU8)]\n\npub fn to_primitive_u8(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n\n to_primitive_of_type(input, quote! {u8})\n\n}\n\n\n\n/// Implements `ToPrimitive<u16>` for the given enum.\n", "file_path": "lain_derive/src/lib.rs", "rank": 73, "score": 57822.38140243985 }, { "content": "#[proc_macro_derive(VariableSizeObject)]\n\npub fn variable_size_object(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n let expanded = variable_size_object_helper(&input);\n\n\n\n // Uncomment to dump the AST\n\n // println!(\"{}\", expanded);\n\n\n\n proc_macro::TokenStream::from(expanded)\n\n}\n\n\n", "file_path": "lain_derive/src/lib.rs", "rank": 74, "score": 56452.363954919 }, { "content": "fn field_mutator(\n\n field: &Field,\n\n name_prefix: &'static str,\n\n is_destructured: bool,\n\n) -> (TokenStream, String, TokenStream) {\n\n let default_constraints = struct_field_constraints(field, true);\n\n let ty = &field.ty;\n\n let field_ident_string = match field.member {\n\n syn::Member::Named(ref ident) => ident.to_string(),\n\n syn::Member::Unnamed(ref idx) => idx.index.to_string(),\n\n };\n\n\n\n let value_ident =\n\n TokenStream::from_str(&format!(\"{}{}\", name_prefix, field_ident_string)).unwrap();\n\n let borrow = if is_destructured {\n\n TokenStream::new()\n\n } else {\n\n quote! {&mut}\n\n };\n\n\n", "file_path": "lain_derive/src/mutations.rs", "rank": 75, "score": 51768.28578637865 }, { "content": "fn field_initializer(\n\n field: &Field,\n\n name_prefix: &'static str,\n\n) -> (TokenStream, String, TokenStream) {\n\n let default_constraints = struct_field_constraints(field, false);\n\n let ty = &field.ty;\n\n let field_ident_string = match field.member {\n\n syn::Member::Named(ref ident) => ident.to_string(),\n\n syn::Member::Unnamed(ref idx) => idx.index.to_string(),\n\n };\n\n\n\n let value_ident =\n\n TokenStream::from_str(&format!(\"{}{}\", name_prefix, field_ident_string)).unwrap();\n\n\n\n let default_initializer = quote! {\n\n <#ty>::new_fuzzed(mutator, constraints.as_ref())\n\n };\n\n\n\n let initializer = if field.attrs.ignore() {\n\n quote! {\n", "file_path": "lain_derive/src/mutations.rs", "rank": 76, "score": 51768.28578637865 }, { "content": "fn to_primitive_of_type(\n\n input: proc_macro::TokenStream,\n\n ty: proc_macro2::TokenStream,\n\n) -> proc_macro::TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n let name = input.ident;\n\n\n\n let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();\n\n\n\n let expanded = quote! {\n\n #[allow(clippy)]\n\n #[allow(unknown_lints)]\n\n impl #impl_generics ::lain::traits::ToPrimitive for #name #ty_generics #where_clause {\n\n type Output = #ty;\n\n\n\n fn to_primitive(&self) -> #ty {\n\n *self as #ty\n\n }\n\n }\n\n };\n\n\n\n // Uncomment to dump the AST\n\n debug!(\"{}\", expanded);\n\n\n\n proc_macro::TokenStream::from(expanded)\n\n}\n", "file_path": "lain_derive/src/lib.rs", "rank": 77, "score": 51768.28578637865 }, { "content": "fn main() {\n\n let mut driver = FuzzerDriver::<GlobalContext>::new(THREAD_COUNT);\n\n\n\n driver.set_global_context(Default::default());\n\n\n\n let driver = Arc::new(driver);\n\n let ctrlc_driver = driver.clone();\n\n\n\n ctrlc::set_handler(move || {\n\n ctrlc_driver.signal_exit();\n\n }).expect(\"couldn't set CTRL-C handler\");\n\n\n\n start_fuzzer(driver.clone(), fuzzer_routine);\n\n\n\n driver.join_threads();\n\n\n\n println!(\"Finished in {} iterations\", driver.num_iterations());\n\n}\n\n\n", "file_path": "examples/example_fuzzer/src/main.rs", "rank": 78, "score": 51768.28578637865 }, { "content": "fn new_fuzzed_enum_visitor(\n\n variants: &[Variant],\n\n cont_ident: &syn::Ident,\n\n) -> (Vec<u64>, Vec<TokenStream>, Vec<f64>) {\n\n let mut weights = vec![];\n\n let mut ignore_chances = vec![];\n\n\n\n let initializers = variants\n\n .iter()\n\n .filter_map(|variant| {\n\n if variant.attrs.ignore() {\n\n return None;\n\n }\n\n ignore_chances.push(variant.attrs.ignore_chance().unwrap_or(1.0));\n\n\n\n let variant_ident = &variant.ident;\n\n let full_ident = quote! {#cont_ident::#variant_ident};\n\n let full_ident_string = full_ident.to_string();\n\n let mut field_identifiers = vec![];\n\n\n", "file_path": "lain_derive/src/mutations.rs", "rank": 79, "score": 49480.8175027441 }, { "content": "fn mutatable_unit_enum_visitor(\n\n variants: &[Variant],\n\n cont_ident: &syn::Ident,\n\n) -> (Vec<u64>, Vec<TokenStream>) {\n\n let mut weights = vec![];\n\n\n\n let variants = variants\n\n .iter()\n\n .filter_map(|variant| {\n\n //if variant.attrs.ignore() {\n\n // None\n\n //} else {\n\n let variant_ident = &variant.ident;\n\n weights.push(variant.attrs.weight().unwrap_or(1));\n\n Some(quote! {#cont_ident::#variant_ident})\n\n //}\n\n })\n\n .collect();\n\n\n\n (weights, variants)\n\n}\n\n\n", "file_path": "lain_derive/src/mutations.rs", "rank": 80, "score": 49480.8175027441 }, { "content": "fn enum_from_ast<'a>(\n\n cx: &Ctxt,\n\n variants: &'a Punctuated<syn::Variant, Token![,]>,\n\n) -> Vec<Variant<'a>> {\n\n variants\n\n .iter()\n\n .map(|variant| {\n\n let attrs = attr::Variant::from_ast(cx, variant);\n\n let (style, fields) = struct_from_ast(cx, &variant.fields);\n\n\n\n Variant {\n\n ident: variant.ident.clone(),\n\n attrs,\n\n style,\n\n fields,\n\n original: variant,\n\n }\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "lain_derive/src/internals/ast.rs", "rank": 81, "score": 48697.767030696574 }, { "content": "fn new_fuzzed_unit_enum_visitor(\n\n variants: &[Variant],\n\n cont_ident: &syn::Ident,\n\n) -> (Vec<u64>, Vec<TokenStream>, Vec<f64>) {\n\n let mut weights = vec![];\n\n let mut ignore_chances = vec![];\n\n\n\n let variants = variants\n\n .iter()\n\n .filter_map(|variant| {\n\n if variant.attrs.ignore() {\n\n None\n\n } else {\n\n let variant_ident = &variant.ident;\n\n\n\n weights.push(variant.attrs.weight().unwrap_or(1));\n\n ignore_chances.push(variant.attrs.ignore_chance().unwrap_or(1.0));\n\n\n\n Some(quote! {#cont_ident::#variant_ident})\n\n }\n\n })\n\n .collect();\n\n\n\n (weights, variants, ignore_chances)\n\n}\n\n\n", "file_path": "lain_derive/src/mutations.rs", "rank": 82, "score": 48460.11896968501 }, { "content": "fn constraints_prelude() -> TokenStream {\n\n quote! {\n\n // Make a copy of the constraints that will remain immutable for\n\n // this function. Here we ensure that the base size of this object has\n\n // been accounted for by the caller, which may be an object containing this.\n\n let parent_constraints = parent_constraints.map(|c| {\n\n let mut c = c.clone();\n\n c.account_for_base_object_size::<Self>();\n\n\n\n c\n\n });\n\n\n\n let mut max_size = parent_constraints.as_ref().and_then(|c| c.max_size);\n\n if let Some(ref mut max) = max_size {\n\n let min_object_size = Self::max_default_object_size();\n\n if min_object_size > *max {\n\n warn!(\"Cannot construct object with given max_size constraints. Object min size is 0x{:X}, max size constraint is 0x{:X}\", min_object_size, *max);\n\n *max = Self::max_default_object_size();\n\n } else {\n\n *max = max.saturating_sub(Self::max_default_object_size());\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "lain_derive/src/mutations.rs", "rank": 83, "score": 47598.21318074466 }, { "content": "fn mutatable_constraints_prelude() -> TokenStream {\n\n quote! {\n\n // Make a copy of the constraints that will remain immutable for\n\n // this function. Here we ensure that the base size of this object has\n\n // been accounted for by the caller, which may be an object containing this.\n\n let parent_constraints = parent_constraints.map(|c| {\n\n let mut c = c.clone();\n\n if !c.base_object_size_accounted_for {\n\n c.base_object_size_accounted_for = true;\n\n c.max_size = c.max_size.map(|size| {\n\n size.saturating_sub(self.serialized_size())\n\n });\n\n }\n\n\n\n c\n\n });\n\n\n\n let mut max_size = parent_constraints.as_ref().and_then(|c| c.max_size);\n\n }\n\n}\n", "file_path": "lain_derive/src/mutations.rs", "rank": 84, "score": 46577.51464768557 }, { "content": "fn mutatable_struct(fields: &[Field]) -> TokenStream {\n\n let mutators = mutatable_struct_visitor(fields);\n\n let prelude = mutatable_constraints_prelude();\n\n\n\n if mutators.is_empty() {\n\n return TokenStream::new();\n\n }\n\n\n\n let len = mutators.len();\n\n let mut match_arms = vec![];\n\n\n\n for (i, mutator) in mutators.iter().enumerate() {\n\n match_arms.push(quote! {\n\n #i => {\n\n #mutator\n\n }\n\n });\n\n }\n\n\n\n quote! {\n", "file_path": "lain_derive/src/mutations.rs", "rank": 85, "score": 42720.40184892495 }, { "content": "fn mutatable_body(cont: &Container) -> TokenStream {\n\n match cont.data {\n\n Data::Enum(ref variants) if variants[0].style != Style::Unit => {\n\n mutatable_enum(variants, &cont.ident)\n\n }\n\n Data::Enum(ref variants) => mutatable_unit_enum(variants, &cont.ident),\n\n Data::Struct(Style::Struct, ref fields) | Data::Struct(Style::Tuple, ref fields) => {\n\n mutatable_struct(fields)\n\n }\n\n Data::Struct(Style::Unit, ref _fields) => TokenStream::new(),\n\n }\n\n}\n\n\n", "file_path": "lain_derive/src/mutations.rs", "rank": 86, "score": 42720.40184892495 }, { "content": "fn new_fuzzed_body(cont: &Container) -> TokenStream {\n\n match cont.data {\n\n Data::Enum(ref variants) if variants[0].style != Style::Unit => {\n\n new_fuzzed_enum(variants, &cont.ident)\n\n }\n\n Data::Enum(ref variants) => new_fuzzed_unit_enum(variants, &cont.ident),\n\n Data::Struct(Style::Struct, ref fields) | Data::Struct(Style::Tuple, ref fields) => {\n\n new_fuzzed_struct(fields, &cont.ident)\n\n }\n\n Data::Struct(Style::Unit, ref _fields) => new_fuzzed_unit_struct(&cont.ident),\n\n }\n\n}\n\n\n", "file_path": "lain_derive/src/mutations.rs", "rank": 87, "score": 41833.942605425334 }, { "content": "fn new_fuzzed_unit_struct(cont_ident: &syn::Ident) -> TokenStream {\n\n quote! {\n\n #cont_ident\n\n }\n\n}\n\n\n", "file_path": "lain_derive/src/mutations.rs", "rank": 88, "score": 38352.35844076881 }, { "content": "fn respan_token_stream(stream: TokenStream, span: Span) -> TokenStream {\n\n stream\n\n .into_iter()\n\n .map(|token| respan_token_tree(token, span))\n\n .collect()\n\n}\n\n\n", "file_path": "lain_derive/src/internals/attr.rs", "rank": 89, "score": 36671.07993277104 }, { "content": "fn mutatable_enum(variants: &[Variant], cont_ident: &syn::Ident) -> TokenStream {\n\n let constraints_prelude = mutatable_constraints_prelude();\n\n let match_arms = mutatable_enum_visitor(variants, cont_ident);\n\n\n\n if match_arms.is_empty() {\n\n return TokenStream::new();\n\n }\n\n\n\n quote! {\n\n // 10% chance to re-generate this field\n\n if mutator.gen_chance(0.10) {\n\n *self = Self::new_fuzzed(mutator, parent_constraints.and_then(|constraints| {\n\n let mut constraints = constraints.clone();\n\n\n\n // If base object size has already been accounted for, that means\n\n // the max_size represents the amount of extra data that may be consumed.\n\n // We want to give back the size of this object when generating a new instance\n\n if constraints.base_object_size_accounted_for {\n\n if let Some(max_size) = constraints.max_size.as_mut() {\n\n *max_size = self.serialized_size() + *max_size;\n", "file_path": "lain_derive/src/mutations.rs", "rank": 90, "score": 36486.335181991744 } ]
Rust
rust token listener/test/src/bin/test2.rs
everscale-experts/hackathon_new
dafaaea8b7f70cfdb9162a1b6752ac31d6a4a5df
use ureq::json; use std::convert::TryInto; use serde::Serialize; use serde::Serializer; use crypto::blake2b; use crypto::Prefix; use crypto::WithPrefix; use crypto::WithoutPrefix; use crypto::base58check::{FromBase58Check, ToBase58Check}; use crypto::FromBase58CheckError; use crypto::NotMatchingPrefixError; use types::ImplicitAddress; #[derive(thiserror::Error, PartialEq, Debug)] pub enum FromPrefixedBase58CheckError { #[error("invalid base58")] InvalidBase58, #[error("invalid checksum")] InvalidChecksum, #[error("missing checksum")] MissingChecksum, #[error("not matching prefix")] NotMatchingPrefix, #[error("invalid size")] InvalidSize, } impl From<FromBase58CheckError> for FromPrefixedBase58CheckError { fn from(err: FromBase58CheckError) -> Self { match err { FromBase58CheckError::InvalidBase58 => { Self::InvalidBase58 } FromBase58CheckError::InvalidChecksum => { Self::InvalidChecksum } FromBase58CheckError::MissingChecksum => { Self::MissingChecksum } } } } impl From<NotMatchingPrefixError> for FromPrefixedBase58CheckError { fn from(_: NotMatchingPrefixError) -> Self { Self::NotMatchingPrefix } } pub const PUBLIC_KEY_LEN: usize = 32; #[allow(non_camel_case_types)] #[derive(PartialEq, Debug, Clone)] pub enum PublicKey { edpk([u8; 32]), sppk([u8; 33]), p2pk([u8; 33]), } impl PublicKey { fn try_without_prefix( bytes: &[u8], prefix: Prefix, ) -> Result<(Prefix, Vec<u8>), NotMatchingPrefixError> { bytes .without_prefix(prefix) .map(|bytes| (prefix, bytes)) } fn try_into_inner<T, U>(bytes: U) -> Result<T, FromPrefixedBase58CheckError> where U: TryInto<T>, { bytes.try_into().or(Err(FromPrefixedBase58CheckError::InvalidSize)) } pub fn from_base58check(encoded: &str) -> Result<Self, FromPrefixedBase58CheckError> { let bytes = encoded.from_base58check()?; let (prefix, bytes_vec) = Self::try_without_prefix(&bytes, Prefix::edpk) .or_else(|_| Self::try_without_prefix(&bytes, Prefix::sppk)) .or_else(|_| Self::try_without_prefix(&bytes, Prefix::p2pk))?; match prefix { Prefix::edpk => Ok(Self::edpk(Self::try_into_inner(bytes_vec)?)), Prefix::sppk => Ok(Self::sppk(Self::try_into_inner(bytes_vec)?)), Prefix::p2pk => Ok(Self::p2pk(Self::try_into_inner(bytes_vec)?)), _ => unreachable!(), } } pub fn hash(&self) -> ImplicitAddress { let key = match self { Self::edpk(key) => &key[..], Self::sppk(key) => &key[..], Self::p2pk(key) => &key[..], }; let hash = blake2b::digest_160(key); let addr_bytes: [u8; 20] = hash .try_into() .unwrap(); match self { Self::edpk(_) => ImplicitAddress::tz1(addr_bytes), Self::sppk(_) => ImplicitAddress::tz2(addr_bytes), Self::p2pk(_) => ImplicitAddress::tz3(addr_bytes), } } } impl ToBase58Check for PublicKey { fn to_base58check(&self) -> String { self.as_ref() .with_prefix(Prefix::edpk) .to_base58check() } } impl AsRef<[u8]> for PublicKey { fn as_ref(&self) -> &[u8] { match self { Self::edpk(k) => k, Self::sppk(k) => k, Self::p2pk(k) => k, } } } impl Serialize for PublicKey { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { serializer.serialize_str( &self.to_base58check() ) } } fn transfer() { let params = json!("{ to: \"KT1MeAHVkJp87r9neejmaxCfaccoUfXAssy1\", amount: 1, parameter: { entrypoint: \"transfer\", value: { prim: \"Pair\", args: [ { string: \"tz1gVYfPffnmhyZkiEXadeg5SS8uerbXo2DM\" }, { prim: \"Pair\", args: [{ string: \"tz1f1c3WWBBd4wGF57sJNgej9vKSCG5GTLjd\" }, { int: \"2\" } ]} ] } } }"); } fn main() { }
use ureq::json; use std::convert::TryInto; use serde::Serialize; use serde::Serializer; use crypto::blake2b; use crypto::Prefix; use crypto::WithPrefix; use crypto::WithoutPrefix; use crypto::base58check::{FromBase58Check, ToBase58Check}; use crypto::FromBase58CheckError; use crypto::NotMatchingPrefixError; use types::ImplicitAddress; #[derive(thiserror::Error, PartialEq, Debug)] pub enum FromPrefixedBase58CheckError { #[error("invalid base58")] InvalidBase58, #[error("invalid checksum")] InvalidChecksum, #[error("missing checksum")] MissingChecksum, #[error("
ializer { serializer.serialize_str( &self.to_base58check() ) } } fn transfer() { let params = json!("{ to: \"KT1MeAHVkJp87r9neejmaxCfaccoUfXAssy1\", amount: 1, parameter: { entrypoint: \"transfer\", value: { prim: \"Pair\", args: [ { string: \"tz1gVYfPffnmhyZkiEXadeg5SS8uerbXo2DM\" }, { prim: \"Pair\", args: [{ string: \"tz1f1c3WWBBd4wGF57sJNgej9vKSCG5GTLjd\" }, { int: \"2\" } ]} ] } } }"); } fn main() { }
not matching prefix")] NotMatchingPrefix, #[error("invalid size")] InvalidSize, } impl From<FromBase58CheckError> for FromPrefixedBase58CheckError { fn from(err: FromBase58CheckError) -> Self { match err { FromBase58CheckError::InvalidBase58 => { Self::InvalidBase58 } FromBase58CheckError::InvalidChecksum => { Self::InvalidChecksum } FromBase58CheckError::MissingChecksum => { Self::MissingChecksum } } } } impl From<NotMatchingPrefixError> for FromPrefixedBase58CheckError { fn from(_: NotMatchingPrefixError) -> Self { Self::NotMatchingPrefix } } pub const PUBLIC_KEY_LEN: usize = 32; #[allow(non_camel_case_types)] #[derive(PartialEq, Debug, Clone)] pub enum PublicKey { edpk([u8; 32]), sppk([u8; 33]), p2pk([u8; 33]), } impl PublicKey { fn try_without_prefix( bytes: &[u8], prefix: Prefix, ) -> Result<(Prefix, Vec<u8>), NotMatchingPrefixError> { bytes .without_prefix(prefix) .map(|bytes| (prefix, bytes)) } fn try_into_inner<T, U>(bytes: U) -> Result<T, FromPrefixedBase58CheckError> where U: TryInto<T>, { bytes.try_into().or(Err(FromPrefixedBase58CheckError::InvalidSize)) } pub fn from_base58check(encoded: &str) -> Result<Self, FromPrefixedBase58CheckError> { let bytes = encoded.from_base58check()?; let (prefix, bytes_vec) = Self::try_without_prefix(&bytes, Prefix::edpk) .or_else(|_| Self::try_without_prefix(&bytes, Prefix::sppk)) .or_else(|_| Self::try_without_prefix(&bytes, Prefix::p2pk))?; match prefix { Prefix::edpk => Ok(Self::edpk(Self::try_into_inner(bytes_vec)?)), Prefix::sppk => Ok(Self::sppk(Self::try_into_inner(bytes_vec)?)), Prefix::p2pk => Ok(Self::p2pk(Self::try_into_inner(bytes_vec)?)), _ => unreachable!(), } } pub fn hash(&self) -> ImplicitAddress { let key = match self { Self::edpk(key) => &key[..], Self::sppk(key) => &key[..], Self::p2pk(key) => &key[..], }; let hash = blake2b::digest_160(key); let addr_bytes: [u8; 20] = hash .try_into() .unwrap(); match self { Self::edpk(_) => ImplicitAddress::tz1(addr_bytes), Self::sppk(_) => ImplicitAddress::tz2(addr_bytes), Self::p2pk(_) => ImplicitAddress::tz3(addr_bytes), } } } impl ToBase58Check for PublicKey { fn to_base58check(&self) -> String { self.as_ref() .with_prefix(Prefix::edpk) .to_base58check() } } impl AsRef<[u8]> for PublicKey { fn as_ref(&self) -> &[u8] { match self { Self::edpk(k) => k, Self::sppk(k) => k, Self::p2pk(k) => k, } } } impl Serialize for PublicKey { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Ser
random
[ { "content": "/// A trait for converting a value to base58 encoded string.\n\npub trait ToBase58Check {\n\n /// Converts a value of `self` to a base58 value, returning the owned string.\n\n fn to_base58check(&self) -> String;\n\n}\n\n\n", "file_path": "rust token listener/crypto/src/base58check.rs", "rank": 0, "score": 163780.99771317904 }, { "content": "/// A trait for converting a value to base58 encoded string.\n\npub trait ToBase58Check {\n\n /// Converts a value of `self` to a base58 value, returning the owned string.\n\n fn to_base58check(&self) -> String;\n\n}\n\n\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/crypto/src/base58check.rs", "rank": 1, "score": 157228.84833772428 }, { "content": "pub fn exit_with_error<E: Display>(error: E) -> ! {\n\n eprintln!(\n\n \"{} {}\",\n\n style(\"[ERROR]\").red().bold(),\n\n error,\n\n );\n\n process::exit(1)\n\n}\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/lib/src/common/exit_with_error.rs", "rank": 2, "score": 142678.99985392462 }, { "content": "/// A trait for converting base58check encoded values.\n\npub trait FromBase58Check {\n\n /// Size of the checksum used by implementation.\n\n const CHECKSUM_BYTE_SIZE: usize = 4;\n\n\n\n /// Convert a value of `self`, interpreted as base58check encoded data, into the tuple with version and payload as bytes vector.\n\n fn from_base58check(&self) -> Result<Vec<u8>, FromBase58CheckError>;\n\n}\n\n\n\nimpl ToBase58Check for [u8] {\n\n fn to_base58check(&self) -> String {\n\n // 4 bytes checksum\n\n let mut payload = Vec::with_capacity(self.len() + 4);\n\n payload.extend(self);\n\n let checksum = double_sha256(self);\n\n payload.extend(&checksum[..4]);\n\n\n\n payload.to_base58()\n\n }\n\n}\n\n\n", "file_path": "rust token listener/crypto/src/base58check.rs", "rank": 3, "score": 130889.1778870222 }, { "content": "/// A trait for converting base58check encoded values.\n\npub trait FromBase58Check {\n\n /// Size of the checksum used by implementation.\n\n const CHECKSUM_BYTE_SIZE: usize = 4;\n\n\n\n /// Convert a value of `self`, interpreted as base58check encoded data, into the tuple with version and payload as bytes vector.\n\n fn from_base58check(&self) -> Result<Vec<u8>, FromBase58CheckError>;\n\n}\n\n\n\nimpl ToBase58Check for [u8] {\n\n fn to_base58check(&self) -> String {\n\n // 4 bytes checksum\n\n let mut payload = Vec::with_capacity(self.len() + 4);\n\n payload.extend(self);\n\n let checksum = double_sha256(self);\n\n payload.extend(&checksum[..4]);\n\n\n\n payload.to_base58()\n\n }\n\n}\n\n\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/crypto/src/base58check.rs", "rank": 4, "score": 124337.02851156748 }, { "content": "/// Exit and print error that no wallet type(trezor, ledger, local) was selected.\n\npub fn exit_with_error_no_wallet_type_selected() -> ! {\n\n exit_with_error(format!(\n\n \"{}\\n{}\",\n\n \"trezor, ledger, or local wallet needs to be used to create this operation. Neither selected.\",\n\n \"Technically this shouldn't be possible!\",\n\n ))\n\n}\n\n\n\npub struct OperationOptions {\n\n pub no_prompt: bool,\n\n}\n\n\n\npub struct OperationCommandState {\n\n pub version: Option<VersionInfo>,\n\n pub counter: Option<u64>,\n\n pub manager_address: Option<ImplicitAddress>,\n\n}\n\n\n\nimpl Default for OperationCommandState {\n\n fn default() -> Self {\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/lib/src/common/operation_command/mod.rs", "rank": 5, "score": 113404.82034969528 }, { "content": "pub fn deserialize<'de, D>(d: D) -> Result<u64, D::Error>\n\n where D: Deserializer<'de>,\n\n{\n\n let amount_str: String = Deserialize::deserialize(d)?;\n\n parse_float_amount(&amount_str)\n\n .or(Err(\"invalid_amount\".to_string()))\n\n .map_err(serde::de::Error::custom)\n\n}\n", "file_path": "rust token listener/utils/src/serde_amount.rs", "rank": 6, "score": 112528.37368496062 }, { "content": "pub fn ask_for_key_path() -> Result<String, std::io::Error> {\n\n eprintln!(\n\n \"{} in order to create operation using trezor, you need to manually enter the {}, from which the {} was derived.\\n\\n For more about key derivation path see: {}\\n\",\n\n style(\"help:\").yellow(),\n\n style(\"path\").green(),\n\n style(\"--from\").bold(),\n\n style(\"https://learnmeabitcoin.com/technical/derivation-paths\").cyan(),\n\n );\n\n dialoguer::Input::with_theme(&ColorfulTheme::default())\n\n .with_prompt(\"please enter a key derivation path\")\n\n .with_initial_text(\"m/44'/1729'/0'\")\n\n .interact_text()\n\n}\n\n\n\n#[derive(thiserror::Error, Debug)]\n\npub enum GetKeyPathError {\n\n // /// If operation is to be created using, but we don't have key_path\n\n // /// available to us and interactivity is turned off, this error will be thrown.\n\n // NotAvailable,\n\n IO(#[from] std::io::Error),\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/lib/src/common/operation_command/raw_operation_command.rs", "rank": 7, "score": 109681.58214082668 }, { "content": "pub fn deserialize<'de, T, D>(d: D) -> Result<T, D::Error>\n\n where T: FromStr,\n\n <T as FromStr>::Err: Display,\n\n D: Deserializer<'de>,\n\n{\n\n let val_str: String = Deserialize::deserialize(d)?;\n\n T::from_str(&val_str)\n\n .map_err(serde::de::Error::custom)\n\n}\n", "file_path": "rust token listener/utils/src/serde_str.rs", "rank": 8, "score": 108966.73289932442 }, { "content": "pub fn deserialize<'de, D>(d: D) -> Result<u64, D::Error>\n\n where D: Deserializer<'de>,\n\n{\n\n let amount_str: String = Deserialize::deserialize(d)?;\n\n parse_float_amount(&amount_str)\n\n .or(Err(\"invalid_amount\".to_string()))\n\n .map_err(serde::de::Error::custom)\n\n}\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/utils/src/serde_amount.rs", "rank": 9, "score": 107678.07389759546 }, { "content": "pub fn serialize<S>(amount: &u64, s: S) -> Result<S::Ok, S::Error>\n\n where S: Serializer,\n\n{\n\n s.serialize_str(&amount.to_string())\n\n}\n\n\n", "file_path": "rust token listener/utils/src/serde_amount.rs", "rank": 10, "score": 105703.73232120798 }, { "content": "pub fn deserialize<'de, T, D>(d: D) -> Result<T, D::Error>\n\n where T: FromStr,\n\n <T as FromStr>::Err: Display,\n\n D: Deserializer<'de>,\n\n{\n\n let val_str: String = Deserialize::deserialize(d)?;\n\n T::from_str(&val_str)\n\n .map_err(serde::de::Error::custom)\n\n}\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/utils/src/serde_str.rs", "rank": 11, "score": 104303.2379677808 }, { "content": "type Error = Box<dyn std::error::Error>;\n\nconst BASE_FEE: u64 = 100;\n\nconst MIN_NTEZ_PER_GAS: u64 = 100;\n\nconst MIN_NTEZ_PER_BYTE: u64 = 1000;\n\nconst CONFIG: &str = \"./dependencies/json/config.json\";\n\nconst AWAIT_TIMEOUT: u128 = 120000; // ms\n\nconst RPC: &str = \"https://hangzhounet.api.tez.ie\";\n\nconst ENDPOINT: &str = \"https://api.hangzhounet.tzkt.io\";\n\n\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/lib/src/tezos_batch.rs", "rank": 12, "score": 104293.22559897506 }, { "content": "type Error = Box<dyn std::error::Error>;\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/lib/src/common/operation_command/mod.rs", "rank": 13, "score": 102997.38351606243 }, { "content": "pub fn serialize<T, S>(value: &T, s: S) -> Result<S::Ok, S::Error>\n\n where T: ToString,\n\n S: Serializer,\n\n{\n\n s.serialize_str(&value.to_string())\n\n}\n\n\n", "file_path": "rust token listener/utils/src/serde_str.rs", "rank": 14, "score": 102694.89406726294 }, { "content": "pub fn serialize<S>(amount: &u64, s: S) -> Result<S::Ok, S::Error>\n\n where S: Serializer,\n\n{\n\n s.serialize_str(&amount.to_string())\n\n}\n\n\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/utils/src/serde_amount.rs", "rank": 15, "score": 101216.45169883527 }, { "content": "pub fn serialize<T, S>(value: &T, s: S) -> Result<S::Ok, S::Error>\n\n where T: ToString,\n\n S: Serializer,\n\n{\n\n s.serialize_str(&value.to_string())\n\n}\n\n\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/utils/src/serde_str.rs", "rank": 16, "score": 98374.02308689301 }, { "content": "\"use strict\";(self.webpackChunkbridge=self.webpackChunkbridge||[]).push([[179],{532:()=>{function De(n){return\"function\"==typeof n}function xo(n){const e=n(i=>{Error.call(i),i.stack=(new Error).stack});return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}const fl=xo(n=>function(e){n(this),this.message=e?`${e.length} errors occurred during unsubscription:\\n${e.map((i,r)=>`${r+1}) ${i.toString()}`).join(\"\\n \")}`:\"\",this.name=\"UnsubscriptionError\",this.errors=e});function ss(n,t){if(n){const e=n.indexOf(t);0<=e&&n.splice(e,1)}}class ke{constructor(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}unsubscribe(){let t;if(!this.closed){this.closed=!0;const{_parentage:e}=this;if(e)if(this._parentage=null,Array.isArray(e))for(const s of e)s.remove(this);else e.remove(this);const{initialTeardown:i}=this;if(De(i))try{i()}catch(s){t=s instanceof fl?s.errors:[s]}const{_finalizers:r}=this;if(r){this._finalizers=null;for(const s of r)try{t_(s)}catch(o){t=null!=t?t:[],o instanceof fl?t=[...t,...o.errors]:t.push(o)}}if(t)throw new fl(t)}}add(t){var e;if(t&&t!==this)if(this.closed)t_(t);else{if(t instanceof ke){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(e=this._finalizers)&&void 0!==e?e:[]).push(t)}}_hasParent(t){const{_parentage:e}=this;return e===t||Array.isArray(e)&&e.includes(t)}_addParent(t){const{_parentage:e}=this;this._parentage=Array.isArray(e)?(e.push(t),e):e?[e,t]:t}_removeParent(t){const{_parentage:e}=this;e===t?this._parentage=null:Array.isArray(e)&&ss(e,t)}remove(t){const{_finalizers:e}=this;e&&ss(e,t),t instanceof ke&&t._removeParent(this)}}ke.EMPTY=(()=>{const n=new ke;return n.closed=!0,n})();const Jg=ke.EMPTY;function e_(n){return n instanceof ke||n&&\"closed\"in n&&De(n.remove)&&De(n.add)&&De(n.unsubscribe)}function t_(n){De(n)?n():n.unsubscribe()}const fr={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},ml={setTimeout(n,t,...e){const{delegate:i}=ml;return(null==i?void 0:i.setTimeout)?i.setTimeout(n,t,...e):setTimeout(n,t,...e)},clearTimeout(n){const{delegate:t}=ml;return((null==t?void 0:t.clearTimeout)||clearTimeout)(n)},delegate:void 0};function n_(n){ml.setTimeout(()=>{const{onUnhandledError:t}=fr;if(!t)throw n;t(n)})}function gl(){}const fk=fu(\"C\",void 0,void 0);function fu(n,t,e){return{kind:n,value:t,error:e}}let mr=null;function _l(n){if(fr.useDeprecatedSynchronousErrorHandling){const t=!mr;if(t&&(mr={errorThrown:!1,error:null}),n(),t){const{errorThrown:e,error:i}=mr;if(mr=null,e)throw i}}else n()}class mu extends ke{constructor(t){super(),this.isStopped=!1,t?(this.destination=t,e_(t)&&t.add(this)):this.destination=Ck}static create(t,e,i){return new vl(t,e,i)}next(t){this.isStopped?_u(function gk(n){return fu(\"N\",n,void 0)}(t),this):this._next(t)}error(t){this.isStopped?_u(function mk(n){return fu(\"E\",void 0,n)}(t),this):(this.isStopped=!0,this._error(t))}complete(){this.isStopped?_u(fk,this):(this.isStopped=!0,this._complete())}unsubscribe(){this.closed||(this.isStopped=!0,super.unsubscribe(),this.destination=null)}_next(t){this.destination.next(t)}_error(t){try{this.destination.error(t)}finally{this.unsubscribe()}}_complete(){try{this.destination.complete()}finally{this.unsubscribe()}}}const vk=Function.prototype.bind;function gu(n,t){return vk.call(n,t)}class yk{constructor(t){this.partialObserver=t}next(t){const{partialObserver:e}=this;if(e.next)try{e.next(t)}catch(i){yl(i)}}error(t){const{partialObserver:e}=this;if(e.error)try{e.error(t)}catch(i){yl(i)}else yl(t)}complete(){const{partialObserver:t}=this;if(t.complete)try{t.complete()}catch(e){yl(e)}}}class vl extends mu{constructor(t,e,i){let r;if(super(),De(t)||!t)r={next:null!=t?t:void 0,error:null!=e?e:void 0,complete:null!=i?i:void 0};else{let s;this&&fr.useDeprecatedNextContext?(s=Object.create(t),s.unsubscribe=()=>this.unsubscribe(),r={next:t.next&&gu(t.next,s),error:t.error&&gu(t.error,s),complete:t.complete&&gu(t.complete,s)}):r=t}this.destination=new yk(r)}}function yl(n){fr.useDeprecatedSynchronousErrorHandling?function _k(n){fr.useDeprecatedSynchronousErrorHandling&&mr&&(mr.errorThrown=!0,mr.error=n)}(n):n_(n)}function _u(n,t){const{onStoppedNotification:e}=fr;e&&ml.setTimeout(()=>e(n,t))}const Ck={closed:!0,next:gl,error:function bk(n){throw n},complete:gl},vu=\"function\"==typeof Symbol&&Symbol.observable||\"@@observable\";function Wi(n){return n}let Ve=(()=>{class n{constructor(e){e&&(this._subscribe=e)}lift(e){const i=new n;return i.source=this,i.operator=e,i}subscribe(e,i,r){const s=function wk(n){return n&&n instanceof mu||function Dk(n){return n&&De(n.next)&&De(n.error)&&De(n.complete)}(n)&&e_(n)}(e)?e:new vl(e,i,r);return _l(()=>{const{operator:o,source:a}=this;s.add(o?o.call(s,a):a?this._subscribe(s):this._trySubscribe(s))}),s}_trySubscribe(e){try{return this._subscribe(e)}catch(i){e.error(i)}}forEach(e,i){return new(i=r_(i))((r,s)=>{const o=new vl({next:a=>{try{e(a)}catch(l){s(l),o.unsubscribe()}},error:s,complete:r});this.subscribe(o)})}_subscribe(e){var i;return null===(i=this.source)||void 0===i?void 0:i.subscribe(e)}[vu](){return this}pipe(...e){return function i_(n){return 0===n.length?Wi:1===n.length?n[0]:function(e){return n.reduce((i,r)=>r(i),e)}}(e)(this)}toPromise(e){return new(e=r_(e))((i,r)=>{let s;this.subscribe(o=>s=o,o=>r(o),()=>i(s))})}}return n.create=t=>new n(t),n})();function r_(n){var t;return null!==(t=null!=n?n:fr.Promise)&&void 0!==t?t:Promise}const Mk=xo(n=>function(){n(this),this.name=\"ObjectUnsubscribedError\",this.message=\"object unsubscribed\"});let O=(()=>{class n extends Ve{constructor(){super(),this.closed=!1,this.currentObservers=null,this.observers=[],this.isStopped=!1,this.hasError=!1,this.thrownError=null}lift(e){const i=new s_(this,this);return i.operator=e,i}_throwIfClosed(){if(this.closed)throw new Mk}next(e){_l(()=>{if(this._throwIfClosed(),!this.isStopped){this.currentObservers||(this.currentObservers=Array.from(this.observers));for(const i of this.currentObservers)i.next(e)}})}error(e){_l(()=>{if(this._throwIfClosed(),!this.isStopped){this.hasError=this.isStopped=!0,this.thrownError=e;const{observers:i}=this;for(;i.length;)i.shift().error(e)}})}complete(){_l(()=>{if(this._throwIfClosed(),!this.isStopped){this.isStopped=!0;const{observers:e}=this;for(;e.length;)e.shift().complete()}})}unsubscribe(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null}get observed(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0}_trySubscribe(e){return this._throwIfClosed(),super._trySubscribe(e)}_subscribe(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)}_innerSubscribe(e){const{hasError:i,isStopped:r,observers:s}=this;return i||r?Jg:(this.currentObservers=null,s.push(e),new ke(()=>{this.currentObservers=null,ss(s,e)}))}_checkFinalizedStatuses(e){const{hasError:i,thrownError:r,isStopped:s}=this;i?e.error(r):s&&e.complete()}asObservable(){const e=new Ve;return e.source=this,e}}return n.create=(t,e)=>new s_(t,e),n})();class s_ extends O{constructor(t,e){super(),this.destination=t,this.source=e}next(t){var e,i;null===(i=null===(e=this.destination)||void 0===e?void 0:e.next)||void 0===i||i.call(e,t)}error(t){var e,i;null===(i=null===(e=this.destination)||void 0===e?void 0:e.error)||void 0===i||i.call(e,t)}complete(){var t,e;null===(e=null===(t=this.destination)||void 0===t?void 0:t.complete)||void 0===e||e.call(t)}_subscribe(t){var e,i;return null!==(i=null===(e=this.source)||void 0===e?void 0:e.subscribe(t))&&void 0!==i?i:Jg}}function o_(n){return De(null==n?void 0:n.lift)}function qe(n){return t=>{if(o_(t))return t.lift(function(e){try{return n(e,this)}catch(i){this.error(i)}});throw new TypeError(\"Unable to lift unknown Observable type\")}}function Ue(n,t,e,i,r){return new xk(n,t,e,i,r)}class xk extends mu{constructor(t,e,i,r,s,o){super(t),this.onFinalize=s,this.shouldUnsubscribe=o,this._next=e?function(a){try{e(a)}catch(l){t.error(l)}}:super._next,this._error=r?function(a){try{r(a)}catch(l){t.error(l)}finally{this.unsubscribe()}}:super._error,this._complete=i?function(){try{i()}catch(a){t.error(a)}finally{this.unsubscribe()}}:super._complete}unsubscribe(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){const{closed:e}=this;super.unsubscribe(),!e&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}}}function ue(n,t){return qe((e,i)=>{let r=0;e.subscribe(Ue(i,s=>{i.next(n.call(t,s,r++))}))})}function gr(n){return this instanceof gr?(this.v=n,this):new gr(n)}function kk(n,t,e){if(!Symbol.asyncIterator)throw new TypeError(\"Symbol.asyncIterator is not defined.\");var r,i=e.apply(n,t||[]),s=[];return r={},o(\"next\"),o(\"throw\"),o(\"return\"),r[Symbol.asyncIterator]=function(){return this},r;function o(h){i[h]&&(r[h]=function(p){return new Promise(function(m,g){s.push([h,p,m,g])>1||a(h,p)})})}function a(h,p){try{!function l(h){h.value instanceof gr?Promise.resolve(h.value.v).then(c,d):u(s[0][2],h)}(i[h](p))}catch(m){u(s[0][3],m)}}function c(h){a(\"next\",h)}function d(h){a(\"throw\",h)}function u(h,p){h(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function Tk(n){if(!Symbol.asyncIterator)throw new TypeError(\"Symbol.asyncIterator is not defined.\");var e,t=n[Symbol.asyncIterator];return t?t.call(n):(n=function c_(n){var t=\"function\"==typeof Symbol&&Symbol.iterator,e=t&&n[t],i=0;if(e)return e.call(n);if(n&&\"number\"==typeof n.length)return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(t?\"Object is not iterable.\":\"Symbol.iterator is not defined.\")}(n),e={},i(\"next\"),i(\"throw\"),i(\"return\"),e[Symbol.asyncIterator]=function(){return this},e);function i(s){e[s]=n[s]&&function(o){return new Promise(function(a,l){!function r(s,o,a,l){Promise.resolve(l).then(function(c){s({value:c,done:a})},o)}(a,l,(o=n[s](o)).done,o.value)})}}}const bu=n=>n&&\"number\"==typeof n.length&&\"function\"!=typeof n;function d_(n){return De(null==n?void 0:n.then)}function u_(n){return De(n[vu])}function h_(n){return Symbol.asyncIterator&&De(null==n?void 0:n[Symbol.asyncIterator])}function p_(n){return new TypeError(`You provided ${null!==n&&\"object\"==typeof n?\"an invalid object\":`'${n}'`} where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.`)}const f_=function Ik(){return\"function\"==typeof Symbol&&Symbol.iterator?Symbol.iterator:\"@@iterator\"}();function m_(n){return De(null==n?void 0:n[f_])}function g_(n){return kk(this,arguments,function*(){const e=n.getReader();try{for(;;){const{value:i,done:r}=yield gr(e.read());if(r)return yield gr(void 0);yield yield gr(i)}}finally{e.releaseLock()}})}function __(n){return De(null==n?void 0:n.getReader)}function Jt(n){if(n instanceof Ve)return n;if(null!=n){if(u_(n))return function Rk(n){return new Ve(t=>{const e=n[vu]();if(De(e.subscribe))return e.subscribe(t);throw new TypeError(\"Provided object does not correctly implement Symbol.observable\")})}(n);if(bu(n))return function Ok(n){return new Ve(t=>{for(let e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()})}(n);if(d_(n))return function Pk(n){return new Ve(t=>{n.then(e=>{t.closed||(t.next(e),t.complete())},e=>t.error(e)).then(null,n_)})}(n);if(h_(n))return v_(n);if(m_(n))return function Fk(n){return new Ve(t=>{for(const e of n)if(t.next(e),t.closed)return;t.complete()})}(n);if(__(n))return function Nk(n){return v_(g_(n))}(n)}throw p_(n)}function v_(n){return new Ve(t=>{(function Lk(n,t){var e,i,r,s;return function Ek(n,t,e,i){return new(e||(e=Promise))(function(s,o){function a(d){try{c(i.next(d))}catch(u){o(u)}}function l(d){try{c(i.throw(d))}catch(u){o(u)}}function c(d){d.done?s(d.value):function r(s){return s instanceof e?s:new e(function(o){o(s)})}(d.value).then(a,l)}c((i=i.apply(n,t||[])).next())})}(this,void 0,void 0,function*(){try{for(e=Tk(n);!(i=yield e.next()).done;)if(t.next(i.value),t.closed)return}catch(o){r={error:o}}finally{try{i&&!i.done&&(s=e.return)&&(yield s.call(e))}finally{if(r)throw r.error}}t.complete()})})(n,t).catch(e=>t.error(e))})}function Mi(n,t,e,i=0,r=!1){const s=t.schedule(function(){e(),r?n.add(this.schedule(null,i)):this.unsubscribe()},i);if(n.add(s),!r)return s}function lt(n,t,e=1/0){return De(t)?lt((i,r)=>ue((s,o)=>t(i,s,r,o))(Jt(n(i,r))),e):(\"number\"==typeof t&&(e=t),qe((i,r)=>function Bk(n,t,e,i,r,s,o,a){const l=[];let c=0,d=0,u=!1;const h=()=>{u&&!l.length&&!c&&t.complete()},p=g=>c<i?m(g):l.push(g),m=g=>{s&&t.next(g),c++;let _=!1;Jt(e(g,d++)).subscribe(Ue(t,D=>{null==r||r(D),s?p(D):t.next(D)},()=>{_=!0},void 0,()=>{if(_)try{for(c--;l.length&&c<i;){const D=l.shift();o?Mi(t,o,()=>m(D)):m(D)}h()}catch(D){t.error(D)}}))};return n.subscribe(Ue(t,p,()=>{u=!0,h()})),()=>{null==a||a()}}(i,r,n,e)))}function Eo(n=1/0){return lt(Wi,n)}const ri=new Ve(n=>n.complete());function y_(n){return n&&De(n.schedule)}function Cu(n){return n[n.length-1]}function b_(n){return De(Cu(n))?n.pop():void 0}function So(n){return y_(Cu(n))?n.pop():void 0}function C_(n,t=0){return qe((e,i)=>{e.subscribe(Ue(i,r=>Mi(i,n,()=>i.next(r),t),()=>Mi(i,n,()=>i.complete(),t),r=>Mi(i,n,()=>i.error(r),t)))})}function D_(n,t=0){return qe((e,i)=>{i.add(n.schedule(()=>e.subscribe(i),t))})}function w_(n,t){if(!n)throw new Error(\"Iterable cannot be null\");return new Ve(e=>{Mi(e,t,()=>{const i=n[Symbol.asyncIterator]();Mi(e,t,()=>{i.next().then(r=>{r.done?e.complete():e.next(r.value)})},0,!0)})})}function mt(n,t){return t?function Wk(n,t){if(null!=n){if(u_(n))return function jk(n,t){return Jt(n).pipe(D_(t),C_(t))}(n,t);if(bu(n))return function Uk(n,t){return new Ve(e=>{let i=0;return t.schedule(function(){i===n.length?e.complete():(e.next(n[i++]),e.closed||this.schedule())})})}(n,t);if(d_(n))return function zk(n,t){return Jt(n).pipe(D_(t),C_(t))}(n,t);if(h_(n))return w_(n,t);if(m_(n))return function $k(n,t){return new Ve(e=>{let i;return Mi(e,t,()=>{i=n[f_](),Mi(e,t,()=>{let r,s;try{({value:r,done:s}=i.next())}catch(o){return void e.error(o)}s?e.complete():e.next(r)},0,!0)}),()=>De(null==i?void 0:i.return)&&i.return()})}(n,t);if(__(n))return function Gk(n,t){return w_(g_(n),t)}(n,t)}throw p_(n)}(n,t):Jt(n)}function Bt(...n){const t=So(n),e=function Hk(n,t){return\"number\"==typeof Cu(n)?n.pop():t}(n,1/0),i=n;return i.length?1===i.length?Jt(i[0]):Eo(e)(mt(i,t)):ri}function it(n){return n<=0?()=>ri:qe((t,e)=>{let i=0;t.subscribe(Ue(e,r=>{++i<=n&&(e.next(r),n<=i&&e.complete())}))})}function Du(n,t,...e){return!0===t?(n(),null):!1===t?null:t(...e).pipe(it(1)).subscribe(()=>n())}function Fe(n){for(let t in n)if(n[t]===Fe)return t;throw Error(\"Could not find renamed property on target object.\")}function wu(n,t){for(const e in t)t.hasOwnProperty(e)&&!n.hasOwnProperty(e)&&(n[e]=t[e])}function Re(n){if(\"string\"==typeof n)return n;if(Array.isArray(n))return\"[\"+n.map(Re).join(\", \")+\"]\";if(null==n)return\"\"+n;if(n.overriddenName)return`${n.overriddenName}`;if(n.name)return`${n.name}`;const t=n.toString();if(null==t)return\"\"+t;const e=t.indexOf(\"\\n\");return-1===e?t:t.substring(0,e)}function Mu(n,t){return null==n||\"\"===n?null===t?\"\":t:null==t||\"\"===t?n:n+\" \"+t}const qk=Fe({__forward_ref__:Fe});function pe(n){return n.__forward_ref__=pe,n.toString=function(){return Re(this())},n}function le(n){return x_(n)?n():n}function x_(n){return\"function\"==typeof n&&n.hasOwnProperty(qk)&&n.__forward_ref__===pe}class H extends Error{constructor(t,e){super(function xu(n,t){return`NG0${Math.abs(n)}${t?\": \"+t:\"\"}`}(t,e)),this.code=t}}function re(n){return\"string\"==typeof n?n:null==n?\"\":String(n)}function Vt(n){return\"function\"==typeof n?n.name||n.toString():\"object\"==typeof n&&null!=n&&\"function\"==typeof n.type?n.type.name||n.type.toString():re(n)}function bl(n,t){const e=t?` in ${t}`:\"\";throw new H(-201,`No provider for ${Vt(n)} found${e}`)}function tn(n,t){null==n&&function $e(n,t,e,i){throw new Error(`ASSERTION ERROR: ${n}`+(null==i?\"\":` [Expected=> ${e} ${i} ${t} <=Actual]`))}(t,n,null,\"!=\")}function k(n){return{token:n.token,providedIn:n.providedIn||null,factory:n.factory,value:void 0}}function P(n){return{providers:n.providers||[],imports:n.imports||[]}}function Eu(n){return E_(n,Cl)||E_(n,k_)}function E_(n,t){return n.hasOwnProperty(t)?n[t]:null}function S_(n){return n&&(n.hasOwnProperty(Su)||n.hasOwnProperty(eT))?n[Su]:null}const Cl=Fe({\\u0275prov:Fe}),Su=Fe({\\u0275inj:Fe}),k_=Fe({ngInjectableDef:Fe}),eT=Fe({ngInjectorDef:Fe});var ee=(()=>((ee=ee||{})[ee.Default=0]=\"Default\",ee[ee.Host=1]=\"Host\",ee[ee.Self=2]=\"Self\",ee[ee.SkipSelf=4]=\"SkipSelf\",ee[ee.Optional=8]=\"Optional\",ee))();let ku;function qi(n){const t=ku;return ku=n,t}function T_(n,t,e){const i=Eu(n);return i&&\"root\"==i.providedIn?void 0===i.value?i.value=i.factory():i.value:e&ee.Optional?null:void 0!==t?t:void bl(Re(n),\"Injector\")}function Yi(n){return{toString:n}.toString()}var Nn=(()=>((Nn=Nn||{})[Nn.OnPush=0]=\"OnPush\",Nn[Nn.Default=1]=\"Default\",Nn))(),Ln=(()=>{return(n=Ln||(Ln={}))[n.Emulated=0]=\"Emulated\",n[n.None=2]=\"None\",n[n.ShadowDom=3]=\"ShadowDom\",Ln;var n})();const nT=\"undefined\"!=typeof globalThis&&globalThis,iT=\"undefined\"!=typeof window&&window,rT=\"undefined\"!=typeof self&&\"undefined\"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&self,Oe=nT||\"undefined\"!=typeof global&&global||iT||rT,os={},Ne=[],Dl=Fe({\\u0275cmp:Fe}),Tu=Fe({\\u0275dir:Fe}),Au=Fe({\\u0275pipe:Fe}),A_=Fe({\\u0275mod:Fe}),Ei=Fe({\\u0275fac:Fe}),ko=Fe({__NG_ELEMENT_ID__:Fe});let sT=0;function xe(n){return Yi(()=>{const e={},i={type:n.type,providersResolver:null,decls:n.decls,vars:n.vars,factory:null,template:n.template||null,consts:n.consts||null,ngContentSelectors:n.ngContentSelectors,hostBindings:n.hostBindings||null,hostVars:n.hostVars||0,hostAttrs:n.hostAttrs||null,contentQueries:n.contentQueries||null,declaredInputs:e,inputs:null,outputs:null,exportAs:n.exportAs||null,onPush:n.changeDetection===Nn.OnPush,directiveDefs:null,pipeDefs:null,selectors:n.selectors||Ne,viewQuery:n.viewQuery||null,features:n.features||null,data:n.data||{},encapsulation:n.encapsulation||Ln.Emulated,id:\"c\",styles:n.styles||Ne,_:null,setInput:null,schemas:n.schemas||null,tView:null},r=n.directives,s=n.features,o=n.pipes;return i.id+=sT++,i.inputs=P_(n.inputs,e),i.outputs=P_(n.outputs),s&&s.forEach(a=>a(i)),i.directiveDefs=r?()=>(\"function\"==typeof r?r():r).map(I_):null,i.pipeDefs=o?()=>(\"function\"==typeof o?o():o).map(R_):null,i})}function I_(n){return Ot(n)||function Qi(n){return n[Tu]||null}(n)}function R_(n){return function _r(n){return n[Au]||null}(n)}const O_={};function F(n){return Yi(()=>{const t={type:n.type,bootstrap:n.bootstrap||Ne,declarations:n.declarations||Ne,imports:n.imports||Ne,exports:n.exports||Ne,transitiveCompileScopes:null,schemas:n.schemas||null,id:n.id||null};return null!=n.id&&(O_[n.id]=n.type),t})}function P_(n,t){if(null==n)return os;const e={};for(const i in n)if(n.hasOwnProperty(i)){let r=n[i],s=r;Array.isArray(r)&&(s=r[1],r=r[0]),e[r]=i,t&&(t[r]=s)}return e}const C=xe;function Ot(n){return n[Dl]||null}function gn(n,t){const e=n[A_]||null;if(!e&&!0===t)throw new Error(`Type ${Re(n)} does not have '\\u0275mod' property.`);return e}function si(n){return Array.isArray(n)&&\"object\"==typeof n[1]}function Vn(n){return Array.isArray(n)&&!0===n[1]}function Ou(n){return 0!=(8&n.flags)}function El(n){return 2==(2&n.flags)}function Sl(n){return 1==(1&n.flags)}function Hn(n){return null!==n.template}function uT(n){return 0!=(512&n[2])}function Cr(n,t){return n.hasOwnProperty(Ei)?n[Ei]:null}class fT{constructor(t,e,i){this.previousValue=t,this.currentValue=e,this.firstChange=i}isFirstChange(){return this.firstChange}}function Je(){return N_}function N_(n){return n.type.prototype.ngOnChanges&&(n.setInput=gT),mT}function mT(){const n=B_(this),t=null==n?void 0:n.current;if(t){const e=n.previous;if(e===os)n.previous=t;else for(let i in t)e[i]=t[i];n.current=null,this.ngOnChanges(t)}}function gT(n,t,e,i){const r=B_(n)||function _T(n,t){return n[L_]=t}(n,{previous:os,current:null}),s=r.current||(r.current={}),o=r.previous,a=this.declaredInputs[e],l=o[a];s[a]=new fT(l&&l.currentValue,t,o===os),n[i]=t}Je.ngInherit=!0;const L_=\"__ngSimpleChanges__\";function B_(n){return n[L_]||null}let Bu;function et(n){return!!n.listen}const V_={createRenderer:(n,t)=>function Vu(){return void 0!==Bu?Bu:\"undefined\"!=typeof document?document:void 0}()};function ct(n){for(;Array.isArray(n);)n=n[0];return n}function kl(n,t){return ct(t[n])}function yn(n,t){return ct(t[n.index])}function Hu(n,t){return n.data[t]}function rn(n,t){const e=t[n];return si(e)?e:e[0]}function H_(n){return 4==(4&n[2])}function ju(n){return 128==(128&n[2])}function Ki(n,t){return null==t?null:n[t]}function j_(n){n[18]=0}function zu(n,t){n[5]+=t;let e=n,i=n[3];for(;null!==i&&(1===t&&1===e[5]||-1===t&&0===e[5]);)i[5]+=t,e=i,i=i[3]}const te={lFrame:Q_(null),bindingsEnabled:!0,isInCheckNoChangesMode:!1};function z_(){return te.bindingsEnabled}function w(){return te.lFrame.lView}function Me(){return te.lFrame.tView}function Dr(n){return te.lFrame.contextLView=n,n[8]}function gt(){let n=U_();for(;null!==n&&64===n.type;)n=n.parent;return n}function U_(){return te.lFrame.currentTNode}function oi(n,t){const e=te.lFrame;e.currentTNode=n,e.isParent=t}function Uu(){return te.lFrame.isParent}function $u(){te.lFrame.isParent=!1}function Tl(){return te.isInCheckNoChangesMode}function Al(n){te.isInCheckNoChangesMode=n}function hs(){return te.lFrame.bindingIndex++}function ki(n){const t=te.lFrame,e=t.bindingIndex;return t.bindingIndex=t.bindingIndex+n,e}function PT(n,t){const e=te.lFrame;e.bindingIndex=e.bindingRootIndex=n,Gu(t)}function Gu(n){te.lFrame.currentDirectiveIndex=n}function Wu(n){const t=te.lFrame.currentDirectiveIndex;return-1===t?null:n[t]}function W_(){return te.lFrame.currentQueryIndex}function qu(n){te.lFrame.currentQueryIndex=n}function NT(n){const t=n[1];return 2===t.type?t.declTNode:1===t.type?n[6]:null}function q_(n,t,e){if(e&ee.SkipSelf){let r=t,s=n;for(;!(r=r.parent,null!==r||e&ee.Host||(r=NT(s),null===r||(s=s[15],10&r.type))););if(null===r)return!1;t=r,n=s}const i=te.lFrame=Y_();return i.currentTNode=t,i.lView=n,!0}function Il(n){const t=Y_(),e=n[1];te.lFrame=t,t.currentTNode=e.firstChild,t.lView=n,t.tView=e,t.contextLView=n,t.bindingIndex=e.bindingStartIndex,t.inI18n=!1}function Y_(){const n=te.lFrame,t=null===n?null:n.child;return null===t?Q_(n):t}function Q_(n){const t={currentTNode:null,isParent:!0,lView:null,tView:null,selectedIndex:-1,contextLView:null,elementDepthCount:0,currentNamespace:null,currentDirectiveIndex:-1,bindingRootIndex:-1,bindingIndex:-1,currentQueryIndex:0,parent:n,child:null,inI18n:!1};return null!==n&&(n.child=t),t}function K_(){const n=te.lFrame;return te.lFrame=n.parent,n.currentTNode=null,n.lView=null,n}const Z_=K_;function Rl(){const n=K_();n.isParent=!0,n.tView=null,n.selectedIndex=-1,n.contextLView=null,n.elementDepthCount=0,n.currentDirectiveIndex=-1,n.currentNamespace=null,n.bindingRootIndex=-1,n.bindingIndex=-1,n.currentQueryIndex=0}function jt(){return te.lFrame.selectedIndex}function Zi(n){te.lFrame.selectedIndex=n}function tt(){const n=te.lFrame;return Hu(n.tView,n.selectedIndex)}function Oo(){te.lFrame.currentNamespace=\"svg\"}function Ol(n,t){for(let e=t.directiveStart,i=t.directiveEnd;e<i;e++){const s=n.data[e].type.prototype,{ngAfterContentInit:o,ngAfterContentChecked:a,ngAfterViewInit:l,ngAfterViewChecked:c,ngOnDestroy:d}=s;o&&(n.contentHooks||(n.contentHooks=[])).push(-e,o),a&&((n.contentHooks||(n.contentHooks=[])).push(e,a),(n.contentCheckHooks||(n.contentCheckHooks=[])).push(e,a)),l&&(n.viewHooks||(n.viewHooks=[])).push(-e,l),c&&((n.viewHooks||(n.viewHooks=[])).push(e,c),(n.viewCheckHooks||(n.viewCheckHooks=[])).push(e,c)),null!=d&&(n.destroyHooks||(n.destroyHooks=[])).push(e,d)}}function Pl(n,t,e){J_(n,t,3,e)}function Fl(n,t,e,i){(3&n[2])===e&&J_(n,t,e,i)}function Yu(n,t){let e=n[2];(3&e)===t&&(e&=2047,e+=1,n[2]=e)}function J_(n,t,e,i){const s=null!=i?i:-1,o=t.length-1;let a=0;for(let l=void 0!==i?65535&n[18]:0;l<o;l++)if(\"number\"==typeof t[l+1]){if(a=t[l],null!=i&&a>=i)break}else t[l]<0&&(n[18]+=65536),(a<s||-1==s)&&(UT(n,e,t,l),n[18]=(4294901760&n[18])+l+2),l++}function UT(n,t,e,i){const r=e[i]<0,s=e[i+1],a=n[r?-e[i]:e[i]];if(r){if(n[2]>>11<n[18]>>16&&(3&n[2])===t){n[2]+=2048;try{s.call(a)}finally{}}}else try{s.call(a)}finally{}}class Po{constructor(t,e,i){this.factory=t,this.resolving=!1,this.canSeeViewProviders=e,this.injectImpl=i}}function Nl(n,t,e){const i=et(n);let r=0;for(;r<e.length;){const s=e[r];if(\"number\"==typeof s){if(0!==s)break;r++;const o=e[r++],a=e[r++],l=e[r++];i?n.setAttribute(t,a,l,o):t.setAttributeNS(o,a,l)}else{const o=s,a=e[++r];Ku(o)?i&&n.setProperty(t,o,a):i?n.setAttribute(t,o,a):t.setAttribute(o,a),r++}}return r}function ev(n){return 3===n||4===n||6===n}function Ku(n){return 64===n.charCodeAt(0)}function Ll(n,t){if(null!==t&&0!==t.length)if(null===n||0===n.length)n=t.slice();else{let e=-1;for(let i=0;i<t.length;i++){const r=t[i];\"number\"==typeof r?e=r:0===e||tv(n,e,r,null,-1===e||2===e?t[++i]:null)}}return n}function tv(n,t,e,i,r){let s=0,o=n.length;if(-1===t)o=-1;else for(;s<n.length;){const a=n[s++];if(\"number\"==typeof a){if(a===t){o=-1;break}if(a>t){o=s-1;break}}}for(;s<n.length;){const a=n[s];if(\"number\"==typeof a)break;if(a===e){if(null===i)return void(null!==r&&(n[s+1]=r));if(i===n[s+1])return void(n[s+2]=r)}s++,null!==i&&s++,null!==r&&s++}-1!==o&&(n.splice(o,0,t),s=o+1),n.splice(s++,0,e),null!==i&&n.splice(s++,0,i),null!==r&&n.splice(s++,0,r)}function nv(n){return-1!==n}function ps(n){return 32767&n}function fs(n,t){let e=function YT(n){return n>>16}(n),i=t;for(;e>0;)i=i[15],e--;return i}let Zu=!0;function Bl(n){const t=Zu;return Zu=n,t}let QT=0;function No(n,t){const e=Ju(n,t);if(-1!==e)return e;const i=t[1];i.firstCreatePass&&(n.injectorIndex=t.length,Xu(i.data,n),Xu(t,null),Xu(i.blueprint,null));const r=Vl(n,t),s=n.injectorIndex;if(nv(r)){const o=ps(r),a=fs(r,t),l=a[1].data;for(let c=0;c<8;c++)t[s+c]=a[o+c]|l[o+c]}return t[s+8]=r,s}function Xu(n,t){n.push(0,0,0,0,0,0,0,0,t)}function Ju(n,t){return-1===n.injectorIndex||n.parent&&n.parent.injectorIndex===n.injectorIndex||null===t[n.injectorIndex+8]?-1:n.injectorIndex}function Vl(n,t){if(n.parent&&-1!==n.parent.injectorIndex)return n.parent.injectorIndex;let e=0,i=null,r=t;for(;null!==r;){const s=r[1],o=s.type;if(i=2===o?s.declTNode:1===o?r[6]:null,null===i)return-1;if(e++,r=r[15],-1!==i.injectorIndex)return i.injectorIndex|e<<16}return-1}function Hl(n,t,e){!function KT(n,t,e){let i;\"string\"==typeof e?i=e.charCodeAt(0)||0:e.hasOwnProperty(ko)&&(i=e[ko]),null==i&&(i=e[ko]=QT++);const r=255&i;t.data[n+(r>>5)]|=1<<r}(n,t,e)}function sv(n,t,e){if(e&ee.Optional)return n;bl(t,\"NodeInjector\")}function ov(n,t,e,i){if(e&ee.Optional&&void 0===i&&(i=null),0==(e&(ee.Self|ee.Host))){const r=n[9],s=qi(void 0);try{return r?r.get(t,i,e&ee.Optional):T_(t,i,e&ee.Optional)}finally{qi(s)}}return sv(i,t,e)}function av(n,t,e,i=ee.Default,r){if(null!==n){const s=function eA(n){if(\"string\"==typeof n)return n.charCodeAt(0)||0;const t=n.hasOwnProperty(ko)?n[ko]:void 0;return\"number\"==typeof t?t>=0?255&t:XT:t}(e);if(\"function\"==typeof s){if(!q_(t,n,i))return i&ee.Host?sv(r,e,i):ov(t,e,i,r);try{const o=s(i);if(null!=o||i&ee.Optional)return o;bl(e)}finally{Z_()}}else if(\"number\"==typeof s){let o=null,a=Ju(n,t),l=-1,c=i&ee.Host?t[16][6]:null;for((-1===a||i&ee.SkipSelf)&&(l=-1===a?Vl(n,t):t[a+8],-1!==l&&dv(i,!1)?(o=t[1],a=ps(l),t=fs(l,t)):a=-1);-1!==a;){const d=t[1];if(cv(s,a,d.data)){const u=JT(a,t,e,o,i,c);if(u!==lv)return u}l=t[a+8],-1!==l&&dv(i,t[1].data[a+8]===c)&&cv(s,a,t)?(o=d,a=ps(l),t=fs(l,t)):a=-1}}}return ov(t,e,i,r)}const lv={};function XT(){return new ms(gt(),w())}function JT(n,t,e,i,r,s){const o=t[1],a=o.data[n+8],d=jl(a,o,e,null==i?El(a)&&Zu:i!=o&&0!=(3&a.type),r&ee.Host&&s===a);return null!==d?Lo(t,o,d,a):lv}function jl(n,t,e,i,r){const s=n.providerIndexes,o=t.data,a=1048575&s,l=n.directiveStart,d=s>>20,h=r?a+d:n.directiveEnd;for(let p=i?a:a+d;p<h;p++){const m=o[p];if(p<l&&e===m||p>=l&&m.type===e)return p}if(r){const p=o[l];if(p&&Hn(p)&&p.type===e)return l}return null}function Lo(n,t,e,i){let r=n[e];const s=t.data;if(function $T(n){return n instanceof Po}(r)){const o=r;o.resolving&&function Yk(n,t){const e=t?`. Dependency path: ${t.join(\" > \")} > ${n}`:\"\";throw new H(-200,`Circular dependency in DI detected for ${n}${e}`)}(Vt(s[e]));const a=Bl(o.canSeeViewProviders);o.resolving=!0;const l=o.injectImpl?qi(o.injectImpl):null;q_(n,i,ee.Default);try{r=n[e]=o.factory(void 0,s,n,i),t.firstCreatePass&&e>=i.directiveStart&&function zT(n,t,e){const{ngOnChanges:i,ngOnInit:r,ngDoCheck:s}=t.type.prototype;if(i){const o=N_(t);(e.preOrderHooks||(e.preOrderHooks=[])).push(n,o),(e.preOrderCheckHooks||(e.preOrderCheckHooks=[])).push(n,o)}r&&(e.preOrderHooks||(e.preOrderHooks=[])).push(0-n,r),s&&((e.preOrderHooks||(e.preOrderHooks=[])).push(n,s),(e.preOrderCheckHooks||(e.preOrderCheckHooks=[])).push(n,s))}(e,s[e],t)}finally{null!==l&&qi(l),Bl(a),o.resolving=!1,Z_()}}return r}function cv(n,t,e){return!!(e[t+(n>>5)]&1<<n)}function dv(n,t){return!(n&ee.Self||n&ee.Host&&t)}class ms{constructor(t,e){this._tNode=t,this._lView=e}get(t,e,i){return av(this._tNode,this._lView,t,i,e)}}function oe(n){return Yi(()=>{const t=n.prototype.constructor,e=t[Ei]||eh(t),i=Object.prototype;let r=Object.getPrototypeOf(n.prototype).constructor;for(;r&&r!==i;){const s=r[Ei]||eh(r);if(s&&s!==e)return s;r=Object.getPrototypeOf(r)}return s=>new s})}function eh(n){return x_(n)?()=>{const t=eh(le(n));return t&&t()}:Cr(n)}function kt(n){return function ZT(n,t){if(\"class\"===t)return n.classes;if(\"style\"===t)return n.styles;const e=n.attrs;if(e){const i=e.length;let r=0;for(;r<i;){const s=e[r];if(ev(s))break;if(0===s)r+=2;else if(\"number\"==typeof s)for(r++;r<i&&\"string\"==typeof e[r];)r++;else{if(s===t)return e[r+1];r+=2}}}return null}(gt(),n)}const _s=\"__parameters__\";function ys(n,t,e){return Yi(()=>{const i=function th(n){return function(...e){if(n){const i=n(...e);for(const r in i)this[r]=i[r]}}}(t);function r(...s){if(this instanceof r)return i.apply(this,s),this;const o=new r(...s);return a.annotation=o,a;function a(l,c,d){const u=l.hasOwnProperty(_s)?l[_s]:Object.defineProperty(l,_s,{value:[]})[_s];for(;u.length<=d;)u.push(null);return(u[d]=u[d]||[]).push(o),l}}return e&&(r.prototype=Object.create(e.prototype)),r.prototype.ngMetadataName=n,r.annotationCls=r,r})}class b{constructor(t,e){this._desc=t,this.ngMetadataName=\"InjectionToken\",this.\\u0275prov=void 0,\"number\"==typeof e?this.__NG_ELEMENT_ID__=e:void 0!==e&&(this.\\u0275prov=k({token:this,providedIn:e.providedIn||\"root\",factory:e.factory}))}toString(){return`InjectionToken ${this._desc}`}}const nA=new b(\"AnalyzeForEntryComponents\");function bn(n,t){void 0===t&&(t=n);for(let e=0;e<n.length;e++){let i=n[e];Array.isArray(i)?(t===n&&(t=n.slice(0,e)),bn(i,t)):t!==n&&t.push(i)}return t}function ai(n,t){n.forEach(e=>Array.isArray(e)?ai(e,t):t(e))}function hv(n,t,e){t>=n.length?n.push(e):n.splice(t,0,e)}function zl(n,t){return t>=n.length-1?n.pop():n.splice(t,1)[0]}function Ho(n,t){const e=[];for(let i=0;i<n;i++)e.push(t);return e}function sn(n,t,e){let i=bs(n,t);return i>=0?n[1|i]=e:(i=~i,function sA(n,t,e,i){let r=n.length;if(r==t)n.push(e,i);else if(1===r)n.push(i,n[0]),n[0]=e;else{for(r--,n.push(n[r-1],n[r]);r>t;)n[r]=n[r-2],r--;n[t]=e,n[t+1]=i}}(n,i,t,e)),i}function ih(n,t){const e=bs(n,t);if(e>=0)return n[1|e]}function bs(n,t){return function mv(n,t,e){let i=0,r=n.length>>e;for(;r!==i;){const s=i+(r-i>>1),o=n[s<<e];if(t===o)return s<<e;o>t?r=s:i=s+1}return~(r<<e)}(n,t,1)}const jo={},sh=\"__NG_DI_FLAG__\",$l=\"ngTempTokenPath\",hA=/\\n/gm,_v=\"__source\",fA=Fe({provide:String,useValue:Fe});let zo;function vv(n){const t=zo;return zo=n,t}function mA(n,t=ee.Default){if(void 0===zo)throw new H(203,\"\");return null===zo?T_(n,void 0,t):zo.get(n,t&ee.Optional?null:void 0,t)}function y(n,t=ee.Default){return(function tT(){return ku}()||mA)(le(n),t)}const Uo=y;function oh(n){const t=[];for(let e=0;e<n.length;e++){const i=le(n[e]);if(Array.isArray(i)){if(0===i.length)throw new H(900,\"\");let r,s=ee.Default;for(let o=0;o<i.length;o++){const a=i[o],l=gA(a);\"number\"==typeof l?-1===l?r=a.token:s|=l:r=a}t.push(y(r,s))}else t.push(y(i))}return t}function $o(n,t){return n[sh]=t,n.prototype[sh]=t,n}function gA(n){return n[sh]}const Gl=$o(ys(\"Inject\",n=>({token:n})),-1),Tt=$o(ys(\"Optional\"),8),Cn=$o(ys(\"SkipSelf\"),4);function on(n){return n instanceof class wr{constructor(t){this.changingThisBreaksApplicationSecurity=t}toString(){return`SafeValue must use [property]=binding: ${this.changingThisBreaksApplicationSecurity} (see https://g.co/ng/security#xss)`}}?n.changingThisBreaksApplicationSecurity:n}const Bv=\"__ngContext__\";function Ft(n,t){n[Bv]=t}function gh(n){const t=function Qo(n){return n[Bv]||null}(n);return t?Array.isArray(t)?t:t.lView:null}function vh(n){return n.ngOriginalError}function uI(n,...t){n.error(...t)}class Mr{constructor(){this._console=console}handleError(t){const e=this._findOriginalError(t),i=function dI(n){return n&&n.ngErrorLogger||uI}(t);i(this._console,\"ERROR\",t),e&&i(this._console,\"ORIGINAL ERROR\",e)}_findOriginalError(t){let e=t&&vh(t);for(;e&&vh(e);)e=vh(e);return e||null}}const CI=(()=>(\"undefined\"!=typeof requestAnimationFrame&&requestAnimationFrame||setTimeout).bind(Oe))();function Uv(n){return n.ownerDocument.defaultView}function di(n){return n instanceof Function?n():n}var an=(()=>((an=an||{})[an.Important=1]=\"Important\",an[an.DashCase=2]=\"DashCase\",an))();function bh(n,t){return undefined(n,t)}function Ko(n){const t=n[3];return Vn(t)?t[3]:t}function Ch(n){return Yv(n[13])}function Dh(n){return Yv(n[4])}function Yv(n){for(;null!==n&&!Vn(n);)n=n[4];return n}function Ms(n,t,e,i,r){if(null!=i){let s,o=!1;Vn(i)?s=i:si(i)&&(o=!0,i=i[0]);const a=ct(i);0===n&&null!==e?null==r?ey(t,e,a):xr(t,e,a,r||null,!0):1===n&&null!==e?xr(t,e,a,r||null,!0):2===n?function ay(n,t,e){const i=Kl(n,t);i&&function PI(n,t,e,i){et(n)?n.removeChild(t,e,i):t.removeChild(e)}(n,i,t,e)}(t,a,o):3===n&&t.destroyNode(a),null!=s&&function LI(n,t,e,i,r){const s=e[7];s!==ct(e)&&Ms(t,n,i,s,r);for(let a=10;a<e.length;a++){const l=e[a];Zo(l[1],l,n,t,i,s)}}(t,n,s,e,r)}}function Mh(n,t,e){if(et(n))return n.createElement(t,e);{const i=null!==e?function CT(n){const t=n.toLowerCase();return\"svg\"===t?\"http://www.w3.org/2000/svg\":\"math\"===t?\"http://www.w3.org/1998/MathML/\":null}(e):null;return null===i?n.createElement(t):n.createElementNS(i,t)}}function Kv(n,t){const e=n[9],i=e.indexOf(t),r=t[3];1024&t[2]&&(t[2]&=-1025,zu(r,-1)),e.splice(i,1)}function xh(n,t){if(n.length<=10)return;const e=10+t,i=n[e];if(i){const r=i[17];null!==r&&r!==n&&Kv(r,i),t>0&&(n[e-1][4]=i[4]);const s=zl(n,10+t);!function EI(n,t){Zo(n,t,t[11],2,null,null),t[0]=null,t[6]=null}(i[1],i);const o=s[19];null!==o&&o.detachView(s[1]),i[3]=null,i[4]=null,i[2]&=-129}return i}function Zv(n,t){if(!(256&t[2])){const e=t[11];et(e)&&e.destroyNode&&Zo(n,t,e,3,null,null),function TI(n){let t=n[13];if(!t)return Eh(n[1],n);for(;t;){let e=null;if(si(t))e=t[13];else{const i=t[10];i&&(e=i)}if(!e){for(;t&&!t[4]&&t!==n;)si(t)&&Eh(t[1],t),t=t[3];null===t&&(t=n),si(t)&&Eh(t[1],t),e=t&&t[4]}t=e}}(t)}}function Eh(n,t){if(!(256&t[2])){t[2]&=-129,t[2]|=256,function OI(n,t){let e;if(null!=n&&null!=(e=n.destroyHooks))for(let i=0;i<e.length;i+=2){const r=t[e[i]];if(!(r instanceof Po)){const s=e[i+1];if(Array.isArray(s))for(let o=0;o<s.length;o+=2){const a=r[s[o]],l=s[o+1];try{l.call(a)}finally{}}else try{s.call(r)}finally{}}}}(n,t),function RI(n,t){const e=n.cleanup,i=t[7];let r=-1;if(null!==e)for(let s=0;s<e.length-1;s+=2)if(\"string\"==typeof e[s]){const o=e[s+1],a=\"function\"==typeof o?o(t):ct(t[o]),l=i[r=e[s+2]],c=e[s+3];\"boolean\"==typeof c?a.removeEventListener(e[s],l,c):c>=0?i[r=c]():i[r=-c].unsubscribe(),s+=2}else{const o=i[r=e[s+1]];e[s].call(o)}if(null!==i){for(let s=r+1;s<i.length;s++)i[s]();t[7]=null}}(n,t),1===t[1].type&&et(t[11])&&t[11].destroy();const e=t[17];if(null!==e&&Vn(t[3])){e!==t[3]&&Kv(e,t);const i=t[19];null!==i&&i.detachView(n)}}}function Xv(n,t,e){return function Jv(n,t,e){let i=t;for(;null!==i&&40&i.type;)i=(t=i).parent;if(null===i)return e[0];if(2&i.flags){const r=n.data[i.directiveStart].encapsulation;if(r===Ln.None||r===Ln.Emulated)return null}return yn(i,e)}(n,t.parent,e)}function xr(n,t,e,i,r){et(n)?n.insertBefore(t,e,i,r):t.insertBefore(e,i,r)}function ey(n,t,e){et(n)?n.appendChild(t,e):t.appendChild(e)}function ty(n,t,e,i,r){null!==i?xr(n,t,e,i,r):ey(n,t,e)}function Kl(n,t){return et(n)?n.parentNode(t):t.parentNode}function ny(n,t,e){return ry(n,t,e)}let ry=function iy(n,t,e){return 40&n.type?yn(n,e):null};function Zl(n,t,e,i){const r=Xv(n,i,t),s=t[11],a=ny(i.parent||t[6],i,t);if(null!=r)if(Array.isArray(e))for(let l=0;l<e.length;l++)ty(s,r,e[l],a,!1);else ty(s,r,e,a,!1)}function Xl(n,t){if(null!==t){const e=t.type;if(3&e)return yn(t,n);if(4&e)return kh(-1,n[t.index]);if(8&e){const i=t.child;if(null!==i)return Xl(n,i);{const r=n[t.index];return Vn(r)?kh(-1,r):ct(r)}}if(32&e)return bh(t,n)()||ct(n[t.index]);{const i=oy(n,t);return null!==i?Array.isArray(i)?i[0]:Xl(Ko(n[16]),i):Xl(n,t.next)}}return null}function oy(n,t){return null!==t?n[16][6].projection[t.projection]:null}function kh(n,t){const e=10+n+1;if(e<t.length){const i=t[e],r=i[1].firstChild;if(null!==r)return Xl(i,r)}return t[7]}function Th(n,t,e,i,r,s,o){for(;null!=e;){const a=i[e.index],l=e.type;if(o&&0===t&&(a&&Ft(ct(a),i),e.flags|=4),64!=(64&e.flags))if(8&l)Th(n,t,e.child,i,r,s,!1),Ms(t,n,r,a,s);else if(32&l){const c=bh(e,i);let d;for(;d=c();)Ms(t,n,r,d,s);Ms(t,n,r,a,s)}else 16&l?ly(n,t,i,e,r,s):Ms(t,n,r,a,s);e=o?e.projectionNext:e.next}}function Zo(n,t,e,i,r,s){Th(e,i,n.firstChild,t,r,s,!1)}function ly(n,t,e,i,r,s){const o=e[16],l=o[6].projection[i.projection];if(Array.isArray(l))for(let c=0;c<l.length;c++)Ms(t,n,r,l[c],s);else Th(n,t,l,o[3],r,s,!0)}function cy(n,t,e){et(n)?n.setAttribute(t,\"style\",e):t.style.cssText=e}function Ah(n,t,e){et(n)?\"\"===e?n.removeAttribute(t,\"class\"):n.setAttribute(t,\"class\",e):t.className=e}function dy(n,t,e){let i=n.length;for(;;){const r=n.indexOf(t,e);if(-1===r)return r;if(0===r||n.charCodeAt(r-1)<=32){const s=t.length;if(r+s===i||n.charCodeAt(r+s)<=32)return r}e=r+1}}const uy=\"ng-template\";function VI(n,t,e){let i=0;for(;i<n.length;){let r=n[i++];if(e&&\"class\"===r){if(r=n[i],-1!==dy(r.toLowerCase(),t,0))return!0}else if(1===r){for(;i<n.length&&\"string\"==typeof(r=n[i++]);)if(r.toLowerCase()===t)return!0;return!1}}return!1}function hy(n){return 4===n.type&&n.value!==uy}function HI(n,t,e){return t===(4!==n.type||e?n.value:uy)}function jI(n,t,e){let i=4;const r=n.attrs||[],s=function $I(n){for(let t=0;t<n.length;t++)if(ev(n[t]))return t;return n.length}(r);let o=!1;for(let a=0;a<t.length;a++){const l=t[a];if(\"number\"!=typeof l){if(!o)if(4&i){if(i=2|1&i,\"\"!==l&&!HI(n,l,e)||\"\"===l&&1===t.length){if(jn(i))return!1;o=!0}}else{const c=8&i?l:t[++a];if(8&i&&null!==n.attrs){if(!VI(n.attrs,c,e)){if(jn(i))return!1;o=!0}continue}const u=zI(8&i?\"class\":l,r,hy(n),e);if(-1===u){if(jn(i))return!1;o=!0;continue}if(\"\"!==c){let h;h=u>s?\"\":r[u+1].toLowerCase();const p=8&i?h:null;if(p&&-1!==dy(p,c,0)||2&i&&c!==h){if(jn(i))return!1;o=!0}}}}else{if(!o&&!jn(i)&&!jn(l))return!1;if(o&&jn(l))continue;o=!1,i=l|1&i}}return jn(i)||o}function jn(n){return 0==(1&n)}function zI(n,t,e,i){if(null===t)return-1;let r=0;if(i||!e){let s=!1;for(;r<t.length;){const o=t[r];if(o===n)return r;if(3===o||6===o)s=!0;else{if(1===o||2===o){let a=t[++r];for(;\"string\"==typeof a;)a=t[++r];continue}if(4===o)break;if(0===o){r+=4;continue}}r+=s?1:2}return-1}return function GI(n,t){let e=n.indexOf(4);if(e>-1)for(e++;e<n.length;){const i=n[e];if(\"number\"==typeof i)return-1;if(i===t)return e;e++}return-1}(t,n)}function py(n,t,e=!1){for(let i=0;i<t.length;i++)if(jI(n,t[i],e))return!0;return!1}function WI(n,t){e:for(let e=0;e<t.length;e++){const i=t[e];if(n.length===i.length){for(let r=0;r<n.length;r++)if(n[r]!==i[r])continue e;return!0}}return!1}function fy(n,t){return n?\":not(\"+t.trim()+\")\":t}function qI(n){let t=n[0],e=1,i=2,r=\"\",s=!1;for(;e<n.length;){let o=n[e];if(\"string\"==typeof o)if(2&i){const a=n[++e];r+=\"[\"+o+(a.length>0?'=\"'+a+'\"':\"\")+\"]\"}else 8&i?r+=\".\"+o:4&i&&(r+=\" \"+o);else\"\"!==r&&!jn(o)&&(t+=fy(s,r),r=\"\"),i=o,s=s||!jn(i);e++}return\"\"!==r&&(t+=fy(s,r)),t}const se={};function T(n){my(Me(),w(),jt()+n,Tl())}function my(n,t,e,i){if(!i)if(3==(3&t[2])){const s=n.preOrderCheckHooks;null!==s&&Pl(t,s,e)}else{const s=n.preOrderHooks;null!==s&&Fl(t,s,0,e)}Zi(e)}function Jl(n,t){return n<<17|t<<2}function zn(n){return n>>17&32767}function Ih(n){return 2|n}function Ti(n){return(131068&n)>>2}function Rh(n,t){return-131069&n|t<<2}function Oh(n){return 1|n}function Ey(n,t){const e=n.contentQueries;if(null!==e)for(let i=0;i<e.length;i+=2){const r=e[i],s=e[i+1];if(-1!==s){const o=n.data[s];qu(r),o.contentQueries(2,t[s],s)}}}function Xo(n,t,e,i,r,s,o,a,l,c){const d=t.blueprint.slice();return d[0]=r,d[2]=140|i,j_(d),d[3]=d[15]=n,d[8]=e,d[10]=o||n&&n[10],d[11]=a||n&&n[11],d[12]=l||n&&n[12]||null,d[9]=c||n&&n[9]||null,d[6]=s,d[16]=2==t.type?n[16]:d,d}function xs(n,t,e,i,r){let s=n.data[t];if(null===s)s=function zh(n,t,e,i,r){const s=U_(),o=Uu(),l=n.data[t]=function uR(n,t,e,i,r,s){return{type:e,index:i,insertBeforeIndex:null,injectorIndex:t?t.injectorIndex:-1,directiveStart:-1,directiveEnd:-1,directiveStylingLast:-1,propertyBindings:null,flags:0,providerIndexes:0,value:r,attrs:s,mergedAttrs:null,localNames:null,initialInputs:void 0,inputs:null,outputs:null,tViews:null,next:null,projectionNext:null,child:null,parent:t,projection:null,styles:null,stylesWithoutHost:null,residualStyles:void 0,classes:null,classesWithoutHost:null,residualClasses:void 0,classBindings:0,styleBindings:0}}(0,o?s:s&&s.parent,e,t,i,r);return null===n.firstChild&&(n.firstChild=l),null!==s&&(o?null==s.child&&null!==l.parent&&(s.child=l):null===s.next&&(s.next=l)),l}(n,t,e,i,r),function OT(){return te.lFrame.inI18n}()&&(s.flags|=64);else if(64&s.type){s.type=e,s.value=i,s.attrs=r;const o=function Ro(){const n=te.lFrame,t=n.currentTNode;return n.isParent?t:t.parent}();s.injectorIndex=null===o?-1:o.injectorIndex}return oi(s,!0),s}function Es(n,t,e,i){if(0===e)return-1;const r=t.length;for(let s=0;s<e;s++)t.push(i),n.blueprint.push(i),n.data.push(null);return r}function Jo(n,t,e){Il(t);try{const i=n.viewQuery;null!==i&&Zh(1,i,e);const r=n.template;null!==r&&Sy(n,t,r,1,e),n.firstCreatePass&&(n.firstCreatePass=!1),n.staticContentQueries&&Ey(n,t),n.staticViewQueries&&Zh(2,n.viewQuery,e);const s=n.components;null!==s&&function lR(n,t){for(let e=0;e<t.length;e++)TR(n,t[e])}(t,s)}catch(i){throw n.firstCreatePass&&(n.incompleteFirstPass=!0,n.firstCreatePass=!1),i}finally{t[2]&=-5,Rl()}}function Ss(n,t,e,i){const r=t[2];if(256==(256&r))return;Il(t);const s=Tl();try{j_(t),function $_(n){return te.lFrame.bindingIndex=n}(n.bindingStartIndex),null!==e&&Sy(n,t,e,2,i);const o=3==(3&r);if(!s)if(o){const c=n.preOrderCheckHooks;null!==c&&Pl(t,c,null)}else{const c=n.preOrderHooks;null!==c&&Fl(t,c,0,null),Yu(t,0)}if(function SR(n){for(let t=Ch(n);null!==t;t=Dh(t)){if(!t[2])continue;const e=t[9];for(let i=0;i<e.length;i++){const r=e[i],s=r[3];0==(1024&r[2])&&zu(s,1),r[2]|=1024}}}(t),function ER(n){for(let t=Ch(n);null!==t;t=Dh(t))for(let e=10;e<t.length;e++){const i=t[e],r=i[1];ju(i)&&Ss(r,i,r.template,i[8])}}(t),null!==n.contentQueries&&Ey(n,t),!s)if(o){const c=n.contentCheckHooks;null!==c&&Pl(t,c)}else{const c=n.contentHooks;null!==c&&Fl(t,c,1),Yu(t,1)}!function oR(n,t){const e=n.hostBindingOpCodes;if(null!==e)try{for(let i=0;i<e.length;i++){const r=e[i];if(r<0)Zi(~r);else{const s=r,o=e[++i],a=e[++i];PT(o,s),a(2,t[s])}}}finally{Zi(-1)}}(n,t);const a=n.components;null!==a&&function aR(n,t){for(let e=0;e<t.length;e++)kR(n,t[e])}(t,a);const l=n.viewQuery;if(null!==l&&Zh(2,l,i),!s)if(o){const c=n.viewCheckHooks;null!==c&&Pl(t,c)}else{const c=n.viewHooks;null!==c&&Fl(t,c,2),Yu(t,2)}!0===n.firstUpdatePass&&(n.firstUpdatePass=!1),s||(t[2]&=-73),1024&t[2]&&(t[2]&=-1025,zu(t[3],-1))}finally{Rl()}}function cR(n,t,e,i){const r=t[10],s=!Tl(),o=H_(t);try{s&&!o&&r.begin&&r.begin(),o&&Jo(n,t,i),Ss(n,t,e,i)}finally{s&&!o&&r.end&&r.end()}}function Sy(n,t,e,i,r){const s=jt(),o=2&i;try{Zi(-1),o&&t.length>20&&my(n,t,20,Tl()),e(i,r)}finally{Zi(s)}}function ky(n,t,e){if(Ou(t)){const r=t.directiveEnd;for(let s=t.directiveStart;s<r;s++){const o=n.data[s];o.contentQueries&&o.contentQueries(1,e[s],s)}}}function Uh(n,t,e){!z_()||(function vR(n,t,e,i){const r=e.directiveStart,s=e.directiveEnd;n.firstCreatePass||No(e,t),Ft(i,t);const o=e.initialInputs;for(let a=r;a<s;a++){const l=n.data[a],c=Hn(l);c&&wR(t,e,l);const d=Lo(t,n,a,e);Ft(d,t),null!==o&&MR(0,a-r,d,l,0,o),c&&(rn(e.index,t)[8]=d)}}(n,t,e,yn(e,t)),128==(128&e.flags)&&function yR(n,t,e){const i=e.directiveStart,r=e.directiveEnd,o=e.index,a=function FT(){return te.lFrame.currentDirectiveIndex}();try{Zi(o);for(let l=i;l<r;l++){const c=n.data[l],d=t[l];Gu(l),(null!==c.hostBindings||0!==c.hostVars||null!==c.hostAttrs)&&Ny(c,d)}}finally{Zi(-1),Gu(a)}}(n,t,e))}function $h(n,t,e=yn){const i=t.localNames;if(null!==i){let r=t.index+1;for(let s=0;s<i.length;s+=2){const o=i[s+1],a=-1===o?e(t,n):n[o];n[r++]=a}}}function Ty(n){const t=n.tView;return null===t||t.incompleteFirstPass?n.tView=nc(1,null,n.template,n.decls,n.vars,n.directiveDefs,n.pipeDefs,n.viewQuery,n.schemas,n.consts):t}function nc(n,t,e,i,r,s,o,a,l,c){const d=20+i,u=d+r,h=function dR(n,t){const e=[];for(let i=0;i<t;i++)e.push(i<n?null:se);return e}(d,u),p=\"function\"==typeof c?c():c;return h[1]={type:n,blueprint:h,template:e,queries:null,viewQuery:a,declTNode:t,data:h.slice().fill(null,d),bindingStartIndex:d,expandoStartIndex:u,hostBindingOpCodes:null,firstCreatePass:!0,firstUpdatePass:!0,staticViewQueries:!1,staticContentQueries:!1,preOrderHooks:null,preOrderCheckHooks:null,contentHooks:null,contentCheckHooks:null,viewHooks:null,viewCheckHooks:null,destroyHooks:null,cleanup:null,contentQueries:null,components:null,directiveRegistry:\"function\"==typeof s?s():s,pipeRegistry:\"function\"==typeof o?o():o,firstChild:null,schemas:l,consts:p,incompleteFirstPass:!1}}function Ry(n,t,e,i){const r=zy(t);null===e?r.push(i):(r.push(e),n.firstCreatePass&&Uy(n).push(i,r.length-1))}function Oy(n,t,e){for(let i in n)if(n.hasOwnProperty(i)){const r=n[i];(e=null===e?{}:e).hasOwnProperty(i)?e[i].push(t,r):e[i]=[t,r]}return e}function ln(n,t,e,i,r,s,o,a){const l=yn(t,e);let d,c=t.inputs;!a&&null!=c&&(d=c[i])?(Wy(n,e,d,i,r),El(t)&&function fR(n,t){const e=rn(t,n);16&e[2]||(e[2]|=64)}(e,t.index)):3&t.type&&(i=function pR(n){return\"class\"===n?\"className\":\"for\"===n?\"htmlFor\":\"formaction\"===n?\"formAction\":\"innerHtml\"===n?\"innerHTML\":\"readonly\"===n?\"readOnly\":\"tabindex\"===n?\"tabIndex\":n}(i),r=null!=o?o(r,t.value||\"\",i):r,et(s)?s.setProperty(l,i,r):Ku(i)||(l.setProperty?l.setProperty(i,r):l[i]=r))}function Gh(n,t,e,i){let r=!1;if(z_()){const s=function bR(n,t,e){const i=n.directiveRegistry;let r=null;if(i)for(let s=0;s<i.length;s++){const o=i[s];py(e,o.selectors,!1)&&(r||(r=[]),Hl(No(e,t),n,o.type),Hn(o)?(Ly(n,e),r.unshift(o)):r.push(o))}return r}(n,t,e),o=null===i?null:{\"\":-1};if(null!==s){r=!0,By(e,n.data.length,s.length);for(let d=0;d<s.length;d++){const u=s[d];u.providersResolver&&u.providersResolver(u)}let a=!1,l=!1,c=Es(n,t,s.length,null);for(let d=0;d<s.length;d++){const u=s[d];e.mergedAttrs=Ll(e.mergedAttrs,u.hostAttrs),Vy(n,e,t,c,u),DR(c,u,o),null!==u.contentQueries&&(e.flags|=8),(null!==u.hostBindings||null!==u.hostAttrs||0!==u.hostVars)&&(e.flags|=128);const h=u.type.prototype;!a&&(h.ngOnChanges||h.ngOnInit||h.ngDoCheck)&&((n.preOrderHooks||(n.preOrderHooks=[])).push(e.index),a=!0),!l&&(h.ngOnChanges||h.ngDoCheck)&&((n.preOrderCheckHooks||(n.preOrderCheckHooks=[])).push(e.index),l=!0),c++}!function hR(n,t){const i=t.directiveEnd,r=n.data,s=t.attrs,o=[];let a=null,l=null;for(let c=t.directiveStart;c<i;c++){const d=r[c],u=d.inputs,h=null===s||hy(t)?null:xR(u,s);o.push(h),a=Oy(u,c,a),l=Oy(d.outputs,c,l)}null!==a&&(a.hasOwnProperty(\"class\")&&(t.flags|=16),a.hasOwnProperty(\"style\")&&(t.flags|=32)),t.initialInputs=o,t.inputs=a,t.outputs=l}(n,e)}o&&function CR(n,t,e){if(t){const i=n.localNames=[];for(let r=0;r<t.length;r+=2){const s=e[t[r+1]];if(null==s)throw new H(-301,!1);i.push(t[r],s)}}}(e,i,o)}return e.mergedAttrs=Ll(e.mergedAttrs,e.attrs),r}function Fy(n,t,e,i,r,s){const o=s.hostBindings;if(o){let a=n.hostBindingOpCodes;null===a&&(a=n.hostBindingOpCodes=[]);const l=~t.index;(function _R(n){let t=n.length;for(;t>0;){const e=n[--t];if(\"number\"==typeof e&&e<0)return e}return 0})(a)!=l&&a.push(l),a.push(i,r,o)}}function Ny(n,t){null!==n.hostBindings&&n.hostBindings(1,t)}function Ly(n,t){t.flags|=2,(n.components||(n.components=[])).push(t.index)}function DR(n,t,e){if(e){if(t.exportAs)for(let i=0;i<t.exportAs.length;i++)e[t.exportAs[i]]=n;Hn(t)&&(e[\"\"]=n)}}function By(n,t,e){n.flags|=1,n.directiveStart=t,n.directiveEnd=t+e,n.providerIndexes=t}function Vy(n,t,e,i,r){n.data[i]=r;const s=r.factory||(r.factory=Cr(r.type)),o=new Po(s,Hn(r),null);n.blueprint[i]=o,e[i]=o,Fy(n,t,0,i,Es(n,e,r.hostVars,se),r)}function wR(n,t,e){const i=yn(t,n),r=Ty(e),s=n[10],o=ic(n,Xo(n,r,null,e.onPush?64:16,i,t,s,s.createRenderer(i,e),null,null));n[t.index]=o}function ui(n,t,e,i,r,s){const o=yn(n,t);!function Wh(n,t,e,i,r,s,o){if(null==s)et(n)?n.removeAttribute(t,r,e):t.removeAttribute(r);else{const a=null==o?re(s):o(s,i||\"\",r);et(n)?n.setAttribute(t,r,a,e):e?t.setAttributeNS(e,r,a):t.setAttribute(r,a)}}(t[11],o,s,n.value,e,i,r)}function MR(n,t,e,i,r,s){const o=s[t];if(null!==o){const a=i.setInput;for(let l=0;l<o.length;){const c=o[l++],d=o[l++],u=o[l++];null!==a?i.setInput(e,u,c,d):e[d]=u}}}function xR(n,t){let e=null,i=0;for(;i<t.length;){const r=t[i];if(0!==r)if(5!==r){if(\"number\"==typeof r)break;n.hasOwnProperty(r)&&(null===e&&(e=[]),e.push(r,n[r],t[i+1])),i+=2}else i+=2;else i+=4}return e}function Hy(n,t,e,i){return new Array(n,!0,!1,t,null,0,i,e,null,null)}function kR(n,t){const e=rn(t,n);if(ju(e)){const i=e[1];80&e[2]?Ss(i,e,i.template,e[8]):e[5]>0&&qh(e)}}function qh(n){for(let i=Ch(n);null!==i;i=Dh(i))for(let r=10;r<i.length;r++){const s=i[r];if(1024&s[2]){const o=s[1];Ss(o,s,o.template,s[8])}else s[5]>0&&qh(s)}const e=n[1].components;if(null!==e)for(let i=0;i<e.length;i++){const r=rn(e[i],n);ju(r)&&r[5]>0&&qh(r)}}function TR(n,t){const e=rn(t,n),i=e[1];(function AR(n,t){for(let e=t.length;e<n.blueprint.length;e++)t.push(n.blueprint[e])})(i,e),Jo(i,e,e[8])}function ic(n,t){return n[13]?n[14][4]=t:n[13]=t,n[14]=t,t}function Yh(n){for(;n;){n[2]|=64;const t=Ko(n);if(uT(n)&&!t)return n;n=t}return null}function Kh(n,t,e){const i=t[10];i.begin&&i.begin();try{Ss(n,t,n.template,e)}catch(r){throw Gy(t,r),r}finally{i.end&&i.end()}}function jy(n){!function Qh(n){for(let t=0;t<n.components.length;t++){const e=n.components[t],i=gh(e),r=i[1];cR(r,i,r.template,e)}}(n[8])}function Zh(n,t,e){qu(0),t(n,e)}const PR=(()=>Promise.resolve(null))();function zy(n){return n[7]||(n[7]=[])}function Uy(n){return n.cleanup||(n.cleanup=[])}function $y(n,t,e){return(null===n||Hn(n))&&(e=function MT(n){for(;Array.isArray(n);){if(\"object\"==typeof n[1])return n;n=n[0]}return null}(e[t.index])),e[11]}function Gy(n,t){const e=n[9],i=e?e.get(Mr,null):null;i&&i.handleError(t)}function Wy(n,t,e,i,r){for(let s=0;s<e.length;){const o=e[s++],a=e[s++],l=t[o],c=n.data[o];null!==c.setInput?c.setInput(l,r,i,a):l[a]=r}}function Ai(n,t,e){const i=kl(t,n);!function Qv(n,t,e){et(n)?n.setValue(t,e):t.textContent=e}(n[11],i,e)}function rc(n,t,e){let i=e?n.styles:null,r=e?n.classes:null,s=0;if(null!==t)for(let o=0;o<t.length;o++){const a=t[o];\"number\"==typeof a?s=a:1==s?r=Mu(r,a):2==s&&(i=Mu(i,a+\": \"+t[++o]+\";\"))}e?n.styles=i:n.stylesWithoutHost=i,e?n.classes=r:n.classesWithoutHost=r}const Xh=new b(\"INJECTOR\",-1);class qy{get(t,e=jo){if(e===jo){const i=new Error(`NullInjectorError: No provider for ${Re(t)}!`);throw i.name=\"NullInjectorError\",i}return e}}const Jh=new b(\"Set Injector scope.\"),ea={},LR={};let ep;function Yy(){return void 0===ep&&(ep=new qy),ep}function Qy(n,t=null,e=null,i){const r=Ky(n,t,e,i);return r._resolveInjectorDefTypes(),r}function Ky(n,t=null,e=null,i){return new BR(n,e,t||Yy(),i)}class BR{constructor(t,e,i,r=null){this.parent=i,this.records=new Map,this.injectorDefTypes=new Set,this.onDestroy=new Set,this._destroyed=!1;const s=[];e&&ai(e,a=>this.processProvider(a,t,e)),ai([t],a=>this.processInjectorType(a,[],s)),this.records.set(Xh,ks(void 0,this));const o=this.records.get(Jh);this.scope=null!=o?o.value:null,this.source=r||(\"object\"==typeof t?null:Re(t))}get destroyed(){return this._destroyed}destroy(){this.assertNotDestroyed(),this._destroyed=!0;try{this.onDestroy.forEach(t=>t.ngOnDestroy())}finally{this.records.clear(),this.onDestroy.clear(),this.injectorDefTypes.clear()}}get(t,e=jo,i=ee.Default){this.assertNotDestroyed();const r=vv(this),s=qi(void 0);try{if(!(i&ee.SkipSelf)){let a=this.records.get(t);if(void 0===a){const l=function WR(n){return\"function\"==typeof n||\"object\"==typeof n&&n instanceof b}(t)&&Eu(t);a=l&&this.injectableDefInScope(l)?ks(tp(t),ea):null,this.records.set(t,a)}if(null!=a)return this.hydrate(t,a)}return(i&ee.Self?Yy():this.parent).get(t,e=i&ee.Optional&&e===jo?null:e)}catch(o){if(\"NullInjectorError\"===o.name){if((o[$l]=o[$l]||[]).unshift(Re(t)),r)throw o;return function _A(n,t,e,i){const r=n[$l];throw t[_v]&&r.unshift(t[_v]),n.message=function vA(n,t,e,i=null){n=n&&\"\\n\"===n.charAt(0)&&\"\\u0275\"==n.charAt(1)?n.substr(2):n;let r=Re(t);if(Array.isArray(t))r=t.map(Re).join(\" -> \");else if(\"object\"==typeof t){let s=[];for(let o in t)if(t.hasOwnProperty(o)){let a=t[o];s.push(o+\":\"+(\"string\"==typeof a?JSON.stringify(a):Re(a)))}r=`{${s.join(\", \")}}`}return`${e}${i?\"(\"+i+\")\":\"\"}[${r}]: ${n.replace(hA,\"\\n \")}`}(\"\\n\"+n.message,r,e,i),n.ngTokenPath=r,n[$l]=null,n}(o,t,\"R3InjectorError\",this.source)}throw o}finally{qi(s),vv(r)}}_resolveInjectorDefTypes(){this.injectorDefTypes.forEach(t=>this.get(t))}toString(){const t=[];return this.records.forEach((i,r)=>t.push(Re(r))),`R3Injector[${t.join(\", \")}]`}assertNotDestroyed(){if(this._destroyed)throw new H(205,!1)}processInjectorType(t,e,i){if(!(t=le(t)))return!1;let r=S_(t);const s=null==r&&t.ngModule||void 0,o=void 0===s?t:s,a=-1!==i.indexOf(o);if(void 0!==s&&(r=S_(s)),null==r)return!1;if(null!=r.imports&&!a){let d;i.push(o);try{ai(r.imports,u=>{this.processInjectorType(u,e,i)&&(void 0===d&&(d=[]),d.push(u))})}finally{}if(void 0!==d)for(let u=0;u<d.length;u++){const{ngModule:h,providers:p}=d[u];ai(p,m=>this.processProvider(m,h,p||Ne))}}this.injectorDefTypes.add(o);const l=Cr(o)||(()=>new o);this.records.set(o,ks(l,ea));const c=r.providers;if(null!=c&&!a){const d=t;ai(c,u=>this.processProvider(u,d,c))}return void 0!==s&&void 0!==t.providers}processProvider(t,e,i){let r=Ts(t=le(t))?t:le(t&&t.provide);const s=function HR(n,t,e){return Xy(n)?ks(void 0,n.useValue):ks(Zy(n),ea)}(t);if(Ts(t)||!0!==t.multi)this.records.get(r);else{let o=this.records.get(r);o||(o=ks(void 0,ea,!0),o.factory=()=>oh(o.multi),this.records.set(r,o)),r=t,o.multi.push(t)}this.records.set(r,s)}hydrate(t,e){return e.value===ea&&(e.value=LR,e.value=e.factory()),\"object\"==typeof e.value&&e.value&&function GR(n){return null!==n&&\"object\"==typeof n&&\"function\"==typeof n.ngOnDestroy}(e.value)&&this.onDestroy.add(e.value),e.value}injectableDefInScope(t){if(!t.providedIn)return!1;const e=le(t.providedIn);return\"string\"==typeof e?\"any\"===e||e===this.scope:this.injectorDefTypes.has(e)}}function tp(n){const t=Eu(n),e=null!==t?t.factory:Cr(n);if(null!==e)return e;if(n instanceof b)throw new H(204,!1);if(n instanceof Function)return function VR(n){const t=n.length;if(t>0)throw Ho(t,\"?\"),new H(204,!1);const e=function Xk(n){const t=n&&(n[Cl]||n[k_]);if(t){const e=function Jk(n){if(n.hasOwnProperty(\"name\"))return n.name;const t=(\"\"+n).match(/^function\\s*([^\\s(]+)/);return null===t?\"\":t[1]}(n);return console.warn(`DEPRECATED: DI is instantiating a token \"${e}\" that inherits its @Injectable decorator but does not provide one itself.\\nThis will become an error in a future version of Angular. Please add @Injectable() to the \"${e}\" class.`),t}return null}(n);return null!==e?()=>e.factory(n):()=>new n}(n);throw new H(204,!1)}function Zy(n,t,e){let i;if(Ts(n)){const r=le(n);return Cr(r)||tp(r)}if(Xy(n))i=()=>le(n.useValue);else if(function zR(n){return!(!n||!n.useFactory)}(n))i=()=>n.useFactory(...oh(n.deps||[]));else if(function jR(n){return!(!n||!n.useExisting)}(n))i=()=>y(le(n.useExisting));else{const r=le(n&&(n.useClass||n.provide));if(!function $R(n){return!!n.deps}(n))return Cr(r)||tp(r);i=()=>new r(...oh(n.deps))}return i}function ks(n,t,e=!1){return{factory:n,value:t,multi:e?[]:void 0}}function Xy(n){return null!==n&&\"object\"==typeof n&&fA in n}function Ts(n){return\"function\"==typeof n}let dt=(()=>{class n{static create(e,i){var r;if(Array.isArray(e))return Qy({name:\"\"},i,e,\"\");{const s=null!==(r=e.name)&&void 0!==r?r:\"\";return Qy({name:s},e.parent,e.providers,s)}}}return n.THROW_IF_NOT_FOUND=jo,n.NULL=new qy,n.\\u0275prov=k({token:n,providedIn:\"any\",factory:()=>y(Xh)}),n.__NG_ELEMENT_ID__=-1,n})();function e1(n,t){Ol(gh(n)[1],gt())}function E(n){let t=function db(n){return Object.getPrototypeOf(n.prototype).constructor}(n.type),e=!0;const i=[n];for(;t;){let r;if(Hn(n))r=t.\\u0275cmp||t.\\u0275dir;else{if(t.\\u0275cmp)throw new H(903,\"\");r=t.\\u0275dir}if(r){if(e){i.push(r);const o=n;o.inputs=rp(n.inputs),o.declaredInputs=rp(n.declaredInputs),o.outputs=rp(n.outputs);const a=r.hostBindings;a&&s1(n,a);const l=r.viewQuery,c=r.contentQueries;if(l&&n1(n,l),c&&r1(n,c),wu(n.inputs,r.inputs),wu(n.declaredInputs,r.declaredInputs),wu(n.outputs,r.outputs),Hn(r)&&r.data.animation){const d=n.data;d.animation=(d.animation||[]).concat(r.data.animation)}}const s=r.features;if(s)for(let o=0;o<s.length;o++){const a=s[o];a&&a.ngInherit&&a(n),a===E&&(e=!1)}}t=Object.getPrototypeOf(t)}!function t1(n){let t=0,e=null;for(let i=n.length-1;i>=0;i--){const r=n[i];r.hostVars=t+=r.hostVars,r.hostAttrs=Ll(r.hostAttrs,e=Ll(e,r.hostAttrs))}}(i)}function rp(n){return n===os?{}:n===Ne?[]:n}function n1(n,t){const e=n.viewQuery;n.viewQuery=e?(i,r)=>{t(i,r),e(i,r)}:t}function r1(n,t){const e=n.contentQueries;n.contentQueries=e?(i,r,s)=>{t(i,r,s),e(i,r,s)}:t}function s1(n,t){const e=n.hostBindings;n.hostBindings=e?(i,r)=>{t(i,r),e(i,r)}:t}let sc=null;function As(){if(!sc){const n=Oe.Symbol;if(n&&n.iterator)sc=n.iterator;else{const t=Object.getOwnPropertyNames(Map.prototype);for(let e=0;e<t.length;++e){const i=t[e];\"entries\"!==i&&\"size\"!==i&&Map.prototype[i]===Map.prototype.entries&&(sc=i)}}}return sc}function ta(n){return!!sp(n)&&(Array.isArray(n)||!(n instanceof Map)&&As()in n)}function sp(n){return null!==n&&(\"function\"==typeof n||\"object\"==typeof n)}function Nt(n,t,e){return!Object.is(n[t],e)&&(n[t]=e,!0)}function Z(n,t,e,i){const r=w();return Nt(r,hs(),t)&&(Me(),ui(tt(),r,n,t,e,i)),Z}function Rs(n,t,e,i){return Nt(n,hs(),e)?t+re(e)+i:se}function Ee(n,t,e,i,r,s,o,a){const l=w(),c=Me(),d=n+20,u=c.firstCreatePass?function h1(n,t,e,i,r,s,o,a,l){const c=t.consts,d=xs(t,n,4,o||null,Ki(c,a));Gh(t,e,d,Ki(c,l)),Ol(t,d);const u=d.tViews=nc(2,d,i,r,s,t.directiveRegistry,t.pipeRegistry,null,t.schemas,c);return null!==t.queries&&(t.queries.template(t,d),u.queries=t.queries.embeddedTView(d)),d}(d,c,l,t,e,i,r,s,o):c.data[d];oi(u,!1);const h=l[11].createComment(\"\");Zl(c,l,h,u),Ft(h,l),ic(l,l[d]=Hy(h,l,h,u)),Sl(u)&&Uh(c,l,u),null!=o&&$h(l,u,a)}function wn(n){return function us(n,t){return n[t]}(function RT(){return te.lFrame.contextLView}(),20+n)}function f(n,t=ee.Default){const e=w();return null===e?y(n,t):av(gt(),e,le(n),t)}function Sr(){throw new Error(\"invalid\")}function N(n,t,e){const i=w();return Nt(i,hs(),t)&&ln(Me(),tt(),i,n,t,i[11],e,!1),N}function dp(n,t,e,i,r){const o=r?\"class\":\"style\";Wy(n,e,t.inputs[o],o,i)}function x(n,t,e,i){const r=w(),s=Me(),o=20+n,a=r[11],l=r[o]=Mh(a,t,function jT(){return te.lFrame.currentNamespace}()),c=s.firstCreatePass?function O1(n,t,e,i,r,s,o){const a=t.consts,c=xs(t,n,2,r,Ki(a,s));return Gh(t,e,c,Ki(a,o)),null!==c.attrs&&rc(c,c.attrs,!1),null!==c.mergedAttrs&&rc(c,c.mergedAttrs,!0),null!==t.queries&&t.queries.elementStart(t,c),c}(o,s,r,0,t,e,i):s.data[o];oi(c,!0);const d=c.mergedAttrs;null!==d&&Nl(a,l,d);const u=c.classes;null!==u&&Ah(a,l,u);const h=c.styles;return null!==h&&cy(a,l,h),64!=(64&c.flags)&&Zl(s,r,l,c),0===function ST(){return te.lFrame.elementDepthCount}()&&Ft(l,r),function kT(){te.lFrame.elementDepthCount++}(),Sl(c)&&(Uh(s,r,c),ky(s,c,r)),null!==i&&$h(r,c),x}function S(){let n=gt();Uu()?$u():(n=n.parent,oi(n,!1));const t=n;!function TT(){te.lFrame.elementDepthCount--}();const e=Me();return e.firstCreatePass&&(Ol(e,n),Ou(n)&&e.queries.elementEnd(n)),null!=t.classesWithoutHost&&function WT(n){return 0!=(16&n.flags)}(t)&&dp(e,t,w(),t.classesWithoutHost,!0),null!=t.stylesWithoutHost&&function qT(n){return 0!=(32&n.flags)}(t)&&dp(e,t,w(),t.stylesWithoutHost,!1),S}function Le(n,t,e,i){return x(n,t,e,i),S(),Le}function kr(n,t,e){const i=w(),r=Me(),s=n+20,o=r.firstCreatePass?function P1(n,t,e,i,r){const s=t.consts,o=Ki(s,i),a=xs(t,n,8,\"ng-container\",o);return null!==o&&rc(a,o,!0),Gh(t,e,a,Ki(s,r)),null!==t.queries&&t.queries.elementStart(t,a),a}(s,r,i,t,e):r.data[s];oi(o,!0);const a=i[s]=i[11].createComment(\"\");return Zl(r,i,a,o),Ft(a,i),Sl(o)&&(Uh(r,i,o),ky(r,o,i)),null!=e&&$h(i,o),kr}function Tr(){let n=gt();const t=Me();return Uu()?$u():(n=n.parent,oi(n,!1)),t.firstCreatePass&&(Ol(t,n),Ou(n)&&t.queries.elementEnd(n)),Tr}function ia(){return w()}function ra(n){return!!n&&\"function\"==typeof n.then}const up=function Ab(n){return!!n&&\"function\"==typeof n.subscribe};function J(n,t,e,i){const r=w(),s=Me(),o=gt();return Ib(s,r,r[11],o,n,t,!!e,i),J}function hp(n,t){const e=gt(),i=w(),r=Me();return Ib(r,i,$y(Wu(r.data),e,i),e,n,t,!1),hp}function Ib(n,t,e,i,r,s,o,a){const l=Sl(i),d=n.firstCreatePass&&Uy(n),u=t[8],h=zy(t);let p=!0;if(3&i.type||a){const _=yn(i,t),D=a?a(_):_,v=h.length,M=a?V=>a(ct(V[i.index])):i.index;if(et(e)){let V=null;if(!a&&l&&(V=function F1(n,t,e,i){const r=n.cleanup;if(null!=r)for(let s=0;s<r.length-1;s+=2){const o=r[s];if(o===e&&r[s+1]===i){const a=t[7],l=r[s+2];return a.length>l?a[l]:null}\"string\"==typeof o&&(s+=2)}return null}(n,t,r,i.index)),null!==V)(V.__ngLastListenerFn__||V).__ngNextListenerFn__=s,V.__ngLastListenerFn__=s,p=!1;else{s=pp(i,t,u,s,!1);const he=e.listen(D,r,s);h.push(s,he),d&&d.push(r,M,v,v+1)}}else s=pp(i,t,u,s,!0),D.addEventListener(r,s,o),h.push(s),d&&d.push(r,M,v,o)}else s=pp(i,t,u,s,!1);const m=i.outputs;let g;if(p&&null!==m&&(g=m[r])){const _=g.length;if(_)for(let D=0;D<_;D+=2){const We=t[g[D]][g[D+1]].subscribe(s),Ze=h.length;h.push(s,We),d&&d.push(r,i.index,Ze,-(Ze+1))}}}function Rb(n,t,e,i){try{return!1!==e(i)}catch(r){return Gy(n,r),!1}}function pp(n,t,e,i,r){return function s(o){if(o===Function)return i;const a=2&n.flags?rn(n.index,t):t;0==(32&t[2])&&Yh(a);let l=Rb(t,0,i,o),c=s.__ngNextListenerFn__;for(;c;)l=Rb(t,0,c,o)&&l,c=c.__ngNextListenerFn__;return r&&!1===l&&(o.preventDefault(),o.returnValue=!1),l}}function Be(n=1){return function LT(n){return(te.lFrame.contextLView=function BT(n,t){for(;n>0;)t=t[15],n--;return t}(n,te.lFrame.contextLView))[8]}(n)}function N1(n,t){let e=null;const i=function UI(n){const t=n.attrs;if(null!=t){const e=t.indexOf(5);if(0==(1&e))return t[e+1]}return null}(n);for(let r=0;r<t.length;r++){const s=t[r];if(\"*\"!==s){if(null===i?py(n,s,!0):WI(i,s))return r}else e=r}return e}function Lt(n){const t=w()[16][6];if(!t.projection){const i=t.projection=Ho(n?n.length:1,null),r=i.slice();let s=t.child;for(;null!==s;){const o=n?N1(s,n):0;null!==o&&(r[o]?r[o].projectionNext=s:i[o]=s,r[o]=s),s=s.next}}}function Pe(n,t=0,e){const i=w(),r=Me(),s=xs(r,20+n,16,null,e||null);null===s.projection&&(s.projection=t),$u(),64!=(64&s.flags)&&function NI(n,t,e){ly(t[11],0,t,e,Xv(n,e,t),ny(e.parent||t[6],e,t))}(r,i,s)}function zb(n,t,e,i,r){const s=n[e+1],o=null===t;let a=i?zn(s):Ti(s),l=!1;for(;0!==a&&(!1===l||o);){const d=n[a+1];V1(n[a],t)&&(l=!0,n[a+1]=i?Oh(d):Ih(d)),a=i?zn(d):Ti(d)}l&&(n[e+1]=i?Ih(s):Oh(s))}function V1(n,t){return null===n||null==t||(Array.isArray(n)?n[1]:n)===t||!(!Array.isArray(n)||\"string\"!=typeof t)&&bs(n,t)>=0}const vt={textEnd:0,key:0,keyEnd:0,value:0,valueEnd:0};function Ub(n){return n.substring(vt.key,vt.keyEnd)}function $b(n,t){const e=vt.textEnd;return e===t?-1:(t=vt.keyEnd=function U1(n,t,e){for(;t<e&&n.charCodeAt(t)>32;)t++;return t}(n,vt.key=t,e),js(n,t,e))}function js(n,t,e){for(;t<e&&n.charCodeAt(t)<=32;)t++;return t}function $n(n,t,e){return Gn(n,t,e,!1),$n}function Ae(n,t){return Gn(n,t,null,!0),Ae}function fi(n,t){for(let e=function j1(n){return function Wb(n){vt.key=0,vt.keyEnd=0,vt.value=0,vt.valueEnd=0,vt.textEnd=n.length}(n),$b(n,js(n,0,vt.textEnd))}(t);e>=0;e=$b(t,e))sn(n,Ub(t),!0)}function Gn(n,t,e,i){const r=w(),s=Me(),o=ki(2);s.firstUpdatePass&&Kb(s,n,o,i),t!==se&&Nt(r,o,t)&&Xb(s,s.data[jt()],r,r[11],n,r[o+1]=function eO(n,t){return null==n||(\"string\"==typeof t?n+=t:\"object\"==typeof n&&(n=Re(on(n)))),n}(t,e),i,o)}function Qb(n,t){return t>=n.expandoStartIndex}function Kb(n,t,e,i){const r=n.data;if(null===r[e+1]){const s=r[jt()],o=Qb(n,e);eC(s,i)&&null===t&&!o&&(t=!1),t=function Y1(n,t,e,i){const r=Wu(n);let s=i?t.residualClasses:t.residualStyles;if(null===r)0===(i?t.classBindings:t.styleBindings)&&(e=sa(e=mp(null,n,t,e,i),t.attrs,i),s=null);else{const o=t.directiveStylingLast;if(-1===o||n[o]!==r)if(e=mp(r,n,t,e,i),null===s){let l=function Q1(n,t,e){const i=e?t.classBindings:t.styleBindings;if(0!==Ti(i))return n[zn(i)]}(n,t,i);void 0!==l&&Array.isArray(l)&&(l=mp(null,n,t,l[1],i),l=sa(l,t.attrs,i),function K1(n,t,e,i){n[zn(e?t.classBindings:t.styleBindings)]=i}(n,t,i,l))}else s=function Z1(n,t,e){let i;const r=t.directiveEnd;for(let s=1+t.directiveStylingLast;s<r;s++)i=sa(i,n[s].hostAttrs,e);return sa(i,t.attrs,e)}(n,t,i)}return void 0!==s&&(i?t.residualClasses=s:t.residualStyles=s),e}(r,s,t,i),function L1(n,t,e,i,r,s){let o=s?t.classBindings:t.styleBindings,a=zn(o),l=Ti(o);n[i]=e;let d,c=!1;if(Array.isArray(e)){const u=e;d=u[1],(null===d||bs(u,d)>0)&&(c=!0)}else d=e;if(r)if(0!==l){const h=zn(n[a+1]);n[i+1]=Jl(h,a),0!==h&&(n[h+1]=Rh(n[h+1],i)),n[a+1]=function KI(n,t){return 131071&n|t<<17}(n[a+1],i)}else n[i+1]=Jl(a,0),0!==a&&(n[a+1]=Rh(n[a+1],i)),a=i;else n[i+1]=Jl(l,0),0===a?a=i:n[l+1]=Rh(n[l+1],i),l=i;c&&(n[i+1]=Ih(n[i+1])),zb(n,d,i,!0),zb(n,d,i,!1),function B1(n,t,e,i,r){const s=r?n.residualClasses:n.residualStyles;null!=s&&\"string\"==typeof t&&bs(s,t)>=0&&(e[i+1]=Oh(e[i+1]))}(t,d,n,i,s),o=Jl(a,l),s?t.classBindings=o:t.styleBindings=o}(r,s,t,e,o,i)}}function mp(n,t,e,i,r){let s=null;const o=e.directiveEnd;let a=e.directiveStylingLast;for(-1===a?a=e.directiveStart:a++;a<o&&(s=t[a],i=sa(i,s.hostAttrs,r),s!==n);)a++;return null!==n&&(e.directiveStylingLast=a),i}function sa(n,t,e){const i=e?1:2;let r=-1;if(null!==t)for(let s=0;s<t.length;s++){const o=t[s];\"number\"==typeof o?r=o:r===i&&(Array.isArray(n)||(n=void 0===n?[]:[\"\",n]),sn(n,o,!!e||t[++s]))}return void 0===n?null:n}function Xb(n,t,e,i,r,s,o,a){if(!(3&t.type))return;const l=n.data,c=l[a+1];lc(function vy(n){return 1==(1&n)}(c)?Jb(l,t,e,r,Ti(c),o):void 0)||(lc(s)||function _y(n){return 2==(2&n)}(c)&&(s=Jb(l,null,e,r,a,o)),function BI(n,t,e,i,r){const s=et(n);if(t)r?s?n.addClass(e,i):e.classList.add(i):s?n.removeClass(e,i):e.classList.remove(i);else{let o=-1===i.indexOf(\"-\")?void 0:an.DashCase;if(null==r)s?n.removeStyle(e,i,o):e.style.removeProperty(i);else{const a=\"string\"==typeof r&&r.endsWith(\"!important\");a&&(r=r.slice(0,-10),o|=an.Important),s?n.setStyle(e,i,r,o):e.style.setProperty(i,r,a?\"important\":\"\")}}}(i,o,kl(jt(),e),r,s))}function Jb(n,t,e,i,r,s){const o=null===t;let a;for(;r>0;){const l=n[r],c=Array.isArray(l),d=c?l[1]:l,u=null===d;let h=e[r+1];h===se&&(h=u?Ne:void 0);let p=u?ih(h,i):d===i?h:void 0;if(c&&!lc(p)&&(p=ih(l,i)),lc(p)&&(a=p,o))return a;const m=n[r+1];r=o?zn(m):Ti(m)}if(null!==t){let l=s?t.residualClasses:t.residualStyles;null!=l&&(a=ih(l,i))}return a}function lc(n){return void 0!==n}function eC(n,t){return 0!=(n.flags&(t?16:32))}function we(n,t=\"\"){const e=w(),i=Me(),r=n+20,s=i.firstCreatePass?xs(i,r,1,t,null):i.data[r],o=e[r]=function wh(n,t){return et(n)?n.createText(t):n.createTextNode(t)}(e[11],t);Zl(i,e,o,s),oi(s,!1)}function Ut(n){return qn(\"\",n,\"\"),Ut}function qn(n,t,e){const i=w(),r=Rs(i,n,t,e);return r!==se&&Ai(i,jt(),r),qn}function cC(n,t,e){!function Wn(n,t,e,i){const r=Me(),s=ki(2);r.firstUpdatePass&&Kb(r,null,s,i);const o=w();if(e!==se&&Nt(o,s,e)){const a=r.data[jt()];if(eC(a,i)&&!Qb(r,s)){let l=i?a.classesWithoutHost:a.stylesWithoutHost;null!==l&&(e=Mu(l,e||\"\")),dp(r,a,o,e,i)}else!function J1(n,t,e,i,r,s,o,a){r===se&&(r=Ne);let l=0,c=0,d=0<r.length?r[0]:null,u=0<s.length?s[0]:null;for(;null!==d||null!==u;){const h=l<r.length?r[l+1]:void 0,p=c<s.length?s[c+1]:void 0;let g,m=null;d===u?(l+=2,c+=2,h!==p&&(m=u,g=p)):null===u||null!==d&&d<u?(l+=2,m=d):(c+=2,m=u,g=p),null!==m&&Xb(n,t,e,i,m,g,o,a),d=l<r.length?r[l]:null,u=c<s.length?s[c]:null}}(r,a,o,o[11],o[s+1],o[s+1]=function X1(n,t,e){if(null==e||\"\"===e)return Ne;const i=[],r=on(e);if(Array.isArray(r))for(let s=0;s<r.length;s++)n(i,r[s],!0);else if(\"object\"==typeof r)for(const s in r)r.hasOwnProperty(s)&&n(i,s,r[s]);else\"string\"==typeof r&&t(i,r);return i}(n,t,e),i,s)}}(sn,fi,Rs(w(),n,t,e),!0)}function Yn(n,t,e){const i=w();return Nt(i,hs(),t)&&ln(Me(),tt(),i,n,t,i[11],e,!0),Yn}function gp(n,t,e){const i=w();if(Nt(i,hs(),t)){const s=Me(),o=tt();ln(s,o,i,n,t,$y(Wu(s.data),o,i),e,!0)}return gp}const cc=\"en-US\";let CC=cc;function yp(n,t,e,i,r){if(n=le(n),Array.isArray(n))for(let s=0;s<n.length;s++)yp(n[s],t,e,i,r);else{const s=Me(),o=w();let a=Ts(n)?n:le(n.provide),l=Zy(n);const c=gt(),d=1048575&c.providerIndexes,u=c.directiveStart,h=c.providerIndexes>>20;if(Ts(n)||!n.multi){const p=new Po(l,r,f),m=Cp(a,t,r?d:d+h,u);-1===m?(Hl(No(c,o),s,a),bp(s,n,t.length),t.push(a),c.directiveStart++,c.directiveEnd++,r&&(c.providerIndexes+=1048576),e.push(p),o.push(p)):(e[m]=p,o[m]=p)}else{const p=Cp(a,t,d+h,u),m=Cp(a,t,d,d+h),g=p>=0&&e[p],_=m>=0&&e[m];if(r&&!_||!r&&!g){Hl(No(c,o),s,a);const D=function vP(n,t,e,i,r){const s=new Po(n,e,f);return s.multi=[],s.index=t,s.componentProviders=0,GC(s,r,i&&!e),s}(r?_P:gP,e.length,r,i,l);!r&&_&&(e[m].providerFactory=D),bp(s,n,t.length,0),t.push(a),c.directiveStart++,c.directiveEnd++,r&&(c.providerIndexes+=1048576),e.push(D),o.push(D)}else bp(s,n,p>-1?p:m,GC(e[r?m:p],l,!r&&i));!r&&i&&_&&e[m].componentProviders++}}}function bp(n,t,e,i){const r=Ts(t),s=function UR(n){return!!n.useClass}(t);if(r||s){const l=(s?le(t.useClass):t).prototype.ngOnDestroy;if(l){const c=n.destroyHooks||(n.destroyHooks=[]);if(!r&&t.multi){const d=c.indexOf(e);-1===d?c.push(e,[i,l]):c[d+1].push(i,l)}else c.push(e,l)}}}function GC(n,t,e){return e&&n.componentProviders++,n.multi.push(t)-1}function Cp(n,t,e,i){for(let r=e;r<i;r++)if(t[r]===n)return r;return-1}function gP(n,t,e,i){return Dp(this.multi,[])}function _P(n,t,e,i){const r=this.multi;let s;if(this.providerFactory){const o=this.providerFactory.componentProviders,a=Lo(e,e[1],this.providerFactory.index,i);s=a.slice(0,o),Dp(r,s);for(let l=o;l<a.length;l++)s.push(a[l])}else s=[],Dp(r,s);return s}function Dp(n,t){for(let e=0;e<n.length;e++)t.push((0,n[e])());return t}function L(n,t=[]){return e=>{e.providersResolver=(i,r)=>function mP(n,t,e){const i=Me();if(i.firstCreatePass){const r=Hn(n);yp(e,i.data,i.blueprint,r,!0),yp(t,i.data,i.blueprint,r,!1)}}(i,r?r(n):n,t)}}class WC{}class CP{resolveComponentFactory(t){throw function bP(n){const t=Error(`No component factory found for ${Re(n)}. Did you add it to @NgModule.entryComponents?`);return t.ngComponent=n,t}(t)}}let Ir=(()=>{class n{}return n.NULL=new CP,n})();function DP(){return $s(gt(),w())}function $s(n,t){return new W(yn(n,t))}let W=(()=>{class n{constructor(e){this.nativeElement=e}}return n.__NG_ELEMENT_ID__=DP,n})();function wP(n){return n instanceof W?n.nativeElement:n}class da{}let Ii=(()=>{class n{}return n.__NG_ELEMENT_ID__=()=>function xP(){const n=w(),e=rn(gt().index,n);return function MP(n){return n[11]}(si(e)?e:n)}(),n})(),EP=(()=>{class n{}return n.\\u0275prov=k({token:n,providedIn:\"root\",factory:()=>null}),n})();class Rr{constructor(t){this.full=t,this.major=t.split(\".\")[0],this.minor=t.split(\".\")[1],this.patch=t.split(\".\").slice(2).join(\".\")}}const SP=new Rr(\"13.3.0\"),wp={};function fc(n,t,e,i,r=!1){for(;null!==e;){const s=t[e.index];if(null!==s&&i.push(ct(s)),Vn(s))for(let a=10;a<s.length;a++){const l=s[a],c=l[1].firstChild;null!==c&&fc(l[1],l,c,i)}const o=e.type;if(8&o)fc(n,t,e.child,i);else if(32&o){const a=bh(e,t);let l;for(;l=a();)i.push(l)}else if(16&o){const a=oy(t,e);if(Array.isArray(a))i.push(...a);else{const l=Ko(t[16]);fc(l[1],l,a,i,!0)}}e=r?e.projectionNext:e.next}return i}class ua{constructor(t,e){this._lView=t,this._cdRefInjectingView=e,this._appRef=null,this._attachedToViewContainer=!1}get rootNodes(){const t=this._lView,e=t[1];return fc(e,t,e.firstChild,[])}get context(){return this._lView[8]}set context(t){this._lView[8]=t}get destroyed(){return 256==(256&this._lView[2])}destroy(){if(this._appRef)this._appRef.detachView(this);else if(this._attachedToViewContainer){const t=this._lView[3];if(Vn(t)){const e=t[8],i=e?e.indexOf(this):-1;i>-1&&(xh(t,i),zl(e,i))}this._attachedToViewContainer=!1}Zv(this._lView[1],this._lView)}onDestroy(t){Ry(this._lView[1],this._lView,null,t)}markForCheck(){Yh(this._cdRefInjectingView||this._lView)}detach(){this._lView[2]&=-129}reattach(){this._lView[2]|=128}detectChanges(){Kh(this._lView[1],this._lView,this.context)}checkNoChanges(){!function RR(n,t,e){Al(!0);try{Kh(n,t,e)}finally{Al(!1)}}(this._lView[1],this._lView,this.context)}attachToViewContainerRef(){if(this._appRef)throw new H(902,\"\");this._attachedToViewContainer=!0}detachFromAppRef(){this._appRef=null,function kI(n,t){Zo(n,t,t[11],2,null,null)}(this._lView[1],this._lView)}attachToAppRef(t){if(this._attachedToViewContainer)throw new H(902,\"\");this._appRef=t}}class kP extends ua{constructor(t){super(t),this._view=t}detectChanges(){jy(this._view)}checkNoChanges(){!function OR(n){Al(!0);try{jy(n)}finally{Al(!1)}}(this._view)}get context(){return null}}class YC extends Ir{constructor(t){super(),this.ngModule=t}resolveComponentFactory(t){const e=Ot(t);return new Mp(e,this.ngModule)}}function QC(n){const t=[];for(let e in n)n.hasOwnProperty(e)&&t.push({propName:n[e],templateName:e});return t}class Mp extends WC{constructor(t,e){super(),this.componentDef=t,this.ngModule=e,this.componentType=t.type,this.selector=function YI(n){return n.map(qI).join(\",\")}(t.selectors),this.ngContentSelectors=t.ngContentSelectors?t.ngContentSelectors:[],this.isBoundToModule=!!e}get inputs(){return QC(this.componentDef.inputs)}get outputs(){return QC(this.componentDef.outputs)}create(t,e,i,r){const s=(r=r||this.ngModule)?function AP(n,t){return{get:(e,i,r)=>{const s=n.get(e,wp,r);return s!==wp||i===wp?s:t.get(e,i,r)}}}(t,r.injector):t,o=s.get(da,V_),a=s.get(EP,null),l=o.createRenderer(null,this.componentDef),c=this.componentDef.selectors[0][0]||\"div\",d=i?function Iy(n,t,e){if(et(n))return n.selectRootElement(t,e===Ln.ShadowDom);let i=\"string\"==typeof t?n.querySelector(t):t;return i.textContent=\"\",i}(l,i,this.componentDef.encapsulation):Mh(o.createRenderer(null,this.componentDef),c,function TP(n){const t=n.toLowerCase();return\"svg\"===t?\"svg\":\"math\"===t?\"math\":null}(c)),u=this.componentDef.onPush?576:528,h=function cb(n,t){return{components:[],scheduler:n||CI,clean:PR,playerHandler:t||null,flags:0}}(),p=nc(0,null,null,1,0,null,null,null,null,null),m=Xo(null,p,h,u,null,null,o,l,a,s);let g,_;Il(m);try{const D=function ab(n,t,e,i,r,s){const o=e[1];e[20]=n;const l=xs(o,20,2,\"#host\",null),c=l.mergedAttrs=t.hostAttrs;null!==c&&(rc(l,c,!0),null!==n&&(Nl(r,n,c),null!==l.classes&&Ah(r,n,l.classes),null!==l.styles&&cy(r,n,l.styles)));const d=i.createRenderer(n,t),u=Xo(e,Ty(t),null,t.onPush?64:16,e[20],l,i,d,s||null,null);return o.firstCreatePass&&(Hl(No(l,e),o,t.type),Ly(o,l),By(l,e.length,1)),ic(e,u),e[20]=u}(d,this.componentDef,m,o,l);if(d)if(i)Nl(l,d,[\"ng-version\",SP.full]);else{const{attrs:v,classes:M}=function QI(n){const t=[],e=[];let i=1,r=2;for(;i<n.length;){let s=n[i];if(\"string\"==typeof s)2===r?\"\"!==s&&t.push(s,n[++i]):8===r&&e.push(s);else{if(!jn(r))break;r=s}i++}return{attrs:t,classes:e}}(this.componentDef.selectors[0]);v&&Nl(l,d,v),M&&M.length>0&&Ah(l,d,M.join(\" \"))}if(_=Hu(p,20),void 0!==e){const v=_.projection=[];for(let M=0;M<this.ngContentSelectors.length;M++){const V=e[M];v.push(null!=V?Array.from(V):null)}}g=function lb(n,t,e,i,r){const s=e[1],o=function gR(n,t,e){const i=gt();n.firstCreatePass&&(e.providersResolver&&e.providersResolver(e),Vy(n,i,t,Es(n,t,1,null),e));const r=Lo(t,n,i.directiveStart,i);Ft(r,t);const s=yn(i,t);return s&&Ft(s,t),r}(s,e,t);if(i.components.push(o),n[8]=o,r&&r.forEach(l=>l(o,t)),t.contentQueries){const l=gt();t.contentQueries(1,o,l.directiveStart)}const a=gt();return!s.firstCreatePass||null===t.hostBindings&&null===t.hostAttrs||(Zi(a.index),Fy(e[1],a,0,a.directiveStart,a.directiveEnd,t),Ny(t,o)),o}(D,this.componentDef,m,h,[e1]),Jo(p,m,null)}finally{Rl()}return new RP(this.componentType,g,$s(_,m),m,_)}}class RP extends class yP{}{constructor(t,e,i,r,s){super(),this.location=i,this._rootLView=r,this._tNode=s,this.instance=e,this.hostView=this.changeDetectorRef=new kP(r),this.componentType=t}get injector(){return new ms(this._tNode,this._rootLView)}destroy(){this.hostView.destroy()}onDestroy(t){this.hostView.onDestroy(t)}}class Ri{}class KC{}const Gs=new Map;class JC extends Ri{constructor(t,e){super(),this._parent=e,this._bootstrapComponents=[],this.injector=this,this.destroyCbs=[],this.componentFactoryResolver=new YC(this);const i=gn(t);this._bootstrapComponents=di(i.bootstrap),this._r3Injector=Ky(t,e,[{provide:Ri,useValue:this},{provide:Ir,useValue:this.componentFactoryResolver}],Re(t)),this._r3Injector._resolveInjectorDefTypes(),this.instance=this.get(t)}get(t,e=dt.THROW_IF_NOT_FOUND,i=ee.Default){return t===dt||t===Ri||t===Xh?this:this._r3Injector.get(t,e,i)}destroy(){const t=this._r3Injector;!t.destroyed&&t.destroy(),this.destroyCbs.forEach(e=>e()),this.destroyCbs=null}onDestroy(t){this.destroyCbs.push(t)}}class xp extends KC{constructor(t){super(),this.moduleType=t,null!==gn(t)&&function PP(n){const t=new Set;!function e(i){const r=gn(i,!0),s=r.id;null!==s&&(function ZC(n,t,e){if(t&&t!==e)throw new Error(`Duplicate module registered for ${n} - ${Re(t)} vs ${Re(t.name)}`)}(s,Gs.get(s),i),Gs.set(s,i));const o=di(r.imports);for(const a of o)t.has(a)||(t.add(a),e(a))}(n)}(t)}create(t){return new JC(this.moduleType,t)}}function Ep(n){return t=>{setTimeout(n,void 0,t)}}const $=class ZP extends O{constructor(t=!1){super(),this.__isAsync=t}emit(t){super.next(t)}subscribe(t,e,i){var r,s,o;let a=t,l=e||(()=>null),c=i;if(t&&\"object\"==typeof t){const u=t;a=null===(r=u.next)||void 0===r?void 0:r.bind(u),l=null===(s=u.error)||void 0===s?void 0:s.bind(u),c=null===(o=u.complete)||void 0===o?void 0:o.bind(u)}this.__isAsync&&(l=Ep(l),a&&(a=Ep(a)),c&&(c=Ep(c)));const d=super.subscribe({next:a,error:l,complete:c});return t instanceof ke&&t.add(d),d}};function XP(){return this._results[As()]()}class fa{constructor(t=!1){this._emitDistinctChangesOnly=t,this.dirty=!0,this._results=[],this._changesDetected=!1,this._changes=null,this.length=0,this.first=void 0,this.last=void 0;const e=As(),i=fa.prototype;i[e]||(i[e]=XP)}get changes(){return this._changes||(this._changes=new $)}get(t){return this._results[t]}map(t){return this._results.map(t)}filter(t){return this._results.filter(t)}find(t){return this._results.find(t)}reduce(t,e){return this._results.reduce(t,e)}forEach(t){this._results.forEach(t)}some(t){return this._results.some(t)}toArray(){return this._results.slice()}toString(){return this._results.toString()}reset(t,e){const i=this;i.dirty=!1;const r=bn(t);(this._changesDetected=!function iA(n,t,e){if(n.length!==t.length)return!1;for(let i=0;i<n.length;i++){let r=n[i],s=t[i];if(e&&(r=e(r),s=e(s)),s!==r)return!1}return!0}(i._results,r,e))&&(i._results=r,i.length=r.length,i.last=r[this.length-1],i.first=r[0])}notifyOnChanges(){this._changes&&(this._changesDetected||!this._emitDistinctChangesOnly)&&this._changes.emit(this)}setDirty(){this.dirty=!0}destroy(){this.changes.complete(),this.changes.unsubscribe()}}Symbol;let ut=(()=>{class n{}return n.__NG_ELEMENT_ID__=tF,n})();const JP=ut,eF=class extends JP{constructor(t,e,i){super(),this._declarationLView=t,this._declarationTContainer=e,this.elementRef=i}createEmbeddedView(t){const e=this._declarationTContainer.tViews,i=Xo(this._declarationLView,e,t,16,null,e.declTNode,null,null,null,null);i[17]=this._declarationLView[this._declarationTContainer.index];const s=this._declarationLView[19];return null!==s&&(i[19]=s.createEmbeddedView(e)),Jo(e,i,t),new ua(i)}};function tF(){return gc(gt(),w())}function gc(n,t){return 4&n.type?new eF(t,n,$s(n,t)):null}let st=(()=>{class n{}return n.__NG_ELEMENT_ID__=nF,n})();function nF(){return l0(gt(),w())}const iF=st,o0=class extends iF{constructor(t,e,i){super(),this._lContainer=t,this._hostTNode=e,this._hostLView=i}get element(){return $s(this._hostTNode,this._hostLView)}get injector(){return new ms(this._hostTNode,this._hostLView)}get parentInjector(){const t=Vl(this._hostTNode,this._hostLView);if(nv(t)){const e=fs(t,this._hostLView),i=ps(t);return new ms(e[1].data[i+8],e)}return new ms(null,this._hostLView)}clear(){for(;this.length>0;)this.remove(this.length-1)}get(t){const e=a0(this._lContainer);return null!==e&&e[t]||null}get length(){return this._lContainer.length-10}createEmbeddedView(t,e,i){const r=t.createEmbeddedView(e||{});return this.insert(r,i),r}createComponent(t,e,i,r,s){const o=t&&!function Vo(n){return\"function\"==typeof n}(t);let a;if(o)a=e;else{const u=e||{};a=u.index,i=u.injector,r=u.projectableNodes,s=u.ngModuleRef}const l=o?t:new Mp(Ot(t)),c=i||this.parentInjector;if(!s&&null==l.ngModule){const h=(o?c:this.parentInjector).get(Ri,null);h&&(s=h)}const d=l.create(c,r,void 0,s);return this.insert(d.hostView,a),d}insert(t,e){const i=t._lView,r=i[1];if(function ET(n){return Vn(n[3])}(i)){const d=this.indexOf(t);if(-1!==d)this.detach(d);else{const u=i[3],h=new o0(u,u[6],u[3]);h.detach(h.indexOf(t))}}const s=this._adjustIndex(e),o=this._lContainer;!function AI(n,t,e,i){const r=10+i,s=e.length;i>0&&(e[r-1][4]=t),i<s-10?(t[4]=e[r],hv(e,10+i,t)):(e.push(t),t[4]=null),t[3]=e;const o=t[17];null!==o&&e!==o&&function II(n,t){const e=n[9];t[16]!==t[3][3][16]&&(n[2]=!0),null===e?n[9]=[t]:e.push(t)}(o,t);const a=t[19];null!==a&&a.insertView(n),t[2]|=128}(r,i,o,s);const a=kh(s,o),l=i[11],c=Kl(l,o[7]);return null!==c&&function SI(n,t,e,i,r,s){i[0]=r,i[6]=t,Zo(n,i,e,1,r,s)}(r,o[6],l,i,c,a),t.attachToViewContainerRef(),hv(Sp(o),s,t),t}move(t,e){return this.insert(t,e)}indexOf(t){const e=a0(this._lContainer);return null!==e?e.indexOf(t):-1}remove(t){const e=this._adjustIndex(t,-1),i=xh(this._lContainer,e);i&&(zl(Sp(this._lContainer),e),Zv(i[1],i))}detach(t){const e=this._adjustIndex(t,-1),i=xh(this._lContainer,e);return i&&null!=zl(Sp(this._lContainer),e)?new ua(i):null}_adjustIndex(t,e=0){return null==t?this.length+e:t}};function a0(n){return n[8]}function Sp(n){return n[8]||(n[8]=[])}function l0(n,t){let e;const i=t[n.index];if(Vn(i))e=i;else{let r;if(8&n.type)r=ct(i);else{const s=t[11];r=s.createComment(\"\");const o=yn(n,t);xr(s,Kl(s,o),r,function FI(n,t){return et(n)?n.nextSibling(t):t.nextSibling}(s,o),!1)}t[n.index]=e=Hy(i,t,r,n),ic(t,e)}return new o0(e,n,t)}class kp{constructor(t){this.queryList=t,this.matches=null}clone(){return new kp(this.queryList)}setDirty(){this.queryList.setDirty()}}class Tp{constructor(t=[]){this.queries=t}createEmbeddedView(t){const e=t.queries;if(null!==e){const i=null!==t.contentQueries?t.contentQueries[0]:e.length,r=[];for(let s=0;s<i;s++){const o=e.getByIndex(s);r.push(this.queries[o.indexInDeclarationView].clone())}return new Tp(r)}return null}insertView(t){this.dirtyQueriesWithMatches(t)}detachView(t){this.dirtyQueriesWithMatches(t)}dirtyQueriesWithMatches(t){for(let e=0;e<this.queries.length;e++)null!==p0(t,e).matches&&this.queries[e].setDirty()}}class c0{constructor(t,e,i=null){this.predicate=t,this.flags=e,this.read=i}}class Ap{constructor(t=[]){this.queries=t}elementStart(t,e){for(let i=0;i<this.queries.length;i++)this.queries[i].elementStart(t,e)}elementEnd(t){for(let e=0;e<this.queries.length;e++)this.queries[e].elementEnd(t)}embeddedTView(t){let e=null;for(let i=0;i<this.length;i++){const r=null!==e?e.length:0,s=this.getByIndex(i).embeddedTView(t,r);s&&(s.indexInDeclarationView=i,null!==e?e.push(s):e=[s])}return null!==e?new Ap(e):null}template(t,e){for(let i=0;i<this.queries.length;i++)this.queries[i].template(t,e)}getByIndex(t){return this.queries[t]}get length(){return this.queries.length}track(t){this.queries.push(t)}}class Ip{constructor(t,e=-1){this.metadata=t,this.matches=null,this.indexInDeclarationView=-1,this.crossesNgTemplate=!1,this._appliesToNextNode=!0,this._declarationNodeIndex=e}elementStart(t,e){this.isApplyingToNode(e)&&this.matchTNode(t,e)}elementEnd(t){this._declarationNodeIndex===t.index&&(this._appliesToNextNode=!1)}template(t,e){this.elementStart(t,e)}embeddedTView(t,e){return this.isApplyingToNode(t)?(this.crossesNgTemplate=!0,this.addMatch(-t.index,e),new Ip(this.metadata)):null}isApplyingToNode(t){if(this._appliesToNextNode&&1!=(1&this.metadata.flags)){const e=this._declarationNodeIndex;let i=t.parent;for(;null!==i&&8&i.type&&i.index!==e;)i=i.parent;return e===(null!==i?i.index:-1)}return this._appliesToNextNode}matchTNode(t,e){const i=this.metadata.predicate;if(Array.isArray(i))for(let r=0;r<i.length;r++){const s=i[r];this.matchTNodeWithReadOption(t,e,oF(e,s)),this.matchTNodeWithReadOption(t,e,jl(e,t,s,!1,!1))}else i===ut?4&e.type&&this.matchTNodeWithReadOption(t,e,-1):this.matchTNodeWithReadOption(t,e,jl(e,t,i,!1,!1))}matchTNodeWithReadOption(t,e,i){if(null!==i){const r=this.metadata.read;if(null!==r)if(r===W||r===st||r===ut&&4&e.type)this.addMatch(e.index,-2);else{const s=jl(e,t,r,!1,!1);null!==s&&this.addMatch(e.index,s)}else this.addMatch(e.index,i)}}addMatch(t,e){null===this.matches?this.matches=[t,e]:this.matches.push(t,e)}}function oF(n,t){const e=n.localNames;if(null!==e)for(let i=0;i<e.length;i+=2)if(e[i]===t)return e[i+1];return null}function lF(n,t,e,i){return-1===e?function aF(n,t){return 11&n.type?$s(n,t):4&n.type?gc(n,t):null}(t,n):-2===e?function cF(n,t,e){return e===W?$s(t,n):e===ut?gc(t,n):e===st?l0(t,n):void 0}(n,t,i):Lo(n,n[1],e,t)}function d0(n,t,e,i){const r=t[19].queries[i];if(null===r.matches){const s=n.data,o=e.matches,a=[];for(let l=0;l<o.length;l+=2){const c=o[l];a.push(c<0?null:lF(t,s[c],o[l+1],e.metadata.read))}r.matches=a}return r.matches}function Rp(n,t,e,i){const r=n.queries.getByIndex(e),s=r.matches;if(null!==s){const o=d0(n,t,r,e);for(let a=0;a<s.length;a+=2){const l=s[a];if(l>0)i.push(o[a/2]);else{const c=s[a+1],d=t[-l];for(let u=10;u<d.length;u++){const h=d[u];h[17]===h[3]&&Rp(h[1],h,c,i)}if(null!==d[9]){const u=d[9];for(let h=0;h<u.length;h++){const p=u[h];Rp(p[1],p,c,i)}}}}}return i}function z(n){const t=w(),e=Me(),i=W_();qu(i+1);const r=p0(e,i);if(n.dirty&&H_(t)===(2==(2&r.metadata.flags))){if(null===r.matches)n.reset([]);else{const s=r.crossesNgTemplate?Rp(e,t,i,[]):d0(e,t,r,i);n.reset(s,wP),n.notifyOnChanges()}return!0}return!1}function je(n,t,e){const i=Me();i.firstCreatePass&&(h0(i,new c0(n,t,e),-1),2==(2&t)&&(i.staticViewQueries=!0)),u0(i,w(),t)}function ve(n,t,e,i){const r=Me();if(r.firstCreatePass){const s=gt();h0(r,new c0(t,e,i),s.index),function uF(n,t){const e=n.contentQueries||(n.contentQueries=[]);t!==(e.length?e[e.length-1]:-1)&&e.push(n.queries.length-1,t)}(r,n),2==(2&e)&&(r.staticContentQueries=!0)}u0(r,w(),e)}function U(){return function dF(n,t){return n[19].queries[t].queryList}(w(),W_())}function u0(n,t,e){const i=new fa(4==(4&e));Ry(n,t,i,i.destroy),null===t[19]&&(t[19]=new Tp),t[19].queries.push(new kp(i))}function h0(n,t,e){null===n.queries&&(n.queries=new Ap),n.queries.track(new Ip(t,e))}function p0(n,t){return n.queries.getByIndex(t)}function yc(...n){}const Bp=new b(\"Application Initializer\");let Vp=(()=>{class n{constructor(e){this.appInits=e,this.resolve=yc,this.reject=yc,this.initialized=!1,this.done=!1,this.donePromise=new Promise((i,r)=>{this.resolve=i,this.reject=r})}runInitializers(){if(this.initialized)return;const e=[],i=()=>{this.done=!0,this.resolve()};if(this.appInits)for(let r=0;r<this.appInits.length;r++){const s=this.appInits[r]();if(ra(s))e.push(s);else if(up(s)){const o=new Promise((a,l)=>{s.subscribe({complete:a,error:l})});e.push(o)}}Promise.all(e).then(()=>{i()}).catch(r=>{this.reject(r)}),0===e.length&&i(),this.initialized=!0}}return n.\\u0275fac=function(e){return new(e||n)(y(Bp,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const ga=new b(\"AppId\",{providedIn:\"root\",factory:function A0(){return`${Hp()}${Hp()}${Hp()}`}});function Hp(){return String.fromCharCode(97+Math.floor(25*Math.random()))}const I0=new b(\"Platform Initializer\"),bc=new b(\"Platform ID\"),R0=new b(\"appBootstrapListener\");let O0=(()=>{class n{log(e){console.log(e)}warn(e){console.warn(e)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const Oi=new b(\"LocaleId\",{providedIn:\"root\",factory:()=>Uo(Oi,ee.Optional|ee.SkipSelf)||function TF(){return\"undefined\"!=typeof $localize&&$localize.locale||cc}()});class IF{constructor(t,e){this.ngModuleFactory=t,this.componentFactories=e}}let P0=(()=>{class n{compileModuleSync(e){return new xp(e)}compileModuleAsync(e){return Promise.resolve(this.compileModuleSync(e))}compileModuleAndAllComponentsSync(e){const i=this.compileModuleSync(e),s=di(gn(e).declarations).reduce((o,a)=>{const l=Ot(a);return l&&o.push(new Mp(l)),o},[]);return new IF(i,s)}compileModuleAndAllComponentsAsync(e){return Promise.resolve(this.compileModuleAndAllComponentsSync(e))}clearCache(){}clearCacheFor(e){}getModuleId(e){}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const OF=(()=>Promise.resolve(0))();function jp(n){\"undefined\"==typeof Zone?OF.then(()=>{n&&n.apply(null,null)}):Zone.current.scheduleMicroTask(\"scheduleMicrotask\",n)}class ne{constructor({enableLongStackTrace:t=!1,shouldCoalesceEventChangeDetection:e=!1,shouldCoalesceRunChangeDetection:i=!1}){if(this.hasPendingMacrotasks=!1,this.hasPendingMicrotasks=!1,this.isStable=!0,this.onUnstable=new $(!1),this.onMicrotaskEmpty=new $(!1),this.onStable=new $(!1),this.onError=new $(!1),\"undefined\"==typeof Zone)throw new Error(\"In this configuration Angular requires Zone.js\");Zone.assertZonePatched();const r=this;r._nesting=0,r._outer=r._inner=Zone.current,Zone.TaskTrackingZoneSpec&&(r._inner=r._inner.fork(new Zone.TaskTrackingZoneSpec)),t&&Zone.longStackTraceZoneSpec&&(r._inner=r._inner.fork(Zone.longStackTraceZoneSpec)),r.shouldCoalesceEventChangeDetection=!i&&e,r.shouldCoalesceRunChangeDetection=i,r.lastRequestAnimationFrameId=-1,r.nativeRequestAnimationFrame=function PF(){let n=Oe.requestAnimationFrame,t=Oe.cancelAnimationFrame;if(\"undefined\"!=typeof Zone&&n&&t){const e=n[Zone.__symbol__(\"OriginalDelegate\")];e&&(n=e);const i=t[Zone.__symbol__(\"OriginalDelegate\")];i&&(t=i)}return{nativeRequestAnimationFrame:n,nativeCancelAnimationFrame:t}}().nativeRequestAnimationFrame,function LF(n){const t=()=>{!function NF(n){n.isCheckStableRunning||-1!==n.lastRequestAnimationFrameId||(n.lastRequestAnimationFrameId=n.nativeRequestAnimationFrame.call(Oe,()=>{n.fakeTopEventTask||(n.fakeTopEventTask=Zone.root.scheduleEventTask(\"fakeTopEventTask\",()=>{n.lastRequestAnimationFrameId=-1,Up(n),n.isCheckStableRunning=!0,zp(n),n.isCheckStableRunning=!1},void 0,()=>{},()=>{})),n.fakeTopEventTask.invoke()}),Up(n))}(n)};n._inner=n._inner.fork({name:\"angular\",properties:{isAngularZone:!0},onInvokeTask:(e,i,r,s,o,a)=>{try{return F0(n),e.invokeTask(r,s,o,a)}finally{(n.shouldCoalesceEventChangeDetection&&\"eventTask\"===s.type||n.shouldCoalesceRunChangeDetection)&&t(),N0(n)}},onInvoke:(e,i,r,s,o,a,l)=>{try{return F0(n),e.invoke(r,s,o,a,l)}finally{n.shouldCoalesceRunChangeDetection&&t(),N0(n)}},onHasTask:(e,i,r,s)=>{e.hasTask(r,s),i===r&&(\"microTask\"==s.change?(n._hasPendingMicrotasks=s.microTask,Up(n),zp(n)):\"macroTask\"==s.change&&(n.hasPendingMacrotasks=s.macroTask))},onHandleError:(e,i,r,s)=>(e.handleError(r,s),n.runOutsideAngular(()=>n.onError.emit(s)),!1)})}(r)}static isInAngularZone(){return\"undefined\"!=typeof Zone&&!0===Zone.current.get(\"isAngularZone\")}static assertInAngularZone(){if(!ne.isInAngularZone())throw new Error(\"Expected to be in Angular Zone, but it is not!\")}static assertNotInAngularZone(){if(ne.isInAngularZone())throw new Error(\"Expected to not be in Angular Zone, but it is!\")}run(t,e,i){return this._inner.run(t,e,i)}runTask(t,e,i,r){const s=this._inner,o=s.scheduleEventTask(\"NgZoneEvent: \"+r,t,FF,yc,yc);try{return s.runTask(o,e,i)}finally{s.cancelTask(o)}}runGuarded(t,e,i){return this._inner.runGuarded(t,e,i)}runOutsideAngular(t){return this._outer.run(t)}}const FF={};function zp(n){if(0==n._nesting&&!n.hasPendingMicrotasks&&!n.isStable)try{n._nesting++,n.onMicrotaskEmpty.emit(null)}finally{if(n._nesting--,!n.hasPendingMicrotasks)try{n.runOutsideAngular(()=>n.onStable.emit(null))}finally{n.isStable=!0}}}function Up(n){n.hasPendingMicrotasks=!!(n._hasPendingMicrotasks||(n.shouldCoalesceEventChangeDetection||n.shouldCoalesceRunChangeDetection)&&-1!==n.lastRequestAnimationFrameId)}function F0(n){n._nesting++,n.isStable&&(n.isStable=!1,n.onUnstable.emit(null))}function N0(n){n._nesting--,zp(n)}class BF{constructor(){this.hasPendingMicrotasks=!1,this.hasPendingMacrotasks=!1,this.isStable=!0,this.onUnstable=new $,this.onMicrotaskEmpty=new $,this.onStable=new $,this.onError=new $}run(t,e,i){return t.apply(e,i)}runGuarded(t,e,i){return t.apply(e,i)}runOutsideAngular(t){return t()}runTask(t,e,i,r){return t.apply(e,i)}}let $p=(()=>{class n{constructor(e){this._ngZone=e,this._pendingCount=0,this._isZoneStable=!0,this._didWork=!1,this._callbacks=[],this.taskTrackingZone=null,this._watchAngularEvents(),e.run(()=>{this.taskTrackingZone=\"undefined\"==typeof Zone?null:Zone.current.get(\"TaskTrackingZone\")})}_watchAngularEvents(){this._ngZone.onUnstable.subscribe({next:()=>{this._didWork=!0,this._isZoneStable=!1}}),this._ngZone.runOutsideAngular(()=>{this._ngZone.onStable.subscribe({next:()=>{ne.assertNotInAngularZone(),jp(()=>{this._isZoneStable=!0,this._runCallbacksIfReady()})}})})}increasePendingRequestCount(){return this._pendingCount+=1,this._didWork=!0,this._pendingCount}decreasePendingRequestCount(){if(this._pendingCount-=1,this._pendingCount<0)throw new Error(\"pending async requests below zero\");return this._runCallbacksIfReady(),this._pendingCount}isStable(){return this._isZoneStable&&0===this._pendingCount&&!this._ngZone.hasPendingMacrotasks}_runCallbacksIfReady(){if(this.isStable())jp(()=>{for(;0!==this._callbacks.length;){let e=this._callbacks.pop();clearTimeout(e.timeoutId),e.doneCb(this._didWork)}this._didWork=!1});else{let e=this.getPendingTasks();this._callbacks=this._callbacks.filter(i=>!i.updateCb||!i.updateCb(e)||(clearTimeout(i.timeoutId),!1)),this._didWork=!0}}getPendingTasks(){return this.taskTrackingZone?this.taskTrackingZone.macroTasks.map(e=>({source:e.source,creationLocation:e.creationLocation,data:e.data})):[]}addCallback(e,i,r){let s=-1;i&&i>0&&(s=setTimeout(()=>{this._callbacks=this._callbacks.filter(o=>o.timeoutId!==s),e(this._didWork,this.getPendingTasks())},i)),this._callbacks.push({doneCb:e,timeoutId:s,updateCb:r})}whenStable(e,i,r){if(r&&!this.taskTrackingZone)throw new Error('Task tracking zone is required when passing an update callback to whenStable(). Is \"zone.js/plugins/task-tracking\" loaded?');this.addCallback(e,i,r),this._runCallbacksIfReady()}getPendingRequestCount(){return this._pendingCount}findProviders(e,i,r){return[]}}return n.\\u0275fac=function(e){return new(e||n)(y(ne))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),L0=(()=>{class n{constructor(){this._applications=new Map,Gp.addToWindow(this)}registerApplication(e,i){this._applications.set(e,i)}unregisterApplication(e){this._applications.delete(e)}unregisterAllApplications(){this._applications.clear()}getTestability(e){return this._applications.get(e)||null}getAllTestabilities(){return Array.from(this._applications.values())}getAllRootElements(){return Array.from(this._applications.keys())}findTestabilityInTree(e,i=!0){return Gp.findTestabilityInTree(this,e,i)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class VF{addToWindow(t){}findTestabilityInTree(t,e,i){return null}}let Qn,Gp=new VF;const B0=new b(\"AllowMultipleToken\");class V0{constructor(t,e){this.name=t,this.token=e}}function H0(n,t,e=[]){const i=`Platform: ${t}`,r=new b(i);return(s=[])=>{let o=j0();if(!o||o.injector.get(B0,!1))if(n)n(e.concat(s).concat({provide:r,useValue:!0}));else{const a=e.concat(s).concat({provide:r,useValue:!0},{provide:Jh,useValue:\"platform\"});!function UF(n){if(Qn&&!Qn.destroyed&&!Qn.injector.get(B0,!1))throw new H(400,\"\");Qn=n.get(z0);const t=n.get(I0,null);t&&t.forEach(e=>e())}(dt.create({providers:a,name:i}))}return function $F(n){const t=j0();if(!t)throw new H(401,\"\");return t}()}}function j0(){return Qn&&!Qn.destroyed?Qn:null}let z0=(()=>{class n{constructor(e){this._injector=e,this._modules=[],this._destroyListeners=[],this._destroyed=!1}bootstrapModuleFactory(e,i){const a=function GF(n,t){let e;return e=\"noop\"===n?new BF:(\"zone.js\"===n?void 0:n)||new ne({enableLongStackTrace:!1,shouldCoalesceEventChangeDetection:!!(null==t?void 0:t.ngZoneEventCoalescing),shouldCoalesceRunChangeDetection:!!(null==t?void 0:t.ngZoneRunCoalescing)}),e}(i?i.ngZone:void 0,{ngZoneEventCoalescing:i&&i.ngZoneEventCoalescing||!1,ngZoneRunCoalescing:i&&i.ngZoneRunCoalescing||!1}),l=[{provide:ne,useValue:a}];return a.run(()=>{const c=dt.create({providers:l,parent:this.injector,name:e.moduleType.name}),d=e.create(c),u=d.injector.get(Mr,null);if(!u)throw new H(402,\"\");return a.runOutsideAngular(()=>{const h=a.onError.subscribe({next:p=>{u.handleError(p)}});d.onDestroy(()=>{Wp(this._modules,d),h.unsubscribe()})}),function WF(n,t,e){try{const i=e();return ra(i)?i.catch(r=>{throw t.runOutsideAngular(()=>n.handleError(r)),r}):i}catch(i){throw t.runOutsideAngular(()=>n.handleError(i)),i}}(u,a,()=>{const h=d.injector.get(Vp);return h.runInitializers(),h.donePromise.then(()=>(function MO(n){tn(n,\"Expected localeId to be defined\"),\"string\"==typeof n&&(CC=n.toLowerCase().replace(/_/g,\"-\"))}(d.injector.get(Oi,cc)||cc),this._moduleDoBootstrap(d),d))})})}bootstrapModule(e,i=[]){const r=U0({},i);return function jF(n,t,e){const i=new xp(e);return Promise.resolve(i)}(0,0,e).then(s=>this.bootstrapModuleFactory(s,r))}_moduleDoBootstrap(e){const i=e.injector.get(Cc);if(e._bootstrapComponents.length>0)e._bootstrapComponents.forEach(r=>i.bootstrap(r));else{if(!e.instance.ngDoBootstrap)throw new H(403,\"\");e.instance.ngDoBootstrap(i)}this._modules.push(e)}onDestroy(e){this._destroyListeners.push(e)}get injector(){return this._injector}destroy(){if(this._destroyed)throw new H(404,\"\");this._modules.slice().forEach(e=>e.destroy()),this._destroyListeners.forEach(e=>e()),this._destroyed=!0}get destroyed(){return this._destroyed}}return n.\\u0275fac=function(e){return new(e||n)(y(dt))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();function U0(n,t){return Array.isArray(t)?t.reduce(U0,n):Object.assign(Object.assign({},n),t)}let Cc=(()=>{class n{constructor(e,i,r,s,o){this._zone=e,this._injector=i,this._exceptionHandler=r,this._componentFactoryResolver=s,this._initStatus=o,this._bootstrapListeners=[],this._views=[],this._runningTick=!1,this._stable=!0,this.componentTypes=[],this.components=[],this._onMicrotaskEmptySubscription=this._zone.onMicrotaskEmpty.subscribe({next:()=>{this._zone.run(()=>{this.tick()})}});const a=new Ve(c=>{this._stable=this._zone.isStable&&!this._zone.hasPendingMacrotasks&&!this._zone.hasPendingMicrotasks,this._zone.runOutsideAngular(()=>{c.next(this._stable),c.complete()})}),l=new Ve(c=>{let d;this._zone.runOutsideAngular(()=>{d=this._zone.onStable.subscribe(()=>{ne.assertNotInAngularZone(),jp(()=>{!this._stable&&!this._zone.hasPendingMacrotasks&&!this._zone.hasPendingMicrotasks&&(this._stable=!0,c.next(!0))})})});const u=this._zone.onUnstable.subscribe(()=>{ne.assertInAngularZone(),this._stable&&(this._stable=!1,this._zone.runOutsideAngular(()=>{c.next(!1)}))});return()=>{d.unsubscribe(),u.unsubscribe()}});this.isStable=Bt(a,l.pipe(function M_(n={}){const{connector:t=(()=>new O),resetOnError:e=!0,resetOnComplete:i=!0,resetOnRefCountZero:r=!0}=n;return s=>{let o=null,a=null,l=null,c=0,d=!1,u=!1;const h=()=>{null==a||a.unsubscribe(),a=null},p=()=>{h(),o=l=null,d=u=!1},m=()=>{const g=o;p(),null==g||g.unsubscribe()};return qe((g,_)=>{c++,!u&&!d&&h();const D=l=null!=l?l:t();_.add(()=>{c--,0===c&&!u&&!d&&(a=Du(m,r))}),D.subscribe(_),o||(o=new vl({next:v=>D.next(v),error:v=>{u=!0,h(),a=Du(p,e,v),D.error(v)},complete:()=>{d=!0,h(),a=Du(p,i),D.complete()}}),mt(g).subscribe(o))})(s)}}()))}bootstrap(e,i){if(!this._initStatus.done)throw new H(405,\"\");let r;r=e instanceof WC?e:this._componentFactoryResolver.resolveComponentFactory(e),this.componentTypes.push(r.componentType);const s=function zF(n){return n.isBoundToModule}(r)?void 0:this._injector.get(Ri),a=r.create(dt.NULL,[],i||r.selector,s),l=a.location.nativeElement,c=a.injector.get($p,null),d=c&&a.injector.get(L0);return c&&d&&d.registerApplication(l,c),a.onDestroy(()=>{this.detachView(a.hostView),Wp(this.components,a),d&&d.unregisterApplication(l)}),this._loadComponent(a),a}tick(){if(this._runningTick)throw new H(101,\"\");try{this._runningTick=!0;for(let e of this._views)e.detectChanges()}catch(e){this._zone.runOutsideAngular(()=>this._exceptionHandler.handleError(e))}finally{this._runningTick=!1}}attachView(e){const i=e;this._views.push(i),i.attachToAppRef(this)}detachView(e){const i=e;Wp(this._views,i),i.detachFromAppRef()}_loadComponent(e){this.attachView(e.hostView),this.tick(),this.components.push(e),this._injector.get(R0,[]).concat(this._bootstrapListeners).forEach(r=>r(e))}ngOnDestroy(){this._views.slice().forEach(e=>e.destroy()),this._onMicrotaskEmptySubscription.unsubscribe()}get viewCount(){return this._views.length}}return n.\\u0275fac=function(e){return new(e||n)(y(ne),y(dt),y(Mr),y(Ir),y(Vp))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();function Wp(n,t){const e=n.indexOf(t);e>-1&&n.splice(e,1)}let G0=!0,Ye=(()=>{class n{}return n.__NG_ELEMENT_ID__=QF,n})();function QF(n){return function KF(n,t,e){if(El(n)&&!e){const i=rn(n.index,t);return new ua(i,i)}return 47&n.type?new ua(t[16],t):null}(gt(),w(),16==(16&n))}class K0{constructor(){}supports(t){return ta(t)}create(t){return new nN(t)}}const tN=(n,t)=>t;class nN{constructor(t){this.length=0,this._linkedRecords=null,this._unlinkedRecords=null,this._previousItHead=null,this._itHead=null,this._itTail=null,this._additionsHead=null,this._additionsTail=null,this._movesHead=null,this._movesTail=null,this._removalsHead=null,this._removalsTail=null,this._identityChangesHead=null,this._identityChangesTail=null,this._trackByFn=t||tN}forEachItem(t){let e;for(e=this._itHead;null!==e;e=e._next)t(e)}forEachOperation(t){let e=this._itHead,i=this._removalsHead,r=0,s=null;for(;e||i;){const o=!i||e&&e.currentIndex<X0(i,r,s)?e:i,a=X0(o,r,s),l=o.currentIndex;if(o===i)r--,i=i._nextRemoved;else if(e=e._next,null==o.previousIndex)r++;else{s||(s=[]);const c=a-r,d=l-r;if(c!=d){for(let h=0;h<c;h++){const p=h<s.length?s[h]:s[h]=0,m=p+h;d<=m&&m<c&&(s[h]=p+1)}s[o.previousIndex]=d-c}}a!==l&&t(o,a,l)}}forEachPreviousItem(t){let e;for(e=this._previousItHead;null!==e;e=e._nextPrevious)t(e)}forEachAddedItem(t){let e;for(e=this._additionsHead;null!==e;e=e._nextAdded)t(e)}forEachMovedItem(t){let e;for(e=this._movesHead;null!==e;e=e._nextMoved)t(e)}forEachRemovedItem(t){let e;for(e=this._removalsHead;null!==e;e=e._nextRemoved)t(e)}forEachIdentityChange(t){let e;for(e=this._identityChangesHead;null!==e;e=e._nextIdentityChange)t(e)}diff(t){if(null==t&&(t=[]),!ta(t))throw new H(900,\"\");return this.check(t)?this:null}onDestroy(){}check(t){this._reset();let r,s,o,e=this._itHead,i=!1;if(Array.isArray(t)){this.length=t.length;for(let a=0;a<this.length;a++)s=t[a],o=this._trackByFn(a,s),null!==e&&Object.is(e.trackById,o)?(i&&(e=this._verifyReinsertion(e,s,o,a)),Object.is(e.item,s)||this._addIdentityChange(e,s)):(e=this._mismatch(e,s,o,a),i=!0),e=e._next}else r=0,function u1(n,t){if(Array.isArray(n))for(let e=0;e<n.length;e++)t(n[e]);else{const e=n[As()]();let i;for(;!(i=e.next()).done;)t(i.value)}}(t,a=>{o=this._trackByFn(r,a),null!==e&&Object.is(e.trackById,o)?(i&&(e=this._verifyReinsertion(e,a,o,r)),Object.is(e.item,a)||this._addIdentityChange(e,a)):(e=this._mismatch(e,a,o,r),i=!0),e=e._next,r++}),this.length=r;return this._truncate(e),this.collection=t,this.isDirty}get isDirty(){return null!==this._additionsHead||null!==this._movesHead||null!==this._removalsHead||null!==this._identityChangesHead}_reset(){if(this.isDirty){let t;for(t=this._previousItHead=this._itHead;null!==t;t=t._next)t._nextPrevious=t._next;for(t=this._additionsHead;null!==t;t=t._nextAdded)t.previousIndex=t.currentIndex;for(this._additionsHead=this._additionsTail=null,t=this._movesHead;null!==t;t=t._nextMoved)t.previousIndex=t.currentIndex;this._movesHead=this._movesTail=null,this._removalsHead=this._removalsTail=null,this._identityChangesHead=this._identityChangesTail=null}}_mismatch(t,e,i,r){let s;return null===t?s=this._itTail:(s=t._prev,this._remove(t)),null!==(t=null===this._unlinkedRecords?null:this._unlinkedRecords.get(i,null))?(Object.is(t.item,e)||this._addIdentityChange(t,e),this._reinsertAfter(t,s,r)):null!==(t=null===this._linkedRecords?null:this._linkedRecords.get(i,r))?(Object.is(t.item,e)||this._addIdentityChange(t,e),this._moveAfter(t,s,r)):t=this._addAfter(new iN(e,i),s,r),t}_verifyReinsertion(t,e,i,r){let s=null===this._unlinkedRecords?null:this._unlinkedRecords.get(i,null);return null!==s?t=this._reinsertAfter(s,t._prev,r):t.currentIndex!=r&&(t.currentIndex=r,this._addToMoves(t,r)),t}_truncate(t){for(;null!==t;){const e=t._next;this._addToRemovals(this._unlink(t)),t=e}null!==this._unlinkedRecords&&this._unlinkedRecords.clear(),null!==this._additionsTail&&(this._additionsTail._nextAdded=null),null!==this._movesTail&&(this._movesTail._nextMoved=null),null!==this._itTail&&(this._itTail._next=null),null!==this._removalsTail&&(this._removalsTail._nextRemoved=null),null!==this._identityChangesTail&&(this._identityChangesTail._nextIdentityChange=null)}_reinsertAfter(t,e,i){null!==this._unlinkedRecords&&this._unlinkedRecords.remove(t);const r=t._prevRemoved,s=t._nextRemoved;return null===r?this._removalsHead=s:r._nextRemoved=s,null===s?this._removalsTail=r:s._prevRemoved=r,this._insertAfter(t,e,i),this._addToMoves(t,i),t}_moveAfter(t,e,i){return this._unlink(t),this._insertAfter(t,e,i),this._addToMoves(t,i),t}_addAfter(t,e,i){return this._insertAfter(t,e,i),this._additionsTail=null===this._additionsTail?this._additionsHead=t:this._additionsTail._nextAdded=t,t}_insertAfter(t,e,i){const r=null===e?this._itHead:e._next;return t._next=r,t._prev=e,null===r?this._itTail=t:r._prev=t,null===e?this._itHead=t:e._next=t,null===this._linkedRecords&&(this._linkedRecords=new Z0),this._linkedRecords.put(t),t.currentIndex=i,t}_remove(t){return this._addToRemovals(this._unlink(t))}_unlink(t){null!==this._linkedRecords&&this._linkedRecords.remove(t);const e=t._prev,i=t._next;return null===e?this._itHead=i:e._next=i,null===i?this._itTail=e:i._prev=e,t}_addToMoves(t,e){return t.previousIndex===e||(this._movesTail=null===this._movesTail?this._movesHead=t:this._movesTail._nextMoved=t),t}_addToRemovals(t){return null===this._unlinkedRecords&&(this._unlinkedRecords=new Z0),this._unlinkedRecords.put(t),t.currentIndex=null,t._nextRemoved=null,null===this._removalsTail?(this._removalsTail=this._removalsHead=t,t._prevRemoved=null):(t._prevRemoved=this._removalsTail,this._removalsTail=this._removalsTail._nextRemoved=t),t}_addIdentityChange(t,e){return t.item=e,this._identityChangesTail=null===this._identityChangesTail?this._identityChangesHead=t:this._identityChangesTail._nextIdentityChange=t,t}}class iN{constructor(t,e){this.item=t,this.trackById=e,this.currentIndex=null,this.previousIndex=null,this._nextPrevious=null,this._prev=null,this._next=null,this._prevDup=null,this._nextDup=null,this._prevRemoved=null,this._nextRemoved=null,this._nextAdded=null,this._nextMoved=null,this._nextIdentityChange=null}}class rN{constructor(){this._head=null,this._tail=null}add(t){null===this._head?(this._head=this._tail=t,t._nextDup=null,t._prevDup=null):(this._tail._nextDup=t,t._prevDup=this._tail,t._nextDup=null,this._tail=t)}get(t,e){let i;for(i=this._head;null!==i;i=i._nextDup)if((null===e||e<=i.currentIndex)&&Object.is(i.trackById,t))return i;return null}remove(t){const e=t._prevDup,i=t._nextDup;return null===e?this._head=i:e._nextDup=i,null===i?this._tail=e:i._prevDup=e,null===this._head}}class Z0{constructor(){this.map=new Map}put(t){const e=t.trackById;let i=this.map.get(e);i||(i=new rN,this.map.set(e,i)),i.add(t)}get(t,e){const r=this.map.get(t);return r?r.get(t,e):null}remove(t){const e=t.trackById;return this.map.get(e).remove(t)&&this.map.delete(e),t}get isEmpty(){return 0===this.map.size}clear(){this.map.clear()}}function X0(n,t,e){const i=n.previousIndex;if(null===i)return i;let r=0;return e&&i<e.length&&(r=e[i]),i+t+r}class J0{constructor(){}supports(t){return t instanceof Map||sp(t)}create(){return new sN}}class sN{constructor(){this._records=new Map,this._mapHead=null,this._appendAfter=null,this._previousMapHead=null,this._changesHead=null,this._changesTail=null,this._additionsHead=null,this._additionsTail=null,this._removalsHead=null,this._removalsTail=null}get isDirty(){return null!==this._additionsHead||null!==this._changesHead||null!==this._removalsHead}forEachItem(t){let e;for(e=this._mapHead;null!==e;e=e._next)t(e)}forEachPreviousItem(t){let e;for(e=this._previousMapHead;null!==e;e=e._nextPrevious)t(e)}forEachChangedItem(t){let e;for(e=this._changesHead;null!==e;e=e._nextChanged)t(e)}forEachAddedItem(t){let e;for(e=this._additionsHead;null!==e;e=e._nextAdded)t(e)}forEachRemovedItem(t){let e;for(e=this._removalsHead;null!==e;e=e._nextRemoved)t(e)}diff(t){if(t){if(!(t instanceof Map||sp(t)))throw new H(900,\"\")}else t=new Map;return this.check(t)?this:null}onDestroy(){}check(t){this._reset();let e=this._mapHead;if(this._appendAfter=null,this._forEach(t,(i,r)=>{if(e&&e.key===r)this._maybeAddToChanges(e,i),this._appendAfter=e,e=e._next;else{const s=this._getOrCreateRecordForKey(r,i);e=this._insertBeforeOrAppend(e,s)}}),e){e._prev&&(e._prev._next=null),this._removalsHead=e;for(let i=e;null!==i;i=i._nextRemoved)i===this._mapHead&&(this._mapHead=null),this._records.delete(i.key),i._nextRemoved=i._next,i.previousValue=i.currentValue,i.currentValue=null,i._prev=null,i._next=null}return this._changesTail&&(this._changesTail._nextChanged=null),this._additionsTail&&(this._additionsTail._nextAdded=null),this.isDirty}_insertBeforeOrAppend(t,e){if(t){const i=t._prev;return e._next=t,e._prev=i,t._prev=e,i&&(i._next=e),t===this._mapHead&&(this._mapHead=e),this._appendAfter=t,t}return this._appendAfter?(this._appendAfter._next=e,e._prev=this._appendAfter):this._mapHead=e,this._appendAfter=e,null}_getOrCreateRecordForKey(t,e){if(this._records.has(t)){const r=this._records.get(t);this._maybeAddToChanges(r,e);const s=r._prev,o=r._next;return s&&(s._next=o),o&&(o._prev=s),r._next=null,r._prev=null,r}const i=new oN(t);return this._records.set(t,i),i.currentValue=e,this._addToAdditions(i),i}_reset(){if(this.isDirty){let t;for(this._previousMapHead=this._mapHead,t=this._previousMapHead;null!==t;t=t._next)t._nextPrevious=t._next;for(t=this._changesHead;null!==t;t=t._nextChanged)t.previousValue=t.currentValue;for(t=this._additionsHead;null!=t;t=t._nextAdded)t.previousValue=t.currentValue;this._changesHead=this._changesTail=null,this._additionsHead=this._additionsTail=null,this._removalsHead=null}}_maybeAddToChanges(t,e){Object.is(e,t.currentValue)||(t.previousValue=t.currentValue,t.currentValue=e,this._addToChanges(t))}_addToAdditions(t){null===this._additionsHead?this._additionsHead=this._additionsTail=t:(this._additionsTail._nextAdded=t,this._additionsTail=t)}_addToChanges(t){null===this._changesHead?this._changesHead=this._changesTail=t:(this._changesTail._nextChanged=t,this._changesTail=t)}_forEach(t,e){t instanceof Map?t.forEach(e):Object.keys(t).forEach(i=>e(t[i],i))}}class oN{constructor(t){this.key=t,this.previousValue=null,this.currentValue=null,this._nextPrevious=null,this._next=null,this._prev=null,this._nextAdded=null,this._nextRemoved=null,this._nextChanged=null}}function eD(){return new xn([new K0])}let xn=(()=>{class n{constructor(e){this.factories=e}static create(e,i){if(null!=i){const r=i.factories.slice();e=e.concat(r)}return new n(e)}static extend(e){return{provide:n,useFactory:i=>n.create(e,i||eD()),deps:[[n,new Cn,new Tt]]}}find(e){const i=this.factories.find(r=>r.supports(e));if(null!=i)return i;throw new H(901,\"\")}}return n.\\u0275prov=k({token:n,providedIn:\"root\",factory:eD}),n})();function tD(){return new _a([new J0])}let _a=(()=>{class n{constructor(e){this.factories=e}static create(e,i){if(i){const r=i.factories.slice();e=e.concat(r)}return new n(e)}static extend(e){return{provide:n,useFactory:i=>n.create(e,i||tD()),deps:[[n,new Cn,new Tt]]}}find(e){const i=this.factories.find(s=>s.supports(e));if(i)return i;throw new H(901,\"\")}}return n.\\u0275prov=k({token:n,providedIn:\"root\",factory:tD}),n})();const cN=H0(null,\"core\",[{provide:bc,useValue:\"unknown\"},{provide:z0,deps:[dt]},{provide:L0,deps:[]},{provide:O0,deps:[]}]);let dN=(()=>{class n{constructor(e){}}return n.\\u0275fac=function(e){return new(e||n)(y(Cc))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),Mc=null;function mi(){return Mc}const ie=new b(\"DocumentToken\");let Pr=(()=>{class n{historyGo(e){throw new Error(\"Not implemented\")}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:function(){return function fN(){return y(nD)}()},providedIn:\"platform\"}),n})();const mN=new b(\"Location Initialized\");let nD=(()=>{class n extends Pr{constructor(e){super(),this._doc=e,this._init()}_init(){this.location=window.location,this._history=window.history}getBaseHrefFromDOM(){return mi().getBaseHref(this._doc)}onPopState(e){const i=mi().getGlobalEventTarget(this._doc,\"window\");return i.addEventListener(\"popstate\",e,!1),()=>i.removeEventListener(\"popstate\",e)}onHashChange(e){const i=mi().getGlobalEventTarget(this._doc,\"window\");return i.addEventListener(\"hashchange\",e,!1),()=>i.removeEventListener(\"hashchange\",e)}get href(){return this.location.href}get protocol(){return this.location.protocol}get hostname(){return this.location.hostname}get port(){return this.location.port}get pathname(){return this.location.pathname}get search(){return this.location.search}get hash(){return this.location.hash}set pathname(e){this.location.pathname=e}pushState(e,i,r){iD()?this._history.pushState(e,i,r):this.location.hash=r}replaceState(e,i,r){iD()?this._history.replaceState(e,i,r):this.location.hash=r}forward(){this._history.forward()}back(){this._history.back()}historyGo(e=0){this._history.go(e)}getState(){return this._history.state}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:function(){return function gN(){return new nD(y(ie))}()},providedIn:\"platform\"}),n})();function iD(){return!!window.history.pushState}function Zp(n,t){if(0==n.length)return t;if(0==t.length)return n;let e=0;return n.endsWith(\"/\")&&e++,t.startsWith(\"/\")&&e++,2==e?n+t.substring(1):1==e?n+t:n+\"/\"+t}function rD(n){const t=n.match(/#|\\?|$/),e=t&&t.index||n.length;return n.slice(0,e-(\"/\"===n[e-1]?1:0))+n.slice(e)}function Pi(n){return n&&\"?\"!==n[0]?\"?\"+n:n}let qs=(()=>{class n{historyGo(e){throw new Error(\"Not implemented\")}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:function(){return function _N(n){const t=y(ie).location;return new sD(y(Pr),t&&t.origin||\"\")}()},providedIn:\"root\"}),n})();const Xp=new b(\"appBaseHref\");let sD=(()=>{class n extends qs{constructor(e,i){if(super(),this._platformLocation=e,this._removeListenerFns=[],null==i&&(i=this._platformLocation.getBaseHrefFromDOM()),null==i)throw new Error(\"No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.\");this._baseHref=i}ngOnDestroy(){for(;this._removeListenerFns.length;)this._removeListenerFns.pop()()}onPopState(e){this._removeListenerFns.push(this._platformLocation.onPopState(e),this._platformLocation.onHashChange(e))}getBaseHref(){return this._baseHref}prepareExternalUrl(e){return Zp(this._baseHref,e)}path(e=!1){const i=this._platformLocation.pathname+Pi(this._platformLocation.search),r=this._platformLocation.hash;return r&&e?`${i}${r}`:i}pushState(e,i,r,s){const o=this.prepareExternalUrl(r+Pi(s));this._platformLocation.pushState(e,i,o)}replaceState(e,i,r,s){const o=this.prepareExternalUrl(r+Pi(s));this._platformLocation.replaceState(e,i,o)}forward(){this._platformLocation.forward()}back(){this._platformLocation.back()}historyGo(e=0){var i,r;null===(r=(i=this._platformLocation).historyGo)||void 0===r||r.call(i,e)}}return n.\\u0275fac=function(e){return new(e||n)(y(Pr),y(Xp,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),vN=(()=>{class n extends qs{constructor(e,i){super(),this._platformLocation=e,this._baseHref=\"\",this._removeListenerFns=[],null!=i&&(this._baseHref=i)}ngOnDestroy(){for(;this._removeListenerFns.length;)this._removeListenerFns.pop()()}onPopState(e){this._removeListenerFns.push(this._platformLocation.onPopState(e),this._platformLocation.onHashChange(e))}getBaseHref(){return this._baseHref}path(e=!1){let i=this._platformLocation.hash;return null==i&&(i=\"#\"),i.length>0?i.substring(1):i}prepareExternalUrl(e){const i=Zp(this._baseHref,e);return i.length>0?\"#\"+i:i}pushState(e,i,r,s){let o=this.prepareExternalUrl(r+Pi(s));0==o.length&&(o=this._platformLocation.pathname),this._platformLocation.pushState(e,i,o)}replaceState(e,i,r,s){let o=this.prepareExternalUrl(r+Pi(s));0==o.length&&(o=this._platformLocation.pathname),this._platformLocation.replaceState(e,i,o)}forward(){this._platformLocation.forward()}back(){this._platformLocation.back()}historyGo(e=0){var i,r;null===(r=(i=this._platformLocation).historyGo)||void 0===r||r.call(i,e)}}return n.\\u0275fac=function(e){return new(e||n)(y(Pr),y(Xp,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),va=(()=>{class n{constructor(e,i){this._subject=new $,this._urlChangeListeners=[],this._platformStrategy=e;const r=this._platformStrategy.getBaseHref();this._platformLocation=i,this._baseHref=rD(oD(r)),this._platformStrategy.onPopState(s=>{this._subject.emit({url:this.path(!0),pop:!0,state:s.state,type:s.type})})}path(e=!1){return this.normalize(this._platformStrategy.path(e))}getState(){return this._platformLocation.getState()}isCurrentPathEqualTo(e,i=\"\"){return this.path()==this.normalize(e+Pi(i))}normalize(e){return n.stripTrailingSlash(function bN(n,t){return n&&t.startsWith(n)?t.substring(n.length):t}(this._baseHref,oD(e)))}prepareExternalUrl(e){return e&&\"/\"!==e[0]&&(e=\"/\"+e),this._platformStrategy.prepareExternalUrl(e)}go(e,i=\"\",r=null){this._platformStrategy.pushState(r,\"\",e,i),this._notifyUrlChangeListeners(this.prepareExternalUrl(e+Pi(i)),r)}replaceState(e,i=\"\",r=null){this._platformStrategy.replaceState(r,\"\",e,i),this._notifyUrlChangeListeners(this.prepareExternalUrl(e+Pi(i)),r)}forward(){this._platformStrategy.forward()}back(){this._platformStrategy.back()}historyGo(e=0){var i,r;null===(r=(i=this._platformStrategy).historyGo)||void 0===r||r.call(i,e)}onUrlChange(e){this._urlChangeListeners.push(e),this._urlChangeSubscription||(this._urlChangeSubscription=this.subscribe(i=>{this._notifyUrlChangeListeners(i.url,i.state)}))}_notifyUrlChangeListeners(e=\"\",i){this._urlChangeListeners.forEach(r=>r(e,i))}subscribe(e,i,r){return this._subject.subscribe({next:e,error:i,complete:r})}}return n.normalizeQueryParams=Pi,n.joinWithSlash=Zp,n.stripTrailingSlash=rD,n.\\u0275fac=function(e){return new(e||n)(y(qs),y(Pr))},n.\\u0275prov=k({token:n,factory:function(){return function yN(){return new va(y(qs),y(Pr))}()},providedIn:\"root\"}),n})();function oD(n){return n.replace(/\\/index.html$/,\"\")}let mD=(()=>{class n{constructor(e,i,r,s){this._iterableDiffers=e,this._keyValueDiffers=i,this._ngEl=r,this._renderer=s,this._iterableDiffer=null,this._keyValueDiffer=null,this._initialClasses=[],this._rawClass=null}set klass(e){this._removeClasses(this._initialClasses),this._initialClasses=\"string\"==typeof e?e.split(/\\s+/):[],this._applyClasses(this._initialClasses),this._applyClasses(this._rawClass)}set ngClass(e){this._removeClasses(this._rawClass),this._applyClasses(this._initialClasses),this._iterableDiffer=null,this._keyValueDiffer=null,this._rawClass=\"string\"==typeof e?e.split(/\\s+/):e,this._rawClass&&(ta(this._rawClass)?this._iterableDiffer=this._iterableDiffers.find(this._rawClass).create():this._keyValueDiffer=this._keyValueDiffers.find(this._rawClass).create())}ngDoCheck(){if(this._iterableDiffer){const e=this._iterableDiffer.diff(this._rawClass);e&&this._applyIterableChanges(e)}else if(this._keyValueDiffer){const e=this._keyValueDiffer.diff(this._rawClass);e&&this._applyKeyValueChanges(e)}}_applyKeyValueChanges(e){e.forEachAddedItem(i=>this._toggleClass(i.key,i.currentValue)),e.forEachChangedItem(i=>this._toggleClass(i.key,i.currentValue)),e.forEachRemovedItem(i=>{i.previousValue&&this._toggleClass(i.key,!1)})}_applyIterableChanges(e){e.forEachAddedItem(i=>{if(\"string\"!=typeof i.item)throw new Error(`NgClass can only toggle CSS classes expressed as strings, got ${Re(i.item)}`);this._toggleClass(i.item,!0)}),e.forEachRemovedItem(i=>this._toggleClass(i.item,!1))}_applyClasses(e){e&&(Array.isArray(e)||e instanceof Set?e.forEach(i=>this._toggleClass(i,!0)):Object.keys(e).forEach(i=>this._toggleClass(i,!!e[i])))}_removeClasses(e){e&&(Array.isArray(e)||e instanceof Set?e.forEach(i=>this._toggleClass(i,!1)):Object.keys(e).forEach(i=>this._toggleClass(i,!1)))}_toggleClass(e,i){(e=e.trim())&&e.split(/\\s+/g).forEach(r=>{i?this._renderer.addClass(this._ngEl.nativeElement,r):this._renderer.removeClass(this._ngEl.nativeElement,r)})}}return n.\\u0275fac=function(e){return new(e||n)(f(xn),f(_a),f(W),f(Ii))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngClass\",\"\"]],inputs:{klass:[\"class\",\"klass\"],ngClass:\"ngClass\"}}),n})();class sL{constructor(t,e,i,r){this.$implicit=t,this.ngForOf=e,this.index=i,this.count=r}get first(){return 0===this.index}get last(){return this.index===this.count-1}get even(){return this.index%2==0}get odd(){return!this.even}}let gD=(()=>{class n{constructor(e,i,r){this._viewContainer=e,this._template=i,this._differs=r,this._ngForOf=null,this._ngForOfDirty=!0,this._differ=null}set ngForOf(e){this._ngForOf=e,this._ngForOfDirty=!0}set ngForTrackBy(e){this._trackByFn=e}get ngForTrackBy(){return this._trackByFn}set ngForTemplate(e){e&&(this._template=e)}ngDoCheck(){if(this._ngForOfDirty){this._ngForOfDirty=!1;const e=this._ngForOf;!this._differ&&e&&(this._differ=this._differs.find(e).create(this.ngForTrackBy))}if(this._differ){const e=this._differ.diff(this._ngForOf);e&&this._applyChanges(e)}}_applyChanges(e){const i=this._viewContainer;e.forEachOperation((r,s,o)=>{if(null==r.previousIndex)i.createEmbeddedView(this._template,new sL(r.item,this._ngForOf,-1,-1),null===o?void 0:o);else if(null==o)i.remove(null===s?void 0:s);else if(null!==s){const a=i.get(s);i.move(a,o),_D(a,r)}});for(let r=0,s=i.length;r<s;r++){const a=i.get(r).context;a.index=r,a.count=s,a.ngForOf=this._ngForOf}e.forEachIdentityChange(r=>{_D(i.get(r.currentIndex),r)})}static ngTemplateContextGuard(e,i){return!0}}return n.\\u0275fac=function(e){return new(e||n)(f(st),f(ut),f(xn))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngFor\",\"\",\"ngForOf\",\"\"]],inputs:{ngForOf:\"ngForOf\",ngForTrackBy:\"ngForTrackBy\",ngForTemplate:\"ngForTemplate\"}}),n})();function _D(n,t){n.context.$implicit=t.item}let Ca=(()=>{class n{constructor(e,i){this._viewContainer=e,this._context=new oL,this._thenTemplateRef=null,this._elseTemplateRef=null,this._thenViewRef=null,this._elseViewRef=null,this._thenTemplateRef=i}set ngIf(e){this._context.$implicit=this._context.ngIf=e,this._updateView()}set ngIfThen(e){vD(\"ngIfThen\",e),this._thenTemplateRef=e,this._thenViewRef=null,this._updateView()}set ngIfElse(e){vD(\"ngIfElse\",e),this._elseTemplateRef=e,this._elseViewRef=null,this._updateView()}_updateView(){this._context.$implicit?this._thenViewRef||(this._viewContainer.clear(),this._elseViewRef=null,this._thenTemplateRef&&(this._thenViewRef=this._viewContainer.createEmbeddedView(this._thenTemplateRef,this._context))):this._elseViewRef||(this._viewContainer.clear(),this._thenViewRef=null,this._elseTemplateRef&&(this._elseViewRef=this._viewContainer.createEmbeddedView(this._elseTemplateRef,this._context)))}static ngTemplateContextGuard(e,i){return!0}}return n.\\u0275fac=function(e){return new(e||n)(f(st),f(ut))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngIf\",\"\"]],inputs:{ngIf:\"ngIf\",ngIfThen:\"ngIfThen\",ngIfElse:\"ngIfElse\"}}),n})();class oL{constructor(){this.$implicit=null,this.ngIf=null}}function vD(n,t){if(t&&!t.createEmbeddedView)throw new Error(`${n} must be a TemplateRef, but received '${Re(t)}'.`)}class df{constructor(t,e){this._viewContainerRef=t,this._templateRef=e,this._created=!1}create(){this._created=!0,this._viewContainerRef.createEmbeddedView(this._templateRef)}destroy(){this._created=!1,this._viewContainerRef.clear()}enforceState(t){t&&!this._created?this.create():!t&&this._created&&this.destroy()}}let Ys=(()=>{class n{constructor(){this._defaultUsed=!1,this._caseCount=0,this._lastCaseCheckIndex=0,this._lastCasesMatched=!1}set ngSwitch(e){this._ngSwitch=e,0===this._caseCount&&this._updateDefaultCases(!0)}_addCase(){return this._caseCount++}_addDefault(e){this._defaultViews||(this._defaultViews=[]),this._defaultViews.push(e)}_matchCase(e){const i=e==this._ngSwitch;return this._lastCasesMatched=this._lastCasesMatched||i,this._lastCaseCheckIndex++,this._lastCaseCheckIndex===this._caseCount&&(this._updateDefaultCases(!this._lastCasesMatched),this._lastCaseCheckIndex=0,this._lastCasesMatched=!1),i}_updateDefaultCases(e){if(this._defaultViews&&e!==this._defaultUsed){this._defaultUsed=e;for(let i=0;i<this._defaultViews.length;i++)this._defaultViews[i].enforceState(e)}}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngSwitch\",\"\"]],inputs:{ngSwitch:\"ngSwitch\"}}),n})(),Pc=(()=>{class n{constructor(e,i,r){this.ngSwitch=r,r._addCase(),this._view=new df(e,i)}ngDoCheck(){this._view.enforceState(this.ngSwitch._matchCase(this.ngSwitchCase))}}return n.\\u0275fac=function(e){return new(e||n)(f(st),f(ut),f(Ys,9))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngSwitchCase\",\"\"]],inputs:{ngSwitchCase:\"ngSwitchCase\"}}),n})(),yD=(()=>{class n{constructor(e,i,r){r._addDefault(new df(e,i))}}return n.\\u0275fac=function(e){return new(e||n)(f(st),f(ut),f(Ys,9))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngSwitchDefault\",\"\"]]}),n})(),bt=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const wD=\"browser\";let PL=(()=>{class n{}return n.\\u0275prov=k({token:n,providedIn:\"root\",factory:()=>new FL(y(ie),window)}),n})();class FL{constructor(t,e){this.document=t,this.window=e,this.offset=()=>[0,0]}setOffset(t){this.offset=Array.isArray(t)?()=>t:t}getScrollPosition(){return this.supportsScrolling()?[this.window.pageXOffset,this.window.pageYOffset]:[0,0]}scrollToPosition(t){this.supportsScrolling()&&this.window.scrollTo(t[0],t[1])}scrollToAnchor(t){if(!this.supportsScrolling())return;const e=function NL(n,t){const e=n.getElementById(t)||n.getElementsByName(t)[0];if(e)return e;if(\"function\"==typeof n.createTreeWalker&&n.body&&(n.body.createShadowRoot||n.body.attachShadow)){const i=n.createTreeWalker(n.body,NodeFilter.SHOW_ELEMENT);let r=i.currentNode;for(;r;){const s=r.shadowRoot;if(s){const o=s.getElementById(t)||s.querySelector(`[name=\"${t}\"]`);if(o)return o}r=i.nextNode()}}return null}(this.document,t);e&&(this.scrollToElement(e),e.focus())}setHistoryScrollRestoration(t){if(this.supportScrollRestoration()){const e=this.window.history;e&&e.scrollRestoration&&(e.scrollRestoration=t)}}scrollToElement(t){const e=t.getBoundingClientRect(),i=e.left+this.window.pageXOffset,r=e.top+this.window.pageYOffset,s=this.offset();this.window.scrollTo(i-s[0],r-s[1])}supportScrollRestoration(){try{if(!this.supportsScrolling())return!1;const t=MD(this.window.history)||MD(Object.getPrototypeOf(this.window.history));return!(!t||!t.writable&&!t.set)}catch(t){return!1}}supportsScrolling(){try{return!!this.window&&!!this.window.scrollTo&&\"pageXOffset\"in this.window}catch(t){return!1}}}function MD(n){return Object.getOwnPropertyDescriptor(n,\"scrollRestoration\")}class pf extends class BL extends class pN{}{constructor(){super(...arguments),this.supportsDOMEvents=!0}}{static makeCurrent(){!function hN(n){Mc||(Mc=n)}(new pf)}onAndCancel(t,e,i){return t.addEventListener(e,i,!1),()=>{t.removeEventListener(e,i,!1)}}dispatchEvent(t,e){t.dispatchEvent(e)}remove(t){t.parentNode&&t.parentNode.removeChild(t)}createElement(t,e){return(e=e||this.getDefaultDocument()).createElement(t)}createHtmlDocument(){return document.implementation.createHTMLDocument(\"fakeTitle\")}getDefaultDocument(){return document}isElementNode(t){return t.nodeType===Node.ELEMENT_NODE}isShadowRoot(t){return t instanceof DocumentFragment}getGlobalEventTarget(t,e){return\"window\"===e?window:\"document\"===e?t:\"body\"===e?t.body:null}getBaseHref(t){const e=function VL(){return Da=Da||document.querySelector(\"base\"),Da?Da.getAttribute(\"href\"):null}();return null==e?null:function HL(n){Fc=Fc||document.createElement(\"a\"),Fc.setAttribute(\"href\",n);const t=Fc.pathname;return\"/\"===t.charAt(0)?t:`/${t}`}(e)}resetBaseElement(){Da=null}getUserAgent(){return window.navigator.userAgent}getCookie(t){return function iL(n,t){t=encodeURIComponent(t);for(const e of n.split(\";\")){const i=e.indexOf(\"=\"),[r,s]=-1==i?[e,\"\"]:[e.slice(0,i),e.slice(i+1)];if(r.trim()===t)return decodeURIComponent(s)}return null}(document.cookie,t)}}let Fc,Da=null;const xD=new b(\"TRANSITION_ID\"),zL=[{provide:Bp,useFactory:function jL(n,t,e){return()=>{e.get(Vp).donePromise.then(()=>{const i=mi(),r=t.querySelectorAll(`style[ng-transition=\"${n}\"]`);for(let s=0;s<r.length;s++)i.remove(r[s])})}},deps:[xD,ie,dt],multi:!0}];class ff{static init(){!function HF(n){Gp=n}(new ff)}addToWindow(t){Oe.getAngularTestability=(i,r=!0)=>{const s=t.findTestabilityInTree(i,r);if(null==s)throw new Error(\"Could not find testability for element.\");return s},Oe.getAllAngularTestabilities=()=>t.getAllTestabilities(),Oe.getAllAngularRootElements=()=>t.getAllRootElements(),Oe.frameworkStabilizers||(Oe.frameworkStabilizers=[]),Oe.frameworkStabilizers.push(i=>{const r=Oe.getAllAngularTestabilities();let s=r.length,o=!1;const a=function(l){o=o||l,s--,0==s&&i(o)};r.forEach(function(l){l.whenStable(a)})})}findTestabilityInTree(t,e,i){if(null==e)return null;const r=t.getTestability(e);return null!=r?r:i?mi().isShadowRoot(e)?this.findTestabilityInTree(t,e.host,!0):this.findTestabilityInTree(t,e.parentElement,!0):null}}let UL=(()=>{class n{build(){return new XMLHttpRequest}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const Nc=new b(\"EventManagerPlugins\");let Lc=(()=>{class n{constructor(e,i){this._zone=i,this._eventNameToPlugin=new Map,e.forEach(r=>r.manager=this),this._plugins=e.slice().reverse()}addEventListener(e,i,r){return this._findPluginFor(i).addEventListener(e,i,r)}addGlobalEventListener(e,i,r){return this._findPluginFor(i).addGlobalEventListener(e,i,r)}getZone(){return this._zone}_findPluginFor(e){const i=this._eventNameToPlugin.get(e);if(i)return i;const r=this._plugins;for(let s=0;s<r.length;s++){const o=r[s];if(o.supports(e))return this._eventNameToPlugin.set(e,o),o}throw new Error(`No event manager plugin found for event ${e}`)}}return n.\\u0275fac=function(e){return new(e||n)(y(Nc),y(ne))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class ED{constructor(t){this._doc=t}addGlobalEventListener(t,e,i){const r=mi().getGlobalEventTarget(this._doc,t);if(!r)throw new Error(`Unsupported event target ${r} for event ${e}`);return this.addEventListener(r,e,i)}}let SD=(()=>{class n{constructor(){this._stylesSet=new Set}addStyles(e){const i=new Set;e.forEach(r=>{this._stylesSet.has(r)||(this._stylesSet.add(r),i.add(r))}),this.onStylesAdded(i)}onStylesAdded(e){}getAllStyles(){return Array.from(this._stylesSet)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),wa=(()=>{class n extends SD{constructor(e){super(),this._doc=e,this._hostNodes=new Map,this._hostNodes.set(e.head,[])}_addStylesToHost(e,i,r){e.forEach(s=>{const o=this._doc.createElement(\"style\");o.textContent=s,r.push(i.appendChild(o))})}addHost(e){const i=[];this._addStylesToHost(this._stylesSet,e,i),this._hostNodes.set(e,i)}removeHost(e){const i=this._hostNodes.get(e);i&&i.forEach(kD),this._hostNodes.delete(e)}onStylesAdded(e){this._hostNodes.forEach((i,r)=>{this._addStylesToHost(e,r,i)})}ngOnDestroy(){this._hostNodes.forEach(e=>e.forEach(kD))}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();function kD(n){mi().remove(n)}const mf={svg:\"http://www.w3.org/2000/svg\",xhtml:\"http://www.w3.org/1999/xhtml\",xlink:\"http://www.w3.org/1999/xlink\",xml:\"http://www.w3.org/XML/1998/namespace\",xmlns:\"http://www.w3.org/2000/xmlns/\",math:\"http://www.w3.org/1998/MathML/\"},gf=/%COMP%/g;function Bc(n,t,e){for(let i=0;i<t.length;i++){let r=t[i];Array.isArray(r)?Bc(n,r,e):(r=r.replace(gf,n),e.push(r))}return e}function ID(n){return t=>{if(\"__ngUnwrap__\"===t)return n;!1===n(t)&&(t.preventDefault(),t.returnValue=!1)}}let Vc=(()=>{class n{constructor(e,i,r){this.eventManager=e,this.sharedStylesHost=i,this.appId=r,this.rendererByCompId=new Map,this.defaultRenderer=new _f(e)}createRenderer(e,i){if(!e||!i)return this.defaultRenderer;switch(i.encapsulation){case Ln.Emulated:{let r=this.rendererByCompId.get(i.id);return r||(r=new QL(this.eventManager,this.sharedStylesHost,i,this.appId),this.rendererByCompId.set(i.id,r)),r.applyToHost(e),r}case 1:case Ln.ShadowDom:return new KL(this.eventManager,this.sharedStylesHost,e,i);default:if(!this.rendererByCompId.has(i.id)){const r=Bc(i.id,i.styles,[]);this.sharedStylesHost.addStyles(r),this.rendererByCompId.set(i.id,this.defaultRenderer)}return this.defaultRenderer}}begin(){}end(){}}return n.\\u0275fac=function(e){return new(e||n)(y(Lc),y(wa),y(ga))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class _f{constructor(t){this.eventManager=t,this.data=Object.create(null),this.destroyNode=null}destroy(){}createElement(t,e){return e?document.createElementNS(mf[e]||e,t):document.createElement(t)}createComment(t){return document.createComment(t)}createText(t){return document.createTextNode(t)}appendChild(t,e){t.appendChild(e)}insertBefore(t,e,i){t&&t.insertBefore(e,i)}removeChild(t,e){t&&t.removeChild(e)}selectRootElement(t,e){let i=\"string\"==typeof t?document.querySelector(t):t;if(!i)throw new Error(`The selector \"${t}\" did not match any elements`);return e||(i.textContent=\"\"),i}parentNode(t){return t.parentNode}nextSibling(t){return t.nextSibling}setAttribute(t,e,i,r){if(r){e=r+\":\"+e;const s=mf[r];s?t.setAttributeNS(s,e,i):t.setAttribute(e,i)}else t.setAttribute(e,i)}removeAttribute(t,e,i){if(i){const r=mf[i];r?t.removeAttributeNS(r,e):t.removeAttribute(`${i}:${e}`)}else t.removeAttribute(e)}addClass(t,e){t.classList.add(e)}removeClass(t,e){t.classList.remove(e)}setStyle(t,e,i,r){r&(an.DashCase|an.Important)?t.style.setProperty(e,i,r&an.Important?\"important\":\"\"):t.style[e]=i}removeStyle(t,e,i){i&an.DashCase?t.style.removeProperty(e):t.style[e]=\"\"}setProperty(t,e,i){t[e]=i}setValue(t,e){t.nodeValue=e}listen(t,e,i){return\"string\"==typeof t?this.eventManager.addGlobalEventListener(t,e,ID(i)):this.eventManager.addEventListener(t,e,ID(i))}}class QL extends _f{constructor(t,e,i,r){super(t),this.component=i;const s=Bc(r+\"-\"+i.id,i.styles,[]);e.addStyles(s),this.contentAttr=function WL(n){return\"_ngcontent-%COMP%\".replace(gf,n)}(r+\"-\"+i.id),this.hostAttr=function qL(n){return\"_nghost-%COMP%\".replace(gf,n)}(r+\"-\"+i.id)}applyToHost(t){super.setAttribute(t,this.hostAttr,\"\")}createElement(t,e){const i=super.createElement(t,e);return super.setAttribute(i,this.contentAttr,\"\"),i}}class KL extends _f{constructor(t,e,i,r){super(t),this.sharedStylesHost=e,this.hostEl=i,this.shadowRoot=i.attachShadow({mode:\"open\"}),this.sharedStylesHost.addHost(this.shadowRoot);const s=Bc(r.id,r.styles,[]);for(let o=0;o<s.length;o++){const a=document.createElement(\"style\");a.textContent=s[o],this.shadowRoot.appendChild(a)}}nodeOrShadowRoot(t){return t===this.hostEl?this.shadowRoot:t}destroy(){this.sharedStylesHost.removeHost(this.shadowRoot)}appendChild(t,e){return super.appendChild(this.nodeOrShadowRoot(t),e)}insertBefore(t,e,i){return super.insertBefore(this.nodeOrShadowRoot(t),e,i)}removeChild(t,e){return super.removeChild(this.nodeOrShadowRoot(t),e)}parentNode(t){return this.nodeOrShadowRoot(super.parentNode(this.nodeOrShadowRoot(t)))}}let ZL=(()=>{class n extends ED{constructor(e){super(e)}supports(e){return!0}addEventListener(e,i,r){return e.addEventListener(i,r,!1),()=>this.removeEventListener(e,i,r)}removeEventListener(e,i,r){return e.removeEventListener(i,r)}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const OD=[\"alt\",\"control\",\"meta\",\"shift\"],JL={\"\\b\":\"Backspace\",\"\\t\":\"Tab\",\"\\x7f\":\"Delete\",\"\\x1b\":\"Escape\",Del:\"Delete\",Esc:\"Escape\",Left:\"ArrowLeft\",Right:\"ArrowRight\",Up:\"ArrowUp\",Down:\"ArrowDown\",Menu:\"ContextMenu\",Scroll:\"ScrollLock\",Win:\"OS\"},PD={A:\"1\",B:\"2\",C:\"3\",D:\"4\",E:\"5\",F:\"6\",G:\"7\",H:\"8\",I:\"9\",J:\"*\",K:\"+\",M:\"-\",N:\".\",O:\"/\",\"`\":\"0\",\"\\x90\":\"NumLock\"},eB={alt:n=>n.altKey,control:n=>n.ctrlKey,meta:n=>n.metaKey,shift:n=>n.shiftKey};let tB=(()=>{class n extends ED{constructor(e){super(e)}supports(e){return null!=n.parseEventName(e)}addEventListener(e,i,r){const s=n.parseEventName(i),o=n.eventCallback(s.fullKey,r,this.manager.getZone());return this.manager.getZone().runOutsideAngular(()=>mi().onAndCancel(e,s.domEventName,o))}static parseEventName(e){const i=e.toLowerCase().split(\".\"),r=i.shift();if(0===i.length||\"keydown\"!==r&&\"keyup\"!==r)return null;const s=n._normalizeKey(i.pop());let o=\"\";if(OD.forEach(l=>{const c=i.indexOf(l);c>-1&&(i.splice(c,1),o+=l+\".\")}),o+=s,0!=i.length||0===s.length)return null;const a={};return a.domEventName=r,a.fullKey=o,a}static getEventFullKey(e){let i=\"\",r=function nB(n){let t=n.key;if(null==t){if(t=n.keyIdentifier,null==t)return\"Unidentified\";t.startsWith(\"U+\")&&(t=String.fromCharCode(parseInt(t.substring(2),16)),3===n.location&&PD.hasOwnProperty(t)&&(t=PD[t]))}return JL[t]||t}(e);return r=r.toLowerCase(),\" \"===r?r=\"space\":\".\"===r&&(r=\"dot\"),OD.forEach(s=>{s!=r&&eB[s](e)&&(i+=s+\".\")}),i+=r,i}static eventCallback(e,i,r){return s=>{n.getEventFullKey(s)===e&&r.runGuarded(()=>i(s))}}static _normalizeKey(e){return\"esc\"===e?\"escape\":e}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const oB=H0(cN,\"browser\",[{provide:bc,useValue:wD},{provide:I0,useValue:function iB(){pf.makeCurrent(),ff.init()},multi:!0},{provide:ie,useFactory:function sB(){return function DT(n){Bu=n}(document),document},deps:[]}]),aB=[{provide:Jh,useValue:\"root\"},{provide:Mr,useFactory:function rB(){return new Mr},deps:[]},{provide:Nc,useClass:ZL,multi:!0,deps:[ie,ne,bc]},{provide:Nc,useClass:tB,multi:!0,deps:[ie]},{provide:Vc,useClass:Vc,deps:[Lc,wa,ga]},{provide:da,useExisting:Vc},{provide:SD,useExisting:wa},{provide:wa,useClass:wa,deps:[ie]},{provide:$p,useClass:$p,deps:[ne]},{provide:Lc,useClass:Lc,deps:[Nc,ne]},{provide:class LL{},useClass:UL,deps:[]}];let FD=(()=>{class n{constructor(e){if(e)throw new Error(\"BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.\")}static withServerTransition(e){return{ngModule:n,providers:[{provide:ga,useValue:e.appId},{provide:xD,useExisting:ga},zL]}}}return n.\\u0275fac=function(e){return new(e||n)(y(n,12))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:aB,imports:[bt,dN]}),n})();function q(...n){return mt(n,So(n))}\"undefined\"!=typeof window&&window;class Zt extends O{constructor(t){super(),this._value=t}get value(){return this.getValue()}_subscribe(t){const e=super._subscribe(t);return!e.closed&&t.next(this._value),e}getValue(){const{hasError:t,thrownError:e,_value:i}=this;if(t)throw e;return this._throwIfClosed(),i}next(t){super.next(this._value=t)}}const{isArray:vB}=Array,{getPrototypeOf:yB,prototype:bB,keys:CB}=Object;function VD(n){if(1===n.length){const t=n[0];if(vB(t))return{args:t,keys:null};if(function DB(n){return n&&\"object\"==typeof n&&yB(n)===bB}(t)){const e=CB(t);return{args:e.map(i=>t[i]),keys:e}}}return{args:n,keys:null}}const{isArray:wB}=Array;function bf(n){return ue(t=>function MB(n,t){return wB(t)?n(...t):n(t)}(n,t))}function HD(n,t){return n.reduce((e,i,r)=>(e[i]=t[r],e),{})}function jD(n,t,e){n?Mi(e,n,t):t()}function Ma(n,t){const e=De(n)?n:()=>n,i=r=>r.error(e());return new Ve(t?r=>t.schedule(i,0,r):i)}const Hc=xo(n=>function(){n(this),this.name=\"EmptyError\",this.message=\"no elements in sequence\"});function jc(...n){return function SB(){return Eo(1)}()(mt(n,So(n)))}function xa(n){return new Ve(t=>{Jt(n()).subscribe(t)})}function zD(){return qe((n,t)=>{let e=null;n._refCount++;const i=Ue(t,void 0,void 0,void 0,()=>{if(!n||n._refCount<=0||0<--n._refCount)return void(e=null);const r=n._connection,s=e;e=null,r&&(!s||r===s)&&r.unsubscribe(),t.unsubscribe()});n.subscribe(i),i.closed||(e=n.connect())})}class kB extends Ve{constructor(t,e){super(),this.source=t,this.subjectFactory=e,this._subject=null,this._refCount=0,this._connection=null,o_(t)&&(this.lift=t.lift)}_subscribe(t){return this.getSubject().subscribe(t)}getSubject(){const t=this._subject;return(!t||t.isStopped)&&(this._subject=this.subjectFactory()),this._subject}_teardown(){this._refCount=0;const{_connection:t}=this;this._subject=this._connection=null,null==t||t.unsubscribe()}connect(){let t=this._connection;if(!t){t=this._connection=new ke;const e=this.getSubject();t.add(this.source.subscribe(Ue(e,void 0,()=>{this._teardown(),e.complete()},i=>{this._teardown(),e.error(i)},()=>this._teardown()))),t.closed&&(this._connection=null,t=ke.EMPTY)}return t}refCount(){return zD()(this)}}function kn(n,t){return qe((e,i)=>{let r=null,s=0,o=!1;const a=()=>o&&!r&&i.complete();e.subscribe(Ue(i,l=>{null==r||r.unsubscribe();let c=0;const d=s++;Jt(n(l,d)).subscribe(r=Ue(i,u=>i.next(t?t(l,u,d,c++):u),()=>{r=null,a()}))},()=>{o=!0,a()}))})}function Xn(...n){const t=So(n);return qe((e,i)=>{(t?jc(n,e,t):jc(n,e)).subscribe(i)})}function TB(n,t,e,i,r){return(s,o)=>{let a=e,l=t,c=0;s.subscribe(Ue(o,d=>{const u=c++;l=a?n(l,d,u):(a=!0,d),i&&o.next(l)},r&&(()=>{a&&o.next(l),o.complete()})))}}function UD(n,t){return qe(TB(n,t,arguments.length>=2,!0))}function Ct(n,t){return qe((e,i)=>{let r=0;e.subscribe(Ue(i,s=>n.call(t,s,r++)&&i.next(s)))})}function Ni(n){return qe((t,e)=>{let s,i=null,r=!1;i=t.subscribe(Ue(e,void 0,void 0,o=>{s=Jt(n(o,Ni(n)(t))),i?(i.unsubscribe(),i=null,s.subscribe(e)):r=!0})),r&&(i.unsubscribe(),i=null,s.subscribe(e))})}function Qs(n,t){return De(t)?lt(n,t,1):lt(n,1)}function Cf(n){return n<=0?()=>ri:qe((t,e)=>{let i=[];t.subscribe(Ue(e,r=>{i.push(r),n<i.length&&i.shift()},()=>{for(const r of i)e.next(r);e.complete()},void 0,()=>{i=null}))})}function $D(n=AB){return qe((t,e)=>{let i=!1;t.subscribe(Ue(e,r=>{i=!0,e.next(r)},()=>i?e.complete():e.error(n())))})}function AB(){return new Hc}function GD(n){return qe((t,e)=>{let i=!1;t.subscribe(Ue(e,r=>{i=!0,e.next(r)},()=>{i||e.next(n),e.complete()}))})}function Ks(n,t){const e=arguments.length>=2;return i=>i.pipe(n?Ct((r,s)=>n(r,s,i)):Wi,it(1),e?GD(t):$D(()=>new Hc))}function Mt(n,t,e){const i=De(n)||t||e?{next:n,error:t,complete:e}:n;return i?qe((r,s)=>{var o;null===(o=i.subscribe)||void 0===o||o.call(i);let a=!0;r.subscribe(Ue(s,l=>{var c;null===(c=i.next)||void 0===c||c.call(i,l),s.next(l)},()=>{var l;a=!1,null===(l=i.complete)||void 0===l||l.call(i),s.complete()},l=>{var c;a=!1,null===(c=i.error)||void 0===c||c.call(i,l),s.error(l)},()=>{var l,c;a&&(null===(l=i.unsubscribe)||void 0===l||l.call(i)),null===(c=i.finalize)||void 0===c||c.call(i)}))}):Wi}class Li{constructor(t,e){this.id=t,this.url=e}}class Df extends Li{constructor(t,e,i=\"imperative\",r=null){super(t,e),this.navigationTrigger=i,this.restoredState=r}toString(){return`NavigationStart(id: ${this.id}, url: '${this.url}')`}}class Ea extends Li{constructor(t,e,i){super(t,e),this.urlAfterRedirects=i}toString(){return`NavigationEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}')`}}class qD extends Li{constructor(t,e,i){super(t,e),this.reason=i}toString(){return`NavigationCancel(id: ${this.id}, url: '${this.url}')`}}class RB extends Li{constructor(t,e,i){super(t,e),this.error=i}toString(){return`NavigationError(id: ${this.id}, url: '${this.url}', error: ${this.error})`}}class OB extends Li{constructor(t,e,i,r){super(t,e),this.urlAfterRedirects=i,this.state=r}toString(){return`RoutesRecognized(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`}}class PB extends Li{constructor(t,e,i,r){super(t,e),this.urlAfterRedirects=i,this.state=r}toString(){return`GuardsCheckStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`}}class FB extends Li{constructor(t,e,i,r,s){super(t,e),this.urlAfterRedirects=i,this.state=r,this.shouldActivate=s}toString(){return`GuardsCheckEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state}, shouldActivate: ${this.shouldActivate})`}}class NB extends Li{constructor(t,e,i,r){super(t,e),this.urlAfterRedirects=i,this.state=r}toString(){return`ResolveStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`}}class LB extends Li{constructor(t,e,i,r){super(t,e),this.urlAfterRedirects=i,this.state=r}toString(){return`ResolveEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`}}class YD{constructor(t){this.route=t}toString(){return`RouteConfigLoadStart(path: ${this.route.path})`}}class QD{constructor(t){this.route=t}toString(){return`RouteConfigLoadEnd(path: ${this.route.path})`}}class BB{constructor(t){this.snapshot=t}toString(){return`ChildActivationStart(path: '${this.snapshot.routeConfig&&this.snapshot.routeConfig.path||\"\"}')`}}class VB{constructor(t){this.snapshot=t}toString(){return`ChildActivationEnd(path: '${this.snapshot.routeConfig&&this.snapshot.routeConfig.path||\"\"}')`}}class HB{constructor(t){this.snapshot=t}toString(){return`ActivationStart(path: '${this.snapshot.routeConfig&&this.snapshot.routeConfig.path||\"\"}')`}}class jB{constructor(t){this.snapshot=t}toString(){return`ActivationEnd(path: '${this.snapshot.routeConfig&&this.snapshot.routeConfig.path||\"\"}')`}}class KD{constructor(t,e,i){this.routerEvent=t,this.position=e,this.anchor=i}toString(){return`Scroll(anchor: '${this.anchor}', position: '${this.position?`${this.position[0]}, ${this.position[1]}`:null}')`}}const me=\"primary\";class zB{constructor(t){this.params=t||{}}has(t){return Object.prototype.hasOwnProperty.call(this.params,t)}get(t){if(this.has(t)){const e=this.params[t];return Array.isArray(e)?e[0]:e}return null}getAll(t){if(this.has(t)){const e=this.params[t];return Array.isArray(e)?e:[e]}return[]}get keys(){return Object.keys(this.params)}}function Zs(n){return new zB(n)}const ZD=\"ngNavigationCancelingError\";function wf(n){const t=Error(\"NavigationCancelingError: \"+n);return t[ZD]=!0,t}function $B(n,t,e){const i=e.path.split(\"/\");if(i.length>n.length||\"full\"===e.pathMatch&&(t.hasChildren()||i.length<n.length))return null;const r={};for(let s=0;s<i.length;s++){const o=i[s],a=n[s];if(o.startsWith(\":\"))r[o.substring(1)]=a;else if(o!==a.path)return null}return{consumed:n.slice(0,i.length),posParams:r}}function gi(n,t){const e=n?Object.keys(n):void 0,i=t?Object.keys(t):void 0;if(!e||!i||e.length!=i.length)return!1;let r;for(let s=0;s<e.length;s++)if(r=e[s],!XD(n[r],t[r]))return!1;return!0}function XD(n,t){if(Array.isArray(n)&&Array.isArray(t)){if(n.length!==t.length)return!1;const e=[...n].sort(),i=[...t].sort();return e.every((r,s)=>i[s]===r)}return n===t}function JD(n){return Array.prototype.concat.apply([],n)}function ew(n){return n.length>0?n[n.length-1]:null}function At(n,t){for(const e in n)n.hasOwnProperty(e)&&t(n[e],e)}function _i(n){return up(n)?n:ra(n)?mt(Promise.resolve(n)):q(n)}const qB={exact:function iw(n,t,e){if(!Nr(n.segments,t.segments)||!zc(n.segments,t.segments,e)||n.numberOfChildren!==t.numberOfChildren)return!1;for(const i in t.children)if(!n.children[i]||!iw(n.children[i],t.children[i],e))return!1;return!0},subset:rw},tw={exact:function YB(n,t){return gi(n,t)},subset:function QB(n,t){return Object.keys(t).length<=Object.keys(n).length&&Object.keys(t).every(e=>XD(n[e],t[e]))},ignored:()=>!0};function nw(n,t,e){return qB[e.paths](n.root,t.root,e.matrixParams)&&tw[e.queryParams](n.queryParams,t.queryParams)&&!(\"exact\"===e.fragment&&n.fragment!==t.fragment)}function rw(n,t,e){return sw(n,t,t.segments,e)}function sw(n,t,e,i){if(n.segments.length>e.length){const r=n.segments.slice(0,e.length);return!(!Nr(r,e)||t.hasChildren()||!zc(r,e,i))}if(n.segments.length===e.length){if(!Nr(n.segments,e)||!zc(n.segments,e,i))return!1;for(const r in t.children)if(!n.children[r]||!rw(n.children[r],t.children[r],i))return!1;return!0}{const r=e.slice(0,n.segments.length),s=e.slice(n.segments.length);return!!(Nr(n.segments,r)&&zc(n.segments,r,i)&&n.children[me])&&sw(n.children[me],t,s,i)}}function zc(n,t,e){return t.every((i,r)=>tw[e](n[r].parameters,i.parameters))}class Fr{constructor(t,e,i){this.root=t,this.queryParams=e,this.fragment=i}get queryParamMap(){return this._queryParamMap||(this._queryParamMap=Zs(this.queryParams)),this._queryParamMap}toString(){return XB.serialize(this)}}class ye{constructor(t,e){this.segments=t,this.children=e,this.parent=null,At(e,(i,r)=>i.parent=this)}hasChildren(){return this.numberOfChildren>0}get numberOfChildren(){return Object.keys(this.children).length}toString(){return Uc(this)}}class Sa{constructor(t,e){this.path=t,this.parameters=e}get parameterMap(){return this._parameterMap||(this._parameterMap=Zs(this.parameters)),this._parameterMap}toString(){return dw(this)}}function Nr(n,t){return n.length===t.length&&n.every((e,i)=>e.path===t[i].path)}class ow{}class aw{parse(t){const e=new aV(t);return new Fr(e.parseRootSegment(),e.parseQueryParams(),e.parseFragment())}serialize(t){const e=`/${ka(t.root,!0)}`,i=function tV(n){const t=Object.keys(n).map(e=>{const i=n[e];return Array.isArray(i)?i.map(r=>`${$c(e)}=${$c(r)}`).join(\"&\"):`${$c(e)}=${$c(i)}`}).filter(e=>!!e);return t.length?`?${t.join(\"&\")}`:\"\"}(t.queryParams);return`${e}${i}${\"string\"==typeof t.fragment?`#${function JB(n){return encodeURI(n)}(t.fragment)}`:\"\"}`}}const XB=new aw;function Uc(n){return n.segments.map(t=>dw(t)).join(\"/\")}function ka(n,t){if(!n.hasChildren())return Uc(n);if(t){const e=n.children[me]?ka(n.children[me],!1):\"\",i=[];return At(n.children,(r,s)=>{s!==me&&i.push(`${s}:${ka(r,!1)}`)}),i.length>0?`${e}(${i.join(\"//\")})`:e}{const e=function ZB(n,t){let e=[];return At(n.children,(i,r)=>{r===me&&(e=e.concat(t(i,r)))}),At(n.children,(i,r)=>{r!==me&&(e=e.concat(t(i,r)))}),e}(n,(i,r)=>r===me?[ka(n.children[me],!1)]:[`${r}:${ka(i,!1)}`]);return 1===Object.keys(n.children).length&&null!=n.children[me]?`${Uc(n)}/${e[0]}`:`${Uc(n)}/(${e.join(\"//\")})`}}function lw(n){return encodeURIComponent(n).replace(/%40/g,\"@\").replace(/%3A/gi,\":\").replace(/%24/g,\"$\").replace(/%2C/gi,\",\")}function $c(n){return lw(n).replace(/%3B/gi,\";\")}function Mf(n){return lw(n).replace(/\\(/g,\"%28\").replace(/\\)/g,\"%29\").replace(/%26/gi,\"&\")}function Gc(n){return decodeURIComponent(n)}function cw(n){return Gc(n.replace(/\\+/g,\"%20\"))}function dw(n){return`${Mf(n.path)}${function eV(n){return Object.keys(n).map(t=>`;${Mf(t)}=${Mf(n[t])}`).join(\"\")}(n.parameters)}`}const nV=/^[^\\/()?;=#]+/;function Wc(n){const t=n.match(nV);return t?t[0]:\"\"}const iV=/^[^=?&#]+/,sV=/^[^&#]+/;class aV{constructor(t){this.url=t,this.remaining=t}parseRootSegment(){return this.consumeOptional(\"/\"),\"\"===this.remaining||this.peekStartsWith(\"?\")||this.peekStartsWith(\"#\")?new ye([],{}):new ye([],this.parseChildren())}parseQueryParams(){const t={};if(this.consumeOptional(\"?\"))do{this.parseQueryParam(t)}while(this.consumeOptional(\"&\"));return t}parseFragment(){return this.consumeOptional(\"#\")?decodeURIComponent(this.remaining):null}parseChildren(){if(\"\"===this.remaining)return{};this.consumeOptional(\"/\");const t=[];for(this.peekStartsWith(\"(\")||t.push(this.parseSegment());this.peekStartsWith(\"/\")&&!this.peekStartsWith(\"//\")&&!this.peekStartsWith(\"/(\");)this.capture(\"/\"),t.push(this.parseSegment());let e={};this.peekStartsWith(\"/(\")&&(this.capture(\"/\"),e=this.parseParens(!0));let i={};return this.peekStartsWith(\"(\")&&(i=this.parseParens(!1)),(t.length>0||Object.keys(e).length>0)&&(i[me]=new ye(t,e)),i}parseSegment(){const t=Wc(this.remaining);if(\"\"===t&&this.peekStartsWith(\";\"))throw new Error(`Empty path url segment cannot have parameters: '${this.remaining}'.`);return this.capture(t),new Sa(Gc(t),this.parseMatrixParams())}parseMatrixParams(){const t={};for(;this.consumeOptional(\";\");)this.parseParam(t);return t}parseParam(t){const e=Wc(this.remaining);if(!e)return;this.capture(e);let i=\"\";if(this.consumeOptional(\"=\")){const r=Wc(this.remaining);r&&(i=r,this.capture(i))}t[Gc(e)]=Gc(i)}parseQueryParam(t){const e=function rV(n){const t=n.match(iV);return t?t[0]:\"\"}(this.remaining);if(!e)return;this.capture(e);let i=\"\";if(this.consumeOptional(\"=\")){const o=function oV(n){const t=n.match(sV);return t?t[0]:\"\"}(this.remaining);o&&(i=o,this.capture(i))}const r=cw(e),s=cw(i);if(t.hasOwnProperty(r)){let o=t[r];Array.isArray(o)||(o=[o],t[r]=o),o.push(s)}else t[r]=s}parseParens(t){const e={};for(this.capture(\"(\");!this.consumeOptional(\")\")&&this.remaining.length>0;){const i=Wc(this.remaining),r=this.remaining[i.length];if(\"/\"!==r&&\")\"!==r&&\";\"!==r)throw new Error(`Cannot parse url '${this.url}'`);let s;i.indexOf(\":\")>-1?(s=i.substr(0,i.indexOf(\":\")),this.capture(s),this.capture(\":\")):t&&(s=me);const o=this.parseChildren();e[s]=1===Object.keys(o).length?o[me]:new ye([],o),this.consumeOptional(\"//\")}return e}peekStartsWith(t){return this.remaining.startsWith(t)}consumeOptional(t){return!!this.peekStartsWith(t)&&(this.remaining=this.remaining.substring(t.length),!0)}capture(t){if(!this.consumeOptional(t))throw new Error(`Expected \"${t}\".`)}}class uw{constructor(t){this._root=t}get root(){return this._root.value}parent(t){const e=this.pathFromRoot(t);return e.length>1?e[e.length-2]:null}children(t){const e=xf(t,this._root);return e?e.children.map(i=>i.value):[]}firstChild(t){const e=xf(t,this._root);return e&&e.children.length>0?e.children[0].value:null}siblings(t){const e=Ef(t,this._root);return e.length<2?[]:e[e.length-2].children.map(r=>r.value).filter(r=>r!==t)}pathFromRoot(t){return Ef(t,this._root).map(e=>e.value)}}function xf(n,t){if(n===t.value)return t;for(const e of t.children){const i=xf(n,e);if(i)return i}return null}function Ef(n,t){if(n===t.value)return[t];for(const e of t.children){const i=Ef(n,e);if(i.length)return i.unshift(t),i}return[]}class Bi{constructor(t,e){this.value=t,this.children=e}toString(){return`TreeNode(${this.value})`}}function Xs(n){const t={};return n&&n.children.forEach(e=>t[e.value.outlet]=e),t}class hw extends uw{constructor(t,e){super(t),this.snapshot=e,Sf(this,t)}toString(){return this.snapshot.toString()}}function pw(n,t){const e=function lV(n,t){const o=new qc([],{},{},\"\",{},me,t,null,n.root,-1,{});return new mw(\"\",new Bi(o,[]))}(n,t),i=new Zt([new Sa(\"\",{})]),r=new Zt({}),s=new Zt({}),o=new Zt({}),a=new Zt(\"\"),l=new Js(i,r,o,a,s,me,t,e.root);return l.snapshot=e.root,new hw(new Bi(l,[]),e)}class Js{constructor(t,e,i,r,s,o,a,l){this.url=t,this.params=e,this.queryParams=i,this.fragment=r,this.data=s,this.outlet=o,this.component=a,this._futureSnapshot=l}get routeConfig(){return this._futureSnapshot.routeConfig}get root(){return this._routerState.root}get parent(){return this._routerState.parent(this)}get firstChild(){return this._routerState.firstChild(this)}get children(){return this._routerState.children(this)}get pathFromRoot(){return this._routerState.pathFromRoot(this)}get paramMap(){return this._paramMap||(this._paramMap=this.params.pipe(ue(t=>Zs(t)))),this._paramMap}get queryParamMap(){return this._queryParamMap||(this._queryParamMap=this.queryParams.pipe(ue(t=>Zs(t)))),this._queryParamMap}toString(){return this.snapshot?this.snapshot.toString():`Future(${this._futureSnapshot})`}}function fw(n,t=\"emptyOnly\"){const e=n.pathFromRoot;let i=0;if(\"always\"!==t)for(i=e.length-1;i>=1;){const r=e[i],s=e[i-1];if(r.routeConfig&&\"\"===r.routeConfig.path)i--;else{if(s.component)break;i--}}return function cV(n){return n.reduce((t,e)=>({params:Object.assign(Object.assign({},t.params),e.params),data:Object.assign(Object.assign({},t.data),e.data),resolve:Object.assign(Object.assign({},t.resolve),e._resolvedData)}),{params:{},data:{},resolve:{}})}(e.slice(i))}class qc{constructor(t,e,i,r,s,o,a,l,c,d,u){this.url=t,this.params=e,this.queryParams=i,this.fragment=r,this.data=s,this.outlet=o,this.component=a,this.routeConfig=l,this._urlSegment=c,this._lastPathIndex=d,this._resolve=u}get root(){return this._routerState.root}get parent(){return this._routerState.parent(this)}get firstChild(){return this._routerState.firstChild(this)}get children(){return this._routerState.children(this)}get pathFromRoot(){return this._routerState.pathFromRoot(this)}get paramMap(){return this._paramMap||(this._paramMap=Zs(this.params)),this._paramMap}get queryParamMap(){return this._queryParamMap||(this._queryParamMap=Zs(this.queryParams)),this._queryParamMap}toString(){return`Route(url:'${this.url.map(i=>i.toString()).join(\"/\")}', path:'${this.routeConfig?this.routeConfig.path:\"\"}')`}}class mw extends uw{constructor(t,e){super(e),this.url=t,Sf(this,e)}toString(){return gw(this._root)}}function Sf(n,t){t.value._routerState=n,t.children.forEach(e=>Sf(n,e))}function gw(n){const t=n.children.length>0?` { ${n.children.map(gw).join(\", \")} } `:\"\";return`${n.value}${t}`}function kf(n){if(n.snapshot){const t=n.snapshot,e=n._futureSnapshot;n.snapshot=e,gi(t.queryParams,e.queryParams)||n.queryParams.next(e.queryParams),t.fragment!==e.fragment&&n.fragment.next(e.fragment),gi(t.params,e.params)||n.params.next(e.params),function GB(n,t){if(n.length!==t.length)return!1;for(let e=0;e<n.length;++e)if(!gi(n[e],t[e]))return!1;return!0}(t.url,e.url)||n.url.next(e.url),gi(t.data,e.data)||n.data.next(e.data)}else n.snapshot=n._futureSnapshot,n.data.next(n._futureSnapshot.data)}function Tf(n,t){const e=gi(n.params,t.params)&&function KB(n,t){return Nr(n,t)&&n.every((e,i)=>gi(e.parameters,t[i].parameters))}(n.url,t.url);return e&&!(!n.parent!=!t.parent)&&(!n.parent||Tf(n.parent,t.parent))}function Ta(n,t,e){if(e&&n.shouldReuseRoute(t.value,e.value.snapshot)){const i=e.value;i._futureSnapshot=t.value;const r=function uV(n,t,e){return t.children.map(i=>{for(const r of e.children)if(n.shouldReuseRoute(i.value,r.value.snapshot))return Ta(n,i,r);return Ta(n,i)})}(n,t,e);return new Bi(i,r)}{if(n.shouldAttach(t.value)){const s=n.retrieve(t.value);if(null!==s){const o=s.route;return o.value._futureSnapshot=t.value,o.children=t.children.map(a=>Ta(n,a)),o}}const i=function hV(n){return new Js(new Zt(n.url),new Zt(n.params),new Zt(n.queryParams),new Zt(n.fragment),new Zt(n.data),n.outlet,n.component,n)}(t.value),r=t.children.map(s=>Ta(n,s));return new Bi(i,r)}}function Yc(n){return\"object\"==typeof n&&null!=n&&!n.outlets&&!n.segmentPath}function Aa(n){return\"object\"==typeof n&&null!=n&&n.outlets}function Af(n,t,e,i,r){let s={};if(i&&At(i,(a,l)=>{s[l]=Array.isArray(a)?a.map(c=>`${c}`):`${a}`}),n===t)return new Fr(e,s,r);const o=_w(n,t,e);return new Fr(o,s,r)}function _w(n,t,e){const i={};return At(n.children,(r,s)=>{i[s]=r===t?e:_w(r,t,e)}),new ye(n.segments,i)}class vw{constructor(t,e,i){if(this.isAbsolute=t,this.numberOfDoubleDots=e,this.commands=i,t&&i.length>0&&Yc(i[0]))throw new Error(\"Root segment cannot have matrix parameters\");const r=i.find(Aa);if(r&&r!==ew(i))throw new Error(\"{outlets:{}} has to be the last command\")}toRoot(){return this.isAbsolute&&1===this.commands.length&&\"/\"==this.commands[0]}}class If{constructor(t,e,i){this.segmentGroup=t,this.processChildren=e,this.index=i}}function yw(n,t,e){if(n||(n=new ye([],{})),0===n.segments.length&&n.hasChildren())return Qc(n,t,e);const i=function vV(n,t,e){let i=0,r=t;const s={match:!1,pathIndex:0,commandIndex:0};for(;r<n.segments.length;){if(i>=e.length)return s;const o=n.segments[r],a=e[i];if(Aa(a))break;const l=`${a}`,c=i<e.length-1?e[i+1]:null;if(r>0&&void 0===l)break;if(l&&c&&\"object\"==typeof c&&void 0===c.outlets){if(!Cw(l,c,o))return s;i+=2}else{if(!Cw(l,{},o))return s;i++}r++}return{match:!0,pathIndex:r,commandIndex:i}}(n,t,e),r=e.slice(i.commandIndex);if(i.match&&i.pathIndex<n.segments.length){const s=new ye(n.segments.slice(0,i.pathIndex),{});return s.children[me]=new ye(n.segments.slice(i.pathIndex),n.children),Qc(s,0,r)}return i.match&&0===r.length?new ye(n.segments,{}):i.match&&!n.hasChildren()?Rf(n,t,e):i.match?Qc(n,0,r):Rf(n,t,e)}function Qc(n,t,e){if(0===e.length)return new ye(n.segments,{});{const i=function _V(n){return Aa(n[0])?n[0].outlets:{[me]:n}}(e),r={};return At(i,(s,o)=>{\"string\"==typeof s&&(s=[s]),null!==s&&(r[o]=yw(n.children[o],t,s))}),At(n.children,(s,o)=>{void 0===i[o]&&(r[o]=s)}),new ye(n.segments,r)}}function Rf(n,t,e){const i=n.segments.slice(0,t);let r=0;for(;r<e.length;){const s=e[r];if(Aa(s)){const l=yV(s.outlets);return new ye(i,l)}if(0===r&&Yc(e[0])){i.push(new Sa(n.segments[t].path,bw(e[0]))),r++;continue}const o=Aa(s)?s.outlets[me]:`${s}`,a=r<e.length-1?e[r+1]:null;o&&a&&Yc(a)?(i.push(new Sa(o,bw(a))),r+=2):(i.push(new Sa(o,{})),r++)}return new ye(i,{})}function yV(n){const t={};return At(n,(e,i)=>{\"string\"==typeof e&&(e=[e]),null!==e&&(t[i]=Rf(new ye([],{}),0,e))}),t}function bw(n){const t={};return At(n,(e,i)=>t[i]=`${e}`),t}function Cw(n,t,e){return n==e.path&&gi(t,e.parameters)}class CV{constructor(t,e,i,r){this.routeReuseStrategy=t,this.futureState=e,this.currState=i,this.forwardEvent=r}activate(t){const e=this.futureState._root,i=this.currState?this.currState._root:null;this.deactivateChildRoutes(e,i,t),kf(this.futureState.root),this.activateChildRoutes(e,i,t)}deactivateChildRoutes(t,e,i){const r=Xs(e);t.children.forEach(s=>{const o=s.value.outlet;this.deactivateRoutes(s,r[o],i),delete r[o]}),At(r,(s,o)=>{this.deactivateRouteAndItsChildren(s,i)})}deactivateRoutes(t,e,i){const r=t.value,s=e?e.value:null;if(r===s)if(r.component){const o=i.getContext(r.outlet);o&&this.deactivateChildRoutes(t,e,o.children)}else this.deactivateChildRoutes(t,e,i);else s&&this.deactivateRouteAndItsChildren(e,i)}deactivateRouteAndItsChildren(t,e){t.value.component&&this.routeReuseStrategy.shouldDetach(t.value.snapshot)?this.detachAndStoreRouteSubtree(t,e):this.deactivateRouteAndOutlet(t,e)}detachAndStoreRouteSubtree(t,e){const i=e.getContext(t.value.outlet),r=i&&t.value.component?i.children:e,s=Xs(t);for(const o of Object.keys(s))this.deactivateRouteAndItsChildren(s[o],r);if(i&&i.outlet){const o=i.outlet.detach(),a=i.children.onOutletDeactivated();this.routeReuseStrategy.store(t.value.snapshot,{componentRef:o,route:t,contexts:a})}}deactivateRouteAndOutlet(t,e){const i=e.getContext(t.value.outlet),r=i&&t.value.component?i.children:e,s=Xs(t);for(const o of Object.keys(s))this.deactivateRouteAndItsChildren(s[o],r);i&&i.outlet&&(i.outlet.deactivate(),i.children.onOutletDeactivated(),i.attachRef=null,i.resolver=null,i.route=null)}activateChildRoutes(t,e,i){const r=Xs(e);t.children.forEach(s=>{this.activateRoutes(s,r[s.value.outlet],i),this.forwardEvent(new jB(s.value.snapshot))}),t.children.length&&this.forwardEvent(new VB(t.value.snapshot))}activateRoutes(t,e,i){const r=t.value,s=e?e.value:null;if(kf(r),r===s)if(r.component){const o=i.getOrCreateContext(r.outlet);this.activateChildRoutes(t,e,o.children)}else this.activateChildRoutes(t,e,i);else if(r.component){const o=i.getOrCreateContext(r.outlet);if(this.routeReuseStrategy.shouldAttach(r.snapshot)){const a=this.routeReuseStrategy.retrieve(r.snapshot);this.routeReuseStrategy.store(r.snapshot,null),o.children.onOutletReAttached(a.contexts),o.attachRef=a.componentRef,o.route=a.route.value,o.outlet&&o.outlet.attach(a.componentRef,a.route.value),kf(a.route.value),this.activateChildRoutes(t,null,o.children)}else{const a=function DV(n){for(let t=n.parent;t;t=t.parent){const e=t.routeConfig;if(e&&e._loadedConfig)return e._loadedConfig;if(e&&e.component)return null}return null}(r.snapshot),l=a?a.module.componentFactoryResolver:null;o.attachRef=null,o.route=r,o.resolver=l,o.outlet&&o.outlet.activateWith(r,l),this.activateChildRoutes(t,null,o.children)}}else this.activateChildRoutes(t,null,i)}}class Of{constructor(t,e){this.routes=t,this.module=e}}function nr(n){return\"function\"==typeof n}function Lr(n){return n instanceof Fr}const Ia=Symbol(\"INITIAL_VALUE\");function Ra(){return kn(n=>function xB(...n){const t=So(n),e=b_(n),{args:i,keys:r}=VD(n);if(0===i.length)return mt([],t);const s=new Ve(function EB(n,t,e=Wi){return i=>{jD(t,()=>{const{length:r}=n,s=new Array(r);let o=r,a=r;for(let l=0;l<r;l++)jD(t,()=>{const c=mt(n[l],t);let d=!1;c.subscribe(Ue(i,u=>{s[l]=u,d||(d=!0,a--),a||i.next(e(s.slice()))},()=>{--o||i.complete()}))},i)},i)}}(i,t,r?o=>HD(r,o):Wi));return e?s.pipe(bf(e)):s}(n.map(t=>t.pipe(it(1),Xn(Ia)))).pipe(UD((t,e)=>{let i=!1;return e.reduce((r,s,o)=>r!==Ia?r:(s===Ia&&(i=!0),i||!1!==s&&o!==e.length-1&&!Lr(s)?r:s),t)},Ia),Ct(t=>t!==Ia),ue(t=>Lr(t)?t:!0===t),it(1)))}class kV{constructor(){this.outlet=null,this.route=null,this.resolver=null,this.children=new Oa,this.attachRef=null}}class Oa{constructor(){this.contexts=new Map}onChildOutletCreated(t,e){const i=this.getOrCreateContext(t);i.outlet=e,this.contexts.set(t,i)}onChildOutletDestroyed(t){const e=this.getContext(t);e&&(e.outlet=null,e.attachRef=null)}onOutletDeactivated(){const t=this.contexts;return this.contexts=new Map,t}onOutletReAttached(t){this.contexts=t}getOrCreateContext(t){let e=this.getContext(t);return e||(e=new kV,this.contexts.set(t,e)),e}getContext(t){return this.contexts.get(t)||null}}let Pf=(()=>{class n{constructor(e,i,r,s,o){this.parentContexts=e,this.location=i,this.resolver=r,this.changeDetector=o,this.activated=null,this._activatedRoute=null,this.activateEvents=new $,this.deactivateEvents=new $,this.attachEvents=new $,this.detachEvents=new $,this.name=s||me,e.onChildOutletCreated(this.name,this)}ngOnDestroy(){this.parentContexts.onChildOutletDestroyed(this.name)}ngOnInit(){if(!this.activated){const e=this.parentContexts.getContext(this.name);e&&e.route&&(e.attachRef?this.attach(e.attachRef,e.route):this.activateWith(e.route,e.resolver||null))}}get isActivated(){return!!this.activated}get component(){if(!this.activated)throw new Error(\"Outlet is not activated\");return this.activated.instance}get activatedRoute(){if(!this.activated)throw new Error(\"Outlet is not activated\");return this._activatedRoute}get activatedRouteData(){return this._activatedRoute?this._activatedRoute.snapshot.data:{}}detach(){if(!this.activated)throw new Error(\"Outlet is not activated\");this.location.detach();const e=this.activated;return this.activated=null,this._activatedRoute=null,this.detachEvents.emit(e.instance),e}attach(e,i){this.activated=e,this._activatedRoute=i,this.location.insert(e.hostView),this.attachEvents.emit(e.instance)}deactivate(){if(this.activated){const e=this.component;this.activated.destroy(),this.activated=null,this._activatedRoute=null,this.deactivateEvents.emit(e)}}activateWith(e,i){if(this.isActivated)throw new Error(\"Cannot activate an already activated outlet\");this._activatedRoute=e;const o=(i=i||this.resolver).resolveComponentFactory(e._futureSnapshot.routeConfig.component),a=this.parentContexts.getOrCreateContext(this.name).children,l=new TV(e,a,this.location.injector);this.activated=this.location.createComponent(o,this.location.length,l),this.changeDetector.markForCheck(),this.activateEvents.emit(this.activated.instance)}}return n.\\u0275fac=function(e){return new(e||n)(f(Oa),f(st),f(Ir),kt(\"name\"),f(Ye))},n.\\u0275dir=C({type:n,selectors:[[\"router-outlet\"]],outputs:{activateEvents:\"activate\",deactivateEvents:\"deactivate\",attachEvents:\"attach\",detachEvents:\"detach\"},exportAs:[\"outlet\"]}),n})();class TV{constructor(t,e,i){this.route=t,this.childContexts=e,this.parent=i}get(t,e){return t===Js?this.route:t===Oa?this.childContexts:this.parent.get(t,e)}}let Dw=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275cmp=xe({type:n,selectors:[[\"ng-component\"]],decls:1,vars:0,template:function(e,i){1&e&&Le(0,\"router-outlet\")},directives:[Pf],encapsulation:2}),n})();function ww(n,t=\"\"){for(let e=0;e<n.length;e++){const i=n[e];AV(i,IV(t,i))}}function AV(n,t){n.children&&ww(n.children,t)}function IV(n,t){return t?n||t.path?n&&!t.path?`${n}/`:!n&&t.path?t.path:`${n}/${t.path}`:\"\":n}function Ff(n){const t=n.children&&n.children.map(Ff),e=t?Object.assign(Object.assign({},n),{children:t}):Object.assign({},n);return!e.component&&(t||e.loadChildren)&&e.outlet&&e.outlet!==me&&(e.component=Dw),e}function Tn(n){return n.outlet||me}function Mw(n,t){const e=n.filter(i=>Tn(i)===t);return e.push(...n.filter(i=>Tn(i)!==t)),e}const xw={matched:!1,consumedSegments:[],remainingSegments:[],parameters:{},positionalParamSegments:{}};function Kc(n,t,e){var i;if(\"\"===t.path)return\"full\"===t.pathMatch&&(n.hasChildren()||e.length>0)?Object.assign({},xw):{matched:!0,consumedSegments:[],remainingSegments:e,parameters:{},positionalParamSegments:{}};const s=(t.matcher||$B)(e,n,t);if(!s)return Object.assign({},xw);const o={};At(s.posParams,(l,c)=>{o[c]=l.path});const a=s.consumed.length>0?Object.assign(Object.assign({},o),s.consumed[s.consumed.length-1].parameters):o;return{matched:!0,consumedSegments:s.consumed,remainingSegments:e.slice(s.consumed.length),parameters:a,positionalParamSegments:null!==(i=s.posParams)&&void 0!==i?i:{}}}function Zc(n,t,e,i,r=\"corrected\"){if(e.length>0&&function PV(n,t,e){return e.some(i=>Xc(n,t,i)&&Tn(i)!==me)}(n,e,i)){const o=new ye(t,function OV(n,t,e,i){const r={};r[me]=i,i._sourceSegment=n,i._segmentIndexShift=t.length;for(const s of e)if(\"\"===s.path&&Tn(s)!==me){const o=new ye([],{});o._sourceSegment=n,o._segmentIndexShift=t.length,r[Tn(s)]=o}return r}(n,t,i,new ye(e,n.children)));return o._sourceSegment=n,o._segmentIndexShift=t.length,{segmentGroup:o,slicedSegments:[]}}if(0===e.length&&function FV(n,t,e){return e.some(i=>Xc(n,t,i))}(n,e,i)){const o=new ye(n.segments,function RV(n,t,e,i,r,s){const o={};for(const a of i)if(Xc(n,e,a)&&!r[Tn(a)]){const l=new ye([],{});l._sourceSegment=n,l._segmentIndexShift=\"legacy\"===s?n.segments.length:t.length,o[Tn(a)]=l}return Object.assign(Object.assign({},r),o)}(n,t,e,i,n.children,r));return o._sourceSegment=n,o._segmentIndexShift=t.length,{segmentGroup:o,slicedSegments:e}}const s=new ye(n.segments,n.children);return s._sourceSegment=n,s._segmentIndexShift=t.length,{segmentGroup:s,slicedSegments:e}}function Xc(n,t,e){return(!(n.hasChildren()||t.length>0)||\"full\"!==e.pathMatch)&&\"\"===e.path}function Ew(n,t,e,i){return!!(Tn(n)===i||i!==me&&Xc(t,e,n))&&(\"**\"===n.path||Kc(t,n,e).matched)}function Sw(n,t,e){return 0===t.length&&!n.children[e]}class Jc{constructor(t){this.segmentGroup=t||null}}class kw{constructor(t){this.urlTree=t}}function Pa(n){return Ma(new Jc(n))}function Tw(n){return Ma(new kw(n))}class VV{constructor(t,e,i,r,s){this.configLoader=e,this.urlSerializer=i,this.urlTree=r,this.config=s,this.allowRedirects=!0,this.ngModule=t.get(Ri)}apply(){const t=Zc(this.urlTree.root,[],[],this.config).segmentGroup,e=new ye(t.segments,t.children);return this.expandSegmentGroup(this.ngModule,this.config,e,me).pipe(ue(s=>this.createUrlTree(Nf(s),this.urlTree.queryParams,this.urlTree.fragment))).pipe(Ni(s=>{if(s instanceof kw)return this.allowRedirects=!1,this.match(s.urlTree);throw s instanceof Jc?this.noMatchError(s):s}))}match(t){return this.expandSegmentGroup(this.ngModule,this.config,t.root,me).pipe(ue(r=>this.createUrlTree(Nf(r),t.queryParams,t.fragment))).pipe(Ni(r=>{throw r instanceof Jc?this.noMatchError(r):r}))}noMatchError(t){return new Error(`Cannot match any routes. URL Segment: '${t.segmentGroup}'`)}createUrlTree(t,e,i){const r=t.segments.length>0?new ye([],{[me]:t}):t;return new Fr(r,e,i)}expandSegmentGroup(t,e,i,r){return 0===i.segments.length&&i.hasChildren()?this.expandChildren(t,e,i).pipe(ue(s=>new ye([],s))):this.expandSegment(t,i,e,i.segments,r,!0)}expandChildren(t,e,i){const r=[];for(const s of Object.keys(i.children))\"primary\"===s?r.unshift(s):r.push(s);return mt(r).pipe(Qs(s=>{const o=i.children[s],a=Mw(e,s);return this.expandSegmentGroup(t,a,o,s).pipe(ue(l=>({segment:l,outlet:s})))}),UD((s,o)=>(s[o.outlet]=o.segment,s),{}),function IB(n,t){const e=arguments.length>=2;return i=>i.pipe(n?Ct((r,s)=>n(r,s,i)):Wi,Cf(1),e?GD(t):$D(()=>new Hc))}())}expandSegment(t,e,i,r,s,o){return mt(i).pipe(Qs(a=>this.expandSegmentAgainstRoute(t,e,i,a,r,s,o).pipe(Ni(c=>{if(c instanceof Jc)return q(null);throw c}))),Ks(a=>!!a),Ni((a,l)=>{if(a instanceof Hc||\"EmptyError\"===a.name)return Sw(e,r,s)?q(new ye([],{})):Pa(e);throw a}))}expandSegmentAgainstRoute(t,e,i,r,s,o,a){return Ew(r,e,s,o)?void 0===r.redirectTo?this.matchSegmentAgainstRoute(t,e,r,s,o):a&&this.allowRedirects?this.expandSegmentAgainstRouteUsingRedirect(t,e,i,r,s,o):Pa(e):Pa(e)}expandSegmentAgainstRouteUsingRedirect(t,e,i,r,s,o){return\"**\"===r.path?this.expandWildCardWithParamsAgainstRouteUsingRedirect(t,i,r,o):this.expandRegularSegmentAgainstRouteUsingRedirect(t,e,i,r,s,o)}expandWildCardWithParamsAgainstRouteUsingRedirect(t,e,i,r){const s=this.applyRedirectCommands([],i.redirectTo,{});return i.redirectTo.startsWith(\"/\")?Tw(s):this.lineralizeSegments(i,s).pipe(lt(o=>{const a=new ye(o,{});return this.expandSegment(t,a,e,o,r,!1)}))}expandRegularSegmentAgainstRouteUsingRedirect(t,e,i,r,s,o){const{matched:a,consumedSegments:l,remainingSegments:c,positionalParamSegments:d}=Kc(e,r,s);if(!a)return Pa(e);const u=this.applyRedirectCommands(l,r.redirectTo,d);return r.redirectTo.startsWith(\"/\")?Tw(u):this.lineralizeSegments(r,u).pipe(lt(h=>this.expandSegment(t,e,i,h.concat(c),o,!1)))}matchSegmentAgainstRoute(t,e,i,r,s){if(\"**\"===i.path)return i.loadChildren?(i._loadedConfig?q(i._loadedConfig):this.configLoader.load(t.injector,i)).pipe(ue(u=>(i._loadedConfig=u,new ye(r,{})))):q(new ye(r,{}));const{matched:o,consumedSegments:a,remainingSegments:l}=Kc(e,i,r);return o?this.getChildConfig(t,i,r).pipe(lt(d=>{const u=d.module,h=d.routes,{segmentGroup:p,slicedSegments:m}=Zc(e,a,l,h),g=new ye(p.segments,p.children);if(0===m.length&&g.hasChildren())return this.expandChildren(u,h,g).pipe(ue(M=>new ye(a,M)));if(0===h.length&&0===m.length)return q(new ye(a,{}));const _=Tn(i)===s;return this.expandSegment(u,g,h,m,_?me:s,!0).pipe(ue(v=>new ye(a.concat(v.segments),v.children)))})):Pa(e)}getChildConfig(t,e,i){return e.children?q(new Of(e.children,t)):e.loadChildren?void 0!==e._loadedConfig?q(e._loadedConfig):this.runCanLoadGuards(t.injector,e,i).pipe(lt(r=>r?this.configLoader.load(t.injector,e).pipe(ue(s=>(e._loadedConfig=s,s))):function LV(n){return Ma(wf(`Cannot load children because the guard of the route \"path: '${n.path}'\" returned false`))}(e))):q(new Of([],t))}runCanLoadGuards(t,e,i){const r=e.canLoad;return r&&0!==r.length?q(r.map(o=>{const a=t.get(o);let l;if(function MV(n){return n&&nr(n.canLoad)}(a))l=a.canLoad(e,i);else{if(!nr(a))throw new Error(\"Invalid CanLoad guard\");l=a(e,i)}return _i(l)})).pipe(Ra(),Mt(o=>{if(!Lr(o))return;const a=wf(`Redirecting to \"${this.urlSerializer.serialize(o)}\"`);throw a.url=o,a}),ue(o=>!0===o)):q(!0)}lineralizeSegments(t,e){let i=[],r=e.root;for(;;){if(i=i.concat(r.segments),0===r.numberOfChildren)return q(i);if(r.numberOfChildren>1||!r.children[me])return Ma(new Error(`Only absolute redirects can have named outlets. redirectTo: '${t.redirectTo}'`));r=r.children[me]}}applyRedirectCommands(t,e,i){return this.applyRedirectCreatreUrlTree(e,this.urlSerializer.parse(e),t,i)}applyRedirectCreatreUrlTree(t,e,i,r){const s=this.createSegmentGroup(t,e.root,i,r);return new Fr(s,this.createQueryParams(e.queryParams,this.urlTree.queryParams),e.fragment)}createQueryParams(t,e){const i={};return At(t,(r,s)=>{if(\"string\"==typeof r&&r.startsWith(\":\")){const a=r.substring(1);i[s]=e[a]}else i[s]=r}),i}createSegmentGroup(t,e,i,r){const s=this.createSegments(t,e.segments,i,r);let o={};return At(e.children,(a,l)=>{o[l]=this.createSegmentGroup(t,a,i,r)}),new ye(s,o)}createSegments(t,e,i,r){return e.map(s=>s.path.startsWith(\":\")?this.findPosParam(t,s,r):this.findOrReturn(s,i))}findPosParam(t,e,i){const r=i[e.path.substring(1)];if(!r)throw new Error(`Cannot redirect to '${t}'. Cannot find '${e.path}'.`);return r}findOrReturn(t,e){let i=0;for(const r of e){if(r.path===t.path)return e.splice(i),r;i++}return t}}function Nf(n){const t={};for(const i of Object.keys(n.children)){const s=Nf(n.children[i]);(s.segments.length>0||s.hasChildren())&&(t[i]=s)}return function HV(n){if(1===n.numberOfChildren&&n.children[me]){const t=n.children[me];return new ye(n.segments.concat(t.segments),t.children)}return n}(new ye(n.segments,t))}class Aw{constructor(t){this.path=t,this.route=this.path[this.path.length-1]}}class ed{constructor(t,e){this.component=t,this.route=e}}function zV(n,t,e){const i=n._root;return Fa(i,t?t._root:null,e,[i.value])}function td(n,t,e){const i=function $V(n){if(!n)return null;for(let t=n.parent;t;t=t.parent){const e=t.routeConfig;if(e&&e._loadedConfig)return e._loadedConfig}return null}(t);return(i?i.module.injector:e).get(n)}function Fa(n,t,e,i,r={canDeactivateChecks:[],canActivateChecks:[]}){const s=Xs(t);return n.children.forEach(o=>{(function GV(n,t,e,i,r={canDeactivateChecks:[],canActivateChecks:[]}){const s=n.value,o=t?t.value:null,a=e?e.getContext(n.value.outlet):null;if(o&&s.routeConfig===o.routeConfig){const l=function WV(n,t,e){if(\"function\"==typeof e)return e(n,t);switch(e){case\"pathParamsChange\":return!Nr(n.url,t.url);case\"pathParamsOrQueryParamsChange\":return!Nr(n.url,t.url)||!gi(n.queryParams,t.queryParams);case\"always\":return!0;case\"paramsOrQueryParamsChange\":return!Tf(n,t)||!gi(n.queryParams,t.queryParams);default:return!Tf(n,t)}}(o,s,s.routeConfig.runGuardsAndResolvers);l?r.canActivateChecks.push(new Aw(i)):(s.data=o.data,s._resolvedData=o._resolvedData),Fa(n,t,s.component?a?a.children:null:e,i,r),l&&a&&a.outlet&&a.outlet.isActivated&&r.canDeactivateChecks.push(new ed(a.outlet.component,o))}else o&&Na(t,a,r),r.canActivateChecks.push(new Aw(i)),Fa(n,null,s.component?a?a.children:null:e,i,r)})(o,s[o.value.outlet],e,i.concat([o.value]),r),delete s[o.value.outlet]}),At(s,(o,a)=>Na(o,e.getContext(a),r)),r}function Na(n,t,e){const i=Xs(n),r=n.value;At(i,(s,o)=>{Na(s,r.component?t?t.children.getContext(o):null:t,e)}),e.canDeactivateChecks.push(new ed(r.component&&t&&t.outlet&&t.outlet.isActivated?t.outlet.component:null,r))}class t2{}function Iw(n){return new Ve(t=>t.error(n))}class r2{constructor(t,e,i,r,s,o){this.rootComponentType=t,this.config=e,this.urlTree=i,this.url=r,this.paramsInheritanceStrategy=s,this.relativeLinkResolution=o}recognize(){const t=Zc(this.urlTree.root,[],[],this.config.filter(o=>void 0===o.redirectTo),this.relativeLinkResolution).segmentGroup,e=this.processSegmentGroup(this.config,t,me);if(null===e)return null;const i=new qc([],Object.freeze({}),Object.freeze(Object.assign({},this.urlTree.queryParams)),this.urlTree.fragment,{},me,this.rootComponentType,null,this.urlTree.root,-1,{}),r=new Bi(i,e),s=new mw(this.url,r);return this.inheritParamsAndData(s._root),s}inheritParamsAndData(t){const e=t.value,i=fw(e,this.paramsInheritanceStrategy);e.params=Object.freeze(i.params),e.data=Object.freeze(i.data),t.children.forEach(r=>this.inheritParamsAndData(r))}processSegmentGroup(t,e,i){return 0===e.segments.length&&e.hasChildren()?this.processChildren(t,e):this.processSegment(t,e,e.segments,i)}processChildren(t,e){const i=[];for(const s of Object.keys(e.children)){const o=e.children[s],a=Mw(t,s),l=this.processSegmentGroup(a,o,s);if(null===l)return null;i.push(...l)}const r=Rw(i);return function s2(n){n.sort((t,e)=>t.value.outlet===me?-1:e.value.outlet===me?1:t.value.outlet.localeCompare(e.value.outlet))}(r),r}processSegment(t,e,i,r){for(const s of t){const o=this.processSegmentAgainstRoute(s,e,i,r);if(null!==o)return o}return Sw(e,i,r)?[]:null}processSegmentAgainstRoute(t,e,i,r){if(t.redirectTo||!Ew(t,e,i,r))return null;let s,o=[],a=[];if(\"**\"===t.path){const p=i.length>0?ew(i).parameters:{};s=new qc(i,p,Object.freeze(Object.assign({},this.urlTree.queryParams)),this.urlTree.fragment,Fw(t),Tn(t),t.component,t,Ow(e),Pw(e)+i.length,Nw(t))}else{const p=Kc(e,t,i);if(!p.matched)return null;o=p.consumedSegments,a=p.remainingSegments,s=new qc(o,p.parameters,Object.freeze(Object.assign({},this.urlTree.queryParams)),this.urlTree.fragment,Fw(t),Tn(t),t.component,t,Ow(e),Pw(e)+o.length,Nw(t))}const l=function o2(n){return n.children?n.children:n.loadChildren?n._loadedConfig.routes:[]}(t),{segmentGroup:c,slicedSegments:d}=Zc(e,o,a,l.filter(p=>void 0===p.redirectTo),this.relativeLinkResolution);if(0===d.length&&c.hasChildren()){const p=this.processChildren(l,c);return null===p?null:[new Bi(s,p)]}if(0===l.length&&0===d.length)return[new Bi(s,[])];const u=Tn(t)===r,h=this.processSegment(l,c,d,u?me:r);return null===h?null:[new Bi(s,h)]}}function a2(n){const t=n.value.routeConfig;return t&&\"\"===t.path&&void 0===t.redirectTo}function Rw(n){const t=[],e=new Set;for(const i of n){if(!a2(i)){t.push(i);continue}const r=t.find(s=>i.value.routeConfig===s.value.routeConfig);void 0!==r?(r.children.push(...i.children),e.add(r)):t.push(i)}for(const i of e){const r=Rw(i.children);t.push(new Bi(i.value,r))}return t.filter(i=>!e.has(i))}function Ow(n){let t=n;for(;t._sourceSegment;)t=t._sourceSegment;return t}function Pw(n){let t=n,e=t._segmentIndexShift?t._segmentIndexShift:0;for(;t._sourceSegment;)t=t._sourceSegment,e+=t._segmentIndexShift?t._segmentIndexShift:0;return e-1}function Fw(n){return n.data||{}}function Nw(n){return n.resolve||{}}function Lw(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n)]}function Lf(n){return kn(t=>{const e=n(t);return e?mt(e).pipe(ue(()=>t)):q(t)})}class m2 extends class f2{shouldDetach(t){return!1}store(t,e){}shouldAttach(t){return!1}retrieve(t){return null}shouldReuseRoute(t,e){return t.routeConfig===e.routeConfig}}{}const Bf=new b(\"ROUTES\");class Bw{constructor(t,e,i,r){this.injector=t,this.compiler=e,this.onLoadStartListener=i,this.onLoadEndListener=r}load(t,e){if(e._loader$)return e._loader$;this.onLoadStartListener&&this.onLoadStartListener(e);const r=this.loadModuleFactory(e.loadChildren).pipe(ue(s=>{this.onLoadEndListener&&this.onLoadEndListener(e);const o=s.create(t);return new Of(JD(o.injector.get(Bf,void 0,ee.Self|ee.Optional)).map(Ff),o)}),Ni(s=>{throw e._loader$=void 0,s}));return e._loader$=new kB(r,()=>new O).pipe(zD()),e._loader$}loadModuleFactory(t){return _i(t()).pipe(lt(e=>e instanceof KC?q(e):mt(this.compiler.compileModuleAsync(e))))}}class _2{shouldProcessUrl(t){return!0}extract(t){return t}merge(t,e){return t}}function v2(n){throw n}function y2(n,t,e){return t.parse(\"/\")}function Vw(n,t){return q(null)}const b2={paths:\"exact\",fragment:\"ignored\",matrixParams:\"ignored\",queryParams:\"exact\"},C2={paths:\"subset\",fragment:\"ignored\",matrixParams:\"ignored\",queryParams:\"subset\"};let cn=(()=>{class n{constructor(e,i,r,s,o,a,l){this.rootComponentType=e,this.urlSerializer=i,this.rootContexts=r,this.location=s,this.config=l,this.lastSuccessfulNavigation=null,this.currentNavigation=null,this.disposed=!1,this.navigationId=0,this.currentPageId=0,this.isNgZoneEnabled=!1,this.events=new O,this.errorHandler=v2,this.malformedUriErrorHandler=y2,this.navigated=!1,this.lastSuccessfulId=-1,this.hooks={beforePreactivation:Vw,afterPreactivation:Vw},this.urlHandlingStrategy=new _2,this.routeReuseStrategy=new m2,this.onSameUrlNavigation=\"ignore\",this.paramsInheritanceStrategy=\"emptyOnly\",this.urlUpdateStrategy=\"deferred\",this.relativeLinkResolution=\"corrected\",this.canceledNavigationResolution=\"replace\",this.ngModule=o.get(Ri),this.console=o.get(O0);const u=o.get(ne);this.isNgZoneEnabled=u instanceof ne&&ne.isInAngularZone(),this.resetConfig(l),this.currentUrlTree=function WB(){return new Fr(new ye([],{}),{},null)}(),this.rawUrlTree=this.currentUrlTree,this.browserUrlTree=this.currentUrlTree,this.configLoader=new Bw(o,a,h=>this.triggerEvent(new YD(h)),h=>this.triggerEvent(new QD(h))),this.routerState=pw(this.currentUrlTree,this.rootComponentType),this.transitions=new Zt({id:0,targetPageId:0,currentUrlTree:this.currentUrlTree,currentRawUrl:this.currentUrlTree,extractedUrl:this.urlHandlingStrategy.extract(this.currentUrlTree),urlAfterRedirects:this.urlHandlingStrategy.extract(this.currentUrlTree),rawUrl:this.currentUrlTree,extras:{},resolve:null,reject:null,promise:Promise.resolve(!0),source:\"imperative\",restoredState:null,currentSnapshot:this.routerState.snapshot,targetSnapshot:null,currentRouterState:this.routerState,targetRouterState:null,guards:{canActivateChecks:[],canDeactivateChecks:[]},guardsResult:null}),this.navigations=this.setupNavigations(this.transitions),this.processNavigations()}get browserPageId(){var e;return null===(e=this.location.getState())||void 0===e?void 0:e.\\u0275routerPageId}setupNavigations(e){const i=this.events;return e.pipe(Ct(r=>0!==r.id),ue(r=>Object.assign(Object.assign({},r),{extractedUrl:this.urlHandlingStrategy.extract(r.rawUrl)})),kn(r=>{let s=!1,o=!1;return q(r).pipe(Mt(a=>{this.currentNavigation={id:a.id,initialUrl:a.currentRawUrl,extractedUrl:a.extractedUrl,trigger:a.source,extras:a.extras,previousNavigation:this.lastSuccessfulNavigation?Object.assign(Object.assign({},this.lastSuccessfulNavigation),{previousNavigation:null}):null}}),kn(a=>{const l=this.browserUrlTree.toString(),c=!this.navigated||a.extractedUrl.toString()!==l||l!==this.currentUrlTree.toString();if((\"reload\"===this.onSameUrlNavigation||c)&&this.urlHandlingStrategy.shouldProcessUrl(a.rawUrl))return Hw(a.source)&&(this.browserUrlTree=a.extractedUrl),q(a).pipe(kn(u=>{const h=this.transitions.getValue();return i.next(new Df(u.id,this.serializeUrl(u.extractedUrl),u.source,u.restoredState)),h!==this.transitions.getValue()?ri:Promise.resolve(u)}),function jV(n,t,e,i){return kn(r=>function BV(n,t,e,i,r){return new VV(n,t,e,i,r).apply()}(n,t,e,r.extractedUrl,i).pipe(ue(s=>Object.assign(Object.assign({},r),{urlAfterRedirects:s}))))}(this.ngModule.injector,this.configLoader,this.urlSerializer,this.config),Mt(u=>{this.currentNavigation=Object.assign(Object.assign({},this.currentNavigation),{finalUrl:u.urlAfterRedirects})}),function l2(n,t,e,i,r){return lt(s=>function n2(n,t,e,i,r=\"emptyOnly\",s=\"legacy\"){try{const o=new r2(n,t,e,i,r,s).recognize();return null===o?Iw(new t2):q(o)}catch(o){return Iw(o)}}(n,t,s.urlAfterRedirects,e(s.urlAfterRedirects),i,r).pipe(ue(o=>Object.assign(Object.assign({},s),{targetSnapshot:o}))))}(this.rootComponentType,this.config,u=>this.serializeUrl(u),this.paramsInheritanceStrategy,this.relativeLinkResolution),Mt(u=>{if(\"eager\"===this.urlUpdateStrategy){if(!u.extras.skipLocationChange){const p=this.urlHandlingStrategy.merge(u.urlAfterRedirects,u.rawUrl);this.setBrowserUrl(p,u)}this.browserUrlTree=u.urlAfterRedirects}const h=new OB(u.id,this.serializeUrl(u.extractedUrl),this.serializeUrl(u.urlAfterRedirects),u.targetSnapshot);i.next(h)}));if(c&&this.rawUrlTree&&this.urlHandlingStrategy.shouldProcessUrl(this.rawUrlTree)){const{id:h,extractedUrl:p,source:m,restoredState:g,extras:_}=a,D=new Df(h,this.serializeUrl(p),m,g);i.next(D);const v=pw(p,this.rootComponentType).snapshot;return q(Object.assign(Object.assign({},a),{targetSnapshot:v,urlAfterRedirects:p,extras:Object.assign(Object.assign({},_),{skipLocationChange:!1,replaceUrl:!1})}))}return this.rawUrlTree=a.rawUrl,a.resolve(null),ri}),Lf(a=>{const{targetSnapshot:l,id:c,extractedUrl:d,rawUrl:u,extras:{skipLocationChange:h,replaceUrl:p}}=a;return this.hooks.beforePreactivation(l,{navigationId:c,appliedUrlTree:d,rawUrlTree:u,skipLocationChange:!!h,replaceUrl:!!p})}),Mt(a=>{const l=new PB(a.id,this.serializeUrl(a.extractedUrl),this.serializeUrl(a.urlAfterRedirects),a.targetSnapshot);this.triggerEvent(l)}),ue(a=>Object.assign(Object.assign({},a),{guards:zV(a.targetSnapshot,a.currentSnapshot,this.rootContexts)})),function qV(n,t){return lt(e=>{const{targetSnapshot:i,currentSnapshot:r,guards:{canActivateChecks:s,canDeactivateChecks:o}}=e;return 0===o.length&&0===s.length?q(Object.assign(Object.assign({},e),{guardsResult:!0})):function YV(n,t,e,i){return mt(n).pipe(lt(r=>function e2(n,t,e,i,r){const s=t&&t.routeConfig?t.routeConfig.canDeactivate:null;return s&&0!==s.length?q(s.map(a=>{const l=td(a,t,r);let c;if(function SV(n){return n&&nr(n.canDeactivate)}(l))c=_i(l.canDeactivate(n,t,e,i));else{if(!nr(l))throw new Error(\"Invalid CanDeactivate guard\");c=_i(l(n,t,e,i))}return c.pipe(Ks())})).pipe(Ra()):q(!0)}(r.component,r.route,e,t,i)),Ks(r=>!0!==r,!0))}(o,i,r,n).pipe(lt(a=>a&&function wV(n){return\"boolean\"==typeof n}(a)?function QV(n,t,e,i){return mt(t).pipe(Qs(r=>jc(function ZV(n,t){return null!==n&&t&&t(new BB(n)),q(!0)}(r.route.parent,i),function KV(n,t){return null!==n&&t&&t(new HB(n)),q(!0)}(r.route,i),function JV(n,t,e){const i=t[t.length-1],s=t.slice(0,t.length-1).reverse().map(o=>function UV(n){const t=n.routeConfig?n.routeConfig.canActivateChild:null;return t&&0!==t.length?{node:n,guards:t}:null}(o)).filter(o=>null!==o).map(o=>xa(()=>q(o.guards.map(l=>{const c=td(l,o.node,e);let d;if(function EV(n){return n&&nr(n.canActivateChild)}(c))d=_i(c.canActivateChild(i,n));else{if(!nr(c))throw new Error(\"Invalid CanActivateChild guard\");d=_i(c(i,n))}return d.pipe(Ks())})).pipe(Ra())));return q(s).pipe(Ra())}(n,r.path,e),function XV(n,t,e){const i=t.routeConfig?t.routeConfig.canActivate:null;if(!i||0===i.length)return q(!0);const r=i.map(s=>xa(()=>{const o=td(s,t,e);let a;if(function xV(n){return n&&nr(n.canActivate)}(o))a=_i(o.canActivate(t,n));else{if(!nr(o))throw new Error(\"Invalid CanActivate guard\");a=_i(o(t,n))}return a.pipe(Ks())}));return q(r).pipe(Ra())}(n,r.route,e))),Ks(r=>!0!==r,!0))}(i,s,n,t):q(a)),ue(a=>Object.assign(Object.assign({},e),{guardsResult:a})))})}(this.ngModule.injector,a=>this.triggerEvent(a)),Mt(a=>{if(Lr(a.guardsResult)){const c=wf(`Redirecting to \"${this.serializeUrl(a.guardsResult)}\"`);throw c.url=a.guardsResult,c}const l=new FB(a.id,this.serializeUrl(a.extractedUrl),this.serializeUrl(a.urlAfterRedirects),a.targetSnapshot,!!a.guardsResult);this.triggerEvent(l)}),Ct(a=>!!a.guardsResult||(this.restoreHistory(a),this.cancelNavigationTransition(a,\"\"),!1)),Lf(a=>{if(a.guards.canActivateChecks.length)return q(a).pipe(Mt(l=>{const c=new NB(l.id,this.serializeUrl(l.extractedUrl),this.serializeUrl(l.urlAfterRedirects),l.targetSnapshot);this.triggerEvent(c)}),kn(l=>{let c=!1;return q(l).pipe(function c2(n,t){return lt(e=>{const{targetSnapshot:i,guards:{canActivateChecks:r}}=e;if(!r.length)return q(e);let s=0;return mt(r).pipe(Qs(o=>function d2(n,t,e,i){return function u2(n,t,e,i){const r=Lw(n);if(0===r.length)return q({});const s={};return mt(r).pipe(lt(o=>function h2(n,t,e,i){const r=td(n,t,i);return _i(r.resolve?r.resolve(t,e):r(t,e))}(n[o],t,e,i).pipe(Mt(a=>{s[o]=a}))),Cf(1),lt(()=>Lw(s).length===r.length?q(s):ri))}(n._resolve,n,t,i).pipe(ue(s=>(n._resolvedData=s,n.data=Object.assign(Object.assign({},n.data),fw(n,e).resolve),null)))}(o.route,i,n,t)),Mt(()=>s++),Cf(1),lt(o=>s===r.length?q(e):ri))})}(this.paramsInheritanceStrategy,this.ngModule.injector),Mt({next:()=>c=!0,complete:()=>{c||(this.restoreHistory(l),this.cancelNavigationTransition(l,\"At least one route resolver didn't emit any value.\"))}}))}),Mt(l=>{const c=new LB(l.id,this.serializeUrl(l.extractedUrl),this.serializeUrl(l.urlAfterRedirects),l.targetSnapshot);this.triggerEvent(c)}))}),Lf(a=>{const{targetSnapshot:l,id:c,extractedUrl:d,rawUrl:u,extras:{skipLocationChange:h,replaceUrl:p}}=a;return this.hooks.afterPreactivation(l,{navigationId:c,appliedUrlTree:d,rawUrlTree:u,skipLocationChange:!!h,replaceUrl:!!p})}),ue(a=>{const l=function dV(n,t,e){const i=Ta(n,t._root,e?e._root:void 0);return new hw(i,t)}(this.routeReuseStrategy,a.targetSnapshot,a.currentRouterState);return Object.assign(Object.assign({},a),{targetRouterState:l})}),Mt(a=>{this.currentUrlTree=a.urlAfterRedirects,this.rawUrlTree=this.urlHandlingStrategy.merge(a.urlAfterRedirects,a.rawUrl),this.routerState=a.targetRouterState,\"deferred\"===this.urlUpdateStrategy&&(a.extras.skipLocationChange||this.setBrowserUrl(this.rawUrlTree,a),this.browserUrlTree=a.urlAfterRedirects)}),((n,t,e)=>ue(i=>(new CV(t,i.targetRouterState,i.currentRouterState,e).activate(n),i)))(this.rootContexts,this.routeReuseStrategy,a=>this.triggerEvent(a)),Mt({next(){s=!0},complete(){s=!0}}),function WD(n){return qe((t,e)=>{try{t.subscribe(e)}finally{e.add(n)}})}(()=>{var a;s||o||this.cancelNavigationTransition(r,`Navigation ID ${r.id} is not equal to the current navigation id ${this.navigationId}`),(null===(a=this.currentNavigation)||void 0===a?void 0:a.id)===r.id&&(this.currentNavigation=null)}),Ni(a=>{if(o=!0,function UB(n){return n&&n[ZD]}(a)){const l=Lr(a.url);l||(this.navigated=!0,this.restoreHistory(r,!0));const c=new qD(r.id,this.serializeUrl(r.extractedUrl),a.message);i.next(c),l?setTimeout(()=>{const d=this.urlHandlingStrategy.merge(a.url,this.rawUrlTree),u={skipLocationChange:r.extras.skipLocationChange,replaceUrl:\"eager\"===this.urlUpdateStrategy||Hw(r.source)};this.scheduleNavigation(d,\"imperative\",null,u,{resolve:r.resolve,reject:r.reject,promise:r.promise})},0):r.resolve(!1)}else{this.restoreHistory(r,!0);const l=new RB(r.id,this.serializeUrl(r.extractedUrl),a);i.next(l);try{r.resolve(this.errorHandler(a))}catch(c){r.reject(c)}}return ri}))}))}resetRootComponentType(e){this.rootComponentType=e,this.routerState.root.component=this.rootComponentType}setTransition(e){this.transitions.next(Object.assign(Object.assign({},this.transitions.value),e))}initialNavigation(){this.setUpLocationChangeListener(),0===this.navigationId&&this.navigateByUrl(this.location.path(!0),{replaceUrl:!0})}setUpLocationChangeListener(){this.locationSubscription||(this.locationSubscription=this.location.subscribe(e=>{const i=\"popstate\"===e.type?\"popstate\":\"hashchange\";\"popstate\"===i&&setTimeout(()=>{var r;const s={replaceUrl:!0},o=(null===(r=e.state)||void 0===r?void 0:r.navigationId)?e.state:null;if(o){const l=Object.assign({},o);delete l.navigationId,delete l.\\u0275routerPageId,0!==Object.keys(l).length&&(s.state=l)}const a=this.parseUrl(e.url);this.scheduleNavigation(a,i,o,s)},0)}))}get url(){return this.serializeUrl(this.currentUrlTree)}getCurrentNavigation(){return this.currentNavigation}triggerEvent(e){this.events.next(e)}resetConfig(e){ww(e),this.config=e.map(Ff),this.navigated=!1,this.lastSuccessfulId=-1}ngOnDestroy(){this.dispose()}dispose(){this.transitions.complete(),this.locationSubscription&&(this.locationSubscription.unsubscribe(),this.locationSubscription=void 0),this.disposed=!0}createUrlTree(e,i={}){const{relativeTo:r,queryParams:s,fragment:o,queryParamsHandling:a,preserveFragment:l}=i,c=r||this.routerState.root,d=l?this.currentUrlTree.fragment:o;let u=null;switch(a){case\"merge\":u=Object.assign(Object.assign({},this.currentUrlTree.queryParams),s);break;case\"preserve\":u=this.currentUrlTree.queryParams;break;default:u=s||null}return null!==u&&(u=this.removeEmptyProps(u)),function pV(n,t,e,i,r){if(0===e.length)return Af(t.root,t.root,t.root,i,r);const s=function fV(n){if(\"string\"==typeof n[0]&&1===n.length&&\"/\"===n[0])return new vw(!0,0,n);let t=0,e=!1;const i=n.reduce((r,s,o)=>{if(\"object\"==typeof s&&null!=s){if(s.outlets){const a={};return At(s.outlets,(l,c)=>{a[c]=\"string\"==typeof l?l.split(\"/\"):l}),[...r,{outlets:a}]}if(s.segmentPath)return[...r,s.segmentPath]}return\"string\"!=typeof s?[...r,s]:0===o?(s.split(\"/\").forEach((a,l)=>{0==l&&\".\"===a||(0==l&&\"\"===a?e=!0:\"..\"===a?t++:\"\"!=a&&r.push(a))}),r):[...r,s]},[]);return new vw(e,t,i)}(e);if(s.toRoot())return Af(t.root,t.root,new ye([],{}),i,r);const o=function mV(n,t,e){if(n.isAbsolute)return new If(t.root,!0,0);if(-1===e.snapshot._lastPathIndex){const s=e.snapshot._urlSegment;return new If(s,s===t.root,0)}const i=Yc(n.commands[0])?0:1;return function gV(n,t,e){let i=n,r=t,s=e;for(;s>r;){if(s-=r,i=i.parent,!i)throw new Error(\"Invalid number of '../'\");r=i.segments.length}return new If(i,!1,r-s)}(e.snapshot._urlSegment,e.snapshot._lastPathIndex+i,n.numberOfDoubleDots)}(s,t,n),a=o.processChildren?Qc(o.segmentGroup,o.index,s.commands):yw(o.segmentGroup,o.index,s.commands);return Af(t.root,o.segmentGroup,a,i,r)}(c,this.currentUrlTree,e,u,null!=d?d:null)}navigateByUrl(e,i={skipLocationChange:!1}){const r=Lr(e)?e:this.parseUrl(e),s=this.urlHandlingStrategy.merge(r,this.rawUrlTree);return this.scheduleNavigation(s,\"imperative\",null,i)}navigate(e,i={skipLocationChange:!1}){return function D2(n){for(let t=0;t<n.length;t++){const e=n[t];if(null==e)throw new Error(`The requested path contains ${e} segment at index ${t}`)}}(e),this.navigateByUrl(this.createUrlTree(e,i),i)}serializeUrl(e){return this.urlSerializer.serialize(e)}parseUrl(e){let i;try{i=this.urlSerializer.parse(e)}catch(r){i=this.malformedUriErrorHandler(r,this.urlSerializer,e)}return i}isActive(e,i){let r;if(r=!0===i?Object.assign({},b2):!1===i?Object.assign({},C2):i,Lr(e))return nw(this.currentUrlTree,e,r);const s=this.parseUrl(e);return nw(this.currentUrlTree,s,r)}removeEmptyProps(e){return Object.keys(e).reduce((i,r)=>{const s=e[r];return null!=s&&(i[r]=s),i},{})}processNavigations(){this.navigations.subscribe(e=>{this.navigated=!0,this.lastSuccessfulId=e.id,this.currentPageId=e.targetPageId,this.events.next(new Ea(e.id,this.serializeUrl(e.extractedUrl),this.serializeUrl(this.currentUrlTree))),this.lastSuccessfulNavigation=this.currentNavigation,e.resolve(!0)},e=>{this.console.warn(`Unhandled Navigation Error: ${e}`)})}scheduleNavigation(e,i,r,s,o){var a,l;if(this.disposed)return Promise.resolve(!1);let c,d,u;o?(c=o.resolve,d=o.reject,u=o.promise):u=new Promise((m,g)=>{c=m,d=g});const h=++this.navigationId;let p;return\"computed\"===this.canceledNavigationResolution?(0===this.currentPageId&&(r=this.location.getState()),p=r&&r.\\u0275routerPageId?r.\\u0275routerPageId:s.replaceUrl||s.skipLocationChange?null!==(a=this.browserPageId)&&void 0!==a?a:0:(null!==(l=this.browserPageId)&&void 0!==l?l:0)+1):p=0,this.setTransition({id:h,targetPageId:p,source:i,restoredState:r,currentUrlTree:this.currentUrlTree,currentRawUrl:this.rawUrlTree,rawUrl:e,extras:s,resolve:c,reject:d,promise:u,currentSnapshot:this.routerState.snapshot,currentRouterState:this.routerState}),u.catch(m=>Promise.reject(m))}setBrowserUrl(e,i){const r=this.urlSerializer.serialize(e),s=Object.assign(Object.assign({},i.extras.state),this.generateNgRouterState(i.id,i.targetPageId));this.location.isCurrentPathEqualTo(r)||i.extras.replaceUrl?this.location.replaceState(r,\"\",s):this.location.go(r,\"\",s)}restoreHistory(e,i=!1){var r,s;if(\"computed\"===this.canceledNavigationResolution){const o=this.currentPageId-e.targetPageId;\"popstate\"!==e.source&&\"eager\"!==this.urlUpdateStrategy&&this.currentUrlTree!==(null===(r=this.currentNavigation)||void 0===r?void 0:r.finalUrl)||0===o?this.currentUrlTree===(null===(s=this.currentNavigation)||void 0===s?void 0:s.finalUrl)&&0===o&&(this.resetState(e),this.browserUrlTree=e.currentUrlTree,this.resetUrlToCurrentUrlTree()):this.location.historyGo(o)}else\"replace\"===this.canceledNavigationResolution&&(i&&this.resetState(e),this.resetUrlToCurrentUrlTree())}resetState(e){this.routerState=e.currentRouterState,this.currentUrlTree=e.currentUrlTree,this.rawUrlTree=this.urlHandlingStrategy.merge(this.currentUrlTree,e.rawUrl)}resetUrlToCurrentUrlTree(){this.location.replaceState(this.urlSerializer.serialize(this.rawUrlTree),\"\",this.generateNgRouterState(this.lastSuccessfulId,this.currentPageId))}cancelNavigationTransition(e,i){const r=new qD(e.id,this.serializeUrl(e.extractedUrl),i);this.triggerEvent(r),e.resolve(!1)}generateNgRouterState(e,i){return\"computed\"===this.canceledNavigationResolution?{navigationId:e,\\u0275routerPageId:i}:{navigationId:e}}}return n.\\u0275fac=function(e){Sr()},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();function Hw(n){return\"imperative\"!==n}class jw{}class zw{preload(t,e){return q(null)}}let Uw=(()=>{class n{constructor(e,i,r,s){this.router=e,this.injector=r,this.preloadingStrategy=s,this.loader=new Bw(r,i,l=>e.triggerEvent(new YD(l)),l=>e.triggerEvent(new QD(l)))}setUpPreloading(){this.subscription=this.router.events.pipe(Ct(e=>e instanceof Ea),Qs(()=>this.preload())).subscribe(()=>{})}preload(){const e=this.injector.get(Ri);return this.processRoutes(e,this.router.config)}ngOnDestroy(){this.subscription&&this.subscription.unsubscribe()}processRoutes(e,i){const r=[];for(const s of i)if(s.loadChildren&&!s.canLoad&&s._loadedConfig){const o=s._loadedConfig;r.push(this.processRoutes(o.module,o.routes))}else s.loadChildren&&!s.canLoad?r.push(this.preloadConfig(e,s)):s.children&&r.push(this.processRoutes(e,s.children));return mt(r).pipe(Eo(),ue(s=>{}))}preloadConfig(e,i){return this.preloadingStrategy.preload(i,()=>(i._loadedConfig?q(i._loadedConfig):this.loader.load(e.injector,i)).pipe(lt(s=>(i._loadedConfig=s,this.processRoutes(s.module,s.routes)))))}}return n.\\u0275fac=function(e){return new(e||n)(y(cn),y(P0),y(dt),y(jw))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),jf=(()=>{class n{constructor(e,i,r={}){this.router=e,this.viewportScroller=i,this.options=r,this.lastId=0,this.lastSource=\"imperative\",this.restoredId=0,this.store={},r.scrollPositionRestoration=r.scrollPositionRestoration||\"disabled\",r.anchorScrolling=r.anchorScrolling||\"disabled\"}init(){\"disabled\"!==this.options.scrollPositionRestoration&&this.viewportScroller.setHistoryScrollRestoration(\"manual\"),this.routerEventsSubscription=this.createScrollEvents(),this.scrollEventsSubscription=this.consumeScrollEvents()}createScrollEvents(){return this.router.events.subscribe(e=>{e instanceof Df?(this.store[this.lastId]=this.viewportScroller.getScrollPosition(),this.lastSource=e.navigationTrigger,this.restoredId=e.restoredState?e.restoredState.navigationId:0):e instanceof Ea&&(this.lastId=e.id,this.scheduleScrollEvent(e,this.router.parseUrl(e.urlAfterRedirects).fragment))})}consumeScrollEvents(){return this.router.events.subscribe(e=>{e instanceof KD&&(e.position?\"top\"===this.options.scrollPositionRestoration?this.viewportScroller.scrollToPosition([0,0]):\"enabled\"===this.options.scrollPositionRestoration&&this.viewportScroller.scrollToPosition(e.position):e.anchor&&\"enabled\"===this.options.anchorScrolling?this.viewportScroller.scrollToAnchor(e.anchor):\"disabled\"!==this.options.scrollPositionRestoration&&this.viewportScroller.scrollToPosition([0,0]))})}scheduleScrollEvent(e,i){this.router.triggerEvent(new KD(e,\"popstate\"===this.lastSource?this.store[this.restoredId]:null,i))}ngOnDestroy(){this.routerEventsSubscription&&this.routerEventsSubscription.unsubscribe(),this.scrollEventsSubscription&&this.scrollEventsSubscription.unsubscribe()}}return n.\\u0275fac=function(e){Sr()},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const Br=new b(\"ROUTER_CONFIGURATION\"),$w=new b(\"ROUTER_FORROOT_GUARD\"),E2=[va,{provide:ow,useClass:aw},{provide:cn,useFactory:function I2(n,t,e,i,r,s,o={},a,l){const c=new cn(null,n,t,e,i,r,JD(s));return a&&(c.urlHandlingStrategy=a),l&&(c.routeReuseStrategy=l),function R2(n,t){n.errorHandler&&(t.errorHandler=n.errorHandler),n.malformedUriErrorHandler&&(t.malformedUriErrorHandler=n.malformedUriErrorHandler),n.onSameUrlNavigation&&(t.onSameUrlNavigation=n.onSameUrlNavigation),n.paramsInheritanceStrategy&&(t.paramsInheritanceStrategy=n.paramsInheritanceStrategy),n.relativeLinkResolution&&(t.relativeLinkResolution=n.relativeLinkResolution),n.urlUpdateStrategy&&(t.urlUpdateStrategy=n.urlUpdateStrategy),n.canceledNavigationResolution&&(t.canceledNavigationResolution=n.canceledNavigationResolution)}(o,c),o.enableTracing&&c.events.subscribe(d=>{var u,h;null===(u=console.group)||void 0===u||u.call(console,`Router Event: ${d.constructor.name}`),console.log(d.toString()),console.log(d),null===(h=console.groupEnd)||void 0===h||h.call(console)}),c},deps:[ow,Oa,va,dt,P0,Bf,Br,[class g2{},new Tt],[class p2{},new Tt]]},Oa,{provide:Js,useFactory:function O2(n){return n.routerState.root},deps:[cn]},Uw,zw,class x2{preload(t,e){return e().pipe(Ni(()=>q(null)))}},{provide:Br,useValue:{enableTracing:!1}}];function S2(){return new V0(\"Router\",cn)}let Gw=(()=>{class n{constructor(e,i){}static forRoot(e,i){return{ngModule:n,providers:[E2,Ww(e),{provide:$w,useFactory:A2,deps:[[cn,new Tt,new Cn]]},{provide:Br,useValue:i||{}},{provide:qs,useFactory:T2,deps:[Pr,[new Gl(Xp),new Tt],Br]},{provide:jf,useFactory:k2,deps:[cn,PL,Br]},{provide:jw,useExisting:i&&i.preloadingStrategy?i.preloadingStrategy:zw},{provide:V0,multi:!0,useFactory:S2},[zf,{provide:Bp,multi:!0,useFactory:P2,deps:[zf]},{provide:qw,useFactory:F2,deps:[zf]},{provide:R0,multi:!0,useExisting:qw}]]}}static forChild(e){return{ngModule:n,providers:[Ww(e)]}}}return n.\\u0275fac=function(e){return new(e||n)(y($w,8),y(cn,8))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();function k2(n,t,e){return e.scrollOffset&&t.setOffset(e.scrollOffset),new jf(n,t,e)}function T2(n,t,e={}){return e.useHash?new vN(n,t):new sD(n,t)}function A2(n){return\"guarded\"}function Ww(n){return[{provide:nA,multi:!0,useValue:n},{provide:Bf,multi:!0,useValue:n}]}let zf=(()=>{class n{constructor(e){this.injector=e,this.initNavigation=!1,this.destroyed=!1,this.resultOfPreactivationDone=new O}appInitializer(){return this.injector.get(mN,Promise.resolve(null)).then(()=>{if(this.destroyed)return Promise.resolve(!0);let i=null;const r=new Promise(a=>i=a),s=this.injector.get(cn),o=this.injector.get(Br);return\"disabled\"===o.initialNavigation?(s.setUpLocationChangeListener(),i(!0)):\"enabled\"===o.initialNavigation||\"enabledBlocking\"===o.initialNavigation?(s.hooks.afterPreactivation=()=>this.initNavigation?q(null):(this.initNavigation=!0,i(!0),this.resultOfPreactivationDone),s.initialNavigation()):i(!0),r})}bootstrapListener(e){const i=this.injector.get(Br),r=this.injector.get(Uw),s=this.injector.get(jf),o=this.injector.get(cn),a=this.injector.get(Cc);e===a.components[0]&&((\"enabledNonBlocking\"===i.initialNavigation||void 0===i.initialNavigation)&&o.initialNavigation(),r.setUpPreloading(),s.init(),o.resetRootComponentType(a.componentTypes[0]),this.resultOfPreactivationDone.next(null),this.resultOfPreactivationDone.complete())}ngOnDestroy(){this.destroyed=!0}}return n.\\u0275fac=function(e){return new(e||n)(y(dt))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();function P2(n){return n.appInitializer.bind(n)}function F2(n){return n.bootstrapListener.bind(n)}const qw=new b(\"Router Initializer\"),L2=[];let B2=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Gw.forRoot(L2)],Gw]}),n})();class Yw{}const Vi=\"*\";function Ke(n,t){return{type:7,name:n,definitions:t,options:{}}}function be(n,t=null){return{type:4,styles:t,timings:n}}function nd(n,t=null){return{type:3,steps:n,options:t}}function Qw(n,t=null){return{type:2,steps:n,options:t}}function R(n){return{type:6,styles:n,offset:null}}function ae(n,t,e){return{type:0,name:n,styles:t,options:e}}function ge(n,t,e=null){return{type:1,expr:n,animation:t,options:e}}function to(n=null){return{type:9,options:n}}function no(n,t,e=null){return{type:11,selector:n,animation:t,options:e}}function Kw(n){Promise.resolve(null).then(n)}class La{constructor(t=0,e=0){this._onDoneFns=[],this._onStartFns=[],this._onDestroyFns=[],this._started=!1,this._destroyed=!1,this._finished=!1,this._position=0,this.parentPlayer=null,this.totalTime=t+e}_onFinish(){this._finished||(this._finished=!0,this._onDoneFns.forEach(t=>t()),this._onDoneFns=[])}onStart(t){this._onStartFns.push(t)}onDone(t){this._onDoneFns.push(t)}onDestroy(t){this._onDestroyFns.push(t)}hasStarted(){return this._started}init(){}play(){this.hasStarted()||(this._onStart(),this.triggerMicrotask()),this._started=!0}triggerMicrotask(){Kw(()=>this._onFinish())}_onStart(){this._onStartFns.forEach(t=>t()),this._onStartFns=[]}pause(){}restart(){}finish(){this._onFinish()}destroy(){this._destroyed||(this._destroyed=!0,this.hasStarted()||this._onStart(),this.finish(),this._onDestroyFns.forEach(t=>t()),this._onDestroyFns=[])}reset(){this._started=!1}setPosition(t){this._position=this.totalTime?t*this.totalTime:1}getPosition(){return this.totalTime?this._position/this.totalTime:1}triggerCallback(t){const e=\"start\"==t?this._onStartFns:this._onDoneFns;e.forEach(i=>i()),e.length=0}}class Zw{constructor(t){this._onDoneFns=[],this._onStartFns=[],this._finished=!1,this._started=!1,this._destroyed=!1,this._onDestroyFns=[],this.parentPlayer=null,this.totalTime=0,this.players=t;let e=0,i=0,r=0;const s=this.players.length;0==s?Kw(()=>this._onFinish()):this.players.forEach(o=>{o.onDone(()=>{++e==s&&this._onFinish()}),o.onDestroy(()=>{++i==s&&this._onDestroy()}),o.onStart(()=>{++r==s&&this._onStart()})}),this.totalTime=this.players.reduce((o,a)=>Math.max(o,a.totalTime),0)}_onFinish(){this._finished||(this._finished=!0,this._onDoneFns.forEach(t=>t()),this._onDoneFns=[])}init(){this.players.forEach(t=>t.init())}onStart(t){this._onStartFns.push(t)}_onStart(){this.hasStarted()||(this._started=!0,this._onStartFns.forEach(t=>t()),this._onStartFns=[])}onDone(t){this._onDoneFns.push(t)}onDestroy(t){this._onDestroyFns.push(t)}hasStarted(){return this._started}play(){this.parentPlayer||this.init(),this._onStart(),this.players.forEach(t=>t.play())}pause(){this.players.forEach(t=>t.pause())}restart(){this.players.forEach(t=>t.restart())}finish(){this._onFinish(),this.players.forEach(t=>t.finish())}destroy(){this._onDestroy()}_onDestroy(){this._destroyed||(this._destroyed=!0,this._onFinish(),this.players.forEach(t=>t.destroy()),this._onDestroyFns.forEach(t=>t()),this._onDestroyFns=[])}reset(){this.players.forEach(t=>t.reset()),this._destroyed=!1,this._finished=!1,this._started=!1}setPosition(t){const e=t*this.totalTime;this.players.forEach(i=>{const r=i.totalTime?Math.min(1,e/i.totalTime):1;i.setPosition(r)})}getPosition(){const t=this.players.reduce((e,i)=>null===e||i.totalTime>e.totalTime?i:e,null);return null!=t?t.getPosition():0}beforeDestroy(){this.players.forEach(t=>{t.beforeDestroy&&t.beforeDestroy()})}triggerCallback(t){const e=\"start\"==t?this._onStartFns:this._onDoneFns;e.forEach(i=>i()),e.length=0}}const Ce=!1;function Xw(n){return new H(3e3,Ce)}function yH(){return\"undefined\"!=typeof window&&void 0!==window.document}function $f(){return\"undefined\"!=typeof process&&\"[object process]\"==={}.toString.call(process)}function ir(n){switch(n.length){case 0:return new La;case 1:return n[0];default:return new Zw(n)}}function Jw(n,t,e,i,r={},s={}){const o=[],a=[];let l=-1,c=null;if(i.forEach(d=>{const u=d.offset,h=u==l,p=h&&c||{};Object.keys(d).forEach(m=>{let g=m,_=d[m];if(\"offset\"!==m)switch(g=t.normalizePropertyName(g,o),_){case\"!\":_=r[m];break;case Vi:_=s[m];break;default:_=t.normalizeStyleValue(m,g,_,o)}p[g]=_}),h||a.push(p),c=p,l=u}),o.length)throw function lH(n){return new H(3502,Ce)}();return a}function Gf(n,t,e,i){switch(t){case\"start\":n.onStart(()=>i(e&&Wf(e,\"start\",n)));break;case\"done\":n.onDone(()=>i(e&&Wf(e,\"done\",n)));break;case\"destroy\":n.onDestroy(()=>i(e&&Wf(e,\"destroy\",n)))}}function Wf(n,t,e){const i=e.totalTime,s=qf(n.element,n.triggerName,n.fromState,n.toState,t||n.phaseName,null==i?n.totalTime:i,!!e.disabled),o=n._data;return null!=o&&(s._data=o),s}function qf(n,t,e,i,r=\"\",s=0,o){return{element:n,triggerName:t,fromState:e,toState:i,phaseName:r,totalTime:s,disabled:!!o}}function dn(n,t,e){let i;return n instanceof Map?(i=n.get(t),i||n.set(t,i=e)):(i=n[t],i||(i=n[t]=e)),i}function eM(n){const t=n.indexOf(\":\");return[n.substring(1,t),n.substr(t+1)]}let Yf=(n,t)=>!1,tM=(n,t,e)=>[],nM=null;function Qf(n){const t=n.parentNode||n.host;return t===nM?null:t}($f()||\"undefined\"!=typeof Element)&&(yH()?(nM=(()=>document.documentElement)(),Yf=(n,t)=>{for(;t;){if(t===n)return!0;t=Qf(t)}return!1}):Yf=(n,t)=>n.contains(t),tM=(n,t,e)=>{if(e)return Array.from(n.querySelectorAll(t));const i=n.querySelector(t);return i?[i]:[]});let Hr=null,iM=!1;function rM(n){Hr||(Hr=function CH(){return\"undefined\"!=typeof document?document.body:null}()||{},iM=!!Hr.style&&\"WebkitAppearance\"in Hr.style);let t=!0;return Hr.style&&!function bH(n){return\"ebkit\"==n.substring(1,6)}(n)&&(t=n in Hr.style,!t&&iM&&(t=\"Webkit\"+n.charAt(0).toUpperCase()+n.substr(1)in Hr.style)),t}const sM=Yf,oM=tM;let aM=(()=>{class n{validateStyleProperty(e){return rM(e)}matchesElement(e,i){return!1}containsElement(e,i){return sM(e,i)}getParentElement(e){return Qf(e)}query(e,i,r){return oM(e,i,r)}computeStyle(e,i,r){return r||\"\"}animate(e,i,r,s,o,a=[],l){return new La(r,s)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),Kf=(()=>{class n{}return n.NOOP=new aM,n})();const Zf=\"ng-enter\",rd=\"ng-leave\",sd=\"ng-trigger\",od=\".ng-trigger\",cM=\"ng-animating\",Xf=\".ng-animating\";function jr(n){if(\"number\"==typeof n)return n;const t=n.match(/^(-?[\\.\\d]+)(m?s)/);return!t||t.length<2?0:Jf(parseFloat(t[1]),t[2])}function Jf(n,t){return\"s\"===t?1e3*n:n}function ad(n,t,e){return n.hasOwnProperty(\"duration\")?n:function MH(n,t,e){let r,s=0,o=\"\";if(\"string\"==typeof n){const a=n.match(/^(-?[\\.\\d]+)(m?s)(?:\\s+(-?[\\.\\d]+)(m?s))?(?:\\s+([-a-z]+(?:\\(.+?\\))?))?$/i);if(null===a)return t.push(Xw()),{duration:0,delay:0,easing:\"\"};r=Jf(parseFloat(a[1]),a[2]);const l=a[3];null!=l&&(s=Jf(parseFloat(l),a[4]));const c=a[5];c&&(o=c)}else r=n;if(!e){let a=!1,l=t.length;r<0&&(t.push(function H2(){return new H(3100,Ce)}()),a=!0),s<0&&(t.push(function j2(){return new H(3101,Ce)}()),a=!0),a&&t.splice(l,0,Xw())}return{duration:r,delay:s,easing:o}}(n,t,e)}function io(n,t={}){return Object.keys(n).forEach(e=>{t[e]=n[e]}),t}function rr(n,t,e={}){if(t)for(let i in n)e[i]=n[i];else io(n,e);return e}function uM(n,t,e){return e?t+\":\"+e+\";\":\"\"}function hM(n){let t=\"\";for(let e=0;e<n.style.length;e++){const i=n.style.item(e);t+=uM(0,i,n.style.getPropertyValue(i))}for(const e in n.style)n.style.hasOwnProperty(e)&&!e.startsWith(\"_\")&&(t+=uM(0,SH(e),n.style[e]));n.setAttribute(\"style\",t)}function vi(n,t,e){n.style&&(Object.keys(t).forEach(i=>{const r=tm(i);e&&!e.hasOwnProperty(i)&&(e[i]=n.style[r]),n.style[r]=t[i]}),$f()&&hM(n))}function zr(n,t){n.style&&(Object.keys(t).forEach(e=>{const i=tm(e);n.style[i]=\"\"}),$f()&&hM(n))}function Ba(n){return Array.isArray(n)?1==n.length?n[0]:Qw(n):n}const em=new RegExp(\"{{\\\\s*(.+?)\\\\s*}}\",\"g\");function pM(n){let t=[];if(\"string\"==typeof n){let e;for(;e=em.exec(n);)t.push(e[1]);em.lastIndex=0}return t}function ld(n,t,e){const i=n.toString(),r=i.replace(em,(s,o)=>{let a=t[o];return t.hasOwnProperty(o)||(e.push(function U2(n){return new H(3003,Ce)}()),a=\"\"),a.toString()});return r==i?n:r}function cd(n){const t=[];let e=n.next();for(;!e.done;)t.push(e.value),e=n.next();return t}const EH=/-+([a-z0-9])/g;function tm(n){return n.replace(EH,(...t)=>t[1].toUpperCase())}function SH(n){return n.replace(/([a-z])([A-Z])/g,\"$1-$2\").toLowerCase()}function un(n,t,e){switch(t.type){case 7:return n.visitTrigger(t,e);case 0:return n.visitState(t,e);case 1:return n.visitTransition(t,e);case 2:return n.visitSequence(t,e);case 3:return n.visitGroup(t,e);case 4:return n.visitAnimate(t,e);case 5:return n.visitKeyframes(t,e);case 6:return n.visitStyle(t,e);case 8:return n.visitReference(t,e);case 9:return n.visitAnimateChild(t,e);case 10:return n.visitAnimateRef(t,e);case 11:return n.visitQuery(t,e);case 12:return n.visitStagger(t,e);default:throw function $2(n){return new H(3004,Ce)}()}}function fM(n,t){return window.getComputedStyle(n)[t]}function OH(n,t){const e=[];return\"string\"==typeof n?n.split(/\\s*,\\s*/).forEach(i=>function PH(n,t,e){if(\":\"==n[0]){const l=function FH(n,t){switch(n){case\":enter\":return\"void => *\";case\":leave\":return\"* => void\";case\":increment\":return(e,i)=>parseFloat(i)>parseFloat(e);case\":decrement\":return(e,i)=>parseFloat(i)<parseFloat(e);default:return t.push(function rH(n){return new H(3016,Ce)}()),\"* => *\"}}(n,e);if(\"function\"==typeof l)return void t.push(l);n=l}const i=n.match(/^(\\*|[-\\w]+)\\s*(<?[=-]>)\\s*(\\*|[-\\w]+)$/);if(null==i||i.length<4)return e.push(function iH(n){return new H(3015,Ce)}()),t;const r=i[1],s=i[2],o=i[3];t.push(mM(r,o));\"<\"==s[0]&&!(\"*\"==r&&\"*\"==o)&&t.push(mM(o,r))}(i,e,t)):e.push(n),e}const pd=new Set([\"true\",\"1\"]),fd=new Set([\"false\",\"0\"]);function mM(n,t){const e=pd.has(n)||fd.has(n),i=pd.has(t)||fd.has(t);return(r,s)=>{let o=\"*\"==n||n==r,a=\"*\"==t||t==s;return!o&&e&&\"boolean\"==typeof r&&(o=r?pd.has(n):fd.has(n)),!a&&i&&\"boolean\"==typeof s&&(a=s?pd.has(t):fd.has(t)),o&&a}}const NH=new RegExp(\"s*:selfs*,?\",\"g\");function nm(n,t,e,i){return new LH(n).build(t,e,i)}class LH{constructor(t){this._driver=t}build(t,e,i){const r=new HH(e);this._resetContextStyleTimingState(r);const s=un(this,Ba(t),r);return r.unsupportedCSSPropertiesFound.size&&r.unsupportedCSSPropertiesFound.keys(),s}_resetContextStyleTimingState(t){t.currentQuerySelector=\"\",t.collectedStyles={},t.collectedStyles[\"\"]={},t.currentTime=0}visitTrigger(t,e){let i=e.queryCount=0,r=e.depCount=0;const s=[],o=[];return\"@\"==t.name.charAt(0)&&e.errors.push(function W2(){return new H(3006,Ce)}()),t.definitions.forEach(a=>{if(this._resetContextStyleTimingState(e),0==a.type){const l=a,c=l.name;c.toString().split(/\\s*,\\s*/).forEach(d=>{l.name=d,s.push(this.visitState(l,e))}),l.name=c}else if(1==a.type){const l=this.visitTransition(a,e);i+=l.queryCount,r+=l.depCount,o.push(l)}else e.errors.push(function q2(){return new H(3007,Ce)}())}),{type:7,name:t.name,states:s,transitions:o,queryCount:i,depCount:r,options:null}}visitState(t,e){const i=this.visitStyle(t.styles,e),r=t.options&&t.options.params||null;if(i.containsDynamicStyles){const s=new Set,o=r||{};i.styles.forEach(a=>{if(md(a)){const l=a;Object.keys(l).forEach(c=>{pM(l[c]).forEach(d=>{o.hasOwnProperty(d)||s.add(d)})})}}),s.size&&(cd(s.values()),e.errors.push(function Y2(n,t){return new H(3008,Ce)}()))}return{type:0,name:t.name,style:i,options:r?{params:r}:null}}visitTransition(t,e){e.queryCount=0,e.depCount=0;const i=un(this,Ba(t.animation),e);return{type:1,matchers:OH(t.expr,e.errors),animation:i,queryCount:e.queryCount,depCount:e.depCount,options:Ur(t.options)}}visitSequence(t,e){return{type:2,steps:t.steps.map(i=>un(this,i,e)),options:Ur(t.options)}}visitGroup(t,e){const i=e.currentTime;let r=0;const s=t.steps.map(o=>{e.currentTime=i;const a=un(this,o,e);return r=Math.max(r,e.currentTime),a});return e.currentTime=r,{type:3,steps:s,options:Ur(t.options)}}visitAnimate(t,e){const i=function zH(n,t){let e=null;if(n.hasOwnProperty(\"duration\"))e=n;else if(\"number\"==typeof n)return im(ad(n,t).duration,0,\"\");const i=n;if(i.split(/\\s+/).some(s=>\"{\"==s.charAt(0)&&\"{\"==s.charAt(1))){const s=im(0,0,\"\");return s.dynamic=!0,s.strValue=i,s}return e=e||ad(i,t),im(e.duration,e.delay,e.easing)}(t.timings,e.errors);e.currentAnimateTimings=i;let r,s=t.styles?t.styles:R({});if(5==s.type)r=this.visitKeyframes(s,e);else{let o=t.styles,a=!1;if(!o){a=!0;const c={};i.easing&&(c.easing=i.easing),o=R(c)}e.currentTime+=i.duration+i.delay;const l=this.visitStyle(o,e);l.isEmptyStep=a,r=l}return e.currentAnimateTimings=null,{type:4,timings:i,style:r,options:null}}visitStyle(t,e){const i=this._makeStyleAst(t,e);return this._validateStyleAst(i,e),i}_makeStyleAst(t,e){const i=[];Array.isArray(t.styles)?t.styles.forEach(o=>{\"string\"==typeof o?o==Vi?i.push(o):e.errors.push(function Q2(n){return new H(3002,Ce)}()):i.push(o)}):i.push(t.styles);let r=!1,s=null;return i.forEach(o=>{if(md(o)){const a=o,l=a.easing;if(l&&(s=l,delete a.easing),!r)for(let c in a)if(a[c].toString().indexOf(\"{{\")>=0){r=!0;break}}}),{type:6,styles:i,easing:s,offset:t.offset,containsDynamicStyles:r,options:null}}_validateStyleAst(t,e){const i=e.currentAnimateTimings;let r=e.currentTime,s=e.currentTime;i&&s>0&&(s-=i.duration+i.delay),t.styles.forEach(o=>{\"string\"!=typeof o&&Object.keys(o).forEach(a=>{if(!this._driver.validateStyleProperty(a))return delete o[a],void e.unsupportedCSSPropertiesFound.add(a);const l=e.collectedStyles[e.currentQuerySelector],c=l[a];let d=!0;c&&(s!=r&&s>=c.startTime&&r<=c.endTime&&(e.errors.push(function K2(n,t,e,i,r){return new H(3010,Ce)}()),d=!1),s=c.startTime),d&&(l[a]={startTime:s,endTime:r}),e.options&&function xH(n,t,e){const i=t.params||{},r=pM(n);r.length&&r.forEach(s=>{i.hasOwnProperty(s)||e.push(function z2(n){return new H(3001,Ce)}())})}(o[a],e.options,e.errors)})})}visitKeyframes(t,e){const i={type:5,styles:[],options:null};if(!e.currentAnimateTimings)return e.errors.push(function Z2(){return new H(3011,Ce)}()),i;let s=0;const o=[];let a=!1,l=!1,c=0;const d=t.steps.map(D=>{const v=this._makeStyleAst(D,e);let M=null!=v.offset?v.offset:function jH(n){if(\"string\"==typeof n)return null;let t=null;if(Array.isArray(n))n.forEach(e=>{if(md(e)&&e.hasOwnProperty(\"offset\")){const i=e;t=parseFloat(i.offset),delete i.offset}});else if(md(n)&&n.hasOwnProperty(\"offset\")){const e=n;t=parseFloat(e.offset),delete e.offset}return t}(v.styles),V=0;return null!=M&&(s++,V=v.offset=M),l=l||V<0||V>1,a=a||V<c,c=V,o.push(V),v});l&&e.errors.push(function X2(){return new H(3012,Ce)}()),a&&e.errors.push(function J2(){return new H(3200,Ce)}());const u=t.steps.length;let h=0;s>0&&s<u?e.errors.push(function eH(){return new H(3202,Ce)}()):0==s&&(h=1/(u-1));const p=u-1,m=e.currentTime,g=e.currentAnimateTimings,_=g.duration;return d.forEach((D,v)=>{const M=h>0?v==p?1:h*v:o[v],V=M*_;e.currentTime=m+g.delay+V,g.duration=V,this._validateStyleAst(D,e),D.offset=M,i.styles.push(D)}),i}visitReference(t,e){return{type:8,animation:un(this,Ba(t.animation),e),options:Ur(t.options)}}visitAnimateChild(t,e){return e.depCount++,{type:9,options:Ur(t.options)}}visitAnimateRef(t,e){return{type:10,animation:this.visitReference(t.animation,e),options:Ur(t.options)}}visitQuery(t,e){const i=e.currentQuerySelector,r=t.options||{};e.queryCount++,e.currentQuery=t;const[s,o]=function BH(n){const t=!!n.split(/\\s*,\\s*/).find(e=>\":self\"==e);return t&&(n=n.replace(NH,\"\")),n=n.replace(/@\\*/g,od).replace(/@\\w+/g,e=>od+\"-\"+e.substr(1)).replace(/:animating/g,Xf),[n,t]}(t.selector);e.currentQuerySelector=i.length?i+\" \"+s:s,dn(e.collectedStyles,e.currentQuerySelector,{});const a=un(this,Ba(t.animation),e);return e.currentQuery=null,e.currentQuerySelector=i,{type:11,selector:s,limit:r.limit||0,optional:!!r.optional,includeSelf:o,animation:a,originalSelector:t.selector,options:Ur(t.options)}}visitStagger(t,e){e.currentQuery||e.errors.push(function tH(){return new H(3013,Ce)}());const i=\"full\"===t.timings?{duration:0,delay:0,easing:\"full\"}:ad(t.timings,e.errors,!0);return{type:12,animation:un(this,Ba(t.animation),e),timings:i,options:null}}}class HH{constructor(t){this.errors=t,this.queryCount=0,this.depCount=0,this.currentTransition=null,this.currentQuery=null,this.currentQuerySelector=null,this.currentAnimateTimings=null,this.currentTime=0,this.collectedStyles={},this.options=null,this.unsupportedCSSPropertiesFound=new Set}}function md(n){return!Array.isArray(n)&&\"object\"==typeof n}function Ur(n){return n?(n=io(n)).params&&(n.params=function VH(n){return n?io(n):null}(n.params)):n={},n}function im(n,t,e){return{duration:n,delay:t,easing:e}}function rm(n,t,e,i,r,s,o=null,a=!1){return{type:1,element:n,keyframes:t,preStyleProps:e,postStyleProps:i,duration:r,delay:s,totalTime:r+s,easing:o,subTimeline:a}}class gd{constructor(){this._map=new Map}get(t){return this._map.get(t)||[]}append(t,e){let i=this._map.get(t);i||this._map.set(t,i=[]),i.push(...e)}has(t){return this._map.has(t)}clear(){this._map.clear()}}const GH=new RegExp(\":enter\",\"g\"),qH=new RegExp(\":leave\",\"g\");function sm(n,t,e,i,r,s={},o={},a,l,c=[]){return(new YH).buildKeyframes(n,t,e,i,r,s,o,a,l,c)}class YH{buildKeyframes(t,e,i,r,s,o,a,l,c,d=[]){c=c||new gd;const u=new om(t,e,c,r,s,d,[]);u.options=l,u.currentTimeline.setStyles([o],null,u.errors,l),un(this,i,u);const h=u.timelines.filter(p=>p.containsAnimation());if(Object.keys(a).length){let p;for(let m=h.length-1;m>=0;m--){const g=h[m];if(g.element===e){p=g;break}}p&&!p.allowOnlyTimelineStyles()&&p.setStyles([a],null,u.errors,l)}return h.length?h.map(p=>p.buildKeyframes()):[rm(e,[],[],[],0,0,\"\",!1)]}visitTrigger(t,e){}visitState(t,e){}visitTransition(t,e){}visitAnimateChild(t,e){const i=e.subInstructions.get(e.element);if(i){const r=e.createSubContext(t.options),s=e.currentTimeline.currentTime,o=this._visitSubInstructions(i,r,r.options);s!=o&&e.transformIntoNewTimeline(o)}e.previousNode=t}visitAnimateRef(t,e){const i=e.createSubContext(t.options);i.transformIntoNewTimeline(),this.visitReference(t.animation,i),e.transformIntoNewTimeline(i.currentTimeline.currentTime),e.previousNode=t}_visitSubInstructions(t,e,i){let s=e.currentTimeline.currentTime;const o=null!=i.duration?jr(i.duration):null,a=null!=i.delay?jr(i.delay):null;return 0!==o&&t.forEach(l=>{const c=e.appendInstructionToTimeline(l,o,a);s=Math.max(s,c.duration+c.delay)}),s}visitReference(t,e){e.updateOptions(t.options,!0),un(this,t.animation,e),e.previousNode=t}visitSequence(t,e){const i=e.subContextCount;let r=e;const s=t.options;if(s&&(s.params||s.delay)&&(r=e.createSubContext(s),r.transformIntoNewTimeline(),null!=s.delay)){6==r.previousNode.type&&(r.currentTimeline.snapshotCurrentStyles(),r.previousNode=_d);const o=jr(s.delay);r.delayNextStep(o)}t.steps.length&&(t.steps.forEach(o=>un(this,o,r)),r.currentTimeline.applyStylesToKeyframe(),r.subContextCount>i&&r.transformIntoNewTimeline()),e.previousNode=t}visitGroup(t,e){const i=[];let r=e.currentTimeline.currentTime;const s=t.options&&t.options.delay?jr(t.options.delay):0;t.steps.forEach(o=>{const a=e.createSubContext(t.options);s&&a.delayNextStep(s),un(this,o,a),r=Math.max(r,a.currentTimeline.currentTime),i.push(a.currentTimeline)}),i.forEach(o=>e.currentTimeline.mergeTimelineCollectedStyles(o)),e.transformIntoNewTimeline(r),e.previousNode=t}_visitTiming(t,e){if(t.dynamic){const i=t.strValue;return ad(e.params?ld(i,e.params,e.errors):i,e.errors)}return{duration:t.duration,delay:t.delay,easing:t.easing}}visitAnimate(t,e){const i=e.currentAnimateTimings=this._visitTiming(t.timings,e),r=e.currentTimeline;i.delay&&(e.incrementTime(i.delay),r.snapshotCurrentStyles());const s=t.style;5==s.type?this.visitKeyframes(s,e):(e.incrementTime(i.duration),this.visitStyle(s,e),r.applyStylesToKeyframe()),e.currentAnimateTimings=null,e.previousNode=t}visitStyle(t,e){const i=e.currentTimeline,r=e.currentAnimateTimings;!r&&i.getCurrentStyleProperties().length&&i.forwardFrame();const s=r&&r.easing||t.easing;t.isEmptyStep?i.applyEmptyStep(s):i.setStyles(t.styles,s,e.errors,e.options),e.previousNode=t}visitKeyframes(t,e){const i=e.currentAnimateTimings,r=e.currentTimeline.duration,s=i.duration,a=e.createSubContext().currentTimeline;a.easing=i.easing,t.styles.forEach(l=>{a.forwardTime((l.offset||0)*s),a.setStyles(l.styles,l.easing,e.errors,e.options),a.applyStylesToKeyframe()}),e.currentTimeline.mergeTimelineCollectedStyles(a),e.transformIntoNewTimeline(r+s),e.previousNode=t}visitQuery(t,e){const i=e.currentTimeline.currentTime,r=t.options||{},s=r.delay?jr(r.delay):0;s&&(6===e.previousNode.type||0==i&&e.currentTimeline.getCurrentStyleProperties().length)&&(e.currentTimeline.snapshotCurrentStyles(),e.previousNode=_d);let o=i;const a=e.invokeQuery(t.selector,t.originalSelector,t.limit,t.includeSelf,!!r.optional,e.errors);e.currentQueryTotal=a.length;let l=null;a.forEach((c,d)=>{e.currentQueryIndex=d;const u=e.createSubContext(t.options,c);s&&u.delayNextStep(s),c===e.element&&(l=u.currentTimeline),un(this,t.animation,u),u.currentTimeline.applyStylesToKeyframe(),o=Math.max(o,u.currentTimeline.currentTime)}),e.currentQueryIndex=0,e.currentQueryTotal=0,e.transformIntoNewTimeline(o),l&&(e.currentTimeline.mergeTimelineCollectedStyles(l),e.currentTimeline.snapshotCurrentStyles()),e.previousNode=t}visitStagger(t,e){const i=e.parentContext,r=e.currentTimeline,s=t.timings,o=Math.abs(s.duration),a=o*(e.currentQueryTotal-1);let l=o*e.currentQueryIndex;switch(s.duration<0?\"reverse\":s.easing){case\"reverse\":l=a-l;break;case\"full\":l=i.currentStaggerTime}const d=e.currentTimeline;l&&d.delayNextStep(l);const u=d.currentTime;un(this,t.animation,e),e.previousNode=t,i.currentStaggerTime=r.currentTime-u+(r.startTime-i.currentTimeline.startTime)}}const _d={};class om{constructor(t,e,i,r,s,o,a,l){this._driver=t,this.element=e,this.subInstructions=i,this._enterClassName=r,this._leaveClassName=s,this.errors=o,this.timelines=a,this.parentContext=null,this.currentAnimateTimings=null,this.previousNode=_d,this.subContextCount=0,this.options={},this.currentQueryIndex=0,this.currentQueryTotal=0,this.currentStaggerTime=0,this.currentTimeline=l||new vd(this._driver,e,0),a.push(this.currentTimeline)}get params(){return this.options.params}updateOptions(t,e){if(!t)return;const i=t;let r=this.options;null!=i.duration&&(r.duration=jr(i.duration)),null!=i.delay&&(r.delay=jr(i.delay));const s=i.params;if(s){let o=r.params;o||(o=this.options.params={}),Object.keys(s).forEach(a=>{(!e||!o.hasOwnProperty(a))&&(o[a]=ld(s[a],o,this.errors))})}}_copyOptions(){const t={};if(this.options){const e=this.options.params;if(e){const i=t.params={};Object.keys(e).forEach(r=>{i[r]=e[r]})}}return t}createSubContext(t=null,e,i){const r=e||this.element,s=new om(this._driver,r,this.subInstructions,this._enterClassName,this._leaveClassName,this.errors,this.timelines,this.currentTimeline.fork(r,i||0));return s.previousNode=this.previousNode,s.currentAnimateTimings=this.currentAnimateTimings,s.options=this._copyOptions(),s.updateOptions(t),s.currentQueryIndex=this.currentQueryIndex,s.currentQueryTotal=this.currentQueryTotal,s.parentContext=this,this.subContextCount++,s}transformIntoNewTimeline(t){return this.previousNode=_d,this.currentTimeline=this.currentTimeline.fork(this.element,t),this.timelines.push(this.currentTimeline),this.currentTimeline}appendInstructionToTimeline(t,e,i){const r={duration:null!=e?e:t.duration,delay:this.currentTimeline.currentTime+(null!=i?i:0)+t.delay,easing:\"\"},s=new QH(this._driver,t.element,t.keyframes,t.preStyleProps,t.postStyleProps,r,t.stretchStartingKeyframe);return this.timelines.push(s),r}incrementTime(t){this.currentTimeline.forwardTime(this.currentTimeline.duration+t)}delayNextStep(t){t>0&&this.currentTimeline.delayNextStep(t)}invokeQuery(t,e,i,r,s,o){let a=[];if(r&&a.push(this.element),t.length>0){t=(t=t.replace(GH,\".\"+this._enterClassName)).replace(qH,\".\"+this._leaveClassName);let c=this._driver.query(this.element,t,1!=i);0!==i&&(c=i<0?c.slice(c.length+i,c.length):c.slice(0,i)),a.push(...c)}return!s&&0==a.length&&o.push(function nH(n){return new H(3014,Ce)}()),a}}class vd{constructor(t,e,i,r){this._driver=t,this.element=e,this.startTime=i,this._elementTimelineStylesLookup=r,this.duration=0,this._previousKeyframe={},this._currentKeyframe={},this._keyframes=new Map,this._styleSummary={},this._pendingStyles={},this._backFill={},this._currentEmptyStepKeyframe=null,this._elementTimelineStylesLookup||(this._elementTimelineStylesLookup=new Map),this._localTimelineStyles=Object.create(this._backFill,{}),this._globalTimelineStyles=this._elementTimelineStylesLookup.get(e),this._globalTimelineStyles||(this._globalTimelineStyles=this._localTimelineStyles,this._elementTimelineStylesLookup.set(e,this._localTimelineStyles)),this._loadKeyframe()}containsAnimation(){switch(this._keyframes.size){case 0:return!1;case 1:return this.getCurrentStyleProperties().length>0;default:return!0}}getCurrentStyleProperties(){return Object.keys(this._currentKeyframe)}get currentTime(){return this.startTime+this.duration}delayNextStep(t){const e=1==this._keyframes.size&&Object.keys(this._pendingStyles).length;this.duration||e?(this.forwardTime(this.currentTime+t),e&&this.snapshotCurrentStyles()):this.startTime+=t}fork(t,e){return this.applyStylesToKeyframe(),new vd(this._driver,t,e||this.currentTime,this._elementTimelineStylesLookup)}_loadKeyframe(){this._currentKeyframe&&(this._previousKeyframe=this._currentKeyframe),this._currentKeyframe=this._keyframes.get(this.duration),this._currentKeyframe||(this._currentKeyframe=Object.create(this._backFill,{}),this._keyframes.set(this.duration,this._currentKeyframe))}forwardFrame(){this.duration+=1,this._loadKeyframe()}forwardTime(t){this.applyStylesToKeyframe(),this.duration=t,this._loadKeyframe()}_updateStyle(t,e){this._localTimelineStyles[t]=e,this._globalTimelineStyles[t]=e,this._styleSummary[t]={time:this.currentTime,value:e}}allowOnlyTimelineStyles(){return this._currentEmptyStepKeyframe!==this._currentKeyframe}applyEmptyStep(t){t&&(this._previousKeyframe.easing=t),Object.keys(this._globalTimelineStyles).forEach(e=>{this._backFill[e]=this._globalTimelineStyles[e]||Vi,this._currentKeyframe[e]=Vi}),this._currentEmptyStepKeyframe=this._currentKeyframe}setStyles(t,e,i,r){e&&(this._previousKeyframe.easing=e);const s=r&&r.params||{},o=function KH(n,t){const e={};let i;return n.forEach(r=>{\"*\"===r?(i=i||Object.keys(t),i.forEach(s=>{e[s]=Vi})):rr(r,!1,e)}),e}(t,this._globalTimelineStyles);Object.keys(o).forEach(a=>{const l=ld(o[a],s,i);this._pendingStyles[a]=l,this._localTimelineStyles.hasOwnProperty(a)||(this._backFill[a]=this._globalTimelineStyles.hasOwnProperty(a)?this._globalTimelineStyles[a]:Vi),this._updateStyle(a,l)})}applyStylesToKeyframe(){const t=this._pendingStyles,e=Object.keys(t);0!=e.length&&(this._pendingStyles={},e.forEach(i=>{this._currentKeyframe[i]=t[i]}),Object.keys(this._localTimelineStyles).forEach(i=>{this._currentKeyframe.hasOwnProperty(i)||(this._currentKeyframe[i]=this._localTimelineStyles[i])}))}snapshotCurrentStyles(){Object.keys(this._localTimelineStyles).forEach(t=>{const e=this._localTimelineStyles[t];this._pendingStyles[t]=e,this._updateStyle(t,e)})}getFinalKeyframe(){return this._keyframes.get(this.duration)}get properties(){const t=[];for(let e in this._currentKeyframe)t.push(e);return t}mergeTimelineCollectedStyles(t){Object.keys(t._styleSummary).forEach(e=>{const i=this._styleSummary[e],r=t._styleSummary[e];(!i||r.time>i.time)&&this._updateStyle(e,r.value)})}buildKeyframes(){this.applyStylesToKeyframe();const t=new Set,e=new Set,i=1===this._keyframes.size&&0===this.duration;let r=[];this._keyframes.forEach((a,l)=>{const c=rr(a,!0);Object.keys(c).forEach(d=>{const u=c[d];\"!\"==u?t.add(d):u==Vi&&e.add(d)}),i||(c.offset=l/this.duration),r.push(c)});const s=t.size?cd(t.values()):[],o=e.size?cd(e.values()):[];if(i){const a=r[0],l=io(a);a.offset=0,l.offset=1,r=[a,l]}return rm(this.element,r,s,o,this.duration,this.startTime,this.easing,!1)}}class QH extends vd{constructor(t,e,i,r,s,o,a=!1){super(t,e,o.delay),this.keyframes=i,this.preStyleProps=r,this.postStyleProps=s,this._stretchStartingKeyframe=a,this.timings={duration:o.duration,delay:o.delay,easing:o.easing}}containsAnimation(){return this.keyframes.length>1}buildKeyframes(){let t=this.keyframes,{delay:e,duration:i,easing:r}=this.timings;if(this._stretchStartingKeyframe&&e){const s=[],o=i+e,a=e/o,l=rr(t[0],!1);l.offset=0,s.push(l);const c=rr(t[0],!1);c.offset=vM(a),s.push(c);const d=t.length-1;for(let u=1;u<=d;u++){let h=rr(t[u],!1);h.offset=vM((e+h.offset*i)/o),s.push(h)}i=o,e=0,r=\"\",t=s}return rm(this.element,t,this.preStyleProps,this.postStyleProps,i,e,r,!0)}}function vM(n,t=3){const e=Math.pow(10,t-1);return Math.round(n*e)/e}class am{}class ZH extends am{normalizePropertyName(t,e){return tm(t)}normalizeStyleValue(t,e,i,r){let s=\"\";const o=i.toString().trim();if(XH[e]&&0!==i&&\"0\"!==i)if(\"number\"==typeof i)s=\"px\";else{const a=i.match(/^[+-]?[\\d\\.]+([a-z]*)$/);a&&0==a[1].length&&r.push(function G2(n,t){return new H(3005,Ce)}())}return o+s}}const XH=(()=>function JH(n){const t={};return n.forEach(e=>t[e]=!0),t}(\"width,height,minWidth,minHeight,maxWidth,maxHeight,left,top,bottom,right,fontSize,outlineWidth,outlineOffset,paddingTop,paddingLeft,paddingBottom,paddingRight,marginTop,marginLeft,marginBottom,marginRight,borderRadius,borderWidth,borderTopWidth,borderLeftWidth,borderRightWidth,borderBottomWidth,textIndent,perspective\".split(\",\")))();function yM(n,t,e,i,r,s,o,a,l,c,d,u,h){return{type:0,element:n,triggerName:t,isRemovalTransition:r,fromState:e,fromStyles:s,toState:i,toStyles:o,timelines:a,queriedElements:l,preStyleProps:c,postStyleProps:d,totalTime:u,errors:h}}const lm={};class bM{constructor(t,e,i){this._triggerName=t,this.ast=e,this._stateStyles=i}match(t,e,i,r){return function ej(n,t,e,i,r){return n.some(s=>s(t,e,i,r))}(this.ast.matchers,t,e,i,r)}buildStyles(t,e,i){const r=this._stateStyles[\"*\"],s=this._stateStyles[t],o=r?r.buildStyles(e,i):{};return s?s.buildStyles(e,i):o}build(t,e,i,r,s,o,a,l,c,d){const u=[],h=this.ast.options&&this.ast.options.params||lm,m=this.buildStyles(i,a&&a.params||lm,u),g=l&&l.params||lm,_=this.buildStyles(r,g,u),D=new Set,v=new Map,M=new Map,V=\"void\"===r,he={params:Object.assign(Object.assign({},h),g)},We=d?[]:sm(t,e,this.ast.animation,s,o,m,_,he,c,u);let Ze=0;if(We.forEach(pn=>{Ze=Math.max(pn.duration+pn.delay,Ze)}),u.length)return yM(e,this._triggerName,i,r,V,m,_,[],[],v,M,Ze,u);We.forEach(pn=>{const fn=pn.element,Do=dn(v,fn,{});pn.preStyleProps.forEach(ii=>Do[ii]=!0);const Gi=dn(M,fn,{});pn.postStyleProps.forEach(ii=>Gi[ii]=!0),fn!==e&&D.add(fn)});const hn=cd(D.values());return yM(e,this._triggerName,i,r,V,m,_,We,hn,v,M,Ze)}}class tj{constructor(t,e,i){this.styles=t,this.defaultParams=e,this.normalizer=i}buildStyles(t,e){const i={},r=io(this.defaultParams);return Object.keys(t).forEach(s=>{const o=t[s];null!=o&&(r[s]=o)}),this.styles.styles.forEach(s=>{if(\"string\"!=typeof s){const o=s;Object.keys(o).forEach(a=>{let l=o[a];l.length>1&&(l=ld(l,r,e));const c=this.normalizer.normalizePropertyName(a,e);l=this.normalizer.normalizeStyleValue(a,c,l,e),i[c]=l})}}),i}}class ij{constructor(t,e,i){this.name=t,this.ast=e,this._normalizer=i,this.transitionFactories=[],this.states={},e.states.forEach(r=>{this.states[r.name]=new tj(r.style,r.options&&r.options.params||{},i)}),CM(this.states,\"true\",\"1\"),CM(this.states,\"false\",\"0\"),e.transitions.forEach(r=>{this.transitionFactories.push(new bM(t,r,this.states))}),this.fallbackTransition=function rj(n,t,e){return new bM(n,{type:1,animation:{type:2,steps:[],options:null},matchers:[(o,a)=>!0],options:null,queryCount:0,depCount:0},t)}(t,this.states)}get containsQueries(){return this.ast.queryCount>0}matchTransition(t,e,i,r){return this.transitionFactories.find(o=>o.match(t,e,i,r))||null}matchStyles(t,e,i){return this.fallbackTransition.buildStyles(t,e,i)}}function CM(n,t,e){n.hasOwnProperty(t)?n.hasOwnProperty(e)||(n[e]=n[t]):n.hasOwnProperty(e)&&(n[t]=n[e])}const sj=new gd;class oj{constructor(t,e,i){this.bodyNode=t,this._driver=e,this._normalizer=i,this._animations={},this._playersById={},this.players=[]}register(t,e){const i=[],s=nm(this._driver,e,i,[]);if(i.length)throw function cH(n){return new H(3503,Ce)}();this._animations[t]=s}_buildPlayer(t,e,i){const r=t.element,s=Jw(0,this._normalizer,0,t.keyframes,e,i);return this._driver.animate(r,s,t.duration,t.delay,t.easing,[],!0)}create(t,e,i={}){const r=[],s=this._animations[t];let o;const a=new Map;if(s?(o=sm(this._driver,e,s,Zf,rd,{},{},i,sj,r),o.forEach(d=>{const u=dn(a,d.element,{});d.postStyleProps.forEach(h=>u[h]=null)})):(r.push(function dH(){return new H(3300,Ce)}()),o=[]),r.length)throw function uH(n){return new H(3504,Ce)}();a.forEach((d,u)=>{Object.keys(d).forEach(h=>{d[h]=this._driver.computeStyle(u,h,Vi)})});const c=ir(o.map(d=>{const u=a.get(d.element);return this._buildPlayer(d,{},u)}));return this._playersById[t]=c,c.onDestroy(()=>this.destroy(t)),this.players.push(c),c}destroy(t){const e=this._getPlayer(t);e.destroy(),delete this._playersById[t];const i=this.players.indexOf(e);i>=0&&this.players.splice(i,1)}_getPlayer(t){const e=this._playersById[t];if(!e)throw function hH(n){return new H(3301,Ce)}();return e}listen(t,e,i,r){const s=qf(e,\"\",\"\",\"\");return Gf(this._getPlayer(t),i,s,r),()=>{}}command(t,e,i,r){if(\"register\"==i)return void this.register(t,r[0]);if(\"create\"==i)return void this.create(t,e,r[0]||{});const s=this._getPlayer(t);switch(i){case\"play\":s.play();break;case\"pause\":s.pause();break;case\"reset\":s.reset();break;case\"restart\":s.restart();break;case\"finish\":s.finish();break;case\"init\":s.init();break;case\"setPosition\":s.setPosition(parseFloat(r[0]));break;case\"destroy\":this.destroy(t)}}}const DM=\"ng-animate-queued\",cm=\"ng-animate-disabled\",uj=[],wM={namespaceId:\"\",setForRemoval:!1,setForMove:!1,hasAnimation:!1,removedBeforeQueried:!1},hj={namespaceId:\"\",setForMove:!1,setForRemoval:!1,hasAnimation:!1,removedBeforeQueried:!0},An=\"__ng_removed\";class dm{constructor(t,e=\"\"){this.namespaceId=e;const i=t&&t.hasOwnProperty(\"value\");if(this.value=function gj(n){return null!=n?n:null}(i?t.value:t),i){const s=io(t);delete s.value,this.options=s}else this.options={};this.options.params||(this.options.params={})}get params(){return this.options.params}absorbOptions(t){const e=t.params;if(e){const i=this.options.params;Object.keys(e).forEach(r=>{null==i[r]&&(i[r]=e[r])})}}}const Va=\"void\",um=new dm(Va);class pj{constructor(t,e,i){this.id=t,this.hostElement=e,this._engine=i,this.players=[],this._triggers={},this._queue=[],this._elementListeners=new Map,this._hostClassName=\"ng-tns-\"+t,In(e,this._hostClassName)}listen(t,e,i,r){if(!this._triggers.hasOwnProperty(e))throw function pH(n,t){return new H(3302,Ce)}();if(null==i||0==i.length)throw function fH(n){return new H(3303,Ce)}();if(!function _j(n){return\"start\"==n||\"done\"==n}(i))throw function mH(n,t){return new H(3400,Ce)}();const s=dn(this._elementListeners,t,[]),o={name:e,phase:i,callback:r};s.push(o);const a=dn(this._engine.statesByElement,t,{});return a.hasOwnProperty(e)||(In(t,sd),In(t,sd+\"-\"+e),a[e]=um),()=>{this._engine.afterFlush(()=>{const l=s.indexOf(o);l>=0&&s.splice(l,1),this._triggers[e]||delete a[e]})}}register(t,e){return!this._triggers[t]&&(this._triggers[t]=e,!0)}_getTrigger(t){const e=this._triggers[t];if(!e)throw function gH(n){return new H(3401,Ce)}();return e}trigger(t,e,i,r=!0){const s=this._getTrigger(e),o=new hm(this.id,e,t);let a=this._engine.statesByElement.get(t);a||(In(t,sd),In(t,sd+\"-\"+e),this._engine.statesByElement.set(t,a={}));let l=a[e];const c=new dm(i,this.id);if(!(i&&i.hasOwnProperty(\"value\"))&&l&&c.absorbOptions(l.options),a[e]=c,l||(l=um),c.value!==Va&&l.value===c.value){if(!function bj(n,t){const e=Object.keys(n),i=Object.keys(t);if(e.length!=i.length)return!1;for(let r=0;r<e.length;r++){const s=e[r];if(!t.hasOwnProperty(s)||n[s]!==t[s])return!1}return!0}(l.params,c.params)){const g=[],_=s.matchStyles(l.value,l.params,g),D=s.matchStyles(c.value,c.params,g);g.length?this._engine.reportError(g):this._engine.afterFlush(()=>{zr(t,_),vi(t,D)})}return}const h=dn(this._engine.playersByElement,t,[]);h.forEach(g=>{g.namespaceId==this.id&&g.triggerName==e&&g.queued&&g.destroy()});let p=s.matchTransition(l.value,c.value,t,c.params),m=!1;if(!p){if(!r)return;p=s.fallbackTransition,m=!0}return this._engine.totalQueuedPlayers++,this._queue.push({element:t,triggerName:e,transition:p,fromState:l,toState:c,player:o,isFallbackTransition:m}),m||(In(t,DM),o.onStart(()=>{ro(t,DM)})),o.onDone(()=>{let g=this.players.indexOf(o);g>=0&&this.players.splice(g,1);const _=this._engine.playersByElement.get(t);if(_){let D=_.indexOf(o);D>=0&&_.splice(D,1)}}),this.players.push(o),h.push(o),o}deregister(t){delete this._triggers[t],this._engine.statesByElement.forEach((e,i)=>{delete e[t]}),this._elementListeners.forEach((e,i)=>{this._elementListeners.set(i,e.filter(r=>r.name!=t))})}clearElementCache(t){this._engine.statesByElement.delete(t),this._elementListeners.delete(t);const e=this._engine.playersByElement.get(t);e&&(e.forEach(i=>i.destroy()),this._engine.playersByElement.delete(t))}_signalRemovalForInnerTriggers(t,e){const i=this._engine.driver.query(t,od,!0);i.forEach(r=>{if(r[An])return;const s=this._engine.fetchNamespacesByElement(r);s.size?s.forEach(o=>o.triggerLeaveAnimation(r,e,!1,!0)):this.clearElementCache(r)}),this._engine.afterFlushAnimationsDone(()=>i.forEach(r=>this.clearElementCache(r)))}triggerLeaveAnimation(t,e,i,r){const s=this._engine.statesByElement.get(t),o=new Map;if(s){const a=[];if(Object.keys(s).forEach(l=>{if(o.set(l,s[l].value),this._triggers[l]){const c=this.trigger(t,l,Va,r);c&&a.push(c)}}),a.length)return this._engine.markElementAsRemoved(this.id,t,!0,e,o),i&&ir(a).onDone(()=>this._engine.processLeaveNode(t)),!0}return!1}prepareLeaveAnimationListeners(t){const e=this._elementListeners.get(t),i=this._engine.statesByElement.get(t);if(e&&i){const r=new Set;e.forEach(s=>{const o=s.name;if(r.has(o))return;r.add(o);const l=this._triggers[o].fallbackTransition,c=i[o]||um,d=new dm(Va),u=new hm(this.id,o,t);this._engine.totalQueuedPlayers++,this._queue.push({element:t,triggerName:o,transition:l,fromState:c,toState:d,player:u,isFallbackTransition:!0})})}}removeNode(t,e){const i=this._engine;if(t.childElementCount&&this._signalRemovalForInnerTriggers(t,e),this.triggerLeaveAnimation(t,e,!0))return;let r=!1;if(i.totalAnimations){const s=i.players.length?i.playersByQueriedElement.get(t):[];if(s&&s.length)r=!0;else{let o=t;for(;o=o.parentNode;)if(i.statesByElement.get(o)){r=!0;break}}}if(this.prepareLeaveAnimationListeners(t),r)i.markElementAsRemoved(this.id,t,!1,e);else{const s=t[An];(!s||s===wM)&&(i.afterFlush(()=>this.clearElementCache(t)),i.destroyInnerAnimations(t),i._onRemovalComplete(t,e))}}insertNode(t,e){In(t,this._hostClassName)}drainQueuedTransitions(t){const e=[];return this._queue.forEach(i=>{const r=i.player;if(r.destroyed)return;const s=i.element,o=this._elementListeners.get(s);o&&o.forEach(a=>{if(a.name==i.triggerName){const l=qf(s,i.triggerName,i.fromState.value,i.toState.value);l._data=t,Gf(i.player,a.phase,l,a.callback)}}),r.markedForDestroy?this._engine.afterFlush(()=>{r.destroy()}):e.push(i)}),this._queue=[],e.sort((i,r)=>{const s=i.transition.ast.depCount,o=r.transition.ast.depCount;return 0==s||0==o?s-o:this._engine.driver.containsElement(i.element,r.element)?1:-1})}destroy(t){this.players.forEach(e=>e.destroy()),this._signalRemovalForInnerTriggers(this.hostElement,t)}elementContainsData(t){let e=!1;return this._elementListeners.has(t)&&(e=!0),e=!!this._queue.find(i=>i.element===t)||e,e}}class fj{constructor(t,e,i){this.bodyNode=t,this.driver=e,this._normalizer=i,this.players=[],this.newHostElements=new Map,this.playersByElement=new Map,this.playersByQueriedElement=new Map,this.statesByElement=new Map,this.disabledNodes=new Set,this.totalAnimations=0,this.totalQueuedPlayers=0,this._namespaceLookup={},this._namespaceList=[],this._flushFns=[],this._whenQuietFns=[],this.namespacesByHostElement=new Map,this.collectedEnterElements=[],this.collectedLeaveElements=[],this.onRemovalComplete=(r,s)=>{}}_onRemovalComplete(t,e){this.onRemovalComplete(t,e)}get queuedPlayers(){const t=[];return this._namespaceList.forEach(e=>{e.players.forEach(i=>{i.queued&&t.push(i)})}),t}createNamespace(t,e){const i=new pj(t,e,this);return this.bodyNode&&this.driver.containsElement(this.bodyNode,e)?this._balanceNamespaceList(i,e):(this.newHostElements.set(e,i),this.collectEnterElement(e)),this._namespaceLookup[t]=i}_balanceNamespaceList(t,e){const i=this._namespaceList,r=this.namespacesByHostElement,s=i.length-1;if(s>=0){let o=!1;if(void 0!==this.driver.getParentElement){let a=this.driver.getParentElement(e);for(;a;){const l=r.get(a);if(l){const c=i.indexOf(l);i.splice(c+1,0,t),o=!0;break}a=this.driver.getParentElement(a)}}else for(let a=s;a>=0;a--)if(this.driver.containsElement(i[a].hostElement,e)){i.splice(a+1,0,t),o=!0;break}o||i.unshift(t)}else i.push(t);return r.set(e,t),t}register(t,e){let i=this._namespaceLookup[t];return i||(i=this.createNamespace(t,e)),i}registerTrigger(t,e,i){let r=this._namespaceLookup[t];r&&r.register(e,i)&&this.totalAnimations++}destroy(t,e){if(!t)return;const i=this._fetchNamespace(t);this.afterFlush(()=>{this.namespacesByHostElement.delete(i.hostElement),delete this._namespaceLookup[t];const r=this._namespaceList.indexOf(i);r>=0&&this._namespaceList.splice(r,1)}),this.afterFlushAnimationsDone(()=>i.destroy(e))}_fetchNamespace(t){return this._namespaceLookup[t]}fetchNamespacesByElement(t){const e=new Set,i=this.statesByElement.get(t);if(i){const r=Object.keys(i);for(let s=0;s<r.length;s++){const o=i[r[s]].namespaceId;if(o){const a=this._fetchNamespace(o);a&&e.add(a)}}}return e}trigger(t,e,i,r){if(yd(e)){const s=this._fetchNamespace(t);if(s)return s.trigger(e,i,r),!0}return!1}insertNode(t,e,i,r){if(!yd(e))return;const s=e[An];if(s&&s.setForRemoval){s.setForRemoval=!1,s.setForMove=!0;const o=this.collectedLeaveElements.indexOf(e);o>=0&&this.collectedLeaveElements.splice(o,1)}if(t){const o=this._fetchNamespace(t);o&&o.insertNode(e,i)}r&&this.collectEnterElement(e)}collectEnterElement(t){this.collectedEnterElements.push(t)}markElementAsDisabled(t,e){e?this.disabledNodes.has(t)||(this.disabledNodes.add(t),In(t,cm)):this.disabledNodes.has(t)&&(this.disabledNodes.delete(t),ro(t,cm))}removeNode(t,e,i,r){if(yd(e)){const s=t?this._fetchNamespace(t):null;if(s?s.removeNode(e,r):this.markElementAsRemoved(t,e,!1,r),i){const o=this.namespacesByHostElement.get(e);o&&o.id!==t&&o.removeNode(e,r)}}else this._onRemovalComplete(e,r)}markElementAsRemoved(t,e,i,r,s){this.collectedLeaveElements.push(e),e[An]={namespaceId:t,setForRemoval:r,hasAnimation:i,removedBeforeQueried:!1,previousTriggersValues:s}}listen(t,e,i,r,s){return yd(e)?this._fetchNamespace(t).listen(e,i,r,s):()=>{}}_buildInstruction(t,e,i,r,s){return t.transition.build(this.driver,t.element,t.fromState.value,t.toState.value,i,r,t.fromState.options,t.toState.options,e,s)}destroyInnerAnimations(t){let e=this.driver.query(t,od,!0);e.forEach(i=>this.destroyActiveAnimationsForElement(i)),0!=this.playersByQueriedElement.size&&(e=this.driver.query(t,Xf,!0),e.forEach(i=>this.finishActiveQueriedAnimationOnElement(i)))}destroyActiveAnimationsForElement(t){const e=this.playersByElement.get(t);e&&e.forEach(i=>{i.queued?i.markedForDestroy=!0:i.destroy()})}finishActiveQueriedAnimationOnElement(t){const e=this.playersByQueriedElement.get(t);e&&e.forEach(i=>i.finish())}whenRenderingDone(){return new Promise(t=>{if(this.players.length)return ir(this.players).onDone(()=>t());t()})}processLeaveNode(t){var e;const i=t[An];if(i&&i.setForRemoval){if(t[An]=wM,i.namespaceId){this.destroyInnerAnimations(t);const r=this._fetchNamespace(i.namespaceId);r&&r.clearElementCache(t)}this._onRemovalComplete(t,i.setForRemoval)}(null===(e=t.classList)||void 0===e?void 0:e.contains(cm))&&this.markElementAsDisabled(t,!1),this.driver.query(t,\".ng-animate-disabled\",!0).forEach(r=>{this.markElementAsDisabled(r,!1)})}flush(t=-1){let e=[];if(this.newHostElements.size&&(this.newHostElements.forEach((i,r)=>this._balanceNamespaceList(i,r)),this.newHostElements.clear()),this.totalAnimations&&this.collectedEnterElements.length)for(let i=0;i<this.collectedEnterElements.length;i++)In(this.collectedEnterElements[i],\"ng-star-inserted\");if(this._namespaceList.length&&(this.totalQueuedPlayers||this.collectedLeaveElements.length)){const i=[];try{e=this._flushAnimations(i,t)}finally{for(let r=0;r<i.length;r++)i[r]()}}else for(let i=0;i<this.collectedLeaveElements.length;i++)this.processLeaveNode(this.collectedLeaveElements[i]);if(this.totalQueuedPlayers=0,this.collectedEnterElements.length=0,this.collectedLeaveElements.length=0,this._flushFns.forEach(i=>i()),this._flushFns=[],this._whenQuietFns.length){const i=this._whenQuietFns;this._whenQuietFns=[],e.length?ir(e).onDone(()=>{i.forEach(r=>r())}):i.forEach(r=>r())}}reportError(t){throw function _H(n){return new H(3402,Ce)}()}_flushAnimations(t,e){const i=new gd,r=[],s=new Map,o=[],a=new Map,l=new Map,c=new Map,d=new Set;this.disabledNodes.forEach(j=>{d.add(j);const Y=this.driver.query(j,\".ng-animate-queued\",!0);for(let X=0;X<Y.length;X++)d.add(Y[X])});const u=this.bodyNode,h=Array.from(this.statesByElement.keys()),p=EM(h,this.collectedEnterElements),m=new Map;let g=0;p.forEach((j,Y)=>{const X=Zf+g++;m.set(Y,X),j.forEach(Se=>In(Se,X))});const _=[],D=new Set,v=new Set;for(let j=0;j<this.collectedLeaveElements.length;j++){const Y=this.collectedLeaveElements[j],X=Y[An];X&&X.setForRemoval&&(_.push(Y),D.add(Y),X.hasAnimation?this.driver.query(Y,\".ng-star-inserted\",!0).forEach(Se=>D.add(Se)):v.add(Y))}const M=new Map,V=EM(h,Array.from(D));V.forEach((j,Y)=>{const X=rd+g++;M.set(Y,X),j.forEach(Se=>In(Se,X))}),t.push(()=>{p.forEach((j,Y)=>{const X=m.get(Y);j.forEach(Se=>ro(Se,X))}),V.forEach((j,Y)=>{const X=M.get(Y);j.forEach(Se=>ro(Se,X))}),_.forEach(j=>{this.processLeaveNode(j)})});const he=[],We=[];for(let j=this._namespaceList.length-1;j>=0;j--)this._namespaceList[j].drainQueuedTransitions(e).forEach(X=>{const Se=X.player,St=X.element;if(he.push(Se),this.collectedEnterElements.length){const qt=St[An];if(qt&&qt.setForMove){if(qt.previousTriggersValues&&qt.previousTriggersValues.has(X.triggerName)){const is=qt.previousTriggersValues.get(X.triggerName),pr=this.statesByElement.get(X.element);pr&&pr[X.triggerName]&&(pr[X.triggerName].value=is)}return void Se.destroy()}}const wi=!u||!this.driver.containsElement(u,St),mn=M.get(St),hr=m.get(St),Xe=this._buildInstruction(X,i,hr,mn,wi);if(Xe.errors&&Xe.errors.length)return void We.push(Xe);if(wi)return Se.onStart(()=>zr(St,Xe.fromStyles)),Se.onDestroy(()=>vi(St,Xe.toStyles)),void r.push(Se);if(X.isFallbackTransition)return Se.onStart(()=>zr(St,Xe.fromStyles)),Se.onDestroy(()=>vi(St,Xe.toStyles)),void r.push(Se);const pk=[];Xe.timelines.forEach(qt=>{qt.stretchStartingKeyframe=!0,this.disabledNodes.has(qt.element)||pk.push(qt)}),Xe.timelines=pk,i.append(St,Xe.timelines),o.push({instruction:Xe,player:Se,element:St}),Xe.queriedElements.forEach(qt=>dn(a,qt,[]).push(Se)),Xe.preStyleProps.forEach((qt,is)=>{const pr=Object.keys(qt);if(pr.length){let rs=l.get(is);rs||l.set(is,rs=new Set),pr.forEach(Xg=>rs.add(Xg))}}),Xe.postStyleProps.forEach((qt,is)=>{const pr=Object.keys(qt);let rs=c.get(is);rs||c.set(is,rs=new Set),pr.forEach(Xg=>rs.add(Xg))})});if(We.length){const j=[];We.forEach(Y=>{j.push(function vH(n,t){return new H(3505,Ce)}())}),he.forEach(Y=>Y.destroy()),this.reportError(j)}const Ze=new Map,hn=new Map;o.forEach(j=>{const Y=j.element;i.has(Y)&&(hn.set(Y,Y),this._beforeAnimationBuild(j.player.namespaceId,j.instruction,Ze))}),r.forEach(j=>{const Y=j.element;this._getPreviousPlayers(Y,!1,j.namespaceId,j.triggerName,null).forEach(Se=>{dn(Ze,Y,[]).push(Se),Se.destroy()})});const pn=_.filter(j=>kM(j,l,c)),fn=new Map;xM(fn,this.driver,v,c,Vi).forEach(j=>{kM(j,l,c)&&pn.push(j)});const Gi=new Map;p.forEach((j,Y)=>{xM(Gi,this.driver,new Set(j),l,\"!\")}),pn.forEach(j=>{const Y=fn.get(j),X=Gi.get(j);fn.set(j,Object.assign(Object.assign({},Y),X))});const ii=[],wo=[],Mo={};o.forEach(j=>{const{element:Y,player:X,instruction:Se}=j;if(i.has(Y)){if(d.has(Y))return X.onDestroy(()=>vi(Y,Se.toStyles)),X.disabled=!0,X.overrideTotalTime(Se.totalTime),void r.push(X);let St=Mo;if(hn.size>1){let mn=Y;const hr=[];for(;mn=mn.parentNode;){const Xe=hn.get(mn);if(Xe){St=Xe;break}hr.push(mn)}hr.forEach(Xe=>hn.set(Xe,St))}const wi=this._buildAnimation(X.namespaceId,Se,Ze,s,Gi,fn);if(X.setRealPlayer(wi),St===Mo)ii.push(X);else{const mn=this.playersByElement.get(St);mn&&mn.length&&(X.parentPlayer=ir(mn)),r.push(X)}}else zr(Y,Se.fromStyles),X.onDestroy(()=>vi(Y,Se.toStyles)),wo.push(X),d.has(Y)&&r.push(X)}),wo.forEach(j=>{const Y=s.get(j.element);if(Y&&Y.length){const X=ir(Y);j.setRealPlayer(X)}}),r.forEach(j=>{j.parentPlayer?j.syncPlayerEvents(j.parentPlayer):j.destroy()});for(let j=0;j<_.length;j++){const Y=_[j],X=Y[An];if(ro(Y,rd),X&&X.hasAnimation)continue;let Se=[];if(a.size){let wi=a.get(Y);wi&&wi.length&&Se.push(...wi);let mn=this.driver.query(Y,Xf,!0);for(let hr=0;hr<mn.length;hr++){let Xe=a.get(mn[hr]);Xe&&Xe.length&&Se.push(...Xe)}}const St=Se.filter(wi=>!wi.destroyed);St.length?vj(this,Y,St):this.processLeaveNode(Y)}return _.length=0,ii.forEach(j=>{this.players.push(j),j.onDone(()=>{j.destroy();const Y=this.players.indexOf(j);this.players.splice(Y,1)}),j.play()}),ii}elementContainsData(t,e){let i=!1;const r=e[An];return r&&r.setForRemoval&&(i=!0),this.playersByElement.has(e)&&(i=!0),this.playersByQueriedElement.has(e)&&(i=!0),this.statesByElement.has(e)&&(i=!0),this._fetchNamespace(t).elementContainsData(e)||i}afterFlush(t){this._flushFns.push(t)}afterFlushAnimationsDone(t){this._whenQuietFns.push(t)}_getPreviousPlayers(t,e,i,r,s){let o=[];if(e){const a=this.playersByQueriedElement.get(t);a&&(o=a)}else{const a=this.playersByElement.get(t);if(a){const l=!s||s==Va;a.forEach(c=>{c.queued||!l&&c.triggerName!=r||o.push(c)})}}return(i||r)&&(o=o.filter(a=>!(i&&i!=a.namespaceId||r&&r!=a.triggerName))),o}_beforeAnimationBuild(t,e,i){const s=e.element,o=e.isRemovalTransition?void 0:t,a=e.isRemovalTransition?void 0:e.triggerName;for(const l of e.timelines){const c=l.element,d=c!==s,u=dn(i,c,[]);this._getPreviousPlayers(c,d,o,a,e.toState).forEach(p=>{const m=p.getRealPlayer();m.beforeDestroy&&m.beforeDestroy(),p.destroy(),u.push(p)})}zr(s,e.fromStyles)}_buildAnimation(t,e,i,r,s,o){const a=e.triggerName,l=e.element,c=[],d=new Set,u=new Set,h=e.timelines.map(m=>{const g=m.element;d.add(g);const _=g[An];if(_&&_.removedBeforeQueried)return new La(m.duration,m.delay);const D=g!==l,v=function yj(n){const t=[];return SM(n,t),t}((i.get(g)||uj).map(Ze=>Ze.getRealPlayer())).filter(Ze=>!!Ze.element&&Ze.element===g),M=s.get(g),V=o.get(g),he=Jw(0,this._normalizer,0,m.keyframes,M,V),We=this._buildPlayer(m,he,v);if(m.subTimeline&&r&&u.add(g),D){const Ze=new hm(t,a,g);Ze.setRealPlayer(We),c.push(Ze)}return We});c.forEach(m=>{dn(this.playersByQueriedElement,m.element,[]).push(m),m.onDone(()=>function mj(n,t,e){let i;if(n instanceof Map){if(i=n.get(t),i){if(i.length){const r=i.indexOf(e);i.splice(r,1)}0==i.length&&n.delete(t)}}else if(i=n[t],i){if(i.length){const r=i.indexOf(e);i.splice(r,1)}0==i.length&&delete n[t]}return i}(this.playersByQueriedElement,m.element,m))}),d.forEach(m=>In(m,cM));const p=ir(h);return p.onDestroy(()=>{d.forEach(m=>ro(m,cM)),vi(l,e.toStyles)}),u.forEach(m=>{dn(r,m,[]).push(p)}),p}_buildPlayer(t,e,i){return e.length>0?this.driver.animate(t.element,e,t.duration,t.delay,t.easing,i):new La(t.duration,t.delay)}}class hm{constructor(t,e,i){this.namespaceId=t,this.triggerName=e,this.element=i,this._player=new La,this._containsRealPlayer=!1,this._queuedCallbacks={},this.destroyed=!1,this.markedForDestroy=!1,this.disabled=!1,this.queued=!0,this.totalTime=0}setRealPlayer(t){this._containsRealPlayer||(this._player=t,Object.keys(this._queuedCallbacks).forEach(e=>{this._queuedCallbacks[e].forEach(i=>Gf(t,e,void 0,i))}),this._queuedCallbacks={},this._containsRealPlayer=!0,this.overrideTotalTime(t.totalTime),this.queued=!1)}getRealPlayer(){return this._player}overrideTotalTime(t){this.totalTime=t}syncPlayerEvents(t){const e=this._player;e.triggerCallback&&t.onStart(()=>e.triggerCallback(\"start\")),t.onDone(()=>this.finish()),t.onDestroy(()=>this.destroy())}_queueEvent(t,e){dn(this._queuedCallbacks,t,[]).push(e)}onDone(t){this.queued&&this._queueEvent(\"done\",t),this._player.onDone(t)}onStart(t){this.queued&&this._queueEvent(\"start\",t),this._player.onStart(t)}onDestroy(t){this.queued&&this._queueEvent(\"destroy\",t),this._player.onDestroy(t)}init(){this._player.init()}hasStarted(){return!this.queued&&this._player.hasStarted()}play(){!this.queued&&this._player.play()}pause(){!this.queued&&this._player.pause()}restart(){!this.queued&&this._player.restart()}finish(){this._player.finish()}destroy(){this.destroyed=!0,this._player.destroy()}reset(){!this.queued&&this._player.reset()}setPosition(t){this.queued||this._player.setPosition(t)}getPosition(){return this.queued?0:this._player.getPosition()}triggerCallback(t){const e=this._player;e.triggerCallback&&e.triggerCallback(t)}}function yd(n){return n&&1===n.nodeType}function MM(n,t){const e=n.style.display;return n.style.display=null!=t?t:\"none\",e}function xM(n,t,e,i,r){const s=[];e.forEach(l=>s.push(MM(l)));const o=[];i.forEach((l,c)=>{const d={};l.forEach(u=>{const h=d[u]=t.computeStyle(c,u,r);(!h||0==h.length)&&(c[An]=hj,o.push(c))}),n.set(c,d)});let a=0;return e.forEach(l=>MM(l,s[a++])),o}function EM(n,t){const e=new Map;if(n.forEach(a=>e.set(a,[])),0==t.length)return e;const r=new Set(t),s=new Map;function o(a){if(!a)return 1;let l=s.get(a);if(l)return l;const c=a.parentNode;return l=e.has(c)?c:r.has(c)?1:o(c),s.set(a,l),l}return t.forEach(a=>{const l=o(a);1!==l&&e.get(l).push(a)}),e}function In(n,t){var e;null===(e=n.classList)||void 0===e||e.add(t)}function ro(n,t){var e;null===(e=n.classList)||void 0===e||e.remove(t)}function vj(n,t,e){ir(e).onDone(()=>n.processLeaveNode(t))}function SM(n,t){for(let e=0;e<n.length;e++){const i=n[e];i instanceof Zw?SM(i.players,t):t.push(i)}}function kM(n,t,e){const i=e.get(n);if(!i)return!1;let r=t.get(n);return r?i.forEach(s=>r.add(s)):t.set(n,i),e.delete(n),!0}class bd{constructor(t,e,i){this.bodyNode=t,this._driver=e,this._normalizer=i,this._triggerCache={},this.onRemovalComplete=(r,s)=>{},this._transitionEngine=new fj(t,e,i),this._timelineEngine=new oj(t,e,i),this._transitionEngine.onRemovalComplete=(r,s)=>this.onRemovalComplete(r,s)}registerTrigger(t,e,i,r,s){const o=t+\"-\"+r;let a=this._triggerCache[o];if(!a){const l=[],d=nm(this._driver,s,l,[]);if(l.length)throw function aH(n,t){return new H(3404,Ce)}();a=function nj(n,t,e){return new ij(n,t,e)}(r,d,this._normalizer),this._triggerCache[o]=a}this._transitionEngine.registerTrigger(e,r,a)}register(t,e){this._transitionEngine.register(t,e)}destroy(t,e){this._transitionEngine.destroy(t,e)}onInsert(t,e,i,r){this._transitionEngine.insertNode(t,e,i,r)}onRemove(t,e,i,r){this._transitionEngine.removeNode(t,e,r||!1,i)}disableAnimations(t,e){this._transitionEngine.markElementAsDisabled(t,e)}process(t,e,i,r){if(\"@\"==i.charAt(0)){const[s,o]=eM(i);this._timelineEngine.command(s,e,o,r)}else this._transitionEngine.trigger(t,e,i,r)}listen(t,e,i,r,s){if(\"@\"==i.charAt(0)){const[o,a]=eM(i);return this._timelineEngine.listen(o,e,a,s)}return this._transitionEngine.listen(t,e,i,r,s)}flush(t=-1){this._transitionEngine.flush(t)}get players(){return this._transitionEngine.players.concat(this._timelineEngine.players)}whenRenderingDone(){return this._transitionEngine.whenRenderingDone()}}let Dj=(()=>{class n{constructor(e,i,r){this._element=e,this._startStyles=i,this._endStyles=r,this._state=0;let s=n.initialStylesByElement.get(e);s||n.initialStylesByElement.set(e,s={}),this._initialStyles=s}start(){this._state<1&&(this._startStyles&&vi(this._element,this._startStyles,this._initialStyles),this._state=1)}finish(){this.start(),this._state<2&&(vi(this._element,this._initialStyles),this._endStyles&&(vi(this._element,this._endStyles),this._endStyles=null),this._state=1)}destroy(){this.finish(),this._state<3&&(n.initialStylesByElement.delete(this._element),this._startStyles&&(zr(this._element,this._startStyles),this._endStyles=null),this._endStyles&&(zr(this._element,this._endStyles),this._endStyles=null),vi(this._element,this._initialStyles),this._state=3)}}return n.initialStylesByElement=new WeakMap,n})();function pm(n){let t=null;const e=Object.keys(n);for(let i=0;i<e.length;i++){const r=e[i];wj(r)&&(t=t||{},t[r]=n[r])}return t}function wj(n){return\"display\"===n||\"position\"===n}class TM{constructor(t,e,i,r){this.element=t,this.keyframes=e,this.options=i,this._specialStyles=r,this._onDoneFns=[],this._onStartFns=[],this._onDestroyFns=[],this._initialized=!1,this._finished=!1,this._started=!1,this._destroyed=!1,this.time=0,this.parentPlayer=null,this.currentSnapshot={},this._duration=i.duration,this._delay=i.delay||0,this.time=this._duration+this._delay}_onFinish(){this._finished||(this._finished=!0,this._onDoneFns.forEach(t=>t()),this._onDoneFns=[])}init(){this._buildPlayer(),this._preparePlayerBeforeStart()}_buildPlayer(){if(this._initialized)return;this._initialized=!0;const t=this.keyframes;this.domPlayer=this._triggerWebAnimation(this.element,t,this.options),this._finalKeyframe=t.length?t[t.length-1]:{},this.domPlayer.addEventListener(\"finish\",()=>this._onFinish())}_preparePlayerBeforeStart(){this._delay?this._resetDomPlayerState():this.domPlayer.pause()}_triggerWebAnimation(t,e,i){return t.animate(e,i)}onStart(t){this._onStartFns.push(t)}onDone(t){this._onDoneFns.push(t)}onDestroy(t){this._onDestroyFns.push(t)}play(){this._buildPlayer(),this.hasStarted()||(this._onStartFns.forEach(t=>t()),this._onStartFns=[],this._started=!0,this._specialStyles&&this._specialStyles.start()),this.domPlayer.play()}pause(){this.init(),this.domPlayer.pause()}finish(){this.init(),this._specialStyles&&this._specialStyles.finish(),this._onFinish(),this.domPlayer.finish()}reset(){this._resetDomPlayerState(),this._destroyed=!1,this._finished=!1,this._started=!1}_resetDomPlayerState(){this.domPlayer&&this.domPlayer.cancel()}restart(){this.reset(),this.play()}hasStarted(){return this._started}destroy(){this._destroyed||(this._destroyed=!0,this._resetDomPlayerState(),this._onFinish(),this._specialStyles&&this._specialStyles.destroy(),this._onDestroyFns.forEach(t=>t()),this._onDestroyFns=[])}setPosition(t){void 0===this.domPlayer&&this.init(),this.domPlayer.currentTime=t*this.time}getPosition(){return this.domPlayer.currentTime/this.time}get totalTime(){return this._delay+this._duration}beforeDestroy(){const t={};if(this.hasStarted()){const e=this._finalKeyframe;Object.keys(e).forEach(i=>{\"offset\"!=i&&(t[i]=this._finished?e[i]:fM(this.element,i))})}this.currentSnapshot=t}triggerCallback(t){const e=\"start\"==t?this._onStartFns:this._onDoneFns;e.forEach(i=>i()),e.length=0}}class Mj{validateStyleProperty(t){return rM(t)}matchesElement(t,e){return!1}containsElement(t,e){return sM(t,e)}getParentElement(t){return Qf(t)}query(t,e,i){return oM(t,e,i)}computeStyle(t,e,i){return window.getComputedStyle(t)[e]}animate(t,e,i,r,s,o=[]){const l={duration:i,delay:r,fill:0==r?\"both\":\"forwards\"};s&&(l.easing=s);const c={},d=o.filter(h=>h instanceof TM);(function kH(n,t){return 0===n||0===t})(i,r)&&d.forEach(h=>{let p=h.currentSnapshot;Object.keys(p).forEach(m=>c[m]=p[m])}),e=function TH(n,t,e){const i=Object.keys(e);if(i.length&&t.length){let s=t[0],o=[];if(i.forEach(a=>{s.hasOwnProperty(a)||o.push(a),s[a]=e[a]}),o.length)for(var r=1;r<t.length;r++){let a=t[r];o.forEach(function(l){a[l]=fM(n,l)})}}return t}(t,e=e.map(h=>rr(h,!1)),c);const u=function Cj(n,t){let e=null,i=null;return Array.isArray(t)&&t.length?(e=pm(t[0]),t.length>1&&(i=pm(t[t.length-1]))):t&&(e=pm(t)),e||i?new Dj(n,e,i):null}(t,e);return new TM(t,e,l,u)}}let xj=(()=>{class n extends Yw{constructor(e,i){super(),this._nextAnimationId=0,this._renderer=e.createRenderer(i.body,{id:\"0\",encapsulation:Ln.None,styles:[],data:{animation:[]}})}build(e){const i=this._nextAnimationId.toString();this._nextAnimationId++;const r=Array.isArray(e)?Qw(e):e;return AM(this._renderer,null,i,\"register\",[r]),new Ej(i,this._renderer)}}return n.\\u0275fac=function(e){return new(e||n)(y(da),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class Ej extends class V2{}{constructor(t,e){super(),this._id=t,this._renderer=e}create(t,e){return new Sj(this._id,t,e||{},this._renderer)}}class Sj{constructor(t,e,i,r){this.id=t,this.element=e,this._renderer=r,this.parentPlayer=null,this._started=!1,this.totalTime=0,this._command(\"create\",i)}_listen(t,e){return this._renderer.listen(this.element,`@@${this.id}:${t}`,e)}_command(t,...e){return AM(this._renderer,this.element,this.id,t,e)}onDone(t){this._listen(\"done\",t)}onStart(t){this._listen(\"start\",t)}onDestroy(t){this._listen(\"destroy\",t)}init(){this._command(\"init\")}hasStarted(){return this._started}play(){this._command(\"play\"),this._started=!0}pause(){this._command(\"pause\")}restart(){this._command(\"restart\")}finish(){this._command(\"finish\")}destroy(){this._command(\"destroy\")}reset(){this._command(\"reset\"),this._started=!1}setPosition(t){this._command(\"setPosition\",t)}getPosition(){var t,e;return null!==(e=null===(t=this._renderer.engine.players[+this.id])||void 0===t?void 0:t.getPosition())&&void 0!==e?e:0}}function AM(n,t,e,i,r){return n.setProperty(t,`@@${e}:${i}`,r)}const IM=\"@.disabled\";let kj=(()=>{class n{constructor(e,i,r){this.delegate=e,this.engine=i,this._zone=r,this._currentId=0,this._microtaskId=1,this._animationCallbacksBuffer=[],this._rendererCache=new Map,this._cdRecurDepth=0,this.promise=Promise.resolve(0),i.onRemovalComplete=(s,o)=>{const a=null==o?void 0:o.parentNode(s);a&&o.removeChild(a,s)}}createRenderer(e,i){const s=this.delegate.createRenderer(e,i);if(!(e&&i&&i.data&&i.data.animation)){let d=this._rendererCache.get(s);return d||(d=new RM(\"\",s,this.engine),this._rendererCache.set(s,d)),d}const o=i.id,a=i.id+\"-\"+this._currentId;this._currentId++,this.engine.register(a,e);const l=d=>{Array.isArray(d)?d.forEach(l):this.engine.registerTrigger(o,a,e,d.name,d)};return i.data.animation.forEach(l),new Tj(this,a,s,this.engine)}begin(){this._cdRecurDepth++,this.delegate.begin&&this.delegate.begin()}_scheduleCountTask(){this.promise.then(()=>{this._microtaskId++})}scheduleListenerCallback(e,i,r){e>=0&&e<this._microtaskId?this._zone.run(()=>i(r)):(0==this._animationCallbacksBuffer.length&&Promise.resolve(null).then(()=>{this._zone.run(()=>{this._animationCallbacksBuffer.forEach(s=>{const[o,a]=s;o(a)}),this._animationCallbacksBuffer=[]})}),this._animationCallbacksBuffer.push([i,r]))}end(){this._cdRecurDepth--,0==this._cdRecurDepth&&this._zone.runOutsideAngular(()=>{this._scheduleCountTask(),this.engine.flush(this._microtaskId)}),this.delegate.end&&this.delegate.end()}whenRenderingDone(){return this.engine.whenRenderingDone()}}return n.\\u0275fac=function(e){return new(e||n)(y(da),y(bd),y(ne))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class RM{constructor(t,e,i){this.namespaceId=t,this.delegate=e,this.engine=i,this.destroyNode=this.delegate.destroyNode?r=>e.destroyNode(r):null}get data(){return this.delegate.data}destroy(){this.engine.destroy(this.namespaceId,this.delegate),this.delegate.destroy()}createElement(t,e){return this.delegate.createElement(t,e)}createComment(t){return this.delegate.createComment(t)}createText(t){return this.delegate.createText(t)}appendChild(t,e){this.delegate.appendChild(t,e),this.engine.onInsert(this.namespaceId,e,t,!1)}insertBefore(t,e,i,r=!0){this.delegate.insertBefore(t,e,i),this.engine.onInsert(this.namespaceId,e,t,r)}removeChild(t,e,i){this.engine.onRemove(this.namespaceId,e,this.delegate,i)}selectRootElement(t,e){return this.delegate.selectRootElement(t,e)}parentNode(t){return this.delegate.parentNode(t)}nextSibling(t){return this.delegate.nextSibling(t)}setAttribute(t,e,i,r){this.delegate.setAttribute(t,e,i,r)}removeAttribute(t,e,i){this.delegate.removeAttribute(t,e,i)}addClass(t,e){this.delegate.addClass(t,e)}removeClass(t,e){this.delegate.removeClass(t,e)}setStyle(t,e,i,r){this.delegate.setStyle(t,e,i,r)}removeStyle(t,e,i){this.delegate.removeStyle(t,e,i)}setProperty(t,e,i){\"@\"==e.charAt(0)&&e==IM?this.disableAnimations(t,!!i):this.delegate.setProperty(t,e,i)}setValue(t,e){this.delegate.setValue(t,e)}listen(t,e,i){return this.delegate.listen(t,e,i)}disableAnimations(t,e){this.engine.disableAnimations(t,e)}}class Tj extends RM{constructor(t,e,i,r){super(e,i,r),this.factory=t,this.namespaceId=e}setProperty(t,e,i){\"@\"==e.charAt(0)?\".\"==e.charAt(1)&&e==IM?this.disableAnimations(t,i=void 0===i||!!i):this.engine.process(this.namespaceId,t,e.substr(1),i):this.delegate.setProperty(t,e,i)}listen(t,e,i){if(\"@\"==e.charAt(0)){const r=function Aj(n){switch(n){case\"body\":return document.body;case\"document\":return document;case\"window\":return window;default:return n}}(t);let s=e.substr(1),o=\"\";return\"@\"!=s.charAt(0)&&([s,o]=function Ij(n){const t=n.indexOf(\".\");return[n.substring(0,t),n.substr(t+1)]}(s)),this.engine.listen(this.namespaceId,r,s,o,a=>{this.factory.scheduleListenerCallback(a._data||-1,i,a)})}return this.delegate.listen(t,e,i)}}let Rj=(()=>{class n extends bd{constructor(e,i,r){super(e.body,i,r)}ngOnDestroy(){this.flush()}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(Kf),y(am))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const Rn=new b(\"AnimationModuleType\"),OM=[{provide:Yw,useClass:xj},{provide:am,useFactory:function Oj(){return new ZH}},{provide:bd,useClass:Rj},{provide:da,useFactory:function Pj(n,t,e){return new kj(n,t,e)},deps:[Vc,bd,ne]}],PM=[{provide:Kf,useFactory:()=>new Mj},{provide:Rn,useValue:\"BrowserAnimations\"},...OM],Fj=[{provide:Kf,useClass:aM},{provide:Rn,useValue:\"NoopAnimations\"},...OM];let Nj=(()=>{class n{static withConfig(e){return{ngModule:n,providers:e.disableAnimations?Fj:PM}}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:PM,imports:[FD]}),n})();let NM=(()=>{class n{constructor(e,i){this._renderer=e,this._elementRef=i,this.onChange=r=>{},this.onTouched=()=>{}}setProperty(e,i){this._renderer.setProperty(this._elementRef.nativeElement,e,i)}registerOnTouched(e){this.onTouched=e}registerOnChange(e){this.onChange=e}setDisabledState(e){this.setProperty(\"disabled\",e)}}return n.\\u0275fac=function(e){return new(e||n)(f(Ii),f(W))},n.\\u0275dir=C({type:n}),n})(),$r=(()=>{class n extends NM{}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275dir=C({type:n,features:[E]}),n})();const xt=new b(\"NgValueAccessor\"),Bj={provide:xt,useExisting:pe(()=>Dd),multi:!0},Hj=new b(\"CompositionEventMode\");let Dd=(()=>{class n extends NM{constructor(e,i,r){super(e,i),this._compositionMode=r,this._composing=!1,null==this._compositionMode&&(this._compositionMode=!function Vj(){const n=mi()?mi().getUserAgent():\"\";return/android (\\d+)/.test(n.toLowerCase())}())}writeValue(e){this.setProperty(\"value\",null==e?\"\":e)}_handleInput(e){(!this._compositionMode||this._compositionMode&&!this._composing)&&this.onChange(e)}_compositionStart(){this._composing=!0}_compositionEnd(e){this._composing=!1,this._compositionMode&&this.onChange(e)}}return n.\\u0275fac=function(e){return new(e||n)(f(Ii),f(W),f(Hj,8))},n.\\u0275dir=C({type:n,selectors:[[\"input\",\"formControlName\",\"\",3,\"type\",\"checkbox\"],[\"textarea\",\"formControlName\",\"\"],[\"input\",\"formControl\",\"\",3,\"type\",\"checkbox\"],[\"textarea\",\"formControl\",\"\"],[\"input\",\"ngModel\",\"\",3,\"type\",\"checkbox\"],[\"textarea\",\"ngModel\",\"\"],[\"\",\"ngDefaultControl\",\"\"]],hostBindings:function(e,i){1&e&&J(\"input\",function(s){return i._handleInput(s.target.value)})(\"blur\",function(){return i.onTouched()})(\"compositionstart\",function(){return i._compositionStart()})(\"compositionend\",function(s){return i._compositionEnd(s.target.value)})},features:[L([Bj]),E]}),n})();function sr(n){return null==n||0===n.length}function BM(n){return null!=n&&\"number\"==typeof n.length}const Dt=new b(\"NgValidators\"),or=new b(\"NgAsyncValidators\"),jj=/^(?=.{1,254}$)(?=.{1,64}@)[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;class yi{static min(t){return function VM(n){return t=>{if(sr(t.value)||sr(n))return null;const e=parseFloat(t.value);return!isNaN(e)&&e<n?{min:{min:n,actual:t.value}}:null}}(t)}static max(t){return function HM(n){return t=>{if(sr(t.value)||sr(n))return null;const e=parseFloat(t.value);return!isNaN(e)&&e>n?{max:{max:n,actual:t.value}}:null}}(t)}static required(t){return function jM(n){return sr(n.value)?{required:!0}:null}(t)}static requiredTrue(t){return function zM(n){return!0===n.value?null:{required:!0}}(t)}static email(t){return function UM(n){return sr(n.value)||jj.test(n.value)?null:{email:!0}}(t)}static minLength(t){return function $M(n){return t=>sr(t.value)||!BM(t.value)?null:t.value.length<n?{minlength:{requiredLength:n,actualLength:t.value.length}}:null}(t)}static maxLength(t){return function GM(n){return t=>BM(t.value)&&t.value.length>n?{maxlength:{requiredLength:n,actualLength:t.value.length}}:null}(t)}static pattern(t){return function WM(n){if(!n)return wd;let t,e;return\"string\"==typeof n?(e=\"\",\"^\"!==n.charAt(0)&&(e+=\"^\"),e+=n,\"$\"!==n.charAt(n.length-1)&&(e+=\"$\"),t=new RegExp(e)):(e=n.toString(),t=n),i=>{if(sr(i.value))return null;const r=i.value;return t.test(r)?null:{pattern:{requiredPattern:e,actualValue:r}}}}(t)}static nullValidator(t){return null}static compose(t){return XM(t)}static composeAsync(t){return JM(t)}}function wd(n){return null}function qM(n){return null!=n}function YM(n){const t=ra(n)?mt(n):n;return up(t),t}function QM(n){let t={};return n.forEach(e=>{t=null!=e?Object.assign(Object.assign({},t),e):t}),0===Object.keys(t).length?null:t}function KM(n,t){return t.map(e=>e(n))}function ZM(n){return n.map(t=>function zj(n){return!n.validate}(t)?t:e=>t.validate(e))}function XM(n){if(!n)return null;const t=n.filter(qM);return 0==t.length?null:function(e){return QM(KM(e,t))}}function fm(n){return null!=n?XM(ZM(n)):null}function JM(n){if(!n)return null;const t=n.filter(qM);return 0==t.length?null:function(e){return function FM(...n){const t=b_(n),{args:e,keys:i}=VD(n),r=new Ve(s=>{const{length:o}=e;if(!o)return void s.complete();const a=new Array(o);let l=o,c=o;for(let d=0;d<o;d++){let u=!1;Jt(e[d]).subscribe(Ue(s,h=>{u||(u=!0,c--),a[d]=h},()=>l--,void 0,()=>{(!l||!u)&&(c||s.next(i?HD(i,a):a),s.complete())}))}});return t?r.pipe(bf(t)):r}(KM(e,t).map(YM)).pipe(ue(QM))}}function mm(n){return null!=n?JM(ZM(n)):null}function ex(n,t){return null===n?[t]:Array.isArray(n)?[...n,t]:[n,t]}function tx(n){return n._rawValidators}function nx(n){return n._rawAsyncValidators}function gm(n){return n?Array.isArray(n)?n:[n]:[]}function Md(n,t){return Array.isArray(n)?n.includes(t):n===t}function ix(n,t){const e=gm(t);return gm(n).forEach(r=>{Md(e,r)||e.push(r)}),e}function rx(n,t){return gm(t).filter(e=>!Md(n,e))}class sx{constructor(){this._rawValidators=[],this._rawAsyncValidators=[],this._onDestroyCallbacks=[]}get value(){return this.control?this.control.value:null}get valid(){return this.control?this.control.valid:null}get invalid(){return this.control?this.control.invalid:null}get pending(){return this.control?this.control.pending:null}get disabled(){return this.control?this.control.disabled:null}get enabled(){return this.control?this.control.enabled:null}get errors(){return this.control?this.control.errors:null}get pristine(){return this.control?this.control.pristine:null}get dirty(){return this.control?this.control.dirty:null}get touched(){return this.control?this.control.touched:null}get status(){return this.control?this.control.status:null}get untouched(){return this.control?this.control.untouched:null}get statusChanges(){return this.control?this.control.statusChanges:null}get valueChanges(){return this.control?this.control.valueChanges:null}get path(){return null}_setValidators(t){this._rawValidators=t||[],this._composedValidatorFn=fm(this._rawValidators)}_setAsyncValidators(t){this._rawAsyncValidators=t||[],this._composedAsyncValidatorFn=mm(this._rawAsyncValidators)}get validator(){return this._composedValidatorFn||null}get asyncValidator(){return this._composedAsyncValidatorFn||null}_registerOnDestroy(t){this._onDestroyCallbacks.push(t)}_invokeOnDestroyCallbacks(){this._onDestroyCallbacks.forEach(t=>t()),this._onDestroyCallbacks=[]}reset(t){this.control&&this.control.reset(t)}hasError(t,e){return!!this.control&&this.control.hasError(t,e)}getError(t,e){return this.control?this.control.getError(t,e):null}}class Jn extends sx{constructor(){super(...arguments),this._parent=null,this.name=null,this.valueAccessor=null}}class Wt extends sx{get formDirective(){return null}get path(){return null}}let ax=(()=>{class n extends class ox{constructor(t){this._cd=t}is(t){var e,i,r;return\"submitted\"===t?!!(null===(e=this._cd)||void 0===e?void 0:e.submitted):!!(null===(r=null===(i=this._cd)||void 0===i?void 0:i.control)||void 0===r?void 0:r[t])}}{constructor(e){super(e)}}return n.\\u0275fac=function(e){return new(e||n)(f(Jn,2))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"formControlName\",\"\"],[\"\",\"ngModel\",\"\"],[\"\",\"formControl\",\"\"]],hostVars:14,hostBindings:function(e,i){2&e&&Ae(\"ng-untouched\",i.is(\"untouched\"))(\"ng-touched\",i.is(\"touched\"))(\"ng-pristine\",i.is(\"pristine\"))(\"ng-dirty\",i.is(\"dirty\"))(\"ng-valid\",i.is(\"valid\"))(\"ng-invalid\",i.is(\"invalid\"))(\"ng-pending\",i.is(\"pending\"))},features:[E]}),n})();function Ha(n,t){ym(n,t),t.valueAccessor.writeValue(n.value),function Zj(n,t){t.valueAccessor.registerOnChange(e=>{n._pendingValue=e,n._pendingChange=!0,n._pendingDirty=!0,\"change\"===n.updateOn&&cx(n,t)})}(n,t),function Jj(n,t){const e=(i,r)=>{t.valueAccessor.writeValue(i),r&&t.viewToModelUpdate(i)};n.registerOnChange(e),t._registerOnDestroy(()=>{n._unregisterOnChange(e)})}(n,t),function Xj(n,t){t.valueAccessor.registerOnTouched(()=>{n._pendingTouched=!0,\"blur\"===n.updateOn&&n._pendingChange&&cx(n,t),\"submit\"!==n.updateOn&&n.markAsTouched()})}(n,t),function Kj(n,t){if(t.valueAccessor.setDisabledState){const e=i=>{t.valueAccessor.setDisabledState(i)};n.registerOnDisabledChange(e),t._registerOnDestroy(()=>{n._unregisterOnDisabledChange(e)})}}(n,t)}function Sd(n,t,e=!0){const i=()=>{};t.valueAccessor&&(t.valueAccessor.registerOnChange(i),t.valueAccessor.registerOnTouched(i)),Td(n,t),n&&(t._invokeOnDestroyCallbacks(),n._registerOnCollectionChange(()=>{}))}function kd(n,t){n.forEach(e=>{e.registerOnValidatorChange&&e.registerOnValidatorChange(t)})}function ym(n,t){const e=tx(n);null!==t.validator?n.setValidators(ex(e,t.validator)):\"function\"==typeof e&&n.setValidators([e]);const i=nx(n);null!==t.asyncValidator?n.setAsyncValidators(ex(i,t.asyncValidator)):\"function\"==typeof i&&n.setAsyncValidators([i]);const r=()=>n.updateValueAndValidity();kd(t._rawValidators,r),kd(t._rawAsyncValidators,r)}function Td(n,t){let e=!1;if(null!==n){if(null!==t.validator){const r=tx(n);if(Array.isArray(r)&&r.length>0){const s=r.filter(o=>o!==t.validator);s.length!==r.length&&(e=!0,n.setValidators(s))}}if(null!==t.asyncValidator){const r=nx(n);if(Array.isArray(r)&&r.length>0){const s=r.filter(o=>o!==t.asyncValidator);s.length!==r.length&&(e=!0,n.setAsyncValidators(s))}}}const i=()=>{};return kd(t._rawValidators,i),kd(t._rawAsyncValidators,i),e}function cx(n,t){n._pendingDirty&&n.markAsDirty(),n.setValue(n._pendingValue,{emitModelToViewChange:!1}),t.viewToModelUpdate(n._pendingValue),n._pendingChange=!1}function dx(n,t){ym(n,t)}function hx(n,t){n._syncPendingControls(),t.forEach(e=>{const i=e.control;\"submit\"===i.updateOn&&i._pendingChange&&(e.viewToModelUpdate(i._pendingValue),i._pendingChange=!1)})}function Dm(n,t){const e=n.indexOf(t);e>-1&&n.splice(e,1)}const ja=\"VALID\",Ad=\"INVALID\",so=\"PENDING\",za=\"DISABLED\";function Mm(n){return(Id(n)?n.validators:n)||null}function px(n){return Array.isArray(n)?fm(n):n||null}function xm(n,t){return(Id(t)?t.asyncValidators:n)||null}function fx(n){return Array.isArray(n)?mm(n):n||null}function Id(n){return null!=n&&!Array.isArray(n)&&\"object\"==typeof n}const mx=n=>n instanceof Rd,Em=n=>n instanceof km;function gx(n){return mx(n)?n.value:n.getRawValue()}function _x(n,t){const e=Em(n),i=n.controls;if(!(e?Object.keys(i):i).length)throw new H(1e3,\"\");if(!i[t])throw new H(1001,\"\")}function vx(n,t){Em(n),n._forEachChild((i,r)=>{if(void 0===t[r])throw new H(1002,\"\")})}class Sm{constructor(t,e){this._pendingDirty=!1,this._hasOwnPendingAsyncValidator=!1,this._pendingTouched=!1,this._onCollectionChange=()=>{},this._parent=null,this.pristine=!0,this.touched=!1,this._onDisabledChange=[],this._rawValidators=t,this._rawAsyncValidators=e,this._composedValidatorFn=px(this._rawValidators),this._composedAsyncValidatorFn=fx(this._rawAsyncValidators)}get validator(){return this._composedValidatorFn}set validator(t){this._rawValidators=this._composedValidatorFn=t}get asyncValidator(){return this._composedAsyncValidatorFn}set asyncValidator(t){this._rawAsyncValidators=this._composedAsyncValidatorFn=t}get parent(){return this._parent}get valid(){return this.status===ja}get invalid(){return this.status===Ad}get pending(){return this.status==so}get disabled(){return this.status===za}get enabled(){return this.status!==za}get dirty(){return!this.pristine}get untouched(){return!this.touched}get updateOn(){return this._updateOn?this._updateOn:this.parent?this.parent.updateOn:\"change\"}setValidators(t){this._rawValidators=t,this._composedValidatorFn=px(t)}setAsyncValidators(t){this._rawAsyncValidators=t,this._composedAsyncValidatorFn=fx(t)}addValidators(t){this.setValidators(ix(t,this._rawValidators))}addAsyncValidators(t){this.setAsyncValidators(ix(t,this._rawAsyncValidators))}removeValidators(t){this.setValidators(rx(t,this._rawValidators))}removeAsyncValidators(t){this.setAsyncValidators(rx(t,this._rawAsyncValidators))}hasValidator(t){return Md(this._rawValidators,t)}hasAsyncValidator(t){return Md(this._rawAsyncValidators,t)}clearValidators(){this.validator=null}clearAsyncValidators(){this.asyncValidator=null}markAsTouched(t={}){this.touched=!0,this._parent&&!t.onlySelf&&this._parent.markAsTouched(t)}markAllAsTouched(){this.markAsTouched({onlySelf:!0}),this._forEachChild(t=>t.markAllAsTouched())}markAsUntouched(t={}){this.touched=!1,this._pendingTouched=!1,this._forEachChild(e=>{e.markAsUntouched({onlySelf:!0})}),this._parent&&!t.onlySelf&&this._parent._updateTouched(t)}markAsDirty(t={}){this.pristine=!1,this._parent&&!t.onlySelf&&this._parent.markAsDirty(t)}markAsPristine(t={}){this.pristine=!0,this._pendingDirty=!1,this._forEachChild(e=>{e.markAsPristine({onlySelf:!0})}),this._parent&&!t.onlySelf&&this._parent._updatePristine(t)}markAsPending(t={}){this.status=so,!1!==t.emitEvent&&this.statusChanges.emit(this.status),this._parent&&!t.onlySelf&&this._parent.markAsPending(t)}disable(t={}){const e=this._parentMarkedDirty(t.onlySelf);this.status=za,this.errors=null,this._forEachChild(i=>{i.disable(Object.assign(Object.assign({},t),{onlySelf:!0}))}),this._updateValue(),!1!==t.emitEvent&&(this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._updateAncestors(Object.assign(Object.assign({},t),{skipPristineCheck:e})),this._onDisabledChange.forEach(i=>i(!0))}enable(t={}){const e=this._parentMarkedDirty(t.onlySelf);this.status=ja,this._forEachChild(i=>{i.enable(Object.assign(Object.assign({},t),{onlySelf:!0}))}),this.updateValueAndValidity({onlySelf:!0,emitEvent:t.emitEvent}),this._updateAncestors(Object.assign(Object.assign({},t),{skipPristineCheck:e})),this._onDisabledChange.forEach(i=>i(!1))}_updateAncestors(t){this._parent&&!t.onlySelf&&(this._parent.updateValueAndValidity(t),t.skipPristineCheck||this._parent._updatePristine(),this._parent._updateTouched())}setParent(t){this._parent=t}updateValueAndValidity(t={}){this._setInitialStatus(),this._updateValue(),this.enabled&&(this._cancelExistingSubscription(),this.errors=this._runValidator(),this.status=this._calculateStatus(),(this.status===ja||this.status===so)&&this._runAsyncValidator(t.emitEvent)),!1!==t.emitEvent&&(this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._parent&&!t.onlySelf&&this._parent.updateValueAndValidity(t)}_updateTreeValidity(t={emitEvent:!0}){this._forEachChild(e=>e._updateTreeValidity(t)),this.updateValueAndValidity({onlySelf:!0,emitEvent:t.emitEvent})}_setInitialStatus(){this.status=this._allControlsDisabled()?za:ja}_runValidator(){return this.validator?this.validator(this):null}_runAsyncValidator(t){if(this.asyncValidator){this.status=so,this._hasOwnPendingAsyncValidator=!0;const e=YM(this.asyncValidator(this));this._asyncValidationSubscription=e.subscribe(i=>{this._hasOwnPendingAsyncValidator=!1,this.setErrors(i,{emitEvent:t})})}}_cancelExistingSubscription(){this._asyncValidationSubscription&&(this._asyncValidationSubscription.unsubscribe(),this._hasOwnPendingAsyncValidator=!1)}setErrors(t,e={}){this.errors=t,this._updateControlsErrors(!1!==e.emitEvent)}get(t){return function iz(n,t,e){if(null==t||(Array.isArray(t)||(t=t.split(e)),Array.isArray(t)&&0===t.length))return null;let i=n;return t.forEach(r=>{i=Em(i)?i.controls.hasOwnProperty(r)?i.controls[r]:null:(n=>n instanceof sz)(i)&&i.at(r)||null}),i}(this,t,\".\")}getError(t,e){const i=e?this.get(e):this;return i&&i.errors?i.errors[t]:null}hasError(t,e){return!!this.getError(t,e)}get root(){let t=this;for(;t._parent;)t=t._parent;return t}_updateControlsErrors(t){this.status=this._calculateStatus(),t&&this.statusChanges.emit(this.status),this._parent&&this._parent._updateControlsErrors(t)}_initObservables(){this.valueChanges=new $,this.statusChanges=new $}_calculateStatus(){return this._allControlsDisabled()?za:this.errors?Ad:this._hasOwnPendingAsyncValidator||this._anyControlsHaveStatus(so)?so:this._anyControlsHaveStatus(Ad)?Ad:ja}_anyControlsHaveStatus(t){return this._anyControls(e=>e.status===t)}_anyControlsDirty(){return this._anyControls(t=>t.dirty)}_anyControlsTouched(){return this._anyControls(t=>t.touched)}_updatePristine(t={}){this.pristine=!this._anyControlsDirty(),this._parent&&!t.onlySelf&&this._parent._updatePristine(t)}_updateTouched(t={}){this.touched=this._anyControlsTouched(),this._parent&&!t.onlySelf&&this._parent._updateTouched(t)}_isBoxedValue(t){return\"object\"==typeof t&&null!==t&&2===Object.keys(t).length&&\"value\"in t&&\"disabled\"in t}_registerOnCollectionChange(t){this._onCollectionChange=t}_setUpdateStrategy(t){Id(t)&&null!=t.updateOn&&(this._updateOn=t.updateOn)}_parentMarkedDirty(t){return!t&&!(!this._parent||!this._parent.dirty)&&!this._parent._anyControlsDirty()}}class Rd extends Sm{constructor(t=null,e,i){super(Mm(e),xm(i,e)),this.defaultValue=null,this._onChange=[],this._pendingChange=!1,this._applyFormState(t),this._setUpdateStrategy(e),this._initObservables(),this.updateValueAndValidity({onlySelf:!0,emitEvent:!!this.asyncValidator}),Id(e)&&e.initialValueIsDefault&&(this.defaultValue=this._isBoxedValue(t)?t.value:t)}setValue(t,e={}){this.value=this._pendingValue=t,this._onChange.length&&!1!==e.emitModelToViewChange&&this._onChange.forEach(i=>i(this.value,!1!==e.emitViewToModelChange)),this.updateValueAndValidity(e)}patchValue(t,e={}){this.setValue(t,e)}reset(t=this.defaultValue,e={}){this._applyFormState(t),this.markAsPristine(e),this.markAsUntouched(e),this.setValue(this.value,e),this._pendingChange=!1}_updateValue(){}_anyControls(t){return!1}_allControlsDisabled(){return this.disabled}registerOnChange(t){this._onChange.push(t)}_unregisterOnChange(t){Dm(this._onChange,t)}registerOnDisabledChange(t){this._onDisabledChange.push(t)}_unregisterOnDisabledChange(t){Dm(this._onDisabledChange,t)}_forEachChild(t){}_syncPendingControls(){return!(\"submit\"!==this.updateOn||(this._pendingDirty&&this.markAsDirty(),this._pendingTouched&&this.markAsTouched(),!this._pendingChange)||(this.setValue(this._pendingValue,{onlySelf:!0,emitModelToViewChange:!1}),0))}_applyFormState(t){this._isBoxedValue(t)?(this.value=this._pendingValue=t.value,t.disabled?this.disable({onlySelf:!0,emitEvent:!1}):this.enable({onlySelf:!0,emitEvent:!1})):this.value=this._pendingValue=t}}class km extends Sm{constructor(t,e,i){super(Mm(e),xm(i,e)),this.controls=t,this._initObservables(),this._setUpdateStrategy(e),this._setUpControls(),this.updateValueAndValidity({onlySelf:!0,emitEvent:!!this.asyncValidator})}registerControl(t,e){return this.controls[t]?this.controls[t]:(this.controls[t]=e,e.setParent(this),e._registerOnCollectionChange(this._onCollectionChange),e)}addControl(t,e,i={}){this.registerControl(t,e),this.updateValueAndValidity({emitEvent:i.emitEvent}),this._onCollectionChange()}removeControl(t,e={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),delete this.controls[t],this.updateValueAndValidity({emitEvent:e.emitEvent}),this._onCollectionChange()}setControl(t,e,i={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),delete this.controls[t],e&&this.registerControl(t,e),this.updateValueAndValidity({emitEvent:i.emitEvent}),this._onCollectionChange()}contains(t){return this.controls.hasOwnProperty(t)&&this.controls[t].enabled}setValue(t,e={}){vx(this,t),Object.keys(t).forEach(i=>{_x(this,i),this.controls[i].setValue(t[i],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)}patchValue(t,e={}){null!=t&&(Object.keys(t).forEach(i=>{this.controls[i]&&this.controls[i].patchValue(t[i],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e))}reset(t={},e={}){this._forEachChild((i,r)=>{i.reset(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this._updatePristine(e),this._updateTouched(e),this.updateValueAndValidity(e)}getRawValue(){return this._reduceChildren({},(t,e,i)=>(t[i]=gx(e),t))}_syncPendingControls(){let t=this._reduceChildren(!1,(e,i)=>!!i._syncPendingControls()||e);return t&&this.updateValueAndValidity({onlySelf:!0}),t}_forEachChild(t){Object.keys(this.controls).forEach(e=>{const i=this.controls[e];i&&t(i,e)})}_setUpControls(){this._forEachChild(t=>{t.setParent(this),t._registerOnCollectionChange(this._onCollectionChange)})}_updateValue(){this.value=this._reduceValue()}_anyControls(t){for(const e of Object.keys(this.controls)){const i=this.controls[e];if(this.contains(e)&&t(i))return!0}return!1}_reduceValue(){return this._reduceChildren({},(t,e,i)=>((e.enabled||this.disabled)&&(t[i]=e.value),t))}_reduceChildren(t,e){let i=t;return this._forEachChild((r,s)=>{i=e(i,r,s)}),i}_allControlsDisabled(){for(const t of Object.keys(this.controls))if(this.controls[t].enabled)return!1;return Object.keys(this.controls).length>0||this.disabled}}class sz extends Sm{constructor(t,e,i){super(Mm(e),xm(i,e)),this.controls=t,this._initObservables(),this._setUpdateStrategy(e),this._setUpControls(),this.updateValueAndValidity({onlySelf:!0,emitEvent:!!this.asyncValidator})}at(t){return this.controls[t]}push(t,e={}){this.controls.push(t),this._registerControl(t),this.updateValueAndValidity({emitEvent:e.emitEvent}),this._onCollectionChange()}insert(t,e,i={}){this.controls.splice(t,0,e),this._registerControl(e),this.updateValueAndValidity({emitEvent:i.emitEvent})}removeAt(t,e={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),this.controls.splice(t,1),this.updateValueAndValidity({emitEvent:e.emitEvent})}setControl(t,e,i={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),this.controls.splice(t,1),e&&(this.controls.splice(t,0,e),this._registerControl(e)),this.updateValueAndValidity({emitEvent:i.emitEvent}),this._onCollectionChange()}get length(){return this.controls.length}setValue(t,e={}){vx(this,t),t.forEach((i,r)=>{_x(this,r),this.at(r).setValue(i,{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)}patchValue(t,e={}){null!=t&&(t.forEach((i,r)=>{this.at(r)&&this.at(r).patchValue(i,{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e))}reset(t=[],e={}){this._forEachChild((i,r)=>{i.reset(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this._updatePristine(e),this._updateTouched(e),this.updateValueAndValidity(e)}getRawValue(){return this.controls.map(t=>gx(t))}clear(t={}){this.controls.length<1||(this._forEachChild(e=>e._registerOnCollectionChange(()=>{})),this.controls.splice(0),this.updateValueAndValidity({emitEvent:t.emitEvent}))}_syncPendingControls(){let t=this.controls.reduce((e,i)=>!!i._syncPendingControls()||e,!1);return t&&this.updateValueAndValidity({onlySelf:!0}),t}_forEachChild(t){this.controls.forEach((e,i)=>{t(e,i)})}_updateValue(){this.value=this.controls.filter(t=>t.enabled||this.disabled).map(t=>t.value)}_anyControls(t){return this.controls.some(e=>e.enabled&&t(e))}_setUpControls(){this._forEachChild(t=>this._registerControl(t))}_allControlsDisabled(){for(const t of this.controls)if(t.enabled)return!1;return this.controls.length>0||this.disabled}_registerControl(t){t.setParent(this),t._registerOnCollectionChange(this._onCollectionChange)}}const oz={provide:Wt,useExisting:pe(()=>oo)},Ua=(()=>Promise.resolve(null))();let oo=(()=>{class n extends Wt{constructor(e,i){super(),this.submitted=!1,this._directives=new Set,this.ngSubmit=new $,this.form=new km({},fm(e),mm(i))}ngAfterViewInit(){this._setUpdateStrategy()}get formDirective(){return this}get control(){return this.form}get path(){return[]}get controls(){return this.form.controls}addControl(e){Ua.then(()=>{const i=this._findContainer(e.path);e.control=i.registerControl(e.name,e.control),Ha(e.control,e),e.control.updateValueAndValidity({emitEvent:!1}),this._directives.add(e)})}getControl(e){return this.form.get(e.path)}removeControl(e){Ua.then(()=>{const i=this._findContainer(e.path);i&&i.removeControl(e.name),this._directives.delete(e)})}addFormGroup(e){Ua.then(()=>{const i=this._findContainer(e.path),r=new km({});dx(r,e),i.registerControl(e.name,r),r.updateValueAndValidity({emitEvent:!1})})}removeFormGroup(e){Ua.then(()=>{const i=this._findContainer(e.path);i&&i.removeControl(e.name)})}getFormGroup(e){return this.form.get(e.path)}updateModel(e,i){Ua.then(()=>{this.form.get(e.path).setValue(i)})}setValue(e){this.control.setValue(e)}onSubmit(e){return this.submitted=!0,hx(this.form,this._directives),this.ngSubmit.emit(e),!1}onReset(){this.resetForm()}resetForm(e){this.form.reset(e),this.submitted=!1}_setUpdateStrategy(){this.options&&null!=this.options.updateOn&&(this.form._updateOn=this.options.updateOn)}_findContainer(e){return e.pop(),e.length?this.form.get(e):this.form}}return n.\\u0275fac=function(e){return new(e||n)(f(Dt,10),f(or,10))},n.\\u0275dir=C({type:n,selectors:[[\"form\",3,\"ngNoForm\",\"\",3,\"formGroup\",\"\"],[\"ng-form\"],[\"\",\"ngForm\",\"\"]],hostBindings:function(e,i){1&e&&J(\"submit\",function(s){return i.onSubmit(s)})(\"reset\",function(){return i.onReset()})},inputs:{options:[\"ngFormOptions\",\"options\"]},outputs:{ngSubmit:\"ngSubmit\"},exportAs:[\"ngForm\"],features:[L([oz]),E]}),n})();const dz={provide:xt,useExisting:pe(()=>Tm),multi:!0};let Tm=(()=>{class n extends $r{writeValue(e){this.setProperty(\"value\",null==e?\"\":e)}registerOnChange(e){this.onChange=i=>{e(\"\"==i?null:parseFloat(i))}}}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275dir=C({type:n,selectors:[[\"input\",\"type\",\"number\",\"formControlName\",\"\"],[\"input\",\"type\",\"number\",\"formControl\",\"\"],[\"input\",\"type\",\"number\",\"ngModel\",\"\"]],hostBindings:function(e,i){1&e&&J(\"input\",function(s){return i.onChange(s.target.value)})(\"blur\",function(){return i.onTouched()})},features:[L([dz]),E]}),n})(),wx=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const Am=new b(\"NgModelWithFormControlWarning\"),fz={provide:Jn,useExisting:pe(()=>Im)};let Im=(()=>{class n extends Jn{constructor(e,i,r,s){super(),this._ngModelWarningConfig=s,this.update=new $,this._ngModelWarningSent=!1,this._setValidators(e),this._setAsyncValidators(i),this.valueAccessor=function Cm(n,t){if(!t)return null;let e,i,r;return Array.isArray(t),t.forEach(s=>{s.constructor===Dd?e=s:function nz(n){return Object.getPrototypeOf(n.constructor)===$r}(s)?i=s:r=s}),r||i||e||null}(0,r)}set isDisabled(e){}ngOnChanges(e){if(this._isControlChanged(e)){const i=e.form.previousValue;i&&Sd(i,this,!1),Ha(this.form,this),this.control.disabled&&this.valueAccessor.setDisabledState&&this.valueAccessor.setDisabledState(!0),this.form.updateValueAndValidity({emitEvent:!1})}(function bm(n,t){if(!n.hasOwnProperty(\"model\"))return!1;const e=n.model;return!!e.isFirstChange()||!Object.is(t,e.currentValue)})(e,this.viewModel)&&(this.form.setValue(this.model),this.viewModel=this.model)}ngOnDestroy(){this.form&&Sd(this.form,this,!1)}get path(){return[]}get control(){return this.form}viewToModelUpdate(e){this.viewModel=e,this.update.emit(e)}_isControlChanged(e){return e.hasOwnProperty(\"form\")}}return n._ngModelWarningSentOnce=!1,n.\\u0275fac=function(e){return new(e||n)(f(Dt,10),f(or,10),f(xt,10),f(Am,8))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"formControl\",\"\"]],inputs:{form:[\"formControl\",\"form\"],isDisabled:[\"disabled\",\"isDisabled\"],model:[\"ngModel\",\"model\"]},outputs:{update:\"ngModelChange\"},exportAs:[\"ngForm\"],features:[L([fz]),E,Je]}),n})();const mz={provide:Wt,useExisting:pe(()=>ao)};let ao=(()=>{class n extends Wt{constructor(e,i){super(),this.validators=e,this.asyncValidators=i,this.submitted=!1,this._onCollectionChange=()=>this._updateDomValue(),this.directives=[],this.form=null,this.ngSubmit=new $,this._setValidators(e),this._setAsyncValidators(i)}ngOnChanges(e){this._checkFormPresent(),e.hasOwnProperty(\"form\")&&(this._updateValidators(),this._updateDomValue(),this._updateRegistrations(),this._oldForm=this.form)}ngOnDestroy(){this.form&&(Td(this.form,this),this.form._onCollectionChange===this._onCollectionChange&&this.form._registerOnCollectionChange(()=>{}))}get formDirective(){return this}get control(){return this.form}get path(){return[]}addControl(e){const i=this.form.get(e.path);return Ha(i,e),i.updateValueAndValidity({emitEvent:!1}),this.directives.push(e),i}getControl(e){return this.form.get(e.path)}removeControl(e){Sd(e.control||null,e,!1),Dm(this.directives,e)}addFormGroup(e){this._setUpFormContainer(e)}removeFormGroup(e){this._cleanUpFormContainer(e)}getFormGroup(e){return this.form.get(e.path)}addFormArray(e){this._setUpFormContainer(e)}removeFormArray(e){this._cleanUpFormContainer(e)}getFormArray(e){return this.form.get(e.path)}updateModel(e,i){this.form.get(e.path).setValue(i)}onSubmit(e){return this.submitted=!0,hx(this.form,this.directives),this.ngSubmit.emit(e),!1}onReset(){this.resetForm()}resetForm(e){this.form.reset(e),this.submitted=!1}_updateDomValue(){this.directives.forEach(e=>{const i=e.control,r=this.form.get(e.path);i!==r&&(Sd(i||null,e),mx(r)&&(Ha(r,e),e.control=r))}),this.form._updateTreeValidity({emitEvent:!1})}_setUpFormContainer(e){const i=this.form.get(e.path);dx(i,e),i.updateValueAndValidity({emitEvent:!1})}_cleanUpFormContainer(e){if(this.form){const i=this.form.get(e.path);i&&function ez(n,t){return Td(n,t)}(i,e)&&i.updateValueAndValidity({emitEvent:!1})}}_updateRegistrations(){this.form._registerOnCollectionChange(this._onCollectionChange),this._oldForm&&this._oldForm._registerOnCollectionChange(()=>{})}_updateValidators(){ym(this.form,this),this._oldForm&&Td(this._oldForm,this)}_checkFormPresent(){}}return n.\\u0275fac=function(e){return new(e||n)(f(Dt,10),f(or,10))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"formGroup\",\"\"]],hostBindings:function(e,i){1&e&&J(\"submit\",function(s){return i.onSubmit(s)})(\"reset\",function(){return i.onReset()})},inputs:{form:[\"formGroup\",\"form\"]},outputs:{ngSubmit:\"ngSubmit\"},exportAs:[\"ngForm\"],features:[L([mz]),E,Je]}),n})(),Bx=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[wx]]}),n})(),Pz=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[Bx]}),n})(),Fz=(()=>{class n{static withConfig(e){return{ngModule:n,providers:[{provide:Am,useValue:e.warnOnNgModelWithFormControl}]}}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[Bx]}),n})();const Nz=new b(\"cdk-dir-doc\",{providedIn:\"root\",factory:function Lz(){return Uo(ie)}}),Bz=/^(ar|ckb|dv|he|iw|fa|nqo|ps|sd|ug|ur|yi|.*[-_](Adlm|Arab|Hebr|Nkoo|Rohg|Thaa))(?!.*[-_](Latn|Cyrl)($|-|_))($|-|_)/i;let On=(()=>{class n{constructor(e){if(this.value=\"ltr\",this.change=new $,e){const r=e.documentElement?e.documentElement.dir:null;this.value=function Vz(n){const t=(null==n?void 0:n.toLowerCase())||\"\";return\"auto\"===t&&\"undefined\"!=typeof navigator&&(null==navigator?void 0:navigator.language)?Bz.test(navigator.language)?\"rtl\":\"ltr\":\"rtl\"===t?\"rtl\":\"ltr\"}((e.body?e.body.dir:null)||r||\"ltr\")}}ngOnDestroy(){this.change.complete()}}return n.\\u0275fac=function(e){return new(e||n)(y(Nz,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),lo=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const Lm=new Rr(\"13.3.0\");let Bm;try{Bm=\"undefined\"!=typeof Intl&&Intl.v8BreakIterator}catch(n){Bm=!1}let co,It=(()=>{class n{constructor(e){this._platformId=e,this.isBrowser=this._platformId?function OL(n){return n===wD}(this._platformId):\"object\"==typeof document&&!!document,this.EDGE=this.isBrowser&&/(edge)/i.test(navigator.userAgent),this.TRIDENT=this.isBrowser&&/(msie|trident)/i.test(navigator.userAgent),this.BLINK=this.isBrowser&&!(!window.chrome&&!Bm)&&\"undefined\"!=typeof CSS&&!this.EDGE&&!this.TRIDENT,this.WEBKIT=this.isBrowser&&/AppleWebKit/i.test(navigator.userAgent)&&!this.BLINK&&!this.EDGE&&!this.TRIDENT,this.IOS=this.isBrowser&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!(\"MSStream\"in window),this.FIREFOX=this.isBrowser&&/(firefox|minefield)/i.test(navigator.userAgent),this.ANDROID=this.isBrowser&&/android/i.test(navigator.userAgent)&&!this.TRIDENT,this.SAFARI=this.isBrowser&&/safari/i.test(navigator.userAgent)&&this.WEBKIT}}return n.\\u0275fac=function(e){return new(e||n)(y(bc))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const Vx=[\"color\",\"button\",\"checkbox\",\"date\",\"datetime-local\",\"email\",\"file\",\"hidden\",\"image\",\"month\",\"number\",\"password\",\"radio\",\"range\",\"reset\",\"search\",\"submit\",\"tel\",\"text\",\"time\",\"url\",\"week\"];function Hx(){if(co)return co;if(\"object\"!=typeof document||!document)return co=new Set(Vx),co;let n=document.createElement(\"input\");return co=new Set(Vx.filter(t=>(n.setAttribute(\"type\",t),n.type===t))),co}let $a,Wr,Vm;function ei(n){return function Hz(){if(null==$a&&\"undefined\"!=typeof window)try{window.addEventListener(\"test\",null,Object.defineProperty({},\"passive\",{get:()=>$a=!0}))}finally{$a=$a||!1}return $a}()?n:!!n.capture}function jz(){if(null==Wr){if(\"object\"!=typeof document||!document||\"function\"!=typeof Element||!Element)return Wr=!1,Wr;if(\"scrollBehavior\"in document.documentElement.style)Wr=!0;else{const n=Element.prototype.scrollTo;Wr=!!n&&!/\\{\\s*\\[native code\\]\\s*\\}/.test(n.toString())}}return Wr}function Fd(n){if(function zz(){if(null==Vm){const n=\"undefined\"!=typeof document?document.head:null;Vm=!(!n||!n.createShadowRoot&&!n.attachShadow)}return Vm}()){const t=n.getRootNode?n.getRootNode():null;if(\"undefined\"!=typeof ShadowRoot&&ShadowRoot&&t instanceof ShadowRoot)return t}return null}function Hm(){let n=\"undefined\"!=typeof document&&document?document.activeElement:null;for(;n&&n.shadowRoot;){const t=n.shadowRoot.activeElement;if(t===n)break;n=t}return n}function Pn(n){return n.composedPath?n.composedPath()[0]:n.target}function jm(){return\"undefined\"!=typeof __karma__&&!!__karma__||\"undefined\"!=typeof jasmine&&!!jasmine||\"undefined\"!=typeof jest&&!!jest||\"undefined\"!=typeof Mocha&&!!Mocha}function Xt(n,...t){return t.length?t.some(e=>n[e]):n.altKey||n.shiftKey||n.ctrlKey||n.metaKey}class e3 extends ke{constructor(t,e){super()}schedule(t,e=0){return this}}const Ld={setInterval(n,t,...e){const{delegate:i}=Ld;return(null==i?void 0:i.setInterval)?i.setInterval(n,t,...e):setInterval(n,t,...e)},clearInterval(n){const{delegate:t}=Ld;return((null==t?void 0:t.clearInterval)||clearInterval)(n)},delegate:void 0};class qm extends e3{constructor(t,e){super(t,e),this.scheduler=t,this.work=e,this.pending=!1}schedule(t,e=0){if(this.closed)return this;this.state=t;const i=this.id,r=this.scheduler;return null!=i&&(this.id=this.recycleAsyncId(r,i,e)),this.pending=!0,this.delay=e,this.id=this.id||this.requestAsyncId(r,this.id,e),this}requestAsyncId(t,e,i=0){return Ld.setInterval(t.flush.bind(t,this),i)}recycleAsyncId(t,e,i=0){if(null!=i&&this.delay===i&&!1===this.pending)return e;Ld.clearInterval(e)}execute(t,e){if(this.closed)return new Error(\"executing a cancelled action\");this.pending=!1;const i=this._execute(t,e);if(i)return i;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))}_execute(t,e){let r,i=!1;try{this.work(t)}catch(s){i=!0,r=s||new Error(\"Scheduled action threw falsy error\")}if(i)return this.unsubscribe(),r}unsubscribe(){if(!this.closed){const{id:t,scheduler:e}=this,{actions:i}=e;this.work=this.state=this.scheduler=null,this.pending=!1,ss(i,this),null!=t&&(this.id=this.recycleAsyncId(e,t,null)),this.delay=null,super.unsubscribe()}}}const Ux={now:()=>(Ux.delegate||Date).now(),delegate:void 0};class Wa{constructor(t,e=Wa.now){this.schedulerActionCtor=t,this.now=e}schedule(t,e=0,i){return new this.schedulerActionCtor(this,t).schedule(i,e)}}Wa.now=Ux.now;class Ym extends Wa{constructor(t,e=Wa.now){super(t,e),this.actions=[],this._active=!1,this._scheduled=void 0}flush(t){const{actions:e}=this;if(this._active)return void e.push(t);let i;this._active=!0;do{if(i=t.execute(t.state,t.delay))break}while(t=e.shift());if(this._active=!1,i){for(;t=e.shift();)t.unsubscribe();throw i}}}const qa=new Ym(qm),t3=qa;function $x(n,t=qa){return qe((e,i)=>{let r=null,s=null,o=null;const a=()=>{if(r){r.unsubscribe(),r=null;const c=s;s=null,i.next(c)}};function l(){const c=o+n,d=t.now();if(d<c)return r=this.schedule(void 0,c-d),void i.add(r);a()}e.subscribe(Ue(i,c=>{s=c,o=t.now(),r||(r=t.schedule(l,n),i.add(r))},()=>{a(),i.complete()},void 0,()=>{s=r=null}))})}function Gx(n,t=Wi){return n=null!=n?n:r3,qe((e,i)=>{let r,s=!0;e.subscribe(Ue(i,o=>{const a=t(o);(s||!n(r,a))&&(s=!1,r=a,i.next(o))}))})}function r3(n,t){return n===t}function Ie(n){return qe((t,e)=>{Jt(n).subscribe(Ue(e,()=>e.complete(),gl)),!e.closed&&t.subscribe(e)})}function G(n){return null!=n&&\"false\"!=`${n}`}function Et(n,t=0){return function s3(n){return!isNaN(parseFloat(n))&&!isNaN(Number(n))}(n)?Number(n):t}function Wx(n){return Array.isArray(n)?n:[n]}function ft(n){return null==n?\"\":\"string\"==typeof n?n:`${n}px`}function at(n){return n instanceof W?n.nativeElement:n}let qx=(()=>{class n{create(e){return\"undefined\"==typeof MutationObserver?null:new MutationObserver(e)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),o3=(()=>{class n{constructor(e){this._mutationObserverFactory=e,this._observedElements=new Map}ngOnDestroy(){this._observedElements.forEach((e,i)=>this._cleanupObserver(i))}observe(e){const i=at(e);return new Ve(r=>{const o=this._observeElement(i).subscribe(r);return()=>{o.unsubscribe(),this._unobserveElement(i)}})}_observeElement(e){if(this._observedElements.has(e))this._observedElements.get(e).count++;else{const i=new O,r=this._mutationObserverFactory.create(s=>i.next(s));r&&r.observe(e,{characterData:!0,childList:!0,subtree:!0}),this._observedElements.set(e,{observer:r,stream:i,count:1})}return this._observedElements.get(e).stream}_unobserveElement(e){this._observedElements.has(e)&&(this._observedElements.get(e).count--,this._observedElements.get(e).count||this._cleanupObserver(e))}_cleanupObserver(e){if(this._observedElements.has(e)){const{observer:i,stream:r}=this._observedElements.get(e);i&&i.disconnect(),r.complete(),this._observedElements.delete(e)}}}return n.\\u0275fac=function(e){return new(e||n)(y(qx))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),Qm=(()=>{class n{constructor(e,i,r){this._contentObserver=e,this._elementRef=i,this._ngZone=r,this.event=new $,this._disabled=!1,this._currentSubscription=null}get disabled(){return this._disabled}set disabled(e){this._disabled=G(e),this._disabled?this._unsubscribe():this._subscribe()}get debounce(){return this._debounce}set debounce(e){this._debounce=Et(e),this._subscribe()}ngAfterContentInit(){!this._currentSubscription&&!this.disabled&&this._subscribe()}ngOnDestroy(){this._unsubscribe()}_subscribe(){this._unsubscribe();const e=this._contentObserver.observe(this._elementRef);this._ngZone.runOutsideAngular(()=>{this._currentSubscription=(this.debounce?e.pipe($x(this.debounce)):e).subscribe(this.event)})}_unsubscribe(){var e;null===(e=this._currentSubscription)||void 0===e||e.unsubscribe()}}return n.\\u0275fac=function(e){return new(e||n)(f(o3),f(W),f(ne))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"cdkObserveContent\",\"\"]],inputs:{disabled:[\"cdkObserveContentDisabled\",\"disabled\"],debounce:\"debounce\"},outputs:{event:\"cdkObserveContent\"},exportAs:[\"cdkObserveContent\"]}),n})(),Ya=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[qx]}),n})();class c3 extends class Kx{constructor(t){this._items=t,this._activeItemIndex=-1,this._activeItem=null,this._wrap=!1,this._letterKeyStream=new O,this._typeaheadSubscription=ke.EMPTY,this._vertical=!0,this._allowedModifierKeys=[],this._homeAndEnd=!1,this._skipPredicateFn=e=>e.disabled,this._pressedLetters=[],this.tabOut=new O,this.change=new O,t instanceof fa&&t.changes.subscribe(e=>{if(this._activeItem){const r=e.toArray().indexOf(this._activeItem);r>-1&&r!==this._activeItemIndex&&(this._activeItemIndex=r)}})}skipPredicate(t){return this._skipPredicateFn=t,this}withWrap(t=!0){return this._wrap=t,this}withVerticalOrientation(t=!0){return this._vertical=t,this}withHorizontalOrientation(t){return this._horizontal=t,this}withAllowedModifierKeys(t){return this._allowedModifierKeys=t,this}withTypeAhead(t=200){return this._typeaheadSubscription.unsubscribe(),this._typeaheadSubscription=this._letterKeyStream.pipe(Mt(e=>this._pressedLetters.push(e)),$x(t),Ct(()=>this._pressedLetters.length>0),ue(()=>this._pressedLetters.join(\"\"))).subscribe(e=>{const i=this._getItemsArray();for(let r=1;r<i.length+1;r++){const s=(this._activeItemIndex+r)%i.length,o=i[s];if(!this._skipPredicateFn(o)&&0===o.getLabel().toUpperCase().trim().indexOf(e)){this.setActiveItem(s);break}}this._pressedLetters=[]}),this}withHomeAndEnd(t=!0){return this._homeAndEnd=t,this}setActiveItem(t){const e=this._activeItem;this.updateActiveItem(t),this._activeItem!==e&&this.change.next(this._activeItemIndex)}onKeydown(t){const e=t.keyCode,r=[\"altKey\",\"ctrlKey\",\"metaKey\",\"shiftKey\"].every(s=>!t[s]||this._allowedModifierKeys.indexOf(s)>-1);switch(e){case 9:return void this.tabOut.next();case 40:if(this._vertical&&r){this.setNextItemActive();break}return;case 38:if(this._vertical&&r){this.setPreviousItemActive();break}return;case 39:if(this._horizontal&&r){\"rtl\"===this._horizontal?this.setPreviousItemActive():this.setNextItemActive();break}return;case 37:if(this._horizontal&&r){\"rtl\"===this._horizontal?this.setNextItemActive():this.setPreviousItemActive();break}return;case 36:if(this._homeAndEnd&&r){this.setFirstItemActive();break}return;case 35:if(this._homeAndEnd&&r){this.setLastItemActive();break}return;default:return void((r||Xt(t,\"shiftKey\"))&&(t.key&&1===t.key.length?this._letterKeyStream.next(t.key.toLocaleUpperCase()):(e>=65&&e<=90||e>=48&&e<=57)&&this._letterKeyStream.next(String.fromCharCode(e))))}this._pressedLetters=[],t.preventDefault()}get activeItemIndex(){return this._activeItemIndex}get activeItem(){return this._activeItem}isTyping(){return this._pressedLetters.length>0}setFirstItemActive(){this._setActiveItemByIndex(0,1)}setLastItemActive(){this._setActiveItemByIndex(this._items.length-1,-1)}setNextItemActive(){this._activeItemIndex<0?this.setFirstItemActive():this._setActiveItemByDelta(1)}setPreviousItemActive(){this._activeItemIndex<0&&this._wrap?this.setLastItemActive():this._setActiveItemByDelta(-1)}updateActiveItem(t){const e=this._getItemsArray(),i=\"number\"==typeof t?t:e.indexOf(t),r=e[i];this._activeItem=null==r?null:r,this._activeItemIndex=i}_setActiveItemByDelta(t){this._wrap?this._setActiveInWrapMode(t):this._setActiveInDefaultMode(t)}_setActiveInWrapMode(t){const e=this._getItemsArray();for(let i=1;i<=e.length;i++){const r=(this._activeItemIndex+t*i+e.length)%e.length;if(!this._skipPredicateFn(e[r]))return void this.setActiveItem(r)}}_setActiveInDefaultMode(t){this._setActiveItemByIndex(this._activeItemIndex+t,t)}_setActiveItemByIndex(t,e){const i=this._getItemsArray();if(i[t]){for(;this._skipPredicateFn(i[t]);)if(!i[t+=e])return;this.setActiveItem(t)}}_getItemsArray(){return this._items instanceof fa?this._items.toArray():this._items}}{setActiveItem(t){this.activeItem&&this.activeItem.setInactiveStyles(),super.setActiveItem(t),this.activeItem&&this.activeItem.setActiveStyles()}}let Xx=(()=>{class n{constructor(e){this._platform=e}isDisabled(e){return e.hasAttribute(\"disabled\")}isVisible(e){return function u3(n){return!!(n.offsetWidth||n.offsetHeight||\"function\"==typeof n.getClientRects&&n.getClientRects().length)}(e)&&\"visible\"===getComputedStyle(e).visibility}isTabbable(e){if(!this._platform.isBrowser)return!1;const i=function d3(n){try{return n.frameElement}catch(t){return null}}(function y3(n){return n.ownerDocument&&n.ownerDocument.defaultView||window}(e));if(i&&(-1===eE(i)||!this.isVisible(i)))return!1;let r=e.nodeName.toLowerCase(),s=eE(e);return e.hasAttribute(\"contenteditable\")?-1!==s:!(\"iframe\"===r||\"object\"===r||this._platform.WEBKIT&&this._platform.IOS&&!function _3(n){let t=n.nodeName.toLowerCase(),e=\"input\"===t&&n.type;return\"text\"===e||\"password\"===e||\"select\"===t||\"textarea\"===t}(e))&&(\"audio\"===r?!!e.hasAttribute(\"controls\")&&-1!==s:\"video\"===r?-1!==s&&(null!==s||this._platform.FIREFOX||e.hasAttribute(\"controls\")):e.tabIndex>=0)}isFocusable(e,i){return function v3(n){return!function p3(n){return function m3(n){return\"input\"==n.nodeName.toLowerCase()}(n)&&\"hidden\"==n.type}(n)&&(function h3(n){let t=n.nodeName.toLowerCase();return\"input\"===t||\"select\"===t||\"button\"===t||\"textarea\"===t}(n)||function f3(n){return function g3(n){return\"a\"==n.nodeName.toLowerCase()}(n)&&n.hasAttribute(\"href\")}(n)||n.hasAttribute(\"contenteditable\")||Jx(n))}(e)&&!this.isDisabled(e)&&((null==i?void 0:i.ignoreVisibility)||this.isVisible(e))}}return n.\\u0275fac=function(e){return new(e||n)(y(It))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();function Jx(n){if(!n.hasAttribute(\"tabindex\")||void 0===n.tabIndex)return!1;let t=n.getAttribute(\"tabindex\");return!(!t||isNaN(parseInt(t,10)))}function eE(n){if(!Jx(n))return null;const t=parseInt(n.getAttribute(\"tabindex\")||\"\",10);return isNaN(t)?-1:t}class b3{constructor(t,e,i,r,s=!1){this._element=t,this._checker=e,this._ngZone=i,this._document=r,this._hasAttached=!1,this.startAnchorListener=()=>this.focusLastTabbableElement(),this.endAnchorListener=()=>this.focusFirstTabbableElement(),this._enabled=!0,s||this.attachAnchors()}get enabled(){return this._enabled}set enabled(t){this._enabled=t,this._startAnchor&&this._endAnchor&&(this._toggleAnchorTabIndex(t,this._startAnchor),this._toggleAnchorTabIndex(t,this._endAnchor))}destroy(){const t=this._startAnchor,e=this._endAnchor;t&&(t.removeEventListener(\"focus\",this.startAnchorListener),t.remove()),e&&(e.removeEventListener(\"focus\",this.endAnchorListener),e.remove()),this._startAnchor=this._endAnchor=null,this._hasAttached=!1}attachAnchors(){return!!this._hasAttached||(this._ngZone.runOutsideAngular(()=>{this._startAnchor||(this._startAnchor=this._createAnchor(),this._startAnchor.addEventListener(\"focus\",this.startAnchorListener)),this._endAnchor||(this._endAnchor=this._createAnchor(),this._endAnchor.addEventListener(\"focus\",this.endAnchorListener))}),this._element.parentNode&&(this._element.parentNode.insertBefore(this._startAnchor,this._element),this._element.parentNode.insertBefore(this._endAnchor,this._element.nextSibling),this._hasAttached=!0),this._hasAttached)}focusInitialElementWhenReady(t){return new Promise(e=>{this._executeOnStable(()=>e(this.focusInitialElement(t)))})}focusFirstTabbableElementWhenReady(t){return new Promise(e=>{this._executeOnStable(()=>e(this.focusFirstTabbableElement(t)))})}focusLastTabbableElementWhenReady(t){return new Promise(e=>{this._executeOnStable(()=>e(this.focusLastTabbableElement(t)))})}_getRegionBoundary(t){const e=this._element.querySelectorAll(`[cdk-focus-region-${t}], [cdkFocusRegion${t}], [cdk-focus-${t}]`);return\"start\"==t?e.length?e[0]:this._getFirstTabbableElement(this._element):e.length?e[e.length-1]:this._getLastTabbableElement(this._element)}focusInitialElement(t){const e=this._element.querySelector(\"[cdk-focus-initial], [cdkFocusInitial]\");if(e){if(!this._checker.isFocusable(e)){const i=this._getFirstTabbableElement(e);return null==i||i.focus(t),!!i}return e.focus(t),!0}return this.focusFirstTabbableElement(t)}focusFirstTabbableElement(t){const e=this._getRegionBoundary(\"start\");return e&&e.focus(t),!!e}focusLastTabbableElement(t){const e=this._getRegionBoundary(\"end\");return e&&e.focus(t),!!e}hasAttached(){return this._hasAttached}_getFirstTabbableElement(t){if(this._checker.isFocusable(t)&&this._checker.isTabbable(t))return t;const e=t.children;for(let i=0;i<e.length;i++){const r=e[i].nodeType===this._document.ELEMENT_NODE?this._getFirstTabbableElement(e[i]):null;if(r)return r}return null}_getLastTabbableElement(t){if(this._checker.isFocusable(t)&&this._checker.isTabbable(t))return t;const e=t.children;for(let i=e.length-1;i>=0;i--){const r=e[i].nodeType===this._document.ELEMENT_NODE?this._getLastTabbableElement(e[i]):null;if(r)return r}return null}_createAnchor(){const t=this._document.createElement(\"div\");return this._toggleAnchorTabIndex(this._enabled,t),t.classList.add(\"cdk-visually-hidden\"),t.classList.add(\"cdk-focus-trap-anchor\"),t.setAttribute(\"aria-hidden\",\"true\"),t}_toggleAnchorTabIndex(t,e){t?e.setAttribute(\"tabindex\",\"0\"):e.removeAttribute(\"tabindex\")}toggleAnchors(t){this._startAnchor&&this._endAnchor&&(this._toggleAnchorTabIndex(t,this._startAnchor),this._toggleAnchorTabIndex(t,this._endAnchor))}_executeOnStable(t){this._ngZone.isStable?t():this._ngZone.onStable.pipe(it(1)).subscribe(t)}}let C3=(()=>{class n{constructor(e,i,r){this._checker=e,this._ngZone=i,this._document=r}create(e,i=!1){return new b3(e,this._checker,this._ngZone,this._document,i)}}return n.\\u0275fac=function(e){return new(e||n)(y(Xx),y(ne),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();function Km(n){return 0===n.buttons||0===n.offsetX&&0===n.offsetY}function Zm(n){const t=n.touches&&n.touches[0]||n.changedTouches&&n.changedTouches[0];return!(!t||-1!==t.identifier||null!=t.radiusX&&1!==t.radiusX||null!=t.radiusY&&1!==t.radiusY)}const D3=new b(\"cdk-input-modality-detector-options\"),w3={ignoreKeys:[18,17,224,91,16]},ho=ei({passive:!0,capture:!0});let M3=(()=>{class n{constructor(e,i,r,s){this._platform=e,this._mostRecentTarget=null,this._modality=new Zt(null),this._lastTouchMs=0,this._onKeydown=o=>{var a,l;(null===(l=null===(a=this._options)||void 0===a?void 0:a.ignoreKeys)||void 0===l?void 0:l.some(c=>c===o.keyCode))||(this._modality.next(\"keyboard\"),this._mostRecentTarget=Pn(o))},this._onMousedown=o=>{Date.now()-this._lastTouchMs<650||(this._modality.next(Km(o)?\"keyboard\":\"mouse\"),this._mostRecentTarget=Pn(o))},this._onTouchstart=o=>{Zm(o)?this._modality.next(\"keyboard\"):(this._lastTouchMs=Date.now(),this._modality.next(\"touch\"),this._mostRecentTarget=Pn(o))},this._options=Object.assign(Object.assign({},w3),s),this.modalityDetected=this._modality.pipe(function n3(n){return Ct((t,e)=>n<=e)}(1)),this.modalityChanged=this.modalityDetected.pipe(Gx()),e.isBrowser&&i.runOutsideAngular(()=>{r.addEventListener(\"keydown\",this._onKeydown,ho),r.addEventListener(\"mousedown\",this._onMousedown,ho),r.addEventListener(\"touchstart\",this._onTouchstart,ho)})}get mostRecentModality(){return this._modality.value}ngOnDestroy(){this._modality.complete(),this._platform.isBrowser&&(document.removeEventListener(\"keydown\",this._onKeydown,ho),document.removeEventListener(\"mousedown\",this._onMousedown,ho),document.removeEventListener(\"touchstart\",this._onTouchstart,ho))}}return n.\\u0275fac=function(e){return new(e||n)(y(It),y(ne),y(ie),y(D3,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const x3=new b(\"liveAnnouncerElement\",{providedIn:\"root\",factory:function E3(){return null}}),S3=new b(\"LIVE_ANNOUNCER_DEFAULT_OPTIONS\");let k3=(()=>{class n{constructor(e,i,r,s){this._ngZone=i,this._defaultOptions=s,this._document=r,this._liveElement=e||this._createLiveElement()}announce(e,...i){const r=this._defaultOptions;let s,o;return 1===i.length&&\"number\"==typeof i[0]?o=i[0]:[s,o]=i,this.clear(),clearTimeout(this._previousTimeout),s||(s=r&&r.politeness?r.politeness:\"polite\"),null==o&&r&&(o=r.duration),this._liveElement.setAttribute(\"aria-live\",s),this._ngZone.runOutsideAngular(()=>new Promise(a=>{clearTimeout(this._previousTimeout),this._previousTimeout=setTimeout(()=>{this._liveElement.textContent=e,a(),\"number\"==typeof o&&(this._previousTimeout=setTimeout(()=>this.clear(),o))},100)}))}clear(){this._liveElement&&(this._liveElement.textContent=\"\")}ngOnDestroy(){var e;clearTimeout(this._previousTimeout),null===(e=this._liveElement)||void 0===e||e.remove(),this._liveElement=null}_createLiveElement(){const e=\"cdk-live-announcer-element\",i=this._document.getElementsByClassName(e),r=this._document.createElement(\"div\");for(let s=0;s<i.length;s++)i[s].remove();return r.classList.add(e),r.classList.add(\"cdk-visually-hidden\"),r.setAttribute(\"aria-atomic\",\"true\"),r.setAttribute(\"aria-live\",\"polite\"),this._document.body.appendChild(r),r}}return n.\\u0275fac=function(e){return new(e||n)(y(x3,8),y(ne),y(ie),y(S3,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const T3=new b(\"cdk-focus-monitor-default-options\"),Bd=ei({passive:!0,capture:!0});let Qr=(()=>{class n{constructor(e,i,r,s,o){this._ngZone=e,this._platform=i,this._inputModalityDetector=r,this._origin=null,this._windowFocused=!1,this._originFromTouchInteraction=!1,this._elementInfo=new Map,this._monitoredElementCount=0,this._rootNodeFocusListenerCount=new Map,this._windowFocusListener=()=>{this._windowFocused=!0,this._windowFocusTimeoutId=window.setTimeout(()=>this._windowFocused=!1)},this._stopInputModalityDetector=new O,this._rootNodeFocusAndBlurListener=a=>{const l=Pn(a),c=\"focus\"===a.type?this._onFocus:this._onBlur;for(let d=l;d;d=d.parentElement)c.call(this,a,d)},this._document=s,this._detectionMode=(null==o?void 0:o.detectionMode)||0}monitor(e,i=!1){const r=at(e);if(!this._platform.isBrowser||1!==r.nodeType)return q(null);const s=Fd(r)||this._getDocument(),o=this._elementInfo.get(r);if(o)return i&&(o.checkChildren=!0),o.subject;const a={checkChildren:i,subject:new O,rootNode:s};return this._elementInfo.set(r,a),this._registerGlobalListeners(a),a.subject}stopMonitoring(e){const i=at(e),r=this._elementInfo.get(i);r&&(r.subject.complete(),this._setClasses(i),this._elementInfo.delete(i),this._removeGlobalListeners(r))}focusVia(e,i,r){const s=at(e);s===this._getDocument().activeElement?this._getClosestElementsInfo(s).forEach(([a,l])=>this._originChanged(a,i,l)):(this._setOrigin(i),\"function\"==typeof s.focus&&s.focus(r))}ngOnDestroy(){this._elementInfo.forEach((e,i)=>this.stopMonitoring(i))}_getDocument(){return this._document||document}_getWindow(){return this._getDocument().defaultView||window}_getFocusOrigin(e){return this._origin?this._originFromTouchInteraction?this._shouldBeAttributedToTouch(e)?\"touch\":\"program\":this._origin:this._windowFocused&&this._lastFocusOrigin?this._lastFocusOrigin:\"program\"}_shouldBeAttributedToTouch(e){return 1===this._detectionMode||!!(null==e?void 0:e.contains(this._inputModalityDetector._mostRecentTarget))}_setClasses(e,i){e.classList.toggle(\"cdk-focused\",!!i),e.classList.toggle(\"cdk-touch-focused\",\"touch\"===i),e.classList.toggle(\"cdk-keyboard-focused\",\"keyboard\"===i),e.classList.toggle(\"cdk-mouse-focused\",\"mouse\"===i),e.classList.toggle(\"cdk-program-focused\",\"program\"===i)}_setOrigin(e,i=!1){this._ngZone.runOutsideAngular(()=>{this._origin=e,this._originFromTouchInteraction=\"touch\"===e&&i,0===this._detectionMode&&(clearTimeout(this._originTimeoutId),this._originTimeoutId=setTimeout(()=>this._origin=null,this._originFromTouchInteraction?650:1))})}_onFocus(e,i){const r=this._elementInfo.get(i),s=Pn(e);!r||!r.checkChildren&&i!==s||this._originChanged(i,this._getFocusOrigin(s),r)}_onBlur(e,i){const r=this._elementInfo.get(i);!r||r.checkChildren&&e.relatedTarget instanceof Node&&i.contains(e.relatedTarget)||(this._setClasses(i),this._emitOrigin(r.subject,null))}_emitOrigin(e,i){this._ngZone.run(()=>e.next(i))}_registerGlobalListeners(e){if(!this._platform.isBrowser)return;const i=e.rootNode,r=this._rootNodeFocusListenerCount.get(i)||0;r||this._ngZone.runOutsideAngular(()=>{i.addEventListener(\"focus\",this._rootNodeFocusAndBlurListener,Bd),i.addEventListener(\"blur\",this._rootNodeFocusAndBlurListener,Bd)}),this._rootNodeFocusListenerCount.set(i,r+1),1==++this._monitoredElementCount&&(this._ngZone.runOutsideAngular(()=>{this._getWindow().addEventListener(\"focus\",this._windowFocusListener)}),this._inputModalityDetector.modalityDetected.pipe(Ie(this._stopInputModalityDetector)).subscribe(s=>{this._setOrigin(s,!0)}))}_removeGlobalListeners(e){const i=e.rootNode;if(this._rootNodeFocusListenerCount.has(i)){const r=this._rootNodeFocusListenerCount.get(i);r>1?this._rootNodeFocusListenerCount.set(i,r-1):(i.removeEventListener(\"focus\",this._rootNodeFocusAndBlurListener,Bd),i.removeEventListener(\"blur\",this._rootNodeFocusAndBlurListener,Bd),this._rootNodeFocusListenerCount.delete(i))}--this._monitoredElementCount||(this._getWindow().removeEventListener(\"focus\",this._windowFocusListener),this._stopInputModalityDetector.next(),clearTimeout(this._windowFocusTimeoutId),clearTimeout(this._originTimeoutId))}_originChanged(e,i,r){this._setClasses(e,i),this._emitOrigin(r.subject,i),this._lastFocusOrigin=i}_getClosestElementsInfo(e){const i=[];return this._elementInfo.forEach((r,s)=>{(s===e||r.checkChildren&&s.contains(e))&&i.push([s,r])}),i}}return n.\\u0275fac=function(e){return new(e||n)(y(ne),y(It),y(M3),y(ie,8),y(T3,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const nE=\"cdk-high-contrast-black-on-white\",iE=\"cdk-high-contrast-white-on-black\",Xm=\"cdk-high-contrast-active\";let rE=(()=>{class n{constructor(e,i){this._platform=e,this._document=i}getHighContrastMode(){if(!this._platform.isBrowser)return 0;const e=this._document.createElement(\"div\");e.style.backgroundColor=\"rgb(1,2,3)\",e.style.position=\"absolute\",this._document.body.appendChild(e);const i=this._document.defaultView||window,r=i&&i.getComputedStyle?i.getComputedStyle(e):null,s=(r&&r.backgroundColor||\"\").replace(/ /g,\"\");switch(e.remove(),s){case\"rgb(0,0,0)\":return 2;case\"rgb(255,255,255)\":return 1}return 0}_applyBodyHighContrastModeCssClasses(){if(!this._hasCheckedHighContrastMode&&this._platform.isBrowser&&this._document.body){const e=this._document.body.classList;e.remove(Xm),e.remove(nE),e.remove(iE),this._hasCheckedHighContrastMode=!0;const i=this.getHighContrastMode();1===i?(e.add(Xm),e.add(nE)):2===i&&(e.add(Xm),e.add(iE))}}}return n.\\u0275fac=function(e){return new(e||n)(y(It),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),Qa=(()=>{class n{constructor(e){e._applyBodyHighContrastModeCssClasses()}}return n.\\u0275fac=function(e){return new(e||n)(y(rE))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Ya]]}),n})();const A3=[\"*\",[[\"mat-option\"],[\"ng-container\"]]],I3=[\"*\",\"mat-option, ng-container\"];function R3(n,t){if(1&n&&Le(0,\"mat-pseudo-checkbox\",4),2&n){const e=Be();N(\"state\",e.selected?\"checked\":\"unchecked\")(\"disabled\",e.disabled)}}function O3(n,t){if(1&n&&(x(0,\"span\",5),we(1),S()),2&n){const e=Be();T(1),qn(\"(\",e.group.label,\")\")}}const P3=[\"*\"],Jm=new Rr(\"13.3.0\"),N3=new b(\"mat-sanity-checks\",{providedIn:\"root\",factory:function F3(){return!0}});let B=(()=>{class n{constructor(e,i,r){this._sanityChecks=i,this._document=r,this._hasDoneGlobalChecks=!1,e._applyBodyHighContrastModeCssClasses(),this._hasDoneGlobalChecks||(this._hasDoneGlobalChecks=!0)}_checkIsEnabled(e){return!jm()&&(\"boolean\"==typeof this._sanityChecks?this._sanityChecks:!!this._sanityChecks[e])}}return n.\\u0275fac=function(e){return new(e||n)(y(rE),y(N3,8),y(ie))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[lo],lo]}),n})();function po(n){return class extends n{constructor(...t){super(...t),this._disabled=!1}get disabled(){return this._disabled}set disabled(t){this._disabled=G(t)}}}function fo(n,t){return class extends n{constructor(...e){super(...e),this.defaultColor=t,this.color=t}get color(){return this._color}set color(e){const i=e||this.defaultColor;i!==this._color&&(this._color&&this._elementRef.nativeElement.classList.remove(`mat-${this._color}`),i&&this._elementRef.nativeElement.classList.add(`mat-${i}`),this._color=i)}}}function ar(n){return class extends n{constructor(...t){super(...t),this._disableRipple=!1}get disableRipple(){return this._disableRipple}set disableRipple(t){this._disableRipple=G(t)}}}function Kr(n,t=0){return class extends n{constructor(...e){super(...e),this._tabIndex=t,this.defaultTabIndex=t}get tabIndex(){return this.disabled?-1:this._tabIndex}set tabIndex(e){this._tabIndex=null!=e?Et(e):this.defaultTabIndex}}}function ng(n){return class extends n{constructor(...t){super(...t),this.stateChanges=new O,this.errorState=!1}updateErrorState(){const t=this.errorState,s=(this.errorStateMatcher||this._defaultErrorStateMatcher).isErrorState(this.ngControl?this.ngControl.control:null,this._parentFormGroup||this._parentForm);s!==t&&(this.errorState=s,this.stateChanges.next())}}}const L3=new b(\"MAT_DATE_LOCALE\",{providedIn:\"root\",factory:function B3(){return Uo(Oi)}});class bi{constructor(){this._localeChanges=new O,this.localeChanges=this._localeChanges}getValidDateOrNull(t){return this.isDateInstance(t)&&this.isValid(t)?t:null}deserialize(t){return null==t||this.isDateInstance(t)&&this.isValid(t)?t:this.invalid()}setLocale(t){this.locale=t,this._localeChanges.next()}compareDate(t,e){return this.getYear(t)-this.getYear(e)||this.getMonth(t)-this.getMonth(e)||this.getDate(t)-this.getDate(e)}sameDate(t,e){if(t&&e){let i=this.isValid(t),r=this.isValid(e);return i&&r?!this.compareDate(t,e):i==r}return t==e}clampDate(t,e,i){return e&&this.compareDate(t,e)<0?e:i&&this.compareDate(t,i)>0?i:t}}const ig=new b(\"mat-date-formats\"),V3=/^\\d{4}-\\d{2}-\\d{2}(?:T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|(?:(?:\\+|-)\\d{2}:\\d{2}))?)?$/;function rg(n,t){const e=Array(n);for(let i=0;i<n;i++)e[i]=t(i);return e}let H3=(()=>{class n extends bi{constructor(e,i){super(),this.useUtcForDisplay=!1,super.setLocale(e)}getYear(e){return e.getFullYear()}getMonth(e){return e.getMonth()}getDate(e){return e.getDate()}getDayOfWeek(e){return e.getDay()}getMonthNames(e){const i=new Intl.DateTimeFormat(this.locale,{month:e,timeZone:\"utc\"});return rg(12,r=>this._format(i,new Date(2017,r,1)))}getDateNames(){const e=new Intl.DateTimeFormat(this.locale,{day:\"numeric\",timeZone:\"utc\"});return rg(31,i=>this._format(e,new Date(2017,0,i+1)))}getDayOfWeekNames(e){const i=new Intl.DateTimeFormat(this.locale,{weekday:e,timeZone:\"utc\"});return rg(7,r=>this._format(i,new Date(2017,0,r+1)))}getYearName(e){const i=new Intl.DateTimeFormat(this.locale,{year:\"numeric\",timeZone:\"utc\"});return this._format(i,e)}getFirstDayOfWeek(){return 0}getNumDaysInMonth(e){return this.getDate(this._createDateWithOverflow(this.getYear(e),this.getMonth(e)+1,0))}clone(e){return new Date(e.getTime())}createDate(e,i,r){let s=this._createDateWithOverflow(e,i,r);return s.getMonth(),s}today(){return new Date}parse(e){return\"number\"==typeof e?new Date(e):e?new Date(Date.parse(e)):null}format(e,i){if(!this.isValid(e))throw Error(\"NativeDateAdapter: Cannot format invalid date.\");const r=new Intl.DateTimeFormat(this.locale,Object.assign(Object.assign({},i),{timeZone:\"utc\"}));return this._format(r,e)}addCalendarYears(e,i){return this.addCalendarMonths(e,12*i)}addCalendarMonths(e,i){let r=this._createDateWithOverflow(this.getYear(e),this.getMonth(e)+i,this.getDate(e));return this.getMonth(r)!=((this.getMonth(e)+i)%12+12)%12&&(r=this._createDateWithOverflow(this.getYear(r),this.getMonth(r),0)),r}addCalendarDays(e,i){return this._createDateWithOverflow(this.getYear(e),this.getMonth(e),this.getDate(e)+i)}toIso8601(e){return[e.getUTCFullYear(),this._2digit(e.getUTCMonth()+1),this._2digit(e.getUTCDate())].join(\"-\")}deserialize(e){if(\"string\"==typeof e){if(!e)return null;if(V3.test(e)){let i=new Date(e);if(this.isValid(i))return i}}return super.deserialize(e)}isDateInstance(e){return e instanceof Date}isValid(e){return!isNaN(e.getTime())}invalid(){return new Date(NaN)}_createDateWithOverflow(e,i,r){const s=new Date;return s.setFullYear(e,i,r),s.setHours(0,0,0,0),s}_2digit(e){return(\"00\"+e).slice(-2)}_format(e,i){const r=new Date;return r.setUTCFullYear(i.getFullYear(),i.getMonth(),i.getDate()),r.setUTCHours(i.getHours(),i.getMinutes(),i.getSeconds(),i.getMilliseconds()),e.format(r)}}return n.\\u0275fac=function(e){return new(e||n)(y(L3,8),y(It))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const j3={parse:{dateInput:null},display:{dateInput:{year:\"numeric\",month:\"numeric\",day:\"numeric\"},monthYearLabel:{year:\"numeric\",month:\"short\"},dateA11yLabel:{year:\"numeric\",month:\"long\",day:\"numeric\"},monthYearA11yLabel:{year:\"numeric\",month:\"long\"}}};let z3=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[{provide:bi,useClass:H3}]}),n})(),U3=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[{provide:ig,useValue:j3}],imports:[[z3]]}),n})(),mo=(()=>{class n{isErrorState(e,i){return!!(e&&e.invalid&&(e.touched||i&&i.submitted))}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),Vd=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})();class W3{constructor(t,e,i){this._renderer=t,this.element=e,this.config=i,this.state=3}fadeOut(){this._renderer.fadeOutRipple(this)}}const sE={enterDuration:225,exitDuration:150},sg=ei({passive:!0}),oE=[\"mousedown\",\"touchstart\"],aE=[\"mouseup\",\"mouseleave\",\"touchend\",\"touchcancel\"];class lE{constructor(t,e,i,r){this._target=t,this._ngZone=e,this._isPointerDown=!1,this._activeRipples=new Set,this._pointerUpEventsRegistered=!1,r.isBrowser&&(this._containerElement=at(i))}fadeInRipple(t,e,i={}){const r=this._containerRect=this._containerRect||this._containerElement.getBoundingClientRect(),s=Object.assign(Object.assign({},sE),i.animation);i.centered&&(t=r.left+r.width/2,e=r.top+r.height/2);const o=i.radius||function Q3(n,t,e){const i=Math.max(Math.abs(n-e.left),Math.abs(n-e.right)),r=Math.max(Math.abs(t-e.top),Math.abs(t-e.bottom));return Math.sqrt(i*i+r*r)}(t,e,r),a=t-r.left,l=e-r.top,c=s.enterDuration,d=document.createElement(\"div\");d.classList.add(\"mat-ripple-element\"),d.style.left=a-o+\"px\",d.style.top=l-o+\"px\",d.style.height=2*o+\"px\",d.style.width=2*o+\"px\",null!=i.color&&(d.style.backgroundColor=i.color),d.style.transitionDuration=`${c}ms`,this._containerElement.appendChild(d),function Y3(n){window.getComputedStyle(n).getPropertyValue(\"opacity\")}(d),d.style.transform=\"scale(1)\";const u=new W3(this,d,i);return u.state=0,this._activeRipples.add(u),i.persistent||(this._mostRecentTransientRipple=u),this._runTimeoutOutsideZone(()=>{const h=u===this._mostRecentTransientRipple;u.state=1,!i.persistent&&(!h||!this._isPointerDown)&&u.fadeOut()},c),u}fadeOutRipple(t){const e=this._activeRipples.delete(t);if(t===this._mostRecentTransientRipple&&(this._mostRecentTransientRipple=null),this._activeRipples.size||(this._containerRect=null),!e)return;const i=t.element,r=Object.assign(Object.assign({},sE),t.config.animation);i.style.transitionDuration=`${r.exitDuration}ms`,i.style.opacity=\"0\",t.state=2,this._runTimeoutOutsideZone(()=>{t.state=3,i.remove()},r.exitDuration)}fadeOutAll(){this._activeRipples.forEach(t=>t.fadeOut())}fadeOutAllNonPersistent(){this._activeRipples.forEach(t=>{t.config.persistent||t.fadeOut()})}setupTriggerEvents(t){const e=at(t);!e||e===this._triggerElement||(this._removeTriggerEvents(),this._triggerElement=e,this._registerEvents(oE))}handleEvent(t){\"mousedown\"===t.type?this._onMousedown(t):\"touchstart\"===t.type?this._onTouchStart(t):this._onPointerUp(),this._pointerUpEventsRegistered||(this._registerEvents(aE),this._pointerUpEventsRegistered=!0)}_onMousedown(t){const e=Km(t),i=this._lastTouchStartEvent&&Date.now()<this._lastTouchStartEvent+800;!this._target.rippleDisabled&&!e&&!i&&(this._isPointerDown=!0,this.fadeInRipple(t.clientX,t.clientY,this._target.rippleConfig))}_onTouchStart(t){if(!this._target.rippleDisabled&&!Zm(t)){this._lastTouchStartEvent=Date.now(),this._isPointerDown=!0;const e=t.changedTouches;for(let i=0;i<e.length;i++)this.fadeInRipple(e[i].clientX,e[i].clientY,this._target.rippleConfig)}}_onPointerUp(){!this._isPointerDown||(this._isPointerDown=!1,this._activeRipples.forEach(t=>{!t.config.persistent&&(1===t.state||t.config.terminateOnPointerUp&&0===t.state)&&t.fadeOut()}))}_runTimeoutOutsideZone(t,e=0){this._ngZone.runOutsideAngular(()=>setTimeout(t,e))}_registerEvents(t){this._ngZone.runOutsideAngular(()=>{t.forEach(e=>{this._triggerElement.addEventListener(e,this,sg)})})}_removeTriggerEvents(){this._triggerElement&&(oE.forEach(t=>{this._triggerElement.removeEventListener(t,this,sg)}),this._pointerUpEventsRegistered&&aE.forEach(t=>{this._triggerElement.removeEventListener(t,this,sg)}))}}const cE=new b(\"mat-ripple-global-options\");let Zr=(()=>{class n{constructor(e,i,r,s,o){this._elementRef=e,this._animationMode=o,this.radius=0,this._disabled=!1,this._isInitialized=!1,this._globalOptions=s||{},this._rippleRenderer=new lE(this,i,e,r)}get disabled(){return this._disabled}set disabled(e){e&&this.fadeOutAllNonPersistent(),this._disabled=e,this._setupTriggerEventsIfEnabled()}get trigger(){return this._trigger||this._elementRef.nativeElement}set trigger(e){this._trigger=e,this._setupTriggerEventsIfEnabled()}ngOnInit(){this._isInitialized=!0,this._setupTriggerEventsIfEnabled()}ngOnDestroy(){this._rippleRenderer._removeTriggerEvents()}fadeOutAll(){this._rippleRenderer.fadeOutAll()}fadeOutAllNonPersistent(){this._rippleRenderer.fadeOutAllNonPersistent()}get rippleConfig(){return{centered:this.centered,radius:this.radius,color:this.color,animation:Object.assign(Object.assign(Object.assign({},this._globalOptions.animation),\"NoopAnimations\"===this._animationMode?{enterDuration:0,exitDuration:0}:{}),this.animation),terminateOnPointerUp:this._globalOptions.terminateOnPointerUp}}get rippleDisabled(){return this.disabled||!!this._globalOptions.disabled}_setupTriggerEventsIfEnabled(){!this.disabled&&this._isInitialized&&this._rippleRenderer.setupTriggerEvents(this.trigger)}launch(e,i=0,r){return\"number\"==typeof e?this._rippleRenderer.fadeInRipple(e,i,Object.assign(Object.assign({},this.rippleConfig),r)):this._rippleRenderer.fadeInRipple(0,0,Object.assign(Object.assign({},this.rippleConfig),e))}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(ne),f(It),f(cE,8),f(Rn,8))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"mat-ripple\",\"\"],[\"\",\"matRipple\",\"\"]],hostAttrs:[1,\"mat-ripple\"],hostVars:2,hostBindings:function(e,i){2&e&&Ae(\"mat-ripple-unbounded\",i.unbounded)},inputs:{color:[\"matRippleColor\",\"color\"],unbounded:[\"matRippleUnbounded\",\"unbounded\"],centered:[\"matRippleCentered\",\"centered\"],radius:[\"matRippleRadius\",\"radius\"],animation:[\"matRippleAnimation\",\"animation\"],disabled:[\"matRippleDisabled\",\"disabled\"],trigger:[\"matRippleTrigger\",\"trigger\"]},exportAs:[\"matRipple\"]}),n})(),ti=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),dE=(()=>{class n{constructor(e){this._animationMode=e,this.state=\"unchecked\",this.disabled=!1}}return n.\\u0275fac=function(e){return new(e||n)(f(Rn,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-pseudo-checkbox\"]],hostAttrs:[1,\"mat-pseudo-checkbox\"],hostVars:8,hostBindings:function(e,i){2&e&&Ae(\"mat-pseudo-checkbox-indeterminate\",\"indeterminate\"===i.state)(\"mat-pseudo-checkbox-checked\",\"checked\"===i.state)(\"mat-pseudo-checkbox-disabled\",i.disabled)(\"_mat-animation-noopable\",\"NoopAnimations\"===i._animationMode)},inputs:{state:\"state\",disabled:\"disabled\"},decls:0,vars:0,template:function(e,i){},styles:['.mat-pseudo-checkbox{width:16px;height:16px;border:2px solid;border-radius:2px;cursor:pointer;display:inline-block;vertical-align:middle;box-sizing:border-box;position:relative;flex-shrink:0;transition:border-color 90ms cubic-bezier(0, 0, 0.2, 0.1),background-color 90ms cubic-bezier(0, 0, 0.2, 0.1)}.mat-pseudo-checkbox::after{position:absolute;opacity:0;content:\"\";border-bottom:2px solid currentColor;transition:opacity 90ms cubic-bezier(0, 0, 0.2, 0.1)}.mat-pseudo-checkbox.mat-pseudo-checkbox-checked,.mat-pseudo-checkbox.mat-pseudo-checkbox-indeterminate{border-color:transparent}._mat-animation-noopable.mat-pseudo-checkbox{transition:none;animation:none}._mat-animation-noopable.mat-pseudo-checkbox::after{transition:none}.mat-pseudo-checkbox-disabled{cursor:default}.mat-pseudo-checkbox-indeterminate::after{top:5px;left:1px;width:10px;opacity:1;border-radius:2px}.mat-pseudo-checkbox-checked::after{top:2.4px;left:1px;width:8px;height:3px;border-left:2px solid currentColor;transform:rotate(-45deg);opacity:1;box-sizing:content-box}\\n'],encapsulation:2,changeDetection:0}),n})(),og=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B]]}),n})();const ag=new b(\"MAT_OPTION_PARENT_COMPONENT\"),K3=po(class{});let Z3=0,X3=(()=>{class n extends K3{constructor(e){var i;super(),this._labelId=\"mat-optgroup-label-\"+Z3++,this._inert=null!==(i=null==e?void 0:e.inertGroups)&&void 0!==i&&i}}return n.\\u0275fac=function(e){return new(e||n)(f(ag,8))},n.\\u0275dir=C({type:n,inputs:{label:\"label\"},features:[E]}),n})();const lg=new b(\"MatOptgroup\");let J3=(()=>{class n extends X3{}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275cmp=xe({type:n,selectors:[[\"mat-optgroup\"]],hostAttrs:[1,\"mat-optgroup\"],hostVars:5,hostBindings:function(e,i){2&e&&(Z(\"role\",i._inert?null:\"group\")(\"aria-disabled\",i._inert?null:i.disabled.toString())(\"aria-labelledby\",i._inert?null:i._labelId),Ae(\"mat-optgroup-disabled\",i.disabled))},inputs:{disabled:\"disabled\"},exportAs:[\"matOptgroup\"],features:[L([{provide:lg,useExisting:n}]),E],ngContentSelectors:I3,decls:4,vars:2,consts:[[\"aria-hidden\",\"true\",1,\"mat-optgroup-label\",3,\"id\"]],template:function(e,i){1&e&&(Lt(A3),x(0,\"span\",0),we(1),Pe(2),S(),Pe(3,1)),2&e&&(N(\"id\",i._labelId),T(1),qn(\"\",i.label,\" \"))},styles:[\".mat-optgroup-label{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;line-height:48px;height:48px;padding:0 16px;text-align:left;text-decoration:none;max-width:100%;-webkit-user-select:none;-moz-user-select:none;user-select:none;cursor:default}.mat-optgroup-label[disabled]{cursor:default}[dir=rtl] .mat-optgroup-label{text-align:right}.mat-optgroup-label .mat-icon{margin-right:16px;vertical-align:middle}.mat-optgroup-label .mat-icon svg{vertical-align:top}[dir=rtl] .mat-optgroup-label .mat-icon{margin-left:16px;margin-right:0}\\n\"],encapsulation:2,changeDetection:0}),n})(),eU=0;class uE{constructor(t,e=!1){this.source=t,this.isUserInput=e}}let tU=(()=>{class n{constructor(e,i,r,s){this._element=e,this._changeDetectorRef=i,this._parent=r,this.group=s,this._selected=!1,this._active=!1,this._disabled=!1,this._mostRecentViewValue=\"\",this.id=\"mat-option-\"+eU++,this.onSelectionChange=new $,this._stateChanges=new O}get multiple(){return this._parent&&this._parent.multiple}get selected(){return this._selected}get disabled(){return this.group&&this.group.disabled||this._disabled}set disabled(e){this._disabled=G(e)}get disableRipple(){return!(!this._parent||!this._parent.disableRipple)}get active(){return this._active}get viewValue(){return(this._getHostElement().textContent||\"\").trim()}select(){this._selected||(this._selected=!0,this._changeDetectorRef.markForCheck(),this._emitSelectionChangeEvent())}deselect(){this._selected&&(this._selected=!1,this._changeDetectorRef.markForCheck(),this._emitSelectionChangeEvent())}focus(e,i){const r=this._getHostElement();\"function\"==typeof r.focus&&r.focus(i)}setActiveStyles(){this._active||(this._active=!0,this._changeDetectorRef.markForCheck())}setInactiveStyles(){this._active&&(this._active=!1,this._changeDetectorRef.markForCheck())}getLabel(){return this.viewValue}_handleKeydown(e){(13===e.keyCode||32===e.keyCode)&&!Xt(e)&&(this._selectViaInteraction(),e.preventDefault())}_selectViaInteraction(){this.disabled||(this._selected=!this.multiple||!this._selected,this._changeDetectorRef.markForCheck(),this._emitSelectionChangeEvent(!0))}_getAriaSelected(){return this.selected||!this.multiple&&null}_getTabIndex(){return this.disabled?\"-1\":\"0\"}_getHostElement(){return this._element.nativeElement}ngAfterViewChecked(){if(this._selected){const e=this.viewValue;e!==this._mostRecentViewValue&&(this._mostRecentViewValue=e,this._stateChanges.next())}}ngOnDestroy(){this._stateChanges.complete()}_emitSelectionChangeEvent(e=!1){this.onSelectionChange.emit(new uE(this,e))}}return n.\\u0275fac=function(e){Sr()},n.\\u0275dir=C({type:n,inputs:{value:\"value\",id:\"id\",disabled:\"disabled\"},outputs:{onSelectionChange:\"onSelectionChange\"}}),n})(),hE=(()=>{class n extends tU{constructor(e,i,r,s){super(e,i,r,s)}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(Ye),f(ag,8),f(lg,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-option\"]],hostAttrs:[\"role\",\"option\",1,\"mat-option\",\"mat-focus-indicator\"],hostVars:12,hostBindings:function(e,i){1&e&&J(\"click\",function(){return i._selectViaInteraction()})(\"keydown\",function(s){return i._handleKeydown(s)}),2&e&&(Yn(\"id\",i.id),Z(\"tabindex\",i._getTabIndex())(\"aria-selected\",i._getAriaSelected())(\"aria-disabled\",i.disabled.toString()),Ae(\"mat-selected\",i.selected)(\"mat-option-multiple\",i.multiple)(\"mat-active\",i.active)(\"mat-option-disabled\",i.disabled))},exportAs:[\"matOption\"],features:[E],ngContentSelectors:P3,decls:5,vars:4,consts:[[\"class\",\"mat-option-pseudo-checkbox\",3,\"state\",\"disabled\",4,\"ngIf\"],[1,\"mat-option-text\"],[\"class\",\"cdk-visually-hidden\",4,\"ngIf\"],[\"mat-ripple\",\"\",1,\"mat-option-ripple\",3,\"matRippleTrigger\",\"matRippleDisabled\"],[1,\"mat-option-pseudo-checkbox\",3,\"state\",\"disabled\"],[1,\"cdk-visually-hidden\"]],template:function(e,i){1&e&&(Lt(),Ee(0,R3,1,2,\"mat-pseudo-checkbox\",0),x(1,\"span\",1),Pe(2),S(),Ee(3,O3,2,1,\"span\",2),Le(4,\"div\",3)),2&e&&(N(\"ngIf\",i.multiple),T(3),N(\"ngIf\",i.group&&i.group._inert),T(1),N(\"matRippleTrigger\",i._getHostElement())(\"matRippleDisabled\",i.disabled||i.disableRipple))},directives:[dE,Ca,Zr],styles:[\".mat-option{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;line-height:48px;height:48px;padding:0 16px;text-align:left;text-decoration:none;max-width:100%;position:relative;cursor:pointer;outline:none;display:flex;flex-direction:row;max-width:100%;box-sizing:border-box;align-items:center;-webkit-tap-highlight-color:transparent}.mat-option[disabled]{cursor:default}[dir=rtl] .mat-option{text-align:right}.mat-option .mat-icon{margin-right:16px;vertical-align:middle}.mat-option .mat-icon svg{vertical-align:top}[dir=rtl] .mat-option .mat-icon{margin-left:16px;margin-right:0}.mat-option[aria-disabled=true]{-webkit-user-select:none;-moz-user-select:none;user-select:none;cursor:default}.mat-optgroup .mat-option:not(.mat-option-multiple){padding-left:32px}[dir=rtl] .mat-optgroup .mat-option:not(.mat-option-multiple){padding-left:16px;padding-right:32px}.cdk-high-contrast-active .mat-option{margin:0 1px}.cdk-high-contrast-active .mat-option.mat-active{border:solid 1px currentColor;margin:0}.cdk-high-contrast-active .mat-option[aria-disabled=true]{opacity:.5}.mat-option-text{display:inline-block;flex-grow:1;overflow:hidden;text-overflow:ellipsis}.mat-option .mat-option-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-option-pseudo-checkbox{margin-right:8px}[dir=rtl] .mat-option-pseudo-checkbox{margin-left:8px;margin-right:0}\\n\"],encapsulation:2,changeDetection:0}),n})();function cg(n,t,e){if(e.length){let i=t.toArray(),r=e.toArray(),s=0;for(let o=0;o<n+1;o++)i[o].group&&i[o].group===r[s]&&s++;return s}return 0}let Hd=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ti,bt,B,og]]}),n})(),gE=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B],B]}),n})();const Xa=JSON.parse('[{\"from\":{\"name\":\"Everscale\",\"description\":\"Everscale mainnet\",\"url\":\"https://main.ton.dev\"},\"to\":{\"name\":\"Tezos\",\"description\":\"Tezos mainnet\",\"url\":\"https://tzkt.io\"},\"active\":true},{\"from\":{\"name\":\"Tezos\",\"description\":\"Tezos mainnet\",\"url\":\"https://tzkt.io\"},\"to\":{\"name\":\"Everscale\",\"description\":\"Everscale mainnet\",\"url\":\"https://main.ton.dev\"},\"active\":true},{\"from\":{\"name\":\"devnet\",\"description\":\"Everscale devnet\",\"url\":\"https://net.ton.dev\"},\"to\":{\"name\":\"hangzhounet\",\"description\":\"Tezos hangzhounet\",\"url\":\"https://hangzhounet.tzkt.io\"},\"active\":false},{\"from\":{\"name\":\"hangzhounet\",\"description\":\"Tezos hangzhounet\",\"url\":\"https://hangzhounet.tzkt.io\"},\"to\":{\"name\":\"devnet\",\"description\":\"Everscale devnet\",\"url\":\"https://net.ton.dev\"},\"active\":false},{\"from\":{\"name\":\"fld.ton.dev\",\"description\":\"Everscale fld\",\"url\":\"https://gql.custler.net\"},\"to\":{\"name\":\"ithacanet\",\"description\":\"Tezos ithacanet\",\"url\":\"https://ithacanet.tzkt.io\"},\"active\":false},{\"from\":{\"name\":\"ithacanet\",\"description\":\"Tezos ithacanet\",\"url\":\"https://ithacanet.tzkt.io\"},\"to\":{\"name\":\"fld.ton.dev\",\"description\":\"Everscale fld\",\"url\":\"https://gql.custler.net\"},\"active\":false}]'),ug=JSON.parse('[{\"name\":\"wTXZ\",\"type\":\"TIP-3.1\",\"desc\":\"Wrapped Tezos\"},{\"name\":\"SOON\",\"type\":\"TIP-3\",\"desc\":\"Soon\"},{\"name\":\"BRIDGE\",\"type\":\"TIP-3.1\",\"desc\":\"Bridge token\"}]'),hg=JSON.parse('[{\"name\":\"wEVER\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped EVER\"},{\"name\":\"KUSD\",\"type\":\"FA 1.2\",\"desc\":\"Kolibri\"},{\"name\":\"wXTZ\",\"type\":\"FA 1.2\",\"desc\":\"Wrapped Tezos\"},{\"name\":\"USDS\",\"type\":\"FA 2.0\",\"desc\":\"Stably USD\"},{\"name\":\"tzBTC\",\"type\":\"FA 1.2\",\"desc\":\"tzBTC\"},{\"name\":\"STKR\",\"type\":\"FA 1.2\",\"desc\":\"Staker Governance\"},{\"name\":\"USDtz\",\"type\":\"FA 1.2\",\"desc\":\"USDtez\"},{\"name\":\"ETHtz\",\"type\":\"FA 1.2\",\"desc\":\"ETHtez\"},{\"name\":\"hDAO\",\"type\":\"FA 2.0\",\"desc\":\"Hic Et Nunc governance\"},{\"name\":\"WRAP\",\"type\":\"FA 2.0\",\"desc\":\"Wrap Governance\"},{\"name\":\"CRUNCH\",\"type\":\"FA 2.0\",\"desc\":\"CRUNCH\"},{\"name\":\"wAAVE\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped AAVE\"},{\"name\":\"wBUSD\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped BUSD\"},{\"name\":\"wCEL\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped CEL\"},{\"name\":\"wCOMP\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped COMP\"},{\"name\":\"wCRO\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped CRO\"},{\"name\":\"wDAI\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped DAI\"},{\"name\":\"wFTT\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped FTT\"},{\"name\":\"wHT\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped HT\"},{\"name\":\"wHUSD\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped HUSD\"},{\"name\":\"wLEO\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped LEO\"},{\"name\":\"wLINK\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped LINK\"},{\"name\":\"wMATIC\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped MATIC\"},{\"name\":\"wMKR\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped MKR\"},{\"name\":\"wOKB\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped OKB\"},{\"name\":\"wPAX\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped PAX\"},{\"name\":\"wSUSHI\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped SUSHI\"},{\"name\":\"wUNI\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped UNI\"},{\"name\":\"wUSDC\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped USDC\"},{\"name\":\"wUSDT\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped USDT\"},{\"name\":\"wWBTC\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped WBTC\"},{\"name\":\"wWETH\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped WETH\"},{\"name\":\"PLENTY\",\"type\":\"FA 1.2\",\"desc\":\"Plenty DAO\"},{\"name\":\"KALAM\",\"type\":\"FA 2.0\",\"desc\":\"Kalamint\"},{\"name\":\"crDAO\",\"type\":\"FA 2.0\",\"desc\":\"Crunchy DAO\"},{\"name\":\"SMAK\",\"type\":\"FA 1.2\",\"desc\":\"SmartLink\"},{\"name\":\"kDAO\",\"type\":\"FA 1.2\",\"desc\":\"Kolibri DAO\"},{\"name\":\"uUSD\",\"type\":\"FA 2.0\",\"desc\":\"youves uUSD\"},{\"name\":\"uDEFI\",\"type\":\"FA 2.0\",\"desc\":\"youves uDEFI\"},{\"name\":\"bDAO\",\"type\":\"FA 2.0\",\"desc\":\"Bazaar DAO\"},{\"name\":\"YOU\",\"type\":\"FA 2.0\",\"desc\":\"youves YOU governance\"},{\"name\":\"RCKT\",\"type\":\"FA 2.0\",\"desc\":\"Rocket\"},{\"name\":\"rkDAO\",\"type\":\"FA 2.0\",\"desc\":\"Rocket DAO\"},{\"name\":\"UNO\",\"type\":\"FA 2.0\",\"desc\":\"Unobtanium\"},{\"name\":\"GIF\",\"type\":\"FA 2.0\",\"desc\":\"GIF DAO\"},{\"name\":\"IDZ\",\"type\":\"FA 2.0\",\"desc\":\"TezID\"},{\"name\":\"EASY\",\"type\":\"FA 2.0\",\"desc\":\"CryptoEasy\"},{\"name\":\"INSTA\",\"type\":\"FA 2.0\",\"desc\":\"Instaraise\"},{\"name\":\"xPLENTY\",\"type\":\"FA 1.2\",\"desc\":\"xPLENTY\"},{\"name\":\"ctez\",\"type\":\"FA 1.2\",\"desc\":\"Ctez\"},{\"name\":\"PAUL\",\"type\":\"FA 1.2\",\"desc\":\"PAUL Token\"},{\"name\":\"SPI\",\"type\":\"FA 2.0\",\"desc\":\"Spice Token\"},{\"name\":\"WTZ\",\"type\":\"FA 2.0\",\"desc\":\"WTZ\"},{\"name\":\"FLAME\",\"type\":\"FA 2.0\",\"desc\":\"FLAME\"},{\"name\":\"fDAO\",\"type\":\"FA 2.0\",\"desc\":\"fDAO\"},{\"name\":\"PXL\",\"type\":\"FA 2.0\",\"desc\":\"Pixel\"},{\"name\":\"sDAO\",\"type\":\"FA 2.0\",\"desc\":\"Salsa DAO\"},{\"name\":\"akaDAO\",\"type\":\"FA 2.0\",\"desc\":\"akaSwap DAO\"},{\"name\":\"MIN\",\"type\":\"FA 2.0\",\"desc\":\"Minerals\"},{\"name\":\"ENR\",\"type\":\"FA 2.0\",\"desc\":\"Energy\"},{\"name\":\"MCH\",\"type\":\"FA 2.0\",\"desc\":\"Machinery\"},{\"name\":\"uBTC\",\"type\":\"FA 2.0\",\"desc\":\"youves uBTC\"},{\"name\":\"MTRIA\",\"type\":\"FA 2.0\",\"desc\":\"Materia\"},{\"name\":\"DOGA\",\"type\":\"FA 1.2\",\"desc\":\"DOGAMI\"}]'),_E=[\"*\"];class pU{constructor(){this.columnIndex=0,this.rowIndex=0}get rowCount(){return this.rowIndex+1}get rowspan(){const t=Math.max(...this.tracker);return t>1?this.rowCount+t-1:this.rowCount}update(t,e){this.columnIndex=0,this.rowIndex=0,this.tracker=new Array(t),this.tracker.fill(0,0,this.tracker.length),this.positions=e.map(i=>this._trackTile(i))}_trackTile(t){const e=this._findMatchingGap(t.colspan);return this._markTilePosition(e,t),this.columnIndex=e+t.colspan,new fU(this.rowIndex,e)}_findMatchingGap(t){let e=-1,i=-1;do{this.columnIndex+t>this.tracker.length?(this._nextRow(),e=this.tracker.indexOf(0,this.columnIndex),i=this._findGapEndIndex(e)):(e=this.tracker.indexOf(0,this.columnIndex),-1!=e?(i=this._findGapEndIndex(e),this.columnIndex=e+1):(this._nextRow(),e=this.tracker.indexOf(0,this.columnIndex),i=this._findGapEndIndex(e)))}while(i-e<t||0==i);return Math.max(e,0)}_nextRow(){this.columnIndex=0,this.rowIndex++;for(let t=0;t<this.tracker.length;t++)this.tracker[t]=Math.max(0,this.tracker[t]-1)}_findGapEndIndex(t){for(let e=t+1;e<this.tracker.length;e++)if(0!=this.tracker[e])return e;return this.tracker.length}_markTilePosition(t,e){for(let i=0;i<e.colspan;i++)this.tracker[t+i]=e.rowspan}}class fU{constructor(t,e){this.row=t,this.col=e}}const vE=new b(\"MAT_GRID_LIST\");let yE=(()=>{class n{constructor(e,i){this._element=e,this._gridList=i,this._rowspan=1,this._colspan=1}get rowspan(){return this._rowspan}set rowspan(e){this._rowspan=Math.round(Et(e))}get colspan(){return this._colspan}set colspan(e){this._colspan=Math.round(Et(e))}_setStyle(e,i){this._element.nativeElement.style[e]=i}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(vE,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-grid-tile\"]],hostAttrs:[1,\"mat-grid-tile\"],hostVars:2,hostBindings:function(e,i){2&e&&Z(\"rowspan\",i.rowspan)(\"colspan\",i.colspan)},inputs:{rowspan:\"rowspan\",colspan:\"colspan\"},exportAs:[\"matGridTile\"],ngContentSelectors:_E,decls:2,vars:0,consts:[[1,\"mat-grid-tile-content\"]],template:function(e,i){1&e&&(Lt(),x(0,\"div\",0),Pe(1),S())},styles:[\".mat-grid-list{display:block;position:relative}.mat-grid-tile{display:block;position:absolute;overflow:hidden}.mat-grid-tile .mat-grid-tile-header,.mat-grid-tile .mat-grid-tile-footer{display:flex;align-items:center;height:48px;color:#fff;background:rgba(0,0,0,.38);overflow:hidden;padding:0 16px;position:absolute;left:0;right:0}.mat-grid-tile .mat-grid-tile-header>*,.mat-grid-tile .mat-grid-tile-footer>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-grid-tile .mat-grid-tile-header.mat-2-line,.mat-grid-tile .mat-grid-tile-footer.mat-2-line{height:68px}.mat-grid-tile .mat-grid-list-text{display:flex;flex-direction:column;flex:auto;box-sizing:border-box;overflow:hidden}.mat-grid-tile .mat-grid-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-grid-tile .mat-grid-list-text:empty{display:none}.mat-grid-tile .mat-grid-tile-header{top:0}.mat-grid-tile .mat-grid-tile-footer{bottom:0}.mat-grid-tile .mat-grid-avatar{padding-right:16px}[dir=rtl] .mat-grid-tile .mat-grid-avatar{padding-right:0;padding-left:16px}.mat-grid-tile .mat-grid-avatar:empty{display:none}.mat-grid-tile-content{top:0;left:0;right:0;bottom:0;position:absolute;display:flex;align-items:center;justify-content:center;height:100%;padding:0;margin:0}\\n\"],encapsulation:2,changeDetection:0}),n})();const mU=/^-?\\d+((\\.\\d+)?[A-Za-z%$]?)+$/;class pg{constructor(){this._rows=0,this._rowspan=0}init(t,e,i,r){this._gutterSize=bE(t),this._rows=e.rowCount,this._rowspan=e.rowspan,this._cols=i,this._direction=r}getBaseTileSize(t,e){return`(${t}% - (${this._gutterSize} * ${e}))`}getTilePosition(t,e){return 0===e?\"0\":Xr(`(${t} + ${this._gutterSize}) * ${e}`)}getTileSize(t,e){return`(${t} * ${e}) + (${e-1} * ${this._gutterSize})`}setStyle(t,e,i){let r=100/this._cols,s=(this._cols-1)/this._cols;this.setColStyles(t,i,r,s),this.setRowStyles(t,e,r,s)}setColStyles(t,e,i,r){let s=this.getBaseTileSize(i,r);t._setStyle(\"rtl\"===this._direction?\"right\":\"left\",this.getTilePosition(s,e)),t._setStyle(\"width\",Xr(this.getTileSize(s,t.colspan)))}getGutterSpan(){return`${this._gutterSize} * (${this._rowspan} - 1)`}getTileSpan(t){return`${this._rowspan} * ${this.getTileSize(t,1)}`}getComputedHeight(){return null}}class gU extends pg{constructor(t){super(),this.fixedRowHeight=t}init(t,e,i,r){super.init(t,e,i,r),this.fixedRowHeight=bE(this.fixedRowHeight),mU.test(this.fixedRowHeight)}setRowStyles(t,e){t._setStyle(\"top\",this.getTilePosition(this.fixedRowHeight,e)),t._setStyle(\"height\",Xr(this.getTileSize(this.fixedRowHeight,t.rowspan)))}getComputedHeight(){return[\"height\",Xr(`${this.getTileSpan(this.fixedRowHeight)} + ${this.getGutterSpan()}`)]}reset(t){t._setListStyle([\"height\",null]),t._tiles&&t._tiles.forEach(e=>{e._setStyle(\"top\",null),e._setStyle(\"height\",null)})}}class _U extends pg{constructor(t){super(),this._parseRatio(t)}setRowStyles(t,e,i,r){this.baseTileHeight=this.getBaseTileSize(i/this.rowHeightRatio,r),t._setStyle(\"marginTop\",this.getTilePosition(this.baseTileHeight,e)),t._setStyle(\"paddingTop\",Xr(this.getTileSize(this.baseTileHeight,t.rowspan)))}getComputedHeight(){return[\"paddingBottom\",Xr(`${this.getTileSpan(this.baseTileHeight)} + ${this.getGutterSpan()}`)]}reset(t){t._setListStyle([\"paddingBottom\",null]),t._tiles.forEach(e=>{e._setStyle(\"marginTop\",null),e._setStyle(\"paddingTop\",null)})}_parseRatio(t){const e=t.split(\":\");this.rowHeightRatio=parseFloat(e[0])/parseFloat(e[1])}}class vU extends pg{setRowStyles(t,e){let s=this.getBaseTileSize(100/this._rowspan,(this._rows-1)/this._rows);t._setStyle(\"top\",this.getTilePosition(s,e)),t._setStyle(\"height\",Xr(this.getTileSize(s,t.rowspan)))}reset(t){t._tiles&&t._tiles.forEach(e=>{e._setStyle(\"top\",null),e._setStyle(\"height\",null)})}}function Xr(n){return`calc(${n})`}function bE(n){return n.match(/([A-Za-z%]+)$/)?n:`${n}px`}let bU=(()=>{class n{constructor(e,i){this._element=e,this._dir=i,this._gutter=\"1px\"}get cols(){return this._cols}set cols(e){this._cols=Math.max(1,Math.round(Et(e)))}get gutterSize(){return this._gutter}set gutterSize(e){this._gutter=`${null==e?\"\":e}`}get rowHeight(){return this._rowHeight}set rowHeight(e){const i=`${null==e?\"\":e}`;i!==this._rowHeight&&(this._rowHeight=i,this._setTileStyler(this._rowHeight))}ngOnInit(){this._checkCols(),this._checkRowHeight()}ngAfterContentChecked(){this._layoutTiles()}_checkCols(){}_checkRowHeight(){this._rowHeight||this._setTileStyler(\"1:1\")}_setTileStyler(e){this._tileStyler&&this._tileStyler.reset(this),this._tileStyler=\"fit\"===e?new vU:e&&e.indexOf(\":\")>-1?new _U(e):new gU(e)}_layoutTiles(){this._tileCoordinator||(this._tileCoordinator=new pU);const e=this._tileCoordinator,i=this._tiles.filter(s=>!s._gridList||s._gridList===this),r=this._dir?this._dir.value:\"ltr\";this._tileCoordinator.update(this.cols,i),this._tileStyler.init(this.gutterSize,e,this.cols,r),i.forEach((s,o)=>{const a=e.positions[o];this._tileStyler.setStyle(s,a.row,a.col)}),this._setListStyle(this._tileStyler.getComputedHeight())}_setListStyle(e){e&&(this._element.nativeElement.style[e[0]]=e[1])}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(On,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-grid-list\"]],contentQueries:function(e,i,r){if(1&e&&ve(r,yE,5),2&e){let s;z(s=U())&&(i._tiles=s)}},hostAttrs:[1,\"mat-grid-list\"],hostVars:1,hostBindings:function(e,i){2&e&&Z(\"cols\",i.cols)},inputs:{cols:\"cols\",gutterSize:\"gutterSize\",rowHeight:\"rowHeight\"},exportAs:[\"matGridList\"],features:[L([{provide:vE,useExisting:n}])],ngContentSelectors:_E,decls:2,vars:0,template:function(e,i){1&e&&(Lt(),x(0,\"div\"),Pe(1),S())},styles:[\".mat-grid-list{display:block;position:relative}.mat-grid-tile{display:block;position:absolute;overflow:hidden}.mat-grid-tile .mat-grid-tile-header,.mat-grid-tile .mat-grid-tile-footer{display:flex;align-items:center;height:48px;color:#fff;background:rgba(0,0,0,.38);overflow:hidden;padding:0 16px;position:absolute;left:0;right:0}.mat-grid-tile .mat-grid-tile-header>*,.mat-grid-tile .mat-grid-tile-footer>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-grid-tile .mat-grid-tile-header.mat-2-line,.mat-grid-tile .mat-grid-tile-footer.mat-2-line{height:68px}.mat-grid-tile .mat-grid-list-text{display:flex;flex-direction:column;flex:auto;box-sizing:border-box;overflow:hidden}.mat-grid-tile .mat-grid-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-grid-tile .mat-grid-list-text:empty{display:none}.mat-grid-tile .mat-grid-tile-header{top:0}.mat-grid-tile .mat-grid-tile-footer{bottom:0}.mat-grid-tile .mat-grid-avatar{padding-right:16px}[dir=rtl] .mat-grid-tile .mat-grid-avatar{padding-right:0;padding-left:16px}.mat-grid-tile .mat-grid-avatar:empty{display:none}.mat-grid-tile-content{top:0;left:0;right:0;bottom:0;position:absolute;display:flex;align-items:center;justify-content:center;height:100%;padding:0;margin:0}\\n\"],encapsulation:2,changeDetection:0}),n})(),CU=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Vd,B],Vd,B]}),n})();const DU=[\"addListener\",\"removeListener\"],wU=[\"addEventListener\",\"removeEventListener\"],MU=[\"on\",\"off\"];function Jr(n,t,e,i){if(De(e)&&(i=e,e=void 0),i)return Jr(n,t,e).pipe(bf(i));const[r,s]=function SU(n){return De(n.addEventListener)&&De(n.removeEventListener)}(n)?wU.map(o=>a=>n[o](t,a,e)):function xU(n){return De(n.addListener)&&De(n.removeListener)}(n)?DU.map(CE(n,t)):function EU(n){return De(n.on)&&De(n.off)}(n)?MU.map(CE(n,t)):[];if(!r&&bu(n))return lt(o=>Jr(o,t,e))(Jt(n));if(!r)throw new TypeError(\"Invalid event target\");return new Ve(o=>{const a=(...l)=>o.next(1<l.length?l:l[0]);return r(a),()=>s(a)})}function CE(n,t){return e=>i=>n[e](t,i)}const kU=[\"connectionContainer\"],TU=[\"inputContainer\"],AU=[\"label\"];function IU(n,t){1&n&&(kr(0),x(1,\"div\",14),Le(2,\"div\",15)(3,\"div\",16)(4,\"div\",17),S(),x(5,\"div\",18),Le(6,\"div\",15)(7,\"div\",16)(8,\"div\",17),S(),Tr())}function RU(n,t){if(1&n){const e=ia();x(0,\"div\",19),J(\"cdkObserveContent\",function(){return Dr(e),Be().updateOutlineGap()}),Pe(1,1),S()}2&n&&N(\"cdkObserveContentDisabled\",\"outline\"!=Be().appearance)}function OU(n,t){if(1&n&&(kr(0),Pe(1,2),x(2,\"span\"),we(3),S(),Tr()),2&n){const e=Be(2);T(3),Ut(e._control.placeholder)}}function PU(n,t){1&n&&Pe(0,3,[\"*ngSwitchCase\",\"true\"])}function FU(n,t){1&n&&(x(0,\"span\",23),we(1,\" *\"),S())}function NU(n,t){if(1&n){const e=ia();x(0,\"label\",20,21),J(\"cdkObserveContent\",function(){return Dr(e),Be().updateOutlineGap()}),Ee(2,OU,4,1,\"ng-container\",12),Ee(3,PU,1,0,\"ng-content\",12),Ee(4,FU,2,0,\"span\",22),S()}if(2&n){const e=Be();Ae(\"mat-empty\",e._control.empty&&!e._shouldAlwaysFloat())(\"mat-form-field-empty\",e._control.empty&&!e._shouldAlwaysFloat())(\"mat-accent\",\"accent\"==e.color)(\"mat-warn\",\"warn\"==e.color),N(\"cdkObserveContentDisabled\",\"outline\"!=e.appearance)(\"id\",e._labelId)(\"ngSwitch\",e._hasLabel()),Z(\"for\",e._control.id)(\"aria-owns\",e._control.id),T(2),N(\"ngSwitchCase\",!1),T(1),N(\"ngSwitchCase\",!0),T(1),N(\"ngIf\",!e.hideRequiredMarker&&e._control.required&&!e._control.disabled)}}function LU(n,t){1&n&&(x(0,\"div\",24),Pe(1,4),S())}function BU(n,t){if(1&n&&(x(0,\"div\",25),Le(1,\"span\",26),S()),2&n){const e=Be();T(1),Ae(\"mat-accent\",\"accent\"==e.color)(\"mat-warn\",\"warn\"==e.color)}}function VU(n,t){1&n&&(x(0,\"div\"),Pe(1,5),S()),2&n&&N(\"@transitionMessages\",Be()._subscriptAnimationState)}function HU(n,t){if(1&n&&(x(0,\"div\",30),we(1),S()),2&n){const e=Be(2);N(\"id\",e._hintLabelId),T(1),Ut(e.hintLabel)}}function jU(n,t){if(1&n&&(x(0,\"div\",27),Ee(1,HU,2,2,\"div\",28),Pe(2,6),Le(3,\"div\",29),Pe(4,7),S()),2&n){const e=Be();N(\"@transitionMessages\",e._subscriptAnimationState),T(1),N(\"ngIf\",e.hintLabel)}}const zU=[\"*\",[[\"\",\"matPrefix\",\"\"]],[[\"mat-placeholder\"]],[[\"mat-label\"]],[[\"\",\"matSuffix\",\"\"]],[[\"mat-error\"]],[[\"mat-hint\",3,\"align\",\"end\"]],[[\"mat-hint\",\"align\",\"end\"]]],UU=[\"*\",\"[matPrefix]\",\"mat-placeholder\",\"mat-label\",\"[matSuffix]\",\"mat-error\",\"mat-hint:not([align='end'])\",\"mat-hint[align='end']\"];let $U=0;const DE=new b(\"MatError\");let GU=(()=>{class n{constructor(e,i){this.id=\"mat-error-\"+$U++,e||i.nativeElement.setAttribute(\"aria-live\",\"polite\")}}return n.\\u0275fac=function(e){return new(e||n)(kt(\"aria-live\"),f(W))},n.\\u0275dir=C({type:n,selectors:[[\"mat-error\"]],hostAttrs:[\"aria-atomic\",\"true\",1,\"mat-error\"],hostVars:1,hostBindings:function(e,i){2&e&&Z(\"id\",i.id)},inputs:{id:\"id\"},features:[L([{provide:DE,useExisting:n}])]}),n})();const WU={transitionMessages:Ke(\"transitionMessages\",[ae(\"enter\",R({opacity:1,transform:\"translateY(0%)\"})),ge(\"void => enter\",[R({opacity:0,transform:\"translateY(-5px)\"}),be(\"300ms cubic-bezier(0.55, 0, 0.55, 0.2)\")])])};let Ja=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n}),n})(),qU=0;const wE=new b(\"MatHint\");let YU=(()=>{class n{constructor(){this.align=\"start\",this.id=\"mat-hint-\"+qU++}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n,selectors:[[\"mat-hint\"]],hostAttrs:[1,\"mat-hint\"],hostVars:4,hostBindings:function(e,i){2&e&&(Z(\"id\",i.id)(\"align\",null),Ae(\"mat-form-field-hint-end\",\"end\"===i.align))},inputs:{align:\"align\",id:\"id\"},features:[L([{provide:wE,useExisting:n}])]}),n})(),fg=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n,selectors:[[\"mat-label\"]]}),n})(),QU=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n,selectors:[[\"mat-placeholder\"]]}),n})();const KU=new b(\"MatPrefix\"),ZU=new b(\"MatSuffix\");let ME=0;const JU=fo(class{constructor(n){this._elementRef=n}},\"primary\"),e5=new b(\"MAT_FORM_FIELD_DEFAULT_OPTIONS\"),el=new b(\"MatFormField\");let t5=(()=>{class n extends JU{constructor(e,i,r,s,o,a,l){super(e),this._changeDetectorRef=i,this._dir=r,this._defaults=s,this._platform=o,this._ngZone=a,this._outlineGapCalculationNeededImmediately=!1,this._outlineGapCalculationNeededOnStable=!1,this._destroyed=new O,this._showAlwaysAnimate=!1,this._subscriptAnimationState=\"\",this._hintLabel=\"\",this._hintLabelId=\"mat-hint-\"+ME++,this._labelId=\"mat-form-field-label-\"+ME++,this.floatLabel=this._getDefaultFloatLabelState(),this._animationsEnabled=\"NoopAnimations\"!==l,this.appearance=s&&s.appearance?s.appearance:\"legacy\",this._hideRequiredMarker=!(!s||null==s.hideRequiredMarker)&&s.hideRequiredMarker}get appearance(){return this._appearance}set appearance(e){const i=this._appearance;this._appearance=e||this._defaults&&this._defaults.appearance||\"legacy\",\"outline\"===this._appearance&&i!==e&&(this._outlineGapCalculationNeededOnStable=!0)}get hideRequiredMarker(){return this._hideRequiredMarker}set hideRequiredMarker(e){this._hideRequiredMarker=G(e)}_shouldAlwaysFloat(){return\"always\"===this.floatLabel&&!this._showAlwaysAnimate}_canLabelFloat(){return\"never\"!==this.floatLabel}get hintLabel(){return this._hintLabel}set hintLabel(e){this._hintLabel=e,this._processHints()}get floatLabel(){return\"legacy\"!==this.appearance&&\"never\"===this._floatLabel?\"auto\":this._floatLabel}set floatLabel(e){e!==this._floatLabel&&(this._floatLabel=e||this._getDefaultFloatLabelState(),this._changeDetectorRef.markForCheck())}get _control(){return this._explicitFormFieldControl||this._controlNonStatic||this._controlStatic}set _control(e){this._explicitFormFieldControl=e}getLabelId(){return this._hasFloatingLabel()?this._labelId:null}getConnectedOverlayOrigin(){return this._connectionContainerRef||this._elementRef}ngAfterContentInit(){this._validateControlChild();const e=this._control;e.controlType&&this._elementRef.nativeElement.classList.add(`mat-form-field-type-${e.controlType}`),e.stateChanges.pipe(Xn(null)).subscribe(()=>{this._validatePlaceholders(),this._syncDescribedByIds(),this._changeDetectorRef.markForCheck()}),e.ngControl&&e.ngControl.valueChanges&&e.ngControl.valueChanges.pipe(Ie(this._destroyed)).subscribe(()=>this._changeDetectorRef.markForCheck()),this._ngZone.runOutsideAngular(()=>{this._ngZone.onStable.pipe(Ie(this._destroyed)).subscribe(()=>{this._outlineGapCalculationNeededOnStable&&this.updateOutlineGap()})}),Bt(this._prefixChildren.changes,this._suffixChildren.changes).subscribe(()=>{this._outlineGapCalculationNeededOnStable=!0,this._changeDetectorRef.markForCheck()}),this._hintChildren.changes.pipe(Xn(null)).subscribe(()=>{this._processHints(),this._changeDetectorRef.markForCheck()}),this._errorChildren.changes.pipe(Xn(null)).subscribe(()=>{this._syncDescribedByIds(),this._changeDetectorRef.markForCheck()}),this._dir&&this._dir.change.pipe(Ie(this._destroyed)).subscribe(()=>{\"function\"==typeof requestAnimationFrame?this._ngZone.runOutsideAngular(()=>{requestAnimationFrame(()=>this.updateOutlineGap())}):this.updateOutlineGap()})}ngAfterContentChecked(){this._validateControlChild(),this._outlineGapCalculationNeededImmediately&&this.updateOutlineGap()}ngAfterViewInit(){this._subscriptAnimationState=\"enter\",this._changeDetectorRef.detectChanges()}ngOnDestroy(){this._destroyed.next(),this._destroyed.complete()}_shouldForward(e){const i=this._control?this._control.ngControl:null;return i&&i[e]}_hasPlaceholder(){return!!(this._control&&this._control.placeholder||this._placeholderChild)}_hasLabel(){return!(!this._labelChildNonStatic&&!this._labelChildStatic)}_shouldLabelFloat(){return this._canLabelFloat()&&(this._control&&this._control.shouldLabelFloat||this._shouldAlwaysFloat())}_hideControlPlaceholder(){return\"legacy\"===this.appearance&&!this._hasLabel()||this._hasLabel()&&!this._shouldLabelFloat()}_hasFloatingLabel(){return this._hasLabel()||\"legacy\"===this.appearance&&this._hasPlaceholder()}_getDisplayedMessages(){return this._errorChildren&&this._errorChildren.length>0&&this._control.errorState?\"error\":\"hint\"}_animateAndLockLabel(){this._hasFloatingLabel()&&this._canLabelFloat()&&(this._animationsEnabled&&this._label&&(this._showAlwaysAnimate=!0,Jr(this._label.nativeElement,\"transitionend\").pipe(it(1)).subscribe(()=>{this._showAlwaysAnimate=!1})),this.floatLabel=\"always\",this._changeDetectorRef.markForCheck())}_validatePlaceholders(){}_processHints(){this._validateHints(),this._syncDescribedByIds()}_validateHints(){}_getDefaultFloatLabelState(){return this._defaults&&this._defaults.floatLabel||\"auto\"}_syncDescribedByIds(){if(this._control){let e=[];if(this._control.userAriaDescribedBy&&\"string\"==typeof this._control.userAriaDescribedBy&&e.push(...this._control.userAriaDescribedBy.split(\" \")),\"hint\"===this._getDisplayedMessages()){const i=this._hintChildren?this._hintChildren.find(s=>\"start\"===s.align):null,r=this._hintChildren?this._hintChildren.find(s=>\"end\"===s.align):null;i?e.push(i.id):this._hintLabel&&e.push(this._hintLabelId),r&&e.push(r.id)}else this._errorChildren&&e.push(...this._errorChildren.map(i=>i.id));this._control.setDescribedByIds(e)}}_validateControlChild(){}updateOutlineGap(){const e=this._label?this._label.nativeElement:null,i=this._connectionContainerRef.nativeElement,r=\".mat-form-field-outline-start\",s=\".mat-form-field-outline-gap\";if(\"outline\"!==this.appearance||!this._platform.isBrowser)return;if(!e||!e.children.length||!e.textContent.trim()){const d=i.querySelectorAll(`${r}, ${s}`);for(let u=0;u<d.length;u++)d[u].style.width=\"0\";return}if(!this._isAttachedToDOM())return void(this._outlineGapCalculationNeededImmediately=!0);let o=0,a=0;const l=i.querySelectorAll(r),c=i.querySelectorAll(s);if(this._label&&this._label.nativeElement.children.length){const d=i.getBoundingClientRect();if(0===d.width&&0===d.height)return this._outlineGapCalculationNeededOnStable=!0,void(this._outlineGapCalculationNeededImmediately=!1);const u=this._getStartEnd(d),h=e.children,p=this._getStartEnd(h[0].getBoundingClientRect());let m=0;for(let g=0;g<h.length;g++)m+=h[g].offsetWidth;o=Math.abs(p-u)-5,a=m>0?.75*m+10:0}for(let d=0;d<l.length;d++)l[d].style.width=`${o}px`;for(let d=0;d<c.length;d++)c[d].style.width=`${a}px`;this._outlineGapCalculationNeededOnStable=this._outlineGapCalculationNeededImmediately=!1}_getStartEnd(e){return this._dir&&\"rtl\"===this._dir.value?e.right:e.left}_isAttachedToDOM(){const e=this._elementRef.nativeElement;if(e.getRootNode){const i=e.getRootNode();return i&&i!==e}return document.documentElement.contains(e)}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(Ye),f(On,8),f(e5,8),f(It),f(ne),f(Rn,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-form-field\"]],contentQueries:function(e,i,r){if(1&e&&(ve(r,Ja,5),ve(r,Ja,7),ve(r,fg,5),ve(r,fg,7),ve(r,QU,5),ve(r,DE,5),ve(r,wE,5),ve(r,KU,5),ve(r,ZU,5)),2&e){let s;z(s=U())&&(i._controlNonStatic=s.first),z(s=U())&&(i._controlStatic=s.first),z(s=U())&&(i._labelChildNonStatic=s.first),z(s=U())&&(i._labelChildStatic=s.first),z(s=U())&&(i._placeholderChild=s.first),z(s=U())&&(i._errorChildren=s),z(s=U())&&(i._hintChildren=s),z(s=U())&&(i._prefixChildren=s),z(s=U())&&(i._suffixChildren=s)}},viewQuery:function(e,i){if(1&e&&(je(kU,7),je(TU,5),je(AU,5)),2&e){let r;z(r=U())&&(i._connectionContainerRef=r.first),z(r=U())&&(i._inputContainerRef=r.first),z(r=U())&&(i._label=r.first)}},hostAttrs:[1,\"mat-form-field\"],hostVars:40,hostBindings:function(e,i){2&e&&Ae(\"mat-form-field-appearance-standard\",\"standard\"==i.appearance)(\"mat-form-field-appearance-fill\",\"fill\"==i.appearance)(\"mat-form-field-appearance-outline\",\"outline\"==i.appearance)(\"mat-form-field-appearance-legacy\",\"legacy\"==i.appearance)(\"mat-form-field-invalid\",i._control.errorState)(\"mat-form-field-can-float\",i._canLabelFloat())(\"mat-form-field-should-float\",i._shouldLabelFloat())(\"mat-form-field-has-label\",i._hasFloatingLabel())(\"mat-form-field-hide-placeholder\",i._hideControlPlaceholder())(\"mat-form-field-disabled\",i._control.disabled)(\"mat-form-field-autofilled\",i._control.autofilled)(\"mat-focused\",i._control.focused)(\"ng-untouched\",i._shouldForward(\"untouched\"))(\"ng-touched\",i._shouldForward(\"touched\"))(\"ng-pristine\",i._shouldForward(\"pristine\"))(\"ng-dirty\",i._shouldForward(\"dirty\"))(\"ng-valid\",i._shouldForward(\"valid\"))(\"ng-invalid\",i._shouldForward(\"invalid\"))(\"ng-pending\",i._shouldForward(\"pending\"))(\"_mat-animation-noopable\",!i._animationsEnabled)},inputs:{color:\"color\",appearance:\"appearance\",hideRequiredMarker:\"hideRequiredMarker\",hintLabel:\"hintLabel\",floatLabel:\"floatLabel\"},exportAs:[\"matFormField\"],features:[L([{provide:el,useExisting:n}]),E],ngContentSelectors:UU,decls:15,vars:8,consts:[[1,\"mat-form-field-wrapper\"],[1,\"mat-form-field-flex\",3,\"click\"],[\"connectionContainer\",\"\"],[4,\"ngIf\"],[\"class\",\"mat-form-field-prefix\",3,\"cdkObserveContentDisabled\",\"cdkObserveContent\",4,\"ngIf\"],[1,\"mat-form-field-infix\"],[\"inputContainer\",\"\"],[1,\"mat-form-field-label-wrapper\"],[\"class\",\"mat-form-field-label\",3,\"cdkObserveContentDisabled\",\"id\",\"mat-empty\",\"mat-form-field-empty\",\"mat-accent\",\"mat-warn\",\"ngSwitch\",\"cdkObserveContent\",4,\"ngIf\"],[\"class\",\"mat-form-field-suffix\",4,\"ngIf\"],[\"class\",\"mat-form-field-underline\",4,\"ngIf\"],[1,\"mat-form-field-subscript-wrapper\",3,\"ngSwitch\"],[4,\"ngSwitchCase\"],[\"class\",\"mat-form-field-hint-wrapper\",4,\"ngSwitchCase\"],[1,\"mat-form-field-outline\"],[1,\"mat-form-field-outline-start\"],[1,\"mat-form-field-outline-gap\"],[1,\"mat-form-field-outline-end\"],[1,\"mat-form-field-outline\",\"mat-form-field-outline-thick\"],[1,\"mat-form-field-prefix\",3,\"cdkObserveContentDisabled\",\"cdkObserveContent\"],[1,\"mat-form-field-label\",3,\"cdkObserveContentDisabled\",\"id\",\"ngSwitch\",\"cdkObserveContent\"],[\"label\",\"\"],[\"class\",\"mat-placeholder-required mat-form-field-required-marker\",\"aria-hidden\",\"true\",4,\"ngIf\"],[\"aria-hidden\",\"true\",1,\"mat-placeholder-required\",\"mat-form-field-required-marker\"],[1,\"mat-form-field-suffix\"],[1,\"mat-form-field-underline\"],[1,\"mat-form-field-ripple\"],[1,\"mat-form-field-hint-wrapper\"],[\"class\",\"mat-hint\",3,\"id\",4,\"ngIf\"],[1,\"mat-form-field-hint-spacer\"],[1,\"mat-hint\",3,\"id\"]],template:function(e,i){1&e&&(Lt(zU),x(0,\"div\",0)(1,\"div\",1,2),J(\"click\",function(s){return i._control.onContainerClick&&i._control.onContainerClick(s)}),Ee(3,IU,9,0,\"ng-container\",3),Ee(4,RU,2,1,\"div\",4),x(5,\"div\",5,6),Pe(7),x(8,\"span\",7),Ee(9,NU,5,16,\"label\",8),S()(),Ee(10,LU,2,0,\"div\",9),S(),Ee(11,BU,2,4,\"div\",10),x(12,\"div\",11),Ee(13,VU,2,1,\"div\",12),Ee(14,jU,5,2,\"div\",13),S()()),2&e&&(T(3),N(\"ngIf\",\"outline\"==i.appearance),T(1),N(\"ngIf\",i._prefixChildren.length),T(5),N(\"ngIf\",i._hasFloatingLabel()),T(1),N(\"ngIf\",i._suffixChildren.length),T(1),N(\"ngIf\",\"outline\"!=i.appearance),T(1),N(\"ngSwitch\",i._getDisplayedMessages()),T(1),N(\"ngSwitchCase\",\"error\"),T(1),N(\"ngSwitchCase\",\"hint\"))},directives:[Ca,Qm,Ys,Pc],styles:[\".mat-form-field{display:inline-block;position:relative;text-align:left}[dir=rtl] .mat-form-field{text-align:right}.mat-form-field-wrapper{position:relative}.mat-form-field-flex{display:inline-flex;align-items:baseline;box-sizing:border-box;width:100%}.mat-form-field-prefix,.mat-form-field-suffix{white-space:nowrap;flex:none;position:relative}.mat-form-field-infix{display:block;position:relative;flex:auto;min-width:0;width:180px}.cdk-high-contrast-active .mat-form-field-infix{border-image:linear-gradient(transparent, transparent)}.mat-form-field-label-wrapper{position:absolute;left:0;box-sizing:content-box;width:100%;height:100%;overflow:hidden;pointer-events:none}[dir=rtl] .mat-form-field-label-wrapper{left:auto;right:0}.mat-form-field-label{position:absolute;left:0;font:inherit;pointer-events:none;width:100%;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;transform-origin:0 0;transition:transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1),color 400ms cubic-bezier(0.25, 0.8, 0.25, 1),width 400ms cubic-bezier(0.25, 0.8, 0.25, 1);display:none}[dir=rtl] .mat-form-field-label{transform-origin:100% 0;left:auto;right:0}.cdk-high-contrast-active .mat-form-field-disabled .mat-form-field-label{color:GrayText}.mat-form-field-empty.mat-form-field-label,.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-label{display:block}.mat-form-field-autofill-control:-webkit-autofill+.mat-form-field-label-wrapper .mat-form-field-label{display:none}.mat-form-field-can-float .mat-form-field-autofill-control:-webkit-autofill+.mat-form-field-label-wrapper .mat-form-field-label{display:block;transition:none}.mat-input-server:focus+.mat-form-field-label-wrapper .mat-form-field-label,.mat-input-server[placeholder]:not(:placeholder-shown)+.mat-form-field-label-wrapper .mat-form-field-label{display:none}.mat-form-field-can-float .mat-input-server:focus+.mat-form-field-label-wrapper .mat-form-field-label,.mat-form-field-can-float .mat-input-server[placeholder]:not(:placeholder-shown)+.mat-form-field-label-wrapper .mat-form-field-label{display:block}.mat-form-field-label:not(.mat-form-field-empty){transition:none}.mat-form-field-underline{position:absolute;width:100%;pointer-events:none;transform:scale3d(1, 1.0001, 1)}.mat-form-field-ripple{position:absolute;left:0;width:100%;transform-origin:50%;transform:scaleX(0.5);opacity:0;transition:background-color 300ms cubic-bezier(0.55, 0, 0.55, 0.2)}.mat-form-field.mat-focused .mat-form-field-ripple,.mat-form-field.mat-form-field-invalid .mat-form-field-ripple{opacity:1;transform:none;transition:transform 300ms cubic-bezier(0.25, 0.8, 0.25, 1),opacity 100ms cubic-bezier(0.25, 0.8, 0.25, 1),background-color 300ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-subscript-wrapper{position:absolute;box-sizing:border-box;width:100%;overflow:hidden}.mat-form-field-subscript-wrapper .mat-icon,.mat-form-field-label-wrapper .mat-icon{width:1em;height:1em;font-size:inherit;vertical-align:baseline}.mat-form-field-hint-wrapper{display:flex}.mat-form-field-hint-spacer{flex:1 0 1em}.mat-error{display:block}.mat-form-field-control-wrapper{position:relative}.mat-form-field-hint-end{order:1}.mat-form-field._mat-animation-noopable .mat-form-field-label,.mat-form-field._mat-animation-noopable .mat-form-field-ripple{transition:none}\\n\",'.mat-form-field-appearance-fill .mat-form-field-flex{border-radius:4px 4px 0 0;padding:.75em .75em 0 .75em}.cdk-high-contrast-active .mat-form-field-appearance-fill .mat-form-field-flex{outline:solid 1px}.cdk-high-contrast-active .mat-form-field-appearance-fill.mat-form-field-disabled .mat-form-field-flex{outline-color:GrayText}.cdk-high-contrast-active .mat-form-field-appearance-fill.mat-focused .mat-form-field-flex{outline:dashed 3px}.mat-form-field-appearance-fill .mat-form-field-underline::before{content:\"\";display:block;position:absolute;bottom:0;height:1px;width:100%}.mat-form-field-appearance-fill .mat-form-field-ripple{bottom:0;height:2px}.cdk-high-contrast-active .mat-form-field-appearance-fill .mat-form-field-ripple{height:0}.mat-form-field-appearance-fill:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-underline .mat-form-field-ripple{opacity:1;transform:none;transition:opacity 600ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-appearance-fill._mat-animation-noopable:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-underline .mat-form-field-ripple{transition:none}.mat-form-field-appearance-fill .mat-form-field-subscript-wrapper{padding:0 1em}\\n','.mat-input-element{font:inherit;background:transparent;color:currentColor;border:none;outline:none;padding:0;margin:0;width:100%;max-width:100%;vertical-align:bottom;text-align:inherit;box-sizing:content-box}.mat-input-element:-moz-ui-invalid{box-shadow:none}.mat-input-element,.mat-input-element::-webkit-search-cancel-button,.mat-input-element::-webkit-search-decoration,.mat-input-element::-webkit-search-results-button,.mat-input-element::-webkit-search-results-decoration{-webkit-appearance:none}.mat-input-element::-webkit-contacts-auto-fill-button,.mat-input-element::-webkit-caps-lock-indicator,.mat-input-element:not([type=password])::-webkit-credentials-auto-fill-button{visibility:hidden}.mat-input-element[type=date],.mat-input-element[type=datetime],.mat-input-element[type=datetime-local],.mat-input-element[type=month],.mat-input-element[type=week],.mat-input-element[type=time]{line-height:1}.mat-input-element[type=date]::after,.mat-input-element[type=datetime]::after,.mat-input-element[type=datetime-local]::after,.mat-input-element[type=month]::after,.mat-input-element[type=week]::after,.mat-input-element[type=time]::after{content:\" \";white-space:pre;width:1px}.mat-input-element::-webkit-inner-spin-button,.mat-input-element::-webkit-calendar-picker-indicator,.mat-input-element::-webkit-clear-button{font-size:.75em}.mat-input-element::placeholder{-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-input-element::-moz-placeholder{-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-input-element::-webkit-input-placeholder{-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-input-element:-ms-input-placeholder{-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-hide-placeholder .mat-input-element::placeholder{color:transparent !important;-webkit-text-fill-color:transparent;transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-input-element::placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-input-element::-moz-placeholder{color:transparent !important;-webkit-text-fill-color:transparent;transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-input-element::-moz-placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-input-element::-webkit-input-placeholder{color:transparent !important;-webkit-text-fill-color:transparent;transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-input-element::-webkit-input-placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-input-element:-ms-input-placeholder{color:transparent !important;-webkit-text-fill-color:transparent;transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-input-element:-ms-input-placeholder{opacity:0}textarea.mat-input-element{resize:vertical;overflow:auto}textarea.mat-input-element.cdk-textarea-autosize{resize:none}textarea.mat-input-element{padding:2px 0;margin:-2px 0}select.mat-input-element{-moz-appearance:none;-webkit-appearance:none;position:relative;background-color:transparent;display:inline-flex;box-sizing:border-box;padding-top:1em;top:-1em;margin-bottom:-1em}select.mat-input-element::-moz-focus-inner{border:0}select.mat-input-element:not(:disabled){cursor:pointer}.mat-form-field-type-mat-native-select .mat-form-field-infix::after{content:\"\";width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;border-top:5px solid;position:absolute;top:50%;right:0;margin-top:-2.5px;pointer-events:none}[dir=rtl] .mat-form-field-type-mat-native-select .mat-form-field-infix::after{right:auto;left:0}.mat-form-field-type-mat-native-select .mat-input-element{padding-right:15px}[dir=rtl] .mat-form-field-type-mat-native-select .mat-input-element{padding-right:0;padding-left:15px}.mat-form-field-type-mat-native-select .mat-form-field-label-wrapper{max-width:calc(100% - 10px)}.mat-form-field-type-mat-native-select.mat-form-field-appearance-outline .mat-form-field-infix::after{margin-top:-5px}.mat-form-field-type-mat-native-select.mat-form-field-appearance-fill .mat-form-field-infix::after{margin-top:-10px}\\n',\".mat-form-field-appearance-legacy .mat-form-field-label{transform:perspective(100px)}.mat-form-field-appearance-legacy .mat-form-field-prefix .mat-icon,.mat-form-field-appearance-legacy .mat-form-field-suffix .mat-icon{width:1em}.mat-form-field-appearance-legacy .mat-form-field-prefix .mat-icon-button,.mat-form-field-appearance-legacy .mat-form-field-suffix .mat-icon-button{font:inherit;vertical-align:baseline}.mat-form-field-appearance-legacy .mat-form-field-prefix .mat-icon-button .mat-icon,.mat-form-field-appearance-legacy .mat-form-field-suffix .mat-icon-button .mat-icon{font-size:inherit}.mat-form-field-appearance-legacy .mat-form-field-underline{height:1px}.cdk-high-contrast-active .mat-form-field-appearance-legacy .mat-form-field-underline{height:0;border-top:solid 1px}.mat-form-field-appearance-legacy .mat-form-field-ripple{top:0;height:2px;overflow:hidden}.cdk-high-contrast-active .mat-form-field-appearance-legacy .mat-form-field-ripple{height:0;border-top:solid 2px}.mat-form-field-appearance-legacy.mat-form-field-disabled .mat-form-field-underline{background-position:0;background-color:transparent}.cdk-high-contrast-active .mat-form-field-appearance-legacy.mat-form-field-disabled .mat-form-field-underline{border-top-style:dotted;border-top-width:2px;border-top-color:GrayText}.mat-form-field-appearance-legacy.mat-form-field-invalid:not(.mat-focused) .mat-form-field-ripple{height:1px}\\n\",\".mat-form-field-appearance-outline .mat-form-field-wrapper{margin:.25em 0}.mat-form-field-appearance-outline .mat-form-field-flex{padding:0 .75em 0 .75em;margin-top:-0.25em;position:relative}.mat-form-field-appearance-outline .mat-form-field-prefix,.mat-form-field-appearance-outline .mat-form-field-suffix{top:.25em}.mat-form-field-appearance-outline .mat-form-field-outline{display:flex;position:absolute;top:.25em;left:0;right:0;bottom:0;pointer-events:none}.mat-form-field-appearance-outline .mat-form-field-outline-start,.mat-form-field-appearance-outline .mat-form-field-outline-end{border:1px solid currentColor;min-width:5px}.mat-form-field-appearance-outline .mat-form-field-outline-start{border-radius:5px 0 0 5px;border-right-style:none}[dir=rtl] .mat-form-field-appearance-outline .mat-form-field-outline-start{border-right-style:solid;border-left-style:none;border-radius:0 5px 5px 0}.mat-form-field-appearance-outline .mat-form-field-outline-end{border-radius:0 5px 5px 0;border-left-style:none;flex-grow:1}[dir=rtl] .mat-form-field-appearance-outline .mat-form-field-outline-end{border-left-style:solid;border-right-style:none;border-radius:5px 0 0 5px}.mat-form-field-appearance-outline .mat-form-field-outline-gap{border-radius:.000001px;border:1px solid currentColor;border-left-style:none;border-right-style:none}.mat-form-field-appearance-outline.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-outline-gap{border-top-color:transparent}.mat-form-field-appearance-outline .mat-form-field-outline-thick{opacity:0}.mat-form-field-appearance-outline .mat-form-field-outline-thick .mat-form-field-outline-start,.mat-form-field-appearance-outline .mat-form-field-outline-thick .mat-form-field-outline-end,.mat-form-field-appearance-outline .mat-form-field-outline-thick .mat-form-field-outline-gap{border-width:2px}.mat-form-field-appearance-outline.mat-focused .mat-form-field-outline,.mat-form-field-appearance-outline.mat-form-field-invalid .mat-form-field-outline{opacity:0;transition:opacity 100ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-appearance-outline.mat-focused .mat-form-field-outline-thick,.mat-form-field-appearance-outline.mat-form-field-invalid .mat-form-field-outline-thick{opacity:1}.cdk-high-contrast-active .mat-form-field-appearance-outline.mat-focused .mat-form-field-outline-thick{border:3px dashed}.mat-form-field-appearance-outline:not(.mat-form-field-disabled) .mat-form-field-flex:hover .mat-form-field-outline{opacity:0;transition:opacity 600ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-appearance-outline:not(.mat-form-field-disabled) .mat-form-field-flex:hover .mat-form-field-outline-thick{opacity:1}.mat-form-field-appearance-outline .mat-form-field-subscript-wrapper{padding:0 1em}.cdk-high-contrast-active .mat-form-field-appearance-outline.mat-form-field-disabled .mat-form-field-outline{color:GrayText}.mat-form-field-appearance-outline._mat-animation-noopable:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-outline,.mat-form-field-appearance-outline._mat-animation-noopable .mat-form-field-outline,.mat-form-field-appearance-outline._mat-animation-noopable .mat-form-field-outline-start,.mat-form-field-appearance-outline._mat-animation-noopable .mat-form-field-outline-end,.mat-form-field-appearance-outline._mat-animation-noopable .mat-form-field-outline-gap{transition:none}\\n\",\".mat-form-field-appearance-standard .mat-form-field-flex{padding-top:.75em}.mat-form-field-appearance-standard .mat-form-field-underline{height:1px}.cdk-high-contrast-active .mat-form-field-appearance-standard .mat-form-field-underline{height:0;border-top:solid 1px}.mat-form-field-appearance-standard .mat-form-field-ripple{bottom:0;height:2px}.cdk-high-contrast-active .mat-form-field-appearance-standard .mat-form-field-ripple{height:0;border-top:solid 2px}.mat-form-field-appearance-standard.mat-form-field-disabled .mat-form-field-underline{background-position:0;background-color:transparent}.cdk-high-contrast-active .mat-form-field-appearance-standard.mat-form-field-disabled .mat-form-field-underline{border-top-style:dotted;border-top-width:2px}.mat-form-field-appearance-standard:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-underline .mat-form-field-ripple{opacity:1;transform:none;transition:opacity 600ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-appearance-standard._mat-animation-noopable:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-underline .mat-form-field-ripple{transition:none}\\n\"],encapsulation:2,data:{animation:[WU.transitionMessages]},changeDetection:0}),n})(),mg=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B,Ya],B]}),n})();const tl={schedule(n){let t=requestAnimationFrame,e=cancelAnimationFrame;const{delegate:i}=tl;i&&(t=i.requestAnimationFrame,e=i.cancelAnimationFrame);const r=t(s=>{e=void 0,n(s)});return new ke(()=>null==e?void 0:e(r))},requestAnimationFrame(...n){const{delegate:t}=tl;return((null==t?void 0:t.requestAnimationFrame)||requestAnimationFrame)(...n)},cancelAnimationFrame(...n){const{delegate:t}=tl;return((null==t?void 0:t.cancelAnimationFrame)||cancelAnimationFrame)(...n)},delegate:void 0},EE=new class r5 extends Ym{flush(t){this._active=!0;const e=this._scheduled;this._scheduled=void 0;const{actions:i}=this;let r;t=t||i.shift();do{if(r=t.execute(t.state,t.delay))break}while((t=i[0])&&t.id===e&&i.shift());if(this._active=!1,r){for(;(t=i[0])&&t.id===e&&i.shift();)t.unsubscribe();throw r}}}(class n5 extends qm{constructor(t,e){super(t,e),this.scheduler=t,this.work=e}requestAsyncId(t,e,i=0){return null!==i&&i>0?super.requestAsyncId(t,e,i):(t.actions.push(this),t._scheduled||(t._scheduled=tl.requestAnimationFrame(()=>t.flush(void 0))))}recycleAsyncId(t,e,i=0){if(null!=i&&i>0||null==i&&this.delay>0)return super.recycleAsyncId(t,e,i);t.actions.some(r=>r.id===e)||(tl.cancelAnimationFrame(e),t._scheduled=void 0)}});let gg,s5=1;const jd={};function SE(n){return n in jd&&(delete jd[n],!0)}const o5={setImmediate(n){const t=s5++;return jd[t]=!0,gg||(gg=Promise.resolve()),gg.then(()=>SE(t)&&n()),t},clearImmediate(n){SE(n)}},{setImmediate:a5,clearImmediate:l5}=o5,zd={setImmediate(...n){const{delegate:t}=zd;return((null==t?void 0:t.setImmediate)||a5)(...n)},clearImmediate(n){const{delegate:t}=zd;return((null==t?void 0:t.clearImmediate)||l5)(n)},delegate:void 0};new class d5 extends Ym{flush(t){this._active=!0;const e=this._scheduled;this._scheduled=void 0;const{actions:i}=this;let r;t=t||i.shift();do{if(r=t.execute(t.state,t.delay))break}while((t=i[0])&&t.id===e&&i.shift());if(this._active=!1,r){for(;(t=i[0])&&t.id===e&&i.shift();)t.unsubscribe();throw r}}}(class c5 extends qm{constructor(t,e){super(t,e),this.scheduler=t,this.work=e}requestAsyncId(t,e,i=0){return null!==i&&i>0?super.requestAsyncId(t,e,i):(t.actions.push(this),t._scheduled||(t._scheduled=zd.setImmediate(t.flush.bind(t,void 0))))}recycleAsyncId(t,e,i=0){if(null!=i&&i>0||null==i&&this.delay>0)return super.recycleAsyncId(t,e,i);t.actions.some(r=>r.id===e)||(zd.clearImmediate(e),t._scheduled=void 0)}});function _g(n=0,t,e=t3){let i=-1;return null!=t&&(y_(t)?e=t:i=t),new Ve(r=>{let s=function p5(n){return n instanceof Date&&!isNaN(n)}(n)?+n-e.now():n;s<0&&(s=0);let o=0;return e.schedule(function(){r.closed||(r.next(o++),0<=i?this.schedule(void 0,i):r.complete())},s)})}function kE(n,t=qa){return function h5(n){return qe((t,e)=>{let i=!1,r=null,s=null,o=!1;const a=()=>{if(null==s||s.unsubscribe(),s=null,i){i=!1;const c=r;r=null,e.next(c)}o&&e.complete()},l=()=>{s=null,o&&e.complete()};t.subscribe(Ue(e,c=>{i=!0,r=c,s||Jt(n(c)).subscribe(s=Ue(e,a,l))},()=>{o=!0,(!i||!s||s.closed)&&e.complete()}))})}(()=>_g(n,t))}let m5=(()=>{class n{constructor(e,i,r){this._ngZone=e,this._platform=i,this._scrolled=new O,this._globalSubscription=null,this._scrolledCount=0,this.scrollContainers=new Map,this._document=r}register(e){this.scrollContainers.has(e)||this.scrollContainers.set(e,e.elementScrolled().subscribe(()=>this._scrolled.next(e)))}deregister(e){const i=this.scrollContainers.get(e);i&&(i.unsubscribe(),this.scrollContainers.delete(e))}scrolled(e=20){return this._platform.isBrowser?new Ve(i=>{this._globalSubscription||this._addGlobalListener();const r=e>0?this._scrolled.pipe(kE(e)).subscribe(i):this._scrolled.subscribe(i);return this._scrolledCount++,()=>{r.unsubscribe(),this._scrolledCount--,this._scrolledCount||this._removeGlobalListener()}}):q()}ngOnDestroy(){this._removeGlobalListener(),this.scrollContainers.forEach((e,i)=>this.deregister(i)),this._scrolled.complete()}ancestorScrolled(e,i){const r=this.getAncestorScrollContainers(e);return this.scrolled(i).pipe(Ct(s=>!s||r.indexOf(s)>-1))}getAncestorScrollContainers(e){const i=[];return this.scrollContainers.forEach((r,s)=>{this._scrollableContainsElement(s,e)&&i.push(s)}),i}_getWindow(){return this._document.defaultView||window}_scrollableContainsElement(e,i){let r=at(i),s=e.getElementRef().nativeElement;do{if(r==s)return!0}while(r=r.parentElement);return!1}_addGlobalListener(){this._globalSubscription=this._ngZone.runOutsideAngular(()=>Jr(this._getWindow().document,\"scroll\").subscribe(()=>this._scrolled.next()))}_removeGlobalListener(){this._globalSubscription&&(this._globalSubscription.unsubscribe(),this._globalSubscription=null)}}return n.\\u0275fac=function(e){return new(e||n)(y(ne),y(It),y(ie,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),es=(()=>{class n{constructor(e,i,r){this._platform=e,this._change=new O,this._changeListener=s=>{this._change.next(s)},this._document=r,i.runOutsideAngular(()=>{if(e.isBrowser){const s=this._getWindow();s.addEventListener(\"resize\",this._changeListener),s.addEventListener(\"orientationchange\",this._changeListener)}this.change().subscribe(()=>this._viewportSize=null)})}ngOnDestroy(){if(this._platform.isBrowser){const e=this._getWindow();e.removeEventListener(\"resize\",this._changeListener),e.removeEventListener(\"orientationchange\",this._changeListener)}this._change.complete()}getViewportSize(){this._viewportSize||this._updateViewportSize();const e={width:this._viewportSize.width,height:this._viewportSize.height};return this._platform.isBrowser||(this._viewportSize=null),e}getViewportRect(){const e=this.getViewportScrollPosition(),{width:i,height:r}=this.getViewportSize();return{top:e.top,left:e.left,bottom:e.top+r,right:e.left+i,height:r,width:i}}getViewportScrollPosition(){if(!this._platform.isBrowser)return{top:0,left:0};const e=this._document,i=this._getWindow(),r=e.documentElement,s=r.getBoundingClientRect();return{top:-s.top||e.body.scrollTop||i.scrollY||r.scrollTop||0,left:-s.left||e.body.scrollLeft||i.scrollX||r.scrollLeft||0}}change(e=20){return e>0?this._change.pipe(kE(e)):this._change}_getWindow(){return this._document.defaultView||window}_updateViewportSize(){const e=this._getWindow();this._viewportSize=this._platform.isBrowser?{width:e.innerWidth,height:e.innerHeight}:{width:0,height:0}}}return n.\\u0275fac=function(e){return new(e||n)(y(It),y(ne),y(ie,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),Ci=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),Ud=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[lo,Ci],lo,Ci]}),n})();class vg{attach(t){return this._attachedHost=t,t.attach(this)}detach(){let t=this._attachedHost;null!=t&&(this._attachedHost=null,t.detach())}get isAttached(){return null!=this._attachedHost}setAttachedHost(t){this._attachedHost=t}}class yg extends vg{constructor(t,e,i,r){super(),this.component=t,this.viewContainerRef=e,this.injector=i,this.componentFactoryResolver=r}}class $d extends vg{constructor(t,e,i){super(),this.templateRef=t,this.viewContainerRef=e,this.context=i}get origin(){return this.templateRef.elementRef}attach(t,e=this.context){return this.context=e,super.attach(t)}detach(){return this.context=void 0,super.detach()}}class _5 extends vg{constructor(t){super(),this.element=t instanceof W?t.nativeElement:t}}class bg{constructor(){this._isDisposed=!1,this.attachDomPortal=null}hasAttached(){return!!this._attachedPortal}attach(t){return t instanceof yg?(this._attachedPortal=t,this.attachComponentPortal(t)):t instanceof $d?(this._attachedPortal=t,this.attachTemplatePortal(t)):this.attachDomPortal&&t instanceof _5?(this._attachedPortal=t,this.attachDomPortal(t)):void 0}detach(){this._attachedPortal&&(this._attachedPortal.setAttachedHost(null),this._attachedPortal=null),this._invokeDisposeFn()}dispose(){this.hasAttached()&&this.detach(),this._invokeDisposeFn(),this._isDisposed=!0}setDisposeFn(t){this._disposeFn=t}_invokeDisposeFn(){this._disposeFn&&(this._disposeFn(),this._disposeFn=null)}}class v5 extends bg{constructor(t,e,i,r,s){super(),this.outletElement=t,this._componentFactoryResolver=e,this._appRef=i,this._defaultInjector=r,this.attachDomPortal=o=>{const a=o.element,l=this._document.createComment(\"dom-portal\");a.parentNode.insertBefore(l,a),this.outletElement.appendChild(a),this._attachedPortal=o,super.setDisposeFn(()=>{l.parentNode&&l.parentNode.replaceChild(a,l)})},this._document=s}attachComponentPortal(t){const i=(t.componentFactoryResolver||this._componentFactoryResolver).resolveComponentFactory(t.component);let r;return t.viewContainerRef?(r=t.viewContainerRef.createComponent(i,t.viewContainerRef.length,t.injector||t.viewContainerRef.injector),this.setDisposeFn(()=>r.destroy())):(r=i.create(t.injector||this._defaultInjector),this._appRef.attachView(r.hostView),this.setDisposeFn(()=>{this._appRef.detachView(r.hostView),r.destroy()})),this.outletElement.appendChild(this._getComponentRootNode(r)),this._attachedPortal=t,r}attachTemplatePortal(t){let e=t.viewContainerRef,i=e.createEmbeddedView(t.templateRef,t.context);return i.rootNodes.forEach(r=>this.outletElement.appendChild(r)),i.detectChanges(),this.setDisposeFn(()=>{let r=e.indexOf(i);-1!==r&&e.remove(r)}),this._attachedPortal=t,i}dispose(){super.dispose(),this.outletElement.remove()}_getComponentRootNode(t){return t.hostView.rootNodes[0]}}let TE=(()=>{class n extends bg{constructor(e,i,r){super(),this._componentFactoryResolver=e,this._viewContainerRef=i,this._isInitialized=!1,this.attached=new $,this.attachDomPortal=s=>{const o=s.element,a=this._document.createComment(\"dom-portal\");s.setAttachedHost(this),o.parentNode.insertBefore(a,o),this._getRootNode().appendChild(o),this._attachedPortal=s,super.setDisposeFn(()=>{a.parentNode&&a.parentNode.replaceChild(o,a)})},this._document=r}get portal(){return this._attachedPortal}set portal(e){this.hasAttached()&&!e&&!this._isInitialized||(this.hasAttached()&&super.detach(),e&&super.attach(e),this._attachedPortal=e||null)}get attachedRef(){return this._attachedRef}ngOnInit(){this._isInitialized=!0}ngOnDestroy(){super.dispose(),this._attachedPortal=null,this._attachedRef=null}attachComponentPortal(e){e.setAttachedHost(this);const i=null!=e.viewContainerRef?e.viewContainerRef:this._viewContainerRef,s=(e.componentFactoryResolver||this._componentFactoryResolver).resolveComponentFactory(e.component),o=i.createComponent(s,i.length,e.injector||i.injector);return i!==this._viewContainerRef&&this._getRootNode().appendChild(o.hostView.rootNodes[0]),super.setDisposeFn(()=>o.destroy()),this._attachedPortal=e,this._attachedRef=o,this.attached.emit(o),o}attachTemplatePortal(e){e.setAttachedHost(this);const i=this._viewContainerRef.createEmbeddedView(e.templateRef,e.context);return super.setDisposeFn(()=>this._viewContainerRef.clear()),this._attachedPortal=e,this._attachedRef=i,this.attached.emit(i),i}_getRootNode(){const e=this._viewContainerRef.element.nativeElement;return e.nodeType===e.ELEMENT_NODE?e:e.parentNode}}return n.\\u0275fac=function(e){return new(e||n)(f(Ir),f(st),f(ie))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"cdkPortalOutlet\",\"\"]],inputs:{portal:[\"cdkPortalOutlet\",\"portal\"]},outputs:{attached:\"attached\"},exportAs:[\"cdkPortalOutlet\"],features:[E]}),n})(),Hi=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const AE=jz();class b5{constructor(t,e){this._viewportRuler=t,this._previousHTMLStyles={top:\"\",left:\"\"},this._isEnabled=!1,this._document=e}attach(){}enable(){if(this._canBeEnabled()){const t=this._document.documentElement;this._previousScrollPosition=this._viewportRuler.getViewportScrollPosition(),this._previousHTMLStyles.left=t.style.left||\"\",this._previousHTMLStyles.top=t.style.top||\"\",t.style.left=ft(-this._previousScrollPosition.left),t.style.top=ft(-this._previousScrollPosition.top),t.classList.add(\"cdk-global-scrollblock\"),this._isEnabled=!0}}disable(){if(this._isEnabled){const t=this._document.documentElement,i=t.style,r=this._document.body.style,s=i.scrollBehavior||\"\",o=r.scrollBehavior||\"\";this._isEnabled=!1,i.left=this._previousHTMLStyles.left,i.top=this._previousHTMLStyles.top,t.classList.remove(\"cdk-global-scrollblock\"),AE&&(i.scrollBehavior=r.scrollBehavior=\"auto\"),window.scroll(this._previousScrollPosition.left,this._previousScrollPosition.top),AE&&(i.scrollBehavior=s,r.scrollBehavior=o)}}_canBeEnabled(){if(this._document.documentElement.classList.contains(\"cdk-global-scrollblock\")||this._isEnabled)return!1;const e=this._document.body,i=this._viewportRuler.getViewportSize();return e.scrollHeight>i.height||e.scrollWidth>i.width}}class C5{constructor(t,e,i,r){this._scrollDispatcher=t,this._ngZone=e,this._viewportRuler=i,this._config=r,this._scrollSubscription=null,this._detach=()=>{this.disable(),this._overlayRef.hasAttached()&&this._ngZone.run(()=>this._overlayRef.detach())}}attach(t){this._overlayRef=t}enable(){if(this._scrollSubscription)return;const t=this._scrollDispatcher.scrolled(0);this._config&&this._config.threshold&&this._config.threshold>1?(this._initialScrollPosition=this._viewportRuler.getViewportScrollPosition().top,this._scrollSubscription=t.subscribe(()=>{const e=this._viewportRuler.getViewportScrollPosition().top;Math.abs(e-this._initialScrollPosition)>this._config.threshold?this._detach():this._overlayRef.updatePosition()})):this._scrollSubscription=t.subscribe(this._detach)}disable(){this._scrollSubscription&&(this._scrollSubscription.unsubscribe(),this._scrollSubscription=null)}detach(){this.disable(),this._overlayRef=null}}class IE{enable(){}disable(){}attach(){}}function Cg(n,t){return t.some(e=>n.bottom<e.top||n.top>e.bottom||n.right<e.left||n.left>e.right)}function RE(n,t){return t.some(e=>n.top<e.top||n.bottom>e.bottom||n.left<e.left||n.right>e.right)}class D5{constructor(t,e,i,r){this._scrollDispatcher=t,this._viewportRuler=e,this._ngZone=i,this._config=r,this._scrollSubscription=null}attach(t){this._overlayRef=t}enable(){this._scrollSubscription||(this._scrollSubscription=this._scrollDispatcher.scrolled(this._config?this._config.scrollThrottle:0).subscribe(()=>{if(this._overlayRef.updatePosition(),this._config&&this._config.autoClose){const e=this._overlayRef.overlayElement.getBoundingClientRect(),{width:i,height:r}=this._viewportRuler.getViewportSize();Cg(e,[{width:i,height:r,bottom:r,right:i,top:0,left:0}])&&(this.disable(),this._ngZone.run(()=>this._overlayRef.detach()))}}))}disable(){this._scrollSubscription&&(this._scrollSubscription.unsubscribe(),this._scrollSubscription=null)}detach(){this.disable(),this._overlayRef=null}}let w5=(()=>{class n{constructor(e,i,r,s){this._scrollDispatcher=e,this._viewportRuler=i,this._ngZone=r,this.noop=()=>new IE,this.close=o=>new C5(this._scrollDispatcher,this._ngZone,this._viewportRuler,o),this.block=()=>new b5(this._viewportRuler,this._document),this.reposition=o=>new D5(this._scrollDispatcher,this._viewportRuler,this._ngZone,o),this._document=s}}return n.\\u0275fac=function(e){return new(e||n)(y(m5),y(es),y(ne),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();class Gd{constructor(t){if(this.scrollStrategy=new IE,this.panelClass=\"\",this.hasBackdrop=!1,this.backdropClass=\"cdk-overlay-dark-backdrop\",this.disposeOnNavigation=!1,t){const e=Object.keys(t);for(const i of e)void 0!==t[i]&&(this[i]=t[i])}}}class M5{constructor(t,e){this.connectionPair=t,this.scrollableViewProperties=e}}class x5{constructor(t,e,i,r,s,o,a,l,c){this._portalOutlet=t,this._host=e,this._pane=i,this._config=r,this._ngZone=s,this._keyboardDispatcher=o,this._document=a,this._location=l,this._outsideClickDispatcher=c,this._backdropElement=null,this._backdropClick=new O,this._attachments=new O,this._detachments=new O,this._locationChanges=ke.EMPTY,this._backdropClickHandler=d=>this._backdropClick.next(d),this._backdropTransitionendHandler=d=>{this._disposeBackdrop(d.target)},this._keydownEvents=new O,this._outsidePointerEvents=new O,r.scrollStrategy&&(this._scrollStrategy=r.scrollStrategy,this._scrollStrategy.attach(this)),this._positionStrategy=r.positionStrategy}get overlayElement(){return this._pane}get backdropElement(){return this._backdropElement}get hostElement(){return this._host}attach(t){let e=this._portalOutlet.attach(t);return!this._host.parentElement&&this._previousHostParent&&this._previousHostParent.appendChild(this._host),this._positionStrategy&&this._positionStrategy.attach(this),this._updateStackingOrder(),this._updateElementSize(),this._updateElementDirection(),this._scrollStrategy&&this._scrollStrategy.enable(),this._ngZone.onStable.pipe(it(1)).subscribe(()=>{this.hasAttached()&&this.updatePosition()}),this._togglePointerEvents(!0),this._config.hasBackdrop&&this._attachBackdrop(),this._config.panelClass&&this._toggleClasses(this._pane,this._config.panelClass,!0),this._attachments.next(),this._keyboardDispatcher.add(this),this._config.disposeOnNavigation&&(this._locationChanges=this._location.subscribe(()=>this.dispose())),this._outsideClickDispatcher.add(this),e}detach(){if(!this.hasAttached())return;this.detachBackdrop(),this._togglePointerEvents(!1),this._positionStrategy&&this._positionStrategy.detach&&this._positionStrategy.detach(),this._scrollStrategy&&this._scrollStrategy.disable();const t=this._portalOutlet.detach();return this._detachments.next(),this._keyboardDispatcher.remove(this),this._detachContentWhenStable(),this._locationChanges.unsubscribe(),this._outsideClickDispatcher.remove(this),t}dispose(){var t;const e=this.hasAttached();this._positionStrategy&&this._positionStrategy.dispose(),this._disposeScrollStrategy(),this._disposeBackdrop(this._backdropElement),this._locationChanges.unsubscribe(),this._keyboardDispatcher.remove(this),this._portalOutlet.dispose(),this._attachments.complete(),this._backdropClick.complete(),this._keydownEvents.complete(),this._outsidePointerEvents.complete(),this._outsideClickDispatcher.remove(this),null===(t=this._host)||void 0===t||t.remove(),this._previousHostParent=this._pane=this._host=null,e&&this._detachments.next(),this._detachments.complete()}hasAttached(){return this._portalOutlet.hasAttached()}backdropClick(){return this._backdropClick}attachments(){return this._attachments}detachments(){return this._detachments}keydownEvents(){return this._keydownEvents}outsidePointerEvents(){return this._outsidePointerEvents}getConfig(){return this._config}updatePosition(){this._positionStrategy&&this._positionStrategy.apply()}updatePositionStrategy(t){t!==this._positionStrategy&&(this._positionStrategy&&this._positionStrategy.dispose(),this._positionStrategy=t,this.hasAttached()&&(t.attach(this),this.updatePosition()))}updateSize(t){this._config=Object.assign(Object.assign({},this._config),t),this._updateElementSize()}setDirection(t){this._config=Object.assign(Object.assign({},this._config),{direction:t}),this._updateElementDirection()}addPanelClass(t){this._pane&&this._toggleClasses(this._pane,t,!0)}removePanelClass(t){this._pane&&this._toggleClasses(this._pane,t,!1)}getDirection(){const t=this._config.direction;return t?\"string\"==typeof t?t:t.value:\"ltr\"}updateScrollStrategy(t){t!==this._scrollStrategy&&(this._disposeScrollStrategy(),this._scrollStrategy=t,this.hasAttached()&&(t.attach(this),t.enable()))}_updateElementDirection(){this._host.setAttribute(\"dir\",this.getDirection())}_updateElementSize(){if(!this._pane)return;const t=this._pane.style;t.width=ft(this._config.width),t.height=ft(this._config.height),t.minWidth=ft(this._config.minWidth),t.minHeight=ft(this._config.minHeight),t.maxWidth=ft(this._config.maxWidth),t.maxHeight=ft(this._config.maxHeight)}_togglePointerEvents(t){this._pane.style.pointerEvents=t?\"\":\"none\"}_attachBackdrop(){const t=\"cdk-overlay-backdrop-showing\";this._backdropElement=this._document.createElement(\"div\"),this._backdropElement.classList.add(\"cdk-overlay-backdrop\"),this._config.backdropClass&&this._toggleClasses(this._backdropElement,this._config.backdropClass,!0),this._host.parentElement.insertBefore(this._backdropElement,this._host),this._backdropElement.addEventListener(\"click\",this._backdropClickHandler),\"undefined\"!=typeof requestAnimationFrame?this._ngZone.runOutsideAngular(()=>{requestAnimationFrame(()=>{this._backdropElement&&this._backdropElement.classList.add(t)})}):this._backdropElement.classList.add(t)}_updateStackingOrder(){this._host.nextSibling&&this._host.parentNode.appendChild(this._host)}detachBackdrop(){const t=this._backdropElement;!t||(t.classList.remove(\"cdk-overlay-backdrop-showing\"),this._ngZone.runOutsideAngular(()=>{t.addEventListener(\"transitionend\",this._backdropTransitionendHandler)}),t.style.pointerEvents=\"none\",this._backdropTimeout=this._ngZone.runOutsideAngular(()=>setTimeout(()=>{this._disposeBackdrop(t)},500)))}_toggleClasses(t,e,i){const r=Wx(e||[]).filter(s=>!!s);r.length&&(i?t.classList.add(...r):t.classList.remove(...r))}_detachContentWhenStable(){this._ngZone.runOutsideAngular(()=>{const t=this._ngZone.onStable.pipe(Ie(Bt(this._attachments,this._detachments))).subscribe(()=>{(!this._pane||!this._host||0===this._pane.children.length)&&(this._pane&&this._config.panelClass&&this._toggleClasses(this._pane,this._config.panelClass,!1),this._host&&this._host.parentElement&&(this._previousHostParent=this._host.parentElement,this._host.remove()),t.unsubscribe())})})}_disposeScrollStrategy(){const t=this._scrollStrategy;t&&(t.disable(),t.detach&&t.detach())}_disposeBackdrop(t){t&&(t.removeEventListener(\"click\",this._backdropClickHandler),t.removeEventListener(\"transitionend\",this._backdropTransitionendHandler),t.remove(),this._backdropElement===t&&(this._backdropElement=null)),this._backdropTimeout&&(clearTimeout(this._backdropTimeout),this._backdropTimeout=void 0)}}let Dg=(()=>{class n{constructor(e,i){this._platform=i,this._document=e}ngOnDestroy(){var e;null===(e=this._containerElement)||void 0===e||e.remove()}getContainerElement(){return this._containerElement||this._createContainer(),this._containerElement}_createContainer(){const e=\"cdk-overlay-container\";if(this._platform.isBrowser||jm()){const r=this._document.querySelectorAll(`.${e}[platform=\"server\"], .${e}[platform=\"test\"]`);for(let s=0;s<r.length;s++)r[s].remove()}const i=this._document.createElement(\"div\");i.classList.add(e),jm()?i.setAttribute(\"platform\",\"test\"):this._platform.isBrowser||i.setAttribute(\"platform\",\"server\"),this._document.body.appendChild(i),this._containerElement=i}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(It))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const OE=\"cdk-overlay-connected-position-bounding-box\",E5=/([A-Za-z%]+)$/;class S5{constructor(t,e,i,r,s){this._viewportRuler=e,this._document=i,this._platform=r,this._overlayContainer=s,this._lastBoundingBoxSize={width:0,height:0},this._isPushed=!1,this._canPush=!0,this._growAfterOpen=!1,this._hasFlexibleDimensions=!0,this._positionLocked=!1,this._viewportMargin=0,this._scrollables=[],this._preferredPositions=[],this._positionChanges=new O,this._resizeSubscription=ke.EMPTY,this._offsetX=0,this._offsetY=0,this._appliedPanelClasses=[],this.positionChanges=this._positionChanges,this.setOrigin(t)}get positions(){return this._preferredPositions}attach(t){this._validatePositions(),t.hostElement.classList.add(OE),this._overlayRef=t,this._boundingBox=t.hostElement,this._pane=t.overlayElement,this._isDisposed=!1,this._isInitialRender=!0,this._lastPosition=null,this._resizeSubscription.unsubscribe(),this._resizeSubscription=this._viewportRuler.change().subscribe(()=>{this._isInitialRender=!0,this.apply()})}apply(){if(this._isDisposed||!this._platform.isBrowser)return;if(!this._isInitialRender&&this._positionLocked&&this._lastPosition)return void this.reapplyLastPosition();this._clearPanelClasses(),this._resetOverlayElementStyles(),this._resetBoundingBoxStyles(),this._viewportRect=this._getNarrowedViewportRect(),this._originRect=this._getOriginRect(),this._overlayRect=this._pane.getBoundingClientRect(),this._containerRect=this._overlayContainer.getContainerElement().getBoundingClientRect();const t=this._originRect,e=this._overlayRect,i=this._viewportRect,r=this._containerRect,s=[];let o;for(let a of this._preferredPositions){let l=this._getOriginPoint(t,r,a),c=this._getOverlayPoint(l,e,a),d=this._getOverlayFit(c,e,i,a);if(d.isCompletelyWithinViewport)return this._isPushed=!1,void this._applyPosition(a,l);this._canFitWithFlexibleDimensions(d,c,i)?s.push({position:a,origin:l,overlayRect:e,boundingBoxRect:this._calculateBoundingBoxRect(l,a)}):(!o||o.overlayFit.visibleArea<d.visibleArea)&&(o={overlayFit:d,overlayPoint:c,originPoint:l,position:a,overlayRect:e})}if(s.length){let a=null,l=-1;for(const c of s){const d=c.boundingBoxRect.width*c.boundingBoxRect.height*(c.position.weight||1);d>l&&(l=d,a=c)}return this._isPushed=!1,void this._applyPosition(a.position,a.origin)}if(this._canPush)return this._isPushed=!0,void this._applyPosition(o.position,o.originPoint);this._applyPosition(o.position,o.originPoint)}detach(){this._clearPanelClasses(),this._lastPosition=null,this._previousPushAmount=null,this._resizeSubscription.unsubscribe()}dispose(){this._isDisposed||(this._boundingBox&&ts(this._boundingBox.style,{top:\"\",left:\"\",right:\"\",bottom:\"\",height:\"\",width:\"\",alignItems:\"\",justifyContent:\"\"}),this._pane&&this._resetOverlayElementStyles(),this._overlayRef&&this._overlayRef.hostElement.classList.remove(OE),this.detach(),this._positionChanges.complete(),this._overlayRef=this._boundingBox=null,this._isDisposed=!0)}reapplyLastPosition(){if(this._isDisposed||!this._platform.isBrowser)return;const t=this._lastPosition;if(t){this._originRect=this._getOriginRect(),this._overlayRect=this._pane.getBoundingClientRect(),this._viewportRect=this._getNarrowedViewportRect(),this._containerRect=this._overlayContainer.getContainerElement().getBoundingClientRect();const e=this._getOriginPoint(this._originRect,this._containerRect,t);this._applyPosition(t,e)}else this.apply()}withScrollableContainers(t){return this._scrollables=t,this}withPositions(t){return this._preferredPositions=t,-1===t.indexOf(this._lastPosition)&&(this._lastPosition=null),this._validatePositions(),this}withViewportMargin(t){return this._viewportMargin=t,this}withFlexibleDimensions(t=!0){return this._hasFlexibleDimensions=t,this}withGrowAfterOpen(t=!0){return this._growAfterOpen=t,this}withPush(t=!0){return this._canPush=t,this}withLockedPosition(t=!0){return this._positionLocked=t,this}setOrigin(t){return this._origin=t,this}withDefaultOffsetX(t){return this._offsetX=t,this}withDefaultOffsetY(t){return this._offsetY=t,this}withTransformOriginOn(t){return this._transformOriginSelector=t,this}_getOriginPoint(t,e,i){let r,s;if(\"center\"==i.originX)r=t.left+t.width/2;else{const o=this._isRtl()?t.right:t.left,a=this._isRtl()?t.left:t.right;r=\"start\"==i.originX?o:a}return e.left<0&&(r-=e.left),s=\"center\"==i.originY?t.top+t.height/2:\"top\"==i.originY?t.top:t.bottom,e.top<0&&(s-=e.top),{x:r,y:s}}_getOverlayPoint(t,e,i){let r,s;return r=\"center\"==i.overlayX?-e.width/2:\"start\"===i.overlayX?this._isRtl()?-e.width:0:this._isRtl()?0:-e.width,s=\"center\"==i.overlayY?-e.height/2:\"top\"==i.overlayY?0:-e.height,{x:t.x+r,y:t.y+s}}_getOverlayFit(t,e,i,r){const s=FE(e);let{x:o,y:a}=t,l=this._getOffset(r,\"x\"),c=this._getOffset(r,\"y\");l&&(o+=l),c&&(a+=c);let h=0-a,p=a+s.height-i.height,m=this._subtractOverflows(s.width,0-o,o+s.width-i.width),g=this._subtractOverflows(s.height,h,p),_=m*g;return{visibleArea:_,isCompletelyWithinViewport:s.width*s.height===_,fitsInViewportVertically:g===s.height,fitsInViewportHorizontally:m==s.width}}_canFitWithFlexibleDimensions(t,e,i){if(this._hasFlexibleDimensions){const r=i.bottom-e.y,s=i.right-e.x,o=PE(this._overlayRef.getConfig().minHeight),a=PE(this._overlayRef.getConfig().minWidth),c=t.fitsInViewportHorizontally||null!=a&&a<=s;return(t.fitsInViewportVertically||null!=o&&o<=r)&&c}return!1}_pushOverlayOnScreen(t,e,i){if(this._previousPushAmount&&this._positionLocked)return{x:t.x+this._previousPushAmount.x,y:t.y+this._previousPushAmount.y};const r=FE(e),s=this._viewportRect,o=Math.max(t.x+r.width-s.width,0),a=Math.max(t.y+r.height-s.height,0),l=Math.max(s.top-i.top-t.y,0),c=Math.max(s.left-i.left-t.x,0);let d=0,u=0;return d=r.width<=s.width?c||-o:t.x<this._viewportMargin?s.left-i.left-t.x:0,u=r.height<=s.height?l||-a:t.y<this._viewportMargin?s.top-i.top-t.y:0,this._previousPushAmount={x:d,y:u},{x:t.x+d,y:t.y+u}}_applyPosition(t,e){if(this._setTransformOrigin(t),this._setOverlayElementStyles(e,t),this._setBoundingBoxStyles(e,t),t.panelClass&&this._addPanelClasses(t.panelClass),this._lastPosition=t,this._positionChanges.observers.length){const i=this._getScrollVisibility(),r=new M5(t,i);this._positionChanges.next(r)}this._isInitialRender=!1}_setTransformOrigin(t){if(!this._transformOriginSelector)return;const e=this._boundingBox.querySelectorAll(this._transformOriginSelector);let i,r=t.overlayY;i=\"center\"===t.overlayX?\"center\":this._isRtl()?\"start\"===t.overlayX?\"right\":\"left\":\"start\"===t.overlayX?\"left\":\"right\";for(let s=0;s<e.length;s++)e[s].style.transformOrigin=`${i} ${r}`}_calculateBoundingBoxRect(t,e){const i=this._viewportRect,r=this._isRtl();let s,o,a,d,u,h;if(\"top\"===e.overlayY)o=t.y,s=i.height-o+this._viewportMargin;else if(\"bottom\"===e.overlayY)a=i.height-t.y+2*this._viewportMargin,s=i.height-a+this._viewportMargin;else{const p=Math.min(i.bottom-t.y+i.top,t.y),m=this._lastBoundingBoxSize.height;s=2*p,o=t.y-p,s>m&&!this._isInitialRender&&!this._growAfterOpen&&(o=t.y-m/2)}if(\"end\"===e.overlayX&&!r||\"start\"===e.overlayX&&r)h=i.width-t.x+this._viewportMargin,d=t.x-this._viewportMargin;else if(\"start\"===e.overlayX&&!r||\"end\"===e.overlayX&&r)u=t.x,d=i.right-t.x;else{const p=Math.min(i.right-t.x+i.left,t.x),m=this._lastBoundingBoxSize.width;d=2*p,u=t.x-p,d>m&&!this._isInitialRender&&!this._growAfterOpen&&(u=t.x-m/2)}return{top:o,left:u,bottom:a,right:h,width:d,height:s}}_setBoundingBoxStyles(t,e){const i=this._calculateBoundingBoxRect(t,e);!this._isInitialRender&&!this._growAfterOpen&&(i.height=Math.min(i.height,this._lastBoundingBoxSize.height),i.width=Math.min(i.width,this._lastBoundingBoxSize.width));const r={};if(this._hasExactPosition())r.top=r.left=\"0\",r.bottom=r.right=r.maxHeight=r.maxWidth=\"\",r.width=r.height=\"100%\";else{const s=this._overlayRef.getConfig().maxHeight,o=this._overlayRef.getConfig().maxWidth;r.height=ft(i.height),r.top=ft(i.top),r.bottom=ft(i.bottom),r.width=ft(i.width),r.left=ft(i.left),r.right=ft(i.right),r.alignItems=\"center\"===e.overlayX?\"center\":\"end\"===e.overlayX?\"flex-end\":\"flex-start\",r.justifyContent=\"center\"===e.overlayY?\"center\":\"bottom\"===e.overlayY?\"flex-end\":\"flex-start\",s&&(r.maxHeight=ft(s)),o&&(r.maxWidth=ft(o))}this._lastBoundingBoxSize=i,ts(this._boundingBox.style,r)}_resetBoundingBoxStyles(){ts(this._boundingBox.style,{top:\"0\",left:\"0\",right:\"0\",bottom:\"0\",height:\"\",width:\"\",alignItems:\"\",justifyContent:\"\"})}_resetOverlayElementStyles(){ts(this._pane.style,{top:\"\",left:\"\",bottom:\"\",right:\"\",position:\"\",transform:\"\"})}_setOverlayElementStyles(t,e){const i={},r=this._hasExactPosition(),s=this._hasFlexibleDimensions,o=this._overlayRef.getConfig();if(r){const d=this._viewportRuler.getViewportScrollPosition();ts(i,this._getExactOverlayY(e,t,d)),ts(i,this._getExactOverlayX(e,t,d))}else i.position=\"static\";let a=\"\",l=this._getOffset(e,\"x\"),c=this._getOffset(e,\"y\");l&&(a+=`translateX(${l}px) `),c&&(a+=`translateY(${c}px)`),i.transform=a.trim(),o.maxHeight&&(r?i.maxHeight=ft(o.maxHeight):s&&(i.maxHeight=\"\")),o.maxWidth&&(r?i.maxWidth=ft(o.maxWidth):s&&(i.maxWidth=\"\")),ts(this._pane.style,i)}_getExactOverlayY(t,e,i){let r={top:\"\",bottom:\"\"},s=this._getOverlayPoint(e,this._overlayRect,t);return this._isPushed&&(s=this._pushOverlayOnScreen(s,this._overlayRect,i)),\"bottom\"===t.overlayY?r.bottom=this._document.documentElement.clientHeight-(s.y+this._overlayRect.height)+\"px\":r.top=ft(s.y),r}_getExactOverlayX(t,e,i){let o,r={left:\"\",right:\"\"},s=this._getOverlayPoint(e,this._overlayRect,t);return this._isPushed&&(s=this._pushOverlayOnScreen(s,this._overlayRect,i)),o=this._isRtl()?\"end\"===t.overlayX?\"left\":\"right\":\"end\"===t.overlayX?\"right\":\"left\",\"right\"===o?r.right=this._document.documentElement.clientWidth-(s.x+this._overlayRect.width)+\"px\":r.left=ft(s.x),r}_getScrollVisibility(){const t=this._getOriginRect(),e=this._pane.getBoundingClientRect(),i=this._scrollables.map(r=>r.getElementRef().nativeElement.getBoundingClientRect());return{isOriginClipped:RE(t,i),isOriginOutsideView:Cg(t,i),isOverlayClipped:RE(e,i),isOverlayOutsideView:Cg(e,i)}}_subtractOverflows(t,...e){return e.reduce((i,r)=>i-Math.max(r,0),t)}_getNarrowedViewportRect(){const t=this._document.documentElement.clientWidth,e=this._document.documentElement.clientHeight,i=this._viewportRuler.getViewportScrollPosition();return{top:i.top+this._viewportMargin,left:i.left+this._viewportMargin,right:i.left+t-this._viewportMargin,bottom:i.top+e-this._viewportMargin,width:t-2*this._viewportMargin,height:e-2*this._viewportMargin}}_isRtl(){return\"rtl\"===this._overlayRef.getDirection()}_hasExactPosition(){return!this._hasFlexibleDimensions||this._isPushed}_getOffset(t,e){return\"x\"===e?null==t.offsetX?this._offsetX:t.offsetX:null==t.offsetY?this._offsetY:t.offsetY}_validatePositions(){}_addPanelClasses(t){this._pane&&Wx(t).forEach(e=>{\"\"!==e&&-1===this._appliedPanelClasses.indexOf(e)&&(this._appliedPanelClasses.push(e),this._pane.classList.add(e))})}_clearPanelClasses(){this._pane&&(this._appliedPanelClasses.forEach(t=>{this._pane.classList.remove(t)}),this._appliedPanelClasses=[])}_getOriginRect(){const t=this._origin;if(t instanceof W)return t.nativeElement.getBoundingClientRect();if(t instanceof Element)return t.getBoundingClientRect();const e=t.width||0,i=t.height||0;return{top:t.y,bottom:t.y+i,left:t.x,right:t.x+e,height:i,width:e}}}function ts(n,t){for(let e in t)t.hasOwnProperty(e)&&(n[e]=t[e]);return n}function PE(n){if(\"number\"!=typeof n&&null!=n){const[t,e]=n.split(E5);return e&&\"px\"!==e?null:parseFloat(t)}return n||null}function FE(n){return{top:Math.floor(n.top),right:Math.floor(n.right),bottom:Math.floor(n.bottom),left:Math.floor(n.left),width:Math.floor(n.width),height:Math.floor(n.height)}}const NE=\"cdk-global-overlay-wrapper\";class k5{constructor(){this._cssPosition=\"static\",this._topOffset=\"\",this._bottomOffset=\"\",this._leftOffset=\"\",this._rightOffset=\"\",this._alignItems=\"\",this._justifyContent=\"\",this._width=\"\",this._height=\"\"}attach(t){const e=t.getConfig();this._overlayRef=t,this._width&&!e.width&&t.updateSize({width:this._width}),this._height&&!e.height&&t.updateSize({height:this._height}),t.hostElement.classList.add(NE),this._isDisposed=!1}top(t=\"\"){return this._bottomOffset=\"\",this._topOffset=t,this._alignItems=\"flex-start\",this}left(t=\"\"){return this._rightOffset=\"\",this._leftOffset=t,this._justifyContent=\"flex-start\",this}bottom(t=\"\"){return this._topOffset=\"\",this._bottomOffset=t,this._alignItems=\"flex-end\",this}right(t=\"\"){return this._leftOffset=\"\",this._rightOffset=t,this._justifyContent=\"flex-end\",this}width(t=\"\"){return this._overlayRef?this._overlayRef.updateSize({width:t}):this._width=t,this}height(t=\"\"){return this._overlayRef?this._overlayRef.updateSize({height:t}):this._height=t,this}centerHorizontally(t=\"\"){return this.left(t),this._justifyContent=\"center\",this}centerVertically(t=\"\"){return this.top(t),this._alignItems=\"center\",this}apply(){if(!this._overlayRef||!this._overlayRef.hasAttached())return;const t=this._overlayRef.overlayElement.style,e=this._overlayRef.hostElement.style,i=this._overlayRef.getConfig(),{width:r,height:s,maxWidth:o,maxHeight:a}=i,l=!(\"100%\"!==r&&\"100vw\"!==r||o&&\"100%\"!==o&&\"100vw\"!==o),c=!(\"100%\"!==s&&\"100vh\"!==s||a&&\"100%\"!==a&&\"100vh\"!==a);t.position=this._cssPosition,t.marginLeft=l?\"0\":this._leftOffset,t.marginTop=c?\"0\":this._topOffset,t.marginBottom=this._bottomOffset,t.marginRight=this._rightOffset,l?e.justifyContent=\"flex-start\":\"center\"===this._justifyContent?e.justifyContent=\"center\":\"rtl\"===this._overlayRef.getConfig().direction?\"flex-start\"===this._justifyContent?e.justifyContent=\"flex-end\":\"flex-end\"===this._justifyContent&&(e.justifyContent=\"flex-start\"):e.justifyContent=this._justifyContent,e.alignItems=c?\"flex-start\":this._alignItems}dispose(){if(this._isDisposed||!this._overlayRef)return;const t=this._overlayRef.overlayElement.style,e=this._overlayRef.hostElement,i=e.style;e.classList.remove(NE),i.justifyContent=i.alignItems=t.marginTop=t.marginBottom=t.marginLeft=t.marginRight=t.position=\"\",this._overlayRef=null,this._isDisposed=!0}}let T5=(()=>{class n{constructor(e,i,r,s){this._viewportRuler=e,this._document=i,this._platform=r,this._overlayContainer=s}global(){return new k5}flexibleConnectedTo(e){return new S5(e,this._viewportRuler,this._document,this._platform,this._overlayContainer)}}return n.\\u0275fac=function(e){return new(e||n)(y(es),y(ie),y(It),y(Dg))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),LE=(()=>{class n{constructor(e){this._attachedOverlays=[],this._document=e}ngOnDestroy(){this.detach()}add(e){this.remove(e),this._attachedOverlays.push(e)}remove(e){const i=this._attachedOverlays.indexOf(e);i>-1&&this._attachedOverlays.splice(i,1),0===this._attachedOverlays.length&&this.detach()}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),A5=(()=>{class n extends LE{constructor(e,i){super(e),this._ngZone=i,this._keydownListener=r=>{const s=this._attachedOverlays;for(let o=s.length-1;o>-1;o--)if(s[o]._keydownEvents.observers.length>0){const a=s[o]._keydownEvents;this._ngZone?this._ngZone.run(()=>a.next(r)):a.next(r);break}}}add(e){super.add(e),this._isAttached||(this._ngZone?this._ngZone.runOutsideAngular(()=>this._document.body.addEventListener(\"keydown\",this._keydownListener)):this._document.body.addEventListener(\"keydown\",this._keydownListener),this._isAttached=!0)}detach(){this._isAttached&&(this._document.body.removeEventListener(\"keydown\",this._keydownListener),this._isAttached=!1)}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(ne,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),I5=(()=>{class n extends LE{constructor(e,i,r){super(e),this._platform=i,this._ngZone=r,this._cursorStyleIsSet=!1,this._pointerDownListener=s=>{this._pointerDownEventTarget=Pn(s)},this._clickListener=s=>{const o=Pn(s),a=\"click\"===s.type&&this._pointerDownEventTarget?this._pointerDownEventTarget:o;this._pointerDownEventTarget=null;const l=this._attachedOverlays.slice();for(let c=l.length-1;c>-1;c--){const d=l[c];if(d._outsidePointerEvents.observers.length<1||!d.hasAttached())continue;if(d.overlayElement.contains(o)||d.overlayElement.contains(a))break;const u=d._outsidePointerEvents;this._ngZone?this._ngZone.run(()=>u.next(s)):u.next(s)}}}add(e){if(super.add(e),!this._isAttached){const i=this._document.body;this._ngZone?this._ngZone.runOutsideAngular(()=>this._addEventListeners(i)):this._addEventListeners(i),this._platform.IOS&&!this._cursorStyleIsSet&&(this._cursorOriginalValue=i.style.cursor,i.style.cursor=\"pointer\",this._cursorStyleIsSet=!0),this._isAttached=!0}}detach(){if(this._isAttached){const e=this._document.body;e.removeEventListener(\"pointerdown\",this._pointerDownListener,!0),e.removeEventListener(\"click\",this._clickListener,!0),e.removeEventListener(\"auxclick\",this._clickListener,!0),e.removeEventListener(\"contextmenu\",this._clickListener,!0),this._platform.IOS&&this._cursorStyleIsSet&&(e.style.cursor=this._cursorOriginalValue,this._cursorStyleIsSet=!1),this._isAttached=!1}}_addEventListeners(e){e.addEventListener(\"pointerdown\",this._pointerDownListener,!0),e.addEventListener(\"click\",this._clickListener,!0),e.addEventListener(\"auxclick\",this._clickListener,!0),e.addEventListener(\"contextmenu\",this._clickListener,!0)}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(It),y(ne,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),R5=0,ni=(()=>{class n{constructor(e,i,r,s,o,a,l,c,d,u,h){this.scrollStrategies=e,this._overlayContainer=i,this._componentFactoryResolver=r,this._positionBuilder=s,this._keyboardDispatcher=o,this._injector=a,this._ngZone=l,this._document=c,this._directionality=d,this._location=u,this._outsideClickDispatcher=h}create(e){const i=this._createHostElement(),r=this._createPaneElement(i),s=this._createPortalOutlet(r),o=new Gd(e);return o.direction=o.direction||this._directionality.value,new x5(s,i,r,o,this._ngZone,this._keyboardDispatcher,this._document,this._location,this._outsideClickDispatcher)}position(){return this._positionBuilder}_createPaneElement(e){const i=this._document.createElement(\"div\");return i.id=\"cdk-overlay-\"+R5++,i.classList.add(\"cdk-overlay-pane\"),e.appendChild(i),i}_createHostElement(){const e=this._document.createElement(\"div\");return this._overlayContainer.getContainerElement().appendChild(e),e}_createPortalOutlet(e){return this._appRef||(this._appRef=this._injector.get(Cc)),new v5(e,this._componentFactoryResolver,this._appRef,this._injector,this._document)}}return n.\\u0275fac=function(e){return new(e||n)(y(w5),y(Dg),y(Ir),y(T5),y(A5),y(dt),y(ne),y(ie),y(On),y(va),y(I5))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const O5=[{originX:\"start\",originY:\"bottom\",overlayX:\"start\",overlayY:\"top\"},{originX:\"start\",originY:\"top\",overlayX:\"start\",overlayY:\"bottom\"},{originX:\"end\",originY:\"top\",overlayX:\"end\",overlayY:\"bottom\"},{originX:\"end\",originY:\"bottom\",overlayX:\"end\",overlayY:\"top\"}],BE=new b(\"cdk-connected-overlay-scroll-strategy\");let VE=(()=>{class n{constructor(e){this.elementRef=e}}return n.\\u0275fac=function(e){return new(e||n)(f(W))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"cdk-overlay-origin\",\"\"],[\"\",\"overlay-origin\",\"\"],[\"\",\"cdkOverlayOrigin\",\"\"]],exportAs:[\"cdkOverlayOrigin\"]}),n})(),HE=(()=>{class n{constructor(e,i,r,s,o){this._overlay=e,this._dir=o,this._hasBackdrop=!1,this._lockPosition=!1,this._growAfterOpen=!1,this._flexibleDimensions=!1,this._push=!1,this._backdropSubscription=ke.EMPTY,this._attachSubscription=ke.EMPTY,this._detachSubscription=ke.EMPTY,this._positionSubscription=ke.EMPTY,this.viewportMargin=0,this.open=!1,this.disableClose=!1,this.backdropClick=new $,this.positionChange=new $,this.attach=new $,this.detach=new $,this.overlayKeydown=new $,this.overlayOutsideClick=new $,this._templatePortal=new $d(i,r),this._scrollStrategyFactory=s,this.scrollStrategy=this._scrollStrategyFactory()}get offsetX(){return this._offsetX}set offsetX(e){this._offsetX=e,this._position&&this._updatePositionStrategy(this._position)}get offsetY(){return this._offsetY}set offsetY(e){this._offsetY=e,this._position&&this._updatePositionStrategy(this._position)}get hasBackdrop(){return this._hasBackdrop}set hasBackdrop(e){this._hasBackdrop=G(e)}get lockPosition(){return this._lockPosition}set lockPosition(e){this._lockPosition=G(e)}get flexibleDimensions(){return this._flexibleDimensions}set flexibleDimensions(e){this._flexibleDimensions=G(e)}get growAfterOpen(){return this._growAfterOpen}set growAfterOpen(e){this._growAfterOpen=G(e)}get push(){return this._push}set push(e){this._push=G(e)}get overlayRef(){return this._overlayRef}get dir(){return this._dir?this._dir.value:\"ltr\"}ngOnDestroy(){this._attachSubscription.unsubscribe(),this._detachSubscription.unsubscribe(),this._backdropSubscription.unsubscribe(),this._positionSubscription.unsubscribe(),this._overlayRef&&this._overlayRef.dispose()}ngOnChanges(e){this._position&&(this._updatePositionStrategy(this._position),this._overlayRef.updateSize({width:this.width,minWidth:this.minWidth,height:this.height,minHeight:this.minHeight}),e.origin&&this.open&&this._position.apply()),e.open&&(this.open?this._attachOverlay():this._detachOverlay())}_createOverlay(){(!this.positions||!this.positions.length)&&(this.positions=O5);const e=this._overlayRef=this._overlay.create(this._buildConfig());this._attachSubscription=e.attachments().subscribe(()=>this.attach.emit()),this._detachSubscription=e.detachments().subscribe(()=>this.detach.emit()),e.keydownEvents().subscribe(i=>{this.overlayKeydown.next(i),27===i.keyCode&&!this.disableClose&&!Xt(i)&&(i.preventDefault(),this._detachOverlay())}),this._overlayRef.outsidePointerEvents().subscribe(i=>{this.overlayOutsideClick.next(i)})}_buildConfig(){const e=this._position=this.positionStrategy||this._createPositionStrategy(),i=new Gd({direction:this._dir,positionStrategy:e,scrollStrategy:this.scrollStrategy,hasBackdrop:this.hasBackdrop});return(this.width||0===this.width)&&(i.width=this.width),(this.height||0===this.height)&&(i.height=this.height),(this.minWidth||0===this.minWidth)&&(i.minWidth=this.minWidth),(this.minHeight||0===this.minHeight)&&(i.minHeight=this.minHeight),this.backdropClass&&(i.backdropClass=this.backdropClass),this.panelClass&&(i.panelClass=this.panelClass),i}_updatePositionStrategy(e){const i=this.positions.map(r=>({originX:r.originX,originY:r.originY,overlayX:r.overlayX,overlayY:r.overlayY,offsetX:r.offsetX||this.offsetX,offsetY:r.offsetY||this.offsetY,panelClass:r.panelClass||void 0}));return e.setOrigin(this._getFlexibleConnectedPositionStrategyOrigin()).withPositions(i).withFlexibleDimensions(this.flexibleDimensions).withPush(this.push).withGrowAfterOpen(this.growAfterOpen).withViewportMargin(this.viewportMargin).withLockedPosition(this.lockPosition).withTransformOriginOn(this.transformOriginSelector)}_createPositionStrategy(){const e=this._overlay.position().flexibleConnectedTo(this._getFlexibleConnectedPositionStrategyOrigin());return this._updatePositionStrategy(e),e}_getFlexibleConnectedPositionStrategyOrigin(){return this.origin instanceof VE?this.origin.elementRef:this.origin}_attachOverlay(){this._overlayRef?this._overlayRef.getConfig().hasBackdrop=this.hasBackdrop:this._createOverlay(),this._overlayRef.hasAttached()||this._overlayRef.attach(this._templatePortal),this.hasBackdrop?this._backdropSubscription=this._overlayRef.backdropClick().subscribe(e=>{this.backdropClick.emit(e)}):this._backdropSubscription.unsubscribe(),this._positionSubscription.unsubscribe(),this.positionChange.observers.length>0&&(this._positionSubscription=this._position.positionChanges.pipe(function y5(n,t=!1){return qe((e,i)=>{let r=0;e.subscribe(Ue(i,s=>{const o=n(s,r++);(o||t)&&i.next(s),!o&&i.complete()}))})}(()=>this.positionChange.observers.length>0)).subscribe(e=>{this.positionChange.emit(e),0===this.positionChange.observers.length&&this._positionSubscription.unsubscribe()}))}_detachOverlay(){this._overlayRef&&this._overlayRef.detach(),this._backdropSubscription.unsubscribe(),this._positionSubscription.unsubscribe()}}return n.\\u0275fac=function(e){return new(e||n)(f(ni),f(ut),f(st),f(BE),f(On,8))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"cdk-connected-overlay\",\"\"],[\"\",\"connected-overlay\",\"\"],[\"\",\"cdkConnectedOverlay\",\"\"]],inputs:{origin:[\"cdkConnectedOverlayOrigin\",\"origin\"],positions:[\"cdkConnectedOverlayPositions\",\"positions\"],positionStrategy:[\"cdkConnectedOverlayPositionStrategy\",\"positionStrategy\"],offsetX:[\"cdkConnectedOverlayOffsetX\",\"offsetX\"],offsetY:[\"cdkConnectedOverlayOffsetY\",\"offsetY\"],width:[\"cdkConnectedOverlayWidth\",\"width\"],height:[\"cdkConnectedOverlayHeight\",\"height\"],minWidth:[\"cdkConnectedOverlayMinWidth\",\"minWidth\"],minHeight:[\"cdkConnectedOverlayMinHeight\",\"minHeight\"],backdropClass:[\"cdkConnectedOverlayBackdropClass\",\"backdropClass\"],panelClass:[\"cdkConnectedOverlayPanelClass\",\"panelClass\"],viewportMargin:[\"cdkConnectedOverlayViewportMargin\",\"viewportMargin\"],scrollStrategy:[\"cdkConnectedOverlayScrollStrategy\",\"scrollStrategy\"],open:[\"cdkConnectedOverlayOpen\",\"open\"],disableClose:[\"cdkConnectedOverlayDisableClose\",\"disableClose\"],transformOriginSelector:[\"cdkConnectedOverlayTransformOriginOn\",\"transformOriginSelector\"],hasBackdrop:[\"cdkConnectedOverlayHasBackdrop\",\"hasBackdrop\"],lockPosition:[\"cdkConnectedOverlayLockPosition\",\"lockPosition\"],flexibleDimensions:[\"cdkConnectedOverlayFlexibleDimensions\",\"flexibleDimensions\"],growAfterOpen:[\"cdkConnectedOverlayGrowAfterOpen\",\"growAfterOpen\"],push:[\"cdkConnectedOverlayPush\",\"push\"]},outputs:{backdropClick:\"backdropClick\",positionChange:\"positionChange\",attach:\"attach\",detach:\"detach\",overlayKeydown:\"overlayKeydown\",overlayOutsideClick:\"overlayOutsideClick\"},exportAs:[\"cdkConnectedOverlay\"],features:[Je]}),n})();const F5={provide:BE,deps:[ni],useFactory:function P5(n){return()=>n.scrollStrategies.reposition()}};let ji=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[ni,F5],imports:[[lo,Hi,Ud],Ud]}),n})();class nl{constructor(t=!1,e,i=!0){this._multiple=t,this._emitChanges=i,this._selection=new Set,this._deselectedToEmit=[],this._selectedToEmit=[],this.changed=new O,e&&e.length&&(t?e.forEach(r=>this._markSelected(r)):this._markSelected(e[0]),this._selectedToEmit.length=0)}get selected(){return this._selected||(this._selected=Array.from(this._selection.values())),this._selected}select(...t){this._verifyValueAssignment(t),t.forEach(e=>this._markSelected(e)),this._emitChangeEvent()}deselect(...t){this._verifyValueAssignment(t),t.forEach(e=>this._unmarkSelected(e)),this._emitChangeEvent()}toggle(t){this.isSelected(t)?this.deselect(t):this.select(t)}clear(){this._unmarkAll(),this._emitChangeEvent()}isSelected(t){return this._selection.has(t)}isEmpty(){return 0===this._selection.size}hasValue(){return!this.isEmpty()}sort(t){this._multiple&&this.selected&&this._selected.sort(t)}isMultipleSelection(){return this._multiple}_emitChangeEvent(){this._selected=null,(this._selectedToEmit.length||this._deselectedToEmit.length)&&(this.changed.next({source:this,added:this._selectedToEmit,removed:this._deselectedToEmit}),this._deselectedToEmit=[],this._selectedToEmit=[])}_markSelected(t){this.isSelected(t)||(this._multiple||this._unmarkAll(),this._selection.add(t),this._emitChanges&&this._selectedToEmit.push(t))}_unmarkSelected(t){this.isSelected(t)&&(this._selection.delete(t),this._emitChanges&&this._deselectedToEmit.push(t))}_unmarkAll(){this.isEmpty()||this._selection.forEach(t=>this._unmarkSelected(t))}_verifyValueAssignment(t){}}const L5=[\"trigger\"],B5=[\"panel\"];function V5(n,t){if(1&n&&(x(0,\"span\",8),we(1),S()),2&n){const e=Be();T(1),Ut(e.placeholder)}}function H5(n,t){if(1&n&&(x(0,\"span\",12),we(1),S()),2&n){const e=Be(2);T(1),Ut(e.triggerValue)}}function j5(n,t){1&n&&Pe(0,0,[\"*ngSwitchCase\",\"true\"])}function z5(n,t){1&n&&(x(0,\"span\",9),Ee(1,H5,2,1,\"span\",10),Ee(2,j5,1,0,\"ng-content\",11),S()),2&n&&(N(\"ngSwitch\",!!Be().customTrigger),T(2),N(\"ngSwitchCase\",!0))}function U5(n,t){if(1&n){const e=ia();x(0,\"div\",13)(1,\"div\",14,15),J(\"@transformPanel.done\",function(r){return Dr(e),Be()._panelDoneAnimatingStream.next(r.toState)})(\"keydown\",function(r){return Dr(e),Be()._handleKeydown(r)}),Pe(3,1),S()()}if(2&n){const e=Be();N(\"@transformPanelWrap\",void 0),T(1),cC(\"mat-select-panel \",e._getPanelTheme(),\"\"),$n(\"transform-origin\",e._transformOrigin)(\"font-size\",e._triggerFontSize,\"px\"),N(\"ngClass\",e.panelClass)(\"@transformPanel\",e.multiple?\"showing-multiple\":\"showing\"),Z(\"id\",e.id+\"-panel\")(\"aria-multiselectable\",e.multiple)(\"aria-label\",e.ariaLabel||null)(\"aria-labelledby\",e._getPanelAriaLabelledby())}}const $5=[[[\"mat-select-trigger\"]],\"*\"],G5=[\"mat-select-trigger\",\"*\"],UE={transformPanelWrap:Ke(\"transformPanelWrap\",[ge(\"* => void\",no(\"@transformPanel\",[to()],{optional:!0}))]),transformPanel:Ke(\"transformPanel\",[ae(\"void\",R({transform:\"scaleY(0.8)\",minWidth:\"100%\",opacity:0})),ae(\"showing\",R({opacity:1,minWidth:\"calc(100% + 32px)\",transform:\"scaleY(1)\"})),ae(\"showing-multiple\",R({opacity:1,minWidth:\"calc(100% + 64px)\",transform:\"scaleY(1)\"})),ge(\"void => *\",be(\"120ms cubic-bezier(0, 0, 0.2, 1)\")),ge(\"* => void\",be(\"100ms 25ms linear\",R({opacity:0})))])};let $E=0;const WE=new b(\"mat-select-scroll-strategy\"),Q5=new b(\"MAT_SELECT_CONFIG\"),K5={provide:WE,deps:[ni],useFactory:function Y5(n){return()=>n.scrollStrategies.reposition()}};class Z5{constructor(t,e){this.source=t,this.value=e}}const X5=ar(Kr(po(ng(class{constructor(n,t,e,i,r){this._elementRef=n,this._defaultErrorStateMatcher=t,this._parentForm=e,this._parentFormGroup=i,this.ngControl=r}})))),J5=new b(\"MatSelectTrigger\");let e$=(()=>{class n extends X5{constructor(e,i,r,s,o,a,l,c,d,u,h,p,m,g){var _,D,v;super(o,s,l,c,u),this._viewportRuler=e,this._changeDetectorRef=i,this._ngZone=r,this._dir=a,this._parentFormField=d,this._liveAnnouncer=m,this._defaultOptions=g,this._panelOpen=!1,this._compareWith=(M,V)=>M===V,this._uid=\"mat-select-\"+$E++,this._triggerAriaLabelledBy=null,this._destroy=new O,this._onChange=()=>{},this._onTouched=()=>{},this._valueId=\"mat-select-value-\"+$E++,this._panelDoneAnimatingStream=new O,this._overlayPanelClass=(null===(_=this._defaultOptions)||void 0===_?void 0:_.overlayPanelClass)||\"\",this._focused=!1,this.controlType=\"mat-select\",this._multiple=!1,this._disableOptionCentering=null!==(v=null===(D=this._defaultOptions)||void 0===D?void 0:D.disableOptionCentering)&&void 0!==v&&v,this.ariaLabel=\"\",this.optionSelectionChanges=xa(()=>{const M=this.options;return M?M.changes.pipe(Xn(M),kn(()=>Bt(...M.map(V=>V.onSelectionChange)))):this._ngZone.onStable.pipe(it(1),kn(()=>this.optionSelectionChanges))}),this.openedChange=new $,this._openedStream=this.openedChange.pipe(Ct(M=>M),ue(()=>{})),this._closedStream=this.openedChange.pipe(Ct(M=>!M),ue(()=>{})),this.selectionChange=new $,this.valueChange=new $,this.ngControl&&(this.ngControl.valueAccessor=this),null!=(null==g?void 0:g.typeaheadDebounceInterval)&&(this._typeaheadDebounceInterval=g.typeaheadDebounceInterval),this._scrollStrategyFactory=p,this._scrollStrategy=this._scrollStrategyFactory(),this.tabIndex=parseInt(h)||0,this.id=this.id}get focused(){return this._focused||this._panelOpen}get placeholder(){return this._placeholder}set placeholder(e){this._placeholder=e,this.stateChanges.next()}get required(){var e,i,r,s;return null!==(s=null!==(e=this._required)&&void 0!==e?e:null===(r=null===(i=this.ngControl)||void 0===i?void 0:i.control)||void 0===r?void 0:r.hasValidator(yi.required))&&void 0!==s&&s}set required(e){this._required=G(e),this.stateChanges.next()}get multiple(){return this._multiple}set multiple(e){this._multiple=G(e)}get disableOptionCentering(){return this._disableOptionCentering}set disableOptionCentering(e){this._disableOptionCentering=G(e)}get compareWith(){return this._compareWith}set compareWith(e){this._compareWith=e,this._selectionModel&&this._initializeSelection()}get value(){return this._value}set value(e){(e!==this._value||this._multiple&&Array.isArray(e))&&(this.options&&this._setSelectionByValue(e),this._value=e)}get typeaheadDebounceInterval(){return this._typeaheadDebounceInterval}set typeaheadDebounceInterval(e){this._typeaheadDebounceInterval=Et(e)}get id(){return this._id}set id(e){this._id=e||this._uid,this.stateChanges.next()}ngOnInit(){this._selectionModel=new nl(this.multiple),this.stateChanges.next(),this._panelDoneAnimatingStream.pipe(Gx(),Ie(this._destroy)).subscribe(()=>this._panelDoneAnimating(this.panelOpen))}ngAfterContentInit(){this._initKeyManager(),this._selectionModel.changed.pipe(Ie(this._destroy)).subscribe(e=>{e.added.forEach(i=>i.select()),e.removed.forEach(i=>i.deselect())}),this.options.changes.pipe(Xn(null),Ie(this._destroy)).subscribe(()=>{this._resetOptions(),this._initializeSelection()})}ngDoCheck(){const e=this._getTriggerAriaLabelledby(),i=this.ngControl;if(e!==this._triggerAriaLabelledBy){const r=this._elementRef.nativeElement;this._triggerAriaLabelledBy=e,e?r.setAttribute(\"aria-labelledby\",e):r.removeAttribute(\"aria-labelledby\")}i&&(this._previousControl!==i.control&&(void 0!==this._previousControl&&null!==i.disabled&&i.disabled!==this.disabled&&(this.disabled=i.disabled),this._previousControl=i.control),this.updateErrorState())}ngOnChanges(e){e.disabled&&this.stateChanges.next(),e.typeaheadDebounceInterval&&this._keyManager&&this._keyManager.withTypeAhead(this._typeaheadDebounceInterval)}ngOnDestroy(){this._destroy.next(),this._destroy.complete(),this.stateChanges.complete()}toggle(){this.panelOpen?this.close():this.open()}open(){this._canOpen()&&(this._panelOpen=!0,this._keyManager.withHorizontalOrientation(null),this._highlightCorrectOption(),this._changeDetectorRef.markForCheck())}close(){this._panelOpen&&(this._panelOpen=!1,this._keyManager.withHorizontalOrientation(this._isRtl()?\"rtl\":\"ltr\"),this._changeDetectorRef.markForCheck(),this._onTouched())}writeValue(e){this.value=e}registerOnChange(e){this._onChange=e}registerOnTouched(e){this._onTouched=e}setDisabledState(e){this.disabled=e,this._changeDetectorRef.markForCheck(),this.stateChanges.next()}get panelOpen(){return this._panelOpen}get selected(){var e,i;return this.multiple?(null===(e=this._selectionModel)||void 0===e?void 0:e.selected)||[]:null===(i=this._selectionModel)||void 0===i?void 0:i.selected[0]}get triggerValue(){if(this.empty)return\"\";if(this._multiple){const e=this._selectionModel.selected.map(i=>i.viewValue);return this._isRtl()&&e.reverse(),e.join(\", \")}return this._selectionModel.selected[0].viewValue}_isRtl(){return!!this._dir&&\"rtl\"===this._dir.value}_handleKeydown(e){this.disabled||(this.panelOpen?this._handleOpenKeydown(e):this._handleClosedKeydown(e))}_handleClosedKeydown(e){const i=e.keyCode,r=40===i||38===i||37===i||39===i,s=13===i||32===i,o=this._keyManager;if(!o.isTyping()&&s&&!Xt(e)||(this.multiple||e.altKey)&&r)e.preventDefault(),this.open();else if(!this.multiple){const a=this.selected;o.onKeydown(e);const l=this.selected;l&&a!==l&&this._liveAnnouncer.announce(l.viewValue,1e4)}}_handleOpenKeydown(e){const i=this._keyManager,r=e.keyCode,s=40===r||38===r,o=i.isTyping();if(s&&e.altKey)e.preventDefault(),this.close();else if(o||13!==r&&32!==r||!i.activeItem||Xt(e))if(!o&&this._multiple&&65===r&&e.ctrlKey){e.preventDefault();const a=this.options.some(l=>!l.disabled&&!l.selected);this.options.forEach(l=>{l.disabled||(a?l.select():l.deselect())})}else{const a=i.activeItemIndex;i.onKeydown(e),this._multiple&&s&&e.shiftKey&&i.activeItem&&i.activeItemIndex!==a&&i.activeItem._selectViaInteraction()}else e.preventDefault(),i.activeItem._selectViaInteraction()}_onFocus(){this.disabled||(this._focused=!0,this.stateChanges.next())}_onBlur(){this._focused=!1,!this.disabled&&!this.panelOpen&&(this._onTouched(),this._changeDetectorRef.markForCheck(),this.stateChanges.next())}_onAttached(){this._overlayDir.positionChange.pipe(it(1)).subscribe(()=>{this._changeDetectorRef.detectChanges(),this._positioningSettled()})}_getPanelTheme(){return this._parentFormField?`mat-${this._parentFormField.color}`:\"\"}get empty(){return!this._selectionModel||this._selectionModel.isEmpty()}_initializeSelection(){Promise.resolve().then(()=>{this.ngControl&&(this._value=this.ngControl.value),this._setSelectionByValue(this._value),this.stateChanges.next()})}_setSelectionByValue(e){if(this._selectionModel.selected.forEach(i=>i.setInactiveStyles()),this._selectionModel.clear(),this.multiple&&e)Array.isArray(e),e.forEach(i=>this._selectValue(i)),this._sortValues();else{const i=this._selectValue(e);i?this._keyManager.updateActiveItem(i):this.panelOpen||this._keyManager.updateActiveItem(-1)}this._changeDetectorRef.markForCheck()}_selectValue(e){const i=this.options.find(r=>{if(this._selectionModel.isSelected(r))return!1;try{return null!=r.value&&this._compareWith(r.value,e)}catch(s){return!1}});return i&&this._selectionModel.select(i),i}_initKeyManager(){this._keyManager=new c3(this.options).withTypeAhead(this._typeaheadDebounceInterval).withVerticalOrientation().withHorizontalOrientation(this._isRtl()?\"rtl\":\"ltr\").withHomeAndEnd().withAllowedModifierKeys([\"shiftKey\"]),this._keyManager.tabOut.pipe(Ie(this._destroy)).subscribe(()=>{this.panelOpen&&(!this.multiple&&this._keyManager.activeItem&&this._keyManager.activeItem._selectViaInteraction(),this.focus(),this.close())}),this._keyManager.change.pipe(Ie(this._destroy)).subscribe(()=>{this._panelOpen&&this.panel?this._scrollOptionIntoView(this._keyManager.activeItemIndex||0):!this._panelOpen&&!this.multiple&&this._keyManager.activeItem&&this._keyManager.activeItem._selectViaInteraction()})}_resetOptions(){const e=Bt(this.options.changes,this._destroy);this.optionSelectionChanges.pipe(Ie(e)).subscribe(i=>{this._onSelect(i.source,i.isUserInput),i.isUserInput&&!this.multiple&&this._panelOpen&&(this.close(),this.focus())}),Bt(...this.options.map(i=>i._stateChanges)).pipe(Ie(e)).subscribe(()=>{this._changeDetectorRef.markForCheck(),this.stateChanges.next()})}_onSelect(e,i){const r=this._selectionModel.isSelected(e);null!=e.value||this._multiple?(r!==e.selected&&(e.selected?this._selectionModel.select(e):this._selectionModel.deselect(e)),i&&this._keyManager.setActiveItem(e),this.multiple&&(this._sortValues(),i&&this.focus())):(e.deselect(),this._selectionModel.clear(),null!=this.value&&this._propagateChanges(e.value)),r!==this._selectionModel.isSelected(e)&&this._propagateChanges(),this.stateChanges.next()}_sortValues(){if(this.multiple){const e=this.options.toArray();this._selectionModel.sort((i,r)=>this.sortComparator?this.sortComparator(i,r,e):e.indexOf(i)-e.indexOf(r)),this.stateChanges.next()}}_propagateChanges(e){let i=null;i=this.multiple?this.selected.map(r=>r.value):this.selected?this.selected.value:e,this._value=i,this.valueChange.emit(i),this._onChange(i),this.selectionChange.emit(this._getChangeEvent(i)),this._changeDetectorRef.markForCheck()}_highlightCorrectOption(){this._keyManager&&(this.empty?this._keyManager.setFirstItemActive():this._keyManager.setActiveItem(this._selectionModel.selected[0]))}_canOpen(){var e;return!this._panelOpen&&!this.disabled&&(null===(e=this.options)||void 0===e?void 0:e.length)>0}focus(e){this._elementRef.nativeElement.focus(e)}_getPanelAriaLabelledby(){var e;if(this.ariaLabel)return null;const i=null===(e=this._parentFormField)||void 0===e?void 0:e.getLabelId();return this.ariaLabelledby?(i?i+\" \":\"\")+this.ariaLabelledby:i}_getAriaActiveDescendant(){return this.panelOpen&&this._keyManager&&this._keyManager.activeItem?this._keyManager.activeItem.id:null}_getTriggerAriaLabelledby(){var e;if(this.ariaLabel)return null;const i=null===(e=this._parentFormField)||void 0===e?void 0:e.getLabelId();let r=(i?i+\" \":\"\")+this._valueId;return this.ariaLabelledby&&(r+=\" \"+this.ariaLabelledby),r}_panelDoneAnimating(e){this.openedChange.emit(e)}setDescribedByIds(e){this._ariaDescribedby=e.join(\" \")}onContainerClick(){this.focus(),this.open()}get shouldLabelFloat(){return this._panelOpen||!this.empty||this._focused&&!!this._placeholder}}return n.\\u0275fac=function(e){return new(e||n)(f(es),f(Ye),f(ne),f(mo),f(W),f(On,8),f(oo,8),f(ao,8),f(el,8),f(Jn,10),kt(\"tabindex\"),f(WE),f(k3),f(Q5,8))},n.\\u0275dir=C({type:n,viewQuery:function(e,i){if(1&e&&(je(L5,5),je(B5,5),je(HE,5)),2&e){let r;z(r=U())&&(i.trigger=r.first),z(r=U())&&(i.panel=r.first),z(r=U())&&(i._overlayDir=r.first)}},inputs:{panelClass:\"panelClass\",placeholder:\"placeholder\",required:\"required\",multiple:\"multiple\",disableOptionCentering:\"disableOptionCentering\",compareWith:\"compareWith\",value:\"value\",ariaLabel:[\"aria-label\",\"ariaLabel\"],ariaLabelledby:[\"aria-labelledby\",\"ariaLabelledby\"],errorStateMatcher:\"errorStateMatcher\",typeaheadDebounceInterval:\"typeaheadDebounceInterval\",sortComparator:\"sortComparator\",id:\"id\"},outputs:{openedChange:\"openedChange\",_openedStream:\"opened\",_closedStream:\"closed\",selectionChange:\"selectionChange\",valueChange:\"valueChange\"},features:[E,Je]}),n})(),t$=(()=>{class n extends e${constructor(){super(...arguments),this._scrollTop=0,this._triggerFontSize=0,this._transformOrigin=\"top\",this._offsetY=0,this._positions=[{originX:\"start\",originY:\"top\",overlayX:\"start\",overlayY:\"top\"},{originX:\"start\",originY:\"bottom\",overlayX:\"start\",overlayY:\"bottom\"}]}_calculateOverlayScroll(e,i,r){const s=this._getItemHeight();return Math.min(Math.max(0,s*e-i+s/2),r)}ngOnInit(){super.ngOnInit(),this._viewportRuler.change().pipe(Ie(this._destroy)).subscribe(()=>{this.panelOpen&&(this._triggerRect=this.trigger.nativeElement.getBoundingClientRect(),this._changeDetectorRef.markForCheck())})}open(){super._canOpen()&&(super.open(),this._triggerRect=this.trigger.nativeElement.getBoundingClientRect(),this._triggerFontSize=parseInt(getComputedStyle(this.trigger.nativeElement).fontSize||\"0\"),this._calculateOverlayPosition(),this._ngZone.onStable.pipe(it(1)).subscribe(()=>{this._triggerFontSize&&this._overlayDir.overlayRef&&this._overlayDir.overlayRef.overlayElement&&(this._overlayDir.overlayRef.overlayElement.style.fontSize=`${this._triggerFontSize}px`)}))}_scrollOptionIntoView(e){const i=cg(e,this.options,this.optionGroups),r=this._getItemHeight();this.panel.nativeElement.scrollTop=0===e&&1===i?0:function pE(n,t,e,i){return n<e?n:n+t>e+i?Math.max(0,n-i+t):e}((e+i)*r,r,this.panel.nativeElement.scrollTop,256)}_positioningSettled(){this._calculateOverlayOffsetX(),this.panel.nativeElement.scrollTop=this._scrollTop}_panelDoneAnimating(e){this.panelOpen?this._scrollTop=0:(this._overlayDir.offsetX=0,this._changeDetectorRef.markForCheck()),super._panelDoneAnimating(e)}_getChangeEvent(e){return new Z5(this,e)}_calculateOverlayOffsetX(){const e=this._overlayDir.overlayRef.overlayElement.getBoundingClientRect(),i=this._viewportRuler.getViewportSize(),r=this._isRtl(),s=this.multiple?56:32;let o;if(this.multiple)o=40;else if(this.disableOptionCentering)o=16;else{let c=this._selectionModel.selected[0]||this.options.first;o=c&&c.group?32:16}r||(o*=-1);const a=0-(e.left+o-(r?s:0)),l=e.right+o-i.width+(r?0:s);a>0?o+=a+8:l>0&&(o-=l+8),this._overlayDir.offsetX=Math.round(o),this._overlayDir.overlayRef.updatePosition()}_calculateOverlayOffsetY(e,i,r){const s=this._getItemHeight(),o=(s-this._triggerRect.height)/2,a=Math.floor(256/s);let l;return this.disableOptionCentering?0:(l=0===this._scrollTop?e*s:this._scrollTop===r?(e-(this._getItemCount()-a))*s+(s-(this._getItemCount()*s-256)%s):i-s/2,Math.round(-1*l-o))}_checkOverlayWithinViewport(e){const i=this._getItemHeight(),r=this._viewportRuler.getViewportSize(),s=this._triggerRect.top-8,o=r.height-this._triggerRect.bottom-8,a=Math.abs(this._offsetY),c=Math.min(this._getItemCount()*i,256)-a-this._triggerRect.height;c>o?this._adjustPanelUp(c,o):a>s?this._adjustPanelDown(a,s,e):this._transformOrigin=this._getOriginBasedOnOption()}_adjustPanelUp(e,i){const r=Math.round(e-i);this._scrollTop-=r,this._offsetY-=r,this._transformOrigin=this._getOriginBasedOnOption(),this._scrollTop<=0&&(this._scrollTop=0,this._offsetY=0,this._transformOrigin=\"50% bottom 0px\")}_adjustPanelDown(e,i,r){const s=Math.round(e-i);if(this._scrollTop+=s,this._offsetY+=s,this._transformOrigin=this._getOriginBasedOnOption(),this._scrollTop>=r)return this._scrollTop=r,this._offsetY=0,void(this._transformOrigin=\"50% top 0px\")}_calculateOverlayPosition(){const e=this._getItemHeight(),i=this._getItemCount(),r=Math.min(i*e,256),o=i*e-r;let a;a=this.empty?0:Math.max(this.options.toArray().indexOf(this._selectionModel.selected[0]),0),a+=cg(a,this.options,this.optionGroups);const l=r/2;this._scrollTop=this._calculateOverlayScroll(a,l,o),this._offsetY=this._calculateOverlayOffsetY(a,l,o),this._checkOverlayWithinViewport(o)}_getOriginBasedOnOption(){const e=this._getItemHeight(),i=(e-this._triggerRect.height)/2;return`50% ${Math.abs(this._offsetY)-i+e/2}px 0px`}_getItemHeight(){return 3*this._triggerFontSize}_getItemCount(){return this.options.length+this.optionGroups.length}}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275cmp=xe({type:n,selectors:[[\"mat-select\"]],contentQueries:function(e,i,r){if(1&e&&(ve(r,J5,5),ve(r,hE,5),ve(r,lg,5)),2&e){let s;z(s=U())&&(i.customTrigger=s.first),z(s=U())&&(i.options=s),z(s=U())&&(i.optionGroups=s)}},hostAttrs:[\"role\",\"combobox\",\"aria-autocomplete\",\"none\",\"aria-haspopup\",\"true\",1,\"mat-select\"],hostVars:20,hostBindings:function(e,i){1&e&&J(\"keydown\",function(s){return i._handleKeydown(s)})(\"focus\",function(){return i._onFocus()})(\"blur\",function(){return i._onBlur()}),2&e&&(Z(\"id\",i.id)(\"tabindex\",i.tabIndex)(\"aria-controls\",i.panelOpen?i.id+\"-panel\":null)(\"aria-expanded\",i.panelOpen)(\"aria-label\",i.ariaLabel||null)(\"aria-required\",i.required.toString())(\"aria-disabled\",i.disabled.toString())(\"aria-invalid\",i.errorState)(\"aria-describedby\",i._ariaDescribedby||null)(\"aria-activedescendant\",i._getAriaActiveDescendant()),Ae(\"mat-select-disabled\",i.disabled)(\"mat-select-invalid\",i.errorState)(\"mat-select-required\",i.required)(\"mat-select-empty\",i.empty)(\"mat-select-multiple\",i.multiple))},inputs:{disabled:\"disabled\",disableRipple:\"disableRipple\",tabIndex:\"tabIndex\"},exportAs:[\"matSelect\"],features:[L([{provide:Ja,useExisting:n},{provide:ag,useExisting:n}]),E],ngContentSelectors:G5,decls:9,vars:12,consts:[[\"cdk-overlay-origin\",\"\",1,\"mat-select-trigger\",3,\"click\"],[\"origin\",\"cdkOverlayOrigin\",\"trigger\",\"\"],[1,\"mat-select-value\",3,\"ngSwitch\"],[\"class\",\"mat-select-placeholder mat-select-min-line\",4,\"ngSwitchCase\"],[\"class\",\"mat-select-value-text\",3,\"ngSwitch\",4,\"ngSwitchCase\"],[1,\"mat-select-arrow-wrapper\"],[1,\"mat-select-arrow\"],[\"cdk-connected-overlay\",\"\",\"cdkConnectedOverlayLockPosition\",\"\",\"cdkConnectedOverlayHasBackdrop\",\"\",\"cdkConnectedOverlayBackdropClass\",\"cdk-overlay-transparent-backdrop\",3,\"cdkConnectedOverlayPanelClass\",\"cdkConnectedOverlayScrollStrategy\",\"cdkConnectedOverlayOrigin\",\"cdkConnectedOverlayOpen\",\"cdkConnectedOverlayPositions\",\"cdkConnectedOverlayMinWidth\",\"cdkConnectedOverlayOffsetY\",\"backdropClick\",\"attach\",\"detach\"],[1,\"mat-select-placeholder\",\"mat-select-min-line\"],[1,\"mat-select-value-text\",3,\"ngSwitch\"],[\"class\",\"mat-select-min-line\",4,\"ngSwitchDefault\"],[4,\"ngSwitchCase\"],[1,\"mat-select-min-line\"],[1,\"mat-select-panel-wrap\"],[\"role\",\"listbox\",\"tabindex\",\"-1\",3,\"ngClass\",\"keydown\"],[\"panel\",\"\"]],template:function(e,i){if(1&e&&(Lt($5),x(0,\"div\",0,1),J(\"click\",function(){return i.toggle()}),x(3,\"div\",2),Ee(4,V5,2,1,\"span\",3),Ee(5,z5,3,2,\"span\",4),S(),x(6,\"div\",5),Le(7,\"div\",6),S()(),Ee(8,U5,4,14,\"ng-template\",7),J(\"backdropClick\",function(){return i.close()})(\"attach\",function(){return i._onAttached()})(\"detach\",function(){return i.close()})),2&e){const r=wn(1);Z(\"aria-owns\",i.panelOpen?i.id+\"-panel\":null),T(3),N(\"ngSwitch\",i.empty),Z(\"id\",i._valueId),T(1),N(\"ngSwitchCase\",!0),T(1),N(\"ngSwitchCase\",!1),T(3),N(\"cdkConnectedOverlayPanelClass\",i._overlayPanelClass)(\"cdkConnectedOverlayScrollStrategy\",i._scrollStrategy)(\"cdkConnectedOverlayOrigin\",r)(\"cdkConnectedOverlayOpen\",i.panelOpen)(\"cdkConnectedOverlayPositions\",i._positions)(\"cdkConnectedOverlayMinWidth\",null==i._triggerRect?null:i._triggerRect.width)(\"cdkConnectedOverlayOffsetY\",i._offsetY)}},directives:[VE,Ys,Pc,yD,HE,mD],styles:['.mat-select{display:inline-block;width:100%;outline:none}.mat-select-trigger{display:inline-table;cursor:pointer;position:relative;box-sizing:border-box}.mat-select-disabled .mat-select-trigger{-webkit-user-select:none;-moz-user-select:none;user-select:none;cursor:default}.mat-select-value{display:table-cell;max-width:0;width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mat-select-value-text{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.mat-select-arrow-wrapper{display:table-cell;vertical-align:middle}.mat-form-field-appearance-fill .mat-select-arrow-wrapper{transform:translateY(-50%)}.mat-form-field-appearance-outline .mat-select-arrow-wrapper{transform:translateY(-25%)}.mat-form-field-appearance-standard.mat-form-field-has-label .mat-select:not(.mat-select-empty) .mat-select-arrow-wrapper{transform:translateY(-50%)}.mat-form-field-appearance-standard .mat-select.mat-select-empty .mat-select-arrow-wrapper{transition:transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1)}._mat-animation-noopable.mat-form-field-appearance-standard .mat-select.mat-select-empty .mat-select-arrow-wrapper{transition:none}.mat-select-arrow{width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;border-top:5px solid;margin:0 4px}.mat-form-field.mat-focused .mat-select-arrow{transform:translateX(0)}.mat-select-panel-wrap{flex-basis:100%}.mat-select-panel{min-width:112px;max-width:280px;overflow:auto;-webkit-overflow-scrolling:touch;padding-top:0;padding-bottom:0;max-height:256px;min-width:100%;border-radius:4px;outline:0}.cdk-high-contrast-active .mat-select-panel{outline:solid 1px}.mat-select-panel .mat-optgroup-label,.mat-select-panel .mat-option{font-size:inherit;line-height:3em;height:3em}.mat-form-field-type-mat-select:not(.mat-form-field-disabled) .mat-form-field-flex{cursor:pointer}.mat-form-field-type-mat-select .mat-form-field-label{width:calc(100% - 18px)}.mat-select-placeholder{transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}._mat-animation-noopable .mat-select-placeholder{transition:none}.mat-form-field-hide-placeholder .mat-select-placeholder{color:transparent;-webkit-text-fill-color:transparent;transition:none;display:block}.mat-select-min-line:empty::before{content:\" \";white-space:pre;width:1px;display:inline-block;opacity:0}\\n'],encapsulation:2,data:{animation:[UE.transformPanelWrap,UE.transformPanel]},changeDetection:0}),n})(),qE=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[K5],imports:[[bt,ji,Hd,B],Ci,mg,Hd,B]}),n})();const YE=ei({passive:!0});let n$=(()=>{class n{constructor(e,i){this._platform=e,this._ngZone=i,this._monitoredElements=new Map}monitor(e){if(!this._platform.isBrowser)return ri;const i=at(e),r=this._monitoredElements.get(i);if(r)return r.subject;const s=new O,o=\"cdk-text-field-autofilled\",a=l=>{\"cdk-text-field-autofill-start\"!==l.animationName||i.classList.contains(o)?\"cdk-text-field-autofill-end\"===l.animationName&&i.classList.contains(o)&&(i.classList.remove(o),this._ngZone.run(()=>s.next({target:l.target,isAutofilled:!1}))):(i.classList.add(o),this._ngZone.run(()=>s.next({target:l.target,isAutofilled:!0})))};return this._ngZone.runOutsideAngular(()=>{i.addEventListener(\"animationstart\",a,YE),i.classList.add(\"cdk-text-field-autofill-monitored\")}),this._monitoredElements.set(i,{subject:s,unlisten:()=>{i.removeEventListener(\"animationstart\",a,YE)}}),s}stopMonitoring(e){const i=at(e),r=this._monitoredElements.get(i);r&&(r.unlisten(),r.subject.complete(),i.classList.remove(\"cdk-text-field-autofill-monitored\"),i.classList.remove(\"cdk-text-field-autofilled\"),this._monitoredElements.delete(i))}ngOnDestroy(){this._monitoredElements.forEach((e,i)=>this.stopMonitoring(i))}}return n.\\u0275fac=function(e){return new(e||n)(y(It),y(ne))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),QE=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const KE=new b(\"MAT_INPUT_VALUE_ACCESSOR\"),i$=[\"button\",\"checkbox\",\"file\",\"hidden\",\"image\",\"radio\",\"range\",\"reset\",\"submit\"];let r$=0;const s$=ng(class{constructor(n,t,e,i){this._defaultErrorStateMatcher=n,this._parentForm=t,this._parentFormGroup=e,this.ngControl=i}});let o$=(()=>{class n extends s${constructor(e,i,r,s,o,a,l,c,d,u){super(a,s,o,r),this._elementRef=e,this._platform=i,this._autofillMonitor=c,this._formField=u,this._uid=\"mat-input-\"+r$++,this.focused=!1,this.stateChanges=new O,this.controlType=\"mat-input\",this.autofilled=!1,this._disabled=!1,this._type=\"text\",this._readonly=!1,this._neverEmptyInputTypes=[\"date\",\"datetime\",\"datetime-local\",\"month\",\"time\",\"week\"].filter(m=>Hx().has(m));const h=this._elementRef.nativeElement,p=h.nodeName.toLowerCase();this._inputValueAccessor=l||h,this._previousNativeValue=this.value,this.id=this.id,i.IOS&&d.runOutsideAngular(()=>{e.nativeElement.addEventListener(\"keyup\",m=>{const g=m.target;!g.value&&0===g.selectionStart&&0===g.selectionEnd&&(g.setSelectionRange(1,1),g.setSelectionRange(0,0))})}),this._isServer=!this._platform.isBrowser,this._isNativeSelect=\"select\"===p,this._isTextarea=\"textarea\"===p,this._isInFormField=!!u,this._isNativeSelect&&(this.controlType=h.multiple?\"mat-native-select-multiple\":\"mat-native-select\")}get disabled(){return this.ngControl&&null!==this.ngControl.disabled?this.ngControl.disabled:this._disabled}set disabled(e){this._disabled=G(e),this.focused&&(this.focused=!1,this.stateChanges.next())}get id(){return this._id}set id(e){this._id=e||this._uid}get required(){var e,i,r,s;return null!==(s=null!==(e=this._required)&&void 0!==e?e:null===(r=null===(i=this.ngControl)||void 0===i?void 0:i.control)||void 0===r?void 0:r.hasValidator(yi.required))&&void 0!==s&&s}set required(e){this._required=G(e)}get type(){return this._type}set type(e){this._type=e||\"text\",this._validateType(),!this._isTextarea&&Hx().has(this._type)&&(this._elementRef.nativeElement.type=this._type)}get value(){return this._inputValueAccessor.value}set value(e){e!==this.value&&(this._inputValueAccessor.value=e,this.stateChanges.next())}get readonly(){return this._readonly}set readonly(e){this._readonly=G(e)}ngAfterViewInit(){this._platform.isBrowser&&this._autofillMonitor.monitor(this._elementRef.nativeElement).subscribe(e=>{this.autofilled=e.isAutofilled,this.stateChanges.next()})}ngOnChanges(){this.stateChanges.next()}ngOnDestroy(){this.stateChanges.complete(),this._platform.isBrowser&&this._autofillMonitor.stopMonitoring(this._elementRef.nativeElement)}ngDoCheck(){this.ngControl&&this.updateErrorState(),this._dirtyCheckNativeValue(),this._dirtyCheckPlaceholder()}focus(e){this._elementRef.nativeElement.focus(e)}_focusChanged(e){e!==this.focused&&(this.focused=e,this.stateChanges.next())}_onInput(){}_dirtyCheckPlaceholder(){var e,i;const r=(null===(i=null===(e=this._formField)||void 0===e?void 0:e._hideControlPlaceholder)||void 0===i?void 0:i.call(e))?null:this.placeholder;if(r!==this._previousPlaceholder){const s=this._elementRef.nativeElement;this._previousPlaceholder=r,r?s.setAttribute(\"placeholder\",r):s.removeAttribute(\"placeholder\")}}_dirtyCheckNativeValue(){const e=this._elementRef.nativeElement.value;this._previousNativeValue!==e&&(this._previousNativeValue=e,this.stateChanges.next())}_validateType(){i$.indexOf(this._type)}_isNeverEmpty(){return this._neverEmptyInputTypes.indexOf(this._type)>-1}_isBadInput(){let e=this._elementRef.nativeElement.validity;return e&&e.badInput}get empty(){return!(this._isNeverEmpty()||this._elementRef.nativeElement.value||this._isBadInput()||this.autofilled)}get shouldLabelFloat(){if(this._isNativeSelect){const e=this._elementRef.nativeElement,i=e.options[0];return this.focused||e.multiple||!this.empty||!!(e.selectedIndex>-1&&i&&i.label)}return this.focused||!this.empty}setDescribedByIds(e){e.length?this._elementRef.nativeElement.setAttribute(\"aria-describedby\",e.join(\" \")):this._elementRef.nativeElement.removeAttribute(\"aria-describedby\")}onContainerClick(){this.focused||this.focus()}_isInlineSelect(){const e=this._elementRef.nativeElement;return this._isNativeSelect&&(e.multiple||e.size>1)}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(It),f(Jn,10),f(oo,8),f(ao,8),f(mo),f(KE,10),f(n$),f(ne),f(el,8))},n.\\u0275dir=C({type:n,selectors:[[\"input\",\"matInput\",\"\"],[\"textarea\",\"matInput\",\"\"],[\"select\",\"matNativeControl\",\"\"],[\"input\",\"matNativeControl\",\"\"],[\"textarea\",\"matNativeControl\",\"\"]],hostAttrs:[1,\"mat-input-element\",\"mat-form-field-autofill-control\"],hostVars:12,hostBindings:function(e,i){1&e&&J(\"focus\",function(){return i._focusChanged(!0)})(\"blur\",function(){return i._focusChanged(!1)})(\"input\",function(){return i._onInput()}),2&e&&(Yn(\"disabled\",i.disabled)(\"required\",i.required),Z(\"id\",i.id)(\"data-placeholder\",i.placeholder)(\"name\",i.name||null)(\"readonly\",i.readonly&&!i._isNativeSelect||null)(\"aria-invalid\",i.empty&&i.required?null:i.errorState)(\"aria-required\",i.required),Ae(\"mat-input-server\",i._isServer)(\"mat-native-select-inline\",i._isInlineSelect()))},inputs:{disabled:\"disabled\",id:\"id\",placeholder:\"placeholder\",name:\"name\",required:\"required\",type:\"type\",errorStateMatcher:\"errorStateMatcher\",userAriaDescribedBy:[\"aria-describedby\",\"userAriaDescribedBy\"],value:\"value\",readonly:\"readonly\"},exportAs:[\"matInput\"],features:[L([{provide:Ja,useExisting:n}]),E,Je]}),n})(),a$=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[mo],imports:[[QE,mg,B],QE,mg]}),n})();function l$(n,t){if(1&n&&(x(0,\"mat-option\",13),we(1),S()),2&n){const e=t.$implicit;N(\"value\",e.name)(\"disabled\",e.disabled),T(1),Ut(e.description)}}function c$(n,t){if(1&n&&(x(0,\"mat-option\",13),we(1),S()),2&n){const e=t.$implicit,i=t.index;N(\"value\",e)(\"disabled\",i>0),T(1),Ut(e)}}function d$(n,t){if(1&n&&(x(0,\"mat-error\"),we(1),S()),2&n){const e=Be();T(1),Ut(e.explainTheError(e.srcAmountControl))}}function u$(n,t){if(1&n&&(x(0,\"mat-option\",13),we(1),S()),2&n){const e=t.$implicit;N(\"value\",e.name)(\"disabled\",e.disabled),T(1),Ut(e.description)}}function h$(n,t){if(1&n&&(x(0,\"mat-option\",13),we(1),S()),2&n){const e=t.$implicit,i=t.index;N(\"value\",e)(\"disabled\",i>0),T(1),Ut(e)}}function p$(n,t){if(1&n&&(x(0,\"mat-error\"),we(1),S()),2&n){const e=Be();T(1),Ut(e.explainTheError(e.dstAmountControl))}}let f$=(()=>{class n{constructor(){var e,i;this.srcAmountControl=new Rd(\"0\",[yi.pattern(/\\d+/),yi.min(1),yi.max(9999)]),this.dstAmountControl=new Rd(\"0\",[yi.pattern(/\\d+/),yi.min(1),yi.max(9999)]),this.srcChainList=Xa.map(r=>Object.assign(Object.assign({},r.from),{disabled:!r.active})),this.dstChainList=Xa.map(r=>Object.assign(Object.assign({},r.to),{disabled:!r.active})),this.srcChain=null===(e=this.srcChainList.find(r=>!r.disabled))||void 0===e?void 0:e.name,this.dstChain=(null===(i=Xa.filter(r=>r.from.name===this.srcChain).find(r=>r.active))||void 0===i?void 0:i.to.name)||\"\",this.srcCoin=\"EVER\",this.dstCoin=\"TXZ\",this.srcTokenList=ug.map(r=>r.name),this.dstTokenList=hg.map(r=>r.name),this.srcTokenChosen=\"EVER\",this.dstTokenChosen=\"wEVER\",this.srcAmount=\"0\",this.dstAmount=\"0\"}ngOnInit(){this.breakpoint=window.innerWidth<=400?1:2}onChainSrcValueChange(e){var i;this.srcChain=e,this.dstChain=(null===(i=Xa.filter(r=>r.from.name===this.srcChain).find(r=>r.active))||void 0===i?void 0:i.to.name)||\"\",this.changeTokenList(this.srcChain,this.dstChain)}onChainDstValueChange(e){var i;this.dstChain=e,this.srcChain=(null===(i=Xa.filter(r=>r.from.name===this.srcChain).find(r=>r.active))||void 0===i?void 0:i.to.name)||\"\",this.changeTokenList(this.srcChain,this.dstChain)}changeTokenList(e,i){\"Tezos\"==e&&(this.srcCoin=\"TXZ\",this.dstCoin=\"EVER\",this.srcTokenList=hg.map(r=>r.name),this.dstTokenList=ug.map(r=>r.name),this.srcTokenChosen=\"TXZ\",this.dstTokenChosen=\"wTXZ\"),\"Everscale\"===e&&(this.srcCoin=\"EVER\",this.dstCoin=\"TXZ\",this.srcTokenList=ug.map(r=>r.name),this.dstTokenList=hg.map(r=>r.name),this.srcTokenChosen=\"EVER\",this.dstTokenChosen=\"wEVER\")}onSelectionChange(e){console.log(\"onSelectionChange, newValue = \",e.value,e.source)}onSrcTokenChange(e){this.dstTokenChosen=e===this.srcTokenList[0]?this.dstCoin:this.dstTokenList[0]}onDstTokenChange(e){this.srcTokenChosen=e===this.dstTokenList[0]?this.srcCoin:this.srcTokenList[0]}calculateAmount(e,i){e?(this.dstAmount=(.99*Number.parseFloat(i)).toFixed(8).replace(/(\\.\\d*)0+/,\"$1\"),this.dstAmountControl.setValue(this.dstAmount)):(this.srcAmount=(Number.parseFloat(i)/.99).toFixed(8).replace(/\\.0+$/,\"\"),this.srcAmountControl.setValue(this.srcAmount))}explainTheError(e){const i=e.errors||{};return\"Wrong number: \"+Object.keys(i).reduce((r,s)=>{switch(s){case\"min\":return r+`minimal value is ${i[s].min}. `;case\"max\":return r+`maximum value is ${i[s].max}. `;case\"pattern\":return r+\"it should be number. \";default:return r+\"wrong amount. \"}},\"\")}consoleLog(e){console.log(e)}onResize(e){this.breakpoint=e.target.innerWidth<=400?1:2}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275cmp=xe({type:n,selectors:[[\"app-main\"]],decls:56,vars:21,consts:[[3,\"cols\",\"resize\"],[1,\"container\"],[\"appearance\",\"outline\"],[3,\"value\",\"valueChange\",\"selectionChange\"],[3,\"value\",\"disabled\",4,\"ngFor\",\"ngForOf\"],[3,\"value\",\"valueChange\"],[\"label\",\"Native coins\"],[3,\"value\"],[\"label\",\"Tokens\"],[\"matInput\",\"\",\"placeholder\",\"Amount\",\"type\",\"number\",3,\"value\",\"formControl\",\"change\"],[\"srcInputElement\",\"\"],[4,\"ngIf\"],[\"dstInputElement\",\"\"],[3,\"value\",\"disabled\"]],template:function(e,i){if(1&e){const r=ia();x(0,\"h1\"),we(1,\"Everscale-Tezos Bridge\"),S(),x(2,\"mat-grid-list\",0),J(\"resize\",function(o){return i.onResize(o)},!1,Uv),x(3,\"mat-grid-tile\")(4,\"div\",1)(5,\"h3\"),we(6,\"Choose what you have:\"),S(),x(7,\"mat-form-field\",2)(8,\"mat-label\"),we(9,\"Blockchain\"),S(),x(10,\"mat-select\",3),J(\"valueChange\",function(o){return i.srcChain=o})(\"selectionChange\",function(o){return i.onSelectionChange(o)})(\"valueChange\",function(o){return i.onChainSrcValueChange(o)}),Ee(11,l$,2,3,\"mat-option\",4),S()(),x(12,\"mat-form-field\",2)(13,\"mat-label\"),we(14,\"Token\"),S(),x(15,\"mat-select\",5),J(\"valueChange\",function(o){return i.srcTokenChosen=o})(\"valueChange\",function(o){return i.onSrcTokenChange(o)}),x(16,\"mat-optgroup\",6)(17,\"mat-option\",7),we(18),S()(),x(19,\"mat-optgroup\",8),Ee(20,c$,2,3,\"mat-option\",4),S()()(),x(21,\"mat-form-field\",2)(22,\"mat-label\"),we(23,\"Amount\"),S(),x(24,\"input\",9,10),J(\"change\",function(){Dr(r);const o=wn(25);return i.calculateAmount(!0,o.value)}),S(),x(26,\"mat-hint\"),we(27),S(),Ee(28,d$,2,1,\"mat-error\",11),S()()(),x(29,\"mat-grid-tile\")(30,\"div\",1)(31,\"h3\"),we(32,\"Choose what you want:\"),S(),x(33,\"mat-form-field\",2)(34,\"mat-label\"),we(35,\"Blockchain\"),S(),x(36,\"mat-select\",5),J(\"valueChange\",function(o){return i.dstChain=o})(\"valueChange\",function(o){return i.onChainDstValueChange(o)}),Ee(37,u$,2,3,\"mat-option\",4),S()(),x(38,\"mat-form-field\",2)(39,\"mat-label\"),we(40,\"Token\"),S(),x(41,\"mat-select\",5),J(\"valueChange\",function(o){return i.dstTokenChosen=o})(\"valueChange\",function(o){return i.onDstTokenChange(o)}),x(42,\"mat-optgroup\",6)(43,\"mat-option\",7),we(44),S()(),x(45,\"mat-optgroup\",8),Ee(46,h$,2,3,\"mat-option\",4),S()()(),x(47,\"mat-form-field\",2)(48,\"mat-label\"),we(49,\"Amount\"),S(),x(50,\"input\",9,12),J(\"change\",function(){Dr(r);const o=wn(51);return i.calculateAmount(!1,o.value)}),S(),Ee(52,p$,2,1,\"mat-error\",11),x(53,\"mat-hint\"),we(54),S()()()(),Le(55,\"router-outlet\"),S()}2&e&&(T(2),N(\"cols\",i.breakpoint),T(8),N(\"value\",i.srcChain),T(1),N(\"ngForOf\",i.srcChainList),T(4),N(\"value\",i.srcTokenChosen),T(2),N(\"value\",i.srcCoin),T(1),Ut(i.srcCoin),T(2),N(\"ngForOf\",i.srcTokenList),T(4),N(\"value\",i.srcAmount)(\"formControl\",i.srcAmountControl),T(3),qn(\"Amount of \",i.srcTokenChosen,\" to pay\"),T(1),N(\"ngIf\",i.srcAmountControl.invalid),T(8),N(\"value\",i.dstChain),T(1),N(\"ngForOf\",i.dstChainList),T(4),N(\"value\",i.dstTokenChosen),T(2),N(\"value\",i.dstCoin),T(1),Ut(i.dstCoin),T(2),N(\"ngForOf\",i.dstTokenList),T(4),N(\"value\",i.dstAmount)(\"formControl\",i.dstAmountControl),T(2),N(\"ngIf\",i.dstAmountControl.invalid),T(2),qn(\"Amount of \",i.dstTokenChosen,\" to receive\"))},directives:[bU,yE,t5,fg,t$,gD,hE,J3,o$,Tm,Dd,ax,Im,YU,Ca,GU,Pf],styles:[\".container[_ngcontent-%COMP%] .mat-form-field[_ngcontent-%COMP%] + .mat-form-field[_ngcontent-%COMP%]{margin-left:8px}mat-form-field[_ngcontent-%COMP%]{display:block}mat-grid-list[_ngcontent-%COMP%]{display:flex;flex-wrap:wrap;justify-content:center}\"]}),n})(),ZE=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),m$=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();function wg(n,t,e){for(let i in t)if(t.hasOwnProperty(i)){const r=t[i];r?n.setProperty(i,r,(null==e?void 0:e.has(i))?\"important\":\"\"):n.removeProperty(i)}return n}function _o(n,t){const e=t?\"\":\"none\";wg(n.style,{\"touch-action\":t?\"\":\"none\",\"-webkit-user-drag\":t?\"\":\"none\",\"-webkit-tap-highlight-color\":t?\"\":\"transparent\",\"user-select\":e,\"-ms-user-select\":e,\"-webkit-user-select\":e,\"-moz-user-select\":e})}function XE(n,t,e){wg(n.style,{position:t?\"\":\"fixed\",top:t?\"\":\"0\",opacity:t?\"\":\"0\",left:t?\"\":\"-999em\"},e)}function Yd(n,t){return t&&\"none\"!=t?n+\" \"+t:n}function JE(n){const t=n.toLowerCase().indexOf(\"ms\")>-1?1:1e3;return parseFloat(n)*t}function Mg(n,t){return n.getPropertyValue(t).split(\",\").map(i=>i.trim())}function xg(n){const t=n.getBoundingClientRect();return{top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:t.width,height:t.height,x:t.x,y:t.y}}function Eg(n,t,e){const{top:i,bottom:r,left:s,right:o}=n;return e>=i&&e<=r&&t>=s&&t<=o}function sl(n,t,e){n.top+=t,n.bottom=n.top+n.height,n.left+=e,n.right=n.left+n.width}function eS(n,t,e,i){const{top:r,right:s,bottom:o,left:a,width:l,height:c}=n,d=l*t,u=c*t;return i>r-u&&i<o+u&&e>a-d&&e<s+d}class tS{constructor(t){this._document=t,this.positions=new Map}clear(){this.positions.clear()}cache(t){this.clear(),this.positions.set(this._document,{scrollPosition:this.getViewportScrollPosition()}),t.forEach(e=>{this.positions.set(e,{scrollPosition:{top:e.scrollTop,left:e.scrollLeft},clientRect:xg(e)})})}handleScroll(t){const e=Pn(t),i=this.positions.get(e);if(!i)return null;const r=i.scrollPosition;let s,o;if(e===this._document){const c=this.getViewportScrollPosition();s=c.top,o=c.left}else s=e.scrollTop,o=e.scrollLeft;const a=r.top-s,l=r.left-o;return this.positions.forEach((c,d)=>{c.clientRect&&e!==d&&e.contains(d)&&sl(c.clientRect,a,l)}),r.top=s,r.left=o,{top:a,left:l}}getViewportScrollPosition(){return{top:window.scrollY,left:window.scrollX}}}function nS(n){const t=n.cloneNode(!0),e=t.querySelectorAll(\"[id]\"),i=n.nodeName.toLowerCase();t.removeAttribute(\"id\");for(let r=0;r<e.length;r++)e[r].removeAttribute(\"id\");return\"canvas\"===i?sS(n,t):(\"input\"===i||\"select\"===i||\"textarea\"===i)&&rS(n,t),iS(\"canvas\",n,t,sS),iS(\"input, textarea, select\",n,t,rS),t}function iS(n,t,e,i){const r=t.querySelectorAll(n);if(r.length){const s=e.querySelectorAll(n);for(let o=0;o<r.length;o++)i(r[o],s[o])}}let v$=0;function rS(n,t){\"file\"!==t.type&&(t.value=n.value),\"radio\"===t.type&&t.name&&(t.name=`mat-clone-${t.name}-${v$++}`)}function sS(n,t){const e=t.getContext(\"2d\");if(e)try{e.drawImage(n,0,0)}catch(i){}}const oS=ei({passive:!0}),Qd=ei({passive:!1}),Sg=new Set([\"position\"]);class b${constructor(t,e,i,r,s,o){this._config=e,this._document=i,this._ngZone=r,this._viewportRuler=s,this._dragDropRegistry=o,this._passiveTransform={x:0,y:0},this._activeTransform={x:0,y:0},this._hasStartedDragging=!1,this._moveEvents=new O,this._pointerMoveSubscription=ke.EMPTY,this._pointerUpSubscription=ke.EMPTY,this._scrollSubscription=ke.EMPTY,this._resizeSubscription=ke.EMPTY,this._boundaryElement=null,this._nativeInteractionsEnabled=!0,this._handles=[],this._disabledHandles=new Set,this._direction=\"ltr\",this.dragStartDelay=0,this._disabled=!1,this.beforeStarted=new O,this.started=new O,this.released=new O,this.ended=new O,this.entered=new O,this.exited=new O,this.dropped=new O,this.moved=this._moveEvents,this._pointerDown=a=>{if(this.beforeStarted.next(),this._handles.length){const l=this._getTargetHandle(a);l&&!this._disabledHandles.has(l)&&!this.disabled&&this._initializeDragSequence(l,a)}else this.disabled||this._initializeDragSequence(this._rootElement,a)},this._pointerMove=a=>{const l=this._getPointerPositionOnPage(a);if(!this._hasStartedDragging){if(Math.abs(l.x-this._pickupPositionOnPage.x)+Math.abs(l.y-this._pickupPositionOnPage.y)>=this._config.dragStartThreshold){const p=Date.now()>=this._dragStartTime+this._getDragStartDelay(a),m=this._dropContainer;if(!p)return void this._endDragSequence(a);(!m||!m.isDragging()&&!m.isReceiving())&&(a.preventDefault(),this._hasStartedDragging=!0,this._ngZone.run(()=>this._startDragSequence(a)))}return}a.preventDefault();const c=this._getConstrainedPointerPosition(l);if(this._hasMoved=!0,this._lastKnownPointerPosition=l,this._updatePointerDirectionDelta(c),this._dropContainer)this._updateActiveDropContainer(c,l);else{const d=this._activeTransform;d.x=c.x-this._pickupPositionOnPage.x+this._passiveTransform.x,d.y=c.y-this._pickupPositionOnPage.y+this._passiveTransform.y,this._applyRootElementTransform(d.x,d.y)}this._moveEvents.observers.length&&this._ngZone.run(()=>{this._moveEvents.next({source:this,pointerPosition:c,event:a,distance:this._getDragDistance(c),delta:this._pointerDirectionDelta})})},this._pointerUp=a=>{this._endDragSequence(a)},this._nativeDragStart=a=>{if(this._handles.length){const l=this._getTargetHandle(a);l&&!this._disabledHandles.has(l)&&!this.disabled&&a.preventDefault()}else this.disabled||a.preventDefault()},this.withRootElement(t).withParent(e.parentDragRef||null),this._parentPositions=new tS(i),o.registerDragItem(this)}get disabled(){return this._disabled||!(!this._dropContainer||!this._dropContainer.disabled)}set disabled(t){const e=G(t);e!==this._disabled&&(this._disabled=e,this._toggleNativeDragInteractions(),this._handles.forEach(i=>_o(i,e)))}getPlaceholderElement(){return this._placeholder}getRootElement(){return this._rootElement}getVisibleElement(){return this.isDragging()?this.getPlaceholderElement():this.getRootElement()}withHandles(t){this._handles=t.map(i=>at(i)),this._handles.forEach(i=>_o(i,this.disabled)),this._toggleNativeDragInteractions();const e=new Set;return this._disabledHandles.forEach(i=>{this._handles.indexOf(i)>-1&&e.add(i)}),this._disabledHandles=e,this}withPreviewTemplate(t){return this._previewTemplate=t,this}withPlaceholderTemplate(t){return this._placeholderTemplate=t,this}withRootElement(t){const e=at(t);return e!==this._rootElement&&(this._rootElement&&this._removeRootElementListeners(this._rootElement),this._ngZone.runOutsideAngular(()=>{e.addEventListener(\"mousedown\",this._pointerDown,Qd),e.addEventListener(\"touchstart\",this._pointerDown,oS),e.addEventListener(\"dragstart\",this._nativeDragStart,Qd)}),this._initialTransform=void 0,this._rootElement=e),\"undefined\"!=typeof SVGElement&&this._rootElement instanceof SVGElement&&(this._ownerSVGElement=this._rootElement.ownerSVGElement),this}withBoundaryElement(t){return this._boundaryElement=t?at(t):null,this._resizeSubscription.unsubscribe(),t&&(this._resizeSubscription=this._viewportRuler.change(10).subscribe(()=>this._containInsideBoundaryOnResize())),this}withParent(t){return this._parentDragRef=t,this}dispose(){var t,e;this._removeRootElementListeners(this._rootElement),this.isDragging()&&(null===(t=this._rootElement)||void 0===t||t.remove()),null===(e=this._anchor)||void 0===e||e.remove(),this._destroyPreview(),this._destroyPlaceholder(),this._dragDropRegistry.removeDragItem(this),this._removeSubscriptions(),this.beforeStarted.complete(),this.started.complete(),this.released.complete(),this.ended.complete(),this.entered.complete(),this.exited.complete(),this.dropped.complete(),this._moveEvents.complete(),this._handles=[],this._disabledHandles.clear(),this._dropContainer=void 0,this._resizeSubscription.unsubscribe(),this._parentPositions.clear(),this._boundaryElement=this._rootElement=this._ownerSVGElement=this._placeholderTemplate=this._previewTemplate=this._anchor=this._parentDragRef=null}isDragging(){return this._hasStartedDragging&&this._dragDropRegistry.isDragging(this)}reset(){this._rootElement.style.transform=this._initialTransform||\"\",this._activeTransform={x:0,y:0},this._passiveTransform={x:0,y:0}}disableHandle(t){!this._disabledHandles.has(t)&&this._handles.indexOf(t)>-1&&(this._disabledHandles.add(t),_o(t,!0))}enableHandle(t){this._disabledHandles.has(t)&&(this._disabledHandles.delete(t),_o(t,this.disabled))}withDirection(t){return this._direction=t,this}_withDropContainer(t){this._dropContainer=t}getFreeDragPosition(){const t=this.isDragging()?this._activeTransform:this._passiveTransform;return{x:t.x,y:t.y}}setFreeDragPosition(t){return this._activeTransform={x:0,y:0},this._passiveTransform.x=t.x,this._passiveTransform.y=t.y,this._dropContainer||this._applyRootElementTransform(t.x,t.y),this}withPreviewContainer(t){return this._previewContainer=t,this}_sortFromLastPointerPosition(){const t=this._lastKnownPointerPosition;t&&this._dropContainer&&this._updateActiveDropContainer(this._getConstrainedPointerPosition(t),t)}_removeSubscriptions(){this._pointerMoveSubscription.unsubscribe(),this._pointerUpSubscription.unsubscribe(),this._scrollSubscription.unsubscribe()}_destroyPreview(){var t,e;null===(t=this._preview)||void 0===t||t.remove(),null===(e=this._previewRef)||void 0===e||e.destroy(),this._preview=this._previewRef=null}_destroyPlaceholder(){var t,e;null===(t=this._placeholder)||void 0===t||t.remove(),null===(e=this._placeholderRef)||void 0===e||e.destroy(),this._placeholder=this._placeholderRef=null}_endDragSequence(t){if(this._dragDropRegistry.isDragging(this)&&(this._removeSubscriptions(),this._dragDropRegistry.stopDragging(this),this._toggleNativeDragInteractions(),this._handles&&(this._rootElement.style.webkitTapHighlightColor=this._rootElementTapHighlight),this._hasStartedDragging))if(this.released.next({source:this}),this._dropContainer)this._dropContainer._stopScrolling(),this._animatePreviewToPlaceholder().then(()=>{this._cleanupDragArtifacts(t),this._cleanupCachedDimensions(),this._dragDropRegistry.stopDragging(this)});else{this._passiveTransform.x=this._activeTransform.x;const e=this._getPointerPositionOnPage(t);this._passiveTransform.y=this._activeTransform.y,this._ngZone.run(()=>{this.ended.next({source:this,distance:this._getDragDistance(e),dropPoint:e})}),this._cleanupCachedDimensions(),this._dragDropRegistry.stopDragging(this)}}_startDragSequence(t){ol(t)&&(this._lastTouchEventTime=Date.now()),this._toggleNativeDragInteractions();const e=this._dropContainer;if(e){const i=this._rootElement,r=i.parentNode,s=this._placeholder=this._createPlaceholderElement(),o=this._anchor=this._anchor||this._document.createComment(\"\"),a=this._getShadowRoot();r.insertBefore(o,i),this._initialTransform=i.style.transform||\"\",this._preview=this._createPreviewElement(),XE(i,!1,Sg),this._document.body.appendChild(r.replaceChild(s,i)),this._getPreviewInsertionPoint(r,a).appendChild(this._preview),this.started.next({source:this}),e.start(),this._initialContainer=e,this._initialIndex=e.getItemIndex(this)}else this.started.next({source:this}),this._initialContainer=this._initialIndex=void 0;this._parentPositions.cache(e?e.getScrollableParents():[])}_initializeDragSequence(t,e){this._parentDragRef&&e.stopPropagation();const i=this.isDragging(),r=ol(e),s=!r&&0!==e.button,o=this._rootElement,a=Pn(e),l=!r&&this._lastTouchEventTime&&this._lastTouchEventTime+800>Date.now(),c=r?Zm(e):Km(e);if(a&&a.draggable&&\"mousedown\"===e.type&&e.preventDefault(),i||s||l||c)return;if(this._handles.length){const h=o.style;this._rootElementTapHighlight=h.webkitTapHighlightColor||\"\",h.webkitTapHighlightColor=\"transparent\"}this._hasStartedDragging=this._hasMoved=!1,this._removeSubscriptions(),this._pointerMoveSubscription=this._dragDropRegistry.pointerMove.subscribe(this._pointerMove),this._pointerUpSubscription=this._dragDropRegistry.pointerUp.subscribe(this._pointerUp),this._scrollSubscription=this._dragDropRegistry.scrolled(this._getShadowRoot()).subscribe(h=>this._updateOnScroll(h)),this._boundaryElement&&(this._boundaryRect=xg(this._boundaryElement));const d=this._previewTemplate;this._pickupPositionInElement=d&&d.template&&!d.matchSize?{x:0,y:0}:this._getPointerPositionInElement(t,e);const u=this._pickupPositionOnPage=this._lastKnownPointerPosition=this._getPointerPositionOnPage(e);this._pointerDirectionDelta={x:0,y:0},this._pointerPositionAtLastDirectionChange={x:u.x,y:u.y},this._dragStartTime=Date.now(),this._dragDropRegistry.startDragging(this,e)}_cleanupDragArtifacts(t){XE(this._rootElement,!0,Sg),this._anchor.parentNode.replaceChild(this._rootElement,this._anchor),this._destroyPreview(),this._destroyPlaceholder(),this._boundaryRect=this._previewRect=this._initialTransform=void 0,this._ngZone.run(()=>{const e=this._dropContainer,i=e.getItemIndex(this),r=this._getPointerPositionOnPage(t),s=this._getDragDistance(r),o=e._isOverContainer(r.x,r.y);this.ended.next({source:this,distance:s,dropPoint:r}),this.dropped.next({item:this,currentIndex:i,previousIndex:this._initialIndex,container:e,previousContainer:this._initialContainer,isPointerOverContainer:o,distance:s,dropPoint:r}),e.drop(this,i,this._initialIndex,this._initialContainer,o,s,r),this._dropContainer=this._initialContainer})}_updateActiveDropContainer({x:t,y:e},{x:i,y:r}){let s=this._initialContainer._getSiblingContainerFromPosition(this,t,e);!s&&this._dropContainer!==this._initialContainer&&this._initialContainer._isOverContainer(t,e)&&(s=this._initialContainer),s&&s!==this._dropContainer&&this._ngZone.run(()=>{this.exited.next({item:this,container:this._dropContainer}),this._dropContainer.exit(this),this._dropContainer=s,this._dropContainer.enter(this,t,e,s===this._initialContainer&&s.sortingDisabled?this._initialIndex:void 0),this.entered.next({item:this,container:s,currentIndex:s.getItemIndex(this)})}),this.isDragging()&&(this._dropContainer._startScrollingIfNecessary(i,r),this._dropContainer._sortItem(this,t,e,this._pointerDirectionDelta),this._applyPreviewTransform(t-this._pickupPositionInElement.x,e-this._pickupPositionInElement.y))}_createPreviewElement(){const t=this._previewTemplate,e=this.previewClass,i=t?t.template:null;let r;if(i&&t){const s=t.matchSize?this._rootElement.getBoundingClientRect():null,o=t.viewContainer.createEmbeddedView(i,t.context);o.detectChanges(),r=lS(o,this._document),this._previewRef=o,t.matchSize?cS(r,s):r.style.transform=Kd(this._pickupPositionOnPage.x,this._pickupPositionOnPage.y)}else{const s=this._rootElement;r=nS(s),cS(r,s.getBoundingClientRect()),this._initialTransform&&(r.style.transform=this._initialTransform)}return wg(r.style,{\"pointer-events\":\"none\",margin:\"0\",position:\"fixed\",top:\"0\",left:\"0\",\"z-index\":`${this._config.zIndex||1e3}`},Sg),_o(r,!1),r.classList.add(\"cdk-drag-preview\"),r.setAttribute(\"dir\",this._direction),e&&(Array.isArray(e)?e.forEach(s=>r.classList.add(s)):r.classList.add(e)),r}_animatePreviewToPlaceholder(){if(!this._hasMoved)return Promise.resolve();const t=this._placeholder.getBoundingClientRect();this._preview.classList.add(\"cdk-drag-animating\"),this._applyPreviewTransform(t.left,t.top);const e=function _$(n){const t=getComputedStyle(n),e=Mg(t,\"transition-property\"),i=e.find(a=>\"transform\"===a||\"all\"===a);if(!i)return 0;const r=e.indexOf(i),s=Mg(t,\"transition-duration\"),o=Mg(t,\"transition-delay\");return JE(s[r])+JE(o[r])}(this._preview);return 0===e?Promise.resolve():this._ngZone.runOutsideAngular(()=>new Promise(i=>{const r=o=>{var a;(!o||Pn(o)===this._preview&&\"transform\"===o.propertyName)&&(null===(a=this._preview)||void 0===a||a.removeEventListener(\"transitionend\",r),i(),clearTimeout(s))},s=setTimeout(r,1.5*e);this._preview.addEventListener(\"transitionend\",r)}))}_createPlaceholderElement(){const t=this._placeholderTemplate,e=t?t.template:null;let i;return e?(this._placeholderRef=t.viewContainer.createEmbeddedView(e,t.context),this._placeholderRef.detectChanges(),i=lS(this._placeholderRef,this._document)):i=nS(this._rootElement),i.style.pointerEvents=\"none\",i.classList.add(\"cdk-drag-placeholder\"),i}_getPointerPositionInElement(t,e){const i=this._rootElement.getBoundingClientRect(),r=t===this._rootElement?null:t,s=r?r.getBoundingClientRect():i,o=ol(e)?e.targetTouches[0]:e,a=this._getViewportScrollPosition();return{x:s.left-i.left+(o.pageX-s.left-a.left),y:s.top-i.top+(o.pageY-s.top-a.top)}}_getPointerPositionOnPage(t){const e=this._getViewportScrollPosition(),i=ol(t)?t.touches[0]||t.changedTouches[0]||{pageX:0,pageY:0}:t,r=i.pageX-e.left,s=i.pageY-e.top;if(this._ownerSVGElement){const o=this._ownerSVGElement.getScreenCTM();if(o){const a=this._ownerSVGElement.createSVGPoint();return a.x=r,a.y=s,a.matrixTransform(o.inverse())}}return{x:r,y:s}}_getConstrainedPointerPosition(t){const e=this._dropContainer?this._dropContainer.lockAxis:null;let{x:i,y:r}=this.constrainPosition?this.constrainPosition(t,this):t;if(\"x\"===this.lockAxis||\"x\"===e?r=this._pickupPositionOnPage.y:(\"y\"===this.lockAxis||\"y\"===e)&&(i=this._pickupPositionOnPage.x),this._boundaryRect){const{x:s,y:o}=this._pickupPositionInElement,a=this._boundaryRect,{width:l,height:c}=this._getPreviewRect(),d=a.top+o,u=a.bottom-(c-o);i=aS(i,a.left+s,a.right-(l-s)),r=aS(r,d,u)}return{x:i,y:r}}_updatePointerDirectionDelta(t){const{x:e,y:i}=t,r=this._pointerDirectionDelta,s=this._pointerPositionAtLastDirectionChange,o=Math.abs(e-s.x),a=Math.abs(i-s.y);return o>this._config.pointerDirectionChangeThreshold&&(r.x=e>s.x?1:-1,s.x=e),a>this._config.pointerDirectionChangeThreshold&&(r.y=i>s.y?1:-1,s.y=i),r}_toggleNativeDragInteractions(){if(!this._rootElement||!this._handles)return;const t=this._handles.length>0||!this.isDragging();t!==this._nativeInteractionsEnabled&&(this._nativeInteractionsEnabled=t,_o(this._rootElement,t))}_removeRootElementListeners(t){t.removeEventListener(\"mousedown\",this._pointerDown,Qd),t.removeEventListener(\"touchstart\",this._pointerDown,oS),t.removeEventListener(\"dragstart\",this._nativeDragStart,Qd)}_applyRootElementTransform(t,e){const i=Kd(t,e),r=this._rootElement.style;null==this._initialTransform&&(this._initialTransform=r.transform&&\"none\"!=r.transform?r.transform:\"\"),r.transform=Yd(i,this._initialTransform)}_applyPreviewTransform(t,e){var i;const r=(null===(i=this._previewTemplate)||void 0===i?void 0:i.template)?void 0:this._initialTransform,s=Kd(t,e);this._preview.style.transform=Yd(s,r)}_getDragDistance(t){const e=this._pickupPositionOnPage;return e?{x:t.x-e.x,y:t.y-e.y}:{x:0,y:0}}_cleanupCachedDimensions(){this._boundaryRect=this._previewRect=void 0,this._parentPositions.clear()}_containInsideBoundaryOnResize(){let{x:t,y:e}=this._passiveTransform;if(0===t&&0===e||this.isDragging()||!this._boundaryElement)return;const i=this._boundaryElement.getBoundingClientRect(),r=this._rootElement.getBoundingClientRect();if(0===i.width&&0===i.height||0===r.width&&0===r.height)return;const s=i.left-r.left,o=r.right-i.right,a=i.top-r.top,l=r.bottom-i.bottom;i.width>r.width?(s>0&&(t+=s),o>0&&(t-=o)):t=0,i.height>r.height?(a>0&&(e+=a),l>0&&(e-=l)):e=0,(t!==this._passiveTransform.x||e!==this._passiveTransform.y)&&this.setFreeDragPosition({y:e,x:t})}_getDragStartDelay(t){const e=this.dragStartDelay;return\"number\"==typeof e?e:ol(t)?e.touch:e?e.mouse:0}_updateOnScroll(t){const e=this._parentPositions.handleScroll(t);if(e){const i=Pn(t);this._boundaryRect&&i!==this._boundaryElement&&i.contains(this._boundaryElement)&&sl(this._boundaryRect,e.top,e.left),this._pickupPositionOnPage.x+=e.left,this._pickupPositionOnPage.y+=e.top,this._dropContainer||(this._activeTransform.x-=e.left,this._activeTransform.y-=e.top,this._applyRootElementTransform(this._activeTransform.x,this._activeTransform.y))}}_getViewportScrollPosition(){var t;return(null===(t=this._parentPositions.positions.get(this._document))||void 0===t?void 0:t.scrollPosition)||this._parentPositions.getViewportScrollPosition()}_getShadowRoot(){return void 0===this._cachedShadowRoot&&(this._cachedShadowRoot=Fd(this._rootElement)),this._cachedShadowRoot}_getPreviewInsertionPoint(t,e){const i=this._previewContainer||\"global\";if(\"parent\"===i)return t;if(\"global\"===i){const r=this._document;return e||r.fullscreenElement||r.webkitFullscreenElement||r.mozFullScreenElement||r.msFullscreenElement||r.body}return at(i)}_getPreviewRect(){return(!this._previewRect||!this._previewRect.width&&!this._previewRect.height)&&(this._previewRect=(this._preview||this._rootElement).getBoundingClientRect()),this._previewRect}_getTargetHandle(t){return this._handles.find(e=>t.target&&(t.target===e||e.contains(t.target)))}}function Kd(n,t){return`translate3d(${Math.round(n)}px, ${Math.round(t)}px, 0)`}function aS(n,t,e){return Math.max(t,Math.min(e,n))}function ol(n){return\"t\"===n.type[0]}function lS(n,t){const e=n.rootNodes;if(1===e.length&&e[0].nodeType===t.ELEMENT_NODE)return e[0];const i=t.createElement(\"div\");return e.forEach(r=>i.appendChild(r)),i}function cS(n,t){n.style.width=`${t.width}px`,n.style.height=`${t.height}px`,n.style.transform=Kd(t.left,t.top)}function al(n,t){return Math.max(0,Math.min(t,n))}class D${constructor(t,e,i,r,s){this._dragDropRegistry=e,this._ngZone=r,this._viewportRuler=s,this.disabled=!1,this.sortingDisabled=!1,this.autoScrollDisabled=!1,this.autoScrollStep=2,this.enterPredicate=()=>!0,this.sortPredicate=()=>!0,this.beforeStarted=new O,this.entered=new O,this.exited=new O,this.dropped=new O,this.sorted=new O,this._isDragging=!1,this._itemPositions=[],this._previousSwap={drag:null,delta:0,overlaps:!1},this._draggables=[],this._siblings=[],this._orientation=\"vertical\",this._activeSiblings=new Set,this._direction=\"ltr\",this._viewportScrollSubscription=ke.EMPTY,this._verticalScrollDirection=0,this._horizontalScrollDirection=0,this._stopScrollTimers=new O,this._cachedShadowRoot=null,this._startScrollInterval=()=>{this._stopScrolling(),function g$(n=0,t=qa){return n<0&&(n=0),_g(n,n,t)}(0,EE).pipe(Ie(this._stopScrollTimers)).subscribe(()=>{const o=this._scrollNode,a=this.autoScrollStep;1===this._verticalScrollDirection?o.scrollBy(0,-a):2===this._verticalScrollDirection&&o.scrollBy(0,a),1===this._horizontalScrollDirection?o.scrollBy(-a,0):2===this._horizontalScrollDirection&&o.scrollBy(a,0)})},this.element=at(t),this._document=i,this.withScrollableParents([this.element]),e.registerDropContainer(this),this._parentPositions=new tS(i)}dispose(){this._stopScrolling(),this._stopScrollTimers.complete(),this._viewportScrollSubscription.unsubscribe(),this.beforeStarted.complete(),this.entered.complete(),this.exited.complete(),this.dropped.complete(),this.sorted.complete(),this._activeSiblings.clear(),this._scrollNode=null,this._parentPositions.clear(),this._dragDropRegistry.removeDropContainer(this)}isDragging(){return this._isDragging}start(){this._draggingStarted(),this._notifyReceivingSiblings()}enter(t,e,i,r){let s;this._draggingStarted(),null==r?(s=this.sortingDisabled?this._draggables.indexOf(t):-1,-1===s&&(s=this._getItemIndexFromPointerPosition(t,e,i))):s=r;const o=this._activeDraggables,a=o.indexOf(t),l=t.getPlaceholderElement();let c=o[s];if(c===t&&(c=o[s+1]),!c&&(null==s||-1===s||s<o.length-1)&&this._shouldEnterAsFirstChild(e,i)&&(c=o[0]),a>-1&&o.splice(a,1),c&&!this._dragDropRegistry.isDragging(c)){const d=c.getRootElement();d.parentElement.insertBefore(l,d),o.splice(s,0,t)}else at(this.element).appendChild(l),o.push(t);l.style.transform=\"\",this._cacheItemPositions(),this._cacheParentPositions(),this._notifyReceivingSiblings(),this.entered.next({item:t,container:this,currentIndex:this.getItemIndex(t)})}exit(t){this._reset(),this.exited.next({item:t,container:this})}drop(t,e,i,r,s,o,a){this._reset(),this.dropped.next({item:t,currentIndex:e,previousIndex:i,container:this,previousContainer:r,isPointerOverContainer:s,distance:o,dropPoint:a})}withItems(t){const e=this._draggables;return this._draggables=t,t.forEach(i=>i._withDropContainer(this)),this.isDragging()&&(e.filter(r=>r.isDragging()).every(r=>-1===t.indexOf(r))?this._reset():this._cacheItems()),this}withDirection(t){return this._direction=t,this}connectedTo(t){return this._siblings=t.slice(),this}withOrientation(t){return this._orientation=t,this}withScrollableParents(t){const e=at(this.element);return this._scrollableElements=-1===t.indexOf(e)?[e,...t]:t.slice(),this}getScrollableParents(){return this._scrollableElements}getItemIndex(t){return this._isDragging?(\"horizontal\"===this._orientation&&\"rtl\"===this._direction?this._itemPositions.slice().reverse():this._itemPositions).findIndex(i=>i.drag===t):this._draggables.indexOf(t)}isReceiving(){return this._activeSiblings.size>0}_sortItem(t,e,i,r){if(this.sortingDisabled||!this._clientRect||!eS(this._clientRect,.05,e,i))return;const s=this._itemPositions,o=this._getItemIndexFromPointerPosition(t,e,i,r);if(-1===o&&s.length>0)return;const a=\"horizontal\"===this._orientation,l=s.findIndex(_=>_.drag===t),c=s[o],u=c.clientRect,h=l>o?1:-1,p=this._getItemOffsetPx(s[l].clientRect,u,h),m=this._getSiblingOffsetPx(l,s,h),g=s.slice();(function C$(n,t,e){const i=al(t,n.length-1),r=al(e,n.length-1);if(i===r)return;const s=n[i],o=r<i?-1:1;for(let a=i;a!==r;a+=o)n[a]=n[a+o];n[r]=s})(s,l,o),this.sorted.next({previousIndex:l,currentIndex:o,container:this,item:t}),s.forEach((_,D)=>{if(g[D]===_)return;const v=_.drag===t,M=v?p:m,V=v?t.getPlaceholderElement():_.drag.getRootElement();_.offset+=M,a?(V.style.transform=Yd(`translate3d(${Math.round(_.offset)}px, 0, 0)`,_.initialTransform),sl(_.clientRect,0,M)):(V.style.transform=Yd(`translate3d(0, ${Math.round(_.offset)}px, 0)`,_.initialTransform),sl(_.clientRect,M,0))}),this._previousSwap.overlaps=Eg(u,e,i),this._previousSwap.drag=c.drag,this._previousSwap.delta=a?r.x:r.y}_startScrollingIfNecessary(t,e){if(this.autoScrollDisabled)return;let i,r=0,s=0;if(this._parentPositions.positions.forEach((o,a)=>{a===this._document||!o.clientRect||i||eS(o.clientRect,.05,t,e)&&([r,s]=function w$(n,t,e,i){const r=hS(t,i),s=pS(t,e);let o=0,a=0;if(r){const l=n.scrollTop;1===r?l>0&&(o=1):n.scrollHeight-l>n.clientHeight&&(o=2)}if(s){const l=n.scrollLeft;1===s?l>0&&(a=1):n.scrollWidth-l>n.clientWidth&&(a=2)}return[o,a]}(a,o.clientRect,t,e),(r||s)&&(i=a))}),!r&&!s){const{width:o,height:a}=this._viewportRuler.getViewportSize(),l={width:o,height:a,top:0,right:o,bottom:a,left:0};r=hS(l,e),s=pS(l,t),i=window}i&&(r!==this._verticalScrollDirection||s!==this._horizontalScrollDirection||i!==this._scrollNode)&&(this._verticalScrollDirection=r,this._horizontalScrollDirection=s,this._scrollNode=i,(r||s)&&i?this._ngZone.runOutsideAngular(this._startScrollInterval):this._stopScrolling())}_stopScrolling(){this._stopScrollTimers.next()}_draggingStarted(){const t=at(this.element).style;this.beforeStarted.next(),this._isDragging=!0,this._initialScrollSnap=t.msScrollSnapType||t.scrollSnapType||\"\",t.scrollSnapType=t.msScrollSnapType=\"none\",this._cacheItems(),this._viewportScrollSubscription.unsubscribe(),this._listenToScrollEvents()}_cacheParentPositions(){const t=at(this.element);this._parentPositions.cache(this._scrollableElements),this._clientRect=this._parentPositions.positions.get(t).clientRect}_cacheItemPositions(){const t=\"horizontal\"===this._orientation;this._itemPositions=this._activeDraggables.map(e=>{const i=e.getVisibleElement();return{drag:e,offset:0,initialTransform:i.style.transform||\"\",clientRect:xg(i)}}).sort((e,i)=>t?e.clientRect.left-i.clientRect.left:e.clientRect.top-i.clientRect.top)}_reset(){this._isDragging=!1;const t=at(this.element).style;t.scrollSnapType=t.msScrollSnapType=this._initialScrollSnap,this._activeDraggables.forEach(e=>{var i;const r=e.getRootElement();if(r){const s=null===(i=this._itemPositions.find(o=>o.drag===e))||void 0===i?void 0:i.initialTransform;r.style.transform=s||\"\"}}),this._siblings.forEach(e=>e._stopReceiving(this)),this._activeDraggables=[],this._itemPositions=[],this._previousSwap.drag=null,this._previousSwap.delta=0,this._previousSwap.overlaps=!1,this._stopScrolling(),this._viewportScrollSubscription.unsubscribe(),this._parentPositions.clear()}_getSiblingOffsetPx(t,e,i){const r=\"horizontal\"===this._orientation,s=e[t].clientRect,o=e[t+-1*i];let a=s[r?\"width\":\"height\"]*i;if(o){const l=r?\"left\":\"top\",c=r?\"right\":\"bottom\";-1===i?a-=o.clientRect[l]-s[c]:a+=s[l]-o.clientRect[c]}return a}_getItemOffsetPx(t,e,i){const r=\"horizontal\"===this._orientation;let s=r?e.left-t.left:e.top-t.top;return-1===i&&(s+=r?e.width-t.width:e.height-t.height),s}_shouldEnterAsFirstChild(t,e){if(!this._activeDraggables.length)return!1;const i=this._itemPositions,r=\"horizontal\"===this._orientation;if(i[0].drag!==this._activeDraggables[0]){const o=i[i.length-1].clientRect;return r?t>=o.right:e>=o.bottom}{const o=i[0].clientRect;return r?t<=o.left:e<=o.top}}_getItemIndexFromPointerPosition(t,e,i,r){const s=\"horizontal\"===this._orientation,o=this._itemPositions.findIndex(({drag:a,clientRect:l})=>{if(a===t)return!1;if(r){const c=s?r.x:r.y;if(a===this._previousSwap.drag&&this._previousSwap.overlaps&&c===this._previousSwap.delta)return!1}return s?e>=Math.floor(l.left)&&e<Math.floor(l.right):i>=Math.floor(l.top)&&i<Math.floor(l.bottom)});return-1!==o&&this.sortPredicate(o,t,this)?o:-1}_cacheItems(){this._activeDraggables=this._draggables.slice(),this._cacheItemPositions(),this._cacheParentPositions()}_isOverContainer(t,e){return null!=this._clientRect&&Eg(this._clientRect,t,e)}_getSiblingContainerFromPosition(t,e,i){return this._siblings.find(r=>r._canReceive(t,e,i))}_canReceive(t,e,i){if(!this._clientRect||!Eg(this._clientRect,e,i)||!this.enterPredicate(t,this))return!1;const r=this._getShadowRoot().elementFromPoint(e,i);if(!r)return!1;const s=at(this.element);return r===s||s.contains(r)}_startReceiving(t,e){const i=this._activeSiblings;!i.has(t)&&e.every(r=>this.enterPredicate(r,this)||this._draggables.indexOf(r)>-1)&&(i.add(t),this._cacheParentPositions(),this._listenToScrollEvents())}_stopReceiving(t){this._activeSiblings.delete(t),this._viewportScrollSubscription.unsubscribe()}_listenToScrollEvents(){this._viewportScrollSubscription=this._dragDropRegistry.scrolled(this._getShadowRoot()).subscribe(t=>{if(this.isDragging()){const e=this._parentPositions.handleScroll(t);e&&(this._itemPositions.forEach(({clientRect:i})=>{sl(i,e.top,e.left)}),this._itemPositions.forEach(({drag:i})=>{this._dragDropRegistry.isDragging(i)&&i._sortFromLastPointerPosition()}))}else this.isReceiving()&&this._cacheParentPositions()})}_getShadowRoot(){if(!this._cachedShadowRoot){const t=Fd(at(this.element));this._cachedShadowRoot=t||this._document}return this._cachedShadowRoot}_notifyReceivingSiblings(){const t=this._activeDraggables.filter(e=>e.isDragging());this._siblings.forEach(e=>e._startReceiving(this,t))}}function hS(n,t){const{top:e,bottom:i,height:r}=n,s=.05*r;return t>=e-s&&t<=e+s?1:t>=i-s&&t<=i+s?2:0}function pS(n,t){const{left:e,right:i,width:r}=n,s=.05*r;return t>=e-s&&t<=e+s?1:t>=i-s&&t<=i+s?2:0}const Zd=ei({passive:!1,capture:!0});let M$=(()=>{class n{constructor(e,i){this._ngZone=e,this._dropInstances=new Set,this._dragInstances=new Set,this._activeDragInstances=[],this._globalListeners=new Map,this._draggingPredicate=r=>r.isDragging(),this.pointerMove=new O,this.pointerUp=new O,this.scroll=new O,this._preventDefaultWhileDragging=r=>{this._activeDragInstances.length>0&&r.preventDefault()},this._persistentTouchmoveListener=r=>{this._activeDragInstances.length>0&&(this._activeDragInstances.some(this._draggingPredicate)&&r.preventDefault(),this.pointerMove.next(r))},this._document=i}registerDropContainer(e){this._dropInstances.has(e)||this._dropInstances.add(e)}registerDragItem(e){this._dragInstances.add(e),1===this._dragInstances.size&&this._ngZone.runOutsideAngular(()=>{this._document.addEventListener(\"touchmove\",this._persistentTouchmoveListener,Zd)})}removeDropContainer(e){this._dropInstances.delete(e)}removeDragItem(e){this._dragInstances.delete(e),this.stopDragging(e),0===this._dragInstances.size&&this._document.removeEventListener(\"touchmove\",this._persistentTouchmoveListener,Zd)}startDragging(e,i){if(!(this._activeDragInstances.indexOf(e)>-1)&&(this._activeDragInstances.push(e),1===this._activeDragInstances.length)){const r=i.type.startsWith(\"touch\");this._globalListeners.set(r?\"touchend\":\"mouseup\",{handler:s=>this.pointerUp.next(s),options:!0}).set(\"scroll\",{handler:s=>this.scroll.next(s),options:!0}).set(\"selectstart\",{handler:this._preventDefaultWhileDragging,options:Zd}),r||this._globalListeners.set(\"mousemove\",{handler:s=>this.pointerMove.next(s),options:Zd}),this._ngZone.runOutsideAngular(()=>{this._globalListeners.forEach((s,o)=>{this._document.addEventListener(o,s.handler,s.options)})})}}stopDragging(e){const i=this._activeDragInstances.indexOf(e);i>-1&&(this._activeDragInstances.splice(i,1),0===this._activeDragInstances.length&&this._clearGlobalListeners())}isDragging(e){return this._activeDragInstances.indexOf(e)>-1}scrolled(e){const i=[this.scroll];return e&&e!==this._document&&i.push(new Ve(r=>this._ngZone.runOutsideAngular(()=>{const o=a=>{this._activeDragInstances.length&&r.next(a)};return e.addEventListener(\"scroll\",o,!0),()=>{e.removeEventListener(\"scroll\",o,!0)}}))),Bt(...i)}ngOnDestroy(){this._dragInstances.forEach(e=>this.removeDragItem(e)),this._dropInstances.forEach(e=>this.removeDropContainer(e)),this._clearGlobalListeners(),this.pointerMove.complete(),this.pointerUp.complete()}_clearGlobalListeners(){this._globalListeners.forEach((e,i)=>{this._document.removeEventListener(i,e.handler,e.options)}),this._globalListeners.clear()}}return n.\\u0275fac=function(e){return new(e||n)(y(ne),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const x$={dragStartThreshold:5,pointerDirectionChangeThreshold:5};let E$=(()=>{class n{constructor(e,i,r,s){this._document=e,this._ngZone=i,this._viewportRuler=r,this._dragDropRegistry=s}createDrag(e,i=x$){return new b$(e,i,this._document,this._ngZone,this._viewportRuler,this._dragDropRegistry)}createDropList(e){return new D$(e,this._dragDropRegistry,this._document,this._ngZone,this._viewportRuler)}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(ne),y(es),y(M$))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),S$=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[E$],imports:[Ci]}),n})(),fS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[lo]]}),n})(),bS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Ud]]}),n})(),CS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const Z$={provide:new b(\"mat-autocomplete-scroll-strategy\"),deps:[ni],useFactory:function K$(n){return()=>n.scrollStrategies.reposition()}};let t8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[Z$],imports:[[ji,Hd,B,bt],Ci,Hd,B]}),n})(),n8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Qa,B],B]}),n})(),r8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ji,B,Hi],B]}),n})(),ul=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ti,B],B]}),n})(),u8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B,ti],B]}),n})(),h8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),AS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),M8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ti,B,Ya,AS],B,AS]}),n})();const PS=new b(\"mat-chips-default-options\");let L8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[mo,{provide:PS,useValue:{separatorKeyCodes:[13]}}],imports:[[B]]}),n})(),WS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),Wg=(()=>{class n{constructor(){this.changes=new O,this.optionalLabel=\"Optional\",this.completedLabel=\"Completed\",this.editableLabel=\"Editable\"}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const d4={provide:Wg,deps:[[new Tt,new Cn,Wg]],useFactory:function c4(n){return n||new Wg}};let u4=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[d4,mo],imports:[[B,bt,Hi,ul,fS,WS,ti],B]}),n})(),C4=(()=>{class n{constructor(){this.changes=new O,this.calendarLabel=\"Calendar\",this.openCalendarLabel=\"Open calendar\",this.closeCalendarLabel=\"Close calendar\",this.prevMonthLabel=\"Previous month\",this.nextMonthLabel=\"Next month\",this.prevYearLabel=\"Previous year\",this.nextYearLabel=\"Next year\",this.prevMultiYearLabel=\"Previous 24 years\",this.nextMultiYearLabel=\"Next 24 years\",this.switchToMonthViewLabel=\"Choose date\",this.switchToMultiYearViewLabel=\"Choose month and year\"}formatYearRange(e,i){return`${e} \\u2013 ${i}`}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const M4={provide:new b(\"mat-datepicker-scroll-strategy\"),deps:[ni],useFactory:function w4(n){return()=>n.scrollStrategies.reposition()}};let T4=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[C4,M4],imports:[[bt,ul,ji,Qa,Hi,B],Ci]}),n})();function A4(n,t){}class qg{constructor(){this.role=\"dialog\",this.panelClass=\"\",this.hasBackdrop=!0,this.backdropClass=\"\",this.disableClose=!1,this.width=\"\",this.height=\"\",this.maxWidth=\"80vw\",this.data=null,this.ariaDescribedBy=null,this.ariaLabelledBy=null,this.ariaLabel=null,this.autoFocus=\"first-tabbable\",this.restoreFocus=!0,this.delayFocusTrap=!0,this.closeOnNavigation=!0}}const I4={dialogContainer:Ke(\"dialogContainer\",[ae(\"void, exit\",R({opacity:0,transform:\"scale(0.7)\"})),ae(\"enter\",R({transform:\"none\"})),ge(\"* => enter\",nd([be(\"150ms cubic-bezier(0, 0, 0.2, 1)\",R({transform:\"none\",opacity:1})),no(\"@*\",to(),{optional:!0})])),ge(\"* => void, * => exit\",nd([be(\"75ms cubic-bezier(0.4, 0.0, 0.2, 1)\",R({opacity:0})),no(\"@*\",to(),{optional:!0})]))])};let R4=(()=>{class n extends bg{constructor(e,i,r,s,o,a,l,c){super(),this._elementRef=e,this._focusTrapFactory=i,this._changeDetectorRef=r,this._config=o,this._interactivityChecker=a,this._ngZone=l,this._focusMonitor=c,this._animationStateChanged=new $,this._elementFocusedBeforeDialogWasOpened=null,this._closeInteractionType=null,this.attachDomPortal=d=>(this._portalOutlet.hasAttached(),this._portalOutlet.attachDomPortal(d)),this._ariaLabelledBy=o.ariaLabelledBy||null,this._document=s}_initializeWithAttachedContent(){this._focusTrap=this._focusTrapFactory.create(this._elementRef.nativeElement),this._document&&(this._elementFocusedBeforeDialogWasOpened=Hm())}attachComponentPortal(e){return this._portalOutlet.hasAttached(),this._portalOutlet.attachComponentPortal(e)}attachTemplatePortal(e){return this._portalOutlet.hasAttached(),this._portalOutlet.attachTemplatePortal(e)}_recaptureFocus(){this._containsFocus()||this._trapFocus()}_forceFocus(e,i){this._interactivityChecker.isFocusable(e)||(e.tabIndex=-1,this._ngZone.runOutsideAngular(()=>{e.addEventListener(\"blur\",()=>e.removeAttribute(\"tabindex\")),e.addEventListener(\"mousedown\",()=>e.removeAttribute(\"tabindex\"))})),e.focus(i)}_focusByCssSelector(e,i){let r=this._elementRef.nativeElement.querySelector(e);r&&this._forceFocus(r,i)}_trapFocus(){const e=this._elementRef.nativeElement;switch(this._config.autoFocus){case!1:case\"dialog\":this._containsFocus()||e.focus();break;case!0:case\"first-tabbable\":this._focusTrap.focusInitialElementWhenReady().then(i=>{i||this._focusDialogContainer()});break;case\"first-heading\":this._focusByCssSelector('h1, h2, h3, h4, h5, h6, [role=\"heading\"]');break;default:this._focusByCssSelector(this._config.autoFocus)}}_restoreFocus(){const e=this._elementFocusedBeforeDialogWasOpened;if(this._config.restoreFocus&&e&&\"function\"==typeof e.focus){const i=Hm(),r=this._elementRef.nativeElement;(!i||i===this._document.body||i===r||r.contains(i))&&(this._focusMonitor?(this._focusMonitor.focusVia(e,this._closeInteractionType),this._closeInteractionType=null):e.focus())}this._focusTrap&&this._focusTrap.destroy()}_focusDialogContainer(){this._elementRef.nativeElement.focus&&this._elementRef.nativeElement.focus()}_containsFocus(){const e=this._elementRef.nativeElement,i=Hm();return e===i||e.contains(i)}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(C3),f(Ye),f(ie,8),f(qg),f(Xx),f(ne),f(Qr))},n.\\u0275dir=C({type:n,viewQuery:function(e,i){if(1&e&&je(TE,7),2&e){let r;z(r=U())&&(i._portalOutlet=r.first)}},features:[E]}),n})(),O4=(()=>{class n extends R4{constructor(){super(...arguments),this._state=\"enter\"}_onAnimationDone({toState:e,totalTime:i}){\"enter\"===e?(this._config.delayFocusTrap&&this._trapFocus(),this._animationStateChanged.next({state:\"opened\",totalTime:i})):\"exit\"===e&&(this._restoreFocus(),this._animationStateChanged.next({state:\"closed\",totalTime:i}))}_onAnimationStart({toState:e,totalTime:i}){\"enter\"===e?this._animationStateChanged.next({state:\"opening\",totalTime:i}):(\"exit\"===e||\"void\"===e)&&this._animationStateChanged.next({state:\"closing\",totalTime:i})}_startExitAnimation(){this._state=\"exit\",this._changeDetectorRef.markForCheck()}_initializeWithAttachedContent(){super._initializeWithAttachedContent(),this._config.delayFocusTrap||this._trapFocus()}}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275cmp=xe({type:n,selectors:[[\"mat-dialog-container\"]],hostAttrs:[\"tabindex\",\"-1\",\"aria-modal\",\"true\",1,\"mat-dialog-container\"],hostVars:6,hostBindings:function(e,i){1&e&&hp(\"@dialogContainer.start\",function(s){return i._onAnimationStart(s)})(\"@dialogContainer.done\",function(s){return i._onAnimationDone(s)}),2&e&&(Yn(\"id\",i._id),Z(\"role\",i._config.role)(\"aria-labelledby\",i._config.ariaLabel?null:i._ariaLabelledBy)(\"aria-label\",i._config.ariaLabel)(\"aria-describedby\",i._config.ariaDescribedBy||null),gp(\"@dialogContainer\",i._state))},features:[E],decls:1,vars:0,consts:[[\"cdkPortalOutlet\",\"\"]],template:function(e,i){1&e&&Ee(0,A4,0,0,\"ng-template\",0)},directives:[TE],styles:[\".mat-dialog-container{display:block;padding:24px;border-radius:4px;box-sizing:border-box;overflow:auto;outline:0;width:100%;height:100%;min-height:inherit;max-height:inherit}.cdk-high-contrast-active .mat-dialog-container{outline:solid 1px}.mat-dialog-content{display:block;margin:0 -24px;padding:0 24px;max-height:65vh;overflow:auto;-webkit-overflow-scrolling:touch}.mat-dialog-title{margin:0 0 20px;display:block}.mat-dialog-actions{padding:8px 0;display:flex;flex-wrap:wrap;min-height:52px;align-items:center;box-sizing:content-box;margin-bottom:-24px}.mat-dialog-actions[align=end]{justify-content:flex-end}.mat-dialog-actions[align=center]{justify-content:center}.mat-dialog-actions .mat-button-base+.mat-button-base,.mat-dialog-actions .mat-mdc-button-base+.mat-mdc-button-base{margin-left:8px}[dir=rtl] .mat-dialog-actions .mat-button-base+.mat-button-base,[dir=rtl] .mat-dialog-actions .mat-mdc-button-base+.mat-mdc-button-base{margin-left:0;margin-right:8px}\\n\"],encapsulation:2,data:{animation:[I4.dialogContainer]}}),n})(),P4=0;class F4{constructor(t,e,i=\"mat-dialog-\"+P4++){this._overlayRef=t,this._containerInstance=e,this.id=i,this.disableClose=this._containerInstance._config.disableClose,this._afterOpened=new O,this._afterClosed=new O,this._beforeClosed=new O,this._state=0,e._id=i,e._animationStateChanged.pipe(Ct(r=>\"opened\"===r.state),it(1)).subscribe(()=>{this._afterOpened.next(),this._afterOpened.complete()}),e._animationStateChanged.pipe(Ct(r=>\"closed\"===r.state),it(1)).subscribe(()=>{clearTimeout(this._closeFallbackTimeout),this._finishDialogClose()}),t.detachments().subscribe(()=>{this._beforeClosed.next(this._result),this._beforeClosed.complete(),this._afterClosed.next(this._result),this._afterClosed.complete(),this.componentInstance=null,this._overlayRef.dispose()}),t.keydownEvents().pipe(Ct(r=>27===r.keyCode&&!this.disableClose&&!Xt(r))).subscribe(r=>{r.preventDefault(),ZS(this,\"keyboard\")}),t.backdropClick().subscribe(()=>{this.disableClose?this._containerInstance._recaptureFocus():ZS(this,\"mouse\")})}close(t){this._result=t,this._containerInstance._animationStateChanged.pipe(Ct(e=>\"closing\"===e.state),it(1)).subscribe(e=>{this._beforeClosed.next(t),this._beforeClosed.complete(),this._overlayRef.detachBackdrop(),this._closeFallbackTimeout=setTimeout(()=>this._finishDialogClose(),e.totalTime+100)}),this._state=1,this._containerInstance._startExitAnimation()}afterOpened(){return this._afterOpened}afterClosed(){return this._afterClosed}beforeClosed(){return this._beforeClosed}backdropClick(){return this._overlayRef.backdropClick()}keydownEvents(){return this._overlayRef.keydownEvents()}updatePosition(t){let e=this._getPositionStrategy();return t&&(t.left||t.right)?t.left?e.left(t.left):e.right(t.right):e.centerHorizontally(),t&&(t.top||t.bottom)?t.top?e.top(t.top):e.bottom(t.bottom):e.centerVertically(),this._overlayRef.updatePosition(),this}updateSize(t=\"\",e=\"\"){return this._overlayRef.updateSize({width:t,height:e}),this._overlayRef.updatePosition(),this}addPanelClass(t){return this._overlayRef.addPanelClass(t),this}removePanelClass(t){return this._overlayRef.removePanelClass(t),this}getState(){return this._state}_finishDialogClose(){this._state=2,this._overlayRef.dispose()}_getPositionStrategy(){return this._overlayRef.getConfig().positionStrategy}}function ZS(n,t,e){return void 0!==n._containerInstance&&(n._containerInstance._closeInteractionType=t),n.close(e)}const N4=new b(\"MatDialogData\"),L4=new b(\"mat-dialog-default-options\"),XS=new b(\"mat-dialog-scroll-strategy\"),V4={provide:XS,deps:[ni],useFactory:function B4(n){return()=>n.scrollStrategies.block()}};let H4=(()=>{class n{constructor(e,i,r,s,o,a,l,c,d,u){this._overlay=e,this._injector=i,this._defaultOptions=r,this._parentDialog=s,this._overlayContainer=o,this._dialogRefConstructor=l,this._dialogContainerType=c,this._dialogDataToken=d,this._openDialogsAtThisLevel=[],this._afterAllClosedAtThisLevel=new O,this._afterOpenedAtThisLevel=new O,this._ariaHiddenElements=new Map,this.afterAllClosed=xa(()=>this.openDialogs.length?this._getAfterAllClosed():this._getAfterAllClosed().pipe(Xn(void 0))),this._scrollStrategy=a}get openDialogs(){return this._parentDialog?this._parentDialog.openDialogs:this._openDialogsAtThisLevel}get afterOpened(){return this._parentDialog?this._parentDialog.afterOpened:this._afterOpenedAtThisLevel}_getAfterAllClosed(){const e=this._parentDialog;return e?e._getAfterAllClosed():this._afterAllClosedAtThisLevel}open(e,i){i=function z4(n,t){return Object.assign(Object.assign({},t),n)}(i,this._defaultOptions||new qg),i.id&&this.getDialogById(i.id);const r=this._createOverlay(i),s=this._attachDialogContainer(r,i),o=this._attachDialogContent(e,s,r,i);return this.openDialogs.length||this._hideNonDialogContentFromAssistiveTechnology(),this.openDialogs.push(o),o.afterClosed().subscribe(()=>this._removeOpenDialog(o)),this.afterOpened.next(o),s._initializeWithAttachedContent(),o}closeAll(){this._closeDialogs(this.openDialogs)}getDialogById(e){return this.openDialogs.find(i=>i.id===e)}ngOnDestroy(){this._closeDialogs(this._openDialogsAtThisLevel),this._afterAllClosedAtThisLevel.complete(),this._afterOpenedAtThisLevel.complete()}_createOverlay(e){const i=this._getOverlayConfig(e);return this._overlay.create(i)}_getOverlayConfig(e){const i=new Gd({positionStrategy:this._overlay.position().global(),scrollStrategy:e.scrollStrategy||this._scrollStrategy(),panelClass:e.panelClass,hasBackdrop:e.hasBackdrop,direction:e.direction,minWidth:e.minWidth,minHeight:e.minHeight,maxWidth:e.maxWidth,maxHeight:e.maxHeight,disposeOnNavigation:e.closeOnNavigation});return e.backdropClass&&(i.backdropClass=e.backdropClass),i}_attachDialogContainer(e,i){const s=dt.create({parent:i&&i.viewContainerRef&&i.viewContainerRef.injector||this._injector,providers:[{provide:qg,useValue:i}]}),o=new yg(this._dialogContainerType,i.viewContainerRef,s,i.componentFactoryResolver);return e.attach(o).instance}_attachDialogContent(e,i,r,s){const o=new this._dialogRefConstructor(r,i,s.id);if(e instanceof ut)i.attachTemplatePortal(new $d(e,null,{$implicit:s.data,dialogRef:o}));else{const a=this._createInjector(s,o,i),l=i.attachComponentPortal(new yg(e,s.viewContainerRef,a,s.componentFactoryResolver));o.componentInstance=l.instance}return o.updateSize(s.width,s.height).updatePosition(s.position),o}_createInjector(e,i,r){const s=e&&e.viewContainerRef&&e.viewContainerRef.injector,o=[{provide:this._dialogContainerType,useValue:r},{provide:this._dialogDataToken,useValue:e.data},{provide:this._dialogRefConstructor,useValue:i}];return e.direction&&(!s||!s.get(On,null,ee.Optional))&&o.push({provide:On,useValue:{value:e.direction,change:q()}}),dt.create({parent:s||this._injector,providers:o})}_removeOpenDialog(e){const i=this.openDialogs.indexOf(e);i>-1&&(this.openDialogs.splice(i,1),this.openDialogs.length||(this._ariaHiddenElements.forEach((r,s)=>{r?s.setAttribute(\"aria-hidden\",r):s.removeAttribute(\"aria-hidden\")}),this._ariaHiddenElements.clear(),this._getAfterAllClosed().next()))}_hideNonDialogContentFromAssistiveTechnology(){const e=this._overlayContainer.getContainerElement();if(e.parentElement){const i=e.parentElement.children;for(let r=i.length-1;r>-1;r--){let s=i[r];s!==e&&\"SCRIPT\"!==s.nodeName&&\"STYLE\"!==s.nodeName&&!s.hasAttribute(\"aria-live\")&&(this._ariaHiddenElements.set(s,s.getAttribute(\"aria-hidden\")),s.setAttribute(\"aria-hidden\",\"true\"))}}}_closeDialogs(e){let i=e.length;for(;i--;)e[i].close()}}return n.\\u0275fac=function(e){Sr()},n.\\u0275dir=C({type:n}),n})(),j4=(()=>{class n extends H4{constructor(e,i,r,s,o,a,l,c){super(e,i,s,a,l,o,F4,O4,N4,c)}}return n.\\u0275fac=function(e){return new(e||n)(y(ni),y(dt),y(va,8),y(L4,8),y(XS),y(n,12),y(Dg),y(Rn,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),U4=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[j4,V4],imports:[[ji,Hi,B],B]}),n})(),JS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),$4=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B,ZE,Hi]]}),n})(),rG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Vd,ti,B,og,bt],Vd,B,og,JS]}),n})();const lG={provide:new b(\"mat-menu-scroll-strategy\"),deps:[ni],useFactory:function aG(n){return()=>n.scrollStrategies.reposition()}};let cG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[lG],imports:[[bt,B,ti,ji],Ci,B]}),n})();const pG={provide:new b(\"mat-tooltip-scroll-strategy\"),deps:[ni],useFactory:function hG(n){return()=>n.scrollStrategies.reposition({scrollThrottle:20})}};let ik=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[pG],imports:[[Qa,bt,ji,B],B,Ci]}),n})(),Yg=(()=>{class n{constructor(){this.changes=new O,this.itemsPerPageLabel=\"Items per page:\",this.nextPageLabel=\"Next page\",this.previousPageLabel=\"Previous page\",this.firstPageLabel=\"First page\",this.lastPageLabel=\"Last page\",this.getRangeLabel=(e,i,r)=>{if(0==r||0==i)return`0 of ${r}`;const s=e*i;return`${s+1} \\u2013 ${s<(r=Math.max(r,0))?Math.min(s+i,r):s+i} of ${r}`}}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const yG={provide:Yg,deps:[[new Tt,new Cn,Yg]],useFactory:function vG(n){return n||new Yg}};let bG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[yG],imports:[[bt,ul,qE,ik,B]]}),n})(),DG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B],B]}),n})();function wG(n,t){if(1&n&&(Oo(),Le(0,\"circle\",4)),2&n){const e=Be(),i=wn(1);$n(\"animation-name\",\"mat-progress-spinner-stroke-rotate-\"+e._spinnerAnimationLabel)(\"stroke-dashoffset\",e._getStrokeDashOffset(),\"px\")(\"stroke-dasharray\",e._getStrokeCircumference(),\"px\")(\"stroke-width\",e._getCircleStrokeWidth(),\"%\")(\"transform-origin\",e._getCircleTransformOrigin(i)),Z(\"r\",e._getCircleRadius())}}function MG(n,t){if(1&n&&(Oo(),Le(0,\"circle\",4)),2&n){const e=Be(),i=wn(1);$n(\"stroke-dashoffset\",e._getStrokeDashOffset(),\"px\")(\"stroke-dasharray\",e._getStrokeCircumference(),\"px\")(\"stroke-width\",e._getCircleStrokeWidth(),\"%\")(\"transform-origin\",e._getCircleTransformOrigin(i)),Z(\"r\",e._getCircleRadius())}}const EG=fo(class{constructor(n){this._elementRef=n}},\"primary\"),SG=new b(\"mat-progress-spinner-default-options\",{providedIn:\"root\",factory:function kG(){return{diameter:100}}});class dr extends EG{constructor(t,e,i,r,s,o,a,l){super(t),this._document=i,this._diameter=100,this._value=0,this._resizeSubscription=ke.EMPTY,this.mode=\"determinate\";const c=dr._diameters;this._spinnerAnimationLabel=this._getSpinnerAnimationLabel(),c.has(i.head)||c.set(i.head,new Set([100])),this._noopAnimations=\"NoopAnimations\"===r&&!!s&&!s._forceAnimations,\"mat-spinner\"===t.nativeElement.nodeName.toLowerCase()&&(this.mode=\"indeterminate\"),s&&(s.diameter&&(this.diameter=s.diameter),s.strokeWidth&&(this.strokeWidth=s.strokeWidth)),e.isBrowser&&e.SAFARI&&a&&o&&l&&(this._resizeSubscription=a.change(150).subscribe(()=>{\"indeterminate\"===this.mode&&l.run(()=>o.markForCheck())}))}get diameter(){return this._diameter}set diameter(t){this._diameter=Et(t),this._spinnerAnimationLabel=this._getSpinnerAnimationLabel(),this._styleRoot&&this._attachStyleNode()}get strokeWidth(){return this._strokeWidth||this.diameter/10}set strokeWidth(t){this._strokeWidth=Et(t)}get value(){return\"determinate\"===this.mode?this._value:0}set value(t){this._value=Math.max(0,Math.min(100,Et(t)))}ngOnInit(){const t=this._elementRef.nativeElement;this._styleRoot=Fd(t)||this._document.head,this._attachStyleNode(),t.classList.add(\"mat-progress-spinner-indeterminate-animation\")}ngOnDestroy(){this._resizeSubscription.unsubscribe()}_getCircleRadius(){return(this.diameter-10)/2}_getViewBox(){const t=2*this._getCircleRadius()+this.strokeWidth;return`0 0 ${t} ${t}`}_getStrokeCircumference(){return 2*Math.PI*this._getCircleRadius()}_getStrokeDashOffset(){return\"determinate\"===this.mode?this._getStrokeCircumference()*(100-this._value)/100:null}_getCircleStrokeWidth(){return this.strokeWidth/this.diameter*100}_getCircleTransformOrigin(t){var e;const i=50*(null!==(e=t.currentScale)&&void 0!==e?e:1);return`${i}% ${i}%`}_attachStyleNode(){const t=this._styleRoot,e=this._diameter,i=dr._diameters;let r=i.get(t);if(!r||!r.has(e)){const s=this._document.createElement(\"style\");s.setAttribute(\"mat-spinner-animation\",this._spinnerAnimationLabel),s.textContent=this._getAnimationText(),t.appendChild(s),r||(r=new Set,i.set(t,r)),r.add(e)}}_getAnimationText(){const t=this._getStrokeCircumference();return\"\\n @keyframes mat-progress-spinner-stroke-rotate-DIAMETER {\\n 0% { stroke-dashoffset: START_VALUE; transform: rotate(0); }\\n 12.5% { stroke-dashoffset: END_VALUE; transform: rotate(0); }\\n 12.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(72.5deg); }\\n 25% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(72.5deg); }\\n\\n 25.0001% { stroke-dashoffset: START_VALUE; transform: rotate(270deg); }\\n 37.5% { stroke-dashoffset: END_VALUE; transform: rotate(270deg); }\\n 37.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(161.5deg); }\\n 50% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(161.5deg); }\\n\\n 50.0001% { stroke-dashoffset: START_VALUE; transform: rotate(180deg); }\\n 62.5% { stroke-dashoffset: END_VALUE; transform: rotate(180deg); }\\n 62.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(251.5deg); }\\n 75% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(251.5deg); }\\n\\n 75.0001% { stroke-dashoffset: START_VALUE; transform: rotate(90deg); }\\n 87.5% { stroke-dashoffset: END_VALUE; transform: rotate(90deg); }\\n 87.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(341.5deg); }\\n 100% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(341.5deg); }\\n }\\n\".replace(/START_VALUE/g,\"\"+.95*t).replace(/END_VALUE/g,\"\"+.2*t).replace(/DIAMETER/g,`${this._spinnerAnimationLabel}`)}_getSpinnerAnimationLabel(){return this.diameter.toString().replace(\".\",\"_\")}}dr._diameters=new WeakMap,dr.\\u0275fac=function(t){return new(t||dr)(f(W),f(It),f(ie,8),f(Rn,8),f(SG),f(Ye),f(es),f(ne))},dr.\\u0275cmp=xe({type:dr,selectors:[[\"mat-progress-spinner\"],[\"mat-spinner\"]],hostAttrs:[\"role\",\"progressbar\",\"tabindex\",\"-1\",1,\"mat-progress-spinner\",\"mat-spinner\"],hostVars:10,hostBindings:function(t,e){2&t&&(Z(\"aria-valuemin\",\"determinate\"===e.mode?0:null)(\"aria-valuemax\",\"determinate\"===e.mode?100:null)(\"aria-valuenow\",\"determinate\"===e.mode?e.value:null)(\"mode\",e.mode),$n(\"width\",e.diameter,\"px\")(\"height\",e.diameter,\"px\"),Ae(\"_mat-animation-noopable\",e._noopAnimations))},inputs:{color:\"color\",diameter:\"diameter\",strokeWidth:\"strokeWidth\",mode:\"mode\",value:\"value\"},exportAs:[\"matProgressSpinner\"],features:[E],decls:4,vars:8,consts:[[\"preserveAspectRatio\",\"xMidYMid meet\",\"focusable\",\"false\",\"aria-hidden\",\"true\",3,\"ngSwitch\"],[\"svg\",\"\"],[\"cx\",\"50%\",\"cy\",\"50%\",3,\"animation-name\",\"stroke-dashoffset\",\"stroke-dasharray\",\"stroke-width\",\"transform-origin\",4,\"ngSwitchCase\"],[\"cx\",\"50%\",\"cy\",\"50%\",3,\"stroke-dashoffset\",\"stroke-dasharray\",\"stroke-width\",\"transform-origin\",4,\"ngSwitchCase\"],[\"cx\",\"50%\",\"cy\",\"50%\"]],template:function(t,e){1&t&&(Oo(),x(0,\"svg\",0,1),Ee(2,wG,1,11,\"circle\",2),Ee(3,MG,1,9,\"circle\",3),S()),2&t&&($n(\"width\",e.diameter,\"px\")(\"height\",e.diameter,\"px\"),N(\"ngSwitch\",\"indeterminate\"===e.mode),Z(\"viewBox\",e._getViewBox()),T(2),N(\"ngSwitchCase\",!0),T(1),N(\"ngSwitchCase\",!1))},directives:[Ys,Pc],styles:[\".mat-progress-spinner{display:block;position:relative;overflow:hidden}.mat-progress-spinner svg{position:absolute;transform:rotate(-90deg);top:0;left:0;transform-origin:center;overflow:visible}.mat-progress-spinner circle{fill:transparent;transition:stroke-dashoffset 225ms linear}._mat-animation-noopable.mat-progress-spinner circle{transition:none;animation:none}.cdk-high-contrast-active .mat-progress-spinner circle{stroke:CanvasText}.mat-progress-spinner.mat-progress-spinner-indeterminate-animation[mode=indeterminate] svg{animation:mat-progress-spinner-linear-rotate 2000ms linear infinite}._mat-animation-noopable.mat-progress-spinner.mat-progress-spinner-indeterminate-animation[mode=indeterminate] svg{transition:none;animation:none}.mat-progress-spinner.mat-progress-spinner-indeterminate-animation[mode=indeterminate] circle{transition-property:stroke;animation-duration:4000ms;animation-timing-function:cubic-bezier(0.35, 0, 0.25, 1);animation-iteration-count:infinite}._mat-animation-noopable.mat-progress-spinner.mat-progress-spinner-indeterminate-animation[mode=indeterminate] circle{transition:none;animation:none}@keyframes mat-progress-spinner-linear-rotate{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@keyframes mat-progress-spinner-stroke-rotate-100{0%{stroke-dashoffset:268.606171575px;transform:rotate(0)}12.5%{stroke-dashoffset:56.5486677px;transform:rotate(0)}12.5001%{stroke-dashoffset:56.5486677px;transform:rotateX(180deg) rotate(72.5deg)}25%{stroke-dashoffset:268.606171575px;transform:rotateX(180deg) rotate(72.5deg)}25.0001%{stroke-dashoffset:268.606171575px;transform:rotate(270deg)}37.5%{stroke-dashoffset:56.5486677px;transform:rotate(270deg)}37.5001%{stroke-dashoffset:56.5486677px;transform:rotateX(180deg) rotate(161.5deg)}50%{stroke-dashoffset:268.606171575px;transform:rotateX(180deg) rotate(161.5deg)}50.0001%{stroke-dashoffset:268.606171575px;transform:rotate(180deg)}62.5%{stroke-dashoffset:56.5486677px;transform:rotate(180deg)}62.5001%{stroke-dashoffset:56.5486677px;transform:rotateX(180deg) rotate(251.5deg)}75%{stroke-dashoffset:268.606171575px;transform:rotateX(180deg) rotate(251.5deg)}75.0001%{stroke-dashoffset:268.606171575px;transform:rotate(90deg)}87.5%{stroke-dashoffset:56.5486677px;transform:rotate(90deg)}87.5001%{stroke-dashoffset:56.5486677px;transform:rotateX(180deg) rotate(341.5deg)}100%{stroke-dashoffset:268.606171575px;transform:rotateX(180deg) rotate(341.5deg)}}\\n\"],encapsulation:2,changeDetection:0});let AG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B,bt],B]}),n})(),UG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ti,B],B]}),n})(),GG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B,Ci],Ci,B]}),n})(),ak=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),sW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ak,ti,B,Ya],ak,B]}),n})(),lW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ji,Hi,bt,ul,B],B]}),n})(),Kg=(()=>{class n{constructor(){this.changes=new O}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const uW={provide:Kg,deps:[[new Tt,new Cn,Kg]],useFactory:function dW(n){return n||new Kg}};let hW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[uW],imports:[[bt,B]]}),n})(),TW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bS,B],B]}),n})(),FW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B,Hi,ti,Ya,Qa],B]}),n})(),NW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),$W=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[CS,B],B]}),n})(),GW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[Qa,ZE,m$,fS,bS,CS,S$,t8,n8,r8,ul,u8,h8,M8,L8,u4,T4,U4,JS,$4,CU,WS,a$,rG,cG,U3,bG,DG,AG,UG,ti,qE,GG,gE,sW,lW,hW,TW,FW,NW,ik,$W,ji,Hi,Ud]}),n})(),WW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n,bootstrap:[f$]}),n.\\u0275inj=P({providers:[],imports:[[FD,B2,Pz,Fz,Nj,gE,GW]]}),n})();(function YF(){G0=!1})(),console.info(\"Angular CDK version\",Lm.full),console.info(\"Angular Material version\",Jm.full),oB().bootstrapModule(WW).catch(n=>console.error(n))}},De=>{De(De.s=532)}]);", "file_path": "docs/main.e3e00859dfd66644.js", "rank": 17, "score": 97647.15064309725 }, { "content": "export class Base58DecodingError extends Error {\n\n public name = 'Base58DecodingError';\n\n constructor(public message: string) {\n\n super(message);\n\n }\n", "file_path": "HTLC/lambda_function_for_tokens/taquito-michel-codec/src/base58.ts", "rank": 18, "score": 97161.06782682492 }, { "content": "\"use strict\";(self.webpackChunkbridge=self.webpackChunkbridge||[]).push([[179],{532:()=>{function De(n){return\"function\"==typeof n}function xo(n){const e=n(i=>{Error.call(i),i.stack=(new Error).stack});return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}const fl=xo(n=>function(e){n(this),this.message=e?`${e.length} errors occurred during unsubscription:\\n${e.map((i,r)=>`${r+1}) ${i.toString()}`).join(\"\\n \")}`:\"\",this.name=\"UnsubscriptionError\",this.errors=e});function ss(n,t){if(n){const e=n.indexOf(t);0<=e&&n.splice(e,1)}}class ke{constructor(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}unsubscribe(){let t;if(!this.closed){this.closed=!0;const{_parentage:e}=this;if(e)if(this._parentage=null,Array.isArray(e))for(const s of e)s.remove(this);else e.remove(this);const{initialTeardown:i}=this;if(De(i))try{i()}catch(s){t=s instanceof fl?s.errors:[s]}const{_finalizers:r}=this;if(r){this._finalizers=null;for(const s of r)try{t_(s)}catch(o){t=null!=t?t:[],o instanceof fl?t=[...t,...o.errors]:t.push(o)}}if(t)throw new fl(t)}}add(t){var e;if(t&&t!==this)if(this.closed)t_(t);else{if(t instanceof ke){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(e=this._finalizers)&&void 0!==e?e:[]).push(t)}}_hasParent(t){const{_parentage:e}=this;return e===t||Array.isArray(e)&&e.includes(t)}_addParent(t){const{_parentage:e}=this;this._parentage=Array.isArray(e)?(e.push(t),e):e?[e,t]:t}_removeParent(t){const{_parentage:e}=this;e===t?this._parentage=null:Array.isArray(e)&&ss(e,t)}remove(t){const{_finalizers:e}=this;e&&ss(e,t),t instanceof ke&&t._removeParent(this)}}ke.EMPTY=(()=>{const n=new ke;return n.closed=!0,n})();const Jg=ke.EMPTY;function e_(n){return n instanceof ke||n&&\"closed\"in n&&De(n.remove)&&De(n.add)&&De(n.unsubscribe)}function t_(n){De(n)?n():n.unsubscribe()}const fr={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},ml={setTimeout(n,t,...e){const{delegate:i}=ml;return(null==i?void 0:i.setTimeout)?i.setTimeout(n,t,...e):setTimeout(n,t,...e)},clearTimeout(n){const{delegate:t}=ml;return((null==t?void 0:t.clearTimeout)||clearTimeout)(n)},delegate:void 0};function n_(n){ml.setTimeout(()=>{const{onUnhandledError:t}=fr;if(!t)throw n;t(n)})}function gl(){}const fk=fu(\"C\",void 0,void 0);function fu(n,t,e){return{kind:n,value:t,error:e}}let mr=null;function _l(n){if(fr.useDeprecatedSynchronousErrorHandling){const t=!mr;if(t&&(mr={errorThrown:!1,error:null}),n(),t){const{errorThrown:e,error:i}=mr;if(mr=null,e)throw i}}else n()}class mu extends ke{constructor(t){super(),this.isStopped=!1,t?(this.destination=t,e_(t)&&t.add(this)):this.destination=Ck}static create(t,e,i){return new vl(t,e,i)}next(t){this.isStopped?_u(function gk(n){return fu(\"N\",n,void 0)}(t),this):this._next(t)}error(t){this.isStopped?_u(function mk(n){return fu(\"E\",void 0,n)}(t),this):(this.isStopped=!0,this._error(t))}complete(){this.isStopped?_u(fk,this):(this.isStopped=!0,this._complete())}unsubscribe(){this.closed||(this.isStopped=!0,super.unsubscribe(),this.destination=null)}_next(t){this.destination.next(t)}_error(t){try{this.destination.error(t)}finally{this.unsubscribe()}}_complete(){try{this.destination.complete()}finally{this.unsubscribe()}}}const vk=Function.prototype.bind;function gu(n,t){return vk.call(n,t)}class yk{constructor(t){this.partialObserver=t}next(t){const{partialObserver:e}=this;if(e.next)try{e.next(t)}catch(i){yl(i)}}error(t){const{partialObserver:e}=this;if(e.error)try{e.error(t)}catch(i){yl(i)}else yl(t)}complete(){const{partialObserver:t}=this;if(t.complete)try{t.complete()}catch(e){yl(e)}}}class vl extends mu{constructor(t,e,i){let r;if(super(),De(t)||!t)r={next:null!=t?t:void 0,error:null!=e?e:void 0,complete:null!=i?i:void 0};else{let s;this&&fr.useDeprecatedNextContext?(s=Object.create(t),s.unsubscribe=()=>this.unsubscribe(),r={next:t.next&&gu(t.next,s),error:t.error&&gu(t.error,s),complete:t.complete&&gu(t.complete,s)}):r=t}this.destination=new yk(r)}}function yl(n){fr.useDeprecatedSynchronousErrorHandling?function _k(n){fr.useDeprecatedSynchronousErrorHandling&&mr&&(mr.errorThrown=!0,mr.error=n)}(n):n_(n)}function _u(n,t){const{onStoppedNotification:e}=fr;e&&ml.setTimeout(()=>e(n,t))}const Ck={closed:!0,next:gl,error:function bk(n){throw n},complete:gl},vu=\"function\"==typeof Symbol&&Symbol.observable||\"@@observable\";function Wi(n){return n}let Ve=(()=>{class n{constructor(e){e&&(this._subscribe=e)}lift(e){const i=new n;return i.source=this,i.operator=e,i}subscribe(e,i,r){const s=function wk(n){return n&&n instanceof mu||function Dk(n){return n&&De(n.next)&&De(n.error)&&De(n.complete)}(n)&&e_(n)}(e)?e:new vl(e,i,r);return _l(()=>{const{operator:o,source:a}=this;s.add(o?o.call(s,a):a?this._subscribe(s):this._trySubscribe(s))}),s}_trySubscribe(e){try{return this._subscribe(e)}catch(i){e.error(i)}}forEach(e,i){return new(i=r_(i))((r,s)=>{const o=new vl({next:a=>{try{e(a)}catch(l){s(l),o.unsubscribe()}},error:s,complete:r});this.subscribe(o)})}_subscribe(e){var i;return null===(i=this.source)||void 0===i?void 0:i.subscribe(e)}[vu](){return this}pipe(...e){return function i_(n){return 0===n.length?Wi:1===n.length?n[0]:function(e){return n.reduce((i,r)=>r(i),e)}}(e)(this)}toPromise(e){return new(e=r_(e))((i,r)=>{let s;this.subscribe(o=>s=o,o=>r(o),()=>i(s))})}}return n.create=t=>new n(t),n})();function r_(n){var t;return null!==(t=null!=n?n:fr.Promise)&&void 0!==t?t:Promise}const Mk=xo(n=>function(){n(this),this.name=\"ObjectUnsubscribedError\",this.message=\"object unsubscribed\"});let O=(()=>{class n extends Ve{constructor(){super(),this.closed=!1,this.currentObservers=null,this.observers=[],this.isStopped=!1,this.hasError=!1,this.thrownError=null}lift(e){const i=new s_(this,this);return i.operator=e,i}_throwIfClosed(){if(this.closed)throw new Mk}next(e){_l(()=>{if(this._throwIfClosed(),!this.isStopped){this.currentObservers||(this.currentObservers=Array.from(this.observers));for(const i of this.currentObservers)i.next(e)}})}error(e){_l(()=>{if(this._throwIfClosed(),!this.isStopped){this.hasError=this.isStopped=!0,this.thrownError=e;const{observers:i}=this;for(;i.length;)i.shift().error(e)}})}complete(){_l(()=>{if(this._throwIfClosed(),!this.isStopped){this.isStopped=!0;const{observers:e}=this;for(;e.length;)e.shift().complete()}})}unsubscribe(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null}get observed(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0}_trySubscribe(e){return this._throwIfClosed(),super._trySubscribe(e)}_subscribe(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)}_innerSubscribe(e){const{hasError:i,isStopped:r,observers:s}=this;return i||r?Jg:(this.currentObservers=null,s.push(e),new ke(()=>{this.currentObservers=null,ss(s,e)}))}_checkFinalizedStatuses(e){const{hasError:i,thrownError:r,isStopped:s}=this;i?e.error(r):s&&e.complete()}asObservable(){const e=new Ve;return e.source=this,e}}return n.create=(t,e)=>new s_(t,e),n})();class s_ extends O{constructor(t,e){super(),this.destination=t,this.source=e}next(t){var e,i;null===(i=null===(e=this.destination)||void 0===e?void 0:e.next)||void 0===i||i.call(e,t)}error(t){var e,i;null===(i=null===(e=this.destination)||void 0===e?void 0:e.error)||void 0===i||i.call(e,t)}complete(){var t,e;null===(e=null===(t=this.destination)||void 0===t?void 0:t.complete)||void 0===e||e.call(t)}_subscribe(t){var e,i;return null!==(i=null===(e=this.source)||void 0===e?void 0:e.subscribe(t))&&void 0!==i?i:Jg}}function o_(n){return De(null==n?void 0:n.lift)}function qe(n){return t=>{if(o_(t))return t.lift(function(e){try{return n(e,this)}catch(i){this.error(i)}});throw new TypeError(\"Unable to lift unknown Observable type\")}}function Ue(n,t,e,i,r){return new xk(n,t,e,i,r)}class xk extends mu{constructor(t,e,i,r,s,o){super(t),this.onFinalize=s,this.shouldUnsubscribe=o,this._next=e?function(a){try{e(a)}catch(l){t.error(l)}}:super._next,this._error=r?function(a){try{r(a)}catch(l){t.error(l)}finally{this.unsubscribe()}}:super._error,this._complete=i?function(){try{i()}catch(a){t.error(a)}finally{this.unsubscribe()}}:super._complete}unsubscribe(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){const{closed:e}=this;super.unsubscribe(),!e&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}}}function ue(n,t){return qe((e,i)=>{let r=0;e.subscribe(Ue(i,s=>{i.next(n.call(t,s,r++))}))})}function gr(n){return this instanceof gr?(this.v=n,this):new gr(n)}function kk(n,t,e){if(!Symbol.asyncIterator)throw new TypeError(\"Symbol.asyncIterator is not defined.\");var r,i=e.apply(n,t||[]),s=[];return r={},o(\"next\"),o(\"throw\"),o(\"return\"),r[Symbol.asyncIterator]=function(){return this},r;function o(h){i[h]&&(r[h]=function(p){return new Promise(function(m,g){s.push([h,p,m,g])>1||a(h,p)})})}function a(h,p){try{!function l(h){h.value instanceof gr?Promise.resolve(h.value.v).then(c,d):u(s[0][2],h)}(i[h](p))}catch(m){u(s[0][3],m)}}function c(h){a(\"next\",h)}function d(h){a(\"throw\",h)}function u(h,p){h(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function Tk(n){if(!Symbol.asyncIterator)throw new TypeError(\"Symbol.asyncIterator is not defined.\");var e,t=n[Symbol.asyncIterator];return t?t.call(n):(n=function c_(n){var t=\"function\"==typeof Symbol&&Symbol.iterator,e=t&&n[t],i=0;if(e)return e.call(n);if(n&&\"number\"==typeof n.length)return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(t?\"Object is not iterable.\":\"Symbol.iterator is not defined.\")}(n),e={},i(\"next\"),i(\"throw\"),i(\"return\"),e[Symbol.asyncIterator]=function(){return this},e);function i(s){e[s]=n[s]&&function(o){return new Promise(function(a,l){!function r(s,o,a,l){Promise.resolve(l).then(function(c){s({value:c,done:a})},o)}(a,l,(o=n[s](o)).done,o.value)})}}}const bu=n=>n&&\"number\"==typeof n.length&&\"function\"!=typeof n;function d_(n){return De(null==n?void 0:n.then)}function u_(n){return De(n[vu])}function h_(n){return Symbol.asyncIterator&&De(null==n?void 0:n[Symbol.asyncIterator])}function p_(n){return new TypeError(`You provided ${null!==n&&\"object\"==typeof n?\"an invalid object\":`'${n}'`} where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.`)}const f_=function Ik(){return\"function\"==typeof Symbol&&Symbol.iterator?Symbol.iterator:\"@@iterator\"}();function m_(n){return De(null==n?void 0:n[f_])}function g_(n){return kk(this,arguments,function*(){const e=n.getReader();try{for(;;){const{value:i,done:r}=yield gr(e.read());if(r)return yield gr(void 0);yield yield gr(i)}}finally{e.releaseLock()}})}function __(n){return De(null==n?void 0:n.getReader)}function Jt(n){if(n instanceof Ve)return n;if(null!=n){if(u_(n))return function Rk(n){return new Ve(t=>{const e=n[vu]();if(De(e.subscribe))return e.subscribe(t);throw new TypeError(\"Provided object does not correctly implement Symbol.observable\")})}(n);if(bu(n))return function Ok(n){return new Ve(t=>{for(let e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()})}(n);if(d_(n))return function Pk(n){return new Ve(t=>{n.then(e=>{t.closed||(t.next(e),t.complete())},e=>t.error(e)).then(null,n_)})}(n);if(h_(n))return v_(n);if(m_(n))return function Fk(n){return new Ve(t=>{for(const e of n)if(t.next(e),t.closed)return;t.complete()})}(n);if(__(n))return function Nk(n){return v_(g_(n))}(n)}throw p_(n)}function v_(n){return new Ve(t=>{(function Lk(n,t){var e,i,r,s;return function Ek(n,t,e,i){return new(e||(e=Promise))(function(s,o){function a(d){try{c(i.next(d))}catch(u){o(u)}}function l(d){try{c(i.throw(d))}catch(u){o(u)}}function c(d){d.done?s(d.value):function r(s){return s instanceof e?s:new e(function(o){o(s)})}(d.value).then(a,l)}c((i=i.apply(n,t||[])).next())})}(this,void 0,void 0,function*(){try{for(e=Tk(n);!(i=yield e.next()).done;)if(t.next(i.value),t.closed)return}catch(o){r={error:o}}finally{try{i&&!i.done&&(s=e.return)&&(yield s.call(e))}finally{if(r)throw r.error}}t.complete()})})(n,t).catch(e=>t.error(e))})}function Mi(n,t,e,i=0,r=!1){const s=t.schedule(function(){e(),r?n.add(this.schedule(null,i)):this.unsubscribe()},i);if(n.add(s),!r)return s}function lt(n,t,e=1/0){return De(t)?lt((i,r)=>ue((s,o)=>t(i,s,r,o))(Jt(n(i,r))),e):(\"number\"==typeof t&&(e=t),qe((i,r)=>function Bk(n,t,e,i,r,s,o,a){const l=[];let c=0,d=0,u=!1;const h=()=>{u&&!l.length&&!c&&t.complete()},p=g=>c<i?m(g):l.push(g),m=g=>{s&&t.next(g),c++;let _=!1;Jt(e(g,d++)).subscribe(Ue(t,D=>{null==r||r(D),s?p(D):t.next(D)},()=>{_=!0},void 0,()=>{if(_)try{for(c--;l.length&&c<i;){const D=l.shift();o?Mi(t,o,()=>m(D)):m(D)}h()}catch(D){t.error(D)}}))};return n.subscribe(Ue(t,p,()=>{u=!0,h()})),()=>{null==a||a()}}(i,r,n,e)))}function Eo(n=1/0){return lt(Wi,n)}const ri=new Ve(n=>n.complete());function y_(n){return n&&De(n.schedule)}function Cu(n){return n[n.length-1]}function b_(n){return De(Cu(n))?n.pop():void 0}function So(n){return y_(Cu(n))?n.pop():void 0}function C_(n,t=0){return qe((e,i)=>{e.subscribe(Ue(i,r=>Mi(i,n,()=>i.next(r),t),()=>Mi(i,n,()=>i.complete(),t),r=>Mi(i,n,()=>i.error(r),t)))})}function D_(n,t=0){return qe((e,i)=>{i.add(n.schedule(()=>e.subscribe(i),t))})}function w_(n,t){if(!n)throw new Error(\"Iterable cannot be null\");return new Ve(e=>{Mi(e,t,()=>{const i=n[Symbol.asyncIterator]();Mi(e,t,()=>{i.next().then(r=>{r.done?e.complete():e.next(r.value)})},0,!0)})})}function mt(n,t){return t?function Wk(n,t){if(null!=n){if(u_(n))return function jk(n,t){return Jt(n).pipe(D_(t),C_(t))}(n,t);if(bu(n))return function Uk(n,t){return new Ve(e=>{let i=0;return t.schedule(function(){i===n.length?e.complete():(e.next(n[i++]),e.closed||this.schedule())})})}(n,t);if(d_(n))return function zk(n,t){return Jt(n).pipe(D_(t),C_(t))}(n,t);if(h_(n))return w_(n,t);if(m_(n))return function $k(n,t){return new Ve(e=>{let i;return Mi(e,t,()=>{i=n[f_](),Mi(e,t,()=>{let r,s;try{({value:r,done:s}=i.next())}catch(o){return void e.error(o)}s?e.complete():e.next(r)},0,!0)}),()=>De(null==i?void 0:i.return)&&i.return()})}(n,t);if(__(n))return function Gk(n,t){return w_(g_(n),t)}(n,t)}throw p_(n)}(n,t):Jt(n)}function Bt(...n){const t=So(n),e=function Hk(n,t){return\"number\"==typeof Cu(n)?n.pop():t}(n,1/0),i=n;return i.length?1===i.length?Jt(i[0]):Eo(e)(mt(i,t)):ri}function it(n){return n<=0?()=>ri:qe((t,e)=>{let i=0;t.subscribe(Ue(e,r=>{++i<=n&&(e.next(r),n<=i&&e.complete())}))})}function Du(n,t,...e){return!0===t?(n(),null):!1===t?null:t(...e).pipe(it(1)).subscribe(()=>n())}function Fe(n){for(let t in n)if(n[t]===Fe)return t;throw Error(\"Could not find renamed property on target object.\")}function wu(n,t){for(const e in t)t.hasOwnProperty(e)&&!n.hasOwnProperty(e)&&(n[e]=t[e])}function Re(n){if(\"string\"==typeof n)return n;if(Array.isArray(n))return\"[\"+n.map(Re).join(\", \")+\"]\";if(null==n)return\"\"+n;if(n.overriddenName)return`${n.overriddenName}`;if(n.name)return`${n.name}`;const t=n.toString();if(null==t)return\"\"+t;const e=t.indexOf(\"\\n\");return-1===e?t:t.substring(0,e)}function Mu(n,t){return null==n||\"\"===n?null===t?\"\":t:null==t||\"\"===t?n:n+\" \"+t}const qk=Fe({__forward_ref__:Fe});function pe(n){return n.__forward_ref__=pe,n.toString=function(){return Re(this())},n}function le(n){return x_(n)?n():n}function x_(n){return\"function\"==typeof n&&n.hasOwnProperty(qk)&&n.__forward_ref__===pe}class H extends Error{constructor(t,e){super(function xu(n,t){return`NG0${Math.abs(n)}${t?\": \"+t:\"\"}`}(t,e)),this.code=t}}function re(n){return\"string\"==typeof n?n:null==n?\"\":String(n)}function Vt(n){return\"function\"==typeof n?n.name||n.toString():\"object\"==typeof n&&null!=n&&\"function\"==typeof n.type?n.type.name||n.type.toString():re(n)}function bl(n,t){const e=t?` in ${t}`:\"\";throw new H(-201,`No provider for ${Vt(n)} found${e}`)}function tn(n,t){null==n&&function $e(n,t,e,i){throw new Error(`ASSERTION ERROR: ${n}`+(null==i?\"\":` [Expected=> ${e} ${i} ${t} <=Actual]`))}(t,n,null,\"!=\")}function k(n){return{token:n.token,providedIn:n.providedIn||null,factory:n.factory,value:void 0}}function P(n){return{providers:n.providers||[],imports:n.imports||[]}}function Eu(n){return E_(n,Cl)||E_(n,k_)}function E_(n,t){return n.hasOwnProperty(t)?n[t]:null}function S_(n){return n&&(n.hasOwnProperty(Su)||n.hasOwnProperty(eT))?n[Su]:null}const Cl=Fe({\\u0275prov:Fe}),Su=Fe({\\u0275inj:Fe}),k_=Fe({ngInjectableDef:Fe}),eT=Fe({ngInjectorDef:Fe});var ee=(()=>((ee=ee||{})[ee.Default=0]=\"Default\",ee[ee.Host=1]=\"Host\",ee[ee.Self=2]=\"Self\",ee[ee.SkipSelf=4]=\"SkipSelf\",ee[ee.Optional=8]=\"Optional\",ee))();let ku;function qi(n){const t=ku;return ku=n,t}function T_(n,t,e){const i=Eu(n);return i&&\"root\"==i.providedIn?void 0===i.value?i.value=i.factory():i.value:e&ee.Optional?null:void 0!==t?t:void bl(Re(n),\"Injector\")}function Yi(n){return{toString:n}.toString()}var Nn=(()=>((Nn=Nn||{})[Nn.OnPush=0]=\"OnPush\",Nn[Nn.Default=1]=\"Default\",Nn))(),Ln=(()=>{return(n=Ln||(Ln={}))[n.Emulated=0]=\"Emulated\",n[n.None=2]=\"None\",n[n.ShadowDom=3]=\"ShadowDom\",Ln;var n})();const nT=\"undefined\"!=typeof globalThis&&globalThis,iT=\"undefined\"!=typeof window&&window,rT=\"undefined\"!=typeof self&&\"undefined\"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&self,Oe=nT||\"undefined\"!=typeof global&&global||iT||rT,os={},Ne=[],Dl=Fe({\\u0275cmp:Fe}),Tu=Fe({\\u0275dir:Fe}),Au=Fe({\\u0275pipe:Fe}),A_=Fe({\\u0275mod:Fe}),Ei=Fe({\\u0275fac:Fe}),ko=Fe({__NG_ELEMENT_ID__:Fe});let sT=0;function xe(n){return Yi(()=>{const e={},i={type:n.type,providersResolver:null,decls:n.decls,vars:n.vars,factory:null,template:n.template||null,consts:n.consts||null,ngContentSelectors:n.ngContentSelectors,hostBindings:n.hostBindings||null,hostVars:n.hostVars||0,hostAttrs:n.hostAttrs||null,contentQueries:n.contentQueries||null,declaredInputs:e,inputs:null,outputs:null,exportAs:n.exportAs||null,onPush:n.changeDetection===Nn.OnPush,directiveDefs:null,pipeDefs:null,selectors:n.selectors||Ne,viewQuery:n.viewQuery||null,features:n.features||null,data:n.data||{},encapsulation:n.encapsulation||Ln.Emulated,id:\"c\",styles:n.styles||Ne,_:null,setInput:null,schemas:n.schemas||null,tView:null},r=n.directives,s=n.features,o=n.pipes;return i.id+=sT++,i.inputs=P_(n.inputs,e),i.outputs=P_(n.outputs),s&&s.forEach(a=>a(i)),i.directiveDefs=r?()=>(\"function\"==typeof r?r():r).map(I_):null,i.pipeDefs=o?()=>(\"function\"==typeof o?o():o).map(R_):null,i})}function I_(n){return Ot(n)||function Qi(n){return n[Tu]||null}(n)}function R_(n){return function _r(n){return n[Au]||null}(n)}const O_={};function F(n){return Yi(()=>{const t={type:n.type,bootstrap:n.bootstrap||Ne,declarations:n.declarations||Ne,imports:n.imports||Ne,exports:n.exports||Ne,transitiveCompileScopes:null,schemas:n.schemas||null,id:n.id||null};return null!=n.id&&(O_[n.id]=n.type),t})}function P_(n,t){if(null==n)return os;const e={};for(const i in n)if(n.hasOwnProperty(i)){let r=n[i],s=r;Array.isArray(r)&&(s=r[1],r=r[0]),e[r]=i,t&&(t[r]=s)}return e}const C=xe;function Ot(n){return n[Dl]||null}function gn(n,t){const e=n[A_]||null;if(!e&&!0===t)throw new Error(`Type ${Re(n)} does not have '\\u0275mod' property.`);return e}function si(n){return Array.isArray(n)&&\"object\"==typeof n[1]}function Vn(n){return Array.isArray(n)&&!0===n[1]}function Ou(n){return 0!=(8&n.flags)}function El(n){return 2==(2&n.flags)}function Sl(n){return 1==(1&n.flags)}function Hn(n){return null!==n.template}function uT(n){return 0!=(512&n[2])}function Cr(n,t){return n.hasOwnProperty(Ei)?n[Ei]:null}class fT{constructor(t,e,i){this.previousValue=t,this.currentValue=e,this.firstChange=i}isFirstChange(){return this.firstChange}}function Je(){return N_}function N_(n){return n.type.prototype.ngOnChanges&&(n.setInput=gT),mT}function mT(){const n=B_(this),t=null==n?void 0:n.current;if(t){const e=n.previous;if(e===os)n.previous=t;else for(let i in t)e[i]=t[i];n.current=null,this.ngOnChanges(t)}}function gT(n,t,e,i){const r=B_(n)||function _T(n,t){return n[L_]=t}(n,{previous:os,current:null}),s=r.current||(r.current={}),o=r.previous,a=this.declaredInputs[e],l=o[a];s[a]=new fT(l&&l.currentValue,t,o===os),n[i]=t}Je.ngInherit=!0;const L_=\"__ngSimpleChanges__\";function B_(n){return n[L_]||null}let Bu;function et(n){return!!n.listen}const V_={createRenderer:(n,t)=>function Vu(){return void 0!==Bu?Bu:\"undefined\"!=typeof document?document:void 0}()};function ct(n){for(;Array.isArray(n);)n=n[0];return n}function kl(n,t){return ct(t[n])}function yn(n,t){return ct(t[n.index])}function Hu(n,t){return n.data[t]}function rn(n,t){const e=t[n];return si(e)?e:e[0]}function H_(n){return 4==(4&n[2])}function ju(n){return 128==(128&n[2])}function Ki(n,t){return null==t?null:n[t]}function j_(n){n[18]=0}function zu(n,t){n[5]+=t;let e=n,i=n[3];for(;null!==i&&(1===t&&1===e[5]||-1===t&&0===e[5]);)i[5]+=t,e=i,i=i[3]}const te={lFrame:Q_(null),bindingsEnabled:!0,isInCheckNoChangesMode:!1};function z_(){return te.bindingsEnabled}function w(){return te.lFrame.lView}function Me(){return te.lFrame.tView}function Dr(n){return te.lFrame.contextLView=n,n[8]}function gt(){let n=U_();for(;null!==n&&64===n.type;)n=n.parent;return n}function U_(){return te.lFrame.currentTNode}function oi(n,t){const e=te.lFrame;e.currentTNode=n,e.isParent=t}function Uu(){return te.lFrame.isParent}function $u(){te.lFrame.isParent=!1}function Tl(){return te.isInCheckNoChangesMode}function Al(n){te.isInCheckNoChangesMode=n}function hs(){return te.lFrame.bindingIndex++}function ki(n){const t=te.lFrame,e=t.bindingIndex;return t.bindingIndex=t.bindingIndex+n,e}function PT(n,t){const e=te.lFrame;e.bindingIndex=e.bindingRootIndex=n,Gu(t)}function Gu(n){te.lFrame.currentDirectiveIndex=n}function Wu(n){const t=te.lFrame.currentDirectiveIndex;return-1===t?null:n[t]}function W_(){return te.lFrame.currentQueryIndex}function qu(n){te.lFrame.currentQueryIndex=n}function NT(n){const t=n[1];return 2===t.type?t.declTNode:1===t.type?n[6]:null}function q_(n,t,e){if(e&ee.SkipSelf){let r=t,s=n;for(;!(r=r.parent,null!==r||e&ee.Host||(r=NT(s),null===r||(s=s[15],10&r.type))););if(null===r)return!1;t=r,n=s}const i=te.lFrame=Y_();return i.currentTNode=t,i.lView=n,!0}function Il(n){const t=Y_(),e=n[1];te.lFrame=t,t.currentTNode=e.firstChild,t.lView=n,t.tView=e,t.contextLView=n,t.bindingIndex=e.bindingStartIndex,t.inI18n=!1}function Y_(){const n=te.lFrame,t=null===n?null:n.child;return null===t?Q_(n):t}function Q_(n){const t={currentTNode:null,isParent:!0,lView:null,tView:null,selectedIndex:-1,contextLView:null,elementDepthCount:0,currentNamespace:null,currentDirectiveIndex:-1,bindingRootIndex:-1,bindingIndex:-1,currentQueryIndex:0,parent:n,child:null,inI18n:!1};return null!==n&&(n.child=t),t}function K_(){const n=te.lFrame;return te.lFrame=n.parent,n.currentTNode=null,n.lView=null,n}const Z_=K_;function Rl(){const n=K_();n.isParent=!0,n.tView=null,n.selectedIndex=-1,n.contextLView=null,n.elementDepthCount=0,n.currentDirectiveIndex=-1,n.currentNamespace=null,n.bindingRootIndex=-1,n.bindingIndex=-1,n.currentQueryIndex=0}function jt(){return te.lFrame.selectedIndex}function Zi(n){te.lFrame.selectedIndex=n}function tt(){const n=te.lFrame;return Hu(n.tView,n.selectedIndex)}function Oo(){te.lFrame.currentNamespace=\"svg\"}function Ol(n,t){for(let e=t.directiveStart,i=t.directiveEnd;e<i;e++){const s=n.data[e].type.prototype,{ngAfterContentInit:o,ngAfterContentChecked:a,ngAfterViewInit:l,ngAfterViewChecked:c,ngOnDestroy:d}=s;o&&(n.contentHooks||(n.contentHooks=[])).push(-e,o),a&&((n.contentHooks||(n.contentHooks=[])).push(e,a),(n.contentCheckHooks||(n.contentCheckHooks=[])).push(e,a)),l&&(n.viewHooks||(n.viewHooks=[])).push(-e,l),c&&((n.viewHooks||(n.viewHooks=[])).push(e,c),(n.viewCheckHooks||(n.viewCheckHooks=[])).push(e,c)),null!=d&&(n.destroyHooks||(n.destroyHooks=[])).push(e,d)}}function Pl(n,t,e){J_(n,t,3,e)}function Fl(n,t,e,i){(3&n[2])===e&&J_(n,t,e,i)}function Yu(n,t){let e=n[2];(3&e)===t&&(e&=2047,e+=1,n[2]=e)}function J_(n,t,e,i){const s=null!=i?i:-1,o=t.length-1;let a=0;for(let l=void 0!==i?65535&n[18]:0;l<o;l++)if(\"number\"==typeof t[l+1]){if(a=t[l],null!=i&&a>=i)break}else t[l]<0&&(n[18]+=65536),(a<s||-1==s)&&(UT(n,e,t,l),n[18]=(4294901760&n[18])+l+2),l++}function UT(n,t,e,i){const r=e[i]<0,s=e[i+1],a=n[r?-e[i]:e[i]];if(r){if(n[2]>>11<n[18]>>16&&(3&n[2])===t){n[2]+=2048;try{s.call(a)}finally{}}}else try{s.call(a)}finally{}}class Po{constructor(t,e,i){this.factory=t,this.resolving=!1,this.canSeeViewProviders=e,this.injectImpl=i}}function Nl(n,t,e){const i=et(n);let r=0;for(;r<e.length;){const s=e[r];if(\"number\"==typeof s){if(0!==s)break;r++;const o=e[r++],a=e[r++],l=e[r++];i?n.setAttribute(t,a,l,o):t.setAttributeNS(o,a,l)}else{const o=s,a=e[++r];Ku(o)?i&&n.setProperty(t,o,a):i?n.setAttribute(t,o,a):t.setAttribute(o,a),r++}}return r}function ev(n){return 3===n||4===n||6===n}function Ku(n){return 64===n.charCodeAt(0)}function Ll(n,t){if(null!==t&&0!==t.length)if(null===n||0===n.length)n=t.slice();else{let e=-1;for(let i=0;i<t.length;i++){const r=t[i];\"number\"==typeof r?e=r:0===e||tv(n,e,r,null,-1===e||2===e?t[++i]:null)}}return n}function tv(n,t,e,i,r){let s=0,o=n.length;if(-1===t)o=-1;else for(;s<n.length;){const a=n[s++];if(\"number\"==typeof a){if(a===t){o=-1;break}if(a>t){o=s-1;break}}}for(;s<n.length;){const a=n[s];if(\"number\"==typeof a)break;if(a===e){if(null===i)return void(null!==r&&(n[s+1]=r));if(i===n[s+1])return void(n[s+2]=r)}s++,null!==i&&s++,null!==r&&s++}-1!==o&&(n.splice(o,0,t),s=o+1),n.splice(s++,0,e),null!==i&&n.splice(s++,0,i),null!==r&&n.splice(s++,0,r)}function nv(n){return-1!==n}function ps(n){return 32767&n}function fs(n,t){let e=function YT(n){return n>>16}(n),i=t;for(;e>0;)i=i[15],e--;return i}let Zu=!0;function Bl(n){const t=Zu;return Zu=n,t}let QT=0;function No(n,t){const e=Ju(n,t);if(-1!==e)return e;const i=t[1];i.firstCreatePass&&(n.injectorIndex=t.length,Xu(i.data,n),Xu(t,null),Xu(i.blueprint,null));const r=Vl(n,t),s=n.injectorIndex;if(nv(r)){const o=ps(r),a=fs(r,t),l=a[1].data;for(let c=0;c<8;c++)t[s+c]=a[o+c]|l[o+c]}return t[s+8]=r,s}function Xu(n,t){n.push(0,0,0,0,0,0,0,0,t)}function Ju(n,t){return-1===n.injectorIndex||n.parent&&n.parent.injectorIndex===n.injectorIndex||null===t[n.injectorIndex+8]?-1:n.injectorIndex}function Vl(n,t){if(n.parent&&-1!==n.parent.injectorIndex)return n.parent.injectorIndex;let e=0,i=null,r=t;for(;null!==r;){const s=r[1],o=s.type;if(i=2===o?s.declTNode:1===o?r[6]:null,null===i)return-1;if(e++,r=r[15],-1!==i.injectorIndex)return i.injectorIndex|e<<16}return-1}function Hl(n,t,e){!function KT(n,t,e){let i;\"string\"==typeof e?i=e.charCodeAt(0)||0:e.hasOwnProperty(ko)&&(i=e[ko]),null==i&&(i=e[ko]=QT++);const r=255&i;t.data[n+(r>>5)]|=1<<r}(n,t,e)}function sv(n,t,e){if(e&ee.Optional)return n;bl(t,\"NodeInjector\")}function ov(n,t,e,i){if(e&ee.Optional&&void 0===i&&(i=null),0==(e&(ee.Self|ee.Host))){const r=n[9],s=qi(void 0);try{return r?r.get(t,i,e&ee.Optional):T_(t,i,e&ee.Optional)}finally{qi(s)}}return sv(i,t,e)}function av(n,t,e,i=ee.Default,r){if(null!==n){const s=function eA(n){if(\"string\"==typeof n)return n.charCodeAt(0)||0;const t=n.hasOwnProperty(ko)?n[ko]:void 0;return\"number\"==typeof t?t>=0?255&t:XT:t}(e);if(\"function\"==typeof s){if(!q_(t,n,i))return i&ee.Host?sv(r,e,i):ov(t,e,i,r);try{const o=s(i);if(null!=o||i&ee.Optional)return o;bl(e)}finally{Z_()}}else if(\"number\"==typeof s){let o=null,a=Ju(n,t),l=-1,c=i&ee.Host?t[16][6]:null;for((-1===a||i&ee.SkipSelf)&&(l=-1===a?Vl(n,t):t[a+8],-1!==l&&dv(i,!1)?(o=t[1],a=ps(l),t=fs(l,t)):a=-1);-1!==a;){const d=t[1];if(cv(s,a,d.data)){const u=JT(a,t,e,o,i,c);if(u!==lv)return u}l=t[a+8],-1!==l&&dv(i,t[1].data[a+8]===c)&&cv(s,a,t)?(o=d,a=ps(l),t=fs(l,t)):a=-1}}}return ov(t,e,i,r)}const lv={};function XT(){return new ms(gt(),w())}function JT(n,t,e,i,r,s){const o=t[1],a=o.data[n+8],d=jl(a,o,e,null==i?El(a)&&Zu:i!=o&&0!=(3&a.type),r&ee.Host&&s===a);return null!==d?Lo(t,o,d,a):lv}function jl(n,t,e,i,r){const s=n.providerIndexes,o=t.data,a=1048575&s,l=n.directiveStart,d=s>>20,h=r?a+d:n.directiveEnd;for(let p=i?a:a+d;p<h;p++){const m=o[p];if(p<l&&e===m||p>=l&&m.type===e)return p}if(r){const p=o[l];if(p&&Hn(p)&&p.type===e)return l}return null}function Lo(n,t,e,i){let r=n[e];const s=t.data;if(function $T(n){return n instanceof Po}(r)){const o=r;o.resolving&&function Yk(n,t){const e=t?`. Dependency path: ${t.join(\" > \")} > ${n}`:\"\";throw new H(-200,`Circular dependency in DI detected for ${n}${e}`)}(Vt(s[e]));const a=Bl(o.canSeeViewProviders);o.resolving=!0;const l=o.injectImpl?qi(o.injectImpl):null;q_(n,i,ee.Default);try{r=n[e]=o.factory(void 0,s,n,i),t.firstCreatePass&&e>=i.directiveStart&&function zT(n,t,e){const{ngOnChanges:i,ngOnInit:r,ngDoCheck:s}=t.type.prototype;if(i){const o=N_(t);(e.preOrderHooks||(e.preOrderHooks=[])).push(n,o),(e.preOrderCheckHooks||(e.preOrderCheckHooks=[])).push(n,o)}r&&(e.preOrderHooks||(e.preOrderHooks=[])).push(0-n,r),s&&((e.preOrderHooks||(e.preOrderHooks=[])).push(n,s),(e.preOrderCheckHooks||(e.preOrderCheckHooks=[])).push(n,s))}(e,s[e],t)}finally{null!==l&&qi(l),Bl(a),o.resolving=!1,Z_()}}return r}function cv(n,t,e){return!!(e[t+(n>>5)]&1<<n)}function dv(n,t){return!(n&ee.Self||n&ee.Host&&t)}class ms{constructor(t,e){this._tNode=t,this._lView=e}get(t,e,i){return av(this._tNode,this._lView,t,i,e)}}function oe(n){return Yi(()=>{const t=n.prototype.constructor,e=t[Ei]||eh(t),i=Object.prototype;let r=Object.getPrototypeOf(n.prototype).constructor;for(;r&&r!==i;){const s=r[Ei]||eh(r);if(s&&s!==e)return s;r=Object.getPrototypeOf(r)}return s=>new s})}function eh(n){return x_(n)?()=>{const t=eh(le(n));return t&&t()}:Cr(n)}function kt(n){return function ZT(n,t){if(\"class\"===t)return n.classes;if(\"style\"===t)return n.styles;const e=n.attrs;if(e){const i=e.length;let r=0;for(;r<i;){const s=e[r];if(ev(s))break;if(0===s)r+=2;else if(\"number\"==typeof s)for(r++;r<i&&\"string\"==typeof e[r];)r++;else{if(s===t)return e[r+1];r+=2}}}return null}(gt(),n)}const _s=\"__parameters__\";function ys(n,t,e){return Yi(()=>{const i=function th(n){return function(...e){if(n){const i=n(...e);for(const r in i)this[r]=i[r]}}}(t);function r(...s){if(this instanceof r)return i.apply(this,s),this;const o=new r(...s);return a.annotation=o,a;function a(l,c,d){const u=l.hasOwnProperty(_s)?l[_s]:Object.defineProperty(l,_s,{value:[]})[_s];for(;u.length<=d;)u.push(null);return(u[d]=u[d]||[]).push(o),l}}return e&&(r.prototype=Object.create(e.prototype)),r.prototype.ngMetadataName=n,r.annotationCls=r,r})}class b{constructor(t,e){this._desc=t,this.ngMetadataName=\"InjectionToken\",this.\\u0275prov=void 0,\"number\"==typeof e?this.__NG_ELEMENT_ID__=e:void 0!==e&&(this.\\u0275prov=k({token:this,providedIn:e.providedIn||\"root\",factory:e.factory}))}toString(){return`InjectionToken ${this._desc}`}}const nA=new b(\"AnalyzeForEntryComponents\");function bn(n,t){void 0===t&&(t=n);for(let e=0;e<n.length;e++){let i=n[e];Array.isArray(i)?(t===n&&(t=n.slice(0,e)),bn(i,t)):t!==n&&t.push(i)}return t}function ai(n,t){n.forEach(e=>Array.isArray(e)?ai(e,t):t(e))}function hv(n,t,e){t>=n.length?n.push(e):n.splice(t,0,e)}function zl(n,t){return t>=n.length-1?n.pop():n.splice(t,1)[0]}function Ho(n,t){const e=[];for(let i=0;i<n;i++)e.push(t);return e}function sn(n,t,e){let i=bs(n,t);return i>=0?n[1|i]=e:(i=~i,function sA(n,t,e,i){let r=n.length;if(r==t)n.push(e,i);else if(1===r)n.push(i,n[0]),n[0]=e;else{for(r--,n.push(n[r-1],n[r]);r>t;)n[r]=n[r-2],r--;n[t]=e,n[t+1]=i}}(n,i,t,e)),i}function ih(n,t){const e=bs(n,t);if(e>=0)return n[1|e]}function bs(n,t){return function mv(n,t,e){let i=0,r=n.length>>e;for(;r!==i;){const s=i+(r-i>>1),o=n[s<<e];if(t===o)return s<<e;o>t?r=s:i=s+1}return~(r<<e)}(n,t,1)}const jo={},sh=\"__NG_DI_FLAG__\",$l=\"ngTempTokenPath\",hA=/\\n/gm,_v=\"__source\",fA=Fe({provide:String,useValue:Fe});let zo;function vv(n){const t=zo;return zo=n,t}function mA(n,t=ee.Default){if(void 0===zo)throw new H(203,\"\");return null===zo?T_(n,void 0,t):zo.get(n,t&ee.Optional?null:void 0,t)}function y(n,t=ee.Default){return(function tT(){return ku}()||mA)(le(n),t)}const Uo=y;function oh(n){const t=[];for(let e=0;e<n.length;e++){const i=le(n[e]);if(Array.isArray(i)){if(0===i.length)throw new H(900,\"\");let r,s=ee.Default;for(let o=0;o<i.length;o++){const a=i[o],l=gA(a);\"number\"==typeof l?-1===l?r=a.token:s|=l:r=a}t.push(y(r,s))}else t.push(y(i))}return t}function $o(n,t){return n[sh]=t,n.prototype[sh]=t,n}function gA(n){return n[sh]}const Gl=$o(ys(\"Inject\",n=>({token:n})),-1),Tt=$o(ys(\"Optional\"),8),Cn=$o(ys(\"SkipSelf\"),4);function on(n){return n instanceof class wr{constructor(t){this.changingThisBreaksApplicationSecurity=t}toString(){return`SafeValue must use [property]=binding: ${this.changingThisBreaksApplicationSecurity} (see https://g.co/ng/security#xss)`}}?n.changingThisBreaksApplicationSecurity:n}const Bv=\"__ngContext__\";function Ft(n,t){n[Bv]=t}function gh(n){const t=function Qo(n){return n[Bv]||null}(n);return t?Array.isArray(t)?t:t.lView:null}function vh(n){return n.ngOriginalError}function uI(n,...t){n.error(...t)}class Mr{constructor(){this._console=console}handleError(t){const e=this._findOriginalError(t),i=function dI(n){return n&&n.ngErrorLogger||uI}(t);i(this._console,\"ERROR\",t),e&&i(this._console,\"ORIGINAL ERROR\",e)}_findOriginalError(t){let e=t&&vh(t);for(;e&&vh(e);)e=vh(e);return e||null}}const CI=(()=>(\"undefined\"!=typeof requestAnimationFrame&&requestAnimationFrame||setTimeout).bind(Oe))();function Uv(n){return n.ownerDocument.defaultView}function di(n){return n instanceof Function?n():n}var an=(()=>((an=an||{})[an.Important=1]=\"Important\",an[an.DashCase=2]=\"DashCase\",an))();function bh(n,t){return undefined(n,t)}function Ko(n){const t=n[3];return Vn(t)?t[3]:t}function Ch(n){return Yv(n[13])}function Dh(n){return Yv(n[4])}function Yv(n){for(;null!==n&&!Vn(n);)n=n[4];return n}function Ms(n,t,e,i,r){if(null!=i){let s,o=!1;Vn(i)?s=i:si(i)&&(o=!0,i=i[0]);const a=ct(i);0===n&&null!==e?null==r?ey(t,e,a):xr(t,e,a,r||null,!0):1===n&&null!==e?xr(t,e,a,r||null,!0):2===n?function ay(n,t,e){const i=Kl(n,t);i&&function PI(n,t,e,i){et(n)?n.removeChild(t,e,i):t.removeChild(e)}(n,i,t,e)}(t,a,o):3===n&&t.destroyNode(a),null!=s&&function LI(n,t,e,i,r){const s=e[7];s!==ct(e)&&Ms(t,n,i,s,r);for(let a=10;a<e.length;a++){const l=e[a];Zo(l[1],l,n,t,i,s)}}(t,n,s,e,r)}}function Mh(n,t,e){if(et(n))return n.createElement(t,e);{const i=null!==e?function CT(n){const t=n.toLowerCase();return\"svg\"===t?\"http://www.w3.org/2000/svg\":\"math\"===t?\"http://www.w3.org/1998/MathML/\":null}(e):null;return null===i?n.createElement(t):n.createElementNS(i,t)}}function Kv(n,t){const e=n[9],i=e.indexOf(t),r=t[3];1024&t[2]&&(t[2]&=-1025,zu(r,-1)),e.splice(i,1)}function xh(n,t){if(n.length<=10)return;const e=10+t,i=n[e];if(i){const r=i[17];null!==r&&r!==n&&Kv(r,i),t>0&&(n[e-1][4]=i[4]);const s=zl(n,10+t);!function EI(n,t){Zo(n,t,t[11],2,null,null),t[0]=null,t[6]=null}(i[1],i);const o=s[19];null!==o&&o.detachView(s[1]),i[3]=null,i[4]=null,i[2]&=-129}return i}function Zv(n,t){if(!(256&t[2])){const e=t[11];et(e)&&e.destroyNode&&Zo(n,t,e,3,null,null),function TI(n){let t=n[13];if(!t)return Eh(n[1],n);for(;t;){let e=null;if(si(t))e=t[13];else{const i=t[10];i&&(e=i)}if(!e){for(;t&&!t[4]&&t!==n;)si(t)&&Eh(t[1],t),t=t[3];null===t&&(t=n),si(t)&&Eh(t[1],t),e=t&&t[4]}t=e}}(t)}}function Eh(n,t){if(!(256&t[2])){t[2]&=-129,t[2]|=256,function OI(n,t){let e;if(null!=n&&null!=(e=n.destroyHooks))for(let i=0;i<e.length;i+=2){const r=t[e[i]];if(!(r instanceof Po)){const s=e[i+1];if(Array.isArray(s))for(let o=0;o<s.length;o+=2){const a=r[s[o]],l=s[o+1];try{l.call(a)}finally{}}else try{s.call(r)}finally{}}}}(n,t),function RI(n,t){const e=n.cleanup,i=t[7];let r=-1;if(null!==e)for(let s=0;s<e.length-1;s+=2)if(\"string\"==typeof e[s]){const o=e[s+1],a=\"function\"==typeof o?o(t):ct(t[o]),l=i[r=e[s+2]],c=e[s+3];\"boolean\"==typeof c?a.removeEventListener(e[s],l,c):c>=0?i[r=c]():i[r=-c].unsubscribe(),s+=2}else{const o=i[r=e[s+1]];e[s].call(o)}if(null!==i){for(let s=r+1;s<i.length;s++)i[s]();t[7]=null}}(n,t),1===t[1].type&&et(t[11])&&t[11].destroy();const e=t[17];if(null!==e&&Vn(t[3])){e!==t[3]&&Kv(e,t);const i=t[19];null!==i&&i.detachView(n)}}}function Xv(n,t,e){return function Jv(n,t,e){let i=t;for(;null!==i&&40&i.type;)i=(t=i).parent;if(null===i)return e[0];if(2&i.flags){const r=n.data[i.directiveStart].encapsulation;if(r===Ln.None||r===Ln.Emulated)return null}return yn(i,e)}(n,t.parent,e)}function xr(n,t,e,i,r){et(n)?n.insertBefore(t,e,i,r):t.insertBefore(e,i,r)}function ey(n,t,e){et(n)?n.appendChild(t,e):t.appendChild(e)}function ty(n,t,e,i,r){null!==i?xr(n,t,e,i,r):ey(n,t,e)}function Kl(n,t){return et(n)?n.parentNode(t):t.parentNode}function ny(n,t,e){return ry(n,t,e)}let ry=function iy(n,t,e){return 40&n.type?yn(n,e):null};function Zl(n,t,e,i){const r=Xv(n,i,t),s=t[11],a=ny(i.parent||t[6],i,t);if(null!=r)if(Array.isArray(e))for(let l=0;l<e.length;l++)ty(s,r,e[l],a,!1);else ty(s,r,e,a,!1)}function Xl(n,t){if(null!==t){const e=t.type;if(3&e)return yn(t,n);if(4&e)return kh(-1,n[t.index]);if(8&e){const i=t.child;if(null!==i)return Xl(n,i);{const r=n[t.index];return Vn(r)?kh(-1,r):ct(r)}}if(32&e)return bh(t,n)()||ct(n[t.index]);{const i=oy(n,t);return null!==i?Array.isArray(i)?i[0]:Xl(Ko(n[16]),i):Xl(n,t.next)}}return null}function oy(n,t){return null!==t?n[16][6].projection[t.projection]:null}function kh(n,t){const e=10+n+1;if(e<t.length){const i=t[e],r=i[1].firstChild;if(null!==r)return Xl(i,r)}return t[7]}function Th(n,t,e,i,r,s,o){for(;null!=e;){const a=i[e.index],l=e.type;if(o&&0===t&&(a&&Ft(ct(a),i),e.flags|=4),64!=(64&e.flags))if(8&l)Th(n,t,e.child,i,r,s,!1),Ms(t,n,r,a,s);else if(32&l){const c=bh(e,i);let d;for(;d=c();)Ms(t,n,r,d,s);Ms(t,n,r,a,s)}else 16&l?ly(n,t,i,e,r,s):Ms(t,n,r,a,s);e=o?e.projectionNext:e.next}}function Zo(n,t,e,i,r,s){Th(e,i,n.firstChild,t,r,s,!1)}function ly(n,t,e,i,r,s){const o=e[16],l=o[6].projection[i.projection];if(Array.isArray(l))for(let c=0;c<l.length;c++)Ms(t,n,r,l[c],s);else Th(n,t,l,o[3],r,s,!0)}function cy(n,t,e){et(n)?n.setAttribute(t,\"style\",e):t.style.cssText=e}function Ah(n,t,e){et(n)?\"\"===e?n.removeAttribute(t,\"class\"):n.setAttribute(t,\"class\",e):t.className=e}function dy(n,t,e){let i=n.length;for(;;){const r=n.indexOf(t,e);if(-1===r)return r;if(0===r||n.charCodeAt(r-1)<=32){const s=t.length;if(r+s===i||n.charCodeAt(r+s)<=32)return r}e=r+1}}const uy=\"ng-template\";function VI(n,t,e){let i=0;for(;i<n.length;){let r=n[i++];if(e&&\"class\"===r){if(r=n[i],-1!==dy(r.toLowerCase(),t,0))return!0}else if(1===r){for(;i<n.length&&\"string\"==typeof(r=n[i++]);)if(r.toLowerCase()===t)return!0;return!1}}return!1}function hy(n){return 4===n.type&&n.value!==uy}function HI(n,t,e){return t===(4!==n.type||e?n.value:uy)}function jI(n,t,e){let i=4;const r=n.attrs||[],s=function $I(n){for(let t=0;t<n.length;t++)if(ev(n[t]))return t;return n.length}(r);let o=!1;for(let a=0;a<t.length;a++){const l=t[a];if(\"number\"!=typeof l){if(!o)if(4&i){if(i=2|1&i,\"\"!==l&&!HI(n,l,e)||\"\"===l&&1===t.length){if(jn(i))return!1;o=!0}}else{const c=8&i?l:t[++a];if(8&i&&null!==n.attrs){if(!VI(n.attrs,c,e)){if(jn(i))return!1;o=!0}continue}const u=zI(8&i?\"class\":l,r,hy(n),e);if(-1===u){if(jn(i))return!1;o=!0;continue}if(\"\"!==c){let h;h=u>s?\"\":r[u+1].toLowerCase();const p=8&i?h:null;if(p&&-1!==dy(p,c,0)||2&i&&c!==h){if(jn(i))return!1;o=!0}}}}else{if(!o&&!jn(i)&&!jn(l))return!1;if(o&&jn(l))continue;o=!1,i=l|1&i}}return jn(i)||o}function jn(n){return 0==(1&n)}function zI(n,t,e,i){if(null===t)return-1;let r=0;if(i||!e){let s=!1;for(;r<t.length;){const o=t[r];if(o===n)return r;if(3===o||6===o)s=!0;else{if(1===o||2===o){let a=t[++r];for(;\"string\"==typeof a;)a=t[++r];continue}if(4===o)break;if(0===o){r+=4;continue}}r+=s?1:2}return-1}return function GI(n,t){let e=n.indexOf(4);if(e>-1)for(e++;e<n.length;){const i=n[e];if(\"number\"==typeof i)return-1;if(i===t)return e;e++}return-1}(t,n)}function py(n,t,e=!1){for(let i=0;i<t.length;i++)if(jI(n,t[i],e))return!0;return!1}function WI(n,t){e:for(let e=0;e<t.length;e++){const i=t[e];if(n.length===i.length){for(let r=0;r<n.length;r++)if(n[r]!==i[r])continue e;return!0}}return!1}function fy(n,t){return n?\":not(\"+t.trim()+\")\":t}function qI(n){let t=n[0],e=1,i=2,r=\"\",s=!1;for(;e<n.length;){let o=n[e];if(\"string\"==typeof o)if(2&i){const a=n[++e];r+=\"[\"+o+(a.length>0?'=\"'+a+'\"':\"\")+\"]\"}else 8&i?r+=\".\"+o:4&i&&(r+=\" \"+o);else\"\"!==r&&!jn(o)&&(t+=fy(s,r),r=\"\"),i=o,s=s||!jn(i);e++}return\"\"!==r&&(t+=fy(s,r)),t}const se={};function T(n){my(Me(),w(),jt()+n,Tl())}function my(n,t,e,i){if(!i)if(3==(3&t[2])){const s=n.preOrderCheckHooks;null!==s&&Pl(t,s,e)}else{const s=n.preOrderHooks;null!==s&&Fl(t,s,0,e)}Zi(e)}function Jl(n,t){return n<<17|t<<2}function zn(n){return n>>17&32767}function Ih(n){return 2|n}function Ti(n){return(131068&n)>>2}function Rh(n,t){return-131069&n|t<<2}function Oh(n){return 1|n}function Ey(n,t){const e=n.contentQueries;if(null!==e)for(let i=0;i<e.length;i+=2){const r=e[i],s=e[i+1];if(-1!==s){const o=n.data[s];qu(r),o.contentQueries(2,t[s],s)}}}function Xo(n,t,e,i,r,s,o,a,l,c){const d=t.blueprint.slice();return d[0]=r,d[2]=140|i,j_(d),d[3]=d[15]=n,d[8]=e,d[10]=o||n&&n[10],d[11]=a||n&&n[11],d[12]=l||n&&n[12]||null,d[9]=c||n&&n[9]||null,d[6]=s,d[16]=2==t.type?n[16]:d,d}function xs(n,t,e,i,r){let s=n.data[t];if(null===s)s=function zh(n,t,e,i,r){const s=U_(),o=Uu(),l=n.data[t]=function uR(n,t,e,i,r,s){return{type:e,index:i,insertBeforeIndex:null,injectorIndex:t?t.injectorIndex:-1,directiveStart:-1,directiveEnd:-1,directiveStylingLast:-1,propertyBindings:null,flags:0,providerIndexes:0,value:r,attrs:s,mergedAttrs:null,localNames:null,initialInputs:void 0,inputs:null,outputs:null,tViews:null,next:null,projectionNext:null,child:null,parent:t,projection:null,styles:null,stylesWithoutHost:null,residualStyles:void 0,classes:null,classesWithoutHost:null,residualClasses:void 0,classBindings:0,styleBindings:0}}(0,o?s:s&&s.parent,e,t,i,r);return null===n.firstChild&&(n.firstChild=l),null!==s&&(o?null==s.child&&null!==l.parent&&(s.child=l):null===s.next&&(s.next=l)),l}(n,t,e,i,r),function OT(){return te.lFrame.inI18n}()&&(s.flags|=64);else if(64&s.type){s.type=e,s.value=i,s.attrs=r;const o=function Ro(){const n=te.lFrame,t=n.currentTNode;return n.isParent?t:t.parent}();s.injectorIndex=null===o?-1:o.injectorIndex}return oi(s,!0),s}function Es(n,t,e,i){if(0===e)return-1;const r=t.length;for(let s=0;s<e;s++)t.push(i),n.blueprint.push(i),n.data.push(null);return r}function Jo(n,t,e){Il(t);try{const i=n.viewQuery;null!==i&&Zh(1,i,e);const r=n.template;null!==r&&Sy(n,t,r,1,e),n.firstCreatePass&&(n.firstCreatePass=!1),n.staticContentQueries&&Ey(n,t),n.staticViewQueries&&Zh(2,n.viewQuery,e);const s=n.components;null!==s&&function lR(n,t){for(let e=0;e<t.length;e++)TR(n,t[e])}(t,s)}catch(i){throw n.firstCreatePass&&(n.incompleteFirstPass=!0,n.firstCreatePass=!1),i}finally{t[2]&=-5,Rl()}}function Ss(n,t,e,i){const r=t[2];if(256==(256&r))return;Il(t);const s=Tl();try{j_(t),function $_(n){return te.lFrame.bindingIndex=n}(n.bindingStartIndex),null!==e&&Sy(n,t,e,2,i);const o=3==(3&r);if(!s)if(o){const c=n.preOrderCheckHooks;null!==c&&Pl(t,c,null)}else{const c=n.preOrderHooks;null!==c&&Fl(t,c,0,null),Yu(t,0)}if(function SR(n){for(let t=Ch(n);null!==t;t=Dh(t)){if(!t[2])continue;const e=t[9];for(let i=0;i<e.length;i++){const r=e[i],s=r[3];0==(1024&r[2])&&zu(s,1),r[2]|=1024}}}(t),function ER(n){for(let t=Ch(n);null!==t;t=Dh(t))for(let e=10;e<t.length;e++){const i=t[e],r=i[1];ju(i)&&Ss(r,i,r.template,i[8])}}(t),null!==n.contentQueries&&Ey(n,t),!s)if(o){const c=n.contentCheckHooks;null!==c&&Pl(t,c)}else{const c=n.contentHooks;null!==c&&Fl(t,c,1),Yu(t,1)}!function oR(n,t){const e=n.hostBindingOpCodes;if(null!==e)try{for(let i=0;i<e.length;i++){const r=e[i];if(r<0)Zi(~r);else{const s=r,o=e[++i],a=e[++i];PT(o,s),a(2,t[s])}}}finally{Zi(-1)}}(n,t);const a=n.components;null!==a&&function aR(n,t){for(let e=0;e<t.length;e++)kR(n,t[e])}(t,a);const l=n.viewQuery;if(null!==l&&Zh(2,l,i),!s)if(o){const c=n.viewCheckHooks;null!==c&&Pl(t,c)}else{const c=n.viewHooks;null!==c&&Fl(t,c,2),Yu(t,2)}!0===n.firstUpdatePass&&(n.firstUpdatePass=!1),s||(t[2]&=-73),1024&t[2]&&(t[2]&=-1025,zu(t[3],-1))}finally{Rl()}}function cR(n,t,e,i){const r=t[10],s=!Tl(),o=H_(t);try{s&&!o&&r.begin&&r.begin(),o&&Jo(n,t,i),Ss(n,t,e,i)}finally{s&&!o&&r.end&&r.end()}}function Sy(n,t,e,i,r){const s=jt(),o=2&i;try{Zi(-1),o&&t.length>20&&my(n,t,20,Tl()),e(i,r)}finally{Zi(s)}}function ky(n,t,e){if(Ou(t)){const r=t.directiveEnd;for(let s=t.directiveStart;s<r;s++){const o=n.data[s];o.contentQueries&&o.contentQueries(1,e[s],s)}}}function Uh(n,t,e){!z_()||(function vR(n,t,e,i){const r=e.directiveStart,s=e.directiveEnd;n.firstCreatePass||No(e,t),Ft(i,t);const o=e.initialInputs;for(let a=r;a<s;a++){const l=n.data[a],c=Hn(l);c&&wR(t,e,l);const d=Lo(t,n,a,e);Ft(d,t),null!==o&&MR(0,a-r,d,l,0,o),c&&(rn(e.index,t)[8]=d)}}(n,t,e,yn(e,t)),128==(128&e.flags)&&function yR(n,t,e){const i=e.directiveStart,r=e.directiveEnd,o=e.index,a=function FT(){return te.lFrame.currentDirectiveIndex}();try{Zi(o);for(let l=i;l<r;l++){const c=n.data[l],d=t[l];Gu(l),(null!==c.hostBindings||0!==c.hostVars||null!==c.hostAttrs)&&Ny(c,d)}}finally{Zi(-1),Gu(a)}}(n,t,e))}function $h(n,t,e=yn){const i=t.localNames;if(null!==i){let r=t.index+1;for(let s=0;s<i.length;s+=2){const o=i[s+1],a=-1===o?e(t,n):n[o];n[r++]=a}}}function Ty(n){const t=n.tView;return null===t||t.incompleteFirstPass?n.tView=nc(1,null,n.template,n.decls,n.vars,n.directiveDefs,n.pipeDefs,n.viewQuery,n.schemas,n.consts):t}function nc(n,t,e,i,r,s,o,a,l,c){const d=20+i,u=d+r,h=function dR(n,t){const e=[];for(let i=0;i<t;i++)e.push(i<n?null:se);return e}(d,u),p=\"function\"==typeof c?c():c;return h[1]={type:n,blueprint:h,template:e,queries:null,viewQuery:a,declTNode:t,data:h.slice().fill(null,d),bindingStartIndex:d,expandoStartIndex:u,hostBindingOpCodes:null,firstCreatePass:!0,firstUpdatePass:!0,staticViewQueries:!1,staticContentQueries:!1,preOrderHooks:null,preOrderCheckHooks:null,contentHooks:null,contentCheckHooks:null,viewHooks:null,viewCheckHooks:null,destroyHooks:null,cleanup:null,contentQueries:null,components:null,directiveRegistry:\"function\"==typeof s?s():s,pipeRegistry:\"function\"==typeof o?o():o,firstChild:null,schemas:l,consts:p,incompleteFirstPass:!1}}function Ry(n,t,e,i){const r=zy(t);null===e?r.push(i):(r.push(e),n.firstCreatePass&&Uy(n).push(i,r.length-1))}function Oy(n,t,e){for(let i in n)if(n.hasOwnProperty(i)){const r=n[i];(e=null===e?{}:e).hasOwnProperty(i)?e[i].push(t,r):e[i]=[t,r]}return e}function ln(n,t,e,i,r,s,o,a){const l=yn(t,e);let d,c=t.inputs;!a&&null!=c&&(d=c[i])?(Wy(n,e,d,i,r),El(t)&&function fR(n,t){const e=rn(t,n);16&e[2]||(e[2]|=64)}(e,t.index)):3&t.type&&(i=function pR(n){return\"class\"===n?\"className\":\"for\"===n?\"htmlFor\":\"formaction\"===n?\"formAction\":\"innerHtml\"===n?\"innerHTML\":\"readonly\"===n?\"readOnly\":\"tabindex\"===n?\"tabIndex\":n}(i),r=null!=o?o(r,t.value||\"\",i):r,et(s)?s.setProperty(l,i,r):Ku(i)||(l.setProperty?l.setProperty(i,r):l[i]=r))}function Gh(n,t,e,i){let r=!1;if(z_()){const s=function bR(n,t,e){const i=n.directiveRegistry;let r=null;if(i)for(let s=0;s<i.length;s++){const o=i[s];py(e,o.selectors,!1)&&(r||(r=[]),Hl(No(e,t),n,o.type),Hn(o)?(Ly(n,e),r.unshift(o)):r.push(o))}return r}(n,t,e),o=null===i?null:{\"\":-1};if(null!==s){r=!0,By(e,n.data.length,s.length);for(let d=0;d<s.length;d++){const u=s[d];u.providersResolver&&u.providersResolver(u)}let a=!1,l=!1,c=Es(n,t,s.length,null);for(let d=0;d<s.length;d++){const u=s[d];e.mergedAttrs=Ll(e.mergedAttrs,u.hostAttrs),Vy(n,e,t,c,u),DR(c,u,o),null!==u.contentQueries&&(e.flags|=8),(null!==u.hostBindings||null!==u.hostAttrs||0!==u.hostVars)&&(e.flags|=128);const h=u.type.prototype;!a&&(h.ngOnChanges||h.ngOnInit||h.ngDoCheck)&&((n.preOrderHooks||(n.preOrderHooks=[])).push(e.index),a=!0),!l&&(h.ngOnChanges||h.ngDoCheck)&&((n.preOrderCheckHooks||(n.preOrderCheckHooks=[])).push(e.index),l=!0),c++}!function hR(n,t){const i=t.directiveEnd,r=n.data,s=t.attrs,o=[];let a=null,l=null;for(let c=t.directiveStart;c<i;c++){const d=r[c],u=d.inputs,h=null===s||hy(t)?null:xR(u,s);o.push(h),a=Oy(u,c,a),l=Oy(d.outputs,c,l)}null!==a&&(a.hasOwnProperty(\"class\")&&(t.flags|=16),a.hasOwnProperty(\"style\")&&(t.flags|=32)),t.initialInputs=o,t.inputs=a,t.outputs=l}(n,e)}o&&function CR(n,t,e){if(t){const i=n.localNames=[];for(let r=0;r<t.length;r+=2){const s=e[t[r+1]];if(null==s)throw new H(-301,!1);i.push(t[r],s)}}}(e,i,o)}return e.mergedAttrs=Ll(e.mergedAttrs,e.attrs),r}function Fy(n,t,e,i,r,s){const o=s.hostBindings;if(o){let a=n.hostBindingOpCodes;null===a&&(a=n.hostBindingOpCodes=[]);const l=~t.index;(function _R(n){let t=n.length;for(;t>0;){const e=n[--t];if(\"number\"==typeof e&&e<0)return e}return 0})(a)!=l&&a.push(l),a.push(i,r,o)}}function Ny(n,t){null!==n.hostBindings&&n.hostBindings(1,t)}function Ly(n,t){t.flags|=2,(n.components||(n.components=[])).push(t.index)}function DR(n,t,e){if(e){if(t.exportAs)for(let i=0;i<t.exportAs.length;i++)e[t.exportAs[i]]=n;Hn(t)&&(e[\"\"]=n)}}function By(n,t,e){n.flags|=1,n.directiveStart=t,n.directiveEnd=t+e,n.providerIndexes=t}function Vy(n,t,e,i,r){n.data[i]=r;const s=r.factory||(r.factory=Cr(r.type)),o=new Po(s,Hn(r),null);n.blueprint[i]=o,e[i]=o,Fy(n,t,0,i,Es(n,e,r.hostVars,se),r)}function wR(n,t,e){const i=yn(t,n),r=Ty(e),s=n[10],o=ic(n,Xo(n,r,null,e.onPush?64:16,i,t,s,s.createRenderer(i,e),null,null));n[t.index]=o}function ui(n,t,e,i,r,s){const o=yn(n,t);!function Wh(n,t,e,i,r,s,o){if(null==s)et(n)?n.removeAttribute(t,r,e):t.removeAttribute(r);else{const a=null==o?re(s):o(s,i||\"\",r);et(n)?n.setAttribute(t,r,a,e):e?t.setAttributeNS(e,r,a):t.setAttribute(r,a)}}(t[11],o,s,n.value,e,i,r)}function MR(n,t,e,i,r,s){const o=s[t];if(null!==o){const a=i.setInput;for(let l=0;l<o.length;){const c=o[l++],d=o[l++],u=o[l++];null!==a?i.setInput(e,u,c,d):e[d]=u}}}function xR(n,t){let e=null,i=0;for(;i<t.length;){const r=t[i];if(0!==r)if(5!==r){if(\"number\"==typeof r)break;n.hasOwnProperty(r)&&(null===e&&(e=[]),e.push(r,n[r],t[i+1])),i+=2}else i+=2;else i+=4}return e}function Hy(n,t,e,i){return new Array(n,!0,!1,t,null,0,i,e,null,null)}function kR(n,t){const e=rn(t,n);if(ju(e)){const i=e[1];80&e[2]?Ss(i,e,i.template,e[8]):e[5]>0&&qh(e)}}function qh(n){for(let i=Ch(n);null!==i;i=Dh(i))for(let r=10;r<i.length;r++){const s=i[r];if(1024&s[2]){const o=s[1];Ss(o,s,o.template,s[8])}else s[5]>0&&qh(s)}const e=n[1].components;if(null!==e)for(let i=0;i<e.length;i++){const r=rn(e[i],n);ju(r)&&r[5]>0&&qh(r)}}function TR(n,t){const e=rn(t,n),i=e[1];(function AR(n,t){for(let e=t.length;e<n.blueprint.length;e++)t.push(n.blueprint[e])})(i,e),Jo(i,e,e[8])}function ic(n,t){return n[13]?n[14][4]=t:n[13]=t,n[14]=t,t}function Yh(n){for(;n;){n[2]|=64;const t=Ko(n);if(uT(n)&&!t)return n;n=t}return null}function Kh(n,t,e){const i=t[10];i.begin&&i.begin();try{Ss(n,t,n.template,e)}catch(r){throw Gy(t,r),r}finally{i.end&&i.end()}}function jy(n){!function Qh(n){for(let t=0;t<n.components.length;t++){const e=n.components[t],i=gh(e),r=i[1];cR(r,i,r.template,e)}}(n[8])}function Zh(n,t,e){qu(0),t(n,e)}const PR=(()=>Promise.resolve(null))();function zy(n){return n[7]||(n[7]=[])}function Uy(n){return n.cleanup||(n.cleanup=[])}function $y(n,t,e){return(null===n||Hn(n))&&(e=function MT(n){for(;Array.isArray(n);){if(\"object\"==typeof n[1])return n;n=n[0]}return null}(e[t.index])),e[11]}function Gy(n,t){const e=n[9],i=e?e.get(Mr,null):null;i&&i.handleError(t)}function Wy(n,t,e,i,r){for(let s=0;s<e.length;){const o=e[s++],a=e[s++],l=t[o],c=n.data[o];null!==c.setInput?c.setInput(l,r,i,a):l[a]=r}}function Ai(n,t,e){const i=kl(t,n);!function Qv(n,t,e){et(n)?n.setValue(t,e):t.textContent=e}(n[11],i,e)}function rc(n,t,e){let i=e?n.styles:null,r=e?n.classes:null,s=0;if(null!==t)for(let o=0;o<t.length;o++){const a=t[o];\"number\"==typeof a?s=a:1==s?r=Mu(r,a):2==s&&(i=Mu(i,a+\": \"+t[++o]+\";\"))}e?n.styles=i:n.stylesWithoutHost=i,e?n.classes=r:n.classesWithoutHost=r}const Xh=new b(\"INJECTOR\",-1);class qy{get(t,e=jo){if(e===jo){const i=new Error(`NullInjectorError: No provider for ${Re(t)}!`);throw i.name=\"NullInjectorError\",i}return e}}const Jh=new b(\"Set Injector scope.\"),ea={},LR={};let ep;function Yy(){return void 0===ep&&(ep=new qy),ep}function Qy(n,t=null,e=null,i){const r=Ky(n,t,e,i);return r._resolveInjectorDefTypes(),r}function Ky(n,t=null,e=null,i){return new BR(n,e,t||Yy(),i)}class BR{constructor(t,e,i,r=null){this.parent=i,this.records=new Map,this.injectorDefTypes=new Set,this.onDestroy=new Set,this._destroyed=!1;const s=[];e&&ai(e,a=>this.processProvider(a,t,e)),ai([t],a=>this.processInjectorType(a,[],s)),this.records.set(Xh,ks(void 0,this));const o=this.records.get(Jh);this.scope=null!=o?o.value:null,this.source=r||(\"object\"==typeof t?null:Re(t))}get destroyed(){return this._destroyed}destroy(){this.assertNotDestroyed(),this._destroyed=!0;try{this.onDestroy.forEach(t=>t.ngOnDestroy())}finally{this.records.clear(),this.onDestroy.clear(),this.injectorDefTypes.clear()}}get(t,e=jo,i=ee.Default){this.assertNotDestroyed();const r=vv(this),s=qi(void 0);try{if(!(i&ee.SkipSelf)){let a=this.records.get(t);if(void 0===a){const l=function WR(n){return\"function\"==typeof n||\"object\"==typeof n&&n instanceof b}(t)&&Eu(t);a=l&&this.injectableDefInScope(l)?ks(tp(t),ea):null,this.records.set(t,a)}if(null!=a)return this.hydrate(t,a)}return(i&ee.Self?Yy():this.parent).get(t,e=i&ee.Optional&&e===jo?null:e)}catch(o){if(\"NullInjectorError\"===o.name){if((o[$l]=o[$l]||[]).unshift(Re(t)),r)throw o;return function _A(n,t,e,i){const r=n[$l];throw t[_v]&&r.unshift(t[_v]),n.message=function vA(n,t,e,i=null){n=n&&\"\\n\"===n.charAt(0)&&\"\\u0275\"==n.charAt(1)?n.substr(2):n;let r=Re(t);if(Array.isArray(t))r=t.map(Re).join(\" -> \");else if(\"object\"==typeof t){let s=[];for(let o in t)if(t.hasOwnProperty(o)){let a=t[o];s.push(o+\":\"+(\"string\"==typeof a?JSON.stringify(a):Re(a)))}r=`{${s.join(\", \")}}`}return`${e}${i?\"(\"+i+\")\":\"\"}[${r}]: ${n.replace(hA,\"\\n \")}`}(\"\\n\"+n.message,r,e,i),n.ngTokenPath=r,n[$l]=null,n}(o,t,\"R3InjectorError\",this.source)}throw o}finally{qi(s),vv(r)}}_resolveInjectorDefTypes(){this.injectorDefTypes.forEach(t=>this.get(t))}toString(){const t=[];return this.records.forEach((i,r)=>t.push(Re(r))),`R3Injector[${t.join(\", \")}]`}assertNotDestroyed(){if(this._destroyed)throw new H(205,!1)}processInjectorType(t,e,i){if(!(t=le(t)))return!1;let r=S_(t);const s=null==r&&t.ngModule||void 0,o=void 0===s?t:s,a=-1!==i.indexOf(o);if(void 0!==s&&(r=S_(s)),null==r)return!1;if(null!=r.imports&&!a){let d;i.push(o);try{ai(r.imports,u=>{this.processInjectorType(u,e,i)&&(void 0===d&&(d=[]),d.push(u))})}finally{}if(void 0!==d)for(let u=0;u<d.length;u++){const{ngModule:h,providers:p}=d[u];ai(p,m=>this.processProvider(m,h,p||Ne))}}this.injectorDefTypes.add(o);const l=Cr(o)||(()=>new o);this.records.set(o,ks(l,ea));const c=r.providers;if(null!=c&&!a){const d=t;ai(c,u=>this.processProvider(u,d,c))}return void 0!==s&&void 0!==t.providers}processProvider(t,e,i){let r=Ts(t=le(t))?t:le(t&&t.provide);const s=function HR(n,t,e){return Xy(n)?ks(void 0,n.useValue):ks(Zy(n),ea)}(t);if(Ts(t)||!0!==t.multi)this.records.get(r);else{let o=this.records.get(r);o||(o=ks(void 0,ea,!0),o.factory=()=>oh(o.multi),this.records.set(r,o)),r=t,o.multi.push(t)}this.records.set(r,s)}hydrate(t,e){return e.value===ea&&(e.value=LR,e.value=e.factory()),\"object\"==typeof e.value&&e.value&&function GR(n){return null!==n&&\"object\"==typeof n&&\"function\"==typeof n.ngOnDestroy}(e.value)&&this.onDestroy.add(e.value),e.value}injectableDefInScope(t){if(!t.providedIn)return!1;const e=le(t.providedIn);return\"string\"==typeof e?\"any\"===e||e===this.scope:this.injectorDefTypes.has(e)}}function tp(n){const t=Eu(n),e=null!==t?t.factory:Cr(n);if(null!==e)return e;if(n instanceof b)throw new H(204,!1);if(n instanceof Function)return function VR(n){const t=n.length;if(t>0)throw Ho(t,\"?\"),new H(204,!1);const e=function Xk(n){const t=n&&(n[Cl]||n[k_]);if(t){const e=function Jk(n){if(n.hasOwnProperty(\"name\"))return n.name;const t=(\"\"+n).match(/^function\\s*([^\\s(]+)/);return null===t?\"\":t[1]}(n);return console.warn(`DEPRECATED: DI is instantiating a token \"${e}\" that inherits its @Injectable decorator but does not provide one itself.\\nThis will become an error in a future version of Angular. Please add @Injectable() to the \"${e}\" class.`),t}return null}(n);return null!==e?()=>e.factory(n):()=>new n}(n);throw new H(204,!1)}function Zy(n,t,e){let i;if(Ts(n)){const r=le(n);return Cr(r)||tp(r)}if(Xy(n))i=()=>le(n.useValue);else if(function zR(n){return!(!n||!n.useFactory)}(n))i=()=>n.useFactory(...oh(n.deps||[]));else if(function jR(n){return!(!n||!n.useExisting)}(n))i=()=>y(le(n.useExisting));else{const r=le(n&&(n.useClass||n.provide));if(!function $R(n){return!!n.deps}(n))return Cr(r)||tp(r);i=()=>new r(...oh(n.deps))}return i}function ks(n,t,e=!1){return{factory:n,value:t,multi:e?[]:void 0}}function Xy(n){return null!==n&&\"object\"==typeof n&&fA in n}function Ts(n){return\"function\"==typeof n}let dt=(()=>{class n{static create(e,i){var r;if(Array.isArray(e))return Qy({name:\"\"},i,e,\"\");{const s=null!==(r=e.name)&&void 0!==r?r:\"\";return Qy({name:s},e.parent,e.providers,s)}}}return n.THROW_IF_NOT_FOUND=jo,n.NULL=new qy,n.\\u0275prov=k({token:n,providedIn:\"any\",factory:()=>y(Xh)}),n.__NG_ELEMENT_ID__=-1,n})();function e1(n,t){Ol(gh(n)[1],gt())}function E(n){let t=function db(n){return Object.getPrototypeOf(n.prototype).constructor}(n.type),e=!0;const i=[n];for(;t;){let r;if(Hn(n))r=t.\\u0275cmp||t.\\u0275dir;else{if(t.\\u0275cmp)throw new H(903,\"\");r=t.\\u0275dir}if(r){if(e){i.push(r);const o=n;o.inputs=rp(n.inputs),o.declaredInputs=rp(n.declaredInputs),o.outputs=rp(n.outputs);const a=r.hostBindings;a&&s1(n,a);const l=r.viewQuery,c=r.contentQueries;if(l&&n1(n,l),c&&r1(n,c),wu(n.inputs,r.inputs),wu(n.declaredInputs,r.declaredInputs),wu(n.outputs,r.outputs),Hn(r)&&r.data.animation){const d=n.data;d.animation=(d.animation||[]).concat(r.data.animation)}}const s=r.features;if(s)for(let o=0;o<s.length;o++){const a=s[o];a&&a.ngInherit&&a(n),a===E&&(e=!1)}}t=Object.getPrototypeOf(t)}!function t1(n){let t=0,e=null;for(let i=n.length-1;i>=0;i--){const r=n[i];r.hostVars=t+=r.hostVars,r.hostAttrs=Ll(r.hostAttrs,e=Ll(e,r.hostAttrs))}}(i)}function rp(n){return n===os?{}:n===Ne?[]:n}function n1(n,t){const e=n.viewQuery;n.viewQuery=e?(i,r)=>{t(i,r),e(i,r)}:t}function r1(n,t){const e=n.contentQueries;n.contentQueries=e?(i,r,s)=>{t(i,r,s),e(i,r,s)}:t}function s1(n,t){const e=n.hostBindings;n.hostBindings=e?(i,r)=>{t(i,r),e(i,r)}:t}let sc=null;function As(){if(!sc){const n=Oe.Symbol;if(n&&n.iterator)sc=n.iterator;else{const t=Object.getOwnPropertyNames(Map.prototype);for(let e=0;e<t.length;++e){const i=t[e];\"entries\"!==i&&\"size\"!==i&&Map.prototype[i]===Map.prototype.entries&&(sc=i)}}}return sc}function ta(n){return!!sp(n)&&(Array.isArray(n)||!(n instanceof Map)&&As()in n)}function sp(n){return null!==n&&(\"function\"==typeof n||\"object\"==typeof n)}function Nt(n,t,e){return!Object.is(n[t],e)&&(n[t]=e,!0)}function Z(n,t,e,i){const r=w();return Nt(r,hs(),t)&&(Me(),ui(tt(),r,n,t,e,i)),Z}function Rs(n,t,e,i){return Nt(n,hs(),e)?t+re(e)+i:se}function Ee(n,t,e,i,r,s,o,a){const l=w(),c=Me(),d=n+20,u=c.firstCreatePass?function h1(n,t,e,i,r,s,o,a,l){const c=t.consts,d=xs(t,n,4,o||null,Ki(c,a));Gh(t,e,d,Ki(c,l)),Ol(t,d);const u=d.tViews=nc(2,d,i,r,s,t.directiveRegistry,t.pipeRegistry,null,t.schemas,c);return null!==t.queries&&(t.queries.template(t,d),u.queries=t.queries.embeddedTView(d)),d}(d,c,l,t,e,i,r,s,o):c.data[d];oi(u,!1);const h=l[11].createComment(\"\");Zl(c,l,h,u),Ft(h,l),ic(l,l[d]=Hy(h,l,h,u)),Sl(u)&&Uh(c,l,u),null!=o&&$h(l,u,a)}function wn(n){return function us(n,t){return n[t]}(function RT(){return te.lFrame.contextLView}(),20+n)}function f(n,t=ee.Default){const e=w();return null===e?y(n,t):av(gt(),e,le(n),t)}function Sr(){throw new Error(\"invalid\")}function N(n,t,e){const i=w();return Nt(i,hs(),t)&&ln(Me(),tt(),i,n,t,i[11],e,!1),N}function dp(n,t,e,i,r){const o=r?\"class\":\"style\";Wy(n,e,t.inputs[o],o,i)}function x(n,t,e,i){const r=w(),s=Me(),o=20+n,a=r[11],l=r[o]=Mh(a,t,function jT(){return te.lFrame.currentNamespace}()),c=s.firstCreatePass?function O1(n,t,e,i,r,s,o){const a=t.consts,c=xs(t,n,2,r,Ki(a,s));return Gh(t,e,c,Ki(a,o)),null!==c.attrs&&rc(c,c.attrs,!1),null!==c.mergedAttrs&&rc(c,c.mergedAttrs,!0),null!==t.queries&&t.queries.elementStart(t,c),c}(o,s,r,0,t,e,i):s.data[o];oi(c,!0);const d=c.mergedAttrs;null!==d&&Nl(a,l,d);const u=c.classes;null!==u&&Ah(a,l,u);const h=c.styles;return null!==h&&cy(a,l,h),64!=(64&c.flags)&&Zl(s,r,l,c),0===function ST(){return te.lFrame.elementDepthCount}()&&Ft(l,r),function kT(){te.lFrame.elementDepthCount++}(),Sl(c)&&(Uh(s,r,c),ky(s,c,r)),null!==i&&$h(r,c),x}function S(){let n=gt();Uu()?$u():(n=n.parent,oi(n,!1));const t=n;!function TT(){te.lFrame.elementDepthCount--}();const e=Me();return e.firstCreatePass&&(Ol(e,n),Ou(n)&&e.queries.elementEnd(n)),null!=t.classesWithoutHost&&function WT(n){return 0!=(16&n.flags)}(t)&&dp(e,t,w(),t.classesWithoutHost,!0),null!=t.stylesWithoutHost&&function qT(n){return 0!=(32&n.flags)}(t)&&dp(e,t,w(),t.stylesWithoutHost,!1),S}function Le(n,t,e,i){return x(n,t,e,i),S(),Le}function kr(n,t,e){const i=w(),r=Me(),s=n+20,o=r.firstCreatePass?function P1(n,t,e,i,r){const s=t.consts,o=Ki(s,i),a=xs(t,n,8,\"ng-container\",o);return null!==o&&rc(a,o,!0),Gh(t,e,a,Ki(s,r)),null!==t.queries&&t.queries.elementStart(t,a),a}(s,r,i,t,e):r.data[s];oi(o,!0);const a=i[s]=i[11].createComment(\"\");return Zl(r,i,a,o),Ft(a,i),Sl(o)&&(Uh(r,i,o),ky(r,o,i)),null!=e&&$h(i,o),kr}function Tr(){let n=gt();const t=Me();return Uu()?$u():(n=n.parent,oi(n,!1)),t.firstCreatePass&&(Ol(t,n),Ou(n)&&t.queries.elementEnd(n)),Tr}function ia(){return w()}function ra(n){return!!n&&\"function\"==typeof n.then}const up=function Ab(n){return!!n&&\"function\"==typeof n.subscribe};function J(n,t,e,i){const r=w(),s=Me(),o=gt();return Ib(s,r,r[11],o,n,t,!!e,i),J}function hp(n,t){const e=gt(),i=w(),r=Me();return Ib(r,i,$y(Wu(r.data),e,i),e,n,t,!1),hp}function Ib(n,t,e,i,r,s,o,a){const l=Sl(i),d=n.firstCreatePass&&Uy(n),u=t[8],h=zy(t);let p=!0;if(3&i.type||a){const _=yn(i,t),D=a?a(_):_,v=h.length,M=a?V=>a(ct(V[i.index])):i.index;if(et(e)){let V=null;if(!a&&l&&(V=function F1(n,t,e,i){const r=n.cleanup;if(null!=r)for(let s=0;s<r.length-1;s+=2){const o=r[s];if(o===e&&r[s+1]===i){const a=t[7],l=r[s+2];return a.length>l?a[l]:null}\"string\"==typeof o&&(s+=2)}return null}(n,t,r,i.index)),null!==V)(V.__ngLastListenerFn__||V).__ngNextListenerFn__=s,V.__ngLastListenerFn__=s,p=!1;else{s=pp(i,t,u,s,!1);const he=e.listen(D,r,s);h.push(s,he),d&&d.push(r,M,v,v+1)}}else s=pp(i,t,u,s,!0),D.addEventListener(r,s,o),h.push(s),d&&d.push(r,M,v,o)}else s=pp(i,t,u,s,!1);const m=i.outputs;let g;if(p&&null!==m&&(g=m[r])){const _=g.length;if(_)for(let D=0;D<_;D+=2){const We=t[g[D]][g[D+1]].subscribe(s),Ze=h.length;h.push(s,We),d&&d.push(r,i.index,Ze,-(Ze+1))}}}function Rb(n,t,e,i){try{return!1!==e(i)}catch(r){return Gy(n,r),!1}}function pp(n,t,e,i,r){return function s(o){if(o===Function)return i;const a=2&n.flags?rn(n.index,t):t;0==(32&t[2])&&Yh(a);let l=Rb(t,0,i,o),c=s.__ngNextListenerFn__;for(;c;)l=Rb(t,0,c,o)&&l,c=c.__ngNextListenerFn__;return r&&!1===l&&(o.preventDefault(),o.returnValue=!1),l}}function Be(n=1){return function LT(n){return(te.lFrame.contextLView=function BT(n,t){for(;n>0;)t=t[15],n--;return t}(n,te.lFrame.contextLView))[8]}(n)}function N1(n,t){let e=null;const i=function UI(n){const t=n.attrs;if(null!=t){const e=t.indexOf(5);if(0==(1&e))return t[e+1]}return null}(n);for(let r=0;r<t.length;r++){const s=t[r];if(\"*\"!==s){if(null===i?py(n,s,!0):WI(i,s))return r}else e=r}return e}function Lt(n){const t=w()[16][6];if(!t.projection){const i=t.projection=Ho(n?n.length:1,null),r=i.slice();let s=t.child;for(;null!==s;){const o=n?N1(s,n):0;null!==o&&(r[o]?r[o].projectionNext=s:i[o]=s,r[o]=s),s=s.next}}}function Pe(n,t=0,e){const i=w(),r=Me(),s=xs(r,20+n,16,null,e||null);null===s.projection&&(s.projection=t),$u(),64!=(64&s.flags)&&function NI(n,t,e){ly(t[11],0,t,e,Xv(n,e,t),ny(e.parent||t[6],e,t))}(r,i,s)}function zb(n,t,e,i,r){const s=n[e+1],o=null===t;let a=i?zn(s):Ti(s),l=!1;for(;0!==a&&(!1===l||o);){const d=n[a+1];V1(n[a],t)&&(l=!0,n[a+1]=i?Oh(d):Ih(d)),a=i?zn(d):Ti(d)}l&&(n[e+1]=i?Ih(s):Oh(s))}function V1(n,t){return null===n||null==t||(Array.isArray(n)?n[1]:n)===t||!(!Array.isArray(n)||\"string\"!=typeof t)&&bs(n,t)>=0}const vt={textEnd:0,key:0,keyEnd:0,value:0,valueEnd:0};function Ub(n){return n.substring(vt.key,vt.keyEnd)}function $b(n,t){const e=vt.textEnd;return e===t?-1:(t=vt.keyEnd=function U1(n,t,e){for(;t<e&&n.charCodeAt(t)>32;)t++;return t}(n,vt.key=t,e),js(n,t,e))}function js(n,t,e){for(;t<e&&n.charCodeAt(t)<=32;)t++;return t}function $n(n,t,e){return Gn(n,t,e,!1),$n}function Ae(n,t){return Gn(n,t,null,!0),Ae}function fi(n,t){for(let e=function j1(n){return function Wb(n){vt.key=0,vt.keyEnd=0,vt.value=0,vt.valueEnd=0,vt.textEnd=n.length}(n),$b(n,js(n,0,vt.textEnd))}(t);e>=0;e=$b(t,e))sn(n,Ub(t),!0)}function Gn(n,t,e,i){const r=w(),s=Me(),o=ki(2);s.firstUpdatePass&&Kb(s,n,o,i),t!==se&&Nt(r,o,t)&&Xb(s,s.data[jt()],r,r[11],n,r[o+1]=function eO(n,t){return null==n||(\"string\"==typeof t?n+=t:\"object\"==typeof n&&(n=Re(on(n)))),n}(t,e),i,o)}function Qb(n,t){return t>=n.expandoStartIndex}function Kb(n,t,e,i){const r=n.data;if(null===r[e+1]){const s=r[jt()],o=Qb(n,e);eC(s,i)&&null===t&&!o&&(t=!1),t=function Y1(n,t,e,i){const r=Wu(n);let s=i?t.residualClasses:t.residualStyles;if(null===r)0===(i?t.classBindings:t.styleBindings)&&(e=sa(e=mp(null,n,t,e,i),t.attrs,i),s=null);else{const o=t.directiveStylingLast;if(-1===o||n[o]!==r)if(e=mp(r,n,t,e,i),null===s){let l=function Q1(n,t,e){const i=e?t.classBindings:t.styleBindings;if(0!==Ti(i))return n[zn(i)]}(n,t,i);void 0!==l&&Array.isArray(l)&&(l=mp(null,n,t,l[1],i),l=sa(l,t.attrs,i),function K1(n,t,e,i){n[zn(e?t.classBindings:t.styleBindings)]=i}(n,t,i,l))}else s=function Z1(n,t,e){let i;const r=t.directiveEnd;for(let s=1+t.directiveStylingLast;s<r;s++)i=sa(i,n[s].hostAttrs,e);return sa(i,t.attrs,e)}(n,t,i)}return void 0!==s&&(i?t.residualClasses=s:t.residualStyles=s),e}(r,s,t,i),function L1(n,t,e,i,r,s){let o=s?t.classBindings:t.styleBindings,a=zn(o),l=Ti(o);n[i]=e;let d,c=!1;if(Array.isArray(e)){const u=e;d=u[1],(null===d||bs(u,d)>0)&&(c=!0)}else d=e;if(r)if(0!==l){const h=zn(n[a+1]);n[i+1]=Jl(h,a),0!==h&&(n[h+1]=Rh(n[h+1],i)),n[a+1]=function KI(n,t){return 131071&n|t<<17}(n[a+1],i)}else n[i+1]=Jl(a,0),0!==a&&(n[a+1]=Rh(n[a+1],i)),a=i;else n[i+1]=Jl(l,0),0===a?a=i:n[l+1]=Rh(n[l+1],i),l=i;c&&(n[i+1]=Ih(n[i+1])),zb(n,d,i,!0),zb(n,d,i,!1),function B1(n,t,e,i,r){const s=r?n.residualClasses:n.residualStyles;null!=s&&\"string\"==typeof t&&bs(s,t)>=0&&(e[i+1]=Oh(e[i+1]))}(t,d,n,i,s),o=Jl(a,l),s?t.classBindings=o:t.styleBindings=o}(r,s,t,e,o,i)}}function mp(n,t,e,i,r){let s=null;const o=e.directiveEnd;let a=e.directiveStylingLast;for(-1===a?a=e.directiveStart:a++;a<o&&(s=t[a],i=sa(i,s.hostAttrs,r),s!==n);)a++;return null!==n&&(e.directiveStylingLast=a),i}function sa(n,t,e){const i=e?1:2;let r=-1;if(null!==t)for(let s=0;s<t.length;s++){const o=t[s];\"number\"==typeof o?r=o:r===i&&(Array.isArray(n)||(n=void 0===n?[]:[\"\",n]),sn(n,o,!!e||t[++s]))}return void 0===n?null:n}function Xb(n,t,e,i,r,s,o,a){if(!(3&t.type))return;const l=n.data,c=l[a+1];lc(function vy(n){return 1==(1&n)}(c)?Jb(l,t,e,r,Ti(c),o):void 0)||(lc(s)||function _y(n){return 2==(2&n)}(c)&&(s=Jb(l,null,e,r,a,o)),function BI(n,t,e,i,r){const s=et(n);if(t)r?s?n.addClass(e,i):e.classList.add(i):s?n.removeClass(e,i):e.classList.remove(i);else{let o=-1===i.indexOf(\"-\")?void 0:an.DashCase;if(null==r)s?n.removeStyle(e,i,o):e.style.removeProperty(i);else{const a=\"string\"==typeof r&&r.endsWith(\"!important\");a&&(r=r.slice(0,-10),o|=an.Important),s?n.setStyle(e,i,r,o):e.style.setProperty(i,r,a?\"important\":\"\")}}}(i,o,kl(jt(),e),r,s))}function Jb(n,t,e,i,r,s){const o=null===t;let a;for(;r>0;){const l=n[r],c=Array.isArray(l),d=c?l[1]:l,u=null===d;let h=e[r+1];h===se&&(h=u?Ne:void 0);let p=u?ih(h,i):d===i?h:void 0;if(c&&!lc(p)&&(p=ih(l,i)),lc(p)&&(a=p,o))return a;const m=n[r+1];r=o?zn(m):Ti(m)}if(null!==t){let l=s?t.residualClasses:t.residualStyles;null!=l&&(a=ih(l,i))}return a}function lc(n){return void 0!==n}function eC(n,t){return 0!=(n.flags&(t?16:32))}function we(n,t=\"\"){const e=w(),i=Me(),r=n+20,s=i.firstCreatePass?xs(i,r,1,t,null):i.data[r],o=e[r]=function wh(n,t){return et(n)?n.createText(t):n.createTextNode(t)}(e[11],t);Zl(i,e,o,s),oi(s,!1)}function Ut(n){return qn(\"\",n,\"\"),Ut}function qn(n,t,e){const i=w(),r=Rs(i,n,t,e);return r!==se&&Ai(i,jt(),r),qn}function cC(n,t,e){!function Wn(n,t,e,i){const r=Me(),s=ki(2);r.firstUpdatePass&&Kb(r,null,s,i);const o=w();if(e!==se&&Nt(o,s,e)){const a=r.data[jt()];if(eC(a,i)&&!Qb(r,s)){let l=i?a.classesWithoutHost:a.stylesWithoutHost;null!==l&&(e=Mu(l,e||\"\")),dp(r,a,o,e,i)}else!function J1(n,t,e,i,r,s,o,a){r===se&&(r=Ne);let l=0,c=0,d=0<r.length?r[0]:null,u=0<s.length?s[0]:null;for(;null!==d||null!==u;){const h=l<r.length?r[l+1]:void 0,p=c<s.length?s[c+1]:void 0;let g,m=null;d===u?(l+=2,c+=2,h!==p&&(m=u,g=p)):null===u||null!==d&&d<u?(l+=2,m=d):(c+=2,m=u,g=p),null!==m&&Xb(n,t,e,i,m,g,o,a),d=l<r.length?r[l]:null,u=c<s.length?s[c]:null}}(r,a,o,o[11],o[s+1],o[s+1]=function X1(n,t,e){if(null==e||\"\"===e)return Ne;const i=[],r=on(e);if(Array.isArray(r))for(let s=0;s<r.length;s++)n(i,r[s],!0);else if(\"object\"==typeof r)for(const s in r)r.hasOwnProperty(s)&&n(i,s,r[s]);else\"string\"==typeof r&&t(i,r);return i}(n,t,e),i,s)}}(sn,fi,Rs(w(),n,t,e),!0)}function Yn(n,t,e){const i=w();return Nt(i,hs(),t)&&ln(Me(),tt(),i,n,t,i[11],e,!0),Yn}function gp(n,t,e){const i=w();if(Nt(i,hs(),t)){const s=Me(),o=tt();ln(s,o,i,n,t,$y(Wu(s.data),o,i),e,!0)}return gp}const cc=\"en-US\";let CC=cc;function yp(n,t,e,i,r){if(n=le(n),Array.isArray(n))for(let s=0;s<n.length;s++)yp(n[s],t,e,i,r);else{const s=Me(),o=w();let a=Ts(n)?n:le(n.provide),l=Zy(n);const c=gt(),d=1048575&c.providerIndexes,u=c.directiveStart,h=c.providerIndexes>>20;if(Ts(n)||!n.multi){const p=new Po(l,r,f),m=Cp(a,t,r?d:d+h,u);-1===m?(Hl(No(c,o),s,a),bp(s,n,t.length),t.push(a),c.directiveStart++,c.directiveEnd++,r&&(c.providerIndexes+=1048576),e.push(p),o.push(p)):(e[m]=p,o[m]=p)}else{const p=Cp(a,t,d+h,u),m=Cp(a,t,d,d+h),g=p>=0&&e[p],_=m>=0&&e[m];if(r&&!_||!r&&!g){Hl(No(c,o),s,a);const D=function vP(n,t,e,i,r){const s=new Po(n,e,f);return s.multi=[],s.index=t,s.componentProviders=0,GC(s,r,i&&!e),s}(r?_P:gP,e.length,r,i,l);!r&&_&&(e[m].providerFactory=D),bp(s,n,t.length,0),t.push(a),c.directiveStart++,c.directiveEnd++,r&&(c.providerIndexes+=1048576),e.push(D),o.push(D)}else bp(s,n,p>-1?p:m,GC(e[r?m:p],l,!r&&i));!r&&i&&_&&e[m].componentProviders++}}}function bp(n,t,e,i){const r=Ts(t),s=function UR(n){return!!n.useClass}(t);if(r||s){const l=(s?le(t.useClass):t).prototype.ngOnDestroy;if(l){const c=n.destroyHooks||(n.destroyHooks=[]);if(!r&&t.multi){const d=c.indexOf(e);-1===d?c.push(e,[i,l]):c[d+1].push(i,l)}else c.push(e,l)}}}function GC(n,t,e){return e&&n.componentProviders++,n.multi.push(t)-1}function Cp(n,t,e,i){for(let r=e;r<i;r++)if(t[r]===n)return r;return-1}function gP(n,t,e,i){return Dp(this.multi,[])}function _P(n,t,e,i){const r=this.multi;let s;if(this.providerFactory){const o=this.providerFactory.componentProviders,a=Lo(e,e[1],this.providerFactory.index,i);s=a.slice(0,o),Dp(r,s);for(let l=o;l<a.length;l++)s.push(a[l])}else s=[],Dp(r,s);return s}function Dp(n,t){for(let e=0;e<n.length;e++)t.push((0,n[e])());return t}function L(n,t=[]){return e=>{e.providersResolver=(i,r)=>function mP(n,t,e){const i=Me();if(i.firstCreatePass){const r=Hn(n);yp(e,i.data,i.blueprint,r,!0),yp(t,i.data,i.blueprint,r,!1)}}(i,r?r(n):n,t)}}class WC{}class CP{resolveComponentFactory(t){throw function bP(n){const t=Error(`No component factory found for ${Re(n)}. Did you add it to @NgModule.entryComponents?`);return t.ngComponent=n,t}(t)}}let Ir=(()=>{class n{}return n.NULL=new CP,n})();function DP(){return $s(gt(),w())}function $s(n,t){return new W(yn(n,t))}let W=(()=>{class n{constructor(e){this.nativeElement=e}}return n.__NG_ELEMENT_ID__=DP,n})();function wP(n){return n instanceof W?n.nativeElement:n}class da{}let Ii=(()=>{class n{}return n.__NG_ELEMENT_ID__=()=>function xP(){const n=w(),e=rn(gt().index,n);return function MP(n){return n[11]}(si(e)?e:n)}(),n})(),EP=(()=>{class n{}return n.\\u0275prov=k({token:n,providedIn:\"root\",factory:()=>null}),n})();class Rr{constructor(t){this.full=t,this.major=t.split(\".\")[0],this.minor=t.split(\".\")[1],this.patch=t.split(\".\").slice(2).join(\".\")}}const SP=new Rr(\"13.3.0\"),wp={};function fc(n,t,e,i,r=!1){for(;null!==e;){const s=t[e.index];if(null!==s&&i.push(ct(s)),Vn(s))for(let a=10;a<s.length;a++){const l=s[a],c=l[1].firstChild;null!==c&&fc(l[1],l,c,i)}const o=e.type;if(8&o)fc(n,t,e.child,i);else if(32&o){const a=bh(e,t);let l;for(;l=a();)i.push(l)}else if(16&o){const a=oy(t,e);if(Array.isArray(a))i.push(...a);else{const l=Ko(t[16]);fc(l[1],l,a,i,!0)}}e=r?e.projectionNext:e.next}return i}class ua{constructor(t,e){this._lView=t,this._cdRefInjectingView=e,this._appRef=null,this._attachedToViewContainer=!1}get rootNodes(){const t=this._lView,e=t[1];return fc(e,t,e.firstChild,[])}get context(){return this._lView[8]}set context(t){this._lView[8]=t}get destroyed(){return 256==(256&this._lView[2])}destroy(){if(this._appRef)this._appRef.detachView(this);else if(this._attachedToViewContainer){const t=this._lView[3];if(Vn(t)){const e=t[8],i=e?e.indexOf(this):-1;i>-1&&(xh(t,i),zl(e,i))}this._attachedToViewContainer=!1}Zv(this._lView[1],this._lView)}onDestroy(t){Ry(this._lView[1],this._lView,null,t)}markForCheck(){Yh(this._cdRefInjectingView||this._lView)}detach(){this._lView[2]&=-129}reattach(){this._lView[2]|=128}detectChanges(){Kh(this._lView[1],this._lView,this.context)}checkNoChanges(){!function RR(n,t,e){Al(!0);try{Kh(n,t,e)}finally{Al(!1)}}(this._lView[1],this._lView,this.context)}attachToViewContainerRef(){if(this._appRef)throw new H(902,\"\");this._attachedToViewContainer=!0}detachFromAppRef(){this._appRef=null,function kI(n,t){Zo(n,t,t[11],2,null,null)}(this._lView[1],this._lView)}attachToAppRef(t){if(this._attachedToViewContainer)throw new H(902,\"\");this._appRef=t}}class kP extends ua{constructor(t){super(t),this._view=t}detectChanges(){jy(this._view)}checkNoChanges(){!function OR(n){Al(!0);try{jy(n)}finally{Al(!1)}}(this._view)}get context(){return null}}class YC extends Ir{constructor(t){super(),this.ngModule=t}resolveComponentFactory(t){const e=Ot(t);return new Mp(e,this.ngModule)}}function QC(n){const t=[];for(let e in n)n.hasOwnProperty(e)&&t.push({propName:n[e],templateName:e});return t}class Mp extends WC{constructor(t,e){super(),this.componentDef=t,this.ngModule=e,this.componentType=t.type,this.selector=function YI(n){return n.map(qI).join(\",\")}(t.selectors),this.ngContentSelectors=t.ngContentSelectors?t.ngContentSelectors:[],this.isBoundToModule=!!e}get inputs(){return QC(this.componentDef.inputs)}get outputs(){return QC(this.componentDef.outputs)}create(t,e,i,r){const s=(r=r||this.ngModule)?function AP(n,t){return{get:(e,i,r)=>{const s=n.get(e,wp,r);return s!==wp||i===wp?s:t.get(e,i,r)}}}(t,r.injector):t,o=s.get(da,V_),a=s.get(EP,null),l=o.createRenderer(null,this.componentDef),c=this.componentDef.selectors[0][0]||\"div\",d=i?function Iy(n,t,e){if(et(n))return n.selectRootElement(t,e===Ln.ShadowDom);let i=\"string\"==typeof t?n.querySelector(t):t;return i.textContent=\"\",i}(l,i,this.componentDef.encapsulation):Mh(o.createRenderer(null,this.componentDef),c,function TP(n){const t=n.toLowerCase();return\"svg\"===t?\"svg\":\"math\"===t?\"math\":null}(c)),u=this.componentDef.onPush?576:528,h=function cb(n,t){return{components:[],scheduler:n||CI,clean:PR,playerHandler:t||null,flags:0}}(),p=nc(0,null,null,1,0,null,null,null,null,null),m=Xo(null,p,h,u,null,null,o,l,a,s);let g,_;Il(m);try{const D=function ab(n,t,e,i,r,s){const o=e[1];e[20]=n;const l=xs(o,20,2,\"#host\",null),c=l.mergedAttrs=t.hostAttrs;null!==c&&(rc(l,c,!0),null!==n&&(Nl(r,n,c),null!==l.classes&&Ah(r,n,l.classes),null!==l.styles&&cy(r,n,l.styles)));const d=i.createRenderer(n,t),u=Xo(e,Ty(t),null,t.onPush?64:16,e[20],l,i,d,s||null,null);return o.firstCreatePass&&(Hl(No(l,e),o,t.type),Ly(o,l),By(l,e.length,1)),ic(e,u),e[20]=u}(d,this.componentDef,m,o,l);if(d)if(i)Nl(l,d,[\"ng-version\",SP.full]);else{const{attrs:v,classes:M}=function QI(n){const t=[],e=[];let i=1,r=2;for(;i<n.length;){let s=n[i];if(\"string\"==typeof s)2===r?\"\"!==s&&t.push(s,n[++i]):8===r&&e.push(s);else{if(!jn(r))break;r=s}i++}return{attrs:t,classes:e}}(this.componentDef.selectors[0]);v&&Nl(l,d,v),M&&M.length>0&&Ah(l,d,M.join(\" \"))}if(_=Hu(p,20),void 0!==e){const v=_.projection=[];for(let M=0;M<this.ngContentSelectors.length;M++){const V=e[M];v.push(null!=V?Array.from(V):null)}}g=function lb(n,t,e,i,r){const s=e[1],o=function gR(n,t,e){const i=gt();n.firstCreatePass&&(e.providersResolver&&e.providersResolver(e),Vy(n,i,t,Es(n,t,1,null),e));const r=Lo(t,n,i.directiveStart,i);Ft(r,t);const s=yn(i,t);return s&&Ft(s,t),r}(s,e,t);if(i.components.push(o),n[8]=o,r&&r.forEach(l=>l(o,t)),t.contentQueries){const l=gt();t.contentQueries(1,o,l.directiveStart)}const a=gt();return!s.firstCreatePass||null===t.hostBindings&&null===t.hostAttrs||(Zi(a.index),Fy(e[1],a,0,a.directiveStart,a.directiveEnd,t),Ny(t,o)),o}(D,this.componentDef,m,h,[e1]),Jo(p,m,null)}finally{Rl()}return new RP(this.componentType,g,$s(_,m),m,_)}}class RP extends class yP{}{constructor(t,e,i,r,s){super(),this.location=i,this._rootLView=r,this._tNode=s,this.instance=e,this.hostView=this.changeDetectorRef=new kP(r),this.componentType=t}get injector(){return new ms(this._tNode,this._rootLView)}destroy(){this.hostView.destroy()}onDestroy(t){this.hostView.onDestroy(t)}}class Ri{}class KC{}const Gs=new Map;class JC extends Ri{constructor(t,e){super(),this._parent=e,this._bootstrapComponents=[],this.injector=this,this.destroyCbs=[],this.componentFactoryResolver=new YC(this);const i=gn(t);this._bootstrapComponents=di(i.bootstrap),this._r3Injector=Ky(t,e,[{provide:Ri,useValue:this},{provide:Ir,useValue:this.componentFactoryResolver}],Re(t)),this._r3Injector._resolveInjectorDefTypes(),this.instance=this.get(t)}get(t,e=dt.THROW_IF_NOT_FOUND,i=ee.Default){return t===dt||t===Ri||t===Xh?this:this._r3Injector.get(t,e,i)}destroy(){const t=this._r3Injector;!t.destroyed&&t.destroy(),this.destroyCbs.forEach(e=>e()),this.destroyCbs=null}onDestroy(t){this.destroyCbs.push(t)}}class xp extends KC{constructor(t){super(),this.moduleType=t,null!==gn(t)&&function PP(n){const t=new Set;!function e(i){const r=gn(i,!0),s=r.id;null!==s&&(function ZC(n,t,e){if(t&&t!==e)throw new Error(`Duplicate module registered for ${n} - ${Re(t)} vs ${Re(t.name)}`)}(s,Gs.get(s),i),Gs.set(s,i));const o=di(r.imports);for(const a of o)t.has(a)||(t.add(a),e(a))}(n)}(t)}create(t){return new JC(this.moduleType,t)}}function Ep(n){return t=>{setTimeout(n,void 0,t)}}const $=class ZP extends O{constructor(t=!1){super(),this.__isAsync=t}emit(t){super.next(t)}subscribe(t,e,i){var r,s,o;let a=t,l=e||(()=>null),c=i;if(t&&\"object\"==typeof t){const u=t;a=null===(r=u.next)||void 0===r?void 0:r.bind(u),l=null===(s=u.error)||void 0===s?void 0:s.bind(u),c=null===(o=u.complete)||void 0===o?void 0:o.bind(u)}this.__isAsync&&(l=Ep(l),a&&(a=Ep(a)),c&&(c=Ep(c)));const d=super.subscribe({next:a,error:l,complete:c});return t instanceof ke&&t.add(d),d}};function XP(){return this._results[As()]()}class fa{constructor(t=!1){this._emitDistinctChangesOnly=t,this.dirty=!0,this._results=[],this._changesDetected=!1,this._changes=null,this.length=0,this.first=void 0,this.last=void 0;const e=As(),i=fa.prototype;i[e]||(i[e]=XP)}get changes(){return this._changes||(this._changes=new $)}get(t){return this._results[t]}map(t){return this._results.map(t)}filter(t){return this._results.filter(t)}find(t){return this._results.find(t)}reduce(t,e){return this._results.reduce(t,e)}forEach(t){this._results.forEach(t)}some(t){return this._results.some(t)}toArray(){return this._results.slice()}toString(){return this._results.toString()}reset(t,e){const i=this;i.dirty=!1;const r=bn(t);(this._changesDetected=!function iA(n,t,e){if(n.length!==t.length)return!1;for(let i=0;i<n.length;i++){let r=n[i],s=t[i];if(e&&(r=e(r),s=e(s)),s!==r)return!1}return!0}(i._results,r,e))&&(i._results=r,i.length=r.length,i.last=r[this.length-1],i.first=r[0])}notifyOnChanges(){this._changes&&(this._changesDetected||!this._emitDistinctChangesOnly)&&this._changes.emit(this)}setDirty(){this.dirty=!0}destroy(){this.changes.complete(),this.changes.unsubscribe()}}Symbol;let ut=(()=>{class n{}return n.__NG_ELEMENT_ID__=tF,n})();const JP=ut,eF=class extends JP{constructor(t,e,i){super(),this._declarationLView=t,this._declarationTContainer=e,this.elementRef=i}createEmbeddedView(t){const e=this._declarationTContainer.tViews,i=Xo(this._declarationLView,e,t,16,null,e.declTNode,null,null,null,null);i[17]=this._declarationLView[this._declarationTContainer.index];const s=this._declarationLView[19];return null!==s&&(i[19]=s.createEmbeddedView(e)),Jo(e,i,t),new ua(i)}};function tF(){return gc(gt(),w())}function gc(n,t){return 4&n.type?new eF(t,n,$s(n,t)):null}let st=(()=>{class n{}return n.__NG_ELEMENT_ID__=nF,n})();function nF(){return l0(gt(),w())}const iF=st,o0=class extends iF{constructor(t,e,i){super(),this._lContainer=t,this._hostTNode=e,this._hostLView=i}get element(){return $s(this._hostTNode,this._hostLView)}get injector(){return new ms(this._hostTNode,this._hostLView)}get parentInjector(){const t=Vl(this._hostTNode,this._hostLView);if(nv(t)){const e=fs(t,this._hostLView),i=ps(t);return new ms(e[1].data[i+8],e)}return new ms(null,this._hostLView)}clear(){for(;this.length>0;)this.remove(this.length-1)}get(t){const e=a0(this._lContainer);return null!==e&&e[t]||null}get length(){return this._lContainer.length-10}createEmbeddedView(t,e,i){const r=t.createEmbeddedView(e||{});return this.insert(r,i),r}createComponent(t,e,i,r,s){const o=t&&!function Vo(n){return\"function\"==typeof n}(t);let a;if(o)a=e;else{const u=e||{};a=u.index,i=u.injector,r=u.projectableNodes,s=u.ngModuleRef}const l=o?t:new Mp(Ot(t)),c=i||this.parentInjector;if(!s&&null==l.ngModule){const h=(o?c:this.parentInjector).get(Ri,null);h&&(s=h)}const d=l.create(c,r,void 0,s);return this.insert(d.hostView,a),d}insert(t,e){const i=t._lView,r=i[1];if(function ET(n){return Vn(n[3])}(i)){const d=this.indexOf(t);if(-1!==d)this.detach(d);else{const u=i[3],h=new o0(u,u[6],u[3]);h.detach(h.indexOf(t))}}const s=this._adjustIndex(e),o=this._lContainer;!function AI(n,t,e,i){const r=10+i,s=e.length;i>0&&(e[r-1][4]=t),i<s-10?(t[4]=e[r],hv(e,10+i,t)):(e.push(t),t[4]=null),t[3]=e;const o=t[17];null!==o&&e!==o&&function II(n,t){const e=n[9];t[16]!==t[3][3][16]&&(n[2]=!0),null===e?n[9]=[t]:e.push(t)}(o,t);const a=t[19];null!==a&&a.insertView(n),t[2]|=128}(r,i,o,s);const a=kh(s,o),l=i[11],c=Kl(l,o[7]);return null!==c&&function SI(n,t,e,i,r,s){i[0]=r,i[6]=t,Zo(n,i,e,1,r,s)}(r,o[6],l,i,c,a),t.attachToViewContainerRef(),hv(Sp(o),s,t),t}move(t,e){return this.insert(t,e)}indexOf(t){const e=a0(this._lContainer);return null!==e?e.indexOf(t):-1}remove(t){const e=this._adjustIndex(t,-1),i=xh(this._lContainer,e);i&&(zl(Sp(this._lContainer),e),Zv(i[1],i))}detach(t){const e=this._adjustIndex(t,-1),i=xh(this._lContainer,e);return i&&null!=zl(Sp(this._lContainer),e)?new ua(i):null}_adjustIndex(t,e=0){return null==t?this.length+e:t}};function a0(n){return n[8]}function Sp(n){return n[8]||(n[8]=[])}function l0(n,t){let e;const i=t[n.index];if(Vn(i))e=i;else{let r;if(8&n.type)r=ct(i);else{const s=t[11];r=s.createComment(\"\");const o=yn(n,t);xr(s,Kl(s,o),r,function FI(n,t){return et(n)?n.nextSibling(t):t.nextSibling}(s,o),!1)}t[n.index]=e=Hy(i,t,r,n),ic(t,e)}return new o0(e,n,t)}class kp{constructor(t){this.queryList=t,this.matches=null}clone(){return new kp(this.queryList)}setDirty(){this.queryList.setDirty()}}class Tp{constructor(t=[]){this.queries=t}createEmbeddedView(t){const e=t.queries;if(null!==e){const i=null!==t.contentQueries?t.contentQueries[0]:e.length,r=[];for(let s=0;s<i;s++){const o=e.getByIndex(s);r.push(this.queries[o.indexInDeclarationView].clone())}return new Tp(r)}return null}insertView(t){this.dirtyQueriesWithMatches(t)}detachView(t){this.dirtyQueriesWithMatches(t)}dirtyQueriesWithMatches(t){for(let e=0;e<this.queries.length;e++)null!==p0(t,e).matches&&this.queries[e].setDirty()}}class c0{constructor(t,e,i=null){this.predicate=t,this.flags=e,this.read=i}}class Ap{constructor(t=[]){this.queries=t}elementStart(t,e){for(let i=0;i<this.queries.length;i++)this.queries[i].elementStart(t,e)}elementEnd(t){for(let e=0;e<this.queries.length;e++)this.queries[e].elementEnd(t)}embeddedTView(t){let e=null;for(let i=0;i<this.length;i++){const r=null!==e?e.length:0,s=this.getByIndex(i).embeddedTView(t,r);s&&(s.indexInDeclarationView=i,null!==e?e.push(s):e=[s])}return null!==e?new Ap(e):null}template(t,e){for(let i=0;i<this.queries.length;i++)this.queries[i].template(t,e)}getByIndex(t){return this.queries[t]}get length(){return this.queries.length}track(t){this.queries.push(t)}}class Ip{constructor(t,e=-1){this.metadata=t,this.matches=null,this.indexInDeclarationView=-1,this.crossesNgTemplate=!1,this._appliesToNextNode=!0,this._declarationNodeIndex=e}elementStart(t,e){this.isApplyingToNode(e)&&this.matchTNode(t,e)}elementEnd(t){this._declarationNodeIndex===t.index&&(this._appliesToNextNode=!1)}template(t,e){this.elementStart(t,e)}embeddedTView(t,e){return this.isApplyingToNode(t)?(this.crossesNgTemplate=!0,this.addMatch(-t.index,e),new Ip(this.metadata)):null}isApplyingToNode(t){if(this._appliesToNextNode&&1!=(1&this.metadata.flags)){const e=this._declarationNodeIndex;let i=t.parent;for(;null!==i&&8&i.type&&i.index!==e;)i=i.parent;return e===(null!==i?i.index:-1)}return this._appliesToNextNode}matchTNode(t,e){const i=this.metadata.predicate;if(Array.isArray(i))for(let r=0;r<i.length;r++){const s=i[r];this.matchTNodeWithReadOption(t,e,oF(e,s)),this.matchTNodeWithReadOption(t,e,jl(e,t,s,!1,!1))}else i===ut?4&e.type&&this.matchTNodeWithReadOption(t,e,-1):this.matchTNodeWithReadOption(t,e,jl(e,t,i,!1,!1))}matchTNodeWithReadOption(t,e,i){if(null!==i){const r=this.metadata.read;if(null!==r)if(r===W||r===st||r===ut&&4&e.type)this.addMatch(e.index,-2);else{const s=jl(e,t,r,!1,!1);null!==s&&this.addMatch(e.index,s)}else this.addMatch(e.index,i)}}addMatch(t,e){null===this.matches?this.matches=[t,e]:this.matches.push(t,e)}}function oF(n,t){const e=n.localNames;if(null!==e)for(let i=0;i<e.length;i+=2)if(e[i]===t)return e[i+1];return null}function lF(n,t,e,i){return-1===e?function aF(n,t){return 11&n.type?$s(n,t):4&n.type?gc(n,t):null}(t,n):-2===e?function cF(n,t,e){return e===W?$s(t,n):e===ut?gc(t,n):e===st?l0(t,n):void 0}(n,t,i):Lo(n,n[1],e,t)}function d0(n,t,e,i){const r=t[19].queries[i];if(null===r.matches){const s=n.data,o=e.matches,a=[];for(let l=0;l<o.length;l+=2){const c=o[l];a.push(c<0?null:lF(t,s[c],o[l+1],e.metadata.read))}r.matches=a}return r.matches}function Rp(n,t,e,i){const r=n.queries.getByIndex(e),s=r.matches;if(null!==s){const o=d0(n,t,r,e);for(let a=0;a<s.length;a+=2){const l=s[a];if(l>0)i.push(o[a/2]);else{const c=s[a+1],d=t[-l];for(let u=10;u<d.length;u++){const h=d[u];h[17]===h[3]&&Rp(h[1],h,c,i)}if(null!==d[9]){const u=d[9];for(let h=0;h<u.length;h++){const p=u[h];Rp(p[1],p,c,i)}}}}}return i}function z(n){const t=w(),e=Me(),i=W_();qu(i+1);const r=p0(e,i);if(n.dirty&&H_(t)===(2==(2&r.metadata.flags))){if(null===r.matches)n.reset([]);else{const s=r.crossesNgTemplate?Rp(e,t,i,[]):d0(e,t,r,i);n.reset(s,wP),n.notifyOnChanges()}return!0}return!1}function je(n,t,e){const i=Me();i.firstCreatePass&&(h0(i,new c0(n,t,e),-1),2==(2&t)&&(i.staticViewQueries=!0)),u0(i,w(),t)}function ve(n,t,e,i){const r=Me();if(r.firstCreatePass){const s=gt();h0(r,new c0(t,e,i),s.index),function uF(n,t){const e=n.contentQueries||(n.contentQueries=[]);t!==(e.length?e[e.length-1]:-1)&&e.push(n.queries.length-1,t)}(r,n),2==(2&e)&&(r.staticContentQueries=!0)}u0(r,w(),e)}function U(){return function dF(n,t){return n[19].queries[t].queryList}(w(),W_())}function u0(n,t,e){const i=new fa(4==(4&e));Ry(n,t,i,i.destroy),null===t[19]&&(t[19]=new Tp),t[19].queries.push(new kp(i))}function h0(n,t,e){null===n.queries&&(n.queries=new Ap),n.queries.track(new Ip(t,e))}function p0(n,t){return n.queries.getByIndex(t)}function yc(...n){}const Bp=new b(\"Application Initializer\");let Vp=(()=>{class n{constructor(e){this.appInits=e,this.resolve=yc,this.reject=yc,this.initialized=!1,this.done=!1,this.donePromise=new Promise((i,r)=>{this.resolve=i,this.reject=r})}runInitializers(){if(this.initialized)return;const e=[],i=()=>{this.done=!0,this.resolve()};if(this.appInits)for(let r=0;r<this.appInits.length;r++){const s=this.appInits[r]();if(ra(s))e.push(s);else if(up(s)){const o=new Promise((a,l)=>{s.subscribe({complete:a,error:l})});e.push(o)}}Promise.all(e).then(()=>{i()}).catch(r=>{this.reject(r)}),0===e.length&&i(),this.initialized=!0}}return n.\\u0275fac=function(e){return new(e||n)(y(Bp,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const ga=new b(\"AppId\",{providedIn:\"root\",factory:function A0(){return`${Hp()}${Hp()}${Hp()}`}});function Hp(){return String.fromCharCode(97+Math.floor(25*Math.random()))}const I0=new b(\"Platform Initializer\"),bc=new b(\"Platform ID\"),R0=new b(\"appBootstrapListener\");let O0=(()=>{class n{log(e){console.log(e)}warn(e){console.warn(e)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const Oi=new b(\"LocaleId\",{providedIn:\"root\",factory:()=>Uo(Oi,ee.Optional|ee.SkipSelf)||function TF(){return\"undefined\"!=typeof $localize&&$localize.locale||cc}()});class IF{constructor(t,e){this.ngModuleFactory=t,this.componentFactories=e}}let P0=(()=>{class n{compileModuleSync(e){return new xp(e)}compileModuleAsync(e){return Promise.resolve(this.compileModuleSync(e))}compileModuleAndAllComponentsSync(e){const i=this.compileModuleSync(e),s=di(gn(e).declarations).reduce((o,a)=>{const l=Ot(a);return l&&o.push(new Mp(l)),o},[]);return new IF(i,s)}compileModuleAndAllComponentsAsync(e){return Promise.resolve(this.compileModuleAndAllComponentsSync(e))}clearCache(){}clearCacheFor(e){}getModuleId(e){}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const OF=(()=>Promise.resolve(0))();function jp(n){\"undefined\"==typeof Zone?OF.then(()=>{n&&n.apply(null,null)}):Zone.current.scheduleMicroTask(\"scheduleMicrotask\",n)}class ne{constructor({enableLongStackTrace:t=!1,shouldCoalesceEventChangeDetection:e=!1,shouldCoalesceRunChangeDetection:i=!1}){if(this.hasPendingMacrotasks=!1,this.hasPendingMicrotasks=!1,this.isStable=!0,this.onUnstable=new $(!1),this.onMicrotaskEmpty=new $(!1),this.onStable=new $(!1),this.onError=new $(!1),\"undefined\"==typeof Zone)throw new Error(\"In this configuration Angular requires Zone.js\");Zone.assertZonePatched();const r=this;r._nesting=0,r._outer=r._inner=Zone.current,Zone.TaskTrackingZoneSpec&&(r._inner=r._inner.fork(new Zone.TaskTrackingZoneSpec)),t&&Zone.longStackTraceZoneSpec&&(r._inner=r._inner.fork(Zone.longStackTraceZoneSpec)),r.shouldCoalesceEventChangeDetection=!i&&e,r.shouldCoalesceRunChangeDetection=i,r.lastRequestAnimationFrameId=-1,r.nativeRequestAnimationFrame=function PF(){let n=Oe.requestAnimationFrame,t=Oe.cancelAnimationFrame;if(\"undefined\"!=typeof Zone&&n&&t){const e=n[Zone.__symbol__(\"OriginalDelegate\")];e&&(n=e);const i=t[Zone.__symbol__(\"OriginalDelegate\")];i&&(t=i)}return{nativeRequestAnimationFrame:n,nativeCancelAnimationFrame:t}}().nativeRequestAnimationFrame,function LF(n){const t=()=>{!function NF(n){n.isCheckStableRunning||-1!==n.lastRequestAnimationFrameId||(n.lastRequestAnimationFrameId=n.nativeRequestAnimationFrame.call(Oe,()=>{n.fakeTopEventTask||(n.fakeTopEventTask=Zone.root.scheduleEventTask(\"fakeTopEventTask\",()=>{n.lastRequestAnimationFrameId=-1,Up(n),n.isCheckStableRunning=!0,zp(n),n.isCheckStableRunning=!1},void 0,()=>{},()=>{})),n.fakeTopEventTask.invoke()}),Up(n))}(n)};n._inner=n._inner.fork({name:\"angular\",properties:{isAngularZone:!0},onInvokeTask:(e,i,r,s,o,a)=>{try{return F0(n),e.invokeTask(r,s,o,a)}finally{(n.shouldCoalesceEventChangeDetection&&\"eventTask\"===s.type||n.shouldCoalesceRunChangeDetection)&&t(),N0(n)}},onInvoke:(e,i,r,s,o,a,l)=>{try{return F0(n),e.invoke(r,s,o,a,l)}finally{n.shouldCoalesceRunChangeDetection&&t(),N0(n)}},onHasTask:(e,i,r,s)=>{e.hasTask(r,s),i===r&&(\"microTask\"==s.change?(n._hasPendingMicrotasks=s.microTask,Up(n),zp(n)):\"macroTask\"==s.change&&(n.hasPendingMacrotasks=s.macroTask))},onHandleError:(e,i,r,s)=>(e.handleError(r,s),n.runOutsideAngular(()=>n.onError.emit(s)),!1)})}(r)}static isInAngularZone(){return\"undefined\"!=typeof Zone&&!0===Zone.current.get(\"isAngularZone\")}static assertInAngularZone(){if(!ne.isInAngularZone())throw new Error(\"Expected to be in Angular Zone, but it is not!\")}static assertNotInAngularZone(){if(ne.isInAngularZone())throw new Error(\"Expected to not be in Angular Zone, but it is!\")}run(t,e,i){return this._inner.run(t,e,i)}runTask(t,e,i,r){const s=this._inner,o=s.scheduleEventTask(\"NgZoneEvent: \"+r,t,FF,yc,yc);try{return s.runTask(o,e,i)}finally{s.cancelTask(o)}}runGuarded(t,e,i){return this._inner.runGuarded(t,e,i)}runOutsideAngular(t){return this._outer.run(t)}}const FF={};function zp(n){if(0==n._nesting&&!n.hasPendingMicrotasks&&!n.isStable)try{n._nesting++,n.onMicrotaskEmpty.emit(null)}finally{if(n._nesting--,!n.hasPendingMicrotasks)try{n.runOutsideAngular(()=>n.onStable.emit(null))}finally{n.isStable=!0}}}function Up(n){n.hasPendingMicrotasks=!!(n._hasPendingMicrotasks||(n.shouldCoalesceEventChangeDetection||n.shouldCoalesceRunChangeDetection)&&-1!==n.lastRequestAnimationFrameId)}function F0(n){n._nesting++,n.isStable&&(n.isStable=!1,n.onUnstable.emit(null))}function N0(n){n._nesting--,zp(n)}class BF{constructor(){this.hasPendingMicrotasks=!1,this.hasPendingMacrotasks=!1,this.isStable=!0,this.onUnstable=new $,this.onMicrotaskEmpty=new $,this.onStable=new $,this.onError=new $}run(t,e,i){return t.apply(e,i)}runGuarded(t,e,i){return t.apply(e,i)}runOutsideAngular(t){return t()}runTask(t,e,i,r){return t.apply(e,i)}}let $p=(()=>{class n{constructor(e){this._ngZone=e,this._pendingCount=0,this._isZoneStable=!0,this._didWork=!1,this._callbacks=[],this.taskTrackingZone=null,this._watchAngularEvents(),e.run(()=>{this.taskTrackingZone=\"undefined\"==typeof Zone?null:Zone.current.get(\"TaskTrackingZone\")})}_watchAngularEvents(){this._ngZone.onUnstable.subscribe({next:()=>{this._didWork=!0,this._isZoneStable=!1}}),this._ngZone.runOutsideAngular(()=>{this._ngZone.onStable.subscribe({next:()=>{ne.assertNotInAngularZone(),jp(()=>{this._isZoneStable=!0,this._runCallbacksIfReady()})}})})}increasePendingRequestCount(){return this._pendingCount+=1,this._didWork=!0,this._pendingCount}decreasePendingRequestCount(){if(this._pendingCount-=1,this._pendingCount<0)throw new Error(\"pending async requests below zero\");return this._runCallbacksIfReady(),this._pendingCount}isStable(){return this._isZoneStable&&0===this._pendingCount&&!this._ngZone.hasPendingMacrotasks}_runCallbacksIfReady(){if(this.isStable())jp(()=>{for(;0!==this._callbacks.length;){let e=this._callbacks.pop();clearTimeout(e.timeoutId),e.doneCb(this._didWork)}this._didWork=!1});else{let e=this.getPendingTasks();this._callbacks=this._callbacks.filter(i=>!i.updateCb||!i.updateCb(e)||(clearTimeout(i.timeoutId),!1)),this._didWork=!0}}getPendingTasks(){return this.taskTrackingZone?this.taskTrackingZone.macroTasks.map(e=>({source:e.source,creationLocation:e.creationLocation,data:e.data})):[]}addCallback(e,i,r){let s=-1;i&&i>0&&(s=setTimeout(()=>{this._callbacks=this._callbacks.filter(o=>o.timeoutId!==s),e(this._didWork,this.getPendingTasks())},i)),this._callbacks.push({doneCb:e,timeoutId:s,updateCb:r})}whenStable(e,i,r){if(r&&!this.taskTrackingZone)throw new Error('Task tracking zone is required when passing an update callback to whenStable(). Is \"zone.js/plugins/task-tracking\" loaded?');this.addCallback(e,i,r),this._runCallbacksIfReady()}getPendingRequestCount(){return this._pendingCount}findProviders(e,i,r){return[]}}return n.\\u0275fac=function(e){return new(e||n)(y(ne))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),L0=(()=>{class n{constructor(){this._applications=new Map,Gp.addToWindow(this)}registerApplication(e,i){this._applications.set(e,i)}unregisterApplication(e){this._applications.delete(e)}unregisterAllApplications(){this._applications.clear()}getTestability(e){return this._applications.get(e)||null}getAllTestabilities(){return Array.from(this._applications.values())}getAllRootElements(){return Array.from(this._applications.keys())}findTestabilityInTree(e,i=!0){return Gp.findTestabilityInTree(this,e,i)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class VF{addToWindow(t){}findTestabilityInTree(t,e,i){return null}}let Qn,Gp=new VF;const B0=new b(\"AllowMultipleToken\");class V0{constructor(t,e){this.name=t,this.token=e}}function H0(n,t,e=[]){const i=`Platform: ${t}`,r=new b(i);return(s=[])=>{let o=j0();if(!o||o.injector.get(B0,!1))if(n)n(e.concat(s).concat({provide:r,useValue:!0}));else{const a=e.concat(s).concat({provide:r,useValue:!0},{provide:Jh,useValue:\"platform\"});!function UF(n){if(Qn&&!Qn.destroyed&&!Qn.injector.get(B0,!1))throw new H(400,\"\");Qn=n.get(z0);const t=n.get(I0,null);t&&t.forEach(e=>e())}(dt.create({providers:a,name:i}))}return function $F(n){const t=j0();if(!t)throw new H(401,\"\");return t}()}}function j0(){return Qn&&!Qn.destroyed?Qn:null}let z0=(()=>{class n{constructor(e){this._injector=e,this._modules=[],this._destroyListeners=[],this._destroyed=!1}bootstrapModuleFactory(e,i){const a=function GF(n,t){let e;return e=\"noop\"===n?new BF:(\"zone.js\"===n?void 0:n)||new ne({enableLongStackTrace:!1,shouldCoalesceEventChangeDetection:!!(null==t?void 0:t.ngZoneEventCoalescing),shouldCoalesceRunChangeDetection:!!(null==t?void 0:t.ngZoneRunCoalescing)}),e}(i?i.ngZone:void 0,{ngZoneEventCoalescing:i&&i.ngZoneEventCoalescing||!1,ngZoneRunCoalescing:i&&i.ngZoneRunCoalescing||!1}),l=[{provide:ne,useValue:a}];return a.run(()=>{const c=dt.create({providers:l,parent:this.injector,name:e.moduleType.name}),d=e.create(c),u=d.injector.get(Mr,null);if(!u)throw new H(402,\"\");return a.runOutsideAngular(()=>{const h=a.onError.subscribe({next:p=>{u.handleError(p)}});d.onDestroy(()=>{Wp(this._modules,d),h.unsubscribe()})}),function WF(n,t,e){try{const i=e();return ra(i)?i.catch(r=>{throw t.runOutsideAngular(()=>n.handleError(r)),r}):i}catch(i){throw t.runOutsideAngular(()=>n.handleError(i)),i}}(u,a,()=>{const h=d.injector.get(Vp);return h.runInitializers(),h.donePromise.then(()=>(function MO(n){tn(n,\"Expected localeId to be defined\"),\"string\"==typeof n&&(CC=n.toLowerCase().replace(/_/g,\"-\"))}(d.injector.get(Oi,cc)||cc),this._moduleDoBootstrap(d),d))})})}bootstrapModule(e,i=[]){const r=U0({},i);return function jF(n,t,e){const i=new xp(e);return Promise.resolve(i)}(0,0,e).then(s=>this.bootstrapModuleFactory(s,r))}_moduleDoBootstrap(e){const i=e.injector.get(Cc);if(e._bootstrapComponents.length>0)e._bootstrapComponents.forEach(r=>i.bootstrap(r));else{if(!e.instance.ngDoBootstrap)throw new H(403,\"\");e.instance.ngDoBootstrap(i)}this._modules.push(e)}onDestroy(e){this._destroyListeners.push(e)}get injector(){return this._injector}destroy(){if(this._destroyed)throw new H(404,\"\");this._modules.slice().forEach(e=>e.destroy()),this._destroyListeners.forEach(e=>e()),this._destroyed=!0}get destroyed(){return this._destroyed}}return n.\\u0275fac=function(e){return new(e||n)(y(dt))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();function U0(n,t){return Array.isArray(t)?t.reduce(U0,n):Object.assign(Object.assign({},n),t)}let Cc=(()=>{class n{constructor(e,i,r,s,o){this._zone=e,this._injector=i,this._exceptionHandler=r,this._componentFactoryResolver=s,this._initStatus=o,this._bootstrapListeners=[],this._views=[],this._runningTick=!1,this._stable=!0,this.componentTypes=[],this.components=[],this._onMicrotaskEmptySubscription=this._zone.onMicrotaskEmpty.subscribe({next:()=>{this._zone.run(()=>{this.tick()})}});const a=new Ve(c=>{this._stable=this._zone.isStable&&!this._zone.hasPendingMacrotasks&&!this._zone.hasPendingMicrotasks,this._zone.runOutsideAngular(()=>{c.next(this._stable),c.complete()})}),l=new Ve(c=>{let d;this._zone.runOutsideAngular(()=>{d=this._zone.onStable.subscribe(()=>{ne.assertNotInAngularZone(),jp(()=>{!this._stable&&!this._zone.hasPendingMacrotasks&&!this._zone.hasPendingMicrotasks&&(this._stable=!0,c.next(!0))})})});const u=this._zone.onUnstable.subscribe(()=>{ne.assertInAngularZone(),this._stable&&(this._stable=!1,this._zone.runOutsideAngular(()=>{c.next(!1)}))});return()=>{d.unsubscribe(),u.unsubscribe()}});this.isStable=Bt(a,l.pipe(function M_(n={}){const{connector:t=(()=>new O),resetOnError:e=!0,resetOnComplete:i=!0,resetOnRefCountZero:r=!0}=n;return s=>{let o=null,a=null,l=null,c=0,d=!1,u=!1;const h=()=>{null==a||a.unsubscribe(),a=null},p=()=>{h(),o=l=null,d=u=!1},m=()=>{const g=o;p(),null==g||g.unsubscribe()};return qe((g,_)=>{c++,!u&&!d&&h();const D=l=null!=l?l:t();_.add(()=>{c--,0===c&&!u&&!d&&(a=Du(m,r))}),D.subscribe(_),o||(o=new vl({next:v=>D.next(v),error:v=>{u=!0,h(),a=Du(p,e,v),D.error(v)},complete:()=>{d=!0,h(),a=Du(p,i),D.complete()}}),mt(g).subscribe(o))})(s)}}()))}bootstrap(e,i){if(!this._initStatus.done)throw new H(405,\"\");let r;r=e instanceof WC?e:this._componentFactoryResolver.resolveComponentFactory(e),this.componentTypes.push(r.componentType);const s=function zF(n){return n.isBoundToModule}(r)?void 0:this._injector.get(Ri),a=r.create(dt.NULL,[],i||r.selector,s),l=a.location.nativeElement,c=a.injector.get($p,null),d=c&&a.injector.get(L0);return c&&d&&d.registerApplication(l,c),a.onDestroy(()=>{this.detachView(a.hostView),Wp(this.components,a),d&&d.unregisterApplication(l)}),this._loadComponent(a),a}tick(){if(this._runningTick)throw new H(101,\"\");try{this._runningTick=!0;for(let e of this._views)e.detectChanges()}catch(e){this._zone.runOutsideAngular(()=>this._exceptionHandler.handleError(e))}finally{this._runningTick=!1}}attachView(e){const i=e;this._views.push(i),i.attachToAppRef(this)}detachView(e){const i=e;Wp(this._views,i),i.detachFromAppRef()}_loadComponent(e){this.attachView(e.hostView),this.tick(),this.components.push(e),this._injector.get(R0,[]).concat(this._bootstrapListeners).forEach(r=>r(e))}ngOnDestroy(){this._views.slice().forEach(e=>e.destroy()),this._onMicrotaskEmptySubscription.unsubscribe()}get viewCount(){return this._views.length}}return n.\\u0275fac=function(e){return new(e||n)(y(ne),y(dt),y(Mr),y(Ir),y(Vp))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();function Wp(n,t){const e=n.indexOf(t);e>-1&&n.splice(e,1)}let G0=!0,Ye=(()=>{class n{}return n.__NG_ELEMENT_ID__=QF,n})();function QF(n){return function KF(n,t,e){if(El(n)&&!e){const i=rn(n.index,t);return new ua(i,i)}return 47&n.type?new ua(t[16],t):null}(gt(),w(),16==(16&n))}class K0{constructor(){}supports(t){return ta(t)}create(t){return new nN(t)}}const tN=(n,t)=>t;class nN{constructor(t){this.length=0,this._linkedRecords=null,this._unlinkedRecords=null,this._previousItHead=null,this._itHead=null,this._itTail=null,this._additionsHead=null,this._additionsTail=null,this._movesHead=null,this._movesTail=null,this._removalsHead=null,this._removalsTail=null,this._identityChangesHead=null,this._identityChangesTail=null,this._trackByFn=t||tN}forEachItem(t){let e;for(e=this._itHead;null!==e;e=e._next)t(e)}forEachOperation(t){let e=this._itHead,i=this._removalsHead,r=0,s=null;for(;e||i;){const o=!i||e&&e.currentIndex<X0(i,r,s)?e:i,a=X0(o,r,s),l=o.currentIndex;if(o===i)r--,i=i._nextRemoved;else if(e=e._next,null==o.previousIndex)r++;else{s||(s=[]);const c=a-r,d=l-r;if(c!=d){for(let h=0;h<c;h++){const p=h<s.length?s[h]:s[h]=0,m=p+h;d<=m&&m<c&&(s[h]=p+1)}s[o.previousIndex]=d-c}}a!==l&&t(o,a,l)}}forEachPreviousItem(t){let e;for(e=this._previousItHead;null!==e;e=e._nextPrevious)t(e)}forEachAddedItem(t){let e;for(e=this._additionsHead;null!==e;e=e._nextAdded)t(e)}forEachMovedItem(t){let e;for(e=this._movesHead;null!==e;e=e._nextMoved)t(e)}forEachRemovedItem(t){let e;for(e=this._removalsHead;null!==e;e=e._nextRemoved)t(e)}forEachIdentityChange(t){let e;for(e=this._identityChangesHead;null!==e;e=e._nextIdentityChange)t(e)}diff(t){if(null==t&&(t=[]),!ta(t))throw new H(900,\"\");return this.check(t)?this:null}onDestroy(){}check(t){this._reset();let r,s,o,e=this._itHead,i=!1;if(Array.isArray(t)){this.length=t.length;for(let a=0;a<this.length;a++)s=t[a],o=this._trackByFn(a,s),null!==e&&Object.is(e.trackById,o)?(i&&(e=this._verifyReinsertion(e,s,o,a)),Object.is(e.item,s)||this._addIdentityChange(e,s)):(e=this._mismatch(e,s,o,a),i=!0),e=e._next}else r=0,function u1(n,t){if(Array.isArray(n))for(let e=0;e<n.length;e++)t(n[e]);else{const e=n[As()]();let i;for(;!(i=e.next()).done;)t(i.value)}}(t,a=>{o=this._trackByFn(r,a),null!==e&&Object.is(e.trackById,o)?(i&&(e=this._verifyReinsertion(e,a,o,r)),Object.is(e.item,a)||this._addIdentityChange(e,a)):(e=this._mismatch(e,a,o,r),i=!0),e=e._next,r++}),this.length=r;return this._truncate(e),this.collection=t,this.isDirty}get isDirty(){return null!==this._additionsHead||null!==this._movesHead||null!==this._removalsHead||null!==this._identityChangesHead}_reset(){if(this.isDirty){let t;for(t=this._previousItHead=this._itHead;null!==t;t=t._next)t._nextPrevious=t._next;for(t=this._additionsHead;null!==t;t=t._nextAdded)t.previousIndex=t.currentIndex;for(this._additionsHead=this._additionsTail=null,t=this._movesHead;null!==t;t=t._nextMoved)t.previousIndex=t.currentIndex;this._movesHead=this._movesTail=null,this._removalsHead=this._removalsTail=null,this._identityChangesHead=this._identityChangesTail=null}}_mismatch(t,e,i,r){let s;return null===t?s=this._itTail:(s=t._prev,this._remove(t)),null!==(t=null===this._unlinkedRecords?null:this._unlinkedRecords.get(i,null))?(Object.is(t.item,e)||this._addIdentityChange(t,e),this._reinsertAfter(t,s,r)):null!==(t=null===this._linkedRecords?null:this._linkedRecords.get(i,r))?(Object.is(t.item,e)||this._addIdentityChange(t,e),this._moveAfter(t,s,r)):t=this._addAfter(new iN(e,i),s,r),t}_verifyReinsertion(t,e,i,r){let s=null===this._unlinkedRecords?null:this._unlinkedRecords.get(i,null);return null!==s?t=this._reinsertAfter(s,t._prev,r):t.currentIndex!=r&&(t.currentIndex=r,this._addToMoves(t,r)),t}_truncate(t){for(;null!==t;){const e=t._next;this._addToRemovals(this._unlink(t)),t=e}null!==this._unlinkedRecords&&this._unlinkedRecords.clear(),null!==this._additionsTail&&(this._additionsTail._nextAdded=null),null!==this._movesTail&&(this._movesTail._nextMoved=null),null!==this._itTail&&(this._itTail._next=null),null!==this._removalsTail&&(this._removalsTail._nextRemoved=null),null!==this._identityChangesTail&&(this._identityChangesTail._nextIdentityChange=null)}_reinsertAfter(t,e,i){null!==this._unlinkedRecords&&this._unlinkedRecords.remove(t);const r=t._prevRemoved,s=t._nextRemoved;return null===r?this._removalsHead=s:r._nextRemoved=s,null===s?this._removalsTail=r:s._prevRemoved=r,this._insertAfter(t,e,i),this._addToMoves(t,i),t}_moveAfter(t,e,i){return this._unlink(t),this._insertAfter(t,e,i),this._addToMoves(t,i),t}_addAfter(t,e,i){return this._insertAfter(t,e,i),this._additionsTail=null===this._additionsTail?this._additionsHead=t:this._additionsTail._nextAdded=t,t}_insertAfter(t,e,i){const r=null===e?this._itHead:e._next;return t._next=r,t._prev=e,null===r?this._itTail=t:r._prev=t,null===e?this._itHead=t:e._next=t,null===this._linkedRecords&&(this._linkedRecords=new Z0),this._linkedRecords.put(t),t.currentIndex=i,t}_remove(t){return this._addToRemovals(this._unlink(t))}_unlink(t){null!==this._linkedRecords&&this._linkedRecords.remove(t);const e=t._prev,i=t._next;return null===e?this._itHead=i:e._next=i,null===i?this._itTail=e:i._prev=e,t}_addToMoves(t,e){return t.previousIndex===e||(this._movesTail=null===this._movesTail?this._movesHead=t:this._movesTail._nextMoved=t),t}_addToRemovals(t){return null===this._unlinkedRecords&&(this._unlinkedRecords=new Z0),this._unlinkedRecords.put(t),t.currentIndex=null,t._nextRemoved=null,null===this._removalsTail?(this._removalsTail=this._removalsHead=t,t._prevRemoved=null):(t._prevRemoved=this._removalsTail,this._removalsTail=this._removalsTail._nextRemoved=t),t}_addIdentityChange(t,e){return t.item=e,this._identityChangesTail=null===this._identityChangesTail?this._identityChangesHead=t:this._identityChangesTail._nextIdentityChange=t,t}}class iN{constructor(t,e){this.item=t,this.trackById=e,this.currentIndex=null,this.previousIndex=null,this._nextPrevious=null,this._prev=null,this._next=null,this._prevDup=null,this._nextDup=null,this._prevRemoved=null,this._nextRemoved=null,this._nextAdded=null,this._nextMoved=null,this._nextIdentityChange=null}}class rN{constructor(){this._head=null,this._tail=null}add(t){null===this._head?(this._head=this._tail=t,t._nextDup=null,t._prevDup=null):(this._tail._nextDup=t,t._prevDup=this._tail,t._nextDup=null,this._tail=t)}get(t,e){let i;for(i=this._head;null!==i;i=i._nextDup)if((null===e||e<=i.currentIndex)&&Object.is(i.trackById,t))return i;return null}remove(t){const e=t._prevDup,i=t._nextDup;return null===e?this._head=i:e._nextDup=i,null===i?this._tail=e:i._prevDup=e,null===this._head}}class Z0{constructor(){this.map=new Map}put(t){const e=t.trackById;let i=this.map.get(e);i||(i=new rN,this.map.set(e,i)),i.add(t)}get(t,e){const r=this.map.get(t);return r?r.get(t,e):null}remove(t){const e=t.trackById;return this.map.get(e).remove(t)&&this.map.delete(e),t}get isEmpty(){return 0===this.map.size}clear(){this.map.clear()}}function X0(n,t,e){const i=n.previousIndex;if(null===i)return i;let r=0;return e&&i<e.length&&(r=e[i]),i+t+r}class J0{constructor(){}supports(t){return t instanceof Map||sp(t)}create(){return new sN}}class sN{constructor(){this._records=new Map,this._mapHead=null,this._appendAfter=null,this._previousMapHead=null,this._changesHead=null,this._changesTail=null,this._additionsHead=null,this._additionsTail=null,this._removalsHead=null,this._removalsTail=null}get isDirty(){return null!==this._additionsHead||null!==this._changesHead||null!==this._removalsHead}forEachItem(t){let e;for(e=this._mapHead;null!==e;e=e._next)t(e)}forEachPreviousItem(t){let e;for(e=this._previousMapHead;null!==e;e=e._nextPrevious)t(e)}forEachChangedItem(t){let e;for(e=this._changesHead;null!==e;e=e._nextChanged)t(e)}forEachAddedItem(t){let e;for(e=this._additionsHead;null!==e;e=e._nextAdded)t(e)}forEachRemovedItem(t){let e;for(e=this._removalsHead;null!==e;e=e._nextRemoved)t(e)}diff(t){if(t){if(!(t instanceof Map||sp(t)))throw new H(900,\"\")}else t=new Map;return this.check(t)?this:null}onDestroy(){}check(t){this._reset();let e=this._mapHead;if(this._appendAfter=null,this._forEach(t,(i,r)=>{if(e&&e.key===r)this._maybeAddToChanges(e,i),this._appendAfter=e,e=e._next;else{const s=this._getOrCreateRecordForKey(r,i);e=this._insertBeforeOrAppend(e,s)}}),e){e._prev&&(e._prev._next=null),this._removalsHead=e;for(let i=e;null!==i;i=i._nextRemoved)i===this._mapHead&&(this._mapHead=null),this._records.delete(i.key),i._nextRemoved=i._next,i.previousValue=i.currentValue,i.currentValue=null,i._prev=null,i._next=null}return this._changesTail&&(this._changesTail._nextChanged=null),this._additionsTail&&(this._additionsTail._nextAdded=null),this.isDirty}_insertBeforeOrAppend(t,e){if(t){const i=t._prev;return e._next=t,e._prev=i,t._prev=e,i&&(i._next=e),t===this._mapHead&&(this._mapHead=e),this._appendAfter=t,t}return this._appendAfter?(this._appendAfter._next=e,e._prev=this._appendAfter):this._mapHead=e,this._appendAfter=e,null}_getOrCreateRecordForKey(t,e){if(this._records.has(t)){const r=this._records.get(t);this._maybeAddToChanges(r,e);const s=r._prev,o=r._next;return s&&(s._next=o),o&&(o._prev=s),r._next=null,r._prev=null,r}const i=new oN(t);return this._records.set(t,i),i.currentValue=e,this._addToAdditions(i),i}_reset(){if(this.isDirty){let t;for(this._previousMapHead=this._mapHead,t=this._previousMapHead;null!==t;t=t._next)t._nextPrevious=t._next;for(t=this._changesHead;null!==t;t=t._nextChanged)t.previousValue=t.currentValue;for(t=this._additionsHead;null!=t;t=t._nextAdded)t.previousValue=t.currentValue;this._changesHead=this._changesTail=null,this._additionsHead=this._additionsTail=null,this._removalsHead=null}}_maybeAddToChanges(t,e){Object.is(e,t.currentValue)||(t.previousValue=t.currentValue,t.currentValue=e,this._addToChanges(t))}_addToAdditions(t){null===this._additionsHead?this._additionsHead=this._additionsTail=t:(this._additionsTail._nextAdded=t,this._additionsTail=t)}_addToChanges(t){null===this._changesHead?this._changesHead=this._changesTail=t:(this._changesTail._nextChanged=t,this._changesTail=t)}_forEach(t,e){t instanceof Map?t.forEach(e):Object.keys(t).forEach(i=>e(t[i],i))}}class oN{constructor(t){this.key=t,this.previousValue=null,this.currentValue=null,this._nextPrevious=null,this._next=null,this._prev=null,this._nextAdded=null,this._nextRemoved=null,this._nextChanged=null}}function eD(){return new xn([new K0])}let xn=(()=>{class n{constructor(e){this.factories=e}static create(e,i){if(null!=i){const r=i.factories.slice();e=e.concat(r)}return new n(e)}static extend(e){return{provide:n,useFactory:i=>n.create(e,i||eD()),deps:[[n,new Cn,new Tt]]}}find(e){const i=this.factories.find(r=>r.supports(e));if(null!=i)return i;throw new H(901,\"\")}}return n.\\u0275prov=k({token:n,providedIn:\"root\",factory:eD}),n})();function tD(){return new _a([new J0])}let _a=(()=>{class n{constructor(e){this.factories=e}static create(e,i){if(i){const r=i.factories.slice();e=e.concat(r)}return new n(e)}static extend(e){return{provide:n,useFactory:i=>n.create(e,i||tD()),deps:[[n,new Cn,new Tt]]}}find(e){const i=this.factories.find(s=>s.supports(e));if(i)return i;throw new H(901,\"\")}}return n.\\u0275prov=k({token:n,providedIn:\"root\",factory:tD}),n})();const cN=H0(null,\"core\",[{provide:bc,useValue:\"unknown\"},{provide:z0,deps:[dt]},{provide:L0,deps:[]},{provide:O0,deps:[]}]);let dN=(()=>{class n{constructor(e){}}return n.\\u0275fac=function(e){return new(e||n)(y(Cc))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),Mc=null;function mi(){return Mc}const ie=new b(\"DocumentToken\");let Pr=(()=>{class n{historyGo(e){throw new Error(\"Not implemented\")}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:function(){return function fN(){return y(nD)}()},providedIn:\"platform\"}),n})();const mN=new b(\"Location Initialized\");let nD=(()=>{class n extends Pr{constructor(e){super(),this._doc=e,this._init()}_init(){this.location=window.location,this._history=window.history}getBaseHrefFromDOM(){return mi().getBaseHref(this._doc)}onPopState(e){const i=mi().getGlobalEventTarget(this._doc,\"window\");return i.addEventListener(\"popstate\",e,!1),()=>i.removeEventListener(\"popstate\",e)}onHashChange(e){const i=mi().getGlobalEventTarget(this._doc,\"window\");return i.addEventListener(\"hashchange\",e,!1),()=>i.removeEventListener(\"hashchange\",e)}get href(){return this.location.href}get protocol(){return this.location.protocol}get hostname(){return this.location.hostname}get port(){return this.location.port}get pathname(){return this.location.pathname}get search(){return this.location.search}get hash(){return this.location.hash}set pathname(e){this.location.pathname=e}pushState(e,i,r){iD()?this._history.pushState(e,i,r):this.location.hash=r}replaceState(e,i,r){iD()?this._history.replaceState(e,i,r):this.location.hash=r}forward(){this._history.forward()}back(){this._history.back()}historyGo(e=0){this._history.go(e)}getState(){return this._history.state}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:function(){return function gN(){return new nD(y(ie))}()},providedIn:\"platform\"}),n})();function iD(){return!!window.history.pushState}function Zp(n,t){if(0==n.length)return t;if(0==t.length)return n;let e=0;return n.endsWith(\"/\")&&e++,t.startsWith(\"/\")&&e++,2==e?n+t.substring(1):1==e?n+t:n+\"/\"+t}function rD(n){const t=n.match(/#|\\?|$/),e=t&&t.index||n.length;return n.slice(0,e-(\"/\"===n[e-1]?1:0))+n.slice(e)}function Pi(n){return n&&\"?\"!==n[0]?\"?\"+n:n}let qs=(()=>{class n{historyGo(e){throw new Error(\"Not implemented\")}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:function(){return function _N(n){const t=y(ie).location;return new sD(y(Pr),t&&t.origin||\"\")}()},providedIn:\"root\"}),n})();const Xp=new b(\"appBaseHref\");let sD=(()=>{class n extends qs{constructor(e,i){if(super(),this._platformLocation=e,this._removeListenerFns=[],null==i&&(i=this._platformLocation.getBaseHrefFromDOM()),null==i)throw new Error(\"No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.\");this._baseHref=i}ngOnDestroy(){for(;this._removeListenerFns.length;)this._removeListenerFns.pop()()}onPopState(e){this._removeListenerFns.push(this._platformLocation.onPopState(e),this._platformLocation.onHashChange(e))}getBaseHref(){return this._baseHref}prepareExternalUrl(e){return Zp(this._baseHref,e)}path(e=!1){const i=this._platformLocation.pathname+Pi(this._platformLocation.search),r=this._platformLocation.hash;return r&&e?`${i}${r}`:i}pushState(e,i,r,s){const o=this.prepareExternalUrl(r+Pi(s));this._platformLocation.pushState(e,i,o)}replaceState(e,i,r,s){const o=this.prepareExternalUrl(r+Pi(s));this._platformLocation.replaceState(e,i,o)}forward(){this._platformLocation.forward()}back(){this._platformLocation.back()}historyGo(e=0){var i,r;null===(r=(i=this._platformLocation).historyGo)||void 0===r||r.call(i,e)}}return n.\\u0275fac=function(e){return new(e||n)(y(Pr),y(Xp,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),vN=(()=>{class n extends qs{constructor(e,i){super(),this._platformLocation=e,this._baseHref=\"\",this._removeListenerFns=[],null!=i&&(this._baseHref=i)}ngOnDestroy(){for(;this._removeListenerFns.length;)this._removeListenerFns.pop()()}onPopState(e){this._removeListenerFns.push(this._platformLocation.onPopState(e),this._platformLocation.onHashChange(e))}getBaseHref(){return this._baseHref}path(e=!1){let i=this._platformLocation.hash;return null==i&&(i=\"#\"),i.length>0?i.substring(1):i}prepareExternalUrl(e){const i=Zp(this._baseHref,e);return i.length>0?\"#\"+i:i}pushState(e,i,r,s){let o=this.prepareExternalUrl(r+Pi(s));0==o.length&&(o=this._platformLocation.pathname),this._platformLocation.pushState(e,i,o)}replaceState(e,i,r,s){let o=this.prepareExternalUrl(r+Pi(s));0==o.length&&(o=this._platformLocation.pathname),this._platformLocation.replaceState(e,i,o)}forward(){this._platformLocation.forward()}back(){this._platformLocation.back()}historyGo(e=0){var i,r;null===(r=(i=this._platformLocation).historyGo)||void 0===r||r.call(i,e)}}return n.\\u0275fac=function(e){return new(e||n)(y(Pr),y(Xp,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),va=(()=>{class n{constructor(e,i){this._subject=new $,this._urlChangeListeners=[],this._platformStrategy=e;const r=this._platformStrategy.getBaseHref();this._platformLocation=i,this._baseHref=rD(oD(r)),this._platformStrategy.onPopState(s=>{this._subject.emit({url:this.path(!0),pop:!0,state:s.state,type:s.type})})}path(e=!1){return this.normalize(this._platformStrategy.path(e))}getState(){return this._platformLocation.getState()}isCurrentPathEqualTo(e,i=\"\"){return this.path()==this.normalize(e+Pi(i))}normalize(e){return n.stripTrailingSlash(function bN(n,t){return n&&t.startsWith(n)?t.substring(n.length):t}(this._baseHref,oD(e)))}prepareExternalUrl(e){return e&&\"/\"!==e[0]&&(e=\"/\"+e),this._platformStrategy.prepareExternalUrl(e)}go(e,i=\"\",r=null){this._platformStrategy.pushState(r,\"\",e,i),this._notifyUrlChangeListeners(this.prepareExternalUrl(e+Pi(i)),r)}replaceState(e,i=\"\",r=null){this._platformStrategy.replaceState(r,\"\",e,i),this._notifyUrlChangeListeners(this.prepareExternalUrl(e+Pi(i)),r)}forward(){this._platformStrategy.forward()}back(){this._platformStrategy.back()}historyGo(e=0){var i,r;null===(r=(i=this._platformStrategy).historyGo)||void 0===r||r.call(i,e)}onUrlChange(e){this._urlChangeListeners.push(e),this._urlChangeSubscription||(this._urlChangeSubscription=this.subscribe(i=>{this._notifyUrlChangeListeners(i.url,i.state)}))}_notifyUrlChangeListeners(e=\"\",i){this._urlChangeListeners.forEach(r=>r(e,i))}subscribe(e,i,r){return this._subject.subscribe({next:e,error:i,complete:r})}}return n.normalizeQueryParams=Pi,n.joinWithSlash=Zp,n.stripTrailingSlash=rD,n.\\u0275fac=function(e){return new(e||n)(y(qs),y(Pr))},n.\\u0275prov=k({token:n,factory:function(){return function yN(){return new va(y(qs),y(Pr))}()},providedIn:\"root\"}),n})();function oD(n){return n.replace(/\\/index.html$/,\"\")}let mD=(()=>{class n{constructor(e,i,r,s){this._iterableDiffers=e,this._keyValueDiffers=i,this._ngEl=r,this._renderer=s,this._iterableDiffer=null,this._keyValueDiffer=null,this._initialClasses=[],this._rawClass=null}set klass(e){this._removeClasses(this._initialClasses),this._initialClasses=\"string\"==typeof e?e.split(/\\s+/):[],this._applyClasses(this._initialClasses),this._applyClasses(this._rawClass)}set ngClass(e){this._removeClasses(this._rawClass),this._applyClasses(this._initialClasses),this._iterableDiffer=null,this._keyValueDiffer=null,this._rawClass=\"string\"==typeof e?e.split(/\\s+/):e,this._rawClass&&(ta(this._rawClass)?this._iterableDiffer=this._iterableDiffers.find(this._rawClass).create():this._keyValueDiffer=this._keyValueDiffers.find(this._rawClass).create())}ngDoCheck(){if(this._iterableDiffer){const e=this._iterableDiffer.diff(this._rawClass);e&&this._applyIterableChanges(e)}else if(this._keyValueDiffer){const e=this._keyValueDiffer.diff(this._rawClass);e&&this._applyKeyValueChanges(e)}}_applyKeyValueChanges(e){e.forEachAddedItem(i=>this._toggleClass(i.key,i.currentValue)),e.forEachChangedItem(i=>this._toggleClass(i.key,i.currentValue)),e.forEachRemovedItem(i=>{i.previousValue&&this._toggleClass(i.key,!1)})}_applyIterableChanges(e){e.forEachAddedItem(i=>{if(\"string\"!=typeof i.item)throw new Error(`NgClass can only toggle CSS classes expressed as strings, got ${Re(i.item)}`);this._toggleClass(i.item,!0)}),e.forEachRemovedItem(i=>this._toggleClass(i.item,!1))}_applyClasses(e){e&&(Array.isArray(e)||e instanceof Set?e.forEach(i=>this._toggleClass(i,!0)):Object.keys(e).forEach(i=>this._toggleClass(i,!!e[i])))}_removeClasses(e){e&&(Array.isArray(e)||e instanceof Set?e.forEach(i=>this._toggleClass(i,!1)):Object.keys(e).forEach(i=>this._toggleClass(i,!1)))}_toggleClass(e,i){(e=e.trim())&&e.split(/\\s+/g).forEach(r=>{i?this._renderer.addClass(this._ngEl.nativeElement,r):this._renderer.removeClass(this._ngEl.nativeElement,r)})}}return n.\\u0275fac=function(e){return new(e||n)(f(xn),f(_a),f(W),f(Ii))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngClass\",\"\"]],inputs:{klass:[\"class\",\"klass\"],ngClass:\"ngClass\"}}),n})();class sL{constructor(t,e,i,r){this.$implicit=t,this.ngForOf=e,this.index=i,this.count=r}get first(){return 0===this.index}get last(){return this.index===this.count-1}get even(){return this.index%2==0}get odd(){return!this.even}}let gD=(()=>{class n{constructor(e,i,r){this._viewContainer=e,this._template=i,this._differs=r,this._ngForOf=null,this._ngForOfDirty=!0,this._differ=null}set ngForOf(e){this._ngForOf=e,this._ngForOfDirty=!0}set ngForTrackBy(e){this._trackByFn=e}get ngForTrackBy(){return this._trackByFn}set ngForTemplate(e){e&&(this._template=e)}ngDoCheck(){if(this._ngForOfDirty){this._ngForOfDirty=!1;const e=this._ngForOf;!this._differ&&e&&(this._differ=this._differs.find(e).create(this.ngForTrackBy))}if(this._differ){const e=this._differ.diff(this._ngForOf);e&&this._applyChanges(e)}}_applyChanges(e){const i=this._viewContainer;e.forEachOperation((r,s,o)=>{if(null==r.previousIndex)i.createEmbeddedView(this._template,new sL(r.item,this._ngForOf,-1,-1),null===o?void 0:o);else if(null==o)i.remove(null===s?void 0:s);else if(null!==s){const a=i.get(s);i.move(a,o),_D(a,r)}});for(let r=0,s=i.length;r<s;r++){const a=i.get(r).context;a.index=r,a.count=s,a.ngForOf=this._ngForOf}e.forEachIdentityChange(r=>{_D(i.get(r.currentIndex),r)})}static ngTemplateContextGuard(e,i){return!0}}return n.\\u0275fac=function(e){return new(e||n)(f(st),f(ut),f(xn))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngFor\",\"\",\"ngForOf\",\"\"]],inputs:{ngForOf:\"ngForOf\",ngForTrackBy:\"ngForTrackBy\",ngForTemplate:\"ngForTemplate\"}}),n})();function _D(n,t){n.context.$implicit=t.item}let Ca=(()=>{class n{constructor(e,i){this._viewContainer=e,this._context=new oL,this._thenTemplateRef=null,this._elseTemplateRef=null,this._thenViewRef=null,this._elseViewRef=null,this._thenTemplateRef=i}set ngIf(e){this._context.$implicit=this._context.ngIf=e,this._updateView()}set ngIfThen(e){vD(\"ngIfThen\",e),this._thenTemplateRef=e,this._thenViewRef=null,this._updateView()}set ngIfElse(e){vD(\"ngIfElse\",e),this._elseTemplateRef=e,this._elseViewRef=null,this._updateView()}_updateView(){this._context.$implicit?this._thenViewRef||(this._viewContainer.clear(),this._elseViewRef=null,this._thenTemplateRef&&(this._thenViewRef=this._viewContainer.createEmbeddedView(this._thenTemplateRef,this._context))):this._elseViewRef||(this._viewContainer.clear(),this._thenViewRef=null,this._elseTemplateRef&&(this._elseViewRef=this._viewContainer.createEmbeddedView(this._elseTemplateRef,this._context)))}static ngTemplateContextGuard(e,i){return!0}}return n.\\u0275fac=function(e){return new(e||n)(f(st),f(ut))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngIf\",\"\"]],inputs:{ngIf:\"ngIf\",ngIfThen:\"ngIfThen\",ngIfElse:\"ngIfElse\"}}),n})();class oL{constructor(){this.$implicit=null,this.ngIf=null}}function vD(n,t){if(t&&!t.createEmbeddedView)throw new Error(`${n} must be a TemplateRef, but received '${Re(t)}'.`)}class df{constructor(t,e){this._viewContainerRef=t,this._templateRef=e,this._created=!1}create(){this._created=!0,this._viewContainerRef.createEmbeddedView(this._templateRef)}destroy(){this._created=!1,this._viewContainerRef.clear()}enforceState(t){t&&!this._created?this.create():!t&&this._created&&this.destroy()}}let Ys=(()=>{class n{constructor(){this._defaultUsed=!1,this._caseCount=0,this._lastCaseCheckIndex=0,this._lastCasesMatched=!1}set ngSwitch(e){this._ngSwitch=e,0===this._caseCount&&this._updateDefaultCases(!0)}_addCase(){return this._caseCount++}_addDefault(e){this._defaultViews||(this._defaultViews=[]),this._defaultViews.push(e)}_matchCase(e){const i=e==this._ngSwitch;return this._lastCasesMatched=this._lastCasesMatched||i,this._lastCaseCheckIndex++,this._lastCaseCheckIndex===this._caseCount&&(this._updateDefaultCases(!this._lastCasesMatched),this._lastCaseCheckIndex=0,this._lastCasesMatched=!1),i}_updateDefaultCases(e){if(this._defaultViews&&e!==this._defaultUsed){this._defaultUsed=e;for(let i=0;i<this._defaultViews.length;i++)this._defaultViews[i].enforceState(e)}}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngSwitch\",\"\"]],inputs:{ngSwitch:\"ngSwitch\"}}),n})(),Pc=(()=>{class n{constructor(e,i,r){this.ngSwitch=r,r._addCase(),this._view=new df(e,i)}ngDoCheck(){this._view.enforceState(this.ngSwitch._matchCase(this.ngSwitchCase))}}return n.\\u0275fac=function(e){return new(e||n)(f(st),f(ut),f(Ys,9))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngSwitchCase\",\"\"]],inputs:{ngSwitchCase:\"ngSwitchCase\"}}),n})(),yD=(()=>{class n{constructor(e,i,r){r._addDefault(new df(e,i))}}return n.\\u0275fac=function(e){return new(e||n)(f(st),f(ut),f(Ys,9))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngSwitchDefault\",\"\"]]}),n})(),bt=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const wD=\"browser\";let PL=(()=>{class n{}return n.\\u0275prov=k({token:n,providedIn:\"root\",factory:()=>new FL(y(ie),window)}),n})();class FL{constructor(t,e){this.document=t,this.window=e,this.offset=()=>[0,0]}setOffset(t){this.offset=Array.isArray(t)?()=>t:t}getScrollPosition(){return this.supportsScrolling()?[this.window.pageXOffset,this.window.pageYOffset]:[0,0]}scrollToPosition(t){this.supportsScrolling()&&this.window.scrollTo(t[0],t[1])}scrollToAnchor(t){if(!this.supportsScrolling())return;const e=function NL(n,t){const e=n.getElementById(t)||n.getElementsByName(t)[0];if(e)return e;if(\"function\"==typeof n.createTreeWalker&&n.body&&(n.body.createShadowRoot||n.body.attachShadow)){const i=n.createTreeWalker(n.body,NodeFilter.SHOW_ELEMENT);let r=i.currentNode;for(;r;){const s=r.shadowRoot;if(s){const o=s.getElementById(t)||s.querySelector(`[name=\"${t}\"]`);if(o)return o}r=i.nextNode()}}return null}(this.document,t);e&&(this.scrollToElement(e),e.focus())}setHistoryScrollRestoration(t){if(this.supportScrollRestoration()){const e=this.window.history;e&&e.scrollRestoration&&(e.scrollRestoration=t)}}scrollToElement(t){const e=t.getBoundingClientRect(),i=e.left+this.window.pageXOffset,r=e.top+this.window.pageYOffset,s=this.offset();this.window.scrollTo(i-s[0],r-s[1])}supportScrollRestoration(){try{if(!this.supportsScrolling())return!1;const t=MD(this.window.history)||MD(Object.getPrototypeOf(this.window.history));return!(!t||!t.writable&&!t.set)}catch(t){return!1}}supportsScrolling(){try{return!!this.window&&!!this.window.scrollTo&&\"pageXOffset\"in this.window}catch(t){return!1}}}function MD(n){return Object.getOwnPropertyDescriptor(n,\"scrollRestoration\")}class pf extends class BL extends class pN{}{constructor(){super(...arguments),this.supportsDOMEvents=!0}}{static makeCurrent(){!function hN(n){Mc||(Mc=n)}(new pf)}onAndCancel(t,e,i){return t.addEventListener(e,i,!1),()=>{t.removeEventListener(e,i,!1)}}dispatchEvent(t,e){t.dispatchEvent(e)}remove(t){t.parentNode&&t.parentNode.removeChild(t)}createElement(t,e){return(e=e||this.getDefaultDocument()).createElement(t)}createHtmlDocument(){return document.implementation.createHTMLDocument(\"fakeTitle\")}getDefaultDocument(){return document}isElementNode(t){return t.nodeType===Node.ELEMENT_NODE}isShadowRoot(t){return t instanceof DocumentFragment}getGlobalEventTarget(t,e){return\"window\"===e?window:\"document\"===e?t:\"body\"===e?t.body:null}getBaseHref(t){const e=function VL(){return Da=Da||document.querySelector(\"base\"),Da?Da.getAttribute(\"href\"):null}();return null==e?null:function HL(n){Fc=Fc||document.createElement(\"a\"),Fc.setAttribute(\"href\",n);const t=Fc.pathname;return\"/\"===t.charAt(0)?t:`/${t}`}(e)}resetBaseElement(){Da=null}getUserAgent(){return window.navigator.userAgent}getCookie(t){return function iL(n,t){t=encodeURIComponent(t);for(const e of n.split(\";\")){const i=e.indexOf(\"=\"),[r,s]=-1==i?[e,\"\"]:[e.slice(0,i),e.slice(i+1)];if(r.trim()===t)return decodeURIComponent(s)}return null}(document.cookie,t)}}let Fc,Da=null;const xD=new b(\"TRANSITION_ID\"),zL=[{provide:Bp,useFactory:function jL(n,t,e){return()=>{e.get(Vp).donePromise.then(()=>{const i=mi(),r=t.querySelectorAll(`style[ng-transition=\"${n}\"]`);for(let s=0;s<r.length;s++)i.remove(r[s])})}},deps:[xD,ie,dt],multi:!0}];class ff{static init(){!function HF(n){Gp=n}(new ff)}addToWindow(t){Oe.getAngularTestability=(i,r=!0)=>{const s=t.findTestabilityInTree(i,r);if(null==s)throw new Error(\"Could not find testability for element.\");return s},Oe.getAllAngularTestabilities=()=>t.getAllTestabilities(),Oe.getAllAngularRootElements=()=>t.getAllRootElements(),Oe.frameworkStabilizers||(Oe.frameworkStabilizers=[]),Oe.frameworkStabilizers.push(i=>{const r=Oe.getAllAngularTestabilities();let s=r.length,o=!1;const a=function(l){o=o||l,s--,0==s&&i(o)};r.forEach(function(l){l.whenStable(a)})})}findTestabilityInTree(t,e,i){if(null==e)return null;const r=t.getTestability(e);return null!=r?r:i?mi().isShadowRoot(e)?this.findTestabilityInTree(t,e.host,!0):this.findTestabilityInTree(t,e.parentElement,!0):null}}let UL=(()=>{class n{build(){return new XMLHttpRequest}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const Nc=new b(\"EventManagerPlugins\");let Lc=(()=>{class n{constructor(e,i){this._zone=i,this._eventNameToPlugin=new Map,e.forEach(r=>r.manager=this),this._plugins=e.slice().reverse()}addEventListener(e,i,r){return this._findPluginFor(i).addEventListener(e,i,r)}addGlobalEventListener(e,i,r){return this._findPluginFor(i).addGlobalEventListener(e,i,r)}getZone(){return this._zone}_findPluginFor(e){const i=this._eventNameToPlugin.get(e);if(i)return i;const r=this._plugins;for(let s=0;s<r.length;s++){const o=r[s];if(o.supports(e))return this._eventNameToPlugin.set(e,o),o}throw new Error(`No event manager plugin found for event ${e}`)}}return n.\\u0275fac=function(e){return new(e||n)(y(Nc),y(ne))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class ED{constructor(t){this._doc=t}addGlobalEventListener(t,e,i){const r=mi().getGlobalEventTarget(this._doc,t);if(!r)throw new Error(`Unsupported event target ${r} for event ${e}`);return this.addEventListener(r,e,i)}}let SD=(()=>{class n{constructor(){this._stylesSet=new Set}addStyles(e){const i=new Set;e.forEach(r=>{this._stylesSet.has(r)||(this._stylesSet.add(r),i.add(r))}),this.onStylesAdded(i)}onStylesAdded(e){}getAllStyles(){return Array.from(this._stylesSet)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),wa=(()=>{class n extends SD{constructor(e){super(),this._doc=e,this._hostNodes=new Map,this._hostNodes.set(e.head,[])}_addStylesToHost(e,i,r){e.forEach(s=>{const o=this._doc.createElement(\"style\");o.textContent=s,r.push(i.appendChild(o))})}addHost(e){const i=[];this._addStylesToHost(this._stylesSet,e,i),this._hostNodes.set(e,i)}removeHost(e){const i=this._hostNodes.get(e);i&&i.forEach(kD),this._hostNodes.delete(e)}onStylesAdded(e){this._hostNodes.forEach((i,r)=>{this._addStylesToHost(e,r,i)})}ngOnDestroy(){this._hostNodes.forEach(e=>e.forEach(kD))}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();function kD(n){mi().remove(n)}const mf={svg:\"http://www.w3.org/2000/svg\",xhtml:\"http://www.w3.org/1999/xhtml\",xlink:\"http://www.w3.org/1999/xlink\",xml:\"http://www.w3.org/XML/1998/namespace\",xmlns:\"http://www.w3.org/2000/xmlns/\",math:\"http://www.w3.org/1998/MathML/\"},gf=/%COMP%/g;function Bc(n,t,e){for(let i=0;i<t.length;i++){let r=t[i];Array.isArray(r)?Bc(n,r,e):(r=r.replace(gf,n),e.push(r))}return e}function ID(n){return t=>{if(\"__ngUnwrap__\"===t)return n;!1===n(t)&&(t.preventDefault(),t.returnValue=!1)}}let Vc=(()=>{class n{constructor(e,i,r){this.eventManager=e,this.sharedStylesHost=i,this.appId=r,this.rendererByCompId=new Map,this.defaultRenderer=new _f(e)}createRenderer(e,i){if(!e||!i)return this.defaultRenderer;switch(i.encapsulation){case Ln.Emulated:{let r=this.rendererByCompId.get(i.id);return r||(r=new QL(this.eventManager,this.sharedStylesHost,i,this.appId),this.rendererByCompId.set(i.id,r)),r.applyToHost(e),r}case 1:case Ln.ShadowDom:return new KL(this.eventManager,this.sharedStylesHost,e,i);default:if(!this.rendererByCompId.has(i.id)){const r=Bc(i.id,i.styles,[]);this.sharedStylesHost.addStyles(r),this.rendererByCompId.set(i.id,this.defaultRenderer)}return this.defaultRenderer}}begin(){}end(){}}return n.\\u0275fac=function(e){return new(e||n)(y(Lc),y(wa),y(ga))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class _f{constructor(t){this.eventManager=t,this.data=Object.create(null),this.destroyNode=null}destroy(){}createElement(t,e){return e?document.createElementNS(mf[e]||e,t):document.createElement(t)}createComment(t){return document.createComment(t)}createText(t){return document.createTextNode(t)}appendChild(t,e){t.appendChild(e)}insertBefore(t,e,i){t&&t.insertBefore(e,i)}removeChild(t,e){t&&t.removeChild(e)}selectRootElement(t,e){let i=\"string\"==typeof t?document.querySelector(t):t;if(!i)throw new Error(`The selector \"${t}\" did not match any elements`);return e||(i.textContent=\"\"),i}parentNode(t){return t.parentNode}nextSibling(t){return t.nextSibling}setAttribute(t,e,i,r){if(r){e=r+\":\"+e;const s=mf[r];s?t.setAttributeNS(s,e,i):t.setAttribute(e,i)}else t.setAttribute(e,i)}removeAttribute(t,e,i){if(i){const r=mf[i];r?t.removeAttributeNS(r,e):t.removeAttribute(`${i}:${e}`)}else t.removeAttribute(e)}addClass(t,e){t.classList.add(e)}removeClass(t,e){t.classList.remove(e)}setStyle(t,e,i,r){r&(an.DashCase|an.Important)?t.style.setProperty(e,i,r&an.Important?\"important\":\"\"):t.style[e]=i}removeStyle(t,e,i){i&an.DashCase?t.style.removeProperty(e):t.style[e]=\"\"}setProperty(t,e,i){t[e]=i}setValue(t,e){t.nodeValue=e}listen(t,e,i){return\"string\"==typeof t?this.eventManager.addGlobalEventListener(t,e,ID(i)):this.eventManager.addEventListener(t,e,ID(i))}}class QL extends _f{constructor(t,e,i,r){super(t),this.component=i;const s=Bc(r+\"-\"+i.id,i.styles,[]);e.addStyles(s),this.contentAttr=function WL(n){return\"_ngcontent-%COMP%\".replace(gf,n)}(r+\"-\"+i.id),this.hostAttr=function qL(n){return\"_nghost-%COMP%\".replace(gf,n)}(r+\"-\"+i.id)}applyToHost(t){super.setAttribute(t,this.hostAttr,\"\")}createElement(t,e){const i=super.createElement(t,e);return super.setAttribute(i,this.contentAttr,\"\"),i}}class KL extends _f{constructor(t,e,i,r){super(t),this.sharedStylesHost=e,this.hostEl=i,this.shadowRoot=i.attachShadow({mode:\"open\"}),this.sharedStylesHost.addHost(this.shadowRoot);const s=Bc(r.id,r.styles,[]);for(let o=0;o<s.length;o++){const a=document.createElement(\"style\");a.textContent=s[o],this.shadowRoot.appendChild(a)}}nodeOrShadowRoot(t){return t===this.hostEl?this.shadowRoot:t}destroy(){this.sharedStylesHost.removeHost(this.shadowRoot)}appendChild(t,e){return super.appendChild(this.nodeOrShadowRoot(t),e)}insertBefore(t,e,i){return super.insertBefore(this.nodeOrShadowRoot(t),e,i)}removeChild(t,e){return super.removeChild(this.nodeOrShadowRoot(t),e)}parentNode(t){return this.nodeOrShadowRoot(super.parentNode(this.nodeOrShadowRoot(t)))}}let ZL=(()=>{class n extends ED{constructor(e){super(e)}supports(e){return!0}addEventListener(e,i,r){return e.addEventListener(i,r,!1),()=>this.removeEventListener(e,i,r)}removeEventListener(e,i,r){return e.removeEventListener(i,r)}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const OD=[\"alt\",\"control\",\"meta\",\"shift\"],JL={\"\\b\":\"Backspace\",\"\\t\":\"Tab\",\"\\x7f\":\"Delete\",\"\\x1b\":\"Escape\",Del:\"Delete\",Esc:\"Escape\",Left:\"ArrowLeft\",Right:\"ArrowRight\",Up:\"ArrowUp\",Down:\"ArrowDown\",Menu:\"ContextMenu\",Scroll:\"ScrollLock\",Win:\"OS\"},PD={A:\"1\",B:\"2\",C:\"3\",D:\"4\",E:\"5\",F:\"6\",G:\"7\",H:\"8\",I:\"9\",J:\"*\",K:\"+\",M:\"-\",N:\".\",O:\"/\",\"`\":\"0\",\"\\x90\":\"NumLock\"},eB={alt:n=>n.altKey,control:n=>n.ctrlKey,meta:n=>n.metaKey,shift:n=>n.shiftKey};let tB=(()=>{class n extends ED{constructor(e){super(e)}supports(e){return null!=n.parseEventName(e)}addEventListener(e,i,r){const s=n.parseEventName(i),o=n.eventCallback(s.fullKey,r,this.manager.getZone());return this.manager.getZone().runOutsideAngular(()=>mi().onAndCancel(e,s.domEventName,o))}static parseEventName(e){const i=e.toLowerCase().split(\".\"),r=i.shift();if(0===i.length||\"keydown\"!==r&&\"keyup\"!==r)return null;const s=n._normalizeKey(i.pop());let o=\"\";if(OD.forEach(l=>{const c=i.indexOf(l);c>-1&&(i.splice(c,1),o+=l+\".\")}),o+=s,0!=i.length||0===s.length)return null;const a={};return a.domEventName=r,a.fullKey=o,a}static getEventFullKey(e){let i=\"\",r=function nB(n){let t=n.key;if(null==t){if(t=n.keyIdentifier,null==t)return\"Unidentified\";t.startsWith(\"U+\")&&(t=String.fromCharCode(parseInt(t.substring(2),16)),3===n.location&&PD.hasOwnProperty(t)&&(t=PD[t]))}return JL[t]||t}(e);return r=r.toLowerCase(),\" \"===r?r=\"space\":\".\"===r&&(r=\"dot\"),OD.forEach(s=>{s!=r&&eB[s](e)&&(i+=s+\".\")}),i+=r,i}static eventCallback(e,i,r){return s=>{n.getEventFullKey(s)===e&&r.runGuarded(()=>i(s))}}static _normalizeKey(e){return\"esc\"===e?\"escape\":e}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const oB=H0(cN,\"browser\",[{provide:bc,useValue:wD},{provide:I0,useValue:function iB(){pf.makeCurrent(),ff.init()},multi:!0},{provide:ie,useFactory:function sB(){return function DT(n){Bu=n}(document),document},deps:[]}]),aB=[{provide:Jh,useValue:\"root\"},{provide:Mr,useFactory:function rB(){return new Mr},deps:[]},{provide:Nc,useClass:ZL,multi:!0,deps:[ie,ne,bc]},{provide:Nc,useClass:tB,multi:!0,deps:[ie]},{provide:Vc,useClass:Vc,deps:[Lc,wa,ga]},{provide:da,useExisting:Vc},{provide:SD,useExisting:wa},{provide:wa,useClass:wa,deps:[ie]},{provide:$p,useClass:$p,deps:[ne]},{provide:Lc,useClass:Lc,deps:[Nc,ne]},{provide:class LL{},useClass:UL,deps:[]}];let FD=(()=>{class n{constructor(e){if(e)throw new Error(\"BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.\")}static withServerTransition(e){return{ngModule:n,providers:[{provide:ga,useValue:e.appId},{provide:xD,useExisting:ga},zL]}}}return n.\\u0275fac=function(e){return new(e||n)(y(n,12))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:aB,imports:[bt,dN]}),n})();function q(...n){return mt(n,So(n))}\"undefined\"!=typeof window&&window;class Zt extends O{constructor(t){super(),this._value=t}get value(){return this.getValue()}_subscribe(t){const e=super._subscribe(t);return!e.closed&&t.next(this._value),e}getValue(){const{hasError:t,thrownError:e,_value:i}=this;if(t)throw e;return this._throwIfClosed(),i}next(t){super.next(this._value=t)}}const{isArray:vB}=Array,{getPrototypeOf:yB,prototype:bB,keys:CB}=Object;function VD(n){if(1===n.length){const t=n[0];if(vB(t))return{args:t,keys:null};if(function DB(n){return n&&\"object\"==typeof n&&yB(n)===bB}(t)){const e=CB(t);return{args:e.map(i=>t[i]),keys:e}}}return{args:n,keys:null}}const{isArray:wB}=Array;function bf(n){return ue(t=>function MB(n,t){return wB(t)?n(...t):n(t)}(n,t))}function HD(n,t){return n.reduce((e,i,r)=>(e[i]=t[r],e),{})}function jD(n,t,e){n?Mi(e,n,t):t()}function Ma(n,t){const e=De(n)?n:()=>n,i=r=>r.error(e());return new Ve(t?r=>t.schedule(i,0,r):i)}const Hc=xo(n=>function(){n(this),this.name=\"EmptyError\",this.message=\"no elements in sequence\"});function jc(...n){return function SB(){return Eo(1)}()(mt(n,So(n)))}function xa(n){return new Ve(t=>{Jt(n()).subscribe(t)})}function zD(){return qe((n,t)=>{let e=null;n._refCount++;const i=Ue(t,void 0,void 0,void 0,()=>{if(!n||n._refCount<=0||0<--n._refCount)return void(e=null);const r=n._connection,s=e;e=null,r&&(!s||r===s)&&r.unsubscribe(),t.unsubscribe()});n.subscribe(i),i.closed||(e=n.connect())})}class kB extends Ve{constructor(t,e){super(),this.source=t,this.subjectFactory=e,this._subject=null,this._refCount=0,this._connection=null,o_(t)&&(this.lift=t.lift)}_subscribe(t){return this.getSubject().subscribe(t)}getSubject(){const t=this._subject;return(!t||t.isStopped)&&(this._subject=this.subjectFactory()),this._subject}_teardown(){this._refCount=0;const{_connection:t}=this;this._subject=this._connection=null,null==t||t.unsubscribe()}connect(){let t=this._connection;if(!t){t=this._connection=new ke;const e=this.getSubject();t.add(this.source.subscribe(Ue(e,void 0,()=>{this._teardown(),e.complete()},i=>{this._teardown(),e.error(i)},()=>this._teardown()))),t.closed&&(this._connection=null,t=ke.EMPTY)}return t}refCount(){return zD()(this)}}function kn(n,t){return qe((e,i)=>{let r=null,s=0,o=!1;const a=()=>o&&!r&&i.complete();e.subscribe(Ue(i,l=>{null==r||r.unsubscribe();let c=0;const d=s++;Jt(n(l,d)).subscribe(r=Ue(i,u=>i.next(t?t(l,u,d,c++):u),()=>{r=null,a()}))},()=>{o=!0,a()}))})}function Xn(...n){const t=So(n);return qe((e,i)=>{(t?jc(n,e,t):jc(n,e)).subscribe(i)})}function TB(n,t,e,i,r){return(s,o)=>{let a=e,l=t,c=0;s.subscribe(Ue(o,d=>{const u=c++;l=a?n(l,d,u):(a=!0,d),i&&o.next(l)},r&&(()=>{a&&o.next(l),o.complete()})))}}function UD(n,t){return qe(TB(n,t,arguments.length>=2,!0))}function Ct(n,t){return qe((e,i)=>{let r=0;e.subscribe(Ue(i,s=>n.call(t,s,r++)&&i.next(s)))})}function Ni(n){return qe((t,e)=>{let s,i=null,r=!1;i=t.subscribe(Ue(e,void 0,void 0,o=>{s=Jt(n(o,Ni(n)(t))),i?(i.unsubscribe(),i=null,s.subscribe(e)):r=!0})),r&&(i.unsubscribe(),i=null,s.subscribe(e))})}function Qs(n,t){return De(t)?lt(n,t,1):lt(n,1)}function Cf(n){return n<=0?()=>ri:qe((t,e)=>{let i=[];t.subscribe(Ue(e,r=>{i.push(r),n<i.length&&i.shift()},()=>{for(const r of i)e.next(r);e.complete()},void 0,()=>{i=null}))})}function $D(n=AB){return qe((t,e)=>{let i=!1;t.subscribe(Ue(e,r=>{i=!0,e.next(r)},()=>i?e.complete():e.error(n())))})}function AB(){return new Hc}function GD(n){return qe((t,e)=>{let i=!1;t.subscribe(Ue(e,r=>{i=!0,e.next(r)},()=>{i||e.next(n),e.complete()}))})}function Ks(n,t){const e=arguments.length>=2;return i=>i.pipe(n?Ct((r,s)=>n(r,s,i)):Wi,it(1),e?GD(t):$D(()=>new Hc))}function Mt(n,t,e){const i=De(n)||t||e?{next:n,error:t,complete:e}:n;return i?qe((r,s)=>{var o;null===(o=i.subscribe)||void 0===o||o.call(i);let a=!0;r.subscribe(Ue(s,l=>{var c;null===(c=i.next)||void 0===c||c.call(i,l),s.next(l)},()=>{var l;a=!1,null===(l=i.complete)||void 0===l||l.call(i),s.complete()},l=>{var c;a=!1,null===(c=i.error)||void 0===c||c.call(i,l),s.error(l)},()=>{var l,c;a&&(null===(l=i.unsubscribe)||void 0===l||l.call(i)),null===(c=i.finalize)||void 0===c||c.call(i)}))}):Wi}class Li{constructor(t,e){this.id=t,this.url=e}}class Df extends Li{constructor(t,e,i=\"imperative\",r=null){super(t,e),this.navigationTrigger=i,this.restoredState=r}toString(){return`NavigationStart(id: ${this.id}, url: '${this.url}')`}}class Ea extends Li{constructor(t,e,i){super(t,e),this.urlAfterRedirects=i}toString(){return`NavigationEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}')`}}class qD extends Li{constructor(t,e,i){super(t,e),this.reason=i}toString(){return`NavigationCancel(id: ${this.id}, url: '${this.url}')`}}class RB extends Li{constructor(t,e,i){super(t,e),this.error=i}toString(){return`NavigationError(id: ${this.id}, url: '${this.url}', error: ${this.error})`}}class OB extends Li{constructor(t,e,i,r){super(t,e),this.urlAfterRedirects=i,this.state=r}toString(){return`RoutesRecognized(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`}}class PB extends Li{constructor(t,e,i,r){super(t,e),this.urlAfterRedirects=i,this.state=r}toString(){return`GuardsCheckStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`}}class FB extends Li{constructor(t,e,i,r,s){super(t,e),this.urlAfterRedirects=i,this.state=r,this.shouldActivate=s}toString(){return`GuardsCheckEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state}, shouldActivate: ${this.shouldActivate})`}}class NB extends Li{constructor(t,e,i,r){super(t,e),this.urlAfterRedirects=i,this.state=r}toString(){return`ResolveStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`}}class LB extends Li{constructor(t,e,i,r){super(t,e),this.urlAfterRedirects=i,this.state=r}toString(){return`ResolveEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`}}class YD{constructor(t){this.route=t}toString(){return`RouteConfigLoadStart(path: ${this.route.path})`}}class QD{constructor(t){this.route=t}toString(){return`RouteConfigLoadEnd(path: ${this.route.path})`}}class BB{constructor(t){this.snapshot=t}toString(){return`ChildActivationStart(path: '${this.snapshot.routeConfig&&this.snapshot.routeConfig.path||\"\"}')`}}class VB{constructor(t){this.snapshot=t}toString(){return`ChildActivationEnd(path: '${this.snapshot.routeConfig&&this.snapshot.routeConfig.path||\"\"}')`}}class HB{constructor(t){this.snapshot=t}toString(){return`ActivationStart(path: '${this.snapshot.routeConfig&&this.snapshot.routeConfig.path||\"\"}')`}}class jB{constructor(t){this.snapshot=t}toString(){return`ActivationEnd(path: '${this.snapshot.routeConfig&&this.snapshot.routeConfig.path||\"\"}')`}}class KD{constructor(t,e,i){this.routerEvent=t,this.position=e,this.anchor=i}toString(){return`Scroll(anchor: '${this.anchor}', position: '${this.position?`${this.position[0]}, ${this.position[1]}`:null}')`}}const me=\"primary\";class zB{constructor(t){this.params=t||{}}has(t){return Object.prototype.hasOwnProperty.call(this.params,t)}get(t){if(this.has(t)){const e=this.params[t];return Array.isArray(e)?e[0]:e}return null}getAll(t){if(this.has(t)){const e=this.params[t];return Array.isArray(e)?e:[e]}return[]}get keys(){return Object.keys(this.params)}}function Zs(n){return new zB(n)}const ZD=\"ngNavigationCancelingError\";function wf(n){const t=Error(\"NavigationCancelingError: \"+n);return t[ZD]=!0,t}function $B(n,t,e){const i=e.path.split(\"/\");if(i.length>n.length||\"full\"===e.pathMatch&&(t.hasChildren()||i.length<n.length))return null;const r={};for(let s=0;s<i.length;s++){const o=i[s],a=n[s];if(o.startsWith(\":\"))r[o.substring(1)]=a;else if(o!==a.path)return null}return{consumed:n.slice(0,i.length),posParams:r}}function gi(n,t){const e=n?Object.keys(n):void 0,i=t?Object.keys(t):void 0;if(!e||!i||e.length!=i.length)return!1;let r;for(let s=0;s<e.length;s++)if(r=e[s],!XD(n[r],t[r]))return!1;return!0}function XD(n,t){if(Array.isArray(n)&&Array.isArray(t)){if(n.length!==t.length)return!1;const e=[...n].sort(),i=[...t].sort();return e.every((r,s)=>i[s]===r)}return n===t}function JD(n){return Array.prototype.concat.apply([],n)}function ew(n){return n.length>0?n[n.length-1]:null}function At(n,t){for(const e in n)n.hasOwnProperty(e)&&t(n[e],e)}function _i(n){return up(n)?n:ra(n)?mt(Promise.resolve(n)):q(n)}const qB={exact:function iw(n,t,e){if(!Nr(n.segments,t.segments)||!zc(n.segments,t.segments,e)||n.numberOfChildren!==t.numberOfChildren)return!1;for(const i in t.children)if(!n.children[i]||!iw(n.children[i],t.children[i],e))return!1;return!0},subset:rw},tw={exact:function YB(n,t){return gi(n,t)},subset:function QB(n,t){return Object.keys(t).length<=Object.keys(n).length&&Object.keys(t).every(e=>XD(n[e],t[e]))},ignored:()=>!0};function nw(n,t,e){return qB[e.paths](n.root,t.root,e.matrixParams)&&tw[e.queryParams](n.queryParams,t.queryParams)&&!(\"exact\"===e.fragment&&n.fragment!==t.fragment)}function rw(n,t,e){return sw(n,t,t.segments,e)}function sw(n,t,e,i){if(n.segments.length>e.length){const r=n.segments.slice(0,e.length);return!(!Nr(r,e)||t.hasChildren()||!zc(r,e,i))}if(n.segments.length===e.length){if(!Nr(n.segments,e)||!zc(n.segments,e,i))return!1;for(const r in t.children)if(!n.children[r]||!rw(n.children[r],t.children[r],i))return!1;return!0}{const r=e.slice(0,n.segments.length),s=e.slice(n.segments.length);return!!(Nr(n.segments,r)&&zc(n.segments,r,i)&&n.children[me])&&sw(n.children[me],t,s,i)}}function zc(n,t,e){return t.every((i,r)=>tw[e](n[r].parameters,i.parameters))}class Fr{constructor(t,e,i){this.root=t,this.queryParams=e,this.fragment=i}get queryParamMap(){return this._queryParamMap||(this._queryParamMap=Zs(this.queryParams)),this._queryParamMap}toString(){return XB.serialize(this)}}class ye{constructor(t,e){this.segments=t,this.children=e,this.parent=null,At(e,(i,r)=>i.parent=this)}hasChildren(){return this.numberOfChildren>0}get numberOfChildren(){return Object.keys(this.children).length}toString(){return Uc(this)}}class Sa{constructor(t,e){this.path=t,this.parameters=e}get parameterMap(){return this._parameterMap||(this._parameterMap=Zs(this.parameters)),this._parameterMap}toString(){return dw(this)}}function Nr(n,t){return n.length===t.length&&n.every((e,i)=>e.path===t[i].path)}class ow{}class aw{parse(t){const e=new aV(t);return new Fr(e.parseRootSegment(),e.parseQueryParams(),e.parseFragment())}serialize(t){const e=`/${ka(t.root,!0)}`,i=function tV(n){const t=Object.keys(n).map(e=>{const i=n[e];return Array.isArray(i)?i.map(r=>`${$c(e)}=${$c(r)}`).join(\"&\"):`${$c(e)}=${$c(i)}`}).filter(e=>!!e);return t.length?`?${t.join(\"&\")}`:\"\"}(t.queryParams);return`${e}${i}${\"string\"==typeof t.fragment?`#${function JB(n){return encodeURI(n)}(t.fragment)}`:\"\"}`}}const XB=new aw;function Uc(n){return n.segments.map(t=>dw(t)).join(\"/\")}function ka(n,t){if(!n.hasChildren())return Uc(n);if(t){const e=n.children[me]?ka(n.children[me],!1):\"\",i=[];return At(n.children,(r,s)=>{s!==me&&i.push(`${s}:${ka(r,!1)}`)}),i.length>0?`${e}(${i.join(\"//\")})`:e}{const e=function ZB(n,t){let e=[];return At(n.children,(i,r)=>{r===me&&(e=e.concat(t(i,r)))}),At(n.children,(i,r)=>{r!==me&&(e=e.concat(t(i,r)))}),e}(n,(i,r)=>r===me?[ka(n.children[me],!1)]:[`${r}:${ka(i,!1)}`]);return 1===Object.keys(n.children).length&&null!=n.children[me]?`${Uc(n)}/${e[0]}`:`${Uc(n)}/(${e.join(\"//\")})`}}function lw(n){return encodeURIComponent(n).replace(/%40/g,\"@\").replace(/%3A/gi,\":\").replace(/%24/g,\"$\").replace(/%2C/gi,\",\")}function $c(n){return lw(n).replace(/%3B/gi,\";\")}function Mf(n){return lw(n).replace(/\\(/g,\"%28\").replace(/\\)/g,\"%29\").replace(/%26/gi,\"&\")}function Gc(n){return decodeURIComponent(n)}function cw(n){return Gc(n.replace(/\\+/g,\"%20\"))}function dw(n){return`${Mf(n.path)}${function eV(n){return Object.keys(n).map(t=>`;${Mf(t)}=${Mf(n[t])}`).join(\"\")}(n.parameters)}`}const nV=/^[^\\/()?;=#]+/;function Wc(n){const t=n.match(nV);return t?t[0]:\"\"}const iV=/^[^=?&#]+/,sV=/^[^&#]+/;class aV{constructor(t){this.url=t,this.remaining=t}parseRootSegment(){return this.consumeOptional(\"/\"),\"\"===this.remaining||this.peekStartsWith(\"?\")||this.peekStartsWith(\"#\")?new ye([],{}):new ye([],this.parseChildren())}parseQueryParams(){const t={};if(this.consumeOptional(\"?\"))do{this.parseQueryParam(t)}while(this.consumeOptional(\"&\"));return t}parseFragment(){return this.consumeOptional(\"#\")?decodeURIComponent(this.remaining):null}parseChildren(){if(\"\"===this.remaining)return{};this.consumeOptional(\"/\");const t=[];for(this.peekStartsWith(\"(\")||t.push(this.parseSegment());this.peekStartsWith(\"/\")&&!this.peekStartsWith(\"//\")&&!this.peekStartsWith(\"/(\");)this.capture(\"/\"),t.push(this.parseSegment());let e={};this.peekStartsWith(\"/(\")&&(this.capture(\"/\"),e=this.parseParens(!0));let i={};return this.peekStartsWith(\"(\")&&(i=this.parseParens(!1)),(t.length>0||Object.keys(e).length>0)&&(i[me]=new ye(t,e)),i}parseSegment(){const t=Wc(this.remaining);if(\"\"===t&&this.peekStartsWith(\";\"))throw new Error(`Empty path url segment cannot have parameters: '${this.remaining}'.`);return this.capture(t),new Sa(Gc(t),this.parseMatrixParams())}parseMatrixParams(){const t={};for(;this.consumeOptional(\";\");)this.parseParam(t);return t}parseParam(t){const e=Wc(this.remaining);if(!e)return;this.capture(e);let i=\"\";if(this.consumeOptional(\"=\")){const r=Wc(this.remaining);r&&(i=r,this.capture(i))}t[Gc(e)]=Gc(i)}parseQueryParam(t){const e=function rV(n){const t=n.match(iV);return t?t[0]:\"\"}(this.remaining);if(!e)return;this.capture(e);let i=\"\";if(this.consumeOptional(\"=\")){const o=function oV(n){const t=n.match(sV);return t?t[0]:\"\"}(this.remaining);o&&(i=o,this.capture(i))}const r=cw(e),s=cw(i);if(t.hasOwnProperty(r)){let o=t[r];Array.isArray(o)||(o=[o],t[r]=o),o.push(s)}else t[r]=s}parseParens(t){const e={};for(this.capture(\"(\");!this.consumeOptional(\")\")&&this.remaining.length>0;){const i=Wc(this.remaining),r=this.remaining[i.length];if(\"/\"!==r&&\")\"!==r&&\";\"!==r)throw new Error(`Cannot parse url '${this.url}'`);let s;i.indexOf(\":\")>-1?(s=i.substr(0,i.indexOf(\":\")),this.capture(s),this.capture(\":\")):t&&(s=me);const o=this.parseChildren();e[s]=1===Object.keys(o).length?o[me]:new ye([],o),this.consumeOptional(\"//\")}return e}peekStartsWith(t){return this.remaining.startsWith(t)}consumeOptional(t){return!!this.peekStartsWith(t)&&(this.remaining=this.remaining.substring(t.length),!0)}capture(t){if(!this.consumeOptional(t))throw new Error(`Expected \"${t}\".`)}}class uw{constructor(t){this._root=t}get root(){return this._root.value}parent(t){const e=this.pathFromRoot(t);return e.length>1?e[e.length-2]:null}children(t){const e=xf(t,this._root);return e?e.children.map(i=>i.value):[]}firstChild(t){const e=xf(t,this._root);return e&&e.children.length>0?e.children[0].value:null}siblings(t){const e=Ef(t,this._root);return e.length<2?[]:e[e.length-2].children.map(r=>r.value).filter(r=>r!==t)}pathFromRoot(t){return Ef(t,this._root).map(e=>e.value)}}function xf(n,t){if(n===t.value)return t;for(const e of t.children){const i=xf(n,e);if(i)return i}return null}function Ef(n,t){if(n===t.value)return[t];for(const e of t.children){const i=Ef(n,e);if(i.length)return i.unshift(t),i}return[]}class Bi{constructor(t,e){this.value=t,this.children=e}toString(){return`TreeNode(${this.value})`}}function Xs(n){const t={};return n&&n.children.forEach(e=>t[e.value.outlet]=e),t}class hw extends uw{constructor(t,e){super(t),this.snapshot=e,Sf(this,t)}toString(){return this.snapshot.toString()}}function pw(n,t){const e=function lV(n,t){const o=new qc([],{},{},\"\",{},me,t,null,n.root,-1,{});return new mw(\"\",new Bi(o,[]))}(n,t),i=new Zt([new Sa(\"\",{})]),r=new Zt({}),s=new Zt({}),o=new Zt({}),a=new Zt(\"\"),l=new Js(i,r,o,a,s,me,t,e.root);return l.snapshot=e.root,new hw(new Bi(l,[]),e)}class Js{constructor(t,e,i,r,s,o,a,l){this.url=t,this.params=e,this.queryParams=i,this.fragment=r,this.data=s,this.outlet=o,this.component=a,this._futureSnapshot=l}get routeConfig(){return this._futureSnapshot.routeConfig}get root(){return this._routerState.root}get parent(){return this._routerState.parent(this)}get firstChild(){return this._routerState.firstChild(this)}get children(){return this._routerState.children(this)}get pathFromRoot(){return this._routerState.pathFromRoot(this)}get paramMap(){return this._paramMap||(this._paramMap=this.params.pipe(ue(t=>Zs(t)))),this._paramMap}get queryParamMap(){return this._queryParamMap||(this._queryParamMap=this.queryParams.pipe(ue(t=>Zs(t)))),this._queryParamMap}toString(){return this.snapshot?this.snapshot.toString():`Future(${this._futureSnapshot})`}}function fw(n,t=\"emptyOnly\"){const e=n.pathFromRoot;let i=0;if(\"always\"!==t)for(i=e.length-1;i>=1;){const r=e[i],s=e[i-1];if(r.routeConfig&&\"\"===r.routeConfig.path)i--;else{if(s.component)break;i--}}return function cV(n){return n.reduce((t,e)=>({params:Object.assign(Object.assign({},t.params),e.params),data:Object.assign(Object.assign({},t.data),e.data),resolve:Object.assign(Object.assign({},t.resolve),e._resolvedData)}),{params:{},data:{},resolve:{}})}(e.slice(i))}class qc{constructor(t,e,i,r,s,o,a,l,c,d,u){this.url=t,this.params=e,this.queryParams=i,this.fragment=r,this.data=s,this.outlet=o,this.component=a,this.routeConfig=l,this._urlSegment=c,this._lastPathIndex=d,this._resolve=u}get root(){return this._routerState.root}get parent(){return this._routerState.parent(this)}get firstChild(){return this._routerState.firstChild(this)}get children(){return this._routerState.children(this)}get pathFromRoot(){return this._routerState.pathFromRoot(this)}get paramMap(){return this._paramMap||(this._paramMap=Zs(this.params)),this._paramMap}get queryParamMap(){return this._queryParamMap||(this._queryParamMap=Zs(this.queryParams)),this._queryParamMap}toString(){return`Route(url:'${this.url.map(i=>i.toString()).join(\"/\")}', path:'${this.routeConfig?this.routeConfig.path:\"\"}')`}}class mw extends uw{constructor(t,e){super(e),this.url=t,Sf(this,e)}toString(){return gw(this._root)}}function Sf(n,t){t.value._routerState=n,t.children.forEach(e=>Sf(n,e))}function gw(n){const t=n.children.length>0?` { ${n.children.map(gw).join(\", \")} } `:\"\";return`${n.value}${t}`}function kf(n){if(n.snapshot){const t=n.snapshot,e=n._futureSnapshot;n.snapshot=e,gi(t.queryParams,e.queryParams)||n.queryParams.next(e.queryParams),t.fragment!==e.fragment&&n.fragment.next(e.fragment),gi(t.params,e.params)||n.params.next(e.params),function GB(n,t){if(n.length!==t.length)return!1;for(let e=0;e<n.length;++e)if(!gi(n[e],t[e]))return!1;return!0}(t.url,e.url)||n.url.next(e.url),gi(t.data,e.data)||n.data.next(e.data)}else n.snapshot=n._futureSnapshot,n.data.next(n._futureSnapshot.data)}function Tf(n,t){const e=gi(n.params,t.params)&&function KB(n,t){return Nr(n,t)&&n.every((e,i)=>gi(e.parameters,t[i].parameters))}(n.url,t.url);return e&&!(!n.parent!=!t.parent)&&(!n.parent||Tf(n.parent,t.parent))}function Ta(n,t,e){if(e&&n.shouldReuseRoute(t.value,e.value.snapshot)){const i=e.value;i._futureSnapshot=t.value;const r=function uV(n,t,e){return t.children.map(i=>{for(const r of e.children)if(n.shouldReuseRoute(i.value,r.value.snapshot))return Ta(n,i,r);return Ta(n,i)})}(n,t,e);return new Bi(i,r)}{if(n.shouldAttach(t.value)){const s=n.retrieve(t.value);if(null!==s){const o=s.route;return o.value._futureSnapshot=t.value,o.children=t.children.map(a=>Ta(n,a)),o}}const i=function hV(n){return new Js(new Zt(n.url),new Zt(n.params),new Zt(n.queryParams),new Zt(n.fragment),new Zt(n.data),n.outlet,n.component,n)}(t.value),r=t.children.map(s=>Ta(n,s));return new Bi(i,r)}}function Yc(n){return\"object\"==typeof n&&null!=n&&!n.outlets&&!n.segmentPath}function Aa(n){return\"object\"==typeof n&&null!=n&&n.outlets}function Af(n,t,e,i,r){let s={};if(i&&At(i,(a,l)=>{s[l]=Array.isArray(a)?a.map(c=>`${c}`):`${a}`}),n===t)return new Fr(e,s,r);const o=_w(n,t,e);return new Fr(o,s,r)}function _w(n,t,e){const i={};return At(n.children,(r,s)=>{i[s]=r===t?e:_w(r,t,e)}),new ye(n.segments,i)}class vw{constructor(t,e,i){if(this.isAbsolute=t,this.numberOfDoubleDots=e,this.commands=i,t&&i.length>0&&Yc(i[0]))throw new Error(\"Root segment cannot have matrix parameters\");const r=i.find(Aa);if(r&&r!==ew(i))throw new Error(\"{outlets:{}} has to be the last command\")}toRoot(){return this.isAbsolute&&1===this.commands.length&&\"/\"==this.commands[0]}}class If{constructor(t,e,i){this.segmentGroup=t,this.processChildren=e,this.index=i}}function yw(n,t,e){if(n||(n=new ye([],{})),0===n.segments.length&&n.hasChildren())return Qc(n,t,e);const i=function vV(n,t,e){let i=0,r=t;const s={match:!1,pathIndex:0,commandIndex:0};for(;r<n.segments.length;){if(i>=e.length)return s;const o=n.segments[r],a=e[i];if(Aa(a))break;const l=`${a}`,c=i<e.length-1?e[i+1]:null;if(r>0&&void 0===l)break;if(l&&c&&\"object\"==typeof c&&void 0===c.outlets){if(!Cw(l,c,o))return s;i+=2}else{if(!Cw(l,{},o))return s;i++}r++}return{match:!0,pathIndex:r,commandIndex:i}}(n,t,e),r=e.slice(i.commandIndex);if(i.match&&i.pathIndex<n.segments.length){const s=new ye(n.segments.slice(0,i.pathIndex),{});return s.children[me]=new ye(n.segments.slice(i.pathIndex),n.children),Qc(s,0,r)}return i.match&&0===r.length?new ye(n.segments,{}):i.match&&!n.hasChildren()?Rf(n,t,e):i.match?Qc(n,0,r):Rf(n,t,e)}function Qc(n,t,e){if(0===e.length)return new ye(n.segments,{});{const i=function _V(n){return Aa(n[0])?n[0].outlets:{[me]:n}}(e),r={};return At(i,(s,o)=>{\"string\"==typeof s&&(s=[s]),null!==s&&(r[o]=yw(n.children[o],t,s))}),At(n.children,(s,o)=>{void 0===i[o]&&(r[o]=s)}),new ye(n.segments,r)}}function Rf(n,t,e){const i=n.segments.slice(0,t);let r=0;for(;r<e.length;){const s=e[r];if(Aa(s)){const l=yV(s.outlets);return new ye(i,l)}if(0===r&&Yc(e[0])){i.push(new Sa(n.segments[t].path,bw(e[0]))),r++;continue}const o=Aa(s)?s.outlets[me]:`${s}`,a=r<e.length-1?e[r+1]:null;o&&a&&Yc(a)?(i.push(new Sa(o,bw(a))),r+=2):(i.push(new Sa(o,{})),r++)}return new ye(i,{})}function yV(n){const t={};return At(n,(e,i)=>{\"string\"==typeof e&&(e=[e]),null!==e&&(t[i]=Rf(new ye([],{}),0,e))}),t}function bw(n){const t={};return At(n,(e,i)=>t[i]=`${e}`),t}function Cw(n,t,e){return n==e.path&&gi(t,e.parameters)}class CV{constructor(t,e,i,r){this.routeReuseStrategy=t,this.futureState=e,this.currState=i,this.forwardEvent=r}activate(t){const e=this.futureState._root,i=this.currState?this.currState._root:null;this.deactivateChildRoutes(e,i,t),kf(this.futureState.root),this.activateChildRoutes(e,i,t)}deactivateChildRoutes(t,e,i){const r=Xs(e);t.children.forEach(s=>{const o=s.value.outlet;this.deactivateRoutes(s,r[o],i),delete r[o]}),At(r,(s,o)=>{this.deactivateRouteAndItsChildren(s,i)})}deactivateRoutes(t,e,i){const r=t.value,s=e?e.value:null;if(r===s)if(r.component){const o=i.getContext(r.outlet);o&&this.deactivateChildRoutes(t,e,o.children)}else this.deactivateChildRoutes(t,e,i);else s&&this.deactivateRouteAndItsChildren(e,i)}deactivateRouteAndItsChildren(t,e){t.value.component&&this.routeReuseStrategy.shouldDetach(t.value.snapshot)?this.detachAndStoreRouteSubtree(t,e):this.deactivateRouteAndOutlet(t,e)}detachAndStoreRouteSubtree(t,e){const i=e.getContext(t.value.outlet),r=i&&t.value.component?i.children:e,s=Xs(t);for(const o of Object.keys(s))this.deactivateRouteAndItsChildren(s[o],r);if(i&&i.outlet){const o=i.outlet.detach(),a=i.children.onOutletDeactivated();this.routeReuseStrategy.store(t.value.snapshot,{componentRef:o,route:t,contexts:a})}}deactivateRouteAndOutlet(t,e){const i=e.getContext(t.value.outlet),r=i&&t.value.component?i.children:e,s=Xs(t);for(const o of Object.keys(s))this.deactivateRouteAndItsChildren(s[o],r);i&&i.outlet&&(i.outlet.deactivate(),i.children.onOutletDeactivated(),i.attachRef=null,i.resolver=null,i.route=null)}activateChildRoutes(t,e,i){const r=Xs(e);t.children.forEach(s=>{this.activateRoutes(s,r[s.value.outlet],i),this.forwardEvent(new jB(s.value.snapshot))}),t.children.length&&this.forwardEvent(new VB(t.value.snapshot))}activateRoutes(t,e,i){const r=t.value,s=e?e.value:null;if(kf(r),r===s)if(r.component){const o=i.getOrCreateContext(r.outlet);this.activateChildRoutes(t,e,o.children)}else this.activateChildRoutes(t,e,i);else if(r.component){const o=i.getOrCreateContext(r.outlet);if(this.routeReuseStrategy.shouldAttach(r.snapshot)){const a=this.routeReuseStrategy.retrieve(r.snapshot);this.routeReuseStrategy.store(r.snapshot,null),o.children.onOutletReAttached(a.contexts),o.attachRef=a.componentRef,o.route=a.route.value,o.outlet&&o.outlet.attach(a.componentRef,a.route.value),kf(a.route.value),this.activateChildRoutes(t,null,o.children)}else{const a=function DV(n){for(let t=n.parent;t;t=t.parent){const e=t.routeConfig;if(e&&e._loadedConfig)return e._loadedConfig;if(e&&e.component)return null}return null}(r.snapshot),l=a?a.module.componentFactoryResolver:null;o.attachRef=null,o.route=r,o.resolver=l,o.outlet&&o.outlet.activateWith(r,l),this.activateChildRoutes(t,null,o.children)}}else this.activateChildRoutes(t,null,i)}}class Of{constructor(t,e){this.routes=t,this.module=e}}function nr(n){return\"function\"==typeof n}function Lr(n){return n instanceof Fr}const Ia=Symbol(\"INITIAL_VALUE\");function Ra(){return kn(n=>function xB(...n){const t=So(n),e=b_(n),{args:i,keys:r}=VD(n);if(0===i.length)return mt([],t);const s=new Ve(function EB(n,t,e=Wi){return i=>{jD(t,()=>{const{length:r}=n,s=new Array(r);let o=r,a=r;for(let l=0;l<r;l++)jD(t,()=>{const c=mt(n[l],t);let d=!1;c.subscribe(Ue(i,u=>{s[l]=u,d||(d=!0,a--),a||i.next(e(s.slice()))},()=>{--o||i.complete()}))},i)},i)}}(i,t,r?o=>HD(r,o):Wi));return e?s.pipe(bf(e)):s}(n.map(t=>t.pipe(it(1),Xn(Ia)))).pipe(UD((t,e)=>{let i=!1;return e.reduce((r,s,o)=>r!==Ia?r:(s===Ia&&(i=!0),i||!1!==s&&o!==e.length-1&&!Lr(s)?r:s),t)},Ia),Ct(t=>t!==Ia),ue(t=>Lr(t)?t:!0===t),it(1)))}class kV{constructor(){this.outlet=null,this.route=null,this.resolver=null,this.children=new Oa,this.attachRef=null}}class Oa{constructor(){this.contexts=new Map}onChildOutletCreated(t,e){const i=this.getOrCreateContext(t);i.outlet=e,this.contexts.set(t,i)}onChildOutletDestroyed(t){const e=this.getContext(t);e&&(e.outlet=null,e.attachRef=null)}onOutletDeactivated(){const t=this.contexts;return this.contexts=new Map,t}onOutletReAttached(t){this.contexts=t}getOrCreateContext(t){let e=this.getContext(t);return e||(e=new kV,this.contexts.set(t,e)),e}getContext(t){return this.contexts.get(t)||null}}let Pf=(()=>{class n{constructor(e,i,r,s,o){this.parentContexts=e,this.location=i,this.resolver=r,this.changeDetector=o,this.activated=null,this._activatedRoute=null,this.activateEvents=new $,this.deactivateEvents=new $,this.attachEvents=new $,this.detachEvents=new $,this.name=s||me,e.onChildOutletCreated(this.name,this)}ngOnDestroy(){this.parentContexts.onChildOutletDestroyed(this.name)}ngOnInit(){if(!this.activated){const e=this.parentContexts.getContext(this.name);e&&e.route&&(e.attachRef?this.attach(e.attachRef,e.route):this.activateWith(e.route,e.resolver||null))}}get isActivated(){return!!this.activated}get component(){if(!this.activated)throw new Error(\"Outlet is not activated\");return this.activated.instance}get activatedRoute(){if(!this.activated)throw new Error(\"Outlet is not activated\");return this._activatedRoute}get activatedRouteData(){return this._activatedRoute?this._activatedRoute.snapshot.data:{}}detach(){if(!this.activated)throw new Error(\"Outlet is not activated\");this.location.detach();const e=this.activated;return this.activated=null,this._activatedRoute=null,this.detachEvents.emit(e.instance),e}attach(e,i){this.activated=e,this._activatedRoute=i,this.location.insert(e.hostView),this.attachEvents.emit(e.instance)}deactivate(){if(this.activated){const e=this.component;this.activated.destroy(),this.activated=null,this._activatedRoute=null,this.deactivateEvents.emit(e)}}activateWith(e,i){if(this.isActivated)throw new Error(\"Cannot activate an already activated outlet\");this._activatedRoute=e;const o=(i=i||this.resolver).resolveComponentFactory(e._futureSnapshot.routeConfig.component),a=this.parentContexts.getOrCreateContext(this.name).children,l=new TV(e,a,this.location.injector);this.activated=this.location.createComponent(o,this.location.length,l),this.changeDetector.markForCheck(),this.activateEvents.emit(this.activated.instance)}}return n.\\u0275fac=function(e){return new(e||n)(f(Oa),f(st),f(Ir),kt(\"name\"),f(Ye))},n.\\u0275dir=C({type:n,selectors:[[\"router-outlet\"]],outputs:{activateEvents:\"activate\",deactivateEvents:\"deactivate\",attachEvents:\"attach\",detachEvents:\"detach\"},exportAs:[\"outlet\"]}),n})();class TV{constructor(t,e,i){this.route=t,this.childContexts=e,this.parent=i}get(t,e){return t===Js?this.route:t===Oa?this.childContexts:this.parent.get(t,e)}}let Dw=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275cmp=xe({type:n,selectors:[[\"ng-component\"]],decls:1,vars:0,template:function(e,i){1&e&&Le(0,\"router-outlet\")},directives:[Pf],encapsulation:2}),n})();function ww(n,t=\"\"){for(let e=0;e<n.length;e++){const i=n[e];AV(i,IV(t,i))}}function AV(n,t){n.children&&ww(n.children,t)}function IV(n,t){return t?n||t.path?n&&!t.path?`${n}/`:!n&&t.path?t.path:`${n}/${t.path}`:\"\":n}function Ff(n){const t=n.children&&n.children.map(Ff),e=t?Object.assign(Object.assign({},n),{children:t}):Object.assign({},n);return!e.component&&(t||e.loadChildren)&&e.outlet&&e.outlet!==me&&(e.component=Dw),e}function Tn(n){return n.outlet||me}function Mw(n,t){const e=n.filter(i=>Tn(i)===t);return e.push(...n.filter(i=>Tn(i)!==t)),e}const xw={matched:!1,consumedSegments:[],remainingSegments:[],parameters:{},positionalParamSegments:{}};function Kc(n,t,e){var i;if(\"\"===t.path)return\"full\"===t.pathMatch&&(n.hasChildren()||e.length>0)?Object.assign({},xw):{matched:!0,consumedSegments:[],remainingSegments:e,parameters:{},positionalParamSegments:{}};const s=(t.matcher||$B)(e,n,t);if(!s)return Object.assign({},xw);const o={};At(s.posParams,(l,c)=>{o[c]=l.path});const a=s.consumed.length>0?Object.assign(Object.assign({},o),s.consumed[s.consumed.length-1].parameters):o;return{matched:!0,consumedSegments:s.consumed,remainingSegments:e.slice(s.consumed.length),parameters:a,positionalParamSegments:null!==(i=s.posParams)&&void 0!==i?i:{}}}function Zc(n,t,e,i,r=\"corrected\"){if(e.length>0&&function PV(n,t,e){return e.some(i=>Xc(n,t,i)&&Tn(i)!==me)}(n,e,i)){const o=new ye(t,function OV(n,t,e,i){const r={};r[me]=i,i._sourceSegment=n,i._segmentIndexShift=t.length;for(const s of e)if(\"\"===s.path&&Tn(s)!==me){const o=new ye([],{});o._sourceSegment=n,o._segmentIndexShift=t.length,r[Tn(s)]=o}return r}(n,t,i,new ye(e,n.children)));return o._sourceSegment=n,o._segmentIndexShift=t.length,{segmentGroup:o,slicedSegments:[]}}if(0===e.length&&function FV(n,t,e){return e.some(i=>Xc(n,t,i))}(n,e,i)){const o=new ye(n.segments,function RV(n,t,e,i,r,s){const o={};for(const a of i)if(Xc(n,e,a)&&!r[Tn(a)]){const l=new ye([],{});l._sourceSegment=n,l._segmentIndexShift=\"legacy\"===s?n.segments.length:t.length,o[Tn(a)]=l}return Object.assign(Object.assign({},r),o)}(n,t,e,i,n.children,r));return o._sourceSegment=n,o._segmentIndexShift=t.length,{segmentGroup:o,slicedSegments:e}}const s=new ye(n.segments,n.children);return s._sourceSegment=n,s._segmentIndexShift=t.length,{segmentGroup:s,slicedSegments:e}}function Xc(n,t,e){return(!(n.hasChildren()||t.length>0)||\"full\"!==e.pathMatch)&&\"\"===e.path}function Ew(n,t,e,i){return!!(Tn(n)===i||i!==me&&Xc(t,e,n))&&(\"**\"===n.path||Kc(t,n,e).matched)}function Sw(n,t,e){return 0===t.length&&!n.children[e]}class Jc{constructor(t){this.segmentGroup=t||null}}class kw{constructor(t){this.urlTree=t}}function Pa(n){return Ma(new Jc(n))}function Tw(n){return Ma(new kw(n))}class VV{constructor(t,e,i,r,s){this.configLoader=e,this.urlSerializer=i,this.urlTree=r,this.config=s,this.allowRedirects=!0,this.ngModule=t.get(Ri)}apply(){const t=Zc(this.urlTree.root,[],[],this.config).segmentGroup,e=new ye(t.segments,t.children);return this.expandSegmentGroup(this.ngModule,this.config,e,me).pipe(ue(s=>this.createUrlTree(Nf(s),this.urlTree.queryParams,this.urlTree.fragment))).pipe(Ni(s=>{if(s instanceof kw)return this.allowRedirects=!1,this.match(s.urlTree);throw s instanceof Jc?this.noMatchError(s):s}))}match(t){return this.expandSegmentGroup(this.ngModule,this.config,t.root,me).pipe(ue(r=>this.createUrlTree(Nf(r),t.queryParams,t.fragment))).pipe(Ni(r=>{throw r instanceof Jc?this.noMatchError(r):r}))}noMatchError(t){return new Error(`Cannot match any routes. URL Segment: '${t.segmentGroup}'`)}createUrlTree(t,e,i){const r=t.segments.length>0?new ye([],{[me]:t}):t;return new Fr(r,e,i)}expandSegmentGroup(t,e,i,r){return 0===i.segments.length&&i.hasChildren()?this.expandChildren(t,e,i).pipe(ue(s=>new ye([],s))):this.expandSegment(t,i,e,i.segments,r,!0)}expandChildren(t,e,i){const r=[];for(const s of Object.keys(i.children))\"primary\"===s?r.unshift(s):r.push(s);return mt(r).pipe(Qs(s=>{const o=i.children[s],a=Mw(e,s);return this.expandSegmentGroup(t,a,o,s).pipe(ue(l=>({segment:l,outlet:s})))}),UD((s,o)=>(s[o.outlet]=o.segment,s),{}),function IB(n,t){const e=arguments.length>=2;return i=>i.pipe(n?Ct((r,s)=>n(r,s,i)):Wi,Cf(1),e?GD(t):$D(()=>new Hc))}())}expandSegment(t,e,i,r,s,o){return mt(i).pipe(Qs(a=>this.expandSegmentAgainstRoute(t,e,i,a,r,s,o).pipe(Ni(c=>{if(c instanceof Jc)return q(null);throw c}))),Ks(a=>!!a),Ni((a,l)=>{if(a instanceof Hc||\"EmptyError\"===a.name)return Sw(e,r,s)?q(new ye([],{})):Pa(e);throw a}))}expandSegmentAgainstRoute(t,e,i,r,s,o,a){return Ew(r,e,s,o)?void 0===r.redirectTo?this.matchSegmentAgainstRoute(t,e,r,s,o):a&&this.allowRedirects?this.expandSegmentAgainstRouteUsingRedirect(t,e,i,r,s,o):Pa(e):Pa(e)}expandSegmentAgainstRouteUsingRedirect(t,e,i,r,s,o){return\"**\"===r.path?this.expandWildCardWithParamsAgainstRouteUsingRedirect(t,i,r,o):this.expandRegularSegmentAgainstRouteUsingRedirect(t,e,i,r,s,o)}expandWildCardWithParamsAgainstRouteUsingRedirect(t,e,i,r){const s=this.applyRedirectCommands([],i.redirectTo,{});return i.redirectTo.startsWith(\"/\")?Tw(s):this.lineralizeSegments(i,s).pipe(lt(o=>{const a=new ye(o,{});return this.expandSegment(t,a,e,o,r,!1)}))}expandRegularSegmentAgainstRouteUsingRedirect(t,e,i,r,s,o){const{matched:a,consumedSegments:l,remainingSegments:c,positionalParamSegments:d}=Kc(e,r,s);if(!a)return Pa(e);const u=this.applyRedirectCommands(l,r.redirectTo,d);return r.redirectTo.startsWith(\"/\")?Tw(u):this.lineralizeSegments(r,u).pipe(lt(h=>this.expandSegment(t,e,i,h.concat(c),o,!1)))}matchSegmentAgainstRoute(t,e,i,r,s){if(\"**\"===i.path)return i.loadChildren?(i._loadedConfig?q(i._loadedConfig):this.configLoader.load(t.injector,i)).pipe(ue(u=>(i._loadedConfig=u,new ye(r,{})))):q(new ye(r,{}));const{matched:o,consumedSegments:a,remainingSegments:l}=Kc(e,i,r);return o?this.getChildConfig(t,i,r).pipe(lt(d=>{const u=d.module,h=d.routes,{segmentGroup:p,slicedSegments:m}=Zc(e,a,l,h),g=new ye(p.segments,p.children);if(0===m.length&&g.hasChildren())return this.expandChildren(u,h,g).pipe(ue(M=>new ye(a,M)));if(0===h.length&&0===m.length)return q(new ye(a,{}));const _=Tn(i)===s;return this.expandSegment(u,g,h,m,_?me:s,!0).pipe(ue(v=>new ye(a.concat(v.segments),v.children)))})):Pa(e)}getChildConfig(t,e,i){return e.children?q(new Of(e.children,t)):e.loadChildren?void 0!==e._loadedConfig?q(e._loadedConfig):this.runCanLoadGuards(t.injector,e,i).pipe(lt(r=>r?this.configLoader.load(t.injector,e).pipe(ue(s=>(e._loadedConfig=s,s))):function LV(n){return Ma(wf(`Cannot load children because the guard of the route \"path: '${n.path}'\" returned false`))}(e))):q(new Of([],t))}runCanLoadGuards(t,e,i){const r=e.canLoad;return r&&0!==r.length?q(r.map(o=>{const a=t.get(o);let l;if(function MV(n){return n&&nr(n.canLoad)}(a))l=a.canLoad(e,i);else{if(!nr(a))throw new Error(\"Invalid CanLoad guard\");l=a(e,i)}return _i(l)})).pipe(Ra(),Mt(o=>{if(!Lr(o))return;const a=wf(`Redirecting to \"${this.urlSerializer.serialize(o)}\"`);throw a.url=o,a}),ue(o=>!0===o)):q(!0)}lineralizeSegments(t,e){let i=[],r=e.root;for(;;){if(i=i.concat(r.segments),0===r.numberOfChildren)return q(i);if(r.numberOfChildren>1||!r.children[me])return Ma(new Error(`Only absolute redirects can have named outlets. redirectTo: '${t.redirectTo}'`));r=r.children[me]}}applyRedirectCommands(t,e,i){return this.applyRedirectCreatreUrlTree(e,this.urlSerializer.parse(e),t,i)}applyRedirectCreatreUrlTree(t,e,i,r){const s=this.createSegmentGroup(t,e.root,i,r);return new Fr(s,this.createQueryParams(e.queryParams,this.urlTree.queryParams),e.fragment)}createQueryParams(t,e){const i={};return At(t,(r,s)=>{if(\"string\"==typeof r&&r.startsWith(\":\")){const a=r.substring(1);i[s]=e[a]}else i[s]=r}),i}createSegmentGroup(t,e,i,r){const s=this.createSegments(t,e.segments,i,r);let o={};return At(e.children,(a,l)=>{o[l]=this.createSegmentGroup(t,a,i,r)}),new ye(s,o)}createSegments(t,e,i,r){return e.map(s=>s.path.startsWith(\":\")?this.findPosParam(t,s,r):this.findOrReturn(s,i))}findPosParam(t,e,i){const r=i[e.path.substring(1)];if(!r)throw new Error(`Cannot redirect to '${t}'. Cannot find '${e.path}'.`);return r}findOrReturn(t,e){let i=0;for(const r of e){if(r.path===t.path)return e.splice(i),r;i++}return t}}function Nf(n){const t={};for(const i of Object.keys(n.children)){const s=Nf(n.children[i]);(s.segments.length>0||s.hasChildren())&&(t[i]=s)}return function HV(n){if(1===n.numberOfChildren&&n.children[me]){const t=n.children[me];return new ye(n.segments.concat(t.segments),t.children)}return n}(new ye(n.segments,t))}class Aw{constructor(t){this.path=t,this.route=this.path[this.path.length-1]}}class ed{constructor(t,e){this.component=t,this.route=e}}function zV(n,t,e){const i=n._root;return Fa(i,t?t._root:null,e,[i.value])}function td(n,t,e){const i=function $V(n){if(!n)return null;for(let t=n.parent;t;t=t.parent){const e=t.routeConfig;if(e&&e._loadedConfig)return e._loadedConfig}return null}(t);return(i?i.module.injector:e).get(n)}function Fa(n,t,e,i,r={canDeactivateChecks:[],canActivateChecks:[]}){const s=Xs(t);return n.children.forEach(o=>{(function GV(n,t,e,i,r={canDeactivateChecks:[],canActivateChecks:[]}){const s=n.value,o=t?t.value:null,a=e?e.getContext(n.value.outlet):null;if(o&&s.routeConfig===o.routeConfig){const l=function WV(n,t,e){if(\"function\"==typeof e)return e(n,t);switch(e){case\"pathParamsChange\":return!Nr(n.url,t.url);case\"pathParamsOrQueryParamsChange\":return!Nr(n.url,t.url)||!gi(n.queryParams,t.queryParams);case\"always\":return!0;case\"paramsOrQueryParamsChange\":return!Tf(n,t)||!gi(n.queryParams,t.queryParams);default:return!Tf(n,t)}}(o,s,s.routeConfig.runGuardsAndResolvers);l?r.canActivateChecks.push(new Aw(i)):(s.data=o.data,s._resolvedData=o._resolvedData),Fa(n,t,s.component?a?a.children:null:e,i,r),l&&a&&a.outlet&&a.outlet.isActivated&&r.canDeactivateChecks.push(new ed(a.outlet.component,o))}else o&&Na(t,a,r),r.canActivateChecks.push(new Aw(i)),Fa(n,null,s.component?a?a.children:null:e,i,r)})(o,s[o.value.outlet],e,i.concat([o.value]),r),delete s[o.value.outlet]}),At(s,(o,a)=>Na(o,e.getContext(a),r)),r}function Na(n,t,e){const i=Xs(n),r=n.value;At(i,(s,o)=>{Na(s,r.component?t?t.children.getContext(o):null:t,e)}),e.canDeactivateChecks.push(new ed(r.component&&t&&t.outlet&&t.outlet.isActivated?t.outlet.component:null,r))}class t2{}function Iw(n){return new Ve(t=>t.error(n))}class r2{constructor(t,e,i,r,s,o){this.rootComponentType=t,this.config=e,this.urlTree=i,this.url=r,this.paramsInheritanceStrategy=s,this.relativeLinkResolution=o}recognize(){const t=Zc(this.urlTree.root,[],[],this.config.filter(o=>void 0===o.redirectTo),this.relativeLinkResolution).segmentGroup,e=this.processSegmentGroup(this.config,t,me);if(null===e)return null;const i=new qc([],Object.freeze({}),Object.freeze(Object.assign({},this.urlTree.queryParams)),this.urlTree.fragment,{},me,this.rootComponentType,null,this.urlTree.root,-1,{}),r=new Bi(i,e),s=new mw(this.url,r);return this.inheritParamsAndData(s._root),s}inheritParamsAndData(t){const e=t.value,i=fw(e,this.paramsInheritanceStrategy);e.params=Object.freeze(i.params),e.data=Object.freeze(i.data),t.children.forEach(r=>this.inheritParamsAndData(r))}processSegmentGroup(t,e,i){return 0===e.segments.length&&e.hasChildren()?this.processChildren(t,e):this.processSegment(t,e,e.segments,i)}processChildren(t,e){const i=[];for(const s of Object.keys(e.children)){const o=e.children[s],a=Mw(t,s),l=this.processSegmentGroup(a,o,s);if(null===l)return null;i.push(...l)}const r=Rw(i);return function s2(n){n.sort((t,e)=>t.value.outlet===me?-1:e.value.outlet===me?1:t.value.outlet.localeCompare(e.value.outlet))}(r),r}processSegment(t,e,i,r){for(const s of t){const o=this.processSegmentAgainstRoute(s,e,i,r);if(null!==o)return o}return Sw(e,i,r)?[]:null}processSegmentAgainstRoute(t,e,i,r){if(t.redirectTo||!Ew(t,e,i,r))return null;let s,o=[],a=[];if(\"**\"===t.path){const p=i.length>0?ew(i).parameters:{};s=new qc(i,p,Object.freeze(Object.assign({},this.urlTree.queryParams)),this.urlTree.fragment,Fw(t),Tn(t),t.component,t,Ow(e),Pw(e)+i.length,Nw(t))}else{const p=Kc(e,t,i);if(!p.matched)return null;o=p.consumedSegments,a=p.remainingSegments,s=new qc(o,p.parameters,Object.freeze(Object.assign({},this.urlTree.queryParams)),this.urlTree.fragment,Fw(t),Tn(t),t.component,t,Ow(e),Pw(e)+o.length,Nw(t))}const l=function o2(n){return n.children?n.children:n.loadChildren?n._loadedConfig.routes:[]}(t),{segmentGroup:c,slicedSegments:d}=Zc(e,o,a,l.filter(p=>void 0===p.redirectTo),this.relativeLinkResolution);if(0===d.length&&c.hasChildren()){const p=this.processChildren(l,c);return null===p?null:[new Bi(s,p)]}if(0===l.length&&0===d.length)return[new Bi(s,[])];const u=Tn(t)===r,h=this.processSegment(l,c,d,u?me:r);return null===h?null:[new Bi(s,h)]}}function a2(n){const t=n.value.routeConfig;return t&&\"\"===t.path&&void 0===t.redirectTo}function Rw(n){const t=[],e=new Set;for(const i of n){if(!a2(i)){t.push(i);continue}const r=t.find(s=>i.value.routeConfig===s.value.routeConfig);void 0!==r?(r.children.push(...i.children),e.add(r)):t.push(i)}for(const i of e){const r=Rw(i.children);t.push(new Bi(i.value,r))}return t.filter(i=>!e.has(i))}function Ow(n){let t=n;for(;t._sourceSegment;)t=t._sourceSegment;return t}function Pw(n){let t=n,e=t._segmentIndexShift?t._segmentIndexShift:0;for(;t._sourceSegment;)t=t._sourceSegment,e+=t._segmentIndexShift?t._segmentIndexShift:0;return e-1}function Fw(n){return n.data||{}}function Nw(n){return n.resolve||{}}function Lw(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n)]}function Lf(n){return kn(t=>{const e=n(t);return e?mt(e).pipe(ue(()=>t)):q(t)})}class m2 extends class f2{shouldDetach(t){return!1}store(t,e){}shouldAttach(t){return!1}retrieve(t){return null}shouldReuseRoute(t,e){return t.routeConfig===e.routeConfig}}{}const Bf=new b(\"ROUTES\");class Bw{constructor(t,e,i,r){this.injector=t,this.compiler=e,this.onLoadStartListener=i,this.onLoadEndListener=r}load(t,e){if(e._loader$)return e._loader$;this.onLoadStartListener&&this.onLoadStartListener(e);const r=this.loadModuleFactory(e.loadChildren).pipe(ue(s=>{this.onLoadEndListener&&this.onLoadEndListener(e);const o=s.create(t);return new Of(JD(o.injector.get(Bf,void 0,ee.Self|ee.Optional)).map(Ff),o)}),Ni(s=>{throw e._loader$=void 0,s}));return e._loader$=new kB(r,()=>new O).pipe(zD()),e._loader$}loadModuleFactory(t){return _i(t()).pipe(lt(e=>e instanceof KC?q(e):mt(this.compiler.compileModuleAsync(e))))}}class _2{shouldProcessUrl(t){return!0}extract(t){return t}merge(t,e){return t}}function v2(n){throw n}function y2(n,t,e){return t.parse(\"/\")}function Vw(n,t){return q(null)}const b2={paths:\"exact\",fragment:\"ignored\",matrixParams:\"ignored\",queryParams:\"exact\"},C2={paths:\"subset\",fragment:\"ignored\",matrixParams:\"ignored\",queryParams:\"subset\"};let cn=(()=>{class n{constructor(e,i,r,s,o,a,l){this.rootComponentType=e,this.urlSerializer=i,this.rootContexts=r,this.location=s,this.config=l,this.lastSuccessfulNavigation=null,this.currentNavigation=null,this.disposed=!1,this.navigationId=0,this.currentPageId=0,this.isNgZoneEnabled=!1,this.events=new O,this.errorHandler=v2,this.malformedUriErrorHandler=y2,this.navigated=!1,this.lastSuccessfulId=-1,this.hooks={beforePreactivation:Vw,afterPreactivation:Vw},this.urlHandlingStrategy=new _2,this.routeReuseStrategy=new m2,this.onSameUrlNavigation=\"ignore\",this.paramsInheritanceStrategy=\"emptyOnly\",this.urlUpdateStrategy=\"deferred\",this.relativeLinkResolution=\"corrected\",this.canceledNavigationResolution=\"replace\",this.ngModule=o.get(Ri),this.console=o.get(O0);const u=o.get(ne);this.isNgZoneEnabled=u instanceof ne&&ne.isInAngularZone(),this.resetConfig(l),this.currentUrlTree=function WB(){return new Fr(new ye([],{}),{},null)}(),this.rawUrlTree=this.currentUrlTree,this.browserUrlTree=this.currentUrlTree,this.configLoader=new Bw(o,a,h=>this.triggerEvent(new YD(h)),h=>this.triggerEvent(new QD(h))),this.routerState=pw(this.currentUrlTree,this.rootComponentType),this.transitions=new Zt({id:0,targetPageId:0,currentUrlTree:this.currentUrlTree,currentRawUrl:this.currentUrlTree,extractedUrl:this.urlHandlingStrategy.extract(this.currentUrlTree),urlAfterRedirects:this.urlHandlingStrategy.extract(this.currentUrlTree),rawUrl:this.currentUrlTree,extras:{},resolve:null,reject:null,promise:Promise.resolve(!0),source:\"imperative\",restoredState:null,currentSnapshot:this.routerState.snapshot,targetSnapshot:null,currentRouterState:this.routerState,targetRouterState:null,guards:{canActivateChecks:[],canDeactivateChecks:[]},guardsResult:null}),this.navigations=this.setupNavigations(this.transitions),this.processNavigations()}get browserPageId(){var e;return null===(e=this.location.getState())||void 0===e?void 0:e.\\u0275routerPageId}setupNavigations(e){const i=this.events;return e.pipe(Ct(r=>0!==r.id),ue(r=>Object.assign(Object.assign({},r),{extractedUrl:this.urlHandlingStrategy.extract(r.rawUrl)})),kn(r=>{let s=!1,o=!1;return q(r).pipe(Mt(a=>{this.currentNavigation={id:a.id,initialUrl:a.currentRawUrl,extractedUrl:a.extractedUrl,trigger:a.source,extras:a.extras,previousNavigation:this.lastSuccessfulNavigation?Object.assign(Object.assign({},this.lastSuccessfulNavigation),{previousNavigation:null}):null}}),kn(a=>{const l=this.browserUrlTree.toString(),c=!this.navigated||a.extractedUrl.toString()!==l||l!==this.currentUrlTree.toString();if((\"reload\"===this.onSameUrlNavigation||c)&&this.urlHandlingStrategy.shouldProcessUrl(a.rawUrl))return Hw(a.source)&&(this.browserUrlTree=a.extractedUrl),q(a).pipe(kn(u=>{const h=this.transitions.getValue();return i.next(new Df(u.id,this.serializeUrl(u.extractedUrl),u.source,u.restoredState)),h!==this.transitions.getValue()?ri:Promise.resolve(u)}),function jV(n,t,e,i){return kn(r=>function BV(n,t,e,i,r){return new VV(n,t,e,i,r).apply()}(n,t,e,r.extractedUrl,i).pipe(ue(s=>Object.assign(Object.assign({},r),{urlAfterRedirects:s}))))}(this.ngModule.injector,this.configLoader,this.urlSerializer,this.config),Mt(u=>{this.currentNavigation=Object.assign(Object.assign({},this.currentNavigation),{finalUrl:u.urlAfterRedirects})}),function l2(n,t,e,i,r){return lt(s=>function n2(n,t,e,i,r=\"emptyOnly\",s=\"legacy\"){try{const o=new r2(n,t,e,i,r,s).recognize();return null===o?Iw(new t2):q(o)}catch(o){return Iw(o)}}(n,t,s.urlAfterRedirects,e(s.urlAfterRedirects),i,r).pipe(ue(o=>Object.assign(Object.assign({},s),{targetSnapshot:o}))))}(this.rootComponentType,this.config,u=>this.serializeUrl(u),this.paramsInheritanceStrategy,this.relativeLinkResolution),Mt(u=>{if(\"eager\"===this.urlUpdateStrategy){if(!u.extras.skipLocationChange){const p=this.urlHandlingStrategy.merge(u.urlAfterRedirects,u.rawUrl);this.setBrowserUrl(p,u)}this.browserUrlTree=u.urlAfterRedirects}const h=new OB(u.id,this.serializeUrl(u.extractedUrl),this.serializeUrl(u.urlAfterRedirects),u.targetSnapshot);i.next(h)}));if(c&&this.rawUrlTree&&this.urlHandlingStrategy.shouldProcessUrl(this.rawUrlTree)){const{id:h,extractedUrl:p,source:m,restoredState:g,extras:_}=a,D=new Df(h,this.serializeUrl(p),m,g);i.next(D);const v=pw(p,this.rootComponentType).snapshot;return q(Object.assign(Object.assign({},a),{targetSnapshot:v,urlAfterRedirects:p,extras:Object.assign(Object.assign({},_),{skipLocationChange:!1,replaceUrl:!1})}))}return this.rawUrlTree=a.rawUrl,a.resolve(null),ri}),Lf(a=>{const{targetSnapshot:l,id:c,extractedUrl:d,rawUrl:u,extras:{skipLocationChange:h,replaceUrl:p}}=a;return this.hooks.beforePreactivation(l,{navigationId:c,appliedUrlTree:d,rawUrlTree:u,skipLocationChange:!!h,replaceUrl:!!p})}),Mt(a=>{const l=new PB(a.id,this.serializeUrl(a.extractedUrl),this.serializeUrl(a.urlAfterRedirects),a.targetSnapshot);this.triggerEvent(l)}),ue(a=>Object.assign(Object.assign({},a),{guards:zV(a.targetSnapshot,a.currentSnapshot,this.rootContexts)})),function qV(n,t){return lt(e=>{const{targetSnapshot:i,currentSnapshot:r,guards:{canActivateChecks:s,canDeactivateChecks:o}}=e;return 0===o.length&&0===s.length?q(Object.assign(Object.assign({},e),{guardsResult:!0})):function YV(n,t,e,i){return mt(n).pipe(lt(r=>function e2(n,t,e,i,r){const s=t&&t.routeConfig?t.routeConfig.canDeactivate:null;return s&&0!==s.length?q(s.map(a=>{const l=td(a,t,r);let c;if(function SV(n){return n&&nr(n.canDeactivate)}(l))c=_i(l.canDeactivate(n,t,e,i));else{if(!nr(l))throw new Error(\"Invalid CanDeactivate guard\");c=_i(l(n,t,e,i))}return c.pipe(Ks())})).pipe(Ra()):q(!0)}(r.component,r.route,e,t,i)),Ks(r=>!0!==r,!0))}(o,i,r,n).pipe(lt(a=>a&&function wV(n){return\"boolean\"==typeof n}(a)?function QV(n,t,e,i){return mt(t).pipe(Qs(r=>jc(function ZV(n,t){return null!==n&&t&&t(new BB(n)),q(!0)}(r.route.parent,i),function KV(n,t){return null!==n&&t&&t(new HB(n)),q(!0)}(r.route,i),function JV(n,t,e){const i=t[t.length-1],s=t.slice(0,t.length-1).reverse().map(o=>function UV(n){const t=n.routeConfig?n.routeConfig.canActivateChild:null;return t&&0!==t.length?{node:n,guards:t}:null}(o)).filter(o=>null!==o).map(o=>xa(()=>q(o.guards.map(l=>{const c=td(l,o.node,e);let d;if(function EV(n){return n&&nr(n.canActivateChild)}(c))d=_i(c.canActivateChild(i,n));else{if(!nr(c))throw new Error(\"Invalid CanActivateChild guard\");d=_i(c(i,n))}return d.pipe(Ks())})).pipe(Ra())));return q(s).pipe(Ra())}(n,r.path,e),function XV(n,t,e){const i=t.routeConfig?t.routeConfig.canActivate:null;if(!i||0===i.length)return q(!0);const r=i.map(s=>xa(()=>{const o=td(s,t,e);let a;if(function xV(n){return n&&nr(n.canActivate)}(o))a=_i(o.canActivate(t,n));else{if(!nr(o))throw new Error(\"Invalid CanActivate guard\");a=_i(o(t,n))}return a.pipe(Ks())}));return q(r).pipe(Ra())}(n,r.route,e))),Ks(r=>!0!==r,!0))}(i,s,n,t):q(a)),ue(a=>Object.assign(Object.assign({},e),{guardsResult:a})))})}(this.ngModule.injector,a=>this.triggerEvent(a)),Mt(a=>{if(Lr(a.guardsResult)){const c=wf(`Redirecting to \"${this.serializeUrl(a.guardsResult)}\"`);throw c.url=a.guardsResult,c}const l=new FB(a.id,this.serializeUrl(a.extractedUrl),this.serializeUrl(a.urlAfterRedirects),a.targetSnapshot,!!a.guardsResult);this.triggerEvent(l)}),Ct(a=>!!a.guardsResult||(this.restoreHistory(a),this.cancelNavigationTransition(a,\"\"),!1)),Lf(a=>{if(a.guards.canActivateChecks.length)return q(a).pipe(Mt(l=>{const c=new NB(l.id,this.serializeUrl(l.extractedUrl),this.serializeUrl(l.urlAfterRedirects),l.targetSnapshot);this.triggerEvent(c)}),kn(l=>{let c=!1;return q(l).pipe(function c2(n,t){return lt(e=>{const{targetSnapshot:i,guards:{canActivateChecks:r}}=e;if(!r.length)return q(e);let s=0;return mt(r).pipe(Qs(o=>function d2(n,t,e,i){return function u2(n,t,e,i){const r=Lw(n);if(0===r.length)return q({});const s={};return mt(r).pipe(lt(o=>function h2(n,t,e,i){const r=td(n,t,i);return _i(r.resolve?r.resolve(t,e):r(t,e))}(n[o],t,e,i).pipe(Mt(a=>{s[o]=a}))),Cf(1),lt(()=>Lw(s).length===r.length?q(s):ri))}(n._resolve,n,t,i).pipe(ue(s=>(n._resolvedData=s,n.data=Object.assign(Object.assign({},n.data),fw(n,e).resolve),null)))}(o.route,i,n,t)),Mt(()=>s++),Cf(1),lt(o=>s===r.length?q(e):ri))})}(this.paramsInheritanceStrategy,this.ngModule.injector),Mt({next:()=>c=!0,complete:()=>{c||(this.restoreHistory(l),this.cancelNavigationTransition(l,\"At least one route resolver didn't emit any value.\"))}}))}),Mt(l=>{const c=new LB(l.id,this.serializeUrl(l.extractedUrl),this.serializeUrl(l.urlAfterRedirects),l.targetSnapshot);this.triggerEvent(c)}))}),Lf(a=>{const{targetSnapshot:l,id:c,extractedUrl:d,rawUrl:u,extras:{skipLocationChange:h,replaceUrl:p}}=a;return this.hooks.afterPreactivation(l,{navigationId:c,appliedUrlTree:d,rawUrlTree:u,skipLocationChange:!!h,replaceUrl:!!p})}),ue(a=>{const l=function dV(n,t,e){const i=Ta(n,t._root,e?e._root:void 0);return new hw(i,t)}(this.routeReuseStrategy,a.targetSnapshot,a.currentRouterState);return Object.assign(Object.assign({},a),{targetRouterState:l})}),Mt(a=>{this.currentUrlTree=a.urlAfterRedirects,this.rawUrlTree=this.urlHandlingStrategy.merge(a.urlAfterRedirects,a.rawUrl),this.routerState=a.targetRouterState,\"deferred\"===this.urlUpdateStrategy&&(a.extras.skipLocationChange||this.setBrowserUrl(this.rawUrlTree,a),this.browserUrlTree=a.urlAfterRedirects)}),((n,t,e)=>ue(i=>(new CV(t,i.targetRouterState,i.currentRouterState,e).activate(n),i)))(this.rootContexts,this.routeReuseStrategy,a=>this.triggerEvent(a)),Mt({next(){s=!0},complete(){s=!0}}),function WD(n){return qe((t,e)=>{try{t.subscribe(e)}finally{e.add(n)}})}(()=>{var a;s||o||this.cancelNavigationTransition(r,`Navigation ID ${r.id} is not equal to the current navigation id ${this.navigationId}`),(null===(a=this.currentNavigation)||void 0===a?void 0:a.id)===r.id&&(this.currentNavigation=null)}),Ni(a=>{if(o=!0,function UB(n){return n&&n[ZD]}(a)){const l=Lr(a.url);l||(this.navigated=!0,this.restoreHistory(r,!0));const c=new qD(r.id,this.serializeUrl(r.extractedUrl),a.message);i.next(c),l?setTimeout(()=>{const d=this.urlHandlingStrategy.merge(a.url,this.rawUrlTree),u={skipLocationChange:r.extras.skipLocationChange,replaceUrl:\"eager\"===this.urlUpdateStrategy||Hw(r.source)};this.scheduleNavigation(d,\"imperative\",null,u,{resolve:r.resolve,reject:r.reject,promise:r.promise})},0):r.resolve(!1)}else{this.restoreHistory(r,!0);const l=new RB(r.id,this.serializeUrl(r.extractedUrl),a);i.next(l);try{r.resolve(this.errorHandler(a))}catch(c){r.reject(c)}}return ri}))}))}resetRootComponentType(e){this.rootComponentType=e,this.routerState.root.component=this.rootComponentType}setTransition(e){this.transitions.next(Object.assign(Object.assign({},this.transitions.value),e))}initialNavigation(){this.setUpLocationChangeListener(),0===this.navigationId&&this.navigateByUrl(this.location.path(!0),{replaceUrl:!0})}setUpLocationChangeListener(){this.locationSubscription||(this.locationSubscription=this.location.subscribe(e=>{const i=\"popstate\"===e.type?\"popstate\":\"hashchange\";\"popstate\"===i&&setTimeout(()=>{var r;const s={replaceUrl:!0},o=(null===(r=e.state)||void 0===r?void 0:r.navigationId)?e.state:null;if(o){const l=Object.assign({},o);delete l.navigationId,delete l.\\u0275routerPageId,0!==Object.keys(l).length&&(s.state=l)}const a=this.parseUrl(e.url);this.scheduleNavigation(a,i,o,s)},0)}))}get url(){return this.serializeUrl(this.currentUrlTree)}getCurrentNavigation(){return this.currentNavigation}triggerEvent(e){this.events.next(e)}resetConfig(e){ww(e),this.config=e.map(Ff),this.navigated=!1,this.lastSuccessfulId=-1}ngOnDestroy(){this.dispose()}dispose(){this.transitions.complete(),this.locationSubscription&&(this.locationSubscription.unsubscribe(),this.locationSubscription=void 0),this.disposed=!0}createUrlTree(e,i={}){const{relativeTo:r,queryParams:s,fragment:o,queryParamsHandling:a,preserveFragment:l}=i,c=r||this.routerState.root,d=l?this.currentUrlTree.fragment:o;let u=null;switch(a){case\"merge\":u=Object.assign(Object.assign({},this.currentUrlTree.queryParams),s);break;case\"preserve\":u=this.currentUrlTree.queryParams;break;default:u=s||null}return null!==u&&(u=this.removeEmptyProps(u)),function pV(n,t,e,i,r){if(0===e.length)return Af(t.root,t.root,t.root,i,r);const s=function fV(n){if(\"string\"==typeof n[0]&&1===n.length&&\"/\"===n[0])return new vw(!0,0,n);let t=0,e=!1;const i=n.reduce((r,s,o)=>{if(\"object\"==typeof s&&null!=s){if(s.outlets){const a={};return At(s.outlets,(l,c)=>{a[c]=\"string\"==typeof l?l.split(\"/\"):l}),[...r,{outlets:a}]}if(s.segmentPath)return[...r,s.segmentPath]}return\"string\"!=typeof s?[...r,s]:0===o?(s.split(\"/\").forEach((a,l)=>{0==l&&\".\"===a||(0==l&&\"\"===a?e=!0:\"..\"===a?t++:\"\"!=a&&r.push(a))}),r):[...r,s]},[]);return new vw(e,t,i)}(e);if(s.toRoot())return Af(t.root,t.root,new ye([],{}),i,r);const o=function mV(n,t,e){if(n.isAbsolute)return new If(t.root,!0,0);if(-1===e.snapshot._lastPathIndex){const s=e.snapshot._urlSegment;return new If(s,s===t.root,0)}const i=Yc(n.commands[0])?0:1;return function gV(n,t,e){let i=n,r=t,s=e;for(;s>r;){if(s-=r,i=i.parent,!i)throw new Error(\"Invalid number of '../'\");r=i.segments.length}return new If(i,!1,r-s)}(e.snapshot._urlSegment,e.snapshot._lastPathIndex+i,n.numberOfDoubleDots)}(s,t,n),a=o.processChildren?Qc(o.segmentGroup,o.index,s.commands):yw(o.segmentGroup,o.index,s.commands);return Af(t.root,o.segmentGroup,a,i,r)}(c,this.currentUrlTree,e,u,null!=d?d:null)}navigateByUrl(e,i={skipLocationChange:!1}){const r=Lr(e)?e:this.parseUrl(e),s=this.urlHandlingStrategy.merge(r,this.rawUrlTree);return this.scheduleNavigation(s,\"imperative\",null,i)}navigate(e,i={skipLocationChange:!1}){return function D2(n){for(let t=0;t<n.length;t++){const e=n[t];if(null==e)throw new Error(`The requested path contains ${e} segment at index ${t}`)}}(e),this.navigateByUrl(this.createUrlTree(e,i),i)}serializeUrl(e){return this.urlSerializer.serialize(e)}parseUrl(e){let i;try{i=this.urlSerializer.parse(e)}catch(r){i=this.malformedUriErrorHandler(r,this.urlSerializer,e)}return i}isActive(e,i){let r;if(r=!0===i?Object.assign({},b2):!1===i?Object.assign({},C2):i,Lr(e))return nw(this.currentUrlTree,e,r);const s=this.parseUrl(e);return nw(this.currentUrlTree,s,r)}removeEmptyProps(e){return Object.keys(e).reduce((i,r)=>{const s=e[r];return null!=s&&(i[r]=s),i},{})}processNavigations(){this.navigations.subscribe(e=>{this.navigated=!0,this.lastSuccessfulId=e.id,this.currentPageId=e.targetPageId,this.events.next(new Ea(e.id,this.serializeUrl(e.extractedUrl),this.serializeUrl(this.currentUrlTree))),this.lastSuccessfulNavigation=this.currentNavigation,e.resolve(!0)},e=>{this.console.warn(`Unhandled Navigation Error: ${e}`)})}scheduleNavigation(e,i,r,s,o){var a,l;if(this.disposed)return Promise.resolve(!1);let c,d,u;o?(c=o.resolve,d=o.reject,u=o.promise):u=new Promise((m,g)=>{c=m,d=g});const h=++this.navigationId;let p;return\"computed\"===this.canceledNavigationResolution?(0===this.currentPageId&&(r=this.location.getState()),p=r&&r.\\u0275routerPageId?r.\\u0275routerPageId:s.replaceUrl||s.skipLocationChange?null!==(a=this.browserPageId)&&void 0!==a?a:0:(null!==(l=this.browserPageId)&&void 0!==l?l:0)+1):p=0,this.setTransition({id:h,targetPageId:p,source:i,restoredState:r,currentUrlTree:this.currentUrlTree,currentRawUrl:this.rawUrlTree,rawUrl:e,extras:s,resolve:c,reject:d,promise:u,currentSnapshot:this.routerState.snapshot,currentRouterState:this.routerState}),u.catch(m=>Promise.reject(m))}setBrowserUrl(e,i){const r=this.urlSerializer.serialize(e),s=Object.assign(Object.assign({},i.extras.state),this.generateNgRouterState(i.id,i.targetPageId));this.location.isCurrentPathEqualTo(r)||i.extras.replaceUrl?this.location.replaceState(r,\"\",s):this.location.go(r,\"\",s)}restoreHistory(e,i=!1){var r,s;if(\"computed\"===this.canceledNavigationResolution){const o=this.currentPageId-e.targetPageId;\"popstate\"!==e.source&&\"eager\"!==this.urlUpdateStrategy&&this.currentUrlTree!==(null===(r=this.currentNavigation)||void 0===r?void 0:r.finalUrl)||0===o?this.currentUrlTree===(null===(s=this.currentNavigation)||void 0===s?void 0:s.finalUrl)&&0===o&&(this.resetState(e),this.browserUrlTree=e.currentUrlTree,this.resetUrlToCurrentUrlTree()):this.location.historyGo(o)}else\"replace\"===this.canceledNavigationResolution&&(i&&this.resetState(e),this.resetUrlToCurrentUrlTree())}resetState(e){this.routerState=e.currentRouterState,this.currentUrlTree=e.currentUrlTree,this.rawUrlTree=this.urlHandlingStrategy.merge(this.currentUrlTree,e.rawUrl)}resetUrlToCurrentUrlTree(){this.location.replaceState(this.urlSerializer.serialize(this.rawUrlTree),\"\",this.generateNgRouterState(this.lastSuccessfulId,this.currentPageId))}cancelNavigationTransition(e,i){const r=new qD(e.id,this.serializeUrl(e.extractedUrl),i);this.triggerEvent(r),e.resolve(!1)}generateNgRouterState(e,i){return\"computed\"===this.canceledNavigationResolution?{navigationId:e,\\u0275routerPageId:i}:{navigationId:e}}}return n.\\u0275fac=function(e){Sr()},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();function Hw(n){return\"imperative\"!==n}class jw{}class zw{preload(t,e){return q(null)}}let Uw=(()=>{class n{constructor(e,i,r,s){this.router=e,this.injector=r,this.preloadingStrategy=s,this.loader=new Bw(r,i,l=>e.triggerEvent(new YD(l)),l=>e.triggerEvent(new QD(l)))}setUpPreloading(){this.subscription=this.router.events.pipe(Ct(e=>e instanceof Ea),Qs(()=>this.preload())).subscribe(()=>{})}preload(){const e=this.injector.get(Ri);return this.processRoutes(e,this.router.config)}ngOnDestroy(){this.subscription&&this.subscription.unsubscribe()}processRoutes(e,i){const r=[];for(const s of i)if(s.loadChildren&&!s.canLoad&&s._loadedConfig){const o=s._loadedConfig;r.push(this.processRoutes(o.module,o.routes))}else s.loadChildren&&!s.canLoad?r.push(this.preloadConfig(e,s)):s.children&&r.push(this.processRoutes(e,s.children));return mt(r).pipe(Eo(),ue(s=>{}))}preloadConfig(e,i){return this.preloadingStrategy.preload(i,()=>(i._loadedConfig?q(i._loadedConfig):this.loader.load(e.injector,i)).pipe(lt(s=>(i._loadedConfig=s,this.processRoutes(s.module,s.routes)))))}}return n.\\u0275fac=function(e){return new(e||n)(y(cn),y(P0),y(dt),y(jw))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),jf=(()=>{class n{constructor(e,i,r={}){this.router=e,this.viewportScroller=i,this.options=r,this.lastId=0,this.lastSource=\"imperative\",this.restoredId=0,this.store={},r.scrollPositionRestoration=r.scrollPositionRestoration||\"disabled\",r.anchorScrolling=r.anchorScrolling||\"disabled\"}init(){\"disabled\"!==this.options.scrollPositionRestoration&&this.viewportScroller.setHistoryScrollRestoration(\"manual\"),this.routerEventsSubscription=this.createScrollEvents(),this.scrollEventsSubscription=this.consumeScrollEvents()}createScrollEvents(){return this.router.events.subscribe(e=>{e instanceof Df?(this.store[this.lastId]=this.viewportScroller.getScrollPosition(),this.lastSource=e.navigationTrigger,this.restoredId=e.restoredState?e.restoredState.navigationId:0):e instanceof Ea&&(this.lastId=e.id,this.scheduleScrollEvent(e,this.router.parseUrl(e.urlAfterRedirects).fragment))})}consumeScrollEvents(){return this.router.events.subscribe(e=>{e instanceof KD&&(e.position?\"top\"===this.options.scrollPositionRestoration?this.viewportScroller.scrollToPosition([0,0]):\"enabled\"===this.options.scrollPositionRestoration&&this.viewportScroller.scrollToPosition(e.position):e.anchor&&\"enabled\"===this.options.anchorScrolling?this.viewportScroller.scrollToAnchor(e.anchor):\"disabled\"!==this.options.scrollPositionRestoration&&this.viewportScroller.scrollToPosition([0,0]))})}scheduleScrollEvent(e,i){this.router.triggerEvent(new KD(e,\"popstate\"===this.lastSource?this.store[this.restoredId]:null,i))}ngOnDestroy(){this.routerEventsSubscription&&this.routerEventsSubscription.unsubscribe(),this.scrollEventsSubscription&&this.scrollEventsSubscription.unsubscribe()}}return n.\\u0275fac=function(e){Sr()},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const Br=new b(\"ROUTER_CONFIGURATION\"),$w=new b(\"ROUTER_FORROOT_GUARD\"),E2=[va,{provide:ow,useClass:aw},{provide:cn,useFactory:function I2(n,t,e,i,r,s,o={},a,l){const c=new cn(null,n,t,e,i,r,JD(s));return a&&(c.urlHandlingStrategy=a),l&&(c.routeReuseStrategy=l),function R2(n,t){n.errorHandler&&(t.errorHandler=n.errorHandler),n.malformedUriErrorHandler&&(t.malformedUriErrorHandler=n.malformedUriErrorHandler),n.onSameUrlNavigation&&(t.onSameUrlNavigation=n.onSameUrlNavigation),n.paramsInheritanceStrategy&&(t.paramsInheritanceStrategy=n.paramsInheritanceStrategy),n.relativeLinkResolution&&(t.relativeLinkResolution=n.relativeLinkResolution),n.urlUpdateStrategy&&(t.urlUpdateStrategy=n.urlUpdateStrategy),n.canceledNavigationResolution&&(t.canceledNavigationResolution=n.canceledNavigationResolution)}(o,c),o.enableTracing&&c.events.subscribe(d=>{var u,h;null===(u=console.group)||void 0===u||u.call(console,`Router Event: ${d.constructor.name}`),console.log(d.toString()),console.log(d),null===(h=console.groupEnd)||void 0===h||h.call(console)}),c},deps:[ow,Oa,va,dt,P0,Bf,Br,[class g2{},new Tt],[class p2{},new Tt]]},Oa,{provide:Js,useFactory:function O2(n){return n.routerState.root},deps:[cn]},Uw,zw,class x2{preload(t,e){return e().pipe(Ni(()=>q(null)))}},{provide:Br,useValue:{enableTracing:!1}}];function S2(){return new V0(\"Router\",cn)}let Gw=(()=>{class n{constructor(e,i){}static forRoot(e,i){return{ngModule:n,providers:[E2,Ww(e),{provide:$w,useFactory:A2,deps:[[cn,new Tt,new Cn]]},{provide:Br,useValue:i||{}},{provide:qs,useFactory:T2,deps:[Pr,[new Gl(Xp),new Tt],Br]},{provide:jf,useFactory:k2,deps:[cn,PL,Br]},{provide:jw,useExisting:i&&i.preloadingStrategy?i.preloadingStrategy:zw},{provide:V0,multi:!0,useFactory:S2},[zf,{provide:Bp,multi:!0,useFactory:P2,deps:[zf]},{provide:qw,useFactory:F2,deps:[zf]},{provide:R0,multi:!0,useExisting:qw}]]}}static forChild(e){return{ngModule:n,providers:[Ww(e)]}}}return n.\\u0275fac=function(e){return new(e||n)(y($w,8),y(cn,8))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();function k2(n,t,e){return e.scrollOffset&&t.setOffset(e.scrollOffset),new jf(n,t,e)}function T2(n,t,e={}){return e.useHash?new vN(n,t):new sD(n,t)}function A2(n){return\"guarded\"}function Ww(n){return[{provide:nA,multi:!0,useValue:n},{provide:Bf,multi:!0,useValue:n}]}let zf=(()=>{class n{constructor(e){this.injector=e,this.initNavigation=!1,this.destroyed=!1,this.resultOfPreactivationDone=new O}appInitializer(){return this.injector.get(mN,Promise.resolve(null)).then(()=>{if(this.destroyed)return Promise.resolve(!0);let i=null;const r=new Promise(a=>i=a),s=this.injector.get(cn),o=this.injector.get(Br);return\"disabled\"===o.initialNavigation?(s.setUpLocationChangeListener(),i(!0)):\"enabled\"===o.initialNavigation||\"enabledBlocking\"===o.initialNavigation?(s.hooks.afterPreactivation=()=>this.initNavigation?q(null):(this.initNavigation=!0,i(!0),this.resultOfPreactivationDone),s.initialNavigation()):i(!0),r})}bootstrapListener(e){const i=this.injector.get(Br),r=this.injector.get(Uw),s=this.injector.get(jf),o=this.injector.get(cn),a=this.injector.get(Cc);e===a.components[0]&&((\"enabledNonBlocking\"===i.initialNavigation||void 0===i.initialNavigation)&&o.initialNavigation(),r.setUpPreloading(),s.init(),o.resetRootComponentType(a.componentTypes[0]),this.resultOfPreactivationDone.next(null),this.resultOfPreactivationDone.complete())}ngOnDestroy(){this.destroyed=!0}}return n.\\u0275fac=function(e){return new(e||n)(y(dt))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();function P2(n){return n.appInitializer.bind(n)}function F2(n){return n.bootstrapListener.bind(n)}const qw=new b(\"Router Initializer\"),L2=[];let B2=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Gw.forRoot(L2)],Gw]}),n})();class Yw{}const Vi=\"*\";function Ke(n,t){return{type:7,name:n,definitions:t,options:{}}}function be(n,t=null){return{type:4,styles:t,timings:n}}function nd(n,t=null){return{type:3,steps:n,options:t}}function Qw(n,t=null){return{type:2,steps:n,options:t}}function R(n){return{type:6,styles:n,offset:null}}function ae(n,t,e){return{type:0,name:n,styles:t,options:e}}function ge(n,t,e=null){return{type:1,expr:n,animation:t,options:e}}function to(n=null){return{type:9,options:n}}function no(n,t,e=null){return{type:11,selector:n,animation:t,options:e}}function Kw(n){Promise.resolve(null).then(n)}class La{constructor(t=0,e=0){this._onDoneFns=[],this._onStartFns=[],this._onDestroyFns=[],this._started=!1,this._destroyed=!1,this._finished=!1,this._position=0,this.parentPlayer=null,this.totalTime=t+e}_onFinish(){this._finished||(this._finished=!0,this._onDoneFns.forEach(t=>t()),this._onDoneFns=[])}onStart(t){this._onStartFns.push(t)}onDone(t){this._onDoneFns.push(t)}onDestroy(t){this._onDestroyFns.push(t)}hasStarted(){return this._started}init(){}play(){this.hasStarted()||(this._onStart(),this.triggerMicrotask()),this._started=!0}triggerMicrotask(){Kw(()=>this._onFinish())}_onStart(){this._onStartFns.forEach(t=>t()),this._onStartFns=[]}pause(){}restart(){}finish(){this._onFinish()}destroy(){this._destroyed||(this._destroyed=!0,this.hasStarted()||this._onStart(),this.finish(),this._onDestroyFns.forEach(t=>t()),this._onDestroyFns=[])}reset(){this._started=!1}setPosition(t){this._position=this.totalTime?t*this.totalTime:1}getPosition(){return this.totalTime?this._position/this.totalTime:1}triggerCallback(t){const e=\"start\"==t?this._onStartFns:this._onDoneFns;e.forEach(i=>i()),e.length=0}}class Zw{constructor(t){this._onDoneFns=[],this._onStartFns=[],this._finished=!1,this._started=!1,this._destroyed=!1,this._onDestroyFns=[],this.parentPlayer=null,this.totalTime=0,this.players=t;let e=0,i=0,r=0;const s=this.players.length;0==s?Kw(()=>this._onFinish()):this.players.forEach(o=>{o.onDone(()=>{++e==s&&this._onFinish()}),o.onDestroy(()=>{++i==s&&this._onDestroy()}),o.onStart(()=>{++r==s&&this._onStart()})}),this.totalTime=this.players.reduce((o,a)=>Math.max(o,a.totalTime),0)}_onFinish(){this._finished||(this._finished=!0,this._onDoneFns.forEach(t=>t()),this._onDoneFns=[])}init(){this.players.forEach(t=>t.init())}onStart(t){this._onStartFns.push(t)}_onStart(){this.hasStarted()||(this._started=!0,this._onStartFns.forEach(t=>t()),this._onStartFns=[])}onDone(t){this._onDoneFns.push(t)}onDestroy(t){this._onDestroyFns.push(t)}hasStarted(){return this._started}play(){this.parentPlayer||this.init(),this._onStart(),this.players.forEach(t=>t.play())}pause(){this.players.forEach(t=>t.pause())}restart(){this.players.forEach(t=>t.restart())}finish(){this._onFinish(),this.players.forEach(t=>t.finish())}destroy(){this._onDestroy()}_onDestroy(){this._destroyed||(this._destroyed=!0,this._onFinish(),this.players.forEach(t=>t.destroy()),this._onDestroyFns.forEach(t=>t()),this._onDestroyFns=[])}reset(){this.players.forEach(t=>t.reset()),this._destroyed=!1,this._finished=!1,this._started=!1}setPosition(t){const e=t*this.totalTime;this.players.forEach(i=>{const r=i.totalTime?Math.min(1,e/i.totalTime):1;i.setPosition(r)})}getPosition(){const t=this.players.reduce((e,i)=>null===e||i.totalTime>e.totalTime?i:e,null);return null!=t?t.getPosition():0}beforeDestroy(){this.players.forEach(t=>{t.beforeDestroy&&t.beforeDestroy()})}triggerCallback(t){const e=\"start\"==t?this._onStartFns:this._onDoneFns;e.forEach(i=>i()),e.length=0}}const Ce=!1;function Xw(n){return new H(3e3,Ce)}function yH(){return\"undefined\"!=typeof window&&void 0!==window.document}function $f(){return\"undefined\"!=typeof process&&\"[object process]\"==={}.toString.call(process)}function ir(n){switch(n.length){case 0:return new La;case 1:return n[0];default:return new Zw(n)}}function Jw(n,t,e,i,r={},s={}){const o=[],a=[];let l=-1,c=null;if(i.forEach(d=>{const u=d.offset,h=u==l,p=h&&c||{};Object.keys(d).forEach(m=>{let g=m,_=d[m];if(\"offset\"!==m)switch(g=t.normalizePropertyName(g,o),_){case\"!\":_=r[m];break;case Vi:_=s[m];break;default:_=t.normalizeStyleValue(m,g,_,o)}p[g]=_}),h||a.push(p),c=p,l=u}),o.length)throw function lH(n){return new H(3502,Ce)}();return a}function Gf(n,t,e,i){switch(t){case\"start\":n.onStart(()=>i(e&&Wf(e,\"start\",n)));break;case\"done\":n.onDone(()=>i(e&&Wf(e,\"done\",n)));break;case\"destroy\":n.onDestroy(()=>i(e&&Wf(e,\"destroy\",n)))}}function Wf(n,t,e){const i=e.totalTime,s=qf(n.element,n.triggerName,n.fromState,n.toState,t||n.phaseName,null==i?n.totalTime:i,!!e.disabled),o=n._data;return null!=o&&(s._data=o),s}function qf(n,t,e,i,r=\"\",s=0,o){return{element:n,triggerName:t,fromState:e,toState:i,phaseName:r,totalTime:s,disabled:!!o}}function dn(n,t,e){let i;return n instanceof Map?(i=n.get(t),i||n.set(t,i=e)):(i=n[t],i||(i=n[t]=e)),i}function eM(n){const t=n.indexOf(\":\");return[n.substring(1,t),n.substr(t+1)]}let Yf=(n,t)=>!1,tM=(n,t,e)=>[],nM=null;function Qf(n){const t=n.parentNode||n.host;return t===nM?null:t}($f()||\"undefined\"!=typeof Element)&&(yH()?(nM=(()=>document.documentElement)(),Yf=(n,t)=>{for(;t;){if(t===n)return!0;t=Qf(t)}return!1}):Yf=(n,t)=>n.contains(t),tM=(n,t,e)=>{if(e)return Array.from(n.querySelectorAll(t));const i=n.querySelector(t);return i?[i]:[]});let Hr=null,iM=!1;function rM(n){Hr||(Hr=function CH(){return\"undefined\"!=typeof document?document.body:null}()||{},iM=!!Hr.style&&\"WebkitAppearance\"in Hr.style);let t=!0;return Hr.style&&!function bH(n){return\"ebkit\"==n.substring(1,6)}(n)&&(t=n in Hr.style,!t&&iM&&(t=\"Webkit\"+n.charAt(0).toUpperCase()+n.substr(1)in Hr.style)),t}const sM=Yf,oM=tM;let aM=(()=>{class n{validateStyleProperty(e){return rM(e)}matchesElement(e,i){return!1}containsElement(e,i){return sM(e,i)}getParentElement(e){return Qf(e)}query(e,i,r){return oM(e,i,r)}computeStyle(e,i,r){return r||\"\"}animate(e,i,r,s,o,a=[],l){return new La(r,s)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),Kf=(()=>{class n{}return n.NOOP=new aM,n})();const Zf=\"ng-enter\",rd=\"ng-leave\",sd=\"ng-trigger\",od=\".ng-trigger\",cM=\"ng-animating\",Xf=\".ng-animating\";function jr(n){if(\"number\"==typeof n)return n;const t=n.match(/^(-?[\\.\\d]+)(m?s)/);return!t||t.length<2?0:Jf(parseFloat(t[1]),t[2])}function Jf(n,t){return\"s\"===t?1e3*n:n}function ad(n,t,e){return n.hasOwnProperty(\"duration\")?n:function MH(n,t,e){let r,s=0,o=\"\";if(\"string\"==typeof n){const a=n.match(/^(-?[\\.\\d]+)(m?s)(?:\\s+(-?[\\.\\d]+)(m?s))?(?:\\s+([-a-z]+(?:\\(.+?\\))?))?$/i);if(null===a)return t.push(Xw()),{duration:0,delay:0,easing:\"\"};r=Jf(parseFloat(a[1]),a[2]);const l=a[3];null!=l&&(s=Jf(parseFloat(l),a[4]));const c=a[5];c&&(o=c)}else r=n;if(!e){let a=!1,l=t.length;r<0&&(t.push(function H2(){return new H(3100,Ce)}()),a=!0),s<0&&(t.push(function j2(){return new H(3101,Ce)}()),a=!0),a&&t.splice(l,0,Xw())}return{duration:r,delay:s,easing:o}}(n,t,e)}function io(n,t={}){return Object.keys(n).forEach(e=>{t[e]=n[e]}),t}function rr(n,t,e={}){if(t)for(let i in n)e[i]=n[i];else io(n,e);return e}function uM(n,t,e){return e?t+\":\"+e+\";\":\"\"}function hM(n){let t=\"\";for(let e=0;e<n.style.length;e++){const i=n.style.item(e);t+=uM(0,i,n.style.getPropertyValue(i))}for(const e in n.style)n.style.hasOwnProperty(e)&&!e.startsWith(\"_\")&&(t+=uM(0,SH(e),n.style[e]));n.setAttribute(\"style\",t)}function vi(n,t,e){n.style&&(Object.keys(t).forEach(i=>{const r=tm(i);e&&!e.hasOwnProperty(i)&&(e[i]=n.style[r]),n.style[r]=t[i]}),$f()&&hM(n))}function zr(n,t){n.style&&(Object.keys(t).forEach(e=>{const i=tm(e);n.style[i]=\"\"}),$f()&&hM(n))}function Ba(n){return Array.isArray(n)?1==n.length?n[0]:Qw(n):n}const em=new RegExp(\"{{\\\\s*(.+?)\\\\s*}}\",\"g\");function pM(n){let t=[];if(\"string\"==typeof n){let e;for(;e=em.exec(n);)t.push(e[1]);em.lastIndex=0}return t}function ld(n,t,e){const i=n.toString(),r=i.replace(em,(s,o)=>{let a=t[o];return t.hasOwnProperty(o)||(e.push(function U2(n){return new H(3003,Ce)}()),a=\"\"),a.toString()});return r==i?n:r}function cd(n){const t=[];let e=n.next();for(;!e.done;)t.push(e.value),e=n.next();return t}const EH=/-+([a-z0-9])/g;function tm(n){return n.replace(EH,(...t)=>t[1].toUpperCase())}function SH(n){return n.replace(/([a-z])([A-Z])/g,\"$1-$2\").toLowerCase()}function un(n,t,e){switch(t.type){case 7:return n.visitTrigger(t,e);case 0:return n.visitState(t,e);case 1:return n.visitTransition(t,e);case 2:return n.visitSequence(t,e);case 3:return n.visitGroup(t,e);case 4:return n.visitAnimate(t,e);case 5:return n.visitKeyframes(t,e);case 6:return n.visitStyle(t,e);case 8:return n.visitReference(t,e);case 9:return n.visitAnimateChild(t,e);case 10:return n.visitAnimateRef(t,e);case 11:return n.visitQuery(t,e);case 12:return n.visitStagger(t,e);default:throw function $2(n){return new H(3004,Ce)}()}}function fM(n,t){return window.getComputedStyle(n)[t]}function OH(n,t){const e=[];return\"string\"==typeof n?n.split(/\\s*,\\s*/).forEach(i=>function PH(n,t,e){if(\":\"==n[0]){const l=function FH(n,t){switch(n){case\":enter\":return\"void => *\";case\":leave\":return\"* => void\";case\":increment\":return(e,i)=>parseFloat(i)>parseFloat(e);case\":decrement\":return(e,i)=>parseFloat(i)<parseFloat(e);default:return t.push(function rH(n){return new H(3016,Ce)}()),\"* => *\"}}(n,e);if(\"function\"==typeof l)return void t.push(l);n=l}const i=n.match(/^(\\*|[-\\w]+)\\s*(<?[=-]>)\\s*(\\*|[-\\w]+)$/);if(null==i||i.length<4)return e.push(function iH(n){return new H(3015,Ce)}()),t;const r=i[1],s=i[2],o=i[3];t.push(mM(r,o));\"<\"==s[0]&&!(\"*\"==r&&\"*\"==o)&&t.push(mM(o,r))}(i,e,t)):e.push(n),e}const pd=new Set([\"true\",\"1\"]),fd=new Set([\"false\",\"0\"]);function mM(n,t){const e=pd.has(n)||fd.has(n),i=pd.has(t)||fd.has(t);return(r,s)=>{let o=\"*\"==n||n==r,a=\"*\"==t||t==s;return!o&&e&&\"boolean\"==typeof r&&(o=r?pd.has(n):fd.has(n)),!a&&i&&\"boolean\"==typeof s&&(a=s?pd.has(t):fd.has(t)),o&&a}}const NH=new RegExp(\"s*:selfs*,?\",\"g\");function nm(n,t,e,i){return new LH(n).build(t,e,i)}class LH{constructor(t){this._driver=t}build(t,e,i){const r=new HH(e);this._resetContextStyleTimingState(r);const s=un(this,Ba(t),r);return r.unsupportedCSSPropertiesFound.size&&r.unsupportedCSSPropertiesFound.keys(),s}_resetContextStyleTimingState(t){t.currentQuerySelector=\"\",t.collectedStyles={},t.collectedStyles[\"\"]={},t.currentTime=0}visitTrigger(t,e){let i=e.queryCount=0,r=e.depCount=0;const s=[],o=[];return\"@\"==t.name.charAt(0)&&e.errors.push(function W2(){return new H(3006,Ce)}()),t.definitions.forEach(a=>{if(this._resetContextStyleTimingState(e),0==a.type){const l=a,c=l.name;c.toString().split(/\\s*,\\s*/).forEach(d=>{l.name=d,s.push(this.visitState(l,e))}),l.name=c}else if(1==a.type){const l=this.visitTransition(a,e);i+=l.queryCount,r+=l.depCount,o.push(l)}else e.errors.push(function q2(){return new H(3007,Ce)}())}),{type:7,name:t.name,states:s,transitions:o,queryCount:i,depCount:r,options:null}}visitState(t,e){const i=this.visitStyle(t.styles,e),r=t.options&&t.options.params||null;if(i.containsDynamicStyles){const s=new Set,o=r||{};i.styles.forEach(a=>{if(md(a)){const l=a;Object.keys(l).forEach(c=>{pM(l[c]).forEach(d=>{o.hasOwnProperty(d)||s.add(d)})})}}),s.size&&(cd(s.values()),e.errors.push(function Y2(n,t){return new H(3008,Ce)}()))}return{type:0,name:t.name,style:i,options:r?{params:r}:null}}visitTransition(t,e){e.queryCount=0,e.depCount=0;const i=un(this,Ba(t.animation),e);return{type:1,matchers:OH(t.expr,e.errors),animation:i,queryCount:e.queryCount,depCount:e.depCount,options:Ur(t.options)}}visitSequence(t,e){return{type:2,steps:t.steps.map(i=>un(this,i,e)),options:Ur(t.options)}}visitGroup(t,e){const i=e.currentTime;let r=0;const s=t.steps.map(o=>{e.currentTime=i;const a=un(this,o,e);return r=Math.max(r,e.currentTime),a});return e.currentTime=r,{type:3,steps:s,options:Ur(t.options)}}visitAnimate(t,e){const i=function zH(n,t){let e=null;if(n.hasOwnProperty(\"duration\"))e=n;else if(\"number\"==typeof n)return im(ad(n,t).duration,0,\"\");const i=n;if(i.split(/\\s+/).some(s=>\"{\"==s.charAt(0)&&\"{\"==s.charAt(1))){const s=im(0,0,\"\");return s.dynamic=!0,s.strValue=i,s}return e=e||ad(i,t),im(e.duration,e.delay,e.easing)}(t.timings,e.errors);e.currentAnimateTimings=i;let r,s=t.styles?t.styles:R({});if(5==s.type)r=this.visitKeyframes(s,e);else{let o=t.styles,a=!1;if(!o){a=!0;const c={};i.easing&&(c.easing=i.easing),o=R(c)}e.currentTime+=i.duration+i.delay;const l=this.visitStyle(o,e);l.isEmptyStep=a,r=l}return e.currentAnimateTimings=null,{type:4,timings:i,style:r,options:null}}visitStyle(t,e){const i=this._makeStyleAst(t,e);return this._validateStyleAst(i,e),i}_makeStyleAst(t,e){const i=[];Array.isArray(t.styles)?t.styles.forEach(o=>{\"string\"==typeof o?o==Vi?i.push(o):e.errors.push(function Q2(n){return new H(3002,Ce)}()):i.push(o)}):i.push(t.styles);let r=!1,s=null;return i.forEach(o=>{if(md(o)){const a=o,l=a.easing;if(l&&(s=l,delete a.easing),!r)for(let c in a)if(a[c].toString().indexOf(\"{{\")>=0){r=!0;break}}}),{type:6,styles:i,easing:s,offset:t.offset,containsDynamicStyles:r,options:null}}_validateStyleAst(t,e){const i=e.currentAnimateTimings;let r=e.currentTime,s=e.currentTime;i&&s>0&&(s-=i.duration+i.delay),t.styles.forEach(o=>{\"string\"!=typeof o&&Object.keys(o).forEach(a=>{if(!this._driver.validateStyleProperty(a))return delete o[a],void e.unsupportedCSSPropertiesFound.add(a);const l=e.collectedStyles[e.currentQuerySelector],c=l[a];let d=!0;c&&(s!=r&&s>=c.startTime&&r<=c.endTime&&(e.errors.push(function K2(n,t,e,i,r){return new H(3010,Ce)}()),d=!1),s=c.startTime),d&&(l[a]={startTime:s,endTime:r}),e.options&&function xH(n,t,e){const i=t.params||{},r=pM(n);r.length&&r.forEach(s=>{i.hasOwnProperty(s)||e.push(function z2(n){return new H(3001,Ce)}())})}(o[a],e.options,e.errors)})})}visitKeyframes(t,e){const i={type:5,styles:[],options:null};if(!e.currentAnimateTimings)return e.errors.push(function Z2(){return new H(3011,Ce)}()),i;let s=0;const o=[];let a=!1,l=!1,c=0;const d=t.steps.map(D=>{const v=this._makeStyleAst(D,e);let M=null!=v.offset?v.offset:function jH(n){if(\"string\"==typeof n)return null;let t=null;if(Array.isArray(n))n.forEach(e=>{if(md(e)&&e.hasOwnProperty(\"offset\")){const i=e;t=parseFloat(i.offset),delete i.offset}});else if(md(n)&&n.hasOwnProperty(\"offset\")){const e=n;t=parseFloat(e.offset),delete e.offset}return t}(v.styles),V=0;return null!=M&&(s++,V=v.offset=M),l=l||V<0||V>1,a=a||V<c,c=V,o.push(V),v});l&&e.errors.push(function X2(){return new H(3012,Ce)}()),a&&e.errors.push(function J2(){return new H(3200,Ce)}());const u=t.steps.length;let h=0;s>0&&s<u?e.errors.push(function eH(){return new H(3202,Ce)}()):0==s&&(h=1/(u-1));const p=u-1,m=e.currentTime,g=e.currentAnimateTimings,_=g.duration;return d.forEach((D,v)=>{const M=h>0?v==p?1:h*v:o[v],V=M*_;e.currentTime=m+g.delay+V,g.duration=V,this._validateStyleAst(D,e),D.offset=M,i.styles.push(D)}),i}visitReference(t,e){return{type:8,animation:un(this,Ba(t.animation),e),options:Ur(t.options)}}visitAnimateChild(t,e){return e.depCount++,{type:9,options:Ur(t.options)}}visitAnimateRef(t,e){return{type:10,animation:this.visitReference(t.animation,e),options:Ur(t.options)}}visitQuery(t,e){const i=e.currentQuerySelector,r=t.options||{};e.queryCount++,e.currentQuery=t;const[s,o]=function BH(n){const t=!!n.split(/\\s*,\\s*/).find(e=>\":self\"==e);return t&&(n=n.replace(NH,\"\")),n=n.replace(/@\\*/g,od).replace(/@\\w+/g,e=>od+\"-\"+e.substr(1)).replace(/:animating/g,Xf),[n,t]}(t.selector);e.currentQuerySelector=i.length?i+\" \"+s:s,dn(e.collectedStyles,e.currentQuerySelector,{});const a=un(this,Ba(t.animation),e);return e.currentQuery=null,e.currentQuerySelector=i,{type:11,selector:s,limit:r.limit||0,optional:!!r.optional,includeSelf:o,animation:a,originalSelector:t.selector,options:Ur(t.options)}}visitStagger(t,e){e.currentQuery||e.errors.push(function tH(){return new H(3013,Ce)}());const i=\"full\"===t.timings?{duration:0,delay:0,easing:\"full\"}:ad(t.timings,e.errors,!0);return{type:12,animation:un(this,Ba(t.animation),e),timings:i,options:null}}}class HH{constructor(t){this.errors=t,this.queryCount=0,this.depCount=0,this.currentTransition=null,this.currentQuery=null,this.currentQuerySelector=null,this.currentAnimateTimings=null,this.currentTime=0,this.collectedStyles={},this.options=null,this.unsupportedCSSPropertiesFound=new Set}}function md(n){return!Array.isArray(n)&&\"object\"==typeof n}function Ur(n){return n?(n=io(n)).params&&(n.params=function VH(n){return n?io(n):null}(n.params)):n={},n}function im(n,t,e){return{duration:n,delay:t,easing:e}}function rm(n,t,e,i,r,s,o=null,a=!1){return{type:1,element:n,keyframes:t,preStyleProps:e,postStyleProps:i,duration:r,delay:s,totalTime:r+s,easing:o,subTimeline:a}}class gd{constructor(){this._map=new Map}get(t){return this._map.get(t)||[]}append(t,e){let i=this._map.get(t);i||this._map.set(t,i=[]),i.push(...e)}has(t){return this._map.has(t)}clear(){this._map.clear()}}const GH=new RegExp(\":enter\",\"g\"),qH=new RegExp(\":leave\",\"g\");function sm(n,t,e,i,r,s={},o={},a,l,c=[]){return(new YH).buildKeyframes(n,t,e,i,r,s,o,a,l,c)}class YH{buildKeyframes(t,e,i,r,s,o,a,l,c,d=[]){c=c||new gd;const u=new om(t,e,c,r,s,d,[]);u.options=l,u.currentTimeline.setStyles([o],null,u.errors,l),un(this,i,u);const h=u.timelines.filter(p=>p.containsAnimation());if(Object.keys(a).length){let p;for(let m=h.length-1;m>=0;m--){const g=h[m];if(g.element===e){p=g;break}}p&&!p.allowOnlyTimelineStyles()&&p.setStyles([a],null,u.errors,l)}return h.length?h.map(p=>p.buildKeyframes()):[rm(e,[],[],[],0,0,\"\",!1)]}visitTrigger(t,e){}visitState(t,e){}visitTransition(t,e){}visitAnimateChild(t,e){const i=e.subInstructions.get(e.element);if(i){const r=e.createSubContext(t.options),s=e.currentTimeline.currentTime,o=this._visitSubInstructions(i,r,r.options);s!=o&&e.transformIntoNewTimeline(o)}e.previousNode=t}visitAnimateRef(t,e){const i=e.createSubContext(t.options);i.transformIntoNewTimeline(),this.visitReference(t.animation,i),e.transformIntoNewTimeline(i.currentTimeline.currentTime),e.previousNode=t}_visitSubInstructions(t,e,i){let s=e.currentTimeline.currentTime;const o=null!=i.duration?jr(i.duration):null,a=null!=i.delay?jr(i.delay):null;return 0!==o&&t.forEach(l=>{const c=e.appendInstructionToTimeline(l,o,a);s=Math.max(s,c.duration+c.delay)}),s}visitReference(t,e){e.updateOptions(t.options,!0),un(this,t.animation,e),e.previousNode=t}visitSequence(t,e){const i=e.subContextCount;let r=e;const s=t.options;if(s&&(s.params||s.delay)&&(r=e.createSubContext(s),r.transformIntoNewTimeline(),null!=s.delay)){6==r.previousNode.type&&(r.currentTimeline.snapshotCurrentStyles(),r.previousNode=_d);const o=jr(s.delay);r.delayNextStep(o)}t.steps.length&&(t.steps.forEach(o=>un(this,o,r)),r.currentTimeline.applyStylesToKeyframe(),r.subContextCount>i&&r.transformIntoNewTimeline()),e.previousNode=t}visitGroup(t,e){const i=[];let r=e.currentTimeline.currentTime;const s=t.options&&t.options.delay?jr(t.options.delay):0;t.steps.forEach(o=>{const a=e.createSubContext(t.options);s&&a.delayNextStep(s),un(this,o,a),r=Math.max(r,a.currentTimeline.currentTime),i.push(a.currentTimeline)}),i.forEach(o=>e.currentTimeline.mergeTimelineCollectedStyles(o)),e.transformIntoNewTimeline(r),e.previousNode=t}_visitTiming(t,e){if(t.dynamic){const i=t.strValue;return ad(e.params?ld(i,e.params,e.errors):i,e.errors)}return{duration:t.duration,delay:t.delay,easing:t.easing}}visitAnimate(t,e){const i=e.currentAnimateTimings=this._visitTiming(t.timings,e),r=e.currentTimeline;i.delay&&(e.incrementTime(i.delay),r.snapshotCurrentStyles());const s=t.style;5==s.type?this.visitKeyframes(s,e):(e.incrementTime(i.duration),this.visitStyle(s,e),r.applyStylesToKeyframe()),e.currentAnimateTimings=null,e.previousNode=t}visitStyle(t,e){const i=e.currentTimeline,r=e.currentAnimateTimings;!r&&i.getCurrentStyleProperties().length&&i.forwardFrame();const s=r&&r.easing||t.easing;t.isEmptyStep?i.applyEmptyStep(s):i.setStyles(t.styles,s,e.errors,e.options),e.previousNode=t}visitKeyframes(t,e){const i=e.currentAnimateTimings,r=e.currentTimeline.duration,s=i.duration,a=e.createSubContext().currentTimeline;a.easing=i.easing,t.styles.forEach(l=>{a.forwardTime((l.offset||0)*s),a.setStyles(l.styles,l.easing,e.errors,e.options),a.applyStylesToKeyframe()}),e.currentTimeline.mergeTimelineCollectedStyles(a),e.transformIntoNewTimeline(r+s),e.previousNode=t}visitQuery(t,e){const i=e.currentTimeline.currentTime,r=t.options||{},s=r.delay?jr(r.delay):0;s&&(6===e.previousNode.type||0==i&&e.currentTimeline.getCurrentStyleProperties().length)&&(e.currentTimeline.snapshotCurrentStyles(),e.previousNode=_d);let o=i;const a=e.invokeQuery(t.selector,t.originalSelector,t.limit,t.includeSelf,!!r.optional,e.errors);e.currentQueryTotal=a.length;let l=null;a.forEach((c,d)=>{e.currentQueryIndex=d;const u=e.createSubContext(t.options,c);s&&u.delayNextStep(s),c===e.element&&(l=u.currentTimeline),un(this,t.animation,u),u.currentTimeline.applyStylesToKeyframe(),o=Math.max(o,u.currentTimeline.currentTime)}),e.currentQueryIndex=0,e.currentQueryTotal=0,e.transformIntoNewTimeline(o),l&&(e.currentTimeline.mergeTimelineCollectedStyles(l),e.currentTimeline.snapshotCurrentStyles()),e.previousNode=t}visitStagger(t,e){const i=e.parentContext,r=e.currentTimeline,s=t.timings,o=Math.abs(s.duration),a=o*(e.currentQueryTotal-1);let l=o*e.currentQueryIndex;switch(s.duration<0?\"reverse\":s.easing){case\"reverse\":l=a-l;break;case\"full\":l=i.currentStaggerTime}const d=e.currentTimeline;l&&d.delayNextStep(l);const u=d.currentTime;un(this,t.animation,e),e.previousNode=t,i.currentStaggerTime=r.currentTime-u+(r.startTime-i.currentTimeline.startTime)}}const _d={};class om{constructor(t,e,i,r,s,o,a,l){this._driver=t,this.element=e,this.subInstructions=i,this._enterClassName=r,this._leaveClassName=s,this.errors=o,this.timelines=a,this.parentContext=null,this.currentAnimateTimings=null,this.previousNode=_d,this.subContextCount=0,this.options={},this.currentQueryIndex=0,this.currentQueryTotal=0,this.currentStaggerTime=0,this.currentTimeline=l||new vd(this._driver,e,0),a.push(this.currentTimeline)}get params(){return this.options.params}updateOptions(t,e){if(!t)return;const i=t;let r=this.options;null!=i.duration&&(r.duration=jr(i.duration)),null!=i.delay&&(r.delay=jr(i.delay));const s=i.params;if(s){let o=r.params;o||(o=this.options.params={}),Object.keys(s).forEach(a=>{(!e||!o.hasOwnProperty(a))&&(o[a]=ld(s[a],o,this.errors))})}}_copyOptions(){const t={};if(this.options){const e=this.options.params;if(e){const i=t.params={};Object.keys(e).forEach(r=>{i[r]=e[r]})}}return t}createSubContext(t=null,e,i){const r=e||this.element,s=new om(this._driver,r,this.subInstructions,this._enterClassName,this._leaveClassName,this.errors,this.timelines,this.currentTimeline.fork(r,i||0));return s.previousNode=this.previousNode,s.currentAnimateTimings=this.currentAnimateTimings,s.options=this._copyOptions(),s.updateOptions(t),s.currentQueryIndex=this.currentQueryIndex,s.currentQueryTotal=this.currentQueryTotal,s.parentContext=this,this.subContextCount++,s}transformIntoNewTimeline(t){return this.previousNode=_d,this.currentTimeline=this.currentTimeline.fork(this.element,t),this.timelines.push(this.currentTimeline),this.currentTimeline}appendInstructionToTimeline(t,e,i){const r={duration:null!=e?e:t.duration,delay:this.currentTimeline.currentTime+(null!=i?i:0)+t.delay,easing:\"\"},s=new QH(this._driver,t.element,t.keyframes,t.preStyleProps,t.postStyleProps,r,t.stretchStartingKeyframe);return this.timelines.push(s),r}incrementTime(t){this.currentTimeline.forwardTime(this.currentTimeline.duration+t)}delayNextStep(t){t>0&&this.currentTimeline.delayNextStep(t)}invokeQuery(t,e,i,r,s,o){let a=[];if(r&&a.push(this.element),t.length>0){t=(t=t.replace(GH,\".\"+this._enterClassName)).replace(qH,\".\"+this._leaveClassName);let c=this._driver.query(this.element,t,1!=i);0!==i&&(c=i<0?c.slice(c.length+i,c.length):c.slice(0,i)),a.push(...c)}return!s&&0==a.length&&o.push(function nH(n){return new H(3014,Ce)}()),a}}class vd{constructor(t,e,i,r){this._driver=t,this.element=e,this.startTime=i,this._elementTimelineStylesLookup=r,this.duration=0,this._previousKeyframe={},this._currentKeyframe={},this._keyframes=new Map,this._styleSummary={},this._pendingStyles={},this._backFill={},this._currentEmptyStepKeyframe=null,this._elementTimelineStylesLookup||(this._elementTimelineStylesLookup=new Map),this._localTimelineStyles=Object.create(this._backFill,{}),this._globalTimelineStyles=this._elementTimelineStylesLookup.get(e),this._globalTimelineStyles||(this._globalTimelineStyles=this._localTimelineStyles,this._elementTimelineStylesLookup.set(e,this._localTimelineStyles)),this._loadKeyframe()}containsAnimation(){switch(this._keyframes.size){case 0:return!1;case 1:return this.getCurrentStyleProperties().length>0;default:return!0}}getCurrentStyleProperties(){return Object.keys(this._currentKeyframe)}get currentTime(){return this.startTime+this.duration}delayNextStep(t){const e=1==this._keyframes.size&&Object.keys(this._pendingStyles).length;this.duration||e?(this.forwardTime(this.currentTime+t),e&&this.snapshotCurrentStyles()):this.startTime+=t}fork(t,e){return this.applyStylesToKeyframe(),new vd(this._driver,t,e||this.currentTime,this._elementTimelineStylesLookup)}_loadKeyframe(){this._currentKeyframe&&(this._previousKeyframe=this._currentKeyframe),this._currentKeyframe=this._keyframes.get(this.duration),this._currentKeyframe||(this._currentKeyframe=Object.create(this._backFill,{}),this._keyframes.set(this.duration,this._currentKeyframe))}forwardFrame(){this.duration+=1,this._loadKeyframe()}forwardTime(t){this.applyStylesToKeyframe(),this.duration=t,this._loadKeyframe()}_updateStyle(t,e){this._localTimelineStyles[t]=e,this._globalTimelineStyles[t]=e,this._styleSummary[t]={time:this.currentTime,value:e}}allowOnlyTimelineStyles(){return this._currentEmptyStepKeyframe!==this._currentKeyframe}applyEmptyStep(t){t&&(this._previousKeyframe.easing=t),Object.keys(this._globalTimelineStyles).forEach(e=>{this._backFill[e]=this._globalTimelineStyles[e]||Vi,this._currentKeyframe[e]=Vi}),this._currentEmptyStepKeyframe=this._currentKeyframe}setStyles(t,e,i,r){e&&(this._previousKeyframe.easing=e);const s=r&&r.params||{},o=function KH(n,t){const e={};let i;return n.forEach(r=>{\"*\"===r?(i=i||Object.keys(t),i.forEach(s=>{e[s]=Vi})):rr(r,!1,e)}),e}(t,this._globalTimelineStyles);Object.keys(o).forEach(a=>{const l=ld(o[a],s,i);this._pendingStyles[a]=l,this._localTimelineStyles.hasOwnProperty(a)||(this._backFill[a]=this._globalTimelineStyles.hasOwnProperty(a)?this._globalTimelineStyles[a]:Vi),this._updateStyle(a,l)})}applyStylesToKeyframe(){const t=this._pendingStyles,e=Object.keys(t);0!=e.length&&(this._pendingStyles={},e.forEach(i=>{this._currentKeyframe[i]=t[i]}),Object.keys(this._localTimelineStyles).forEach(i=>{this._currentKeyframe.hasOwnProperty(i)||(this._currentKeyframe[i]=this._localTimelineStyles[i])}))}snapshotCurrentStyles(){Object.keys(this._localTimelineStyles).forEach(t=>{const e=this._localTimelineStyles[t];this._pendingStyles[t]=e,this._updateStyle(t,e)})}getFinalKeyframe(){return this._keyframes.get(this.duration)}get properties(){const t=[];for(let e in this._currentKeyframe)t.push(e);return t}mergeTimelineCollectedStyles(t){Object.keys(t._styleSummary).forEach(e=>{const i=this._styleSummary[e],r=t._styleSummary[e];(!i||r.time>i.time)&&this._updateStyle(e,r.value)})}buildKeyframes(){this.applyStylesToKeyframe();const t=new Set,e=new Set,i=1===this._keyframes.size&&0===this.duration;let r=[];this._keyframes.forEach((a,l)=>{const c=rr(a,!0);Object.keys(c).forEach(d=>{const u=c[d];\"!\"==u?t.add(d):u==Vi&&e.add(d)}),i||(c.offset=l/this.duration),r.push(c)});const s=t.size?cd(t.values()):[],o=e.size?cd(e.values()):[];if(i){const a=r[0],l=io(a);a.offset=0,l.offset=1,r=[a,l]}return rm(this.element,r,s,o,this.duration,this.startTime,this.easing,!1)}}class QH extends vd{constructor(t,e,i,r,s,o,a=!1){super(t,e,o.delay),this.keyframes=i,this.preStyleProps=r,this.postStyleProps=s,this._stretchStartingKeyframe=a,this.timings={duration:o.duration,delay:o.delay,easing:o.easing}}containsAnimation(){return this.keyframes.length>1}buildKeyframes(){let t=this.keyframes,{delay:e,duration:i,easing:r}=this.timings;if(this._stretchStartingKeyframe&&e){const s=[],o=i+e,a=e/o,l=rr(t[0],!1);l.offset=0,s.push(l);const c=rr(t[0],!1);c.offset=vM(a),s.push(c);const d=t.length-1;for(let u=1;u<=d;u++){let h=rr(t[u],!1);h.offset=vM((e+h.offset*i)/o),s.push(h)}i=o,e=0,r=\"\",t=s}return rm(this.element,t,this.preStyleProps,this.postStyleProps,i,e,r,!0)}}function vM(n,t=3){const e=Math.pow(10,t-1);return Math.round(n*e)/e}class am{}class ZH extends am{normalizePropertyName(t,e){return tm(t)}normalizeStyleValue(t,e,i,r){let s=\"\";const o=i.toString().trim();if(XH[e]&&0!==i&&\"0\"!==i)if(\"number\"==typeof i)s=\"px\";else{const a=i.match(/^[+-]?[\\d\\.]+([a-z]*)$/);a&&0==a[1].length&&r.push(function G2(n,t){return new H(3005,Ce)}())}return o+s}}const XH=(()=>function JH(n){const t={};return n.forEach(e=>t[e]=!0),t}(\"width,height,minWidth,minHeight,maxWidth,maxHeight,left,top,bottom,right,fontSize,outlineWidth,outlineOffset,paddingTop,paddingLeft,paddingBottom,paddingRight,marginTop,marginLeft,marginBottom,marginRight,borderRadius,borderWidth,borderTopWidth,borderLeftWidth,borderRightWidth,borderBottomWidth,textIndent,perspective\".split(\",\")))();function yM(n,t,e,i,r,s,o,a,l,c,d,u,h){return{type:0,element:n,triggerName:t,isRemovalTransition:r,fromState:e,fromStyles:s,toState:i,toStyles:o,timelines:a,queriedElements:l,preStyleProps:c,postStyleProps:d,totalTime:u,errors:h}}const lm={};class bM{constructor(t,e,i){this._triggerName=t,this.ast=e,this._stateStyles=i}match(t,e,i,r){return function ej(n,t,e,i,r){return n.some(s=>s(t,e,i,r))}(this.ast.matchers,t,e,i,r)}buildStyles(t,e,i){const r=this._stateStyles[\"*\"],s=this._stateStyles[t],o=r?r.buildStyles(e,i):{};return s?s.buildStyles(e,i):o}build(t,e,i,r,s,o,a,l,c,d){const u=[],h=this.ast.options&&this.ast.options.params||lm,m=this.buildStyles(i,a&&a.params||lm,u),g=l&&l.params||lm,_=this.buildStyles(r,g,u),D=new Set,v=new Map,M=new Map,V=\"void\"===r,he={params:Object.assign(Object.assign({},h),g)},We=d?[]:sm(t,e,this.ast.animation,s,o,m,_,he,c,u);let Ze=0;if(We.forEach(pn=>{Ze=Math.max(pn.duration+pn.delay,Ze)}),u.length)return yM(e,this._triggerName,i,r,V,m,_,[],[],v,M,Ze,u);We.forEach(pn=>{const fn=pn.element,Do=dn(v,fn,{});pn.preStyleProps.forEach(ii=>Do[ii]=!0);const Gi=dn(M,fn,{});pn.postStyleProps.forEach(ii=>Gi[ii]=!0),fn!==e&&D.add(fn)});const hn=cd(D.values());return yM(e,this._triggerName,i,r,V,m,_,We,hn,v,M,Ze)}}class tj{constructor(t,e,i){this.styles=t,this.defaultParams=e,this.normalizer=i}buildStyles(t,e){const i={},r=io(this.defaultParams);return Object.keys(t).forEach(s=>{const o=t[s];null!=o&&(r[s]=o)}),this.styles.styles.forEach(s=>{if(\"string\"!=typeof s){const o=s;Object.keys(o).forEach(a=>{let l=o[a];l.length>1&&(l=ld(l,r,e));const c=this.normalizer.normalizePropertyName(a,e);l=this.normalizer.normalizeStyleValue(a,c,l,e),i[c]=l})}}),i}}class ij{constructor(t,e,i){this.name=t,this.ast=e,this._normalizer=i,this.transitionFactories=[],this.states={},e.states.forEach(r=>{this.states[r.name]=new tj(r.style,r.options&&r.options.params||{},i)}),CM(this.states,\"true\",\"1\"),CM(this.states,\"false\",\"0\"),e.transitions.forEach(r=>{this.transitionFactories.push(new bM(t,r,this.states))}),this.fallbackTransition=function rj(n,t,e){return new bM(n,{type:1,animation:{type:2,steps:[],options:null},matchers:[(o,a)=>!0],options:null,queryCount:0,depCount:0},t)}(t,this.states)}get containsQueries(){return this.ast.queryCount>0}matchTransition(t,e,i,r){return this.transitionFactories.find(o=>o.match(t,e,i,r))||null}matchStyles(t,e,i){return this.fallbackTransition.buildStyles(t,e,i)}}function CM(n,t,e){n.hasOwnProperty(t)?n.hasOwnProperty(e)||(n[e]=n[t]):n.hasOwnProperty(e)&&(n[t]=n[e])}const sj=new gd;class oj{constructor(t,e,i){this.bodyNode=t,this._driver=e,this._normalizer=i,this._animations={},this._playersById={},this.players=[]}register(t,e){const i=[],s=nm(this._driver,e,i,[]);if(i.length)throw function cH(n){return new H(3503,Ce)}();this._animations[t]=s}_buildPlayer(t,e,i){const r=t.element,s=Jw(0,this._normalizer,0,t.keyframes,e,i);return this._driver.animate(r,s,t.duration,t.delay,t.easing,[],!0)}create(t,e,i={}){const r=[],s=this._animations[t];let o;const a=new Map;if(s?(o=sm(this._driver,e,s,Zf,rd,{},{},i,sj,r),o.forEach(d=>{const u=dn(a,d.element,{});d.postStyleProps.forEach(h=>u[h]=null)})):(r.push(function dH(){return new H(3300,Ce)}()),o=[]),r.length)throw function uH(n){return new H(3504,Ce)}();a.forEach((d,u)=>{Object.keys(d).forEach(h=>{d[h]=this._driver.computeStyle(u,h,Vi)})});const c=ir(o.map(d=>{const u=a.get(d.element);return this._buildPlayer(d,{},u)}));return this._playersById[t]=c,c.onDestroy(()=>this.destroy(t)),this.players.push(c),c}destroy(t){const e=this._getPlayer(t);e.destroy(),delete this._playersById[t];const i=this.players.indexOf(e);i>=0&&this.players.splice(i,1)}_getPlayer(t){const e=this._playersById[t];if(!e)throw function hH(n){return new H(3301,Ce)}();return e}listen(t,e,i,r){const s=qf(e,\"\",\"\",\"\");return Gf(this._getPlayer(t),i,s,r),()=>{}}command(t,e,i,r){if(\"register\"==i)return void this.register(t,r[0]);if(\"create\"==i)return void this.create(t,e,r[0]||{});const s=this._getPlayer(t);switch(i){case\"play\":s.play();break;case\"pause\":s.pause();break;case\"reset\":s.reset();break;case\"restart\":s.restart();break;case\"finish\":s.finish();break;case\"init\":s.init();break;case\"setPosition\":s.setPosition(parseFloat(r[0]));break;case\"destroy\":this.destroy(t)}}}const DM=\"ng-animate-queued\",cm=\"ng-animate-disabled\",uj=[],wM={namespaceId:\"\",setForRemoval:!1,setForMove:!1,hasAnimation:!1,removedBeforeQueried:!1},hj={namespaceId:\"\",setForMove:!1,setForRemoval:!1,hasAnimation:!1,removedBeforeQueried:!0},An=\"__ng_removed\";class dm{constructor(t,e=\"\"){this.namespaceId=e;const i=t&&t.hasOwnProperty(\"value\");if(this.value=function gj(n){return null!=n?n:null}(i?t.value:t),i){const s=io(t);delete s.value,this.options=s}else this.options={};this.options.params||(this.options.params={})}get params(){return this.options.params}absorbOptions(t){const e=t.params;if(e){const i=this.options.params;Object.keys(e).forEach(r=>{null==i[r]&&(i[r]=e[r])})}}}const Va=\"void\",um=new dm(Va);class pj{constructor(t,e,i){this.id=t,this.hostElement=e,this._engine=i,this.players=[],this._triggers={},this._queue=[],this._elementListeners=new Map,this._hostClassName=\"ng-tns-\"+t,In(e,this._hostClassName)}listen(t,e,i,r){if(!this._triggers.hasOwnProperty(e))throw function pH(n,t){return new H(3302,Ce)}();if(null==i||0==i.length)throw function fH(n){return new H(3303,Ce)}();if(!function _j(n){return\"start\"==n||\"done\"==n}(i))throw function mH(n,t){return new H(3400,Ce)}();const s=dn(this._elementListeners,t,[]),o={name:e,phase:i,callback:r};s.push(o);const a=dn(this._engine.statesByElement,t,{});return a.hasOwnProperty(e)||(In(t,sd),In(t,sd+\"-\"+e),a[e]=um),()=>{this._engine.afterFlush(()=>{const l=s.indexOf(o);l>=0&&s.splice(l,1),this._triggers[e]||delete a[e]})}}register(t,e){return!this._triggers[t]&&(this._triggers[t]=e,!0)}_getTrigger(t){const e=this._triggers[t];if(!e)throw function gH(n){return new H(3401,Ce)}();return e}trigger(t,e,i,r=!0){const s=this._getTrigger(e),o=new hm(this.id,e,t);let a=this._engine.statesByElement.get(t);a||(In(t,sd),In(t,sd+\"-\"+e),this._engine.statesByElement.set(t,a={}));let l=a[e];const c=new dm(i,this.id);if(!(i&&i.hasOwnProperty(\"value\"))&&l&&c.absorbOptions(l.options),a[e]=c,l||(l=um),c.value!==Va&&l.value===c.value){if(!function bj(n,t){const e=Object.keys(n),i=Object.keys(t);if(e.length!=i.length)return!1;for(let r=0;r<e.length;r++){const s=e[r];if(!t.hasOwnProperty(s)||n[s]!==t[s])return!1}return!0}(l.params,c.params)){const g=[],_=s.matchStyles(l.value,l.params,g),D=s.matchStyles(c.value,c.params,g);g.length?this._engine.reportError(g):this._engine.afterFlush(()=>{zr(t,_),vi(t,D)})}return}const h=dn(this._engine.playersByElement,t,[]);h.forEach(g=>{g.namespaceId==this.id&&g.triggerName==e&&g.queued&&g.destroy()});let p=s.matchTransition(l.value,c.value,t,c.params),m=!1;if(!p){if(!r)return;p=s.fallbackTransition,m=!0}return this._engine.totalQueuedPlayers++,this._queue.push({element:t,triggerName:e,transition:p,fromState:l,toState:c,player:o,isFallbackTransition:m}),m||(In(t,DM),o.onStart(()=>{ro(t,DM)})),o.onDone(()=>{let g=this.players.indexOf(o);g>=0&&this.players.splice(g,1);const _=this._engine.playersByElement.get(t);if(_){let D=_.indexOf(o);D>=0&&_.splice(D,1)}}),this.players.push(o),h.push(o),o}deregister(t){delete this._triggers[t],this._engine.statesByElement.forEach((e,i)=>{delete e[t]}),this._elementListeners.forEach((e,i)=>{this._elementListeners.set(i,e.filter(r=>r.name!=t))})}clearElementCache(t){this._engine.statesByElement.delete(t),this._elementListeners.delete(t);const e=this._engine.playersByElement.get(t);e&&(e.forEach(i=>i.destroy()),this._engine.playersByElement.delete(t))}_signalRemovalForInnerTriggers(t,e){const i=this._engine.driver.query(t,od,!0);i.forEach(r=>{if(r[An])return;const s=this._engine.fetchNamespacesByElement(r);s.size?s.forEach(o=>o.triggerLeaveAnimation(r,e,!1,!0)):this.clearElementCache(r)}),this._engine.afterFlushAnimationsDone(()=>i.forEach(r=>this.clearElementCache(r)))}triggerLeaveAnimation(t,e,i,r){const s=this._engine.statesByElement.get(t),o=new Map;if(s){const a=[];if(Object.keys(s).forEach(l=>{if(o.set(l,s[l].value),this._triggers[l]){const c=this.trigger(t,l,Va,r);c&&a.push(c)}}),a.length)return this._engine.markElementAsRemoved(this.id,t,!0,e,o),i&&ir(a).onDone(()=>this._engine.processLeaveNode(t)),!0}return!1}prepareLeaveAnimationListeners(t){const e=this._elementListeners.get(t),i=this._engine.statesByElement.get(t);if(e&&i){const r=new Set;e.forEach(s=>{const o=s.name;if(r.has(o))return;r.add(o);const l=this._triggers[o].fallbackTransition,c=i[o]||um,d=new dm(Va),u=new hm(this.id,o,t);this._engine.totalQueuedPlayers++,this._queue.push({element:t,triggerName:o,transition:l,fromState:c,toState:d,player:u,isFallbackTransition:!0})})}}removeNode(t,e){const i=this._engine;if(t.childElementCount&&this._signalRemovalForInnerTriggers(t,e),this.triggerLeaveAnimation(t,e,!0))return;let r=!1;if(i.totalAnimations){const s=i.players.length?i.playersByQueriedElement.get(t):[];if(s&&s.length)r=!0;else{let o=t;for(;o=o.parentNode;)if(i.statesByElement.get(o)){r=!0;break}}}if(this.prepareLeaveAnimationListeners(t),r)i.markElementAsRemoved(this.id,t,!1,e);else{const s=t[An];(!s||s===wM)&&(i.afterFlush(()=>this.clearElementCache(t)),i.destroyInnerAnimations(t),i._onRemovalComplete(t,e))}}insertNode(t,e){In(t,this._hostClassName)}drainQueuedTransitions(t){const e=[];return this._queue.forEach(i=>{const r=i.player;if(r.destroyed)return;const s=i.element,o=this._elementListeners.get(s);o&&o.forEach(a=>{if(a.name==i.triggerName){const l=qf(s,i.triggerName,i.fromState.value,i.toState.value);l._data=t,Gf(i.player,a.phase,l,a.callback)}}),r.markedForDestroy?this._engine.afterFlush(()=>{r.destroy()}):e.push(i)}),this._queue=[],e.sort((i,r)=>{const s=i.transition.ast.depCount,o=r.transition.ast.depCount;return 0==s||0==o?s-o:this._engine.driver.containsElement(i.element,r.element)?1:-1})}destroy(t){this.players.forEach(e=>e.destroy()),this._signalRemovalForInnerTriggers(this.hostElement,t)}elementContainsData(t){let e=!1;return this._elementListeners.has(t)&&(e=!0),e=!!this._queue.find(i=>i.element===t)||e,e}}class fj{constructor(t,e,i){this.bodyNode=t,this.driver=e,this._normalizer=i,this.players=[],this.newHostElements=new Map,this.playersByElement=new Map,this.playersByQueriedElement=new Map,this.statesByElement=new Map,this.disabledNodes=new Set,this.totalAnimations=0,this.totalQueuedPlayers=0,this._namespaceLookup={},this._namespaceList=[],this._flushFns=[],this._whenQuietFns=[],this.namespacesByHostElement=new Map,this.collectedEnterElements=[],this.collectedLeaveElements=[],this.onRemovalComplete=(r,s)=>{}}_onRemovalComplete(t,e){this.onRemovalComplete(t,e)}get queuedPlayers(){const t=[];return this._namespaceList.forEach(e=>{e.players.forEach(i=>{i.queued&&t.push(i)})}),t}createNamespace(t,e){const i=new pj(t,e,this);return this.bodyNode&&this.driver.containsElement(this.bodyNode,e)?this._balanceNamespaceList(i,e):(this.newHostElements.set(e,i),this.collectEnterElement(e)),this._namespaceLookup[t]=i}_balanceNamespaceList(t,e){const i=this._namespaceList,r=this.namespacesByHostElement,s=i.length-1;if(s>=0){let o=!1;if(void 0!==this.driver.getParentElement){let a=this.driver.getParentElement(e);for(;a;){const l=r.get(a);if(l){const c=i.indexOf(l);i.splice(c+1,0,t),o=!0;break}a=this.driver.getParentElement(a)}}else for(let a=s;a>=0;a--)if(this.driver.containsElement(i[a].hostElement,e)){i.splice(a+1,0,t),o=!0;break}o||i.unshift(t)}else i.push(t);return r.set(e,t),t}register(t,e){let i=this._namespaceLookup[t];return i||(i=this.createNamespace(t,e)),i}registerTrigger(t,e,i){let r=this._namespaceLookup[t];r&&r.register(e,i)&&this.totalAnimations++}destroy(t,e){if(!t)return;const i=this._fetchNamespace(t);this.afterFlush(()=>{this.namespacesByHostElement.delete(i.hostElement),delete this._namespaceLookup[t];const r=this._namespaceList.indexOf(i);r>=0&&this._namespaceList.splice(r,1)}),this.afterFlushAnimationsDone(()=>i.destroy(e))}_fetchNamespace(t){return this._namespaceLookup[t]}fetchNamespacesByElement(t){const e=new Set,i=this.statesByElement.get(t);if(i){const r=Object.keys(i);for(let s=0;s<r.length;s++){const o=i[r[s]].namespaceId;if(o){const a=this._fetchNamespace(o);a&&e.add(a)}}}return e}trigger(t,e,i,r){if(yd(e)){const s=this._fetchNamespace(t);if(s)return s.trigger(e,i,r),!0}return!1}insertNode(t,e,i,r){if(!yd(e))return;const s=e[An];if(s&&s.setForRemoval){s.setForRemoval=!1,s.setForMove=!0;const o=this.collectedLeaveElements.indexOf(e);o>=0&&this.collectedLeaveElements.splice(o,1)}if(t){const o=this._fetchNamespace(t);o&&o.insertNode(e,i)}r&&this.collectEnterElement(e)}collectEnterElement(t){this.collectedEnterElements.push(t)}markElementAsDisabled(t,e){e?this.disabledNodes.has(t)||(this.disabledNodes.add(t),In(t,cm)):this.disabledNodes.has(t)&&(this.disabledNodes.delete(t),ro(t,cm))}removeNode(t,e,i,r){if(yd(e)){const s=t?this._fetchNamespace(t):null;if(s?s.removeNode(e,r):this.markElementAsRemoved(t,e,!1,r),i){const o=this.namespacesByHostElement.get(e);o&&o.id!==t&&o.removeNode(e,r)}}else this._onRemovalComplete(e,r)}markElementAsRemoved(t,e,i,r,s){this.collectedLeaveElements.push(e),e[An]={namespaceId:t,setForRemoval:r,hasAnimation:i,removedBeforeQueried:!1,previousTriggersValues:s}}listen(t,e,i,r,s){return yd(e)?this._fetchNamespace(t).listen(e,i,r,s):()=>{}}_buildInstruction(t,e,i,r,s){return t.transition.build(this.driver,t.element,t.fromState.value,t.toState.value,i,r,t.fromState.options,t.toState.options,e,s)}destroyInnerAnimations(t){let e=this.driver.query(t,od,!0);e.forEach(i=>this.destroyActiveAnimationsForElement(i)),0!=this.playersByQueriedElement.size&&(e=this.driver.query(t,Xf,!0),e.forEach(i=>this.finishActiveQueriedAnimationOnElement(i)))}destroyActiveAnimationsForElement(t){const e=this.playersByElement.get(t);e&&e.forEach(i=>{i.queued?i.markedForDestroy=!0:i.destroy()})}finishActiveQueriedAnimationOnElement(t){const e=this.playersByQueriedElement.get(t);e&&e.forEach(i=>i.finish())}whenRenderingDone(){return new Promise(t=>{if(this.players.length)return ir(this.players).onDone(()=>t());t()})}processLeaveNode(t){var e;const i=t[An];if(i&&i.setForRemoval){if(t[An]=wM,i.namespaceId){this.destroyInnerAnimations(t);const r=this._fetchNamespace(i.namespaceId);r&&r.clearElementCache(t)}this._onRemovalComplete(t,i.setForRemoval)}(null===(e=t.classList)||void 0===e?void 0:e.contains(cm))&&this.markElementAsDisabled(t,!1),this.driver.query(t,\".ng-animate-disabled\",!0).forEach(r=>{this.markElementAsDisabled(r,!1)})}flush(t=-1){let e=[];if(this.newHostElements.size&&(this.newHostElements.forEach((i,r)=>this._balanceNamespaceList(i,r)),this.newHostElements.clear()),this.totalAnimations&&this.collectedEnterElements.length)for(let i=0;i<this.collectedEnterElements.length;i++)In(this.collectedEnterElements[i],\"ng-star-inserted\");if(this._namespaceList.length&&(this.totalQueuedPlayers||this.collectedLeaveElements.length)){const i=[];try{e=this._flushAnimations(i,t)}finally{for(let r=0;r<i.length;r++)i[r]()}}else for(let i=0;i<this.collectedLeaveElements.length;i++)this.processLeaveNode(this.collectedLeaveElements[i]);if(this.totalQueuedPlayers=0,this.collectedEnterElements.length=0,this.collectedLeaveElements.length=0,this._flushFns.forEach(i=>i()),this._flushFns=[],this._whenQuietFns.length){const i=this._whenQuietFns;this._whenQuietFns=[],e.length?ir(e).onDone(()=>{i.forEach(r=>r())}):i.forEach(r=>r())}}reportError(t){throw function _H(n){return new H(3402,Ce)}()}_flushAnimations(t,e){const i=new gd,r=[],s=new Map,o=[],a=new Map,l=new Map,c=new Map,d=new Set;this.disabledNodes.forEach(j=>{d.add(j);const Y=this.driver.query(j,\".ng-animate-queued\",!0);for(let X=0;X<Y.length;X++)d.add(Y[X])});const u=this.bodyNode,h=Array.from(this.statesByElement.keys()),p=EM(h,this.collectedEnterElements),m=new Map;let g=0;p.forEach((j,Y)=>{const X=Zf+g++;m.set(Y,X),j.forEach(Se=>In(Se,X))});const _=[],D=new Set,v=new Set;for(let j=0;j<this.collectedLeaveElements.length;j++){const Y=this.collectedLeaveElements[j],X=Y[An];X&&X.setForRemoval&&(_.push(Y),D.add(Y),X.hasAnimation?this.driver.query(Y,\".ng-star-inserted\",!0).forEach(Se=>D.add(Se)):v.add(Y))}const M=new Map,V=EM(h,Array.from(D));V.forEach((j,Y)=>{const X=rd+g++;M.set(Y,X),j.forEach(Se=>In(Se,X))}),t.push(()=>{p.forEach((j,Y)=>{const X=m.get(Y);j.forEach(Se=>ro(Se,X))}),V.forEach((j,Y)=>{const X=M.get(Y);j.forEach(Se=>ro(Se,X))}),_.forEach(j=>{this.processLeaveNode(j)})});const he=[],We=[];for(let j=this._namespaceList.length-1;j>=0;j--)this._namespaceList[j].drainQueuedTransitions(e).forEach(X=>{const Se=X.player,St=X.element;if(he.push(Se),this.collectedEnterElements.length){const qt=St[An];if(qt&&qt.setForMove){if(qt.previousTriggersValues&&qt.previousTriggersValues.has(X.triggerName)){const is=qt.previousTriggersValues.get(X.triggerName),pr=this.statesByElement.get(X.element);pr&&pr[X.triggerName]&&(pr[X.triggerName].value=is)}return void Se.destroy()}}const wi=!u||!this.driver.containsElement(u,St),mn=M.get(St),hr=m.get(St),Xe=this._buildInstruction(X,i,hr,mn,wi);if(Xe.errors&&Xe.errors.length)return void We.push(Xe);if(wi)return Se.onStart(()=>zr(St,Xe.fromStyles)),Se.onDestroy(()=>vi(St,Xe.toStyles)),void r.push(Se);if(X.isFallbackTransition)return Se.onStart(()=>zr(St,Xe.fromStyles)),Se.onDestroy(()=>vi(St,Xe.toStyles)),void r.push(Se);const pk=[];Xe.timelines.forEach(qt=>{qt.stretchStartingKeyframe=!0,this.disabledNodes.has(qt.element)||pk.push(qt)}),Xe.timelines=pk,i.append(St,Xe.timelines),o.push({instruction:Xe,player:Se,element:St}),Xe.queriedElements.forEach(qt=>dn(a,qt,[]).push(Se)),Xe.preStyleProps.forEach((qt,is)=>{const pr=Object.keys(qt);if(pr.length){let rs=l.get(is);rs||l.set(is,rs=new Set),pr.forEach(Xg=>rs.add(Xg))}}),Xe.postStyleProps.forEach((qt,is)=>{const pr=Object.keys(qt);let rs=c.get(is);rs||c.set(is,rs=new Set),pr.forEach(Xg=>rs.add(Xg))})});if(We.length){const j=[];We.forEach(Y=>{j.push(function vH(n,t){return new H(3505,Ce)}())}),he.forEach(Y=>Y.destroy()),this.reportError(j)}const Ze=new Map,hn=new Map;o.forEach(j=>{const Y=j.element;i.has(Y)&&(hn.set(Y,Y),this._beforeAnimationBuild(j.player.namespaceId,j.instruction,Ze))}),r.forEach(j=>{const Y=j.element;this._getPreviousPlayers(Y,!1,j.namespaceId,j.triggerName,null).forEach(Se=>{dn(Ze,Y,[]).push(Se),Se.destroy()})});const pn=_.filter(j=>kM(j,l,c)),fn=new Map;xM(fn,this.driver,v,c,Vi).forEach(j=>{kM(j,l,c)&&pn.push(j)});const Gi=new Map;p.forEach((j,Y)=>{xM(Gi,this.driver,new Set(j),l,\"!\")}),pn.forEach(j=>{const Y=fn.get(j),X=Gi.get(j);fn.set(j,Object.assign(Object.assign({},Y),X))});const ii=[],wo=[],Mo={};o.forEach(j=>{const{element:Y,player:X,instruction:Se}=j;if(i.has(Y)){if(d.has(Y))return X.onDestroy(()=>vi(Y,Se.toStyles)),X.disabled=!0,X.overrideTotalTime(Se.totalTime),void r.push(X);let St=Mo;if(hn.size>1){let mn=Y;const hr=[];for(;mn=mn.parentNode;){const Xe=hn.get(mn);if(Xe){St=Xe;break}hr.push(mn)}hr.forEach(Xe=>hn.set(Xe,St))}const wi=this._buildAnimation(X.namespaceId,Se,Ze,s,Gi,fn);if(X.setRealPlayer(wi),St===Mo)ii.push(X);else{const mn=this.playersByElement.get(St);mn&&mn.length&&(X.parentPlayer=ir(mn)),r.push(X)}}else zr(Y,Se.fromStyles),X.onDestroy(()=>vi(Y,Se.toStyles)),wo.push(X),d.has(Y)&&r.push(X)}),wo.forEach(j=>{const Y=s.get(j.element);if(Y&&Y.length){const X=ir(Y);j.setRealPlayer(X)}}),r.forEach(j=>{j.parentPlayer?j.syncPlayerEvents(j.parentPlayer):j.destroy()});for(let j=0;j<_.length;j++){const Y=_[j],X=Y[An];if(ro(Y,rd),X&&X.hasAnimation)continue;let Se=[];if(a.size){let wi=a.get(Y);wi&&wi.length&&Se.push(...wi);let mn=this.driver.query(Y,Xf,!0);for(let hr=0;hr<mn.length;hr++){let Xe=a.get(mn[hr]);Xe&&Xe.length&&Se.push(...Xe)}}const St=Se.filter(wi=>!wi.destroyed);St.length?vj(this,Y,St):this.processLeaveNode(Y)}return _.length=0,ii.forEach(j=>{this.players.push(j),j.onDone(()=>{j.destroy();const Y=this.players.indexOf(j);this.players.splice(Y,1)}),j.play()}),ii}elementContainsData(t,e){let i=!1;const r=e[An];return r&&r.setForRemoval&&(i=!0),this.playersByElement.has(e)&&(i=!0),this.playersByQueriedElement.has(e)&&(i=!0),this.statesByElement.has(e)&&(i=!0),this._fetchNamespace(t).elementContainsData(e)||i}afterFlush(t){this._flushFns.push(t)}afterFlushAnimationsDone(t){this._whenQuietFns.push(t)}_getPreviousPlayers(t,e,i,r,s){let o=[];if(e){const a=this.playersByQueriedElement.get(t);a&&(o=a)}else{const a=this.playersByElement.get(t);if(a){const l=!s||s==Va;a.forEach(c=>{c.queued||!l&&c.triggerName!=r||o.push(c)})}}return(i||r)&&(o=o.filter(a=>!(i&&i!=a.namespaceId||r&&r!=a.triggerName))),o}_beforeAnimationBuild(t,e,i){const s=e.element,o=e.isRemovalTransition?void 0:t,a=e.isRemovalTransition?void 0:e.triggerName;for(const l of e.timelines){const c=l.element,d=c!==s,u=dn(i,c,[]);this._getPreviousPlayers(c,d,o,a,e.toState).forEach(p=>{const m=p.getRealPlayer();m.beforeDestroy&&m.beforeDestroy(),p.destroy(),u.push(p)})}zr(s,e.fromStyles)}_buildAnimation(t,e,i,r,s,o){const a=e.triggerName,l=e.element,c=[],d=new Set,u=new Set,h=e.timelines.map(m=>{const g=m.element;d.add(g);const _=g[An];if(_&&_.removedBeforeQueried)return new La(m.duration,m.delay);const D=g!==l,v=function yj(n){const t=[];return SM(n,t),t}((i.get(g)||uj).map(Ze=>Ze.getRealPlayer())).filter(Ze=>!!Ze.element&&Ze.element===g),M=s.get(g),V=o.get(g),he=Jw(0,this._normalizer,0,m.keyframes,M,V),We=this._buildPlayer(m,he,v);if(m.subTimeline&&r&&u.add(g),D){const Ze=new hm(t,a,g);Ze.setRealPlayer(We),c.push(Ze)}return We});c.forEach(m=>{dn(this.playersByQueriedElement,m.element,[]).push(m),m.onDone(()=>function mj(n,t,e){let i;if(n instanceof Map){if(i=n.get(t),i){if(i.length){const r=i.indexOf(e);i.splice(r,1)}0==i.length&&n.delete(t)}}else if(i=n[t],i){if(i.length){const r=i.indexOf(e);i.splice(r,1)}0==i.length&&delete n[t]}return i}(this.playersByQueriedElement,m.element,m))}),d.forEach(m=>In(m,cM));const p=ir(h);return p.onDestroy(()=>{d.forEach(m=>ro(m,cM)),vi(l,e.toStyles)}),u.forEach(m=>{dn(r,m,[]).push(p)}),p}_buildPlayer(t,e,i){return e.length>0?this.driver.animate(t.element,e,t.duration,t.delay,t.easing,i):new La(t.duration,t.delay)}}class hm{constructor(t,e,i){this.namespaceId=t,this.triggerName=e,this.element=i,this._player=new La,this._containsRealPlayer=!1,this._queuedCallbacks={},this.destroyed=!1,this.markedForDestroy=!1,this.disabled=!1,this.queued=!0,this.totalTime=0}setRealPlayer(t){this._containsRealPlayer||(this._player=t,Object.keys(this._queuedCallbacks).forEach(e=>{this._queuedCallbacks[e].forEach(i=>Gf(t,e,void 0,i))}),this._queuedCallbacks={},this._containsRealPlayer=!0,this.overrideTotalTime(t.totalTime),this.queued=!1)}getRealPlayer(){return this._player}overrideTotalTime(t){this.totalTime=t}syncPlayerEvents(t){const e=this._player;e.triggerCallback&&t.onStart(()=>e.triggerCallback(\"start\")),t.onDone(()=>this.finish()),t.onDestroy(()=>this.destroy())}_queueEvent(t,e){dn(this._queuedCallbacks,t,[]).push(e)}onDone(t){this.queued&&this._queueEvent(\"done\",t),this._player.onDone(t)}onStart(t){this.queued&&this._queueEvent(\"start\",t),this._player.onStart(t)}onDestroy(t){this.queued&&this._queueEvent(\"destroy\",t),this._player.onDestroy(t)}init(){this._player.init()}hasStarted(){return!this.queued&&this._player.hasStarted()}play(){!this.queued&&this._player.play()}pause(){!this.queued&&this._player.pause()}restart(){!this.queued&&this._player.restart()}finish(){this._player.finish()}destroy(){this.destroyed=!0,this._player.destroy()}reset(){!this.queued&&this._player.reset()}setPosition(t){this.queued||this._player.setPosition(t)}getPosition(){return this.queued?0:this._player.getPosition()}triggerCallback(t){const e=this._player;e.triggerCallback&&e.triggerCallback(t)}}function yd(n){return n&&1===n.nodeType}function MM(n,t){const e=n.style.display;return n.style.display=null!=t?t:\"none\",e}function xM(n,t,e,i,r){const s=[];e.forEach(l=>s.push(MM(l)));const o=[];i.forEach((l,c)=>{const d={};l.forEach(u=>{const h=d[u]=t.computeStyle(c,u,r);(!h||0==h.length)&&(c[An]=hj,o.push(c))}),n.set(c,d)});let a=0;return e.forEach(l=>MM(l,s[a++])),o}function EM(n,t){const e=new Map;if(n.forEach(a=>e.set(a,[])),0==t.length)return e;const r=new Set(t),s=new Map;function o(a){if(!a)return 1;let l=s.get(a);if(l)return l;const c=a.parentNode;return l=e.has(c)?c:r.has(c)?1:o(c),s.set(a,l),l}return t.forEach(a=>{const l=o(a);1!==l&&e.get(l).push(a)}),e}function In(n,t){var e;null===(e=n.classList)||void 0===e||e.add(t)}function ro(n,t){var e;null===(e=n.classList)||void 0===e||e.remove(t)}function vj(n,t,e){ir(e).onDone(()=>n.processLeaveNode(t))}function SM(n,t){for(let e=0;e<n.length;e++){const i=n[e];i instanceof Zw?SM(i.players,t):t.push(i)}}function kM(n,t,e){const i=e.get(n);if(!i)return!1;let r=t.get(n);return r?i.forEach(s=>r.add(s)):t.set(n,i),e.delete(n),!0}class bd{constructor(t,e,i){this.bodyNode=t,this._driver=e,this._normalizer=i,this._triggerCache={},this.onRemovalComplete=(r,s)=>{},this._transitionEngine=new fj(t,e,i),this._timelineEngine=new oj(t,e,i),this._transitionEngine.onRemovalComplete=(r,s)=>this.onRemovalComplete(r,s)}registerTrigger(t,e,i,r,s){const o=t+\"-\"+r;let a=this._triggerCache[o];if(!a){const l=[],d=nm(this._driver,s,l,[]);if(l.length)throw function aH(n,t){return new H(3404,Ce)}();a=function nj(n,t,e){return new ij(n,t,e)}(r,d,this._normalizer),this._triggerCache[o]=a}this._transitionEngine.registerTrigger(e,r,a)}register(t,e){this._transitionEngine.register(t,e)}destroy(t,e){this._transitionEngine.destroy(t,e)}onInsert(t,e,i,r){this._transitionEngine.insertNode(t,e,i,r)}onRemove(t,e,i,r){this._transitionEngine.removeNode(t,e,r||!1,i)}disableAnimations(t,e){this._transitionEngine.markElementAsDisabled(t,e)}process(t,e,i,r){if(\"@\"==i.charAt(0)){const[s,o]=eM(i);this._timelineEngine.command(s,e,o,r)}else this._transitionEngine.trigger(t,e,i,r)}listen(t,e,i,r,s){if(\"@\"==i.charAt(0)){const[o,a]=eM(i);return this._timelineEngine.listen(o,e,a,s)}return this._transitionEngine.listen(t,e,i,r,s)}flush(t=-1){this._transitionEngine.flush(t)}get players(){return this._transitionEngine.players.concat(this._timelineEngine.players)}whenRenderingDone(){return this._transitionEngine.whenRenderingDone()}}let Dj=(()=>{class n{constructor(e,i,r){this._element=e,this._startStyles=i,this._endStyles=r,this._state=0;let s=n.initialStylesByElement.get(e);s||n.initialStylesByElement.set(e,s={}),this._initialStyles=s}start(){this._state<1&&(this._startStyles&&vi(this._element,this._startStyles,this._initialStyles),this._state=1)}finish(){this.start(),this._state<2&&(vi(this._element,this._initialStyles),this._endStyles&&(vi(this._element,this._endStyles),this._endStyles=null),this._state=1)}destroy(){this.finish(),this._state<3&&(n.initialStylesByElement.delete(this._element),this._startStyles&&(zr(this._element,this._startStyles),this._endStyles=null),this._endStyles&&(zr(this._element,this._endStyles),this._endStyles=null),vi(this._element,this._initialStyles),this._state=3)}}return n.initialStylesByElement=new WeakMap,n})();function pm(n){let t=null;const e=Object.keys(n);for(let i=0;i<e.length;i++){const r=e[i];wj(r)&&(t=t||{},t[r]=n[r])}return t}function wj(n){return\"display\"===n||\"position\"===n}class TM{constructor(t,e,i,r){this.element=t,this.keyframes=e,this.options=i,this._specialStyles=r,this._onDoneFns=[],this._onStartFns=[],this._onDestroyFns=[],this._initialized=!1,this._finished=!1,this._started=!1,this._destroyed=!1,this.time=0,this.parentPlayer=null,this.currentSnapshot={},this._duration=i.duration,this._delay=i.delay||0,this.time=this._duration+this._delay}_onFinish(){this._finished||(this._finished=!0,this._onDoneFns.forEach(t=>t()),this._onDoneFns=[])}init(){this._buildPlayer(),this._preparePlayerBeforeStart()}_buildPlayer(){if(this._initialized)return;this._initialized=!0;const t=this.keyframes;this.domPlayer=this._triggerWebAnimation(this.element,t,this.options),this._finalKeyframe=t.length?t[t.length-1]:{},this.domPlayer.addEventListener(\"finish\",()=>this._onFinish())}_preparePlayerBeforeStart(){this._delay?this._resetDomPlayerState():this.domPlayer.pause()}_triggerWebAnimation(t,e,i){return t.animate(e,i)}onStart(t){this._onStartFns.push(t)}onDone(t){this._onDoneFns.push(t)}onDestroy(t){this._onDestroyFns.push(t)}play(){this._buildPlayer(),this.hasStarted()||(this._onStartFns.forEach(t=>t()),this._onStartFns=[],this._started=!0,this._specialStyles&&this._specialStyles.start()),this.domPlayer.play()}pause(){this.init(),this.domPlayer.pause()}finish(){this.init(),this._specialStyles&&this._specialStyles.finish(),this._onFinish(),this.domPlayer.finish()}reset(){this._resetDomPlayerState(),this._destroyed=!1,this._finished=!1,this._started=!1}_resetDomPlayerState(){this.domPlayer&&this.domPlayer.cancel()}restart(){this.reset(),this.play()}hasStarted(){return this._started}destroy(){this._destroyed||(this._destroyed=!0,this._resetDomPlayerState(),this._onFinish(),this._specialStyles&&this._specialStyles.destroy(),this._onDestroyFns.forEach(t=>t()),this._onDestroyFns=[])}setPosition(t){void 0===this.domPlayer&&this.init(),this.domPlayer.currentTime=t*this.time}getPosition(){return this.domPlayer.currentTime/this.time}get totalTime(){return this._delay+this._duration}beforeDestroy(){const t={};if(this.hasStarted()){const e=this._finalKeyframe;Object.keys(e).forEach(i=>{\"offset\"!=i&&(t[i]=this._finished?e[i]:fM(this.element,i))})}this.currentSnapshot=t}triggerCallback(t){const e=\"start\"==t?this._onStartFns:this._onDoneFns;e.forEach(i=>i()),e.length=0}}class Mj{validateStyleProperty(t){return rM(t)}matchesElement(t,e){return!1}containsElement(t,e){return sM(t,e)}getParentElement(t){return Qf(t)}query(t,e,i){return oM(t,e,i)}computeStyle(t,e,i){return window.getComputedStyle(t)[e]}animate(t,e,i,r,s,o=[]){const l={duration:i,delay:r,fill:0==r?\"both\":\"forwards\"};s&&(l.easing=s);const c={},d=o.filter(h=>h instanceof TM);(function kH(n,t){return 0===n||0===t})(i,r)&&d.forEach(h=>{let p=h.currentSnapshot;Object.keys(p).forEach(m=>c[m]=p[m])}),e=function TH(n,t,e){const i=Object.keys(e);if(i.length&&t.length){let s=t[0],o=[];if(i.forEach(a=>{s.hasOwnProperty(a)||o.push(a),s[a]=e[a]}),o.length)for(var r=1;r<t.length;r++){let a=t[r];o.forEach(function(l){a[l]=fM(n,l)})}}return t}(t,e=e.map(h=>rr(h,!1)),c);const u=function Cj(n,t){let e=null,i=null;return Array.isArray(t)&&t.length?(e=pm(t[0]),t.length>1&&(i=pm(t[t.length-1]))):t&&(e=pm(t)),e||i?new Dj(n,e,i):null}(t,e);return new TM(t,e,l,u)}}let xj=(()=>{class n extends Yw{constructor(e,i){super(),this._nextAnimationId=0,this._renderer=e.createRenderer(i.body,{id:\"0\",encapsulation:Ln.None,styles:[],data:{animation:[]}})}build(e){const i=this._nextAnimationId.toString();this._nextAnimationId++;const r=Array.isArray(e)?Qw(e):e;return AM(this._renderer,null,i,\"register\",[r]),new Ej(i,this._renderer)}}return n.\\u0275fac=function(e){return new(e||n)(y(da),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class Ej extends class V2{}{constructor(t,e){super(),this._id=t,this._renderer=e}create(t,e){return new Sj(this._id,t,e||{},this._renderer)}}class Sj{constructor(t,e,i,r){this.id=t,this.element=e,this._renderer=r,this.parentPlayer=null,this._started=!1,this.totalTime=0,this._command(\"create\",i)}_listen(t,e){return this._renderer.listen(this.element,`@@${this.id}:${t}`,e)}_command(t,...e){return AM(this._renderer,this.element,this.id,t,e)}onDone(t){this._listen(\"done\",t)}onStart(t){this._listen(\"start\",t)}onDestroy(t){this._listen(\"destroy\",t)}init(){this._command(\"init\")}hasStarted(){return this._started}play(){this._command(\"play\"),this._started=!0}pause(){this._command(\"pause\")}restart(){this._command(\"restart\")}finish(){this._command(\"finish\")}destroy(){this._command(\"destroy\")}reset(){this._command(\"reset\"),this._started=!1}setPosition(t){this._command(\"setPosition\",t)}getPosition(){var t,e;return null!==(e=null===(t=this._renderer.engine.players[+this.id])||void 0===t?void 0:t.getPosition())&&void 0!==e?e:0}}function AM(n,t,e,i,r){return n.setProperty(t,`@@${e}:${i}`,r)}const IM=\"@.disabled\";let kj=(()=>{class n{constructor(e,i,r){this.delegate=e,this.engine=i,this._zone=r,this._currentId=0,this._microtaskId=1,this._animationCallbacksBuffer=[],this._rendererCache=new Map,this._cdRecurDepth=0,this.promise=Promise.resolve(0),i.onRemovalComplete=(s,o)=>{const a=null==o?void 0:o.parentNode(s);a&&o.removeChild(a,s)}}createRenderer(e,i){const s=this.delegate.createRenderer(e,i);if(!(e&&i&&i.data&&i.data.animation)){let d=this._rendererCache.get(s);return d||(d=new RM(\"\",s,this.engine),this._rendererCache.set(s,d)),d}const o=i.id,a=i.id+\"-\"+this._currentId;this._currentId++,this.engine.register(a,e);const l=d=>{Array.isArray(d)?d.forEach(l):this.engine.registerTrigger(o,a,e,d.name,d)};return i.data.animation.forEach(l),new Tj(this,a,s,this.engine)}begin(){this._cdRecurDepth++,this.delegate.begin&&this.delegate.begin()}_scheduleCountTask(){this.promise.then(()=>{this._microtaskId++})}scheduleListenerCallback(e,i,r){e>=0&&e<this._microtaskId?this._zone.run(()=>i(r)):(0==this._animationCallbacksBuffer.length&&Promise.resolve(null).then(()=>{this._zone.run(()=>{this._animationCallbacksBuffer.forEach(s=>{const[o,a]=s;o(a)}),this._animationCallbacksBuffer=[]})}),this._animationCallbacksBuffer.push([i,r]))}end(){this._cdRecurDepth--,0==this._cdRecurDepth&&this._zone.runOutsideAngular(()=>{this._scheduleCountTask(),this.engine.flush(this._microtaskId)}),this.delegate.end&&this.delegate.end()}whenRenderingDone(){return this.engine.whenRenderingDone()}}return n.\\u0275fac=function(e){return new(e||n)(y(da),y(bd),y(ne))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class RM{constructor(t,e,i){this.namespaceId=t,this.delegate=e,this.engine=i,this.destroyNode=this.delegate.destroyNode?r=>e.destroyNode(r):null}get data(){return this.delegate.data}destroy(){this.engine.destroy(this.namespaceId,this.delegate),this.delegate.destroy()}createElement(t,e){return this.delegate.createElement(t,e)}createComment(t){return this.delegate.createComment(t)}createText(t){return this.delegate.createText(t)}appendChild(t,e){this.delegate.appendChild(t,e),this.engine.onInsert(this.namespaceId,e,t,!1)}insertBefore(t,e,i,r=!0){this.delegate.insertBefore(t,e,i),this.engine.onInsert(this.namespaceId,e,t,r)}removeChild(t,e,i){this.engine.onRemove(this.namespaceId,e,this.delegate,i)}selectRootElement(t,e){return this.delegate.selectRootElement(t,e)}parentNode(t){return this.delegate.parentNode(t)}nextSibling(t){return this.delegate.nextSibling(t)}setAttribute(t,e,i,r){this.delegate.setAttribute(t,e,i,r)}removeAttribute(t,e,i){this.delegate.removeAttribute(t,e,i)}addClass(t,e){this.delegate.addClass(t,e)}removeClass(t,e){this.delegate.removeClass(t,e)}setStyle(t,e,i,r){this.delegate.setStyle(t,e,i,r)}removeStyle(t,e,i){this.delegate.removeStyle(t,e,i)}setProperty(t,e,i){\"@\"==e.charAt(0)&&e==IM?this.disableAnimations(t,!!i):this.delegate.setProperty(t,e,i)}setValue(t,e){this.delegate.setValue(t,e)}listen(t,e,i){return this.delegate.listen(t,e,i)}disableAnimations(t,e){this.engine.disableAnimations(t,e)}}class Tj extends RM{constructor(t,e,i,r){super(e,i,r),this.factory=t,this.namespaceId=e}setProperty(t,e,i){\"@\"==e.charAt(0)?\".\"==e.charAt(1)&&e==IM?this.disableAnimations(t,i=void 0===i||!!i):this.engine.process(this.namespaceId,t,e.substr(1),i):this.delegate.setProperty(t,e,i)}listen(t,e,i){if(\"@\"==e.charAt(0)){const r=function Aj(n){switch(n){case\"body\":return document.body;case\"document\":return document;case\"window\":return window;default:return n}}(t);let s=e.substr(1),o=\"\";return\"@\"!=s.charAt(0)&&([s,o]=function Ij(n){const t=n.indexOf(\".\");return[n.substring(0,t),n.substr(t+1)]}(s)),this.engine.listen(this.namespaceId,r,s,o,a=>{this.factory.scheduleListenerCallback(a._data||-1,i,a)})}return this.delegate.listen(t,e,i)}}let Rj=(()=>{class n extends bd{constructor(e,i,r){super(e.body,i,r)}ngOnDestroy(){this.flush()}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(Kf),y(am))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const Rn=new b(\"AnimationModuleType\"),OM=[{provide:Yw,useClass:xj},{provide:am,useFactory:function Oj(){return new ZH}},{provide:bd,useClass:Rj},{provide:da,useFactory:function Pj(n,t,e){return new kj(n,t,e)},deps:[Vc,bd,ne]}],PM=[{provide:Kf,useFactory:()=>new Mj},{provide:Rn,useValue:\"BrowserAnimations\"},...OM],Fj=[{provide:Kf,useClass:aM},{provide:Rn,useValue:\"NoopAnimations\"},...OM];let Nj=(()=>{class n{static withConfig(e){return{ngModule:n,providers:e.disableAnimations?Fj:PM}}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:PM,imports:[FD]}),n})();let NM=(()=>{class n{constructor(e,i){this._renderer=e,this._elementRef=i,this.onChange=r=>{},this.onTouched=()=>{}}setProperty(e,i){this._renderer.setProperty(this._elementRef.nativeElement,e,i)}registerOnTouched(e){this.onTouched=e}registerOnChange(e){this.onChange=e}setDisabledState(e){this.setProperty(\"disabled\",e)}}return n.\\u0275fac=function(e){return new(e||n)(f(Ii),f(W))},n.\\u0275dir=C({type:n}),n})(),$r=(()=>{class n extends NM{}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275dir=C({type:n,features:[E]}),n})();const xt=new b(\"NgValueAccessor\"),Bj={provide:xt,useExisting:pe(()=>Dd),multi:!0},Hj=new b(\"CompositionEventMode\");let Dd=(()=>{class n extends NM{constructor(e,i,r){super(e,i),this._compositionMode=r,this._composing=!1,null==this._compositionMode&&(this._compositionMode=!function Vj(){const n=mi()?mi().getUserAgent():\"\";return/android (\\d+)/.test(n.toLowerCase())}())}writeValue(e){this.setProperty(\"value\",null==e?\"\":e)}_handleInput(e){(!this._compositionMode||this._compositionMode&&!this._composing)&&this.onChange(e)}_compositionStart(){this._composing=!0}_compositionEnd(e){this._composing=!1,this._compositionMode&&this.onChange(e)}}return n.\\u0275fac=function(e){return new(e||n)(f(Ii),f(W),f(Hj,8))},n.\\u0275dir=C({type:n,selectors:[[\"input\",\"formControlName\",\"\",3,\"type\",\"checkbox\"],[\"textarea\",\"formControlName\",\"\"],[\"input\",\"formControl\",\"\",3,\"type\",\"checkbox\"],[\"textarea\",\"formControl\",\"\"],[\"input\",\"ngModel\",\"\",3,\"type\",\"checkbox\"],[\"textarea\",\"ngModel\",\"\"],[\"\",\"ngDefaultControl\",\"\"]],hostBindings:function(e,i){1&e&&J(\"input\",function(s){return i._handleInput(s.target.value)})(\"blur\",function(){return i.onTouched()})(\"compositionstart\",function(){return i._compositionStart()})(\"compositionend\",function(s){return i._compositionEnd(s.target.value)})},features:[L([Bj]),E]}),n})();function sr(n){return null==n||0===n.length}function BM(n){return null!=n&&\"number\"==typeof n.length}const Dt=new b(\"NgValidators\"),or=new b(\"NgAsyncValidators\"),jj=/^(?=.{1,254}$)(?=.{1,64}@)[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;class yi{static min(t){return function VM(n){return t=>{if(sr(t.value)||sr(n))return null;const e=parseFloat(t.value);return!isNaN(e)&&e<n?{min:{min:n,actual:t.value}}:null}}(t)}static max(t){return function HM(n){return t=>{if(sr(t.value)||sr(n))return null;const e=parseFloat(t.value);return!isNaN(e)&&e>n?{max:{max:n,actual:t.value}}:null}}(t)}static required(t){return function jM(n){return sr(n.value)?{required:!0}:null}(t)}static requiredTrue(t){return function zM(n){return!0===n.value?null:{required:!0}}(t)}static email(t){return function UM(n){return sr(n.value)||jj.test(n.value)?null:{email:!0}}(t)}static minLength(t){return function $M(n){return t=>sr(t.value)||!BM(t.value)?null:t.value.length<n?{minlength:{requiredLength:n,actualLength:t.value.length}}:null}(t)}static maxLength(t){return function GM(n){return t=>BM(t.value)&&t.value.length>n?{maxlength:{requiredLength:n,actualLength:t.value.length}}:null}(t)}static pattern(t){return function WM(n){if(!n)return wd;let t,e;return\"string\"==typeof n?(e=\"\",\"^\"!==n.charAt(0)&&(e+=\"^\"),e+=n,\"$\"!==n.charAt(n.length-1)&&(e+=\"$\"),t=new RegExp(e)):(e=n.toString(),t=n),i=>{if(sr(i.value))return null;const r=i.value;return t.test(r)?null:{pattern:{requiredPattern:e,actualValue:r}}}}(t)}static nullValidator(t){return null}static compose(t){return XM(t)}static composeAsync(t){return JM(t)}}function wd(n){return null}function qM(n){return null!=n}function YM(n){const t=ra(n)?mt(n):n;return up(t),t}function QM(n){let t={};return n.forEach(e=>{t=null!=e?Object.assign(Object.assign({},t),e):t}),0===Object.keys(t).length?null:t}function KM(n,t){return t.map(e=>e(n))}function ZM(n){return n.map(t=>function zj(n){return!n.validate}(t)?t:e=>t.validate(e))}function XM(n){if(!n)return null;const t=n.filter(qM);return 0==t.length?null:function(e){return QM(KM(e,t))}}function fm(n){return null!=n?XM(ZM(n)):null}function JM(n){if(!n)return null;const t=n.filter(qM);return 0==t.length?null:function(e){return function FM(...n){const t=b_(n),{args:e,keys:i}=VD(n),r=new Ve(s=>{const{length:o}=e;if(!o)return void s.complete();const a=new Array(o);let l=o,c=o;for(let d=0;d<o;d++){let u=!1;Jt(e[d]).subscribe(Ue(s,h=>{u||(u=!0,c--),a[d]=h},()=>l--,void 0,()=>{(!l||!u)&&(c||s.next(i?HD(i,a):a),s.complete())}))}});return t?r.pipe(bf(t)):r}(KM(e,t).map(YM)).pipe(ue(QM))}}function mm(n){return null!=n?JM(ZM(n)):null}function ex(n,t){return null===n?[t]:Array.isArray(n)?[...n,t]:[n,t]}function tx(n){return n._rawValidators}function nx(n){return n._rawAsyncValidators}function gm(n){return n?Array.isArray(n)?n:[n]:[]}function Md(n,t){return Array.isArray(n)?n.includes(t):n===t}function ix(n,t){const e=gm(t);return gm(n).forEach(r=>{Md(e,r)||e.push(r)}),e}function rx(n,t){return gm(t).filter(e=>!Md(n,e))}class sx{constructor(){this._rawValidators=[],this._rawAsyncValidators=[],this._onDestroyCallbacks=[]}get value(){return this.control?this.control.value:null}get valid(){return this.control?this.control.valid:null}get invalid(){return this.control?this.control.invalid:null}get pending(){return this.control?this.control.pending:null}get disabled(){return this.control?this.control.disabled:null}get enabled(){return this.control?this.control.enabled:null}get errors(){return this.control?this.control.errors:null}get pristine(){return this.control?this.control.pristine:null}get dirty(){return this.control?this.control.dirty:null}get touched(){return this.control?this.control.touched:null}get status(){return this.control?this.control.status:null}get untouched(){return this.control?this.control.untouched:null}get statusChanges(){return this.control?this.control.statusChanges:null}get valueChanges(){return this.control?this.control.valueChanges:null}get path(){return null}_setValidators(t){this._rawValidators=t||[],this._composedValidatorFn=fm(this._rawValidators)}_setAsyncValidators(t){this._rawAsyncValidators=t||[],this._composedAsyncValidatorFn=mm(this._rawAsyncValidators)}get validator(){return this._composedValidatorFn||null}get asyncValidator(){return this._composedAsyncValidatorFn||null}_registerOnDestroy(t){this._onDestroyCallbacks.push(t)}_invokeOnDestroyCallbacks(){this._onDestroyCallbacks.forEach(t=>t()),this._onDestroyCallbacks=[]}reset(t){this.control&&this.control.reset(t)}hasError(t,e){return!!this.control&&this.control.hasError(t,e)}getError(t,e){return this.control?this.control.getError(t,e):null}}class Jn extends sx{constructor(){super(...arguments),this._parent=null,this.name=null,this.valueAccessor=null}}class Wt extends sx{get formDirective(){return null}get path(){return null}}let ax=(()=>{class n extends class ox{constructor(t){this._cd=t}is(t){var e,i,r;return\"submitted\"===t?!!(null===(e=this._cd)||void 0===e?void 0:e.submitted):!!(null===(r=null===(i=this._cd)||void 0===i?void 0:i.control)||void 0===r?void 0:r[t])}}{constructor(e){super(e)}}return n.\\u0275fac=function(e){return new(e||n)(f(Jn,2))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"formControlName\",\"\"],[\"\",\"ngModel\",\"\"],[\"\",\"formControl\",\"\"]],hostVars:14,hostBindings:function(e,i){2&e&&Ae(\"ng-untouched\",i.is(\"untouched\"))(\"ng-touched\",i.is(\"touched\"))(\"ng-pristine\",i.is(\"pristine\"))(\"ng-dirty\",i.is(\"dirty\"))(\"ng-valid\",i.is(\"valid\"))(\"ng-invalid\",i.is(\"invalid\"))(\"ng-pending\",i.is(\"pending\"))},features:[E]}),n})();function Ha(n,t){ym(n,t),t.valueAccessor.writeValue(n.value),function Zj(n,t){t.valueAccessor.registerOnChange(e=>{n._pendingValue=e,n._pendingChange=!0,n._pendingDirty=!0,\"change\"===n.updateOn&&cx(n,t)})}(n,t),function Jj(n,t){const e=(i,r)=>{t.valueAccessor.writeValue(i),r&&t.viewToModelUpdate(i)};n.registerOnChange(e),t._registerOnDestroy(()=>{n._unregisterOnChange(e)})}(n,t),function Xj(n,t){t.valueAccessor.registerOnTouched(()=>{n._pendingTouched=!0,\"blur\"===n.updateOn&&n._pendingChange&&cx(n,t),\"submit\"!==n.updateOn&&n.markAsTouched()})}(n,t),function Kj(n,t){if(t.valueAccessor.setDisabledState){const e=i=>{t.valueAccessor.setDisabledState(i)};n.registerOnDisabledChange(e),t._registerOnDestroy(()=>{n._unregisterOnDisabledChange(e)})}}(n,t)}function Sd(n,t,e=!0){const i=()=>{};t.valueAccessor&&(t.valueAccessor.registerOnChange(i),t.valueAccessor.registerOnTouched(i)),Td(n,t),n&&(t._invokeOnDestroyCallbacks(),n._registerOnCollectionChange(()=>{}))}function kd(n,t){n.forEach(e=>{e.registerOnValidatorChange&&e.registerOnValidatorChange(t)})}function ym(n,t){const e=tx(n);null!==t.validator?n.setValidators(ex(e,t.validator)):\"function\"==typeof e&&n.setValidators([e]);const i=nx(n);null!==t.asyncValidator?n.setAsyncValidators(ex(i,t.asyncValidator)):\"function\"==typeof i&&n.setAsyncValidators([i]);const r=()=>n.updateValueAndValidity();kd(t._rawValidators,r),kd(t._rawAsyncValidators,r)}function Td(n,t){let e=!1;if(null!==n){if(null!==t.validator){const r=tx(n);if(Array.isArray(r)&&r.length>0){const s=r.filter(o=>o!==t.validator);s.length!==r.length&&(e=!0,n.setValidators(s))}}if(null!==t.asyncValidator){const r=nx(n);if(Array.isArray(r)&&r.length>0){const s=r.filter(o=>o!==t.asyncValidator);s.length!==r.length&&(e=!0,n.setAsyncValidators(s))}}}const i=()=>{};return kd(t._rawValidators,i),kd(t._rawAsyncValidators,i),e}function cx(n,t){n._pendingDirty&&n.markAsDirty(),n.setValue(n._pendingValue,{emitModelToViewChange:!1}),t.viewToModelUpdate(n._pendingValue),n._pendingChange=!1}function dx(n,t){ym(n,t)}function hx(n,t){n._syncPendingControls(),t.forEach(e=>{const i=e.control;\"submit\"===i.updateOn&&i._pendingChange&&(e.viewToModelUpdate(i._pendingValue),i._pendingChange=!1)})}function Dm(n,t){const e=n.indexOf(t);e>-1&&n.splice(e,1)}const ja=\"VALID\",Ad=\"INVALID\",so=\"PENDING\",za=\"DISABLED\";function Mm(n){return(Id(n)?n.validators:n)||null}function px(n){return Array.isArray(n)?fm(n):n||null}function xm(n,t){return(Id(t)?t.asyncValidators:n)||null}function fx(n){return Array.isArray(n)?mm(n):n||null}function Id(n){return null!=n&&!Array.isArray(n)&&\"object\"==typeof n}const mx=n=>n instanceof Rd,Em=n=>n instanceof km;function gx(n){return mx(n)?n.value:n.getRawValue()}function _x(n,t){const e=Em(n),i=n.controls;if(!(e?Object.keys(i):i).length)throw new H(1e3,\"\");if(!i[t])throw new H(1001,\"\")}function vx(n,t){Em(n),n._forEachChild((i,r)=>{if(void 0===t[r])throw new H(1002,\"\")})}class Sm{constructor(t,e){this._pendingDirty=!1,this._hasOwnPendingAsyncValidator=!1,this._pendingTouched=!1,this._onCollectionChange=()=>{},this._parent=null,this.pristine=!0,this.touched=!1,this._onDisabledChange=[],this._rawValidators=t,this._rawAsyncValidators=e,this._composedValidatorFn=px(this._rawValidators),this._composedAsyncValidatorFn=fx(this._rawAsyncValidators)}get validator(){return this._composedValidatorFn}set validator(t){this._rawValidators=this._composedValidatorFn=t}get asyncValidator(){return this._composedAsyncValidatorFn}set asyncValidator(t){this._rawAsyncValidators=this._composedAsyncValidatorFn=t}get parent(){return this._parent}get valid(){return this.status===ja}get invalid(){return this.status===Ad}get pending(){return this.status==so}get disabled(){return this.status===za}get enabled(){return this.status!==za}get dirty(){return!this.pristine}get untouched(){return!this.touched}get updateOn(){return this._updateOn?this._updateOn:this.parent?this.parent.updateOn:\"change\"}setValidators(t){this._rawValidators=t,this._composedValidatorFn=px(t)}setAsyncValidators(t){this._rawAsyncValidators=t,this._composedAsyncValidatorFn=fx(t)}addValidators(t){this.setValidators(ix(t,this._rawValidators))}addAsyncValidators(t){this.setAsyncValidators(ix(t,this._rawAsyncValidators))}removeValidators(t){this.setValidators(rx(t,this._rawValidators))}removeAsyncValidators(t){this.setAsyncValidators(rx(t,this._rawAsyncValidators))}hasValidator(t){return Md(this._rawValidators,t)}hasAsyncValidator(t){return Md(this._rawAsyncValidators,t)}clearValidators(){this.validator=null}clearAsyncValidators(){this.asyncValidator=null}markAsTouched(t={}){this.touched=!0,this._parent&&!t.onlySelf&&this._parent.markAsTouched(t)}markAllAsTouched(){this.markAsTouched({onlySelf:!0}),this._forEachChild(t=>t.markAllAsTouched())}markAsUntouched(t={}){this.touched=!1,this._pendingTouched=!1,this._forEachChild(e=>{e.markAsUntouched({onlySelf:!0})}),this._parent&&!t.onlySelf&&this._parent._updateTouched(t)}markAsDirty(t={}){this.pristine=!1,this._parent&&!t.onlySelf&&this._parent.markAsDirty(t)}markAsPristine(t={}){this.pristine=!0,this._pendingDirty=!1,this._forEachChild(e=>{e.markAsPristine({onlySelf:!0})}),this._parent&&!t.onlySelf&&this._parent._updatePristine(t)}markAsPending(t={}){this.status=so,!1!==t.emitEvent&&this.statusChanges.emit(this.status),this._parent&&!t.onlySelf&&this._parent.markAsPending(t)}disable(t={}){const e=this._parentMarkedDirty(t.onlySelf);this.status=za,this.errors=null,this._forEachChild(i=>{i.disable(Object.assign(Object.assign({},t),{onlySelf:!0}))}),this._updateValue(),!1!==t.emitEvent&&(this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._updateAncestors(Object.assign(Object.assign({},t),{skipPristineCheck:e})),this._onDisabledChange.forEach(i=>i(!0))}enable(t={}){const e=this._parentMarkedDirty(t.onlySelf);this.status=ja,this._forEachChild(i=>{i.enable(Object.assign(Object.assign({},t),{onlySelf:!0}))}),this.updateValueAndValidity({onlySelf:!0,emitEvent:t.emitEvent}),this._updateAncestors(Object.assign(Object.assign({},t),{skipPristineCheck:e})),this._onDisabledChange.forEach(i=>i(!1))}_updateAncestors(t){this._parent&&!t.onlySelf&&(this._parent.updateValueAndValidity(t),t.skipPristineCheck||this._parent._updatePristine(),this._parent._updateTouched())}setParent(t){this._parent=t}updateValueAndValidity(t={}){this._setInitialStatus(),this._updateValue(),this.enabled&&(this._cancelExistingSubscription(),this.errors=this._runValidator(),this.status=this._calculateStatus(),(this.status===ja||this.status===so)&&this._runAsyncValidator(t.emitEvent)),!1!==t.emitEvent&&(this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._parent&&!t.onlySelf&&this._parent.updateValueAndValidity(t)}_updateTreeValidity(t={emitEvent:!0}){this._forEachChild(e=>e._updateTreeValidity(t)),this.updateValueAndValidity({onlySelf:!0,emitEvent:t.emitEvent})}_setInitialStatus(){this.status=this._allControlsDisabled()?za:ja}_runValidator(){return this.validator?this.validator(this):null}_runAsyncValidator(t){if(this.asyncValidator){this.status=so,this._hasOwnPendingAsyncValidator=!0;const e=YM(this.asyncValidator(this));this._asyncValidationSubscription=e.subscribe(i=>{this._hasOwnPendingAsyncValidator=!1,this.setErrors(i,{emitEvent:t})})}}_cancelExistingSubscription(){this._asyncValidationSubscription&&(this._asyncValidationSubscription.unsubscribe(),this._hasOwnPendingAsyncValidator=!1)}setErrors(t,e={}){this.errors=t,this._updateControlsErrors(!1!==e.emitEvent)}get(t){return function iz(n,t,e){if(null==t||(Array.isArray(t)||(t=t.split(e)),Array.isArray(t)&&0===t.length))return null;let i=n;return t.forEach(r=>{i=Em(i)?i.controls.hasOwnProperty(r)?i.controls[r]:null:(n=>n instanceof sz)(i)&&i.at(r)||null}),i}(this,t,\".\")}getError(t,e){const i=e?this.get(e):this;return i&&i.errors?i.errors[t]:null}hasError(t,e){return!!this.getError(t,e)}get root(){let t=this;for(;t._parent;)t=t._parent;return t}_updateControlsErrors(t){this.status=this._calculateStatus(),t&&this.statusChanges.emit(this.status),this._parent&&this._parent._updateControlsErrors(t)}_initObservables(){this.valueChanges=new $,this.statusChanges=new $}_calculateStatus(){return this._allControlsDisabled()?za:this.errors?Ad:this._hasOwnPendingAsyncValidator||this._anyControlsHaveStatus(so)?so:this._anyControlsHaveStatus(Ad)?Ad:ja}_anyControlsHaveStatus(t){return this._anyControls(e=>e.status===t)}_anyControlsDirty(){return this._anyControls(t=>t.dirty)}_anyControlsTouched(){return this._anyControls(t=>t.touched)}_updatePristine(t={}){this.pristine=!this._anyControlsDirty(),this._parent&&!t.onlySelf&&this._parent._updatePristine(t)}_updateTouched(t={}){this.touched=this._anyControlsTouched(),this._parent&&!t.onlySelf&&this._parent._updateTouched(t)}_isBoxedValue(t){return\"object\"==typeof t&&null!==t&&2===Object.keys(t).length&&\"value\"in t&&\"disabled\"in t}_registerOnCollectionChange(t){this._onCollectionChange=t}_setUpdateStrategy(t){Id(t)&&null!=t.updateOn&&(this._updateOn=t.updateOn)}_parentMarkedDirty(t){return!t&&!(!this._parent||!this._parent.dirty)&&!this._parent._anyControlsDirty()}}class Rd extends Sm{constructor(t=null,e,i){super(Mm(e),xm(i,e)),this.defaultValue=null,this._onChange=[],this._pendingChange=!1,this._applyFormState(t),this._setUpdateStrategy(e),this._initObservables(),this.updateValueAndValidity({onlySelf:!0,emitEvent:!!this.asyncValidator}),Id(e)&&e.initialValueIsDefault&&(this.defaultValue=this._isBoxedValue(t)?t.value:t)}setValue(t,e={}){this.value=this._pendingValue=t,this._onChange.length&&!1!==e.emitModelToViewChange&&this._onChange.forEach(i=>i(this.value,!1!==e.emitViewToModelChange)),this.updateValueAndValidity(e)}patchValue(t,e={}){this.setValue(t,e)}reset(t=this.defaultValue,e={}){this._applyFormState(t),this.markAsPristine(e),this.markAsUntouched(e),this.setValue(this.value,e),this._pendingChange=!1}_updateValue(){}_anyControls(t){return!1}_allControlsDisabled(){return this.disabled}registerOnChange(t){this._onChange.push(t)}_unregisterOnChange(t){Dm(this._onChange,t)}registerOnDisabledChange(t){this._onDisabledChange.push(t)}_unregisterOnDisabledChange(t){Dm(this._onDisabledChange,t)}_forEachChild(t){}_syncPendingControls(){return!(\"submit\"!==this.updateOn||(this._pendingDirty&&this.markAsDirty(),this._pendingTouched&&this.markAsTouched(),!this._pendingChange)||(this.setValue(this._pendingValue,{onlySelf:!0,emitModelToViewChange:!1}),0))}_applyFormState(t){this._isBoxedValue(t)?(this.value=this._pendingValue=t.value,t.disabled?this.disable({onlySelf:!0,emitEvent:!1}):this.enable({onlySelf:!0,emitEvent:!1})):this.value=this._pendingValue=t}}class km extends Sm{constructor(t,e,i){super(Mm(e),xm(i,e)),this.controls=t,this._initObservables(),this._setUpdateStrategy(e),this._setUpControls(),this.updateValueAndValidity({onlySelf:!0,emitEvent:!!this.asyncValidator})}registerControl(t,e){return this.controls[t]?this.controls[t]:(this.controls[t]=e,e.setParent(this),e._registerOnCollectionChange(this._onCollectionChange),e)}addControl(t,e,i={}){this.registerControl(t,e),this.updateValueAndValidity({emitEvent:i.emitEvent}),this._onCollectionChange()}removeControl(t,e={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),delete this.controls[t],this.updateValueAndValidity({emitEvent:e.emitEvent}),this._onCollectionChange()}setControl(t,e,i={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),delete this.controls[t],e&&this.registerControl(t,e),this.updateValueAndValidity({emitEvent:i.emitEvent}),this._onCollectionChange()}contains(t){return this.controls.hasOwnProperty(t)&&this.controls[t].enabled}setValue(t,e={}){vx(this,t),Object.keys(t).forEach(i=>{_x(this,i),this.controls[i].setValue(t[i],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)}patchValue(t,e={}){null!=t&&(Object.keys(t).forEach(i=>{this.controls[i]&&this.controls[i].patchValue(t[i],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e))}reset(t={},e={}){this._forEachChild((i,r)=>{i.reset(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this._updatePristine(e),this._updateTouched(e),this.updateValueAndValidity(e)}getRawValue(){return this._reduceChildren({},(t,e,i)=>(t[i]=gx(e),t))}_syncPendingControls(){let t=this._reduceChildren(!1,(e,i)=>!!i._syncPendingControls()||e);return t&&this.updateValueAndValidity({onlySelf:!0}),t}_forEachChild(t){Object.keys(this.controls).forEach(e=>{const i=this.controls[e];i&&t(i,e)})}_setUpControls(){this._forEachChild(t=>{t.setParent(this),t._registerOnCollectionChange(this._onCollectionChange)})}_updateValue(){this.value=this._reduceValue()}_anyControls(t){for(const e of Object.keys(this.controls)){const i=this.controls[e];if(this.contains(e)&&t(i))return!0}return!1}_reduceValue(){return this._reduceChildren({},(t,e,i)=>((e.enabled||this.disabled)&&(t[i]=e.value),t))}_reduceChildren(t,e){let i=t;return this._forEachChild((r,s)=>{i=e(i,r,s)}),i}_allControlsDisabled(){for(const t of Object.keys(this.controls))if(this.controls[t].enabled)return!1;return Object.keys(this.controls).length>0||this.disabled}}class sz extends Sm{constructor(t,e,i){super(Mm(e),xm(i,e)),this.controls=t,this._initObservables(),this._setUpdateStrategy(e),this._setUpControls(),this.updateValueAndValidity({onlySelf:!0,emitEvent:!!this.asyncValidator})}at(t){return this.controls[t]}push(t,e={}){this.controls.push(t),this._registerControl(t),this.updateValueAndValidity({emitEvent:e.emitEvent}),this._onCollectionChange()}insert(t,e,i={}){this.controls.splice(t,0,e),this._registerControl(e),this.updateValueAndValidity({emitEvent:i.emitEvent})}removeAt(t,e={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),this.controls.splice(t,1),this.updateValueAndValidity({emitEvent:e.emitEvent})}setControl(t,e,i={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),this.controls.splice(t,1),e&&(this.controls.splice(t,0,e),this._registerControl(e)),this.updateValueAndValidity({emitEvent:i.emitEvent}),this._onCollectionChange()}get length(){return this.controls.length}setValue(t,e={}){vx(this,t),t.forEach((i,r)=>{_x(this,r),this.at(r).setValue(i,{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)}patchValue(t,e={}){null!=t&&(t.forEach((i,r)=>{this.at(r)&&this.at(r).patchValue(i,{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e))}reset(t=[],e={}){this._forEachChild((i,r)=>{i.reset(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this._updatePristine(e),this._updateTouched(e),this.updateValueAndValidity(e)}getRawValue(){return this.controls.map(t=>gx(t))}clear(t={}){this.controls.length<1||(this._forEachChild(e=>e._registerOnCollectionChange(()=>{})),this.controls.splice(0),this.updateValueAndValidity({emitEvent:t.emitEvent}))}_syncPendingControls(){let t=this.controls.reduce((e,i)=>!!i._syncPendingControls()||e,!1);return t&&this.updateValueAndValidity({onlySelf:!0}),t}_forEachChild(t){this.controls.forEach((e,i)=>{t(e,i)})}_updateValue(){this.value=this.controls.filter(t=>t.enabled||this.disabled).map(t=>t.value)}_anyControls(t){return this.controls.some(e=>e.enabled&&t(e))}_setUpControls(){this._forEachChild(t=>this._registerControl(t))}_allControlsDisabled(){for(const t of this.controls)if(t.enabled)return!1;return this.controls.length>0||this.disabled}_registerControl(t){t.setParent(this),t._registerOnCollectionChange(this._onCollectionChange)}}const oz={provide:Wt,useExisting:pe(()=>oo)},Ua=(()=>Promise.resolve(null))();let oo=(()=>{class n extends Wt{constructor(e,i){super(),this.submitted=!1,this._directives=new Set,this.ngSubmit=new $,this.form=new km({},fm(e),mm(i))}ngAfterViewInit(){this._setUpdateStrategy()}get formDirective(){return this}get control(){return this.form}get path(){return[]}get controls(){return this.form.controls}addControl(e){Ua.then(()=>{const i=this._findContainer(e.path);e.control=i.registerControl(e.name,e.control),Ha(e.control,e),e.control.updateValueAndValidity({emitEvent:!1}),this._directives.add(e)})}getControl(e){return this.form.get(e.path)}removeControl(e){Ua.then(()=>{const i=this._findContainer(e.path);i&&i.removeControl(e.name),this._directives.delete(e)})}addFormGroup(e){Ua.then(()=>{const i=this._findContainer(e.path),r=new km({});dx(r,e),i.registerControl(e.name,r),r.updateValueAndValidity({emitEvent:!1})})}removeFormGroup(e){Ua.then(()=>{const i=this._findContainer(e.path);i&&i.removeControl(e.name)})}getFormGroup(e){return this.form.get(e.path)}updateModel(e,i){Ua.then(()=>{this.form.get(e.path).setValue(i)})}setValue(e){this.control.setValue(e)}onSubmit(e){return this.submitted=!0,hx(this.form,this._directives),this.ngSubmit.emit(e),!1}onReset(){this.resetForm()}resetForm(e){this.form.reset(e),this.submitted=!1}_setUpdateStrategy(){this.options&&null!=this.options.updateOn&&(this.form._updateOn=this.options.updateOn)}_findContainer(e){return e.pop(),e.length?this.form.get(e):this.form}}return n.\\u0275fac=function(e){return new(e||n)(f(Dt,10),f(or,10))},n.\\u0275dir=C({type:n,selectors:[[\"form\",3,\"ngNoForm\",\"\",3,\"formGroup\",\"\"],[\"ng-form\"],[\"\",\"ngForm\",\"\"]],hostBindings:function(e,i){1&e&&J(\"submit\",function(s){return i.onSubmit(s)})(\"reset\",function(){return i.onReset()})},inputs:{options:[\"ngFormOptions\",\"options\"]},outputs:{ngSubmit:\"ngSubmit\"},exportAs:[\"ngForm\"],features:[L([oz]),E]}),n})();const dz={provide:xt,useExisting:pe(()=>Tm),multi:!0};let Tm=(()=>{class n extends $r{writeValue(e){this.setProperty(\"value\",null==e?\"\":e)}registerOnChange(e){this.onChange=i=>{e(\"\"==i?null:parseFloat(i))}}}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275dir=C({type:n,selectors:[[\"input\",\"type\",\"number\",\"formControlName\",\"\"],[\"input\",\"type\",\"number\",\"formControl\",\"\"],[\"input\",\"type\",\"number\",\"ngModel\",\"\"]],hostBindings:function(e,i){1&e&&J(\"input\",function(s){return i.onChange(s.target.value)})(\"blur\",function(){return i.onTouched()})},features:[L([dz]),E]}),n})(),wx=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const Am=new b(\"NgModelWithFormControlWarning\"),fz={provide:Jn,useExisting:pe(()=>Im)};let Im=(()=>{class n extends Jn{constructor(e,i,r,s){super(),this._ngModelWarningConfig=s,this.update=new $,this._ngModelWarningSent=!1,this._setValidators(e),this._setAsyncValidators(i),this.valueAccessor=function Cm(n,t){if(!t)return null;let e,i,r;return Array.isArray(t),t.forEach(s=>{s.constructor===Dd?e=s:function nz(n){return Object.getPrototypeOf(n.constructor)===$r}(s)?i=s:r=s}),r||i||e||null}(0,r)}set isDisabled(e){}ngOnChanges(e){if(this._isControlChanged(e)){const i=e.form.previousValue;i&&Sd(i,this,!1),Ha(this.form,this),this.control.disabled&&this.valueAccessor.setDisabledState&&this.valueAccessor.setDisabledState(!0),this.form.updateValueAndValidity({emitEvent:!1})}(function bm(n,t){if(!n.hasOwnProperty(\"model\"))return!1;const e=n.model;return!!e.isFirstChange()||!Object.is(t,e.currentValue)})(e,this.viewModel)&&(this.form.setValue(this.model),this.viewModel=this.model)}ngOnDestroy(){this.form&&Sd(this.form,this,!1)}get path(){return[]}get control(){return this.form}viewToModelUpdate(e){this.viewModel=e,this.update.emit(e)}_isControlChanged(e){return e.hasOwnProperty(\"form\")}}return n._ngModelWarningSentOnce=!1,n.\\u0275fac=function(e){return new(e||n)(f(Dt,10),f(or,10),f(xt,10),f(Am,8))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"formControl\",\"\"]],inputs:{form:[\"formControl\",\"form\"],isDisabled:[\"disabled\",\"isDisabled\"],model:[\"ngModel\",\"model\"]},outputs:{update:\"ngModelChange\"},exportAs:[\"ngForm\"],features:[L([fz]),E,Je]}),n})();const mz={provide:Wt,useExisting:pe(()=>ao)};let ao=(()=>{class n extends Wt{constructor(e,i){super(),this.validators=e,this.asyncValidators=i,this.submitted=!1,this._onCollectionChange=()=>this._updateDomValue(),this.directives=[],this.form=null,this.ngSubmit=new $,this._setValidators(e),this._setAsyncValidators(i)}ngOnChanges(e){this._checkFormPresent(),e.hasOwnProperty(\"form\")&&(this._updateValidators(),this._updateDomValue(),this._updateRegistrations(),this._oldForm=this.form)}ngOnDestroy(){this.form&&(Td(this.form,this),this.form._onCollectionChange===this._onCollectionChange&&this.form._registerOnCollectionChange(()=>{}))}get formDirective(){return this}get control(){return this.form}get path(){return[]}addControl(e){const i=this.form.get(e.path);return Ha(i,e),i.updateValueAndValidity({emitEvent:!1}),this.directives.push(e),i}getControl(e){return this.form.get(e.path)}removeControl(e){Sd(e.control||null,e,!1),Dm(this.directives,e)}addFormGroup(e){this._setUpFormContainer(e)}removeFormGroup(e){this._cleanUpFormContainer(e)}getFormGroup(e){return this.form.get(e.path)}addFormArray(e){this._setUpFormContainer(e)}removeFormArray(e){this._cleanUpFormContainer(e)}getFormArray(e){return this.form.get(e.path)}updateModel(e,i){this.form.get(e.path).setValue(i)}onSubmit(e){return this.submitted=!0,hx(this.form,this.directives),this.ngSubmit.emit(e),!1}onReset(){this.resetForm()}resetForm(e){this.form.reset(e),this.submitted=!1}_updateDomValue(){this.directives.forEach(e=>{const i=e.control,r=this.form.get(e.path);i!==r&&(Sd(i||null,e),mx(r)&&(Ha(r,e),e.control=r))}),this.form._updateTreeValidity({emitEvent:!1})}_setUpFormContainer(e){const i=this.form.get(e.path);dx(i,e),i.updateValueAndValidity({emitEvent:!1})}_cleanUpFormContainer(e){if(this.form){const i=this.form.get(e.path);i&&function ez(n,t){return Td(n,t)}(i,e)&&i.updateValueAndValidity({emitEvent:!1})}}_updateRegistrations(){this.form._registerOnCollectionChange(this._onCollectionChange),this._oldForm&&this._oldForm._registerOnCollectionChange(()=>{})}_updateValidators(){ym(this.form,this),this._oldForm&&Td(this._oldForm,this)}_checkFormPresent(){}}return n.\\u0275fac=function(e){return new(e||n)(f(Dt,10),f(or,10))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"formGroup\",\"\"]],hostBindings:function(e,i){1&e&&J(\"submit\",function(s){return i.onSubmit(s)})(\"reset\",function(){return i.onReset()})},inputs:{form:[\"formGroup\",\"form\"]},outputs:{ngSubmit:\"ngSubmit\"},exportAs:[\"ngForm\"],features:[L([mz]),E,Je]}),n})(),Bx=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[wx]]}),n})(),Pz=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[Bx]}),n})(),Fz=(()=>{class n{static withConfig(e){return{ngModule:n,providers:[{provide:Am,useValue:e.warnOnNgModelWithFormControl}]}}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[Bx]}),n})();const Nz=new b(\"cdk-dir-doc\",{providedIn:\"root\",factory:function Lz(){return Uo(ie)}}),Bz=/^(ar|ckb|dv|he|iw|fa|nqo|ps|sd|ug|ur|yi|.*[-_](Adlm|Arab|Hebr|Nkoo|Rohg|Thaa))(?!.*[-_](Latn|Cyrl)($|-|_))($|-|_)/i;let On=(()=>{class n{constructor(e){if(this.value=\"ltr\",this.change=new $,e){const r=e.documentElement?e.documentElement.dir:null;this.value=function Vz(n){const t=(null==n?void 0:n.toLowerCase())||\"\";return\"auto\"===t&&\"undefined\"!=typeof navigator&&(null==navigator?void 0:navigator.language)?Bz.test(navigator.language)?\"rtl\":\"ltr\":\"rtl\"===t?\"rtl\":\"ltr\"}((e.body?e.body.dir:null)||r||\"ltr\")}}ngOnDestroy(){this.change.complete()}}return n.\\u0275fac=function(e){return new(e||n)(y(Nz,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),lo=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const Lm=new Rr(\"13.3.0\");let Bm;try{Bm=\"undefined\"!=typeof Intl&&Intl.v8BreakIterator}catch(n){Bm=!1}let co,It=(()=>{class n{constructor(e){this._platformId=e,this.isBrowser=this._platformId?function OL(n){return n===wD}(this._platformId):\"object\"==typeof document&&!!document,this.EDGE=this.isBrowser&&/(edge)/i.test(navigator.userAgent),this.TRIDENT=this.isBrowser&&/(msie|trident)/i.test(navigator.userAgent),this.BLINK=this.isBrowser&&!(!window.chrome&&!Bm)&&\"undefined\"!=typeof CSS&&!this.EDGE&&!this.TRIDENT,this.WEBKIT=this.isBrowser&&/AppleWebKit/i.test(navigator.userAgent)&&!this.BLINK&&!this.EDGE&&!this.TRIDENT,this.IOS=this.isBrowser&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!(\"MSStream\"in window),this.FIREFOX=this.isBrowser&&/(firefox|minefield)/i.test(navigator.userAgent),this.ANDROID=this.isBrowser&&/android/i.test(navigator.userAgent)&&!this.TRIDENT,this.SAFARI=this.isBrowser&&/safari/i.test(navigator.userAgent)&&this.WEBKIT}}return n.\\u0275fac=function(e){return new(e||n)(y(bc))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const Vx=[\"color\",\"button\",\"checkbox\",\"date\",\"datetime-local\",\"email\",\"file\",\"hidden\",\"image\",\"month\",\"number\",\"password\",\"radio\",\"range\",\"reset\",\"search\",\"submit\",\"tel\",\"text\",\"time\",\"url\",\"week\"];function Hx(){if(co)return co;if(\"object\"!=typeof document||!document)return co=new Set(Vx),co;let n=document.createElement(\"input\");return co=new Set(Vx.filter(t=>(n.setAttribute(\"type\",t),n.type===t))),co}let $a,Wr,Vm;function ei(n){return function Hz(){if(null==$a&&\"undefined\"!=typeof window)try{window.addEventListener(\"test\",null,Object.defineProperty({},\"passive\",{get:()=>$a=!0}))}finally{$a=$a||!1}return $a}()?n:!!n.capture}function jz(){if(null==Wr){if(\"object\"!=typeof document||!document||\"function\"!=typeof Element||!Element)return Wr=!1,Wr;if(\"scrollBehavior\"in document.documentElement.style)Wr=!0;else{const n=Element.prototype.scrollTo;Wr=!!n&&!/\\{\\s*\\[native code\\]\\s*\\}/.test(n.toString())}}return Wr}function Fd(n){if(function zz(){if(null==Vm){const n=\"undefined\"!=typeof document?document.head:null;Vm=!(!n||!n.createShadowRoot&&!n.attachShadow)}return Vm}()){const t=n.getRootNode?n.getRootNode():null;if(\"undefined\"!=typeof ShadowRoot&&ShadowRoot&&t instanceof ShadowRoot)return t}return null}function Hm(){let n=\"undefined\"!=typeof document&&document?document.activeElement:null;for(;n&&n.shadowRoot;){const t=n.shadowRoot.activeElement;if(t===n)break;n=t}return n}function Pn(n){return n.composedPath?n.composedPath()[0]:n.target}function jm(){return\"undefined\"!=typeof __karma__&&!!__karma__||\"undefined\"!=typeof jasmine&&!!jasmine||\"undefined\"!=typeof jest&&!!jest||\"undefined\"!=typeof Mocha&&!!Mocha}function Xt(n,...t){return t.length?t.some(e=>n[e]):n.altKey||n.shiftKey||n.ctrlKey||n.metaKey}class e3 extends ke{constructor(t,e){super()}schedule(t,e=0){return this}}const Ld={setInterval(n,t,...e){const{delegate:i}=Ld;return(null==i?void 0:i.setInterval)?i.setInterval(n,t,...e):setInterval(n,t,...e)},clearInterval(n){const{delegate:t}=Ld;return((null==t?void 0:t.clearInterval)||clearInterval)(n)},delegate:void 0};class qm extends e3{constructor(t,e){super(t,e),this.scheduler=t,this.work=e,this.pending=!1}schedule(t,e=0){if(this.closed)return this;this.state=t;const i=this.id,r=this.scheduler;return null!=i&&(this.id=this.recycleAsyncId(r,i,e)),this.pending=!0,this.delay=e,this.id=this.id||this.requestAsyncId(r,this.id,e),this}requestAsyncId(t,e,i=0){return Ld.setInterval(t.flush.bind(t,this),i)}recycleAsyncId(t,e,i=0){if(null!=i&&this.delay===i&&!1===this.pending)return e;Ld.clearInterval(e)}execute(t,e){if(this.closed)return new Error(\"executing a cancelled action\");this.pending=!1;const i=this._execute(t,e);if(i)return i;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))}_execute(t,e){let r,i=!1;try{this.work(t)}catch(s){i=!0,r=s||new Error(\"Scheduled action threw falsy error\")}if(i)return this.unsubscribe(),r}unsubscribe(){if(!this.closed){const{id:t,scheduler:e}=this,{actions:i}=e;this.work=this.state=this.scheduler=null,this.pending=!1,ss(i,this),null!=t&&(this.id=this.recycleAsyncId(e,t,null)),this.delay=null,super.unsubscribe()}}}const Ux={now:()=>(Ux.delegate||Date).now(),delegate:void 0};class Wa{constructor(t,e=Wa.now){this.schedulerActionCtor=t,this.now=e}schedule(t,e=0,i){return new this.schedulerActionCtor(this,t).schedule(i,e)}}Wa.now=Ux.now;class Ym extends Wa{constructor(t,e=Wa.now){super(t,e),this.actions=[],this._active=!1,this._scheduled=void 0}flush(t){const{actions:e}=this;if(this._active)return void e.push(t);let i;this._active=!0;do{if(i=t.execute(t.state,t.delay))break}while(t=e.shift());if(this._active=!1,i){for(;t=e.shift();)t.unsubscribe();throw i}}}const qa=new Ym(qm),t3=qa;function $x(n,t=qa){return qe((e,i)=>{let r=null,s=null,o=null;const a=()=>{if(r){r.unsubscribe(),r=null;const c=s;s=null,i.next(c)}};function l(){const c=o+n,d=t.now();if(d<c)return r=this.schedule(void 0,c-d),void i.add(r);a()}e.subscribe(Ue(i,c=>{s=c,o=t.now(),r||(r=t.schedule(l,n),i.add(r))},()=>{a(),i.complete()},void 0,()=>{s=r=null}))})}function Gx(n,t=Wi){return n=null!=n?n:r3,qe((e,i)=>{let r,s=!0;e.subscribe(Ue(i,o=>{const a=t(o);(s||!n(r,a))&&(s=!1,r=a,i.next(o))}))})}function r3(n,t){return n===t}function Ie(n){return qe((t,e)=>{Jt(n).subscribe(Ue(e,()=>e.complete(),gl)),!e.closed&&t.subscribe(e)})}function G(n){return null!=n&&\"false\"!=`${n}`}function Et(n,t=0){return function s3(n){return!isNaN(parseFloat(n))&&!isNaN(Number(n))}(n)?Number(n):t}function Wx(n){return Array.isArray(n)?n:[n]}function ft(n){return null==n?\"\":\"string\"==typeof n?n:`${n}px`}function at(n){return n instanceof W?n.nativeElement:n}let qx=(()=>{class n{create(e){return\"undefined\"==typeof MutationObserver?null:new MutationObserver(e)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),o3=(()=>{class n{constructor(e){this._mutationObserverFactory=e,this._observedElements=new Map}ngOnDestroy(){this._observedElements.forEach((e,i)=>this._cleanupObserver(i))}observe(e){const i=at(e);return new Ve(r=>{const o=this._observeElement(i).subscribe(r);return()=>{o.unsubscribe(),this._unobserveElement(i)}})}_observeElement(e){if(this._observedElements.has(e))this._observedElements.get(e).count++;else{const i=new O,r=this._mutationObserverFactory.create(s=>i.next(s));r&&r.observe(e,{characterData:!0,childList:!0,subtree:!0}),this._observedElements.set(e,{observer:r,stream:i,count:1})}return this._observedElements.get(e).stream}_unobserveElement(e){this._observedElements.has(e)&&(this._observedElements.get(e).count--,this._observedElements.get(e).count||this._cleanupObserver(e))}_cleanupObserver(e){if(this._observedElements.has(e)){const{observer:i,stream:r}=this._observedElements.get(e);i&&i.disconnect(),r.complete(),this._observedElements.delete(e)}}}return n.\\u0275fac=function(e){return new(e||n)(y(qx))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),Qm=(()=>{class n{constructor(e,i,r){this._contentObserver=e,this._elementRef=i,this._ngZone=r,this.event=new $,this._disabled=!1,this._currentSubscription=null}get disabled(){return this._disabled}set disabled(e){this._disabled=G(e),this._disabled?this._unsubscribe():this._subscribe()}get debounce(){return this._debounce}set debounce(e){this._debounce=Et(e),this._subscribe()}ngAfterContentInit(){!this._currentSubscription&&!this.disabled&&this._subscribe()}ngOnDestroy(){this._unsubscribe()}_subscribe(){this._unsubscribe();const e=this._contentObserver.observe(this._elementRef);this._ngZone.runOutsideAngular(()=>{this._currentSubscription=(this.debounce?e.pipe($x(this.debounce)):e).subscribe(this.event)})}_unsubscribe(){var e;null===(e=this._currentSubscription)||void 0===e||e.unsubscribe()}}return n.\\u0275fac=function(e){return new(e||n)(f(o3),f(W),f(ne))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"cdkObserveContent\",\"\"]],inputs:{disabled:[\"cdkObserveContentDisabled\",\"disabled\"],debounce:\"debounce\"},outputs:{event:\"cdkObserveContent\"},exportAs:[\"cdkObserveContent\"]}),n})(),Ya=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[qx]}),n})();class c3 extends class Kx{constructor(t){this._items=t,this._activeItemIndex=-1,this._activeItem=null,this._wrap=!1,this._letterKeyStream=new O,this._typeaheadSubscription=ke.EMPTY,this._vertical=!0,this._allowedModifierKeys=[],this._homeAndEnd=!1,this._skipPredicateFn=e=>e.disabled,this._pressedLetters=[],this.tabOut=new O,this.change=new O,t instanceof fa&&t.changes.subscribe(e=>{if(this._activeItem){const r=e.toArray().indexOf(this._activeItem);r>-1&&r!==this._activeItemIndex&&(this._activeItemIndex=r)}})}skipPredicate(t){return this._skipPredicateFn=t,this}withWrap(t=!0){return this._wrap=t,this}withVerticalOrientation(t=!0){return this._vertical=t,this}withHorizontalOrientation(t){return this._horizontal=t,this}withAllowedModifierKeys(t){return this._allowedModifierKeys=t,this}withTypeAhead(t=200){return this._typeaheadSubscription.unsubscribe(),this._typeaheadSubscription=this._letterKeyStream.pipe(Mt(e=>this._pressedLetters.push(e)),$x(t),Ct(()=>this._pressedLetters.length>0),ue(()=>this._pressedLetters.join(\"\"))).subscribe(e=>{const i=this._getItemsArray();for(let r=1;r<i.length+1;r++){const s=(this._activeItemIndex+r)%i.length,o=i[s];if(!this._skipPredicateFn(o)&&0===o.getLabel().toUpperCase().trim().indexOf(e)){this.setActiveItem(s);break}}this._pressedLetters=[]}),this}withHomeAndEnd(t=!0){return this._homeAndEnd=t,this}setActiveItem(t){const e=this._activeItem;this.updateActiveItem(t),this._activeItem!==e&&this.change.next(this._activeItemIndex)}onKeydown(t){const e=t.keyCode,r=[\"altKey\",\"ctrlKey\",\"metaKey\",\"shiftKey\"].every(s=>!t[s]||this._allowedModifierKeys.indexOf(s)>-1);switch(e){case 9:return void this.tabOut.next();case 40:if(this._vertical&&r){this.setNextItemActive();break}return;case 38:if(this._vertical&&r){this.setPreviousItemActive();break}return;case 39:if(this._horizontal&&r){\"rtl\"===this._horizontal?this.setPreviousItemActive():this.setNextItemActive();break}return;case 37:if(this._horizontal&&r){\"rtl\"===this._horizontal?this.setNextItemActive():this.setPreviousItemActive();break}return;case 36:if(this._homeAndEnd&&r){this.setFirstItemActive();break}return;case 35:if(this._homeAndEnd&&r){this.setLastItemActive();break}return;default:return void((r||Xt(t,\"shiftKey\"))&&(t.key&&1===t.key.length?this._letterKeyStream.next(t.key.toLocaleUpperCase()):(e>=65&&e<=90||e>=48&&e<=57)&&this._letterKeyStream.next(String.fromCharCode(e))))}this._pressedLetters=[],t.preventDefault()}get activeItemIndex(){return this._activeItemIndex}get activeItem(){return this._activeItem}isTyping(){return this._pressedLetters.length>0}setFirstItemActive(){this._setActiveItemByIndex(0,1)}setLastItemActive(){this._setActiveItemByIndex(this._items.length-1,-1)}setNextItemActive(){this._activeItemIndex<0?this.setFirstItemActive():this._setActiveItemByDelta(1)}setPreviousItemActive(){this._activeItemIndex<0&&this._wrap?this.setLastItemActive():this._setActiveItemByDelta(-1)}updateActiveItem(t){const e=this._getItemsArray(),i=\"number\"==typeof t?t:e.indexOf(t),r=e[i];this._activeItem=null==r?null:r,this._activeItemIndex=i}_setActiveItemByDelta(t){this._wrap?this._setActiveInWrapMode(t):this._setActiveInDefaultMode(t)}_setActiveInWrapMode(t){const e=this._getItemsArray();for(let i=1;i<=e.length;i++){const r=(this._activeItemIndex+t*i+e.length)%e.length;if(!this._skipPredicateFn(e[r]))return void this.setActiveItem(r)}}_setActiveInDefaultMode(t){this._setActiveItemByIndex(this._activeItemIndex+t,t)}_setActiveItemByIndex(t,e){const i=this._getItemsArray();if(i[t]){for(;this._skipPredicateFn(i[t]);)if(!i[t+=e])return;this.setActiveItem(t)}}_getItemsArray(){return this._items instanceof fa?this._items.toArray():this._items}}{setActiveItem(t){this.activeItem&&this.activeItem.setInactiveStyles(),super.setActiveItem(t),this.activeItem&&this.activeItem.setActiveStyles()}}let Xx=(()=>{class n{constructor(e){this._platform=e}isDisabled(e){return e.hasAttribute(\"disabled\")}isVisible(e){return function u3(n){return!!(n.offsetWidth||n.offsetHeight||\"function\"==typeof n.getClientRects&&n.getClientRects().length)}(e)&&\"visible\"===getComputedStyle(e).visibility}isTabbable(e){if(!this._platform.isBrowser)return!1;const i=function d3(n){try{return n.frameElement}catch(t){return null}}(function y3(n){return n.ownerDocument&&n.ownerDocument.defaultView||window}(e));if(i&&(-1===eE(i)||!this.isVisible(i)))return!1;let r=e.nodeName.toLowerCase(),s=eE(e);return e.hasAttribute(\"contenteditable\")?-1!==s:!(\"iframe\"===r||\"object\"===r||this._platform.WEBKIT&&this._platform.IOS&&!function _3(n){let t=n.nodeName.toLowerCase(),e=\"input\"===t&&n.type;return\"text\"===e||\"password\"===e||\"select\"===t||\"textarea\"===t}(e))&&(\"audio\"===r?!!e.hasAttribute(\"controls\")&&-1!==s:\"video\"===r?-1!==s&&(null!==s||this._platform.FIREFOX||e.hasAttribute(\"controls\")):e.tabIndex>=0)}isFocusable(e,i){return function v3(n){return!function p3(n){return function m3(n){return\"input\"==n.nodeName.toLowerCase()}(n)&&\"hidden\"==n.type}(n)&&(function h3(n){let t=n.nodeName.toLowerCase();return\"input\"===t||\"select\"===t||\"button\"===t||\"textarea\"===t}(n)||function f3(n){return function g3(n){return\"a\"==n.nodeName.toLowerCase()}(n)&&n.hasAttribute(\"href\")}(n)||n.hasAttribute(\"contenteditable\")||Jx(n))}(e)&&!this.isDisabled(e)&&((null==i?void 0:i.ignoreVisibility)||this.isVisible(e))}}return n.\\u0275fac=function(e){return new(e||n)(y(It))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();function Jx(n){if(!n.hasAttribute(\"tabindex\")||void 0===n.tabIndex)return!1;let t=n.getAttribute(\"tabindex\");return!(!t||isNaN(parseInt(t,10)))}function eE(n){if(!Jx(n))return null;const t=parseInt(n.getAttribute(\"tabindex\")||\"\",10);return isNaN(t)?-1:t}class b3{constructor(t,e,i,r,s=!1){this._element=t,this._checker=e,this._ngZone=i,this._document=r,this._hasAttached=!1,this.startAnchorListener=()=>this.focusLastTabbableElement(),this.endAnchorListener=()=>this.focusFirstTabbableElement(),this._enabled=!0,s||this.attachAnchors()}get enabled(){return this._enabled}set enabled(t){this._enabled=t,this._startAnchor&&this._endAnchor&&(this._toggleAnchorTabIndex(t,this._startAnchor),this._toggleAnchorTabIndex(t,this._endAnchor))}destroy(){const t=this._startAnchor,e=this._endAnchor;t&&(t.removeEventListener(\"focus\",this.startAnchorListener),t.remove()),e&&(e.removeEventListener(\"focus\",this.endAnchorListener),e.remove()),this._startAnchor=this._endAnchor=null,this._hasAttached=!1}attachAnchors(){return!!this._hasAttached||(this._ngZone.runOutsideAngular(()=>{this._startAnchor||(this._startAnchor=this._createAnchor(),this._startAnchor.addEventListener(\"focus\",this.startAnchorListener)),this._endAnchor||(this._endAnchor=this._createAnchor(),this._endAnchor.addEventListener(\"focus\",this.endAnchorListener))}),this._element.parentNode&&(this._element.parentNode.insertBefore(this._startAnchor,this._element),this._element.parentNode.insertBefore(this._endAnchor,this._element.nextSibling),this._hasAttached=!0),this._hasAttached)}focusInitialElementWhenReady(t){return new Promise(e=>{this._executeOnStable(()=>e(this.focusInitialElement(t)))})}focusFirstTabbableElementWhenReady(t){return new Promise(e=>{this._executeOnStable(()=>e(this.focusFirstTabbableElement(t)))})}focusLastTabbableElementWhenReady(t){return new Promise(e=>{this._executeOnStable(()=>e(this.focusLastTabbableElement(t)))})}_getRegionBoundary(t){const e=this._element.querySelectorAll(`[cdk-focus-region-${t}], [cdkFocusRegion${t}], [cdk-focus-${t}]`);return\"start\"==t?e.length?e[0]:this._getFirstTabbableElement(this._element):e.length?e[e.length-1]:this._getLastTabbableElement(this._element)}focusInitialElement(t){const e=this._element.querySelector(\"[cdk-focus-initial], [cdkFocusInitial]\");if(e){if(!this._checker.isFocusable(e)){const i=this._getFirstTabbableElement(e);return null==i||i.focus(t),!!i}return e.focus(t),!0}return this.focusFirstTabbableElement(t)}focusFirstTabbableElement(t){const e=this._getRegionBoundary(\"start\");return e&&e.focus(t),!!e}focusLastTabbableElement(t){const e=this._getRegionBoundary(\"end\");return e&&e.focus(t),!!e}hasAttached(){return this._hasAttached}_getFirstTabbableElement(t){if(this._checker.isFocusable(t)&&this._checker.isTabbable(t))return t;const e=t.children;for(let i=0;i<e.length;i++){const r=e[i].nodeType===this._document.ELEMENT_NODE?this._getFirstTabbableElement(e[i]):null;if(r)return r}return null}_getLastTabbableElement(t){if(this._checker.isFocusable(t)&&this._checker.isTabbable(t))return t;const e=t.children;for(let i=e.length-1;i>=0;i--){const r=e[i].nodeType===this._document.ELEMENT_NODE?this._getLastTabbableElement(e[i]):null;if(r)return r}return null}_createAnchor(){const t=this._document.createElement(\"div\");return this._toggleAnchorTabIndex(this._enabled,t),t.classList.add(\"cdk-visually-hidden\"),t.classList.add(\"cdk-focus-trap-anchor\"),t.setAttribute(\"aria-hidden\",\"true\"),t}_toggleAnchorTabIndex(t,e){t?e.setAttribute(\"tabindex\",\"0\"):e.removeAttribute(\"tabindex\")}toggleAnchors(t){this._startAnchor&&this._endAnchor&&(this._toggleAnchorTabIndex(t,this._startAnchor),this._toggleAnchorTabIndex(t,this._endAnchor))}_executeOnStable(t){this._ngZone.isStable?t():this._ngZone.onStable.pipe(it(1)).subscribe(t)}}let C3=(()=>{class n{constructor(e,i,r){this._checker=e,this._ngZone=i,this._document=r}create(e,i=!1){return new b3(e,this._checker,this._ngZone,this._document,i)}}return n.\\u0275fac=function(e){return new(e||n)(y(Xx),y(ne),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();function Km(n){return 0===n.buttons||0===n.offsetX&&0===n.offsetY}function Zm(n){const t=n.touches&&n.touches[0]||n.changedTouches&&n.changedTouches[0];return!(!t||-1!==t.identifier||null!=t.radiusX&&1!==t.radiusX||null!=t.radiusY&&1!==t.radiusY)}const D3=new b(\"cdk-input-modality-detector-options\"),w3={ignoreKeys:[18,17,224,91,16]},ho=ei({passive:!0,capture:!0});let M3=(()=>{class n{constructor(e,i,r,s){this._platform=e,this._mostRecentTarget=null,this._modality=new Zt(null),this._lastTouchMs=0,this._onKeydown=o=>{var a,l;(null===(l=null===(a=this._options)||void 0===a?void 0:a.ignoreKeys)||void 0===l?void 0:l.some(c=>c===o.keyCode))||(this._modality.next(\"keyboard\"),this._mostRecentTarget=Pn(o))},this._onMousedown=o=>{Date.now()-this._lastTouchMs<650||(this._modality.next(Km(o)?\"keyboard\":\"mouse\"),this._mostRecentTarget=Pn(o))},this._onTouchstart=o=>{Zm(o)?this._modality.next(\"keyboard\"):(this._lastTouchMs=Date.now(),this._modality.next(\"touch\"),this._mostRecentTarget=Pn(o))},this._options=Object.assign(Object.assign({},w3),s),this.modalityDetected=this._modality.pipe(function n3(n){return Ct((t,e)=>n<=e)}(1)),this.modalityChanged=this.modalityDetected.pipe(Gx()),e.isBrowser&&i.runOutsideAngular(()=>{r.addEventListener(\"keydown\",this._onKeydown,ho),r.addEventListener(\"mousedown\",this._onMousedown,ho),r.addEventListener(\"touchstart\",this._onTouchstart,ho)})}get mostRecentModality(){return this._modality.value}ngOnDestroy(){this._modality.complete(),this._platform.isBrowser&&(document.removeEventListener(\"keydown\",this._onKeydown,ho),document.removeEventListener(\"mousedown\",this._onMousedown,ho),document.removeEventListener(\"touchstart\",this._onTouchstart,ho))}}return n.\\u0275fac=function(e){return new(e||n)(y(It),y(ne),y(ie),y(D3,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const x3=new b(\"liveAnnouncerElement\",{providedIn:\"root\",factory:function E3(){return null}}),S3=new b(\"LIVE_ANNOUNCER_DEFAULT_OPTIONS\");let k3=(()=>{class n{constructor(e,i,r,s){this._ngZone=i,this._defaultOptions=s,this._document=r,this._liveElement=e||this._createLiveElement()}announce(e,...i){const r=this._defaultOptions;let s,o;return 1===i.length&&\"number\"==typeof i[0]?o=i[0]:[s,o]=i,this.clear(),clearTimeout(this._previousTimeout),s||(s=r&&r.politeness?r.politeness:\"polite\"),null==o&&r&&(o=r.duration),this._liveElement.setAttribute(\"aria-live\",s),this._ngZone.runOutsideAngular(()=>new Promise(a=>{clearTimeout(this._previousTimeout),this._previousTimeout=setTimeout(()=>{this._liveElement.textContent=e,a(),\"number\"==typeof o&&(this._previousTimeout=setTimeout(()=>this.clear(),o))},100)}))}clear(){this._liveElement&&(this._liveElement.textContent=\"\")}ngOnDestroy(){var e;clearTimeout(this._previousTimeout),null===(e=this._liveElement)||void 0===e||e.remove(),this._liveElement=null}_createLiveElement(){const e=\"cdk-live-announcer-element\",i=this._document.getElementsByClassName(e),r=this._document.createElement(\"div\");for(let s=0;s<i.length;s++)i[s].remove();return r.classList.add(e),r.classList.add(\"cdk-visually-hidden\"),r.setAttribute(\"aria-atomic\",\"true\"),r.setAttribute(\"aria-live\",\"polite\"),this._document.body.appendChild(r),r}}return n.\\u0275fac=function(e){return new(e||n)(y(x3,8),y(ne),y(ie),y(S3,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const T3=new b(\"cdk-focus-monitor-default-options\"),Bd=ei({passive:!0,capture:!0});let Qr=(()=>{class n{constructor(e,i,r,s,o){this._ngZone=e,this._platform=i,this._inputModalityDetector=r,this._origin=null,this._windowFocused=!1,this._originFromTouchInteraction=!1,this._elementInfo=new Map,this._monitoredElementCount=0,this._rootNodeFocusListenerCount=new Map,this._windowFocusListener=()=>{this._windowFocused=!0,this._windowFocusTimeoutId=window.setTimeout(()=>this._windowFocused=!1)},this._stopInputModalityDetector=new O,this._rootNodeFocusAndBlurListener=a=>{const l=Pn(a),c=\"focus\"===a.type?this._onFocus:this._onBlur;for(let d=l;d;d=d.parentElement)c.call(this,a,d)},this._document=s,this._detectionMode=(null==o?void 0:o.detectionMode)||0}monitor(e,i=!1){const r=at(e);if(!this._platform.isBrowser||1!==r.nodeType)return q(null);const s=Fd(r)||this._getDocument(),o=this._elementInfo.get(r);if(o)return i&&(o.checkChildren=!0),o.subject;const a={checkChildren:i,subject:new O,rootNode:s};return this._elementInfo.set(r,a),this._registerGlobalListeners(a),a.subject}stopMonitoring(e){const i=at(e),r=this._elementInfo.get(i);r&&(r.subject.complete(),this._setClasses(i),this._elementInfo.delete(i),this._removeGlobalListeners(r))}focusVia(e,i,r){const s=at(e);s===this._getDocument().activeElement?this._getClosestElementsInfo(s).forEach(([a,l])=>this._originChanged(a,i,l)):(this._setOrigin(i),\"function\"==typeof s.focus&&s.focus(r))}ngOnDestroy(){this._elementInfo.forEach((e,i)=>this.stopMonitoring(i))}_getDocument(){return this._document||document}_getWindow(){return this._getDocument().defaultView||window}_getFocusOrigin(e){return this._origin?this._originFromTouchInteraction?this._shouldBeAttributedToTouch(e)?\"touch\":\"program\":this._origin:this._windowFocused&&this._lastFocusOrigin?this._lastFocusOrigin:\"program\"}_shouldBeAttributedToTouch(e){return 1===this._detectionMode||!!(null==e?void 0:e.contains(this._inputModalityDetector._mostRecentTarget))}_setClasses(e,i){e.classList.toggle(\"cdk-focused\",!!i),e.classList.toggle(\"cdk-touch-focused\",\"touch\"===i),e.classList.toggle(\"cdk-keyboard-focused\",\"keyboard\"===i),e.classList.toggle(\"cdk-mouse-focused\",\"mouse\"===i),e.classList.toggle(\"cdk-program-focused\",\"program\"===i)}_setOrigin(e,i=!1){this._ngZone.runOutsideAngular(()=>{this._origin=e,this._originFromTouchInteraction=\"touch\"===e&&i,0===this._detectionMode&&(clearTimeout(this._originTimeoutId),this._originTimeoutId=setTimeout(()=>this._origin=null,this._originFromTouchInteraction?650:1))})}_onFocus(e,i){const r=this._elementInfo.get(i),s=Pn(e);!r||!r.checkChildren&&i!==s||this._originChanged(i,this._getFocusOrigin(s),r)}_onBlur(e,i){const r=this._elementInfo.get(i);!r||r.checkChildren&&e.relatedTarget instanceof Node&&i.contains(e.relatedTarget)||(this._setClasses(i),this._emitOrigin(r.subject,null))}_emitOrigin(e,i){this._ngZone.run(()=>e.next(i))}_registerGlobalListeners(e){if(!this._platform.isBrowser)return;const i=e.rootNode,r=this._rootNodeFocusListenerCount.get(i)||0;r||this._ngZone.runOutsideAngular(()=>{i.addEventListener(\"focus\",this._rootNodeFocusAndBlurListener,Bd),i.addEventListener(\"blur\",this._rootNodeFocusAndBlurListener,Bd)}),this._rootNodeFocusListenerCount.set(i,r+1),1==++this._monitoredElementCount&&(this._ngZone.runOutsideAngular(()=>{this._getWindow().addEventListener(\"focus\",this._windowFocusListener)}),this._inputModalityDetector.modalityDetected.pipe(Ie(this._stopInputModalityDetector)).subscribe(s=>{this._setOrigin(s,!0)}))}_removeGlobalListeners(e){const i=e.rootNode;if(this._rootNodeFocusListenerCount.has(i)){const r=this._rootNodeFocusListenerCount.get(i);r>1?this._rootNodeFocusListenerCount.set(i,r-1):(i.removeEventListener(\"focus\",this._rootNodeFocusAndBlurListener,Bd),i.removeEventListener(\"blur\",this._rootNodeFocusAndBlurListener,Bd),this._rootNodeFocusListenerCount.delete(i))}--this._monitoredElementCount||(this._getWindow().removeEventListener(\"focus\",this._windowFocusListener),this._stopInputModalityDetector.next(),clearTimeout(this._windowFocusTimeoutId),clearTimeout(this._originTimeoutId))}_originChanged(e,i,r){this._setClasses(e,i),this._emitOrigin(r.subject,i),this._lastFocusOrigin=i}_getClosestElementsInfo(e){const i=[];return this._elementInfo.forEach((r,s)=>{(s===e||r.checkChildren&&s.contains(e))&&i.push([s,r])}),i}}return n.\\u0275fac=function(e){return new(e||n)(y(ne),y(It),y(M3),y(ie,8),y(T3,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const nE=\"cdk-high-contrast-black-on-white\",iE=\"cdk-high-contrast-white-on-black\",Xm=\"cdk-high-contrast-active\";let rE=(()=>{class n{constructor(e,i){this._platform=e,this._document=i}getHighContrastMode(){if(!this._platform.isBrowser)return 0;const e=this._document.createElement(\"div\");e.style.backgroundColor=\"rgb(1,2,3)\",e.style.position=\"absolute\",this._document.body.appendChild(e);const i=this._document.defaultView||window,r=i&&i.getComputedStyle?i.getComputedStyle(e):null,s=(r&&r.backgroundColor||\"\").replace(/ /g,\"\");switch(e.remove(),s){case\"rgb(0,0,0)\":return 2;case\"rgb(255,255,255)\":return 1}return 0}_applyBodyHighContrastModeCssClasses(){if(!this._hasCheckedHighContrastMode&&this._platform.isBrowser&&this._document.body){const e=this._document.body.classList;e.remove(Xm),e.remove(nE),e.remove(iE),this._hasCheckedHighContrastMode=!0;const i=this.getHighContrastMode();1===i?(e.add(Xm),e.add(nE)):2===i&&(e.add(Xm),e.add(iE))}}}return n.\\u0275fac=function(e){return new(e||n)(y(It),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),Qa=(()=>{class n{constructor(e){e._applyBodyHighContrastModeCssClasses()}}return n.\\u0275fac=function(e){return new(e||n)(y(rE))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Ya]]}),n})();const A3=[\"*\",[[\"mat-option\"],[\"ng-container\"]]],I3=[\"*\",\"mat-option, ng-container\"];function R3(n,t){if(1&n&&Le(0,\"mat-pseudo-checkbox\",4),2&n){const e=Be();N(\"state\",e.selected?\"checked\":\"unchecked\")(\"disabled\",e.disabled)}}function O3(n,t){if(1&n&&(x(0,\"span\",5),we(1),S()),2&n){const e=Be();T(1),qn(\"(\",e.group.label,\")\")}}const P3=[\"*\"],Jm=new Rr(\"13.3.0\"),N3=new b(\"mat-sanity-checks\",{providedIn:\"root\",factory:function F3(){return!0}});let B=(()=>{class n{constructor(e,i,r){this._sanityChecks=i,this._document=r,this._hasDoneGlobalChecks=!1,e._applyBodyHighContrastModeCssClasses(),this._hasDoneGlobalChecks||(this._hasDoneGlobalChecks=!0)}_checkIsEnabled(e){return!jm()&&(\"boolean\"==typeof this._sanityChecks?this._sanityChecks:!!this._sanityChecks[e])}}return n.\\u0275fac=function(e){return new(e||n)(y(rE),y(N3,8),y(ie))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[lo],lo]}),n})();function po(n){return class extends n{constructor(...t){super(...t),this._disabled=!1}get disabled(){return this._disabled}set disabled(t){this._disabled=G(t)}}}function fo(n,t){return class extends n{constructor(...e){super(...e),this.defaultColor=t,this.color=t}get color(){return this._color}set color(e){const i=e||this.defaultColor;i!==this._color&&(this._color&&this._elementRef.nativeElement.classList.remove(`mat-${this._color}`),i&&this._elementRef.nativeElement.classList.add(`mat-${i}`),this._color=i)}}}function ar(n){return class extends n{constructor(...t){super(...t),this._disableRipple=!1}get disableRipple(){return this._disableRipple}set disableRipple(t){this._disableRipple=G(t)}}}function Kr(n,t=0){return class extends n{constructor(...e){super(...e),this._tabIndex=t,this.defaultTabIndex=t}get tabIndex(){return this.disabled?-1:this._tabIndex}set tabIndex(e){this._tabIndex=null!=e?Et(e):this.defaultTabIndex}}}function ng(n){return class extends n{constructor(...t){super(...t),this.stateChanges=new O,this.errorState=!1}updateErrorState(){const t=this.errorState,s=(this.errorStateMatcher||this._defaultErrorStateMatcher).isErrorState(this.ngControl?this.ngControl.control:null,this._parentFormGroup||this._parentForm);s!==t&&(this.errorState=s,this.stateChanges.next())}}}const L3=new b(\"MAT_DATE_LOCALE\",{providedIn:\"root\",factory:function B3(){return Uo(Oi)}});class bi{constructor(){this._localeChanges=new O,this.localeChanges=this._localeChanges}getValidDateOrNull(t){return this.isDateInstance(t)&&this.isValid(t)?t:null}deserialize(t){return null==t||this.isDateInstance(t)&&this.isValid(t)?t:this.invalid()}setLocale(t){this.locale=t,this._localeChanges.next()}compareDate(t,e){return this.getYear(t)-this.getYear(e)||this.getMonth(t)-this.getMonth(e)||this.getDate(t)-this.getDate(e)}sameDate(t,e){if(t&&e){let i=this.isValid(t),r=this.isValid(e);return i&&r?!this.compareDate(t,e):i==r}return t==e}clampDate(t,e,i){return e&&this.compareDate(t,e)<0?e:i&&this.compareDate(t,i)>0?i:t}}const ig=new b(\"mat-date-formats\"),V3=/^\\d{4}-\\d{2}-\\d{2}(?:T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|(?:(?:\\+|-)\\d{2}:\\d{2}))?)?$/;function rg(n,t){const e=Array(n);for(let i=0;i<n;i++)e[i]=t(i);return e}let H3=(()=>{class n extends bi{constructor(e,i){super(),this.useUtcForDisplay=!1,super.setLocale(e)}getYear(e){return e.getFullYear()}getMonth(e){return e.getMonth()}getDate(e){return e.getDate()}getDayOfWeek(e){return e.getDay()}getMonthNames(e){const i=new Intl.DateTimeFormat(this.locale,{month:e,timeZone:\"utc\"});return rg(12,r=>this._format(i,new Date(2017,r,1)))}getDateNames(){const e=new Intl.DateTimeFormat(this.locale,{day:\"numeric\",timeZone:\"utc\"});return rg(31,i=>this._format(e,new Date(2017,0,i+1)))}getDayOfWeekNames(e){const i=new Intl.DateTimeFormat(this.locale,{weekday:e,timeZone:\"utc\"});return rg(7,r=>this._format(i,new Date(2017,0,r+1)))}getYearName(e){const i=new Intl.DateTimeFormat(this.locale,{year:\"numeric\",timeZone:\"utc\"});return this._format(i,e)}getFirstDayOfWeek(){return 0}getNumDaysInMonth(e){return this.getDate(this._createDateWithOverflow(this.getYear(e),this.getMonth(e)+1,0))}clone(e){return new Date(e.getTime())}createDate(e,i,r){let s=this._createDateWithOverflow(e,i,r);return s.getMonth(),s}today(){return new Date}parse(e){return\"number\"==typeof e?new Date(e):e?new Date(Date.parse(e)):null}format(e,i){if(!this.isValid(e))throw Error(\"NativeDateAdapter: Cannot format invalid date.\");const r=new Intl.DateTimeFormat(this.locale,Object.assign(Object.assign({},i),{timeZone:\"utc\"}));return this._format(r,e)}addCalendarYears(e,i){return this.addCalendarMonths(e,12*i)}addCalendarMonths(e,i){let r=this._createDateWithOverflow(this.getYear(e),this.getMonth(e)+i,this.getDate(e));return this.getMonth(r)!=((this.getMonth(e)+i)%12+12)%12&&(r=this._createDateWithOverflow(this.getYear(r),this.getMonth(r),0)),r}addCalendarDays(e,i){return this._createDateWithOverflow(this.getYear(e),this.getMonth(e),this.getDate(e)+i)}toIso8601(e){return[e.getUTCFullYear(),this._2digit(e.getUTCMonth()+1),this._2digit(e.getUTCDate())].join(\"-\")}deserialize(e){if(\"string\"==typeof e){if(!e)return null;if(V3.test(e)){let i=new Date(e);if(this.isValid(i))return i}}return super.deserialize(e)}isDateInstance(e){return e instanceof Date}isValid(e){return!isNaN(e.getTime())}invalid(){return new Date(NaN)}_createDateWithOverflow(e,i,r){const s=new Date;return s.setFullYear(e,i,r),s.setHours(0,0,0,0),s}_2digit(e){return(\"00\"+e).slice(-2)}_format(e,i){const r=new Date;return r.setUTCFullYear(i.getFullYear(),i.getMonth(),i.getDate()),r.setUTCHours(i.getHours(),i.getMinutes(),i.getSeconds(),i.getMilliseconds()),e.format(r)}}return n.\\u0275fac=function(e){return new(e||n)(y(L3,8),y(It))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const j3={parse:{dateInput:null},display:{dateInput:{year:\"numeric\",month:\"numeric\",day:\"numeric\"},monthYearLabel:{year:\"numeric\",month:\"short\"},dateA11yLabel:{year:\"numeric\",month:\"long\",day:\"numeric\"},monthYearA11yLabel:{year:\"numeric\",month:\"long\"}}};let z3=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[{provide:bi,useClass:H3}]}),n})(),U3=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[{provide:ig,useValue:j3}],imports:[[z3]]}),n})(),mo=(()=>{class n{isErrorState(e,i){return!!(e&&e.invalid&&(e.touched||i&&i.submitted))}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),Vd=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})();class W3{constructor(t,e,i){this._renderer=t,this.element=e,this.config=i,this.state=3}fadeOut(){this._renderer.fadeOutRipple(this)}}const sE={enterDuration:225,exitDuration:150},sg=ei({passive:!0}),oE=[\"mousedown\",\"touchstart\"],aE=[\"mouseup\",\"mouseleave\",\"touchend\",\"touchcancel\"];class lE{constructor(t,e,i,r){this._target=t,this._ngZone=e,this._isPointerDown=!1,this._activeRipples=new Set,this._pointerUpEventsRegistered=!1,r.isBrowser&&(this._containerElement=at(i))}fadeInRipple(t,e,i={}){const r=this._containerRect=this._containerRect||this._containerElement.getBoundingClientRect(),s=Object.assign(Object.assign({},sE),i.animation);i.centered&&(t=r.left+r.width/2,e=r.top+r.height/2);const o=i.radius||function Q3(n,t,e){const i=Math.max(Math.abs(n-e.left),Math.abs(n-e.right)),r=Math.max(Math.abs(t-e.top),Math.abs(t-e.bottom));return Math.sqrt(i*i+r*r)}(t,e,r),a=t-r.left,l=e-r.top,c=s.enterDuration,d=document.createElement(\"div\");d.classList.add(\"mat-ripple-element\"),d.style.left=a-o+\"px\",d.style.top=l-o+\"px\",d.style.height=2*o+\"px\",d.style.width=2*o+\"px\",null!=i.color&&(d.style.backgroundColor=i.color),d.style.transitionDuration=`${c}ms`,this._containerElement.appendChild(d),function Y3(n){window.getComputedStyle(n).getPropertyValue(\"opacity\")}(d),d.style.transform=\"scale(1)\";const u=new W3(this,d,i);return u.state=0,this._activeRipples.add(u),i.persistent||(this._mostRecentTransientRipple=u),this._runTimeoutOutsideZone(()=>{const h=u===this._mostRecentTransientRipple;u.state=1,!i.persistent&&(!h||!this._isPointerDown)&&u.fadeOut()},c),u}fadeOutRipple(t){const e=this._activeRipples.delete(t);if(t===this._mostRecentTransientRipple&&(this._mostRecentTransientRipple=null),this._activeRipples.size||(this._containerRect=null),!e)return;const i=t.element,r=Object.assign(Object.assign({},sE),t.config.animation);i.style.transitionDuration=`${r.exitDuration}ms`,i.style.opacity=\"0\",t.state=2,this._runTimeoutOutsideZone(()=>{t.state=3,i.remove()},r.exitDuration)}fadeOutAll(){this._activeRipples.forEach(t=>t.fadeOut())}fadeOutAllNonPersistent(){this._activeRipples.forEach(t=>{t.config.persistent||t.fadeOut()})}setupTriggerEvents(t){const e=at(t);!e||e===this._triggerElement||(this._removeTriggerEvents(),this._triggerElement=e,this._registerEvents(oE))}handleEvent(t){\"mousedown\"===t.type?this._onMousedown(t):\"touchstart\"===t.type?this._onTouchStart(t):this._onPointerUp(),this._pointerUpEventsRegistered||(this._registerEvents(aE),this._pointerUpEventsRegistered=!0)}_onMousedown(t){const e=Km(t),i=this._lastTouchStartEvent&&Date.now()<this._lastTouchStartEvent+800;!this._target.rippleDisabled&&!e&&!i&&(this._isPointerDown=!0,this.fadeInRipple(t.clientX,t.clientY,this._target.rippleConfig))}_onTouchStart(t){if(!this._target.rippleDisabled&&!Zm(t)){this._lastTouchStartEvent=Date.now(),this._isPointerDown=!0;const e=t.changedTouches;for(let i=0;i<e.length;i++)this.fadeInRipple(e[i].clientX,e[i].clientY,this._target.rippleConfig)}}_onPointerUp(){!this._isPointerDown||(this._isPointerDown=!1,this._activeRipples.forEach(t=>{!t.config.persistent&&(1===t.state||t.config.terminateOnPointerUp&&0===t.state)&&t.fadeOut()}))}_runTimeoutOutsideZone(t,e=0){this._ngZone.runOutsideAngular(()=>setTimeout(t,e))}_registerEvents(t){this._ngZone.runOutsideAngular(()=>{t.forEach(e=>{this._triggerElement.addEventListener(e,this,sg)})})}_removeTriggerEvents(){this._triggerElement&&(oE.forEach(t=>{this._triggerElement.removeEventListener(t,this,sg)}),this._pointerUpEventsRegistered&&aE.forEach(t=>{this._triggerElement.removeEventListener(t,this,sg)}))}}const cE=new b(\"mat-ripple-global-options\");let Zr=(()=>{class n{constructor(e,i,r,s,o){this._elementRef=e,this._animationMode=o,this.radius=0,this._disabled=!1,this._isInitialized=!1,this._globalOptions=s||{},this._rippleRenderer=new lE(this,i,e,r)}get disabled(){return this._disabled}set disabled(e){e&&this.fadeOutAllNonPersistent(),this._disabled=e,this._setupTriggerEventsIfEnabled()}get trigger(){return this._trigger||this._elementRef.nativeElement}set trigger(e){this._trigger=e,this._setupTriggerEventsIfEnabled()}ngOnInit(){this._isInitialized=!0,this._setupTriggerEventsIfEnabled()}ngOnDestroy(){this._rippleRenderer._removeTriggerEvents()}fadeOutAll(){this._rippleRenderer.fadeOutAll()}fadeOutAllNonPersistent(){this._rippleRenderer.fadeOutAllNonPersistent()}get rippleConfig(){return{centered:this.centered,radius:this.radius,color:this.color,animation:Object.assign(Object.assign(Object.assign({},this._globalOptions.animation),\"NoopAnimations\"===this._animationMode?{enterDuration:0,exitDuration:0}:{}),this.animation),terminateOnPointerUp:this._globalOptions.terminateOnPointerUp}}get rippleDisabled(){return this.disabled||!!this._globalOptions.disabled}_setupTriggerEventsIfEnabled(){!this.disabled&&this._isInitialized&&this._rippleRenderer.setupTriggerEvents(this.trigger)}launch(e,i=0,r){return\"number\"==typeof e?this._rippleRenderer.fadeInRipple(e,i,Object.assign(Object.assign({},this.rippleConfig),r)):this._rippleRenderer.fadeInRipple(0,0,Object.assign(Object.assign({},this.rippleConfig),e))}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(ne),f(It),f(cE,8),f(Rn,8))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"mat-ripple\",\"\"],[\"\",\"matRipple\",\"\"]],hostAttrs:[1,\"mat-ripple\"],hostVars:2,hostBindings:function(e,i){2&e&&Ae(\"mat-ripple-unbounded\",i.unbounded)},inputs:{color:[\"matRippleColor\",\"color\"],unbounded:[\"matRippleUnbounded\",\"unbounded\"],centered:[\"matRippleCentered\",\"centered\"],radius:[\"matRippleRadius\",\"radius\"],animation:[\"matRippleAnimation\",\"animation\"],disabled:[\"matRippleDisabled\",\"disabled\"],trigger:[\"matRippleTrigger\",\"trigger\"]},exportAs:[\"matRipple\"]}),n})(),ti=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),dE=(()=>{class n{constructor(e){this._animationMode=e,this.state=\"unchecked\",this.disabled=!1}}return n.\\u0275fac=function(e){return new(e||n)(f(Rn,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-pseudo-checkbox\"]],hostAttrs:[1,\"mat-pseudo-checkbox\"],hostVars:8,hostBindings:function(e,i){2&e&&Ae(\"mat-pseudo-checkbox-indeterminate\",\"indeterminate\"===i.state)(\"mat-pseudo-checkbox-checked\",\"checked\"===i.state)(\"mat-pseudo-checkbox-disabled\",i.disabled)(\"_mat-animation-noopable\",\"NoopAnimations\"===i._animationMode)},inputs:{state:\"state\",disabled:\"disabled\"},decls:0,vars:0,template:function(e,i){},styles:['.mat-pseudo-checkbox{width:16px;height:16px;border:2px solid;border-radius:2px;cursor:pointer;display:inline-block;vertical-align:middle;box-sizing:border-box;position:relative;flex-shrink:0;transition:border-color 90ms cubic-bezier(0, 0, 0.2, 0.1),background-color 90ms cubic-bezier(0, 0, 0.2, 0.1)}.mat-pseudo-checkbox::after{position:absolute;opacity:0;content:\"\";border-bottom:2px solid currentColor;transition:opacity 90ms cubic-bezier(0, 0, 0.2, 0.1)}.mat-pseudo-checkbox.mat-pseudo-checkbox-checked,.mat-pseudo-checkbox.mat-pseudo-checkbox-indeterminate{border-color:transparent}._mat-animation-noopable.mat-pseudo-checkbox{transition:none;animation:none}._mat-animation-noopable.mat-pseudo-checkbox::after{transition:none}.mat-pseudo-checkbox-disabled{cursor:default}.mat-pseudo-checkbox-indeterminate::after{top:5px;left:1px;width:10px;opacity:1;border-radius:2px}.mat-pseudo-checkbox-checked::after{top:2.4px;left:1px;width:8px;height:3px;border-left:2px solid currentColor;transform:rotate(-45deg);opacity:1;box-sizing:content-box}\\n'],encapsulation:2,changeDetection:0}),n})(),og=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B]]}),n})();const ag=new b(\"MAT_OPTION_PARENT_COMPONENT\"),K3=po(class{});let Z3=0,X3=(()=>{class n extends K3{constructor(e){var i;super(),this._labelId=\"mat-optgroup-label-\"+Z3++,this._inert=null!==(i=null==e?void 0:e.inertGroups)&&void 0!==i&&i}}return n.\\u0275fac=function(e){return new(e||n)(f(ag,8))},n.\\u0275dir=C({type:n,inputs:{label:\"label\"},features:[E]}),n})();const lg=new b(\"MatOptgroup\");let J3=(()=>{class n extends X3{}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275cmp=xe({type:n,selectors:[[\"mat-optgroup\"]],hostAttrs:[1,\"mat-optgroup\"],hostVars:5,hostBindings:function(e,i){2&e&&(Z(\"role\",i._inert?null:\"group\")(\"aria-disabled\",i._inert?null:i.disabled.toString())(\"aria-labelledby\",i._inert?null:i._labelId),Ae(\"mat-optgroup-disabled\",i.disabled))},inputs:{disabled:\"disabled\"},exportAs:[\"matOptgroup\"],features:[L([{provide:lg,useExisting:n}]),E],ngContentSelectors:I3,decls:4,vars:2,consts:[[\"aria-hidden\",\"true\",1,\"mat-optgroup-label\",3,\"id\"]],template:function(e,i){1&e&&(Lt(A3),x(0,\"span\",0),we(1),Pe(2),S(),Pe(3,1)),2&e&&(N(\"id\",i._labelId),T(1),qn(\"\",i.label,\" \"))},styles:[\".mat-optgroup-label{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;line-height:48px;height:48px;padding:0 16px;text-align:left;text-decoration:none;max-width:100%;-webkit-user-select:none;-moz-user-select:none;user-select:none;cursor:default}.mat-optgroup-label[disabled]{cursor:default}[dir=rtl] .mat-optgroup-label{text-align:right}.mat-optgroup-label .mat-icon{margin-right:16px;vertical-align:middle}.mat-optgroup-label .mat-icon svg{vertical-align:top}[dir=rtl] .mat-optgroup-label .mat-icon{margin-left:16px;margin-right:0}\\n\"],encapsulation:2,changeDetection:0}),n})(),eU=0;class uE{constructor(t,e=!1){this.source=t,this.isUserInput=e}}let tU=(()=>{class n{constructor(e,i,r,s){this._element=e,this._changeDetectorRef=i,this._parent=r,this.group=s,this._selected=!1,this._active=!1,this._disabled=!1,this._mostRecentViewValue=\"\",this.id=\"mat-option-\"+eU++,this.onSelectionChange=new $,this._stateChanges=new O}get multiple(){return this._parent&&this._parent.multiple}get selected(){return this._selected}get disabled(){return this.group&&this.group.disabled||this._disabled}set disabled(e){this._disabled=G(e)}get disableRipple(){return!(!this._parent||!this._parent.disableRipple)}get active(){return this._active}get viewValue(){return(this._getHostElement().textContent||\"\").trim()}select(){this._selected||(this._selected=!0,this._changeDetectorRef.markForCheck(),this._emitSelectionChangeEvent())}deselect(){this._selected&&(this._selected=!1,this._changeDetectorRef.markForCheck(),this._emitSelectionChangeEvent())}focus(e,i){const r=this._getHostElement();\"function\"==typeof r.focus&&r.focus(i)}setActiveStyles(){this._active||(this._active=!0,this._changeDetectorRef.markForCheck())}setInactiveStyles(){this._active&&(this._active=!1,this._changeDetectorRef.markForCheck())}getLabel(){return this.viewValue}_handleKeydown(e){(13===e.keyCode||32===e.keyCode)&&!Xt(e)&&(this._selectViaInteraction(),e.preventDefault())}_selectViaInteraction(){this.disabled||(this._selected=!this.multiple||!this._selected,this._changeDetectorRef.markForCheck(),this._emitSelectionChangeEvent(!0))}_getAriaSelected(){return this.selected||!this.multiple&&null}_getTabIndex(){return this.disabled?\"-1\":\"0\"}_getHostElement(){return this._element.nativeElement}ngAfterViewChecked(){if(this._selected){const e=this.viewValue;e!==this._mostRecentViewValue&&(this._mostRecentViewValue=e,this._stateChanges.next())}}ngOnDestroy(){this._stateChanges.complete()}_emitSelectionChangeEvent(e=!1){this.onSelectionChange.emit(new uE(this,e))}}return n.\\u0275fac=function(e){Sr()},n.\\u0275dir=C({type:n,inputs:{value:\"value\",id:\"id\",disabled:\"disabled\"},outputs:{onSelectionChange:\"onSelectionChange\"}}),n})(),hE=(()=>{class n extends tU{constructor(e,i,r,s){super(e,i,r,s)}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(Ye),f(ag,8),f(lg,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-option\"]],hostAttrs:[\"role\",\"option\",1,\"mat-option\",\"mat-focus-indicator\"],hostVars:12,hostBindings:function(e,i){1&e&&J(\"click\",function(){return i._selectViaInteraction()})(\"keydown\",function(s){return i._handleKeydown(s)}),2&e&&(Yn(\"id\",i.id),Z(\"tabindex\",i._getTabIndex())(\"aria-selected\",i._getAriaSelected())(\"aria-disabled\",i.disabled.toString()),Ae(\"mat-selected\",i.selected)(\"mat-option-multiple\",i.multiple)(\"mat-active\",i.active)(\"mat-option-disabled\",i.disabled))},exportAs:[\"matOption\"],features:[E],ngContentSelectors:P3,decls:5,vars:4,consts:[[\"class\",\"mat-option-pseudo-checkbox\",3,\"state\",\"disabled\",4,\"ngIf\"],[1,\"mat-option-text\"],[\"class\",\"cdk-visually-hidden\",4,\"ngIf\"],[\"mat-ripple\",\"\",1,\"mat-option-ripple\",3,\"matRippleTrigger\",\"matRippleDisabled\"],[1,\"mat-option-pseudo-checkbox\",3,\"state\",\"disabled\"],[1,\"cdk-visually-hidden\"]],template:function(e,i){1&e&&(Lt(),Ee(0,R3,1,2,\"mat-pseudo-checkbox\",0),x(1,\"span\",1),Pe(2),S(),Ee(3,O3,2,1,\"span\",2),Le(4,\"div\",3)),2&e&&(N(\"ngIf\",i.multiple),T(3),N(\"ngIf\",i.group&&i.group._inert),T(1),N(\"matRippleTrigger\",i._getHostElement())(\"matRippleDisabled\",i.disabled||i.disableRipple))},directives:[dE,Ca,Zr],styles:[\".mat-option{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;line-height:48px;height:48px;padding:0 16px;text-align:left;text-decoration:none;max-width:100%;position:relative;cursor:pointer;outline:none;display:flex;flex-direction:row;max-width:100%;box-sizing:border-box;align-items:center;-webkit-tap-highlight-color:transparent}.mat-option[disabled]{cursor:default}[dir=rtl] .mat-option{text-align:right}.mat-option .mat-icon{margin-right:16px;vertical-align:middle}.mat-option .mat-icon svg{vertical-align:top}[dir=rtl] .mat-option .mat-icon{margin-left:16px;margin-right:0}.mat-option[aria-disabled=true]{-webkit-user-select:none;-moz-user-select:none;user-select:none;cursor:default}.mat-optgroup .mat-option:not(.mat-option-multiple){padding-left:32px}[dir=rtl] .mat-optgroup .mat-option:not(.mat-option-multiple){padding-left:16px;padding-right:32px}.cdk-high-contrast-active .mat-option{margin:0 1px}.cdk-high-contrast-active .mat-option.mat-active{border:solid 1px currentColor;margin:0}.cdk-high-contrast-active .mat-option[aria-disabled=true]{opacity:.5}.mat-option-text{display:inline-block;flex-grow:1;overflow:hidden;text-overflow:ellipsis}.mat-option .mat-option-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-option-pseudo-checkbox{margin-right:8px}[dir=rtl] .mat-option-pseudo-checkbox{margin-left:8px;margin-right:0}\\n\"],encapsulation:2,changeDetection:0}),n})();function cg(n,t,e){if(e.length){let i=t.toArray(),r=e.toArray(),s=0;for(let o=0;o<n+1;o++)i[o].group&&i[o].group===r[s]&&s++;return s}return 0}let Hd=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ti,bt,B,og]]}),n})(),gE=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B],B]}),n})();const Xa=JSON.parse('[{\"from\":{\"name\":\"Everscale\",\"description\":\"Everscale mainnet\",\"url\":\"https://main.ton.dev\"},\"to\":{\"name\":\"Tezos\",\"description\":\"Tezos mainnet\",\"url\":\"https://tzkt.io\"},\"active\":true},{\"from\":{\"name\":\"Tezos\",\"description\":\"Tezos mainnet\",\"url\":\"https://tzkt.io\"},\"to\":{\"name\":\"Everscale\",\"description\":\"Everscale mainnet\",\"url\":\"https://main.ton.dev\"},\"active\":true},{\"from\":{\"name\":\"devnet\",\"description\":\"Everscale devnet\",\"url\":\"https://net.ton.dev\"},\"to\":{\"name\":\"hangzhounet\",\"description\":\"Tezos hangzhounet\",\"url\":\"https://hangzhounet.tzkt.io\"},\"active\":false},{\"from\":{\"name\":\"hangzhounet\",\"description\":\"Tezos hangzhounet\",\"url\":\"https://hangzhounet.tzkt.io\"},\"to\":{\"name\":\"devnet\",\"description\":\"Everscale devnet\",\"url\":\"https://net.ton.dev\"},\"active\":false},{\"from\":{\"name\":\"fld.ton.dev\",\"description\":\"Everscale fld\",\"url\":\"https://gql.custler.net\"},\"to\":{\"name\":\"ithacanet\",\"description\":\"Tezos ithacanet\",\"url\":\"https://ithacanet.tzkt.io\"},\"active\":false},{\"from\":{\"name\":\"ithacanet\",\"description\":\"Tezos ithacanet\",\"url\":\"https://ithacanet.tzkt.io\"},\"to\":{\"name\":\"fld.ton.dev\",\"description\":\"Everscale fld\",\"url\":\"https://gql.custler.net\"},\"active\":false}]'),ug=JSON.parse('[{\"name\":\"wTXZ\",\"type\":\"TIP-3.1\",\"desc\":\"Wrapped Tezos\"},{\"name\":\"SOON\",\"type\":\"TIP-3\",\"desc\":\"Soon\"},{\"name\":\"BRIDGE\",\"type\":\"TIP-3.1\",\"desc\":\"Bridge token\"}]'),hg=JSON.parse('[{\"name\":\"wEVER\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped EVER\"},{\"name\":\"KUSD\",\"type\":\"FA 1.2\",\"desc\":\"Kolibri\"},{\"name\":\"wXTZ\",\"type\":\"FA 1.2\",\"desc\":\"Wrapped Tezos\"},{\"name\":\"USDS\",\"type\":\"FA 2.0\",\"desc\":\"Stably USD\"},{\"name\":\"tzBTC\",\"type\":\"FA 1.2\",\"desc\":\"tzBTC\"},{\"name\":\"STKR\",\"type\":\"FA 1.2\",\"desc\":\"Staker Governance\"},{\"name\":\"USDtz\",\"type\":\"FA 1.2\",\"desc\":\"USDtez\"},{\"name\":\"ETHtz\",\"type\":\"FA 1.2\",\"desc\":\"ETHtez\"},{\"name\":\"hDAO\",\"type\":\"FA 2.0\",\"desc\":\"Hic Et Nunc governance\"},{\"name\":\"WRAP\",\"type\":\"FA 2.0\",\"desc\":\"Wrap Governance\"},{\"name\":\"CRUNCH\",\"type\":\"FA 2.0\",\"desc\":\"CRUNCH\"},{\"name\":\"wAAVE\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped AAVE\"},{\"name\":\"wBUSD\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped BUSD\"},{\"name\":\"wCEL\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped CEL\"},{\"name\":\"wCOMP\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped COMP\"},{\"name\":\"wCRO\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped CRO\"},{\"name\":\"wDAI\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped DAI\"},{\"name\":\"wFTT\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped FTT\"},{\"name\":\"wHT\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped HT\"},{\"name\":\"wHUSD\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped HUSD\"},{\"name\":\"wLEO\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped LEO\"},{\"name\":\"wLINK\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped LINK\"},{\"name\":\"wMATIC\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped MATIC\"},{\"name\":\"wMKR\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped MKR\"},{\"name\":\"wOKB\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped OKB\"},{\"name\":\"wPAX\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped PAX\"},{\"name\":\"wSUSHI\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped SUSHI\"},{\"name\":\"wUNI\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped UNI\"},{\"name\":\"wUSDC\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped USDC\"},{\"name\":\"wUSDT\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped USDT\"},{\"name\":\"wWBTC\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped WBTC\"},{\"name\":\"wWETH\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped WETH\"},{\"name\":\"PLENTY\",\"type\":\"FA 1.2\",\"desc\":\"Plenty DAO\"},{\"name\":\"KALAM\",\"type\":\"FA 2.0\",\"desc\":\"Kalamint\"},{\"name\":\"crDAO\",\"type\":\"FA 2.0\",\"desc\":\"Crunchy DAO\"},{\"name\":\"SMAK\",\"type\":\"FA 1.2\",\"desc\":\"SmartLink\"},{\"name\":\"kDAO\",\"type\":\"FA 1.2\",\"desc\":\"Kolibri DAO\"},{\"name\":\"uUSD\",\"type\":\"FA 2.0\",\"desc\":\"youves uUSD\"},{\"name\":\"uDEFI\",\"type\":\"FA 2.0\",\"desc\":\"youves uDEFI\"},{\"name\":\"bDAO\",\"type\":\"FA 2.0\",\"desc\":\"Bazaar DAO\"},{\"name\":\"YOU\",\"type\":\"FA 2.0\",\"desc\":\"youves YOU governance\"},{\"name\":\"RCKT\",\"type\":\"FA 2.0\",\"desc\":\"Rocket\"},{\"name\":\"rkDAO\",\"type\":\"FA 2.0\",\"desc\":\"Rocket DAO\"},{\"name\":\"UNO\",\"type\":\"FA 2.0\",\"desc\":\"Unobtanium\"},{\"name\":\"GIF\",\"type\":\"FA 2.0\",\"desc\":\"GIF DAO\"},{\"name\":\"IDZ\",\"type\":\"FA 2.0\",\"desc\":\"TezID\"},{\"name\":\"EASY\",\"type\":\"FA 2.0\",\"desc\":\"CryptoEasy\"},{\"name\":\"INSTA\",\"type\":\"FA 2.0\",\"desc\":\"Instaraise\"},{\"name\":\"xPLENTY\",\"type\":\"FA 1.2\",\"desc\":\"xPLENTY\"},{\"name\":\"ctez\",\"type\":\"FA 1.2\",\"desc\":\"Ctez\"},{\"name\":\"PAUL\",\"type\":\"FA 1.2\",\"desc\":\"PAUL Token\"},{\"name\":\"SPI\",\"type\":\"FA 2.0\",\"desc\":\"Spice Token\"},{\"name\":\"WTZ\",\"type\":\"FA 2.0\",\"desc\":\"WTZ\"},{\"name\":\"FLAME\",\"type\":\"FA 2.0\",\"desc\":\"FLAME\"},{\"name\":\"fDAO\",\"type\":\"FA 2.0\",\"desc\":\"fDAO\"},{\"name\":\"PXL\",\"type\":\"FA 2.0\",\"desc\":\"Pixel\"},{\"name\":\"sDAO\",\"type\":\"FA 2.0\",\"desc\":\"Salsa DAO\"},{\"name\":\"akaDAO\",\"type\":\"FA 2.0\",\"desc\":\"akaSwap DAO\"},{\"name\":\"MIN\",\"type\":\"FA 2.0\",\"desc\":\"Minerals\"},{\"name\":\"ENR\",\"type\":\"FA 2.0\",\"desc\":\"Energy\"},{\"name\":\"MCH\",\"type\":\"FA 2.0\",\"desc\":\"Machinery\"},{\"name\":\"uBTC\",\"type\":\"FA 2.0\",\"desc\":\"youves uBTC\"},{\"name\":\"MTRIA\",\"type\":\"FA 2.0\",\"desc\":\"Materia\"},{\"name\":\"DOGA\",\"type\":\"FA 1.2\",\"desc\":\"DOGAMI\"}]'),_E=[\"*\"];class pU{constructor(){this.columnIndex=0,this.rowIndex=0}get rowCount(){return this.rowIndex+1}get rowspan(){const t=Math.max(...this.tracker);return t>1?this.rowCount+t-1:this.rowCount}update(t,e){this.columnIndex=0,this.rowIndex=0,this.tracker=new Array(t),this.tracker.fill(0,0,this.tracker.length),this.positions=e.map(i=>this._trackTile(i))}_trackTile(t){const e=this._findMatchingGap(t.colspan);return this._markTilePosition(e,t),this.columnIndex=e+t.colspan,new fU(this.rowIndex,e)}_findMatchingGap(t){let e=-1,i=-1;do{this.columnIndex+t>this.tracker.length?(this._nextRow(),e=this.tracker.indexOf(0,this.columnIndex),i=this._findGapEndIndex(e)):(e=this.tracker.indexOf(0,this.columnIndex),-1!=e?(i=this._findGapEndIndex(e),this.columnIndex=e+1):(this._nextRow(),e=this.tracker.indexOf(0,this.columnIndex),i=this._findGapEndIndex(e)))}while(i-e<t||0==i);return Math.max(e,0)}_nextRow(){this.columnIndex=0,this.rowIndex++;for(let t=0;t<this.tracker.length;t++)this.tracker[t]=Math.max(0,this.tracker[t]-1)}_findGapEndIndex(t){for(let e=t+1;e<this.tracker.length;e++)if(0!=this.tracker[e])return e;return this.tracker.length}_markTilePosition(t,e){for(let i=0;i<e.colspan;i++)this.tracker[t+i]=e.rowspan}}class fU{constructor(t,e){this.row=t,this.col=e}}const vE=new b(\"MAT_GRID_LIST\");let yE=(()=>{class n{constructor(e,i){this._element=e,this._gridList=i,this._rowspan=1,this._colspan=1}get rowspan(){return this._rowspan}set rowspan(e){this._rowspan=Math.round(Et(e))}get colspan(){return this._colspan}set colspan(e){this._colspan=Math.round(Et(e))}_setStyle(e,i){this._element.nativeElement.style[e]=i}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(vE,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-grid-tile\"]],hostAttrs:[1,\"mat-grid-tile\"],hostVars:2,hostBindings:function(e,i){2&e&&Z(\"rowspan\",i.rowspan)(\"colspan\",i.colspan)},inputs:{rowspan:\"rowspan\",colspan:\"colspan\"},exportAs:[\"matGridTile\"],ngContentSelectors:_E,decls:2,vars:0,consts:[[1,\"mat-grid-tile-content\"]],template:function(e,i){1&e&&(Lt(),x(0,\"div\",0),Pe(1),S())},styles:[\".mat-grid-list{display:block;position:relative}.mat-grid-tile{display:block;position:absolute;overflow:hidden}.mat-grid-tile .mat-grid-tile-header,.mat-grid-tile .mat-grid-tile-footer{display:flex;align-items:center;height:48px;color:#fff;background:rgba(0,0,0,.38);overflow:hidden;padding:0 16px;position:absolute;left:0;right:0}.mat-grid-tile .mat-grid-tile-header>*,.mat-grid-tile .mat-grid-tile-footer>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-grid-tile .mat-grid-tile-header.mat-2-line,.mat-grid-tile .mat-grid-tile-footer.mat-2-line{height:68px}.mat-grid-tile .mat-grid-list-text{display:flex;flex-direction:column;flex:auto;box-sizing:border-box;overflow:hidden}.mat-grid-tile .mat-grid-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-grid-tile .mat-grid-list-text:empty{display:none}.mat-grid-tile .mat-grid-tile-header{top:0}.mat-grid-tile .mat-grid-tile-footer{bottom:0}.mat-grid-tile .mat-grid-avatar{padding-right:16px}[dir=rtl] .mat-grid-tile .mat-grid-avatar{padding-right:0;padding-left:16px}.mat-grid-tile .mat-grid-avatar:empty{display:none}.mat-grid-tile-content{top:0;left:0;right:0;bottom:0;position:absolute;display:flex;align-items:center;justify-content:center;height:100%;padding:0;margin:0}\\n\"],encapsulation:2,changeDetection:0}),n})();const mU=/^-?\\d+((\\.\\d+)?[A-Za-z%$]?)+$/;class pg{constructor(){this._rows=0,this._rowspan=0}init(t,e,i,r){this._gutterSize=bE(t),this._rows=e.rowCount,this._rowspan=e.rowspan,this._cols=i,this._direction=r}getBaseTileSize(t,e){return`(${t}% - (${this._gutterSize} * ${e}))`}getTilePosition(t,e){return 0===e?\"0\":Xr(`(${t} + ${this._gutterSize}) * ${e}`)}getTileSize(t,e){return`(${t} * ${e}) + (${e-1} * ${this._gutterSize})`}setStyle(t,e,i){let r=100/this._cols,s=(this._cols-1)/this._cols;this.setColStyles(t,i,r,s),this.setRowStyles(t,e,r,s)}setColStyles(t,e,i,r){let s=this.getBaseTileSize(i,r);t._setStyle(\"rtl\"===this._direction?\"right\":\"left\",this.getTilePosition(s,e)),t._setStyle(\"width\",Xr(this.getTileSize(s,t.colspan)))}getGutterSpan(){return`${this._gutterSize} * (${this._rowspan} - 1)`}getTileSpan(t){return`${this._rowspan} * ${this.getTileSize(t,1)}`}getComputedHeight(){return null}}class gU extends pg{constructor(t){super(),this.fixedRowHeight=t}init(t,e,i,r){super.init(t,e,i,r),this.fixedRowHeight=bE(this.fixedRowHeight),mU.test(this.fixedRowHeight)}setRowStyles(t,e){t._setStyle(\"top\",this.getTilePosition(this.fixedRowHeight,e)),t._setStyle(\"height\",Xr(this.getTileSize(this.fixedRowHeight,t.rowspan)))}getComputedHeight(){return[\"height\",Xr(`${this.getTileSpan(this.fixedRowHeight)} + ${this.getGutterSpan()}`)]}reset(t){t._setListStyle([\"height\",null]),t._tiles&&t._tiles.forEach(e=>{e._setStyle(\"top\",null),e._setStyle(\"height\",null)})}}class _U extends pg{constructor(t){super(),this._parseRatio(t)}setRowStyles(t,e,i,r){this.baseTileHeight=this.getBaseTileSize(i/this.rowHeightRatio,r),t._setStyle(\"marginTop\",this.getTilePosition(this.baseTileHeight,e)),t._setStyle(\"paddingTop\",Xr(this.getTileSize(this.baseTileHeight,t.rowspan)))}getComputedHeight(){return[\"paddingBottom\",Xr(`${this.getTileSpan(this.baseTileHeight)} + ${this.getGutterSpan()}`)]}reset(t){t._setListStyle([\"paddingBottom\",null]),t._tiles.forEach(e=>{e._setStyle(\"marginTop\",null),e._setStyle(\"paddingTop\",null)})}_parseRatio(t){const e=t.split(\":\");this.rowHeightRatio=parseFloat(e[0])/parseFloat(e[1])}}class vU extends pg{setRowStyles(t,e){let s=this.getBaseTileSize(100/this._rowspan,(this._rows-1)/this._rows);t._setStyle(\"top\",this.getTilePosition(s,e)),t._setStyle(\"height\",Xr(this.getTileSize(s,t.rowspan)))}reset(t){t._tiles&&t._tiles.forEach(e=>{e._setStyle(\"top\",null),e._setStyle(\"height\",null)})}}function Xr(n){return`calc(${n})`}function bE(n){return n.match(/([A-Za-z%]+)$/)?n:`${n}px`}let bU=(()=>{class n{constructor(e,i){this._element=e,this._dir=i,this._gutter=\"1px\"}get cols(){return this._cols}set cols(e){this._cols=Math.max(1,Math.round(Et(e)))}get gutterSize(){return this._gutter}set gutterSize(e){this._gutter=`${null==e?\"\":e}`}get rowHeight(){return this._rowHeight}set rowHeight(e){const i=`${null==e?\"\":e}`;i!==this._rowHeight&&(this._rowHeight=i,this._setTileStyler(this._rowHeight))}ngOnInit(){this._checkCols(),this._checkRowHeight()}ngAfterContentChecked(){this._layoutTiles()}_checkCols(){}_checkRowHeight(){this._rowHeight||this._setTileStyler(\"1:1\")}_setTileStyler(e){this._tileStyler&&this._tileStyler.reset(this),this._tileStyler=\"fit\"===e?new vU:e&&e.indexOf(\":\")>-1?new _U(e):new gU(e)}_layoutTiles(){this._tileCoordinator||(this._tileCoordinator=new pU);const e=this._tileCoordinator,i=this._tiles.filter(s=>!s._gridList||s._gridList===this),r=this._dir?this._dir.value:\"ltr\";this._tileCoordinator.update(this.cols,i),this._tileStyler.init(this.gutterSize,e,this.cols,r),i.forEach((s,o)=>{const a=e.positions[o];this._tileStyler.setStyle(s,a.row,a.col)}),this._setListStyle(this._tileStyler.getComputedHeight())}_setListStyle(e){e&&(this._element.nativeElement.style[e[0]]=e[1])}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(On,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-grid-list\"]],contentQueries:function(e,i,r){if(1&e&&ve(r,yE,5),2&e){let s;z(s=U())&&(i._tiles=s)}},hostAttrs:[1,\"mat-grid-list\"],hostVars:1,hostBindings:function(e,i){2&e&&Z(\"cols\",i.cols)},inputs:{cols:\"cols\",gutterSize:\"gutterSize\",rowHeight:\"rowHeight\"},exportAs:[\"matGridList\"],features:[L([{provide:vE,useExisting:n}])],ngContentSelectors:_E,decls:2,vars:0,template:function(e,i){1&e&&(Lt(),x(0,\"div\"),Pe(1),S())},styles:[\".mat-grid-list{display:block;position:relative}.mat-grid-tile{display:block;position:absolute;overflow:hidden}.mat-grid-tile .mat-grid-tile-header,.mat-grid-tile .mat-grid-tile-footer{display:flex;align-items:center;height:48px;color:#fff;background:rgba(0,0,0,.38);overflow:hidden;padding:0 16px;position:absolute;left:0;right:0}.mat-grid-tile .mat-grid-tile-header>*,.mat-grid-tile .mat-grid-tile-footer>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-grid-tile .mat-grid-tile-header.mat-2-line,.mat-grid-tile .mat-grid-tile-footer.mat-2-line{height:68px}.mat-grid-tile .mat-grid-list-text{display:flex;flex-direction:column;flex:auto;box-sizing:border-box;overflow:hidden}.mat-grid-tile .mat-grid-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-grid-tile .mat-grid-list-text:empty{display:none}.mat-grid-tile .mat-grid-tile-header{top:0}.mat-grid-tile .mat-grid-tile-footer{bottom:0}.mat-grid-tile .mat-grid-avatar{padding-right:16px}[dir=rtl] .mat-grid-tile .mat-grid-avatar{padding-right:0;padding-left:16px}.mat-grid-tile .mat-grid-avatar:empty{display:none}.mat-grid-tile-content{top:0;left:0;right:0;bottom:0;position:absolute;display:flex;align-items:center;justify-content:center;height:100%;padding:0;margin:0}\\n\"],encapsulation:2,changeDetection:0}),n})(),CU=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Vd,B],Vd,B]}),n})();const DU=[\"addListener\",\"removeListener\"],wU=[\"addEventListener\",\"removeEventListener\"],MU=[\"on\",\"off\"];function Jr(n,t,e,i){if(De(e)&&(i=e,e=void 0),i)return Jr(n,t,e).pipe(bf(i));const[r,s]=function SU(n){return De(n.addEventListener)&&De(n.removeEventListener)}(n)?wU.map(o=>a=>n[o](t,a,e)):function xU(n){return De(n.addListener)&&De(n.removeListener)}(n)?DU.map(CE(n,t)):function EU(n){return De(n.on)&&De(n.off)}(n)?MU.map(CE(n,t)):[];if(!r&&bu(n))return lt(o=>Jr(o,t,e))(Jt(n));if(!r)throw new TypeError(\"Invalid event target\");return new Ve(o=>{const a=(...l)=>o.next(1<l.length?l:l[0]);return r(a),()=>s(a)})}function CE(n,t){return e=>i=>n[e](t,i)}const kU=[\"connectionContainer\"],TU=[\"inputContainer\"],AU=[\"label\"];function IU(n,t){1&n&&(kr(0),x(1,\"div\",14),Le(2,\"div\",15)(3,\"div\",16)(4,\"div\",17),S(),x(5,\"div\",18),Le(6,\"div\",15)(7,\"div\",16)(8,\"div\",17),S(),Tr())}function RU(n,t){if(1&n){const e=ia();x(0,\"div\",19),J(\"cdkObserveContent\",function(){return Dr(e),Be().updateOutlineGap()}),Pe(1,1),S()}2&n&&N(\"cdkObserveContentDisabled\",\"outline\"!=Be().appearance)}function OU(n,t){if(1&n&&(kr(0),Pe(1,2),x(2,\"span\"),we(3),S(),Tr()),2&n){const e=Be(2);T(3),Ut(e._control.placeholder)}}function PU(n,t){1&n&&Pe(0,3,[\"*ngSwitchCase\",\"true\"])}function FU(n,t){1&n&&(x(0,\"span\",23),we(1,\" *\"),S())}function NU(n,t){if(1&n){const e=ia();x(0,\"label\",20,21),J(\"cdkObserveContent\",function(){return Dr(e),Be().updateOutlineGap()}),Ee(2,OU,4,1,\"ng-container\",12),Ee(3,PU,1,0,\"ng-content\",12),Ee(4,FU,2,0,\"span\",22),S()}if(2&n){const e=Be();Ae(\"mat-empty\",e._control.empty&&!e._shouldAlwaysFloat())(\"mat-form-field-empty\",e._control.empty&&!e._shouldAlwaysFloat())(\"mat-accent\",\"accent\"==e.color)(\"mat-warn\",\"warn\"==e.color),N(\"cdkObserveContentDisabled\",\"outline\"!=e.appearance)(\"id\",e._labelId)(\"ngSwitch\",e._hasLabel()),Z(\"for\",e._control.id)(\"aria-owns\",e._control.id),T(2),N(\"ngSwitchCase\",!1),T(1),N(\"ngSwitchCase\",!0),T(1),N(\"ngIf\",!e.hideRequiredMarker&&e._control.required&&!e._control.disabled)}}function LU(n,t){1&n&&(x(0,\"div\",24),Pe(1,4),S())}function BU(n,t){if(1&n&&(x(0,\"div\",25),Le(1,\"span\",26),S()),2&n){const e=Be();T(1),Ae(\"mat-accent\",\"accent\"==e.color)(\"mat-warn\",\"warn\"==e.color)}}function VU(n,t){1&n&&(x(0,\"div\"),Pe(1,5),S()),2&n&&N(\"@transitionMessages\",Be()._subscriptAnimationState)}function HU(n,t){if(1&n&&(x(0,\"div\",30),we(1),S()),2&n){const e=Be(2);N(\"id\",e._hintLabelId),T(1),Ut(e.hintLabel)}}function jU(n,t){if(1&n&&(x(0,\"div\",27),Ee(1,HU,2,2,\"div\",28),Pe(2,6),Le(3,\"div\",29),Pe(4,7),S()),2&n){const e=Be();N(\"@transitionMessages\",e._subscriptAnimationState),T(1),N(\"ngIf\",e.hintLabel)}}const zU=[\"*\",[[\"\",\"matPrefix\",\"\"]],[[\"mat-placeholder\"]],[[\"mat-label\"]],[[\"\",\"matSuffix\",\"\"]],[[\"mat-error\"]],[[\"mat-hint\",3,\"align\",\"end\"]],[[\"mat-hint\",\"align\",\"end\"]]],UU=[\"*\",\"[matPrefix]\",\"mat-placeholder\",\"mat-label\",\"[matSuffix]\",\"mat-error\",\"mat-hint:not([align='end'])\",\"mat-hint[align='end']\"];let $U=0;const DE=new b(\"MatError\");let GU=(()=>{class n{constructor(e,i){this.id=\"mat-error-\"+$U++,e||i.nativeElement.setAttribute(\"aria-live\",\"polite\")}}return n.\\u0275fac=function(e){return new(e||n)(kt(\"aria-live\"),f(W))},n.\\u0275dir=C({type:n,selectors:[[\"mat-error\"]],hostAttrs:[\"aria-atomic\",\"true\",1,\"mat-error\"],hostVars:1,hostBindings:function(e,i){2&e&&Z(\"id\",i.id)},inputs:{id:\"id\"},features:[L([{provide:DE,useExisting:n}])]}),n})();const WU={transitionMessages:Ke(\"transitionMessages\",[ae(\"enter\",R({opacity:1,transform:\"translateY(0%)\"})),ge(\"void => enter\",[R({opacity:0,transform:\"translateY(-5px)\"}),be(\"300ms cubic-bezier(0.55, 0, 0.55, 0.2)\")])])};let Ja=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n}),n})(),qU=0;const wE=new b(\"MatHint\");let YU=(()=>{class n{constructor(){this.align=\"start\",this.id=\"mat-hint-\"+qU++}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n,selectors:[[\"mat-hint\"]],hostAttrs:[1,\"mat-hint\"],hostVars:4,hostBindings:function(e,i){2&e&&(Z(\"id\",i.id)(\"align\",null),Ae(\"mat-form-field-hint-end\",\"end\"===i.align))},inputs:{align:\"align\",id:\"id\"},features:[L([{provide:wE,useExisting:n}])]}),n})(),fg=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n,selectors:[[\"mat-label\"]]}),n})(),QU=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n,selectors:[[\"mat-placeholder\"]]}),n})();const KU=new b(\"MatPrefix\"),ZU=new b(\"MatSuffix\");let ME=0;const JU=fo(class{constructor(n){this._elementRef=n}},\"primary\"),e5=new b(\"MAT_FORM_FIELD_DEFAULT_OPTIONS\"),el=new b(\"MatFormField\");let t5=(()=>{class n extends JU{constructor(e,i,r,s,o,a,l){super(e),this._changeDetectorRef=i,this._dir=r,this._defaults=s,this._platform=o,this._ngZone=a,this._outlineGapCalculationNeededImmediately=!1,this._outlineGapCalculationNeededOnStable=!1,this._destroyed=new O,this._showAlwaysAnimate=!1,this._subscriptAnimationState=\"\",this._hintLabel=\"\",this._hintLabelId=\"mat-hint-\"+ME++,this._labelId=\"mat-form-field-label-\"+ME++,this.floatLabel=this._getDefaultFloatLabelState(),this._animationsEnabled=\"NoopAnimations\"!==l,this.appearance=s&&s.appearance?s.appearance:\"legacy\",this._hideRequiredMarker=!(!s||null==s.hideRequiredMarker)&&s.hideRequiredMarker}get appearance(){return this._appearance}set appearance(e){const i=this._appearance;this._appearance=e||this._defaults&&this._defaults.appearance||\"legacy\",\"outline\"===this._appearance&&i!==e&&(this._outlineGapCalculationNeededOnStable=!0)}get hideRequiredMarker(){return this._hideRequiredMarker}set hideRequiredMarker(e){this._hideRequiredMarker=G(e)}_shouldAlwaysFloat(){return\"always\"===this.floatLabel&&!this._showAlwaysAnimate}_canLabelFloat(){return\"never\"!==this.floatLabel}get hintLabel(){return this._hintLabel}set hintLabel(e){this._hintLabel=e,this._processHints()}get floatLabel(){return\"legacy\"!==this.appearance&&\"never\"===this._floatLabel?\"auto\":this._floatLabel}set floatLabel(e){e!==this._floatLabel&&(this._floatLabel=e||this._getDefaultFloatLabelState(),this._changeDetectorRef.markForCheck())}get _control(){return this._explicitFormFieldControl||this._controlNonStatic||this._controlStatic}set _control(e){this._explicitFormFieldControl=e}getLabelId(){return this._hasFloatingLabel()?this._labelId:null}getConnectedOverlayOrigin(){return this._connectionContainerRef||this._elementRef}ngAfterContentInit(){this._validateControlChild();const e=this._control;e.controlType&&this._elementRef.nativeElement.classList.add(`mat-form-field-type-${e.controlType}`),e.stateChanges.pipe(Xn(null)).subscribe(()=>{this._validatePlaceholders(),this._syncDescribedByIds(),this._changeDetectorRef.markForCheck()}),e.ngControl&&e.ngControl.valueChanges&&e.ngControl.valueChanges.pipe(Ie(this._destroyed)).subscribe(()=>this._changeDetectorRef.markForCheck()),this._ngZone.runOutsideAngular(()=>{this._ngZone.onStable.pipe(Ie(this._destroyed)).subscribe(()=>{this._outlineGapCalculationNeededOnStable&&this.updateOutlineGap()})}),Bt(this._prefixChildren.changes,this._suffixChildren.changes).subscribe(()=>{this._outlineGapCalculationNeededOnStable=!0,this._changeDetectorRef.markForCheck()}),this._hintChildren.changes.pipe(Xn(null)).subscribe(()=>{this._processHints(),this._changeDetectorRef.markForCheck()}),this._errorChildren.changes.pipe(Xn(null)).subscribe(()=>{this._syncDescribedByIds(),this._changeDetectorRef.markForCheck()}),this._dir&&this._dir.change.pipe(Ie(this._destroyed)).subscribe(()=>{\"function\"==typeof requestAnimationFrame?this._ngZone.runOutsideAngular(()=>{requestAnimationFrame(()=>this.updateOutlineGap())}):this.updateOutlineGap()})}ngAfterContentChecked(){this._validateControlChild(),this._outlineGapCalculationNeededImmediately&&this.updateOutlineGap()}ngAfterViewInit(){this._subscriptAnimationState=\"enter\",this._changeDetectorRef.detectChanges()}ngOnDestroy(){this._destroyed.next(),this._destroyed.complete()}_shouldForward(e){const i=this._control?this._control.ngControl:null;return i&&i[e]}_hasPlaceholder(){return!!(this._control&&this._control.placeholder||this._placeholderChild)}_hasLabel(){return!(!this._labelChildNonStatic&&!this._labelChildStatic)}_shouldLabelFloat(){return this._canLabelFloat()&&(this._control&&this._control.shouldLabelFloat||this._shouldAlwaysFloat())}_hideControlPlaceholder(){return\"legacy\"===this.appearance&&!this._hasLabel()||this._hasLabel()&&!this._shouldLabelFloat()}_hasFloatingLabel(){return this._hasLabel()||\"legacy\"===this.appearance&&this._hasPlaceholder()}_getDisplayedMessages(){return this._errorChildren&&this._errorChildren.length>0&&this._control.errorState?\"error\":\"hint\"}_animateAndLockLabel(){this._hasFloatingLabel()&&this._canLabelFloat()&&(this._animationsEnabled&&this._label&&(this._showAlwaysAnimate=!0,Jr(this._label.nativeElement,\"transitionend\").pipe(it(1)).subscribe(()=>{this._showAlwaysAnimate=!1})),this.floatLabel=\"always\",this._changeDetectorRef.markForCheck())}_validatePlaceholders(){}_processHints(){this._validateHints(),this._syncDescribedByIds()}_validateHints(){}_getDefaultFloatLabelState(){return this._defaults&&this._defaults.floatLabel||\"auto\"}_syncDescribedByIds(){if(this._control){let e=[];if(this._control.userAriaDescribedBy&&\"string\"==typeof this._control.userAriaDescribedBy&&e.push(...this._control.userAriaDescribedBy.split(\" \")),\"hint\"===this._getDisplayedMessages()){const i=this._hintChildren?this._hintChildren.find(s=>\"start\"===s.align):null,r=this._hintChildren?this._hintChildren.find(s=>\"end\"===s.align):null;i?e.push(i.id):this._hintLabel&&e.push(this._hintLabelId),r&&e.push(r.id)}else this._errorChildren&&e.push(...this._errorChildren.map(i=>i.id));this._control.setDescribedByIds(e)}}_validateControlChild(){}updateOutlineGap(){const e=this._label?this._label.nativeElement:null,i=this._connectionContainerRef.nativeElement,r=\".mat-form-field-outline-start\",s=\".mat-form-field-outline-gap\";if(\"outline\"!==this.appearance||!this._platform.isBrowser)return;if(!e||!e.children.length||!e.textContent.trim()){const d=i.querySelectorAll(`${r}, ${s}`);for(let u=0;u<d.length;u++)d[u].style.width=\"0\";return}if(!this._isAttachedToDOM())return void(this._outlineGapCalculationNeededImmediately=!0);let o=0,a=0;const l=i.querySelectorAll(r),c=i.querySelectorAll(s);if(this._label&&this._label.nativeElement.children.length){const d=i.getBoundingClientRect();if(0===d.width&&0===d.height)return this._outlineGapCalculationNeededOnStable=!0,void(this._outlineGapCalculationNeededImmediately=!1);const u=this._getStartEnd(d),h=e.children,p=this._getStartEnd(h[0].getBoundingClientRect());let m=0;for(let g=0;g<h.length;g++)m+=h[g].offsetWidth;o=Math.abs(p-u)-5,a=m>0?.75*m+10:0}for(let d=0;d<l.length;d++)l[d].style.width=`${o}px`;for(let d=0;d<c.length;d++)c[d].style.width=`${a}px`;this._outlineGapCalculationNeededOnStable=this._outlineGapCalculationNeededImmediately=!1}_getStartEnd(e){return this._dir&&\"rtl\"===this._dir.value?e.right:e.left}_isAttachedToDOM(){const e=this._elementRef.nativeElement;if(e.getRootNode){const i=e.getRootNode();return i&&i!==e}return document.documentElement.contains(e)}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(Ye),f(On,8),f(e5,8),f(It),f(ne),f(Rn,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-form-field\"]],contentQueries:function(e,i,r){if(1&e&&(ve(r,Ja,5),ve(r,Ja,7),ve(r,fg,5),ve(r,fg,7),ve(r,QU,5),ve(r,DE,5),ve(r,wE,5),ve(r,KU,5),ve(r,ZU,5)),2&e){let s;z(s=U())&&(i._controlNonStatic=s.first),z(s=U())&&(i._controlStatic=s.first),z(s=U())&&(i._labelChildNonStatic=s.first),z(s=U())&&(i._labelChildStatic=s.first),z(s=U())&&(i._placeholderChild=s.first),z(s=U())&&(i._errorChildren=s),z(s=U())&&(i._hintChildren=s),z(s=U())&&(i._prefixChildren=s),z(s=U())&&(i._suffixChildren=s)}},viewQuery:function(e,i){if(1&e&&(je(kU,7),je(TU,5),je(AU,5)),2&e){let r;z(r=U())&&(i._connectionContainerRef=r.first),z(r=U())&&(i._inputContainerRef=r.first),z(r=U())&&(i._label=r.first)}},hostAttrs:[1,\"mat-form-field\"],hostVars:40,hostBindings:function(e,i){2&e&&Ae(\"mat-form-field-appearance-standard\",\"standard\"==i.appearance)(\"mat-form-field-appearance-fill\",\"fill\"==i.appearance)(\"mat-form-field-appearance-outline\",\"outline\"==i.appearance)(\"mat-form-field-appearance-legacy\",\"legacy\"==i.appearance)(\"mat-form-field-invalid\",i._control.errorState)(\"mat-form-field-can-float\",i._canLabelFloat())(\"mat-form-field-should-float\",i._shouldLabelFloat())(\"mat-form-field-has-label\",i._hasFloatingLabel())(\"mat-form-field-hide-placeholder\",i._hideControlPlaceholder())(\"mat-form-field-disabled\",i._control.disabled)(\"mat-form-field-autofilled\",i._control.autofilled)(\"mat-focused\",i._control.focused)(\"ng-untouched\",i._shouldForward(\"untouched\"))(\"ng-touched\",i._shouldForward(\"touched\"))(\"ng-pristine\",i._shouldForward(\"pristine\"))(\"ng-dirty\",i._shouldForward(\"dirty\"))(\"ng-valid\",i._shouldForward(\"valid\"))(\"ng-invalid\",i._shouldForward(\"invalid\"))(\"ng-pending\",i._shouldForward(\"pending\"))(\"_mat-animation-noopable\",!i._animationsEnabled)},inputs:{color:\"color\",appearance:\"appearance\",hideRequiredMarker:\"hideRequiredMarker\",hintLabel:\"hintLabel\",floatLabel:\"floatLabel\"},exportAs:[\"matFormField\"],features:[L([{provide:el,useExisting:n}]),E],ngContentSelectors:UU,decls:15,vars:8,consts:[[1,\"mat-form-field-wrapper\"],[1,\"mat-form-field-flex\",3,\"click\"],[\"connectionContainer\",\"\"],[4,\"ngIf\"],[\"class\",\"mat-form-field-prefix\",3,\"cdkObserveContentDisabled\",\"cdkObserveContent\",4,\"ngIf\"],[1,\"mat-form-field-infix\"],[\"inputContainer\",\"\"],[1,\"mat-form-field-label-wrapper\"],[\"class\",\"mat-form-field-label\",3,\"cdkObserveContentDisabled\",\"id\",\"mat-empty\",\"mat-form-field-empty\",\"mat-accent\",\"mat-warn\",\"ngSwitch\",\"cdkObserveContent\",4,\"ngIf\"],[\"class\",\"mat-form-field-suffix\",4,\"ngIf\"],[\"class\",\"mat-form-field-underline\",4,\"ngIf\"],[1,\"mat-form-field-subscript-wrapper\",3,\"ngSwitch\"],[4,\"ngSwitchCase\"],[\"class\",\"mat-form-field-hint-wrapper\",4,\"ngSwitchCase\"],[1,\"mat-form-field-outline\"],[1,\"mat-form-field-outline-start\"],[1,\"mat-form-field-outline-gap\"],[1,\"mat-form-field-outline-end\"],[1,\"mat-form-field-outline\",\"mat-form-field-outline-thick\"],[1,\"mat-form-field-prefix\",3,\"cdkObserveContentDisabled\",\"cdkObserveContent\"],[1,\"mat-form-field-label\",3,\"cdkObserveContentDisabled\",\"id\",\"ngSwitch\",\"cdkObserveContent\"],[\"label\",\"\"],[\"class\",\"mat-placeholder-required mat-form-field-required-marker\",\"aria-hidden\",\"true\",4,\"ngIf\"],[\"aria-hidden\",\"true\",1,\"mat-placeholder-required\",\"mat-form-field-required-marker\"],[1,\"mat-form-field-suffix\"],[1,\"mat-form-field-underline\"],[1,\"mat-form-field-ripple\"],[1,\"mat-form-field-hint-wrapper\"],[\"class\",\"mat-hint\",3,\"id\",4,\"ngIf\"],[1,\"mat-form-field-hint-spacer\"],[1,\"mat-hint\",3,\"id\"]],template:function(e,i){1&e&&(Lt(zU),x(0,\"div\",0)(1,\"div\",1,2),J(\"click\",function(s){return i._control.onContainerClick&&i._control.onContainerClick(s)}),Ee(3,IU,9,0,\"ng-container\",3),Ee(4,RU,2,1,\"div\",4),x(5,\"div\",5,6),Pe(7),x(8,\"span\",7),Ee(9,NU,5,16,\"label\",8),S()(),Ee(10,LU,2,0,\"div\",9),S(),Ee(11,BU,2,4,\"div\",10),x(12,\"div\",11),Ee(13,VU,2,1,\"div\",12),Ee(14,jU,5,2,\"div\",13),S()()),2&e&&(T(3),N(\"ngIf\",\"outline\"==i.appearance),T(1),N(\"ngIf\",i._prefixChildren.length),T(5),N(\"ngIf\",i._hasFloatingLabel()),T(1),N(\"ngIf\",i._suffixChildren.length),T(1),N(\"ngIf\",\"outline\"!=i.appearance),T(1),N(\"ngSwitch\",i._getDisplayedMessages()),T(1),N(\"ngSwitchCase\",\"error\"),T(1),N(\"ngSwitchCase\",\"hint\"))},directives:[Ca,Qm,Ys,Pc],styles:[\".mat-form-field{display:inline-block;position:relative;text-align:left}[dir=rtl] .mat-form-field{text-align:right}.mat-form-field-wrapper{position:relative}.mat-form-field-flex{display:inline-flex;align-items:baseline;box-sizing:border-box;width:100%}.mat-form-field-prefix,.mat-form-field-suffix{white-space:nowrap;flex:none;position:relative}.mat-form-field-infix{display:block;position:relative;flex:auto;min-width:0;width:180px}.cdk-high-contrast-active .mat-form-field-infix{border-image:linear-gradient(transparent, transparent)}.mat-form-field-label-wrapper{position:absolute;left:0;box-sizing:content-box;width:100%;height:100%;overflow:hidden;pointer-events:none}[dir=rtl] .mat-form-field-label-wrapper{left:auto;right:0}.mat-form-field-label{position:absolute;left:0;font:inherit;pointer-events:none;width:100%;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;transform-origin:0 0;transition:transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1),color 400ms cubic-bezier(0.25, 0.8, 0.25, 1),width 400ms cubic-bezier(0.25, 0.8, 0.25, 1);display:none}[dir=rtl] .mat-form-field-label{transform-origin:100% 0;left:auto;right:0}.cdk-high-contrast-active .mat-form-field-disabled .mat-form-field-label{color:GrayText}.mat-form-field-empty.mat-form-field-label,.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-label{display:block}.mat-form-field-autofill-control:-webkit-autofill+.mat-form-field-label-wrapper .mat-form-field-label{display:none}.mat-form-field-can-float .mat-form-field-autofill-control:-webkit-autofill+.mat-form-field-label-wrapper .mat-form-field-label{display:block;transition:none}.mat-input-server:focus+.mat-form-field-label-wrapper .mat-form-field-label,.mat-input-server[placeholder]:not(:placeholder-shown)+.mat-form-field-label-wrapper .mat-form-field-label{display:none}.mat-form-field-can-float .mat-input-server:focus+.mat-form-field-label-wrapper .mat-form-field-label,.mat-form-field-can-float .mat-input-server[placeholder]:not(:placeholder-shown)+.mat-form-field-label-wrapper .mat-form-field-label{display:block}.mat-form-field-label:not(.mat-form-field-empty){transition:none}.mat-form-field-underline{position:absolute;width:100%;pointer-events:none;transform:scale3d(1, 1.0001, 1)}.mat-form-field-ripple{position:absolute;left:0;width:100%;transform-origin:50%;transform:scaleX(0.5);opacity:0;transition:background-color 300ms cubic-bezier(0.55, 0, 0.55, 0.2)}.mat-form-field.mat-focused .mat-form-field-ripple,.mat-form-field.mat-form-field-invalid .mat-form-field-ripple{opacity:1;transform:none;transition:transform 300ms cubic-bezier(0.25, 0.8, 0.25, 1),opacity 100ms cubic-bezier(0.25, 0.8, 0.25, 1),background-color 300ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-subscript-wrapper{position:absolute;box-sizing:border-box;width:100%;overflow:hidden}.mat-form-field-subscript-wrapper .mat-icon,.mat-form-field-label-wrapper .mat-icon{width:1em;height:1em;font-size:inherit;vertical-align:baseline}.mat-form-field-hint-wrapper{display:flex}.mat-form-field-hint-spacer{flex:1 0 1em}.mat-error{display:block}.mat-form-field-control-wrapper{position:relative}.mat-form-field-hint-end{order:1}.mat-form-field._mat-animation-noopable .mat-form-field-label,.mat-form-field._mat-animation-noopable .mat-form-field-ripple{transition:none}\\n\",'.mat-form-field-appearance-fill .mat-form-field-flex{border-radius:4px 4px 0 0;padding:.75em .75em 0 .75em}.cdk-high-contrast-active .mat-form-field-appearance-fill .mat-form-field-flex{outline:solid 1px}.cdk-high-contrast-active .mat-form-field-appearance-fill.mat-form-field-disabled .mat-form-field-flex{outline-color:GrayText}.cdk-high-contrast-active .mat-form-field-appearance-fill.mat-focused .mat-form-field-flex{outline:dashed 3px}.mat-form-field-appearance-fill .mat-form-field-underline::before{content:\"\";display:block;position:absolute;bottom:0;height:1px;width:100%}.mat-form-field-appearance-fill .mat-form-field-ripple{bottom:0;height:2px}.cdk-high-contrast-active .mat-form-field-appearance-fill .mat-form-field-ripple{height:0}.mat-form-field-appearance-fill:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-underline .mat-form-field-ripple{opacity:1;transform:none;transition:opacity 600ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-appearance-fill._mat-animation-noopable:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-underline .mat-form-field-ripple{transition:none}.mat-form-field-appearance-fill .mat-form-field-subscript-wrapper{padding:0 1em}\\n','.mat-input-element{font:inherit;background:transparent;color:currentColor;border:none;outline:none;padding:0;margin:0;width:100%;max-width:100%;vertical-align:bottom;text-align:inherit;box-sizing:content-box}.mat-input-element:-moz-ui-invalid{box-shadow:none}.mat-input-element,.mat-input-element::-webkit-search-cancel-button,.mat-input-element::-webkit-search-decoration,.mat-input-element::-webkit-search-results-button,.mat-input-element::-webkit-search-results-decoration{-webkit-appearance:none}.mat-input-element::-webkit-contacts-auto-fill-button,.mat-input-element::-webkit-caps-lock-indicator,.mat-input-element:not([type=password])::-webkit-credentials-auto-fill-button{visibility:hidden}.mat-input-element[type=date],.mat-input-element[type=datetime],.mat-input-element[type=datetime-local],.mat-input-element[type=month],.mat-input-element[type=week],.mat-input-element[type=time]{line-height:1}.mat-input-element[type=date]::after,.mat-input-element[type=datetime]::after,.mat-input-element[type=datetime-local]::after,.mat-input-element[type=month]::after,.mat-input-element[type=week]::after,.mat-input-element[type=time]::after{content:\" \";white-space:pre;width:1px}.mat-input-element::-webkit-inner-spin-button,.mat-input-element::-webkit-calendar-picker-indicator,.mat-input-element::-webkit-clear-button{font-size:.75em}.mat-input-element::placeholder{-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-input-element::-moz-placeholder{-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-input-element::-webkit-input-placeholder{-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-input-element:-ms-input-placeholder{-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-hide-placeholder .mat-input-element::placeholder{color:transparent !important;-webkit-text-fill-color:transparent;transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-input-element::placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-input-element::-moz-placeholder{color:transparent !important;-webkit-text-fill-color:transparent;transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-input-element::-moz-placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-input-element::-webkit-input-placeholder{color:transparent !important;-webkit-text-fill-color:transparent;transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-input-element::-webkit-input-placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-input-element:-ms-input-placeholder{color:transparent !important;-webkit-text-fill-color:transparent;transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-input-element:-ms-input-placeholder{opacity:0}textarea.mat-input-element{resize:vertical;overflow:auto}textarea.mat-input-element.cdk-textarea-autosize{resize:none}textarea.mat-input-element{padding:2px 0;margin:-2px 0}select.mat-input-element{-moz-appearance:none;-webkit-appearance:none;position:relative;background-color:transparent;display:inline-flex;box-sizing:border-box;padding-top:1em;top:-1em;margin-bottom:-1em}select.mat-input-element::-moz-focus-inner{border:0}select.mat-input-element:not(:disabled){cursor:pointer}.mat-form-field-type-mat-native-select .mat-form-field-infix::after{content:\"\";width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;border-top:5px solid;position:absolute;top:50%;right:0;margin-top:-2.5px;pointer-events:none}[dir=rtl] .mat-form-field-type-mat-native-select .mat-form-field-infix::after{right:auto;left:0}.mat-form-field-type-mat-native-select .mat-input-element{padding-right:15px}[dir=rtl] .mat-form-field-type-mat-native-select .mat-input-element{padding-right:0;padding-left:15px}.mat-form-field-type-mat-native-select .mat-form-field-label-wrapper{max-width:calc(100% - 10px)}.mat-form-field-type-mat-native-select.mat-form-field-appearance-outline .mat-form-field-infix::after{margin-top:-5px}.mat-form-field-type-mat-native-select.mat-form-field-appearance-fill .mat-form-field-infix::after{margin-top:-10px}\\n',\".mat-form-field-appearance-legacy .mat-form-field-label{transform:perspective(100px)}.mat-form-field-appearance-legacy .mat-form-field-prefix .mat-icon,.mat-form-field-appearance-legacy .mat-form-field-suffix .mat-icon{width:1em}.mat-form-field-appearance-legacy .mat-form-field-prefix .mat-icon-button,.mat-form-field-appearance-legacy .mat-form-field-suffix .mat-icon-button{font:inherit;vertical-align:baseline}.mat-form-field-appearance-legacy .mat-form-field-prefix .mat-icon-button .mat-icon,.mat-form-field-appearance-legacy .mat-form-field-suffix .mat-icon-button .mat-icon{font-size:inherit}.mat-form-field-appearance-legacy .mat-form-field-underline{height:1px}.cdk-high-contrast-active .mat-form-field-appearance-legacy .mat-form-field-underline{height:0;border-top:solid 1px}.mat-form-field-appearance-legacy .mat-form-field-ripple{top:0;height:2px;overflow:hidden}.cdk-high-contrast-active .mat-form-field-appearance-legacy .mat-form-field-ripple{height:0;border-top:solid 2px}.mat-form-field-appearance-legacy.mat-form-field-disabled .mat-form-field-underline{background-position:0;background-color:transparent}.cdk-high-contrast-active .mat-form-field-appearance-legacy.mat-form-field-disabled .mat-form-field-underline{border-top-style:dotted;border-top-width:2px;border-top-color:GrayText}.mat-form-field-appearance-legacy.mat-form-field-invalid:not(.mat-focused) .mat-form-field-ripple{height:1px}\\n\",\".mat-form-field-appearance-outline .mat-form-field-wrapper{margin:.25em 0}.mat-form-field-appearance-outline .mat-form-field-flex{padding:0 .75em 0 .75em;margin-top:-0.25em;position:relative}.mat-form-field-appearance-outline .mat-form-field-prefix,.mat-form-field-appearance-outline .mat-form-field-suffix{top:.25em}.mat-form-field-appearance-outline .mat-form-field-outline{display:flex;position:absolute;top:.25em;left:0;right:0;bottom:0;pointer-events:none}.mat-form-field-appearance-outline .mat-form-field-outline-start,.mat-form-field-appearance-outline .mat-form-field-outline-end{border:1px solid currentColor;min-width:5px}.mat-form-field-appearance-outline .mat-form-field-outline-start{border-radius:5px 0 0 5px;border-right-style:none}[dir=rtl] .mat-form-field-appearance-outline .mat-form-field-outline-start{border-right-style:solid;border-left-style:none;border-radius:0 5px 5px 0}.mat-form-field-appearance-outline .mat-form-field-outline-end{border-radius:0 5px 5px 0;border-left-style:none;flex-grow:1}[dir=rtl] .mat-form-field-appearance-outline .mat-form-field-outline-end{border-left-style:solid;border-right-style:none;border-radius:5px 0 0 5px}.mat-form-field-appearance-outline .mat-form-field-outline-gap{border-radius:.000001px;border:1px solid currentColor;border-left-style:none;border-right-style:none}.mat-form-field-appearance-outline.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-outline-gap{border-top-color:transparent}.mat-form-field-appearance-outline .mat-form-field-outline-thick{opacity:0}.mat-form-field-appearance-outline .mat-form-field-outline-thick .mat-form-field-outline-start,.mat-form-field-appearance-outline .mat-form-field-outline-thick .mat-form-field-outline-end,.mat-form-field-appearance-outline .mat-form-field-outline-thick .mat-form-field-outline-gap{border-width:2px}.mat-form-field-appearance-outline.mat-focused .mat-form-field-outline,.mat-form-field-appearance-outline.mat-form-field-invalid .mat-form-field-outline{opacity:0;transition:opacity 100ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-appearance-outline.mat-focused .mat-form-field-outline-thick,.mat-form-field-appearance-outline.mat-form-field-invalid .mat-form-field-outline-thick{opacity:1}.cdk-high-contrast-active .mat-form-field-appearance-outline.mat-focused .mat-form-field-outline-thick{border:3px dashed}.mat-form-field-appearance-outline:not(.mat-form-field-disabled) .mat-form-field-flex:hover .mat-form-field-outline{opacity:0;transition:opacity 600ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-appearance-outline:not(.mat-form-field-disabled) .mat-form-field-flex:hover .mat-form-field-outline-thick{opacity:1}.mat-form-field-appearance-outline .mat-form-field-subscript-wrapper{padding:0 1em}.cdk-high-contrast-active .mat-form-field-appearance-outline.mat-form-field-disabled .mat-form-field-outline{color:GrayText}.mat-form-field-appearance-outline._mat-animation-noopable:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-outline,.mat-form-field-appearance-outline._mat-animation-noopable .mat-form-field-outline,.mat-form-field-appearance-outline._mat-animation-noopable .mat-form-field-outline-start,.mat-form-field-appearance-outline._mat-animation-noopable .mat-form-field-outline-end,.mat-form-field-appearance-outline._mat-animation-noopable .mat-form-field-outline-gap{transition:none}\\n\",\".mat-form-field-appearance-standard .mat-form-field-flex{padding-top:.75em}.mat-form-field-appearance-standard .mat-form-field-underline{height:1px}.cdk-high-contrast-active .mat-form-field-appearance-standard .mat-form-field-underline{height:0;border-top:solid 1px}.mat-form-field-appearance-standard .mat-form-field-ripple{bottom:0;height:2px}.cdk-high-contrast-active .mat-form-field-appearance-standard .mat-form-field-ripple{height:0;border-top:solid 2px}.mat-form-field-appearance-standard.mat-form-field-disabled .mat-form-field-underline{background-position:0;background-color:transparent}.cdk-high-contrast-active .mat-form-field-appearance-standard.mat-form-field-disabled .mat-form-field-underline{border-top-style:dotted;border-top-width:2px}.mat-form-field-appearance-standard:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-underline .mat-form-field-ripple{opacity:1;transform:none;transition:opacity 600ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-appearance-standard._mat-animation-noopable:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-underline .mat-form-field-ripple{transition:none}\\n\"],encapsulation:2,data:{animation:[WU.transitionMessages]},changeDetection:0}),n})(),mg=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B,Ya],B]}),n})();const tl={schedule(n){let t=requestAnimationFrame,e=cancelAnimationFrame;const{delegate:i}=tl;i&&(t=i.requestAnimationFrame,e=i.cancelAnimationFrame);const r=t(s=>{e=void 0,n(s)});return new ke(()=>null==e?void 0:e(r))},requestAnimationFrame(...n){const{delegate:t}=tl;return((null==t?void 0:t.requestAnimationFrame)||requestAnimationFrame)(...n)},cancelAnimationFrame(...n){const{delegate:t}=tl;return((null==t?void 0:t.cancelAnimationFrame)||cancelAnimationFrame)(...n)},delegate:void 0},EE=new class r5 extends Ym{flush(t){this._active=!0;const e=this._scheduled;this._scheduled=void 0;const{actions:i}=this;let r;t=t||i.shift();do{if(r=t.execute(t.state,t.delay))break}while((t=i[0])&&t.id===e&&i.shift());if(this._active=!1,r){for(;(t=i[0])&&t.id===e&&i.shift();)t.unsubscribe();throw r}}}(class n5 extends qm{constructor(t,e){super(t,e),this.scheduler=t,this.work=e}requestAsyncId(t,e,i=0){return null!==i&&i>0?super.requestAsyncId(t,e,i):(t.actions.push(this),t._scheduled||(t._scheduled=tl.requestAnimationFrame(()=>t.flush(void 0))))}recycleAsyncId(t,e,i=0){if(null!=i&&i>0||null==i&&this.delay>0)return super.recycleAsyncId(t,e,i);t.actions.some(r=>r.id===e)||(tl.cancelAnimationFrame(e),t._scheduled=void 0)}});let gg,s5=1;const jd={};function SE(n){return n in jd&&(delete jd[n],!0)}const o5={setImmediate(n){const t=s5++;return jd[t]=!0,gg||(gg=Promise.resolve()),gg.then(()=>SE(t)&&n()),t},clearImmediate(n){SE(n)}},{setImmediate:a5,clearImmediate:l5}=o5,zd={setImmediate(...n){const{delegate:t}=zd;return((null==t?void 0:t.setImmediate)||a5)(...n)},clearImmediate(n){const{delegate:t}=zd;return((null==t?void 0:t.clearImmediate)||l5)(n)},delegate:void 0};new class d5 extends Ym{flush(t){this._active=!0;const e=this._scheduled;this._scheduled=void 0;const{actions:i}=this;let r;t=t||i.shift();do{if(r=t.execute(t.state,t.delay))break}while((t=i[0])&&t.id===e&&i.shift());if(this._active=!1,r){for(;(t=i[0])&&t.id===e&&i.shift();)t.unsubscribe();throw r}}}(class c5 extends qm{constructor(t,e){super(t,e),this.scheduler=t,this.work=e}requestAsyncId(t,e,i=0){return null!==i&&i>0?super.requestAsyncId(t,e,i):(t.actions.push(this),t._scheduled||(t._scheduled=zd.setImmediate(t.flush.bind(t,void 0))))}recycleAsyncId(t,e,i=0){if(null!=i&&i>0||null==i&&this.delay>0)return super.recycleAsyncId(t,e,i);t.actions.some(r=>r.id===e)||(zd.clearImmediate(e),t._scheduled=void 0)}});function _g(n=0,t,e=t3){let i=-1;return null!=t&&(y_(t)?e=t:i=t),new Ve(r=>{let s=function p5(n){return n instanceof Date&&!isNaN(n)}(n)?+n-e.now():n;s<0&&(s=0);let o=0;return e.schedule(function(){r.closed||(r.next(o++),0<=i?this.schedule(void 0,i):r.complete())},s)})}function kE(n,t=qa){return function h5(n){return qe((t,e)=>{let i=!1,r=null,s=null,o=!1;const a=()=>{if(null==s||s.unsubscribe(),s=null,i){i=!1;const c=r;r=null,e.next(c)}o&&e.complete()},l=()=>{s=null,o&&e.complete()};t.subscribe(Ue(e,c=>{i=!0,r=c,s||Jt(n(c)).subscribe(s=Ue(e,a,l))},()=>{o=!0,(!i||!s||s.closed)&&e.complete()}))})}(()=>_g(n,t))}let m5=(()=>{class n{constructor(e,i,r){this._ngZone=e,this._platform=i,this._scrolled=new O,this._globalSubscription=null,this._scrolledCount=0,this.scrollContainers=new Map,this._document=r}register(e){this.scrollContainers.has(e)||this.scrollContainers.set(e,e.elementScrolled().subscribe(()=>this._scrolled.next(e)))}deregister(e){const i=this.scrollContainers.get(e);i&&(i.unsubscribe(),this.scrollContainers.delete(e))}scrolled(e=20){return this._platform.isBrowser?new Ve(i=>{this._globalSubscription||this._addGlobalListener();const r=e>0?this._scrolled.pipe(kE(e)).subscribe(i):this._scrolled.subscribe(i);return this._scrolledCount++,()=>{r.unsubscribe(),this._scrolledCount--,this._scrolledCount||this._removeGlobalListener()}}):q()}ngOnDestroy(){this._removeGlobalListener(),this.scrollContainers.forEach((e,i)=>this.deregister(i)),this._scrolled.complete()}ancestorScrolled(e,i){const r=this.getAncestorScrollContainers(e);return this.scrolled(i).pipe(Ct(s=>!s||r.indexOf(s)>-1))}getAncestorScrollContainers(e){const i=[];return this.scrollContainers.forEach((r,s)=>{this._scrollableContainsElement(s,e)&&i.push(s)}),i}_getWindow(){return this._document.defaultView||window}_scrollableContainsElement(e,i){let r=at(i),s=e.getElementRef().nativeElement;do{if(r==s)return!0}while(r=r.parentElement);return!1}_addGlobalListener(){this._globalSubscription=this._ngZone.runOutsideAngular(()=>Jr(this._getWindow().document,\"scroll\").subscribe(()=>this._scrolled.next()))}_removeGlobalListener(){this._globalSubscription&&(this._globalSubscription.unsubscribe(),this._globalSubscription=null)}}return n.\\u0275fac=function(e){return new(e||n)(y(ne),y(It),y(ie,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),es=(()=>{class n{constructor(e,i,r){this._platform=e,this._change=new O,this._changeListener=s=>{this._change.next(s)},this._document=r,i.runOutsideAngular(()=>{if(e.isBrowser){const s=this._getWindow();s.addEventListener(\"resize\",this._changeListener),s.addEventListener(\"orientationchange\",this._changeListener)}this.change().subscribe(()=>this._viewportSize=null)})}ngOnDestroy(){if(this._platform.isBrowser){const e=this._getWindow();e.removeEventListener(\"resize\",this._changeListener),e.removeEventListener(\"orientationchange\",this._changeListener)}this._change.complete()}getViewportSize(){this._viewportSize||this._updateViewportSize();const e={width:this._viewportSize.width,height:this._viewportSize.height};return this._platform.isBrowser||(this._viewportSize=null),e}getViewportRect(){const e=this.getViewportScrollPosition(),{width:i,height:r}=this.getViewportSize();return{top:e.top,left:e.left,bottom:e.top+r,right:e.left+i,height:r,width:i}}getViewportScrollPosition(){if(!this._platform.isBrowser)return{top:0,left:0};const e=this._document,i=this._getWindow(),r=e.documentElement,s=r.getBoundingClientRect();return{top:-s.top||e.body.scrollTop||i.scrollY||r.scrollTop||0,left:-s.left||e.body.scrollLeft||i.scrollX||r.scrollLeft||0}}change(e=20){return e>0?this._change.pipe(kE(e)):this._change}_getWindow(){return this._document.defaultView||window}_updateViewportSize(){const e=this._getWindow();this._viewportSize=this._platform.isBrowser?{width:e.innerWidth,height:e.innerHeight}:{width:0,height:0}}}return n.\\u0275fac=function(e){return new(e||n)(y(It),y(ne),y(ie,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),Ci=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),Ud=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[lo,Ci],lo,Ci]}),n})();class vg{attach(t){return this._attachedHost=t,t.attach(this)}detach(){let t=this._attachedHost;null!=t&&(this._attachedHost=null,t.detach())}get isAttached(){return null!=this._attachedHost}setAttachedHost(t){this._attachedHost=t}}class yg extends vg{constructor(t,e,i,r){super(),this.component=t,this.viewContainerRef=e,this.injector=i,this.componentFactoryResolver=r}}class $d extends vg{constructor(t,e,i){super(),this.templateRef=t,this.viewContainerRef=e,this.context=i}get origin(){return this.templateRef.elementRef}attach(t,e=this.context){return this.context=e,super.attach(t)}detach(){return this.context=void 0,super.detach()}}class _5 extends vg{constructor(t){super(),this.element=t instanceof W?t.nativeElement:t}}class bg{constructor(){this._isDisposed=!1,this.attachDomPortal=null}hasAttached(){return!!this._attachedPortal}attach(t){return t instanceof yg?(this._attachedPortal=t,this.attachComponentPortal(t)):t instanceof $d?(this._attachedPortal=t,this.attachTemplatePortal(t)):this.attachDomPortal&&t instanceof _5?(this._attachedPortal=t,this.attachDomPortal(t)):void 0}detach(){this._attachedPortal&&(this._attachedPortal.setAttachedHost(null),this._attachedPortal=null),this._invokeDisposeFn()}dispose(){this.hasAttached()&&this.detach(),this._invokeDisposeFn(),this._isDisposed=!0}setDisposeFn(t){this._disposeFn=t}_invokeDisposeFn(){this._disposeFn&&(this._disposeFn(),this._disposeFn=null)}}class v5 extends bg{constructor(t,e,i,r,s){super(),this.outletElement=t,this._componentFactoryResolver=e,this._appRef=i,this._defaultInjector=r,this.attachDomPortal=o=>{const a=o.element,l=this._document.createComment(\"dom-portal\");a.parentNode.insertBefore(l,a),this.outletElement.appendChild(a),this._attachedPortal=o,super.setDisposeFn(()=>{l.parentNode&&l.parentNode.replaceChild(a,l)})},this._document=s}attachComponentPortal(t){const i=(t.componentFactoryResolver||this._componentFactoryResolver).resolveComponentFactory(t.component);let r;return t.viewContainerRef?(r=t.viewContainerRef.createComponent(i,t.viewContainerRef.length,t.injector||t.viewContainerRef.injector),this.setDisposeFn(()=>r.destroy())):(r=i.create(t.injector||this._defaultInjector),this._appRef.attachView(r.hostView),this.setDisposeFn(()=>{this._appRef.detachView(r.hostView),r.destroy()})),this.outletElement.appendChild(this._getComponentRootNode(r)),this._attachedPortal=t,r}attachTemplatePortal(t){let e=t.viewContainerRef,i=e.createEmbeddedView(t.templateRef,t.context);return i.rootNodes.forEach(r=>this.outletElement.appendChild(r)),i.detectChanges(),this.setDisposeFn(()=>{let r=e.indexOf(i);-1!==r&&e.remove(r)}),this._attachedPortal=t,i}dispose(){super.dispose(),this.outletElement.remove()}_getComponentRootNode(t){return t.hostView.rootNodes[0]}}let TE=(()=>{class n extends bg{constructor(e,i,r){super(),this._componentFactoryResolver=e,this._viewContainerRef=i,this._isInitialized=!1,this.attached=new $,this.attachDomPortal=s=>{const o=s.element,a=this._document.createComment(\"dom-portal\");s.setAttachedHost(this),o.parentNode.insertBefore(a,o),this._getRootNode().appendChild(o),this._attachedPortal=s,super.setDisposeFn(()=>{a.parentNode&&a.parentNode.replaceChild(o,a)})},this._document=r}get portal(){return this._attachedPortal}set portal(e){this.hasAttached()&&!e&&!this._isInitialized||(this.hasAttached()&&super.detach(),e&&super.attach(e),this._attachedPortal=e||null)}get attachedRef(){return this._attachedRef}ngOnInit(){this._isInitialized=!0}ngOnDestroy(){super.dispose(),this._attachedPortal=null,this._attachedRef=null}attachComponentPortal(e){e.setAttachedHost(this);const i=null!=e.viewContainerRef?e.viewContainerRef:this._viewContainerRef,s=(e.componentFactoryResolver||this._componentFactoryResolver).resolveComponentFactory(e.component),o=i.createComponent(s,i.length,e.injector||i.injector);return i!==this._viewContainerRef&&this._getRootNode().appendChild(o.hostView.rootNodes[0]),super.setDisposeFn(()=>o.destroy()),this._attachedPortal=e,this._attachedRef=o,this.attached.emit(o),o}attachTemplatePortal(e){e.setAttachedHost(this);const i=this._viewContainerRef.createEmbeddedView(e.templateRef,e.context);return super.setDisposeFn(()=>this._viewContainerRef.clear()),this._attachedPortal=e,this._attachedRef=i,this.attached.emit(i),i}_getRootNode(){const e=this._viewContainerRef.element.nativeElement;return e.nodeType===e.ELEMENT_NODE?e:e.parentNode}}return n.\\u0275fac=function(e){return new(e||n)(f(Ir),f(st),f(ie))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"cdkPortalOutlet\",\"\"]],inputs:{portal:[\"cdkPortalOutlet\",\"portal\"]},outputs:{attached:\"attached\"},exportAs:[\"cdkPortalOutlet\"],features:[E]}),n})(),Hi=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const AE=jz();class b5{constructor(t,e){this._viewportRuler=t,this._previousHTMLStyles={top:\"\",left:\"\"},this._isEnabled=!1,this._document=e}attach(){}enable(){if(this._canBeEnabled()){const t=this._document.documentElement;this._previousScrollPosition=this._viewportRuler.getViewportScrollPosition(),this._previousHTMLStyles.left=t.style.left||\"\",this._previousHTMLStyles.top=t.style.top||\"\",t.style.left=ft(-this._previousScrollPosition.left),t.style.top=ft(-this._previousScrollPosition.top),t.classList.add(\"cdk-global-scrollblock\"),this._isEnabled=!0}}disable(){if(this._isEnabled){const t=this._document.documentElement,i=t.style,r=this._document.body.style,s=i.scrollBehavior||\"\",o=r.scrollBehavior||\"\";this._isEnabled=!1,i.left=this._previousHTMLStyles.left,i.top=this._previousHTMLStyles.top,t.classList.remove(\"cdk-global-scrollblock\"),AE&&(i.scrollBehavior=r.scrollBehavior=\"auto\"),window.scroll(this._previousScrollPosition.left,this._previousScrollPosition.top),AE&&(i.scrollBehavior=s,r.scrollBehavior=o)}}_canBeEnabled(){if(this._document.documentElement.classList.contains(\"cdk-global-scrollblock\")||this._isEnabled)return!1;const e=this._document.body,i=this._viewportRuler.getViewportSize();return e.scrollHeight>i.height||e.scrollWidth>i.width}}class C5{constructor(t,e,i,r){this._scrollDispatcher=t,this._ngZone=e,this._viewportRuler=i,this._config=r,this._scrollSubscription=null,this._detach=()=>{this.disable(),this._overlayRef.hasAttached()&&this._ngZone.run(()=>this._overlayRef.detach())}}attach(t){this._overlayRef=t}enable(){if(this._scrollSubscription)return;const t=this._scrollDispatcher.scrolled(0);this._config&&this._config.threshold&&this._config.threshold>1?(this._initialScrollPosition=this._viewportRuler.getViewportScrollPosition().top,this._scrollSubscription=t.subscribe(()=>{const e=this._viewportRuler.getViewportScrollPosition().top;Math.abs(e-this._initialScrollPosition)>this._config.threshold?this._detach():this._overlayRef.updatePosition()})):this._scrollSubscription=t.subscribe(this._detach)}disable(){this._scrollSubscription&&(this._scrollSubscription.unsubscribe(),this._scrollSubscription=null)}detach(){this.disable(),this._overlayRef=null}}class IE{enable(){}disable(){}attach(){}}function Cg(n,t){return t.some(e=>n.bottom<e.top||n.top>e.bottom||n.right<e.left||n.left>e.right)}function RE(n,t){return t.some(e=>n.top<e.top||n.bottom>e.bottom||n.left<e.left||n.right>e.right)}class D5{constructor(t,e,i,r){this._scrollDispatcher=t,this._viewportRuler=e,this._ngZone=i,this._config=r,this._scrollSubscription=null}attach(t){this._overlayRef=t}enable(){this._scrollSubscription||(this._scrollSubscription=this._scrollDispatcher.scrolled(this._config?this._config.scrollThrottle:0).subscribe(()=>{if(this._overlayRef.updatePosition(),this._config&&this._config.autoClose){const e=this._overlayRef.overlayElement.getBoundingClientRect(),{width:i,height:r}=this._viewportRuler.getViewportSize();Cg(e,[{width:i,height:r,bottom:r,right:i,top:0,left:0}])&&(this.disable(),this._ngZone.run(()=>this._overlayRef.detach()))}}))}disable(){this._scrollSubscription&&(this._scrollSubscription.unsubscribe(),this._scrollSubscription=null)}detach(){this.disable(),this._overlayRef=null}}let w5=(()=>{class n{constructor(e,i,r,s){this._scrollDispatcher=e,this._viewportRuler=i,this._ngZone=r,this.noop=()=>new IE,this.close=o=>new C5(this._scrollDispatcher,this._ngZone,this._viewportRuler,o),this.block=()=>new b5(this._viewportRuler,this._document),this.reposition=o=>new D5(this._scrollDispatcher,this._viewportRuler,this._ngZone,o),this._document=s}}return n.\\u0275fac=function(e){return new(e||n)(y(m5),y(es),y(ne),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();class Gd{constructor(t){if(this.scrollStrategy=new IE,this.panelClass=\"\",this.hasBackdrop=!1,this.backdropClass=\"cdk-overlay-dark-backdrop\",this.disposeOnNavigation=!1,t){const e=Object.keys(t);for(const i of e)void 0!==t[i]&&(this[i]=t[i])}}}class M5{constructor(t,e){this.connectionPair=t,this.scrollableViewProperties=e}}class x5{constructor(t,e,i,r,s,o,a,l,c){this._portalOutlet=t,this._host=e,this._pane=i,this._config=r,this._ngZone=s,this._keyboardDispatcher=o,this._document=a,this._location=l,this._outsideClickDispatcher=c,this._backdropElement=null,this._backdropClick=new O,this._attachments=new O,this._detachments=new O,this._locationChanges=ke.EMPTY,this._backdropClickHandler=d=>this._backdropClick.next(d),this._backdropTransitionendHandler=d=>{this._disposeBackdrop(d.target)},this._keydownEvents=new O,this._outsidePointerEvents=new O,r.scrollStrategy&&(this._scrollStrategy=r.scrollStrategy,this._scrollStrategy.attach(this)),this._positionStrategy=r.positionStrategy}get overlayElement(){return this._pane}get backdropElement(){return this._backdropElement}get hostElement(){return this._host}attach(t){let e=this._portalOutlet.attach(t);return!this._host.parentElement&&this._previousHostParent&&this._previousHostParent.appendChild(this._host),this._positionStrategy&&this._positionStrategy.attach(this),this._updateStackingOrder(),this._updateElementSize(),this._updateElementDirection(),this._scrollStrategy&&this._scrollStrategy.enable(),this._ngZone.onStable.pipe(it(1)).subscribe(()=>{this.hasAttached()&&this.updatePosition()}),this._togglePointerEvents(!0),this._config.hasBackdrop&&this._attachBackdrop(),this._config.panelClass&&this._toggleClasses(this._pane,this._config.panelClass,!0),this._attachments.next(),this._keyboardDispatcher.add(this),this._config.disposeOnNavigation&&(this._locationChanges=this._location.subscribe(()=>this.dispose())),this._outsideClickDispatcher.add(this),e}detach(){if(!this.hasAttached())return;this.detachBackdrop(),this._togglePointerEvents(!1),this._positionStrategy&&this._positionStrategy.detach&&this._positionStrategy.detach(),this._scrollStrategy&&this._scrollStrategy.disable();const t=this._portalOutlet.detach();return this._detachments.next(),this._keyboardDispatcher.remove(this),this._detachContentWhenStable(),this._locationChanges.unsubscribe(),this._outsideClickDispatcher.remove(this),t}dispose(){var t;const e=this.hasAttached();this._positionStrategy&&this._positionStrategy.dispose(),this._disposeScrollStrategy(),this._disposeBackdrop(this._backdropElement),this._locationChanges.unsubscribe(),this._keyboardDispatcher.remove(this),this._portalOutlet.dispose(),this._attachments.complete(),this._backdropClick.complete(),this._keydownEvents.complete(),this._outsidePointerEvents.complete(),this._outsideClickDispatcher.remove(this),null===(t=this._host)||void 0===t||t.remove(),this._previousHostParent=this._pane=this._host=null,e&&this._detachments.next(),this._detachments.complete()}hasAttached(){return this._portalOutlet.hasAttached()}backdropClick(){return this._backdropClick}attachments(){return this._attachments}detachments(){return this._detachments}keydownEvents(){return this._keydownEvents}outsidePointerEvents(){return this._outsidePointerEvents}getConfig(){return this._config}updatePosition(){this._positionStrategy&&this._positionStrategy.apply()}updatePositionStrategy(t){t!==this._positionStrategy&&(this._positionStrategy&&this._positionStrategy.dispose(),this._positionStrategy=t,this.hasAttached()&&(t.attach(this),this.updatePosition()))}updateSize(t){this._config=Object.assign(Object.assign({},this._config),t),this._updateElementSize()}setDirection(t){this._config=Object.assign(Object.assign({},this._config),{direction:t}),this._updateElementDirection()}addPanelClass(t){this._pane&&this._toggleClasses(this._pane,t,!0)}removePanelClass(t){this._pane&&this._toggleClasses(this._pane,t,!1)}getDirection(){const t=this._config.direction;return t?\"string\"==typeof t?t:t.value:\"ltr\"}updateScrollStrategy(t){t!==this._scrollStrategy&&(this._disposeScrollStrategy(),this._scrollStrategy=t,this.hasAttached()&&(t.attach(this),t.enable()))}_updateElementDirection(){this._host.setAttribute(\"dir\",this.getDirection())}_updateElementSize(){if(!this._pane)return;const t=this._pane.style;t.width=ft(this._config.width),t.height=ft(this._config.height),t.minWidth=ft(this._config.minWidth),t.minHeight=ft(this._config.minHeight),t.maxWidth=ft(this._config.maxWidth),t.maxHeight=ft(this._config.maxHeight)}_togglePointerEvents(t){this._pane.style.pointerEvents=t?\"\":\"none\"}_attachBackdrop(){const t=\"cdk-overlay-backdrop-showing\";this._backdropElement=this._document.createElement(\"div\"),this._backdropElement.classList.add(\"cdk-overlay-backdrop\"),this._config.backdropClass&&this._toggleClasses(this._backdropElement,this._config.backdropClass,!0),this._host.parentElement.insertBefore(this._backdropElement,this._host),this._backdropElement.addEventListener(\"click\",this._backdropClickHandler),\"undefined\"!=typeof requestAnimationFrame?this._ngZone.runOutsideAngular(()=>{requestAnimationFrame(()=>{this._backdropElement&&this._backdropElement.classList.add(t)})}):this._backdropElement.classList.add(t)}_updateStackingOrder(){this._host.nextSibling&&this._host.parentNode.appendChild(this._host)}detachBackdrop(){const t=this._backdropElement;!t||(t.classList.remove(\"cdk-overlay-backdrop-showing\"),this._ngZone.runOutsideAngular(()=>{t.addEventListener(\"transitionend\",this._backdropTransitionendHandler)}),t.style.pointerEvents=\"none\",this._backdropTimeout=this._ngZone.runOutsideAngular(()=>setTimeout(()=>{this._disposeBackdrop(t)},500)))}_toggleClasses(t,e,i){const r=Wx(e||[]).filter(s=>!!s);r.length&&(i?t.classList.add(...r):t.classList.remove(...r))}_detachContentWhenStable(){this._ngZone.runOutsideAngular(()=>{const t=this._ngZone.onStable.pipe(Ie(Bt(this._attachments,this._detachments))).subscribe(()=>{(!this._pane||!this._host||0===this._pane.children.length)&&(this._pane&&this._config.panelClass&&this._toggleClasses(this._pane,this._config.panelClass,!1),this._host&&this._host.parentElement&&(this._previousHostParent=this._host.parentElement,this._host.remove()),t.unsubscribe())})})}_disposeScrollStrategy(){const t=this._scrollStrategy;t&&(t.disable(),t.detach&&t.detach())}_disposeBackdrop(t){t&&(t.removeEventListener(\"click\",this._backdropClickHandler),t.removeEventListener(\"transitionend\",this._backdropTransitionendHandler),t.remove(),this._backdropElement===t&&(this._backdropElement=null)),this._backdropTimeout&&(clearTimeout(this._backdropTimeout),this._backdropTimeout=void 0)}}let Dg=(()=>{class n{constructor(e,i){this._platform=i,this._document=e}ngOnDestroy(){var e;null===(e=this._containerElement)||void 0===e||e.remove()}getContainerElement(){return this._containerElement||this._createContainer(),this._containerElement}_createContainer(){const e=\"cdk-overlay-container\";if(this._platform.isBrowser||jm()){const r=this._document.querySelectorAll(`.${e}[platform=\"server\"], .${e}[platform=\"test\"]`);for(let s=0;s<r.length;s++)r[s].remove()}const i=this._document.createElement(\"div\");i.classList.add(e),jm()?i.setAttribute(\"platform\",\"test\"):this._platform.isBrowser||i.setAttribute(\"platform\",\"server\"),this._document.body.appendChild(i),this._containerElement=i}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(It))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const OE=\"cdk-overlay-connected-position-bounding-box\",E5=/([A-Za-z%]+)$/;class S5{constructor(t,e,i,r,s){this._viewportRuler=e,this._document=i,this._platform=r,this._overlayContainer=s,this._lastBoundingBoxSize={width:0,height:0},this._isPushed=!1,this._canPush=!0,this._growAfterOpen=!1,this._hasFlexibleDimensions=!0,this._positionLocked=!1,this._viewportMargin=0,this._scrollables=[],this._preferredPositions=[],this._positionChanges=new O,this._resizeSubscription=ke.EMPTY,this._offsetX=0,this._offsetY=0,this._appliedPanelClasses=[],this.positionChanges=this._positionChanges,this.setOrigin(t)}get positions(){return this._preferredPositions}attach(t){this._validatePositions(),t.hostElement.classList.add(OE),this._overlayRef=t,this._boundingBox=t.hostElement,this._pane=t.overlayElement,this._isDisposed=!1,this._isInitialRender=!0,this._lastPosition=null,this._resizeSubscription.unsubscribe(),this._resizeSubscription=this._viewportRuler.change().subscribe(()=>{this._isInitialRender=!0,this.apply()})}apply(){if(this._isDisposed||!this._platform.isBrowser)return;if(!this._isInitialRender&&this._positionLocked&&this._lastPosition)return void this.reapplyLastPosition();this._clearPanelClasses(),this._resetOverlayElementStyles(),this._resetBoundingBoxStyles(),this._viewportRect=this._getNarrowedViewportRect(),this._originRect=this._getOriginRect(),this._overlayRect=this._pane.getBoundingClientRect(),this._containerRect=this._overlayContainer.getContainerElement().getBoundingClientRect();const t=this._originRect,e=this._overlayRect,i=this._viewportRect,r=this._containerRect,s=[];let o;for(let a of this._preferredPositions){let l=this._getOriginPoint(t,r,a),c=this._getOverlayPoint(l,e,a),d=this._getOverlayFit(c,e,i,a);if(d.isCompletelyWithinViewport)return this._isPushed=!1,void this._applyPosition(a,l);this._canFitWithFlexibleDimensions(d,c,i)?s.push({position:a,origin:l,overlayRect:e,boundingBoxRect:this._calculateBoundingBoxRect(l,a)}):(!o||o.overlayFit.visibleArea<d.visibleArea)&&(o={overlayFit:d,overlayPoint:c,originPoint:l,position:a,overlayRect:e})}if(s.length){let a=null,l=-1;for(const c of s){const d=c.boundingBoxRect.width*c.boundingBoxRect.height*(c.position.weight||1);d>l&&(l=d,a=c)}return this._isPushed=!1,void this._applyPosition(a.position,a.origin)}if(this._canPush)return this._isPushed=!0,void this._applyPosition(o.position,o.originPoint);this._applyPosition(o.position,o.originPoint)}detach(){this._clearPanelClasses(),this._lastPosition=null,this._previousPushAmount=null,this._resizeSubscription.unsubscribe()}dispose(){this._isDisposed||(this._boundingBox&&ts(this._boundingBox.style,{top:\"\",left:\"\",right:\"\",bottom:\"\",height:\"\",width:\"\",alignItems:\"\",justifyContent:\"\"}),this._pane&&this._resetOverlayElementStyles(),this._overlayRef&&this._overlayRef.hostElement.classList.remove(OE),this.detach(),this._positionChanges.complete(),this._overlayRef=this._boundingBox=null,this._isDisposed=!0)}reapplyLastPosition(){if(this._isDisposed||!this._platform.isBrowser)return;const t=this._lastPosition;if(t){this._originRect=this._getOriginRect(),this._overlayRect=this._pane.getBoundingClientRect(),this._viewportRect=this._getNarrowedViewportRect(),this._containerRect=this._overlayContainer.getContainerElement().getBoundingClientRect();const e=this._getOriginPoint(this._originRect,this._containerRect,t);this._applyPosition(t,e)}else this.apply()}withScrollableContainers(t){return this._scrollables=t,this}withPositions(t){return this._preferredPositions=t,-1===t.indexOf(this._lastPosition)&&(this._lastPosition=null),this._validatePositions(),this}withViewportMargin(t){return this._viewportMargin=t,this}withFlexibleDimensions(t=!0){return this._hasFlexibleDimensions=t,this}withGrowAfterOpen(t=!0){return this._growAfterOpen=t,this}withPush(t=!0){return this._canPush=t,this}withLockedPosition(t=!0){return this._positionLocked=t,this}setOrigin(t){return this._origin=t,this}withDefaultOffsetX(t){return this._offsetX=t,this}withDefaultOffsetY(t){return this._offsetY=t,this}withTransformOriginOn(t){return this._transformOriginSelector=t,this}_getOriginPoint(t,e,i){let r,s;if(\"center\"==i.originX)r=t.left+t.width/2;else{const o=this._isRtl()?t.right:t.left,a=this._isRtl()?t.left:t.right;r=\"start\"==i.originX?o:a}return e.left<0&&(r-=e.left),s=\"center\"==i.originY?t.top+t.height/2:\"top\"==i.originY?t.top:t.bottom,e.top<0&&(s-=e.top),{x:r,y:s}}_getOverlayPoint(t,e,i){let r,s;return r=\"center\"==i.overlayX?-e.width/2:\"start\"===i.overlayX?this._isRtl()?-e.width:0:this._isRtl()?0:-e.width,s=\"center\"==i.overlayY?-e.height/2:\"top\"==i.overlayY?0:-e.height,{x:t.x+r,y:t.y+s}}_getOverlayFit(t,e,i,r){const s=FE(e);let{x:o,y:a}=t,l=this._getOffset(r,\"x\"),c=this._getOffset(r,\"y\");l&&(o+=l),c&&(a+=c);let h=0-a,p=a+s.height-i.height,m=this._subtractOverflows(s.width,0-o,o+s.width-i.width),g=this._subtractOverflows(s.height,h,p),_=m*g;return{visibleArea:_,isCompletelyWithinViewport:s.width*s.height===_,fitsInViewportVertically:g===s.height,fitsInViewportHorizontally:m==s.width}}_canFitWithFlexibleDimensions(t,e,i){if(this._hasFlexibleDimensions){const r=i.bottom-e.y,s=i.right-e.x,o=PE(this._overlayRef.getConfig().minHeight),a=PE(this._overlayRef.getConfig().minWidth),c=t.fitsInViewportHorizontally||null!=a&&a<=s;return(t.fitsInViewportVertically||null!=o&&o<=r)&&c}return!1}_pushOverlayOnScreen(t,e,i){if(this._previousPushAmount&&this._positionLocked)return{x:t.x+this._previousPushAmount.x,y:t.y+this._previousPushAmount.y};const r=FE(e),s=this._viewportRect,o=Math.max(t.x+r.width-s.width,0),a=Math.max(t.y+r.height-s.height,0),l=Math.max(s.top-i.top-t.y,0),c=Math.max(s.left-i.left-t.x,0);let d=0,u=0;return d=r.width<=s.width?c||-o:t.x<this._viewportMargin?s.left-i.left-t.x:0,u=r.height<=s.height?l||-a:t.y<this._viewportMargin?s.top-i.top-t.y:0,this._previousPushAmount={x:d,y:u},{x:t.x+d,y:t.y+u}}_applyPosition(t,e){if(this._setTransformOrigin(t),this._setOverlayElementStyles(e,t),this._setBoundingBoxStyles(e,t),t.panelClass&&this._addPanelClasses(t.panelClass),this._lastPosition=t,this._positionChanges.observers.length){const i=this._getScrollVisibility(),r=new M5(t,i);this._positionChanges.next(r)}this._isInitialRender=!1}_setTransformOrigin(t){if(!this._transformOriginSelector)return;const e=this._boundingBox.querySelectorAll(this._transformOriginSelector);let i,r=t.overlayY;i=\"center\"===t.overlayX?\"center\":this._isRtl()?\"start\"===t.overlayX?\"right\":\"left\":\"start\"===t.overlayX?\"left\":\"right\";for(let s=0;s<e.length;s++)e[s].style.transformOrigin=`${i} ${r}`}_calculateBoundingBoxRect(t,e){const i=this._viewportRect,r=this._isRtl();let s,o,a,d,u,h;if(\"top\"===e.overlayY)o=t.y,s=i.height-o+this._viewportMargin;else if(\"bottom\"===e.overlayY)a=i.height-t.y+2*this._viewportMargin,s=i.height-a+this._viewportMargin;else{const p=Math.min(i.bottom-t.y+i.top,t.y),m=this._lastBoundingBoxSize.height;s=2*p,o=t.y-p,s>m&&!this._isInitialRender&&!this._growAfterOpen&&(o=t.y-m/2)}if(\"end\"===e.overlayX&&!r||\"start\"===e.overlayX&&r)h=i.width-t.x+this._viewportMargin,d=t.x-this._viewportMargin;else if(\"start\"===e.overlayX&&!r||\"end\"===e.overlayX&&r)u=t.x,d=i.right-t.x;else{const p=Math.min(i.right-t.x+i.left,t.x),m=this._lastBoundingBoxSize.width;d=2*p,u=t.x-p,d>m&&!this._isInitialRender&&!this._growAfterOpen&&(u=t.x-m/2)}return{top:o,left:u,bottom:a,right:h,width:d,height:s}}_setBoundingBoxStyles(t,e){const i=this._calculateBoundingBoxRect(t,e);!this._isInitialRender&&!this._growAfterOpen&&(i.height=Math.min(i.height,this._lastBoundingBoxSize.height),i.width=Math.min(i.width,this._lastBoundingBoxSize.width));const r={};if(this._hasExactPosition())r.top=r.left=\"0\",r.bottom=r.right=r.maxHeight=r.maxWidth=\"\",r.width=r.height=\"100%\";else{const s=this._overlayRef.getConfig().maxHeight,o=this._overlayRef.getConfig().maxWidth;r.height=ft(i.height),r.top=ft(i.top),r.bottom=ft(i.bottom),r.width=ft(i.width),r.left=ft(i.left),r.right=ft(i.right),r.alignItems=\"center\"===e.overlayX?\"center\":\"end\"===e.overlayX?\"flex-end\":\"flex-start\",r.justifyContent=\"center\"===e.overlayY?\"center\":\"bottom\"===e.overlayY?\"flex-end\":\"flex-start\",s&&(r.maxHeight=ft(s)),o&&(r.maxWidth=ft(o))}this._lastBoundingBoxSize=i,ts(this._boundingBox.style,r)}_resetBoundingBoxStyles(){ts(this._boundingBox.style,{top:\"0\",left:\"0\",right:\"0\",bottom:\"0\",height:\"\",width:\"\",alignItems:\"\",justifyContent:\"\"})}_resetOverlayElementStyles(){ts(this._pane.style,{top:\"\",left:\"\",bottom:\"\",right:\"\",position:\"\",transform:\"\"})}_setOverlayElementStyles(t,e){const i={},r=this._hasExactPosition(),s=this._hasFlexibleDimensions,o=this._overlayRef.getConfig();if(r){const d=this._viewportRuler.getViewportScrollPosition();ts(i,this._getExactOverlayY(e,t,d)),ts(i,this._getExactOverlayX(e,t,d))}else i.position=\"static\";let a=\"\",l=this._getOffset(e,\"x\"),c=this._getOffset(e,\"y\");l&&(a+=`translateX(${l}px) `),c&&(a+=`translateY(${c}px)`),i.transform=a.trim(),o.maxHeight&&(r?i.maxHeight=ft(o.maxHeight):s&&(i.maxHeight=\"\")),o.maxWidth&&(r?i.maxWidth=ft(o.maxWidth):s&&(i.maxWidth=\"\")),ts(this._pane.style,i)}_getExactOverlayY(t,e,i){let r={top:\"\",bottom:\"\"},s=this._getOverlayPoint(e,this._overlayRect,t);return this._isPushed&&(s=this._pushOverlayOnScreen(s,this._overlayRect,i)),\"bottom\"===t.overlayY?r.bottom=this._document.documentElement.clientHeight-(s.y+this._overlayRect.height)+\"px\":r.top=ft(s.y),r}_getExactOverlayX(t,e,i){let o,r={left:\"\",right:\"\"},s=this._getOverlayPoint(e,this._overlayRect,t);return this._isPushed&&(s=this._pushOverlayOnScreen(s,this._overlayRect,i)),o=this._isRtl()?\"end\"===t.overlayX?\"left\":\"right\":\"end\"===t.overlayX?\"right\":\"left\",\"right\"===o?r.right=this._document.documentElement.clientWidth-(s.x+this._overlayRect.width)+\"px\":r.left=ft(s.x),r}_getScrollVisibility(){const t=this._getOriginRect(),e=this._pane.getBoundingClientRect(),i=this._scrollables.map(r=>r.getElementRef().nativeElement.getBoundingClientRect());return{isOriginClipped:RE(t,i),isOriginOutsideView:Cg(t,i),isOverlayClipped:RE(e,i),isOverlayOutsideView:Cg(e,i)}}_subtractOverflows(t,...e){return e.reduce((i,r)=>i-Math.max(r,0),t)}_getNarrowedViewportRect(){const t=this._document.documentElement.clientWidth,e=this._document.documentElement.clientHeight,i=this._viewportRuler.getViewportScrollPosition();return{top:i.top+this._viewportMargin,left:i.left+this._viewportMargin,right:i.left+t-this._viewportMargin,bottom:i.top+e-this._viewportMargin,width:t-2*this._viewportMargin,height:e-2*this._viewportMargin}}_isRtl(){return\"rtl\"===this._overlayRef.getDirection()}_hasExactPosition(){return!this._hasFlexibleDimensions||this._isPushed}_getOffset(t,e){return\"x\"===e?null==t.offsetX?this._offsetX:t.offsetX:null==t.offsetY?this._offsetY:t.offsetY}_validatePositions(){}_addPanelClasses(t){this._pane&&Wx(t).forEach(e=>{\"\"!==e&&-1===this._appliedPanelClasses.indexOf(e)&&(this._appliedPanelClasses.push(e),this._pane.classList.add(e))})}_clearPanelClasses(){this._pane&&(this._appliedPanelClasses.forEach(t=>{this._pane.classList.remove(t)}),this._appliedPanelClasses=[])}_getOriginRect(){const t=this._origin;if(t instanceof W)return t.nativeElement.getBoundingClientRect();if(t instanceof Element)return t.getBoundingClientRect();const e=t.width||0,i=t.height||0;return{top:t.y,bottom:t.y+i,left:t.x,right:t.x+e,height:i,width:e}}}function ts(n,t){for(let e in t)t.hasOwnProperty(e)&&(n[e]=t[e]);return n}function PE(n){if(\"number\"!=typeof n&&null!=n){const[t,e]=n.split(E5);return e&&\"px\"!==e?null:parseFloat(t)}return n||null}function FE(n){return{top:Math.floor(n.top),right:Math.floor(n.right),bottom:Math.floor(n.bottom),left:Math.floor(n.left),width:Math.floor(n.width),height:Math.floor(n.height)}}const NE=\"cdk-global-overlay-wrapper\";class k5{constructor(){this._cssPosition=\"static\",this._topOffset=\"\",this._bottomOffset=\"\",this._leftOffset=\"\",this._rightOffset=\"\",this._alignItems=\"\",this._justifyContent=\"\",this._width=\"\",this._height=\"\"}attach(t){const e=t.getConfig();this._overlayRef=t,this._width&&!e.width&&t.updateSize({width:this._width}),this._height&&!e.height&&t.updateSize({height:this._height}),t.hostElement.classList.add(NE),this._isDisposed=!1}top(t=\"\"){return this._bottomOffset=\"\",this._topOffset=t,this._alignItems=\"flex-start\",this}left(t=\"\"){return this._rightOffset=\"\",this._leftOffset=t,this._justifyContent=\"flex-start\",this}bottom(t=\"\"){return this._topOffset=\"\",this._bottomOffset=t,this._alignItems=\"flex-end\",this}right(t=\"\"){return this._leftOffset=\"\",this._rightOffset=t,this._justifyContent=\"flex-end\",this}width(t=\"\"){return this._overlayRef?this._overlayRef.updateSize({width:t}):this._width=t,this}height(t=\"\"){return this._overlayRef?this._overlayRef.updateSize({height:t}):this._height=t,this}centerHorizontally(t=\"\"){return this.left(t),this._justifyContent=\"center\",this}centerVertically(t=\"\"){return this.top(t),this._alignItems=\"center\",this}apply(){if(!this._overlayRef||!this._overlayRef.hasAttached())return;const t=this._overlayRef.overlayElement.style,e=this._overlayRef.hostElement.style,i=this._overlayRef.getConfig(),{width:r,height:s,maxWidth:o,maxHeight:a}=i,l=!(\"100%\"!==r&&\"100vw\"!==r||o&&\"100%\"!==o&&\"100vw\"!==o),c=!(\"100%\"!==s&&\"100vh\"!==s||a&&\"100%\"!==a&&\"100vh\"!==a);t.position=this._cssPosition,t.marginLeft=l?\"0\":this._leftOffset,t.marginTop=c?\"0\":this._topOffset,t.marginBottom=this._bottomOffset,t.marginRight=this._rightOffset,l?e.justifyContent=\"flex-start\":\"center\"===this._justifyContent?e.justifyContent=\"center\":\"rtl\"===this._overlayRef.getConfig().direction?\"flex-start\"===this._justifyContent?e.justifyContent=\"flex-end\":\"flex-end\"===this._justifyContent&&(e.justifyContent=\"flex-start\"):e.justifyContent=this._justifyContent,e.alignItems=c?\"flex-start\":this._alignItems}dispose(){if(this._isDisposed||!this._overlayRef)return;const t=this._overlayRef.overlayElement.style,e=this._overlayRef.hostElement,i=e.style;e.classList.remove(NE),i.justifyContent=i.alignItems=t.marginTop=t.marginBottom=t.marginLeft=t.marginRight=t.position=\"\",this._overlayRef=null,this._isDisposed=!0}}let T5=(()=>{class n{constructor(e,i,r,s){this._viewportRuler=e,this._document=i,this._platform=r,this._overlayContainer=s}global(){return new k5}flexibleConnectedTo(e){return new S5(e,this._viewportRuler,this._document,this._platform,this._overlayContainer)}}return n.\\u0275fac=function(e){return new(e||n)(y(es),y(ie),y(It),y(Dg))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),LE=(()=>{class n{constructor(e){this._attachedOverlays=[],this._document=e}ngOnDestroy(){this.detach()}add(e){this.remove(e),this._attachedOverlays.push(e)}remove(e){const i=this._attachedOverlays.indexOf(e);i>-1&&this._attachedOverlays.splice(i,1),0===this._attachedOverlays.length&&this.detach()}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),A5=(()=>{class n extends LE{constructor(e,i){super(e),this._ngZone=i,this._keydownListener=r=>{const s=this._attachedOverlays;for(let o=s.length-1;o>-1;o--)if(s[o]._keydownEvents.observers.length>0){const a=s[o]._keydownEvents;this._ngZone?this._ngZone.run(()=>a.next(r)):a.next(r);break}}}add(e){super.add(e),this._isAttached||(this._ngZone?this._ngZone.runOutsideAngular(()=>this._document.body.addEventListener(\"keydown\",this._keydownListener)):this._document.body.addEventListener(\"keydown\",this._keydownListener),this._isAttached=!0)}detach(){this._isAttached&&(this._document.body.removeEventListener(\"keydown\",this._keydownListener),this._isAttached=!1)}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(ne,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),I5=(()=>{class n extends LE{constructor(e,i,r){super(e),this._platform=i,this._ngZone=r,this._cursorStyleIsSet=!1,this._pointerDownListener=s=>{this._pointerDownEventTarget=Pn(s)},this._clickListener=s=>{const o=Pn(s),a=\"click\"===s.type&&this._pointerDownEventTarget?this._pointerDownEventTarget:o;this._pointerDownEventTarget=null;const l=this._attachedOverlays.slice();for(let c=l.length-1;c>-1;c--){const d=l[c];if(d._outsidePointerEvents.observers.length<1||!d.hasAttached())continue;if(d.overlayElement.contains(o)||d.overlayElement.contains(a))break;const u=d._outsidePointerEvents;this._ngZone?this._ngZone.run(()=>u.next(s)):u.next(s)}}}add(e){if(super.add(e),!this._isAttached){const i=this._document.body;this._ngZone?this._ngZone.runOutsideAngular(()=>this._addEventListeners(i)):this._addEventListeners(i),this._platform.IOS&&!this._cursorStyleIsSet&&(this._cursorOriginalValue=i.style.cursor,i.style.cursor=\"pointer\",this._cursorStyleIsSet=!0),this._isAttached=!0}}detach(){if(this._isAttached){const e=this._document.body;e.removeEventListener(\"pointerdown\",this._pointerDownListener,!0),e.removeEventListener(\"click\",this._clickListener,!0),e.removeEventListener(\"auxclick\",this._clickListener,!0),e.removeEventListener(\"contextmenu\",this._clickListener,!0),this._platform.IOS&&this._cursorStyleIsSet&&(e.style.cursor=this._cursorOriginalValue,this._cursorStyleIsSet=!1),this._isAttached=!1}}_addEventListeners(e){e.addEventListener(\"pointerdown\",this._pointerDownListener,!0),e.addEventListener(\"click\",this._clickListener,!0),e.addEventListener(\"auxclick\",this._clickListener,!0),e.addEventListener(\"contextmenu\",this._clickListener,!0)}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(It),y(ne,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),R5=0,ni=(()=>{class n{constructor(e,i,r,s,o,a,l,c,d,u,h){this.scrollStrategies=e,this._overlayContainer=i,this._componentFactoryResolver=r,this._positionBuilder=s,this._keyboardDispatcher=o,this._injector=a,this._ngZone=l,this._document=c,this._directionality=d,this._location=u,this._outsideClickDispatcher=h}create(e){const i=this._createHostElement(),r=this._createPaneElement(i),s=this._createPortalOutlet(r),o=new Gd(e);return o.direction=o.direction||this._directionality.value,new x5(s,i,r,o,this._ngZone,this._keyboardDispatcher,this._document,this._location,this._outsideClickDispatcher)}position(){return this._positionBuilder}_createPaneElement(e){const i=this._document.createElement(\"div\");return i.id=\"cdk-overlay-\"+R5++,i.classList.add(\"cdk-overlay-pane\"),e.appendChild(i),i}_createHostElement(){const e=this._document.createElement(\"div\");return this._overlayContainer.getContainerElement().appendChild(e),e}_createPortalOutlet(e){return this._appRef||(this._appRef=this._injector.get(Cc)),new v5(e,this._componentFactoryResolver,this._appRef,this._injector,this._document)}}return n.\\u0275fac=function(e){return new(e||n)(y(w5),y(Dg),y(Ir),y(T5),y(A5),y(dt),y(ne),y(ie),y(On),y(va),y(I5))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const O5=[{originX:\"start\",originY:\"bottom\",overlayX:\"start\",overlayY:\"top\"},{originX:\"start\",originY:\"top\",overlayX:\"start\",overlayY:\"bottom\"},{originX:\"end\",originY:\"top\",overlayX:\"end\",overlayY:\"bottom\"},{originX:\"end\",originY:\"bottom\",overlayX:\"end\",overlayY:\"top\"}],BE=new b(\"cdk-connected-overlay-scroll-strategy\");let VE=(()=>{class n{constructor(e){this.elementRef=e}}return n.\\u0275fac=function(e){return new(e||n)(f(W))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"cdk-overlay-origin\",\"\"],[\"\",\"overlay-origin\",\"\"],[\"\",\"cdkOverlayOrigin\",\"\"]],exportAs:[\"cdkOverlayOrigin\"]}),n})(),HE=(()=>{class n{constructor(e,i,r,s,o){this._overlay=e,this._dir=o,this._hasBackdrop=!1,this._lockPosition=!1,this._growAfterOpen=!1,this._flexibleDimensions=!1,this._push=!1,this._backdropSubscription=ke.EMPTY,this._attachSubscription=ke.EMPTY,this._detachSubscription=ke.EMPTY,this._positionSubscription=ke.EMPTY,this.viewportMargin=0,this.open=!1,this.disableClose=!1,this.backdropClick=new $,this.positionChange=new $,this.attach=new $,this.detach=new $,this.overlayKeydown=new $,this.overlayOutsideClick=new $,this._templatePortal=new $d(i,r),this._scrollStrategyFactory=s,this.scrollStrategy=this._scrollStrategyFactory()}get offsetX(){return this._offsetX}set offsetX(e){this._offsetX=e,this._position&&this._updatePositionStrategy(this._position)}get offsetY(){return this._offsetY}set offsetY(e){this._offsetY=e,this._position&&this._updatePositionStrategy(this._position)}get hasBackdrop(){return this._hasBackdrop}set hasBackdrop(e){this._hasBackdrop=G(e)}get lockPosition(){return this._lockPosition}set lockPosition(e){this._lockPosition=G(e)}get flexibleDimensions(){return this._flexibleDimensions}set flexibleDimensions(e){this._flexibleDimensions=G(e)}get growAfterOpen(){return this._growAfterOpen}set growAfterOpen(e){this._growAfterOpen=G(e)}get push(){return this._push}set push(e){this._push=G(e)}get overlayRef(){return this._overlayRef}get dir(){return this._dir?this._dir.value:\"ltr\"}ngOnDestroy(){this._attachSubscription.unsubscribe(),this._detachSubscription.unsubscribe(),this._backdropSubscription.unsubscribe(),this._positionSubscription.unsubscribe(),this._overlayRef&&this._overlayRef.dispose()}ngOnChanges(e){this._position&&(this._updatePositionStrategy(this._position),this._overlayRef.updateSize({width:this.width,minWidth:this.minWidth,height:this.height,minHeight:this.minHeight}),e.origin&&this.open&&this._position.apply()),e.open&&(this.open?this._attachOverlay():this._detachOverlay())}_createOverlay(){(!this.positions||!this.positions.length)&&(this.positions=O5);const e=this._overlayRef=this._overlay.create(this._buildConfig());this._attachSubscription=e.attachments().subscribe(()=>this.attach.emit()),this._detachSubscription=e.detachments().subscribe(()=>this.detach.emit()),e.keydownEvents().subscribe(i=>{this.overlayKeydown.next(i),27===i.keyCode&&!this.disableClose&&!Xt(i)&&(i.preventDefault(),this._detachOverlay())}),this._overlayRef.outsidePointerEvents().subscribe(i=>{this.overlayOutsideClick.next(i)})}_buildConfig(){const e=this._position=this.positionStrategy||this._createPositionStrategy(),i=new Gd({direction:this._dir,positionStrategy:e,scrollStrategy:this.scrollStrategy,hasBackdrop:this.hasBackdrop});return(this.width||0===this.width)&&(i.width=this.width),(this.height||0===this.height)&&(i.height=this.height),(this.minWidth||0===this.minWidth)&&(i.minWidth=this.minWidth),(this.minHeight||0===this.minHeight)&&(i.minHeight=this.minHeight),this.backdropClass&&(i.backdropClass=this.backdropClass),this.panelClass&&(i.panelClass=this.panelClass),i}_updatePositionStrategy(e){const i=this.positions.map(r=>({originX:r.originX,originY:r.originY,overlayX:r.overlayX,overlayY:r.overlayY,offsetX:r.offsetX||this.offsetX,offsetY:r.offsetY||this.offsetY,panelClass:r.panelClass||void 0}));return e.setOrigin(this._getFlexibleConnectedPositionStrategyOrigin()).withPositions(i).withFlexibleDimensions(this.flexibleDimensions).withPush(this.push).withGrowAfterOpen(this.growAfterOpen).withViewportMargin(this.viewportMargin).withLockedPosition(this.lockPosition).withTransformOriginOn(this.transformOriginSelector)}_createPositionStrategy(){const e=this._overlay.position().flexibleConnectedTo(this._getFlexibleConnectedPositionStrategyOrigin());return this._updatePositionStrategy(e),e}_getFlexibleConnectedPositionStrategyOrigin(){return this.origin instanceof VE?this.origin.elementRef:this.origin}_attachOverlay(){this._overlayRef?this._overlayRef.getConfig().hasBackdrop=this.hasBackdrop:this._createOverlay(),this._overlayRef.hasAttached()||this._overlayRef.attach(this._templatePortal),this.hasBackdrop?this._backdropSubscription=this._overlayRef.backdropClick().subscribe(e=>{this.backdropClick.emit(e)}):this._backdropSubscription.unsubscribe(),this._positionSubscription.unsubscribe(),this.positionChange.observers.length>0&&(this._positionSubscription=this._position.positionChanges.pipe(function y5(n,t=!1){return qe((e,i)=>{let r=0;e.subscribe(Ue(i,s=>{const o=n(s,r++);(o||t)&&i.next(s),!o&&i.complete()}))})}(()=>this.positionChange.observers.length>0)).subscribe(e=>{this.positionChange.emit(e),0===this.positionChange.observers.length&&this._positionSubscription.unsubscribe()}))}_detachOverlay(){this._overlayRef&&this._overlayRef.detach(),this._backdropSubscription.unsubscribe(),this._positionSubscription.unsubscribe()}}return n.\\u0275fac=function(e){return new(e||n)(f(ni),f(ut),f(st),f(BE),f(On,8))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"cdk-connected-overlay\",\"\"],[\"\",\"connected-overlay\",\"\"],[\"\",\"cdkConnectedOverlay\",\"\"]],inputs:{origin:[\"cdkConnectedOverlayOrigin\",\"origin\"],positions:[\"cdkConnectedOverlayPositions\",\"positions\"],positionStrategy:[\"cdkConnectedOverlayPositionStrategy\",\"positionStrategy\"],offsetX:[\"cdkConnectedOverlayOffsetX\",\"offsetX\"],offsetY:[\"cdkConnectedOverlayOffsetY\",\"offsetY\"],width:[\"cdkConnectedOverlayWidth\",\"width\"],height:[\"cdkConnectedOverlayHeight\",\"height\"],minWidth:[\"cdkConnectedOverlayMinWidth\",\"minWidth\"],minHeight:[\"cdkConnectedOverlayMinHeight\",\"minHeight\"],backdropClass:[\"cdkConnectedOverlayBackdropClass\",\"backdropClass\"],panelClass:[\"cdkConnectedOverlayPanelClass\",\"panelClass\"],viewportMargin:[\"cdkConnectedOverlayViewportMargin\",\"viewportMargin\"],scrollStrategy:[\"cdkConnectedOverlayScrollStrategy\",\"scrollStrategy\"],open:[\"cdkConnectedOverlayOpen\",\"open\"],disableClose:[\"cdkConnectedOverlayDisableClose\",\"disableClose\"],transformOriginSelector:[\"cdkConnectedOverlayTransformOriginOn\",\"transformOriginSelector\"],hasBackdrop:[\"cdkConnectedOverlayHasBackdrop\",\"hasBackdrop\"],lockPosition:[\"cdkConnectedOverlayLockPosition\",\"lockPosition\"],flexibleDimensions:[\"cdkConnectedOverlayFlexibleDimensions\",\"flexibleDimensions\"],growAfterOpen:[\"cdkConnectedOverlayGrowAfterOpen\",\"growAfterOpen\"],push:[\"cdkConnectedOverlayPush\",\"push\"]},outputs:{backdropClick:\"backdropClick\",positionChange:\"positionChange\",attach:\"attach\",detach:\"detach\",overlayKeydown:\"overlayKeydown\",overlayOutsideClick:\"overlayOutsideClick\"},exportAs:[\"cdkConnectedOverlay\"],features:[Je]}),n})();const F5={provide:BE,deps:[ni],useFactory:function P5(n){return()=>n.scrollStrategies.reposition()}};let ji=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[ni,F5],imports:[[lo,Hi,Ud],Ud]}),n})();class nl{constructor(t=!1,e,i=!0){this._multiple=t,this._emitChanges=i,this._selection=new Set,this._deselectedToEmit=[],this._selectedToEmit=[],this.changed=new O,e&&e.length&&(t?e.forEach(r=>this._markSelected(r)):this._markSelected(e[0]),this._selectedToEmit.length=0)}get selected(){return this._selected||(this._selected=Array.from(this._selection.values())),this._selected}select(...t){this._verifyValueAssignment(t),t.forEach(e=>this._markSelected(e)),this._emitChangeEvent()}deselect(...t){this._verifyValueAssignment(t),t.forEach(e=>this._unmarkSelected(e)),this._emitChangeEvent()}toggle(t){this.isSelected(t)?this.deselect(t):this.select(t)}clear(){this._unmarkAll(),this._emitChangeEvent()}isSelected(t){return this._selection.has(t)}isEmpty(){return 0===this._selection.size}hasValue(){return!this.isEmpty()}sort(t){this._multiple&&this.selected&&this._selected.sort(t)}isMultipleSelection(){return this._multiple}_emitChangeEvent(){this._selected=null,(this._selectedToEmit.length||this._deselectedToEmit.length)&&(this.changed.next({source:this,added:this._selectedToEmit,removed:this._deselectedToEmit}),this._deselectedToEmit=[],this._selectedToEmit=[])}_markSelected(t){this.isSelected(t)||(this._multiple||this._unmarkAll(),this._selection.add(t),this._emitChanges&&this._selectedToEmit.push(t))}_unmarkSelected(t){this.isSelected(t)&&(this._selection.delete(t),this._emitChanges&&this._deselectedToEmit.push(t))}_unmarkAll(){this.isEmpty()||this._selection.forEach(t=>this._unmarkSelected(t))}_verifyValueAssignment(t){}}const L5=[\"trigger\"],B5=[\"panel\"];function V5(n,t){if(1&n&&(x(0,\"span\",8),we(1),S()),2&n){const e=Be();T(1),Ut(e.placeholder)}}function H5(n,t){if(1&n&&(x(0,\"span\",12),we(1),S()),2&n){const e=Be(2);T(1),Ut(e.triggerValue)}}function j5(n,t){1&n&&Pe(0,0,[\"*ngSwitchCase\",\"true\"])}function z5(n,t){1&n&&(x(0,\"span\",9),Ee(1,H5,2,1,\"span\",10),Ee(2,j5,1,0,\"ng-content\",11),S()),2&n&&(N(\"ngSwitch\",!!Be().customTrigger),T(2),N(\"ngSwitchCase\",!0))}function U5(n,t){if(1&n){const e=ia();x(0,\"div\",13)(1,\"div\",14,15),J(\"@transformPanel.done\",function(r){return Dr(e),Be()._panelDoneAnimatingStream.next(r.toState)})(\"keydown\",function(r){return Dr(e),Be()._handleKeydown(r)}),Pe(3,1),S()()}if(2&n){const e=Be();N(\"@transformPanelWrap\",void 0),T(1),cC(\"mat-select-panel \",e._getPanelTheme(),\"\"),$n(\"transform-origin\",e._transformOrigin)(\"font-size\",e._triggerFontSize,\"px\"),N(\"ngClass\",e.panelClass)(\"@transformPanel\",e.multiple?\"showing-multiple\":\"showing\"),Z(\"id\",e.id+\"-panel\")(\"aria-multiselectable\",e.multiple)(\"aria-label\",e.ariaLabel||null)(\"aria-labelledby\",e._getPanelAriaLabelledby())}}const $5=[[[\"mat-select-trigger\"]],\"*\"],G5=[\"mat-select-trigger\",\"*\"],UE={transformPanelWrap:Ke(\"transformPanelWrap\",[ge(\"* => void\",no(\"@transformPanel\",[to()],{optional:!0}))]),transformPanel:Ke(\"transformPanel\",[ae(\"void\",R({transform:\"scaleY(0.8)\",minWidth:\"100%\",opacity:0})),ae(\"showing\",R({opacity:1,minWidth:\"calc(100% + 32px)\",transform:\"scaleY(1)\"})),ae(\"showing-multiple\",R({opacity:1,minWidth:\"calc(100% + 64px)\",transform:\"scaleY(1)\"})),ge(\"void => *\",be(\"120ms cubic-bezier(0, 0, 0.2, 1)\")),ge(\"* => void\",be(\"100ms 25ms linear\",R({opacity:0})))])};let $E=0;const WE=new b(\"mat-select-scroll-strategy\"),Q5=new b(\"MAT_SELECT_CONFIG\"),K5={provide:WE,deps:[ni],useFactory:function Y5(n){return()=>n.scrollStrategies.reposition()}};class Z5{constructor(t,e){this.source=t,this.value=e}}const X5=ar(Kr(po(ng(class{constructor(n,t,e,i,r){this._elementRef=n,this._defaultErrorStateMatcher=t,this._parentForm=e,this._parentFormGroup=i,this.ngControl=r}})))),J5=new b(\"MatSelectTrigger\");let e$=(()=>{class n extends X5{constructor(e,i,r,s,o,a,l,c,d,u,h,p,m,g){var _,D,v;super(o,s,l,c,u),this._viewportRuler=e,this._changeDetectorRef=i,this._ngZone=r,this._dir=a,this._parentFormField=d,this._liveAnnouncer=m,this._defaultOptions=g,this._panelOpen=!1,this._compareWith=(M,V)=>M===V,this._uid=\"mat-select-\"+$E++,this._triggerAriaLabelledBy=null,this._destroy=new O,this._onChange=()=>{},this._onTouched=()=>{},this._valueId=\"mat-select-value-\"+$E++,this._panelDoneAnimatingStream=new O,this._overlayPanelClass=(null===(_=this._defaultOptions)||void 0===_?void 0:_.overlayPanelClass)||\"\",this._focused=!1,this.controlType=\"mat-select\",this._multiple=!1,this._disableOptionCentering=null!==(v=null===(D=this._defaultOptions)||void 0===D?void 0:D.disableOptionCentering)&&void 0!==v&&v,this.ariaLabel=\"\",this.optionSelectionChanges=xa(()=>{const M=this.options;return M?M.changes.pipe(Xn(M),kn(()=>Bt(...M.map(V=>V.onSelectionChange)))):this._ngZone.onStable.pipe(it(1),kn(()=>this.optionSelectionChanges))}),this.openedChange=new $,this._openedStream=this.openedChange.pipe(Ct(M=>M),ue(()=>{})),this._closedStream=this.openedChange.pipe(Ct(M=>!M),ue(()=>{})),this.selectionChange=new $,this.valueChange=new $,this.ngControl&&(this.ngControl.valueAccessor=this),null!=(null==g?void 0:g.typeaheadDebounceInterval)&&(this._typeaheadDebounceInterval=g.typeaheadDebounceInterval),this._scrollStrategyFactory=p,this._scrollStrategy=this._scrollStrategyFactory(),this.tabIndex=parseInt(h)||0,this.id=this.id}get focused(){return this._focused||this._panelOpen}get placeholder(){return this._placeholder}set placeholder(e){this._placeholder=e,this.stateChanges.next()}get required(){var e,i,r,s;return null!==(s=null!==(e=this._required)&&void 0!==e?e:null===(r=null===(i=this.ngControl)||void 0===i?void 0:i.control)||void 0===r?void 0:r.hasValidator(yi.required))&&void 0!==s&&s}set required(e){this._required=G(e),this.stateChanges.next()}get multiple(){return this._multiple}set multiple(e){this._multiple=G(e)}get disableOptionCentering(){return this._disableOptionCentering}set disableOptionCentering(e){this._disableOptionCentering=G(e)}get compareWith(){return this._compareWith}set compareWith(e){this._compareWith=e,this._selectionModel&&this._initializeSelection()}get value(){return this._value}set value(e){(e!==this._value||this._multiple&&Array.isArray(e))&&(this.options&&this._setSelectionByValue(e),this._value=e)}get typeaheadDebounceInterval(){return this._typeaheadDebounceInterval}set typeaheadDebounceInterval(e){this._typeaheadDebounceInterval=Et(e)}get id(){return this._id}set id(e){this._id=e||this._uid,this.stateChanges.next()}ngOnInit(){this._selectionModel=new nl(this.multiple),this.stateChanges.next(),this._panelDoneAnimatingStream.pipe(Gx(),Ie(this._destroy)).subscribe(()=>this._panelDoneAnimating(this.panelOpen))}ngAfterContentInit(){this._initKeyManager(),this._selectionModel.changed.pipe(Ie(this._destroy)).subscribe(e=>{e.added.forEach(i=>i.select()),e.removed.forEach(i=>i.deselect())}),this.options.changes.pipe(Xn(null),Ie(this._destroy)).subscribe(()=>{this._resetOptions(),this._initializeSelection()})}ngDoCheck(){const e=this._getTriggerAriaLabelledby(),i=this.ngControl;if(e!==this._triggerAriaLabelledBy){const r=this._elementRef.nativeElement;this._triggerAriaLabelledBy=e,e?r.setAttribute(\"aria-labelledby\",e):r.removeAttribute(\"aria-labelledby\")}i&&(this._previousControl!==i.control&&(void 0!==this._previousControl&&null!==i.disabled&&i.disabled!==this.disabled&&(this.disabled=i.disabled),this._previousControl=i.control),this.updateErrorState())}ngOnChanges(e){e.disabled&&this.stateChanges.next(),e.typeaheadDebounceInterval&&this._keyManager&&this._keyManager.withTypeAhead(this._typeaheadDebounceInterval)}ngOnDestroy(){this._destroy.next(),this._destroy.complete(),this.stateChanges.complete()}toggle(){this.panelOpen?this.close():this.open()}open(){this._canOpen()&&(this._panelOpen=!0,this._keyManager.withHorizontalOrientation(null),this._highlightCorrectOption(),this._changeDetectorRef.markForCheck())}close(){this._panelOpen&&(this._panelOpen=!1,this._keyManager.withHorizontalOrientation(this._isRtl()?\"rtl\":\"ltr\"),this._changeDetectorRef.markForCheck(),this._onTouched())}writeValue(e){this.value=e}registerOnChange(e){this._onChange=e}registerOnTouched(e){this._onTouched=e}setDisabledState(e){this.disabled=e,this._changeDetectorRef.markForCheck(),this.stateChanges.next()}get panelOpen(){return this._panelOpen}get selected(){var e,i;return this.multiple?(null===(e=this._selectionModel)||void 0===e?void 0:e.selected)||[]:null===(i=this._selectionModel)||void 0===i?void 0:i.selected[0]}get triggerValue(){if(this.empty)return\"\";if(this._multiple){const e=this._selectionModel.selected.map(i=>i.viewValue);return this._isRtl()&&e.reverse(),e.join(\", \")}return this._selectionModel.selected[0].viewValue}_isRtl(){return!!this._dir&&\"rtl\"===this._dir.value}_handleKeydown(e){this.disabled||(this.panelOpen?this._handleOpenKeydown(e):this._handleClosedKeydown(e))}_handleClosedKeydown(e){const i=e.keyCode,r=40===i||38===i||37===i||39===i,s=13===i||32===i,o=this._keyManager;if(!o.isTyping()&&s&&!Xt(e)||(this.multiple||e.altKey)&&r)e.preventDefault(),this.open();else if(!this.multiple){const a=this.selected;o.onKeydown(e);const l=this.selected;l&&a!==l&&this._liveAnnouncer.announce(l.viewValue,1e4)}}_handleOpenKeydown(e){const i=this._keyManager,r=e.keyCode,s=40===r||38===r,o=i.isTyping();if(s&&e.altKey)e.preventDefault(),this.close();else if(o||13!==r&&32!==r||!i.activeItem||Xt(e))if(!o&&this._multiple&&65===r&&e.ctrlKey){e.preventDefault();const a=this.options.some(l=>!l.disabled&&!l.selected);this.options.forEach(l=>{l.disabled||(a?l.select():l.deselect())})}else{const a=i.activeItemIndex;i.onKeydown(e),this._multiple&&s&&e.shiftKey&&i.activeItem&&i.activeItemIndex!==a&&i.activeItem._selectViaInteraction()}else e.preventDefault(),i.activeItem._selectViaInteraction()}_onFocus(){this.disabled||(this._focused=!0,this.stateChanges.next())}_onBlur(){this._focused=!1,!this.disabled&&!this.panelOpen&&(this._onTouched(),this._changeDetectorRef.markForCheck(),this.stateChanges.next())}_onAttached(){this._overlayDir.positionChange.pipe(it(1)).subscribe(()=>{this._changeDetectorRef.detectChanges(),this._positioningSettled()})}_getPanelTheme(){return this._parentFormField?`mat-${this._parentFormField.color}`:\"\"}get empty(){return!this._selectionModel||this._selectionModel.isEmpty()}_initializeSelection(){Promise.resolve().then(()=>{this.ngControl&&(this._value=this.ngControl.value),this._setSelectionByValue(this._value),this.stateChanges.next()})}_setSelectionByValue(e){if(this._selectionModel.selected.forEach(i=>i.setInactiveStyles()),this._selectionModel.clear(),this.multiple&&e)Array.isArray(e),e.forEach(i=>this._selectValue(i)),this._sortValues();else{const i=this._selectValue(e);i?this._keyManager.updateActiveItem(i):this.panelOpen||this._keyManager.updateActiveItem(-1)}this._changeDetectorRef.markForCheck()}_selectValue(e){const i=this.options.find(r=>{if(this._selectionModel.isSelected(r))return!1;try{return null!=r.value&&this._compareWith(r.value,e)}catch(s){return!1}});return i&&this._selectionModel.select(i),i}_initKeyManager(){this._keyManager=new c3(this.options).withTypeAhead(this._typeaheadDebounceInterval).withVerticalOrientation().withHorizontalOrientation(this._isRtl()?\"rtl\":\"ltr\").withHomeAndEnd().withAllowedModifierKeys([\"shiftKey\"]),this._keyManager.tabOut.pipe(Ie(this._destroy)).subscribe(()=>{this.panelOpen&&(!this.multiple&&this._keyManager.activeItem&&this._keyManager.activeItem._selectViaInteraction(),this.focus(),this.close())}),this._keyManager.change.pipe(Ie(this._destroy)).subscribe(()=>{this._panelOpen&&this.panel?this._scrollOptionIntoView(this._keyManager.activeItemIndex||0):!this._panelOpen&&!this.multiple&&this._keyManager.activeItem&&this._keyManager.activeItem._selectViaInteraction()})}_resetOptions(){const e=Bt(this.options.changes,this._destroy);this.optionSelectionChanges.pipe(Ie(e)).subscribe(i=>{this._onSelect(i.source,i.isUserInput),i.isUserInput&&!this.multiple&&this._panelOpen&&(this.close(),this.focus())}),Bt(...this.options.map(i=>i._stateChanges)).pipe(Ie(e)).subscribe(()=>{this._changeDetectorRef.markForCheck(),this.stateChanges.next()})}_onSelect(e,i){const r=this._selectionModel.isSelected(e);null!=e.value||this._multiple?(r!==e.selected&&(e.selected?this._selectionModel.select(e):this._selectionModel.deselect(e)),i&&this._keyManager.setActiveItem(e),this.multiple&&(this._sortValues(),i&&this.focus())):(e.deselect(),this._selectionModel.clear(),null!=this.value&&this._propagateChanges(e.value)),r!==this._selectionModel.isSelected(e)&&this._propagateChanges(),this.stateChanges.next()}_sortValues(){if(this.multiple){const e=this.options.toArray();this._selectionModel.sort((i,r)=>this.sortComparator?this.sortComparator(i,r,e):e.indexOf(i)-e.indexOf(r)),this.stateChanges.next()}}_propagateChanges(e){let i=null;i=this.multiple?this.selected.map(r=>r.value):this.selected?this.selected.value:e,this._value=i,this.valueChange.emit(i),this._onChange(i),this.selectionChange.emit(this._getChangeEvent(i)),this._changeDetectorRef.markForCheck()}_highlightCorrectOption(){this._keyManager&&(this.empty?this._keyManager.setFirstItemActive():this._keyManager.setActiveItem(this._selectionModel.selected[0]))}_canOpen(){var e;return!this._panelOpen&&!this.disabled&&(null===(e=this.options)||void 0===e?void 0:e.length)>0}focus(e){this._elementRef.nativeElement.focus(e)}_getPanelAriaLabelledby(){var e;if(this.ariaLabel)return null;const i=null===(e=this._parentFormField)||void 0===e?void 0:e.getLabelId();return this.ariaLabelledby?(i?i+\" \":\"\")+this.ariaLabelledby:i}_getAriaActiveDescendant(){return this.panelOpen&&this._keyManager&&this._keyManager.activeItem?this._keyManager.activeItem.id:null}_getTriggerAriaLabelledby(){var e;if(this.ariaLabel)return null;const i=null===(e=this._parentFormField)||void 0===e?void 0:e.getLabelId();let r=(i?i+\" \":\"\")+this._valueId;return this.ariaLabelledby&&(r+=\" \"+this.ariaLabelledby),r}_panelDoneAnimating(e){this.openedChange.emit(e)}setDescribedByIds(e){this._ariaDescribedby=e.join(\" \")}onContainerClick(){this.focus(),this.open()}get shouldLabelFloat(){return this._panelOpen||!this.empty||this._focused&&!!this._placeholder}}return n.\\u0275fac=function(e){return new(e||n)(f(es),f(Ye),f(ne),f(mo),f(W),f(On,8),f(oo,8),f(ao,8),f(el,8),f(Jn,10),kt(\"tabindex\"),f(WE),f(k3),f(Q5,8))},n.\\u0275dir=C({type:n,viewQuery:function(e,i){if(1&e&&(je(L5,5),je(B5,5),je(HE,5)),2&e){let r;z(r=U())&&(i.trigger=r.first),z(r=U())&&(i.panel=r.first),z(r=U())&&(i._overlayDir=r.first)}},inputs:{panelClass:\"panelClass\",placeholder:\"placeholder\",required:\"required\",multiple:\"multiple\",disableOptionCentering:\"disableOptionCentering\",compareWith:\"compareWith\",value:\"value\",ariaLabel:[\"aria-label\",\"ariaLabel\"],ariaLabelledby:[\"aria-labelledby\",\"ariaLabelledby\"],errorStateMatcher:\"errorStateMatcher\",typeaheadDebounceInterval:\"typeaheadDebounceInterval\",sortComparator:\"sortComparator\",id:\"id\"},outputs:{openedChange:\"openedChange\",_openedStream:\"opened\",_closedStream:\"closed\",selectionChange:\"selectionChange\",valueChange:\"valueChange\"},features:[E,Je]}),n})(),t$=(()=>{class n extends e${constructor(){super(...arguments),this._scrollTop=0,this._triggerFontSize=0,this._transformOrigin=\"top\",this._offsetY=0,this._positions=[{originX:\"start\",originY:\"top\",overlayX:\"start\",overlayY:\"top\"},{originX:\"start\",originY:\"bottom\",overlayX:\"start\",overlayY:\"bottom\"}]}_calculateOverlayScroll(e,i,r){const s=this._getItemHeight();return Math.min(Math.max(0,s*e-i+s/2),r)}ngOnInit(){super.ngOnInit(),this._viewportRuler.change().pipe(Ie(this._destroy)).subscribe(()=>{this.panelOpen&&(this._triggerRect=this.trigger.nativeElement.getBoundingClientRect(),this._changeDetectorRef.markForCheck())})}open(){super._canOpen()&&(super.open(),this._triggerRect=this.trigger.nativeElement.getBoundingClientRect(),this._triggerFontSize=parseInt(getComputedStyle(this.trigger.nativeElement).fontSize||\"0\"),this._calculateOverlayPosition(),this._ngZone.onStable.pipe(it(1)).subscribe(()=>{this._triggerFontSize&&this._overlayDir.overlayRef&&this._overlayDir.overlayRef.overlayElement&&(this._overlayDir.overlayRef.overlayElement.style.fontSize=`${this._triggerFontSize}px`)}))}_scrollOptionIntoView(e){const i=cg(e,this.options,this.optionGroups),r=this._getItemHeight();this.panel.nativeElement.scrollTop=0===e&&1===i?0:function pE(n,t,e,i){return n<e?n:n+t>e+i?Math.max(0,n-i+t):e}((e+i)*r,r,this.panel.nativeElement.scrollTop,256)}_positioningSettled(){this._calculateOverlayOffsetX(),this.panel.nativeElement.scrollTop=this._scrollTop}_panelDoneAnimating(e){this.panelOpen?this._scrollTop=0:(this._overlayDir.offsetX=0,this._changeDetectorRef.markForCheck()),super._panelDoneAnimating(e)}_getChangeEvent(e){return new Z5(this,e)}_calculateOverlayOffsetX(){const e=this._overlayDir.overlayRef.overlayElement.getBoundingClientRect(),i=this._viewportRuler.getViewportSize(),r=this._isRtl(),s=this.multiple?56:32;let o;if(this.multiple)o=40;else if(this.disableOptionCentering)o=16;else{let c=this._selectionModel.selected[0]||this.options.first;o=c&&c.group?32:16}r||(o*=-1);const a=0-(e.left+o-(r?s:0)),l=e.right+o-i.width+(r?0:s);a>0?o+=a+8:l>0&&(o-=l+8),this._overlayDir.offsetX=Math.round(o),this._overlayDir.overlayRef.updatePosition()}_calculateOverlayOffsetY(e,i,r){const s=this._getItemHeight(),o=(s-this._triggerRect.height)/2,a=Math.floor(256/s);let l;return this.disableOptionCentering?0:(l=0===this._scrollTop?e*s:this._scrollTop===r?(e-(this._getItemCount()-a))*s+(s-(this._getItemCount()*s-256)%s):i-s/2,Math.round(-1*l-o))}_checkOverlayWithinViewport(e){const i=this._getItemHeight(),r=this._viewportRuler.getViewportSize(),s=this._triggerRect.top-8,o=r.height-this._triggerRect.bottom-8,a=Math.abs(this._offsetY),c=Math.min(this._getItemCount()*i,256)-a-this._triggerRect.height;c>o?this._adjustPanelUp(c,o):a>s?this._adjustPanelDown(a,s,e):this._transformOrigin=this._getOriginBasedOnOption()}_adjustPanelUp(e,i){const r=Math.round(e-i);this._scrollTop-=r,this._offsetY-=r,this._transformOrigin=this._getOriginBasedOnOption(),this._scrollTop<=0&&(this._scrollTop=0,this._offsetY=0,this._transformOrigin=\"50% bottom 0px\")}_adjustPanelDown(e,i,r){const s=Math.round(e-i);if(this._scrollTop+=s,this._offsetY+=s,this._transformOrigin=this._getOriginBasedOnOption(),this._scrollTop>=r)return this._scrollTop=r,this._offsetY=0,void(this._transformOrigin=\"50% top 0px\")}_calculateOverlayPosition(){const e=this._getItemHeight(),i=this._getItemCount(),r=Math.min(i*e,256),o=i*e-r;let a;a=this.empty?0:Math.max(this.options.toArray().indexOf(this._selectionModel.selected[0]),0),a+=cg(a,this.options,this.optionGroups);const l=r/2;this._scrollTop=this._calculateOverlayScroll(a,l,o),this._offsetY=this._calculateOverlayOffsetY(a,l,o),this._checkOverlayWithinViewport(o)}_getOriginBasedOnOption(){const e=this._getItemHeight(),i=(e-this._triggerRect.height)/2;return`50% ${Math.abs(this._offsetY)-i+e/2}px 0px`}_getItemHeight(){return 3*this._triggerFontSize}_getItemCount(){return this.options.length+this.optionGroups.length}}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275cmp=xe({type:n,selectors:[[\"mat-select\"]],contentQueries:function(e,i,r){if(1&e&&(ve(r,J5,5),ve(r,hE,5),ve(r,lg,5)),2&e){let s;z(s=U())&&(i.customTrigger=s.first),z(s=U())&&(i.options=s),z(s=U())&&(i.optionGroups=s)}},hostAttrs:[\"role\",\"combobox\",\"aria-autocomplete\",\"none\",\"aria-haspopup\",\"true\",1,\"mat-select\"],hostVars:20,hostBindings:function(e,i){1&e&&J(\"keydown\",function(s){return i._handleKeydown(s)})(\"focus\",function(){return i._onFocus()})(\"blur\",function(){return i._onBlur()}),2&e&&(Z(\"id\",i.id)(\"tabindex\",i.tabIndex)(\"aria-controls\",i.panelOpen?i.id+\"-panel\":null)(\"aria-expanded\",i.panelOpen)(\"aria-label\",i.ariaLabel||null)(\"aria-required\",i.required.toString())(\"aria-disabled\",i.disabled.toString())(\"aria-invalid\",i.errorState)(\"aria-describedby\",i._ariaDescribedby||null)(\"aria-activedescendant\",i._getAriaActiveDescendant()),Ae(\"mat-select-disabled\",i.disabled)(\"mat-select-invalid\",i.errorState)(\"mat-select-required\",i.required)(\"mat-select-empty\",i.empty)(\"mat-select-multiple\",i.multiple))},inputs:{disabled:\"disabled\",disableRipple:\"disableRipple\",tabIndex:\"tabIndex\"},exportAs:[\"matSelect\"],features:[L([{provide:Ja,useExisting:n},{provide:ag,useExisting:n}]),E],ngContentSelectors:G5,decls:9,vars:12,consts:[[\"cdk-overlay-origin\",\"\",1,\"mat-select-trigger\",3,\"click\"],[\"origin\",\"cdkOverlayOrigin\",\"trigger\",\"\"],[1,\"mat-select-value\",3,\"ngSwitch\"],[\"class\",\"mat-select-placeholder mat-select-min-line\",4,\"ngSwitchCase\"],[\"class\",\"mat-select-value-text\",3,\"ngSwitch\",4,\"ngSwitchCase\"],[1,\"mat-select-arrow-wrapper\"],[1,\"mat-select-arrow\"],[\"cdk-connected-overlay\",\"\",\"cdkConnectedOverlayLockPosition\",\"\",\"cdkConnectedOverlayHasBackdrop\",\"\",\"cdkConnectedOverlayBackdropClass\",\"cdk-overlay-transparent-backdrop\",3,\"cdkConnectedOverlayPanelClass\",\"cdkConnectedOverlayScrollStrategy\",\"cdkConnectedOverlayOrigin\",\"cdkConnectedOverlayOpen\",\"cdkConnectedOverlayPositions\",\"cdkConnectedOverlayMinWidth\",\"cdkConnectedOverlayOffsetY\",\"backdropClick\",\"attach\",\"detach\"],[1,\"mat-select-placeholder\",\"mat-select-min-line\"],[1,\"mat-select-value-text\",3,\"ngSwitch\"],[\"class\",\"mat-select-min-line\",4,\"ngSwitchDefault\"],[4,\"ngSwitchCase\"],[1,\"mat-select-min-line\"],[1,\"mat-select-panel-wrap\"],[\"role\",\"listbox\",\"tabindex\",\"-1\",3,\"ngClass\",\"keydown\"],[\"panel\",\"\"]],template:function(e,i){if(1&e&&(Lt($5),x(0,\"div\",0,1),J(\"click\",function(){return i.toggle()}),x(3,\"div\",2),Ee(4,V5,2,1,\"span\",3),Ee(5,z5,3,2,\"span\",4),S(),x(6,\"div\",5),Le(7,\"div\",6),S()(),Ee(8,U5,4,14,\"ng-template\",7),J(\"backdropClick\",function(){return i.close()})(\"attach\",function(){return i._onAttached()})(\"detach\",function(){return i.close()})),2&e){const r=wn(1);Z(\"aria-owns\",i.panelOpen?i.id+\"-panel\":null),T(3),N(\"ngSwitch\",i.empty),Z(\"id\",i._valueId),T(1),N(\"ngSwitchCase\",!0),T(1),N(\"ngSwitchCase\",!1),T(3),N(\"cdkConnectedOverlayPanelClass\",i._overlayPanelClass)(\"cdkConnectedOverlayScrollStrategy\",i._scrollStrategy)(\"cdkConnectedOverlayOrigin\",r)(\"cdkConnectedOverlayOpen\",i.panelOpen)(\"cdkConnectedOverlayPositions\",i._positions)(\"cdkConnectedOverlayMinWidth\",null==i._triggerRect?null:i._triggerRect.width)(\"cdkConnectedOverlayOffsetY\",i._offsetY)}},directives:[VE,Ys,Pc,yD,HE,mD],styles:['.mat-select{display:inline-block;width:100%;outline:none}.mat-select-trigger{display:inline-table;cursor:pointer;position:relative;box-sizing:border-box}.mat-select-disabled .mat-select-trigger{-webkit-user-select:none;-moz-user-select:none;user-select:none;cursor:default}.mat-select-value{display:table-cell;max-width:0;width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mat-select-value-text{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.mat-select-arrow-wrapper{display:table-cell;vertical-align:middle}.mat-form-field-appearance-fill .mat-select-arrow-wrapper{transform:translateY(-50%)}.mat-form-field-appearance-outline .mat-select-arrow-wrapper{transform:translateY(-25%)}.mat-form-field-appearance-standard.mat-form-field-has-label .mat-select:not(.mat-select-empty) .mat-select-arrow-wrapper{transform:translateY(-50%)}.mat-form-field-appearance-standard .mat-select.mat-select-empty .mat-select-arrow-wrapper{transition:transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1)}._mat-animation-noopable.mat-form-field-appearance-standard .mat-select.mat-select-empty .mat-select-arrow-wrapper{transition:none}.mat-select-arrow{width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;border-top:5px solid;margin:0 4px}.mat-form-field.mat-focused .mat-select-arrow{transform:translateX(0)}.mat-select-panel-wrap{flex-basis:100%}.mat-select-panel{min-width:112px;max-width:280px;overflow:auto;-webkit-overflow-scrolling:touch;padding-top:0;padding-bottom:0;max-height:256px;min-width:100%;border-radius:4px;outline:0}.cdk-high-contrast-active .mat-select-panel{outline:solid 1px}.mat-select-panel .mat-optgroup-label,.mat-select-panel .mat-option{font-size:inherit;line-height:3em;height:3em}.mat-form-field-type-mat-select:not(.mat-form-field-disabled) .mat-form-field-flex{cursor:pointer}.mat-form-field-type-mat-select .mat-form-field-label{width:calc(100% - 18px)}.mat-select-placeholder{transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}._mat-animation-noopable .mat-select-placeholder{transition:none}.mat-form-field-hide-placeholder .mat-select-placeholder{color:transparent;-webkit-text-fill-color:transparent;transition:none;display:block}.mat-select-min-line:empty::before{content:\" \";white-space:pre;width:1px;display:inline-block;opacity:0}\\n'],encapsulation:2,data:{animation:[UE.transformPanelWrap,UE.transformPanel]},changeDetection:0}),n})(),qE=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[K5],imports:[[bt,ji,Hd,B],Ci,mg,Hd,B]}),n})();const YE=ei({passive:!0});let n$=(()=>{class n{constructor(e,i){this._platform=e,this._ngZone=i,this._monitoredElements=new Map}monitor(e){if(!this._platform.isBrowser)return ri;const i=at(e),r=this._monitoredElements.get(i);if(r)return r.subject;const s=new O,o=\"cdk-text-field-autofilled\",a=l=>{\"cdk-text-field-autofill-start\"!==l.animationName||i.classList.contains(o)?\"cdk-text-field-autofill-end\"===l.animationName&&i.classList.contains(o)&&(i.classList.remove(o),this._ngZone.run(()=>s.next({target:l.target,isAutofilled:!1}))):(i.classList.add(o),this._ngZone.run(()=>s.next({target:l.target,isAutofilled:!0})))};return this._ngZone.runOutsideAngular(()=>{i.addEventListener(\"animationstart\",a,YE),i.classList.add(\"cdk-text-field-autofill-monitored\")}),this._monitoredElements.set(i,{subject:s,unlisten:()=>{i.removeEventListener(\"animationstart\",a,YE)}}),s}stopMonitoring(e){const i=at(e),r=this._monitoredElements.get(i);r&&(r.unlisten(),r.subject.complete(),i.classList.remove(\"cdk-text-field-autofill-monitored\"),i.classList.remove(\"cdk-text-field-autofilled\"),this._monitoredElements.delete(i))}ngOnDestroy(){this._monitoredElements.forEach((e,i)=>this.stopMonitoring(i))}}return n.\\u0275fac=function(e){return new(e||n)(y(It),y(ne))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),QE=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const KE=new b(\"MAT_INPUT_VALUE_ACCESSOR\"),i$=[\"button\",\"checkbox\",\"file\",\"hidden\",\"image\",\"radio\",\"range\",\"reset\",\"submit\"];let r$=0;const s$=ng(class{constructor(n,t,e,i){this._defaultErrorStateMatcher=n,this._parentForm=t,this._parentFormGroup=e,this.ngControl=i}});let o$=(()=>{class n extends s${constructor(e,i,r,s,o,a,l,c,d,u){super(a,s,o,r),this._elementRef=e,this._platform=i,this._autofillMonitor=c,this._formField=u,this._uid=\"mat-input-\"+r$++,this.focused=!1,this.stateChanges=new O,this.controlType=\"mat-input\",this.autofilled=!1,this._disabled=!1,this._type=\"text\",this._readonly=!1,this._neverEmptyInputTypes=[\"date\",\"datetime\",\"datetime-local\",\"month\",\"time\",\"week\"].filter(m=>Hx().has(m));const h=this._elementRef.nativeElement,p=h.nodeName.toLowerCase();this._inputValueAccessor=l||h,this._previousNativeValue=this.value,this.id=this.id,i.IOS&&d.runOutsideAngular(()=>{e.nativeElement.addEventListener(\"keyup\",m=>{const g=m.target;!g.value&&0===g.selectionStart&&0===g.selectionEnd&&(g.setSelectionRange(1,1),g.setSelectionRange(0,0))})}),this._isServer=!this._platform.isBrowser,this._isNativeSelect=\"select\"===p,this._isTextarea=\"textarea\"===p,this._isInFormField=!!u,this._isNativeSelect&&(this.controlType=h.multiple?\"mat-native-select-multiple\":\"mat-native-select\")}get disabled(){return this.ngControl&&null!==this.ngControl.disabled?this.ngControl.disabled:this._disabled}set disabled(e){this._disabled=G(e),this.focused&&(this.focused=!1,this.stateChanges.next())}get id(){return this._id}set id(e){this._id=e||this._uid}get required(){var e,i,r,s;return null!==(s=null!==(e=this._required)&&void 0!==e?e:null===(r=null===(i=this.ngControl)||void 0===i?void 0:i.control)||void 0===r?void 0:r.hasValidator(yi.required))&&void 0!==s&&s}set required(e){this._required=G(e)}get type(){return this._type}set type(e){this._type=e||\"text\",this._validateType(),!this._isTextarea&&Hx().has(this._type)&&(this._elementRef.nativeElement.type=this._type)}get value(){return this._inputValueAccessor.value}set value(e){e!==this.value&&(this._inputValueAccessor.value=e,this.stateChanges.next())}get readonly(){return this._readonly}set readonly(e){this._readonly=G(e)}ngAfterViewInit(){this._platform.isBrowser&&this._autofillMonitor.monitor(this._elementRef.nativeElement).subscribe(e=>{this.autofilled=e.isAutofilled,this.stateChanges.next()})}ngOnChanges(){this.stateChanges.next()}ngOnDestroy(){this.stateChanges.complete(),this._platform.isBrowser&&this._autofillMonitor.stopMonitoring(this._elementRef.nativeElement)}ngDoCheck(){this.ngControl&&this.updateErrorState(),this._dirtyCheckNativeValue(),this._dirtyCheckPlaceholder()}focus(e){this._elementRef.nativeElement.focus(e)}_focusChanged(e){e!==this.focused&&(this.focused=e,this.stateChanges.next())}_onInput(){}_dirtyCheckPlaceholder(){var e,i;const r=(null===(i=null===(e=this._formField)||void 0===e?void 0:e._hideControlPlaceholder)||void 0===i?void 0:i.call(e))?null:this.placeholder;if(r!==this._previousPlaceholder){const s=this._elementRef.nativeElement;this._previousPlaceholder=r,r?s.setAttribute(\"placeholder\",r):s.removeAttribute(\"placeholder\")}}_dirtyCheckNativeValue(){const e=this._elementRef.nativeElement.value;this._previousNativeValue!==e&&(this._previousNativeValue=e,this.stateChanges.next())}_validateType(){i$.indexOf(this._type)}_isNeverEmpty(){return this._neverEmptyInputTypes.indexOf(this._type)>-1}_isBadInput(){let e=this._elementRef.nativeElement.validity;return e&&e.badInput}get empty(){return!(this._isNeverEmpty()||this._elementRef.nativeElement.value||this._isBadInput()||this.autofilled)}get shouldLabelFloat(){if(this._isNativeSelect){const e=this._elementRef.nativeElement,i=e.options[0];return this.focused||e.multiple||!this.empty||!!(e.selectedIndex>-1&&i&&i.label)}return this.focused||!this.empty}setDescribedByIds(e){e.length?this._elementRef.nativeElement.setAttribute(\"aria-describedby\",e.join(\" \")):this._elementRef.nativeElement.removeAttribute(\"aria-describedby\")}onContainerClick(){this.focused||this.focus()}_isInlineSelect(){const e=this._elementRef.nativeElement;return this._isNativeSelect&&(e.multiple||e.size>1)}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(It),f(Jn,10),f(oo,8),f(ao,8),f(mo),f(KE,10),f(n$),f(ne),f(el,8))},n.\\u0275dir=C({type:n,selectors:[[\"input\",\"matInput\",\"\"],[\"textarea\",\"matInput\",\"\"],[\"select\",\"matNativeControl\",\"\"],[\"input\",\"matNativeControl\",\"\"],[\"textarea\",\"matNativeControl\",\"\"]],hostAttrs:[1,\"mat-input-element\",\"mat-form-field-autofill-control\"],hostVars:12,hostBindings:function(e,i){1&e&&J(\"focus\",function(){return i._focusChanged(!0)})(\"blur\",function(){return i._focusChanged(!1)})(\"input\",function(){return i._onInput()}),2&e&&(Yn(\"disabled\",i.disabled)(\"required\",i.required),Z(\"id\",i.id)(\"data-placeholder\",i.placeholder)(\"name\",i.name||null)(\"readonly\",i.readonly&&!i._isNativeSelect||null)(\"aria-invalid\",i.empty&&i.required?null:i.errorState)(\"aria-required\",i.required),Ae(\"mat-input-server\",i._isServer)(\"mat-native-select-inline\",i._isInlineSelect()))},inputs:{disabled:\"disabled\",id:\"id\",placeholder:\"placeholder\",name:\"name\",required:\"required\",type:\"type\",errorStateMatcher:\"errorStateMatcher\",userAriaDescribedBy:[\"aria-describedby\",\"userAriaDescribedBy\"],value:\"value\",readonly:\"readonly\"},exportAs:[\"matInput\"],features:[L([{provide:Ja,useExisting:n}]),E,Je]}),n})(),a$=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[mo],imports:[[QE,mg,B],QE,mg]}),n})();function l$(n,t){if(1&n&&(x(0,\"mat-option\",13),we(1),S()),2&n){const e=t.$implicit;N(\"value\",e.name)(\"disabled\",e.disabled),T(1),Ut(e.description)}}function c$(n,t){if(1&n&&(x(0,\"mat-option\",13),we(1),S()),2&n){const e=t.$implicit,i=t.index;N(\"value\",e)(\"disabled\",i>0),T(1),Ut(e)}}function d$(n,t){if(1&n&&(x(0,\"mat-error\"),we(1),S()),2&n){const e=Be();T(1),Ut(e.explainTheError(e.srcAmountControl))}}function u$(n,t){if(1&n&&(x(0,\"mat-option\",13),we(1),S()),2&n){const e=t.$implicit;N(\"value\",e.name)(\"disabled\",e.disabled),T(1),Ut(e.description)}}function h$(n,t){if(1&n&&(x(0,\"mat-option\",13),we(1),S()),2&n){const e=t.$implicit,i=t.index;N(\"value\",e)(\"disabled\",i>0),T(1),Ut(e)}}function p$(n,t){if(1&n&&(x(0,\"mat-error\"),we(1),S()),2&n){const e=Be();T(1),Ut(e.explainTheError(e.dstAmountControl))}}let f$=(()=>{class n{constructor(){var e,i;this.srcAmountControl=new Rd(\"0\",[yi.pattern(/\\d+/),yi.min(1),yi.max(9999)]),this.dstAmountControl=new Rd(\"0\",[yi.pattern(/\\d+/),yi.min(1),yi.max(9999)]),this.srcChainList=Xa.map(r=>Object.assign(Object.assign({},r.from),{disabled:!r.active})),this.dstChainList=Xa.map(r=>Object.assign(Object.assign({},r.to),{disabled:!r.active})),this.srcChain=null===(e=this.srcChainList.find(r=>!r.disabled))||void 0===e?void 0:e.name,this.dstChain=(null===(i=Xa.filter(r=>r.from.name===this.srcChain).find(r=>r.active))||void 0===i?void 0:i.to.name)||\"\",this.srcCoin=\"EVER\",this.dstCoin=\"TXZ\",this.srcTokenList=ug.map(r=>r.name),this.dstTokenList=hg.map(r=>r.name),this.srcTokenChosen=\"EVER\",this.dstTokenChosen=\"wEVER\",this.srcAmount=\"0\",this.dstAmount=\"0\"}ngOnInit(){this.breakpoint=window.innerWidth<=400?1:2}onChainSrcValueChange(e){var i;this.srcChain=e,this.dstChain=(null===(i=Xa.filter(r=>r.from.name===this.srcChain).find(r=>r.active))||void 0===i?void 0:i.to.name)||\"\",this.changeTokenList(this.srcChain,this.dstChain)}onChainDstValueChange(e){var i;this.dstChain=e,this.srcChain=(null===(i=Xa.filter(r=>r.from.name===this.srcChain).find(r=>r.active))||void 0===i?void 0:i.to.name)||\"\",this.changeTokenList(this.srcChain,this.dstChain)}changeTokenList(e,i){\"Tezos\"==e&&(this.srcCoin=\"TXZ\",this.dstCoin=\"EVER\",this.srcTokenList=hg.map(r=>r.name),this.dstTokenList=ug.map(r=>r.name),this.srcTokenChosen=\"TXZ\",this.dstTokenChosen=\"wTXZ\"),\"Everscale\"===e&&(this.srcCoin=\"EVER\",this.dstCoin=\"TXZ\",this.srcTokenList=ug.map(r=>r.name),this.dstTokenList=hg.map(r=>r.name),this.srcTokenChosen=\"EVER\",this.dstTokenChosen=\"wEVER\")}onSelectionChange(e){console.log(\"onSelectionChange, newValue = \",e.value,e.source)}onSrcTokenChange(e){this.dstTokenChosen=e===this.srcTokenList[0]?this.dstCoin:this.dstTokenList[0]}onDstTokenChange(e){this.srcTokenChosen=e===this.dstTokenList[0]?this.srcCoin:this.srcTokenList[0]}calculateAmount(e,i){e?(this.dstAmount=(.99*Number.parseFloat(i)).toFixed(8).replace(/(\\.\\d*)0+/,\"$1\"),this.dstAmountControl.setValue(this.dstAmount)):(this.srcAmount=(Number.parseFloat(i)/.99).toFixed(8).replace(/\\.0+$/,\"\"),this.srcAmountControl.setValue(this.srcAmount))}explainTheError(e){const i=e.errors||{};return\"Wrong number: \"+Object.keys(i).reduce((r,s)=>{switch(s){case\"min\":return r+`minimal value is ${i[s].min}. `;case\"max\":return r+`maximum value is ${i[s].max}. `;case\"pattern\":return r+\"it should be number. \";default:return r+\"wrong amount. \"}},\"\")}consoleLog(e){console.log(e)}onResize(e){this.breakpoint=e.target.innerWidth<=400?1:2}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275cmp=xe({type:n,selectors:[[\"app-main\"]],decls:56,vars:21,consts:[[3,\"cols\",\"resize\"],[1,\"container\"],[\"appearance\",\"outline\"],[3,\"value\",\"valueChange\",\"selectionChange\"],[3,\"value\",\"disabled\",4,\"ngFor\",\"ngForOf\"],[3,\"value\",\"valueChange\"],[\"label\",\"Native coins\"],[3,\"value\"],[\"label\",\"Tokens\"],[\"matInput\",\"\",\"placeholder\",\"Amount\",\"type\",\"number\",3,\"value\",\"formControl\",\"change\"],[\"srcInputElement\",\"\"],[4,\"ngIf\"],[\"dstInputElement\",\"\"],[3,\"value\",\"disabled\"]],template:function(e,i){if(1&e){const r=ia();x(0,\"h1\"),we(1,\"Everscale-Tezos Bridge\"),S(),x(2,\"mat-grid-list\",0),J(\"resize\",function(o){return i.onResize(o)},!1,Uv),x(3,\"mat-grid-tile\")(4,\"div\",1)(5,\"h3\"),we(6,\"Choose what you have:\"),S(),x(7,\"mat-form-field\",2)(8,\"mat-label\"),we(9,\"Blockchain\"),S(),x(10,\"mat-select\",3),J(\"valueChange\",function(o){return i.srcChain=o})(\"selectionChange\",function(o){return i.onSelectionChange(o)})(\"valueChange\",function(o){return i.onChainSrcValueChange(o)}),Ee(11,l$,2,3,\"mat-option\",4),S()(),x(12,\"mat-form-field\",2)(13,\"mat-label\"),we(14,\"Token\"),S(),x(15,\"mat-select\",5),J(\"valueChange\",function(o){return i.srcTokenChosen=o})(\"valueChange\",function(o){return i.onSrcTokenChange(o)}),x(16,\"mat-optgroup\",6)(17,\"mat-option\",7),we(18),S()(),x(19,\"mat-optgroup\",8),Ee(20,c$,2,3,\"mat-option\",4),S()()(),x(21,\"mat-form-field\",2)(22,\"mat-label\"),we(23,\"Amount\"),S(),x(24,\"input\",9,10),J(\"change\",function(){Dr(r);const o=wn(25);return i.calculateAmount(!0,o.value)}),S(),x(26,\"mat-hint\"),we(27),S(),Ee(28,d$,2,1,\"mat-error\",11),S()()(),x(29,\"mat-grid-tile\")(30,\"div\",1)(31,\"h3\"),we(32,\"Choose what you want:\"),S(),x(33,\"mat-form-field\",2)(34,\"mat-label\"),we(35,\"Blockchain\"),S(),x(36,\"mat-select\",5),J(\"valueChange\",function(o){return i.dstChain=o})(\"valueChange\",function(o){return i.onChainDstValueChange(o)}),Ee(37,u$,2,3,\"mat-option\",4),S()(),x(38,\"mat-form-field\",2)(39,\"mat-label\"),we(40,\"Token\"),S(),x(41,\"mat-select\",5),J(\"valueChange\",function(o){return i.dstTokenChosen=o})(\"valueChange\",function(o){return i.onDstTokenChange(o)}),x(42,\"mat-optgroup\",6)(43,\"mat-option\",7),we(44),S()(),x(45,\"mat-optgroup\",8),Ee(46,h$,2,3,\"mat-option\",4),S()()(),x(47,\"mat-form-field\",2)(48,\"mat-label\"),we(49,\"Amount\"),S(),x(50,\"input\",9,12),J(\"change\",function(){Dr(r);const o=wn(51);return i.calculateAmount(!1,o.value)}),S(),Ee(52,p$,2,1,\"mat-error\",11),x(53,\"mat-hint\"),we(54),S()()()(),Le(55,\"router-outlet\"),S()}2&e&&(T(2),N(\"cols\",i.breakpoint),T(8),N(\"value\",i.srcChain),T(1),N(\"ngForOf\",i.srcChainList),T(4),N(\"value\",i.srcTokenChosen),T(2),N(\"value\",i.srcCoin),T(1),Ut(i.srcCoin),T(2),N(\"ngForOf\",i.srcTokenList),T(4),N(\"value\",i.srcAmount)(\"formControl\",i.srcAmountControl),T(3),qn(\"Amount of \",i.srcTokenChosen,\" to pay\"),T(1),N(\"ngIf\",i.srcAmountControl.invalid),T(8),N(\"value\",i.dstChain),T(1),N(\"ngForOf\",i.dstChainList),T(4),N(\"value\",i.dstTokenChosen),T(2),N(\"value\",i.dstCoin),T(1),Ut(i.dstCoin),T(2),N(\"ngForOf\",i.dstTokenList),T(4),N(\"value\",i.dstAmount)(\"formControl\",i.dstAmountControl),T(2),N(\"ngIf\",i.dstAmountControl.invalid),T(2),qn(\"Amount of \",i.dstTokenChosen,\" to receive\"))},directives:[bU,yE,t5,fg,t$,gD,hE,J3,o$,Tm,Dd,ax,Im,YU,Ca,GU,Pf],styles:[\".container[_ngcontent-%COMP%] .mat-form-field[_ngcontent-%COMP%] + .mat-form-field[_ngcontent-%COMP%]{margin-left:8px}mat-form-field[_ngcontent-%COMP%]{display:block}mat-grid-list[_ngcontent-%COMP%]{display:flex;flex-wrap:wrap;justify-content:center}\"]}),n})(),ZE=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),m$=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();function wg(n,t,e){for(let i in t)if(t.hasOwnProperty(i)){const r=t[i];r?n.setProperty(i,r,(null==e?void 0:e.has(i))?\"important\":\"\"):n.removeProperty(i)}return n}function _o(n,t){const e=t?\"\":\"none\";wg(n.style,{\"touch-action\":t?\"\":\"none\",\"-webkit-user-drag\":t?\"\":\"none\",\"-webkit-tap-highlight-color\":t?\"\":\"transparent\",\"user-select\":e,\"-ms-user-select\":e,\"-webkit-user-select\":e,\"-moz-user-select\":e})}function XE(n,t,e){wg(n.style,{position:t?\"\":\"fixed\",top:t?\"\":\"0\",opacity:t?\"\":\"0\",left:t?\"\":\"-999em\"},e)}function Yd(n,t){return t&&\"none\"!=t?n+\" \"+t:n}function JE(n){const t=n.toLowerCase().indexOf(\"ms\")>-1?1:1e3;return parseFloat(n)*t}function Mg(n,t){return n.getPropertyValue(t).split(\",\").map(i=>i.trim())}function xg(n){const t=n.getBoundingClientRect();return{top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:t.width,height:t.height,x:t.x,y:t.y}}function Eg(n,t,e){const{top:i,bottom:r,left:s,right:o}=n;return e>=i&&e<=r&&t>=s&&t<=o}function sl(n,t,e){n.top+=t,n.bottom=n.top+n.height,n.left+=e,n.right=n.left+n.width}function eS(n,t,e,i){const{top:r,right:s,bottom:o,left:a,width:l,height:c}=n,d=l*t,u=c*t;return i>r-u&&i<o+u&&e>a-d&&e<s+d}class tS{constructor(t){this._document=t,this.positions=new Map}clear(){this.positions.clear()}cache(t){this.clear(),this.positions.set(this._document,{scrollPosition:this.getViewportScrollPosition()}),t.forEach(e=>{this.positions.set(e,{scrollPosition:{top:e.scrollTop,left:e.scrollLeft},clientRect:xg(e)})})}handleScroll(t){const e=Pn(t),i=this.positions.get(e);if(!i)return null;const r=i.scrollPosition;let s,o;if(e===this._document){const c=this.getViewportScrollPosition();s=c.top,o=c.left}else s=e.scrollTop,o=e.scrollLeft;const a=r.top-s,l=r.left-o;return this.positions.forEach((c,d)=>{c.clientRect&&e!==d&&e.contains(d)&&sl(c.clientRect,a,l)}),r.top=s,r.left=o,{top:a,left:l}}getViewportScrollPosition(){return{top:window.scrollY,left:window.scrollX}}}function nS(n){const t=n.cloneNode(!0),e=t.querySelectorAll(\"[id]\"),i=n.nodeName.toLowerCase();t.removeAttribute(\"id\");for(let r=0;r<e.length;r++)e[r].removeAttribute(\"id\");return\"canvas\"===i?sS(n,t):(\"input\"===i||\"select\"===i||\"textarea\"===i)&&rS(n,t),iS(\"canvas\",n,t,sS),iS(\"input, textarea, select\",n,t,rS),t}function iS(n,t,e,i){const r=t.querySelectorAll(n);if(r.length){const s=e.querySelectorAll(n);for(let o=0;o<r.length;o++)i(r[o],s[o])}}let v$=0;function rS(n,t){\"file\"!==t.type&&(t.value=n.value),\"radio\"===t.type&&t.name&&(t.name=`mat-clone-${t.name}-${v$++}`)}function sS(n,t){const e=t.getContext(\"2d\");if(e)try{e.drawImage(n,0,0)}catch(i){}}const oS=ei({passive:!0}),Qd=ei({passive:!1}),Sg=new Set([\"position\"]);class b${constructor(t,e,i,r,s,o){this._config=e,this._document=i,this._ngZone=r,this._viewportRuler=s,this._dragDropRegistry=o,this._passiveTransform={x:0,y:0},this._activeTransform={x:0,y:0},this._hasStartedDragging=!1,this._moveEvents=new O,this._pointerMoveSubscription=ke.EMPTY,this._pointerUpSubscription=ke.EMPTY,this._scrollSubscription=ke.EMPTY,this._resizeSubscription=ke.EMPTY,this._boundaryElement=null,this._nativeInteractionsEnabled=!0,this._handles=[],this._disabledHandles=new Set,this._direction=\"ltr\",this.dragStartDelay=0,this._disabled=!1,this.beforeStarted=new O,this.started=new O,this.released=new O,this.ended=new O,this.entered=new O,this.exited=new O,this.dropped=new O,this.moved=this._moveEvents,this._pointerDown=a=>{if(this.beforeStarted.next(),this._handles.length){const l=this._getTargetHandle(a);l&&!this._disabledHandles.has(l)&&!this.disabled&&this._initializeDragSequence(l,a)}else this.disabled||this._initializeDragSequence(this._rootElement,a)},this._pointerMove=a=>{const l=this._getPointerPositionOnPage(a);if(!this._hasStartedDragging){if(Math.abs(l.x-this._pickupPositionOnPage.x)+Math.abs(l.y-this._pickupPositionOnPage.y)>=this._config.dragStartThreshold){const p=Date.now()>=this._dragStartTime+this._getDragStartDelay(a),m=this._dropContainer;if(!p)return void this._endDragSequence(a);(!m||!m.isDragging()&&!m.isReceiving())&&(a.preventDefault(),this._hasStartedDragging=!0,this._ngZone.run(()=>this._startDragSequence(a)))}return}a.preventDefault();const c=this._getConstrainedPointerPosition(l);if(this._hasMoved=!0,this._lastKnownPointerPosition=l,this._updatePointerDirectionDelta(c),this._dropContainer)this._updateActiveDropContainer(c,l);else{const d=this._activeTransform;d.x=c.x-this._pickupPositionOnPage.x+this._passiveTransform.x,d.y=c.y-this._pickupPositionOnPage.y+this._passiveTransform.y,this._applyRootElementTransform(d.x,d.y)}this._moveEvents.observers.length&&this._ngZone.run(()=>{this._moveEvents.next({source:this,pointerPosition:c,event:a,distance:this._getDragDistance(c),delta:this._pointerDirectionDelta})})},this._pointerUp=a=>{this._endDragSequence(a)},this._nativeDragStart=a=>{if(this._handles.length){const l=this._getTargetHandle(a);l&&!this._disabledHandles.has(l)&&!this.disabled&&a.preventDefault()}else this.disabled||a.preventDefault()},this.withRootElement(t).withParent(e.parentDragRef||null),this._parentPositions=new tS(i),o.registerDragItem(this)}get disabled(){return this._disabled||!(!this._dropContainer||!this._dropContainer.disabled)}set disabled(t){const e=G(t);e!==this._disabled&&(this._disabled=e,this._toggleNativeDragInteractions(),this._handles.forEach(i=>_o(i,e)))}getPlaceholderElement(){return this._placeholder}getRootElement(){return this._rootElement}getVisibleElement(){return this.isDragging()?this.getPlaceholderElement():this.getRootElement()}withHandles(t){this._handles=t.map(i=>at(i)),this._handles.forEach(i=>_o(i,this.disabled)),this._toggleNativeDragInteractions();const e=new Set;return this._disabledHandles.forEach(i=>{this._handles.indexOf(i)>-1&&e.add(i)}),this._disabledHandles=e,this}withPreviewTemplate(t){return this._previewTemplate=t,this}withPlaceholderTemplate(t){return this._placeholderTemplate=t,this}withRootElement(t){const e=at(t);return e!==this._rootElement&&(this._rootElement&&this._removeRootElementListeners(this._rootElement),this._ngZone.runOutsideAngular(()=>{e.addEventListener(\"mousedown\",this._pointerDown,Qd),e.addEventListener(\"touchstart\",this._pointerDown,oS),e.addEventListener(\"dragstart\",this._nativeDragStart,Qd)}),this._initialTransform=void 0,this._rootElement=e),\"undefined\"!=typeof SVGElement&&this._rootElement instanceof SVGElement&&(this._ownerSVGElement=this._rootElement.ownerSVGElement),this}withBoundaryElement(t){return this._boundaryElement=t?at(t):null,this._resizeSubscription.unsubscribe(),t&&(this._resizeSubscription=this._viewportRuler.change(10).subscribe(()=>this._containInsideBoundaryOnResize())),this}withParent(t){return this._parentDragRef=t,this}dispose(){var t,e;this._removeRootElementListeners(this._rootElement),this.isDragging()&&(null===(t=this._rootElement)||void 0===t||t.remove()),null===(e=this._anchor)||void 0===e||e.remove(),this._destroyPreview(),this._destroyPlaceholder(),this._dragDropRegistry.removeDragItem(this),this._removeSubscriptions(),this.beforeStarted.complete(),this.started.complete(),this.released.complete(),this.ended.complete(),this.entered.complete(),this.exited.complete(),this.dropped.complete(),this._moveEvents.complete(),this._handles=[],this._disabledHandles.clear(),this._dropContainer=void 0,this._resizeSubscription.unsubscribe(),this._parentPositions.clear(),this._boundaryElement=this._rootElement=this._ownerSVGElement=this._placeholderTemplate=this._previewTemplate=this._anchor=this._parentDragRef=null}isDragging(){return this._hasStartedDragging&&this._dragDropRegistry.isDragging(this)}reset(){this._rootElement.style.transform=this._initialTransform||\"\",this._activeTransform={x:0,y:0},this._passiveTransform={x:0,y:0}}disableHandle(t){!this._disabledHandles.has(t)&&this._handles.indexOf(t)>-1&&(this._disabledHandles.add(t),_o(t,!0))}enableHandle(t){this._disabledHandles.has(t)&&(this._disabledHandles.delete(t),_o(t,this.disabled))}withDirection(t){return this._direction=t,this}_withDropContainer(t){this._dropContainer=t}getFreeDragPosition(){const t=this.isDragging()?this._activeTransform:this._passiveTransform;return{x:t.x,y:t.y}}setFreeDragPosition(t){return this._activeTransform={x:0,y:0},this._passiveTransform.x=t.x,this._passiveTransform.y=t.y,this._dropContainer||this._applyRootElementTransform(t.x,t.y),this}withPreviewContainer(t){return this._previewContainer=t,this}_sortFromLastPointerPosition(){const t=this._lastKnownPointerPosition;t&&this._dropContainer&&this._updateActiveDropContainer(this._getConstrainedPointerPosition(t),t)}_removeSubscriptions(){this._pointerMoveSubscription.unsubscribe(),this._pointerUpSubscription.unsubscribe(),this._scrollSubscription.unsubscribe()}_destroyPreview(){var t,e;null===(t=this._preview)||void 0===t||t.remove(),null===(e=this._previewRef)||void 0===e||e.destroy(),this._preview=this._previewRef=null}_destroyPlaceholder(){var t,e;null===(t=this._placeholder)||void 0===t||t.remove(),null===(e=this._placeholderRef)||void 0===e||e.destroy(),this._placeholder=this._placeholderRef=null}_endDragSequence(t){if(this._dragDropRegistry.isDragging(this)&&(this._removeSubscriptions(),this._dragDropRegistry.stopDragging(this),this._toggleNativeDragInteractions(),this._handles&&(this._rootElement.style.webkitTapHighlightColor=this._rootElementTapHighlight),this._hasStartedDragging))if(this.released.next({source:this}),this._dropContainer)this._dropContainer._stopScrolling(),this._animatePreviewToPlaceholder().then(()=>{this._cleanupDragArtifacts(t),this._cleanupCachedDimensions(),this._dragDropRegistry.stopDragging(this)});else{this._passiveTransform.x=this._activeTransform.x;const e=this._getPointerPositionOnPage(t);this._passiveTransform.y=this._activeTransform.y,this._ngZone.run(()=>{this.ended.next({source:this,distance:this._getDragDistance(e),dropPoint:e})}),this._cleanupCachedDimensions(),this._dragDropRegistry.stopDragging(this)}}_startDragSequence(t){ol(t)&&(this._lastTouchEventTime=Date.now()),this._toggleNativeDragInteractions();const e=this._dropContainer;if(e){const i=this._rootElement,r=i.parentNode,s=this._placeholder=this._createPlaceholderElement(),o=this._anchor=this._anchor||this._document.createComment(\"\"),a=this._getShadowRoot();r.insertBefore(o,i),this._initialTransform=i.style.transform||\"\",this._preview=this._createPreviewElement(),XE(i,!1,Sg),this._document.body.appendChild(r.replaceChild(s,i)),this._getPreviewInsertionPoint(r,a).appendChild(this._preview),this.started.next({source:this}),e.start(),this._initialContainer=e,this._initialIndex=e.getItemIndex(this)}else this.started.next({source:this}),this._initialContainer=this._initialIndex=void 0;this._parentPositions.cache(e?e.getScrollableParents():[])}_initializeDragSequence(t,e){this._parentDragRef&&e.stopPropagation();const i=this.isDragging(),r=ol(e),s=!r&&0!==e.button,o=this._rootElement,a=Pn(e),l=!r&&this._lastTouchEventTime&&this._lastTouchEventTime+800>Date.now(),c=r?Zm(e):Km(e);if(a&&a.draggable&&\"mousedown\"===e.type&&e.preventDefault(),i||s||l||c)return;if(this._handles.length){const h=o.style;this._rootElementTapHighlight=h.webkitTapHighlightColor||\"\",h.webkitTapHighlightColor=\"transparent\"}this._hasStartedDragging=this._hasMoved=!1,this._removeSubscriptions(),this._pointerMoveSubscription=this._dragDropRegistry.pointerMove.subscribe(this._pointerMove),this._pointerUpSubscription=this._dragDropRegistry.pointerUp.subscribe(this._pointerUp),this._scrollSubscription=this._dragDropRegistry.scrolled(this._getShadowRoot()).subscribe(h=>this._updateOnScroll(h)),this._boundaryElement&&(this._boundaryRect=xg(this._boundaryElement));const d=this._previewTemplate;this._pickupPositionInElement=d&&d.template&&!d.matchSize?{x:0,y:0}:this._getPointerPositionInElement(t,e);const u=this._pickupPositionOnPage=this._lastKnownPointerPosition=this._getPointerPositionOnPage(e);this._pointerDirectionDelta={x:0,y:0},this._pointerPositionAtLastDirectionChange={x:u.x,y:u.y},this._dragStartTime=Date.now(),this._dragDropRegistry.startDragging(this,e)}_cleanupDragArtifacts(t){XE(this._rootElement,!0,Sg),this._anchor.parentNode.replaceChild(this._rootElement,this._anchor),this._destroyPreview(),this._destroyPlaceholder(),this._boundaryRect=this._previewRect=this._initialTransform=void 0,this._ngZone.run(()=>{const e=this._dropContainer,i=e.getItemIndex(this),r=this._getPointerPositionOnPage(t),s=this._getDragDistance(r),o=e._isOverContainer(r.x,r.y);this.ended.next({source:this,distance:s,dropPoint:r}),this.dropped.next({item:this,currentIndex:i,previousIndex:this._initialIndex,container:e,previousContainer:this._initialContainer,isPointerOverContainer:o,distance:s,dropPoint:r}),e.drop(this,i,this._initialIndex,this._initialContainer,o,s,r),this._dropContainer=this._initialContainer})}_updateActiveDropContainer({x:t,y:e},{x:i,y:r}){let s=this._initialContainer._getSiblingContainerFromPosition(this,t,e);!s&&this._dropContainer!==this._initialContainer&&this._initialContainer._isOverContainer(t,e)&&(s=this._initialContainer),s&&s!==this._dropContainer&&this._ngZone.run(()=>{this.exited.next({item:this,container:this._dropContainer}),this._dropContainer.exit(this),this._dropContainer=s,this._dropContainer.enter(this,t,e,s===this._initialContainer&&s.sortingDisabled?this._initialIndex:void 0),this.entered.next({item:this,container:s,currentIndex:s.getItemIndex(this)})}),this.isDragging()&&(this._dropContainer._startScrollingIfNecessary(i,r),this._dropContainer._sortItem(this,t,e,this._pointerDirectionDelta),this._applyPreviewTransform(t-this._pickupPositionInElement.x,e-this._pickupPositionInElement.y))}_createPreviewElement(){const t=this._previewTemplate,e=this.previewClass,i=t?t.template:null;let r;if(i&&t){const s=t.matchSize?this._rootElement.getBoundingClientRect():null,o=t.viewContainer.createEmbeddedView(i,t.context);o.detectChanges(),r=lS(o,this._document),this._previewRef=o,t.matchSize?cS(r,s):r.style.transform=Kd(this._pickupPositionOnPage.x,this._pickupPositionOnPage.y)}else{const s=this._rootElement;r=nS(s),cS(r,s.getBoundingClientRect()),this._initialTransform&&(r.style.transform=this._initialTransform)}return wg(r.style,{\"pointer-events\":\"none\",margin:\"0\",position:\"fixed\",top:\"0\",left:\"0\",\"z-index\":`${this._config.zIndex||1e3}`},Sg),_o(r,!1),r.classList.add(\"cdk-drag-preview\"),r.setAttribute(\"dir\",this._direction),e&&(Array.isArray(e)?e.forEach(s=>r.classList.add(s)):r.classList.add(e)),r}_animatePreviewToPlaceholder(){if(!this._hasMoved)return Promise.resolve();const t=this._placeholder.getBoundingClientRect();this._preview.classList.add(\"cdk-drag-animating\"),this._applyPreviewTransform(t.left,t.top);const e=function _$(n){const t=getComputedStyle(n),e=Mg(t,\"transition-property\"),i=e.find(a=>\"transform\"===a||\"all\"===a);if(!i)return 0;const r=e.indexOf(i),s=Mg(t,\"transition-duration\"),o=Mg(t,\"transition-delay\");return JE(s[r])+JE(o[r])}(this._preview);return 0===e?Promise.resolve():this._ngZone.runOutsideAngular(()=>new Promise(i=>{const r=o=>{var a;(!o||Pn(o)===this._preview&&\"transform\"===o.propertyName)&&(null===(a=this._preview)||void 0===a||a.removeEventListener(\"transitionend\",r),i(),clearTimeout(s))},s=setTimeout(r,1.5*e);this._preview.addEventListener(\"transitionend\",r)}))}_createPlaceholderElement(){const t=this._placeholderTemplate,e=t?t.template:null;let i;return e?(this._placeholderRef=t.viewContainer.createEmbeddedView(e,t.context),this._placeholderRef.detectChanges(),i=lS(this._placeholderRef,this._document)):i=nS(this._rootElement),i.style.pointerEvents=\"none\",i.classList.add(\"cdk-drag-placeholder\"),i}_getPointerPositionInElement(t,e){const i=this._rootElement.getBoundingClientRect(),r=t===this._rootElement?null:t,s=r?r.getBoundingClientRect():i,o=ol(e)?e.targetTouches[0]:e,a=this._getViewportScrollPosition();return{x:s.left-i.left+(o.pageX-s.left-a.left),y:s.top-i.top+(o.pageY-s.top-a.top)}}_getPointerPositionOnPage(t){const e=this._getViewportScrollPosition(),i=ol(t)?t.touches[0]||t.changedTouches[0]||{pageX:0,pageY:0}:t,r=i.pageX-e.left,s=i.pageY-e.top;if(this._ownerSVGElement){const o=this._ownerSVGElement.getScreenCTM();if(o){const a=this._ownerSVGElement.createSVGPoint();return a.x=r,a.y=s,a.matrixTransform(o.inverse())}}return{x:r,y:s}}_getConstrainedPointerPosition(t){const e=this._dropContainer?this._dropContainer.lockAxis:null;let{x:i,y:r}=this.constrainPosition?this.constrainPosition(t,this):t;if(\"x\"===this.lockAxis||\"x\"===e?r=this._pickupPositionOnPage.y:(\"y\"===this.lockAxis||\"y\"===e)&&(i=this._pickupPositionOnPage.x),this._boundaryRect){const{x:s,y:o}=this._pickupPositionInElement,a=this._boundaryRect,{width:l,height:c}=this._getPreviewRect(),d=a.top+o,u=a.bottom-(c-o);i=aS(i,a.left+s,a.right-(l-s)),r=aS(r,d,u)}return{x:i,y:r}}_updatePointerDirectionDelta(t){const{x:e,y:i}=t,r=this._pointerDirectionDelta,s=this._pointerPositionAtLastDirectionChange,o=Math.abs(e-s.x),a=Math.abs(i-s.y);return o>this._config.pointerDirectionChangeThreshold&&(r.x=e>s.x?1:-1,s.x=e),a>this._config.pointerDirectionChangeThreshold&&(r.y=i>s.y?1:-1,s.y=i),r}_toggleNativeDragInteractions(){if(!this._rootElement||!this._handles)return;const t=this._handles.length>0||!this.isDragging();t!==this._nativeInteractionsEnabled&&(this._nativeInteractionsEnabled=t,_o(this._rootElement,t))}_removeRootElementListeners(t){t.removeEventListener(\"mousedown\",this._pointerDown,Qd),t.removeEventListener(\"touchstart\",this._pointerDown,oS),t.removeEventListener(\"dragstart\",this._nativeDragStart,Qd)}_applyRootElementTransform(t,e){const i=Kd(t,e),r=this._rootElement.style;null==this._initialTransform&&(this._initialTransform=r.transform&&\"none\"!=r.transform?r.transform:\"\"),r.transform=Yd(i,this._initialTransform)}_applyPreviewTransform(t,e){var i;const r=(null===(i=this._previewTemplate)||void 0===i?void 0:i.template)?void 0:this._initialTransform,s=Kd(t,e);this._preview.style.transform=Yd(s,r)}_getDragDistance(t){const e=this._pickupPositionOnPage;return e?{x:t.x-e.x,y:t.y-e.y}:{x:0,y:0}}_cleanupCachedDimensions(){this._boundaryRect=this._previewRect=void 0,this._parentPositions.clear()}_containInsideBoundaryOnResize(){let{x:t,y:e}=this._passiveTransform;if(0===t&&0===e||this.isDragging()||!this._boundaryElement)return;const i=this._boundaryElement.getBoundingClientRect(),r=this._rootElement.getBoundingClientRect();if(0===i.width&&0===i.height||0===r.width&&0===r.height)return;const s=i.left-r.left,o=r.right-i.right,a=i.top-r.top,l=r.bottom-i.bottom;i.width>r.width?(s>0&&(t+=s),o>0&&(t-=o)):t=0,i.height>r.height?(a>0&&(e+=a),l>0&&(e-=l)):e=0,(t!==this._passiveTransform.x||e!==this._passiveTransform.y)&&this.setFreeDragPosition({y:e,x:t})}_getDragStartDelay(t){const e=this.dragStartDelay;return\"number\"==typeof e?e:ol(t)?e.touch:e?e.mouse:0}_updateOnScroll(t){const e=this._parentPositions.handleScroll(t);if(e){const i=Pn(t);this._boundaryRect&&i!==this._boundaryElement&&i.contains(this._boundaryElement)&&sl(this._boundaryRect,e.top,e.left),this._pickupPositionOnPage.x+=e.left,this._pickupPositionOnPage.y+=e.top,this._dropContainer||(this._activeTransform.x-=e.left,this._activeTransform.y-=e.top,this._applyRootElementTransform(this._activeTransform.x,this._activeTransform.y))}}_getViewportScrollPosition(){var t;return(null===(t=this._parentPositions.positions.get(this._document))||void 0===t?void 0:t.scrollPosition)||this._parentPositions.getViewportScrollPosition()}_getShadowRoot(){return void 0===this._cachedShadowRoot&&(this._cachedShadowRoot=Fd(this._rootElement)),this._cachedShadowRoot}_getPreviewInsertionPoint(t,e){const i=this._previewContainer||\"global\";if(\"parent\"===i)return t;if(\"global\"===i){const r=this._document;return e||r.fullscreenElement||r.webkitFullscreenElement||r.mozFullScreenElement||r.msFullscreenElement||r.body}return at(i)}_getPreviewRect(){return(!this._previewRect||!this._previewRect.width&&!this._previewRect.height)&&(this._previewRect=(this._preview||this._rootElement).getBoundingClientRect()),this._previewRect}_getTargetHandle(t){return this._handles.find(e=>t.target&&(t.target===e||e.contains(t.target)))}}function Kd(n,t){return`translate3d(${Math.round(n)}px, ${Math.round(t)}px, 0)`}function aS(n,t,e){return Math.max(t,Math.min(e,n))}function ol(n){return\"t\"===n.type[0]}function lS(n,t){const e=n.rootNodes;if(1===e.length&&e[0].nodeType===t.ELEMENT_NODE)return e[0];const i=t.createElement(\"div\");return e.forEach(r=>i.appendChild(r)),i}function cS(n,t){n.style.width=`${t.width}px`,n.style.height=`${t.height}px`,n.style.transform=Kd(t.left,t.top)}function al(n,t){return Math.max(0,Math.min(t,n))}class D${constructor(t,e,i,r,s){this._dragDropRegistry=e,this._ngZone=r,this._viewportRuler=s,this.disabled=!1,this.sortingDisabled=!1,this.autoScrollDisabled=!1,this.autoScrollStep=2,this.enterPredicate=()=>!0,this.sortPredicate=()=>!0,this.beforeStarted=new O,this.entered=new O,this.exited=new O,this.dropped=new O,this.sorted=new O,this._isDragging=!1,this._itemPositions=[],this._previousSwap={drag:null,delta:0,overlaps:!1},this._draggables=[],this._siblings=[],this._orientation=\"vertical\",this._activeSiblings=new Set,this._direction=\"ltr\",this._viewportScrollSubscription=ke.EMPTY,this._verticalScrollDirection=0,this._horizontalScrollDirection=0,this._stopScrollTimers=new O,this._cachedShadowRoot=null,this._startScrollInterval=()=>{this._stopScrolling(),function g$(n=0,t=qa){return n<0&&(n=0),_g(n,n,t)}(0,EE).pipe(Ie(this._stopScrollTimers)).subscribe(()=>{const o=this._scrollNode,a=this.autoScrollStep;1===this._verticalScrollDirection?o.scrollBy(0,-a):2===this._verticalScrollDirection&&o.scrollBy(0,a),1===this._horizontalScrollDirection?o.scrollBy(-a,0):2===this._horizontalScrollDirection&&o.scrollBy(a,0)})},this.element=at(t),this._document=i,this.withScrollableParents([this.element]),e.registerDropContainer(this),this._parentPositions=new tS(i)}dispose(){this._stopScrolling(),this._stopScrollTimers.complete(),this._viewportScrollSubscription.unsubscribe(),this.beforeStarted.complete(),this.entered.complete(),this.exited.complete(),this.dropped.complete(),this.sorted.complete(),this._activeSiblings.clear(),this._scrollNode=null,this._parentPositions.clear(),this._dragDropRegistry.removeDropContainer(this)}isDragging(){return this._isDragging}start(){this._draggingStarted(),this._notifyReceivingSiblings()}enter(t,e,i,r){let s;this._draggingStarted(),null==r?(s=this.sortingDisabled?this._draggables.indexOf(t):-1,-1===s&&(s=this._getItemIndexFromPointerPosition(t,e,i))):s=r;const o=this._activeDraggables,a=o.indexOf(t),l=t.getPlaceholderElement();let c=o[s];if(c===t&&(c=o[s+1]),!c&&(null==s||-1===s||s<o.length-1)&&this._shouldEnterAsFirstChild(e,i)&&(c=o[0]),a>-1&&o.splice(a,1),c&&!this._dragDropRegistry.isDragging(c)){const d=c.getRootElement();d.parentElement.insertBefore(l,d),o.splice(s,0,t)}else at(this.element).appendChild(l),o.push(t);l.style.transform=\"\",this._cacheItemPositions(),this._cacheParentPositions(),this._notifyReceivingSiblings(),this.entered.next({item:t,container:this,currentIndex:this.getItemIndex(t)})}exit(t){this._reset(),this.exited.next({item:t,container:this})}drop(t,e,i,r,s,o,a){this._reset(),this.dropped.next({item:t,currentIndex:e,previousIndex:i,container:this,previousContainer:r,isPointerOverContainer:s,distance:o,dropPoint:a})}withItems(t){const e=this._draggables;return this._draggables=t,t.forEach(i=>i._withDropContainer(this)),this.isDragging()&&(e.filter(r=>r.isDragging()).every(r=>-1===t.indexOf(r))?this._reset():this._cacheItems()),this}withDirection(t){return this._direction=t,this}connectedTo(t){return this._siblings=t.slice(),this}withOrientation(t){return this._orientation=t,this}withScrollableParents(t){const e=at(this.element);return this._scrollableElements=-1===t.indexOf(e)?[e,...t]:t.slice(),this}getScrollableParents(){return this._scrollableElements}getItemIndex(t){return this._isDragging?(\"horizontal\"===this._orientation&&\"rtl\"===this._direction?this._itemPositions.slice().reverse():this._itemPositions).findIndex(i=>i.drag===t):this._draggables.indexOf(t)}isReceiving(){return this._activeSiblings.size>0}_sortItem(t,e,i,r){if(this.sortingDisabled||!this._clientRect||!eS(this._clientRect,.05,e,i))return;const s=this._itemPositions,o=this._getItemIndexFromPointerPosition(t,e,i,r);if(-1===o&&s.length>0)return;const a=\"horizontal\"===this._orientation,l=s.findIndex(_=>_.drag===t),c=s[o],u=c.clientRect,h=l>o?1:-1,p=this._getItemOffsetPx(s[l].clientRect,u,h),m=this._getSiblingOffsetPx(l,s,h),g=s.slice();(function C$(n,t,e){const i=al(t,n.length-1),r=al(e,n.length-1);if(i===r)return;const s=n[i],o=r<i?-1:1;for(let a=i;a!==r;a+=o)n[a]=n[a+o];n[r]=s})(s,l,o),this.sorted.next({previousIndex:l,currentIndex:o,container:this,item:t}),s.forEach((_,D)=>{if(g[D]===_)return;const v=_.drag===t,M=v?p:m,V=v?t.getPlaceholderElement():_.drag.getRootElement();_.offset+=M,a?(V.style.transform=Yd(`translate3d(${Math.round(_.offset)}px, 0, 0)`,_.initialTransform),sl(_.clientRect,0,M)):(V.style.transform=Yd(`translate3d(0, ${Math.round(_.offset)}px, 0)`,_.initialTransform),sl(_.clientRect,M,0))}),this._previousSwap.overlaps=Eg(u,e,i),this._previousSwap.drag=c.drag,this._previousSwap.delta=a?r.x:r.y}_startScrollingIfNecessary(t,e){if(this.autoScrollDisabled)return;let i,r=0,s=0;if(this._parentPositions.positions.forEach((o,a)=>{a===this._document||!o.clientRect||i||eS(o.clientRect,.05,t,e)&&([r,s]=function w$(n,t,e,i){const r=hS(t,i),s=pS(t,e);let o=0,a=0;if(r){const l=n.scrollTop;1===r?l>0&&(o=1):n.scrollHeight-l>n.clientHeight&&(o=2)}if(s){const l=n.scrollLeft;1===s?l>0&&(a=1):n.scrollWidth-l>n.clientWidth&&(a=2)}return[o,a]}(a,o.clientRect,t,e),(r||s)&&(i=a))}),!r&&!s){const{width:o,height:a}=this._viewportRuler.getViewportSize(),l={width:o,height:a,top:0,right:o,bottom:a,left:0};r=hS(l,e),s=pS(l,t),i=window}i&&(r!==this._verticalScrollDirection||s!==this._horizontalScrollDirection||i!==this._scrollNode)&&(this._verticalScrollDirection=r,this._horizontalScrollDirection=s,this._scrollNode=i,(r||s)&&i?this._ngZone.runOutsideAngular(this._startScrollInterval):this._stopScrolling())}_stopScrolling(){this._stopScrollTimers.next()}_draggingStarted(){const t=at(this.element).style;this.beforeStarted.next(),this._isDragging=!0,this._initialScrollSnap=t.msScrollSnapType||t.scrollSnapType||\"\",t.scrollSnapType=t.msScrollSnapType=\"none\",this._cacheItems(),this._viewportScrollSubscription.unsubscribe(),this._listenToScrollEvents()}_cacheParentPositions(){const t=at(this.element);this._parentPositions.cache(this._scrollableElements),this._clientRect=this._parentPositions.positions.get(t).clientRect}_cacheItemPositions(){const t=\"horizontal\"===this._orientation;this._itemPositions=this._activeDraggables.map(e=>{const i=e.getVisibleElement();return{drag:e,offset:0,initialTransform:i.style.transform||\"\",clientRect:xg(i)}}).sort((e,i)=>t?e.clientRect.left-i.clientRect.left:e.clientRect.top-i.clientRect.top)}_reset(){this._isDragging=!1;const t=at(this.element).style;t.scrollSnapType=t.msScrollSnapType=this._initialScrollSnap,this._activeDraggables.forEach(e=>{var i;const r=e.getRootElement();if(r){const s=null===(i=this._itemPositions.find(o=>o.drag===e))||void 0===i?void 0:i.initialTransform;r.style.transform=s||\"\"}}),this._siblings.forEach(e=>e._stopReceiving(this)),this._activeDraggables=[],this._itemPositions=[],this._previousSwap.drag=null,this._previousSwap.delta=0,this._previousSwap.overlaps=!1,this._stopScrolling(),this._viewportScrollSubscription.unsubscribe(),this._parentPositions.clear()}_getSiblingOffsetPx(t,e,i){const r=\"horizontal\"===this._orientation,s=e[t].clientRect,o=e[t+-1*i];let a=s[r?\"width\":\"height\"]*i;if(o){const l=r?\"left\":\"top\",c=r?\"right\":\"bottom\";-1===i?a-=o.clientRect[l]-s[c]:a+=s[l]-o.clientRect[c]}return a}_getItemOffsetPx(t,e,i){const r=\"horizontal\"===this._orientation;let s=r?e.left-t.left:e.top-t.top;return-1===i&&(s+=r?e.width-t.width:e.height-t.height),s}_shouldEnterAsFirstChild(t,e){if(!this._activeDraggables.length)return!1;const i=this._itemPositions,r=\"horizontal\"===this._orientation;if(i[0].drag!==this._activeDraggables[0]){const o=i[i.length-1].clientRect;return r?t>=o.right:e>=o.bottom}{const o=i[0].clientRect;return r?t<=o.left:e<=o.top}}_getItemIndexFromPointerPosition(t,e,i,r){const s=\"horizontal\"===this._orientation,o=this._itemPositions.findIndex(({drag:a,clientRect:l})=>{if(a===t)return!1;if(r){const c=s?r.x:r.y;if(a===this._previousSwap.drag&&this._previousSwap.overlaps&&c===this._previousSwap.delta)return!1}return s?e>=Math.floor(l.left)&&e<Math.floor(l.right):i>=Math.floor(l.top)&&i<Math.floor(l.bottom)});return-1!==o&&this.sortPredicate(o,t,this)?o:-1}_cacheItems(){this._activeDraggables=this._draggables.slice(),this._cacheItemPositions(),this._cacheParentPositions()}_isOverContainer(t,e){return null!=this._clientRect&&Eg(this._clientRect,t,e)}_getSiblingContainerFromPosition(t,e,i){return this._siblings.find(r=>r._canReceive(t,e,i))}_canReceive(t,e,i){if(!this._clientRect||!Eg(this._clientRect,e,i)||!this.enterPredicate(t,this))return!1;const r=this._getShadowRoot().elementFromPoint(e,i);if(!r)return!1;const s=at(this.element);return r===s||s.contains(r)}_startReceiving(t,e){const i=this._activeSiblings;!i.has(t)&&e.every(r=>this.enterPredicate(r,this)||this._draggables.indexOf(r)>-1)&&(i.add(t),this._cacheParentPositions(),this._listenToScrollEvents())}_stopReceiving(t){this._activeSiblings.delete(t),this._viewportScrollSubscription.unsubscribe()}_listenToScrollEvents(){this._viewportScrollSubscription=this._dragDropRegistry.scrolled(this._getShadowRoot()).subscribe(t=>{if(this.isDragging()){const e=this._parentPositions.handleScroll(t);e&&(this._itemPositions.forEach(({clientRect:i})=>{sl(i,e.top,e.left)}),this._itemPositions.forEach(({drag:i})=>{this._dragDropRegistry.isDragging(i)&&i._sortFromLastPointerPosition()}))}else this.isReceiving()&&this._cacheParentPositions()})}_getShadowRoot(){if(!this._cachedShadowRoot){const t=Fd(at(this.element));this._cachedShadowRoot=t||this._document}return this._cachedShadowRoot}_notifyReceivingSiblings(){const t=this._activeDraggables.filter(e=>e.isDragging());this._siblings.forEach(e=>e._startReceiving(this,t))}}function hS(n,t){const{top:e,bottom:i,height:r}=n,s=.05*r;return t>=e-s&&t<=e+s?1:t>=i-s&&t<=i+s?2:0}function pS(n,t){const{left:e,right:i,width:r}=n,s=.05*r;return t>=e-s&&t<=e+s?1:t>=i-s&&t<=i+s?2:0}const Zd=ei({passive:!1,capture:!0});let M$=(()=>{class n{constructor(e,i){this._ngZone=e,this._dropInstances=new Set,this._dragInstances=new Set,this._activeDragInstances=[],this._globalListeners=new Map,this._draggingPredicate=r=>r.isDragging(),this.pointerMove=new O,this.pointerUp=new O,this.scroll=new O,this._preventDefaultWhileDragging=r=>{this._activeDragInstances.length>0&&r.preventDefault()},this._persistentTouchmoveListener=r=>{this._activeDragInstances.length>0&&(this._activeDragInstances.some(this._draggingPredicate)&&r.preventDefault(),this.pointerMove.next(r))},this._document=i}registerDropContainer(e){this._dropInstances.has(e)||this._dropInstances.add(e)}registerDragItem(e){this._dragInstances.add(e),1===this._dragInstances.size&&this._ngZone.runOutsideAngular(()=>{this._document.addEventListener(\"touchmove\",this._persistentTouchmoveListener,Zd)})}removeDropContainer(e){this._dropInstances.delete(e)}removeDragItem(e){this._dragInstances.delete(e),this.stopDragging(e),0===this._dragInstances.size&&this._document.removeEventListener(\"touchmove\",this._persistentTouchmoveListener,Zd)}startDragging(e,i){if(!(this._activeDragInstances.indexOf(e)>-1)&&(this._activeDragInstances.push(e),1===this._activeDragInstances.length)){const r=i.type.startsWith(\"touch\");this._globalListeners.set(r?\"touchend\":\"mouseup\",{handler:s=>this.pointerUp.next(s),options:!0}).set(\"scroll\",{handler:s=>this.scroll.next(s),options:!0}).set(\"selectstart\",{handler:this._preventDefaultWhileDragging,options:Zd}),r||this._globalListeners.set(\"mousemove\",{handler:s=>this.pointerMove.next(s),options:Zd}),this._ngZone.runOutsideAngular(()=>{this._globalListeners.forEach((s,o)=>{this._document.addEventListener(o,s.handler,s.options)})})}}stopDragging(e){const i=this._activeDragInstances.indexOf(e);i>-1&&(this._activeDragInstances.splice(i,1),0===this._activeDragInstances.length&&this._clearGlobalListeners())}isDragging(e){return this._activeDragInstances.indexOf(e)>-1}scrolled(e){const i=[this.scroll];return e&&e!==this._document&&i.push(new Ve(r=>this._ngZone.runOutsideAngular(()=>{const o=a=>{this._activeDragInstances.length&&r.next(a)};return e.addEventListener(\"scroll\",o,!0),()=>{e.removeEventListener(\"scroll\",o,!0)}}))),Bt(...i)}ngOnDestroy(){this._dragInstances.forEach(e=>this.removeDragItem(e)),this._dropInstances.forEach(e=>this.removeDropContainer(e)),this._clearGlobalListeners(),this.pointerMove.complete(),this.pointerUp.complete()}_clearGlobalListeners(){this._globalListeners.forEach((e,i)=>{this._document.removeEventListener(i,e.handler,e.options)}),this._globalListeners.clear()}}return n.\\u0275fac=function(e){return new(e||n)(y(ne),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const x$={dragStartThreshold:5,pointerDirectionChangeThreshold:5};let E$=(()=>{class n{constructor(e,i,r,s){this._document=e,this._ngZone=i,this._viewportRuler=r,this._dragDropRegistry=s}createDrag(e,i=x$){return new b$(e,i,this._document,this._ngZone,this._viewportRuler,this._dragDropRegistry)}createDropList(e){return new D$(e,this._dragDropRegistry,this._document,this._ngZone,this._viewportRuler)}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(ne),y(es),y(M$))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),S$=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[E$],imports:[Ci]}),n})(),fS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[lo]]}),n})(),bS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Ud]]}),n})(),CS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const Z$={provide:new b(\"mat-autocomplete-scroll-strategy\"),deps:[ni],useFactory:function K$(n){return()=>n.scrollStrategies.reposition()}};let t8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[Z$],imports:[[ji,Hd,B,bt],Ci,Hd,B]}),n})(),n8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Qa,B],B]}),n})(),r8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ji,B,Hi],B]}),n})(),ul=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ti,B],B]}),n})(),u8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B,ti],B]}),n})(),h8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),AS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),M8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ti,B,Ya,AS],B,AS]}),n})();const PS=new b(\"mat-chips-default-options\");let L8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[mo,{provide:PS,useValue:{separatorKeyCodes:[13]}}],imports:[[B]]}),n})(),WS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),Wg=(()=>{class n{constructor(){this.changes=new O,this.optionalLabel=\"Optional\",this.completedLabel=\"Completed\",this.editableLabel=\"Editable\"}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const d4={provide:Wg,deps:[[new Tt,new Cn,Wg]],useFactory:function c4(n){return n||new Wg}};let u4=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[d4,mo],imports:[[B,bt,Hi,ul,fS,WS,ti],B]}),n})(),C4=(()=>{class n{constructor(){this.changes=new O,this.calendarLabel=\"Calendar\",this.openCalendarLabel=\"Open calendar\",this.closeCalendarLabel=\"Close calendar\",this.prevMonthLabel=\"Previous month\",this.nextMonthLabel=\"Next month\",this.prevYearLabel=\"Previous year\",this.nextYearLabel=\"Next year\",this.prevMultiYearLabel=\"Previous 24 years\",this.nextMultiYearLabel=\"Next 24 years\",this.switchToMonthViewLabel=\"Choose date\",this.switchToMultiYearViewLabel=\"Choose month and year\"}formatYearRange(e,i){return`${e} \\u2013 ${i}`}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const M4={provide:new b(\"mat-datepicker-scroll-strategy\"),deps:[ni],useFactory:function w4(n){return()=>n.scrollStrategies.reposition()}};let T4=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[C4,M4],imports:[[bt,ul,ji,Qa,Hi,B],Ci]}),n})();function A4(n,t){}class qg{constructor(){this.role=\"dialog\",this.panelClass=\"\",this.hasBackdrop=!0,this.backdropClass=\"\",this.disableClose=!1,this.width=\"\",this.height=\"\",this.maxWidth=\"80vw\",this.data=null,this.ariaDescribedBy=null,this.ariaLabelledBy=null,this.ariaLabel=null,this.autoFocus=\"first-tabbable\",this.restoreFocus=!0,this.delayFocusTrap=!0,this.closeOnNavigation=!0}}const I4={dialogContainer:Ke(\"dialogContainer\",[ae(\"void, exit\",R({opacity:0,transform:\"scale(0.7)\"})),ae(\"enter\",R({transform:\"none\"})),ge(\"* => enter\",nd([be(\"150ms cubic-bezier(0, 0, 0.2, 1)\",R({transform:\"none\",opacity:1})),no(\"@*\",to(),{optional:!0})])),ge(\"* => void, * => exit\",nd([be(\"75ms cubic-bezier(0.4, 0.0, 0.2, 1)\",R({opacity:0})),no(\"@*\",to(),{optional:!0})]))])};let R4=(()=>{class n extends bg{constructor(e,i,r,s,o,a,l,c){super(),this._elementRef=e,this._focusTrapFactory=i,this._changeDetectorRef=r,this._config=o,this._interactivityChecker=a,this._ngZone=l,this._focusMonitor=c,this._animationStateChanged=new $,this._elementFocusedBeforeDialogWasOpened=null,this._closeInteractionType=null,this.attachDomPortal=d=>(this._portalOutlet.hasAttached(),this._portalOutlet.attachDomPortal(d)),this._ariaLabelledBy=o.ariaLabelledBy||null,this._document=s}_initializeWithAttachedContent(){this._focusTrap=this._focusTrapFactory.create(this._elementRef.nativeElement),this._document&&(this._elementFocusedBeforeDialogWasOpened=Hm())}attachComponentPortal(e){return this._portalOutlet.hasAttached(),this._portalOutlet.attachComponentPortal(e)}attachTemplatePortal(e){return this._portalOutlet.hasAttached(),this._portalOutlet.attachTemplatePortal(e)}_recaptureFocus(){this._containsFocus()||this._trapFocus()}_forceFocus(e,i){this._interactivityChecker.isFocusable(e)||(e.tabIndex=-1,this._ngZone.runOutsideAngular(()=>{e.addEventListener(\"blur\",()=>e.removeAttribute(\"tabindex\")),e.addEventListener(\"mousedown\",()=>e.removeAttribute(\"tabindex\"))})),e.focus(i)}_focusByCssSelector(e,i){let r=this._elementRef.nativeElement.querySelector(e);r&&this._forceFocus(r,i)}_trapFocus(){const e=this._elementRef.nativeElement;switch(this._config.autoFocus){case!1:case\"dialog\":this._containsFocus()||e.focus();break;case!0:case\"first-tabbable\":this._focusTrap.focusInitialElementWhenReady().then(i=>{i||this._focusDialogContainer()});break;case\"first-heading\":this._focusByCssSelector('h1, h2, h3, h4, h5, h6, [role=\"heading\"]');break;default:this._focusByCssSelector(this._config.autoFocus)}}_restoreFocus(){const e=this._elementFocusedBeforeDialogWasOpened;if(this._config.restoreFocus&&e&&\"function\"==typeof e.focus){const i=Hm(),r=this._elementRef.nativeElement;(!i||i===this._document.body||i===r||r.contains(i))&&(this._focusMonitor?(this._focusMonitor.focusVia(e,this._closeInteractionType),this._closeInteractionType=null):e.focus())}this._focusTrap&&this._focusTrap.destroy()}_focusDialogContainer(){this._elementRef.nativeElement.focus&&this._elementRef.nativeElement.focus()}_containsFocus(){const e=this._elementRef.nativeElement,i=Hm();return e===i||e.contains(i)}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(C3),f(Ye),f(ie,8),f(qg),f(Xx),f(ne),f(Qr))},n.\\u0275dir=C({type:n,viewQuery:function(e,i){if(1&e&&je(TE,7),2&e){let r;z(r=U())&&(i._portalOutlet=r.first)}},features:[E]}),n})(),O4=(()=>{class n extends R4{constructor(){super(...arguments),this._state=\"enter\"}_onAnimationDone({toState:e,totalTime:i}){\"enter\"===e?(this._config.delayFocusTrap&&this._trapFocus(),this._animationStateChanged.next({state:\"opened\",totalTime:i})):\"exit\"===e&&(this._restoreFocus(),this._animationStateChanged.next({state:\"closed\",totalTime:i}))}_onAnimationStart({toState:e,totalTime:i}){\"enter\"===e?this._animationStateChanged.next({state:\"opening\",totalTime:i}):(\"exit\"===e||\"void\"===e)&&this._animationStateChanged.next({state:\"closing\",totalTime:i})}_startExitAnimation(){this._state=\"exit\",this._changeDetectorRef.markForCheck()}_initializeWithAttachedContent(){super._initializeWithAttachedContent(),this._config.delayFocusTrap||this._trapFocus()}}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275cmp=xe({type:n,selectors:[[\"mat-dialog-container\"]],hostAttrs:[\"tabindex\",\"-1\",\"aria-modal\",\"true\",1,\"mat-dialog-container\"],hostVars:6,hostBindings:function(e,i){1&e&&hp(\"@dialogContainer.start\",function(s){return i._onAnimationStart(s)})(\"@dialogContainer.done\",function(s){return i._onAnimationDone(s)}),2&e&&(Yn(\"id\",i._id),Z(\"role\",i._config.role)(\"aria-labelledby\",i._config.ariaLabel?null:i._ariaLabelledBy)(\"aria-label\",i._config.ariaLabel)(\"aria-describedby\",i._config.ariaDescribedBy||null),gp(\"@dialogContainer\",i._state))},features:[E],decls:1,vars:0,consts:[[\"cdkPortalOutlet\",\"\"]],template:function(e,i){1&e&&Ee(0,A4,0,0,\"ng-template\",0)},directives:[TE],styles:[\".mat-dialog-container{display:block;padding:24px;border-radius:4px;box-sizing:border-box;overflow:auto;outline:0;width:100%;height:100%;min-height:inherit;max-height:inherit}.cdk-high-contrast-active .mat-dialog-container{outline:solid 1px}.mat-dialog-content{display:block;margin:0 -24px;padding:0 24px;max-height:65vh;overflow:auto;-webkit-overflow-scrolling:touch}.mat-dialog-title{margin:0 0 20px;display:block}.mat-dialog-actions{padding:8px 0;display:flex;flex-wrap:wrap;min-height:52px;align-items:center;box-sizing:content-box;margin-bottom:-24px}.mat-dialog-actions[align=end]{justify-content:flex-end}.mat-dialog-actions[align=center]{justify-content:center}.mat-dialog-actions .mat-button-base+.mat-button-base,.mat-dialog-actions .mat-mdc-button-base+.mat-mdc-button-base{margin-left:8px}[dir=rtl] .mat-dialog-actions .mat-button-base+.mat-button-base,[dir=rtl] .mat-dialog-actions .mat-mdc-button-base+.mat-mdc-button-base{margin-left:0;margin-right:8px}\\n\"],encapsulation:2,data:{animation:[I4.dialogContainer]}}),n})(),P4=0;class F4{constructor(t,e,i=\"mat-dialog-\"+P4++){this._overlayRef=t,this._containerInstance=e,this.id=i,this.disableClose=this._containerInstance._config.disableClose,this._afterOpened=new O,this._afterClosed=new O,this._beforeClosed=new O,this._state=0,e._id=i,e._animationStateChanged.pipe(Ct(r=>\"opened\"===r.state),it(1)).subscribe(()=>{this._afterOpened.next(),this._afterOpened.complete()}),e._animationStateChanged.pipe(Ct(r=>\"closed\"===r.state),it(1)).subscribe(()=>{clearTimeout(this._closeFallbackTimeout),this._finishDialogClose()}),t.detachments().subscribe(()=>{this._beforeClosed.next(this._result),this._beforeClosed.complete(),this._afterClosed.next(this._result),this._afterClosed.complete(),this.componentInstance=null,this._overlayRef.dispose()}),t.keydownEvents().pipe(Ct(r=>27===r.keyCode&&!this.disableClose&&!Xt(r))).subscribe(r=>{r.preventDefault(),ZS(this,\"keyboard\")}),t.backdropClick().subscribe(()=>{this.disableClose?this._containerInstance._recaptureFocus():ZS(this,\"mouse\")})}close(t){this._result=t,this._containerInstance._animationStateChanged.pipe(Ct(e=>\"closing\"===e.state),it(1)).subscribe(e=>{this._beforeClosed.next(t),this._beforeClosed.complete(),this._overlayRef.detachBackdrop(),this._closeFallbackTimeout=setTimeout(()=>this._finishDialogClose(),e.totalTime+100)}),this._state=1,this._containerInstance._startExitAnimation()}afterOpened(){return this._afterOpened}afterClosed(){return this._afterClosed}beforeClosed(){return this._beforeClosed}backdropClick(){return this._overlayRef.backdropClick()}keydownEvents(){return this._overlayRef.keydownEvents()}updatePosition(t){let e=this._getPositionStrategy();return t&&(t.left||t.right)?t.left?e.left(t.left):e.right(t.right):e.centerHorizontally(),t&&(t.top||t.bottom)?t.top?e.top(t.top):e.bottom(t.bottom):e.centerVertically(),this._overlayRef.updatePosition(),this}updateSize(t=\"\",e=\"\"){return this._overlayRef.updateSize({width:t,height:e}),this._overlayRef.updatePosition(),this}addPanelClass(t){return this._overlayRef.addPanelClass(t),this}removePanelClass(t){return this._overlayRef.removePanelClass(t),this}getState(){return this._state}_finishDialogClose(){this._state=2,this._overlayRef.dispose()}_getPositionStrategy(){return this._overlayRef.getConfig().positionStrategy}}function ZS(n,t,e){return void 0!==n._containerInstance&&(n._containerInstance._closeInteractionType=t),n.close(e)}const N4=new b(\"MatDialogData\"),L4=new b(\"mat-dialog-default-options\"),XS=new b(\"mat-dialog-scroll-strategy\"),V4={provide:XS,deps:[ni],useFactory:function B4(n){return()=>n.scrollStrategies.block()}};let H4=(()=>{class n{constructor(e,i,r,s,o,a,l,c,d,u){this._overlay=e,this._injector=i,this._defaultOptions=r,this._parentDialog=s,this._overlayContainer=o,this._dialogRefConstructor=l,this._dialogContainerType=c,this._dialogDataToken=d,this._openDialogsAtThisLevel=[],this._afterAllClosedAtThisLevel=new O,this._afterOpenedAtThisLevel=new O,this._ariaHiddenElements=new Map,this.afterAllClosed=xa(()=>this.openDialogs.length?this._getAfterAllClosed():this._getAfterAllClosed().pipe(Xn(void 0))),this._scrollStrategy=a}get openDialogs(){return this._parentDialog?this._parentDialog.openDialogs:this._openDialogsAtThisLevel}get afterOpened(){return this._parentDialog?this._parentDialog.afterOpened:this._afterOpenedAtThisLevel}_getAfterAllClosed(){const e=this._parentDialog;return e?e._getAfterAllClosed():this._afterAllClosedAtThisLevel}open(e,i){i=function z4(n,t){return Object.assign(Object.assign({},t),n)}(i,this._defaultOptions||new qg),i.id&&this.getDialogById(i.id);const r=this._createOverlay(i),s=this._attachDialogContainer(r,i),o=this._attachDialogContent(e,s,r,i);return this.openDialogs.length||this._hideNonDialogContentFromAssistiveTechnology(),this.openDialogs.push(o),o.afterClosed().subscribe(()=>this._removeOpenDialog(o)),this.afterOpened.next(o),s._initializeWithAttachedContent(),o}closeAll(){this._closeDialogs(this.openDialogs)}getDialogById(e){return this.openDialogs.find(i=>i.id===e)}ngOnDestroy(){this._closeDialogs(this._openDialogsAtThisLevel),this._afterAllClosedAtThisLevel.complete(),this._afterOpenedAtThisLevel.complete()}_createOverlay(e){const i=this._getOverlayConfig(e);return this._overlay.create(i)}_getOverlayConfig(e){const i=new Gd({positionStrategy:this._overlay.position().global(),scrollStrategy:e.scrollStrategy||this._scrollStrategy(),panelClass:e.panelClass,hasBackdrop:e.hasBackdrop,direction:e.direction,minWidth:e.minWidth,minHeight:e.minHeight,maxWidth:e.maxWidth,maxHeight:e.maxHeight,disposeOnNavigation:e.closeOnNavigation});return e.backdropClass&&(i.backdropClass=e.backdropClass),i}_attachDialogContainer(e,i){const s=dt.create({parent:i&&i.viewContainerRef&&i.viewContainerRef.injector||this._injector,providers:[{provide:qg,useValue:i}]}),o=new yg(this._dialogContainerType,i.viewContainerRef,s,i.componentFactoryResolver);return e.attach(o).instance}_attachDialogContent(e,i,r,s){const o=new this._dialogRefConstructor(r,i,s.id);if(e instanceof ut)i.attachTemplatePortal(new $d(e,null,{$implicit:s.data,dialogRef:o}));else{const a=this._createInjector(s,o,i),l=i.attachComponentPortal(new yg(e,s.viewContainerRef,a,s.componentFactoryResolver));o.componentInstance=l.instance}return o.updateSize(s.width,s.height).updatePosition(s.position),o}_createInjector(e,i,r){const s=e&&e.viewContainerRef&&e.viewContainerRef.injector,o=[{provide:this._dialogContainerType,useValue:r},{provide:this._dialogDataToken,useValue:e.data},{provide:this._dialogRefConstructor,useValue:i}];return e.direction&&(!s||!s.get(On,null,ee.Optional))&&o.push({provide:On,useValue:{value:e.direction,change:q()}}),dt.create({parent:s||this._injector,providers:o})}_removeOpenDialog(e){const i=this.openDialogs.indexOf(e);i>-1&&(this.openDialogs.splice(i,1),this.openDialogs.length||(this._ariaHiddenElements.forEach((r,s)=>{r?s.setAttribute(\"aria-hidden\",r):s.removeAttribute(\"aria-hidden\")}),this._ariaHiddenElements.clear(),this._getAfterAllClosed().next()))}_hideNonDialogContentFromAssistiveTechnology(){const e=this._overlayContainer.getContainerElement();if(e.parentElement){const i=e.parentElement.children;for(let r=i.length-1;r>-1;r--){let s=i[r];s!==e&&\"SCRIPT\"!==s.nodeName&&\"STYLE\"!==s.nodeName&&!s.hasAttribute(\"aria-live\")&&(this._ariaHiddenElements.set(s,s.getAttribute(\"aria-hidden\")),s.setAttribute(\"aria-hidden\",\"true\"))}}}_closeDialogs(e){let i=e.length;for(;i--;)e[i].close()}}return n.\\u0275fac=function(e){Sr()},n.\\u0275dir=C({type:n}),n})(),j4=(()=>{class n extends H4{constructor(e,i,r,s,o,a,l,c){super(e,i,s,a,l,o,F4,O4,N4,c)}}return n.\\u0275fac=function(e){return new(e||n)(y(ni),y(dt),y(va,8),y(L4,8),y(XS),y(n,12),y(Dg),y(Rn,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),U4=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[j4,V4],imports:[[ji,Hi,B],B]}),n})(),JS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),$4=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B,ZE,Hi]]}),n})(),rG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Vd,ti,B,og,bt],Vd,B,og,JS]}),n})();const lG={provide:new b(\"mat-menu-scroll-strategy\"),deps:[ni],useFactory:function aG(n){return()=>n.scrollStrategies.reposition()}};let cG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[lG],imports:[[bt,B,ti,ji],Ci,B]}),n})();const pG={provide:new b(\"mat-tooltip-scroll-strategy\"),deps:[ni],useFactory:function hG(n){return()=>n.scrollStrategies.reposition({scrollThrottle:20})}};let ik=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[pG],imports:[[Qa,bt,ji,B],B,Ci]}),n})(),Yg=(()=>{class n{constructor(){this.changes=new O,this.itemsPerPageLabel=\"Items per page:\",this.nextPageLabel=\"Next page\",this.previousPageLabel=\"Previous page\",this.firstPageLabel=\"First page\",this.lastPageLabel=\"Last page\",this.getRangeLabel=(e,i,r)=>{if(0==r||0==i)return`0 of ${r}`;const s=e*i;return`${s+1} \\u2013 ${s<(r=Math.max(r,0))?Math.min(s+i,r):s+i} of ${r}`}}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const yG={provide:Yg,deps:[[new Tt,new Cn,Yg]],useFactory:function vG(n){return n||new Yg}};let bG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[yG],imports:[[bt,ul,qE,ik,B]]}),n})(),DG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B],B]}),n})();function wG(n,t){if(1&n&&(Oo(),Le(0,\"circle\",4)),2&n){const e=Be(),i=wn(1);$n(\"animation-name\",\"mat-progress-spinner-stroke-rotate-\"+e._spinnerAnimationLabel)(\"stroke-dashoffset\",e._getStrokeDashOffset(),\"px\")(\"stroke-dasharray\",e._getStrokeCircumference(),\"px\")(\"stroke-width\",e._getCircleStrokeWidth(),\"%\")(\"transform-origin\",e._getCircleTransformOrigin(i)),Z(\"r\",e._getCircleRadius())}}function MG(n,t){if(1&n&&(Oo(),Le(0,\"circle\",4)),2&n){const e=Be(),i=wn(1);$n(\"stroke-dashoffset\",e._getStrokeDashOffset(),\"px\")(\"stroke-dasharray\",e._getStrokeCircumference(),\"px\")(\"stroke-width\",e._getCircleStrokeWidth(),\"%\")(\"transform-origin\",e._getCircleTransformOrigin(i)),Z(\"r\",e._getCircleRadius())}}const EG=fo(class{constructor(n){this._elementRef=n}},\"primary\"),SG=new b(\"mat-progress-spinner-default-options\",{providedIn:\"root\",factory:function kG(){return{diameter:100}}});class dr extends EG{constructor(t,e,i,r,s,o,a,l){super(t),this._document=i,this._diameter=100,this._value=0,this._resizeSubscription=ke.EMPTY,this.mode=\"determinate\";const c=dr._diameters;this._spinnerAnimationLabel=this._getSpinnerAnimationLabel(),c.has(i.head)||c.set(i.head,new Set([100])),this._noopAnimations=\"NoopAnimations\"===r&&!!s&&!s._forceAnimations,\"mat-spinner\"===t.nativeElement.nodeName.toLowerCase()&&(this.mode=\"indeterminate\"),s&&(s.diameter&&(this.diameter=s.diameter),s.strokeWidth&&(this.strokeWidth=s.strokeWidth)),e.isBrowser&&e.SAFARI&&a&&o&&l&&(this._resizeSubscription=a.change(150).subscribe(()=>{\"indeterminate\"===this.mode&&l.run(()=>o.markForCheck())}))}get diameter(){return this._diameter}set diameter(t){this._diameter=Et(t),this._spinnerAnimationLabel=this._getSpinnerAnimationLabel(),this._styleRoot&&this._attachStyleNode()}get strokeWidth(){return this._strokeWidth||this.diameter/10}set strokeWidth(t){this._strokeWidth=Et(t)}get value(){return\"determinate\"===this.mode?this._value:0}set value(t){this._value=Math.max(0,Math.min(100,Et(t)))}ngOnInit(){const t=this._elementRef.nativeElement;this._styleRoot=Fd(t)||this._document.head,this._attachStyleNode(),t.classList.add(\"mat-progress-spinner-indeterminate-animation\")}ngOnDestroy(){this._resizeSubscription.unsubscribe()}_getCircleRadius(){return(this.diameter-10)/2}_getViewBox(){const t=2*this._getCircleRadius()+this.strokeWidth;return`0 0 ${t} ${t}`}_getStrokeCircumference(){return 2*Math.PI*this._getCircleRadius()}_getStrokeDashOffset(){return\"determinate\"===this.mode?this._getStrokeCircumference()*(100-this._value)/100:null}_getCircleStrokeWidth(){return this.strokeWidth/this.diameter*100}_getCircleTransformOrigin(t){var e;const i=50*(null!==(e=t.currentScale)&&void 0!==e?e:1);return`${i}% ${i}%`}_attachStyleNode(){const t=this._styleRoot,e=this._diameter,i=dr._diameters;let r=i.get(t);if(!r||!r.has(e)){const s=this._document.createElement(\"style\");s.setAttribute(\"mat-spinner-animation\",this._spinnerAnimationLabel),s.textContent=this._getAnimationText(),t.appendChild(s),r||(r=new Set,i.set(t,r)),r.add(e)}}_getAnimationText(){const t=this._getStrokeCircumference();return\"\\n @keyframes mat-progress-spinner-stroke-rotate-DIAMETER {\\n 0% { stroke-dashoffset: START_VALUE; transform: rotate(0); }\\n 12.5% { stroke-dashoffset: END_VALUE; transform: rotate(0); }\\n 12.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(72.5deg); }\\n 25% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(72.5deg); }\\n\\n 25.0001% { stroke-dashoffset: START_VALUE; transform: rotate(270deg); }\\n 37.5% { stroke-dashoffset: END_VALUE; transform: rotate(270deg); }\\n 37.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(161.5deg); }\\n 50% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(161.5deg); }\\n\\n 50.0001% { stroke-dashoffset: START_VALUE; transform: rotate(180deg); }\\n 62.5% { stroke-dashoffset: END_VALUE; transform: rotate(180deg); }\\n 62.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(251.5deg); }\\n 75% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(251.5deg); }\\n\\n 75.0001% { stroke-dashoffset: START_VALUE; transform: rotate(90deg); }\\n 87.5% { stroke-dashoffset: END_VALUE; transform: rotate(90deg); }\\n 87.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(341.5deg); }\\n 100% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(341.5deg); }\\n }\\n\".replace(/START_VALUE/g,\"\"+.95*t).replace(/END_VALUE/g,\"\"+.2*t).replace(/DIAMETER/g,`${this._spinnerAnimationLabel}`)}_getSpinnerAnimationLabel(){return this.diameter.toString().replace(\".\",\"_\")}}dr._diameters=new WeakMap,dr.\\u0275fac=function(t){return new(t||dr)(f(W),f(It),f(ie,8),f(Rn,8),f(SG),f(Ye),f(es),f(ne))},dr.\\u0275cmp=xe({type:dr,selectors:[[\"mat-progress-spinner\"],[\"mat-spinner\"]],hostAttrs:[\"role\",\"progressbar\",\"tabindex\",\"-1\",1,\"mat-progress-spinner\",\"mat-spinner\"],hostVars:10,hostBindings:function(t,e){2&t&&(Z(\"aria-valuemin\",\"determinate\"===e.mode?0:null)(\"aria-valuemax\",\"determinate\"===e.mode?100:null)(\"aria-valuenow\",\"determinate\"===e.mode?e.value:null)(\"mode\",e.mode),$n(\"width\",e.diameter,\"px\")(\"height\",e.diameter,\"px\"),Ae(\"_mat-animation-noopable\",e._noopAnimations))},inputs:{color:\"color\",diameter:\"diameter\",strokeWidth:\"strokeWidth\",mode:\"mode\",value:\"value\"},exportAs:[\"matProgressSpinner\"],features:[E],decls:4,vars:8,consts:[[\"preserveAspectRatio\",\"xMidYMid meet\",\"focusable\",\"false\",\"aria-hidden\",\"true\",3,\"ngSwitch\"],[\"svg\",\"\"],[\"cx\",\"50%\",\"cy\",\"50%\",3,\"animation-name\",\"stroke-dashoffset\",\"stroke-dasharray\",\"stroke-width\",\"transform-origin\",4,\"ngSwitchCase\"],[\"cx\",\"50%\",\"cy\",\"50%\",3,\"stroke-dashoffset\",\"stroke-dasharray\",\"stroke-width\",\"transform-origin\",4,\"ngSwitchCase\"],[\"cx\",\"50%\",\"cy\",\"50%\"]],template:function(t,e){1&t&&(Oo(),x(0,\"svg\",0,1),Ee(2,wG,1,11,\"circle\",2),Ee(3,MG,1,9,\"circle\",3),S()),2&t&&($n(\"width\",e.diameter,\"px\")(\"height\",e.diameter,\"px\"),N(\"ngSwitch\",\"indeterminate\"===e.mode),Z(\"viewBox\",e._getViewBox()),T(2),N(\"ngSwitchCase\",!0),T(1),N(\"ngSwitchCase\",!1))},directives:[Ys,Pc],styles:[\".mat-progress-spinner{display:block;position:relative;overflow:hidden}.mat-progress-spinner svg{position:absolute;transform:rotate(-90deg);top:0;left:0;transform-origin:center;overflow:visible}.mat-progress-spinner circle{fill:transparent;transition:stroke-dashoffset 225ms linear}._mat-animation-noopable.mat-progress-spinner circle{transition:none;animation:none}.cdk-high-contrast-active .mat-progress-spinner circle{stroke:CanvasText}.mat-progress-spinner.mat-progress-spinner-indeterminate-animation[mode=indeterminate] svg{animation:mat-progress-spinner-linear-rotate 2000ms linear infinite}._mat-animation-noopable.mat-progress-spinner.mat-progress-spinner-indeterminate-animation[mode=indeterminate] svg{transition:none;animation:none}.mat-progress-spinner.mat-progress-spinner-indeterminate-animation[mode=indeterminate] circle{transition-property:stroke;animation-duration:4000ms;animation-timing-function:cubic-bezier(0.35, 0, 0.25, 1);animation-iteration-count:infinite}._mat-animation-noopable.mat-progress-spinner.mat-progress-spinner-indeterminate-animation[mode=indeterminate] circle{transition:none;animation:none}@keyframes mat-progress-spinner-linear-rotate{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@keyframes mat-progress-spinner-stroke-rotate-100{0%{stroke-dashoffset:268.606171575px;transform:rotate(0)}12.5%{stroke-dashoffset:56.5486677px;transform:rotate(0)}12.5001%{stroke-dashoffset:56.5486677px;transform:rotateX(180deg) rotate(72.5deg)}25%{stroke-dashoffset:268.606171575px;transform:rotateX(180deg) rotate(72.5deg)}25.0001%{stroke-dashoffset:268.606171575px;transform:rotate(270deg)}37.5%{stroke-dashoffset:56.5486677px;transform:rotate(270deg)}37.5001%{stroke-dashoffset:56.5486677px;transform:rotateX(180deg) rotate(161.5deg)}50%{stroke-dashoffset:268.606171575px;transform:rotateX(180deg) rotate(161.5deg)}50.0001%{stroke-dashoffset:268.606171575px;transform:rotate(180deg)}62.5%{stroke-dashoffset:56.5486677px;transform:rotate(180deg)}62.5001%{stroke-dashoffset:56.5486677px;transform:rotateX(180deg) rotate(251.5deg)}75%{stroke-dashoffset:268.606171575px;transform:rotateX(180deg) rotate(251.5deg)}75.0001%{stroke-dashoffset:268.606171575px;transform:rotate(90deg)}87.5%{stroke-dashoffset:56.5486677px;transform:rotate(90deg)}87.5001%{stroke-dashoffset:56.5486677px;transform:rotateX(180deg) rotate(341.5deg)}100%{stroke-dashoffset:268.606171575px;transform:rotateX(180deg) rotate(341.5deg)}}\\n\"],encapsulation:2,changeDetection:0});let AG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B,bt],B]}),n})(),UG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ti,B],B]}),n})(),GG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B,Ci],Ci,B]}),n})(),ak=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),sW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ak,ti,B,Ya],ak,B]}),n})(),lW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ji,Hi,bt,ul,B],B]}),n})(),Kg=(()=>{class n{constructor(){this.changes=new O}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const uW={provide:Kg,deps:[[new Tt,new Cn,Kg]],useFactory:function dW(n){return n||new Kg}};let hW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[uW],imports:[[bt,B]]}),n})(),TW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bS,B],B]}),n})(),FW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B,Hi,ti,Ya,Qa],B]}),n})(),NW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),$W=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[CS,B],B]}),n})(),GW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[Qa,ZE,m$,fS,bS,CS,S$,t8,n8,r8,ul,u8,h8,M8,L8,u4,T4,U4,JS,$4,CU,WS,a$,rG,cG,U3,bG,DG,AG,UG,ti,qE,GG,gE,sW,lW,hW,TW,FW,NW,ik,$W,ji,Hi,Ud]}),n})(),WW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n,bootstrap:[f$]}),n.\\u0275inj=P({providers:[],imports:[[FD,B2,Pz,Fz,Nj,gE,GW]]}),n})();(function YF(){G0=!1})(),console.info(\"Angular CDK version\",Lm.full),console.info(\"Angular Material version\",Jm.full),oB().bootstrapModule(WW).catch(n=>console.error(n))}},De=>{De(De.s=532)}]);", "file_path": "docs/main.e3e00859dfd66644.js", "rank": 19, "score": 96506.13743688195 }, { "content": "\"use strict\";(self.webpackChunkbridge=self.webpackChunkbridge||[]).push([[179],{532:()=>{function De(n){return\"function\"==typeof n}function xo(n){const e=n(i=>{Error.call(i),i.stack=(new Error).stack});return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}const fl=xo(n=>function(e){n(this),this.message=e?`${e.length} errors occurred during unsubscription:\\n${e.map((i,r)=>`${r+1}) ${i.toString()}`).join(\"\\n \")}`:\"\",this.name=\"UnsubscriptionError\",this.errors=e});function ss(n,t){if(n){const e=n.indexOf(t);0<=e&&n.splice(e,1)}}class ke{constructor(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}unsubscribe(){let t;if(!this.closed){this.closed=!0;const{_parentage:e}=this;if(e)if(this._parentage=null,Array.isArray(e))for(const s of e)s.remove(this);else e.remove(this);const{initialTeardown:i}=this;if(De(i))try{i()}catch(s){t=s instanceof fl?s.errors:[s]}const{_finalizers:r}=this;if(r){this._finalizers=null;for(const s of r)try{t_(s)}catch(o){t=null!=t?t:[],o instanceof fl?t=[...t,...o.errors]:t.push(o)}}if(t)throw new fl(t)}}add(t){var e;if(t&&t!==this)if(this.closed)t_(t);else{if(t instanceof ke){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(e=this._finalizers)&&void 0!==e?e:[]).push(t)}}_hasParent(t){const{_parentage:e}=this;return e===t||Array.isArray(e)&&e.includes(t)}_addParent(t){const{_parentage:e}=this;this._parentage=Array.isArray(e)?(e.push(t),e):e?[e,t]:t}_removeParent(t){const{_parentage:e}=this;e===t?this._parentage=null:Array.isArray(e)&&ss(e,t)}remove(t){const{_finalizers:e}=this;e&&ss(e,t),t instanceof ke&&t._removeParent(this)}}ke.EMPTY=(()=>{const n=new ke;return n.closed=!0,n})();const Jg=ke.EMPTY;function e_(n){return n instanceof ke||n&&\"closed\"in n&&De(n.remove)&&De(n.add)&&De(n.unsubscribe)}function t_(n){De(n)?n():n.unsubscribe()}const fr={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},ml={setTimeout(n,t,...e){const{delegate:i}=ml;return(null==i?void 0:i.setTimeout)?i.setTimeout(n,t,...e):setTimeout(n,t,...e)},clearTimeout(n){const{delegate:t}=ml;return((null==t?void 0:t.clearTimeout)||clearTimeout)(n)},delegate:void 0};function n_(n){ml.setTimeout(()=>{const{onUnhandledError:t}=fr;if(!t)throw n;t(n)})}function gl(){}const fk=fu(\"C\",void 0,void 0);function fu(n,t,e){return{kind:n,value:t,error:e}}let mr=null;function _l(n){if(fr.useDeprecatedSynchronousErrorHandling){const t=!mr;if(t&&(mr={errorThrown:!1,error:null}),n(),t){const{errorThrown:e,error:i}=mr;if(mr=null,e)throw i}}else n()}class mu extends ke{constructor(t){super(),this.isStopped=!1,t?(this.destination=t,e_(t)&&t.add(this)):this.destination=Ck}static create(t,e,i){return new vl(t,e,i)}next(t){this.isStopped?_u(function gk(n){return fu(\"N\",n,void 0)}(t),this):this._next(t)}error(t){this.isStopped?_u(function mk(n){return fu(\"E\",void 0,n)}(t),this):(this.isStopped=!0,this._error(t))}complete(){this.isStopped?_u(fk,this):(this.isStopped=!0,this._complete())}unsubscribe(){this.closed||(this.isStopped=!0,super.unsubscribe(),this.destination=null)}_next(t){this.destination.next(t)}_error(t){try{this.destination.error(t)}finally{this.unsubscribe()}}_complete(){try{this.destination.complete()}finally{this.unsubscribe()}}}const vk=Function.prototype.bind;function gu(n,t){return vk.call(n,t)}class yk{constructor(t){this.partialObserver=t}next(t){const{partialObserver:e}=this;if(e.next)try{e.next(t)}catch(i){yl(i)}}error(t){const{partialObserver:e}=this;if(e.error)try{e.error(t)}catch(i){yl(i)}else yl(t)}complete(){const{partialObserver:t}=this;if(t.complete)try{t.complete()}catch(e){yl(e)}}}class vl extends mu{constructor(t,e,i){let r;if(super(),De(t)||!t)r={next:null!=t?t:void 0,error:null!=e?e:void 0,complete:null!=i?i:void 0};else{let s;this&&fr.useDeprecatedNextContext?(s=Object.create(t),s.unsubscribe=()=>this.unsubscribe(),r={next:t.next&&gu(t.next,s),error:t.error&&gu(t.error,s),complete:t.complete&&gu(t.complete,s)}):r=t}this.destination=new yk(r)}}function yl(n){fr.useDeprecatedSynchronousErrorHandling?function _k(n){fr.useDeprecatedSynchronousErrorHandling&&mr&&(mr.errorThrown=!0,mr.error=n)}(n):n_(n)}function _u(n,t){const{onStoppedNotification:e}=fr;e&&ml.setTimeout(()=>e(n,t))}const Ck={closed:!0,next:gl,error:function bk(n){throw n},complete:gl},vu=\"function\"==typeof Symbol&&Symbol.observable||\"@@observable\";function Wi(n){return n}let Ve=(()=>{class n{constructor(e){e&&(this._subscribe=e)}lift(e){const i=new n;return i.source=this,i.operator=e,i}subscribe(e,i,r){const s=function wk(n){return n&&n instanceof mu||function Dk(n){return n&&De(n.next)&&De(n.error)&&De(n.complete)}(n)&&e_(n)}(e)?e:new vl(e,i,r);return _l(()=>{const{operator:o,source:a}=this;s.add(o?o.call(s,a):a?this._subscribe(s):this._trySubscribe(s))}),s}_trySubscribe(e){try{return this._subscribe(e)}catch(i){e.error(i)}}forEach(e,i){return new(i=r_(i))((r,s)=>{const o=new vl({next:a=>{try{e(a)}catch(l){s(l),o.unsubscribe()}},error:s,complete:r});this.subscribe(o)})}_subscribe(e){var i;return null===(i=this.source)||void 0===i?void 0:i.subscribe(e)}[vu](){return this}pipe(...e){return function i_(n){return 0===n.length?Wi:1===n.length?n[0]:function(e){return n.reduce((i,r)=>r(i),e)}}(e)(this)}toPromise(e){return new(e=r_(e))((i,r)=>{let s;this.subscribe(o=>s=o,o=>r(o),()=>i(s))})}}return n.create=t=>new n(t),n})();function r_(n){var t;return null!==(t=null!=n?n:fr.Promise)&&void 0!==t?t:Promise}const Mk=xo(n=>function(){n(this),this.name=\"ObjectUnsubscribedError\",this.message=\"object unsubscribed\"});let O=(()=>{class n extends Ve{constructor(){super(),this.closed=!1,this.currentObservers=null,this.observers=[],this.isStopped=!1,this.hasError=!1,this.thrownError=null}lift(e){const i=new s_(this,this);return i.operator=e,i}_throwIfClosed(){if(this.closed)throw new Mk}next(e){_l(()=>{if(this._throwIfClosed(),!this.isStopped){this.currentObservers||(this.currentObservers=Array.from(this.observers));for(const i of this.currentObservers)i.next(e)}})}error(e){_l(()=>{if(this._throwIfClosed(),!this.isStopped){this.hasError=this.isStopped=!0,this.thrownError=e;const{observers:i}=this;for(;i.length;)i.shift().error(e)}})}complete(){_l(()=>{if(this._throwIfClosed(),!this.isStopped){this.isStopped=!0;const{observers:e}=this;for(;e.length;)e.shift().complete()}})}unsubscribe(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null}get observed(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0}_trySubscribe(e){return this._throwIfClosed(),super._trySubscribe(e)}_subscribe(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)}_innerSubscribe(e){const{hasError:i,isStopped:r,observers:s}=this;return i||r?Jg:(this.currentObservers=null,s.push(e),new ke(()=>{this.currentObservers=null,ss(s,e)}))}_checkFinalizedStatuses(e){const{hasError:i,thrownError:r,isStopped:s}=this;i?e.error(r):s&&e.complete()}asObservable(){const e=new Ve;return e.source=this,e}}return n.create=(t,e)=>new s_(t,e),n})();class s_ extends O{constructor(t,e){super(),this.destination=t,this.source=e}next(t){var e,i;null===(i=null===(e=this.destination)||void 0===e?void 0:e.next)||void 0===i||i.call(e,t)}error(t){var e,i;null===(i=null===(e=this.destination)||void 0===e?void 0:e.error)||void 0===i||i.call(e,t)}complete(){var t,e;null===(e=null===(t=this.destination)||void 0===t?void 0:t.complete)||void 0===e||e.call(t)}_subscribe(t){var e,i;return null!==(i=null===(e=this.source)||void 0===e?void 0:e.subscribe(t))&&void 0!==i?i:Jg}}function o_(n){return De(null==n?void 0:n.lift)}function qe(n){return t=>{if(o_(t))return t.lift(function(e){try{return n(e,this)}catch(i){this.error(i)}});throw new TypeError(\"Unable to lift unknown Observable type\")}}function Ue(n,t,e,i,r){return new xk(n,t,e,i,r)}class xk extends mu{constructor(t,e,i,r,s,o){super(t),this.onFinalize=s,this.shouldUnsubscribe=o,this._next=e?function(a){try{e(a)}catch(l){t.error(l)}}:super._next,this._error=r?function(a){try{r(a)}catch(l){t.error(l)}finally{this.unsubscribe()}}:super._error,this._complete=i?function(){try{i()}catch(a){t.error(a)}finally{this.unsubscribe()}}:super._complete}unsubscribe(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){const{closed:e}=this;super.unsubscribe(),!e&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}}}function ue(n,t){return qe((e,i)=>{let r=0;e.subscribe(Ue(i,s=>{i.next(n.call(t,s,r++))}))})}function gr(n){return this instanceof gr?(this.v=n,this):new gr(n)}function kk(n,t,e){if(!Symbol.asyncIterator)throw new TypeError(\"Symbol.asyncIterator is not defined.\");var r,i=e.apply(n,t||[]),s=[];return r={},o(\"next\"),o(\"throw\"),o(\"return\"),r[Symbol.asyncIterator]=function(){return this},r;function o(h){i[h]&&(r[h]=function(p){return new Promise(function(m,g){s.push([h,p,m,g])>1||a(h,p)})})}function a(h,p){try{!function l(h){h.value instanceof gr?Promise.resolve(h.value.v).then(c,d):u(s[0][2],h)}(i[h](p))}catch(m){u(s[0][3],m)}}function c(h){a(\"next\",h)}function d(h){a(\"throw\",h)}function u(h,p){h(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function Tk(n){if(!Symbol.asyncIterator)throw new TypeError(\"Symbol.asyncIterator is not defined.\");var e,t=n[Symbol.asyncIterator];return t?t.call(n):(n=function c_(n){var t=\"function\"==typeof Symbol&&Symbol.iterator,e=t&&n[t],i=0;if(e)return e.call(n);if(n&&\"number\"==typeof n.length)return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(t?\"Object is not iterable.\":\"Symbol.iterator is not defined.\")}(n),e={},i(\"next\"),i(\"throw\"),i(\"return\"),e[Symbol.asyncIterator]=function(){return this},e);function i(s){e[s]=n[s]&&function(o){return new Promise(function(a,l){!function r(s,o,a,l){Promise.resolve(l).then(function(c){s({value:c,done:a})},o)}(a,l,(o=n[s](o)).done,o.value)})}}}const bu=n=>n&&\"number\"==typeof n.length&&\"function\"!=typeof n;function d_(n){return De(null==n?void 0:n.then)}function u_(n){return De(n[vu])}function h_(n){return Symbol.asyncIterator&&De(null==n?void 0:n[Symbol.asyncIterator])}function p_(n){return new TypeError(`You provided ${null!==n&&\"object\"==typeof n?\"an invalid object\":`'${n}'`} where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.`)}const f_=function Ik(){return\"function\"==typeof Symbol&&Symbol.iterator?Symbol.iterator:\"@@iterator\"}();function m_(n){return De(null==n?void 0:n[f_])}function g_(n){return kk(this,arguments,function*(){const e=n.getReader();try{for(;;){const{value:i,done:r}=yield gr(e.read());if(r)return yield gr(void 0);yield yield gr(i)}}finally{e.releaseLock()}})}function __(n){return De(null==n?void 0:n.getReader)}function Jt(n){if(n instanceof Ve)return n;if(null!=n){if(u_(n))return function Rk(n){return new Ve(t=>{const e=n[vu]();if(De(e.subscribe))return e.subscribe(t);throw new TypeError(\"Provided object does not correctly implement Symbol.observable\")})}(n);if(bu(n))return function Ok(n){return new Ve(t=>{for(let e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()})}(n);if(d_(n))return function Pk(n){return new Ve(t=>{n.then(e=>{t.closed||(t.next(e),t.complete())},e=>t.error(e)).then(null,n_)})}(n);if(h_(n))return v_(n);if(m_(n))return function Fk(n){return new Ve(t=>{for(const e of n)if(t.next(e),t.closed)return;t.complete()})}(n);if(__(n))return function Nk(n){return v_(g_(n))}(n)}throw p_(n)}function v_(n){return new Ve(t=>{(function Lk(n,t){var e,i,r,s;return function Ek(n,t,e,i){return new(e||(e=Promise))(function(s,o){function a(d){try{c(i.next(d))}catch(u){o(u)}}function l(d){try{c(i.throw(d))}catch(u){o(u)}}function c(d){d.done?s(d.value):function r(s){return s instanceof e?s:new e(function(o){o(s)})}(d.value).then(a,l)}c((i=i.apply(n,t||[])).next())})}(this,void 0,void 0,function*(){try{for(e=Tk(n);!(i=yield e.next()).done;)if(t.next(i.value),t.closed)return}catch(o){r={error:o}}finally{try{i&&!i.done&&(s=e.return)&&(yield s.call(e))}finally{if(r)throw r.error}}t.complete()})})(n,t).catch(e=>t.error(e))})}function Mi(n,t,e,i=0,r=!1){const s=t.schedule(function(){e(),r?n.add(this.schedule(null,i)):this.unsubscribe()},i);if(n.add(s),!r)return s}function lt(n,t,e=1/0){return De(t)?lt((i,r)=>ue((s,o)=>t(i,s,r,o))(Jt(n(i,r))),e):(\"number\"==typeof t&&(e=t),qe((i,r)=>function Bk(n,t,e,i,r,s,o,a){const l=[];let c=0,d=0,u=!1;const h=()=>{u&&!l.length&&!c&&t.complete()},p=g=>c<i?m(g):l.push(g),m=g=>{s&&t.next(g),c++;let _=!1;Jt(e(g,d++)).subscribe(Ue(t,D=>{null==r||r(D),s?p(D):t.next(D)},()=>{_=!0},void 0,()=>{if(_)try{for(c--;l.length&&c<i;){const D=l.shift();o?Mi(t,o,()=>m(D)):m(D)}h()}catch(D){t.error(D)}}))};return n.subscribe(Ue(t,p,()=>{u=!0,h()})),()=>{null==a||a()}}(i,r,n,e)))}function Eo(n=1/0){return lt(Wi,n)}const ri=new Ve(n=>n.complete());function y_(n){return n&&De(n.schedule)}function Cu(n){return n[n.length-1]}function b_(n){return De(Cu(n))?n.pop():void 0}function So(n){return y_(Cu(n))?n.pop():void 0}function C_(n,t=0){return qe((e,i)=>{e.subscribe(Ue(i,r=>Mi(i,n,()=>i.next(r),t),()=>Mi(i,n,()=>i.complete(),t),r=>Mi(i,n,()=>i.error(r),t)))})}function D_(n,t=0){return qe((e,i)=>{i.add(n.schedule(()=>e.subscribe(i),t))})}function w_(n,t){if(!n)throw new Error(\"Iterable cannot be null\");return new Ve(e=>{Mi(e,t,()=>{const i=n[Symbol.asyncIterator]();Mi(e,t,()=>{i.next().then(r=>{r.done?e.complete():e.next(r.value)})},0,!0)})})}function mt(n,t){return t?function Wk(n,t){if(null!=n){if(u_(n))return function jk(n,t){return Jt(n).pipe(D_(t),C_(t))}(n,t);if(bu(n))return function Uk(n,t){return new Ve(e=>{let i=0;return t.schedule(function(){i===n.length?e.complete():(e.next(n[i++]),e.closed||this.schedule())})})}(n,t);if(d_(n))return function zk(n,t){return Jt(n).pipe(D_(t),C_(t))}(n,t);if(h_(n))return w_(n,t);if(m_(n))return function $k(n,t){return new Ve(e=>{let i;return Mi(e,t,()=>{i=n[f_](),Mi(e,t,()=>{let r,s;try{({value:r,done:s}=i.next())}catch(o){return void e.error(o)}s?e.complete():e.next(r)},0,!0)}),()=>De(null==i?void 0:i.return)&&i.return()})}(n,t);if(__(n))return function Gk(n,t){return w_(g_(n),t)}(n,t)}throw p_(n)}(n,t):Jt(n)}function Bt(...n){const t=So(n),e=function Hk(n,t){return\"number\"==typeof Cu(n)?n.pop():t}(n,1/0),i=n;return i.length?1===i.length?Jt(i[0]):Eo(e)(mt(i,t)):ri}function it(n){return n<=0?()=>ri:qe((t,e)=>{let i=0;t.subscribe(Ue(e,r=>{++i<=n&&(e.next(r),n<=i&&e.complete())}))})}function Du(n,t,...e){return!0===t?(n(),null):!1===t?null:t(...e).pipe(it(1)).subscribe(()=>n())}function Fe(n){for(let t in n)if(n[t]===Fe)return t;throw Error(\"Could not find renamed property on target object.\")}function wu(n,t){for(const e in t)t.hasOwnProperty(e)&&!n.hasOwnProperty(e)&&(n[e]=t[e])}function Re(n){if(\"string\"==typeof n)return n;if(Array.isArray(n))return\"[\"+n.map(Re).join(\", \")+\"]\";if(null==n)return\"\"+n;if(n.overriddenName)return`${n.overriddenName}`;if(n.name)return`${n.name}`;const t=n.toString();if(null==t)return\"\"+t;const e=t.indexOf(\"\\n\");return-1===e?t:t.substring(0,e)}function Mu(n,t){return null==n||\"\"===n?null===t?\"\":t:null==t||\"\"===t?n:n+\" \"+t}const qk=Fe({__forward_ref__:Fe});function pe(n){return n.__forward_ref__=pe,n.toString=function(){return Re(this())},n}function le(n){return x_(n)?n():n}function x_(n){return\"function\"==typeof n&&n.hasOwnProperty(qk)&&n.__forward_ref__===pe}class H extends Error{constructor(t,e){super(function xu(n,t){return`NG0${Math.abs(n)}${t?\": \"+t:\"\"}`}(t,e)),this.code=t}}function re(n){return\"string\"==typeof n?n:null==n?\"\":String(n)}function Vt(n){return\"function\"==typeof n?n.name||n.toString():\"object\"==typeof n&&null!=n&&\"function\"==typeof n.type?n.type.name||n.type.toString():re(n)}function bl(n,t){const e=t?` in ${t}`:\"\";throw new H(-201,`No provider for ${Vt(n)} found${e}`)}function tn(n,t){null==n&&function $e(n,t,e,i){throw new Error(`ASSERTION ERROR: ${n}`+(null==i?\"\":` [Expected=> ${e} ${i} ${t} <=Actual]`))}(t,n,null,\"!=\")}function k(n){return{token:n.token,providedIn:n.providedIn||null,factory:n.factory,value:void 0}}function P(n){return{providers:n.providers||[],imports:n.imports||[]}}function Eu(n){return E_(n,Cl)||E_(n,k_)}function E_(n,t){return n.hasOwnProperty(t)?n[t]:null}function S_(n){return n&&(n.hasOwnProperty(Su)||n.hasOwnProperty(eT))?n[Su]:null}const Cl=Fe({\\u0275prov:Fe}),Su=Fe({\\u0275inj:Fe}),k_=Fe({ngInjectableDef:Fe}),eT=Fe({ngInjectorDef:Fe});var ee=(()=>((ee=ee||{})[ee.Default=0]=\"Default\",ee[ee.Host=1]=\"Host\",ee[ee.Self=2]=\"Self\",ee[ee.SkipSelf=4]=\"SkipSelf\",ee[ee.Optional=8]=\"Optional\",ee))();let ku;function qi(n){const t=ku;return ku=n,t}function T_(n,t,e){const i=Eu(n);return i&&\"root\"==i.providedIn?void 0===i.value?i.value=i.factory():i.value:e&ee.Optional?null:void 0!==t?t:void bl(Re(n),\"Injector\")}function Yi(n){return{toString:n}.toString()}var Nn=(()=>((Nn=Nn||{})[Nn.OnPush=0]=\"OnPush\",Nn[Nn.Default=1]=\"Default\",Nn))(),Ln=(()=>{return(n=Ln||(Ln={}))[n.Emulated=0]=\"Emulated\",n[n.None=2]=\"None\",n[n.ShadowDom=3]=\"ShadowDom\",Ln;var n})();const nT=\"undefined\"!=typeof globalThis&&globalThis,iT=\"undefined\"!=typeof window&&window,rT=\"undefined\"!=typeof self&&\"undefined\"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&self,Oe=nT||\"undefined\"!=typeof global&&global||iT||rT,os={},Ne=[],Dl=Fe({\\u0275cmp:Fe}),Tu=Fe({\\u0275dir:Fe}),Au=Fe({\\u0275pipe:Fe}),A_=Fe({\\u0275mod:Fe}),Ei=Fe({\\u0275fac:Fe}),ko=Fe({__NG_ELEMENT_ID__:Fe});let sT=0;function xe(n){return Yi(()=>{const e={},i={type:n.type,providersResolver:null,decls:n.decls,vars:n.vars,factory:null,template:n.template||null,consts:n.consts||null,ngContentSelectors:n.ngContentSelectors,hostBindings:n.hostBindings||null,hostVars:n.hostVars||0,hostAttrs:n.hostAttrs||null,contentQueries:n.contentQueries||null,declaredInputs:e,inputs:null,outputs:null,exportAs:n.exportAs||null,onPush:n.changeDetection===Nn.OnPush,directiveDefs:null,pipeDefs:null,selectors:n.selectors||Ne,viewQuery:n.viewQuery||null,features:n.features||null,data:n.data||{},encapsulation:n.encapsulation||Ln.Emulated,id:\"c\",styles:n.styles||Ne,_:null,setInput:null,schemas:n.schemas||null,tView:null},r=n.directives,s=n.features,o=n.pipes;return i.id+=sT++,i.inputs=P_(n.inputs,e),i.outputs=P_(n.outputs),s&&s.forEach(a=>a(i)),i.directiveDefs=r?()=>(\"function\"==typeof r?r():r).map(I_):null,i.pipeDefs=o?()=>(\"function\"==typeof o?o():o).map(R_):null,i})}function I_(n){return Ot(n)||function Qi(n){return n[Tu]||null}(n)}function R_(n){return function _r(n){return n[Au]||null}(n)}const O_={};function F(n){return Yi(()=>{const t={type:n.type,bootstrap:n.bootstrap||Ne,declarations:n.declarations||Ne,imports:n.imports||Ne,exports:n.exports||Ne,transitiveCompileScopes:null,schemas:n.schemas||null,id:n.id||null};return null!=n.id&&(O_[n.id]=n.type),t})}function P_(n,t){if(null==n)return os;const e={};for(const i in n)if(n.hasOwnProperty(i)){let r=n[i],s=r;Array.isArray(r)&&(s=r[1],r=r[0]),e[r]=i,t&&(t[r]=s)}return e}const C=xe;function Ot(n){return n[Dl]||null}function gn(n,t){const e=n[A_]||null;if(!e&&!0===t)throw new Error(`Type ${Re(n)} does not have '\\u0275mod' property.`);return e}function si(n){return Array.isArray(n)&&\"object\"==typeof n[1]}function Vn(n){return Array.isArray(n)&&!0===n[1]}function Ou(n){return 0!=(8&n.flags)}function El(n){return 2==(2&n.flags)}function Sl(n){return 1==(1&n.flags)}function Hn(n){return null!==n.template}function uT(n){return 0!=(512&n[2])}function Cr(n,t){return n.hasOwnProperty(Ei)?n[Ei]:null}class fT{constructor(t,e,i){this.previousValue=t,this.currentValue=e,this.firstChange=i}isFirstChange(){return this.firstChange}}function Je(){return N_}function N_(n){return n.type.prototype.ngOnChanges&&(n.setInput=gT),mT}function mT(){const n=B_(this),t=null==n?void 0:n.current;if(t){const e=n.previous;if(e===os)n.previous=t;else for(let i in t)e[i]=t[i];n.current=null,this.ngOnChanges(t)}}function gT(n,t,e,i){const r=B_(n)||function _T(n,t){return n[L_]=t}(n,{previous:os,current:null}),s=r.current||(r.current={}),o=r.previous,a=this.declaredInputs[e],l=o[a];s[a]=new fT(l&&l.currentValue,t,o===os),n[i]=t}Je.ngInherit=!0;const L_=\"__ngSimpleChanges__\";function B_(n){return n[L_]||null}let Bu;function et(n){return!!n.listen}const V_={createRenderer:(n,t)=>function Vu(){return void 0!==Bu?Bu:\"undefined\"!=typeof document?document:void 0}()};function ct(n){for(;Array.isArray(n);)n=n[0];return n}function kl(n,t){return ct(t[n])}function yn(n,t){return ct(t[n.index])}function Hu(n,t){return n.data[t]}function rn(n,t){const e=t[n];return si(e)?e:e[0]}function H_(n){return 4==(4&n[2])}function ju(n){return 128==(128&n[2])}function Ki(n,t){return null==t?null:n[t]}function j_(n){n[18]=0}function zu(n,t){n[5]+=t;let e=n,i=n[3];for(;null!==i&&(1===t&&1===e[5]||-1===t&&0===e[5]);)i[5]+=t,e=i,i=i[3]}const te={lFrame:Q_(null),bindingsEnabled:!0,isInCheckNoChangesMode:!1};function z_(){return te.bindingsEnabled}function w(){return te.lFrame.lView}function Me(){return te.lFrame.tView}function Dr(n){return te.lFrame.contextLView=n,n[8]}function gt(){let n=U_();for(;null!==n&&64===n.type;)n=n.parent;return n}function U_(){return te.lFrame.currentTNode}function oi(n,t){const e=te.lFrame;e.currentTNode=n,e.isParent=t}function Uu(){return te.lFrame.isParent}function $u(){te.lFrame.isParent=!1}function Tl(){return te.isInCheckNoChangesMode}function Al(n){te.isInCheckNoChangesMode=n}function hs(){return te.lFrame.bindingIndex++}function ki(n){const t=te.lFrame,e=t.bindingIndex;return t.bindingIndex=t.bindingIndex+n,e}function PT(n,t){const e=te.lFrame;e.bindingIndex=e.bindingRootIndex=n,Gu(t)}function Gu(n){te.lFrame.currentDirectiveIndex=n}function Wu(n){const t=te.lFrame.currentDirectiveIndex;return-1===t?null:n[t]}function W_(){return te.lFrame.currentQueryIndex}function qu(n){te.lFrame.currentQueryIndex=n}function NT(n){const t=n[1];return 2===t.type?t.declTNode:1===t.type?n[6]:null}function q_(n,t,e){if(e&ee.SkipSelf){let r=t,s=n;for(;!(r=r.parent,null!==r||e&ee.Host||(r=NT(s),null===r||(s=s[15],10&r.type))););if(null===r)return!1;t=r,n=s}const i=te.lFrame=Y_();return i.currentTNode=t,i.lView=n,!0}function Il(n){const t=Y_(),e=n[1];te.lFrame=t,t.currentTNode=e.firstChild,t.lView=n,t.tView=e,t.contextLView=n,t.bindingIndex=e.bindingStartIndex,t.inI18n=!1}function Y_(){const n=te.lFrame,t=null===n?null:n.child;return null===t?Q_(n):t}function Q_(n){const t={currentTNode:null,isParent:!0,lView:null,tView:null,selectedIndex:-1,contextLView:null,elementDepthCount:0,currentNamespace:null,currentDirectiveIndex:-1,bindingRootIndex:-1,bindingIndex:-1,currentQueryIndex:0,parent:n,child:null,inI18n:!1};return null!==n&&(n.child=t),t}function K_(){const n=te.lFrame;return te.lFrame=n.parent,n.currentTNode=null,n.lView=null,n}const Z_=K_;function Rl(){const n=K_();n.isParent=!0,n.tView=null,n.selectedIndex=-1,n.contextLView=null,n.elementDepthCount=0,n.currentDirectiveIndex=-1,n.currentNamespace=null,n.bindingRootIndex=-1,n.bindingIndex=-1,n.currentQueryIndex=0}function jt(){return te.lFrame.selectedIndex}function Zi(n){te.lFrame.selectedIndex=n}function tt(){const n=te.lFrame;return Hu(n.tView,n.selectedIndex)}function Oo(){te.lFrame.currentNamespace=\"svg\"}function Ol(n,t){for(let e=t.directiveStart,i=t.directiveEnd;e<i;e++){const s=n.data[e].type.prototype,{ngAfterContentInit:o,ngAfterContentChecked:a,ngAfterViewInit:l,ngAfterViewChecked:c,ngOnDestroy:d}=s;o&&(n.contentHooks||(n.contentHooks=[])).push(-e,o),a&&((n.contentHooks||(n.contentHooks=[])).push(e,a),(n.contentCheckHooks||(n.contentCheckHooks=[])).push(e,a)),l&&(n.viewHooks||(n.viewHooks=[])).push(-e,l),c&&((n.viewHooks||(n.viewHooks=[])).push(e,c),(n.viewCheckHooks||(n.viewCheckHooks=[])).push(e,c)),null!=d&&(n.destroyHooks||(n.destroyHooks=[])).push(e,d)}}function Pl(n,t,e){J_(n,t,3,e)}function Fl(n,t,e,i){(3&n[2])===e&&J_(n,t,e,i)}function Yu(n,t){let e=n[2];(3&e)===t&&(e&=2047,e+=1,n[2]=e)}function J_(n,t,e,i){const s=null!=i?i:-1,o=t.length-1;let a=0;for(let l=void 0!==i?65535&n[18]:0;l<o;l++)if(\"number\"==typeof t[l+1]){if(a=t[l],null!=i&&a>=i)break}else t[l]<0&&(n[18]+=65536),(a<s||-1==s)&&(UT(n,e,t,l),n[18]=(4294901760&n[18])+l+2),l++}function UT(n,t,e,i){const r=e[i]<0,s=e[i+1],a=n[r?-e[i]:e[i]];if(r){if(n[2]>>11<n[18]>>16&&(3&n[2])===t){n[2]+=2048;try{s.call(a)}finally{}}}else try{s.call(a)}finally{}}class Po{constructor(t,e,i){this.factory=t,this.resolving=!1,this.canSeeViewProviders=e,this.injectImpl=i}}function Nl(n,t,e){const i=et(n);let r=0;for(;r<e.length;){const s=e[r];if(\"number\"==typeof s){if(0!==s)break;r++;const o=e[r++],a=e[r++],l=e[r++];i?n.setAttribute(t,a,l,o):t.setAttributeNS(o,a,l)}else{const o=s,a=e[++r];Ku(o)?i&&n.setProperty(t,o,a):i?n.setAttribute(t,o,a):t.setAttribute(o,a),r++}}return r}function ev(n){return 3===n||4===n||6===n}function Ku(n){return 64===n.charCodeAt(0)}function Ll(n,t){if(null!==t&&0!==t.length)if(null===n||0===n.length)n=t.slice();else{let e=-1;for(let i=0;i<t.length;i++){const r=t[i];\"number\"==typeof r?e=r:0===e||tv(n,e,r,null,-1===e||2===e?t[++i]:null)}}return n}function tv(n,t,e,i,r){let s=0,o=n.length;if(-1===t)o=-1;else for(;s<n.length;){const a=n[s++];if(\"number\"==typeof a){if(a===t){o=-1;break}if(a>t){o=s-1;break}}}for(;s<n.length;){const a=n[s];if(\"number\"==typeof a)break;if(a===e){if(null===i)return void(null!==r&&(n[s+1]=r));if(i===n[s+1])return void(n[s+2]=r)}s++,null!==i&&s++,null!==r&&s++}-1!==o&&(n.splice(o,0,t),s=o+1),n.splice(s++,0,e),null!==i&&n.splice(s++,0,i),null!==r&&n.splice(s++,0,r)}function nv(n){return-1!==n}function ps(n){return 32767&n}function fs(n,t){let e=function YT(n){return n>>16}(n),i=t;for(;e>0;)i=i[15],e--;return i}let Zu=!0;function Bl(n){const t=Zu;return Zu=n,t}let QT=0;function No(n,t){const e=Ju(n,t);if(-1!==e)return e;const i=t[1];i.firstCreatePass&&(n.injectorIndex=t.length,Xu(i.data,n),Xu(t,null),Xu(i.blueprint,null));const r=Vl(n,t),s=n.injectorIndex;if(nv(r)){const o=ps(r),a=fs(r,t),l=a[1].data;for(let c=0;c<8;c++)t[s+c]=a[o+c]|l[o+c]}return t[s+8]=r,s}function Xu(n,t){n.push(0,0,0,0,0,0,0,0,t)}function Ju(n,t){return-1===n.injectorIndex||n.parent&&n.parent.injectorIndex===n.injectorIndex||null===t[n.injectorIndex+8]?-1:n.injectorIndex}function Vl(n,t){if(n.parent&&-1!==n.parent.injectorIndex)return n.parent.injectorIndex;let e=0,i=null,r=t;for(;null!==r;){const s=r[1],o=s.type;if(i=2===o?s.declTNode:1===o?r[6]:null,null===i)return-1;if(e++,r=r[15],-1!==i.injectorIndex)return i.injectorIndex|e<<16}return-1}function Hl(n,t,e){!function KT(n,t,e){let i;\"string\"==typeof e?i=e.charCodeAt(0)||0:e.hasOwnProperty(ko)&&(i=e[ko]),null==i&&(i=e[ko]=QT++);const r=255&i;t.data[n+(r>>5)]|=1<<r}(n,t,e)}function sv(n,t,e){if(e&ee.Optional)return n;bl(t,\"NodeInjector\")}function ov(n,t,e,i){if(e&ee.Optional&&void 0===i&&(i=null),0==(e&(ee.Self|ee.Host))){const r=n[9],s=qi(void 0);try{return r?r.get(t,i,e&ee.Optional):T_(t,i,e&ee.Optional)}finally{qi(s)}}return sv(i,t,e)}function av(n,t,e,i=ee.Default,r){if(null!==n){const s=function eA(n){if(\"string\"==typeof n)return n.charCodeAt(0)||0;const t=n.hasOwnProperty(ko)?n[ko]:void 0;return\"number\"==typeof t?t>=0?255&t:XT:t}(e);if(\"function\"==typeof s){if(!q_(t,n,i))return i&ee.Host?sv(r,e,i):ov(t,e,i,r);try{const o=s(i);if(null!=o||i&ee.Optional)return o;bl(e)}finally{Z_()}}else if(\"number\"==typeof s){let o=null,a=Ju(n,t),l=-1,c=i&ee.Host?t[16][6]:null;for((-1===a||i&ee.SkipSelf)&&(l=-1===a?Vl(n,t):t[a+8],-1!==l&&dv(i,!1)?(o=t[1],a=ps(l),t=fs(l,t)):a=-1);-1!==a;){const d=t[1];if(cv(s,a,d.data)){const u=JT(a,t,e,o,i,c);if(u!==lv)return u}l=t[a+8],-1!==l&&dv(i,t[1].data[a+8]===c)&&cv(s,a,t)?(o=d,a=ps(l),t=fs(l,t)):a=-1}}}return ov(t,e,i,r)}const lv={};function XT(){return new ms(gt(),w())}function JT(n,t,e,i,r,s){const o=t[1],a=o.data[n+8],d=jl(a,o,e,null==i?El(a)&&Zu:i!=o&&0!=(3&a.type),r&ee.Host&&s===a);return null!==d?Lo(t,o,d,a):lv}function jl(n,t,e,i,r){const s=n.providerIndexes,o=t.data,a=1048575&s,l=n.directiveStart,d=s>>20,h=r?a+d:n.directiveEnd;for(let p=i?a:a+d;p<h;p++){const m=o[p];if(p<l&&e===m||p>=l&&m.type===e)return p}if(r){const p=o[l];if(p&&Hn(p)&&p.type===e)return l}return null}function Lo(n,t,e,i){let r=n[e];const s=t.data;if(function $T(n){return n instanceof Po}(r)){const o=r;o.resolving&&function Yk(n,t){const e=t?`. Dependency path: ${t.join(\" > \")} > ${n}`:\"\";throw new H(-200,`Circular dependency in DI detected for ${n}${e}`)}(Vt(s[e]));const a=Bl(o.canSeeViewProviders);o.resolving=!0;const l=o.injectImpl?qi(o.injectImpl):null;q_(n,i,ee.Default);try{r=n[e]=o.factory(void 0,s,n,i),t.firstCreatePass&&e>=i.directiveStart&&function zT(n,t,e){const{ngOnChanges:i,ngOnInit:r,ngDoCheck:s}=t.type.prototype;if(i){const o=N_(t);(e.preOrderHooks||(e.preOrderHooks=[])).push(n,o),(e.preOrderCheckHooks||(e.preOrderCheckHooks=[])).push(n,o)}r&&(e.preOrderHooks||(e.preOrderHooks=[])).push(0-n,r),s&&((e.preOrderHooks||(e.preOrderHooks=[])).push(n,s),(e.preOrderCheckHooks||(e.preOrderCheckHooks=[])).push(n,s))}(e,s[e],t)}finally{null!==l&&qi(l),Bl(a),o.resolving=!1,Z_()}}return r}function cv(n,t,e){return!!(e[t+(n>>5)]&1<<n)}function dv(n,t){return!(n&ee.Self||n&ee.Host&&t)}class ms{constructor(t,e){this._tNode=t,this._lView=e}get(t,e,i){return av(this._tNode,this._lView,t,i,e)}}function oe(n){return Yi(()=>{const t=n.prototype.constructor,e=t[Ei]||eh(t),i=Object.prototype;let r=Object.getPrototypeOf(n.prototype).constructor;for(;r&&r!==i;){const s=r[Ei]||eh(r);if(s&&s!==e)return s;r=Object.getPrototypeOf(r)}return s=>new s})}function eh(n){return x_(n)?()=>{const t=eh(le(n));return t&&t()}:Cr(n)}function kt(n){return function ZT(n,t){if(\"class\"===t)return n.classes;if(\"style\"===t)return n.styles;const e=n.attrs;if(e){const i=e.length;let r=0;for(;r<i;){const s=e[r];if(ev(s))break;if(0===s)r+=2;else if(\"number\"==typeof s)for(r++;r<i&&\"string\"==typeof e[r];)r++;else{if(s===t)return e[r+1];r+=2}}}return null}(gt(),n)}const _s=\"__parameters__\";function ys(n,t,e){return Yi(()=>{const i=function th(n){return function(...e){if(n){const i=n(...e);for(const r in i)this[r]=i[r]}}}(t);function r(...s){if(this instanceof r)return i.apply(this,s),this;const o=new r(...s);return a.annotation=o,a;function a(l,c,d){const u=l.hasOwnProperty(_s)?l[_s]:Object.defineProperty(l,_s,{value:[]})[_s];for(;u.length<=d;)u.push(null);return(u[d]=u[d]||[]).push(o),l}}return e&&(r.prototype=Object.create(e.prototype)),r.prototype.ngMetadataName=n,r.annotationCls=r,r})}class b{constructor(t,e){this._desc=t,this.ngMetadataName=\"InjectionToken\",this.\\u0275prov=void 0,\"number\"==typeof e?this.__NG_ELEMENT_ID__=e:void 0!==e&&(this.\\u0275prov=k({token:this,providedIn:e.providedIn||\"root\",factory:e.factory}))}toString(){return`InjectionToken ${this._desc}`}}const nA=new b(\"AnalyzeForEntryComponents\");function bn(n,t){void 0===t&&(t=n);for(let e=0;e<n.length;e++){let i=n[e];Array.isArray(i)?(t===n&&(t=n.slice(0,e)),bn(i,t)):t!==n&&t.push(i)}return t}function ai(n,t){n.forEach(e=>Array.isArray(e)?ai(e,t):t(e))}function hv(n,t,e){t>=n.length?n.push(e):n.splice(t,0,e)}function zl(n,t){return t>=n.length-1?n.pop():n.splice(t,1)[0]}function Ho(n,t){const e=[];for(let i=0;i<n;i++)e.push(t);return e}function sn(n,t,e){let i=bs(n,t);return i>=0?n[1|i]=e:(i=~i,function sA(n,t,e,i){let r=n.length;if(r==t)n.push(e,i);else if(1===r)n.push(i,n[0]),n[0]=e;else{for(r--,n.push(n[r-1],n[r]);r>t;)n[r]=n[r-2],r--;n[t]=e,n[t+1]=i}}(n,i,t,e)),i}function ih(n,t){const e=bs(n,t);if(e>=0)return n[1|e]}function bs(n,t){return function mv(n,t,e){let i=0,r=n.length>>e;for(;r!==i;){const s=i+(r-i>>1),o=n[s<<e];if(t===o)return s<<e;o>t?r=s:i=s+1}return~(r<<e)}(n,t,1)}const jo={},sh=\"__NG_DI_FLAG__\",$l=\"ngTempTokenPath\",hA=/\\n/gm,_v=\"__source\",fA=Fe({provide:String,useValue:Fe});let zo;function vv(n){const t=zo;return zo=n,t}function mA(n,t=ee.Default){if(void 0===zo)throw new H(203,\"\");return null===zo?T_(n,void 0,t):zo.get(n,t&ee.Optional?null:void 0,t)}function y(n,t=ee.Default){return(function tT(){return ku}()||mA)(le(n),t)}const Uo=y;function oh(n){const t=[];for(let e=0;e<n.length;e++){const i=le(n[e]);if(Array.isArray(i)){if(0===i.length)throw new H(900,\"\");let r,s=ee.Default;for(let o=0;o<i.length;o++){const a=i[o],l=gA(a);\"number\"==typeof l?-1===l?r=a.token:s|=l:r=a}t.push(y(r,s))}else t.push(y(i))}return t}function $o(n,t){return n[sh]=t,n.prototype[sh]=t,n}function gA(n){return n[sh]}const Gl=$o(ys(\"Inject\",n=>({token:n})),-1),Tt=$o(ys(\"Optional\"),8),Cn=$o(ys(\"SkipSelf\"),4);function on(n){return n instanceof class wr{constructor(t){this.changingThisBreaksApplicationSecurity=t}toString(){return`SafeValue must use [property]=binding: ${this.changingThisBreaksApplicationSecurity} (see https://g.co/ng/security#xss)`}}?n.changingThisBreaksApplicationSecurity:n}const Bv=\"__ngContext__\";function Ft(n,t){n[Bv]=t}function gh(n){const t=function Qo(n){return n[Bv]||null}(n);return t?Array.isArray(t)?t:t.lView:null}function vh(n){return n.ngOriginalError}function uI(n,...t){n.error(...t)}class Mr{constructor(){this._console=console}handleError(t){const e=this._findOriginalError(t),i=function dI(n){return n&&n.ngErrorLogger||uI}(t);i(this._console,\"ERROR\",t),e&&i(this._console,\"ORIGINAL ERROR\",e)}_findOriginalError(t){let e=t&&vh(t);for(;e&&vh(e);)e=vh(e);return e||null}}const CI=(()=>(\"undefined\"!=typeof requestAnimationFrame&&requestAnimationFrame||setTimeout).bind(Oe))();function Uv(n){return n.ownerDocument.defaultView}function di(n){return n instanceof Function?n():n}var an=(()=>((an=an||{})[an.Important=1]=\"Important\",an[an.DashCase=2]=\"DashCase\",an))();function bh(n,t){return undefined(n,t)}function Ko(n){const t=n[3];return Vn(t)?t[3]:t}function Ch(n){return Yv(n[13])}function Dh(n){return Yv(n[4])}function Yv(n){for(;null!==n&&!Vn(n);)n=n[4];return n}function Ms(n,t,e,i,r){if(null!=i){let s,o=!1;Vn(i)?s=i:si(i)&&(o=!0,i=i[0]);const a=ct(i);0===n&&null!==e?null==r?ey(t,e,a):xr(t,e,a,r||null,!0):1===n&&null!==e?xr(t,e,a,r||null,!0):2===n?function ay(n,t,e){const i=Kl(n,t);i&&function PI(n,t,e,i){et(n)?n.removeChild(t,e,i):t.removeChild(e)}(n,i,t,e)}(t,a,o):3===n&&t.destroyNode(a),null!=s&&function LI(n,t,e,i,r){const s=e[7];s!==ct(e)&&Ms(t,n,i,s,r);for(let a=10;a<e.length;a++){const l=e[a];Zo(l[1],l,n,t,i,s)}}(t,n,s,e,r)}}function Mh(n,t,e){if(et(n))return n.createElement(t,e);{const i=null!==e?function CT(n){const t=n.toLowerCase();return\"svg\"===t?\"http://www.w3.org/2000/svg\":\"math\"===t?\"http://www.w3.org/1998/MathML/\":null}(e):null;return null===i?n.createElement(t):n.createElementNS(i,t)}}function Kv(n,t){const e=n[9],i=e.indexOf(t),r=t[3];1024&t[2]&&(t[2]&=-1025,zu(r,-1)),e.splice(i,1)}function xh(n,t){if(n.length<=10)return;const e=10+t,i=n[e];if(i){const r=i[17];null!==r&&r!==n&&Kv(r,i),t>0&&(n[e-1][4]=i[4]);const s=zl(n,10+t);!function EI(n,t){Zo(n,t,t[11],2,null,null),t[0]=null,t[6]=null}(i[1],i);const o=s[19];null!==o&&o.detachView(s[1]),i[3]=null,i[4]=null,i[2]&=-129}return i}function Zv(n,t){if(!(256&t[2])){const e=t[11];et(e)&&e.destroyNode&&Zo(n,t,e,3,null,null),function TI(n){let t=n[13];if(!t)return Eh(n[1],n);for(;t;){let e=null;if(si(t))e=t[13];else{const i=t[10];i&&(e=i)}if(!e){for(;t&&!t[4]&&t!==n;)si(t)&&Eh(t[1],t),t=t[3];null===t&&(t=n),si(t)&&Eh(t[1],t),e=t&&t[4]}t=e}}(t)}}function Eh(n,t){if(!(256&t[2])){t[2]&=-129,t[2]|=256,function OI(n,t){let e;if(null!=n&&null!=(e=n.destroyHooks))for(let i=0;i<e.length;i+=2){const r=t[e[i]];if(!(r instanceof Po)){const s=e[i+1];if(Array.isArray(s))for(let o=0;o<s.length;o+=2){const a=r[s[o]],l=s[o+1];try{l.call(a)}finally{}}else try{s.call(r)}finally{}}}}(n,t),function RI(n,t){const e=n.cleanup,i=t[7];let r=-1;if(null!==e)for(let s=0;s<e.length-1;s+=2)if(\"string\"==typeof e[s]){const o=e[s+1],a=\"function\"==typeof o?o(t):ct(t[o]),l=i[r=e[s+2]],c=e[s+3];\"boolean\"==typeof c?a.removeEventListener(e[s],l,c):c>=0?i[r=c]():i[r=-c].unsubscribe(),s+=2}else{const o=i[r=e[s+1]];e[s].call(o)}if(null!==i){for(let s=r+1;s<i.length;s++)i[s]();t[7]=null}}(n,t),1===t[1].type&&et(t[11])&&t[11].destroy();const e=t[17];if(null!==e&&Vn(t[3])){e!==t[3]&&Kv(e,t);const i=t[19];null!==i&&i.detachView(n)}}}function Xv(n,t,e){return function Jv(n,t,e){let i=t;for(;null!==i&&40&i.type;)i=(t=i).parent;if(null===i)return e[0];if(2&i.flags){const r=n.data[i.directiveStart].encapsulation;if(r===Ln.None||r===Ln.Emulated)return null}return yn(i,e)}(n,t.parent,e)}function xr(n,t,e,i,r){et(n)?n.insertBefore(t,e,i,r):t.insertBefore(e,i,r)}function ey(n,t,e){et(n)?n.appendChild(t,e):t.appendChild(e)}function ty(n,t,e,i,r){null!==i?xr(n,t,e,i,r):ey(n,t,e)}function Kl(n,t){return et(n)?n.parentNode(t):t.parentNode}function ny(n,t,e){return ry(n,t,e)}let ry=function iy(n,t,e){return 40&n.type?yn(n,e):null};function Zl(n,t,e,i){const r=Xv(n,i,t),s=t[11],a=ny(i.parent||t[6],i,t);if(null!=r)if(Array.isArray(e))for(let l=0;l<e.length;l++)ty(s,r,e[l],a,!1);else ty(s,r,e,a,!1)}function Xl(n,t){if(null!==t){const e=t.type;if(3&e)return yn(t,n);if(4&e)return kh(-1,n[t.index]);if(8&e){const i=t.child;if(null!==i)return Xl(n,i);{const r=n[t.index];return Vn(r)?kh(-1,r):ct(r)}}if(32&e)return bh(t,n)()||ct(n[t.index]);{const i=oy(n,t);return null!==i?Array.isArray(i)?i[0]:Xl(Ko(n[16]),i):Xl(n,t.next)}}return null}function oy(n,t){return null!==t?n[16][6].projection[t.projection]:null}function kh(n,t){const e=10+n+1;if(e<t.length){const i=t[e],r=i[1].firstChild;if(null!==r)return Xl(i,r)}return t[7]}function Th(n,t,e,i,r,s,o){for(;null!=e;){const a=i[e.index],l=e.type;if(o&&0===t&&(a&&Ft(ct(a),i),e.flags|=4),64!=(64&e.flags))if(8&l)Th(n,t,e.child,i,r,s,!1),Ms(t,n,r,a,s);else if(32&l){const c=bh(e,i);let d;for(;d=c();)Ms(t,n,r,d,s);Ms(t,n,r,a,s)}else 16&l?ly(n,t,i,e,r,s):Ms(t,n,r,a,s);e=o?e.projectionNext:e.next}}function Zo(n,t,e,i,r,s){Th(e,i,n.firstChild,t,r,s,!1)}function ly(n,t,e,i,r,s){const o=e[16],l=o[6].projection[i.projection];if(Array.isArray(l))for(let c=0;c<l.length;c++)Ms(t,n,r,l[c],s);else Th(n,t,l,o[3],r,s,!0)}function cy(n,t,e){et(n)?n.setAttribute(t,\"style\",e):t.style.cssText=e}function Ah(n,t,e){et(n)?\"\"===e?n.removeAttribute(t,\"class\"):n.setAttribute(t,\"class\",e):t.className=e}function dy(n,t,e){let i=n.length;for(;;){const r=n.indexOf(t,e);if(-1===r)return r;if(0===r||n.charCodeAt(r-1)<=32){const s=t.length;if(r+s===i||n.charCodeAt(r+s)<=32)return r}e=r+1}}const uy=\"ng-template\";function VI(n,t,e){let i=0;for(;i<n.length;){let r=n[i++];if(e&&\"class\"===r){if(r=n[i],-1!==dy(r.toLowerCase(),t,0))return!0}else if(1===r){for(;i<n.length&&\"string\"==typeof(r=n[i++]);)if(r.toLowerCase()===t)return!0;return!1}}return!1}function hy(n){return 4===n.type&&n.value!==uy}function HI(n,t,e){return t===(4!==n.type||e?n.value:uy)}function jI(n,t,e){let i=4;const r=n.attrs||[],s=function $I(n){for(let t=0;t<n.length;t++)if(ev(n[t]))return t;return n.length}(r);let o=!1;for(let a=0;a<t.length;a++){const l=t[a];if(\"number\"!=typeof l){if(!o)if(4&i){if(i=2|1&i,\"\"!==l&&!HI(n,l,e)||\"\"===l&&1===t.length){if(jn(i))return!1;o=!0}}else{const c=8&i?l:t[++a];if(8&i&&null!==n.attrs){if(!VI(n.attrs,c,e)){if(jn(i))return!1;o=!0}continue}const u=zI(8&i?\"class\":l,r,hy(n),e);if(-1===u){if(jn(i))return!1;o=!0;continue}if(\"\"!==c){let h;h=u>s?\"\":r[u+1].toLowerCase();const p=8&i?h:null;if(p&&-1!==dy(p,c,0)||2&i&&c!==h){if(jn(i))return!1;o=!0}}}}else{if(!o&&!jn(i)&&!jn(l))return!1;if(o&&jn(l))continue;o=!1,i=l|1&i}}return jn(i)||o}function jn(n){return 0==(1&n)}function zI(n,t,e,i){if(null===t)return-1;let r=0;if(i||!e){let s=!1;for(;r<t.length;){const o=t[r];if(o===n)return r;if(3===o||6===o)s=!0;else{if(1===o||2===o){let a=t[++r];for(;\"string\"==typeof a;)a=t[++r];continue}if(4===o)break;if(0===o){r+=4;continue}}r+=s?1:2}return-1}return function GI(n,t){let e=n.indexOf(4);if(e>-1)for(e++;e<n.length;){const i=n[e];if(\"number\"==typeof i)return-1;if(i===t)return e;e++}return-1}(t,n)}function py(n,t,e=!1){for(let i=0;i<t.length;i++)if(jI(n,t[i],e))return!0;return!1}function WI(n,t){e:for(let e=0;e<t.length;e++){const i=t[e];if(n.length===i.length){for(let r=0;r<n.length;r++)if(n[r]!==i[r])continue e;return!0}}return!1}function fy(n,t){return n?\":not(\"+t.trim()+\")\":t}function qI(n){let t=n[0],e=1,i=2,r=\"\",s=!1;for(;e<n.length;){let o=n[e];if(\"string\"==typeof o)if(2&i){const a=n[++e];r+=\"[\"+o+(a.length>0?'=\"'+a+'\"':\"\")+\"]\"}else 8&i?r+=\".\"+o:4&i&&(r+=\" \"+o);else\"\"!==r&&!jn(o)&&(t+=fy(s,r),r=\"\"),i=o,s=s||!jn(i);e++}return\"\"!==r&&(t+=fy(s,r)),t}const se={};function T(n){my(Me(),w(),jt()+n,Tl())}function my(n,t,e,i){if(!i)if(3==(3&t[2])){const s=n.preOrderCheckHooks;null!==s&&Pl(t,s,e)}else{const s=n.preOrderHooks;null!==s&&Fl(t,s,0,e)}Zi(e)}function Jl(n,t){return n<<17|t<<2}function zn(n){return n>>17&32767}function Ih(n){return 2|n}function Ti(n){return(131068&n)>>2}function Rh(n,t){return-131069&n|t<<2}function Oh(n){return 1|n}function Ey(n,t){const e=n.contentQueries;if(null!==e)for(let i=0;i<e.length;i+=2){const r=e[i],s=e[i+1];if(-1!==s){const o=n.data[s];qu(r),o.contentQueries(2,t[s],s)}}}function Xo(n,t,e,i,r,s,o,a,l,c){const d=t.blueprint.slice();return d[0]=r,d[2]=140|i,j_(d),d[3]=d[15]=n,d[8]=e,d[10]=o||n&&n[10],d[11]=a||n&&n[11],d[12]=l||n&&n[12]||null,d[9]=c||n&&n[9]||null,d[6]=s,d[16]=2==t.type?n[16]:d,d}function xs(n,t,e,i,r){let s=n.data[t];if(null===s)s=function zh(n,t,e,i,r){const s=U_(),o=Uu(),l=n.data[t]=function uR(n,t,e,i,r,s){return{type:e,index:i,insertBeforeIndex:null,injectorIndex:t?t.injectorIndex:-1,directiveStart:-1,directiveEnd:-1,directiveStylingLast:-1,propertyBindings:null,flags:0,providerIndexes:0,value:r,attrs:s,mergedAttrs:null,localNames:null,initialInputs:void 0,inputs:null,outputs:null,tViews:null,next:null,projectionNext:null,child:null,parent:t,projection:null,styles:null,stylesWithoutHost:null,residualStyles:void 0,classes:null,classesWithoutHost:null,residualClasses:void 0,classBindings:0,styleBindings:0}}(0,o?s:s&&s.parent,e,t,i,r);return null===n.firstChild&&(n.firstChild=l),null!==s&&(o?null==s.child&&null!==l.parent&&(s.child=l):null===s.next&&(s.next=l)),l}(n,t,e,i,r),function OT(){return te.lFrame.inI18n}()&&(s.flags|=64);else if(64&s.type){s.type=e,s.value=i,s.attrs=r;const o=function Ro(){const n=te.lFrame,t=n.currentTNode;return n.isParent?t:t.parent}();s.injectorIndex=null===o?-1:o.injectorIndex}return oi(s,!0),s}function Es(n,t,e,i){if(0===e)return-1;const r=t.length;for(let s=0;s<e;s++)t.push(i),n.blueprint.push(i),n.data.push(null);return r}function Jo(n,t,e){Il(t);try{const i=n.viewQuery;null!==i&&Zh(1,i,e);const r=n.template;null!==r&&Sy(n,t,r,1,e),n.firstCreatePass&&(n.firstCreatePass=!1),n.staticContentQueries&&Ey(n,t),n.staticViewQueries&&Zh(2,n.viewQuery,e);const s=n.components;null!==s&&function lR(n,t){for(let e=0;e<t.length;e++)TR(n,t[e])}(t,s)}catch(i){throw n.firstCreatePass&&(n.incompleteFirstPass=!0,n.firstCreatePass=!1),i}finally{t[2]&=-5,Rl()}}function Ss(n,t,e,i){const r=t[2];if(256==(256&r))return;Il(t);const s=Tl();try{j_(t),function $_(n){return te.lFrame.bindingIndex=n}(n.bindingStartIndex),null!==e&&Sy(n,t,e,2,i);const o=3==(3&r);if(!s)if(o){const c=n.preOrderCheckHooks;null!==c&&Pl(t,c,null)}else{const c=n.preOrderHooks;null!==c&&Fl(t,c,0,null),Yu(t,0)}if(function SR(n){for(let t=Ch(n);null!==t;t=Dh(t)){if(!t[2])continue;const e=t[9];for(let i=0;i<e.length;i++){const r=e[i],s=r[3];0==(1024&r[2])&&zu(s,1),r[2]|=1024}}}(t),function ER(n){for(let t=Ch(n);null!==t;t=Dh(t))for(let e=10;e<t.length;e++){const i=t[e],r=i[1];ju(i)&&Ss(r,i,r.template,i[8])}}(t),null!==n.contentQueries&&Ey(n,t),!s)if(o){const c=n.contentCheckHooks;null!==c&&Pl(t,c)}else{const c=n.contentHooks;null!==c&&Fl(t,c,1),Yu(t,1)}!function oR(n,t){const e=n.hostBindingOpCodes;if(null!==e)try{for(let i=0;i<e.length;i++){const r=e[i];if(r<0)Zi(~r);else{const s=r,o=e[++i],a=e[++i];PT(o,s),a(2,t[s])}}}finally{Zi(-1)}}(n,t);const a=n.components;null!==a&&function aR(n,t){for(let e=0;e<t.length;e++)kR(n,t[e])}(t,a);const l=n.viewQuery;if(null!==l&&Zh(2,l,i),!s)if(o){const c=n.viewCheckHooks;null!==c&&Pl(t,c)}else{const c=n.viewHooks;null!==c&&Fl(t,c,2),Yu(t,2)}!0===n.firstUpdatePass&&(n.firstUpdatePass=!1),s||(t[2]&=-73),1024&t[2]&&(t[2]&=-1025,zu(t[3],-1))}finally{Rl()}}function cR(n,t,e,i){const r=t[10],s=!Tl(),o=H_(t);try{s&&!o&&r.begin&&r.begin(),o&&Jo(n,t,i),Ss(n,t,e,i)}finally{s&&!o&&r.end&&r.end()}}function Sy(n,t,e,i,r){const s=jt(),o=2&i;try{Zi(-1),o&&t.length>20&&my(n,t,20,Tl()),e(i,r)}finally{Zi(s)}}function ky(n,t,e){if(Ou(t)){const r=t.directiveEnd;for(let s=t.directiveStart;s<r;s++){const o=n.data[s];o.contentQueries&&o.contentQueries(1,e[s],s)}}}function Uh(n,t,e){!z_()||(function vR(n,t,e,i){const r=e.directiveStart,s=e.directiveEnd;n.firstCreatePass||No(e,t),Ft(i,t);const o=e.initialInputs;for(let a=r;a<s;a++){const l=n.data[a],c=Hn(l);c&&wR(t,e,l);const d=Lo(t,n,a,e);Ft(d,t),null!==o&&MR(0,a-r,d,l,0,o),c&&(rn(e.index,t)[8]=d)}}(n,t,e,yn(e,t)),128==(128&e.flags)&&function yR(n,t,e){const i=e.directiveStart,r=e.directiveEnd,o=e.index,a=function FT(){return te.lFrame.currentDirectiveIndex}();try{Zi(o);for(let l=i;l<r;l++){const c=n.data[l],d=t[l];Gu(l),(null!==c.hostBindings||0!==c.hostVars||null!==c.hostAttrs)&&Ny(c,d)}}finally{Zi(-1),Gu(a)}}(n,t,e))}function $h(n,t,e=yn){const i=t.localNames;if(null!==i){let r=t.index+1;for(let s=0;s<i.length;s+=2){const o=i[s+1],a=-1===o?e(t,n):n[o];n[r++]=a}}}function Ty(n){const t=n.tView;return null===t||t.incompleteFirstPass?n.tView=nc(1,null,n.template,n.decls,n.vars,n.directiveDefs,n.pipeDefs,n.viewQuery,n.schemas,n.consts):t}function nc(n,t,e,i,r,s,o,a,l,c){const d=20+i,u=d+r,h=function dR(n,t){const e=[];for(let i=0;i<t;i++)e.push(i<n?null:se);return e}(d,u),p=\"function\"==typeof c?c():c;return h[1]={type:n,blueprint:h,template:e,queries:null,viewQuery:a,declTNode:t,data:h.slice().fill(null,d),bindingStartIndex:d,expandoStartIndex:u,hostBindingOpCodes:null,firstCreatePass:!0,firstUpdatePass:!0,staticViewQueries:!1,staticContentQueries:!1,preOrderHooks:null,preOrderCheckHooks:null,contentHooks:null,contentCheckHooks:null,viewHooks:null,viewCheckHooks:null,destroyHooks:null,cleanup:null,contentQueries:null,components:null,directiveRegistry:\"function\"==typeof s?s():s,pipeRegistry:\"function\"==typeof o?o():o,firstChild:null,schemas:l,consts:p,incompleteFirstPass:!1}}function Ry(n,t,e,i){const r=zy(t);null===e?r.push(i):(r.push(e),n.firstCreatePass&&Uy(n).push(i,r.length-1))}function Oy(n,t,e){for(let i in n)if(n.hasOwnProperty(i)){const r=n[i];(e=null===e?{}:e).hasOwnProperty(i)?e[i].push(t,r):e[i]=[t,r]}return e}function ln(n,t,e,i,r,s,o,a){const l=yn(t,e);let d,c=t.inputs;!a&&null!=c&&(d=c[i])?(Wy(n,e,d,i,r),El(t)&&function fR(n,t){const e=rn(t,n);16&e[2]||(e[2]|=64)}(e,t.index)):3&t.type&&(i=function pR(n){return\"class\"===n?\"className\":\"for\"===n?\"htmlFor\":\"formaction\"===n?\"formAction\":\"innerHtml\"===n?\"innerHTML\":\"readonly\"===n?\"readOnly\":\"tabindex\"===n?\"tabIndex\":n}(i),r=null!=o?o(r,t.value||\"\",i):r,et(s)?s.setProperty(l,i,r):Ku(i)||(l.setProperty?l.setProperty(i,r):l[i]=r))}function Gh(n,t,e,i){let r=!1;if(z_()){const s=function bR(n,t,e){const i=n.directiveRegistry;let r=null;if(i)for(let s=0;s<i.length;s++){const o=i[s];py(e,o.selectors,!1)&&(r||(r=[]),Hl(No(e,t),n,o.type),Hn(o)?(Ly(n,e),r.unshift(o)):r.push(o))}return r}(n,t,e),o=null===i?null:{\"\":-1};if(null!==s){r=!0,By(e,n.data.length,s.length);for(let d=0;d<s.length;d++){const u=s[d];u.providersResolver&&u.providersResolver(u)}let a=!1,l=!1,c=Es(n,t,s.length,null);for(let d=0;d<s.length;d++){const u=s[d];e.mergedAttrs=Ll(e.mergedAttrs,u.hostAttrs),Vy(n,e,t,c,u),DR(c,u,o),null!==u.contentQueries&&(e.flags|=8),(null!==u.hostBindings||null!==u.hostAttrs||0!==u.hostVars)&&(e.flags|=128);const h=u.type.prototype;!a&&(h.ngOnChanges||h.ngOnInit||h.ngDoCheck)&&((n.preOrderHooks||(n.preOrderHooks=[])).push(e.index),a=!0),!l&&(h.ngOnChanges||h.ngDoCheck)&&((n.preOrderCheckHooks||(n.preOrderCheckHooks=[])).push(e.index),l=!0),c++}!function hR(n,t){const i=t.directiveEnd,r=n.data,s=t.attrs,o=[];let a=null,l=null;for(let c=t.directiveStart;c<i;c++){const d=r[c],u=d.inputs,h=null===s||hy(t)?null:xR(u,s);o.push(h),a=Oy(u,c,a),l=Oy(d.outputs,c,l)}null!==a&&(a.hasOwnProperty(\"class\")&&(t.flags|=16),a.hasOwnProperty(\"style\")&&(t.flags|=32)),t.initialInputs=o,t.inputs=a,t.outputs=l}(n,e)}o&&function CR(n,t,e){if(t){const i=n.localNames=[];for(let r=0;r<t.length;r+=2){const s=e[t[r+1]];if(null==s)throw new H(-301,!1);i.push(t[r],s)}}}(e,i,o)}return e.mergedAttrs=Ll(e.mergedAttrs,e.attrs),r}function Fy(n,t,e,i,r,s){const o=s.hostBindings;if(o){let a=n.hostBindingOpCodes;null===a&&(a=n.hostBindingOpCodes=[]);const l=~t.index;(function _R(n){let t=n.length;for(;t>0;){const e=n[--t];if(\"number\"==typeof e&&e<0)return e}return 0})(a)!=l&&a.push(l),a.push(i,r,o)}}function Ny(n,t){null!==n.hostBindings&&n.hostBindings(1,t)}function Ly(n,t){t.flags|=2,(n.components||(n.components=[])).push(t.index)}function DR(n,t,e){if(e){if(t.exportAs)for(let i=0;i<t.exportAs.length;i++)e[t.exportAs[i]]=n;Hn(t)&&(e[\"\"]=n)}}function By(n,t,e){n.flags|=1,n.directiveStart=t,n.directiveEnd=t+e,n.providerIndexes=t}function Vy(n,t,e,i,r){n.data[i]=r;const s=r.factory||(r.factory=Cr(r.type)),o=new Po(s,Hn(r),null);n.blueprint[i]=o,e[i]=o,Fy(n,t,0,i,Es(n,e,r.hostVars,se),r)}function wR(n,t,e){const i=yn(t,n),r=Ty(e),s=n[10],o=ic(n,Xo(n,r,null,e.onPush?64:16,i,t,s,s.createRenderer(i,e),null,null));n[t.index]=o}function ui(n,t,e,i,r,s){const o=yn(n,t);!function Wh(n,t,e,i,r,s,o){if(null==s)et(n)?n.removeAttribute(t,r,e):t.removeAttribute(r);else{const a=null==o?re(s):o(s,i||\"\",r);et(n)?n.setAttribute(t,r,a,e):e?t.setAttributeNS(e,r,a):t.setAttribute(r,a)}}(t[11],o,s,n.value,e,i,r)}function MR(n,t,e,i,r,s){const o=s[t];if(null!==o){const a=i.setInput;for(let l=0;l<o.length;){const c=o[l++],d=o[l++],u=o[l++];null!==a?i.setInput(e,u,c,d):e[d]=u}}}function xR(n,t){let e=null,i=0;for(;i<t.length;){const r=t[i];if(0!==r)if(5!==r){if(\"number\"==typeof r)break;n.hasOwnProperty(r)&&(null===e&&(e=[]),e.push(r,n[r],t[i+1])),i+=2}else i+=2;else i+=4}return e}function Hy(n,t,e,i){return new Array(n,!0,!1,t,null,0,i,e,null,null)}function kR(n,t){const e=rn(t,n);if(ju(e)){const i=e[1];80&e[2]?Ss(i,e,i.template,e[8]):e[5]>0&&qh(e)}}function qh(n){for(let i=Ch(n);null!==i;i=Dh(i))for(let r=10;r<i.length;r++){const s=i[r];if(1024&s[2]){const o=s[1];Ss(o,s,o.template,s[8])}else s[5]>0&&qh(s)}const e=n[1].components;if(null!==e)for(let i=0;i<e.length;i++){const r=rn(e[i],n);ju(r)&&r[5]>0&&qh(r)}}function TR(n,t){const e=rn(t,n),i=e[1];(function AR(n,t){for(let e=t.length;e<n.blueprint.length;e++)t.push(n.blueprint[e])})(i,e),Jo(i,e,e[8])}function ic(n,t){return n[13]?n[14][4]=t:n[13]=t,n[14]=t,t}function Yh(n){for(;n;){n[2]|=64;const t=Ko(n);if(uT(n)&&!t)return n;n=t}return null}function Kh(n,t,e){const i=t[10];i.begin&&i.begin();try{Ss(n,t,n.template,e)}catch(r){throw Gy(t,r),r}finally{i.end&&i.end()}}function jy(n){!function Qh(n){for(let t=0;t<n.components.length;t++){const e=n.components[t],i=gh(e),r=i[1];cR(r,i,r.template,e)}}(n[8])}function Zh(n,t,e){qu(0),t(n,e)}const PR=(()=>Promise.resolve(null))();function zy(n){return n[7]||(n[7]=[])}function Uy(n){return n.cleanup||(n.cleanup=[])}function $y(n,t,e){return(null===n||Hn(n))&&(e=function MT(n){for(;Array.isArray(n);){if(\"object\"==typeof n[1])return n;n=n[0]}return null}(e[t.index])),e[11]}function Gy(n,t){const e=n[9],i=e?e.get(Mr,null):null;i&&i.handleError(t)}function Wy(n,t,e,i,r){for(let s=0;s<e.length;){const o=e[s++],a=e[s++],l=t[o],c=n.data[o];null!==c.setInput?c.setInput(l,r,i,a):l[a]=r}}function Ai(n,t,e){const i=kl(t,n);!function Qv(n,t,e){et(n)?n.setValue(t,e):t.textContent=e}(n[11],i,e)}function rc(n,t,e){let i=e?n.styles:null,r=e?n.classes:null,s=0;if(null!==t)for(let o=0;o<t.length;o++){const a=t[o];\"number\"==typeof a?s=a:1==s?r=Mu(r,a):2==s&&(i=Mu(i,a+\": \"+t[++o]+\";\"))}e?n.styles=i:n.stylesWithoutHost=i,e?n.classes=r:n.classesWithoutHost=r}const Xh=new b(\"INJECTOR\",-1);class qy{get(t,e=jo){if(e===jo){const i=new Error(`NullInjectorError: No provider for ${Re(t)}!`);throw i.name=\"NullInjectorError\",i}return e}}const Jh=new b(\"Set Injector scope.\"),ea={},LR={};let ep;function Yy(){return void 0===ep&&(ep=new qy),ep}function Qy(n,t=null,e=null,i){const r=Ky(n,t,e,i);return r._resolveInjectorDefTypes(),r}function Ky(n,t=null,e=null,i){return new BR(n,e,t||Yy(),i)}class BR{constructor(t,e,i,r=null){this.parent=i,this.records=new Map,this.injectorDefTypes=new Set,this.onDestroy=new Set,this._destroyed=!1;const s=[];e&&ai(e,a=>this.processProvider(a,t,e)),ai([t],a=>this.processInjectorType(a,[],s)),this.records.set(Xh,ks(void 0,this));const o=this.records.get(Jh);this.scope=null!=o?o.value:null,this.source=r||(\"object\"==typeof t?null:Re(t))}get destroyed(){return this._destroyed}destroy(){this.assertNotDestroyed(),this._destroyed=!0;try{this.onDestroy.forEach(t=>t.ngOnDestroy())}finally{this.records.clear(),this.onDestroy.clear(),this.injectorDefTypes.clear()}}get(t,e=jo,i=ee.Default){this.assertNotDestroyed();const r=vv(this),s=qi(void 0);try{if(!(i&ee.SkipSelf)){let a=this.records.get(t);if(void 0===a){const l=function WR(n){return\"function\"==typeof n||\"object\"==typeof n&&n instanceof b}(t)&&Eu(t);a=l&&this.injectableDefInScope(l)?ks(tp(t),ea):null,this.records.set(t,a)}if(null!=a)return this.hydrate(t,a)}return(i&ee.Self?Yy():this.parent).get(t,e=i&ee.Optional&&e===jo?null:e)}catch(o){if(\"NullInjectorError\"===o.name){if((o[$l]=o[$l]||[]).unshift(Re(t)),r)throw o;return function _A(n,t,e,i){const r=n[$l];throw t[_v]&&r.unshift(t[_v]),n.message=function vA(n,t,e,i=null){n=n&&\"\\n\"===n.charAt(0)&&\"\\u0275\"==n.charAt(1)?n.substr(2):n;let r=Re(t);if(Array.isArray(t))r=t.map(Re).join(\" -> \");else if(\"object\"==typeof t){let s=[];for(let o in t)if(t.hasOwnProperty(o)){let a=t[o];s.push(o+\":\"+(\"string\"==typeof a?JSON.stringify(a):Re(a)))}r=`{${s.join(\", \")}}`}return`${e}${i?\"(\"+i+\")\":\"\"}[${r}]: ${n.replace(hA,\"\\n \")}`}(\"\\n\"+n.message,r,e,i),n.ngTokenPath=r,n[$l]=null,n}(o,t,\"R3InjectorError\",this.source)}throw o}finally{qi(s),vv(r)}}_resolveInjectorDefTypes(){this.injectorDefTypes.forEach(t=>this.get(t))}toString(){const t=[];return this.records.forEach((i,r)=>t.push(Re(r))),`R3Injector[${t.join(\", \")}]`}assertNotDestroyed(){if(this._destroyed)throw new H(205,!1)}processInjectorType(t,e,i){if(!(t=le(t)))return!1;let r=S_(t);const s=null==r&&t.ngModule||void 0,o=void 0===s?t:s,a=-1!==i.indexOf(o);if(void 0!==s&&(r=S_(s)),null==r)return!1;if(null!=r.imports&&!a){let d;i.push(o);try{ai(r.imports,u=>{this.processInjectorType(u,e,i)&&(void 0===d&&(d=[]),d.push(u))})}finally{}if(void 0!==d)for(let u=0;u<d.length;u++){const{ngModule:h,providers:p}=d[u];ai(p,m=>this.processProvider(m,h,p||Ne))}}this.injectorDefTypes.add(o);const l=Cr(o)||(()=>new o);this.records.set(o,ks(l,ea));const c=r.providers;if(null!=c&&!a){const d=t;ai(c,u=>this.processProvider(u,d,c))}return void 0!==s&&void 0!==t.providers}processProvider(t,e,i){let r=Ts(t=le(t))?t:le(t&&t.provide);const s=function HR(n,t,e){return Xy(n)?ks(void 0,n.useValue):ks(Zy(n),ea)}(t);if(Ts(t)||!0!==t.multi)this.records.get(r);else{let o=this.records.get(r);o||(o=ks(void 0,ea,!0),o.factory=()=>oh(o.multi),this.records.set(r,o)),r=t,o.multi.push(t)}this.records.set(r,s)}hydrate(t,e){return e.value===ea&&(e.value=LR,e.value=e.factory()),\"object\"==typeof e.value&&e.value&&function GR(n){return null!==n&&\"object\"==typeof n&&\"function\"==typeof n.ngOnDestroy}(e.value)&&this.onDestroy.add(e.value),e.value}injectableDefInScope(t){if(!t.providedIn)return!1;const e=le(t.providedIn);return\"string\"==typeof e?\"any\"===e||e===this.scope:this.injectorDefTypes.has(e)}}function tp(n){const t=Eu(n),e=null!==t?t.factory:Cr(n);if(null!==e)return e;if(n instanceof b)throw new H(204,!1);if(n instanceof Function)return function VR(n){const t=n.length;if(t>0)throw Ho(t,\"?\"),new H(204,!1);const e=function Xk(n){const t=n&&(n[Cl]||n[k_]);if(t){const e=function Jk(n){if(n.hasOwnProperty(\"name\"))return n.name;const t=(\"\"+n).match(/^function\\s*([^\\s(]+)/);return null===t?\"\":t[1]}(n);return console.warn(`DEPRECATED: DI is instantiating a token \"${e}\" that inherits its @Injectable decorator but does not provide one itself.\\nThis will become an error in a future version of Angular. Please add @Injectable() to the \"${e}\" class.`),t}return null}(n);return null!==e?()=>e.factory(n):()=>new n}(n);throw new H(204,!1)}function Zy(n,t,e){let i;if(Ts(n)){const r=le(n);return Cr(r)||tp(r)}if(Xy(n))i=()=>le(n.useValue);else if(function zR(n){return!(!n||!n.useFactory)}(n))i=()=>n.useFactory(...oh(n.deps||[]));else if(function jR(n){return!(!n||!n.useExisting)}(n))i=()=>y(le(n.useExisting));else{const r=le(n&&(n.useClass||n.provide));if(!function $R(n){return!!n.deps}(n))return Cr(r)||tp(r);i=()=>new r(...oh(n.deps))}return i}function ks(n,t,e=!1){return{factory:n,value:t,multi:e?[]:void 0}}function Xy(n){return null!==n&&\"object\"==typeof n&&fA in n}function Ts(n){return\"function\"==typeof n}let dt=(()=>{class n{static create(e,i){var r;if(Array.isArray(e))return Qy({name:\"\"},i,e,\"\");{const s=null!==(r=e.name)&&void 0!==r?r:\"\";return Qy({name:s},e.parent,e.providers,s)}}}return n.THROW_IF_NOT_FOUND=jo,n.NULL=new qy,n.\\u0275prov=k({token:n,providedIn:\"any\",factory:()=>y(Xh)}),n.__NG_ELEMENT_ID__=-1,n})();function e1(n,t){Ol(gh(n)[1],gt())}function E(n){let t=function db(n){return Object.getPrototypeOf(n.prototype).constructor}(n.type),e=!0;const i=[n];for(;t;){let r;if(Hn(n))r=t.\\u0275cmp||t.\\u0275dir;else{if(t.\\u0275cmp)throw new H(903,\"\");r=t.\\u0275dir}if(r){if(e){i.push(r);const o=n;o.inputs=rp(n.inputs),o.declaredInputs=rp(n.declaredInputs),o.outputs=rp(n.outputs);const a=r.hostBindings;a&&s1(n,a);const l=r.viewQuery,c=r.contentQueries;if(l&&n1(n,l),c&&r1(n,c),wu(n.inputs,r.inputs),wu(n.declaredInputs,r.declaredInputs),wu(n.outputs,r.outputs),Hn(r)&&r.data.animation){const d=n.data;d.animation=(d.animation||[]).concat(r.data.animation)}}const s=r.features;if(s)for(let o=0;o<s.length;o++){const a=s[o];a&&a.ngInherit&&a(n),a===E&&(e=!1)}}t=Object.getPrototypeOf(t)}!function t1(n){let t=0,e=null;for(let i=n.length-1;i>=0;i--){const r=n[i];r.hostVars=t+=r.hostVars,r.hostAttrs=Ll(r.hostAttrs,e=Ll(e,r.hostAttrs))}}(i)}function rp(n){return n===os?{}:n===Ne?[]:n}function n1(n,t){const e=n.viewQuery;n.viewQuery=e?(i,r)=>{t(i,r),e(i,r)}:t}function r1(n,t){const e=n.contentQueries;n.contentQueries=e?(i,r,s)=>{t(i,r,s),e(i,r,s)}:t}function s1(n,t){const e=n.hostBindings;n.hostBindings=e?(i,r)=>{t(i,r),e(i,r)}:t}let sc=null;function As(){if(!sc){const n=Oe.Symbol;if(n&&n.iterator)sc=n.iterator;else{const t=Object.getOwnPropertyNames(Map.prototype);for(let e=0;e<t.length;++e){const i=t[e];\"entries\"!==i&&\"size\"!==i&&Map.prototype[i]===Map.prototype.entries&&(sc=i)}}}return sc}function ta(n){return!!sp(n)&&(Array.isArray(n)||!(n instanceof Map)&&As()in n)}function sp(n){return null!==n&&(\"function\"==typeof n||\"object\"==typeof n)}function Nt(n,t,e){return!Object.is(n[t],e)&&(n[t]=e,!0)}function Z(n,t,e,i){const r=w();return Nt(r,hs(),t)&&(Me(),ui(tt(),r,n,t,e,i)),Z}function Rs(n,t,e,i){return Nt(n,hs(),e)?t+re(e)+i:se}function Ee(n,t,e,i,r,s,o,a){const l=w(),c=Me(),d=n+20,u=c.firstCreatePass?function h1(n,t,e,i,r,s,o,a,l){const c=t.consts,d=xs(t,n,4,o||null,Ki(c,a));Gh(t,e,d,Ki(c,l)),Ol(t,d);const u=d.tViews=nc(2,d,i,r,s,t.directiveRegistry,t.pipeRegistry,null,t.schemas,c);return null!==t.queries&&(t.queries.template(t,d),u.queries=t.queries.embeddedTView(d)),d}(d,c,l,t,e,i,r,s,o):c.data[d];oi(u,!1);const h=l[11].createComment(\"\");Zl(c,l,h,u),Ft(h,l),ic(l,l[d]=Hy(h,l,h,u)),Sl(u)&&Uh(c,l,u),null!=o&&$h(l,u,a)}function wn(n){return function us(n,t){return n[t]}(function RT(){return te.lFrame.contextLView}(),20+n)}function f(n,t=ee.Default){const e=w();return null===e?y(n,t):av(gt(),e,le(n),t)}function Sr(){throw new Error(\"invalid\")}function N(n,t,e){const i=w();return Nt(i,hs(),t)&&ln(Me(),tt(),i,n,t,i[11],e,!1),N}function dp(n,t,e,i,r){const o=r?\"class\":\"style\";Wy(n,e,t.inputs[o],o,i)}function x(n,t,e,i){const r=w(),s=Me(),o=20+n,a=r[11],l=r[o]=Mh(a,t,function jT(){return te.lFrame.currentNamespace}()),c=s.firstCreatePass?function O1(n,t,e,i,r,s,o){const a=t.consts,c=xs(t,n,2,r,Ki(a,s));return Gh(t,e,c,Ki(a,o)),null!==c.attrs&&rc(c,c.attrs,!1),null!==c.mergedAttrs&&rc(c,c.mergedAttrs,!0),null!==t.queries&&t.queries.elementStart(t,c),c}(o,s,r,0,t,e,i):s.data[o];oi(c,!0);const d=c.mergedAttrs;null!==d&&Nl(a,l,d);const u=c.classes;null!==u&&Ah(a,l,u);const h=c.styles;return null!==h&&cy(a,l,h),64!=(64&c.flags)&&Zl(s,r,l,c),0===function ST(){return te.lFrame.elementDepthCount}()&&Ft(l,r),function kT(){te.lFrame.elementDepthCount++}(),Sl(c)&&(Uh(s,r,c),ky(s,c,r)),null!==i&&$h(r,c),x}function S(){let n=gt();Uu()?$u():(n=n.parent,oi(n,!1));const t=n;!function TT(){te.lFrame.elementDepthCount--}();const e=Me();return e.firstCreatePass&&(Ol(e,n),Ou(n)&&e.queries.elementEnd(n)),null!=t.classesWithoutHost&&function WT(n){return 0!=(16&n.flags)}(t)&&dp(e,t,w(),t.classesWithoutHost,!0),null!=t.stylesWithoutHost&&function qT(n){return 0!=(32&n.flags)}(t)&&dp(e,t,w(),t.stylesWithoutHost,!1),S}function Le(n,t,e,i){return x(n,t,e,i),S(),Le}function kr(n,t,e){const i=w(),r=Me(),s=n+20,o=r.firstCreatePass?function P1(n,t,e,i,r){const s=t.consts,o=Ki(s,i),a=xs(t,n,8,\"ng-container\",o);return null!==o&&rc(a,o,!0),Gh(t,e,a,Ki(s,r)),null!==t.queries&&t.queries.elementStart(t,a),a}(s,r,i,t,e):r.data[s];oi(o,!0);const a=i[s]=i[11].createComment(\"\");return Zl(r,i,a,o),Ft(a,i),Sl(o)&&(Uh(r,i,o),ky(r,o,i)),null!=e&&$h(i,o),kr}function Tr(){let n=gt();const t=Me();return Uu()?$u():(n=n.parent,oi(n,!1)),t.firstCreatePass&&(Ol(t,n),Ou(n)&&t.queries.elementEnd(n)),Tr}function ia(){return w()}function ra(n){return!!n&&\"function\"==typeof n.then}const up=function Ab(n){return!!n&&\"function\"==typeof n.subscribe};function J(n,t,e,i){const r=w(),s=Me(),o=gt();return Ib(s,r,r[11],o,n,t,!!e,i),J}function hp(n,t){const e=gt(),i=w(),r=Me();return Ib(r,i,$y(Wu(r.data),e,i),e,n,t,!1),hp}function Ib(n,t,e,i,r,s,o,a){const l=Sl(i),d=n.firstCreatePass&&Uy(n),u=t[8],h=zy(t);let p=!0;if(3&i.type||a){const _=yn(i,t),D=a?a(_):_,v=h.length,M=a?V=>a(ct(V[i.index])):i.index;if(et(e)){let V=null;if(!a&&l&&(V=function F1(n,t,e,i){const r=n.cleanup;if(null!=r)for(let s=0;s<r.length-1;s+=2){const o=r[s];if(o===e&&r[s+1]===i){const a=t[7],l=r[s+2];return a.length>l?a[l]:null}\"string\"==typeof o&&(s+=2)}return null}(n,t,r,i.index)),null!==V)(V.__ngLastListenerFn__||V).__ngNextListenerFn__=s,V.__ngLastListenerFn__=s,p=!1;else{s=pp(i,t,u,s,!1);const he=e.listen(D,r,s);h.push(s,he),d&&d.push(r,M,v,v+1)}}else s=pp(i,t,u,s,!0),D.addEventListener(r,s,o),h.push(s),d&&d.push(r,M,v,o)}else s=pp(i,t,u,s,!1);const m=i.outputs;let g;if(p&&null!==m&&(g=m[r])){const _=g.length;if(_)for(let D=0;D<_;D+=2){const We=t[g[D]][g[D+1]].subscribe(s),Ze=h.length;h.push(s,We),d&&d.push(r,i.index,Ze,-(Ze+1))}}}function Rb(n,t,e,i){try{return!1!==e(i)}catch(r){return Gy(n,r),!1}}function pp(n,t,e,i,r){return function s(o){if(o===Function)return i;const a=2&n.flags?rn(n.index,t):t;0==(32&t[2])&&Yh(a);let l=Rb(t,0,i,o),c=s.__ngNextListenerFn__;for(;c;)l=Rb(t,0,c,o)&&l,c=c.__ngNextListenerFn__;return r&&!1===l&&(o.preventDefault(),o.returnValue=!1),l}}function Be(n=1){return function LT(n){return(te.lFrame.contextLView=function BT(n,t){for(;n>0;)t=t[15],n--;return t}(n,te.lFrame.contextLView))[8]}(n)}function N1(n,t){let e=null;const i=function UI(n){const t=n.attrs;if(null!=t){const e=t.indexOf(5);if(0==(1&e))return t[e+1]}return null}(n);for(let r=0;r<t.length;r++){const s=t[r];if(\"*\"!==s){if(null===i?py(n,s,!0):WI(i,s))return r}else e=r}return e}function Lt(n){const t=w()[16][6];if(!t.projection){const i=t.projection=Ho(n?n.length:1,null),r=i.slice();let s=t.child;for(;null!==s;){const o=n?N1(s,n):0;null!==o&&(r[o]?r[o].projectionNext=s:i[o]=s,r[o]=s),s=s.next}}}function Pe(n,t=0,e){const i=w(),r=Me(),s=xs(r,20+n,16,null,e||null);null===s.projection&&(s.projection=t),$u(),64!=(64&s.flags)&&function NI(n,t,e){ly(t[11],0,t,e,Xv(n,e,t),ny(e.parent||t[6],e,t))}(r,i,s)}function zb(n,t,e,i,r){const s=n[e+1],o=null===t;let a=i?zn(s):Ti(s),l=!1;for(;0!==a&&(!1===l||o);){const d=n[a+1];V1(n[a],t)&&(l=!0,n[a+1]=i?Oh(d):Ih(d)),a=i?zn(d):Ti(d)}l&&(n[e+1]=i?Ih(s):Oh(s))}function V1(n,t){return null===n||null==t||(Array.isArray(n)?n[1]:n)===t||!(!Array.isArray(n)||\"string\"!=typeof t)&&bs(n,t)>=0}const vt={textEnd:0,key:0,keyEnd:0,value:0,valueEnd:0};function Ub(n){return n.substring(vt.key,vt.keyEnd)}function $b(n,t){const e=vt.textEnd;return e===t?-1:(t=vt.keyEnd=function U1(n,t,e){for(;t<e&&n.charCodeAt(t)>32;)t++;return t}(n,vt.key=t,e),js(n,t,e))}function js(n,t,e){for(;t<e&&n.charCodeAt(t)<=32;)t++;return t}function $n(n,t,e){return Gn(n,t,e,!1),$n}function Ae(n,t){return Gn(n,t,null,!0),Ae}function fi(n,t){for(let e=function j1(n){return function Wb(n){vt.key=0,vt.keyEnd=0,vt.value=0,vt.valueEnd=0,vt.textEnd=n.length}(n),$b(n,js(n,0,vt.textEnd))}(t);e>=0;e=$b(t,e))sn(n,Ub(t),!0)}function Gn(n,t,e,i){const r=w(),s=Me(),o=ki(2);s.firstUpdatePass&&Kb(s,n,o,i),t!==se&&Nt(r,o,t)&&Xb(s,s.data[jt()],r,r[11],n,r[o+1]=function eO(n,t){return null==n||(\"string\"==typeof t?n+=t:\"object\"==typeof n&&(n=Re(on(n)))),n}(t,e),i,o)}function Qb(n,t){return t>=n.expandoStartIndex}function Kb(n,t,e,i){const r=n.data;if(null===r[e+1]){const s=r[jt()],o=Qb(n,e);eC(s,i)&&null===t&&!o&&(t=!1),t=function Y1(n,t,e,i){const r=Wu(n);let s=i?t.residualClasses:t.residualStyles;if(null===r)0===(i?t.classBindings:t.styleBindings)&&(e=sa(e=mp(null,n,t,e,i),t.attrs,i),s=null);else{const o=t.directiveStylingLast;if(-1===o||n[o]!==r)if(e=mp(r,n,t,e,i),null===s){let l=function Q1(n,t,e){const i=e?t.classBindings:t.styleBindings;if(0!==Ti(i))return n[zn(i)]}(n,t,i);void 0!==l&&Array.isArray(l)&&(l=mp(null,n,t,l[1],i),l=sa(l,t.attrs,i),function K1(n,t,e,i){n[zn(e?t.classBindings:t.styleBindings)]=i}(n,t,i,l))}else s=function Z1(n,t,e){let i;const r=t.directiveEnd;for(let s=1+t.directiveStylingLast;s<r;s++)i=sa(i,n[s].hostAttrs,e);return sa(i,t.attrs,e)}(n,t,i)}return void 0!==s&&(i?t.residualClasses=s:t.residualStyles=s),e}(r,s,t,i),function L1(n,t,e,i,r,s){let o=s?t.classBindings:t.styleBindings,a=zn(o),l=Ti(o);n[i]=e;let d,c=!1;if(Array.isArray(e)){const u=e;d=u[1],(null===d||bs(u,d)>0)&&(c=!0)}else d=e;if(r)if(0!==l){const h=zn(n[a+1]);n[i+1]=Jl(h,a),0!==h&&(n[h+1]=Rh(n[h+1],i)),n[a+1]=function KI(n,t){return 131071&n|t<<17}(n[a+1],i)}else n[i+1]=Jl(a,0),0!==a&&(n[a+1]=Rh(n[a+1],i)),a=i;else n[i+1]=Jl(l,0),0===a?a=i:n[l+1]=Rh(n[l+1],i),l=i;c&&(n[i+1]=Ih(n[i+1])),zb(n,d,i,!0),zb(n,d,i,!1),function B1(n,t,e,i,r){const s=r?n.residualClasses:n.residualStyles;null!=s&&\"string\"==typeof t&&bs(s,t)>=0&&(e[i+1]=Oh(e[i+1]))}(t,d,n,i,s),o=Jl(a,l),s?t.classBindings=o:t.styleBindings=o}(r,s,t,e,o,i)}}function mp(n,t,e,i,r){let s=null;const o=e.directiveEnd;let a=e.directiveStylingLast;for(-1===a?a=e.directiveStart:a++;a<o&&(s=t[a],i=sa(i,s.hostAttrs,r),s!==n);)a++;return null!==n&&(e.directiveStylingLast=a),i}function sa(n,t,e){const i=e?1:2;let r=-1;if(null!==t)for(let s=0;s<t.length;s++){const o=t[s];\"number\"==typeof o?r=o:r===i&&(Array.isArray(n)||(n=void 0===n?[]:[\"\",n]),sn(n,o,!!e||t[++s]))}return void 0===n?null:n}function Xb(n,t,e,i,r,s,o,a){if(!(3&t.type))return;const l=n.data,c=l[a+1];lc(function vy(n){return 1==(1&n)}(c)?Jb(l,t,e,r,Ti(c),o):void 0)||(lc(s)||function _y(n){return 2==(2&n)}(c)&&(s=Jb(l,null,e,r,a,o)),function BI(n,t,e,i,r){const s=et(n);if(t)r?s?n.addClass(e,i):e.classList.add(i):s?n.removeClass(e,i):e.classList.remove(i);else{let o=-1===i.indexOf(\"-\")?void 0:an.DashCase;if(null==r)s?n.removeStyle(e,i,o):e.style.removeProperty(i);else{const a=\"string\"==typeof r&&r.endsWith(\"!important\");a&&(r=r.slice(0,-10),o|=an.Important),s?n.setStyle(e,i,r,o):e.style.setProperty(i,r,a?\"important\":\"\")}}}(i,o,kl(jt(),e),r,s))}function Jb(n,t,e,i,r,s){const o=null===t;let a;for(;r>0;){const l=n[r],c=Array.isArray(l),d=c?l[1]:l,u=null===d;let h=e[r+1];h===se&&(h=u?Ne:void 0);let p=u?ih(h,i):d===i?h:void 0;if(c&&!lc(p)&&(p=ih(l,i)),lc(p)&&(a=p,o))return a;const m=n[r+1];r=o?zn(m):Ti(m)}if(null!==t){let l=s?t.residualClasses:t.residualStyles;null!=l&&(a=ih(l,i))}return a}function lc(n){return void 0!==n}function eC(n,t){return 0!=(n.flags&(t?16:32))}function we(n,t=\"\"){const e=w(),i=Me(),r=n+20,s=i.firstCreatePass?xs(i,r,1,t,null):i.data[r],o=e[r]=function wh(n,t){return et(n)?n.createText(t):n.createTextNode(t)}(e[11],t);Zl(i,e,o,s),oi(s,!1)}function Ut(n){return qn(\"\",n,\"\"),Ut}function qn(n,t,e){const i=w(),r=Rs(i,n,t,e);return r!==se&&Ai(i,jt(),r),qn}function cC(n,t,e){!function Wn(n,t,e,i){const r=Me(),s=ki(2);r.firstUpdatePass&&Kb(r,null,s,i);const o=w();if(e!==se&&Nt(o,s,e)){const a=r.data[jt()];if(eC(a,i)&&!Qb(r,s)){let l=i?a.classesWithoutHost:a.stylesWithoutHost;null!==l&&(e=Mu(l,e||\"\")),dp(r,a,o,e,i)}else!function J1(n,t,e,i,r,s,o,a){r===se&&(r=Ne);let l=0,c=0,d=0<r.length?r[0]:null,u=0<s.length?s[0]:null;for(;null!==d||null!==u;){const h=l<r.length?r[l+1]:void 0,p=c<s.length?s[c+1]:void 0;let g,m=null;d===u?(l+=2,c+=2,h!==p&&(m=u,g=p)):null===u||null!==d&&d<u?(l+=2,m=d):(c+=2,m=u,g=p),null!==m&&Xb(n,t,e,i,m,g,o,a),d=l<r.length?r[l]:null,u=c<s.length?s[c]:null}}(r,a,o,o[11],o[s+1],o[s+1]=function X1(n,t,e){if(null==e||\"\"===e)return Ne;const i=[],r=on(e);if(Array.isArray(r))for(let s=0;s<r.length;s++)n(i,r[s],!0);else if(\"object\"==typeof r)for(const s in r)r.hasOwnProperty(s)&&n(i,s,r[s]);else\"string\"==typeof r&&t(i,r);return i}(n,t,e),i,s)}}(sn,fi,Rs(w(),n,t,e),!0)}function Yn(n,t,e){const i=w();return Nt(i,hs(),t)&&ln(Me(),tt(),i,n,t,i[11],e,!0),Yn}function gp(n,t,e){const i=w();if(Nt(i,hs(),t)){const s=Me(),o=tt();ln(s,o,i,n,t,$y(Wu(s.data),o,i),e,!0)}return gp}const cc=\"en-US\";let CC=cc;function yp(n,t,e,i,r){if(n=le(n),Array.isArray(n))for(let s=0;s<n.length;s++)yp(n[s],t,e,i,r);else{const s=Me(),o=w();let a=Ts(n)?n:le(n.provide),l=Zy(n);const c=gt(),d=1048575&c.providerIndexes,u=c.directiveStart,h=c.providerIndexes>>20;if(Ts(n)||!n.multi){const p=new Po(l,r,f),m=Cp(a,t,r?d:d+h,u);-1===m?(Hl(No(c,o),s,a),bp(s,n,t.length),t.push(a),c.directiveStart++,c.directiveEnd++,r&&(c.providerIndexes+=1048576),e.push(p),o.push(p)):(e[m]=p,o[m]=p)}else{const p=Cp(a,t,d+h,u),m=Cp(a,t,d,d+h),g=p>=0&&e[p],_=m>=0&&e[m];if(r&&!_||!r&&!g){Hl(No(c,o),s,a);const D=function vP(n,t,e,i,r){const s=new Po(n,e,f);return s.multi=[],s.index=t,s.componentProviders=0,GC(s,r,i&&!e),s}(r?_P:gP,e.length,r,i,l);!r&&_&&(e[m].providerFactory=D),bp(s,n,t.length,0),t.push(a),c.directiveStart++,c.directiveEnd++,r&&(c.providerIndexes+=1048576),e.push(D),o.push(D)}else bp(s,n,p>-1?p:m,GC(e[r?m:p],l,!r&&i));!r&&i&&_&&e[m].componentProviders++}}}function bp(n,t,e,i){const r=Ts(t),s=function UR(n){return!!n.useClass}(t);if(r||s){const l=(s?le(t.useClass):t).prototype.ngOnDestroy;if(l){const c=n.destroyHooks||(n.destroyHooks=[]);if(!r&&t.multi){const d=c.indexOf(e);-1===d?c.push(e,[i,l]):c[d+1].push(i,l)}else c.push(e,l)}}}function GC(n,t,e){return e&&n.componentProviders++,n.multi.push(t)-1}function Cp(n,t,e,i){for(let r=e;r<i;r++)if(t[r]===n)return r;return-1}function gP(n,t,e,i){return Dp(this.multi,[])}function _P(n,t,e,i){const r=this.multi;let s;if(this.providerFactory){const o=this.providerFactory.componentProviders,a=Lo(e,e[1],this.providerFactory.index,i);s=a.slice(0,o),Dp(r,s);for(let l=o;l<a.length;l++)s.push(a[l])}else s=[],Dp(r,s);return s}function Dp(n,t){for(let e=0;e<n.length;e++)t.push((0,n[e])());return t}function L(n,t=[]){return e=>{e.providersResolver=(i,r)=>function mP(n,t,e){const i=Me();if(i.firstCreatePass){const r=Hn(n);yp(e,i.data,i.blueprint,r,!0),yp(t,i.data,i.blueprint,r,!1)}}(i,r?r(n):n,t)}}class WC{}class CP{resolveComponentFactory(t){throw function bP(n){const t=Error(`No component factory found for ${Re(n)}. Did you add it to @NgModule.entryComponents?`);return t.ngComponent=n,t}(t)}}let Ir=(()=>{class n{}return n.NULL=new CP,n})();function DP(){return $s(gt(),w())}function $s(n,t){return new W(yn(n,t))}let W=(()=>{class n{constructor(e){this.nativeElement=e}}return n.__NG_ELEMENT_ID__=DP,n})();function wP(n){return n instanceof W?n.nativeElement:n}class da{}let Ii=(()=>{class n{}return n.__NG_ELEMENT_ID__=()=>function xP(){const n=w(),e=rn(gt().index,n);return function MP(n){return n[11]}(si(e)?e:n)}(),n})(),EP=(()=>{class n{}return n.\\u0275prov=k({token:n,providedIn:\"root\",factory:()=>null}),n})();class Rr{constructor(t){this.full=t,this.major=t.split(\".\")[0],this.minor=t.split(\".\")[1],this.patch=t.split(\".\").slice(2).join(\".\")}}const SP=new Rr(\"13.3.0\"),wp={};function fc(n,t,e,i,r=!1){for(;null!==e;){const s=t[e.index];if(null!==s&&i.push(ct(s)),Vn(s))for(let a=10;a<s.length;a++){const l=s[a],c=l[1].firstChild;null!==c&&fc(l[1],l,c,i)}const o=e.type;if(8&o)fc(n,t,e.child,i);else if(32&o){const a=bh(e,t);let l;for(;l=a();)i.push(l)}else if(16&o){const a=oy(t,e);if(Array.isArray(a))i.push(...a);else{const l=Ko(t[16]);fc(l[1],l,a,i,!0)}}e=r?e.projectionNext:e.next}return i}class ua{constructor(t,e){this._lView=t,this._cdRefInjectingView=e,this._appRef=null,this._attachedToViewContainer=!1}get rootNodes(){const t=this._lView,e=t[1];return fc(e,t,e.firstChild,[])}get context(){return this._lView[8]}set context(t){this._lView[8]=t}get destroyed(){return 256==(256&this._lView[2])}destroy(){if(this._appRef)this._appRef.detachView(this);else if(this._attachedToViewContainer){const t=this._lView[3];if(Vn(t)){const e=t[8],i=e?e.indexOf(this):-1;i>-1&&(xh(t,i),zl(e,i))}this._attachedToViewContainer=!1}Zv(this._lView[1],this._lView)}onDestroy(t){Ry(this._lView[1],this._lView,null,t)}markForCheck(){Yh(this._cdRefInjectingView||this._lView)}detach(){this._lView[2]&=-129}reattach(){this._lView[2]|=128}detectChanges(){Kh(this._lView[1],this._lView,this.context)}checkNoChanges(){!function RR(n,t,e){Al(!0);try{Kh(n,t,e)}finally{Al(!1)}}(this._lView[1],this._lView,this.context)}attachToViewContainerRef(){if(this._appRef)throw new H(902,\"\");this._attachedToViewContainer=!0}detachFromAppRef(){this._appRef=null,function kI(n,t){Zo(n,t,t[11],2,null,null)}(this._lView[1],this._lView)}attachToAppRef(t){if(this._attachedToViewContainer)throw new H(902,\"\");this._appRef=t}}class kP extends ua{constructor(t){super(t),this._view=t}detectChanges(){jy(this._view)}checkNoChanges(){!function OR(n){Al(!0);try{jy(n)}finally{Al(!1)}}(this._view)}get context(){return null}}class YC extends Ir{constructor(t){super(),this.ngModule=t}resolveComponentFactory(t){const e=Ot(t);return new Mp(e,this.ngModule)}}function QC(n){const t=[];for(let e in n)n.hasOwnProperty(e)&&t.push({propName:n[e],templateName:e});return t}class Mp extends WC{constructor(t,e){super(),this.componentDef=t,this.ngModule=e,this.componentType=t.type,this.selector=function YI(n){return n.map(qI).join(\",\")}(t.selectors),this.ngContentSelectors=t.ngContentSelectors?t.ngContentSelectors:[],this.isBoundToModule=!!e}get inputs(){return QC(this.componentDef.inputs)}get outputs(){return QC(this.componentDef.outputs)}create(t,e,i,r){const s=(r=r||this.ngModule)?function AP(n,t){return{get:(e,i,r)=>{const s=n.get(e,wp,r);return s!==wp||i===wp?s:t.get(e,i,r)}}}(t,r.injector):t,o=s.get(da,V_),a=s.get(EP,null),l=o.createRenderer(null,this.componentDef),c=this.componentDef.selectors[0][0]||\"div\",d=i?function Iy(n,t,e){if(et(n))return n.selectRootElement(t,e===Ln.ShadowDom);let i=\"string\"==typeof t?n.querySelector(t):t;return i.textContent=\"\",i}(l,i,this.componentDef.encapsulation):Mh(o.createRenderer(null,this.componentDef),c,function TP(n){const t=n.toLowerCase();return\"svg\"===t?\"svg\":\"math\"===t?\"math\":null}(c)),u=this.componentDef.onPush?576:528,h=function cb(n,t){return{components:[],scheduler:n||CI,clean:PR,playerHandler:t||null,flags:0}}(),p=nc(0,null,null,1,0,null,null,null,null,null),m=Xo(null,p,h,u,null,null,o,l,a,s);let g,_;Il(m);try{const D=function ab(n,t,e,i,r,s){const o=e[1];e[20]=n;const l=xs(o,20,2,\"#host\",null),c=l.mergedAttrs=t.hostAttrs;null!==c&&(rc(l,c,!0),null!==n&&(Nl(r,n,c),null!==l.classes&&Ah(r,n,l.classes),null!==l.styles&&cy(r,n,l.styles)));const d=i.createRenderer(n,t),u=Xo(e,Ty(t),null,t.onPush?64:16,e[20],l,i,d,s||null,null);return o.firstCreatePass&&(Hl(No(l,e),o,t.type),Ly(o,l),By(l,e.length,1)),ic(e,u),e[20]=u}(d,this.componentDef,m,o,l);if(d)if(i)Nl(l,d,[\"ng-version\",SP.full]);else{const{attrs:v,classes:M}=function QI(n){const t=[],e=[];let i=1,r=2;for(;i<n.length;){let s=n[i];if(\"string\"==typeof s)2===r?\"\"!==s&&t.push(s,n[++i]):8===r&&e.push(s);else{if(!jn(r))break;r=s}i++}return{attrs:t,classes:e}}(this.componentDef.selectors[0]);v&&Nl(l,d,v),M&&M.length>0&&Ah(l,d,M.join(\" \"))}if(_=Hu(p,20),void 0!==e){const v=_.projection=[];for(let M=0;M<this.ngContentSelectors.length;M++){const V=e[M];v.push(null!=V?Array.from(V):null)}}g=function lb(n,t,e,i,r){const s=e[1],o=function gR(n,t,e){const i=gt();n.firstCreatePass&&(e.providersResolver&&e.providersResolver(e),Vy(n,i,t,Es(n,t,1,null),e));const r=Lo(t,n,i.directiveStart,i);Ft(r,t);const s=yn(i,t);return s&&Ft(s,t),r}(s,e,t);if(i.components.push(o),n[8]=o,r&&r.forEach(l=>l(o,t)),t.contentQueries){const l=gt();t.contentQueries(1,o,l.directiveStart)}const a=gt();return!s.firstCreatePass||null===t.hostBindings&&null===t.hostAttrs||(Zi(a.index),Fy(e[1],a,0,a.directiveStart,a.directiveEnd,t),Ny(t,o)),o}(D,this.componentDef,m,h,[e1]),Jo(p,m,null)}finally{Rl()}return new RP(this.componentType,g,$s(_,m),m,_)}}class RP extends class yP{}{constructor(t,e,i,r,s){super(),this.location=i,this._rootLView=r,this._tNode=s,this.instance=e,this.hostView=this.changeDetectorRef=new kP(r),this.componentType=t}get injector(){return new ms(this._tNode,this._rootLView)}destroy(){this.hostView.destroy()}onDestroy(t){this.hostView.onDestroy(t)}}class Ri{}class KC{}const Gs=new Map;class JC extends Ri{constructor(t,e){super(),this._parent=e,this._bootstrapComponents=[],this.injector=this,this.destroyCbs=[],this.componentFactoryResolver=new YC(this);const i=gn(t);this._bootstrapComponents=di(i.bootstrap),this._r3Injector=Ky(t,e,[{provide:Ri,useValue:this},{provide:Ir,useValue:this.componentFactoryResolver}],Re(t)),this._r3Injector._resolveInjectorDefTypes(),this.instance=this.get(t)}get(t,e=dt.THROW_IF_NOT_FOUND,i=ee.Default){return t===dt||t===Ri||t===Xh?this:this._r3Injector.get(t,e,i)}destroy(){const t=this._r3Injector;!t.destroyed&&t.destroy(),this.destroyCbs.forEach(e=>e()),this.destroyCbs=null}onDestroy(t){this.destroyCbs.push(t)}}class xp extends KC{constructor(t){super(),this.moduleType=t,null!==gn(t)&&function PP(n){const t=new Set;!function e(i){const r=gn(i,!0),s=r.id;null!==s&&(function ZC(n,t,e){if(t&&t!==e)throw new Error(`Duplicate module registered for ${n} - ${Re(t)} vs ${Re(t.name)}`)}(s,Gs.get(s),i),Gs.set(s,i));const o=di(r.imports);for(const a of o)t.has(a)||(t.add(a),e(a))}(n)}(t)}create(t){return new JC(this.moduleType,t)}}function Ep(n){return t=>{setTimeout(n,void 0,t)}}const $=class ZP extends O{constructor(t=!1){super(),this.__isAsync=t}emit(t){super.next(t)}subscribe(t,e,i){var r,s,o;let a=t,l=e||(()=>null),c=i;if(t&&\"object\"==typeof t){const u=t;a=null===(r=u.next)||void 0===r?void 0:r.bind(u),l=null===(s=u.error)||void 0===s?void 0:s.bind(u),c=null===(o=u.complete)||void 0===o?void 0:o.bind(u)}this.__isAsync&&(l=Ep(l),a&&(a=Ep(a)),c&&(c=Ep(c)));const d=super.subscribe({next:a,error:l,complete:c});return t instanceof ke&&t.add(d),d}};function XP(){return this._results[As()]()}class fa{constructor(t=!1){this._emitDistinctChangesOnly=t,this.dirty=!0,this._results=[],this._changesDetected=!1,this._changes=null,this.length=0,this.first=void 0,this.last=void 0;const e=As(),i=fa.prototype;i[e]||(i[e]=XP)}get changes(){return this._changes||(this._changes=new $)}get(t){return this._results[t]}map(t){return this._results.map(t)}filter(t){return this._results.filter(t)}find(t){return this._results.find(t)}reduce(t,e){return this._results.reduce(t,e)}forEach(t){this._results.forEach(t)}some(t){return this._results.some(t)}toArray(){return this._results.slice()}toString(){return this._results.toString()}reset(t,e){const i=this;i.dirty=!1;const r=bn(t);(this._changesDetected=!function iA(n,t,e){if(n.length!==t.length)return!1;for(let i=0;i<n.length;i++){let r=n[i],s=t[i];if(e&&(r=e(r),s=e(s)),s!==r)return!1}return!0}(i._results,r,e))&&(i._results=r,i.length=r.length,i.last=r[this.length-1],i.first=r[0])}notifyOnChanges(){this._changes&&(this._changesDetected||!this._emitDistinctChangesOnly)&&this._changes.emit(this)}setDirty(){this.dirty=!0}destroy(){this.changes.complete(),this.changes.unsubscribe()}}Symbol;let ut=(()=>{class n{}return n.__NG_ELEMENT_ID__=tF,n})();const JP=ut,eF=class extends JP{constructor(t,e,i){super(),this._declarationLView=t,this._declarationTContainer=e,this.elementRef=i}createEmbeddedView(t){const e=this._declarationTContainer.tViews,i=Xo(this._declarationLView,e,t,16,null,e.declTNode,null,null,null,null);i[17]=this._declarationLView[this._declarationTContainer.index];const s=this._declarationLView[19];return null!==s&&(i[19]=s.createEmbeddedView(e)),Jo(e,i,t),new ua(i)}};function tF(){return gc(gt(),w())}function gc(n,t){return 4&n.type?new eF(t,n,$s(n,t)):null}let st=(()=>{class n{}return n.__NG_ELEMENT_ID__=nF,n})();function nF(){return l0(gt(),w())}const iF=st,o0=class extends iF{constructor(t,e,i){super(),this._lContainer=t,this._hostTNode=e,this._hostLView=i}get element(){return $s(this._hostTNode,this._hostLView)}get injector(){return new ms(this._hostTNode,this._hostLView)}get parentInjector(){const t=Vl(this._hostTNode,this._hostLView);if(nv(t)){const e=fs(t,this._hostLView),i=ps(t);return new ms(e[1].data[i+8],e)}return new ms(null,this._hostLView)}clear(){for(;this.length>0;)this.remove(this.length-1)}get(t){const e=a0(this._lContainer);return null!==e&&e[t]||null}get length(){return this._lContainer.length-10}createEmbeddedView(t,e,i){const r=t.createEmbeddedView(e||{});return this.insert(r,i),r}createComponent(t,e,i,r,s){const o=t&&!function Vo(n){return\"function\"==typeof n}(t);let a;if(o)a=e;else{const u=e||{};a=u.index,i=u.injector,r=u.projectableNodes,s=u.ngModuleRef}const l=o?t:new Mp(Ot(t)),c=i||this.parentInjector;if(!s&&null==l.ngModule){const h=(o?c:this.parentInjector).get(Ri,null);h&&(s=h)}const d=l.create(c,r,void 0,s);return this.insert(d.hostView,a),d}insert(t,e){const i=t._lView,r=i[1];if(function ET(n){return Vn(n[3])}(i)){const d=this.indexOf(t);if(-1!==d)this.detach(d);else{const u=i[3],h=new o0(u,u[6],u[3]);h.detach(h.indexOf(t))}}const s=this._adjustIndex(e),o=this._lContainer;!function AI(n,t,e,i){const r=10+i,s=e.length;i>0&&(e[r-1][4]=t),i<s-10?(t[4]=e[r],hv(e,10+i,t)):(e.push(t),t[4]=null),t[3]=e;const o=t[17];null!==o&&e!==o&&function II(n,t){const e=n[9];t[16]!==t[3][3][16]&&(n[2]=!0),null===e?n[9]=[t]:e.push(t)}(o,t);const a=t[19];null!==a&&a.insertView(n),t[2]|=128}(r,i,o,s);const a=kh(s,o),l=i[11],c=Kl(l,o[7]);return null!==c&&function SI(n,t,e,i,r,s){i[0]=r,i[6]=t,Zo(n,i,e,1,r,s)}(r,o[6],l,i,c,a),t.attachToViewContainerRef(),hv(Sp(o),s,t),t}move(t,e){return this.insert(t,e)}indexOf(t){const e=a0(this._lContainer);return null!==e?e.indexOf(t):-1}remove(t){const e=this._adjustIndex(t,-1),i=xh(this._lContainer,e);i&&(zl(Sp(this._lContainer),e),Zv(i[1],i))}detach(t){const e=this._adjustIndex(t,-1),i=xh(this._lContainer,e);return i&&null!=zl(Sp(this._lContainer),e)?new ua(i):null}_adjustIndex(t,e=0){return null==t?this.length+e:t}};function a0(n){return n[8]}function Sp(n){return n[8]||(n[8]=[])}function l0(n,t){let e;const i=t[n.index];if(Vn(i))e=i;else{let r;if(8&n.type)r=ct(i);else{const s=t[11];r=s.createComment(\"\");const o=yn(n,t);xr(s,Kl(s,o),r,function FI(n,t){return et(n)?n.nextSibling(t):t.nextSibling}(s,o),!1)}t[n.index]=e=Hy(i,t,r,n),ic(t,e)}return new o0(e,n,t)}class kp{constructor(t){this.queryList=t,this.matches=null}clone(){return new kp(this.queryList)}setDirty(){this.queryList.setDirty()}}class Tp{constructor(t=[]){this.queries=t}createEmbeddedView(t){const e=t.queries;if(null!==e){const i=null!==t.contentQueries?t.contentQueries[0]:e.length,r=[];for(let s=0;s<i;s++){const o=e.getByIndex(s);r.push(this.queries[o.indexInDeclarationView].clone())}return new Tp(r)}return null}insertView(t){this.dirtyQueriesWithMatches(t)}detachView(t){this.dirtyQueriesWithMatches(t)}dirtyQueriesWithMatches(t){for(let e=0;e<this.queries.length;e++)null!==p0(t,e).matches&&this.queries[e].setDirty()}}class c0{constructor(t,e,i=null){this.predicate=t,this.flags=e,this.read=i}}class Ap{constructor(t=[]){this.queries=t}elementStart(t,e){for(let i=0;i<this.queries.length;i++)this.queries[i].elementStart(t,e)}elementEnd(t){for(let e=0;e<this.queries.length;e++)this.queries[e].elementEnd(t)}embeddedTView(t){let e=null;for(let i=0;i<this.length;i++){const r=null!==e?e.length:0,s=this.getByIndex(i).embeddedTView(t,r);s&&(s.indexInDeclarationView=i,null!==e?e.push(s):e=[s])}return null!==e?new Ap(e):null}template(t,e){for(let i=0;i<this.queries.length;i++)this.queries[i].template(t,e)}getByIndex(t){return this.queries[t]}get length(){return this.queries.length}track(t){this.queries.push(t)}}class Ip{constructor(t,e=-1){this.metadata=t,this.matches=null,this.indexInDeclarationView=-1,this.crossesNgTemplate=!1,this._appliesToNextNode=!0,this._declarationNodeIndex=e}elementStart(t,e){this.isApplyingToNode(e)&&this.matchTNode(t,e)}elementEnd(t){this._declarationNodeIndex===t.index&&(this._appliesToNextNode=!1)}template(t,e){this.elementStart(t,e)}embeddedTView(t,e){return this.isApplyingToNode(t)?(this.crossesNgTemplate=!0,this.addMatch(-t.index,e),new Ip(this.metadata)):null}isApplyingToNode(t){if(this._appliesToNextNode&&1!=(1&this.metadata.flags)){const e=this._declarationNodeIndex;let i=t.parent;for(;null!==i&&8&i.type&&i.index!==e;)i=i.parent;return e===(null!==i?i.index:-1)}return this._appliesToNextNode}matchTNode(t,e){const i=this.metadata.predicate;if(Array.isArray(i))for(let r=0;r<i.length;r++){const s=i[r];this.matchTNodeWithReadOption(t,e,oF(e,s)),this.matchTNodeWithReadOption(t,e,jl(e,t,s,!1,!1))}else i===ut?4&e.type&&this.matchTNodeWithReadOption(t,e,-1):this.matchTNodeWithReadOption(t,e,jl(e,t,i,!1,!1))}matchTNodeWithReadOption(t,e,i){if(null!==i){const r=this.metadata.read;if(null!==r)if(r===W||r===st||r===ut&&4&e.type)this.addMatch(e.index,-2);else{const s=jl(e,t,r,!1,!1);null!==s&&this.addMatch(e.index,s)}else this.addMatch(e.index,i)}}addMatch(t,e){null===this.matches?this.matches=[t,e]:this.matches.push(t,e)}}function oF(n,t){const e=n.localNames;if(null!==e)for(let i=0;i<e.length;i+=2)if(e[i]===t)return e[i+1];return null}function lF(n,t,e,i){return-1===e?function aF(n,t){return 11&n.type?$s(n,t):4&n.type?gc(n,t):null}(t,n):-2===e?function cF(n,t,e){return e===W?$s(t,n):e===ut?gc(t,n):e===st?l0(t,n):void 0}(n,t,i):Lo(n,n[1],e,t)}function d0(n,t,e,i){const r=t[19].queries[i];if(null===r.matches){const s=n.data,o=e.matches,a=[];for(let l=0;l<o.length;l+=2){const c=o[l];a.push(c<0?null:lF(t,s[c],o[l+1],e.metadata.read))}r.matches=a}return r.matches}function Rp(n,t,e,i){const r=n.queries.getByIndex(e),s=r.matches;if(null!==s){const o=d0(n,t,r,e);for(let a=0;a<s.length;a+=2){const l=s[a];if(l>0)i.push(o[a/2]);else{const c=s[a+1],d=t[-l];for(let u=10;u<d.length;u++){const h=d[u];h[17]===h[3]&&Rp(h[1],h,c,i)}if(null!==d[9]){const u=d[9];for(let h=0;h<u.length;h++){const p=u[h];Rp(p[1],p,c,i)}}}}}return i}function z(n){const t=w(),e=Me(),i=W_();qu(i+1);const r=p0(e,i);if(n.dirty&&H_(t)===(2==(2&r.metadata.flags))){if(null===r.matches)n.reset([]);else{const s=r.crossesNgTemplate?Rp(e,t,i,[]):d0(e,t,r,i);n.reset(s,wP),n.notifyOnChanges()}return!0}return!1}function je(n,t,e){const i=Me();i.firstCreatePass&&(h0(i,new c0(n,t,e),-1),2==(2&t)&&(i.staticViewQueries=!0)),u0(i,w(),t)}function ve(n,t,e,i){const r=Me();if(r.firstCreatePass){const s=gt();h0(r,new c0(t,e,i),s.index),function uF(n,t){const e=n.contentQueries||(n.contentQueries=[]);t!==(e.length?e[e.length-1]:-1)&&e.push(n.queries.length-1,t)}(r,n),2==(2&e)&&(r.staticContentQueries=!0)}u0(r,w(),e)}function U(){return function dF(n,t){return n[19].queries[t].queryList}(w(),W_())}function u0(n,t,e){const i=new fa(4==(4&e));Ry(n,t,i,i.destroy),null===t[19]&&(t[19]=new Tp),t[19].queries.push(new kp(i))}function h0(n,t,e){null===n.queries&&(n.queries=new Ap),n.queries.track(new Ip(t,e))}function p0(n,t){return n.queries.getByIndex(t)}function yc(...n){}const Bp=new b(\"Application Initializer\");let Vp=(()=>{class n{constructor(e){this.appInits=e,this.resolve=yc,this.reject=yc,this.initialized=!1,this.done=!1,this.donePromise=new Promise((i,r)=>{this.resolve=i,this.reject=r})}runInitializers(){if(this.initialized)return;const e=[],i=()=>{this.done=!0,this.resolve()};if(this.appInits)for(let r=0;r<this.appInits.length;r++){const s=this.appInits[r]();if(ra(s))e.push(s);else if(up(s)){const o=new Promise((a,l)=>{s.subscribe({complete:a,error:l})});e.push(o)}}Promise.all(e).then(()=>{i()}).catch(r=>{this.reject(r)}),0===e.length&&i(),this.initialized=!0}}return n.\\u0275fac=function(e){return new(e||n)(y(Bp,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const ga=new b(\"AppId\",{providedIn:\"root\",factory:function A0(){return`${Hp()}${Hp()}${Hp()}`}});function Hp(){return String.fromCharCode(97+Math.floor(25*Math.random()))}const I0=new b(\"Platform Initializer\"),bc=new b(\"Platform ID\"),R0=new b(\"appBootstrapListener\");let O0=(()=>{class n{log(e){console.log(e)}warn(e){console.warn(e)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const Oi=new b(\"LocaleId\",{providedIn:\"root\",factory:()=>Uo(Oi,ee.Optional|ee.SkipSelf)||function TF(){return\"undefined\"!=typeof $localize&&$localize.locale||cc}()});class IF{constructor(t,e){this.ngModuleFactory=t,this.componentFactories=e}}let P0=(()=>{class n{compileModuleSync(e){return new xp(e)}compileModuleAsync(e){return Promise.resolve(this.compileModuleSync(e))}compileModuleAndAllComponentsSync(e){const i=this.compileModuleSync(e),s=di(gn(e).declarations).reduce((o,a)=>{const l=Ot(a);return l&&o.push(new Mp(l)),o},[]);return new IF(i,s)}compileModuleAndAllComponentsAsync(e){return Promise.resolve(this.compileModuleAndAllComponentsSync(e))}clearCache(){}clearCacheFor(e){}getModuleId(e){}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const OF=(()=>Promise.resolve(0))();function jp(n){\"undefined\"==typeof Zone?OF.then(()=>{n&&n.apply(null,null)}):Zone.current.scheduleMicroTask(\"scheduleMicrotask\",n)}class ne{constructor({enableLongStackTrace:t=!1,shouldCoalesceEventChangeDetection:e=!1,shouldCoalesceRunChangeDetection:i=!1}){if(this.hasPendingMacrotasks=!1,this.hasPendingMicrotasks=!1,this.isStable=!0,this.onUnstable=new $(!1),this.onMicrotaskEmpty=new $(!1),this.onStable=new $(!1),this.onError=new $(!1),\"undefined\"==typeof Zone)throw new Error(\"In this configuration Angular requires Zone.js\");Zone.assertZonePatched();const r=this;r._nesting=0,r._outer=r._inner=Zone.current,Zone.TaskTrackingZoneSpec&&(r._inner=r._inner.fork(new Zone.TaskTrackingZoneSpec)),t&&Zone.longStackTraceZoneSpec&&(r._inner=r._inner.fork(Zone.longStackTraceZoneSpec)),r.shouldCoalesceEventChangeDetection=!i&&e,r.shouldCoalesceRunChangeDetection=i,r.lastRequestAnimationFrameId=-1,r.nativeRequestAnimationFrame=function PF(){let n=Oe.requestAnimationFrame,t=Oe.cancelAnimationFrame;if(\"undefined\"!=typeof Zone&&n&&t){const e=n[Zone.__symbol__(\"OriginalDelegate\")];e&&(n=e);const i=t[Zone.__symbol__(\"OriginalDelegate\")];i&&(t=i)}return{nativeRequestAnimationFrame:n,nativeCancelAnimationFrame:t}}().nativeRequestAnimationFrame,function LF(n){const t=()=>{!function NF(n){n.isCheckStableRunning||-1!==n.lastRequestAnimationFrameId||(n.lastRequestAnimationFrameId=n.nativeRequestAnimationFrame.call(Oe,()=>{n.fakeTopEventTask||(n.fakeTopEventTask=Zone.root.scheduleEventTask(\"fakeTopEventTask\",()=>{n.lastRequestAnimationFrameId=-1,Up(n),n.isCheckStableRunning=!0,zp(n),n.isCheckStableRunning=!1},void 0,()=>{},()=>{})),n.fakeTopEventTask.invoke()}),Up(n))}(n)};n._inner=n._inner.fork({name:\"angular\",properties:{isAngularZone:!0},onInvokeTask:(e,i,r,s,o,a)=>{try{return F0(n),e.invokeTask(r,s,o,a)}finally{(n.shouldCoalesceEventChangeDetection&&\"eventTask\"===s.type||n.shouldCoalesceRunChangeDetection)&&t(),N0(n)}},onInvoke:(e,i,r,s,o,a,l)=>{try{return F0(n),e.invoke(r,s,o,a,l)}finally{n.shouldCoalesceRunChangeDetection&&t(),N0(n)}},onHasTask:(e,i,r,s)=>{e.hasTask(r,s),i===r&&(\"microTask\"==s.change?(n._hasPendingMicrotasks=s.microTask,Up(n),zp(n)):\"macroTask\"==s.change&&(n.hasPendingMacrotasks=s.macroTask))},onHandleError:(e,i,r,s)=>(e.handleError(r,s),n.runOutsideAngular(()=>n.onError.emit(s)),!1)})}(r)}static isInAngularZone(){return\"undefined\"!=typeof Zone&&!0===Zone.current.get(\"isAngularZone\")}static assertInAngularZone(){if(!ne.isInAngularZone())throw new Error(\"Expected to be in Angular Zone, but it is not!\")}static assertNotInAngularZone(){if(ne.isInAngularZone())throw new Error(\"Expected to not be in Angular Zone, but it is!\")}run(t,e,i){return this._inner.run(t,e,i)}runTask(t,e,i,r){const s=this._inner,o=s.scheduleEventTask(\"NgZoneEvent: \"+r,t,FF,yc,yc);try{return s.runTask(o,e,i)}finally{s.cancelTask(o)}}runGuarded(t,e,i){return this._inner.runGuarded(t,e,i)}runOutsideAngular(t){return this._outer.run(t)}}const FF={};function zp(n){if(0==n._nesting&&!n.hasPendingMicrotasks&&!n.isStable)try{n._nesting++,n.onMicrotaskEmpty.emit(null)}finally{if(n._nesting--,!n.hasPendingMicrotasks)try{n.runOutsideAngular(()=>n.onStable.emit(null))}finally{n.isStable=!0}}}function Up(n){n.hasPendingMicrotasks=!!(n._hasPendingMicrotasks||(n.shouldCoalesceEventChangeDetection||n.shouldCoalesceRunChangeDetection)&&-1!==n.lastRequestAnimationFrameId)}function F0(n){n._nesting++,n.isStable&&(n.isStable=!1,n.onUnstable.emit(null))}function N0(n){n._nesting--,zp(n)}class BF{constructor(){this.hasPendingMicrotasks=!1,this.hasPendingMacrotasks=!1,this.isStable=!0,this.onUnstable=new $,this.onMicrotaskEmpty=new $,this.onStable=new $,this.onError=new $}run(t,e,i){return t.apply(e,i)}runGuarded(t,e,i){return t.apply(e,i)}runOutsideAngular(t){return t()}runTask(t,e,i,r){return t.apply(e,i)}}let $p=(()=>{class n{constructor(e){this._ngZone=e,this._pendingCount=0,this._isZoneStable=!0,this._didWork=!1,this._callbacks=[],this.taskTrackingZone=null,this._watchAngularEvents(),e.run(()=>{this.taskTrackingZone=\"undefined\"==typeof Zone?null:Zone.current.get(\"TaskTrackingZone\")})}_watchAngularEvents(){this._ngZone.onUnstable.subscribe({next:()=>{this._didWork=!0,this._isZoneStable=!1}}),this._ngZone.runOutsideAngular(()=>{this._ngZone.onStable.subscribe({next:()=>{ne.assertNotInAngularZone(),jp(()=>{this._isZoneStable=!0,this._runCallbacksIfReady()})}})})}increasePendingRequestCount(){return this._pendingCount+=1,this._didWork=!0,this._pendingCount}decreasePendingRequestCount(){if(this._pendingCount-=1,this._pendingCount<0)throw new Error(\"pending async requests below zero\");return this._runCallbacksIfReady(),this._pendingCount}isStable(){return this._isZoneStable&&0===this._pendingCount&&!this._ngZone.hasPendingMacrotasks}_runCallbacksIfReady(){if(this.isStable())jp(()=>{for(;0!==this._callbacks.length;){let e=this._callbacks.pop();clearTimeout(e.timeoutId),e.doneCb(this._didWork)}this._didWork=!1});else{let e=this.getPendingTasks();this._callbacks=this._callbacks.filter(i=>!i.updateCb||!i.updateCb(e)||(clearTimeout(i.timeoutId),!1)),this._didWork=!0}}getPendingTasks(){return this.taskTrackingZone?this.taskTrackingZone.macroTasks.map(e=>({source:e.source,creationLocation:e.creationLocation,data:e.data})):[]}addCallback(e,i,r){let s=-1;i&&i>0&&(s=setTimeout(()=>{this._callbacks=this._callbacks.filter(o=>o.timeoutId!==s),e(this._didWork,this.getPendingTasks())},i)),this._callbacks.push({doneCb:e,timeoutId:s,updateCb:r})}whenStable(e,i,r){if(r&&!this.taskTrackingZone)throw new Error('Task tracking zone is required when passing an update callback to whenStable(). Is \"zone.js/plugins/task-tracking\" loaded?');this.addCallback(e,i,r),this._runCallbacksIfReady()}getPendingRequestCount(){return this._pendingCount}findProviders(e,i,r){return[]}}return n.\\u0275fac=function(e){return new(e||n)(y(ne))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),L0=(()=>{class n{constructor(){this._applications=new Map,Gp.addToWindow(this)}registerApplication(e,i){this._applications.set(e,i)}unregisterApplication(e){this._applications.delete(e)}unregisterAllApplications(){this._applications.clear()}getTestability(e){return this._applications.get(e)||null}getAllTestabilities(){return Array.from(this._applications.values())}getAllRootElements(){return Array.from(this._applications.keys())}findTestabilityInTree(e,i=!0){return Gp.findTestabilityInTree(this,e,i)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class VF{addToWindow(t){}findTestabilityInTree(t,e,i){return null}}let Qn,Gp=new VF;const B0=new b(\"AllowMultipleToken\");class V0{constructor(t,e){this.name=t,this.token=e}}function H0(n,t,e=[]){const i=`Platform: ${t}`,r=new b(i);return(s=[])=>{let o=j0();if(!o||o.injector.get(B0,!1))if(n)n(e.concat(s).concat({provide:r,useValue:!0}));else{const a=e.concat(s).concat({provide:r,useValue:!0},{provide:Jh,useValue:\"platform\"});!function UF(n){if(Qn&&!Qn.destroyed&&!Qn.injector.get(B0,!1))throw new H(400,\"\");Qn=n.get(z0);const t=n.get(I0,null);t&&t.forEach(e=>e())}(dt.create({providers:a,name:i}))}return function $F(n){const t=j0();if(!t)throw new H(401,\"\");return t}()}}function j0(){return Qn&&!Qn.destroyed?Qn:null}let z0=(()=>{class n{constructor(e){this._injector=e,this._modules=[],this._destroyListeners=[],this._destroyed=!1}bootstrapModuleFactory(e,i){const a=function GF(n,t){let e;return e=\"noop\"===n?new BF:(\"zone.js\"===n?void 0:n)||new ne({enableLongStackTrace:!1,shouldCoalesceEventChangeDetection:!!(null==t?void 0:t.ngZoneEventCoalescing),shouldCoalesceRunChangeDetection:!!(null==t?void 0:t.ngZoneRunCoalescing)}),e}(i?i.ngZone:void 0,{ngZoneEventCoalescing:i&&i.ngZoneEventCoalescing||!1,ngZoneRunCoalescing:i&&i.ngZoneRunCoalescing||!1}),l=[{provide:ne,useValue:a}];return a.run(()=>{const c=dt.create({providers:l,parent:this.injector,name:e.moduleType.name}),d=e.create(c),u=d.injector.get(Mr,null);if(!u)throw new H(402,\"\");return a.runOutsideAngular(()=>{const h=a.onError.subscribe({next:p=>{u.handleError(p)}});d.onDestroy(()=>{Wp(this._modules,d),h.unsubscribe()})}),function WF(n,t,e){try{const i=e();return ra(i)?i.catch(r=>{throw t.runOutsideAngular(()=>n.handleError(r)),r}):i}catch(i){throw t.runOutsideAngular(()=>n.handleError(i)),i}}(u,a,()=>{const h=d.injector.get(Vp);return h.runInitializers(),h.donePromise.then(()=>(function MO(n){tn(n,\"Expected localeId to be defined\"),\"string\"==typeof n&&(CC=n.toLowerCase().replace(/_/g,\"-\"))}(d.injector.get(Oi,cc)||cc),this._moduleDoBootstrap(d),d))})})}bootstrapModule(e,i=[]){const r=U0({},i);return function jF(n,t,e){const i=new xp(e);return Promise.resolve(i)}(0,0,e).then(s=>this.bootstrapModuleFactory(s,r))}_moduleDoBootstrap(e){const i=e.injector.get(Cc);if(e._bootstrapComponents.length>0)e._bootstrapComponents.forEach(r=>i.bootstrap(r));else{if(!e.instance.ngDoBootstrap)throw new H(403,\"\");e.instance.ngDoBootstrap(i)}this._modules.push(e)}onDestroy(e){this._destroyListeners.push(e)}get injector(){return this._injector}destroy(){if(this._destroyed)throw new H(404,\"\");this._modules.slice().forEach(e=>e.destroy()),this._destroyListeners.forEach(e=>e()),this._destroyed=!0}get destroyed(){return this._destroyed}}return n.\\u0275fac=function(e){return new(e||n)(y(dt))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();function U0(n,t){return Array.isArray(t)?t.reduce(U0,n):Object.assign(Object.assign({},n),t)}let Cc=(()=>{class n{constructor(e,i,r,s,o){this._zone=e,this._injector=i,this._exceptionHandler=r,this._componentFactoryResolver=s,this._initStatus=o,this._bootstrapListeners=[],this._views=[],this._runningTick=!1,this._stable=!0,this.componentTypes=[],this.components=[],this._onMicrotaskEmptySubscription=this._zone.onMicrotaskEmpty.subscribe({next:()=>{this._zone.run(()=>{this.tick()})}});const a=new Ve(c=>{this._stable=this._zone.isStable&&!this._zone.hasPendingMacrotasks&&!this._zone.hasPendingMicrotasks,this._zone.runOutsideAngular(()=>{c.next(this._stable),c.complete()})}),l=new Ve(c=>{let d;this._zone.runOutsideAngular(()=>{d=this._zone.onStable.subscribe(()=>{ne.assertNotInAngularZone(),jp(()=>{!this._stable&&!this._zone.hasPendingMacrotasks&&!this._zone.hasPendingMicrotasks&&(this._stable=!0,c.next(!0))})})});const u=this._zone.onUnstable.subscribe(()=>{ne.assertInAngularZone(),this._stable&&(this._stable=!1,this._zone.runOutsideAngular(()=>{c.next(!1)}))});return()=>{d.unsubscribe(),u.unsubscribe()}});this.isStable=Bt(a,l.pipe(function M_(n={}){const{connector:t=(()=>new O),resetOnError:e=!0,resetOnComplete:i=!0,resetOnRefCountZero:r=!0}=n;return s=>{let o=null,a=null,l=null,c=0,d=!1,u=!1;const h=()=>{null==a||a.unsubscribe(),a=null},p=()=>{h(),o=l=null,d=u=!1},m=()=>{const g=o;p(),null==g||g.unsubscribe()};return qe((g,_)=>{c++,!u&&!d&&h();const D=l=null!=l?l:t();_.add(()=>{c--,0===c&&!u&&!d&&(a=Du(m,r))}),D.subscribe(_),o||(o=new vl({next:v=>D.next(v),error:v=>{u=!0,h(),a=Du(p,e,v),D.error(v)},complete:()=>{d=!0,h(),a=Du(p,i),D.complete()}}),mt(g).subscribe(o))})(s)}}()))}bootstrap(e,i){if(!this._initStatus.done)throw new H(405,\"\");let r;r=e instanceof WC?e:this._componentFactoryResolver.resolveComponentFactory(e),this.componentTypes.push(r.componentType);const s=function zF(n){return n.isBoundToModule}(r)?void 0:this._injector.get(Ri),a=r.create(dt.NULL,[],i||r.selector,s),l=a.location.nativeElement,c=a.injector.get($p,null),d=c&&a.injector.get(L0);return c&&d&&d.registerApplication(l,c),a.onDestroy(()=>{this.detachView(a.hostView),Wp(this.components,a),d&&d.unregisterApplication(l)}),this._loadComponent(a),a}tick(){if(this._runningTick)throw new H(101,\"\");try{this._runningTick=!0;for(let e of this._views)e.detectChanges()}catch(e){this._zone.runOutsideAngular(()=>this._exceptionHandler.handleError(e))}finally{this._runningTick=!1}}attachView(e){const i=e;this._views.push(i),i.attachToAppRef(this)}detachView(e){const i=e;Wp(this._views,i),i.detachFromAppRef()}_loadComponent(e){this.attachView(e.hostView),this.tick(),this.components.push(e),this._injector.get(R0,[]).concat(this._bootstrapListeners).forEach(r=>r(e))}ngOnDestroy(){this._views.slice().forEach(e=>e.destroy()),this._onMicrotaskEmptySubscription.unsubscribe()}get viewCount(){return this._views.length}}return n.\\u0275fac=function(e){return new(e||n)(y(ne),y(dt),y(Mr),y(Ir),y(Vp))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();function Wp(n,t){const e=n.indexOf(t);e>-1&&n.splice(e,1)}let G0=!0,Ye=(()=>{class n{}return n.__NG_ELEMENT_ID__=QF,n})();function QF(n){return function KF(n,t,e){if(El(n)&&!e){const i=rn(n.index,t);return new ua(i,i)}return 47&n.type?new ua(t[16],t):null}(gt(),w(),16==(16&n))}class K0{constructor(){}supports(t){return ta(t)}create(t){return new nN(t)}}const tN=(n,t)=>t;class nN{constructor(t){this.length=0,this._linkedRecords=null,this._unlinkedRecords=null,this._previousItHead=null,this._itHead=null,this._itTail=null,this._additionsHead=null,this._additionsTail=null,this._movesHead=null,this._movesTail=null,this._removalsHead=null,this._removalsTail=null,this._identityChangesHead=null,this._identityChangesTail=null,this._trackByFn=t||tN}forEachItem(t){let e;for(e=this._itHead;null!==e;e=e._next)t(e)}forEachOperation(t){let e=this._itHead,i=this._removalsHead,r=0,s=null;for(;e||i;){const o=!i||e&&e.currentIndex<X0(i,r,s)?e:i,a=X0(o,r,s),l=o.currentIndex;if(o===i)r--,i=i._nextRemoved;else if(e=e._next,null==o.previousIndex)r++;else{s||(s=[]);const c=a-r,d=l-r;if(c!=d){for(let h=0;h<c;h++){const p=h<s.length?s[h]:s[h]=0,m=p+h;d<=m&&m<c&&(s[h]=p+1)}s[o.previousIndex]=d-c}}a!==l&&t(o,a,l)}}forEachPreviousItem(t){let e;for(e=this._previousItHead;null!==e;e=e._nextPrevious)t(e)}forEachAddedItem(t){let e;for(e=this._additionsHead;null!==e;e=e._nextAdded)t(e)}forEachMovedItem(t){let e;for(e=this._movesHead;null!==e;e=e._nextMoved)t(e)}forEachRemovedItem(t){let e;for(e=this._removalsHead;null!==e;e=e._nextRemoved)t(e)}forEachIdentityChange(t){let e;for(e=this._identityChangesHead;null!==e;e=e._nextIdentityChange)t(e)}diff(t){if(null==t&&(t=[]),!ta(t))throw new H(900,\"\");return this.check(t)?this:null}onDestroy(){}check(t){this._reset();let r,s,o,e=this._itHead,i=!1;if(Array.isArray(t)){this.length=t.length;for(let a=0;a<this.length;a++)s=t[a],o=this._trackByFn(a,s),null!==e&&Object.is(e.trackById,o)?(i&&(e=this._verifyReinsertion(e,s,o,a)),Object.is(e.item,s)||this._addIdentityChange(e,s)):(e=this._mismatch(e,s,o,a),i=!0),e=e._next}else r=0,function u1(n,t){if(Array.isArray(n))for(let e=0;e<n.length;e++)t(n[e]);else{const e=n[As()]();let i;for(;!(i=e.next()).done;)t(i.value)}}(t,a=>{o=this._trackByFn(r,a),null!==e&&Object.is(e.trackById,o)?(i&&(e=this._verifyReinsertion(e,a,o,r)),Object.is(e.item,a)||this._addIdentityChange(e,a)):(e=this._mismatch(e,a,o,r),i=!0),e=e._next,r++}),this.length=r;return this._truncate(e),this.collection=t,this.isDirty}get isDirty(){return null!==this._additionsHead||null!==this._movesHead||null!==this._removalsHead||null!==this._identityChangesHead}_reset(){if(this.isDirty){let t;for(t=this._previousItHead=this._itHead;null!==t;t=t._next)t._nextPrevious=t._next;for(t=this._additionsHead;null!==t;t=t._nextAdded)t.previousIndex=t.currentIndex;for(this._additionsHead=this._additionsTail=null,t=this._movesHead;null!==t;t=t._nextMoved)t.previousIndex=t.currentIndex;this._movesHead=this._movesTail=null,this._removalsHead=this._removalsTail=null,this._identityChangesHead=this._identityChangesTail=null}}_mismatch(t,e,i,r){let s;return null===t?s=this._itTail:(s=t._prev,this._remove(t)),null!==(t=null===this._unlinkedRecords?null:this._unlinkedRecords.get(i,null))?(Object.is(t.item,e)||this._addIdentityChange(t,e),this._reinsertAfter(t,s,r)):null!==(t=null===this._linkedRecords?null:this._linkedRecords.get(i,r))?(Object.is(t.item,e)||this._addIdentityChange(t,e),this._moveAfter(t,s,r)):t=this._addAfter(new iN(e,i),s,r),t}_verifyReinsertion(t,e,i,r){let s=null===this._unlinkedRecords?null:this._unlinkedRecords.get(i,null);return null!==s?t=this._reinsertAfter(s,t._prev,r):t.currentIndex!=r&&(t.currentIndex=r,this._addToMoves(t,r)),t}_truncate(t){for(;null!==t;){const e=t._next;this._addToRemovals(this._unlink(t)),t=e}null!==this._unlinkedRecords&&this._unlinkedRecords.clear(),null!==this._additionsTail&&(this._additionsTail._nextAdded=null),null!==this._movesTail&&(this._movesTail._nextMoved=null),null!==this._itTail&&(this._itTail._next=null),null!==this._removalsTail&&(this._removalsTail._nextRemoved=null),null!==this._identityChangesTail&&(this._identityChangesTail._nextIdentityChange=null)}_reinsertAfter(t,e,i){null!==this._unlinkedRecords&&this._unlinkedRecords.remove(t);const r=t._prevRemoved,s=t._nextRemoved;return null===r?this._removalsHead=s:r._nextRemoved=s,null===s?this._removalsTail=r:s._prevRemoved=r,this._insertAfter(t,e,i),this._addToMoves(t,i),t}_moveAfter(t,e,i){return this._unlink(t),this._insertAfter(t,e,i),this._addToMoves(t,i),t}_addAfter(t,e,i){return this._insertAfter(t,e,i),this._additionsTail=null===this._additionsTail?this._additionsHead=t:this._additionsTail._nextAdded=t,t}_insertAfter(t,e,i){const r=null===e?this._itHead:e._next;return t._next=r,t._prev=e,null===r?this._itTail=t:r._prev=t,null===e?this._itHead=t:e._next=t,null===this._linkedRecords&&(this._linkedRecords=new Z0),this._linkedRecords.put(t),t.currentIndex=i,t}_remove(t){return this._addToRemovals(this._unlink(t))}_unlink(t){null!==this._linkedRecords&&this._linkedRecords.remove(t);const e=t._prev,i=t._next;return null===e?this._itHead=i:e._next=i,null===i?this._itTail=e:i._prev=e,t}_addToMoves(t,e){return t.previousIndex===e||(this._movesTail=null===this._movesTail?this._movesHead=t:this._movesTail._nextMoved=t),t}_addToRemovals(t){return null===this._unlinkedRecords&&(this._unlinkedRecords=new Z0),this._unlinkedRecords.put(t),t.currentIndex=null,t._nextRemoved=null,null===this._removalsTail?(this._removalsTail=this._removalsHead=t,t._prevRemoved=null):(t._prevRemoved=this._removalsTail,this._removalsTail=this._removalsTail._nextRemoved=t),t}_addIdentityChange(t,e){return t.item=e,this._identityChangesTail=null===this._identityChangesTail?this._identityChangesHead=t:this._identityChangesTail._nextIdentityChange=t,t}}class iN{constructor(t,e){this.item=t,this.trackById=e,this.currentIndex=null,this.previousIndex=null,this._nextPrevious=null,this._prev=null,this._next=null,this._prevDup=null,this._nextDup=null,this._prevRemoved=null,this._nextRemoved=null,this._nextAdded=null,this._nextMoved=null,this._nextIdentityChange=null}}class rN{constructor(){this._head=null,this._tail=null}add(t){null===this._head?(this._head=this._tail=t,t._nextDup=null,t._prevDup=null):(this._tail._nextDup=t,t._prevDup=this._tail,t._nextDup=null,this._tail=t)}get(t,e){let i;for(i=this._head;null!==i;i=i._nextDup)if((null===e||e<=i.currentIndex)&&Object.is(i.trackById,t))return i;return null}remove(t){const e=t._prevDup,i=t._nextDup;return null===e?this._head=i:e._nextDup=i,null===i?this._tail=e:i._prevDup=e,null===this._head}}class Z0{constructor(){this.map=new Map}put(t){const e=t.trackById;let i=this.map.get(e);i||(i=new rN,this.map.set(e,i)),i.add(t)}get(t,e){const r=this.map.get(t);return r?r.get(t,e):null}remove(t){const e=t.trackById;return this.map.get(e).remove(t)&&this.map.delete(e),t}get isEmpty(){return 0===this.map.size}clear(){this.map.clear()}}function X0(n,t,e){const i=n.previousIndex;if(null===i)return i;let r=0;return e&&i<e.length&&(r=e[i]),i+t+r}class J0{constructor(){}supports(t){return t instanceof Map||sp(t)}create(){return new sN}}class sN{constructor(){this._records=new Map,this._mapHead=null,this._appendAfter=null,this._previousMapHead=null,this._changesHead=null,this._changesTail=null,this._additionsHead=null,this._additionsTail=null,this._removalsHead=null,this._removalsTail=null}get isDirty(){return null!==this._additionsHead||null!==this._changesHead||null!==this._removalsHead}forEachItem(t){let e;for(e=this._mapHead;null!==e;e=e._next)t(e)}forEachPreviousItem(t){let e;for(e=this._previousMapHead;null!==e;e=e._nextPrevious)t(e)}forEachChangedItem(t){let e;for(e=this._changesHead;null!==e;e=e._nextChanged)t(e)}forEachAddedItem(t){let e;for(e=this._additionsHead;null!==e;e=e._nextAdded)t(e)}forEachRemovedItem(t){let e;for(e=this._removalsHead;null!==e;e=e._nextRemoved)t(e)}diff(t){if(t){if(!(t instanceof Map||sp(t)))throw new H(900,\"\")}else t=new Map;return this.check(t)?this:null}onDestroy(){}check(t){this._reset();let e=this._mapHead;if(this._appendAfter=null,this._forEach(t,(i,r)=>{if(e&&e.key===r)this._maybeAddToChanges(e,i),this._appendAfter=e,e=e._next;else{const s=this._getOrCreateRecordForKey(r,i);e=this._insertBeforeOrAppend(e,s)}}),e){e._prev&&(e._prev._next=null),this._removalsHead=e;for(let i=e;null!==i;i=i._nextRemoved)i===this._mapHead&&(this._mapHead=null),this._records.delete(i.key),i._nextRemoved=i._next,i.previousValue=i.currentValue,i.currentValue=null,i._prev=null,i._next=null}return this._changesTail&&(this._changesTail._nextChanged=null),this._additionsTail&&(this._additionsTail._nextAdded=null),this.isDirty}_insertBeforeOrAppend(t,e){if(t){const i=t._prev;return e._next=t,e._prev=i,t._prev=e,i&&(i._next=e),t===this._mapHead&&(this._mapHead=e),this._appendAfter=t,t}return this._appendAfter?(this._appendAfter._next=e,e._prev=this._appendAfter):this._mapHead=e,this._appendAfter=e,null}_getOrCreateRecordForKey(t,e){if(this._records.has(t)){const r=this._records.get(t);this._maybeAddToChanges(r,e);const s=r._prev,o=r._next;return s&&(s._next=o),o&&(o._prev=s),r._next=null,r._prev=null,r}const i=new oN(t);return this._records.set(t,i),i.currentValue=e,this._addToAdditions(i),i}_reset(){if(this.isDirty){let t;for(this._previousMapHead=this._mapHead,t=this._previousMapHead;null!==t;t=t._next)t._nextPrevious=t._next;for(t=this._changesHead;null!==t;t=t._nextChanged)t.previousValue=t.currentValue;for(t=this._additionsHead;null!=t;t=t._nextAdded)t.previousValue=t.currentValue;this._changesHead=this._changesTail=null,this._additionsHead=this._additionsTail=null,this._removalsHead=null}}_maybeAddToChanges(t,e){Object.is(e,t.currentValue)||(t.previousValue=t.currentValue,t.currentValue=e,this._addToChanges(t))}_addToAdditions(t){null===this._additionsHead?this._additionsHead=this._additionsTail=t:(this._additionsTail._nextAdded=t,this._additionsTail=t)}_addToChanges(t){null===this._changesHead?this._changesHead=this._changesTail=t:(this._changesTail._nextChanged=t,this._changesTail=t)}_forEach(t,e){t instanceof Map?t.forEach(e):Object.keys(t).forEach(i=>e(t[i],i))}}class oN{constructor(t){this.key=t,this.previousValue=null,this.currentValue=null,this._nextPrevious=null,this._next=null,this._prev=null,this._nextAdded=null,this._nextRemoved=null,this._nextChanged=null}}function eD(){return new xn([new K0])}let xn=(()=>{class n{constructor(e){this.factories=e}static create(e,i){if(null!=i){const r=i.factories.slice();e=e.concat(r)}return new n(e)}static extend(e){return{provide:n,useFactory:i=>n.create(e,i||eD()),deps:[[n,new Cn,new Tt]]}}find(e){const i=this.factories.find(r=>r.supports(e));if(null!=i)return i;throw new H(901,\"\")}}return n.\\u0275prov=k({token:n,providedIn:\"root\",factory:eD}),n})();function tD(){return new _a([new J0])}let _a=(()=>{class n{constructor(e){this.factories=e}static create(e,i){if(i){const r=i.factories.slice();e=e.concat(r)}return new n(e)}static extend(e){return{provide:n,useFactory:i=>n.create(e,i||tD()),deps:[[n,new Cn,new Tt]]}}find(e){const i=this.factories.find(s=>s.supports(e));if(i)return i;throw new H(901,\"\")}}return n.\\u0275prov=k({token:n,providedIn:\"root\",factory:tD}),n})();const cN=H0(null,\"core\",[{provide:bc,useValue:\"unknown\"},{provide:z0,deps:[dt]},{provide:L0,deps:[]},{provide:O0,deps:[]}]);let dN=(()=>{class n{constructor(e){}}return n.\\u0275fac=function(e){return new(e||n)(y(Cc))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),Mc=null;function mi(){return Mc}const ie=new b(\"DocumentToken\");let Pr=(()=>{class n{historyGo(e){throw new Error(\"Not implemented\")}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:function(){return function fN(){return y(nD)}()},providedIn:\"platform\"}),n})();const mN=new b(\"Location Initialized\");let nD=(()=>{class n extends Pr{constructor(e){super(),this._doc=e,this._init()}_init(){this.location=window.location,this._history=window.history}getBaseHrefFromDOM(){return mi().getBaseHref(this._doc)}onPopState(e){const i=mi().getGlobalEventTarget(this._doc,\"window\");return i.addEventListener(\"popstate\",e,!1),()=>i.removeEventListener(\"popstate\",e)}onHashChange(e){const i=mi().getGlobalEventTarget(this._doc,\"window\");return i.addEventListener(\"hashchange\",e,!1),()=>i.removeEventListener(\"hashchange\",e)}get href(){return this.location.href}get protocol(){return this.location.protocol}get hostname(){return this.location.hostname}get port(){return this.location.port}get pathname(){return this.location.pathname}get search(){return this.location.search}get hash(){return this.location.hash}set pathname(e){this.location.pathname=e}pushState(e,i,r){iD()?this._history.pushState(e,i,r):this.location.hash=r}replaceState(e,i,r){iD()?this._history.replaceState(e,i,r):this.location.hash=r}forward(){this._history.forward()}back(){this._history.back()}historyGo(e=0){this._history.go(e)}getState(){return this._history.state}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:function(){return function gN(){return new nD(y(ie))}()},providedIn:\"platform\"}),n})();function iD(){return!!window.history.pushState}function Zp(n,t){if(0==n.length)return t;if(0==t.length)return n;let e=0;return n.endsWith(\"/\")&&e++,t.startsWith(\"/\")&&e++,2==e?n+t.substring(1):1==e?n+t:n+\"/\"+t}function rD(n){const t=n.match(/#|\\?|$/),e=t&&t.index||n.length;return n.slice(0,e-(\"/\"===n[e-1]?1:0))+n.slice(e)}function Pi(n){return n&&\"?\"!==n[0]?\"?\"+n:n}let qs=(()=>{class n{historyGo(e){throw new Error(\"Not implemented\")}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:function(){return function _N(n){const t=y(ie).location;return new sD(y(Pr),t&&t.origin||\"\")}()},providedIn:\"root\"}),n})();const Xp=new b(\"appBaseHref\");let sD=(()=>{class n extends qs{constructor(e,i){if(super(),this._platformLocation=e,this._removeListenerFns=[],null==i&&(i=this._platformLocation.getBaseHrefFromDOM()),null==i)throw new Error(\"No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.\");this._baseHref=i}ngOnDestroy(){for(;this._removeListenerFns.length;)this._removeListenerFns.pop()()}onPopState(e){this._removeListenerFns.push(this._platformLocation.onPopState(e),this._platformLocation.onHashChange(e))}getBaseHref(){return this._baseHref}prepareExternalUrl(e){return Zp(this._baseHref,e)}path(e=!1){const i=this._platformLocation.pathname+Pi(this._platformLocation.search),r=this._platformLocation.hash;return r&&e?`${i}${r}`:i}pushState(e,i,r,s){const o=this.prepareExternalUrl(r+Pi(s));this._platformLocation.pushState(e,i,o)}replaceState(e,i,r,s){const o=this.prepareExternalUrl(r+Pi(s));this._platformLocation.replaceState(e,i,o)}forward(){this._platformLocation.forward()}back(){this._platformLocation.back()}historyGo(e=0){var i,r;null===(r=(i=this._platformLocation).historyGo)||void 0===r||r.call(i,e)}}return n.\\u0275fac=function(e){return new(e||n)(y(Pr),y(Xp,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),vN=(()=>{class n extends qs{constructor(e,i){super(),this._platformLocation=e,this._baseHref=\"\",this._removeListenerFns=[],null!=i&&(this._baseHref=i)}ngOnDestroy(){for(;this._removeListenerFns.length;)this._removeListenerFns.pop()()}onPopState(e){this._removeListenerFns.push(this._platformLocation.onPopState(e),this._platformLocation.onHashChange(e))}getBaseHref(){return this._baseHref}path(e=!1){let i=this._platformLocation.hash;return null==i&&(i=\"#\"),i.length>0?i.substring(1):i}prepareExternalUrl(e){const i=Zp(this._baseHref,e);return i.length>0?\"#\"+i:i}pushState(e,i,r,s){let o=this.prepareExternalUrl(r+Pi(s));0==o.length&&(o=this._platformLocation.pathname),this._platformLocation.pushState(e,i,o)}replaceState(e,i,r,s){let o=this.prepareExternalUrl(r+Pi(s));0==o.length&&(o=this._platformLocation.pathname),this._platformLocation.replaceState(e,i,o)}forward(){this._platformLocation.forward()}back(){this._platformLocation.back()}historyGo(e=0){var i,r;null===(r=(i=this._platformLocation).historyGo)||void 0===r||r.call(i,e)}}return n.\\u0275fac=function(e){return new(e||n)(y(Pr),y(Xp,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),va=(()=>{class n{constructor(e,i){this._subject=new $,this._urlChangeListeners=[],this._platformStrategy=e;const r=this._platformStrategy.getBaseHref();this._platformLocation=i,this._baseHref=rD(oD(r)),this._platformStrategy.onPopState(s=>{this._subject.emit({url:this.path(!0),pop:!0,state:s.state,type:s.type})})}path(e=!1){return this.normalize(this._platformStrategy.path(e))}getState(){return this._platformLocation.getState()}isCurrentPathEqualTo(e,i=\"\"){return this.path()==this.normalize(e+Pi(i))}normalize(e){return n.stripTrailingSlash(function bN(n,t){return n&&t.startsWith(n)?t.substring(n.length):t}(this._baseHref,oD(e)))}prepareExternalUrl(e){return e&&\"/\"!==e[0]&&(e=\"/\"+e),this._platformStrategy.prepareExternalUrl(e)}go(e,i=\"\",r=null){this._platformStrategy.pushState(r,\"\",e,i),this._notifyUrlChangeListeners(this.prepareExternalUrl(e+Pi(i)),r)}replaceState(e,i=\"\",r=null){this._platformStrategy.replaceState(r,\"\",e,i),this._notifyUrlChangeListeners(this.prepareExternalUrl(e+Pi(i)),r)}forward(){this._platformStrategy.forward()}back(){this._platformStrategy.back()}historyGo(e=0){var i,r;null===(r=(i=this._platformStrategy).historyGo)||void 0===r||r.call(i,e)}onUrlChange(e){this._urlChangeListeners.push(e),this._urlChangeSubscription||(this._urlChangeSubscription=this.subscribe(i=>{this._notifyUrlChangeListeners(i.url,i.state)}))}_notifyUrlChangeListeners(e=\"\",i){this._urlChangeListeners.forEach(r=>r(e,i))}subscribe(e,i,r){return this._subject.subscribe({next:e,error:i,complete:r})}}return n.normalizeQueryParams=Pi,n.joinWithSlash=Zp,n.stripTrailingSlash=rD,n.\\u0275fac=function(e){return new(e||n)(y(qs),y(Pr))},n.\\u0275prov=k({token:n,factory:function(){return function yN(){return new va(y(qs),y(Pr))}()},providedIn:\"root\"}),n})();function oD(n){return n.replace(/\\/index.html$/,\"\")}let mD=(()=>{class n{constructor(e,i,r,s){this._iterableDiffers=e,this._keyValueDiffers=i,this._ngEl=r,this._renderer=s,this._iterableDiffer=null,this._keyValueDiffer=null,this._initialClasses=[],this._rawClass=null}set klass(e){this._removeClasses(this._initialClasses),this._initialClasses=\"string\"==typeof e?e.split(/\\s+/):[],this._applyClasses(this._initialClasses),this._applyClasses(this._rawClass)}set ngClass(e){this._removeClasses(this._rawClass),this._applyClasses(this._initialClasses),this._iterableDiffer=null,this._keyValueDiffer=null,this._rawClass=\"string\"==typeof e?e.split(/\\s+/):e,this._rawClass&&(ta(this._rawClass)?this._iterableDiffer=this._iterableDiffers.find(this._rawClass).create():this._keyValueDiffer=this._keyValueDiffers.find(this._rawClass).create())}ngDoCheck(){if(this._iterableDiffer){const e=this._iterableDiffer.diff(this._rawClass);e&&this._applyIterableChanges(e)}else if(this._keyValueDiffer){const e=this._keyValueDiffer.diff(this._rawClass);e&&this._applyKeyValueChanges(e)}}_applyKeyValueChanges(e){e.forEachAddedItem(i=>this._toggleClass(i.key,i.currentValue)),e.forEachChangedItem(i=>this._toggleClass(i.key,i.currentValue)),e.forEachRemovedItem(i=>{i.previousValue&&this._toggleClass(i.key,!1)})}_applyIterableChanges(e){e.forEachAddedItem(i=>{if(\"string\"!=typeof i.item)throw new Error(`NgClass can only toggle CSS classes expressed as strings, got ${Re(i.item)}`);this._toggleClass(i.item,!0)}),e.forEachRemovedItem(i=>this._toggleClass(i.item,!1))}_applyClasses(e){e&&(Array.isArray(e)||e instanceof Set?e.forEach(i=>this._toggleClass(i,!0)):Object.keys(e).forEach(i=>this._toggleClass(i,!!e[i])))}_removeClasses(e){e&&(Array.isArray(e)||e instanceof Set?e.forEach(i=>this._toggleClass(i,!1)):Object.keys(e).forEach(i=>this._toggleClass(i,!1)))}_toggleClass(e,i){(e=e.trim())&&e.split(/\\s+/g).forEach(r=>{i?this._renderer.addClass(this._ngEl.nativeElement,r):this._renderer.removeClass(this._ngEl.nativeElement,r)})}}return n.\\u0275fac=function(e){return new(e||n)(f(xn),f(_a),f(W),f(Ii))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngClass\",\"\"]],inputs:{klass:[\"class\",\"klass\"],ngClass:\"ngClass\"}}),n})();class sL{constructor(t,e,i,r){this.$implicit=t,this.ngForOf=e,this.index=i,this.count=r}get first(){return 0===this.index}get last(){return this.index===this.count-1}get even(){return this.index%2==0}get odd(){return!this.even}}let gD=(()=>{class n{constructor(e,i,r){this._viewContainer=e,this._template=i,this._differs=r,this._ngForOf=null,this._ngForOfDirty=!0,this._differ=null}set ngForOf(e){this._ngForOf=e,this._ngForOfDirty=!0}set ngForTrackBy(e){this._trackByFn=e}get ngForTrackBy(){return this._trackByFn}set ngForTemplate(e){e&&(this._template=e)}ngDoCheck(){if(this._ngForOfDirty){this._ngForOfDirty=!1;const e=this._ngForOf;!this._differ&&e&&(this._differ=this._differs.find(e).create(this.ngForTrackBy))}if(this._differ){const e=this._differ.diff(this._ngForOf);e&&this._applyChanges(e)}}_applyChanges(e){const i=this._viewContainer;e.forEachOperation((r,s,o)=>{if(null==r.previousIndex)i.createEmbeddedView(this._template,new sL(r.item,this._ngForOf,-1,-1),null===o?void 0:o);else if(null==o)i.remove(null===s?void 0:s);else if(null!==s){const a=i.get(s);i.move(a,o),_D(a,r)}});for(let r=0,s=i.length;r<s;r++){const a=i.get(r).context;a.index=r,a.count=s,a.ngForOf=this._ngForOf}e.forEachIdentityChange(r=>{_D(i.get(r.currentIndex),r)})}static ngTemplateContextGuard(e,i){return!0}}return n.\\u0275fac=function(e){return new(e||n)(f(st),f(ut),f(xn))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngFor\",\"\",\"ngForOf\",\"\"]],inputs:{ngForOf:\"ngForOf\",ngForTrackBy:\"ngForTrackBy\",ngForTemplate:\"ngForTemplate\"}}),n})();function _D(n,t){n.context.$implicit=t.item}let Ca=(()=>{class n{constructor(e,i){this._viewContainer=e,this._context=new oL,this._thenTemplateRef=null,this._elseTemplateRef=null,this._thenViewRef=null,this._elseViewRef=null,this._thenTemplateRef=i}set ngIf(e){this._context.$implicit=this._context.ngIf=e,this._updateView()}set ngIfThen(e){vD(\"ngIfThen\",e),this._thenTemplateRef=e,this._thenViewRef=null,this._updateView()}set ngIfElse(e){vD(\"ngIfElse\",e),this._elseTemplateRef=e,this._elseViewRef=null,this._updateView()}_updateView(){this._context.$implicit?this._thenViewRef||(this._viewContainer.clear(),this._elseViewRef=null,this._thenTemplateRef&&(this._thenViewRef=this._viewContainer.createEmbeddedView(this._thenTemplateRef,this._context))):this._elseViewRef||(this._viewContainer.clear(),this._thenViewRef=null,this._elseTemplateRef&&(this._elseViewRef=this._viewContainer.createEmbeddedView(this._elseTemplateRef,this._context)))}static ngTemplateContextGuard(e,i){return!0}}return n.\\u0275fac=function(e){return new(e||n)(f(st),f(ut))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngIf\",\"\"]],inputs:{ngIf:\"ngIf\",ngIfThen:\"ngIfThen\",ngIfElse:\"ngIfElse\"}}),n})();class oL{constructor(){this.$implicit=null,this.ngIf=null}}function vD(n,t){if(t&&!t.createEmbeddedView)throw new Error(`${n} must be a TemplateRef, but received '${Re(t)}'.`)}class df{constructor(t,e){this._viewContainerRef=t,this._templateRef=e,this._created=!1}create(){this._created=!0,this._viewContainerRef.createEmbeddedView(this._templateRef)}destroy(){this._created=!1,this._viewContainerRef.clear()}enforceState(t){t&&!this._created?this.create():!t&&this._created&&this.destroy()}}let Ys=(()=>{class n{constructor(){this._defaultUsed=!1,this._caseCount=0,this._lastCaseCheckIndex=0,this._lastCasesMatched=!1}set ngSwitch(e){this._ngSwitch=e,0===this._caseCount&&this._updateDefaultCases(!0)}_addCase(){return this._caseCount++}_addDefault(e){this._defaultViews||(this._defaultViews=[]),this._defaultViews.push(e)}_matchCase(e){const i=e==this._ngSwitch;return this._lastCasesMatched=this._lastCasesMatched||i,this._lastCaseCheckIndex++,this._lastCaseCheckIndex===this._caseCount&&(this._updateDefaultCases(!this._lastCasesMatched),this._lastCaseCheckIndex=0,this._lastCasesMatched=!1),i}_updateDefaultCases(e){if(this._defaultViews&&e!==this._defaultUsed){this._defaultUsed=e;for(let i=0;i<this._defaultViews.length;i++)this._defaultViews[i].enforceState(e)}}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngSwitch\",\"\"]],inputs:{ngSwitch:\"ngSwitch\"}}),n})(),Pc=(()=>{class n{constructor(e,i,r){this.ngSwitch=r,r._addCase(),this._view=new df(e,i)}ngDoCheck(){this._view.enforceState(this.ngSwitch._matchCase(this.ngSwitchCase))}}return n.\\u0275fac=function(e){return new(e||n)(f(st),f(ut),f(Ys,9))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngSwitchCase\",\"\"]],inputs:{ngSwitchCase:\"ngSwitchCase\"}}),n})(),yD=(()=>{class n{constructor(e,i,r){r._addDefault(new df(e,i))}}return n.\\u0275fac=function(e){return new(e||n)(f(st),f(ut),f(Ys,9))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngSwitchDefault\",\"\"]]}),n})(),bt=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const wD=\"browser\";let PL=(()=>{class n{}return n.\\u0275prov=k({token:n,providedIn:\"root\",factory:()=>new FL(y(ie),window)}),n})();class FL{constructor(t,e){this.document=t,this.window=e,this.offset=()=>[0,0]}setOffset(t){this.offset=Array.isArray(t)?()=>t:t}getScrollPosition(){return this.supportsScrolling()?[this.window.pageXOffset,this.window.pageYOffset]:[0,0]}scrollToPosition(t){this.supportsScrolling()&&this.window.scrollTo(t[0],t[1])}scrollToAnchor(t){if(!this.supportsScrolling())return;const e=function NL(n,t){const e=n.getElementById(t)||n.getElementsByName(t)[0];if(e)return e;if(\"function\"==typeof n.createTreeWalker&&n.body&&(n.body.createShadowRoot||n.body.attachShadow)){const i=n.createTreeWalker(n.body,NodeFilter.SHOW_ELEMENT);let r=i.currentNode;for(;r;){const s=r.shadowRoot;if(s){const o=s.getElementById(t)||s.querySelector(`[name=\"${t}\"]`);if(o)return o}r=i.nextNode()}}return null}(this.document,t);e&&(this.scrollToElement(e),e.focus())}setHistoryScrollRestoration(t){if(this.supportScrollRestoration()){const e=this.window.history;e&&e.scrollRestoration&&(e.scrollRestoration=t)}}scrollToElement(t){const e=t.getBoundingClientRect(),i=e.left+this.window.pageXOffset,r=e.top+this.window.pageYOffset,s=this.offset();this.window.scrollTo(i-s[0],r-s[1])}supportScrollRestoration(){try{if(!this.supportsScrolling())return!1;const t=MD(this.window.history)||MD(Object.getPrototypeOf(this.window.history));return!(!t||!t.writable&&!t.set)}catch(t){return!1}}supportsScrolling(){try{return!!this.window&&!!this.window.scrollTo&&\"pageXOffset\"in this.window}catch(t){return!1}}}function MD(n){return Object.getOwnPropertyDescriptor(n,\"scrollRestoration\")}class pf extends class BL extends class pN{}{constructor(){super(...arguments),this.supportsDOMEvents=!0}}{static makeCurrent(){!function hN(n){Mc||(Mc=n)}(new pf)}onAndCancel(t,e,i){return t.addEventListener(e,i,!1),()=>{t.removeEventListener(e,i,!1)}}dispatchEvent(t,e){t.dispatchEvent(e)}remove(t){t.parentNode&&t.parentNode.removeChild(t)}createElement(t,e){return(e=e||this.getDefaultDocument()).createElement(t)}createHtmlDocument(){return document.implementation.createHTMLDocument(\"fakeTitle\")}getDefaultDocument(){return document}isElementNode(t){return t.nodeType===Node.ELEMENT_NODE}isShadowRoot(t){return t instanceof DocumentFragment}getGlobalEventTarget(t,e){return\"window\"===e?window:\"document\"===e?t:\"body\"===e?t.body:null}getBaseHref(t){const e=function VL(){return Da=Da||document.querySelector(\"base\"),Da?Da.getAttribute(\"href\"):null}();return null==e?null:function HL(n){Fc=Fc||document.createElement(\"a\"),Fc.setAttribute(\"href\",n);const t=Fc.pathname;return\"/\"===t.charAt(0)?t:`/${t}`}(e)}resetBaseElement(){Da=null}getUserAgent(){return window.navigator.userAgent}getCookie(t){return function iL(n,t){t=encodeURIComponent(t);for(const e of n.split(\";\")){const i=e.indexOf(\"=\"),[r,s]=-1==i?[e,\"\"]:[e.slice(0,i),e.slice(i+1)];if(r.trim()===t)return decodeURIComponent(s)}return null}(document.cookie,t)}}let Fc,Da=null;const xD=new b(\"TRANSITION_ID\"),zL=[{provide:Bp,useFactory:function jL(n,t,e){return()=>{e.get(Vp).donePromise.then(()=>{const i=mi(),r=t.querySelectorAll(`style[ng-transition=\"${n}\"]`);for(let s=0;s<r.length;s++)i.remove(r[s])})}},deps:[xD,ie,dt],multi:!0}];class ff{static init(){!function HF(n){Gp=n}(new ff)}addToWindow(t){Oe.getAngularTestability=(i,r=!0)=>{const s=t.findTestabilityInTree(i,r);if(null==s)throw new Error(\"Could not find testability for element.\");return s},Oe.getAllAngularTestabilities=()=>t.getAllTestabilities(),Oe.getAllAngularRootElements=()=>t.getAllRootElements(),Oe.frameworkStabilizers||(Oe.frameworkStabilizers=[]),Oe.frameworkStabilizers.push(i=>{const r=Oe.getAllAngularTestabilities();let s=r.length,o=!1;const a=function(l){o=o||l,s--,0==s&&i(o)};r.forEach(function(l){l.whenStable(a)})})}findTestabilityInTree(t,e,i){if(null==e)return null;const r=t.getTestability(e);return null!=r?r:i?mi().isShadowRoot(e)?this.findTestabilityInTree(t,e.host,!0):this.findTestabilityInTree(t,e.parentElement,!0):null}}let UL=(()=>{class n{build(){return new XMLHttpRequest}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const Nc=new b(\"EventManagerPlugins\");let Lc=(()=>{class n{constructor(e,i){this._zone=i,this._eventNameToPlugin=new Map,e.forEach(r=>r.manager=this),this._plugins=e.slice().reverse()}addEventListener(e,i,r){return this._findPluginFor(i).addEventListener(e,i,r)}addGlobalEventListener(e,i,r){return this._findPluginFor(i).addGlobalEventListener(e,i,r)}getZone(){return this._zone}_findPluginFor(e){const i=this._eventNameToPlugin.get(e);if(i)return i;const r=this._plugins;for(let s=0;s<r.length;s++){const o=r[s];if(o.supports(e))return this._eventNameToPlugin.set(e,o),o}throw new Error(`No event manager plugin found for event ${e}`)}}return n.\\u0275fac=function(e){return new(e||n)(y(Nc),y(ne))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class ED{constructor(t){this._doc=t}addGlobalEventListener(t,e,i){const r=mi().getGlobalEventTarget(this._doc,t);if(!r)throw new Error(`Unsupported event target ${r} for event ${e}`);return this.addEventListener(r,e,i)}}let SD=(()=>{class n{constructor(){this._stylesSet=new Set}addStyles(e){const i=new Set;e.forEach(r=>{this._stylesSet.has(r)||(this._stylesSet.add(r),i.add(r))}),this.onStylesAdded(i)}onStylesAdded(e){}getAllStyles(){return Array.from(this._stylesSet)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),wa=(()=>{class n extends SD{constructor(e){super(),this._doc=e,this._hostNodes=new Map,this._hostNodes.set(e.head,[])}_addStylesToHost(e,i,r){e.forEach(s=>{const o=this._doc.createElement(\"style\");o.textContent=s,r.push(i.appendChild(o))})}addHost(e){const i=[];this._addStylesToHost(this._stylesSet,e,i),this._hostNodes.set(e,i)}removeHost(e){const i=this._hostNodes.get(e);i&&i.forEach(kD),this._hostNodes.delete(e)}onStylesAdded(e){this._hostNodes.forEach((i,r)=>{this._addStylesToHost(e,r,i)})}ngOnDestroy(){this._hostNodes.forEach(e=>e.forEach(kD))}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();function kD(n){mi().remove(n)}const mf={svg:\"http://www.w3.org/2000/svg\",xhtml:\"http://www.w3.org/1999/xhtml\",xlink:\"http://www.w3.org/1999/xlink\",xml:\"http://www.w3.org/XML/1998/namespace\",xmlns:\"http://www.w3.org/2000/xmlns/\",math:\"http://www.w3.org/1998/MathML/\"},gf=/%COMP%/g;function Bc(n,t,e){for(let i=0;i<t.length;i++){let r=t[i];Array.isArray(r)?Bc(n,r,e):(r=r.replace(gf,n),e.push(r))}return e}function ID(n){return t=>{if(\"__ngUnwrap__\"===t)return n;!1===n(t)&&(t.preventDefault(),t.returnValue=!1)}}let Vc=(()=>{class n{constructor(e,i,r){this.eventManager=e,this.sharedStylesHost=i,this.appId=r,this.rendererByCompId=new Map,this.defaultRenderer=new _f(e)}createRenderer(e,i){if(!e||!i)return this.defaultRenderer;switch(i.encapsulation){case Ln.Emulated:{let r=this.rendererByCompId.get(i.id);return r||(r=new QL(this.eventManager,this.sharedStylesHost,i,this.appId),this.rendererByCompId.set(i.id,r)),r.applyToHost(e),r}case 1:case Ln.ShadowDom:return new KL(this.eventManager,this.sharedStylesHost,e,i);default:if(!this.rendererByCompId.has(i.id)){const r=Bc(i.id,i.styles,[]);this.sharedStylesHost.addStyles(r),this.rendererByCompId.set(i.id,this.defaultRenderer)}return this.defaultRenderer}}begin(){}end(){}}return n.\\u0275fac=function(e){return new(e||n)(y(Lc),y(wa),y(ga))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class _f{constructor(t){this.eventManager=t,this.data=Object.create(null),this.destroyNode=null}destroy(){}createElement(t,e){return e?document.createElementNS(mf[e]||e,t):document.createElement(t)}createComment(t){return document.createComment(t)}createText(t){return document.createTextNode(t)}appendChild(t,e){t.appendChild(e)}insertBefore(t,e,i){t&&t.insertBefore(e,i)}removeChild(t,e){t&&t.removeChild(e)}selectRootElement(t,e){let i=\"string\"==typeof t?document.querySelector(t):t;if(!i)throw new Error(`The selector \"${t}\" did not match any elements`);return e||(i.textContent=\"\"),i}parentNode(t){return t.parentNode}nextSibling(t){return t.nextSibling}setAttribute(t,e,i,r){if(r){e=r+\":\"+e;const s=mf[r];s?t.setAttributeNS(s,e,i):t.setAttribute(e,i)}else t.setAttribute(e,i)}removeAttribute(t,e,i){if(i){const r=mf[i];r?t.removeAttributeNS(r,e):t.removeAttribute(`${i}:${e}`)}else t.removeAttribute(e)}addClass(t,e){t.classList.add(e)}removeClass(t,e){t.classList.remove(e)}setStyle(t,e,i,r){r&(an.DashCase|an.Important)?t.style.setProperty(e,i,r&an.Important?\"important\":\"\"):t.style[e]=i}removeStyle(t,e,i){i&an.DashCase?t.style.removeProperty(e):t.style[e]=\"\"}setProperty(t,e,i){t[e]=i}setValue(t,e){t.nodeValue=e}listen(t,e,i){return\"string\"==typeof t?this.eventManager.addGlobalEventListener(t,e,ID(i)):this.eventManager.addEventListener(t,e,ID(i))}}class QL extends _f{constructor(t,e,i,r){super(t),this.component=i;const s=Bc(r+\"-\"+i.id,i.styles,[]);e.addStyles(s),this.contentAttr=function WL(n){return\"_ngcontent-%COMP%\".replace(gf,n)}(r+\"-\"+i.id),this.hostAttr=function qL(n){return\"_nghost-%COMP%\".replace(gf,n)}(r+\"-\"+i.id)}applyToHost(t){super.setAttribute(t,this.hostAttr,\"\")}createElement(t,e){const i=super.createElement(t,e);return super.setAttribute(i,this.contentAttr,\"\"),i}}class KL extends _f{constructor(t,e,i,r){super(t),this.sharedStylesHost=e,this.hostEl=i,this.shadowRoot=i.attachShadow({mode:\"open\"}),this.sharedStylesHost.addHost(this.shadowRoot);const s=Bc(r.id,r.styles,[]);for(let o=0;o<s.length;o++){const a=document.createElement(\"style\");a.textContent=s[o],this.shadowRoot.appendChild(a)}}nodeOrShadowRoot(t){return t===this.hostEl?this.shadowRoot:t}destroy(){this.sharedStylesHost.removeHost(this.shadowRoot)}appendChild(t,e){return super.appendChild(this.nodeOrShadowRoot(t),e)}insertBefore(t,e,i){return super.insertBefore(this.nodeOrShadowRoot(t),e,i)}removeChild(t,e){return super.removeChild(this.nodeOrShadowRoot(t),e)}parentNode(t){return this.nodeOrShadowRoot(super.parentNode(this.nodeOrShadowRoot(t)))}}let ZL=(()=>{class n extends ED{constructor(e){super(e)}supports(e){return!0}addEventListener(e,i,r){return e.addEventListener(i,r,!1),()=>this.removeEventListener(e,i,r)}removeEventListener(e,i,r){return e.removeEventListener(i,r)}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const OD=[\"alt\",\"control\",\"meta\",\"shift\"],JL={\"\\b\":\"Backspace\",\"\\t\":\"Tab\",\"\\x7f\":\"Delete\",\"\\x1b\":\"Escape\",Del:\"Delete\",Esc:\"Escape\",Left:\"ArrowLeft\",Right:\"ArrowRight\",Up:\"ArrowUp\",Down:\"ArrowDown\",Menu:\"ContextMenu\",Scroll:\"ScrollLock\",Win:\"OS\"},PD={A:\"1\",B:\"2\",C:\"3\",D:\"4\",E:\"5\",F:\"6\",G:\"7\",H:\"8\",I:\"9\",J:\"*\",K:\"+\",M:\"-\",N:\".\",O:\"/\",\"`\":\"0\",\"\\x90\":\"NumLock\"},eB={alt:n=>n.altKey,control:n=>n.ctrlKey,meta:n=>n.metaKey,shift:n=>n.shiftKey};let tB=(()=>{class n extends ED{constructor(e){super(e)}supports(e){return null!=n.parseEventName(e)}addEventListener(e,i,r){const s=n.parseEventName(i),o=n.eventCallback(s.fullKey,r,this.manager.getZone());return this.manager.getZone().runOutsideAngular(()=>mi().onAndCancel(e,s.domEventName,o))}static parseEventName(e){const i=e.toLowerCase().split(\".\"),r=i.shift();if(0===i.length||\"keydown\"!==r&&\"keyup\"!==r)return null;const s=n._normalizeKey(i.pop());let o=\"\";if(OD.forEach(l=>{const c=i.indexOf(l);c>-1&&(i.splice(c,1),o+=l+\".\")}),o+=s,0!=i.length||0===s.length)return null;const a={};return a.domEventName=r,a.fullKey=o,a}static getEventFullKey(e){let i=\"\",r=function nB(n){let t=n.key;if(null==t){if(t=n.keyIdentifier,null==t)return\"Unidentified\";t.startsWith(\"U+\")&&(t=String.fromCharCode(parseInt(t.substring(2),16)),3===n.location&&PD.hasOwnProperty(t)&&(t=PD[t]))}return JL[t]||t}(e);return r=r.toLowerCase(),\" \"===r?r=\"space\":\".\"===r&&(r=\"dot\"),OD.forEach(s=>{s!=r&&eB[s](e)&&(i+=s+\".\")}),i+=r,i}static eventCallback(e,i,r){return s=>{n.getEventFullKey(s)===e&&r.runGuarded(()=>i(s))}}static _normalizeKey(e){return\"esc\"===e?\"escape\":e}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const oB=H0(cN,\"browser\",[{provide:bc,useValue:wD},{provide:I0,useValue:function iB(){pf.makeCurrent(),ff.init()},multi:!0},{provide:ie,useFactory:function sB(){return function DT(n){Bu=n}(document),document},deps:[]}]),aB=[{provide:Jh,useValue:\"root\"},{provide:Mr,useFactory:function rB(){return new Mr},deps:[]},{provide:Nc,useClass:ZL,multi:!0,deps:[ie,ne,bc]},{provide:Nc,useClass:tB,multi:!0,deps:[ie]},{provide:Vc,useClass:Vc,deps:[Lc,wa,ga]},{provide:da,useExisting:Vc},{provide:SD,useExisting:wa},{provide:wa,useClass:wa,deps:[ie]},{provide:$p,useClass:$p,deps:[ne]},{provide:Lc,useClass:Lc,deps:[Nc,ne]},{provide:class LL{},useClass:UL,deps:[]}];let FD=(()=>{class n{constructor(e){if(e)throw new Error(\"BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.\")}static withServerTransition(e){return{ngModule:n,providers:[{provide:ga,useValue:e.appId},{provide:xD,useExisting:ga},zL]}}}return n.\\u0275fac=function(e){return new(e||n)(y(n,12))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:aB,imports:[bt,dN]}),n})();function q(...n){return mt(n,So(n))}\"undefined\"!=typeof window&&window;class Zt extends O{constructor(t){super(),this._value=t}get value(){return this.getValue()}_subscribe(t){const e=super._subscribe(t);return!e.closed&&t.next(this._value),e}getValue(){const{hasError:t,thrownError:e,_value:i}=this;if(t)throw e;return this._throwIfClosed(),i}next(t){super.next(this._value=t)}}const{isArray:vB}=Array,{getPrototypeOf:yB,prototype:bB,keys:CB}=Object;function VD(n){if(1===n.length){const t=n[0];if(vB(t))return{args:t,keys:null};if(function DB(n){return n&&\"object\"==typeof n&&yB(n)===bB}(t)){const e=CB(t);return{args:e.map(i=>t[i]),keys:e}}}return{args:n,keys:null}}const{isArray:wB}=Array;function bf(n){return ue(t=>function MB(n,t){return wB(t)?n(...t):n(t)}(n,t))}function HD(n,t){return n.reduce((e,i,r)=>(e[i]=t[r],e),{})}function jD(n,t,e){n?Mi(e,n,t):t()}function Ma(n,t){const e=De(n)?n:()=>n,i=r=>r.error(e());return new Ve(t?r=>t.schedule(i,0,r):i)}const Hc=xo(n=>function(){n(this),this.name=\"EmptyError\",this.message=\"no elements in sequence\"});function jc(...n){return function SB(){return Eo(1)}()(mt(n,So(n)))}function xa(n){return new Ve(t=>{Jt(n()).subscribe(t)})}function zD(){return qe((n,t)=>{let e=null;n._refCount++;const i=Ue(t,void 0,void 0,void 0,()=>{if(!n||n._refCount<=0||0<--n._refCount)return void(e=null);const r=n._connection,s=e;e=null,r&&(!s||r===s)&&r.unsubscribe(),t.unsubscribe()});n.subscribe(i),i.closed||(e=n.connect())})}class kB extends Ve{constructor(t,e){super(),this.source=t,this.subjectFactory=e,this._subject=null,this._refCount=0,this._connection=null,o_(t)&&(this.lift=t.lift)}_subscribe(t){return this.getSubject().subscribe(t)}getSubject(){const t=this._subject;return(!t||t.isStopped)&&(this._subject=this.subjectFactory()),this._subject}_teardown(){this._refCount=0;const{_connection:t}=this;this._subject=this._connection=null,null==t||t.unsubscribe()}connect(){let t=this._connection;if(!t){t=this._connection=new ke;const e=this.getSubject();t.add(this.source.subscribe(Ue(e,void 0,()=>{this._teardown(),e.complete()},i=>{this._teardown(),e.error(i)},()=>this._teardown()))),t.closed&&(this._connection=null,t=ke.EMPTY)}return t}refCount(){return zD()(this)}}function kn(n,t){return qe((e,i)=>{let r=null,s=0,o=!1;const a=()=>o&&!r&&i.complete();e.subscribe(Ue(i,l=>{null==r||r.unsubscribe();let c=0;const d=s++;Jt(n(l,d)).subscribe(r=Ue(i,u=>i.next(t?t(l,u,d,c++):u),()=>{r=null,a()}))},()=>{o=!0,a()}))})}function Xn(...n){const t=So(n);return qe((e,i)=>{(t?jc(n,e,t):jc(n,e)).subscribe(i)})}function TB(n,t,e,i,r){return(s,o)=>{let a=e,l=t,c=0;s.subscribe(Ue(o,d=>{const u=c++;l=a?n(l,d,u):(a=!0,d),i&&o.next(l)},r&&(()=>{a&&o.next(l),o.complete()})))}}function UD(n,t){return qe(TB(n,t,arguments.length>=2,!0))}function Ct(n,t){return qe((e,i)=>{let r=0;e.subscribe(Ue(i,s=>n.call(t,s,r++)&&i.next(s)))})}function Ni(n){return qe((t,e)=>{let s,i=null,r=!1;i=t.subscribe(Ue(e,void 0,void 0,o=>{s=Jt(n(o,Ni(n)(t))),i?(i.unsubscribe(),i=null,s.subscribe(e)):r=!0})),r&&(i.unsubscribe(),i=null,s.subscribe(e))})}function Qs(n,t){return De(t)?lt(n,t,1):lt(n,1)}function Cf(n){return n<=0?()=>ri:qe((t,e)=>{let i=[];t.subscribe(Ue(e,r=>{i.push(r),n<i.length&&i.shift()},()=>{for(const r of i)e.next(r);e.complete()},void 0,()=>{i=null}))})}function $D(n=AB){return qe((t,e)=>{let i=!1;t.subscribe(Ue(e,r=>{i=!0,e.next(r)},()=>i?e.complete():e.error(n())))})}function AB(){return new Hc}function GD(n){return qe((t,e)=>{let i=!1;t.subscribe(Ue(e,r=>{i=!0,e.next(r)},()=>{i||e.next(n),e.complete()}))})}function Ks(n,t){const e=arguments.length>=2;return i=>i.pipe(n?Ct((r,s)=>n(r,s,i)):Wi,it(1),e?GD(t):$D(()=>new Hc))}function Mt(n,t,e){const i=De(n)||t||e?{next:n,error:t,complete:e}:n;return i?qe((r,s)=>{var o;null===(o=i.subscribe)||void 0===o||o.call(i);let a=!0;r.subscribe(Ue(s,l=>{var c;null===(c=i.next)||void 0===c||c.call(i,l),s.next(l)},()=>{var l;a=!1,null===(l=i.complete)||void 0===l||l.call(i),s.complete()},l=>{var c;a=!1,null===(c=i.error)||void 0===c||c.call(i,l),s.error(l)},()=>{var l,c;a&&(null===(l=i.unsubscribe)||void 0===l||l.call(i)),null===(c=i.finalize)||void 0===c||c.call(i)}))}):Wi}class Li{constructor(t,e){this.id=t,this.url=e}}class Df extends Li{constructor(t,e,i=\"imperative\",r=null){super(t,e),this.navigationTrigger=i,this.restoredState=r}toString(){return`NavigationStart(id: ${this.id}, url: '${this.url}')`}}class Ea extends Li{constructor(t,e,i){super(t,e),this.urlAfterRedirects=i}toString(){return`NavigationEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}')`}}class qD extends Li{constructor(t,e,i){super(t,e),this.reason=i}toString(){return`NavigationCancel(id: ${this.id}, url: '${this.url}')`}}class RB extends Li{constructor(t,e,i){super(t,e),this.error=i}toString(){return`NavigationError(id: ${this.id}, url: '${this.url}', error: ${this.error})`}}class OB extends Li{constructor(t,e,i,r){super(t,e),this.urlAfterRedirects=i,this.state=r}toString(){return`RoutesRecognized(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`}}class PB extends Li{constructor(t,e,i,r){super(t,e),this.urlAfterRedirects=i,this.state=r}toString(){return`GuardsCheckStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`}}class FB extends Li{constructor(t,e,i,r,s){super(t,e),this.urlAfterRedirects=i,this.state=r,this.shouldActivate=s}toString(){return`GuardsCheckEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state}, shouldActivate: ${this.shouldActivate})`}}class NB extends Li{constructor(t,e,i,r){super(t,e),this.urlAfterRedirects=i,this.state=r}toString(){return`ResolveStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`}}class LB extends Li{constructor(t,e,i,r){super(t,e),this.urlAfterRedirects=i,this.state=r}toString(){return`ResolveEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`}}class YD{constructor(t){this.route=t}toString(){return`RouteConfigLoadStart(path: ${this.route.path})`}}class QD{constructor(t){this.route=t}toString(){return`RouteConfigLoadEnd(path: ${this.route.path})`}}class BB{constructor(t){this.snapshot=t}toString(){return`ChildActivationStart(path: '${this.snapshot.routeConfig&&this.snapshot.routeConfig.path||\"\"}')`}}class VB{constructor(t){this.snapshot=t}toString(){return`ChildActivationEnd(path: '${this.snapshot.routeConfig&&this.snapshot.routeConfig.path||\"\"}')`}}class HB{constructor(t){this.snapshot=t}toString(){return`ActivationStart(path: '${this.snapshot.routeConfig&&this.snapshot.routeConfig.path||\"\"}')`}}class jB{constructor(t){this.snapshot=t}toString(){return`ActivationEnd(path: '${this.snapshot.routeConfig&&this.snapshot.routeConfig.path||\"\"}')`}}class KD{constructor(t,e,i){this.routerEvent=t,this.position=e,this.anchor=i}toString(){return`Scroll(anchor: '${this.anchor}', position: '${this.position?`${this.position[0]}, ${this.position[1]}`:null}')`}}const me=\"primary\";class zB{constructor(t){this.params=t||{}}has(t){return Object.prototype.hasOwnProperty.call(this.params,t)}get(t){if(this.has(t)){const e=this.params[t];return Array.isArray(e)?e[0]:e}return null}getAll(t){if(this.has(t)){const e=this.params[t];return Array.isArray(e)?e:[e]}return[]}get keys(){return Object.keys(this.params)}}function Zs(n){return new zB(n)}const ZD=\"ngNavigationCancelingError\";function wf(n){const t=Error(\"NavigationCancelingError: \"+n);return t[ZD]=!0,t}function $B(n,t,e){const i=e.path.split(\"/\");if(i.length>n.length||\"full\"===e.pathMatch&&(t.hasChildren()||i.length<n.length))return null;const r={};for(let s=0;s<i.length;s++){const o=i[s],a=n[s];if(o.startsWith(\":\"))r[o.substring(1)]=a;else if(o!==a.path)return null}return{consumed:n.slice(0,i.length),posParams:r}}function gi(n,t){const e=n?Object.keys(n):void 0,i=t?Object.keys(t):void 0;if(!e||!i||e.length!=i.length)return!1;let r;for(let s=0;s<e.length;s++)if(r=e[s],!XD(n[r],t[r]))return!1;return!0}function XD(n,t){if(Array.isArray(n)&&Array.isArray(t)){if(n.length!==t.length)return!1;const e=[...n].sort(),i=[...t].sort();return e.every((r,s)=>i[s]===r)}return n===t}function JD(n){return Array.prototype.concat.apply([],n)}function ew(n){return n.length>0?n[n.length-1]:null}function At(n,t){for(const e in n)n.hasOwnProperty(e)&&t(n[e],e)}function _i(n){return up(n)?n:ra(n)?mt(Promise.resolve(n)):q(n)}const qB={exact:function iw(n,t,e){if(!Nr(n.segments,t.segments)||!zc(n.segments,t.segments,e)||n.numberOfChildren!==t.numberOfChildren)return!1;for(const i in t.children)if(!n.children[i]||!iw(n.children[i],t.children[i],e))return!1;return!0},subset:rw},tw={exact:function YB(n,t){return gi(n,t)},subset:function QB(n,t){return Object.keys(t).length<=Object.keys(n).length&&Object.keys(t).every(e=>XD(n[e],t[e]))},ignored:()=>!0};function nw(n,t,e){return qB[e.paths](n.root,t.root,e.matrixParams)&&tw[e.queryParams](n.queryParams,t.queryParams)&&!(\"exact\"===e.fragment&&n.fragment!==t.fragment)}function rw(n,t,e){return sw(n,t,t.segments,e)}function sw(n,t,e,i){if(n.segments.length>e.length){const r=n.segments.slice(0,e.length);return!(!Nr(r,e)||t.hasChildren()||!zc(r,e,i))}if(n.segments.length===e.length){if(!Nr(n.segments,e)||!zc(n.segments,e,i))return!1;for(const r in t.children)if(!n.children[r]||!rw(n.children[r],t.children[r],i))return!1;return!0}{const r=e.slice(0,n.segments.length),s=e.slice(n.segments.length);return!!(Nr(n.segments,r)&&zc(n.segments,r,i)&&n.children[me])&&sw(n.children[me],t,s,i)}}function zc(n,t,e){return t.every((i,r)=>tw[e](n[r].parameters,i.parameters))}class Fr{constructor(t,e,i){this.root=t,this.queryParams=e,this.fragment=i}get queryParamMap(){return this._queryParamMap||(this._queryParamMap=Zs(this.queryParams)),this._queryParamMap}toString(){return XB.serialize(this)}}class ye{constructor(t,e){this.segments=t,this.children=e,this.parent=null,At(e,(i,r)=>i.parent=this)}hasChildren(){return this.numberOfChildren>0}get numberOfChildren(){return Object.keys(this.children).length}toString(){return Uc(this)}}class Sa{constructor(t,e){this.path=t,this.parameters=e}get parameterMap(){return this._parameterMap||(this._parameterMap=Zs(this.parameters)),this._parameterMap}toString(){return dw(this)}}function Nr(n,t){return n.length===t.length&&n.every((e,i)=>e.path===t[i].path)}class ow{}class aw{parse(t){const e=new aV(t);return new Fr(e.parseRootSegment(),e.parseQueryParams(),e.parseFragment())}serialize(t){const e=`/${ka(t.root,!0)}`,i=function tV(n){const t=Object.keys(n).map(e=>{const i=n[e];return Array.isArray(i)?i.map(r=>`${$c(e)}=${$c(r)}`).join(\"&\"):`${$c(e)}=${$c(i)}`}).filter(e=>!!e);return t.length?`?${t.join(\"&\")}`:\"\"}(t.queryParams);return`${e}${i}${\"string\"==typeof t.fragment?`#${function JB(n){return encodeURI(n)}(t.fragment)}`:\"\"}`}}const XB=new aw;function Uc(n){return n.segments.map(t=>dw(t)).join(\"/\")}function ka(n,t){if(!n.hasChildren())return Uc(n);if(t){const e=n.children[me]?ka(n.children[me],!1):\"\",i=[];return At(n.children,(r,s)=>{s!==me&&i.push(`${s}:${ka(r,!1)}`)}),i.length>0?`${e}(${i.join(\"//\")})`:e}{const e=function ZB(n,t){let e=[];return At(n.children,(i,r)=>{r===me&&(e=e.concat(t(i,r)))}),At(n.children,(i,r)=>{r!==me&&(e=e.concat(t(i,r)))}),e}(n,(i,r)=>r===me?[ka(n.children[me],!1)]:[`${r}:${ka(i,!1)}`]);return 1===Object.keys(n.children).length&&null!=n.children[me]?`${Uc(n)}/${e[0]}`:`${Uc(n)}/(${e.join(\"//\")})`}}function lw(n){return encodeURIComponent(n).replace(/%40/g,\"@\").replace(/%3A/gi,\":\").replace(/%24/g,\"$\").replace(/%2C/gi,\",\")}function $c(n){return lw(n).replace(/%3B/gi,\";\")}function Mf(n){return lw(n).replace(/\\(/g,\"%28\").replace(/\\)/g,\"%29\").replace(/%26/gi,\"&\")}function Gc(n){return decodeURIComponent(n)}function cw(n){return Gc(n.replace(/\\+/g,\"%20\"))}function dw(n){return`${Mf(n.path)}${function eV(n){return Object.keys(n).map(t=>`;${Mf(t)}=${Mf(n[t])}`).join(\"\")}(n.parameters)}`}const nV=/^[^\\/()?;=#]+/;function Wc(n){const t=n.match(nV);return t?t[0]:\"\"}const iV=/^[^=?&#]+/,sV=/^[^&#]+/;class aV{constructor(t){this.url=t,this.remaining=t}parseRootSegment(){return this.consumeOptional(\"/\"),\"\"===this.remaining||this.peekStartsWith(\"?\")||this.peekStartsWith(\"#\")?new ye([],{}):new ye([],this.parseChildren())}parseQueryParams(){const t={};if(this.consumeOptional(\"?\"))do{this.parseQueryParam(t)}while(this.consumeOptional(\"&\"));return t}parseFragment(){return this.consumeOptional(\"#\")?decodeURIComponent(this.remaining):null}parseChildren(){if(\"\"===this.remaining)return{};this.consumeOptional(\"/\");const t=[];for(this.peekStartsWith(\"(\")||t.push(this.parseSegment());this.peekStartsWith(\"/\")&&!this.peekStartsWith(\"//\")&&!this.peekStartsWith(\"/(\");)this.capture(\"/\"),t.push(this.parseSegment());let e={};this.peekStartsWith(\"/(\")&&(this.capture(\"/\"),e=this.parseParens(!0));let i={};return this.peekStartsWith(\"(\")&&(i=this.parseParens(!1)),(t.length>0||Object.keys(e).length>0)&&(i[me]=new ye(t,e)),i}parseSegment(){const t=Wc(this.remaining);if(\"\"===t&&this.peekStartsWith(\";\"))throw new Error(`Empty path url segment cannot have parameters: '${this.remaining}'.`);return this.capture(t),new Sa(Gc(t),this.parseMatrixParams())}parseMatrixParams(){const t={};for(;this.consumeOptional(\";\");)this.parseParam(t);return t}parseParam(t){const e=Wc(this.remaining);if(!e)return;this.capture(e);let i=\"\";if(this.consumeOptional(\"=\")){const r=Wc(this.remaining);r&&(i=r,this.capture(i))}t[Gc(e)]=Gc(i)}parseQueryParam(t){const e=function rV(n){const t=n.match(iV);return t?t[0]:\"\"}(this.remaining);if(!e)return;this.capture(e);let i=\"\";if(this.consumeOptional(\"=\")){const o=function oV(n){const t=n.match(sV);return t?t[0]:\"\"}(this.remaining);o&&(i=o,this.capture(i))}const r=cw(e),s=cw(i);if(t.hasOwnProperty(r)){let o=t[r];Array.isArray(o)||(o=[o],t[r]=o),o.push(s)}else t[r]=s}parseParens(t){const e={};for(this.capture(\"(\");!this.consumeOptional(\")\")&&this.remaining.length>0;){const i=Wc(this.remaining),r=this.remaining[i.length];if(\"/\"!==r&&\")\"!==r&&\";\"!==r)throw new Error(`Cannot parse url '${this.url}'`);let s;i.indexOf(\":\")>-1?(s=i.substr(0,i.indexOf(\":\")),this.capture(s),this.capture(\":\")):t&&(s=me);const o=this.parseChildren();e[s]=1===Object.keys(o).length?o[me]:new ye([],o),this.consumeOptional(\"//\")}return e}peekStartsWith(t){return this.remaining.startsWith(t)}consumeOptional(t){return!!this.peekStartsWith(t)&&(this.remaining=this.remaining.substring(t.length),!0)}capture(t){if(!this.consumeOptional(t))throw new Error(`Expected \"${t}\".`)}}class uw{constructor(t){this._root=t}get root(){return this._root.value}parent(t){const e=this.pathFromRoot(t);return e.length>1?e[e.length-2]:null}children(t){const e=xf(t,this._root);return e?e.children.map(i=>i.value):[]}firstChild(t){const e=xf(t,this._root);return e&&e.children.length>0?e.children[0].value:null}siblings(t){const e=Ef(t,this._root);return e.length<2?[]:e[e.length-2].children.map(r=>r.value).filter(r=>r!==t)}pathFromRoot(t){return Ef(t,this._root).map(e=>e.value)}}function xf(n,t){if(n===t.value)return t;for(const e of t.children){const i=xf(n,e);if(i)return i}return null}function Ef(n,t){if(n===t.value)return[t];for(const e of t.children){const i=Ef(n,e);if(i.length)return i.unshift(t),i}return[]}class Bi{constructor(t,e){this.value=t,this.children=e}toString(){return`TreeNode(${this.value})`}}function Xs(n){const t={};return n&&n.children.forEach(e=>t[e.value.outlet]=e),t}class hw extends uw{constructor(t,e){super(t),this.snapshot=e,Sf(this,t)}toString(){return this.snapshot.toString()}}function pw(n,t){const e=function lV(n,t){const o=new qc([],{},{},\"\",{},me,t,null,n.root,-1,{});return new mw(\"\",new Bi(o,[]))}(n,t),i=new Zt([new Sa(\"\",{})]),r=new Zt({}),s=new Zt({}),o=new Zt({}),a=new Zt(\"\"),l=new Js(i,r,o,a,s,me,t,e.root);return l.snapshot=e.root,new hw(new Bi(l,[]),e)}class Js{constructor(t,e,i,r,s,o,a,l){this.url=t,this.params=e,this.queryParams=i,this.fragment=r,this.data=s,this.outlet=o,this.component=a,this._futureSnapshot=l}get routeConfig(){return this._futureSnapshot.routeConfig}get root(){return this._routerState.root}get parent(){return this._routerState.parent(this)}get firstChild(){return this._routerState.firstChild(this)}get children(){return this._routerState.children(this)}get pathFromRoot(){return this._routerState.pathFromRoot(this)}get paramMap(){return this._paramMap||(this._paramMap=this.params.pipe(ue(t=>Zs(t)))),this._paramMap}get queryParamMap(){return this._queryParamMap||(this._queryParamMap=this.queryParams.pipe(ue(t=>Zs(t)))),this._queryParamMap}toString(){return this.snapshot?this.snapshot.toString():`Future(${this._futureSnapshot})`}}function fw(n,t=\"emptyOnly\"){const e=n.pathFromRoot;let i=0;if(\"always\"!==t)for(i=e.length-1;i>=1;){const r=e[i],s=e[i-1];if(r.routeConfig&&\"\"===r.routeConfig.path)i--;else{if(s.component)break;i--}}return function cV(n){return n.reduce((t,e)=>({params:Object.assign(Object.assign({},t.params),e.params),data:Object.assign(Object.assign({},t.data),e.data),resolve:Object.assign(Object.assign({},t.resolve),e._resolvedData)}),{params:{},data:{},resolve:{}})}(e.slice(i))}class qc{constructor(t,e,i,r,s,o,a,l,c,d,u){this.url=t,this.params=e,this.queryParams=i,this.fragment=r,this.data=s,this.outlet=o,this.component=a,this.routeConfig=l,this._urlSegment=c,this._lastPathIndex=d,this._resolve=u}get root(){return this._routerState.root}get parent(){return this._routerState.parent(this)}get firstChild(){return this._routerState.firstChild(this)}get children(){return this._routerState.children(this)}get pathFromRoot(){return this._routerState.pathFromRoot(this)}get paramMap(){return this._paramMap||(this._paramMap=Zs(this.params)),this._paramMap}get queryParamMap(){return this._queryParamMap||(this._queryParamMap=Zs(this.queryParams)),this._queryParamMap}toString(){return`Route(url:'${this.url.map(i=>i.toString()).join(\"/\")}', path:'${this.routeConfig?this.routeConfig.path:\"\"}')`}}class mw extends uw{constructor(t,e){super(e),this.url=t,Sf(this,e)}toString(){return gw(this._root)}}function Sf(n,t){t.value._routerState=n,t.children.forEach(e=>Sf(n,e))}function gw(n){const t=n.children.length>0?` { ${n.children.map(gw).join(\", \")} } `:\"\";return`${n.value}${t}`}function kf(n){if(n.snapshot){const t=n.snapshot,e=n._futureSnapshot;n.snapshot=e,gi(t.queryParams,e.queryParams)||n.queryParams.next(e.queryParams),t.fragment!==e.fragment&&n.fragment.next(e.fragment),gi(t.params,e.params)||n.params.next(e.params),function GB(n,t){if(n.length!==t.length)return!1;for(let e=0;e<n.length;++e)if(!gi(n[e],t[e]))return!1;return!0}(t.url,e.url)||n.url.next(e.url),gi(t.data,e.data)||n.data.next(e.data)}else n.snapshot=n._futureSnapshot,n.data.next(n._futureSnapshot.data)}function Tf(n,t){const e=gi(n.params,t.params)&&function KB(n,t){return Nr(n,t)&&n.every((e,i)=>gi(e.parameters,t[i].parameters))}(n.url,t.url);return e&&!(!n.parent!=!t.parent)&&(!n.parent||Tf(n.parent,t.parent))}function Ta(n,t,e){if(e&&n.shouldReuseRoute(t.value,e.value.snapshot)){const i=e.value;i._futureSnapshot=t.value;const r=function uV(n,t,e){return t.children.map(i=>{for(const r of e.children)if(n.shouldReuseRoute(i.value,r.value.snapshot))return Ta(n,i,r);return Ta(n,i)})}(n,t,e);return new Bi(i,r)}{if(n.shouldAttach(t.value)){const s=n.retrieve(t.value);if(null!==s){const o=s.route;return o.value._futureSnapshot=t.value,o.children=t.children.map(a=>Ta(n,a)),o}}const i=function hV(n){return new Js(new Zt(n.url),new Zt(n.params),new Zt(n.queryParams),new Zt(n.fragment),new Zt(n.data),n.outlet,n.component,n)}(t.value),r=t.children.map(s=>Ta(n,s));return new Bi(i,r)}}function Yc(n){return\"object\"==typeof n&&null!=n&&!n.outlets&&!n.segmentPath}function Aa(n){return\"object\"==typeof n&&null!=n&&n.outlets}function Af(n,t,e,i,r){let s={};if(i&&At(i,(a,l)=>{s[l]=Array.isArray(a)?a.map(c=>`${c}`):`${a}`}),n===t)return new Fr(e,s,r);const o=_w(n,t,e);return new Fr(o,s,r)}function _w(n,t,e){const i={};return At(n.children,(r,s)=>{i[s]=r===t?e:_w(r,t,e)}),new ye(n.segments,i)}class vw{constructor(t,e,i){if(this.isAbsolute=t,this.numberOfDoubleDots=e,this.commands=i,t&&i.length>0&&Yc(i[0]))throw new Error(\"Root segment cannot have matrix parameters\");const r=i.find(Aa);if(r&&r!==ew(i))throw new Error(\"{outlets:{}} has to be the last command\")}toRoot(){return this.isAbsolute&&1===this.commands.length&&\"/\"==this.commands[0]}}class If{constructor(t,e,i){this.segmentGroup=t,this.processChildren=e,this.index=i}}function yw(n,t,e){if(n||(n=new ye([],{})),0===n.segments.length&&n.hasChildren())return Qc(n,t,e);const i=function vV(n,t,e){let i=0,r=t;const s={match:!1,pathIndex:0,commandIndex:0};for(;r<n.segments.length;){if(i>=e.length)return s;const o=n.segments[r],a=e[i];if(Aa(a))break;const l=`${a}`,c=i<e.length-1?e[i+1]:null;if(r>0&&void 0===l)break;if(l&&c&&\"object\"==typeof c&&void 0===c.outlets){if(!Cw(l,c,o))return s;i+=2}else{if(!Cw(l,{},o))return s;i++}r++}return{match:!0,pathIndex:r,commandIndex:i}}(n,t,e),r=e.slice(i.commandIndex);if(i.match&&i.pathIndex<n.segments.length){const s=new ye(n.segments.slice(0,i.pathIndex),{});return s.children[me]=new ye(n.segments.slice(i.pathIndex),n.children),Qc(s,0,r)}return i.match&&0===r.length?new ye(n.segments,{}):i.match&&!n.hasChildren()?Rf(n,t,e):i.match?Qc(n,0,r):Rf(n,t,e)}function Qc(n,t,e){if(0===e.length)return new ye(n.segments,{});{const i=function _V(n){return Aa(n[0])?n[0].outlets:{[me]:n}}(e),r={};return At(i,(s,o)=>{\"string\"==typeof s&&(s=[s]),null!==s&&(r[o]=yw(n.children[o],t,s))}),At(n.children,(s,o)=>{void 0===i[o]&&(r[o]=s)}),new ye(n.segments,r)}}function Rf(n,t,e){const i=n.segments.slice(0,t);let r=0;for(;r<e.length;){const s=e[r];if(Aa(s)){const l=yV(s.outlets);return new ye(i,l)}if(0===r&&Yc(e[0])){i.push(new Sa(n.segments[t].path,bw(e[0]))),r++;continue}const o=Aa(s)?s.outlets[me]:`${s}`,a=r<e.length-1?e[r+1]:null;o&&a&&Yc(a)?(i.push(new Sa(o,bw(a))),r+=2):(i.push(new Sa(o,{})),r++)}return new ye(i,{})}function yV(n){const t={};return At(n,(e,i)=>{\"string\"==typeof e&&(e=[e]),null!==e&&(t[i]=Rf(new ye([],{}),0,e))}),t}function bw(n){const t={};return At(n,(e,i)=>t[i]=`${e}`),t}function Cw(n,t,e){return n==e.path&&gi(t,e.parameters)}class CV{constructor(t,e,i,r){this.routeReuseStrategy=t,this.futureState=e,this.currState=i,this.forwardEvent=r}activate(t){const e=this.futureState._root,i=this.currState?this.currState._root:null;this.deactivateChildRoutes(e,i,t),kf(this.futureState.root),this.activateChildRoutes(e,i,t)}deactivateChildRoutes(t,e,i){const r=Xs(e);t.children.forEach(s=>{const o=s.value.outlet;this.deactivateRoutes(s,r[o],i),delete r[o]}),At(r,(s,o)=>{this.deactivateRouteAndItsChildren(s,i)})}deactivateRoutes(t,e,i){const r=t.value,s=e?e.value:null;if(r===s)if(r.component){const o=i.getContext(r.outlet);o&&this.deactivateChildRoutes(t,e,o.children)}else this.deactivateChildRoutes(t,e,i);else s&&this.deactivateRouteAndItsChildren(e,i)}deactivateRouteAndItsChildren(t,e){t.value.component&&this.routeReuseStrategy.shouldDetach(t.value.snapshot)?this.detachAndStoreRouteSubtree(t,e):this.deactivateRouteAndOutlet(t,e)}detachAndStoreRouteSubtree(t,e){const i=e.getContext(t.value.outlet),r=i&&t.value.component?i.children:e,s=Xs(t);for(const o of Object.keys(s))this.deactivateRouteAndItsChildren(s[o],r);if(i&&i.outlet){const o=i.outlet.detach(),a=i.children.onOutletDeactivated();this.routeReuseStrategy.store(t.value.snapshot,{componentRef:o,route:t,contexts:a})}}deactivateRouteAndOutlet(t,e){const i=e.getContext(t.value.outlet),r=i&&t.value.component?i.children:e,s=Xs(t);for(const o of Object.keys(s))this.deactivateRouteAndItsChildren(s[o],r);i&&i.outlet&&(i.outlet.deactivate(),i.children.onOutletDeactivated(),i.attachRef=null,i.resolver=null,i.route=null)}activateChildRoutes(t,e,i){const r=Xs(e);t.children.forEach(s=>{this.activateRoutes(s,r[s.value.outlet],i),this.forwardEvent(new jB(s.value.snapshot))}),t.children.length&&this.forwardEvent(new VB(t.value.snapshot))}activateRoutes(t,e,i){const r=t.value,s=e?e.value:null;if(kf(r),r===s)if(r.component){const o=i.getOrCreateContext(r.outlet);this.activateChildRoutes(t,e,o.children)}else this.activateChildRoutes(t,e,i);else if(r.component){const o=i.getOrCreateContext(r.outlet);if(this.routeReuseStrategy.shouldAttach(r.snapshot)){const a=this.routeReuseStrategy.retrieve(r.snapshot);this.routeReuseStrategy.store(r.snapshot,null),o.children.onOutletReAttached(a.contexts),o.attachRef=a.componentRef,o.route=a.route.value,o.outlet&&o.outlet.attach(a.componentRef,a.route.value),kf(a.route.value),this.activateChildRoutes(t,null,o.children)}else{const a=function DV(n){for(let t=n.parent;t;t=t.parent){const e=t.routeConfig;if(e&&e._loadedConfig)return e._loadedConfig;if(e&&e.component)return null}return null}(r.snapshot),l=a?a.module.componentFactoryResolver:null;o.attachRef=null,o.route=r,o.resolver=l,o.outlet&&o.outlet.activateWith(r,l),this.activateChildRoutes(t,null,o.children)}}else this.activateChildRoutes(t,null,i)}}class Of{constructor(t,e){this.routes=t,this.module=e}}function nr(n){return\"function\"==typeof n}function Lr(n){return n instanceof Fr}const Ia=Symbol(\"INITIAL_VALUE\");function Ra(){return kn(n=>function xB(...n){const t=So(n),e=b_(n),{args:i,keys:r}=VD(n);if(0===i.length)return mt([],t);const s=new Ve(function EB(n,t,e=Wi){return i=>{jD(t,()=>{const{length:r}=n,s=new Array(r);let o=r,a=r;for(let l=0;l<r;l++)jD(t,()=>{const c=mt(n[l],t);let d=!1;c.subscribe(Ue(i,u=>{s[l]=u,d||(d=!0,a--),a||i.next(e(s.slice()))},()=>{--o||i.complete()}))},i)},i)}}(i,t,r?o=>HD(r,o):Wi));return e?s.pipe(bf(e)):s}(n.map(t=>t.pipe(it(1),Xn(Ia)))).pipe(UD((t,e)=>{let i=!1;return e.reduce((r,s,o)=>r!==Ia?r:(s===Ia&&(i=!0),i||!1!==s&&o!==e.length-1&&!Lr(s)?r:s),t)},Ia),Ct(t=>t!==Ia),ue(t=>Lr(t)?t:!0===t),it(1)))}class kV{constructor(){this.outlet=null,this.route=null,this.resolver=null,this.children=new Oa,this.attachRef=null}}class Oa{constructor(){this.contexts=new Map}onChildOutletCreated(t,e){const i=this.getOrCreateContext(t);i.outlet=e,this.contexts.set(t,i)}onChildOutletDestroyed(t){const e=this.getContext(t);e&&(e.outlet=null,e.attachRef=null)}onOutletDeactivated(){const t=this.contexts;return this.contexts=new Map,t}onOutletReAttached(t){this.contexts=t}getOrCreateContext(t){let e=this.getContext(t);return e||(e=new kV,this.contexts.set(t,e)),e}getContext(t){return this.contexts.get(t)||null}}let Pf=(()=>{class n{constructor(e,i,r,s,o){this.parentContexts=e,this.location=i,this.resolver=r,this.changeDetector=o,this.activated=null,this._activatedRoute=null,this.activateEvents=new $,this.deactivateEvents=new $,this.attachEvents=new $,this.detachEvents=new $,this.name=s||me,e.onChildOutletCreated(this.name,this)}ngOnDestroy(){this.parentContexts.onChildOutletDestroyed(this.name)}ngOnInit(){if(!this.activated){const e=this.parentContexts.getContext(this.name);e&&e.route&&(e.attachRef?this.attach(e.attachRef,e.route):this.activateWith(e.route,e.resolver||null))}}get isActivated(){return!!this.activated}get component(){if(!this.activated)throw new Error(\"Outlet is not activated\");return this.activated.instance}get activatedRoute(){if(!this.activated)throw new Error(\"Outlet is not activated\");return this._activatedRoute}get activatedRouteData(){return this._activatedRoute?this._activatedRoute.snapshot.data:{}}detach(){if(!this.activated)throw new Error(\"Outlet is not activated\");this.location.detach();const e=this.activated;return this.activated=null,this._activatedRoute=null,this.detachEvents.emit(e.instance),e}attach(e,i){this.activated=e,this._activatedRoute=i,this.location.insert(e.hostView),this.attachEvents.emit(e.instance)}deactivate(){if(this.activated){const e=this.component;this.activated.destroy(),this.activated=null,this._activatedRoute=null,this.deactivateEvents.emit(e)}}activateWith(e,i){if(this.isActivated)throw new Error(\"Cannot activate an already activated outlet\");this._activatedRoute=e;const o=(i=i||this.resolver).resolveComponentFactory(e._futureSnapshot.routeConfig.component),a=this.parentContexts.getOrCreateContext(this.name).children,l=new TV(e,a,this.location.injector);this.activated=this.location.createComponent(o,this.location.length,l),this.changeDetector.markForCheck(),this.activateEvents.emit(this.activated.instance)}}return n.\\u0275fac=function(e){return new(e||n)(f(Oa),f(st),f(Ir),kt(\"name\"),f(Ye))},n.\\u0275dir=C({type:n,selectors:[[\"router-outlet\"]],outputs:{activateEvents:\"activate\",deactivateEvents:\"deactivate\",attachEvents:\"attach\",detachEvents:\"detach\"},exportAs:[\"outlet\"]}),n})();class TV{constructor(t,e,i){this.route=t,this.childContexts=e,this.parent=i}get(t,e){return t===Js?this.route:t===Oa?this.childContexts:this.parent.get(t,e)}}let Dw=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275cmp=xe({type:n,selectors:[[\"ng-component\"]],decls:1,vars:0,template:function(e,i){1&e&&Le(0,\"router-outlet\")},directives:[Pf],encapsulation:2}),n})();function ww(n,t=\"\"){for(let e=0;e<n.length;e++){const i=n[e];AV(i,IV(t,i))}}function AV(n,t){n.children&&ww(n.children,t)}function IV(n,t){return t?n||t.path?n&&!t.path?`${n}/`:!n&&t.path?t.path:`${n}/${t.path}`:\"\":n}function Ff(n){const t=n.children&&n.children.map(Ff),e=t?Object.assign(Object.assign({},n),{children:t}):Object.assign({},n);return!e.component&&(t||e.loadChildren)&&e.outlet&&e.outlet!==me&&(e.component=Dw),e}function Tn(n){return n.outlet||me}function Mw(n,t){const e=n.filter(i=>Tn(i)===t);return e.push(...n.filter(i=>Tn(i)!==t)),e}const xw={matched:!1,consumedSegments:[],remainingSegments:[],parameters:{},positionalParamSegments:{}};function Kc(n,t,e){var i;if(\"\"===t.path)return\"full\"===t.pathMatch&&(n.hasChildren()||e.length>0)?Object.assign({},xw):{matched:!0,consumedSegments:[],remainingSegments:e,parameters:{},positionalParamSegments:{}};const s=(t.matcher||$B)(e,n,t);if(!s)return Object.assign({},xw);const o={};At(s.posParams,(l,c)=>{o[c]=l.path});const a=s.consumed.length>0?Object.assign(Object.assign({},o),s.consumed[s.consumed.length-1].parameters):o;return{matched:!0,consumedSegments:s.consumed,remainingSegments:e.slice(s.consumed.length),parameters:a,positionalParamSegments:null!==(i=s.posParams)&&void 0!==i?i:{}}}function Zc(n,t,e,i,r=\"corrected\"){if(e.length>0&&function PV(n,t,e){return e.some(i=>Xc(n,t,i)&&Tn(i)!==me)}(n,e,i)){const o=new ye(t,function OV(n,t,e,i){const r={};r[me]=i,i._sourceSegment=n,i._segmentIndexShift=t.length;for(const s of e)if(\"\"===s.path&&Tn(s)!==me){const o=new ye([],{});o._sourceSegment=n,o._segmentIndexShift=t.length,r[Tn(s)]=o}return r}(n,t,i,new ye(e,n.children)));return o._sourceSegment=n,o._segmentIndexShift=t.length,{segmentGroup:o,slicedSegments:[]}}if(0===e.length&&function FV(n,t,e){return e.some(i=>Xc(n,t,i))}(n,e,i)){const o=new ye(n.segments,function RV(n,t,e,i,r,s){const o={};for(const a of i)if(Xc(n,e,a)&&!r[Tn(a)]){const l=new ye([],{});l._sourceSegment=n,l._segmentIndexShift=\"legacy\"===s?n.segments.length:t.length,o[Tn(a)]=l}return Object.assign(Object.assign({},r),o)}(n,t,e,i,n.children,r));return o._sourceSegment=n,o._segmentIndexShift=t.length,{segmentGroup:o,slicedSegments:e}}const s=new ye(n.segments,n.children);return s._sourceSegment=n,s._segmentIndexShift=t.length,{segmentGroup:s,slicedSegments:e}}function Xc(n,t,e){return(!(n.hasChildren()||t.length>0)||\"full\"!==e.pathMatch)&&\"\"===e.path}function Ew(n,t,e,i){return!!(Tn(n)===i||i!==me&&Xc(t,e,n))&&(\"**\"===n.path||Kc(t,n,e).matched)}function Sw(n,t,e){return 0===t.length&&!n.children[e]}class Jc{constructor(t){this.segmentGroup=t||null}}class kw{constructor(t){this.urlTree=t}}function Pa(n){return Ma(new Jc(n))}function Tw(n){return Ma(new kw(n))}class VV{constructor(t,e,i,r,s){this.configLoader=e,this.urlSerializer=i,this.urlTree=r,this.config=s,this.allowRedirects=!0,this.ngModule=t.get(Ri)}apply(){const t=Zc(this.urlTree.root,[],[],this.config).segmentGroup,e=new ye(t.segments,t.children);return this.expandSegmentGroup(this.ngModule,this.config,e,me).pipe(ue(s=>this.createUrlTree(Nf(s),this.urlTree.queryParams,this.urlTree.fragment))).pipe(Ni(s=>{if(s instanceof kw)return this.allowRedirects=!1,this.match(s.urlTree);throw s instanceof Jc?this.noMatchError(s):s}))}match(t){return this.expandSegmentGroup(this.ngModule,this.config,t.root,me).pipe(ue(r=>this.createUrlTree(Nf(r),t.queryParams,t.fragment))).pipe(Ni(r=>{throw r instanceof Jc?this.noMatchError(r):r}))}noMatchError(t){return new Error(`Cannot match any routes. URL Segment: '${t.segmentGroup}'`)}createUrlTree(t,e,i){const r=t.segments.length>0?new ye([],{[me]:t}):t;return new Fr(r,e,i)}expandSegmentGroup(t,e,i,r){return 0===i.segments.length&&i.hasChildren()?this.expandChildren(t,e,i).pipe(ue(s=>new ye([],s))):this.expandSegment(t,i,e,i.segments,r,!0)}expandChildren(t,e,i){const r=[];for(const s of Object.keys(i.children))\"primary\"===s?r.unshift(s):r.push(s);return mt(r).pipe(Qs(s=>{const o=i.children[s],a=Mw(e,s);return this.expandSegmentGroup(t,a,o,s).pipe(ue(l=>({segment:l,outlet:s})))}),UD((s,o)=>(s[o.outlet]=o.segment,s),{}),function IB(n,t){const e=arguments.length>=2;return i=>i.pipe(n?Ct((r,s)=>n(r,s,i)):Wi,Cf(1),e?GD(t):$D(()=>new Hc))}())}expandSegment(t,e,i,r,s,o){return mt(i).pipe(Qs(a=>this.expandSegmentAgainstRoute(t,e,i,a,r,s,o).pipe(Ni(c=>{if(c instanceof Jc)return q(null);throw c}))),Ks(a=>!!a),Ni((a,l)=>{if(a instanceof Hc||\"EmptyError\"===a.name)return Sw(e,r,s)?q(new ye([],{})):Pa(e);throw a}))}expandSegmentAgainstRoute(t,e,i,r,s,o,a){return Ew(r,e,s,o)?void 0===r.redirectTo?this.matchSegmentAgainstRoute(t,e,r,s,o):a&&this.allowRedirects?this.expandSegmentAgainstRouteUsingRedirect(t,e,i,r,s,o):Pa(e):Pa(e)}expandSegmentAgainstRouteUsingRedirect(t,e,i,r,s,o){return\"**\"===r.path?this.expandWildCardWithParamsAgainstRouteUsingRedirect(t,i,r,o):this.expandRegularSegmentAgainstRouteUsingRedirect(t,e,i,r,s,o)}expandWildCardWithParamsAgainstRouteUsingRedirect(t,e,i,r){const s=this.applyRedirectCommands([],i.redirectTo,{});return i.redirectTo.startsWith(\"/\")?Tw(s):this.lineralizeSegments(i,s).pipe(lt(o=>{const a=new ye(o,{});return this.expandSegment(t,a,e,o,r,!1)}))}expandRegularSegmentAgainstRouteUsingRedirect(t,e,i,r,s,o){const{matched:a,consumedSegments:l,remainingSegments:c,positionalParamSegments:d}=Kc(e,r,s);if(!a)return Pa(e);const u=this.applyRedirectCommands(l,r.redirectTo,d);return r.redirectTo.startsWith(\"/\")?Tw(u):this.lineralizeSegments(r,u).pipe(lt(h=>this.expandSegment(t,e,i,h.concat(c),o,!1)))}matchSegmentAgainstRoute(t,e,i,r,s){if(\"**\"===i.path)return i.loadChildren?(i._loadedConfig?q(i._loadedConfig):this.configLoader.load(t.injector,i)).pipe(ue(u=>(i._loadedConfig=u,new ye(r,{})))):q(new ye(r,{}));const{matched:o,consumedSegments:a,remainingSegments:l}=Kc(e,i,r);return o?this.getChildConfig(t,i,r).pipe(lt(d=>{const u=d.module,h=d.routes,{segmentGroup:p,slicedSegments:m}=Zc(e,a,l,h),g=new ye(p.segments,p.children);if(0===m.length&&g.hasChildren())return this.expandChildren(u,h,g).pipe(ue(M=>new ye(a,M)));if(0===h.length&&0===m.length)return q(new ye(a,{}));const _=Tn(i)===s;return this.expandSegment(u,g,h,m,_?me:s,!0).pipe(ue(v=>new ye(a.concat(v.segments),v.children)))})):Pa(e)}getChildConfig(t,e,i){return e.children?q(new Of(e.children,t)):e.loadChildren?void 0!==e._loadedConfig?q(e._loadedConfig):this.runCanLoadGuards(t.injector,e,i).pipe(lt(r=>r?this.configLoader.load(t.injector,e).pipe(ue(s=>(e._loadedConfig=s,s))):function LV(n){return Ma(wf(`Cannot load children because the guard of the route \"path: '${n.path}'\" returned false`))}(e))):q(new Of([],t))}runCanLoadGuards(t,e,i){const r=e.canLoad;return r&&0!==r.length?q(r.map(o=>{const a=t.get(o);let l;if(function MV(n){return n&&nr(n.canLoad)}(a))l=a.canLoad(e,i);else{if(!nr(a))throw new Error(\"Invalid CanLoad guard\");l=a(e,i)}return _i(l)})).pipe(Ra(),Mt(o=>{if(!Lr(o))return;const a=wf(`Redirecting to \"${this.urlSerializer.serialize(o)}\"`);throw a.url=o,a}),ue(o=>!0===o)):q(!0)}lineralizeSegments(t,e){let i=[],r=e.root;for(;;){if(i=i.concat(r.segments),0===r.numberOfChildren)return q(i);if(r.numberOfChildren>1||!r.children[me])return Ma(new Error(`Only absolute redirects can have named outlets. redirectTo: '${t.redirectTo}'`));r=r.children[me]}}applyRedirectCommands(t,e,i){return this.applyRedirectCreatreUrlTree(e,this.urlSerializer.parse(e),t,i)}applyRedirectCreatreUrlTree(t,e,i,r){const s=this.createSegmentGroup(t,e.root,i,r);return new Fr(s,this.createQueryParams(e.queryParams,this.urlTree.queryParams),e.fragment)}createQueryParams(t,e){const i={};return At(t,(r,s)=>{if(\"string\"==typeof r&&r.startsWith(\":\")){const a=r.substring(1);i[s]=e[a]}else i[s]=r}),i}createSegmentGroup(t,e,i,r){const s=this.createSegments(t,e.segments,i,r);let o={};return At(e.children,(a,l)=>{o[l]=this.createSegmentGroup(t,a,i,r)}),new ye(s,o)}createSegments(t,e,i,r){return e.map(s=>s.path.startsWith(\":\")?this.findPosParam(t,s,r):this.findOrReturn(s,i))}findPosParam(t,e,i){const r=i[e.path.substring(1)];if(!r)throw new Error(`Cannot redirect to '${t}'. Cannot find '${e.path}'.`);return r}findOrReturn(t,e){let i=0;for(const r of e){if(r.path===t.path)return e.splice(i),r;i++}return t}}function Nf(n){const t={};for(const i of Object.keys(n.children)){const s=Nf(n.children[i]);(s.segments.length>0||s.hasChildren())&&(t[i]=s)}return function HV(n){if(1===n.numberOfChildren&&n.children[me]){const t=n.children[me];return new ye(n.segments.concat(t.segments),t.children)}return n}(new ye(n.segments,t))}class Aw{constructor(t){this.path=t,this.route=this.path[this.path.length-1]}}class ed{constructor(t,e){this.component=t,this.route=e}}function zV(n,t,e){const i=n._root;return Fa(i,t?t._root:null,e,[i.value])}function td(n,t,e){const i=function $V(n){if(!n)return null;for(let t=n.parent;t;t=t.parent){const e=t.routeConfig;if(e&&e._loadedConfig)return e._loadedConfig}return null}(t);return(i?i.module.injector:e).get(n)}function Fa(n,t,e,i,r={canDeactivateChecks:[],canActivateChecks:[]}){const s=Xs(t);return n.children.forEach(o=>{(function GV(n,t,e,i,r={canDeactivateChecks:[],canActivateChecks:[]}){const s=n.value,o=t?t.value:null,a=e?e.getContext(n.value.outlet):null;if(o&&s.routeConfig===o.routeConfig){const l=function WV(n,t,e){if(\"function\"==typeof e)return e(n,t);switch(e){case\"pathParamsChange\":return!Nr(n.url,t.url);case\"pathParamsOrQueryParamsChange\":return!Nr(n.url,t.url)||!gi(n.queryParams,t.queryParams);case\"always\":return!0;case\"paramsOrQueryParamsChange\":return!Tf(n,t)||!gi(n.queryParams,t.queryParams);default:return!Tf(n,t)}}(o,s,s.routeConfig.runGuardsAndResolvers);l?r.canActivateChecks.push(new Aw(i)):(s.data=o.data,s._resolvedData=o._resolvedData),Fa(n,t,s.component?a?a.children:null:e,i,r),l&&a&&a.outlet&&a.outlet.isActivated&&r.canDeactivateChecks.push(new ed(a.outlet.component,o))}else o&&Na(t,a,r),r.canActivateChecks.push(new Aw(i)),Fa(n,null,s.component?a?a.children:null:e,i,r)})(o,s[o.value.outlet],e,i.concat([o.value]),r),delete s[o.value.outlet]}),At(s,(o,a)=>Na(o,e.getContext(a),r)),r}function Na(n,t,e){const i=Xs(n),r=n.value;At(i,(s,o)=>{Na(s,r.component?t?t.children.getContext(o):null:t,e)}),e.canDeactivateChecks.push(new ed(r.component&&t&&t.outlet&&t.outlet.isActivated?t.outlet.component:null,r))}class t2{}function Iw(n){return new Ve(t=>t.error(n))}class r2{constructor(t,e,i,r,s,o){this.rootComponentType=t,this.config=e,this.urlTree=i,this.url=r,this.paramsInheritanceStrategy=s,this.relativeLinkResolution=o}recognize(){const t=Zc(this.urlTree.root,[],[],this.config.filter(o=>void 0===o.redirectTo),this.relativeLinkResolution).segmentGroup,e=this.processSegmentGroup(this.config,t,me);if(null===e)return null;const i=new qc([],Object.freeze({}),Object.freeze(Object.assign({},this.urlTree.queryParams)),this.urlTree.fragment,{},me,this.rootComponentType,null,this.urlTree.root,-1,{}),r=new Bi(i,e),s=new mw(this.url,r);return this.inheritParamsAndData(s._root),s}inheritParamsAndData(t){const e=t.value,i=fw(e,this.paramsInheritanceStrategy);e.params=Object.freeze(i.params),e.data=Object.freeze(i.data),t.children.forEach(r=>this.inheritParamsAndData(r))}processSegmentGroup(t,e,i){return 0===e.segments.length&&e.hasChildren()?this.processChildren(t,e):this.processSegment(t,e,e.segments,i)}processChildren(t,e){const i=[];for(const s of Object.keys(e.children)){const o=e.children[s],a=Mw(t,s),l=this.processSegmentGroup(a,o,s);if(null===l)return null;i.push(...l)}const r=Rw(i);return function s2(n){n.sort((t,e)=>t.value.outlet===me?-1:e.value.outlet===me?1:t.value.outlet.localeCompare(e.value.outlet))}(r),r}processSegment(t,e,i,r){for(const s of t){const o=this.processSegmentAgainstRoute(s,e,i,r);if(null!==o)return o}return Sw(e,i,r)?[]:null}processSegmentAgainstRoute(t,e,i,r){if(t.redirectTo||!Ew(t,e,i,r))return null;let s,o=[],a=[];if(\"**\"===t.path){const p=i.length>0?ew(i).parameters:{};s=new qc(i,p,Object.freeze(Object.assign({},this.urlTree.queryParams)),this.urlTree.fragment,Fw(t),Tn(t),t.component,t,Ow(e),Pw(e)+i.length,Nw(t))}else{const p=Kc(e,t,i);if(!p.matched)return null;o=p.consumedSegments,a=p.remainingSegments,s=new qc(o,p.parameters,Object.freeze(Object.assign({},this.urlTree.queryParams)),this.urlTree.fragment,Fw(t),Tn(t),t.component,t,Ow(e),Pw(e)+o.length,Nw(t))}const l=function o2(n){return n.children?n.children:n.loadChildren?n._loadedConfig.routes:[]}(t),{segmentGroup:c,slicedSegments:d}=Zc(e,o,a,l.filter(p=>void 0===p.redirectTo),this.relativeLinkResolution);if(0===d.length&&c.hasChildren()){const p=this.processChildren(l,c);return null===p?null:[new Bi(s,p)]}if(0===l.length&&0===d.length)return[new Bi(s,[])];const u=Tn(t)===r,h=this.processSegment(l,c,d,u?me:r);return null===h?null:[new Bi(s,h)]}}function a2(n){const t=n.value.routeConfig;return t&&\"\"===t.path&&void 0===t.redirectTo}function Rw(n){const t=[],e=new Set;for(const i of n){if(!a2(i)){t.push(i);continue}const r=t.find(s=>i.value.routeConfig===s.value.routeConfig);void 0!==r?(r.children.push(...i.children),e.add(r)):t.push(i)}for(const i of e){const r=Rw(i.children);t.push(new Bi(i.value,r))}return t.filter(i=>!e.has(i))}function Ow(n){let t=n;for(;t._sourceSegment;)t=t._sourceSegment;return t}function Pw(n){let t=n,e=t._segmentIndexShift?t._segmentIndexShift:0;for(;t._sourceSegment;)t=t._sourceSegment,e+=t._segmentIndexShift?t._segmentIndexShift:0;return e-1}function Fw(n){return n.data||{}}function Nw(n){return n.resolve||{}}function Lw(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n)]}function Lf(n){return kn(t=>{const e=n(t);return e?mt(e).pipe(ue(()=>t)):q(t)})}class m2 extends class f2{shouldDetach(t){return!1}store(t,e){}shouldAttach(t){return!1}retrieve(t){return null}shouldReuseRoute(t,e){return t.routeConfig===e.routeConfig}}{}const Bf=new b(\"ROUTES\");class Bw{constructor(t,e,i,r){this.injector=t,this.compiler=e,this.onLoadStartListener=i,this.onLoadEndListener=r}load(t,e){if(e._loader$)return e._loader$;this.onLoadStartListener&&this.onLoadStartListener(e);const r=this.loadModuleFactory(e.loadChildren).pipe(ue(s=>{this.onLoadEndListener&&this.onLoadEndListener(e);const o=s.create(t);return new Of(JD(o.injector.get(Bf,void 0,ee.Self|ee.Optional)).map(Ff),o)}),Ni(s=>{throw e._loader$=void 0,s}));return e._loader$=new kB(r,()=>new O).pipe(zD()),e._loader$}loadModuleFactory(t){return _i(t()).pipe(lt(e=>e instanceof KC?q(e):mt(this.compiler.compileModuleAsync(e))))}}class _2{shouldProcessUrl(t){return!0}extract(t){return t}merge(t,e){return t}}function v2(n){throw n}function y2(n,t,e){return t.parse(\"/\")}function Vw(n,t){return q(null)}const b2={paths:\"exact\",fragment:\"ignored\",matrixParams:\"ignored\",queryParams:\"exact\"},C2={paths:\"subset\",fragment:\"ignored\",matrixParams:\"ignored\",queryParams:\"subset\"};let cn=(()=>{class n{constructor(e,i,r,s,o,a,l){this.rootComponentType=e,this.urlSerializer=i,this.rootContexts=r,this.location=s,this.config=l,this.lastSuccessfulNavigation=null,this.currentNavigation=null,this.disposed=!1,this.navigationId=0,this.currentPageId=0,this.isNgZoneEnabled=!1,this.events=new O,this.errorHandler=v2,this.malformedUriErrorHandler=y2,this.navigated=!1,this.lastSuccessfulId=-1,this.hooks={beforePreactivation:Vw,afterPreactivation:Vw},this.urlHandlingStrategy=new _2,this.routeReuseStrategy=new m2,this.onSameUrlNavigation=\"ignore\",this.paramsInheritanceStrategy=\"emptyOnly\",this.urlUpdateStrategy=\"deferred\",this.relativeLinkResolution=\"corrected\",this.canceledNavigationResolution=\"replace\",this.ngModule=o.get(Ri),this.console=o.get(O0);const u=o.get(ne);this.isNgZoneEnabled=u instanceof ne&&ne.isInAngularZone(),this.resetConfig(l),this.currentUrlTree=function WB(){return new Fr(new ye([],{}),{},null)}(),this.rawUrlTree=this.currentUrlTree,this.browserUrlTree=this.currentUrlTree,this.configLoader=new Bw(o,a,h=>this.triggerEvent(new YD(h)),h=>this.triggerEvent(new QD(h))),this.routerState=pw(this.currentUrlTree,this.rootComponentType),this.transitions=new Zt({id:0,targetPageId:0,currentUrlTree:this.currentUrlTree,currentRawUrl:this.currentUrlTree,extractedUrl:this.urlHandlingStrategy.extract(this.currentUrlTree),urlAfterRedirects:this.urlHandlingStrategy.extract(this.currentUrlTree),rawUrl:this.currentUrlTree,extras:{},resolve:null,reject:null,promise:Promise.resolve(!0),source:\"imperative\",restoredState:null,currentSnapshot:this.routerState.snapshot,targetSnapshot:null,currentRouterState:this.routerState,targetRouterState:null,guards:{canActivateChecks:[],canDeactivateChecks:[]},guardsResult:null}),this.navigations=this.setupNavigations(this.transitions),this.processNavigations()}get browserPageId(){var e;return null===(e=this.location.getState())||void 0===e?void 0:e.\\u0275routerPageId}setupNavigations(e){const i=this.events;return e.pipe(Ct(r=>0!==r.id),ue(r=>Object.assign(Object.assign({},r),{extractedUrl:this.urlHandlingStrategy.extract(r.rawUrl)})),kn(r=>{let s=!1,o=!1;return q(r).pipe(Mt(a=>{this.currentNavigation={id:a.id,initialUrl:a.currentRawUrl,extractedUrl:a.extractedUrl,trigger:a.source,extras:a.extras,previousNavigation:this.lastSuccessfulNavigation?Object.assign(Object.assign({},this.lastSuccessfulNavigation),{previousNavigation:null}):null}}),kn(a=>{const l=this.browserUrlTree.toString(),c=!this.navigated||a.extractedUrl.toString()!==l||l!==this.currentUrlTree.toString();if((\"reload\"===this.onSameUrlNavigation||c)&&this.urlHandlingStrategy.shouldProcessUrl(a.rawUrl))return Hw(a.source)&&(this.browserUrlTree=a.extractedUrl),q(a).pipe(kn(u=>{const h=this.transitions.getValue();return i.next(new Df(u.id,this.serializeUrl(u.extractedUrl),u.source,u.restoredState)),h!==this.transitions.getValue()?ri:Promise.resolve(u)}),function jV(n,t,e,i){return kn(r=>function BV(n,t,e,i,r){return new VV(n,t,e,i,r).apply()}(n,t,e,r.extractedUrl,i).pipe(ue(s=>Object.assign(Object.assign({},r),{urlAfterRedirects:s}))))}(this.ngModule.injector,this.configLoader,this.urlSerializer,this.config),Mt(u=>{this.currentNavigation=Object.assign(Object.assign({},this.currentNavigation),{finalUrl:u.urlAfterRedirects})}),function l2(n,t,e,i,r){return lt(s=>function n2(n,t,e,i,r=\"emptyOnly\",s=\"legacy\"){try{const o=new r2(n,t,e,i,r,s).recognize();return null===o?Iw(new t2):q(o)}catch(o){return Iw(o)}}(n,t,s.urlAfterRedirects,e(s.urlAfterRedirects),i,r).pipe(ue(o=>Object.assign(Object.assign({},s),{targetSnapshot:o}))))}(this.rootComponentType,this.config,u=>this.serializeUrl(u),this.paramsInheritanceStrategy,this.relativeLinkResolution),Mt(u=>{if(\"eager\"===this.urlUpdateStrategy){if(!u.extras.skipLocationChange){const p=this.urlHandlingStrategy.merge(u.urlAfterRedirects,u.rawUrl);this.setBrowserUrl(p,u)}this.browserUrlTree=u.urlAfterRedirects}const h=new OB(u.id,this.serializeUrl(u.extractedUrl),this.serializeUrl(u.urlAfterRedirects),u.targetSnapshot);i.next(h)}));if(c&&this.rawUrlTree&&this.urlHandlingStrategy.shouldProcessUrl(this.rawUrlTree)){const{id:h,extractedUrl:p,source:m,restoredState:g,extras:_}=a,D=new Df(h,this.serializeUrl(p),m,g);i.next(D);const v=pw(p,this.rootComponentType).snapshot;return q(Object.assign(Object.assign({},a),{targetSnapshot:v,urlAfterRedirects:p,extras:Object.assign(Object.assign({},_),{skipLocationChange:!1,replaceUrl:!1})}))}return this.rawUrlTree=a.rawUrl,a.resolve(null),ri}),Lf(a=>{const{targetSnapshot:l,id:c,extractedUrl:d,rawUrl:u,extras:{skipLocationChange:h,replaceUrl:p}}=a;return this.hooks.beforePreactivation(l,{navigationId:c,appliedUrlTree:d,rawUrlTree:u,skipLocationChange:!!h,replaceUrl:!!p})}),Mt(a=>{const l=new PB(a.id,this.serializeUrl(a.extractedUrl),this.serializeUrl(a.urlAfterRedirects),a.targetSnapshot);this.triggerEvent(l)}),ue(a=>Object.assign(Object.assign({},a),{guards:zV(a.targetSnapshot,a.currentSnapshot,this.rootContexts)})),function qV(n,t){return lt(e=>{const{targetSnapshot:i,currentSnapshot:r,guards:{canActivateChecks:s,canDeactivateChecks:o}}=e;return 0===o.length&&0===s.length?q(Object.assign(Object.assign({},e),{guardsResult:!0})):function YV(n,t,e,i){return mt(n).pipe(lt(r=>function e2(n,t,e,i,r){const s=t&&t.routeConfig?t.routeConfig.canDeactivate:null;return s&&0!==s.length?q(s.map(a=>{const l=td(a,t,r);let c;if(function SV(n){return n&&nr(n.canDeactivate)}(l))c=_i(l.canDeactivate(n,t,e,i));else{if(!nr(l))throw new Error(\"Invalid CanDeactivate guard\");c=_i(l(n,t,e,i))}return c.pipe(Ks())})).pipe(Ra()):q(!0)}(r.component,r.route,e,t,i)),Ks(r=>!0!==r,!0))}(o,i,r,n).pipe(lt(a=>a&&function wV(n){return\"boolean\"==typeof n}(a)?function QV(n,t,e,i){return mt(t).pipe(Qs(r=>jc(function ZV(n,t){return null!==n&&t&&t(new BB(n)),q(!0)}(r.route.parent,i),function KV(n,t){return null!==n&&t&&t(new HB(n)),q(!0)}(r.route,i),function JV(n,t,e){const i=t[t.length-1],s=t.slice(0,t.length-1).reverse().map(o=>function UV(n){const t=n.routeConfig?n.routeConfig.canActivateChild:null;return t&&0!==t.length?{node:n,guards:t}:null}(o)).filter(o=>null!==o).map(o=>xa(()=>q(o.guards.map(l=>{const c=td(l,o.node,e);let d;if(function EV(n){return n&&nr(n.canActivateChild)}(c))d=_i(c.canActivateChild(i,n));else{if(!nr(c))throw new Error(\"Invalid CanActivateChild guard\");d=_i(c(i,n))}return d.pipe(Ks())})).pipe(Ra())));return q(s).pipe(Ra())}(n,r.path,e),function XV(n,t,e){const i=t.routeConfig?t.routeConfig.canActivate:null;if(!i||0===i.length)return q(!0);const r=i.map(s=>xa(()=>{const o=td(s,t,e);let a;if(function xV(n){return n&&nr(n.canActivate)}(o))a=_i(o.canActivate(t,n));else{if(!nr(o))throw new Error(\"Invalid CanActivate guard\");a=_i(o(t,n))}return a.pipe(Ks())}));return q(r).pipe(Ra())}(n,r.route,e))),Ks(r=>!0!==r,!0))}(i,s,n,t):q(a)),ue(a=>Object.assign(Object.assign({},e),{guardsResult:a})))})}(this.ngModule.injector,a=>this.triggerEvent(a)),Mt(a=>{if(Lr(a.guardsResult)){const c=wf(`Redirecting to \"${this.serializeUrl(a.guardsResult)}\"`);throw c.url=a.guardsResult,c}const l=new FB(a.id,this.serializeUrl(a.extractedUrl),this.serializeUrl(a.urlAfterRedirects),a.targetSnapshot,!!a.guardsResult);this.triggerEvent(l)}),Ct(a=>!!a.guardsResult||(this.restoreHistory(a),this.cancelNavigationTransition(a,\"\"),!1)),Lf(a=>{if(a.guards.canActivateChecks.length)return q(a).pipe(Mt(l=>{const c=new NB(l.id,this.serializeUrl(l.extractedUrl),this.serializeUrl(l.urlAfterRedirects),l.targetSnapshot);this.triggerEvent(c)}),kn(l=>{let c=!1;return q(l).pipe(function c2(n,t){return lt(e=>{const{targetSnapshot:i,guards:{canActivateChecks:r}}=e;if(!r.length)return q(e);let s=0;return mt(r).pipe(Qs(o=>function d2(n,t,e,i){return function u2(n,t,e,i){const r=Lw(n);if(0===r.length)return q({});const s={};return mt(r).pipe(lt(o=>function h2(n,t,e,i){const r=td(n,t,i);return _i(r.resolve?r.resolve(t,e):r(t,e))}(n[o],t,e,i).pipe(Mt(a=>{s[o]=a}))),Cf(1),lt(()=>Lw(s).length===r.length?q(s):ri))}(n._resolve,n,t,i).pipe(ue(s=>(n._resolvedData=s,n.data=Object.assign(Object.assign({},n.data),fw(n,e).resolve),null)))}(o.route,i,n,t)),Mt(()=>s++),Cf(1),lt(o=>s===r.length?q(e):ri))})}(this.paramsInheritanceStrategy,this.ngModule.injector),Mt({next:()=>c=!0,complete:()=>{c||(this.restoreHistory(l),this.cancelNavigationTransition(l,\"At least one route resolver didn't emit any value.\"))}}))}),Mt(l=>{const c=new LB(l.id,this.serializeUrl(l.extractedUrl),this.serializeUrl(l.urlAfterRedirects),l.targetSnapshot);this.triggerEvent(c)}))}),Lf(a=>{const{targetSnapshot:l,id:c,extractedUrl:d,rawUrl:u,extras:{skipLocationChange:h,replaceUrl:p}}=a;return this.hooks.afterPreactivation(l,{navigationId:c,appliedUrlTree:d,rawUrlTree:u,skipLocationChange:!!h,replaceUrl:!!p})}),ue(a=>{const l=function dV(n,t,e){const i=Ta(n,t._root,e?e._root:void 0);return new hw(i,t)}(this.routeReuseStrategy,a.targetSnapshot,a.currentRouterState);return Object.assign(Object.assign({},a),{targetRouterState:l})}),Mt(a=>{this.currentUrlTree=a.urlAfterRedirects,this.rawUrlTree=this.urlHandlingStrategy.merge(a.urlAfterRedirects,a.rawUrl),this.routerState=a.targetRouterState,\"deferred\"===this.urlUpdateStrategy&&(a.extras.skipLocationChange||this.setBrowserUrl(this.rawUrlTree,a),this.browserUrlTree=a.urlAfterRedirects)}),((n,t,e)=>ue(i=>(new CV(t,i.targetRouterState,i.currentRouterState,e).activate(n),i)))(this.rootContexts,this.routeReuseStrategy,a=>this.triggerEvent(a)),Mt({next(){s=!0},complete(){s=!0}}),function WD(n){return qe((t,e)=>{try{t.subscribe(e)}finally{e.add(n)}})}(()=>{var a;s||o||this.cancelNavigationTransition(r,`Navigation ID ${r.id} is not equal to the current navigation id ${this.navigationId}`),(null===(a=this.currentNavigation)||void 0===a?void 0:a.id)===r.id&&(this.currentNavigation=null)}),Ni(a=>{if(o=!0,function UB(n){return n&&n[ZD]}(a)){const l=Lr(a.url);l||(this.navigated=!0,this.restoreHistory(r,!0));const c=new qD(r.id,this.serializeUrl(r.extractedUrl),a.message);i.next(c),l?setTimeout(()=>{const d=this.urlHandlingStrategy.merge(a.url,this.rawUrlTree),u={skipLocationChange:r.extras.skipLocationChange,replaceUrl:\"eager\"===this.urlUpdateStrategy||Hw(r.source)};this.scheduleNavigation(d,\"imperative\",null,u,{resolve:r.resolve,reject:r.reject,promise:r.promise})},0):r.resolve(!1)}else{this.restoreHistory(r,!0);const l=new RB(r.id,this.serializeUrl(r.extractedUrl),a);i.next(l);try{r.resolve(this.errorHandler(a))}catch(c){r.reject(c)}}return ri}))}))}resetRootComponentType(e){this.rootComponentType=e,this.routerState.root.component=this.rootComponentType}setTransition(e){this.transitions.next(Object.assign(Object.assign({},this.transitions.value),e))}initialNavigation(){this.setUpLocationChangeListener(),0===this.navigationId&&this.navigateByUrl(this.location.path(!0),{replaceUrl:!0})}setUpLocationChangeListener(){this.locationSubscription||(this.locationSubscription=this.location.subscribe(e=>{const i=\"popstate\"===e.type?\"popstate\":\"hashchange\";\"popstate\"===i&&setTimeout(()=>{var r;const s={replaceUrl:!0},o=(null===(r=e.state)||void 0===r?void 0:r.navigationId)?e.state:null;if(o){const l=Object.assign({},o);delete l.navigationId,delete l.\\u0275routerPageId,0!==Object.keys(l).length&&(s.state=l)}const a=this.parseUrl(e.url);this.scheduleNavigation(a,i,o,s)},0)}))}get url(){return this.serializeUrl(this.currentUrlTree)}getCurrentNavigation(){return this.currentNavigation}triggerEvent(e){this.events.next(e)}resetConfig(e){ww(e),this.config=e.map(Ff),this.navigated=!1,this.lastSuccessfulId=-1}ngOnDestroy(){this.dispose()}dispose(){this.transitions.complete(),this.locationSubscription&&(this.locationSubscription.unsubscribe(),this.locationSubscription=void 0),this.disposed=!0}createUrlTree(e,i={}){const{relativeTo:r,queryParams:s,fragment:o,queryParamsHandling:a,preserveFragment:l}=i,c=r||this.routerState.root,d=l?this.currentUrlTree.fragment:o;let u=null;switch(a){case\"merge\":u=Object.assign(Object.assign({},this.currentUrlTree.queryParams),s);break;case\"preserve\":u=this.currentUrlTree.queryParams;break;default:u=s||null}return null!==u&&(u=this.removeEmptyProps(u)),function pV(n,t,e,i,r){if(0===e.length)return Af(t.root,t.root,t.root,i,r);const s=function fV(n){if(\"string\"==typeof n[0]&&1===n.length&&\"/\"===n[0])return new vw(!0,0,n);let t=0,e=!1;const i=n.reduce((r,s,o)=>{if(\"object\"==typeof s&&null!=s){if(s.outlets){const a={};return At(s.outlets,(l,c)=>{a[c]=\"string\"==typeof l?l.split(\"/\"):l}),[...r,{outlets:a}]}if(s.segmentPath)return[...r,s.segmentPath]}return\"string\"!=typeof s?[...r,s]:0===o?(s.split(\"/\").forEach((a,l)=>{0==l&&\".\"===a||(0==l&&\"\"===a?e=!0:\"..\"===a?t++:\"\"!=a&&r.push(a))}),r):[...r,s]},[]);return new vw(e,t,i)}(e);if(s.toRoot())return Af(t.root,t.root,new ye([],{}),i,r);const o=function mV(n,t,e){if(n.isAbsolute)return new If(t.root,!0,0);if(-1===e.snapshot._lastPathIndex){const s=e.snapshot._urlSegment;return new If(s,s===t.root,0)}const i=Yc(n.commands[0])?0:1;return function gV(n,t,e){let i=n,r=t,s=e;for(;s>r;){if(s-=r,i=i.parent,!i)throw new Error(\"Invalid number of '../'\");r=i.segments.length}return new If(i,!1,r-s)}(e.snapshot._urlSegment,e.snapshot._lastPathIndex+i,n.numberOfDoubleDots)}(s,t,n),a=o.processChildren?Qc(o.segmentGroup,o.index,s.commands):yw(o.segmentGroup,o.index,s.commands);return Af(t.root,o.segmentGroup,a,i,r)}(c,this.currentUrlTree,e,u,null!=d?d:null)}navigateByUrl(e,i={skipLocationChange:!1}){const r=Lr(e)?e:this.parseUrl(e),s=this.urlHandlingStrategy.merge(r,this.rawUrlTree);return this.scheduleNavigation(s,\"imperative\",null,i)}navigate(e,i={skipLocationChange:!1}){return function D2(n){for(let t=0;t<n.length;t++){const e=n[t];if(null==e)throw new Error(`The requested path contains ${e} segment at index ${t}`)}}(e),this.navigateByUrl(this.createUrlTree(e,i),i)}serializeUrl(e){return this.urlSerializer.serialize(e)}parseUrl(e){let i;try{i=this.urlSerializer.parse(e)}catch(r){i=this.malformedUriErrorHandler(r,this.urlSerializer,e)}return i}isActive(e,i){let r;if(r=!0===i?Object.assign({},b2):!1===i?Object.assign({},C2):i,Lr(e))return nw(this.currentUrlTree,e,r);const s=this.parseUrl(e);return nw(this.currentUrlTree,s,r)}removeEmptyProps(e){return Object.keys(e).reduce((i,r)=>{const s=e[r];return null!=s&&(i[r]=s),i},{})}processNavigations(){this.navigations.subscribe(e=>{this.navigated=!0,this.lastSuccessfulId=e.id,this.currentPageId=e.targetPageId,this.events.next(new Ea(e.id,this.serializeUrl(e.extractedUrl),this.serializeUrl(this.currentUrlTree))),this.lastSuccessfulNavigation=this.currentNavigation,e.resolve(!0)},e=>{this.console.warn(`Unhandled Navigation Error: ${e}`)})}scheduleNavigation(e,i,r,s,o){var a,l;if(this.disposed)return Promise.resolve(!1);let c,d,u;o?(c=o.resolve,d=o.reject,u=o.promise):u=new Promise((m,g)=>{c=m,d=g});const h=++this.navigationId;let p;return\"computed\"===this.canceledNavigationResolution?(0===this.currentPageId&&(r=this.location.getState()),p=r&&r.\\u0275routerPageId?r.\\u0275routerPageId:s.replaceUrl||s.skipLocationChange?null!==(a=this.browserPageId)&&void 0!==a?a:0:(null!==(l=this.browserPageId)&&void 0!==l?l:0)+1):p=0,this.setTransition({id:h,targetPageId:p,source:i,restoredState:r,currentUrlTree:this.currentUrlTree,currentRawUrl:this.rawUrlTree,rawUrl:e,extras:s,resolve:c,reject:d,promise:u,currentSnapshot:this.routerState.snapshot,currentRouterState:this.routerState}),u.catch(m=>Promise.reject(m))}setBrowserUrl(e,i){const r=this.urlSerializer.serialize(e),s=Object.assign(Object.assign({},i.extras.state),this.generateNgRouterState(i.id,i.targetPageId));this.location.isCurrentPathEqualTo(r)||i.extras.replaceUrl?this.location.replaceState(r,\"\",s):this.location.go(r,\"\",s)}restoreHistory(e,i=!1){var r,s;if(\"computed\"===this.canceledNavigationResolution){const o=this.currentPageId-e.targetPageId;\"popstate\"!==e.source&&\"eager\"!==this.urlUpdateStrategy&&this.currentUrlTree!==(null===(r=this.currentNavigation)||void 0===r?void 0:r.finalUrl)||0===o?this.currentUrlTree===(null===(s=this.currentNavigation)||void 0===s?void 0:s.finalUrl)&&0===o&&(this.resetState(e),this.browserUrlTree=e.currentUrlTree,this.resetUrlToCurrentUrlTree()):this.location.historyGo(o)}else\"replace\"===this.canceledNavigationResolution&&(i&&this.resetState(e),this.resetUrlToCurrentUrlTree())}resetState(e){this.routerState=e.currentRouterState,this.currentUrlTree=e.currentUrlTree,this.rawUrlTree=this.urlHandlingStrategy.merge(this.currentUrlTree,e.rawUrl)}resetUrlToCurrentUrlTree(){this.location.replaceState(this.urlSerializer.serialize(this.rawUrlTree),\"\",this.generateNgRouterState(this.lastSuccessfulId,this.currentPageId))}cancelNavigationTransition(e,i){const r=new qD(e.id,this.serializeUrl(e.extractedUrl),i);this.triggerEvent(r),e.resolve(!1)}generateNgRouterState(e,i){return\"computed\"===this.canceledNavigationResolution?{navigationId:e,\\u0275routerPageId:i}:{navigationId:e}}}return n.\\u0275fac=function(e){Sr()},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();function Hw(n){return\"imperative\"!==n}class jw{}class zw{preload(t,e){return q(null)}}let Uw=(()=>{class n{constructor(e,i,r,s){this.router=e,this.injector=r,this.preloadingStrategy=s,this.loader=new Bw(r,i,l=>e.triggerEvent(new YD(l)),l=>e.triggerEvent(new QD(l)))}setUpPreloading(){this.subscription=this.router.events.pipe(Ct(e=>e instanceof Ea),Qs(()=>this.preload())).subscribe(()=>{})}preload(){const e=this.injector.get(Ri);return this.processRoutes(e,this.router.config)}ngOnDestroy(){this.subscription&&this.subscription.unsubscribe()}processRoutes(e,i){const r=[];for(const s of i)if(s.loadChildren&&!s.canLoad&&s._loadedConfig){const o=s._loadedConfig;r.push(this.processRoutes(o.module,o.routes))}else s.loadChildren&&!s.canLoad?r.push(this.preloadConfig(e,s)):s.children&&r.push(this.processRoutes(e,s.children));return mt(r).pipe(Eo(),ue(s=>{}))}preloadConfig(e,i){return this.preloadingStrategy.preload(i,()=>(i._loadedConfig?q(i._loadedConfig):this.loader.load(e.injector,i)).pipe(lt(s=>(i._loadedConfig=s,this.processRoutes(s.module,s.routes)))))}}return n.\\u0275fac=function(e){return new(e||n)(y(cn),y(P0),y(dt),y(jw))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),jf=(()=>{class n{constructor(e,i,r={}){this.router=e,this.viewportScroller=i,this.options=r,this.lastId=0,this.lastSource=\"imperative\",this.restoredId=0,this.store={},r.scrollPositionRestoration=r.scrollPositionRestoration||\"disabled\",r.anchorScrolling=r.anchorScrolling||\"disabled\"}init(){\"disabled\"!==this.options.scrollPositionRestoration&&this.viewportScroller.setHistoryScrollRestoration(\"manual\"),this.routerEventsSubscription=this.createScrollEvents(),this.scrollEventsSubscription=this.consumeScrollEvents()}createScrollEvents(){return this.router.events.subscribe(e=>{e instanceof Df?(this.store[this.lastId]=this.viewportScroller.getScrollPosition(),this.lastSource=e.navigationTrigger,this.restoredId=e.restoredState?e.restoredState.navigationId:0):e instanceof Ea&&(this.lastId=e.id,this.scheduleScrollEvent(e,this.router.parseUrl(e.urlAfterRedirects).fragment))})}consumeScrollEvents(){return this.router.events.subscribe(e=>{e instanceof KD&&(e.position?\"top\"===this.options.scrollPositionRestoration?this.viewportScroller.scrollToPosition([0,0]):\"enabled\"===this.options.scrollPositionRestoration&&this.viewportScroller.scrollToPosition(e.position):e.anchor&&\"enabled\"===this.options.anchorScrolling?this.viewportScroller.scrollToAnchor(e.anchor):\"disabled\"!==this.options.scrollPositionRestoration&&this.viewportScroller.scrollToPosition([0,0]))})}scheduleScrollEvent(e,i){this.router.triggerEvent(new KD(e,\"popstate\"===this.lastSource?this.store[this.restoredId]:null,i))}ngOnDestroy(){this.routerEventsSubscription&&this.routerEventsSubscription.unsubscribe(),this.scrollEventsSubscription&&this.scrollEventsSubscription.unsubscribe()}}return n.\\u0275fac=function(e){Sr()},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const Br=new b(\"ROUTER_CONFIGURATION\"),$w=new b(\"ROUTER_FORROOT_GUARD\"),E2=[va,{provide:ow,useClass:aw},{provide:cn,useFactory:function I2(n,t,e,i,r,s,o={},a,l){const c=new cn(null,n,t,e,i,r,JD(s));return a&&(c.urlHandlingStrategy=a),l&&(c.routeReuseStrategy=l),function R2(n,t){n.errorHandler&&(t.errorHandler=n.errorHandler),n.malformedUriErrorHandler&&(t.malformedUriErrorHandler=n.malformedUriErrorHandler),n.onSameUrlNavigation&&(t.onSameUrlNavigation=n.onSameUrlNavigation),n.paramsInheritanceStrategy&&(t.paramsInheritanceStrategy=n.paramsInheritanceStrategy),n.relativeLinkResolution&&(t.relativeLinkResolution=n.relativeLinkResolution),n.urlUpdateStrategy&&(t.urlUpdateStrategy=n.urlUpdateStrategy),n.canceledNavigationResolution&&(t.canceledNavigationResolution=n.canceledNavigationResolution)}(o,c),o.enableTracing&&c.events.subscribe(d=>{var u,h;null===(u=console.group)||void 0===u||u.call(console,`Router Event: ${d.constructor.name}`),console.log(d.toString()),console.log(d),null===(h=console.groupEnd)||void 0===h||h.call(console)}),c},deps:[ow,Oa,va,dt,P0,Bf,Br,[class g2{},new Tt],[class p2{},new Tt]]},Oa,{provide:Js,useFactory:function O2(n){return n.routerState.root},deps:[cn]},Uw,zw,class x2{preload(t,e){return e().pipe(Ni(()=>q(null)))}},{provide:Br,useValue:{enableTracing:!1}}];function S2(){return new V0(\"Router\",cn)}let Gw=(()=>{class n{constructor(e,i){}static forRoot(e,i){return{ngModule:n,providers:[E2,Ww(e),{provide:$w,useFactory:A2,deps:[[cn,new Tt,new Cn]]},{provide:Br,useValue:i||{}},{provide:qs,useFactory:T2,deps:[Pr,[new Gl(Xp),new Tt],Br]},{provide:jf,useFactory:k2,deps:[cn,PL,Br]},{provide:jw,useExisting:i&&i.preloadingStrategy?i.preloadingStrategy:zw},{provide:V0,multi:!0,useFactory:S2},[zf,{provide:Bp,multi:!0,useFactory:P2,deps:[zf]},{provide:qw,useFactory:F2,deps:[zf]},{provide:R0,multi:!0,useExisting:qw}]]}}static forChild(e){return{ngModule:n,providers:[Ww(e)]}}}return n.\\u0275fac=function(e){return new(e||n)(y($w,8),y(cn,8))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();function k2(n,t,e){return e.scrollOffset&&t.setOffset(e.scrollOffset),new jf(n,t,e)}function T2(n,t,e={}){return e.useHash?new vN(n,t):new sD(n,t)}function A2(n){return\"guarded\"}function Ww(n){return[{provide:nA,multi:!0,useValue:n},{provide:Bf,multi:!0,useValue:n}]}let zf=(()=>{class n{constructor(e){this.injector=e,this.initNavigation=!1,this.destroyed=!1,this.resultOfPreactivationDone=new O}appInitializer(){return this.injector.get(mN,Promise.resolve(null)).then(()=>{if(this.destroyed)return Promise.resolve(!0);let i=null;const r=new Promise(a=>i=a),s=this.injector.get(cn),o=this.injector.get(Br);return\"disabled\"===o.initialNavigation?(s.setUpLocationChangeListener(),i(!0)):\"enabled\"===o.initialNavigation||\"enabledBlocking\"===o.initialNavigation?(s.hooks.afterPreactivation=()=>this.initNavigation?q(null):(this.initNavigation=!0,i(!0),this.resultOfPreactivationDone),s.initialNavigation()):i(!0),r})}bootstrapListener(e){const i=this.injector.get(Br),r=this.injector.get(Uw),s=this.injector.get(jf),o=this.injector.get(cn),a=this.injector.get(Cc);e===a.components[0]&&((\"enabledNonBlocking\"===i.initialNavigation||void 0===i.initialNavigation)&&o.initialNavigation(),r.setUpPreloading(),s.init(),o.resetRootComponentType(a.componentTypes[0]),this.resultOfPreactivationDone.next(null),this.resultOfPreactivationDone.complete())}ngOnDestroy(){this.destroyed=!0}}return n.\\u0275fac=function(e){return new(e||n)(y(dt))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();function P2(n){return n.appInitializer.bind(n)}function F2(n){return n.bootstrapListener.bind(n)}const qw=new b(\"Router Initializer\"),L2=[];let B2=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Gw.forRoot(L2)],Gw]}),n})();class Yw{}const Vi=\"*\";function Ke(n,t){return{type:7,name:n,definitions:t,options:{}}}function be(n,t=null){return{type:4,styles:t,timings:n}}function nd(n,t=null){return{type:3,steps:n,options:t}}function Qw(n,t=null){return{type:2,steps:n,options:t}}function R(n){return{type:6,styles:n,offset:null}}function ae(n,t,e){return{type:0,name:n,styles:t,options:e}}function ge(n,t,e=null){return{type:1,expr:n,animation:t,options:e}}function to(n=null){return{type:9,options:n}}function no(n,t,e=null){return{type:11,selector:n,animation:t,options:e}}function Kw(n){Promise.resolve(null).then(n)}class La{constructor(t=0,e=0){this._onDoneFns=[],this._onStartFns=[],this._onDestroyFns=[],this._started=!1,this._destroyed=!1,this._finished=!1,this._position=0,this.parentPlayer=null,this.totalTime=t+e}_onFinish(){this._finished||(this._finished=!0,this._onDoneFns.forEach(t=>t()),this._onDoneFns=[])}onStart(t){this._onStartFns.push(t)}onDone(t){this._onDoneFns.push(t)}onDestroy(t){this._onDestroyFns.push(t)}hasStarted(){return this._started}init(){}play(){this.hasStarted()||(this._onStart(),this.triggerMicrotask()),this._started=!0}triggerMicrotask(){Kw(()=>this._onFinish())}_onStart(){this._onStartFns.forEach(t=>t()),this._onStartFns=[]}pause(){}restart(){}finish(){this._onFinish()}destroy(){this._destroyed||(this._destroyed=!0,this.hasStarted()||this._onStart(),this.finish(),this._onDestroyFns.forEach(t=>t()),this._onDestroyFns=[])}reset(){this._started=!1}setPosition(t){this._position=this.totalTime?t*this.totalTime:1}getPosition(){return this.totalTime?this._position/this.totalTime:1}triggerCallback(t){const e=\"start\"==t?this._onStartFns:this._onDoneFns;e.forEach(i=>i()),e.length=0}}class Zw{constructor(t){this._onDoneFns=[],this._onStartFns=[],this._finished=!1,this._started=!1,this._destroyed=!1,this._onDestroyFns=[],this.parentPlayer=null,this.totalTime=0,this.players=t;let e=0,i=0,r=0;const s=this.players.length;0==s?Kw(()=>this._onFinish()):this.players.forEach(o=>{o.onDone(()=>{++e==s&&this._onFinish()}),o.onDestroy(()=>{++i==s&&this._onDestroy()}),o.onStart(()=>{++r==s&&this._onStart()})}),this.totalTime=this.players.reduce((o,a)=>Math.max(o,a.totalTime),0)}_onFinish(){this._finished||(this._finished=!0,this._onDoneFns.forEach(t=>t()),this._onDoneFns=[])}init(){this.players.forEach(t=>t.init())}onStart(t){this._onStartFns.push(t)}_onStart(){this.hasStarted()||(this._started=!0,this._onStartFns.forEach(t=>t()),this._onStartFns=[])}onDone(t){this._onDoneFns.push(t)}onDestroy(t){this._onDestroyFns.push(t)}hasStarted(){return this._started}play(){this.parentPlayer||this.init(),this._onStart(),this.players.forEach(t=>t.play())}pause(){this.players.forEach(t=>t.pause())}restart(){this.players.forEach(t=>t.restart())}finish(){this._onFinish(),this.players.forEach(t=>t.finish())}destroy(){this._onDestroy()}_onDestroy(){this._destroyed||(this._destroyed=!0,this._onFinish(),this.players.forEach(t=>t.destroy()),this._onDestroyFns.forEach(t=>t()),this._onDestroyFns=[])}reset(){this.players.forEach(t=>t.reset()),this._destroyed=!1,this._finished=!1,this._started=!1}setPosition(t){const e=t*this.totalTime;this.players.forEach(i=>{const r=i.totalTime?Math.min(1,e/i.totalTime):1;i.setPosition(r)})}getPosition(){const t=this.players.reduce((e,i)=>null===e||i.totalTime>e.totalTime?i:e,null);return null!=t?t.getPosition():0}beforeDestroy(){this.players.forEach(t=>{t.beforeDestroy&&t.beforeDestroy()})}triggerCallback(t){const e=\"start\"==t?this._onStartFns:this._onDoneFns;e.forEach(i=>i()),e.length=0}}const Ce=!1;function Xw(n){return new H(3e3,Ce)}function yH(){return\"undefined\"!=typeof window&&void 0!==window.document}function $f(){return\"undefined\"!=typeof process&&\"[object process]\"==={}.toString.call(process)}function ir(n){switch(n.length){case 0:return new La;case 1:return n[0];default:return new Zw(n)}}function Jw(n,t,e,i,r={},s={}){const o=[],a=[];let l=-1,c=null;if(i.forEach(d=>{const u=d.offset,h=u==l,p=h&&c||{};Object.keys(d).forEach(m=>{let g=m,_=d[m];if(\"offset\"!==m)switch(g=t.normalizePropertyName(g,o),_){case\"!\":_=r[m];break;case Vi:_=s[m];break;default:_=t.normalizeStyleValue(m,g,_,o)}p[g]=_}),h||a.push(p),c=p,l=u}),o.length)throw function lH(n){return new H(3502,Ce)}();return a}function Gf(n,t,e,i){switch(t){case\"start\":n.onStart(()=>i(e&&Wf(e,\"start\",n)));break;case\"done\":n.onDone(()=>i(e&&Wf(e,\"done\",n)));break;case\"destroy\":n.onDestroy(()=>i(e&&Wf(e,\"destroy\",n)))}}function Wf(n,t,e){const i=e.totalTime,s=qf(n.element,n.triggerName,n.fromState,n.toState,t||n.phaseName,null==i?n.totalTime:i,!!e.disabled),o=n._data;return null!=o&&(s._data=o),s}function qf(n,t,e,i,r=\"\",s=0,o){return{element:n,triggerName:t,fromState:e,toState:i,phaseName:r,totalTime:s,disabled:!!o}}function dn(n,t,e){let i;return n instanceof Map?(i=n.get(t),i||n.set(t,i=e)):(i=n[t],i||(i=n[t]=e)),i}function eM(n){const t=n.indexOf(\":\");return[n.substring(1,t),n.substr(t+1)]}let Yf=(n,t)=>!1,tM=(n,t,e)=>[],nM=null;function Qf(n){const t=n.parentNode||n.host;return t===nM?null:t}($f()||\"undefined\"!=typeof Element)&&(yH()?(nM=(()=>document.documentElement)(),Yf=(n,t)=>{for(;t;){if(t===n)return!0;t=Qf(t)}return!1}):Yf=(n,t)=>n.contains(t),tM=(n,t,e)=>{if(e)return Array.from(n.querySelectorAll(t));const i=n.querySelector(t);return i?[i]:[]});let Hr=null,iM=!1;function rM(n){Hr||(Hr=function CH(){return\"undefined\"!=typeof document?document.body:null}()||{},iM=!!Hr.style&&\"WebkitAppearance\"in Hr.style);let t=!0;return Hr.style&&!function bH(n){return\"ebkit\"==n.substring(1,6)}(n)&&(t=n in Hr.style,!t&&iM&&(t=\"Webkit\"+n.charAt(0).toUpperCase()+n.substr(1)in Hr.style)),t}const sM=Yf,oM=tM;let aM=(()=>{class n{validateStyleProperty(e){return rM(e)}matchesElement(e,i){return!1}containsElement(e,i){return sM(e,i)}getParentElement(e){return Qf(e)}query(e,i,r){return oM(e,i,r)}computeStyle(e,i,r){return r||\"\"}animate(e,i,r,s,o,a=[],l){return new La(r,s)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),Kf=(()=>{class n{}return n.NOOP=new aM,n})();const Zf=\"ng-enter\",rd=\"ng-leave\",sd=\"ng-trigger\",od=\".ng-trigger\",cM=\"ng-animating\",Xf=\".ng-animating\";function jr(n){if(\"number\"==typeof n)return n;const t=n.match(/^(-?[\\.\\d]+)(m?s)/);return!t||t.length<2?0:Jf(parseFloat(t[1]),t[2])}function Jf(n,t){return\"s\"===t?1e3*n:n}function ad(n,t,e){return n.hasOwnProperty(\"duration\")?n:function MH(n,t,e){let r,s=0,o=\"\";if(\"string\"==typeof n){const a=n.match(/^(-?[\\.\\d]+)(m?s)(?:\\s+(-?[\\.\\d]+)(m?s))?(?:\\s+([-a-z]+(?:\\(.+?\\))?))?$/i);if(null===a)return t.push(Xw()),{duration:0,delay:0,easing:\"\"};r=Jf(parseFloat(a[1]),a[2]);const l=a[3];null!=l&&(s=Jf(parseFloat(l),a[4]));const c=a[5];c&&(o=c)}else r=n;if(!e){let a=!1,l=t.length;r<0&&(t.push(function H2(){return new H(3100,Ce)}()),a=!0),s<0&&(t.push(function j2(){return new H(3101,Ce)}()),a=!0),a&&t.splice(l,0,Xw())}return{duration:r,delay:s,easing:o}}(n,t,e)}function io(n,t={}){return Object.keys(n).forEach(e=>{t[e]=n[e]}),t}function rr(n,t,e={}){if(t)for(let i in n)e[i]=n[i];else io(n,e);return e}function uM(n,t,e){return e?t+\":\"+e+\";\":\"\"}function hM(n){let t=\"\";for(let e=0;e<n.style.length;e++){const i=n.style.item(e);t+=uM(0,i,n.style.getPropertyValue(i))}for(const e in n.style)n.style.hasOwnProperty(e)&&!e.startsWith(\"_\")&&(t+=uM(0,SH(e),n.style[e]));n.setAttribute(\"style\",t)}function vi(n,t,e){n.style&&(Object.keys(t).forEach(i=>{const r=tm(i);e&&!e.hasOwnProperty(i)&&(e[i]=n.style[r]),n.style[r]=t[i]}),$f()&&hM(n))}function zr(n,t){n.style&&(Object.keys(t).forEach(e=>{const i=tm(e);n.style[i]=\"\"}),$f()&&hM(n))}function Ba(n){return Array.isArray(n)?1==n.length?n[0]:Qw(n):n}const em=new RegExp(\"{{\\\\s*(.+?)\\\\s*}}\",\"g\");function pM(n){let t=[];if(\"string\"==typeof n){let e;for(;e=em.exec(n);)t.push(e[1]);em.lastIndex=0}return t}function ld(n,t,e){const i=n.toString(),r=i.replace(em,(s,o)=>{let a=t[o];return t.hasOwnProperty(o)||(e.push(function U2(n){return new H(3003,Ce)}()),a=\"\"),a.toString()});return r==i?n:r}function cd(n){const t=[];let e=n.next();for(;!e.done;)t.push(e.value),e=n.next();return t}const EH=/-+([a-z0-9])/g;function tm(n){return n.replace(EH,(...t)=>t[1].toUpperCase())}function SH(n){return n.replace(/([a-z])([A-Z])/g,\"$1-$2\").toLowerCase()}function un(n,t,e){switch(t.type){case 7:return n.visitTrigger(t,e);case 0:return n.visitState(t,e);case 1:return n.visitTransition(t,e);case 2:return n.visitSequence(t,e);case 3:return n.visitGroup(t,e);case 4:return n.visitAnimate(t,e);case 5:return n.visitKeyframes(t,e);case 6:return n.visitStyle(t,e);case 8:return n.visitReference(t,e);case 9:return n.visitAnimateChild(t,e);case 10:return n.visitAnimateRef(t,e);case 11:return n.visitQuery(t,e);case 12:return n.visitStagger(t,e);default:throw function $2(n){return new H(3004,Ce)}()}}function fM(n,t){return window.getComputedStyle(n)[t]}function OH(n,t){const e=[];return\"string\"==typeof n?n.split(/\\s*,\\s*/).forEach(i=>function PH(n,t,e){if(\":\"==n[0]){const l=function FH(n,t){switch(n){case\":enter\":return\"void => *\";case\":leave\":return\"* => void\";case\":increment\":return(e,i)=>parseFloat(i)>parseFloat(e);case\":decrement\":return(e,i)=>parseFloat(i)<parseFloat(e);default:return t.push(function rH(n){return new H(3016,Ce)}()),\"* => *\"}}(n,e);if(\"function\"==typeof l)return void t.push(l);n=l}const i=n.match(/^(\\*|[-\\w]+)\\s*(<?[=-]>)\\s*(\\*|[-\\w]+)$/);if(null==i||i.length<4)return e.push(function iH(n){return new H(3015,Ce)}()),t;const r=i[1],s=i[2],o=i[3];t.push(mM(r,o));\"<\"==s[0]&&!(\"*\"==r&&\"*\"==o)&&t.push(mM(o,r))}(i,e,t)):e.push(n),e}const pd=new Set([\"true\",\"1\"]),fd=new Set([\"false\",\"0\"]);function mM(n,t){const e=pd.has(n)||fd.has(n),i=pd.has(t)||fd.has(t);return(r,s)=>{let o=\"*\"==n||n==r,a=\"*\"==t||t==s;return!o&&e&&\"boolean\"==typeof r&&(o=r?pd.has(n):fd.has(n)),!a&&i&&\"boolean\"==typeof s&&(a=s?pd.has(t):fd.has(t)),o&&a}}const NH=new RegExp(\"s*:selfs*,?\",\"g\");function nm(n,t,e,i){return new LH(n).build(t,e,i)}class LH{constructor(t){this._driver=t}build(t,e,i){const r=new HH(e);this._resetContextStyleTimingState(r);const s=un(this,Ba(t),r);return r.unsupportedCSSPropertiesFound.size&&r.unsupportedCSSPropertiesFound.keys(),s}_resetContextStyleTimingState(t){t.currentQuerySelector=\"\",t.collectedStyles={},t.collectedStyles[\"\"]={},t.currentTime=0}visitTrigger(t,e){let i=e.queryCount=0,r=e.depCount=0;const s=[],o=[];return\"@\"==t.name.charAt(0)&&e.errors.push(function W2(){return new H(3006,Ce)}()),t.definitions.forEach(a=>{if(this._resetContextStyleTimingState(e),0==a.type){const l=a,c=l.name;c.toString().split(/\\s*,\\s*/).forEach(d=>{l.name=d,s.push(this.visitState(l,e))}),l.name=c}else if(1==a.type){const l=this.visitTransition(a,e);i+=l.queryCount,r+=l.depCount,o.push(l)}else e.errors.push(function q2(){return new H(3007,Ce)}())}),{type:7,name:t.name,states:s,transitions:o,queryCount:i,depCount:r,options:null}}visitState(t,e){const i=this.visitStyle(t.styles,e),r=t.options&&t.options.params||null;if(i.containsDynamicStyles){const s=new Set,o=r||{};i.styles.forEach(a=>{if(md(a)){const l=a;Object.keys(l).forEach(c=>{pM(l[c]).forEach(d=>{o.hasOwnProperty(d)||s.add(d)})})}}),s.size&&(cd(s.values()),e.errors.push(function Y2(n,t){return new H(3008,Ce)}()))}return{type:0,name:t.name,style:i,options:r?{params:r}:null}}visitTransition(t,e){e.queryCount=0,e.depCount=0;const i=un(this,Ba(t.animation),e);return{type:1,matchers:OH(t.expr,e.errors),animation:i,queryCount:e.queryCount,depCount:e.depCount,options:Ur(t.options)}}visitSequence(t,e){return{type:2,steps:t.steps.map(i=>un(this,i,e)),options:Ur(t.options)}}visitGroup(t,e){const i=e.currentTime;let r=0;const s=t.steps.map(o=>{e.currentTime=i;const a=un(this,o,e);return r=Math.max(r,e.currentTime),a});return e.currentTime=r,{type:3,steps:s,options:Ur(t.options)}}visitAnimate(t,e){const i=function zH(n,t){let e=null;if(n.hasOwnProperty(\"duration\"))e=n;else if(\"number\"==typeof n)return im(ad(n,t).duration,0,\"\");const i=n;if(i.split(/\\s+/).some(s=>\"{\"==s.charAt(0)&&\"{\"==s.charAt(1))){const s=im(0,0,\"\");return s.dynamic=!0,s.strValue=i,s}return e=e||ad(i,t),im(e.duration,e.delay,e.easing)}(t.timings,e.errors);e.currentAnimateTimings=i;let r,s=t.styles?t.styles:R({});if(5==s.type)r=this.visitKeyframes(s,e);else{let o=t.styles,a=!1;if(!o){a=!0;const c={};i.easing&&(c.easing=i.easing),o=R(c)}e.currentTime+=i.duration+i.delay;const l=this.visitStyle(o,e);l.isEmptyStep=a,r=l}return e.currentAnimateTimings=null,{type:4,timings:i,style:r,options:null}}visitStyle(t,e){const i=this._makeStyleAst(t,e);return this._validateStyleAst(i,e),i}_makeStyleAst(t,e){const i=[];Array.isArray(t.styles)?t.styles.forEach(o=>{\"string\"==typeof o?o==Vi?i.push(o):e.errors.push(function Q2(n){return new H(3002,Ce)}()):i.push(o)}):i.push(t.styles);let r=!1,s=null;return i.forEach(o=>{if(md(o)){const a=o,l=a.easing;if(l&&(s=l,delete a.easing),!r)for(let c in a)if(a[c].toString().indexOf(\"{{\")>=0){r=!0;break}}}),{type:6,styles:i,easing:s,offset:t.offset,containsDynamicStyles:r,options:null}}_validateStyleAst(t,e){const i=e.currentAnimateTimings;let r=e.currentTime,s=e.currentTime;i&&s>0&&(s-=i.duration+i.delay),t.styles.forEach(o=>{\"string\"!=typeof o&&Object.keys(o).forEach(a=>{if(!this._driver.validateStyleProperty(a))return delete o[a],void e.unsupportedCSSPropertiesFound.add(a);const l=e.collectedStyles[e.currentQuerySelector],c=l[a];let d=!0;c&&(s!=r&&s>=c.startTime&&r<=c.endTime&&(e.errors.push(function K2(n,t,e,i,r){return new H(3010,Ce)}()),d=!1),s=c.startTime),d&&(l[a]={startTime:s,endTime:r}),e.options&&function xH(n,t,e){const i=t.params||{},r=pM(n);r.length&&r.forEach(s=>{i.hasOwnProperty(s)||e.push(function z2(n){return new H(3001,Ce)}())})}(o[a],e.options,e.errors)})})}visitKeyframes(t,e){const i={type:5,styles:[],options:null};if(!e.currentAnimateTimings)return e.errors.push(function Z2(){return new H(3011,Ce)}()),i;let s=0;const o=[];let a=!1,l=!1,c=0;const d=t.steps.map(D=>{const v=this._makeStyleAst(D,e);let M=null!=v.offset?v.offset:function jH(n){if(\"string\"==typeof n)return null;let t=null;if(Array.isArray(n))n.forEach(e=>{if(md(e)&&e.hasOwnProperty(\"offset\")){const i=e;t=parseFloat(i.offset),delete i.offset}});else if(md(n)&&n.hasOwnProperty(\"offset\")){const e=n;t=parseFloat(e.offset),delete e.offset}return t}(v.styles),V=0;return null!=M&&(s++,V=v.offset=M),l=l||V<0||V>1,a=a||V<c,c=V,o.push(V),v});l&&e.errors.push(function X2(){return new H(3012,Ce)}()),a&&e.errors.push(function J2(){return new H(3200,Ce)}());const u=t.steps.length;let h=0;s>0&&s<u?e.errors.push(function eH(){return new H(3202,Ce)}()):0==s&&(h=1/(u-1));const p=u-1,m=e.currentTime,g=e.currentAnimateTimings,_=g.duration;return d.forEach((D,v)=>{const M=h>0?v==p?1:h*v:o[v],V=M*_;e.currentTime=m+g.delay+V,g.duration=V,this._validateStyleAst(D,e),D.offset=M,i.styles.push(D)}),i}visitReference(t,e){return{type:8,animation:un(this,Ba(t.animation),e),options:Ur(t.options)}}visitAnimateChild(t,e){return e.depCount++,{type:9,options:Ur(t.options)}}visitAnimateRef(t,e){return{type:10,animation:this.visitReference(t.animation,e),options:Ur(t.options)}}visitQuery(t,e){const i=e.currentQuerySelector,r=t.options||{};e.queryCount++,e.currentQuery=t;const[s,o]=function BH(n){const t=!!n.split(/\\s*,\\s*/).find(e=>\":self\"==e);return t&&(n=n.replace(NH,\"\")),n=n.replace(/@\\*/g,od).replace(/@\\w+/g,e=>od+\"-\"+e.substr(1)).replace(/:animating/g,Xf),[n,t]}(t.selector);e.currentQuerySelector=i.length?i+\" \"+s:s,dn(e.collectedStyles,e.currentQuerySelector,{});const a=un(this,Ba(t.animation),e);return e.currentQuery=null,e.currentQuerySelector=i,{type:11,selector:s,limit:r.limit||0,optional:!!r.optional,includeSelf:o,animation:a,originalSelector:t.selector,options:Ur(t.options)}}visitStagger(t,e){e.currentQuery||e.errors.push(function tH(){return new H(3013,Ce)}());const i=\"full\"===t.timings?{duration:0,delay:0,easing:\"full\"}:ad(t.timings,e.errors,!0);return{type:12,animation:un(this,Ba(t.animation),e),timings:i,options:null}}}class HH{constructor(t){this.errors=t,this.queryCount=0,this.depCount=0,this.currentTransition=null,this.currentQuery=null,this.currentQuerySelector=null,this.currentAnimateTimings=null,this.currentTime=0,this.collectedStyles={},this.options=null,this.unsupportedCSSPropertiesFound=new Set}}function md(n){return!Array.isArray(n)&&\"object\"==typeof n}function Ur(n){return n?(n=io(n)).params&&(n.params=function VH(n){return n?io(n):null}(n.params)):n={},n}function im(n,t,e){return{duration:n,delay:t,easing:e}}function rm(n,t,e,i,r,s,o=null,a=!1){return{type:1,element:n,keyframes:t,preStyleProps:e,postStyleProps:i,duration:r,delay:s,totalTime:r+s,easing:o,subTimeline:a}}class gd{constructor(){this._map=new Map}get(t){return this._map.get(t)||[]}append(t,e){let i=this._map.get(t);i||this._map.set(t,i=[]),i.push(...e)}has(t){return this._map.has(t)}clear(){this._map.clear()}}const GH=new RegExp(\":enter\",\"g\"),qH=new RegExp(\":leave\",\"g\");function sm(n,t,e,i,r,s={},o={},a,l,c=[]){return(new YH).buildKeyframes(n,t,e,i,r,s,o,a,l,c)}class YH{buildKeyframes(t,e,i,r,s,o,a,l,c,d=[]){c=c||new gd;const u=new om(t,e,c,r,s,d,[]);u.options=l,u.currentTimeline.setStyles([o],null,u.errors,l),un(this,i,u);const h=u.timelines.filter(p=>p.containsAnimation());if(Object.keys(a).length){let p;for(let m=h.length-1;m>=0;m--){const g=h[m];if(g.element===e){p=g;break}}p&&!p.allowOnlyTimelineStyles()&&p.setStyles([a],null,u.errors,l)}return h.length?h.map(p=>p.buildKeyframes()):[rm(e,[],[],[],0,0,\"\",!1)]}visitTrigger(t,e){}visitState(t,e){}visitTransition(t,e){}visitAnimateChild(t,e){const i=e.subInstructions.get(e.element);if(i){const r=e.createSubContext(t.options),s=e.currentTimeline.currentTime,o=this._visitSubInstructions(i,r,r.options);s!=o&&e.transformIntoNewTimeline(o)}e.previousNode=t}visitAnimateRef(t,e){const i=e.createSubContext(t.options);i.transformIntoNewTimeline(),this.visitReference(t.animation,i),e.transformIntoNewTimeline(i.currentTimeline.currentTime),e.previousNode=t}_visitSubInstructions(t,e,i){let s=e.currentTimeline.currentTime;const o=null!=i.duration?jr(i.duration):null,a=null!=i.delay?jr(i.delay):null;return 0!==o&&t.forEach(l=>{const c=e.appendInstructionToTimeline(l,o,a);s=Math.max(s,c.duration+c.delay)}),s}visitReference(t,e){e.updateOptions(t.options,!0),un(this,t.animation,e),e.previousNode=t}visitSequence(t,e){const i=e.subContextCount;let r=e;const s=t.options;if(s&&(s.params||s.delay)&&(r=e.createSubContext(s),r.transformIntoNewTimeline(),null!=s.delay)){6==r.previousNode.type&&(r.currentTimeline.snapshotCurrentStyles(),r.previousNode=_d);const o=jr(s.delay);r.delayNextStep(o)}t.steps.length&&(t.steps.forEach(o=>un(this,o,r)),r.currentTimeline.applyStylesToKeyframe(),r.subContextCount>i&&r.transformIntoNewTimeline()),e.previousNode=t}visitGroup(t,e){const i=[];let r=e.currentTimeline.currentTime;const s=t.options&&t.options.delay?jr(t.options.delay):0;t.steps.forEach(o=>{const a=e.createSubContext(t.options);s&&a.delayNextStep(s),un(this,o,a),r=Math.max(r,a.currentTimeline.currentTime),i.push(a.currentTimeline)}),i.forEach(o=>e.currentTimeline.mergeTimelineCollectedStyles(o)),e.transformIntoNewTimeline(r),e.previousNode=t}_visitTiming(t,e){if(t.dynamic){const i=t.strValue;return ad(e.params?ld(i,e.params,e.errors):i,e.errors)}return{duration:t.duration,delay:t.delay,easing:t.easing}}visitAnimate(t,e){const i=e.currentAnimateTimings=this._visitTiming(t.timings,e),r=e.currentTimeline;i.delay&&(e.incrementTime(i.delay),r.snapshotCurrentStyles());const s=t.style;5==s.type?this.visitKeyframes(s,e):(e.incrementTime(i.duration),this.visitStyle(s,e),r.applyStylesToKeyframe()),e.currentAnimateTimings=null,e.previousNode=t}visitStyle(t,e){const i=e.currentTimeline,r=e.currentAnimateTimings;!r&&i.getCurrentStyleProperties().length&&i.forwardFrame();const s=r&&r.easing||t.easing;t.isEmptyStep?i.applyEmptyStep(s):i.setStyles(t.styles,s,e.errors,e.options),e.previousNode=t}visitKeyframes(t,e){const i=e.currentAnimateTimings,r=e.currentTimeline.duration,s=i.duration,a=e.createSubContext().currentTimeline;a.easing=i.easing,t.styles.forEach(l=>{a.forwardTime((l.offset||0)*s),a.setStyles(l.styles,l.easing,e.errors,e.options),a.applyStylesToKeyframe()}),e.currentTimeline.mergeTimelineCollectedStyles(a),e.transformIntoNewTimeline(r+s),e.previousNode=t}visitQuery(t,e){const i=e.currentTimeline.currentTime,r=t.options||{},s=r.delay?jr(r.delay):0;s&&(6===e.previousNode.type||0==i&&e.currentTimeline.getCurrentStyleProperties().length)&&(e.currentTimeline.snapshotCurrentStyles(),e.previousNode=_d);let o=i;const a=e.invokeQuery(t.selector,t.originalSelector,t.limit,t.includeSelf,!!r.optional,e.errors);e.currentQueryTotal=a.length;let l=null;a.forEach((c,d)=>{e.currentQueryIndex=d;const u=e.createSubContext(t.options,c);s&&u.delayNextStep(s),c===e.element&&(l=u.currentTimeline),un(this,t.animation,u),u.currentTimeline.applyStylesToKeyframe(),o=Math.max(o,u.currentTimeline.currentTime)}),e.currentQueryIndex=0,e.currentQueryTotal=0,e.transformIntoNewTimeline(o),l&&(e.currentTimeline.mergeTimelineCollectedStyles(l),e.currentTimeline.snapshotCurrentStyles()),e.previousNode=t}visitStagger(t,e){const i=e.parentContext,r=e.currentTimeline,s=t.timings,o=Math.abs(s.duration),a=o*(e.currentQueryTotal-1);let l=o*e.currentQueryIndex;switch(s.duration<0?\"reverse\":s.easing){case\"reverse\":l=a-l;break;case\"full\":l=i.currentStaggerTime}const d=e.currentTimeline;l&&d.delayNextStep(l);const u=d.currentTime;un(this,t.animation,e),e.previousNode=t,i.currentStaggerTime=r.currentTime-u+(r.startTime-i.currentTimeline.startTime)}}const _d={};class om{constructor(t,e,i,r,s,o,a,l){this._driver=t,this.element=e,this.subInstructions=i,this._enterClassName=r,this._leaveClassName=s,this.errors=o,this.timelines=a,this.parentContext=null,this.currentAnimateTimings=null,this.previousNode=_d,this.subContextCount=0,this.options={},this.currentQueryIndex=0,this.currentQueryTotal=0,this.currentStaggerTime=0,this.currentTimeline=l||new vd(this._driver,e,0),a.push(this.currentTimeline)}get params(){return this.options.params}updateOptions(t,e){if(!t)return;const i=t;let r=this.options;null!=i.duration&&(r.duration=jr(i.duration)),null!=i.delay&&(r.delay=jr(i.delay));const s=i.params;if(s){let o=r.params;o||(o=this.options.params={}),Object.keys(s).forEach(a=>{(!e||!o.hasOwnProperty(a))&&(o[a]=ld(s[a],o,this.errors))})}}_copyOptions(){const t={};if(this.options){const e=this.options.params;if(e){const i=t.params={};Object.keys(e).forEach(r=>{i[r]=e[r]})}}return t}createSubContext(t=null,e,i){const r=e||this.element,s=new om(this._driver,r,this.subInstructions,this._enterClassName,this._leaveClassName,this.errors,this.timelines,this.currentTimeline.fork(r,i||0));return s.previousNode=this.previousNode,s.currentAnimateTimings=this.currentAnimateTimings,s.options=this._copyOptions(),s.updateOptions(t),s.currentQueryIndex=this.currentQueryIndex,s.currentQueryTotal=this.currentQueryTotal,s.parentContext=this,this.subContextCount++,s}transformIntoNewTimeline(t){return this.previousNode=_d,this.currentTimeline=this.currentTimeline.fork(this.element,t),this.timelines.push(this.currentTimeline),this.currentTimeline}appendInstructionToTimeline(t,e,i){const r={duration:null!=e?e:t.duration,delay:this.currentTimeline.currentTime+(null!=i?i:0)+t.delay,easing:\"\"},s=new QH(this._driver,t.element,t.keyframes,t.preStyleProps,t.postStyleProps,r,t.stretchStartingKeyframe);return this.timelines.push(s),r}incrementTime(t){this.currentTimeline.forwardTime(this.currentTimeline.duration+t)}delayNextStep(t){t>0&&this.currentTimeline.delayNextStep(t)}invokeQuery(t,e,i,r,s,o){let a=[];if(r&&a.push(this.element),t.length>0){t=(t=t.replace(GH,\".\"+this._enterClassName)).replace(qH,\".\"+this._leaveClassName);let c=this._driver.query(this.element,t,1!=i);0!==i&&(c=i<0?c.slice(c.length+i,c.length):c.slice(0,i)),a.push(...c)}return!s&&0==a.length&&o.push(function nH(n){return new H(3014,Ce)}()),a}}class vd{constructor(t,e,i,r){this._driver=t,this.element=e,this.startTime=i,this._elementTimelineStylesLookup=r,this.duration=0,this._previousKeyframe={},this._currentKeyframe={},this._keyframes=new Map,this._styleSummary={},this._pendingStyles={},this._backFill={},this._currentEmptyStepKeyframe=null,this._elementTimelineStylesLookup||(this._elementTimelineStylesLookup=new Map),this._localTimelineStyles=Object.create(this._backFill,{}),this._globalTimelineStyles=this._elementTimelineStylesLookup.get(e),this._globalTimelineStyles||(this._globalTimelineStyles=this._localTimelineStyles,this._elementTimelineStylesLookup.set(e,this._localTimelineStyles)),this._loadKeyframe()}containsAnimation(){switch(this._keyframes.size){case 0:return!1;case 1:return this.getCurrentStyleProperties().length>0;default:return!0}}getCurrentStyleProperties(){return Object.keys(this._currentKeyframe)}get currentTime(){return this.startTime+this.duration}delayNextStep(t){const e=1==this._keyframes.size&&Object.keys(this._pendingStyles).length;this.duration||e?(this.forwardTime(this.currentTime+t),e&&this.snapshotCurrentStyles()):this.startTime+=t}fork(t,e){return this.applyStylesToKeyframe(),new vd(this._driver,t,e||this.currentTime,this._elementTimelineStylesLookup)}_loadKeyframe(){this._currentKeyframe&&(this._previousKeyframe=this._currentKeyframe),this._currentKeyframe=this._keyframes.get(this.duration),this._currentKeyframe||(this._currentKeyframe=Object.create(this._backFill,{}),this._keyframes.set(this.duration,this._currentKeyframe))}forwardFrame(){this.duration+=1,this._loadKeyframe()}forwardTime(t){this.applyStylesToKeyframe(),this.duration=t,this._loadKeyframe()}_updateStyle(t,e){this._localTimelineStyles[t]=e,this._globalTimelineStyles[t]=e,this._styleSummary[t]={time:this.currentTime,value:e}}allowOnlyTimelineStyles(){return this._currentEmptyStepKeyframe!==this._currentKeyframe}applyEmptyStep(t){t&&(this._previousKeyframe.easing=t),Object.keys(this._globalTimelineStyles).forEach(e=>{this._backFill[e]=this._globalTimelineStyles[e]||Vi,this._currentKeyframe[e]=Vi}),this._currentEmptyStepKeyframe=this._currentKeyframe}setStyles(t,e,i,r){e&&(this._previousKeyframe.easing=e);const s=r&&r.params||{},o=function KH(n,t){const e={};let i;return n.forEach(r=>{\"*\"===r?(i=i||Object.keys(t),i.forEach(s=>{e[s]=Vi})):rr(r,!1,e)}),e}(t,this._globalTimelineStyles);Object.keys(o).forEach(a=>{const l=ld(o[a],s,i);this._pendingStyles[a]=l,this._localTimelineStyles.hasOwnProperty(a)||(this._backFill[a]=this._globalTimelineStyles.hasOwnProperty(a)?this._globalTimelineStyles[a]:Vi),this._updateStyle(a,l)})}applyStylesToKeyframe(){const t=this._pendingStyles,e=Object.keys(t);0!=e.length&&(this._pendingStyles={},e.forEach(i=>{this._currentKeyframe[i]=t[i]}),Object.keys(this._localTimelineStyles).forEach(i=>{this._currentKeyframe.hasOwnProperty(i)||(this._currentKeyframe[i]=this._localTimelineStyles[i])}))}snapshotCurrentStyles(){Object.keys(this._localTimelineStyles).forEach(t=>{const e=this._localTimelineStyles[t];this._pendingStyles[t]=e,this._updateStyle(t,e)})}getFinalKeyframe(){return this._keyframes.get(this.duration)}get properties(){const t=[];for(let e in this._currentKeyframe)t.push(e);return t}mergeTimelineCollectedStyles(t){Object.keys(t._styleSummary).forEach(e=>{const i=this._styleSummary[e],r=t._styleSummary[e];(!i||r.time>i.time)&&this._updateStyle(e,r.value)})}buildKeyframes(){this.applyStylesToKeyframe();const t=new Set,e=new Set,i=1===this._keyframes.size&&0===this.duration;let r=[];this._keyframes.forEach((a,l)=>{const c=rr(a,!0);Object.keys(c).forEach(d=>{const u=c[d];\"!\"==u?t.add(d):u==Vi&&e.add(d)}),i||(c.offset=l/this.duration),r.push(c)});const s=t.size?cd(t.values()):[],o=e.size?cd(e.values()):[];if(i){const a=r[0],l=io(a);a.offset=0,l.offset=1,r=[a,l]}return rm(this.element,r,s,o,this.duration,this.startTime,this.easing,!1)}}class QH extends vd{constructor(t,e,i,r,s,o,a=!1){super(t,e,o.delay),this.keyframes=i,this.preStyleProps=r,this.postStyleProps=s,this._stretchStartingKeyframe=a,this.timings={duration:o.duration,delay:o.delay,easing:o.easing}}containsAnimation(){return this.keyframes.length>1}buildKeyframes(){let t=this.keyframes,{delay:e,duration:i,easing:r}=this.timings;if(this._stretchStartingKeyframe&&e){const s=[],o=i+e,a=e/o,l=rr(t[0],!1);l.offset=0,s.push(l);const c=rr(t[0],!1);c.offset=vM(a),s.push(c);const d=t.length-1;for(let u=1;u<=d;u++){let h=rr(t[u],!1);h.offset=vM((e+h.offset*i)/o),s.push(h)}i=o,e=0,r=\"\",t=s}return rm(this.element,t,this.preStyleProps,this.postStyleProps,i,e,r,!0)}}function vM(n,t=3){const e=Math.pow(10,t-1);return Math.round(n*e)/e}class am{}class ZH extends am{normalizePropertyName(t,e){return tm(t)}normalizeStyleValue(t,e,i,r){let s=\"\";const o=i.toString().trim();if(XH[e]&&0!==i&&\"0\"!==i)if(\"number\"==typeof i)s=\"px\";else{const a=i.match(/^[+-]?[\\d\\.]+([a-z]*)$/);a&&0==a[1].length&&r.push(function G2(n,t){return new H(3005,Ce)}())}return o+s}}const XH=(()=>function JH(n){const t={};return n.forEach(e=>t[e]=!0),t}(\"width,height,minWidth,minHeight,maxWidth,maxHeight,left,top,bottom,right,fontSize,outlineWidth,outlineOffset,paddingTop,paddingLeft,paddingBottom,paddingRight,marginTop,marginLeft,marginBottom,marginRight,borderRadius,borderWidth,borderTopWidth,borderLeftWidth,borderRightWidth,borderBottomWidth,textIndent,perspective\".split(\",\")))();function yM(n,t,e,i,r,s,o,a,l,c,d,u,h){return{type:0,element:n,triggerName:t,isRemovalTransition:r,fromState:e,fromStyles:s,toState:i,toStyles:o,timelines:a,queriedElements:l,preStyleProps:c,postStyleProps:d,totalTime:u,errors:h}}const lm={};class bM{constructor(t,e,i){this._triggerName=t,this.ast=e,this._stateStyles=i}match(t,e,i,r){return function ej(n,t,e,i,r){return n.some(s=>s(t,e,i,r))}(this.ast.matchers,t,e,i,r)}buildStyles(t,e,i){const r=this._stateStyles[\"*\"],s=this._stateStyles[t],o=r?r.buildStyles(e,i):{};return s?s.buildStyles(e,i):o}build(t,e,i,r,s,o,a,l,c,d){const u=[],h=this.ast.options&&this.ast.options.params||lm,m=this.buildStyles(i,a&&a.params||lm,u),g=l&&l.params||lm,_=this.buildStyles(r,g,u),D=new Set,v=new Map,M=new Map,V=\"void\"===r,he={params:Object.assign(Object.assign({},h),g)},We=d?[]:sm(t,e,this.ast.animation,s,o,m,_,he,c,u);let Ze=0;if(We.forEach(pn=>{Ze=Math.max(pn.duration+pn.delay,Ze)}),u.length)return yM(e,this._triggerName,i,r,V,m,_,[],[],v,M,Ze,u);We.forEach(pn=>{const fn=pn.element,Do=dn(v,fn,{});pn.preStyleProps.forEach(ii=>Do[ii]=!0);const Gi=dn(M,fn,{});pn.postStyleProps.forEach(ii=>Gi[ii]=!0),fn!==e&&D.add(fn)});const hn=cd(D.values());return yM(e,this._triggerName,i,r,V,m,_,We,hn,v,M,Ze)}}class tj{constructor(t,e,i){this.styles=t,this.defaultParams=e,this.normalizer=i}buildStyles(t,e){const i={},r=io(this.defaultParams);return Object.keys(t).forEach(s=>{const o=t[s];null!=o&&(r[s]=o)}),this.styles.styles.forEach(s=>{if(\"string\"!=typeof s){const o=s;Object.keys(o).forEach(a=>{let l=o[a];l.length>1&&(l=ld(l,r,e));const c=this.normalizer.normalizePropertyName(a,e);l=this.normalizer.normalizeStyleValue(a,c,l,e),i[c]=l})}}),i}}class ij{constructor(t,e,i){this.name=t,this.ast=e,this._normalizer=i,this.transitionFactories=[],this.states={},e.states.forEach(r=>{this.states[r.name]=new tj(r.style,r.options&&r.options.params||{},i)}),CM(this.states,\"true\",\"1\"),CM(this.states,\"false\",\"0\"),e.transitions.forEach(r=>{this.transitionFactories.push(new bM(t,r,this.states))}),this.fallbackTransition=function rj(n,t,e){return new bM(n,{type:1,animation:{type:2,steps:[],options:null},matchers:[(o,a)=>!0],options:null,queryCount:0,depCount:0},t)}(t,this.states)}get containsQueries(){return this.ast.queryCount>0}matchTransition(t,e,i,r){return this.transitionFactories.find(o=>o.match(t,e,i,r))||null}matchStyles(t,e,i){return this.fallbackTransition.buildStyles(t,e,i)}}function CM(n,t,e){n.hasOwnProperty(t)?n.hasOwnProperty(e)||(n[e]=n[t]):n.hasOwnProperty(e)&&(n[t]=n[e])}const sj=new gd;class oj{constructor(t,e,i){this.bodyNode=t,this._driver=e,this._normalizer=i,this._animations={},this._playersById={},this.players=[]}register(t,e){const i=[],s=nm(this._driver,e,i,[]);if(i.length)throw function cH(n){return new H(3503,Ce)}();this._animations[t]=s}_buildPlayer(t,e,i){const r=t.element,s=Jw(0,this._normalizer,0,t.keyframes,e,i);return this._driver.animate(r,s,t.duration,t.delay,t.easing,[],!0)}create(t,e,i={}){const r=[],s=this._animations[t];let o;const a=new Map;if(s?(o=sm(this._driver,e,s,Zf,rd,{},{},i,sj,r),o.forEach(d=>{const u=dn(a,d.element,{});d.postStyleProps.forEach(h=>u[h]=null)})):(r.push(function dH(){return new H(3300,Ce)}()),o=[]),r.length)throw function uH(n){return new H(3504,Ce)}();a.forEach((d,u)=>{Object.keys(d).forEach(h=>{d[h]=this._driver.computeStyle(u,h,Vi)})});const c=ir(o.map(d=>{const u=a.get(d.element);return this._buildPlayer(d,{},u)}));return this._playersById[t]=c,c.onDestroy(()=>this.destroy(t)),this.players.push(c),c}destroy(t){const e=this._getPlayer(t);e.destroy(),delete this._playersById[t];const i=this.players.indexOf(e);i>=0&&this.players.splice(i,1)}_getPlayer(t){const e=this._playersById[t];if(!e)throw function hH(n){return new H(3301,Ce)}();return e}listen(t,e,i,r){const s=qf(e,\"\",\"\",\"\");return Gf(this._getPlayer(t),i,s,r),()=>{}}command(t,e,i,r){if(\"register\"==i)return void this.register(t,r[0]);if(\"create\"==i)return void this.create(t,e,r[0]||{});const s=this._getPlayer(t);switch(i){case\"play\":s.play();break;case\"pause\":s.pause();break;case\"reset\":s.reset();break;case\"restart\":s.restart();break;case\"finish\":s.finish();break;case\"init\":s.init();break;case\"setPosition\":s.setPosition(parseFloat(r[0]));break;case\"destroy\":this.destroy(t)}}}const DM=\"ng-animate-queued\",cm=\"ng-animate-disabled\",uj=[],wM={namespaceId:\"\",setForRemoval:!1,setForMove:!1,hasAnimation:!1,removedBeforeQueried:!1},hj={namespaceId:\"\",setForMove:!1,setForRemoval:!1,hasAnimation:!1,removedBeforeQueried:!0},An=\"__ng_removed\";class dm{constructor(t,e=\"\"){this.namespaceId=e;const i=t&&t.hasOwnProperty(\"value\");if(this.value=function gj(n){return null!=n?n:null}(i?t.value:t),i){const s=io(t);delete s.value,this.options=s}else this.options={};this.options.params||(this.options.params={})}get params(){return this.options.params}absorbOptions(t){const e=t.params;if(e){const i=this.options.params;Object.keys(e).forEach(r=>{null==i[r]&&(i[r]=e[r])})}}}const Va=\"void\",um=new dm(Va);class pj{constructor(t,e,i){this.id=t,this.hostElement=e,this._engine=i,this.players=[],this._triggers={},this._queue=[],this._elementListeners=new Map,this._hostClassName=\"ng-tns-\"+t,In(e,this._hostClassName)}listen(t,e,i,r){if(!this._triggers.hasOwnProperty(e))throw function pH(n,t){return new H(3302,Ce)}();if(null==i||0==i.length)throw function fH(n){return new H(3303,Ce)}();if(!function _j(n){return\"start\"==n||\"done\"==n}(i))throw function mH(n,t){return new H(3400,Ce)}();const s=dn(this._elementListeners,t,[]),o={name:e,phase:i,callback:r};s.push(o);const a=dn(this._engine.statesByElement,t,{});return a.hasOwnProperty(e)||(In(t,sd),In(t,sd+\"-\"+e),a[e]=um),()=>{this._engine.afterFlush(()=>{const l=s.indexOf(o);l>=0&&s.splice(l,1),this._triggers[e]||delete a[e]})}}register(t,e){return!this._triggers[t]&&(this._triggers[t]=e,!0)}_getTrigger(t){const e=this._triggers[t];if(!e)throw function gH(n){return new H(3401,Ce)}();return e}trigger(t,e,i,r=!0){const s=this._getTrigger(e),o=new hm(this.id,e,t);let a=this._engine.statesByElement.get(t);a||(In(t,sd),In(t,sd+\"-\"+e),this._engine.statesByElement.set(t,a={}));let l=a[e];const c=new dm(i,this.id);if(!(i&&i.hasOwnProperty(\"value\"))&&l&&c.absorbOptions(l.options),a[e]=c,l||(l=um),c.value!==Va&&l.value===c.value){if(!function bj(n,t){const e=Object.keys(n),i=Object.keys(t);if(e.length!=i.length)return!1;for(let r=0;r<e.length;r++){const s=e[r];if(!t.hasOwnProperty(s)||n[s]!==t[s])return!1}return!0}(l.params,c.params)){const g=[],_=s.matchStyles(l.value,l.params,g),D=s.matchStyles(c.value,c.params,g);g.length?this._engine.reportError(g):this._engine.afterFlush(()=>{zr(t,_),vi(t,D)})}return}const h=dn(this._engine.playersByElement,t,[]);h.forEach(g=>{g.namespaceId==this.id&&g.triggerName==e&&g.queued&&g.destroy()});let p=s.matchTransition(l.value,c.value,t,c.params),m=!1;if(!p){if(!r)return;p=s.fallbackTransition,m=!0}return this._engine.totalQueuedPlayers++,this._queue.push({element:t,triggerName:e,transition:p,fromState:l,toState:c,player:o,isFallbackTransition:m}),m||(In(t,DM),o.onStart(()=>{ro(t,DM)})),o.onDone(()=>{let g=this.players.indexOf(o);g>=0&&this.players.splice(g,1);const _=this._engine.playersByElement.get(t);if(_){let D=_.indexOf(o);D>=0&&_.splice(D,1)}}),this.players.push(o),h.push(o),o}deregister(t){delete this._triggers[t],this._engine.statesByElement.forEach((e,i)=>{delete e[t]}),this._elementListeners.forEach((e,i)=>{this._elementListeners.set(i,e.filter(r=>r.name!=t))})}clearElementCache(t){this._engine.statesByElement.delete(t),this._elementListeners.delete(t);const e=this._engine.playersByElement.get(t);e&&(e.forEach(i=>i.destroy()),this._engine.playersByElement.delete(t))}_signalRemovalForInnerTriggers(t,e){const i=this._engine.driver.query(t,od,!0);i.forEach(r=>{if(r[An])return;const s=this._engine.fetchNamespacesByElement(r);s.size?s.forEach(o=>o.triggerLeaveAnimation(r,e,!1,!0)):this.clearElementCache(r)}),this._engine.afterFlushAnimationsDone(()=>i.forEach(r=>this.clearElementCache(r)))}triggerLeaveAnimation(t,e,i,r){const s=this._engine.statesByElement.get(t),o=new Map;if(s){const a=[];if(Object.keys(s).forEach(l=>{if(o.set(l,s[l].value),this._triggers[l]){const c=this.trigger(t,l,Va,r);c&&a.push(c)}}),a.length)return this._engine.markElementAsRemoved(this.id,t,!0,e,o),i&&ir(a).onDone(()=>this._engine.processLeaveNode(t)),!0}return!1}prepareLeaveAnimationListeners(t){const e=this._elementListeners.get(t),i=this._engine.statesByElement.get(t);if(e&&i){const r=new Set;e.forEach(s=>{const o=s.name;if(r.has(o))return;r.add(o);const l=this._triggers[o].fallbackTransition,c=i[o]||um,d=new dm(Va),u=new hm(this.id,o,t);this._engine.totalQueuedPlayers++,this._queue.push({element:t,triggerName:o,transition:l,fromState:c,toState:d,player:u,isFallbackTransition:!0})})}}removeNode(t,e){const i=this._engine;if(t.childElementCount&&this._signalRemovalForInnerTriggers(t,e),this.triggerLeaveAnimation(t,e,!0))return;let r=!1;if(i.totalAnimations){const s=i.players.length?i.playersByQueriedElement.get(t):[];if(s&&s.length)r=!0;else{let o=t;for(;o=o.parentNode;)if(i.statesByElement.get(o)){r=!0;break}}}if(this.prepareLeaveAnimationListeners(t),r)i.markElementAsRemoved(this.id,t,!1,e);else{const s=t[An];(!s||s===wM)&&(i.afterFlush(()=>this.clearElementCache(t)),i.destroyInnerAnimations(t),i._onRemovalComplete(t,e))}}insertNode(t,e){In(t,this._hostClassName)}drainQueuedTransitions(t){const e=[];return this._queue.forEach(i=>{const r=i.player;if(r.destroyed)return;const s=i.element,o=this._elementListeners.get(s);o&&o.forEach(a=>{if(a.name==i.triggerName){const l=qf(s,i.triggerName,i.fromState.value,i.toState.value);l._data=t,Gf(i.player,a.phase,l,a.callback)}}),r.markedForDestroy?this._engine.afterFlush(()=>{r.destroy()}):e.push(i)}),this._queue=[],e.sort((i,r)=>{const s=i.transition.ast.depCount,o=r.transition.ast.depCount;return 0==s||0==o?s-o:this._engine.driver.containsElement(i.element,r.element)?1:-1})}destroy(t){this.players.forEach(e=>e.destroy()),this._signalRemovalForInnerTriggers(this.hostElement,t)}elementContainsData(t){let e=!1;return this._elementListeners.has(t)&&(e=!0),e=!!this._queue.find(i=>i.element===t)||e,e}}class fj{constructor(t,e,i){this.bodyNode=t,this.driver=e,this._normalizer=i,this.players=[],this.newHostElements=new Map,this.playersByElement=new Map,this.playersByQueriedElement=new Map,this.statesByElement=new Map,this.disabledNodes=new Set,this.totalAnimations=0,this.totalQueuedPlayers=0,this._namespaceLookup={},this._namespaceList=[],this._flushFns=[],this._whenQuietFns=[],this.namespacesByHostElement=new Map,this.collectedEnterElements=[],this.collectedLeaveElements=[],this.onRemovalComplete=(r,s)=>{}}_onRemovalComplete(t,e){this.onRemovalComplete(t,e)}get queuedPlayers(){const t=[];return this._namespaceList.forEach(e=>{e.players.forEach(i=>{i.queued&&t.push(i)})}),t}createNamespace(t,e){const i=new pj(t,e,this);return this.bodyNode&&this.driver.containsElement(this.bodyNode,e)?this._balanceNamespaceList(i,e):(this.newHostElements.set(e,i),this.collectEnterElement(e)),this._namespaceLookup[t]=i}_balanceNamespaceList(t,e){const i=this._namespaceList,r=this.namespacesByHostElement,s=i.length-1;if(s>=0){let o=!1;if(void 0!==this.driver.getParentElement){let a=this.driver.getParentElement(e);for(;a;){const l=r.get(a);if(l){const c=i.indexOf(l);i.splice(c+1,0,t),o=!0;break}a=this.driver.getParentElement(a)}}else for(let a=s;a>=0;a--)if(this.driver.containsElement(i[a].hostElement,e)){i.splice(a+1,0,t),o=!0;break}o||i.unshift(t)}else i.push(t);return r.set(e,t),t}register(t,e){let i=this._namespaceLookup[t];return i||(i=this.createNamespace(t,e)),i}registerTrigger(t,e,i){let r=this._namespaceLookup[t];r&&r.register(e,i)&&this.totalAnimations++}destroy(t,e){if(!t)return;const i=this._fetchNamespace(t);this.afterFlush(()=>{this.namespacesByHostElement.delete(i.hostElement),delete this._namespaceLookup[t];const r=this._namespaceList.indexOf(i);r>=0&&this._namespaceList.splice(r,1)}),this.afterFlushAnimationsDone(()=>i.destroy(e))}_fetchNamespace(t){return this._namespaceLookup[t]}fetchNamespacesByElement(t){const e=new Set,i=this.statesByElement.get(t);if(i){const r=Object.keys(i);for(let s=0;s<r.length;s++){const o=i[r[s]].namespaceId;if(o){const a=this._fetchNamespace(o);a&&e.add(a)}}}return e}trigger(t,e,i,r){if(yd(e)){const s=this._fetchNamespace(t);if(s)return s.trigger(e,i,r),!0}return!1}insertNode(t,e,i,r){if(!yd(e))return;const s=e[An];if(s&&s.setForRemoval){s.setForRemoval=!1,s.setForMove=!0;const o=this.collectedLeaveElements.indexOf(e);o>=0&&this.collectedLeaveElements.splice(o,1)}if(t){const o=this._fetchNamespace(t);o&&o.insertNode(e,i)}r&&this.collectEnterElement(e)}collectEnterElement(t){this.collectedEnterElements.push(t)}markElementAsDisabled(t,e){e?this.disabledNodes.has(t)||(this.disabledNodes.add(t),In(t,cm)):this.disabledNodes.has(t)&&(this.disabledNodes.delete(t),ro(t,cm))}removeNode(t,e,i,r){if(yd(e)){const s=t?this._fetchNamespace(t):null;if(s?s.removeNode(e,r):this.markElementAsRemoved(t,e,!1,r),i){const o=this.namespacesByHostElement.get(e);o&&o.id!==t&&o.removeNode(e,r)}}else this._onRemovalComplete(e,r)}markElementAsRemoved(t,e,i,r,s){this.collectedLeaveElements.push(e),e[An]={namespaceId:t,setForRemoval:r,hasAnimation:i,removedBeforeQueried:!1,previousTriggersValues:s}}listen(t,e,i,r,s){return yd(e)?this._fetchNamespace(t).listen(e,i,r,s):()=>{}}_buildInstruction(t,e,i,r,s){return t.transition.build(this.driver,t.element,t.fromState.value,t.toState.value,i,r,t.fromState.options,t.toState.options,e,s)}destroyInnerAnimations(t){let e=this.driver.query(t,od,!0);e.forEach(i=>this.destroyActiveAnimationsForElement(i)),0!=this.playersByQueriedElement.size&&(e=this.driver.query(t,Xf,!0),e.forEach(i=>this.finishActiveQueriedAnimationOnElement(i)))}destroyActiveAnimationsForElement(t){const e=this.playersByElement.get(t);e&&e.forEach(i=>{i.queued?i.markedForDestroy=!0:i.destroy()})}finishActiveQueriedAnimationOnElement(t){const e=this.playersByQueriedElement.get(t);e&&e.forEach(i=>i.finish())}whenRenderingDone(){return new Promise(t=>{if(this.players.length)return ir(this.players).onDone(()=>t());t()})}processLeaveNode(t){var e;const i=t[An];if(i&&i.setForRemoval){if(t[An]=wM,i.namespaceId){this.destroyInnerAnimations(t);const r=this._fetchNamespace(i.namespaceId);r&&r.clearElementCache(t)}this._onRemovalComplete(t,i.setForRemoval)}(null===(e=t.classList)||void 0===e?void 0:e.contains(cm))&&this.markElementAsDisabled(t,!1),this.driver.query(t,\".ng-animate-disabled\",!0).forEach(r=>{this.markElementAsDisabled(r,!1)})}flush(t=-1){let e=[];if(this.newHostElements.size&&(this.newHostElements.forEach((i,r)=>this._balanceNamespaceList(i,r)),this.newHostElements.clear()),this.totalAnimations&&this.collectedEnterElements.length)for(let i=0;i<this.collectedEnterElements.length;i++)In(this.collectedEnterElements[i],\"ng-star-inserted\");if(this._namespaceList.length&&(this.totalQueuedPlayers||this.collectedLeaveElements.length)){const i=[];try{e=this._flushAnimations(i,t)}finally{for(let r=0;r<i.length;r++)i[r]()}}else for(let i=0;i<this.collectedLeaveElements.length;i++)this.processLeaveNode(this.collectedLeaveElements[i]);if(this.totalQueuedPlayers=0,this.collectedEnterElements.length=0,this.collectedLeaveElements.length=0,this._flushFns.forEach(i=>i()),this._flushFns=[],this._whenQuietFns.length){const i=this._whenQuietFns;this._whenQuietFns=[],e.length?ir(e).onDone(()=>{i.forEach(r=>r())}):i.forEach(r=>r())}}reportError(t){throw function _H(n){return new H(3402,Ce)}()}_flushAnimations(t,e){const i=new gd,r=[],s=new Map,o=[],a=new Map,l=new Map,c=new Map,d=new Set;this.disabledNodes.forEach(j=>{d.add(j);const Y=this.driver.query(j,\".ng-animate-queued\",!0);for(let X=0;X<Y.length;X++)d.add(Y[X])});const u=this.bodyNode,h=Array.from(this.statesByElement.keys()),p=EM(h,this.collectedEnterElements),m=new Map;let g=0;p.forEach((j,Y)=>{const X=Zf+g++;m.set(Y,X),j.forEach(Se=>In(Se,X))});const _=[],D=new Set,v=new Set;for(let j=0;j<this.collectedLeaveElements.length;j++){const Y=this.collectedLeaveElements[j],X=Y[An];X&&X.setForRemoval&&(_.push(Y),D.add(Y),X.hasAnimation?this.driver.query(Y,\".ng-star-inserted\",!0).forEach(Se=>D.add(Se)):v.add(Y))}const M=new Map,V=EM(h,Array.from(D));V.forEach((j,Y)=>{const X=rd+g++;M.set(Y,X),j.forEach(Se=>In(Se,X))}),t.push(()=>{p.forEach((j,Y)=>{const X=m.get(Y);j.forEach(Se=>ro(Se,X))}),V.forEach((j,Y)=>{const X=M.get(Y);j.forEach(Se=>ro(Se,X))}),_.forEach(j=>{this.processLeaveNode(j)})});const he=[],We=[];for(let j=this._namespaceList.length-1;j>=0;j--)this._namespaceList[j].drainQueuedTransitions(e).forEach(X=>{const Se=X.player,St=X.element;if(he.push(Se),this.collectedEnterElements.length){const qt=St[An];if(qt&&qt.setForMove){if(qt.previousTriggersValues&&qt.previousTriggersValues.has(X.triggerName)){const is=qt.previousTriggersValues.get(X.triggerName),pr=this.statesByElement.get(X.element);pr&&pr[X.triggerName]&&(pr[X.triggerName].value=is)}return void Se.destroy()}}const wi=!u||!this.driver.containsElement(u,St),mn=M.get(St),hr=m.get(St),Xe=this._buildInstruction(X,i,hr,mn,wi);if(Xe.errors&&Xe.errors.length)return void We.push(Xe);if(wi)return Se.onStart(()=>zr(St,Xe.fromStyles)),Se.onDestroy(()=>vi(St,Xe.toStyles)),void r.push(Se);if(X.isFallbackTransition)return Se.onStart(()=>zr(St,Xe.fromStyles)),Se.onDestroy(()=>vi(St,Xe.toStyles)),void r.push(Se);const pk=[];Xe.timelines.forEach(qt=>{qt.stretchStartingKeyframe=!0,this.disabledNodes.has(qt.element)||pk.push(qt)}),Xe.timelines=pk,i.append(St,Xe.timelines),o.push({instruction:Xe,player:Se,element:St}),Xe.queriedElements.forEach(qt=>dn(a,qt,[]).push(Se)),Xe.preStyleProps.forEach((qt,is)=>{const pr=Object.keys(qt);if(pr.length){let rs=l.get(is);rs||l.set(is,rs=new Set),pr.forEach(Xg=>rs.add(Xg))}}),Xe.postStyleProps.forEach((qt,is)=>{const pr=Object.keys(qt);let rs=c.get(is);rs||c.set(is,rs=new Set),pr.forEach(Xg=>rs.add(Xg))})});if(We.length){const j=[];We.forEach(Y=>{j.push(function vH(n,t){return new H(3505,Ce)}())}),he.forEach(Y=>Y.destroy()),this.reportError(j)}const Ze=new Map,hn=new Map;o.forEach(j=>{const Y=j.element;i.has(Y)&&(hn.set(Y,Y),this._beforeAnimationBuild(j.player.namespaceId,j.instruction,Ze))}),r.forEach(j=>{const Y=j.element;this._getPreviousPlayers(Y,!1,j.namespaceId,j.triggerName,null).forEach(Se=>{dn(Ze,Y,[]).push(Se),Se.destroy()})});const pn=_.filter(j=>kM(j,l,c)),fn=new Map;xM(fn,this.driver,v,c,Vi).forEach(j=>{kM(j,l,c)&&pn.push(j)});const Gi=new Map;p.forEach((j,Y)=>{xM(Gi,this.driver,new Set(j),l,\"!\")}),pn.forEach(j=>{const Y=fn.get(j),X=Gi.get(j);fn.set(j,Object.assign(Object.assign({},Y),X))});const ii=[],wo=[],Mo={};o.forEach(j=>{const{element:Y,player:X,instruction:Se}=j;if(i.has(Y)){if(d.has(Y))return X.onDestroy(()=>vi(Y,Se.toStyles)),X.disabled=!0,X.overrideTotalTime(Se.totalTime),void r.push(X);let St=Mo;if(hn.size>1){let mn=Y;const hr=[];for(;mn=mn.parentNode;){const Xe=hn.get(mn);if(Xe){St=Xe;break}hr.push(mn)}hr.forEach(Xe=>hn.set(Xe,St))}const wi=this._buildAnimation(X.namespaceId,Se,Ze,s,Gi,fn);if(X.setRealPlayer(wi),St===Mo)ii.push(X);else{const mn=this.playersByElement.get(St);mn&&mn.length&&(X.parentPlayer=ir(mn)),r.push(X)}}else zr(Y,Se.fromStyles),X.onDestroy(()=>vi(Y,Se.toStyles)),wo.push(X),d.has(Y)&&r.push(X)}),wo.forEach(j=>{const Y=s.get(j.element);if(Y&&Y.length){const X=ir(Y);j.setRealPlayer(X)}}),r.forEach(j=>{j.parentPlayer?j.syncPlayerEvents(j.parentPlayer):j.destroy()});for(let j=0;j<_.length;j++){const Y=_[j],X=Y[An];if(ro(Y,rd),X&&X.hasAnimation)continue;let Se=[];if(a.size){let wi=a.get(Y);wi&&wi.length&&Se.push(...wi);let mn=this.driver.query(Y,Xf,!0);for(let hr=0;hr<mn.length;hr++){let Xe=a.get(mn[hr]);Xe&&Xe.length&&Se.push(...Xe)}}const St=Se.filter(wi=>!wi.destroyed);St.length?vj(this,Y,St):this.processLeaveNode(Y)}return _.length=0,ii.forEach(j=>{this.players.push(j),j.onDone(()=>{j.destroy();const Y=this.players.indexOf(j);this.players.splice(Y,1)}),j.play()}),ii}elementContainsData(t,e){let i=!1;const r=e[An];return r&&r.setForRemoval&&(i=!0),this.playersByElement.has(e)&&(i=!0),this.playersByQueriedElement.has(e)&&(i=!0),this.statesByElement.has(e)&&(i=!0),this._fetchNamespace(t).elementContainsData(e)||i}afterFlush(t){this._flushFns.push(t)}afterFlushAnimationsDone(t){this._whenQuietFns.push(t)}_getPreviousPlayers(t,e,i,r,s){let o=[];if(e){const a=this.playersByQueriedElement.get(t);a&&(o=a)}else{const a=this.playersByElement.get(t);if(a){const l=!s||s==Va;a.forEach(c=>{c.queued||!l&&c.triggerName!=r||o.push(c)})}}return(i||r)&&(o=o.filter(a=>!(i&&i!=a.namespaceId||r&&r!=a.triggerName))),o}_beforeAnimationBuild(t,e,i){const s=e.element,o=e.isRemovalTransition?void 0:t,a=e.isRemovalTransition?void 0:e.triggerName;for(const l of e.timelines){const c=l.element,d=c!==s,u=dn(i,c,[]);this._getPreviousPlayers(c,d,o,a,e.toState).forEach(p=>{const m=p.getRealPlayer();m.beforeDestroy&&m.beforeDestroy(),p.destroy(),u.push(p)})}zr(s,e.fromStyles)}_buildAnimation(t,e,i,r,s,o){const a=e.triggerName,l=e.element,c=[],d=new Set,u=new Set,h=e.timelines.map(m=>{const g=m.element;d.add(g);const _=g[An];if(_&&_.removedBeforeQueried)return new La(m.duration,m.delay);const D=g!==l,v=function yj(n){const t=[];return SM(n,t),t}((i.get(g)||uj).map(Ze=>Ze.getRealPlayer())).filter(Ze=>!!Ze.element&&Ze.element===g),M=s.get(g),V=o.get(g),he=Jw(0,this._normalizer,0,m.keyframes,M,V),We=this._buildPlayer(m,he,v);if(m.subTimeline&&r&&u.add(g),D){const Ze=new hm(t,a,g);Ze.setRealPlayer(We),c.push(Ze)}return We});c.forEach(m=>{dn(this.playersByQueriedElement,m.element,[]).push(m),m.onDone(()=>function mj(n,t,e){let i;if(n instanceof Map){if(i=n.get(t),i){if(i.length){const r=i.indexOf(e);i.splice(r,1)}0==i.length&&n.delete(t)}}else if(i=n[t],i){if(i.length){const r=i.indexOf(e);i.splice(r,1)}0==i.length&&delete n[t]}return i}(this.playersByQueriedElement,m.element,m))}),d.forEach(m=>In(m,cM));const p=ir(h);return p.onDestroy(()=>{d.forEach(m=>ro(m,cM)),vi(l,e.toStyles)}),u.forEach(m=>{dn(r,m,[]).push(p)}),p}_buildPlayer(t,e,i){return e.length>0?this.driver.animate(t.element,e,t.duration,t.delay,t.easing,i):new La(t.duration,t.delay)}}class hm{constructor(t,e,i){this.namespaceId=t,this.triggerName=e,this.element=i,this._player=new La,this._containsRealPlayer=!1,this._queuedCallbacks={},this.destroyed=!1,this.markedForDestroy=!1,this.disabled=!1,this.queued=!0,this.totalTime=0}setRealPlayer(t){this._containsRealPlayer||(this._player=t,Object.keys(this._queuedCallbacks).forEach(e=>{this._queuedCallbacks[e].forEach(i=>Gf(t,e,void 0,i))}),this._queuedCallbacks={},this._containsRealPlayer=!0,this.overrideTotalTime(t.totalTime),this.queued=!1)}getRealPlayer(){return this._player}overrideTotalTime(t){this.totalTime=t}syncPlayerEvents(t){const e=this._player;e.triggerCallback&&t.onStart(()=>e.triggerCallback(\"start\")),t.onDone(()=>this.finish()),t.onDestroy(()=>this.destroy())}_queueEvent(t,e){dn(this._queuedCallbacks,t,[]).push(e)}onDone(t){this.queued&&this._queueEvent(\"done\",t),this._player.onDone(t)}onStart(t){this.queued&&this._queueEvent(\"start\",t),this._player.onStart(t)}onDestroy(t){this.queued&&this._queueEvent(\"destroy\",t),this._player.onDestroy(t)}init(){this._player.init()}hasStarted(){return!this.queued&&this._player.hasStarted()}play(){!this.queued&&this._player.play()}pause(){!this.queued&&this._player.pause()}restart(){!this.queued&&this._player.restart()}finish(){this._player.finish()}destroy(){this.destroyed=!0,this._player.destroy()}reset(){!this.queued&&this._player.reset()}setPosition(t){this.queued||this._player.setPosition(t)}getPosition(){return this.queued?0:this._player.getPosition()}triggerCallback(t){const e=this._player;e.triggerCallback&&e.triggerCallback(t)}}function yd(n){return n&&1===n.nodeType}function MM(n,t){const e=n.style.display;return n.style.display=null!=t?t:\"none\",e}function xM(n,t,e,i,r){const s=[];e.forEach(l=>s.push(MM(l)));const o=[];i.forEach((l,c)=>{const d={};l.forEach(u=>{const h=d[u]=t.computeStyle(c,u,r);(!h||0==h.length)&&(c[An]=hj,o.push(c))}),n.set(c,d)});let a=0;return e.forEach(l=>MM(l,s[a++])),o}function EM(n,t){const e=new Map;if(n.forEach(a=>e.set(a,[])),0==t.length)return e;const r=new Set(t),s=new Map;function o(a){if(!a)return 1;let l=s.get(a);if(l)return l;const c=a.parentNode;return l=e.has(c)?c:r.has(c)?1:o(c),s.set(a,l),l}return t.forEach(a=>{const l=o(a);1!==l&&e.get(l).push(a)}),e}function In(n,t){var e;null===(e=n.classList)||void 0===e||e.add(t)}function ro(n,t){var e;null===(e=n.classList)||void 0===e||e.remove(t)}function vj(n,t,e){ir(e).onDone(()=>n.processLeaveNode(t))}function SM(n,t){for(let e=0;e<n.length;e++){const i=n[e];i instanceof Zw?SM(i.players,t):t.push(i)}}function kM(n,t,e){const i=e.get(n);if(!i)return!1;let r=t.get(n);return r?i.forEach(s=>r.add(s)):t.set(n,i),e.delete(n),!0}class bd{constructor(t,e,i){this.bodyNode=t,this._driver=e,this._normalizer=i,this._triggerCache={},this.onRemovalComplete=(r,s)=>{},this._transitionEngine=new fj(t,e,i),this._timelineEngine=new oj(t,e,i),this._transitionEngine.onRemovalComplete=(r,s)=>this.onRemovalComplete(r,s)}registerTrigger(t,e,i,r,s){const o=t+\"-\"+r;let a=this._triggerCache[o];if(!a){const l=[],d=nm(this._driver,s,l,[]);if(l.length)throw function aH(n,t){return new H(3404,Ce)}();a=function nj(n,t,e){return new ij(n,t,e)}(r,d,this._normalizer),this._triggerCache[o]=a}this._transitionEngine.registerTrigger(e,r,a)}register(t,e){this._transitionEngine.register(t,e)}destroy(t,e){this._transitionEngine.destroy(t,e)}onInsert(t,e,i,r){this._transitionEngine.insertNode(t,e,i,r)}onRemove(t,e,i,r){this._transitionEngine.removeNode(t,e,r||!1,i)}disableAnimations(t,e){this._transitionEngine.markElementAsDisabled(t,e)}process(t,e,i,r){if(\"@\"==i.charAt(0)){const[s,o]=eM(i);this._timelineEngine.command(s,e,o,r)}else this._transitionEngine.trigger(t,e,i,r)}listen(t,e,i,r,s){if(\"@\"==i.charAt(0)){const[o,a]=eM(i);return this._timelineEngine.listen(o,e,a,s)}return this._transitionEngine.listen(t,e,i,r,s)}flush(t=-1){this._transitionEngine.flush(t)}get players(){return this._transitionEngine.players.concat(this._timelineEngine.players)}whenRenderingDone(){return this._transitionEngine.whenRenderingDone()}}let Dj=(()=>{class n{constructor(e,i,r){this._element=e,this._startStyles=i,this._endStyles=r,this._state=0;let s=n.initialStylesByElement.get(e);s||n.initialStylesByElement.set(e,s={}),this._initialStyles=s}start(){this._state<1&&(this._startStyles&&vi(this._element,this._startStyles,this._initialStyles),this._state=1)}finish(){this.start(),this._state<2&&(vi(this._element,this._initialStyles),this._endStyles&&(vi(this._element,this._endStyles),this._endStyles=null),this._state=1)}destroy(){this.finish(),this._state<3&&(n.initialStylesByElement.delete(this._element),this._startStyles&&(zr(this._element,this._startStyles),this._endStyles=null),this._endStyles&&(zr(this._element,this._endStyles),this._endStyles=null),vi(this._element,this._initialStyles),this._state=3)}}return n.initialStylesByElement=new WeakMap,n})();function pm(n){let t=null;const e=Object.keys(n);for(let i=0;i<e.length;i++){const r=e[i];wj(r)&&(t=t||{},t[r]=n[r])}return t}function wj(n){return\"display\"===n||\"position\"===n}class TM{constructor(t,e,i,r){this.element=t,this.keyframes=e,this.options=i,this._specialStyles=r,this._onDoneFns=[],this._onStartFns=[],this._onDestroyFns=[],this._initialized=!1,this._finished=!1,this._started=!1,this._destroyed=!1,this.time=0,this.parentPlayer=null,this.currentSnapshot={},this._duration=i.duration,this._delay=i.delay||0,this.time=this._duration+this._delay}_onFinish(){this._finished||(this._finished=!0,this._onDoneFns.forEach(t=>t()),this._onDoneFns=[])}init(){this._buildPlayer(),this._preparePlayerBeforeStart()}_buildPlayer(){if(this._initialized)return;this._initialized=!0;const t=this.keyframes;this.domPlayer=this._triggerWebAnimation(this.element,t,this.options),this._finalKeyframe=t.length?t[t.length-1]:{},this.domPlayer.addEventListener(\"finish\",()=>this._onFinish())}_preparePlayerBeforeStart(){this._delay?this._resetDomPlayerState():this.domPlayer.pause()}_triggerWebAnimation(t,e,i){return t.animate(e,i)}onStart(t){this._onStartFns.push(t)}onDone(t){this._onDoneFns.push(t)}onDestroy(t){this._onDestroyFns.push(t)}play(){this._buildPlayer(),this.hasStarted()||(this._onStartFns.forEach(t=>t()),this._onStartFns=[],this._started=!0,this._specialStyles&&this._specialStyles.start()),this.domPlayer.play()}pause(){this.init(),this.domPlayer.pause()}finish(){this.init(),this._specialStyles&&this._specialStyles.finish(),this._onFinish(),this.domPlayer.finish()}reset(){this._resetDomPlayerState(),this._destroyed=!1,this._finished=!1,this._started=!1}_resetDomPlayerState(){this.domPlayer&&this.domPlayer.cancel()}restart(){this.reset(),this.play()}hasStarted(){return this._started}destroy(){this._destroyed||(this._destroyed=!0,this._resetDomPlayerState(),this._onFinish(),this._specialStyles&&this._specialStyles.destroy(),this._onDestroyFns.forEach(t=>t()),this._onDestroyFns=[])}setPosition(t){void 0===this.domPlayer&&this.init(),this.domPlayer.currentTime=t*this.time}getPosition(){return this.domPlayer.currentTime/this.time}get totalTime(){return this._delay+this._duration}beforeDestroy(){const t={};if(this.hasStarted()){const e=this._finalKeyframe;Object.keys(e).forEach(i=>{\"offset\"!=i&&(t[i]=this._finished?e[i]:fM(this.element,i))})}this.currentSnapshot=t}triggerCallback(t){const e=\"start\"==t?this._onStartFns:this._onDoneFns;e.forEach(i=>i()),e.length=0}}class Mj{validateStyleProperty(t){return rM(t)}matchesElement(t,e){return!1}containsElement(t,e){return sM(t,e)}getParentElement(t){return Qf(t)}query(t,e,i){return oM(t,e,i)}computeStyle(t,e,i){return window.getComputedStyle(t)[e]}animate(t,e,i,r,s,o=[]){const l={duration:i,delay:r,fill:0==r?\"both\":\"forwards\"};s&&(l.easing=s);const c={},d=o.filter(h=>h instanceof TM);(function kH(n,t){return 0===n||0===t})(i,r)&&d.forEach(h=>{let p=h.currentSnapshot;Object.keys(p).forEach(m=>c[m]=p[m])}),e=function TH(n,t,e){const i=Object.keys(e);if(i.length&&t.length){let s=t[0],o=[];if(i.forEach(a=>{s.hasOwnProperty(a)||o.push(a),s[a]=e[a]}),o.length)for(var r=1;r<t.length;r++){let a=t[r];o.forEach(function(l){a[l]=fM(n,l)})}}return t}(t,e=e.map(h=>rr(h,!1)),c);const u=function Cj(n,t){let e=null,i=null;return Array.isArray(t)&&t.length?(e=pm(t[0]),t.length>1&&(i=pm(t[t.length-1]))):t&&(e=pm(t)),e||i?new Dj(n,e,i):null}(t,e);return new TM(t,e,l,u)}}let xj=(()=>{class n extends Yw{constructor(e,i){super(),this._nextAnimationId=0,this._renderer=e.createRenderer(i.body,{id:\"0\",encapsulation:Ln.None,styles:[],data:{animation:[]}})}build(e){const i=this._nextAnimationId.toString();this._nextAnimationId++;const r=Array.isArray(e)?Qw(e):e;return AM(this._renderer,null,i,\"register\",[r]),new Ej(i,this._renderer)}}return n.\\u0275fac=function(e){return new(e||n)(y(da),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class Ej extends class V2{}{constructor(t,e){super(),this._id=t,this._renderer=e}create(t,e){return new Sj(this._id,t,e||{},this._renderer)}}class Sj{constructor(t,e,i,r){this.id=t,this.element=e,this._renderer=r,this.parentPlayer=null,this._started=!1,this.totalTime=0,this._command(\"create\",i)}_listen(t,e){return this._renderer.listen(this.element,`@@${this.id}:${t}`,e)}_command(t,...e){return AM(this._renderer,this.element,this.id,t,e)}onDone(t){this._listen(\"done\",t)}onStart(t){this._listen(\"start\",t)}onDestroy(t){this._listen(\"destroy\",t)}init(){this._command(\"init\")}hasStarted(){return this._started}play(){this._command(\"play\"),this._started=!0}pause(){this._command(\"pause\")}restart(){this._command(\"restart\")}finish(){this._command(\"finish\")}destroy(){this._command(\"destroy\")}reset(){this._command(\"reset\"),this._started=!1}setPosition(t){this._command(\"setPosition\",t)}getPosition(){var t,e;return null!==(e=null===(t=this._renderer.engine.players[+this.id])||void 0===t?void 0:t.getPosition())&&void 0!==e?e:0}}function AM(n,t,e,i,r){return n.setProperty(t,`@@${e}:${i}`,r)}const IM=\"@.disabled\";let kj=(()=>{class n{constructor(e,i,r){this.delegate=e,this.engine=i,this._zone=r,this._currentId=0,this._microtaskId=1,this._animationCallbacksBuffer=[],this._rendererCache=new Map,this._cdRecurDepth=0,this.promise=Promise.resolve(0),i.onRemovalComplete=(s,o)=>{const a=null==o?void 0:o.parentNode(s);a&&o.removeChild(a,s)}}createRenderer(e,i){const s=this.delegate.createRenderer(e,i);if(!(e&&i&&i.data&&i.data.animation)){let d=this._rendererCache.get(s);return d||(d=new RM(\"\",s,this.engine),this._rendererCache.set(s,d)),d}const o=i.id,a=i.id+\"-\"+this._currentId;this._currentId++,this.engine.register(a,e);const l=d=>{Array.isArray(d)?d.forEach(l):this.engine.registerTrigger(o,a,e,d.name,d)};return i.data.animation.forEach(l),new Tj(this,a,s,this.engine)}begin(){this._cdRecurDepth++,this.delegate.begin&&this.delegate.begin()}_scheduleCountTask(){this.promise.then(()=>{this._microtaskId++})}scheduleListenerCallback(e,i,r){e>=0&&e<this._microtaskId?this._zone.run(()=>i(r)):(0==this._animationCallbacksBuffer.length&&Promise.resolve(null).then(()=>{this._zone.run(()=>{this._animationCallbacksBuffer.forEach(s=>{const[o,a]=s;o(a)}),this._animationCallbacksBuffer=[]})}),this._animationCallbacksBuffer.push([i,r]))}end(){this._cdRecurDepth--,0==this._cdRecurDepth&&this._zone.runOutsideAngular(()=>{this._scheduleCountTask(),this.engine.flush(this._microtaskId)}),this.delegate.end&&this.delegate.end()}whenRenderingDone(){return this.engine.whenRenderingDone()}}return n.\\u0275fac=function(e){return new(e||n)(y(da),y(bd),y(ne))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class RM{constructor(t,e,i){this.namespaceId=t,this.delegate=e,this.engine=i,this.destroyNode=this.delegate.destroyNode?r=>e.destroyNode(r):null}get data(){return this.delegate.data}destroy(){this.engine.destroy(this.namespaceId,this.delegate),this.delegate.destroy()}createElement(t,e){return this.delegate.createElement(t,e)}createComment(t){return this.delegate.createComment(t)}createText(t){return this.delegate.createText(t)}appendChild(t,e){this.delegate.appendChild(t,e),this.engine.onInsert(this.namespaceId,e,t,!1)}insertBefore(t,e,i,r=!0){this.delegate.insertBefore(t,e,i),this.engine.onInsert(this.namespaceId,e,t,r)}removeChild(t,e,i){this.engine.onRemove(this.namespaceId,e,this.delegate,i)}selectRootElement(t,e){return this.delegate.selectRootElement(t,e)}parentNode(t){return this.delegate.parentNode(t)}nextSibling(t){return this.delegate.nextSibling(t)}setAttribute(t,e,i,r){this.delegate.setAttribute(t,e,i,r)}removeAttribute(t,e,i){this.delegate.removeAttribute(t,e,i)}addClass(t,e){this.delegate.addClass(t,e)}removeClass(t,e){this.delegate.removeClass(t,e)}setStyle(t,e,i,r){this.delegate.setStyle(t,e,i,r)}removeStyle(t,e,i){this.delegate.removeStyle(t,e,i)}setProperty(t,e,i){\"@\"==e.charAt(0)&&e==IM?this.disableAnimations(t,!!i):this.delegate.setProperty(t,e,i)}setValue(t,e){this.delegate.setValue(t,e)}listen(t,e,i){return this.delegate.listen(t,e,i)}disableAnimations(t,e){this.engine.disableAnimations(t,e)}}class Tj extends RM{constructor(t,e,i,r){super(e,i,r),this.factory=t,this.namespaceId=e}setProperty(t,e,i){\"@\"==e.charAt(0)?\".\"==e.charAt(1)&&e==IM?this.disableAnimations(t,i=void 0===i||!!i):this.engine.process(this.namespaceId,t,e.substr(1),i):this.delegate.setProperty(t,e,i)}listen(t,e,i){if(\"@\"==e.charAt(0)){const r=function Aj(n){switch(n){case\"body\":return document.body;case\"document\":return document;case\"window\":return window;default:return n}}(t);let s=e.substr(1),o=\"\";return\"@\"!=s.charAt(0)&&([s,o]=function Ij(n){const t=n.indexOf(\".\");return[n.substring(0,t),n.substr(t+1)]}(s)),this.engine.listen(this.namespaceId,r,s,o,a=>{this.factory.scheduleListenerCallback(a._data||-1,i,a)})}return this.delegate.listen(t,e,i)}}let Rj=(()=>{class n extends bd{constructor(e,i,r){super(e.body,i,r)}ngOnDestroy(){this.flush()}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(Kf),y(am))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const Rn=new b(\"AnimationModuleType\"),OM=[{provide:Yw,useClass:xj},{provide:am,useFactory:function Oj(){return new ZH}},{provide:bd,useClass:Rj},{provide:da,useFactory:function Pj(n,t,e){return new kj(n,t,e)},deps:[Vc,bd,ne]}],PM=[{provide:Kf,useFactory:()=>new Mj},{provide:Rn,useValue:\"BrowserAnimations\"},...OM],Fj=[{provide:Kf,useClass:aM},{provide:Rn,useValue:\"NoopAnimations\"},...OM];let Nj=(()=>{class n{static withConfig(e){return{ngModule:n,providers:e.disableAnimations?Fj:PM}}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:PM,imports:[FD]}),n})();let NM=(()=>{class n{constructor(e,i){this._renderer=e,this._elementRef=i,this.onChange=r=>{},this.onTouched=()=>{}}setProperty(e,i){this._renderer.setProperty(this._elementRef.nativeElement,e,i)}registerOnTouched(e){this.onTouched=e}registerOnChange(e){this.onChange=e}setDisabledState(e){this.setProperty(\"disabled\",e)}}return n.\\u0275fac=function(e){return new(e||n)(f(Ii),f(W))},n.\\u0275dir=C({type:n}),n})(),$r=(()=>{class n extends NM{}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275dir=C({type:n,features:[E]}),n})();const xt=new b(\"NgValueAccessor\"),Bj={provide:xt,useExisting:pe(()=>Dd),multi:!0},Hj=new b(\"CompositionEventMode\");let Dd=(()=>{class n extends NM{constructor(e,i,r){super(e,i),this._compositionMode=r,this._composing=!1,null==this._compositionMode&&(this._compositionMode=!function Vj(){const n=mi()?mi().getUserAgent():\"\";return/android (\\d+)/.test(n.toLowerCase())}())}writeValue(e){this.setProperty(\"value\",null==e?\"\":e)}_handleInput(e){(!this._compositionMode||this._compositionMode&&!this._composing)&&this.onChange(e)}_compositionStart(){this._composing=!0}_compositionEnd(e){this._composing=!1,this._compositionMode&&this.onChange(e)}}return n.\\u0275fac=function(e){return new(e||n)(f(Ii),f(W),f(Hj,8))},n.\\u0275dir=C({type:n,selectors:[[\"input\",\"formControlName\",\"\",3,\"type\",\"checkbox\"],[\"textarea\",\"formControlName\",\"\"],[\"input\",\"formControl\",\"\",3,\"type\",\"checkbox\"],[\"textarea\",\"formControl\",\"\"],[\"input\",\"ngModel\",\"\",3,\"type\",\"checkbox\"],[\"textarea\",\"ngModel\",\"\"],[\"\",\"ngDefaultControl\",\"\"]],hostBindings:function(e,i){1&e&&J(\"input\",function(s){return i._handleInput(s.target.value)})(\"blur\",function(){return i.onTouched()})(\"compositionstart\",function(){return i._compositionStart()})(\"compositionend\",function(s){return i._compositionEnd(s.target.value)})},features:[L([Bj]),E]}),n})();function sr(n){return null==n||0===n.length}function BM(n){return null!=n&&\"number\"==typeof n.length}const Dt=new b(\"NgValidators\"),or=new b(\"NgAsyncValidators\"),jj=/^(?=.{1,254}$)(?=.{1,64}@)[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;class yi{static min(t){return function VM(n){return t=>{if(sr(t.value)||sr(n))return null;const e=parseFloat(t.value);return!isNaN(e)&&e<n?{min:{min:n,actual:t.value}}:null}}(t)}static max(t){return function HM(n){return t=>{if(sr(t.value)||sr(n))return null;const e=parseFloat(t.value);return!isNaN(e)&&e>n?{max:{max:n,actual:t.value}}:null}}(t)}static required(t){return function jM(n){return sr(n.value)?{required:!0}:null}(t)}static requiredTrue(t){return function zM(n){return!0===n.value?null:{required:!0}}(t)}static email(t){return function UM(n){return sr(n.value)||jj.test(n.value)?null:{email:!0}}(t)}static minLength(t){return function $M(n){return t=>sr(t.value)||!BM(t.value)?null:t.value.length<n?{minlength:{requiredLength:n,actualLength:t.value.length}}:null}(t)}static maxLength(t){return function GM(n){return t=>BM(t.value)&&t.value.length>n?{maxlength:{requiredLength:n,actualLength:t.value.length}}:null}(t)}static pattern(t){return function WM(n){if(!n)return wd;let t,e;return\"string\"==typeof n?(e=\"\",\"^\"!==n.charAt(0)&&(e+=\"^\"),e+=n,\"$\"!==n.charAt(n.length-1)&&(e+=\"$\"),t=new RegExp(e)):(e=n.toString(),t=n),i=>{if(sr(i.value))return null;const r=i.value;return t.test(r)?null:{pattern:{requiredPattern:e,actualValue:r}}}}(t)}static nullValidator(t){return null}static compose(t){return XM(t)}static composeAsync(t){return JM(t)}}function wd(n){return null}function qM(n){return null!=n}function YM(n){const t=ra(n)?mt(n):n;return up(t),t}function QM(n){let t={};return n.forEach(e=>{t=null!=e?Object.assign(Object.assign({},t),e):t}),0===Object.keys(t).length?null:t}function KM(n,t){return t.map(e=>e(n))}function ZM(n){return n.map(t=>function zj(n){return!n.validate}(t)?t:e=>t.validate(e))}function XM(n){if(!n)return null;const t=n.filter(qM);return 0==t.length?null:function(e){return QM(KM(e,t))}}function fm(n){return null!=n?XM(ZM(n)):null}function JM(n){if(!n)return null;const t=n.filter(qM);return 0==t.length?null:function(e){return function FM(...n){const t=b_(n),{args:e,keys:i}=VD(n),r=new Ve(s=>{const{length:o}=e;if(!o)return void s.complete();const a=new Array(o);let l=o,c=o;for(let d=0;d<o;d++){let u=!1;Jt(e[d]).subscribe(Ue(s,h=>{u||(u=!0,c--),a[d]=h},()=>l--,void 0,()=>{(!l||!u)&&(c||s.next(i?HD(i,a):a),s.complete())}))}});return t?r.pipe(bf(t)):r}(KM(e,t).map(YM)).pipe(ue(QM))}}function mm(n){return null!=n?JM(ZM(n)):null}function ex(n,t){return null===n?[t]:Array.isArray(n)?[...n,t]:[n,t]}function tx(n){return n._rawValidators}function nx(n){return n._rawAsyncValidators}function gm(n){return n?Array.isArray(n)?n:[n]:[]}function Md(n,t){return Array.isArray(n)?n.includes(t):n===t}function ix(n,t){const e=gm(t);return gm(n).forEach(r=>{Md(e,r)||e.push(r)}),e}function rx(n,t){return gm(t).filter(e=>!Md(n,e))}class sx{constructor(){this._rawValidators=[],this._rawAsyncValidators=[],this._onDestroyCallbacks=[]}get value(){return this.control?this.control.value:null}get valid(){return this.control?this.control.valid:null}get invalid(){return this.control?this.control.invalid:null}get pending(){return this.control?this.control.pending:null}get disabled(){return this.control?this.control.disabled:null}get enabled(){return this.control?this.control.enabled:null}get errors(){return this.control?this.control.errors:null}get pristine(){return this.control?this.control.pristine:null}get dirty(){return this.control?this.control.dirty:null}get touched(){return this.control?this.control.touched:null}get status(){return this.control?this.control.status:null}get untouched(){return this.control?this.control.untouched:null}get statusChanges(){return this.control?this.control.statusChanges:null}get valueChanges(){return this.control?this.control.valueChanges:null}get path(){return null}_setValidators(t){this._rawValidators=t||[],this._composedValidatorFn=fm(this._rawValidators)}_setAsyncValidators(t){this._rawAsyncValidators=t||[],this._composedAsyncValidatorFn=mm(this._rawAsyncValidators)}get validator(){return this._composedValidatorFn||null}get asyncValidator(){return this._composedAsyncValidatorFn||null}_registerOnDestroy(t){this._onDestroyCallbacks.push(t)}_invokeOnDestroyCallbacks(){this._onDestroyCallbacks.forEach(t=>t()),this._onDestroyCallbacks=[]}reset(t){this.control&&this.control.reset(t)}hasError(t,e){return!!this.control&&this.control.hasError(t,e)}getError(t,e){return this.control?this.control.getError(t,e):null}}class Jn extends sx{constructor(){super(...arguments),this._parent=null,this.name=null,this.valueAccessor=null}}class Wt extends sx{get formDirective(){return null}get path(){return null}}let ax=(()=>{class n extends class ox{constructor(t){this._cd=t}is(t){var e,i,r;return\"submitted\"===t?!!(null===(e=this._cd)||void 0===e?void 0:e.submitted):!!(null===(r=null===(i=this._cd)||void 0===i?void 0:i.control)||void 0===r?void 0:r[t])}}{constructor(e){super(e)}}return n.\\u0275fac=function(e){return new(e||n)(f(Jn,2))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"formControlName\",\"\"],[\"\",\"ngModel\",\"\"],[\"\",\"formControl\",\"\"]],hostVars:14,hostBindings:function(e,i){2&e&&Ae(\"ng-untouched\",i.is(\"untouched\"))(\"ng-touched\",i.is(\"touched\"))(\"ng-pristine\",i.is(\"pristine\"))(\"ng-dirty\",i.is(\"dirty\"))(\"ng-valid\",i.is(\"valid\"))(\"ng-invalid\",i.is(\"invalid\"))(\"ng-pending\",i.is(\"pending\"))},features:[E]}),n})();function Ha(n,t){ym(n,t),t.valueAccessor.writeValue(n.value),function Zj(n,t){t.valueAccessor.registerOnChange(e=>{n._pendingValue=e,n._pendingChange=!0,n._pendingDirty=!0,\"change\"===n.updateOn&&cx(n,t)})}(n,t),function Jj(n,t){const e=(i,r)=>{t.valueAccessor.writeValue(i),r&&t.viewToModelUpdate(i)};n.registerOnChange(e),t._registerOnDestroy(()=>{n._unregisterOnChange(e)})}(n,t),function Xj(n,t){t.valueAccessor.registerOnTouched(()=>{n._pendingTouched=!0,\"blur\"===n.updateOn&&n._pendingChange&&cx(n,t),\"submit\"!==n.updateOn&&n.markAsTouched()})}(n,t),function Kj(n,t){if(t.valueAccessor.setDisabledState){const e=i=>{t.valueAccessor.setDisabledState(i)};n.registerOnDisabledChange(e),t._registerOnDestroy(()=>{n._unregisterOnDisabledChange(e)})}}(n,t)}function Sd(n,t,e=!0){const i=()=>{};t.valueAccessor&&(t.valueAccessor.registerOnChange(i),t.valueAccessor.registerOnTouched(i)),Td(n,t),n&&(t._invokeOnDestroyCallbacks(),n._registerOnCollectionChange(()=>{}))}function kd(n,t){n.forEach(e=>{e.registerOnValidatorChange&&e.registerOnValidatorChange(t)})}function ym(n,t){const e=tx(n);null!==t.validator?n.setValidators(ex(e,t.validator)):\"function\"==typeof e&&n.setValidators([e]);const i=nx(n);null!==t.asyncValidator?n.setAsyncValidators(ex(i,t.asyncValidator)):\"function\"==typeof i&&n.setAsyncValidators([i]);const r=()=>n.updateValueAndValidity();kd(t._rawValidators,r),kd(t._rawAsyncValidators,r)}function Td(n,t){let e=!1;if(null!==n){if(null!==t.validator){const r=tx(n);if(Array.isArray(r)&&r.length>0){const s=r.filter(o=>o!==t.validator);s.length!==r.length&&(e=!0,n.setValidators(s))}}if(null!==t.asyncValidator){const r=nx(n);if(Array.isArray(r)&&r.length>0){const s=r.filter(o=>o!==t.asyncValidator);s.length!==r.length&&(e=!0,n.setAsyncValidators(s))}}}const i=()=>{};return kd(t._rawValidators,i),kd(t._rawAsyncValidators,i),e}function cx(n,t){n._pendingDirty&&n.markAsDirty(),n.setValue(n._pendingValue,{emitModelToViewChange:!1}),t.viewToModelUpdate(n._pendingValue),n._pendingChange=!1}function dx(n,t){ym(n,t)}function hx(n,t){n._syncPendingControls(),t.forEach(e=>{const i=e.control;\"submit\"===i.updateOn&&i._pendingChange&&(e.viewToModelUpdate(i._pendingValue),i._pendingChange=!1)})}function Dm(n,t){const e=n.indexOf(t);e>-1&&n.splice(e,1)}const ja=\"VALID\",Ad=\"INVALID\",so=\"PENDING\",za=\"DISABLED\";function Mm(n){return(Id(n)?n.validators:n)||null}function px(n){return Array.isArray(n)?fm(n):n||null}function xm(n,t){return(Id(t)?t.asyncValidators:n)||null}function fx(n){return Array.isArray(n)?mm(n):n||null}function Id(n){return null!=n&&!Array.isArray(n)&&\"object\"==typeof n}const mx=n=>n instanceof Rd,Em=n=>n instanceof km;function gx(n){return mx(n)?n.value:n.getRawValue()}function _x(n,t){const e=Em(n),i=n.controls;if(!(e?Object.keys(i):i).length)throw new H(1e3,\"\");if(!i[t])throw new H(1001,\"\")}function vx(n,t){Em(n),n._forEachChild((i,r)=>{if(void 0===t[r])throw new H(1002,\"\")})}class Sm{constructor(t,e){this._pendingDirty=!1,this._hasOwnPendingAsyncValidator=!1,this._pendingTouched=!1,this._onCollectionChange=()=>{},this._parent=null,this.pristine=!0,this.touched=!1,this._onDisabledChange=[],this._rawValidators=t,this._rawAsyncValidators=e,this._composedValidatorFn=px(this._rawValidators),this._composedAsyncValidatorFn=fx(this._rawAsyncValidators)}get validator(){return this._composedValidatorFn}set validator(t){this._rawValidators=this._composedValidatorFn=t}get asyncValidator(){return this._composedAsyncValidatorFn}set asyncValidator(t){this._rawAsyncValidators=this._composedAsyncValidatorFn=t}get parent(){return this._parent}get valid(){return this.status===ja}get invalid(){return this.status===Ad}get pending(){return this.status==so}get disabled(){return this.status===za}get enabled(){return this.status!==za}get dirty(){return!this.pristine}get untouched(){return!this.touched}get updateOn(){return this._updateOn?this._updateOn:this.parent?this.parent.updateOn:\"change\"}setValidators(t){this._rawValidators=t,this._composedValidatorFn=px(t)}setAsyncValidators(t){this._rawAsyncValidators=t,this._composedAsyncValidatorFn=fx(t)}addValidators(t){this.setValidators(ix(t,this._rawValidators))}addAsyncValidators(t){this.setAsyncValidators(ix(t,this._rawAsyncValidators))}removeValidators(t){this.setValidators(rx(t,this._rawValidators))}removeAsyncValidators(t){this.setAsyncValidators(rx(t,this._rawAsyncValidators))}hasValidator(t){return Md(this._rawValidators,t)}hasAsyncValidator(t){return Md(this._rawAsyncValidators,t)}clearValidators(){this.validator=null}clearAsyncValidators(){this.asyncValidator=null}markAsTouched(t={}){this.touched=!0,this._parent&&!t.onlySelf&&this._parent.markAsTouched(t)}markAllAsTouched(){this.markAsTouched({onlySelf:!0}),this._forEachChild(t=>t.markAllAsTouched())}markAsUntouched(t={}){this.touched=!1,this._pendingTouched=!1,this._forEachChild(e=>{e.markAsUntouched({onlySelf:!0})}),this._parent&&!t.onlySelf&&this._parent._updateTouched(t)}markAsDirty(t={}){this.pristine=!1,this._parent&&!t.onlySelf&&this._parent.markAsDirty(t)}markAsPristine(t={}){this.pristine=!0,this._pendingDirty=!1,this._forEachChild(e=>{e.markAsPristine({onlySelf:!0})}),this._parent&&!t.onlySelf&&this._parent._updatePristine(t)}markAsPending(t={}){this.status=so,!1!==t.emitEvent&&this.statusChanges.emit(this.status),this._parent&&!t.onlySelf&&this._parent.markAsPending(t)}disable(t={}){const e=this._parentMarkedDirty(t.onlySelf);this.status=za,this.errors=null,this._forEachChild(i=>{i.disable(Object.assign(Object.assign({},t),{onlySelf:!0}))}),this._updateValue(),!1!==t.emitEvent&&(this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._updateAncestors(Object.assign(Object.assign({},t),{skipPristineCheck:e})),this._onDisabledChange.forEach(i=>i(!0))}enable(t={}){const e=this._parentMarkedDirty(t.onlySelf);this.status=ja,this._forEachChild(i=>{i.enable(Object.assign(Object.assign({},t),{onlySelf:!0}))}),this.updateValueAndValidity({onlySelf:!0,emitEvent:t.emitEvent}),this._updateAncestors(Object.assign(Object.assign({},t),{skipPristineCheck:e})),this._onDisabledChange.forEach(i=>i(!1))}_updateAncestors(t){this._parent&&!t.onlySelf&&(this._parent.updateValueAndValidity(t),t.skipPristineCheck||this._parent._updatePristine(),this._parent._updateTouched())}setParent(t){this._parent=t}updateValueAndValidity(t={}){this._setInitialStatus(),this._updateValue(),this.enabled&&(this._cancelExistingSubscription(),this.errors=this._runValidator(),this.status=this._calculateStatus(),(this.status===ja||this.status===so)&&this._runAsyncValidator(t.emitEvent)),!1!==t.emitEvent&&(this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._parent&&!t.onlySelf&&this._parent.updateValueAndValidity(t)}_updateTreeValidity(t={emitEvent:!0}){this._forEachChild(e=>e._updateTreeValidity(t)),this.updateValueAndValidity({onlySelf:!0,emitEvent:t.emitEvent})}_setInitialStatus(){this.status=this._allControlsDisabled()?za:ja}_runValidator(){return this.validator?this.validator(this):null}_runAsyncValidator(t){if(this.asyncValidator){this.status=so,this._hasOwnPendingAsyncValidator=!0;const e=YM(this.asyncValidator(this));this._asyncValidationSubscription=e.subscribe(i=>{this._hasOwnPendingAsyncValidator=!1,this.setErrors(i,{emitEvent:t})})}}_cancelExistingSubscription(){this._asyncValidationSubscription&&(this._asyncValidationSubscription.unsubscribe(),this._hasOwnPendingAsyncValidator=!1)}setErrors(t,e={}){this.errors=t,this._updateControlsErrors(!1!==e.emitEvent)}get(t){return function iz(n,t,e){if(null==t||(Array.isArray(t)||(t=t.split(e)),Array.isArray(t)&&0===t.length))return null;let i=n;return t.forEach(r=>{i=Em(i)?i.controls.hasOwnProperty(r)?i.controls[r]:null:(n=>n instanceof sz)(i)&&i.at(r)||null}),i}(this,t,\".\")}getError(t,e){const i=e?this.get(e):this;return i&&i.errors?i.errors[t]:null}hasError(t,e){return!!this.getError(t,e)}get root(){let t=this;for(;t._parent;)t=t._parent;return t}_updateControlsErrors(t){this.status=this._calculateStatus(),t&&this.statusChanges.emit(this.status),this._parent&&this._parent._updateControlsErrors(t)}_initObservables(){this.valueChanges=new $,this.statusChanges=new $}_calculateStatus(){return this._allControlsDisabled()?za:this.errors?Ad:this._hasOwnPendingAsyncValidator||this._anyControlsHaveStatus(so)?so:this._anyControlsHaveStatus(Ad)?Ad:ja}_anyControlsHaveStatus(t){return this._anyControls(e=>e.status===t)}_anyControlsDirty(){return this._anyControls(t=>t.dirty)}_anyControlsTouched(){return this._anyControls(t=>t.touched)}_updatePristine(t={}){this.pristine=!this._anyControlsDirty(),this._parent&&!t.onlySelf&&this._parent._updatePristine(t)}_updateTouched(t={}){this.touched=this._anyControlsTouched(),this._parent&&!t.onlySelf&&this._parent._updateTouched(t)}_isBoxedValue(t){return\"object\"==typeof t&&null!==t&&2===Object.keys(t).length&&\"value\"in t&&\"disabled\"in t}_registerOnCollectionChange(t){this._onCollectionChange=t}_setUpdateStrategy(t){Id(t)&&null!=t.updateOn&&(this._updateOn=t.updateOn)}_parentMarkedDirty(t){return!t&&!(!this._parent||!this._parent.dirty)&&!this._parent._anyControlsDirty()}}class Rd extends Sm{constructor(t=null,e,i){super(Mm(e),xm(i,e)),this.defaultValue=null,this._onChange=[],this._pendingChange=!1,this._applyFormState(t),this._setUpdateStrategy(e),this._initObservables(),this.updateValueAndValidity({onlySelf:!0,emitEvent:!!this.asyncValidator}),Id(e)&&e.initialValueIsDefault&&(this.defaultValue=this._isBoxedValue(t)?t.value:t)}setValue(t,e={}){this.value=this._pendingValue=t,this._onChange.length&&!1!==e.emitModelToViewChange&&this._onChange.forEach(i=>i(this.value,!1!==e.emitViewToModelChange)),this.updateValueAndValidity(e)}patchValue(t,e={}){this.setValue(t,e)}reset(t=this.defaultValue,e={}){this._applyFormState(t),this.markAsPristine(e),this.markAsUntouched(e),this.setValue(this.value,e),this._pendingChange=!1}_updateValue(){}_anyControls(t){return!1}_allControlsDisabled(){return this.disabled}registerOnChange(t){this._onChange.push(t)}_unregisterOnChange(t){Dm(this._onChange,t)}registerOnDisabledChange(t){this._onDisabledChange.push(t)}_unregisterOnDisabledChange(t){Dm(this._onDisabledChange,t)}_forEachChild(t){}_syncPendingControls(){return!(\"submit\"!==this.updateOn||(this._pendingDirty&&this.markAsDirty(),this._pendingTouched&&this.markAsTouched(),!this._pendingChange)||(this.setValue(this._pendingValue,{onlySelf:!0,emitModelToViewChange:!1}),0))}_applyFormState(t){this._isBoxedValue(t)?(this.value=this._pendingValue=t.value,t.disabled?this.disable({onlySelf:!0,emitEvent:!1}):this.enable({onlySelf:!0,emitEvent:!1})):this.value=this._pendingValue=t}}class km extends Sm{constructor(t,e,i){super(Mm(e),xm(i,e)),this.controls=t,this._initObservables(),this._setUpdateStrategy(e),this._setUpControls(),this.updateValueAndValidity({onlySelf:!0,emitEvent:!!this.asyncValidator})}registerControl(t,e){return this.controls[t]?this.controls[t]:(this.controls[t]=e,e.setParent(this),e._registerOnCollectionChange(this._onCollectionChange),e)}addControl(t,e,i={}){this.registerControl(t,e),this.updateValueAndValidity({emitEvent:i.emitEvent}),this._onCollectionChange()}removeControl(t,e={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),delete this.controls[t],this.updateValueAndValidity({emitEvent:e.emitEvent}),this._onCollectionChange()}setControl(t,e,i={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),delete this.controls[t],e&&this.registerControl(t,e),this.updateValueAndValidity({emitEvent:i.emitEvent}),this._onCollectionChange()}contains(t){return this.controls.hasOwnProperty(t)&&this.controls[t].enabled}setValue(t,e={}){vx(this,t),Object.keys(t).forEach(i=>{_x(this,i),this.controls[i].setValue(t[i],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)}patchValue(t,e={}){null!=t&&(Object.keys(t).forEach(i=>{this.controls[i]&&this.controls[i].patchValue(t[i],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e))}reset(t={},e={}){this._forEachChild((i,r)=>{i.reset(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this._updatePristine(e),this._updateTouched(e),this.updateValueAndValidity(e)}getRawValue(){return this._reduceChildren({},(t,e,i)=>(t[i]=gx(e),t))}_syncPendingControls(){let t=this._reduceChildren(!1,(e,i)=>!!i._syncPendingControls()||e);return t&&this.updateValueAndValidity({onlySelf:!0}),t}_forEachChild(t){Object.keys(this.controls).forEach(e=>{const i=this.controls[e];i&&t(i,e)})}_setUpControls(){this._forEachChild(t=>{t.setParent(this),t._registerOnCollectionChange(this._onCollectionChange)})}_updateValue(){this.value=this._reduceValue()}_anyControls(t){for(const e of Object.keys(this.controls)){const i=this.controls[e];if(this.contains(e)&&t(i))return!0}return!1}_reduceValue(){return this._reduceChildren({},(t,e,i)=>((e.enabled||this.disabled)&&(t[i]=e.value),t))}_reduceChildren(t,e){let i=t;return this._forEachChild((r,s)=>{i=e(i,r,s)}),i}_allControlsDisabled(){for(const t of Object.keys(this.controls))if(this.controls[t].enabled)return!1;return Object.keys(this.controls).length>0||this.disabled}}class sz extends Sm{constructor(t,e,i){super(Mm(e),xm(i,e)),this.controls=t,this._initObservables(),this._setUpdateStrategy(e),this._setUpControls(),this.updateValueAndValidity({onlySelf:!0,emitEvent:!!this.asyncValidator})}at(t){return this.controls[t]}push(t,e={}){this.controls.push(t),this._registerControl(t),this.updateValueAndValidity({emitEvent:e.emitEvent}),this._onCollectionChange()}insert(t,e,i={}){this.controls.splice(t,0,e),this._registerControl(e),this.updateValueAndValidity({emitEvent:i.emitEvent})}removeAt(t,e={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),this.controls.splice(t,1),this.updateValueAndValidity({emitEvent:e.emitEvent})}setControl(t,e,i={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),this.controls.splice(t,1),e&&(this.controls.splice(t,0,e),this._registerControl(e)),this.updateValueAndValidity({emitEvent:i.emitEvent}),this._onCollectionChange()}get length(){return this.controls.length}setValue(t,e={}){vx(this,t),t.forEach((i,r)=>{_x(this,r),this.at(r).setValue(i,{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)}patchValue(t,e={}){null!=t&&(t.forEach((i,r)=>{this.at(r)&&this.at(r).patchValue(i,{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e))}reset(t=[],e={}){this._forEachChild((i,r)=>{i.reset(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this._updatePristine(e),this._updateTouched(e),this.updateValueAndValidity(e)}getRawValue(){return this.controls.map(t=>gx(t))}clear(t={}){this.controls.length<1||(this._forEachChild(e=>e._registerOnCollectionChange(()=>{})),this.controls.splice(0),this.updateValueAndValidity({emitEvent:t.emitEvent}))}_syncPendingControls(){let t=this.controls.reduce((e,i)=>!!i._syncPendingControls()||e,!1);return t&&this.updateValueAndValidity({onlySelf:!0}),t}_forEachChild(t){this.controls.forEach((e,i)=>{t(e,i)})}_updateValue(){this.value=this.controls.filter(t=>t.enabled||this.disabled).map(t=>t.value)}_anyControls(t){return this.controls.some(e=>e.enabled&&t(e))}_setUpControls(){this._forEachChild(t=>this._registerControl(t))}_allControlsDisabled(){for(const t of this.controls)if(t.enabled)return!1;return this.controls.length>0||this.disabled}_registerControl(t){t.setParent(this),t._registerOnCollectionChange(this._onCollectionChange)}}const oz={provide:Wt,useExisting:pe(()=>oo)},Ua=(()=>Promise.resolve(null))();let oo=(()=>{class n extends Wt{constructor(e,i){super(),this.submitted=!1,this._directives=new Set,this.ngSubmit=new $,this.form=new km({},fm(e),mm(i))}ngAfterViewInit(){this._setUpdateStrategy()}get formDirective(){return this}get control(){return this.form}get path(){return[]}get controls(){return this.form.controls}addControl(e){Ua.then(()=>{const i=this._findContainer(e.path);e.control=i.registerControl(e.name,e.control),Ha(e.control,e),e.control.updateValueAndValidity({emitEvent:!1}),this._directives.add(e)})}getControl(e){return this.form.get(e.path)}removeControl(e){Ua.then(()=>{const i=this._findContainer(e.path);i&&i.removeControl(e.name),this._directives.delete(e)})}addFormGroup(e){Ua.then(()=>{const i=this._findContainer(e.path),r=new km({});dx(r,e),i.registerControl(e.name,r),r.updateValueAndValidity({emitEvent:!1})})}removeFormGroup(e){Ua.then(()=>{const i=this._findContainer(e.path);i&&i.removeControl(e.name)})}getFormGroup(e){return this.form.get(e.path)}updateModel(e,i){Ua.then(()=>{this.form.get(e.path).setValue(i)})}setValue(e){this.control.setValue(e)}onSubmit(e){return this.submitted=!0,hx(this.form,this._directives),this.ngSubmit.emit(e),!1}onReset(){this.resetForm()}resetForm(e){this.form.reset(e),this.submitted=!1}_setUpdateStrategy(){this.options&&null!=this.options.updateOn&&(this.form._updateOn=this.options.updateOn)}_findContainer(e){return e.pop(),e.length?this.form.get(e):this.form}}return n.\\u0275fac=function(e){return new(e||n)(f(Dt,10),f(or,10))},n.\\u0275dir=C({type:n,selectors:[[\"form\",3,\"ngNoForm\",\"\",3,\"formGroup\",\"\"],[\"ng-form\"],[\"\",\"ngForm\",\"\"]],hostBindings:function(e,i){1&e&&J(\"submit\",function(s){return i.onSubmit(s)})(\"reset\",function(){return i.onReset()})},inputs:{options:[\"ngFormOptions\",\"options\"]},outputs:{ngSubmit:\"ngSubmit\"},exportAs:[\"ngForm\"],features:[L([oz]),E]}),n})();const dz={provide:xt,useExisting:pe(()=>Tm),multi:!0};let Tm=(()=>{class n extends $r{writeValue(e){this.setProperty(\"value\",null==e?\"\":e)}registerOnChange(e){this.onChange=i=>{e(\"\"==i?null:parseFloat(i))}}}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275dir=C({type:n,selectors:[[\"input\",\"type\",\"number\",\"formControlName\",\"\"],[\"input\",\"type\",\"number\",\"formControl\",\"\"],[\"input\",\"type\",\"number\",\"ngModel\",\"\"]],hostBindings:function(e,i){1&e&&J(\"input\",function(s){return i.onChange(s.target.value)})(\"blur\",function(){return i.onTouched()})},features:[L([dz]),E]}),n})(),wx=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const Am=new b(\"NgModelWithFormControlWarning\"),fz={provide:Jn,useExisting:pe(()=>Im)};let Im=(()=>{class n extends Jn{constructor(e,i,r,s){super(),this._ngModelWarningConfig=s,this.update=new $,this._ngModelWarningSent=!1,this._setValidators(e),this._setAsyncValidators(i),this.valueAccessor=function Cm(n,t){if(!t)return null;let e,i,r;return Array.isArray(t),t.forEach(s=>{s.constructor===Dd?e=s:function nz(n){return Object.getPrototypeOf(n.constructor)===$r}(s)?i=s:r=s}),r||i||e||null}(0,r)}set isDisabled(e){}ngOnChanges(e){if(this._isControlChanged(e)){const i=e.form.previousValue;i&&Sd(i,this,!1),Ha(this.form,this),this.control.disabled&&this.valueAccessor.setDisabledState&&this.valueAccessor.setDisabledState(!0),this.form.updateValueAndValidity({emitEvent:!1})}(function bm(n,t){if(!n.hasOwnProperty(\"model\"))return!1;const e=n.model;return!!e.isFirstChange()||!Object.is(t,e.currentValue)})(e,this.viewModel)&&(this.form.setValue(this.model),this.viewModel=this.model)}ngOnDestroy(){this.form&&Sd(this.form,this,!1)}get path(){return[]}get control(){return this.form}viewToModelUpdate(e){this.viewModel=e,this.update.emit(e)}_isControlChanged(e){return e.hasOwnProperty(\"form\")}}return n._ngModelWarningSentOnce=!1,n.\\u0275fac=function(e){return new(e||n)(f(Dt,10),f(or,10),f(xt,10),f(Am,8))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"formControl\",\"\"]],inputs:{form:[\"formControl\",\"form\"],isDisabled:[\"disabled\",\"isDisabled\"],model:[\"ngModel\",\"model\"]},outputs:{update:\"ngModelChange\"},exportAs:[\"ngForm\"],features:[L([fz]),E,Je]}),n})();const mz={provide:Wt,useExisting:pe(()=>ao)};let ao=(()=>{class n extends Wt{constructor(e,i){super(),this.validators=e,this.asyncValidators=i,this.submitted=!1,this._onCollectionChange=()=>this._updateDomValue(),this.directives=[],this.form=null,this.ngSubmit=new $,this._setValidators(e),this._setAsyncValidators(i)}ngOnChanges(e){this._checkFormPresent(),e.hasOwnProperty(\"form\")&&(this._updateValidators(),this._updateDomValue(),this._updateRegistrations(),this._oldForm=this.form)}ngOnDestroy(){this.form&&(Td(this.form,this),this.form._onCollectionChange===this._onCollectionChange&&this.form._registerOnCollectionChange(()=>{}))}get formDirective(){return this}get control(){return this.form}get path(){return[]}addControl(e){const i=this.form.get(e.path);return Ha(i,e),i.updateValueAndValidity({emitEvent:!1}),this.directives.push(e),i}getControl(e){return this.form.get(e.path)}removeControl(e){Sd(e.control||null,e,!1),Dm(this.directives,e)}addFormGroup(e){this._setUpFormContainer(e)}removeFormGroup(e){this._cleanUpFormContainer(e)}getFormGroup(e){return this.form.get(e.path)}addFormArray(e){this._setUpFormContainer(e)}removeFormArray(e){this._cleanUpFormContainer(e)}getFormArray(e){return this.form.get(e.path)}updateModel(e,i){this.form.get(e.path).setValue(i)}onSubmit(e){return this.submitted=!0,hx(this.form,this.directives),this.ngSubmit.emit(e),!1}onReset(){this.resetForm()}resetForm(e){this.form.reset(e),this.submitted=!1}_updateDomValue(){this.directives.forEach(e=>{const i=e.control,r=this.form.get(e.path);i!==r&&(Sd(i||null,e),mx(r)&&(Ha(r,e),e.control=r))}),this.form._updateTreeValidity({emitEvent:!1})}_setUpFormContainer(e){const i=this.form.get(e.path);dx(i,e),i.updateValueAndValidity({emitEvent:!1})}_cleanUpFormContainer(e){if(this.form){const i=this.form.get(e.path);i&&function ez(n,t){return Td(n,t)}(i,e)&&i.updateValueAndValidity({emitEvent:!1})}}_updateRegistrations(){this.form._registerOnCollectionChange(this._onCollectionChange),this._oldForm&&this._oldForm._registerOnCollectionChange(()=>{})}_updateValidators(){ym(this.form,this),this._oldForm&&Td(this._oldForm,this)}_checkFormPresent(){}}return n.\\u0275fac=function(e){return new(e||n)(f(Dt,10),f(or,10))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"formGroup\",\"\"]],hostBindings:function(e,i){1&e&&J(\"submit\",function(s){return i.onSubmit(s)})(\"reset\",function(){return i.onReset()})},inputs:{form:[\"formGroup\",\"form\"]},outputs:{ngSubmit:\"ngSubmit\"},exportAs:[\"ngForm\"],features:[L([mz]),E,Je]}),n})(),Bx=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[wx]]}),n})(),Pz=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[Bx]}),n})(),Fz=(()=>{class n{static withConfig(e){return{ngModule:n,providers:[{provide:Am,useValue:e.warnOnNgModelWithFormControl}]}}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[Bx]}),n})();const Nz=new b(\"cdk-dir-doc\",{providedIn:\"root\",factory:function Lz(){return Uo(ie)}}),Bz=/^(ar|ckb|dv|he|iw|fa|nqo|ps|sd|ug|ur|yi|.*[-_](Adlm|Arab|Hebr|Nkoo|Rohg|Thaa))(?!.*[-_](Latn|Cyrl)($|-|_))($|-|_)/i;let On=(()=>{class n{constructor(e){if(this.value=\"ltr\",this.change=new $,e){const r=e.documentElement?e.documentElement.dir:null;this.value=function Vz(n){const t=(null==n?void 0:n.toLowerCase())||\"\";return\"auto\"===t&&\"undefined\"!=typeof navigator&&(null==navigator?void 0:navigator.language)?Bz.test(navigator.language)?\"rtl\":\"ltr\":\"rtl\"===t?\"rtl\":\"ltr\"}((e.body?e.body.dir:null)||r||\"ltr\")}}ngOnDestroy(){this.change.complete()}}return n.\\u0275fac=function(e){return new(e||n)(y(Nz,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),lo=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const Lm=new Rr(\"13.3.0\");let Bm;try{Bm=\"undefined\"!=typeof Intl&&Intl.v8BreakIterator}catch(n){Bm=!1}let co,It=(()=>{class n{constructor(e){this._platformId=e,this.isBrowser=this._platformId?function OL(n){return n===wD}(this._platformId):\"object\"==typeof document&&!!document,this.EDGE=this.isBrowser&&/(edge)/i.test(navigator.userAgent),this.TRIDENT=this.isBrowser&&/(msie|trident)/i.test(navigator.userAgent),this.BLINK=this.isBrowser&&!(!window.chrome&&!Bm)&&\"undefined\"!=typeof CSS&&!this.EDGE&&!this.TRIDENT,this.WEBKIT=this.isBrowser&&/AppleWebKit/i.test(navigator.userAgent)&&!this.BLINK&&!this.EDGE&&!this.TRIDENT,this.IOS=this.isBrowser&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!(\"MSStream\"in window),this.FIREFOX=this.isBrowser&&/(firefox|minefield)/i.test(navigator.userAgent),this.ANDROID=this.isBrowser&&/android/i.test(navigator.userAgent)&&!this.TRIDENT,this.SAFARI=this.isBrowser&&/safari/i.test(navigator.userAgent)&&this.WEBKIT}}return n.\\u0275fac=function(e){return new(e||n)(y(bc))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const Vx=[\"color\",\"button\",\"checkbox\",\"date\",\"datetime-local\",\"email\",\"file\",\"hidden\",\"image\",\"month\",\"number\",\"password\",\"radio\",\"range\",\"reset\",\"search\",\"submit\",\"tel\",\"text\",\"time\",\"url\",\"week\"];function Hx(){if(co)return co;if(\"object\"!=typeof document||!document)return co=new Set(Vx),co;let n=document.createElement(\"input\");return co=new Set(Vx.filter(t=>(n.setAttribute(\"type\",t),n.type===t))),co}let $a,Wr,Vm;function ei(n){return function Hz(){if(null==$a&&\"undefined\"!=typeof window)try{window.addEventListener(\"test\",null,Object.defineProperty({},\"passive\",{get:()=>$a=!0}))}finally{$a=$a||!1}return $a}()?n:!!n.capture}function jz(){if(null==Wr){if(\"object\"!=typeof document||!document||\"function\"!=typeof Element||!Element)return Wr=!1,Wr;if(\"scrollBehavior\"in document.documentElement.style)Wr=!0;else{const n=Element.prototype.scrollTo;Wr=!!n&&!/\\{\\s*\\[native code\\]\\s*\\}/.test(n.toString())}}return Wr}function Fd(n){if(function zz(){if(null==Vm){const n=\"undefined\"!=typeof document?document.head:null;Vm=!(!n||!n.createShadowRoot&&!n.attachShadow)}return Vm}()){const t=n.getRootNode?n.getRootNode():null;if(\"undefined\"!=typeof ShadowRoot&&ShadowRoot&&t instanceof ShadowRoot)return t}return null}function Hm(){let n=\"undefined\"!=typeof document&&document?document.activeElement:null;for(;n&&n.shadowRoot;){const t=n.shadowRoot.activeElement;if(t===n)break;n=t}return n}function Pn(n){return n.composedPath?n.composedPath()[0]:n.target}function jm(){return\"undefined\"!=typeof __karma__&&!!__karma__||\"undefined\"!=typeof jasmine&&!!jasmine||\"undefined\"!=typeof jest&&!!jest||\"undefined\"!=typeof Mocha&&!!Mocha}function Xt(n,...t){return t.length?t.some(e=>n[e]):n.altKey||n.shiftKey||n.ctrlKey||n.metaKey}class e3 extends ke{constructor(t,e){super()}schedule(t,e=0){return this}}const Ld={setInterval(n,t,...e){const{delegate:i}=Ld;return(null==i?void 0:i.setInterval)?i.setInterval(n,t,...e):setInterval(n,t,...e)},clearInterval(n){const{delegate:t}=Ld;return((null==t?void 0:t.clearInterval)||clearInterval)(n)},delegate:void 0};class qm extends e3{constructor(t,e){super(t,e),this.scheduler=t,this.work=e,this.pending=!1}schedule(t,e=0){if(this.closed)return this;this.state=t;const i=this.id,r=this.scheduler;return null!=i&&(this.id=this.recycleAsyncId(r,i,e)),this.pending=!0,this.delay=e,this.id=this.id||this.requestAsyncId(r,this.id,e),this}requestAsyncId(t,e,i=0){return Ld.setInterval(t.flush.bind(t,this),i)}recycleAsyncId(t,e,i=0){if(null!=i&&this.delay===i&&!1===this.pending)return e;Ld.clearInterval(e)}execute(t,e){if(this.closed)return new Error(\"executing a cancelled action\");this.pending=!1;const i=this._execute(t,e);if(i)return i;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))}_execute(t,e){let r,i=!1;try{this.work(t)}catch(s){i=!0,r=s||new Error(\"Scheduled action threw falsy error\")}if(i)return this.unsubscribe(),r}unsubscribe(){if(!this.closed){const{id:t,scheduler:e}=this,{actions:i}=e;this.work=this.state=this.scheduler=null,this.pending=!1,ss(i,this),null!=t&&(this.id=this.recycleAsyncId(e,t,null)),this.delay=null,super.unsubscribe()}}}const Ux={now:()=>(Ux.delegate||Date).now(),delegate:void 0};class Wa{constructor(t,e=Wa.now){this.schedulerActionCtor=t,this.now=e}schedule(t,e=0,i){return new this.schedulerActionCtor(this,t).schedule(i,e)}}Wa.now=Ux.now;class Ym extends Wa{constructor(t,e=Wa.now){super(t,e),this.actions=[],this._active=!1,this._scheduled=void 0}flush(t){const{actions:e}=this;if(this._active)return void e.push(t);let i;this._active=!0;do{if(i=t.execute(t.state,t.delay))break}while(t=e.shift());if(this._active=!1,i){for(;t=e.shift();)t.unsubscribe();throw i}}}const qa=new Ym(qm),t3=qa;function $x(n,t=qa){return qe((e,i)=>{let r=null,s=null,o=null;const a=()=>{if(r){r.unsubscribe(),r=null;const c=s;s=null,i.next(c)}};function l(){const c=o+n,d=t.now();if(d<c)return r=this.schedule(void 0,c-d),void i.add(r);a()}e.subscribe(Ue(i,c=>{s=c,o=t.now(),r||(r=t.schedule(l,n),i.add(r))},()=>{a(),i.complete()},void 0,()=>{s=r=null}))})}function Gx(n,t=Wi){return n=null!=n?n:r3,qe((e,i)=>{let r,s=!0;e.subscribe(Ue(i,o=>{const a=t(o);(s||!n(r,a))&&(s=!1,r=a,i.next(o))}))})}function r3(n,t){return n===t}function Ie(n){return qe((t,e)=>{Jt(n).subscribe(Ue(e,()=>e.complete(),gl)),!e.closed&&t.subscribe(e)})}function G(n){return null!=n&&\"false\"!=`${n}`}function Et(n,t=0){return function s3(n){return!isNaN(parseFloat(n))&&!isNaN(Number(n))}(n)?Number(n):t}function Wx(n){return Array.isArray(n)?n:[n]}function ft(n){return null==n?\"\":\"string\"==typeof n?n:`${n}px`}function at(n){return n instanceof W?n.nativeElement:n}let qx=(()=>{class n{create(e){return\"undefined\"==typeof MutationObserver?null:new MutationObserver(e)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),o3=(()=>{class n{constructor(e){this._mutationObserverFactory=e,this._observedElements=new Map}ngOnDestroy(){this._observedElements.forEach((e,i)=>this._cleanupObserver(i))}observe(e){const i=at(e);return new Ve(r=>{const o=this._observeElement(i).subscribe(r);return()=>{o.unsubscribe(),this._unobserveElement(i)}})}_observeElement(e){if(this._observedElements.has(e))this._observedElements.get(e).count++;else{const i=new O,r=this._mutationObserverFactory.create(s=>i.next(s));r&&r.observe(e,{characterData:!0,childList:!0,subtree:!0}),this._observedElements.set(e,{observer:r,stream:i,count:1})}return this._observedElements.get(e).stream}_unobserveElement(e){this._observedElements.has(e)&&(this._observedElements.get(e).count--,this._observedElements.get(e).count||this._cleanupObserver(e))}_cleanupObserver(e){if(this._observedElements.has(e)){const{observer:i,stream:r}=this._observedElements.get(e);i&&i.disconnect(),r.complete(),this._observedElements.delete(e)}}}return n.\\u0275fac=function(e){return new(e||n)(y(qx))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),Qm=(()=>{class n{constructor(e,i,r){this._contentObserver=e,this._elementRef=i,this._ngZone=r,this.event=new $,this._disabled=!1,this._currentSubscription=null}get disabled(){return this._disabled}set disabled(e){this._disabled=G(e),this._disabled?this._unsubscribe():this._subscribe()}get debounce(){return this._debounce}set debounce(e){this._debounce=Et(e),this._subscribe()}ngAfterContentInit(){!this._currentSubscription&&!this.disabled&&this._subscribe()}ngOnDestroy(){this._unsubscribe()}_subscribe(){this._unsubscribe();const e=this._contentObserver.observe(this._elementRef);this._ngZone.runOutsideAngular(()=>{this._currentSubscription=(this.debounce?e.pipe($x(this.debounce)):e).subscribe(this.event)})}_unsubscribe(){var e;null===(e=this._currentSubscription)||void 0===e||e.unsubscribe()}}return n.\\u0275fac=function(e){return new(e||n)(f(o3),f(W),f(ne))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"cdkObserveContent\",\"\"]],inputs:{disabled:[\"cdkObserveContentDisabled\",\"disabled\"],debounce:\"debounce\"},outputs:{event:\"cdkObserveContent\"},exportAs:[\"cdkObserveContent\"]}),n})(),Ya=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[qx]}),n})();class c3 extends class Kx{constructor(t){this._items=t,this._activeItemIndex=-1,this._activeItem=null,this._wrap=!1,this._letterKeyStream=new O,this._typeaheadSubscription=ke.EMPTY,this._vertical=!0,this._allowedModifierKeys=[],this._homeAndEnd=!1,this._skipPredicateFn=e=>e.disabled,this._pressedLetters=[],this.tabOut=new O,this.change=new O,t instanceof fa&&t.changes.subscribe(e=>{if(this._activeItem){const r=e.toArray().indexOf(this._activeItem);r>-1&&r!==this._activeItemIndex&&(this._activeItemIndex=r)}})}skipPredicate(t){return this._skipPredicateFn=t,this}withWrap(t=!0){return this._wrap=t,this}withVerticalOrientation(t=!0){return this._vertical=t,this}withHorizontalOrientation(t){return this._horizontal=t,this}withAllowedModifierKeys(t){return this._allowedModifierKeys=t,this}withTypeAhead(t=200){return this._typeaheadSubscription.unsubscribe(),this._typeaheadSubscription=this._letterKeyStream.pipe(Mt(e=>this._pressedLetters.push(e)),$x(t),Ct(()=>this._pressedLetters.length>0),ue(()=>this._pressedLetters.join(\"\"))).subscribe(e=>{const i=this._getItemsArray();for(let r=1;r<i.length+1;r++){const s=(this._activeItemIndex+r)%i.length,o=i[s];if(!this._skipPredicateFn(o)&&0===o.getLabel().toUpperCase().trim().indexOf(e)){this.setActiveItem(s);break}}this._pressedLetters=[]}),this}withHomeAndEnd(t=!0){return this._homeAndEnd=t,this}setActiveItem(t){const e=this._activeItem;this.updateActiveItem(t),this._activeItem!==e&&this.change.next(this._activeItemIndex)}onKeydown(t){const e=t.keyCode,r=[\"altKey\",\"ctrlKey\",\"metaKey\",\"shiftKey\"].every(s=>!t[s]||this._allowedModifierKeys.indexOf(s)>-1);switch(e){case 9:return void this.tabOut.next();case 40:if(this._vertical&&r){this.setNextItemActive();break}return;case 38:if(this._vertical&&r){this.setPreviousItemActive();break}return;case 39:if(this._horizontal&&r){\"rtl\"===this._horizontal?this.setPreviousItemActive():this.setNextItemActive();break}return;case 37:if(this._horizontal&&r){\"rtl\"===this._horizontal?this.setNextItemActive():this.setPreviousItemActive();break}return;case 36:if(this._homeAndEnd&&r){this.setFirstItemActive();break}return;case 35:if(this._homeAndEnd&&r){this.setLastItemActive();break}return;default:return void((r||Xt(t,\"shiftKey\"))&&(t.key&&1===t.key.length?this._letterKeyStream.next(t.key.toLocaleUpperCase()):(e>=65&&e<=90||e>=48&&e<=57)&&this._letterKeyStream.next(String.fromCharCode(e))))}this._pressedLetters=[],t.preventDefault()}get activeItemIndex(){return this._activeItemIndex}get activeItem(){return this._activeItem}isTyping(){return this._pressedLetters.length>0}setFirstItemActive(){this._setActiveItemByIndex(0,1)}setLastItemActive(){this._setActiveItemByIndex(this._items.length-1,-1)}setNextItemActive(){this._activeItemIndex<0?this.setFirstItemActive():this._setActiveItemByDelta(1)}setPreviousItemActive(){this._activeItemIndex<0&&this._wrap?this.setLastItemActive():this._setActiveItemByDelta(-1)}updateActiveItem(t){const e=this._getItemsArray(),i=\"number\"==typeof t?t:e.indexOf(t),r=e[i];this._activeItem=null==r?null:r,this._activeItemIndex=i}_setActiveItemByDelta(t){this._wrap?this._setActiveInWrapMode(t):this._setActiveInDefaultMode(t)}_setActiveInWrapMode(t){const e=this._getItemsArray();for(let i=1;i<=e.length;i++){const r=(this._activeItemIndex+t*i+e.length)%e.length;if(!this._skipPredicateFn(e[r]))return void this.setActiveItem(r)}}_setActiveInDefaultMode(t){this._setActiveItemByIndex(this._activeItemIndex+t,t)}_setActiveItemByIndex(t,e){const i=this._getItemsArray();if(i[t]){for(;this._skipPredicateFn(i[t]);)if(!i[t+=e])return;this.setActiveItem(t)}}_getItemsArray(){return this._items instanceof fa?this._items.toArray():this._items}}{setActiveItem(t){this.activeItem&&this.activeItem.setInactiveStyles(),super.setActiveItem(t),this.activeItem&&this.activeItem.setActiveStyles()}}let Xx=(()=>{class n{constructor(e){this._platform=e}isDisabled(e){return e.hasAttribute(\"disabled\")}isVisible(e){return function u3(n){return!!(n.offsetWidth||n.offsetHeight||\"function\"==typeof n.getClientRects&&n.getClientRects().length)}(e)&&\"visible\"===getComputedStyle(e).visibility}isTabbable(e){if(!this._platform.isBrowser)return!1;const i=function d3(n){try{return n.frameElement}catch(t){return null}}(function y3(n){return n.ownerDocument&&n.ownerDocument.defaultView||window}(e));if(i&&(-1===eE(i)||!this.isVisible(i)))return!1;let r=e.nodeName.toLowerCase(),s=eE(e);return e.hasAttribute(\"contenteditable\")?-1!==s:!(\"iframe\"===r||\"object\"===r||this._platform.WEBKIT&&this._platform.IOS&&!function _3(n){let t=n.nodeName.toLowerCase(),e=\"input\"===t&&n.type;return\"text\"===e||\"password\"===e||\"select\"===t||\"textarea\"===t}(e))&&(\"audio\"===r?!!e.hasAttribute(\"controls\")&&-1!==s:\"video\"===r?-1!==s&&(null!==s||this._platform.FIREFOX||e.hasAttribute(\"controls\")):e.tabIndex>=0)}isFocusable(e,i){return function v3(n){return!function p3(n){return function m3(n){return\"input\"==n.nodeName.toLowerCase()}(n)&&\"hidden\"==n.type}(n)&&(function h3(n){let t=n.nodeName.toLowerCase();return\"input\"===t||\"select\"===t||\"button\"===t||\"textarea\"===t}(n)||function f3(n){return function g3(n){return\"a\"==n.nodeName.toLowerCase()}(n)&&n.hasAttribute(\"href\")}(n)||n.hasAttribute(\"contenteditable\")||Jx(n))}(e)&&!this.isDisabled(e)&&((null==i?void 0:i.ignoreVisibility)||this.isVisible(e))}}return n.\\u0275fac=function(e){return new(e||n)(y(It))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();function Jx(n){if(!n.hasAttribute(\"tabindex\")||void 0===n.tabIndex)return!1;let t=n.getAttribute(\"tabindex\");return!(!t||isNaN(parseInt(t,10)))}function eE(n){if(!Jx(n))return null;const t=parseInt(n.getAttribute(\"tabindex\")||\"\",10);return isNaN(t)?-1:t}class b3{constructor(t,e,i,r,s=!1){this._element=t,this._checker=e,this._ngZone=i,this._document=r,this._hasAttached=!1,this.startAnchorListener=()=>this.focusLastTabbableElement(),this.endAnchorListener=()=>this.focusFirstTabbableElement(),this._enabled=!0,s||this.attachAnchors()}get enabled(){return this._enabled}set enabled(t){this._enabled=t,this._startAnchor&&this._endAnchor&&(this._toggleAnchorTabIndex(t,this._startAnchor),this._toggleAnchorTabIndex(t,this._endAnchor))}destroy(){const t=this._startAnchor,e=this._endAnchor;t&&(t.removeEventListener(\"focus\",this.startAnchorListener),t.remove()),e&&(e.removeEventListener(\"focus\",this.endAnchorListener),e.remove()),this._startAnchor=this._endAnchor=null,this._hasAttached=!1}attachAnchors(){return!!this._hasAttached||(this._ngZone.runOutsideAngular(()=>{this._startAnchor||(this._startAnchor=this._createAnchor(),this._startAnchor.addEventListener(\"focus\",this.startAnchorListener)),this._endAnchor||(this._endAnchor=this._createAnchor(),this._endAnchor.addEventListener(\"focus\",this.endAnchorListener))}),this._element.parentNode&&(this._element.parentNode.insertBefore(this._startAnchor,this._element),this._element.parentNode.insertBefore(this._endAnchor,this._element.nextSibling),this._hasAttached=!0),this._hasAttached)}focusInitialElementWhenReady(t){return new Promise(e=>{this._executeOnStable(()=>e(this.focusInitialElement(t)))})}focusFirstTabbableElementWhenReady(t){return new Promise(e=>{this._executeOnStable(()=>e(this.focusFirstTabbableElement(t)))})}focusLastTabbableElementWhenReady(t){return new Promise(e=>{this._executeOnStable(()=>e(this.focusLastTabbableElement(t)))})}_getRegionBoundary(t){const e=this._element.querySelectorAll(`[cdk-focus-region-${t}], [cdkFocusRegion${t}], [cdk-focus-${t}]`);return\"start\"==t?e.length?e[0]:this._getFirstTabbableElement(this._element):e.length?e[e.length-1]:this._getLastTabbableElement(this._element)}focusInitialElement(t){const e=this._element.querySelector(\"[cdk-focus-initial], [cdkFocusInitial]\");if(e){if(!this._checker.isFocusable(e)){const i=this._getFirstTabbableElement(e);return null==i||i.focus(t),!!i}return e.focus(t),!0}return this.focusFirstTabbableElement(t)}focusFirstTabbableElement(t){const e=this._getRegionBoundary(\"start\");return e&&e.focus(t),!!e}focusLastTabbableElement(t){const e=this._getRegionBoundary(\"end\");return e&&e.focus(t),!!e}hasAttached(){return this._hasAttached}_getFirstTabbableElement(t){if(this._checker.isFocusable(t)&&this._checker.isTabbable(t))return t;const e=t.children;for(let i=0;i<e.length;i++){const r=e[i].nodeType===this._document.ELEMENT_NODE?this._getFirstTabbableElement(e[i]):null;if(r)return r}return null}_getLastTabbableElement(t){if(this._checker.isFocusable(t)&&this._checker.isTabbable(t))return t;const e=t.children;for(let i=e.length-1;i>=0;i--){const r=e[i].nodeType===this._document.ELEMENT_NODE?this._getLastTabbableElement(e[i]):null;if(r)return r}return null}_createAnchor(){const t=this._document.createElement(\"div\");return this._toggleAnchorTabIndex(this._enabled,t),t.classList.add(\"cdk-visually-hidden\"),t.classList.add(\"cdk-focus-trap-anchor\"),t.setAttribute(\"aria-hidden\",\"true\"),t}_toggleAnchorTabIndex(t,e){t?e.setAttribute(\"tabindex\",\"0\"):e.removeAttribute(\"tabindex\")}toggleAnchors(t){this._startAnchor&&this._endAnchor&&(this._toggleAnchorTabIndex(t,this._startAnchor),this._toggleAnchorTabIndex(t,this._endAnchor))}_executeOnStable(t){this._ngZone.isStable?t():this._ngZone.onStable.pipe(it(1)).subscribe(t)}}let C3=(()=>{class n{constructor(e,i,r){this._checker=e,this._ngZone=i,this._document=r}create(e,i=!1){return new b3(e,this._checker,this._ngZone,this._document,i)}}return n.\\u0275fac=function(e){return new(e||n)(y(Xx),y(ne),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();function Km(n){return 0===n.buttons||0===n.offsetX&&0===n.offsetY}function Zm(n){const t=n.touches&&n.touches[0]||n.changedTouches&&n.changedTouches[0];return!(!t||-1!==t.identifier||null!=t.radiusX&&1!==t.radiusX||null!=t.radiusY&&1!==t.radiusY)}const D3=new b(\"cdk-input-modality-detector-options\"),w3={ignoreKeys:[18,17,224,91,16]},ho=ei({passive:!0,capture:!0});let M3=(()=>{class n{constructor(e,i,r,s){this._platform=e,this._mostRecentTarget=null,this._modality=new Zt(null),this._lastTouchMs=0,this._onKeydown=o=>{var a,l;(null===(l=null===(a=this._options)||void 0===a?void 0:a.ignoreKeys)||void 0===l?void 0:l.some(c=>c===o.keyCode))||(this._modality.next(\"keyboard\"),this._mostRecentTarget=Pn(o))},this._onMousedown=o=>{Date.now()-this._lastTouchMs<650||(this._modality.next(Km(o)?\"keyboard\":\"mouse\"),this._mostRecentTarget=Pn(o))},this._onTouchstart=o=>{Zm(o)?this._modality.next(\"keyboard\"):(this._lastTouchMs=Date.now(),this._modality.next(\"touch\"),this._mostRecentTarget=Pn(o))},this._options=Object.assign(Object.assign({},w3),s),this.modalityDetected=this._modality.pipe(function n3(n){return Ct((t,e)=>n<=e)}(1)),this.modalityChanged=this.modalityDetected.pipe(Gx()),e.isBrowser&&i.runOutsideAngular(()=>{r.addEventListener(\"keydown\",this._onKeydown,ho),r.addEventListener(\"mousedown\",this._onMousedown,ho),r.addEventListener(\"touchstart\",this._onTouchstart,ho)})}get mostRecentModality(){return this._modality.value}ngOnDestroy(){this._modality.complete(),this._platform.isBrowser&&(document.removeEventListener(\"keydown\",this._onKeydown,ho),document.removeEventListener(\"mousedown\",this._onMousedown,ho),document.removeEventListener(\"touchstart\",this._onTouchstart,ho))}}return n.\\u0275fac=function(e){return new(e||n)(y(It),y(ne),y(ie),y(D3,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const x3=new b(\"liveAnnouncerElement\",{providedIn:\"root\",factory:function E3(){return null}}),S3=new b(\"LIVE_ANNOUNCER_DEFAULT_OPTIONS\");let k3=(()=>{class n{constructor(e,i,r,s){this._ngZone=i,this._defaultOptions=s,this._document=r,this._liveElement=e||this._createLiveElement()}announce(e,...i){const r=this._defaultOptions;let s,o;return 1===i.length&&\"number\"==typeof i[0]?o=i[0]:[s,o]=i,this.clear(),clearTimeout(this._previousTimeout),s||(s=r&&r.politeness?r.politeness:\"polite\"),null==o&&r&&(o=r.duration),this._liveElement.setAttribute(\"aria-live\",s),this._ngZone.runOutsideAngular(()=>new Promise(a=>{clearTimeout(this._previousTimeout),this._previousTimeout=setTimeout(()=>{this._liveElement.textContent=e,a(),\"number\"==typeof o&&(this._previousTimeout=setTimeout(()=>this.clear(),o))},100)}))}clear(){this._liveElement&&(this._liveElement.textContent=\"\")}ngOnDestroy(){var e;clearTimeout(this._previousTimeout),null===(e=this._liveElement)||void 0===e||e.remove(),this._liveElement=null}_createLiveElement(){const e=\"cdk-live-announcer-element\",i=this._document.getElementsByClassName(e),r=this._document.createElement(\"div\");for(let s=0;s<i.length;s++)i[s].remove();return r.classList.add(e),r.classList.add(\"cdk-visually-hidden\"),r.setAttribute(\"aria-atomic\",\"true\"),r.setAttribute(\"aria-live\",\"polite\"),this._document.body.appendChild(r),r}}return n.\\u0275fac=function(e){return new(e||n)(y(x3,8),y(ne),y(ie),y(S3,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const T3=new b(\"cdk-focus-monitor-default-options\"),Bd=ei({passive:!0,capture:!0});let Qr=(()=>{class n{constructor(e,i,r,s,o){this._ngZone=e,this._platform=i,this._inputModalityDetector=r,this._origin=null,this._windowFocused=!1,this._originFromTouchInteraction=!1,this._elementInfo=new Map,this._monitoredElementCount=0,this._rootNodeFocusListenerCount=new Map,this._windowFocusListener=()=>{this._windowFocused=!0,this._windowFocusTimeoutId=window.setTimeout(()=>this._windowFocused=!1)},this._stopInputModalityDetector=new O,this._rootNodeFocusAndBlurListener=a=>{const l=Pn(a),c=\"focus\"===a.type?this._onFocus:this._onBlur;for(let d=l;d;d=d.parentElement)c.call(this,a,d)},this._document=s,this._detectionMode=(null==o?void 0:o.detectionMode)||0}monitor(e,i=!1){const r=at(e);if(!this._platform.isBrowser||1!==r.nodeType)return q(null);const s=Fd(r)||this._getDocument(),o=this._elementInfo.get(r);if(o)return i&&(o.checkChildren=!0),o.subject;const a={checkChildren:i,subject:new O,rootNode:s};return this._elementInfo.set(r,a),this._registerGlobalListeners(a),a.subject}stopMonitoring(e){const i=at(e),r=this._elementInfo.get(i);r&&(r.subject.complete(),this._setClasses(i),this._elementInfo.delete(i),this._removeGlobalListeners(r))}focusVia(e,i,r){const s=at(e);s===this._getDocument().activeElement?this._getClosestElementsInfo(s).forEach(([a,l])=>this._originChanged(a,i,l)):(this._setOrigin(i),\"function\"==typeof s.focus&&s.focus(r))}ngOnDestroy(){this._elementInfo.forEach((e,i)=>this.stopMonitoring(i))}_getDocument(){return this._document||document}_getWindow(){return this._getDocument().defaultView||window}_getFocusOrigin(e){return this._origin?this._originFromTouchInteraction?this._shouldBeAttributedToTouch(e)?\"touch\":\"program\":this._origin:this._windowFocused&&this._lastFocusOrigin?this._lastFocusOrigin:\"program\"}_shouldBeAttributedToTouch(e){return 1===this._detectionMode||!!(null==e?void 0:e.contains(this._inputModalityDetector._mostRecentTarget))}_setClasses(e,i){e.classList.toggle(\"cdk-focused\",!!i),e.classList.toggle(\"cdk-touch-focused\",\"touch\"===i),e.classList.toggle(\"cdk-keyboard-focused\",\"keyboard\"===i),e.classList.toggle(\"cdk-mouse-focused\",\"mouse\"===i),e.classList.toggle(\"cdk-program-focused\",\"program\"===i)}_setOrigin(e,i=!1){this._ngZone.runOutsideAngular(()=>{this._origin=e,this._originFromTouchInteraction=\"touch\"===e&&i,0===this._detectionMode&&(clearTimeout(this._originTimeoutId),this._originTimeoutId=setTimeout(()=>this._origin=null,this._originFromTouchInteraction?650:1))})}_onFocus(e,i){const r=this._elementInfo.get(i),s=Pn(e);!r||!r.checkChildren&&i!==s||this._originChanged(i,this._getFocusOrigin(s),r)}_onBlur(e,i){const r=this._elementInfo.get(i);!r||r.checkChildren&&e.relatedTarget instanceof Node&&i.contains(e.relatedTarget)||(this._setClasses(i),this._emitOrigin(r.subject,null))}_emitOrigin(e,i){this._ngZone.run(()=>e.next(i))}_registerGlobalListeners(e){if(!this._platform.isBrowser)return;const i=e.rootNode,r=this._rootNodeFocusListenerCount.get(i)||0;r||this._ngZone.runOutsideAngular(()=>{i.addEventListener(\"focus\",this._rootNodeFocusAndBlurListener,Bd),i.addEventListener(\"blur\",this._rootNodeFocusAndBlurListener,Bd)}),this._rootNodeFocusListenerCount.set(i,r+1),1==++this._monitoredElementCount&&(this._ngZone.runOutsideAngular(()=>{this._getWindow().addEventListener(\"focus\",this._windowFocusListener)}),this._inputModalityDetector.modalityDetected.pipe(Ie(this._stopInputModalityDetector)).subscribe(s=>{this._setOrigin(s,!0)}))}_removeGlobalListeners(e){const i=e.rootNode;if(this._rootNodeFocusListenerCount.has(i)){const r=this._rootNodeFocusListenerCount.get(i);r>1?this._rootNodeFocusListenerCount.set(i,r-1):(i.removeEventListener(\"focus\",this._rootNodeFocusAndBlurListener,Bd),i.removeEventListener(\"blur\",this._rootNodeFocusAndBlurListener,Bd),this._rootNodeFocusListenerCount.delete(i))}--this._monitoredElementCount||(this._getWindow().removeEventListener(\"focus\",this._windowFocusListener),this._stopInputModalityDetector.next(),clearTimeout(this._windowFocusTimeoutId),clearTimeout(this._originTimeoutId))}_originChanged(e,i,r){this._setClasses(e,i),this._emitOrigin(r.subject,i),this._lastFocusOrigin=i}_getClosestElementsInfo(e){const i=[];return this._elementInfo.forEach((r,s)=>{(s===e||r.checkChildren&&s.contains(e))&&i.push([s,r])}),i}}return n.\\u0275fac=function(e){return new(e||n)(y(ne),y(It),y(M3),y(ie,8),y(T3,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const nE=\"cdk-high-contrast-black-on-white\",iE=\"cdk-high-contrast-white-on-black\",Xm=\"cdk-high-contrast-active\";let rE=(()=>{class n{constructor(e,i){this._platform=e,this._document=i}getHighContrastMode(){if(!this._platform.isBrowser)return 0;const e=this._document.createElement(\"div\");e.style.backgroundColor=\"rgb(1,2,3)\",e.style.position=\"absolute\",this._document.body.appendChild(e);const i=this._document.defaultView||window,r=i&&i.getComputedStyle?i.getComputedStyle(e):null,s=(r&&r.backgroundColor||\"\").replace(/ /g,\"\");switch(e.remove(),s){case\"rgb(0,0,0)\":return 2;case\"rgb(255,255,255)\":return 1}return 0}_applyBodyHighContrastModeCssClasses(){if(!this._hasCheckedHighContrastMode&&this._platform.isBrowser&&this._document.body){const e=this._document.body.classList;e.remove(Xm),e.remove(nE),e.remove(iE),this._hasCheckedHighContrastMode=!0;const i=this.getHighContrastMode();1===i?(e.add(Xm),e.add(nE)):2===i&&(e.add(Xm),e.add(iE))}}}return n.\\u0275fac=function(e){return new(e||n)(y(It),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),Qa=(()=>{class n{constructor(e){e._applyBodyHighContrastModeCssClasses()}}return n.\\u0275fac=function(e){return new(e||n)(y(rE))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Ya]]}),n})();const A3=[\"*\",[[\"mat-option\"],[\"ng-container\"]]],I3=[\"*\",\"mat-option, ng-container\"];function R3(n,t){if(1&n&&Le(0,\"mat-pseudo-checkbox\",4),2&n){const e=Be();N(\"state\",e.selected?\"checked\":\"unchecked\")(\"disabled\",e.disabled)}}function O3(n,t){if(1&n&&(x(0,\"span\",5),we(1),S()),2&n){const e=Be();T(1),qn(\"(\",e.group.label,\")\")}}const P3=[\"*\"],Jm=new Rr(\"13.3.0\"),N3=new b(\"mat-sanity-checks\",{providedIn:\"root\",factory:function F3(){return!0}});let B=(()=>{class n{constructor(e,i,r){this._sanityChecks=i,this._document=r,this._hasDoneGlobalChecks=!1,e._applyBodyHighContrastModeCssClasses(),this._hasDoneGlobalChecks||(this._hasDoneGlobalChecks=!0)}_checkIsEnabled(e){return!jm()&&(\"boolean\"==typeof this._sanityChecks?this._sanityChecks:!!this._sanityChecks[e])}}return n.\\u0275fac=function(e){return new(e||n)(y(rE),y(N3,8),y(ie))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[lo],lo]}),n})();function po(n){return class extends n{constructor(...t){super(...t),this._disabled=!1}get disabled(){return this._disabled}set disabled(t){this._disabled=G(t)}}}function fo(n,t){return class extends n{constructor(...e){super(...e),this.defaultColor=t,this.color=t}get color(){return this._color}set color(e){const i=e||this.defaultColor;i!==this._color&&(this._color&&this._elementRef.nativeElement.classList.remove(`mat-${this._color}`),i&&this._elementRef.nativeElement.classList.add(`mat-${i}`),this._color=i)}}}function ar(n){return class extends n{constructor(...t){super(...t),this._disableRipple=!1}get disableRipple(){return this._disableRipple}set disableRipple(t){this._disableRipple=G(t)}}}function Kr(n,t=0){return class extends n{constructor(...e){super(...e),this._tabIndex=t,this.defaultTabIndex=t}get tabIndex(){return this.disabled?-1:this._tabIndex}set tabIndex(e){this._tabIndex=null!=e?Et(e):this.defaultTabIndex}}}function ng(n){return class extends n{constructor(...t){super(...t),this.stateChanges=new O,this.errorState=!1}updateErrorState(){const t=this.errorState,s=(this.errorStateMatcher||this._defaultErrorStateMatcher).isErrorState(this.ngControl?this.ngControl.control:null,this._parentFormGroup||this._parentForm);s!==t&&(this.errorState=s,this.stateChanges.next())}}}const L3=new b(\"MAT_DATE_LOCALE\",{providedIn:\"root\",factory:function B3(){return Uo(Oi)}});class bi{constructor(){this._localeChanges=new O,this.localeChanges=this._localeChanges}getValidDateOrNull(t){return this.isDateInstance(t)&&this.isValid(t)?t:null}deserialize(t){return null==t||this.isDateInstance(t)&&this.isValid(t)?t:this.invalid()}setLocale(t){this.locale=t,this._localeChanges.next()}compareDate(t,e){return this.getYear(t)-this.getYear(e)||this.getMonth(t)-this.getMonth(e)||this.getDate(t)-this.getDate(e)}sameDate(t,e){if(t&&e){let i=this.isValid(t),r=this.isValid(e);return i&&r?!this.compareDate(t,e):i==r}return t==e}clampDate(t,e,i){return e&&this.compareDate(t,e)<0?e:i&&this.compareDate(t,i)>0?i:t}}const ig=new b(\"mat-date-formats\"),V3=/^\\d{4}-\\d{2}-\\d{2}(?:T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|(?:(?:\\+|-)\\d{2}:\\d{2}))?)?$/;function rg(n,t){const e=Array(n);for(let i=0;i<n;i++)e[i]=t(i);return e}let H3=(()=>{class n extends bi{constructor(e,i){super(),this.useUtcForDisplay=!1,super.setLocale(e)}getYear(e){return e.getFullYear()}getMonth(e){return e.getMonth()}getDate(e){return e.getDate()}getDayOfWeek(e){return e.getDay()}getMonthNames(e){const i=new Intl.DateTimeFormat(this.locale,{month:e,timeZone:\"utc\"});return rg(12,r=>this._format(i,new Date(2017,r,1)))}getDateNames(){const e=new Intl.DateTimeFormat(this.locale,{day:\"numeric\",timeZone:\"utc\"});return rg(31,i=>this._format(e,new Date(2017,0,i+1)))}getDayOfWeekNames(e){const i=new Intl.DateTimeFormat(this.locale,{weekday:e,timeZone:\"utc\"});return rg(7,r=>this._format(i,new Date(2017,0,r+1)))}getYearName(e){const i=new Intl.DateTimeFormat(this.locale,{year:\"numeric\",timeZone:\"utc\"});return this._format(i,e)}getFirstDayOfWeek(){return 0}getNumDaysInMonth(e){return this.getDate(this._createDateWithOverflow(this.getYear(e),this.getMonth(e)+1,0))}clone(e){return new Date(e.getTime())}createDate(e,i,r){let s=this._createDateWithOverflow(e,i,r);return s.getMonth(),s}today(){return new Date}parse(e){return\"number\"==typeof e?new Date(e):e?new Date(Date.parse(e)):null}format(e,i){if(!this.isValid(e))throw Error(\"NativeDateAdapter: Cannot format invalid date.\");const r=new Intl.DateTimeFormat(this.locale,Object.assign(Object.assign({},i),{timeZone:\"utc\"}));return this._format(r,e)}addCalendarYears(e,i){return this.addCalendarMonths(e,12*i)}addCalendarMonths(e,i){let r=this._createDateWithOverflow(this.getYear(e),this.getMonth(e)+i,this.getDate(e));return this.getMonth(r)!=((this.getMonth(e)+i)%12+12)%12&&(r=this._createDateWithOverflow(this.getYear(r),this.getMonth(r),0)),r}addCalendarDays(e,i){return this._createDateWithOverflow(this.getYear(e),this.getMonth(e),this.getDate(e)+i)}toIso8601(e){return[e.getUTCFullYear(),this._2digit(e.getUTCMonth()+1),this._2digit(e.getUTCDate())].join(\"-\")}deserialize(e){if(\"string\"==typeof e){if(!e)return null;if(V3.test(e)){let i=new Date(e);if(this.isValid(i))return i}}return super.deserialize(e)}isDateInstance(e){return e instanceof Date}isValid(e){return!isNaN(e.getTime())}invalid(){return new Date(NaN)}_createDateWithOverflow(e,i,r){const s=new Date;return s.setFullYear(e,i,r),s.setHours(0,0,0,0),s}_2digit(e){return(\"00\"+e).slice(-2)}_format(e,i){const r=new Date;return r.setUTCFullYear(i.getFullYear(),i.getMonth(),i.getDate()),r.setUTCHours(i.getHours(),i.getMinutes(),i.getSeconds(),i.getMilliseconds()),e.format(r)}}return n.\\u0275fac=function(e){return new(e||n)(y(L3,8),y(It))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const j3={parse:{dateInput:null},display:{dateInput:{year:\"numeric\",month:\"numeric\",day:\"numeric\"},monthYearLabel:{year:\"numeric\",month:\"short\"},dateA11yLabel:{year:\"numeric\",month:\"long\",day:\"numeric\"},monthYearA11yLabel:{year:\"numeric\",month:\"long\"}}};let z3=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[{provide:bi,useClass:H3}]}),n})(),U3=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[{provide:ig,useValue:j3}],imports:[[z3]]}),n})(),mo=(()=>{class n{isErrorState(e,i){return!!(e&&e.invalid&&(e.touched||i&&i.submitted))}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),Vd=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})();class W3{constructor(t,e,i){this._renderer=t,this.element=e,this.config=i,this.state=3}fadeOut(){this._renderer.fadeOutRipple(this)}}const sE={enterDuration:225,exitDuration:150},sg=ei({passive:!0}),oE=[\"mousedown\",\"touchstart\"],aE=[\"mouseup\",\"mouseleave\",\"touchend\",\"touchcancel\"];class lE{constructor(t,e,i,r){this._target=t,this._ngZone=e,this._isPointerDown=!1,this._activeRipples=new Set,this._pointerUpEventsRegistered=!1,r.isBrowser&&(this._containerElement=at(i))}fadeInRipple(t,e,i={}){const r=this._containerRect=this._containerRect||this._containerElement.getBoundingClientRect(),s=Object.assign(Object.assign({},sE),i.animation);i.centered&&(t=r.left+r.width/2,e=r.top+r.height/2);const o=i.radius||function Q3(n,t,e){const i=Math.max(Math.abs(n-e.left),Math.abs(n-e.right)),r=Math.max(Math.abs(t-e.top),Math.abs(t-e.bottom));return Math.sqrt(i*i+r*r)}(t,e,r),a=t-r.left,l=e-r.top,c=s.enterDuration,d=document.createElement(\"div\");d.classList.add(\"mat-ripple-element\"),d.style.left=a-o+\"px\",d.style.top=l-o+\"px\",d.style.height=2*o+\"px\",d.style.width=2*o+\"px\",null!=i.color&&(d.style.backgroundColor=i.color),d.style.transitionDuration=`${c}ms`,this._containerElement.appendChild(d),function Y3(n){window.getComputedStyle(n).getPropertyValue(\"opacity\")}(d),d.style.transform=\"scale(1)\";const u=new W3(this,d,i);return u.state=0,this._activeRipples.add(u),i.persistent||(this._mostRecentTransientRipple=u),this._runTimeoutOutsideZone(()=>{const h=u===this._mostRecentTransientRipple;u.state=1,!i.persistent&&(!h||!this._isPointerDown)&&u.fadeOut()},c),u}fadeOutRipple(t){const e=this._activeRipples.delete(t);if(t===this._mostRecentTransientRipple&&(this._mostRecentTransientRipple=null),this._activeRipples.size||(this._containerRect=null),!e)return;const i=t.element,r=Object.assign(Object.assign({},sE),t.config.animation);i.style.transitionDuration=`${r.exitDuration}ms`,i.style.opacity=\"0\",t.state=2,this._runTimeoutOutsideZone(()=>{t.state=3,i.remove()},r.exitDuration)}fadeOutAll(){this._activeRipples.forEach(t=>t.fadeOut())}fadeOutAllNonPersistent(){this._activeRipples.forEach(t=>{t.config.persistent||t.fadeOut()})}setupTriggerEvents(t){const e=at(t);!e||e===this._triggerElement||(this._removeTriggerEvents(),this._triggerElement=e,this._registerEvents(oE))}handleEvent(t){\"mousedown\"===t.type?this._onMousedown(t):\"touchstart\"===t.type?this._onTouchStart(t):this._onPointerUp(),this._pointerUpEventsRegistered||(this._registerEvents(aE),this._pointerUpEventsRegistered=!0)}_onMousedown(t){const e=Km(t),i=this._lastTouchStartEvent&&Date.now()<this._lastTouchStartEvent+800;!this._target.rippleDisabled&&!e&&!i&&(this._isPointerDown=!0,this.fadeInRipple(t.clientX,t.clientY,this._target.rippleConfig))}_onTouchStart(t){if(!this._target.rippleDisabled&&!Zm(t)){this._lastTouchStartEvent=Date.now(),this._isPointerDown=!0;const e=t.changedTouches;for(let i=0;i<e.length;i++)this.fadeInRipple(e[i].clientX,e[i].clientY,this._target.rippleConfig)}}_onPointerUp(){!this._isPointerDown||(this._isPointerDown=!1,this._activeRipples.forEach(t=>{!t.config.persistent&&(1===t.state||t.config.terminateOnPointerUp&&0===t.state)&&t.fadeOut()}))}_runTimeoutOutsideZone(t,e=0){this._ngZone.runOutsideAngular(()=>setTimeout(t,e))}_registerEvents(t){this._ngZone.runOutsideAngular(()=>{t.forEach(e=>{this._triggerElement.addEventListener(e,this,sg)})})}_removeTriggerEvents(){this._triggerElement&&(oE.forEach(t=>{this._triggerElement.removeEventListener(t,this,sg)}),this._pointerUpEventsRegistered&&aE.forEach(t=>{this._triggerElement.removeEventListener(t,this,sg)}))}}const cE=new b(\"mat-ripple-global-options\");let Zr=(()=>{class n{constructor(e,i,r,s,o){this._elementRef=e,this._animationMode=o,this.radius=0,this._disabled=!1,this._isInitialized=!1,this._globalOptions=s||{},this._rippleRenderer=new lE(this,i,e,r)}get disabled(){return this._disabled}set disabled(e){e&&this.fadeOutAllNonPersistent(),this._disabled=e,this._setupTriggerEventsIfEnabled()}get trigger(){return this._trigger||this._elementRef.nativeElement}set trigger(e){this._trigger=e,this._setupTriggerEventsIfEnabled()}ngOnInit(){this._isInitialized=!0,this._setupTriggerEventsIfEnabled()}ngOnDestroy(){this._rippleRenderer._removeTriggerEvents()}fadeOutAll(){this._rippleRenderer.fadeOutAll()}fadeOutAllNonPersistent(){this._rippleRenderer.fadeOutAllNonPersistent()}get rippleConfig(){return{centered:this.centered,radius:this.radius,color:this.color,animation:Object.assign(Object.assign(Object.assign({},this._globalOptions.animation),\"NoopAnimations\"===this._animationMode?{enterDuration:0,exitDuration:0}:{}),this.animation),terminateOnPointerUp:this._globalOptions.terminateOnPointerUp}}get rippleDisabled(){return this.disabled||!!this._globalOptions.disabled}_setupTriggerEventsIfEnabled(){!this.disabled&&this._isInitialized&&this._rippleRenderer.setupTriggerEvents(this.trigger)}launch(e,i=0,r){return\"number\"==typeof e?this._rippleRenderer.fadeInRipple(e,i,Object.assign(Object.assign({},this.rippleConfig),r)):this._rippleRenderer.fadeInRipple(0,0,Object.assign(Object.assign({},this.rippleConfig),e))}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(ne),f(It),f(cE,8),f(Rn,8))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"mat-ripple\",\"\"],[\"\",\"matRipple\",\"\"]],hostAttrs:[1,\"mat-ripple\"],hostVars:2,hostBindings:function(e,i){2&e&&Ae(\"mat-ripple-unbounded\",i.unbounded)},inputs:{color:[\"matRippleColor\",\"color\"],unbounded:[\"matRippleUnbounded\",\"unbounded\"],centered:[\"matRippleCentered\",\"centered\"],radius:[\"matRippleRadius\",\"radius\"],animation:[\"matRippleAnimation\",\"animation\"],disabled:[\"matRippleDisabled\",\"disabled\"],trigger:[\"matRippleTrigger\",\"trigger\"]},exportAs:[\"matRipple\"]}),n})(),ti=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),dE=(()=>{class n{constructor(e){this._animationMode=e,this.state=\"unchecked\",this.disabled=!1}}return n.\\u0275fac=function(e){return new(e||n)(f(Rn,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-pseudo-checkbox\"]],hostAttrs:[1,\"mat-pseudo-checkbox\"],hostVars:8,hostBindings:function(e,i){2&e&&Ae(\"mat-pseudo-checkbox-indeterminate\",\"indeterminate\"===i.state)(\"mat-pseudo-checkbox-checked\",\"checked\"===i.state)(\"mat-pseudo-checkbox-disabled\",i.disabled)(\"_mat-animation-noopable\",\"NoopAnimations\"===i._animationMode)},inputs:{state:\"state\",disabled:\"disabled\"},decls:0,vars:0,template:function(e,i){},styles:['.mat-pseudo-checkbox{width:16px;height:16px;border:2px solid;border-radius:2px;cursor:pointer;display:inline-block;vertical-align:middle;box-sizing:border-box;position:relative;flex-shrink:0;transition:border-color 90ms cubic-bezier(0, 0, 0.2, 0.1),background-color 90ms cubic-bezier(0, 0, 0.2, 0.1)}.mat-pseudo-checkbox::after{position:absolute;opacity:0;content:\"\";border-bottom:2px solid currentColor;transition:opacity 90ms cubic-bezier(0, 0, 0.2, 0.1)}.mat-pseudo-checkbox.mat-pseudo-checkbox-checked,.mat-pseudo-checkbox.mat-pseudo-checkbox-indeterminate{border-color:transparent}._mat-animation-noopable.mat-pseudo-checkbox{transition:none;animation:none}._mat-animation-noopable.mat-pseudo-checkbox::after{transition:none}.mat-pseudo-checkbox-disabled{cursor:default}.mat-pseudo-checkbox-indeterminate::after{top:5px;left:1px;width:10px;opacity:1;border-radius:2px}.mat-pseudo-checkbox-checked::after{top:2.4px;left:1px;width:8px;height:3px;border-left:2px solid currentColor;transform:rotate(-45deg);opacity:1;box-sizing:content-box}\\n'],encapsulation:2,changeDetection:0}),n})(),og=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B]]}),n})();const ag=new b(\"MAT_OPTION_PARENT_COMPONENT\"),K3=po(class{});let Z3=0,X3=(()=>{class n extends K3{constructor(e){var i;super(),this._labelId=\"mat-optgroup-label-\"+Z3++,this._inert=null!==(i=null==e?void 0:e.inertGroups)&&void 0!==i&&i}}return n.\\u0275fac=function(e){return new(e||n)(f(ag,8))},n.\\u0275dir=C({type:n,inputs:{label:\"label\"},features:[E]}),n})();const lg=new b(\"MatOptgroup\");let J3=(()=>{class n extends X3{}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275cmp=xe({type:n,selectors:[[\"mat-optgroup\"]],hostAttrs:[1,\"mat-optgroup\"],hostVars:5,hostBindings:function(e,i){2&e&&(Z(\"role\",i._inert?null:\"group\")(\"aria-disabled\",i._inert?null:i.disabled.toString())(\"aria-labelledby\",i._inert?null:i._labelId),Ae(\"mat-optgroup-disabled\",i.disabled))},inputs:{disabled:\"disabled\"},exportAs:[\"matOptgroup\"],features:[L([{provide:lg,useExisting:n}]),E],ngContentSelectors:I3,decls:4,vars:2,consts:[[\"aria-hidden\",\"true\",1,\"mat-optgroup-label\",3,\"id\"]],template:function(e,i){1&e&&(Lt(A3),x(0,\"span\",0),we(1),Pe(2),S(),Pe(3,1)),2&e&&(N(\"id\",i._labelId),T(1),qn(\"\",i.label,\" \"))},styles:[\".mat-optgroup-label{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;line-height:48px;height:48px;padding:0 16px;text-align:left;text-decoration:none;max-width:100%;-webkit-user-select:none;-moz-user-select:none;user-select:none;cursor:default}.mat-optgroup-label[disabled]{cursor:default}[dir=rtl] .mat-optgroup-label{text-align:right}.mat-optgroup-label .mat-icon{margin-right:16px;vertical-align:middle}.mat-optgroup-label .mat-icon svg{vertical-align:top}[dir=rtl] .mat-optgroup-label .mat-icon{margin-left:16px;margin-right:0}\\n\"],encapsulation:2,changeDetection:0}),n})(),eU=0;class uE{constructor(t,e=!1){this.source=t,this.isUserInput=e}}let tU=(()=>{class n{constructor(e,i,r,s){this._element=e,this._changeDetectorRef=i,this._parent=r,this.group=s,this._selected=!1,this._active=!1,this._disabled=!1,this._mostRecentViewValue=\"\",this.id=\"mat-option-\"+eU++,this.onSelectionChange=new $,this._stateChanges=new O}get multiple(){return this._parent&&this._parent.multiple}get selected(){return this._selected}get disabled(){return this.group&&this.group.disabled||this._disabled}set disabled(e){this._disabled=G(e)}get disableRipple(){return!(!this._parent||!this._parent.disableRipple)}get active(){return this._active}get viewValue(){return(this._getHostElement().textContent||\"\").trim()}select(){this._selected||(this._selected=!0,this._changeDetectorRef.markForCheck(),this._emitSelectionChangeEvent())}deselect(){this._selected&&(this._selected=!1,this._changeDetectorRef.markForCheck(),this._emitSelectionChangeEvent())}focus(e,i){const r=this._getHostElement();\"function\"==typeof r.focus&&r.focus(i)}setActiveStyles(){this._active||(this._active=!0,this._changeDetectorRef.markForCheck())}setInactiveStyles(){this._active&&(this._active=!1,this._changeDetectorRef.markForCheck())}getLabel(){return this.viewValue}_handleKeydown(e){(13===e.keyCode||32===e.keyCode)&&!Xt(e)&&(this._selectViaInteraction(),e.preventDefault())}_selectViaInteraction(){this.disabled||(this._selected=!this.multiple||!this._selected,this._changeDetectorRef.markForCheck(),this._emitSelectionChangeEvent(!0))}_getAriaSelected(){return this.selected||!this.multiple&&null}_getTabIndex(){return this.disabled?\"-1\":\"0\"}_getHostElement(){return this._element.nativeElement}ngAfterViewChecked(){if(this._selected){const e=this.viewValue;e!==this._mostRecentViewValue&&(this._mostRecentViewValue=e,this._stateChanges.next())}}ngOnDestroy(){this._stateChanges.complete()}_emitSelectionChangeEvent(e=!1){this.onSelectionChange.emit(new uE(this,e))}}return n.\\u0275fac=function(e){Sr()},n.\\u0275dir=C({type:n,inputs:{value:\"value\",id:\"id\",disabled:\"disabled\"},outputs:{onSelectionChange:\"onSelectionChange\"}}),n})(),hE=(()=>{class n extends tU{constructor(e,i,r,s){super(e,i,r,s)}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(Ye),f(ag,8),f(lg,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-option\"]],hostAttrs:[\"role\",\"option\",1,\"mat-option\",\"mat-focus-indicator\"],hostVars:12,hostBindings:function(e,i){1&e&&J(\"click\",function(){return i._selectViaInteraction()})(\"keydown\",function(s){return i._handleKeydown(s)}),2&e&&(Yn(\"id\",i.id),Z(\"tabindex\",i._getTabIndex())(\"aria-selected\",i._getAriaSelected())(\"aria-disabled\",i.disabled.toString()),Ae(\"mat-selected\",i.selected)(\"mat-option-multiple\",i.multiple)(\"mat-active\",i.active)(\"mat-option-disabled\",i.disabled))},exportAs:[\"matOption\"],features:[E],ngContentSelectors:P3,decls:5,vars:4,consts:[[\"class\",\"mat-option-pseudo-checkbox\",3,\"state\",\"disabled\",4,\"ngIf\"],[1,\"mat-option-text\"],[\"class\",\"cdk-visually-hidden\",4,\"ngIf\"],[\"mat-ripple\",\"\",1,\"mat-option-ripple\",3,\"matRippleTrigger\",\"matRippleDisabled\"],[1,\"mat-option-pseudo-checkbox\",3,\"state\",\"disabled\"],[1,\"cdk-visually-hidden\"]],template:function(e,i){1&e&&(Lt(),Ee(0,R3,1,2,\"mat-pseudo-checkbox\",0),x(1,\"span\",1),Pe(2),S(),Ee(3,O3,2,1,\"span\",2),Le(4,\"div\",3)),2&e&&(N(\"ngIf\",i.multiple),T(3),N(\"ngIf\",i.group&&i.group._inert),T(1),N(\"matRippleTrigger\",i._getHostElement())(\"matRippleDisabled\",i.disabled||i.disableRipple))},directives:[dE,Ca,Zr],styles:[\".mat-option{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;line-height:48px;height:48px;padding:0 16px;text-align:left;text-decoration:none;max-width:100%;position:relative;cursor:pointer;outline:none;display:flex;flex-direction:row;max-width:100%;box-sizing:border-box;align-items:center;-webkit-tap-highlight-color:transparent}.mat-option[disabled]{cursor:default}[dir=rtl] .mat-option{text-align:right}.mat-option .mat-icon{margin-right:16px;vertical-align:middle}.mat-option .mat-icon svg{vertical-align:top}[dir=rtl] .mat-option .mat-icon{margin-left:16px;margin-right:0}.mat-option[aria-disabled=true]{-webkit-user-select:none;-moz-user-select:none;user-select:none;cursor:default}.mat-optgroup .mat-option:not(.mat-option-multiple){padding-left:32px}[dir=rtl] .mat-optgroup .mat-option:not(.mat-option-multiple){padding-left:16px;padding-right:32px}.cdk-high-contrast-active .mat-option{margin:0 1px}.cdk-high-contrast-active .mat-option.mat-active{border:solid 1px currentColor;margin:0}.cdk-high-contrast-active .mat-option[aria-disabled=true]{opacity:.5}.mat-option-text{display:inline-block;flex-grow:1;overflow:hidden;text-overflow:ellipsis}.mat-option .mat-option-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-option-pseudo-checkbox{margin-right:8px}[dir=rtl] .mat-option-pseudo-checkbox{margin-left:8px;margin-right:0}\\n\"],encapsulation:2,changeDetection:0}),n})();function cg(n,t,e){if(e.length){let i=t.toArray(),r=e.toArray(),s=0;for(let o=0;o<n+1;o++)i[o].group&&i[o].group===r[s]&&s++;return s}return 0}let Hd=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ti,bt,B,og]]}),n})(),gE=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B],B]}),n})();const Xa=JSON.parse('[{\"from\":{\"name\":\"Everscale\",\"description\":\"Everscale mainnet\",\"url\":\"https://main.ton.dev\"},\"to\":{\"name\":\"Tezos\",\"description\":\"Tezos mainnet\",\"url\":\"https://tzkt.io\"},\"active\":true},{\"from\":{\"name\":\"Tezos\",\"description\":\"Tezos mainnet\",\"url\":\"https://tzkt.io\"},\"to\":{\"name\":\"Everscale\",\"description\":\"Everscale mainnet\",\"url\":\"https://main.ton.dev\"},\"active\":true},{\"from\":{\"name\":\"devnet\",\"description\":\"Everscale devnet\",\"url\":\"https://net.ton.dev\"},\"to\":{\"name\":\"hangzhounet\",\"description\":\"Tezos hangzhounet\",\"url\":\"https://hangzhounet.tzkt.io\"},\"active\":false},{\"from\":{\"name\":\"hangzhounet\",\"description\":\"Tezos hangzhounet\",\"url\":\"https://hangzhounet.tzkt.io\"},\"to\":{\"name\":\"devnet\",\"description\":\"Everscale devnet\",\"url\":\"https://net.ton.dev\"},\"active\":false},{\"from\":{\"name\":\"fld.ton.dev\",\"description\":\"Everscale fld\",\"url\":\"https://gql.custler.net\"},\"to\":{\"name\":\"ithacanet\",\"description\":\"Tezos ithacanet\",\"url\":\"https://ithacanet.tzkt.io\"},\"active\":false},{\"from\":{\"name\":\"ithacanet\",\"description\":\"Tezos ithacanet\",\"url\":\"https://ithacanet.tzkt.io\"},\"to\":{\"name\":\"fld.ton.dev\",\"description\":\"Everscale fld\",\"url\":\"https://gql.custler.net\"},\"active\":false}]'),ug=JSON.parse('[{\"name\":\"wTXZ\",\"type\":\"TIP-3.1\",\"desc\":\"Wrapped Tezos\"},{\"name\":\"SOON\",\"type\":\"TIP-3\",\"desc\":\"Soon\"},{\"name\":\"BRIDGE\",\"type\":\"TIP-3.1\",\"desc\":\"Bridge token\"}]'),hg=JSON.parse('[{\"name\":\"wEVER\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped EVER\"},{\"name\":\"KUSD\",\"type\":\"FA 1.2\",\"desc\":\"Kolibri\"},{\"name\":\"wXTZ\",\"type\":\"FA 1.2\",\"desc\":\"Wrapped Tezos\"},{\"name\":\"USDS\",\"type\":\"FA 2.0\",\"desc\":\"Stably USD\"},{\"name\":\"tzBTC\",\"type\":\"FA 1.2\",\"desc\":\"tzBTC\"},{\"name\":\"STKR\",\"type\":\"FA 1.2\",\"desc\":\"Staker Governance\"},{\"name\":\"USDtz\",\"type\":\"FA 1.2\",\"desc\":\"USDtez\"},{\"name\":\"ETHtz\",\"type\":\"FA 1.2\",\"desc\":\"ETHtez\"},{\"name\":\"hDAO\",\"type\":\"FA 2.0\",\"desc\":\"Hic Et Nunc governance\"},{\"name\":\"WRAP\",\"type\":\"FA 2.0\",\"desc\":\"Wrap Governance\"},{\"name\":\"CRUNCH\",\"type\":\"FA 2.0\",\"desc\":\"CRUNCH\"},{\"name\":\"wAAVE\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped AAVE\"},{\"name\":\"wBUSD\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped BUSD\"},{\"name\":\"wCEL\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped CEL\"},{\"name\":\"wCOMP\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped COMP\"},{\"name\":\"wCRO\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped CRO\"},{\"name\":\"wDAI\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped DAI\"},{\"name\":\"wFTT\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped FTT\"},{\"name\":\"wHT\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped HT\"},{\"name\":\"wHUSD\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped HUSD\"},{\"name\":\"wLEO\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped LEO\"},{\"name\":\"wLINK\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped LINK\"},{\"name\":\"wMATIC\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped MATIC\"},{\"name\":\"wMKR\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped MKR\"},{\"name\":\"wOKB\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped OKB\"},{\"name\":\"wPAX\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped PAX\"},{\"name\":\"wSUSHI\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped SUSHI\"},{\"name\":\"wUNI\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped UNI\"},{\"name\":\"wUSDC\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped USDC\"},{\"name\":\"wUSDT\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped USDT\"},{\"name\":\"wWBTC\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped WBTC\"},{\"name\":\"wWETH\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped WETH\"},{\"name\":\"PLENTY\",\"type\":\"FA 1.2\",\"desc\":\"Plenty DAO\"},{\"name\":\"KALAM\",\"type\":\"FA 2.0\",\"desc\":\"Kalamint\"},{\"name\":\"crDAO\",\"type\":\"FA 2.0\",\"desc\":\"Crunchy DAO\"},{\"name\":\"SMAK\",\"type\":\"FA 1.2\",\"desc\":\"SmartLink\"},{\"name\":\"kDAO\",\"type\":\"FA 1.2\",\"desc\":\"Kolibri DAO\"},{\"name\":\"uUSD\",\"type\":\"FA 2.0\",\"desc\":\"youves uUSD\"},{\"name\":\"uDEFI\",\"type\":\"FA 2.0\",\"desc\":\"youves uDEFI\"},{\"name\":\"bDAO\",\"type\":\"FA 2.0\",\"desc\":\"Bazaar DAO\"},{\"name\":\"YOU\",\"type\":\"FA 2.0\",\"desc\":\"youves YOU governance\"},{\"name\":\"RCKT\",\"type\":\"FA 2.0\",\"desc\":\"Rocket\"},{\"name\":\"rkDAO\",\"type\":\"FA 2.0\",\"desc\":\"Rocket DAO\"},{\"name\":\"UNO\",\"type\":\"FA 2.0\",\"desc\":\"Unobtanium\"},{\"name\":\"GIF\",\"type\":\"FA 2.0\",\"desc\":\"GIF DAO\"},{\"name\":\"IDZ\",\"type\":\"FA 2.0\",\"desc\":\"TezID\"},{\"name\":\"EASY\",\"type\":\"FA 2.0\",\"desc\":\"CryptoEasy\"},{\"name\":\"INSTA\",\"type\":\"FA 2.0\",\"desc\":\"Instaraise\"},{\"name\":\"xPLENTY\",\"type\":\"FA 1.2\",\"desc\":\"xPLENTY\"},{\"name\":\"ctez\",\"type\":\"FA 1.2\",\"desc\":\"Ctez\"},{\"name\":\"PAUL\",\"type\":\"FA 1.2\",\"desc\":\"PAUL Token\"},{\"name\":\"SPI\",\"type\":\"FA 2.0\",\"desc\":\"Spice Token\"},{\"name\":\"WTZ\",\"type\":\"FA 2.0\",\"desc\":\"WTZ\"},{\"name\":\"FLAME\",\"type\":\"FA 2.0\",\"desc\":\"FLAME\"},{\"name\":\"fDAO\",\"type\":\"FA 2.0\",\"desc\":\"fDAO\"},{\"name\":\"PXL\",\"type\":\"FA 2.0\",\"desc\":\"Pixel\"},{\"name\":\"sDAO\",\"type\":\"FA 2.0\",\"desc\":\"Salsa DAO\"},{\"name\":\"akaDAO\",\"type\":\"FA 2.0\",\"desc\":\"akaSwap DAO\"},{\"name\":\"MIN\",\"type\":\"FA 2.0\",\"desc\":\"Minerals\"},{\"name\":\"ENR\",\"type\":\"FA 2.0\",\"desc\":\"Energy\"},{\"name\":\"MCH\",\"type\":\"FA 2.0\",\"desc\":\"Machinery\"},{\"name\":\"uBTC\",\"type\":\"FA 2.0\",\"desc\":\"youves uBTC\"},{\"name\":\"MTRIA\",\"type\":\"FA 2.0\",\"desc\":\"Materia\"},{\"name\":\"DOGA\",\"type\":\"FA 1.2\",\"desc\":\"DOGAMI\"}]'),_E=[\"*\"];class pU{constructor(){this.columnIndex=0,this.rowIndex=0}get rowCount(){return this.rowIndex+1}get rowspan(){const t=Math.max(...this.tracker);return t>1?this.rowCount+t-1:this.rowCount}update(t,e){this.columnIndex=0,this.rowIndex=0,this.tracker=new Array(t),this.tracker.fill(0,0,this.tracker.length),this.positions=e.map(i=>this._trackTile(i))}_trackTile(t){const e=this._findMatchingGap(t.colspan);return this._markTilePosition(e,t),this.columnIndex=e+t.colspan,new fU(this.rowIndex,e)}_findMatchingGap(t){let e=-1,i=-1;do{this.columnIndex+t>this.tracker.length?(this._nextRow(),e=this.tracker.indexOf(0,this.columnIndex),i=this._findGapEndIndex(e)):(e=this.tracker.indexOf(0,this.columnIndex),-1!=e?(i=this._findGapEndIndex(e),this.columnIndex=e+1):(this._nextRow(),e=this.tracker.indexOf(0,this.columnIndex),i=this._findGapEndIndex(e)))}while(i-e<t||0==i);return Math.max(e,0)}_nextRow(){this.columnIndex=0,this.rowIndex++;for(let t=0;t<this.tracker.length;t++)this.tracker[t]=Math.max(0,this.tracker[t]-1)}_findGapEndIndex(t){for(let e=t+1;e<this.tracker.length;e++)if(0!=this.tracker[e])return e;return this.tracker.length}_markTilePosition(t,e){for(let i=0;i<e.colspan;i++)this.tracker[t+i]=e.rowspan}}class fU{constructor(t,e){this.row=t,this.col=e}}const vE=new b(\"MAT_GRID_LIST\");let yE=(()=>{class n{constructor(e,i){this._element=e,this._gridList=i,this._rowspan=1,this._colspan=1}get rowspan(){return this._rowspan}set rowspan(e){this._rowspan=Math.round(Et(e))}get colspan(){return this._colspan}set colspan(e){this._colspan=Math.round(Et(e))}_setStyle(e,i){this._element.nativeElement.style[e]=i}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(vE,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-grid-tile\"]],hostAttrs:[1,\"mat-grid-tile\"],hostVars:2,hostBindings:function(e,i){2&e&&Z(\"rowspan\",i.rowspan)(\"colspan\",i.colspan)},inputs:{rowspan:\"rowspan\",colspan:\"colspan\"},exportAs:[\"matGridTile\"],ngContentSelectors:_E,decls:2,vars:0,consts:[[1,\"mat-grid-tile-content\"]],template:function(e,i){1&e&&(Lt(),x(0,\"div\",0),Pe(1),S())},styles:[\".mat-grid-list{display:block;position:relative}.mat-grid-tile{display:block;position:absolute;overflow:hidden}.mat-grid-tile .mat-grid-tile-header,.mat-grid-tile .mat-grid-tile-footer{display:flex;align-items:center;height:48px;color:#fff;background:rgba(0,0,0,.38);overflow:hidden;padding:0 16px;position:absolute;left:0;right:0}.mat-grid-tile .mat-grid-tile-header>*,.mat-grid-tile .mat-grid-tile-footer>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-grid-tile .mat-grid-tile-header.mat-2-line,.mat-grid-tile .mat-grid-tile-footer.mat-2-line{height:68px}.mat-grid-tile .mat-grid-list-text{display:flex;flex-direction:column;flex:auto;box-sizing:border-box;overflow:hidden}.mat-grid-tile .mat-grid-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-grid-tile .mat-grid-list-text:empty{display:none}.mat-grid-tile .mat-grid-tile-header{top:0}.mat-grid-tile .mat-grid-tile-footer{bottom:0}.mat-grid-tile .mat-grid-avatar{padding-right:16px}[dir=rtl] .mat-grid-tile .mat-grid-avatar{padding-right:0;padding-left:16px}.mat-grid-tile .mat-grid-avatar:empty{display:none}.mat-grid-tile-content{top:0;left:0;right:0;bottom:0;position:absolute;display:flex;align-items:center;justify-content:center;height:100%;padding:0;margin:0}\\n\"],encapsulation:2,changeDetection:0}),n})();const mU=/^-?\\d+((\\.\\d+)?[A-Za-z%$]?)+$/;class pg{constructor(){this._rows=0,this._rowspan=0}init(t,e,i,r){this._gutterSize=bE(t),this._rows=e.rowCount,this._rowspan=e.rowspan,this._cols=i,this._direction=r}getBaseTileSize(t,e){return`(${t}% - (${this._gutterSize} * ${e}))`}getTilePosition(t,e){return 0===e?\"0\":Xr(`(${t} + ${this._gutterSize}) * ${e}`)}getTileSize(t,e){return`(${t} * ${e}) + (${e-1} * ${this._gutterSize})`}setStyle(t,e,i){let r=100/this._cols,s=(this._cols-1)/this._cols;this.setColStyles(t,i,r,s),this.setRowStyles(t,e,r,s)}setColStyles(t,e,i,r){let s=this.getBaseTileSize(i,r);t._setStyle(\"rtl\"===this._direction?\"right\":\"left\",this.getTilePosition(s,e)),t._setStyle(\"width\",Xr(this.getTileSize(s,t.colspan)))}getGutterSpan(){return`${this._gutterSize} * (${this._rowspan} - 1)`}getTileSpan(t){return`${this._rowspan} * ${this.getTileSize(t,1)}`}getComputedHeight(){return null}}class gU extends pg{constructor(t){super(),this.fixedRowHeight=t}init(t,e,i,r){super.init(t,e,i,r),this.fixedRowHeight=bE(this.fixedRowHeight),mU.test(this.fixedRowHeight)}setRowStyles(t,e){t._setStyle(\"top\",this.getTilePosition(this.fixedRowHeight,e)),t._setStyle(\"height\",Xr(this.getTileSize(this.fixedRowHeight,t.rowspan)))}getComputedHeight(){return[\"height\",Xr(`${this.getTileSpan(this.fixedRowHeight)} + ${this.getGutterSpan()}`)]}reset(t){t._setListStyle([\"height\",null]),t._tiles&&t._tiles.forEach(e=>{e._setStyle(\"top\",null),e._setStyle(\"height\",null)})}}class _U extends pg{constructor(t){super(),this._parseRatio(t)}setRowStyles(t,e,i,r){this.baseTileHeight=this.getBaseTileSize(i/this.rowHeightRatio,r),t._setStyle(\"marginTop\",this.getTilePosition(this.baseTileHeight,e)),t._setStyle(\"paddingTop\",Xr(this.getTileSize(this.baseTileHeight,t.rowspan)))}getComputedHeight(){return[\"paddingBottom\",Xr(`${this.getTileSpan(this.baseTileHeight)} + ${this.getGutterSpan()}`)]}reset(t){t._setListStyle([\"paddingBottom\",null]),t._tiles.forEach(e=>{e._setStyle(\"marginTop\",null),e._setStyle(\"paddingTop\",null)})}_parseRatio(t){const e=t.split(\":\");this.rowHeightRatio=parseFloat(e[0])/parseFloat(e[1])}}class vU extends pg{setRowStyles(t,e){let s=this.getBaseTileSize(100/this._rowspan,(this._rows-1)/this._rows);t._setStyle(\"top\",this.getTilePosition(s,e)),t._setStyle(\"height\",Xr(this.getTileSize(s,t.rowspan)))}reset(t){t._tiles&&t._tiles.forEach(e=>{e._setStyle(\"top\",null),e._setStyle(\"height\",null)})}}function Xr(n){return`calc(${n})`}function bE(n){return n.match(/([A-Za-z%]+)$/)?n:`${n}px`}let bU=(()=>{class n{constructor(e,i){this._element=e,this._dir=i,this._gutter=\"1px\"}get cols(){return this._cols}set cols(e){this._cols=Math.max(1,Math.round(Et(e)))}get gutterSize(){return this._gutter}set gutterSize(e){this._gutter=`${null==e?\"\":e}`}get rowHeight(){return this._rowHeight}set rowHeight(e){const i=`${null==e?\"\":e}`;i!==this._rowHeight&&(this._rowHeight=i,this._setTileStyler(this._rowHeight))}ngOnInit(){this._checkCols(),this._checkRowHeight()}ngAfterContentChecked(){this._layoutTiles()}_checkCols(){}_checkRowHeight(){this._rowHeight||this._setTileStyler(\"1:1\")}_setTileStyler(e){this._tileStyler&&this._tileStyler.reset(this),this._tileStyler=\"fit\"===e?new vU:e&&e.indexOf(\":\")>-1?new _U(e):new gU(e)}_layoutTiles(){this._tileCoordinator||(this._tileCoordinator=new pU);const e=this._tileCoordinator,i=this._tiles.filter(s=>!s._gridList||s._gridList===this),r=this._dir?this._dir.value:\"ltr\";this._tileCoordinator.update(this.cols,i),this._tileStyler.init(this.gutterSize,e,this.cols,r),i.forEach((s,o)=>{const a=e.positions[o];this._tileStyler.setStyle(s,a.row,a.col)}),this._setListStyle(this._tileStyler.getComputedHeight())}_setListStyle(e){e&&(this._element.nativeElement.style[e[0]]=e[1])}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(On,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-grid-list\"]],contentQueries:function(e,i,r){if(1&e&&ve(r,yE,5),2&e){let s;z(s=U())&&(i._tiles=s)}},hostAttrs:[1,\"mat-grid-list\"],hostVars:1,hostBindings:function(e,i){2&e&&Z(\"cols\",i.cols)},inputs:{cols:\"cols\",gutterSize:\"gutterSize\",rowHeight:\"rowHeight\"},exportAs:[\"matGridList\"],features:[L([{provide:vE,useExisting:n}])],ngContentSelectors:_E,decls:2,vars:0,template:function(e,i){1&e&&(Lt(),x(0,\"div\"),Pe(1),S())},styles:[\".mat-grid-list{display:block;position:relative}.mat-grid-tile{display:block;position:absolute;overflow:hidden}.mat-grid-tile .mat-grid-tile-header,.mat-grid-tile .mat-grid-tile-footer{display:flex;align-items:center;height:48px;color:#fff;background:rgba(0,0,0,.38);overflow:hidden;padding:0 16px;position:absolute;left:0;right:0}.mat-grid-tile .mat-grid-tile-header>*,.mat-grid-tile .mat-grid-tile-footer>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-grid-tile .mat-grid-tile-header.mat-2-line,.mat-grid-tile .mat-grid-tile-footer.mat-2-line{height:68px}.mat-grid-tile .mat-grid-list-text{display:flex;flex-direction:column;flex:auto;box-sizing:border-box;overflow:hidden}.mat-grid-tile .mat-grid-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-grid-tile .mat-grid-list-text:empty{display:none}.mat-grid-tile .mat-grid-tile-header{top:0}.mat-grid-tile .mat-grid-tile-footer{bottom:0}.mat-grid-tile .mat-grid-avatar{padding-right:16px}[dir=rtl] .mat-grid-tile .mat-grid-avatar{padding-right:0;padding-left:16px}.mat-grid-tile .mat-grid-avatar:empty{display:none}.mat-grid-tile-content{top:0;left:0;right:0;bottom:0;position:absolute;display:flex;align-items:center;justify-content:center;height:100%;padding:0;margin:0}\\n\"],encapsulation:2,changeDetection:0}),n})(),CU=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Vd,B],Vd,B]}),n})();const DU=[\"addListener\",\"removeListener\"],wU=[\"addEventListener\",\"removeEventListener\"],MU=[\"on\",\"off\"];function Jr(n,t,e,i){if(De(e)&&(i=e,e=void 0),i)return Jr(n,t,e).pipe(bf(i));const[r,s]=function SU(n){return De(n.addEventListener)&&De(n.removeEventListener)}(n)?wU.map(o=>a=>n[o](t,a,e)):function xU(n){return De(n.addListener)&&De(n.removeListener)}(n)?DU.map(CE(n,t)):function EU(n){return De(n.on)&&De(n.off)}(n)?MU.map(CE(n,t)):[];if(!r&&bu(n))return lt(o=>Jr(o,t,e))(Jt(n));if(!r)throw new TypeError(\"Invalid event target\");return new Ve(o=>{const a=(...l)=>o.next(1<l.length?l:l[0]);return r(a),()=>s(a)})}function CE(n,t){return e=>i=>n[e](t,i)}const kU=[\"connectionContainer\"],TU=[\"inputContainer\"],AU=[\"label\"];function IU(n,t){1&n&&(kr(0),x(1,\"div\",14),Le(2,\"div\",15)(3,\"div\",16)(4,\"div\",17),S(),x(5,\"div\",18),Le(6,\"div\",15)(7,\"div\",16)(8,\"div\",17),S(),Tr())}function RU(n,t){if(1&n){const e=ia();x(0,\"div\",19),J(\"cdkObserveContent\",function(){return Dr(e),Be().updateOutlineGap()}),Pe(1,1),S()}2&n&&N(\"cdkObserveContentDisabled\",\"outline\"!=Be().appearance)}function OU(n,t){if(1&n&&(kr(0),Pe(1,2),x(2,\"span\"),we(3),S(),Tr()),2&n){const e=Be(2);T(3),Ut(e._control.placeholder)}}function PU(n,t){1&n&&Pe(0,3,[\"*ngSwitchCase\",\"true\"])}function FU(n,t){1&n&&(x(0,\"span\",23),we(1,\" *\"),S())}function NU(n,t){if(1&n){const e=ia();x(0,\"label\",20,21),J(\"cdkObserveContent\",function(){return Dr(e),Be().updateOutlineGap()}),Ee(2,OU,4,1,\"ng-container\",12),Ee(3,PU,1,0,\"ng-content\",12),Ee(4,FU,2,0,\"span\",22),S()}if(2&n){const e=Be();Ae(\"mat-empty\",e._control.empty&&!e._shouldAlwaysFloat())(\"mat-form-field-empty\",e._control.empty&&!e._shouldAlwaysFloat())(\"mat-accent\",\"accent\"==e.color)(\"mat-warn\",\"warn\"==e.color),N(\"cdkObserveContentDisabled\",\"outline\"!=e.appearance)(\"id\",e._labelId)(\"ngSwitch\",e._hasLabel()),Z(\"for\",e._control.id)(\"aria-owns\",e._control.id),T(2),N(\"ngSwitchCase\",!1),T(1),N(\"ngSwitchCase\",!0),T(1),N(\"ngIf\",!e.hideRequiredMarker&&e._control.required&&!e._control.disabled)}}function LU(n,t){1&n&&(x(0,\"div\",24),Pe(1,4),S())}function BU(n,t){if(1&n&&(x(0,\"div\",25),Le(1,\"span\",26),S()),2&n){const e=Be();T(1),Ae(\"mat-accent\",\"accent\"==e.color)(\"mat-warn\",\"warn\"==e.color)}}function VU(n,t){1&n&&(x(0,\"div\"),Pe(1,5),S()),2&n&&N(\"@transitionMessages\",Be()._subscriptAnimationState)}function HU(n,t){if(1&n&&(x(0,\"div\",30),we(1),S()),2&n){const e=Be(2);N(\"id\",e._hintLabelId),T(1),Ut(e.hintLabel)}}function jU(n,t){if(1&n&&(x(0,\"div\",27),Ee(1,HU,2,2,\"div\",28),Pe(2,6),Le(3,\"div\",29),Pe(4,7),S()),2&n){const e=Be();N(\"@transitionMessages\",e._subscriptAnimationState),T(1),N(\"ngIf\",e.hintLabel)}}const zU=[\"*\",[[\"\",\"matPrefix\",\"\"]],[[\"mat-placeholder\"]],[[\"mat-label\"]],[[\"\",\"matSuffix\",\"\"]],[[\"mat-error\"]],[[\"mat-hint\",3,\"align\",\"end\"]],[[\"mat-hint\",\"align\",\"end\"]]],UU=[\"*\",\"[matPrefix]\",\"mat-placeholder\",\"mat-label\",\"[matSuffix]\",\"mat-error\",\"mat-hint:not([align='end'])\",\"mat-hint[align='end']\"];let $U=0;const DE=new b(\"MatError\");let GU=(()=>{class n{constructor(e,i){this.id=\"mat-error-\"+$U++,e||i.nativeElement.setAttribute(\"aria-live\",\"polite\")}}return n.\\u0275fac=function(e){return new(e||n)(kt(\"aria-live\"),f(W))},n.\\u0275dir=C({type:n,selectors:[[\"mat-error\"]],hostAttrs:[\"aria-atomic\",\"true\",1,\"mat-error\"],hostVars:1,hostBindings:function(e,i){2&e&&Z(\"id\",i.id)},inputs:{id:\"id\"},features:[L([{provide:DE,useExisting:n}])]}),n})();const WU={transitionMessages:Ke(\"transitionMessages\",[ae(\"enter\",R({opacity:1,transform:\"translateY(0%)\"})),ge(\"void => enter\",[R({opacity:0,transform:\"translateY(-5px)\"}),be(\"300ms cubic-bezier(0.55, 0, 0.55, 0.2)\")])])};let Ja=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n}),n})(),qU=0;const wE=new b(\"MatHint\");let YU=(()=>{class n{constructor(){this.align=\"start\",this.id=\"mat-hint-\"+qU++}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n,selectors:[[\"mat-hint\"]],hostAttrs:[1,\"mat-hint\"],hostVars:4,hostBindings:function(e,i){2&e&&(Z(\"id\",i.id)(\"align\",null),Ae(\"mat-form-field-hint-end\",\"end\"===i.align))},inputs:{align:\"align\",id:\"id\"},features:[L([{provide:wE,useExisting:n}])]}),n})(),fg=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n,selectors:[[\"mat-label\"]]}),n})(),QU=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n,selectors:[[\"mat-placeholder\"]]}),n})();const KU=new b(\"MatPrefix\"),ZU=new b(\"MatSuffix\");let ME=0;const JU=fo(class{constructor(n){this._elementRef=n}},\"primary\"),e5=new b(\"MAT_FORM_FIELD_DEFAULT_OPTIONS\"),el=new b(\"MatFormField\");let t5=(()=>{class n extends JU{constructor(e,i,r,s,o,a,l){super(e),this._changeDetectorRef=i,this._dir=r,this._defaults=s,this._platform=o,this._ngZone=a,this._outlineGapCalculationNeededImmediately=!1,this._outlineGapCalculationNeededOnStable=!1,this._destroyed=new O,this._showAlwaysAnimate=!1,this._subscriptAnimationState=\"\",this._hintLabel=\"\",this._hintLabelId=\"mat-hint-\"+ME++,this._labelId=\"mat-form-field-label-\"+ME++,this.floatLabel=this._getDefaultFloatLabelState(),this._animationsEnabled=\"NoopAnimations\"!==l,this.appearance=s&&s.appearance?s.appearance:\"legacy\",this._hideRequiredMarker=!(!s||null==s.hideRequiredMarker)&&s.hideRequiredMarker}get appearance(){return this._appearance}set appearance(e){const i=this._appearance;this._appearance=e||this._defaults&&this._defaults.appearance||\"legacy\",\"outline\"===this._appearance&&i!==e&&(this._outlineGapCalculationNeededOnStable=!0)}get hideRequiredMarker(){return this._hideRequiredMarker}set hideRequiredMarker(e){this._hideRequiredMarker=G(e)}_shouldAlwaysFloat(){return\"always\"===this.floatLabel&&!this._showAlwaysAnimate}_canLabelFloat(){return\"never\"!==this.floatLabel}get hintLabel(){return this._hintLabel}set hintLabel(e){this._hintLabel=e,this._processHints()}get floatLabel(){return\"legacy\"!==this.appearance&&\"never\"===this._floatLabel?\"auto\":this._floatLabel}set floatLabel(e){e!==this._floatLabel&&(this._floatLabel=e||this._getDefaultFloatLabelState(),this._changeDetectorRef.markForCheck())}get _control(){return this._explicitFormFieldControl||this._controlNonStatic||this._controlStatic}set _control(e){this._explicitFormFieldControl=e}getLabelId(){return this._hasFloatingLabel()?this._labelId:null}getConnectedOverlayOrigin(){return this._connectionContainerRef||this._elementRef}ngAfterContentInit(){this._validateControlChild();const e=this._control;e.controlType&&this._elementRef.nativeElement.classList.add(`mat-form-field-type-${e.controlType}`),e.stateChanges.pipe(Xn(null)).subscribe(()=>{this._validatePlaceholders(),this._syncDescribedByIds(),this._changeDetectorRef.markForCheck()}),e.ngControl&&e.ngControl.valueChanges&&e.ngControl.valueChanges.pipe(Ie(this._destroyed)).subscribe(()=>this._changeDetectorRef.markForCheck()),this._ngZone.runOutsideAngular(()=>{this._ngZone.onStable.pipe(Ie(this._destroyed)).subscribe(()=>{this._outlineGapCalculationNeededOnStable&&this.updateOutlineGap()})}),Bt(this._prefixChildren.changes,this._suffixChildren.changes).subscribe(()=>{this._outlineGapCalculationNeededOnStable=!0,this._changeDetectorRef.markForCheck()}),this._hintChildren.changes.pipe(Xn(null)).subscribe(()=>{this._processHints(),this._changeDetectorRef.markForCheck()}),this._errorChildren.changes.pipe(Xn(null)).subscribe(()=>{this._syncDescribedByIds(),this._changeDetectorRef.markForCheck()}),this._dir&&this._dir.change.pipe(Ie(this._destroyed)).subscribe(()=>{\"function\"==typeof requestAnimationFrame?this._ngZone.runOutsideAngular(()=>{requestAnimationFrame(()=>this.updateOutlineGap())}):this.updateOutlineGap()})}ngAfterContentChecked(){this._validateControlChild(),this._outlineGapCalculationNeededImmediately&&this.updateOutlineGap()}ngAfterViewInit(){this._subscriptAnimationState=\"enter\",this._changeDetectorRef.detectChanges()}ngOnDestroy(){this._destroyed.next(),this._destroyed.complete()}_shouldForward(e){const i=this._control?this._control.ngControl:null;return i&&i[e]}_hasPlaceholder(){return!!(this._control&&this._control.placeholder||this._placeholderChild)}_hasLabel(){return!(!this._labelChildNonStatic&&!this._labelChildStatic)}_shouldLabelFloat(){return this._canLabelFloat()&&(this._control&&this._control.shouldLabelFloat||this._shouldAlwaysFloat())}_hideControlPlaceholder(){return\"legacy\"===this.appearance&&!this._hasLabel()||this._hasLabel()&&!this._shouldLabelFloat()}_hasFloatingLabel(){return this._hasLabel()||\"legacy\"===this.appearance&&this._hasPlaceholder()}_getDisplayedMessages(){return this._errorChildren&&this._errorChildren.length>0&&this._control.errorState?\"error\":\"hint\"}_animateAndLockLabel(){this._hasFloatingLabel()&&this._canLabelFloat()&&(this._animationsEnabled&&this._label&&(this._showAlwaysAnimate=!0,Jr(this._label.nativeElement,\"transitionend\").pipe(it(1)).subscribe(()=>{this._showAlwaysAnimate=!1})),this.floatLabel=\"always\",this._changeDetectorRef.markForCheck())}_validatePlaceholders(){}_processHints(){this._validateHints(),this._syncDescribedByIds()}_validateHints(){}_getDefaultFloatLabelState(){return this._defaults&&this._defaults.floatLabel||\"auto\"}_syncDescribedByIds(){if(this._control){let e=[];if(this._control.userAriaDescribedBy&&\"string\"==typeof this._control.userAriaDescribedBy&&e.push(...this._control.userAriaDescribedBy.split(\" \")),\"hint\"===this._getDisplayedMessages()){const i=this._hintChildren?this._hintChildren.find(s=>\"start\"===s.align):null,r=this._hintChildren?this._hintChildren.find(s=>\"end\"===s.align):null;i?e.push(i.id):this._hintLabel&&e.push(this._hintLabelId),r&&e.push(r.id)}else this._errorChildren&&e.push(...this._errorChildren.map(i=>i.id));this._control.setDescribedByIds(e)}}_validateControlChild(){}updateOutlineGap(){const e=this._label?this._label.nativeElement:null,i=this._connectionContainerRef.nativeElement,r=\".mat-form-field-outline-start\",s=\".mat-form-field-outline-gap\";if(\"outline\"!==this.appearance||!this._platform.isBrowser)return;if(!e||!e.children.length||!e.textContent.trim()){const d=i.querySelectorAll(`${r}, ${s}`);for(let u=0;u<d.length;u++)d[u].style.width=\"0\";return}if(!this._isAttachedToDOM())return void(this._outlineGapCalculationNeededImmediately=!0);let o=0,a=0;const l=i.querySelectorAll(r),c=i.querySelectorAll(s);if(this._label&&this._label.nativeElement.children.length){const d=i.getBoundingClientRect();if(0===d.width&&0===d.height)return this._outlineGapCalculationNeededOnStable=!0,void(this._outlineGapCalculationNeededImmediately=!1);const u=this._getStartEnd(d),h=e.children,p=this._getStartEnd(h[0].getBoundingClientRect());let m=0;for(let g=0;g<h.length;g++)m+=h[g].offsetWidth;o=Math.abs(p-u)-5,a=m>0?.75*m+10:0}for(let d=0;d<l.length;d++)l[d].style.width=`${o}px`;for(let d=0;d<c.length;d++)c[d].style.width=`${a}px`;this._outlineGapCalculationNeededOnStable=this._outlineGapCalculationNeededImmediately=!1}_getStartEnd(e){return this._dir&&\"rtl\"===this._dir.value?e.right:e.left}_isAttachedToDOM(){const e=this._elementRef.nativeElement;if(e.getRootNode){const i=e.getRootNode();return i&&i!==e}return document.documentElement.contains(e)}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(Ye),f(On,8),f(e5,8),f(It),f(ne),f(Rn,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-form-field\"]],contentQueries:function(e,i,r){if(1&e&&(ve(r,Ja,5),ve(r,Ja,7),ve(r,fg,5),ve(r,fg,7),ve(r,QU,5),ve(r,DE,5),ve(r,wE,5),ve(r,KU,5),ve(r,ZU,5)),2&e){let s;z(s=U())&&(i._controlNonStatic=s.first),z(s=U())&&(i._controlStatic=s.first),z(s=U())&&(i._labelChildNonStatic=s.first),z(s=U())&&(i._labelChildStatic=s.first),z(s=U())&&(i._placeholderChild=s.first),z(s=U())&&(i._errorChildren=s),z(s=U())&&(i._hintChildren=s),z(s=U())&&(i._prefixChildren=s),z(s=U())&&(i._suffixChildren=s)}},viewQuery:function(e,i){if(1&e&&(je(kU,7),je(TU,5),je(AU,5)),2&e){let r;z(r=U())&&(i._connectionContainerRef=r.first),z(r=U())&&(i._inputContainerRef=r.first),z(r=U())&&(i._label=r.first)}},hostAttrs:[1,\"mat-form-field\"],hostVars:40,hostBindings:function(e,i){2&e&&Ae(\"mat-form-field-appearance-standard\",\"standard\"==i.appearance)(\"mat-form-field-appearance-fill\",\"fill\"==i.appearance)(\"mat-form-field-appearance-outline\",\"outline\"==i.appearance)(\"mat-form-field-appearance-legacy\",\"legacy\"==i.appearance)(\"mat-form-field-invalid\",i._control.errorState)(\"mat-form-field-can-float\",i._canLabelFloat())(\"mat-form-field-should-float\",i._shouldLabelFloat())(\"mat-form-field-has-label\",i._hasFloatingLabel())(\"mat-form-field-hide-placeholder\",i._hideControlPlaceholder())(\"mat-form-field-disabled\",i._control.disabled)(\"mat-form-field-autofilled\",i._control.autofilled)(\"mat-focused\",i._control.focused)(\"ng-untouched\",i._shouldForward(\"untouched\"))(\"ng-touched\",i._shouldForward(\"touched\"))(\"ng-pristine\",i._shouldForward(\"pristine\"))(\"ng-dirty\",i._shouldForward(\"dirty\"))(\"ng-valid\",i._shouldForward(\"valid\"))(\"ng-invalid\",i._shouldForward(\"invalid\"))(\"ng-pending\",i._shouldForward(\"pending\"))(\"_mat-animation-noopable\",!i._animationsEnabled)},inputs:{color:\"color\",appearance:\"appearance\",hideRequiredMarker:\"hideRequiredMarker\",hintLabel:\"hintLabel\",floatLabel:\"floatLabel\"},exportAs:[\"matFormField\"],features:[L([{provide:el,useExisting:n}]),E],ngContentSelectors:UU,decls:15,vars:8,consts:[[1,\"mat-form-field-wrapper\"],[1,\"mat-form-field-flex\",3,\"click\"],[\"connectionContainer\",\"\"],[4,\"ngIf\"],[\"class\",\"mat-form-field-prefix\",3,\"cdkObserveContentDisabled\",\"cdkObserveContent\",4,\"ngIf\"],[1,\"mat-form-field-infix\"],[\"inputContainer\",\"\"],[1,\"mat-form-field-label-wrapper\"],[\"class\",\"mat-form-field-label\",3,\"cdkObserveContentDisabled\",\"id\",\"mat-empty\",\"mat-form-field-empty\",\"mat-accent\",\"mat-warn\",\"ngSwitch\",\"cdkObserveContent\",4,\"ngIf\"],[\"class\",\"mat-form-field-suffix\",4,\"ngIf\"],[\"class\",\"mat-form-field-underline\",4,\"ngIf\"],[1,\"mat-form-field-subscript-wrapper\",3,\"ngSwitch\"],[4,\"ngSwitchCase\"],[\"class\",\"mat-form-field-hint-wrapper\",4,\"ngSwitchCase\"],[1,\"mat-form-field-outline\"],[1,\"mat-form-field-outline-start\"],[1,\"mat-form-field-outline-gap\"],[1,\"mat-form-field-outline-end\"],[1,\"mat-form-field-outline\",\"mat-form-field-outline-thick\"],[1,\"mat-form-field-prefix\",3,\"cdkObserveContentDisabled\",\"cdkObserveContent\"],[1,\"mat-form-field-label\",3,\"cdkObserveContentDisabled\",\"id\",\"ngSwitch\",\"cdkObserveContent\"],[\"label\",\"\"],[\"class\",\"mat-placeholder-required mat-form-field-required-marker\",\"aria-hidden\",\"true\",4,\"ngIf\"],[\"aria-hidden\",\"true\",1,\"mat-placeholder-required\",\"mat-form-field-required-marker\"],[1,\"mat-form-field-suffix\"],[1,\"mat-form-field-underline\"],[1,\"mat-form-field-ripple\"],[1,\"mat-form-field-hint-wrapper\"],[\"class\",\"mat-hint\",3,\"id\",4,\"ngIf\"],[1,\"mat-form-field-hint-spacer\"],[1,\"mat-hint\",3,\"id\"]],template:function(e,i){1&e&&(Lt(zU),x(0,\"div\",0)(1,\"div\",1,2),J(\"click\",function(s){return i._control.onContainerClick&&i._control.onContainerClick(s)}),Ee(3,IU,9,0,\"ng-container\",3),Ee(4,RU,2,1,\"div\",4),x(5,\"div\",5,6),Pe(7),x(8,\"span\",7),Ee(9,NU,5,16,\"label\",8),S()(),Ee(10,LU,2,0,\"div\",9),S(),Ee(11,BU,2,4,\"div\",10),x(12,\"div\",11),Ee(13,VU,2,1,\"div\",12),Ee(14,jU,5,2,\"div\",13),S()()),2&e&&(T(3),N(\"ngIf\",\"outline\"==i.appearance),T(1),N(\"ngIf\",i._prefixChildren.length),T(5),N(\"ngIf\",i._hasFloatingLabel()),T(1),N(\"ngIf\",i._suffixChildren.length),T(1),N(\"ngIf\",\"outline\"!=i.appearance),T(1),N(\"ngSwitch\",i._getDisplayedMessages()),T(1),N(\"ngSwitchCase\",\"error\"),T(1),N(\"ngSwitchCase\",\"hint\"))},directives:[Ca,Qm,Ys,Pc],styles:[\".mat-form-field{display:inline-block;position:relative;text-align:left}[dir=rtl] .mat-form-field{text-align:right}.mat-form-field-wrapper{position:relative}.mat-form-field-flex{display:inline-flex;align-items:baseline;box-sizing:border-box;width:100%}.mat-form-field-prefix,.mat-form-field-suffix{white-space:nowrap;flex:none;position:relative}.mat-form-field-infix{display:block;position:relative;flex:auto;min-width:0;width:180px}.cdk-high-contrast-active .mat-form-field-infix{border-image:linear-gradient(transparent, transparent)}.mat-form-field-label-wrapper{position:absolute;left:0;box-sizing:content-box;width:100%;height:100%;overflow:hidden;pointer-events:none}[dir=rtl] .mat-form-field-label-wrapper{left:auto;right:0}.mat-form-field-label{position:absolute;left:0;font:inherit;pointer-events:none;width:100%;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;transform-origin:0 0;transition:transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1),color 400ms cubic-bezier(0.25, 0.8, 0.25, 1),width 400ms cubic-bezier(0.25, 0.8, 0.25, 1);display:none}[dir=rtl] .mat-form-field-label{transform-origin:100% 0;left:auto;right:0}.cdk-high-contrast-active .mat-form-field-disabled .mat-form-field-label{color:GrayText}.mat-form-field-empty.mat-form-field-label,.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-label{display:block}.mat-form-field-autofill-control:-webkit-autofill+.mat-form-field-label-wrapper .mat-form-field-label{display:none}.mat-form-field-can-float .mat-form-field-autofill-control:-webkit-autofill+.mat-form-field-label-wrapper .mat-form-field-label{display:block;transition:none}.mat-input-server:focus+.mat-form-field-label-wrapper .mat-form-field-label,.mat-input-server[placeholder]:not(:placeholder-shown)+.mat-form-field-label-wrapper .mat-form-field-label{display:none}.mat-form-field-can-float .mat-input-server:focus+.mat-form-field-label-wrapper .mat-form-field-label,.mat-form-field-can-float .mat-input-server[placeholder]:not(:placeholder-shown)+.mat-form-field-label-wrapper .mat-form-field-label{display:block}.mat-form-field-label:not(.mat-form-field-empty){transition:none}.mat-form-field-underline{position:absolute;width:100%;pointer-events:none;transform:scale3d(1, 1.0001, 1)}.mat-form-field-ripple{position:absolute;left:0;width:100%;transform-origin:50%;transform:scaleX(0.5);opacity:0;transition:background-color 300ms cubic-bezier(0.55, 0, 0.55, 0.2)}.mat-form-field.mat-focused .mat-form-field-ripple,.mat-form-field.mat-form-field-invalid .mat-form-field-ripple{opacity:1;transform:none;transition:transform 300ms cubic-bezier(0.25, 0.8, 0.25, 1),opacity 100ms cubic-bezier(0.25, 0.8, 0.25, 1),background-color 300ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-subscript-wrapper{position:absolute;box-sizing:border-box;width:100%;overflow:hidden}.mat-form-field-subscript-wrapper .mat-icon,.mat-form-field-label-wrapper .mat-icon{width:1em;height:1em;font-size:inherit;vertical-align:baseline}.mat-form-field-hint-wrapper{display:flex}.mat-form-field-hint-spacer{flex:1 0 1em}.mat-error{display:block}.mat-form-field-control-wrapper{position:relative}.mat-form-field-hint-end{order:1}.mat-form-field._mat-animation-noopable .mat-form-field-label,.mat-form-field._mat-animation-noopable .mat-form-field-ripple{transition:none}\\n\",'.mat-form-field-appearance-fill .mat-form-field-flex{border-radius:4px 4px 0 0;padding:.75em .75em 0 .75em}.cdk-high-contrast-active .mat-form-field-appearance-fill .mat-form-field-flex{outline:solid 1px}.cdk-high-contrast-active .mat-form-field-appearance-fill.mat-form-field-disabled .mat-form-field-flex{outline-color:GrayText}.cdk-high-contrast-active .mat-form-field-appearance-fill.mat-focused .mat-form-field-flex{outline:dashed 3px}.mat-form-field-appearance-fill .mat-form-field-underline::before{content:\"\";display:block;position:absolute;bottom:0;height:1px;width:100%}.mat-form-field-appearance-fill .mat-form-field-ripple{bottom:0;height:2px}.cdk-high-contrast-active .mat-form-field-appearance-fill .mat-form-field-ripple{height:0}.mat-form-field-appearance-fill:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-underline .mat-form-field-ripple{opacity:1;transform:none;transition:opacity 600ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-appearance-fill._mat-animation-noopable:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-underline .mat-form-field-ripple{transition:none}.mat-form-field-appearance-fill .mat-form-field-subscript-wrapper{padding:0 1em}\\n','.mat-input-element{font:inherit;background:transparent;color:currentColor;border:none;outline:none;padding:0;margin:0;width:100%;max-width:100%;vertical-align:bottom;text-align:inherit;box-sizing:content-box}.mat-input-element:-moz-ui-invalid{box-shadow:none}.mat-input-element,.mat-input-element::-webkit-search-cancel-button,.mat-input-element::-webkit-search-decoration,.mat-input-element::-webkit-search-results-button,.mat-input-element::-webkit-search-results-decoration{-webkit-appearance:none}.mat-input-element::-webkit-contacts-auto-fill-button,.mat-input-element::-webkit-caps-lock-indicator,.mat-input-element:not([type=password])::-webkit-credentials-auto-fill-button{visibility:hidden}.mat-input-element[type=date],.mat-input-element[type=datetime],.mat-input-element[type=datetime-local],.mat-input-element[type=month],.mat-input-element[type=week],.mat-input-element[type=time]{line-height:1}.mat-input-element[type=date]::after,.mat-input-element[type=datetime]::after,.mat-input-element[type=datetime-local]::after,.mat-input-element[type=month]::after,.mat-input-element[type=week]::after,.mat-input-element[type=time]::after{content:\" \";white-space:pre;width:1px}.mat-input-element::-webkit-inner-spin-button,.mat-input-element::-webkit-calendar-picker-indicator,.mat-input-element::-webkit-clear-button{font-size:.75em}.mat-input-element::placeholder{-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-input-element::-moz-placeholder{-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-input-element::-webkit-input-placeholder{-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-input-element:-ms-input-placeholder{-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-hide-placeholder .mat-input-element::placeholder{color:transparent !important;-webkit-text-fill-color:transparent;transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-input-element::placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-input-element::-moz-placeholder{color:transparent !important;-webkit-text-fill-color:transparent;transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-input-element::-moz-placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-input-element::-webkit-input-placeholder{color:transparent !important;-webkit-text-fill-color:transparent;transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-input-element::-webkit-input-placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-input-element:-ms-input-placeholder{color:transparent !important;-webkit-text-fill-color:transparent;transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-input-element:-ms-input-placeholder{opacity:0}textarea.mat-input-element{resize:vertical;overflow:auto}textarea.mat-input-element.cdk-textarea-autosize{resize:none}textarea.mat-input-element{padding:2px 0;margin:-2px 0}select.mat-input-element{-moz-appearance:none;-webkit-appearance:none;position:relative;background-color:transparent;display:inline-flex;box-sizing:border-box;padding-top:1em;top:-1em;margin-bottom:-1em}select.mat-input-element::-moz-focus-inner{border:0}select.mat-input-element:not(:disabled){cursor:pointer}.mat-form-field-type-mat-native-select .mat-form-field-infix::after{content:\"\";width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;border-top:5px solid;position:absolute;top:50%;right:0;margin-top:-2.5px;pointer-events:none}[dir=rtl] .mat-form-field-type-mat-native-select .mat-form-field-infix::after{right:auto;left:0}.mat-form-field-type-mat-native-select .mat-input-element{padding-right:15px}[dir=rtl] .mat-form-field-type-mat-native-select .mat-input-element{padding-right:0;padding-left:15px}.mat-form-field-type-mat-native-select .mat-form-field-label-wrapper{max-width:calc(100% - 10px)}.mat-form-field-type-mat-native-select.mat-form-field-appearance-outline .mat-form-field-infix::after{margin-top:-5px}.mat-form-field-type-mat-native-select.mat-form-field-appearance-fill .mat-form-field-infix::after{margin-top:-10px}\\n',\".mat-form-field-appearance-legacy .mat-form-field-label{transform:perspective(100px)}.mat-form-field-appearance-legacy .mat-form-field-prefix .mat-icon,.mat-form-field-appearance-legacy .mat-form-field-suffix .mat-icon{width:1em}.mat-form-field-appearance-legacy .mat-form-field-prefix .mat-icon-button,.mat-form-field-appearance-legacy .mat-form-field-suffix .mat-icon-button{font:inherit;vertical-align:baseline}.mat-form-field-appearance-legacy .mat-form-field-prefix .mat-icon-button .mat-icon,.mat-form-field-appearance-legacy .mat-form-field-suffix .mat-icon-button .mat-icon{font-size:inherit}.mat-form-field-appearance-legacy .mat-form-field-underline{height:1px}.cdk-high-contrast-active .mat-form-field-appearance-legacy .mat-form-field-underline{height:0;border-top:solid 1px}.mat-form-field-appearance-legacy .mat-form-field-ripple{top:0;height:2px;overflow:hidden}.cdk-high-contrast-active .mat-form-field-appearance-legacy .mat-form-field-ripple{height:0;border-top:solid 2px}.mat-form-field-appearance-legacy.mat-form-field-disabled .mat-form-field-underline{background-position:0;background-color:transparent}.cdk-high-contrast-active .mat-form-field-appearance-legacy.mat-form-field-disabled .mat-form-field-underline{border-top-style:dotted;border-top-width:2px;border-top-color:GrayText}.mat-form-field-appearance-legacy.mat-form-field-invalid:not(.mat-focused) .mat-form-field-ripple{height:1px}\\n\",\".mat-form-field-appearance-outline .mat-form-field-wrapper{margin:.25em 0}.mat-form-field-appearance-outline .mat-form-field-flex{padding:0 .75em 0 .75em;margin-top:-0.25em;position:relative}.mat-form-field-appearance-outline .mat-form-field-prefix,.mat-form-field-appearance-outline .mat-form-field-suffix{top:.25em}.mat-form-field-appearance-outline .mat-form-field-outline{display:flex;position:absolute;top:.25em;left:0;right:0;bottom:0;pointer-events:none}.mat-form-field-appearance-outline .mat-form-field-outline-start,.mat-form-field-appearance-outline .mat-form-field-outline-end{border:1px solid currentColor;min-width:5px}.mat-form-field-appearance-outline .mat-form-field-outline-start{border-radius:5px 0 0 5px;border-right-style:none}[dir=rtl] .mat-form-field-appearance-outline .mat-form-field-outline-start{border-right-style:solid;border-left-style:none;border-radius:0 5px 5px 0}.mat-form-field-appearance-outline .mat-form-field-outline-end{border-radius:0 5px 5px 0;border-left-style:none;flex-grow:1}[dir=rtl] .mat-form-field-appearance-outline .mat-form-field-outline-end{border-left-style:solid;border-right-style:none;border-radius:5px 0 0 5px}.mat-form-field-appearance-outline .mat-form-field-outline-gap{border-radius:.000001px;border:1px solid currentColor;border-left-style:none;border-right-style:none}.mat-form-field-appearance-outline.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-outline-gap{border-top-color:transparent}.mat-form-field-appearance-outline .mat-form-field-outline-thick{opacity:0}.mat-form-field-appearance-outline .mat-form-field-outline-thick .mat-form-field-outline-start,.mat-form-field-appearance-outline .mat-form-field-outline-thick .mat-form-field-outline-end,.mat-form-field-appearance-outline .mat-form-field-outline-thick .mat-form-field-outline-gap{border-width:2px}.mat-form-field-appearance-outline.mat-focused .mat-form-field-outline,.mat-form-field-appearance-outline.mat-form-field-invalid .mat-form-field-outline{opacity:0;transition:opacity 100ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-appearance-outline.mat-focused .mat-form-field-outline-thick,.mat-form-field-appearance-outline.mat-form-field-invalid .mat-form-field-outline-thick{opacity:1}.cdk-high-contrast-active .mat-form-field-appearance-outline.mat-focused .mat-form-field-outline-thick{border:3px dashed}.mat-form-field-appearance-outline:not(.mat-form-field-disabled) .mat-form-field-flex:hover .mat-form-field-outline{opacity:0;transition:opacity 600ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-appearance-outline:not(.mat-form-field-disabled) .mat-form-field-flex:hover .mat-form-field-outline-thick{opacity:1}.mat-form-field-appearance-outline .mat-form-field-subscript-wrapper{padding:0 1em}.cdk-high-contrast-active .mat-form-field-appearance-outline.mat-form-field-disabled .mat-form-field-outline{color:GrayText}.mat-form-field-appearance-outline._mat-animation-noopable:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-outline,.mat-form-field-appearance-outline._mat-animation-noopable .mat-form-field-outline,.mat-form-field-appearance-outline._mat-animation-noopable .mat-form-field-outline-start,.mat-form-field-appearance-outline._mat-animation-noopable .mat-form-field-outline-end,.mat-form-field-appearance-outline._mat-animation-noopable .mat-form-field-outline-gap{transition:none}\\n\",\".mat-form-field-appearance-standard .mat-form-field-flex{padding-top:.75em}.mat-form-field-appearance-standard .mat-form-field-underline{height:1px}.cdk-high-contrast-active .mat-form-field-appearance-standard .mat-form-field-underline{height:0;border-top:solid 1px}.mat-form-field-appearance-standard .mat-form-field-ripple{bottom:0;height:2px}.cdk-high-contrast-active .mat-form-field-appearance-standard .mat-form-field-ripple{height:0;border-top:solid 2px}.mat-form-field-appearance-standard.mat-form-field-disabled .mat-form-field-underline{background-position:0;background-color:transparent}.cdk-high-contrast-active .mat-form-field-appearance-standard.mat-form-field-disabled .mat-form-field-underline{border-top-style:dotted;border-top-width:2px}.mat-form-field-appearance-standard:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-underline .mat-form-field-ripple{opacity:1;transform:none;transition:opacity 600ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-appearance-standard._mat-animation-noopable:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-underline .mat-form-field-ripple{transition:none}\\n\"],encapsulation:2,data:{animation:[WU.transitionMessages]},changeDetection:0}),n})(),mg=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B,Ya],B]}),n})();const tl={schedule(n){let t=requestAnimationFrame,e=cancelAnimationFrame;const{delegate:i}=tl;i&&(t=i.requestAnimationFrame,e=i.cancelAnimationFrame);const r=t(s=>{e=void 0,n(s)});return new ke(()=>null==e?void 0:e(r))},requestAnimationFrame(...n){const{delegate:t}=tl;return((null==t?void 0:t.requestAnimationFrame)||requestAnimationFrame)(...n)},cancelAnimationFrame(...n){const{delegate:t}=tl;return((null==t?void 0:t.cancelAnimationFrame)||cancelAnimationFrame)(...n)},delegate:void 0},EE=new class r5 extends Ym{flush(t){this._active=!0;const e=this._scheduled;this._scheduled=void 0;const{actions:i}=this;let r;t=t||i.shift();do{if(r=t.execute(t.state,t.delay))break}while((t=i[0])&&t.id===e&&i.shift());if(this._active=!1,r){for(;(t=i[0])&&t.id===e&&i.shift();)t.unsubscribe();throw r}}}(class n5 extends qm{constructor(t,e){super(t,e),this.scheduler=t,this.work=e}requestAsyncId(t,e,i=0){return null!==i&&i>0?super.requestAsyncId(t,e,i):(t.actions.push(this),t._scheduled||(t._scheduled=tl.requestAnimationFrame(()=>t.flush(void 0))))}recycleAsyncId(t,e,i=0){if(null!=i&&i>0||null==i&&this.delay>0)return super.recycleAsyncId(t,e,i);t.actions.some(r=>r.id===e)||(tl.cancelAnimationFrame(e),t._scheduled=void 0)}});let gg,s5=1;const jd={};function SE(n){return n in jd&&(delete jd[n],!0)}const o5={setImmediate(n){const t=s5++;return jd[t]=!0,gg||(gg=Promise.resolve()),gg.then(()=>SE(t)&&n()),t},clearImmediate(n){SE(n)}},{setImmediate:a5,clearImmediate:l5}=o5,zd={setImmediate(...n){const{delegate:t}=zd;return((null==t?void 0:t.setImmediate)||a5)(...n)},clearImmediate(n){const{delegate:t}=zd;return((null==t?void 0:t.clearImmediate)||l5)(n)},delegate:void 0};new class d5 extends Ym{flush(t){this._active=!0;const e=this._scheduled;this._scheduled=void 0;const{actions:i}=this;let r;t=t||i.shift();do{if(r=t.execute(t.state,t.delay))break}while((t=i[0])&&t.id===e&&i.shift());if(this._active=!1,r){for(;(t=i[0])&&t.id===e&&i.shift();)t.unsubscribe();throw r}}}(class c5 extends qm{constructor(t,e){super(t,e),this.scheduler=t,this.work=e}requestAsyncId(t,e,i=0){return null!==i&&i>0?super.requestAsyncId(t,e,i):(t.actions.push(this),t._scheduled||(t._scheduled=zd.setImmediate(t.flush.bind(t,void 0))))}recycleAsyncId(t,e,i=0){if(null!=i&&i>0||null==i&&this.delay>0)return super.recycleAsyncId(t,e,i);t.actions.some(r=>r.id===e)||(zd.clearImmediate(e),t._scheduled=void 0)}});function _g(n=0,t,e=t3){let i=-1;return null!=t&&(y_(t)?e=t:i=t),new Ve(r=>{let s=function p5(n){return n instanceof Date&&!isNaN(n)}(n)?+n-e.now():n;s<0&&(s=0);let o=0;return e.schedule(function(){r.closed||(r.next(o++),0<=i?this.schedule(void 0,i):r.complete())},s)})}function kE(n,t=qa){return function h5(n){return qe((t,e)=>{let i=!1,r=null,s=null,o=!1;const a=()=>{if(null==s||s.unsubscribe(),s=null,i){i=!1;const c=r;r=null,e.next(c)}o&&e.complete()},l=()=>{s=null,o&&e.complete()};t.subscribe(Ue(e,c=>{i=!0,r=c,s||Jt(n(c)).subscribe(s=Ue(e,a,l))},()=>{o=!0,(!i||!s||s.closed)&&e.complete()}))})}(()=>_g(n,t))}let m5=(()=>{class n{constructor(e,i,r){this._ngZone=e,this._platform=i,this._scrolled=new O,this._globalSubscription=null,this._scrolledCount=0,this.scrollContainers=new Map,this._document=r}register(e){this.scrollContainers.has(e)||this.scrollContainers.set(e,e.elementScrolled().subscribe(()=>this._scrolled.next(e)))}deregister(e){const i=this.scrollContainers.get(e);i&&(i.unsubscribe(),this.scrollContainers.delete(e))}scrolled(e=20){return this._platform.isBrowser?new Ve(i=>{this._globalSubscription||this._addGlobalListener();const r=e>0?this._scrolled.pipe(kE(e)).subscribe(i):this._scrolled.subscribe(i);return this._scrolledCount++,()=>{r.unsubscribe(),this._scrolledCount--,this._scrolledCount||this._removeGlobalListener()}}):q()}ngOnDestroy(){this._removeGlobalListener(),this.scrollContainers.forEach((e,i)=>this.deregister(i)),this._scrolled.complete()}ancestorScrolled(e,i){const r=this.getAncestorScrollContainers(e);return this.scrolled(i).pipe(Ct(s=>!s||r.indexOf(s)>-1))}getAncestorScrollContainers(e){const i=[];return this.scrollContainers.forEach((r,s)=>{this._scrollableContainsElement(s,e)&&i.push(s)}),i}_getWindow(){return this._document.defaultView||window}_scrollableContainsElement(e,i){let r=at(i),s=e.getElementRef().nativeElement;do{if(r==s)return!0}while(r=r.parentElement);return!1}_addGlobalListener(){this._globalSubscription=this._ngZone.runOutsideAngular(()=>Jr(this._getWindow().document,\"scroll\").subscribe(()=>this._scrolled.next()))}_removeGlobalListener(){this._globalSubscription&&(this._globalSubscription.unsubscribe(),this._globalSubscription=null)}}return n.\\u0275fac=function(e){return new(e||n)(y(ne),y(It),y(ie,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),es=(()=>{class n{constructor(e,i,r){this._platform=e,this._change=new O,this._changeListener=s=>{this._change.next(s)},this._document=r,i.runOutsideAngular(()=>{if(e.isBrowser){const s=this._getWindow();s.addEventListener(\"resize\",this._changeListener),s.addEventListener(\"orientationchange\",this._changeListener)}this.change().subscribe(()=>this._viewportSize=null)})}ngOnDestroy(){if(this._platform.isBrowser){const e=this._getWindow();e.removeEventListener(\"resize\",this._changeListener),e.removeEventListener(\"orientationchange\",this._changeListener)}this._change.complete()}getViewportSize(){this._viewportSize||this._updateViewportSize();const e={width:this._viewportSize.width,height:this._viewportSize.height};return this._platform.isBrowser||(this._viewportSize=null),e}getViewportRect(){const e=this.getViewportScrollPosition(),{width:i,height:r}=this.getViewportSize();return{top:e.top,left:e.left,bottom:e.top+r,right:e.left+i,height:r,width:i}}getViewportScrollPosition(){if(!this._platform.isBrowser)return{top:0,left:0};const e=this._document,i=this._getWindow(),r=e.documentElement,s=r.getBoundingClientRect();return{top:-s.top||e.body.scrollTop||i.scrollY||r.scrollTop||0,left:-s.left||e.body.scrollLeft||i.scrollX||r.scrollLeft||0}}change(e=20){return e>0?this._change.pipe(kE(e)):this._change}_getWindow(){return this._document.defaultView||window}_updateViewportSize(){const e=this._getWindow();this._viewportSize=this._platform.isBrowser?{width:e.innerWidth,height:e.innerHeight}:{width:0,height:0}}}return n.\\u0275fac=function(e){return new(e||n)(y(It),y(ne),y(ie,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),Ci=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),Ud=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[lo,Ci],lo,Ci]}),n})();class vg{attach(t){return this._attachedHost=t,t.attach(this)}detach(){let t=this._attachedHost;null!=t&&(this._attachedHost=null,t.detach())}get isAttached(){return null!=this._attachedHost}setAttachedHost(t){this._attachedHost=t}}class yg extends vg{constructor(t,e,i,r){super(),this.component=t,this.viewContainerRef=e,this.injector=i,this.componentFactoryResolver=r}}class $d extends vg{constructor(t,e,i){super(),this.templateRef=t,this.viewContainerRef=e,this.context=i}get origin(){return this.templateRef.elementRef}attach(t,e=this.context){return this.context=e,super.attach(t)}detach(){return this.context=void 0,super.detach()}}class _5 extends vg{constructor(t){super(),this.element=t instanceof W?t.nativeElement:t}}class bg{constructor(){this._isDisposed=!1,this.attachDomPortal=null}hasAttached(){return!!this._attachedPortal}attach(t){return t instanceof yg?(this._attachedPortal=t,this.attachComponentPortal(t)):t instanceof $d?(this._attachedPortal=t,this.attachTemplatePortal(t)):this.attachDomPortal&&t instanceof _5?(this._attachedPortal=t,this.attachDomPortal(t)):void 0}detach(){this._attachedPortal&&(this._attachedPortal.setAttachedHost(null),this._attachedPortal=null),this._invokeDisposeFn()}dispose(){this.hasAttached()&&this.detach(),this._invokeDisposeFn(),this._isDisposed=!0}setDisposeFn(t){this._disposeFn=t}_invokeDisposeFn(){this._disposeFn&&(this._disposeFn(),this._disposeFn=null)}}class v5 extends bg{constructor(t,e,i,r,s){super(),this.outletElement=t,this._componentFactoryResolver=e,this._appRef=i,this._defaultInjector=r,this.attachDomPortal=o=>{const a=o.element,l=this._document.createComment(\"dom-portal\");a.parentNode.insertBefore(l,a),this.outletElement.appendChild(a),this._attachedPortal=o,super.setDisposeFn(()=>{l.parentNode&&l.parentNode.replaceChild(a,l)})},this._document=s}attachComponentPortal(t){const i=(t.componentFactoryResolver||this._componentFactoryResolver).resolveComponentFactory(t.component);let r;return t.viewContainerRef?(r=t.viewContainerRef.createComponent(i,t.viewContainerRef.length,t.injector||t.viewContainerRef.injector),this.setDisposeFn(()=>r.destroy())):(r=i.create(t.injector||this._defaultInjector),this._appRef.attachView(r.hostView),this.setDisposeFn(()=>{this._appRef.detachView(r.hostView),r.destroy()})),this.outletElement.appendChild(this._getComponentRootNode(r)),this._attachedPortal=t,r}attachTemplatePortal(t){let e=t.viewContainerRef,i=e.createEmbeddedView(t.templateRef,t.context);return i.rootNodes.forEach(r=>this.outletElement.appendChild(r)),i.detectChanges(),this.setDisposeFn(()=>{let r=e.indexOf(i);-1!==r&&e.remove(r)}),this._attachedPortal=t,i}dispose(){super.dispose(),this.outletElement.remove()}_getComponentRootNode(t){return t.hostView.rootNodes[0]}}let TE=(()=>{class n extends bg{constructor(e,i,r){super(),this._componentFactoryResolver=e,this._viewContainerRef=i,this._isInitialized=!1,this.attached=new $,this.attachDomPortal=s=>{const o=s.element,a=this._document.createComment(\"dom-portal\");s.setAttachedHost(this),o.parentNode.insertBefore(a,o),this._getRootNode().appendChild(o),this._attachedPortal=s,super.setDisposeFn(()=>{a.parentNode&&a.parentNode.replaceChild(o,a)})},this._document=r}get portal(){return this._attachedPortal}set portal(e){this.hasAttached()&&!e&&!this._isInitialized||(this.hasAttached()&&super.detach(),e&&super.attach(e),this._attachedPortal=e||null)}get attachedRef(){return this._attachedRef}ngOnInit(){this._isInitialized=!0}ngOnDestroy(){super.dispose(),this._attachedPortal=null,this._attachedRef=null}attachComponentPortal(e){e.setAttachedHost(this);const i=null!=e.viewContainerRef?e.viewContainerRef:this._viewContainerRef,s=(e.componentFactoryResolver||this._componentFactoryResolver).resolveComponentFactory(e.component),o=i.createComponent(s,i.length,e.injector||i.injector);return i!==this._viewContainerRef&&this._getRootNode().appendChild(o.hostView.rootNodes[0]),super.setDisposeFn(()=>o.destroy()),this._attachedPortal=e,this._attachedRef=o,this.attached.emit(o),o}attachTemplatePortal(e){e.setAttachedHost(this);const i=this._viewContainerRef.createEmbeddedView(e.templateRef,e.context);return super.setDisposeFn(()=>this._viewContainerRef.clear()),this._attachedPortal=e,this._attachedRef=i,this.attached.emit(i),i}_getRootNode(){const e=this._viewContainerRef.element.nativeElement;return e.nodeType===e.ELEMENT_NODE?e:e.parentNode}}return n.\\u0275fac=function(e){return new(e||n)(f(Ir),f(st),f(ie))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"cdkPortalOutlet\",\"\"]],inputs:{portal:[\"cdkPortalOutlet\",\"portal\"]},outputs:{attached:\"attached\"},exportAs:[\"cdkPortalOutlet\"],features:[E]}),n})(),Hi=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const AE=jz();class b5{constructor(t,e){this._viewportRuler=t,this._previousHTMLStyles={top:\"\",left:\"\"},this._isEnabled=!1,this._document=e}attach(){}enable(){if(this._canBeEnabled()){const t=this._document.documentElement;this._previousScrollPosition=this._viewportRuler.getViewportScrollPosition(),this._previousHTMLStyles.left=t.style.left||\"\",this._previousHTMLStyles.top=t.style.top||\"\",t.style.left=ft(-this._previousScrollPosition.left),t.style.top=ft(-this._previousScrollPosition.top),t.classList.add(\"cdk-global-scrollblock\"),this._isEnabled=!0}}disable(){if(this._isEnabled){const t=this._document.documentElement,i=t.style,r=this._document.body.style,s=i.scrollBehavior||\"\",o=r.scrollBehavior||\"\";this._isEnabled=!1,i.left=this._previousHTMLStyles.left,i.top=this._previousHTMLStyles.top,t.classList.remove(\"cdk-global-scrollblock\"),AE&&(i.scrollBehavior=r.scrollBehavior=\"auto\"),window.scroll(this._previousScrollPosition.left,this._previousScrollPosition.top),AE&&(i.scrollBehavior=s,r.scrollBehavior=o)}}_canBeEnabled(){if(this._document.documentElement.classList.contains(\"cdk-global-scrollblock\")||this._isEnabled)return!1;const e=this._document.body,i=this._viewportRuler.getViewportSize();return e.scrollHeight>i.height||e.scrollWidth>i.width}}class C5{constructor(t,e,i,r){this._scrollDispatcher=t,this._ngZone=e,this._viewportRuler=i,this._config=r,this._scrollSubscription=null,this._detach=()=>{this.disable(),this._overlayRef.hasAttached()&&this._ngZone.run(()=>this._overlayRef.detach())}}attach(t){this._overlayRef=t}enable(){if(this._scrollSubscription)return;const t=this._scrollDispatcher.scrolled(0);this._config&&this._config.threshold&&this._config.threshold>1?(this._initialScrollPosition=this._viewportRuler.getViewportScrollPosition().top,this._scrollSubscription=t.subscribe(()=>{const e=this._viewportRuler.getViewportScrollPosition().top;Math.abs(e-this._initialScrollPosition)>this._config.threshold?this._detach():this._overlayRef.updatePosition()})):this._scrollSubscription=t.subscribe(this._detach)}disable(){this._scrollSubscription&&(this._scrollSubscription.unsubscribe(),this._scrollSubscription=null)}detach(){this.disable(),this._overlayRef=null}}class IE{enable(){}disable(){}attach(){}}function Cg(n,t){return t.some(e=>n.bottom<e.top||n.top>e.bottom||n.right<e.left||n.left>e.right)}function RE(n,t){return t.some(e=>n.top<e.top||n.bottom>e.bottom||n.left<e.left||n.right>e.right)}class D5{constructor(t,e,i,r){this._scrollDispatcher=t,this._viewportRuler=e,this._ngZone=i,this._config=r,this._scrollSubscription=null}attach(t){this._overlayRef=t}enable(){this._scrollSubscription||(this._scrollSubscription=this._scrollDispatcher.scrolled(this._config?this._config.scrollThrottle:0).subscribe(()=>{if(this._overlayRef.updatePosition(),this._config&&this._config.autoClose){const e=this._overlayRef.overlayElement.getBoundingClientRect(),{width:i,height:r}=this._viewportRuler.getViewportSize();Cg(e,[{width:i,height:r,bottom:r,right:i,top:0,left:0}])&&(this.disable(),this._ngZone.run(()=>this._overlayRef.detach()))}}))}disable(){this._scrollSubscription&&(this._scrollSubscription.unsubscribe(),this._scrollSubscription=null)}detach(){this.disable(),this._overlayRef=null}}let w5=(()=>{class n{constructor(e,i,r,s){this._scrollDispatcher=e,this._viewportRuler=i,this._ngZone=r,this.noop=()=>new IE,this.close=o=>new C5(this._scrollDispatcher,this._ngZone,this._viewportRuler,o),this.block=()=>new b5(this._viewportRuler,this._document),this.reposition=o=>new D5(this._scrollDispatcher,this._viewportRuler,this._ngZone,o),this._document=s}}return n.\\u0275fac=function(e){return new(e||n)(y(m5),y(es),y(ne),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();class Gd{constructor(t){if(this.scrollStrategy=new IE,this.panelClass=\"\",this.hasBackdrop=!1,this.backdropClass=\"cdk-overlay-dark-backdrop\",this.disposeOnNavigation=!1,t){const e=Object.keys(t);for(const i of e)void 0!==t[i]&&(this[i]=t[i])}}}class M5{constructor(t,e){this.connectionPair=t,this.scrollableViewProperties=e}}class x5{constructor(t,e,i,r,s,o,a,l,c){this._portalOutlet=t,this._host=e,this._pane=i,this._config=r,this._ngZone=s,this._keyboardDispatcher=o,this._document=a,this._location=l,this._outsideClickDispatcher=c,this._backdropElement=null,this._backdropClick=new O,this._attachments=new O,this._detachments=new O,this._locationChanges=ke.EMPTY,this._backdropClickHandler=d=>this._backdropClick.next(d),this._backdropTransitionendHandler=d=>{this._disposeBackdrop(d.target)},this._keydownEvents=new O,this._outsidePointerEvents=new O,r.scrollStrategy&&(this._scrollStrategy=r.scrollStrategy,this._scrollStrategy.attach(this)),this._positionStrategy=r.positionStrategy}get overlayElement(){return this._pane}get backdropElement(){return this._backdropElement}get hostElement(){return this._host}attach(t){let e=this._portalOutlet.attach(t);return!this._host.parentElement&&this._previousHostParent&&this._previousHostParent.appendChild(this._host),this._positionStrategy&&this._positionStrategy.attach(this),this._updateStackingOrder(),this._updateElementSize(),this._updateElementDirection(),this._scrollStrategy&&this._scrollStrategy.enable(),this._ngZone.onStable.pipe(it(1)).subscribe(()=>{this.hasAttached()&&this.updatePosition()}),this._togglePointerEvents(!0),this._config.hasBackdrop&&this._attachBackdrop(),this._config.panelClass&&this._toggleClasses(this._pane,this._config.panelClass,!0),this._attachments.next(),this._keyboardDispatcher.add(this),this._config.disposeOnNavigation&&(this._locationChanges=this._location.subscribe(()=>this.dispose())),this._outsideClickDispatcher.add(this),e}detach(){if(!this.hasAttached())return;this.detachBackdrop(),this._togglePointerEvents(!1),this._positionStrategy&&this._positionStrategy.detach&&this._positionStrategy.detach(),this._scrollStrategy&&this._scrollStrategy.disable();const t=this._portalOutlet.detach();return this._detachments.next(),this._keyboardDispatcher.remove(this),this._detachContentWhenStable(),this._locationChanges.unsubscribe(),this._outsideClickDispatcher.remove(this),t}dispose(){var t;const e=this.hasAttached();this._positionStrategy&&this._positionStrategy.dispose(),this._disposeScrollStrategy(),this._disposeBackdrop(this._backdropElement),this._locationChanges.unsubscribe(),this._keyboardDispatcher.remove(this),this._portalOutlet.dispose(),this._attachments.complete(),this._backdropClick.complete(),this._keydownEvents.complete(),this._outsidePointerEvents.complete(),this._outsideClickDispatcher.remove(this),null===(t=this._host)||void 0===t||t.remove(),this._previousHostParent=this._pane=this._host=null,e&&this._detachments.next(),this._detachments.complete()}hasAttached(){return this._portalOutlet.hasAttached()}backdropClick(){return this._backdropClick}attachments(){return this._attachments}detachments(){return this._detachments}keydownEvents(){return this._keydownEvents}outsidePointerEvents(){return this._outsidePointerEvents}getConfig(){return this._config}updatePosition(){this._positionStrategy&&this._positionStrategy.apply()}updatePositionStrategy(t){t!==this._positionStrategy&&(this._positionStrategy&&this._positionStrategy.dispose(),this._positionStrategy=t,this.hasAttached()&&(t.attach(this),this.updatePosition()))}updateSize(t){this._config=Object.assign(Object.assign({},this._config),t),this._updateElementSize()}setDirection(t){this._config=Object.assign(Object.assign({},this._config),{direction:t}),this._updateElementDirection()}addPanelClass(t){this._pane&&this._toggleClasses(this._pane,t,!0)}removePanelClass(t){this._pane&&this._toggleClasses(this._pane,t,!1)}getDirection(){const t=this._config.direction;return t?\"string\"==typeof t?t:t.value:\"ltr\"}updateScrollStrategy(t){t!==this._scrollStrategy&&(this._disposeScrollStrategy(),this._scrollStrategy=t,this.hasAttached()&&(t.attach(this),t.enable()))}_updateElementDirection(){this._host.setAttribute(\"dir\",this.getDirection())}_updateElementSize(){if(!this._pane)return;const t=this._pane.style;t.width=ft(this._config.width),t.height=ft(this._config.height),t.minWidth=ft(this._config.minWidth),t.minHeight=ft(this._config.minHeight),t.maxWidth=ft(this._config.maxWidth),t.maxHeight=ft(this._config.maxHeight)}_togglePointerEvents(t){this._pane.style.pointerEvents=t?\"\":\"none\"}_attachBackdrop(){const t=\"cdk-overlay-backdrop-showing\";this._backdropElement=this._document.createElement(\"div\"),this._backdropElement.classList.add(\"cdk-overlay-backdrop\"),this._config.backdropClass&&this._toggleClasses(this._backdropElement,this._config.backdropClass,!0),this._host.parentElement.insertBefore(this._backdropElement,this._host),this._backdropElement.addEventListener(\"click\",this._backdropClickHandler),\"undefined\"!=typeof requestAnimationFrame?this._ngZone.runOutsideAngular(()=>{requestAnimationFrame(()=>{this._backdropElement&&this._backdropElement.classList.add(t)})}):this._backdropElement.classList.add(t)}_updateStackingOrder(){this._host.nextSibling&&this._host.parentNode.appendChild(this._host)}detachBackdrop(){const t=this._backdropElement;!t||(t.classList.remove(\"cdk-overlay-backdrop-showing\"),this._ngZone.runOutsideAngular(()=>{t.addEventListener(\"transitionend\",this._backdropTransitionendHandler)}),t.style.pointerEvents=\"none\",this._backdropTimeout=this._ngZone.runOutsideAngular(()=>setTimeout(()=>{this._disposeBackdrop(t)},500)))}_toggleClasses(t,e,i){const r=Wx(e||[]).filter(s=>!!s);r.length&&(i?t.classList.add(...r):t.classList.remove(...r))}_detachContentWhenStable(){this._ngZone.runOutsideAngular(()=>{const t=this._ngZone.onStable.pipe(Ie(Bt(this._attachments,this._detachments))).subscribe(()=>{(!this._pane||!this._host||0===this._pane.children.length)&&(this._pane&&this._config.panelClass&&this._toggleClasses(this._pane,this._config.panelClass,!1),this._host&&this._host.parentElement&&(this._previousHostParent=this._host.parentElement,this._host.remove()),t.unsubscribe())})})}_disposeScrollStrategy(){const t=this._scrollStrategy;t&&(t.disable(),t.detach&&t.detach())}_disposeBackdrop(t){t&&(t.removeEventListener(\"click\",this._backdropClickHandler),t.removeEventListener(\"transitionend\",this._backdropTransitionendHandler),t.remove(),this._backdropElement===t&&(this._backdropElement=null)),this._backdropTimeout&&(clearTimeout(this._backdropTimeout),this._backdropTimeout=void 0)}}let Dg=(()=>{class n{constructor(e,i){this._platform=i,this._document=e}ngOnDestroy(){var e;null===(e=this._containerElement)||void 0===e||e.remove()}getContainerElement(){return this._containerElement||this._createContainer(),this._containerElement}_createContainer(){const e=\"cdk-overlay-container\";if(this._platform.isBrowser||jm()){const r=this._document.querySelectorAll(`.${e}[platform=\"server\"], .${e}[platform=\"test\"]`);for(let s=0;s<r.length;s++)r[s].remove()}const i=this._document.createElement(\"div\");i.classList.add(e),jm()?i.setAttribute(\"platform\",\"test\"):this._platform.isBrowser||i.setAttribute(\"platform\",\"server\"),this._document.body.appendChild(i),this._containerElement=i}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(It))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const OE=\"cdk-overlay-connected-position-bounding-box\",E5=/([A-Za-z%]+)$/;class S5{constructor(t,e,i,r,s){this._viewportRuler=e,this._document=i,this._platform=r,this._overlayContainer=s,this._lastBoundingBoxSize={width:0,height:0},this._isPushed=!1,this._canPush=!0,this._growAfterOpen=!1,this._hasFlexibleDimensions=!0,this._positionLocked=!1,this._viewportMargin=0,this._scrollables=[],this._preferredPositions=[],this._positionChanges=new O,this._resizeSubscription=ke.EMPTY,this._offsetX=0,this._offsetY=0,this._appliedPanelClasses=[],this.positionChanges=this._positionChanges,this.setOrigin(t)}get positions(){return this._preferredPositions}attach(t){this._validatePositions(),t.hostElement.classList.add(OE),this._overlayRef=t,this._boundingBox=t.hostElement,this._pane=t.overlayElement,this._isDisposed=!1,this._isInitialRender=!0,this._lastPosition=null,this._resizeSubscription.unsubscribe(),this._resizeSubscription=this._viewportRuler.change().subscribe(()=>{this._isInitialRender=!0,this.apply()})}apply(){if(this._isDisposed||!this._platform.isBrowser)return;if(!this._isInitialRender&&this._positionLocked&&this._lastPosition)return void this.reapplyLastPosition();this._clearPanelClasses(),this._resetOverlayElementStyles(),this._resetBoundingBoxStyles(),this._viewportRect=this._getNarrowedViewportRect(),this._originRect=this._getOriginRect(),this._overlayRect=this._pane.getBoundingClientRect(),this._containerRect=this._overlayContainer.getContainerElement().getBoundingClientRect();const t=this._originRect,e=this._overlayRect,i=this._viewportRect,r=this._containerRect,s=[];let o;for(let a of this._preferredPositions){let l=this._getOriginPoint(t,r,a),c=this._getOverlayPoint(l,e,a),d=this._getOverlayFit(c,e,i,a);if(d.isCompletelyWithinViewport)return this._isPushed=!1,void this._applyPosition(a,l);this._canFitWithFlexibleDimensions(d,c,i)?s.push({position:a,origin:l,overlayRect:e,boundingBoxRect:this._calculateBoundingBoxRect(l,a)}):(!o||o.overlayFit.visibleArea<d.visibleArea)&&(o={overlayFit:d,overlayPoint:c,originPoint:l,position:a,overlayRect:e})}if(s.length){let a=null,l=-1;for(const c of s){const d=c.boundingBoxRect.width*c.boundingBoxRect.height*(c.position.weight||1);d>l&&(l=d,a=c)}return this._isPushed=!1,void this._applyPosition(a.position,a.origin)}if(this._canPush)return this._isPushed=!0,void this._applyPosition(o.position,o.originPoint);this._applyPosition(o.position,o.originPoint)}detach(){this._clearPanelClasses(),this._lastPosition=null,this._previousPushAmount=null,this._resizeSubscription.unsubscribe()}dispose(){this._isDisposed||(this._boundingBox&&ts(this._boundingBox.style,{top:\"\",left:\"\",right:\"\",bottom:\"\",height:\"\",width:\"\",alignItems:\"\",justifyContent:\"\"}),this._pane&&this._resetOverlayElementStyles(),this._overlayRef&&this._overlayRef.hostElement.classList.remove(OE),this.detach(),this._positionChanges.complete(),this._overlayRef=this._boundingBox=null,this._isDisposed=!0)}reapplyLastPosition(){if(this._isDisposed||!this._platform.isBrowser)return;const t=this._lastPosition;if(t){this._originRect=this._getOriginRect(),this._overlayRect=this._pane.getBoundingClientRect(),this._viewportRect=this._getNarrowedViewportRect(),this._containerRect=this._overlayContainer.getContainerElement().getBoundingClientRect();const e=this._getOriginPoint(this._originRect,this._containerRect,t);this._applyPosition(t,e)}else this.apply()}withScrollableContainers(t){return this._scrollables=t,this}withPositions(t){return this._preferredPositions=t,-1===t.indexOf(this._lastPosition)&&(this._lastPosition=null),this._validatePositions(),this}withViewportMargin(t){return this._viewportMargin=t,this}withFlexibleDimensions(t=!0){return this._hasFlexibleDimensions=t,this}withGrowAfterOpen(t=!0){return this._growAfterOpen=t,this}withPush(t=!0){return this._canPush=t,this}withLockedPosition(t=!0){return this._positionLocked=t,this}setOrigin(t){return this._origin=t,this}withDefaultOffsetX(t){return this._offsetX=t,this}withDefaultOffsetY(t){return this._offsetY=t,this}withTransformOriginOn(t){return this._transformOriginSelector=t,this}_getOriginPoint(t,e,i){let r,s;if(\"center\"==i.originX)r=t.left+t.width/2;else{const o=this._isRtl()?t.right:t.left,a=this._isRtl()?t.left:t.right;r=\"start\"==i.originX?o:a}return e.left<0&&(r-=e.left),s=\"center\"==i.originY?t.top+t.height/2:\"top\"==i.originY?t.top:t.bottom,e.top<0&&(s-=e.top),{x:r,y:s}}_getOverlayPoint(t,e,i){let r,s;return r=\"center\"==i.overlayX?-e.width/2:\"start\"===i.overlayX?this._isRtl()?-e.width:0:this._isRtl()?0:-e.width,s=\"center\"==i.overlayY?-e.height/2:\"top\"==i.overlayY?0:-e.height,{x:t.x+r,y:t.y+s}}_getOverlayFit(t,e,i,r){const s=FE(e);let{x:o,y:a}=t,l=this._getOffset(r,\"x\"),c=this._getOffset(r,\"y\");l&&(o+=l),c&&(a+=c);let h=0-a,p=a+s.height-i.height,m=this._subtractOverflows(s.width,0-o,o+s.width-i.width),g=this._subtractOverflows(s.height,h,p),_=m*g;return{visibleArea:_,isCompletelyWithinViewport:s.width*s.height===_,fitsInViewportVertically:g===s.height,fitsInViewportHorizontally:m==s.width}}_canFitWithFlexibleDimensions(t,e,i){if(this._hasFlexibleDimensions){const r=i.bottom-e.y,s=i.right-e.x,o=PE(this._overlayRef.getConfig().minHeight),a=PE(this._overlayRef.getConfig().minWidth),c=t.fitsInViewportHorizontally||null!=a&&a<=s;return(t.fitsInViewportVertically||null!=o&&o<=r)&&c}return!1}_pushOverlayOnScreen(t,e,i){if(this._previousPushAmount&&this._positionLocked)return{x:t.x+this._previousPushAmount.x,y:t.y+this._previousPushAmount.y};const r=FE(e),s=this._viewportRect,o=Math.max(t.x+r.width-s.width,0),a=Math.max(t.y+r.height-s.height,0),l=Math.max(s.top-i.top-t.y,0),c=Math.max(s.left-i.left-t.x,0);let d=0,u=0;return d=r.width<=s.width?c||-o:t.x<this._viewportMargin?s.left-i.left-t.x:0,u=r.height<=s.height?l||-a:t.y<this._viewportMargin?s.top-i.top-t.y:0,this._previousPushAmount={x:d,y:u},{x:t.x+d,y:t.y+u}}_applyPosition(t,e){if(this._setTransformOrigin(t),this._setOverlayElementStyles(e,t),this._setBoundingBoxStyles(e,t),t.panelClass&&this._addPanelClasses(t.panelClass),this._lastPosition=t,this._positionChanges.observers.length){const i=this._getScrollVisibility(),r=new M5(t,i);this._positionChanges.next(r)}this._isInitialRender=!1}_setTransformOrigin(t){if(!this._transformOriginSelector)return;const e=this._boundingBox.querySelectorAll(this._transformOriginSelector);let i,r=t.overlayY;i=\"center\"===t.overlayX?\"center\":this._isRtl()?\"start\"===t.overlayX?\"right\":\"left\":\"start\"===t.overlayX?\"left\":\"right\";for(let s=0;s<e.length;s++)e[s].style.transformOrigin=`${i} ${r}`}_calculateBoundingBoxRect(t,e){const i=this._viewportRect,r=this._isRtl();let s,o,a,d,u,h;if(\"top\"===e.overlayY)o=t.y,s=i.height-o+this._viewportMargin;else if(\"bottom\"===e.overlayY)a=i.height-t.y+2*this._viewportMargin,s=i.height-a+this._viewportMargin;else{const p=Math.min(i.bottom-t.y+i.top,t.y),m=this._lastBoundingBoxSize.height;s=2*p,o=t.y-p,s>m&&!this._isInitialRender&&!this._growAfterOpen&&(o=t.y-m/2)}if(\"end\"===e.overlayX&&!r||\"start\"===e.overlayX&&r)h=i.width-t.x+this._viewportMargin,d=t.x-this._viewportMargin;else if(\"start\"===e.overlayX&&!r||\"end\"===e.overlayX&&r)u=t.x,d=i.right-t.x;else{const p=Math.min(i.right-t.x+i.left,t.x),m=this._lastBoundingBoxSize.width;d=2*p,u=t.x-p,d>m&&!this._isInitialRender&&!this._growAfterOpen&&(u=t.x-m/2)}return{top:o,left:u,bottom:a,right:h,width:d,height:s}}_setBoundingBoxStyles(t,e){const i=this._calculateBoundingBoxRect(t,e);!this._isInitialRender&&!this._growAfterOpen&&(i.height=Math.min(i.height,this._lastBoundingBoxSize.height),i.width=Math.min(i.width,this._lastBoundingBoxSize.width));const r={};if(this._hasExactPosition())r.top=r.left=\"0\",r.bottom=r.right=r.maxHeight=r.maxWidth=\"\",r.width=r.height=\"100%\";else{const s=this._overlayRef.getConfig().maxHeight,o=this._overlayRef.getConfig().maxWidth;r.height=ft(i.height),r.top=ft(i.top),r.bottom=ft(i.bottom),r.width=ft(i.width),r.left=ft(i.left),r.right=ft(i.right),r.alignItems=\"center\"===e.overlayX?\"center\":\"end\"===e.overlayX?\"flex-end\":\"flex-start\",r.justifyContent=\"center\"===e.overlayY?\"center\":\"bottom\"===e.overlayY?\"flex-end\":\"flex-start\",s&&(r.maxHeight=ft(s)),o&&(r.maxWidth=ft(o))}this._lastBoundingBoxSize=i,ts(this._boundingBox.style,r)}_resetBoundingBoxStyles(){ts(this._boundingBox.style,{top:\"0\",left:\"0\",right:\"0\",bottom:\"0\",height:\"\",width:\"\",alignItems:\"\",justifyContent:\"\"})}_resetOverlayElementStyles(){ts(this._pane.style,{top:\"\",left:\"\",bottom:\"\",right:\"\",position:\"\",transform:\"\"})}_setOverlayElementStyles(t,e){const i={},r=this._hasExactPosition(),s=this._hasFlexibleDimensions,o=this._overlayRef.getConfig();if(r){const d=this._viewportRuler.getViewportScrollPosition();ts(i,this._getExactOverlayY(e,t,d)),ts(i,this._getExactOverlayX(e,t,d))}else i.position=\"static\";let a=\"\",l=this._getOffset(e,\"x\"),c=this._getOffset(e,\"y\");l&&(a+=`translateX(${l}px) `),c&&(a+=`translateY(${c}px)`),i.transform=a.trim(),o.maxHeight&&(r?i.maxHeight=ft(o.maxHeight):s&&(i.maxHeight=\"\")),o.maxWidth&&(r?i.maxWidth=ft(o.maxWidth):s&&(i.maxWidth=\"\")),ts(this._pane.style,i)}_getExactOverlayY(t,e,i){let r={top:\"\",bottom:\"\"},s=this._getOverlayPoint(e,this._overlayRect,t);return this._isPushed&&(s=this._pushOverlayOnScreen(s,this._overlayRect,i)),\"bottom\"===t.overlayY?r.bottom=this._document.documentElement.clientHeight-(s.y+this._overlayRect.height)+\"px\":r.top=ft(s.y),r}_getExactOverlayX(t,e,i){let o,r={left:\"\",right:\"\"},s=this._getOverlayPoint(e,this._overlayRect,t);return this._isPushed&&(s=this._pushOverlayOnScreen(s,this._overlayRect,i)),o=this._isRtl()?\"end\"===t.overlayX?\"left\":\"right\":\"end\"===t.overlayX?\"right\":\"left\",\"right\"===o?r.right=this._document.documentElement.clientWidth-(s.x+this._overlayRect.width)+\"px\":r.left=ft(s.x),r}_getScrollVisibility(){const t=this._getOriginRect(),e=this._pane.getBoundingClientRect(),i=this._scrollables.map(r=>r.getElementRef().nativeElement.getBoundingClientRect());return{isOriginClipped:RE(t,i),isOriginOutsideView:Cg(t,i),isOverlayClipped:RE(e,i),isOverlayOutsideView:Cg(e,i)}}_subtractOverflows(t,...e){return e.reduce((i,r)=>i-Math.max(r,0),t)}_getNarrowedViewportRect(){const t=this._document.documentElement.clientWidth,e=this._document.documentElement.clientHeight,i=this._viewportRuler.getViewportScrollPosition();return{top:i.top+this._viewportMargin,left:i.left+this._viewportMargin,right:i.left+t-this._viewportMargin,bottom:i.top+e-this._viewportMargin,width:t-2*this._viewportMargin,height:e-2*this._viewportMargin}}_isRtl(){return\"rtl\"===this._overlayRef.getDirection()}_hasExactPosition(){return!this._hasFlexibleDimensions||this._isPushed}_getOffset(t,e){return\"x\"===e?null==t.offsetX?this._offsetX:t.offsetX:null==t.offsetY?this._offsetY:t.offsetY}_validatePositions(){}_addPanelClasses(t){this._pane&&Wx(t).forEach(e=>{\"\"!==e&&-1===this._appliedPanelClasses.indexOf(e)&&(this._appliedPanelClasses.push(e),this._pane.classList.add(e))})}_clearPanelClasses(){this._pane&&(this._appliedPanelClasses.forEach(t=>{this._pane.classList.remove(t)}),this._appliedPanelClasses=[])}_getOriginRect(){const t=this._origin;if(t instanceof W)return t.nativeElement.getBoundingClientRect();if(t instanceof Element)return t.getBoundingClientRect();const e=t.width||0,i=t.height||0;return{top:t.y,bottom:t.y+i,left:t.x,right:t.x+e,height:i,width:e}}}function ts(n,t){for(let e in t)t.hasOwnProperty(e)&&(n[e]=t[e]);return n}function PE(n){if(\"number\"!=typeof n&&null!=n){const[t,e]=n.split(E5);return e&&\"px\"!==e?null:parseFloat(t)}return n||null}function FE(n){return{top:Math.floor(n.top),right:Math.floor(n.right),bottom:Math.floor(n.bottom),left:Math.floor(n.left),width:Math.floor(n.width),height:Math.floor(n.height)}}const NE=\"cdk-global-overlay-wrapper\";class k5{constructor(){this._cssPosition=\"static\",this._topOffset=\"\",this._bottomOffset=\"\",this._leftOffset=\"\",this._rightOffset=\"\",this._alignItems=\"\",this._justifyContent=\"\",this._width=\"\",this._height=\"\"}attach(t){const e=t.getConfig();this._overlayRef=t,this._width&&!e.width&&t.updateSize({width:this._width}),this._height&&!e.height&&t.updateSize({height:this._height}),t.hostElement.classList.add(NE),this._isDisposed=!1}top(t=\"\"){return this._bottomOffset=\"\",this._topOffset=t,this._alignItems=\"flex-start\",this}left(t=\"\"){return this._rightOffset=\"\",this._leftOffset=t,this._justifyContent=\"flex-start\",this}bottom(t=\"\"){return this._topOffset=\"\",this._bottomOffset=t,this._alignItems=\"flex-end\",this}right(t=\"\"){return this._leftOffset=\"\",this._rightOffset=t,this._justifyContent=\"flex-end\",this}width(t=\"\"){return this._overlayRef?this._overlayRef.updateSize({width:t}):this._width=t,this}height(t=\"\"){return this._overlayRef?this._overlayRef.updateSize({height:t}):this._height=t,this}centerHorizontally(t=\"\"){return this.left(t),this._justifyContent=\"center\",this}centerVertically(t=\"\"){return this.top(t),this._alignItems=\"center\",this}apply(){if(!this._overlayRef||!this._overlayRef.hasAttached())return;const t=this._overlayRef.overlayElement.style,e=this._overlayRef.hostElement.style,i=this._overlayRef.getConfig(),{width:r,height:s,maxWidth:o,maxHeight:a}=i,l=!(\"100%\"!==r&&\"100vw\"!==r||o&&\"100%\"!==o&&\"100vw\"!==o),c=!(\"100%\"!==s&&\"100vh\"!==s||a&&\"100%\"!==a&&\"100vh\"!==a);t.position=this._cssPosition,t.marginLeft=l?\"0\":this._leftOffset,t.marginTop=c?\"0\":this._topOffset,t.marginBottom=this._bottomOffset,t.marginRight=this._rightOffset,l?e.justifyContent=\"flex-start\":\"center\"===this._justifyContent?e.justifyContent=\"center\":\"rtl\"===this._overlayRef.getConfig().direction?\"flex-start\"===this._justifyContent?e.justifyContent=\"flex-end\":\"flex-end\"===this._justifyContent&&(e.justifyContent=\"flex-start\"):e.justifyContent=this._justifyContent,e.alignItems=c?\"flex-start\":this._alignItems}dispose(){if(this._isDisposed||!this._overlayRef)return;const t=this._overlayRef.overlayElement.style,e=this._overlayRef.hostElement,i=e.style;e.classList.remove(NE),i.justifyContent=i.alignItems=t.marginTop=t.marginBottom=t.marginLeft=t.marginRight=t.position=\"\",this._overlayRef=null,this._isDisposed=!0}}let T5=(()=>{class n{constructor(e,i,r,s){this._viewportRuler=e,this._document=i,this._platform=r,this._overlayContainer=s}global(){return new k5}flexibleConnectedTo(e){return new S5(e,this._viewportRuler,this._document,this._platform,this._overlayContainer)}}return n.\\u0275fac=function(e){return new(e||n)(y(es),y(ie),y(It),y(Dg))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),LE=(()=>{class n{constructor(e){this._attachedOverlays=[],this._document=e}ngOnDestroy(){this.detach()}add(e){this.remove(e),this._attachedOverlays.push(e)}remove(e){const i=this._attachedOverlays.indexOf(e);i>-1&&this._attachedOverlays.splice(i,1),0===this._attachedOverlays.length&&this.detach()}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),A5=(()=>{class n extends LE{constructor(e,i){super(e),this._ngZone=i,this._keydownListener=r=>{const s=this._attachedOverlays;for(let o=s.length-1;o>-1;o--)if(s[o]._keydownEvents.observers.length>0){const a=s[o]._keydownEvents;this._ngZone?this._ngZone.run(()=>a.next(r)):a.next(r);break}}}add(e){super.add(e),this._isAttached||(this._ngZone?this._ngZone.runOutsideAngular(()=>this._document.body.addEventListener(\"keydown\",this._keydownListener)):this._document.body.addEventListener(\"keydown\",this._keydownListener),this._isAttached=!0)}detach(){this._isAttached&&(this._document.body.removeEventListener(\"keydown\",this._keydownListener),this._isAttached=!1)}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(ne,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),I5=(()=>{class n extends LE{constructor(e,i,r){super(e),this._platform=i,this._ngZone=r,this._cursorStyleIsSet=!1,this._pointerDownListener=s=>{this._pointerDownEventTarget=Pn(s)},this._clickListener=s=>{const o=Pn(s),a=\"click\"===s.type&&this._pointerDownEventTarget?this._pointerDownEventTarget:o;this._pointerDownEventTarget=null;const l=this._attachedOverlays.slice();for(let c=l.length-1;c>-1;c--){const d=l[c];if(d._outsidePointerEvents.observers.length<1||!d.hasAttached())continue;if(d.overlayElement.contains(o)||d.overlayElement.contains(a))break;const u=d._outsidePointerEvents;this._ngZone?this._ngZone.run(()=>u.next(s)):u.next(s)}}}add(e){if(super.add(e),!this._isAttached){const i=this._document.body;this._ngZone?this._ngZone.runOutsideAngular(()=>this._addEventListeners(i)):this._addEventListeners(i),this._platform.IOS&&!this._cursorStyleIsSet&&(this._cursorOriginalValue=i.style.cursor,i.style.cursor=\"pointer\",this._cursorStyleIsSet=!0),this._isAttached=!0}}detach(){if(this._isAttached){const e=this._document.body;e.removeEventListener(\"pointerdown\",this._pointerDownListener,!0),e.removeEventListener(\"click\",this._clickListener,!0),e.removeEventListener(\"auxclick\",this._clickListener,!0),e.removeEventListener(\"contextmenu\",this._clickListener,!0),this._platform.IOS&&this._cursorStyleIsSet&&(e.style.cursor=this._cursorOriginalValue,this._cursorStyleIsSet=!1),this._isAttached=!1}}_addEventListeners(e){e.addEventListener(\"pointerdown\",this._pointerDownListener,!0),e.addEventListener(\"click\",this._clickListener,!0),e.addEventListener(\"auxclick\",this._clickListener,!0),e.addEventListener(\"contextmenu\",this._clickListener,!0)}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(It),y(ne,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),R5=0,ni=(()=>{class n{constructor(e,i,r,s,o,a,l,c,d,u,h){this.scrollStrategies=e,this._overlayContainer=i,this._componentFactoryResolver=r,this._positionBuilder=s,this._keyboardDispatcher=o,this._injector=a,this._ngZone=l,this._document=c,this._directionality=d,this._location=u,this._outsideClickDispatcher=h}create(e){const i=this._createHostElement(),r=this._createPaneElement(i),s=this._createPortalOutlet(r),o=new Gd(e);return o.direction=o.direction||this._directionality.value,new x5(s,i,r,o,this._ngZone,this._keyboardDispatcher,this._document,this._location,this._outsideClickDispatcher)}position(){return this._positionBuilder}_createPaneElement(e){const i=this._document.createElement(\"div\");return i.id=\"cdk-overlay-\"+R5++,i.classList.add(\"cdk-overlay-pane\"),e.appendChild(i),i}_createHostElement(){const e=this._document.createElement(\"div\");return this._overlayContainer.getContainerElement().appendChild(e),e}_createPortalOutlet(e){return this._appRef||(this._appRef=this._injector.get(Cc)),new v5(e,this._componentFactoryResolver,this._appRef,this._injector,this._document)}}return n.\\u0275fac=function(e){return new(e||n)(y(w5),y(Dg),y(Ir),y(T5),y(A5),y(dt),y(ne),y(ie),y(On),y(va),y(I5))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const O5=[{originX:\"start\",originY:\"bottom\",overlayX:\"start\",overlayY:\"top\"},{originX:\"start\",originY:\"top\",overlayX:\"start\",overlayY:\"bottom\"},{originX:\"end\",originY:\"top\",overlayX:\"end\",overlayY:\"bottom\"},{originX:\"end\",originY:\"bottom\",overlayX:\"end\",overlayY:\"top\"}],BE=new b(\"cdk-connected-overlay-scroll-strategy\");let VE=(()=>{class n{constructor(e){this.elementRef=e}}return n.\\u0275fac=function(e){return new(e||n)(f(W))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"cdk-overlay-origin\",\"\"],[\"\",\"overlay-origin\",\"\"],[\"\",\"cdkOverlayOrigin\",\"\"]],exportAs:[\"cdkOverlayOrigin\"]}),n})(),HE=(()=>{class n{constructor(e,i,r,s,o){this._overlay=e,this._dir=o,this._hasBackdrop=!1,this._lockPosition=!1,this._growAfterOpen=!1,this._flexibleDimensions=!1,this._push=!1,this._backdropSubscription=ke.EMPTY,this._attachSubscription=ke.EMPTY,this._detachSubscription=ke.EMPTY,this._positionSubscription=ke.EMPTY,this.viewportMargin=0,this.open=!1,this.disableClose=!1,this.backdropClick=new $,this.positionChange=new $,this.attach=new $,this.detach=new $,this.overlayKeydown=new $,this.overlayOutsideClick=new $,this._templatePortal=new $d(i,r),this._scrollStrategyFactory=s,this.scrollStrategy=this._scrollStrategyFactory()}get offsetX(){return this._offsetX}set offsetX(e){this._offsetX=e,this._position&&this._updatePositionStrategy(this._position)}get offsetY(){return this._offsetY}set offsetY(e){this._offsetY=e,this._position&&this._updatePositionStrategy(this._position)}get hasBackdrop(){return this._hasBackdrop}set hasBackdrop(e){this._hasBackdrop=G(e)}get lockPosition(){return this._lockPosition}set lockPosition(e){this._lockPosition=G(e)}get flexibleDimensions(){return this._flexibleDimensions}set flexibleDimensions(e){this._flexibleDimensions=G(e)}get growAfterOpen(){return this._growAfterOpen}set growAfterOpen(e){this._growAfterOpen=G(e)}get push(){return this._push}set push(e){this._push=G(e)}get overlayRef(){return this._overlayRef}get dir(){return this._dir?this._dir.value:\"ltr\"}ngOnDestroy(){this._attachSubscription.unsubscribe(),this._detachSubscription.unsubscribe(),this._backdropSubscription.unsubscribe(),this._positionSubscription.unsubscribe(),this._overlayRef&&this._overlayRef.dispose()}ngOnChanges(e){this._position&&(this._updatePositionStrategy(this._position),this._overlayRef.updateSize({width:this.width,minWidth:this.minWidth,height:this.height,minHeight:this.minHeight}),e.origin&&this.open&&this._position.apply()),e.open&&(this.open?this._attachOverlay():this._detachOverlay())}_createOverlay(){(!this.positions||!this.positions.length)&&(this.positions=O5);const e=this._overlayRef=this._overlay.create(this._buildConfig());this._attachSubscription=e.attachments().subscribe(()=>this.attach.emit()),this._detachSubscription=e.detachments().subscribe(()=>this.detach.emit()),e.keydownEvents().subscribe(i=>{this.overlayKeydown.next(i),27===i.keyCode&&!this.disableClose&&!Xt(i)&&(i.preventDefault(),this._detachOverlay())}),this._overlayRef.outsidePointerEvents().subscribe(i=>{this.overlayOutsideClick.next(i)})}_buildConfig(){const e=this._position=this.positionStrategy||this._createPositionStrategy(),i=new Gd({direction:this._dir,positionStrategy:e,scrollStrategy:this.scrollStrategy,hasBackdrop:this.hasBackdrop});return(this.width||0===this.width)&&(i.width=this.width),(this.height||0===this.height)&&(i.height=this.height),(this.minWidth||0===this.minWidth)&&(i.minWidth=this.minWidth),(this.minHeight||0===this.minHeight)&&(i.minHeight=this.minHeight),this.backdropClass&&(i.backdropClass=this.backdropClass),this.panelClass&&(i.panelClass=this.panelClass),i}_updatePositionStrategy(e){const i=this.positions.map(r=>({originX:r.originX,originY:r.originY,overlayX:r.overlayX,overlayY:r.overlayY,offsetX:r.offsetX||this.offsetX,offsetY:r.offsetY||this.offsetY,panelClass:r.panelClass||void 0}));return e.setOrigin(this._getFlexibleConnectedPositionStrategyOrigin()).withPositions(i).withFlexibleDimensions(this.flexibleDimensions).withPush(this.push).withGrowAfterOpen(this.growAfterOpen).withViewportMargin(this.viewportMargin).withLockedPosition(this.lockPosition).withTransformOriginOn(this.transformOriginSelector)}_createPositionStrategy(){const e=this._overlay.position().flexibleConnectedTo(this._getFlexibleConnectedPositionStrategyOrigin());return this._updatePositionStrategy(e),e}_getFlexibleConnectedPositionStrategyOrigin(){return this.origin instanceof VE?this.origin.elementRef:this.origin}_attachOverlay(){this._overlayRef?this._overlayRef.getConfig().hasBackdrop=this.hasBackdrop:this._createOverlay(),this._overlayRef.hasAttached()||this._overlayRef.attach(this._templatePortal),this.hasBackdrop?this._backdropSubscription=this._overlayRef.backdropClick().subscribe(e=>{this.backdropClick.emit(e)}):this._backdropSubscription.unsubscribe(),this._positionSubscription.unsubscribe(),this.positionChange.observers.length>0&&(this._positionSubscription=this._position.positionChanges.pipe(function y5(n,t=!1){return qe((e,i)=>{let r=0;e.subscribe(Ue(i,s=>{const o=n(s,r++);(o||t)&&i.next(s),!o&&i.complete()}))})}(()=>this.positionChange.observers.length>0)).subscribe(e=>{this.positionChange.emit(e),0===this.positionChange.observers.length&&this._positionSubscription.unsubscribe()}))}_detachOverlay(){this._overlayRef&&this._overlayRef.detach(),this._backdropSubscription.unsubscribe(),this._positionSubscription.unsubscribe()}}return n.\\u0275fac=function(e){return new(e||n)(f(ni),f(ut),f(st),f(BE),f(On,8))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"cdk-connected-overlay\",\"\"],[\"\",\"connected-overlay\",\"\"],[\"\",\"cdkConnectedOverlay\",\"\"]],inputs:{origin:[\"cdkConnectedOverlayOrigin\",\"origin\"],positions:[\"cdkConnectedOverlayPositions\",\"positions\"],positionStrategy:[\"cdkConnectedOverlayPositionStrategy\",\"positionStrategy\"],offsetX:[\"cdkConnectedOverlayOffsetX\",\"offsetX\"],offsetY:[\"cdkConnectedOverlayOffsetY\",\"offsetY\"],width:[\"cdkConnectedOverlayWidth\",\"width\"],height:[\"cdkConnectedOverlayHeight\",\"height\"],minWidth:[\"cdkConnectedOverlayMinWidth\",\"minWidth\"],minHeight:[\"cdkConnectedOverlayMinHeight\",\"minHeight\"],backdropClass:[\"cdkConnectedOverlayBackdropClass\",\"backdropClass\"],panelClass:[\"cdkConnectedOverlayPanelClass\",\"panelClass\"],viewportMargin:[\"cdkConnectedOverlayViewportMargin\",\"viewportMargin\"],scrollStrategy:[\"cdkConnectedOverlayScrollStrategy\",\"scrollStrategy\"],open:[\"cdkConnectedOverlayOpen\",\"open\"],disableClose:[\"cdkConnectedOverlayDisableClose\",\"disableClose\"],transformOriginSelector:[\"cdkConnectedOverlayTransformOriginOn\",\"transformOriginSelector\"],hasBackdrop:[\"cdkConnectedOverlayHasBackdrop\",\"hasBackdrop\"],lockPosition:[\"cdkConnectedOverlayLockPosition\",\"lockPosition\"],flexibleDimensions:[\"cdkConnectedOverlayFlexibleDimensions\",\"flexibleDimensions\"],growAfterOpen:[\"cdkConnectedOverlayGrowAfterOpen\",\"growAfterOpen\"],push:[\"cdkConnectedOverlayPush\",\"push\"]},outputs:{backdropClick:\"backdropClick\",positionChange:\"positionChange\",attach:\"attach\",detach:\"detach\",overlayKeydown:\"overlayKeydown\",overlayOutsideClick:\"overlayOutsideClick\"},exportAs:[\"cdkConnectedOverlay\"],features:[Je]}),n})();const F5={provide:BE,deps:[ni],useFactory:function P5(n){return()=>n.scrollStrategies.reposition()}};let ji=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[ni,F5],imports:[[lo,Hi,Ud],Ud]}),n})();class nl{constructor(t=!1,e,i=!0){this._multiple=t,this._emitChanges=i,this._selection=new Set,this._deselectedToEmit=[],this._selectedToEmit=[],this.changed=new O,e&&e.length&&(t?e.forEach(r=>this._markSelected(r)):this._markSelected(e[0]),this._selectedToEmit.length=0)}get selected(){return this._selected||(this._selected=Array.from(this._selection.values())),this._selected}select(...t){this._verifyValueAssignment(t),t.forEach(e=>this._markSelected(e)),this._emitChangeEvent()}deselect(...t){this._verifyValueAssignment(t),t.forEach(e=>this._unmarkSelected(e)),this._emitChangeEvent()}toggle(t){this.isSelected(t)?this.deselect(t):this.select(t)}clear(){this._unmarkAll(),this._emitChangeEvent()}isSelected(t){return this._selection.has(t)}isEmpty(){return 0===this._selection.size}hasValue(){return!this.isEmpty()}sort(t){this._multiple&&this.selected&&this._selected.sort(t)}isMultipleSelection(){return this._multiple}_emitChangeEvent(){this._selected=null,(this._selectedToEmit.length||this._deselectedToEmit.length)&&(this.changed.next({source:this,added:this._selectedToEmit,removed:this._deselectedToEmit}),this._deselectedToEmit=[],this._selectedToEmit=[])}_markSelected(t){this.isSelected(t)||(this._multiple||this._unmarkAll(),this._selection.add(t),this._emitChanges&&this._selectedToEmit.push(t))}_unmarkSelected(t){this.isSelected(t)&&(this._selection.delete(t),this._emitChanges&&this._deselectedToEmit.push(t))}_unmarkAll(){this.isEmpty()||this._selection.forEach(t=>this._unmarkSelected(t))}_verifyValueAssignment(t){}}const L5=[\"trigger\"],B5=[\"panel\"];function V5(n,t){if(1&n&&(x(0,\"span\",8),we(1),S()),2&n){const e=Be();T(1),Ut(e.placeholder)}}function H5(n,t){if(1&n&&(x(0,\"span\",12),we(1),S()),2&n){const e=Be(2);T(1),Ut(e.triggerValue)}}function j5(n,t){1&n&&Pe(0,0,[\"*ngSwitchCase\",\"true\"])}function z5(n,t){1&n&&(x(0,\"span\",9),Ee(1,H5,2,1,\"span\",10),Ee(2,j5,1,0,\"ng-content\",11),S()),2&n&&(N(\"ngSwitch\",!!Be().customTrigger),T(2),N(\"ngSwitchCase\",!0))}function U5(n,t){if(1&n){const e=ia();x(0,\"div\",13)(1,\"div\",14,15),J(\"@transformPanel.done\",function(r){return Dr(e),Be()._panelDoneAnimatingStream.next(r.toState)})(\"keydown\",function(r){return Dr(e),Be()._handleKeydown(r)}),Pe(3,1),S()()}if(2&n){const e=Be();N(\"@transformPanelWrap\",void 0),T(1),cC(\"mat-select-panel \",e._getPanelTheme(),\"\"),$n(\"transform-origin\",e._transformOrigin)(\"font-size\",e._triggerFontSize,\"px\"),N(\"ngClass\",e.panelClass)(\"@transformPanel\",e.multiple?\"showing-multiple\":\"showing\"),Z(\"id\",e.id+\"-panel\")(\"aria-multiselectable\",e.multiple)(\"aria-label\",e.ariaLabel||null)(\"aria-labelledby\",e._getPanelAriaLabelledby())}}const $5=[[[\"mat-select-trigger\"]],\"*\"],G5=[\"mat-select-trigger\",\"*\"],UE={transformPanelWrap:Ke(\"transformPanelWrap\",[ge(\"* => void\",no(\"@transformPanel\",[to()],{optional:!0}))]),transformPanel:Ke(\"transformPanel\",[ae(\"void\",R({transform:\"scaleY(0.8)\",minWidth:\"100%\",opacity:0})),ae(\"showing\",R({opacity:1,minWidth:\"calc(100% + 32px)\",transform:\"scaleY(1)\"})),ae(\"showing-multiple\",R({opacity:1,minWidth:\"calc(100% + 64px)\",transform:\"scaleY(1)\"})),ge(\"void => *\",be(\"120ms cubic-bezier(0, 0, 0.2, 1)\")),ge(\"* => void\",be(\"100ms 25ms linear\",R({opacity:0})))])};let $E=0;const WE=new b(\"mat-select-scroll-strategy\"),Q5=new b(\"MAT_SELECT_CONFIG\"),K5={provide:WE,deps:[ni],useFactory:function Y5(n){return()=>n.scrollStrategies.reposition()}};class Z5{constructor(t,e){this.source=t,this.value=e}}const X5=ar(Kr(po(ng(class{constructor(n,t,e,i,r){this._elementRef=n,this._defaultErrorStateMatcher=t,this._parentForm=e,this._parentFormGroup=i,this.ngControl=r}})))),J5=new b(\"MatSelectTrigger\");let e$=(()=>{class n extends X5{constructor(e,i,r,s,o,a,l,c,d,u,h,p,m,g){var _,D,v;super(o,s,l,c,u),this._viewportRuler=e,this._changeDetectorRef=i,this._ngZone=r,this._dir=a,this._parentFormField=d,this._liveAnnouncer=m,this._defaultOptions=g,this._panelOpen=!1,this._compareWith=(M,V)=>M===V,this._uid=\"mat-select-\"+$E++,this._triggerAriaLabelledBy=null,this._destroy=new O,this._onChange=()=>{},this._onTouched=()=>{},this._valueId=\"mat-select-value-\"+$E++,this._panelDoneAnimatingStream=new O,this._overlayPanelClass=(null===(_=this._defaultOptions)||void 0===_?void 0:_.overlayPanelClass)||\"\",this._focused=!1,this.controlType=\"mat-select\",this._multiple=!1,this._disableOptionCentering=null!==(v=null===(D=this._defaultOptions)||void 0===D?void 0:D.disableOptionCentering)&&void 0!==v&&v,this.ariaLabel=\"\",this.optionSelectionChanges=xa(()=>{const M=this.options;return M?M.changes.pipe(Xn(M),kn(()=>Bt(...M.map(V=>V.onSelectionChange)))):this._ngZone.onStable.pipe(it(1),kn(()=>this.optionSelectionChanges))}),this.openedChange=new $,this._openedStream=this.openedChange.pipe(Ct(M=>M),ue(()=>{})),this._closedStream=this.openedChange.pipe(Ct(M=>!M),ue(()=>{})),this.selectionChange=new $,this.valueChange=new $,this.ngControl&&(this.ngControl.valueAccessor=this),null!=(null==g?void 0:g.typeaheadDebounceInterval)&&(this._typeaheadDebounceInterval=g.typeaheadDebounceInterval),this._scrollStrategyFactory=p,this._scrollStrategy=this._scrollStrategyFactory(),this.tabIndex=parseInt(h)||0,this.id=this.id}get focused(){return this._focused||this._panelOpen}get placeholder(){return this._placeholder}set placeholder(e){this._placeholder=e,this.stateChanges.next()}get required(){var e,i,r,s;return null!==(s=null!==(e=this._required)&&void 0!==e?e:null===(r=null===(i=this.ngControl)||void 0===i?void 0:i.control)||void 0===r?void 0:r.hasValidator(yi.required))&&void 0!==s&&s}set required(e){this._required=G(e),this.stateChanges.next()}get multiple(){return this._multiple}set multiple(e){this._multiple=G(e)}get disableOptionCentering(){return this._disableOptionCentering}set disableOptionCentering(e){this._disableOptionCentering=G(e)}get compareWith(){return this._compareWith}set compareWith(e){this._compareWith=e,this._selectionModel&&this._initializeSelection()}get value(){return this._value}set value(e){(e!==this._value||this._multiple&&Array.isArray(e))&&(this.options&&this._setSelectionByValue(e),this._value=e)}get typeaheadDebounceInterval(){return this._typeaheadDebounceInterval}set typeaheadDebounceInterval(e){this._typeaheadDebounceInterval=Et(e)}get id(){return this._id}set id(e){this._id=e||this._uid,this.stateChanges.next()}ngOnInit(){this._selectionModel=new nl(this.multiple),this.stateChanges.next(),this._panelDoneAnimatingStream.pipe(Gx(),Ie(this._destroy)).subscribe(()=>this._panelDoneAnimating(this.panelOpen))}ngAfterContentInit(){this._initKeyManager(),this._selectionModel.changed.pipe(Ie(this._destroy)).subscribe(e=>{e.added.forEach(i=>i.select()),e.removed.forEach(i=>i.deselect())}),this.options.changes.pipe(Xn(null),Ie(this._destroy)).subscribe(()=>{this._resetOptions(),this._initializeSelection()})}ngDoCheck(){const e=this._getTriggerAriaLabelledby(),i=this.ngControl;if(e!==this._triggerAriaLabelledBy){const r=this._elementRef.nativeElement;this._triggerAriaLabelledBy=e,e?r.setAttribute(\"aria-labelledby\",e):r.removeAttribute(\"aria-labelledby\")}i&&(this._previousControl!==i.control&&(void 0!==this._previousControl&&null!==i.disabled&&i.disabled!==this.disabled&&(this.disabled=i.disabled),this._previousControl=i.control),this.updateErrorState())}ngOnChanges(e){e.disabled&&this.stateChanges.next(),e.typeaheadDebounceInterval&&this._keyManager&&this._keyManager.withTypeAhead(this._typeaheadDebounceInterval)}ngOnDestroy(){this._destroy.next(),this._destroy.complete(),this.stateChanges.complete()}toggle(){this.panelOpen?this.close():this.open()}open(){this._canOpen()&&(this._panelOpen=!0,this._keyManager.withHorizontalOrientation(null),this._highlightCorrectOption(),this._changeDetectorRef.markForCheck())}close(){this._panelOpen&&(this._panelOpen=!1,this._keyManager.withHorizontalOrientation(this._isRtl()?\"rtl\":\"ltr\"),this._changeDetectorRef.markForCheck(),this._onTouched())}writeValue(e){this.value=e}registerOnChange(e){this._onChange=e}registerOnTouched(e){this._onTouched=e}setDisabledState(e){this.disabled=e,this._changeDetectorRef.markForCheck(),this.stateChanges.next()}get panelOpen(){return this._panelOpen}get selected(){var e,i;return this.multiple?(null===(e=this._selectionModel)||void 0===e?void 0:e.selected)||[]:null===(i=this._selectionModel)||void 0===i?void 0:i.selected[0]}get triggerValue(){if(this.empty)return\"\";if(this._multiple){const e=this._selectionModel.selected.map(i=>i.viewValue);return this._isRtl()&&e.reverse(),e.join(\", \")}return this._selectionModel.selected[0].viewValue}_isRtl(){return!!this._dir&&\"rtl\"===this._dir.value}_handleKeydown(e){this.disabled||(this.panelOpen?this._handleOpenKeydown(e):this._handleClosedKeydown(e))}_handleClosedKeydown(e){const i=e.keyCode,r=40===i||38===i||37===i||39===i,s=13===i||32===i,o=this._keyManager;if(!o.isTyping()&&s&&!Xt(e)||(this.multiple||e.altKey)&&r)e.preventDefault(),this.open();else if(!this.multiple){const a=this.selected;o.onKeydown(e);const l=this.selected;l&&a!==l&&this._liveAnnouncer.announce(l.viewValue,1e4)}}_handleOpenKeydown(e){const i=this._keyManager,r=e.keyCode,s=40===r||38===r,o=i.isTyping();if(s&&e.altKey)e.preventDefault(),this.close();else if(o||13!==r&&32!==r||!i.activeItem||Xt(e))if(!o&&this._multiple&&65===r&&e.ctrlKey){e.preventDefault();const a=this.options.some(l=>!l.disabled&&!l.selected);this.options.forEach(l=>{l.disabled||(a?l.select():l.deselect())})}else{const a=i.activeItemIndex;i.onKeydown(e),this._multiple&&s&&e.shiftKey&&i.activeItem&&i.activeItemIndex!==a&&i.activeItem._selectViaInteraction()}else e.preventDefault(),i.activeItem._selectViaInteraction()}_onFocus(){this.disabled||(this._focused=!0,this.stateChanges.next())}_onBlur(){this._focused=!1,!this.disabled&&!this.panelOpen&&(this._onTouched(),this._changeDetectorRef.markForCheck(),this.stateChanges.next())}_onAttached(){this._overlayDir.positionChange.pipe(it(1)).subscribe(()=>{this._changeDetectorRef.detectChanges(),this._positioningSettled()})}_getPanelTheme(){return this._parentFormField?`mat-${this._parentFormField.color}`:\"\"}get empty(){return!this._selectionModel||this._selectionModel.isEmpty()}_initializeSelection(){Promise.resolve().then(()=>{this.ngControl&&(this._value=this.ngControl.value),this._setSelectionByValue(this._value),this.stateChanges.next()})}_setSelectionByValue(e){if(this._selectionModel.selected.forEach(i=>i.setInactiveStyles()),this._selectionModel.clear(),this.multiple&&e)Array.isArray(e),e.forEach(i=>this._selectValue(i)),this._sortValues();else{const i=this._selectValue(e);i?this._keyManager.updateActiveItem(i):this.panelOpen||this._keyManager.updateActiveItem(-1)}this._changeDetectorRef.markForCheck()}_selectValue(e){const i=this.options.find(r=>{if(this._selectionModel.isSelected(r))return!1;try{return null!=r.value&&this._compareWith(r.value,e)}catch(s){return!1}});return i&&this._selectionModel.select(i),i}_initKeyManager(){this._keyManager=new c3(this.options).withTypeAhead(this._typeaheadDebounceInterval).withVerticalOrientation().withHorizontalOrientation(this._isRtl()?\"rtl\":\"ltr\").withHomeAndEnd().withAllowedModifierKeys([\"shiftKey\"]),this._keyManager.tabOut.pipe(Ie(this._destroy)).subscribe(()=>{this.panelOpen&&(!this.multiple&&this._keyManager.activeItem&&this._keyManager.activeItem._selectViaInteraction(),this.focus(),this.close())}),this._keyManager.change.pipe(Ie(this._destroy)).subscribe(()=>{this._panelOpen&&this.panel?this._scrollOptionIntoView(this._keyManager.activeItemIndex||0):!this._panelOpen&&!this.multiple&&this._keyManager.activeItem&&this._keyManager.activeItem._selectViaInteraction()})}_resetOptions(){const e=Bt(this.options.changes,this._destroy);this.optionSelectionChanges.pipe(Ie(e)).subscribe(i=>{this._onSelect(i.source,i.isUserInput),i.isUserInput&&!this.multiple&&this._panelOpen&&(this.close(),this.focus())}),Bt(...this.options.map(i=>i._stateChanges)).pipe(Ie(e)).subscribe(()=>{this._changeDetectorRef.markForCheck(),this.stateChanges.next()})}_onSelect(e,i){const r=this._selectionModel.isSelected(e);null!=e.value||this._multiple?(r!==e.selected&&(e.selected?this._selectionModel.select(e):this._selectionModel.deselect(e)),i&&this._keyManager.setActiveItem(e),this.multiple&&(this._sortValues(),i&&this.focus())):(e.deselect(),this._selectionModel.clear(),null!=this.value&&this._propagateChanges(e.value)),r!==this._selectionModel.isSelected(e)&&this._propagateChanges(),this.stateChanges.next()}_sortValues(){if(this.multiple){const e=this.options.toArray();this._selectionModel.sort((i,r)=>this.sortComparator?this.sortComparator(i,r,e):e.indexOf(i)-e.indexOf(r)),this.stateChanges.next()}}_propagateChanges(e){let i=null;i=this.multiple?this.selected.map(r=>r.value):this.selected?this.selected.value:e,this._value=i,this.valueChange.emit(i),this._onChange(i),this.selectionChange.emit(this._getChangeEvent(i)),this._changeDetectorRef.markForCheck()}_highlightCorrectOption(){this._keyManager&&(this.empty?this._keyManager.setFirstItemActive():this._keyManager.setActiveItem(this._selectionModel.selected[0]))}_canOpen(){var e;return!this._panelOpen&&!this.disabled&&(null===(e=this.options)||void 0===e?void 0:e.length)>0}focus(e){this._elementRef.nativeElement.focus(e)}_getPanelAriaLabelledby(){var e;if(this.ariaLabel)return null;const i=null===(e=this._parentFormField)||void 0===e?void 0:e.getLabelId();return this.ariaLabelledby?(i?i+\" \":\"\")+this.ariaLabelledby:i}_getAriaActiveDescendant(){return this.panelOpen&&this._keyManager&&this._keyManager.activeItem?this._keyManager.activeItem.id:null}_getTriggerAriaLabelledby(){var e;if(this.ariaLabel)return null;const i=null===(e=this._parentFormField)||void 0===e?void 0:e.getLabelId();let r=(i?i+\" \":\"\")+this._valueId;return this.ariaLabelledby&&(r+=\" \"+this.ariaLabelledby),r}_panelDoneAnimating(e){this.openedChange.emit(e)}setDescribedByIds(e){this._ariaDescribedby=e.join(\" \")}onContainerClick(){this.focus(),this.open()}get shouldLabelFloat(){return this._panelOpen||!this.empty||this._focused&&!!this._placeholder}}return n.\\u0275fac=function(e){return new(e||n)(f(es),f(Ye),f(ne),f(mo),f(W),f(On,8),f(oo,8),f(ao,8),f(el,8),f(Jn,10),kt(\"tabindex\"),f(WE),f(k3),f(Q5,8))},n.\\u0275dir=C({type:n,viewQuery:function(e,i){if(1&e&&(je(L5,5),je(B5,5),je(HE,5)),2&e){let r;z(r=U())&&(i.trigger=r.first),z(r=U())&&(i.panel=r.first),z(r=U())&&(i._overlayDir=r.first)}},inputs:{panelClass:\"panelClass\",placeholder:\"placeholder\",required:\"required\",multiple:\"multiple\",disableOptionCentering:\"disableOptionCentering\",compareWith:\"compareWith\",value:\"value\",ariaLabel:[\"aria-label\",\"ariaLabel\"],ariaLabelledby:[\"aria-labelledby\",\"ariaLabelledby\"],errorStateMatcher:\"errorStateMatcher\",typeaheadDebounceInterval:\"typeaheadDebounceInterval\",sortComparator:\"sortComparator\",id:\"id\"},outputs:{openedChange:\"openedChange\",_openedStream:\"opened\",_closedStream:\"closed\",selectionChange:\"selectionChange\",valueChange:\"valueChange\"},features:[E,Je]}),n})(),t$=(()=>{class n extends e${constructor(){super(...arguments),this._scrollTop=0,this._triggerFontSize=0,this._transformOrigin=\"top\",this._offsetY=0,this._positions=[{originX:\"start\",originY:\"top\",overlayX:\"start\",overlayY:\"top\"},{originX:\"start\",originY:\"bottom\",overlayX:\"start\",overlayY:\"bottom\"}]}_calculateOverlayScroll(e,i,r){const s=this._getItemHeight();return Math.min(Math.max(0,s*e-i+s/2),r)}ngOnInit(){super.ngOnInit(),this._viewportRuler.change().pipe(Ie(this._destroy)).subscribe(()=>{this.panelOpen&&(this._triggerRect=this.trigger.nativeElement.getBoundingClientRect(),this._changeDetectorRef.markForCheck())})}open(){super._canOpen()&&(super.open(),this._triggerRect=this.trigger.nativeElement.getBoundingClientRect(),this._triggerFontSize=parseInt(getComputedStyle(this.trigger.nativeElement).fontSize||\"0\"),this._calculateOverlayPosition(),this._ngZone.onStable.pipe(it(1)).subscribe(()=>{this._triggerFontSize&&this._overlayDir.overlayRef&&this._overlayDir.overlayRef.overlayElement&&(this._overlayDir.overlayRef.overlayElement.style.fontSize=`${this._triggerFontSize}px`)}))}_scrollOptionIntoView(e){const i=cg(e,this.options,this.optionGroups),r=this._getItemHeight();this.panel.nativeElement.scrollTop=0===e&&1===i?0:function pE(n,t,e,i){return n<e?n:n+t>e+i?Math.max(0,n-i+t):e}((e+i)*r,r,this.panel.nativeElement.scrollTop,256)}_positioningSettled(){this._calculateOverlayOffsetX(),this.panel.nativeElement.scrollTop=this._scrollTop}_panelDoneAnimating(e){this.panelOpen?this._scrollTop=0:(this._overlayDir.offsetX=0,this._changeDetectorRef.markForCheck()),super._panelDoneAnimating(e)}_getChangeEvent(e){return new Z5(this,e)}_calculateOverlayOffsetX(){const e=this._overlayDir.overlayRef.overlayElement.getBoundingClientRect(),i=this._viewportRuler.getViewportSize(),r=this._isRtl(),s=this.multiple?56:32;let o;if(this.multiple)o=40;else if(this.disableOptionCentering)o=16;else{let c=this._selectionModel.selected[0]||this.options.first;o=c&&c.group?32:16}r||(o*=-1);const a=0-(e.left+o-(r?s:0)),l=e.right+o-i.width+(r?0:s);a>0?o+=a+8:l>0&&(o-=l+8),this._overlayDir.offsetX=Math.round(o),this._overlayDir.overlayRef.updatePosition()}_calculateOverlayOffsetY(e,i,r){const s=this._getItemHeight(),o=(s-this._triggerRect.height)/2,a=Math.floor(256/s);let l;return this.disableOptionCentering?0:(l=0===this._scrollTop?e*s:this._scrollTop===r?(e-(this._getItemCount()-a))*s+(s-(this._getItemCount()*s-256)%s):i-s/2,Math.round(-1*l-o))}_checkOverlayWithinViewport(e){const i=this._getItemHeight(),r=this._viewportRuler.getViewportSize(),s=this._triggerRect.top-8,o=r.height-this._triggerRect.bottom-8,a=Math.abs(this._offsetY),c=Math.min(this._getItemCount()*i,256)-a-this._triggerRect.height;c>o?this._adjustPanelUp(c,o):a>s?this._adjustPanelDown(a,s,e):this._transformOrigin=this._getOriginBasedOnOption()}_adjustPanelUp(e,i){const r=Math.round(e-i);this._scrollTop-=r,this._offsetY-=r,this._transformOrigin=this._getOriginBasedOnOption(),this._scrollTop<=0&&(this._scrollTop=0,this._offsetY=0,this._transformOrigin=\"50% bottom 0px\")}_adjustPanelDown(e,i,r){const s=Math.round(e-i);if(this._scrollTop+=s,this._offsetY+=s,this._transformOrigin=this._getOriginBasedOnOption(),this._scrollTop>=r)return this._scrollTop=r,this._offsetY=0,void(this._transformOrigin=\"50% top 0px\")}_calculateOverlayPosition(){const e=this._getItemHeight(),i=this._getItemCount(),r=Math.min(i*e,256),o=i*e-r;let a;a=this.empty?0:Math.max(this.options.toArray().indexOf(this._selectionModel.selected[0]),0),a+=cg(a,this.options,this.optionGroups);const l=r/2;this._scrollTop=this._calculateOverlayScroll(a,l,o),this._offsetY=this._calculateOverlayOffsetY(a,l,o),this._checkOverlayWithinViewport(o)}_getOriginBasedOnOption(){const e=this._getItemHeight(),i=(e-this._triggerRect.height)/2;return`50% ${Math.abs(this._offsetY)-i+e/2}px 0px`}_getItemHeight(){return 3*this._triggerFontSize}_getItemCount(){return this.options.length+this.optionGroups.length}}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275cmp=xe({type:n,selectors:[[\"mat-select\"]],contentQueries:function(e,i,r){if(1&e&&(ve(r,J5,5),ve(r,hE,5),ve(r,lg,5)),2&e){let s;z(s=U())&&(i.customTrigger=s.first),z(s=U())&&(i.options=s),z(s=U())&&(i.optionGroups=s)}},hostAttrs:[\"role\",\"combobox\",\"aria-autocomplete\",\"none\",\"aria-haspopup\",\"true\",1,\"mat-select\"],hostVars:20,hostBindings:function(e,i){1&e&&J(\"keydown\",function(s){return i._handleKeydown(s)})(\"focus\",function(){return i._onFocus()})(\"blur\",function(){return i._onBlur()}),2&e&&(Z(\"id\",i.id)(\"tabindex\",i.tabIndex)(\"aria-controls\",i.panelOpen?i.id+\"-panel\":null)(\"aria-expanded\",i.panelOpen)(\"aria-label\",i.ariaLabel||null)(\"aria-required\",i.required.toString())(\"aria-disabled\",i.disabled.toString())(\"aria-invalid\",i.errorState)(\"aria-describedby\",i._ariaDescribedby||null)(\"aria-activedescendant\",i._getAriaActiveDescendant()),Ae(\"mat-select-disabled\",i.disabled)(\"mat-select-invalid\",i.errorState)(\"mat-select-required\",i.required)(\"mat-select-empty\",i.empty)(\"mat-select-multiple\",i.multiple))},inputs:{disabled:\"disabled\",disableRipple:\"disableRipple\",tabIndex:\"tabIndex\"},exportAs:[\"matSelect\"],features:[L([{provide:Ja,useExisting:n},{provide:ag,useExisting:n}]),E],ngContentSelectors:G5,decls:9,vars:12,consts:[[\"cdk-overlay-origin\",\"\",1,\"mat-select-trigger\",3,\"click\"],[\"origin\",\"cdkOverlayOrigin\",\"trigger\",\"\"],[1,\"mat-select-value\",3,\"ngSwitch\"],[\"class\",\"mat-select-placeholder mat-select-min-line\",4,\"ngSwitchCase\"],[\"class\",\"mat-select-value-text\",3,\"ngSwitch\",4,\"ngSwitchCase\"],[1,\"mat-select-arrow-wrapper\"],[1,\"mat-select-arrow\"],[\"cdk-connected-overlay\",\"\",\"cdkConnectedOverlayLockPosition\",\"\",\"cdkConnectedOverlayHasBackdrop\",\"\",\"cdkConnectedOverlayBackdropClass\",\"cdk-overlay-transparent-backdrop\",3,\"cdkConnectedOverlayPanelClass\",\"cdkConnectedOverlayScrollStrategy\",\"cdkConnectedOverlayOrigin\",\"cdkConnectedOverlayOpen\",\"cdkConnectedOverlayPositions\",\"cdkConnectedOverlayMinWidth\",\"cdkConnectedOverlayOffsetY\",\"backdropClick\",\"attach\",\"detach\"],[1,\"mat-select-placeholder\",\"mat-select-min-line\"],[1,\"mat-select-value-text\",3,\"ngSwitch\"],[\"class\",\"mat-select-min-line\",4,\"ngSwitchDefault\"],[4,\"ngSwitchCase\"],[1,\"mat-select-min-line\"],[1,\"mat-select-panel-wrap\"],[\"role\",\"listbox\",\"tabindex\",\"-1\",3,\"ngClass\",\"keydown\"],[\"panel\",\"\"]],template:function(e,i){if(1&e&&(Lt($5),x(0,\"div\",0,1),J(\"click\",function(){return i.toggle()}),x(3,\"div\",2),Ee(4,V5,2,1,\"span\",3),Ee(5,z5,3,2,\"span\",4),S(),x(6,\"div\",5),Le(7,\"div\",6),S()(),Ee(8,U5,4,14,\"ng-template\",7),J(\"backdropClick\",function(){return i.close()})(\"attach\",function(){return i._onAttached()})(\"detach\",function(){return i.close()})),2&e){const r=wn(1);Z(\"aria-owns\",i.panelOpen?i.id+\"-panel\":null),T(3),N(\"ngSwitch\",i.empty),Z(\"id\",i._valueId),T(1),N(\"ngSwitchCase\",!0),T(1),N(\"ngSwitchCase\",!1),T(3),N(\"cdkConnectedOverlayPanelClass\",i._overlayPanelClass)(\"cdkConnectedOverlayScrollStrategy\",i._scrollStrategy)(\"cdkConnectedOverlayOrigin\",r)(\"cdkConnectedOverlayOpen\",i.panelOpen)(\"cdkConnectedOverlayPositions\",i._positions)(\"cdkConnectedOverlayMinWidth\",null==i._triggerRect?null:i._triggerRect.width)(\"cdkConnectedOverlayOffsetY\",i._offsetY)}},directives:[VE,Ys,Pc,yD,HE,mD],styles:['.mat-select{display:inline-block;width:100%;outline:none}.mat-select-trigger{display:inline-table;cursor:pointer;position:relative;box-sizing:border-box}.mat-select-disabled .mat-select-trigger{-webkit-user-select:none;-moz-user-select:none;user-select:none;cursor:default}.mat-select-value{display:table-cell;max-width:0;width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mat-select-value-text{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.mat-select-arrow-wrapper{display:table-cell;vertical-align:middle}.mat-form-field-appearance-fill .mat-select-arrow-wrapper{transform:translateY(-50%)}.mat-form-field-appearance-outline .mat-select-arrow-wrapper{transform:translateY(-25%)}.mat-form-field-appearance-standard.mat-form-field-has-label .mat-select:not(.mat-select-empty) .mat-select-arrow-wrapper{transform:translateY(-50%)}.mat-form-field-appearance-standard .mat-select.mat-select-empty .mat-select-arrow-wrapper{transition:transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1)}._mat-animation-noopable.mat-form-field-appearance-standard .mat-select.mat-select-empty .mat-select-arrow-wrapper{transition:none}.mat-select-arrow{width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;border-top:5px solid;margin:0 4px}.mat-form-field.mat-focused .mat-select-arrow{transform:translateX(0)}.mat-select-panel-wrap{flex-basis:100%}.mat-select-panel{min-width:112px;max-width:280px;overflow:auto;-webkit-overflow-scrolling:touch;padding-top:0;padding-bottom:0;max-height:256px;min-width:100%;border-radius:4px;outline:0}.cdk-high-contrast-active .mat-select-panel{outline:solid 1px}.mat-select-panel .mat-optgroup-label,.mat-select-panel .mat-option{font-size:inherit;line-height:3em;height:3em}.mat-form-field-type-mat-select:not(.mat-form-field-disabled) .mat-form-field-flex{cursor:pointer}.mat-form-field-type-mat-select .mat-form-field-label{width:calc(100% - 18px)}.mat-select-placeholder{transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}._mat-animation-noopable .mat-select-placeholder{transition:none}.mat-form-field-hide-placeholder .mat-select-placeholder{color:transparent;-webkit-text-fill-color:transparent;transition:none;display:block}.mat-select-min-line:empty::before{content:\" \";white-space:pre;width:1px;display:inline-block;opacity:0}\\n'],encapsulation:2,data:{animation:[UE.transformPanelWrap,UE.transformPanel]},changeDetection:0}),n})(),qE=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[K5],imports:[[bt,ji,Hd,B],Ci,mg,Hd,B]}),n})();const YE=ei({passive:!0});let n$=(()=>{class n{constructor(e,i){this._platform=e,this._ngZone=i,this._monitoredElements=new Map}monitor(e){if(!this._platform.isBrowser)return ri;const i=at(e),r=this._monitoredElements.get(i);if(r)return r.subject;const s=new O,o=\"cdk-text-field-autofilled\",a=l=>{\"cdk-text-field-autofill-start\"!==l.animationName||i.classList.contains(o)?\"cdk-text-field-autofill-end\"===l.animationName&&i.classList.contains(o)&&(i.classList.remove(o),this._ngZone.run(()=>s.next({target:l.target,isAutofilled:!1}))):(i.classList.add(o),this._ngZone.run(()=>s.next({target:l.target,isAutofilled:!0})))};return this._ngZone.runOutsideAngular(()=>{i.addEventListener(\"animationstart\",a,YE),i.classList.add(\"cdk-text-field-autofill-monitored\")}),this._monitoredElements.set(i,{subject:s,unlisten:()=>{i.removeEventListener(\"animationstart\",a,YE)}}),s}stopMonitoring(e){const i=at(e),r=this._monitoredElements.get(i);r&&(r.unlisten(),r.subject.complete(),i.classList.remove(\"cdk-text-field-autofill-monitored\"),i.classList.remove(\"cdk-text-field-autofilled\"),this._monitoredElements.delete(i))}ngOnDestroy(){this._monitoredElements.forEach((e,i)=>this.stopMonitoring(i))}}return n.\\u0275fac=function(e){return new(e||n)(y(It),y(ne))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),QE=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const KE=new b(\"MAT_INPUT_VALUE_ACCESSOR\"),i$=[\"button\",\"checkbox\",\"file\",\"hidden\",\"image\",\"radio\",\"range\",\"reset\",\"submit\"];let r$=0;const s$=ng(class{constructor(n,t,e,i){this._defaultErrorStateMatcher=n,this._parentForm=t,this._parentFormGroup=e,this.ngControl=i}});let o$=(()=>{class n extends s${constructor(e,i,r,s,o,a,l,c,d,u){super(a,s,o,r),this._elementRef=e,this._platform=i,this._autofillMonitor=c,this._formField=u,this._uid=\"mat-input-\"+r$++,this.focused=!1,this.stateChanges=new O,this.controlType=\"mat-input\",this.autofilled=!1,this._disabled=!1,this._type=\"text\",this._readonly=!1,this._neverEmptyInputTypes=[\"date\",\"datetime\",\"datetime-local\",\"month\",\"time\",\"week\"].filter(m=>Hx().has(m));const h=this._elementRef.nativeElement,p=h.nodeName.toLowerCase();this._inputValueAccessor=l||h,this._previousNativeValue=this.value,this.id=this.id,i.IOS&&d.runOutsideAngular(()=>{e.nativeElement.addEventListener(\"keyup\",m=>{const g=m.target;!g.value&&0===g.selectionStart&&0===g.selectionEnd&&(g.setSelectionRange(1,1),g.setSelectionRange(0,0))})}),this._isServer=!this._platform.isBrowser,this._isNativeSelect=\"select\"===p,this._isTextarea=\"textarea\"===p,this._isInFormField=!!u,this._isNativeSelect&&(this.controlType=h.multiple?\"mat-native-select-multiple\":\"mat-native-select\")}get disabled(){return this.ngControl&&null!==this.ngControl.disabled?this.ngControl.disabled:this._disabled}set disabled(e){this._disabled=G(e),this.focused&&(this.focused=!1,this.stateChanges.next())}get id(){return this._id}set id(e){this._id=e||this._uid}get required(){var e,i,r,s;return null!==(s=null!==(e=this._required)&&void 0!==e?e:null===(r=null===(i=this.ngControl)||void 0===i?void 0:i.control)||void 0===r?void 0:r.hasValidator(yi.required))&&void 0!==s&&s}set required(e){this._required=G(e)}get type(){return this._type}set type(e){this._type=e||\"text\",this._validateType(),!this._isTextarea&&Hx().has(this._type)&&(this._elementRef.nativeElement.type=this._type)}get value(){return this._inputValueAccessor.value}set value(e){e!==this.value&&(this._inputValueAccessor.value=e,this.stateChanges.next())}get readonly(){return this._readonly}set readonly(e){this._readonly=G(e)}ngAfterViewInit(){this._platform.isBrowser&&this._autofillMonitor.monitor(this._elementRef.nativeElement).subscribe(e=>{this.autofilled=e.isAutofilled,this.stateChanges.next()})}ngOnChanges(){this.stateChanges.next()}ngOnDestroy(){this.stateChanges.complete(),this._platform.isBrowser&&this._autofillMonitor.stopMonitoring(this._elementRef.nativeElement)}ngDoCheck(){this.ngControl&&this.updateErrorState(),this._dirtyCheckNativeValue(),this._dirtyCheckPlaceholder()}focus(e){this._elementRef.nativeElement.focus(e)}_focusChanged(e){e!==this.focused&&(this.focused=e,this.stateChanges.next())}_onInput(){}_dirtyCheckPlaceholder(){var e,i;const r=(null===(i=null===(e=this._formField)||void 0===e?void 0:e._hideControlPlaceholder)||void 0===i?void 0:i.call(e))?null:this.placeholder;if(r!==this._previousPlaceholder){const s=this._elementRef.nativeElement;this._previousPlaceholder=r,r?s.setAttribute(\"placeholder\",r):s.removeAttribute(\"placeholder\")}}_dirtyCheckNativeValue(){const e=this._elementRef.nativeElement.value;this._previousNativeValue!==e&&(this._previousNativeValue=e,this.stateChanges.next())}_validateType(){i$.indexOf(this._type)}_isNeverEmpty(){return this._neverEmptyInputTypes.indexOf(this._type)>-1}_isBadInput(){let e=this._elementRef.nativeElement.validity;return e&&e.badInput}get empty(){return!(this._isNeverEmpty()||this._elementRef.nativeElement.value||this._isBadInput()||this.autofilled)}get shouldLabelFloat(){if(this._isNativeSelect){const e=this._elementRef.nativeElement,i=e.options[0];return this.focused||e.multiple||!this.empty||!!(e.selectedIndex>-1&&i&&i.label)}return this.focused||!this.empty}setDescribedByIds(e){e.length?this._elementRef.nativeElement.setAttribute(\"aria-describedby\",e.join(\" \")):this._elementRef.nativeElement.removeAttribute(\"aria-describedby\")}onContainerClick(){this.focused||this.focus()}_isInlineSelect(){const e=this._elementRef.nativeElement;return this._isNativeSelect&&(e.multiple||e.size>1)}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(It),f(Jn,10),f(oo,8),f(ao,8),f(mo),f(KE,10),f(n$),f(ne),f(el,8))},n.\\u0275dir=C({type:n,selectors:[[\"input\",\"matInput\",\"\"],[\"textarea\",\"matInput\",\"\"],[\"select\",\"matNativeControl\",\"\"],[\"input\",\"matNativeControl\",\"\"],[\"textarea\",\"matNativeControl\",\"\"]],hostAttrs:[1,\"mat-input-element\",\"mat-form-field-autofill-control\"],hostVars:12,hostBindings:function(e,i){1&e&&J(\"focus\",function(){return i._focusChanged(!0)})(\"blur\",function(){return i._focusChanged(!1)})(\"input\",function(){return i._onInput()}),2&e&&(Yn(\"disabled\",i.disabled)(\"required\",i.required),Z(\"id\",i.id)(\"data-placeholder\",i.placeholder)(\"name\",i.name||null)(\"readonly\",i.readonly&&!i._isNativeSelect||null)(\"aria-invalid\",i.empty&&i.required?null:i.errorState)(\"aria-required\",i.required),Ae(\"mat-input-server\",i._isServer)(\"mat-native-select-inline\",i._isInlineSelect()))},inputs:{disabled:\"disabled\",id:\"id\",placeholder:\"placeholder\",name:\"name\",required:\"required\",type:\"type\",errorStateMatcher:\"errorStateMatcher\",userAriaDescribedBy:[\"aria-describedby\",\"userAriaDescribedBy\"],value:\"value\",readonly:\"readonly\"},exportAs:[\"matInput\"],features:[L([{provide:Ja,useExisting:n}]),E,Je]}),n})(),a$=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[mo],imports:[[QE,mg,B],QE,mg]}),n})();function l$(n,t){if(1&n&&(x(0,\"mat-option\",13),we(1),S()),2&n){const e=t.$implicit;N(\"value\",e.name)(\"disabled\",e.disabled),T(1),Ut(e.description)}}function c$(n,t){if(1&n&&(x(0,\"mat-option\",13),we(1),S()),2&n){const e=t.$implicit,i=t.index;N(\"value\",e)(\"disabled\",i>0),T(1),Ut(e)}}function d$(n,t){if(1&n&&(x(0,\"mat-error\"),we(1),S()),2&n){const e=Be();T(1),Ut(e.explainTheError(e.srcAmountControl))}}function u$(n,t){if(1&n&&(x(0,\"mat-option\",13),we(1),S()),2&n){const e=t.$implicit;N(\"value\",e.name)(\"disabled\",e.disabled),T(1),Ut(e.description)}}function h$(n,t){if(1&n&&(x(0,\"mat-option\",13),we(1),S()),2&n){const e=t.$implicit,i=t.index;N(\"value\",e)(\"disabled\",i>0),T(1),Ut(e)}}function p$(n,t){if(1&n&&(x(0,\"mat-error\"),we(1),S()),2&n){const e=Be();T(1),Ut(e.explainTheError(e.dstAmountControl))}}let f$=(()=>{class n{constructor(){var e,i;this.srcAmountControl=new Rd(\"0\",[yi.pattern(/\\d+/),yi.min(1),yi.max(9999)]),this.dstAmountControl=new Rd(\"0\",[yi.pattern(/\\d+/),yi.min(1),yi.max(9999)]),this.srcChainList=Xa.map(r=>Object.assign(Object.assign({},r.from),{disabled:!r.active})),this.dstChainList=Xa.map(r=>Object.assign(Object.assign({},r.to),{disabled:!r.active})),this.srcChain=null===(e=this.srcChainList.find(r=>!r.disabled))||void 0===e?void 0:e.name,this.dstChain=(null===(i=Xa.filter(r=>r.from.name===this.srcChain).find(r=>r.active))||void 0===i?void 0:i.to.name)||\"\",this.srcCoin=\"EVER\",this.dstCoin=\"TXZ\",this.srcTokenList=ug.map(r=>r.name),this.dstTokenList=hg.map(r=>r.name),this.srcTokenChosen=\"EVER\",this.dstTokenChosen=\"wEVER\",this.srcAmount=\"0\",this.dstAmount=\"0\"}ngOnInit(){this.breakpoint=window.innerWidth<=400?1:2}onChainSrcValueChange(e){var i;this.srcChain=e,this.dstChain=(null===(i=Xa.filter(r=>r.from.name===this.srcChain).find(r=>r.active))||void 0===i?void 0:i.to.name)||\"\",this.changeTokenList(this.srcChain,this.dstChain)}onChainDstValueChange(e){var i;this.dstChain=e,this.srcChain=(null===(i=Xa.filter(r=>r.from.name===this.srcChain).find(r=>r.active))||void 0===i?void 0:i.to.name)||\"\",this.changeTokenList(this.srcChain,this.dstChain)}changeTokenList(e,i){\"Tezos\"==e&&(this.srcCoin=\"TXZ\",this.dstCoin=\"EVER\",this.srcTokenList=hg.map(r=>r.name),this.dstTokenList=ug.map(r=>r.name),this.srcTokenChosen=\"TXZ\",this.dstTokenChosen=\"wTXZ\"),\"Everscale\"===e&&(this.srcCoin=\"EVER\",this.dstCoin=\"TXZ\",this.srcTokenList=ug.map(r=>r.name),this.dstTokenList=hg.map(r=>r.name),this.srcTokenChosen=\"EVER\",this.dstTokenChosen=\"wEVER\")}onSelectionChange(e){console.log(\"onSelectionChange, newValue = \",e.value,e.source)}onSrcTokenChange(e){this.dstTokenChosen=e===this.srcTokenList[0]?this.dstCoin:this.dstTokenList[0]}onDstTokenChange(e){this.srcTokenChosen=e===this.dstTokenList[0]?this.srcCoin:this.srcTokenList[0]}calculateAmount(e,i){e?(this.dstAmount=(.99*Number.parseFloat(i)).toFixed(8).replace(/(\\.\\d*)0+/,\"$1\"),this.dstAmountControl.setValue(this.dstAmount)):(this.srcAmount=(Number.parseFloat(i)/.99).toFixed(8).replace(/\\.0+$/,\"\"),this.srcAmountControl.setValue(this.srcAmount))}explainTheError(e){const i=e.errors||{};return\"Wrong number: \"+Object.keys(i).reduce((r,s)=>{switch(s){case\"min\":return r+`minimal value is ${i[s].min}. `;case\"max\":return r+`maximum value is ${i[s].max}. `;case\"pattern\":return r+\"it should be number. \";default:return r+\"wrong amount. \"}},\"\")}consoleLog(e){console.log(e)}onResize(e){this.breakpoint=e.target.innerWidth<=400?1:2}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275cmp=xe({type:n,selectors:[[\"app-main\"]],decls:56,vars:21,consts:[[3,\"cols\",\"resize\"],[1,\"container\"],[\"appearance\",\"outline\"],[3,\"value\",\"valueChange\",\"selectionChange\"],[3,\"value\",\"disabled\",4,\"ngFor\",\"ngForOf\"],[3,\"value\",\"valueChange\"],[\"label\",\"Native coins\"],[3,\"value\"],[\"label\",\"Tokens\"],[\"matInput\",\"\",\"placeholder\",\"Amount\",\"type\",\"number\",3,\"value\",\"formControl\",\"change\"],[\"srcInputElement\",\"\"],[4,\"ngIf\"],[\"dstInputElement\",\"\"],[3,\"value\",\"disabled\"]],template:function(e,i){if(1&e){const r=ia();x(0,\"h1\"),we(1,\"Everscale-Tezos Bridge\"),S(),x(2,\"mat-grid-list\",0),J(\"resize\",function(o){return i.onResize(o)},!1,Uv),x(3,\"mat-grid-tile\")(4,\"div\",1)(5,\"h3\"),we(6,\"Choose what you have:\"),S(),x(7,\"mat-form-field\",2)(8,\"mat-label\"),we(9,\"Blockchain\"),S(),x(10,\"mat-select\",3),J(\"valueChange\",function(o){return i.srcChain=o})(\"selectionChange\",function(o){return i.onSelectionChange(o)})(\"valueChange\",function(o){return i.onChainSrcValueChange(o)}),Ee(11,l$,2,3,\"mat-option\",4),S()(),x(12,\"mat-form-field\",2)(13,\"mat-label\"),we(14,\"Token\"),S(),x(15,\"mat-select\",5),J(\"valueChange\",function(o){return i.srcTokenChosen=o})(\"valueChange\",function(o){return i.onSrcTokenChange(o)}),x(16,\"mat-optgroup\",6)(17,\"mat-option\",7),we(18),S()(),x(19,\"mat-optgroup\",8),Ee(20,c$,2,3,\"mat-option\",4),S()()(),x(21,\"mat-form-field\",2)(22,\"mat-label\"),we(23,\"Amount\"),S(),x(24,\"input\",9,10),J(\"change\",function(){Dr(r);const o=wn(25);return i.calculateAmount(!0,o.value)}),S(),x(26,\"mat-hint\"),we(27),S(),Ee(28,d$,2,1,\"mat-error\",11),S()()(),x(29,\"mat-grid-tile\")(30,\"div\",1)(31,\"h3\"),we(32,\"Choose what you want:\"),S(),x(33,\"mat-form-field\",2)(34,\"mat-label\"),we(35,\"Blockchain\"),S(),x(36,\"mat-select\",5),J(\"valueChange\",function(o){return i.dstChain=o})(\"valueChange\",function(o){return i.onChainDstValueChange(o)}),Ee(37,u$,2,3,\"mat-option\",4),S()(),x(38,\"mat-form-field\",2)(39,\"mat-label\"),we(40,\"Token\"),S(),x(41,\"mat-select\",5),J(\"valueChange\",function(o){return i.dstTokenChosen=o})(\"valueChange\",function(o){return i.onDstTokenChange(o)}),x(42,\"mat-optgroup\",6)(43,\"mat-option\",7),we(44),S()(),x(45,\"mat-optgroup\",8),Ee(46,h$,2,3,\"mat-option\",4),S()()(),x(47,\"mat-form-field\",2)(48,\"mat-label\"),we(49,\"Amount\"),S(),x(50,\"input\",9,12),J(\"change\",function(){Dr(r);const o=wn(51);return i.calculateAmount(!1,o.value)}),S(),Ee(52,p$,2,1,\"mat-error\",11),x(53,\"mat-hint\"),we(54),S()()()(),Le(55,\"router-outlet\"),S()}2&e&&(T(2),N(\"cols\",i.breakpoint),T(8),N(\"value\",i.srcChain),T(1),N(\"ngForOf\",i.srcChainList),T(4),N(\"value\",i.srcTokenChosen),T(2),N(\"value\",i.srcCoin),T(1),Ut(i.srcCoin),T(2),N(\"ngForOf\",i.srcTokenList),T(4),N(\"value\",i.srcAmount)(\"formControl\",i.srcAmountControl),T(3),qn(\"Amount of \",i.srcTokenChosen,\" to pay\"),T(1),N(\"ngIf\",i.srcAmountControl.invalid),T(8),N(\"value\",i.dstChain),T(1),N(\"ngForOf\",i.dstChainList),T(4),N(\"value\",i.dstTokenChosen),T(2),N(\"value\",i.dstCoin),T(1),Ut(i.dstCoin),T(2),N(\"ngForOf\",i.dstTokenList),T(4),N(\"value\",i.dstAmount)(\"formControl\",i.dstAmountControl),T(2),N(\"ngIf\",i.dstAmountControl.invalid),T(2),qn(\"Amount of \",i.dstTokenChosen,\" to receive\"))},directives:[bU,yE,t5,fg,t$,gD,hE,J3,o$,Tm,Dd,ax,Im,YU,Ca,GU,Pf],styles:[\".container[_ngcontent-%COMP%] .mat-form-field[_ngcontent-%COMP%] + .mat-form-field[_ngcontent-%COMP%]{margin-left:8px}mat-form-field[_ngcontent-%COMP%]{display:block}mat-grid-list[_ngcontent-%COMP%]{display:flex;flex-wrap:wrap;justify-content:center}\"]}),n})(),ZE=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),m$=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();function wg(n,t,e){for(let i in t)if(t.hasOwnProperty(i)){const r=t[i];r?n.setProperty(i,r,(null==e?void 0:e.has(i))?\"important\":\"\"):n.removeProperty(i)}return n}function _o(n,t){const e=t?\"\":\"none\";wg(n.style,{\"touch-action\":t?\"\":\"none\",\"-webkit-user-drag\":t?\"\":\"none\",\"-webkit-tap-highlight-color\":t?\"\":\"transparent\",\"user-select\":e,\"-ms-user-select\":e,\"-webkit-user-select\":e,\"-moz-user-select\":e})}function XE(n,t,e){wg(n.style,{position:t?\"\":\"fixed\",top:t?\"\":\"0\",opacity:t?\"\":\"0\",left:t?\"\":\"-999em\"},e)}function Yd(n,t){return t&&\"none\"!=t?n+\" \"+t:n}function JE(n){const t=n.toLowerCase().indexOf(\"ms\")>-1?1:1e3;return parseFloat(n)*t}function Mg(n,t){return n.getPropertyValue(t).split(\",\").map(i=>i.trim())}function xg(n){const t=n.getBoundingClientRect();return{top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:t.width,height:t.height,x:t.x,y:t.y}}function Eg(n,t,e){const{top:i,bottom:r,left:s,right:o}=n;return e>=i&&e<=r&&t>=s&&t<=o}function sl(n,t,e){n.top+=t,n.bottom=n.top+n.height,n.left+=e,n.right=n.left+n.width}function eS(n,t,e,i){const{top:r,right:s,bottom:o,left:a,width:l,height:c}=n,d=l*t,u=c*t;return i>r-u&&i<o+u&&e>a-d&&e<s+d}class tS{constructor(t){this._document=t,this.positions=new Map}clear(){this.positions.clear()}cache(t){this.clear(),this.positions.set(this._document,{scrollPosition:this.getViewportScrollPosition()}),t.forEach(e=>{this.positions.set(e,{scrollPosition:{top:e.scrollTop,left:e.scrollLeft},clientRect:xg(e)})})}handleScroll(t){const e=Pn(t),i=this.positions.get(e);if(!i)return null;const r=i.scrollPosition;let s,o;if(e===this._document){const c=this.getViewportScrollPosition();s=c.top,o=c.left}else s=e.scrollTop,o=e.scrollLeft;const a=r.top-s,l=r.left-o;return this.positions.forEach((c,d)=>{c.clientRect&&e!==d&&e.contains(d)&&sl(c.clientRect,a,l)}),r.top=s,r.left=o,{top:a,left:l}}getViewportScrollPosition(){return{top:window.scrollY,left:window.scrollX}}}function nS(n){const t=n.cloneNode(!0),e=t.querySelectorAll(\"[id]\"),i=n.nodeName.toLowerCase();t.removeAttribute(\"id\");for(let r=0;r<e.length;r++)e[r].removeAttribute(\"id\");return\"canvas\"===i?sS(n,t):(\"input\"===i||\"select\"===i||\"textarea\"===i)&&rS(n,t),iS(\"canvas\",n,t,sS),iS(\"input, textarea, select\",n,t,rS),t}function iS(n,t,e,i){const r=t.querySelectorAll(n);if(r.length){const s=e.querySelectorAll(n);for(let o=0;o<r.length;o++)i(r[o],s[o])}}let v$=0;function rS(n,t){\"file\"!==t.type&&(t.value=n.value),\"radio\"===t.type&&t.name&&(t.name=`mat-clone-${t.name}-${v$++}`)}function sS(n,t){const e=t.getContext(\"2d\");if(e)try{e.drawImage(n,0,0)}catch(i){}}const oS=ei({passive:!0}),Qd=ei({passive:!1}),Sg=new Set([\"position\"]);class b${constructor(t,e,i,r,s,o){this._config=e,this._document=i,this._ngZone=r,this._viewportRuler=s,this._dragDropRegistry=o,this._passiveTransform={x:0,y:0},this._activeTransform={x:0,y:0},this._hasStartedDragging=!1,this._moveEvents=new O,this._pointerMoveSubscription=ke.EMPTY,this._pointerUpSubscription=ke.EMPTY,this._scrollSubscription=ke.EMPTY,this._resizeSubscription=ke.EMPTY,this._boundaryElement=null,this._nativeInteractionsEnabled=!0,this._handles=[],this._disabledHandles=new Set,this._direction=\"ltr\",this.dragStartDelay=0,this._disabled=!1,this.beforeStarted=new O,this.started=new O,this.released=new O,this.ended=new O,this.entered=new O,this.exited=new O,this.dropped=new O,this.moved=this._moveEvents,this._pointerDown=a=>{if(this.beforeStarted.next(),this._handles.length){const l=this._getTargetHandle(a);l&&!this._disabledHandles.has(l)&&!this.disabled&&this._initializeDragSequence(l,a)}else this.disabled||this._initializeDragSequence(this._rootElement,a)},this._pointerMove=a=>{const l=this._getPointerPositionOnPage(a);if(!this._hasStartedDragging){if(Math.abs(l.x-this._pickupPositionOnPage.x)+Math.abs(l.y-this._pickupPositionOnPage.y)>=this._config.dragStartThreshold){const p=Date.now()>=this._dragStartTime+this._getDragStartDelay(a),m=this._dropContainer;if(!p)return void this._endDragSequence(a);(!m||!m.isDragging()&&!m.isReceiving())&&(a.preventDefault(),this._hasStartedDragging=!0,this._ngZone.run(()=>this._startDragSequence(a)))}return}a.preventDefault();const c=this._getConstrainedPointerPosition(l);if(this._hasMoved=!0,this._lastKnownPointerPosition=l,this._updatePointerDirectionDelta(c),this._dropContainer)this._updateActiveDropContainer(c,l);else{const d=this._activeTransform;d.x=c.x-this._pickupPositionOnPage.x+this._passiveTransform.x,d.y=c.y-this._pickupPositionOnPage.y+this._passiveTransform.y,this._applyRootElementTransform(d.x,d.y)}this._moveEvents.observers.length&&this._ngZone.run(()=>{this._moveEvents.next({source:this,pointerPosition:c,event:a,distance:this._getDragDistance(c),delta:this._pointerDirectionDelta})})},this._pointerUp=a=>{this._endDragSequence(a)},this._nativeDragStart=a=>{if(this._handles.length){const l=this._getTargetHandle(a);l&&!this._disabledHandles.has(l)&&!this.disabled&&a.preventDefault()}else this.disabled||a.preventDefault()},this.withRootElement(t).withParent(e.parentDragRef||null),this._parentPositions=new tS(i),o.registerDragItem(this)}get disabled(){return this._disabled||!(!this._dropContainer||!this._dropContainer.disabled)}set disabled(t){const e=G(t);e!==this._disabled&&(this._disabled=e,this._toggleNativeDragInteractions(),this._handles.forEach(i=>_o(i,e)))}getPlaceholderElement(){return this._placeholder}getRootElement(){return this._rootElement}getVisibleElement(){return this.isDragging()?this.getPlaceholderElement():this.getRootElement()}withHandles(t){this._handles=t.map(i=>at(i)),this._handles.forEach(i=>_o(i,this.disabled)),this._toggleNativeDragInteractions();const e=new Set;return this._disabledHandles.forEach(i=>{this._handles.indexOf(i)>-1&&e.add(i)}),this._disabledHandles=e,this}withPreviewTemplate(t){return this._previewTemplate=t,this}withPlaceholderTemplate(t){return this._placeholderTemplate=t,this}withRootElement(t){const e=at(t);return e!==this._rootElement&&(this._rootElement&&this._removeRootElementListeners(this._rootElement),this._ngZone.runOutsideAngular(()=>{e.addEventListener(\"mousedown\",this._pointerDown,Qd),e.addEventListener(\"touchstart\",this._pointerDown,oS),e.addEventListener(\"dragstart\",this._nativeDragStart,Qd)}),this._initialTransform=void 0,this._rootElement=e),\"undefined\"!=typeof SVGElement&&this._rootElement instanceof SVGElement&&(this._ownerSVGElement=this._rootElement.ownerSVGElement),this}withBoundaryElement(t){return this._boundaryElement=t?at(t):null,this._resizeSubscription.unsubscribe(),t&&(this._resizeSubscription=this._viewportRuler.change(10).subscribe(()=>this._containInsideBoundaryOnResize())),this}withParent(t){return this._parentDragRef=t,this}dispose(){var t,e;this._removeRootElementListeners(this._rootElement),this.isDragging()&&(null===(t=this._rootElement)||void 0===t||t.remove()),null===(e=this._anchor)||void 0===e||e.remove(),this._destroyPreview(),this._destroyPlaceholder(),this._dragDropRegistry.removeDragItem(this),this._removeSubscriptions(),this.beforeStarted.complete(),this.started.complete(),this.released.complete(),this.ended.complete(),this.entered.complete(),this.exited.complete(),this.dropped.complete(),this._moveEvents.complete(),this._handles=[],this._disabledHandles.clear(),this._dropContainer=void 0,this._resizeSubscription.unsubscribe(),this._parentPositions.clear(),this._boundaryElement=this._rootElement=this._ownerSVGElement=this._placeholderTemplate=this._previewTemplate=this._anchor=this._parentDragRef=null}isDragging(){return this._hasStartedDragging&&this._dragDropRegistry.isDragging(this)}reset(){this._rootElement.style.transform=this._initialTransform||\"\",this._activeTransform={x:0,y:0},this._passiveTransform={x:0,y:0}}disableHandle(t){!this._disabledHandles.has(t)&&this._handles.indexOf(t)>-1&&(this._disabledHandles.add(t),_o(t,!0))}enableHandle(t){this._disabledHandles.has(t)&&(this._disabledHandles.delete(t),_o(t,this.disabled))}withDirection(t){return this._direction=t,this}_withDropContainer(t){this._dropContainer=t}getFreeDragPosition(){const t=this.isDragging()?this._activeTransform:this._passiveTransform;return{x:t.x,y:t.y}}setFreeDragPosition(t){return this._activeTransform={x:0,y:0},this._passiveTransform.x=t.x,this._passiveTransform.y=t.y,this._dropContainer||this._applyRootElementTransform(t.x,t.y),this}withPreviewContainer(t){return this._previewContainer=t,this}_sortFromLastPointerPosition(){const t=this._lastKnownPointerPosition;t&&this._dropContainer&&this._updateActiveDropContainer(this._getConstrainedPointerPosition(t),t)}_removeSubscriptions(){this._pointerMoveSubscription.unsubscribe(),this._pointerUpSubscription.unsubscribe(),this._scrollSubscription.unsubscribe()}_destroyPreview(){var t,e;null===(t=this._preview)||void 0===t||t.remove(),null===(e=this._previewRef)||void 0===e||e.destroy(),this._preview=this._previewRef=null}_destroyPlaceholder(){var t,e;null===(t=this._placeholder)||void 0===t||t.remove(),null===(e=this._placeholderRef)||void 0===e||e.destroy(),this._placeholder=this._placeholderRef=null}_endDragSequence(t){if(this._dragDropRegistry.isDragging(this)&&(this._removeSubscriptions(),this._dragDropRegistry.stopDragging(this),this._toggleNativeDragInteractions(),this._handles&&(this._rootElement.style.webkitTapHighlightColor=this._rootElementTapHighlight),this._hasStartedDragging))if(this.released.next({source:this}),this._dropContainer)this._dropContainer._stopScrolling(),this._animatePreviewToPlaceholder().then(()=>{this._cleanupDragArtifacts(t),this._cleanupCachedDimensions(),this._dragDropRegistry.stopDragging(this)});else{this._passiveTransform.x=this._activeTransform.x;const e=this._getPointerPositionOnPage(t);this._passiveTransform.y=this._activeTransform.y,this._ngZone.run(()=>{this.ended.next({source:this,distance:this._getDragDistance(e),dropPoint:e})}),this._cleanupCachedDimensions(),this._dragDropRegistry.stopDragging(this)}}_startDragSequence(t){ol(t)&&(this._lastTouchEventTime=Date.now()),this._toggleNativeDragInteractions();const e=this._dropContainer;if(e){const i=this._rootElement,r=i.parentNode,s=this._placeholder=this._createPlaceholderElement(),o=this._anchor=this._anchor||this._document.createComment(\"\"),a=this._getShadowRoot();r.insertBefore(o,i),this._initialTransform=i.style.transform||\"\",this._preview=this._createPreviewElement(),XE(i,!1,Sg),this._document.body.appendChild(r.replaceChild(s,i)),this._getPreviewInsertionPoint(r,a).appendChild(this._preview),this.started.next({source:this}),e.start(),this._initialContainer=e,this._initialIndex=e.getItemIndex(this)}else this.started.next({source:this}),this._initialContainer=this._initialIndex=void 0;this._parentPositions.cache(e?e.getScrollableParents():[])}_initializeDragSequence(t,e){this._parentDragRef&&e.stopPropagation();const i=this.isDragging(),r=ol(e),s=!r&&0!==e.button,o=this._rootElement,a=Pn(e),l=!r&&this._lastTouchEventTime&&this._lastTouchEventTime+800>Date.now(),c=r?Zm(e):Km(e);if(a&&a.draggable&&\"mousedown\"===e.type&&e.preventDefault(),i||s||l||c)return;if(this._handles.length){const h=o.style;this._rootElementTapHighlight=h.webkitTapHighlightColor||\"\",h.webkitTapHighlightColor=\"transparent\"}this._hasStartedDragging=this._hasMoved=!1,this._removeSubscriptions(),this._pointerMoveSubscription=this._dragDropRegistry.pointerMove.subscribe(this._pointerMove),this._pointerUpSubscription=this._dragDropRegistry.pointerUp.subscribe(this._pointerUp),this._scrollSubscription=this._dragDropRegistry.scrolled(this._getShadowRoot()).subscribe(h=>this._updateOnScroll(h)),this._boundaryElement&&(this._boundaryRect=xg(this._boundaryElement));const d=this._previewTemplate;this._pickupPositionInElement=d&&d.template&&!d.matchSize?{x:0,y:0}:this._getPointerPositionInElement(t,e);const u=this._pickupPositionOnPage=this._lastKnownPointerPosition=this._getPointerPositionOnPage(e);this._pointerDirectionDelta={x:0,y:0},this._pointerPositionAtLastDirectionChange={x:u.x,y:u.y},this._dragStartTime=Date.now(),this._dragDropRegistry.startDragging(this,e)}_cleanupDragArtifacts(t){XE(this._rootElement,!0,Sg),this._anchor.parentNode.replaceChild(this._rootElement,this._anchor),this._destroyPreview(),this._destroyPlaceholder(),this._boundaryRect=this._previewRect=this._initialTransform=void 0,this._ngZone.run(()=>{const e=this._dropContainer,i=e.getItemIndex(this),r=this._getPointerPositionOnPage(t),s=this._getDragDistance(r),o=e._isOverContainer(r.x,r.y);this.ended.next({source:this,distance:s,dropPoint:r}),this.dropped.next({item:this,currentIndex:i,previousIndex:this._initialIndex,container:e,previousContainer:this._initialContainer,isPointerOverContainer:o,distance:s,dropPoint:r}),e.drop(this,i,this._initialIndex,this._initialContainer,o,s,r),this._dropContainer=this._initialContainer})}_updateActiveDropContainer({x:t,y:e},{x:i,y:r}){let s=this._initialContainer._getSiblingContainerFromPosition(this,t,e);!s&&this._dropContainer!==this._initialContainer&&this._initialContainer._isOverContainer(t,e)&&(s=this._initialContainer),s&&s!==this._dropContainer&&this._ngZone.run(()=>{this.exited.next({item:this,container:this._dropContainer}),this._dropContainer.exit(this),this._dropContainer=s,this._dropContainer.enter(this,t,e,s===this._initialContainer&&s.sortingDisabled?this._initialIndex:void 0),this.entered.next({item:this,container:s,currentIndex:s.getItemIndex(this)})}),this.isDragging()&&(this._dropContainer._startScrollingIfNecessary(i,r),this._dropContainer._sortItem(this,t,e,this._pointerDirectionDelta),this._applyPreviewTransform(t-this._pickupPositionInElement.x,e-this._pickupPositionInElement.y))}_createPreviewElement(){const t=this._previewTemplate,e=this.previewClass,i=t?t.template:null;let r;if(i&&t){const s=t.matchSize?this._rootElement.getBoundingClientRect():null,o=t.viewContainer.createEmbeddedView(i,t.context);o.detectChanges(),r=lS(o,this._document),this._previewRef=o,t.matchSize?cS(r,s):r.style.transform=Kd(this._pickupPositionOnPage.x,this._pickupPositionOnPage.y)}else{const s=this._rootElement;r=nS(s),cS(r,s.getBoundingClientRect()),this._initialTransform&&(r.style.transform=this._initialTransform)}return wg(r.style,{\"pointer-events\":\"none\",margin:\"0\",position:\"fixed\",top:\"0\",left:\"0\",\"z-index\":`${this._config.zIndex||1e3}`},Sg),_o(r,!1),r.classList.add(\"cdk-drag-preview\"),r.setAttribute(\"dir\",this._direction),e&&(Array.isArray(e)?e.forEach(s=>r.classList.add(s)):r.classList.add(e)),r}_animatePreviewToPlaceholder(){if(!this._hasMoved)return Promise.resolve();const t=this._placeholder.getBoundingClientRect();this._preview.classList.add(\"cdk-drag-animating\"),this._applyPreviewTransform(t.left,t.top);const e=function _$(n){const t=getComputedStyle(n),e=Mg(t,\"transition-property\"),i=e.find(a=>\"transform\"===a||\"all\"===a);if(!i)return 0;const r=e.indexOf(i),s=Mg(t,\"transition-duration\"),o=Mg(t,\"transition-delay\");return JE(s[r])+JE(o[r])}(this._preview);return 0===e?Promise.resolve():this._ngZone.runOutsideAngular(()=>new Promise(i=>{const r=o=>{var a;(!o||Pn(o)===this._preview&&\"transform\"===o.propertyName)&&(null===(a=this._preview)||void 0===a||a.removeEventListener(\"transitionend\",r),i(),clearTimeout(s))},s=setTimeout(r,1.5*e);this._preview.addEventListener(\"transitionend\",r)}))}_createPlaceholderElement(){const t=this._placeholderTemplate,e=t?t.template:null;let i;return e?(this._placeholderRef=t.viewContainer.createEmbeddedView(e,t.context),this._placeholderRef.detectChanges(),i=lS(this._placeholderRef,this._document)):i=nS(this._rootElement),i.style.pointerEvents=\"none\",i.classList.add(\"cdk-drag-placeholder\"),i}_getPointerPositionInElement(t,e){const i=this._rootElement.getBoundingClientRect(),r=t===this._rootElement?null:t,s=r?r.getBoundingClientRect():i,o=ol(e)?e.targetTouches[0]:e,a=this._getViewportScrollPosition();return{x:s.left-i.left+(o.pageX-s.left-a.left),y:s.top-i.top+(o.pageY-s.top-a.top)}}_getPointerPositionOnPage(t){const e=this._getViewportScrollPosition(),i=ol(t)?t.touches[0]||t.changedTouches[0]||{pageX:0,pageY:0}:t,r=i.pageX-e.left,s=i.pageY-e.top;if(this._ownerSVGElement){const o=this._ownerSVGElement.getScreenCTM();if(o){const a=this._ownerSVGElement.createSVGPoint();return a.x=r,a.y=s,a.matrixTransform(o.inverse())}}return{x:r,y:s}}_getConstrainedPointerPosition(t){const e=this._dropContainer?this._dropContainer.lockAxis:null;let{x:i,y:r}=this.constrainPosition?this.constrainPosition(t,this):t;if(\"x\"===this.lockAxis||\"x\"===e?r=this._pickupPositionOnPage.y:(\"y\"===this.lockAxis||\"y\"===e)&&(i=this._pickupPositionOnPage.x),this._boundaryRect){const{x:s,y:o}=this._pickupPositionInElement,a=this._boundaryRect,{width:l,height:c}=this._getPreviewRect(),d=a.top+o,u=a.bottom-(c-o);i=aS(i,a.left+s,a.right-(l-s)),r=aS(r,d,u)}return{x:i,y:r}}_updatePointerDirectionDelta(t){const{x:e,y:i}=t,r=this._pointerDirectionDelta,s=this._pointerPositionAtLastDirectionChange,o=Math.abs(e-s.x),a=Math.abs(i-s.y);return o>this._config.pointerDirectionChangeThreshold&&(r.x=e>s.x?1:-1,s.x=e),a>this._config.pointerDirectionChangeThreshold&&(r.y=i>s.y?1:-1,s.y=i),r}_toggleNativeDragInteractions(){if(!this._rootElement||!this._handles)return;const t=this._handles.length>0||!this.isDragging();t!==this._nativeInteractionsEnabled&&(this._nativeInteractionsEnabled=t,_o(this._rootElement,t))}_removeRootElementListeners(t){t.removeEventListener(\"mousedown\",this._pointerDown,Qd),t.removeEventListener(\"touchstart\",this._pointerDown,oS),t.removeEventListener(\"dragstart\",this._nativeDragStart,Qd)}_applyRootElementTransform(t,e){const i=Kd(t,e),r=this._rootElement.style;null==this._initialTransform&&(this._initialTransform=r.transform&&\"none\"!=r.transform?r.transform:\"\"),r.transform=Yd(i,this._initialTransform)}_applyPreviewTransform(t,e){var i;const r=(null===(i=this._previewTemplate)||void 0===i?void 0:i.template)?void 0:this._initialTransform,s=Kd(t,e);this._preview.style.transform=Yd(s,r)}_getDragDistance(t){const e=this._pickupPositionOnPage;return e?{x:t.x-e.x,y:t.y-e.y}:{x:0,y:0}}_cleanupCachedDimensions(){this._boundaryRect=this._previewRect=void 0,this._parentPositions.clear()}_containInsideBoundaryOnResize(){let{x:t,y:e}=this._passiveTransform;if(0===t&&0===e||this.isDragging()||!this._boundaryElement)return;const i=this._boundaryElement.getBoundingClientRect(),r=this._rootElement.getBoundingClientRect();if(0===i.width&&0===i.height||0===r.width&&0===r.height)return;const s=i.left-r.left,o=r.right-i.right,a=i.top-r.top,l=r.bottom-i.bottom;i.width>r.width?(s>0&&(t+=s),o>0&&(t-=o)):t=0,i.height>r.height?(a>0&&(e+=a),l>0&&(e-=l)):e=0,(t!==this._passiveTransform.x||e!==this._passiveTransform.y)&&this.setFreeDragPosition({y:e,x:t})}_getDragStartDelay(t){const e=this.dragStartDelay;return\"number\"==typeof e?e:ol(t)?e.touch:e?e.mouse:0}_updateOnScroll(t){const e=this._parentPositions.handleScroll(t);if(e){const i=Pn(t);this._boundaryRect&&i!==this._boundaryElement&&i.contains(this._boundaryElement)&&sl(this._boundaryRect,e.top,e.left),this._pickupPositionOnPage.x+=e.left,this._pickupPositionOnPage.y+=e.top,this._dropContainer||(this._activeTransform.x-=e.left,this._activeTransform.y-=e.top,this._applyRootElementTransform(this._activeTransform.x,this._activeTransform.y))}}_getViewportScrollPosition(){var t;return(null===(t=this._parentPositions.positions.get(this._document))||void 0===t?void 0:t.scrollPosition)||this._parentPositions.getViewportScrollPosition()}_getShadowRoot(){return void 0===this._cachedShadowRoot&&(this._cachedShadowRoot=Fd(this._rootElement)),this._cachedShadowRoot}_getPreviewInsertionPoint(t,e){const i=this._previewContainer||\"global\";if(\"parent\"===i)return t;if(\"global\"===i){const r=this._document;return e||r.fullscreenElement||r.webkitFullscreenElement||r.mozFullScreenElement||r.msFullscreenElement||r.body}return at(i)}_getPreviewRect(){return(!this._previewRect||!this._previewRect.width&&!this._previewRect.height)&&(this._previewRect=(this._preview||this._rootElement).getBoundingClientRect()),this._previewRect}_getTargetHandle(t){return this._handles.find(e=>t.target&&(t.target===e||e.contains(t.target)))}}function Kd(n,t){return`translate3d(${Math.round(n)}px, ${Math.round(t)}px, 0)`}function aS(n,t,e){return Math.max(t,Math.min(e,n))}function ol(n){return\"t\"===n.type[0]}function lS(n,t){const e=n.rootNodes;if(1===e.length&&e[0].nodeType===t.ELEMENT_NODE)return e[0];const i=t.createElement(\"div\");return e.forEach(r=>i.appendChild(r)),i}function cS(n,t){n.style.width=`${t.width}px`,n.style.height=`${t.height}px`,n.style.transform=Kd(t.left,t.top)}function al(n,t){return Math.max(0,Math.min(t,n))}class D${constructor(t,e,i,r,s){this._dragDropRegistry=e,this._ngZone=r,this._viewportRuler=s,this.disabled=!1,this.sortingDisabled=!1,this.autoScrollDisabled=!1,this.autoScrollStep=2,this.enterPredicate=()=>!0,this.sortPredicate=()=>!0,this.beforeStarted=new O,this.entered=new O,this.exited=new O,this.dropped=new O,this.sorted=new O,this._isDragging=!1,this._itemPositions=[],this._previousSwap={drag:null,delta:0,overlaps:!1},this._draggables=[],this._siblings=[],this._orientation=\"vertical\",this._activeSiblings=new Set,this._direction=\"ltr\",this._viewportScrollSubscription=ke.EMPTY,this._verticalScrollDirection=0,this._horizontalScrollDirection=0,this._stopScrollTimers=new O,this._cachedShadowRoot=null,this._startScrollInterval=()=>{this._stopScrolling(),function g$(n=0,t=qa){return n<0&&(n=0),_g(n,n,t)}(0,EE).pipe(Ie(this._stopScrollTimers)).subscribe(()=>{const o=this._scrollNode,a=this.autoScrollStep;1===this._verticalScrollDirection?o.scrollBy(0,-a):2===this._verticalScrollDirection&&o.scrollBy(0,a),1===this._horizontalScrollDirection?o.scrollBy(-a,0):2===this._horizontalScrollDirection&&o.scrollBy(a,0)})},this.element=at(t),this._document=i,this.withScrollableParents([this.element]),e.registerDropContainer(this),this._parentPositions=new tS(i)}dispose(){this._stopScrolling(),this._stopScrollTimers.complete(),this._viewportScrollSubscription.unsubscribe(),this.beforeStarted.complete(),this.entered.complete(),this.exited.complete(),this.dropped.complete(),this.sorted.complete(),this._activeSiblings.clear(),this._scrollNode=null,this._parentPositions.clear(),this._dragDropRegistry.removeDropContainer(this)}isDragging(){return this._isDragging}start(){this._draggingStarted(),this._notifyReceivingSiblings()}enter(t,e,i,r){let s;this._draggingStarted(),null==r?(s=this.sortingDisabled?this._draggables.indexOf(t):-1,-1===s&&(s=this._getItemIndexFromPointerPosition(t,e,i))):s=r;const o=this._activeDraggables,a=o.indexOf(t),l=t.getPlaceholderElement();let c=o[s];if(c===t&&(c=o[s+1]),!c&&(null==s||-1===s||s<o.length-1)&&this._shouldEnterAsFirstChild(e,i)&&(c=o[0]),a>-1&&o.splice(a,1),c&&!this._dragDropRegistry.isDragging(c)){const d=c.getRootElement();d.parentElement.insertBefore(l,d),o.splice(s,0,t)}else at(this.element).appendChild(l),o.push(t);l.style.transform=\"\",this._cacheItemPositions(),this._cacheParentPositions(),this._notifyReceivingSiblings(),this.entered.next({item:t,container:this,currentIndex:this.getItemIndex(t)})}exit(t){this._reset(),this.exited.next({item:t,container:this})}drop(t,e,i,r,s,o,a){this._reset(),this.dropped.next({item:t,currentIndex:e,previousIndex:i,container:this,previousContainer:r,isPointerOverContainer:s,distance:o,dropPoint:a})}withItems(t){const e=this._draggables;return this._draggables=t,t.forEach(i=>i._withDropContainer(this)),this.isDragging()&&(e.filter(r=>r.isDragging()).every(r=>-1===t.indexOf(r))?this._reset():this._cacheItems()),this}withDirection(t){return this._direction=t,this}connectedTo(t){return this._siblings=t.slice(),this}withOrientation(t){return this._orientation=t,this}withScrollableParents(t){const e=at(this.element);return this._scrollableElements=-1===t.indexOf(e)?[e,...t]:t.slice(),this}getScrollableParents(){return this._scrollableElements}getItemIndex(t){return this._isDragging?(\"horizontal\"===this._orientation&&\"rtl\"===this._direction?this._itemPositions.slice().reverse():this._itemPositions).findIndex(i=>i.drag===t):this._draggables.indexOf(t)}isReceiving(){return this._activeSiblings.size>0}_sortItem(t,e,i,r){if(this.sortingDisabled||!this._clientRect||!eS(this._clientRect,.05,e,i))return;const s=this._itemPositions,o=this._getItemIndexFromPointerPosition(t,e,i,r);if(-1===o&&s.length>0)return;const a=\"horizontal\"===this._orientation,l=s.findIndex(_=>_.drag===t),c=s[o],u=c.clientRect,h=l>o?1:-1,p=this._getItemOffsetPx(s[l].clientRect,u,h),m=this._getSiblingOffsetPx(l,s,h),g=s.slice();(function C$(n,t,e){const i=al(t,n.length-1),r=al(e,n.length-1);if(i===r)return;const s=n[i],o=r<i?-1:1;for(let a=i;a!==r;a+=o)n[a]=n[a+o];n[r]=s})(s,l,o),this.sorted.next({previousIndex:l,currentIndex:o,container:this,item:t}),s.forEach((_,D)=>{if(g[D]===_)return;const v=_.drag===t,M=v?p:m,V=v?t.getPlaceholderElement():_.drag.getRootElement();_.offset+=M,a?(V.style.transform=Yd(`translate3d(${Math.round(_.offset)}px, 0, 0)`,_.initialTransform),sl(_.clientRect,0,M)):(V.style.transform=Yd(`translate3d(0, ${Math.round(_.offset)}px, 0)`,_.initialTransform),sl(_.clientRect,M,0))}),this._previousSwap.overlaps=Eg(u,e,i),this._previousSwap.drag=c.drag,this._previousSwap.delta=a?r.x:r.y}_startScrollingIfNecessary(t,e){if(this.autoScrollDisabled)return;let i,r=0,s=0;if(this._parentPositions.positions.forEach((o,a)=>{a===this._document||!o.clientRect||i||eS(o.clientRect,.05,t,e)&&([r,s]=function w$(n,t,e,i){const r=hS(t,i),s=pS(t,e);let o=0,a=0;if(r){const l=n.scrollTop;1===r?l>0&&(o=1):n.scrollHeight-l>n.clientHeight&&(o=2)}if(s){const l=n.scrollLeft;1===s?l>0&&(a=1):n.scrollWidth-l>n.clientWidth&&(a=2)}return[o,a]}(a,o.clientRect,t,e),(r||s)&&(i=a))}),!r&&!s){const{width:o,height:a}=this._viewportRuler.getViewportSize(),l={width:o,height:a,top:0,right:o,bottom:a,left:0};r=hS(l,e),s=pS(l,t),i=window}i&&(r!==this._verticalScrollDirection||s!==this._horizontalScrollDirection||i!==this._scrollNode)&&(this._verticalScrollDirection=r,this._horizontalScrollDirection=s,this._scrollNode=i,(r||s)&&i?this._ngZone.runOutsideAngular(this._startScrollInterval):this._stopScrolling())}_stopScrolling(){this._stopScrollTimers.next()}_draggingStarted(){const t=at(this.element).style;this.beforeStarted.next(),this._isDragging=!0,this._initialScrollSnap=t.msScrollSnapType||t.scrollSnapType||\"\",t.scrollSnapType=t.msScrollSnapType=\"none\",this._cacheItems(),this._viewportScrollSubscription.unsubscribe(),this._listenToScrollEvents()}_cacheParentPositions(){const t=at(this.element);this._parentPositions.cache(this._scrollableElements),this._clientRect=this._parentPositions.positions.get(t).clientRect}_cacheItemPositions(){const t=\"horizontal\"===this._orientation;this._itemPositions=this._activeDraggables.map(e=>{const i=e.getVisibleElement();return{drag:e,offset:0,initialTransform:i.style.transform||\"\",clientRect:xg(i)}}).sort((e,i)=>t?e.clientRect.left-i.clientRect.left:e.clientRect.top-i.clientRect.top)}_reset(){this._isDragging=!1;const t=at(this.element).style;t.scrollSnapType=t.msScrollSnapType=this._initialScrollSnap,this._activeDraggables.forEach(e=>{var i;const r=e.getRootElement();if(r){const s=null===(i=this._itemPositions.find(o=>o.drag===e))||void 0===i?void 0:i.initialTransform;r.style.transform=s||\"\"}}),this._siblings.forEach(e=>e._stopReceiving(this)),this._activeDraggables=[],this._itemPositions=[],this._previousSwap.drag=null,this._previousSwap.delta=0,this._previousSwap.overlaps=!1,this._stopScrolling(),this._viewportScrollSubscription.unsubscribe(),this._parentPositions.clear()}_getSiblingOffsetPx(t,e,i){const r=\"horizontal\"===this._orientation,s=e[t].clientRect,o=e[t+-1*i];let a=s[r?\"width\":\"height\"]*i;if(o){const l=r?\"left\":\"top\",c=r?\"right\":\"bottom\";-1===i?a-=o.clientRect[l]-s[c]:a+=s[l]-o.clientRect[c]}return a}_getItemOffsetPx(t,e,i){const r=\"horizontal\"===this._orientation;let s=r?e.left-t.left:e.top-t.top;return-1===i&&(s+=r?e.width-t.width:e.height-t.height),s}_shouldEnterAsFirstChild(t,e){if(!this._activeDraggables.length)return!1;const i=this._itemPositions,r=\"horizontal\"===this._orientation;if(i[0].drag!==this._activeDraggables[0]){const o=i[i.length-1].clientRect;return r?t>=o.right:e>=o.bottom}{const o=i[0].clientRect;return r?t<=o.left:e<=o.top}}_getItemIndexFromPointerPosition(t,e,i,r){const s=\"horizontal\"===this._orientation,o=this._itemPositions.findIndex(({drag:a,clientRect:l})=>{if(a===t)return!1;if(r){const c=s?r.x:r.y;if(a===this._previousSwap.drag&&this._previousSwap.overlaps&&c===this._previousSwap.delta)return!1}return s?e>=Math.floor(l.left)&&e<Math.floor(l.right):i>=Math.floor(l.top)&&i<Math.floor(l.bottom)});return-1!==o&&this.sortPredicate(o,t,this)?o:-1}_cacheItems(){this._activeDraggables=this._draggables.slice(),this._cacheItemPositions(),this._cacheParentPositions()}_isOverContainer(t,e){return null!=this._clientRect&&Eg(this._clientRect,t,e)}_getSiblingContainerFromPosition(t,e,i){return this._siblings.find(r=>r._canReceive(t,e,i))}_canReceive(t,e,i){if(!this._clientRect||!Eg(this._clientRect,e,i)||!this.enterPredicate(t,this))return!1;const r=this._getShadowRoot().elementFromPoint(e,i);if(!r)return!1;const s=at(this.element);return r===s||s.contains(r)}_startReceiving(t,e){const i=this._activeSiblings;!i.has(t)&&e.every(r=>this.enterPredicate(r,this)||this._draggables.indexOf(r)>-1)&&(i.add(t),this._cacheParentPositions(),this._listenToScrollEvents())}_stopReceiving(t){this._activeSiblings.delete(t),this._viewportScrollSubscription.unsubscribe()}_listenToScrollEvents(){this._viewportScrollSubscription=this._dragDropRegistry.scrolled(this._getShadowRoot()).subscribe(t=>{if(this.isDragging()){const e=this._parentPositions.handleScroll(t);e&&(this._itemPositions.forEach(({clientRect:i})=>{sl(i,e.top,e.left)}),this._itemPositions.forEach(({drag:i})=>{this._dragDropRegistry.isDragging(i)&&i._sortFromLastPointerPosition()}))}else this.isReceiving()&&this._cacheParentPositions()})}_getShadowRoot(){if(!this._cachedShadowRoot){const t=Fd(at(this.element));this._cachedShadowRoot=t||this._document}return this._cachedShadowRoot}_notifyReceivingSiblings(){const t=this._activeDraggables.filter(e=>e.isDragging());this._siblings.forEach(e=>e._startReceiving(this,t))}}function hS(n,t){const{top:e,bottom:i,height:r}=n,s=.05*r;return t>=e-s&&t<=e+s?1:t>=i-s&&t<=i+s?2:0}function pS(n,t){const{left:e,right:i,width:r}=n,s=.05*r;return t>=e-s&&t<=e+s?1:t>=i-s&&t<=i+s?2:0}const Zd=ei({passive:!1,capture:!0});let M$=(()=>{class n{constructor(e,i){this._ngZone=e,this._dropInstances=new Set,this._dragInstances=new Set,this._activeDragInstances=[],this._globalListeners=new Map,this._draggingPredicate=r=>r.isDragging(),this.pointerMove=new O,this.pointerUp=new O,this.scroll=new O,this._preventDefaultWhileDragging=r=>{this._activeDragInstances.length>0&&r.preventDefault()},this._persistentTouchmoveListener=r=>{this._activeDragInstances.length>0&&(this._activeDragInstances.some(this._draggingPredicate)&&r.preventDefault(),this.pointerMove.next(r))},this._document=i}registerDropContainer(e){this._dropInstances.has(e)||this._dropInstances.add(e)}registerDragItem(e){this._dragInstances.add(e),1===this._dragInstances.size&&this._ngZone.runOutsideAngular(()=>{this._document.addEventListener(\"touchmove\",this._persistentTouchmoveListener,Zd)})}removeDropContainer(e){this._dropInstances.delete(e)}removeDragItem(e){this._dragInstances.delete(e),this.stopDragging(e),0===this._dragInstances.size&&this._document.removeEventListener(\"touchmove\",this._persistentTouchmoveListener,Zd)}startDragging(e,i){if(!(this._activeDragInstances.indexOf(e)>-1)&&(this._activeDragInstances.push(e),1===this._activeDragInstances.length)){const r=i.type.startsWith(\"touch\");this._globalListeners.set(r?\"touchend\":\"mouseup\",{handler:s=>this.pointerUp.next(s),options:!0}).set(\"scroll\",{handler:s=>this.scroll.next(s),options:!0}).set(\"selectstart\",{handler:this._preventDefaultWhileDragging,options:Zd}),r||this._globalListeners.set(\"mousemove\",{handler:s=>this.pointerMove.next(s),options:Zd}),this._ngZone.runOutsideAngular(()=>{this._globalListeners.forEach((s,o)=>{this._document.addEventListener(o,s.handler,s.options)})})}}stopDragging(e){const i=this._activeDragInstances.indexOf(e);i>-1&&(this._activeDragInstances.splice(i,1),0===this._activeDragInstances.length&&this._clearGlobalListeners())}isDragging(e){return this._activeDragInstances.indexOf(e)>-1}scrolled(e){const i=[this.scroll];return e&&e!==this._document&&i.push(new Ve(r=>this._ngZone.runOutsideAngular(()=>{const o=a=>{this._activeDragInstances.length&&r.next(a)};return e.addEventListener(\"scroll\",o,!0),()=>{e.removeEventListener(\"scroll\",o,!0)}}))),Bt(...i)}ngOnDestroy(){this._dragInstances.forEach(e=>this.removeDragItem(e)),this._dropInstances.forEach(e=>this.removeDropContainer(e)),this._clearGlobalListeners(),this.pointerMove.complete(),this.pointerUp.complete()}_clearGlobalListeners(){this._globalListeners.forEach((e,i)=>{this._document.removeEventListener(i,e.handler,e.options)}),this._globalListeners.clear()}}return n.\\u0275fac=function(e){return new(e||n)(y(ne),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const x$={dragStartThreshold:5,pointerDirectionChangeThreshold:5};let E$=(()=>{class n{constructor(e,i,r,s){this._document=e,this._ngZone=i,this._viewportRuler=r,this._dragDropRegistry=s}createDrag(e,i=x$){return new b$(e,i,this._document,this._ngZone,this._viewportRuler,this._dragDropRegistry)}createDropList(e){return new D$(e,this._dragDropRegistry,this._document,this._ngZone,this._viewportRuler)}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(ne),y(es),y(M$))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),S$=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[E$],imports:[Ci]}),n})(),fS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[lo]]}),n})(),bS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Ud]]}),n})(),CS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const Z$={provide:new b(\"mat-autocomplete-scroll-strategy\"),deps:[ni],useFactory:function K$(n){return()=>n.scrollStrategies.reposition()}};let t8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[Z$],imports:[[ji,Hd,B,bt],Ci,Hd,B]}),n})(),n8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Qa,B],B]}),n})(),r8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ji,B,Hi],B]}),n})(),ul=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ti,B],B]}),n})(),u8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B,ti],B]}),n})(),h8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),AS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),M8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ti,B,Ya,AS],B,AS]}),n})();const PS=new b(\"mat-chips-default-options\");let L8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[mo,{provide:PS,useValue:{separatorKeyCodes:[13]}}],imports:[[B]]}),n})(),WS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),Wg=(()=>{class n{constructor(){this.changes=new O,this.optionalLabel=\"Optional\",this.completedLabel=\"Completed\",this.editableLabel=\"Editable\"}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const d4={provide:Wg,deps:[[new Tt,new Cn,Wg]],useFactory:function c4(n){return n||new Wg}};let u4=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[d4,mo],imports:[[B,bt,Hi,ul,fS,WS,ti],B]}),n})(),C4=(()=>{class n{constructor(){this.changes=new O,this.calendarLabel=\"Calendar\",this.openCalendarLabel=\"Open calendar\",this.closeCalendarLabel=\"Close calendar\",this.prevMonthLabel=\"Previous month\",this.nextMonthLabel=\"Next month\",this.prevYearLabel=\"Previous year\",this.nextYearLabel=\"Next year\",this.prevMultiYearLabel=\"Previous 24 years\",this.nextMultiYearLabel=\"Next 24 years\",this.switchToMonthViewLabel=\"Choose date\",this.switchToMultiYearViewLabel=\"Choose month and year\"}formatYearRange(e,i){return`${e} \\u2013 ${i}`}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const M4={provide:new b(\"mat-datepicker-scroll-strategy\"),deps:[ni],useFactory:function w4(n){return()=>n.scrollStrategies.reposition()}};let T4=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[C4,M4],imports:[[bt,ul,ji,Qa,Hi,B],Ci]}),n})();function A4(n,t){}class qg{constructor(){this.role=\"dialog\",this.panelClass=\"\",this.hasBackdrop=!0,this.backdropClass=\"\",this.disableClose=!1,this.width=\"\",this.height=\"\",this.maxWidth=\"80vw\",this.data=null,this.ariaDescribedBy=null,this.ariaLabelledBy=null,this.ariaLabel=null,this.autoFocus=\"first-tabbable\",this.restoreFocus=!0,this.delayFocusTrap=!0,this.closeOnNavigation=!0}}const I4={dialogContainer:Ke(\"dialogContainer\",[ae(\"void, exit\",R({opacity:0,transform:\"scale(0.7)\"})),ae(\"enter\",R({transform:\"none\"})),ge(\"* => enter\",nd([be(\"150ms cubic-bezier(0, 0, 0.2, 1)\",R({transform:\"none\",opacity:1})),no(\"@*\",to(),{optional:!0})])),ge(\"* => void, * => exit\",nd([be(\"75ms cubic-bezier(0.4, 0.0, 0.2, 1)\",R({opacity:0})),no(\"@*\",to(),{optional:!0})]))])};let R4=(()=>{class n extends bg{constructor(e,i,r,s,o,a,l,c){super(),this._elementRef=e,this._focusTrapFactory=i,this._changeDetectorRef=r,this._config=o,this._interactivityChecker=a,this._ngZone=l,this._focusMonitor=c,this._animationStateChanged=new $,this._elementFocusedBeforeDialogWasOpened=null,this._closeInteractionType=null,this.attachDomPortal=d=>(this._portalOutlet.hasAttached(),this._portalOutlet.attachDomPortal(d)),this._ariaLabelledBy=o.ariaLabelledBy||null,this._document=s}_initializeWithAttachedContent(){this._focusTrap=this._focusTrapFactory.create(this._elementRef.nativeElement),this._document&&(this._elementFocusedBeforeDialogWasOpened=Hm())}attachComponentPortal(e){return this._portalOutlet.hasAttached(),this._portalOutlet.attachComponentPortal(e)}attachTemplatePortal(e){return this._portalOutlet.hasAttached(),this._portalOutlet.attachTemplatePortal(e)}_recaptureFocus(){this._containsFocus()||this._trapFocus()}_forceFocus(e,i){this._interactivityChecker.isFocusable(e)||(e.tabIndex=-1,this._ngZone.runOutsideAngular(()=>{e.addEventListener(\"blur\",()=>e.removeAttribute(\"tabindex\")),e.addEventListener(\"mousedown\",()=>e.removeAttribute(\"tabindex\"))})),e.focus(i)}_focusByCssSelector(e,i){let r=this._elementRef.nativeElement.querySelector(e);r&&this._forceFocus(r,i)}_trapFocus(){const e=this._elementRef.nativeElement;switch(this._config.autoFocus){case!1:case\"dialog\":this._containsFocus()||e.focus();break;case!0:case\"first-tabbable\":this._focusTrap.focusInitialElementWhenReady().then(i=>{i||this._focusDialogContainer()});break;case\"first-heading\":this._focusByCssSelector('h1, h2, h3, h4, h5, h6, [role=\"heading\"]');break;default:this._focusByCssSelector(this._config.autoFocus)}}_restoreFocus(){const e=this._elementFocusedBeforeDialogWasOpened;if(this._config.restoreFocus&&e&&\"function\"==typeof e.focus){const i=Hm(),r=this._elementRef.nativeElement;(!i||i===this._document.body||i===r||r.contains(i))&&(this._focusMonitor?(this._focusMonitor.focusVia(e,this._closeInteractionType),this._closeInteractionType=null):e.focus())}this._focusTrap&&this._focusTrap.destroy()}_focusDialogContainer(){this._elementRef.nativeElement.focus&&this._elementRef.nativeElement.focus()}_containsFocus(){const e=this._elementRef.nativeElement,i=Hm();return e===i||e.contains(i)}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(C3),f(Ye),f(ie,8),f(qg),f(Xx),f(ne),f(Qr))},n.\\u0275dir=C({type:n,viewQuery:function(e,i){if(1&e&&je(TE,7),2&e){let r;z(r=U())&&(i._portalOutlet=r.first)}},features:[E]}),n})(),O4=(()=>{class n extends R4{constructor(){super(...arguments),this._state=\"enter\"}_onAnimationDone({toState:e,totalTime:i}){\"enter\"===e?(this._config.delayFocusTrap&&this._trapFocus(),this._animationStateChanged.next({state:\"opened\",totalTime:i})):\"exit\"===e&&(this._restoreFocus(),this._animationStateChanged.next({state:\"closed\",totalTime:i}))}_onAnimationStart({toState:e,totalTime:i}){\"enter\"===e?this._animationStateChanged.next({state:\"opening\",totalTime:i}):(\"exit\"===e||\"void\"===e)&&this._animationStateChanged.next({state:\"closing\",totalTime:i})}_startExitAnimation(){this._state=\"exit\",this._changeDetectorRef.markForCheck()}_initializeWithAttachedContent(){super._initializeWithAttachedContent(),this._config.delayFocusTrap||this._trapFocus()}}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275cmp=xe({type:n,selectors:[[\"mat-dialog-container\"]],hostAttrs:[\"tabindex\",\"-1\",\"aria-modal\",\"true\",1,\"mat-dialog-container\"],hostVars:6,hostBindings:function(e,i){1&e&&hp(\"@dialogContainer.start\",function(s){return i._onAnimationStart(s)})(\"@dialogContainer.done\",function(s){return i._onAnimationDone(s)}),2&e&&(Yn(\"id\",i._id),Z(\"role\",i._config.role)(\"aria-labelledby\",i._config.ariaLabel?null:i._ariaLabelledBy)(\"aria-label\",i._config.ariaLabel)(\"aria-describedby\",i._config.ariaDescribedBy||null),gp(\"@dialogContainer\",i._state))},features:[E],decls:1,vars:0,consts:[[\"cdkPortalOutlet\",\"\"]],template:function(e,i){1&e&&Ee(0,A4,0,0,\"ng-template\",0)},directives:[TE],styles:[\".mat-dialog-container{display:block;padding:24px;border-radius:4px;box-sizing:border-box;overflow:auto;outline:0;width:100%;height:100%;min-height:inherit;max-height:inherit}.cdk-high-contrast-active .mat-dialog-container{outline:solid 1px}.mat-dialog-content{display:block;margin:0 -24px;padding:0 24px;max-height:65vh;overflow:auto;-webkit-overflow-scrolling:touch}.mat-dialog-title{margin:0 0 20px;display:block}.mat-dialog-actions{padding:8px 0;display:flex;flex-wrap:wrap;min-height:52px;align-items:center;box-sizing:content-box;margin-bottom:-24px}.mat-dialog-actions[align=end]{justify-content:flex-end}.mat-dialog-actions[align=center]{justify-content:center}.mat-dialog-actions .mat-button-base+.mat-button-base,.mat-dialog-actions .mat-mdc-button-base+.mat-mdc-button-base{margin-left:8px}[dir=rtl] .mat-dialog-actions .mat-button-base+.mat-button-base,[dir=rtl] .mat-dialog-actions .mat-mdc-button-base+.mat-mdc-button-base{margin-left:0;margin-right:8px}\\n\"],encapsulation:2,data:{animation:[I4.dialogContainer]}}),n})(),P4=0;class F4{constructor(t,e,i=\"mat-dialog-\"+P4++){this._overlayRef=t,this._containerInstance=e,this.id=i,this.disableClose=this._containerInstance._config.disableClose,this._afterOpened=new O,this._afterClosed=new O,this._beforeClosed=new O,this._state=0,e._id=i,e._animationStateChanged.pipe(Ct(r=>\"opened\"===r.state),it(1)).subscribe(()=>{this._afterOpened.next(),this._afterOpened.complete()}),e._animationStateChanged.pipe(Ct(r=>\"closed\"===r.state),it(1)).subscribe(()=>{clearTimeout(this._closeFallbackTimeout),this._finishDialogClose()}),t.detachments().subscribe(()=>{this._beforeClosed.next(this._result),this._beforeClosed.complete(),this._afterClosed.next(this._result),this._afterClosed.complete(),this.componentInstance=null,this._overlayRef.dispose()}),t.keydownEvents().pipe(Ct(r=>27===r.keyCode&&!this.disableClose&&!Xt(r))).subscribe(r=>{r.preventDefault(),ZS(this,\"keyboard\")}),t.backdropClick().subscribe(()=>{this.disableClose?this._containerInstance._recaptureFocus():ZS(this,\"mouse\")})}close(t){this._result=t,this._containerInstance._animationStateChanged.pipe(Ct(e=>\"closing\"===e.state),it(1)).subscribe(e=>{this._beforeClosed.next(t),this._beforeClosed.complete(),this._overlayRef.detachBackdrop(),this._closeFallbackTimeout=setTimeout(()=>this._finishDialogClose(),e.totalTime+100)}),this._state=1,this._containerInstance._startExitAnimation()}afterOpened(){return this._afterOpened}afterClosed(){return this._afterClosed}beforeClosed(){return this._beforeClosed}backdropClick(){return this._overlayRef.backdropClick()}keydownEvents(){return this._overlayRef.keydownEvents()}updatePosition(t){let e=this._getPositionStrategy();return t&&(t.left||t.right)?t.left?e.left(t.left):e.right(t.right):e.centerHorizontally(),t&&(t.top||t.bottom)?t.top?e.top(t.top):e.bottom(t.bottom):e.centerVertically(),this._overlayRef.updatePosition(),this}updateSize(t=\"\",e=\"\"){return this._overlayRef.updateSize({width:t,height:e}),this._overlayRef.updatePosition(),this}addPanelClass(t){return this._overlayRef.addPanelClass(t),this}removePanelClass(t){return this._overlayRef.removePanelClass(t),this}getState(){return this._state}_finishDialogClose(){this._state=2,this._overlayRef.dispose()}_getPositionStrategy(){return this._overlayRef.getConfig().positionStrategy}}function ZS(n,t,e){return void 0!==n._containerInstance&&(n._containerInstance._closeInteractionType=t),n.close(e)}const N4=new b(\"MatDialogData\"),L4=new b(\"mat-dialog-default-options\"),XS=new b(\"mat-dialog-scroll-strategy\"),V4={provide:XS,deps:[ni],useFactory:function B4(n){return()=>n.scrollStrategies.block()}};let H4=(()=>{class n{constructor(e,i,r,s,o,a,l,c,d,u){this._overlay=e,this._injector=i,this._defaultOptions=r,this._parentDialog=s,this._overlayContainer=o,this._dialogRefConstructor=l,this._dialogContainerType=c,this._dialogDataToken=d,this._openDialogsAtThisLevel=[],this._afterAllClosedAtThisLevel=new O,this._afterOpenedAtThisLevel=new O,this._ariaHiddenElements=new Map,this.afterAllClosed=xa(()=>this.openDialogs.length?this._getAfterAllClosed():this._getAfterAllClosed().pipe(Xn(void 0))),this._scrollStrategy=a}get openDialogs(){return this._parentDialog?this._parentDialog.openDialogs:this._openDialogsAtThisLevel}get afterOpened(){return this._parentDialog?this._parentDialog.afterOpened:this._afterOpenedAtThisLevel}_getAfterAllClosed(){const e=this._parentDialog;return e?e._getAfterAllClosed():this._afterAllClosedAtThisLevel}open(e,i){i=function z4(n,t){return Object.assign(Object.assign({},t),n)}(i,this._defaultOptions||new qg),i.id&&this.getDialogById(i.id);const r=this._createOverlay(i),s=this._attachDialogContainer(r,i),o=this._attachDialogContent(e,s,r,i);return this.openDialogs.length||this._hideNonDialogContentFromAssistiveTechnology(),this.openDialogs.push(o),o.afterClosed().subscribe(()=>this._removeOpenDialog(o)),this.afterOpened.next(o),s._initializeWithAttachedContent(),o}closeAll(){this._closeDialogs(this.openDialogs)}getDialogById(e){return this.openDialogs.find(i=>i.id===e)}ngOnDestroy(){this._closeDialogs(this._openDialogsAtThisLevel),this._afterAllClosedAtThisLevel.complete(),this._afterOpenedAtThisLevel.complete()}_createOverlay(e){const i=this._getOverlayConfig(e);return this._overlay.create(i)}_getOverlayConfig(e){const i=new Gd({positionStrategy:this._overlay.position().global(),scrollStrategy:e.scrollStrategy||this._scrollStrategy(),panelClass:e.panelClass,hasBackdrop:e.hasBackdrop,direction:e.direction,minWidth:e.minWidth,minHeight:e.minHeight,maxWidth:e.maxWidth,maxHeight:e.maxHeight,disposeOnNavigation:e.closeOnNavigation});return e.backdropClass&&(i.backdropClass=e.backdropClass),i}_attachDialogContainer(e,i){const s=dt.create({parent:i&&i.viewContainerRef&&i.viewContainerRef.injector||this._injector,providers:[{provide:qg,useValue:i}]}),o=new yg(this._dialogContainerType,i.viewContainerRef,s,i.componentFactoryResolver);return e.attach(o).instance}_attachDialogContent(e,i,r,s){const o=new this._dialogRefConstructor(r,i,s.id);if(e instanceof ut)i.attachTemplatePortal(new $d(e,null,{$implicit:s.data,dialogRef:o}));else{const a=this._createInjector(s,o,i),l=i.attachComponentPortal(new yg(e,s.viewContainerRef,a,s.componentFactoryResolver));o.componentInstance=l.instance}return o.updateSize(s.width,s.height).updatePosition(s.position),o}_createInjector(e,i,r){const s=e&&e.viewContainerRef&&e.viewContainerRef.injector,o=[{provide:this._dialogContainerType,useValue:r},{provide:this._dialogDataToken,useValue:e.data},{provide:this._dialogRefConstructor,useValue:i}];return e.direction&&(!s||!s.get(On,null,ee.Optional))&&o.push({provide:On,useValue:{value:e.direction,change:q()}}),dt.create({parent:s||this._injector,providers:o})}_removeOpenDialog(e){const i=this.openDialogs.indexOf(e);i>-1&&(this.openDialogs.splice(i,1),this.openDialogs.length||(this._ariaHiddenElements.forEach((r,s)=>{r?s.setAttribute(\"aria-hidden\",r):s.removeAttribute(\"aria-hidden\")}),this._ariaHiddenElements.clear(),this._getAfterAllClosed().next()))}_hideNonDialogContentFromAssistiveTechnology(){const e=this._overlayContainer.getContainerElement();if(e.parentElement){const i=e.parentElement.children;for(let r=i.length-1;r>-1;r--){let s=i[r];s!==e&&\"SCRIPT\"!==s.nodeName&&\"STYLE\"!==s.nodeName&&!s.hasAttribute(\"aria-live\")&&(this._ariaHiddenElements.set(s,s.getAttribute(\"aria-hidden\")),s.setAttribute(\"aria-hidden\",\"true\"))}}}_closeDialogs(e){let i=e.length;for(;i--;)e[i].close()}}return n.\\u0275fac=function(e){Sr()},n.\\u0275dir=C({type:n}),n})(),j4=(()=>{class n extends H4{constructor(e,i,r,s,o,a,l,c){super(e,i,s,a,l,o,F4,O4,N4,c)}}return n.\\u0275fac=function(e){return new(e||n)(y(ni),y(dt),y(va,8),y(L4,8),y(XS),y(n,12),y(Dg),y(Rn,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),U4=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[j4,V4],imports:[[ji,Hi,B],B]}),n})(),JS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),$4=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B,ZE,Hi]]}),n})(),rG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Vd,ti,B,og,bt],Vd,B,og,JS]}),n})();const lG={provide:new b(\"mat-menu-scroll-strategy\"),deps:[ni],useFactory:function aG(n){return()=>n.scrollStrategies.reposition()}};let cG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[lG],imports:[[bt,B,ti,ji],Ci,B]}),n})();const pG={provide:new b(\"mat-tooltip-scroll-strategy\"),deps:[ni],useFactory:function hG(n){return()=>n.scrollStrategies.reposition({scrollThrottle:20})}};let ik=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[pG],imports:[[Qa,bt,ji,B],B,Ci]}),n})(),Yg=(()=>{class n{constructor(){this.changes=new O,this.itemsPerPageLabel=\"Items per page:\",this.nextPageLabel=\"Next page\",this.previousPageLabel=\"Previous page\",this.firstPageLabel=\"First page\",this.lastPageLabel=\"Last page\",this.getRangeLabel=(e,i,r)=>{if(0==r||0==i)return`0 of ${r}`;const s=e*i;return`${s+1} \\u2013 ${s<(r=Math.max(r,0))?Math.min(s+i,r):s+i} of ${r}`}}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const yG={provide:Yg,deps:[[new Tt,new Cn,Yg]],useFactory:function vG(n){return n||new Yg}};let bG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[yG],imports:[[bt,ul,qE,ik,B]]}),n})(),DG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B],B]}),n})();function wG(n,t){if(1&n&&(Oo(),Le(0,\"circle\",4)),2&n){const e=Be(),i=wn(1);$n(\"animation-name\",\"mat-progress-spinner-stroke-rotate-\"+e._spinnerAnimationLabel)(\"stroke-dashoffset\",e._getStrokeDashOffset(),\"px\")(\"stroke-dasharray\",e._getStrokeCircumference(),\"px\")(\"stroke-width\",e._getCircleStrokeWidth(),\"%\")(\"transform-origin\",e._getCircleTransformOrigin(i)),Z(\"r\",e._getCircleRadius())}}function MG(n,t){if(1&n&&(Oo(),Le(0,\"circle\",4)),2&n){const e=Be(),i=wn(1);$n(\"stroke-dashoffset\",e._getStrokeDashOffset(),\"px\")(\"stroke-dasharray\",e._getStrokeCircumference(),\"px\")(\"stroke-width\",e._getCircleStrokeWidth(),\"%\")(\"transform-origin\",e._getCircleTransformOrigin(i)),Z(\"r\",e._getCircleRadius())}}const EG=fo(class{constructor(n){this._elementRef=n}},\"primary\"),SG=new b(\"mat-progress-spinner-default-options\",{providedIn:\"root\",factory:function kG(){return{diameter:100}}});class dr extends EG{constructor(t,e,i,r,s,o,a,l){super(t),this._document=i,this._diameter=100,this._value=0,this._resizeSubscription=ke.EMPTY,this.mode=\"determinate\";const c=dr._diameters;this._spinnerAnimationLabel=this._getSpinnerAnimationLabel(),c.has(i.head)||c.set(i.head,new Set([100])),this._noopAnimations=\"NoopAnimations\"===r&&!!s&&!s._forceAnimations,\"mat-spinner\"===t.nativeElement.nodeName.toLowerCase()&&(this.mode=\"indeterminate\"),s&&(s.diameter&&(this.diameter=s.diameter),s.strokeWidth&&(this.strokeWidth=s.strokeWidth)),e.isBrowser&&e.SAFARI&&a&&o&&l&&(this._resizeSubscription=a.change(150).subscribe(()=>{\"indeterminate\"===this.mode&&l.run(()=>o.markForCheck())}))}get diameter(){return this._diameter}set diameter(t){this._diameter=Et(t),this._spinnerAnimationLabel=this._getSpinnerAnimationLabel(),this._styleRoot&&this._attachStyleNode()}get strokeWidth(){return this._strokeWidth||this.diameter/10}set strokeWidth(t){this._strokeWidth=Et(t)}get value(){return\"determinate\"===this.mode?this._value:0}set value(t){this._value=Math.max(0,Math.min(100,Et(t)))}ngOnInit(){const t=this._elementRef.nativeElement;this._styleRoot=Fd(t)||this._document.head,this._attachStyleNode(),t.classList.add(\"mat-progress-spinner-indeterminate-animation\")}ngOnDestroy(){this._resizeSubscription.unsubscribe()}_getCircleRadius(){return(this.diameter-10)/2}_getViewBox(){const t=2*this._getCircleRadius()+this.strokeWidth;return`0 0 ${t} ${t}`}_getStrokeCircumference(){return 2*Math.PI*this._getCircleRadius()}_getStrokeDashOffset(){return\"determinate\"===this.mode?this._getStrokeCircumference()*(100-this._value)/100:null}_getCircleStrokeWidth(){return this.strokeWidth/this.diameter*100}_getCircleTransformOrigin(t){var e;const i=50*(null!==(e=t.currentScale)&&void 0!==e?e:1);return`${i}% ${i}%`}_attachStyleNode(){const t=this._styleRoot,e=this._diameter,i=dr._diameters;let r=i.get(t);if(!r||!r.has(e)){const s=this._document.createElement(\"style\");s.setAttribute(\"mat-spinner-animation\",this._spinnerAnimationLabel),s.textContent=this._getAnimationText(),t.appendChild(s),r||(r=new Set,i.set(t,r)),r.add(e)}}_getAnimationText(){const t=this._getStrokeCircumference();return\"\\n @keyframes mat-progress-spinner-stroke-rotate-DIAMETER {\\n 0% { stroke-dashoffset: START_VALUE; transform: rotate(0); }\\n 12.5% { stroke-dashoffset: END_VALUE; transform: rotate(0); }\\n 12.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(72.5deg); }\\n 25% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(72.5deg); }\\n\\n 25.0001% { stroke-dashoffset: START_VALUE; transform: rotate(270deg); }\\n 37.5% { stroke-dashoffset: END_VALUE; transform: rotate(270deg); }\\n 37.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(161.5deg); }\\n 50% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(161.5deg); }\\n\\n 50.0001% { stroke-dashoffset: START_VALUE; transform: rotate(180deg); }\\n 62.5% { stroke-dashoffset: END_VALUE; transform: rotate(180deg); }\\n 62.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(251.5deg); }\\n 75% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(251.5deg); }\\n\\n 75.0001% { stroke-dashoffset: START_VALUE; transform: rotate(90deg); }\\n 87.5% { stroke-dashoffset: END_VALUE; transform: rotate(90deg); }\\n 87.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(341.5deg); }\\n 100% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(341.5deg); }\\n }\\n\".replace(/START_VALUE/g,\"\"+.95*t).replace(/END_VALUE/g,\"\"+.2*t).replace(/DIAMETER/g,`${this._spinnerAnimationLabel}`)}_getSpinnerAnimationLabel(){return this.diameter.toString().replace(\".\",\"_\")}}dr._diameters=new WeakMap,dr.\\u0275fac=function(t){return new(t||dr)(f(W),f(It),f(ie,8),f(Rn,8),f(SG),f(Ye),f(es),f(ne))},dr.\\u0275cmp=xe({type:dr,selectors:[[\"mat-progress-spinner\"],[\"mat-spinner\"]],hostAttrs:[\"role\",\"progressbar\",\"tabindex\",\"-1\",1,\"mat-progress-spinner\",\"mat-spinner\"],hostVars:10,hostBindings:function(t,e){2&t&&(Z(\"aria-valuemin\",\"determinate\"===e.mode?0:null)(\"aria-valuemax\",\"determinate\"===e.mode?100:null)(\"aria-valuenow\",\"determinate\"===e.mode?e.value:null)(\"mode\",e.mode),$n(\"width\",e.diameter,\"px\")(\"height\",e.diameter,\"px\"),Ae(\"_mat-animation-noopable\",e._noopAnimations))},inputs:{color:\"color\",diameter:\"diameter\",strokeWidth:\"strokeWidth\",mode:\"mode\",value:\"value\"},exportAs:[\"matProgressSpinner\"],features:[E],decls:4,vars:8,consts:[[\"preserveAspectRatio\",\"xMidYMid meet\",\"focusable\",\"false\",\"aria-hidden\",\"true\",3,\"ngSwitch\"],[\"svg\",\"\"],[\"cx\",\"50%\",\"cy\",\"50%\",3,\"animation-name\",\"stroke-dashoffset\",\"stroke-dasharray\",\"stroke-width\",\"transform-origin\",4,\"ngSwitchCase\"],[\"cx\",\"50%\",\"cy\",\"50%\",3,\"stroke-dashoffset\",\"stroke-dasharray\",\"stroke-width\",\"transform-origin\",4,\"ngSwitchCase\"],[\"cx\",\"50%\",\"cy\",\"50%\"]],template:function(t,e){1&t&&(Oo(),x(0,\"svg\",0,1),Ee(2,wG,1,11,\"circle\",2),Ee(3,MG,1,9,\"circle\",3),S()),2&t&&($n(\"width\",e.diameter,\"px\")(\"height\",e.diameter,\"px\"),N(\"ngSwitch\",\"indeterminate\"===e.mode),Z(\"viewBox\",e._getViewBox()),T(2),N(\"ngSwitchCase\",!0),T(1),N(\"ngSwitchCase\",!1))},directives:[Ys,Pc],styles:[\".mat-progress-spinner{display:block;position:relative;overflow:hidden}.mat-progress-spinner svg{position:absolute;transform:rotate(-90deg);top:0;left:0;transform-origin:center;overflow:visible}.mat-progress-spinner circle{fill:transparent;transition:stroke-dashoffset 225ms linear}._mat-animation-noopable.mat-progress-spinner circle{transition:none;animation:none}.cdk-high-contrast-active .mat-progress-spinner circle{stroke:CanvasText}.mat-progress-spinner.mat-progress-spinner-indeterminate-animation[mode=indeterminate] svg{animation:mat-progress-spinner-linear-rotate 2000ms linear infinite}._mat-animation-noopable.mat-progress-spinner.mat-progress-spinner-indeterminate-animation[mode=indeterminate] svg{transition:none;animation:none}.mat-progress-spinner.mat-progress-spinner-indeterminate-animation[mode=indeterminate] circle{transition-property:stroke;animation-duration:4000ms;animation-timing-function:cubic-bezier(0.35, 0, 0.25, 1);animation-iteration-count:infinite}._mat-animation-noopable.mat-progress-spinner.mat-progress-spinner-indeterminate-animation[mode=indeterminate] circle{transition:none;animation:none}@keyframes mat-progress-spinner-linear-rotate{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@keyframes mat-progress-spinner-stroke-rotate-100{0%{stroke-dashoffset:268.606171575px;transform:rotate(0)}12.5%{stroke-dashoffset:56.5486677px;transform:rotate(0)}12.5001%{stroke-dashoffset:56.5486677px;transform:rotateX(180deg) rotate(72.5deg)}25%{stroke-dashoffset:268.606171575px;transform:rotateX(180deg) rotate(72.5deg)}25.0001%{stroke-dashoffset:268.606171575px;transform:rotate(270deg)}37.5%{stroke-dashoffset:56.5486677px;transform:rotate(270deg)}37.5001%{stroke-dashoffset:56.5486677px;transform:rotateX(180deg) rotate(161.5deg)}50%{stroke-dashoffset:268.606171575px;transform:rotateX(180deg) rotate(161.5deg)}50.0001%{stroke-dashoffset:268.606171575px;transform:rotate(180deg)}62.5%{stroke-dashoffset:56.5486677px;transform:rotate(180deg)}62.5001%{stroke-dashoffset:56.5486677px;transform:rotateX(180deg) rotate(251.5deg)}75%{stroke-dashoffset:268.606171575px;transform:rotateX(180deg) rotate(251.5deg)}75.0001%{stroke-dashoffset:268.606171575px;transform:rotate(90deg)}87.5%{stroke-dashoffset:56.5486677px;transform:rotate(90deg)}87.5001%{stroke-dashoffset:56.5486677px;transform:rotateX(180deg) rotate(341.5deg)}100%{stroke-dashoffset:268.606171575px;transform:rotateX(180deg) rotate(341.5deg)}}\\n\"],encapsulation:2,changeDetection:0});let AG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B,bt],B]}),n})(),UG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ti,B],B]}),n})(),GG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B,Ci],Ci,B]}),n})(),ak=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),sW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ak,ti,B,Ya],ak,B]}),n})(),lW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ji,Hi,bt,ul,B],B]}),n})(),Kg=(()=>{class n{constructor(){this.changes=new O}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const uW={provide:Kg,deps:[[new Tt,new Cn,Kg]],useFactory:function dW(n){return n||new Kg}};let hW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[uW],imports:[[bt,B]]}),n})(),TW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bS,B],B]}),n})(),FW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B,Hi,ti,Ya,Qa],B]}),n})(),NW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),$W=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[CS,B],B]}),n})(),GW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[Qa,ZE,m$,fS,bS,CS,S$,t8,n8,r8,ul,u8,h8,M8,L8,u4,T4,U4,JS,$4,CU,WS,a$,rG,cG,U3,bG,DG,AG,UG,ti,qE,GG,gE,sW,lW,hW,TW,FW,NW,ik,$W,ji,Hi,Ud]}),n})(),WW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n,bootstrap:[f$]}),n.\\u0275inj=P({providers:[],imports:[[FD,B2,Pz,Fz,Nj,gE,GW]]}),n})();(function YF(){G0=!1})(),console.info(\"Angular CDK version\",Lm.full),console.info(\"Angular Material version\",Jm.full),oB().bootstrapModule(WW).catch(n=>console.error(n))}},De=>{De(De.s=532)}]);", "file_path": "docs/main.e3e00859dfd66644.js", "rank": 20, "score": 96506.13743688195 }, { "content": "\"use strict\";(self.webpackChunkbridge=self.webpackChunkbridge||[]).push([[179],{532:()=>{function De(n){return\"function\"==typeof n}function xo(n){const e=n(i=>{Error.call(i),i.stack=(new Error).stack});return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}const fl=xo(n=>function(e){n(this),this.message=e?`${e.length} errors occurred during unsubscription:\\n${e.map((i,r)=>`${r+1}) ${i.toString()}`).join(\"\\n \")}`:\"\",this.name=\"UnsubscriptionError\",this.errors=e});function ss(n,t){if(n){const e=n.indexOf(t);0<=e&&n.splice(e,1)}}class ke{constructor(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}unsubscribe(){let t;if(!this.closed){this.closed=!0;const{_parentage:e}=this;if(e)if(this._parentage=null,Array.isArray(e))for(const s of e)s.remove(this);else e.remove(this);const{initialTeardown:i}=this;if(De(i))try{i()}catch(s){t=s instanceof fl?s.errors:[s]}const{_finalizers:r}=this;if(r){this._finalizers=null;for(const s of r)try{t_(s)}catch(o){t=null!=t?t:[],o instanceof fl?t=[...t,...o.errors]:t.push(o)}}if(t)throw new fl(t)}}add(t){var e;if(t&&t!==this)if(this.closed)t_(t);else{if(t instanceof ke){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(e=this._finalizers)&&void 0!==e?e:[]).push(t)}}_hasParent(t){const{_parentage:e}=this;return e===t||Array.isArray(e)&&e.includes(t)}_addParent(t){const{_parentage:e}=this;this._parentage=Array.isArray(e)?(e.push(t),e):e?[e,t]:t}_removeParent(t){const{_parentage:e}=this;e===t?this._parentage=null:Array.isArray(e)&&ss(e,t)}remove(t){const{_finalizers:e}=this;e&&ss(e,t),t instanceof ke&&t._removeParent(this)}}ke.EMPTY=(()=>{const n=new ke;return n.closed=!0,n})();const Jg=ke.EMPTY;function e_(n){return n instanceof ke||n&&\"closed\"in n&&De(n.remove)&&De(n.add)&&De(n.unsubscribe)}function t_(n){De(n)?n():n.unsubscribe()}const fr={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},ml={setTimeout(n,t,...e){const{delegate:i}=ml;return(null==i?void 0:i.setTimeout)?i.setTimeout(n,t,...e):setTimeout(n,t,...e)},clearTimeout(n){const{delegate:t}=ml;return((null==t?void 0:t.clearTimeout)||clearTimeout)(n)},delegate:void 0};function n_(n){ml.setTimeout(()=>{const{onUnhandledError:t}=fr;if(!t)throw n;t(n)})}function gl(){}const fk=fu(\"C\",void 0,void 0);function fu(n,t,e){return{kind:n,value:t,error:e}}let mr=null;function _l(n){if(fr.useDeprecatedSynchronousErrorHandling){const t=!mr;if(t&&(mr={errorThrown:!1,error:null}),n(),t){const{errorThrown:e,error:i}=mr;if(mr=null,e)throw i}}else n()}class mu extends ke{constructor(t){super(),this.isStopped=!1,t?(this.destination=t,e_(t)&&t.add(this)):this.destination=Ck}static create(t,e,i){return new vl(t,e,i)}next(t){this.isStopped?_u(function gk(n){return fu(\"N\",n,void 0)}(t),this):this._next(t)}error(t){this.isStopped?_u(function mk(n){return fu(\"E\",void 0,n)}(t),this):(this.isStopped=!0,this._error(t))}complete(){this.isStopped?_u(fk,this):(this.isStopped=!0,this._complete())}unsubscribe(){this.closed||(this.isStopped=!0,super.unsubscribe(),this.destination=null)}_next(t){this.destination.next(t)}_error(t){try{this.destination.error(t)}finally{this.unsubscribe()}}_complete(){try{this.destination.complete()}finally{this.unsubscribe()}}}const vk=Function.prototype.bind;function gu(n,t){return vk.call(n,t)}class yk{constructor(t){this.partialObserver=t}next(t){const{partialObserver:e}=this;if(e.next)try{e.next(t)}catch(i){yl(i)}}error(t){const{partialObserver:e}=this;if(e.error)try{e.error(t)}catch(i){yl(i)}else yl(t)}complete(){const{partialObserver:t}=this;if(t.complete)try{t.complete()}catch(e){yl(e)}}}class vl extends mu{constructor(t,e,i){let r;if(super(),De(t)||!t)r={next:null!=t?t:void 0,error:null!=e?e:void 0,complete:null!=i?i:void 0};else{let s;this&&fr.useDeprecatedNextContext?(s=Object.create(t),s.unsubscribe=()=>this.unsubscribe(),r={next:t.next&&gu(t.next,s),error:t.error&&gu(t.error,s),complete:t.complete&&gu(t.complete,s)}):r=t}this.destination=new yk(r)}}function yl(n){fr.useDeprecatedSynchronousErrorHandling?function _k(n){fr.useDeprecatedSynchronousErrorHandling&&mr&&(mr.errorThrown=!0,mr.error=n)}(n):n_(n)}function _u(n,t){const{onStoppedNotification:e}=fr;e&&ml.setTimeout(()=>e(n,t))}const Ck={closed:!0,next:gl,error:function bk(n){throw n},complete:gl},vu=\"function\"==typeof Symbol&&Symbol.observable||\"@@observable\";function Wi(n){return n}let Ve=(()=>{class n{constructor(e){e&&(this._subscribe=e)}lift(e){const i=new n;return i.source=this,i.operator=e,i}subscribe(e,i,r){const s=function wk(n){return n&&n instanceof mu||function Dk(n){return n&&De(n.next)&&De(n.error)&&De(n.complete)}(n)&&e_(n)}(e)?e:new vl(e,i,r);return _l(()=>{const{operator:o,source:a}=this;s.add(o?o.call(s,a):a?this._subscribe(s):this._trySubscribe(s))}),s}_trySubscribe(e){try{return this._subscribe(e)}catch(i){e.error(i)}}forEach(e,i){return new(i=r_(i))((r,s)=>{const o=new vl({next:a=>{try{e(a)}catch(l){s(l),o.unsubscribe()}},error:s,complete:r});this.subscribe(o)})}_subscribe(e){var i;return null===(i=this.source)||void 0===i?void 0:i.subscribe(e)}[vu](){return this}pipe(...e){return function i_(n){return 0===n.length?Wi:1===n.length?n[0]:function(e){return n.reduce((i,r)=>r(i),e)}}(e)(this)}toPromise(e){return new(e=r_(e))((i,r)=>{let s;this.subscribe(o=>s=o,o=>r(o),()=>i(s))})}}return n.create=t=>new n(t),n})();function r_(n){var t;return null!==(t=null!=n?n:fr.Promise)&&void 0!==t?t:Promise}const Mk=xo(n=>function(){n(this),this.name=\"ObjectUnsubscribedError\",this.message=\"object unsubscribed\"});let O=(()=>{class n extends Ve{constructor(){super(),this.closed=!1,this.currentObservers=null,this.observers=[],this.isStopped=!1,this.hasError=!1,this.thrownError=null}lift(e){const i=new s_(this,this);return i.operator=e,i}_throwIfClosed(){if(this.closed)throw new Mk}next(e){_l(()=>{if(this._throwIfClosed(),!this.isStopped){this.currentObservers||(this.currentObservers=Array.from(this.observers));for(const i of this.currentObservers)i.next(e)}})}error(e){_l(()=>{if(this._throwIfClosed(),!this.isStopped){this.hasError=this.isStopped=!0,this.thrownError=e;const{observers:i}=this;for(;i.length;)i.shift().error(e)}})}complete(){_l(()=>{if(this._throwIfClosed(),!this.isStopped){this.isStopped=!0;const{observers:e}=this;for(;e.length;)e.shift().complete()}})}unsubscribe(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null}get observed(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0}_trySubscribe(e){return this._throwIfClosed(),super._trySubscribe(e)}_subscribe(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)}_innerSubscribe(e){const{hasError:i,isStopped:r,observers:s}=this;return i||r?Jg:(this.currentObservers=null,s.push(e),new ke(()=>{this.currentObservers=null,ss(s,e)}))}_checkFinalizedStatuses(e){const{hasError:i,thrownError:r,isStopped:s}=this;i?e.error(r):s&&e.complete()}asObservable(){const e=new Ve;return e.source=this,e}}return n.create=(t,e)=>new s_(t,e),n})();class s_ extends O{constructor(t,e){super(),this.destination=t,this.source=e}next(t){var e,i;null===(i=null===(e=this.destination)||void 0===e?void 0:e.next)||void 0===i||i.call(e,t)}error(t){var e,i;null===(i=null===(e=this.destination)||void 0===e?void 0:e.error)||void 0===i||i.call(e,t)}complete(){var t,e;null===(e=null===(t=this.destination)||void 0===t?void 0:t.complete)||void 0===e||e.call(t)}_subscribe(t){var e,i;return null!==(i=null===(e=this.source)||void 0===e?void 0:e.subscribe(t))&&void 0!==i?i:Jg}}function o_(n){return De(null==n?void 0:n.lift)}function qe(n){return t=>{if(o_(t))return t.lift(function(e){try{return n(e,this)}catch(i){this.error(i)}});throw new TypeError(\"Unable to lift unknown Observable type\")}}function Ue(n,t,e,i,r){return new xk(n,t,e,i,r)}class xk extends mu{constructor(t,e,i,r,s,o){super(t),this.onFinalize=s,this.shouldUnsubscribe=o,this._next=e?function(a){try{e(a)}catch(l){t.error(l)}}:super._next,this._error=r?function(a){try{r(a)}catch(l){t.error(l)}finally{this.unsubscribe()}}:super._error,this._complete=i?function(){try{i()}catch(a){t.error(a)}finally{this.unsubscribe()}}:super._complete}unsubscribe(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){const{closed:e}=this;super.unsubscribe(),!e&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}}}function ue(n,t){return qe((e,i)=>{let r=0;e.subscribe(Ue(i,s=>{i.next(n.call(t,s,r++))}))})}function gr(n){return this instanceof gr?(this.v=n,this):new gr(n)}function kk(n,t,e){if(!Symbol.asyncIterator)throw new TypeError(\"Symbol.asyncIterator is not defined.\");var r,i=e.apply(n,t||[]),s=[];return r={},o(\"next\"),o(\"throw\"),o(\"return\"),r[Symbol.asyncIterator]=function(){return this},r;function o(h){i[h]&&(r[h]=function(p){return new Promise(function(m,g){s.push([h,p,m,g])>1||a(h,p)})})}function a(h,p){try{!function l(h){h.value instanceof gr?Promise.resolve(h.value.v).then(c,d):u(s[0][2],h)}(i[h](p))}catch(m){u(s[0][3],m)}}function c(h){a(\"next\",h)}function d(h){a(\"throw\",h)}function u(h,p){h(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function Tk(n){if(!Symbol.asyncIterator)throw new TypeError(\"Symbol.asyncIterator is not defined.\");var e,t=n[Symbol.asyncIterator];return t?t.call(n):(n=function c_(n){var t=\"function\"==typeof Symbol&&Symbol.iterator,e=t&&n[t],i=0;if(e)return e.call(n);if(n&&\"number\"==typeof n.length)return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(t?\"Object is not iterable.\":\"Symbol.iterator is not defined.\")}(n),e={},i(\"next\"),i(\"throw\"),i(\"return\"),e[Symbol.asyncIterator]=function(){return this},e);function i(s){e[s]=n[s]&&function(o){return new Promise(function(a,l){!function r(s,o,a,l){Promise.resolve(l).then(function(c){s({value:c,done:a})},o)}(a,l,(o=n[s](o)).done,o.value)})}}}const bu=n=>n&&\"number\"==typeof n.length&&\"function\"!=typeof n;function d_(n){return De(null==n?void 0:n.then)}function u_(n){return De(n[vu])}function h_(n){return Symbol.asyncIterator&&De(null==n?void 0:n[Symbol.asyncIterator])}function p_(n){return new TypeError(`You provided ${null!==n&&\"object\"==typeof n?\"an invalid object\":`'${n}'`} where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.`)}const f_=function Ik(){return\"function\"==typeof Symbol&&Symbol.iterator?Symbol.iterator:\"@@iterator\"}();function m_(n){return De(null==n?void 0:n[f_])}function g_(n){return kk(this,arguments,function*(){const e=n.getReader();try{for(;;){const{value:i,done:r}=yield gr(e.read());if(r)return yield gr(void 0);yield yield gr(i)}}finally{e.releaseLock()}})}function __(n){return De(null==n?void 0:n.getReader)}function Jt(n){if(n instanceof Ve)return n;if(null!=n){if(u_(n))return function Rk(n){return new Ve(t=>{const e=n[vu]();if(De(e.subscribe))return e.subscribe(t);throw new TypeError(\"Provided object does not correctly implement Symbol.observable\")})}(n);if(bu(n))return function Ok(n){return new Ve(t=>{for(let e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()})}(n);if(d_(n))return function Pk(n){return new Ve(t=>{n.then(e=>{t.closed||(t.next(e),t.complete())},e=>t.error(e)).then(null,n_)})}(n);if(h_(n))return v_(n);if(m_(n))return function Fk(n){return new Ve(t=>{for(const e of n)if(t.next(e),t.closed)return;t.complete()})}(n);if(__(n))return function Nk(n){return v_(g_(n))}(n)}throw p_(n)}function v_(n){return new Ve(t=>{(function Lk(n,t){var e,i,r,s;return function Ek(n,t,e,i){return new(e||(e=Promise))(function(s,o){function a(d){try{c(i.next(d))}catch(u){o(u)}}function l(d){try{c(i.throw(d))}catch(u){o(u)}}function c(d){d.done?s(d.value):function r(s){return s instanceof e?s:new e(function(o){o(s)})}(d.value).then(a,l)}c((i=i.apply(n,t||[])).next())})}(this,void 0,void 0,function*(){try{for(e=Tk(n);!(i=yield e.next()).done;)if(t.next(i.value),t.closed)return}catch(o){r={error:o}}finally{try{i&&!i.done&&(s=e.return)&&(yield s.call(e))}finally{if(r)throw r.error}}t.complete()})})(n,t).catch(e=>t.error(e))})}function Mi(n,t,e,i=0,r=!1){const s=t.schedule(function(){e(),r?n.add(this.schedule(null,i)):this.unsubscribe()},i);if(n.add(s),!r)return s}function lt(n,t,e=1/0){return De(t)?lt((i,r)=>ue((s,o)=>t(i,s,r,o))(Jt(n(i,r))),e):(\"number\"==typeof t&&(e=t),qe((i,r)=>function Bk(n,t,e,i,r,s,o,a){const l=[];let c=0,d=0,u=!1;const h=()=>{u&&!l.length&&!c&&t.complete()},p=g=>c<i?m(g):l.push(g),m=g=>{s&&t.next(g),c++;let _=!1;Jt(e(g,d++)).subscribe(Ue(t,D=>{null==r||r(D),s?p(D):t.next(D)},()=>{_=!0},void 0,()=>{if(_)try{for(c--;l.length&&c<i;){const D=l.shift();o?Mi(t,o,()=>m(D)):m(D)}h()}catch(D){t.error(D)}}))};return n.subscribe(Ue(t,p,()=>{u=!0,h()})),()=>{null==a||a()}}(i,r,n,e)))}function Eo(n=1/0){return lt(Wi,n)}const ri=new Ve(n=>n.complete());function y_(n){return n&&De(n.schedule)}function Cu(n){return n[n.length-1]}function b_(n){return De(Cu(n))?n.pop():void 0}function So(n){return y_(Cu(n))?n.pop():void 0}function C_(n,t=0){return qe((e,i)=>{e.subscribe(Ue(i,r=>Mi(i,n,()=>i.next(r),t),()=>Mi(i,n,()=>i.complete(),t),r=>Mi(i,n,()=>i.error(r),t)))})}function D_(n,t=0){return qe((e,i)=>{i.add(n.schedule(()=>e.subscribe(i),t))})}function w_(n,t){if(!n)throw new Error(\"Iterable cannot be null\");return new Ve(e=>{Mi(e,t,()=>{const i=n[Symbol.asyncIterator]();Mi(e,t,()=>{i.next().then(r=>{r.done?e.complete():e.next(r.value)})},0,!0)})})}function mt(n,t){return t?function Wk(n,t){if(null!=n){if(u_(n))return function jk(n,t){return Jt(n).pipe(D_(t),C_(t))}(n,t);if(bu(n))return function Uk(n,t){return new Ve(e=>{let i=0;return t.schedule(function(){i===n.length?e.complete():(e.next(n[i++]),e.closed||this.schedule())})})}(n,t);if(d_(n))return function zk(n,t){return Jt(n).pipe(D_(t),C_(t))}(n,t);if(h_(n))return w_(n,t);if(m_(n))return function $k(n,t){return new Ve(e=>{let i;return Mi(e,t,()=>{i=n[f_](),Mi(e,t,()=>{let r,s;try{({value:r,done:s}=i.next())}catch(o){return void e.error(o)}s?e.complete():e.next(r)},0,!0)}),()=>De(null==i?void 0:i.return)&&i.return()})}(n,t);if(__(n))return function Gk(n,t){return w_(g_(n),t)}(n,t)}throw p_(n)}(n,t):Jt(n)}function Bt(...n){const t=So(n),e=function Hk(n,t){return\"number\"==typeof Cu(n)?n.pop():t}(n,1/0),i=n;return i.length?1===i.length?Jt(i[0]):Eo(e)(mt(i,t)):ri}function it(n){return n<=0?()=>ri:qe((t,e)=>{let i=0;t.subscribe(Ue(e,r=>{++i<=n&&(e.next(r),n<=i&&e.complete())}))})}function Du(n,t,...e){return!0===t?(n(),null):!1===t?null:t(...e).pipe(it(1)).subscribe(()=>n())}function Fe(n){for(let t in n)if(n[t]===Fe)return t;throw Error(\"Could not find renamed property on target object.\")}function wu(n,t){for(const e in t)t.hasOwnProperty(e)&&!n.hasOwnProperty(e)&&(n[e]=t[e])}function Re(n){if(\"string\"==typeof n)return n;if(Array.isArray(n))return\"[\"+n.map(Re).join(\", \")+\"]\";if(null==n)return\"\"+n;if(n.overriddenName)return`${n.overriddenName}`;if(n.name)return`${n.name}`;const t=n.toString();if(null==t)return\"\"+t;const e=t.indexOf(\"\\n\");return-1===e?t:t.substring(0,e)}function Mu(n,t){return null==n||\"\"===n?null===t?\"\":t:null==t||\"\"===t?n:n+\" \"+t}const qk=Fe({__forward_ref__:Fe});function pe(n){return n.__forward_ref__=pe,n.toString=function(){return Re(this())},n}function le(n){return x_(n)?n():n}function x_(n){return\"function\"==typeof n&&n.hasOwnProperty(qk)&&n.__forward_ref__===pe}class H extends Error{constructor(t,e){super(function xu(n,t){return`NG0${Math.abs(n)}${t?\": \"+t:\"\"}`}(t,e)),this.code=t}}function re(n){return\"string\"==typeof n?n:null==n?\"\":String(n)}function Vt(n){return\"function\"==typeof n?n.name||n.toString():\"object\"==typeof n&&null!=n&&\"function\"==typeof n.type?n.type.name||n.type.toString():re(n)}function bl(n,t){const e=t?` in ${t}`:\"\";throw new H(-201,`No provider for ${Vt(n)} found${e}`)}function tn(n,t){null==n&&function $e(n,t,e,i){throw new Error(`ASSERTION ERROR: ${n}`+(null==i?\"\":` [Expected=> ${e} ${i} ${t} <=Actual]`))}(t,n,null,\"!=\")}function k(n){return{token:n.token,providedIn:n.providedIn||null,factory:n.factory,value:void 0}}function P(n){return{providers:n.providers||[],imports:n.imports||[]}}function Eu(n){return E_(n,Cl)||E_(n,k_)}function E_(n,t){return n.hasOwnProperty(t)?n[t]:null}function S_(n){return n&&(n.hasOwnProperty(Su)||n.hasOwnProperty(eT))?n[Su]:null}const Cl=Fe({\\u0275prov:Fe}),Su=Fe({\\u0275inj:Fe}),k_=Fe({ngInjectableDef:Fe}),eT=Fe({ngInjectorDef:Fe});var ee=(()=>((ee=ee||{})[ee.Default=0]=\"Default\",ee[ee.Host=1]=\"Host\",ee[ee.Self=2]=\"Self\",ee[ee.SkipSelf=4]=\"SkipSelf\",ee[ee.Optional=8]=\"Optional\",ee))();let ku;function qi(n){const t=ku;return ku=n,t}function T_(n,t,e){const i=Eu(n);return i&&\"root\"==i.providedIn?void 0===i.value?i.value=i.factory():i.value:e&ee.Optional?null:void 0!==t?t:void bl(Re(n),\"Injector\")}function Yi(n){return{toString:n}.toString()}var Nn=(()=>((Nn=Nn||{})[Nn.OnPush=0]=\"OnPush\",Nn[Nn.Default=1]=\"Default\",Nn))(),Ln=(()=>{return(n=Ln||(Ln={}))[n.Emulated=0]=\"Emulated\",n[n.None=2]=\"None\",n[n.ShadowDom=3]=\"ShadowDom\",Ln;var n})();const nT=\"undefined\"!=typeof globalThis&&globalThis,iT=\"undefined\"!=typeof window&&window,rT=\"undefined\"!=typeof self&&\"undefined\"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&self,Oe=nT||\"undefined\"!=typeof global&&global||iT||rT,os={},Ne=[],Dl=Fe({\\u0275cmp:Fe}),Tu=Fe({\\u0275dir:Fe}),Au=Fe({\\u0275pipe:Fe}),A_=Fe({\\u0275mod:Fe}),Ei=Fe({\\u0275fac:Fe}),ko=Fe({__NG_ELEMENT_ID__:Fe});let sT=0;function xe(n){return Yi(()=>{const e={},i={type:n.type,providersResolver:null,decls:n.decls,vars:n.vars,factory:null,template:n.template||null,consts:n.consts||null,ngContentSelectors:n.ngContentSelectors,hostBindings:n.hostBindings||null,hostVars:n.hostVars||0,hostAttrs:n.hostAttrs||null,contentQueries:n.contentQueries||null,declaredInputs:e,inputs:null,outputs:null,exportAs:n.exportAs||null,onPush:n.changeDetection===Nn.OnPush,directiveDefs:null,pipeDefs:null,selectors:n.selectors||Ne,viewQuery:n.viewQuery||null,features:n.features||null,data:n.data||{},encapsulation:n.encapsulation||Ln.Emulated,id:\"c\",styles:n.styles||Ne,_:null,setInput:null,schemas:n.schemas||null,tView:null},r=n.directives,s=n.features,o=n.pipes;return i.id+=sT++,i.inputs=P_(n.inputs,e),i.outputs=P_(n.outputs),s&&s.forEach(a=>a(i)),i.directiveDefs=r?()=>(\"function\"==typeof r?r():r).map(I_):null,i.pipeDefs=o?()=>(\"function\"==typeof o?o():o).map(R_):null,i})}function I_(n){return Ot(n)||function Qi(n){return n[Tu]||null}(n)}function R_(n){return function _r(n){return n[Au]||null}(n)}const O_={};function F(n){return Yi(()=>{const t={type:n.type,bootstrap:n.bootstrap||Ne,declarations:n.declarations||Ne,imports:n.imports||Ne,exports:n.exports||Ne,transitiveCompileScopes:null,schemas:n.schemas||null,id:n.id||null};return null!=n.id&&(O_[n.id]=n.type),t})}function P_(n,t){if(null==n)return os;const e={};for(const i in n)if(n.hasOwnProperty(i)){let r=n[i],s=r;Array.isArray(r)&&(s=r[1],r=r[0]),e[r]=i,t&&(t[r]=s)}return e}const C=xe;function Ot(n){return n[Dl]||null}function gn(n,t){const e=n[A_]||null;if(!e&&!0===t)throw new Error(`Type ${Re(n)} does not have '\\u0275mod' property.`);return e}function si(n){return Array.isArray(n)&&\"object\"==typeof n[1]}function Vn(n){return Array.isArray(n)&&!0===n[1]}function Ou(n){return 0!=(8&n.flags)}function El(n){return 2==(2&n.flags)}function Sl(n){return 1==(1&n.flags)}function Hn(n){return null!==n.template}function uT(n){return 0!=(512&n[2])}function Cr(n,t){return n.hasOwnProperty(Ei)?n[Ei]:null}class fT{constructor(t,e,i){this.previousValue=t,this.currentValue=e,this.firstChange=i}isFirstChange(){return this.firstChange}}function Je(){return N_}function N_(n){return n.type.prototype.ngOnChanges&&(n.setInput=gT),mT}function mT(){const n=B_(this),t=null==n?void 0:n.current;if(t){const e=n.previous;if(e===os)n.previous=t;else for(let i in t)e[i]=t[i];n.current=null,this.ngOnChanges(t)}}function gT(n,t,e,i){const r=B_(n)||function _T(n,t){return n[L_]=t}(n,{previous:os,current:null}),s=r.current||(r.current={}),o=r.previous,a=this.declaredInputs[e],l=o[a];s[a]=new fT(l&&l.currentValue,t,o===os),n[i]=t}Je.ngInherit=!0;const L_=\"__ngSimpleChanges__\";function B_(n){return n[L_]||null}let Bu;function et(n){return!!n.listen}const V_={createRenderer:(n,t)=>function Vu(){return void 0!==Bu?Bu:\"undefined\"!=typeof document?document:void 0}()};function ct(n){for(;Array.isArray(n);)n=n[0];return n}function kl(n,t){return ct(t[n])}function yn(n,t){return ct(t[n.index])}function Hu(n,t){return n.data[t]}function rn(n,t){const e=t[n];return si(e)?e:e[0]}function H_(n){return 4==(4&n[2])}function ju(n){return 128==(128&n[2])}function Ki(n,t){return null==t?null:n[t]}function j_(n){n[18]=0}function zu(n,t){n[5]+=t;let e=n,i=n[3];for(;null!==i&&(1===t&&1===e[5]||-1===t&&0===e[5]);)i[5]+=t,e=i,i=i[3]}const te={lFrame:Q_(null),bindingsEnabled:!0,isInCheckNoChangesMode:!1};function z_(){return te.bindingsEnabled}function w(){return te.lFrame.lView}function Me(){return te.lFrame.tView}function Dr(n){return te.lFrame.contextLView=n,n[8]}function gt(){let n=U_();for(;null!==n&&64===n.type;)n=n.parent;return n}function U_(){return te.lFrame.currentTNode}function oi(n,t){const e=te.lFrame;e.currentTNode=n,e.isParent=t}function Uu(){return te.lFrame.isParent}function $u(){te.lFrame.isParent=!1}function Tl(){return te.isInCheckNoChangesMode}function Al(n){te.isInCheckNoChangesMode=n}function hs(){return te.lFrame.bindingIndex++}function ki(n){const t=te.lFrame,e=t.bindingIndex;return t.bindingIndex=t.bindingIndex+n,e}function PT(n,t){const e=te.lFrame;e.bindingIndex=e.bindingRootIndex=n,Gu(t)}function Gu(n){te.lFrame.currentDirectiveIndex=n}function Wu(n){const t=te.lFrame.currentDirectiveIndex;return-1===t?null:n[t]}function W_(){return te.lFrame.currentQueryIndex}function qu(n){te.lFrame.currentQueryIndex=n}function NT(n){const t=n[1];return 2===t.type?t.declTNode:1===t.type?n[6]:null}function q_(n,t,e){if(e&ee.SkipSelf){let r=t,s=n;for(;!(r=r.parent,null!==r||e&ee.Host||(r=NT(s),null===r||(s=s[15],10&r.type))););if(null===r)return!1;t=r,n=s}const i=te.lFrame=Y_();return i.currentTNode=t,i.lView=n,!0}function Il(n){const t=Y_(),e=n[1];te.lFrame=t,t.currentTNode=e.firstChild,t.lView=n,t.tView=e,t.contextLView=n,t.bindingIndex=e.bindingStartIndex,t.inI18n=!1}function Y_(){const n=te.lFrame,t=null===n?null:n.child;return null===t?Q_(n):t}function Q_(n){const t={currentTNode:null,isParent:!0,lView:null,tView:null,selectedIndex:-1,contextLView:null,elementDepthCount:0,currentNamespace:null,currentDirectiveIndex:-1,bindingRootIndex:-1,bindingIndex:-1,currentQueryIndex:0,parent:n,child:null,inI18n:!1};return null!==n&&(n.child=t),t}function K_(){const n=te.lFrame;return te.lFrame=n.parent,n.currentTNode=null,n.lView=null,n}const Z_=K_;function Rl(){const n=K_();n.isParent=!0,n.tView=null,n.selectedIndex=-1,n.contextLView=null,n.elementDepthCount=0,n.currentDirectiveIndex=-1,n.currentNamespace=null,n.bindingRootIndex=-1,n.bindingIndex=-1,n.currentQueryIndex=0}function jt(){return te.lFrame.selectedIndex}function Zi(n){te.lFrame.selectedIndex=n}function tt(){const n=te.lFrame;return Hu(n.tView,n.selectedIndex)}function Oo(){te.lFrame.currentNamespace=\"svg\"}function Ol(n,t){for(let e=t.directiveStart,i=t.directiveEnd;e<i;e++){const s=n.data[e].type.prototype,{ngAfterContentInit:o,ngAfterContentChecked:a,ngAfterViewInit:l,ngAfterViewChecked:c,ngOnDestroy:d}=s;o&&(n.contentHooks||(n.contentHooks=[])).push(-e,o),a&&((n.contentHooks||(n.contentHooks=[])).push(e,a),(n.contentCheckHooks||(n.contentCheckHooks=[])).push(e,a)),l&&(n.viewHooks||(n.viewHooks=[])).push(-e,l),c&&((n.viewHooks||(n.viewHooks=[])).push(e,c),(n.viewCheckHooks||(n.viewCheckHooks=[])).push(e,c)),null!=d&&(n.destroyHooks||(n.destroyHooks=[])).push(e,d)}}function Pl(n,t,e){J_(n,t,3,e)}function Fl(n,t,e,i){(3&n[2])===e&&J_(n,t,e,i)}function Yu(n,t){let e=n[2];(3&e)===t&&(e&=2047,e+=1,n[2]=e)}function J_(n,t,e,i){const s=null!=i?i:-1,o=t.length-1;let a=0;for(let l=void 0!==i?65535&n[18]:0;l<o;l++)if(\"number\"==typeof t[l+1]){if(a=t[l],null!=i&&a>=i)break}else t[l]<0&&(n[18]+=65536),(a<s||-1==s)&&(UT(n,e,t,l),n[18]=(4294901760&n[18])+l+2),l++}function UT(n,t,e,i){const r=e[i]<0,s=e[i+1],a=n[r?-e[i]:e[i]];if(r){if(n[2]>>11<n[18]>>16&&(3&n[2])===t){n[2]+=2048;try{s.call(a)}finally{}}}else try{s.call(a)}finally{}}class Po{constructor(t,e,i){this.factory=t,this.resolving=!1,this.canSeeViewProviders=e,this.injectImpl=i}}function Nl(n,t,e){const i=et(n);let r=0;for(;r<e.length;){const s=e[r];if(\"number\"==typeof s){if(0!==s)break;r++;const o=e[r++],a=e[r++],l=e[r++];i?n.setAttribute(t,a,l,o):t.setAttributeNS(o,a,l)}else{const o=s,a=e[++r];Ku(o)?i&&n.setProperty(t,o,a):i?n.setAttribute(t,o,a):t.setAttribute(o,a),r++}}return r}function ev(n){return 3===n||4===n||6===n}function Ku(n){return 64===n.charCodeAt(0)}function Ll(n,t){if(null!==t&&0!==t.length)if(null===n||0===n.length)n=t.slice();else{let e=-1;for(let i=0;i<t.length;i++){const r=t[i];\"number\"==typeof r?e=r:0===e||tv(n,e,r,null,-1===e||2===e?t[++i]:null)}}return n}function tv(n,t,e,i,r){let s=0,o=n.length;if(-1===t)o=-1;else for(;s<n.length;){const a=n[s++];if(\"number\"==typeof a){if(a===t){o=-1;break}if(a>t){o=s-1;break}}}for(;s<n.length;){const a=n[s];if(\"number\"==typeof a)break;if(a===e){if(null===i)return void(null!==r&&(n[s+1]=r));if(i===n[s+1])return void(n[s+2]=r)}s++,null!==i&&s++,null!==r&&s++}-1!==o&&(n.splice(o,0,t),s=o+1),n.splice(s++,0,e),null!==i&&n.splice(s++,0,i),null!==r&&n.splice(s++,0,r)}function nv(n){return-1!==n}function ps(n){return 32767&n}function fs(n,t){let e=function YT(n){return n>>16}(n),i=t;for(;e>0;)i=i[15],e--;return i}let Zu=!0;function Bl(n){const t=Zu;return Zu=n,t}let QT=0;function No(n,t){const e=Ju(n,t);if(-1!==e)return e;const i=t[1];i.firstCreatePass&&(n.injectorIndex=t.length,Xu(i.data,n),Xu(t,null),Xu(i.blueprint,null));const r=Vl(n,t),s=n.injectorIndex;if(nv(r)){const o=ps(r),a=fs(r,t),l=a[1].data;for(let c=0;c<8;c++)t[s+c]=a[o+c]|l[o+c]}return t[s+8]=r,s}function Xu(n,t){n.push(0,0,0,0,0,0,0,0,t)}function Ju(n,t){return-1===n.injectorIndex||n.parent&&n.parent.injectorIndex===n.injectorIndex||null===t[n.injectorIndex+8]?-1:n.injectorIndex}function Vl(n,t){if(n.parent&&-1!==n.parent.injectorIndex)return n.parent.injectorIndex;let e=0,i=null,r=t;for(;null!==r;){const s=r[1],o=s.type;if(i=2===o?s.declTNode:1===o?r[6]:null,null===i)return-1;if(e++,r=r[15],-1!==i.injectorIndex)return i.injectorIndex|e<<16}return-1}function Hl(n,t,e){!function KT(n,t,e){let i;\"string\"==typeof e?i=e.charCodeAt(0)||0:e.hasOwnProperty(ko)&&(i=e[ko]),null==i&&(i=e[ko]=QT++);const r=255&i;t.data[n+(r>>5)]|=1<<r}(n,t,e)}function sv(n,t,e){if(e&ee.Optional)return n;bl(t,\"NodeInjector\")}function ov(n,t,e,i){if(e&ee.Optional&&void 0===i&&(i=null),0==(e&(ee.Self|ee.Host))){const r=n[9],s=qi(void 0);try{return r?r.get(t,i,e&ee.Optional):T_(t,i,e&ee.Optional)}finally{qi(s)}}return sv(i,t,e)}function av(n,t,e,i=ee.Default,r){if(null!==n){const s=function eA(n){if(\"string\"==typeof n)return n.charCodeAt(0)||0;const t=n.hasOwnProperty(ko)?n[ko]:void 0;return\"number\"==typeof t?t>=0?255&t:XT:t}(e);if(\"function\"==typeof s){if(!q_(t,n,i))return i&ee.Host?sv(r,e,i):ov(t,e,i,r);try{const o=s(i);if(null!=o||i&ee.Optional)return o;bl(e)}finally{Z_()}}else if(\"number\"==typeof s){let o=null,a=Ju(n,t),l=-1,c=i&ee.Host?t[16][6]:null;for((-1===a||i&ee.SkipSelf)&&(l=-1===a?Vl(n,t):t[a+8],-1!==l&&dv(i,!1)?(o=t[1],a=ps(l),t=fs(l,t)):a=-1);-1!==a;){const d=t[1];if(cv(s,a,d.data)){const u=JT(a,t,e,o,i,c);if(u!==lv)return u}l=t[a+8],-1!==l&&dv(i,t[1].data[a+8]===c)&&cv(s,a,t)?(o=d,a=ps(l),t=fs(l,t)):a=-1}}}return ov(t,e,i,r)}const lv={};function XT(){return new ms(gt(),w())}function JT(n,t,e,i,r,s){const o=t[1],a=o.data[n+8],d=jl(a,o,e,null==i?El(a)&&Zu:i!=o&&0!=(3&a.type),r&ee.Host&&s===a);return null!==d?Lo(t,o,d,a):lv}function jl(n,t,e,i,r){const s=n.providerIndexes,o=t.data,a=1048575&s,l=n.directiveStart,d=s>>20,h=r?a+d:n.directiveEnd;for(let p=i?a:a+d;p<h;p++){const m=o[p];if(p<l&&e===m||p>=l&&m.type===e)return p}if(r){const p=o[l];if(p&&Hn(p)&&p.type===e)return l}return null}function Lo(n,t,e,i){let r=n[e];const s=t.data;if(function $T(n){return n instanceof Po}(r)){const o=r;o.resolving&&function Yk(n,t){const e=t?`. Dependency path: ${t.join(\" > \")} > ${n}`:\"\";throw new H(-200,`Circular dependency in DI detected for ${n}${e}`)}(Vt(s[e]));const a=Bl(o.canSeeViewProviders);o.resolving=!0;const l=o.injectImpl?qi(o.injectImpl):null;q_(n,i,ee.Default);try{r=n[e]=o.factory(void 0,s,n,i),t.firstCreatePass&&e>=i.directiveStart&&function zT(n,t,e){const{ngOnChanges:i,ngOnInit:r,ngDoCheck:s}=t.type.prototype;if(i){const o=N_(t);(e.preOrderHooks||(e.preOrderHooks=[])).push(n,o),(e.preOrderCheckHooks||(e.preOrderCheckHooks=[])).push(n,o)}r&&(e.preOrderHooks||(e.preOrderHooks=[])).push(0-n,r),s&&((e.preOrderHooks||(e.preOrderHooks=[])).push(n,s),(e.preOrderCheckHooks||(e.preOrderCheckHooks=[])).push(n,s))}(e,s[e],t)}finally{null!==l&&qi(l),Bl(a),o.resolving=!1,Z_()}}return r}function cv(n,t,e){return!!(e[t+(n>>5)]&1<<n)}function dv(n,t){return!(n&ee.Self||n&ee.Host&&t)}class ms{constructor(t,e){this._tNode=t,this._lView=e}get(t,e,i){return av(this._tNode,this._lView,t,i,e)}}function oe(n){return Yi(()=>{const t=n.prototype.constructor,e=t[Ei]||eh(t),i=Object.prototype;let r=Object.getPrototypeOf(n.prototype).constructor;for(;r&&r!==i;){const s=r[Ei]||eh(r);if(s&&s!==e)return s;r=Object.getPrototypeOf(r)}return s=>new s})}function eh(n){return x_(n)?()=>{const t=eh(le(n));return t&&t()}:Cr(n)}function kt(n){return function ZT(n,t){if(\"class\"===t)return n.classes;if(\"style\"===t)return n.styles;const e=n.attrs;if(e){const i=e.length;let r=0;for(;r<i;){const s=e[r];if(ev(s))break;if(0===s)r+=2;else if(\"number\"==typeof s)for(r++;r<i&&\"string\"==typeof e[r];)r++;else{if(s===t)return e[r+1];r+=2}}}return null}(gt(),n)}const _s=\"__parameters__\";function ys(n,t,e){return Yi(()=>{const i=function th(n){return function(...e){if(n){const i=n(...e);for(const r in i)this[r]=i[r]}}}(t);function r(...s){if(this instanceof r)return i.apply(this,s),this;const o=new r(...s);return a.annotation=o,a;function a(l,c,d){const u=l.hasOwnProperty(_s)?l[_s]:Object.defineProperty(l,_s,{value:[]})[_s];for(;u.length<=d;)u.push(null);return(u[d]=u[d]||[]).push(o),l}}return e&&(r.prototype=Object.create(e.prototype)),r.prototype.ngMetadataName=n,r.annotationCls=r,r})}class b{constructor(t,e){this._desc=t,this.ngMetadataName=\"InjectionToken\",this.\\u0275prov=void 0,\"number\"==typeof e?this.__NG_ELEMENT_ID__=e:void 0!==e&&(this.\\u0275prov=k({token:this,providedIn:e.providedIn||\"root\",factory:e.factory}))}toString(){return`InjectionToken ${this._desc}`}}const nA=new b(\"AnalyzeForEntryComponents\");function bn(n,t){void 0===t&&(t=n);for(let e=0;e<n.length;e++){let i=n[e];Array.isArray(i)?(t===n&&(t=n.slice(0,e)),bn(i,t)):t!==n&&t.push(i)}return t}function ai(n,t){n.forEach(e=>Array.isArray(e)?ai(e,t):t(e))}function hv(n,t,e){t>=n.length?n.push(e):n.splice(t,0,e)}function zl(n,t){return t>=n.length-1?n.pop():n.splice(t,1)[0]}function Ho(n,t){const e=[];for(let i=0;i<n;i++)e.push(t);return e}function sn(n,t,e){let i=bs(n,t);return i>=0?n[1|i]=e:(i=~i,function sA(n,t,e,i){let r=n.length;if(r==t)n.push(e,i);else if(1===r)n.push(i,n[0]),n[0]=e;else{for(r--,n.push(n[r-1],n[r]);r>t;)n[r]=n[r-2],r--;n[t]=e,n[t+1]=i}}(n,i,t,e)),i}function ih(n,t){const e=bs(n,t);if(e>=0)return n[1|e]}function bs(n,t){return function mv(n,t,e){let i=0,r=n.length>>e;for(;r!==i;){const s=i+(r-i>>1),o=n[s<<e];if(t===o)return s<<e;o>t?r=s:i=s+1}return~(r<<e)}(n,t,1)}const jo={},sh=\"__NG_DI_FLAG__\",$l=\"ngTempTokenPath\",hA=/\\n/gm,_v=\"__source\",fA=Fe({provide:String,useValue:Fe});let zo;function vv(n){const t=zo;return zo=n,t}function mA(n,t=ee.Default){if(void 0===zo)throw new H(203,\"\");return null===zo?T_(n,void 0,t):zo.get(n,t&ee.Optional?null:void 0,t)}function y(n,t=ee.Default){return(function tT(){return ku}()||mA)(le(n),t)}const Uo=y;function oh(n){const t=[];for(let e=0;e<n.length;e++){const i=le(n[e]);if(Array.isArray(i)){if(0===i.length)throw new H(900,\"\");let r,s=ee.Default;for(let o=0;o<i.length;o++){const a=i[o],l=gA(a);\"number\"==typeof l?-1===l?r=a.token:s|=l:r=a}t.push(y(r,s))}else t.push(y(i))}return t}function $o(n,t){return n[sh]=t,n.prototype[sh]=t,n}function gA(n){return n[sh]}const Gl=$o(ys(\"Inject\",n=>({token:n})),-1),Tt=$o(ys(\"Optional\"),8),Cn=$o(ys(\"SkipSelf\"),4);function on(n){return n instanceof class wr{constructor(t){this.changingThisBreaksApplicationSecurity=t}toString(){return`SafeValue must use [property]=binding: ${this.changingThisBreaksApplicationSecurity} (see https://g.co/ng/security#xss)`}}?n.changingThisBreaksApplicationSecurity:n}const Bv=\"__ngContext__\";function Ft(n,t){n[Bv]=t}function gh(n){const t=function Qo(n){return n[Bv]||null}(n);return t?Array.isArray(t)?t:t.lView:null}function vh(n){return n.ngOriginalError}function uI(n,...t){n.error(...t)}class Mr{constructor(){this._console=console}handleError(t){const e=this._findOriginalError(t),i=function dI(n){return n&&n.ngErrorLogger||uI}(t);i(this._console,\"ERROR\",t),e&&i(this._console,\"ORIGINAL ERROR\",e)}_findOriginalError(t){let e=t&&vh(t);for(;e&&vh(e);)e=vh(e);return e||null}}const CI=(()=>(\"undefined\"!=typeof requestAnimationFrame&&requestAnimationFrame||setTimeout).bind(Oe))();function Uv(n){return n.ownerDocument.defaultView}function di(n){return n instanceof Function?n():n}var an=(()=>((an=an||{})[an.Important=1]=\"Important\",an[an.DashCase=2]=\"DashCase\",an))();function bh(n,t){return undefined(n,t)}function Ko(n){const t=n[3];return Vn(t)?t[3]:t}function Ch(n){return Yv(n[13])}function Dh(n){return Yv(n[4])}function Yv(n){for(;null!==n&&!Vn(n);)n=n[4];return n}function Ms(n,t,e,i,r){if(null!=i){let s,o=!1;Vn(i)?s=i:si(i)&&(o=!0,i=i[0]);const a=ct(i);0===n&&null!==e?null==r?ey(t,e,a):xr(t,e,a,r||null,!0):1===n&&null!==e?xr(t,e,a,r||null,!0):2===n?function ay(n,t,e){const i=Kl(n,t);i&&function PI(n,t,e,i){et(n)?n.removeChild(t,e,i):t.removeChild(e)}(n,i,t,e)}(t,a,o):3===n&&t.destroyNode(a),null!=s&&function LI(n,t,e,i,r){const s=e[7];s!==ct(e)&&Ms(t,n,i,s,r);for(let a=10;a<e.length;a++){const l=e[a];Zo(l[1],l,n,t,i,s)}}(t,n,s,e,r)}}function Mh(n,t,e){if(et(n))return n.createElement(t,e);{const i=null!==e?function CT(n){const t=n.toLowerCase();return\"svg\"===t?\"http://www.w3.org/2000/svg\":\"math\"===t?\"http://www.w3.org/1998/MathML/\":null}(e):null;return null===i?n.createElement(t):n.createElementNS(i,t)}}function Kv(n,t){const e=n[9],i=e.indexOf(t),r=t[3];1024&t[2]&&(t[2]&=-1025,zu(r,-1)),e.splice(i,1)}function xh(n,t){if(n.length<=10)return;const e=10+t,i=n[e];if(i){const r=i[17];null!==r&&r!==n&&Kv(r,i),t>0&&(n[e-1][4]=i[4]);const s=zl(n,10+t);!function EI(n,t){Zo(n,t,t[11],2,null,null),t[0]=null,t[6]=null}(i[1],i);const o=s[19];null!==o&&o.detachView(s[1]),i[3]=null,i[4]=null,i[2]&=-129}return i}function Zv(n,t){if(!(256&t[2])){const e=t[11];et(e)&&e.destroyNode&&Zo(n,t,e,3,null,null),function TI(n){let t=n[13];if(!t)return Eh(n[1],n);for(;t;){let e=null;if(si(t))e=t[13];else{const i=t[10];i&&(e=i)}if(!e){for(;t&&!t[4]&&t!==n;)si(t)&&Eh(t[1],t),t=t[3];null===t&&(t=n),si(t)&&Eh(t[1],t),e=t&&t[4]}t=e}}(t)}}function Eh(n,t){if(!(256&t[2])){t[2]&=-129,t[2]|=256,function OI(n,t){let e;if(null!=n&&null!=(e=n.destroyHooks))for(let i=0;i<e.length;i+=2){const r=t[e[i]];if(!(r instanceof Po)){const s=e[i+1];if(Array.isArray(s))for(let o=0;o<s.length;o+=2){const a=r[s[o]],l=s[o+1];try{l.call(a)}finally{}}else try{s.call(r)}finally{}}}}(n,t),function RI(n,t){const e=n.cleanup,i=t[7];let r=-1;if(null!==e)for(let s=0;s<e.length-1;s+=2)if(\"string\"==typeof e[s]){const o=e[s+1],a=\"function\"==typeof o?o(t):ct(t[o]),l=i[r=e[s+2]],c=e[s+3];\"boolean\"==typeof c?a.removeEventListener(e[s],l,c):c>=0?i[r=c]():i[r=-c].unsubscribe(),s+=2}else{const o=i[r=e[s+1]];e[s].call(o)}if(null!==i){for(let s=r+1;s<i.length;s++)i[s]();t[7]=null}}(n,t),1===t[1].type&&et(t[11])&&t[11].destroy();const e=t[17];if(null!==e&&Vn(t[3])){e!==t[3]&&Kv(e,t);const i=t[19];null!==i&&i.detachView(n)}}}function Xv(n,t,e){return function Jv(n,t,e){let i=t;for(;null!==i&&40&i.type;)i=(t=i).parent;if(null===i)return e[0];if(2&i.flags){const r=n.data[i.directiveStart].encapsulation;if(r===Ln.None||r===Ln.Emulated)return null}return yn(i,e)}(n,t.parent,e)}function xr(n,t,e,i,r){et(n)?n.insertBefore(t,e,i,r):t.insertBefore(e,i,r)}function ey(n,t,e){et(n)?n.appendChild(t,e):t.appendChild(e)}function ty(n,t,e,i,r){null!==i?xr(n,t,e,i,r):ey(n,t,e)}function Kl(n,t){return et(n)?n.parentNode(t):t.parentNode}function ny(n,t,e){return ry(n,t,e)}let ry=function iy(n,t,e){return 40&n.type?yn(n,e):null};function Zl(n,t,e,i){const r=Xv(n,i,t),s=t[11],a=ny(i.parent||t[6],i,t);if(null!=r)if(Array.isArray(e))for(let l=0;l<e.length;l++)ty(s,r,e[l],a,!1);else ty(s,r,e,a,!1)}function Xl(n,t){if(null!==t){const e=t.type;if(3&e)return yn(t,n);if(4&e)return kh(-1,n[t.index]);if(8&e){const i=t.child;if(null!==i)return Xl(n,i);{const r=n[t.index];return Vn(r)?kh(-1,r):ct(r)}}if(32&e)return bh(t,n)()||ct(n[t.index]);{const i=oy(n,t);return null!==i?Array.isArray(i)?i[0]:Xl(Ko(n[16]),i):Xl(n,t.next)}}return null}function oy(n,t){return null!==t?n[16][6].projection[t.projection]:null}function kh(n,t){const e=10+n+1;if(e<t.length){const i=t[e],r=i[1].firstChild;if(null!==r)return Xl(i,r)}return t[7]}function Th(n,t,e,i,r,s,o){for(;null!=e;){const a=i[e.index],l=e.type;if(o&&0===t&&(a&&Ft(ct(a),i),e.flags|=4),64!=(64&e.flags))if(8&l)Th(n,t,e.child,i,r,s,!1),Ms(t,n,r,a,s);else if(32&l){const c=bh(e,i);let d;for(;d=c();)Ms(t,n,r,d,s);Ms(t,n,r,a,s)}else 16&l?ly(n,t,i,e,r,s):Ms(t,n,r,a,s);e=o?e.projectionNext:e.next}}function Zo(n,t,e,i,r,s){Th(e,i,n.firstChild,t,r,s,!1)}function ly(n,t,e,i,r,s){const o=e[16],l=o[6].projection[i.projection];if(Array.isArray(l))for(let c=0;c<l.length;c++)Ms(t,n,r,l[c],s);else Th(n,t,l,o[3],r,s,!0)}function cy(n,t,e){et(n)?n.setAttribute(t,\"style\",e):t.style.cssText=e}function Ah(n,t,e){et(n)?\"\"===e?n.removeAttribute(t,\"class\"):n.setAttribute(t,\"class\",e):t.className=e}function dy(n,t,e){let i=n.length;for(;;){const r=n.indexOf(t,e);if(-1===r)return r;if(0===r||n.charCodeAt(r-1)<=32){const s=t.length;if(r+s===i||n.charCodeAt(r+s)<=32)return r}e=r+1}}const uy=\"ng-template\";function VI(n,t,e){let i=0;for(;i<n.length;){let r=n[i++];if(e&&\"class\"===r){if(r=n[i],-1!==dy(r.toLowerCase(),t,0))return!0}else if(1===r){for(;i<n.length&&\"string\"==typeof(r=n[i++]);)if(r.toLowerCase()===t)return!0;return!1}}return!1}function hy(n){return 4===n.type&&n.value!==uy}function HI(n,t,e){return t===(4!==n.type||e?n.value:uy)}function jI(n,t,e){let i=4;const r=n.attrs||[],s=function $I(n){for(let t=0;t<n.length;t++)if(ev(n[t]))return t;return n.length}(r);let o=!1;for(let a=0;a<t.length;a++){const l=t[a];if(\"number\"!=typeof l){if(!o)if(4&i){if(i=2|1&i,\"\"!==l&&!HI(n,l,e)||\"\"===l&&1===t.length){if(jn(i))return!1;o=!0}}else{const c=8&i?l:t[++a];if(8&i&&null!==n.attrs){if(!VI(n.attrs,c,e)){if(jn(i))return!1;o=!0}continue}const u=zI(8&i?\"class\":l,r,hy(n),e);if(-1===u){if(jn(i))return!1;o=!0;continue}if(\"\"!==c){let h;h=u>s?\"\":r[u+1].toLowerCase();const p=8&i?h:null;if(p&&-1!==dy(p,c,0)||2&i&&c!==h){if(jn(i))return!1;o=!0}}}}else{if(!o&&!jn(i)&&!jn(l))return!1;if(o&&jn(l))continue;o=!1,i=l|1&i}}return jn(i)||o}function jn(n){return 0==(1&n)}function zI(n,t,e,i){if(null===t)return-1;let r=0;if(i||!e){let s=!1;for(;r<t.length;){const o=t[r];if(o===n)return r;if(3===o||6===o)s=!0;else{if(1===o||2===o){let a=t[++r];for(;\"string\"==typeof a;)a=t[++r];continue}if(4===o)break;if(0===o){r+=4;continue}}r+=s?1:2}return-1}return function GI(n,t){let e=n.indexOf(4);if(e>-1)for(e++;e<n.length;){const i=n[e];if(\"number\"==typeof i)return-1;if(i===t)return e;e++}return-1}(t,n)}function py(n,t,e=!1){for(let i=0;i<t.length;i++)if(jI(n,t[i],e))return!0;return!1}function WI(n,t){e:for(let e=0;e<t.length;e++){const i=t[e];if(n.length===i.length){for(let r=0;r<n.length;r++)if(n[r]!==i[r])continue e;return!0}}return!1}function fy(n,t){return n?\":not(\"+t.trim()+\")\":t}function qI(n){let t=n[0],e=1,i=2,r=\"\",s=!1;for(;e<n.length;){let o=n[e];if(\"string\"==typeof o)if(2&i){const a=n[++e];r+=\"[\"+o+(a.length>0?'=\"'+a+'\"':\"\")+\"]\"}else 8&i?r+=\".\"+o:4&i&&(r+=\" \"+o);else\"\"!==r&&!jn(o)&&(t+=fy(s,r),r=\"\"),i=o,s=s||!jn(i);e++}return\"\"!==r&&(t+=fy(s,r)),t}const se={};function T(n){my(Me(),w(),jt()+n,Tl())}function my(n,t,e,i){if(!i)if(3==(3&t[2])){const s=n.preOrderCheckHooks;null!==s&&Pl(t,s,e)}else{const s=n.preOrderHooks;null!==s&&Fl(t,s,0,e)}Zi(e)}function Jl(n,t){return n<<17|t<<2}function zn(n){return n>>17&32767}function Ih(n){return 2|n}function Ti(n){return(131068&n)>>2}function Rh(n,t){return-131069&n|t<<2}function Oh(n){return 1|n}function Ey(n,t){const e=n.contentQueries;if(null!==e)for(let i=0;i<e.length;i+=2){const r=e[i],s=e[i+1];if(-1!==s){const o=n.data[s];qu(r),o.contentQueries(2,t[s],s)}}}function Xo(n,t,e,i,r,s,o,a,l,c){const d=t.blueprint.slice();return d[0]=r,d[2]=140|i,j_(d),d[3]=d[15]=n,d[8]=e,d[10]=o||n&&n[10],d[11]=a||n&&n[11],d[12]=l||n&&n[12]||null,d[9]=c||n&&n[9]||null,d[6]=s,d[16]=2==t.type?n[16]:d,d}function xs(n,t,e,i,r){let s=n.data[t];if(null===s)s=function zh(n,t,e,i,r){const s=U_(),o=Uu(),l=n.data[t]=function uR(n,t,e,i,r,s){return{type:e,index:i,insertBeforeIndex:null,injectorIndex:t?t.injectorIndex:-1,directiveStart:-1,directiveEnd:-1,directiveStylingLast:-1,propertyBindings:null,flags:0,providerIndexes:0,value:r,attrs:s,mergedAttrs:null,localNames:null,initialInputs:void 0,inputs:null,outputs:null,tViews:null,next:null,projectionNext:null,child:null,parent:t,projection:null,styles:null,stylesWithoutHost:null,residualStyles:void 0,classes:null,classesWithoutHost:null,residualClasses:void 0,classBindings:0,styleBindings:0}}(0,o?s:s&&s.parent,e,t,i,r);return null===n.firstChild&&(n.firstChild=l),null!==s&&(o?null==s.child&&null!==l.parent&&(s.child=l):null===s.next&&(s.next=l)),l}(n,t,e,i,r),function OT(){return te.lFrame.inI18n}()&&(s.flags|=64);else if(64&s.type){s.type=e,s.value=i,s.attrs=r;const o=function Ro(){const n=te.lFrame,t=n.currentTNode;return n.isParent?t:t.parent}();s.injectorIndex=null===o?-1:o.injectorIndex}return oi(s,!0),s}function Es(n,t,e,i){if(0===e)return-1;const r=t.length;for(let s=0;s<e;s++)t.push(i),n.blueprint.push(i),n.data.push(null);return r}function Jo(n,t,e){Il(t);try{const i=n.viewQuery;null!==i&&Zh(1,i,e);const r=n.template;null!==r&&Sy(n,t,r,1,e),n.firstCreatePass&&(n.firstCreatePass=!1),n.staticContentQueries&&Ey(n,t),n.staticViewQueries&&Zh(2,n.viewQuery,e);const s=n.components;null!==s&&function lR(n,t){for(let e=0;e<t.length;e++)TR(n,t[e])}(t,s)}catch(i){throw n.firstCreatePass&&(n.incompleteFirstPass=!0,n.firstCreatePass=!1),i}finally{t[2]&=-5,Rl()}}function Ss(n,t,e,i){const r=t[2];if(256==(256&r))return;Il(t);const s=Tl();try{j_(t),function $_(n){return te.lFrame.bindingIndex=n}(n.bindingStartIndex),null!==e&&Sy(n,t,e,2,i);const o=3==(3&r);if(!s)if(o){const c=n.preOrderCheckHooks;null!==c&&Pl(t,c,null)}else{const c=n.preOrderHooks;null!==c&&Fl(t,c,0,null),Yu(t,0)}if(function SR(n){for(let t=Ch(n);null!==t;t=Dh(t)){if(!t[2])continue;const e=t[9];for(let i=0;i<e.length;i++){const r=e[i],s=r[3];0==(1024&r[2])&&zu(s,1),r[2]|=1024}}}(t),function ER(n){for(let t=Ch(n);null!==t;t=Dh(t))for(let e=10;e<t.length;e++){const i=t[e],r=i[1];ju(i)&&Ss(r,i,r.template,i[8])}}(t),null!==n.contentQueries&&Ey(n,t),!s)if(o){const c=n.contentCheckHooks;null!==c&&Pl(t,c)}else{const c=n.contentHooks;null!==c&&Fl(t,c,1),Yu(t,1)}!function oR(n,t){const e=n.hostBindingOpCodes;if(null!==e)try{for(let i=0;i<e.length;i++){const r=e[i];if(r<0)Zi(~r);else{const s=r,o=e[++i],a=e[++i];PT(o,s),a(2,t[s])}}}finally{Zi(-1)}}(n,t);const a=n.components;null!==a&&function aR(n,t){for(let e=0;e<t.length;e++)kR(n,t[e])}(t,a);const l=n.viewQuery;if(null!==l&&Zh(2,l,i),!s)if(o){const c=n.viewCheckHooks;null!==c&&Pl(t,c)}else{const c=n.viewHooks;null!==c&&Fl(t,c,2),Yu(t,2)}!0===n.firstUpdatePass&&(n.firstUpdatePass=!1),s||(t[2]&=-73),1024&t[2]&&(t[2]&=-1025,zu(t[3],-1))}finally{Rl()}}function cR(n,t,e,i){const r=t[10],s=!Tl(),o=H_(t);try{s&&!o&&r.begin&&r.begin(),o&&Jo(n,t,i),Ss(n,t,e,i)}finally{s&&!o&&r.end&&r.end()}}function Sy(n,t,e,i,r){const s=jt(),o=2&i;try{Zi(-1),o&&t.length>20&&my(n,t,20,Tl()),e(i,r)}finally{Zi(s)}}function ky(n,t,e){if(Ou(t)){const r=t.directiveEnd;for(let s=t.directiveStart;s<r;s++){const o=n.data[s];o.contentQueries&&o.contentQueries(1,e[s],s)}}}function Uh(n,t,e){!z_()||(function vR(n,t,e,i){const r=e.directiveStart,s=e.directiveEnd;n.firstCreatePass||No(e,t),Ft(i,t);const o=e.initialInputs;for(let a=r;a<s;a++){const l=n.data[a],c=Hn(l);c&&wR(t,e,l);const d=Lo(t,n,a,e);Ft(d,t),null!==o&&MR(0,a-r,d,l,0,o),c&&(rn(e.index,t)[8]=d)}}(n,t,e,yn(e,t)),128==(128&e.flags)&&function yR(n,t,e){const i=e.directiveStart,r=e.directiveEnd,o=e.index,a=function FT(){return te.lFrame.currentDirectiveIndex}();try{Zi(o);for(let l=i;l<r;l++){const c=n.data[l],d=t[l];Gu(l),(null!==c.hostBindings||0!==c.hostVars||null!==c.hostAttrs)&&Ny(c,d)}}finally{Zi(-1),Gu(a)}}(n,t,e))}function $h(n,t,e=yn){const i=t.localNames;if(null!==i){let r=t.index+1;for(let s=0;s<i.length;s+=2){const o=i[s+1],a=-1===o?e(t,n):n[o];n[r++]=a}}}function Ty(n){const t=n.tView;return null===t||t.incompleteFirstPass?n.tView=nc(1,null,n.template,n.decls,n.vars,n.directiveDefs,n.pipeDefs,n.viewQuery,n.schemas,n.consts):t}function nc(n,t,e,i,r,s,o,a,l,c){const d=20+i,u=d+r,h=function dR(n,t){const e=[];for(let i=0;i<t;i++)e.push(i<n?null:se);return e}(d,u),p=\"function\"==typeof c?c():c;return h[1]={type:n,blueprint:h,template:e,queries:null,viewQuery:a,declTNode:t,data:h.slice().fill(null,d),bindingStartIndex:d,expandoStartIndex:u,hostBindingOpCodes:null,firstCreatePass:!0,firstUpdatePass:!0,staticViewQueries:!1,staticContentQueries:!1,preOrderHooks:null,preOrderCheckHooks:null,contentHooks:null,contentCheckHooks:null,viewHooks:null,viewCheckHooks:null,destroyHooks:null,cleanup:null,contentQueries:null,components:null,directiveRegistry:\"function\"==typeof s?s():s,pipeRegistry:\"function\"==typeof o?o():o,firstChild:null,schemas:l,consts:p,incompleteFirstPass:!1}}function Ry(n,t,e,i){const r=zy(t);null===e?r.push(i):(r.push(e),n.firstCreatePass&&Uy(n).push(i,r.length-1))}function Oy(n,t,e){for(let i in n)if(n.hasOwnProperty(i)){const r=n[i];(e=null===e?{}:e).hasOwnProperty(i)?e[i].push(t,r):e[i]=[t,r]}return e}function ln(n,t,e,i,r,s,o,a){const l=yn(t,e);let d,c=t.inputs;!a&&null!=c&&(d=c[i])?(Wy(n,e,d,i,r),El(t)&&function fR(n,t){const e=rn(t,n);16&e[2]||(e[2]|=64)}(e,t.index)):3&t.type&&(i=function pR(n){return\"class\"===n?\"className\":\"for\"===n?\"htmlFor\":\"formaction\"===n?\"formAction\":\"innerHtml\"===n?\"innerHTML\":\"readonly\"===n?\"readOnly\":\"tabindex\"===n?\"tabIndex\":n}(i),r=null!=o?o(r,t.value||\"\",i):r,et(s)?s.setProperty(l,i,r):Ku(i)||(l.setProperty?l.setProperty(i,r):l[i]=r))}function Gh(n,t,e,i){let r=!1;if(z_()){const s=function bR(n,t,e){const i=n.directiveRegistry;let r=null;if(i)for(let s=0;s<i.length;s++){const o=i[s];py(e,o.selectors,!1)&&(r||(r=[]),Hl(No(e,t),n,o.type),Hn(o)?(Ly(n,e),r.unshift(o)):r.push(o))}return r}(n,t,e),o=null===i?null:{\"\":-1};if(null!==s){r=!0,By(e,n.data.length,s.length);for(let d=0;d<s.length;d++){const u=s[d];u.providersResolver&&u.providersResolver(u)}let a=!1,l=!1,c=Es(n,t,s.length,null);for(let d=0;d<s.length;d++){const u=s[d];e.mergedAttrs=Ll(e.mergedAttrs,u.hostAttrs),Vy(n,e,t,c,u),DR(c,u,o),null!==u.contentQueries&&(e.flags|=8),(null!==u.hostBindings||null!==u.hostAttrs||0!==u.hostVars)&&(e.flags|=128);const h=u.type.prototype;!a&&(h.ngOnChanges||h.ngOnInit||h.ngDoCheck)&&((n.preOrderHooks||(n.preOrderHooks=[])).push(e.index),a=!0),!l&&(h.ngOnChanges||h.ngDoCheck)&&((n.preOrderCheckHooks||(n.preOrderCheckHooks=[])).push(e.index),l=!0),c++}!function hR(n,t){const i=t.directiveEnd,r=n.data,s=t.attrs,o=[];let a=null,l=null;for(let c=t.directiveStart;c<i;c++){const d=r[c],u=d.inputs,h=null===s||hy(t)?null:xR(u,s);o.push(h),a=Oy(u,c,a),l=Oy(d.outputs,c,l)}null!==a&&(a.hasOwnProperty(\"class\")&&(t.flags|=16),a.hasOwnProperty(\"style\")&&(t.flags|=32)),t.initialInputs=o,t.inputs=a,t.outputs=l}(n,e)}o&&function CR(n,t,e){if(t){const i=n.localNames=[];for(let r=0;r<t.length;r+=2){const s=e[t[r+1]];if(null==s)throw new H(-301,!1);i.push(t[r],s)}}}(e,i,o)}return e.mergedAttrs=Ll(e.mergedAttrs,e.attrs),r}function Fy(n,t,e,i,r,s){const o=s.hostBindings;if(o){let a=n.hostBindingOpCodes;null===a&&(a=n.hostBindingOpCodes=[]);const l=~t.index;(function _R(n){let t=n.length;for(;t>0;){const e=n[--t];if(\"number\"==typeof e&&e<0)return e}return 0})(a)!=l&&a.push(l),a.push(i,r,o)}}function Ny(n,t){null!==n.hostBindings&&n.hostBindings(1,t)}function Ly(n,t){t.flags|=2,(n.components||(n.components=[])).push(t.index)}function DR(n,t,e){if(e){if(t.exportAs)for(let i=0;i<t.exportAs.length;i++)e[t.exportAs[i]]=n;Hn(t)&&(e[\"\"]=n)}}function By(n,t,e){n.flags|=1,n.directiveStart=t,n.directiveEnd=t+e,n.providerIndexes=t}function Vy(n,t,e,i,r){n.data[i]=r;const s=r.factory||(r.factory=Cr(r.type)),o=new Po(s,Hn(r),null);n.blueprint[i]=o,e[i]=o,Fy(n,t,0,i,Es(n,e,r.hostVars,se),r)}function wR(n,t,e){const i=yn(t,n),r=Ty(e),s=n[10],o=ic(n,Xo(n,r,null,e.onPush?64:16,i,t,s,s.createRenderer(i,e),null,null));n[t.index]=o}function ui(n,t,e,i,r,s){const o=yn(n,t);!function Wh(n,t,e,i,r,s,o){if(null==s)et(n)?n.removeAttribute(t,r,e):t.removeAttribute(r);else{const a=null==o?re(s):o(s,i||\"\",r);et(n)?n.setAttribute(t,r,a,e):e?t.setAttributeNS(e,r,a):t.setAttribute(r,a)}}(t[11],o,s,n.value,e,i,r)}function MR(n,t,e,i,r,s){const o=s[t];if(null!==o){const a=i.setInput;for(let l=0;l<o.length;){const c=o[l++],d=o[l++],u=o[l++];null!==a?i.setInput(e,u,c,d):e[d]=u}}}function xR(n,t){let e=null,i=0;for(;i<t.length;){const r=t[i];if(0!==r)if(5!==r){if(\"number\"==typeof r)break;n.hasOwnProperty(r)&&(null===e&&(e=[]),e.push(r,n[r],t[i+1])),i+=2}else i+=2;else i+=4}return e}function Hy(n,t,e,i){return new Array(n,!0,!1,t,null,0,i,e,null,null)}function kR(n,t){const e=rn(t,n);if(ju(e)){const i=e[1];80&e[2]?Ss(i,e,i.template,e[8]):e[5]>0&&qh(e)}}function qh(n){for(let i=Ch(n);null!==i;i=Dh(i))for(let r=10;r<i.length;r++){const s=i[r];if(1024&s[2]){const o=s[1];Ss(o,s,o.template,s[8])}else s[5]>0&&qh(s)}const e=n[1].components;if(null!==e)for(let i=0;i<e.length;i++){const r=rn(e[i],n);ju(r)&&r[5]>0&&qh(r)}}function TR(n,t){const e=rn(t,n),i=e[1];(function AR(n,t){for(let e=t.length;e<n.blueprint.length;e++)t.push(n.blueprint[e])})(i,e),Jo(i,e,e[8])}function ic(n,t){return n[13]?n[14][4]=t:n[13]=t,n[14]=t,t}function Yh(n){for(;n;){n[2]|=64;const t=Ko(n);if(uT(n)&&!t)return n;n=t}return null}function Kh(n,t,e){const i=t[10];i.begin&&i.begin();try{Ss(n,t,n.template,e)}catch(r){throw Gy(t,r),r}finally{i.end&&i.end()}}function jy(n){!function Qh(n){for(let t=0;t<n.components.length;t++){const e=n.components[t],i=gh(e),r=i[1];cR(r,i,r.template,e)}}(n[8])}function Zh(n,t,e){qu(0),t(n,e)}const PR=(()=>Promise.resolve(null))();function zy(n){return n[7]||(n[7]=[])}function Uy(n){return n.cleanup||(n.cleanup=[])}function $y(n,t,e){return(null===n||Hn(n))&&(e=function MT(n){for(;Array.isArray(n);){if(\"object\"==typeof n[1])return n;n=n[0]}return null}(e[t.index])),e[11]}function Gy(n,t){const e=n[9],i=e?e.get(Mr,null):null;i&&i.handleError(t)}function Wy(n,t,e,i,r){for(let s=0;s<e.length;){const o=e[s++],a=e[s++],l=t[o],c=n.data[o];null!==c.setInput?c.setInput(l,r,i,a):l[a]=r}}function Ai(n,t,e){const i=kl(t,n);!function Qv(n,t,e){et(n)?n.setValue(t,e):t.textContent=e}(n[11],i,e)}function rc(n,t,e){let i=e?n.styles:null,r=e?n.classes:null,s=0;if(null!==t)for(let o=0;o<t.length;o++){const a=t[o];\"number\"==typeof a?s=a:1==s?r=Mu(r,a):2==s&&(i=Mu(i,a+\": \"+t[++o]+\";\"))}e?n.styles=i:n.stylesWithoutHost=i,e?n.classes=r:n.classesWithoutHost=r}const Xh=new b(\"INJECTOR\",-1);class qy{get(t,e=jo){if(e===jo){const i=new Error(`NullInjectorError: No provider for ${Re(t)}!`);throw i.name=\"NullInjectorError\",i}return e}}const Jh=new b(\"Set Injector scope.\"),ea={},LR={};let ep;function Yy(){return void 0===ep&&(ep=new qy),ep}function Qy(n,t=null,e=null,i){const r=Ky(n,t,e,i);return r._resolveInjectorDefTypes(),r}function Ky(n,t=null,e=null,i){return new BR(n,e,t||Yy(),i)}class BR{constructor(t,e,i,r=null){this.parent=i,this.records=new Map,this.injectorDefTypes=new Set,this.onDestroy=new Set,this._destroyed=!1;const s=[];e&&ai(e,a=>this.processProvider(a,t,e)),ai([t],a=>this.processInjectorType(a,[],s)),this.records.set(Xh,ks(void 0,this));const o=this.records.get(Jh);this.scope=null!=o?o.value:null,this.source=r||(\"object\"==typeof t?null:Re(t))}get destroyed(){return this._destroyed}destroy(){this.assertNotDestroyed(),this._destroyed=!0;try{this.onDestroy.forEach(t=>t.ngOnDestroy())}finally{this.records.clear(),this.onDestroy.clear(),this.injectorDefTypes.clear()}}get(t,e=jo,i=ee.Default){this.assertNotDestroyed();const r=vv(this),s=qi(void 0);try{if(!(i&ee.SkipSelf)){let a=this.records.get(t);if(void 0===a){const l=function WR(n){return\"function\"==typeof n||\"object\"==typeof n&&n instanceof b}(t)&&Eu(t);a=l&&this.injectableDefInScope(l)?ks(tp(t),ea):null,this.records.set(t,a)}if(null!=a)return this.hydrate(t,a)}return(i&ee.Self?Yy():this.parent).get(t,e=i&ee.Optional&&e===jo?null:e)}catch(o){if(\"NullInjectorError\"===o.name){if((o[$l]=o[$l]||[]).unshift(Re(t)),r)throw o;return function _A(n,t,e,i){const r=n[$l];throw t[_v]&&r.unshift(t[_v]),n.message=function vA(n,t,e,i=null){n=n&&\"\\n\"===n.charAt(0)&&\"\\u0275\"==n.charAt(1)?n.substr(2):n;let r=Re(t);if(Array.isArray(t))r=t.map(Re).join(\" -> \");else if(\"object\"==typeof t){let s=[];for(let o in t)if(t.hasOwnProperty(o)){let a=t[o];s.push(o+\":\"+(\"string\"==typeof a?JSON.stringify(a):Re(a)))}r=`{${s.join(\", \")}}`}return`${e}${i?\"(\"+i+\")\":\"\"}[${r}]: ${n.replace(hA,\"\\n \")}`}(\"\\n\"+n.message,r,e,i),n.ngTokenPath=r,n[$l]=null,n}(o,t,\"R3InjectorError\",this.source)}throw o}finally{qi(s),vv(r)}}_resolveInjectorDefTypes(){this.injectorDefTypes.forEach(t=>this.get(t))}toString(){const t=[];return this.records.forEach((i,r)=>t.push(Re(r))),`R3Injector[${t.join(\", \")}]`}assertNotDestroyed(){if(this._destroyed)throw new H(205,!1)}processInjectorType(t,e,i){if(!(t=le(t)))return!1;let r=S_(t);const s=null==r&&t.ngModule||void 0,o=void 0===s?t:s,a=-1!==i.indexOf(o);if(void 0!==s&&(r=S_(s)),null==r)return!1;if(null!=r.imports&&!a){let d;i.push(o);try{ai(r.imports,u=>{this.processInjectorType(u,e,i)&&(void 0===d&&(d=[]),d.push(u))})}finally{}if(void 0!==d)for(let u=0;u<d.length;u++){const{ngModule:h,providers:p}=d[u];ai(p,m=>this.processProvider(m,h,p||Ne))}}this.injectorDefTypes.add(o);const l=Cr(o)||(()=>new o);this.records.set(o,ks(l,ea));const c=r.providers;if(null!=c&&!a){const d=t;ai(c,u=>this.processProvider(u,d,c))}return void 0!==s&&void 0!==t.providers}processProvider(t,e,i){let r=Ts(t=le(t))?t:le(t&&t.provide);const s=function HR(n,t,e){return Xy(n)?ks(void 0,n.useValue):ks(Zy(n),ea)}(t);if(Ts(t)||!0!==t.multi)this.records.get(r);else{let o=this.records.get(r);o||(o=ks(void 0,ea,!0),o.factory=()=>oh(o.multi),this.records.set(r,o)),r=t,o.multi.push(t)}this.records.set(r,s)}hydrate(t,e){return e.value===ea&&(e.value=LR,e.value=e.factory()),\"object\"==typeof e.value&&e.value&&function GR(n){return null!==n&&\"object\"==typeof n&&\"function\"==typeof n.ngOnDestroy}(e.value)&&this.onDestroy.add(e.value),e.value}injectableDefInScope(t){if(!t.providedIn)return!1;const e=le(t.providedIn);return\"string\"==typeof e?\"any\"===e||e===this.scope:this.injectorDefTypes.has(e)}}function tp(n){const t=Eu(n),e=null!==t?t.factory:Cr(n);if(null!==e)return e;if(n instanceof b)throw new H(204,!1);if(n instanceof Function)return function VR(n){const t=n.length;if(t>0)throw Ho(t,\"?\"),new H(204,!1);const e=function Xk(n){const t=n&&(n[Cl]||n[k_]);if(t){const e=function Jk(n){if(n.hasOwnProperty(\"name\"))return n.name;const t=(\"\"+n).match(/^function\\s*([^\\s(]+)/);return null===t?\"\":t[1]}(n);return console.warn(`DEPRECATED: DI is instantiating a token \"${e}\" that inherits its @Injectable decorator but does not provide one itself.\\nThis will become an error in a future version of Angular. Please add @Injectable() to the \"${e}\" class.`),t}return null}(n);return null!==e?()=>e.factory(n):()=>new n}(n);throw new H(204,!1)}function Zy(n,t,e){let i;if(Ts(n)){const r=le(n);return Cr(r)||tp(r)}if(Xy(n))i=()=>le(n.useValue);else if(function zR(n){return!(!n||!n.useFactory)}(n))i=()=>n.useFactory(...oh(n.deps||[]));else if(function jR(n){return!(!n||!n.useExisting)}(n))i=()=>y(le(n.useExisting));else{const r=le(n&&(n.useClass||n.provide));if(!function $R(n){return!!n.deps}(n))return Cr(r)||tp(r);i=()=>new r(...oh(n.deps))}return i}function ks(n,t,e=!1){return{factory:n,value:t,multi:e?[]:void 0}}function Xy(n){return null!==n&&\"object\"==typeof n&&fA in n}function Ts(n){return\"function\"==typeof n}let dt=(()=>{class n{static create(e,i){var r;if(Array.isArray(e))return Qy({name:\"\"},i,e,\"\");{const s=null!==(r=e.name)&&void 0!==r?r:\"\";return Qy({name:s},e.parent,e.providers,s)}}}return n.THROW_IF_NOT_FOUND=jo,n.NULL=new qy,n.\\u0275prov=k({token:n,providedIn:\"any\",factory:()=>y(Xh)}),n.__NG_ELEMENT_ID__=-1,n})();function e1(n,t){Ol(gh(n)[1],gt())}function E(n){let t=function db(n){return Object.getPrototypeOf(n.prototype).constructor}(n.type),e=!0;const i=[n];for(;t;){let r;if(Hn(n))r=t.\\u0275cmp||t.\\u0275dir;else{if(t.\\u0275cmp)throw new H(903,\"\");r=t.\\u0275dir}if(r){if(e){i.push(r);const o=n;o.inputs=rp(n.inputs),o.declaredInputs=rp(n.declaredInputs),o.outputs=rp(n.outputs);const a=r.hostBindings;a&&s1(n,a);const l=r.viewQuery,c=r.contentQueries;if(l&&n1(n,l),c&&r1(n,c),wu(n.inputs,r.inputs),wu(n.declaredInputs,r.declaredInputs),wu(n.outputs,r.outputs),Hn(r)&&r.data.animation){const d=n.data;d.animation=(d.animation||[]).concat(r.data.animation)}}const s=r.features;if(s)for(let o=0;o<s.length;o++){const a=s[o];a&&a.ngInherit&&a(n),a===E&&(e=!1)}}t=Object.getPrototypeOf(t)}!function t1(n){let t=0,e=null;for(let i=n.length-1;i>=0;i--){const r=n[i];r.hostVars=t+=r.hostVars,r.hostAttrs=Ll(r.hostAttrs,e=Ll(e,r.hostAttrs))}}(i)}function rp(n){return n===os?{}:n===Ne?[]:n}function n1(n,t){const e=n.viewQuery;n.viewQuery=e?(i,r)=>{t(i,r),e(i,r)}:t}function r1(n,t){const e=n.contentQueries;n.contentQueries=e?(i,r,s)=>{t(i,r,s),e(i,r,s)}:t}function s1(n,t){const e=n.hostBindings;n.hostBindings=e?(i,r)=>{t(i,r),e(i,r)}:t}let sc=null;function As(){if(!sc){const n=Oe.Symbol;if(n&&n.iterator)sc=n.iterator;else{const t=Object.getOwnPropertyNames(Map.prototype);for(let e=0;e<t.length;++e){const i=t[e];\"entries\"!==i&&\"size\"!==i&&Map.prototype[i]===Map.prototype.entries&&(sc=i)}}}return sc}function ta(n){return!!sp(n)&&(Array.isArray(n)||!(n instanceof Map)&&As()in n)}function sp(n){return null!==n&&(\"function\"==typeof n||\"object\"==typeof n)}function Nt(n,t,e){return!Object.is(n[t],e)&&(n[t]=e,!0)}function Z(n,t,e,i){const r=w();return Nt(r,hs(),t)&&(Me(),ui(tt(),r,n,t,e,i)),Z}function Rs(n,t,e,i){return Nt(n,hs(),e)?t+re(e)+i:se}function Ee(n,t,e,i,r,s,o,a){const l=w(),c=Me(),d=n+20,u=c.firstCreatePass?function h1(n,t,e,i,r,s,o,a,l){const c=t.consts,d=xs(t,n,4,o||null,Ki(c,a));Gh(t,e,d,Ki(c,l)),Ol(t,d);const u=d.tViews=nc(2,d,i,r,s,t.directiveRegistry,t.pipeRegistry,null,t.schemas,c);return null!==t.queries&&(t.queries.template(t,d),u.queries=t.queries.embeddedTView(d)),d}(d,c,l,t,e,i,r,s,o):c.data[d];oi(u,!1);const h=l[11].createComment(\"\");Zl(c,l,h,u),Ft(h,l),ic(l,l[d]=Hy(h,l,h,u)),Sl(u)&&Uh(c,l,u),null!=o&&$h(l,u,a)}function wn(n){return function us(n,t){return n[t]}(function RT(){return te.lFrame.contextLView}(),20+n)}function f(n,t=ee.Default){const e=w();return null===e?y(n,t):av(gt(),e,le(n),t)}function Sr(){throw new Error(\"invalid\")}function N(n,t,e){const i=w();return Nt(i,hs(),t)&&ln(Me(),tt(),i,n,t,i[11],e,!1),N}function dp(n,t,e,i,r){const o=r?\"class\":\"style\";Wy(n,e,t.inputs[o],o,i)}function x(n,t,e,i){const r=w(),s=Me(),o=20+n,a=r[11],l=r[o]=Mh(a,t,function jT(){return te.lFrame.currentNamespace}()),c=s.firstCreatePass?function O1(n,t,e,i,r,s,o){const a=t.consts,c=xs(t,n,2,r,Ki(a,s));return Gh(t,e,c,Ki(a,o)),null!==c.attrs&&rc(c,c.attrs,!1),null!==c.mergedAttrs&&rc(c,c.mergedAttrs,!0),null!==t.queries&&t.queries.elementStart(t,c),c}(o,s,r,0,t,e,i):s.data[o];oi(c,!0);const d=c.mergedAttrs;null!==d&&Nl(a,l,d);const u=c.classes;null!==u&&Ah(a,l,u);const h=c.styles;return null!==h&&cy(a,l,h),64!=(64&c.flags)&&Zl(s,r,l,c),0===function ST(){return te.lFrame.elementDepthCount}()&&Ft(l,r),function kT(){te.lFrame.elementDepthCount++}(),Sl(c)&&(Uh(s,r,c),ky(s,c,r)),null!==i&&$h(r,c),x}function S(){let n=gt();Uu()?$u():(n=n.parent,oi(n,!1));const t=n;!function TT(){te.lFrame.elementDepthCount--}();const e=Me();return e.firstCreatePass&&(Ol(e,n),Ou(n)&&e.queries.elementEnd(n)),null!=t.classesWithoutHost&&function WT(n){return 0!=(16&n.flags)}(t)&&dp(e,t,w(),t.classesWithoutHost,!0),null!=t.stylesWithoutHost&&function qT(n){return 0!=(32&n.flags)}(t)&&dp(e,t,w(),t.stylesWithoutHost,!1),S}function Le(n,t,e,i){return x(n,t,e,i),S(),Le}function kr(n,t,e){const i=w(),r=Me(),s=n+20,o=r.firstCreatePass?function P1(n,t,e,i,r){const s=t.consts,o=Ki(s,i),a=xs(t,n,8,\"ng-container\",o);return null!==o&&rc(a,o,!0),Gh(t,e,a,Ki(s,r)),null!==t.queries&&t.queries.elementStart(t,a),a}(s,r,i,t,e):r.data[s];oi(o,!0);const a=i[s]=i[11].createComment(\"\");return Zl(r,i,a,o),Ft(a,i),Sl(o)&&(Uh(r,i,o),ky(r,o,i)),null!=e&&$h(i,o),kr}function Tr(){let n=gt();const t=Me();return Uu()?$u():(n=n.parent,oi(n,!1)),t.firstCreatePass&&(Ol(t,n),Ou(n)&&t.queries.elementEnd(n)),Tr}function ia(){return w()}function ra(n){return!!n&&\"function\"==typeof n.then}const up=function Ab(n){return!!n&&\"function\"==typeof n.subscribe};function J(n,t,e,i){const r=w(),s=Me(),o=gt();return Ib(s,r,r[11],o,n,t,!!e,i),J}function hp(n,t){const e=gt(),i=w(),r=Me();return Ib(r,i,$y(Wu(r.data),e,i),e,n,t,!1),hp}function Ib(n,t,e,i,r,s,o,a){const l=Sl(i),d=n.firstCreatePass&&Uy(n),u=t[8],h=zy(t);let p=!0;if(3&i.type||a){const _=yn(i,t),D=a?a(_):_,v=h.length,M=a?V=>a(ct(V[i.index])):i.index;if(et(e)){let V=null;if(!a&&l&&(V=function F1(n,t,e,i){const r=n.cleanup;if(null!=r)for(let s=0;s<r.length-1;s+=2){const o=r[s];if(o===e&&r[s+1]===i){const a=t[7],l=r[s+2];return a.length>l?a[l]:null}\"string\"==typeof o&&(s+=2)}return null}(n,t,r,i.index)),null!==V)(V.__ngLastListenerFn__||V).__ngNextListenerFn__=s,V.__ngLastListenerFn__=s,p=!1;else{s=pp(i,t,u,s,!1);const he=e.listen(D,r,s);h.push(s,he),d&&d.push(r,M,v,v+1)}}else s=pp(i,t,u,s,!0),D.addEventListener(r,s,o),h.push(s),d&&d.push(r,M,v,o)}else s=pp(i,t,u,s,!1);const m=i.outputs;let g;if(p&&null!==m&&(g=m[r])){const _=g.length;if(_)for(let D=0;D<_;D+=2){const We=t[g[D]][g[D+1]].subscribe(s),Ze=h.length;h.push(s,We),d&&d.push(r,i.index,Ze,-(Ze+1))}}}function Rb(n,t,e,i){try{return!1!==e(i)}catch(r){return Gy(n,r),!1}}function pp(n,t,e,i,r){return function s(o){if(o===Function)return i;const a=2&n.flags?rn(n.index,t):t;0==(32&t[2])&&Yh(a);let l=Rb(t,0,i,o),c=s.__ngNextListenerFn__;for(;c;)l=Rb(t,0,c,o)&&l,c=c.__ngNextListenerFn__;return r&&!1===l&&(o.preventDefault(),o.returnValue=!1),l}}function Be(n=1){return function LT(n){return(te.lFrame.contextLView=function BT(n,t){for(;n>0;)t=t[15],n--;return t}(n,te.lFrame.contextLView))[8]}(n)}function N1(n,t){let e=null;const i=function UI(n){const t=n.attrs;if(null!=t){const e=t.indexOf(5);if(0==(1&e))return t[e+1]}return null}(n);for(let r=0;r<t.length;r++){const s=t[r];if(\"*\"!==s){if(null===i?py(n,s,!0):WI(i,s))return r}else e=r}return e}function Lt(n){const t=w()[16][6];if(!t.projection){const i=t.projection=Ho(n?n.length:1,null),r=i.slice();let s=t.child;for(;null!==s;){const o=n?N1(s,n):0;null!==o&&(r[o]?r[o].projectionNext=s:i[o]=s,r[o]=s),s=s.next}}}function Pe(n,t=0,e){const i=w(),r=Me(),s=xs(r,20+n,16,null,e||null);null===s.projection&&(s.projection=t),$u(),64!=(64&s.flags)&&function NI(n,t,e){ly(t[11],0,t,e,Xv(n,e,t),ny(e.parent||t[6],e,t))}(r,i,s)}function zb(n,t,e,i,r){const s=n[e+1],o=null===t;let a=i?zn(s):Ti(s),l=!1;for(;0!==a&&(!1===l||o);){const d=n[a+1];V1(n[a],t)&&(l=!0,n[a+1]=i?Oh(d):Ih(d)),a=i?zn(d):Ti(d)}l&&(n[e+1]=i?Ih(s):Oh(s))}function V1(n,t){return null===n||null==t||(Array.isArray(n)?n[1]:n)===t||!(!Array.isArray(n)||\"string\"!=typeof t)&&bs(n,t)>=0}const vt={textEnd:0,key:0,keyEnd:0,value:0,valueEnd:0};function Ub(n){return n.substring(vt.key,vt.keyEnd)}function $b(n,t){const e=vt.textEnd;return e===t?-1:(t=vt.keyEnd=function U1(n,t,e){for(;t<e&&n.charCodeAt(t)>32;)t++;return t}(n,vt.key=t,e),js(n,t,e))}function js(n,t,e){for(;t<e&&n.charCodeAt(t)<=32;)t++;return t}function $n(n,t,e){return Gn(n,t,e,!1),$n}function Ae(n,t){return Gn(n,t,null,!0),Ae}function fi(n,t){for(let e=function j1(n){return function Wb(n){vt.key=0,vt.keyEnd=0,vt.value=0,vt.valueEnd=0,vt.textEnd=n.length}(n),$b(n,js(n,0,vt.textEnd))}(t);e>=0;e=$b(t,e))sn(n,Ub(t),!0)}function Gn(n,t,e,i){const r=w(),s=Me(),o=ki(2);s.firstUpdatePass&&Kb(s,n,o,i),t!==se&&Nt(r,o,t)&&Xb(s,s.data[jt()],r,r[11],n,r[o+1]=function eO(n,t){return null==n||(\"string\"==typeof t?n+=t:\"object\"==typeof n&&(n=Re(on(n)))),n}(t,e),i,o)}function Qb(n,t){return t>=n.expandoStartIndex}function Kb(n,t,e,i){const r=n.data;if(null===r[e+1]){const s=r[jt()],o=Qb(n,e);eC(s,i)&&null===t&&!o&&(t=!1),t=function Y1(n,t,e,i){const r=Wu(n);let s=i?t.residualClasses:t.residualStyles;if(null===r)0===(i?t.classBindings:t.styleBindings)&&(e=sa(e=mp(null,n,t,e,i),t.attrs,i),s=null);else{const o=t.directiveStylingLast;if(-1===o||n[o]!==r)if(e=mp(r,n,t,e,i),null===s){let l=function Q1(n,t,e){const i=e?t.classBindings:t.styleBindings;if(0!==Ti(i))return n[zn(i)]}(n,t,i);void 0!==l&&Array.isArray(l)&&(l=mp(null,n,t,l[1],i),l=sa(l,t.attrs,i),function K1(n,t,e,i){n[zn(e?t.classBindings:t.styleBindings)]=i}(n,t,i,l))}else s=function Z1(n,t,e){let i;const r=t.directiveEnd;for(let s=1+t.directiveStylingLast;s<r;s++)i=sa(i,n[s].hostAttrs,e);return sa(i,t.attrs,e)}(n,t,i)}return void 0!==s&&(i?t.residualClasses=s:t.residualStyles=s),e}(r,s,t,i),function L1(n,t,e,i,r,s){let o=s?t.classBindings:t.styleBindings,a=zn(o),l=Ti(o);n[i]=e;let d,c=!1;if(Array.isArray(e)){const u=e;d=u[1],(null===d||bs(u,d)>0)&&(c=!0)}else d=e;if(r)if(0!==l){const h=zn(n[a+1]);n[i+1]=Jl(h,a),0!==h&&(n[h+1]=Rh(n[h+1],i)),n[a+1]=function KI(n,t){return 131071&n|t<<17}(n[a+1],i)}else n[i+1]=Jl(a,0),0!==a&&(n[a+1]=Rh(n[a+1],i)),a=i;else n[i+1]=Jl(l,0),0===a?a=i:n[l+1]=Rh(n[l+1],i),l=i;c&&(n[i+1]=Ih(n[i+1])),zb(n,d,i,!0),zb(n,d,i,!1),function B1(n,t,e,i,r){const s=r?n.residualClasses:n.residualStyles;null!=s&&\"string\"==typeof t&&bs(s,t)>=0&&(e[i+1]=Oh(e[i+1]))}(t,d,n,i,s),o=Jl(a,l),s?t.classBindings=o:t.styleBindings=o}(r,s,t,e,o,i)}}function mp(n,t,e,i,r){let s=null;const o=e.directiveEnd;let a=e.directiveStylingLast;for(-1===a?a=e.directiveStart:a++;a<o&&(s=t[a],i=sa(i,s.hostAttrs,r),s!==n);)a++;return null!==n&&(e.directiveStylingLast=a),i}function sa(n,t,e){const i=e?1:2;let r=-1;if(null!==t)for(let s=0;s<t.length;s++){const o=t[s];\"number\"==typeof o?r=o:r===i&&(Array.isArray(n)||(n=void 0===n?[]:[\"\",n]),sn(n,o,!!e||t[++s]))}return void 0===n?null:n}function Xb(n,t,e,i,r,s,o,a){if(!(3&t.type))return;const l=n.data,c=l[a+1];lc(function vy(n){return 1==(1&n)}(c)?Jb(l,t,e,r,Ti(c),o):void 0)||(lc(s)||function _y(n){return 2==(2&n)}(c)&&(s=Jb(l,null,e,r,a,o)),function BI(n,t,e,i,r){const s=et(n);if(t)r?s?n.addClass(e,i):e.classList.add(i):s?n.removeClass(e,i):e.classList.remove(i);else{let o=-1===i.indexOf(\"-\")?void 0:an.DashCase;if(null==r)s?n.removeStyle(e,i,o):e.style.removeProperty(i);else{const a=\"string\"==typeof r&&r.endsWith(\"!important\");a&&(r=r.slice(0,-10),o|=an.Important),s?n.setStyle(e,i,r,o):e.style.setProperty(i,r,a?\"important\":\"\")}}}(i,o,kl(jt(),e),r,s))}function Jb(n,t,e,i,r,s){const o=null===t;let a;for(;r>0;){const l=n[r],c=Array.isArray(l),d=c?l[1]:l,u=null===d;let h=e[r+1];h===se&&(h=u?Ne:void 0);let p=u?ih(h,i):d===i?h:void 0;if(c&&!lc(p)&&(p=ih(l,i)),lc(p)&&(a=p,o))return a;const m=n[r+1];r=o?zn(m):Ti(m)}if(null!==t){let l=s?t.residualClasses:t.residualStyles;null!=l&&(a=ih(l,i))}return a}function lc(n){return void 0!==n}function eC(n,t){return 0!=(n.flags&(t?16:32))}function we(n,t=\"\"){const e=w(),i=Me(),r=n+20,s=i.firstCreatePass?xs(i,r,1,t,null):i.data[r],o=e[r]=function wh(n,t){return et(n)?n.createText(t):n.createTextNode(t)}(e[11],t);Zl(i,e,o,s),oi(s,!1)}function Ut(n){return qn(\"\",n,\"\"),Ut}function qn(n,t,e){const i=w(),r=Rs(i,n,t,e);return r!==se&&Ai(i,jt(),r),qn}function cC(n,t,e){!function Wn(n,t,e,i){const r=Me(),s=ki(2);r.firstUpdatePass&&Kb(r,null,s,i);const o=w();if(e!==se&&Nt(o,s,e)){const a=r.data[jt()];if(eC(a,i)&&!Qb(r,s)){let l=i?a.classesWithoutHost:a.stylesWithoutHost;null!==l&&(e=Mu(l,e||\"\")),dp(r,a,o,e,i)}else!function J1(n,t,e,i,r,s,o,a){r===se&&(r=Ne);let l=0,c=0,d=0<r.length?r[0]:null,u=0<s.length?s[0]:null;for(;null!==d||null!==u;){const h=l<r.length?r[l+1]:void 0,p=c<s.length?s[c+1]:void 0;let g,m=null;d===u?(l+=2,c+=2,h!==p&&(m=u,g=p)):null===u||null!==d&&d<u?(l+=2,m=d):(c+=2,m=u,g=p),null!==m&&Xb(n,t,e,i,m,g,o,a),d=l<r.length?r[l]:null,u=c<s.length?s[c]:null}}(r,a,o,o[11],o[s+1],o[s+1]=function X1(n,t,e){if(null==e||\"\"===e)return Ne;const i=[],r=on(e);if(Array.isArray(r))for(let s=0;s<r.length;s++)n(i,r[s],!0);else if(\"object\"==typeof r)for(const s in r)r.hasOwnProperty(s)&&n(i,s,r[s]);else\"string\"==typeof r&&t(i,r);return i}(n,t,e),i,s)}}(sn,fi,Rs(w(),n,t,e),!0)}function Yn(n,t,e){const i=w();return Nt(i,hs(),t)&&ln(Me(),tt(),i,n,t,i[11],e,!0),Yn}function gp(n,t,e){const i=w();if(Nt(i,hs(),t)){const s=Me(),o=tt();ln(s,o,i,n,t,$y(Wu(s.data),o,i),e,!0)}return gp}const cc=\"en-US\";let CC=cc;function yp(n,t,e,i,r){if(n=le(n),Array.isArray(n))for(let s=0;s<n.length;s++)yp(n[s],t,e,i,r);else{const s=Me(),o=w();let a=Ts(n)?n:le(n.provide),l=Zy(n);const c=gt(),d=1048575&c.providerIndexes,u=c.directiveStart,h=c.providerIndexes>>20;if(Ts(n)||!n.multi){const p=new Po(l,r,f),m=Cp(a,t,r?d:d+h,u);-1===m?(Hl(No(c,o),s,a),bp(s,n,t.length),t.push(a),c.directiveStart++,c.directiveEnd++,r&&(c.providerIndexes+=1048576),e.push(p),o.push(p)):(e[m]=p,o[m]=p)}else{const p=Cp(a,t,d+h,u),m=Cp(a,t,d,d+h),g=p>=0&&e[p],_=m>=0&&e[m];if(r&&!_||!r&&!g){Hl(No(c,o),s,a);const D=function vP(n,t,e,i,r){const s=new Po(n,e,f);return s.multi=[],s.index=t,s.componentProviders=0,GC(s,r,i&&!e),s}(r?_P:gP,e.length,r,i,l);!r&&_&&(e[m].providerFactory=D),bp(s,n,t.length,0),t.push(a),c.directiveStart++,c.directiveEnd++,r&&(c.providerIndexes+=1048576),e.push(D),o.push(D)}else bp(s,n,p>-1?p:m,GC(e[r?m:p],l,!r&&i));!r&&i&&_&&e[m].componentProviders++}}}function bp(n,t,e,i){const r=Ts(t),s=function UR(n){return!!n.useClass}(t);if(r||s){const l=(s?le(t.useClass):t).prototype.ngOnDestroy;if(l){const c=n.destroyHooks||(n.destroyHooks=[]);if(!r&&t.multi){const d=c.indexOf(e);-1===d?c.push(e,[i,l]):c[d+1].push(i,l)}else c.push(e,l)}}}function GC(n,t,e){return e&&n.componentProviders++,n.multi.push(t)-1}function Cp(n,t,e,i){for(let r=e;r<i;r++)if(t[r]===n)return r;return-1}function gP(n,t,e,i){return Dp(this.multi,[])}function _P(n,t,e,i){const r=this.multi;let s;if(this.providerFactory){const o=this.providerFactory.componentProviders,a=Lo(e,e[1],this.providerFactory.index,i);s=a.slice(0,o),Dp(r,s);for(let l=o;l<a.length;l++)s.push(a[l])}else s=[],Dp(r,s);return s}function Dp(n,t){for(let e=0;e<n.length;e++)t.push((0,n[e])());return t}function L(n,t=[]){return e=>{e.providersResolver=(i,r)=>function mP(n,t,e){const i=Me();if(i.firstCreatePass){const r=Hn(n);yp(e,i.data,i.blueprint,r,!0),yp(t,i.data,i.blueprint,r,!1)}}(i,r?r(n):n,t)}}class WC{}class CP{resolveComponentFactory(t){throw function bP(n){const t=Error(`No component factory found for ${Re(n)}. Did you add it to @NgModule.entryComponents?`);return t.ngComponent=n,t}(t)}}let Ir=(()=>{class n{}return n.NULL=new CP,n})();function DP(){return $s(gt(),w())}function $s(n,t){return new W(yn(n,t))}let W=(()=>{class n{constructor(e){this.nativeElement=e}}return n.__NG_ELEMENT_ID__=DP,n})();function wP(n){return n instanceof W?n.nativeElement:n}class da{}let Ii=(()=>{class n{}return n.__NG_ELEMENT_ID__=()=>function xP(){const n=w(),e=rn(gt().index,n);return function MP(n){return n[11]}(si(e)?e:n)}(),n})(),EP=(()=>{class n{}return n.\\u0275prov=k({token:n,providedIn:\"root\",factory:()=>null}),n})();class Rr{constructor(t){this.full=t,this.major=t.split(\".\")[0],this.minor=t.split(\".\")[1],this.patch=t.split(\".\").slice(2).join(\".\")}}const SP=new Rr(\"13.3.0\"),wp={};function fc(n,t,e,i,r=!1){for(;null!==e;){const s=t[e.index];if(null!==s&&i.push(ct(s)),Vn(s))for(let a=10;a<s.length;a++){const l=s[a],c=l[1].firstChild;null!==c&&fc(l[1],l,c,i)}const o=e.type;if(8&o)fc(n,t,e.child,i);else if(32&o){const a=bh(e,t);let l;for(;l=a();)i.push(l)}else if(16&o){const a=oy(t,e);if(Array.isArray(a))i.push(...a);else{const l=Ko(t[16]);fc(l[1],l,a,i,!0)}}e=r?e.projectionNext:e.next}return i}class ua{constructor(t,e){this._lView=t,this._cdRefInjectingView=e,this._appRef=null,this._attachedToViewContainer=!1}get rootNodes(){const t=this._lView,e=t[1];return fc(e,t,e.firstChild,[])}get context(){return this._lView[8]}set context(t){this._lView[8]=t}get destroyed(){return 256==(256&this._lView[2])}destroy(){if(this._appRef)this._appRef.detachView(this);else if(this._attachedToViewContainer){const t=this._lView[3];if(Vn(t)){const e=t[8],i=e?e.indexOf(this):-1;i>-1&&(xh(t,i),zl(e,i))}this._attachedToViewContainer=!1}Zv(this._lView[1],this._lView)}onDestroy(t){Ry(this._lView[1],this._lView,null,t)}markForCheck(){Yh(this._cdRefInjectingView||this._lView)}detach(){this._lView[2]&=-129}reattach(){this._lView[2]|=128}detectChanges(){Kh(this._lView[1],this._lView,this.context)}checkNoChanges(){!function RR(n,t,e){Al(!0);try{Kh(n,t,e)}finally{Al(!1)}}(this._lView[1],this._lView,this.context)}attachToViewContainerRef(){if(this._appRef)throw new H(902,\"\");this._attachedToViewContainer=!0}detachFromAppRef(){this._appRef=null,function kI(n,t){Zo(n,t,t[11],2,null,null)}(this._lView[1],this._lView)}attachToAppRef(t){if(this._attachedToViewContainer)throw new H(902,\"\");this._appRef=t}}class kP extends ua{constructor(t){super(t),this._view=t}detectChanges(){jy(this._view)}checkNoChanges(){!function OR(n){Al(!0);try{jy(n)}finally{Al(!1)}}(this._view)}get context(){return null}}class YC extends Ir{constructor(t){super(),this.ngModule=t}resolveComponentFactory(t){const e=Ot(t);return new Mp(e,this.ngModule)}}function QC(n){const t=[];for(let e in n)n.hasOwnProperty(e)&&t.push({propName:n[e],templateName:e});return t}class Mp extends WC{constructor(t,e){super(),this.componentDef=t,this.ngModule=e,this.componentType=t.type,this.selector=function YI(n){return n.map(qI).join(\",\")}(t.selectors),this.ngContentSelectors=t.ngContentSelectors?t.ngContentSelectors:[],this.isBoundToModule=!!e}get inputs(){return QC(this.componentDef.inputs)}get outputs(){return QC(this.componentDef.outputs)}create(t,e,i,r){const s=(r=r||this.ngModule)?function AP(n,t){return{get:(e,i,r)=>{const s=n.get(e,wp,r);return s!==wp||i===wp?s:t.get(e,i,r)}}}(t,r.injector):t,o=s.get(da,V_),a=s.get(EP,null),l=o.createRenderer(null,this.componentDef),c=this.componentDef.selectors[0][0]||\"div\",d=i?function Iy(n,t,e){if(et(n))return n.selectRootElement(t,e===Ln.ShadowDom);let i=\"string\"==typeof t?n.querySelector(t):t;return i.textContent=\"\",i}(l,i,this.componentDef.encapsulation):Mh(o.createRenderer(null,this.componentDef),c,function TP(n){const t=n.toLowerCase();return\"svg\"===t?\"svg\":\"math\"===t?\"math\":null}(c)),u=this.componentDef.onPush?576:528,h=function cb(n,t){return{components:[],scheduler:n||CI,clean:PR,playerHandler:t||null,flags:0}}(),p=nc(0,null,null,1,0,null,null,null,null,null),m=Xo(null,p,h,u,null,null,o,l,a,s);let g,_;Il(m);try{const D=function ab(n,t,e,i,r,s){const o=e[1];e[20]=n;const l=xs(o,20,2,\"#host\",null),c=l.mergedAttrs=t.hostAttrs;null!==c&&(rc(l,c,!0),null!==n&&(Nl(r,n,c),null!==l.classes&&Ah(r,n,l.classes),null!==l.styles&&cy(r,n,l.styles)));const d=i.createRenderer(n,t),u=Xo(e,Ty(t),null,t.onPush?64:16,e[20],l,i,d,s||null,null);return o.firstCreatePass&&(Hl(No(l,e),o,t.type),Ly(o,l),By(l,e.length,1)),ic(e,u),e[20]=u}(d,this.componentDef,m,o,l);if(d)if(i)Nl(l,d,[\"ng-version\",SP.full]);else{const{attrs:v,classes:M}=function QI(n){const t=[],e=[];let i=1,r=2;for(;i<n.length;){let s=n[i];if(\"string\"==typeof s)2===r?\"\"!==s&&t.push(s,n[++i]):8===r&&e.push(s);else{if(!jn(r))break;r=s}i++}return{attrs:t,classes:e}}(this.componentDef.selectors[0]);v&&Nl(l,d,v),M&&M.length>0&&Ah(l,d,M.join(\" \"))}if(_=Hu(p,20),void 0!==e){const v=_.projection=[];for(let M=0;M<this.ngContentSelectors.length;M++){const V=e[M];v.push(null!=V?Array.from(V):null)}}g=function lb(n,t,e,i,r){const s=e[1],o=function gR(n,t,e){const i=gt();n.firstCreatePass&&(e.providersResolver&&e.providersResolver(e),Vy(n,i,t,Es(n,t,1,null),e));const r=Lo(t,n,i.directiveStart,i);Ft(r,t);const s=yn(i,t);return s&&Ft(s,t),r}(s,e,t);if(i.components.push(o),n[8]=o,r&&r.forEach(l=>l(o,t)),t.contentQueries){const l=gt();t.contentQueries(1,o,l.directiveStart)}const a=gt();return!s.firstCreatePass||null===t.hostBindings&&null===t.hostAttrs||(Zi(a.index),Fy(e[1],a,0,a.directiveStart,a.directiveEnd,t),Ny(t,o)),o}(D,this.componentDef,m,h,[e1]),Jo(p,m,null)}finally{Rl()}return new RP(this.componentType,g,$s(_,m),m,_)}}class RP extends class yP{}{constructor(t,e,i,r,s){super(),this.location=i,this._rootLView=r,this._tNode=s,this.instance=e,this.hostView=this.changeDetectorRef=new kP(r),this.componentType=t}get injector(){return new ms(this._tNode,this._rootLView)}destroy(){this.hostView.destroy()}onDestroy(t){this.hostView.onDestroy(t)}}class Ri{}class KC{}const Gs=new Map;class JC extends Ri{constructor(t,e){super(),this._parent=e,this._bootstrapComponents=[],this.injector=this,this.destroyCbs=[],this.componentFactoryResolver=new YC(this);const i=gn(t);this._bootstrapComponents=di(i.bootstrap),this._r3Injector=Ky(t,e,[{provide:Ri,useValue:this},{provide:Ir,useValue:this.componentFactoryResolver}],Re(t)),this._r3Injector._resolveInjectorDefTypes(),this.instance=this.get(t)}get(t,e=dt.THROW_IF_NOT_FOUND,i=ee.Default){return t===dt||t===Ri||t===Xh?this:this._r3Injector.get(t,e,i)}destroy(){const t=this._r3Injector;!t.destroyed&&t.destroy(),this.destroyCbs.forEach(e=>e()),this.destroyCbs=null}onDestroy(t){this.destroyCbs.push(t)}}class xp extends KC{constructor(t){super(),this.moduleType=t,null!==gn(t)&&function PP(n){const t=new Set;!function e(i){const r=gn(i,!0),s=r.id;null!==s&&(function ZC(n,t,e){if(t&&t!==e)throw new Error(`Duplicate module registered for ${n} - ${Re(t)} vs ${Re(t.name)}`)}(s,Gs.get(s),i),Gs.set(s,i));const o=di(r.imports);for(const a of o)t.has(a)||(t.add(a),e(a))}(n)}(t)}create(t){return new JC(this.moduleType,t)}}function Ep(n){return t=>{setTimeout(n,void 0,t)}}const $=class ZP extends O{constructor(t=!1){super(),this.__isAsync=t}emit(t){super.next(t)}subscribe(t,e,i){var r,s,o;let a=t,l=e||(()=>null),c=i;if(t&&\"object\"==typeof t){const u=t;a=null===(r=u.next)||void 0===r?void 0:r.bind(u),l=null===(s=u.error)||void 0===s?void 0:s.bind(u),c=null===(o=u.complete)||void 0===o?void 0:o.bind(u)}this.__isAsync&&(l=Ep(l),a&&(a=Ep(a)),c&&(c=Ep(c)));const d=super.subscribe({next:a,error:l,complete:c});return t instanceof ke&&t.add(d),d}};function XP(){return this._results[As()]()}class fa{constructor(t=!1){this._emitDistinctChangesOnly=t,this.dirty=!0,this._results=[],this._changesDetected=!1,this._changes=null,this.length=0,this.first=void 0,this.last=void 0;const e=As(),i=fa.prototype;i[e]||(i[e]=XP)}get changes(){return this._changes||(this._changes=new $)}get(t){return this._results[t]}map(t){return this._results.map(t)}filter(t){return this._results.filter(t)}find(t){return this._results.find(t)}reduce(t,e){return this._results.reduce(t,e)}forEach(t){this._results.forEach(t)}some(t){return this._results.some(t)}toArray(){return this._results.slice()}toString(){return this._results.toString()}reset(t,e){const i=this;i.dirty=!1;const r=bn(t);(this._changesDetected=!function iA(n,t,e){if(n.length!==t.length)return!1;for(let i=0;i<n.length;i++){let r=n[i],s=t[i];if(e&&(r=e(r),s=e(s)),s!==r)return!1}return!0}(i._results,r,e))&&(i._results=r,i.length=r.length,i.last=r[this.length-1],i.first=r[0])}notifyOnChanges(){this._changes&&(this._changesDetected||!this._emitDistinctChangesOnly)&&this._changes.emit(this)}setDirty(){this.dirty=!0}destroy(){this.changes.complete(),this.changes.unsubscribe()}}Symbol;let ut=(()=>{class n{}return n.__NG_ELEMENT_ID__=tF,n})();const JP=ut,eF=class extends JP{constructor(t,e,i){super(),this._declarationLView=t,this._declarationTContainer=e,this.elementRef=i}createEmbeddedView(t){const e=this._declarationTContainer.tViews,i=Xo(this._declarationLView,e,t,16,null,e.declTNode,null,null,null,null);i[17]=this._declarationLView[this._declarationTContainer.index];const s=this._declarationLView[19];return null!==s&&(i[19]=s.createEmbeddedView(e)),Jo(e,i,t),new ua(i)}};function tF(){return gc(gt(),w())}function gc(n,t){return 4&n.type?new eF(t,n,$s(n,t)):null}let st=(()=>{class n{}return n.__NG_ELEMENT_ID__=nF,n})();function nF(){return l0(gt(),w())}const iF=st,o0=class extends iF{constructor(t,e,i){super(),this._lContainer=t,this._hostTNode=e,this._hostLView=i}get element(){return $s(this._hostTNode,this._hostLView)}get injector(){return new ms(this._hostTNode,this._hostLView)}get parentInjector(){const t=Vl(this._hostTNode,this._hostLView);if(nv(t)){const e=fs(t,this._hostLView),i=ps(t);return new ms(e[1].data[i+8],e)}return new ms(null,this._hostLView)}clear(){for(;this.length>0;)this.remove(this.length-1)}get(t){const e=a0(this._lContainer);return null!==e&&e[t]||null}get length(){return this._lContainer.length-10}createEmbeddedView(t,e,i){const r=t.createEmbeddedView(e||{});return this.insert(r,i),r}createComponent(t,e,i,r,s){const o=t&&!function Vo(n){return\"function\"==typeof n}(t);let a;if(o)a=e;else{const u=e||{};a=u.index,i=u.injector,r=u.projectableNodes,s=u.ngModuleRef}const l=o?t:new Mp(Ot(t)),c=i||this.parentInjector;if(!s&&null==l.ngModule){const h=(o?c:this.parentInjector).get(Ri,null);h&&(s=h)}const d=l.create(c,r,void 0,s);return this.insert(d.hostView,a),d}insert(t,e){const i=t._lView,r=i[1];if(function ET(n){return Vn(n[3])}(i)){const d=this.indexOf(t);if(-1!==d)this.detach(d);else{const u=i[3],h=new o0(u,u[6],u[3]);h.detach(h.indexOf(t))}}const s=this._adjustIndex(e),o=this._lContainer;!function AI(n,t,e,i){const r=10+i,s=e.length;i>0&&(e[r-1][4]=t),i<s-10?(t[4]=e[r],hv(e,10+i,t)):(e.push(t),t[4]=null),t[3]=e;const o=t[17];null!==o&&e!==o&&function II(n,t){const e=n[9];t[16]!==t[3][3][16]&&(n[2]=!0),null===e?n[9]=[t]:e.push(t)}(o,t);const a=t[19];null!==a&&a.insertView(n),t[2]|=128}(r,i,o,s);const a=kh(s,o),l=i[11],c=Kl(l,o[7]);return null!==c&&function SI(n,t,e,i,r,s){i[0]=r,i[6]=t,Zo(n,i,e,1,r,s)}(r,o[6],l,i,c,a),t.attachToViewContainerRef(),hv(Sp(o),s,t),t}move(t,e){return this.insert(t,e)}indexOf(t){const e=a0(this._lContainer);return null!==e?e.indexOf(t):-1}remove(t){const e=this._adjustIndex(t,-1),i=xh(this._lContainer,e);i&&(zl(Sp(this._lContainer),e),Zv(i[1],i))}detach(t){const e=this._adjustIndex(t,-1),i=xh(this._lContainer,e);return i&&null!=zl(Sp(this._lContainer),e)?new ua(i):null}_adjustIndex(t,e=0){return null==t?this.length+e:t}};function a0(n){return n[8]}function Sp(n){return n[8]||(n[8]=[])}function l0(n,t){let e;const i=t[n.index];if(Vn(i))e=i;else{let r;if(8&n.type)r=ct(i);else{const s=t[11];r=s.createComment(\"\");const o=yn(n,t);xr(s,Kl(s,o),r,function FI(n,t){return et(n)?n.nextSibling(t):t.nextSibling}(s,o),!1)}t[n.index]=e=Hy(i,t,r,n),ic(t,e)}return new o0(e,n,t)}class kp{constructor(t){this.queryList=t,this.matches=null}clone(){return new kp(this.queryList)}setDirty(){this.queryList.setDirty()}}class Tp{constructor(t=[]){this.queries=t}createEmbeddedView(t){const e=t.queries;if(null!==e){const i=null!==t.contentQueries?t.contentQueries[0]:e.length,r=[];for(let s=0;s<i;s++){const o=e.getByIndex(s);r.push(this.queries[o.indexInDeclarationView].clone())}return new Tp(r)}return null}insertView(t){this.dirtyQueriesWithMatches(t)}detachView(t){this.dirtyQueriesWithMatches(t)}dirtyQueriesWithMatches(t){for(let e=0;e<this.queries.length;e++)null!==p0(t,e).matches&&this.queries[e].setDirty()}}class c0{constructor(t,e,i=null){this.predicate=t,this.flags=e,this.read=i}}class Ap{constructor(t=[]){this.queries=t}elementStart(t,e){for(let i=0;i<this.queries.length;i++)this.queries[i].elementStart(t,e)}elementEnd(t){for(let e=0;e<this.queries.length;e++)this.queries[e].elementEnd(t)}embeddedTView(t){let e=null;for(let i=0;i<this.length;i++){const r=null!==e?e.length:0,s=this.getByIndex(i).embeddedTView(t,r);s&&(s.indexInDeclarationView=i,null!==e?e.push(s):e=[s])}return null!==e?new Ap(e):null}template(t,e){for(let i=0;i<this.queries.length;i++)this.queries[i].template(t,e)}getByIndex(t){return this.queries[t]}get length(){return this.queries.length}track(t){this.queries.push(t)}}class Ip{constructor(t,e=-1){this.metadata=t,this.matches=null,this.indexInDeclarationView=-1,this.crossesNgTemplate=!1,this._appliesToNextNode=!0,this._declarationNodeIndex=e}elementStart(t,e){this.isApplyingToNode(e)&&this.matchTNode(t,e)}elementEnd(t){this._declarationNodeIndex===t.index&&(this._appliesToNextNode=!1)}template(t,e){this.elementStart(t,e)}embeddedTView(t,e){return this.isApplyingToNode(t)?(this.crossesNgTemplate=!0,this.addMatch(-t.index,e),new Ip(this.metadata)):null}isApplyingToNode(t){if(this._appliesToNextNode&&1!=(1&this.metadata.flags)){const e=this._declarationNodeIndex;let i=t.parent;for(;null!==i&&8&i.type&&i.index!==e;)i=i.parent;return e===(null!==i?i.index:-1)}return this._appliesToNextNode}matchTNode(t,e){const i=this.metadata.predicate;if(Array.isArray(i))for(let r=0;r<i.length;r++){const s=i[r];this.matchTNodeWithReadOption(t,e,oF(e,s)),this.matchTNodeWithReadOption(t,e,jl(e,t,s,!1,!1))}else i===ut?4&e.type&&this.matchTNodeWithReadOption(t,e,-1):this.matchTNodeWithReadOption(t,e,jl(e,t,i,!1,!1))}matchTNodeWithReadOption(t,e,i){if(null!==i){const r=this.metadata.read;if(null!==r)if(r===W||r===st||r===ut&&4&e.type)this.addMatch(e.index,-2);else{const s=jl(e,t,r,!1,!1);null!==s&&this.addMatch(e.index,s)}else this.addMatch(e.index,i)}}addMatch(t,e){null===this.matches?this.matches=[t,e]:this.matches.push(t,e)}}function oF(n,t){const e=n.localNames;if(null!==e)for(let i=0;i<e.length;i+=2)if(e[i]===t)return e[i+1];return null}function lF(n,t,e,i){return-1===e?function aF(n,t){return 11&n.type?$s(n,t):4&n.type?gc(n,t):null}(t,n):-2===e?function cF(n,t,e){return e===W?$s(t,n):e===ut?gc(t,n):e===st?l0(t,n):void 0}(n,t,i):Lo(n,n[1],e,t)}function d0(n,t,e,i){const r=t[19].queries[i];if(null===r.matches){const s=n.data,o=e.matches,a=[];for(let l=0;l<o.length;l+=2){const c=o[l];a.push(c<0?null:lF(t,s[c],o[l+1],e.metadata.read))}r.matches=a}return r.matches}function Rp(n,t,e,i){const r=n.queries.getByIndex(e),s=r.matches;if(null!==s){const o=d0(n,t,r,e);for(let a=0;a<s.length;a+=2){const l=s[a];if(l>0)i.push(o[a/2]);else{const c=s[a+1],d=t[-l];for(let u=10;u<d.length;u++){const h=d[u];h[17]===h[3]&&Rp(h[1],h,c,i)}if(null!==d[9]){const u=d[9];for(let h=0;h<u.length;h++){const p=u[h];Rp(p[1],p,c,i)}}}}}return i}function z(n){const t=w(),e=Me(),i=W_();qu(i+1);const r=p0(e,i);if(n.dirty&&H_(t)===(2==(2&r.metadata.flags))){if(null===r.matches)n.reset([]);else{const s=r.crossesNgTemplate?Rp(e,t,i,[]):d0(e,t,r,i);n.reset(s,wP),n.notifyOnChanges()}return!0}return!1}function je(n,t,e){const i=Me();i.firstCreatePass&&(h0(i,new c0(n,t,e),-1),2==(2&t)&&(i.staticViewQueries=!0)),u0(i,w(),t)}function ve(n,t,e,i){const r=Me();if(r.firstCreatePass){const s=gt();h0(r,new c0(t,e,i),s.index),function uF(n,t){const e=n.contentQueries||(n.contentQueries=[]);t!==(e.length?e[e.length-1]:-1)&&e.push(n.queries.length-1,t)}(r,n),2==(2&e)&&(r.staticContentQueries=!0)}u0(r,w(),e)}function U(){return function dF(n,t){return n[19].queries[t].queryList}(w(),W_())}function u0(n,t,e){const i=new fa(4==(4&e));Ry(n,t,i,i.destroy),null===t[19]&&(t[19]=new Tp),t[19].queries.push(new kp(i))}function h0(n,t,e){null===n.queries&&(n.queries=new Ap),n.queries.track(new Ip(t,e))}function p0(n,t){return n.queries.getByIndex(t)}function yc(...n){}const Bp=new b(\"Application Initializer\");let Vp=(()=>{class n{constructor(e){this.appInits=e,this.resolve=yc,this.reject=yc,this.initialized=!1,this.done=!1,this.donePromise=new Promise((i,r)=>{this.resolve=i,this.reject=r})}runInitializers(){if(this.initialized)return;const e=[],i=()=>{this.done=!0,this.resolve()};if(this.appInits)for(let r=0;r<this.appInits.length;r++){const s=this.appInits[r]();if(ra(s))e.push(s);else if(up(s)){const o=new Promise((a,l)=>{s.subscribe({complete:a,error:l})});e.push(o)}}Promise.all(e).then(()=>{i()}).catch(r=>{this.reject(r)}),0===e.length&&i(),this.initialized=!0}}return n.\\u0275fac=function(e){return new(e||n)(y(Bp,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const ga=new b(\"AppId\",{providedIn:\"root\",factory:function A0(){return`${Hp()}${Hp()}${Hp()}`}});function Hp(){return String.fromCharCode(97+Math.floor(25*Math.random()))}const I0=new b(\"Platform Initializer\"),bc=new b(\"Platform ID\"),R0=new b(\"appBootstrapListener\");let O0=(()=>{class n{log(e){console.log(e)}warn(e){console.warn(e)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const Oi=new b(\"LocaleId\",{providedIn:\"root\",factory:()=>Uo(Oi,ee.Optional|ee.SkipSelf)||function TF(){return\"undefined\"!=typeof $localize&&$localize.locale||cc}()});class IF{constructor(t,e){this.ngModuleFactory=t,this.componentFactories=e}}let P0=(()=>{class n{compileModuleSync(e){return new xp(e)}compileModuleAsync(e){return Promise.resolve(this.compileModuleSync(e))}compileModuleAndAllComponentsSync(e){const i=this.compileModuleSync(e),s=di(gn(e).declarations).reduce((o,a)=>{const l=Ot(a);return l&&o.push(new Mp(l)),o},[]);return new IF(i,s)}compileModuleAndAllComponentsAsync(e){return Promise.resolve(this.compileModuleAndAllComponentsSync(e))}clearCache(){}clearCacheFor(e){}getModuleId(e){}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const OF=(()=>Promise.resolve(0))();function jp(n){\"undefined\"==typeof Zone?OF.then(()=>{n&&n.apply(null,null)}):Zone.current.scheduleMicroTask(\"scheduleMicrotask\",n)}class ne{constructor({enableLongStackTrace:t=!1,shouldCoalesceEventChangeDetection:e=!1,shouldCoalesceRunChangeDetection:i=!1}){if(this.hasPendingMacrotasks=!1,this.hasPendingMicrotasks=!1,this.isStable=!0,this.onUnstable=new $(!1),this.onMicrotaskEmpty=new $(!1),this.onStable=new $(!1),this.onError=new $(!1),\"undefined\"==typeof Zone)throw new Error(\"In this configuration Angular requires Zone.js\");Zone.assertZonePatched();const r=this;r._nesting=0,r._outer=r._inner=Zone.current,Zone.TaskTrackingZoneSpec&&(r._inner=r._inner.fork(new Zone.TaskTrackingZoneSpec)),t&&Zone.longStackTraceZoneSpec&&(r._inner=r._inner.fork(Zone.longStackTraceZoneSpec)),r.shouldCoalesceEventChangeDetection=!i&&e,r.shouldCoalesceRunChangeDetection=i,r.lastRequestAnimationFrameId=-1,r.nativeRequestAnimationFrame=function PF(){let n=Oe.requestAnimationFrame,t=Oe.cancelAnimationFrame;if(\"undefined\"!=typeof Zone&&n&&t){const e=n[Zone.__symbol__(\"OriginalDelegate\")];e&&(n=e);const i=t[Zone.__symbol__(\"OriginalDelegate\")];i&&(t=i)}return{nativeRequestAnimationFrame:n,nativeCancelAnimationFrame:t}}().nativeRequestAnimationFrame,function LF(n){const t=()=>{!function NF(n){n.isCheckStableRunning||-1!==n.lastRequestAnimationFrameId||(n.lastRequestAnimationFrameId=n.nativeRequestAnimationFrame.call(Oe,()=>{n.fakeTopEventTask||(n.fakeTopEventTask=Zone.root.scheduleEventTask(\"fakeTopEventTask\",()=>{n.lastRequestAnimationFrameId=-1,Up(n),n.isCheckStableRunning=!0,zp(n),n.isCheckStableRunning=!1},void 0,()=>{},()=>{})),n.fakeTopEventTask.invoke()}),Up(n))}(n)};n._inner=n._inner.fork({name:\"angular\",properties:{isAngularZone:!0},onInvokeTask:(e,i,r,s,o,a)=>{try{return F0(n),e.invokeTask(r,s,o,a)}finally{(n.shouldCoalesceEventChangeDetection&&\"eventTask\"===s.type||n.shouldCoalesceRunChangeDetection)&&t(),N0(n)}},onInvoke:(e,i,r,s,o,a,l)=>{try{return F0(n),e.invoke(r,s,o,a,l)}finally{n.shouldCoalesceRunChangeDetection&&t(),N0(n)}},onHasTask:(e,i,r,s)=>{e.hasTask(r,s),i===r&&(\"microTask\"==s.change?(n._hasPendingMicrotasks=s.microTask,Up(n),zp(n)):\"macroTask\"==s.change&&(n.hasPendingMacrotasks=s.macroTask))},onHandleError:(e,i,r,s)=>(e.handleError(r,s),n.runOutsideAngular(()=>n.onError.emit(s)),!1)})}(r)}static isInAngularZone(){return\"undefined\"!=typeof Zone&&!0===Zone.current.get(\"isAngularZone\")}static assertInAngularZone(){if(!ne.isInAngularZone())throw new Error(\"Expected to be in Angular Zone, but it is not!\")}static assertNotInAngularZone(){if(ne.isInAngularZone())throw new Error(\"Expected to not be in Angular Zone, but it is!\")}run(t,e,i){return this._inner.run(t,e,i)}runTask(t,e,i,r){const s=this._inner,o=s.scheduleEventTask(\"NgZoneEvent: \"+r,t,FF,yc,yc);try{return s.runTask(o,e,i)}finally{s.cancelTask(o)}}runGuarded(t,e,i){return this._inner.runGuarded(t,e,i)}runOutsideAngular(t){return this._outer.run(t)}}const FF={};function zp(n){if(0==n._nesting&&!n.hasPendingMicrotasks&&!n.isStable)try{n._nesting++,n.onMicrotaskEmpty.emit(null)}finally{if(n._nesting--,!n.hasPendingMicrotasks)try{n.runOutsideAngular(()=>n.onStable.emit(null))}finally{n.isStable=!0}}}function Up(n){n.hasPendingMicrotasks=!!(n._hasPendingMicrotasks||(n.shouldCoalesceEventChangeDetection||n.shouldCoalesceRunChangeDetection)&&-1!==n.lastRequestAnimationFrameId)}function F0(n){n._nesting++,n.isStable&&(n.isStable=!1,n.onUnstable.emit(null))}function N0(n){n._nesting--,zp(n)}class BF{constructor(){this.hasPendingMicrotasks=!1,this.hasPendingMacrotasks=!1,this.isStable=!0,this.onUnstable=new $,this.onMicrotaskEmpty=new $,this.onStable=new $,this.onError=new $}run(t,e,i){return t.apply(e,i)}runGuarded(t,e,i){return t.apply(e,i)}runOutsideAngular(t){return t()}runTask(t,e,i,r){return t.apply(e,i)}}let $p=(()=>{class n{constructor(e){this._ngZone=e,this._pendingCount=0,this._isZoneStable=!0,this._didWork=!1,this._callbacks=[],this.taskTrackingZone=null,this._watchAngularEvents(),e.run(()=>{this.taskTrackingZone=\"undefined\"==typeof Zone?null:Zone.current.get(\"TaskTrackingZone\")})}_watchAngularEvents(){this._ngZone.onUnstable.subscribe({next:()=>{this._didWork=!0,this._isZoneStable=!1}}),this._ngZone.runOutsideAngular(()=>{this._ngZone.onStable.subscribe({next:()=>{ne.assertNotInAngularZone(),jp(()=>{this._isZoneStable=!0,this._runCallbacksIfReady()})}})})}increasePendingRequestCount(){return this._pendingCount+=1,this._didWork=!0,this._pendingCount}decreasePendingRequestCount(){if(this._pendingCount-=1,this._pendingCount<0)throw new Error(\"pending async requests below zero\");return this._runCallbacksIfReady(),this._pendingCount}isStable(){return this._isZoneStable&&0===this._pendingCount&&!this._ngZone.hasPendingMacrotasks}_runCallbacksIfReady(){if(this.isStable())jp(()=>{for(;0!==this._callbacks.length;){let e=this._callbacks.pop();clearTimeout(e.timeoutId),e.doneCb(this._didWork)}this._didWork=!1});else{let e=this.getPendingTasks();this._callbacks=this._callbacks.filter(i=>!i.updateCb||!i.updateCb(e)||(clearTimeout(i.timeoutId),!1)),this._didWork=!0}}getPendingTasks(){return this.taskTrackingZone?this.taskTrackingZone.macroTasks.map(e=>({source:e.source,creationLocation:e.creationLocation,data:e.data})):[]}addCallback(e,i,r){let s=-1;i&&i>0&&(s=setTimeout(()=>{this._callbacks=this._callbacks.filter(o=>o.timeoutId!==s),e(this._didWork,this.getPendingTasks())},i)),this._callbacks.push({doneCb:e,timeoutId:s,updateCb:r})}whenStable(e,i,r){if(r&&!this.taskTrackingZone)throw new Error('Task tracking zone is required when passing an update callback to whenStable(). Is \"zone.js/plugins/task-tracking\" loaded?');this.addCallback(e,i,r),this._runCallbacksIfReady()}getPendingRequestCount(){return this._pendingCount}findProviders(e,i,r){return[]}}return n.\\u0275fac=function(e){return new(e||n)(y(ne))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),L0=(()=>{class n{constructor(){this._applications=new Map,Gp.addToWindow(this)}registerApplication(e,i){this._applications.set(e,i)}unregisterApplication(e){this._applications.delete(e)}unregisterAllApplications(){this._applications.clear()}getTestability(e){return this._applications.get(e)||null}getAllTestabilities(){return Array.from(this._applications.values())}getAllRootElements(){return Array.from(this._applications.keys())}findTestabilityInTree(e,i=!0){return Gp.findTestabilityInTree(this,e,i)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class VF{addToWindow(t){}findTestabilityInTree(t,e,i){return null}}let Qn,Gp=new VF;const B0=new b(\"AllowMultipleToken\");class V0{constructor(t,e){this.name=t,this.token=e}}function H0(n,t,e=[]){const i=`Platform: ${t}`,r=new b(i);return(s=[])=>{let o=j0();if(!o||o.injector.get(B0,!1))if(n)n(e.concat(s).concat({provide:r,useValue:!0}));else{const a=e.concat(s).concat({provide:r,useValue:!0},{provide:Jh,useValue:\"platform\"});!function UF(n){if(Qn&&!Qn.destroyed&&!Qn.injector.get(B0,!1))throw new H(400,\"\");Qn=n.get(z0);const t=n.get(I0,null);t&&t.forEach(e=>e())}(dt.create({providers:a,name:i}))}return function $F(n){const t=j0();if(!t)throw new H(401,\"\");return t}()}}function j0(){return Qn&&!Qn.destroyed?Qn:null}let z0=(()=>{class n{constructor(e){this._injector=e,this._modules=[],this._destroyListeners=[],this._destroyed=!1}bootstrapModuleFactory(e,i){const a=function GF(n,t){let e;return e=\"noop\"===n?new BF:(\"zone.js\"===n?void 0:n)||new ne({enableLongStackTrace:!1,shouldCoalesceEventChangeDetection:!!(null==t?void 0:t.ngZoneEventCoalescing),shouldCoalesceRunChangeDetection:!!(null==t?void 0:t.ngZoneRunCoalescing)}),e}(i?i.ngZone:void 0,{ngZoneEventCoalescing:i&&i.ngZoneEventCoalescing||!1,ngZoneRunCoalescing:i&&i.ngZoneRunCoalescing||!1}),l=[{provide:ne,useValue:a}];return a.run(()=>{const c=dt.create({providers:l,parent:this.injector,name:e.moduleType.name}),d=e.create(c),u=d.injector.get(Mr,null);if(!u)throw new H(402,\"\");return a.runOutsideAngular(()=>{const h=a.onError.subscribe({next:p=>{u.handleError(p)}});d.onDestroy(()=>{Wp(this._modules,d),h.unsubscribe()})}),function WF(n,t,e){try{const i=e();return ra(i)?i.catch(r=>{throw t.runOutsideAngular(()=>n.handleError(r)),r}):i}catch(i){throw t.runOutsideAngular(()=>n.handleError(i)),i}}(u,a,()=>{const h=d.injector.get(Vp);return h.runInitializers(),h.donePromise.then(()=>(function MO(n){tn(n,\"Expected localeId to be defined\"),\"string\"==typeof n&&(CC=n.toLowerCase().replace(/_/g,\"-\"))}(d.injector.get(Oi,cc)||cc),this._moduleDoBootstrap(d),d))})})}bootstrapModule(e,i=[]){const r=U0({},i);return function jF(n,t,e){const i=new xp(e);return Promise.resolve(i)}(0,0,e).then(s=>this.bootstrapModuleFactory(s,r))}_moduleDoBootstrap(e){const i=e.injector.get(Cc);if(e._bootstrapComponents.length>0)e._bootstrapComponents.forEach(r=>i.bootstrap(r));else{if(!e.instance.ngDoBootstrap)throw new H(403,\"\");e.instance.ngDoBootstrap(i)}this._modules.push(e)}onDestroy(e){this._destroyListeners.push(e)}get injector(){return this._injector}destroy(){if(this._destroyed)throw new H(404,\"\");this._modules.slice().forEach(e=>e.destroy()),this._destroyListeners.forEach(e=>e()),this._destroyed=!0}get destroyed(){return this._destroyed}}return n.\\u0275fac=function(e){return new(e||n)(y(dt))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();function U0(n,t){return Array.isArray(t)?t.reduce(U0,n):Object.assign(Object.assign({},n),t)}let Cc=(()=>{class n{constructor(e,i,r,s,o){this._zone=e,this._injector=i,this._exceptionHandler=r,this._componentFactoryResolver=s,this._initStatus=o,this._bootstrapListeners=[],this._views=[],this._runningTick=!1,this._stable=!0,this.componentTypes=[],this.components=[],this._onMicrotaskEmptySubscription=this._zone.onMicrotaskEmpty.subscribe({next:()=>{this._zone.run(()=>{this.tick()})}});const a=new Ve(c=>{this._stable=this._zone.isStable&&!this._zone.hasPendingMacrotasks&&!this._zone.hasPendingMicrotasks,this._zone.runOutsideAngular(()=>{c.next(this._stable),c.complete()})}),l=new Ve(c=>{let d;this._zone.runOutsideAngular(()=>{d=this._zone.onStable.subscribe(()=>{ne.assertNotInAngularZone(),jp(()=>{!this._stable&&!this._zone.hasPendingMacrotasks&&!this._zone.hasPendingMicrotasks&&(this._stable=!0,c.next(!0))})})});const u=this._zone.onUnstable.subscribe(()=>{ne.assertInAngularZone(),this._stable&&(this._stable=!1,this._zone.runOutsideAngular(()=>{c.next(!1)}))});return()=>{d.unsubscribe(),u.unsubscribe()}});this.isStable=Bt(a,l.pipe(function M_(n={}){const{connector:t=(()=>new O),resetOnError:e=!0,resetOnComplete:i=!0,resetOnRefCountZero:r=!0}=n;return s=>{let o=null,a=null,l=null,c=0,d=!1,u=!1;const h=()=>{null==a||a.unsubscribe(),a=null},p=()=>{h(),o=l=null,d=u=!1},m=()=>{const g=o;p(),null==g||g.unsubscribe()};return qe((g,_)=>{c++,!u&&!d&&h();const D=l=null!=l?l:t();_.add(()=>{c--,0===c&&!u&&!d&&(a=Du(m,r))}),D.subscribe(_),o||(o=new vl({next:v=>D.next(v),error:v=>{u=!0,h(),a=Du(p,e,v),D.error(v)},complete:()=>{d=!0,h(),a=Du(p,i),D.complete()}}),mt(g).subscribe(o))})(s)}}()))}bootstrap(e,i){if(!this._initStatus.done)throw new H(405,\"\");let r;r=e instanceof WC?e:this._componentFactoryResolver.resolveComponentFactory(e),this.componentTypes.push(r.componentType);const s=function zF(n){return n.isBoundToModule}(r)?void 0:this._injector.get(Ri),a=r.create(dt.NULL,[],i||r.selector,s),l=a.location.nativeElement,c=a.injector.get($p,null),d=c&&a.injector.get(L0);return c&&d&&d.registerApplication(l,c),a.onDestroy(()=>{this.detachView(a.hostView),Wp(this.components,a),d&&d.unregisterApplication(l)}),this._loadComponent(a),a}tick(){if(this._runningTick)throw new H(101,\"\");try{this._runningTick=!0;for(let e of this._views)e.detectChanges()}catch(e){this._zone.runOutsideAngular(()=>this._exceptionHandler.handleError(e))}finally{this._runningTick=!1}}attachView(e){const i=e;this._views.push(i),i.attachToAppRef(this)}detachView(e){const i=e;Wp(this._views,i),i.detachFromAppRef()}_loadComponent(e){this.attachView(e.hostView),this.tick(),this.components.push(e),this._injector.get(R0,[]).concat(this._bootstrapListeners).forEach(r=>r(e))}ngOnDestroy(){this._views.slice().forEach(e=>e.destroy()),this._onMicrotaskEmptySubscription.unsubscribe()}get viewCount(){return this._views.length}}return n.\\u0275fac=function(e){return new(e||n)(y(ne),y(dt),y(Mr),y(Ir),y(Vp))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();function Wp(n,t){const e=n.indexOf(t);e>-1&&n.splice(e,1)}let G0=!0,Ye=(()=>{class n{}return n.__NG_ELEMENT_ID__=QF,n})();function QF(n){return function KF(n,t,e){if(El(n)&&!e){const i=rn(n.index,t);return new ua(i,i)}return 47&n.type?new ua(t[16],t):null}(gt(),w(),16==(16&n))}class K0{constructor(){}supports(t){return ta(t)}create(t){return new nN(t)}}const tN=(n,t)=>t;class nN{constructor(t){this.length=0,this._linkedRecords=null,this._unlinkedRecords=null,this._previousItHead=null,this._itHead=null,this._itTail=null,this._additionsHead=null,this._additionsTail=null,this._movesHead=null,this._movesTail=null,this._removalsHead=null,this._removalsTail=null,this._identityChangesHead=null,this._identityChangesTail=null,this._trackByFn=t||tN}forEachItem(t){let e;for(e=this._itHead;null!==e;e=e._next)t(e)}forEachOperation(t){let e=this._itHead,i=this._removalsHead,r=0,s=null;for(;e||i;){const o=!i||e&&e.currentIndex<X0(i,r,s)?e:i,a=X0(o,r,s),l=o.currentIndex;if(o===i)r--,i=i._nextRemoved;else if(e=e._next,null==o.previousIndex)r++;else{s||(s=[]);const c=a-r,d=l-r;if(c!=d){for(let h=0;h<c;h++){const p=h<s.length?s[h]:s[h]=0,m=p+h;d<=m&&m<c&&(s[h]=p+1)}s[o.previousIndex]=d-c}}a!==l&&t(o,a,l)}}forEachPreviousItem(t){let e;for(e=this._previousItHead;null!==e;e=e._nextPrevious)t(e)}forEachAddedItem(t){let e;for(e=this._additionsHead;null!==e;e=e._nextAdded)t(e)}forEachMovedItem(t){let e;for(e=this._movesHead;null!==e;e=e._nextMoved)t(e)}forEachRemovedItem(t){let e;for(e=this._removalsHead;null!==e;e=e._nextRemoved)t(e)}forEachIdentityChange(t){let e;for(e=this._identityChangesHead;null!==e;e=e._nextIdentityChange)t(e)}diff(t){if(null==t&&(t=[]),!ta(t))throw new H(900,\"\");return this.check(t)?this:null}onDestroy(){}check(t){this._reset();let r,s,o,e=this._itHead,i=!1;if(Array.isArray(t)){this.length=t.length;for(let a=0;a<this.length;a++)s=t[a],o=this._trackByFn(a,s),null!==e&&Object.is(e.trackById,o)?(i&&(e=this._verifyReinsertion(e,s,o,a)),Object.is(e.item,s)||this._addIdentityChange(e,s)):(e=this._mismatch(e,s,o,a),i=!0),e=e._next}else r=0,function u1(n,t){if(Array.isArray(n))for(let e=0;e<n.length;e++)t(n[e]);else{const e=n[As()]();let i;for(;!(i=e.next()).done;)t(i.value)}}(t,a=>{o=this._trackByFn(r,a),null!==e&&Object.is(e.trackById,o)?(i&&(e=this._verifyReinsertion(e,a,o,r)),Object.is(e.item,a)||this._addIdentityChange(e,a)):(e=this._mismatch(e,a,o,r),i=!0),e=e._next,r++}),this.length=r;return this._truncate(e),this.collection=t,this.isDirty}get isDirty(){return null!==this._additionsHead||null!==this._movesHead||null!==this._removalsHead||null!==this._identityChangesHead}_reset(){if(this.isDirty){let t;for(t=this._previousItHead=this._itHead;null!==t;t=t._next)t._nextPrevious=t._next;for(t=this._additionsHead;null!==t;t=t._nextAdded)t.previousIndex=t.currentIndex;for(this._additionsHead=this._additionsTail=null,t=this._movesHead;null!==t;t=t._nextMoved)t.previousIndex=t.currentIndex;this._movesHead=this._movesTail=null,this._removalsHead=this._removalsTail=null,this._identityChangesHead=this._identityChangesTail=null}}_mismatch(t,e,i,r){let s;return null===t?s=this._itTail:(s=t._prev,this._remove(t)),null!==(t=null===this._unlinkedRecords?null:this._unlinkedRecords.get(i,null))?(Object.is(t.item,e)||this._addIdentityChange(t,e),this._reinsertAfter(t,s,r)):null!==(t=null===this._linkedRecords?null:this._linkedRecords.get(i,r))?(Object.is(t.item,e)||this._addIdentityChange(t,e),this._moveAfter(t,s,r)):t=this._addAfter(new iN(e,i),s,r),t}_verifyReinsertion(t,e,i,r){let s=null===this._unlinkedRecords?null:this._unlinkedRecords.get(i,null);return null!==s?t=this._reinsertAfter(s,t._prev,r):t.currentIndex!=r&&(t.currentIndex=r,this._addToMoves(t,r)),t}_truncate(t){for(;null!==t;){const e=t._next;this._addToRemovals(this._unlink(t)),t=e}null!==this._unlinkedRecords&&this._unlinkedRecords.clear(),null!==this._additionsTail&&(this._additionsTail._nextAdded=null),null!==this._movesTail&&(this._movesTail._nextMoved=null),null!==this._itTail&&(this._itTail._next=null),null!==this._removalsTail&&(this._removalsTail._nextRemoved=null),null!==this._identityChangesTail&&(this._identityChangesTail._nextIdentityChange=null)}_reinsertAfter(t,e,i){null!==this._unlinkedRecords&&this._unlinkedRecords.remove(t);const r=t._prevRemoved,s=t._nextRemoved;return null===r?this._removalsHead=s:r._nextRemoved=s,null===s?this._removalsTail=r:s._prevRemoved=r,this._insertAfter(t,e,i),this._addToMoves(t,i),t}_moveAfter(t,e,i){return this._unlink(t),this._insertAfter(t,e,i),this._addToMoves(t,i),t}_addAfter(t,e,i){return this._insertAfter(t,e,i),this._additionsTail=null===this._additionsTail?this._additionsHead=t:this._additionsTail._nextAdded=t,t}_insertAfter(t,e,i){const r=null===e?this._itHead:e._next;return t._next=r,t._prev=e,null===r?this._itTail=t:r._prev=t,null===e?this._itHead=t:e._next=t,null===this._linkedRecords&&(this._linkedRecords=new Z0),this._linkedRecords.put(t),t.currentIndex=i,t}_remove(t){return this._addToRemovals(this._unlink(t))}_unlink(t){null!==this._linkedRecords&&this._linkedRecords.remove(t);const e=t._prev,i=t._next;return null===e?this._itHead=i:e._next=i,null===i?this._itTail=e:i._prev=e,t}_addToMoves(t,e){return t.previousIndex===e||(this._movesTail=null===this._movesTail?this._movesHead=t:this._movesTail._nextMoved=t),t}_addToRemovals(t){return null===this._unlinkedRecords&&(this._unlinkedRecords=new Z0),this._unlinkedRecords.put(t),t.currentIndex=null,t._nextRemoved=null,null===this._removalsTail?(this._removalsTail=this._removalsHead=t,t._prevRemoved=null):(t._prevRemoved=this._removalsTail,this._removalsTail=this._removalsTail._nextRemoved=t),t}_addIdentityChange(t,e){return t.item=e,this._identityChangesTail=null===this._identityChangesTail?this._identityChangesHead=t:this._identityChangesTail._nextIdentityChange=t,t}}class iN{constructor(t,e){this.item=t,this.trackById=e,this.currentIndex=null,this.previousIndex=null,this._nextPrevious=null,this._prev=null,this._next=null,this._prevDup=null,this._nextDup=null,this._prevRemoved=null,this._nextRemoved=null,this._nextAdded=null,this._nextMoved=null,this._nextIdentityChange=null}}class rN{constructor(){this._head=null,this._tail=null}add(t){null===this._head?(this._head=this._tail=t,t._nextDup=null,t._prevDup=null):(this._tail._nextDup=t,t._prevDup=this._tail,t._nextDup=null,this._tail=t)}get(t,e){let i;for(i=this._head;null!==i;i=i._nextDup)if((null===e||e<=i.currentIndex)&&Object.is(i.trackById,t))return i;return null}remove(t){const e=t._prevDup,i=t._nextDup;return null===e?this._head=i:e._nextDup=i,null===i?this._tail=e:i._prevDup=e,null===this._head}}class Z0{constructor(){this.map=new Map}put(t){const e=t.trackById;let i=this.map.get(e);i||(i=new rN,this.map.set(e,i)),i.add(t)}get(t,e){const r=this.map.get(t);return r?r.get(t,e):null}remove(t){const e=t.trackById;return this.map.get(e).remove(t)&&this.map.delete(e),t}get isEmpty(){return 0===this.map.size}clear(){this.map.clear()}}function X0(n,t,e){const i=n.previousIndex;if(null===i)return i;let r=0;return e&&i<e.length&&(r=e[i]),i+t+r}class J0{constructor(){}supports(t){return t instanceof Map||sp(t)}create(){return new sN}}class sN{constructor(){this._records=new Map,this._mapHead=null,this._appendAfter=null,this._previousMapHead=null,this._changesHead=null,this._changesTail=null,this._additionsHead=null,this._additionsTail=null,this._removalsHead=null,this._removalsTail=null}get isDirty(){return null!==this._additionsHead||null!==this._changesHead||null!==this._removalsHead}forEachItem(t){let e;for(e=this._mapHead;null!==e;e=e._next)t(e)}forEachPreviousItem(t){let e;for(e=this._previousMapHead;null!==e;e=e._nextPrevious)t(e)}forEachChangedItem(t){let e;for(e=this._changesHead;null!==e;e=e._nextChanged)t(e)}forEachAddedItem(t){let e;for(e=this._additionsHead;null!==e;e=e._nextAdded)t(e)}forEachRemovedItem(t){let e;for(e=this._removalsHead;null!==e;e=e._nextRemoved)t(e)}diff(t){if(t){if(!(t instanceof Map||sp(t)))throw new H(900,\"\")}else t=new Map;return this.check(t)?this:null}onDestroy(){}check(t){this._reset();let e=this._mapHead;if(this._appendAfter=null,this._forEach(t,(i,r)=>{if(e&&e.key===r)this._maybeAddToChanges(e,i),this._appendAfter=e,e=e._next;else{const s=this._getOrCreateRecordForKey(r,i);e=this._insertBeforeOrAppend(e,s)}}),e){e._prev&&(e._prev._next=null),this._removalsHead=e;for(let i=e;null!==i;i=i._nextRemoved)i===this._mapHead&&(this._mapHead=null),this._records.delete(i.key),i._nextRemoved=i._next,i.previousValue=i.currentValue,i.currentValue=null,i._prev=null,i._next=null}return this._changesTail&&(this._changesTail._nextChanged=null),this._additionsTail&&(this._additionsTail._nextAdded=null),this.isDirty}_insertBeforeOrAppend(t,e){if(t){const i=t._prev;return e._next=t,e._prev=i,t._prev=e,i&&(i._next=e),t===this._mapHead&&(this._mapHead=e),this._appendAfter=t,t}return this._appendAfter?(this._appendAfter._next=e,e._prev=this._appendAfter):this._mapHead=e,this._appendAfter=e,null}_getOrCreateRecordForKey(t,e){if(this._records.has(t)){const r=this._records.get(t);this._maybeAddToChanges(r,e);const s=r._prev,o=r._next;return s&&(s._next=o),o&&(o._prev=s),r._next=null,r._prev=null,r}const i=new oN(t);return this._records.set(t,i),i.currentValue=e,this._addToAdditions(i),i}_reset(){if(this.isDirty){let t;for(this._previousMapHead=this._mapHead,t=this._previousMapHead;null!==t;t=t._next)t._nextPrevious=t._next;for(t=this._changesHead;null!==t;t=t._nextChanged)t.previousValue=t.currentValue;for(t=this._additionsHead;null!=t;t=t._nextAdded)t.previousValue=t.currentValue;this._changesHead=this._changesTail=null,this._additionsHead=this._additionsTail=null,this._removalsHead=null}}_maybeAddToChanges(t,e){Object.is(e,t.currentValue)||(t.previousValue=t.currentValue,t.currentValue=e,this._addToChanges(t))}_addToAdditions(t){null===this._additionsHead?this._additionsHead=this._additionsTail=t:(this._additionsTail._nextAdded=t,this._additionsTail=t)}_addToChanges(t){null===this._changesHead?this._changesHead=this._changesTail=t:(this._changesTail._nextChanged=t,this._changesTail=t)}_forEach(t,e){t instanceof Map?t.forEach(e):Object.keys(t).forEach(i=>e(t[i],i))}}class oN{constructor(t){this.key=t,this.previousValue=null,this.currentValue=null,this._nextPrevious=null,this._next=null,this._prev=null,this._nextAdded=null,this._nextRemoved=null,this._nextChanged=null}}function eD(){return new xn([new K0])}let xn=(()=>{class n{constructor(e){this.factories=e}static create(e,i){if(null!=i){const r=i.factories.slice();e=e.concat(r)}return new n(e)}static extend(e){return{provide:n,useFactory:i=>n.create(e,i||eD()),deps:[[n,new Cn,new Tt]]}}find(e){const i=this.factories.find(r=>r.supports(e));if(null!=i)return i;throw new H(901,\"\")}}return n.\\u0275prov=k({token:n,providedIn:\"root\",factory:eD}),n})();function tD(){return new _a([new J0])}let _a=(()=>{class n{constructor(e){this.factories=e}static create(e,i){if(i){const r=i.factories.slice();e=e.concat(r)}return new n(e)}static extend(e){return{provide:n,useFactory:i=>n.create(e,i||tD()),deps:[[n,new Cn,new Tt]]}}find(e){const i=this.factories.find(s=>s.supports(e));if(i)return i;throw new H(901,\"\")}}return n.\\u0275prov=k({token:n,providedIn:\"root\",factory:tD}),n})();const cN=H0(null,\"core\",[{provide:bc,useValue:\"unknown\"},{provide:z0,deps:[dt]},{provide:L0,deps:[]},{provide:O0,deps:[]}]);let dN=(()=>{class n{constructor(e){}}return n.\\u0275fac=function(e){return new(e||n)(y(Cc))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),Mc=null;function mi(){return Mc}const ie=new b(\"DocumentToken\");let Pr=(()=>{class n{historyGo(e){throw new Error(\"Not implemented\")}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:function(){return function fN(){return y(nD)}()},providedIn:\"platform\"}),n})();const mN=new b(\"Location Initialized\");let nD=(()=>{class n extends Pr{constructor(e){super(),this._doc=e,this._init()}_init(){this.location=window.location,this._history=window.history}getBaseHrefFromDOM(){return mi().getBaseHref(this._doc)}onPopState(e){const i=mi().getGlobalEventTarget(this._doc,\"window\");return i.addEventListener(\"popstate\",e,!1),()=>i.removeEventListener(\"popstate\",e)}onHashChange(e){const i=mi().getGlobalEventTarget(this._doc,\"window\");return i.addEventListener(\"hashchange\",e,!1),()=>i.removeEventListener(\"hashchange\",e)}get href(){return this.location.href}get protocol(){return this.location.protocol}get hostname(){return this.location.hostname}get port(){return this.location.port}get pathname(){return this.location.pathname}get search(){return this.location.search}get hash(){return this.location.hash}set pathname(e){this.location.pathname=e}pushState(e,i,r){iD()?this._history.pushState(e,i,r):this.location.hash=r}replaceState(e,i,r){iD()?this._history.replaceState(e,i,r):this.location.hash=r}forward(){this._history.forward()}back(){this._history.back()}historyGo(e=0){this._history.go(e)}getState(){return this._history.state}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:function(){return function gN(){return new nD(y(ie))}()},providedIn:\"platform\"}),n})();function iD(){return!!window.history.pushState}function Zp(n,t){if(0==n.length)return t;if(0==t.length)return n;let e=0;return n.endsWith(\"/\")&&e++,t.startsWith(\"/\")&&e++,2==e?n+t.substring(1):1==e?n+t:n+\"/\"+t}function rD(n){const t=n.match(/#|\\?|$/),e=t&&t.index||n.length;return n.slice(0,e-(\"/\"===n[e-1]?1:0))+n.slice(e)}function Pi(n){return n&&\"?\"!==n[0]?\"?\"+n:n}let qs=(()=>{class n{historyGo(e){throw new Error(\"Not implemented\")}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:function(){return function _N(n){const t=y(ie).location;return new sD(y(Pr),t&&t.origin||\"\")}()},providedIn:\"root\"}),n})();const Xp=new b(\"appBaseHref\");let sD=(()=>{class n extends qs{constructor(e,i){if(super(),this._platformLocation=e,this._removeListenerFns=[],null==i&&(i=this._platformLocation.getBaseHrefFromDOM()),null==i)throw new Error(\"No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.\");this._baseHref=i}ngOnDestroy(){for(;this._removeListenerFns.length;)this._removeListenerFns.pop()()}onPopState(e){this._removeListenerFns.push(this._platformLocation.onPopState(e),this._platformLocation.onHashChange(e))}getBaseHref(){return this._baseHref}prepareExternalUrl(e){return Zp(this._baseHref,e)}path(e=!1){const i=this._platformLocation.pathname+Pi(this._platformLocation.search),r=this._platformLocation.hash;return r&&e?`${i}${r}`:i}pushState(e,i,r,s){const o=this.prepareExternalUrl(r+Pi(s));this._platformLocation.pushState(e,i,o)}replaceState(e,i,r,s){const o=this.prepareExternalUrl(r+Pi(s));this._platformLocation.replaceState(e,i,o)}forward(){this._platformLocation.forward()}back(){this._platformLocation.back()}historyGo(e=0){var i,r;null===(r=(i=this._platformLocation).historyGo)||void 0===r||r.call(i,e)}}return n.\\u0275fac=function(e){return new(e||n)(y(Pr),y(Xp,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),vN=(()=>{class n extends qs{constructor(e,i){super(),this._platformLocation=e,this._baseHref=\"\",this._removeListenerFns=[],null!=i&&(this._baseHref=i)}ngOnDestroy(){for(;this._removeListenerFns.length;)this._removeListenerFns.pop()()}onPopState(e){this._removeListenerFns.push(this._platformLocation.onPopState(e),this._platformLocation.onHashChange(e))}getBaseHref(){return this._baseHref}path(e=!1){let i=this._platformLocation.hash;return null==i&&(i=\"#\"),i.length>0?i.substring(1):i}prepareExternalUrl(e){const i=Zp(this._baseHref,e);return i.length>0?\"#\"+i:i}pushState(e,i,r,s){let o=this.prepareExternalUrl(r+Pi(s));0==o.length&&(o=this._platformLocation.pathname),this._platformLocation.pushState(e,i,o)}replaceState(e,i,r,s){let o=this.prepareExternalUrl(r+Pi(s));0==o.length&&(o=this._platformLocation.pathname),this._platformLocation.replaceState(e,i,o)}forward(){this._platformLocation.forward()}back(){this._platformLocation.back()}historyGo(e=0){var i,r;null===(r=(i=this._platformLocation).historyGo)||void 0===r||r.call(i,e)}}return n.\\u0275fac=function(e){return new(e||n)(y(Pr),y(Xp,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),va=(()=>{class n{constructor(e,i){this._subject=new $,this._urlChangeListeners=[],this._platformStrategy=e;const r=this._platformStrategy.getBaseHref();this._platformLocation=i,this._baseHref=rD(oD(r)),this._platformStrategy.onPopState(s=>{this._subject.emit({url:this.path(!0),pop:!0,state:s.state,type:s.type})})}path(e=!1){return this.normalize(this._platformStrategy.path(e))}getState(){return this._platformLocation.getState()}isCurrentPathEqualTo(e,i=\"\"){return this.path()==this.normalize(e+Pi(i))}normalize(e){return n.stripTrailingSlash(function bN(n,t){return n&&t.startsWith(n)?t.substring(n.length):t}(this._baseHref,oD(e)))}prepareExternalUrl(e){return e&&\"/\"!==e[0]&&(e=\"/\"+e),this._platformStrategy.prepareExternalUrl(e)}go(e,i=\"\",r=null){this._platformStrategy.pushState(r,\"\",e,i),this._notifyUrlChangeListeners(this.prepareExternalUrl(e+Pi(i)),r)}replaceState(e,i=\"\",r=null){this._platformStrategy.replaceState(r,\"\",e,i),this._notifyUrlChangeListeners(this.prepareExternalUrl(e+Pi(i)),r)}forward(){this._platformStrategy.forward()}back(){this._platformStrategy.back()}historyGo(e=0){var i,r;null===(r=(i=this._platformStrategy).historyGo)||void 0===r||r.call(i,e)}onUrlChange(e){this._urlChangeListeners.push(e),this._urlChangeSubscription||(this._urlChangeSubscription=this.subscribe(i=>{this._notifyUrlChangeListeners(i.url,i.state)}))}_notifyUrlChangeListeners(e=\"\",i){this._urlChangeListeners.forEach(r=>r(e,i))}subscribe(e,i,r){return this._subject.subscribe({next:e,error:i,complete:r})}}return n.normalizeQueryParams=Pi,n.joinWithSlash=Zp,n.stripTrailingSlash=rD,n.\\u0275fac=function(e){return new(e||n)(y(qs),y(Pr))},n.\\u0275prov=k({token:n,factory:function(){return function yN(){return new va(y(qs),y(Pr))}()},providedIn:\"root\"}),n})();function oD(n){return n.replace(/\\/index.html$/,\"\")}let mD=(()=>{class n{constructor(e,i,r,s){this._iterableDiffers=e,this._keyValueDiffers=i,this._ngEl=r,this._renderer=s,this._iterableDiffer=null,this._keyValueDiffer=null,this._initialClasses=[],this._rawClass=null}set klass(e){this._removeClasses(this._initialClasses),this._initialClasses=\"string\"==typeof e?e.split(/\\s+/):[],this._applyClasses(this._initialClasses),this._applyClasses(this._rawClass)}set ngClass(e){this._removeClasses(this._rawClass),this._applyClasses(this._initialClasses),this._iterableDiffer=null,this._keyValueDiffer=null,this._rawClass=\"string\"==typeof e?e.split(/\\s+/):e,this._rawClass&&(ta(this._rawClass)?this._iterableDiffer=this._iterableDiffers.find(this._rawClass).create():this._keyValueDiffer=this._keyValueDiffers.find(this._rawClass).create())}ngDoCheck(){if(this._iterableDiffer){const e=this._iterableDiffer.diff(this._rawClass);e&&this._applyIterableChanges(e)}else if(this._keyValueDiffer){const e=this._keyValueDiffer.diff(this._rawClass);e&&this._applyKeyValueChanges(e)}}_applyKeyValueChanges(e){e.forEachAddedItem(i=>this._toggleClass(i.key,i.currentValue)),e.forEachChangedItem(i=>this._toggleClass(i.key,i.currentValue)),e.forEachRemovedItem(i=>{i.previousValue&&this._toggleClass(i.key,!1)})}_applyIterableChanges(e){e.forEachAddedItem(i=>{if(\"string\"!=typeof i.item)throw new Error(`NgClass can only toggle CSS classes expressed as strings, got ${Re(i.item)}`);this._toggleClass(i.item,!0)}),e.forEachRemovedItem(i=>this._toggleClass(i.item,!1))}_applyClasses(e){e&&(Array.isArray(e)||e instanceof Set?e.forEach(i=>this._toggleClass(i,!0)):Object.keys(e).forEach(i=>this._toggleClass(i,!!e[i])))}_removeClasses(e){e&&(Array.isArray(e)||e instanceof Set?e.forEach(i=>this._toggleClass(i,!1)):Object.keys(e).forEach(i=>this._toggleClass(i,!1)))}_toggleClass(e,i){(e=e.trim())&&e.split(/\\s+/g).forEach(r=>{i?this._renderer.addClass(this._ngEl.nativeElement,r):this._renderer.removeClass(this._ngEl.nativeElement,r)})}}return n.\\u0275fac=function(e){return new(e||n)(f(xn),f(_a),f(W),f(Ii))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngClass\",\"\"]],inputs:{klass:[\"class\",\"klass\"],ngClass:\"ngClass\"}}),n})();class sL{constructor(t,e,i,r){this.$implicit=t,this.ngForOf=e,this.index=i,this.count=r}get first(){return 0===this.index}get last(){return this.index===this.count-1}get even(){return this.index%2==0}get odd(){return!this.even}}let gD=(()=>{class n{constructor(e,i,r){this._viewContainer=e,this._template=i,this._differs=r,this._ngForOf=null,this._ngForOfDirty=!0,this._differ=null}set ngForOf(e){this._ngForOf=e,this._ngForOfDirty=!0}set ngForTrackBy(e){this._trackByFn=e}get ngForTrackBy(){return this._trackByFn}set ngForTemplate(e){e&&(this._template=e)}ngDoCheck(){if(this._ngForOfDirty){this._ngForOfDirty=!1;const e=this._ngForOf;!this._differ&&e&&(this._differ=this._differs.find(e).create(this.ngForTrackBy))}if(this._differ){const e=this._differ.diff(this._ngForOf);e&&this._applyChanges(e)}}_applyChanges(e){const i=this._viewContainer;e.forEachOperation((r,s,o)=>{if(null==r.previousIndex)i.createEmbeddedView(this._template,new sL(r.item,this._ngForOf,-1,-1),null===o?void 0:o);else if(null==o)i.remove(null===s?void 0:s);else if(null!==s){const a=i.get(s);i.move(a,o),_D(a,r)}});for(let r=0,s=i.length;r<s;r++){const a=i.get(r).context;a.index=r,a.count=s,a.ngForOf=this._ngForOf}e.forEachIdentityChange(r=>{_D(i.get(r.currentIndex),r)})}static ngTemplateContextGuard(e,i){return!0}}return n.\\u0275fac=function(e){return new(e||n)(f(st),f(ut),f(xn))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngFor\",\"\",\"ngForOf\",\"\"]],inputs:{ngForOf:\"ngForOf\",ngForTrackBy:\"ngForTrackBy\",ngForTemplate:\"ngForTemplate\"}}),n})();function _D(n,t){n.context.$implicit=t.item}let Ca=(()=>{class n{constructor(e,i){this._viewContainer=e,this._context=new oL,this._thenTemplateRef=null,this._elseTemplateRef=null,this._thenViewRef=null,this._elseViewRef=null,this._thenTemplateRef=i}set ngIf(e){this._context.$implicit=this._context.ngIf=e,this._updateView()}set ngIfThen(e){vD(\"ngIfThen\",e),this._thenTemplateRef=e,this._thenViewRef=null,this._updateView()}set ngIfElse(e){vD(\"ngIfElse\",e),this._elseTemplateRef=e,this._elseViewRef=null,this._updateView()}_updateView(){this._context.$implicit?this._thenViewRef||(this._viewContainer.clear(),this._elseViewRef=null,this._thenTemplateRef&&(this._thenViewRef=this._viewContainer.createEmbeddedView(this._thenTemplateRef,this._context))):this._elseViewRef||(this._viewContainer.clear(),this._thenViewRef=null,this._elseTemplateRef&&(this._elseViewRef=this._viewContainer.createEmbeddedView(this._elseTemplateRef,this._context)))}static ngTemplateContextGuard(e,i){return!0}}return n.\\u0275fac=function(e){return new(e||n)(f(st),f(ut))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngIf\",\"\"]],inputs:{ngIf:\"ngIf\",ngIfThen:\"ngIfThen\",ngIfElse:\"ngIfElse\"}}),n})();class oL{constructor(){this.$implicit=null,this.ngIf=null}}function vD(n,t){if(t&&!t.createEmbeddedView)throw new Error(`${n} must be a TemplateRef, but received '${Re(t)}'.`)}class df{constructor(t,e){this._viewContainerRef=t,this._templateRef=e,this._created=!1}create(){this._created=!0,this._viewContainerRef.createEmbeddedView(this._templateRef)}destroy(){this._created=!1,this._viewContainerRef.clear()}enforceState(t){t&&!this._created?this.create():!t&&this._created&&this.destroy()}}let Ys=(()=>{class n{constructor(){this._defaultUsed=!1,this._caseCount=0,this._lastCaseCheckIndex=0,this._lastCasesMatched=!1}set ngSwitch(e){this._ngSwitch=e,0===this._caseCount&&this._updateDefaultCases(!0)}_addCase(){return this._caseCount++}_addDefault(e){this._defaultViews||(this._defaultViews=[]),this._defaultViews.push(e)}_matchCase(e){const i=e==this._ngSwitch;return this._lastCasesMatched=this._lastCasesMatched||i,this._lastCaseCheckIndex++,this._lastCaseCheckIndex===this._caseCount&&(this._updateDefaultCases(!this._lastCasesMatched),this._lastCaseCheckIndex=0,this._lastCasesMatched=!1),i}_updateDefaultCases(e){if(this._defaultViews&&e!==this._defaultUsed){this._defaultUsed=e;for(let i=0;i<this._defaultViews.length;i++)this._defaultViews[i].enforceState(e)}}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngSwitch\",\"\"]],inputs:{ngSwitch:\"ngSwitch\"}}),n})(),Pc=(()=>{class n{constructor(e,i,r){this.ngSwitch=r,r._addCase(),this._view=new df(e,i)}ngDoCheck(){this._view.enforceState(this.ngSwitch._matchCase(this.ngSwitchCase))}}return n.\\u0275fac=function(e){return new(e||n)(f(st),f(ut),f(Ys,9))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngSwitchCase\",\"\"]],inputs:{ngSwitchCase:\"ngSwitchCase\"}}),n})(),yD=(()=>{class n{constructor(e,i,r){r._addDefault(new df(e,i))}}return n.\\u0275fac=function(e){return new(e||n)(f(st),f(ut),f(Ys,9))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"ngSwitchDefault\",\"\"]]}),n})(),bt=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const wD=\"browser\";let PL=(()=>{class n{}return n.\\u0275prov=k({token:n,providedIn:\"root\",factory:()=>new FL(y(ie),window)}),n})();class FL{constructor(t,e){this.document=t,this.window=e,this.offset=()=>[0,0]}setOffset(t){this.offset=Array.isArray(t)?()=>t:t}getScrollPosition(){return this.supportsScrolling()?[this.window.pageXOffset,this.window.pageYOffset]:[0,0]}scrollToPosition(t){this.supportsScrolling()&&this.window.scrollTo(t[0],t[1])}scrollToAnchor(t){if(!this.supportsScrolling())return;const e=function NL(n,t){const e=n.getElementById(t)||n.getElementsByName(t)[0];if(e)return e;if(\"function\"==typeof n.createTreeWalker&&n.body&&(n.body.createShadowRoot||n.body.attachShadow)){const i=n.createTreeWalker(n.body,NodeFilter.SHOW_ELEMENT);let r=i.currentNode;for(;r;){const s=r.shadowRoot;if(s){const o=s.getElementById(t)||s.querySelector(`[name=\"${t}\"]`);if(o)return o}r=i.nextNode()}}return null}(this.document,t);e&&(this.scrollToElement(e),e.focus())}setHistoryScrollRestoration(t){if(this.supportScrollRestoration()){const e=this.window.history;e&&e.scrollRestoration&&(e.scrollRestoration=t)}}scrollToElement(t){const e=t.getBoundingClientRect(),i=e.left+this.window.pageXOffset,r=e.top+this.window.pageYOffset,s=this.offset();this.window.scrollTo(i-s[0],r-s[1])}supportScrollRestoration(){try{if(!this.supportsScrolling())return!1;const t=MD(this.window.history)||MD(Object.getPrototypeOf(this.window.history));return!(!t||!t.writable&&!t.set)}catch(t){return!1}}supportsScrolling(){try{return!!this.window&&!!this.window.scrollTo&&\"pageXOffset\"in this.window}catch(t){return!1}}}function MD(n){return Object.getOwnPropertyDescriptor(n,\"scrollRestoration\")}class pf extends class BL extends class pN{}{constructor(){super(...arguments),this.supportsDOMEvents=!0}}{static makeCurrent(){!function hN(n){Mc||(Mc=n)}(new pf)}onAndCancel(t,e,i){return t.addEventListener(e,i,!1),()=>{t.removeEventListener(e,i,!1)}}dispatchEvent(t,e){t.dispatchEvent(e)}remove(t){t.parentNode&&t.parentNode.removeChild(t)}createElement(t,e){return(e=e||this.getDefaultDocument()).createElement(t)}createHtmlDocument(){return document.implementation.createHTMLDocument(\"fakeTitle\")}getDefaultDocument(){return document}isElementNode(t){return t.nodeType===Node.ELEMENT_NODE}isShadowRoot(t){return t instanceof DocumentFragment}getGlobalEventTarget(t,e){return\"window\"===e?window:\"document\"===e?t:\"body\"===e?t.body:null}getBaseHref(t){const e=function VL(){return Da=Da||document.querySelector(\"base\"),Da?Da.getAttribute(\"href\"):null}();return null==e?null:function HL(n){Fc=Fc||document.createElement(\"a\"),Fc.setAttribute(\"href\",n);const t=Fc.pathname;return\"/\"===t.charAt(0)?t:`/${t}`}(e)}resetBaseElement(){Da=null}getUserAgent(){return window.navigator.userAgent}getCookie(t){return function iL(n,t){t=encodeURIComponent(t);for(const e of n.split(\";\")){const i=e.indexOf(\"=\"),[r,s]=-1==i?[e,\"\"]:[e.slice(0,i),e.slice(i+1)];if(r.trim()===t)return decodeURIComponent(s)}return null}(document.cookie,t)}}let Fc,Da=null;const xD=new b(\"TRANSITION_ID\"),zL=[{provide:Bp,useFactory:function jL(n,t,e){return()=>{e.get(Vp).donePromise.then(()=>{const i=mi(),r=t.querySelectorAll(`style[ng-transition=\"${n}\"]`);for(let s=0;s<r.length;s++)i.remove(r[s])})}},deps:[xD,ie,dt],multi:!0}];class ff{static init(){!function HF(n){Gp=n}(new ff)}addToWindow(t){Oe.getAngularTestability=(i,r=!0)=>{const s=t.findTestabilityInTree(i,r);if(null==s)throw new Error(\"Could not find testability for element.\");return s},Oe.getAllAngularTestabilities=()=>t.getAllTestabilities(),Oe.getAllAngularRootElements=()=>t.getAllRootElements(),Oe.frameworkStabilizers||(Oe.frameworkStabilizers=[]),Oe.frameworkStabilizers.push(i=>{const r=Oe.getAllAngularTestabilities();let s=r.length,o=!1;const a=function(l){o=o||l,s--,0==s&&i(o)};r.forEach(function(l){l.whenStable(a)})})}findTestabilityInTree(t,e,i){if(null==e)return null;const r=t.getTestability(e);return null!=r?r:i?mi().isShadowRoot(e)?this.findTestabilityInTree(t,e.host,!0):this.findTestabilityInTree(t,e.parentElement,!0):null}}let UL=(()=>{class n{build(){return new XMLHttpRequest}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const Nc=new b(\"EventManagerPlugins\");let Lc=(()=>{class n{constructor(e,i){this._zone=i,this._eventNameToPlugin=new Map,e.forEach(r=>r.manager=this),this._plugins=e.slice().reverse()}addEventListener(e,i,r){return this._findPluginFor(i).addEventListener(e,i,r)}addGlobalEventListener(e,i,r){return this._findPluginFor(i).addGlobalEventListener(e,i,r)}getZone(){return this._zone}_findPluginFor(e){const i=this._eventNameToPlugin.get(e);if(i)return i;const r=this._plugins;for(let s=0;s<r.length;s++){const o=r[s];if(o.supports(e))return this._eventNameToPlugin.set(e,o),o}throw new Error(`No event manager plugin found for event ${e}`)}}return n.\\u0275fac=function(e){return new(e||n)(y(Nc),y(ne))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class ED{constructor(t){this._doc=t}addGlobalEventListener(t,e,i){const r=mi().getGlobalEventTarget(this._doc,t);if(!r)throw new Error(`Unsupported event target ${r} for event ${e}`);return this.addEventListener(r,e,i)}}let SD=(()=>{class n{constructor(){this._stylesSet=new Set}addStyles(e){const i=new Set;e.forEach(r=>{this._stylesSet.has(r)||(this._stylesSet.add(r),i.add(r))}),this.onStylesAdded(i)}onStylesAdded(e){}getAllStyles(){return Array.from(this._stylesSet)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),wa=(()=>{class n extends SD{constructor(e){super(),this._doc=e,this._hostNodes=new Map,this._hostNodes.set(e.head,[])}_addStylesToHost(e,i,r){e.forEach(s=>{const o=this._doc.createElement(\"style\");o.textContent=s,r.push(i.appendChild(o))})}addHost(e){const i=[];this._addStylesToHost(this._stylesSet,e,i),this._hostNodes.set(e,i)}removeHost(e){const i=this._hostNodes.get(e);i&&i.forEach(kD),this._hostNodes.delete(e)}onStylesAdded(e){this._hostNodes.forEach((i,r)=>{this._addStylesToHost(e,r,i)})}ngOnDestroy(){this._hostNodes.forEach(e=>e.forEach(kD))}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();function kD(n){mi().remove(n)}const mf={svg:\"http://www.w3.org/2000/svg\",xhtml:\"http://www.w3.org/1999/xhtml\",xlink:\"http://www.w3.org/1999/xlink\",xml:\"http://www.w3.org/XML/1998/namespace\",xmlns:\"http://www.w3.org/2000/xmlns/\",math:\"http://www.w3.org/1998/MathML/\"},gf=/%COMP%/g;function Bc(n,t,e){for(let i=0;i<t.length;i++){let r=t[i];Array.isArray(r)?Bc(n,r,e):(r=r.replace(gf,n),e.push(r))}return e}function ID(n){return t=>{if(\"__ngUnwrap__\"===t)return n;!1===n(t)&&(t.preventDefault(),t.returnValue=!1)}}let Vc=(()=>{class n{constructor(e,i,r){this.eventManager=e,this.sharedStylesHost=i,this.appId=r,this.rendererByCompId=new Map,this.defaultRenderer=new _f(e)}createRenderer(e,i){if(!e||!i)return this.defaultRenderer;switch(i.encapsulation){case Ln.Emulated:{let r=this.rendererByCompId.get(i.id);return r||(r=new QL(this.eventManager,this.sharedStylesHost,i,this.appId),this.rendererByCompId.set(i.id,r)),r.applyToHost(e),r}case 1:case Ln.ShadowDom:return new KL(this.eventManager,this.sharedStylesHost,e,i);default:if(!this.rendererByCompId.has(i.id)){const r=Bc(i.id,i.styles,[]);this.sharedStylesHost.addStyles(r),this.rendererByCompId.set(i.id,this.defaultRenderer)}return this.defaultRenderer}}begin(){}end(){}}return n.\\u0275fac=function(e){return new(e||n)(y(Lc),y(wa),y(ga))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class _f{constructor(t){this.eventManager=t,this.data=Object.create(null),this.destroyNode=null}destroy(){}createElement(t,e){return e?document.createElementNS(mf[e]||e,t):document.createElement(t)}createComment(t){return document.createComment(t)}createText(t){return document.createTextNode(t)}appendChild(t,e){t.appendChild(e)}insertBefore(t,e,i){t&&t.insertBefore(e,i)}removeChild(t,e){t&&t.removeChild(e)}selectRootElement(t,e){let i=\"string\"==typeof t?document.querySelector(t):t;if(!i)throw new Error(`The selector \"${t}\" did not match any elements`);return e||(i.textContent=\"\"),i}parentNode(t){return t.parentNode}nextSibling(t){return t.nextSibling}setAttribute(t,e,i,r){if(r){e=r+\":\"+e;const s=mf[r];s?t.setAttributeNS(s,e,i):t.setAttribute(e,i)}else t.setAttribute(e,i)}removeAttribute(t,e,i){if(i){const r=mf[i];r?t.removeAttributeNS(r,e):t.removeAttribute(`${i}:${e}`)}else t.removeAttribute(e)}addClass(t,e){t.classList.add(e)}removeClass(t,e){t.classList.remove(e)}setStyle(t,e,i,r){r&(an.DashCase|an.Important)?t.style.setProperty(e,i,r&an.Important?\"important\":\"\"):t.style[e]=i}removeStyle(t,e,i){i&an.DashCase?t.style.removeProperty(e):t.style[e]=\"\"}setProperty(t,e,i){t[e]=i}setValue(t,e){t.nodeValue=e}listen(t,e,i){return\"string\"==typeof t?this.eventManager.addGlobalEventListener(t,e,ID(i)):this.eventManager.addEventListener(t,e,ID(i))}}class QL extends _f{constructor(t,e,i,r){super(t),this.component=i;const s=Bc(r+\"-\"+i.id,i.styles,[]);e.addStyles(s),this.contentAttr=function WL(n){return\"_ngcontent-%COMP%\".replace(gf,n)}(r+\"-\"+i.id),this.hostAttr=function qL(n){return\"_nghost-%COMP%\".replace(gf,n)}(r+\"-\"+i.id)}applyToHost(t){super.setAttribute(t,this.hostAttr,\"\")}createElement(t,e){const i=super.createElement(t,e);return super.setAttribute(i,this.contentAttr,\"\"),i}}class KL extends _f{constructor(t,e,i,r){super(t),this.sharedStylesHost=e,this.hostEl=i,this.shadowRoot=i.attachShadow({mode:\"open\"}),this.sharedStylesHost.addHost(this.shadowRoot);const s=Bc(r.id,r.styles,[]);for(let o=0;o<s.length;o++){const a=document.createElement(\"style\");a.textContent=s[o],this.shadowRoot.appendChild(a)}}nodeOrShadowRoot(t){return t===this.hostEl?this.shadowRoot:t}destroy(){this.sharedStylesHost.removeHost(this.shadowRoot)}appendChild(t,e){return super.appendChild(this.nodeOrShadowRoot(t),e)}insertBefore(t,e,i){return super.insertBefore(this.nodeOrShadowRoot(t),e,i)}removeChild(t,e){return super.removeChild(this.nodeOrShadowRoot(t),e)}parentNode(t){return this.nodeOrShadowRoot(super.parentNode(this.nodeOrShadowRoot(t)))}}let ZL=(()=>{class n extends ED{constructor(e){super(e)}supports(e){return!0}addEventListener(e,i,r){return e.addEventListener(i,r,!1),()=>this.removeEventListener(e,i,r)}removeEventListener(e,i,r){return e.removeEventListener(i,r)}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const OD=[\"alt\",\"control\",\"meta\",\"shift\"],JL={\"\\b\":\"Backspace\",\"\\t\":\"Tab\",\"\\x7f\":\"Delete\",\"\\x1b\":\"Escape\",Del:\"Delete\",Esc:\"Escape\",Left:\"ArrowLeft\",Right:\"ArrowRight\",Up:\"ArrowUp\",Down:\"ArrowDown\",Menu:\"ContextMenu\",Scroll:\"ScrollLock\",Win:\"OS\"},PD={A:\"1\",B:\"2\",C:\"3\",D:\"4\",E:\"5\",F:\"6\",G:\"7\",H:\"8\",I:\"9\",J:\"*\",K:\"+\",M:\"-\",N:\".\",O:\"/\",\"`\":\"0\",\"\\x90\":\"NumLock\"},eB={alt:n=>n.altKey,control:n=>n.ctrlKey,meta:n=>n.metaKey,shift:n=>n.shiftKey};let tB=(()=>{class n extends ED{constructor(e){super(e)}supports(e){return null!=n.parseEventName(e)}addEventListener(e,i,r){const s=n.parseEventName(i),o=n.eventCallback(s.fullKey,r,this.manager.getZone());return this.manager.getZone().runOutsideAngular(()=>mi().onAndCancel(e,s.domEventName,o))}static parseEventName(e){const i=e.toLowerCase().split(\".\"),r=i.shift();if(0===i.length||\"keydown\"!==r&&\"keyup\"!==r)return null;const s=n._normalizeKey(i.pop());let o=\"\";if(OD.forEach(l=>{const c=i.indexOf(l);c>-1&&(i.splice(c,1),o+=l+\".\")}),o+=s,0!=i.length||0===s.length)return null;const a={};return a.domEventName=r,a.fullKey=o,a}static getEventFullKey(e){let i=\"\",r=function nB(n){let t=n.key;if(null==t){if(t=n.keyIdentifier,null==t)return\"Unidentified\";t.startsWith(\"U+\")&&(t=String.fromCharCode(parseInt(t.substring(2),16)),3===n.location&&PD.hasOwnProperty(t)&&(t=PD[t]))}return JL[t]||t}(e);return r=r.toLowerCase(),\" \"===r?r=\"space\":\".\"===r&&(r=\"dot\"),OD.forEach(s=>{s!=r&&eB[s](e)&&(i+=s+\".\")}),i+=r,i}static eventCallback(e,i,r){return s=>{n.getEventFullKey(s)===e&&r.runGuarded(()=>i(s))}}static _normalizeKey(e){return\"esc\"===e?\"escape\":e}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const oB=H0(cN,\"browser\",[{provide:bc,useValue:wD},{provide:I0,useValue:function iB(){pf.makeCurrent(),ff.init()},multi:!0},{provide:ie,useFactory:function sB(){return function DT(n){Bu=n}(document),document},deps:[]}]),aB=[{provide:Jh,useValue:\"root\"},{provide:Mr,useFactory:function rB(){return new Mr},deps:[]},{provide:Nc,useClass:ZL,multi:!0,deps:[ie,ne,bc]},{provide:Nc,useClass:tB,multi:!0,deps:[ie]},{provide:Vc,useClass:Vc,deps:[Lc,wa,ga]},{provide:da,useExisting:Vc},{provide:SD,useExisting:wa},{provide:wa,useClass:wa,deps:[ie]},{provide:$p,useClass:$p,deps:[ne]},{provide:Lc,useClass:Lc,deps:[Nc,ne]},{provide:class LL{},useClass:UL,deps:[]}];let FD=(()=>{class n{constructor(e){if(e)throw new Error(\"BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.\")}static withServerTransition(e){return{ngModule:n,providers:[{provide:ga,useValue:e.appId},{provide:xD,useExisting:ga},zL]}}}return n.\\u0275fac=function(e){return new(e||n)(y(n,12))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:aB,imports:[bt,dN]}),n})();function q(...n){return mt(n,So(n))}\"undefined\"!=typeof window&&window;class Zt extends O{constructor(t){super(),this._value=t}get value(){return this.getValue()}_subscribe(t){const e=super._subscribe(t);return!e.closed&&t.next(this._value),e}getValue(){const{hasError:t,thrownError:e,_value:i}=this;if(t)throw e;return this._throwIfClosed(),i}next(t){super.next(this._value=t)}}const{isArray:vB}=Array,{getPrototypeOf:yB,prototype:bB,keys:CB}=Object;function VD(n){if(1===n.length){const t=n[0];if(vB(t))return{args:t,keys:null};if(function DB(n){return n&&\"object\"==typeof n&&yB(n)===bB}(t)){const e=CB(t);return{args:e.map(i=>t[i]),keys:e}}}return{args:n,keys:null}}const{isArray:wB}=Array;function bf(n){return ue(t=>function MB(n,t){return wB(t)?n(...t):n(t)}(n,t))}function HD(n,t){return n.reduce((e,i,r)=>(e[i]=t[r],e),{})}function jD(n,t,e){n?Mi(e,n,t):t()}function Ma(n,t){const e=De(n)?n:()=>n,i=r=>r.error(e());return new Ve(t?r=>t.schedule(i,0,r):i)}const Hc=xo(n=>function(){n(this),this.name=\"EmptyError\",this.message=\"no elements in sequence\"});function jc(...n){return function SB(){return Eo(1)}()(mt(n,So(n)))}function xa(n){return new Ve(t=>{Jt(n()).subscribe(t)})}function zD(){return qe((n,t)=>{let e=null;n._refCount++;const i=Ue(t,void 0,void 0,void 0,()=>{if(!n||n._refCount<=0||0<--n._refCount)return void(e=null);const r=n._connection,s=e;e=null,r&&(!s||r===s)&&r.unsubscribe(),t.unsubscribe()});n.subscribe(i),i.closed||(e=n.connect())})}class kB extends Ve{constructor(t,e){super(),this.source=t,this.subjectFactory=e,this._subject=null,this._refCount=0,this._connection=null,o_(t)&&(this.lift=t.lift)}_subscribe(t){return this.getSubject().subscribe(t)}getSubject(){const t=this._subject;return(!t||t.isStopped)&&(this._subject=this.subjectFactory()),this._subject}_teardown(){this._refCount=0;const{_connection:t}=this;this._subject=this._connection=null,null==t||t.unsubscribe()}connect(){let t=this._connection;if(!t){t=this._connection=new ke;const e=this.getSubject();t.add(this.source.subscribe(Ue(e,void 0,()=>{this._teardown(),e.complete()},i=>{this._teardown(),e.error(i)},()=>this._teardown()))),t.closed&&(this._connection=null,t=ke.EMPTY)}return t}refCount(){return zD()(this)}}function kn(n,t){return qe((e,i)=>{let r=null,s=0,o=!1;const a=()=>o&&!r&&i.complete();e.subscribe(Ue(i,l=>{null==r||r.unsubscribe();let c=0;const d=s++;Jt(n(l,d)).subscribe(r=Ue(i,u=>i.next(t?t(l,u,d,c++):u),()=>{r=null,a()}))},()=>{o=!0,a()}))})}function Xn(...n){const t=So(n);return qe((e,i)=>{(t?jc(n,e,t):jc(n,e)).subscribe(i)})}function TB(n,t,e,i,r){return(s,o)=>{let a=e,l=t,c=0;s.subscribe(Ue(o,d=>{const u=c++;l=a?n(l,d,u):(a=!0,d),i&&o.next(l)},r&&(()=>{a&&o.next(l),o.complete()})))}}function UD(n,t){return qe(TB(n,t,arguments.length>=2,!0))}function Ct(n,t){return qe((e,i)=>{let r=0;e.subscribe(Ue(i,s=>n.call(t,s,r++)&&i.next(s)))})}function Ni(n){return qe((t,e)=>{let s,i=null,r=!1;i=t.subscribe(Ue(e,void 0,void 0,o=>{s=Jt(n(o,Ni(n)(t))),i?(i.unsubscribe(),i=null,s.subscribe(e)):r=!0})),r&&(i.unsubscribe(),i=null,s.subscribe(e))})}function Qs(n,t){return De(t)?lt(n,t,1):lt(n,1)}function Cf(n){return n<=0?()=>ri:qe((t,e)=>{let i=[];t.subscribe(Ue(e,r=>{i.push(r),n<i.length&&i.shift()},()=>{for(const r of i)e.next(r);e.complete()},void 0,()=>{i=null}))})}function $D(n=AB){return qe((t,e)=>{let i=!1;t.subscribe(Ue(e,r=>{i=!0,e.next(r)},()=>i?e.complete():e.error(n())))})}function AB(){return new Hc}function GD(n){return qe((t,e)=>{let i=!1;t.subscribe(Ue(e,r=>{i=!0,e.next(r)},()=>{i||e.next(n),e.complete()}))})}function Ks(n,t){const e=arguments.length>=2;return i=>i.pipe(n?Ct((r,s)=>n(r,s,i)):Wi,it(1),e?GD(t):$D(()=>new Hc))}function Mt(n,t,e){const i=De(n)||t||e?{next:n,error:t,complete:e}:n;return i?qe((r,s)=>{var o;null===(o=i.subscribe)||void 0===o||o.call(i);let a=!0;r.subscribe(Ue(s,l=>{var c;null===(c=i.next)||void 0===c||c.call(i,l),s.next(l)},()=>{var l;a=!1,null===(l=i.complete)||void 0===l||l.call(i),s.complete()},l=>{var c;a=!1,null===(c=i.error)||void 0===c||c.call(i,l),s.error(l)},()=>{var l,c;a&&(null===(l=i.unsubscribe)||void 0===l||l.call(i)),null===(c=i.finalize)||void 0===c||c.call(i)}))}):Wi}class Li{constructor(t,e){this.id=t,this.url=e}}class Df extends Li{constructor(t,e,i=\"imperative\",r=null){super(t,e),this.navigationTrigger=i,this.restoredState=r}toString(){return`NavigationStart(id: ${this.id}, url: '${this.url}')`}}class Ea extends Li{constructor(t,e,i){super(t,e),this.urlAfterRedirects=i}toString(){return`NavigationEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}')`}}class qD extends Li{constructor(t,e,i){super(t,e),this.reason=i}toString(){return`NavigationCancel(id: ${this.id}, url: '${this.url}')`}}class RB extends Li{constructor(t,e,i){super(t,e),this.error=i}toString(){return`NavigationError(id: ${this.id}, url: '${this.url}', error: ${this.error})`}}class OB extends Li{constructor(t,e,i,r){super(t,e),this.urlAfterRedirects=i,this.state=r}toString(){return`RoutesRecognized(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`}}class PB extends Li{constructor(t,e,i,r){super(t,e),this.urlAfterRedirects=i,this.state=r}toString(){return`GuardsCheckStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`}}class FB extends Li{constructor(t,e,i,r,s){super(t,e),this.urlAfterRedirects=i,this.state=r,this.shouldActivate=s}toString(){return`GuardsCheckEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state}, shouldActivate: ${this.shouldActivate})`}}class NB extends Li{constructor(t,e,i,r){super(t,e),this.urlAfterRedirects=i,this.state=r}toString(){return`ResolveStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`}}class LB extends Li{constructor(t,e,i,r){super(t,e),this.urlAfterRedirects=i,this.state=r}toString(){return`ResolveEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`}}class YD{constructor(t){this.route=t}toString(){return`RouteConfigLoadStart(path: ${this.route.path})`}}class QD{constructor(t){this.route=t}toString(){return`RouteConfigLoadEnd(path: ${this.route.path})`}}class BB{constructor(t){this.snapshot=t}toString(){return`ChildActivationStart(path: '${this.snapshot.routeConfig&&this.snapshot.routeConfig.path||\"\"}')`}}class VB{constructor(t){this.snapshot=t}toString(){return`ChildActivationEnd(path: '${this.snapshot.routeConfig&&this.snapshot.routeConfig.path||\"\"}')`}}class HB{constructor(t){this.snapshot=t}toString(){return`ActivationStart(path: '${this.snapshot.routeConfig&&this.snapshot.routeConfig.path||\"\"}')`}}class jB{constructor(t){this.snapshot=t}toString(){return`ActivationEnd(path: '${this.snapshot.routeConfig&&this.snapshot.routeConfig.path||\"\"}')`}}class KD{constructor(t,e,i){this.routerEvent=t,this.position=e,this.anchor=i}toString(){return`Scroll(anchor: '${this.anchor}', position: '${this.position?`${this.position[0]}, ${this.position[1]}`:null}')`}}const me=\"primary\";class zB{constructor(t){this.params=t||{}}has(t){return Object.prototype.hasOwnProperty.call(this.params,t)}get(t){if(this.has(t)){const e=this.params[t];return Array.isArray(e)?e[0]:e}return null}getAll(t){if(this.has(t)){const e=this.params[t];return Array.isArray(e)?e:[e]}return[]}get keys(){return Object.keys(this.params)}}function Zs(n){return new zB(n)}const ZD=\"ngNavigationCancelingError\";function wf(n){const t=Error(\"NavigationCancelingError: \"+n);return t[ZD]=!0,t}function $B(n,t,e){const i=e.path.split(\"/\");if(i.length>n.length||\"full\"===e.pathMatch&&(t.hasChildren()||i.length<n.length))return null;const r={};for(let s=0;s<i.length;s++){const o=i[s],a=n[s];if(o.startsWith(\":\"))r[o.substring(1)]=a;else if(o!==a.path)return null}return{consumed:n.slice(0,i.length),posParams:r}}function gi(n,t){const e=n?Object.keys(n):void 0,i=t?Object.keys(t):void 0;if(!e||!i||e.length!=i.length)return!1;let r;for(let s=0;s<e.length;s++)if(r=e[s],!XD(n[r],t[r]))return!1;return!0}function XD(n,t){if(Array.isArray(n)&&Array.isArray(t)){if(n.length!==t.length)return!1;const e=[...n].sort(),i=[...t].sort();return e.every((r,s)=>i[s]===r)}return n===t}function JD(n){return Array.prototype.concat.apply([],n)}function ew(n){return n.length>0?n[n.length-1]:null}function At(n,t){for(const e in n)n.hasOwnProperty(e)&&t(n[e],e)}function _i(n){return up(n)?n:ra(n)?mt(Promise.resolve(n)):q(n)}const qB={exact:function iw(n,t,e){if(!Nr(n.segments,t.segments)||!zc(n.segments,t.segments,e)||n.numberOfChildren!==t.numberOfChildren)return!1;for(const i in t.children)if(!n.children[i]||!iw(n.children[i],t.children[i],e))return!1;return!0},subset:rw},tw={exact:function YB(n,t){return gi(n,t)},subset:function QB(n,t){return Object.keys(t).length<=Object.keys(n).length&&Object.keys(t).every(e=>XD(n[e],t[e]))},ignored:()=>!0};function nw(n,t,e){return qB[e.paths](n.root,t.root,e.matrixParams)&&tw[e.queryParams](n.queryParams,t.queryParams)&&!(\"exact\"===e.fragment&&n.fragment!==t.fragment)}function rw(n,t,e){return sw(n,t,t.segments,e)}function sw(n,t,e,i){if(n.segments.length>e.length){const r=n.segments.slice(0,e.length);return!(!Nr(r,e)||t.hasChildren()||!zc(r,e,i))}if(n.segments.length===e.length){if(!Nr(n.segments,e)||!zc(n.segments,e,i))return!1;for(const r in t.children)if(!n.children[r]||!rw(n.children[r],t.children[r],i))return!1;return!0}{const r=e.slice(0,n.segments.length),s=e.slice(n.segments.length);return!!(Nr(n.segments,r)&&zc(n.segments,r,i)&&n.children[me])&&sw(n.children[me],t,s,i)}}function zc(n,t,e){return t.every((i,r)=>tw[e](n[r].parameters,i.parameters))}class Fr{constructor(t,e,i){this.root=t,this.queryParams=e,this.fragment=i}get queryParamMap(){return this._queryParamMap||(this._queryParamMap=Zs(this.queryParams)),this._queryParamMap}toString(){return XB.serialize(this)}}class ye{constructor(t,e){this.segments=t,this.children=e,this.parent=null,At(e,(i,r)=>i.parent=this)}hasChildren(){return this.numberOfChildren>0}get numberOfChildren(){return Object.keys(this.children).length}toString(){return Uc(this)}}class Sa{constructor(t,e){this.path=t,this.parameters=e}get parameterMap(){return this._parameterMap||(this._parameterMap=Zs(this.parameters)),this._parameterMap}toString(){return dw(this)}}function Nr(n,t){return n.length===t.length&&n.every((e,i)=>e.path===t[i].path)}class ow{}class aw{parse(t){const e=new aV(t);return new Fr(e.parseRootSegment(),e.parseQueryParams(),e.parseFragment())}serialize(t){const e=`/${ka(t.root,!0)}`,i=function tV(n){const t=Object.keys(n).map(e=>{const i=n[e];return Array.isArray(i)?i.map(r=>`${$c(e)}=${$c(r)}`).join(\"&\"):`${$c(e)}=${$c(i)}`}).filter(e=>!!e);return t.length?`?${t.join(\"&\")}`:\"\"}(t.queryParams);return`${e}${i}${\"string\"==typeof t.fragment?`#${function JB(n){return encodeURI(n)}(t.fragment)}`:\"\"}`}}const XB=new aw;function Uc(n){return n.segments.map(t=>dw(t)).join(\"/\")}function ka(n,t){if(!n.hasChildren())return Uc(n);if(t){const e=n.children[me]?ka(n.children[me],!1):\"\",i=[];return At(n.children,(r,s)=>{s!==me&&i.push(`${s}:${ka(r,!1)}`)}),i.length>0?`${e}(${i.join(\"//\")})`:e}{const e=function ZB(n,t){let e=[];return At(n.children,(i,r)=>{r===me&&(e=e.concat(t(i,r)))}),At(n.children,(i,r)=>{r!==me&&(e=e.concat(t(i,r)))}),e}(n,(i,r)=>r===me?[ka(n.children[me],!1)]:[`${r}:${ka(i,!1)}`]);return 1===Object.keys(n.children).length&&null!=n.children[me]?`${Uc(n)}/${e[0]}`:`${Uc(n)}/(${e.join(\"//\")})`}}function lw(n){return encodeURIComponent(n).replace(/%40/g,\"@\").replace(/%3A/gi,\":\").replace(/%24/g,\"$\").replace(/%2C/gi,\",\")}function $c(n){return lw(n).replace(/%3B/gi,\";\")}function Mf(n){return lw(n).replace(/\\(/g,\"%28\").replace(/\\)/g,\"%29\").replace(/%26/gi,\"&\")}function Gc(n){return decodeURIComponent(n)}function cw(n){return Gc(n.replace(/\\+/g,\"%20\"))}function dw(n){return`${Mf(n.path)}${function eV(n){return Object.keys(n).map(t=>`;${Mf(t)}=${Mf(n[t])}`).join(\"\")}(n.parameters)}`}const nV=/^[^\\/()?;=#]+/;function Wc(n){const t=n.match(nV);return t?t[0]:\"\"}const iV=/^[^=?&#]+/,sV=/^[^&#]+/;class aV{constructor(t){this.url=t,this.remaining=t}parseRootSegment(){return this.consumeOptional(\"/\"),\"\"===this.remaining||this.peekStartsWith(\"?\")||this.peekStartsWith(\"#\")?new ye([],{}):new ye([],this.parseChildren())}parseQueryParams(){const t={};if(this.consumeOptional(\"?\"))do{this.parseQueryParam(t)}while(this.consumeOptional(\"&\"));return t}parseFragment(){return this.consumeOptional(\"#\")?decodeURIComponent(this.remaining):null}parseChildren(){if(\"\"===this.remaining)return{};this.consumeOptional(\"/\");const t=[];for(this.peekStartsWith(\"(\")||t.push(this.parseSegment());this.peekStartsWith(\"/\")&&!this.peekStartsWith(\"//\")&&!this.peekStartsWith(\"/(\");)this.capture(\"/\"),t.push(this.parseSegment());let e={};this.peekStartsWith(\"/(\")&&(this.capture(\"/\"),e=this.parseParens(!0));let i={};return this.peekStartsWith(\"(\")&&(i=this.parseParens(!1)),(t.length>0||Object.keys(e).length>0)&&(i[me]=new ye(t,e)),i}parseSegment(){const t=Wc(this.remaining);if(\"\"===t&&this.peekStartsWith(\";\"))throw new Error(`Empty path url segment cannot have parameters: '${this.remaining}'.`);return this.capture(t),new Sa(Gc(t),this.parseMatrixParams())}parseMatrixParams(){const t={};for(;this.consumeOptional(\";\");)this.parseParam(t);return t}parseParam(t){const e=Wc(this.remaining);if(!e)return;this.capture(e);let i=\"\";if(this.consumeOptional(\"=\")){const r=Wc(this.remaining);r&&(i=r,this.capture(i))}t[Gc(e)]=Gc(i)}parseQueryParam(t){const e=function rV(n){const t=n.match(iV);return t?t[0]:\"\"}(this.remaining);if(!e)return;this.capture(e);let i=\"\";if(this.consumeOptional(\"=\")){const o=function oV(n){const t=n.match(sV);return t?t[0]:\"\"}(this.remaining);o&&(i=o,this.capture(i))}const r=cw(e),s=cw(i);if(t.hasOwnProperty(r)){let o=t[r];Array.isArray(o)||(o=[o],t[r]=o),o.push(s)}else t[r]=s}parseParens(t){const e={};for(this.capture(\"(\");!this.consumeOptional(\")\")&&this.remaining.length>0;){const i=Wc(this.remaining),r=this.remaining[i.length];if(\"/\"!==r&&\")\"!==r&&\";\"!==r)throw new Error(`Cannot parse url '${this.url}'`);let s;i.indexOf(\":\")>-1?(s=i.substr(0,i.indexOf(\":\")),this.capture(s),this.capture(\":\")):t&&(s=me);const o=this.parseChildren();e[s]=1===Object.keys(o).length?o[me]:new ye([],o),this.consumeOptional(\"//\")}return e}peekStartsWith(t){return this.remaining.startsWith(t)}consumeOptional(t){return!!this.peekStartsWith(t)&&(this.remaining=this.remaining.substring(t.length),!0)}capture(t){if(!this.consumeOptional(t))throw new Error(`Expected \"${t}\".`)}}class uw{constructor(t){this._root=t}get root(){return this._root.value}parent(t){const e=this.pathFromRoot(t);return e.length>1?e[e.length-2]:null}children(t){const e=xf(t,this._root);return e?e.children.map(i=>i.value):[]}firstChild(t){const e=xf(t,this._root);return e&&e.children.length>0?e.children[0].value:null}siblings(t){const e=Ef(t,this._root);return e.length<2?[]:e[e.length-2].children.map(r=>r.value).filter(r=>r!==t)}pathFromRoot(t){return Ef(t,this._root).map(e=>e.value)}}function xf(n,t){if(n===t.value)return t;for(const e of t.children){const i=xf(n,e);if(i)return i}return null}function Ef(n,t){if(n===t.value)return[t];for(const e of t.children){const i=Ef(n,e);if(i.length)return i.unshift(t),i}return[]}class Bi{constructor(t,e){this.value=t,this.children=e}toString(){return`TreeNode(${this.value})`}}function Xs(n){const t={};return n&&n.children.forEach(e=>t[e.value.outlet]=e),t}class hw extends uw{constructor(t,e){super(t),this.snapshot=e,Sf(this,t)}toString(){return this.snapshot.toString()}}function pw(n,t){const e=function lV(n,t){const o=new qc([],{},{},\"\",{},me,t,null,n.root,-1,{});return new mw(\"\",new Bi(o,[]))}(n,t),i=new Zt([new Sa(\"\",{})]),r=new Zt({}),s=new Zt({}),o=new Zt({}),a=new Zt(\"\"),l=new Js(i,r,o,a,s,me,t,e.root);return l.snapshot=e.root,new hw(new Bi(l,[]),e)}class Js{constructor(t,e,i,r,s,o,a,l){this.url=t,this.params=e,this.queryParams=i,this.fragment=r,this.data=s,this.outlet=o,this.component=a,this._futureSnapshot=l}get routeConfig(){return this._futureSnapshot.routeConfig}get root(){return this._routerState.root}get parent(){return this._routerState.parent(this)}get firstChild(){return this._routerState.firstChild(this)}get children(){return this._routerState.children(this)}get pathFromRoot(){return this._routerState.pathFromRoot(this)}get paramMap(){return this._paramMap||(this._paramMap=this.params.pipe(ue(t=>Zs(t)))),this._paramMap}get queryParamMap(){return this._queryParamMap||(this._queryParamMap=this.queryParams.pipe(ue(t=>Zs(t)))),this._queryParamMap}toString(){return this.snapshot?this.snapshot.toString():`Future(${this._futureSnapshot})`}}function fw(n,t=\"emptyOnly\"){const e=n.pathFromRoot;let i=0;if(\"always\"!==t)for(i=e.length-1;i>=1;){const r=e[i],s=e[i-1];if(r.routeConfig&&\"\"===r.routeConfig.path)i--;else{if(s.component)break;i--}}return function cV(n){return n.reduce((t,e)=>({params:Object.assign(Object.assign({},t.params),e.params),data:Object.assign(Object.assign({},t.data),e.data),resolve:Object.assign(Object.assign({},t.resolve),e._resolvedData)}),{params:{},data:{},resolve:{}})}(e.slice(i))}class qc{constructor(t,e,i,r,s,o,a,l,c,d,u){this.url=t,this.params=e,this.queryParams=i,this.fragment=r,this.data=s,this.outlet=o,this.component=a,this.routeConfig=l,this._urlSegment=c,this._lastPathIndex=d,this._resolve=u}get root(){return this._routerState.root}get parent(){return this._routerState.parent(this)}get firstChild(){return this._routerState.firstChild(this)}get children(){return this._routerState.children(this)}get pathFromRoot(){return this._routerState.pathFromRoot(this)}get paramMap(){return this._paramMap||(this._paramMap=Zs(this.params)),this._paramMap}get queryParamMap(){return this._queryParamMap||(this._queryParamMap=Zs(this.queryParams)),this._queryParamMap}toString(){return`Route(url:'${this.url.map(i=>i.toString()).join(\"/\")}', path:'${this.routeConfig?this.routeConfig.path:\"\"}')`}}class mw extends uw{constructor(t,e){super(e),this.url=t,Sf(this,e)}toString(){return gw(this._root)}}function Sf(n,t){t.value._routerState=n,t.children.forEach(e=>Sf(n,e))}function gw(n){const t=n.children.length>0?` { ${n.children.map(gw).join(\", \")} } `:\"\";return`${n.value}${t}`}function kf(n){if(n.snapshot){const t=n.snapshot,e=n._futureSnapshot;n.snapshot=e,gi(t.queryParams,e.queryParams)||n.queryParams.next(e.queryParams),t.fragment!==e.fragment&&n.fragment.next(e.fragment),gi(t.params,e.params)||n.params.next(e.params),function GB(n,t){if(n.length!==t.length)return!1;for(let e=0;e<n.length;++e)if(!gi(n[e],t[e]))return!1;return!0}(t.url,e.url)||n.url.next(e.url),gi(t.data,e.data)||n.data.next(e.data)}else n.snapshot=n._futureSnapshot,n.data.next(n._futureSnapshot.data)}function Tf(n,t){const e=gi(n.params,t.params)&&function KB(n,t){return Nr(n,t)&&n.every((e,i)=>gi(e.parameters,t[i].parameters))}(n.url,t.url);return e&&!(!n.parent!=!t.parent)&&(!n.parent||Tf(n.parent,t.parent))}function Ta(n,t,e){if(e&&n.shouldReuseRoute(t.value,e.value.snapshot)){const i=e.value;i._futureSnapshot=t.value;const r=function uV(n,t,e){return t.children.map(i=>{for(const r of e.children)if(n.shouldReuseRoute(i.value,r.value.snapshot))return Ta(n,i,r);return Ta(n,i)})}(n,t,e);return new Bi(i,r)}{if(n.shouldAttach(t.value)){const s=n.retrieve(t.value);if(null!==s){const o=s.route;return o.value._futureSnapshot=t.value,o.children=t.children.map(a=>Ta(n,a)),o}}const i=function hV(n){return new Js(new Zt(n.url),new Zt(n.params),new Zt(n.queryParams),new Zt(n.fragment),new Zt(n.data),n.outlet,n.component,n)}(t.value),r=t.children.map(s=>Ta(n,s));return new Bi(i,r)}}function Yc(n){return\"object\"==typeof n&&null!=n&&!n.outlets&&!n.segmentPath}function Aa(n){return\"object\"==typeof n&&null!=n&&n.outlets}function Af(n,t,e,i,r){let s={};if(i&&At(i,(a,l)=>{s[l]=Array.isArray(a)?a.map(c=>`${c}`):`${a}`}),n===t)return new Fr(e,s,r);const o=_w(n,t,e);return new Fr(o,s,r)}function _w(n,t,e){const i={};return At(n.children,(r,s)=>{i[s]=r===t?e:_w(r,t,e)}),new ye(n.segments,i)}class vw{constructor(t,e,i){if(this.isAbsolute=t,this.numberOfDoubleDots=e,this.commands=i,t&&i.length>0&&Yc(i[0]))throw new Error(\"Root segment cannot have matrix parameters\");const r=i.find(Aa);if(r&&r!==ew(i))throw new Error(\"{outlets:{}} has to be the last command\")}toRoot(){return this.isAbsolute&&1===this.commands.length&&\"/\"==this.commands[0]}}class If{constructor(t,e,i){this.segmentGroup=t,this.processChildren=e,this.index=i}}function yw(n,t,e){if(n||(n=new ye([],{})),0===n.segments.length&&n.hasChildren())return Qc(n,t,e);const i=function vV(n,t,e){let i=0,r=t;const s={match:!1,pathIndex:0,commandIndex:0};for(;r<n.segments.length;){if(i>=e.length)return s;const o=n.segments[r],a=e[i];if(Aa(a))break;const l=`${a}`,c=i<e.length-1?e[i+1]:null;if(r>0&&void 0===l)break;if(l&&c&&\"object\"==typeof c&&void 0===c.outlets){if(!Cw(l,c,o))return s;i+=2}else{if(!Cw(l,{},o))return s;i++}r++}return{match:!0,pathIndex:r,commandIndex:i}}(n,t,e),r=e.slice(i.commandIndex);if(i.match&&i.pathIndex<n.segments.length){const s=new ye(n.segments.slice(0,i.pathIndex),{});return s.children[me]=new ye(n.segments.slice(i.pathIndex),n.children),Qc(s,0,r)}return i.match&&0===r.length?new ye(n.segments,{}):i.match&&!n.hasChildren()?Rf(n,t,e):i.match?Qc(n,0,r):Rf(n,t,e)}function Qc(n,t,e){if(0===e.length)return new ye(n.segments,{});{const i=function _V(n){return Aa(n[0])?n[0].outlets:{[me]:n}}(e),r={};return At(i,(s,o)=>{\"string\"==typeof s&&(s=[s]),null!==s&&(r[o]=yw(n.children[o],t,s))}),At(n.children,(s,o)=>{void 0===i[o]&&(r[o]=s)}),new ye(n.segments,r)}}function Rf(n,t,e){const i=n.segments.slice(0,t);let r=0;for(;r<e.length;){const s=e[r];if(Aa(s)){const l=yV(s.outlets);return new ye(i,l)}if(0===r&&Yc(e[0])){i.push(new Sa(n.segments[t].path,bw(e[0]))),r++;continue}const o=Aa(s)?s.outlets[me]:`${s}`,a=r<e.length-1?e[r+1]:null;o&&a&&Yc(a)?(i.push(new Sa(o,bw(a))),r+=2):(i.push(new Sa(o,{})),r++)}return new ye(i,{})}function yV(n){const t={};return At(n,(e,i)=>{\"string\"==typeof e&&(e=[e]),null!==e&&(t[i]=Rf(new ye([],{}),0,e))}),t}function bw(n){const t={};return At(n,(e,i)=>t[i]=`${e}`),t}function Cw(n,t,e){return n==e.path&&gi(t,e.parameters)}class CV{constructor(t,e,i,r){this.routeReuseStrategy=t,this.futureState=e,this.currState=i,this.forwardEvent=r}activate(t){const e=this.futureState._root,i=this.currState?this.currState._root:null;this.deactivateChildRoutes(e,i,t),kf(this.futureState.root),this.activateChildRoutes(e,i,t)}deactivateChildRoutes(t,e,i){const r=Xs(e);t.children.forEach(s=>{const o=s.value.outlet;this.deactivateRoutes(s,r[o],i),delete r[o]}),At(r,(s,o)=>{this.deactivateRouteAndItsChildren(s,i)})}deactivateRoutes(t,e,i){const r=t.value,s=e?e.value:null;if(r===s)if(r.component){const o=i.getContext(r.outlet);o&&this.deactivateChildRoutes(t,e,o.children)}else this.deactivateChildRoutes(t,e,i);else s&&this.deactivateRouteAndItsChildren(e,i)}deactivateRouteAndItsChildren(t,e){t.value.component&&this.routeReuseStrategy.shouldDetach(t.value.snapshot)?this.detachAndStoreRouteSubtree(t,e):this.deactivateRouteAndOutlet(t,e)}detachAndStoreRouteSubtree(t,e){const i=e.getContext(t.value.outlet),r=i&&t.value.component?i.children:e,s=Xs(t);for(const o of Object.keys(s))this.deactivateRouteAndItsChildren(s[o],r);if(i&&i.outlet){const o=i.outlet.detach(),a=i.children.onOutletDeactivated();this.routeReuseStrategy.store(t.value.snapshot,{componentRef:o,route:t,contexts:a})}}deactivateRouteAndOutlet(t,e){const i=e.getContext(t.value.outlet),r=i&&t.value.component?i.children:e,s=Xs(t);for(const o of Object.keys(s))this.deactivateRouteAndItsChildren(s[o],r);i&&i.outlet&&(i.outlet.deactivate(),i.children.onOutletDeactivated(),i.attachRef=null,i.resolver=null,i.route=null)}activateChildRoutes(t,e,i){const r=Xs(e);t.children.forEach(s=>{this.activateRoutes(s,r[s.value.outlet],i),this.forwardEvent(new jB(s.value.snapshot))}),t.children.length&&this.forwardEvent(new VB(t.value.snapshot))}activateRoutes(t,e,i){const r=t.value,s=e?e.value:null;if(kf(r),r===s)if(r.component){const o=i.getOrCreateContext(r.outlet);this.activateChildRoutes(t,e,o.children)}else this.activateChildRoutes(t,e,i);else if(r.component){const o=i.getOrCreateContext(r.outlet);if(this.routeReuseStrategy.shouldAttach(r.snapshot)){const a=this.routeReuseStrategy.retrieve(r.snapshot);this.routeReuseStrategy.store(r.snapshot,null),o.children.onOutletReAttached(a.contexts),o.attachRef=a.componentRef,o.route=a.route.value,o.outlet&&o.outlet.attach(a.componentRef,a.route.value),kf(a.route.value),this.activateChildRoutes(t,null,o.children)}else{const a=function DV(n){for(let t=n.parent;t;t=t.parent){const e=t.routeConfig;if(e&&e._loadedConfig)return e._loadedConfig;if(e&&e.component)return null}return null}(r.snapshot),l=a?a.module.componentFactoryResolver:null;o.attachRef=null,o.route=r,o.resolver=l,o.outlet&&o.outlet.activateWith(r,l),this.activateChildRoutes(t,null,o.children)}}else this.activateChildRoutes(t,null,i)}}class Of{constructor(t,e){this.routes=t,this.module=e}}function nr(n){return\"function\"==typeof n}function Lr(n){return n instanceof Fr}const Ia=Symbol(\"INITIAL_VALUE\");function Ra(){return kn(n=>function xB(...n){const t=So(n),e=b_(n),{args:i,keys:r}=VD(n);if(0===i.length)return mt([],t);const s=new Ve(function EB(n,t,e=Wi){return i=>{jD(t,()=>{const{length:r}=n,s=new Array(r);let o=r,a=r;for(let l=0;l<r;l++)jD(t,()=>{const c=mt(n[l],t);let d=!1;c.subscribe(Ue(i,u=>{s[l]=u,d||(d=!0,a--),a||i.next(e(s.slice()))},()=>{--o||i.complete()}))},i)},i)}}(i,t,r?o=>HD(r,o):Wi));return e?s.pipe(bf(e)):s}(n.map(t=>t.pipe(it(1),Xn(Ia)))).pipe(UD((t,e)=>{let i=!1;return e.reduce((r,s,o)=>r!==Ia?r:(s===Ia&&(i=!0),i||!1!==s&&o!==e.length-1&&!Lr(s)?r:s),t)},Ia),Ct(t=>t!==Ia),ue(t=>Lr(t)?t:!0===t),it(1)))}class kV{constructor(){this.outlet=null,this.route=null,this.resolver=null,this.children=new Oa,this.attachRef=null}}class Oa{constructor(){this.contexts=new Map}onChildOutletCreated(t,e){const i=this.getOrCreateContext(t);i.outlet=e,this.contexts.set(t,i)}onChildOutletDestroyed(t){const e=this.getContext(t);e&&(e.outlet=null,e.attachRef=null)}onOutletDeactivated(){const t=this.contexts;return this.contexts=new Map,t}onOutletReAttached(t){this.contexts=t}getOrCreateContext(t){let e=this.getContext(t);return e||(e=new kV,this.contexts.set(t,e)),e}getContext(t){return this.contexts.get(t)||null}}let Pf=(()=>{class n{constructor(e,i,r,s,o){this.parentContexts=e,this.location=i,this.resolver=r,this.changeDetector=o,this.activated=null,this._activatedRoute=null,this.activateEvents=new $,this.deactivateEvents=new $,this.attachEvents=new $,this.detachEvents=new $,this.name=s||me,e.onChildOutletCreated(this.name,this)}ngOnDestroy(){this.parentContexts.onChildOutletDestroyed(this.name)}ngOnInit(){if(!this.activated){const e=this.parentContexts.getContext(this.name);e&&e.route&&(e.attachRef?this.attach(e.attachRef,e.route):this.activateWith(e.route,e.resolver||null))}}get isActivated(){return!!this.activated}get component(){if(!this.activated)throw new Error(\"Outlet is not activated\");return this.activated.instance}get activatedRoute(){if(!this.activated)throw new Error(\"Outlet is not activated\");return this._activatedRoute}get activatedRouteData(){return this._activatedRoute?this._activatedRoute.snapshot.data:{}}detach(){if(!this.activated)throw new Error(\"Outlet is not activated\");this.location.detach();const e=this.activated;return this.activated=null,this._activatedRoute=null,this.detachEvents.emit(e.instance),e}attach(e,i){this.activated=e,this._activatedRoute=i,this.location.insert(e.hostView),this.attachEvents.emit(e.instance)}deactivate(){if(this.activated){const e=this.component;this.activated.destroy(),this.activated=null,this._activatedRoute=null,this.deactivateEvents.emit(e)}}activateWith(e,i){if(this.isActivated)throw new Error(\"Cannot activate an already activated outlet\");this._activatedRoute=e;const o=(i=i||this.resolver).resolveComponentFactory(e._futureSnapshot.routeConfig.component),a=this.parentContexts.getOrCreateContext(this.name).children,l=new TV(e,a,this.location.injector);this.activated=this.location.createComponent(o,this.location.length,l),this.changeDetector.markForCheck(),this.activateEvents.emit(this.activated.instance)}}return n.\\u0275fac=function(e){return new(e||n)(f(Oa),f(st),f(Ir),kt(\"name\"),f(Ye))},n.\\u0275dir=C({type:n,selectors:[[\"router-outlet\"]],outputs:{activateEvents:\"activate\",deactivateEvents:\"deactivate\",attachEvents:\"attach\",detachEvents:\"detach\"},exportAs:[\"outlet\"]}),n})();class TV{constructor(t,e,i){this.route=t,this.childContexts=e,this.parent=i}get(t,e){return t===Js?this.route:t===Oa?this.childContexts:this.parent.get(t,e)}}let Dw=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275cmp=xe({type:n,selectors:[[\"ng-component\"]],decls:1,vars:0,template:function(e,i){1&e&&Le(0,\"router-outlet\")},directives:[Pf],encapsulation:2}),n})();function ww(n,t=\"\"){for(let e=0;e<n.length;e++){const i=n[e];AV(i,IV(t,i))}}function AV(n,t){n.children&&ww(n.children,t)}function IV(n,t){return t?n||t.path?n&&!t.path?`${n}/`:!n&&t.path?t.path:`${n}/${t.path}`:\"\":n}function Ff(n){const t=n.children&&n.children.map(Ff),e=t?Object.assign(Object.assign({},n),{children:t}):Object.assign({},n);return!e.component&&(t||e.loadChildren)&&e.outlet&&e.outlet!==me&&(e.component=Dw),e}function Tn(n){return n.outlet||me}function Mw(n,t){const e=n.filter(i=>Tn(i)===t);return e.push(...n.filter(i=>Tn(i)!==t)),e}const xw={matched:!1,consumedSegments:[],remainingSegments:[],parameters:{},positionalParamSegments:{}};function Kc(n,t,e){var i;if(\"\"===t.path)return\"full\"===t.pathMatch&&(n.hasChildren()||e.length>0)?Object.assign({},xw):{matched:!0,consumedSegments:[],remainingSegments:e,parameters:{},positionalParamSegments:{}};const s=(t.matcher||$B)(e,n,t);if(!s)return Object.assign({},xw);const o={};At(s.posParams,(l,c)=>{o[c]=l.path});const a=s.consumed.length>0?Object.assign(Object.assign({},o),s.consumed[s.consumed.length-1].parameters):o;return{matched:!0,consumedSegments:s.consumed,remainingSegments:e.slice(s.consumed.length),parameters:a,positionalParamSegments:null!==(i=s.posParams)&&void 0!==i?i:{}}}function Zc(n,t,e,i,r=\"corrected\"){if(e.length>0&&function PV(n,t,e){return e.some(i=>Xc(n,t,i)&&Tn(i)!==me)}(n,e,i)){const o=new ye(t,function OV(n,t,e,i){const r={};r[me]=i,i._sourceSegment=n,i._segmentIndexShift=t.length;for(const s of e)if(\"\"===s.path&&Tn(s)!==me){const o=new ye([],{});o._sourceSegment=n,o._segmentIndexShift=t.length,r[Tn(s)]=o}return r}(n,t,i,new ye(e,n.children)));return o._sourceSegment=n,o._segmentIndexShift=t.length,{segmentGroup:o,slicedSegments:[]}}if(0===e.length&&function FV(n,t,e){return e.some(i=>Xc(n,t,i))}(n,e,i)){const o=new ye(n.segments,function RV(n,t,e,i,r,s){const o={};for(const a of i)if(Xc(n,e,a)&&!r[Tn(a)]){const l=new ye([],{});l._sourceSegment=n,l._segmentIndexShift=\"legacy\"===s?n.segments.length:t.length,o[Tn(a)]=l}return Object.assign(Object.assign({},r),o)}(n,t,e,i,n.children,r));return o._sourceSegment=n,o._segmentIndexShift=t.length,{segmentGroup:o,slicedSegments:e}}const s=new ye(n.segments,n.children);return s._sourceSegment=n,s._segmentIndexShift=t.length,{segmentGroup:s,slicedSegments:e}}function Xc(n,t,e){return(!(n.hasChildren()||t.length>0)||\"full\"!==e.pathMatch)&&\"\"===e.path}function Ew(n,t,e,i){return!!(Tn(n)===i||i!==me&&Xc(t,e,n))&&(\"**\"===n.path||Kc(t,n,e).matched)}function Sw(n,t,e){return 0===t.length&&!n.children[e]}class Jc{constructor(t){this.segmentGroup=t||null}}class kw{constructor(t){this.urlTree=t}}function Pa(n){return Ma(new Jc(n))}function Tw(n){return Ma(new kw(n))}class VV{constructor(t,e,i,r,s){this.configLoader=e,this.urlSerializer=i,this.urlTree=r,this.config=s,this.allowRedirects=!0,this.ngModule=t.get(Ri)}apply(){const t=Zc(this.urlTree.root,[],[],this.config).segmentGroup,e=new ye(t.segments,t.children);return this.expandSegmentGroup(this.ngModule,this.config,e,me).pipe(ue(s=>this.createUrlTree(Nf(s),this.urlTree.queryParams,this.urlTree.fragment))).pipe(Ni(s=>{if(s instanceof kw)return this.allowRedirects=!1,this.match(s.urlTree);throw s instanceof Jc?this.noMatchError(s):s}))}match(t){return this.expandSegmentGroup(this.ngModule,this.config,t.root,me).pipe(ue(r=>this.createUrlTree(Nf(r),t.queryParams,t.fragment))).pipe(Ni(r=>{throw r instanceof Jc?this.noMatchError(r):r}))}noMatchError(t){return new Error(`Cannot match any routes. URL Segment: '${t.segmentGroup}'`)}createUrlTree(t,e,i){const r=t.segments.length>0?new ye([],{[me]:t}):t;return new Fr(r,e,i)}expandSegmentGroup(t,e,i,r){return 0===i.segments.length&&i.hasChildren()?this.expandChildren(t,e,i).pipe(ue(s=>new ye([],s))):this.expandSegment(t,i,e,i.segments,r,!0)}expandChildren(t,e,i){const r=[];for(const s of Object.keys(i.children))\"primary\"===s?r.unshift(s):r.push(s);return mt(r).pipe(Qs(s=>{const o=i.children[s],a=Mw(e,s);return this.expandSegmentGroup(t,a,o,s).pipe(ue(l=>({segment:l,outlet:s})))}),UD((s,o)=>(s[o.outlet]=o.segment,s),{}),function IB(n,t){const e=arguments.length>=2;return i=>i.pipe(n?Ct((r,s)=>n(r,s,i)):Wi,Cf(1),e?GD(t):$D(()=>new Hc))}())}expandSegment(t,e,i,r,s,o){return mt(i).pipe(Qs(a=>this.expandSegmentAgainstRoute(t,e,i,a,r,s,o).pipe(Ni(c=>{if(c instanceof Jc)return q(null);throw c}))),Ks(a=>!!a),Ni((a,l)=>{if(a instanceof Hc||\"EmptyError\"===a.name)return Sw(e,r,s)?q(new ye([],{})):Pa(e);throw a}))}expandSegmentAgainstRoute(t,e,i,r,s,o,a){return Ew(r,e,s,o)?void 0===r.redirectTo?this.matchSegmentAgainstRoute(t,e,r,s,o):a&&this.allowRedirects?this.expandSegmentAgainstRouteUsingRedirect(t,e,i,r,s,o):Pa(e):Pa(e)}expandSegmentAgainstRouteUsingRedirect(t,e,i,r,s,o){return\"**\"===r.path?this.expandWildCardWithParamsAgainstRouteUsingRedirect(t,i,r,o):this.expandRegularSegmentAgainstRouteUsingRedirect(t,e,i,r,s,o)}expandWildCardWithParamsAgainstRouteUsingRedirect(t,e,i,r){const s=this.applyRedirectCommands([],i.redirectTo,{});return i.redirectTo.startsWith(\"/\")?Tw(s):this.lineralizeSegments(i,s).pipe(lt(o=>{const a=new ye(o,{});return this.expandSegment(t,a,e,o,r,!1)}))}expandRegularSegmentAgainstRouteUsingRedirect(t,e,i,r,s,o){const{matched:a,consumedSegments:l,remainingSegments:c,positionalParamSegments:d}=Kc(e,r,s);if(!a)return Pa(e);const u=this.applyRedirectCommands(l,r.redirectTo,d);return r.redirectTo.startsWith(\"/\")?Tw(u):this.lineralizeSegments(r,u).pipe(lt(h=>this.expandSegment(t,e,i,h.concat(c),o,!1)))}matchSegmentAgainstRoute(t,e,i,r,s){if(\"**\"===i.path)return i.loadChildren?(i._loadedConfig?q(i._loadedConfig):this.configLoader.load(t.injector,i)).pipe(ue(u=>(i._loadedConfig=u,new ye(r,{})))):q(new ye(r,{}));const{matched:o,consumedSegments:a,remainingSegments:l}=Kc(e,i,r);return o?this.getChildConfig(t,i,r).pipe(lt(d=>{const u=d.module,h=d.routes,{segmentGroup:p,slicedSegments:m}=Zc(e,a,l,h),g=new ye(p.segments,p.children);if(0===m.length&&g.hasChildren())return this.expandChildren(u,h,g).pipe(ue(M=>new ye(a,M)));if(0===h.length&&0===m.length)return q(new ye(a,{}));const _=Tn(i)===s;return this.expandSegment(u,g,h,m,_?me:s,!0).pipe(ue(v=>new ye(a.concat(v.segments),v.children)))})):Pa(e)}getChildConfig(t,e,i){return e.children?q(new Of(e.children,t)):e.loadChildren?void 0!==e._loadedConfig?q(e._loadedConfig):this.runCanLoadGuards(t.injector,e,i).pipe(lt(r=>r?this.configLoader.load(t.injector,e).pipe(ue(s=>(e._loadedConfig=s,s))):function LV(n){return Ma(wf(`Cannot load children because the guard of the route \"path: '${n.path}'\" returned false`))}(e))):q(new Of([],t))}runCanLoadGuards(t,e,i){const r=e.canLoad;return r&&0!==r.length?q(r.map(o=>{const a=t.get(o);let l;if(function MV(n){return n&&nr(n.canLoad)}(a))l=a.canLoad(e,i);else{if(!nr(a))throw new Error(\"Invalid CanLoad guard\");l=a(e,i)}return _i(l)})).pipe(Ra(),Mt(o=>{if(!Lr(o))return;const a=wf(`Redirecting to \"${this.urlSerializer.serialize(o)}\"`);throw a.url=o,a}),ue(o=>!0===o)):q(!0)}lineralizeSegments(t,e){let i=[],r=e.root;for(;;){if(i=i.concat(r.segments),0===r.numberOfChildren)return q(i);if(r.numberOfChildren>1||!r.children[me])return Ma(new Error(`Only absolute redirects can have named outlets. redirectTo: '${t.redirectTo}'`));r=r.children[me]}}applyRedirectCommands(t,e,i){return this.applyRedirectCreatreUrlTree(e,this.urlSerializer.parse(e),t,i)}applyRedirectCreatreUrlTree(t,e,i,r){const s=this.createSegmentGroup(t,e.root,i,r);return new Fr(s,this.createQueryParams(e.queryParams,this.urlTree.queryParams),e.fragment)}createQueryParams(t,e){const i={};return At(t,(r,s)=>{if(\"string\"==typeof r&&r.startsWith(\":\")){const a=r.substring(1);i[s]=e[a]}else i[s]=r}),i}createSegmentGroup(t,e,i,r){const s=this.createSegments(t,e.segments,i,r);let o={};return At(e.children,(a,l)=>{o[l]=this.createSegmentGroup(t,a,i,r)}),new ye(s,o)}createSegments(t,e,i,r){return e.map(s=>s.path.startsWith(\":\")?this.findPosParam(t,s,r):this.findOrReturn(s,i))}findPosParam(t,e,i){const r=i[e.path.substring(1)];if(!r)throw new Error(`Cannot redirect to '${t}'. Cannot find '${e.path}'.`);return r}findOrReturn(t,e){let i=0;for(const r of e){if(r.path===t.path)return e.splice(i),r;i++}return t}}function Nf(n){const t={};for(const i of Object.keys(n.children)){const s=Nf(n.children[i]);(s.segments.length>0||s.hasChildren())&&(t[i]=s)}return function HV(n){if(1===n.numberOfChildren&&n.children[me]){const t=n.children[me];return new ye(n.segments.concat(t.segments),t.children)}return n}(new ye(n.segments,t))}class Aw{constructor(t){this.path=t,this.route=this.path[this.path.length-1]}}class ed{constructor(t,e){this.component=t,this.route=e}}function zV(n,t,e){const i=n._root;return Fa(i,t?t._root:null,e,[i.value])}function td(n,t,e){const i=function $V(n){if(!n)return null;for(let t=n.parent;t;t=t.parent){const e=t.routeConfig;if(e&&e._loadedConfig)return e._loadedConfig}return null}(t);return(i?i.module.injector:e).get(n)}function Fa(n,t,e,i,r={canDeactivateChecks:[],canActivateChecks:[]}){const s=Xs(t);return n.children.forEach(o=>{(function GV(n,t,e,i,r={canDeactivateChecks:[],canActivateChecks:[]}){const s=n.value,o=t?t.value:null,a=e?e.getContext(n.value.outlet):null;if(o&&s.routeConfig===o.routeConfig){const l=function WV(n,t,e){if(\"function\"==typeof e)return e(n,t);switch(e){case\"pathParamsChange\":return!Nr(n.url,t.url);case\"pathParamsOrQueryParamsChange\":return!Nr(n.url,t.url)||!gi(n.queryParams,t.queryParams);case\"always\":return!0;case\"paramsOrQueryParamsChange\":return!Tf(n,t)||!gi(n.queryParams,t.queryParams);default:return!Tf(n,t)}}(o,s,s.routeConfig.runGuardsAndResolvers);l?r.canActivateChecks.push(new Aw(i)):(s.data=o.data,s._resolvedData=o._resolvedData),Fa(n,t,s.component?a?a.children:null:e,i,r),l&&a&&a.outlet&&a.outlet.isActivated&&r.canDeactivateChecks.push(new ed(a.outlet.component,o))}else o&&Na(t,a,r),r.canActivateChecks.push(new Aw(i)),Fa(n,null,s.component?a?a.children:null:e,i,r)})(o,s[o.value.outlet],e,i.concat([o.value]),r),delete s[o.value.outlet]}),At(s,(o,a)=>Na(o,e.getContext(a),r)),r}function Na(n,t,e){const i=Xs(n),r=n.value;At(i,(s,o)=>{Na(s,r.component?t?t.children.getContext(o):null:t,e)}),e.canDeactivateChecks.push(new ed(r.component&&t&&t.outlet&&t.outlet.isActivated?t.outlet.component:null,r))}class t2{}function Iw(n){return new Ve(t=>t.error(n))}class r2{constructor(t,e,i,r,s,o){this.rootComponentType=t,this.config=e,this.urlTree=i,this.url=r,this.paramsInheritanceStrategy=s,this.relativeLinkResolution=o}recognize(){const t=Zc(this.urlTree.root,[],[],this.config.filter(o=>void 0===o.redirectTo),this.relativeLinkResolution).segmentGroup,e=this.processSegmentGroup(this.config,t,me);if(null===e)return null;const i=new qc([],Object.freeze({}),Object.freeze(Object.assign({},this.urlTree.queryParams)),this.urlTree.fragment,{},me,this.rootComponentType,null,this.urlTree.root,-1,{}),r=new Bi(i,e),s=new mw(this.url,r);return this.inheritParamsAndData(s._root),s}inheritParamsAndData(t){const e=t.value,i=fw(e,this.paramsInheritanceStrategy);e.params=Object.freeze(i.params),e.data=Object.freeze(i.data),t.children.forEach(r=>this.inheritParamsAndData(r))}processSegmentGroup(t,e,i){return 0===e.segments.length&&e.hasChildren()?this.processChildren(t,e):this.processSegment(t,e,e.segments,i)}processChildren(t,e){const i=[];for(const s of Object.keys(e.children)){const o=e.children[s],a=Mw(t,s),l=this.processSegmentGroup(a,o,s);if(null===l)return null;i.push(...l)}const r=Rw(i);return function s2(n){n.sort((t,e)=>t.value.outlet===me?-1:e.value.outlet===me?1:t.value.outlet.localeCompare(e.value.outlet))}(r),r}processSegment(t,e,i,r){for(const s of t){const o=this.processSegmentAgainstRoute(s,e,i,r);if(null!==o)return o}return Sw(e,i,r)?[]:null}processSegmentAgainstRoute(t,e,i,r){if(t.redirectTo||!Ew(t,e,i,r))return null;let s,o=[],a=[];if(\"**\"===t.path){const p=i.length>0?ew(i).parameters:{};s=new qc(i,p,Object.freeze(Object.assign({},this.urlTree.queryParams)),this.urlTree.fragment,Fw(t),Tn(t),t.component,t,Ow(e),Pw(e)+i.length,Nw(t))}else{const p=Kc(e,t,i);if(!p.matched)return null;o=p.consumedSegments,a=p.remainingSegments,s=new qc(o,p.parameters,Object.freeze(Object.assign({},this.urlTree.queryParams)),this.urlTree.fragment,Fw(t),Tn(t),t.component,t,Ow(e),Pw(e)+o.length,Nw(t))}const l=function o2(n){return n.children?n.children:n.loadChildren?n._loadedConfig.routes:[]}(t),{segmentGroup:c,slicedSegments:d}=Zc(e,o,a,l.filter(p=>void 0===p.redirectTo),this.relativeLinkResolution);if(0===d.length&&c.hasChildren()){const p=this.processChildren(l,c);return null===p?null:[new Bi(s,p)]}if(0===l.length&&0===d.length)return[new Bi(s,[])];const u=Tn(t)===r,h=this.processSegment(l,c,d,u?me:r);return null===h?null:[new Bi(s,h)]}}function a2(n){const t=n.value.routeConfig;return t&&\"\"===t.path&&void 0===t.redirectTo}function Rw(n){const t=[],e=new Set;for(const i of n){if(!a2(i)){t.push(i);continue}const r=t.find(s=>i.value.routeConfig===s.value.routeConfig);void 0!==r?(r.children.push(...i.children),e.add(r)):t.push(i)}for(const i of e){const r=Rw(i.children);t.push(new Bi(i.value,r))}return t.filter(i=>!e.has(i))}function Ow(n){let t=n;for(;t._sourceSegment;)t=t._sourceSegment;return t}function Pw(n){let t=n,e=t._segmentIndexShift?t._segmentIndexShift:0;for(;t._sourceSegment;)t=t._sourceSegment,e+=t._segmentIndexShift?t._segmentIndexShift:0;return e-1}function Fw(n){return n.data||{}}function Nw(n){return n.resolve||{}}function Lw(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n)]}function Lf(n){return kn(t=>{const e=n(t);return e?mt(e).pipe(ue(()=>t)):q(t)})}class m2 extends class f2{shouldDetach(t){return!1}store(t,e){}shouldAttach(t){return!1}retrieve(t){return null}shouldReuseRoute(t,e){return t.routeConfig===e.routeConfig}}{}const Bf=new b(\"ROUTES\");class Bw{constructor(t,e,i,r){this.injector=t,this.compiler=e,this.onLoadStartListener=i,this.onLoadEndListener=r}load(t,e){if(e._loader$)return e._loader$;this.onLoadStartListener&&this.onLoadStartListener(e);const r=this.loadModuleFactory(e.loadChildren).pipe(ue(s=>{this.onLoadEndListener&&this.onLoadEndListener(e);const o=s.create(t);return new Of(JD(o.injector.get(Bf,void 0,ee.Self|ee.Optional)).map(Ff),o)}),Ni(s=>{throw e._loader$=void 0,s}));return e._loader$=new kB(r,()=>new O).pipe(zD()),e._loader$}loadModuleFactory(t){return _i(t()).pipe(lt(e=>e instanceof KC?q(e):mt(this.compiler.compileModuleAsync(e))))}}class _2{shouldProcessUrl(t){return!0}extract(t){return t}merge(t,e){return t}}function v2(n){throw n}function y2(n,t,e){return t.parse(\"/\")}function Vw(n,t){return q(null)}const b2={paths:\"exact\",fragment:\"ignored\",matrixParams:\"ignored\",queryParams:\"exact\"},C2={paths:\"subset\",fragment:\"ignored\",matrixParams:\"ignored\",queryParams:\"subset\"};let cn=(()=>{class n{constructor(e,i,r,s,o,a,l){this.rootComponentType=e,this.urlSerializer=i,this.rootContexts=r,this.location=s,this.config=l,this.lastSuccessfulNavigation=null,this.currentNavigation=null,this.disposed=!1,this.navigationId=0,this.currentPageId=0,this.isNgZoneEnabled=!1,this.events=new O,this.errorHandler=v2,this.malformedUriErrorHandler=y2,this.navigated=!1,this.lastSuccessfulId=-1,this.hooks={beforePreactivation:Vw,afterPreactivation:Vw},this.urlHandlingStrategy=new _2,this.routeReuseStrategy=new m2,this.onSameUrlNavigation=\"ignore\",this.paramsInheritanceStrategy=\"emptyOnly\",this.urlUpdateStrategy=\"deferred\",this.relativeLinkResolution=\"corrected\",this.canceledNavigationResolution=\"replace\",this.ngModule=o.get(Ri),this.console=o.get(O0);const u=o.get(ne);this.isNgZoneEnabled=u instanceof ne&&ne.isInAngularZone(),this.resetConfig(l),this.currentUrlTree=function WB(){return new Fr(new ye([],{}),{},null)}(),this.rawUrlTree=this.currentUrlTree,this.browserUrlTree=this.currentUrlTree,this.configLoader=new Bw(o,a,h=>this.triggerEvent(new YD(h)),h=>this.triggerEvent(new QD(h))),this.routerState=pw(this.currentUrlTree,this.rootComponentType),this.transitions=new Zt({id:0,targetPageId:0,currentUrlTree:this.currentUrlTree,currentRawUrl:this.currentUrlTree,extractedUrl:this.urlHandlingStrategy.extract(this.currentUrlTree),urlAfterRedirects:this.urlHandlingStrategy.extract(this.currentUrlTree),rawUrl:this.currentUrlTree,extras:{},resolve:null,reject:null,promise:Promise.resolve(!0),source:\"imperative\",restoredState:null,currentSnapshot:this.routerState.snapshot,targetSnapshot:null,currentRouterState:this.routerState,targetRouterState:null,guards:{canActivateChecks:[],canDeactivateChecks:[]},guardsResult:null}),this.navigations=this.setupNavigations(this.transitions),this.processNavigations()}get browserPageId(){var e;return null===(e=this.location.getState())||void 0===e?void 0:e.\\u0275routerPageId}setupNavigations(e){const i=this.events;return e.pipe(Ct(r=>0!==r.id),ue(r=>Object.assign(Object.assign({},r),{extractedUrl:this.urlHandlingStrategy.extract(r.rawUrl)})),kn(r=>{let s=!1,o=!1;return q(r).pipe(Mt(a=>{this.currentNavigation={id:a.id,initialUrl:a.currentRawUrl,extractedUrl:a.extractedUrl,trigger:a.source,extras:a.extras,previousNavigation:this.lastSuccessfulNavigation?Object.assign(Object.assign({},this.lastSuccessfulNavigation),{previousNavigation:null}):null}}),kn(a=>{const l=this.browserUrlTree.toString(),c=!this.navigated||a.extractedUrl.toString()!==l||l!==this.currentUrlTree.toString();if((\"reload\"===this.onSameUrlNavigation||c)&&this.urlHandlingStrategy.shouldProcessUrl(a.rawUrl))return Hw(a.source)&&(this.browserUrlTree=a.extractedUrl),q(a).pipe(kn(u=>{const h=this.transitions.getValue();return i.next(new Df(u.id,this.serializeUrl(u.extractedUrl),u.source,u.restoredState)),h!==this.transitions.getValue()?ri:Promise.resolve(u)}),function jV(n,t,e,i){return kn(r=>function BV(n,t,e,i,r){return new VV(n,t,e,i,r).apply()}(n,t,e,r.extractedUrl,i).pipe(ue(s=>Object.assign(Object.assign({},r),{urlAfterRedirects:s}))))}(this.ngModule.injector,this.configLoader,this.urlSerializer,this.config),Mt(u=>{this.currentNavigation=Object.assign(Object.assign({},this.currentNavigation),{finalUrl:u.urlAfterRedirects})}),function l2(n,t,e,i,r){return lt(s=>function n2(n,t,e,i,r=\"emptyOnly\",s=\"legacy\"){try{const o=new r2(n,t,e,i,r,s).recognize();return null===o?Iw(new t2):q(o)}catch(o){return Iw(o)}}(n,t,s.urlAfterRedirects,e(s.urlAfterRedirects),i,r).pipe(ue(o=>Object.assign(Object.assign({},s),{targetSnapshot:o}))))}(this.rootComponentType,this.config,u=>this.serializeUrl(u),this.paramsInheritanceStrategy,this.relativeLinkResolution),Mt(u=>{if(\"eager\"===this.urlUpdateStrategy){if(!u.extras.skipLocationChange){const p=this.urlHandlingStrategy.merge(u.urlAfterRedirects,u.rawUrl);this.setBrowserUrl(p,u)}this.browserUrlTree=u.urlAfterRedirects}const h=new OB(u.id,this.serializeUrl(u.extractedUrl),this.serializeUrl(u.urlAfterRedirects),u.targetSnapshot);i.next(h)}));if(c&&this.rawUrlTree&&this.urlHandlingStrategy.shouldProcessUrl(this.rawUrlTree)){const{id:h,extractedUrl:p,source:m,restoredState:g,extras:_}=a,D=new Df(h,this.serializeUrl(p),m,g);i.next(D);const v=pw(p,this.rootComponentType).snapshot;return q(Object.assign(Object.assign({},a),{targetSnapshot:v,urlAfterRedirects:p,extras:Object.assign(Object.assign({},_),{skipLocationChange:!1,replaceUrl:!1})}))}return this.rawUrlTree=a.rawUrl,a.resolve(null),ri}),Lf(a=>{const{targetSnapshot:l,id:c,extractedUrl:d,rawUrl:u,extras:{skipLocationChange:h,replaceUrl:p}}=a;return this.hooks.beforePreactivation(l,{navigationId:c,appliedUrlTree:d,rawUrlTree:u,skipLocationChange:!!h,replaceUrl:!!p})}),Mt(a=>{const l=new PB(a.id,this.serializeUrl(a.extractedUrl),this.serializeUrl(a.urlAfterRedirects),a.targetSnapshot);this.triggerEvent(l)}),ue(a=>Object.assign(Object.assign({},a),{guards:zV(a.targetSnapshot,a.currentSnapshot,this.rootContexts)})),function qV(n,t){return lt(e=>{const{targetSnapshot:i,currentSnapshot:r,guards:{canActivateChecks:s,canDeactivateChecks:o}}=e;return 0===o.length&&0===s.length?q(Object.assign(Object.assign({},e),{guardsResult:!0})):function YV(n,t,e,i){return mt(n).pipe(lt(r=>function e2(n,t,e,i,r){const s=t&&t.routeConfig?t.routeConfig.canDeactivate:null;return s&&0!==s.length?q(s.map(a=>{const l=td(a,t,r);let c;if(function SV(n){return n&&nr(n.canDeactivate)}(l))c=_i(l.canDeactivate(n,t,e,i));else{if(!nr(l))throw new Error(\"Invalid CanDeactivate guard\");c=_i(l(n,t,e,i))}return c.pipe(Ks())})).pipe(Ra()):q(!0)}(r.component,r.route,e,t,i)),Ks(r=>!0!==r,!0))}(o,i,r,n).pipe(lt(a=>a&&function wV(n){return\"boolean\"==typeof n}(a)?function QV(n,t,e,i){return mt(t).pipe(Qs(r=>jc(function ZV(n,t){return null!==n&&t&&t(new BB(n)),q(!0)}(r.route.parent,i),function KV(n,t){return null!==n&&t&&t(new HB(n)),q(!0)}(r.route,i),function JV(n,t,e){const i=t[t.length-1],s=t.slice(0,t.length-1).reverse().map(o=>function UV(n){const t=n.routeConfig?n.routeConfig.canActivateChild:null;return t&&0!==t.length?{node:n,guards:t}:null}(o)).filter(o=>null!==o).map(o=>xa(()=>q(o.guards.map(l=>{const c=td(l,o.node,e);let d;if(function EV(n){return n&&nr(n.canActivateChild)}(c))d=_i(c.canActivateChild(i,n));else{if(!nr(c))throw new Error(\"Invalid CanActivateChild guard\");d=_i(c(i,n))}return d.pipe(Ks())})).pipe(Ra())));return q(s).pipe(Ra())}(n,r.path,e),function XV(n,t,e){const i=t.routeConfig?t.routeConfig.canActivate:null;if(!i||0===i.length)return q(!0);const r=i.map(s=>xa(()=>{const o=td(s,t,e);let a;if(function xV(n){return n&&nr(n.canActivate)}(o))a=_i(o.canActivate(t,n));else{if(!nr(o))throw new Error(\"Invalid CanActivate guard\");a=_i(o(t,n))}return a.pipe(Ks())}));return q(r).pipe(Ra())}(n,r.route,e))),Ks(r=>!0!==r,!0))}(i,s,n,t):q(a)),ue(a=>Object.assign(Object.assign({},e),{guardsResult:a})))})}(this.ngModule.injector,a=>this.triggerEvent(a)),Mt(a=>{if(Lr(a.guardsResult)){const c=wf(`Redirecting to \"${this.serializeUrl(a.guardsResult)}\"`);throw c.url=a.guardsResult,c}const l=new FB(a.id,this.serializeUrl(a.extractedUrl),this.serializeUrl(a.urlAfterRedirects),a.targetSnapshot,!!a.guardsResult);this.triggerEvent(l)}),Ct(a=>!!a.guardsResult||(this.restoreHistory(a),this.cancelNavigationTransition(a,\"\"),!1)),Lf(a=>{if(a.guards.canActivateChecks.length)return q(a).pipe(Mt(l=>{const c=new NB(l.id,this.serializeUrl(l.extractedUrl),this.serializeUrl(l.urlAfterRedirects),l.targetSnapshot);this.triggerEvent(c)}),kn(l=>{let c=!1;return q(l).pipe(function c2(n,t){return lt(e=>{const{targetSnapshot:i,guards:{canActivateChecks:r}}=e;if(!r.length)return q(e);let s=0;return mt(r).pipe(Qs(o=>function d2(n,t,e,i){return function u2(n,t,e,i){const r=Lw(n);if(0===r.length)return q({});const s={};return mt(r).pipe(lt(o=>function h2(n,t,e,i){const r=td(n,t,i);return _i(r.resolve?r.resolve(t,e):r(t,e))}(n[o],t,e,i).pipe(Mt(a=>{s[o]=a}))),Cf(1),lt(()=>Lw(s).length===r.length?q(s):ri))}(n._resolve,n,t,i).pipe(ue(s=>(n._resolvedData=s,n.data=Object.assign(Object.assign({},n.data),fw(n,e).resolve),null)))}(o.route,i,n,t)),Mt(()=>s++),Cf(1),lt(o=>s===r.length?q(e):ri))})}(this.paramsInheritanceStrategy,this.ngModule.injector),Mt({next:()=>c=!0,complete:()=>{c||(this.restoreHistory(l),this.cancelNavigationTransition(l,\"At least one route resolver didn't emit any value.\"))}}))}),Mt(l=>{const c=new LB(l.id,this.serializeUrl(l.extractedUrl),this.serializeUrl(l.urlAfterRedirects),l.targetSnapshot);this.triggerEvent(c)}))}),Lf(a=>{const{targetSnapshot:l,id:c,extractedUrl:d,rawUrl:u,extras:{skipLocationChange:h,replaceUrl:p}}=a;return this.hooks.afterPreactivation(l,{navigationId:c,appliedUrlTree:d,rawUrlTree:u,skipLocationChange:!!h,replaceUrl:!!p})}),ue(a=>{const l=function dV(n,t,e){const i=Ta(n,t._root,e?e._root:void 0);return new hw(i,t)}(this.routeReuseStrategy,a.targetSnapshot,a.currentRouterState);return Object.assign(Object.assign({},a),{targetRouterState:l})}),Mt(a=>{this.currentUrlTree=a.urlAfterRedirects,this.rawUrlTree=this.urlHandlingStrategy.merge(a.urlAfterRedirects,a.rawUrl),this.routerState=a.targetRouterState,\"deferred\"===this.urlUpdateStrategy&&(a.extras.skipLocationChange||this.setBrowserUrl(this.rawUrlTree,a),this.browserUrlTree=a.urlAfterRedirects)}),((n,t,e)=>ue(i=>(new CV(t,i.targetRouterState,i.currentRouterState,e).activate(n),i)))(this.rootContexts,this.routeReuseStrategy,a=>this.triggerEvent(a)),Mt({next(){s=!0},complete(){s=!0}}),function WD(n){return qe((t,e)=>{try{t.subscribe(e)}finally{e.add(n)}})}(()=>{var a;s||o||this.cancelNavigationTransition(r,`Navigation ID ${r.id} is not equal to the current navigation id ${this.navigationId}`),(null===(a=this.currentNavigation)||void 0===a?void 0:a.id)===r.id&&(this.currentNavigation=null)}),Ni(a=>{if(o=!0,function UB(n){return n&&n[ZD]}(a)){const l=Lr(a.url);l||(this.navigated=!0,this.restoreHistory(r,!0));const c=new qD(r.id,this.serializeUrl(r.extractedUrl),a.message);i.next(c),l?setTimeout(()=>{const d=this.urlHandlingStrategy.merge(a.url,this.rawUrlTree),u={skipLocationChange:r.extras.skipLocationChange,replaceUrl:\"eager\"===this.urlUpdateStrategy||Hw(r.source)};this.scheduleNavigation(d,\"imperative\",null,u,{resolve:r.resolve,reject:r.reject,promise:r.promise})},0):r.resolve(!1)}else{this.restoreHistory(r,!0);const l=new RB(r.id,this.serializeUrl(r.extractedUrl),a);i.next(l);try{r.resolve(this.errorHandler(a))}catch(c){r.reject(c)}}return ri}))}))}resetRootComponentType(e){this.rootComponentType=e,this.routerState.root.component=this.rootComponentType}setTransition(e){this.transitions.next(Object.assign(Object.assign({},this.transitions.value),e))}initialNavigation(){this.setUpLocationChangeListener(),0===this.navigationId&&this.navigateByUrl(this.location.path(!0),{replaceUrl:!0})}setUpLocationChangeListener(){this.locationSubscription||(this.locationSubscription=this.location.subscribe(e=>{const i=\"popstate\"===e.type?\"popstate\":\"hashchange\";\"popstate\"===i&&setTimeout(()=>{var r;const s={replaceUrl:!0},o=(null===(r=e.state)||void 0===r?void 0:r.navigationId)?e.state:null;if(o){const l=Object.assign({},o);delete l.navigationId,delete l.\\u0275routerPageId,0!==Object.keys(l).length&&(s.state=l)}const a=this.parseUrl(e.url);this.scheduleNavigation(a,i,o,s)},0)}))}get url(){return this.serializeUrl(this.currentUrlTree)}getCurrentNavigation(){return this.currentNavigation}triggerEvent(e){this.events.next(e)}resetConfig(e){ww(e),this.config=e.map(Ff),this.navigated=!1,this.lastSuccessfulId=-1}ngOnDestroy(){this.dispose()}dispose(){this.transitions.complete(),this.locationSubscription&&(this.locationSubscription.unsubscribe(),this.locationSubscription=void 0),this.disposed=!0}createUrlTree(e,i={}){const{relativeTo:r,queryParams:s,fragment:o,queryParamsHandling:a,preserveFragment:l}=i,c=r||this.routerState.root,d=l?this.currentUrlTree.fragment:o;let u=null;switch(a){case\"merge\":u=Object.assign(Object.assign({},this.currentUrlTree.queryParams),s);break;case\"preserve\":u=this.currentUrlTree.queryParams;break;default:u=s||null}return null!==u&&(u=this.removeEmptyProps(u)),function pV(n,t,e,i,r){if(0===e.length)return Af(t.root,t.root,t.root,i,r);const s=function fV(n){if(\"string\"==typeof n[0]&&1===n.length&&\"/\"===n[0])return new vw(!0,0,n);let t=0,e=!1;const i=n.reduce((r,s,o)=>{if(\"object\"==typeof s&&null!=s){if(s.outlets){const a={};return At(s.outlets,(l,c)=>{a[c]=\"string\"==typeof l?l.split(\"/\"):l}),[...r,{outlets:a}]}if(s.segmentPath)return[...r,s.segmentPath]}return\"string\"!=typeof s?[...r,s]:0===o?(s.split(\"/\").forEach((a,l)=>{0==l&&\".\"===a||(0==l&&\"\"===a?e=!0:\"..\"===a?t++:\"\"!=a&&r.push(a))}),r):[...r,s]},[]);return new vw(e,t,i)}(e);if(s.toRoot())return Af(t.root,t.root,new ye([],{}),i,r);const o=function mV(n,t,e){if(n.isAbsolute)return new If(t.root,!0,0);if(-1===e.snapshot._lastPathIndex){const s=e.snapshot._urlSegment;return new If(s,s===t.root,0)}const i=Yc(n.commands[0])?0:1;return function gV(n,t,e){let i=n,r=t,s=e;for(;s>r;){if(s-=r,i=i.parent,!i)throw new Error(\"Invalid number of '../'\");r=i.segments.length}return new If(i,!1,r-s)}(e.snapshot._urlSegment,e.snapshot._lastPathIndex+i,n.numberOfDoubleDots)}(s,t,n),a=o.processChildren?Qc(o.segmentGroup,o.index,s.commands):yw(o.segmentGroup,o.index,s.commands);return Af(t.root,o.segmentGroup,a,i,r)}(c,this.currentUrlTree,e,u,null!=d?d:null)}navigateByUrl(e,i={skipLocationChange:!1}){const r=Lr(e)?e:this.parseUrl(e),s=this.urlHandlingStrategy.merge(r,this.rawUrlTree);return this.scheduleNavigation(s,\"imperative\",null,i)}navigate(e,i={skipLocationChange:!1}){return function D2(n){for(let t=0;t<n.length;t++){const e=n[t];if(null==e)throw new Error(`The requested path contains ${e} segment at index ${t}`)}}(e),this.navigateByUrl(this.createUrlTree(e,i),i)}serializeUrl(e){return this.urlSerializer.serialize(e)}parseUrl(e){let i;try{i=this.urlSerializer.parse(e)}catch(r){i=this.malformedUriErrorHandler(r,this.urlSerializer,e)}return i}isActive(e,i){let r;if(r=!0===i?Object.assign({},b2):!1===i?Object.assign({},C2):i,Lr(e))return nw(this.currentUrlTree,e,r);const s=this.parseUrl(e);return nw(this.currentUrlTree,s,r)}removeEmptyProps(e){return Object.keys(e).reduce((i,r)=>{const s=e[r];return null!=s&&(i[r]=s),i},{})}processNavigations(){this.navigations.subscribe(e=>{this.navigated=!0,this.lastSuccessfulId=e.id,this.currentPageId=e.targetPageId,this.events.next(new Ea(e.id,this.serializeUrl(e.extractedUrl),this.serializeUrl(this.currentUrlTree))),this.lastSuccessfulNavigation=this.currentNavigation,e.resolve(!0)},e=>{this.console.warn(`Unhandled Navigation Error: ${e}`)})}scheduleNavigation(e,i,r,s,o){var a,l;if(this.disposed)return Promise.resolve(!1);let c,d,u;o?(c=o.resolve,d=o.reject,u=o.promise):u=new Promise((m,g)=>{c=m,d=g});const h=++this.navigationId;let p;return\"computed\"===this.canceledNavigationResolution?(0===this.currentPageId&&(r=this.location.getState()),p=r&&r.\\u0275routerPageId?r.\\u0275routerPageId:s.replaceUrl||s.skipLocationChange?null!==(a=this.browserPageId)&&void 0!==a?a:0:(null!==(l=this.browserPageId)&&void 0!==l?l:0)+1):p=0,this.setTransition({id:h,targetPageId:p,source:i,restoredState:r,currentUrlTree:this.currentUrlTree,currentRawUrl:this.rawUrlTree,rawUrl:e,extras:s,resolve:c,reject:d,promise:u,currentSnapshot:this.routerState.snapshot,currentRouterState:this.routerState}),u.catch(m=>Promise.reject(m))}setBrowserUrl(e,i){const r=this.urlSerializer.serialize(e),s=Object.assign(Object.assign({},i.extras.state),this.generateNgRouterState(i.id,i.targetPageId));this.location.isCurrentPathEqualTo(r)||i.extras.replaceUrl?this.location.replaceState(r,\"\",s):this.location.go(r,\"\",s)}restoreHistory(e,i=!1){var r,s;if(\"computed\"===this.canceledNavigationResolution){const o=this.currentPageId-e.targetPageId;\"popstate\"!==e.source&&\"eager\"!==this.urlUpdateStrategy&&this.currentUrlTree!==(null===(r=this.currentNavigation)||void 0===r?void 0:r.finalUrl)||0===o?this.currentUrlTree===(null===(s=this.currentNavigation)||void 0===s?void 0:s.finalUrl)&&0===o&&(this.resetState(e),this.browserUrlTree=e.currentUrlTree,this.resetUrlToCurrentUrlTree()):this.location.historyGo(o)}else\"replace\"===this.canceledNavigationResolution&&(i&&this.resetState(e),this.resetUrlToCurrentUrlTree())}resetState(e){this.routerState=e.currentRouterState,this.currentUrlTree=e.currentUrlTree,this.rawUrlTree=this.urlHandlingStrategy.merge(this.currentUrlTree,e.rawUrl)}resetUrlToCurrentUrlTree(){this.location.replaceState(this.urlSerializer.serialize(this.rawUrlTree),\"\",this.generateNgRouterState(this.lastSuccessfulId,this.currentPageId))}cancelNavigationTransition(e,i){const r=new qD(e.id,this.serializeUrl(e.extractedUrl),i);this.triggerEvent(r),e.resolve(!1)}generateNgRouterState(e,i){return\"computed\"===this.canceledNavigationResolution?{navigationId:e,\\u0275routerPageId:i}:{navigationId:e}}}return n.\\u0275fac=function(e){Sr()},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();function Hw(n){return\"imperative\"!==n}class jw{}class zw{preload(t,e){return q(null)}}let Uw=(()=>{class n{constructor(e,i,r,s){this.router=e,this.injector=r,this.preloadingStrategy=s,this.loader=new Bw(r,i,l=>e.triggerEvent(new YD(l)),l=>e.triggerEvent(new QD(l)))}setUpPreloading(){this.subscription=this.router.events.pipe(Ct(e=>e instanceof Ea),Qs(()=>this.preload())).subscribe(()=>{})}preload(){const e=this.injector.get(Ri);return this.processRoutes(e,this.router.config)}ngOnDestroy(){this.subscription&&this.subscription.unsubscribe()}processRoutes(e,i){const r=[];for(const s of i)if(s.loadChildren&&!s.canLoad&&s._loadedConfig){const o=s._loadedConfig;r.push(this.processRoutes(o.module,o.routes))}else s.loadChildren&&!s.canLoad?r.push(this.preloadConfig(e,s)):s.children&&r.push(this.processRoutes(e,s.children));return mt(r).pipe(Eo(),ue(s=>{}))}preloadConfig(e,i){return this.preloadingStrategy.preload(i,()=>(i._loadedConfig?q(i._loadedConfig):this.loader.load(e.injector,i)).pipe(lt(s=>(i._loadedConfig=s,this.processRoutes(s.module,s.routes)))))}}return n.\\u0275fac=function(e){return new(e||n)(y(cn),y(P0),y(dt),y(jw))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),jf=(()=>{class n{constructor(e,i,r={}){this.router=e,this.viewportScroller=i,this.options=r,this.lastId=0,this.lastSource=\"imperative\",this.restoredId=0,this.store={},r.scrollPositionRestoration=r.scrollPositionRestoration||\"disabled\",r.anchorScrolling=r.anchorScrolling||\"disabled\"}init(){\"disabled\"!==this.options.scrollPositionRestoration&&this.viewportScroller.setHistoryScrollRestoration(\"manual\"),this.routerEventsSubscription=this.createScrollEvents(),this.scrollEventsSubscription=this.consumeScrollEvents()}createScrollEvents(){return this.router.events.subscribe(e=>{e instanceof Df?(this.store[this.lastId]=this.viewportScroller.getScrollPosition(),this.lastSource=e.navigationTrigger,this.restoredId=e.restoredState?e.restoredState.navigationId:0):e instanceof Ea&&(this.lastId=e.id,this.scheduleScrollEvent(e,this.router.parseUrl(e.urlAfterRedirects).fragment))})}consumeScrollEvents(){return this.router.events.subscribe(e=>{e instanceof KD&&(e.position?\"top\"===this.options.scrollPositionRestoration?this.viewportScroller.scrollToPosition([0,0]):\"enabled\"===this.options.scrollPositionRestoration&&this.viewportScroller.scrollToPosition(e.position):e.anchor&&\"enabled\"===this.options.anchorScrolling?this.viewportScroller.scrollToAnchor(e.anchor):\"disabled\"!==this.options.scrollPositionRestoration&&this.viewportScroller.scrollToPosition([0,0]))})}scheduleScrollEvent(e,i){this.router.triggerEvent(new KD(e,\"popstate\"===this.lastSource?this.store[this.restoredId]:null,i))}ngOnDestroy(){this.routerEventsSubscription&&this.routerEventsSubscription.unsubscribe(),this.scrollEventsSubscription&&this.scrollEventsSubscription.unsubscribe()}}return n.\\u0275fac=function(e){Sr()},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const Br=new b(\"ROUTER_CONFIGURATION\"),$w=new b(\"ROUTER_FORROOT_GUARD\"),E2=[va,{provide:ow,useClass:aw},{provide:cn,useFactory:function I2(n,t,e,i,r,s,o={},a,l){const c=new cn(null,n,t,e,i,r,JD(s));return a&&(c.urlHandlingStrategy=a),l&&(c.routeReuseStrategy=l),function R2(n,t){n.errorHandler&&(t.errorHandler=n.errorHandler),n.malformedUriErrorHandler&&(t.malformedUriErrorHandler=n.malformedUriErrorHandler),n.onSameUrlNavigation&&(t.onSameUrlNavigation=n.onSameUrlNavigation),n.paramsInheritanceStrategy&&(t.paramsInheritanceStrategy=n.paramsInheritanceStrategy),n.relativeLinkResolution&&(t.relativeLinkResolution=n.relativeLinkResolution),n.urlUpdateStrategy&&(t.urlUpdateStrategy=n.urlUpdateStrategy),n.canceledNavigationResolution&&(t.canceledNavigationResolution=n.canceledNavigationResolution)}(o,c),o.enableTracing&&c.events.subscribe(d=>{var u,h;null===(u=console.group)||void 0===u||u.call(console,`Router Event: ${d.constructor.name}`),console.log(d.toString()),console.log(d),null===(h=console.groupEnd)||void 0===h||h.call(console)}),c},deps:[ow,Oa,va,dt,P0,Bf,Br,[class g2{},new Tt],[class p2{},new Tt]]},Oa,{provide:Js,useFactory:function O2(n){return n.routerState.root},deps:[cn]},Uw,zw,class x2{preload(t,e){return e().pipe(Ni(()=>q(null)))}},{provide:Br,useValue:{enableTracing:!1}}];function S2(){return new V0(\"Router\",cn)}let Gw=(()=>{class n{constructor(e,i){}static forRoot(e,i){return{ngModule:n,providers:[E2,Ww(e),{provide:$w,useFactory:A2,deps:[[cn,new Tt,new Cn]]},{provide:Br,useValue:i||{}},{provide:qs,useFactory:T2,deps:[Pr,[new Gl(Xp),new Tt],Br]},{provide:jf,useFactory:k2,deps:[cn,PL,Br]},{provide:jw,useExisting:i&&i.preloadingStrategy?i.preloadingStrategy:zw},{provide:V0,multi:!0,useFactory:S2},[zf,{provide:Bp,multi:!0,useFactory:P2,deps:[zf]},{provide:qw,useFactory:F2,deps:[zf]},{provide:R0,multi:!0,useExisting:qw}]]}}static forChild(e){return{ngModule:n,providers:[Ww(e)]}}}return n.\\u0275fac=function(e){return new(e||n)(y($w,8),y(cn,8))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();function k2(n,t,e){return e.scrollOffset&&t.setOffset(e.scrollOffset),new jf(n,t,e)}function T2(n,t,e={}){return e.useHash?new vN(n,t):new sD(n,t)}function A2(n){return\"guarded\"}function Ww(n){return[{provide:nA,multi:!0,useValue:n},{provide:Bf,multi:!0,useValue:n}]}let zf=(()=>{class n{constructor(e){this.injector=e,this.initNavigation=!1,this.destroyed=!1,this.resultOfPreactivationDone=new O}appInitializer(){return this.injector.get(mN,Promise.resolve(null)).then(()=>{if(this.destroyed)return Promise.resolve(!0);let i=null;const r=new Promise(a=>i=a),s=this.injector.get(cn),o=this.injector.get(Br);return\"disabled\"===o.initialNavigation?(s.setUpLocationChangeListener(),i(!0)):\"enabled\"===o.initialNavigation||\"enabledBlocking\"===o.initialNavigation?(s.hooks.afterPreactivation=()=>this.initNavigation?q(null):(this.initNavigation=!0,i(!0),this.resultOfPreactivationDone),s.initialNavigation()):i(!0),r})}bootstrapListener(e){const i=this.injector.get(Br),r=this.injector.get(Uw),s=this.injector.get(jf),o=this.injector.get(cn),a=this.injector.get(Cc);e===a.components[0]&&((\"enabledNonBlocking\"===i.initialNavigation||void 0===i.initialNavigation)&&o.initialNavigation(),r.setUpPreloading(),s.init(),o.resetRootComponentType(a.componentTypes[0]),this.resultOfPreactivationDone.next(null),this.resultOfPreactivationDone.complete())}ngOnDestroy(){this.destroyed=!0}}return n.\\u0275fac=function(e){return new(e||n)(y(dt))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();function P2(n){return n.appInitializer.bind(n)}function F2(n){return n.bootstrapListener.bind(n)}const qw=new b(\"Router Initializer\"),L2=[];let B2=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Gw.forRoot(L2)],Gw]}),n})();class Yw{}const Vi=\"*\";function Ke(n,t){return{type:7,name:n,definitions:t,options:{}}}function be(n,t=null){return{type:4,styles:t,timings:n}}function nd(n,t=null){return{type:3,steps:n,options:t}}function Qw(n,t=null){return{type:2,steps:n,options:t}}function R(n){return{type:6,styles:n,offset:null}}function ae(n,t,e){return{type:0,name:n,styles:t,options:e}}function ge(n,t,e=null){return{type:1,expr:n,animation:t,options:e}}function to(n=null){return{type:9,options:n}}function no(n,t,e=null){return{type:11,selector:n,animation:t,options:e}}function Kw(n){Promise.resolve(null).then(n)}class La{constructor(t=0,e=0){this._onDoneFns=[],this._onStartFns=[],this._onDestroyFns=[],this._started=!1,this._destroyed=!1,this._finished=!1,this._position=0,this.parentPlayer=null,this.totalTime=t+e}_onFinish(){this._finished||(this._finished=!0,this._onDoneFns.forEach(t=>t()),this._onDoneFns=[])}onStart(t){this._onStartFns.push(t)}onDone(t){this._onDoneFns.push(t)}onDestroy(t){this._onDestroyFns.push(t)}hasStarted(){return this._started}init(){}play(){this.hasStarted()||(this._onStart(),this.triggerMicrotask()),this._started=!0}triggerMicrotask(){Kw(()=>this._onFinish())}_onStart(){this._onStartFns.forEach(t=>t()),this._onStartFns=[]}pause(){}restart(){}finish(){this._onFinish()}destroy(){this._destroyed||(this._destroyed=!0,this.hasStarted()||this._onStart(),this.finish(),this._onDestroyFns.forEach(t=>t()),this._onDestroyFns=[])}reset(){this._started=!1}setPosition(t){this._position=this.totalTime?t*this.totalTime:1}getPosition(){return this.totalTime?this._position/this.totalTime:1}triggerCallback(t){const e=\"start\"==t?this._onStartFns:this._onDoneFns;e.forEach(i=>i()),e.length=0}}class Zw{constructor(t){this._onDoneFns=[],this._onStartFns=[],this._finished=!1,this._started=!1,this._destroyed=!1,this._onDestroyFns=[],this.parentPlayer=null,this.totalTime=0,this.players=t;let e=0,i=0,r=0;const s=this.players.length;0==s?Kw(()=>this._onFinish()):this.players.forEach(o=>{o.onDone(()=>{++e==s&&this._onFinish()}),o.onDestroy(()=>{++i==s&&this._onDestroy()}),o.onStart(()=>{++r==s&&this._onStart()})}),this.totalTime=this.players.reduce((o,a)=>Math.max(o,a.totalTime),0)}_onFinish(){this._finished||(this._finished=!0,this._onDoneFns.forEach(t=>t()),this._onDoneFns=[])}init(){this.players.forEach(t=>t.init())}onStart(t){this._onStartFns.push(t)}_onStart(){this.hasStarted()||(this._started=!0,this._onStartFns.forEach(t=>t()),this._onStartFns=[])}onDone(t){this._onDoneFns.push(t)}onDestroy(t){this._onDestroyFns.push(t)}hasStarted(){return this._started}play(){this.parentPlayer||this.init(),this._onStart(),this.players.forEach(t=>t.play())}pause(){this.players.forEach(t=>t.pause())}restart(){this.players.forEach(t=>t.restart())}finish(){this._onFinish(),this.players.forEach(t=>t.finish())}destroy(){this._onDestroy()}_onDestroy(){this._destroyed||(this._destroyed=!0,this._onFinish(),this.players.forEach(t=>t.destroy()),this._onDestroyFns.forEach(t=>t()),this._onDestroyFns=[])}reset(){this.players.forEach(t=>t.reset()),this._destroyed=!1,this._finished=!1,this._started=!1}setPosition(t){const e=t*this.totalTime;this.players.forEach(i=>{const r=i.totalTime?Math.min(1,e/i.totalTime):1;i.setPosition(r)})}getPosition(){const t=this.players.reduce((e,i)=>null===e||i.totalTime>e.totalTime?i:e,null);return null!=t?t.getPosition():0}beforeDestroy(){this.players.forEach(t=>{t.beforeDestroy&&t.beforeDestroy()})}triggerCallback(t){const e=\"start\"==t?this._onStartFns:this._onDoneFns;e.forEach(i=>i()),e.length=0}}const Ce=!1;function Xw(n){return new H(3e3,Ce)}function yH(){return\"undefined\"!=typeof window&&void 0!==window.document}function $f(){return\"undefined\"!=typeof process&&\"[object process]\"==={}.toString.call(process)}function ir(n){switch(n.length){case 0:return new La;case 1:return n[0];default:return new Zw(n)}}function Jw(n,t,e,i,r={},s={}){const o=[],a=[];let l=-1,c=null;if(i.forEach(d=>{const u=d.offset,h=u==l,p=h&&c||{};Object.keys(d).forEach(m=>{let g=m,_=d[m];if(\"offset\"!==m)switch(g=t.normalizePropertyName(g,o),_){case\"!\":_=r[m];break;case Vi:_=s[m];break;default:_=t.normalizeStyleValue(m,g,_,o)}p[g]=_}),h||a.push(p),c=p,l=u}),o.length)throw function lH(n){return new H(3502,Ce)}();return a}function Gf(n,t,e,i){switch(t){case\"start\":n.onStart(()=>i(e&&Wf(e,\"start\",n)));break;case\"done\":n.onDone(()=>i(e&&Wf(e,\"done\",n)));break;case\"destroy\":n.onDestroy(()=>i(e&&Wf(e,\"destroy\",n)))}}function Wf(n,t,e){const i=e.totalTime,s=qf(n.element,n.triggerName,n.fromState,n.toState,t||n.phaseName,null==i?n.totalTime:i,!!e.disabled),o=n._data;return null!=o&&(s._data=o),s}function qf(n,t,e,i,r=\"\",s=0,o){return{element:n,triggerName:t,fromState:e,toState:i,phaseName:r,totalTime:s,disabled:!!o}}function dn(n,t,e){let i;return n instanceof Map?(i=n.get(t),i||n.set(t,i=e)):(i=n[t],i||(i=n[t]=e)),i}function eM(n){const t=n.indexOf(\":\");return[n.substring(1,t),n.substr(t+1)]}let Yf=(n,t)=>!1,tM=(n,t,e)=>[],nM=null;function Qf(n){const t=n.parentNode||n.host;return t===nM?null:t}($f()||\"undefined\"!=typeof Element)&&(yH()?(nM=(()=>document.documentElement)(),Yf=(n,t)=>{for(;t;){if(t===n)return!0;t=Qf(t)}return!1}):Yf=(n,t)=>n.contains(t),tM=(n,t,e)=>{if(e)return Array.from(n.querySelectorAll(t));const i=n.querySelector(t);return i?[i]:[]});let Hr=null,iM=!1;function rM(n){Hr||(Hr=function CH(){return\"undefined\"!=typeof document?document.body:null}()||{},iM=!!Hr.style&&\"WebkitAppearance\"in Hr.style);let t=!0;return Hr.style&&!function bH(n){return\"ebkit\"==n.substring(1,6)}(n)&&(t=n in Hr.style,!t&&iM&&(t=\"Webkit\"+n.charAt(0).toUpperCase()+n.substr(1)in Hr.style)),t}const sM=Yf,oM=tM;let aM=(()=>{class n{validateStyleProperty(e){return rM(e)}matchesElement(e,i){return!1}containsElement(e,i){return sM(e,i)}getParentElement(e){return Qf(e)}query(e,i,r){return oM(e,i,r)}computeStyle(e,i,r){return r||\"\"}animate(e,i,r,s,o,a=[],l){return new La(r,s)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),Kf=(()=>{class n{}return n.NOOP=new aM,n})();const Zf=\"ng-enter\",rd=\"ng-leave\",sd=\"ng-trigger\",od=\".ng-trigger\",cM=\"ng-animating\",Xf=\".ng-animating\";function jr(n){if(\"number\"==typeof n)return n;const t=n.match(/^(-?[\\.\\d]+)(m?s)/);return!t||t.length<2?0:Jf(parseFloat(t[1]),t[2])}function Jf(n,t){return\"s\"===t?1e3*n:n}function ad(n,t,e){return n.hasOwnProperty(\"duration\")?n:function MH(n,t,e){let r,s=0,o=\"\";if(\"string\"==typeof n){const a=n.match(/^(-?[\\.\\d]+)(m?s)(?:\\s+(-?[\\.\\d]+)(m?s))?(?:\\s+([-a-z]+(?:\\(.+?\\))?))?$/i);if(null===a)return t.push(Xw()),{duration:0,delay:0,easing:\"\"};r=Jf(parseFloat(a[1]),a[2]);const l=a[3];null!=l&&(s=Jf(parseFloat(l),a[4]));const c=a[5];c&&(o=c)}else r=n;if(!e){let a=!1,l=t.length;r<0&&(t.push(function H2(){return new H(3100,Ce)}()),a=!0),s<0&&(t.push(function j2(){return new H(3101,Ce)}()),a=!0),a&&t.splice(l,0,Xw())}return{duration:r,delay:s,easing:o}}(n,t,e)}function io(n,t={}){return Object.keys(n).forEach(e=>{t[e]=n[e]}),t}function rr(n,t,e={}){if(t)for(let i in n)e[i]=n[i];else io(n,e);return e}function uM(n,t,e){return e?t+\":\"+e+\";\":\"\"}function hM(n){let t=\"\";for(let e=0;e<n.style.length;e++){const i=n.style.item(e);t+=uM(0,i,n.style.getPropertyValue(i))}for(const e in n.style)n.style.hasOwnProperty(e)&&!e.startsWith(\"_\")&&(t+=uM(0,SH(e),n.style[e]));n.setAttribute(\"style\",t)}function vi(n,t,e){n.style&&(Object.keys(t).forEach(i=>{const r=tm(i);e&&!e.hasOwnProperty(i)&&(e[i]=n.style[r]),n.style[r]=t[i]}),$f()&&hM(n))}function zr(n,t){n.style&&(Object.keys(t).forEach(e=>{const i=tm(e);n.style[i]=\"\"}),$f()&&hM(n))}function Ba(n){return Array.isArray(n)?1==n.length?n[0]:Qw(n):n}const em=new RegExp(\"{{\\\\s*(.+?)\\\\s*}}\",\"g\");function pM(n){let t=[];if(\"string\"==typeof n){let e;for(;e=em.exec(n);)t.push(e[1]);em.lastIndex=0}return t}function ld(n,t,e){const i=n.toString(),r=i.replace(em,(s,o)=>{let a=t[o];return t.hasOwnProperty(o)||(e.push(function U2(n){return new H(3003,Ce)}()),a=\"\"),a.toString()});return r==i?n:r}function cd(n){const t=[];let e=n.next();for(;!e.done;)t.push(e.value),e=n.next();return t}const EH=/-+([a-z0-9])/g;function tm(n){return n.replace(EH,(...t)=>t[1].toUpperCase())}function SH(n){return n.replace(/([a-z])([A-Z])/g,\"$1-$2\").toLowerCase()}function un(n,t,e){switch(t.type){case 7:return n.visitTrigger(t,e);case 0:return n.visitState(t,e);case 1:return n.visitTransition(t,e);case 2:return n.visitSequence(t,e);case 3:return n.visitGroup(t,e);case 4:return n.visitAnimate(t,e);case 5:return n.visitKeyframes(t,e);case 6:return n.visitStyle(t,e);case 8:return n.visitReference(t,e);case 9:return n.visitAnimateChild(t,e);case 10:return n.visitAnimateRef(t,e);case 11:return n.visitQuery(t,e);case 12:return n.visitStagger(t,e);default:throw function $2(n){return new H(3004,Ce)}()}}function fM(n,t){return window.getComputedStyle(n)[t]}function OH(n,t){const e=[];return\"string\"==typeof n?n.split(/\\s*,\\s*/).forEach(i=>function PH(n,t,e){if(\":\"==n[0]){const l=function FH(n,t){switch(n){case\":enter\":return\"void => *\";case\":leave\":return\"* => void\";case\":increment\":return(e,i)=>parseFloat(i)>parseFloat(e);case\":decrement\":return(e,i)=>parseFloat(i)<parseFloat(e);default:return t.push(function rH(n){return new H(3016,Ce)}()),\"* => *\"}}(n,e);if(\"function\"==typeof l)return void t.push(l);n=l}const i=n.match(/^(\\*|[-\\w]+)\\s*(<?[=-]>)\\s*(\\*|[-\\w]+)$/);if(null==i||i.length<4)return e.push(function iH(n){return new H(3015,Ce)}()),t;const r=i[1],s=i[2],o=i[3];t.push(mM(r,o));\"<\"==s[0]&&!(\"*\"==r&&\"*\"==o)&&t.push(mM(o,r))}(i,e,t)):e.push(n),e}const pd=new Set([\"true\",\"1\"]),fd=new Set([\"false\",\"0\"]);function mM(n,t){const e=pd.has(n)||fd.has(n),i=pd.has(t)||fd.has(t);return(r,s)=>{let o=\"*\"==n||n==r,a=\"*\"==t||t==s;return!o&&e&&\"boolean\"==typeof r&&(o=r?pd.has(n):fd.has(n)),!a&&i&&\"boolean\"==typeof s&&(a=s?pd.has(t):fd.has(t)),o&&a}}const NH=new RegExp(\"s*:selfs*,?\",\"g\");function nm(n,t,e,i){return new LH(n).build(t,e,i)}class LH{constructor(t){this._driver=t}build(t,e,i){const r=new HH(e);this._resetContextStyleTimingState(r);const s=un(this,Ba(t),r);return r.unsupportedCSSPropertiesFound.size&&r.unsupportedCSSPropertiesFound.keys(),s}_resetContextStyleTimingState(t){t.currentQuerySelector=\"\",t.collectedStyles={},t.collectedStyles[\"\"]={},t.currentTime=0}visitTrigger(t,e){let i=e.queryCount=0,r=e.depCount=0;const s=[],o=[];return\"@\"==t.name.charAt(0)&&e.errors.push(function W2(){return new H(3006,Ce)}()),t.definitions.forEach(a=>{if(this._resetContextStyleTimingState(e),0==a.type){const l=a,c=l.name;c.toString().split(/\\s*,\\s*/).forEach(d=>{l.name=d,s.push(this.visitState(l,e))}),l.name=c}else if(1==a.type){const l=this.visitTransition(a,e);i+=l.queryCount,r+=l.depCount,o.push(l)}else e.errors.push(function q2(){return new H(3007,Ce)}())}),{type:7,name:t.name,states:s,transitions:o,queryCount:i,depCount:r,options:null}}visitState(t,e){const i=this.visitStyle(t.styles,e),r=t.options&&t.options.params||null;if(i.containsDynamicStyles){const s=new Set,o=r||{};i.styles.forEach(a=>{if(md(a)){const l=a;Object.keys(l).forEach(c=>{pM(l[c]).forEach(d=>{o.hasOwnProperty(d)||s.add(d)})})}}),s.size&&(cd(s.values()),e.errors.push(function Y2(n,t){return new H(3008,Ce)}()))}return{type:0,name:t.name,style:i,options:r?{params:r}:null}}visitTransition(t,e){e.queryCount=0,e.depCount=0;const i=un(this,Ba(t.animation),e);return{type:1,matchers:OH(t.expr,e.errors),animation:i,queryCount:e.queryCount,depCount:e.depCount,options:Ur(t.options)}}visitSequence(t,e){return{type:2,steps:t.steps.map(i=>un(this,i,e)),options:Ur(t.options)}}visitGroup(t,e){const i=e.currentTime;let r=0;const s=t.steps.map(o=>{e.currentTime=i;const a=un(this,o,e);return r=Math.max(r,e.currentTime),a});return e.currentTime=r,{type:3,steps:s,options:Ur(t.options)}}visitAnimate(t,e){const i=function zH(n,t){let e=null;if(n.hasOwnProperty(\"duration\"))e=n;else if(\"number\"==typeof n)return im(ad(n,t).duration,0,\"\");const i=n;if(i.split(/\\s+/).some(s=>\"{\"==s.charAt(0)&&\"{\"==s.charAt(1))){const s=im(0,0,\"\");return s.dynamic=!0,s.strValue=i,s}return e=e||ad(i,t),im(e.duration,e.delay,e.easing)}(t.timings,e.errors);e.currentAnimateTimings=i;let r,s=t.styles?t.styles:R({});if(5==s.type)r=this.visitKeyframes(s,e);else{let o=t.styles,a=!1;if(!o){a=!0;const c={};i.easing&&(c.easing=i.easing),o=R(c)}e.currentTime+=i.duration+i.delay;const l=this.visitStyle(o,e);l.isEmptyStep=a,r=l}return e.currentAnimateTimings=null,{type:4,timings:i,style:r,options:null}}visitStyle(t,e){const i=this._makeStyleAst(t,e);return this._validateStyleAst(i,e),i}_makeStyleAst(t,e){const i=[];Array.isArray(t.styles)?t.styles.forEach(o=>{\"string\"==typeof o?o==Vi?i.push(o):e.errors.push(function Q2(n){return new H(3002,Ce)}()):i.push(o)}):i.push(t.styles);let r=!1,s=null;return i.forEach(o=>{if(md(o)){const a=o,l=a.easing;if(l&&(s=l,delete a.easing),!r)for(let c in a)if(a[c].toString().indexOf(\"{{\")>=0){r=!0;break}}}),{type:6,styles:i,easing:s,offset:t.offset,containsDynamicStyles:r,options:null}}_validateStyleAst(t,e){const i=e.currentAnimateTimings;let r=e.currentTime,s=e.currentTime;i&&s>0&&(s-=i.duration+i.delay),t.styles.forEach(o=>{\"string\"!=typeof o&&Object.keys(o).forEach(a=>{if(!this._driver.validateStyleProperty(a))return delete o[a],void e.unsupportedCSSPropertiesFound.add(a);const l=e.collectedStyles[e.currentQuerySelector],c=l[a];let d=!0;c&&(s!=r&&s>=c.startTime&&r<=c.endTime&&(e.errors.push(function K2(n,t,e,i,r){return new H(3010,Ce)}()),d=!1),s=c.startTime),d&&(l[a]={startTime:s,endTime:r}),e.options&&function xH(n,t,e){const i=t.params||{},r=pM(n);r.length&&r.forEach(s=>{i.hasOwnProperty(s)||e.push(function z2(n){return new H(3001,Ce)}())})}(o[a],e.options,e.errors)})})}visitKeyframes(t,e){const i={type:5,styles:[],options:null};if(!e.currentAnimateTimings)return e.errors.push(function Z2(){return new H(3011,Ce)}()),i;let s=0;const o=[];let a=!1,l=!1,c=0;const d=t.steps.map(D=>{const v=this._makeStyleAst(D,e);let M=null!=v.offset?v.offset:function jH(n){if(\"string\"==typeof n)return null;let t=null;if(Array.isArray(n))n.forEach(e=>{if(md(e)&&e.hasOwnProperty(\"offset\")){const i=e;t=parseFloat(i.offset),delete i.offset}});else if(md(n)&&n.hasOwnProperty(\"offset\")){const e=n;t=parseFloat(e.offset),delete e.offset}return t}(v.styles),V=0;return null!=M&&(s++,V=v.offset=M),l=l||V<0||V>1,a=a||V<c,c=V,o.push(V),v});l&&e.errors.push(function X2(){return new H(3012,Ce)}()),a&&e.errors.push(function J2(){return new H(3200,Ce)}());const u=t.steps.length;let h=0;s>0&&s<u?e.errors.push(function eH(){return new H(3202,Ce)}()):0==s&&(h=1/(u-1));const p=u-1,m=e.currentTime,g=e.currentAnimateTimings,_=g.duration;return d.forEach((D,v)=>{const M=h>0?v==p?1:h*v:o[v],V=M*_;e.currentTime=m+g.delay+V,g.duration=V,this._validateStyleAst(D,e),D.offset=M,i.styles.push(D)}),i}visitReference(t,e){return{type:8,animation:un(this,Ba(t.animation),e),options:Ur(t.options)}}visitAnimateChild(t,e){return e.depCount++,{type:9,options:Ur(t.options)}}visitAnimateRef(t,e){return{type:10,animation:this.visitReference(t.animation,e),options:Ur(t.options)}}visitQuery(t,e){const i=e.currentQuerySelector,r=t.options||{};e.queryCount++,e.currentQuery=t;const[s,o]=function BH(n){const t=!!n.split(/\\s*,\\s*/).find(e=>\":self\"==e);return t&&(n=n.replace(NH,\"\")),n=n.replace(/@\\*/g,od).replace(/@\\w+/g,e=>od+\"-\"+e.substr(1)).replace(/:animating/g,Xf),[n,t]}(t.selector);e.currentQuerySelector=i.length?i+\" \"+s:s,dn(e.collectedStyles,e.currentQuerySelector,{});const a=un(this,Ba(t.animation),e);return e.currentQuery=null,e.currentQuerySelector=i,{type:11,selector:s,limit:r.limit||0,optional:!!r.optional,includeSelf:o,animation:a,originalSelector:t.selector,options:Ur(t.options)}}visitStagger(t,e){e.currentQuery||e.errors.push(function tH(){return new H(3013,Ce)}());const i=\"full\"===t.timings?{duration:0,delay:0,easing:\"full\"}:ad(t.timings,e.errors,!0);return{type:12,animation:un(this,Ba(t.animation),e),timings:i,options:null}}}class HH{constructor(t){this.errors=t,this.queryCount=0,this.depCount=0,this.currentTransition=null,this.currentQuery=null,this.currentQuerySelector=null,this.currentAnimateTimings=null,this.currentTime=0,this.collectedStyles={},this.options=null,this.unsupportedCSSPropertiesFound=new Set}}function md(n){return!Array.isArray(n)&&\"object\"==typeof n}function Ur(n){return n?(n=io(n)).params&&(n.params=function VH(n){return n?io(n):null}(n.params)):n={},n}function im(n,t,e){return{duration:n,delay:t,easing:e}}function rm(n,t,e,i,r,s,o=null,a=!1){return{type:1,element:n,keyframes:t,preStyleProps:e,postStyleProps:i,duration:r,delay:s,totalTime:r+s,easing:o,subTimeline:a}}class gd{constructor(){this._map=new Map}get(t){return this._map.get(t)||[]}append(t,e){let i=this._map.get(t);i||this._map.set(t,i=[]),i.push(...e)}has(t){return this._map.has(t)}clear(){this._map.clear()}}const GH=new RegExp(\":enter\",\"g\"),qH=new RegExp(\":leave\",\"g\");function sm(n,t,e,i,r,s={},o={},a,l,c=[]){return(new YH).buildKeyframes(n,t,e,i,r,s,o,a,l,c)}class YH{buildKeyframes(t,e,i,r,s,o,a,l,c,d=[]){c=c||new gd;const u=new om(t,e,c,r,s,d,[]);u.options=l,u.currentTimeline.setStyles([o],null,u.errors,l),un(this,i,u);const h=u.timelines.filter(p=>p.containsAnimation());if(Object.keys(a).length){let p;for(let m=h.length-1;m>=0;m--){const g=h[m];if(g.element===e){p=g;break}}p&&!p.allowOnlyTimelineStyles()&&p.setStyles([a],null,u.errors,l)}return h.length?h.map(p=>p.buildKeyframes()):[rm(e,[],[],[],0,0,\"\",!1)]}visitTrigger(t,e){}visitState(t,e){}visitTransition(t,e){}visitAnimateChild(t,e){const i=e.subInstructions.get(e.element);if(i){const r=e.createSubContext(t.options),s=e.currentTimeline.currentTime,o=this._visitSubInstructions(i,r,r.options);s!=o&&e.transformIntoNewTimeline(o)}e.previousNode=t}visitAnimateRef(t,e){const i=e.createSubContext(t.options);i.transformIntoNewTimeline(),this.visitReference(t.animation,i),e.transformIntoNewTimeline(i.currentTimeline.currentTime),e.previousNode=t}_visitSubInstructions(t,e,i){let s=e.currentTimeline.currentTime;const o=null!=i.duration?jr(i.duration):null,a=null!=i.delay?jr(i.delay):null;return 0!==o&&t.forEach(l=>{const c=e.appendInstructionToTimeline(l,o,a);s=Math.max(s,c.duration+c.delay)}),s}visitReference(t,e){e.updateOptions(t.options,!0),un(this,t.animation,e),e.previousNode=t}visitSequence(t,e){const i=e.subContextCount;let r=e;const s=t.options;if(s&&(s.params||s.delay)&&(r=e.createSubContext(s),r.transformIntoNewTimeline(),null!=s.delay)){6==r.previousNode.type&&(r.currentTimeline.snapshotCurrentStyles(),r.previousNode=_d);const o=jr(s.delay);r.delayNextStep(o)}t.steps.length&&(t.steps.forEach(o=>un(this,o,r)),r.currentTimeline.applyStylesToKeyframe(),r.subContextCount>i&&r.transformIntoNewTimeline()),e.previousNode=t}visitGroup(t,e){const i=[];let r=e.currentTimeline.currentTime;const s=t.options&&t.options.delay?jr(t.options.delay):0;t.steps.forEach(o=>{const a=e.createSubContext(t.options);s&&a.delayNextStep(s),un(this,o,a),r=Math.max(r,a.currentTimeline.currentTime),i.push(a.currentTimeline)}),i.forEach(o=>e.currentTimeline.mergeTimelineCollectedStyles(o)),e.transformIntoNewTimeline(r),e.previousNode=t}_visitTiming(t,e){if(t.dynamic){const i=t.strValue;return ad(e.params?ld(i,e.params,e.errors):i,e.errors)}return{duration:t.duration,delay:t.delay,easing:t.easing}}visitAnimate(t,e){const i=e.currentAnimateTimings=this._visitTiming(t.timings,e),r=e.currentTimeline;i.delay&&(e.incrementTime(i.delay),r.snapshotCurrentStyles());const s=t.style;5==s.type?this.visitKeyframes(s,e):(e.incrementTime(i.duration),this.visitStyle(s,e),r.applyStylesToKeyframe()),e.currentAnimateTimings=null,e.previousNode=t}visitStyle(t,e){const i=e.currentTimeline,r=e.currentAnimateTimings;!r&&i.getCurrentStyleProperties().length&&i.forwardFrame();const s=r&&r.easing||t.easing;t.isEmptyStep?i.applyEmptyStep(s):i.setStyles(t.styles,s,e.errors,e.options),e.previousNode=t}visitKeyframes(t,e){const i=e.currentAnimateTimings,r=e.currentTimeline.duration,s=i.duration,a=e.createSubContext().currentTimeline;a.easing=i.easing,t.styles.forEach(l=>{a.forwardTime((l.offset||0)*s),a.setStyles(l.styles,l.easing,e.errors,e.options),a.applyStylesToKeyframe()}),e.currentTimeline.mergeTimelineCollectedStyles(a),e.transformIntoNewTimeline(r+s),e.previousNode=t}visitQuery(t,e){const i=e.currentTimeline.currentTime,r=t.options||{},s=r.delay?jr(r.delay):0;s&&(6===e.previousNode.type||0==i&&e.currentTimeline.getCurrentStyleProperties().length)&&(e.currentTimeline.snapshotCurrentStyles(),e.previousNode=_d);let o=i;const a=e.invokeQuery(t.selector,t.originalSelector,t.limit,t.includeSelf,!!r.optional,e.errors);e.currentQueryTotal=a.length;let l=null;a.forEach((c,d)=>{e.currentQueryIndex=d;const u=e.createSubContext(t.options,c);s&&u.delayNextStep(s),c===e.element&&(l=u.currentTimeline),un(this,t.animation,u),u.currentTimeline.applyStylesToKeyframe(),o=Math.max(o,u.currentTimeline.currentTime)}),e.currentQueryIndex=0,e.currentQueryTotal=0,e.transformIntoNewTimeline(o),l&&(e.currentTimeline.mergeTimelineCollectedStyles(l),e.currentTimeline.snapshotCurrentStyles()),e.previousNode=t}visitStagger(t,e){const i=e.parentContext,r=e.currentTimeline,s=t.timings,o=Math.abs(s.duration),a=o*(e.currentQueryTotal-1);let l=o*e.currentQueryIndex;switch(s.duration<0?\"reverse\":s.easing){case\"reverse\":l=a-l;break;case\"full\":l=i.currentStaggerTime}const d=e.currentTimeline;l&&d.delayNextStep(l);const u=d.currentTime;un(this,t.animation,e),e.previousNode=t,i.currentStaggerTime=r.currentTime-u+(r.startTime-i.currentTimeline.startTime)}}const _d={};class om{constructor(t,e,i,r,s,o,a,l){this._driver=t,this.element=e,this.subInstructions=i,this._enterClassName=r,this._leaveClassName=s,this.errors=o,this.timelines=a,this.parentContext=null,this.currentAnimateTimings=null,this.previousNode=_d,this.subContextCount=0,this.options={},this.currentQueryIndex=0,this.currentQueryTotal=0,this.currentStaggerTime=0,this.currentTimeline=l||new vd(this._driver,e,0),a.push(this.currentTimeline)}get params(){return this.options.params}updateOptions(t,e){if(!t)return;const i=t;let r=this.options;null!=i.duration&&(r.duration=jr(i.duration)),null!=i.delay&&(r.delay=jr(i.delay));const s=i.params;if(s){let o=r.params;o||(o=this.options.params={}),Object.keys(s).forEach(a=>{(!e||!o.hasOwnProperty(a))&&(o[a]=ld(s[a],o,this.errors))})}}_copyOptions(){const t={};if(this.options){const e=this.options.params;if(e){const i=t.params={};Object.keys(e).forEach(r=>{i[r]=e[r]})}}return t}createSubContext(t=null,e,i){const r=e||this.element,s=new om(this._driver,r,this.subInstructions,this._enterClassName,this._leaveClassName,this.errors,this.timelines,this.currentTimeline.fork(r,i||0));return s.previousNode=this.previousNode,s.currentAnimateTimings=this.currentAnimateTimings,s.options=this._copyOptions(),s.updateOptions(t),s.currentQueryIndex=this.currentQueryIndex,s.currentQueryTotal=this.currentQueryTotal,s.parentContext=this,this.subContextCount++,s}transformIntoNewTimeline(t){return this.previousNode=_d,this.currentTimeline=this.currentTimeline.fork(this.element,t),this.timelines.push(this.currentTimeline),this.currentTimeline}appendInstructionToTimeline(t,e,i){const r={duration:null!=e?e:t.duration,delay:this.currentTimeline.currentTime+(null!=i?i:0)+t.delay,easing:\"\"},s=new QH(this._driver,t.element,t.keyframes,t.preStyleProps,t.postStyleProps,r,t.stretchStartingKeyframe);return this.timelines.push(s),r}incrementTime(t){this.currentTimeline.forwardTime(this.currentTimeline.duration+t)}delayNextStep(t){t>0&&this.currentTimeline.delayNextStep(t)}invokeQuery(t,e,i,r,s,o){let a=[];if(r&&a.push(this.element),t.length>0){t=(t=t.replace(GH,\".\"+this._enterClassName)).replace(qH,\".\"+this._leaveClassName);let c=this._driver.query(this.element,t,1!=i);0!==i&&(c=i<0?c.slice(c.length+i,c.length):c.slice(0,i)),a.push(...c)}return!s&&0==a.length&&o.push(function nH(n){return new H(3014,Ce)}()),a}}class vd{constructor(t,e,i,r){this._driver=t,this.element=e,this.startTime=i,this._elementTimelineStylesLookup=r,this.duration=0,this._previousKeyframe={},this._currentKeyframe={},this._keyframes=new Map,this._styleSummary={},this._pendingStyles={},this._backFill={},this._currentEmptyStepKeyframe=null,this._elementTimelineStylesLookup||(this._elementTimelineStylesLookup=new Map),this._localTimelineStyles=Object.create(this._backFill,{}),this._globalTimelineStyles=this._elementTimelineStylesLookup.get(e),this._globalTimelineStyles||(this._globalTimelineStyles=this._localTimelineStyles,this._elementTimelineStylesLookup.set(e,this._localTimelineStyles)),this._loadKeyframe()}containsAnimation(){switch(this._keyframes.size){case 0:return!1;case 1:return this.getCurrentStyleProperties().length>0;default:return!0}}getCurrentStyleProperties(){return Object.keys(this._currentKeyframe)}get currentTime(){return this.startTime+this.duration}delayNextStep(t){const e=1==this._keyframes.size&&Object.keys(this._pendingStyles).length;this.duration||e?(this.forwardTime(this.currentTime+t),e&&this.snapshotCurrentStyles()):this.startTime+=t}fork(t,e){return this.applyStylesToKeyframe(),new vd(this._driver,t,e||this.currentTime,this._elementTimelineStylesLookup)}_loadKeyframe(){this._currentKeyframe&&(this._previousKeyframe=this._currentKeyframe),this._currentKeyframe=this._keyframes.get(this.duration),this._currentKeyframe||(this._currentKeyframe=Object.create(this._backFill,{}),this._keyframes.set(this.duration,this._currentKeyframe))}forwardFrame(){this.duration+=1,this._loadKeyframe()}forwardTime(t){this.applyStylesToKeyframe(),this.duration=t,this._loadKeyframe()}_updateStyle(t,e){this._localTimelineStyles[t]=e,this._globalTimelineStyles[t]=e,this._styleSummary[t]={time:this.currentTime,value:e}}allowOnlyTimelineStyles(){return this._currentEmptyStepKeyframe!==this._currentKeyframe}applyEmptyStep(t){t&&(this._previousKeyframe.easing=t),Object.keys(this._globalTimelineStyles).forEach(e=>{this._backFill[e]=this._globalTimelineStyles[e]||Vi,this._currentKeyframe[e]=Vi}),this._currentEmptyStepKeyframe=this._currentKeyframe}setStyles(t,e,i,r){e&&(this._previousKeyframe.easing=e);const s=r&&r.params||{},o=function KH(n,t){const e={};let i;return n.forEach(r=>{\"*\"===r?(i=i||Object.keys(t),i.forEach(s=>{e[s]=Vi})):rr(r,!1,e)}),e}(t,this._globalTimelineStyles);Object.keys(o).forEach(a=>{const l=ld(o[a],s,i);this._pendingStyles[a]=l,this._localTimelineStyles.hasOwnProperty(a)||(this._backFill[a]=this._globalTimelineStyles.hasOwnProperty(a)?this._globalTimelineStyles[a]:Vi),this._updateStyle(a,l)})}applyStylesToKeyframe(){const t=this._pendingStyles,e=Object.keys(t);0!=e.length&&(this._pendingStyles={},e.forEach(i=>{this._currentKeyframe[i]=t[i]}),Object.keys(this._localTimelineStyles).forEach(i=>{this._currentKeyframe.hasOwnProperty(i)||(this._currentKeyframe[i]=this._localTimelineStyles[i])}))}snapshotCurrentStyles(){Object.keys(this._localTimelineStyles).forEach(t=>{const e=this._localTimelineStyles[t];this._pendingStyles[t]=e,this._updateStyle(t,e)})}getFinalKeyframe(){return this._keyframes.get(this.duration)}get properties(){const t=[];for(let e in this._currentKeyframe)t.push(e);return t}mergeTimelineCollectedStyles(t){Object.keys(t._styleSummary).forEach(e=>{const i=this._styleSummary[e],r=t._styleSummary[e];(!i||r.time>i.time)&&this._updateStyle(e,r.value)})}buildKeyframes(){this.applyStylesToKeyframe();const t=new Set,e=new Set,i=1===this._keyframes.size&&0===this.duration;let r=[];this._keyframes.forEach((a,l)=>{const c=rr(a,!0);Object.keys(c).forEach(d=>{const u=c[d];\"!\"==u?t.add(d):u==Vi&&e.add(d)}),i||(c.offset=l/this.duration),r.push(c)});const s=t.size?cd(t.values()):[],o=e.size?cd(e.values()):[];if(i){const a=r[0],l=io(a);a.offset=0,l.offset=1,r=[a,l]}return rm(this.element,r,s,o,this.duration,this.startTime,this.easing,!1)}}class QH extends vd{constructor(t,e,i,r,s,o,a=!1){super(t,e,o.delay),this.keyframes=i,this.preStyleProps=r,this.postStyleProps=s,this._stretchStartingKeyframe=a,this.timings={duration:o.duration,delay:o.delay,easing:o.easing}}containsAnimation(){return this.keyframes.length>1}buildKeyframes(){let t=this.keyframes,{delay:e,duration:i,easing:r}=this.timings;if(this._stretchStartingKeyframe&&e){const s=[],o=i+e,a=e/o,l=rr(t[0],!1);l.offset=0,s.push(l);const c=rr(t[0],!1);c.offset=vM(a),s.push(c);const d=t.length-1;for(let u=1;u<=d;u++){let h=rr(t[u],!1);h.offset=vM((e+h.offset*i)/o),s.push(h)}i=o,e=0,r=\"\",t=s}return rm(this.element,t,this.preStyleProps,this.postStyleProps,i,e,r,!0)}}function vM(n,t=3){const e=Math.pow(10,t-1);return Math.round(n*e)/e}class am{}class ZH extends am{normalizePropertyName(t,e){return tm(t)}normalizeStyleValue(t,e,i,r){let s=\"\";const o=i.toString().trim();if(XH[e]&&0!==i&&\"0\"!==i)if(\"number\"==typeof i)s=\"px\";else{const a=i.match(/^[+-]?[\\d\\.]+([a-z]*)$/);a&&0==a[1].length&&r.push(function G2(n,t){return new H(3005,Ce)}())}return o+s}}const XH=(()=>function JH(n){const t={};return n.forEach(e=>t[e]=!0),t}(\"width,height,minWidth,minHeight,maxWidth,maxHeight,left,top,bottom,right,fontSize,outlineWidth,outlineOffset,paddingTop,paddingLeft,paddingBottom,paddingRight,marginTop,marginLeft,marginBottom,marginRight,borderRadius,borderWidth,borderTopWidth,borderLeftWidth,borderRightWidth,borderBottomWidth,textIndent,perspective\".split(\",\")))();function yM(n,t,e,i,r,s,o,a,l,c,d,u,h){return{type:0,element:n,triggerName:t,isRemovalTransition:r,fromState:e,fromStyles:s,toState:i,toStyles:o,timelines:a,queriedElements:l,preStyleProps:c,postStyleProps:d,totalTime:u,errors:h}}const lm={};class bM{constructor(t,e,i){this._triggerName=t,this.ast=e,this._stateStyles=i}match(t,e,i,r){return function ej(n,t,e,i,r){return n.some(s=>s(t,e,i,r))}(this.ast.matchers,t,e,i,r)}buildStyles(t,e,i){const r=this._stateStyles[\"*\"],s=this._stateStyles[t],o=r?r.buildStyles(e,i):{};return s?s.buildStyles(e,i):o}build(t,e,i,r,s,o,a,l,c,d){const u=[],h=this.ast.options&&this.ast.options.params||lm,m=this.buildStyles(i,a&&a.params||lm,u),g=l&&l.params||lm,_=this.buildStyles(r,g,u),D=new Set,v=new Map,M=new Map,V=\"void\"===r,he={params:Object.assign(Object.assign({},h),g)},We=d?[]:sm(t,e,this.ast.animation,s,o,m,_,he,c,u);let Ze=0;if(We.forEach(pn=>{Ze=Math.max(pn.duration+pn.delay,Ze)}),u.length)return yM(e,this._triggerName,i,r,V,m,_,[],[],v,M,Ze,u);We.forEach(pn=>{const fn=pn.element,Do=dn(v,fn,{});pn.preStyleProps.forEach(ii=>Do[ii]=!0);const Gi=dn(M,fn,{});pn.postStyleProps.forEach(ii=>Gi[ii]=!0),fn!==e&&D.add(fn)});const hn=cd(D.values());return yM(e,this._triggerName,i,r,V,m,_,We,hn,v,M,Ze)}}class tj{constructor(t,e,i){this.styles=t,this.defaultParams=e,this.normalizer=i}buildStyles(t,e){const i={},r=io(this.defaultParams);return Object.keys(t).forEach(s=>{const o=t[s];null!=o&&(r[s]=o)}),this.styles.styles.forEach(s=>{if(\"string\"!=typeof s){const o=s;Object.keys(o).forEach(a=>{let l=o[a];l.length>1&&(l=ld(l,r,e));const c=this.normalizer.normalizePropertyName(a,e);l=this.normalizer.normalizeStyleValue(a,c,l,e),i[c]=l})}}),i}}class ij{constructor(t,e,i){this.name=t,this.ast=e,this._normalizer=i,this.transitionFactories=[],this.states={},e.states.forEach(r=>{this.states[r.name]=new tj(r.style,r.options&&r.options.params||{},i)}),CM(this.states,\"true\",\"1\"),CM(this.states,\"false\",\"0\"),e.transitions.forEach(r=>{this.transitionFactories.push(new bM(t,r,this.states))}),this.fallbackTransition=function rj(n,t,e){return new bM(n,{type:1,animation:{type:2,steps:[],options:null},matchers:[(o,a)=>!0],options:null,queryCount:0,depCount:0},t)}(t,this.states)}get containsQueries(){return this.ast.queryCount>0}matchTransition(t,e,i,r){return this.transitionFactories.find(o=>o.match(t,e,i,r))||null}matchStyles(t,e,i){return this.fallbackTransition.buildStyles(t,e,i)}}function CM(n,t,e){n.hasOwnProperty(t)?n.hasOwnProperty(e)||(n[e]=n[t]):n.hasOwnProperty(e)&&(n[t]=n[e])}const sj=new gd;class oj{constructor(t,e,i){this.bodyNode=t,this._driver=e,this._normalizer=i,this._animations={},this._playersById={},this.players=[]}register(t,e){const i=[],s=nm(this._driver,e,i,[]);if(i.length)throw function cH(n){return new H(3503,Ce)}();this._animations[t]=s}_buildPlayer(t,e,i){const r=t.element,s=Jw(0,this._normalizer,0,t.keyframes,e,i);return this._driver.animate(r,s,t.duration,t.delay,t.easing,[],!0)}create(t,e,i={}){const r=[],s=this._animations[t];let o;const a=new Map;if(s?(o=sm(this._driver,e,s,Zf,rd,{},{},i,sj,r),o.forEach(d=>{const u=dn(a,d.element,{});d.postStyleProps.forEach(h=>u[h]=null)})):(r.push(function dH(){return new H(3300,Ce)}()),o=[]),r.length)throw function uH(n){return new H(3504,Ce)}();a.forEach((d,u)=>{Object.keys(d).forEach(h=>{d[h]=this._driver.computeStyle(u,h,Vi)})});const c=ir(o.map(d=>{const u=a.get(d.element);return this._buildPlayer(d,{},u)}));return this._playersById[t]=c,c.onDestroy(()=>this.destroy(t)),this.players.push(c),c}destroy(t){const e=this._getPlayer(t);e.destroy(),delete this._playersById[t];const i=this.players.indexOf(e);i>=0&&this.players.splice(i,1)}_getPlayer(t){const e=this._playersById[t];if(!e)throw function hH(n){return new H(3301,Ce)}();return e}listen(t,e,i,r){const s=qf(e,\"\",\"\",\"\");return Gf(this._getPlayer(t),i,s,r),()=>{}}command(t,e,i,r){if(\"register\"==i)return void this.register(t,r[0]);if(\"create\"==i)return void this.create(t,e,r[0]||{});const s=this._getPlayer(t);switch(i){case\"play\":s.play();break;case\"pause\":s.pause();break;case\"reset\":s.reset();break;case\"restart\":s.restart();break;case\"finish\":s.finish();break;case\"init\":s.init();break;case\"setPosition\":s.setPosition(parseFloat(r[0]));break;case\"destroy\":this.destroy(t)}}}const DM=\"ng-animate-queued\",cm=\"ng-animate-disabled\",uj=[],wM={namespaceId:\"\",setForRemoval:!1,setForMove:!1,hasAnimation:!1,removedBeforeQueried:!1},hj={namespaceId:\"\",setForMove:!1,setForRemoval:!1,hasAnimation:!1,removedBeforeQueried:!0},An=\"__ng_removed\";class dm{constructor(t,e=\"\"){this.namespaceId=e;const i=t&&t.hasOwnProperty(\"value\");if(this.value=function gj(n){return null!=n?n:null}(i?t.value:t),i){const s=io(t);delete s.value,this.options=s}else this.options={};this.options.params||(this.options.params={})}get params(){return this.options.params}absorbOptions(t){const e=t.params;if(e){const i=this.options.params;Object.keys(e).forEach(r=>{null==i[r]&&(i[r]=e[r])})}}}const Va=\"void\",um=new dm(Va);class pj{constructor(t,e,i){this.id=t,this.hostElement=e,this._engine=i,this.players=[],this._triggers={},this._queue=[],this._elementListeners=new Map,this._hostClassName=\"ng-tns-\"+t,In(e,this._hostClassName)}listen(t,e,i,r){if(!this._triggers.hasOwnProperty(e))throw function pH(n,t){return new H(3302,Ce)}();if(null==i||0==i.length)throw function fH(n){return new H(3303,Ce)}();if(!function _j(n){return\"start\"==n||\"done\"==n}(i))throw function mH(n,t){return new H(3400,Ce)}();const s=dn(this._elementListeners,t,[]),o={name:e,phase:i,callback:r};s.push(o);const a=dn(this._engine.statesByElement,t,{});return a.hasOwnProperty(e)||(In(t,sd),In(t,sd+\"-\"+e),a[e]=um),()=>{this._engine.afterFlush(()=>{const l=s.indexOf(o);l>=0&&s.splice(l,1),this._triggers[e]||delete a[e]})}}register(t,e){return!this._triggers[t]&&(this._triggers[t]=e,!0)}_getTrigger(t){const e=this._triggers[t];if(!e)throw function gH(n){return new H(3401,Ce)}();return e}trigger(t,e,i,r=!0){const s=this._getTrigger(e),o=new hm(this.id,e,t);let a=this._engine.statesByElement.get(t);a||(In(t,sd),In(t,sd+\"-\"+e),this._engine.statesByElement.set(t,a={}));let l=a[e];const c=new dm(i,this.id);if(!(i&&i.hasOwnProperty(\"value\"))&&l&&c.absorbOptions(l.options),a[e]=c,l||(l=um),c.value!==Va&&l.value===c.value){if(!function bj(n,t){const e=Object.keys(n),i=Object.keys(t);if(e.length!=i.length)return!1;for(let r=0;r<e.length;r++){const s=e[r];if(!t.hasOwnProperty(s)||n[s]!==t[s])return!1}return!0}(l.params,c.params)){const g=[],_=s.matchStyles(l.value,l.params,g),D=s.matchStyles(c.value,c.params,g);g.length?this._engine.reportError(g):this._engine.afterFlush(()=>{zr(t,_),vi(t,D)})}return}const h=dn(this._engine.playersByElement,t,[]);h.forEach(g=>{g.namespaceId==this.id&&g.triggerName==e&&g.queued&&g.destroy()});let p=s.matchTransition(l.value,c.value,t,c.params),m=!1;if(!p){if(!r)return;p=s.fallbackTransition,m=!0}return this._engine.totalQueuedPlayers++,this._queue.push({element:t,triggerName:e,transition:p,fromState:l,toState:c,player:o,isFallbackTransition:m}),m||(In(t,DM),o.onStart(()=>{ro(t,DM)})),o.onDone(()=>{let g=this.players.indexOf(o);g>=0&&this.players.splice(g,1);const _=this._engine.playersByElement.get(t);if(_){let D=_.indexOf(o);D>=0&&_.splice(D,1)}}),this.players.push(o),h.push(o),o}deregister(t){delete this._triggers[t],this._engine.statesByElement.forEach((e,i)=>{delete e[t]}),this._elementListeners.forEach((e,i)=>{this._elementListeners.set(i,e.filter(r=>r.name!=t))})}clearElementCache(t){this._engine.statesByElement.delete(t),this._elementListeners.delete(t);const e=this._engine.playersByElement.get(t);e&&(e.forEach(i=>i.destroy()),this._engine.playersByElement.delete(t))}_signalRemovalForInnerTriggers(t,e){const i=this._engine.driver.query(t,od,!0);i.forEach(r=>{if(r[An])return;const s=this._engine.fetchNamespacesByElement(r);s.size?s.forEach(o=>o.triggerLeaveAnimation(r,e,!1,!0)):this.clearElementCache(r)}),this._engine.afterFlushAnimationsDone(()=>i.forEach(r=>this.clearElementCache(r)))}triggerLeaveAnimation(t,e,i,r){const s=this._engine.statesByElement.get(t),o=new Map;if(s){const a=[];if(Object.keys(s).forEach(l=>{if(o.set(l,s[l].value),this._triggers[l]){const c=this.trigger(t,l,Va,r);c&&a.push(c)}}),a.length)return this._engine.markElementAsRemoved(this.id,t,!0,e,o),i&&ir(a).onDone(()=>this._engine.processLeaveNode(t)),!0}return!1}prepareLeaveAnimationListeners(t){const e=this._elementListeners.get(t),i=this._engine.statesByElement.get(t);if(e&&i){const r=new Set;e.forEach(s=>{const o=s.name;if(r.has(o))return;r.add(o);const l=this._triggers[o].fallbackTransition,c=i[o]||um,d=new dm(Va),u=new hm(this.id,o,t);this._engine.totalQueuedPlayers++,this._queue.push({element:t,triggerName:o,transition:l,fromState:c,toState:d,player:u,isFallbackTransition:!0})})}}removeNode(t,e){const i=this._engine;if(t.childElementCount&&this._signalRemovalForInnerTriggers(t,e),this.triggerLeaveAnimation(t,e,!0))return;let r=!1;if(i.totalAnimations){const s=i.players.length?i.playersByQueriedElement.get(t):[];if(s&&s.length)r=!0;else{let o=t;for(;o=o.parentNode;)if(i.statesByElement.get(o)){r=!0;break}}}if(this.prepareLeaveAnimationListeners(t),r)i.markElementAsRemoved(this.id,t,!1,e);else{const s=t[An];(!s||s===wM)&&(i.afterFlush(()=>this.clearElementCache(t)),i.destroyInnerAnimations(t),i._onRemovalComplete(t,e))}}insertNode(t,e){In(t,this._hostClassName)}drainQueuedTransitions(t){const e=[];return this._queue.forEach(i=>{const r=i.player;if(r.destroyed)return;const s=i.element,o=this._elementListeners.get(s);o&&o.forEach(a=>{if(a.name==i.triggerName){const l=qf(s,i.triggerName,i.fromState.value,i.toState.value);l._data=t,Gf(i.player,a.phase,l,a.callback)}}),r.markedForDestroy?this._engine.afterFlush(()=>{r.destroy()}):e.push(i)}),this._queue=[],e.sort((i,r)=>{const s=i.transition.ast.depCount,o=r.transition.ast.depCount;return 0==s||0==o?s-o:this._engine.driver.containsElement(i.element,r.element)?1:-1})}destroy(t){this.players.forEach(e=>e.destroy()),this._signalRemovalForInnerTriggers(this.hostElement,t)}elementContainsData(t){let e=!1;return this._elementListeners.has(t)&&(e=!0),e=!!this._queue.find(i=>i.element===t)||e,e}}class fj{constructor(t,e,i){this.bodyNode=t,this.driver=e,this._normalizer=i,this.players=[],this.newHostElements=new Map,this.playersByElement=new Map,this.playersByQueriedElement=new Map,this.statesByElement=new Map,this.disabledNodes=new Set,this.totalAnimations=0,this.totalQueuedPlayers=0,this._namespaceLookup={},this._namespaceList=[],this._flushFns=[],this._whenQuietFns=[],this.namespacesByHostElement=new Map,this.collectedEnterElements=[],this.collectedLeaveElements=[],this.onRemovalComplete=(r,s)=>{}}_onRemovalComplete(t,e){this.onRemovalComplete(t,e)}get queuedPlayers(){const t=[];return this._namespaceList.forEach(e=>{e.players.forEach(i=>{i.queued&&t.push(i)})}),t}createNamespace(t,e){const i=new pj(t,e,this);return this.bodyNode&&this.driver.containsElement(this.bodyNode,e)?this._balanceNamespaceList(i,e):(this.newHostElements.set(e,i),this.collectEnterElement(e)),this._namespaceLookup[t]=i}_balanceNamespaceList(t,e){const i=this._namespaceList,r=this.namespacesByHostElement,s=i.length-1;if(s>=0){let o=!1;if(void 0!==this.driver.getParentElement){let a=this.driver.getParentElement(e);for(;a;){const l=r.get(a);if(l){const c=i.indexOf(l);i.splice(c+1,0,t),o=!0;break}a=this.driver.getParentElement(a)}}else for(let a=s;a>=0;a--)if(this.driver.containsElement(i[a].hostElement,e)){i.splice(a+1,0,t),o=!0;break}o||i.unshift(t)}else i.push(t);return r.set(e,t),t}register(t,e){let i=this._namespaceLookup[t];return i||(i=this.createNamespace(t,e)),i}registerTrigger(t,e,i){let r=this._namespaceLookup[t];r&&r.register(e,i)&&this.totalAnimations++}destroy(t,e){if(!t)return;const i=this._fetchNamespace(t);this.afterFlush(()=>{this.namespacesByHostElement.delete(i.hostElement),delete this._namespaceLookup[t];const r=this._namespaceList.indexOf(i);r>=0&&this._namespaceList.splice(r,1)}),this.afterFlushAnimationsDone(()=>i.destroy(e))}_fetchNamespace(t){return this._namespaceLookup[t]}fetchNamespacesByElement(t){const e=new Set,i=this.statesByElement.get(t);if(i){const r=Object.keys(i);for(let s=0;s<r.length;s++){const o=i[r[s]].namespaceId;if(o){const a=this._fetchNamespace(o);a&&e.add(a)}}}return e}trigger(t,e,i,r){if(yd(e)){const s=this._fetchNamespace(t);if(s)return s.trigger(e,i,r),!0}return!1}insertNode(t,e,i,r){if(!yd(e))return;const s=e[An];if(s&&s.setForRemoval){s.setForRemoval=!1,s.setForMove=!0;const o=this.collectedLeaveElements.indexOf(e);o>=0&&this.collectedLeaveElements.splice(o,1)}if(t){const o=this._fetchNamespace(t);o&&o.insertNode(e,i)}r&&this.collectEnterElement(e)}collectEnterElement(t){this.collectedEnterElements.push(t)}markElementAsDisabled(t,e){e?this.disabledNodes.has(t)||(this.disabledNodes.add(t),In(t,cm)):this.disabledNodes.has(t)&&(this.disabledNodes.delete(t),ro(t,cm))}removeNode(t,e,i,r){if(yd(e)){const s=t?this._fetchNamespace(t):null;if(s?s.removeNode(e,r):this.markElementAsRemoved(t,e,!1,r),i){const o=this.namespacesByHostElement.get(e);o&&o.id!==t&&o.removeNode(e,r)}}else this._onRemovalComplete(e,r)}markElementAsRemoved(t,e,i,r,s){this.collectedLeaveElements.push(e),e[An]={namespaceId:t,setForRemoval:r,hasAnimation:i,removedBeforeQueried:!1,previousTriggersValues:s}}listen(t,e,i,r,s){return yd(e)?this._fetchNamespace(t).listen(e,i,r,s):()=>{}}_buildInstruction(t,e,i,r,s){return t.transition.build(this.driver,t.element,t.fromState.value,t.toState.value,i,r,t.fromState.options,t.toState.options,e,s)}destroyInnerAnimations(t){let e=this.driver.query(t,od,!0);e.forEach(i=>this.destroyActiveAnimationsForElement(i)),0!=this.playersByQueriedElement.size&&(e=this.driver.query(t,Xf,!0),e.forEach(i=>this.finishActiveQueriedAnimationOnElement(i)))}destroyActiveAnimationsForElement(t){const e=this.playersByElement.get(t);e&&e.forEach(i=>{i.queued?i.markedForDestroy=!0:i.destroy()})}finishActiveQueriedAnimationOnElement(t){const e=this.playersByQueriedElement.get(t);e&&e.forEach(i=>i.finish())}whenRenderingDone(){return new Promise(t=>{if(this.players.length)return ir(this.players).onDone(()=>t());t()})}processLeaveNode(t){var e;const i=t[An];if(i&&i.setForRemoval){if(t[An]=wM,i.namespaceId){this.destroyInnerAnimations(t);const r=this._fetchNamespace(i.namespaceId);r&&r.clearElementCache(t)}this._onRemovalComplete(t,i.setForRemoval)}(null===(e=t.classList)||void 0===e?void 0:e.contains(cm))&&this.markElementAsDisabled(t,!1),this.driver.query(t,\".ng-animate-disabled\",!0).forEach(r=>{this.markElementAsDisabled(r,!1)})}flush(t=-1){let e=[];if(this.newHostElements.size&&(this.newHostElements.forEach((i,r)=>this._balanceNamespaceList(i,r)),this.newHostElements.clear()),this.totalAnimations&&this.collectedEnterElements.length)for(let i=0;i<this.collectedEnterElements.length;i++)In(this.collectedEnterElements[i],\"ng-star-inserted\");if(this._namespaceList.length&&(this.totalQueuedPlayers||this.collectedLeaveElements.length)){const i=[];try{e=this._flushAnimations(i,t)}finally{for(let r=0;r<i.length;r++)i[r]()}}else for(let i=0;i<this.collectedLeaveElements.length;i++)this.processLeaveNode(this.collectedLeaveElements[i]);if(this.totalQueuedPlayers=0,this.collectedEnterElements.length=0,this.collectedLeaveElements.length=0,this._flushFns.forEach(i=>i()),this._flushFns=[],this._whenQuietFns.length){const i=this._whenQuietFns;this._whenQuietFns=[],e.length?ir(e).onDone(()=>{i.forEach(r=>r())}):i.forEach(r=>r())}}reportError(t){throw function _H(n){return new H(3402,Ce)}()}_flushAnimations(t,e){const i=new gd,r=[],s=new Map,o=[],a=new Map,l=new Map,c=new Map,d=new Set;this.disabledNodes.forEach(j=>{d.add(j);const Y=this.driver.query(j,\".ng-animate-queued\",!0);for(let X=0;X<Y.length;X++)d.add(Y[X])});const u=this.bodyNode,h=Array.from(this.statesByElement.keys()),p=EM(h,this.collectedEnterElements),m=new Map;let g=0;p.forEach((j,Y)=>{const X=Zf+g++;m.set(Y,X),j.forEach(Se=>In(Se,X))});const _=[],D=new Set,v=new Set;for(let j=0;j<this.collectedLeaveElements.length;j++){const Y=this.collectedLeaveElements[j],X=Y[An];X&&X.setForRemoval&&(_.push(Y),D.add(Y),X.hasAnimation?this.driver.query(Y,\".ng-star-inserted\",!0).forEach(Se=>D.add(Se)):v.add(Y))}const M=new Map,V=EM(h,Array.from(D));V.forEach((j,Y)=>{const X=rd+g++;M.set(Y,X),j.forEach(Se=>In(Se,X))}),t.push(()=>{p.forEach((j,Y)=>{const X=m.get(Y);j.forEach(Se=>ro(Se,X))}),V.forEach((j,Y)=>{const X=M.get(Y);j.forEach(Se=>ro(Se,X))}),_.forEach(j=>{this.processLeaveNode(j)})});const he=[],We=[];for(let j=this._namespaceList.length-1;j>=0;j--)this._namespaceList[j].drainQueuedTransitions(e).forEach(X=>{const Se=X.player,St=X.element;if(he.push(Se),this.collectedEnterElements.length){const qt=St[An];if(qt&&qt.setForMove){if(qt.previousTriggersValues&&qt.previousTriggersValues.has(X.triggerName)){const is=qt.previousTriggersValues.get(X.triggerName),pr=this.statesByElement.get(X.element);pr&&pr[X.triggerName]&&(pr[X.triggerName].value=is)}return void Se.destroy()}}const wi=!u||!this.driver.containsElement(u,St),mn=M.get(St),hr=m.get(St),Xe=this._buildInstruction(X,i,hr,mn,wi);if(Xe.errors&&Xe.errors.length)return void We.push(Xe);if(wi)return Se.onStart(()=>zr(St,Xe.fromStyles)),Se.onDestroy(()=>vi(St,Xe.toStyles)),void r.push(Se);if(X.isFallbackTransition)return Se.onStart(()=>zr(St,Xe.fromStyles)),Se.onDestroy(()=>vi(St,Xe.toStyles)),void r.push(Se);const pk=[];Xe.timelines.forEach(qt=>{qt.stretchStartingKeyframe=!0,this.disabledNodes.has(qt.element)||pk.push(qt)}),Xe.timelines=pk,i.append(St,Xe.timelines),o.push({instruction:Xe,player:Se,element:St}),Xe.queriedElements.forEach(qt=>dn(a,qt,[]).push(Se)),Xe.preStyleProps.forEach((qt,is)=>{const pr=Object.keys(qt);if(pr.length){let rs=l.get(is);rs||l.set(is,rs=new Set),pr.forEach(Xg=>rs.add(Xg))}}),Xe.postStyleProps.forEach((qt,is)=>{const pr=Object.keys(qt);let rs=c.get(is);rs||c.set(is,rs=new Set),pr.forEach(Xg=>rs.add(Xg))})});if(We.length){const j=[];We.forEach(Y=>{j.push(function vH(n,t){return new H(3505,Ce)}())}),he.forEach(Y=>Y.destroy()),this.reportError(j)}const Ze=new Map,hn=new Map;o.forEach(j=>{const Y=j.element;i.has(Y)&&(hn.set(Y,Y),this._beforeAnimationBuild(j.player.namespaceId,j.instruction,Ze))}),r.forEach(j=>{const Y=j.element;this._getPreviousPlayers(Y,!1,j.namespaceId,j.triggerName,null).forEach(Se=>{dn(Ze,Y,[]).push(Se),Se.destroy()})});const pn=_.filter(j=>kM(j,l,c)),fn=new Map;xM(fn,this.driver,v,c,Vi).forEach(j=>{kM(j,l,c)&&pn.push(j)});const Gi=new Map;p.forEach((j,Y)=>{xM(Gi,this.driver,new Set(j),l,\"!\")}),pn.forEach(j=>{const Y=fn.get(j),X=Gi.get(j);fn.set(j,Object.assign(Object.assign({},Y),X))});const ii=[],wo=[],Mo={};o.forEach(j=>{const{element:Y,player:X,instruction:Se}=j;if(i.has(Y)){if(d.has(Y))return X.onDestroy(()=>vi(Y,Se.toStyles)),X.disabled=!0,X.overrideTotalTime(Se.totalTime),void r.push(X);let St=Mo;if(hn.size>1){let mn=Y;const hr=[];for(;mn=mn.parentNode;){const Xe=hn.get(mn);if(Xe){St=Xe;break}hr.push(mn)}hr.forEach(Xe=>hn.set(Xe,St))}const wi=this._buildAnimation(X.namespaceId,Se,Ze,s,Gi,fn);if(X.setRealPlayer(wi),St===Mo)ii.push(X);else{const mn=this.playersByElement.get(St);mn&&mn.length&&(X.parentPlayer=ir(mn)),r.push(X)}}else zr(Y,Se.fromStyles),X.onDestroy(()=>vi(Y,Se.toStyles)),wo.push(X),d.has(Y)&&r.push(X)}),wo.forEach(j=>{const Y=s.get(j.element);if(Y&&Y.length){const X=ir(Y);j.setRealPlayer(X)}}),r.forEach(j=>{j.parentPlayer?j.syncPlayerEvents(j.parentPlayer):j.destroy()});for(let j=0;j<_.length;j++){const Y=_[j],X=Y[An];if(ro(Y,rd),X&&X.hasAnimation)continue;let Se=[];if(a.size){let wi=a.get(Y);wi&&wi.length&&Se.push(...wi);let mn=this.driver.query(Y,Xf,!0);for(let hr=0;hr<mn.length;hr++){let Xe=a.get(mn[hr]);Xe&&Xe.length&&Se.push(...Xe)}}const St=Se.filter(wi=>!wi.destroyed);St.length?vj(this,Y,St):this.processLeaveNode(Y)}return _.length=0,ii.forEach(j=>{this.players.push(j),j.onDone(()=>{j.destroy();const Y=this.players.indexOf(j);this.players.splice(Y,1)}),j.play()}),ii}elementContainsData(t,e){let i=!1;const r=e[An];return r&&r.setForRemoval&&(i=!0),this.playersByElement.has(e)&&(i=!0),this.playersByQueriedElement.has(e)&&(i=!0),this.statesByElement.has(e)&&(i=!0),this._fetchNamespace(t).elementContainsData(e)||i}afterFlush(t){this._flushFns.push(t)}afterFlushAnimationsDone(t){this._whenQuietFns.push(t)}_getPreviousPlayers(t,e,i,r,s){let o=[];if(e){const a=this.playersByQueriedElement.get(t);a&&(o=a)}else{const a=this.playersByElement.get(t);if(a){const l=!s||s==Va;a.forEach(c=>{c.queued||!l&&c.triggerName!=r||o.push(c)})}}return(i||r)&&(o=o.filter(a=>!(i&&i!=a.namespaceId||r&&r!=a.triggerName))),o}_beforeAnimationBuild(t,e,i){const s=e.element,o=e.isRemovalTransition?void 0:t,a=e.isRemovalTransition?void 0:e.triggerName;for(const l of e.timelines){const c=l.element,d=c!==s,u=dn(i,c,[]);this._getPreviousPlayers(c,d,o,a,e.toState).forEach(p=>{const m=p.getRealPlayer();m.beforeDestroy&&m.beforeDestroy(),p.destroy(),u.push(p)})}zr(s,e.fromStyles)}_buildAnimation(t,e,i,r,s,o){const a=e.triggerName,l=e.element,c=[],d=new Set,u=new Set,h=e.timelines.map(m=>{const g=m.element;d.add(g);const _=g[An];if(_&&_.removedBeforeQueried)return new La(m.duration,m.delay);const D=g!==l,v=function yj(n){const t=[];return SM(n,t),t}((i.get(g)||uj).map(Ze=>Ze.getRealPlayer())).filter(Ze=>!!Ze.element&&Ze.element===g),M=s.get(g),V=o.get(g),he=Jw(0,this._normalizer,0,m.keyframes,M,V),We=this._buildPlayer(m,he,v);if(m.subTimeline&&r&&u.add(g),D){const Ze=new hm(t,a,g);Ze.setRealPlayer(We),c.push(Ze)}return We});c.forEach(m=>{dn(this.playersByQueriedElement,m.element,[]).push(m),m.onDone(()=>function mj(n,t,e){let i;if(n instanceof Map){if(i=n.get(t),i){if(i.length){const r=i.indexOf(e);i.splice(r,1)}0==i.length&&n.delete(t)}}else if(i=n[t],i){if(i.length){const r=i.indexOf(e);i.splice(r,1)}0==i.length&&delete n[t]}return i}(this.playersByQueriedElement,m.element,m))}),d.forEach(m=>In(m,cM));const p=ir(h);return p.onDestroy(()=>{d.forEach(m=>ro(m,cM)),vi(l,e.toStyles)}),u.forEach(m=>{dn(r,m,[]).push(p)}),p}_buildPlayer(t,e,i){return e.length>0?this.driver.animate(t.element,e,t.duration,t.delay,t.easing,i):new La(t.duration,t.delay)}}class hm{constructor(t,e,i){this.namespaceId=t,this.triggerName=e,this.element=i,this._player=new La,this._containsRealPlayer=!1,this._queuedCallbacks={},this.destroyed=!1,this.markedForDestroy=!1,this.disabled=!1,this.queued=!0,this.totalTime=0}setRealPlayer(t){this._containsRealPlayer||(this._player=t,Object.keys(this._queuedCallbacks).forEach(e=>{this._queuedCallbacks[e].forEach(i=>Gf(t,e,void 0,i))}),this._queuedCallbacks={},this._containsRealPlayer=!0,this.overrideTotalTime(t.totalTime),this.queued=!1)}getRealPlayer(){return this._player}overrideTotalTime(t){this.totalTime=t}syncPlayerEvents(t){const e=this._player;e.triggerCallback&&t.onStart(()=>e.triggerCallback(\"start\")),t.onDone(()=>this.finish()),t.onDestroy(()=>this.destroy())}_queueEvent(t,e){dn(this._queuedCallbacks,t,[]).push(e)}onDone(t){this.queued&&this._queueEvent(\"done\",t),this._player.onDone(t)}onStart(t){this.queued&&this._queueEvent(\"start\",t),this._player.onStart(t)}onDestroy(t){this.queued&&this._queueEvent(\"destroy\",t),this._player.onDestroy(t)}init(){this._player.init()}hasStarted(){return!this.queued&&this._player.hasStarted()}play(){!this.queued&&this._player.play()}pause(){!this.queued&&this._player.pause()}restart(){!this.queued&&this._player.restart()}finish(){this._player.finish()}destroy(){this.destroyed=!0,this._player.destroy()}reset(){!this.queued&&this._player.reset()}setPosition(t){this.queued||this._player.setPosition(t)}getPosition(){return this.queued?0:this._player.getPosition()}triggerCallback(t){const e=this._player;e.triggerCallback&&e.triggerCallback(t)}}function yd(n){return n&&1===n.nodeType}function MM(n,t){const e=n.style.display;return n.style.display=null!=t?t:\"none\",e}function xM(n,t,e,i,r){const s=[];e.forEach(l=>s.push(MM(l)));const o=[];i.forEach((l,c)=>{const d={};l.forEach(u=>{const h=d[u]=t.computeStyle(c,u,r);(!h||0==h.length)&&(c[An]=hj,o.push(c))}),n.set(c,d)});let a=0;return e.forEach(l=>MM(l,s[a++])),o}function EM(n,t){const e=new Map;if(n.forEach(a=>e.set(a,[])),0==t.length)return e;const r=new Set(t),s=new Map;function o(a){if(!a)return 1;let l=s.get(a);if(l)return l;const c=a.parentNode;return l=e.has(c)?c:r.has(c)?1:o(c),s.set(a,l),l}return t.forEach(a=>{const l=o(a);1!==l&&e.get(l).push(a)}),e}function In(n,t){var e;null===(e=n.classList)||void 0===e||e.add(t)}function ro(n,t){var e;null===(e=n.classList)||void 0===e||e.remove(t)}function vj(n,t,e){ir(e).onDone(()=>n.processLeaveNode(t))}function SM(n,t){for(let e=0;e<n.length;e++){const i=n[e];i instanceof Zw?SM(i.players,t):t.push(i)}}function kM(n,t,e){const i=e.get(n);if(!i)return!1;let r=t.get(n);return r?i.forEach(s=>r.add(s)):t.set(n,i),e.delete(n),!0}class bd{constructor(t,e,i){this.bodyNode=t,this._driver=e,this._normalizer=i,this._triggerCache={},this.onRemovalComplete=(r,s)=>{},this._transitionEngine=new fj(t,e,i),this._timelineEngine=new oj(t,e,i),this._transitionEngine.onRemovalComplete=(r,s)=>this.onRemovalComplete(r,s)}registerTrigger(t,e,i,r,s){const o=t+\"-\"+r;let a=this._triggerCache[o];if(!a){const l=[],d=nm(this._driver,s,l,[]);if(l.length)throw function aH(n,t){return new H(3404,Ce)}();a=function nj(n,t,e){return new ij(n,t,e)}(r,d,this._normalizer),this._triggerCache[o]=a}this._transitionEngine.registerTrigger(e,r,a)}register(t,e){this._transitionEngine.register(t,e)}destroy(t,e){this._transitionEngine.destroy(t,e)}onInsert(t,e,i,r){this._transitionEngine.insertNode(t,e,i,r)}onRemove(t,e,i,r){this._transitionEngine.removeNode(t,e,r||!1,i)}disableAnimations(t,e){this._transitionEngine.markElementAsDisabled(t,e)}process(t,e,i,r){if(\"@\"==i.charAt(0)){const[s,o]=eM(i);this._timelineEngine.command(s,e,o,r)}else this._transitionEngine.trigger(t,e,i,r)}listen(t,e,i,r,s){if(\"@\"==i.charAt(0)){const[o,a]=eM(i);return this._timelineEngine.listen(o,e,a,s)}return this._transitionEngine.listen(t,e,i,r,s)}flush(t=-1){this._transitionEngine.flush(t)}get players(){return this._transitionEngine.players.concat(this._timelineEngine.players)}whenRenderingDone(){return this._transitionEngine.whenRenderingDone()}}let Dj=(()=>{class n{constructor(e,i,r){this._element=e,this._startStyles=i,this._endStyles=r,this._state=0;let s=n.initialStylesByElement.get(e);s||n.initialStylesByElement.set(e,s={}),this._initialStyles=s}start(){this._state<1&&(this._startStyles&&vi(this._element,this._startStyles,this._initialStyles),this._state=1)}finish(){this.start(),this._state<2&&(vi(this._element,this._initialStyles),this._endStyles&&(vi(this._element,this._endStyles),this._endStyles=null),this._state=1)}destroy(){this.finish(),this._state<3&&(n.initialStylesByElement.delete(this._element),this._startStyles&&(zr(this._element,this._startStyles),this._endStyles=null),this._endStyles&&(zr(this._element,this._endStyles),this._endStyles=null),vi(this._element,this._initialStyles),this._state=3)}}return n.initialStylesByElement=new WeakMap,n})();function pm(n){let t=null;const e=Object.keys(n);for(let i=0;i<e.length;i++){const r=e[i];wj(r)&&(t=t||{},t[r]=n[r])}return t}function wj(n){return\"display\"===n||\"position\"===n}class TM{constructor(t,e,i,r){this.element=t,this.keyframes=e,this.options=i,this._specialStyles=r,this._onDoneFns=[],this._onStartFns=[],this._onDestroyFns=[],this._initialized=!1,this._finished=!1,this._started=!1,this._destroyed=!1,this.time=0,this.parentPlayer=null,this.currentSnapshot={},this._duration=i.duration,this._delay=i.delay||0,this.time=this._duration+this._delay}_onFinish(){this._finished||(this._finished=!0,this._onDoneFns.forEach(t=>t()),this._onDoneFns=[])}init(){this._buildPlayer(),this._preparePlayerBeforeStart()}_buildPlayer(){if(this._initialized)return;this._initialized=!0;const t=this.keyframes;this.domPlayer=this._triggerWebAnimation(this.element,t,this.options),this._finalKeyframe=t.length?t[t.length-1]:{},this.domPlayer.addEventListener(\"finish\",()=>this._onFinish())}_preparePlayerBeforeStart(){this._delay?this._resetDomPlayerState():this.domPlayer.pause()}_triggerWebAnimation(t,e,i){return t.animate(e,i)}onStart(t){this._onStartFns.push(t)}onDone(t){this._onDoneFns.push(t)}onDestroy(t){this._onDestroyFns.push(t)}play(){this._buildPlayer(),this.hasStarted()||(this._onStartFns.forEach(t=>t()),this._onStartFns=[],this._started=!0,this._specialStyles&&this._specialStyles.start()),this.domPlayer.play()}pause(){this.init(),this.domPlayer.pause()}finish(){this.init(),this._specialStyles&&this._specialStyles.finish(),this._onFinish(),this.domPlayer.finish()}reset(){this._resetDomPlayerState(),this._destroyed=!1,this._finished=!1,this._started=!1}_resetDomPlayerState(){this.domPlayer&&this.domPlayer.cancel()}restart(){this.reset(),this.play()}hasStarted(){return this._started}destroy(){this._destroyed||(this._destroyed=!0,this._resetDomPlayerState(),this._onFinish(),this._specialStyles&&this._specialStyles.destroy(),this._onDestroyFns.forEach(t=>t()),this._onDestroyFns=[])}setPosition(t){void 0===this.domPlayer&&this.init(),this.domPlayer.currentTime=t*this.time}getPosition(){return this.domPlayer.currentTime/this.time}get totalTime(){return this._delay+this._duration}beforeDestroy(){const t={};if(this.hasStarted()){const e=this._finalKeyframe;Object.keys(e).forEach(i=>{\"offset\"!=i&&(t[i]=this._finished?e[i]:fM(this.element,i))})}this.currentSnapshot=t}triggerCallback(t){const e=\"start\"==t?this._onStartFns:this._onDoneFns;e.forEach(i=>i()),e.length=0}}class Mj{validateStyleProperty(t){return rM(t)}matchesElement(t,e){return!1}containsElement(t,e){return sM(t,e)}getParentElement(t){return Qf(t)}query(t,e,i){return oM(t,e,i)}computeStyle(t,e,i){return window.getComputedStyle(t)[e]}animate(t,e,i,r,s,o=[]){const l={duration:i,delay:r,fill:0==r?\"both\":\"forwards\"};s&&(l.easing=s);const c={},d=o.filter(h=>h instanceof TM);(function kH(n,t){return 0===n||0===t})(i,r)&&d.forEach(h=>{let p=h.currentSnapshot;Object.keys(p).forEach(m=>c[m]=p[m])}),e=function TH(n,t,e){const i=Object.keys(e);if(i.length&&t.length){let s=t[0],o=[];if(i.forEach(a=>{s.hasOwnProperty(a)||o.push(a),s[a]=e[a]}),o.length)for(var r=1;r<t.length;r++){let a=t[r];o.forEach(function(l){a[l]=fM(n,l)})}}return t}(t,e=e.map(h=>rr(h,!1)),c);const u=function Cj(n,t){let e=null,i=null;return Array.isArray(t)&&t.length?(e=pm(t[0]),t.length>1&&(i=pm(t[t.length-1]))):t&&(e=pm(t)),e||i?new Dj(n,e,i):null}(t,e);return new TM(t,e,l,u)}}let xj=(()=>{class n extends Yw{constructor(e,i){super(),this._nextAnimationId=0,this._renderer=e.createRenderer(i.body,{id:\"0\",encapsulation:Ln.None,styles:[],data:{animation:[]}})}build(e){const i=this._nextAnimationId.toString();this._nextAnimationId++;const r=Array.isArray(e)?Qw(e):e;return AM(this._renderer,null,i,\"register\",[r]),new Ej(i,this._renderer)}}return n.\\u0275fac=function(e){return new(e||n)(y(da),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class Ej extends class V2{}{constructor(t,e){super(),this._id=t,this._renderer=e}create(t,e){return new Sj(this._id,t,e||{},this._renderer)}}class Sj{constructor(t,e,i,r){this.id=t,this.element=e,this._renderer=r,this.parentPlayer=null,this._started=!1,this.totalTime=0,this._command(\"create\",i)}_listen(t,e){return this._renderer.listen(this.element,`@@${this.id}:${t}`,e)}_command(t,...e){return AM(this._renderer,this.element,this.id,t,e)}onDone(t){this._listen(\"done\",t)}onStart(t){this._listen(\"start\",t)}onDestroy(t){this._listen(\"destroy\",t)}init(){this._command(\"init\")}hasStarted(){return this._started}play(){this._command(\"play\"),this._started=!0}pause(){this._command(\"pause\")}restart(){this._command(\"restart\")}finish(){this._command(\"finish\")}destroy(){this._command(\"destroy\")}reset(){this._command(\"reset\"),this._started=!1}setPosition(t){this._command(\"setPosition\",t)}getPosition(){var t,e;return null!==(e=null===(t=this._renderer.engine.players[+this.id])||void 0===t?void 0:t.getPosition())&&void 0!==e?e:0}}function AM(n,t,e,i,r){return n.setProperty(t,`@@${e}:${i}`,r)}const IM=\"@.disabled\";let kj=(()=>{class n{constructor(e,i,r){this.delegate=e,this.engine=i,this._zone=r,this._currentId=0,this._microtaskId=1,this._animationCallbacksBuffer=[],this._rendererCache=new Map,this._cdRecurDepth=0,this.promise=Promise.resolve(0),i.onRemovalComplete=(s,o)=>{const a=null==o?void 0:o.parentNode(s);a&&o.removeChild(a,s)}}createRenderer(e,i){const s=this.delegate.createRenderer(e,i);if(!(e&&i&&i.data&&i.data.animation)){let d=this._rendererCache.get(s);return d||(d=new RM(\"\",s,this.engine),this._rendererCache.set(s,d)),d}const o=i.id,a=i.id+\"-\"+this._currentId;this._currentId++,this.engine.register(a,e);const l=d=>{Array.isArray(d)?d.forEach(l):this.engine.registerTrigger(o,a,e,d.name,d)};return i.data.animation.forEach(l),new Tj(this,a,s,this.engine)}begin(){this._cdRecurDepth++,this.delegate.begin&&this.delegate.begin()}_scheduleCountTask(){this.promise.then(()=>{this._microtaskId++})}scheduleListenerCallback(e,i,r){e>=0&&e<this._microtaskId?this._zone.run(()=>i(r)):(0==this._animationCallbacksBuffer.length&&Promise.resolve(null).then(()=>{this._zone.run(()=>{this._animationCallbacksBuffer.forEach(s=>{const[o,a]=s;o(a)}),this._animationCallbacksBuffer=[]})}),this._animationCallbacksBuffer.push([i,r]))}end(){this._cdRecurDepth--,0==this._cdRecurDepth&&this._zone.runOutsideAngular(()=>{this._scheduleCountTask(),this.engine.flush(this._microtaskId)}),this.delegate.end&&this.delegate.end()}whenRenderingDone(){return this.engine.whenRenderingDone()}}return n.\\u0275fac=function(e){return new(e||n)(y(da),y(bd),y(ne))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();class RM{constructor(t,e,i){this.namespaceId=t,this.delegate=e,this.engine=i,this.destroyNode=this.delegate.destroyNode?r=>e.destroyNode(r):null}get data(){return this.delegate.data}destroy(){this.engine.destroy(this.namespaceId,this.delegate),this.delegate.destroy()}createElement(t,e){return this.delegate.createElement(t,e)}createComment(t){return this.delegate.createComment(t)}createText(t){return this.delegate.createText(t)}appendChild(t,e){this.delegate.appendChild(t,e),this.engine.onInsert(this.namespaceId,e,t,!1)}insertBefore(t,e,i,r=!0){this.delegate.insertBefore(t,e,i),this.engine.onInsert(this.namespaceId,e,t,r)}removeChild(t,e,i){this.engine.onRemove(this.namespaceId,e,this.delegate,i)}selectRootElement(t,e){return this.delegate.selectRootElement(t,e)}parentNode(t){return this.delegate.parentNode(t)}nextSibling(t){return this.delegate.nextSibling(t)}setAttribute(t,e,i,r){this.delegate.setAttribute(t,e,i,r)}removeAttribute(t,e,i){this.delegate.removeAttribute(t,e,i)}addClass(t,e){this.delegate.addClass(t,e)}removeClass(t,e){this.delegate.removeClass(t,e)}setStyle(t,e,i,r){this.delegate.setStyle(t,e,i,r)}removeStyle(t,e,i){this.delegate.removeStyle(t,e,i)}setProperty(t,e,i){\"@\"==e.charAt(0)&&e==IM?this.disableAnimations(t,!!i):this.delegate.setProperty(t,e,i)}setValue(t,e){this.delegate.setValue(t,e)}listen(t,e,i){return this.delegate.listen(t,e,i)}disableAnimations(t,e){this.engine.disableAnimations(t,e)}}class Tj extends RM{constructor(t,e,i,r){super(e,i,r),this.factory=t,this.namespaceId=e}setProperty(t,e,i){\"@\"==e.charAt(0)?\".\"==e.charAt(1)&&e==IM?this.disableAnimations(t,i=void 0===i||!!i):this.engine.process(this.namespaceId,t,e.substr(1),i):this.delegate.setProperty(t,e,i)}listen(t,e,i){if(\"@\"==e.charAt(0)){const r=function Aj(n){switch(n){case\"body\":return document.body;case\"document\":return document;case\"window\":return window;default:return n}}(t);let s=e.substr(1),o=\"\";return\"@\"!=s.charAt(0)&&([s,o]=function Ij(n){const t=n.indexOf(\".\");return[n.substring(0,t),n.substr(t+1)]}(s)),this.engine.listen(this.namespaceId,r,s,o,a=>{this.factory.scheduleListenerCallback(a._data||-1,i,a)})}return this.delegate.listen(t,e,i)}}let Rj=(()=>{class n extends bd{constructor(e,i,r){super(e.body,i,r)}ngOnDestroy(){this.flush()}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(Kf),y(am))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const Rn=new b(\"AnimationModuleType\"),OM=[{provide:Yw,useClass:xj},{provide:am,useFactory:function Oj(){return new ZH}},{provide:bd,useClass:Rj},{provide:da,useFactory:function Pj(n,t,e){return new kj(n,t,e)},deps:[Vc,bd,ne]}],PM=[{provide:Kf,useFactory:()=>new Mj},{provide:Rn,useValue:\"BrowserAnimations\"},...OM],Fj=[{provide:Kf,useClass:aM},{provide:Rn,useValue:\"NoopAnimations\"},...OM];let Nj=(()=>{class n{static withConfig(e){return{ngModule:n,providers:e.disableAnimations?Fj:PM}}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:PM,imports:[FD]}),n})();let NM=(()=>{class n{constructor(e,i){this._renderer=e,this._elementRef=i,this.onChange=r=>{},this.onTouched=()=>{}}setProperty(e,i){this._renderer.setProperty(this._elementRef.nativeElement,e,i)}registerOnTouched(e){this.onTouched=e}registerOnChange(e){this.onChange=e}setDisabledState(e){this.setProperty(\"disabled\",e)}}return n.\\u0275fac=function(e){return new(e||n)(f(Ii),f(W))},n.\\u0275dir=C({type:n}),n})(),$r=(()=>{class n extends NM{}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275dir=C({type:n,features:[E]}),n})();const xt=new b(\"NgValueAccessor\"),Bj={provide:xt,useExisting:pe(()=>Dd),multi:!0},Hj=new b(\"CompositionEventMode\");let Dd=(()=>{class n extends NM{constructor(e,i,r){super(e,i),this._compositionMode=r,this._composing=!1,null==this._compositionMode&&(this._compositionMode=!function Vj(){const n=mi()?mi().getUserAgent():\"\";return/android (\\d+)/.test(n.toLowerCase())}())}writeValue(e){this.setProperty(\"value\",null==e?\"\":e)}_handleInput(e){(!this._compositionMode||this._compositionMode&&!this._composing)&&this.onChange(e)}_compositionStart(){this._composing=!0}_compositionEnd(e){this._composing=!1,this._compositionMode&&this.onChange(e)}}return n.\\u0275fac=function(e){return new(e||n)(f(Ii),f(W),f(Hj,8))},n.\\u0275dir=C({type:n,selectors:[[\"input\",\"formControlName\",\"\",3,\"type\",\"checkbox\"],[\"textarea\",\"formControlName\",\"\"],[\"input\",\"formControl\",\"\",3,\"type\",\"checkbox\"],[\"textarea\",\"formControl\",\"\"],[\"input\",\"ngModel\",\"\",3,\"type\",\"checkbox\"],[\"textarea\",\"ngModel\",\"\"],[\"\",\"ngDefaultControl\",\"\"]],hostBindings:function(e,i){1&e&&J(\"input\",function(s){return i._handleInput(s.target.value)})(\"blur\",function(){return i.onTouched()})(\"compositionstart\",function(){return i._compositionStart()})(\"compositionend\",function(s){return i._compositionEnd(s.target.value)})},features:[L([Bj]),E]}),n})();function sr(n){return null==n||0===n.length}function BM(n){return null!=n&&\"number\"==typeof n.length}const Dt=new b(\"NgValidators\"),or=new b(\"NgAsyncValidators\"),jj=/^(?=.{1,254}$)(?=.{1,64}@)[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;class yi{static min(t){return function VM(n){return t=>{if(sr(t.value)||sr(n))return null;const e=parseFloat(t.value);return!isNaN(e)&&e<n?{min:{min:n,actual:t.value}}:null}}(t)}static max(t){return function HM(n){return t=>{if(sr(t.value)||sr(n))return null;const e=parseFloat(t.value);return!isNaN(e)&&e>n?{max:{max:n,actual:t.value}}:null}}(t)}static required(t){return function jM(n){return sr(n.value)?{required:!0}:null}(t)}static requiredTrue(t){return function zM(n){return!0===n.value?null:{required:!0}}(t)}static email(t){return function UM(n){return sr(n.value)||jj.test(n.value)?null:{email:!0}}(t)}static minLength(t){return function $M(n){return t=>sr(t.value)||!BM(t.value)?null:t.value.length<n?{minlength:{requiredLength:n,actualLength:t.value.length}}:null}(t)}static maxLength(t){return function GM(n){return t=>BM(t.value)&&t.value.length>n?{maxlength:{requiredLength:n,actualLength:t.value.length}}:null}(t)}static pattern(t){return function WM(n){if(!n)return wd;let t,e;return\"string\"==typeof n?(e=\"\",\"^\"!==n.charAt(0)&&(e+=\"^\"),e+=n,\"$\"!==n.charAt(n.length-1)&&(e+=\"$\"),t=new RegExp(e)):(e=n.toString(),t=n),i=>{if(sr(i.value))return null;const r=i.value;return t.test(r)?null:{pattern:{requiredPattern:e,actualValue:r}}}}(t)}static nullValidator(t){return null}static compose(t){return XM(t)}static composeAsync(t){return JM(t)}}function wd(n){return null}function qM(n){return null!=n}function YM(n){const t=ra(n)?mt(n):n;return up(t),t}function QM(n){let t={};return n.forEach(e=>{t=null!=e?Object.assign(Object.assign({},t),e):t}),0===Object.keys(t).length?null:t}function KM(n,t){return t.map(e=>e(n))}function ZM(n){return n.map(t=>function zj(n){return!n.validate}(t)?t:e=>t.validate(e))}function XM(n){if(!n)return null;const t=n.filter(qM);return 0==t.length?null:function(e){return QM(KM(e,t))}}function fm(n){return null!=n?XM(ZM(n)):null}function JM(n){if(!n)return null;const t=n.filter(qM);return 0==t.length?null:function(e){return function FM(...n){const t=b_(n),{args:e,keys:i}=VD(n),r=new Ve(s=>{const{length:o}=e;if(!o)return void s.complete();const a=new Array(o);let l=o,c=o;for(let d=0;d<o;d++){let u=!1;Jt(e[d]).subscribe(Ue(s,h=>{u||(u=!0,c--),a[d]=h},()=>l--,void 0,()=>{(!l||!u)&&(c||s.next(i?HD(i,a):a),s.complete())}))}});return t?r.pipe(bf(t)):r}(KM(e,t).map(YM)).pipe(ue(QM))}}function mm(n){return null!=n?JM(ZM(n)):null}function ex(n,t){return null===n?[t]:Array.isArray(n)?[...n,t]:[n,t]}function tx(n){return n._rawValidators}function nx(n){return n._rawAsyncValidators}function gm(n){return n?Array.isArray(n)?n:[n]:[]}function Md(n,t){return Array.isArray(n)?n.includes(t):n===t}function ix(n,t){const e=gm(t);return gm(n).forEach(r=>{Md(e,r)||e.push(r)}),e}function rx(n,t){return gm(t).filter(e=>!Md(n,e))}class sx{constructor(){this._rawValidators=[],this._rawAsyncValidators=[],this._onDestroyCallbacks=[]}get value(){return this.control?this.control.value:null}get valid(){return this.control?this.control.valid:null}get invalid(){return this.control?this.control.invalid:null}get pending(){return this.control?this.control.pending:null}get disabled(){return this.control?this.control.disabled:null}get enabled(){return this.control?this.control.enabled:null}get errors(){return this.control?this.control.errors:null}get pristine(){return this.control?this.control.pristine:null}get dirty(){return this.control?this.control.dirty:null}get touched(){return this.control?this.control.touched:null}get status(){return this.control?this.control.status:null}get untouched(){return this.control?this.control.untouched:null}get statusChanges(){return this.control?this.control.statusChanges:null}get valueChanges(){return this.control?this.control.valueChanges:null}get path(){return null}_setValidators(t){this._rawValidators=t||[],this._composedValidatorFn=fm(this._rawValidators)}_setAsyncValidators(t){this._rawAsyncValidators=t||[],this._composedAsyncValidatorFn=mm(this._rawAsyncValidators)}get validator(){return this._composedValidatorFn||null}get asyncValidator(){return this._composedAsyncValidatorFn||null}_registerOnDestroy(t){this._onDestroyCallbacks.push(t)}_invokeOnDestroyCallbacks(){this._onDestroyCallbacks.forEach(t=>t()),this._onDestroyCallbacks=[]}reset(t){this.control&&this.control.reset(t)}hasError(t,e){return!!this.control&&this.control.hasError(t,e)}getError(t,e){return this.control?this.control.getError(t,e):null}}class Jn extends sx{constructor(){super(...arguments),this._parent=null,this.name=null,this.valueAccessor=null}}class Wt extends sx{get formDirective(){return null}get path(){return null}}let ax=(()=>{class n extends class ox{constructor(t){this._cd=t}is(t){var e,i,r;return\"submitted\"===t?!!(null===(e=this._cd)||void 0===e?void 0:e.submitted):!!(null===(r=null===(i=this._cd)||void 0===i?void 0:i.control)||void 0===r?void 0:r[t])}}{constructor(e){super(e)}}return n.\\u0275fac=function(e){return new(e||n)(f(Jn,2))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"formControlName\",\"\"],[\"\",\"ngModel\",\"\"],[\"\",\"formControl\",\"\"]],hostVars:14,hostBindings:function(e,i){2&e&&Ae(\"ng-untouched\",i.is(\"untouched\"))(\"ng-touched\",i.is(\"touched\"))(\"ng-pristine\",i.is(\"pristine\"))(\"ng-dirty\",i.is(\"dirty\"))(\"ng-valid\",i.is(\"valid\"))(\"ng-invalid\",i.is(\"invalid\"))(\"ng-pending\",i.is(\"pending\"))},features:[E]}),n})();function Ha(n,t){ym(n,t),t.valueAccessor.writeValue(n.value),function Zj(n,t){t.valueAccessor.registerOnChange(e=>{n._pendingValue=e,n._pendingChange=!0,n._pendingDirty=!0,\"change\"===n.updateOn&&cx(n,t)})}(n,t),function Jj(n,t){const e=(i,r)=>{t.valueAccessor.writeValue(i),r&&t.viewToModelUpdate(i)};n.registerOnChange(e),t._registerOnDestroy(()=>{n._unregisterOnChange(e)})}(n,t),function Xj(n,t){t.valueAccessor.registerOnTouched(()=>{n._pendingTouched=!0,\"blur\"===n.updateOn&&n._pendingChange&&cx(n,t),\"submit\"!==n.updateOn&&n.markAsTouched()})}(n,t),function Kj(n,t){if(t.valueAccessor.setDisabledState){const e=i=>{t.valueAccessor.setDisabledState(i)};n.registerOnDisabledChange(e),t._registerOnDestroy(()=>{n._unregisterOnDisabledChange(e)})}}(n,t)}function Sd(n,t,e=!0){const i=()=>{};t.valueAccessor&&(t.valueAccessor.registerOnChange(i),t.valueAccessor.registerOnTouched(i)),Td(n,t),n&&(t._invokeOnDestroyCallbacks(),n._registerOnCollectionChange(()=>{}))}function kd(n,t){n.forEach(e=>{e.registerOnValidatorChange&&e.registerOnValidatorChange(t)})}function ym(n,t){const e=tx(n);null!==t.validator?n.setValidators(ex(e,t.validator)):\"function\"==typeof e&&n.setValidators([e]);const i=nx(n);null!==t.asyncValidator?n.setAsyncValidators(ex(i,t.asyncValidator)):\"function\"==typeof i&&n.setAsyncValidators([i]);const r=()=>n.updateValueAndValidity();kd(t._rawValidators,r),kd(t._rawAsyncValidators,r)}function Td(n,t){let e=!1;if(null!==n){if(null!==t.validator){const r=tx(n);if(Array.isArray(r)&&r.length>0){const s=r.filter(o=>o!==t.validator);s.length!==r.length&&(e=!0,n.setValidators(s))}}if(null!==t.asyncValidator){const r=nx(n);if(Array.isArray(r)&&r.length>0){const s=r.filter(o=>o!==t.asyncValidator);s.length!==r.length&&(e=!0,n.setAsyncValidators(s))}}}const i=()=>{};return kd(t._rawValidators,i),kd(t._rawAsyncValidators,i),e}function cx(n,t){n._pendingDirty&&n.markAsDirty(),n.setValue(n._pendingValue,{emitModelToViewChange:!1}),t.viewToModelUpdate(n._pendingValue),n._pendingChange=!1}function dx(n,t){ym(n,t)}function hx(n,t){n._syncPendingControls(),t.forEach(e=>{const i=e.control;\"submit\"===i.updateOn&&i._pendingChange&&(e.viewToModelUpdate(i._pendingValue),i._pendingChange=!1)})}function Dm(n,t){const e=n.indexOf(t);e>-1&&n.splice(e,1)}const ja=\"VALID\",Ad=\"INVALID\",so=\"PENDING\",za=\"DISABLED\";function Mm(n){return(Id(n)?n.validators:n)||null}function px(n){return Array.isArray(n)?fm(n):n||null}function xm(n,t){return(Id(t)?t.asyncValidators:n)||null}function fx(n){return Array.isArray(n)?mm(n):n||null}function Id(n){return null!=n&&!Array.isArray(n)&&\"object\"==typeof n}const mx=n=>n instanceof Rd,Em=n=>n instanceof km;function gx(n){return mx(n)?n.value:n.getRawValue()}function _x(n,t){const e=Em(n),i=n.controls;if(!(e?Object.keys(i):i).length)throw new H(1e3,\"\");if(!i[t])throw new H(1001,\"\")}function vx(n,t){Em(n),n._forEachChild((i,r)=>{if(void 0===t[r])throw new H(1002,\"\")})}class Sm{constructor(t,e){this._pendingDirty=!1,this._hasOwnPendingAsyncValidator=!1,this._pendingTouched=!1,this._onCollectionChange=()=>{},this._parent=null,this.pristine=!0,this.touched=!1,this._onDisabledChange=[],this._rawValidators=t,this._rawAsyncValidators=e,this._composedValidatorFn=px(this._rawValidators),this._composedAsyncValidatorFn=fx(this._rawAsyncValidators)}get validator(){return this._composedValidatorFn}set validator(t){this._rawValidators=this._composedValidatorFn=t}get asyncValidator(){return this._composedAsyncValidatorFn}set asyncValidator(t){this._rawAsyncValidators=this._composedAsyncValidatorFn=t}get parent(){return this._parent}get valid(){return this.status===ja}get invalid(){return this.status===Ad}get pending(){return this.status==so}get disabled(){return this.status===za}get enabled(){return this.status!==za}get dirty(){return!this.pristine}get untouched(){return!this.touched}get updateOn(){return this._updateOn?this._updateOn:this.parent?this.parent.updateOn:\"change\"}setValidators(t){this._rawValidators=t,this._composedValidatorFn=px(t)}setAsyncValidators(t){this._rawAsyncValidators=t,this._composedAsyncValidatorFn=fx(t)}addValidators(t){this.setValidators(ix(t,this._rawValidators))}addAsyncValidators(t){this.setAsyncValidators(ix(t,this._rawAsyncValidators))}removeValidators(t){this.setValidators(rx(t,this._rawValidators))}removeAsyncValidators(t){this.setAsyncValidators(rx(t,this._rawAsyncValidators))}hasValidator(t){return Md(this._rawValidators,t)}hasAsyncValidator(t){return Md(this._rawAsyncValidators,t)}clearValidators(){this.validator=null}clearAsyncValidators(){this.asyncValidator=null}markAsTouched(t={}){this.touched=!0,this._parent&&!t.onlySelf&&this._parent.markAsTouched(t)}markAllAsTouched(){this.markAsTouched({onlySelf:!0}),this._forEachChild(t=>t.markAllAsTouched())}markAsUntouched(t={}){this.touched=!1,this._pendingTouched=!1,this._forEachChild(e=>{e.markAsUntouched({onlySelf:!0})}),this._parent&&!t.onlySelf&&this._parent._updateTouched(t)}markAsDirty(t={}){this.pristine=!1,this._parent&&!t.onlySelf&&this._parent.markAsDirty(t)}markAsPristine(t={}){this.pristine=!0,this._pendingDirty=!1,this._forEachChild(e=>{e.markAsPristine({onlySelf:!0})}),this._parent&&!t.onlySelf&&this._parent._updatePristine(t)}markAsPending(t={}){this.status=so,!1!==t.emitEvent&&this.statusChanges.emit(this.status),this._parent&&!t.onlySelf&&this._parent.markAsPending(t)}disable(t={}){const e=this._parentMarkedDirty(t.onlySelf);this.status=za,this.errors=null,this._forEachChild(i=>{i.disable(Object.assign(Object.assign({},t),{onlySelf:!0}))}),this._updateValue(),!1!==t.emitEvent&&(this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._updateAncestors(Object.assign(Object.assign({},t),{skipPristineCheck:e})),this._onDisabledChange.forEach(i=>i(!0))}enable(t={}){const e=this._parentMarkedDirty(t.onlySelf);this.status=ja,this._forEachChild(i=>{i.enable(Object.assign(Object.assign({},t),{onlySelf:!0}))}),this.updateValueAndValidity({onlySelf:!0,emitEvent:t.emitEvent}),this._updateAncestors(Object.assign(Object.assign({},t),{skipPristineCheck:e})),this._onDisabledChange.forEach(i=>i(!1))}_updateAncestors(t){this._parent&&!t.onlySelf&&(this._parent.updateValueAndValidity(t),t.skipPristineCheck||this._parent._updatePristine(),this._parent._updateTouched())}setParent(t){this._parent=t}updateValueAndValidity(t={}){this._setInitialStatus(),this._updateValue(),this.enabled&&(this._cancelExistingSubscription(),this.errors=this._runValidator(),this.status=this._calculateStatus(),(this.status===ja||this.status===so)&&this._runAsyncValidator(t.emitEvent)),!1!==t.emitEvent&&(this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._parent&&!t.onlySelf&&this._parent.updateValueAndValidity(t)}_updateTreeValidity(t={emitEvent:!0}){this._forEachChild(e=>e._updateTreeValidity(t)),this.updateValueAndValidity({onlySelf:!0,emitEvent:t.emitEvent})}_setInitialStatus(){this.status=this._allControlsDisabled()?za:ja}_runValidator(){return this.validator?this.validator(this):null}_runAsyncValidator(t){if(this.asyncValidator){this.status=so,this._hasOwnPendingAsyncValidator=!0;const e=YM(this.asyncValidator(this));this._asyncValidationSubscription=e.subscribe(i=>{this._hasOwnPendingAsyncValidator=!1,this.setErrors(i,{emitEvent:t})})}}_cancelExistingSubscription(){this._asyncValidationSubscription&&(this._asyncValidationSubscription.unsubscribe(),this._hasOwnPendingAsyncValidator=!1)}setErrors(t,e={}){this.errors=t,this._updateControlsErrors(!1!==e.emitEvent)}get(t){return function iz(n,t,e){if(null==t||(Array.isArray(t)||(t=t.split(e)),Array.isArray(t)&&0===t.length))return null;let i=n;return t.forEach(r=>{i=Em(i)?i.controls.hasOwnProperty(r)?i.controls[r]:null:(n=>n instanceof sz)(i)&&i.at(r)||null}),i}(this,t,\".\")}getError(t,e){const i=e?this.get(e):this;return i&&i.errors?i.errors[t]:null}hasError(t,e){return!!this.getError(t,e)}get root(){let t=this;for(;t._parent;)t=t._parent;return t}_updateControlsErrors(t){this.status=this._calculateStatus(),t&&this.statusChanges.emit(this.status),this._parent&&this._parent._updateControlsErrors(t)}_initObservables(){this.valueChanges=new $,this.statusChanges=new $}_calculateStatus(){return this._allControlsDisabled()?za:this.errors?Ad:this._hasOwnPendingAsyncValidator||this._anyControlsHaveStatus(so)?so:this._anyControlsHaveStatus(Ad)?Ad:ja}_anyControlsHaveStatus(t){return this._anyControls(e=>e.status===t)}_anyControlsDirty(){return this._anyControls(t=>t.dirty)}_anyControlsTouched(){return this._anyControls(t=>t.touched)}_updatePristine(t={}){this.pristine=!this._anyControlsDirty(),this._parent&&!t.onlySelf&&this._parent._updatePristine(t)}_updateTouched(t={}){this.touched=this._anyControlsTouched(),this._parent&&!t.onlySelf&&this._parent._updateTouched(t)}_isBoxedValue(t){return\"object\"==typeof t&&null!==t&&2===Object.keys(t).length&&\"value\"in t&&\"disabled\"in t}_registerOnCollectionChange(t){this._onCollectionChange=t}_setUpdateStrategy(t){Id(t)&&null!=t.updateOn&&(this._updateOn=t.updateOn)}_parentMarkedDirty(t){return!t&&!(!this._parent||!this._parent.dirty)&&!this._parent._anyControlsDirty()}}class Rd extends Sm{constructor(t=null,e,i){super(Mm(e),xm(i,e)),this.defaultValue=null,this._onChange=[],this._pendingChange=!1,this._applyFormState(t),this._setUpdateStrategy(e),this._initObservables(),this.updateValueAndValidity({onlySelf:!0,emitEvent:!!this.asyncValidator}),Id(e)&&e.initialValueIsDefault&&(this.defaultValue=this._isBoxedValue(t)?t.value:t)}setValue(t,e={}){this.value=this._pendingValue=t,this._onChange.length&&!1!==e.emitModelToViewChange&&this._onChange.forEach(i=>i(this.value,!1!==e.emitViewToModelChange)),this.updateValueAndValidity(e)}patchValue(t,e={}){this.setValue(t,e)}reset(t=this.defaultValue,e={}){this._applyFormState(t),this.markAsPristine(e),this.markAsUntouched(e),this.setValue(this.value,e),this._pendingChange=!1}_updateValue(){}_anyControls(t){return!1}_allControlsDisabled(){return this.disabled}registerOnChange(t){this._onChange.push(t)}_unregisterOnChange(t){Dm(this._onChange,t)}registerOnDisabledChange(t){this._onDisabledChange.push(t)}_unregisterOnDisabledChange(t){Dm(this._onDisabledChange,t)}_forEachChild(t){}_syncPendingControls(){return!(\"submit\"!==this.updateOn||(this._pendingDirty&&this.markAsDirty(),this._pendingTouched&&this.markAsTouched(),!this._pendingChange)||(this.setValue(this._pendingValue,{onlySelf:!0,emitModelToViewChange:!1}),0))}_applyFormState(t){this._isBoxedValue(t)?(this.value=this._pendingValue=t.value,t.disabled?this.disable({onlySelf:!0,emitEvent:!1}):this.enable({onlySelf:!0,emitEvent:!1})):this.value=this._pendingValue=t}}class km extends Sm{constructor(t,e,i){super(Mm(e),xm(i,e)),this.controls=t,this._initObservables(),this._setUpdateStrategy(e),this._setUpControls(),this.updateValueAndValidity({onlySelf:!0,emitEvent:!!this.asyncValidator})}registerControl(t,e){return this.controls[t]?this.controls[t]:(this.controls[t]=e,e.setParent(this),e._registerOnCollectionChange(this._onCollectionChange),e)}addControl(t,e,i={}){this.registerControl(t,e),this.updateValueAndValidity({emitEvent:i.emitEvent}),this._onCollectionChange()}removeControl(t,e={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),delete this.controls[t],this.updateValueAndValidity({emitEvent:e.emitEvent}),this._onCollectionChange()}setControl(t,e,i={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),delete this.controls[t],e&&this.registerControl(t,e),this.updateValueAndValidity({emitEvent:i.emitEvent}),this._onCollectionChange()}contains(t){return this.controls.hasOwnProperty(t)&&this.controls[t].enabled}setValue(t,e={}){vx(this,t),Object.keys(t).forEach(i=>{_x(this,i),this.controls[i].setValue(t[i],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)}patchValue(t,e={}){null!=t&&(Object.keys(t).forEach(i=>{this.controls[i]&&this.controls[i].patchValue(t[i],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e))}reset(t={},e={}){this._forEachChild((i,r)=>{i.reset(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this._updatePristine(e),this._updateTouched(e),this.updateValueAndValidity(e)}getRawValue(){return this._reduceChildren({},(t,e,i)=>(t[i]=gx(e),t))}_syncPendingControls(){let t=this._reduceChildren(!1,(e,i)=>!!i._syncPendingControls()||e);return t&&this.updateValueAndValidity({onlySelf:!0}),t}_forEachChild(t){Object.keys(this.controls).forEach(e=>{const i=this.controls[e];i&&t(i,e)})}_setUpControls(){this._forEachChild(t=>{t.setParent(this),t._registerOnCollectionChange(this._onCollectionChange)})}_updateValue(){this.value=this._reduceValue()}_anyControls(t){for(const e of Object.keys(this.controls)){const i=this.controls[e];if(this.contains(e)&&t(i))return!0}return!1}_reduceValue(){return this._reduceChildren({},(t,e,i)=>((e.enabled||this.disabled)&&(t[i]=e.value),t))}_reduceChildren(t,e){let i=t;return this._forEachChild((r,s)=>{i=e(i,r,s)}),i}_allControlsDisabled(){for(const t of Object.keys(this.controls))if(this.controls[t].enabled)return!1;return Object.keys(this.controls).length>0||this.disabled}}class sz extends Sm{constructor(t,e,i){super(Mm(e),xm(i,e)),this.controls=t,this._initObservables(),this._setUpdateStrategy(e),this._setUpControls(),this.updateValueAndValidity({onlySelf:!0,emitEvent:!!this.asyncValidator})}at(t){return this.controls[t]}push(t,e={}){this.controls.push(t),this._registerControl(t),this.updateValueAndValidity({emitEvent:e.emitEvent}),this._onCollectionChange()}insert(t,e,i={}){this.controls.splice(t,0,e),this._registerControl(e),this.updateValueAndValidity({emitEvent:i.emitEvent})}removeAt(t,e={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),this.controls.splice(t,1),this.updateValueAndValidity({emitEvent:e.emitEvent})}setControl(t,e,i={}){this.controls[t]&&this.controls[t]._registerOnCollectionChange(()=>{}),this.controls.splice(t,1),e&&(this.controls.splice(t,0,e),this._registerControl(e)),this.updateValueAndValidity({emitEvent:i.emitEvent}),this._onCollectionChange()}get length(){return this.controls.length}setValue(t,e={}){vx(this,t),t.forEach((i,r)=>{_x(this,r),this.at(r).setValue(i,{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)}patchValue(t,e={}){null!=t&&(t.forEach((i,r)=>{this.at(r)&&this.at(r).patchValue(i,{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e))}reset(t=[],e={}){this._forEachChild((i,r)=>{i.reset(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this._updatePristine(e),this._updateTouched(e),this.updateValueAndValidity(e)}getRawValue(){return this.controls.map(t=>gx(t))}clear(t={}){this.controls.length<1||(this._forEachChild(e=>e._registerOnCollectionChange(()=>{})),this.controls.splice(0),this.updateValueAndValidity({emitEvent:t.emitEvent}))}_syncPendingControls(){let t=this.controls.reduce((e,i)=>!!i._syncPendingControls()||e,!1);return t&&this.updateValueAndValidity({onlySelf:!0}),t}_forEachChild(t){this.controls.forEach((e,i)=>{t(e,i)})}_updateValue(){this.value=this.controls.filter(t=>t.enabled||this.disabled).map(t=>t.value)}_anyControls(t){return this.controls.some(e=>e.enabled&&t(e))}_setUpControls(){this._forEachChild(t=>this._registerControl(t))}_allControlsDisabled(){for(const t of this.controls)if(t.enabled)return!1;return this.controls.length>0||this.disabled}_registerControl(t){t.setParent(this),t._registerOnCollectionChange(this._onCollectionChange)}}const oz={provide:Wt,useExisting:pe(()=>oo)},Ua=(()=>Promise.resolve(null))();let oo=(()=>{class n extends Wt{constructor(e,i){super(),this.submitted=!1,this._directives=new Set,this.ngSubmit=new $,this.form=new km({},fm(e),mm(i))}ngAfterViewInit(){this._setUpdateStrategy()}get formDirective(){return this}get control(){return this.form}get path(){return[]}get controls(){return this.form.controls}addControl(e){Ua.then(()=>{const i=this._findContainer(e.path);e.control=i.registerControl(e.name,e.control),Ha(e.control,e),e.control.updateValueAndValidity({emitEvent:!1}),this._directives.add(e)})}getControl(e){return this.form.get(e.path)}removeControl(e){Ua.then(()=>{const i=this._findContainer(e.path);i&&i.removeControl(e.name),this._directives.delete(e)})}addFormGroup(e){Ua.then(()=>{const i=this._findContainer(e.path),r=new km({});dx(r,e),i.registerControl(e.name,r),r.updateValueAndValidity({emitEvent:!1})})}removeFormGroup(e){Ua.then(()=>{const i=this._findContainer(e.path);i&&i.removeControl(e.name)})}getFormGroup(e){return this.form.get(e.path)}updateModel(e,i){Ua.then(()=>{this.form.get(e.path).setValue(i)})}setValue(e){this.control.setValue(e)}onSubmit(e){return this.submitted=!0,hx(this.form,this._directives),this.ngSubmit.emit(e),!1}onReset(){this.resetForm()}resetForm(e){this.form.reset(e),this.submitted=!1}_setUpdateStrategy(){this.options&&null!=this.options.updateOn&&(this.form._updateOn=this.options.updateOn)}_findContainer(e){return e.pop(),e.length?this.form.get(e):this.form}}return n.\\u0275fac=function(e){return new(e||n)(f(Dt,10),f(or,10))},n.\\u0275dir=C({type:n,selectors:[[\"form\",3,\"ngNoForm\",\"\",3,\"formGroup\",\"\"],[\"ng-form\"],[\"\",\"ngForm\",\"\"]],hostBindings:function(e,i){1&e&&J(\"submit\",function(s){return i.onSubmit(s)})(\"reset\",function(){return i.onReset()})},inputs:{options:[\"ngFormOptions\",\"options\"]},outputs:{ngSubmit:\"ngSubmit\"},exportAs:[\"ngForm\"],features:[L([oz]),E]}),n})();const dz={provide:xt,useExisting:pe(()=>Tm),multi:!0};let Tm=(()=>{class n extends $r{writeValue(e){this.setProperty(\"value\",null==e?\"\":e)}registerOnChange(e){this.onChange=i=>{e(\"\"==i?null:parseFloat(i))}}}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275dir=C({type:n,selectors:[[\"input\",\"type\",\"number\",\"formControlName\",\"\"],[\"input\",\"type\",\"number\",\"formControl\",\"\"],[\"input\",\"type\",\"number\",\"ngModel\",\"\"]],hostBindings:function(e,i){1&e&&J(\"input\",function(s){return i.onChange(s.target.value)})(\"blur\",function(){return i.onTouched()})},features:[L([dz]),E]}),n})(),wx=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const Am=new b(\"NgModelWithFormControlWarning\"),fz={provide:Jn,useExisting:pe(()=>Im)};let Im=(()=>{class n extends Jn{constructor(e,i,r,s){super(),this._ngModelWarningConfig=s,this.update=new $,this._ngModelWarningSent=!1,this._setValidators(e),this._setAsyncValidators(i),this.valueAccessor=function Cm(n,t){if(!t)return null;let e,i,r;return Array.isArray(t),t.forEach(s=>{s.constructor===Dd?e=s:function nz(n){return Object.getPrototypeOf(n.constructor)===$r}(s)?i=s:r=s}),r||i||e||null}(0,r)}set isDisabled(e){}ngOnChanges(e){if(this._isControlChanged(e)){const i=e.form.previousValue;i&&Sd(i,this,!1),Ha(this.form,this),this.control.disabled&&this.valueAccessor.setDisabledState&&this.valueAccessor.setDisabledState(!0),this.form.updateValueAndValidity({emitEvent:!1})}(function bm(n,t){if(!n.hasOwnProperty(\"model\"))return!1;const e=n.model;return!!e.isFirstChange()||!Object.is(t,e.currentValue)})(e,this.viewModel)&&(this.form.setValue(this.model),this.viewModel=this.model)}ngOnDestroy(){this.form&&Sd(this.form,this,!1)}get path(){return[]}get control(){return this.form}viewToModelUpdate(e){this.viewModel=e,this.update.emit(e)}_isControlChanged(e){return e.hasOwnProperty(\"form\")}}return n._ngModelWarningSentOnce=!1,n.\\u0275fac=function(e){return new(e||n)(f(Dt,10),f(or,10),f(xt,10),f(Am,8))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"formControl\",\"\"]],inputs:{form:[\"formControl\",\"form\"],isDisabled:[\"disabled\",\"isDisabled\"],model:[\"ngModel\",\"model\"]},outputs:{update:\"ngModelChange\"},exportAs:[\"ngForm\"],features:[L([fz]),E,Je]}),n})();const mz={provide:Wt,useExisting:pe(()=>ao)};let ao=(()=>{class n extends Wt{constructor(e,i){super(),this.validators=e,this.asyncValidators=i,this.submitted=!1,this._onCollectionChange=()=>this._updateDomValue(),this.directives=[],this.form=null,this.ngSubmit=new $,this._setValidators(e),this._setAsyncValidators(i)}ngOnChanges(e){this._checkFormPresent(),e.hasOwnProperty(\"form\")&&(this._updateValidators(),this._updateDomValue(),this._updateRegistrations(),this._oldForm=this.form)}ngOnDestroy(){this.form&&(Td(this.form,this),this.form._onCollectionChange===this._onCollectionChange&&this.form._registerOnCollectionChange(()=>{}))}get formDirective(){return this}get control(){return this.form}get path(){return[]}addControl(e){const i=this.form.get(e.path);return Ha(i,e),i.updateValueAndValidity({emitEvent:!1}),this.directives.push(e),i}getControl(e){return this.form.get(e.path)}removeControl(e){Sd(e.control||null,e,!1),Dm(this.directives,e)}addFormGroup(e){this._setUpFormContainer(e)}removeFormGroup(e){this._cleanUpFormContainer(e)}getFormGroup(e){return this.form.get(e.path)}addFormArray(e){this._setUpFormContainer(e)}removeFormArray(e){this._cleanUpFormContainer(e)}getFormArray(e){return this.form.get(e.path)}updateModel(e,i){this.form.get(e.path).setValue(i)}onSubmit(e){return this.submitted=!0,hx(this.form,this.directives),this.ngSubmit.emit(e),!1}onReset(){this.resetForm()}resetForm(e){this.form.reset(e),this.submitted=!1}_updateDomValue(){this.directives.forEach(e=>{const i=e.control,r=this.form.get(e.path);i!==r&&(Sd(i||null,e),mx(r)&&(Ha(r,e),e.control=r))}),this.form._updateTreeValidity({emitEvent:!1})}_setUpFormContainer(e){const i=this.form.get(e.path);dx(i,e),i.updateValueAndValidity({emitEvent:!1})}_cleanUpFormContainer(e){if(this.form){const i=this.form.get(e.path);i&&function ez(n,t){return Td(n,t)}(i,e)&&i.updateValueAndValidity({emitEvent:!1})}}_updateRegistrations(){this.form._registerOnCollectionChange(this._onCollectionChange),this._oldForm&&this._oldForm._registerOnCollectionChange(()=>{})}_updateValidators(){ym(this.form,this),this._oldForm&&Td(this._oldForm,this)}_checkFormPresent(){}}return n.\\u0275fac=function(e){return new(e||n)(f(Dt,10),f(or,10))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"formGroup\",\"\"]],hostBindings:function(e,i){1&e&&J(\"submit\",function(s){return i.onSubmit(s)})(\"reset\",function(){return i.onReset()})},inputs:{form:[\"formGroup\",\"form\"]},outputs:{ngSubmit:\"ngSubmit\"},exportAs:[\"ngForm\"],features:[L([mz]),E,Je]}),n})(),Bx=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[wx]]}),n})(),Pz=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[Bx]}),n})(),Fz=(()=>{class n{static withConfig(e){return{ngModule:n,providers:[{provide:Am,useValue:e.warnOnNgModelWithFormControl}]}}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[Bx]}),n})();const Nz=new b(\"cdk-dir-doc\",{providedIn:\"root\",factory:function Lz(){return Uo(ie)}}),Bz=/^(ar|ckb|dv|he|iw|fa|nqo|ps|sd|ug|ur|yi|.*[-_](Adlm|Arab|Hebr|Nkoo|Rohg|Thaa))(?!.*[-_](Latn|Cyrl)($|-|_))($|-|_)/i;let On=(()=>{class n{constructor(e){if(this.value=\"ltr\",this.change=new $,e){const r=e.documentElement?e.documentElement.dir:null;this.value=function Vz(n){const t=(null==n?void 0:n.toLowerCase())||\"\";return\"auto\"===t&&\"undefined\"!=typeof navigator&&(null==navigator?void 0:navigator.language)?Bz.test(navigator.language)?\"rtl\":\"ltr\":\"rtl\"===t?\"rtl\":\"ltr\"}((e.body?e.body.dir:null)||r||\"ltr\")}}ngOnDestroy(){this.change.complete()}}return n.\\u0275fac=function(e){return new(e||n)(y(Nz,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),lo=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const Lm=new Rr(\"13.3.0\");let Bm;try{Bm=\"undefined\"!=typeof Intl&&Intl.v8BreakIterator}catch(n){Bm=!1}let co,It=(()=>{class n{constructor(e){this._platformId=e,this.isBrowser=this._platformId?function OL(n){return n===wD}(this._platformId):\"object\"==typeof document&&!!document,this.EDGE=this.isBrowser&&/(edge)/i.test(navigator.userAgent),this.TRIDENT=this.isBrowser&&/(msie|trident)/i.test(navigator.userAgent),this.BLINK=this.isBrowser&&!(!window.chrome&&!Bm)&&\"undefined\"!=typeof CSS&&!this.EDGE&&!this.TRIDENT,this.WEBKIT=this.isBrowser&&/AppleWebKit/i.test(navigator.userAgent)&&!this.BLINK&&!this.EDGE&&!this.TRIDENT,this.IOS=this.isBrowser&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!(\"MSStream\"in window),this.FIREFOX=this.isBrowser&&/(firefox|minefield)/i.test(navigator.userAgent),this.ANDROID=this.isBrowser&&/android/i.test(navigator.userAgent)&&!this.TRIDENT,this.SAFARI=this.isBrowser&&/safari/i.test(navigator.userAgent)&&this.WEBKIT}}return n.\\u0275fac=function(e){return new(e||n)(y(bc))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const Vx=[\"color\",\"button\",\"checkbox\",\"date\",\"datetime-local\",\"email\",\"file\",\"hidden\",\"image\",\"month\",\"number\",\"password\",\"radio\",\"range\",\"reset\",\"search\",\"submit\",\"tel\",\"text\",\"time\",\"url\",\"week\"];function Hx(){if(co)return co;if(\"object\"!=typeof document||!document)return co=new Set(Vx),co;let n=document.createElement(\"input\");return co=new Set(Vx.filter(t=>(n.setAttribute(\"type\",t),n.type===t))),co}let $a,Wr,Vm;function ei(n){return function Hz(){if(null==$a&&\"undefined\"!=typeof window)try{window.addEventListener(\"test\",null,Object.defineProperty({},\"passive\",{get:()=>$a=!0}))}finally{$a=$a||!1}return $a}()?n:!!n.capture}function jz(){if(null==Wr){if(\"object\"!=typeof document||!document||\"function\"!=typeof Element||!Element)return Wr=!1,Wr;if(\"scrollBehavior\"in document.documentElement.style)Wr=!0;else{const n=Element.prototype.scrollTo;Wr=!!n&&!/\\{\\s*\\[native code\\]\\s*\\}/.test(n.toString())}}return Wr}function Fd(n){if(function zz(){if(null==Vm){const n=\"undefined\"!=typeof document?document.head:null;Vm=!(!n||!n.createShadowRoot&&!n.attachShadow)}return Vm}()){const t=n.getRootNode?n.getRootNode():null;if(\"undefined\"!=typeof ShadowRoot&&ShadowRoot&&t instanceof ShadowRoot)return t}return null}function Hm(){let n=\"undefined\"!=typeof document&&document?document.activeElement:null;for(;n&&n.shadowRoot;){const t=n.shadowRoot.activeElement;if(t===n)break;n=t}return n}function Pn(n){return n.composedPath?n.composedPath()[0]:n.target}function jm(){return\"undefined\"!=typeof __karma__&&!!__karma__||\"undefined\"!=typeof jasmine&&!!jasmine||\"undefined\"!=typeof jest&&!!jest||\"undefined\"!=typeof Mocha&&!!Mocha}function Xt(n,...t){return t.length?t.some(e=>n[e]):n.altKey||n.shiftKey||n.ctrlKey||n.metaKey}class e3 extends ke{constructor(t,e){super()}schedule(t,e=0){return this}}const Ld={setInterval(n,t,...e){const{delegate:i}=Ld;return(null==i?void 0:i.setInterval)?i.setInterval(n,t,...e):setInterval(n,t,...e)},clearInterval(n){const{delegate:t}=Ld;return((null==t?void 0:t.clearInterval)||clearInterval)(n)},delegate:void 0};class qm extends e3{constructor(t,e){super(t,e),this.scheduler=t,this.work=e,this.pending=!1}schedule(t,e=0){if(this.closed)return this;this.state=t;const i=this.id,r=this.scheduler;return null!=i&&(this.id=this.recycleAsyncId(r,i,e)),this.pending=!0,this.delay=e,this.id=this.id||this.requestAsyncId(r,this.id,e),this}requestAsyncId(t,e,i=0){return Ld.setInterval(t.flush.bind(t,this),i)}recycleAsyncId(t,e,i=0){if(null!=i&&this.delay===i&&!1===this.pending)return e;Ld.clearInterval(e)}execute(t,e){if(this.closed)return new Error(\"executing a cancelled action\");this.pending=!1;const i=this._execute(t,e);if(i)return i;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))}_execute(t,e){let r,i=!1;try{this.work(t)}catch(s){i=!0,r=s||new Error(\"Scheduled action threw falsy error\")}if(i)return this.unsubscribe(),r}unsubscribe(){if(!this.closed){const{id:t,scheduler:e}=this,{actions:i}=e;this.work=this.state=this.scheduler=null,this.pending=!1,ss(i,this),null!=t&&(this.id=this.recycleAsyncId(e,t,null)),this.delay=null,super.unsubscribe()}}}const Ux={now:()=>(Ux.delegate||Date).now(),delegate:void 0};class Wa{constructor(t,e=Wa.now){this.schedulerActionCtor=t,this.now=e}schedule(t,e=0,i){return new this.schedulerActionCtor(this,t).schedule(i,e)}}Wa.now=Ux.now;class Ym extends Wa{constructor(t,e=Wa.now){super(t,e),this.actions=[],this._active=!1,this._scheduled=void 0}flush(t){const{actions:e}=this;if(this._active)return void e.push(t);let i;this._active=!0;do{if(i=t.execute(t.state,t.delay))break}while(t=e.shift());if(this._active=!1,i){for(;t=e.shift();)t.unsubscribe();throw i}}}const qa=new Ym(qm),t3=qa;function $x(n,t=qa){return qe((e,i)=>{let r=null,s=null,o=null;const a=()=>{if(r){r.unsubscribe(),r=null;const c=s;s=null,i.next(c)}};function l(){const c=o+n,d=t.now();if(d<c)return r=this.schedule(void 0,c-d),void i.add(r);a()}e.subscribe(Ue(i,c=>{s=c,o=t.now(),r||(r=t.schedule(l,n),i.add(r))},()=>{a(),i.complete()},void 0,()=>{s=r=null}))})}function Gx(n,t=Wi){return n=null!=n?n:r3,qe((e,i)=>{let r,s=!0;e.subscribe(Ue(i,o=>{const a=t(o);(s||!n(r,a))&&(s=!1,r=a,i.next(o))}))})}function r3(n,t){return n===t}function Ie(n){return qe((t,e)=>{Jt(n).subscribe(Ue(e,()=>e.complete(),gl)),!e.closed&&t.subscribe(e)})}function G(n){return null!=n&&\"false\"!=`${n}`}function Et(n,t=0){return function s3(n){return!isNaN(parseFloat(n))&&!isNaN(Number(n))}(n)?Number(n):t}function Wx(n){return Array.isArray(n)?n:[n]}function ft(n){return null==n?\"\":\"string\"==typeof n?n:`${n}px`}function at(n){return n instanceof W?n.nativeElement:n}let qx=(()=>{class n{create(e){return\"undefined\"==typeof MutationObserver?null:new MutationObserver(e)}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),o3=(()=>{class n{constructor(e){this._mutationObserverFactory=e,this._observedElements=new Map}ngOnDestroy(){this._observedElements.forEach((e,i)=>this._cleanupObserver(i))}observe(e){const i=at(e);return new Ve(r=>{const o=this._observeElement(i).subscribe(r);return()=>{o.unsubscribe(),this._unobserveElement(i)}})}_observeElement(e){if(this._observedElements.has(e))this._observedElements.get(e).count++;else{const i=new O,r=this._mutationObserverFactory.create(s=>i.next(s));r&&r.observe(e,{characterData:!0,childList:!0,subtree:!0}),this._observedElements.set(e,{observer:r,stream:i,count:1})}return this._observedElements.get(e).stream}_unobserveElement(e){this._observedElements.has(e)&&(this._observedElements.get(e).count--,this._observedElements.get(e).count||this._cleanupObserver(e))}_cleanupObserver(e){if(this._observedElements.has(e)){const{observer:i,stream:r}=this._observedElements.get(e);i&&i.disconnect(),r.complete(),this._observedElements.delete(e)}}}return n.\\u0275fac=function(e){return new(e||n)(y(qx))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),Qm=(()=>{class n{constructor(e,i,r){this._contentObserver=e,this._elementRef=i,this._ngZone=r,this.event=new $,this._disabled=!1,this._currentSubscription=null}get disabled(){return this._disabled}set disabled(e){this._disabled=G(e),this._disabled?this._unsubscribe():this._subscribe()}get debounce(){return this._debounce}set debounce(e){this._debounce=Et(e),this._subscribe()}ngAfterContentInit(){!this._currentSubscription&&!this.disabled&&this._subscribe()}ngOnDestroy(){this._unsubscribe()}_subscribe(){this._unsubscribe();const e=this._contentObserver.observe(this._elementRef);this._ngZone.runOutsideAngular(()=>{this._currentSubscription=(this.debounce?e.pipe($x(this.debounce)):e).subscribe(this.event)})}_unsubscribe(){var e;null===(e=this._currentSubscription)||void 0===e||e.unsubscribe()}}return n.\\u0275fac=function(e){return new(e||n)(f(o3),f(W),f(ne))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"cdkObserveContent\",\"\"]],inputs:{disabled:[\"cdkObserveContentDisabled\",\"disabled\"],debounce:\"debounce\"},outputs:{event:\"cdkObserveContent\"},exportAs:[\"cdkObserveContent\"]}),n})(),Ya=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[qx]}),n})();class c3 extends class Kx{constructor(t){this._items=t,this._activeItemIndex=-1,this._activeItem=null,this._wrap=!1,this._letterKeyStream=new O,this._typeaheadSubscription=ke.EMPTY,this._vertical=!0,this._allowedModifierKeys=[],this._homeAndEnd=!1,this._skipPredicateFn=e=>e.disabled,this._pressedLetters=[],this.tabOut=new O,this.change=new O,t instanceof fa&&t.changes.subscribe(e=>{if(this._activeItem){const r=e.toArray().indexOf(this._activeItem);r>-1&&r!==this._activeItemIndex&&(this._activeItemIndex=r)}})}skipPredicate(t){return this._skipPredicateFn=t,this}withWrap(t=!0){return this._wrap=t,this}withVerticalOrientation(t=!0){return this._vertical=t,this}withHorizontalOrientation(t){return this._horizontal=t,this}withAllowedModifierKeys(t){return this._allowedModifierKeys=t,this}withTypeAhead(t=200){return this._typeaheadSubscription.unsubscribe(),this._typeaheadSubscription=this._letterKeyStream.pipe(Mt(e=>this._pressedLetters.push(e)),$x(t),Ct(()=>this._pressedLetters.length>0),ue(()=>this._pressedLetters.join(\"\"))).subscribe(e=>{const i=this._getItemsArray();for(let r=1;r<i.length+1;r++){const s=(this._activeItemIndex+r)%i.length,o=i[s];if(!this._skipPredicateFn(o)&&0===o.getLabel().toUpperCase().trim().indexOf(e)){this.setActiveItem(s);break}}this._pressedLetters=[]}),this}withHomeAndEnd(t=!0){return this._homeAndEnd=t,this}setActiveItem(t){const e=this._activeItem;this.updateActiveItem(t),this._activeItem!==e&&this.change.next(this._activeItemIndex)}onKeydown(t){const e=t.keyCode,r=[\"altKey\",\"ctrlKey\",\"metaKey\",\"shiftKey\"].every(s=>!t[s]||this._allowedModifierKeys.indexOf(s)>-1);switch(e){case 9:return void this.tabOut.next();case 40:if(this._vertical&&r){this.setNextItemActive();break}return;case 38:if(this._vertical&&r){this.setPreviousItemActive();break}return;case 39:if(this._horizontal&&r){\"rtl\"===this._horizontal?this.setPreviousItemActive():this.setNextItemActive();break}return;case 37:if(this._horizontal&&r){\"rtl\"===this._horizontal?this.setNextItemActive():this.setPreviousItemActive();break}return;case 36:if(this._homeAndEnd&&r){this.setFirstItemActive();break}return;case 35:if(this._homeAndEnd&&r){this.setLastItemActive();break}return;default:return void((r||Xt(t,\"shiftKey\"))&&(t.key&&1===t.key.length?this._letterKeyStream.next(t.key.toLocaleUpperCase()):(e>=65&&e<=90||e>=48&&e<=57)&&this._letterKeyStream.next(String.fromCharCode(e))))}this._pressedLetters=[],t.preventDefault()}get activeItemIndex(){return this._activeItemIndex}get activeItem(){return this._activeItem}isTyping(){return this._pressedLetters.length>0}setFirstItemActive(){this._setActiveItemByIndex(0,1)}setLastItemActive(){this._setActiveItemByIndex(this._items.length-1,-1)}setNextItemActive(){this._activeItemIndex<0?this.setFirstItemActive():this._setActiveItemByDelta(1)}setPreviousItemActive(){this._activeItemIndex<0&&this._wrap?this.setLastItemActive():this._setActiveItemByDelta(-1)}updateActiveItem(t){const e=this._getItemsArray(),i=\"number\"==typeof t?t:e.indexOf(t),r=e[i];this._activeItem=null==r?null:r,this._activeItemIndex=i}_setActiveItemByDelta(t){this._wrap?this._setActiveInWrapMode(t):this._setActiveInDefaultMode(t)}_setActiveInWrapMode(t){const e=this._getItemsArray();for(let i=1;i<=e.length;i++){const r=(this._activeItemIndex+t*i+e.length)%e.length;if(!this._skipPredicateFn(e[r]))return void this.setActiveItem(r)}}_setActiveInDefaultMode(t){this._setActiveItemByIndex(this._activeItemIndex+t,t)}_setActiveItemByIndex(t,e){const i=this._getItemsArray();if(i[t]){for(;this._skipPredicateFn(i[t]);)if(!i[t+=e])return;this.setActiveItem(t)}}_getItemsArray(){return this._items instanceof fa?this._items.toArray():this._items}}{setActiveItem(t){this.activeItem&&this.activeItem.setInactiveStyles(),super.setActiveItem(t),this.activeItem&&this.activeItem.setActiveStyles()}}let Xx=(()=>{class n{constructor(e){this._platform=e}isDisabled(e){return e.hasAttribute(\"disabled\")}isVisible(e){return function u3(n){return!!(n.offsetWidth||n.offsetHeight||\"function\"==typeof n.getClientRects&&n.getClientRects().length)}(e)&&\"visible\"===getComputedStyle(e).visibility}isTabbable(e){if(!this._platform.isBrowser)return!1;const i=function d3(n){try{return n.frameElement}catch(t){return null}}(function y3(n){return n.ownerDocument&&n.ownerDocument.defaultView||window}(e));if(i&&(-1===eE(i)||!this.isVisible(i)))return!1;let r=e.nodeName.toLowerCase(),s=eE(e);return e.hasAttribute(\"contenteditable\")?-1!==s:!(\"iframe\"===r||\"object\"===r||this._platform.WEBKIT&&this._platform.IOS&&!function _3(n){let t=n.nodeName.toLowerCase(),e=\"input\"===t&&n.type;return\"text\"===e||\"password\"===e||\"select\"===t||\"textarea\"===t}(e))&&(\"audio\"===r?!!e.hasAttribute(\"controls\")&&-1!==s:\"video\"===r?-1!==s&&(null!==s||this._platform.FIREFOX||e.hasAttribute(\"controls\")):e.tabIndex>=0)}isFocusable(e,i){return function v3(n){return!function p3(n){return function m3(n){return\"input\"==n.nodeName.toLowerCase()}(n)&&\"hidden\"==n.type}(n)&&(function h3(n){let t=n.nodeName.toLowerCase();return\"input\"===t||\"select\"===t||\"button\"===t||\"textarea\"===t}(n)||function f3(n){return function g3(n){return\"a\"==n.nodeName.toLowerCase()}(n)&&n.hasAttribute(\"href\")}(n)||n.hasAttribute(\"contenteditable\")||Jx(n))}(e)&&!this.isDisabled(e)&&((null==i?void 0:i.ignoreVisibility)||this.isVisible(e))}}return n.\\u0275fac=function(e){return new(e||n)(y(It))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();function Jx(n){if(!n.hasAttribute(\"tabindex\")||void 0===n.tabIndex)return!1;let t=n.getAttribute(\"tabindex\");return!(!t||isNaN(parseInt(t,10)))}function eE(n){if(!Jx(n))return null;const t=parseInt(n.getAttribute(\"tabindex\")||\"\",10);return isNaN(t)?-1:t}class b3{constructor(t,e,i,r,s=!1){this._element=t,this._checker=e,this._ngZone=i,this._document=r,this._hasAttached=!1,this.startAnchorListener=()=>this.focusLastTabbableElement(),this.endAnchorListener=()=>this.focusFirstTabbableElement(),this._enabled=!0,s||this.attachAnchors()}get enabled(){return this._enabled}set enabled(t){this._enabled=t,this._startAnchor&&this._endAnchor&&(this._toggleAnchorTabIndex(t,this._startAnchor),this._toggleAnchorTabIndex(t,this._endAnchor))}destroy(){const t=this._startAnchor,e=this._endAnchor;t&&(t.removeEventListener(\"focus\",this.startAnchorListener),t.remove()),e&&(e.removeEventListener(\"focus\",this.endAnchorListener),e.remove()),this._startAnchor=this._endAnchor=null,this._hasAttached=!1}attachAnchors(){return!!this._hasAttached||(this._ngZone.runOutsideAngular(()=>{this._startAnchor||(this._startAnchor=this._createAnchor(),this._startAnchor.addEventListener(\"focus\",this.startAnchorListener)),this._endAnchor||(this._endAnchor=this._createAnchor(),this._endAnchor.addEventListener(\"focus\",this.endAnchorListener))}),this._element.parentNode&&(this._element.parentNode.insertBefore(this._startAnchor,this._element),this._element.parentNode.insertBefore(this._endAnchor,this._element.nextSibling),this._hasAttached=!0),this._hasAttached)}focusInitialElementWhenReady(t){return new Promise(e=>{this._executeOnStable(()=>e(this.focusInitialElement(t)))})}focusFirstTabbableElementWhenReady(t){return new Promise(e=>{this._executeOnStable(()=>e(this.focusFirstTabbableElement(t)))})}focusLastTabbableElementWhenReady(t){return new Promise(e=>{this._executeOnStable(()=>e(this.focusLastTabbableElement(t)))})}_getRegionBoundary(t){const e=this._element.querySelectorAll(`[cdk-focus-region-${t}], [cdkFocusRegion${t}], [cdk-focus-${t}]`);return\"start\"==t?e.length?e[0]:this._getFirstTabbableElement(this._element):e.length?e[e.length-1]:this._getLastTabbableElement(this._element)}focusInitialElement(t){const e=this._element.querySelector(\"[cdk-focus-initial], [cdkFocusInitial]\");if(e){if(!this._checker.isFocusable(e)){const i=this._getFirstTabbableElement(e);return null==i||i.focus(t),!!i}return e.focus(t),!0}return this.focusFirstTabbableElement(t)}focusFirstTabbableElement(t){const e=this._getRegionBoundary(\"start\");return e&&e.focus(t),!!e}focusLastTabbableElement(t){const e=this._getRegionBoundary(\"end\");return e&&e.focus(t),!!e}hasAttached(){return this._hasAttached}_getFirstTabbableElement(t){if(this._checker.isFocusable(t)&&this._checker.isTabbable(t))return t;const e=t.children;for(let i=0;i<e.length;i++){const r=e[i].nodeType===this._document.ELEMENT_NODE?this._getFirstTabbableElement(e[i]):null;if(r)return r}return null}_getLastTabbableElement(t){if(this._checker.isFocusable(t)&&this._checker.isTabbable(t))return t;const e=t.children;for(let i=e.length-1;i>=0;i--){const r=e[i].nodeType===this._document.ELEMENT_NODE?this._getLastTabbableElement(e[i]):null;if(r)return r}return null}_createAnchor(){const t=this._document.createElement(\"div\");return this._toggleAnchorTabIndex(this._enabled,t),t.classList.add(\"cdk-visually-hidden\"),t.classList.add(\"cdk-focus-trap-anchor\"),t.setAttribute(\"aria-hidden\",\"true\"),t}_toggleAnchorTabIndex(t,e){t?e.setAttribute(\"tabindex\",\"0\"):e.removeAttribute(\"tabindex\")}toggleAnchors(t){this._startAnchor&&this._endAnchor&&(this._toggleAnchorTabIndex(t,this._startAnchor),this._toggleAnchorTabIndex(t,this._endAnchor))}_executeOnStable(t){this._ngZone.isStable?t():this._ngZone.onStable.pipe(it(1)).subscribe(t)}}let C3=(()=>{class n{constructor(e,i,r){this._checker=e,this._ngZone=i,this._document=r}create(e,i=!1){return new b3(e,this._checker,this._ngZone,this._document,i)}}return n.\\u0275fac=function(e){return new(e||n)(y(Xx),y(ne),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();function Km(n){return 0===n.buttons||0===n.offsetX&&0===n.offsetY}function Zm(n){const t=n.touches&&n.touches[0]||n.changedTouches&&n.changedTouches[0];return!(!t||-1!==t.identifier||null!=t.radiusX&&1!==t.radiusX||null!=t.radiusY&&1!==t.radiusY)}const D3=new b(\"cdk-input-modality-detector-options\"),w3={ignoreKeys:[18,17,224,91,16]},ho=ei({passive:!0,capture:!0});let M3=(()=>{class n{constructor(e,i,r,s){this._platform=e,this._mostRecentTarget=null,this._modality=new Zt(null),this._lastTouchMs=0,this._onKeydown=o=>{var a,l;(null===(l=null===(a=this._options)||void 0===a?void 0:a.ignoreKeys)||void 0===l?void 0:l.some(c=>c===o.keyCode))||(this._modality.next(\"keyboard\"),this._mostRecentTarget=Pn(o))},this._onMousedown=o=>{Date.now()-this._lastTouchMs<650||(this._modality.next(Km(o)?\"keyboard\":\"mouse\"),this._mostRecentTarget=Pn(o))},this._onTouchstart=o=>{Zm(o)?this._modality.next(\"keyboard\"):(this._lastTouchMs=Date.now(),this._modality.next(\"touch\"),this._mostRecentTarget=Pn(o))},this._options=Object.assign(Object.assign({},w3),s),this.modalityDetected=this._modality.pipe(function n3(n){return Ct((t,e)=>n<=e)}(1)),this.modalityChanged=this.modalityDetected.pipe(Gx()),e.isBrowser&&i.runOutsideAngular(()=>{r.addEventListener(\"keydown\",this._onKeydown,ho),r.addEventListener(\"mousedown\",this._onMousedown,ho),r.addEventListener(\"touchstart\",this._onTouchstart,ho)})}get mostRecentModality(){return this._modality.value}ngOnDestroy(){this._modality.complete(),this._platform.isBrowser&&(document.removeEventListener(\"keydown\",this._onKeydown,ho),document.removeEventListener(\"mousedown\",this._onMousedown,ho),document.removeEventListener(\"touchstart\",this._onTouchstart,ho))}}return n.\\u0275fac=function(e){return new(e||n)(y(It),y(ne),y(ie),y(D3,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const x3=new b(\"liveAnnouncerElement\",{providedIn:\"root\",factory:function E3(){return null}}),S3=new b(\"LIVE_ANNOUNCER_DEFAULT_OPTIONS\");let k3=(()=>{class n{constructor(e,i,r,s){this._ngZone=i,this._defaultOptions=s,this._document=r,this._liveElement=e||this._createLiveElement()}announce(e,...i){const r=this._defaultOptions;let s,o;return 1===i.length&&\"number\"==typeof i[0]?o=i[0]:[s,o]=i,this.clear(),clearTimeout(this._previousTimeout),s||(s=r&&r.politeness?r.politeness:\"polite\"),null==o&&r&&(o=r.duration),this._liveElement.setAttribute(\"aria-live\",s),this._ngZone.runOutsideAngular(()=>new Promise(a=>{clearTimeout(this._previousTimeout),this._previousTimeout=setTimeout(()=>{this._liveElement.textContent=e,a(),\"number\"==typeof o&&(this._previousTimeout=setTimeout(()=>this.clear(),o))},100)}))}clear(){this._liveElement&&(this._liveElement.textContent=\"\")}ngOnDestroy(){var e;clearTimeout(this._previousTimeout),null===(e=this._liveElement)||void 0===e||e.remove(),this._liveElement=null}_createLiveElement(){const e=\"cdk-live-announcer-element\",i=this._document.getElementsByClassName(e),r=this._document.createElement(\"div\");for(let s=0;s<i.length;s++)i[s].remove();return r.classList.add(e),r.classList.add(\"cdk-visually-hidden\"),r.setAttribute(\"aria-atomic\",\"true\"),r.setAttribute(\"aria-live\",\"polite\"),this._document.body.appendChild(r),r}}return n.\\u0275fac=function(e){return new(e||n)(y(x3,8),y(ne),y(ie),y(S3,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const T3=new b(\"cdk-focus-monitor-default-options\"),Bd=ei({passive:!0,capture:!0});let Qr=(()=>{class n{constructor(e,i,r,s,o){this._ngZone=e,this._platform=i,this._inputModalityDetector=r,this._origin=null,this._windowFocused=!1,this._originFromTouchInteraction=!1,this._elementInfo=new Map,this._monitoredElementCount=0,this._rootNodeFocusListenerCount=new Map,this._windowFocusListener=()=>{this._windowFocused=!0,this._windowFocusTimeoutId=window.setTimeout(()=>this._windowFocused=!1)},this._stopInputModalityDetector=new O,this._rootNodeFocusAndBlurListener=a=>{const l=Pn(a),c=\"focus\"===a.type?this._onFocus:this._onBlur;for(let d=l;d;d=d.parentElement)c.call(this,a,d)},this._document=s,this._detectionMode=(null==o?void 0:o.detectionMode)||0}monitor(e,i=!1){const r=at(e);if(!this._platform.isBrowser||1!==r.nodeType)return q(null);const s=Fd(r)||this._getDocument(),o=this._elementInfo.get(r);if(o)return i&&(o.checkChildren=!0),o.subject;const a={checkChildren:i,subject:new O,rootNode:s};return this._elementInfo.set(r,a),this._registerGlobalListeners(a),a.subject}stopMonitoring(e){const i=at(e),r=this._elementInfo.get(i);r&&(r.subject.complete(),this._setClasses(i),this._elementInfo.delete(i),this._removeGlobalListeners(r))}focusVia(e,i,r){const s=at(e);s===this._getDocument().activeElement?this._getClosestElementsInfo(s).forEach(([a,l])=>this._originChanged(a,i,l)):(this._setOrigin(i),\"function\"==typeof s.focus&&s.focus(r))}ngOnDestroy(){this._elementInfo.forEach((e,i)=>this.stopMonitoring(i))}_getDocument(){return this._document||document}_getWindow(){return this._getDocument().defaultView||window}_getFocusOrigin(e){return this._origin?this._originFromTouchInteraction?this._shouldBeAttributedToTouch(e)?\"touch\":\"program\":this._origin:this._windowFocused&&this._lastFocusOrigin?this._lastFocusOrigin:\"program\"}_shouldBeAttributedToTouch(e){return 1===this._detectionMode||!!(null==e?void 0:e.contains(this._inputModalityDetector._mostRecentTarget))}_setClasses(e,i){e.classList.toggle(\"cdk-focused\",!!i),e.classList.toggle(\"cdk-touch-focused\",\"touch\"===i),e.classList.toggle(\"cdk-keyboard-focused\",\"keyboard\"===i),e.classList.toggle(\"cdk-mouse-focused\",\"mouse\"===i),e.classList.toggle(\"cdk-program-focused\",\"program\"===i)}_setOrigin(e,i=!1){this._ngZone.runOutsideAngular(()=>{this._origin=e,this._originFromTouchInteraction=\"touch\"===e&&i,0===this._detectionMode&&(clearTimeout(this._originTimeoutId),this._originTimeoutId=setTimeout(()=>this._origin=null,this._originFromTouchInteraction?650:1))})}_onFocus(e,i){const r=this._elementInfo.get(i),s=Pn(e);!r||!r.checkChildren&&i!==s||this._originChanged(i,this._getFocusOrigin(s),r)}_onBlur(e,i){const r=this._elementInfo.get(i);!r||r.checkChildren&&e.relatedTarget instanceof Node&&i.contains(e.relatedTarget)||(this._setClasses(i),this._emitOrigin(r.subject,null))}_emitOrigin(e,i){this._ngZone.run(()=>e.next(i))}_registerGlobalListeners(e){if(!this._platform.isBrowser)return;const i=e.rootNode,r=this._rootNodeFocusListenerCount.get(i)||0;r||this._ngZone.runOutsideAngular(()=>{i.addEventListener(\"focus\",this._rootNodeFocusAndBlurListener,Bd),i.addEventListener(\"blur\",this._rootNodeFocusAndBlurListener,Bd)}),this._rootNodeFocusListenerCount.set(i,r+1),1==++this._monitoredElementCount&&(this._ngZone.runOutsideAngular(()=>{this._getWindow().addEventListener(\"focus\",this._windowFocusListener)}),this._inputModalityDetector.modalityDetected.pipe(Ie(this._stopInputModalityDetector)).subscribe(s=>{this._setOrigin(s,!0)}))}_removeGlobalListeners(e){const i=e.rootNode;if(this._rootNodeFocusListenerCount.has(i)){const r=this._rootNodeFocusListenerCount.get(i);r>1?this._rootNodeFocusListenerCount.set(i,r-1):(i.removeEventListener(\"focus\",this._rootNodeFocusAndBlurListener,Bd),i.removeEventListener(\"blur\",this._rootNodeFocusAndBlurListener,Bd),this._rootNodeFocusListenerCount.delete(i))}--this._monitoredElementCount||(this._getWindow().removeEventListener(\"focus\",this._windowFocusListener),this._stopInputModalityDetector.next(),clearTimeout(this._windowFocusTimeoutId),clearTimeout(this._originTimeoutId))}_originChanged(e,i,r){this._setClasses(e,i),this._emitOrigin(r.subject,i),this._lastFocusOrigin=i}_getClosestElementsInfo(e){const i=[];return this._elementInfo.forEach((r,s)=>{(s===e||r.checkChildren&&s.contains(e))&&i.push([s,r])}),i}}return n.\\u0275fac=function(e){return new(e||n)(y(ne),y(It),y(M3),y(ie,8),y(T3,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const nE=\"cdk-high-contrast-black-on-white\",iE=\"cdk-high-contrast-white-on-black\",Xm=\"cdk-high-contrast-active\";let rE=(()=>{class n{constructor(e,i){this._platform=e,this._document=i}getHighContrastMode(){if(!this._platform.isBrowser)return 0;const e=this._document.createElement(\"div\");e.style.backgroundColor=\"rgb(1,2,3)\",e.style.position=\"absolute\",this._document.body.appendChild(e);const i=this._document.defaultView||window,r=i&&i.getComputedStyle?i.getComputedStyle(e):null,s=(r&&r.backgroundColor||\"\").replace(/ /g,\"\");switch(e.remove(),s){case\"rgb(0,0,0)\":return 2;case\"rgb(255,255,255)\":return 1}return 0}_applyBodyHighContrastModeCssClasses(){if(!this._hasCheckedHighContrastMode&&this._platform.isBrowser&&this._document.body){const e=this._document.body.classList;e.remove(Xm),e.remove(nE),e.remove(iE),this._hasCheckedHighContrastMode=!0;const i=this.getHighContrastMode();1===i?(e.add(Xm),e.add(nE)):2===i&&(e.add(Xm),e.add(iE))}}}return n.\\u0275fac=function(e){return new(e||n)(y(It),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),Qa=(()=>{class n{constructor(e){e._applyBodyHighContrastModeCssClasses()}}return n.\\u0275fac=function(e){return new(e||n)(y(rE))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Ya]]}),n})();const A3=[\"*\",[[\"mat-option\"],[\"ng-container\"]]],I3=[\"*\",\"mat-option, ng-container\"];function R3(n,t){if(1&n&&Le(0,\"mat-pseudo-checkbox\",4),2&n){const e=Be();N(\"state\",e.selected?\"checked\":\"unchecked\")(\"disabled\",e.disabled)}}function O3(n,t){if(1&n&&(x(0,\"span\",5),we(1),S()),2&n){const e=Be();T(1),qn(\"(\",e.group.label,\")\")}}const P3=[\"*\"],Jm=new Rr(\"13.3.0\"),N3=new b(\"mat-sanity-checks\",{providedIn:\"root\",factory:function F3(){return!0}});let B=(()=>{class n{constructor(e,i,r){this._sanityChecks=i,this._document=r,this._hasDoneGlobalChecks=!1,e._applyBodyHighContrastModeCssClasses(),this._hasDoneGlobalChecks||(this._hasDoneGlobalChecks=!0)}_checkIsEnabled(e){return!jm()&&(\"boolean\"==typeof this._sanityChecks?this._sanityChecks:!!this._sanityChecks[e])}}return n.\\u0275fac=function(e){return new(e||n)(y(rE),y(N3,8),y(ie))},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[lo],lo]}),n})();function po(n){return class extends n{constructor(...t){super(...t),this._disabled=!1}get disabled(){return this._disabled}set disabled(t){this._disabled=G(t)}}}function fo(n,t){return class extends n{constructor(...e){super(...e),this.defaultColor=t,this.color=t}get color(){return this._color}set color(e){const i=e||this.defaultColor;i!==this._color&&(this._color&&this._elementRef.nativeElement.classList.remove(`mat-${this._color}`),i&&this._elementRef.nativeElement.classList.add(`mat-${i}`),this._color=i)}}}function ar(n){return class extends n{constructor(...t){super(...t),this._disableRipple=!1}get disableRipple(){return this._disableRipple}set disableRipple(t){this._disableRipple=G(t)}}}function Kr(n,t=0){return class extends n{constructor(...e){super(...e),this._tabIndex=t,this.defaultTabIndex=t}get tabIndex(){return this.disabled?-1:this._tabIndex}set tabIndex(e){this._tabIndex=null!=e?Et(e):this.defaultTabIndex}}}function ng(n){return class extends n{constructor(...t){super(...t),this.stateChanges=new O,this.errorState=!1}updateErrorState(){const t=this.errorState,s=(this.errorStateMatcher||this._defaultErrorStateMatcher).isErrorState(this.ngControl?this.ngControl.control:null,this._parentFormGroup||this._parentForm);s!==t&&(this.errorState=s,this.stateChanges.next())}}}const L3=new b(\"MAT_DATE_LOCALE\",{providedIn:\"root\",factory:function B3(){return Uo(Oi)}});class bi{constructor(){this._localeChanges=new O,this.localeChanges=this._localeChanges}getValidDateOrNull(t){return this.isDateInstance(t)&&this.isValid(t)?t:null}deserialize(t){return null==t||this.isDateInstance(t)&&this.isValid(t)?t:this.invalid()}setLocale(t){this.locale=t,this._localeChanges.next()}compareDate(t,e){return this.getYear(t)-this.getYear(e)||this.getMonth(t)-this.getMonth(e)||this.getDate(t)-this.getDate(e)}sameDate(t,e){if(t&&e){let i=this.isValid(t),r=this.isValid(e);return i&&r?!this.compareDate(t,e):i==r}return t==e}clampDate(t,e,i){return e&&this.compareDate(t,e)<0?e:i&&this.compareDate(t,i)>0?i:t}}const ig=new b(\"mat-date-formats\"),V3=/^\\d{4}-\\d{2}-\\d{2}(?:T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|(?:(?:\\+|-)\\d{2}:\\d{2}))?)?$/;function rg(n,t){const e=Array(n);for(let i=0;i<n;i++)e[i]=t(i);return e}let H3=(()=>{class n extends bi{constructor(e,i){super(),this.useUtcForDisplay=!1,super.setLocale(e)}getYear(e){return e.getFullYear()}getMonth(e){return e.getMonth()}getDate(e){return e.getDate()}getDayOfWeek(e){return e.getDay()}getMonthNames(e){const i=new Intl.DateTimeFormat(this.locale,{month:e,timeZone:\"utc\"});return rg(12,r=>this._format(i,new Date(2017,r,1)))}getDateNames(){const e=new Intl.DateTimeFormat(this.locale,{day:\"numeric\",timeZone:\"utc\"});return rg(31,i=>this._format(e,new Date(2017,0,i+1)))}getDayOfWeekNames(e){const i=new Intl.DateTimeFormat(this.locale,{weekday:e,timeZone:\"utc\"});return rg(7,r=>this._format(i,new Date(2017,0,r+1)))}getYearName(e){const i=new Intl.DateTimeFormat(this.locale,{year:\"numeric\",timeZone:\"utc\"});return this._format(i,e)}getFirstDayOfWeek(){return 0}getNumDaysInMonth(e){return this.getDate(this._createDateWithOverflow(this.getYear(e),this.getMonth(e)+1,0))}clone(e){return new Date(e.getTime())}createDate(e,i,r){let s=this._createDateWithOverflow(e,i,r);return s.getMonth(),s}today(){return new Date}parse(e){return\"number\"==typeof e?new Date(e):e?new Date(Date.parse(e)):null}format(e,i){if(!this.isValid(e))throw Error(\"NativeDateAdapter: Cannot format invalid date.\");const r=new Intl.DateTimeFormat(this.locale,Object.assign(Object.assign({},i),{timeZone:\"utc\"}));return this._format(r,e)}addCalendarYears(e,i){return this.addCalendarMonths(e,12*i)}addCalendarMonths(e,i){let r=this._createDateWithOverflow(this.getYear(e),this.getMonth(e)+i,this.getDate(e));return this.getMonth(r)!=((this.getMonth(e)+i)%12+12)%12&&(r=this._createDateWithOverflow(this.getYear(r),this.getMonth(r),0)),r}addCalendarDays(e,i){return this._createDateWithOverflow(this.getYear(e),this.getMonth(e),this.getDate(e)+i)}toIso8601(e){return[e.getUTCFullYear(),this._2digit(e.getUTCMonth()+1),this._2digit(e.getUTCDate())].join(\"-\")}deserialize(e){if(\"string\"==typeof e){if(!e)return null;if(V3.test(e)){let i=new Date(e);if(this.isValid(i))return i}}return super.deserialize(e)}isDateInstance(e){return e instanceof Date}isValid(e){return!isNaN(e.getTime())}invalid(){return new Date(NaN)}_createDateWithOverflow(e,i,r){const s=new Date;return s.setFullYear(e,i,r),s.setHours(0,0,0,0),s}_2digit(e){return(\"00\"+e).slice(-2)}_format(e,i){const r=new Date;return r.setUTCFullYear(i.getFullYear(),i.getMonth(),i.getDate()),r.setUTCHours(i.getHours(),i.getMinutes(),i.getSeconds(),i.getMilliseconds()),e.format(r)}}return n.\\u0275fac=function(e){return new(e||n)(y(L3,8),y(It))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const j3={parse:{dateInput:null},display:{dateInput:{year:\"numeric\",month:\"numeric\",day:\"numeric\"},monthYearLabel:{year:\"numeric\",month:\"short\"},dateA11yLabel:{year:\"numeric\",month:\"long\",day:\"numeric\"},monthYearA11yLabel:{year:\"numeric\",month:\"long\"}}};let z3=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[{provide:bi,useClass:H3}]}),n})(),U3=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[{provide:ig,useValue:j3}],imports:[[z3]]}),n})(),mo=(()=>{class n{isErrorState(e,i){return!!(e&&e.invalid&&(e.touched||i&&i.submitted))}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),Vd=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})();class W3{constructor(t,e,i){this._renderer=t,this.element=e,this.config=i,this.state=3}fadeOut(){this._renderer.fadeOutRipple(this)}}const sE={enterDuration:225,exitDuration:150},sg=ei({passive:!0}),oE=[\"mousedown\",\"touchstart\"],aE=[\"mouseup\",\"mouseleave\",\"touchend\",\"touchcancel\"];class lE{constructor(t,e,i,r){this._target=t,this._ngZone=e,this._isPointerDown=!1,this._activeRipples=new Set,this._pointerUpEventsRegistered=!1,r.isBrowser&&(this._containerElement=at(i))}fadeInRipple(t,e,i={}){const r=this._containerRect=this._containerRect||this._containerElement.getBoundingClientRect(),s=Object.assign(Object.assign({},sE),i.animation);i.centered&&(t=r.left+r.width/2,e=r.top+r.height/2);const o=i.radius||function Q3(n,t,e){const i=Math.max(Math.abs(n-e.left),Math.abs(n-e.right)),r=Math.max(Math.abs(t-e.top),Math.abs(t-e.bottom));return Math.sqrt(i*i+r*r)}(t,e,r),a=t-r.left,l=e-r.top,c=s.enterDuration,d=document.createElement(\"div\");d.classList.add(\"mat-ripple-element\"),d.style.left=a-o+\"px\",d.style.top=l-o+\"px\",d.style.height=2*o+\"px\",d.style.width=2*o+\"px\",null!=i.color&&(d.style.backgroundColor=i.color),d.style.transitionDuration=`${c}ms`,this._containerElement.appendChild(d),function Y3(n){window.getComputedStyle(n).getPropertyValue(\"opacity\")}(d),d.style.transform=\"scale(1)\";const u=new W3(this,d,i);return u.state=0,this._activeRipples.add(u),i.persistent||(this._mostRecentTransientRipple=u),this._runTimeoutOutsideZone(()=>{const h=u===this._mostRecentTransientRipple;u.state=1,!i.persistent&&(!h||!this._isPointerDown)&&u.fadeOut()},c),u}fadeOutRipple(t){const e=this._activeRipples.delete(t);if(t===this._mostRecentTransientRipple&&(this._mostRecentTransientRipple=null),this._activeRipples.size||(this._containerRect=null),!e)return;const i=t.element,r=Object.assign(Object.assign({},sE),t.config.animation);i.style.transitionDuration=`${r.exitDuration}ms`,i.style.opacity=\"0\",t.state=2,this._runTimeoutOutsideZone(()=>{t.state=3,i.remove()},r.exitDuration)}fadeOutAll(){this._activeRipples.forEach(t=>t.fadeOut())}fadeOutAllNonPersistent(){this._activeRipples.forEach(t=>{t.config.persistent||t.fadeOut()})}setupTriggerEvents(t){const e=at(t);!e||e===this._triggerElement||(this._removeTriggerEvents(),this._triggerElement=e,this._registerEvents(oE))}handleEvent(t){\"mousedown\"===t.type?this._onMousedown(t):\"touchstart\"===t.type?this._onTouchStart(t):this._onPointerUp(),this._pointerUpEventsRegistered||(this._registerEvents(aE),this._pointerUpEventsRegistered=!0)}_onMousedown(t){const e=Km(t),i=this._lastTouchStartEvent&&Date.now()<this._lastTouchStartEvent+800;!this._target.rippleDisabled&&!e&&!i&&(this._isPointerDown=!0,this.fadeInRipple(t.clientX,t.clientY,this._target.rippleConfig))}_onTouchStart(t){if(!this._target.rippleDisabled&&!Zm(t)){this._lastTouchStartEvent=Date.now(),this._isPointerDown=!0;const e=t.changedTouches;for(let i=0;i<e.length;i++)this.fadeInRipple(e[i].clientX,e[i].clientY,this._target.rippleConfig)}}_onPointerUp(){!this._isPointerDown||(this._isPointerDown=!1,this._activeRipples.forEach(t=>{!t.config.persistent&&(1===t.state||t.config.terminateOnPointerUp&&0===t.state)&&t.fadeOut()}))}_runTimeoutOutsideZone(t,e=0){this._ngZone.runOutsideAngular(()=>setTimeout(t,e))}_registerEvents(t){this._ngZone.runOutsideAngular(()=>{t.forEach(e=>{this._triggerElement.addEventListener(e,this,sg)})})}_removeTriggerEvents(){this._triggerElement&&(oE.forEach(t=>{this._triggerElement.removeEventListener(t,this,sg)}),this._pointerUpEventsRegistered&&aE.forEach(t=>{this._triggerElement.removeEventListener(t,this,sg)}))}}const cE=new b(\"mat-ripple-global-options\");let Zr=(()=>{class n{constructor(e,i,r,s,o){this._elementRef=e,this._animationMode=o,this.radius=0,this._disabled=!1,this._isInitialized=!1,this._globalOptions=s||{},this._rippleRenderer=new lE(this,i,e,r)}get disabled(){return this._disabled}set disabled(e){e&&this.fadeOutAllNonPersistent(),this._disabled=e,this._setupTriggerEventsIfEnabled()}get trigger(){return this._trigger||this._elementRef.nativeElement}set trigger(e){this._trigger=e,this._setupTriggerEventsIfEnabled()}ngOnInit(){this._isInitialized=!0,this._setupTriggerEventsIfEnabled()}ngOnDestroy(){this._rippleRenderer._removeTriggerEvents()}fadeOutAll(){this._rippleRenderer.fadeOutAll()}fadeOutAllNonPersistent(){this._rippleRenderer.fadeOutAllNonPersistent()}get rippleConfig(){return{centered:this.centered,radius:this.radius,color:this.color,animation:Object.assign(Object.assign(Object.assign({},this._globalOptions.animation),\"NoopAnimations\"===this._animationMode?{enterDuration:0,exitDuration:0}:{}),this.animation),terminateOnPointerUp:this._globalOptions.terminateOnPointerUp}}get rippleDisabled(){return this.disabled||!!this._globalOptions.disabled}_setupTriggerEventsIfEnabled(){!this.disabled&&this._isInitialized&&this._rippleRenderer.setupTriggerEvents(this.trigger)}launch(e,i=0,r){return\"number\"==typeof e?this._rippleRenderer.fadeInRipple(e,i,Object.assign(Object.assign({},this.rippleConfig),r)):this._rippleRenderer.fadeInRipple(0,0,Object.assign(Object.assign({},this.rippleConfig),e))}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(ne),f(It),f(cE,8),f(Rn,8))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"mat-ripple\",\"\"],[\"\",\"matRipple\",\"\"]],hostAttrs:[1,\"mat-ripple\"],hostVars:2,hostBindings:function(e,i){2&e&&Ae(\"mat-ripple-unbounded\",i.unbounded)},inputs:{color:[\"matRippleColor\",\"color\"],unbounded:[\"matRippleUnbounded\",\"unbounded\"],centered:[\"matRippleCentered\",\"centered\"],radius:[\"matRippleRadius\",\"radius\"],animation:[\"matRippleAnimation\",\"animation\"],disabled:[\"matRippleDisabled\",\"disabled\"],trigger:[\"matRippleTrigger\",\"trigger\"]},exportAs:[\"matRipple\"]}),n})(),ti=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),dE=(()=>{class n{constructor(e){this._animationMode=e,this.state=\"unchecked\",this.disabled=!1}}return n.\\u0275fac=function(e){return new(e||n)(f(Rn,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-pseudo-checkbox\"]],hostAttrs:[1,\"mat-pseudo-checkbox\"],hostVars:8,hostBindings:function(e,i){2&e&&Ae(\"mat-pseudo-checkbox-indeterminate\",\"indeterminate\"===i.state)(\"mat-pseudo-checkbox-checked\",\"checked\"===i.state)(\"mat-pseudo-checkbox-disabled\",i.disabled)(\"_mat-animation-noopable\",\"NoopAnimations\"===i._animationMode)},inputs:{state:\"state\",disabled:\"disabled\"},decls:0,vars:0,template:function(e,i){},styles:['.mat-pseudo-checkbox{width:16px;height:16px;border:2px solid;border-radius:2px;cursor:pointer;display:inline-block;vertical-align:middle;box-sizing:border-box;position:relative;flex-shrink:0;transition:border-color 90ms cubic-bezier(0, 0, 0.2, 0.1),background-color 90ms cubic-bezier(0, 0, 0.2, 0.1)}.mat-pseudo-checkbox::after{position:absolute;opacity:0;content:\"\";border-bottom:2px solid currentColor;transition:opacity 90ms cubic-bezier(0, 0, 0.2, 0.1)}.mat-pseudo-checkbox.mat-pseudo-checkbox-checked,.mat-pseudo-checkbox.mat-pseudo-checkbox-indeterminate{border-color:transparent}._mat-animation-noopable.mat-pseudo-checkbox{transition:none;animation:none}._mat-animation-noopable.mat-pseudo-checkbox::after{transition:none}.mat-pseudo-checkbox-disabled{cursor:default}.mat-pseudo-checkbox-indeterminate::after{top:5px;left:1px;width:10px;opacity:1;border-radius:2px}.mat-pseudo-checkbox-checked::after{top:2.4px;left:1px;width:8px;height:3px;border-left:2px solid currentColor;transform:rotate(-45deg);opacity:1;box-sizing:content-box}\\n'],encapsulation:2,changeDetection:0}),n})(),og=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B]]}),n})();const ag=new b(\"MAT_OPTION_PARENT_COMPONENT\"),K3=po(class{});let Z3=0,X3=(()=>{class n extends K3{constructor(e){var i;super(),this._labelId=\"mat-optgroup-label-\"+Z3++,this._inert=null!==(i=null==e?void 0:e.inertGroups)&&void 0!==i&&i}}return n.\\u0275fac=function(e){return new(e||n)(f(ag,8))},n.\\u0275dir=C({type:n,inputs:{label:\"label\"},features:[E]}),n})();const lg=new b(\"MatOptgroup\");let J3=(()=>{class n extends X3{}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275cmp=xe({type:n,selectors:[[\"mat-optgroup\"]],hostAttrs:[1,\"mat-optgroup\"],hostVars:5,hostBindings:function(e,i){2&e&&(Z(\"role\",i._inert?null:\"group\")(\"aria-disabled\",i._inert?null:i.disabled.toString())(\"aria-labelledby\",i._inert?null:i._labelId),Ae(\"mat-optgroup-disabled\",i.disabled))},inputs:{disabled:\"disabled\"},exportAs:[\"matOptgroup\"],features:[L([{provide:lg,useExisting:n}]),E],ngContentSelectors:I3,decls:4,vars:2,consts:[[\"aria-hidden\",\"true\",1,\"mat-optgroup-label\",3,\"id\"]],template:function(e,i){1&e&&(Lt(A3),x(0,\"span\",0),we(1),Pe(2),S(),Pe(3,1)),2&e&&(N(\"id\",i._labelId),T(1),qn(\"\",i.label,\" \"))},styles:[\".mat-optgroup-label{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;line-height:48px;height:48px;padding:0 16px;text-align:left;text-decoration:none;max-width:100%;-webkit-user-select:none;-moz-user-select:none;user-select:none;cursor:default}.mat-optgroup-label[disabled]{cursor:default}[dir=rtl] .mat-optgroup-label{text-align:right}.mat-optgroup-label .mat-icon{margin-right:16px;vertical-align:middle}.mat-optgroup-label .mat-icon svg{vertical-align:top}[dir=rtl] .mat-optgroup-label .mat-icon{margin-left:16px;margin-right:0}\\n\"],encapsulation:2,changeDetection:0}),n})(),eU=0;class uE{constructor(t,e=!1){this.source=t,this.isUserInput=e}}let tU=(()=>{class n{constructor(e,i,r,s){this._element=e,this._changeDetectorRef=i,this._parent=r,this.group=s,this._selected=!1,this._active=!1,this._disabled=!1,this._mostRecentViewValue=\"\",this.id=\"mat-option-\"+eU++,this.onSelectionChange=new $,this._stateChanges=new O}get multiple(){return this._parent&&this._parent.multiple}get selected(){return this._selected}get disabled(){return this.group&&this.group.disabled||this._disabled}set disabled(e){this._disabled=G(e)}get disableRipple(){return!(!this._parent||!this._parent.disableRipple)}get active(){return this._active}get viewValue(){return(this._getHostElement().textContent||\"\").trim()}select(){this._selected||(this._selected=!0,this._changeDetectorRef.markForCheck(),this._emitSelectionChangeEvent())}deselect(){this._selected&&(this._selected=!1,this._changeDetectorRef.markForCheck(),this._emitSelectionChangeEvent())}focus(e,i){const r=this._getHostElement();\"function\"==typeof r.focus&&r.focus(i)}setActiveStyles(){this._active||(this._active=!0,this._changeDetectorRef.markForCheck())}setInactiveStyles(){this._active&&(this._active=!1,this._changeDetectorRef.markForCheck())}getLabel(){return this.viewValue}_handleKeydown(e){(13===e.keyCode||32===e.keyCode)&&!Xt(e)&&(this._selectViaInteraction(),e.preventDefault())}_selectViaInteraction(){this.disabled||(this._selected=!this.multiple||!this._selected,this._changeDetectorRef.markForCheck(),this._emitSelectionChangeEvent(!0))}_getAriaSelected(){return this.selected||!this.multiple&&null}_getTabIndex(){return this.disabled?\"-1\":\"0\"}_getHostElement(){return this._element.nativeElement}ngAfterViewChecked(){if(this._selected){const e=this.viewValue;e!==this._mostRecentViewValue&&(this._mostRecentViewValue=e,this._stateChanges.next())}}ngOnDestroy(){this._stateChanges.complete()}_emitSelectionChangeEvent(e=!1){this.onSelectionChange.emit(new uE(this,e))}}return n.\\u0275fac=function(e){Sr()},n.\\u0275dir=C({type:n,inputs:{value:\"value\",id:\"id\",disabled:\"disabled\"},outputs:{onSelectionChange:\"onSelectionChange\"}}),n})(),hE=(()=>{class n extends tU{constructor(e,i,r,s){super(e,i,r,s)}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(Ye),f(ag,8),f(lg,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-option\"]],hostAttrs:[\"role\",\"option\",1,\"mat-option\",\"mat-focus-indicator\"],hostVars:12,hostBindings:function(e,i){1&e&&J(\"click\",function(){return i._selectViaInteraction()})(\"keydown\",function(s){return i._handleKeydown(s)}),2&e&&(Yn(\"id\",i.id),Z(\"tabindex\",i._getTabIndex())(\"aria-selected\",i._getAriaSelected())(\"aria-disabled\",i.disabled.toString()),Ae(\"mat-selected\",i.selected)(\"mat-option-multiple\",i.multiple)(\"mat-active\",i.active)(\"mat-option-disabled\",i.disabled))},exportAs:[\"matOption\"],features:[E],ngContentSelectors:P3,decls:5,vars:4,consts:[[\"class\",\"mat-option-pseudo-checkbox\",3,\"state\",\"disabled\",4,\"ngIf\"],[1,\"mat-option-text\"],[\"class\",\"cdk-visually-hidden\",4,\"ngIf\"],[\"mat-ripple\",\"\",1,\"mat-option-ripple\",3,\"matRippleTrigger\",\"matRippleDisabled\"],[1,\"mat-option-pseudo-checkbox\",3,\"state\",\"disabled\"],[1,\"cdk-visually-hidden\"]],template:function(e,i){1&e&&(Lt(),Ee(0,R3,1,2,\"mat-pseudo-checkbox\",0),x(1,\"span\",1),Pe(2),S(),Ee(3,O3,2,1,\"span\",2),Le(4,\"div\",3)),2&e&&(N(\"ngIf\",i.multiple),T(3),N(\"ngIf\",i.group&&i.group._inert),T(1),N(\"matRippleTrigger\",i._getHostElement())(\"matRippleDisabled\",i.disabled||i.disableRipple))},directives:[dE,Ca,Zr],styles:[\".mat-option{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;line-height:48px;height:48px;padding:0 16px;text-align:left;text-decoration:none;max-width:100%;position:relative;cursor:pointer;outline:none;display:flex;flex-direction:row;max-width:100%;box-sizing:border-box;align-items:center;-webkit-tap-highlight-color:transparent}.mat-option[disabled]{cursor:default}[dir=rtl] .mat-option{text-align:right}.mat-option .mat-icon{margin-right:16px;vertical-align:middle}.mat-option .mat-icon svg{vertical-align:top}[dir=rtl] .mat-option .mat-icon{margin-left:16px;margin-right:0}.mat-option[aria-disabled=true]{-webkit-user-select:none;-moz-user-select:none;user-select:none;cursor:default}.mat-optgroup .mat-option:not(.mat-option-multiple){padding-left:32px}[dir=rtl] .mat-optgroup .mat-option:not(.mat-option-multiple){padding-left:16px;padding-right:32px}.cdk-high-contrast-active .mat-option{margin:0 1px}.cdk-high-contrast-active .mat-option.mat-active{border:solid 1px currentColor;margin:0}.cdk-high-contrast-active .mat-option[aria-disabled=true]{opacity:.5}.mat-option-text{display:inline-block;flex-grow:1;overflow:hidden;text-overflow:ellipsis}.mat-option .mat-option-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-option-pseudo-checkbox{margin-right:8px}[dir=rtl] .mat-option-pseudo-checkbox{margin-left:8px;margin-right:0}\\n\"],encapsulation:2,changeDetection:0}),n})();function cg(n,t,e){if(e.length){let i=t.toArray(),r=e.toArray(),s=0;for(let o=0;o<n+1;o++)i[o].group&&i[o].group===r[s]&&s++;return s}return 0}let Hd=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ti,bt,B,og]]}),n})(),gE=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B],B]}),n})();const Xa=JSON.parse('[{\"from\":{\"name\":\"Everscale\",\"description\":\"Everscale mainnet\",\"url\":\"https://main.ton.dev\"},\"to\":{\"name\":\"Tezos\",\"description\":\"Tezos mainnet\",\"url\":\"https://tzkt.io\"},\"active\":true},{\"from\":{\"name\":\"Tezos\",\"description\":\"Tezos mainnet\",\"url\":\"https://tzkt.io\"},\"to\":{\"name\":\"Everscale\",\"description\":\"Everscale mainnet\",\"url\":\"https://main.ton.dev\"},\"active\":true},{\"from\":{\"name\":\"devnet\",\"description\":\"Everscale devnet\",\"url\":\"https://net.ton.dev\"},\"to\":{\"name\":\"hangzhounet\",\"description\":\"Tezos hangzhounet\",\"url\":\"https://hangzhounet.tzkt.io\"},\"active\":false},{\"from\":{\"name\":\"hangzhounet\",\"description\":\"Tezos hangzhounet\",\"url\":\"https://hangzhounet.tzkt.io\"},\"to\":{\"name\":\"devnet\",\"description\":\"Everscale devnet\",\"url\":\"https://net.ton.dev\"},\"active\":false},{\"from\":{\"name\":\"fld.ton.dev\",\"description\":\"Everscale fld\",\"url\":\"https://gql.custler.net\"},\"to\":{\"name\":\"ithacanet\",\"description\":\"Tezos ithacanet\",\"url\":\"https://ithacanet.tzkt.io\"},\"active\":false},{\"from\":{\"name\":\"ithacanet\",\"description\":\"Tezos ithacanet\",\"url\":\"https://ithacanet.tzkt.io\"},\"to\":{\"name\":\"fld.ton.dev\",\"description\":\"Everscale fld\",\"url\":\"https://gql.custler.net\"},\"active\":false}]'),ug=JSON.parse('[{\"name\":\"wTXZ\",\"type\":\"TIP-3.1\",\"desc\":\"Wrapped Tezos\"},{\"name\":\"SOON\",\"type\":\"TIP-3\",\"desc\":\"Soon\"},{\"name\":\"BRIDGE\",\"type\":\"TIP-3.1\",\"desc\":\"Bridge token\"}]'),hg=JSON.parse('[{\"name\":\"wEVER\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped EVER\"},{\"name\":\"KUSD\",\"type\":\"FA 1.2\",\"desc\":\"Kolibri\"},{\"name\":\"wXTZ\",\"type\":\"FA 1.2\",\"desc\":\"Wrapped Tezos\"},{\"name\":\"USDS\",\"type\":\"FA 2.0\",\"desc\":\"Stably USD\"},{\"name\":\"tzBTC\",\"type\":\"FA 1.2\",\"desc\":\"tzBTC\"},{\"name\":\"STKR\",\"type\":\"FA 1.2\",\"desc\":\"Staker Governance\"},{\"name\":\"USDtz\",\"type\":\"FA 1.2\",\"desc\":\"USDtez\"},{\"name\":\"ETHtz\",\"type\":\"FA 1.2\",\"desc\":\"ETHtez\"},{\"name\":\"hDAO\",\"type\":\"FA 2.0\",\"desc\":\"Hic Et Nunc governance\"},{\"name\":\"WRAP\",\"type\":\"FA 2.0\",\"desc\":\"Wrap Governance\"},{\"name\":\"CRUNCH\",\"type\":\"FA 2.0\",\"desc\":\"CRUNCH\"},{\"name\":\"wAAVE\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped AAVE\"},{\"name\":\"wBUSD\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped BUSD\"},{\"name\":\"wCEL\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped CEL\"},{\"name\":\"wCOMP\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped COMP\"},{\"name\":\"wCRO\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped CRO\"},{\"name\":\"wDAI\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped DAI\"},{\"name\":\"wFTT\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped FTT\"},{\"name\":\"wHT\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped HT\"},{\"name\":\"wHUSD\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped HUSD\"},{\"name\":\"wLEO\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped LEO\"},{\"name\":\"wLINK\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped LINK\"},{\"name\":\"wMATIC\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped MATIC\"},{\"name\":\"wMKR\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped MKR\"},{\"name\":\"wOKB\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped OKB\"},{\"name\":\"wPAX\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped PAX\"},{\"name\":\"wSUSHI\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped SUSHI\"},{\"name\":\"wUNI\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped UNI\"},{\"name\":\"wUSDC\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped USDC\"},{\"name\":\"wUSDT\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped USDT\"},{\"name\":\"wWBTC\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped WBTC\"},{\"name\":\"wWETH\",\"type\":\"FA 2.0\",\"desc\":\"Wrapped WETH\"},{\"name\":\"PLENTY\",\"type\":\"FA 1.2\",\"desc\":\"Plenty DAO\"},{\"name\":\"KALAM\",\"type\":\"FA 2.0\",\"desc\":\"Kalamint\"},{\"name\":\"crDAO\",\"type\":\"FA 2.0\",\"desc\":\"Crunchy DAO\"},{\"name\":\"SMAK\",\"type\":\"FA 1.2\",\"desc\":\"SmartLink\"},{\"name\":\"kDAO\",\"type\":\"FA 1.2\",\"desc\":\"Kolibri DAO\"},{\"name\":\"uUSD\",\"type\":\"FA 2.0\",\"desc\":\"youves uUSD\"},{\"name\":\"uDEFI\",\"type\":\"FA 2.0\",\"desc\":\"youves uDEFI\"},{\"name\":\"bDAO\",\"type\":\"FA 2.0\",\"desc\":\"Bazaar DAO\"},{\"name\":\"YOU\",\"type\":\"FA 2.0\",\"desc\":\"youves YOU governance\"},{\"name\":\"RCKT\",\"type\":\"FA 2.0\",\"desc\":\"Rocket\"},{\"name\":\"rkDAO\",\"type\":\"FA 2.0\",\"desc\":\"Rocket DAO\"},{\"name\":\"UNO\",\"type\":\"FA 2.0\",\"desc\":\"Unobtanium\"},{\"name\":\"GIF\",\"type\":\"FA 2.0\",\"desc\":\"GIF DAO\"},{\"name\":\"IDZ\",\"type\":\"FA 2.0\",\"desc\":\"TezID\"},{\"name\":\"EASY\",\"type\":\"FA 2.0\",\"desc\":\"CryptoEasy\"},{\"name\":\"INSTA\",\"type\":\"FA 2.0\",\"desc\":\"Instaraise\"},{\"name\":\"xPLENTY\",\"type\":\"FA 1.2\",\"desc\":\"xPLENTY\"},{\"name\":\"ctez\",\"type\":\"FA 1.2\",\"desc\":\"Ctez\"},{\"name\":\"PAUL\",\"type\":\"FA 1.2\",\"desc\":\"PAUL Token\"},{\"name\":\"SPI\",\"type\":\"FA 2.0\",\"desc\":\"Spice Token\"},{\"name\":\"WTZ\",\"type\":\"FA 2.0\",\"desc\":\"WTZ\"},{\"name\":\"FLAME\",\"type\":\"FA 2.0\",\"desc\":\"FLAME\"},{\"name\":\"fDAO\",\"type\":\"FA 2.0\",\"desc\":\"fDAO\"},{\"name\":\"PXL\",\"type\":\"FA 2.0\",\"desc\":\"Pixel\"},{\"name\":\"sDAO\",\"type\":\"FA 2.0\",\"desc\":\"Salsa DAO\"},{\"name\":\"akaDAO\",\"type\":\"FA 2.0\",\"desc\":\"akaSwap DAO\"},{\"name\":\"MIN\",\"type\":\"FA 2.0\",\"desc\":\"Minerals\"},{\"name\":\"ENR\",\"type\":\"FA 2.0\",\"desc\":\"Energy\"},{\"name\":\"MCH\",\"type\":\"FA 2.0\",\"desc\":\"Machinery\"},{\"name\":\"uBTC\",\"type\":\"FA 2.0\",\"desc\":\"youves uBTC\"},{\"name\":\"MTRIA\",\"type\":\"FA 2.0\",\"desc\":\"Materia\"},{\"name\":\"DOGA\",\"type\":\"FA 1.2\",\"desc\":\"DOGAMI\"}]'),_E=[\"*\"];class pU{constructor(){this.columnIndex=0,this.rowIndex=0}get rowCount(){return this.rowIndex+1}get rowspan(){const t=Math.max(...this.tracker);return t>1?this.rowCount+t-1:this.rowCount}update(t,e){this.columnIndex=0,this.rowIndex=0,this.tracker=new Array(t),this.tracker.fill(0,0,this.tracker.length),this.positions=e.map(i=>this._trackTile(i))}_trackTile(t){const e=this._findMatchingGap(t.colspan);return this._markTilePosition(e,t),this.columnIndex=e+t.colspan,new fU(this.rowIndex,e)}_findMatchingGap(t){let e=-1,i=-1;do{this.columnIndex+t>this.tracker.length?(this._nextRow(),e=this.tracker.indexOf(0,this.columnIndex),i=this._findGapEndIndex(e)):(e=this.tracker.indexOf(0,this.columnIndex),-1!=e?(i=this._findGapEndIndex(e),this.columnIndex=e+1):(this._nextRow(),e=this.tracker.indexOf(0,this.columnIndex),i=this._findGapEndIndex(e)))}while(i-e<t||0==i);return Math.max(e,0)}_nextRow(){this.columnIndex=0,this.rowIndex++;for(let t=0;t<this.tracker.length;t++)this.tracker[t]=Math.max(0,this.tracker[t]-1)}_findGapEndIndex(t){for(let e=t+1;e<this.tracker.length;e++)if(0!=this.tracker[e])return e;return this.tracker.length}_markTilePosition(t,e){for(let i=0;i<e.colspan;i++)this.tracker[t+i]=e.rowspan}}class fU{constructor(t,e){this.row=t,this.col=e}}const vE=new b(\"MAT_GRID_LIST\");let yE=(()=>{class n{constructor(e,i){this._element=e,this._gridList=i,this._rowspan=1,this._colspan=1}get rowspan(){return this._rowspan}set rowspan(e){this._rowspan=Math.round(Et(e))}get colspan(){return this._colspan}set colspan(e){this._colspan=Math.round(Et(e))}_setStyle(e,i){this._element.nativeElement.style[e]=i}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(vE,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-grid-tile\"]],hostAttrs:[1,\"mat-grid-tile\"],hostVars:2,hostBindings:function(e,i){2&e&&Z(\"rowspan\",i.rowspan)(\"colspan\",i.colspan)},inputs:{rowspan:\"rowspan\",colspan:\"colspan\"},exportAs:[\"matGridTile\"],ngContentSelectors:_E,decls:2,vars:0,consts:[[1,\"mat-grid-tile-content\"]],template:function(e,i){1&e&&(Lt(),x(0,\"div\",0),Pe(1),S())},styles:[\".mat-grid-list{display:block;position:relative}.mat-grid-tile{display:block;position:absolute;overflow:hidden}.mat-grid-tile .mat-grid-tile-header,.mat-grid-tile .mat-grid-tile-footer{display:flex;align-items:center;height:48px;color:#fff;background:rgba(0,0,0,.38);overflow:hidden;padding:0 16px;position:absolute;left:0;right:0}.mat-grid-tile .mat-grid-tile-header>*,.mat-grid-tile .mat-grid-tile-footer>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-grid-tile .mat-grid-tile-header.mat-2-line,.mat-grid-tile .mat-grid-tile-footer.mat-2-line{height:68px}.mat-grid-tile .mat-grid-list-text{display:flex;flex-direction:column;flex:auto;box-sizing:border-box;overflow:hidden}.mat-grid-tile .mat-grid-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-grid-tile .mat-grid-list-text:empty{display:none}.mat-grid-tile .mat-grid-tile-header{top:0}.mat-grid-tile .mat-grid-tile-footer{bottom:0}.mat-grid-tile .mat-grid-avatar{padding-right:16px}[dir=rtl] .mat-grid-tile .mat-grid-avatar{padding-right:0;padding-left:16px}.mat-grid-tile .mat-grid-avatar:empty{display:none}.mat-grid-tile-content{top:0;left:0;right:0;bottom:0;position:absolute;display:flex;align-items:center;justify-content:center;height:100%;padding:0;margin:0}\\n\"],encapsulation:2,changeDetection:0}),n})();const mU=/^-?\\d+((\\.\\d+)?[A-Za-z%$]?)+$/;class pg{constructor(){this._rows=0,this._rowspan=0}init(t,e,i,r){this._gutterSize=bE(t),this._rows=e.rowCount,this._rowspan=e.rowspan,this._cols=i,this._direction=r}getBaseTileSize(t,e){return`(${t}% - (${this._gutterSize} * ${e}))`}getTilePosition(t,e){return 0===e?\"0\":Xr(`(${t} + ${this._gutterSize}) * ${e}`)}getTileSize(t,e){return`(${t} * ${e}) + (${e-1} * ${this._gutterSize})`}setStyle(t,e,i){let r=100/this._cols,s=(this._cols-1)/this._cols;this.setColStyles(t,i,r,s),this.setRowStyles(t,e,r,s)}setColStyles(t,e,i,r){let s=this.getBaseTileSize(i,r);t._setStyle(\"rtl\"===this._direction?\"right\":\"left\",this.getTilePosition(s,e)),t._setStyle(\"width\",Xr(this.getTileSize(s,t.colspan)))}getGutterSpan(){return`${this._gutterSize} * (${this._rowspan} - 1)`}getTileSpan(t){return`${this._rowspan} * ${this.getTileSize(t,1)}`}getComputedHeight(){return null}}class gU extends pg{constructor(t){super(),this.fixedRowHeight=t}init(t,e,i,r){super.init(t,e,i,r),this.fixedRowHeight=bE(this.fixedRowHeight),mU.test(this.fixedRowHeight)}setRowStyles(t,e){t._setStyle(\"top\",this.getTilePosition(this.fixedRowHeight,e)),t._setStyle(\"height\",Xr(this.getTileSize(this.fixedRowHeight,t.rowspan)))}getComputedHeight(){return[\"height\",Xr(`${this.getTileSpan(this.fixedRowHeight)} + ${this.getGutterSpan()}`)]}reset(t){t._setListStyle([\"height\",null]),t._tiles&&t._tiles.forEach(e=>{e._setStyle(\"top\",null),e._setStyle(\"height\",null)})}}class _U extends pg{constructor(t){super(),this._parseRatio(t)}setRowStyles(t,e,i,r){this.baseTileHeight=this.getBaseTileSize(i/this.rowHeightRatio,r),t._setStyle(\"marginTop\",this.getTilePosition(this.baseTileHeight,e)),t._setStyle(\"paddingTop\",Xr(this.getTileSize(this.baseTileHeight,t.rowspan)))}getComputedHeight(){return[\"paddingBottom\",Xr(`${this.getTileSpan(this.baseTileHeight)} + ${this.getGutterSpan()}`)]}reset(t){t._setListStyle([\"paddingBottom\",null]),t._tiles.forEach(e=>{e._setStyle(\"marginTop\",null),e._setStyle(\"paddingTop\",null)})}_parseRatio(t){const e=t.split(\":\");this.rowHeightRatio=parseFloat(e[0])/parseFloat(e[1])}}class vU extends pg{setRowStyles(t,e){let s=this.getBaseTileSize(100/this._rowspan,(this._rows-1)/this._rows);t._setStyle(\"top\",this.getTilePosition(s,e)),t._setStyle(\"height\",Xr(this.getTileSize(s,t.rowspan)))}reset(t){t._tiles&&t._tiles.forEach(e=>{e._setStyle(\"top\",null),e._setStyle(\"height\",null)})}}function Xr(n){return`calc(${n})`}function bE(n){return n.match(/([A-Za-z%]+)$/)?n:`${n}px`}let bU=(()=>{class n{constructor(e,i){this._element=e,this._dir=i,this._gutter=\"1px\"}get cols(){return this._cols}set cols(e){this._cols=Math.max(1,Math.round(Et(e)))}get gutterSize(){return this._gutter}set gutterSize(e){this._gutter=`${null==e?\"\":e}`}get rowHeight(){return this._rowHeight}set rowHeight(e){const i=`${null==e?\"\":e}`;i!==this._rowHeight&&(this._rowHeight=i,this._setTileStyler(this._rowHeight))}ngOnInit(){this._checkCols(),this._checkRowHeight()}ngAfterContentChecked(){this._layoutTiles()}_checkCols(){}_checkRowHeight(){this._rowHeight||this._setTileStyler(\"1:1\")}_setTileStyler(e){this._tileStyler&&this._tileStyler.reset(this),this._tileStyler=\"fit\"===e?new vU:e&&e.indexOf(\":\")>-1?new _U(e):new gU(e)}_layoutTiles(){this._tileCoordinator||(this._tileCoordinator=new pU);const e=this._tileCoordinator,i=this._tiles.filter(s=>!s._gridList||s._gridList===this),r=this._dir?this._dir.value:\"ltr\";this._tileCoordinator.update(this.cols,i),this._tileStyler.init(this.gutterSize,e,this.cols,r),i.forEach((s,o)=>{const a=e.positions[o];this._tileStyler.setStyle(s,a.row,a.col)}),this._setListStyle(this._tileStyler.getComputedHeight())}_setListStyle(e){e&&(this._element.nativeElement.style[e[0]]=e[1])}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(On,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-grid-list\"]],contentQueries:function(e,i,r){if(1&e&&ve(r,yE,5),2&e){let s;z(s=U())&&(i._tiles=s)}},hostAttrs:[1,\"mat-grid-list\"],hostVars:1,hostBindings:function(e,i){2&e&&Z(\"cols\",i.cols)},inputs:{cols:\"cols\",gutterSize:\"gutterSize\",rowHeight:\"rowHeight\"},exportAs:[\"matGridList\"],features:[L([{provide:vE,useExisting:n}])],ngContentSelectors:_E,decls:2,vars:0,template:function(e,i){1&e&&(Lt(),x(0,\"div\"),Pe(1),S())},styles:[\".mat-grid-list{display:block;position:relative}.mat-grid-tile{display:block;position:absolute;overflow:hidden}.mat-grid-tile .mat-grid-tile-header,.mat-grid-tile .mat-grid-tile-footer{display:flex;align-items:center;height:48px;color:#fff;background:rgba(0,0,0,.38);overflow:hidden;padding:0 16px;position:absolute;left:0;right:0}.mat-grid-tile .mat-grid-tile-header>*,.mat-grid-tile .mat-grid-tile-footer>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-grid-tile .mat-grid-tile-header.mat-2-line,.mat-grid-tile .mat-grid-tile-footer.mat-2-line{height:68px}.mat-grid-tile .mat-grid-list-text{display:flex;flex-direction:column;flex:auto;box-sizing:border-box;overflow:hidden}.mat-grid-tile .mat-grid-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-grid-tile .mat-grid-list-text:empty{display:none}.mat-grid-tile .mat-grid-tile-header{top:0}.mat-grid-tile .mat-grid-tile-footer{bottom:0}.mat-grid-tile .mat-grid-avatar{padding-right:16px}[dir=rtl] .mat-grid-tile .mat-grid-avatar{padding-right:0;padding-left:16px}.mat-grid-tile .mat-grid-avatar:empty{display:none}.mat-grid-tile-content{top:0;left:0;right:0;bottom:0;position:absolute;display:flex;align-items:center;justify-content:center;height:100%;padding:0;margin:0}\\n\"],encapsulation:2,changeDetection:0}),n})(),CU=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Vd,B],Vd,B]}),n})();const DU=[\"addListener\",\"removeListener\"],wU=[\"addEventListener\",\"removeEventListener\"],MU=[\"on\",\"off\"];function Jr(n,t,e,i){if(De(e)&&(i=e,e=void 0),i)return Jr(n,t,e).pipe(bf(i));const[r,s]=function SU(n){return De(n.addEventListener)&&De(n.removeEventListener)}(n)?wU.map(o=>a=>n[o](t,a,e)):function xU(n){return De(n.addListener)&&De(n.removeListener)}(n)?DU.map(CE(n,t)):function EU(n){return De(n.on)&&De(n.off)}(n)?MU.map(CE(n,t)):[];if(!r&&bu(n))return lt(o=>Jr(o,t,e))(Jt(n));if(!r)throw new TypeError(\"Invalid event target\");return new Ve(o=>{const a=(...l)=>o.next(1<l.length?l:l[0]);return r(a),()=>s(a)})}function CE(n,t){return e=>i=>n[e](t,i)}const kU=[\"connectionContainer\"],TU=[\"inputContainer\"],AU=[\"label\"];function IU(n,t){1&n&&(kr(0),x(1,\"div\",14),Le(2,\"div\",15)(3,\"div\",16)(4,\"div\",17),S(),x(5,\"div\",18),Le(6,\"div\",15)(7,\"div\",16)(8,\"div\",17),S(),Tr())}function RU(n,t){if(1&n){const e=ia();x(0,\"div\",19),J(\"cdkObserveContent\",function(){return Dr(e),Be().updateOutlineGap()}),Pe(1,1),S()}2&n&&N(\"cdkObserveContentDisabled\",\"outline\"!=Be().appearance)}function OU(n,t){if(1&n&&(kr(0),Pe(1,2),x(2,\"span\"),we(3),S(),Tr()),2&n){const e=Be(2);T(3),Ut(e._control.placeholder)}}function PU(n,t){1&n&&Pe(0,3,[\"*ngSwitchCase\",\"true\"])}function FU(n,t){1&n&&(x(0,\"span\",23),we(1,\" *\"),S())}function NU(n,t){if(1&n){const e=ia();x(0,\"label\",20,21),J(\"cdkObserveContent\",function(){return Dr(e),Be().updateOutlineGap()}),Ee(2,OU,4,1,\"ng-container\",12),Ee(3,PU,1,0,\"ng-content\",12),Ee(4,FU,2,0,\"span\",22),S()}if(2&n){const e=Be();Ae(\"mat-empty\",e._control.empty&&!e._shouldAlwaysFloat())(\"mat-form-field-empty\",e._control.empty&&!e._shouldAlwaysFloat())(\"mat-accent\",\"accent\"==e.color)(\"mat-warn\",\"warn\"==e.color),N(\"cdkObserveContentDisabled\",\"outline\"!=e.appearance)(\"id\",e._labelId)(\"ngSwitch\",e._hasLabel()),Z(\"for\",e._control.id)(\"aria-owns\",e._control.id),T(2),N(\"ngSwitchCase\",!1),T(1),N(\"ngSwitchCase\",!0),T(1),N(\"ngIf\",!e.hideRequiredMarker&&e._control.required&&!e._control.disabled)}}function LU(n,t){1&n&&(x(0,\"div\",24),Pe(1,4),S())}function BU(n,t){if(1&n&&(x(0,\"div\",25),Le(1,\"span\",26),S()),2&n){const e=Be();T(1),Ae(\"mat-accent\",\"accent\"==e.color)(\"mat-warn\",\"warn\"==e.color)}}function VU(n,t){1&n&&(x(0,\"div\"),Pe(1,5),S()),2&n&&N(\"@transitionMessages\",Be()._subscriptAnimationState)}function HU(n,t){if(1&n&&(x(0,\"div\",30),we(1),S()),2&n){const e=Be(2);N(\"id\",e._hintLabelId),T(1),Ut(e.hintLabel)}}function jU(n,t){if(1&n&&(x(0,\"div\",27),Ee(1,HU,2,2,\"div\",28),Pe(2,6),Le(3,\"div\",29),Pe(4,7),S()),2&n){const e=Be();N(\"@transitionMessages\",e._subscriptAnimationState),T(1),N(\"ngIf\",e.hintLabel)}}const zU=[\"*\",[[\"\",\"matPrefix\",\"\"]],[[\"mat-placeholder\"]],[[\"mat-label\"]],[[\"\",\"matSuffix\",\"\"]],[[\"mat-error\"]],[[\"mat-hint\",3,\"align\",\"end\"]],[[\"mat-hint\",\"align\",\"end\"]]],UU=[\"*\",\"[matPrefix]\",\"mat-placeholder\",\"mat-label\",\"[matSuffix]\",\"mat-error\",\"mat-hint:not([align='end'])\",\"mat-hint[align='end']\"];let $U=0;const DE=new b(\"MatError\");let GU=(()=>{class n{constructor(e,i){this.id=\"mat-error-\"+$U++,e||i.nativeElement.setAttribute(\"aria-live\",\"polite\")}}return n.\\u0275fac=function(e){return new(e||n)(kt(\"aria-live\"),f(W))},n.\\u0275dir=C({type:n,selectors:[[\"mat-error\"]],hostAttrs:[\"aria-atomic\",\"true\",1,\"mat-error\"],hostVars:1,hostBindings:function(e,i){2&e&&Z(\"id\",i.id)},inputs:{id:\"id\"},features:[L([{provide:DE,useExisting:n}])]}),n})();const WU={transitionMessages:Ke(\"transitionMessages\",[ae(\"enter\",R({opacity:1,transform:\"translateY(0%)\"})),ge(\"void => enter\",[R({opacity:0,transform:\"translateY(-5px)\"}),be(\"300ms cubic-bezier(0.55, 0, 0.55, 0.2)\")])])};let Ja=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n}),n})(),qU=0;const wE=new b(\"MatHint\");let YU=(()=>{class n{constructor(){this.align=\"start\",this.id=\"mat-hint-\"+qU++}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n,selectors:[[\"mat-hint\"]],hostAttrs:[1,\"mat-hint\"],hostVars:4,hostBindings:function(e,i){2&e&&(Z(\"id\",i.id)(\"align\",null),Ae(\"mat-form-field-hint-end\",\"end\"===i.align))},inputs:{align:\"align\",id:\"id\"},features:[L([{provide:wE,useExisting:n}])]}),n})(),fg=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n,selectors:[[\"mat-label\"]]}),n})(),QU=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275dir=C({type:n,selectors:[[\"mat-placeholder\"]]}),n})();const KU=new b(\"MatPrefix\"),ZU=new b(\"MatSuffix\");let ME=0;const JU=fo(class{constructor(n){this._elementRef=n}},\"primary\"),e5=new b(\"MAT_FORM_FIELD_DEFAULT_OPTIONS\"),el=new b(\"MatFormField\");let t5=(()=>{class n extends JU{constructor(e,i,r,s,o,a,l){super(e),this._changeDetectorRef=i,this._dir=r,this._defaults=s,this._platform=o,this._ngZone=a,this._outlineGapCalculationNeededImmediately=!1,this._outlineGapCalculationNeededOnStable=!1,this._destroyed=new O,this._showAlwaysAnimate=!1,this._subscriptAnimationState=\"\",this._hintLabel=\"\",this._hintLabelId=\"mat-hint-\"+ME++,this._labelId=\"mat-form-field-label-\"+ME++,this.floatLabel=this._getDefaultFloatLabelState(),this._animationsEnabled=\"NoopAnimations\"!==l,this.appearance=s&&s.appearance?s.appearance:\"legacy\",this._hideRequiredMarker=!(!s||null==s.hideRequiredMarker)&&s.hideRequiredMarker}get appearance(){return this._appearance}set appearance(e){const i=this._appearance;this._appearance=e||this._defaults&&this._defaults.appearance||\"legacy\",\"outline\"===this._appearance&&i!==e&&(this._outlineGapCalculationNeededOnStable=!0)}get hideRequiredMarker(){return this._hideRequiredMarker}set hideRequiredMarker(e){this._hideRequiredMarker=G(e)}_shouldAlwaysFloat(){return\"always\"===this.floatLabel&&!this._showAlwaysAnimate}_canLabelFloat(){return\"never\"!==this.floatLabel}get hintLabel(){return this._hintLabel}set hintLabel(e){this._hintLabel=e,this._processHints()}get floatLabel(){return\"legacy\"!==this.appearance&&\"never\"===this._floatLabel?\"auto\":this._floatLabel}set floatLabel(e){e!==this._floatLabel&&(this._floatLabel=e||this._getDefaultFloatLabelState(),this._changeDetectorRef.markForCheck())}get _control(){return this._explicitFormFieldControl||this._controlNonStatic||this._controlStatic}set _control(e){this._explicitFormFieldControl=e}getLabelId(){return this._hasFloatingLabel()?this._labelId:null}getConnectedOverlayOrigin(){return this._connectionContainerRef||this._elementRef}ngAfterContentInit(){this._validateControlChild();const e=this._control;e.controlType&&this._elementRef.nativeElement.classList.add(`mat-form-field-type-${e.controlType}`),e.stateChanges.pipe(Xn(null)).subscribe(()=>{this._validatePlaceholders(),this._syncDescribedByIds(),this._changeDetectorRef.markForCheck()}),e.ngControl&&e.ngControl.valueChanges&&e.ngControl.valueChanges.pipe(Ie(this._destroyed)).subscribe(()=>this._changeDetectorRef.markForCheck()),this._ngZone.runOutsideAngular(()=>{this._ngZone.onStable.pipe(Ie(this._destroyed)).subscribe(()=>{this._outlineGapCalculationNeededOnStable&&this.updateOutlineGap()})}),Bt(this._prefixChildren.changes,this._suffixChildren.changes).subscribe(()=>{this._outlineGapCalculationNeededOnStable=!0,this._changeDetectorRef.markForCheck()}),this._hintChildren.changes.pipe(Xn(null)).subscribe(()=>{this._processHints(),this._changeDetectorRef.markForCheck()}),this._errorChildren.changes.pipe(Xn(null)).subscribe(()=>{this._syncDescribedByIds(),this._changeDetectorRef.markForCheck()}),this._dir&&this._dir.change.pipe(Ie(this._destroyed)).subscribe(()=>{\"function\"==typeof requestAnimationFrame?this._ngZone.runOutsideAngular(()=>{requestAnimationFrame(()=>this.updateOutlineGap())}):this.updateOutlineGap()})}ngAfterContentChecked(){this._validateControlChild(),this._outlineGapCalculationNeededImmediately&&this.updateOutlineGap()}ngAfterViewInit(){this._subscriptAnimationState=\"enter\",this._changeDetectorRef.detectChanges()}ngOnDestroy(){this._destroyed.next(),this._destroyed.complete()}_shouldForward(e){const i=this._control?this._control.ngControl:null;return i&&i[e]}_hasPlaceholder(){return!!(this._control&&this._control.placeholder||this._placeholderChild)}_hasLabel(){return!(!this._labelChildNonStatic&&!this._labelChildStatic)}_shouldLabelFloat(){return this._canLabelFloat()&&(this._control&&this._control.shouldLabelFloat||this._shouldAlwaysFloat())}_hideControlPlaceholder(){return\"legacy\"===this.appearance&&!this._hasLabel()||this._hasLabel()&&!this._shouldLabelFloat()}_hasFloatingLabel(){return this._hasLabel()||\"legacy\"===this.appearance&&this._hasPlaceholder()}_getDisplayedMessages(){return this._errorChildren&&this._errorChildren.length>0&&this._control.errorState?\"error\":\"hint\"}_animateAndLockLabel(){this._hasFloatingLabel()&&this._canLabelFloat()&&(this._animationsEnabled&&this._label&&(this._showAlwaysAnimate=!0,Jr(this._label.nativeElement,\"transitionend\").pipe(it(1)).subscribe(()=>{this._showAlwaysAnimate=!1})),this.floatLabel=\"always\",this._changeDetectorRef.markForCheck())}_validatePlaceholders(){}_processHints(){this._validateHints(),this._syncDescribedByIds()}_validateHints(){}_getDefaultFloatLabelState(){return this._defaults&&this._defaults.floatLabel||\"auto\"}_syncDescribedByIds(){if(this._control){let e=[];if(this._control.userAriaDescribedBy&&\"string\"==typeof this._control.userAriaDescribedBy&&e.push(...this._control.userAriaDescribedBy.split(\" \")),\"hint\"===this._getDisplayedMessages()){const i=this._hintChildren?this._hintChildren.find(s=>\"start\"===s.align):null,r=this._hintChildren?this._hintChildren.find(s=>\"end\"===s.align):null;i?e.push(i.id):this._hintLabel&&e.push(this._hintLabelId),r&&e.push(r.id)}else this._errorChildren&&e.push(...this._errorChildren.map(i=>i.id));this._control.setDescribedByIds(e)}}_validateControlChild(){}updateOutlineGap(){const e=this._label?this._label.nativeElement:null,i=this._connectionContainerRef.nativeElement,r=\".mat-form-field-outline-start\",s=\".mat-form-field-outline-gap\";if(\"outline\"!==this.appearance||!this._platform.isBrowser)return;if(!e||!e.children.length||!e.textContent.trim()){const d=i.querySelectorAll(`${r}, ${s}`);for(let u=0;u<d.length;u++)d[u].style.width=\"0\";return}if(!this._isAttachedToDOM())return void(this._outlineGapCalculationNeededImmediately=!0);let o=0,a=0;const l=i.querySelectorAll(r),c=i.querySelectorAll(s);if(this._label&&this._label.nativeElement.children.length){const d=i.getBoundingClientRect();if(0===d.width&&0===d.height)return this._outlineGapCalculationNeededOnStable=!0,void(this._outlineGapCalculationNeededImmediately=!1);const u=this._getStartEnd(d),h=e.children,p=this._getStartEnd(h[0].getBoundingClientRect());let m=0;for(let g=0;g<h.length;g++)m+=h[g].offsetWidth;o=Math.abs(p-u)-5,a=m>0?.75*m+10:0}for(let d=0;d<l.length;d++)l[d].style.width=`${o}px`;for(let d=0;d<c.length;d++)c[d].style.width=`${a}px`;this._outlineGapCalculationNeededOnStable=this._outlineGapCalculationNeededImmediately=!1}_getStartEnd(e){return this._dir&&\"rtl\"===this._dir.value?e.right:e.left}_isAttachedToDOM(){const e=this._elementRef.nativeElement;if(e.getRootNode){const i=e.getRootNode();return i&&i!==e}return document.documentElement.contains(e)}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(Ye),f(On,8),f(e5,8),f(It),f(ne),f(Rn,8))},n.\\u0275cmp=xe({type:n,selectors:[[\"mat-form-field\"]],contentQueries:function(e,i,r){if(1&e&&(ve(r,Ja,5),ve(r,Ja,7),ve(r,fg,5),ve(r,fg,7),ve(r,QU,5),ve(r,DE,5),ve(r,wE,5),ve(r,KU,5),ve(r,ZU,5)),2&e){let s;z(s=U())&&(i._controlNonStatic=s.first),z(s=U())&&(i._controlStatic=s.first),z(s=U())&&(i._labelChildNonStatic=s.first),z(s=U())&&(i._labelChildStatic=s.first),z(s=U())&&(i._placeholderChild=s.first),z(s=U())&&(i._errorChildren=s),z(s=U())&&(i._hintChildren=s),z(s=U())&&(i._prefixChildren=s),z(s=U())&&(i._suffixChildren=s)}},viewQuery:function(e,i){if(1&e&&(je(kU,7),je(TU,5),je(AU,5)),2&e){let r;z(r=U())&&(i._connectionContainerRef=r.first),z(r=U())&&(i._inputContainerRef=r.first),z(r=U())&&(i._label=r.first)}},hostAttrs:[1,\"mat-form-field\"],hostVars:40,hostBindings:function(e,i){2&e&&Ae(\"mat-form-field-appearance-standard\",\"standard\"==i.appearance)(\"mat-form-field-appearance-fill\",\"fill\"==i.appearance)(\"mat-form-field-appearance-outline\",\"outline\"==i.appearance)(\"mat-form-field-appearance-legacy\",\"legacy\"==i.appearance)(\"mat-form-field-invalid\",i._control.errorState)(\"mat-form-field-can-float\",i._canLabelFloat())(\"mat-form-field-should-float\",i._shouldLabelFloat())(\"mat-form-field-has-label\",i._hasFloatingLabel())(\"mat-form-field-hide-placeholder\",i._hideControlPlaceholder())(\"mat-form-field-disabled\",i._control.disabled)(\"mat-form-field-autofilled\",i._control.autofilled)(\"mat-focused\",i._control.focused)(\"ng-untouched\",i._shouldForward(\"untouched\"))(\"ng-touched\",i._shouldForward(\"touched\"))(\"ng-pristine\",i._shouldForward(\"pristine\"))(\"ng-dirty\",i._shouldForward(\"dirty\"))(\"ng-valid\",i._shouldForward(\"valid\"))(\"ng-invalid\",i._shouldForward(\"invalid\"))(\"ng-pending\",i._shouldForward(\"pending\"))(\"_mat-animation-noopable\",!i._animationsEnabled)},inputs:{color:\"color\",appearance:\"appearance\",hideRequiredMarker:\"hideRequiredMarker\",hintLabel:\"hintLabel\",floatLabel:\"floatLabel\"},exportAs:[\"matFormField\"],features:[L([{provide:el,useExisting:n}]),E],ngContentSelectors:UU,decls:15,vars:8,consts:[[1,\"mat-form-field-wrapper\"],[1,\"mat-form-field-flex\",3,\"click\"],[\"connectionContainer\",\"\"],[4,\"ngIf\"],[\"class\",\"mat-form-field-prefix\",3,\"cdkObserveContentDisabled\",\"cdkObserveContent\",4,\"ngIf\"],[1,\"mat-form-field-infix\"],[\"inputContainer\",\"\"],[1,\"mat-form-field-label-wrapper\"],[\"class\",\"mat-form-field-label\",3,\"cdkObserveContentDisabled\",\"id\",\"mat-empty\",\"mat-form-field-empty\",\"mat-accent\",\"mat-warn\",\"ngSwitch\",\"cdkObserveContent\",4,\"ngIf\"],[\"class\",\"mat-form-field-suffix\",4,\"ngIf\"],[\"class\",\"mat-form-field-underline\",4,\"ngIf\"],[1,\"mat-form-field-subscript-wrapper\",3,\"ngSwitch\"],[4,\"ngSwitchCase\"],[\"class\",\"mat-form-field-hint-wrapper\",4,\"ngSwitchCase\"],[1,\"mat-form-field-outline\"],[1,\"mat-form-field-outline-start\"],[1,\"mat-form-field-outline-gap\"],[1,\"mat-form-field-outline-end\"],[1,\"mat-form-field-outline\",\"mat-form-field-outline-thick\"],[1,\"mat-form-field-prefix\",3,\"cdkObserveContentDisabled\",\"cdkObserveContent\"],[1,\"mat-form-field-label\",3,\"cdkObserveContentDisabled\",\"id\",\"ngSwitch\",\"cdkObserveContent\"],[\"label\",\"\"],[\"class\",\"mat-placeholder-required mat-form-field-required-marker\",\"aria-hidden\",\"true\",4,\"ngIf\"],[\"aria-hidden\",\"true\",1,\"mat-placeholder-required\",\"mat-form-field-required-marker\"],[1,\"mat-form-field-suffix\"],[1,\"mat-form-field-underline\"],[1,\"mat-form-field-ripple\"],[1,\"mat-form-field-hint-wrapper\"],[\"class\",\"mat-hint\",3,\"id\",4,\"ngIf\"],[1,\"mat-form-field-hint-spacer\"],[1,\"mat-hint\",3,\"id\"]],template:function(e,i){1&e&&(Lt(zU),x(0,\"div\",0)(1,\"div\",1,2),J(\"click\",function(s){return i._control.onContainerClick&&i._control.onContainerClick(s)}),Ee(3,IU,9,0,\"ng-container\",3),Ee(4,RU,2,1,\"div\",4),x(5,\"div\",5,6),Pe(7),x(8,\"span\",7),Ee(9,NU,5,16,\"label\",8),S()(),Ee(10,LU,2,0,\"div\",9),S(),Ee(11,BU,2,4,\"div\",10),x(12,\"div\",11),Ee(13,VU,2,1,\"div\",12),Ee(14,jU,5,2,\"div\",13),S()()),2&e&&(T(3),N(\"ngIf\",\"outline\"==i.appearance),T(1),N(\"ngIf\",i._prefixChildren.length),T(5),N(\"ngIf\",i._hasFloatingLabel()),T(1),N(\"ngIf\",i._suffixChildren.length),T(1),N(\"ngIf\",\"outline\"!=i.appearance),T(1),N(\"ngSwitch\",i._getDisplayedMessages()),T(1),N(\"ngSwitchCase\",\"error\"),T(1),N(\"ngSwitchCase\",\"hint\"))},directives:[Ca,Qm,Ys,Pc],styles:[\".mat-form-field{display:inline-block;position:relative;text-align:left}[dir=rtl] .mat-form-field{text-align:right}.mat-form-field-wrapper{position:relative}.mat-form-field-flex{display:inline-flex;align-items:baseline;box-sizing:border-box;width:100%}.mat-form-field-prefix,.mat-form-field-suffix{white-space:nowrap;flex:none;position:relative}.mat-form-field-infix{display:block;position:relative;flex:auto;min-width:0;width:180px}.cdk-high-contrast-active .mat-form-field-infix{border-image:linear-gradient(transparent, transparent)}.mat-form-field-label-wrapper{position:absolute;left:0;box-sizing:content-box;width:100%;height:100%;overflow:hidden;pointer-events:none}[dir=rtl] .mat-form-field-label-wrapper{left:auto;right:0}.mat-form-field-label{position:absolute;left:0;font:inherit;pointer-events:none;width:100%;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;transform-origin:0 0;transition:transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1),color 400ms cubic-bezier(0.25, 0.8, 0.25, 1),width 400ms cubic-bezier(0.25, 0.8, 0.25, 1);display:none}[dir=rtl] .mat-form-field-label{transform-origin:100% 0;left:auto;right:0}.cdk-high-contrast-active .mat-form-field-disabled .mat-form-field-label{color:GrayText}.mat-form-field-empty.mat-form-field-label,.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-label{display:block}.mat-form-field-autofill-control:-webkit-autofill+.mat-form-field-label-wrapper .mat-form-field-label{display:none}.mat-form-field-can-float .mat-form-field-autofill-control:-webkit-autofill+.mat-form-field-label-wrapper .mat-form-field-label{display:block;transition:none}.mat-input-server:focus+.mat-form-field-label-wrapper .mat-form-field-label,.mat-input-server[placeholder]:not(:placeholder-shown)+.mat-form-field-label-wrapper .mat-form-field-label{display:none}.mat-form-field-can-float .mat-input-server:focus+.mat-form-field-label-wrapper .mat-form-field-label,.mat-form-field-can-float .mat-input-server[placeholder]:not(:placeholder-shown)+.mat-form-field-label-wrapper .mat-form-field-label{display:block}.mat-form-field-label:not(.mat-form-field-empty){transition:none}.mat-form-field-underline{position:absolute;width:100%;pointer-events:none;transform:scale3d(1, 1.0001, 1)}.mat-form-field-ripple{position:absolute;left:0;width:100%;transform-origin:50%;transform:scaleX(0.5);opacity:0;transition:background-color 300ms cubic-bezier(0.55, 0, 0.55, 0.2)}.mat-form-field.mat-focused .mat-form-field-ripple,.mat-form-field.mat-form-field-invalid .mat-form-field-ripple{opacity:1;transform:none;transition:transform 300ms cubic-bezier(0.25, 0.8, 0.25, 1),opacity 100ms cubic-bezier(0.25, 0.8, 0.25, 1),background-color 300ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-subscript-wrapper{position:absolute;box-sizing:border-box;width:100%;overflow:hidden}.mat-form-field-subscript-wrapper .mat-icon,.mat-form-field-label-wrapper .mat-icon{width:1em;height:1em;font-size:inherit;vertical-align:baseline}.mat-form-field-hint-wrapper{display:flex}.mat-form-field-hint-spacer{flex:1 0 1em}.mat-error{display:block}.mat-form-field-control-wrapper{position:relative}.mat-form-field-hint-end{order:1}.mat-form-field._mat-animation-noopable .mat-form-field-label,.mat-form-field._mat-animation-noopable .mat-form-field-ripple{transition:none}\\n\",'.mat-form-field-appearance-fill .mat-form-field-flex{border-radius:4px 4px 0 0;padding:.75em .75em 0 .75em}.cdk-high-contrast-active .mat-form-field-appearance-fill .mat-form-field-flex{outline:solid 1px}.cdk-high-contrast-active .mat-form-field-appearance-fill.mat-form-field-disabled .mat-form-field-flex{outline-color:GrayText}.cdk-high-contrast-active .mat-form-field-appearance-fill.mat-focused .mat-form-field-flex{outline:dashed 3px}.mat-form-field-appearance-fill .mat-form-field-underline::before{content:\"\";display:block;position:absolute;bottom:0;height:1px;width:100%}.mat-form-field-appearance-fill .mat-form-field-ripple{bottom:0;height:2px}.cdk-high-contrast-active .mat-form-field-appearance-fill .mat-form-field-ripple{height:0}.mat-form-field-appearance-fill:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-underline .mat-form-field-ripple{opacity:1;transform:none;transition:opacity 600ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-appearance-fill._mat-animation-noopable:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-underline .mat-form-field-ripple{transition:none}.mat-form-field-appearance-fill .mat-form-field-subscript-wrapper{padding:0 1em}\\n','.mat-input-element{font:inherit;background:transparent;color:currentColor;border:none;outline:none;padding:0;margin:0;width:100%;max-width:100%;vertical-align:bottom;text-align:inherit;box-sizing:content-box}.mat-input-element:-moz-ui-invalid{box-shadow:none}.mat-input-element,.mat-input-element::-webkit-search-cancel-button,.mat-input-element::-webkit-search-decoration,.mat-input-element::-webkit-search-results-button,.mat-input-element::-webkit-search-results-decoration{-webkit-appearance:none}.mat-input-element::-webkit-contacts-auto-fill-button,.mat-input-element::-webkit-caps-lock-indicator,.mat-input-element:not([type=password])::-webkit-credentials-auto-fill-button{visibility:hidden}.mat-input-element[type=date],.mat-input-element[type=datetime],.mat-input-element[type=datetime-local],.mat-input-element[type=month],.mat-input-element[type=week],.mat-input-element[type=time]{line-height:1}.mat-input-element[type=date]::after,.mat-input-element[type=datetime]::after,.mat-input-element[type=datetime-local]::after,.mat-input-element[type=month]::after,.mat-input-element[type=week]::after,.mat-input-element[type=time]::after{content:\" \";white-space:pre;width:1px}.mat-input-element::-webkit-inner-spin-button,.mat-input-element::-webkit-calendar-picker-indicator,.mat-input-element::-webkit-clear-button{font-size:.75em}.mat-input-element::placeholder{-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-input-element::-moz-placeholder{-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-input-element::-webkit-input-placeholder{-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-input-element:-ms-input-placeholder{-webkit-user-select:none;-moz-user-select:none;user-select:none;transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-hide-placeholder .mat-input-element::placeholder{color:transparent !important;-webkit-text-fill-color:transparent;transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-input-element::placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-input-element::-moz-placeholder{color:transparent !important;-webkit-text-fill-color:transparent;transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-input-element::-moz-placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-input-element::-webkit-input-placeholder{color:transparent !important;-webkit-text-fill-color:transparent;transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-input-element::-webkit-input-placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-input-element:-ms-input-placeholder{color:transparent !important;-webkit-text-fill-color:transparent;transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-input-element:-ms-input-placeholder{opacity:0}textarea.mat-input-element{resize:vertical;overflow:auto}textarea.mat-input-element.cdk-textarea-autosize{resize:none}textarea.mat-input-element{padding:2px 0;margin:-2px 0}select.mat-input-element{-moz-appearance:none;-webkit-appearance:none;position:relative;background-color:transparent;display:inline-flex;box-sizing:border-box;padding-top:1em;top:-1em;margin-bottom:-1em}select.mat-input-element::-moz-focus-inner{border:0}select.mat-input-element:not(:disabled){cursor:pointer}.mat-form-field-type-mat-native-select .mat-form-field-infix::after{content:\"\";width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;border-top:5px solid;position:absolute;top:50%;right:0;margin-top:-2.5px;pointer-events:none}[dir=rtl] .mat-form-field-type-mat-native-select .mat-form-field-infix::after{right:auto;left:0}.mat-form-field-type-mat-native-select .mat-input-element{padding-right:15px}[dir=rtl] .mat-form-field-type-mat-native-select .mat-input-element{padding-right:0;padding-left:15px}.mat-form-field-type-mat-native-select .mat-form-field-label-wrapper{max-width:calc(100% - 10px)}.mat-form-field-type-mat-native-select.mat-form-field-appearance-outline .mat-form-field-infix::after{margin-top:-5px}.mat-form-field-type-mat-native-select.mat-form-field-appearance-fill .mat-form-field-infix::after{margin-top:-10px}\\n',\".mat-form-field-appearance-legacy .mat-form-field-label{transform:perspective(100px)}.mat-form-field-appearance-legacy .mat-form-field-prefix .mat-icon,.mat-form-field-appearance-legacy .mat-form-field-suffix .mat-icon{width:1em}.mat-form-field-appearance-legacy .mat-form-field-prefix .mat-icon-button,.mat-form-field-appearance-legacy .mat-form-field-suffix .mat-icon-button{font:inherit;vertical-align:baseline}.mat-form-field-appearance-legacy .mat-form-field-prefix .mat-icon-button .mat-icon,.mat-form-field-appearance-legacy .mat-form-field-suffix .mat-icon-button .mat-icon{font-size:inherit}.mat-form-field-appearance-legacy .mat-form-field-underline{height:1px}.cdk-high-contrast-active .mat-form-field-appearance-legacy .mat-form-field-underline{height:0;border-top:solid 1px}.mat-form-field-appearance-legacy .mat-form-field-ripple{top:0;height:2px;overflow:hidden}.cdk-high-contrast-active .mat-form-field-appearance-legacy .mat-form-field-ripple{height:0;border-top:solid 2px}.mat-form-field-appearance-legacy.mat-form-field-disabled .mat-form-field-underline{background-position:0;background-color:transparent}.cdk-high-contrast-active .mat-form-field-appearance-legacy.mat-form-field-disabled .mat-form-field-underline{border-top-style:dotted;border-top-width:2px;border-top-color:GrayText}.mat-form-field-appearance-legacy.mat-form-field-invalid:not(.mat-focused) .mat-form-field-ripple{height:1px}\\n\",\".mat-form-field-appearance-outline .mat-form-field-wrapper{margin:.25em 0}.mat-form-field-appearance-outline .mat-form-field-flex{padding:0 .75em 0 .75em;margin-top:-0.25em;position:relative}.mat-form-field-appearance-outline .mat-form-field-prefix,.mat-form-field-appearance-outline .mat-form-field-suffix{top:.25em}.mat-form-field-appearance-outline .mat-form-field-outline{display:flex;position:absolute;top:.25em;left:0;right:0;bottom:0;pointer-events:none}.mat-form-field-appearance-outline .mat-form-field-outline-start,.mat-form-field-appearance-outline .mat-form-field-outline-end{border:1px solid currentColor;min-width:5px}.mat-form-field-appearance-outline .mat-form-field-outline-start{border-radius:5px 0 0 5px;border-right-style:none}[dir=rtl] .mat-form-field-appearance-outline .mat-form-field-outline-start{border-right-style:solid;border-left-style:none;border-radius:0 5px 5px 0}.mat-form-field-appearance-outline .mat-form-field-outline-end{border-radius:0 5px 5px 0;border-left-style:none;flex-grow:1}[dir=rtl] .mat-form-field-appearance-outline .mat-form-field-outline-end{border-left-style:solid;border-right-style:none;border-radius:5px 0 0 5px}.mat-form-field-appearance-outline .mat-form-field-outline-gap{border-radius:.000001px;border:1px solid currentColor;border-left-style:none;border-right-style:none}.mat-form-field-appearance-outline.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-outline-gap{border-top-color:transparent}.mat-form-field-appearance-outline .mat-form-field-outline-thick{opacity:0}.mat-form-field-appearance-outline .mat-form-field-outline-thick .mat-form-field-outline-start,.mat-form-field-appearance-outline .mat-form-field-outline-thick .mat-form-field-outline-end,.mat-form-field-appearance-outline .mat-form-field-outline-thick .mat-form-field-outline-gap{border-width:2px}.mat-form-field-appearance-outline.mat-focused .mat-form-field-outline,.mat-form-field-appearance-outline.mat-form-field-invalid .mat-form-field-outline{opacity:0;transition:opacity 100ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-appearance-outline.mat-focused .mat-form-field-outline-thick,.mat-form-field-appearance-outline.mat-form-field-invalid .mat-form-field-outline-thick{opacity:1}.cdk-high-contrast-active .mat-form-field-appearance-outline.mat-focused .mat-form-field-outline-thick{border:3px dashed}.mat-form-field-appearance-outline:not(.mat-form-field-disabled) .mat-form-field-flex:hover .mat-form-field-outline{opacity:0;transition:opacity 600ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-appearance-outline:not(.mat-form-field-disabled) .mat-form-field-flex:hover .mat-form-field-outline-thick{opacity:1}.mat-form-field-appearance-outline .mat-form-field-subscript-wrapper{padding:0 1em}.cdk-high-contrast-active .mat-form-field-appearance-outline.mat-form-field-disabled .mat-form-field-outline{color:GrayText}.mat-form-field-appearance-outline._mat-animation-noopable:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-outline,.mat-form-field-appearance-outline._mat-animation-noopable .mat-form-field-outline,.mat-form-field-appearance-outline._mat-animation-noopable .mat-form-field-outline-start,.mat-form-field-appearance-outline._mat-animation-noopable .mat-form-field-outline-end,.mat-form-field-appearance-outline._mat-animation-noopable .mat-form-field-outline-gap{transition:none}\\n\",\".mat-form-field-appearance-standard .mat-form-field-flex{padding-top:.75em}.mat-form-field-appearance-standard .mat-form-field-underline{height:1px}.cdk-high-contrast-active .mat-form-field-appearance-standard .mat-form-field-underline{height:0;border-top:solid 1px}.mat-form-field-appearance-standard .mat-form-field-ripple{bottom:0;height:2px}.cdk-high-contrast-active .mat-form-field-appearance-standard .mat-form-field-ripple{height:0;border-top:solid 2px}.mat-form-field-appearance-standard.mat-form-field-disabled .mat-form-field-underline{background-position:0;background-color:transparent}.cdk-high-contrast-active .mat-form-field-appearance-standard.mat-form-field-disabled .mat-form-field-underline{border-top-style:dotted;border-top-width:2px}.mat-form-field-appearance-standard:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-underline .mat-form-field-ripple{opacity:1;transform:none;transition:opacity 600ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-appearance-standard._mat-animation-noopable:not(.mat-form-field-disabled) .mat-form-field-flex:hover~.mat-form-field-underline .mat-form-field-ripple{transition:none}\\n\"],encapsulation:2,data:{animation:[WU.transitionMessages]},changeDetection:0}),n})(),mg=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B,Ya],B]}),n})();const tl={schedule(n){let t=requestAnimationFrame,e=cancelAnimationFrame;const{delegate:i}=tl;i&&(t=i.requestAnimationFrame,e=i.cancelAnimationFrame);const r=t(s=>{e=void 0,n(s)});return new ke(()=>null==e?void 0:e(r))},requestAnimationFrame(...n){const{delegate:t}=tl;return((null==t?void 0:t.requestAnimationFrame)||requestAnimationFrame)(...n)},cancelAnimationFrame(...n){const{delegate:t}=tl;return((null==t?void 0:t.cancelAnimationFrame)||cancelAnimationFrame)(...n)},delegate:void 0},EE=new class r5 extends Ym{flush(t){this._active=!0;const e=this._scheduled;this._scheduled=void 0;const{actions:i}=this;let r;t=t||i.shift();do{if(r=t.execute(t.state,t.delay))break}while((t=i[0])&&t.id===e&&i.shift());if(this._active=!1,r){for(;(t=i[0])&&t.id===e&&i.shift();)t.unsubscribe();throw r}}}(class n5 extends qm{constructor(t,e){super(t,e),this.scheduler=t,this.work=e}requestAsyncId(t,e,i=0){return null!==i&&i>0?super.requestAsyncId(t,e,i):(t.actions.push(this),t._scheduled||(t._scheduled=tl.requestAnimationFrame(()=>t.flush(void 0))))}recycleAsyncId(t,e,i=0){if(null!=i&&i>0||null==i&&this.delay>0)return super.recycleAsyncId(t,e,i);t.actions.some(r=>r.id===e)||(tl.cancelAnimationFrame(e),t._scheduled=void 0)}});let gg,s5=1;const jd={};function SE(n){return n in jd&&(delete jd[n],!0)}const o5={setImmediate(n){const t=s5++;return jd[t]=!0,gg||(gg=Promise.resolve()),gg.then(()=>SE(t)&&n()),t},clearImmediate(n){SE(n)}},{setImmediate:a5,clearImmediate:l5}=o5,zd={setImmediate(...n){const{delegate:t}=zd;return((null==t?void 0:t.setImmediate)||a5)(...n)},clearImmediate(n){const{delegate:t}=zd;return((null==t?void 0:t.clearImmediate)||l5)(n)},delegate:void 0};new class d5 extends Ym{flush(t){this._active=!0;const e=this._scheduled;this._scheduled=void 0;const{actions:i}=this;let r;t=t||i.shift();do{if(r=t.execute(t.state,t.delay))break}while((t=i[0])&&t.id===e&&i.shift());if(this._active=!1,r){for(;(t=i[0])&&t.id===e&&i.shift();)t.unsubscribe();throw r}}}(class c5 extends qm{constructor(t,e){super(t,e),this.scheduler=t,this.work=e}requestAsyncId(t,e,i=0){return null!==i&&i>0?super.requestAsyncId(t,e,i):(t.actions.push(this),t._scheduled||(t._scheduled=zd.setImmediate(t.flush.bind(t,void 0))))}recycleAsyncId(t,e,i=0){if(null!=i&&i>0||null==i&&this.delay>0)return super.recycleAsyncId(t,e,i);t.actions.some(r=>r.id===e)||(zd.clearImmediate(e),t._scheduled=void 0)}});function _g(n=0,t,e=t3){let i=-1;return null!=t&&(y_(t)?e=t:i=t),new Ve(r=>{let s=function p5(n){return n instanceof Date&&!isNaN(n)}(n)?+n-e.now():n;s<0&&(s=0);let o=0;return e.schedule(function(){r.closed||(r.next(o++),0<=i?this.schedule(void 0,i):r.complete())},s)})}function kE(n,t=qa){return function h5(n){return qe((t,e)=>{let i=!1,r=null,s=null,o=!1;const a=()=>{if(null==s||s.unsubscribe(),s=null,i){i=!1;const c=r;r=null,e.next(c)}o&&e.complete()},l=()=>{s=null,o&&e.complete()};t.subscribe(Ue(e,c=>{i=!0,r=c,s||Jt(n(c)).subscribe(s=Ue(e,a,l))},()=>{o=!0,(!i||!s||s.closed)&&e.complete()}))})}(()=>_g(n,t))}let m5=(()=>{class n{constructor(e,i,r){this._ngZone=e,this._platform=i,this._scrolled=new O,this._globalSubscription=null,this._scrolledCount=0,this.scrollContainers=new Map,this._document=r}register(e){this.scrollContainers.has(e)||this.scrollContainers.set(e,e.elementScrolled().subscribe(()=>this._scrolled.next(e)))}deregister(e){const i=this.scrollContainers.get(e);i&&(i.unsubscribe(),this.scrollContainers.delete(e))}scrolled(e=20){return this._platform.isBrowser?new Ve(i=>{this._globalSubscription||this._addGlobalListener();const r=e>0?this._scrolled.pipe(kE(e)).subscribe(i):this._scrolled.subscribe(i);return this._scrolledCount++,()=>{r.unsubscribe(),this._scrolledCount--,this._scrolledCount||this._removeGlobalListener()}}):q()}ngOnDestroy(){this._removeGlobalListener(),this.scrollContainers.forEach((e,i)=>this.deregister(i)),this._scrolled.complete()}ancestorScrolled(e,i){const r=this.getAncestorScrollContainers(e);return this.scrolled(i).pipe(Ct(s=>!s||r.indexOf(s)>-1))}getAncestorScrollContainers(e){const i=[];return this.scrollContainers.forEach((r,s)=>{this._scrollableContainsElement(s,e)&&i.push(s)}),i}_getWindow(){return this._document.defaultView||window}_scrollableContainsElement(e,i){let r=at(i),s=e.getElementRef().nativeElement;do{if(r==s)return!0}while(r=r.parentElement);return!1}_addGlobalListener(){this._globalSubscription=this._ngZone.runOutsideAngular(()=>Jr(this._getWindow().document,\"scroll\").subscribe(()=>this._scrolled.next()))}_removeGlobalListener(){this._globalSubscription&&(this._globalSubscription.unsubscribe(),this._globalSubscription=null)}}return n.\\u0275fac=function(e){return new(e||n)(y(ne),y(It),y(ie,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),es=(()=>{class n{constructor(e,i,r){this._platform=e,this._change=new O,this._changeListener=s=>{this._change.next(s)},this._document=r,i.runOutsideAngular(()=>{if(e.isBrowser){const s=this._getWindow();s.addEventListener(\"resize\",this._changeListener),s.addEventListener(\"orientationchange\",this._changeListener)}this.change().subscribe(()=>this._viewportSize=null)})}ngOnDestroy(){if(this._platform.isBrowser){const e=this._getWindow();e.removeEventListener(\"resize\",this._changeListener),e.removeEventListener(\"orientationchange\",this._changeListener)}this._change.complete()}getViewportSize(){this._viewportSize||this._updateViewportSize();const e={width:this._viewportSize.width,height:this._viewportSize.height};return this._platform.isBrowser||(this._viewportSize=null),e}getViewportRect(){const e=this.getViewportScrollPosition(),{width:i,height:r}=this.getViewportSize();return{top:e.top,left:e.left,bottom:e.top+r,right:e.left+i,height:r,width:i}}getViewportScrollPosition(){if(!this._platform.isBrowser)return{top:0,left:0};const e=this._document,i=this._getWindow(),r=e.documentElement,s=r.getBoundingClientRect();return{top:-s.top||e.body.scrollTop||i.scrollY||r.scrollTop||0,left:-s.left||e.body.scrollLeft||i.scrollX||r.scrollLeft||0}}change(e=20){return e>0?this._change.pipe(kE(e)):this._change}_getWindow(){return this._document.defaultView||window}_updateViewportSize(){const e=this._getWindow();this._viewportSize=this._platform.isBrowser?{width:e.innerWidth,height:e.innerHeight}:{width:0,height:0}}}return n.\\u0275fac=function(e){return new(e||n)(y(It),y(ne),y(ie,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),Ci=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),Ud=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[lo,Ci],lo,Ci]}),n})();class vg{attach(t){return this._attachedHost=t,t.attach(this)}detach(){let t=this._attachedHost;null!=t&&(this._attachedHost=null,t.detach())}get isAttached(){return null!=this._attachedHost}setAttachedHost(t){this._attachedHost=t}}class yg extends vg{constructor(t,e,i,r){super(),this.component=t,this.viewContainerRef=e,this.injector=i,this.componentFactoryResolver=r}}class $d extends vg{constructor(t,e,i){super(),this.templateRef=t,this.viewContainerRef=e,this.context=i}get origin(){return this.templateRef.elementRef}attach(t,e=this.context){return this.context=e,super.attach(t)}detach(){return this.context=void 0,super.detach()}}class _5 extends vg{constructor(t){super(),this.element=t instanceof W?t.nativeElement:t}}class bg{constructor(){this._isDisposed=!1,this.attachDomPortal=null}hasAttached(){return!!this._attachedPortal}attach(t){return t instanceof yg?(this._attachedPortal=t,this.attachComponentPortal(t)):t instanceof $d?(this._attachedPortal=t,this.attachTemplatePortal(t)):this.attachDomPortal&&t instanceof _5?(this._attachedPortal=t,this.attachDomPortal(t)):void 0}detach(){this._attachedPortal&&(this._attachedPortal.setAttachedHost(null),this._attachedPortal=null),this._invokeDisposeFn()}dispose(){this.hasAttached()&&this.detach(),this._invokeDisposeFn(),this._isDisposed=!0}setDisposeFn(t){this._disposeFn=t}_invokeDisposeFn(){this._disposeFn&&(this._disposeFn(),this._disposeFn=null)}}class v5 extends bg{constructor(t,e,i,r,s){super(),this.outletElement=t,this._componentFactoryResolver=e,this._appRef=i,this._defaultInjector=r,this.attachDomPortal=o=>{const a=o.element,l=this._document.createComment(\"dom-portal\");a.parentNode.insertBefore(l,a),this.outletElement.appendChild(a),this._attachedPortal=o,super.setDisposeFn(()=>{l.parentNode&&l.parentNode.replaceChild(a,l)})},this._document=s}attachComponentPortal(t){const i=(t.componentFactoryResolver||this._componentFactoryResolver).resolveComponentFactory(t.component);let r;return t.viewContainerRef?(r=t.viewContainerRef.createComponent(i,t.viewContainerRef.length,t.injector||t.viewContainerRef.injector),this.setDisposeFn(()=>r.destroy())):(r=i.create(t.injector||this._defaultInjector),this._appRef.attachView(r.hostView),this.setDisposeFn(()=>{this._appRef.detachView(r.hostView),r.destroy()})),this.outletElement.appendChild(this._getComponentRootNode(r)),this._attachedPortal=t,r}attachTemplatePortal(t){let e=t.viewContainerRef,i=e.createEmbeddedView(t.templateRef,t.context);return i.rootNodes.forEach(r=>this.outletElement.appendChild(r)),i.detectChanges(),this.setDisposeFn(()=>{let r=e.indexOf(i);-1!==r&&e.remove(r)}),this._attachedPortal=t,i}dispose(){super.dispose(),this.outletElement.remove()}_getComponentRootNode(t){return t.hostView.rootNodes[0]}}let TE=(()=>{class n extends bg{constructor(e,i,r){super(),this._componentFactoryResolver=e,this._viewContainerRef=i,this._isInitialized=!1,this.attached=new $,this.attachDomPortal=s=>{const o=s.element,a=this._document.createComment(\"dom-portal\");s.setAttachedHost(this),o.parentNode.insertBefore(a,o),this._getRootNode().appendChild(o),this._attachedPortal=s,super.setDisposeFn(()=>{a.parentNode&&a.parentNode.replaceChild(o,a)})},this._document=r}get portal(){return this._attachedPortal}set portal(e){this.hasAttached()&&!e&&!this._isInitialized||(this.hasAttached()&&super.detach(),e&&super.attach(e),this._attachedPortal=e||null)}get attachedRef(){return this._attachedRef}ngOnInit(){this._isInitialized=!0}ngOnDestroy(){super.dispose(),this._attachedPortal=null,this._attachedRef=null}attachComponentPortal(e){e.setAttachedHost(this);const i=null!=e.viewContainerRef?e.viewContainerRef:this._viewContainerRef,s=(e.componentFactoryResolver||this._componentFactoryResolver).resolveComponentFactory(e.component),o=i.createComponent(s,i.length,e.injector||i.injector);return i!==this._viewContainerRef&&this._getRootNode().appendChild(o.hostView.rootNodes[0]),super.setDisposeFn(()=>o.destroy()),this._attachedPortal=e,this._attachedRef=o,this.attached.emit(o),o}attachTemplatePortal(e){e.setAttachedHost(this);const i=this._viewContainerRef.createEmbeddedView(e.templateRef,e.context);return super.setDisposeFn(()=>this._viewContainerRef.clear()),this._attachedPortal=e,this._attachedRef=i,this.attached.emit(i),i}_getRootNode(){const e=this._viewContainerRef.element.nativeElement;return e.nodeType===e.ELEMENT_NODE?e:e.parentNode}}return n.\\u0275fac=function(e){return new(e||n)(f(Ir),f(st),f(ie))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"cdkPortalOutlet\",\"\"]],inputs:{portal:[\"cdkPortalOutlet\",\"portal\"]},outputs:{attached:\"attached\"},exportAs:[\"cdkPortalOutlet\"],features:[E]}),n})(),Hi=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const AE=jz();class b5{constructor(t,e){this._viewportRuler=t,this._previousHTMLStyles={top:\"\",left:\"\"},this._isEnabled=!1,this._document=e}attach(){}enable(){if(this._canBeEnabled()){const t=this._document.documentElement;this._previousScrollPosition=this._viewportRuler.getViewportScrollPosition(),this._previousHTMLStyles.left=t.style.left||\"\",this._previousHTMLStyles.top=t.style.top||\"\",t.style.left=ft(-this._previousScrollPosition.left),t.style.top=ft(-this._previousScrollPosition.top),t.classList.add(\"cdk-global-scrollblock\"),this._isEnabled=!0}}disable(){if(this._isEnabled){const t=this._document.documentElement,i=t.style,r=this._document.body.style,s=i.scrollBehavior||\"\",o=r.scrollBehavior||\"\";this._isEnabled=!1,i.left=this._previousHTMLStyles.left,i.top=this._previousHTMLStyles.top,t.classList.remove(\"cdk-global-scrollblock\"),AE&&(i.scrollBehavior=r.scrollBehavior=\"auto\"),window.scroll(this._previousScrollPosition.left,this._previousScrollPosition.top),AE&&(i.scrollBehavior=s,r.scrollBehavior=o)}}_canBeEnabled(){if(this._document.documentElement.classList.contains(\"cdk-global-scrollblock\")||this._isEnabled)return!1;const e=this._document.body,i=this._viewportRuler.getViewportSize();return e.scrollHeight>i.height||e.scrollWidth>i.width}}class C5{constructor(t,e,i,r){this._scrollDispatcher=t,this._ngZone=e,this._viewportRuler=i,this._config=r,this._scrollSubscription=null,this._detach=()=>{this.disable(),this._overlayRef.hasAttached()&&this._ngZone.run(()=>this._overlayRef.detach())}}attach(t){this._overlayRef=t}enable(){if(this._scrollSubscription)return;const t=this._scrollDispatcher.scrolled(0);this._config&&this._config.threshold&&this._config.threshold>1?(this._initialScrollPosition=this._viewportRuler.getViewportScrollPosition().top,this._scrollSubscription=t.subscribe(()=>{const e=this._viewportRuler.getViewportScrollPosition().top;Math.abs(e-this._initialScrollPosition)>this._config.threshold?this._detach():this._overlayRef.updatePosition()})):this._scrollSubscription=t.subscribe(this._detach)}disable(){this._scrollSubscription&&(this._scrollSubscription.unsubscribe(),this._scrollSubscription=null)}detach(){this.disable(),this._overlayRef=null}}class IE{enable(){}disable(){}attach(){}}function Cg(n,t){return t.some(e=>n.bottom<e.top||n.top>e.bottom||n.right<e.left||n.left>e.right)}function RE(n,t){return t.some(e=>n.top<e.top||n.bottom>e.bottom||n.left<e.left||n.right>e.right)}class D5{constructor(t,e,i,r){this._scrollDispatcher=t,this._viewportRuler=e,this._ngZone=i,this._config=r,this._scrollSubscription=null}attach(t){this._overlayRef=t}enable(){this._scrollSubscription||(this._scrollSubscription=this._scrollDispatcher.scrolled(this._config?this._config.scrollThrottle:0).subscribe(()=>{if(this._overlayRef.updatePosition(),this._config&&this._config.autoClose){const e=this._overlayRef.overlayElement.getBoundingClientRect(),{width:i,height:r}=this._viewportRuler.getViewportSize();Cg(e,[{width:i,height:r,bottom:r,right:i,top:0,left:0}])&&(this.disable(),this._ngZone.run(()=>this._overlayRef.detach()))}}))}disable(){this._scrollSubscription&&(this._scrollSubscription.unsubscribe(),this._scrollSubscription=null)}detach(){this.disable(),this._overlayRef=null}}let w5=(()=>{class n{constructor(e,i,r,s){this._scrollDispatcher=e,this._viewportRuler=i,this._ngZone=r,this.noop=()=>new IE,this.close=o=>new C5(this._scrollDispatcher,this._ngZone,this._viewportRuler,o),this.block=()=>new b5(this._viewportRuler,this._document),this.reposition=o=>new D5(this._scrollDispatcher,this._viewportRuler,this._ngZone,o),this._document=s}}return n.\\u0275fac=function(e){return new(e||n)(y(m5),y(es),y(ne),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();class Gd{constructor(t){if(this.scrollStrategy=new IE,this.panelClass=\"\",this.hasBackdrop=!1,this.backdropClass=\"cdk-overlay-dark-backdrop\",this.disposeOnNavigation=!1,t){const e=Object.keys(t);for(const i of e)void 0!==t[i]&&(this[i]=t[i])}}}class M5{constructor(t,e){this.connectionPair=t,this.scrollableViewProperties=e}}class x5{constructor(t,e,i,r,s,o,a,l,c){this._portalOutlet=t,this._host=e,this._pane=i,this._config=r,this._ngZone=s,this._keyboardDispatcher=o,this._document=a,this._location=l,this._outsideClickDispatcher=c,this._backdropElement=null,this._backdropClick=new O,this._attachments=new O,this._detachments=new O,this._locationChanges=ke.EMPTY,this._backdropClickHandler=d=>this._backdropClick.next(d),this._backdropTransitionendHandler=d=>{this._disposeBackdrop(d.target)},this._keydownEvents=new O,this._outsidePointerEvents=new O,r.scrollStrategy&&(this._scrollStrategy=r.scrollStrategy,this._scrollStrategy.attach(this)),this._positionStrategy=r.positionStrategy}get overlayElement(){return this._pane}get backdropElement(){return this._backdropElement}get hostElement(){return this._host}attach(t){let e=this._portalOutlet.attach(t);return!this._host.parentElement&&this._previousHostParent&&this._previousHostParent.appendChild(this._host),this._positionStrategy&&this._positionStrategy.attach(this),this._updateStackingOrder(),this._updateElementSize(),this._updateElementDirection(),this._scrollStrategy&&this._scrollStrategy.enable(),this._ngZone.onStable.pipe(it(1)).subscribe(()=>{this.hasAttached()&&this.updatePosition()}),this._togglePointerEvents(!0),this._config.hasBackdrop&&this._attachBackdrop(),this._config.panelClass&&this._toggleClasses(this._pane,this._config.panelClass,!0),this._attachments.next(),this._keyboardDispatcher.add(this),this._config.disposeOnNavigation&&(this._locationChanges=this._location.subscribe(()=>this.dispose())),this._outsideClickDispatcher.add(this),e}detach(){if(!this.hasAttached())return;this.detachBackdrop(),this._togglePointerEvents(!1),this._positionStrategy&&this._positionStrategy.detach&&this._positionStrategy.detach(),this._scrollStrategy&&this._scrollStrategy.disable();const t=this._portalOutlet.detach();return this._detachments.next(),this._keyboardDispatcher.remove(this),this._detachContentWhenStable(),this._locationChanges.unsubscribe(),this._outsideClickDispatcher.remove(this),t}dispose(){var t;const e=this.hasAttached();this._positionStrategy&&this._positionStrategy.dispose(),this._disposeScrollStrategy(),this._disposeBackdrop(this._backdropElement),this._locationChanges.unsubscribe(),this._keyboardDispatcher.remove(this),this._portalOutlet.dispose(),this._attachments.complete(),this._backdropClick.complete(),this._keydownEvents.complete(),this._outsidePointerEvents.complete(),this._outsideClickDispatcher.remove(this),null===(t=this._host)||void 0===t||t.remove(),this._previousHostParent=this._pane=this._host=null,e&&this._detachments.next(),this._detachments.complete()}hasAttached(){return this._portalOutlet.hasAttached()}backdropClick(){return this._backdropClick}attachments(){return this._attachments}detachments(){return this._detachments}keydownEvents(){return this._keydownEvents}outsidePointerEvents(){return this._outsidePointerEvents}getConfig(){return this._config}updatePosition(){this._positionStrategy&&this._positionStrategy.apply()}updatePositionStrategy(t){t!==this._positionStrategy&&(this._positionStrategy&&this._positionStrategy.dispose(),this._positionStrategy=t,this.hasAttached()&&(t.attach(this),this.updatePosition()))}updateSize(t){this._config=Object.assign(Object.assign({},this._config),t),this._updateElementSize()}setDirection(t){this._config=Object.assign(Object.assign({},this._config),{direction:t}),this._updateElementDirection()}addPanelClass(t){this._pane&&this._toggleClasses(this._pane,t,!0)}removePanelClass(t){this._pane&&this._toggleClasses(this._pane,t,!1)}getDirection(){const t=this._config.direction;return t?\"string\"==typeof t?t:t.value:\"ltr\"}updateScrollStrategy(t){t!==this._scrollStrategy&&(this._disposeScrollStrategy(),this._scrollStrategy=t,this.hasAttached()&&(t.attach(this),t.enable()))}_updateElementDirection(){this._host.setAttribute(\"dir\",this.getDirection())}_updateElementSize(){if(!this._pane)return;const t=this._pane.style;t.width=ft(this._config.width),t.height=ft(this._config.height),t.minWidth=ft(this._config.minWidth),t.minHeight=ft(this._config.minHeight),t.maxWidth=ft(this._config.maxWidth),t.maxHeight=ft(this._config.maxHeight)}_togglePointerEvents(t){this._pane.style.pointerEvents=t?\"\":\"none\"}_attachBackdrop(){const t=\"cdk-overlay-backdrop-showing\";this._backdropElement=this._document.createElement(\"div\"),this._backdropElement.classList.add(\"cdk-overlay-backdrop\"),this._config.backdropClass&&this._toggleClasses(this._backdropElement,this._config.backdropClass,!0),this._host.parentElement.insertBefore(this._backdropElement,this._host),this._backdropElement.addEventListener(\"click\",this._backdropClickHandler),\"undefined\"!=typeof requestAnimationFrame?this._ngZone.runOutsideAngular(()=>{requestAnimationFrame(()=>{this._backdropElement&&this._backdropElement.classList.add(t)})}):this._backdropElement.classList.add(t)}_updateStackingOrder(){this._host.nextSibling&&this._host.parentNode.appendChild(this._host)}detachBackdrop(){const t=this._backdropElement;!t||(t.classList.remove(\"cdk-overlay-backdrop-showing\"),this._ngZone.runOutsideAngular(()=>{t.addEventListener(\"transitionend\",this._backdropTransitionendHandler)}),t.style.pointerEvents=\"none\",this._backdropTimeout=this._ngZone.runOutsideAngular(()=>setTimeout(()=>{this._disposeBackdrop(t)},500)))}_toggleClasses(t,e,i){const r=Wx(e||[]).filter(s=>!!s);r.length&&(i?t.classList.add(...r):t.classList.remove(...r))}_detachContentWhenStable(){this._ngZone.runOutsideAngular(()=>{const t=this._ngZone.onStable.pipe(Ie(Bt(this._attachments,this._detachments))).subscribe(()=>{(!this._pane||!this._host||0===this._pane.children.length)&&(this._pane&&this._config.panelClass&&this._toggleClasses(this._pane,this._config.panelClass,!1),this._host&&this._host.parentElement&&(this._previousHostParent=this._host.parentElement,this._host.remove()),t.unsubscribe())})})}_disposeScrollStrategy(){const t=this._scrollStrategy;t&&(t.disable(),t.detach&&t.detach())}_disposeBackdrop(t){t&&(t.removeEventListener(\"click\",this._backdropClickHandler),t.removeEventListener(\"transitionend\",this._backdropTransitionendHandler),t.remove(),this._backdropElement===t&&(this._backdropElement=null)),this._backdropTimeout&&(clearTimeout(this._backdropTimeout),this._backdropTimeout=void 0)}}let Dg=(()=>{class n{constructor(e,i){this._platform=i,this._document=e}ngOnDestroy(){var e;null===(e=this._containerElement)||void 0===e||e.remove()}getContainerElement(){return this._containerElement||this._createContainer(),this._containerElement}_createContainer(){const e=\"cdk-overlay-container\";if(this._platform.isBrowser||jm()){const r=this._document.querySelectorAll(`.${e}[platform=\"server\"], .${e}[platform=\"test\"]`);for(let s=0;s<r.length;s++)r[s].remove()}const i=this._document.createElement(\"div\");i.classList.add(e),jm()?i.setAttribute(\"platform\",\"test\"):this._platform.isBrowser||i.setAttribute(\"platform\",\"server\"),this._document.body.appendChild(i),this._containerElement=i}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(It))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const OE=\"cdk-overlay-connected-position-bounding-box\",E5=/([A-Za-z%]+)$/;class S5{constructor(t,e,i,r,s){this._viewportRuler=e,this._document=i,this._platform=r,this._overlayContainer=s,this._lastBoundingBoxSize={width:0,height:0},this._isPushed=!1,this._canPush=!0,this._growAfterOpen=!1,this._hasFlexibleDimensions=!0,this._positionLocked=!1,this._viewportMargin=0,this._scrollables=[],this._preferredPositions=[],this._positionChanges=new O,this._resizeSubscription=ke.EMPTY,this._offsetX=0,this._offsetY=0,this._appliedPanelClasses=[],this.positionChanges=this._positionChanges,this.setOrigin(t)}get positions(){return this._preferredPositions}attach(t){this._validatePositions(),t.hostElement.classList.add(OE),this._overlayRef=t,this._boundingBox=t.hostElement,this._pane=t.overlayElement,this._isDisposed=!1,this._isInitialRender=!0,this._lastPosition=null,this._resizeSubscription.unsubscribe(),this._resizeSubscription=this._viewportRuler.change().subscribe(()=>{this._isInitialRender=!0,this.apply()})}apply(){if(this._isDisposed||!this._platform.isBrowser)return;if(!this._isInitialRender&&this._positionLocked&&this._lastPosition)return void this.reapplyLastPosition();this._clearPanelClasses(),this._resetOverlayElementStyles(),this._resetBoundingBoxStyles(),this._viewportRect=this._getNarrowedViewportRect(),this._originRect=this._getOriginRect(),this._overlayRect=this._pane.getBoundingClientRect(),this._containerRect=this._overlayContainer.getContainerElement().getBoundingClientRect();const t=this._originRect,e=this._overlayRect,i=this._viewportRect,r=this._containerRect,s=[];let o;for(let a of this._preferredPositions){let l=this._getOriginPoint(t,r,a),c=this._getOverlayPoint(l,e,a),d=this._getOverlayFit(c,e,i,a);if(d.isCompletelyWithinViewport)return this._isPushed=!1,void this._applyPosition(a,l);this._canFitWithFlexibleDimensions(d,c,i)?s.push({position:a,origin:l,overlayRect:e,boundingBoxRect:this._calculateBoundingBoxRect(l,a)}):(!o||o.overlayFit.visibleArea<d.visibleArea)&&(o={overlayFit:d,overlayPoint:c,originPoint:l,position:a,overlayRect:e})}if(s.length){let a=null,l=-1;for(const c of s){const d=c.boundingBoxRect.width*c.boundingBoxRect.height*(c.position.weight||1);d>l&&(l=d,a=c)}return this._isPushed=!1,void this._applyPosition(a.position,a.origin)}if(this._canPush)return this._isPushed=!0,void this._applyPosition(o.position,o.originPoint);this._applyPosition(o.position,o.originPoint)}detach(){this._clearPanelClasses(),this._lastPosition=null,this._previousPushAmount=null,this._resizeSubscription.unsubscribe()}dispose(){this._isDisposed||(this._boundingBox&&ts(this._boundingBox.style,{top:\"\",left:\"\",right:\"\",bottom:\"\",height:\"\",width:\"\",alignItems:\"\",justifyContent:\"\"}),this._pane&&this._resetOverlayElementStyles(),this._overlayRef&&this._overlayRef.hostElement.classList.remove(OE),this.detach(),this._positionChanges.complete(),this._overlayRef=this._boundingBox=null,this._isDisposed=!0)}reapplyLastPosition(){if(this._isDisposed||!this._platform.isBrowser)return;const t=this._lastPosition;if(t){this._originRect=this._getOriginRect(),this._overlayRect=this._pane.getBoundingClientRect(),this._viewportRect=this._getNarrowedViewportRect(),this._containerRect=this._overlayContainer.getContainerElement().getBoundingClientRect();const e=this._getOriginPoint(this._originRect,this._containerRect,t);this._applyPosition(t,e)}else this.apply()}withScrollableContainers(t){return this._scrollables=t,this}withPositions(t){return this._preferredPositions=t,-1===t.indexOf(this._lastPosition)&&(this._lastPosition=null),this._validatePositions(),this}withViewportMargin(t){return this._viewportMargin=t,this}withFlexibleDimensions(t=!0){return this._hasFlexibleDimensions=t,this}withGrowAfterOpen(t=!0){return this._growAfterOpen=t,this}withPush(t=!0){return this._canPush=t,this}withLockedPosition(t=!0){return this._positionLocked=t,this}setOrigin(t){return this._origin=t,this}withDefaultOffsetX(t){return this._offsetX=t,this}withDefaultOffsetY(t){return this._offsetY=t,this}withTransformOriginOn(t){return this._transformOriginSelector=t,this}_getOriginPoint(t,e,i){let r,s;if(\"center\"==i.originX)r=t.left+t.width/2;else{const o=this._isRtl()?t.right:t.left,a=this._isRtl()?t.left:t.right;r=\"start\"==i.originX?o:a}return e.left<0&&(r-=e.left),s=\"center\"==i.originY?t.top+t.height/2:\"top\"==i.originY?t.top:t.bottom,e.top<0&&(s-=e.top),{x:r,y:s}}_getOverlayPoint(t,e,i){let r,s;return r=\"center\"==i.overlayX?-e.width/2:\"start\"===i.overlayX?this._isRtl()?-e.width:0:this._isRtl()?0:-e.width,s=\"center\"==i.overlayY?-e.height/2:\"top\"==i.overlayY?0:-e.height,{x:t.x+r,y:t.y+s}}_getOverlayFit(t,e,i,r){const s=FE(e);let{x:o,y:a}=t,l=this._getOffset(r,\"x\"),c=this._getOffset(r,\"y\");l&&(o+=l),c&&(a+=c);let h=0-a,p=a+s.height-i.height,m=this._subtractOverflows(s.width,0-o,o+s.width-i.width),g=this._subtractOverflows(s.height,h,p),_=m*g;return{visibleArea:_,isCompletelyWithinViewport:s.width*s.height===_,fitsInViewportVertically:g===s.height,fitsInViewportHorizontally:m==s.width}}_canFitWithFlexibleDimensions(t,e,i){if(this._hasFlexibleDimensions){const r=i.bottom-e.y,s=i.right-e.x,o=PE(this._overlayRef.getConfig().minHeight),a=PE(this._overlayRef.getConfig().minWidth),c=t.fitsInViewportHorizontally||null!=a&&a<=s;return(t.fitsInViewportVertically||null!=o&&o<=r)&&c}return!1}_pushOverlayOnScreen(t,e,i){if(this._previousPushAmount&&this._positionLocked)return{x:t.x+this._previousPushAmount.x,y:t.y+this._previousPushAmount.y};const r=FE(e),s=this._viewportRect,o=Math.max(t.x+r.width-s.width,0),a=Math.max(t.y+r.height-s.height,0),l=Math.max(s.top-i.top-t.y,0),c=Math.max(s.left-i.left-t.x,0);let d=0,u=0;return d=r.width<=s.width?c||-o:t.x<this._viewportMargin?s.left-i.left-t.x:0,u=r.height<=s.height?l||-a:t.y<this._viewportMargin?s.top-i.top-t.y:0,this._previousPushAmount={x:d,y:u},{x:t.x+d,y:t.y+u}}_applyPosition(t,e){if(this._setTransformOrigin(t),this._setOverlayElementStyles(e,t),this._setBoundingBoxStyles(e,t),t.panelClass&&this._addPanelClasses(t.panelClass),this._lastPosition=t,this._positionChanges.observers.length){const i=this._getScrollVisibility(),r=new M5(t,i);this._positionChanges.next(r)}this._isInitialRender=!1}_setTransformOrigin(t){if(!this._transformOriginSelector)return;const e=this._boundingBox.querySelectorAll(this._transformOriginSelector);let i,r=t.overlayY;i=\"center\"===t.overlayX?\"center\":this._isRtl()?\"start\"===t.overlayX?\"right\":\"left\":\"start\"===t.overlayX?\"left\":\"right\";for(let s=0;s<e.length;s++)e[s].style.transformOrigin=`${i} ${r}`}_calculateBoundingBoxRect(t,e){const i=this._viewportRect,r=this._isRtl();let s,o,a,d,u,h;if(\"top\"===e.overlayY)o=t.y,s=i.height-o+this._viewportMargin;else if(\"bottom\"===e.overlayY)a=i.height-t.y+2*this._viewportMargin,s=i.height-a+this._viewportMargin;else{const p=Math.min(i.bottom-t.y+i.top,t.y),m=this._lastBoundingBoxSize.height;s=2*p,o=t.y-p,s>m&&!this._isInitialRender&&!this._growAfterOpen&&(o=t.y-m/2)}if(\"end\"===e.overlayX&&!r||\"start\"===e.overlayX&&r)h=i.width-t.x+this._viewportMargin,d=t.x-this._viewportMargin;else if(\"start\"===e.overlayX&&!r||\"end\"===e.overlayX&&r)u=t.x,d=i.right-t.x;else{const p=Math.min(i.right-t.x+i.left,t.x),m=this._lastBoundingBoxSize.width;d=2*p,u=t.x-p,d>m&&!this._isInitialRender&&!this._growAfterOpen&&(u=t.x-m/2)}return{top:o,left:u,bottom:a,right:h,width:d,height:s}}_setBoundingBoxStyles(t,e){const i=this._calculateBoundingBoxRect(t,e);!this._isInitialRender&&!this._growAfterOpen&&(i.height=Math.min(i.height,this._lastBoundingBoxSize.height),i.width=Math.min(i.width,this._lastBoundingBoxSize.width));const r={};if(this._hasExactPosition())r.top=r.left=\"0\",r.bottom=r.right=r.maxHeight=r.maxWidth=\"\",r.width=r.height=\"100%\";else{const s=this._overlayRef.getConfig().maxHeight,o=this._overlayRef.getConfig().maxWidth;r.height=ft(i.height),r.top=ft(i.top),r.bottom=ft(i.bottom),r.width=ft(i.width),r.left=ft(i.left),r.right=ft(i.right),r.alignItems=\"center\"===e.overlayX?\"center\":\"end\"===e.overlayX?\"flex-end\":\"flex-start\",r.justifyContent=\"center\"===e.overlayY?\"center\":\"bottom\"===e.overlayY?\"flex-end\":\"flex-start\",s&&(r.maxHeight=ft(s)),o&&(r.maxWidth=ft(o))}this._lastBoundingBoxSize=i,ts(this._boundingBox.style,r)}_resetBoundingBoxStyles(){ts(this._boundingBox.style,{top:\"0\",left:\"0\",right:\"0\",bottom:\"0\",height:\"\",width:\"\",alignItems:\"\",justifyContent:\"\"})}_resetOverlayElementStyles(){ts(this._pane.style,{top:\"\",left:\"\",bottom:\"\",right:\"\",position:\"\",transform:\"\"})}_setOverlayElementStyles(t,e){const i={},r=this._hasExactPosition(),s=this._hasFlexibleDimensions,o=this._overlayRef.getConfig();if(r){const d=this._viewportRuler.getViewportScrollPosition();ts(i,this._getExactOverlayY(e,t,d)),ts(i,this._getExactOverlayX(e,t,d))}else i.position=\"static\";let a=\"\",l=this._getOffset(e,\"x\"),c=this._getOffset(e,\"y\");l&&(a+=`translateX(${l}px) `),c&&(a+=`translateY(${c}px)`),i.transform=a.trim(),o.maxHeight&&(r?i.maxHeight=ft(o.maxHeight):s&&(i.maxHeight=\"\")),o.maxWidth&&(r?i.maxWidth=ft(o.maxWidth):s&&(i.maxWidth=\"\")),ts(this._pane.style,i)}_getExactOverlayY(t,e,i){let r={top:\"\",bottom:\"\"},s=this._getOverlayPoint(e,this._overlayRect,t);return this._isPushed&&(s=this._pushOverlayOnScreen(s,this._overlayRect,i)),\"bottom\"===t.overlayY?r.bottom=this._document.documentElement.clientHeight-(s.y+this._overlayRect.height)+\"px\":r.top=ft(s.y),r}_getExactOverlayX(t,e,i){let o,r={left:\"\",right:\"\"},s=this._getOverlayPoint(e,this._overlayRect,t);return this._isPushed&&(s=this._pushOverlayOnScreen(s,this._overlayRect,i)),o=this._isRtl()?\"end\"===t.overlayX?\"left\":\"right\":\"end\"===t.overlayX?\"right\":\"left\",\"right\"===o?r.right=this._document.documentElement.clientWidth-(s.x+this._overlayRect.width)+\"px\":r.left=ft(s.x),r}_getScrollVisibility(){const t=this._getOriginRect(),e=this._pane.getBoundingClientRect(),i=this._scrollables.map(r=>r.getElementRef().nativeElement.getBoundingClientRect());return{isOriginClipped:RE(t,i),isOriginOutsideView:Cg(t,i),isOverlayClipped:RE(e,i),isOverlayOutsideView:Cg(e,i)}}_subtractOverflows(t,...e){return e.reduce((i,r)=>i-Math.max(r,0),t)}_getNarrowedViewportRect(){const t=this._document.documentElement.clientWidth,e=this._document.documentElement.clientHeight,i=this._viewportRuler.getViewportScrollPosition();return{top:i.top+this._viewportMargin,left:i.left+this._viewportMargin,right:i.left+t-this._viewportMargin,bottom:i.top+e-this._viewportMargin,width:t-2*this._viewportMargin,height:e-2*this._viewportMargin}}_isRtl(){return\"rtl\"===this._overlayRef.getDirection()}_hasExactPosition(){return!this._hasFlexibleDimensions||this._isPushed}_getOffset(t,e){return\"x\"===e?null==t.offsetX?this._offsetX:t.offsetX:null==t.offsetY?this._offsetY:t.offsetY}_validatePositions(){}_addPanelClasses(t){this._pane&&Wx(t).forEach(e=>{\"\"!==e&&-1===this._appliedPanelClasses.indexOf(e)&&(this._appliedPanelClasses.push(e),this._pane.classList.add(e))})}_clearPanelClasses(){this._pane&&(this._appliedPanelClasses.forEach(t=>{this._pane.classList.remove(t)}),this._appliedPanelClasses=[])}_getOriginRect(){const t=this._origin;if(t instanceof W)return t.nativeElement.getBoundingClientRect();if(t instanceof Element)return t.getBoundingClientRect();const e=t.width||0,i=t.height||0;return{top:t.y,bottom:t.y+i,left:t.x,right:t.x+e,height:i,width:e}}}function ts(n,t){for(let e in t)t.hasOwnProperty(e)&&(n[e]=t[e]);return n}function PE(n){if(\"number\"!=typeof n&&null!=n){const[t,e]=n.split(E5);return e&&\"px\"!==e?null:parseFloat(t)}return n||null}function FE(n){return{top:Math.floor(n.top),right:Math.floor(n.right),bottom:Math.floor(n.bottom),left:Math.floor(n.left),width:Math.floor(n.width),height:Math.floor(n.height)}}const NE=\"cdk-global-overlay-wrapper\";class k5{constructor(){this._cssPosition=\"static\",this._topOffset=\"\",this._bottomOffset=\"\",this._leftOffset=\"\",this._rightOffset=\"\",this._alignItems=\"\",this._justifyContent=\"\",this._width=\"\",this._height=\"\"}attach(t){const e=t.getConfig();this._overlayRef=t,this._width&&!e.width&&t.updateSize({width:this._width}),this._height&&!e.height&&t.updateSize({height:this._height}),t.hostElement.classList.add(NE),this._isDisposed=!1}top(t=\"\"){return this._bottomOffset=\"\",this._topOffset=t,this._alignItems=\"flex-start\",this}left(t=\"\"){return this._rightOffset=\"\",this._leftOffset=t,this._justifyContent=\"flex-start\",this}bottom(t=\"\"){return this._topOffset=\"\",this._bottomOffset=t,this._alignItems=\"flex-end\",this}right(t=\"\"){return this._leftOffset=\"\",this._rightOffset=t,this._justifyContent=\"flex-end\",this}width(t=\"\"){return this._overlayRef?this._overlayRef.updateSize({width:t}):this._width=t,this}height(t=\"\"){return this._overlayRef?this._overlayRef.updateSize({height:t}):this._height=t,this}centerHorizontally(t=\"\"){return this.left(t),this._justifyContent=\"center\",this}centerVertically(t=\"\"){return this.top(t),this._alignItems=\"center\",this}apply(){if(!this._overlayRef||!this._overlayRef.hasAttached())return;const t=this._overlayRef.overlayElement.style,e=this._overlayRef.hostElement.style,i=this._overlayRef.getConfig(),{width:r,height:s,maxWidth:o,maxHeight:a}=i,l=!(\"100%\"!==r&&\"100vw\"!==r||o&&\"100%\"!==o&&\"100vw\"!==o),c=!(\"100%\"!==s&&\"100vh\"!==s||a&&\"100%\"!==a&&\"100vh\"!==a);t.position=this._cssPosition,t.marginLeft=l?\"0\":this._leftOffset,t.marginTop=c?\"0\":this._topOffset,t.marginBottom=this._bottomOffset,t.marginRight=this._rightOffset,l?e.justifyContent=\"flex-start\":\"center\"===this._justifyContent?e.justifyContent=\"center\":\"rtl\"===this._overlayRef.getConfig().direction?\"flex-start\"===this._justifyContent?e.justifyContent=\"flex-end\":\"flex-end\"===this._justifyContent&&(e.justifyContent=\"flex-start\"):e.justifyContent=this._justifyContent,e.alignItems=c?\"flex-start\":this._alignItems}dispose(){if(this._isDisposed||!this._overlayRef)return;const t=this._overlayRef.overlayElement.style,e=this._overlayRef.hostElement,i=e.style;e.classList.remove(NE),i.justifyContent=i.alignItems=t.marginTop=t.marginBottom=t.marginLeft=t.marginRight=t.position=\"\",this._overlayRef=null,this._isDisposed=!0}}let T5=(()=>{class n{constructor(e,i,r,s){this._viewportRuler=e,this._document=i,this._platform=r,this._overlayContainer=s}global(){return new k5}flexibleConnectedTo(e){return new S5(e,this._viewportRuler,this._document,this._platform,this._overlayContainer)}}return n.\\u0275fac=function(e){return new(e||n)(y(es),y(ie),y(It),y(Dg))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),LE=(()=>{class n{constructor(e){this._attachedOverlays=[],this._document=e}ngOnDestroy(){this.detach()}add(e){this.remove(e),this._attachedOverlays.push(e)}remove(e){const i=this._attachedOverlays.indexOf(e);i>-1&&this._attachedOverlays.splice(i,1),0===this._attachedOverlays.length&&this.detach()}}return n.\\u0275fac=function(e){return new(e||n)(y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),A5=(()=>{class n extends LE{constructor(e,i){super(e),this._ngZone=i,this._keydownListener=r=>{const s=this._attachedOverlays;for(let o=s.length-1;o>-1;o--)if(s[o]._keydownEvents.observers.length>0){const a=s[o]._keydownEvents;this._ngZone?this._ngZone.run(()=>a.next(r)):a.next(r);break}}}add(e){super.add(e),this._isAttached||(this._ngZone?this._ngZone.runOutsideAngular(()=>this._document.body.addEventListener(\"keydown\",this._keydownListener)):this._document.body.addEventListener(\"keydown\",this._keydownListener),this._isAttached=!0)}detach(){this._isAttached&&(this._document.body.removeEventListener(\"keydown\",this._keydownListener),this._isAttached=!1)}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(ne,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),I5=(()=>{class n extends LE{constructor(e,i,r){super(e),this._platform=i,this._ngZone=r,this._cursorStyleIsSet=!1,this._pointerDownListener=s=>{this._pointerDownEventTarget=Pn(s)},this._clickListener=s=>{const o=Pn(s),a=\"click\"===s.type&&this._pointerDownEventTarget?this._pointerDownEventTarget:o;this._pointerDownEventTarget=null;const l=this._attachedOverlays.slice();for(let c=l.length-1;c>-1;c--){const d=l[c];if(d._outsidePointerEvents.observers.length<1||!d.hasAttached())continue;if(d.overlayElement.contains(o)||d.overlayElement.contains(a))break;const u=d._outsidePointerEvents;this._ngZone?this._ngZone.run(()=>u.next(s)):u.next(s)}}}add(e){if(super.add(e),!this._isAttached){const i=this._document.body;this._ngZone?this._ngZone.runOutsideAngular(()=>this._addEventListeners(i)):this._addEventListeners(i),this._platform.IOS&&!this._cursorStyleIsSet&&(this._cursorOriginalValue=i.style.cursor,i.style.cursor=\"pointer\",this._cursorStyleIsSet=!0),this._isAttached=!0}}detach(){if(this._isAttached){const e=this._document.body;e.removeEventListener(\"pointerdown\",this._pointerDownListener,!0),e.removeEventListener(\"click\",this._clickListener,!0),e.removeEventListener(\"auxclick\",this._clickListener,!0),e.removeEventListener(\"contextmenu\",this._clickListener,!0),this._platform.IOS&&this._cursorStyleIsSet&&(e.style.cursor=this._cursorOriginalValue,this._cursorStyleIsSet=!1),this._isAttached=!1}}_addEventListeners(e){e.addEventListener(\"pointerdown\",this._pointerDownListener,!0),e.addEventListener(\"click\",this._clickListener,!0),e.addEventListener(\"auxclick\",this._clickListener,!0),e.addEventListener(\"contextmenu\",this._clickListener,!0)}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(It),y(ne,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),R5=0,ni=(()=>{class n{constructor(e,i,r,s,o,a,l,c,d,u,h){this.scrollStrategies=e,this._overlayContainer=i,this._componentFactoryResolver=r,this._positionBuilder=s,this._keyboardDispatcher=o,this._injector=a,this._ngZone=l,this._document=c,this._directionality=d,this._location=u,this._outsideClickDispatcher=h}create(e){const i=this._createHostElement(),r=this._createPaneElement(i),s=this._createPortalOutlet(r),o=new Gd(e);return o.direction=o.direction||this._directionality.value,new x5(s,i,r,o,this._ngZone,this._keyboardDispatcher,this._document,this._location,this._outsideClickDispatcher)}position(){return this._positionBuilder}_createPaneElement(e){const i=this._document.createElement(\"div\");return i.id=\"cdk-overlay-\"+R5++,i.classList.add(\"cdk-overlay-pane\"),e.appendChild(i),i}_createHostElement(){const e=this._document.createElement(\"div\");return this._overlayContainer.getContainerElement().appendChild(e),e}_createPortalOutlet(e){return this._appRef||(this._appRef=this._injector.get(Cc)),new v5(e,this._componentFactoryResolver,this._appRef,this._injector,this._document)}}return n.\\u0275fac=function(e){return new(e||n)(y(w5),y(Dg),y(Ir),y(T5),y(A5),y(dt),y(ne),y(ie),y(On),y(va),y(I5))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})();const O5=[{originX:\"start\",originY:\"bottom\",overlayX:\"start\",overlayY:\"top\"},{originX:\"start\",originY:\"top\",overlayX:\"start\",overlayY:\"bottom\"},{originX:\"end\",originY:\"top\",overlayX:\"end\",overlayY:\"bottom\"},{originX:\"end\",originY:\"bottom\",overlayX:\"end\",overlayY:\"top\"}],BE=new b(\"cdk-connected-overlay-scroll-strategy\");let VE=(()=>{class n{constructor(e){this.elementRef=e}}return n.\\u0275fac=function(e){return new(e||n)(f(W))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"cdk-overlay-origin\",\"\"],[\"\",\"overlay-origin\",\"\"],[\"\",\"cdkOverlayOrigin\",\"\"]],exportAs:[\"cdkOverlayOrigin\"]}),n})(),HE=(()=>{class n{constructor(e,i,r,s,o){this._overlay=e,this._dir=o,this._hasBackdrop=!1,this._lockPosition=!1,this._growAfterOpen=!1,this._flexibleDimensions=!1,this._push=!1,this._backdropSubscription=ke.EMPTY,this._attachSubscription=ke.EMPTY,this._detachSubscription=ke.EMPTY,this._positionSubscription=ke.EMPTY,this.viewportMargin=0,this.open=!1,this.disableClose=!1,this.backdropClick=new $,this.positionChange=new $,this.attach=new $,this.detach=new $,this.overlayKeydown=new $,this.overlayOutsideClick=new $,this._templatePortal=new $d(i,r),this._scrollStrategyFactory=s,this.scrollStrategy=this._scrollStrategyFactory()}get offsetX(){return this._offsetX}set offsetX(e){this._offsetX=e,this._position&&this._updatePositionStrategy(this._position)}get offsetY(){return this._offsetY}set offsetY(e){this._offsetY=e,this._position&&this._updatePositionStrategy(this._position)}get hasBackdrop(){return this._hasBackdrop}set hasBackdrop(e){this._hasBackdrop=G(e)}get lockPosition(){return this._lockPosition}set lockPosition(e){this._lockPosition=G(e)}get flexibleDimensions(){return this._flexibleDimensions}set flexibleDimensions(e){this._flexibleDimensions=G(e)}get growAfterOpen(){return this._growAfterOpen}set growAfterOpen(e){this._growAfterOpen=G(e)}get push(){return this._push}set push(e){this._push=G(e)}get overlayRef(){return this._overlayRef}get dir(){return this._dir?this._dir.value:\"ltr\"}ngOnDestroy(){this._attachSubscription.unsubscribe(),this._detachSubscription.unsubscribe(),this._backdropSubscription.unsubscribe(),this._positionSubscription.unsubscribe(),this._overlayRef&&this._overlayRef.dispose()}ngOnChanges(e){this._position&&(this._updatePositionStrategy(this._position),this._overlayRef.updateSize({width:this.width,minWidth:this.minWidth,height:this.height,minHeight:this.minHeight}),e.origin&&this.open&&this._position.apply()),e.open&&(this.open?this._attachOverlay():this._detachOverlay())}_createOverlay(){(!this.positions||!this.positions.length)&&(this.positions=O5);const e=this._overlayRef=this._overlay.create(this._buildConfig());this._attachSubscription=e.attachments().subscribe(()=>this.attach.emit()),this._detachSubscription=e.detachments().subscribe(()=>this.detach.emit()),e.keydownEvents().subscribe(i=>{this.overlayKeydown.next(i),27===i.keyCode&&!this.disableClose&&!Xt(i)&&(i.preventDefault(),this._detachOverlay())}),this._overlayRef.outsidePointerEvents().subscribe(i=>{this.overlayOutsideClick.next(i)})}_buildConfig(){const e=this._position=this.positionStrategy||this._createPositionStrategy(),i=new Gd({direction:this._dir,positionStrategy:e,scrollStrategy:this.scrollStrategy,hasBackdrop:this.hasBackdrop});return(this.width||0===this.width)&&(i.width=this.width),(this.height||0===this.height)&&(i.height=this.height),(this.minWidth||0===this.minWidth)&&(i.minWidth=this.minWidth),(this.minHeight||0===this.minHeight)&&(i.minHeight=this.minHeight),this.backdropClass&&(i.backdropClass=this.backdropClass),this.panelClass&&(i.panelClass=this.panelClass),i}_updatePositionStrategy(e){const i=this.positions.map(r=>({originX:r.originX,originY:r.originY,overlayX:r.overlayX,overlayY:r.overlayY,offsetX:r.offsetX||this.offsetX,offsetY:r.offsetY||this.offsetY,panelClass:r.panelClass||void 0}));return e.setOrigin(this._getFlexibleConnectedPositionStrategyOrigin()).withPositions(i).withFlexibleDimensions(this.flexibleDimensions).withPush(this.push).withGrowAfterOpen(this.growAfterOpen).withViewportMargin(this.viewportMargin).withLockedPosition(this.lockPosition).withTransformOriginOn(this.transformOriginSelector)}_createPositionStrategy(){const e=this._overlay.position().flexibleConnectedTo(this._getFlexibleConnectedPositionStrategyOrigin());return this._updatePositionStrategy(e),e}_getFlexibleConnectedPositionStrategyOrigin(){return this.origin instanceof VE?this.origin.elementRef:this.origin}_attachOverlay(){this._overlayRef?this._overlayRef.getConfig().hasBackdrop=this.hasBackdrop:this._createOverlay(),this._overlayRef.hasAttached()||this._overlayRef.attach(this._templatePortal),this.hasBackdrop?this._backdropSubscription=this._overlayRef.backdropClick().subscribe(e=>{this.backdropClick.emit(e)}):this._backdropSubscription.unsubscribe(),this._positionSubscription.unsubscribe(),this.positionChange.observers.length>0&&(this._positionSubscription=this._position.positionChanges.pipe(function y5(n,t=!1){return qe((e,i)=>{let r=0;e.subscribe(Ue(i,s=>{const o=n(s,r++);(o||t)&&i.next(s),!o&&i.complete()}))})}(()=>this.positionChange.observers.length>0)).subscribe(e=>{this.positionChange.emit(e),0===this.positionChange.observers.length&&this._positionSubscription.unsubscribe()}))}_detachOverlay(){this._overlayRef&&this._overlayRef.detach(),this._backdropSubscription.unsubscribe(),this._positionSubscription.unsubscribe()}}return n.\\u0275fac=function(e){return new(e||n)(f(ni),f(ut),f(st),f(BE),f(On,8))},n.\\u0275dir=C({type:n,selectors:[[\"\",\"cdk-connected-overlay\",\"\"],[\"\",\"connected-overlay\",\"\"],[\"\",\"cdkConnectedOverlay\",\"\"]],inputs:{origin:[\"cdkConnectedOverlayOrigin\",\"origin\"],positions:[\"cdkConnectedOverlayPositions\",\"positions\"],positionStrategy:[\"cdkConnectedOverlayPositionStrategy\",\"positionStrategy\"],offsetX:[\"cdkConnectedOverlayOffsetX\",\"offsetX\"],offsetY:[\"cdkConnectedOverlayOffsetY\",\"offsetY\"],width:[\"cdkConnectedOverlayWidth\",\"width\"],height:[\"cdkConnectedOverlayHeight\",\"height\"],minWidth:[\"cdkConnectedOverlayMinWidth\",\"minWidth\"],minHeight:[\"cdkConnectedOverlayMinHeight\",\"minHeight\"],backdropClass:[\"cdkConnectedOverlayBackdropClass\",\"backdropClass\"],panelClass:[\"cdkConnectedOverlayPanelClass\",\"panelClass\"],viewportMargin:[\"cdkConnectedOverlayViewportMargin\",\"viewportMargin\"],scrollStrategy:[\"cdkConnectedOverlayScrollStrategy\",\"scrollStrategy\"],open:[\"cdkConnectedOverlayOpen\",\"open\"],disableClose:[\"cdkConnectedOverlayDisableClose\",\"disableClose\"],transformOriginSelector:[\"cdkConnectedOverlayTransformOriginOn\",\"transformOriginSelector\"],hasBackdrop:[\"cdkConnectedOverlayHasBackdrop\",\"hasBackdrop\"],lockPosition:[\"cdkConnectedOverlayLockPosition\",\"lockPosition\"],flexibleDimensions:[\"cdkConnectedOverlayFlexibleDimensions\",\"flexibleDimensions\"],growAfterOpen:[\"cdkConnectedOverlayGrowAfterOpen\",\"growAfterOpen\"],push:[\"cdkConnectedOverlayPush\",\"push\"]},outputs:{backdropClick:\"backdropClick\",positionChange:\"positionChange\",attach:\"attach\",detach:\"detach\",overlayKeydown:\"overlayKeydown\",overlayOutsideClick:\"overlayOutsideClick\"},exportAs:[\"cdkConnectedOverlay\"],features:[Je]}),n})();const F5={provide:BE,deps:[ni],useFactory:function P5(n){return()=>n.scrollStrategies.reposition()}};let ji=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[ni,F5],imports:[[lo,Hi,Ud],Ud]}),n})();class nl{constructor(t=!1,e,i=!0){this._multiple=t,this._emitChanges=i,this._selection=new Set,this._deselectedToEmit=[],this._selectedToEmit=[],this.changed=new O,e&&e.length&&(t?e.forEach(r=>this._markSelected(r)):this._markSelected(e[0]),this._selectedToEmit.length=0)}get selected(){return this._selected||(this._selected=Array.from(this._selection.values())),this._selected}select(...t){this._verifyValueAssignment(t),t.forEach(e=>this._markSelected(e)),this._emitChangeEvent()}deselect(...t){this._verifyValueAssignment(t),t.forEach(e=>this._unmarkSelected(e)),this._emitChangeEvent()}toggle(t){this.isSelected(t)?this.deselect(t):this.select(t)}clear(){this._unmarkAll(),this._emitChangeEvent()}isSelected(t){return this._selection.has(t)}isEmpty(){return 0===this._selection.size}hasValue(){return!this.isEmpty()}sort(t){this._multiple&&this.selected&&this._selected.sort(t)}isMultipleSelection(){return this._multiple}_emitChangeEvent(){this._selected=null,(this._selectedToEmit.length||this._deselectedToEmit.length)&&(this.changed.next({source:this,added:this._selectedToEmit,removed:this._deselectedToEmit}),this._deselectedToEmit=[],this._selectedToEmit=[])}_markSelected(t){this.isSelected(t)||(this._multiple||this._unmarkAll(),this._selection.add(t),this._emitChanges&&this._selectedToEmit.push(t))}_unmarkSelected(t){this.isSelected(t)&&(this._selection.delete(t),this._emitChanges&&this._deselectedToEmit.push(t))}_unmarkAll(){this.isEmpty()||this._selection.forEach(t=>this._unmarkSelected(t))}_verifyValueAssignment(t){}}const L5=[\"trigger\"],B5=[\"panel\"];function V5(n,t){if(1&n&&(x(0,\"span\",8),we(1),S()),2&n){const e=Be();T(1),Ut(e.placeholder)}}function H5(n,t){if(1&n&&(x(0,\"span\",12),we(1),S()),2&n){const e=Be(2);T(1),Ut(e.triggerValue)}}function j5(n,t){1&n&&Pe(0,0,[\"*ngSwitchCase\",\"true\"])}function z5(n,t){1&n&&(x(0,\"span\",9),Ee(1,H5,2,1,\"span\",10),Ee(2,j5,1,0,\"ng-content\",11),S()),2&n&&(N(\"ngSwitch\",!!Be().customTrigger),T(2),N(\"ngSwitchCase\",!0))}function U5(n,t){if(1&n){const e=ia();x(0,\"div\",13)(1,\"div\",14,15),J(\"@transformPanel.done\",function(r){return Dr(e),Be()._panelDoneAnimatingStream.next(r.toState)})(\"keydown\",function(r){return Dr(e),Be()._handleKeydown(r)}),Pe(3,1),S()()}if(2&n){const e=Be();N(\"@transformPanelWrap\",void 0),T(1),cC(\"mat-select-panel \",e._getPanelTheme(),\"\"),$n(\"transform-origin\",e._transformOrigin)(\"font-size\",e._triggerFontSize,\"px\"),N(\"ngClass\",e.panelClass)(\"@transformPanel\",e.multiple?\"showing-multiple\":\"showing\"),Z(\"id\",e.id+\"-panel\")(\"aria-multiselectable\",e.multiple)(\"aria-label\",e.ariaLabel||null)(\"aria-labelledby\",e._getPanelAriaLabelledby())}}const $5=[[[\"mat-select-trigger\"]],\"*\"],G5=[\"mat-select-trigger\",\"*\"],UE={transformPanelWrap:Ke(\"transformPanelWrap\",[ge(\"* => void\",no(\"@transformPanel\",[to()],{optional:!0}))]),transformPanel:Ke(\"transformPanel\",[ae(\"void\",R({transform:\"scaleY(0.8)\",minWidth:\"100%\",opacity:0})),ae(\"showing\",R({opacity:1,minWidth:\"calc(100% + 32px)\",transform:\"scaleY(1)\"})),ae(\"showing-multiple\",R({opacity:1,minWidth:\"calc(100% + 64px)\",transform:\"scaleY(1)\"})),ge(\"void => *\",be(\"120ms cubic-bezier(0, 0, 0.2, 1)\")),ge(\"* => void\",be(\"100ms 25ms linear\",R({opacity:0})))])};let $E=0;const WE=new b(\"mat-select-scroll-strategy\"),Q5=new b(\"MAT_SELECT_CONFIG\"),K5={provide:WE,deps:[ni],useFactory:function Y5(n){return()=>n.scrollStrategies.reposition()}};class Z5{constructor(t,e){this.source=t,this.value=e}}const X5=ar(Kr(po(ng(class{constructor(n,t,e,i,r){this._elementRef=n,this._defaultErrorStateMatcher=t,this._parentForm=e,this._parentFormGroup=i,this.ngControl=r}})))),J5=new b(\"MatSelectTrigger\");let e$=(()=>{class n extends X5{constructor(e,i,r,s,o,a,l,c,d,u,h,p,m,g){var _,D,v;super(o,s,l,c,u),this._viewportRuler=e,this._changeDetectorRef=i,this._ngZone=r,this._dir=a,this._parentFormField=d,this._liveAnnouncer=m,this._defaultOptions=g,this._panelOpen=!1,this._compareWith=(M,V)=>M===V,this._uid=\"mat-select-\"+$E++,this._triggerAriaLabelledBy=null,this._destroy=new O,this._onChange=()=>{},this._onTouched=()=>{},this._valueId=\"mat-select-value-\"+$E++,this._panelDoneAnimatingStream=new O,this._overlayPanelClass=(null===(_=this._defaultOptions)||void 0===_?void 0:_.overlayPanelClass)||\"\",this._focused=!1,this.controlType=\"mat-select\",this._multiple=!1,this._disableOptionCentering=null!==(v=null===(D=this._defaultOptions)||void 0===D?void 0:D.disableOptionCentering)&&void 0!==v&&v,this.ariaLabel=\"\",this.optionSelectionChanges=xa(()=>{const M=this.options;return M?M.changes.pipe(Xn(M),kn(()=>Bt(...M.map(V=>V.onSelectionChange)))):this._ngZone.onStable.pipe(it(1),kn(()=>this.optionSelectionChanges))}),this.openedChange=new $,this._openedStream=this.openedChange.pipe(Ct(M=>M),ue(()=>{})),this._closedStream=this.openedChange.pipe(Ct(M=>!M),ue(()=>{})),this.selectionChange=new $,this.valueChange=new $,this.ngControl&&(this.ngControl.valueAccessor=this),null!=(null==g?void 0:g.typeaheadDebounceInterval)&&(this._typeaheadDebounceInterval=g.typeaheadDebounceInterval),this._scrollStrategyFactory=p,this._scrollStrategy=this._scrollStrategyFactory(),this.tabIndex=parseInt(h)||0,this.id=this.id}get focused(){return this._focused||this._panelOpen}get placeholder(){return this._placeholder}set placeholder(e){this._placeholder=e,this.stateChanges.next()}get required(){var e,i,r,s;return null!==(s=null!==(e=this._required)&&void 0!==e?e:null===(r=null===(i=this.ngControl)||void 0===i?void 0:i.control)||void 0===r?void 0:r.hasValidator(yi.required))&&void 0!==s&&s}set required(e){this._required=G(e),this.stateChanges.next()}get multiple(){return this._multiple}set multiple(e){this._multiple=G(e)}get disableOptionCentering(){return this._disableOptionCentering}set disableOptionCentering(e){this._disableOptionCentering=G(e)}get compareWith(){return this._compareWith}set compareWith(e){this._compareWith=e,this._selectionModel&&this._initializeSelection()}get value(){return this._value}set value(e){(e!==this._value||this._multiple&&Array.isArray(e))&&(this.options&&this._setSelectionByValue(e),this._value=e)}get typeaheadDebounceInterval(){return this._typeaheadDebounceInterval}set typeaheadDebounceInterval(e){this._typeaheadDebounceInterval=Et(e)}get id(){return this._id}set id(e){this._id=e||this._uid,this.stateChanges.next()}ngOnInit(){this._selectionModel=new nl(this.multiple),this.stateChanges.next(),this._panelDoneAnimatingStream.pipe(Gx(),Ie(this._destroy)).subscribe(()=>this._panelDoneAnimating(this.panelOpen))}ngAfterContentInit(){this._initKeyManager(),this._selectionModel.changed.pipe(Ie(this._destroy)).subscribe(e=>{e.added.forEach(i=>i.select()),e.removed.forEach(i=>i.deselect())}),this.options.changes.pipe(Xn(null),Ie(this._destroy)).subscribe(()=>{this._resetOptions(),this._initializeSelection()})}ngDoCheck(){const e=this._getTriggerAriaLabelledby(),i=this.ngControl;if(e!==this._triggerAriaLabelledBy){const r=this._elementRef.nativeElement;this._triggerAriaLabelledBy=e,e?r.setAttribute(\"aria-labelledby\",e):r.removeAttribute(\"aria-labelledby\")}i&&(this._previousControl!==i.control&&(void 0!==this._previousControl&&null!==i.disabled&&i.disabled!==this.disabled&&(this.disabled=i.disabled),this._previousControl=i.control),this.updateErrorState())}ngOnChanges(e){e.disabled&&this.stateChanges.next(),e.typeaheadDebounceInterval&&this._keyManager&&this._keyManager.withTypeAhead(this._typeaheadDebounceInterval)}ngOnDestroy(){this._destroy.next(),this._destroy.complete(),this.stateChanges.complete()}toggle(){this.panelOpen?this.close():this.open()}open(){this._canOpen()&&(this._panelOpen=!0,this._keyManager.withHorizontalOrientation(null),this._highlightCorrectOption(),this._changeDetectorRef.markForCheck())}close(){this._panelOpen&&(this._panelOpen=!1,this._keyManager.withHorizontalOrientation(this._isRtl()?\"rtl\":\"ltr\"),this._changeDetectorRef.markForCheck(),this._onTouched())}writeValue(e){this.value=e}registerOnChange(e){this._onChange=e}registerOnTouched(e){this._onTouched=e}setDisabledState(e){this.disabled=e,this._changeDetectorRef.markForCheck(),this.stateChanges.next()}get panelOpen(){return this._panelOpen}get selected(){var e,i;return this.multiple?(null===(e=this._selectionModel)||void 0===e?void 0:e.selected)||[]:null===(i=this._selectionModel)||void 0===i?void 0:i.selected[0]}get triggerValue(){if(this.empty)return\"\";if(this._multiple){const e=this._selectionModel.selected.map(i=>i.viewValue);return this._isRtl()&&e.reverse(),e.join(\", \")}return this._selectionModel.selected[0].viewValue}_isRtl(){return!!this._dir&&\"rtl\"===this._dir.value}_handleKeydown(e){this.disabled||(this.panelOpen?this._handleOpenKeydown(e):this._handleClosedKeydown(e))}_handleClosedKeydown(e){const i=e.keyCode,r=40===i||38===i||37===i||39===i,s=13===i||32===i,o=this._keyManager;if(!o.isTyping()&&s&&!Xt(e)||(this.multiple||e.altKey)&&r)e.preventDefault(),this.open();else if(!this.multiple){const a=this.selected;o.onKeydown(e);const l=this.selected;l&&a!==l&&this._liveAnnouncer.announce(l.viewValue,1e4)}}_handleOpenKeydown(e){const i=this._keyManager,r=e.keyCode,s=40===r||38===r,o=i.isTyping();if(s&&e.altKey)e.preventDefault(),this.close();else if(o||13!==r&&32!==r||!i.activeItem||Xt(e))if(!o&&this._multiple&&65===r&&e.ctrlKey){e.preventDefault();const a=this.options.some(l=>!l.disabled&&!l.selected);this.options.forEach(l=>{l.disabled||(a?l.select():l.deselect())})}else{const a=i.activeItemIndex;i.onKeydown(e),this._multiple&&s&&e.shiftKey&&i.activeItem&&i.activeItemIndex!==a&&i.activeItem._selectViaInteraction()}else e.preventDefault(),i.activeItem._selectViaInteraction()}_onFocus(){this.disabled||(this._focused=!0,this.stateChanges.next())}_onBlur(){this._focused=!1,!this.disabled&&!this.panelOpen&&(this._onTouched(),this._changeDetectorRef.markForCheck(),this.stateChanges.next())}_onAttached(){this._overlayDir.positionChange.pipe(it(1)).subscribe(()=>{this._changeDetectorRef.detectChanges(),this._positioningSettled()})}_getPanelTheme(){return this._parentFormField?`mat-${this._parentFormField.color}`:\"\"}get empty(){return!this._selectionModel||this._selectionModel.isEmpty()}_initializeSelection(){Promise.resolve().then(()=>{this.ngControl&&(this._value=this.ngControl.value),this._setSelectionByValue(this._value),this.stateChanges.next()})}_setSelectionByValue(e){if(this._selectionModel.selected.forEach(i=>i.setInactiveStyles()),this._selectionModel.clear(),this.multiple&&e)Array.isArray(e),e.forEach(i=>this._selectValue(i)),this._sortValues();else{const i=this._selectValue(e);i?this._keyManager.updateActiveItem(i):this.panelOpen||this._keyManager.updateActiveItem(-1)}this._changeDetectorRef.markForCheck()}_selectValue(e){const i=this.options.find(r=>{if(this._selectionModel.isSelected(r))return!1;try{return null!=r.value&&this._compareWith(r.value,e)}catch(s){return!1}});return i&&this._selectionModel.select(i),i}_initKeyManager(){this._keyManager=new c3(this.options).withTypeAhead(this._typeaheadDebounceInterval).withVerticalOrientation().withHorizontalOrientation(this._isRtl()?\"rtl\":\"ltr\").withHomeAndEnd().withAllowedModifierKeys([\"shiftKey\"]),this._keyManager.tabOut.pipe(Ie(this._destroy)).subscribe(()=>{this.panelOpen&&(!this.multiple&&this._keyManager.activeItem&&this._keyManager.activeItem._selectViaInteraction(),this.focus(),this.close())}),this._keyManager.change.pipe(Ie(this._destroy)).subscribe(()=>{this._panelOpen&&this.panel?this._scrollOptionIntoView(this._keyManager.activeItemIndex||0):!this._panelOpen&&!this.multiple&&this._keyManager.activeItem&&this._keyManager.activeItem._selectViaInteraction()})}_resetOptions(){const e=Bt(this.options.changes,this._destroy);this.optionSelectionChanges.pipe(Ie(e)).subscribe(i=>{this._onSelect(i.source,i.isUserInput),i.isUserInput&&!this.multiple&&this._panelOpen&&(this.close(),this.focus())}),Bt(...this.options.map(i=>i._stateChanges)).pipe(Ie(e)).subscribe(()=>{this._changeDetectorRef.markForCheck(),this.stateChanges.next()})}_onSelect(e,i){const r=this._selectionModel.isSelected(e);null!=e.value||this._multiple?(r!==e.selected&&(e.selected?this._selectionModel.select(e):this._selectionModel.deselect(e)),i&&this._keyManager.setActiveItem(e),this.multiple&&(this._sortValues(),i&&this.focus())):(e.deselect(),this._selectionModel.clear(),null!=this.value&&this._propagateChanges(e.value)),r!==this._selectionModel.isSelected(e)&&this._propagateChanges(),this.stateChanges.next()}_sortValues(){if(this.multiple){const e=this.options.toArray();this._selectionModel.sort((i,r)=>this.sortComparator?this.sortComparator(i,r,e):e.indexOf(i)-e.indexOf(r)),this.stateChanges.next()}}_propagateChanges(e){let i=null;i=this.multiple?this.selected.map(r=>r.value):this.selected?this.selected.value:e,this._value=i,this.valueChange.emit(i),this._onChange(i),this.selectionChange.emit(this._getChangeEvent(i)),this._changeDetectorRef.markForCheck()}_highlightCorrectOption(){this._keyManager&&(this.empty?this._keyManager.setFirstItemActive():this._keyManager.setActiveItem(this._selectionModel.selected[0]))}_canOpen(){var e;return!this._panelOpen&&!this.disabled&&(null===(e=this.options)||void 0===e?void 0:e.length)>0}focus(e){this._elementRef.nativeElement.focus(e)}_getPanelAriaLabelledby(){var e;if(this.ariaLabel)return null;const i=null===(e=this._parentFormField)||void 0===e?void 0:e.getLabelId();return this.ariaLabelledby?(i?i+\" \":\"\")+this.ariaLabelledby:i}_getAriaActiveDescendant(){return this.panelOpen&&this._keyManager&&this._keyManager.activeItem?this._keyManager.activeItem.id:null}_getTriggerAriaLabelledby(){var e;if(this.ariaLabel)return null;const i=null===(e=this._parentFormField)||void 0===e?void 0:e.getLabelId();let r=(i?i+\" \":\"\")+this._valueId;return this.ariaLabelledby&&(r+=\" \"+this.ariaLabelledby),r}_panelDoneAnimating(e){this.openedChange.emit(e)}setDescribedByIds(e){this._ariaDescribedby=e.join(\" \")}onContainerClick(){this.focus(),this.open()}get shouldLabelFloat(){return this._panelOpen||!this.empty||this._focused&&!!this._placeholder}}return n.\\u0275fac=function(e){return new(e||n)(f(es),f(Ye),f(ne),f(mo),f(W),f(On,8),f(oo,8),f(ao,8),f(el,8),f(Jn,10),kt(\"tabindex\"),f(WE),f(k3),f(Q5,8))},n.\\u0275dir=C({type:n,viewQuery:function(e,i){if(1&e&&(je(L5,5),je(B5,5),je(HE,5)),2&e){let r;z(r=U())&&(i.trigger=r.first),z(r=U())&&(i.panel=r.first),z(r=U())&&(i._overlayDir=r.first)}},inputs:{panelClass:\"panelClass\",placeholder:\"placeholder\",required:\"required\",multiple:\"multiple\",disableOptionCentering:\"disableOptionCentering\",compareWith:\"compareWith\",value:\"value\",ariaLabel:[\"aria-label\",\"ariaLabel\"],ariaLabelledby:[\"aria-labelledby\",\"ariaLabelledby\"],errorStateMatcher:\"errorStateMatcher\",typeaheadDebounceInterval:\"typeaheadDebounceInterval\",sortComparator:\"sortComparator\",id:\"id\"},outputs:{openedChange:\"openedChange\",_openedStream:\"opened\",_closedStream:\"closed\",selectionChange:\"selectionChange\",valueChange:\"valueChange\"},features:[E,Je]}),n})(),t$=(()=>{class n extends e${constructor(){super(...arguments),this._scrollTop=0,this._triggerFontSize=0,this._transformOrigin=\"top\",this._offsetY=0,this._positions=[{originX:\"start\",originY:\"top\",overlayX:\"start\",overlayY:\"top\"},{originX:\"start\",originY:\"bottom\",overlayX:\"start\",overlayY:\"bottom\"}]}_calculateOverlayScroll(e,i,r){const s=this._getItemHeight();return Math.min(Math.max(0,s*e-i+s/2),r)}ngOnInit(){super.ngOnInit(),this._viewportRuler.change().pipe(Ie(this._destroy)).subscribe(()=>{this.panelOpen&&(this._triggerRect=this.trigger.nativeElement.getBoundingClientRect(),this._changeDetectorRef.markForCheck())})}open(){super._canOpen()&&(super.open(),this._triggerRect=this.trigger.nativeElement.getBoundingClientRect(),this._triggerFontSize=parseInt(getComputedStyle(this.trigger.nativeElement).fontSize||\"0\"),this._calculateOverlayPosition(),this._ngZone.onStable.pipe(it(1)).subscribe(()=>{this._triggerFontSize&&this._overlayDir.overlayRef&&this._overlayDir.overlayRef.overlayElement&&(this._overlayDir.overlayRef.overlayElement.style.fontSize=`${this._triggerFontSize}px`)}))}_scrollOptionIntoView(e){const i=cg(e,this.options,this.optionGroups),r=this._getItemHeight();this.panel.nativeElement.scrollTop=0===e&&1===i?0:function pE(n,t,e,i){return n<e?n:n+t>e+i?Math.max(0,n-i+t):e}((e+i)*r,r,this.panel.nativeElement.scrollTop,256)}_positioningSettled(){this._calculateOverlayOffsetX(),this.panel.nativeElement.scrollTop=this._scrollTop}_panelDoneAnimating(e){this.panelOpen?this._scrollTop=0:(this._overlayDir.offsetX=0,this._changeDetectorRef.markForCheck()),super._panelDoneAnimating(e)}_getChangeEvent(e){return new Z5(this,e)}_calculateOverlayOffsetX(){const e=this._overlayDir.overlayRef.overlayElement.getBoundingClientRect(),i=this._viewportRuler.getViewportSize(),r=this._isRtl(),s=this.multiple?56:32;let o;if(this.multiple)o=40;else if(this.disableOptionCentering)o=16;else{let c=this._selectionModel.selected[0]||this.options.first;o=c&&c.group?32:16}r||(o*=-1);const a=0-(e.left+o-(r?s:0)),l=e.right+o-i.width+(r?0:s);a>0?o+=a+8:l>0&&(o-=l+8),this._overlayDir.offsetX=Math.round(o),this._overlayDir.overlayRef.updatePosition()}_calculateOverlayOffsetY(e,i,r){const s=this._getItemHeight(),o=(s-this._triggerRect.height)/2,a=Math.floor(256/s);let l;return this.disableOptionCentering?0:(l=0===this._scrollTop?e*s:this._scrollTop===r?(e-(this._getItemCount()-a))*s+(s-(this._getItemCount()*s-256)%s):i-s/2,Math.round(-1*l-o))}_checkOverlayWithinViewport(e){const i=this._getItemHeight(),r=this._viewportRuler.getViewportSize(),s=this._triggerRect.top-8,o=r.height-this._triggerRect.bottom-8,a=Math.abs(this._offsetY),c=Math.min(this._getItemCount()*i,256)-a-this._triggerRect.height;c>o?this._adjustPanelUp(c,o):a>s?this._adjustPanelDown(a,s,e):this._transformOrigin=this._getOriginBasedOnOption()}_adjustPanelUp(e,i){const r=Math.round(e-i);this._scrollTop-=r,this._offsetY-=r,this._transformOrigin=this._getOriginBasedOnOption(),this._scrollTop<=0&&(this._scrollTop=0,this._offsetY=0,this._transformOrigin=\"50% bottom 0px\")}_adjustPanelDown(e,i,r){const s=Math.round(e-i);if(this._scrollTop+=s,this._offsetY+=s,this._transformOrigin=this._getOriginBasedOnOption(),this._scrollTop>=r)return this._scrollTop=r,this._offsetY=0,void(this._transformOrigin=\"50% top 0px\")}_calculateOverlayPosition(){const e=this._getItemHeight(),i=this._getItemCount(),r=Math.min(i*e,256),o=i*e-r;let a;a=this.empty?0:Math.max(this.options.toArray().indexOf(this._selectionModel.selected[0]),0),a+=cg(a,this.options,this.optionGroups);const l=r/2;this._scrollTop=this._calculateOverlayScroll(a,l,o),this._offsetY=this._calculateOverlayOffsetY(a,l,o),this._checkOverlayWithinViewport(o)}_getOriginBasedOnOption(){const e=this._getItemHeight(),i=(e-this._triggerRect.height)/2;return`50% ${Math.abs(this._offsetY)-i+e/2}px 0px`}_getItemHeight(){return 3*this._triggerFontSize}_getItemCount(){return this.options.length+this.optionGroups.length}}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275cmp=xe({type:n,selectors:[[\"mat-select\"]],contentQueries:function(e,i,r){if(1&e&&(ve(r,J5,5),ve(r,hE,5),ve(r,lg,5)),2&e){let s;z(s=U())&&(i.customTrigger=s.first),z(s=U())&&(i.options=s),z(s=U())&&(i.optionGroups=s)}},hostAttrs:[\"role\",\"combobox\",\"aria-autocomplete\",\"none\",\"aria-haspopup\",\"true\",1,\"mat-select\"],hostVars:20,hostBindings:function(e,i){1&e&&J(\"keydown\",function(s){return i._handleKeydown(s)})(\"focus\",function(){return i._onFocus()})(\"blur\",function(){return i._onBlur()}),2&e&&(Z(\"id\",i.id)(\"tabindex\",i.tabIndex)(\"aria-controls\",i.panelOpen?i.id+\"-panel\":null)(\"aria-expanded\",i.panelOpen)(\"aria-label\",i.ariaLabel||null)(\"aria-required\",i.required.toString())(\"aria-disabled\",i.disabled.toString())(\"aria-invalid\",i.errorState)(\"aria-describedby\",i._ariaDescribedby||null)(\"aria-activedescendant\",i._getAriaActiveDescendant()),Ae(\"mat-select-disabled\",i.disabled)(\"mat-select-invalid\",i.errorState)(\"mat-select-required\",i.required)(\"mat-select-empty\",i.empty)(\"mat-select-multiple\",i.multiple))},inputs:{disabled:\"disabled\",disableRipple:\"disableRipple\",tabIndex:\"tabIndex\"},exportAs:[\"matSelect\"],features:[L([{provide:Ja,useExisting:n},{provide:ag,useExisting:n}]),E],ngContentSelectors:G5,decls:9,vars:12,consts:[[\"cdk-overlay-origin\",\"\",1,\"mat-select-trigger\",3,\"click\"],[\"origin\",\"cdkOverlayOrigin\",\"trigger\",\"\"],[1,\"mat-select-value\",3,\"ngSwitch\"],[\"class\",\"mat-select-placeholder mat-select-min-line\",4,\"ngSwitchCase\"],[\"class\",\"mat-select-value-text\",3,\"ngSwitch\",4,\"ngSwitchCase\"],[1,\"mat-select-arrow-wrapper\"],[1,\"mat-select-arrow\"],[\"cdk-connected-overlay\",\"\",\"cdkConnectedOverlayLockPosition\",\"\",\"cdkConnectedOverlayHasBackdrop\",\"\",\"cdkConnectedOverlayBackdropClass\",\"cdk-overlay-transparent-backdrop\",3,\"cdkConnectedOverlayPanelClass\",\"cdkConnectedOverlayScrollStrategy\",\"cdkConnectedOverlayOrigin\",\"cdkConnectedOverlayOpen\",\"cdkConnectedOverlayPositions\",\"cdkConnectedOverlayMinWidth\",\"cdkConnectedOverlayOffsetY\",\"backdropClick\",\"attach\",\"detach\"],[1,\"mat-select-placeholder\",\"mat-select-min-line\"],[1,\"mat-select-value-text\",3,\"ngSwitch\"],[\"class\",\"mat-select-min-line\",4,\"ngSwitchDefault\"],[4,\"ngSwitchCase\"],[1,\"mat-select-min-line\"],[1,\"mat-select-panel-wrap\"],[\"role\",\"listbox\",\"tabindex\",\"-1\",3,\"ngClass\",\"keydown\"],[\"panel\",\"\"]],template:function(e,i){if(1&e&&(Lt($5),x(0,\"div\",0,1),J(\"click\",function(){return i.toggle()}),x(3,\"div\",2),Ee(4,V5,2,1,\"span\",3),Ee(5,z5,3,2,\"span\",4),S(),x(6,\"div\",5),Le(7,\"div\",6),S()(),Ee(8,U5,4,14,\"ng-template\",7),J(\"backdropClick\",function(){return i.close()})(\"attach\",function(){return i._onAttached()})(\"detach\",function(){return i.close()})),2&e){const r=wn(1);Z(\"aria-owns\",i.panelOpen?i.id+\"-panel\":null),T(3),N(\"ngSwitch\",i.empty),Z(\"id\",i._valueId),T(1),N(\"ngSwitchCase\",!0),T(1),N(\"ngSwitchCase\",!1),T(3),N(\"cdkConnectedOverlayPanelClass\",i._overlayPanelClass)(\"cdkConnectedOverlayScrollStrategy\",i._scrollStrategy)(\"cdkConnectedOverlayOrigin\",r)(\"cdkConnectedOverlayOpen\",i.panelOpen)(\"cdkConnectedOverlayPositions\",i._positions)(\"cdkConnectedOverlayMinWidth\",null==i._triggerRect?null:i._triggerRect.width)(\"cdkConnectedOverlayOffsetY\",i._offsetY)}},directives:[VE,Ys,Pc,yD,HE,mD],styles:['.mat-select{display:inline-block;width:100%;outline:none}.mat-select-trigger{display:inline-table;cursor:pointer;position:relative;box-sizing:border-box}.mat-select-disabled .mat-select-trigger{-webkit-user-select:none;-moz-user-select:none;user-select:none;cursor:default}.mat-select-value{display:table-cell;max-width:0;width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mat-select-value-text{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.mat-select-arrow-wrapper{display:table-cell;vertical-align:middle}.mat-form-field-appearance-fill .mat-select-arrow-wrapper{transform:translateY(-50%)}.mat-form-field-appearance-outline .mat-select-arrow-wrapper{transform:translateY(-25%)}.mat-form-field-appearance-standard.mat-form-field-has-label .mat-select:not(.mat-select-empty) .mat-select-arrow-wrapper{transform:translateY(-50%)}.mat-form-field-appearance-standard .mat-select.mat-select-empty .mat-select-arrow-wrapper{transition:transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1)}._mat-animation-noopable.mat-form-field-appearance-standard .mat-select.mat-select-empty .mat-select-arrow-wrapper{transition:none}.mat-select-arrow{width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;border-top:5px solid;margin:0 4px}.mat-form-field.mat-focused .mat-select-arrow{transform:translateX(0)}.mat-select-panel-wrap{flex-basis:100%}.mat-select-panel{min-width:112px;max-width:280px;overflow:auto;-webkit-overflow-scrolling:touch;padding-top:0;padding-bottom:0;max-height:256px;min-width:100%;border-radius:4px;outline:0}.cdk-high-contrast-active .mat-select-panel{outline:solid 1px}.mat-select-panel .mat-optgroup-label,.mat-select-panel .mat-option{font-size:inherit;line-height:3em;height:3em}.mat-form-field-type-mat-select:not(.mat-form-field-disabled) .mat-form-field-flex{cursor:pointer}.mat-form-field-type-mat-select .mat-form-field-label{width:calc(100% - 18px)}.mat-select-placeholder{transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}._mat-animation-noopable .mat-select-placeholder{transition:none}.mat-form-field-hide-placeholder .mat-select-placeholder{color:transparent;-webkit-text-fill-color:transparent;transition:none;display:block}.mat-select-min-line:empty::before{content:\" \";white-space:pre;width:1px;display:inline-block;opacity:0}\\n'],encapsulation:2,data:{animation:[UE.transformPanelWrap,UE.transformPanel]},changeDetection:0}),n})(),qE=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[K5],imports:[[bt,ji,Hd,B],Ci,mg,Hd,B]}),n})();const YE=ei({passive:!0});let n$=(()=>{class n{constructor(e,i){this._platform=e,this._ngZone=i,this._monitoredElements=new Map}monitor(e){if(!this._platform.isBrowser)return ri;const i=at(e),r=this._monitoredElements.get(i);if(r)return r.subject;const s=new O,o=\"cdk-text-field-autofilled\",a=l=>{\"cdk-text-field-autofill-start\"!==l.animationName||i.classList.contains(o)?\"cdk-text-field-autofill-end\"===l.animationName&&i.classList.contains(o)&&(i.classList.remove(o),this._ngZone.run(()=>s.next({target:l.target,isAutofilled:!1}))):(i.classList.add(o),this._ngZone.run(()=>s.next({target:l.target,isAutofilled:!0})))};return this._ngZone.runOutsideAngular(()=>{i.addEventListener(\"animationstart\",a,YE),i.classList.add(\"cdk-text-field-autofill-monitored\")}),this._monitoredElements.set(i,{subject:s,unlisten:()=>{i.removeEventListener(\"animationstart\",a,YE)}}),s}stopMonitoring(e){const i=at(e),r=this._monitoredElements.get(i);r&&(r.unlisten(),r.subject.complete(),i.classList.remove(\"cdk-text-field-autofill-monitored\"),i.classList.remove(\"cdk-text-field-autofilled\"),this._monitoredElements.delete(i))}ngOnDestroy(){this._monitoredElements.forEach((e,i)=>this.stopMonitoring(i))}}return n.\\u0275fac=function(e){return new(e||n)(y(It),y(ne))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),QE=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const KE=new b(\"MAT_INPUT_VALUE_ACCESSOR\"),i$=[\"button\",\"checkbox\",\"file\",\"hidden\",\"image\",\"radio\",\"range\",\"reset\",\"submit\"];let r$=0;const s$=ng(class{constructor(n,t,e,i){this._defaultErrorStateMatcher=n,this._parentForm=t,this._parentFormGroup=e,this.ngControl=i}});let o$=(()=>{class n extends s${constructor(e,i,r,s,o,a,l,c,d,u){super(a,s,o,r),this._elementRef=e,this._platform=i,this._autofillMonitor=c,this._formField=u,this._uid=\"mat-input-\"+r$++,this.focused=!1,this.stateChanges=new O,this.controlType=\"mat-input\",this.autofilled=!1,this._disabled=!1,this._type=\"text\",this._readonly=!1,this._neverEmptyInputTypes=[\"date\",\"datetime\",\"datetime-local\",\"month\",\"time\",\"week\"].filter(m=>Hx().has(m));const h=this._elementRef.nativeElement,p=h.nodeName.toLowerCase();this._inputValueAccessor=l||h,this._previousNativeValue=this.value,this.id=this.id,i.IOS&&d.runOutsideAngular(()=>{e.nativeElement.addEventListener(\"keyup\",m=>{const g=m.target;!g.value&&0===g.selectionStart&&0===g.selectionEnd&&(g.setSelectionRange(1,1),g.setSelectionRange(0,0))})}),this._isServer=!this._platform.isBrowser,this._isNativeSelect=\"select\"===p,this._isTextarea=\"textarea\"===p,this._isInFormField=!!u,this._isNativeSelect&&(this.controlType=h.multiple?\"mat-native-select-multiple\":\"mat-native-select\")}get disabled(){return this.ngControl&&null!==this.ngControl.disabled?this.ngControl.disabled:this._disabled}set disabled(e){this._disabled=G(e),this.focused&&(this.focused=!1,this.stateChanges.next())}get id(){return this._id}set id(e){this._id=e||this._uid}get required(){var e,i,r,s;return null!==(s=null!==(e=this._required)&&void 0!==e?e:null===(r=null===(i=this.ngControl)||void 0===i?void 0:i.control)||void 0===r?void 0:r.hasValidator(yi.required))&&void 0!==s&&s}set required(e){this._required=G(e)}get type(){return this._type}set type(e){this._type=e||\"text\",this._validateType(),!this._isTextarea&&Hx().has(this._type)&&(this._elementRef.nativeElement.type=this._type)}get value(){return this._inputValueAccessor.value}set value(e){e!==this.value&&(this._inputValueAccessor.value=e,this.stateChanges.next())}get readonly(){return this._readonly}set readonly(e){this._readonly=G(e)}ngAfterViewInit(){this._platform.isBrowser&&this._autofillMonitor.monitor(this._elementRef.nativeElement).subscribe(e=>{this.autofilled=e.isAutofilled,this.stateChanges.next()})}ngOnChanges(){this.stateChanges.next()}ngOnDestroy(){this.stateChanges.complete(),this._platform.isBrowser&&this._autofillMonitor.stopMonitoring(this._elementRef.nativeElement)}ngDoCheck(){this.ngControl&&this.updateErrorState(),this._dirtyCheckNativeValue(),this._dirtyCheckPlaceholder()}focus(e){this._elementRef.nativeElement.focus(e)}_focusChanged(e){e!==this.focused&&(this.focused=e,this.stateChanges.next())}_onInput(){}_dirtyCheckPlaceholder(){var e,i;const r=(null===(i=null===(e=this._formField)||void 0===e?void 0:e._hideControlPlaceholder)||void 0===i?void 0:i.call(e))?null:this.placeholder;if(r!==this._previousPlaceholder){const s=this._elementRef.nativeElement;this._previousPlaceholder=r,r?s.setAttribute(\"placeholder\",r):s.removeAttribute(\"placeholder\")}}_dirtyCheckNativeValue(){const e=this._elementRef.nativeElement.value;this._previousNativeValue!==e&&(this._previousNativeValue=e,this.stateChanges.next())}_validateType(){i$.indexOf(this._type)}_isNeverEmpty(){return this._neverEmptyInputTypes.indexOf(this._type)>-1}_isBadInput(){let e=this._elementRef.nativeElement.validity;return e&&e.badInput}get empty(){return!(this._isNeverEmpty()||this._elementRef.nativeElement.value||this._isBadInput()||this.autofilled)}get shouldLabelFloat(){if(this._isNativeSelect){const e=this._elementRef.nativeElement,i=e.options[0];return this.focused||e.multiple||!this.empty||!!(e.selectedIndex>-1&&i&&i.label)}return this.focused||!this.empty}setDescribedByIds(e){e.length?this._elementRef.nativeElement.setAttribute(\"aria-describedby\",e.join(\" \")):this._elementRef.nativeElement.removeAttribute(\"aria-describedby\")}onContainerClick(){this.focused||this.focus()}_isInlineSelect(){const e=this._elementRef.nativeElement;return this._isNativeSelect&&(e.multiple||e.size>1)}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(It),f(Jn,10),f(oo,8),f(ao,8),f(mo),f(KE,10),f(n$),f(ne),f(el,8))},n.\\u0275dir=C({type:n,selectors:[[\"input\",\"matInput\",\"\"],[\"textarea\",\"matInput\",\"\"],[\"select\",\"matNativeControl\",\"\"],[\"input\",\"matNativeControl\",\"\"],[\"textarea\",\"matNativeControl\",\"\"]],hostAttrs:[1,\"mat-input-element\",\"mat-form-field-autofill-control\"],hostVars:12,hostBindings:function(e,i){1&e&&J(\"focus\",function(){return i._focusChanged(!0)})(\"blur\",function(){return i._focusChanged(!1)})(\"input\",function(){return i._onInput()}),2&e&&(Yn(\"disabled\",i.disabled)(\"required\",i.required),Z(\"id\",i.id)(\"data-placeholder\",i.placeholder)(\"name\",i.name||null)(\"readonly\",i.readonly&&!i._isNativeSelect||null)(\"aria-invalid\",i.empty&&i.required?null:i.errorState)(\"aria-required\",i.required),Ae(\"mat-input-server\",i._isServer)(\"mat-native-select-inline\",i._isInlineSelect()))},inputs:{disabled:\"disabled\",id:\"id\",placeholder:\"placeholder\",name:\"name\",required:\"required\",type:\"type\",errorStateMatcher:\"errorStateMatcher\",userAriaDescribedBy:[\"aria-describedby\",\"userAriaDescribedBy\"],value:\"value\",readonly:\"readonly\"},exportAs:[\"matInput\"],features:[L([{provide:Ja,useExisting:n}]),E,Je]}),n})(),a$=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[mo],imports:[[QE,mg,B],QE,mg]}),n})();function l$(n,t){if(1&n&&(x(0,\"mat-option\",13),we(1),S()),2&n){const e=t.$implicit;N(\"value\",e.name)(\"disabled\",e.disabled),T(1),Ut(e.description)}}function c$(n,t){if(1&n&&(x(0,\"mat-option\",13),we(1),S()),2&n){const e=t.$implicit,i=t.index;N(\"value\",e)(\"disabled\",i>0),T(1),Ut(e)}}function d$(n,t){if(1&n&&(x(0,\"mat-error\"),we(1),S()),2&n){const e=Be();T(1),Ut(e.explainTheError(e.srcAmountControl))}}function u$(n,t){if(1&n&&(x(0,\"mat-option\",13),we(1),S()),2&n){const e=t.$implicit;N(\"value\",e.name)(\"disabled\",e.disabled),T(1),Ut(e.description)}}function h$(n,t){if(1&n&&(x(0,\"mat-option\",13),we(1),S()),2&n){const e=t.$implicit,i=t.index;N(\"value\",e)(\"disabled\",i>0),T(1),Ut(e)}}function p$(n,t){if(1&n&&(x(0,\"mat-error\"),we(1),S()),2&n){const e=Be();T(1),Ut(e.explainTheError(e.dstAmountControl))}}let f$=(()=>{class n{constructor(){var e,i;this.srcAmountControl=new Rd(\"0\",[yi.pattern(/\\d+/),yi.min(1),yi.max(9999)]),this.dstAmountControl=new Rd(\"0\",[yi.pattern(/\\d+/),yi.min(1),yi.max(9999)]),this.srcChainList=Xa.map(r=>Object.assign(Object.assign({},r.from),{disabled:!r.active})),this.dstChainList=Xa.map(r=>Object.assign(Object.assign({},r.to),{disabled:!r.active})),this.srcChain=null===(e=this.srcChainList.find(r=>!r.disabled))||void 0===e?void 0:e.name,this.dstChain=(null===(i=Xa.filter(r=>r.from.name===this.srcChain).find(r=>r.active))||void 0===i?void 0:i.to.name)||\"\",this.srcCoin=\"EVER\",this.dstCoin=\"TXZ\",this.srcTokenList=ug.map(r=>r.name),this.dstTokenList=hg.map(r=>r.name),this.srcTokenChosen=\"EVER\",this.dstTokenChosen=\"wEVER\",this.srcAmount=\"0\",this.dstAmount=\"0\"}ngOnInit(){this.breakpoint=window.innerWidth<=400?1:2}onChainSrcValueChange(e){var i;this.srcChain=e,this.dstChain=(null===(i=Xa.filter(r=>r.from.name===this.srcChain).find(r=>r.active))||void 0===i?void 0:i.to.name)||\"\",this.changeTokenList(this.srcChain,this.dstChain)}onChainDstValueChange(e){var i;this.dstChain=e,this.srcChain=(null===(i=Xa.filter(r=>r.from.name===this.srcChain).find(r=>r.active))||void 0===i?void 0:i.to.name)||\"\",this.changeTokenList(this.srcChain,this.dstChain)}changeTokenList(e,i){\"Tezos\"==e&&(this.srcCoin=\"TXZ\",this.dstCoin=\"EVER\",this.srcTokenList=hg.map(r=>r.name),this.dstTokenList=ug.map(r=>r.name),this.srcTokenChosen=\"TXZ\",this.dstTokenChosen=\"wTXZ\"),\"Everscale\"===e&&(this.srcCoin=\"EVER\",this.dstCoin=\"TXZ\",this.srcTokenList=ug.map(r=>r.name),this.dstTokenList=hg.map(r=>r.name),this.srcTokenChosen=\"EVER\",this.dstTokenChosen=\"wEVER\")}onSelectionChange(e){console.log(\"onSelectionChange, newValue = \",e.value,e.source)}onSrcTokenChange(e){this.dstTokenChosen=e===this.srcTokenList[0]?this.dstCoin:this.dstTokenList[0]}onDstTokenChange(e){this.srcTokenChosen=e===this.dstTokenList[0]?this.srcCoin:this.srcTokenList[0]}calculateAmount(e,i){e?(this.dstAmount=(.99*Number.parseFloat(i)).toFixed(8).replace(/(\\.\\d*)0+/,\"$1\"),this.dstAmountControl.setValue(this.dstAmount)):(this.srcAmount=(Number.parseFloat(i)/.99).toFixed(8).replace(/\\.0+$/,\"\"),this.srcAmountControl.setValue(this.srcAmount))}explainTheError(e){const i=e.errors||{};return\"Wrong number: \"+Object.keys(i).reduce((r,s)=>{switch(s){case\"min\":return r+`minimal value is ${i[s].min}. `;case\"max\":return r+`maximum value is ${i[s].max}. `;case\"pattern\":return r+\"it should be number. \";default:return r+\"wrong amount. \"}},\"\")}consoleLog(e){console.log(e)}onResize(e){this.breakpoint=e.target.innerWidth<=400?1:2}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275cmp=xe({type:n,selectors:[[\"app-main\"]],decls:56,vars:21,consts:[[3,\"cols\",\"resize\"],[1,\"container\"],[\"appearance\",\"outline\"],[3,\"value\",\"valueChange\",\"selectionChange\"],[3,\"value\",\"disabled\",4,\"ngFor\",\"ngForOf\"],[3,\"value\",\"valueChange\"],[\"label\",\"Native coins\"],[3,\"value\"],[\"label\",\"Tokens\"],[\"matInput\",\"\",\"placeholder\",\"Amount\",\"type\",\"number\",3,\"value\",\"formControl\",\"change\"],[\"srcInputElement\",\"\"],[4,\"ngIf\"],[\"dstInputElement\",\"\"],[3,\"value\",\"disabled\"]],template:function(e,i){if(1&e){const r=ia();x(0,\"h1\"),we(1,\"Everscale-Tezos Bridge\"),S(),x(2,\"mat-grid-list\",0),J(\"resize\",function(o){return i.onResize(o)},!1,Uv),x(3,\"mat-grid-tile\")(4,\"div\",1)(5,\"h3\"),we(6,\"Choose what you have:\"),S(),x(7,\"mat-form-field\",2)(8,\"mat-label\"),we(9,\"Blockchain\"),S(),x(10,\"mat-select\",3),J(\"valueChange\",function(o){return i.srcChain=o})(\"selectionChange\",function(o){return i.onSelectionChange(o)})(\"valueChange\",function(o){return i.onChainSrcValueChange(o)}),Ee(11,l$,2,3,\"mat-option\",4),S()(),x(12,\"mat-form-field\",2)(13,\"mat-label\"),we(14,\"Token\"),S(),x(15,\"mat-select\",5),J(\"valueChange\",function(o){return i.srcTokenChosen=o})(\"valueChange\",function(o){return i.onSrcTokenChange(o)}),x(16,\"mat-optgroup\",6)(17,\"mat-option\",7),we(18),S()(),x(19,\"mat-optgroup\",8),Ee(20,c$,2,3,\"mat-option\",4),S()()(),x(21,\"mat-form-field\",2)(22,\"mat-label\"),we(23,\"Amount\"),S(),x(24,\"input\",9,10),J(\"change\",function(){Dr(r);const o=wn(25);return i.calculateAmount(!0,o.value)}),S(),x(26,\"mat-hint\"),we(27),S(),Ee(28,d$,2,1,\"mat-error\",11),S()()(),x(29,\"mat-grid-tile\")(30,\"div\",1)(31,\"h3\"),we(32,\"Choose what you want:\"),S(),x(33,\"mat-form-field\",2)(34,\"mat-label\"),we(35,\"Blockchain\"),S(),x(36,\"mat-select\",5),J(\"valueChange\",function(o){return i.dstChain=o})(\"valueChange\",function(o){return i.onChainDstValueChange(o)}),Ee(37,u$,2,3,\"mat-option\",4),S()(),x(38,\"mat-form-field\",2)(39,\"mat-label\"),we(40,\"Token\"),S(),x(41,\"mat-select\",5),J(\"valueChange\",function(o){return i.dstTokenChosen=o})(\"valueChange\",function(o){return i.onDstTokenChange(o)}),x(42,\"mat-optgroup\",6)(43,\"mat-option\",7),we(44),S()(),x(45,\"mat-optgroup\",8),Ee(46,h$,2,3,\"mat-option\",4),S()()(),x(47,\"mat-form-field\",2)(48,\"mat-label\"),we(49,\"Amount\"),S(),x(50,\"input\",9,12),J(\"change\",function(){Dr(r);const o=wn(51);return i.calculateAmount(!1,o.value)}),S(),Ee(52,p$,2,1,\"mat-error\",11),x(53,\"mat-hint\"),we(54),S()()()(),Le(55,\"router-outlet\"),S()}2&e&&(T(2),N(\"cols\",i.breakpoint),T(8),N(\"value\",i.srcChain),T(1),N(\"ngForOf\",i.srcChainList),T(4),N(\"value\",i.srcTokenChosen),T(2),N(\"value\",i.srcCoin),T(1),Ut(i.srcCoin),T(2),N(\"ngForOf\",i.srcTokenList),T(4),N(\"value\",i.srcAmount)(\"formControl\",i.srcAmountControl),T(3),qn(\"Amount of \",i.srcTokenChosen,\" to pay\"),T(1),N(\"ngIf\",i.srcAmountControl.invalid),T(8),N(\"value\",i.dstChain),T(1),N(\"ngForOf\",i.dstChainList),T(4),N(\"value\",i.dstTokenChosen),T(2),N(\"value\",i.dstCoin),T(1),Ut(i.dstCoin),T(2),N(\"ngForOf\",i.dstTokenList),T(4),N(\"value\",i.dstAmount)(\"formControl\",i.dstAmountControl),T(2),N(\"ngIf\",i.dstAmountControl.invalid),T(2),qn(\"Amount of \",i.dstTokenChosen,\" to receive\"))},directives:[bU,yE,t5,fg,t$,gD,hE,J3,o$,Tm,Dd,ax,Im,YU,Ca,GU,Pf],styles:[\".container[_ngcontent-%COMP%] .mat-form-field[_ngcontent-%COMP%] + .mat-form-field[_ngcontent-%COMP%]{margin-left:8px}mat-form-field[_ngcontent-%COMP%]{display:block}mat-grid-list[_ngcontent-%COMP%]{display:flex;flex-wrap:wrap;justify-content:center}\"]}),n})(),ZE=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),m$=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();function wg(n,t,e){for(let i in t)if(t.hasOwnProperty(i)){const r=t[i];r?n.setProperty(i,r,(null==e?void 0:e.has(i))?\"important\":\"\"):n.removeProperty(i)}return n}function _o(n,t){const e=t?\"\":\"none\";wg(n.style,{\"touch-action\":t?\"\":\"none\",\"-webkit-user-drag\":t?\"\":\"none\",\"-webkit-tap-highlight-color\":t?\"\":\"transparent\",\"user-select\":e,\"-ms-user-select\":e,\"-webkit-user-select\":e,\"-moz-user-select\":e})}function XE(n,t,e){wg(n.style,{position:t?\"\":\"fixed\",top:t?\"\":\"0\",opacity:t?\"\":\"0\",left:t?\"\":\"-999em\"},e)}function Yd(n,t){return t&&\"none\"!=t?n+\" \"+t:n}function JE(n){const t=n.toLowerCase().indexOf(\"ms\")>-1?1:1e3;return parseFloat(n)*t}function Mg(n,t){return n.getPropertyValue(t).split(\",\").map(i=>i.trim())}function xg(n){const t=n.getBoundingClientRect();return{top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:t.width,height:t.height,x:t.x,y:t.y}}function Eg(n,t,e){const{top:i,bottom:r,left:s,right:o}=n;return e>=i&&e<=r&&t>=s&&t<=o}function sl(n,t,e){n.top+=t,n.bottom=n.top+n.height,n.left+=e,n.right=n.left+n.width}function eS(n,t,e,i){const{top:r,right:s,bottom:o,left:a,width:l,height:c}=n,d=l*t,u=c*t;return i>r-u&&i<o+u&&e>a-d&&e<s+d}class tS{constructor(t){this._document=t,this.positions=new Map}clear(){this.positions.clear()}cache(t){this.clear(),this.positions.set(this._document,{scrollPosition:this.getViewportScrollPosition()}),t.forEach(e=>{this.positions.set(e,{scrollPosition:{top:e.scrollTop,left:e.scrollLeft},clientRect:xg(e)})})}handleScroll(t){const e=Pn(t),i=this.positions.get(e);if(!i)return null;const r=i.scrollPosition;let s,o;if(e===this._document){const c=this.getViewportScrollPosition();s=c.top,o=c.left}else s=e.scrollTop,o=e.scrollLeft;const a=r.top-s,l=r.left-o;return this.positions.forEach((c,d)=>{c.clientRect&&e!==d&&e.contains(d)&&sl(c.clientRect,a,l)}),r.top=s,r.left=o,{top:a,left:l}}getViewportScrollPosition(){return{top:window.scrollY,left:window.scrollX}}}function nS(n){const t=n.cloneNode(!0),e=t.querySelectorAll(\"[id]\"),i=n.nodeName.toLowerCase();t.removeAttribute(\"id\");for(let r=0;r<e.length;r++)e[r].removeAttribute(\"id\");return\"canvas\"===i?sS(n,t):(\"input\"===i||\"select\"===i||\"textarea\"===i)&&rS(n,t),iS(\"canvas\",n,t,sS),iS(\"input, textarea, select\",n,t,rS),t}function iS(n,t,e,i){const r=t.querySelectorAll(n);if(r.length){const s=e.querySelectorAll(n);for(let o=0;o<r.length;o++)i(r[o],s[o])}}let v$=0;function rS(n,t){\"file\"!==t.type&&(t.value=n.value),\"radio\"===t.type&&t.name&&(t.name=`mat-clone-${t.name}-${v$++}`)}function sS(n,t){const e=t.getContext(\"2d\");if(e)try{e.drawImage(n,0,0)}catch(i){}}const oS=ei({passive:!0}),Qd=ei({passive:!1}),Sg=new Set([\"position\"]);class b${constructor(t,e,i,r,s,o){this._config=e,this._document=i,this._ngZone=r,this._viewportRuler=s,this._dragDropRegistry=o,this._passiveTransform={x:0,y:0},this._activeTransform={x:0,y:0},this._hasStartedDragging=!1,this._moveEvents=new O,this._pointerMoveSubscription=ke.EMPTY,this._pointerUpSubscription=ke.EMPTY,this._scrollSubscription=ke.EMPTY,this._resizeSubscription=ke.EMPTY,this._boundaryElement=null,this._nativeInteractionsEnabled=!0,this._handles=[],this._disabledHandles=new Set,this._direction=\"ltr\",this.dragStartDelay=0,this._disabled=!1,this.beforeStarted=new O,this.started=new O,this.released=new O,this.ended=new O,this.entered=new O,this.exited=new O,this.dropped=new O,this.moved=this._moveEvents,this._pointerDown=a=>{if(this.beforeStarted.next(),this._handles.length){const l=this._getTargetHandle(a);l&&!this._disabledHandles.has(l)&&!this.disabled&&this._initializeDragSequence(l,a)}else this.disabled||this._initializeDragSequence(this._rootElement,a)},this._pointerMove=a=>{const l=this._getPointerPositionOnPage(a);if(!this._hasStartedDragging){if(Math.abs(l.x-this._pickupPositionOnPage.x)+Math.abs(l.y-this._pickupPositionOnPage.y)>=this._config.dragStartThreshold){const p=Date.now()>=this._dragStartTime+this._getDragStartDelay(a),m=this._dropContainer;if(!p)return void this._endDragSequence(a);(!m||!m.isDragging()&&!m.isReceiving())&&(a.preventDefault(),this._hasStartedDragging=!0,this._ngZone.run(()=>this._startDragSequence(a)))}return}a.preventDefault();const c=this._getConstrainedPointerPosition(l);if(this._hasMoved=!0,this._lastKnownPointerPosition=l,this._updatePointerDirectionDelta(c),this._dropContainer)this._updateActiveDropContainer(c,l);else{const d=this._activeTransform;d.x=c.x-this._pickupPositionOnPage.x+this._passiveTransform.x,d.y=c.y-this._pickupPositionOnPage.y+this._passiveTransform.y,this._applyRootElementTransform(d.x,d.y)}this._moveEvents.observers.length&&this._ngZone.run(()=>{this._moveEvents.next({source:this,pointerPosition:c,event:a,distance:this._getDragDistance(c),delta:this._pointerDirectionDelta})})},this._pointerUp=a=>{this._endDragSequence(a)},this._nativeDragStart=a=>{if(this._handles.length){const l=this._getTargetHandle(a);l&&!this._disabledHandles.has(l)&&!this.disabled&&a.preventDefault()}else this.disabled||a.preventDefault()},this.withRootElement(t).withParent(e.parentDragRef||null),this._parentPositions=new tS(i),o.registerDragItem(this)}get disabled(){return this._disabled||!(!this._dropContainer||!this._dropContainer.disabled)}set disabled(t){const e=G(t);e!==this._disabled&&(this._disabled=e,this._toggleNativeDragInteractions(),this._handles.forEach(i=>_o(i,e)))}getPlaceholderElement(){return this._placeholder}getRootElement(){return this._rootElement}getVisibleElement(){return this.isDragging()?this.getPlaceholderElement():this.getRootElement()}withHandles(t){this._handles=t.map(i=>at(i)),this._handles.forEach(i=>_o(i,this.disabled)),this._toggleNativeDragInteractions();const e=new Set;return this._disabledHandles.forEach(i=>{this._handles.indexOf(i)>-1&&e.add(i)}),this._disabledHandles=e,this}withPreviewTemplate(t){return this._previewTemplate=t,this}withPlaceholderTemplate(t){return this._placeholderTemplate=t,this}withRootElement(t){const e=at(t);return e!==this._rootElement&&(this._rootElement&&this._removeRootElementListeners(this._rootElement),this._ngZone.runOutsideAngular(()=>{e.addEventListener(\"mousedown\",this._pointerDown,Qd),e.addEventListener(\"touchstart\",this._pointerDown,oS),e.addEventListener(\"dragstart\",this._nativeDragStart,Qd)}),this._initialTransform=void 0,this._rootElement=e),\"undefined\"!=typeof SVGElement&&this._rootElement instanceof SVGElement&&(this._ownerSVGElement=this._rootElement.ownerSVGElement),this}withBoundaryElement(t){return this._boundaryElement=t?at(t):null,this._resizeSubscription.unsubscribe(),t&&(this._resizeSubscription=this._viewportRuler.change(10).subscribe(()=>this._containInsideBoundaryOnResize())),this}withParent(t){return this._parentDragRef=t,this}dispose(){var t,e;this._removeRootElementListeners(this._rootElement),this.isDragging()&&(null===(t=this._rootElement)||void 0===t||t.remove()),null===(e=this._anchor)||void 0===e||e.remove(),this._destroyPreview(),this._destroyPlaceholder(),this._dragDropRegistry.removeDragItem(this),this._removeSubscriptions(),this.beforeStarted.complete(),this.started.complete(),this.released.complete(),this.ended.complete(),this.entered.complete(),this.exited.complete(),this.dropped.complete(),this._moveEvents.complete(),this._handles=[],this._disabledHandles.clear(),this._dropContainer=void 0,this._resizeSubscription.unsubscribe(),this._parentPositions.clear(),this._boundaryElement=this._rootElement=this._ownerSVGElement=this._placeholderTemplate=this._previewTemplate=this._anchor=this._parentDragRef=null}isDragging(){return this._hasStartedDragging&&this._dragDropRegistry.isDragging(this)}reset(){this._rootElement.style.transform=this._initialTransform||\"\",this._activeTransform={x:0,y:0},this._passiveTransform={x:0,y:0}}disableHandle(t){!this._disabledHandles.has(t)&&this._handles.indexOf(t)>-1&&(this._disabledHandles.add(t),_o(t,!0))}enableHandle(t){this._disabledHandles.has(t)&&(this._disabledHandles.delete(t),_o(t,this.disabled))}withDirection(t){return this._direction=t,this}_withDropContainer(t){this._dropContainer=t}getFreeDragPosition(){const t=this.isDragging()?this._activeTransform:this._passiveTransform;return{x:t.x,y:t.y}}setFreeDragPosition(t){return this._activeTransform={x:0,y:0},this._passiveTransform.x=t.x,this._passiveTransform.y=t.y,this._dropContainer||this._applyRootElementTransform(t.x,t.y),this}withPreviewContainer(t){return this._previewContainer=t,this}_sortFromLastPointerPosition(){const t=this._lastKnownPointerPosition;t&&this._dropContainer&&this._updateActiveDropContainer(this._getConstrainedPointerPosition(t),t)}_removeSubscriptions(){this._pointerMoveSubscription.unsubscribe(),this._pointerUpSubscription.unsubscribe(),this._scrollSubscription.unsubscribe()}_destroyPreview(){var t,e;null===(t=this._preview)||void 0===t||t.remove(),null===(e=this._previewRef)||void 0===e||e.destroy(),this._preview=this._previewRef=null}_destroyPlaceholder(){var t,e;null===(t=this._placeholder)||void 0===t||t.remove(),null===(e=this._placeholderRef)||void 0===e||e.destroy(),this._placeholder=this._placeholderRef=null}_endDragSequence(t){if(this._dragDropRegistry.isDragging(this)&&(this._removeSubscriptions(),this._dragDropRegistry.stopDragging(this),this._toggleNativeDragInteractions(),this._handles&&(this._rootElement.style.webkitTapHighlightColor=this._rootElementTapHighlight),this._hasStartedDragging))if(this.released.next({source:this}),this._dropContainer)this._dropContainer._stopScrolling(),this._animatePreviewToPlaceholder().then(()=>{this._cleanupDragArtifacts(t),this._cleanupCachedDimensions(),this._dragDropRegistry.stopDragging(this)});else{this._passiveTransform.x=this._activeTransform.x;const e=this._getPointerPositionOnPage(t);this._passiveTransform.y=this._activeTransform.y,this._ngZone.run(()=>{this.ended.next({source:this,distance:this._getDragDistance(e),dropPoint:e})}),this._cleanupCachedDimensions(),this._dragDropRegistry.stopDragging(this)}}_startDragSequence(t){ol(t)&&(this._lastTouchEventTime=Date.now()),this._toggleNativeDragInteractions();const e=this._dropContainer;if(e){const i=this._rootElement,r=i.parentNode,s=this._placeholder=this._createPlaceholderElement(),o=this._anchor=this._anchor||this._document.createComment(\"\"),a=this._getShadowRoot();r.insertBefore(o,i),this._initialTransform=i.style.transform||\"\",this._preview=this._createPreviewElement(),XE(i,!1,Sg),this._document.body.appendChild(r.replaceChild(s,i)),this._getPreviewInsertionPoint(r,a).appendChild(this._preview),this.started.next({source:this}),e.start(),this._initialContainer=e,this._initialIndex=e.getItemIndex(this)}else this.started.next({source:this}),this._initialContainer=this._initialIndex=void 0;this._parentPositions.cache(e?e.getScrollableParents():[])}_initializeDragSequence(t,e){this._parentDragRef&&e.stopPropagation();const i=this.isDragging(),r=ol(e),s=!r&&0!==e.button,o=this._rootElement,a=Pn(e),l=!r&&this._lastTouchEventTime&&this._lastTouchEventTime+800>Date.now(),c=r?Zm(e):Km(e);if(a&&a.draggable&&\"mousedown\"===e.type&&e.preventDefault(),i||s||l||c)return;if(this._handles.length){const h=o.style;this._rootElementTapHighlight=h.webkitTapHighlightColor||\"\",h.webkitTapHighlightColor=\"transparent\"}this._hasStartedDragging=this._hasMoved=!1,this._removeSubscriptions(),this._pointerMoveSubscription=this._dragDropRegistry.pointerMove.subscribe(this._pointerMove),this._pointerUpSubscription=this._dragDropRegistry.pointerUp.subscribe(this._pointerUp),this._scrollSubscription=this._dragDropRegistry.scrolled(this._getShadowRoot()).subscribe(h=>this._updateOnScroll(h)),this._boundaryElement&&(this._boundaryRect=xg(this._boundaryElement));const d=this._previewTemplate;this._pickupPositionInElement=d&&d.template&&!d.matchSize?{x:0,y:0}:this._getPointerPositionInElement(t,e);const u=this._pickupPositionOnPage=this._lastKnownPointerPosition=this._getPointerPositionOnPage(e);this._pointerDirectionDelta={x:0,y:0},this._pointerPositionAtLastDirectionChange={x:u.x,y:u.y},this._dragStartTime=Date.now(),this._dragDropRegistry.startDragging(this,e)}_cleanupDragArtifacts(t){XE(this._rootElement,!0,Sg),this._anchor.parentNode.replaceChild(this._rootElement,this._anchor),this._destroyPreview(),this._destroyPlaceholder(),this._boundaryRect=this._previewRect=this._initialTransform=void 0,this._ngZone.run(()=>{const e=this._dropContainer,i=e.getItemIndex(this),r=this._getPointerPositionOnPage(t),s=this._getDragDistance(r),o=e._isOverContainer(r.x,r.y);this.ended.next({source:this,distance:s,dropPoint:r}),this.dropped.next({item:this,currentIndex:i,previousIndex:this._initialIndex,container:e,previousContainer:this._initialContainer,isPointerOverContainer:o,distance:s,dropPoint:r}),e.drop(this,i,this._initialIndex,this._initialContainer,o,s,r),this._dropContainer=this._initialContainer})}_updateActiveDropContainer({x:t,y:e},{x:i,y:r}){let s=this._initialContainer._getSiblingContainerFromPosition(this,t,e);!s&&this._dropContainer!==this._initialContainer&&this._initialContainer._isOverContainer(t,e)&&(s=this._initialContainer),s&&s!==this._dropContainer&&this._ngZone.run(()=>{this.exited.next({item:this,container:this._dropContainer}),this._dropContainer.exit(this),this._dropContainer=s,this._dropContainer.enter(this,t,e,s===this._initialContainer&&s.sortingDisabled?this._initialIndex:void 0),this.entered.next({item:this,container:s,currentIndex:s.getItemIndex(this)})}),this.isDragging()&&(this._dropContainer._startScrollingIfNecessary(i,r),this._dropContainer._sortItem(this,t,e,this._pointerDirectionDelta),this._applyPreviewTransform(t-this._pickupPositionInElement.x,e-this._pickupPositionInElement.y))}_createPreviewElement(){const t=this._previewTemplate,e=this.previewClass,i=t?t.template:null;let r;if(i&&t){const s=t.matchSize?this._rootElement.getBoundingClientRect():null,o=t.viewContainer.createEmbeddedView(i,t.context);o.detectChanges(),r=lS(o,this._document),this._previewRef=o,t.matchSize?cS(r,s):r.style.transform=Kd(this._pickupPositionOnPage.x,this._pickupPositionOnPage.y)}else{const s=this._rootElement;r=nS(s),cS(r,s.getBoundingClientRect()),this._initialTransform&&(r.style.transform=this._initialTransform)}return wg(r.style,{\"pointer-events\":\"none\",margin:\"0\",position:\"fixed\",top:\"0\",left:\"0\",\"z-index\":`${this._config.zIndex||1e3}`},Sg),_o(r,!1),r.classList.add(\"cdk-drag-preview\"),r.setAttribute(\"dir\",this._direction),e&&(Array.isArray(e)?e.forEach(s=>r.classList.add(s)):r.classList.add(e)),r}_animatePreviewToPlaceholder(){if(!this._hasMoved)return Promise.resolve();const t=this._placeholder.getBoundingClientRect();this._preview.classList.add(\"cdk-drag-animating\"),this._applyPreviewTransform(t.left,t.top);const e=function _$(n){const t=getComputedStyle(n),e=Mg(t,\"transition-property\"),i=e.find(a=>\"transform\"===a||\"all\"===a);if(!i)return 0;const r=e.indexOf(i),s=Mg(t,\"transition-duration\"),o=Mg(t,\"transition-delay\");return JE(s[r])+JE(o[r])}(this._preview);return 0===e?Promise.resolve():this._ngZone.runOutsideAngular(()=>new Promise(i=>{const r=o=>{var a;(!o||Pn(o)===this._preview&&\"transform\"===o.propertyName)&&(null===(a=this._preview)||void 0===a||a.removeEventListener(\"transitionend\",r),i(),clearTimeout(s))},s=setTimeout(r,1.5*e);this._preview.addEventListener(\"transitionend\",r)}))}_createPlaceholderElement(){const t=this._placeholderTemplate,e=t?t.template:null;let i;return e?(this._placeholderRef=t.viewContainer.createEmbeddedView(e,t.context),this._placeholderRef.detectChanges(),i=lS(this._placeholderRef,this._document)):i=nS(this._rootElement),i.style.pointerEvents=\"none\",i.classList.add(\"cdk-drag-placeholder\"),i}_getPointerPositionInElement(t,e){const i=this._rootElement.getBoundingClientRect(),r=t===this._rootElement?null:t,s=r?r.getBoundingClientRect():i,o=ol(e)?e.targetTouches[0]:e,a=this._getViewportScrollPosition();return{x:s.left-i.left+(o.pageX-s.left-a.left),y:s.top-i.top+(o.pageY-s.top-a.top)}}_getPointerPositionOnPage(t){const e=this._getViewportScrollPosition(),i=ol(t)?t.touches[0]||t.changedTouches[0]||{pageX:0,pageY:0}:t,r=i.pageX-e.left,s=i.pageY-e.top;if(this._ownerSVGElement){const o=this._ownerSVGElement.getScreenCTM();if(o){const a=this._ownerSVGElement.createSVGPoint();return a.x=r,a.y=s,a.matrixTransform(o.inverse())}}return{x:r,y:s}}_getConstrainedPointerPosition(t){const e=this._dropContainer?this._dropContainer.lockAxis:null;let{x:i,y:r}=this.constrainPosition?this.constrainPosition(t,this):t;if(\"x\"===this.lockAxis||\"x\"===e?r=this._pickupPositionOnPage.y:(\"y\"===this.lockAxis||\"y\"===e)&&(i=this._pickupPositionOnPage.x),this._boundaryRect){const{x:s,y:o}=this._pickupPositionInElement,a=this._boundaryRect,{width:l,height:c}=this._getPreviewRect(),d=a.top+o,u=a.bottom-(c-o);i=aS(i,a.left+s,a.right-(l-s)),r=aS(r,d,u)}return{x:i,y:r}}_updatePointerDirectionDelta(t){const{x:e,y:i}=t,r=this._pointerDirectionDelta,s=this._pointerPositionAtLastDirectionChange,o=Math.abs(e-s.x),a=Math.abs(i-s.y);return o>this._config.pointerDirectionChangeThreshold&&(r.x=e>s.x?1:-1,s.x=e),a>this._config.pointerDirectionChangeThreshold&&(r.y=i>s.y?1:-1,s.y=i),r}_toggleNativeDragInteractions(){if(!this._rootElement||!this._handles)return;const t=this._handles.length>0||!this.isDragging();t!==this._nativeInteractionsEnabled&&(this._nativeInteractionsEnabled=t,_o(this._rootElement,t))}_removeRootElementListeners(t){t.removeEventListener(\"mousedown\",this._pointerDown,Qd),t.removeEventListener(\"touchstart\",this._pointerDown,oS),t.removeEventListener(\"dragstart\",this._nativeDragStart,Qd)}_applyRootElementTransform(t,e){const i=Kd(t,e),r=this._rootElement.style;null==this._initialTransform&&(this._initialTransform=r.transform&&\"none\"!=r.transform?r.transform:\"\"),r.transform=Yd(i,this._initialTransform)}_applyPreviewTransform(t,e){var i;const r=(null===(i=this._previewTemplate)||void 0===i?void 0:i.template)?void 0:this._initialTransform,s=Kd(t,e);this._preview.style.transform=Yd(s,r)}_getDragDistance(t){const e=this._pickupPositionOnPage;return e?{x:t.x-e.x,y:t.y-e.y}:{x:0,y:0}}_cleanupCachedDimensions(){this._boundaryRect=this._previewRect=void 0,this._parentPositions.clear()}_containInsideBoundaryOnResize(){let{x:t,y:e}=this._passiveTransform;if(0===t&&0===e||this.isDragging()||!this._boundaryElement)return;const i=this._boundaryElement.getBoundingClientRect(),r=this._rootElement.getBoundingClientRect();if(0===i.width&&0===i.height||0===r.width&&0===r.height)return;const s=i.left-r.left,o=r.right-i.right,a=i.top-r.top,l=r.bottom-i.bottom;i.width>r.width?(s>0&&(t+=s),o>0&&(t-=o)):t=0,i.height>r.height?(a>0&&(e+=a),l>0&&(e-=l)):e=0,(t!==this._passiveTransform.x||e!==this._passiveTransform.y)&&this.setFreeDragPosition({y:e,x:t})}_getDragStartDelay(t){const e=this.dragStartDelay;return\"number\"==typeof e?e:ol(t)?e.touch:e?e.mouse:0}_updateOnScroll(t){const e=this._parentPositions.handleScroll(t);if(e){const i=Pn(t);this._boundaryRect&&i!==this._boundaryElement&&i.contains(this._boundaryElement)&&sl(this._boundaryRect,e.top,e.left),this._pickupPositionOnPage.x+=e.left,this._pickupPositionOnPage.y+=e.top,this._dropContainer||(this._activeTransform.x-=e.left,this._activeTransform.y-=e.top,this._applyRootElementTransform(this._activeTransform.x,this._activeTransform.y))}}_getViewportScrollPosition(){var t;return(null===(t=this._parentPositions.positions.get(this._document))||void 0===t?void 0:t.scrollPosition)||this._parentPositions.getViewportScrollPosition()}_getShadowRoot(){return void 0===this._cachedShadowRoot&&(this._cachedShadowRoot=Fd(this._rootElement)),this._cachedShadowRoot}_getPreviewInsertionPoint(t,e){const i=this._previewContainer||\"global\";if(\"parent\"===i)return t;if(\"global\"===i){const r=this._document;return e||r.fullscreenElement||r.webkitFullscreenElement||r.mozFullScreenElement||r.msFullscreenElement||r.body}return at(i)}_getPreviewRect(){return(!this._previewRect||!this._previewRect.width&&!this._previewRect.height)&&(this._previewRect=(this._preview||this._rootElement).getBoundingClientRect()),this._previewRect}_getTargetHandle(t){return this._handles.find(e=>t.target&&(t.target===e||e.contains(t.target)))}}function Kd(n,t){return`translate3d(${Math.round(n)}px, ${Math.round(t)}px, 0)`}function aS(n,t,e){return Math.max(t,Math.min(e,n))}function ol(n){return\"t\"===n.type[0]}function lS(n,t){const e=n.rootNodes;if(1===e.length&&e[0].nodeType===t.ELEMENT_NODE)return e[0];const i=t.createElement(\"div\");return e.forEach(r=>i.appendChild(r)),i}function cS(n,t){n.style.width=`${t.width}px`,n.style.height=`${t.height}px`,n.style.transform=Kd(t.left,t.top)}function al(n,t){return Math.max(0,Math.min(t,n))}class D${constructor(t,e,i,r,s){this._dragDropRegistry=e,this._ngZone=r,this._viewportRuler=s,this.disabled=!1,this.sortingDisabled=!1,this.autoScrollDisabled=!1,this.autoScrollStep=2,this.enterPredicate=()=>!0,this.sortPredicate=()=>!0,this.beforeStarted=new O,this.entered=new O,this.exited=new O,this.dropped=new O,this.sorted=new O,this._isDragging=!1,this._itemPositions=[],this._previousSwap={drag:null,delta:0,overlaps:!1},this._draggables=[],this._siblings=[],this._orientation=\"vertical\",this._activeSiblings=new Set,this._direction=\"ltr\",this._viewportScrollSubscription=ke.EMPTY,this._verticalScrollDirection=0,this._horizontalScrollDirection=0,this._stopScrollTimers=new O,this._cachedShadowRoot=null,this._startScrollInterval=()=>{this._stopScrolling(),function g$(n=0,t=qa){return n<0&&(n=0),_g(n,n,t)}(0,EE).pipe(Ie(this._stopScrollTimers)).subscribe(()=>{const o=this._scrollNode,a=this.autoScrollStep;1===this._verticalScrollDirection?o.scrollBy(0,-a):2===this._verticalScrollDirection&&o.scrollBy(0,a),1===this._horizontalScrollDirection?o.scrollBy(-a,0):2===this._horizontalScrollDirection&&o.scrollBy(a,0)})},this.element=at(t),this._document=i,this.withScrollableParents([this.element]),e.registerDropContainer(this),this._parentPositions=new tS(i)}dispose(){this._stopScrolling(),this._stopScrollTimers.complete(),this._viewportScrollSubscription.unsubscribe(),this.beforeStarted.complete(),this.entered.complete(),this.exited.complete(),this.dropped.complete(),this.sorted.complete(),this._activeSiblings.clear(),this._scrollNode=null,this._parentPositions.clear(),this._dragDropRegistry.removeDropContainer(this)}isDragging(){return this._isDragging}start(){this._draggingStarted(),this._notifyReceivingSiblings()}enter(t,e,i,r){let s;this._draggingStarted(),null==r?(s=this.sortingDisabled?this._draggables.indexOf(t):-1,-1===s&&(s=this._getItemIndexFromPointerPosition(t,e,i))):s=r;const o=this._activeDraggables,a=o.indexOf(t),l=t.getPlaceholderElement();let c=o[s];if(c===t&&(c=o[s+1]),!c&&(null==s||-1===s||s<o.length-1)&&this._shouldEnterAsFirstChild(e,i)&&(c=o[0]),a>-1&&o.splice(a,1),c&&!this._dragDropRegistry.isDragging(c)){const d=c.getRootElement();d.parentElement.insertBefore(l,d),o.splice(s,0,t)}else at(this.element).appendChild(l),o.push(t);l.style.transform=\"\",this._cacheItemPositions(),this._cacheParentPositions(),this._notifyReceivingSiblings(),this.entered.next({item:t,container:this,currentIndex:this.getItemIndex(t)})}exit(t){this._reset(),this.exited.next({item:t,container:this})}drop(t,e,i,r,s,o,a){this._reset(),this.dropped.next({item:t,currentIndex:e,previousIndex:i,container:this,previousContainer:r,isPointerOverContainer:s,distance:o,dropPoint:a})}withItems(t){const e=this._draggables;return this._draggables=t,t.forEach(i=>i._withDropContainer(this)),this.isDragging()&&(e.filter(r=>r.isDragging()).every(r=>-1===t.indexOf(r))?this._reset():this._cacheItems()),this}withDirection(t){return this._direction=t,this}connectedTo(t){return this._siblings=t.slice(),this}withOrientation(t){return this._orientation=t,this}withScrollableParents(t){const e=at(this.element);return this._scrollableElements=-1===t.indexOf(e)?[e,...t]:t.slice(),this}getScrollableParents(){return this._scrollableElements}getItemIndex(t){return this._isDragging?(\"horizontal\"===this._orientation&&\"rtl\"===this._direction?this._itemPositions.slice().reverse():this._itemPositions).findIndex(i=>i.drag===t):this._draggables.indexOf(t)}isReceiving(){return this._activeSiblings.size>0}_sortItem(t,e,i,r){if(this.sortingDisabled||!this._clientRect||!eS(this._clientRect,.05,e,i))return;const s=this._itemPositions,o=this._getItemIndexFromPointerPosition(t,e,i,r);if(-1===o&&s.length>0)return;const a=\"horizontal\"===this._orientation,l=s.findIndex(_=>_.drag===t),c=s[o],u=c.clientRect,h=l>o?1:-1,p=this._getItemOffsetPx(s[l].clientRect,u,h),m=this._getSiblingOffsetPx(l,s,h),g=s.slice();(function C$(n,t,e){const i=al(t,n.length-1),r=al(e,n.length-1);if(i===r)return;const s=n[i],o=r<i?-1:1;for(let a=i;a!==r;a+=o)n[a]=n[a+o];n[r]=s})(s,l,o),this.sorted.next({previousIndex:l,currentIndex:o,container:this,item:t}),s.forEach((_,D)=>{if(g[D]===_)return;const v=_.drag===t,M=v?p:m,V=v?t.getPlaceholderElement():_.drag.getRootElement();_.offset+=M,a?(V.style.transform=Yd(`translate3d(${Math.round(_.offset)}px, 0, 0)`,_.initialTransform),sl(_.clientRect,0,M)):(V.style.transform=Yd(`translate3d(0, ${Math.round(_.offset)}px, 0)`,_.initialTransform),sl(_.clientRect,M,0))}),this._previousSwap.overlaps=Eg(u,e,i),this._previousSwap.drag=c.drag,this._previousSwap.delta=a?r.x:r.y}_startScrollingIfNecessary(t,e){if(this.autoScrollDisabled)return;let i,r=0,s=0;if(this._parentPositions.positions.forEach((o,a)=>{a===this._document||!o.clientRect||i||eS(o.clientRect,.05,t,e)&&([r,s]=function w$(n,t,e,i){const r=hS(t,i),s=pS(t,e);let o=0,a=0;if(r){const l=n.scrollTop;1===r?l>0&&(o=1):n.scrollHeight-l>n.clientHeight&&(o=2)}if(s){const l=n.scrollLeft;1===s?l>0&&(a=1):n.scrollWidth-l>n.clientWidth&&(a=2)}return[o,a]}(a,o.clientRect,t,e),(r||s)&&(i=a))}),!r&&!s){const{width:o,height:a}=this._viewportRuler.getViewportSize(),l={width:o,height:a,top:0,right:o,bottom:a,left:0};r=hS(l,e),s=pS(l,t),i=window}i&&(r!==this._verticalScrollDirection||s!==this._horizontalScrollDirection||i!==this._scrollNode)&&(this._verticalScrollDirection=r,this._horizontalScrollDirection=s,this._scrollNode=i,(r||s)&&i?this._ngZone.runOutsideAngular(this._startScrollInterval):this._stopScrolling())}_stopScrolling(){this._stopScrollTimers.next()}_draggingStarted(){const t=at(this.element).style;this.beforeStarted.next(),this._isDragging=!0,this._initialScrollSnap=t.msScrollSnapType||t.scrollSnapType||\"\",t.scrollSnapType=t.msScrollSnapType=\"none\",this._cacheItems(),this._viewportScrollSubscription.unsubscribe(),this._listenToScrollEvents()}_cacheParentPositions(){const t=at(this.element);this._parentPositions.cache(this._scrollableElements),this._clientRect=this._parentPositions.positions.get(t).clientRect}_cacheItemPositions(){const t=\"horizontal\"===this._orientation;this._itemPositions=this._activeDraggables.map(e=>{const i=e.getVisibleElement();return{drag:e,offset:0,initialTransform:i.style.transform||\"\",clientRect:xg(i)}}).sort((e,i)=>t?e.clientRect.left-i.clientRect.left:e.clientRect.top-i.clientRect.top)}_reset(){this._isDragging=!1;const t=at(this.element).style;t.scrollSnapType=t.msScrollSnapType=this._initialScrollSnap,this._activeDraggables.forEach(e=>{var i;const r=e.getRootElement();if(r){const s=null===(i=this._itemPositions.find(o=>o.drag===e))||void 0===i?void 0:i.initialTransform;r.style.transform=s||\"\"}}),this._siblings.forEach(e=>e._stopReceiving(this)),this._activeDraggables=[],this._itemPositions=[],this._previousSwap.drag=null,this._previousSwap.delta=0,this._previousSwap.overlaps=!1,this._stopScrolling(),this._viewportScrollSubscription.unsubscribe(),this._parentPositions.clear()}_getSiblingOffsetPx(t,e,i){const r=\"horizontal\"===this._orientation,s=e[t].clientRect,o=e[t+-1*i];let a=s[r?\"width\":\"height\"]*i;if(o){const l=r?\"left\":\"top\",c=r?\"right\":\"bottom\";-1===i?a-=o.clientRect[l]-s[c]:a+=s[l]-o.clientRect[c]}return a}_getItemOffsetPx(t,e,i){const r=\"horizontal\"===this._orientation;let s=r?e.left-t.left:e.top-t.top;return-1===i&&(s+=r?e.width-t.width:e.height-t.height),s}_shouldEnterAsFirstChild(t,e){if(!this._activeDraggables.length)return!1;const i=this._itemPositions,r=\"horizontal\"===this._orientation;if(i[0].drag!==this._activeDraggables[0]){const o=i[i.length-1].clientRect;return r?t>=o.right:e>=o.bottom}{const o=i[0].clientRect;return r?t<=o.left:e<=o.top}}_getItemIndexFromPointerPosition(t,e,i,r){const s=\"horizontal\"===this._orientation,o=this._itemPositions.findIndex(({drag:a,clientRect:l})=>{if(a===t)return!1;if(r){const c=s?r.x:r.y;if(a===this._previousSwap.drag&&this._previousSwap.overlaps&&c===this._previousSwap.delta)return!1}return s?e>=Math.floor(l.left)&&e<Math.floor(l.right):i>=Math.floor(l.top)&&i<Math.floor(l.bottom)});return-1!==o&&this.sortPredicate(o,t,this)?o:-1}_cacheItems(){this._activeDraggables=this._draggables.slice(),this._cacheItemPositions(),this._cacheParentPositions()}_isOverContainer(t,e){return null!=this._clientRect&&Eg(this._clientRect,t,e)}_getSiblingContainerFromPosition(t,e,i){return this._siblings.find(r=>r._canReceive(t,e,i))}_canReceive(t,e,i){if(!this._clientRect||!Eg(this._clientRect,e,i)||!this.enterPredicate(t,this))return!1;const r=this._getShadowRoot().elementFromPoint(e,i);if(!r)return!1;const s=at(this.element);return r===s||s.contains(r)}_startReceiving(t,e){const i=this._activeSiblings;!i.has(t)&&e.every(r=>this.enterPredicate(r,this)||this._draggables.indexOf(r)>-1)&&(i.add(t),this._cacheParentPositions(),this._listenToScrollEvents())}_stopReceiving(t){this._activeSiblings.delete(t),this._viewportScrollSubscription.unsubscribe()}_listenToScrollEvents(){this._viewportScrollSubscription=this._dragDropRegistry.scrolled(this._getShadowRoot()).subscribe(t=>{if(this.isDragging()){const e=this._parentPositions.handleScroll(t);e&&(this._itemPositions.forEach(({clientRect:i})=>{sl(i,e.top,e.left)}),this._itemPositions.forEach(({drag:i})=>{this._dragDropRegistry.isDragging(i)&&i._sortFromLastPointerPosition()}))}else this.isReceiving()&&this._cacheParentPositions()})}_getShadowRoot(){if(!this._cachedShadowRoot){const t=Fd(at(this.element));this._cachedShadowRoot=t||this._document}return this._cachedShadowRoot}_notifyReceivingSiblings(){const t=this._activeDraggables.filter(e=>e.isDragging());this._siblings.forEach(e=>e._startReceiving(this,t))}}function hS(n,t){const{top:e,bottom:i,height:r}=n,s=.05*r;return t>=e-s&&t<=e+s?1:t>=i-s&&t<=i+s?2:0}function pS(n,t){const{left:e,right:i,width:r}=n,s=.05*r;return t>=e-s&&t<=e+s?1:t>=i-s&&t<=i+s?2:0}const Zd=ei({passive:!1,capture:!0});let M$=(()=>{class n{constructor(e,i){this._ngZone=e,this._dropInstances=new Set,this._dragInstances=new Set,this._activeDragInstances=[],this._globalListeners=new Map,this._draggingPredicate=r=>r.isDragging(),this.pointerMove=new O,this.pointerUp=new O,this.scroll=new O,this._preventDefaultWhileDragging=r=>{this._activeDragInstances.length>0&&r.preventDefault()},this._persistentTouchmoveListener=r=>{this._activeDragInstances.length>0&&(this._activeDragInstances.some(this._draggingPredicate)&&r.preventDefault(),this.pointerMove.next(r))},this._document=i}registerDropContainer(e){this._dropInstances.has(e)||this._dropInstances.add(e)}registerDragItem(e){this._dragInstances.add(e),1===this._dragInstances.size&&this._ngZone.runOutsideAngular(()=>{this._document.addEventListener(\"touchmove\",this._persistentTouchmoveListener,Zd)})}removeDropContainer(e){this._dropInstances.delete(e)}removeDragItem(e){this._dragInstances.delete(e),this.stopDragging(e),0===this._dragInstances.size&&this._document.removeEventListener(\"touchmove\",this._persistentTouchmoveListener,Zd)}startDragging(e,i){if(!(this._activeDragInstances.indexOf(e)>-1)&&(this._activeDragInstances.push(e),1===this._activeDragInstances.length)){const r=i.type.startsWith(\"touch\");this._globalListeners.set(r?\"touchend\":\"mouseup\",{handler:s=>this.pointerUp.next(s),options:!0}).set(\"scroll\",{handler:s=>this.scroll.next(s),options:!0}).set(\"selectstart\",{handler:this._preventDefaultWhileDragging,options:Zd}),r||this._globalListeners.set(\"mousemove\",{handler:s=>this.pointerMove.next(s),options:Zd}),this._ngZone.runOutsideAngular(()=>{this._globalListeners.forEach((s,o)=>{this._document.addEventListener(o,s.handler,s.options)})})}}stopDragging(e){const i=this._activeDragInstances.indexOf(e);i>-1&&(this._activeDragInstances.splice(i,1),0===this._activeDragInstances.length&&this._clearGlobalListeners())}isDragging(e){return this._activeDragInstances.indexOf(e)>-1}scrolled(e){const i=[this.scroll];return e&&e!==this._document&&i.push(new Ve(r=>this._ngZone.runOutsideAngular(()=>{const o=a=>{this._activeDragInstances.length&&r.next(a)};return e.addEventListener(\"scroll\",o,!0),()=>{e.removeEventListener(\"scroll\",o,!0)}}))),Bt(...i)}ngOnDestroy(){this._dragInstances.forEach(e=>this.removeDragItem(e)),this._dropInstances.forEach(e=>this.removeDropContainer(e)),this._clearGlobalListeners(),this.pointerMove.complete(),this.pointerUp.complete()}_clearGlobalListeners(){this._globalListeners.forEach((e,i)=>{this._document.removeEventListener(i,e.handler,e.options)}),this._globalListeners.clear()}}return n.\\u0275fac=function(e){return new(e||n)(y(ne),y(ie))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const x$={dragStartThreshold:5,pointerDirectionChangeThreshold:5};let E$=(()=>{class n{constructor(e,i,r,s){this._document=e,this._ngZone=i,this._viewportRuler=r,this._dragDropRegistry=s}createDrag(e,i=x$){return new b$(e,i,this._document,this._ngZone,this._viewportRuler,this._dragDropRegistry)}createDropList(e){return new D$(e,this._dragDropRegistry,this._document,this._ngZone,this._viewportRuler)}}return n.\\u0275fac=function(e){return new(e||n)(y(ie),y(ne),y(es),y(M$))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})(),S$=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[E$],imports:[Ci]}),n})(),fS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[lo]]}),n})(),bS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Ud]]}),n})(),CS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})();const Z$={provide:new b(\"mat-autocomplete-scroll-strategy\"),deps:[ni],useFactory:function K$(n){return()=>n.scrollStrategies.reposition()}};let t8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[Z$],imports:[[ji,Hd,B,bt],Ci,Hd,B]}),n})(),n8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Qa,B],B]}),n})(),r8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ji,B,Hi],B]}),n})(),ul=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ti,B],B]}),n})(),u8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B,ti],B]}),n})(),h8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),AS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),M8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ti,B,Ya,AS],B,AS]}),n})();const PS=new b(\"mat-chips-default-options\");let L8=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[mo,{provide:PS,useValue:{separatorKeyCodes:[13]}}],imports:[[B]]}),n})(),WS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),Wg=(()=>{class n{constructor(){this.changes=new O,this.optionalLabel=\"Optional\",this.completedLabel=\"Completed\",this.editableLabel=\"Editable\"}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const d4={provide:Wg,deps:[[new Tt,new Cn,Wg]],useFactory:function c4(n){return n||new Wg}};let u4=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[d4,mo],imports:[[B,bt,Hi,ul,fS,WS,ti],B]}),n})(),C4=(()=>{class n{constructor(){this.changes=new O,this.calendarLabel=\"Calendar\",this.openCalendarLabel=\"Open calendar\",this.closeCalendarLabel=\"Close calendar\",this.prevMonthLabel=\"Previous month\",this.nextMonthLabel=\"Next month\",this.prevYearLabel=\"Previous year\",this.nextYearLabel=\"Next year\",this.prevMultiYearLabel=\"Previous 24 years\",this.nextMultiYearLabel=\"Next 24 years\",this.switchToMonthViewLabel=\"Choose date\",this.switchToMultiYearViewLabel=\"Choose month and year\"}formatYearRange(e,i){return`${e} \\u2013 ${i}`}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const M4={provide:new b(\"mat-datepicker-scroll-strategy\"),deps:[ni],useFactory:function w4(n){return()=>n.scrollStrategies.reposition()}};let T4=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[C4,M4],imports:[[bt,ul,ji,Qa,Hi,B],Ci]}),n})();function A4(n,t){}class qg{constructor(){this.role=\"dialog\",this.panelClass=\"\",this.hasBackdrop=!0,this.backdropClass=\"\",this.disableClose=!1,this.width=\"\",this.height=\"\",this.maxWidth=\"80vw\",this.data=null,this.ariaDescribedBy=null,this.ariaLabelledBy=null,this.ariaLabel=null,this.autoFocus=\"first-tabbable\",this.restoreFocus=!0,this.delayFocusTrap=!0,this.closeOnNavigation=!0}}const I4={dialogContainer:Ke(\"dialogContainer\",[ae(\"void, exit\",R({opacity:0,transform:\"scale(0.7)\"})),ae(\"enter\",R({transform:\"none\"})),ge(\"* => enter\",nd([be(\"150ms cubic-bezier(0, 0, 0.2, 1)\",R({transform:\"none\",opacity:1})),no(\"@*\",to(),{optional:!0})])),ge(\"* => void, * => exit\",nd([be(\"75ms cubic-bezier(0.4, 0.0, 0.2, 1)\",R({opacity:0})),no(\"@*\",to(),{optional:!0})]))])};let R4=(()=>{class n extends bg{constructor(e,i,r,s,o,a,l,c){super(),this._elementRef=e,this._focusTrapFactory=i,this._changeDetectorRef=r,this._config=o,this._interactivityChecker=a,this._ngZone=l,this._focusMonitor=c,this._animationStateChanged=new $,this._elementFocusedBeforeDialogWasOpened=null,this._closeInteractionType=null,this.attachDomPortal=d=>(this._portalOutlet.hasAttached(),this._portalOutlet.attachDomPortal(d)),this._ariaLabelledBy=o.ariaLabelledBy||null,this._document=s}_initializeWithAttachedContent(){this._focusTrap=this._focusTrapFactory.create(this._elementRef.nativeElement),this._document&&(this._elementFocusedBeforeDialogWasOpened=Hm())}attachComponentPortal(e){return this._portalOutlet.hasAttached(),this._portalOutlet.attachComponentPortal(e)}attachTemplatePortal(e){return this._portalOutlet.hasAttached(),this._portalOutlet.attachTemplatePortal(e)}_recaptureFocus(){this._containsFocus()||this._trapFocus()}_forceFocus(e,i){this._interactivityChecker.isFocusable(e)||(e.tabIndex=-1,this._ngZone.runOutsideAngular(()=>{e.addEventListener(\"blur\",()=>e.removeAttribute(\"tabindex\")),e.addEventListener(\"mousedown\",()=>e.removeAttribute(\"tabindex\"))})),e.focus(i)}_focusByCssSelector(e,i){let r=this._elementRef.nativeElement.querySelector(e);r&&this._forceFocus(r,i)}_trapFocus(){const e=this._elementRef.nativeElement;switch(this._config.autoFocus){case!1:case\"dialog\":this._containsFocus()||e.focus();break;case!0:case\"first-tabbable\":this._focusTrap.focusInitialElementWhenReady().then(i=>{i||this._focusDialogContainer()});break;case\"first-heading\":this._focusByCssSelector('h1, h2, h3, h4, h5, h6, [role=\"heading\"]');break;default:this._focusByCssSelector(this._config.autoFocus)}}_restoreFocus(){const e=this._elementFocusedBeforeDialogWasOpened;if(this._config.restoreFocus&&e&&\"function\"==typeof e.focus){const i=Hm(),r=this._elementRef.nativeElement;(!i||i===this._document.body||i===r||r.contains(i))&&(this._focusMonitor?(this._focusMonitor.focusVia(e,this._closeInteractionType),this._closeInteractionType=null):e.focus())}this._focusTrap&&this._focusTrap.destroy()}_focusDialogContainer(){this._elementRef.nativeElement.focus&&this._elementRef.nativeElement.focus()}_containsFocus(){const e=this._elementRef.nativeElement,i=Hm();return e===i||e.contains(i)}}return n.\\u0275fac=function(e){return new(e||n)(f(W),f(C3),f(Ye),f(ie,8),f(qg),f(Xx),f(ne),f(Qr))},n.\\u0275dir=C({type:n,viewQuery:function(e,i){if(1&e&&je(TE,7),2&e){let r;z(r=U())&&(i._portalOutlet=r.first)}},features:[E]}),n})(),O4=(()=>{class n extends R4{constructor(){super(...arguments),this._state=\"enter\"}_onAnimationDone({toState:e,totalTime:i}){\"enter\"===e?(this._config.delayFocusTrap&&this._trapFocus(),this._animationStateChanged.next({state:\"opened\",totalTime:i})):\"exit\"===e&&(this._restoreFocus(),this._animationStateChanged.next({state:\"closed\",totalTime:i}))}_onAnimationStart({toState:e,totalTime:i}){\"enter\"===e?this._animationStateChanged.next({state:\"opening\",totalTime:i}):(\"exit\"===e||\"void\"===e)&&this._animationStateChanged.next({state:\"closing\",totalTime:i})}_startExitAnimation(){this._state=\"exit\",this._changeDetectorRef.markForCheck()}_initializeWithAttachedContent(){super._initializeWithAttachedContent(),this._config.delayFocusTrap||this._trapFocus()}}return n.\\u0275fac=function(){let t;return function(i){return(t||(t=oe(n)))(i||n)}}(),n.\\u0275cmp=xe({type:n,selectors:[[\"mat-dialog-container\"]],hostAttrs:[\"tabindex\",\"-1\",\"aria-modal\",\"true\",1,\"mat-dialog-container\"],hostVars:6,hostBindings:function(e,i){1&e&&hp(\"@dialogContainer.start\",function(s){return i._onAnimationStart(s)})(\"@dialogContainer.done\",function(s){return i._onAnimationDone(s)}),2&e&&(Yn(\"id\",i._id),Z(\"role\",i._config.role)(\"aria-labelledby\",i._config.ariaLabel?null:i._ariaLabelledBy)(\"aria-label\",i._config.ariaLabel)(\"aria-describedby\",i._config.ariaDescribedBy||null),gp(\"@dialogContainer\",i._state))},features:[E],decls:1,vars:0,consts:[[\"cdkPortalOutlet\",\"\"]],template:function(e,i){1&e&&Ee(0,A4,0,0,\"ng-template\",0)},directives:[TE],styles:[\".mat-dialog-container{display:block;padding:24px;border-radius:4px;box-sizing:border-box;overflow:auto;outline:0;width:100%;height:100%;min-height:inherit;max-height:inherit}.cdk-high-contrast-active .mat-dialog-container{outline:solid 1px}.mat-dialog-content{display:block;margin:0 -24px;padding:0 24px;max-height:65vh;overflow:auto;-webkit-overflow-scrolling:touch}.mat-dialog-title{margin:0 0 20px;display:block}.mat-dialog-actions{padding:8px 0;display:flex;flex-wrap:wrap;min-height:52px;align-items:center;box-sizing:content-box;margin-bottom:-24px}.mat-dialog-actions[align=end]{justify-content:flex-end}.mat-dialog-actions[align=center]{justify-content:center}.mat-dialog-actions .mat-button-base+.mat-button-base,.mat-dialog-actions .mat-mdc-button-base+.mat-mdc-button-base{margin-left:8px}[dir=rtl] .mat-dialog-actions .mat-button-base+.mat-button-base,[dir=rtl] .mat-dialog-actions .mat-mdc-button-base+.mat-mdc-button-base{margin-left:0;margin-right:8px}\\n\"],encapsulation:2,data:{animation:[I4.dialogContainer]}}),n})(),P4=0;class F4{constructor(t,e,i=\"mat-dialog-\"+P4++){this._overlayRef=t,this._containerInstance=e,this.id=i,this.disableClose=this._containerInstance._config.disableClose,this._afterOpened=new O,this._afterClosed=new O,this._beforeClosed=new O,this._state=0,e._id=i,e._animationStateChanged.pipe(Ct(r=>\"opened\"===r.state),it(1)).subscribe(()=>{this._afterOpened.next(),this._afterOpened.complete()}),e._animationStateChanged.pipe(Ct(r=>\"closed\"===r.state),it(1)).subscribe(()=>{clearTimeout(this._closeFallbackTimeout),this._finishDialogClose()}),t.detachments().subscribe(()=>{this._beforeClosed.next(this._result),this._beforeClosed.complete(),this._afterClosed.next(this._result),this._afterClosed.complete(),this.componentInstance=null,this._overlayRef.dispose()}),t.keydownEvents().pipe(Ct(r=>27===r.keyCode&&!this.disableClose&&!Xt(r))).subscribe(r=>{r.preventDefault(),ZS(this,\"keyboard\")}),t.backdropClick().subscribe(()=>{this.disableClose?this._containerInstance._recaptureFocus():ZS(this,\"mouse\")})}close(t){this._result=t,this._containerInstance._animationStateChanged.pipe(Ct(e=>\"closing\"===e.state),it(1)).subscribe(e=>{this._beforeClosed.next(t),this._beforeClosed.complete(),this._overlayRef.detachBackdrop(),this._closeFallbackTimeout=setTimeout(()=>this._finishDialogClose(),e.totalTime+100)}),this._state=1,this._containerInstance._startExitAnimation()}afterOpened(){return this._afterOpened}afterClosed(){return this._afterClosed}beforeClosed(){return this._beforeClosed}backdropClick(){return this._overlayRef.backdropClick()}keydownEvents(){return this._overlayRef.keydownEvents()}updatePosition(t){let e=this._getPositionStrategy();return t&&(t.left||t.right)?t.left?e.left(t.left):e.right(t.right):e.centerHorizontally(),t&&(t.top||t.bottom)?t.top?e.top(t.top):e.bottom(t.bottom):e.centerVertically(),this._overlayRef.updatePosition(),this}updateSize(t=\"\",e=\"\"){return this._overlayRef.updateSize({width:t,height:e}),this._overlayRef.updatePosition(),this}addPanelClass(t){return this._overlayRef.addPanelClass(t),this}removePanelClass(t){return this._overlayRef.removePanelClass(t),this}getState(){return this._state}_finishDialogClose(){this._state=2,this._overlayRef.dispose()}_getPositionStrategy(){return this._overlayRef.getConfig().positionStrategy}}function ZS(n,t,e){return void 0!==n._containerInstance&&(n._containerInstance._closeInteractionType=t),n.close(e)}const N4=new b(\"MatDialogData\"),L4=new b(\"mat-dialog-default-options\"),XS=new b(\"mat-dialog-scroll-strategy\"),V4={provide:XS,deps:[ni],useFactory:function B4(n){return()=>n.scrollStrategies.block()}};let H4=(()=>{class n{constructor(e,i,r,s,o,a,l,c,d,u){this._overlay=e,this._injector=i,this._defaultOptions=r,this._parentDialog=s,this._overlayContainer=o,this._dialogRefConstructor=l,this._dialogContainerType=c,this._dialogDataToken=d,this._openDialogsAtThisLevel=[],this._afterAllClosedAtThisLevel=new O,this._afterOpenedAtThisLevel=new O,this._ariaHiddenElements=new Map,this.afterAllClosed=xa(()=>this.openDialogs.length?this._getAfterAllClosed():this._getAfterAllClosed().pipe(Xn(void 0))),this._scrollStrategy=a}get openDialogs(){return this._parentDialog?this._parentDialog.openDialogs:this._openDialogsAtThisLevel}get afterOpened(){return this._parentDialog?this._parentDialog.afterOpened:this._afterOpenedAtThisLevel}_getAfterAllClosed(){const e=this._parentDialog;return e?e._getAfterAllClosed():this._afterAllClosedAtThisLevel}open(e,i){i=function z4(n,t){return Object.assign(Object.assign({},t),n)}(i,this._defaultOptions||new qg),i.id&&this.getDialogById(i.id);const r=this._createOverlay(i),s=this._attachDialogContainer(r,i),o=this._attachDialogContent(e,s,r,i);return this.openDialogs.length||this._hideNonDialogContentFromAssistiveTechnology(),this.openDialogs.push(o),o.afterClosed().subscribe(()=>this._removeOpenDialog(o)),this.afterOpened.next(o),s._initializeWithAttachedContent(),o}closeAll(){this._closeDialogs(this.openDialogs)}getDialogById(e){return this.openDialogs.find(i=>i.id===e)}ngOnDestroy(){this._closeDialogs(this._openDialogsAtThisLevel),this._afterAllClosedAtThisLevel.complete(),this._afterOpenedAtThisLevel.complete()}_createOverlay(e){const i=this._getOverlayConfig(e);return this._overlay.create(i)}_getOverlayConfig(e){const i=new Gd({positionStrategy:this._overlay.position().global(),scrollStrategy:e.scrollStrategy||this._scrollStrategy(),panelClass:e.panelClass,hasBackdrop:e.hasBackdrop,direction:e.direction,minWidth:e.minWidth,minHeight:e.minHeight,maxWidth:e.maxWidth,maxHeight:e.maxHeight,disposeOnNavigation:e.closeOnNavigation});return e.backdropClass&&(i.backdropClass=e.backdropClass),i}_attachDialogContainer(e,i){const s=dt.create({parent:i&&i.viewContainerRef&&i.viewContainerRef.injector||this._injector,providers:[{provide:qg,useValue:i}]}),o=new yg(this._dialogContainerType,i.viewContainerRef,s,i.componentFactoryResolver);return e.attach(o).instance}_attachDialogContent(e,i,r,s){const o=new this._dialogRefConstructor(r,i,s.id);if(e instanceof ut)i.attachTemplatePortal(new $d(e,null,{$implicit:s.data,dialogRef:o}));else{const a=this._createInjector(s,o,i),l=i.attachComponentPortal(new yg(e,s.viewContainerRef,a,s.componentFactoryResolver));o.componentInstance=l.instance}return o.updateSize(s.width,s.height).updatePosition(s.position),o}_createInjector(e,i,r){const s=e&&e.viewContainerRef&&e.viewContainerRef.injector,o=[{provide:this._dialogContainerType,useValue:r},{provide:this._dialogDataToken,useValue:e.data},{provide:this._dialogRefConstructor,useValue:i}];return e.direction&&(!s||!s.get(On,null,ee.Optional))&&o.push({provide:On,useValue:{value:e.direction,change:q()}}),dt.create({parent:s||this._injector,providers:o})}_removeOpenDialog(e){const i=this.openDialogs.indexOf(e);i>-1&&(this.openDialogs.splice(i,1),this.openDialogs.length||(this._ariaHiddenElements.forEach((r,s)=>{r?s.setAttribute(\"aria-hidden\",r):s.removeAttribute(\"aria-hidden\")}),this._ariaHiddenElements.clear(),this._getAfterAllClosed().next()))}_hideNonDialogContentFromAssistiveTechnology(){const e=this._overlayContainer.getContainerElement();if(e.parentElement){const i=e.parentElement.children;for(let r=i.length-1;r>-1;r--){let s=i[r];s!==e&&\"SCRIPT\"!==s.nodeName&&\"STYLE\"!==s.nodeName&&!s.hasAttribute(\"aria-live\")&&(this._ariaHiddenElements.set(s,s.getAttribute(\"aria-hidden\")),s.setAttribute(\"aria-hidden\",\"true\"))}}}_closeDialogs(e){let i=e.length;for(;i--;)e[i].close()}}return n.\\u0275fac=function(e){Sr()},n.\\u0275dir=C({type:n}),n})(),j4=(()=>{class n extends H4{constructor(e,i,r,s,o,a,l,c){super(e,i,s,a,l,o,F4,O4,N4,c)}}return n.\\u0275fac=function(e){return new(e||n)(y(ni),y(dt),y(va,8),y(L4,8),y(XS),y(n,12),y(Dg),y(Rn,8))},n.\\u0275prov=k({token:n,factory:n.\\u0275fac}),n})(),U4=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[j4,V4],imports:[[ji,Hi,B],B]}),n})(),JS=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),$4=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B,ZE,Hi]]}),n})(),rG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[Vd,ti,B,og,bt],Vd,B,og,JS]}),n})();const lG={provide:new b(\"mat-menu-scroll-strategy\"),deps:[ni],useFactory:function aG(n){return()=>n.scrollStrategies.reposition()}};let cG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[lG],imports:[[bt,B,ti,ji],Ci,B]}),n})();const pG={provide:new b(\"mat-tooltip-scroll-strategy\"),deps:[ni],useFactory:function hG(n){return()=>n.scrollStrategies.reposition({scrollThrottle:20})}};let ik=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[pG],imports:[[Qa,bt,ji,B],B,Ci]}),n})(),Yg=(()=>{class n{constructor(){this.changes=new O,this.itemsPerPageLabel=\"Items per page:\",this.nextPageLabel=\"Next page\",this.previousPageLabel=\"Previous page\",this.firstPageLabel=\"First page\",this.lastPageLabel=\"Last page\",this.getRangeLabel=(e,i,r)=>{if(0==r||0==i)return`0 of ${r}`;const s=e*i;return`${s+1} \\u2013 ${s<(r=Math.max(r,0))?Math.min(s+i,r):s+i} of ${r}`}}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const yG={provide:Yg,deps:[[new Tt,new Cn,Yg]],useFactory:function vG(n){return n||new Yg}};let bG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[yG],imports:[[bt,ul,qE,ik,B]]}),n})(),DG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B],B]}),n})();function wG(n,t){if(1&n&&(Oo(),Le(0,\"circle\",4)),2&n){const e=Be(),i=wn(1);$n(\"animation-name\",\"mat-progress-spinner-stroke-rotate-\"+e._spinnerAnimationLabel)(\"stroke-dashoffset\",e._getStrokeDashOffset(),\"px\")(\"stroke-dasharray\",e._getStrokeCircumference(),\"px\")(\"stroke-width\",e._getCircleStrokeWidth(),\"%\")(\"transform-origin\",e._getCircleTransformOrigin(i)),Z(\"r\",e._getCircleRadius())}}function MG(n,t){if(1&n&&(Oo(),Le(0,\"circle\",4)),2&n){const e=Be(),i=wn(1);$n(\"stroke-dashoffset\",e._getStrokeDashOffset(),\"px\")(\"stroke-dasharray\",e._getStrokeCircumference(),\"px\")(\"stroke-width\",e._getCircleStrokeWidth(),\"%\")(\"transform-origin\",e._getCircleTransformOrigin(i)),Z(\"r\",e._getCircleRadius())}}const EG=fo(class{constructor(n){this._elementRef=n}},\"primary\"),SG=new b(\"mat-progress-spinner-default-options\",{providedIn:\"root\",factory:function kG(){return{diameter:100}}});class dr extends EG{constructor(t,e,i,r,s,o,a,l){super(t),this._document=i,this._diameter=100,this._value=0,this._resizeSubscription=ke.EMPTY,this.mode=\"determinate\";const c=dr._diameters;this._spinnerAnimationLabel=this._getSpinnerAnimationLabel(),c.has(i.head)||c.set(i.head,new Set([100])),this._noopAnimations=\"NoopAnimations\"===r&&!!s&&!s._forceAnimations,\"mat-spinner\"===t.nativeElement.nodeName.toLowerCase()&&(this.mode=\"indeterminate\"),s&&(s.diameter&&(this.diameter=s.diameter),s.strokeWidth&&(this.strokeWidth=s.strokeWidth)),e.isBrowser&&e.SAFARI&&a&&o&&l&&(this._resizeSubscription=a.change(150).subscribe(()=>{\"indeterminate\"===this.mode&&l.run(()=>o.markForCheck())}))}get diameter(){return this._diameter}set diameter(t){this._diameter=Et(t),this._spinnerAnimationLabel=this._getSpinnerAnimationLabel(),this._styleRoot&&this._attachStyleNode()}get strokeWidth(){return this._strokeWidth||this.diameter/10}set strokeWidth(t){this._strokeWidth=Et(t)}get value(){return\"determinate\"===this.mode?this._value:0}set value(t){this._value=Math.max(0,Math.min(100,Et(t)))}ngOnInit(){const t=this._elementRef.nativeElement;this._styleRoot=Fd(t)||this._document.head,this._attachStyleNode(),t.classList.add(\"mat-progress-spinner-indeterminate-animation\")}ngOnDestroy(){this._resizeSubscription.unsubscribe()}_getCircleRadius(){return(this.diameter-10)/2}_getViewBox(){const t=2*this._getCircleRadius()+this.strokeWidth;return`0 0 ${t} ${t}`}_getStrokeCircumference(){return 2*Math.PI*this._getCircleRadius()}_getStrokeDashOffset(){return\"determinate\"===this.mode?this._getStrokeCircumference()*(100-this._value)/100:null}_getCircleStrokeWidth(){return this.strokeWidth/this.diameter*100}_getCircleTransformOrigin(t){var e;const i=50*(null!==(e=t.currentScale)&&void 0!==e?e:1);return`${i}% ${i}%`}_attachStyleNode(){const t=this._styleRoot,e=this._diameter,i=dr._diameters;let r=i.get(t);if(!r||!r.has(e)){const s=this._document.createElement(\"style\");s.setAttribute(\"mat-spinner-animation\",this._spinnerAnimationLabel),s.textContent=this._getAnimationText(),t.appendChild(s),r||(r=new Set,i.set(t,r)),r.add(e)}}_getAnimationText(){const t=this._getStrokeCircumference();return\"\\n @keyframes mat-progress-spinner-stroke-rotate-DIAMETER {\\n 0% { stroke-dashoffset: START_VALUE; transform: rotate(0); }\\n 12.5% { stroke-dashoffset: END_VALUE; transform: rotate(0); }\\n 12.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(72.5deg); }\\n 25% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(72.5deg); }\\n\\n 25.0001% { stroke-dashoffset: START_VALUE; transform: rotate(270deg); }\\n 37.5% { stroke-dashoffset: END_VALUE; transform: rotate(270deg); }\\n 37.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(161.5deg); }\\n 50% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(161.5deg); }\\n\\n 50.0001% { stroke-dashoffset: START_VALUE; transform: rotate(180deg); }\\n 62.5% { stroke-dashoffset: END_VALUE; transform: rotate(180deg); }\\n 62.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(251.5deg); }\\n 75% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(251.5deg); }\\n\\n 75.0001% { stroke-dashoffset: START_VALUE; transform: rotate(90deg); }\\n 87.5% { stroke-dashoffset: END_VALUE; transform: rotate(90deg); }\\n 87.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(341.5deg); }\\n 100% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(341.5deg); }\\n }\\n\".replace(/START_VALUE/g,\"\"+.95*t).replace(/END_VALUE/g,\"\"+.2*t).replace(/DIAMETER/g,`${this._spinnerAnimationLabel}`)}_getSpinnerAnimationLabel(){return this.diameter.toString().replace(\".\",\"_\")}}dr._diameters=new WeakMap,dr.\\u0275fac=function(t){return new(t||dr)(f(W),f(It),f(ie,8),f(Rn,8),f(SG),f(Ye),f(es),f(ne))},dr.\\u0275cmp=xe({type:dr,selectors:[[\"mat-progress-spinner\"],[\"mat-spinner\"]],hostAttrs:[\"role\",\"progressbar\",\"tabindex\",\"-1\",1,\"mat-progress-spinner\",\"mat-spinner\"],hostVars:10,hostBindings:function(t,e){2&t&&(Z(\"aria-valuemin\",\"determinate\"===e.mode?0:null)(\"aria-valuemax\",\"determinate\"===e.mode?100:null)(\"aria-valuenow\",\"determinate\"===e.mode?e.value:null)(\"mode\",e.mode),$n(\"width\",e.diameter,\"px\")(\"height\",e.diameter,\"px\"),Ae(\"_mat-animation-noopable\",e._noopAnimations))},inputs:{color:\"color\",diameter:\"diameter\",strokeWidth:\"strokeWidth\",mode:\"mode\",value:\"value\"},exportAs:[\"matProgressSpinner\"],features:[E],decls:4,vars:8,consts:[[\"preserveAspectRatio\",\"xMidYMid meet\",\"focusable\",\"false\",\"aria-hidden\",\"true\",3,\"ngSwitch\"],[\"svg\",\"\"],[\"cx\",\"50%\",\"cy\",\"50%\",3,\"animation-name\",\"stroke-dashoffset\",\"stroke-dasharray\",\"stroke-width\",\"transform-origin\",4,\"ngSwitchCase\"],[\"cx\",\"50%\",\"cy\",\"50%\",3,\"stroke-dashoffset\",\"stroke-dasharray\",\"stroke-width\",\"transform-origin\",4,\"ngSwitchCase\"],[\"cx\",\"50%\",\"cy\",\"50%\"]],template:function(t,e){1&t&&(Oo(),x(0,\"svg\",0,1),Ee(2,wG,1,11,\"circle\",2),Ee(3,MG,1,9,\"circle\",3),S()),2&t&&($n(\"width\",e.diameter,\"px\")(\"height\",e.diameter,\"px\"),N(\"ngSwitch\",\"indeterminate\"===e.mode),Z(\"viewBox\",e._getViewBox()),T(2),N(\"ngSwitchCase\",!0),T(1),N(\"ngSwitchCase\",!1))},directives:[Ys,Pc],styles:[\".mat-progress-spinner{display:block;position:relative;overflow:hidden}.mat-progress-spinner svg{position:absolute;transform:rotate(-90deg);top:0;left:0;transform-origin:center;overflow:visible}.mat-progress-spinner circle{fill:transparent;transition:stroke-dashoffset 225ms linear}._mat-animation-noopable.mat-progress-spinner circle{transition:none;animation:none}.cdk-high-contrast-active .mat-progress-spinner circle{stroke:CanvasText}.mat-progress-spinner.mat-progress-spinner-indeterminate-animation[mode=indeterminate] svg{animation:mat-progress-spinner-linear-rotate 2000ms linear infinite}._mat-animation-noopable.mat-progress-spinner.mat-progress-spinner-indeterminate-animation[mode=indeterminate] svg{transition:none;animation:none}.mat-progress-spinner.mat-progress-spinner-indeterminate-animation[mode=indeterminate] circle{transition-property:stroke;animation-duration:4000ms;animation-timing-function:cubic-bezier(0.35, 0, 0.25, 1);animation-iteration-count:infinite}._mat-animation-noopable.mat-progress-spinner.mat-progress-spinner-indeterminate-animation[mode=indeterminate] circle{transition:none;animation:none}@keyframes mat-progress-spinner-linear-rotate{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@keyframes mat-progress-spinner-stroke-rotate-100{0%{stroke-dashoffset:268.606171575px;transform:rotate(0)}12.5%{stroke-dashoffset:56.5486677px;transform:rotate(0)}12.5001%{stroke-dashoffset:56.5486677px;transform:rotateX(180deg) rotate(72.5deg)}25%{stroke-dashoffset:268.606171575px;transform:rotateX(180deg) rotate(72.5deg)}25.0001%{stroke-dashoffset:268.606171575px;transform:rotate(270deg)}37.5%{stroke-dashoffset:56.5486677px;transform:rotate(270deg)}37.5001%{stroke-dashoffset:56.5486677px;transform:rotateX(180deg) rotate(161.5deg)}50%{stroke-dashoffset:268.606171575px;transform:rotateX(180deg) rotate(161.5deg)}50.0001%{stroke-dashoffset:268.606171575px;transform:rotate(180deg)}62.5%{stroke-dashoffset:56.5486677px;transform:rotate(180deg)}62.5001%{stroke-dashoffset:56.5486677px;transform:rotateX(180deg) rotate(251.5deg)}75%{stroke-dashoffset:268.606171575px;transform:rotateX(180deg) rotate(251.5deg)}75.0001%{stroke-dashoffset:268.606171575px;transform:rotate(90deg)}87.5%{stroke-dashoffset:56.5486677px;transform:rotate(90deg)}87.5001%{stroke-dashoffset:56.5486677px;transform:rotateX(180deg) rotate(341.5deg)}100%{stroke-dashoffset:268.606171575px;transform:rotateX(180deg) rotate(341.5deg)}}\\n\"],encapsulation:2,changeDetection:0});let AG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B,bt],B]}),n})(),UG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ti,B],B]}),n})(),GG=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B,Ci],Ci,B]}),n})(),ak=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({}),n})(),sW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ak,ti,B,Ya],ak,B]}),n})(),lW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[ji,Hi,bt,ul,B],B]}),n})(),Kg=(()=>{class n{constructor(){this.changes=new O}}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275prov=k({token:n,factory:n.\\u0275fac,providedIn:\"root\"}),n})();const uW={provide:Kg,deps:[[new Tt,new Cn,Kg]],useFactory:function dW(n){return n||new Kg}};let hW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({providers:[uW],imports:[[bt,B]]}),n})(),TW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bS,B],B]}),n})(),FW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[bt,B,Hi,ti,Ya,Qa],B]}),n})(),NW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[B],B]}),n})(),$W=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[[CS,B],B]}),n})(),GW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n}),n.\\u0275inj=P({imports:[Qa,ZE,m$,fS,bS,CS,S$,t8,n8,r8,ul,u8,h8,M8,L8,u4,T4,U4,JS,$4,CU,WS,a$,rG,cG,U3,bG,DG,AG,UG,ti,qE,GG,gE,sW,lW,hW,TW,FW,NW,ik,$W,ji,Hi,Ud]}),n})(),WW=(()=>{class n{}return n.\\u0275fac=function(e){return new(e||n)},n.\\u0275mod=F({type:n,bootstrap:[f$]}),n.\\u0275inj=P({providers:[],imports:[[FD,B2,Pz,Fz,Nj,gE,GW]]}),n})();(function YF(){G0=!1})(),console.info(\"Angular CDK version\",Lm.full),console.info(\"Angular Material version\",Jm.full),oB().bootstrapModule(WW).catch(n=>console.error(n))}},De=>{De(De.s=532)}]);", "file_path": "docs/main.e3e00859dfd66644.js", "rank": 21, "score": 96506.13743688195 }, { "content": " constructor(public message: string) {\n\n super(message);\n", "file_path": "HTLC/lambda_function_for_tokens/taquito-michel-codec/src/base58.ts", "rank": 22, "score": 95593.55973472646 }, { "content": "/// Connect the socket, either by using the pool or grab a new one.\n\nfn connect_socket(unit: &Unit, hostname: &str, use_pooled: bool) -> Result<(Stream, bool), Error> {\n\n match unit.url.scheme() {\n\n \"http\" | \"https\" | \"test\" => (),\n\n scheme => return Err(ErrorKind::UnknownScheme.msg(&format!(\"unknown scheme '{}'\", scheme))),\n\n };\n\n if use_pooled {\n\n let pool = &unit.agent.state.pool;\n\n let proxy = &unit.agent.config.proxy;\n\n // The connection may have been closed by the server\n\n // due to idle timeout while it was sitting in the pool.\n\n // Loop until we find one that is still good or run out of connections.\n\n while let Some(stream) = pool.try_get_connection(&unit.url, proxy.clone()) {\n\n let server_closed = stream.server_closed()?;\n\n if !server_closed {\n\n return Ok((stream, true));\n\n }\n\n debug!(\"dropping stream from pool; closed by server: {:?}\", stream);\n\n }\n\n }\n\n let stream = match unit.url.scheme() {\n\n \"http\" => stream::connect_http(&unit, hostname),\n\n \"https\" => stream::connect_https(&unit, hostname),\n\n \"test\" => connect_test(&unit),\n\n scheme => Err(ErrorKind::UnknownScheme.msg(&format!(\"unknown scheme {}\", scheme))),\n\n };\n\n Ok((stream?, false))\n\n}\n\n\n\n/// Send request line + headers (all up until the body).\n", "file_path": "rust batch listener/ureq/src/unit.rs", "rank": 23, "score": 92690.01228209567 }, { "content": "/// Connect the socket, either by using the pool or grab a new one.\n\nfn connect_socket(unit: &Unit, hostname: &str, use_pooled: bool) -> Result<(Stream, bool), Error> {\n\n match unit.url.scheme() {\n\n \"http\" | \"https\" | \"test\" => (),\n\n scheme => return Err(ErrorKind::UnknownScheme.msg(&format!(\"unknown scheme '{}'\", scheme))),\n\n };\n\n if use_pooled {\n\n let pool = &unit.agent.state.pool;\n\n let proxy = &unit.agent.config.proxy;\n\n // The connection may have been closed by the server\n\n // due to idle timeout while it was sitting in the pool.\n\n // Loop until we find one that is still good or run out of connections.\n\n while let Some(stream) = pool.try_get_connection(&unit.url, proxy.clone()) {\n\n let server_closed = stream.server_closed()?;\n\n if !server_closed {\n\n return Ok((stream, true));\n\n }\n\n debug!(\"dropping stream from pool; closed by server: {:?}\", stream);\n\n }\n\n }\n\n let stream = match unit.url.scheme() {\n\n \"http\" => stream::connect_http(&unit, hostname),\n\n \"https\" => stream::connect_https(&unit, hostname),\n\n \"test\" => connect_test(&unit),\n\n scheme => Err(ErrorKind::UnknownScheme.msg(&format!(\"unknown scheme {}\", scheme))),\n\n };\n\n Ok((stream?, false))\n\n}\n\n\n\n/// Send request line + headers (all up until the body).\n", "file_path": "rust token listener/ureq/src/unit.rs", "rank": 24, "score": 92690.01228209567 }, { "content": "/// Connect the socket, either by using the pool or grab a new one.\n\nfn connect_socket(unit: &Unit, hostname: &str, use_pooled: bool) -> Result<(Stream, bool), Error> {\n\n match unit.url.scheme() {\n\n \"http\" | \"https\" | \"test\" => (),\n\n scheme => return Err(ErrorKind::UnknownScheme.msg(&format!(\"unknown scheme '{}'\", scheme))),\n\n };\n\n if use_pooled {\n\n let pool = &unit.agent.state.pool;\n\n let proxy = &unit.agent.config.proxy;\n\n // The connection may have been closed by the server\n\n // due to idle timeout while it was sitting in the pool.\n\n // Loop until we find one that is still good or run out of connections.\n\n while let Some(stream) = pool.try_get_connection(&unit.url, proxy.clone()) {\n\n let server_closed = stream.server_closed()?;\n\n if !server_closed {\n\n return Ok((stream, true));\n\n }\n\n debug!(\"dropping stream from pool; closed by server: {:?}\", stream);\n\n }\n\n }\n\n let stream = match unit.url.scheme() {\n\n \"http\" => stream::connect_http(&unit, hostname),\n\n \"https\" => stream::connect_https(&unit, hostname),\n\n \"test\" => connect_test(&unit),\n\n scheme => Err(ErrorKind::UnknownScheme.msg(&format!(\"unknown scheme {}\", scheme))),\n\n };\n\n Ok((stream?, false))\n\n}\n\n\n\n/// Send request line + headers (all up until the body).\n", "file_path": "rust token listener/urequ/src/unit.rs", "rank": 25, "score": 92690.01228209567 }, { "content": "#[derive(Debug, Clone)]\n\nenum Urlish {\n\n Url(Url),\n\n Str(String),\n\n}\n\n\n\n/// Request instances are builders that creates a request.\n\n///\n\n/// ```\n\n/// # fn main() -> Result<(), ureq::Error> {\n\n/// # ureq::is_test(true);\n\n/// let response = ureq::get(\"http://example.com/form\")\n\n/// .query(\"foo\", \"bar baz\") // add ?foo=bar+baz\n\n/// .call()?; // run the request\n\n/// # Ok(())\n\n/// # }\n\n/// ```\n\n#[derive(Clone)]\n\npub struct Request {\n\n agent: Agent,\n\n method: String,\n", "file_path": "rust token listener/urequ/src/request.rs", "rank": 26, "score": 90920.87052139065 }, { "content": "#[derive(Debug, Clone)]\n\nenum Urlish {\n\n Url(Url),\n\n Str(String),\n\n}\n\n\n\n/// Request instances are builders that creates a request.\n\n///\n\n/// ```\n\n/// # fn main() -> Result<(), ureq::Error> {\n\n/// # ureq::is_test(true);\n\n/// let response = ureq::get(\"http://example.com/form\")\n\n/// .query(\"foo\", \"bar baz\") // add ?foo=bar+baz\n\n/// .call()?; // run the request\n\n/// # Ok(())\n\n/// # }\n\n/// ```\n\n#[derive(Clone)]\n\npub struct Request {\n\n agent: Agent,\n\n method: String,\n", "file_path": "rust token listener/ureq/src/request.rs", "rank": 27, "score": 90920.87052139065 }, { "content": "#[derive(Debug, Clone)]\n\nenum Urlish {\n\n Url(Url),\n\n Str(String),\n\n}\n\n\n\n/// Request instances are builders that creates a request.\n\n///\n\n/// ```\n\n/// # fn main() -> Result<(), ureq::Error> {\n\n/// # ureq::is_test(true);\n\n/// let response = ureq::get(\"http://example.com/form\")\n\n/// .query(\"foo\", \"bar baz\") // add ?foo=bar+baz\n\n/// .call()?; // run the request\n\n/// # Ok(())\n\n/// # }\n\n/// ```\n\n#[derive(Clone)]\n\npub struct Request {\n\n agent: Agent,\n\n method: String,\n", "file_path": "rust batch listener/ureq/src/request.rs", "rank": 28, "score": 90920.87052139065 }, { "content": "enum Inner {\n\n Http(TcpStream),\n\n #[cfg(feature = \"tls\")]\n\n Https(rustls::StreamOwned<rustls::ClientSession, TcpStream>),\n\n Test(Box<dyn Read + Send + Sync>, Vec<u8>),\n\n}\n\n\n\n// DeadlineStream wraps a stream such that read() will return an error\n\n// after the provided deadline, and sets timeouts on the underlying\n\n// TcpStream to ensure read() doesn't block beyond the deadline.\n\n// When the From trait is used to turn a DeadlineStream back into a\n\n// Stream (by PoolReturningRead), the timeouts are removed.\n\npub(crate) struct DeadlineStream {\n\n stream: Stream,\n\n deadline: Option<Instant>,\n\n}\n\n\n\nimpl DeadlineStream {\n\n pub(crate) fn new(stream: Stream, deadline: Option<Instant>) -> Self {\n\n DeadlineStream { stream, deadline }\n", "file_path": "rust batch listener/ureq/src/stream.rs", "rank": 29, "score": 90915.24913248664 }, { "content": "enum Inner {\n\n Http(TcpStream),\n\n #[cfg(feature = \"tls\")]\n\n Https(rustls::StreamOwned<rustls::ClientSession, TcpStream>),\n\n Test(Box<dyn Read + Send + Sync>, Vec<u8>),\n\n}\n\n\n\n// DeadlineStream wraps a stream such that read() will return an error\n\n// after the provided deadline, and sets timeouts on the underlying\n\n// TcpStream to ensure read() doesn't block beyond the deadline.\n\n// When the From trait is used to turn a DeadlineStream back into a\n\n// Stream (by PoolReturningRead), the timeouts are removed.\n\npub(crate) struct DeadlineStream {\n\n stream: Stream,\n\n deadline: Option<Instant>,\n\n}\n\n\n\nimpl DeadlineStream {\n\n pub(crate) fn new(stream: Stream, deadline: Option<Instant>) -> Self {\n\n DeadlineStream { stream, deadline }\n", "file_path": "rust token listener/urequ/src/stream.rs", "rank": 30, "score": 90915.24913248664 }, { "content": "enum Inner {\n\n Http(TcpStream),\n\n #[cfg(feature = \"tls\")]\n\n Https(rustls::StreamOwned<rustls::ClientSession, TcpStream>),\n\n Test(Box<dyn Read + Send + Sync>, Vec<u8>),\n\n}\n\n\n\n// DeadlineStream wraps a stream such that read() will return an error\n\n// after the provided deadline, and sets timeouts on the underlying\n\n// TcpStream to ensure read() doesn't block beyond the deadline.\n\n// When the From trait is used to turn a DeadlineStream back into a\n\n// Stream (by PoolReturningRead), the timeouts are removed.\n\npub(crate) struct DeadlineStream {\n\n stream: Stream,\n\n deadline: Option<Instant>,\n\n}\n\n\n\nimpl DeadlineStream {\n\n pub(crate) fn new(stream: Stream, deadline: Option<Instant>) -> Self {\n\n DeadlineStream { stream, deadline }\n", "file_path": "rust token listener/ureq/src/stream.rs", "rank": 31, "score": 90915.24913248664 }, { "content": "// ErrorReader returns an error for every read.\n\n// The error is as close to a clone of the underlying\n\n// io::Error as we can get.\n\nstruct ErrorReader(io::Error);\n\n\n\nimpl Read for ErrorReader {\n\n fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {\n\n Err(io::Error::new(self.0.kind(), self.0.to_string()))\n\n }\n\n}\n", "file_path": "rust batch listener/ureq/src/response.rs", "rank": 32, "score": 89875.47750017382 }, { "content": "// ErrorReader returns an error for every read.\n\n// The error is as close to a clone of the underlying\n\n// io::Error as we can get.\n\nstruct ErrorReader(io::Error);\n\n\n\nimpl Read for ErrorReader {\n\n fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {\n\n Err(io::Error::new(self.0.kind(), self.0.to_string()))\n\n }\n\n}\n", "file_path": "rust token listener/ureq/src/response.rs", "rank": 33, "score": 89875.47750017382 }, { "content": "// ErrorReader returns an error for every read.\n\n// The error is as close to a clone of the underlying\n\n// io::Error as we can get.\n\nstruct ErrorReader(io::Error);\n\n\n\nimpl Read for ErrorReader {\n\n fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {\n\n Err(io::Error::new(self.0.kind(), self.0.to_string()))\n\n }\n\n}\n", "file_path": "rust token listener/urequ/src/response.rs", "rank": 34, "score": 89875.47750017382 }, { "content": "enum DocAttr {\n\n None,\n\n Summary(String),\n\n Doc(String),\n\n}\n\n\n\nimpl DocAttr {\n\n fn from(attr: &Attribute) -> DocAttr {\n\n match attr.parse_meta() {\n\n Ok(Meta::NameValue(ref meta)) => {\n\n return get_value_of(\"doc\", meta)\n\n .map(|x| DocAttr::Doc(x))\n\n .unwrap_or(DocAttr::None);\n\n }\n\n Ok(Meta::List(ref list)) => {\n\n if path_is(&list.path, \"doc\") {\n\n if let Some(NestedMeta::Meta(Meta::NameValue(meta))) = list.nested.first() {\n\n return get_value_of(\"summary\", &meta)\n\n .map(|x| DocAttr::Summary(x))\n\n .unwrap_or(DocAttr::None);\n\n }\n\n }\n\n }\n\n _ => (),\n\n };\n\n DocAttr::None\n\n }\n\n}\n\n\n", "file_path": "rust_everscale/api/derive/src/utils.rs", "rank": 35, "score": 89654.02839652741 }, { "content": "enum SupportedNetwork {\n\n Main(String),\n\n Beta(String),\n\n Florence(String),\n\n Edo(String),\n\n Delphi(String),\n\n}\n\n\n\nimpl TryFrom<Network> for SupportedNetwork {\n\n type Error = UnsupportedNetworkError;\n\n\n\n fn try_from(network: Network) -> Result<Self, Self::Error> {\n\n match network {\n\n Network::Main(s) => Ok(SupportedNetwork::Main(s)),\n\n Network::Beta(s) => Ok(SupportedNetwork::Beta(s)),\n\n Network::Florence(s) => Ok(SupportedNetwork::Florence(s)),\n\n Network::Edo(s) => Ok(SupportedNetwork::Edo(s)),\n\n Network::Delphi(s) => Ok(SupportedNetwork::Delphi(s)),\n\n _ => Err(UnsupportedNetworkError {\n\n explorer_type: \"TzStats\".to_owned(),\n", "file_path": "rust token listener/explorer_api/src/tzstats.rs", "rank": 36, "score": 88452.91116216543 }, { "content": "/// Connect the socket, either by using the pool or grab a new one.\n\nfn connect_socket(unit: &Unit, hostname: &str, use_pooled: bool) -> Result<(Stream, bool), Error> {\n\n match unit.url.scheme() {\n\n \"http\" | \"https\" | \"test\" => (),\n\n scheme => return Err(ErrorKind::UnknownScheme.msg(&format!(\"unknown scheme '{}'\", scheme))),\n\n };\n\n if use_pooled {\n\n let pool = &unit.agent.state.pool;\n\n let proxy = &unit.agent.config.proxy;\n\n // The connection may have been closed by the server\n\n // due to idle timeout while it was sitting in the pool.\n\n // Loop until we find one that is still good or run out of connections.\n\n while let Some(stream) = pool.try_get_connection(&unit.url, proxy.clone()) {\n\n let server_closed = stream.server_closed()?;\n\n if !server_closed {\n\n return Ok((stream, true));\n\n }\n\n debug!(\"dropping stream from pool; closed by server: {:?}\", stream);\n\n }\n\n }\n\n let stream = match unit.url.scheme() {\n\n \"http\" => stream::connect_http(&unit, hostname),\n\n \"https\" => stream::connect_https(&unit, hostname),\n\n \"test\" => connect_test(&unit),\n\n scheme => Err(ErrorKind::UnknownScheme.msg(&format!(\"unknown scheme {}\", scheme))),\n\n };\n\n Ok((stream?, false))\n\n}\n\n\n\n/// Send request line + headers (all up until the body).\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/ureq/src/unit.rs", "rank": 37, "score": 88360.00243224758 }, { "content": "#[derive(Debug, Clone)]\n\nenum Urlish {\n\n Url(Url),\n\n Str(String),\n\n}\n\n\n\n/// Request instances are builders that creates a request.\n\n///\n\n/// ```\n\n/// # fn main() -> Result<(), ureq::Error> {\n\n/// # ureq::is_test(true);\n\n/// let response = ureq::get(\"http://example.com/form\")\n\n/// .query(\"foo\", \"bar baz\") // add ?foo=bar+baz\n\n/// .call()?; // run the request\n\n/// # Ok(())\n\n/// # }\n\n/// ```\n\n#[derive(Clone)]\n\npub struct Request {\n\n agent: Agent,\n\n method: String,\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/ureq/src/request.rs", "rank": 38, "score": 87313.32245664447 }, { "content": "enum Inner {\n\n Http(TcpStream),\n\n #[cfg(feature = \"tls\")]\n\n Https(rustls::StreamOwned<rustls::ClientSession, TcpStream>),\n\n Test(Box<dyn Read + Send + Sync>, Vec<u8>),\n\n}\n\n\n\n// DeadlineStream wraps a stream such that read() will return an error\n\n// after the provided deadline, and sets timeouts on the underlying\n\n// TcpStream to ensure read() doesn't block beyond the deadline.\n\n// When the From trait is used to turn a DeadlineStream back into a\n\n// Stream (by PoolReturningRead), the timeouts are removed.\n\npub(crate) struct DeadlineStream {\n\n stream: Stream,\n\n deadline: Option<Instant>,\n\n}\n\n\n\nimpl DeadlineStream {\n\n pub(crate) fn new(stream: Stream, deadline: Option<Instant>) -> Self {\n\n DeadlineStream { stream, deadline }\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/ureq/src/stream.rs", "rank": 39, "score": 87307.70106774048 }, { "content": "// ErrorReader returns an error for every read.\n\n// The error is as close to a clone of the underlying\n\n// io::Error as we can get.\n\nstruct ErrorReader(io::Error);\n\n\n\nimpl Read for ErrorReader {\n\n fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {\n\n Err(io::Error::new(self.0.kind(), self.0.to_string()))\n\n }\n\n}\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/ureq/src/response.rs", "rank": 40, "score": 87226.94102296716 }, { "content": "enum SupportedNetwork {\n\n Main(String),\n\n Beta(String),\n\n Florence(String),\n\n Edo(String),\n\n Delphi(String),\n\n}\n\n\n\nimpl TryFrom<Network> for SupportedNetwork {\n\n type Error = UnsupportedNetworkError;\n\n\n\n fn try_from(network: Network) -> Result<Self, Self::Error> {\n\n match network {\n\n Network::Main(s) => Ok(SupportedNetwork::Main(s)),\n\n Network::Beta(s) => Ok(SupportedNetwork::Beta(s)),\n\n Network::Florence(s) => Ok(SupportedNetwork::Florence(s)),\n\n Network::Edo(s) => Ok(SupportedNetwork::Edo(s)),\n\n Network::Delphi(s) => Ok(SupportedNetwork::Delphi(s)),\n\n _ => Err(UnsupportedNetworkError {\n\n explorer_type: \"TzStats\".to_owned(),\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/explorer_api/src/tzstats.rs", "rank": 41, "score": 85170.08321665422 }, { "content": "#[derive(PartialEq, Debug, Clone)]\n\nenum OperationType {\n\n Transaction { to: Address, amount: u64 },\n\n Delegation { to: Option<ImplicitAddress> },\n\n}\n\n\n\npub struct OperationCommand {\n\n pub options: OperationOptions,\n\n pub from: Address,\n\n pub fee: Option<u64>,\n\n\n\n pub api: Box<dyn OperationCommandApi>,\n\n pub state: OperationCommandState,\n\n /// If `Some`, Local wallet will be used to execute an operation.\n\n pub local_state: Option<LocalWalletState>,\n\n}\n\n\n\nimpl OperationCommand {\n\n fn get_version(&mut self) -> GetVersionInfoResult {\n\n let version = self.state.version.as_ref()\n\n .map(|version| Ok(version.clone()))\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/lib/src/common/operation_command/mod.rs", "rank": 42, "score": 83219.97670988887 }, { "content": "pub trait WithPrefix {\n\n type Target;\n\n\n\n /// returns value with prefix prepended.\n\n fn with_prefix(&self, prefix: Prefix) -> Self::Target;\n\n}\n\n\n\nimpl WithPrefix for [u8] {\n\n type Target = Vec<u8>;\n\n\n\n fn with_prefix(&self, prefix: Prefix) -> Self::Target {\n\n [prefix.as_ref().to_vec(), self.to_vec()].concat()\n\n }\n\n}\n\n\n", "file_path": "rust token listener/crypto/src/prefix.rs", "rank": 43, "score": 82879.63030486816 }, { "content": "import { SDK_VERSION } from '@airgap/beacon-sdk'\n\nimport { ErrorHandler, Injectable } from '@angular/core'\n\nimport { captureException, configureScope, Event, init, Scope, withScope } from '@sentry/browser'\n\n\n\ninit({\n\n dsn: 'https://[email protected]/172',\n\n release: 'unknown'\n\n})\n\n\n\nexport enum ErrorCategory {\n\n UNKNOWN = 'unknown'\n\n}\n\n\n\nconst ERROR_CATEGORY_TAG: string = 'error-category'\n\nconst SDK_VERSION_TAG: string = 'sdk-version'\n\n\n\nconst handleErrorSentry: (category?: ErrorCategory) => (error: any) => void = (\n\n category: ErrorCategory = ErrorCategory.UNKNOWN\n\n): ((error: any) => void) => {\n\n return (error: any): void => {\n\n try {\n\n withScope((scope: Scope) => {\n\n scope.setTag(ERROR_CATEGORY_TAG, category)\n\n scope.setTag(SDK_VERSION_TAG, SDK_VERSION)\n\n const eventId: string = captureException(error.originalError || error)\n\n // tslint:disable-next-line\n\n console.debug(`[sentry](${category}) - ${eventId}`)\n\n })\n\n } catch (sentryReportingError) {\n\n // tslint:disable-next-line\n\n console.debug('Error reporting exception to sentry: ', sentryReportingError)\n\n }\n\n }\n\n}\n\n\n\nconst handleErrorIgnore: (error: any) => void = (error: any): void => {\n\n // tslint:disable\n\n console.debug('[Sentry]: not sending to sentry')\n\n console.debug(error.originalError || error)\n\n // tslint:enable\n\n}\n\n\n\nconst setSentryRelease: (release: string) => void = (release: string): void => {\n\n configureScope((scope: Scope) => {\n\n scope.addEventProcessor(async (event: Event) => {\n\n event.release = release\n\n\n\n return event\n\n })\n\n })\n\n}\n\n\n\nconst setSentryUser: (UUID: string) => void = (UUID: string): void => {\n\n configureScope((scope: Scope) => {\n\n scope.setUser({ id: UUID })\n\n })\n\n}\n\n\n\nexport { setSentryRelease, setSentryUser, handleErrorIgnore, handleErrorSentry }\n\n\n\n@Injectable()\n\nexport class SentryErrorHandler extends ErrorHandler {\n\n public handleError(error: any): void {\n\n super.handleError(error)\n\n handleErrorSentry()(error)\n\n }\n\n}\n", "file_path": "test/wallet_integration/tezoswallet/src/app/classes/sentry-error-handler/sentry-error-handler.ts", "rank": 44, "score": 82546.61813516398 }, { "content": "import { SentryErrorHandler } from './sentry-error-handler'\n\n\n\ndescribe('SentryErrorHandler', () => {\n\n it('should create an instance', () => {\n\n expect(new SentryErrorHandler()).toBeTruthy()\n\n })\n\n})\n", "file_path": "test/wallet_integration/tezoswallet/src/app/classes/sentry-error-handler/sentry-error-handler.spec.ts", "rank": 45, "score": 81953.39318233595 }, { "content": "pub trait ApiType {\n\n fn api() -> Field;\n\n}\n\n\n", "file_path": "rust_everscale/api/info/src/lib.rs", "rank": 46, "score": 81683.40711956355 }, { "content": "pub trait WithoutPrefix {\n\n type Target;\n\n\n\n /// returns value with prefix removed.\n\n fn without_prefix(&self, prefix: Prefix) -> Result<Self::Target, NotMatchingPrefixError>;\n\n}\n\n\n\nimpl WithoutPrefix for [u8] {\n\n type Target = Vec<u8>;\n\n\n\n fn without_prefix(&self, prefix: Prefix) -> Result<Self::Target, NotMatchingPrefixError> {\n\n let prefix_bytes: &[u8] = prefix.as_ref();\n\n\n\n if prefix_bytes.len() > self.len() || prefix_bytes != &self[..prefix_bytes.len()] {\n\n return Err(NotMatchingPrefixError);\n\n }\n\n\n\n Ok(self[prefix_bytes.len()..].to_vec())\n\n }\n\n}\n", "file_path": "rust token listener/crypto/src/prefix.rs", "rank": 47, "score": 81683.40711956355 }, { "content": "pub trait Forge {\n\n fn forge(&self) -> Forged;\n\n}\n\n\n", "file_path": "rust token listener/types/src/forge/mod.rs", "rank": 48, "score": 81683.40711956355 }, { "content": "pub trait ApiModule {\n\n fn api() -> Module;\n\n}\n", "file_path": "rust_everscale/api/info/src/lib.rs", "rank": 49, "score": 81683.40711956355 }, { "content": "#[test]\n\npub fn no_status_text() {\n\n // this one doesn't return the status text\n\n // let resp = get(\"https://www.okex.com/api/spot/v3/products\")\n\n test::set_handler(\"/no_status_text\", |_unit| {\n\n test::make_response(200, \"\", vec![], vec![])\n\n });\n\n let resp = get(\"test://host/no_status_text\").call().unwrap();\n\n assert_eq!(resp.status(), 200);\n\n}\n\n\n", "file_path": "rust batch listener/ureq/src/test/simple.rs", "rank": 50, "score": 80542.8632760446 }, { "content": "#[test]\n\npub fn no_status_text() {\n\n // this one doesn't return the status text\n\n // let resp = get(\"https://www.okex.com/api/spot/v3/products\")\n\n test::set_handler(\"/no_status_text\", |_unit| {\n\n test::make_response(200, \"\", vec![], vec![])\n\n });\n\n let resp = get(\"test://host/no_status_text\").call().unwrap();\n\n assert_eq!(resp.status(), 200);\n\n}\n\n\n", "file_path": "rust token listener/urequ/src/test/simple.rs", "rank": 51, "score": 80542.8632760446 }, { "content": "#[test]\n\npub fn no_status_text() {\n\n // this one doesn't return the status text\n\n // let resp = get(\"https://www.okex.com/api/spot/v3/products\")\n\n test::set_handler(\"/no_status_text\", |_unit| {\n\n test::make_response(200, \"\", vec![], vec![])\n\n });\n\n let resp = get(\"test://host/no_status_text\").call().unwrap();\n\n assert_eq!(resp.status(), 200);\n\n}\n\n\n", "file_path": "rust token listener/ureq/src/test/simple.rs", "rank": 52, "score": 80542.8632760446 }, { "content": "#[test]\n\npub fn host_with_port() {\n\n test::set_handler(\"/host_with_port\", |_| {\n\n test::make_response(200, \"OK\", vec![], vec![])\n\n });\n\n let resp = get(\"test://myhost:234/host_with_port\").call().unwrap();\n\n let vec = resp.to_write_vec();\n\n let s = String::from_utf8_lossy(&vec);\n\n assert!(s.contains(\"\\r\\nHost: myhost:234\\r\\n\"));\n\n}\n", "file_path": "rust batch listener/ureq/src/test/simple.rs", "rank": 53, "score": 80542.8632760446 }, { "content": "#[test]\n\npub fn host_with_port() {\n\n test::set_handler(\"/host_with_port\", |_| {\n\n test::make_response(200, \"OK\", vec![], vec![])\n\n });\n\n let resp = get(\"test://myhost:234/host_with_port\").call().unwrap();\n\n let vec = resp.to_write_vec();\n\n let s = String::from_utf8_lossy(&vec);\n\n assert!(s.contains(\"\\r\\nHost: myhost:234\\r\\n\"));\n\n}\n", "file_path": "rust token listener/urequ/src/test/simple.rs", "rank": 54, "score": 80542.8632760446 }, { "content": "#[test]\n\npub fn host_with_port() {\n\n test::set_handler(\"/host_with_port\", |_| {\n\n test::make_response(200, \"OK\", vec![], vec![])\n\n });\n\n let resp = get(\"test://myhost:234/host_with_port\").call().unwrap();\n\n let vec = resp.to_write_vec();\n\n let s = String::from_utf8_lossy(&vec);\n\n assert!(s.contains(\"\\r\\nHost: myhost:234\\r\\n\"));\n\n}\n", "file_path": "rust token listener/ureq/src/test/simple.rs", "rank": 55, "score": 80542.8632760446 }, { "content": "#[test]\n\npub fn host_no_port() {\n\n test::set_handler(\"/host_no_port\", |_| {\n\n test::make_response(200, \"OK\", vec![], vec![])\n\n });\n\n let resp = get(\"test://myhost/host_no_port\").call().unwrap();\n\n let vec = resp.to_write_vec();\n\n let s = String::from_utf8_lossy(&vec);\n\n assert!(s.contains(\"\\r\\nHost: myhost\\r\\n\"));\n\n}\n\n\n", "file_path": "rust token listener/ureq/src/test/simple.rs", "rank": 56, "score": 80542.8632760446 }, { "content": "#[test]\n\npub fn host_no_port() {\n\n test::set_handler(\"/host_no_port\", |_| {\n\n test::make_response(200, \"OK\", vec![], vec![])\n\n });\n\n let resp = get(\"test://myhost/host_no_port\").call().unwrap();\n\n let vec = resp.to_write_vec();\n\n let s = String::from_utf8_lossy(&vec);\n\n assert!(s.contains(\"\\r\\nHost: myhost\\r\\n\"));\n\n}\n\n\n", "file_path": "rust token listener/urequ/src/test/simple.rs", "rank": 57, "score": 80542.8632760446 }, { "content": "#[test]\n\npub fn host_no_port() {\n\n test::set_handler(\"/host_no_port\", |_| {\n\n test::make_response(200, \"OK\", vec![], vec![])\n\n });\n\n let resp = get(\"test://myhost/host_no_port\").call().unwrap();\n\n let vec = resp.to_write_vec();\n\n let s = String::from_utf8_lossy(&vec);\n\n assert!(s.contains(\"\\r\\nHost: myhost\\r\\n\"));\n\n}\n\n\n", "file_path": "rust batch listener/ureq/src/test/simple.rs", "rank": 58, "score": 80542.8632760446 }, { "content": "pub trait ForgeNat {\n\n /// Encode a number using LEB128 encoding (Zarith).\n\n fn forge_nat(&self) -> Forged;\n\n}\n", "file_path": "rust token listener/types/src/forge/mod.rs", "rank": 59, "score": 80542.8632760446 }, { "content": "pub trait SignOperation {\n\n // TODO: replace String type with newtype to avoid errors\n\n fn sign_operation(&self, forged_operation: String) -> SignOperationResult;\n\n}\n", "file_path": "rust token listener/signer/src/sign_operation.rs", "rank": 60, "score": 80542.8632760446 }, { "content": "pub fn set_config(\n\n mut conf: Config,\n\n path: &str,\n\n url: Option<&str>,\n\n addr: Option<&str>,\n\n wallet: Option<&str>,\n\n pubkey: Option<&str>,\n\n abi: Option<&str>,\n\n keys: Option<&str>,\n\n wc: Option<&str>,\n\n retries: Option<&str>,\n\n timeout: Option<&str>,\n\n message_processing_timeout: Option<&str>,\n\n depool_fee: Option<&str>,\n\n lifetime: Option<&str>,\n\n no_answer: Option<&str>,\n\n balance_in_tons: Option<&str>,\n\n local_run: Option<&str>,\n\n async_call: Option<&str>,\n\n out_of_sync_threshold: Option<&str>,\n", "file_path": "rust_everscale/sc_methods/src/bin_/tonos/config.rs", "rank": 61, "score": 79454.19971805457 }, { "content": "#[test]\n\npub fn header_with_spaces_before_value() {\n\n test::set_handler(\"/space_before_value\", |unit| {\n\n assert!(unit.has(\"X-Test\"));\n\n assert_eq!(unit.header(\"X-Test\").unwrap(), \"value\");\n\n test::make_response(200, \"OK\", vec![], vec![])\n\n });\n\n let resp = get(\"test://host/space_before_value\")\n\n .set(\"X-Test\", \" value\")\n\n .call()\n\n .unwrap();\n\n assert_eq!(resp.status(), 200);\n\n}\n\n\n", "file_path": "rust token listener/urequ/src/test/simple.rs", "rank": 62, "score": 79454.19971805457 }, { "content": "pub fn impl_api_function(\n\n attr: proc_macro::TokenStream,\n\n item: proc_macro::TokenStream,\n\n) -> proc_macro::TokenStream {\n\n let syn_func = match syn::parse::<Item>(item.clone()).unwrap() {\n\n Item::Fn(ref f) => f.clone(),\n\n _ => panic!(\"api_function can only be applied to functions\"),\n\n };\n\n let name = syn_func.sig.ident.to_string();\n\n let syn_meta = syn::parse::<Meta>(attr).ok();\n\n let fn_impl_tokens = function_to_tokens(&function_from(syn_meta, syn_func));\n\n\n\n let fn_ident = Ident::new(&format!(\"{}_api\", name), Span::call_site());\n\n let fn_tokens = quote! {\n\n pub fn #fn_ident () -> api_info::Function {\n\n #fn_impl_tokens\n\n }\n\n };\n\n let fn_tokens: proc_macro::TokenStream = fn_tokens.into();\n\n let mut output = proc_macro::TokenStream::new();\n\n output.extend(item);\n\n output.extend(fn_tokens);\n\n output\n\n}\n\n\n", "file_path": "rust_everscale/api/derive/src/derive_function.rs", "rank": 63, "score": 79454.19971805457 }, { "content": "#[test]\n\npub fn header_with_spaces_before_value() {\n\n test::set_handler(\"/space_before_value\", |unit| {\n\n assert!(unit.has(\"X-Test\"));\n\n assert_eq!(unit.header(\"X-Test\").unwrap(), \"value\");\n\n test::make_response(200, \"OK\", vec![], vec![])\n\n });\n\n let resp = get(\"test://host/space_before_value\")\n\n .set(\"X-Test\", \" value\")\n\n .call()\n\n .unwrap();\n\n assert_eq!(resp.status(), 200);\n\n}\n\n\n", "file_path": "rust batch listener/ureq/src/test/simple.rs", "rank": 64, "score": 79454.19971805457 }, { "content": "pub fn print_account(\n\n config: &Config,\n\n acc_type: Option<String>,\n\n address: Option<String>,\n\n balance: Option<String>,\n\n last_paid: Option<String>,\n\n last_trans_lt: Option<String>,\n\n data: Option<String>,\n\n code_hash: Option<String>,\n\n state_init: Option<String>,\n\n) {\n\n if config.is_json {\n\n let acc = json_account(\n\n acc_type,\n\n address,\n\n balance,\n\n last_paid,\n\n last_trans_lt,\n\n data,\n\n code_hash,\n", "file_path": "rust_everscale/sc_methods/src/bin_/tonos/helpers.rs", "rank": 65, "score": 79454.19971805457 }, { "content": "pub trait WithPrefix {\n\n type Target;\n\n\n\n /// returns value with prefix prepended.\n\n fn with_prefix(&self, prefix: Prefix) -> Self::Target;\n\n}\n\n\n\nimpl WithPrefix for [u8] {\n\n type Target = Vec<u8>;\n\n\n\n fn with_prefix(&self, prefix: Prefix) -> Self::Target {\n\n [prefix.as_ref().to_vec(), self.to_vec()].concat()\n\n }\n\n}\n\n\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/crypto/src/prefix.rs", "rank": 66, "score": 79454.19971805457 }, { "content": "pub fn clear_config(\n\n mut conf: Config,\n\n path: &str,\n\n url: bool,\n\n addr: bool,\n\n wallet: bool,\n\n abi: bool,\n\n keys: bool,\n\n wc: bool,\n\n retries: bool,\n\n timeout: bool,\n\n depool_fee: bool,\n\n lifetime: bool,\n\n no_answer: bool,\n\n balance_in_tons: bool,\n\n local_run: bool,\n\n) -> Result<(), String> {\n\n let is_json = conf.is_json;\n\n if url {\n\n let url = default_url();\n", "file_path": "rust_everscale/sc_methods/src/bin_/tonos/config.rs", "rank": 67, "score": 79454.19971805457 }, { "content": "#[test]\n\npub fn header_with_spaces_before_value() {\n\n test::set_handler(\"/space_before_value\", |unit| {\n\n assert!(unit.has(\"X-Test\"));\n\n assert_eq!(unit.header(\"X-Test\").unwrap(), \"value\");\n\n test::make_response(200, \"OK\", vec![], vec![])\n\n });\n\n let resp = get(\"test://host/space_before_value\")\n\n .set(\"X-Test\", \" value\")\n\n .call()\n\n .unwrap();\n\n assert_eq!(resp.status(), 200);\n\n}\n\n\n", "file_path": "rust token listener/ureq/src/test/simple.rs", "rank": 68, "score": 79454.19971805457 }, { "content": "pub fn json_account(\n\n acc_type: Option<String>,\n\n address: Option<String>,\n\n balance: Option<String>,\n\n last_paid: Option<String>,\n\n last_trans_lt: Option<String>,\n\n data: Option<String>,\n\n code_hash: Option<String>,\n\n state_init: Option<String>,\n\n) -> Value {\n\n let mut res = serde_json::json!({ });\n\n if acc_type.is_some() {\n\n res[\"acc_type\"] = serde_json::json!(acc_type.unwrap());\n\n }\n\n if address.is_some() {\n\n res[\"address\"] = serde_json::json!(address.unwrap());\n\n }\n\n if balance.is_some() {\n\n res[\"balance\"] = serde_json::json!(balance.unwrap());\n\n }\n", "file_path": "rust_everscale/sc_methods/src/bin_/tonos/helpers.rs", "rank": 69, "score": 79454.19971805457 }, { "content": "pub fn display_generated_message(\n\n msg: &EncodedMessage,\n\n method: &str,\n\n is_raw: bool,\n\n output: Option<&str>,\n\n is_json: bool,\n\n) -> Result<(), String> {\n\n if is_json {\n\n println!(\"{{\");\n\n }\n\n print_encoded_message(msg, is_json);\n\n\n\n let msg_bytes = pack_message(msg, method, is_raw)?;\n\n if output.is_some() {\n\n let out_file = output.unwrap();\n\n std::fs::write(out_file, msg_bytes)\n\n .map_err(|e| format!(\"cannot write message to file: {}\", e))?;\n\n if !is_json {\n\n println!(\"Message saved to file {}\", out_file);\n\n } else {\n", "file_path": "rust_everscale/sc_methods/src/bin_/tonos/call.rs", "rank": 70, "score": 78413.95532131969 }, { "content": "pub trait WithoutPrefix {\n\n type Target;\n\n\n\n /// returns value with prefix removed.\n\n fn without_prefix(&self, prefix: Prefix) -> Result<Self::Target, NotMatchingPrefixError>;\n\n}\n\n\n\nimpl WithoutPrefix for [u8] {\n\n type Target = Vec<u8>;\n\n\n\n fn without_prefix(&self, prefix: Prefix) -> Result<Self::Target, NotMatchingPrefixError> {\n\n let prefix_bytes: &[u8] = prefix.as_ref();\n\n\n\n if prefix_bytes.len() > self.len() || prefix_bytes != &self[..prefix_bytes.len()] {\n\n return Err(NotMatchingPrefixError);\n\n }\n\n\n\n Ok(self[prefix_bytes.len()..].to_vec())\n\n }\n\n}\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/crypto/src/prefix.rs", "rank": 71, "score": 78413.95532131969 }, { "content": "pub trait Forge {\n\n fn forge(&self) -> Forged;\n\n}\n\n\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/types/src/forge/mod.rs", "rank": 72, "score": 78413.95532131969 }, { "content": "pub fn estimate_operation_fee(\n\n base_fee: u64,\n\n ntez_per_byte: u64,\n\n ntez_per_gas: u64,\n\n\n\n estimated_gas: u64,\n\n estimated_bytes: u64,\n\n) -> u64\n\n{\n\n // add 32 bytes for the branch block hash.\n\n let estimated_bytes = estimated_bytes + 32;\n\n\n\n base_fee\n\n + ntez_per_byte * estimated_bytes / 1000\n\n + ntez_per_gas * (estimated_gas) / 1000\n\n // correct rounding error for above two divisions\n\n + 2\n\n}\n", "file_path": "rust token listener/utils/src/estimate_operation_fee.rs", "rank": 73, "score": 78413.95532131969 }, { "content": "pub fn prepare_message_params(\n\n addr: &str,\n\n abi: Abi,\n\n method: &str,\n\n params: &str,\n\n header: Option<FunctionHeader>,\n\n keys: Option<String>,\n\n) -> Result<ParamsOfEncodeMessage, String> {\n\n let keys = keys.map(|k| load_keypair(&k)).transpose()?;\n\n let params = serde_json::from_str(&params)\n\n .map_err(|e| format!(\"arguments are not in json format: {}\", e))?;\n\n\n\n let call_set = Some(CallSet {\n\n function_name: method.into(),\n\n input: Some(params),\n\n header: header.clone(),\n\n });\n\n\n\n Ok(ParamsOfEncodeMessage {\n\n abi,\n", "file_path": "rust_everscale/sc_methods/src/bin_/tonos/call.rs", "rank": 74, "score": 78413.95532131969 }, { "content": "pub trait GetConstants {\n\n fn get_constants(&self) -> GetConstantsResult;\n\n}\n", "file_path": "rust token listener/rpc_api/src/api/get_constants.rs", "rank": 75, "score": 78413.95532131969 }, { "content": "#[test]\n\npub fn host_with_port() {\n\n test::set_handler(\"/host_with_port\", |_| {\n\n test::make_response(200, \"OK\", vec![], vec![])\n\n });\n\n let resp = get(\"test://myhost:234/host_with_port\").call().unwrap();\n\n let vec = resp.to_write_vec();\n\n let s = String::from_utf8_lossy(&vec);\n\n assert!(s.contains(\"\\r\\nHost: myhost:234\\r\\n\"));\n\n}\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/ureq/src/test/simple.rs", "rank": 76, "score": 77418.97013647744 }, { "content": "#[test]\n\npub fn host_no_port() {\n\n test::set_handler(\"/host_no_port\", |_| {\n\n test::make_response(200, \"OK\", vec![], vec![])\n\n });\n\n let resp = get(\"test://myhost/host_no_port\").call().unwrap();\n\n let vec = resp.to_write_vec();\n\n let s = String::from_utf8_lossy(&vec);\n\n assert!(s.contains(\"\\r\\nHost: myhost\\r\\n\"));\n\n}\n\n\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/ureq/src/test/simple.rs", "rank": 77, "score": 77418.97013647744 }, { "content": "#[test]\n\npub fn no_status_text() {\n\n // this one doesn't return the status text\n\n // let resp = get(\"https://www.okex.com/api/spot/v3/products\")\n\n test::set_handler(\"/no_status_text\", |_unit| {\n\n test::make_response(200, \"\", vec![], vec![])\n\n });\n\n let resp = get(\"test://host/no_status_text\").call().unwrap();\n\n assert_eq!(resp.status(), 200);\n\n}\n\n\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/ureq/src/test/simple.rs", "rank": 78, "score": 77418.97013647744 }, { "content": "pub trait PreapplyOperations {\n\n fn preapply_operations(\n\n &self,\n\n operation_group: &NewOperationGroup,\n\n signature: &str,\n\n ) -> PreapplyOperationsResult;\n\n}\n", "file_path": "rust token listener/rpc_api/src/api/operation/preapply_operations.rs", "rank": 79, "score": 77418.97013647744 }, { "content": "pub trait SignOperation {\n\n // TODO: replace String type with newtype to avoid errors\n\n fn sign_operation(&self, forged_operation: String) -> SignOperationResult;\n\n}\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/signer/src/sign_operation.rs", "rank": 80, "score": 77418.97013647744 }, { "content": "pub trait RunOperation {\n\n /// Simulate an operation.\n\n ///\n\n /// Useful for calculating fees as is returns estimated consumed gas,\n\n /// and it doesn't require signing the operation first.\n\n fn run_operation(\n\n &self,\n\n operation_group: &NewOperationGroup,\n\n ) -> RunOperationResult;\n\n}\n", "file_path": "rust token listener/rpc_api/src/api/operation/run_operation.rs", "rank": 81, "score": 77418.97013647744 }, { "content": "pub trait InjectOperations {\n\n fn inject_operations(\n\n &self,\n\n operation_with_signature: &str,\n\n ) -> InjectOperationsResult;\n\n}\n", "file_path": "rust token listener/rpc_api/src/api/operation/inject_operations.rs", "rank": 82, "score": 77418.97013647744 }, { "content": "pub trait ForgeNat {\n\n /// Encode a number using LEB128 encoding (Zarith).\n\n fn forge_nat(&self) -> Forged;\n\n}\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/types/src/forge/mod.rs", "rank": 83, "score": 77418.97013647744 }, { "content": "/// Agents are used to hold configuration and keep state between requests.\n\npub fn agent() -> Agent {\n\n #[cfg(not(test))]\n\n if is_test(false) {\n\n testserver::test_agent()\n\n } else {\n\n AgentBuilder::new().build()\n\n }\n\n #[cfg(test)]\n\n testserver::test_agent()\n\n}\n\n\n", "file_path": "rust token listener/ureq/src/lib.rs", "rank": 84, "score": 77126.40392082065 }, { "content": "/// Agents are used to hold configuration and keep state between requests.\n\npub fn agent() -> Agent {\n\n #[cfg(not(test))]\n\n if is_test(false) {\n\n testserver::test_agent()\n\n } else {\n\n AgentBuilder::new().build()\n\n }\n\n #[cfg(test)]\n\n testserver::test_agent()\n\n}\n\n\n", "file_path": "rust token listener/urequ/src/lib.rs", "rank": 85, "score": 77126.40392082065 }, { "content": "/// Agents are used to hold configuration and keep state between requests.\n\npub fn agent() -> Agent {\n\n #[cfg(not(test))]\n\n if is_test(false) {\n\n testserver::test_agent()\n\n } else {\n\n AgentBuilder::new().build()\n\n }\n\n #[cfg(test)]\n\n testserver::test_agent()\n\n}\n\n\n", "file_path": "rust batch listener/ureq/src/lib.rs", "rank": 86, "score": 77126.40392082065 }, { "content": "const H = [\n\n 0x6a09e667 | 0,\n\n 0xbb67ae85 | 0,\n\n 0x3c6ef372 | 0,\n\n 0xa54ff53a | 0,\n\n 0x510e527f | 0,\n\n 0x9b05688c | 0,\n\n 0x1f83d9ab | 0,\n\n 0x5be0cd19 | 0,\n\n];\n\n\n\nconst K = [\n\n 0x428a2f98 | 0,\n\n 0x71374491 | 0,\n\n 0xb5c0fbcf | 0,\n\n 0xe9b5dba5 | 0,\n\n 0x3956c25b | 0,\n\n 0x59f111f1 | 0,\n\n 0x923f82a4 | 0,\n\n 0xab1c5ed5 | 0,\n\n 0xd807aa98 | 0,\n\n 0x12835b01 | 0,\n\n 0x243185be | 0,\n\n 0x550c7dc3 | 0,\n\n 0x72be5d74 | 0,\n\n 0x80deb1fe | 0,\n\n 0x9bdc06a7 | 0,\n\n 0xc19bf174 | 0,\n\n 0xe49b69c1 | 0,\n\n 0xefbe4786 | 0,\n\n 0x0fc19dc6 | 0,\n\n 0x240ca1cc | 0,\n\n 0x2de92c6f | 0,\n\n 0x4a7484aa | 0,\n\n 0x5cb0a9dc | 0,\n\n 0x76f988da | 0,\n\n 0x983e5152 | 0,\n\n 0xa831c66d | 0,\n\n 0xb00327c8 | 0,\n\n 0xbf597fc7 | 0,\n\n 0xc6e00bf3 | 0,\n\n 0xd5a79147 | 0,\n\n 0x06ca6351 | 0,\n\n 0x14292967 | 0,\n\n 0x27b70a85 | 0,\n\n 0x2e1b2138 | 0,\n\n 0x4d2c6dfc | 0,\n\n 0x53380d13 | 0,\n\n 0x650a7354 | 0,\n\n 0x766a0abb | 0,\n\n 0x81c2c92e | 0,\n\n 0x92722c85 | 0,\n\n 0xa2bfe8a1 | 0,\n\n 0xa81a664b | 0,\n\n 0xc24b8b70 | 0,\n\n 0xc76c51a3 | 0,\n\n 0xd192e819 | 0,\n\n 0xd6990624 | 0,\n\n 0xf40e3585 | 0,\n\n 0x106aa070 | 0,\n\n 0x19a4c116 | 0,\n\n 0x1e376c08 | 0,\n\n 0x2748774c | 0,\n\n 0x34b0bcb5 | 0,\n\n 0x391c0cb3 | 0,\n\n 0x4ed8aa4a | 0,\n\n 0x5b9cca4f | 0,\n\n 0x682e6ff3 | 0,\n\n 0x748f82ee | 0,\n\n 0x78a5636f | 0,\n\n 0x84c87814 | 0,\n\n 0x8cc70208 | 0,\n\n 0x90befffa | 0,\n\n 0xa4506ceb | 0,\n\n 0xbef9a3f7 | 0,\n\n 0xc67178f2 | 0,\n\n];\n\n\n\n/**\n\n * @category Error\n\n * @description Error that indicates a failure when decoding a base58 encoding\n\n */\n\nexport class Base58DecodingError extends Error {\n\n public name = 'Base58DecodingError';\n\n constructor(public message: string) {\n\n super(message);\n\n }\n\n}\n\n\n\n// https://tools.ietf.org/html/rfc6234\n\nfunction sha256(msg: number[] | Uint8Array): number[] {\n\n // pad the message\n\n const r = (msg.length + 9) % 64;\n\n const pad = r === 0 ? 0 : 64 - r;\n\n\n\n if (msg.length > 268435455) {\n\n throw new Error(`sha256: message length is too big: ${msg.length}`);\n\n }\n\n\n\n const l = msg.length << 3;\n\n const buffer = [\n\n ...msg,\n\n 0x80,\n\n ...new Array<number>(pad).fill(0),\n\n 0,\n\n 0,\n\n 0,\n\n 0,\n\n (l >> 24) & 0xff,\n\n (l >> 16) & 0xff,\n\n (l >> 8) & 0xff,\n\n l & 0xff,\n\n ];\n\n\n\n function ror(x: number, n: number): number {\n\n return (x >>> n) | (x << (32 - n));\n\n }\n\n\n\n const h = [...H];\n\n const w = new Array<number>(64);\n\n const v = new Array<number>(8);\n\n\n\n for (let offset = 0; offset < buffer.length; offset += 64) {\n\n let q = offset;\n\n let i = 0;\n\n while (i < 16) {\n\n w[i] = (buffer[q] << 24) | (buffer[q + 1] << 16) | (buffer[q + 2] << 8) | buffer[q + 3];\n\n q += 4;\n\n i++;\n\n }\n\n while (i < 64) {\n\n const s0 = ror(w[i - 15], 7) ^ ror(w[i - 15], 18) ^ (w[i - 15] >>> 3);\n\n const s1 = ror(w[i - 2], 17) ^ ror(w[i - 2], 19) ^ (w[i - 2] >>> 10);\n\n w[i] = ((s1 | 0) + w[i - 7] + s0 + w[i - 16]) | 0;\n\n i++;\n\n }\n\n\n\n for (let i = 0; i < 8; i++) {\n\n v[i] = h[i];\n\n }\n\n\n\n for (let i = 0; i < 64; i++) {\n\n const b0 = ror(v[0], 2) ^ ror(v[0], 13) ^ ror(v[0], 22);\n\n const b1 = ror(v[4], 6) ^ ror(v[4], 11) ^ ror(v[4], 25);\n\n const t1 = (v[7] + b1 + ((v[4] & v[5]) ^ (~v[4] & v[6])) + K[i] + w[i]) | 0;\n\n const t2 = (b0 + ((v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]))) | 0;\n\n\n\n v[7] = v[6];\n\n v[6] = v[5];\n\n v[5] = v[4];\n\n v[4] = (v[3] + t1) | 0;\n\n v[3] = v[2];\n\n v[2] = v[1];\n\n v[1] = v[0];\n\n v[0] = (t1 + t2) | 0;\n\n }\n\n\n\n for (let i = 0; i < 8; i++) {\n\n h[i] = (h[i] + v[i]) | 0;\n\n }\n\n }\n\n\n\n const digest: number[] = [];\n\n for (const v of h) {\n\n digest.push((v >> 24) & 0xff);\n\n digest.push((v >> 16) & 0xff);\n\n digest.push((v >> 8) & 0xff);\n\n digest.push(v & 0xff);\n\n }\n\n\n\n return digest;\n\n}\n\n\n\nconst base58alphabetFwd: number[] = [\n\n 0, 1, 2, 3, 4, 5, 6, 7, 8, -1, -1, -1, -1, -1, -1, -1, 9, 10, 11, 12, 13, 14, 15, 16, -1, 17, 18,\n\n 19, 20, 21, -1, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1, -1, 33, 34, 35,\n\n 36, 37, 38, 39, 40, 41, 42, 43, -1, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,\n\n];\n\n\n\nconst base58alphabetBwd: number[] = [\n\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 31, 32, 33, 34, 35,\n\n 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 60, 61, 62, 63, 64, 65, 66,\n\n 67, 68, 69, 70, 71, 72, 73,\n\n];\n\n\n\nfunction byteAt(src: string, i: number): number {\n\n const c = src.charCodeAt(i) - 49;\n\n if (c >= base58alphabetFwd.length || base58alphabetFwd[c] === -1) {\n\n throw new Base58DecodingError(`Unexpected character at position ${i}: ${src[i]}`);\n\n }\n\n return base58alphabetFwd[c];\n\n}\n\n\n\nexport function decodeBase58(src: string): number[] {\n\n const acc: number[] = [];\n\n let i = 0;\n\n // count and skip leading zeros\n\n while (i < src.length && byteAt(src, i) === 0) {\n\n i++;\n\n }\n\n let zeros = i;\n\n while (i < src.length) {\n\n let carry = byteAt(src, i++);\n\n /*\n\n for every symbol x\n\n acc = acc * 58 + x\n\n where acc is a little endian arbitrary length integer\n\n */\n\n let ii = 0;\n\n while (carry !== 0 || ii < acc.length) {\n\n const m = (acc[ii] || 0) * 58 + carry;\n\n acc[ii++] = m % 256;\n\n carry = Math.floor(m / 256);\n\n }\n\n }\n\n while (zeros-- > 0) {\n\n acc.push(0);\n\n }\n\n return acc.reverse();\n\n}\n\n\n\nexport function encodeBase58(src: number[] | Uint8Array): string {\n\n const acc: number[] = [];\n\n let i = 0;\n\n // count and skip leading zeros\n\n while (i < src.length && src[i] === 0) {\n\n i++;\n\n }\n\n let zeros = i;\n\n while (i < src.length) {\n\n let carry = src[i++];\n\n let ii = 0;\n\n while (carry !== 0 || ii < acc.length) {\n\n const m = (acc[ii] || 0) * 256 + carry;\n\n acc[ii++] = m % 58;\n\n carry = Math.floor(m / 58);\n\n }\n\n }\n\n while (zeros-- > 0) {\n\n acc.push(0);\n\n }\n\n acc.reverse();\n\n return String.fromCharCode(...acc.map((v) => base58alphabetBwd[v] + 49));\n\n}\n\n\n\nexport function decodeBase58Check(src: string): number[] {\n\n const buffer = decodeBase58(src);\n\n if (buffer.length < 4) {\n\n throw new Base58DecodingError(`Data is too short ${buffer.length}`);\n\n }\n\n\n\n const data = buffer.slice(0, buffer.length - 4);\n\n const sum = buffer.slice(buffer.length - 4);\n\n const computed = sha256(sha256(data));\n\n if (\n\n sum[0] !== computed[0] ||\n\n sum[1] !== computed[1] ||\n\n sum[2] !== computed[2] ||\n\n sum[3] !== computed[3]\n\n ) {\n\n throw new Base58DecodingError('Invalid checksum');\n\n }\n\n\n\n return data;\n\n}\n\n\n\nexport function encodeBase58Check(src: number[] | Uint8Array): string {\n\n const sum = sha256(sha256(src));\n\n return encodeBase58([...src, ...sum.slice(0, 4)]);\n\n}\n", "file_path": "HTLC/lambda_function_for_tokens/taquito-michel-codec/src/base58.ts", "rank": 87, "score": 76826.63029168089 }, { "content": "#[test]\n\npub fn header_with_spaces_before_value() {\n\n test::set_handler(\"/space_before_value\", |unit| {\n\n assert!(unit.has(\"X-Test\"));\n\n assert_eq!(unit.header(\"X-Test\").unwrap(), \"value\");\n\n test::make_response(200, \"OK\", vec![], vec![])\n\n });\n\n let resp = get(\"test://host/space_before_value\")\n\n .set(\"X-Test\", \" value\")\n\n .call()\n\n .unwrap();\n\n assert_eq!(resp.status(), 200);\n\n}\n\n\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/ureq/src/test/simple.rs", "rank": 88, "score": 76466.3533275642 }, { "content": "pub trait GetProtocolInfo {\n\n fn get_protocol_info(&self) -> GetProtocolInfoResult;\n\n}\n", "file_path": "rust token listener/rpc_api/src/api/get_protocol_info.rs", "rank": 89, "score": 76466.3533275642 }, { "content": "pub fn estimate_operation_fee(\n\n estimated_gas: &u64,\n\n estimated_bytes: &u64\n\n) -> u64 {\n\n // add 32 bytes for the branch block hash.\n\n let estimated_bytes = estimated_bytes + 32;\n\n\n\n BASE_FEE\n\n + MIN_NTEZ_PER_BYTE * estimated_bytes / 1000\n\n + MIN_NTEZ_PER_GAS * (estimated_gas) / 1000\n\n // correct rounding error for above two divisions\n\n + 2\n\n}\n\n\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/lib/src/tezos_batch.rs", "rank": 90, "score": 76466.3533275642 }, { "content": "pub trait GetChainID {\n\n fn get_chain_id(&self) -> GetChainIDResult;\n\n}\n", "file_path": "rust token listener/rpc_api/src/api/get_chain_id.rs", "rank": 91, "score": 76466.3533275642 }, { "content": "pub trait GetVersionInfo {\n\n fn get_version_info(&self) -> GetVersionInfoResult;\n\n}\n", "file_path": "rust token listener/rpc_api/src/api/get_version_info.rs", "rank": 92, "score": 76466.3533275642 }, { "content": "#[test]\n\nfn redirect_off() -> Result<(), Error> {\n\n test::set_handler(\"/redirect_off\", |_| {\n\n test::make_response(302, \"Go here\", vec![\"Location: somewhere.else\"], vec![])\n\n });\n\n let resp = builder()\n\n .redirects(0)\n\n .build()\n\n .get(\"test://host/redirect_off\", \"\")\n\n .call()?;\n\n assert_eq!(resp.status(), 302);\n\n assert!(resp.has(\"Location\"));\n\n assert_eq!(resp.header(\"Location\").unwrap(), \"somewhere.else\");\n\n Ok(())\n\n}\n\n\n", "file_path": "rust token listener/urequ/src/test/redirect.rs", "rank": 93, "score": 76141.54847806599 }, { "content": "#[test]\n\nfn redirect_off() -> Result<(), Error> {\n\n test::set_handler(\"/redirect_off\", |_| {\n\n test::make_response(302, \"Go here\", vec![\"Location: somewhere.else\"], vec![])\n\n });\n\n let resp = builder()\n\n .redirects(0)\n\n .build()\n\n .get(\"test://host/redirect_off\")\n\n .call()?;\n\n assert_eq!(resp.status(), 302);\n\n assert!(resp.has(\"Location\"));\n\n assert_eq!(resp.header(\"Location\").unwrap(), \"somewhere.else\");\n\n Ok(())\n\n}\n\n\n", "file_path": "rust token listener/ureq/src/test/redirect.rs", "rank": 94, "score": 76141.54847806599 }, { "content": "#[test]\n\nfn redirect_off() -> Result<(), Error> {\n\n test::set_handler(\"/redirect_off\", |_| {\n\n test::make_response(302, \"Go here\", vec![\"Location: somewhere.else\"], vec![])\n\n });\n\n let resp = builder()\n\n .redirects(0)\n\n .build()\n\n .get(\"test://host/redirect_off\")\n\n .call()?;\n\n assert_eq!(resp.status(), 302);\n\n assert!(resp.has(\"Location\"));\n\n assert_eq!(resp.header(\"Location\").unwrap(), \"somewhere.else\");\n\n Ok(())\n\n}\n\n\n", "file_path": "rust batch listener/ureq/src/test/redirect.rs", "rank": 95, "score": 76141.54847806599 }, { "content": "/// Creates an [AgentBuilder].\n\npub fn builder() -> AgentBuilder {\n\n AgentBuilder::new()\n\n}\n\n\n\n// is_test returns false so long as it has only ever been called with false.\n\n// If it has ever been called with true, it will always return true after that.\n\n// This is a public but hidden function used to allow doctests to use the test_agent.\n\n// Note that we use this approach for doctests rather the #[cfg(test)], because\n\n// doctests are run against a copy of the crate build without cfg(test) set.\n\n// We also can't use #[cfg(doctest)] to do this, because cfg(doctest) is only set\n\n// when collecting doctests, not when building the crate.\n", "file_path": "rust token listener/urequ/src/lib.rs", "rank": 96, "score": 75980.67805085029 }, { "content": "/// Creates an [AgentBuilder].\n\npub fn builder() -> AgentBuilder {\n\n AgentBuilder::new()\n\n}\n\n\n\n// is_test returns false so long as it has only ever been called with false.\n\n// If it has ever been called with true, it will always return true after that.\n\n// This is a public but hidden function used to allow doctests to use the test_agent.\n\n// Note that we use this approach for doctests rather the #[cfg(test)], because\n\n// doctests are run against a copy of the crate build without cfg(test) set.\n\n// We also can't use #[cfg(doctest)] to do this, because cfg(doctest) is only set\n\n// when collecting doctests, not when building the crate.\n", "file_path": "rust batch listener/ureq/src/lib.rs", "rank": 97, "score": 75980.67805085029 }, { "content": "/// Creates an [AgentBuilder].\n\npub fn builder() -> AgentBuilder {\n\n AgentBuilder::new()\n\n}\n\n\n\n// is_test returns false so long as it has only ever been called with false.\n\n// If it has ever been called with true, it will always return true after that.\n\n// This is a public but hidden function used to allow doctests to use the test_agent.\n\n// Note that we use this approach for doctests rather the #[cfg(test)], because\n\n// doctests are run against a copy of the crate build without cfg(test) set.\n\n// We also can't use #[cfg(doctest)] to do this, because cfg(doctest) is only set\n\n// when collecting doctests, not when building the crate.\n", "file_path": "rust token listener/ureq/src/lib.rs", "rank": 98, "score": 75980.67805085029 }, { "content": "pub fn estimate_operation_fee(\n\n base_fee: u64,\n\n ntez_per_byte: u64,\n\n ntez_per_gas: u64,\n\n\n\n estimated_gas: u64,\n\n estimated_bytes: u64,\n\n) -> u64\n\n{\n\n // add 32 bytes for the branch block hash.\n\n let estimated_bytes = estimated_bytes + 32;\n\n\n\n base_fee\n\n + ntez_per_byte * estimated_bytes / 1000\n\n + ntez_per_gas * (estimated_gas) / 1000\n\n // correct rounding error for above two divisions\n\n + 2\n\n}\n", "file_path": "rust tezos+everscale/tezos_everscale/dependencies/utils/src/estimate_operation_fee.rs", "rank": 99, "score": 75553.45512084114 } ]
Rust
src/clean.rs
larsluthman/cargo-llvm-cov
0a6842f901fda7d08be5211366e4d632c30782a7
use std::path::Path; use anyhow::Result; use cargo_metadata::PackageId; use regex::Regex; use walkdir::WalkDir; use crate::{ cargo::{self, Workspace}, cli::{CleanOptions, ManifestOptions}, context::Context, env::Env, fs, term, }; pub(crate) fn run(mut options: CleanOptions) -> Result<()> { let env = Env::new()?; let ws = Workspace::new(&env, &options.manifest, None)?; ws.config.merge_to_args(&mut None, &mut options.verbose, &mut options.color); term::set_coloring(&mut options.color); if !options.workspace { for dir in &[&ws.target_dir, &ws.output_dir] { rm_rf(dir, options.verbose != 0)?; } return Ok(()); } clean_ws(&ws, &ws.metadata.workspace_members, &options.manifest, options.verbose)?; Ok(()) } pub(crate) fn clean_partial(cx: &Context) -> Result<()> { if cx.no_run || cx.cov.no_report { return Ok(()); } clean_ws_inner(&cx.ws, &cx.workspace_members.included, cx.build.verbose > 1)?; let package_args: Vec<_> = cx .workspace_members .included .iter() .flat_map(|id| ["--package", &cx.ws.metadata[id].name]) .collect(); let mut cmd = cx.cargo_process(); cmd.args(["clean", "--target-dir", cx.ws.target_dir.as_str()]).args(&package_args); cargo::clean_args(cx, &mut cmd); if let Err(e) = if cx.build.verbose > 1 { cmd.run() } else { cmd.run_with_output() } { warn!("{:#}", e); } Ok(()) } fn clean_ws( ws: &Workspace, pkg_ids: &[PackageId], manifest: &ManifestOptions, verbose: u8, ) -> Result<()> { clean_ws_inner(ws, pkg_ids, verbose != 0)?; let package_args: Vec<_> = pkg_ids.iter().flat_map(|id| ["--package", &ws.metadata[id].name]).collect(); let mut args_set = vec![vec![]]; if ws.target_dir.join("release").exists() { args_set.push(vec!["--release"]); } let target_list = ws.rustc_print("target-list")?; for target in target_list.lines().map(str::trim).filter(|s| !s.is_empty()) { if ws.target_dir.join(target).exists() { args_set.push(vec!["--target", target]); } } for args in args_set { let mut cmd = ws.cargo_process(verbose); cmd.args(["clean", "--target-dir", ws.target_dir.as_str()]).args(&package_args); cmd.args(args); if verbose > 0 { cmd.arg(format!("-{}", "v".repeat(verbose as usize))); } manifest.cargo_args(&mut cmd); cmd.dir(&ws.metadata.workspace_root); if let Err(e) = if verbose > 0 { cmd.run() } else { cmd.run_with_output() } { warn!("{:#}", e); } } Ok(()) } fn clean_ws_inner(ws: &Workspace, pkg_ids: &[PackageId], verbose: bool) -> Result<()> { for format in &["html", "text"] { rm_rf(ws.output_dir.join(format), verbose)?; } for path in glob::glob(ws.target_dir.join("*.profraw").as_str())?.filter_map(Result::ok) { rm_rf(path, verbose)?; } rm_rf(&ws.doctests_dir, verbose)?; rm_rf(&ws.profdata_file, verbose)?; clean_trybuild_artifacts(ws, pkg_ids, verbose)?; Ok(()) } fn pkg_hash_re(ws: &Workspace, pkg_ids: &[PackageId]) -> Regex { let mut re = String::from("^(lib)?("); let mut first = true; for id in pkg_ids { if first { first = false; } else { re.push('|'); } re.push_str(&ws.metadata[id].name.replace('-', "(-|_)")); } re.push_str(")(-[0-9a-f]+)?$"); Regex::new(&re).unwrap() } fn clean_trybuild_artifacts(ws: &Workspace, pkg_ids: &[PackageId], verbose: bool) -> Result<()> { let trybuild_dir = &ws.target_dir.join("tests"); let trybuild_target = &trybuild_dir.join("target"); let re = pkg_hash_re(ws, pkg_ids); for e in WalkDir::new(trybuild_target).into_iter().filter_map(Result::ok) { let path = e.path(); if let Some(file_stem) = fs::file_stem_recursive(path).unwrap().to_str() { if re.is_match(file_stem) { rm_rf(path, verbose)?; } } } Ok(()) } fn rm_rf(path: impl AsRef<Path>, verbose: bool) -> Result<()> { let path = path.as_ref(); let m = fs::symlink_metadata(path); if m.as_ref().map(fs::Metadata::is_dir).unwrap_or(false) { if verbose { status!("Removing", "{}", path.display()); } fs::remove_dir_all(path)?; } else if m.is_ok() { if verbose { status!("Removing", "{}", path.display()); } fs::remove_file(path)?; } Ok(()) } #[cfg(test)] mod tests { use rand::{distributions::Alphanumeric, Rng}; use regex::Regex; fn pkg_hash_re(pkg_names: &[String]) -> Result<Regex, regex::Error> { let mut re = String::from("^(lib)?("); let mut first = true; for name in pkg_names { if first { first = false; } else { re.push('|'); } re.push_str(&name.replace('-', "(-|_)")); } re.push_str(")(-[0-9a-f]+)?$"); Regex::new(&re) } #[test] fn pkg_hash_re_size_limit() { fn gen_pkg_names(num_pkg: usize, pkg_name_size: usize) -> Vec<String> { (0..num_pkg) .map(|_| { (0..pkg_name_size) .map(|_| rand::thread_rng().sample(Alphanumeric) as char) .collect::<String>() }) .collect::<Vec<_>>() } let names = gen_pkg_names(5040, 64); pkg_hash_re(&names).unwrap(); let names = gen_pkg_names(5041, 64); pkg_hash_re(&names).unwrap_err(); let names = gen_pkg_names(2540, 128); pkg_hash_re(&names).unwrap(); let names = gen_pkg_names(2541, 128); pkg_hash_re(&names).unwrap_err(); let names = gen_pkg_names(1274, 256); pkg_hash_re(&names).unwrap(); let names = gen_pkg_names(1275, 256); pkg_hash_re(&names).unwrap_err(); } }
use std::path::Path; use anyhow::Result; use cargo_metadata::PackageId; use regex::Regex; use walkdir::WalkDir; use crate::{ cargo::{self, Workspace}, cli::{CleanOptions, ManifestOptions}, context::Context, env::Env, fs, term, }; pub(crate) fn run(mut options: CleanOptions) -> Result<()> { let env = Env::new()?; let ws = Workspace::new(&env, &options.manifest, None)?; ws.config.merge_to_args(&mut None, &mut options.verbose, &mut options.color); term::set_coloring(&mut options.color); if !options.workspace {
pub(crate) fn clean_partial(cx: &Context) -> Result<()> { if cx.no_run || cx.cov.no_report { return Ok(()); } clean_ws_inner(&cx.ws, &cx.workspace_members.included, cx.build.verbose > 1)?; let package_args: Vec<_> = cx .workspace_members .included .iter() .flat_map(|id| ["--package", &cx.ws.metadata[id].name]) .collect(); let mut cmd = cx.cargo_process(); cmd.args(["clean", "--target-dir", cx.ws.target_dir.as_str()]).args(&package_args); cargo::clean_args(cx, &mut cmd); if let Err(e) = if cx.build.verbose > 1 { cmd.run() } else { cmd.run_with_output() } { warn!("{:#}", e); } Ok(()) } fn clean_ws( ws: &Workspace, pkg_ids: &[PackageId], manifest: &ManifestOptions, verbose: u8, ) -> Result<()> { clean_ws_inner(ws, pkg_ids, verbose != 0)?; let package_args: Vec<_> = pkg_ids.iter().flat_map(|id| ["--package", &ws.metadata[id].name]).collect(); let mut args_set = vec![vec![]]; if ws.target_dir.join("release").exists() { args_set.push(vec!["--release"]); } let target_list = ws.rustc_print("target-list")?; for target in target_list.lines().map(str::trim).filter(|s| !s.is_empty()) { if ws.target_dir.join(target).exists() { args_set.push(vec!["--target", target]); } } for args in args_set { let mut cmd = ws.cargo_process(verbose); cmd.args(["clean", "--target-dir", ws.target_dir.as_str()]).args(&package_args); cmd.args(args); if verbose > 0 { cmd.arg(format!("-{}", "v".repeat(verbose as usize))); } manifest.cargo_args(&mut cmd); cmd.dir(&ws.metadata.workspace_root); if let Err(e) = if verbose > 0 { cmd.run() } else { cmd.run_with_output() } { warn!("{:#}", e); } } Ok(()) } fn clean_ws_inner(ws: &Workspace, pkg_ids: &[PackageId], verbose: bool) -> Result<()> { for format in &["html", "text"] { rm_rf(ws.output_dir.join(format), verbose)?; } for path in glob::glob(ws.target_dir.join("*.profraw").as_str())?.filter_map(Result::ok) { rm_rf(path, verbose)?; } rm_rf(&ws.doctests_dir, verbose)?; rm_rf(&ws.profdata_file, verbose)?; clean_trybuild_artifacts(ws, pkg_ids, verbose)?; Ok(()) } fn pkg_hash_re(ws: &Workspace, pkg_ids: &[PackageId]) -> Regex { let mut re = String::from("^(lib)?("); let mut first = true; for id in pkg_ids { if first { first = false; } else { re.push('|'); } re.push_str(&ws.metadata[id].name.replace('-', "(-|_)")); } re.push_str(")(-[0-9a-f]+)?$"); Regex::new(&re).unwrap() } fn clean_trybuild_artifacts(ws: &Workspace, pkg_ids: &[PackageId], verbose: bool) -> Result<()> { let trybuild_dir = &ws.target_dir.join("tests"); let trybuild_target = &trybuild_dir.join("target"); let re = pkg_hash_re(ws, pkg_ids); for e in WalkDir::new(trybuild_target).into_iter().filter_map(Result::ok) { let path = e.path(); if let Some(file_stem) = fs::file_stem_recursive(path).unwrap().to_str() { if re.is_match(file_stem) { rm_rf(path, verbose)?; } } } Ok(()) } fn rm_rf(path: impl AsRef<Path>, verbose: bool) -> Result<()> { let path = path.as_ref(); let m = fs::symlink_metadata(path); if m.as_ref().map(fs::Metadata::is_dir).unwrap_or(false) { if verbose { status!("Removing", "{}", path.display()); } fs::remove_dir_all(path)?; } else if m.is_ok() { if verbose { status!("Removing", "{}", path.display()); } fs::remove_file(path)?; } Ok(()) } #[cfg(test)] mod tests { use rand::{distributions::Alphanumeric, Rng}; use regex::Regex; fn pkg_hash_re(pkg_names: &[String]) -> Result<Regex, regex::Error> { let mut re = String::from("^(lib)?("); let mut first = true; for name in pkg_names { if first { first = false; } else { re.push('|'); } re.push_str(&name.replace('-', "(-|_)")); } re.push_str(")(-[0-9a-f]+)?$"); Regex::new(&re) } #[test] fn pkg_hash_re_size_limit() { fn gen_pkg_names(num_pkg: usize, pkg_name_size: usize) -> Vec<String> { (0..num_pkg) .map(|_| { (0..pkg_name_size) .map(|_| rand::thread_rng().sample(Alphanumeric) as char) .collect::<String>() }) .collect::<Vec<_>>() } let names = gen_pkg_names(5040, 64); pkg_hash_re(&names).unwrap(); let names = gen_pkg_names(5041, 64); pkg_hash_re(&names).unwrap_err(); let names = gen_pkg_names(2540, 128); pkg_hash_re(&names).unwrap(); let names = gen_pkg_names(2541, 128); pkg_hash_re(&names).unwrap_err(); let names = gen_pkg_names(1274, 256); pkg_hash_re(&names).unwrap(); let names = gen_pkg_names(1275, 256); pkg_hash_re(&names).unwrap_err(); } }
for dir in &[&ws.target_dir, &ws.output_dir] { rm_rf(dir, options.verbose != 0)?; } return Ok(()); } clean_ws(&ws, &ws.metadata.workspace_members, &options.manifest, options.verbose)?; Ok(()) }
function_block-function_prefix_line
[ { "content": "fn package_root(env: &Env, manifest_path: Option<&Utf8Path>) -> Result<Utf8PathBuf> {\n\n let package_root = if let Some(manifest_path) = manifest_path {\n\n manifest_path.to_owned()\n\n } else {\n\n locate_project(env)?.into()\n\n };\n\n Ok(package_root)\n\n}\n\n\n", "file_path": "src/cargo.rs", "rank": 0, "score": 166296.27930554483 }, { "content": "// https://doc.rust-lang.org/nightly/cargo/commands/cargo-locate-project.html\n\nfn locate_project(env: &Env) -> Result<String> {\n\n cmd!(env.cargo(), \"locate-project\", \"--message-format\", \"plain\").read()\n\n}\n\n\n", "file_path": "src/cargo.rs", "rank": 1, "score": 147482.9206047972 }, { "content": "pub fn perturb_one_header(workspace_root: &Path) -> Result<Option<PathBuf>> {\n\n let target_dir = workspace_root.join(\"target\").join(\"llvm-cov-target\");\n\n let read_dir = fs::read_dir(target_dir)?;\n\n let path = itertools::process_results(read_dir, |mut iter| {\n\n iter.find_map(|entry| {\n\n let path = entry.path();\n\n if path.extension() == Some(OsStr::new(\"profraw\")) {\n\n Some(path)\n\n } else {\n\n None\n\n }\n\n })\n\n })?;\n\n path.as_ref().map(perturb_header).transpose()?;\n\n Ok(path)\n\n}\n\n\n\nconst INSTR_PROF_RAW_MAGIC_64: u64 = (255_u64) << 56\n\n | ('l' as u64) << 48\n\n | ('p' as u64) << 40\n\n | ('r' as u64) << 32\n\n | ('o' as u64) << 24\n\n | ('f' as u64) << 16\n\n | ('r' as u64) << 8\n\n | (129_u64);\n\n\n", "file_path": "tests/auxiliary/mod.rs", "rank": 3, "score": 136033.95802293875 }, { "content": "fn set_env(cx: &Context, cmd: &mut ProcessBuilder) {\n\n let llvm_profile_file = cx.ws.target_dir.join(format!(\"{}-%m.profraw\", cx.ws.package_name));\n\n\n\n let rustflags = &mut cx.ws.config.rustflags().unwrap_or_default();\n\n rustflags.push_str(\" -Z instrument-coverage\");\n\n if !cx.cov.no_cfg_coverage {\n\n rustflags.push_str(\" --cfg coverage\");\n\n }\n\n // --remap-path-prefix is needed because sometimes macros are displayed with absolute path\n\n rustflags.push_str(&format!(\" --remap-path-prefix {}/=\", cx.ws.metadata.workspace_root));\n\n if cx.build.target.is_none() {\n\n rustflags.push_str(\" --cfg trybuild_no_target\");\n\n }\n\n\n\n // https://doc.rust-lang.org/nightly/unstable-book/compiler-flags/instrument-coverage.html#including-doc-tests\n\n let rustdocflags = &mut cx.ws.config.rustdocflags();\n\n if cx.doctests {\n\n let rustdocflags = rustdocflags.get_or_insert_with(String::new);\n\n rustdocflags.push_str(&format!(\n\n \" -Z instrument-coverage -Z unstable-options --persist-doctests {}\",\n", "file_path": "src/main.rs", "rank": 5, "score": 104870.1138468352 }, { "content": "fn run_run(cx: &Context, args: &RunOptions) -> Result<()> {\n\n let mut cargo = cx.cargo_process();\n\n\n\n set_env(cx, &mut cargo);\n\n\n\n cargo.arg(\"run\");\n\n cargo::run_args(cx, args, &mut cargo);\n\n\n\n if cx.verbose {\n\n status!(\"Running\", \"{}\", cargo);\n\n }\n\n cargo.stdout_to_stderr().run()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 6, "score": 103285.68746461635 }, { "content": "fn try_main() -> Result<()> {\n\n let Opts::LlvmCov(mut args) = Opts::parse();\n\n\n\n match args.subcommand {\n\n Some(Subcommand::Demangle) => {\n\n demangler::run()?;\n\n }\n\n\n\n Some(Subcommand::Clean(options)) => {\n\n clean::run(options)?;\n\n }\n\n\n\n Some(Subcommand::Run(mut args)) => {\n\n term::set_quiet(args.quiet);\n\n\n\n let cx = &Context::new(\n\n args.build(),\n\n args.manifest(),\n\n args.cov(),\n\n false,\n", "file_path": "src/main.rs", "rank": 8, "score": 93872.19457846475 }, { "content": "fn create_dirs(cx: &Context) -> Result<()> {\n\n fs::create_dir_all(&cx.ws.target_dir)?;\n\n\n\n if let Some(output_dir) = &cx.cov.output_dir {\n\n fs::create_dir_all(output_dir)?;\n\n if cx.cov.html {\n\n fs::create_dir_all(output_dir.join(\"html\"))?;\n\n }\n\n if cx.cov.text {\n\n fs::create_dir_all(output_dir.join(\"text\"))?;\n\n }\n\n }\n\n\n\n if cx.doctests {\n\n fs::create_dir_all(&cx.ws.doctests_dir)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 9, "score": 85524.17992432762 }, { "content": "fn generate_report(cx: &Context) -> Result<()> {\n\n merge_profraw(cx).context(\"failed to merge profile data\")?;\n\n\n\n let object_files = object_files(cx).context(\"failed to collect object files\")?;\n\n let ignore_filename_regex = ignore_filename_regex(cx);\n\n for format in Format::from_args(cx) {\n\n format\n\n .generate_report(cx, &object_files, ignore_filename_regex.as_ref())\n\n .context(\"failed to generate report\")?;\n\n }\n\n\n\n if cx.cov.open {\n\n let path = &cx.cov.output_dir.as_ref().unwrap().join(\"html/index.html\");\n\n status!(\"Opening\", \"{}\", path);\n\n open_report(cx, path)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 10, "score": 85524.17992432762 }, { "content": "fn merge_profraw(cx: &Context) -> Result<()> {\n\n // Convert raw profile data.\n\n let mut cmd = cx.process(&cx.llvm_profdata);\n\n cmd.args([\"merge\", \"-sparse\"])\n\n .args(\n\n glob::glob(\n\n cx.ws.target_dir.join(format!(\"{}-*.profraw\", cx.ws.package_name)).as_str(),\n\n )?\n\n .filter_map(Result::ok),\n\n )\n\n .arg(\"-o\")\n\n .arg(&cx.ws.profdata_file);\n\n if let Some(mode) = &cx.cov.failure_mode {\n\n cmd.arg(format!(\"-failure-mode={}\", mode));\n\n }\n\n if let Some(jobs) = cx.build.jobs {\n\n cmd.arg(format!(\"-num-threads={}\", jobs));\n\n }\n\n if let Some(flags) = &cx.env.cargo_llvm_profdata_flags {\n\n cmd.args(flags.split(' ').filter(|s| !s.trim().is_empty()));\n\n }\n\n if cx.verbose {\n\n status!(\"Running\", \"{}\", cmd);\n\n }\n\n cmd.stdout_to_stderr().run()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 11, "score": 85524.17992432762 }, { "content": "fn ignore_filename_regex(cx: &Context) -> Option<String> {\n\n #[cfg(not(windows))]\n\n const SEPARATOR: &str = \"/\";\n\n #[cfg(windows)]\n\n const SEPARATOR: &str = \"\\\\\\\\\";\n\n\n\n fn default_ignore_filename_regex() -> String {\n\n // TODO: Should we use the actual target path instead of using `tests|examples|benches`?\n\n // We may have a directory like tests/support, so maybe we need both?\n\n format!(\n\n r\"(^|{0})(rustc{0}[0-9a-f]+|.cargo{0}(registry|git)|.rustup{0}toolchains|tests|examples|benches|target{0}llvm-cov-target){0}\",\n\n SEPARATOR\n\n )\n\n }\n\n\n\n #[derive(Default)]\n\n struct Out(String);\n\n\n\n impl Out {\n\n fn push(&mut self, s: impl AsRef<str>) {\n", "file_path": "src/main.rs", "rank": 12, "score": 81772.69396072376 }, { "content": "fn run_test(cx: &Context, args: &Args) -> Result<()> {\n\n let mut cargo = cx.cargo_process();\n\n\n\n set_env(cx, &mut cargo);\n\n\n\n cargo.arg(\"test\");\n\n if cx.doctests && !args.unstable_flags.iter().any(|f| f == \"doctest-in-workspace\") {\n\n // https://github.com/rust-lang/cargo/issues/9427\n\n cargo.arg(\"-Z\");\n\n cargo.arg(\"doctest-in-workspace\");\n\n }\n\n cargo::test_args(cx, args, &mut cargo);\n\n\n\n if cx.verbose {\n\n status!(\"Running\", \"{}\", cargo);\n\n }\n\n cargo.stdout_to_stderr().run()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 13, "score": 78649.51571098788 }, { "content": "pub fn assert_output(output_path: &Utf8Path) -> Result<()> {\n\n if env::var_os(\"CI\").is_some() {\n\n assert!(Command::new(\"git\")\n\n .args([\"--no-pager\", \"diff\", \"--exit-code\"])\n\n .arg(output_path)\n\n .status()?\n\n .success());\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/auxiliary/mod.rs", "rank": 14, "score": 77118.23065122646 }, { "content": "fn object_files(cx: &Context) -> Result<Vec<OsString>> {\n\n fn walk_target_dir(target_dir: &Utf8Path) -> impl Iterator<Item = walkdir::DirEntry> {\n\n WalkDir::new(target_dir)\n\n .into_iter()\n\n .filter_entry(|e| {\n\n let p = e.path();\n\n if p.is_dir()\n\n && p.file_name().map_or(false, |f| f == \"incremental\" || f == \".fingerprint\")\n\n {\n\n return false;\n\n }\n\n true\n\n })\n\n .filter_map(Result::ok)\n\n }\n\n\n\n let mut files = vec![];\n\n // To support testing binary crate like tests that use the CARGO_BIN_EXE\n\n // environment variable, pass all compiled executables.\n\n // This is not the ideal way, but the way unstable book says it is cannot support them.\n", "file_path": "src/main.rs", "rank": 15, "score": 77048.66031232484 }, { "content": "fn open_report(cx: &Context, path: &Utf8Path) -> Result<()> {\n\n let browser = cx.ws.config.doc.browser.as_ref().and_then(StringOrArray::path_and_args);\n\n\n\n match browser {\n\n Some((browser, initial_args)) => {\n\n cmd!(browser).args(initial_args).arg(path).run().with_context(|| {\n\n format!(\"couldn't open report with {}\", browser.to_string_lossy())\n\n })?;\n\n }\n\n None => opener::open(path).context(\"couldn't open report\")?,\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 16, "score": 77048.66031232484 }, { "content": "fn perturb_header<P: AsRef<Path>>(path: P) -> Result<()> {\n\n let mut file = fs::OpenOptions::new().read(true).write(true).open(path.as_ref())?;\n\n let mut magic = {\n\n let mut buf = vec![0_u8; size_of::<u64>()];\n\n file.read_exact(&mut buf)?;\n\n u64::from_ne_bytes(buf.try_into().unwrap())\n\n };\n\n assert_eq!(magic, INSTR_PROF_RAW_MAGIC_64);\n\n magic += 1;\n\n file.rewind()?;\n\n file.write_all(&magic.to_ne_bytes())?;\n\n Ok(())\n\n}\n\n\n\n#[ext(CommandExt)]\n\nimpl Command {\n\n #[track_caller]\n\n pub fn assert_output(&mut self) -> AssertOutput {\n\n let output = self.output().unwrap_or_else(|e| panic!(\"could not execute process: {}\", e));\n\n AssertOutput {\n", "file_path": "tests/auxiliary/mod.rs", "rank": 17, "score": 74134.95484356117 }, { "content": "#[test]\n\nfn clean_ws() {\n\n let model = \"merge\";\n\n let name = \"clean_ws\";\n\n let output_dir = auxiliary::FIXTURES_PATH.join(\"coverage-reports\").join(model);\n\n fs::create_dir_all(&output_dir).unwrap();\n\n for (extension, args) in test_set() {\n\n let workspace_root = test_project(model, name).unwrap();\n\n let output_path = &output_dir.join(name).with_extension(extension);\n\n cargo_llvm_cov()\n\n .args([\"--color\", \"never\", \"--no-report\", \"--features\", \"a\"])\n\n .current_dir(workspace_root.path())\n\n .assert_success();\n\n cargo_llvm_cov()\n\n .args([\"--color\", \"never\", \"--no-run\", \"--output-path\"])\n\n .arg(output_path)\n\n .args(args)\n\n .current_dir(workspace_root.path())\n\n .assert_success();\n\n\n\n auxiliary::normalize_output(output_path, args).unwrap();\n", "file_path": "tests/test.rs", "rank": 20, "score": 72634.94810735864 }, { "content": "fn main() {\n\n match std::env::args().skip(1).next().unwrap().parse::<u8>().unwrap() {\n\n 0 => {}\n\n 1 => {}\n\n 2 => {}\n\n _ => {}\n\n }\n\n}\n", "file_path": "tests/fixtures/crates/bin_crate/src/main.rs", "rank": 21, "score": 72527.3842244945 }, { "content": "#[test]\n\nfn test() {\n\n assert!(Command::new(env!(\"CARGO_BIN_EXE_bin_crate\")).arg(\"0\").status().unwrap().success());\n\n\n\n // The RUSTFLAGS environment variable is applied at compile time,\n\n // so it does not need to be present at run time of the test.\n\n // (i.e., the profile of this test will be collected.)\n\n assert!(\n\n Command::new(env!(\"CARGO_BIN_EXE_bin_crate\"))\n\n .arg(\"1\")\n\n .env_remove(\"RUSTFLAGS\")\n\n .status()\n\n .unwrap()\n\n .success()\n\n );\n\n\n\n // If you remove the LLVM_PROFILE_FILE environment variable,\n\n // no profile will be collected.\n\n assert!(\n\n Command::new(env!(\"CARGO_BIN_EXE_bin_crate\"))\n\n .arg(\"2\")\n\n .env_remove(\"LLVM_PROFILE_FILE\")\n\n .status()\n\n .unwrap()\n\n .success()\n\n );\n\n}\n", "file_path": "tests/fixtures/crates/bin_crate/tests/test.rs", "rank": 22, "score": 72527.3842244945 }, { "content": "#[cfg_attr(coverage, no_coverage)]\n\n#[test]\n\nfn fn_level() {\n\n func(0);\n\n\n\n if false {\n\n func(1);\n\n }\n\n}\n\n\n\n// #[no_coverage] has no effect on expressions.\n", "file_path": "tests/fixtures/crates/no_coverage/src/lib.rs", "rank": 23, "score": 72132.50908801823 }, { "content": "#[test]\n\nfn bin_crate() {\n\n run(\"bin_crate\", \"bin_crate\", &[], &[]);\n\n\n\n let model = \"bin_crate\";\n\n let name = \"run\";\n\n let id = format!(\"{}/{}\", model, name);\n\n for (extension, args2) in test_set() {\n\n test_report(model, name, extension, Some(\"run\"), &[args2, &[\"--\", \"1\"]].concat(), &[])\n\n .context(id.clone())\n\n .unwrap();\n\n }\n\n}\n\n\n", "file_path": "tests/test.rs", "rank": 24, "score": 71895.70994804602 }, { "content": "/// Collects metadata for packages generated by trybuild. If the trybuild test\n\n/// directory is not found, it returns an empty vector.\n\nfn trybuild_metadata(target_dir: &Utf8Path) -> Result<Vec<cargo_metadata::Metadata>> {\n\n let trybuild_dir = &target_dir.join(\"tests\");\n\n if !trybuild_dir.is_dir() {\n\n return Ok(vec![]);\n\n }\n\n let mut metadata = vec![];\n\n for entry in fs::read_dir(trybuild_dir)?.filter_map(Result::ok) {\n\n let manifest_path = entry.path().join(\"Cargo.toml\");\n\n if !manifest_path.is_file() {\n\n continue;\n\n }\n\n metadata.push(\n\n cargo_metadata::MetadataCommand::new().manifest_path(manifest_path).no_deps().exec()?,\n\n );\n\n }\n\n Ok(metadata)\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 25, "score": 71379.40906880154 }, { "content": "pub fn normalize_output(output_path: &Utf8Path, args: &[&str]) -> Result<()> {\n\n if args.contains(&\"--json\") {\n\n let s = fs::read_to_string(output_path)?;\n\n let mut json = serde_json::from_str::<json::LlvmCovJsonExport>(&s).unwrap();\n\n if !args.contains(&\"--summary-only\") {\n\n json.demangle();\n\n }\n\n fs::write(output_path, serde_json::to_vec_pretty(&json)?)?;\n\n }\n\n #[cfg(windows)]\n\n {\n\n let s = fs::read_to_string(output_path)?;\n\n // In json \\ is escaped (\"\\\\\\\\\"), in other it is not escaped (\"\\\\\").\n\n fs::write(output_path, s.replace(\"\\\\\\\\\", \"/\").replace('\\\\', \"/\"))?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/auxiliary/mod.rs", "rank": 26, "score": 71379.40906880154 }, { "content": "pub fn test_project(model: &str, name: &str) -> Result<TempDir> {\n\n static COUNTER: AtomicUsize = AtomicUsize::new(0);\n\n\n\n let tmpdir = Builder::new()\n\n .prefix(&format!(\"test_project_{}_{}_{}\", model, name, COUNTER.fetch_add(1, Relaxed)))\n\n .tempdir()?;\n\n let workspace_root = tmpdir.path();\n\n let model_path = FIXTURES_PATH.join(\"crates\").join(model);\n\n\n\n for entry in WalkDir::new(&model_path).into_iter().filter_map(Result::ok) {\n\n let from = entry.path();\n\n let to = &workspace_root.join(from.strip_prefix(&model_path)?);\n\n if from.is_dir() {\n\n fs::create_dir_all(to)?;\n\n } else {\n\n fs::copy(from, to)?;\n\n }\n\n }\n\n\n\n Ok(tmpdir)\n\n}\n\n\n", "file_path": "tests/auxiliary/mod.rs", "rank": 27, "score": 70112.01841365412 }, { "content": "fn coloring() -> ColorChoice {\n\n match COLORING.load(Relaxed) {\n\n AUTO => ColorChoice::Auto,\n\n ALWAYS => ColorChoice::Always,\n\n NEVER => ColorChoice::Never,\n\n _ => unreachable!(),\n\n }\n\n}\n\n\n\nstatic QUIET: AtomicBool = AtomicBool::new(false);\n\n\n\npub(crate) fn set_quiet(quiet: bool) {\n\n QUIET.store(quiet, Relaxed);\n\n}\n\n\n\npub(crate) fn quiet() -> bool {\n\n QUIET.load(Relaxed)\n\n}\n\n\n\npub(crate) fn print_inner(status: &str, color: Option<Color>, justified: bool) -> StandardStream {\n", "file_path": "src/term.rs", "rank": 28, "score": 69646.00869985395 }, { "content": "#[test]\n\nfn f() {}\n", "file_path": "tests/fixtures/crates/no_test/src/lib.rs", "rank": 29, "score": 67578.31022759563 }, { "content": "#[test]\n\nfn test() {\n\n #[cfg(feature = \"a\")]\n\n assert!(!func(1));\n\n #[cfg(feature = \"b\")]\n\n assert!(func(-1));\n\n}\n", "file_path": "tests/fixtures/crates/merge/src/lib.rs", "rank": 30, "score": 65639.50219610817 }, { "content": "#[test]\n\nfn test() {\n\n func(1);\n\n func(3);\n\n member1::func(0);\n\n member2::func(0);\n\n}\n", "file_path": "tests/fixtures/crates/real1/src/lib.rs", "rank": 31, "score": 65639.50219610817 }, { "content": "#[test]\n\nfn test() {\n\n assert!(!func(1_f32));\n\n assert!(func(-1_i32));\n\n}\n", "file_path": "tests/fixtures/crates/instantiations/src/lib.rs", "rank": 32, "score": 65639.50219610817 }, { "content": "fn line_separated(lines: &str, f: impl FnMut(&str)) {\n\n lines.split('\\n').map(str::trim).filter(|line| !line.is_empty()).for_each(f);\n\n}\n\n\n\nimpl AssertOutput {\n\n /// Receives a line(`\\n`)-separated list of patterns and asserts whether stderr contains each pattern.\n\n #[track_caller]\n\n pub fn stderr_contains(&self, pats: &str) -> &Self {\n\n line_separated(pats, |pat| {\n\n if !self.stderr.contains(pat) {\n\n panic!(\n\n \"assertion failed: `self.stderr.contains(..)`:\\n\\nEXPECTED:\\n{0}\\n{1}\\n{0}\\n\\nACTUAL:\\n{0}\\n{2}\\n{0}\\n\",\n\n \"-\".repeat(60),\n\n pat,\n\n self.stderr\n\n );\n\n }\n\n });\n\n self\n\n }\n", "file_path": "tests/auxiliary/mod.rs", "rank": 33, "score": 64921.831511448036 }, { "content": "#[test]\n\nfn test() {\n\n #[cfg(a)]\n\n assert!(!func(1));\n\n #[cfg(not(a))]\n\n assert!(func(-1));\n\n}\n", "file_path": "tests/fixtures/crates/cargo_config/src/lib.rs", "rank": 34, "score": 63828.03245332155 }, { "content": "#[test]\n\nfn test() {\n\n func(1);\n\n func(3);\n\n member2::func(0);\n\n member3::func(0);\n\n member4::func(0);\n\n}\n", "file_path": "tests/fixtures/crates/virtual1/member1/src/lib.rs", "rank": 35, "score": 63828.03245332155 }, { "content": "#[test]\n\nfn expr_level() {\n\n if false {\n\n #[cfg_attr(coverage, no_coverage)]\n\n func(2);\n\n }\n\n}\n\n\n\n// #[no_coverage] has no effect on modules.\n\n#[cfg_attr(coverage, no_coverage)]\n\nmod mod_level {\n\n use super::func;\n\n\n\n #[test]\n\n fn mod_level() {\n\n if false {\n\n func(3);\n\n }\n\n }\n\n}\n", "file_path": "tests/fixtures/crates/no_coverage/src/lib.rs", "rank": 36, "score": 63828.03245332155 }, { "content": "#[test]\n\nfn test() {\n\n func2(0);\n\n func2(2);\n\n}\n", "file_path": "tests/fixtures/crates/virtual1/member2/src/lib.rs", "rank": 37, "score": 63828.03245332155 }, { "content": "fn func(x: i32) {\n\n match x {\n\n 0 => {}\n\n 1 => {}\n\n 2 => {}\n\n 3 => {}\n\n _ => {}\n\n }\n\n}\n\n\n", "file_path": "tests/fixtures/crates/no_coverage/src/lib.rs", "rank": 38, "score": 62426.80051539729 }, { "content": "#[test]\n\nfn test() {\n\n #[cfg(a)]\n\n assert!(!func(1));\n\n #[cfg(not(a))]\n\n assert!(func(-1));\n\n}\n", "file_path": "tests/fixtures/crates/cargo_config_toml/src/lib.rs", "rank": 39, "score": 62131.75476358958 }, { "content": "pub fn func(x: u32) {\n\n match x {\n\n 0 => {}\n\n 1 => {}\n\n 2 => {}\n\n _ => {}\n\n }\n\n}\n\n\n", "file_path": "tests/fixtures/crates/real1/src/lib.rs", "rank": 40, "score": 60161.64065424975 }, { "content": "fn func(x: i32) -> bool {\n\n if x < 0 {\n\n true\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "tests/fixtures/crates/merge/src/lib.rs", "rank": 41, "score": 60161.64065424975 }, { "content": "pub fn func(x: u32) {\n\n match x {\n\n 0 => {}\n\n 1 => {}\n\n 2 => {}\n\n _ => {}\n\n }\n\n}\n", "file_path": "tests/fixtures/crates/no_test/src/module.rs", "rank": 42, "score": 60161.64065424975 }, { "content": "pub fn func(x: u32) {\n\n match x {\n\n 0 => {}\n\n 1 => {}\n\n 2 => {}\n\n _ => {}\n\n }\n\n}\n", "file_path": "tests/fixtures/crates/real1/member1/src/lib.rs", "rank": 43, "score": 58569.90594681355 }, { "content": "pub fn func2(x: u32) {\n\n match x {\n\n 0 => {}\n\n 1 => {}\n\n 2 => {}\n\n _ => {}\n\n }\n\n}\n\n\n", "file_path": "tests/fixtures/crates/virtual1/member2/src/lib.rs", "rank": 44, "score": 58569.90594681355 }, { "content": "fn func(x: i32) -> bool {\n\n if x < 0 {\n\n true\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "tests/fixtures/crates/cargo_config/src/lib.rs", "rank": 45, "score": 58569.90594681355 }, { "content": "pub fn func(x: u32) {\n\n match x {\n\n 0 => {}\n\n 1 => {}\n\n 2 => {}\n\n _ => {}\n\n }\n\n}\n\n\n", "file_path": "tests/fixtures/crates/virtual1/member2/src/lib.rs", "rank": 46, "score": 58569.90594681355 }, { "content": "pub fn func(x: u32) {\n\n match x {\n\n 0 => {}\n\n 1 => {}\n\n 2 => {}\n\n _ => {}\n\n }\n\n}\n\n\n", "file_path": "tests/fixtures/crates/virtual1/member1/src/lib.rs", "rank": 47, "score": 58569.90594681355 }, { "content": "fn func(x: i32) -> bool {\n\n if x < 0 {\n\n true\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "tests/fixtures/crates/cargo_config_toml/src/lib.rs", "rank": 48, "score": 57073.33853301637 }, { "content": "pub fn func(x: u32) {\n\n match x {\n\n 0 => {}\n\n 1 => {}\n\n 2 => {}\n\n _ => {}\n\n }\n\n}\n", "file_path": "tests/fixtures/crates/real1/member1/member2/src/lib.rs", "rank": 49, "score": 57073.33853301637 }, { "content": "pub fn func(x: u32) {\n\n match x {\n\n 0 => {}\n\n 1 => {}\n\n 2 => {}\n\n _ => {}\n\n }\n\n}\n", "file_path": "tests/fixtures/crates/virtual1/member2/member3/src/lib.rs", "rank": 50, "score": 57073.33853301637 }, { "content": "pub fn func(x: u32) {\n\n match x {\n\n 0 => {}\n\n 1 => {}\n\n 2 => {}\n\n _ => {}\n\n }\n\n}\n", "file_path": "tests/fixtures/crates/virtual1/member2/src/member4/src/lib.rs", "rank": 51, "score": 55663.65129728203 }, { "content": "fn run(model: &str, name: &str, args: &[&str], envs: &[(&str, &str)]) {\n\n let id = format!(\"{}/{}\", model, name);\n\n for (extension, args2) in test_set() {\n\n test_report(model, name, extension, None, &[args, args2].concat(), envs)\n\n .context(id.clone())\n\n .unwrap();\n\n }\n\n}\n\n\n\n// TODO:\n\n// - add tests for non-crates.io dependencies\n\n\n", "file_path": "tests/test.rs", "rank": 52, "score": 53864.57440698991 }, { "content": "fn func<T: Default + PartialOrd>(t: T) -> bool {\n\n if t < T::default() {\n\n true\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "tests/fixtures/crates/instantiations/src/lib.rs", "rank": 53, "score": 52986.98756267385 }, { "content": "#[test]\n\nfn merge() {\n\n let output_dir = auxiliary::FIXTURES_PATH.join(\"coverage-reports\").join(\"merge\");\n\n merge_with_failure_mode(&output_dir, false);\n\n}\n\n\n", "file_path": "tests/test.rs", "rank": 54, "score": 41652.21540643874 }, { "content": "#[test]\n\nfn real1() {\n\n run(\"real1\", \"workspace_root\", &[], &[]);\n\n run(\"real1\", \"all\", &[\"--all\"], &[]);\n\n run(\"real1\", \"manifest_path\", &[\"--manifest-path\", \"member1/member2/Cargo.toml\"], &[]);\n\n run(\"real1\", \"package1\", &[\"--package\", \"member2\"], &[]);\n\n run(\"real1\", \"exclude\", &[\"--all\", \"--exclude\", \"crate1\"], &[]);\n\n}\n\n\n", "file_path": "tests/test.rs", "rank": 55, "score": 41652.21540643874 }, { "content": "#[test]\n\nfn no_test() {\n\n // TODO: we should fix this: https://github.com/taiki-e/cargo-llvm-cov/issues/21\n\n run(\"no_test\", \"no_test\", &[], &[]);\n\n if !(cfg!(windows) && cfg!(target_env = \"msvc\")) {\n\n run(\"no_test\", \"link_dead_code\", &[], &[(\"RUSTFLAGS\", \"-C link-dead-code\")]);\n\n }\n\n}\n\n\n", "file_path": "tests/test.rs", "rank": 56, "score": 41652.21540643874 }, { "content": "#[test]\n\nfn virtual1() {\n\n run(\"virtual1\", \"workspace_root\", &[], &[]);\n\n run(\"virtual1\", \"package1\", &[\"--package\", \"member1\"], &[]);\n\n run(\"virtual1\", \"package2\", &[\"--package\", \"member1\", \"--package\", \"member2\"], &[]);\n\n run(\"virtual1\", \"package3\", &[\"--package\", \"member2\"], &[]);\n\n run(\"virtual1\", \"package4\", &[\"--package\", \"member3\"], &[]);\n\n run(\"virtual1\", \"package5\", &[\"--package\", \"member4\"], &[]);\n\n run(\"virtual1\", \"package6\", &[\"--package\", \"member3\", \"--package\", \"member4\"], &[]);\n\n run(\"virtual1\", \"exclude\", &[\"--workspace\", \"--exclude\", \"member2\"], &[]);\n\n}\n\n\n", "file_path": "tests/test.rs", "rank": 57, "score": 41652.21540643874 }, { "content": "#[test]\n\nfn instantiations() {\n\n // TODO: fix https://github.com/taiki-e/cargo-llvm-cov/issues/43\n\n run(\"instantiations\", \"instantiations\", &[], &[]);\n\n}\n\n\n", "file_path": "tests/test.rs", "rank": 58, "score": 41652.21540643874 }, { "content": "// https://doc.rust-lang.org/nightly/cargo/commands/cargo-metadata.html\n\nfn metadata(\n\n env: &Env,\n\n manifest_path: &Utf8Path,\n\n options: &ManifestOptions,\n\n) -> Result<cargo_metadata::Metadata> {\n\n let mut cmd =\n\n cmd!(env.cargo(), \"metadata\", \"--format-version\", \"1\", \"--manifest-path\", manifest_path);\n\n options.cargo_args(&mut cmd);\n\n serde_json::from_str(&cmd.read()?)\n\n .with_context(|| format!(\"failed to parse output from {}\", cmd))\n\n}\n\n\n\n// https://doc.rust-lang.org/nightly/cargo/commands/cargo-test.html\n\npub(crate) fn test_args(cx: &Context, args: &Args, cmd: &mut ProcessBuilder) {\n\n let mut has_target_selection_options = false;\n\n if args.lib {\n\n has_target_selection_options = true;\n\n cmd.arg(\"--lib\");\n\n }\n\n for name in &args.bin {\n", "file_path": "src/cargo.rs", "rank": 59, "score": 41652.21540643874 }, { "content": "#[test]\n\nfn no_coverage() {\n\n let model = \"no_coverage\";\n\n let id = format!(\"{}/{}\", model, model);\n\n for (extension, args2) in test_set() {\n\n // TODO: On windows, the order of the instantiations in the generated coverage report will be different.\n\n if extension == \"full.json\" && cfg!(windows) {\n\n continue;\n\n }\n\n test_report(model, model, extension, None, args2, &[]).context(id.clone()).unwrap();\n\n }\n\n\n\n let name = \"no_cfg_coverage\";\n\n let id = format!(\"{}/{}\", model, name);\n\n for (extension, args2) in test_set() {\n\n // TODO: On windows, the order of the instantiations in the generated coverage report will be different.\n\n if extension == \"full.json\" && cfg!(windows) {\n\n continue;\n\n }\n\n test_report(model, name, extension, None, &[args2, &[\"--no-cfg-coverage\"]].concat(), &[])\n\n .context(id.clone())\n\n .unwrap();\n\n }\n\n}\n\n\n", "file_path": "tests/test.rs", "rank": 60, "score": 41652.21540643874 }, { "content": "fn main() {\n\n if let Err(e) = try_main() {\n\n error!(\"{:#}\", e);\n\n std::process::exit(1)\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 61, "score": 41652.21540643874 }, { "content": "#[test]\n\nfn version() {\n\n cargo_llvm_cov().arg(\"--version\").assert_success().stdout_contains(env!(\"CARGO_PKG_VERSION\"));\n\n cargo_llvm_cov().args([\"clean\", \"--version\"]).assert_failure().stderr_contains(\n\n \"Found argument '--version' which wasn't expected, or isn't valid in this context\",\n\n );\n\n}\n", "file_path": "tests/test.rs", "rank": 62, "score": 41652.21540643874 }, { "content": "#[test]\n\nfn cargo_config() {\n\n run(\"cargo_config\", \"cargo_config\", &[], &[]);\n\n run(\"cargo_config_toml\", \"cargo_config_toml\", &[], &[]);\n\n}\n\n\n", "file_path": "tests/test.rs", "rank": 63, "score": 40473.66010061073 }, { "content": "#[cfg_attr(windows, ignore)] // `echo` may not be available\n\n#[test]\n\nfn open_report() {\n\n let model = \"real1\";\n\n let workspace_root = test_project(model, \"open_report\").unwrap();\n\n cargo_llvm_cov()\n\n .args([\"--color\", \"never\", \"--open\"])\n\n .current_dir(workspace_root.path())\n\n .env(\"BROWSER\", \"echo\")\n\n .assert_success()\n\n .stdout_contains(\n\n &workspace_root.path().join(\"target/llvm-cov/html/index.html\").to_string_lossy(),\n\n );\n\n}\n\n\n", "file_path": "tests/test.rs", "rank": 64, "score": 40473.66010061073 }, { "content": "#[test]\n\nfn merge_failure_mode_all() {\n\n let tempdir = tempdir().unwrap();\n\n let output_dir = Utf8Path::from_path(tempdir.path()).unwrap();\n\n merge_with_failure_mode(output_dir, true);\n\n}\n\n\n", "file_path": "tests/test.rs", "rank": 65, "score": 39380.969976381646 }, { "content": "#[track_caller]\n\npub fn test_report(\n\n model: &str,\n\n name: &str,\n\n extension: &str,\n\n subcommand: Option<&str>,\n\n args: &[&str],\n\n envs: &[(&str, &str)],\n\n) -> Result<()> {\n\n let workspace_root = test_project(model, name)?;\n\n let output_dir = FIXTURES_PATH.join(\"coverage-reports\").join(model);\n\n fs::create_dir_all(&output_dir)?;\n\n let output_path = &output_dir.join(name).with_extension(extension);\n\n let mut cmd = cargo_llvm_cov();\n\n if let Some(subcommand) = subcommand {\n\n cmd.arg(subcommand);\n\n }\n\n cmd.args([\"--color\", \"never\", \"--output-path\"])\n\n .arg(output_path)\n\n .args(args)\n\n .current_dir(workspace_root.path());\n\n for (key, val) in envs {\n\n cmd.env(key, val);\n\n }\n\n cmd.assert_success();\n\n\n\n normalize_output(output_path, args)?;\n\n assert_output(output_path)\n\n}\n\n\n", "file_path": "tests/auxiliary/mod.rs", "rank": 66, "score": 37614.270740835476 }, { "content": "fn create_disambiguator_re() -> Regex {\n\n Regex::new(r\"\\[[0-9a-f]{5,16}\\]::\").unwrap()\n\n}\n\n\n", "file_path": "src/demangler.rs", "rank": 67, "score": 37614.270740835476 }, { "content": "use std::process::Command;\n\n\n\n#[test]\n", "file_path": "tests/fixtures/crates/bin_crate/tests/test.rs", "rank": 68, "score": 36794.062388982464 }, { "content": "pub fn cargo_llvm_cov() -> Command {\n\n let mut cmd = Command::new(env!(\"CARGO_BIN_EXE_cargo-llvm-cov\"));\n\n cmd.arg(\"llvm-cov\");\n\n cmd.env_remove(\"RUSTFLAGS\")\n\n .env_remove(\"RUSTDOCFLAGS\")\n\n .env_remove(\"CARGO_TARGET_DIR\")\n\n .env_remove(\"CARGO_BUILD_RUSTFLAGS\")\n\n .env_remove(\"CARGO_BUILD_RUSTDOCFLAGS\")\n\n .env_remove(\"CARGO_TERM_VERBOSE\")\n\n .env_remove(\"CARGO_TERM_COLOR\")\n\n .env_remove(\"BROWSER\")\n\n .env_remove(\"RUST_LOG\")\n\n .env_remove(\"CI\");\n\n cmd\n\n}\n\n\n", "file_path": "tests/auxiliary/mod.rs", "rank": 69, "score": 35132.26612082063 }, { "content": "pub(crate) use std::fs::Metadata;\n\nuse std::{ffi::OsStr, io, path::Path};\n\n\n\npub(crate) use fs_err::{create_dir_all, read_dir, symlink_metadata, write};\n\n\n\n/// Removes a file from the filesystem **if exists**.\n\npub(crate) fn remove_file(path: impl AsRef<Path>) -> io::Result<()> {\n\n match fs_err::remove_file(path.as_ref()) {\n\n Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),\n\n res => res,\n\n }\n\n}\n\n\n\n/// Removes a directory at this path **if exists**.\n\npub(crate) fn remove_dir_all(path: impl AsRef<Path>) -> io::Result<()> {\n\n match fs_err::remove_dir_all(path.as_ref()) {\n\n Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),\n\n res => res,\n\n }\n\n}\n", "file_path": "src/fs.rs", "rank": 70, "score": 34893.76520209317 }, { "content": "\n\npub(crate) fn file_stem_recursive(path: &Path) -> Option<&OsStr> {\n\n let mut file_name = path.file_name()?;\n\n while let Some(stem) = Path::new(file_name).file_stem() {\n\n if file_name == stem {\n\n break;\n\n }\n\n file_name = stem;\n\n }\n\n Some(file_name)\n\n}\n", "file_path": "src/fs.rs", "rank": 71, "score": 34888.946455040576 }, { "content": "}\n\n\n\nmacro_rules! warn {\n\n ($($msg:expr),* $(,)?) => {{\n\n use std::io::Write;\n\n let mut stream = crate::term::print_inner(\"warning\", Some(termcolor::Color::Yellow), false);\n\n let _ = writeln!(stream, $($msg),*);\n\n }};\n\n}\n\n\n\nmacro_rules! info {\n\n ($($msg:expr),* $(,)?) => {{\n\n use std::io::Write;\n\n let mut stream = crate::term::print_inner(\"info\", None, false);\n\n let _ = writeln!(stream, $($msg),*);\n\n }};\n\n}\n\n\n\nmacro_rules! status {\n\n ($status:expr, $($msg:expr),* $(,)?) => {{\n\n use std::io::Write;\n\n if !crate::term::quiet() {\n\n let mut stream = crate::term::print_inner($status, Some(termcolor::Color::Cyan), true);\n\n let _ = writeln!(stream, $($msg),*);\n\n }\n\n }};\n\n}\n", "file_path": "src/term.rs", "rank": 72, "score": 34837.14917389812 }, { "content": "use std::{\n\n io::Write,\n\n sync::atomic::{AtomicBool, AtomicU8, Ordering::Relaxed},\n\n};\n\n\n\nuse termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};\n\n\n\nuse crate::cli::Coloring;\n\n\n\nstatic COLORING: AtomicU8 = AtomicU8::new(AUTO);\n\n\n\nconst AUTO: u8 = Coloring::Auto as _;\n\nconst ALWAYS: u8 = Coloring::Always as _;\n\nconst NEVER: u8 = Coloring::Never as _;\n\n\n\npub(crate) fn set_coloring(coloring: &mut Option<Coloring>) {\n\n let mut color = coloring.unwrap_or(Coloring::Auto);\n\n if color == Coloring::Auto && !atty::is(atty::Stream::Stderr) {\n\n *coloring = Some(Coloring::Never);\n\n color = Coloring::Never;\n\n }\n\n COLORING.store(color as _, Relaxed);\n\n}\n\n\n", "file_path": "src/term.rs", "rank": 73, "score": 34831.82254128275 }, { "content": " let mut stream = StandardStream::stderr(coloring());\n\n let _ = stream.set_color(ColorSpec::new().set_bold(true).set_fg(color));\n\n if justified {\n\n let _ = write!(stream, \"{:>12}\", status);\n\n } else {\n\n let _ = write!(stream, \"{}\", status);\n\n let _ = stream.set_color(ColorSpec::new().set_bold(true));\n\n let _ = write!(stream, \":\");\n\n }\n\n let _ = stream.reset();\n\n let _ = write!(stream, \" \");\n\n stream\n\n}\n\n\n\nmacro_rules! error {\n\n ($($msg:expr),* $(,)?) => {{\n\n use std::io::Write;\n\n let mut stream = crate::term::print_inner(\"error\", Some(termcolor::Color::Red), false);\n\n let _ = writeln!(stream, $($msg),*);\n\n }};\n", "file_path": "src/term.rs", "rank": 74, "score": 34830.55063978368 }, { "content": " let exe = format!(\"cargo-llvm-cov{}\", env::consts::EXE_SUFFIX);\n\n warn!(\"failed to get current executable, assuming {} in PATH as current executable: {}\", exe, e);\n\n exe.into()\n\n }\n\n },\n\n })\n\n }\n\n\n\n pub(crate) fn cargo(&self) -> &OsStr {\n\n self.cargo.as_deref().unwrap_or_else(|| OsStr::new(\"cargo\"))\n\n }\n\n}\n\n\n\npub(crate) fn var(key: &str) -> Result<Option<String>> {\n\n match env::var(key) {\n\n Ok(v) if v.is_empty() => Ok(None),\n\n Ok(v) => Ok(Some(v)),\n\n Err(env::VarError::NotPresent) => Ok(None),\n\n Err(e) => Err(e.into()),\n\n }\n\n}\n", "file_path": "src/env.rs", "rank": 75, "score": 34747.333603724146 }, { "content": "use std::{\n\n env,\n\n ffi::{OsStr, OsString},\n\n path::PathBuf,\n\n};\n\n\n\nuse anyhow::Result;\n\n\n\n#[derive(Debug)]\n\npub(crate) struct Env {\n\n /// `CARGO_LLVM_COV_FLAGS` environment variable to pass additional flags\n\n /// to llvm-cov. (value: space-separated list)\n\n pub(crate) cargo_llvm_cov_flags: Option<String>,\n\n /// `CARGO_LLVM_PROFDATA_FLAGS` environment variable to pass additional flags\n\n /// to llvm-profdata. (value: space-separated list)\n\n pub(crate) cargo_llvm_profdata_flags: Option<String>,\n\n\n\n // Environment variables Cargo sets for 3rd party subcommands\n\n // https://doc.rust-lang.org/nightly/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-3rd-party-subcommands\n\n /// `CARGO` environment variable.\n", "file_path": "src/env.rs", "rank": 76, "score": 34745.81918455436 }, { "content": " pub(crate) cargo: Option<OsString>,\n\n\n\n pub(crate) current_exe: PathBuf,\n\n}\n\n\n\nimpl Env {\n\n pub(crate) fn new() -> Result<Self> {\n\n let cargo_llvm_cov_flags = var(\"CARGO_LLVM_COV_FLAGS\")?;\n\n let cargo_llvm_profdata_flags = var(\"CARGO_LLVM_PROFDATA_FLAGS\")?;\n\n env::remove_var(\"LLVM_COV_FLAGS\");\n\n env::remove_var(\"LLVM_PROFDATA_FLAGS\");\n\n env::set_var(\"CARGO_INCREMENTAL\", \"0\");\n\n\n\n Ok(Self {\n\n cargo_llvm_cov_flags,\n\n cargo_llvm_profdata_flags,\n\n cargo: env::var_os(\"CARGO\"),\n\n current_exe: match env::current_exe() {\n\n Ok(exe) => exe,\n\n Err(e) => {\n", "file_path": "src/env.rs", "rank": 77, "score": 34744.273440944206 }, { "content": "fn demangle_lines(lines: Lines<'_>) -> Vec<String> {\n\n let strip_crate_disambiguators = create_disambiguator_re();\n\n let mut demangled_lines = Vec::new();\n\n for mangled in lines {\n\n let mut demangled = demangle(mangled).to_string();\n\n demangled = strip_crate_disambiguators.replace_all(&demangled, REPLACE_COLONS).to_string();\n\n demangled_lines.push(demangled);\n\n }\n\n demangled_lines\n\n}\n\n\n\npub(crate) fn run() -> Result<()> {\n\n let mut buffer = String::new();\n\n io::stdin().read_to_string(&mut buffer)?;\n\n let mut demangled_lines = demangle_lines(buffer.lines());\n\n demangled_lines.push(\"\".to_string()); // ensure a trailing newline\n\n io::stdout().write_all(demangled_lines.join(\"\\n\").as_bytes())?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/demangler.rs", "rank": 78, "score": 33615.71942725589 }, { "content": "fn resolve_excluded_paths(cx: &Context) -> Vec<Utf8PathBuf> {\n\n let excluded: Vec<_> = cx\n\n .workspace_members\n\n .excluded\n\n .iter()\n\n .map(|id| cx.ws.metadata[id].manifest_path.parent().unwrap())\n\n .collect();\n\n let included = cx\n\n .workspace_members\n\n .included\n\n .iter()\n\n .map(|id| cx.ws.metadata[id].manifest_path.parent().unwrap());\n\n let mut excluded_path = vec![];\n\n let mut contains: HashMap<&Utf8Path, Vec<_>> = HashMap::new();\n\n for included in included {\n\n for &excluded in excluded.iter().filter(|e| included.starts_with(e)) {\n\n if let Some(v) = contains.get_mut(&excluded) {\n\n v.push(included);\n\n } else {\n\n contains.insert(excluded, vec![included]);\n", "file_path": "src/main.rs", "rank": 79, "score": 31724.87123827616 }, { "content": "fn test_set() -> Vec<(&'static str, &'static [&'static str])> {\n\n vec![\n\n (\"txt\", &[\"--text\"]),\n\n (\"hide-instantiations.txt\", &[\"--text\", \"--hide-instantiations\"]),\n\n (\"summary.txt\", &[]),\n\n (\"json\", &[\"--json\", \"--summary-only\"]),\n\n (\"full.json\", &[\"--json\"]),\n\n (\"lcov.info\", &[\"--lcov\", \"--summary-only\"]),\n\n ]\n\n}\n\n\n", "file_path": "tests/test.rs", "rank": 80, "score": 31611.051441870273 }, { "content": "fn merge_with_failure_mode(output_dir: &Utf8Path, failure_mode_all: bool) {\n\n let model = \"merge\";\n\n fs::create_dir_all(&output_dir).unwrap();\n\n for (extension, args) in test_set() {\n\n let workspace_root = test_project(model, model).unwrap();\n\n let output_path = &output_dir.join(model).with_extension(extension);\n\n cargo_llvm_cov()\n\n .args([\"--color\", \"never\", \"--no-report\", \"--features\", \"a\"])\n\n .current_dir(workspace_root.path())\n\n .assert_success();\n\n cargo_llvm_cov()\n\n .args([\"--color\", \"never\", \"--no-report\", \"--features\", \"b\"])\n\n .current_dir(workspace_root.path())\n\n .assert_success();\n\n let mut cmd = cargo_llvm_cov();\n\n cmd.args([\"--color\", \"never\", \"--no-run\", \"--output-path\"])\n\n .arg(output_path)\n\n .args(args)\n\n .current_dir(workspace_root.path());\n\n cmd.assert_success();\n", "file_path": "tests/test.rs", "rank": 81, "score": 31036.396005995826 }, { "content": "mod module;\n\npub use module::*;\n\n\n\n#[test]\n", "file_path": "tests/fixtures/crates/no_test/src/lib.rs", "rank": 82, "score": 29216.813947703136 }, { "content": "#![cfg_attr(coverage, feature(no_coverage))]\n\n\n", "file_path": "tests/fixtures/crates/no_coverage/src/lib.rs", "rank": 83, "score": 29213.219106000815 }, { "content": "// https://github.com/taiki-e/cargo-llvm-cov/issues/43\n\n\n", "file_path": "tests/fixtures/crates/instantiations/src/lib.rs", "rank": 84, "score": 29213.219106000815 }, { "content": "use std::{env, ffi::OsString};\n\n\n\nuse anyhow::{bail, Result};\n\nuse camino::Utf8PathBuf;\n\nuse cargo_metadata::PackageId;\n\n\n\nuse crate::{\n\n cargo::Workspace,\n\n cli::{BuildOptions, LlvmCovOptions, ManifestOptions},\n\n env::Env,\n\n process::ProcessBuilder,\n\n term,\n\n};\n\n\n\npub(crate) struct Context {\n\n pub(crate) env: Env,\n\n pub(crate) ws: Workspace,\n\n\n\n pub(crate) build: BuildOptions,\n\n pub(crate) manifest: ManifestOptions,\n", "file_path": "src/context.rs", "rank": 86, "score": 25.495963924851537 }, { "content": " workspace: bool,\n\n exclude: &[String],\n\n package: &[String],\n\n quiet: bool,\n\n doctests: bool,\n\n no_run: bool,\n\n ) -> Result<Self> {\n\n let env = Env::new()?;\n\n let ws = Workspace::new(&env, &manifest, build.target.as_deref())?;\n\n ws.config.merge_to_args(&mut build.target, &mut build.verbose, &mut build.color);\n\n term::set_coloring(&mut build.color);\n\n\n\n cov.html |= cov.open;\n\n if cov.output_dir.is_some() && !cov.show() {\n\n // If the format flag is not specified, this flag is no-op.\n\n cov.output_dir = None;\n\n }\n\n if cov.disable_default_ignore_filename_regex {\n\n warn!(\"--disable-default-ignore-filename-regex option is unstable\");\n\n }\n", "file_path": "src/context.rs", "rank": 88, "score": 20.57568255709016 }, { "content": " #[serde(default)]\n\n target: BTreeMap<String, Target>,\n\n #[serde(default)]\n\n pub(crate) doc: Doc,\n\n #[serde(default)]\n\n pub(crate) term: Term,\n\n}\n\n\n\nimpl Config {\n\n pub(crate) fn new(\n\n cargo: &Cargo,\n\n workspace_root: &Utf8Path,\n\n target: Option<&str>,\n\n host: Option<&str>,\n\n ) -> Result<Self> {\n\n let mut cmd = cargo.process();\n\n cmd.args([\"-Z\", \"unstable-options\", \"config\", \"get\", \"--format\", \"json\"])\n\n .dir(workspace_root);\n\n let mut config = match cmd.read() {\n\n Ok(s) => serde_json::from_str(&s)\n", "file_path": "src/config.rs", "rank": 89, "score": 17.85294735460725 }, { "content": " pub(crate) current_manifest: Utf8PathBuf,\n\n\n\n pub(crate) cargo: Cargo,\n\n}\n\n\n\nimpl Workspace {\n\n pub(crate) fn new(env: &Env, options: &ManifestOptions, target: Option<&str>) -> Result<Self> {\n\n let current_manifest = package_root(env, options.manifest_path.as_deref())?;\n\n let metadata = metadata(env, &current_manifest, options)?;\n\n\n\n let cargo = Cargo::new(env, &metadata.workspace_root)?;\n\n let mut rustc = cargo.rustc_process();\n\n rustc.args([\"--version\", \"--verbose\"]);\n\n let verbose_version = rustc.read()?;\n\n let host = verbose_version\n\n .lines()\n\n .find_map(|line| line.strip_prefix(\"host: \"))\n\n .ok_or_else(|| {\n\n format_err!(\"unexpected version output from `{}`: {}\", rustc, verbose_version)\n\n })?\n", "file_path": "src/cargo.rs", "rank": 90, "score": 17.064478669587253 }, { "content": " Always,\n\n Never,\n\n}\n\n\n\nimpl Coloring {\n\n pub(crate) fn cargo_color(self) -> &'static str {\n\n clap::ArgEnum::as_arg(&self).unwrap()\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::{env, panic, path::Path, process::Command};\n\n\n\n use anyhow::Result;\n\n use clap::{Clap, IntoApp};\n\n use fs_err as fs;\n\n use tempfile::Builder;\n\n\n\n use super::{Args, Opts, MAX_TERM_WIDTH};\n", "file_path": "src/cli.rs", "rank": 91, "score": 17.039786601315424 }, { "content": " self.doc.browser = Some(StringOrArray::String(browser));\n\n }\n\n }\n\n\n\n if let Some(verbose) = env::var(\"CARGO_TERM_VERBOSE\")? {\n\n self.term.verbose = Some(verbose.parse()?);\n\n }\n\n if let Some(color) = env::var(\"CARGO_TERM_COLOR\")? {\n\n self.term.color =\n\n Some(clap::ArgEnum::from_str(&color, false).map_err(|e| format_err!(\"{}\", e))?);\n\n }\n\n Ok(())\n\n }\n\n\n\n pub(crate) fn merge_to_args(\n\n &self,\n\n target: &mut Option<String>,\n\n verbose: &mut u8,\n\n color: &mut Option<Coloring>,\n\n ) {\n", "file_path": "src/config.rs", "rank": 92, "score": 16.36659142262291 }, { "content": "// Refs:\n\n// - https://doc.rust-lang.org/nightly/cargo/index.html\n\n\n\nuse std::{env, path::PathBuf};\n\n\n\nuse anyhow::{format_err, Context as _, Result};\n\nuse camino::{Utf8Path, Utf8PathBuf};\n\n\n\nuse crate::{\n\n cli::{Args, ManifestOptions, RunOptions},\n\n config::Config,\n\n context::Context,\n\n env::Env,\n\n process::ProcessBuilder,\n\n};\n\n\n\npub(crate) struct Cargo {\n\n path: PathBuf,\n\n pub(crate) nightly: bool,\n\n}\n", "file_path": "src/cargo.rs", "rank": 93, "score": 16.05096690400815 }, { "content": "mod demangler;\n\nmod env;\n\nmod fs;\n\n\n\nuse std::{\n\n collections::HashMap,\n\n convert::TryInto,\n\n ffi::{OsStr, OsString},\n\n slice,\n\n};\n\n\n\nuse anyhow::{Context as _, Result};\n\nuse camino::{Utf8Path, Utf8PathBuf};\n\nuse clap::Clap;\n\nuse cli::RunOptions;\n\nuse regex::Regex;\n\nuse walkdir::WalkDir;\n\n\n\nuse crate::{\n\n cli::{Args, Coloring, Opts, Subcommand},\n\n config::StringOrArray,\n\n context::Context,\n\n process::ProcessBuilder,\n\n};\n\n\n", "file_path": "src/main.rs", "rank": 94, "score": 15.189986673613676 }, { "content": " Ok(Self {\n\n env,\n\n ws,\n\n build,\n\n manifest,\n\n cov,\n\n verbose,\n\n quiet,\n\n doctests,\n\n no_run,\n\n workspace_members,\n\n llvm_cov,\n\n llvm_profdata,\n\n })\n\n }\n\n\n\n pub(crate) fn process(&self, program: impl Into<OsString>) -> ProcessBuilder {\n\n let mut cmd = cmd!(program);\n\n cmd.dir(&self.ws.metadata.workspace_root);\n\n // cargo displays env vars only with -vv.\n", "file_path": "src/context.rs", "rank": 95, "score": 15.181501079797371 }, { "content": "}\n\n\n\n#[derive(Debug, Clap)]\n\npub(crate) struct CleanOptions {\n\n /// Remove artifacts that may affect the coverage results of packages in the workspace.\n\n #[clap(long)]\n\n pub(crate) workspace: bool,\n\n // TODO: Currently, we are using a subdirectory of the target directory as\n\n // the actual target directory. What effect should this option have\n\n // on its behavior?\n\n // /// Directory for all generated artifacts\n\n // #[clap(long, value_name = \"DIRECTORY\")]\n\n // pub(crate) target_dir: Option<Utf8PathBuf>,\n\n /// Use verbose output\n\n #[clap(short, long, parse(from_occurrences))]\n\n pub(crate) verbose: u8,\n\n /// Coloring\n\n #[clap(long, arg_enum, value_name = \"WHEN\")]\n\n pub(crate) color: Option<Coloring>,\n\n #[clap(flatten)]\n", "file_path": "src/cli.rs", "rank": 96, "score": 14.836139569941652 }, { "content": " // CLI flags are prefer over config values.\n\n if target.is_none() {\n\n *target = self.build.target.clone();\n\n }\n\n if *verbose == 0 && self.term.verbose.unwrap_or(false) {\n\n *verbose = 1;\n\n }\n\n if color.is_none() {\n\n *color = self.term.color;\n\n }\n\n }\n\n\n\n pub(crate) fn rustflags(&self) -> Option<String> {\n\n // Refer only build.rustflags because Self::apply_env update build.rustflags\n\n // based on target.<..>.rustflags.\n\n self.build.rustflags.as_ref().map(ToString::to_string)\n\n }\n\n\n\n pub(crate) fn rustdocflags(&self) -> Option<String> {\n\n self.build.rustdocflags.as_ref().map(ToString::to_string)\n", "file_path": "src/config.rs", "rank": 97, "score": 14.576653107611374 }, { "content": " pub(crate) fn cov(&mut self) -> LlvmCovOptions {\n\n mem::take(&mut self.cov)\n\n }\n\n\n\n pub(crate) fn build(&mut self) -> BuildOptions {\n\n mem::take(&mut self.build)\n\n }\n\n\n\n pub(crate) fn manifest(&mut self) -> ManifestOptions {\n\n mem::take(&mut self.manifest)\n\n }\n\n}\n\n\n\n#[derive(Debug, Clap)]\n\npub(crate) enum Subcommand {\n\n /// Run a binary or example and generate coverage report.\n\n #[clap(\n\n bin_name = \"cargo llvm-cov run\",\n\n max_term_width = MAX_TERM_WIDTH,\n\n setting = AppSettings::DeriveDisplayOrder,\n", "file_path": "src/cli.rs", "rank": 98, "score": 14.07080004554275 }, { "content": " if flag == \"--exclude\" {\n\n Opts::try_parse_from(&[\"cargo\", \"llvm-cov\", flag, \"\", \"--workspace\"]).unwrap();\n\n } else {\n\n Opts::try_parse_from(&[\"cargo\", \"llvm-cov\", flag, \"\"]).unwrap();\n\n }\n\n }\n\n }\n\n\n\n fn get_help(long: bool) -> Result<String> {\n\n let mut buf = vec![];\n\n if long {\n\n Args::into_app().term_width(MAX_TERM_WIDTH).write_long_help(&mut buf)?;\n\n } else {\n\n Args::into_app().term_width(MAX_TERM_WIDTH).write_help(&mut buf)?;\n\n }\n\n let mut out = String::new();\n\n for mut line in String::from_utf8(buf)?.lines() {\n\n if let Some(new) = line.trim_end().strip_suffix(env!(\"CARGO_PKG_VERSION\")) {\n\n line = new;\n\n }\n", "file_path": "src/cli.rs", "rank": 99, "score": 13.66386783184474 } ]
Rust
src/full_node/apply_block.rs
NilFoundation/rust-ton
ea970ca3a96f93f2ad48576fd5d8f5503ad2040d
use crate::{ block::BlockStuff, engine_traits::EngineOperations, shard_state::ShardStateStuff }; use std::{ops::Deref, sync::Arc}; use storage::block_handle_db::BlockHandle; use ton_types::{error, fail, Result}; use ton_block::BlockIdExt; pub const MAX_RECURSION_DEPTH: u32 = 16; pub async fn apply_block( handle: &Arc<BlockHandle>, block: &BlockStuff, mc_seq_no: u32, engine: &Arc<dyn EngineOperations>, pre_apply: bool, recursion_depth: u32 ) -> Result<()> { if handle.id() != block.id() { fail!("Block id mismatch in apply block: {} vs {}", handle.id(), block.id()) } let prev_ids = block.construct_prev_id()?; check_prev_blocks(&prev_ids, engine, mc_seq_no, pre_apply, recursion_depth).await?; let shard_state = if handle.has_state() { engine.load_state(handle.id()).await? } else { calc_shard_state(handle, block, &prev_ids, engine).await? }; if !pre_apply { set_next_prev_ids(&handle, &prev_ids, engine.deref())?; engine.process_block_in_ext_db(handle, &block, None, &shard_state, mc_seq_no).await?; } Ok(()) } async fn check_prev_blocks( prev_ids: &(BlockIdExt, Option<BlockIdExt>), engine: &Arc<dyn EngineOperations>, mc_seq_no: u32, pre_apply: bool, recursion_depth: u32 ) -> Result<()> { match prev_ids { (prev1_id, Some(prev2_id)) => { let mut apply_prev_futures = Vec::with_capacity(2); apply_prev_futures.push( engine.clone().download_and_apply_block_internal(&prev1_id, mc_seq_no, pre_apply, recursion_depth + 1) ); apply_prev_futures.push( engine.clone().download_and_apply_block_internal(&prev2_id, mc_seq_no, pre_apply, recursion_depth + 1) ); futures::future::join_all(apply_prev_futures) .await .into_iter() .find(|r| r.is_err()) .unwrap_or(Ok(()))?; }, (prev_id, None) => { engine.clone().download_and_apply_block_internal(&prev_id, mc_seq_no, pre_apply, recursion_depth + 1).await?; } } Ok(()) } pub async fn calc_shard_state( handle: &Arc<BlockHandle>, block: &BlockStuff, prev_ids: &(BlockIdExt, Option<BlockIdExt>), engine: &Arc<dyn EngineOperations> ) -> Result<Arc<ShardStateStuff>> { log::trace!("calc_shard_state: block: {}", block.id()); let prev_ss_root = match prev_ids { (prev1, Some(prev2)) => { let ss1 = engine.clone().wait_state(prev1, None, true).await?.root_cell().clone(); let ss2 = engine.clone().wait_state(prev2, None, true).await?.root_cell().clone(); ShardStateStuff::construct_split_root(ss1, ss2)? }, (prev, None) => { engine.clone().wait_state(prev, None, true).await?.root_cell().clone() } }; let merkle_update = block.block().read_state_update()?; let block_id = block.id().clone(); let engine_cloned = engine.clone(); let ss = tokio::task::spawn_blocking( move || -> Result<Arc<ShardStateStuff>> { let now = std::time::Instant::now(); let ss_root = merkle_update.apply_for(&prev_ss_root)?; log::trace!("TIME: calc_shard_state: applied Merkle update {}ms {}", now.elapsed().as_millis(), block_id); ShardStateStuff::from_root_cell( block_id.clone(), ss_root, #[cfg(feature = "telemetry")] engine_cloned.engine_telemetry(), engine_cloned.engine_allocated() ) } ).await??; let now = std::time::Instant::now(); let ss = engine.store_state(handle, ss).await?; log::trace!("TIME: calc_shard_state: store_state {}ms {}", now.elapsed().as_millis(), handle.id()); Ok(ss) } pub fn set_next_prev_ids( handle: &Arc<BlockHandle>, prev_ids: &(BlockIdExt, Option<BlockIdExt>), engine: &dyn EngineOperations ) -> Result<()> { match prev_ids { (prev_id1, Some(prev_id2)) => { let prev_handle1 = engine.load_block_handle(&prev_id1)?.ok_or_else( || error!("Cannot load handle for prev1 block {}", prev_id1) )?; engine.store_block_next1(&prev_handle1, handle.id())?; let prev_handle2 = engine.load_block_handle(&prev_id2)?.ok_or_else( || error!("Cannot load handle for prev2 block {}", prev_id2) )?; engine.store_block_next1(&prev_handle2, handle.id())?; engine.store_block_prev1(handle, &prev_id1)?; engine.store_block_prev2(handle, &prev_id2)?; }, (prev_id, None) => { let prev_shard = prev_id.shard().clone(); let shard = handle.id().shard().clone(); let prev_handle = engine.load_block_handle(&prev_id)?.ok_or_else( || error!("Cannot load handle for prev block {}", prev_id) )?; if (prev_shard != shard) && (prev_shard.split()?.1 == shard) { engine.store_block_next2(&prev_handle, handle.id())?; } else { engine.store_block_next1(&prev_handle, handle.id())?; } engine.store_block_prev1(handle, &prev_id)?; } } Ok(()) }
use crate::{ block::BlockStuff, engine_traits::EngineOperations, shard_state::ShardStateStuff }; use std::{ops::Deref, sync::Arc}; use storage::block_handle_db::BlockHandle; use ton_types::{error, fail, Result}; use ton_block::BlockIdExt; pub const MAX_RECURSION_DEPTH: u32 = 16;
async fn check_prev_blocks( prev_ids: &(BlockIdExt, Option<BlockIdExt>), engine: &Arc<dyn EngineOperations>, mc_seq_no: u32, pre_apply: bool, recursion_depth: u32 ) -> Result<()> { match prev_ids { (prev1_id, Some(prev2_id)) => { let mut apply_prev_futures = Vec::with_capacity(2); apply_prev_futures.push( engine.clone().download_and_apply_block_internal(&prev1_id, mc_seq_no, pre_apply, recursion_depth + 1) ); apply_prev_futures.push( engine.clone().download_and_apply_block_internal(&prev2_id, mc_seq_no, pre_apply, recursion_depth + 1) ); futures::future::join_all(apply_prev_futures) .await .into_iter() .find(|r| r.is_err()) .unwrap_or(Ok(()))?; }, (prev_id, None) => { engine.clone().download_and_apply_block_internal(&prev_id, mc_seq_no, pre_apply, recursion_depth + 1).await?; } } Ok(()) } pub async fn calc_shard_state( handle: &Arc<BlockHandle>, block: &BlockStuff, prev_ids: &(BlockIdExt, Option<BlockIdExt>), engine: &Arc<dyn EngineOperations> ) -> Result<Arc<ShardStateStuff>> { log::trace!("calc_shard_state: block: {}", block.id()); let prev_ss_root = match prev_ids { (prev1, Some(prev2)) => { let ss1 = engine.clone().wait_state(prev1, None, true).await?.root_cell().clone(); let ss2 = engine.clone().wait_state(prev2, None, true).await?.root_cell().clone(); ShardStateStuff::construct_split_root(ss1, ss2)? }, (prev, None) => { engine.clone().wait_state(prev, None, true).await?.root_cell().clone() } }; let merkle_update = block.block().read_state_update()?; let block_id = block.id().clone(); let engine_cloned = engine.clone(); let ss = tokio::task::spawn_blocking( move || -> Result<Arc<ShardStateStuff>> { let now = std::time::Instant::now(); let ss_root = merkle_update.apply_for(&prev_ss_root)?; log::trace!("TIME: calc_shard_state: applied Merkle update {}ms {}", now.elapsed().as_millis(), block_id); ShardStateStuff::from_root_cell( block_id.clone(), ss_root, #[cfg(feature = "telemetry")] engine_cloned.engine_telemetry(), engine_cloned.engine_allocated() ) } ).await??; let now = std::time::Instant::now(); let ss = engine.store_state(handle, ss).await?; log::trace!("TIME: calc_shard_state: store_state {}ms {}", now.elapsed().as_millis(), handle.id()); Ok(ss) } pub fn set_next_prev_ids( handle: &Arc<BlockHandle>, prev_ids: &(BlockIdExt, Option<BlockIdExt>), engine: &dyn EngineOperations ) -> Result<()> { match prev_ids { (prev_id1, Some(prev_id2)) => { let prev_handle1 = engine.load_block_handle(&prev_id1)?.ok_or_else( || error!("Cannot load handle for prev1 block {}", prev_id1) )?; engine.store_block_next1(&prev_handle1, handle.id())?; let prev_handle2 = engine.load_block_handle(&prev_id2)?.ok_or_else( || error!("Cannot load handle for prev2 block {}", prev_id2) )?; engine.store_block_next1(&prev_handle2, handle.id())?; engine.store_block_prev1(handle, &prev_id1)?; engine.store_block_prev2(handle, &prev_id2)?; }, (prev_id, None) => { let prev_shard = prev_id.shard().clone(); let shard = handle.id().shard().clone(); let prev_handle = engine.load_block_handle(&prev_id)?.ok_or_else( || error!("Cannot load handle for prev block {}", prev_id) )?; if (prev_shard != shard) && (prev_shard.split()?.1 == shard) { engine.store_block_next2(&prev_handle, handle.id())?; } else { engine.store_block_next1(&prev_handle, handle.id())?; } engine.store_block_prev1(handle, &prev_id)?; } } Ok(()) }
pub async fn apply_block( handle: &Arc<BlockHandle>, block: &BlockStuff, mc_seq_no: u32, engine: &Arc<dyn EngineOperations>, pre_apply: bool, recursion_depth: u32 ) -> Result<()> { if handle.id() != block.id() { fail!("Block id mismatch in apply block: {} vs {}", handle.id(), block.id()) } let prev_ids = block.construct_prev_id()?; check_prev_blocks(&prev_ids, engine, mc_seq_no, pre_apply, recursion_depth).await?; let shard_state = if handle.has_state() { engine.load_state(handle.id()).await? } else { calc_shard_state(handle, block, &prev_ids, engine).await? }; if !pre_apply { set_next_prev_ids(&handle, &prev_ids, engine.deref())?; engine.process_block_in_ext_db(handle, &block, None, &shard_state, mc_seq_no).await?; } Ok(()) }
function_block-full_function
[]
Rust
src/lexer/mod.rs
rickspencer3/sabre
de0de9f3bc14e85b5443046c7fe21cd4b142e8e5
/** * Copyright 2020 Garrit Franke * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pub(crate) mod cursor; use self::TokenKind::*; use cursor::Cursor; #[cfg(test)] mod tests; #[derive(Debug, PartialEq, Eq, Clone)] pub struct Token { pub kind: TokenKind, pub len: usize, pub raw: String, pub pos: Position, } impl Token { fn new(kind: TokenKind, len: usize, raw: String, pos: Position) -> Token { Token { kind, len, raw, pos, } } } #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub struct Position { pub line: usize, pub offset: usize, pub raw: usize, } #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum TokenKind { Whitespace, Identifier(String), Literal(Value), Keyword(Keyword), Comment, Plus, Minus, Star, Slash, Percent, Colon, SemiColon, Dot, Exclamation, Comma, Assign, Equals, LessThan, LessThanOrEqual, GreaterThan, GreaterThanOrEqual, NotEqual, And, Or, PlusEqual, MinusEqual, StarEqual, SlashEqual, BraceOpen, BraceClose, SquareBraceOpen, SquareBraceClose, CurlyBracesOpen, CurlyBracesClose, Tab, CarriageReturn, Unknown, } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum Value { Int, Str, } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum Keyword { Let, If, Else, Return, While, For, In, Break, Continue, Function, Boolean, Struct, New, Unknown, } pub fn tokenize(mut input: &str) -> Vec<Token> { let mut pos = Position { raw: usize::MAX, line: 1, offset: 0, }; std::iter::from_fn(move || { if input.is_empty() { return None; } let token = first_token(input, &mut pos); input = &input[token.len..]; Some(token) }) .collect() } pub fn first_token(input: &str, pos: &mut Position) -> Token { debug_assert!(!input.is_empty()); Cursor::new(input, pos).advance_token() } pub fn is_whitespace(c: char) -> bool { match c { ' ' | '\n' | '\r' | '\t' => true, '\u{00A0}' => { dbg!("Non-standard unicode character found: '\u{00A0}'"); true } _ => false, } } pub fn is_id_start(c: char) -> bool { ('a'..='z').contains(&c) || ('A'..='Z').contains(&c) || c == '_' } pub fn is_id_continue(c: char) -> bool { ('a'..='z').contains(&c) || ('A'..='Z').contains(&c) || ('0'..='9').contains(&c) || c == '_' } impl Cursor<'_> { fn advance_token(&mut self) -> Token { let original_chars = self.chars(); let original_chars2 = self.chars(); let first_char = self.bump().unwrap(); let token_kind = match first_char { c if is_whitespace(c) => self.whitespace(), '0'..='9' => self.number(), '"' | '\'' => self.string(), '.' => Dot, '+' => match self.first() { '=' => { self.bump(); PlusEqual } _ => Plus, }, '-' => match self.first() { '=' => { self.bump(); MinusEqual } _ => Minus, }, '*' => match self.first() { '=' => { self.bump(); StarEqual } _ => Star, }, '%' => Percent, '/' => match self.first() { '/' => { self.bump(); self.comment() } '=' => { self.bump(); SlashEqual } _ => Slash, }, '=' => match self.first() { '=' => { self.bump(); Equals } _ => Assign, }, ':' => Colon, ';' => SemiColon, ',' => Comma, '<' => match self.first() { '=' => { self.bump(); LessThanOrEqual } _ => LessThan, }, '>' => match self.first() { '=' => { self.bump(); GreaterThanOrEqual } _ => GreaterThan, }, '&' => match self.first() { '&' => { self.bump(); And } _ => Unknown, }, '|' => match self.first() { '|' => { self.bump(); Or } _ => Unknown, }, '!' => match self.first() { '=' => { self.bump(); NotEqual } _ => Exclamation, }, '(' => BraceOpen, ')' => BraceClose, '[' => SquareBraceOpen, ']' => SquareBraceClose, '{' => CurlyBracesOpen, '}' => CurlyBracesClose, c if is_id_start(c) => { let kind = self.identifier(c); if kind == Keyword::Unknown { let mut ch: String = original_chars.collect(); ch.truncate(self.len_consumed()); TokenKind::Identifier(ch) } else { TokenKind::Keyword(kind) } } '\n' => CarriageReturn, '\t' => Tab, _ => Unknown, }; let len = self.len_consumed(); let mut raw = original_chars2.collect::<String>(); raw.truncate(len); let position = self.pos(); Token::new(token_kind, len, raw, position) } fn eat_while<F>(&mut self, mut predicate: F) -> usize where F: FnMut(char) -> bool, { let mut eaten: usize = 0; while predicate(self.first()) && !self.is_eof() { eaten += 1; self.bump(); } eaten } fn whitespace(&mut self) -> TokenKind { debug_assert!(is_whitespace(self.prev())); self.eat_while(is_whitespace); Whitespace } fn number(&mut self) -> TokenKind { self.eat_digits(); TokenKind::Literal(Value::Int) } fn string(&mut self) -> TokenKind { self.eat_string(); TokenKind::Literal(Value::Str) } fn identifier(&mut self, first_char: char) -> Keyword { let mut original: String = self.chars().collect::<String>(); let len = self.eat_while(is_id_continue); original.truncate(len); original = format!("{}{}", first_char, original); match original { c if c == "if" => Keyword::If, c if c == "else" => Keyword::Else, c if c == "fn" => Keyword::Function, c if c == "true" || c == "false" => Keyword::Boolean, c if c == "let" => Keyword::Let, c if c == "return" => Keyword::Return, c if c == "while" => Keyword::While, c if c == "for" => Keyword::For, c if c == "in" => Keyword::In, c if c == "break" => Keyword::Break, c if c == "continue" => Keyword::Continue, c if c == "struct" => Keyword::Struct, c if c == "new" => Keyword::New, _ => Keyword::Unknown, } } fn comment(&mut self) -> TokenKind { while self.first() != '\n' { self.bump(); } TokenKind::Comment } fn eat_digits(&mut self) -> bool { let mut has_digits = false; loop { match self.first() { '_' => { self.bump(); } '0'..='9' => { has_digits = true; self.bump(); } _ => break, } } has_digits } fn eat_string(&mut self) { loop { match self.first() { '"' | '\'' => break, '\n' => panic!( "String does not end on same line. At {}:{}", self.pos().line, self.pos().offset ), _ => self.bump(), }; } self.bump(); } }
/** * Copyright 2020 Garrit Franke * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pub(crate) mod cursor; use self::TokenKind::*; use cursor::Cursor; #[cfg(test)] mod tests; #[derive(Debug, PartialEq, Eq, Clone)] pub struct Token { pub kind: TokenKind, pub len: usize, pub raw: String, pub pos: Position, } impl Token { fn new(kind: TokenKind, len: usize, raw: String, pos: Position) -> Token { Token { kind, len, raw, pos, } } } #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub struct Position { pub line: usize, pub offset: usize, pub raw: usize, } #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum TokenKind { Whitespace, Identifier(String), Literal(Value), Keyword(Keyword), Comment, Plus, Minus, Star, Slash, Percent, Colon, SemiColon, Dot, Exclamation, Comma, Assign, Equals, LessThan, LessThanOrEqual, GreaterThan, GreaterThanOrEqual, NotEqual, And, Or, PlusEqual, MinusEqual, StarEqual, SlashEqual, BraceOpen, BraceClose, SquareBraceOpen, SquareBraceClose, CurlyBracesOpen, CurlyBracesClose, Tab, CarriageReturn, Unknown, } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum Value { Int, Str, } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum Keyword { Let, If, Else, Return, While, For, In, Break, Continue, Function, Boolean, Struct, New, Unknown, } pub fn tokenize(mut input: &str) -> Vec<Token> { let mut pos = Position { raw: usize::MAX, line: 1, offset: 0, }; std::iter::from_fn(move || { if input.is_empty() { return None; } let token = first_token(input, &mut pos); input = &input[token.len..]; Some(token) }) .collect() } pub fn first_token(input: &str, pos: &mut Position) -> Token { debug_assert!(!input.is_empty()); Cursor::new(input, pos).advance_token() } pub fn is_whitespace(c: char) -> bool { match c { ' ' | '\n' | '\r' | '\t' => true, '\u{00A0}' => { dbg!("Non-standard unicode character found: '\u{00A0}'"); true } _ => false, } } pub fn is_id_start(c: char) -> bool { ('a'..='z').contains(&c) || ('A'..='Z').contains(&c) || c == '_' } pub fn is_id_continue(c: char) -> bool { ('a'..='z').contains(&c) || ('A'..='Z').contains(&c) || ('0'..='9').contains(&c) || c == '_' } impl Cursor<'_> { fn advance_token(&mut self) -> Token { let original_chars = self.chars(); let original_chars2 = self.chars(); let first_char = self.bump().unwrap(); let token_kind = match first_char { c if is_whitespace(c) => self.whitespace(), '0'..='9' => self.number(), '"' | '\'' => self.string(), '.' => Dot, '+' => match self.first() { '=' => { self.bump(); PlusEqual } _ => Plus, }, '-' => match self.first() { '=' => { self.bump(); MinusEqual } _ => Minus, }, '*' => match self.first() { '=' => { self.bump(); StarEqual } _ => Star, }, '%' => Percent, '/' => match self.first() { '/' => { self.bump(); self.comment() } '=' => { self.bump(); SlashEqual } _ => Slash, }, '=' => match self.first() { '=' => { self.bump(); Equals } _ => Assign, }, ':' => Colon, ';' => SemiColon, ',' => Comma, '<' => match self.first() { '=' => { self.bump(); LessThanOrEqual } _ => LessThan, }, '>' => match self.first() { '=' => { self.bump(); GreaterThanOrEqual } _ => GreaterThan, }, '&' => match self.first() { '&' => { self.bump(); And } _ => Unknown, }, '|' => match self.first() { '|' => { self.bump(); Or } _ => Unknown, }, '!' => match self.first() { '=' => { self.bump(); NotEqual } _ => Exclamation, }, '(' => BraceOpen, ')' => BraceClose, '[' => SquareBraceOpen, ']' => SquareBraceClose, '{' => CurlyBracesOpen, '}' => CurlyBracesClose, c if is_id_start(c) => { let kind = self.identifier(c); if kind == Keyword::Unknown { let mut ch: String = original_chars.collect(); ch.truncate(self.len_consumed()); TokenKind::Identifier(ch) } else { TokenKind::Keyword(kind) } } '\n' => CarriageReturn, '\t' => Tab, _ => Unknown, }; let len = self.len_consumed(); let mut raw = original_chars2.collect::<String>(); raw.truncate(len); let position = self.pos(); Token::new(token_kind, len, raw, position) } fn eat_while<F>(&mut self, mut predicate: F) -> usize where F: FnMut(char) -> bool, { let mut eaten: usize = 0; while predicate(self.first()) && !self.is_eof() { eaten += 1; self.bump(); } eaten } fn whitespace(&mut self) -> TokenKind { debug_assert!(is_whitespace(self.prev())); self.eat_while(is_whitespace); Whitespace } fn number(&mut self) -> TokenKind { self.eat_digits(); TokenKind::Literal(Value::Int) } fn string(&mut self) -> TokenKind { self.eat_string(); TokenKind::Literal(Value::Str) } fn identifier(&mut self, first_char: char) -> Keyword { let mut original: String = self.chars().collect::<String>(); let len = self.eat_while(is_id_continue); original.truncate(len); original = format!("{}{}", first_char, original); match original { c if c == "if" => Keyword::If, c if c == "else" => Keyword::Else, c if c == "fn" => Keyword::Function, c if c == "true" || c == "false" => Keyword::Boolean, c if c == "let" => Keyword::Let, c if c == "return" => Keyword::Return, c if c == "while" => Keyword::While, c if c == "for" => Keyword::For, c if c == "in" => Keyword::In, c if c == "break" => Keyword::Break, c if c == "continue" => Keyword::Continue, c if c == "struct" => Keyword::Struct, c if c == "new" => Keyword::New, _ => Keyword::Unknown, } } fn comment(&mut self) -> TokenKind { while self.first() != '\n' { self.bump(); } TokenKind::Comment }
fn eat_string(&mut self) { loop { match self.first() { '"' | '\'' => break, '\n' => panic!( "String does not end on same line. At {}:{}", self.pos().line, self.pos().offset ), _ => self.bump(), }; } self.bump(); } }
fn eat_digits(&mut self) -> bool { let mut has_digits = false; loop { match self.first() { '_' => { self.bump(); } '0'..='9' => { has_digits = true; self.bump(); } _ => break, } } has_digits }
function_block-full_function
[ { "content": "pub fn highlight_position_in_file(input: String, position: Position) -> String {\n\n // TODO: Chain without collecting in between\n\n input\n\n .chars()\n\n .skip(position.raw)\n\n .take_while(|c| c != &'\\n')\n\n .collect::<String>()\n\n .chars()\n\n .rev()\n\n .take_while(|c| c != &'\\n')\n\n .collect::<String>()\n\n .chars()\n\n .rev()\n\n .collect::<String>()\n\n}\n", "file_path": "src/util/string_util.rs", "rank": 4, "score": 237614.97775228 }, { "content": "pub fn parse(tokens: Vec<Token>, raw: Option<String>) -> Result<Program, String> {\n\n let mut parser = parser::Parser::new(tokens, raw);\n\n parser.parse()\n\n}\n", "file_path": "src/parser/mod.rs", "rank": 6, "score": 224839.44677977622 }, { "content": "#[test]\n\nfn test_tokenizing_without_whitespace() {\n\n let mut tokens = tokenize(\"1=2\").into_iter();\n\n\n\n assert_eq!(\n\n tokens.next().unwrap(),\n\n Token {\n\n len: 1,\n\n kind: TokenKind::Literal(Value::Int),\n\n raw: \"1\".to_owned(),\n\n pos: Position {\n\n raw: 0,\n\n line: 1,\n\n offset: 0\n\n }\n\n }\n\n );\n\n\n\n assert_eq!(\n\n tokens.next().unwrap(),\n\n Token {\n", "file_path": "src/lexer/tests.rs", "rank": 7, "score": 162323.4446507993 }, { "content": "#[allow(unreachable_code)]\n\npub fn generate(prog: Program) -> String {\n\n #[cfg(feature = \"backend_llvm\")]\n\n return llvm::LLVMGenerator::generate(prog);\n\n #[cfg(feature = \"backend_c\")]\n\n return c::CGenerator::generate(prog);\n\n\n\n #[cfg(feature = \"backend_node\")]\n\n return js::JsGenerator::generate(prog);\n\n\n\n panic!(\"No backend specified\");\n\n}\n", "file_path": "src/generator/mod.rs", "rank": 8, "score": 156761.9825645625 }, { "content": "pub fn build(in_file: &Path, out_file: &Path) -> Result<(), String> {\n\n let mut file = File::open(in_file).expect(\"Could not open file\");\n\n let mut contents = String::new();\n\n\n\n file.read_to_string(&mut contents)\n\n .expect(\"Could not read file\");\n\n let tokens = lexer::tokenize(&contents);\n\n let mut program = parser::parse(tokens, Some(contents))?;\n\n\n\n // C Backend currently does not support stdlib yet, since not all features are implemented\n\n if cfg!(feature = \"backend_node\") {\n\n let stdlib = build_stdlib();\n\n program.merge_with(stdlib);\n\n }\n\n\n\n let output = generator::generate(program);\n\n let mut file = std::fs::File::create(out_file).expect(\"create failed\");\n\n file.write_all(output.as_bytes()).expect(\"write failed\");\n\n file.flush().expect(\"Could not flush file\");\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/command/build.rs", "rank": 9, "score": 147986.66875016913 }, { "content": "pub fn run(in_file: PathBuf) -> Result<(), String> {\n\n let out_dir = tempdir()\n\n .expect(\"Could not create temporary file\")\n\n .into_path();\n\n\n\n let intermediate_out_file_path = out_dir.join(\"intermediate.c\");\n\n build::build(&in_file, &intermediate_out_file_path)?;\n\n let out_file = out_dir.join(\"out\");\n\n if cfg!(feature = \"backend_c\") {\n\n Command::new(\"/usr/bin/cc\")\n\n .arg(&intermediate_out_file_path)\n\n .arg(\"-o\")\n\n .arg(&out_file)\n\n .stdout(Stdio::piped())\n\n .stderr(Stdio::piped())\n\n .output()\n\n .expect(\"Could not spawn compilation process\");\n\n\n\n let out = Command::new(out_file)\n\n .stdout(Stdio::piped())\n", "file_path": "src/command/run.rs", "rank": 10, "score": 147189.16136985837 }, { "content": "fn generate_function(func: Function) -> String {\n\n let mut buf = String::new();\n\n buf += &format!(\"{} \", &generate_function_signature(func.clone()));\n\n if let Statement::Block(statements, scope) = func.body {\n\n buf += &generate_block(statements, scope);\n\n }\n\n\n\n buf\n\n}\n\n\n", "file_path": "src/generator/c.rs", "rank": 11, "score": 144889.59091675555 }, { "content": "fn generate_function_signature(func: Function) -> String {\n\n let arguments: String = func\n\n .arguments\n\n .into_iter()\n\n .map(|var| format!(\"{} {}\", generate_type(Either::Left(var.clone())), var.name))\n\n .collect::<Vec<String>>()\n\n .join(\", \");\n\n let t = generate_type(Either::Right(func.ret_type));\n\n format!(\"{T} {N}({A})\", T = t, N = func.name, A = arguments)\n\n}\n\n\n", "file_path": "src/generator/c.rs", "rank": 12, "score": 142211.48060146498 }, { "content": "fn generate_function(func: Function) -> String {\n\n let arguments: String = func\n\n .arguments\n\n .into_iter()\n\n .map(|var| var.name)\n\n .collect::<Vec<String>>()\n\n .join(\", \");\n\n let mut raw = format!(\"function {N}({A})\", N = func.name, A = arguments);\n\n\n\n raw += &generate_block(func.body, None);\n\n\n\n raw\n\n}\n\n\n", "file_path": "src/generator/js.rs", "rank": 13, "score": 142211.48060146498 }, { "content": "fn generate_assign(name: Expression, expr: Expression) -> String {\n\n format!(\n\n \"{} = {};\",\n\n generate_expression(name),\n\n generate_expression(expr)\n\n )\n\n}\n", "file_path": "src/generator/c.rs", "rank": 14, "score": 140386.27170584537 }, { "content": "fn generate_function_call(func: String, args: Vec<Expression>) -> String {\n\n let formatted_args = args\n\n .into_iter()\n\n .map(|arg| match arg {\n\n Expression::Int(i) => i.to_string(),\n\n Expression::Bool(v) => v.to_string(),\n\n Expression::ArrayAccess(name, expr) => generate_array_access(name, *expr),\n\n Expression::FunctionCall(n, a) => generate_function_call(n, a),\n\n Expression::Str(s) | Expression::Variable(s) => s,\n\n Expression::Array(_) => todo!(),\n\n Expression::BinOp(left, op, right) => generate_bin_op(*left, op, *right),\n\n Expression::StructInitialization(_, _) => todo!(),\n\n Expression::FieldAccess(_, _) => todo!(),\n\n })\n\n .collect::<Vec<String>>()\n\n .join(\",\");\n\n format!(\"{N}({A})\", N = func, A = formatted_args)\n\n}\n\n\n", "file_path": "src/generator/c.rs", "rank": 15, "score": 139454.34182001953 }, { "content": "fn generate_assign(name: Expression, expr: Expression) -> String {\n\n format!(\n\n \"{} = {}\",\n\n generate_expression(name),\n\n generate_expression(expr)\n\n )\n\n}\n", "file_path": "src/generator/js.rs", "rank": 16, "score": 137149.0294809947 }, { "content": "fn generate_return(ret: Option<Expression>) -> String {\n\n match ret {\n\n Some(expr) => format!(\"return {};\", generate_expression(expr)),\n\n None => \"return;\".to_string(),\n\n }\n\n}\n\n\n", "file_path": "src/generator/c.rs", "rank": 17, "score": 136747.34541483177 }, { "content": "fn generate_function_call(func: String, args: Vec<Expression>) -> String {\n\n let formatted_args = args\n\n .into_iter()\n\n .map(|arg| match arg {\n\n Expression::Int(i) => i.to_string(),\n\n Expression::Bool(v) => v.to_string(),\n\n Expression::ArrayAccess(name, expr) => generate_array_access(name, *expr),\n\n Expression::FunctionCall(n, a) => generate_function_call(n, a),\n\n Expression::Str(s) | Expression::Variable(s) => s,\n\n Expression::Array(elements) => generate_array(elements),\n\n Expression::BinOp(left, op, right) => generate_bin_op(*left, op, *right),\n\n Expression::StructInitialization(name, fields) => {\n\n generate_struct_initialization(name, fields)\n\n }\n\n Expression::FieldAccess(expr, field) => generate_field_access(*expr, field),\n\n })\n\n .collect::<Vec<String>>()\n\n .join(\",\");\n\n format!(\"{N}({A})\", N = func, A = formatted_args)\n\n}\n\n\n", "file_path": "src/generator/js.rs", "rank": 18, "score": 136580.6778830322 }, { "content": "#[test]\n\nfn test_array_position_assignment() {\n\n let raw = \"\n\n fn main() {\n\n new_arr[i] = 1\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 19, "score": 133235.33171238442 }, { "content": "fn generate_return(ret: Option<Expression>) -> String {\n\n match ret {\n\n Some(expr) => format!(\"return {}\", generate_expression(expr)),\n\n None => \"return\".to_string(),\n\n }\n\n}\n\n\n", "file_path": "src/generator/js.rs", "rank": 20, "score": 133208.89322740573 }, { "content": "#[test]\n\nfn test_booleans_in_function_call() {\n\n let raw = \"\n\n fn main() {\n\n if n > 2 {\n\n _printf(true)\n\n } else {\n\n _printf(true)\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok());\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 21, "score": 132768.69287755448 }, { "content": "#[test]\n\nfn test_while_loop_boolean_expression() {\n\n let raw = \"\n\n fn main() {\n\n let x = 5 * 2\n\n while true && x {\n\n return x\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 22, "score": 132745.52329319125 }, { "content": "#[test]\n\nfn test_parse_function_with_return() {\n\n let raw = \"\n\n fn main() {\n\n return 1\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 23, "score": 132725.32970789282 }, { "content": "#[test]\n\nfn test_function_with_return_type() {\n\n let raw = \"\n\n fn main(x: int): int {\n\n return n\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok());\n\n assert_eq!(tree.unwrap().func[0].ret_type, Some(Type::Int));\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 24, "score": 132725.32970789282 }, { "content": "#[test]\n\nfn test_no_function_args_without_type() {\n\n let raw = \"\n\n fn main(x) {\n\n return n\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_err())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 25, "score": 129179.17267630639 }, { "content": "#[test]\n\nfn test_parse_return_function_call() {\n\n let raw = \"\n\n fn main() {\n\n return fib(2)\n\n }\n\n\n\n fn fib() {\n\n return fib(2)\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 26, "score": 129094.61070179543 }, { "content": "fn generate_break() -> String {\n\n \"break;\\n\".into()\n\n}\n\n\n", "file_path": "src/generator/js.rs", "rank": 27, "score": 123109.36091643022 }, { "content": "fn generate_continue() -> String {\n\n \"continue;\\n\".into()\n\n}\n\n\n", "file_path": "src/generator/js.rs", "rank": 28, "score": 123086.2487693741 }, { "content": "fn generate_expression(expr: Expression) -> String {\n\n match expr {\n\n Expression::Int(val) => val.to_string(),\n\n Expression::Variable(val) | Expression::Str(val) => val,\n\n Expression::Bool(b) => b.to_string(),\n\n Expression::FunctionCall(name, e) => generate_function_call(name, e),\n\n Expression::Array(els) => generate_array(els),\n\n Expression::ArrayAccess(name, expr) => generate_array_access(name, *expr),\n\n Expression::BinOp(left, op, right) => generate_bin_op(*left, op, *right),\n\n Expression::StructInitialization(_, _) => todo!(),\n\n Expression::FieldAccess(_, _) => todo!(),\n\n }\n\n}\n\n\n", "file_path": "src/generator/c.rs", "rank": 29, "score": 122648.51670352225 }, { "content": "fn generate_expression(expr: Expression) -> String {\n\n match expr {\n\n Expression::Int(val) => val.to_string(),\n\n Expression::Variable(val) | Expression::Str(val) => val,\n\n Expression::Bool(b) => b.to_string(),\n\n Expression::FunctionCall(name, e) => generate_function_call(name, e),\n\n Expression::Array(els) => generate_array(els),\n\n Expression::ArrayAccess(name, expr) => generate_array_access(name, *expr),\n\n Expression::BinOp(left, op, right) => generate_bin_op(*left, op, *right),\n\n Expression::StructInitialization(name, fields) => {\n\n generate_struct_initialization(name, fields)\n\n }\n\n Expression::FieldAccess(expr, field) => generate_field_access(*expr, field),\n\n }\n\n}\n\n\n", "file_path": "src/generator/js.rs", "rank": 30, "score": 119971.08712880005 }, { "content": "fn generate_array_access(name: String, expr: Expression) -> String {\n\n format!(\"{n}[{e}]\", n = name, e = generate_expression(expr))\n\n}\n\n\n", "file_path": "src/generator/c.rs", "rank": 31, "score": 118358.09680320826 }, { "content": "fn generate_struct_definition(struct_def: StructDef) -> String {\n\n // JS doesn't care about field declaration\n\n format!(\"class {} {{}}\\n\", struct_def.name)\n\n}\n\n\n", "file_path": "src/generator/js.rs", "rank": 32, "score": 118261.80642773116 }, { "content": "fn test_directory(dir_in: &str) -> Result<(), Error> {\n\n let dir_out = format!(\"{}_out\", dir_in);\n\n let dir = std::env::current_dir().unwrap();\n\n\n\n let examples = std::fs::read_dir(dir.join(dir_in))?;\n\n\n\n let _ = fs::create_dir(&dir_out);\n\n\n\n let out_file_suffix = if cfg!(feature = \"backend_node\") {\n\n \".js\"\n\n } else if cfg!(feature = \"backend_c\") {\n\n \".c\"\n\n } else {\n\n todo!()\n\n };\n\n\n\n for ex in examples {\n\n let example = ex?;\n\n let in_file = dir.join(dir_in).join(example.file_name());\n\n let out_file = dir.join(&dir_out).join(\n", "file_path": "src/tests/test_examples.rs", "rank": 33, "score": 117729.65062788193 }, { "content": "fn generate_array_access(name: String, expr: Expression) -> String {\n\n format!(\"{n}[{e}]\", n = name, e = generate_expression(expr))\n\n}\n\n\n", "file_path": "src/generator/js.rs", "rank": 34, "score": 116111.61567726947 }, { "content": "fn generate_field_access(expr: Expression, field: String) -> String {\n\n format!(\"{}.{}\", generate_expression(expr), field)\n\n}\n\n\n", "file_path": "src/generator/js.rs", "rank": 35, "score": 116111.61567726947 }, { "content": "fn generate_declare(name: String, val: Option<Expression>) -> String {\n\n // var is used here to not collide with scopes.\n\n // TODO: Can let be used instead?\n\n match val {\n\n Some(expr) => format!(\"var {} = {}\", name, generate_expression(expr)),\n\n None => format!(\"var {}\", name),\n\n }\n\n}\n\n\n", "file_path": "src/generator/js.rs", "rank": 36, "score": 114370.30424021113 }, { "content": "#[test]\n\nfn test_comments() {\n\n let mut tokens = tokenize(\n\n \"// foo\n", "file_path": "src/lexer/tests.rs", "rank": 37, "score": 110083.12289518418 }, { "content": "#[test]\n\nfn test_break() {\n\n let raw = \"\n\n fn main() {\n\n let arr = [1, 2, 3]\n\n \n\n for x in arr {\n\n if x == 2 {\n\n break\n\n } else {\n\n println(x)\n\n }\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok());\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 38, "score": 110083.12289518418 }, { "content": "#[test]\n\nfn test_continue() {\n\n let raw = \"\n\n fn main() {\n\n let arr = [1, 2, 3]\n\n \n\n for x in arr {\n\n if x == 2 {\n\n continue\n\n } else {\n\n println(x)\n\n }\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok());\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 39, "score": 110059.14019855327 }, { "content": "#[test]\n\nfn test_booleans() {\n\n let mut tokens = tokenize(\"true false\").into_iter();\n\n\n\n assert_eq!(\n\n tokens.next().unwrap(),\n\n Token {\n\n len: 4,\n\n kind: TokenKind::Keyword(Keyword::Boolean),\n\n raw: \"true\".to_owned(),\n\n pos: Position {\n\n raw: 3,\n\n line: 1,\n\n offset: 3\n\n }\n\n }\n\n );\n\n\n\n assert_eq!(\n\n tokens.nth(1).unwrap(),\n\n Token {\n", "file_path": "src/lexer/tests.rs", "rank": 40, "score": 110035.63533686294 }, { "content": "#[test]\n\nfn test_functions() {\n\n let mut tokens = tokenize(\"fn fib() {}\").into_iter();\n\n\n\n assert_eq!(\n\n tokens.next().unwrap(),\n\n Token {\n\n len: 2,\n\n kind: TokenKind::Keyword(Keyword::Function),\n\n raw: \"fn\".to_owned(),\n\n pos: Position {\n\n raw: 1,\n\n line: 1,\n\n offset: 1\n\n }\n\n }\n\n );\n\n}\n\n\n", "file_path": "src/lexer/tests.rs", "rank": 41, "score": 109557.34822643446 }, { "content": "fn generate_array(elements: Vec<Expression>) -> String {\n\n let mut out_str = String::from(\"[\");\n\n\n\n out_str += &elements\n\n .iter()\n\n .map(|el| match el {\n\n Expression::Int(x) => x.to_string(),\n\n Expression::Str(x) => x.to_string(),\n\n _ => todo!(\"Not yet implemented\"),\n\n })\n\n .collect::<Vec<String>>()\n\n .join(\", \");\n\n\n\n out_str += \"]\";\n\n out_str\n\n}\n\n\n", "file_path": "src/generator/c.rs", "rank": 42, "score": 108728.77896951759 }, { "content": "#[test]\n\nfn test_int_array() {\n\n let raw = \"\n\n fn main() {\n\n let arr = [1, 2, 3]\n\n return arr\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 43, "score": 107077.83918331019 }, { "content": "#[test]\n\nfn test_struct_initialization() {\n\n let raw = \"\n\n struct User {\n\n username: string,\n\n first_name: string,\n\n last_name: string\n\n }\n\n \n\n fn main() {\n\n let foo = new User {\n\n username: 'foobar',\n\n first_name: 'Foo',\n\n last_name: 'Bar'\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok());\n\n}\n", "file_path": "src/parser/tests.rs", "rank": 44, "score": 107007.40570552897 }, { "content": "#[test]\n\nfn test_boolean_arithmetic() {\n\n let raw = \"\n\n fn main() {\n\n let x = true && false\n\n let y = false && true || true\n\n let z = x && true\n\n while true && x {\n\n return x\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 45, "score": 107007.40570552897 }, { "content": "#[test]\n\nfn test_basic_tokenizing() {\n\n let raw = tokenize(\"1 = 2\");\n\n let mut tokens = raw.into_iter();\n\n\n\n assert_eq!(\n\n tokens.next().unwrap(),\n\n Token {\n\n len: 1,\n\n kind: TokenKind::Literal(Value::Int),\n\n raw: \"1\".to_owned(),\n\n pos: Position {\n\n raw: 0,\n\n line: 1,\n\n offset: 0\n\n }\n\n }\n\n );\n\n\n\n assert_eq!(\n\n tokens.next().unwrap(),\n", "file_path": "src/lexer/tests.rs", "rank": 46, "score": 106984.91468347897 }, { "content": "#[test]\n\nfn test_string_array() {\n\n let raw = \"\n\n fn main(n:int) {\n\n return [\\\"Foo\\\", \\\"Bar\\\", \\\"Baz\\\"]\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 47, "score": 106174.84467771562 }, { "content": "fn generate_array(elements: Vec<Expression>) -> String {\n\n let mut out_str = String::from(\"[\");\n\n\n\n out_str += &elements\n\n .iter()\n\n .map(|el| generate_expression(el.clone()))\n\n .collect::<Vec<String>>()\n\n .join(\", \");\n\n\n\n out_str += \"]\";\n\n out_str\n\n}\n\n\n", "file_path": "src/generator/js.rs", "rank": 48, "score": 106107.49736026811 }, { "content": "#[test]\n\nfn test_parse_redundant_semicolon() {\n\n let raw = \"\n\n fn main() {\n\n return 1;\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_err())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 49, "score": 104238.0870885358 }, { "content": "#[test]\n\nfn test_array_access_assignment() {\n\n let raw = \"\n\n fn main() {\n\n let arr = [1, 2, 3]\n\n let x = arr[0]\n\n\n\n return x\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 50, "score": 104170.12072646365 }, { "content": "fn generate_while_loop(expr: Expression, body: Statement) -> String {\n\n let mut out_str = String::from(\"while (\");\n\n\n\n out_str += &generate_expression(expr);\n\n out_str += \") \";\n\n\n\n if let Statement::Block(statements, scope) = body {\n\n out_str += &generate_block(statements, scope);\n\n }\n\n out_str\n\n}\n\n\n", "file_path": "src/generator/c.rs", "rank": 51, "score": 104157.83581894949 }, { "content": "#[test]\n\nfn test_parse_basic_conditional() {\n\n let raw = \"\n\n fn main(n: int) {\n\n if n {\n\n return n\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 52, "score": 104083.38167080077 }, { "content": "#[test]\n\nfn test_parse_function_with_args() {\n\n let raw = \"\n\n fn main(foo: int) {\n\n return foo\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 53, "score": 103725.34011552215 }, { "content": "#[test]\n\nfn test_parse_function_call() {\n\n let raw = \"\n\n fn main(foo: int) {\n\n foo()\n\n }\n\n\n\n fn foo() {\n\n foo(2)\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 54, "score": 103725.34011552215 }, { "content": "#[test]\n\nfn test_function_call_math() {\n\n let raw = \"\n\n fn main(m: int) {\n\n main(m - 1)\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 55, "score": 103725.34011552215 }, { "content": "#[test]\n\nfn test_parse_multiple_functions() {\n\n let raw = \"\n\n fn foo() {\n\n let x = 2\n\n return x\n\n }\n\n\n\n fn bar() {\n\n let y = 5\n\n return y\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 56, "score": 103725.34011552215 }, { "content": "#[test]\n\nfn test_function_multiple_args() {\n\n let raw = \"\n\n fn main(m: int, n: int) {\n\n main(m, n)\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 57, "score": 103725.34011552215 }, { "content": "#[test]\n\nfn test_parse_no_function_context() {\n\n let raw = \"\n\n let x = 1\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_err())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 58, "score": 103725.34011552215 }, { "content": "#[test]\n\nfn test_parse_empty_function() {\n\n let raw = \"fn main() {}\";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 59, "score": 103725.34011552215 }, { "content": "#[test]\n\nfn test_simple_nested_expression() {\n\n let raw = \"\n\n fn main() {\n\n let x = (1 + 2 * (3 + 2))\n\n println(x)\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok());\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 60, "score": 103702.17053115895 }, { "content": "#[test]\n\n#[ignore]\n\nfn test_complex_nested_expressions() {\n\n let raw = \"\n\n fn main() {\n\n let year = 2020\n\n \n\n if (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0) {\n\n println('Leap year')\n\n } else {\n\n println('Not a leap year')\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok());\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 61, "score": 103702.0991521173 }, { "content": "fn generate_while_loop(expr: Expression, body: Statement) -> String {\n\n let mut out_str = String::from(\"while (\");\n\n\n\n out_str += &generate_expression(expr);\n\n out_str += \") \";\n\n out_str += &generate_block(body, None);\n\n out_str\n\n}\n\n\n", "file_path": "src/generator/js.rs", "rank": 62, "score": 101702.72674348875 }, { "content": "#[test]\n\nfn test_parse_compound_ops_return() {\n\n let raw = \"\n\n fn main(n: int) {\n\n return 2 * n\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 63, "score": 101463.87685259242 }, { "content": "#[test]\n\nfn test_parse_conditional_else_branch() {\n\n let raw = \"\n\n fn main(n: int) {\n\n if n > 10 {\n\n let x = 2 * n\n\n return x\n\n } else {\n\n return n\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 64, "score": 101421.96890155066 }, { "content": "#[test]\n\nfn test_parse_conditional_else_if_branch() {\n\n let raw = \"\n\n fn main(n: int) {\n\n if n > 10 {\n\n let x = 2 * n\n\n return x\n\n } else if n <= 10 {\n\n return n\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 65, "score": 101421.96890155066 }, { "content": "fn generate_bin_op(left: Expression, op: BinOp, right: Expression) -> String {\n\n let op_str = match op {\n\n BinOp::Addition => \"+\",\n\n BinOp::And => \"&&\",\n\n BinOp::Division => \"/\",\n\n BinOp::Equal => \"==\",\n\n BinOp::GreaterThan => \">\",\n\n BinOp::GreaterThanOrEqual => \">=\",\n\n BinOp::LessThan => \"<\",\n\n BinOp::LessThanOrEqual => \"<=\",\n\n BinOp::AddAssign => \"+=\",\n\n BinOp::SubtractAssign => \"-=\",\n\n BinOp::MultiplyAssign => \"*=\",\n\n BinOp::DivideAssign => \"/=\",\n\n BinOp::Modulus => \"%\",\n\n BinOp::Multiplication => \"*\",\n\n BinOp::NotEqual => \"!=\",\n\n BinOp::Or => \"||\",\n\n BinOp::Subtraction => \"-\",\n\n };\n\n format!(\n\n \"{l} {op} {r}\",\n\n l = generate_expression(left),\n\n op = op_str,\n\n r = generate_expression(right)\n\n )\n\n}\n\n\n", "file_path": "src/generator/c.rs", "rank": 66, "score": 101282.63387226273 }, { "content": "#[test]\n\nfn test_parse_nexted_function_call() {\n\n let raw = \"\n\n fn main() {\n\n fib(fib(2), 2)\n\n }\n\n\n\n fn fib(n: int) {\n\n return 2\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 67, "score": 101076.04425648128 }, { "content": "#[test]\n\nfn test_parse_compound_ops_with_strings() {\n\n let raw = \"\n\n fn main() {\n\n return 2 * \\\"Hello\\\"\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 68, "score": 100729.56286619391 }, { "content": "fn generate_declare(var: Variable, val: Option<Expression>) -> String {\n\n // var is used here to not collide with scopes.\n\n // TODO: Can let be used instead?\n\n match val {\n\n Some(expr) => format!(\n\n \"{} {} = {};\",\n\n generate_type(Either::Left(var.to_owned())),\n\n var.name,\n\n generate_expression(expr)\n\n ),\n\n None => format!(\n\n \"{} {};\",\n\n generate_type(Either::Left(var.to_owned())),\n\n var.name\n\n ),\n\n }\n\n}\n\n\n", "file_path": "src/generator/c.rs", "rank": 69, "score": 100001.49917132567 }, { "content": "fn generate_bin_op(left: Expression, op: BinOp, right: Expression) -> String {\n\n let op_str = match op {\n\n BinOp::Addition => \"+\",\n\n BinOp::And => \"&&\",\n\n BinOp::Division => \"/\",\n\n BinOp::Equal => \"===\",\n\n BinOp::GreaterThan => \">\",\n\n BinOp::GreaterThanOrEqual => \">=\",\n\n BinOp::LessThan => \"<\",\n\n BinOp::LessThanOrEqual => \"<=\",\n\n BinOp::Modulus => \"%\",\n\n BinOp::Multiplication => \"*\",\n\n BinOp::NotEqual => \"!==\",\n\n BinOp::Or => \"||\",\n\n BinOp::Subtraction => \"-\",\n\n BinOp::AddAssign => \"+=\",\n\n BinOp::SubtractAssign => \"-=\",\n\n BinOp::MultiplyAssign => \"*=\",\n\n BinOp::DivideAssign => \"/=\",\n\n };\n\n format!(\n\n \"({l} {op} {r})\",\n\n l = generate_expression(left),\n\n op = op_str,\n\n r = generate_expression(right)\n\n )\n\n}\n\n\n", "file_path": "src/generator/js.rs", "rank": 70, "score": 99369.82498668222 }, { "content": "#[test]\n\nfn test_parse_basic_conditional_with_multiple_statements() {\n\n let raw = \"\n\n fn main(n: int) {\n\n if n {\n\n let x = 2 * n\n\n return x\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 71, "score": 98917.53378766979 }, { "content": "#[test]\n\nfn test_parse_conditional_elseif_else_branch() {\n\n let raw = \"\n\n fn main(n: int) {\n\n if n > 10 {\n\n let x = 2 * n\n\n return x\n\n } else if n < 10 {\n\n return n\n\n } else if n == 10 {\n\n return n + 1\n\n } else {\n\n return n\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 72, "score": 98917.53378766979 }, { "content": "#[test]\n\nfn test_parse_compound_ops_with_function_call() {\n\n let raw = \"\n\n fn main() {\n\n return 2 * fib(1) / 3\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 73, "score": 98582.93277356998 }, { "content": "#[test]\n\nfn test_parse_function_call_multiple_arguments() {\n\n let raw = \"\n\n fn main() {\n\n fib(1, 2, 3)\n\n }\n\n\n\n fn fib() {\n\n return 2\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 74, "score": 98582.93277356998 }, { "content": "#[test]\n\nfn test_parse_conditional_multiple_else_if_branch_branches() {\n\n let raw = \"\n\n fn main(n: int) {\n\n if n > 10 {\n\n let x = 2 * n\n\n return x\n\n } else if n < 10 {\n\n return n\n\n } else if n == 10 {\n\n return n + 1\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 75, "score": 96556.22561600254 }, { "content": "fn infer_function_call(name: &str, table: &SymbolTable) -> Option<Type> {\n\n match table.get(name) {\n\n Some(t) => t.to_owned(),\n\n None => None,\n\n }\n\n}\n", "file_path": "src/parser/infer.rs", "rank": 76, "score": 95392.29099559617 }, { "content": "fn generate_for_loop(ident: Variable, expr: Expression, body: Statement) -> String {\n\n // Assign expression to variable to access it from within the loop\n\n let expr_name = format!(\"loop_orig_{}\", ident.name);\n\n let mut out_str = format!(\"{};\\n\", generate_declare(expr_name.clone(), Some(expr)));\n\n\n\n // Loop signature\n\n out_str += &format!(\n\n \"for (let iter_{I} = 0; iter_{I} < {E}.length; iter_{I}++)\",\n\n I = ident.name,\n\n E = expr_name\n\n );\n\n\n\n // Block with prepended declaration of the actual variable\n\n out_str += &generate_block(\n\n body,\n\n Some(format!(\n\n \"let {I} = {E}[iter_{I}];\\n\",\n\n I = ident.name,\n\n E = expr_name\n\n )),\n\n );\n\n out_str\n\n}\n\n\n", "file_path": "src/generator/js.rs", "rank": 77, "score": 94032.92673038192 }, { "content": "fn main() -> Result<(), String> {\n\n let opts = Opt::from_args();\n\n\n\n match opts {\n\n Opt::Build { in_file, out_file } => command::build::build(&in_file, &out_file)?,\n\n Opt::Run { in_file } => command::run::run(in_file)?,\n\n };\n\n\n\n Ok(())\n\n}\n", "file_path": "src/main.rs", "rank": 78, "score": 91948.893714209 }, { "content": "/// prepend is used to pass optional statements, that will be put in front of the regular block\n\n/// Currently used in for statements, to declare local variables\n\nfn generate_block(block: Statement, prepend: Option<String>) -> String {\n\n let mut generated = String::from(\"{\\n\");\n\n\n\n if let Some(pre) = prepend {\n\n generated += &pre;\n\n }\n\n\n\n // TODO: Prepend statements\n\n let statements = match block {\n\n Statement::Block(blk, _) => blk,\n\n _ => panic!(\"Block body should be of type Statement::Block\"),\n\n };\n\n\n\n for statement in statements {\n\n generated += &generate_statement(statement);\n\n }\n\n\n\n generated += \"}\\n\";\n\n\n\n generated\n\n}\n\n\n", "file_path": "src/generator/js.rs", "rank": 79, "score": 89310.34398292805 }, { "content": "pub trait Generator {\n\n fn generate(prog: Program) -> String;\n\n}\n\n\n\n// Since we're using multiple features,\n\n// \"unreachable\" statements are okay\n", "file_path": "src/generator/mod.rs", "rank": 80, "score": 87585.54676913947 }, { "content": "fn generate_statement(statement: Statement) -> String {\n\n let state = match statement {\n\n Statement::Return(ret) => generate_return(ret),\n\n Statement::Declare(var, val) => generate_declare(var, val),\n\n Statement::Exp(val) => generate_expression(val) + \";\\n\",\n\n Statement::If(expr, if_state, else_state) => {\n\n generate_conditional(expr, *if_state, else_state.map(|x| *x))\n\n }\n\n Statement::Assign(name, state) => generate_assign(*name, *state),\n\n Statement::Block(statements, scope) => generate_block(statements, scope),\n\n Statement::While(expr, body) => generate_while_loop(expr, *body),\n\n Statement::For(_ident, _expr, _body) => todo!(),\n\n Statement::Continue => todo!(),\n\n Statement::Break => todo!(),\n\n };\n\n\n\n format!(\"{}\\n\", state)\n\n}\n\n\n", "file_path": "src/generator/c.rs", "rank": 81, "score": 85215.09340654682 }, { "content": "fn generate_statement(statement: Statement) -> String {\n\n let state = match statement {\n\n Statement::Return(ret) => generate_return(ret),\n\n Statement::Declare(name, val) => generate_declare(name.name, val),\n\n Statement::Exp(val) => generate_expression(val),\n\n Statement::If(expr, if_state, else_state) => {\n\n generate_conditional(expr, *if_state, else_state.map(|x| *x))\n\n }\n\n Statement::Assign(name, state) => generate_assign(*name, *state),\n\n Statement::Block(_, _) => generate_block(statement, None),\n\n Statement::While(expr, body) => generate_while_loop(expr, *body),\n\n Statement::For(ident, expr, body) => generate_for_loop(ident, expr, *body),\n\n Statement::Continue => generate_continue(),\n\n Statement::Break => generate_break(),\n\n };\n\n\n\n format!(\"{};\\n\", state)\n\n}\n\n\n", "file_path": "src/generator/js.rs", "rank": 82, "score": 83377.23158063437 }, { "content": "#[test]\n\nfn test_basic_while_loop() {\n\n let raw = \"\n\n fn main() {\n\n let x = 5 * 2\n\n while x > 0 {\n\n return x\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 83, "score": 76909.80625943144 }, { "content": "#[test]\n\nfn test_typed_declare() {\n\n let raw = \"\n\n fn main() {\n\n let x = 5\n\n let y: int = 1\n\n let z: bool = false\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 84, "score": 76909.80625943144 }, { "content": "#[test]\n\nfn test_nested_array() {\n\n let raw = \"\n\n fn main() {\n\n\n\n let arr = [[11, 12, 13], [21, 22, 23], [31, 32, 33]]\n\n for i in arr {\n\n for j in i {\n\n println(j)\n\n }\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok());\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 85, "score": 76909.80625943144 }, { "content": "#[test]\n\nfn test_nested_for_loop() {\n\n let raw = \"\n\n fn main() {\n\n let x = [1, 2, 3]\n\n\n\n for i in x {\n\n for j in x {\n\n _printf(j)\n\n }\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok());\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 86, "score": 76909.80625943144 }, { "content": "#[test]\n\nfn test_simple_for_loop() {\n\n let raw = \"\n\n fn main() {\n\n let x = [1, 2, 3]\n\n\n\n for i in x {\n\n _printf(i)\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok());\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 87, "score": 76909.80625943144 }, { "content": "#[test]\n\nfn test_array_as_argument() {\n\n let raw = \"\n\n fn main() {\n\n println([1, 2, 3])\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok());\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 88, "score": 76909.80625943144 }, { "content": "#[test]\n\nfn test_uninitialized_variables() {\n\n let raw = \"\n\n fn main() {\n\n let x\n\n let y\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 89, "score": 76909.80625943144 }, { "content": "#[test]\n\nfn test_array_access_in_if() {\n\n let raw = \"\n\n fn main() {\n\n if arr[d] > arr[d+1] {\n\n let swap = arr[d]\n\n arr[d] = arr[d+1]\n\n arr[d+1] = swap\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 90, "score": 76909.80625943144 }, { "content": "#[test]\n\nfn test_generate_type_regular_type() {\n\n let t = generate_type(Either::Right(Some(Type::Int)));\n\n assert_eq!(t, \"int\")\n\n}\n", "file_path": "src/generator/tests/c_tests.rs", "rank": 91, "score": 76215.80733842378 }, { "content": "#[test]\n\nfn test_testcases() -> Result<(), Error> {\n\n test_directory(\"tests\")?;\n\n Ok(())\n\n}\n", "file_path": "src/tests/test_examples.rs", "rank": 92, "score": 75390.22268007287 }, { "content": "#[test]\n\nfn test_examples() -> Result<(), Error> {\n\n test_directory(\"examples\")?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/tests/test_examples.rs", "rank": 93, "score": 75390.22268007287 }, { "content": "#[test]\n\nfn test_array_access_in_loop() {\n\n let raw = \"\n\n fn main() {\n\n let x = [1, 2, 3, 4, 5]\n\n \n\n let i = 0\n\n \n\n while i < 5 {\n\n println(x[i])\n\n i += 1\n\n }\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 94, "score": 75126.76796443132 }, { "content": "#[test]\n\nfn test_array_access_standalone() {\n\n let raw = \"\n\n fn main() {\n\n let x = [1, 2, 3, 4, 5]\n\n \n\n x[0]\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 95, "score": 75126.76796443132 }, { "content": "#[test]\n\nfn test_parse_variable_reassignment() {\n\n let raw = \"\n\n fn main() {\n\n let x = 1\n\n x = x + 1\n\n return x\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 96, "score": 75126.76796443132 }, { "content": "#[test]\n\nfn test_parse_compound_ops() {\n\n let raw = \"\n\n fn main() {\n\n 2 * 5 / 3\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 97, "score": 75126.76796443132 }, { "content": "#[test]\n\nfn test_parse_variable_declaration() {\n\n let raw = \"\n\n fn main() {\n\n let x = 1\n\n return x\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 98, "score": 75126.76796443132 }, { "content": "#[test]\n\nfn test_parse_basic_ops() {\n\n let raw = \"\n\n fn main() {\n\n return 2 * 5\n\n }\n\n \";\n\n let tokens = tokenize(raw);\n\n let tree = parse(tokens, Some(raw.to_string()));\n\n assert!(tree.is_ok())\n\n}\n\n\n", "file_path": "src/parser/tests.rs", "rank": 99, "score": 75126.76796443132 } ]
Rust
examples/binance_websockets.rs
vikulikov/binance-rs-async
40c0907e67d629d135dea562f56e5629e5046143
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::RwLock; use futures::stream::StreamExt; use serde_json::from_str; use tokio_tungstenite::tungstenite::Message; use binance::api::*; use binance::userstream::*; use binance::websockets::*; use binance::ws_model::{CombinedStreamEvent, WebsocketEvent, WebsocketEventUntag}; #[tokio::main] async fn main() { combined_orderbook().await; } #[allow(dead_code)] async fn user_stream() { let api_key_user = Some("YOUR_API_KEY".into()); let user_stream: UserStream = Binance::new(api_key_user.clone(), None); if let Ok(answer) = user_stream.start().await { println!("Data Stream Started ..."); let listen_key = answer.listen_key; match user_stream.keep_alive(&listen_key).await { Ok(msg) => println!("Keepalive user data stream: {:?}", msg), Err(e) => println!("Error: {}", e), } match user_stream.close(&listen_key).await { Ok(msg) => println!("Close user data stream: {:?}", msg), Err(e) => println!("Error: {}", e), } } else { println!("Not able to start an User Stream (Check your API_KEY)"); } } #[allow(dead_code)] async fn user_stream_websocket<F>() { let keep_running = AtomicBool::new(true); let api_key_user = Some("YOUR_KEY".into()); let user_stream: UserStream = Binance::new(api_key_user, None); if let Ok(answer) = user_stream.start().await { let listen_key = answer.listen_key; let mut web_socket: WebSockets<'_, WebsocketEvent> = WebSockets::new(|event: WebsocketEvent| { if let WebsocketEvent::OrderUpdate(trade) = event { println!( "Symbol: {}, Side: {:?}, Price: {}, Execution Type: {:?}", trade.symbol, trade.side, trade.price, trade.execution_type ); }; Ok(()) }); web_socket.connect(&listen_key).await.unwrap(); if let Err(e) = web_socket.event_loop(&keep_running).await { println!("Error: {}", e); } user_stream.close(&listen_key).await.unwrap(); web_socket.disconnect().await.unwrap(); println!("Userstrem closed and disconnected"); } else { println!("Not able to start an User Stream (Check your API_KEY)"); } } #[allow(dead_code)] async fn market_websocket() { let keep_running = AtomicBool::new(true); let agg_trade: String = agg_trade_stream("ethbtc"); let mut web_socket: WebSockets<'_, WebsocketEvent> = WebSockets::new(|event: WebsocketEvent| { match event { WebsocketEvent::Trade(trade) => { println!("Symbol: {}, price: {}, qty: {}", trade.symbol, trade.price, trade.qty); } WebsocketEvent::DepthOrderBook(depth_order_book) => { println!( "Symbol: {}, Bids: {:?}, Ask: {:?}", depth_order_book.symbol, depth_order_book.bids, depth_order_book.asks ); } _ => (), }; Ok(()) }); web_socket.connect(&agg_trade).await.unwrap(); if let Err(e) = web_socket.event_loop(&keep_running).await { println!("Error: {}", e); } web_socket.disconnect().await.unwrap(); println!("disconnected"); } #[allow(dead_code)] async fn all_trades_websocket() { let keep_running = AtomicBool::new(true); let agg_trade = all_ticker_stream(); let mut web_socket: WebSockets<'_, Vec<WebsocketEvent>> = WebSockets::new(|events: Vec<WebsocketEvent>| { for tick_events in events { if let WebsocketEvent::DayTicker(tick_event) = tick_events { println!( "Symbol: {}, price: {}, qty: {}", tick_event.symbol, tick_event.best_bid, tick_event.best_bid_qty ); } } Ok(()) }); web_socket.connect(agg_trade).await.unwrap(); if let Err(e) = web_socket.event_loop(&keep_running).await { println!("Error: {}", e); } web_socket.disconnect().await.unwrap(); println!("disconnected"); } #[allow(dead_code)] async fn kline_websocket() { let keep_running = AtomicBool::new(true); let kline = kline_stream("ethbtc", "1m"); let mut web_socket: WebSockets<'_, WebsocketEvent> = WebSockets::new(|event: WebsocketEvent| { if let WebsocketEvent::Kline(kline_event) = event { println!( "Symbol: {}, high: {}, low: {}", kline_event.kline.symbol, kline_event.kline.low, kline_event.kline.high ); } Ok(()) }); web_socket.connect(&kline).await.unwrap(); if let Err(e) = web_socket.event_loop(&keep_running).await { println!("Error: {}", e); } web_socket.disconnect().await.unwrap(); println!("disconnected"); } #[allow(dead_code)] async fn last_price() { let keep_running = AtomicBool::new(true); let all_ticker = all_ticker_stream(); let btcusdt: RwLock<f32> = RwLock::new("0".parse().unwrap()); let mut web_socket: WebSockets<'_, Vec<WebsocketEvent>> = WebSockets::new(|events: Vec<WebsocketEvent>| { for tick_events in events { if let WebsocketEvent::DayTicker(tick_event) = tick_events { if tick_event.symbol == "BTCUSDT" { let mut btcusdt = btcusdt.write().unwrap(); *btcusdt = tick_event.average_price.parse::<f32>().unwrap(); let btcusdt_close: f32 = tick_event.current_close.parse().unwrap(); println!("{} - {}", btcusdt, btcusdt_close); if btcusdt_close as i32 == 7000 { keep_running.store(false, Ordering::Relaxed); } } } } Ok(()) }); web_socket.connect(all_ticker).await.unwrap(); if let Err(e) = web_socket.event_loop(&keep_running).await { println!("Error: {}", e); } web_socket.disconnect().await.unwrap(); println!("disconnected"); } #[allow(dead_code)] async fn book_ticker() { let keep_running = AtomicBool::new(true); let book_ticker: String = book_ticker_stream("btcusdt"); let mut web_socket: WebSockets<'_, WebsocketEventUntag> = WebSockets::new(|events: WebsocketEventUntag| { if let WebsocketEventUntag::BookTicker(tick_event) = events { println!("{:?}", tick_event) } Ok(()) }); web_socket.connect(&book_ticker).await.unwrap(); if let Err(e) = web_socket.event_loop(&keep_running).await { println!("Error: {}", e); } web_socket.disconnect().await.unwrap(); println!("disconnected"); } #[allow(dead_code)] async fn combined_orderbook() { let keep_running = AtomicBool::new(true); let streams: Vec<String> = vec!["btcusdt", "ethusdt"] .into_iter() .map(|symbol| partial_book_depth_stream(symbol, 5, 1000)) .collect(); let mut web_socket: WebSockets<'_, CombinedStreamEvent<_>> = WebSockets::new(|event: CombinedStreamEvent<WebsocketEventUntag>| { let data = event.data; if let WebsocketEventUntag::Orderbook(orderbook) = data { println!("{:?}", orderbook) } Ok(()) }); web_socket.connect_multiple(streams).await.unwrap(); if let Err(e) = web_socket.event_loop(&keep_running).await { println!("Error: {}", e); } web_socket.disconnect().await.unwrap(); println!("disconnected"); } #[allow(dead_code)] async fn custom_event_loop() { let streams: Vec<String> = vec!["btcusdt", "ethusdt"] .into_iter() .map(|symbol| partial_book_depth_stream(symbol, 5, 1000)) .collect(); let mut web_socket: WebSockets<'_, CombinedStreamEvent<_>> = WebSockets::new(|event: CombinedStreamEvent<WebsocketEventUntag>| { let data = event.data; if let WebsocketEventUntag::Orderbook(orderbook) = data { println!("{:?}", orderbook) } Ok(()) }); web_socket.connect_multiple(streams).await.unwrap(); loop { if let Some((ref mut socket, _)) = web_socket.socket { if let Ok(message) = socket.next().await.unwrap() { match message { Message::Text(msg) => { if msg.is_empty() { continue; } let event: CombinedStreamEvent<WebsocketEventUntag> = from_str(msg.as_str()).unwrap(); eprintln!("event = {:?}", event); } Message::Ping(_) | Message::Pong(_) | Message::Binary(_) => {} Message::Close(e) => { eprintln!("closed stream = {:?}", e); break; } } } } } }
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::RwLock; use futures::stream::StreamExt; use serde_json::from_str; use tokio_tungstenite::tungstenite::Message; use binance::api::*; use binance::userstream::*; use binance::websockets::*; use binance::ws_model::{CombinedStreamEvent, WebsocketEvent, WebsocketEventUntag}; #[tokio::main] async fn main() { combined_orderbook().await; } #[allow(dead_code)] async fn user_stream() { let api_key_user = Some("YOUR_API_KEY".into()); let user_stream: UserStream = Binance::new(api_key_user.clone(), None); if let Ok(answer) = user_stream.start().await { println!("Data Stream Started ..."); let listen_key = answer.listen_key; match user_stream.keep_alive(&listen_key).await { Ok(msg) => println!("Keepalive user data stream: {:?}", msg), Err(e) => println!("Error: {}", e), } match user_stream.close(&listen_key).await { Ok(msg) => println!("Close user data stream: {:?}", msg), Err(e) => println!("Error: {}", e), } } else { println!("Not able to start an User Stream (Check your API_KEY)"); } } #[allow(dead_code)] async fn user_stream_websocket<F>() { let keep_running = AtomicBool::new(true); let api_key_user = Some("YOUR_KEY".into()); let user_stream: UserStream = Binance::new(api_key_user, None); if let Ok(answer) = user_stream.start().await { let listen_key = answer.listen_key; let mut web_socket: WebSockets<'_, WebsocketEvent> = WebSockets::new(|event: WebsocketEvent| { if let WebsocketEvent::OrderUpdate(trade) = event { println!( "Symbol: {}, Side: {:?}, Price: {}, Execution Type: {:?}", trade.symbol, trade.side, trade.price, trade.execution_type ); }; Ok(()) }); web_socket.connect(&listen_key).await.unwrap(); if let Err(e) = web_socket.event_loop(&keep_running).await { println!("Error: {}", e); } user_stream.close(&listen_key).await.unwrap(); web_socket.disconnect().await.unwrap(); println!("Userstrem closed and disconnected"); } else { println!("Not able to start an User Stream (Check your API_KEY)"); } } #[allow(dead_code)] async fn market_websocket() { let keep_running = AtomicBool::new(true); let agg_trade: String = agg_trade_stream("ethbtc"); let mut web_socket: WebSockets<'_, WebsocketEvent> = WebSockets::new(|event: WebsocketEvent| { match event { WebsocketEvent::Trade(trade) => { println!("Symbol: {}, price: {}, qty: {}", trade.symbol, trade.price, trade.qty); } WebsocketEvent::DepthOrderBook(depth_order_book) => { println!( "Symbol: {}, Bids: {:?}, Ask: {:?}", depth_order_book.symbol, depth_order_book.bids, depth_order_book.asks ); } _ => (), }; Ok(()) }); web_socket.connect(&agg_trade).await.unwrap(); if let Err(e) = web_socket.event_loop(&keep_running).await { println!("Error: {}", e); } web_socket.disconnect().await.unwrap(); println!("disconnected"); } #[allow(dead_code)] async fn all_trades_websocket() { let keep_running = AtomicBool::new(true); let agg_trade = all_ticker_stream(); let mut web_socket: WebSockets<'_, Vec<WebsocketEvent>> = WebSockets::new(|events: Vec<WebsocketEvent>| { for tick_events in events { if let WebsocketEvent::DayTicker(tick_event) = tick_events { println!( "Symbol: {}, price: {}, qty: {}", tick_event.symbol, tick_event.best_bid, tick_event.best_bid_qty ); } } Ok(()) }); web_socket.connect(agg_trade).await.unwrap(); if let Err(e) = web_socket.event_loop(&keep_running).await { println!("Error: {}", e); } web_socket.disconnect().await.unwrap(); println!("disconnected"); } #[allow(dead_code)] async fn kline_websocket() { let keep_running = AtomicBool::new(true); let kline = kline_stream("ethbtc", "1m"); let mut web_socket: WebSockets<'_, WebsocketEvent> = WebSockets::new(|event: WebsocketEvent| { if let WebsocketEvent::Kline(kline_event) = event { println!( "Symbol: {}, high: {}, low: {}", kline_event.kline.symbol, kline_event.kline.low, kline_event.kline.high ); } Ok(()) }); web_socket.connect(&kline).await.unwrap(); if let Err(e) = web_socket.event_loop(&keep_running).await { println!("Error: {}", e); } web_socket.disconnect().await.unwrap(); println!("disconnected"); } #[allow(dead_code)] async fn last_price() { let keep_running = AtomicBool::new(true); let all_ticker = all_ticker_stream(); let btcusdt: RwLock<f32> = RwLock::new("0".parse().unwrap()); let mut web_socket: WebSockets<'_, Vec<WebsocketEvent>> = WebSockets::new(|events: Vec<WebsocketEvent>| { for tick_events in events { if let WebsocketEvent::DayTicker(tick_event) = tick_events { if tick_event.symbol == "BTCUSDT" { let mut btcusdt = btcusdt.write().unwrap(); *btcusdt = tick_event.average_price.parse::<f32>().unwrap(); let btcusdt_close: f32 = tick_event.current_close.parse().unwrap(); println!("{} - {}", btcusdt, btcusdt_close); if btcusdt_close as i32 == 7000 { keep_running.store(false, Ordering::Relaxed); } } } } Ok(()) }); web_socket.connect(all_ticker).await.unwrap(); if let Err(e) = web_socket.event_loop(&keep_running).await { println!("Error: {}", e); } web_socket.disconnect().await.unwrap(); println!("disconnected"); } #[allow(dead_code)] async fn book_ticker() { let keep_running = AtomicBool::new(true); let book_ticker: String = book_ticker_stream("btcusd
=> { if msg.is_empty() { continue; } let event: CombinedStreamEvent<WebsocketEventUntag> = from_str(msg.as_str()).unwrap(); eprintln!("event = {:?}", event); } Message::Ping(_) | Message::Pong(_) | Message::Binary(_) => {} Message::Close(e) => { eprintln!("closed stream = {:?}", e); break; } } } } } }
t"); let mut web_socket: WebSockets<'_, WebsocketEventUntag> = WebSockets::new(|events: WebsocketEventUntag| { if let WebsocketEventUntag::BookTicker(tick_event) = events { println!("{:?}", tick_event) } Ok(()) }); web_socket.connect(&book_ticker).await.unwrap(); if let Err(e) = web_socket.event_loop(&keep_running).await { println!("Error: {}", e); } web_socket.disconnect().await.unwrap(); println!("disconnected"); } #[allow(dead_code)] async fn combined_orderbook() { let keep_running = AtomicBool::new(true); let streams: Vec<String> = vec!["btcusdt", "ethusdt"] .into_iter() .map(|symbol| partial_book_depth_stream(symbol, 5, 1000)) .collect(); let mut web_socket: WebSockets<'_, CombinedStreamEvent<_>> = WebSockets::new(|event: CombinedStreamEvent<WebsocketEventUntag>| { let data = event.data; if let WebsocketEventUntag::Orderbook(orderbook) = data { println!("{:?}", orderbook) } Ok(()) }); web_socket.connect_multiple(streams).await.unwrap(); if let Err(e) = web_socket.event_loop(&keep_running).await { println!("Error: {}", e); } web_socket.disconnect().await.unwrap(); println!("disconnected"); } #[allow(dead_code)] async fn custom_event_loop() { let streams: Vec<String> = vec!["btcusdt", "ethusdt"] .into_iter() .map(|symbol| partial_book_depth_stream(symbol, 5, 1000)) .collect(); let mut web_socket: WebSockets<'_, CombinedStreamEvent<_>> = WebSockets::new(|event: CombinedStreamEvent<WebsocketEventUntag>| { let data = event.data; if let WebsocketEventUntag::Orderbook(orderbook) = data { println!("{:?}", orderbook) } Ok(()) }); web_socket.connect_multiple(streams).await.unwrap(); loop { if let Some((ref mut socket, _)) = web_socket.socket { if let Ok(message) = socket.next().await.unwrap() { match message { Message::Text(msg)
random
[ { "content": "pub fn kline_stream(symbol: &str, interval: &str) -> String { format!(\"{}@kline_{}\", symbol, interval) }\n\n\n", "file_path": "src/websockets.rs", "rank": 0, "score": 149192.0712904504 }, { "content": "pub fn trade_stream(symbol: &str) -> String { format!(\"{}@trade\", symbol) }\n\n\n", "file_path": "src/websockets.rs", "rank": 1, "score": 134450.03846242192 }, { "content": "pub fn ticker_stream(symbol: &str) -> String { format!(\"{}@ticker\", symbol) }\n\n\n", "file_path": "src/websockets.rs", "rank": 2, "score": 134450.03846242192 }, { "content": "pub fn agg_trade_stream(symbol: &str) -> String { format!(\"{}@aggTrade\", symbol) }\n\n\n", "file_path": "src/websockets.rs", "rank": 3, "score": 127840.06118830449 }, { "content": "pub fn mini_ticker_stream(symbol: &str) -> String { format!(\"{}@miniTicker\", symbol) }\n\n\n", "file_path": "src/websockets.rs", "rank": 4, "score": 127840.06118830449 }, { "content": "pub fn book_ticker_stream(symbol: &str) -> String { format!(\"{}@bookTicker\", symbol) }\n\n\n", "file_path": "src/websockets.rs", "rank": 5, "score": 127840.06118830449 }, { "content": "fn combined_stream(streams: Vec<String>) -> String { streams.join(\"/\") }\n\n\n\npub struct WebSockets<'a, WE> {\n\n pub socket: Option<(WebSocketStream<MaybeTlsStream<TcpStream>>, Response)>,\n\n handler: Box<dyn FnMut(WE) -> Result<()> + 'a>,\n\n conf: Config,\n\n}\n\n\n\nimpl<'a, WE: serde::de::DeserializeOwned> WebSockets<'a, WE> {\n\n /// New websocket holder with default configuration\n\n /// # Examples\n\n /// see examples/binance_websockets.rs\n\n pub fn new<Callback>(handler: Callback) -> WebSockets<'a, WE>\n\n where\n\n Callback: FnMut(WE) -> Result<()> + 'a,\n\n {\n\n Self::new_with_options(handler, Config::default())\n\n }\n\n\n\n /// New websocket holder with provided configuration\n", "file_path": "src/websockets.rs", "rank": 6, "score": 124565.5835450191 }, { "content": "/// # Arguments\n\n///\n\n/// * `symbol`: the market symbol\n\n/// * `update_speed`: 1000 or 100\n\npub fn diff_book_depth_stream(symbol: &str, update_speed: u16) -> String {\n\n format!(\"{}@depth@{}ms\", symbol, update_speed)\n\n}\n\n\n", "file_path": "src/websockets.rs", "rank": 7, "score": 114140.22304253995 }, { "content": "/// # Arguments\n\n///\n\n/// * `symbol`: the market symbol\n\n/// * `levels`: 5, 10 or 20\n\n/// * `update_speed`: 1000 or 100\n\npub fn partial_book_depth_stream(symbol: &str, levels: u16, update_speed: u16) -> String {\n\n format!(\"{}@depth{}@{}ms\", symbol, levels, update_speed)\n\n}\n\n\n", "file_path": "src/websockets.rs", "rank": 8, "score": 104094.16368451322 }, { "content": "pub fn build_signed_request(mut parameters: BTreeMap<String, String>, recv_window: u64) -> Result<String> {\n\n if recv_window > 0 {\n\n parameters.insert(\"recvWindow\".into(), recv_window.to_string());\n\n }\n\n\n\n if let Ok(timestamp) = get_timestamp() {\n\n parameters.insert(\"timestamp\".into(), timestamp.to_string());\n\n\n\n let mut request = String::new();\n\n for (key, value) in &parameters {\n\n let param = format!(\"{}={}&\", key, value);\n\n request.push_str(param.as_ref());\n\n }\n\n request.pop(); // remove last &\n\n\n\n Ok(request)\n\n } else {\n\n Err(Error::Msg(\"Failed to get timestamp\".to_string()))\n\n }\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 9, "score": 100674.01449022826 }, { "content": "pub fn build_request(parameters: &BTreeMap<String, String>) -> String {\n\n let mut request = String::new();\n\n for (key, value) in parameters {\n\n let param = format!(\"{}={}&\", key, value);\n\n request.push_str(param.as_ref());\n\n }\n\n request.pop(); // remove last &\n\n\n\n request\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 10, "score": 89462.82214642549 }, { "content": "pub fn bool_to_string(b: bool) -> String {\n\n if b {\n\n TRUE.to_string()\n\n } else {\n\n FALSE.to_string()\n\n }\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 11, "score": 87432.9073921167 }, { "content": "pub fn bool_to_string_some(b: bool) -> Option<String> { Some(bool_to_string(b)) }\n", "file_path": "src/util.rs", "rank": 12, "score": 79669.30439322177 }, { "content": "pub fn all_ticker_stream() -> &'static str { \"!ticker@arr\" }\n\n\n", "file_path": "src/websockets.rs", "rank": 13, "score": 71175.26057629536 }, { "content": "pub fn build_request_p<S>(payload: S) -> Result<String>\n\nwhere\n\n S: serde::Serialize,\n\n{\n\n Ok(qs::to_string(&payload)?)\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 14, "score": 66785.7809411505 }, { "content": "pub fn all_book_ticker_stream() -> &'static str { \"!bookTicker\" }\n\n\n", "file_path": "src/websockets.rs", "rank": 15, "score": 58723.86396751041 }, { "content": "pub fn get_timestamp() -> Result<u64> { Ok(Utc::now().timestamp_millis() as u64) }\n\n\n\nlazy_static! {\n\n static ref TRUE: String = \"TRUE\".to_string();\n\n}\n\nlazy_static! {\n\n static ref FALSE: String = \"FALSE\".to_string();\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 16, "score": 58110.071293384244 }, { "content": "pub fn build_signed_request_p<S>(payload: S, recv_window: u64) -> Result<String>\n\nwhere\n\n S: serde::Serialize,\n\n{\n\n let query_string = qs::to_string(&payload)?;\n\n let mut parameters: BTreeMap<String, String> = BTreeMap::new();\n\n\n\n if recv_window > 0 {\n\n parameters.insert(\"recvWindow\".into(), recv_window.to_string());\n\n }\n\n\n\n if let Ok(timestamp) = get_timestamp() {\n\n parameters.insert(\"timestamp\".into(), timestamp.to_string());\n\n\n\n let mut request = query_string;\n\n for (key, value) in &parameters {\n\n let param = format!(\"&{}={}\", key, value);\n\n request.push_str(param.as_ref());\n\n }\n\n if let Some('&') = request.chars().last() {\n\n request.pop(); // remove last &\n\n }\n\n\n\n Ok(request)\n\n } else {\n\n Err(Error::Msg(\"Failed to get timestamp\".to_string()))\n\n }\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 17, "score": 57369.98528983432 }, { "content": "pub fn all_mini_ticker_stream() -> &'static str { \"!miniTicker@arr\" }\n\n\n", "file_path": "src/websockets.rs", "rank": 18, "score": 55803.704437581226 }, { "content": "/// Serialize bool as str\n\nfn serialize_as_str<S, T>(t: &T, serializer: S) -> std::result::Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n T: fmt::Display,\n\n{\n\n serializer.collect_str(t)\n\n}\n\n\n", "file_path": "src/futures/account.rs", "rank": 19, "score": 49379.54479825067 }, { "content": "/// Serialize opt bool as str\n\nfn serialize_opt_as_uppercase<S, T>(t: &Option<T>, serializer: S) -> std::result::Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n T: ToString,\n\n{\n\n match *t {\n\n Some(ref v) => serializer.serialize_some(&v.to_string().to_uppercase()),\n\n None => serializer.serialize_none(),\n\n }\n\n}\n\n\n", "file_path": "src/futures/account.rs", "rank": 20, "score": 46565.202181082714 }, { "content": "pub fn to_i64(v: &Value) -> i64 { v.as_i64().unwrap() }\n\n\n", "file_path": "src/util.rs", "rank": 21, "score": 35214.964226573604 }, { "content": " /// ```\n\n pub async fn keep_alive(&self, listen_key: &str) -> Result<Success> {\n\n let data = self.client.put(USER_DATA_STREAM, listen_key).await?;\n\n\n\n let success: Success = from_str(data.as_str())?;\n\n\n\n Ok(success)\n\n }\n\n\n\n /// Invalidate the listen key\n\n /// # Examples\n\n /// ```rust,no_run\n\n /// use binance::{api::*, userstream::*, config::*};\n\n /// let userstream: UserStream = Binance::new_with_env(&Config::testnet());\n\n /// let start = tokio_test::block_on(userstream.start());\n\n /// assert!(start.is_ok(), \"{:?}\", start);\n\n /// let close = tokio_test::block_on(userstream.close(&start.unwrap().listen_key));\n\n /// assert!(close.is_ok())\n\n /// ```\n\n pub async fn close(&self, listen_key: &str) -> Result<Success> {\n\n let data = self.client.delete(USER_DATA_STREAM, listen_key).await?;\n\n\n\n let success: Success = from_str(data.as_str())?;\n\n\n\n Ok(success)\n\n }\n\n}\n", "file_path": "src/userstream.rs", "rank": 22, "score": 34912.23106934624 }, { "content": " /// let start = tokio_test::block_on(userstream.start());\n\n /// assert!(start.is_ok(), \"{:?}\", start);\n\n /// assert!(start.unwrap().listen_key.len() > 0)\n\n /// ```\n\n pub async fn start(&self) -> Result<UserDataStream> {\n\n let data = self.client.post(USER_DATA_STREAM).await?;\n\n let user_data_stream: UserDataStream = from_str(data.as_str())?;\n\n\n\n Ok(user_data_stream)\n\n }\n\n\n\n /// Keep the connection alive, as the listen key becomes invalid after 60mn\n\n /// # Examples\n\n /// ```rust,no_run\n\n /// use binance::{api::*, userstream::*, config::*};\n\n /// let userstream: UserStream = Binance::new_with_env(&Config::testnet());\n\n /// let start = tokio_test::block_on(userstream.start());\n\n /// assert!(start.is_ok(), \"{:?}\", start);\n\n /// let keep_alive = tokio_test::block_on(userstream.keep_alive(&start.unwrap().listen_key));\n\n /// assert!(keep_alive.is_ok())\n", "file_path": "src/userstream.rs", "rank": 23, "score": 34910.06228672094 }, { "content": "use serde_json::from_str;\n\n\n\nuse crate::client::*;\n\nuse crate::errors::*;\n\nuse crate::rest_model::*;\n\n\n\nstatic USER_DATA_STREAM: &str = \"/api/v3/userDataStream\";\n\n\n\n#[derive(Clone)]\n\npub struct UserStream {\n\n pub client: Client,\n\n pub recv_window: u64,\n\n}\n\n\n\nimpl UserStream {\n\n /// Get a listen key for the stream\n\n /// # Examples\n\n /// ```rust,no_run\n\n /// use binance::{api::*, userstream::*, config::*};\n\n /// let userstream: UserStream = Binance::new_with_env(&Config::testnet());\n", "file_path": "src/userstream.rs", "rank": 24, "score": 34900.84247199294 }, { "content": "fn handle_content_error(error: BinanceContentError) -> crate::errors::Error {\n\n match (error.code, error.msg.as_ref()) {\n\n (-1013, error_messages::INVALID_PRICE) => Error::InvalidPrice,\n\n (-1125, msg) => Error::InvalidListenKey(msg.to_string()),\n\n _ => Error::BinanceError { response: error },\n\n }\n\n}\n", "file_path": "src/client.rs", "rank": 25, "score": 32330.925224490533 }, { "content": "pub fn to_f64(v: &Value) -> f64 { v.as_str().unwrap().parse().unwrap() }\n\n\n", "file_path": "src/util.rs", "rank": 26, "score": 31737.79845106304 }, { "content": "#[derive(Serialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct OrderRequest {\n\n pub symbol: String,\n\n pub side: OrderSide,\n\n pub position_side: Option<PositionSide>,\n\n #[serde(rename = \"type\")]\n\n pub order_type: OrderType,\n\n pub time_in_force: Option<TimeInForce>,\n\n #[serde(rename = \"quantity\")]\n\n pub qty: Option<f64>,\n\n pub reduce_only: Option<bool>,\n\n pub price: Option<f64>,\n\n pub stop_price: Option<f64>,\n\n pub close_position: Option<bool>,\n\n pub activation_price: Option<f64>,\n\n pub callback_rate: Option<f64>,\n\n pub working_type: Option<WorkingType>,\n\n #[serde(serialize_with = \"serialize_opt_as_uppercase\")]\n\n pub price_protect: Option<bool>,\n\n}\n\n\n", "file_path": "src/futures/account.rs", "rank": 27, "score": 29631.011982721095 }, { "content": "# binance-rs-async\n\n\n\nUnofficial Rust Library for the [Binance API](https://github.com/binance-exchange/binance-official-api-docs)\n\n\n\nThis is a fully async api using [async-std](https://docs.rs/async-std/1.5.0/async_std/).\n\n\n\n## Current state\n\n\n\nThe current beta aims at implementing every single endpoint on the binance docs. Currently, futures and savings have\n\nbeen implemented but not thoroughly tested.\n\n\n\n## Usage\n\n\n\nAdd this to your Cargo.toml\n\n\n\n```toml\n\n[dependencies]\n\nbinance-rs-async = \"1.1.0\"\n\n```\n\n\n\n## Roadmap\n\n\n\n- 1.0.0 Completely tested margin sapi endpoints\n\n- 1.0.1 Changelog check to detect binance API changes\n\n- 1.1.0 Complete tested futures (m-coin and usd-m futures)\n\n\n\n## Risk Warning\n\n\n\nIt is a personal project, use at your own risk. I will not be responsible for your investment losses. Cryptocurrency\n\ninvestment is subject to high market risk. Nonetheless, this crate is aimed at high performance and production use, I\n\nhave been using this to target Binance successfully for several years now.\n\n\n\n### Using TLS\n\n\n\nBy default, the crate uses `native-tls` for tungstenite and reqwest because I believe it's simpler and faster to let the\n\nuser switch LibreSSL or OpenSSL versions rather than rebuild the program.\n\n\n\nYou can however disable default-features and use `rust-tls`, which might be helpful in certain situations such as CI or\n\ndev box.\n\n\n\n## Rust >= 1.37\n\n\n\n```rust\n\nrustup install stable\n\n```\n\n\n\n## Contribution\n\n\n\nSimply create a pull request. Properly documented code and tests (using binance testnet) are a must.\n", "file_path": "README.md", "rank": 28, "score": 20208.96098443495 }, { "content": "### Get force liquidation record (USER_DATA)\n\n```\n\nGet /sapi/v1/margin/forceLiquidationRec\n\n```\n\n\n\n**Weight:**s\n\n5\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nstartTime | LONG |\tNO\t\n\nendTime | LONG | NO\t\n\ncurrent | LONG | NO | Currently querying page. Start from 1. Default:1\n\nsize |\tLONG | NO |\tDefault:10 Max:100\n\nrecvWindow | LONG | NO | The value cannot be greater than ```60000```\n\ntimestamp | LONG | YES\n\n\n\n\n\n**Response:**\n\n\n\n```javascript\n\n {\n\n \"rows\": [\n\n {\n\n \"avgPrice\": \"0.00388359\",\n\n \"executedQty\": \"31.39000000\",\n\n \"orderId\": 180015097,\n\n \"price\": \"0.00388110\",\n\n \"qty\": \"31.39000000\",\n\n \"side\": \"SELL\",\n\n \"symbol\": \"BNBBTC\",\n\n \"timeInForce\": \"GTC\",\n\n \"updatedTime\": 1558941374745\n\n }\n\n ],\n\n \"total\": 1\n\n }\n\n```\n\n\n\n\n\n\n\n### Query margin account's order (USER_DATA)\n\n\n\n```\n\nGet /sapi/v1/margin/order \n\n```\n\n\n\n**Weight:**\n\n5\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nsymbol | STRING | YES |\n\norderId | STRING | NO |\t\n\norigClientOrderId | STRING | NO\t|\n\nrecvWindow | LONG | NO\n\ntimestamp | LONG | YES\n\n\n\nNotes:\n\n\n\n* Either orderId or origClientOrderId must be sent.\n\n* For some historical orders cummulativeQuoteQty will be < 0, meaning the data is not available at this time.\n\n\n\n**Response:**\n\n```javascript\n\n{\n\n \"clientOrderId\": \"ZwfQzuDIGpceVhKW5DvCmO\",\n\n \"cummulativeQuoteQty\": \"0.00000000\",\n\n \"executedQty\": \"0.00000000\",\n\n \"icebergQty\": \"0.00000000\",\n\n \"isWorking\": true,\n\n \"orderId\": 213205622,\n\n \"origQty\": \"0.30000000\",\n\n \"price\": \"0.00493630\",\n\n \"side\": \"SELL\",\n\n \"status\": \"NEW\",\n\n \"stopPrice\": \"0.00000000\",\n\n \"symbol\": \"BNBBTC\",\n\n \"time\": 1562133008725,\n\n \"timeInForce\": \"GTC\",\n\n \"type\": \"LIMIT\",\n\n \"updateTime\": 1562133008725\n\n}\n\n```\n\n\n", "file_path": "docs/margin.md", "rank": 29, "score": 19548.12675361482 }, { "content": "### Query margin account's trade list (USER_DATA)\n\n```\n\nGet /sapi/v1/margin/myTrades \n\n```\n\n\n\n**Weight:**\n\n5\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nsymbol | STRING | YES |\n\nstartTime |\tLONG | NO\t\n\nendTime | LONG | NO\t\n\nfromId | LONG | NO | TradeId to fetch from. Default gets most recent trades.\n\nlimit |\tINT | NO | Default 500; max 1000.\n\nrecvWindow | LONG | NO\n\ntimestamp | LONG | YES\n\n\n\nNotes:\n\n* If fromId is set, it will get orders >= that fromId. Otherwise most recent orders are returned.\n\n\n\n\n\n**Response:**\n\n```javascript\n\n[{\n\n\t\"commission\": \"0.00006000\",\n\n\t\"commissionAsset\": \"BTC\",\n\n\t\"id\": 34,\n\n\t\"isBestMatch\": true,\n\n\t\"isBuyer\": false,\n\n\t\"isMaker\": false,\n\n\t\"orderId\": 39324,\n\n\t\"price\": \"0.02000000\",\n\n\t\"qty\": \"3.00000000\",\n\n\t\"symbol\": \"BNBBTC\",\n\n\t\"time\": 1561973357171\n\n},{\n\n\t\"commission\": \"0.00002950\",\n\n\t\"commissionAsset\": \"BTC\",\n\n\t\"id\": 32,\n\n\t\"isBestMatch\": true,\n\n\t\"isBuyer\": false,\n\n\t\"isMaker\": true,\n\n\t\"orderId\": 39319,\n\n\t\"price\": \"0.00590000\",\n\n\t\"qty\": \"5.00000000\",\n\n\t\"symbol\": \"BNBBTC\",\n\n\t\"time\": 1561964645345\n\n}]\n\n```\n\n\n\n### Query max borrow (USER_DATA)\n\n```\n\nGet /sapi/v1/margin/maxBorrowable \n\n```\n\n\n\n**Weight:**\n\n5\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nasset | STRING | YES |\n\nrecvWindow | LONG | NO\n\ntimestamp | LONG | YES\n\n\n\n**Response:**\n\n```javascript\n\n{\n\n \"amount\": \"1.69248805\"\n\n}\n\n```\n\n\n\n### Query max transfer-out amount (USER_DATA)\n\n```\n\nGet /sapi/v1/margin/maxTransferable \n\n```\n\n\n\n**Weight:**\n\n5\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nasset | STRING | YES |\n\nrecvWindow | LONG | NO\n\ntimestamp | LONG | YES\n\n\n\n**Response:**\n\n```javascript\n\n {\n\n \"amount\": \"3.59498107\"\n\n }\n\n```\n\n\n\n### Start user data stream for margin account (USER_STREAM)\n\n```\n\nPOST /sapi/v1/userDataStream\n\n```\n\n\n\n**Weight:**\n\n1\n\n\n\n**Parameters:**\n\n\n\nNONE\n\n\n\n**Response:**\n\n```javascript\n\n{\"listenKey\": \"T3ee22BIYuWqmvne0HNq2A2WsFlEtLhvWCtItw6ffhhdmjifQ2tRbuKkTHhr\"}\n\n```\n\n\n", "file_path": "docs/margin.md", "rank": 30, "score": 19545.981495992553 }, { "content": "### Query margin account's open order (USER_DATA)\n\n```\n\nGet /sapi/v1/margin/openOrders \n\n```\n\n\n\n**Weight:**\n\n10\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nsymbol | STRING | NO |\n\nrecvWindow | LONG | NO\n\ntimestamp | LONG | YES\n\n\n\n* If the symbol is not sent, orders for all symbols will be returned in an array.\n\n* When all symbols are returned, the number of requests counted against the rate limiter is equal to the number of symbols currently trading on the exchange.\n\n\n\n**Response:**\n\n```javascript\n\n[\n\n {\n\n \"clientOrderId\": \"qhcZw71gAkCCTv0t0k8LUK\",\n\n \"cummulativeQuoteQty\": \"0.00000000\",\n\n \"executedQty\": \"0.00000000\",\n\n \"icebergQty\": \"0.00000000\",\n\n \"isWorking\": true,\n\n \"orderId\": 211842552,\n\n \"origQty\": \"0.30000000\",\n\n \"price\": \"0.00475010\",\n\n \"side\": \"SELL\",\n\n \"status\": \"NEW\",\n\n \"stopPrice\": \"0.00000000\",\n\n \"symbol\": \"BNBBTC\",\n\n \"time\": 1562040170089,\n\n \"timeInForce\": \"GTC\",\n\n \"type\": \"LIMIT\",\n\n \"updateTime\": 1562040170089\n\n }\n\n]\n\n```\n\n\n\n\n", "file_path": "docs/margin.md", "rank": 31, "score": 19545.088851960725 }, { "content": "timestamp | LONG | YES\n\n\n\n**Response ACK:**\n\n```javascript\n\n{\n\n \"symbol\": \"BTCUSDT\",\n\n \"orderId\": 28,\n\n \"clientOrderId\": \"6gCrw2kRUAF9CvJDGP16IP\",\n\n \"transactTime\": 1507725176595\n\n}\n\n```\n\n**Response RESULT:**\n\n```javascript\n\n{\n\n \"symbol\": \"BTCUSDT\",\n\n \"orderId\": 28,\n\n \"clientOrderId\": \"6gCrw2kRUAF9CvJDGP16IP\",\n\n \"transactTime\": 1507725176595,\n\n \"price\": \"1.00000000\",\n\n \"origQty\": \"10.00000000\",\n\n \"executedQty\": \"10.00000000\",\n\n \"cummulativeQuoteQty\": \"10.00000000\",\n\n \"status\": \"FILLED\",\n\n \"timeInForce\": \"GTC\",\n\n \"type\": \"MARKET\",\n\n \"side\": \"SELL\"\n\n}\n\n```\n\n**Response FULL:**\n\n```javascript\n\n{\n\n \"symbol\": \"BTCUSDT\",\n\n \"orderId\": 28,\n\n \"clientOrderId\": \"6gCrw2kRUAF9CvJDGP16IP\",\n\n \"transactTime\": 1507725176595,\n\n \"price\": \"1.00000000\",\n\n \"origQty\": \"10.00000000\",\n\n \"executedQty\": \"10.00000000\",\n\n \"cummulativeQuoteQty\": \"10.00000000\",\n\n \"status\": \"FILLED\",\n\n \"timeInForce\": \"GTC\",\n\n \"type\": \"MARKET\",\n\n \"side\": \"SELL\",\n\n \"fills\": [\n\n {\n\n \"price\": \"4000.00000000\",\n\n \"qty\": \"1.00000000\",\n\n \"commission\": \"4.00000000\",\n\n \"commissionAsset\": \"USDT\"\n\n },\n\n {\n\n \"price\": \"3999.00000000\",\n\n \"qty\": \"5.00000000\",\n\n \"commission\": \"19.99500000\",\n\n \"commissionAsset\": \"USDT\"\n\n },\n\n {\n\n \"price\": \"3998.00000000\",\n\n \"qty\": \"2.00000000\",\n\n \"commission\": \"7.99600000\",\n\n \"commissionAsset\": \"USDT\"\n\n },\n\n {\n\n \"price\": \"3997.00000000\",\n\n \"qty\": \"1.00000000\",\n\n \"commission\": \"3.99700000\",\n\n \"commissionAsset\": \"USDT\"\n\n },\n\n {\n\n \"price\": \"3995.00000000\",\n\n \"qty\": \"1.00000000\",\n\n \"commission\": \"3.99500000\",\n\n \"commissionAsset\": \"USDT\"\n\n }\n\n ]\n\n}\n\n```\n\n\n", "file_path": "docs/margin.md", "rank": 32, "score": 19544.780686831087 }, { "content": "### Query margin account's all order (USER_DATA)\n\n```\n\nGet /sapi/v1/margin/allOrders \n\n```\n\n\n\n**Weight:**\n\n5\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nsymbol | STRING | YES |\n\norderId | LONG | NO\t\n\nstartTime |\tLONG | NO\t\n\nendTime | LONG | NO\t\n\nlimit |\tINT | NO | Default 500; max 1000.\n\nrecvWindow | LONG | NO\n\ntimestamp | LONG | YES\n\n\n\nNotes:\n\n\n\n* If orderId is set, it will get orders >= that orderId. Otherwise most recent orders are returned.\n\n* For some historical orders cummulativeQuoteQty will be < 0, meaning the data is not available at this time.\n\n\n\n**Response:**\n\n```javascript\n\n[\n\n {\n\n \"id\": 43123876,\n\n \"price\": \"0.00395740\",\n\n \"qty\": \"4.06000000\",\n\n \"quoteQty\": \"0.01606704\",\n\n \"symbol\": \"BNBBTC\",\n\n \"time\": 1556089977693\n\n },\n\n {\n\n \"id\": 43123877,\n\n \"price\": \"0.00395740\",\n\n \"qty\": \"0.77000000\",\n\n \"quoteQty\": \"0.00304719\",\n\n \"symbol\": \"BNBBTC\",\n\n \"time\": 1556089977693\n\n },\n\n {\n\n \"id\": 43253549,\n\n \"price\": \"0.00428930\",\n\n \"qty\": \"23.30000000\",\n\n \"quoteQty\": \"0.09994069\",\n\n \"symbol\": \"BNBBTC\",\n\n \"time\": 1556163963504\n\n }\n\n]\n\n```\n\n\n", "file_path": "docs/margin.md", "rank": 33, "score": 19544.238011309186 }, { "content": "### Margin account cancel order (TRADE)\n\n```\n\nDelete /sapi/v1/margin/order\n\n```\n\nCancel an active order for margin account.\n\n\n\n**Weight:**\n\n1\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nsymbol | STRING | YES |\n\norderId | LONG | NO | \n\norigClientOrderId |\tSTRING | NO\t\n\nnewClientOrderId |\tSTRING | NO | Used to uniquely identify this cancel. Automatically generated by default.\n\nrecvWindow | LONG | NO\n\ntimestamp | LONG | YES\n\n\n\nEither orderId or origClientOrderId must be sent.\n\n\n\n**Response:**\n\n```javascript\n\n{\n\n \"symbol\": \"LTCBTC\",\n\n \"orderId\": 28,\n\n \"origClientOrderId\": \"myOrder1\",\n\n \"clientOrderId\": \"cancelMyOrder1\",\n\n \"transactTime\": 1507725176595,\n\n \"price\": \"1.00000000\",\n\n \"origQty\": \"10.00000000\",\n\n \"executedQty\": \"8.00000000\",\n\n \"cummulativeQuoteQty\": \"8.00000000\",\n\n \"status\": \"CANCELED\",\n\n \"timeInForce\": \"GTC\",\n\n \"type\": \"LIMIT\",\n\n \"side\": \"SELL\"\n\n}\n\n```\n\n\n\n### Query loan record (USER_DATA)\n\n```\n\nGet /sapi/v1/margin/loan\n\n```\n\n\n\n**Weight:**\n\n5\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nasset |\tSTRING | YES\t\n\ntxId | LONG | NO | the tranId in POST /sapi/v1/margin/loan\n\nstartTime |\tLONG |\tNO\t\n\nendTime | LONG | NO\t\n\ncurrent | LONG | NO | Currently querying page. Start from 1. Default:1\n\nsize |\tLONG | NO |\tDefault:10 Max:100\n\nrecvWindow | LONG | NO\n\ntimestamp | LONG | YES\n\n\n\ntxId or startTime must be sent. txId takes precedence.\n\n\n\n**Response:**\n\n```javascript\n\n{\n\n \"rows\": [\n\n {\n\n \"asset\": \"BNB\",\n\n \"principal\": \"0.84624403\",\n\n \"timestamp\": 1555056425000,\n\n //one of PENDING (pending to execution), CONFIRMED (successfully loaned), FAILED (execution failed, nothing happened to your account);\n\n \"status\": \"CONFIRMED\"\n\n }\n\n ],\n\n \"total\": 1\n\n}\n\n```\n\n\n", "file_path": "docs/margin.md", "rank": 34, "score": 19543.30147239839 }, { "content": "### Delete user data stream for margin account (USER_STREAM)\n\n```\n\nDELETE /sapi/v1/userDataStream\n\n```\n\n\n\n**Weight:**\n\n1\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nlistenKey | STRING | YES |\n\n\n\n**Response:**\n\n```javascript\n\n{}\n\n```\n\n\n\n## Ping user data stream for margin account (USER_STREAM)\n\n```\n\nPUT /sapi/v1/userDataStream\n\n```\n\n\n\n**Weight:**\n\n1\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nlistenKey | STRING | YES |\n\n\n\n**Response:**\n\n```javascript\n\n{}\n\n```\n", "file_path": "docs/margin.md", "rank": 35, "score": 19538.116579118 }, { "content": "# Endpoint security type\n\n* Each endpoint has a security type that determines the how you will\n\n interact with it.\n\n* API-keys are passed into the Rest API via the `X-MBX-APIKEY`\n\n header.\n\n* API-keys and secret-keys **are case sensitive**.\n\n* API-keys can be configured to only access certain types of secure endpoints.\n\n For example, one API-key could be used for TRADE only, while another API-key\n\n can access everything except for TRADE routes.\n\n* By default, API-keys can access all secure routes.\n\n\n\nSecurity Type | Description\n\n------------ | ------------\n\nNONE | Endpoint can be accessed freely.\n\nTRADE | Endpoint requires sending a valid API-Key and signature.\n\nUSER_DATA | Endpoint requires sending a valid API-Key and signature.\n\nMARGIN | Endpoint requires sending a valid API-Key and signature.\n\nUSER_STREAM | Endpoint requires sending a valid API-Key.\n\nMARKET_DATA | Endpoint requires sending a valid API-Key.\n\n\n\n\n\n* `TRADE` and `USER_DATA` endpoints are `SIGNED` endpoints.\n\n\n\n# SIGNED (TRADE、USER_DATA AND MARGIN) Endpoint security\n\n* `SIGNED` endpoints require an additional parameter, `signature`, to be\n\n sent in the `query string` or `request body`.\n\n* Endpoints use `HMAC SHA256` signatures. The `HMAC SHA256 signature` is a keyed `HMAC SHA256` operation.\n\n Use your `secretKey` as the key and `totalParams` as the value for the HMAC operation.\n\n* The `signature` is **not case sensitive**.\n\n* `totalParams` is defined as the `query string` concatenated with the\n\n `request body`.\n\n\n", "file_path": "docs/margin.md", "rank": 36, "score": 19536.01883595751 }, { "content": "# Public Rest API for Margin Trade (DRAFT, under construction)\n\n# General API Information\n\n* The base endpoint is: **https://api.binance.com**\n\n* All endpoints return either a JSON object or array.\n\n* Data is returned in **ascending** order. Oldest first, newest last.\n\n* All time and timestamp related fields are in milliseconds.\n\n* HTTP `4XX` return codes are used for for malformed requests;\n\n the issue is on the sender's side.\n\n* HTTP `429` return code is used when breaking a request rate limit.\n\n* HTTP `418` return code is used when an IP has been auto-banned for continuing to send requests after receiving `429` codes.\n\n* HTTP `5XX` return codes are used for internal errors; the issue is on\n\n Binance's side.\n\n It is important to **NOT** treat this as a failure operation; the execution status is\n\n **UNKNOWN** and could have been a success.\n\n* Any endpoint can return an ERROR; the error payload is as follows:\n\n```javascript\n\n{\n\n \"code\": -1121,\n\n \"msg\": \"Invalid symbol.\"\n\n}\n\n```\n\n\n\n* Specific error codes and messages defined in another document.\n\n* For `GET` endpoints, parameters must be sent as a `query string`.\n\n* For `POST`, `PUT`, and `DELETE` endpoints, the parameters may be sent as a\n\n `query string` or in the `request body` with content type\n\n `application/x-www-form-urlencoded`. You may mix parameters between both the\n\n `query string` and `request body` if you wish to do so.\n\n* Parameters may be sent in any order.\n\n* If a parameter sent in both the `query string` and `request body`, the\n\n `query string` parameter will be used.\n\n\n\n\n", "file_path": "docs/margin.md", "rank": 37, "score": 19535.892707204774 }, { "content": "### Margin account borrow (MARGIN)\n\n```\n\nPost /sapi/v1/margin/loan \n\n```\n\nApply for a loan.\n\n\n\n**Weight:**\n\n1\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nasset | STRING | YES | \n\namount | DECIMAL | YES | \n\nrecvWindow | LONG | NO\n\ntimestamp | LONG | YES\n\n\n\n**Response:**\n\n```javascript\n\n{\n\n //transaction id\n\n \"tranId\": 100000001\n\n}\n\n```\n\n\n\n### Margin account repay (MARGIN)\n\n```\n\nPost /sapi/v1/margin/repay\n\n```\n\nRepay loan for margin account.\n\n\n\n**Weight:**\n\n1\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nasset | STRING | YES | \n\namount | DECIMAL | YES | \n\nrecvWindow | LONG | NO\n\ntimestamp | LONG | YES\n\n\n\n**Response:**\n\n```javascript\n\n{\n\n //transaction id\n\n \"tranId\": 100000001\n\n}\n\n```\n\n\n\n### Margin account new order (TRADE)\n\n```\n\nPost /sapi/v1/margin/order\n\n```\n\nPost a new order for margin account.\n\n\n\n**Weight:**\n\n1\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nsymbol | STRING | YES |\n\nside |\tENUM |YES |\tBUY<br>SELL\n\ntype | ENUM | YES\t\n\nquantity | DECIMAL |\tYES\t\n\nprice |\tDECIMAL | NO\t\n\nstopPrice | DECIMAL | NO | Used with STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders.\n\nnewClientOrderId | STRING | NO | A unique id for the order. Automatically generated if not sent.\n\nicebergQty | DECIMAL | NO | Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.\n\nnewOrderRespType | ENUM | NO | Set the response JSON. ACK, RESULT, or FULL; MARKET and LIMIT order types default to FULL, all other orders default to ACK.\n\ntimeInForce | ENUM | NO | GTC,IOC,FOK\n\nrecvWindow | LONG | NO\n", "file_path": "docs/margin.md", "rank": 38, "score": 19535.49361715574 }, { "content": "### Example 3: Mixed query string and request body\n\n* **queryString:** symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC\n\n* **requestBody:** quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559\n\n* **HMAC SHA256 signature:**\n\n\n\n ```\n\n [linux]$ echo -n \"symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTCquantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559\" | openssl dgst -sha256 -hmac \"NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j\"\n\n (stdin)= 0fd168b8ddb4876a0358a8d14d0c9f3da0e9b20c5d52b2a00fcf7d1c602f9a77\n\n ```\n\n\n\n\n\n* **curl command:**\n\n\n\n ```\n\n (HMAC SHA256)\n\n [linux]$ curl -H \"X-MBX-APIKEY: vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A\" -X POST 'https://api.binance.com/api/v1/order?symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC' -d 'quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559&signature=0fd168b8ddb4876a0358a8d14d0c9f3da0e9b20c5d52b2a00fcf7d1c602f9a77'\n\n ```\n\n\n\nNote that the signature is different in example 3.\n\nThere is no & between \"GTC\" and \"quantity=1\".\n\n\n\n\n\n\n\n## General endpoints\n\n### Margin account transfer (MARGIN)\n\n```\n\nPost /sapi/v1/margin/transfer \n\n```\n\nExecute transfer between spot account and margin account.\n\n\n\n**Weight:**\n\n1\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nasset | STRING | YES | The asset being transferred, e.g., BTC\n\namount | DECIMAL | YES | The amount to be transferred\n\ntype | INT | YES | 1: transfer from main account to margin account 2: transfer from margin account to main account\n\nrecvWindow | LONG | NO\n\ntimestamp | LONG | YES\n\n\n\n\n\n**Response:**\n\n```javascript\n\n{\n\n //transaction id\n\n \"tranId\": 100000001\n\n}\n\n```\n\n\n", "file_path": "docs/margin.md", "rank": 39, "score": 19535.006333970654 }, { "content": "### Example 1: As a query string\n\n* **queryString:** symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559\n\n* **HMAC SHA256 signature:**\n\n\n\n ```\n\n [linux]$ echo -n \"symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559\" | openssl dgst -sha256 -hmac \"NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j\"\n\n (stdin)= c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71\n\n ```\n\n\n\n\n\n* **curl command:**\n\n\n\n ```\n\n (HMAC SHA256)\n\n [linux]$ curl -H \"X-MBX-APIKEY: vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A\" -X POST 'https://api.binance.com/api/v1/order?symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559&signature=c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71'\n\n ```\n\n\n\n### Example 2: As a request body\n\n* **requestBody:** symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559\n\n* **HMAC SHA256 signature:**\n\n\n\n ```\n\n [linux]$ echo -n \"symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559\" | openssl dgst -sha256 -hmac \"NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j\"\n\n (stdin)= c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71\n\n ```\n\n\n\n\n\n* **curl command:**\n\n\n\n ```\n\n (HMAC SHA256)\n\n [linux]$ curl -H \"X-MBX-APIKEY: vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A\" -X POST 'https://api.binance.com/api/v1/order' -d 'symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559&signature=c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71'\n\n ```\n\n\n", "file_path": "docs/margin.md", "rank": 40, "score": 19533.374409471 }, { "content": "### Query margin pair (MARKET_DATA)\n\n```\n\nGet /sapi/v1/margin/pair \n\n```\n\n\n\n**Weight:**\n\n5\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nsymbol | STRING | YES |\n\n\n\n**Response:**\n\n```javascript\n\n{\n\n \"id\":323355778339572400,\n\n \"symbol\":\"BTCUSDT\",\n\n \"base\":\"BTC\",\n\n \"quote\":\"USDT\",\n\n \"isMarginTrade\":true,\n\n \"isBuyAllowed\":true,\n\n \"isSellAllowed\":true\n\n}\n\n```\n\n\n\n### Get all margin assets (MARKET_DATA)\n\n\n\n```\n\nGet /sapi/v1/margin/allAssets\n\n```\n\n\n\n**Weight:**\n\n5\n\n\n\n**Parameters:**\n\n\n\nNone\n\n\n\n**Response:**\n\n\n\n```javascript\n\n [\n\n {\n\n \"assetFullName\": \"USD coin\",\n\n \"assetName\": \"USDC\",\n\n \"isBorrowable\": true,\n\n \"isMortgageable\": true,\n\n \"userMinBorrow\": \"0.00000000\",\n\n \"userMinRepay\": \"0.00000000\"\n\n },\n\n {\n\n \"assetFullName\": \"BNB-coin\",\n\n \"assetName\": \"BNB\",\n\n \"isBorrowable\": true,\n\n \"isMortgageable\": true,\n\n \"userMinBorrow\": \"1.00000000\",\n\n \"userMinRepay\": \"0.00000000\"\n\n },\n\n {\n\n \"assetFullName\": \"Tether\",\n\n \"assetName\": \"USDT\",\n\n \"isBorrowable\": true,\n\n \"isMortgageable\": true,\n\n \"userMinBorrow\": \"1.00000000\",\n\n \"userMinRepay\": \"0.00000000\"\n\n },\n\n {\n\n \"assetFullName\": \"etherum\",\n\n \"assetName\": \"ETH\",\n\n \"isBorrowable\": true,\n\n \"isMortgageable\": true,\n\n \"userMinBorrow\": \"0.00000000\",\n\n \"userMinRepay\": \"0.00000000\"\n\n },\n\n {\n\n \"assetFullName\": \"Bitcoin\",\n\n \"assetName\": \"BTC\",\n\n \"isBorrowable\": true,\n\n \"isMortgageable\": true,\n\n \"userMinBorrow\": \"0.00000000\",\n\n \"userMinRepay\": \"0.00000000\"\n\n }\n\n ]\n\n```\n\n\n", "file_path": "docs/margin.md", "rank": 41, "score": 19532.683181681925 }, { "content": "### Get all margin pairs (MARKET_DATA)\n\n```\n\nGet /sapi/v1/margin/allPairs \n\n```\n\n\n\n**Weight:**\n\n5\n\n\n\n**Parameters:**\n\n\n\nNone\n\n\n\n**Response:**\n\n\n\n```javascript\n\n[\n\n\t{\n\n\t\t\"base\": \"BNB\",\n\n \t\t\"id\": 351637150141315861,\n\n \t\t\"isBuyAllowed\": True,\n\n \t\t\"isMarginTrade\": True,\n\n \t\t\"isSellAllowed\": True,\n\n \t\t\"quote\": \"BTC\",\n\n \t\t\"symbol\": \"BNBBTC\"\n\n \t},\n\n \t{\n\n \t\t\"base\": \"TRX\",\n\n \t\t\"id\": 351637923235429141,\n\n \t\t\"isBuyAllowed\": True,\n\n \t\t\"isMarginTrade\": True,\n\n \t\t\"isSellAllowed\": True,\n\n \t\t\"quote\": \"BTC\",\n\n \t\t\"symbol\": \"TRXBTC\"\n\n \t},\n\n \t{\n\n \t\t\"base\": \"XRP\",\n\n \t\t\"id\": 351638112213990165,\n\n \t\t\"isBuyAllowed\": True,\n\n \t\t\"isMarginTrade\": True,\n\n \t\t\"isSellAllowed\": True,\n\n \t\t\"quote\": \"BTC\",\n\n \t\t\"symbol\": \"XRPBTC\"\n\n \t},\n\n \t{\n\n \t\t\"base\": \"ETH\",\n\n \t\t\"id\": 351638524530850581,\n\n \t\t\"isBuyAllowed\": True,\n\n \t\t\"isMarginTrade\": True,\n\n \t\t\"isSellAllowed\": True,\n\n \t\t\"quote\": \"BTC\",\n\n \t\t\"symbol\": \"ETHBTC\"\n\n \t},\n\n \t{\n\n \t\t\"base\": \"BNB\",\n\n \t\t\"id\": 376870400832855109,\n\n \t\t\"isBuyAllowed\": True,\n\n \t\t\"isMarginTrade\": True,\n\n \t\t\"isSellAllowed\": True,\n\n \t\t\"quote\": \"USDT\",\n\n \t\t\"symbol\": \"BNBUSDT\"\n\n },\n\n]\n\n```\n\n\n\n### Query margin priceIndex (MARKET_DATA)\n\n```\n\nGet /sapi/v1/margin/priceIndex \n\n```\n\n\n\n**Weight:**\n\n5\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nsymbol | STRING | YES |\n\n\n\n**Response:**\n\n```javascript\n\n{\n\n \"calcTime\": 1562046418000,\n\n \"price\": \"0.00333930\",\n\n \"symbol\": \"BNBBTC\"\n\n}\n\n```\n\n\n", "file_path": "docs/margin.md", "rank": 42, "score": 19531.781632709044 }, { "content": "### Get transfer history (USER_DATA)\n\n```\n\nGet /sapi/v1/margin/transfer\n\n```\n\n\n\n**Weight:**s\n\n5\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nasset | STRING | No\n\ntype | STRING | YES | Tranfer Type: ROLL_IN, ROLL_OUT\n\nstartTime | LONG |\tNO\t\n\nendTime | LONG | NO\t\n\ncurrent | LONG | NO | Currently querying page. Start from 1. Default:1\n\nsize |\tLONG | NO |\tDefault:10 Max:100\n\nrecvWindow | LONG | NO | The value cannot be greater than ```60000```\n\ntimestamp | LONG | YES\n\n\n\n\n\n**Response:**\n\n\n\n```javascript\n\n{\n\n\t\"rows\": [\n\n \t{\n\n \t\t\"amount: \"0.10000000\",\n\n \t\t\"asset\": \"BNB\",\n\n \t\t\"status\": \"CONFIRMED\",\n\n \t\t\"timestamp\": 1566898617,\n\n \t\t\"txId\": 5240372201,\n\n \t\t\"type\": \"ROLL_IN\"\n\n \t},\n\n \t{\n\n \t\t\"amount\": \"5.00000000\",\n\n \t\t\"asset\": \"USDT\",\n\n \t\t\"status\": \"CONFIRMED\",\n\n \t\t\"timestamp\": 1566888436,\n\n \t\t\"txId\": 5239810406,\n\n \t\t\"type\": \"ROLL_OUT\"\n\n \t},\n\n \t{\n\n \t\t\"amount\": \"1.00000000\",\n\n \t\t\"asset\": \"EOS,\n\n \t\t\"status\": \"CONFIRMED\",\n\n \t\t\"timestamp\": 1566888403,\n\n \t\t\"txId\": 5239808703,\n\n \t\t\"type\": \"ROLL_IN\"\n\n \t}\n\n \t\"total\": 3\n\n} \n\n```\n\n\n", "file_path": "docs/margin.md", "rank": 43, "score": 19531.715252461774 }, { "content": "### Query repay record (USER_DATA)\n\n```\n\nGet /sapi/v1/margin/repay\n\n```\n\n\n\n**Weight:**\n\n5\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nasset | STRING |\tYES\t\n\ntxId | LONG | NO | return of /sapi/v1/margin/repay \n\nstartTime | LONG | NO\t\n\nendTime | LONG | NO\t\n\ncurrent | LONG | NO\t| Currently querying page. Start from 1. Default:1\n\nsize | LONG | NO | Default:10 Max:100\n\nrecvWindow | LONG | NO\n\ntimestamp | LONG | YES\n\n\n\ntxId or startTime must be sent. txId takes precedence.\n\n\n\n\n\n**Response:**\n\n```javascript\n\n{\n\n \"rows\": [\n\n {\n\n //Total amount repaid\n\n \"amount\": \"14.00000000\",\n\n \"asset\": \"BNB\",\n\n //Interest repaid\n\n \"interest\": \"0.01866667\",\n\n //Principal repaid\n\n \"principal\": \"13.98133333\",\n\n //one of PENDING (pending to execution), CONFIRMED (successfully loaned), FAILED (execution failed, nothing happened to your account);\n\n \"status\": \"CONFIRMED\",\n\n \"timestamp\": 1563438204000,\n\n \"txId\": 2970933056\n\n }\n\n ],\n\n \"total\": 1\n\n}\n\n```\n\n\n", "file_path": "docs/margin.md", "rank": 44, "score": 19531.5570008038 }, { "content": "### Get interest history (USER_DATA)\n\n```\n\nGet /sapi/v1/margin/interestHistory\n\n```\n\n\n\n**Weight:**s\n\n5\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nasset | STRING | No\n\nstartTime | LONG |\tNO\t\n\nendTime | LONG | NO\t\n\ncurrent | LONG | NO | Currently querying page. Start from 1. Default:1\n\nsize |\tLONG | NO |\tDefault:10 Max:100\n\nrecvWindow | LONG | NO | The value cannot be greater than ```60000```\n\ntimestamp | LONG | YES\n\n\n\n\n\n**Response:**\n\n\n\n```javascript\n\n {\n\n \"rows\": [\n\n {\n\n \"asset\": \"BNB\",\n\n \"interest\": \"0.02414667\",\n\n \"interestAccuredTime\": 1566813600,\n\n \"interestRate\": \"0.01600000\",\n\n \"principal\": \"36.22000000\",\n\n \"type\": \"ON_BORROW\"\n\n },\n\n {\n\n \"asset\": \"BNB\",\n\n \"interest\": \"0.02019334\",\n\n \"interestAccuredTime\": 1566813600,\n\n \"interestRate\": \"0.01600000\",\n\n \"principal\": \"30.29000000\",\n\n \"type\": \"ON_BORROW\"\n\n },\n\n {\n\n \"asset\": \"BNB\",\n\n \"interest\": \"0.02098667\",\n\n \"interestAccuredTime\": 1566813600,\n\n \"interestRate\": \"0.01600000\",\n\n \"principal\": \"31.48000000\",\n\n \"type\": \"ON_BORROW\"\n\n },\n\n {\n\n \"asset\": \"BNB\",\n\n \"interest\": \"0.02483334\",\n\n \"interestAccuredTime\": 1566806400,\n\n \"interestRate\": \"0.01600000\",\n\n \"principal\": \"37.25000000\",\n\n \"type\": \"ON_BORROW\"\n\n },\n\n {\n\n \"asset\": \"BNB\",\n\n \"interest\": \"0.02165334\",\n\n \"interestAccuredTime\": 1566806400,\n\n \"interestRate\": \"0.01600000\",\n\n \"principal\": \"32.48000000\",\n\n \"type\": \"ON_BORROW\"\n\n }\n\n ],\n\n \"total\": 5\n\n }\n\n```\n\n\n", "file_path": "docs/margin.md", "rank": 45, "score": 19529.88727526566 }, { "content": "### Query margin account details (USER_DATA)\n\n```\n\nGet /sapi/v1/margin/account\n\n```\n\n\n\n**Weight:**\n\n5\n\n\n\n**Parameters:**\n\n\n\nNone\n\n\n\n**Response:**\n\n```javascript\n\n{\n\n \"borrowEnabled\": true,\n\n \"marginLevel\": \"11.64405625\",\n\n \"totalAssetOfBtc\": \"6.82728457\",\n\n \"totalLiabilityOfBtc\": \"0.58633215\",\n\n \"totalNetAssetOfBtc\": \"6.24095242\",\n\n \"tradeEnabled\": true,\n\n \"transferEnabled\": true,\n\n \"userAssets\": [\n\n {\n\n \"asset\": \"BTC\",\n\n \"borrowed\": \"0.00000000\",\n\n \"free\": \"0.00499500\",\n\n \"interest\": \"0.00000000\",\n\n \"locked\": \"0.00000000\",\n\n \"netAsset\": \"0.00499500\"\n\n },\n\n {\n\n \"asset\": \"BNB\",\n\n \"borrowed\": \"201.66666672\",\n\n \"free\": \"2346.50000000\",\n\n \"interest\": \"0.00000000\",\n\n \"locked\": \"0.00000000\",\n\n \"netAsset\": \"2144.83333328\"\n\n },\n\n {\n\n \"asset\": \"ETH\",\n\n \"borrowed\": \"0.00000000\",\n\n \"free\": \"0.00000000\",\n\n \"interest\": \"0.00000000\",\n\n \"locked\": \"0.00000000\",\n\n \"netAsset\": \"0.00000000\"\n\n },\n\n {\n\n \"asset\": \"USDT\",\n\n \"borrowed\": \"0.00000000\",\n\n \"free\": \"0.00000000\",\n\n \"interest\": \"0.00000000\",\n\n \"locked\": \"0.00000000\",\n\n \"netAsset\": \"0.00000000\"\n\n }\n\n ]\n\n}\n\n```\n\n\n\n\n\n### Query margin asset (MARKET_DATA)\n\n\n\n```\n\nGet /sapi/v1/margin/asset \n\n```\n\n\n\n**Weight:**\n\n5\n\n\n\n**Parameters:**\n\n\n\nName | Type | Mandatory | Description\n\n------------ | ------------ | ------------ | ------------\n\nasset | STRING | YES |\n\n\n\n**Response:**\n\n```javascript\n\n{\n\n \"assetFullName\": \"Binance Coin\",\n\n \"assetName\": \"BNB\",\n\n \"isBorrowable\": false,\n\n \"isMortgageable\": true,\n\n \"userMinBorrow\": \"0.00000000\",\n\n \"userMinRepay\": \"0.00000000\"\n\n}\n\n```\n\n\n", "file_path": "docs/margin.md", "rank": 46, "score": 19529.090512242958 }, { "content": "## Timing security\n\n* A `SIGNED` endpoint also requires a parameter, `timestamp`, to be sent which\n\n should be the millisecond timestamp of when the request was created and sent.\n\n* An additional parameter, `recvWindow`, may be sent to specify the number of\n\n milliseconds after `timestamp` the request is valid for. If `recvWindow`\n\n is not sent, **it defaults to 5000**.\n\n* The logic is as follows:\n\n ```javascript\n\n if (timestamp < (serverTime + 1000) && (serverTime - timestamp) <= recvWindow) {\n\n // process request\n\n } else {\n\n // reject request\n\n }\n\n ```\n\n\n\n**Serious trading is about timing.** Networks can be unstable and unreliable,\n\nwhich can lead to requests taking varying amounts of time to reach the\n\nservers. With `recvWindow`, you can specify that the request must be\n\nprocessed within a certain number of milliseconds or be rejected by the\n\nserver.\n\n\n\n\n\n**It recommended to use a small recvWindow of 5000 or less!**\n\n\n\n\n\n## SIGNED Endpoint Examples for POST /api/v1/order\n\nHere is a step-by-step example of how to send a vaild signed payload from the\n\nLinux command line using `echo`, `openssl`, and `curl`.\n\n\n\nKey | Value\n\n------------ | ------------\n\napiKey | vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A\n\nsecretKey | NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j\n\n\n\n\n\nParameter | Value\n\n------------ | ------------\n\nsymbol | LTCBTC\n\nside | BUY\n\ntype | LIMIT\n\ntimeInForce | GTC\n\nquantity | 1\n\nprice | 0.1\n\nrecvWindow | 5000\n\ntimestamp | 1499827319559\n\n\n\n\n", "file_path": "docs/margin.md", "rank": 47, "score": 19526.39460405797 }, { "content": "# Usage\n\n\n\n## Binance Endpoints\n\n\n\ncargo run --release --example \"binance_endpoints\"\n\n\n\n## Binance Websockets\n\n\n\ncargo run --release --example \"binance_websockets\"\n\n\n\n## Binance Websockets - Save all trades to file\n\n\n\ncargo run --release --example \"binance_save_all_trades\"\n", "file_path": "examples/README.md", "rank": 48, "score": 19517.732491906787 }, { "content": " }\n\n Err(e) => Err(Error::Msg(format!(\"Error during handshake {}\", e))),\n\n }\n\n }\n\n\n\n /// Disconnect from the endpoint\n\n pub async fn disconnect(&mut self) -> Result<()> {\n\n if let Some(ref mut socket) = self.socket {\n\n socket.0.close(None).await?;\n\n Ok(())\n\n } else {\n\n Err(Error::Msg(\"Not able to close the connection\".to_string()))\n\n }\n\n }\n\n\n\n pub fn socket(&self) -> &Option<(WebSocketStream<MaybeTlsStream<TcpStream>>, Response)> { &self.socket }\n\n\n\n pub async fn event_loop(&mut self, running: &AtomicBool) -> Result<()> {\n\n while running.load(Ordering::Relaxed) {\n\n if let Some((ref mut socket, _)) = self.socket {\n", "file_path": "src/websockets.rs", "rank": 54, "score": 40.113861267856954 }, { "content": " }\n\n\n\n // Best price/qty on the order book for ALL symbols\n\n match market.get_all_book_tickers().await {\n\n Ok(answer) => info!(\"{:?}\", answer),\n\n Err(e) => error!(\"Error: {}\", e),\n\n }\n\n\n\n // Best price/qty on the order book for ONE symbol\n\n match market.get_book_ticker(\"BNBETH\").await {\n\n Ok(answer) => info!(\"Bid Price: {}, Ask Price: {}\", answer.bid_price, answer.ask_price),\n\n Err(e) => error!(\"Error: {}\", e),\n\n }\n\n\n\n // 24hr ticker price change statistics\n\n match market.get_24h_price_stats(\"BNBETH\").await {\n\n Ok(answer) => info!(\n\n \"Open Price: {}, Higher Price: {}, Lower Price: {:?}\",\n\n answer.open_price, answer.high_price, answer.low_price\n\n ),\n", "file_path": "examples/binance_endpoints.rs", "rank": 56, "score": 34.911167836121614 }, { "content": " symbol: symbol.into(),\n\n side: OrderSide::Buy,\n\n position_side: None,\n\n order_type: OrderType::Limit,\n\n time_in_force: Some(time_in_force),\n\n qty: Some(qty.into()),\n\n reduce_only: None,\n\n price: Some(price),\n\n stop_price: None,\n\n close_position: None,\n\n activation_price: None,\n\n callback_rate: None,\n\n working_type: None,\n\n price_protect: None,\n\n };\n\n self.post_order(order).await\n\n }\n\n\n\n pub async fn limit_sell(\n\n &self,\n", "file_path": "src/futures/account.rs", "rank": 57, "score": 34.02090843049618 }, { "content": " close_position: None,\n\n activation_price: None,\n\n callback_rate: None,\n\n working_type: None,\n\n price_protect: None,\n\n };\n\n self.post_order(order).await\n\n }\n\n\n\n // Place a MARKET order - SELL\n\n pub async fn market_sell<S, F>(&self, symbol: S, qty: F) -> Result<Transaction>\n\n where\n\n S: Into<String>,\n\n F: Into<f64>,\n\n {\n\n let order: OrderRequest = OrderRequest {\n\n symbol: symbol.into(),\n\n side: OrderSide::Sell,\n\n position_side: None,\n\n order_type: OrderType::Market,\n", "file_path": "src/futures/account.rs", "rank": 60, "score": 33.54849005223991 }, { "content": " symbol: impl Into<String>,\n\n qty: impl Into<f64>,\n\n price: f64,\n\n time_in_force: TimeInForce,\n\n ) -> Result<Transaction> {\n\n let order = OrderRequest {\n\n symbol: symbol.into(),\n\n side: OrderSide::Sell,\n\n position_side: None,\n\n order_type: OrderType::Limit,\n\n time_in_force: Some(time_in_force),\n\n qty: Some(qty.into()),\n\n reduce_only: None,\n\n price: Some(price),\n\n stop_price: None,\n\n close_position: None,\n\n activation_price: None,\n\n callback_rate: None,\n\n working_type: None,\n\n price_protect: None,\n", "file_path": "src/futures/account.rs", "rank": 61, "score": 33.53906874281321 }, { "content": " };\n\n self.post_order(order).await\n\n }\n\n\n\n // Place a MARKET order - BUY\n\n pub async fn market_buy<S, F>(&self, symbol: S, qty: F) -> Result<Transaction>\n\n where\n\n S: Into<String>,\n\n F: Into<f64>,\n\n {\n\n let order = OrderRequest {\n\n symbol: symbol.into(),\n\n side: OrderSide::Buy,\n\n position_side: None,\n\n order_type: OrderType::Market,\n\n time_in_force: None,\n\n qty: Some(qty.into()),\n\n reduce_only: None,\n\n price: None,\n\n stop_price: None,\n", "file_path": "src/futures/account.rs", "rank": 63, "score": 32.47203923327231 }, { "content": " Err(e) => error!(\"Error: {}\", e),\n\n }\n\n\n\n let market_buy = OrderRequest {\n\n symbol: symbol.to_string(),\n\n quantity: Some(0.001),\n\n order_type: OrderType::Market,\n\n side: OrderSide::Buy,\n\n ..OrderRequest::default()\n\n };\n\n match account.place_order(market_buy).await {\n\n Ok(answer) => info!(\"{:?}\", answer),\n\n Err(e) => error!(\"Error: {}\", e),\n\n }\n\n\n\n let limit_sell = OrderRequest {\n\n symbol: symbol.to_string(),\n\n quantity: Some(0.001),\n\n price: Some(price),\n\n order_type: OrderType::Limit,\n", "file_path": "examples/binance_endpoints.rs", "rank": 65, "score": 31.656489119326665 }, { "content": " eprintln!(\"repay = {:?}\", repay);\n\n let repay_with_isolation = margin\n\n .repay_with_isolation(\"BTCUSDT\", 0.001, Some(true), Some(\"BNB\".to_string()))\n\n .await;\n\n eprintln!(\"repay_with_isolation = {:?}\", repay_with_isolation);\n\n let margin_order = MarginOrder {\n\n symbol: \"BTCUSDT\".to_string(),\n\n side: OrderSide::Sell,\n\n order_type: OrderType::Limit,\n\n quantity: Some(0.001),\n\n quote_order_qty: None,\n\n price: Some(10.0),\n\n stop_price: Some(10.0),\n\n new_client_order_id: Some(\"my_id\".to_string()),\n\n iceberg_qty: Some(10.0),\n\n new_order_resp_type: OrderResponse::Ack,\n\n time_in_force: Some(TimeInForce::FOK),\n\n side_effect_type: SideEffectType::NoSideEffect,\n\n is_isolated: None,\n\n };\n", "file_path": "examples/binance_margin.rs", "rank": 66, "score": 31.046904182255815 }, { "content": " Ok(answer) => info!(\"{:?}\", answer.balances),\n\n Err(e) => error!(\"Error: {}\", e),\n\n }\n\n\n\n match account.get_open_orders(symbol).await {\n\n Ok(answer) => info!(\"{:?}\", answer),\n\n Err(e) => error!(\"Error: {}\", e),\n\n }\n\n\n\n let limit_buy = OrderRequest {\n\n symbol: symbol.to_string(),\n\n quantity: Some(0.001),\n\n price: Some(price),\n\n order_type: OrderType::Limit,\n\n side: OrderSide::Buy,\n\n time_in_force: Some(TimeInForce::FOK),\n\n ..OrderRequest::default()\n\n };\n\n match account.place_order(limit_buy).await {\n\n Ok(answer) => info!(\"{:?}\", answer),\n", "file_path": "examples/binance_endpoints.rs", "rank": 67, "score": 30.848200855981563 }, { "content": " /// # Examples\n\n /// ```rust,no_run\n\n /// use binance::{api::*, margin::*, config::*, rest_model::*};\n\n /// let margin: Margin = Binance::new_with_env(&Config::testnet());\n\n /// let margin_order = MarginOrder {\n\n /// symbol: \"BTCUSDT\".to_string(),\n\n /// side: OrderSide::Sell,\n\n /// order_type: OrderType::Limit,\n\n /// quantity: Some(0.001),\n\n /// quote_order_qty: None,\n\n /// price: Some(10.0),\n\n /// stop_price: Some(10.0),\n\n /// new_client_order_id: Some(\"my_id\".to_string()),\n\n /// iceberg_qty: Some(10.0),\n\n /// new_order_resp_type: OrderResponse::Ack,\n\n /// time_in_force: TimeInForce::FOK,\n\n /// side_effect_type: SideEffectType::NoSideEffect,\n\n /// is_isolated: None,\n\n /// };\n\n /// let transaction_id = tokio_test::block_on(margin.new_order(margin_order));\n", "file_path": "src/margin.rs", "rank": 69, "score": 30.76102828181866 }, { "content": " }\n\n Err(Error::Msg(\"Asset not found\".to_string()))\n\n }\n\n Err(e) => Err(e),\n\n }\n\n }\n\n\n\n /// All currently open orders for a single symbol\n\n /// # Examples\n\n /// ```rust,no_run\n\n /// use binance::{api::*, account::*, config::*};\n\n /// let account: Account = Binance::new_with_env(&Config::testnet());\n\n /// let orders = tokio_test::block_on(account.get_open_orders(\"BTCUSDT\"));\n\n /// assert!(orders.is_ok(), \"{:?}\", orders);\n\n /// ```\n\n pub async fn get_open_orders<S>(&self, symbol: S) -> Result<Vec<Order>>\n\n where\n\n S: Into<String>,\n\n {\n\n let mut parameters: BTreeMap<String, String> = BTreeMap::new();\n", "file_path": "src/account.rs", "rank": 72, "score": 28.70693879565259 }, { "content": "//!\n\n//! This example simply pings the main binance api\n\n//!\n\n//! ```rust\n\n//! # use std::io;\n\n//! use binance::general::General;\n\n//! use binance::api::Binance;\n\n//! use binance::errors::Error as BinanceLibError;\n\n//!\n\n//! #[tokio::main]\n\n//! async fn main() -> std::io::Result<()> {\n\n//! let general: General = Binance::new(None, None);\n\n//! let ping = general.ping().await;\n\n//! match ping {\n\n//! Ok(answer) => println!(\"{:?}\", answer),\n\n//! Err(err) => {\n\n//! match err {\n\n//! BinanceLibError::BinanceError { response } => match response.code {\n\n//! -1000_i16 => println!(\"An unknown error occured while processing the request\"),\n\n//! _ => println!(\"Unknown code {}: {}\", response.code, response.msg),\n", "file_path": "src/lib.rs", "rank": 73, "score": 28.6975790654948 }, { "content": " /// let margin: Margin = Binance::new_with_env(&Config::testnet());\n\n /// let start = tokio_test::block_on(margin.start());\n\n /// assert!(start.is_ok(), \"{:?}\", start);\n\n /// assert!(start.unwrap().listen_key.len() > 0)\n\n /// ```\n\n pub async fn start(&self) -> Result<UserDataStream> {\n\n let data = self.client.post(SAPI_USER_DATA_STREAM).await?;\n\n let user_data_stream: UserDataStream = from_str(data.as_str())?;\n\n\n\n Ok(user_data_stream)\n\n }\n\n\n\n /// Current open orders on a symbol\n\n /// # Examples\n\n /// ```rust,no_run\n\n /// use binance::{api::*, margin::*, config::*};\n\n /// let margin: Margin = Binance::new_with_env(&Config::testnet());\n\n /// let start = tokio_test::block_on(margin.start());\n\n /// assert!(start.is_ok(), \"{:?}\", start);\n\n /// let keep_alive = tokio_test::block_on(margin.keep_alive(&start.unwrap().listen_key));\n", "file_path": "src/margin.rs", "rank": 74, "score": 28.53623338034353 }, { "content": " Err(e) => error!(\"Error: {:?}\", e),\n\n }\n\n\n\n match market.get_agg_trades(\"btcusdt\", None, None, None, 500u16).await {\n\n Ok(AggTrades::AllAggTrades(answer)) => info!(\"First aggregated trade: {:?}\", answer[0]),\n\n Err(e) => error!(\"Error: {:?}\", e),\n\n }\n\n\n\n match market.get_klines(\"btcusdt\", \"5m\", 10u16, None, None).await {\n\n Ok(KlineSummaries::AllKlineSummaries(answer)) => info!(\"First kline: {:?}\", answer[0]),\n\n Err(e) => error!(\"Error: {:?}\", e),\n\n }\n\n\n\n match market.get_24h_price_stats(\"btcusdt\").await {\n\n Ok(answer) => info!(\"24hr price stats: {:?}\", answer),\n\n Err(e) => error!(\"Error: {:?}\", e),\n\n }\n\n\n\n match market.get_price(\"btcusdt\").await {\n\n Ok(answer) => info!(\"Price: {:?}\", answer),\n", "file_path": "examples/binance_futures.rs", "rank": 75, "score": 28.414604569814994 }, { "content": " side: OrderSide::Sell,\n\n time_in_force: Some(TimeInForce::FOK),\n\n ..OrderRequest::default()\n\n };\n\n match account.place_order(limit_sell).await {\n\n Ok(answer) => info!(\"{:?}\", answer),\n\n Err(e) => error!(\"Error: {}\", e),\n\n }\n\n\n\n let market_sell = OrderRequest {\n\n symbol: symbol.to_string(),\n\n quantity: Some(0.001),\n\n order_type: OrderType::Market,\n\n side: OrderSide::Sell,\n\n ..OrderRequest::default()\n\n };\n\n match account.place_order(market_sell).await {\n\n Ok(answer) => info!(\"{:?}\", answer),\n\n Err(e) => error!(\"Error: {}\", e),\n\n }\n", "file_path": "examples/binance_endpoints.rs", "rank": 76, "score": 27.582080400699514 }, { "content": " /// assert!(keep_alive.is_ok())\n\n /// ```\n\n pub async fn keep_alive(&self, listen_key: &str) -> Result<Success> {\n\n let data = self.client.put(SAPI_USER_DATA_STREAM, listen_key).await?;\n\n\n\n let success: Success = from_str(data.as_str())?;\n\n\n\n Ok(success)\n\n }\n\n\n\n /// Close the user stream\n\n /// # Examples\n\n /// ```rust,no_run\n\n /// use binance::{api::*, margin::*, config::*};\n\n /// let margin: Margin = Binance::new_with_env(&Config::testnet());\n\n /// let start = tokio_test::block_on(margin.start());\n\n /// assert!(start.is_ok(), \"{:?}\", start);\n\n /// let close = tokio_test::block_on(margin.close(&start.unwrap().listen_key));\n\n /// assert!(close.is_ok())\n\n /// ```\n", "file_path": "src/margin.rs", "rank": 77, "score": 27.20100256767218 }, { "content": " S: Into<String>,\n\n {\n\n let mut params: BTreeMap<String, String> = BTreeMap::new();\n\n params.insert(\"symbol\".into(), symbol.into());\n\n let request = build_signed_request(params, self.recv_window)?;\n\n let data = self.client.delete_signed(API_V3_OPEN_ORDERS, &request).await?;\n\n let order: Vec<Order> = from_str(data.as_str())?;\n\n Ok(order)\n\n }\n\n\n\n /// Check an order's status\n\n /// # Examples\n\n /// ```rust,no_run\n\n /// use binance::{api::*, account::*, config::*};\n\n /// let account: Account = Binance::new_with_env(&Config::testnet());\n\n /// let query = OrderStatusRequest {\n\n /// symbol: \"BTCUSDT\".to_string(),\n\n /// order_id: Some(1),\n\n /// orig_client_order_id: Some(\"my_id\".to_string()),\n\n /// recv_window: None\n", "file_path": "src/account.rs", "rank": 78, "score": 27.16891285222551 }, { "content": " parameters.insert(\"symbol\".into(), symbol.into());\n\n\n\n let request = build_signed_request(parameters, self.recv_window)?;\n\n let data = self.client.get_signed(API_V3_OPEN_ORDERS, &request).await?;\n\n let order: Vec<Order> = from_str(data.as_str())?;\n\n\n\n Ok(order)\n\n }\n\n\n\n /// All orders for the account\n\n /// # Examples\n\n /// ```rust,no_run\n\n /// use binance::{api::*, account::*, config::*};\n\n /// let account: Account = Binance::new_with_env(&Config::testnet());\n\n /// let query = OrdersQuery {\n\n /// symbol: \"BTCUSDT\".to_string(),\n\n /// order_id: None,\n\n /// start_time: None,\n\n /// end_time: None,\n\n /// limit: None,\n", "file_path": "src/account.rs", "rank": 79, "score": 27.008719730588282 }, { "content": " /// quote_order_qty: None,\n\n /// price: Some(10.0),\n\n /// stop_price: Some(10.0),\n\n /// new_client_order_id: Some(\"my_id\".to_string()),\n\n /// iceberg_qty: Some(10.0),\n\n /// new_order_resp_type: OrderResponse::Ack,\n\n /// time_in_force: TimeInForce::FOK,\n\n /// side_effect_type: SideEffectType::NoSideEffect,\n\n /// is_isolated: None,\n\n /// };\n\n /// let transaction_id = tokio_test::block_on(margin.trade(margin_order));\n\n /// assert!(transaction_id.is_ok(), \"{:?}\", transaction_id);\n\n /// ```\n\n pub async fn trade(&self, margin_order: MarginOrder) -> Result<MarginOrderResult> {\n\n self.client\n\n .post_signed_p(SAPI_V1_MARGIN_ORDER, margin_order, self.recv_window)\n\n .await\n\n }\n\n\n\n /// Post a new order for margin account.\n", "file_path": "src/margin.rs", "rank": 80, "score": 26.84808678603796 }, { "content": " Ok(answer) => info!(\"Exchange information: {:?}\", answer),\n\n Err(e) => error!(\"Error: {:?}\", e),\n\n }\n\n\n\n match general.get_symbol_info(\"btcusdt\").await {\n\n Ok(answer) => info!(\"Symbol information: {:?}\", answer),\n\n Err(e) => error!(\"Error: {:?}\", e),\n\n }\n\n}\n\n\n\nasync fn market_data() {\n\n let market: FuturesMarket = Binance::new(None, None);\n\n\n\n match market.get_depth(\"btcusdt\").await {\n\n Ok(answer) => info!(\"Depth update ID: {:?}\", answer.last_update_id),\n\n Err(e) => error!(\"Error: {:?}\", e),\n\n }\n\n\n\n match market.get_trades(\"btcusdt\").await {\n\n Ok(Trades::AllTrades(answer)) => info!(\"First trade: {:?}\", answer[0]),\n", "file_path": "examples/binance_futures.rs", "rank": 81, "score": 26.282574346603862 }, { "content": " pub async fn get_average_price<S>(&self, symbol: S) -> Result<AveragePrice>\n\n where\n\n S: Into<String>,\n\n {\n\n let request = self.symbol_request(symbol);\n\n let data = self.client.get(API_V3_AVG_PRICE, &request).await?;\n\n let average_price: AveragePrice = from_str(data.as_str())?;\n\n\n\n Ok(average_price)\n\n }\n\n\n\n /// Symbols order book ticker\n\n /// -> Best price/qty on the order book for ALL symbols.\n\n /// # Examples\n\n /// ```rust\n\n /// use binance::{api::*, market::*, config::*};\n\n /// let market: Market = Binance::new_with_env(&Config::default());\n\n /// let tickers = tokio_test::block_on(market.get_all_book_tickers());\n\n /// assert!(tickers.is_ok(), \"{:?}\", tickers);\n\n /// ```\n", "file_path": "src/market.rs", "rank": 82, "score": 26.103708034903164 }, { "content": " let request = build_signed_request_p(order, recv_window)?;\n\n let data = self.client.post_signed(API_V3_ORDER, &request).await?;\n\n let transaction: Transaction = from_str(data.as_str())?;\n\n\n\n Ok(transaction)\n\n }\n\n\n\n /// Place a test order\n\n ///\n\n /// Despite being a test, this order is still validated before calls\n\n /// This order is sandboxed: it is validated, but not sent to the matching engine.\n\n /// # Examples\n\n /// ```rust,no_run\n\n /// use binance::{api::*, account::*, config::*, rest_model::*};\n\n /// let account: Account = Binance::new_with_env(&Config::testnet());\n\n /// let limit_buy = OrderRequest {\n\n /// symbol: \"BTCUSDT\".to_string(),\n\n /// quantity: Some(10.0),\n\n /// price: Some(0.014000),\n\n /// order_type: OrderType::Limit,\n", "file_path": "src/account.rs", "rank": 83, "score": 26.09304162255596 }, { "content": " /// assert_eq!(bids_len, 50);\n\n /// ```\n\n pub async fn get_custom_depth<S>(&self, symbol: S, limit: u16) -> Result<OrderBook>\n\n where\n\n S: Into<String>,\n\n {\n\n let mut parameters: BTreeMap<String, String> = BTreeMap::new();\n\n parameters.insert(\"symbol\".into(), symbol.into());\n\n parameters.insert(\"limit\".into(), limit.to_string());\n\n\n\n let request = build_request(&parameters);\n\n let data = self.client.get(API_V3_DEPTH, &request).await?;\n\n let order_book: OrderBook = from_str(data.as_str())?;\n\n\n\n Ok(order_book)\n\n }\n\n\n\n /// Latest price for ALL symbols.\n\n /// # Examples\n\n /// ```rust\n", "file_path": "src/market.rs", "rank": 84, "score": 25.908792312111707 }, { "content": " Ok(answer) => info!(\"{:?}\", answer),\n\n Err(e) => error!(\"Error: {}\", e),\n\n }\n\n\n\n match account.get_balance(\"BTC\").await {\n\n Ok(answer) => info!(\"{:?}\", answer),\n\n Err(e) => error!(\"Error: {}\", e),\n\n }\n\n\n\n match account.trade_history(symbol).await {\n\n Ok(answer) => info!(\"{:?}\", answer),\n\n Err(e) => error!(\"Error: {}\", e),\n\n }\n\n}\n\n\n\nasync fn market_data() {\n\n let market: Market = Binance::new(None, None);\n\n\n\n // Order book\n\n match market.get_depth(\"BNBETH\").await {\n", "file_path": "examples/binance_endpoints.rs", "rank": 85, "score": 25.845376718616734 }, { "content": " pub async fn get_depth<S>(&self, symbol: S) -> Result<OrderBook>\n\n where\n\n S: Into<String>,\n\n {\n\n let request = self.symbol_request(symbol);\n\n let data = self.client.get(API_V3_DEPTH, &request).await?;\n\n let order_book: OrderBook = from_str(data.as_str())?;\n\n\n\n Ok(order_book)\n\n }\n\n\n\n /// Order book with a custom depth limit\n\n /// Supported limits are: 5, 10, 20, 50, 100, 500, 1000, 5000\n\n /// # Examples\n\n /// ```rust\n\n /// use binance::{api::*, market::*, config::*};\n\n /// let market: Market = Binance::new_with_env(&Config::default());\n\n /// let orderbook = tokio_test::block_on(market.get_custom_depth(\"BTCUSDT\".to_string(), 50));\n\n /// assert!(orderbook.is_ok(), \"{:?}\", orderbook);\n\n /// let bids_len = orderbook.unwrap().bids.len();\n", "file_path": "src/market.rs", "rank": 86, "score": 25.835678648136547 }, { "content": " let data = self.client.get(API_V3_24H_TICKER, &request).await?;\n\n\n\n let stats: PriceStats = from_str(data.as_str())?;\n\n\n\n Ok(stats)\n\n }\n\n\n\n /// Returns up to 'limit' klines for given symbol and interval (\"1m\", \"5m\", ...)\n\n /// https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#klinecandlestick-data\n\n /// # Examples\n\n /// ```rust\n\n /// use binance::{api::*, market::*, config::*};\n\n /// let market: Market = Binance::new_with_env(&Config::default());\n\n /// let klines = tokio_test::block_on(market.get_klines(\"BTCUSDT\", \"1m\", None, None, None));\n\n /// assert!(klines.is_ok(), \"{:?}\", klines);\n\n /// ```\n\n pub async fn get_klines<S1, S2, S3, S4, S5>(\n\n &self,\n\n symbol: S1,\n\n interval: S2,\n", "file_path": "src/market.rs", "rank": 87, "score": 25.70621350938302 }, { "content": "\n\n let result = general.get_server_time().await;\n\n match result {\n\n Ok(answer) => info!(\"Server Time: {}\", answer.server_time),\n\n Err(e) => error!(\"Error: {}\", e),\n\n }\n\n\n\n let result = general.exchange_info().await;\n\n match result {\n\n Ok(answer) => info!(\"Exchange information: {:?}\", answer),\n\n Err(e) => error!(\"Error: {}\", e),\n\n }\n\n}\n\n\n\nasync fn account() {\n\n let market: Market = Binance::new(None, None);\n\n let account: Account = Binance::new_with_env(&Config::testnet());\n\n let symbol = \"BTCUSDT\";\n\n let SymbolPrice { price, .. } = market.get_price(symbol).await.unwrap();\n\n match account.get_account().await {\n", "file_path": "examples/binance_endpoints.rs", "rank": 88, "score": 25.514640270477948 }, { "content": " url.set_query(Some(&format!(\"streams={}\", combined_stream(endpoints))));\n\n\n\n match connect_async(url).await {\n\n Ok(answer) => {\n\n self.socket = Some(answer);\n\n Ok(())\n\n }\n\n Err(e) => Err(Error::Msg(format!(\"Error during handshake {}\", e))),\n\n }\n\n }\n\n\n\n /// Connect to a websocket endpoint\n\n pub async fn connect(&mut self, endpoint: &str) -> Result<()> {\n\n let wss: String = format!(\"{}/{}/{}\", self.conf.ws_endpoint, WS_ENDPOINT, endpoint);\n\n let url = Url::parse(&wss)?;\n\n\n\n match connect_async(url).await {\n\n Ok(answer) => {\n\n self.socket = Some(answer);\n\n Ok(())\n", "file_path": "src/websockets.rs", "rank": 89, "score": 25.46635631711862 }, { "content": " Sell,\n\n}\n\n\n\n/// By default, buy\n\nimpl Default for OrderSide {\n\n fn default() -> Self { Self::Buy }\n\n}\n\n\n\n/// Order types, the following restrictions apply\n\n/// LIMIT_MAKER are LIMIT orders that will be rejected if they would immediately match and trade as a taker.\n\n/// STOP_LOSS and TAKE_PROFIT will execute a MARKET order when the stopPrice is reached.\n\n/// Any LIMIT or LIMIT_MAKER type order can be made an iceberg order by sending an icebergQty.\n\n/// Any order with an icebergQty MUST have timeInForce set to GTC.\n\n/// MARKET orders using quantity specifies how much a user wants to buy or sell based on the market price.\n\n/// MARKET orders using quoteOrderQty specifies the amount the user wants to spend (when buying) or receive (when selling) of the quote asset; the correct quantity will be determined based on the market liquidity and quoteOrderQty.\n\n/// MARKET orders using quoteOrderQty will not break LOT_SIZE filter rules; the order will execute a quantity that will have the notional value as close as possible to quoteOrderQty.\n\n#[derive(Debug, Serialize, Deserialize, Clone)]\n\n#[serde(rename_all = \"SCREAMING_SNAKE_CASE\")]\n\npub enum OrderType {\n\n Limit,\n", "file_path": "src/rest_model.rs", "rank": 90, "score": 25.38071377830952 }, { "content": " let message = socket.next().await.unwrap()?;\n\n\n\n match message {\n\n Message::Text(msg) => {\n\n if msg.is_empty() {\n\n return Ok(());\n\n }\n\n let event: WE = from_str(msg.as_str())?;\n\n (self.handler)(event)?;\n\n }\n\n Message::Ping(_) | Message::Pong(_) | Message::Binary(_) => {}\n\n Message::Close(e) => {\n\n return Err(Error::Msg(format!(\"Disconnected {:?}\", e)));\n\n }\n\n }\n\n }\n\n }\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/websockets.rs", "rank": 91, "score": 25.062159505271524 }, { "content": " pub async fn get_all_book_tickers(&self) -> Result<BookTickers> {\n\n let data = self.client.get(API_V3_BOOK_TICKER, \"\").await?;\n\n\n\n let book_tickers: BookTickers = from_str(data.as_str())?;\n\n\n\n Ok(book_tickers)\n\n }\n\n\n\n /// -> Best price/qty on the order book for ONE symbol\n\n /// # Examples\n\n /// ```rust\n\n /// use binance::{api::*, market::*, config::*};\n\n /// let market: Market = Binance::new_with_env(&Config::default());\n\n /// let tickers = tokio_test::block_on(market.get_book_ticker(\"BTCUSDT\"));\n\n /// assert!(tickers.is_ok(), \"{:?}\", tickers);\n\n /// ```\n\n pub async fn get_book_ticker<S>(&self, symbol: S) -> Result<Tickers>\n\n where\n\n S: Into<String>,\n\n {\n", "file_path": "src/market.rs", "rank": 92, "score": 24.956618706317148 }, { "content": " #[serde(with = \"string_or_float\")]\n\n pub executed_qty: f64,\n\n pub order_id: u64,\n\n #[serde(with = \"string_or_float\")]\n\n pub orig_qty: f64,\n\n pub orig_type: String,\n\n #[serde(with = \"string_or_float\")]\n\n pub price: f64,\n\n pub reduce_only: bool,\n\n pub side: String,\n\n pub position_side: String,\n\n pub status: String,\n\n #[serde(with = \"string_or_float\")]\n\n pub stop_price: f64,\n\n pub close_position: bool,\n\n pub symbol: String,\n\n pub time_in_force: String,\n\n #[serde(rename = \"type\")]\n\n pub type_name: String,\n\n #[serde(default, with = \"string_or_float_opt\")]\n", "file_path": "src/futures/rest_model.rs", "rank": 93, "score": 24.881634271119673 }, { "content": "pub struct Transaction {\n\n pub symbol: String,\n\n pub order_id: u64,\n\n pub client_order_id: String,\n\n pub transact_time: u64,\n\n #[serde(with = \"string_or_float\")]\n\n pub price: f64,\n\n #[serde(with = \"string_or_float\")]\n\n pub orig_qty: f64,\n\n #[serde(with = \"string_or_float\")]\n\n pub executed_qty: f64,\n\n #[serde(with = \"string_or_float\")]\n\n pub cummulative_quote_qty: f64,\n\n pub status: OrderStatus,\n\n pub time_in_force: TimeInForce,\n\n #[serde(rename = \"type\")]\n\n pub order_type: OrderType,\n\n pub side: OrderSide,\n\n pub fills: Vec<Fill>,\n\n}\n", "file_path": "src/rest_model.rs", "rank": 94, "score": 24.746605099644597 }, { "content": " asset: symbol.into(),\n\n amount: qty.into(),\n\n is_isolated: is_isolated.map(bool_to_string),\n\n symbol: isolated_asset,\n\n };\n\n self.client\n\n .post_signed_p(SAPI_V1_MARGIN_REPAY, loan, self.recv_window)\n\n .await\n\n }\n\n\n\n /// Post a new order for margin account.\n\n /// # Examples\n\n /// ```rust,no_run\n\n /// use binance::{api::*, margin::*, config::*, rest_model::*};\n\n /// let margin: Margin = Binance::new_with_env(&Config::testnet());\n\n /// let margin_order = MarginOrder {\n\n /// symbol: \"BTCUSDT\".to_string(),\n\n /// side: OrderSide::Sell,\n\n /// order_type: OrderType::Limit,\n\n /// quantity: Some(0.001),\n", "file_path": "src/margin.rs", "rank": 95, "score": 24.463307029086543 }, { "content": " time_in_force: None,\n\n qty: Some(qty.into()),\n\n reduce_only: None,\n\n price: None,\n\n stop_price: None,\n\n close_position: None,\n\n activation_price: None,\n\n callback_rate: None,\n\n working_type: None,\n\n price_protect: None,\n\n };\n\n self.post_order(order).await\n\n }\n\n\n\n /// Place a cancellation order\n\n pub async fn cancel_order(&self, o: OrderCancellation) -> Result<CanceledOrder> {\n\n let recv_window = o.recv_window.unwrap_or(self.recv_window);\n\n self.client.delete_signed_p(\"/fapi/v1/order\", &o, recv_window).await\n\n }\n\n\n", "file_path": "src/futures/account.rs", "rank": 96, "score": 24.3215576560688 }, { "content": " pub recv_window: u64,\n\n}\n\n\n\nimpl Margin {\n\n /// Execute transfer between spot account and margin account.\n\n /// # Examples\n\n /// ```rust,no_run\n\n /// use binance::{api::*, margin::*, config::*, rest_model::*};\n\n /// let margin: Margin = Binance::new_with_env(&Config::testnet());\n\n /// let transaction_id = tokio_test::block_on(margin.transfer(\"BTCUSDT\", 0.001, MarginTransferType::FromMainToMargin));\n\n /// assert!(transaction_id.is_ok(), \"{:?}\", transaction_id);\n\n /// ```\n\n pub async fn transfer<S, F>(&self, symbol: S, qty: F, transfer_type: MarginTransferType) -> Result<TransactionId>\n\n where\n\n S: Into<String>,\n\n F: Into<f64>,\n\n {\n\n let transfer: Transfer = Transfer {\n\n asset: symbol.into(),\n\n amount: qty.into(),\n", "file_path": "src/margin.rs", "rank": 97, "score": 24.270955305856337 }, { "content": " /// This methods validates the order request before sending, making sure it complies with Binance rules\n\n /// # Examples\n\n /// ```rust,no_run\n\n /// use binance::{api::*, account::*, config::*, rest_model::*};\n\n /// let account: Account = Binance::new_with_env(&Config::testnet());\n\n /// let limit_buy = OrderRequest {\n\n /// symbol: \"BTCUSDT\".to_string(),\n\n /// quantity: Some(10.0),\n\n /// price: Some(0.014000),\n\n /// order_type: OrderType::Limit,\n\n /// side: OrderSide::Buy,\n\n /// time_in_force: Some(TimeInForce::FOK),\n\n /// ..OrderRequest::default()\n\n /// };\n\n /// let transaction = tokio_test::block_on(account.place_order(limit_buy));\n\n /// assert!(transaction.is_ok(), \"{:?}\", transaction);\n\n /// ```\n\n pub async fn place_order(&self, order: OrderRequest) -> Result<Transaction> {\n\n let _ = order.valid()?;\n\n let recv_window = order.recv_window.unwrap_or(self.recv_window);\n", "file_path": "src/account.rs", "rank": 98, "score": 24.1736622905966 }, { "content": " /// ```\n\n pub async fn get_price<S>(&self, symbol: S) -> Result<SymbolPrice>\n\n where\n\n S: Into<String>,\n\n {\n\n let request = self.symbol_request(symbol);\n\n let data = self.client.get(API_V3_TICKER_PRICE, &request).await?;\n\n let symbol_price: SymbolPrice = from_str(data.as_str())?;\n\n\n\n Ok(symbol_price)\n\n }\n\n\n\n /// Average price for ONE symbol.\n\n /// # Examples\n\n /// ```rust\n\n /// use binance::{api::*, market::*, config::*};\n\n /// let market: Market = Binance::new_with_env(&Config::default());\n\n /// let avg_price = tokio_test::block_on(market.get_average_price(\"BTCUSDT\"));\n\n /// assert!(avg_price.is_ok(), \"{:?}\", avg_price);\n\n /// ```\n", "file_path": "src/market.rs", "rank": 99, "score": 24.10914413679937 } ]
Rust
src/adoptopenjdk/mod.rs
wherkamp/adoptopenjdk-installer
d9b94c16d20fbcd4fbd05b15b070a877daa088d2
use reqwest::{StatusCode, Response, Body, Client}; use std::error::Error; use std::fmt::{Formatter, Display}; use crate::adoptopenjdk::response::AvailableReleases; use serde::de::DeserializeOwned; use reqwest::header::{USER_AGENT, HeaderValue, HeaderMap}; use std::path::{Path, PathBuf}; use crate::utils::utils; use std::num::ParseIntError; use url::ParseError; pub mod response; pub mod request; #[derive(Debug)] pub enum AdoptOpenJDKError { HTTPError(StatusCode), ReqwestError(reqwest::Error), JSONError(serde_json::Error), TOMLDeError(toml::de::Error), TOMLSeError(toml::ser::Error), STDIoError(std::io::Error), Custom(String), } impl Display for AdoptOpenJDKError { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match self { AdoptOpenJDKError::HTTPError(status) => { let string = format!("The API returned a non-success error code {}", status.clone().as_str()); return write!(f, "{}", string); } AdoptOpenJDKError::ReqwestError(_) => { let x = "An error occurred while processing the HTTP response"; return write!(f, "{}", x); } AdoptOpenJDKError::JSONError(_) => { let x = "The JSON sent by AdoptOpenJDK did not match what this app was expecting"; return write!(f, "{}", x); } AdoptOpenJDKError::Custom(s) => { return write!(f, "{}", s.as_str()); } AdoptOpenJDKError::STDIoError(err) => { let x = "IO Error"; return write!(f, "{} {}", x, err); } AdoptOpenJDKError::TOMLDeError(e) => { return write!(f, "TOML Error {}", e); } AdoptOpenJDKError::TOMLSeError(e) => { return write!(f, "TOML Error {}", e); } } } } impl Error for AdoptOpenJDKError {} impl From<reqwest::Error> for AdoptOpenJDKError { fn from(err: reqwest::Error) -> AdoptOpenJDKError { AdoptOpenJDKError::ReqwestError(err) } } impl From<ParseIntError> for AdoptOpenJDKError { fn from(err: ParseIntError) -> AdoptOpenJDKError { AdoptOpenJDKError::Custom(format!("{}", err)) } } impl From<std::io::Error> for AdoptOpenJDKError { fn from(err: std::io::Error) -> AdoptOpenJDKError { AdoptOpenJDKError::STDIoError(err) } } impl From<serde_json::Error> for AdoptOpenJDKError { fn from(err: serde_json::Error) -> AdoptOpenJDKError { AdoptOpenJDKError::JSONError(err) } } impl From<toml::de::Error> for AdoptOpenJDKError { fn from(err: toml::de::Error) -> AdoptOpenJDKError { AdoptOpenJDKError::TOMLDeError(err) } } impl From<toml::ser::Error> for AdoptOpenJDKError { fn from(err: toml::ser::Error) -> AdoptOpenJDKError { AdoptOpenJDKError::TOMLSeError(err) } } impl From<ParseError> for AdoptOpenJDKError { fn from(err: ParseError) -> AdoptOpenJDKError { AdoptOpenJDKError::Custom(format!("Unable to parse URL {}", err)) } } pub struct AdoptOpenJDK { client: Client, user_agent: String, } impl AdoptOpenJDK { pub fn new( user_agent: String, ) -> AdoptOpenJDK { let client = Client::new(); AdoptOpenJDK { client, user_agent, } } pub async fn get(&self, url: &str) -> Result<Response, reqwest::Error> { let string = self.build_url(url); let mut headers = HeaderMap::new(); headers.insert( USER_AGENT, HeaderValue::from_str(&*self.user_agent).unwrap(), ); self.client.get(string).headers(headers).send().await } pub async fn post( &self, url: &str, body: Body, ) -> Result<Response, reqwest::Error> { let string = self.build_url(url); let mut headers = HeaderMap::new(); headers.insert( USER_AGENT, HeaderValue::from_str(&*self.user_agent).unwrap(), ); self.client .post(string) .body(body) .headers(headers) .send() .await } pub async fn get_json<T: DeserializeOwned>( &self, url: &str) -> Result<T, AdoptOpenJDKError> { let x = self.get(url).await; return AdoptOpenJDK::respond::<T>(x).await; } pub async fn post_json<T: DeserializeOwned>( &self, url: &str, body: Body, ) -> Result<T, AdoptOpenJDKError> { let x = self.post(url, body).await; return AdoptOpenJDK::respond::<T>(x).await; } pub fn build_url(&self, dest: &str) -> String { format!("https://api.adoptium.net/v3/{}", dest) } pub async fn respond<T: DeserializeOwned>( result: Result<Response, reqwest::Error>, ) -> Result<T, AdoptOpenJDKError> { if let Ok(response) = result { let code = response.status(); if !code.is_success() { return Err(AdoptOpenJDKError::HTTPError(code)); } let value = response.json::<T>().await; if let Ok(about) = value { return Ok(about); } else if let Err(response) = value { return Err(AdoptOpenJDKError::from(response)); } } else if let Err(response) = result { return Err(AdoptOpenJDKError::from(response)); } return Err(AdoptOpenJDKError::Custom("IDK".to_string())); } pub async fn get_releases(&self) -> Result<AvailableReleases, AdoptOpenJDKError> { return self.get_json("info/available_releases").await; } pub async fn download_binary(&self, request: request::LatestBinary, file: &Path) -> Result<PathBuf, AdoptOpenJDKError> { let x = self.build_url(format!("binary/latest/{}", request.to_string()).as_str()); println!("{}", &x); let result = utils::download(x.as_str(), file, format!("Adopt Open JDK {}", request.to_string()).as_str()).await; return result; } }
use reqwest::{StatusCode, Response, Body, Client}; use std::error::Error; use std::fmt::{Formatter, Display}; use crate::adoptopenjdk::response::AvailableReleases; use serde::de::DeserializeOwned; use reqwest::header::{USER_AGENT, HeaderValue, HeaderMap}; use std::path::{Path, PathBuf}; use crate::utils::utils; use std::num::ParseIntError; use url::ParseError; pub mod response; pub mod request; #[derive(Debug)] pub enum AdoptOpenJDKError { HTTPError(StatusCode), ReqwestError(reqwest::Error), JSONError(serde_json::Error), TOMLDeError(toml::de::Error), TOMLSeError(toml::ser::Error), STDIoError(std::io::Error), Custom(String), } impl Display for AdoptOpenJDKError { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match self { AdoptOpenJDKError::HTTPError(status) => { let string = format!("The API returned a non-success error code {}", status.clone().as_str()); return write!(f, "{}", string); } AdoptOpenJDKError::ReqwestError(_) => { let x = "An error occurred while processing the HTTP response"; return write!(f, "{}", x); } AdoptOpenJDKError::JSONError(_) => { let x = "The JSON sent by AdoptOpenJDK did not match what this app was expecting"; return write!(f, "{}", x); } AdoptOpenJDKError::Custom(s) => { return write!(f, "{}", s.as_str()); } AdoptOpenJDKError::STDIoError(err) => { let x = "IO Error"; return write!(f, "{} {}", x, err); } AdoptOpenJDKError::TOMLDeError(e) => { return write!(f, "TOML Error {}", e); } AdoptOpenJDKError::TOMLSeError(e) => { return write!(f, "TOML Error {}", e); } } } } impl Error for AdoptOpenJDKError {} impl From<reqwest::Error> for AdoptOpenJDKError { fn from(err: reqwest::Error) -> AdoptOpenJDKError { AdoptOpenJDKError::ReqwestError(err) } } impl From<ParseIntError> for AdoptOpenJDKError { fn from(err: ParseIntError) -> AdoptOpenJDKError { AdoptOpenJDKError::Custom(format!("{}", err)) } } impl From<std::io::Error> for AdoptOpenJDKError { fn from(err: std::io::Error) -> AdoptOpenJDKError { AdoptOpenJDKError::STDIoError(err) } } impl From<serde_json::Error> for AdoptOpenJDKError { fn from(err: serde_json::Error) -> AdoptOpenJDKError { AdoptOpenJDKError::JSONError(err) } } impl From<toml::de::Error> for AdoptOpenJDKError { fn from(err: toml::de::Error) -> AdoptOpenJDKError { AdoptOpenJDKError::TOMLDeError(err) } } impl From<toml::ser::Error> for AdoptOpenJDKError { fn from(err: toml::ser::Error) -> AdoptOpenJDKError { AdoptOpenJDKError::TOMLSeError(err) } } impl From<ParseError> for AdoptOpenJDKError { fn from(err: ParseError) -> AdoptOpenJDKError { AdoptOpenJDKError::Custom(format!("Unable to parse URL {}", err)) } } pub struct AdoptOpenJDK { client: Client, user_agent: String, } impl AdoptOpenJDK { pub fn new( user_agent: String, ) -> AdoptOpenJDK { let client = Client::new(); AdoptOpenJDK { client, user_agent, } } pub async fn get(&self, url: &str) -> Result<Resp
dest: &str) -> String { format!("https://api.adoptium.net/v3/{}", dest) } pub async fn respond<T: DeserializeOwned>( result: Result<Response, reqwest::Error>, ) -> Result<T, AdoptOpenJDKError> { if let Ok(response) = result { let code = response.status(); if !code.is_success() { return Err(AdoptOpenJDKError::HTTPError(code)); } let value = response.json::<T>().await; if let Ok(about) = value { return Ok(about); } else if let Err(response) = value { return Err(AdoptOpenJDKError::from(response)); } } else if let Err(response) = result { return Err(AdoptOpenJDKError::from(response)); } return Err(AdoptOpenJDKError::Custom("IDK".to_string())); } pub async fn get_releases(&self) -> Result<AvailableReleases, AdoptOpenJDKError> { return self.get_json("info/available_releases").await; } pub async fn download_binary(&self, request: request::LatestBinary, file: &Path) -> Result<PathBuf, AdoptOpenJDKError> { let x = self.build_url(format!("binary/latest/{}", request.to_string()).as_str()); println!("{}", &x); let result = utils::download(x.as_str(), file, format!("Adopt Open JDK {}", request.to_string()).as_str()).await; return result; } }
onse, reqwest::Error> { let string = self.build_url(url); let mut headers = HeaderMap::new(); headers.insert( USER_AGENT, HeaderValue::from_str(&*self.user_agent).unwrap(), ); self.client.get(string).headers(headers).send().await } pub async fn post( &self, url: &str, body: Body, ) -> Result<Response, reqwest::Error> { let string = self.build_url(url); let mut headers = HeaderMap::new(); headers.insert( USER_AGENT, HeaderValue::from_str(&*self.user_agent).unwrap(), ); self.client .post(string) .body(body) .headers(headers) .send() .await } pub async fn get_json<T: DeserializeOwned>( &self, url: &str) -> Result<T, AdoptOpenJDKError> { let x = self.get(url).await; return AdoptOpenJDK::respond::<T>(x).await; } pub async fn post_json<T: DeserializeOwned>( &self, url: &str, body: Body, ) -> Result<T, AdoptOpenJDKError> { let x = self.post(url, body).await; return AdoptOpenJDK::respond::<T>(x).await; } pub fn build_url(&self,
random
[ { "content": "/// Stolen from Tar depend and modified to fit my needs\n\npub fn unpack(mut archive: Archive<GzDecoder<File>>, dst: &Path) -> Result<String, AdoptOpenJDKError> {\n\n let dst = &dst.canonicalize().unwrap_or(dst.to_path_buf());\n\n let mut first = None;\n\n let mut directories = Vec::new();\n\n for entry in archive.entries()? {\n\n let mut file = entry?;\n\n if file.header().entry_type() == tar::EntryType::Directory {\n\n if first.is_none() {\n\n first = Some(file.path().unwrap().to_str().unwrap().to_string());\n\n }\n\n directories.push(file);\n\n } else {\n\n file.unpack_in(dst)?;\n\n }\n\n }\n\n for mut dir in directories {\n\n dir.unpack_in(dst)?;\n\n }\n\n\n\n Ok(first.unwrap())\n", "file_path": "src/installer/mod.rs", "rank": 0, "score": 71381.51974043941 }, { "content": "use serde::Deserialize;\n\nuse serde::Serialize;\n\nuse crate::adoptopenjdk::response::{Architecture, HeapSize, Imagetype, JVMImpl, OS, ReleaseType, Vendor};\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n\npub struct LatestBinary {\n\n pub arch: Architecture,\n\n pub feature_version: i64,\n\n pub heap_size: HeapSize,\n\n pub image_type: Imagetype,\n\n pub jvm_impl: JVMImpl,\n\n pub os: OS,\n\n pub release_type: ReleaseType,\n\n pub vendor: Vendor,\n\n\n\n}\n\n\n\nimpl ToString for LatestBinary {\n\n fn to_string(&self) -> String {\n\n format!(\"{feature_version}/{release_type}/{os}/{arch}/{image_type}/{jvm_impl}/{heap_size}/{vendor}\",\n\n arch = self.arch,\n\n feature_version = self.feature_version,\n\n release_type = self.release_type,\n\n os = self.os,\n\n image_type = self.image_type,\n\n jvm_impl = self.jvm_impl,\n\n heap_size = self.heap_size,\n\n vendor = self.vendor)\n\n }\n\n}", "file_path": "src/adoptopenjdk/request.rs", "rank": 1, "score": 36040.674316139965 }, { "content": "pub mod settings;\n\n\n\nuse std::path::{PathBuf, Path};\n\nuse crate::adoptopenjdk::AdoptOpenJDKError;\n\nuse std::fs::{File, create_dir_all, read_to_string, OpenOptions, remove_dir_all, remove_file};\n\nuse flate2::read::GzDecoder;\n\nuse tar::{Archive};\n\nuse std::process::Command;\n\n\n\nuse crate::installer::settings::{Install, Settings};\n\nuse std::io::Write;\n\n\n\n/// Stolen from Tar depend and modified to fit my needs\n", "file_path": "src/installer/mod.rs", "rank": 12, "score": 16719.940273029286 }, { "content": " let javadoc = path.clone().join(\"bin\").join(\"javadoc\");\n\n Command::new(\"update-alternatives\").arg(\"--remove\").arg(\"java\").arg(java.to_str().unwrap()).spawn()?;\n\n Command::new(\"update-alternatives\").arg(\"--remove\").arg(\"javac\").arg(javac.to_str().unwrap()).spawn()?;\n\n Command::new(\"update-alternatives\").arg(\"--remove\").arg(\"javadoc\").arg(javadoc.to_str().unwrap()).spawn()?;\n\n remove_dir_all(path)?;\n\n Ok(())\n\n }\n\n pub fn get_settings(&self) -> Result<Settings, AdoptOpenJDKError> {\n\n let buf = Path::new(\"/etc\").join(\"adoptopenjdk\").join(\"settings.toml\");\n\n let result = read_to_string(buf)?;\n\n return toml::from_str(result.as_str()).map_err(AdoptOpenJDKError::from);\n\n }\n\n pub fn update_settings(&self, settings: Settings) -> Result<(), AdoptOpenJDKError> {\n\n let buf = Path::new(\"/etc\").join(\"adoptopenjdk\").join(\"settings.toml\");\n\n if !buf.exists() {\n\n let x = buf.parent().unwrap();\n\n if !x.exists() {\n\n create_dir_all(x)?;\n\n }\n\n }else {\n", "file_path": "src/installer/mod.rs", "rank": 13, "score": 16719.8841517498 }, { "content": "}\n\n\n\npub struct Installer;\n\n\n\nimpl Installer {\n\n pub fn install(&self, path: PathBuf, install: Install) -> Result<bool, AdoptOpenJDKError> {\n\n println!(\"Installing: {} {}\", install.jvm_version, install.jvm_impl.to_string());\n\n let file = File::open(path.clone())?;\n\n let tar = GzDecoder::new(file);\n\n let archive = Archive::new(tar);\n\n let mut settings = self.get_settings()?;\n\n\n\n let buf = Path::new(settings.install_location.as_str()).join(install.jvm_impl.to_string());\n\n if !buf.exists() {\n\n create_dir_all(&buf)?;\n\n }\n\n let string = unpack(archive, &buf)?;\n\n let path_two = buf.join(string);\n\n let mut install = install.clone();\n\n install.set_location(path_two.clone().to_str().unwrap().to_string());\n", "file_path": "src/installer/mod.rs", "rank": 14, "score": 16719.39340531782 }, { "content": " remove_file(&buf)?;\n\n }\n\n let string = toml::to_string(&settings)?;\n\n let mut file = OpenOptions::new().write(true).read(true).create(true).open(buf)?;\n\n file.write_all(string.as_bytes())?;\n\n Ok(())\n\n }\n\n pub fn contains_install(&self, install: &Install) -> Result<bool, AdoptOpenJDKError> {\n\n let settings = self.get_settings()?;\n\n Ok(settings.installs.contains(install))\n\n }\n\n pub fn does_settings_exist(&self) -> bool {\n\n Path::new(\"/etc\").join(\"adoptopenjdk\").join(\"settings.toml\").exists()\n\n }\n\n}\n", "file_path": "src/installer/mod.rs", "rank": 15, "score": 16719.157784546576 }, { "content": " settings.add_install(install);\n\n self.update_settings(settings)?;\n\n let java = path_two.clone().join(\"bin\").join(\"java\");\n\n let javac = path_two.clone().join(\"bin\").join(\"javac\");\n\n let javadoc = path_two.clone().join(\"bin\").join(\"javadoc\");\n\n // sudo update-alternatives --install /usr/bin/java java <path> 1\n\n Command::new(\"chmod\").arg(\"-Rv\").arg(\"755\").arg(path_two.to_str().unwrap()).spawn()?;\n\n Command::new(\"update-alternatives\").arg(\"--install\").arg(\"/usr/bin/java\").arg(\"java\").arg(java.to_str().unwrap()).arg(\"1\").spawn()?;\n\n Command::new(\"update-alternatives\").arg(\"--install\").arg(\"/usr/bin/javac\").arg(\"javac\").arg(javac.to_str().unwrap()).arg(\"1\").spawn()?;\n\n Command::new(\"update-alternatives\").arg(\"--install\").arg(\"/usr/bin/javadoc\").arg(\"javadoc\").arg(javadoc.to_str().unwrap()).arg(\"1\").spawn()?;\n\n Ok(true)\n\n }\n\n pub fn uninstall(&self, value: usize) -> Result<(), AdoptOpenJDKError> {\n\n let mut settings = self.get_settings()?;\n\n let install = settings.remove_install(value);\n\n let path = Path::new(&install.location);\n\n\n\n self.update_settings(settings)?;\n\n let java = path.clone().join(\"bin\").join(\"java\");\n\n let javac = path.clone().join(\"bin\").join(\"javac\");\n", "file_path": "src/installer/mod.rs", "rank": 16, "score": 16713.86418298211 }, { "content": "pub mod utils;\n", "file_path": "src/utils/mod.rs", "rank": 17, "score": 16713.269151144763 }, { "content": " riscv64,\n\n}\n\n\n\nimpl FromStr for Architecture {\n\n type Err = AdoptOpenJDKError;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n return match s {\n\n \"x86\" => Ok(Architecture::x86),\n\n \"x32\" => Ok(Architecture::x32),\n\n \"x86_64\" => Ok(Architecture::x64),\n\n _ => Err(AdoptOpenJDKError::Custom(\"Unable to find Architecture \".to_string()))\n\n };\n\n }\n\n}\n\n#[allow(non_camel_case_types)]\n\n#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Display)]\n\npub enum JVMImpl {\n\n hotspot,\n\n openj9,\n", "file_path": "src/adoptopenjdk/response.rs", "rank": 18, "score": 16485.974279020393 }, { "content": "use serde::Deserialize;\n\nuse serde::Serialize;\n\nuse derive_more::Display;\n\nuse std::str::FromStr;\n\nuse crate::adoptopenjdk::AdoptOpenJDKError;\n\nuse std::fmt::{Display, Formatter};\n\n\n\nuse colored::*;\n\n#[allow(non_camel_case_types)]\n\n#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Display)]\n\npub enum Architecture {\n\n x64,\n\n x86,\n\n x32,\n\n ppc64,\n\n ppc64le,\n\n s390x,\n\n aarch64,\n\n arm,\n\n sparcv9,\n", "file_path": "src/adoptopenjdk/response.rs", "rank": 19, "score": 16483.49824073613 }, { "content": " ga,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub struct AvailableReleases {\n\n pub available_lts_releases: Vec<i64>,\n\n pub available_releases: Vec<i64>,\n\n pub most_recent_feature_release: i64,\n\n pub most_recent_feature_version: i64,\n\n pub most_recent_lts: i64,\n\n pub tip_version: i64,\n\n}\n\n\n\nimpl Display for AvailableReleases {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n\n let mut value = String::new();\n\n for x in self.available_releases.clone() {\n\n if self.available_lts_releases.contains(&x) {\n\n value = format!(\"{},{}\", value, x.to_string().as_str().green());\n\n } else {\n", "file_path": "src/adoptopenjdk/response.rs", "rank": 20, "score": 16482.903485257262 }, { "content": " value = format!(\"{},{}\", value, x);\n\n }\n\n }\n\n value.remove(0);\n\n write!(f, \"[{}]\", value)\n\n }\n\n}\n\n#[allow(non_camel_case_types)]\n\n#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Display)]\n\npub enum Vendor {\n\n #[deprecated(note=\"As far as I understand Adoptium is removing this vendor\")]\n\n adoptopenjdk,\n\n #[deprecated(note=\"As far as I understand Adoptium is removing this vendor\")]\n\n openjdk,\n\n eclipse\n\n}", "file_path": "src/adoptopenjdk/response.rs", "rank": 21, "score": 16476.03756890135 }, { "content": "}\n\n#[allow(non_camel_case_types)]\n\n#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Display)]\n\npub enum HeapSize {\n\n normal,\n\n large,\n\n}\n\n#[allow(non_camel_case_types)]\n\n#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Display)]\n\npub enum Project {\n\n jdk,\n\n valhalla,\n\n metropolis,\n\n jfr,\n\n shenandoah,\n\n}\n\n#[allow(non_camel_case_types)]\n\n#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Display)]\n\npub enum Imagetype {\n\n jdk,\n", "file_path": "src/adoptopenjdk/response.rs", "rank": 22, "score": 16475.79153252343 }, { "content": " jre,\n\n testimage,\n\n debugimage,\n\n staticlibs,\n\n}\n\n#[allow(non_camel_case_types)]\n\n#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Display)]\n\npub enum OS {\n\n linux,\n\n windows,\n\n mac,\n\n solaris,\n\n aix,\n\n #[serde(rename = \"alpine-linux\")]\n\n alpine_linux,\n\n}\n\n#[allow(non_camel_case_types)]\n\n#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Display)]\n\npub enum ReleaseType {\n\n ea,\n", "file_path": "src/adoptopenjdk/response.rs", "rank": 23, "score": 16475.371333261653 }, { "content": "# AdoptOpenJDK-Installer\n", "file_path": "README.md", "rank": 24, "score": 10199.090170135381 }, { "content": "use crate::adoptopenjdk::{AdoptOpenJDK, AdoptOpenJDKError};\n\nuse crate::adoptopenjdk::request::LatestBinary;\n\nuse crate::adoptopenjdk::response::{Architecture, HeapSize, Imagetype, JVMImpl, OS, ReleaseType, Vendor};\n\n\n\nuse std::str::FromStr;\n\nuse std::io::{stdin, stdout, Write};\n\nuse crate::installer::settings::{Settings};\n\nuse clap::{App, Arg};\n\nuse crate::installer::Installer;\n\n\n\npub mod utils;\n\n\n\npub mod adoptopenjdk;\n\npub mod installer;\n\n\n\n#[tokio::main]\n\nasync fn main() {\n\n if !whoami::username().eq(\"root\") {\n\n println!(\"This applications must be ran as root!\");\n\n return;\n", "file_path": "src/main.rs", "rank": 25, "score": 16.404527686575925 }, { "content": "use serde::Deserialize;\n\nuse serde::Serialize;\n\nuse crate::adoptopenjdk::response::JVMImpl;\n\nuse std::fmt::{Display, Formatter};\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n\npub struct Settings {\n\n pub install_location: String,\n\n pub installs: Vec<Install>,\n\n}\n\n\n\nimpl Display for Settings {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n\n let result = serde_json::to_string(self).unwrap();\n\n write!(f, \"{}\", result)\n\n }\n\n}\n\n\n\nimpl Settings {\n\n pub fn add_install(&mut self, install: Install) {\n", "file_path": "src/installer/settings.rs", "rank": 26, "score": 16.074273047226058 }, { "content": "use std::{fs,\n\n path::Path,\n\n};\n\nuse std::fs::create_dir_all;\n\nuse std::io::Write;\n\n\n\nuse indicatif::{ProgressBar, ProgressStyle};\n\nuse reqwest::{Client, header};\n\nuse reqwest::Url;\n\nuse crate::adoptopenjdk::AdoptOpenJDKError;\n\nuse std::path::PathBuf;\n\n\n\n// Stolen from Kakara's Klauncher https://github.com/kakaragame/KLauncher/blob/master/src/downloader.rs\n\n// By Wyatt Herkamp and Ryandw11\n\npub async fn download(url: &str, location: &Path, what: &str) -> Result<PathBuf, AdoptOpenJDKError> {\n\n println!(\"Downloading {}\", what);\n\n let x = location.clone();\n\n if !x.exists() {\n\n create_dir_all(x)?;\n\n }\n", "file_path": "src/utils/utils.rs", "rank": 27, "score": 12.225676722875521 }, { "content": " let url = Url::parse(url)?;\n\n let client = Client::new();\n\n let total_size = {\n\n let resp = client.head(url.as_str()).send().await?;\n\n if resp.status().is_success() {\n\n let value: String;\n\n if let Some(e) = resp.headers().get(header::CONTENT_DISPOSITION) {\n\n let result = e.to_str().unwrap();\n\n let split = result.split(\"; \").collect::<Vec<&str>>();\n\n let option = split.get(1);\n\n let split1 = option.unwrap().split(\"=\");\n\n let vec = split1.collect::<Vec<&str>>();\n\n let x1 = vec.get(1).unwrap();\n\n value = x1.to_string();\n\n } else {\n\n return Err(AdoptOpenJDKError::Custom(\"Fail\".to_string()));\n\n }\n\n let x2 = resp.headers()\n\n .get(header::CONTENT_LENGTH)\n\n .and_then(|ct_len| ct_len.to_str().ok())\n", "file_path": "src/utils/utils.rs", "rank": 28, "score": 11.08943568210846 }, { "content": " println!(\"{}\", x);\n\n }\n\n } else if matches.is_present(\"remove\") {\n\n remove(&installer).await.unwrap();\n\n } else {\n\n app.print_long_help().unwrap();\n\n }\n\n}\n\n\n\npub async fn remove(installer: &Installer) -> Result<(), AdoptOpenJDKError> {\n\n let settings = installer.get_settings().unwrap();\n\n let mut i = 0;\n\n for x in settings.installs {\n\n println!(\"[{}]: {}\", i, x);\n\n i = i + 1;\n\n }\n\n print!(\"Please Select a Java Install from above 0-{}:\", i-1);\n\n let mut install = String::new();\n\n stdout().flush()?;\n\n let result = stdin().read_line(&mut install);\n", "file_path": "src/main.rs", "rank": 29, "score": 11.056131103550921 }, { "content": " if let Err(err) = result {\n\n panic!(\"Fail {}\", err);\n\n }\n\n install.truncate(install.len() - 1);\n\n let value = i64::from_str(install.as_str())?;\n\n installer.uninstall(value as usize)?;\n\n Ok(())\n\n}\n\n\n\npub async fn install(installer: &Installer)->Result<(), AdoptOpenJDKError> {\n\n let jdk = AdoptOpenJDK::new(\"Adoptium(AdoptOpenJDK) Installer by Wyatt Herkamp (github.com/wherkamp)\".to_string());\n\n let result = jdk.get_releases().await.unwrap();\n\n print!(\"Please Select a Java Version {}: \", result.to_string());\n\n let mut java_version = String::new();\n\n stdout().flush()?;\n\n let result = stdin().read_line(&mut java_version);\n\n if let Err(err) = result {\n\n panic!(\"Fail {}\", err);\n\n }\n\n java_version.truncate(java_version.len() - 1);\n", "file_path": "src/main.rs", "rank": 30, "score": 11.014752438050534 }, { "content": " .and_then(|ct_len| ct_len.parse().ok())\n\n .unwrap_or(0);\n\n (x2, value)\n\n } else {\n\n return Err(AdoptOpenJDKError::HTTPError(resp.status()));\n\n }\n\n };\n\n let location = location.join(total_size.1);\n\n let mut request = client.get(url.as_str());\n\n let pb = ProgressBar::new(total_size.0);\n\n pb.set_style(ProgressStyle::default_bar()\n\n .template(\"{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})\")\n\n .progress_chars(\"#>-\"));\n\n\n\n\n\n if location.exists() {\n\n let size = &location.metadata()?.len() - 1;\n\n request = request.header(header::RANGE, format!(\"bytes={}-\", size));\n\n pb.inc(size);\n\n }\n", "file_path": "src/utils/utils.rs", "rank": 31, "score": 10.984619472014646 }, { "content": "\n\nimpl Display for Install {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n\n let result = serde_json::to_string(self).unwrap();\n\n write!(f, \"{}\", result)\n\n }\n\n}\n\n\n\nimpl PartialEq for Install {\n\n fn eq(&self, other: &Install) -> bool {\n\n self.jvm_impl == other.jvm_impl && self.jvm_version == other.jvm_version\n\n }\n\n}\n", "file_path": "src/installer/settings.rs", "rank": 32, "score": 10.617401282352873 }, { "content": " }\n\n let installer = installer::Installer;\n\n if !installer.does_settings_exist() {\n\n let settings1 = Settings {\n\n install_location: \"/opt/adoptopenjdk\".to_string(),\n\n installs: vec![],\n\n };\n\n installer.update_settings(settings1).unwrap();\n\n }\n\n let mut app = App::new(\"Adoptium(AdoptOpenJDK) Installer\").\n\n version(\"0.1.0\").author(\"Wyatt Jacob Herkamp <[email protected]>\").about(\"A AdoptOpenJDK installer for Linux\")\n\n .arg(Arg::new(\"install\").short('i').long(\"install\").help(\"Install a Java Version\").takes_value(false))\n\n .arg(Arg::new(\"list\").short('l').long(\"list\").help(\"Lists installed Java versions\").takes_value(false))\n\n .arg(Arg::new(\"remove\").short('r').long(\"remove\").help(\"Remove A Java Install\").takes_value(false));\n\n let matches = app.clone().get_matches();\n\n if matches.is_present(\"install\") {\n\n install(&installer).await.unwrap();\n\n } else if matches.is_present(\"list\") {\n\n let settings = installer.get_settings().unwrap();\n\n for x in settings.installs {\n", "file_path": "src/main.rs", "rank": 33, "score": 8.207522730019285 }, { "content": " self.installs.push(install);\n\n }\n\n\n\n pub fn remove_install(&mut self, value: usize) ->Install {\n\n self.installs.remove(value)\n\n }\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n\npub struct Install {\n\n pub jvm_version: i64,\n\n pub jvm_impl: JVMImpl,\n\n pub location: String,\n\n}\n\n\n\nimpl Install {\n\n pub fn set_location(&mut self, location: String) {\n\n self.location = location;\n\n }\n\n}\n", "file_path": "src/installer/settings.rs", "rank": 34, "score": 8.139190767719747 }, { "content": " let arch = std::env::consts::ARCH;\n\n let value = i64::from_str(java_version.as_str());\n\n if let Err(ref err) = value {\n\n println!(\"{}\", err);\n\n }\n\n let binary = LatestBinary {\n\n arch: Architecture::from_str(arch).unwrap(),\n\n feature_version: value.unwrap(),\n\n heap_size: HeapSize::normal,\n\n image_type: Imagetype::jdk,\n\n jvm_impl: JVMImpl::hotspot,\n\n os: OS::linux,\n\n release_type: ReleaseType::ga,\n\n vendor: Vendor::eclipse,\n\n };\n\n let install = installer::settings::Install {\n\n jvm_version: binary.feature_version.clone(),\n\n jvm_impl: binary.jvm_impl.clone(),\n\n location: \"\".to_string(),\n\n };\n", "file_path": "src/main.rs", "rank": 35, "score": 6.921949228752143 }, { "content": "\n\n\n\n let mut dest = fs::OpenOptions::new()\n\n .create(true)\n\n .append(true)\n\n .open(&location).unwrap();\n\n\n\n\n\n let mut source = request.send().await.unwrap();\n\n while let Some(chunk) = source.chunk().await.unwrap() {\n\n dest.write_all(&chunk)?;\n\n pb.inc(chunk.len() as u64);\n\n }\n\n println!(\n\n \"Download of '{}' has been completed.\",\n\n location.clone().to_str().unwrap()\n\n );\n\n\n\n Ok(location)\n\n}\n", "file_path": "src/utils/utils.rs", "rank": 36, "score": 6.199447755044758 }, { "content": " let result2 = installer.contains_install(&install).unwrap();\n\n if result2 {\n\n println!(\"That version has already been installed\");\n\n return Ok(());\n\n }\n\n let result1 = jdk.download_binary(binary.clone(), std::env::temp_dir().as_path().clone()).await;\n\n if let Err(ref e) = result1 {\n\n println!(\"{}\", e);\n\n }\n\n let buf = result1.unwrap();\n\n let installer = installer::Installer;\n\n let result3 = installer.install(buf, install);\n\n if let Err(ref e) = result3 {\n\n println!(\"{}\", e);\n\n }\n\n return Ok(());\n\n}\n", "file_path": "src/main.rs", "rank": 37, "score": 1.9543261522086057 } ]
Rust
src/lib.rs
FirelightFlagboy/egui_sdl2_gl
70cde948a769ce841c72360b80da73e16b675c4f
#![warn(clippy::all)] #![allow(clippy::single_match)] pub use egui; pub use gl; pub use sdl2; pub mod painter; #[cfg(feature = "use_epi")] pub use epi; use painter::Painter; #[cfg(feature = "use_epi")] use std::time::Instant; use { egui::*, sdl2::{ event::WindowEvent, keyboard::{Keycode, Mod}, mouse::MouseButton, mouse::{Cursor, SystemCursor}, }, }; #[cfg(feature = "use_epi")] pub fn get_frame_time(start_time: Instant) -> f32 { (Instant::now() - start_time).as_secs_f64() as f32 } #[cfg(feature = "use_epi")] pub struct Signal; #[cfg(feature = "use_epi")] impl Default for Signal { fn default() -> Self { Self {} } } #[cfg(feature = "use_epi")] use epi::RepaintSignal; #[cfg(feature = "use_epi")] impl RepaintSignal for Signal { fn request_repaint(&self) {} } pub struct FusedCursor { pub cursor: Cursor, pub icon: SystemCursor, } impl FusedCursor { pub fn new() -> Self { Self { cursor: Cursor::from_system(SystemCursor::Arrow).unwrap(), icon: SystemCursor::Arrow, } } } impl Default for FusedCursor { fn default() -> Self { Self::new() } } pub enum DpiScaling { Default, Custom(f32), } #[derive(Clone)] pub enum ShaderVersion { Default, Adaptive, } pub struct EguiStateHandler { pub fused_cursor: FusedCursor, pub pointer_pos: Pos2, pub input: RawInput, pub modifiers: Modifiers, pub native_pixels_per_point: f32, } pub fn with_sdl2( window: &sdl2::video::Window, shader_ver: ShaderVersion, scale: DpiScaling, ) -> (Painter, EguiStateHandler) { let scale = match scale { DpiScaling::Default => 96.0 / window.subsystem().display_dpi(0).unwrap().0, DpiScaling::Custom(custom) => { (96.0 / window.subsystem().display_dpi(0).unwrap().0) * custom } }; let painter = painter::Painter::new(window, scale, shader_ver); EguiStateHandler::new(painter) } impl EguiStateHandler { pub fn new(painter: Painter) -> (Painter, EguiStateHandler) { let native_pixels_per_point = painter.pixels_per_point; let _self = EguiStateHandler { fused_cursor: FusedCursor::default(), pointer_pos: Pos2::new(0f32, 0f32), input: egui::RawInput { screen_rect: Some(painter.screen_rect), pixels_per_point: Some(native_pixels_per_point), ..Default::default() }, modifiers: Modifiers::default(), native_pixels_per_point, }; (painter, _self) } pub fn process_input( &mut self, window: &sdl2::video::Window, event: sdl2::event::Event, painter: &mut Painter, ) { input_to_egui(window, event, painter, self); } pub fn process_output(&mut self, window: &sdl2::video::Window, egui_output: &egui::Output) { if !egui_output.copied_text.is_empty() { let copied_text = egui_output.copied_text.clone(); { let result = window .subsystem() .clipboard() .set_clipboard_text(&copied_text); if result.is_err() { dbg!("Unable to set clipboard content to SDL clipboard."); } } } translate_cursor(&mut self.fused_cursor, egui_output.cursor_icon); } } pub fn input_to_egui( window: &sdl2::video::Window, event: sdl2::event::Event, painter: &mut Painter, state: &mut EguiStateHandler, ) { use sdl2::event::Event::*; let pixels_per_point = painter.pixels_per_point; if event.get_window_id() != Some(window.id()) { return; } match event { Window { win_event, .. } => match win_event { WindowEvent::Resized(_, _) | sdl2::event::WindowEvent::SizeChanged(_, _) => { painter.update_screen_rect(window.drawable_size()); state.input.screen_rect = Some(painter.screen_rect); } _ => (), }, MouseButtonDown { mouse_btn, .. } => { let mouse_btn = match mouse_btn { MouseButton::Left => Some(egui::PointerButton::Primary), MouseButton::Middle => Some(egui::PointerButton::Middle), MouseButton::Right => Some(egui::PointerButton::Secondary), _ => None, }; if let Some(pressed) = mouse_btn { state.input.events.push(egui::Event::PointerButton { pos: state.pointer_pos, button: pressed, pressed: true, modifiers: state.modifiers, }); } } MouseButtonUp { mouse_btn, .. } => { let mouse_btn = match mouse_btn { MouseButton::Left => Some(egui::PointerButton::Primary), MouseButton::Middle => Some(egui::PointerButton::Middle), MouseButton::Right => Some(egui::PointerButton::Secondary), _ => None, }; if let Some(released) = mouse_btn { state.input.events.push(egui::Event::PointerButton { pos: state.pointer_pos, button: released, pressed: false, modifiers: state.modifiers, }); } } MouseMotion { x, y, .. } => { state.pointer_pos = pos2(x as f32 / pixels_per_point, y as f32 / pixels_per_point); state .input .events .push(egui::Event::PointerMoved(state.pointer_pos)); } KeyUp { keycode, keymod, .. } => { let key_code = match keycode { Some(key_code) => key_code, _ => return, }; let key = match translate_virtual_key_code(key_code) { Some(key) => key, _ => return, }; state.modifiers = Modifiers { alt: (keymod & Mod::LALTMOD == Mod::LALTMOD) || (keymod & Mod::RALTMOD == Mod::RALTMOD), ctrl: (keymod & Mod::LCTRLMOD == Mod::LCTRLMOD) || (keymod & Mod::RCTRLMOD == Mod::RCTRLMOD), shift: (keymod & Mod::LSHIFTMOD == Mod::LSHIFTMOD) || (keymod & Mod::RSHIFTMOD == Mod::RSHIFTMOD), mac_cmd: keymod & Mod::LGUIMOD == Mod::LGUIMOD, command: (keymod & Mod::LCTRLMOD == Mod::LCTRLMOD) || (keymod & Mod::LGUIMOD == Mod::LGUIMOD), }; state.input.events.push(Event::Key { key, pressed: false, modifiers: state.modifiers, }); } KeyDown { keycode, keymod, .. } => { let key_code = match keycode { Some(key_code) => key_code, _ => return, }; let key = match translate_virtual_key_code(key_code) { Some(key) => key, _ => return, }; state.modifiers = Modifiers { alt: (keymod & Mod::LALTMOD == Mod::LALTMOD) || (keymod & Mod::RALTMOD == Mod::RALTMOD), ctrl: (keymod & Mod::LCTRLMOD == Mod::LCTRLMOD) || (keymod & Mod::RCTRLMOD == Mod::RCTRLMOD), shift: (keymod & Mod::LSHIFTMOD == Mod::LSHIFTMOD) || (keymod & Mod::RSHIFTMOD == Mod::RSHIFTMOD), mac_cmd: keymod & Mod::LGUIMOD == Mod::LGUIMOD, command: (keymod & Mod::LCTRLMOD == Mod::LCTRLMOD) || (keymod & Mod::LGUIMOD == Mod::LGUIMOD), }; state.input.events.push(Event::Key { key, pressed: true, modifiers: state.modifiers, }); if state.modifiers.command && key == Key::C { state.input.events.push(Event::Copy); } else if state.modifiers.command && key == Key::X { state.input.events.push(Event::Cut); } else if state.modifiers.command && key == Key::V { if let Ok(contents) = window.subsystem().clipboard().clipboard_text() { state.input.events.push(Event::Text(contents)); } } } TextInput { text, .. } => { state.input.events.push(Event::Text(text)); } MouseWheel { x, y, .. } => { let delta = vec2(x as f32 * 8.0, y as f32 * 8.0); let sdl = window.subsystem().sdl(); if sdl.keyboard().mod_state() & Mod::LCTRLMOD == Mod::LCTRLMOD || sdl.keyboard().mod_state() & Mod::RCTRLMOD == Mod::RCTRLMOD { state.input.zoom_delta *= (delta.y / 125.0).exp(); } else { state.input.scroll_delta = delta; } } _ => { } } } pub fn translate_virtual_key_code(key: sdl2::keyboard::Keycode) -> Option<egui::Key> { use Keycode::*; Some(match key { Left => Key::ArrowLeft, Up => Key::ArrowUp, Right => Key::ArrowRight, Down => Key::ArrowDown, Escape => Key::Escape, Tab => Key::Tab, Backspace => Key::Backspace, Space => Key::Space, Return => Key::Enter, Insert => Key::Insert, Home => Key::Home, Delete => Key::Delete, End => Key::End, PageDown => Key::PageDown, PageUp => Key::PageUp, Kp0 | Num0 => Key::Num0, Kp1 | Num1 => Key::Num1, Kp2 | Num2 => Key::Num2, Kp3 | Num3 => Key::Num3, Kp4 | Num4 => Key::Num4, Kp5 | Num5 => Key::Num5, Kp6 | Num6 => Key::Num6, Kp7 | Num7 => Key::Num7, Kp8 | Num8 => Key::Num8, Kp9 | Num9 => Key::Num9, A => Key::A, B => Key::B, C => Key::C, D => Key::D, E => Key::E, F => Key::F, G => Key::G, H => Key::H, I => Key::I, J => Key::J, K => Key::K, L => Key::L, M => Key::M, N => Key::N, O => Key::O, P => Key::P, Q => Key::Q, R => Key::R, S => Key::S, T => Key::T, U => Key::U, V => Key::V, W => Key::W, X => Key::X, Y => Key::Y, Z => Key::Z, _ => { return None; } }) } pub fn translate_cursor(fused: &mut FusedCursor, cursor_icon: egui::CursorIcon) { let tmp_icon = match cursor_icon { CursorIcon::Crosshair => SystemCursor::Crosshair, CursorIcon::Default => SystemCursor::Arrow, CursorIcon::Grab => SystemCursor::Hand, CursorIcon::Grabbing => SystemCursor::SizeAll, CursorIcon::Move => SystemCursor::SizeAll, CursorIcon::PointingHand => SystemCursor::Hand, CursorIcon::ResizeHorizontal => SystemCursor::SizeWE, CursorIcon::ResizeNeSw => SystemCursor::SizeNESW, CursorIcon::ResizeNwSe => SystemCursor::SizeNWSE, CursorIcon::ResizeVertical => SystemCursor::SizeNS, CursorIcon::Text => SystemCursor::IBeam, CursorIcon::NotAllowed | CursorIcon::NoDrop => SystemCursor::No, CursorIcon::Wait => SystemCursor::Wait, _ => SystemCursor::Arrow, }; if tmp_icon != fused.icon { fused.cursor = Cursor::from_system(tmp_icon).unwrap(); fused.icon = tmp_icon; fused.cursor.set(); } }
#![warn(clippy::all)] #![allow(clippy::single_match)] pub use egui; pub use gl; pub use sdl2; pub mod painter; #[cfg(feature = "use_epi")] pub use epi; use painter::Painter; #[cfg(feature = "use_epi")] use std::time::Instant; use { egui::*, sdl2::{ event::WindowEvent, keyboard::{Keycode, Mod}, mouse::MouseButton, mouse::{Cursor, SystemCursor}, }, }; #[cfg(feature = "use_epi")] pub fn get_frame_time(start_time: Instant) -> f32 { (Instant::now() - start_time).as_secs_f64() as f32 } #[cfg(feature = "use_epi")] pub struct Signal; #[cfg(feature = "use_epi")] impl Default for Signal { fn default() -> Self { Self {} } } #[cfg(feature = "use_epi")] use epi::RepaintSignal; #[cfg(feature = "use_epi")] impl RepaintSignal for Signal { fn request_repaint(&self) {} } pub struct FusedCursor { pub cursor: Cursor, pub icon: SystemCursor, } impl FusedCursor { pub fn new() -> Self { Self { cursor: Cursor::from_system(SystemCursor::Arrow).unwrap(), icon: SystemCursor::Arrow, } } } impl Default for FusedCursor { fn default() -> Self { Self::new() } } pub enum DpiScaling { Default, Custom(f32), } #[derive(Clone)] pub enum ShaderVersion { Default, Adaptive, } pub struct EguiStateHandler { pub fused_cursor: FusedCursor, pub pointer_pos: Pos2, pub input: RawInput, pub modifiers: Modifiers, pub native_pixels_per_point: f32, } pub fn with_sdl2( window: &sdl2::video::Window, shader_ver: ShaderVersion, scale: DpiScaling, ) -> (Painter, EguiStateHandler) { let scale = match scale { DpiScaling::Default => 96.0 / window.subsystem().display_dpi(0).unwrap().0, DpiScaling::Custom(custom) => { (96.0 / window.subsystem().display_dpi(0).unwrap().0) * custom } }; let painter = painter::Painter::new(window, scale, shader_ver); EguiStateHandler::new(painter) } impl EguiStateHandler { pub fn new(painter: Painter) -> (Painter, EguiStateHandler) { let native_pixels_per_point = painter.pixels_per_point; let _self = EguiStateHandler { fused_cursor: FusedCursor::default(), pointer_pos: Pos2::new(0f32, 0f32), input: egui::RawInput { screen_rect: Some(painter.screen_rect), pixels_per_point: Some(native_pixels_per_point), ..Default::default() }, modifiers: Modifiers::default(), native_pixels_per_point,
} KeyDown { keycode, keymod, .. } => { let key_code = match keycode { Some(key_code) => key_code, _ => return, }; let key = match translate_virtual_key_code(key_code) { Some(key) => key, _ => return, }; state.modifiers = Modifiers { alt: (keymod & Mod::LALTMOD == Mod::LALTMOD) || (keymod & Mod::RALTMOD == Mod::RALTMOD), ctrl: (keymod & Mod::LCTRLMOD == Mod::LCTRLMOD) || (keymod & Mod::RCTRLMOD == Mod::RCTRLMOD), shift: (keymod & Mod::LSHIFTMOD == Mod::LSHIFTMOD) || (keymod & Mod::RSHIFTMOD == Mod::RSHIFTMOD), mac_cmd: keymod & Mod::LGUIMOD == Mod::LGUIMOD, command: (keymod & Mod::LCTRLMOD == Mod::LCTRLMOD) || (keymod & Mod::LGUIMOD == Mod::LGUIMOD), }; state.input.events.push(Event::Key { key, pressed: true, modifiers: state.modifiers, }); if state.modifiers.command && key == Key::C { state.input.events.push(Event::Copy); } else if state.modifiers.command && key == Key::X { state.input.events.push(Event::Cut); } else if state.modifiers.command && key == Key::V { if let Ok(contents) = window.subsystem().clipboard().clipboard_text() { state.input.events.push(Event::Text(contents)); } } } TextInput { text, .. } => { state.input.events.push(Event::Text(text)); } MouseWheel { x, y, .. } => { let delta = vec2(x as f32 * 8.0, y as f32 * 8.0); let sdl = window.subsystem().sdl(); if sdl.keyboard().mod_state() & Mod::LCTRLMOD == Mod::LCTRLMOD || sdl.keyboard().mod_state() & Mod::RCTRLMOD == Mod::RCTRLMOD { state.input.zoom_delta *= (delta.y / 125.0).exp(); } else { state.input.scroll_delta = delta; } } _ => { } } } pub fn translate_virtual_key_code(key: sdl2::keyboard::Keycode) -> Option<egui::Key> { use Keycode::*; Some(match key { Left => Key::ArrowLeft, Up => Key::ArrowUp, Right => Key::ArrowRight, Down => Key::ArrowDown, Escape => Key::Escape, Tab => Key::Tab, Backspace => Key::Backspace, Space => Key::Space, Return => Key::Enter, Insert => Key::Insert, Home => Key::Home, Delete => Key::Delete, End => Key::End, PageDown => Key::PageDown, PageUp => Key::PageUp, Kp0 | Num0 => Key::Num0, Kp1 | Num1 => Key::Num1, Kp2 | Num2 => Key::Num2, Kp3 | Num3 => Key::Num3, Kp4 | Num4 => Key::Num4, Kp5 | Num5 => Key::Num5, Kp6 | Num6 => Key::Num6, Kp7 | Num7 => Key::Num7, Kp8 | Num8 => Key::Num8, Kp9 | Num9 => Key::Num9, A => Key::A, B => Key::B, C => Key::C, D => Key::D, E => Key::E, F => Key::F, G => Key::G, H => Key::H, I => Key::I, J => Key::J, K => Key::K, L => Key::L, M => Key::M, N => Key::N, O => Key::O, P => Key::P, Q => Key::Q, R => Key::R, S => Key::S, T => Key::T, U => Key::U, V => Key::V, W => Key::W, X => Key::X, Y => Key::Y, Z => Key::Z, _ => { return None; } }) } pub fn translate_cursor(fused: &mut FusedCursor, cursor_icon: egui::CursorIcon) { let tmp_icon = match cursor_icon { CursorIcon::Crosshair => SystemCursor::Crosshair, CursorIcon::Default => SystemCursor::Arrow, CursorIcon::Grab => SystemCursor::Hand, CursorIcon::Grabbing => SystemCursor::SizeAll, CursorIcon::Move => SystemCursor::SizeAll, CursorIcon::PointingHand => SystemCursor::Hand, CursorIcon::ResizeHorizontal => SystemCursor::SizeWE, CursorIcon::ResizeNeSw => SystemCursor::SizeNESW, CursorIcon::ResizeNwSe => SystemCursor::SizeNWSE, CursorIcon::ResizeVertical => SystemCursor::SizeNS, CursorIcon::Text => SystemCursor::IBeam, CursorIcon::NotAllowed | CursorIcon::NoDrop => SystemCursor::No, CursorIcon::Wait => SystemCursor::Wait, _ => SystemCursor::Arrow, }; if tmp_icon != fused.icon { fused.cursor = Cursor::from_system(tmp_icon).unwrap(); fused.icon = tmp_icon; fused.cursor.set(); } }
}; (painter, _self) } pub fn process_input( &mut self, window: &sdl2::video::Window, event: sdl2::event::Event, painter: &mut Painter, ) { input_to_egui(window, event, painter, self); } pub fn process_output(&mut self, window: &sdl2::video::Window, egui_output: &egui::Output) { if !egui_output.copied_text.is_empty() { let copied_text = egui_output.copied_text.clone(); { let result = window .subsystem() .clipboard() .set_clipboard_text(&copied_text); if result.is_err() { dbg!("Unable to set clipboard content to SDL clipboard."); } } } translate_cursor(&mut self.fused_cursor, egui_output.cursor_icon); } } pub fn input_to_egui( window: &sdl2::video::Window, event: sdl2::event::Event, painter: &mut Painter, state: &mut EguiStateHandler, ) { use sdl2::event::Event::*; let pixels_per_point = painter.pixels_per_point; if event.get_window_id() != Some(window.id()) { return; } match event { Window { win_event, .. } => match win_event { WindowEvent::Resized(_, _) | sdl2::event::WindowEvent::SizeChanged(_, _) => { painter.update_screen_rect(window.drawable_size()); state.input.screen_rect = Some(painter.screen_rect); } _ => (), }, MouseButtonDown { mouse_btn, .. } => { let mouse_btn = match mouse_btn { MouseButton::Left => Some(egui::PointerButton::Primary), MouseButton::Middle => Some(egui::PointerButton::Middle), MouseButton::Right => Some(egui::PointerButton::Secondary), _ => None, }; if let Some(pressed) = mouse_btn { state.input.events.push(egui::Event::PointerButton { pos: state.pointer_pos, button: pressed, pressed: true, modifiers: state.modifiers, }); } } MouseButtonUp { mouse_btn, .. } => { let mouse_btn = match mouse_btn { MouseButton::Left => Some(egui::PointerButton::Primary), MouseButton::Middle => Some(egui::PointerButton::Middle), MouseButton::Right => Some(egui::PointerButton::Secondary), _ => None, }; if let Some(released) = mouse_btn { state.input.events.push(egui::Event::PointerButton { pos: state.pointer_pos, button: released, pressed: false, modifiers: state.modifiers, }); } } MouseMotion { x, y, .. } => { state.pointer_pos = pos2(x as f32 / pixels_per_point, y as f32 / pixels_per_point); state .input .events .push(egui::Event::PointerMoved(state.pointer_pos)); } KeyUp { keycode, keymod, .. } => { let key_code = match keycode { Some(key_code) => key_code, _ => return, }; let key = match translate_virtual_key_code(key_code) { Some(key) => key, _ => return, }; state.modifiers = Modifiers { alt: (keymod & Mod::LALTMOD == Mod::LALTMOD) || (keymod & Mod::RALTMOD == Mod::RALTMOD), ctrl: (keymod & Mod::LCTRLMOD == Mod::LCTRLMOD) || (keymod & Mod::RCTRLMOD == Mod::RCTRLMOD), shift: (keymod & Mod::LSHIFTMOD == Mod::LSHIFTMOD) || (keymod & Mod::RSHIFTMOD == Mod::RSHIFTMOD), mac_cmd: keymod & Mod::LGUIMOD == Mod::LGUIMOD, command: (keymod & Mod::LCTRLMOD == Mod::LCTRLMOD) || (keymod & Mod::LGUIMOD == Mod::LGUIMOD), }; state.input.events.push(Event::Key { key, pressed: false, modifiers: state.modifiers, });
random
[ { "content": "#[derive(Default)]\n\nstruct UserTexture {\n\n size: (usize, usize),\n\n\n\n /// Pending upload (will be emptied later).\n\n pixels: Vec<u8>,\n\n\n\n /// Lazily uploaded\n\n texture: Option<GLuint>,\n\n\n\n /// For user textures there is a choice between\n\n /// Linear (default) and Nearest.\n\n filtering: bool,\n\n\n\n /// User textures can be modified and this flag\n\n /// is used to indicate if pixel data for the\n\n /// texture has been updated.\n\n dirty: bool,\n\n}\n\n\n\nconst VS_SRC_150: &str = r#\"\n", "file_path": "src/painter.rs", "rank": 5, "score": 57435.01673135633 }, { "content": "pub fn compile_shader(src: &str, ty: GLenum) -> GLuint {\n\n let shader;\n\n unsafe {\n\n shader = gl::CreateShader(ty);\n\n // Attempt to compile the shader\n\n let c_str = CString::new(src.as_bytes()).unwrap();\n\n gl::ShaderSource(shader, 1, &c_str.as_ptr(), ptr::null());\n\n gl::CompileShader(shader);\n\n // Get the compile status\n\n let mut status = gl::FALSE as GLint;\n\n gl::GetShaderiv(shader, gl::COMPILE_STATUS, &mut status);\n\n\n\n // Fail on error\n\n if status != (gl::TRUE as GLint) {\n\n let mut len = 0;\n\n gl::GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut len);\n\n let mut buf = Vec::with_capacity(len as usize);\n\n // clippy not happy with this, broke the CI:\n\n // error: calling `set_len()` immediately after reserving a buffer creates uninitialized values\n\n // buf.set_len((len as usize) - 1); // subtract 1 to skip the trailing null character\n", "file_path": "src/painter.rs", "rank": 6, "score": 52495.034533825165 }, { "content": "pub fn link_program(vs: GLuint, fs: GLuint) -> GLuint {\n\n unsafe {\n\n let program = gl::CreateProgram();\n\n gl::AttachShader(program, vs);\n\n gl::AttachShader(program, fs);\n\n gl::LinkProgram(program);\n\n // Get the link status\n\n let mut status = gl::FALSE as GLint;\n\n gl::GetProgramiv(program, gl::LINK_STATUS, &mut status);\n\n\n\n // Fail on error\n\n if status != (gl::TRUE as GLint) {\n\n let mut len: GLint = 0;\n\n gl::GetProgramiv(program, gl::INFO_LOG_LENGTH, &mut len);\n\n let mut buf = Vec::with_capacity(len as usize);\n\n // clippy not happy with this, broke the CI:\n\n // error: calling `set_len()` immediately after reserving a buffer creates uninitialized values\n\n // buf.set_len((len as usize) - 1); // subtract 1 to skip the trailing null character\n\n gl::GetProgramInfoLog(\n\n program,\n", "file_path": "src/painter.rs", "rank": 7, "score": 50842.20679096072 }, { "content": "pub fn compile_shader(src: &str, ty: GLenum) -> GLuint {\n\n let shader;\n\n unsafe {\n\n // Create GLSL shaders\n\n shader = gl::CreateShader(ty);\n\n // Attempt to compile the shader\n\n let c_str = CString::new(src.as_bytes()).unwrap();\n\n gl::ShaderSource(shader, 1, &c_str.as_ptr(), ptr::null());\n\n gl::CompileShader(shader);\n\n\n\n // Get the compile status\n\n let mut status = gl::FALSE as GLint;\n\n gl::GetShaderiv(shader, gl::COMPILE_STATUS, &mut status);\n\n\n\n // Fail on error\n\n if status != (gl::TRUE as GLint) {\n\n let mut len = 0;\n\n gl::GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut len);\n\n let mut buf = Vec::with_capacity(len as usize);\n\n buf.set_len((len as usize) - 1); // subtract 1 to skip the trailing null character\n", "file_path": "examples/mix/triangle.rs", "rank": 8, "score": 38886.43577097425 }, { "content": "pub fn link_program(vs: GLuint, fs: GLuint) -> GLuint {\n\n unsafe {\n\n let program = gl::CreateProgram();\n\n gl::AttachShader(program, vs);\n\n gl::AttachShader(program, fs);\n\n gl::LinkProgram(program);\n\n\n\n gl::DetachShader(program, fs);\n\n gl::DetachShader(program, vs);\n\n gl::DeleteShader(fs);\n\n gl::DeleteShader(vs);\n\n\n\n // Get the link status\n\n let mut status = gl::FALSE as GLint;\n\n gl::GetProgramiv(program, gl::LINK_STATUS, &mut status);\n\n\n\n // Fail on error\n\n if status != (gl::TRUE as GLint) {\n\n let mut len: GLint = 0;\n\n gl::GetProgramiv(program, gl::INFO_LOG_LENGTH, &mut len);\n", "file_path": "examples/mix/triangle.rs", "rank": 9, "score": 37838.29099793351 }, { "content": "[![Crates.io](https://img.shields.io/crates/v/egui_sdl2_gl.svg)](https://crates.io/crates/egui_sdl2_gl)\n\n[![Documentation](https://docs.rs/egui_sdl2_gl/badge.svg)](https://docs.rs/egui_sdl2_gl)\n\n[![CI](https://github.com/ArjunNair/egui_sdl2_gl/actions/workflows/ci.yml/badge.svg)](https://github.com/ArjunNair/egui_sdl2_gl/actions/workflows/ci.yml)\n\n\n\n# Egui backend for SDL2 + Open GL\n\n![Example screenshot](/media/egui_sdl2_gl_example.png)\n\n\n\nThis is a backend implementation for [Egui](https://github.com/emilk/egui) that can be used with [SDL 2](https://github.com/Rust-SDL2/rust-sdl2) for events, audio, input et al and [OpenGL](https://github.com/brendanzab/gl-rs) for rendering.\n\n\n\nI've included an example in the examples folder to illustrate how the three can be used together. To run the example, do the following:\n\n\n\n```\n\ncargo run --example basic\n\ncargo run --example mix\n\ncargo run --example demo_lib --features=use_epi\n\n```\n\n\n\nStarting with v13.1 SDL2 is 'bundled' as a cargo requirement and so SDL2 needn't be setup separately. If, however, you wish to be in control of the SDL2 setup, you can remove the bundled feature from the cargo.toml and set up the SDL2 framework separately, as described in the SDL2 repo above.\n\n\n\nNote that using OpenGL involves wrapping **any** Open GL call in an *unsafe* block. Have a look at the src/painter.rs file to see what I mean. This of course means that all bets are off when dealing with code inside the unsafe blocks, but that's the price to pay when dealing with raw OpenGL. \n\n\n\nWhy would anyone want to use this then, you wonder? Well I would say the familiarity of using SDL2, the elegance of Egui and the power of OpenGL makes for a good combination in making games, emulators, graphics tools and such.\n\n\n", "file_path": "README.md", "rank": 10, "score": 37134.04551018425 }, { "content": "# v0.10.0\n\n* Fixed SRGB to linear color conversion.\n\n* Fixed shader error on Mac\n\n* Fixed triangle example bounds error when amplitude is too high.\n\n* Updated to egui v0.10.0\n\n\n\n# v0.1.9\n\n* Made the background clear optional in Painter. This allows mixing custom Open GL draw calls with egui.\n\n* Added an OpenGL Triangle example to demonstrate the above.\n\n* Minor house keeping.\n\n\n\n# v0.1.8\n\n* Updated to egui 0.9.0.\n\n* Better key input and text handling.\n\n* Added cut, copy and paste support to the backend.\n\n* Updated screenshot\n\n* Fixed example sine wave speeding up unexpectedly after some time.\n\n\n\n# v0.1.7\n\nUpdated to egui 0.8.0\n\n\n\n# v0.1.6 \n\nChanged OpenGL version to 3.2 as minimum to support Mac OS Catalina. GLSL to v1.50\n\n\n\n# v0.1.5\n\nUpdated to egui 0.6.0\n\n\n\n# v0.1.4\n\nUpdated to egui 0.5.0\n\n\n\n# v0.1.3\n\nFixed dodgy modifier key check.\n\n\n\n# v0.1.2\n\nBumped up egui dependency crate to 0.4 (latest as on Dec 13, 2020)\n\nFixed example to conform to egui 4.0 changes\n\n\n\n# v0.1.1\n\nFix example.rs to use egui_sdl2_gl reference instead of egui_sdl2.\n\nAdded example screenshot to README.md.\n\n\n\n# v0.1.0\n", "file_path": "changelog.md", "rank": 11, "score": 37133.055162997014 }, { "content": "# Change log\n\n\n\nNOTE: The major version number of this library matches that of the egui major version that this library currently supports. The minor version number may be different though. \n\n\n\n# v0.15.0\n\n* Updated to egui v0.15.0\n\n* Fix correct window not being checked for other events. See [isse] (https://github.com/ArjunNair/egui_sdl2_gl/issues/11). Thanks [Yamakaky](https://github.com/Yamakaky)\n\n* Added CI checks for clippy, rustfmt, etc. Thanks [Guillaume Gomez](https://github.com/GuillaumeGomez/)\n\n* Re-export painter as pub. Thanks [d10sfan](https://github.com/d10sfan)\n\n* Fix when keycode is None in keyboard event handling. Thanks [d10sfan] (https://github.com/d10sfan)\n\n* Accepted some clippy suggestions for simpler/better code. A couple of others I didn't understand. Suggestions welcome! :)\n\n\n\n# v0.14.1\n\n* The full egui demo lib has been added to examples + cleanup of examples + refactoring. Thanks [Adia Robbie](https://github.com/Ar37-rs).\n\n* SDL2 bundled has been made optional again. Plus other SDL 2 features are now available as options. Thanks [Guillaume Gomez](https://github.com/GuillaumeGomez/).\n\n* Fixed build on doc.rs + other fixes GL related fixes. Thanks [Guillaume Gomez](https://github.com/GuillaumeGomez/).\n\n* Fixed correct window not being checked for window resize events. See [issue](https://github.com/ArjunNair/egui_sdl2_gl/issues/11). Thanks [Yamakaky](https://github.com/Yamakaky)\n\n\n\n# v0.14.0\n\n* Updated to egui v0.14.2\n\n* Updated README to reflect SDL2 bundle feature introduced in v0.13.1\n\n\n\n# v0.13.1\n\n* Updated to egui v0.13.1\n\n* Re-export dependencies Thanks [Guillaume Gomez](https://github.com/GuillaumeGomez/).\n\n* Switched to SDL2 as a bundled feature. Updated to 0.34.5.\n\n\n\n# v0.10.1\n\n* Clipboard is now an optional feature that is enabled by default. Thanks [Katyo](https://github.com/katyo) \n\n* Fix for vertex array not being managed correctly. Thanks [FrankvdStam](https://github.com/FrankvdStam) \n\n\n", "file_path": "changelog.md", "rank": 12, "score": 37130.91403191229 }, { "content": "As far as the implementation goes, I've used Emil's original egui_glium and egui_web backends (see the egui github for source) as guides to implement this version, but have deviated in a couple of ways: \n\n\n\n1. It doesn't use the App architecture as used in the original code because I wanted to keep it as simple as possible. \n\n2. I've added a *update_user_texture_data* method to the painter class, which allows for easy dynamic updating of textures that need to be managed by Egui (to render in an Image control, say). See examples/example.rs to see how this can be useful.\n\n\n\nI'm not an expert in Egui, Open GL or Rust for that matter. Please do submit an issue ticket (or better, send a PR!) if you spot something something that's out of whack in so far as the backend implementation goes. Issues regarding SDL2, Egui or OpenGL should be directed towards their respective repository owners!\n\n\n\nNote: most of essential features are supported now.\n", "file_path": "README.md", "rank": 13, "score": 37130.88039182587 }, { "content": "fn main() {\n\n let sdl_context = sdl2::init().unwrap();\n\n let video_subsystem = sdl_context.video().unwrap();\n\n let gl_attr = video_subsystem.gl_attr();\n\n gl_attr.set_context_profile(GLProfile::Core);\n\n // On linux, OpenGL ES Mesa driver 22.0.0+ can be used like so:\n\n // gl_attr.set_context_profile(GLProfile::GLES);\n\n\n\n gl_attr.set_double_buffer(true);\n\n gl_attr.set_multisample_samples(4);\n\n\n\n let window = video_subsystem\n\n .window(\n\n \"Demo: Egui backend for SDL2 + GL\",\n\n SCREEN_WIDTH,\n\n SCREEN_HEIGHT,\n\n )\n\n .opengl()\n\n .resizable()\n\n .build()\n", "file_path": "examples/basic.rs", "rank": 14, "score": 31092.61564394286 }, { "content": "fn main() {\n\n let sdl_context = sdl2::init().unwrap();\n\n let video_subsystem = sdl_context.video().unwrap();\n\n let gl_attr = video_subsystem.gl_attr();\n\n gl_attr.set_context_profile(GLProfile::Core);\n\n\n\n // Let OpenGL know we are dealing with SRGB colors so that it\n\n // can do the blending correctly. Not setting the framebuffer\n\n // leads to darkened, oversaturated colors.\n\n gl_attr.set_double_buffer(true);\n\n gl_attr.set_multisample_samples(4);\n\n gl_attr.set_framebuffer_srgb_compatible(true);\n\n\n\n // OpenGL 3.2 is the minimum that we will support.\n\n gl_attr.set_context_version(3, 2);\n\n\n\n let window = video_subsystem\n\n .window(\n\n \"Demo: Egui backend for SDL2 + GL\",\n\n SCREEN_WIDTH,\n", "file_path": "examples/mix/main.rs", "rank": 15, "score": 29618.65463454779 }, { "content": "fn main() {\n\n let sdl_context = sdl2::init().unwrap();\n\n let video_subsystem = sdl_context.video().unwrap();\n\n let gl_attr = video_subsystem.gl_attr();\n\n gl_attr.set_context_profile(GLProfile::Core);\n\n // Let OpenGL know we are dealing with SRGB colors so that it\n\n // can do the blending correctly. Not setting the framebuffer\n\n // leads to darkened, oversaturated colors.\n\n gl_attr.set_framebuffer_srgb_compatible(true);\n\n gl_attr.set_double_buffer(true);\n\n gl_attr.set_multisample_samples(4);\n\n\n\n // OpenGL 3.2 is the minimum that we will support.\n\n gl_attr.set_context_version(3, 2);\n\n\n\n let window = video_subsystem\n\n .window(\n\n \"Demo: Egui backend for SDL2 + GL\",\n\n SCREEN_WIDTH,\n\n SCREEN_HEIGHT,\n", "file_path": "examples/demo_lib.rs", "rank": 16, "score": 29618.65463454779 }, { "content": "pub trait ClipboardProvider: Sized {\n\n fn new() -> Result<Self>;\n\n fn get_contents(&mut self) -> Result<String>;\n\n fn set_contents(&mut self, contents: String) -> Result<()>;\n\n fn clear(&mut self) -> Result<()>;\n\n}\n\n\n\npub struct ClipboardContext {\n\n contents: String,\n\n}\n\n\n\nimpl ClipboardProvider for ClipboardContext {\n\n fn new() -> Result<Self> {\n\n Ok(Self {\n\n contents: Default::default(),\n\n })\n\n }\n\n fn get_contents(&mut self) -> Result<String> {\n\n Ok(self.contents.clone())\n\n }\n\n fn set_contents(&mut self, contents: String) -> Result<()> {\n\n self.contents = contents;\n\n Ok(())\n\n }\n\n fn clear(&mut self) -> Result<()> {\n\n self.contents = Default::default();\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/clipboard.rs", "rank": 17, "score": 27942.508345521426 }, { "content": " len,\n\n ptr::null_mut(),\n\n buf.as_mut_ptr() as *mut GLchar,\n\n );\n\n panic!(\n\n \"{}\",\n\n str::from_utf8(&buf).expect(\"ProgramInfoLog not valid utf8\")\n\n );\n\n }\n\n program\n\n }\n\n}\n\n\n\nimpl Painter {\n\n pub fn new(window: &sdl2::video::Window, scale: f32, shader_ver: ShaderVersion) -> Painter {\n\n unsafe {\n\n let mut egui_texture = 0;\n\n gl::load_with(|name| window.subsystem().gl_get_proc_address(name) as *const _);\n\n gl::GenTextures(1, &mut egui_texture);\n\n gl::BindTexture(gl::TEXTURE_2D, egui_texture);\n", "file_path": "src/painter.rs", "rank": 18, "score": 21908.17612979274 }, { "content": "extern crate gl;\n\nextern crate sdl2;\n\n#[cfg(feature = \"use_epi\")]\n\nuse crate::epi::TextureAllocator;\n\nuse crate::ShaderVersion;\n\nuse core::mem;\n\nuse core::ptr;\n\nuse core::str;\n\nuse egui::{\n\n paint::{Color32, Mesh, Texture},\n\n vec2, ClippedMesh, Pos2, Rect,\n\n};\n\nuse gl::types::{GLchar, GLenum, GLint, GLsizeiptr, GLsync, GLuint};\n\nuse std::ffi::CString;\n\nuse std::os::raw::c_void;\n\n\n\n#[derive(Default)]\n", "file_path": "src/painter.rs", "rank": 19, "score": 21903.093602379624 }, { "content": " color_buffer,\n\n egui_texture,\n\n gl_sync_fence: gl::FenceSync(gl::SYNC_GPU_COMMANDS_COMPLETE, 0),\n\n pixels_per_point,\n\n egui_texture_version: None,\n\n user_textures: Default::default(),\n\n canvas_size: (width, height),\n\n screen_rect,\n\n }\n\n }\n\n }\n\n\n\n pub fn update_screen_rect(&mut self, size: (u32, u32)) {\n\n self.canvas_size = size;\n\n let (x, y) = size;\n\n let rect = vec2(x as f32, y as f32) / self.pixels_per_point;\n\n self.screen_rect = Rect::from_min_size(Default::default(), rect);\n\n }\n\n\n\n pub fn new_user_texture(\n", "file_path": "src/painter.rs", "rank": 20, "score": 21901.9698136167 }, { "content": " gl::GenBuffers(1, &mut index_buffer);\n\n gl::GenBuffers(1, &mut pos_buffer);\n\n gl::GenBuffers(1, &mut tc_buffer);\n\n gl::GenBuffers(1, &mut color_buffer);\n\n\n\n let (width, height) = window.size();\n\n let pixels_per_point = scale;\n\n let rect = vec2(width as f32, height as f32) / pixels_per_point;\n\n let screen_rect = Rect::from_min_size(Pos2::new(0f32, 0f32), rect);\n\n\n\n gl::DetachShader(program, vert_shader);\n\n gl::DetachShader(program, frag_shader);\n\n gl::DeleteShader(vert_shader);\n\n gl::DeleteShader(frag_shader);\n\n Painter {\n\n vertex_array,\n\n program,\n\n index_buffer,\n\n pos_buffer,\n\n tc_buffer,\n", "file_path": "src/painter.rs", "rank": 21, "score": 21901.47755148453 }, { "content": " gl::DeleteTextures(1, &user.texture.unwrap());\n\n }\n\n }\n\n\n\n gl::DeleteProgram(self.program);\n\n gl::DeleteBuffers(1, &self.pos_buffer);\n\n gl::DeleteBuffers(1, &self.tc_buffer);\n\n gl::DeleteBuffers(1, &self.color_buffer);\n\n gl::DeleteBuffers(1, &self.index_buffer);\n\n gl::DeleteTextures(1, &self.egui_texture);\n\n gl::DeleteVertexArrays(1, &self.vertex_array);\n\n }\n\n }\n\n}\n\n\n\n#[cfg(feature = \"use_epi\")]\n\nimpl TextureAllocator for Painter {\n\n fn alloc_srgba_premultiplied(\n\n &mut self,\n\n size: (usize, usize),\n", "file_path": "src/painter.rs", "rank": 22, "score": 21900.407549687035 }, { "content": " srgba_pixels: &[egui::Color32],\n\n ) -> egui::TextureId {\n\n self.new_user_texture(size, srgba_pixels, true)\n\n }\n\n\n\n fn free(&mut self, id: egui::TextureId) {\n\n self.free_user_texture(id)\n\n }\n\n}\n\n\n\nimpl Drop for Painter {\n\n fn drop(&mut self) {\n\n self.cleanup();\n\n }\n\n}\n", "file_path": "src/painter.rs", "rank": 23, "score": 21898.813186108167 }, { "content": " let pixels_per_point = self.pixels_per_point;\n\n unsafe {\n\n if let Some(color) = bg_color {\n\n gl::ClearColor(\n\n color[0] as f32 / 255.0,\n\n color[1] as f32 / 255.0,\n\n color[2] as f32 / 255.0,\n\n color[3] as f32 / 255.0,\n\n );\n\n\n\n gl::Clear(gl::COLOR_BUFFER_BIT);\n\n }\n\n //Let OpenGL know we are dealing with SRGB colors so that it\n\n //can do the blending correctly. Not setting the framebuffer\n\n //leads to darkened, oversaturated colors.\n\n gl::Enable(gl::FRAMEBUFFER_SRGB);\n\n gl::Enable(gl::SCISSOR_TEST);\n\n gl::Enable(gl::BLEND);\n\n gl::BlendFunc(gl::ONE, gl::ONE_MINUS_SRC_ALPHA); // premultiplied alpha\n\n gl::UseProgram(self.program);\n", "file_path": "src/painter.rs", "rank": 24, "score": 21898.379740237746 }, { "content": " f_color = v_rgba * texture(u_sampler, v_tc);\n\n#endif\n\n}\n\n#endif\n\n\"#;\n\n\n\npub struct Painter {\n\n vertex_array: GLuint,\n\n program: GLuint,\n\n index_buffer: GLuint,\n\n pos_buffer: GLuint,\n\n tc_buffer: GLuint,\n\n color_buffer: GLuint,\n\n egui_texture: GLuint,\n\n // Call fence for sdl vsync so the CPU won't heat up if there's no heavy activity.\n\n pub gl_sync_fence: GLsync,\n\n egui_texture_version: Option<u64>,\n\n user_textures: Vec<Option<UserTexture>>,\n\n pub pixels_per_point: f32,\n\n pub canvas_size: (u32, u32),\n\n pub screen_rect: Rect,\n\n}\n\n\n", "file_path": "src/painter.rs", "rank": 25, "score": 21898.337317552654 }, { "content": " }));\n\n id\n\n }\n\n\n\n /// fn free_user_texture() and fn free() implemented from epi both are basically the same.\n\n pub fn free_user_texture(&mut self, id: egui::TextureId) {\n\n if let egui::TextureId::User(id) = id {\n\n let idx = id as usize;\n\n if idx < self.user_textures.len() {\n\n if let Some(UserTexture {\n\n texture: Some(texture),\n\n ..\n\n }) = self.user_textures[idx].as_mut()\n\n {\n\n unsafe { gl::DeleteTextures(1, texture) }\n\n }\n\n self.user_textures[idx] = None\n\n }\n\n }\n\n }\n", "file_path": "src/painter.rs", "rank": 26, "score": 21896.82128863166 }, { "content": " }\n\n }\n\n }\n\n }\n\n\n\n pub fn paint_jobs(\n\n &mut self,\n\n bg_color: Option<Color32>,\n\n meshes: Vec<ClippedMesh>,\n\n egui_texture: &Texture,\n\n ) {\n\n unsafe {\n\n gl::PixelStorei(gl::UNPACK_ROW_LENGTH, 0);\n\n gl::PixelStorei(gl::UNPACK_ALIGNMENT, 4);\n\n }\n\n\n\n self.upload_egui_texture(egui_texture);\n\n self.upload_user_textures();\n\n\n\n let (canvas_width, canvas_height) = self.canvas_size;\n", "file_path": "src/painter.rs", "rank": 27, "score": 21896.699150257664 }, { "content": " filtering,\n\n dirty: true,\n\n }));\n\n id\n\n }\n\n\n\n /// Creates a new user texture from rgba8\n\n pub fn new_user_texture_rgba8(\n\n &mut self,\n\n size: (usize, usize),\n\n rgba8_pixels: Vec<u8>,\n\n filtering: bool,\n\n ) -> egui::TextureId {\n\n let id = egui::TextureId::User(self.user_textures.len() as u64);\n\n self.user_textures.push(Some(UserTexture {\n\n size,\n\n pixels: rgba8_pixels,\n\n texture: None,\n\n filtering,\n\n dirty: true,\n", "file_path": "src/painter.rs", "rank": 28, "score": 21895.93895203898 }, { "content": " }\n\n }\n\n }\n\n }\n\n\n\n /// Updates texture rgba8 data\n\n pub fn update_user_texture_rgba8_data(\n\n &mut self,\n\n texture_id: egui::TextureId,\n\n rgba8_pixels: Vec<u8>,\n\n ) {\n\n match texture_id {\n\n egui::TextureId::Egui => {}\n\n egui::TextureId::User(id) => {\n\n let id = id as usize;\n\n if id < self.user_textures.len() {\n\n if let Some(user_textures) = self.user_textures[id].as_mut() {\n\n user_textures.pixels = rgba8_pixels;\n\n user_textures.dirty = true\n\n }\n", "file_path": "src/painter.rs", "rank": 29, "score": 21895.6445873092 }, { "content": " gl::ActiveTexture(gl::TEXTURE0);\n\n\n\n let u_screen_size = CString::new(\"u_screen_size\").unwrap();\n\n let u_screen_size_ptr = u_screen_size.as_ptr();\n\n let u_screen_size_loc = gl::GetUniformLocation(self.program, u_screen_size_ptr);\n\n let (x, y) = (self.screen_rect.width(), self.screen_rect.height());\n\n gl::Uniform2f(u_screen_size_loc, x, y);\n\n let u_sampler = CString::new(\"u_sampler\").unwrap();\n\n let u_sampler_ptr = u_sampler.as_ptr();\n\n let u_sampler_loc = gl::GetUniformLocation(self.program, u_sampler_ptr);\n\n gl::Uniform1i(u_sampler_loc, 0);\n\n gl::Viewport(0, 0, canvas_width as i32, canvas_height as i32);\n\n let screen_x = canvas_width as f32;\n\n let screen_y = canvas_height as f32;\n\n\n\n for ClippedMesh(clip_rect, mesh) in meshes {\n\n if let Some(texture_id) = self.get_texture(mesh.texture_id) {\n\n gl::BindTexture(gl::TEXTURE_2D, texture_id);\n\n let clip_min_x = pixels_per_point * clip_rect.min.x;\n\n let clip_min_y = pixels_per_point * clip_rect.min.y;\n", "file_path": "src/painter.rs", "rank": 30, "score": 21895.59049877931 }, { "content": " }\n\n\n\n // --------------------------------------------------------------------\n\n\n\n gl::BindBuffer(gl::ARRAY_BUFFER, self.pos_buffer);\n\n gl::BufferData(\n\n gl::ARRAY_BUFFER,\n\n (positions.len() * mem::size_of::<f32>()) as GLsizeiptr,\n\n //mem::transmute(&positions.as_ptr()),\n\n positions.as_ptr() as *const gl::types::GLvoid,\n\n gl::STREAM_DRAW,\n\n );\n\n\n\n let a_pos = CString::new(\"a_pos\").unwrap();\n\n let a_pos_ptr = a_pos.as_ptr();\n\n let a_pos_loc = gl::GetAttribLocation(self.program, a_pos_ptr);\n\n assert!(a_pos_loc >= 0);\n\n let a_pos_loc = a_pos_loc as u32;\n\n\n\n let stride = 0;\n", "file_path": "src/painter.rs", "rank": 31, "score": 21895.542961835297 }, { "content": "\n\n pub fn update_user_texture_data(&mut self, texture_id: egui::TextureId, _pixels: &[Color32]) {\n\n match texture_id {\n\n egui::TextureId::Egui => {}\n\n egui::TextureId::User(id) => {\n\n let id = id as usize;\n\n assert!(id < self.user_textures.len());\n\n if let Some(UserTexture { pixels, dirty, .. }) = &mut self.user_textures[id] {\n\n {\n\n *pixels = Vec::with_capacity(pixels.len() * 4);\n\n }\n\n\n\n for p in _pixels {\n\n pixels.push(p[0]);\n\n pixels.push(p[1]);\n\n pixels.push(p[2]);\n\n pixels.push(p[3]);\n\n }\n\n\n\n *dirty = true;\n", "file_path": "src/painter.rs", "rank": 32, "score": 21895.520728264037 }, { "content": " gl::VertexAttribPointer(a_pos_loc, 2, gl::FLOAT, gl::FALSE, stride, ptr::null());\n\n gl::EnableVertexAttribArray(a_pos_loc);\n\n\n\n // --------------------------------------------------------------------\n\n\n\n gl::BindBuffer(gl::ARRAY_BUFFER, self.tc_buffer);\n\n gl::BufferData(\n\n gl::ARRAY_BUFFER,\n\n (tex_coords.len() * mem::size_of::<f32>()) as GLsizeiptr,\n\n //mem::transmute(&tex_coords.as_ptr()),\n\n tex_coords.as_ptr() as *const gl::types::GLvoid,\n\n gl::STREAM_DRAW,\n\n );\n\n\n\n let a_tc = CString::new(\"a_tc\").unwrap();\n\n let a_tc_ptr = a_tc.as_ptr();\n\n let a_tc_loc = gl::GetAttribLocation(self.program, a_tc_ptr);\n\n assert!(a_tc_loc >= 0);\n\n let a_tc_loc = a_tc_loc as u32;\n\n\n", "file_path": "src/painter.rs", "rank": 33, "score": 21895.150558463625 }, { "content": " gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, self.index_buffer);\n\n gl::BufferData(\n\n gl::ELEMENT_ARRAY_BUFFER,\n\n (indices_len * mem::size_of::<u16>()) as GLsizeiptr,\n\n //mem::transmute(&indices.as_ptr()),\n\n indices.as_ptr() as *const gl::types::GLvoid,\n\n gl::STREAM_DRAW,\n\n );\n\n\n\n // --------------------------------------------------------------------\n\n\n\n let mut positions: Vec<f32> = Vec::with_capacity(2 * vertices_len);\n\n let mut tex_coords: Vec<f32> = Vec::with_capacity(2 * vertices_len);\n\n {\n\n for v in &mesh.vertices {\n\n positions.push(v.pos.x);\n\n positions.push(v.pos.y);\n\n tex_coords.push(v.uv.x);\n\n tex_coords.push(v.uv.y);\n\n }\n", "file_path": "src/painter.rs", "rank": 34, "score": 21894.515739351384 }, { "content": "\n\n user_texture.dirty = false;\n\n }\n\n }\n\n }\n\n\n\n fn get_texture(&self, texture_id: egui::TextureId) -> Option<GLuint> {\n\n match texture_id {\n\n egui::TextureId::Egui => Some(self.egui_texture),\n\n egui::TextureId::User(id) => {\n\n let id = id as usize;\n\n if id < self.user_textures.len() {\n\n if let Some(user_texture) = &self.user_textures[id] {\n\n return user_texture.texture;\n\n }\n\n }\n\n None\n\n }\n\n }\n\n }\n", "file_path": "src/painter.rs", "rank": 35, "score": 21894.48403885234 }, { "content": "\n\n fn upload_egui_texture(&mut self, texture: &Texture) {\n\n if self.egui_texture_version == Some(texture.version) {\n\n return; // No change\n\n }\n\n\n\n let mut pixels: Vec<u8> = Vec::with_capacity(texture.pixels.len() * 4);\n\n for &alpha in &texture.pixels {\n\n let srgba = Color32::from_white_alpha(alpha);\n\n pixels.push(srgba[0]);\n\n pixels.push(srgba[1]);\n\n pixels.push(srgba[2]);\n\n pixels.push(srgba[3]);\n\n }\n\n\n\n unsafe {\n\n gl::BindTexture(gl::TEXTURE_2D, self.egui_texture);\n\n\n\n let level = 0;\n\n let internal_format = gl::RGBA;\n", "file_path": "src/painter.rs", "rank": 36, "score": 21894.387337969627 }, { "content": " gl::EnableVertexAttribArray(a_srgba_loc);\n\n\n\n // --------------------------------------------------------------------\n\n gl::DrawElements(\n\n gl::TRIANGLES,\n\n indices_len as i32,\n\n gl::UNSIGNED_SHORT,\n\n ptr::null(),\n\n );\n\n gl::DisableVertexAttribArray(a_pos_loc);\n\n gl::DisableVertexAttribArray(a_tc_loc);\n\n gl::DisableVertexAttribArray(a_srgba_loc);\n\n }\n\n }\n\n\n\n pub fn cleanup(&self) {\n\n unsafe {\n\n gl::DeleteSync(self.gl_sync_fence);\n\n for user in self.user_textures.iter().flatten() {\n\n if user.texture.is_some() {\n", "file_path": "src/painter.rs", "rank": 37, "score": 21894.238186902752 }, { "content": " //mem::transmute(&colors.as_ptr()),\n\n colors.as_ptr() as *const gl::types::GLvoid,\n\n gl::STREAM_DRAW,\n\n );\n\n\n\n let a_srgba = CString::new(\"a_srgba\").unwrap();\n\n let a_srgba_ptr = a_srgba.as_ptr();\n\n let a_srgba_loc = gl::GetAttribLocation(self.program, a_srgba_ptr);\n\n assert!(a_srgba_loc >= 0);\n\n let a_srgba_loc = a_srgba_loc as u32;\n\n\n\n let stride = 0;\n\n gl::VertexAttribPointer(\n\n a_srgba_loc,\n\n 4,\n\n gl::UNSIGNED_BYTE,\n\n gl::FALSE,\n\n stride,\n\n ptr::null(),\n\n );\n", "file_path": "src/painter.rs", "rank": 38, "score": 21894.091917678168 }, { "content": " let border = 0;\n\n let src_format = gl::RGBA;\n\n let src_type = gl::UNSIGNED_BYTE;\n\n gl::TexImage2D(\n\n gl::TEXTURE_2D,\n\n level,\n\n internal_format as i32,\n\n texture.width as i32,\n\n texture.height as i32,\n\n border,\n\n src_format,\n\n src_type,\n\n pixels.as_ptr() as *const c_void,\n\n );\n\n\n\n self.egui_texture_version = Some(texture.version);\n\n }\n\n }\n\n\n\n fn upload_user_textures(&mut self) {\n", "file_path": "src/painter.rs", "rank": 39, "score": 21893.889955575392 }, { "content": " gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::CLAMP_TO_EDGE as i32);\n\n gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::CLAMP_TO_EDGE as i32);\n\n gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);\n\n gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);\n\n let (vs_src, fs_src) = if let ShaderVersion::Default = shader_ver {\n\n (VS_SRC_150, FS_SRC_150)\n\n } else {\n\n (VS_SRC, FS_SRC)\n\n };\n\n let vert_shader = compile_shader(vs_src, gl::VERTEX_SHADER);\n\n let frag_shader = compile_shader(fs_src, gl::FRAGMENT_SHADER);\n\n\n\n let program = link_program(vert_shader, frag_shader);\n\n let mut vertex_array = 0;\n\n let mut index_buffer = 0;\n\n let mut pos_buffer = 0;\n\n let mut tc_buffer = 0;\n\n let mut color_buffer = 0;\n\n gl::GenVertexArrays(1, &mut vertex_array);\n\n gl::BindVertexArray(vertex_array);\n", "file_path": "src/painter.rs", "rank": 40, "score": 21893.721341191787 }, { "content": "}\n\n\n\nvoid main() {\n\n gl_Position = vec4(2.0 * a_pos.x / u_screen_size.x - 1.0, 1.0 - 2.0 * a_pos.y / u_screen_size.y, 0.0, 1.0);\n\n // egui encodes vertex colors in gamma spaces, so we must decode the colors here:\n\n v_rgba = linear_from_srgba(a_srgba);\n\n v_tc = a_tc;\n\n}\n\n\"#;\n\n\n\nconst FS_SRC: &str = r#\"\n\n#ifdef GL_ES\n\nprecision mediump float;\n\n#endif\n\n\n\nuniform sampler2D u_sampler;\n\n#if defined(GL_ES) || __VERSION__ < 140\n\nvarying vec4 v_rgba;\n\nvarying vec2 v_tc;\n\n#else\n", "file_path": "src/painter.rs", "rank": 41, "score": 21893.542861517955 }, { "content": " );\n\n gl::TexParameteri(\n\n gl::TEXTURE_2D,\n\n gl::TEXTURE_MAG_FILTER,\n\n gl::LINEAR as i32,\n\n );\n\n } else {\n\n gl::TexParameteri(\n\n gl::TEXTURE_2D,\n\n gl::TEXTURE_MIN_FILTER,\n\n gl::NEAREST as i32,\n\n );\n\n gl::TexParameteri(\n\n gl::TEXTURE_2D,\n\n gl::TEXTURE_MAG_FILTER,\n\n gl::NEAREST as i32,\n\n );\n\n }\n\n user_texture.texture = Some(gl_texture);\n\n } else {\n", "file_path": "src/painter.rs", "rank": 42, "score": 21892.898795995865 }, { "content": " unsafe {\n\n for user_texture in self.user_textures.iter_mut().flatten() {\n\n if !user_texture.dirty {\n\n continue;\n\n }\n\n\n\n let pixels = std::mem::take(&mut user_texture.pixels);\n\n\n\n if user_texture.texture.is_none() {\n\n let mut gl_texture = 0;\n\n gl::GenTextures(1, &mut gl_texture);\n\n gl::BindTexture(gl::TEXTURE_2D, gl_texture);\n\n gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::CLAMP_TO_EDGE as i32);\n\n gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::CLAMP_TO_EDGE as i32);\n\n\n\n if user_texture.filtering {\n\n gl::TexParameteri(\n\n gl::TEXTURE_2D,\n\n gl::TEXTURE_MIN_FILTER,\n\n gl::LINEAR as i32,\n", "file_path": "src/painter.rs", "rank": 43, "score": 21892.823890046373 }, { "content": "\n\n void main() {\n\n // Need to convert from SRGBA to linear.\n\n vec4 texture_rgba = linear_from_srgba(texture(u_sampler, v_tc) * 255.0);\n\n f_color = v_rgba * texture_rgba;\n\n }\n\n\"#;\n\n\n\n// VS_SRC and FS_SRC shaders taken from egui_glow crate.\n\nconst VS_SRC: &str = r#\"\n\n#if !defined(GL_ES) && __VERSION__ >= 140\n\n#define I in\n\n#define O out\n\n#define V(x) x\n\n#else\n\n#define I attribute\n\n#define O varying\n\n#define V(x) vec3(x)\n\n#endif\n\n\n", "file_path": "src/painter.rs", "rank": 44, "score": 21892.67507815664 }, { "content": " }\n\n }\n\n\n\n gl::Disable(gl::SCISSOR_TEST);\n\n gl::Disable(gl::FRAMEBUFFER_SRGB);\n\n gl::Disable(gl::BLEND);\n\n }\n\n }\n\n\n\n fn paint_mesh(&self, mesh: &Mesh) {\n\n debug_assert!(mesh.is_valid());\n\n unsafe {\n\n let indices: Vec<u16> = mesh.indices.iter().map(move |idx| *idx as u16).collect();\n\n let indices_len = indices.len();\n\n let vertices = &mesh.vertices;\n\n let vertices_len = vertices.len();\n\n\n\n // --------------------------------------------------------------------\n\n\n\n gl::BindVertexArray(self.vertex_array);\n", "file_path": "src/painter.rs", "rank": 45, "score": 21892.59005014889 }, { "content": " gl::BindTexture(gl::TEXTURE_2D, user_texture.texture.unwrap());\n\n }\n\n\n\n let level = 0;\n\n let internal_format = gl::RGBA;\n\n let border = 0;\n\n let src_format = gl::RGBA;\n\n let src_type = gl::UNSIGNED_BYTE;\n\n\n\n gl::TexImage2D(\n\n gl::TEXTURE_2D,\n\n level,\n\n internal_format as i32,\n\n user_texture.size.0 as i32,\n\n user_texture.size.1 as i32,\n\n border,\n\n src_format,\n\n src_type,\n\n pixels.as_ptr() as *const c_void,\n\n );\n", "file_path": "src/painter.rs", "rank": 46, "score": 21892.59005014889 }, { "content": " let stride = 0;\n\n gl::VertexAttribPointer(a_tc_loc, 2, gl::FLOAT, gl::FALSE, stride, ptr::null());\n\n gl::EnableVertexAttribArray(a_tc_loc);\n\n\n\n // --------------------------------------------------------------------\n\n\n\n let mut colors: Vec<u8> = Vec::with_capacity(4 * vertices_len);\n\n {\n\n for v in vertices {\n\n colors.push(v.color[0]);\n\n colors.push(v.color[1]);\n\n colors.push(v.color[2]);\n\n colors.push(v.color[3]);\n\n }\n\n }\n\n\n\n gl::BindBuffer(gl::ARRAY_BUFFER, self.color_buffer);\n\n gl::BufferData(\n\n gl::ARRAY_BUFFER,\n\n (colors.len() * mem::size_of::<u8>()) as GLsizeiptr,\n", "file_path": "src/painter.rs", "rank": 47, "score": 21892.576685636377 }, { "content": " vec4 texture_rgba = texture2D(u_sampler, v_tc);\n\n#endif\n\n\n\n /// Multiply vertex color with texture color (in linear space).\n\n gl_FragColor = v_rgba * texture_rgba;\n\n\n\n // We must gamma-encode again since WebGL doesn't support linear blending in the framebuffer.\n\n gl_FragColor = srgba_from_linear(v_rgba * texture_rgba) / 255.0;\n\n\n\n // WebGL doesn't support linear blending in the framebuffer,\n\n // so we apply this hack to at least get a bit closer to the desired blending:\n\n gl_FragColor.a = pow(gl_FragColor.a, 1.6); // Empiric nonsense\n\n}\n\n#else\n\nvoid main() {\n\n // The texture sampler is sRGB aware, and OpenGL already expects linear rgba output\n\n // so no need for any sRGB conversions here:\n\n#if __VERSION__ < 140\n\n gl_FragColor = v_rgba * texture2D(u_sampler, v_tc);\n\n#else\n", "file_path": "src/painter.rs", "rank": 48, "score": 21892.409053596108 }, { "content": " &mut self,\n\n size: (usize, usize),\n\n srgba_pixels: &[Color32],\n\n filtering: bool,\n\n ) -> egui::TextureId {\n\n assert_eq!(size.0 * size.1, srgba_pixels.len());\n\n\n\n let mut pixels: Vec<u8> = Vec::with_capacity(srgba_pixels.len() * 4);\n\n for srgba in srgba_pixels {\n\n pixels.push(srgba[0]);\n\n pixels.push(srgba[1]);\n\n pixels.push(srgba[2]);\n\n pixels.push(srgba[3]);\n\n }\n\n\n\n let id = egui::TextureId::User(self.user_textures.len() as u64);\n\n self.user_textures.push(Some(UserTexture {\n\n size,\n\n pixels,\n\n texture: None,\n", "file_path": "src/painter.rs", "rank": 49, "score": 21891.72169642559 }, { "content": " gl::GetShaderInfoLog(\n\n shader,\n\n len,\n\n ptr::null_mut(),\n\n buf.as_mut_ptr() as *mut GLchar,\n\n );\n\n panic!(\n\n \"{}\",\n\n str::from_utf8(&buf).expect(\"ShaderInfoLog not valid utf8\")\n\n );\n\n }\n\n }\n\n shader\n\n}\n\n\n", "file_path": "src/painter.rs", "rank": 50, "score": 21891.523010954144 }, { "content": "vec3 linear_from_srgb(vec3 srgb) {\n\n bvec3 cutoff = lessThan(srgb, vec3(10.31475));\n\n vec3 lower = srgb / vec3(3294.6);\n\n vec3 higher = pow((srgb + vec3(14.025)) / vec3(269.025), vec3(2.4));\n\n return mix(higher, lower, vec3(cutoff));\n\n}\n\n\n\nvec4 linear_from_srgba(vec4 srgba) {\n\n return vec4(linear_from_srgb(srgba.rgb), srgba.a / 255.0);\n\n}\n\n#endif\n\n#endif\n\n\n\n#ifdef GL_ES\n\nvoid main() {\n\n#if __VERSION__ < 300\n\n // We must decode the colors, since WebGL doesn't come with sRGBA textures:\n\n vec4 texture_rgba = linear_from_srgba(texture2D(u_sampler, v_tc) * 255.0);\n\n#else\n\n // The texture is set up with `SRGB8_ALPHA8`, so no need to decode here!\n", "file_path": "src/painter.rs", "rank": 51, "score": 21891.500433446374 }, { "content": " void main() {\n\n gl_Position = vec4(\n\n 2.0 * a_pos.x / u_screen_size.x - 1.0,\n\n 1.0 - 2.0 * a_pos.y / u_screen_size.y,\n\n 0.0,\n\n 1.0);\n\n v_rgba = linear_from_srgba(a_srgba);\n\n v_tc = a_tc;\n\n }\n\n\"#;\n\n\n\nconst FS_SRC_150: &str = r#\"\n\n #version 150\n\n uniform sampler2D u_sampler;\n\n in vec4 v_rgba;\n\n in vec2 v_tc;\n\n out vec4 f_color;\n\n\n\n // 0-255 sRGB from 0-1 linear\n\n vec3 srgb_from_linear(vec3 rgb) {\n", "file_path": "src/painter.rs", "rank": 52, "score": 21891.308281935748 }, { "content": "in vec4 v_rgba;\n\nin vec2 v_tc;\n\nout vec4 f_color;\n\n#endif\n\n\n\n#ifdef GL_ES\n\n// 0-255 sRGB from 0-1 linear\n\nvec3 srgb_from_linear(vec3 rgb) {\n\n bvec3 cutoff = lessThan(rgb, vec3(0.0031308));\n\n vec3 lower = rgb * vec3(3294.6);\n\n vec3 higher = vec3(269.025) * pow(rgb, vec3(1.0 / 2.4)) - vec3(14.025);\n\n return mix(higher, lower, vec3(cutoff));\n\n}\n\n\n\nvec4 srgba_from_linear(vec4 rgba) {\n\n return vec4(srgb_from_linear(rgba.rgb), 255.0 * rgba.a);\n\n}\n\n\n\n#if __VERSION__ < 300\n\n// 0-1 linear from 0-255 sRGB\n", "file_path": "src/painter.rs", "rank": 53, "score": 21891.113782395052 }, { "content": "#ifdef GL_ES\n\nprecision mediump float;\n\n#endif\n\nuniform vec2 u_screen_size;\n\nI vec2 a_pos;\n\nI vec4 a_srgba; // 0-255 sRGB\n\nI vec2 a_tc;\n\nO vec4 v_rgba;\n\nO vec2 v_tc;\n\n\n\n// 0-1 linear from 0-255 sRGB\n\nvec3 linear_from_srgb(vec3 srgb) {\n\n bvec3 cutoff = lessThan(srgb, vec3(10.31475));\n\n vec3 lower = srgb / vec3(3294.6);\n\n vec3 higher = pow((srgb + vec3(14.025)) / vec3(269.025), vec3(2.4));\n\n return mix(higher, lower, V(cutoff));\n\n}\n\n\n\nvec4 linear_from_srgba(vec4 srgba) {\n\n return vec4(linear_from_srgb(srgba.rgb), srgba.a / 255.0);\n", "file_path": "src/painter.rs", "rank": 54, "score": 21890.983927700167 }, { "content": " let clip_max_x = pixels_per_point * clip_rect.max.x;\n\n let clip_max_y = pixels_per_point * clip_rect.max.y;\n\n let clip_min_x = clip_min_x.clamp(0.0, x);\n\n let clip_min_y = clip_min_y.clamp(0.0, y);\n\n let clip_max_x = clip_max_x.clamp(clip_min_x, screen_x);\n\n let clip_max_y = clip_max_y.clamp(clip_min_y, screen_y);\n\n let clip_min_x = clip_min_x.round() as i32;\n\n let clip_min_y = clip_min_y.round() as i32;\n\n let clip_max_x = clip_max_x.round() as i32;\n\n let clip_max_y = clip_max_y.round() as i32;\n\n\n\n //scissor Y coordinate is from the bottom\n\n gl::Scissor(\n\n clip_min_x,\n\n canvas_height as i32 - clip_max_y,\n\n clip_max_x - clip_min_x,\n\n clip_max_y - clip_min_y,\n\n );\n\n\n\n self.paint_mesh(&mesh);\n", "file_path": "src/painter.rs", "rank": 55, "score": 21890.744326280532 }, { "content": " #version 150\n\n uniform vec2 u_screen_size;\n\n in vec2 a_pos;\n\n in vec4 a_srgba; // 0-255 sRGB\n\n in vec2 a_tc;\n\n out vec4 v_rgba;\n\n out vec2 v_tc;\n\n\n\n // 0-1 linear from 0-255 sRGB\n\n vec3 linear_from_srgb(vec3 srgb) {\n\n bvec3 cutoff = lessThan(srgb, vec3(10.31475));\n\n vec3 lower = srgb / vec3(3294.6);\n\n vec3 higher = pow((srgb + vec3(14.025)) / vec3(269.025), vec3(2.4));\n\n return mix(higher, lower, cutoff);\n\n }\n\n\n\n vec4 linear_from_srgba(vec4 srgba) {\n\n return vec4(linear_from_srgb(srgba.rgb), srgba.a / 255.0);\n\n }\n\n\n", "file_path": "src/painter.rs", "rank": 56, "score": 21889.770889426796 }, { "content": " bvec3 cutoff = lessThan(rgb, vec3(0.0031308));\n\n vec3 lower = rgb * vec3(3294.6);\n\n vec3 higher = vec3(269.025) * pow(rgb, vec3(1.0 / 2.4)) - vec3(14.025);\n\n return mix(higher, lower, vec3(cutoff));\n\n }\n\n\n\n vec4 srgba_from_linear(vec4 rgba) {\n\n return vec4(srgb_from_linear(rgba.rgb), 255.0 * rgba.a);\n\n }\n\n\n\n vec3 linear_from_srgb(vec3 srgb) {\n\n bvec3 cutoff = lessThan(srgb, vec3(10.31475));\n\n vec3 lower = srgb / vec3(3294.6);\n\n vec3 higher = pow((srgb + vec3(14.025)) / vec3(269.025), vec3(2.4));\n\n return mix(higher, lower, vec3(cutoff));\n\n }\n\n\n\n vec4 linear_from_srgba(vec4 srgba) {\n\n return vec4(linear_from_srgb(srgba.rgb), srgba.a / 255.0);\n\n }\n", "file_path": "src/painter.rs", "rank": 57, "score": 21889.770889426796 }, { "content": "use egui_backend::{\n\n egui,\n\n epi::{\n\n backend::{AppOutput, FrameBuilder},\n\n App, IntegrationInfo,\n\n },\n\n get_frame_time, gl, sdl2,\n\n sdl2::event::Event,\n\n sdl2::video::GLProfile,\n\n sdl2::video::SwapInterval,\n\n DpiScaling, ShaderVersion, Signal,\n\n};\n\nuse std::{sync::Arc, time::Instant};\n\n// Alias the backend to something less mouthful\n\nuse egui_sdl2_gl as egui_backend;\n\nconst SCREEN_WIDTH: u32 = 800;\n\nconst SCREEN_HEIGHT: u32 = 600;\n\n\n", "file_path": "examples/demo_lib.rs", "rank": 62, "score": 17.146101709497245 }, { "content": "use std::time::Instant;\n\n//Alias the backend to something less mouthful\n\nuse egui_backend::egui::{vec2, Color32, Image};\n\nuse egui_backend::sdl2::video::GLProfile;\n\nuse egui_backend::{egui, gl, sdl2};\n\nuse egui_backend::{sdl2::event::Event, DpiScaling, ShaderVersion};\n\nuse egui_sdl2_gl as egui_backend;\n\nuse sdl2::video::SwapInterval;\n\nmod triangle;\n\n\n\nconst SCREEN_WIDTH: u32 = 800;\n\nconst SCREEN_HEIGHT: u32 = 600;\n\nconst PIC_WIDTH: i32 = 320;\n\nconst PIC_HEIGHT: i32 = 192;\n\n\n", "file_path": "examples/mix/main.rs", "rank": 63, "score": 16.111688041476892 }, { "content": " // Process input event\n\n egui_state.process_input(&window, event, &mut painter);\n\n }\n\n }\n\n }\n\n } else {\n\n for event in event_pump.poll_iter() {\n\n match event {\n\n Event::Quit { .. } => break 'running,\n\n _ => {\n\n // Process input event\n\n egui_state.process_input(&window, event, &mut painter);\n\n }\n\n }\n\n }\n\n }\n\n\n\n // For default dpi scaling only, Update window when the size of resized window is very small (to avoid egui::CentralPanel distortions).\n\n // if egui_ctx.used_size() != painter.screen_rect.size() {\n\n // println!(\"resized.\");\n", "file_path": "examples/demo_lib.rs", "rank": 64, "score": 15.929492246964637 }, { "content": "use egui::Checkbox;\n\nuse egui_backend::sdl2::video::GLProfile;\n\nuse egui_backend::{egui, gl, sdl2};\n\nuse egui_backend::{sdl2::event::Event, DpiScaling, ShaderVersion};\n\nuse std::time::Instant;\n\n// Alias the backend to something less mouthful\n\nuse egui_sdl2_gl as egui_backend;\n\nuse sdl2::video::SwapInterval;\n\n\n\nconst SCREEN_WIDTH: u32 = 800;\n\nconst SCREEN_HEIGHT: u32 = 600;\n\n\n", "file_path": "examples/basic.rs", "rank": 65, "score": 15.35959872000199 }, { "content": " )\n\n .opengl()\n\n .resizable()\n\n .build()\n\n .unwrap();\n\n\n\n // Create a window context\n\n let _ctx = window.gl_create_context().unwrap();\n\n debug_assert_eq!(gl_attr.context_profile(), GLProfile::Core);\n\n debug_assert_eq!(gl_attr.context_version(), (3, 2));\n\n\n\n // Enable vsync\n\n window\n\n .subsystem()\n\n .gl_set_swap_interval(SwapInterval::VSync)\n\n .unwrap();\n\n\n\n // Init egui stuff\n\n let (mut painter, mut egui_state) =\n\n egui_backend::with_sdl2(&window, ShaderVersion::Default, DpiScaling::Custom(1.25));\n", "file_path": "examples/demo_lib.rs", "rank": 66, "score": 15.358470658413616 }, { "content": " .unwrap();\n\n\n\n // Create a window context\n\n let _ctx = window.gl_create_context().unwrap();\n\n // Init egui stuff\n\n let shader_ver = ShaderVersion::Default;\n\n // On linux use GLES SL 100+, like so:\n\n // let shader_ver = ShaderVersion::Adaptive;\n\n let (mut painter, mut egui_state) =\n\n egui_backend::with_sdl2(&window, shader_ver, DpiScaling::Custom(2.0));\n\n let mut egui_ctx = egui::CtxRef::default();\n\n let mut event_pump = sdl_context.event_pump().unwrap();\n\n\n\n let mut test_str: String =\n\n \"A text box to write in. Cut, copy, paste commands are available.\".to_owned();\n\n\n\n let mut enable_vsync = false;\n\n let mut quit = false;\n\n let mut slider = 0.0;\n\n\n", "file_path": "examples/basic.rs", "rank": 67, "score": 15.239342862302983 }, { "content": " egui_state.process_input(&window, event, &mut painter);\n\n }\n\n }\n\n }\n\n } else {\n\n painter.paint_jobs(None, paint_jobs, &egui_ctx.texture());\n\n window.gl_swap_window();\n\n for event in event_pump.poll_iter() {\n\n match event {\n\n Event::Quit { .. } => break 'running,\n\n _ => {\n\n // Process input event\n\n egui_state.process_input(&window, event, &mut painter);\n\n }\n\n }\n\n }\n\n }\n\n\n\n if quit {\n\n break;\n\n }\n\n }\n\n}\n", "file_path": "examples/basic.rs", "rank": 68, "score": 14.573417909346219 }, { "content": " let mut sine_shift = 0f32;\n\n let mut amplitude: f32 = 50f32;\n\n let mut test_str: String =\n\n \"A text box to write in. Cut, copy, paste commands are available.\".to_owned();\n\n let start_time = Instant::now();\n\n // We will draw a crisp white triangle using OpenGL.\n\n let triangle = triangle::Triangle::new();\n\n let mut quit = false;\n\n\n\n 'running: loop {\n\n egui_state.input.time = Some(start_time.elapsed().as_secs_f64());\n\n egui_ctx.begin_frame(egui_state.input.take());\n\n\n\n // An example of how OpenGL can be used to draw custom stuff with egui\n\n // overlaying it:\n\n // First clear the background to something nice.\n\n unsafe {\n\n // Clear the screen to green\n\n gl::ClearColor(0.3, 0.6, 0.3, 1.0);\n\n gl::Clear(gl::COLOR_BUFFER_BIT);\n", "file_path": "examples/mix/main.rs", "rank": 69, "score": 14.545071389989905 }, { "content": " });\n\n\n\n let (egui_output, paint_cmds) = egui_ctx.end_frame();\n\n // Process ouput\n\n egui_state.process_output(&window, &egui_output);\n\n\n\n let paint_jobs = egui_ctx.tessellate(paint_cmds);\n\n\n\n // Note: passing a bg_color to paint_jobs will clear any previously drawn stuff.\n\n // Use this only if egui is being used for all drawing and you aren't mixing your own Open GL\n\n // drawing calls with it.\n\n // Since we are custom drawing an OpenGL Triangle we don't need egui to clear the background.\n\n painter.paint_jobs(None, paint_jobs, &egui_ctx.texture());\n\n\n\n window.gl_swap_window();\n\n\n\n if !egui_output.needs_repaint {\n\n if let Some(event) = event_pump.wait_event_timeout(5) {\n\n match event {\n\n Event::Quit { .. } => break 'running,\n", "file_path": "examples/mix/main.rs", "rank": 71, "score": 12.984940885903246 }, { "content": " // let _size = egui_ctx.used_size();\n\n // let (w, h) = (_size.x as u32, _size.y as u32);\n\n // window.set_size(w, h).unwrap();\n\n // }\n\n\n\n let paint_jobs = egui_ctx.tessellate(paint_cmds);\n\n\n\n // An example of how OpenGL can be used to draw custom stuff with egui\n\n // overlaying it:\n\n // First clear the background to something nice.\n\n unsafe {\n\n // Clear the screen to green\n\n gl::ClearColor(0.3, 0.6, 0.3, 1.0);\n\n gl::Clear(gl::COLOR_BUFFER_BIT);\n\n }\n\n\n\n painter.paint_jobs(None, paint_jobs, &egui_ctx.texture());\n\n window.gl_swap_window();\n\n }\n\n}\n", "file_path": "examples/demo_lib.rs", "rank": 72, "score": 12.967274676525347 }, { "content": " _ => {\n\n // Process input event\n\n egui_state.process_input(&window, event, &mut painter);\n\n }\n\n }\n\n }\n\n } else {\n\n for event in event_pump.poll_iter() {\n\n match event {\n\n Event::Quit { .. } => break 'running,\n\n _ => {\n\n // Process input event\n\n egui_state.process_input(&window, event, &mut painter);\n\n }\n\n }\n\n }\n\n }\n\n\n\n if quit {\n\n break;\n\n }\n\n }\n\n}\n", "file_path": "examples/mix/main.rs", "rank": 73, "score": 12.928334550434744 }, { "content": " // window.set_size(w, h).unwrap();\n\n // }\n\n\n\n let paint_jobs = egui_ctx.tessellate(paint_cmds);\n\n\n\n // An example of how OpenGL can be used to draw custom stuff with egui\n\n // overlaying it:\n\n // First clear the background to something nice.\n\n unsafe {\n\n // Clear the screen to green\n\n gl::ClearColor(0.3, 0.6, 0.3, 1.0);\n\n gl::Clear(gl::COLOR_BUFFER_BIT);\n\n }\n\n\n\n if !egui_output.needs_repaint {\n\n if let Some(event) = event_pump.wait_event_timeout(5) {\n\n match event {\n\n Event::Quit { .. } => break 'running,\n\n _ => {\n\n // Process input event\n", "file_path": "examples/basic.rs", "rank": 74, "score": 12.553350651694702 }, { "content": " egui_backend::with_sdl2(&window, ShaderVersion::Default, DpiScaling::Default);\n\n let mut egui_ctx = egui::CtxRef::default();\n\n let mut event_pump: sdl2::EventPump = sdl_context.event_pump().unwrap();\n\n let mut srgba: Vec<Color32> = Vec::new();\n\n\n\n // For now we will just set everything to black, because\n\n // we will be updating it dynamically later. However, this could just as\n\n // easily have been some actual picture data loaded in.\n\n for _ in 0..PIC_HEIGHT {\n\n for _ in 0..PIC_WIDTH {\n\n srgba.push(Color32::BLACK);\n\n }\n\n }\n\n\n\n // The user texture is what allows us to mix Egui and GL rendering contexts.\n\n // Egui just needs the texture id, as the actual texture is managed by the backend.\n\n let chip8_tex_id =\n\n painter.new_user_texture((PIC_WIDTH as usize, PIC_HEIGHT as usize), &srgba, false);\n\n\n\n // Some variables to help draw a sine wave\n", "file_path": "examples/mix/main.rs", "rank": 75, "score": 12.201895263515695 }, { "content": " sine_shift += 0.1f32;\n\n\n\n // This updates the previously initialized texture with new data.\n\n // If we weren't updating the texture, this call wouldn't be required.\n\n painter.update_user_texture_data(chip8_tex_id, &srgba);\n\n\n\n egui::Window::new(\"Egui with SDL2 and GL\").show(&egui_ctx, |ui| {\n\n // Image just needs a texture id reference, so we just pass it the texture id that was returned to us\n\n // when we previously initialized the texture.\n\n ui.add(Image::new(chip8_tex_id, vec2(PIC_WIDTH as f32, PIC_HEIGHT as f32)));\n\n ui.separator();\n\n ui.label(\"A simple sine wave plotted onto a GL texture then blitted to an egui managed Image.\");\n\n ui.label(\" \");\n\n ui.text_edit_multiline(&mut test_str);\n\n ui.label(\" \");\n\n ui.add(egui::Slider::new(&mut amplitude, 0.0..=50.0).text(\"Amplitude\"));\n\n ui.label(\" \");\n\n if ui.button(\"Quit\").clicked() {\n\n quit = true;\n\n }\n", "file_path": "examples/mix/main.rs", "rank": 76, "score": 11.55352004845104 }, { "content": " ui.text_edit_multiline(&mut test_str);\n\n ui.label(\" \");\n\n ui.add(egui::Slider::new(&mut slider, 0.0..=50.0).text(\"Slider\"));\n\n ui.label(\" \");\n\n ui.add(Checkbox::new(&mut enable_vsync, \"Reduce CPU Usage?\"));\n\n ui.separator();\n\n if ui.button(\"Quit?\").clicked() {\n\n quit = true;\n\n }\n\n });\n\n\n\n let (egui_output, paint_cmds) = egui_ctx.end_frame();\n\n // Process ouput\n\n egui_state.process_output(&window, &egui_output);\n\n\n\n // For default dpi scaling only, Update window when the size of resized window is very small (to avoid egui::CentralPanel distortions).\n\n // if egui_ctx.used_size() != painter.screen_rect.size() {\n\n // println!(\"resized.\");\n\n // let _size = egui_ctx.used_size();\n\n // let (w, h) = (_size.x as u32, _size.y as u32);\n", "file_path": "examples/basic.rs", "rank": 78, "score": 11.402102254916084 }, { "content": " let start_time = Instant::now();\n\n\n\n 'running: loop {\n\n if enable_vsync {\n\n window\n\n .subsystem()\n\n .gl_set_swap_interval(SwapInterval::VSync)\n\n .unwrap()\n\n } else {\n\n window\n\n .subsystem()\n\n .gl_set_swap_interval(SwapInterval::Immediate)\n\n .unwrap()\n\n }\n\n\n\n egui_state.input.time = Some(start_time.elapsed().as_secs_f64());\n\n egui_ctx.begin_frame(egui_state.input.take());\n\n\n\n egui::CentralPanel::default().show(&egui_ctx, |ui| {\n\n ui.label(\" \");\n", "file_path": "examples/basic.rs", "rank": 80, "score": 10.86593867398534 }, { "content": " let mut app = egui_demo_lib::WrapApp::default();\n\n let mut egui_ctx = egui::CtxRef::default();\n\n let mut event_pump = sdl_context.event_pump().unwrap();\n\n let start_time = Instant::now();\n\n let repaint_signal = Arc::new(Signal::default());\n\n let mut app_output = AppOutput::default();\n\n\n\n 'running: loop {\n\n egui_state.input.time = Some(start_time.elapsed().as_secs_f64());\n\n egui_ctx.begin_frame(egui_state.input.take());\n\n // Begin frame\n\n let frame_time = get_frame_time(start_time);\n\n let mut frame = FrameBuilder {\n\n info: IntegrationInfo {\n\n web_info: None,\n\n cpu_usage: Some(frame_time),\n\n native_pixels_per_point: Some(egui_state.native_pixels_per_point),\n\n prefer_dark_mode: None,\n\n name: \"egui + sdl2 + gl\",\n\n },\n", "file_path": "examples/demo_lib.rs", "rank": 81, "score": 10.765884448622081 }, { "content": "// Draws a simple white triangle\n\n// based on the example from:\n\n// https://github.com/brendanzab/gl-rs/blob/master/gl/examples/triangle.rs\n\n\n\nuse egui_sdl2_gl::gl;\n\nuse egui_sdl2_gl::gl::types::*;\n\nuse std::ffi::CString;\n\nuse std::mem;\n\nuse std::ptr;\n\nuse std::str;\n\n\n\nconst VS_SRC: &'static str = \"\n\n#version 150\n\nin vec2 position;\n\n\n\nvoid main() {\n\n gl_Position = vec4(position, 0.0, 1.0);\n\n}\";\n\n\n\nconst FS_SRC: &'static str = \"\n", "file_path": "examples/mix/triangle.rs", "rank": 83, "score": 10.28073269795755 }, { "content": " tex_allocator: &mut painter,\n\n output: &mut app_output,\n\n repaint_signal: repaint_signal.clone(),\n\n }\n\n .build();\n\n app.update(&egui_ctx, &mut frame);\n\n let (egui_output, paint_cmds) = egui_ctx.end_frame();\n\n // Process ouput\n\n egui_state.process_output(&window, &egui_output);\n\n // Quite if needed.\n\n if app_output.quit {\n\n break 'running;\n\n }\n\n\n\n if !egui_output.needs_repaint {\n\n // Reactive every 1 second.\n\n if let Some(event) = event_pump.wait_event_timeout(1000) {\n\n match event {\n\n Event::Quit { .. } => break 'running,\n\n _ => {\n", "file_path": "examples/demo_lib.rs", "rank": 86, "score": 9.620054211560543 }, { "content": " SCREEN_HEIGHT,\n\n )\n\n .opengl()\n\n .resizable()\n\n .build()\n\n .unwrap();\n\n\n\n // Create a window context\n\n let _ctx = window.gl_create_context().unwrap();\n\n debug_assert_eq!(gl_attr.context_profile(), GLProfile::Core);\n\n debug_assert_eq!(gl_attr.context_version(), (3, 2));\n\n\n\n // Enable vsync\n\n window\n\n .subsystem()\n\n .gl_set_swap_interval(SwapInterval::VSync)\n\n .unwrap();\n\n\n\n // Init egui stuff\n\n let (mut painter, mut egui_state) =\n", "file_path": "examples/mix/main.rs", "rank": 88, "score": 8.984422500138153 }, { "content": " let mut buf = Vec::with_capacity(len as usize);\n\n buf.set_len((len as usize) - 1); // subtract 1 to skip the trailing null character\n\n gl::GetProgramInfoLog(\n\n program,\n\n len,\n\n ptr::null_mut(),\n\n buf.as_mut_ptr() as *mut GLchar,\n\n );\n\n panic!(\n\n \"{}\",\n\n str::from_utf8(&buf).expect(\"ProgramInfoLog not valid utf8\")\n\n );\n\n }\n\n program\n\n }\n\n}\n\n\n\nimpl Triangle {\n\n pub fn new() -> Self {\n\n // Create Vertex Array Object\n", "file_path": "examples/mix/triangle.rs", "rank": 90, "score": 8.011649148305949 }, { "content": " gl::ARRAY_BUFFER,\n\n (VERTEX_DATA.len() * mem::size_of::<GLfloat>()) as GLsizeiptr,\n\n mem::transmute(&VERTEX_DATA[0]),\n\n gl::STATIC_DRAW,\n\n );\n\n\n\n // Use shader program\n\n gl::UseProgram(self.program);\n\n let c_out_color = CString::new(\"out_color\").unwrap();\n\n gl::BindFragDataLocation(self.program, 0, c_out_color.as_ptr());\n\n\n\n // Specify the layout of the vertex data\n\n let c_position = CString::new(\"position\").unwrap();\n\n let pos_attr = gl::GetAttribLocation(self.program, c_position.as_ptr());\n\n gl::EnableVertexAttribArray(pos_attr as GLuint);\n\n gl::VertexAttribPointer(\n\n pos_attr as GLuint,\n\n 2,\n\n gl::FLOAT,\n\n gl::FALSE as GLboolean,\n", "file_path": "examples/mix/triangle.rs", "rank": 91, "score": 6.657406904267036 }, { "content": " }\n\n\n\n // Then draw our triangle.\n\n triangle.draw();\n\n\n\n let mut srgba: Vec<Color32> = Vec::new();\n\n let mut angle = 0f32;\n\n // Draw a cool sine wave in a buffer.\n\n for y in 0..PIC_HEIGHT {\n\n for x in 0..PIC_WIDTH {\n\n srgba.push(Color32::BLACK);\n\n if y == PIC_HEIGHT - 1 {\n\n let y = amplitude * (angle * 3.142f32 / 180f32 + sine_shift).sin();\n\n let y = PIC_HEIGHT as f32 / 2f32 - y;\n\n srgba[(y as i32 * PIC_WIDTH + x) as usize] = Color32::YELLOW;\n\n angle += 360f32 / PIC_WIDTH as f32;\n\n }\n\n }\n\n }\n\n\n", "file_path": "examples/mix/main.rs", "rank": 92, "score": 5.163104007874332 }, { "content": " 0,\n\n ptr::null(),\n\n );\n\n\n\n // Draw a triangle from the 3 vertices\n\n gl::DrawArrays(gl::TRIANGLES, 0, 3);\n\n }\n\n }\n\n}\n\n\n\nimpl Drop for Triangle {\n\n fn drop(&mut self) {\n\n unsafe {\n\n gl::DeleteProgram(self.program);\n\n gl::DeleteBuffers(1, &self.vbo);\n\n gl::DeleteVertexArrays(1, &self.vao);\n\n }\n\n }\n\n}\n", "file_path": "examples/mix/triangle.rs", "rank": 93, "score": 5.0535946230090225 }, { "content": "#[derive(Clone, Copy, Debug)]\n\npub struct Error;\n\nimpl core::fmt::Display for Error {\n\n fn fmt(&self, _f: &mut core::fmt::Formatter) -> core::fmt::Result {\n\n Ok(())\n\n }\n\n}\n\n\n\npub type Result<T> = core::result::Result<T, Error>;\n\n\n", "file_path": "src/clipboard.rs", "rank": 94, "score": 5.045101266125414 }, { "content": " let mut vao = 0;\n\n let mut vbo = 0;\n\n let vs = compile_shader(VS_SRC, gl::VERTEX_SHADER);\n\n let fs = compile_shader(FS_SRC, gl::FRAGMENT_SHADER);\n\n let program = link_program(vs, fs);\n\n unsafe {\n\n gl::GenVertexArrays(1, &mut vao);\n\n gl::GenBuffers(1, &mut vbo);\n\n }\n\n Triangle { program, vao, vbo }\n\n }\n\n\n\n pub fn draw(&self) {\n\n unsafe {\n\n gl::BindVertexArray(self.vao);\n\n\n\n // Create a Vertex Buffer Object and copy the vertex data to it\n\n\n\n gl::BindBuffer(gl::ARRAY_BUFFER, self.vbo);\n\n gl::BufferData(\n", "file_path": "examples/mix/triangle.rs", "rank": 95, "score": 4.2258708179566025 }, { "content": "#version 150\n\nout vec4 out_color;\n\n\n\nvoid main() {\n\n out_color = vec4(1.0, 1.0, 1.0, 1.0);\n\n}\";\n\n\n\nstatic VERTEX_DATA: [GLfloat; 6] = [0.0, 0.5, 0.5, -0.5, -0.5, -0.5];\n\n\n\npub struct Triangle {\n\n pub program: GLuint,\n\n pub vao: GLuint,\n\n pub vbo: GLuint,\n\n}\n\n\n", "file_path": "examples/mix/triangle.rs", "rank": 96, "score": 3.442755148501641 }, { "content": " gl::GetShaderInfoLog(\n\n shader,\n\n len,\n\n ptr::null_mut(),\n\n buf.as_mut_ptr() as *mut GLchar,\n\n );\n\n panic!(\n\n \"{}\",\n\n str::from_utf8(&buf).expect(\"ShaderInfoLog not valid utf8\")\n\n );\n\n }\n\n }\n\n shader\n\n}\n\n\n", "file_path": "examples/mix/triangle.rs", "rank": 97, "score": 1.7521215273474597 } ]
Rust
test/src/specs/tx_pool/send_large_cycles_tx.rs
chuijiaolianying/ckb
04c8effb7c77f9cb86306090c7f7747dc122ada7
use super::{new_block_assembler_config, type_lock_script_code_hash}; use crate::utils::wait_until; use crate::{Net, Node, Spec, DEFAULT_TX_PROPOSAL_WINDOW}; use ckb_app_config::CKBAppConfig; use ckb_crypto::secp::{Generator, Privkey}; use ckb_hash::{blake2b_256, new_blake2b}; use ckb_types::{ bytes::Bytes, core::{ capacity_bytes, BlockView, Capacity, DepType, ScriptHashType, TransactionBuilder, TransactionView, }, packed::{CellDep, CellInput, CellOutput, OutPoint, Script, WitnessArgs}, prelude::*, H256, }; use log::info; pub struct SendLargeCyclesTxInBlock { privkey: Privkey, lock_arg: Bytes, } impl SendLargeCyclesTxInBlock { #[allow(clippy::new_without_default)] pub fn new() -> Self { let mut generator = Generator::new(); let privkey = generator.gen_privkey(); let pubkey_data = privkey.pubkey().expect("Get pubkey failed").serialize(); let lock_arg = Bytes::from(blake2b_256(&pubkey_data)[0..20].to_vec()); SendLargeCyclesTxInBlock { privkey, lock_arg } } } impl Spec for SendLargeCyclesTxInBlock { crate::name!("send_large_cycles_tx_in_block"); crate::setup!(num_nodes: 2, connect_all: false); fn run(&self, net: &mut Net) { let mut node0 = net.nodes.remove(0); let node1 = &net.nodes[0]; node0.stop(); node0.edit_config_file( Box::new(|_| ()), Box::new(move |config| { config.tx_pool.max_tx_verify_cycles = std::u32::MAX.into(); }), ); node0.start(); node1.generate_blocks((DEFAULT_TX_PROPOSAL_WINDOW.1 + 2) as usize); info!("Generate large cycles tx"); let tx = build_tx(&node1, &self.privkey, self.lock_arg.clone()); let ret = node1.rpc_client().send_transaction_result(tx.data().into()); assert!(ret.is_err()); info!("Node0 mine large cycles tx"); node0.connect(&node1); let result = wait_until(60, || { node1.get_tip_block_number() == node0.get_tip_block_number() }); assert!(result, "node0 can't sync with node1"); node0.disconnect(&node1); let ret = node0.rpc_client().send_transaction_result(tx.data().into()); ret.expect("package large cycles tx"); node0.generate_blocks(3); let block: BlockView = node0.get_tip_block(); assert_eq!(block.transactions()[1], tx); node0.connect(&node1); info!("Wait block relay to node1"); let result = wait_until(60, || { let block2: BlockView = node1.get_tip_block(); block2.hash() == block.hash() }); assert!(result, "block can't relay to node1"); } fn modify_ckb_config(&self) -> Box<dyn Fn(&mut CKBAppConfig)> { let lock_arg = self.lock_arg.clone(); Box::new(move |config| { config.network.connect_outbound_interval_secs = 0; config.tx_pool.max_tx_verify_cycles = 5000u64; let block_assembler = new_block_assembler_config(lock_arg.clone(), ScriptHashType::Type); config.block_assembler = Some(block_assembler); }) } } pub struct SendLargeCyclesTxToRelay { privkey: Privkey, lock_arg: Bytes, } impl SendLargeCyclesTxToRelay { #[allow(clippy::new_without_default)] pub fn new() -> Self { let mut generator = Generator::new(); let privkey = generator.gen_privkey(); let pubkey_data = privkey.pubkey().expect("Get pubkey failed").serialize(); let lock_arg = Bytes::from(blake2b_256(&pubkey_data)[0..20].to_vec()); SendLargeCyclesTxToRelay { privkey, lock_arg } } } impl Spec for SendLargeCyclesTxToRelay { crate::name!("send_large_cycles_tx_to_relay"); crate::setup!(num_nodes: 2, connect_all: false); fn run(&self, net: &mut Net) { let mut node0 = net.nodes.remove(0); let node1 = &net.nodes[0]; node0.stop(); node0.edit_config_file( Box::new(|_| ()), Box::new(move |config| { config.tx_pool.max_tx_verify_cycles = std::u32::MAX.into(); }), ); node0.start(); node1.generate_blocks((DEFAULT_TX_PROPOSAL_WINDOW.1 + 2) as usize); info!("Generate large cycles tx"); let tx = build_tx(&node1, &self.privkey, self.lock_arg.clone()); let ret = node1.rpc_client().send_transaction_result(tx.data().into()); assert!(ret.is_err()); info!("Node0 mine large cycles tx"); node0.connect(&node1); let result = wait_until(60, || { node1.get_tip_block_number() == node0.get_tip_block_number() }); assert!(result, "node0 can't sync with node1"); let ret = node0.rpc_client().send_transaction_result(tx.data().into()); ret.expect("package large cycles tx"); info!("Node1 do not accept tx"); let result = wait_until(5, || { node1.rpc_client().get_transaction(tx.hash()).is_some() }); assert!(!result, "Node1 should ignore tx"); } fn modify_ckb_config(&self) -> Box<dyn Fn(&mut CKBAppConfig)> { let lock_arg = self.lock_arg.clone(); Box::new(move |config| { config.network.connect_outbound_interval_secs = 0; config.tx_pool.max_tx_verify_cycles = 5000u64; let block_assembler = new_block_assembler_config(lock_arg.clone(), ScriptHashType::Type); config.block_assembler = Some(block_assembler); }) } } fn build_tx(node: &Node, privkey: &Privkey, lock_arg: Bytes) -> TransactionView { let secp_out_point = OutPoint::new(node.dep_group_tx_hash(), 0); let lock = Script::new_builder() .args(lock_arg.pack()) .code_hash(type_lock_script_code_hash().pack()) .hash_type(ScriptHashType::Type.into()) .build(); let cell_dep = CellDep::new_builder() .out_point(secp_out_point) .dep_type(DepType::DepGroup.into()) .build(); let input1 = { let block = node.get_tip_block(); let cellbase_hash = block.transactions()[0].hash(); CellInput::new(OutPoint::new(cellbase_hash, 0), 0) }; let output1 = CellOutput::new_builder() .capacity(capacity_bytes!(100).pack()) .lock(lock) .build(); let tx = TransactionBuilder::default() .cell_dep(cell_dep) .input(input1) .output(output1) .output_data(Default::default()) .build(); let tx_hash: H256 = tx.hash().unpack(); let witness = WitnessArgs::new_builder() .lock(Some(Bytes::from(vec![0u8; 65])).pack()) .build(); let witness_len = witness.as_slice().len() as u64; let message = { let mut hasher = new_blake2b(); hasher.update(&tx_hash.as_bytes()); hasher.update(&witness_len.to_le_bytes()); hasher.update(&witness.as_slice()); let mut buf = [0u8; 32]; hasher.finalize(&mut buf); H256::from(buf) }; let sig = privkey.sign_recoverable(&message).expect("sign"); let witness = witness .as_builder() .lock(Some(Bytes::from(sig.serialize())).pack()) .build(); tx.as_advanced_builder() .witness(witness.as_bytes().pack()) .build() }
use super::{new_block_assembler_config, type_lock_script_code_hash}; use crate::utils::wait_until; use crate::{Net, Node, Spec, DEFAULT_TX_PROPOSAL_WINDOW}; use ckb_app_config::CKBAppConfig; use ckb_crypto::secp::{Generator, Privkey}; use ckb_hash::{blake2b_256, new_blake2b}; use ckb_types::{ bytes::Bytes, core::{ capacity_bytes, BlockView, Capacity, DepType, ScriptHashType, TransactionBuilder, TransactionView, }, packed::{CellDep, CellInput, CellOutput, OutPoint, Script, WitnessArgs}, prelude::*, H256, }; use log::info; pub struct SendLargeCyclesTxInBlock { privkey: Privkey, lock_arg: Bytes, } impl SendLargeCyclesTxInBlock { #[allow(clippy::new_without_default)] pub fn new() -> Self { let mut generator = Generator::new(); let privkey = generator.gen_privkey(); let pubkey_data = privkey.pubkey().expect("Get pubkey failed").serialize(); let lock_arg = Bytes::from(blake2b_256(&pubkey_data)[0..20].to_vec()); SendLargeCyclesTxInBlock { privkey, lock_arg } } } impl Spec for SendLargeCyclesTxInBlock { crate::name!("send_large_cycles_tx_in_block"); crate::setup!(num_nodes: 2, connect_all: false); fn run(&self, net: &mut Net) { let mut node0 = net.nodes.remove(0); let node1 = &net.nodes[0]; node0.stop(); node0.edit_config_file( Box::new(|_| ()), Box::new(move |config| { config.tx_pool.max_tx_verify_cycles = std::u32::MAX.into(); }), ); node0.start(); node1.generate_blocks((DEFAULT_TX_PROPOSAL_WINDOW.1 + 2) as usize); info!("Generate large cycles tx"); let tx = build_tx(&node1, &self.privkey, self.lock_arg.clone()); let ret = node1.rpc_client().send_transaction_result(tx.data().into()); assert!(ret.is_err()); info!("Node0 mine large cycles tx"); node0.connect(&node1); let result = wait_until(60, || { node1.get_tip_block_number() == node0.get_tip_block_number() }); assert!(result, "node0 can't sync with node1"); node0.disconnect(&node1); let ret = node0.rpc_client().send_transaction_result(tx.data().into()); ret.expect("package large cycles tx"); node0.generate_blocks(3);
mut Net) { let mut node0 = net.nodes.remove(0); let node1 = &net.nodes[0]; node0.stop(); node0.edit_config_file( Box::new(|_| ()), Box::new(move |config| { config.tx_pool.max_tx_verify_cycles = std::u32::MAX.into(); }), ); node0.start(); node1.generate_blocks((DEFAULT_TX_PROPOSAL_WINDOW.1 + 2) as usize); info!("Generate large cycles tx"); let tx = build_tx(&node1, &self.privkey, self.lock_arg.clone()); let ret = node1.rpc_client().send_transaction_result(tx.data().into()); assert!(ret.is_err()); info!("Node0 mine large cycles tx"); node0.connect(&node1); let result = wait_until(60, || { node1.get_tip_block_number() == node0.get_tip_block_number() }); assert!(result, "node0 can't sync with node1"); let ret = node0.rpc_client().send_transaction_result(tx.data().into()); ret.expect("package large cycles tx"); info!("Node1 do not accept tx"); let result = wait_until(5, || { node1.rpc_client().get_transaction(tx.hash()).is_some() }); assert!(!result, "Node1 should ignore tx"); } fn modify_ckb_config(&self) -> Box<dyn Fn(&mut CKBAppConfig)> { let lock_arg = self.lock_arg.clone(); Box::new(move |config| { config.network.connect_outbound_interval_secs = 0; config.tx_pool.max_tx_verify_cycles = 5000u64; let block_assembler = new_block_assembler_config(lock_arg.clone(), ScriptHashType::Type); config.block_assembler = Some(block_assembler); }) } } fn build_tx(node: &Node, privkey: &Privkey, lock_arg: Bytes) -> TransactionView { let secp_out_point = OutPoint::new(node.dep_group_tx_hash(), 0); let lock = Script::new_builder() .args(lock_arg.pack()) .code_hash(type_lock_script_code_hash().pack()) .hash_type(ScriptHashType::Type.into()) .build(); let cell_dep = CellDep::new_builder() .out_point(secp_out_point) .dep_type(DepType::DepGroup.into()) .build(); let input1 = { let block = node.get_tip_block(); let cellbase_hash = block.transactions()[0].hash(); CellInput::new(OutPoint::new(cellbase_hash, 0), 0) }; let output1 = CellOutput::new_builder() .capacity(capacity_bytes!(100).pack()) .lock(lock) .build(); let tx = TransactionBuilder::default() .cell_dep(cell_dep) .input(input1) .output(output1) .output_data(Default::default()) .build(); let tx_hash: H256 = tx.hash().unpack(); let witness = WitnessArgs::new_builder() .lock(Some(Bytes::from(vec![0u8; 65])).pack()) .build(); let witness_len = witness.as_slice().len() as u64; let message = { let mut hasher = new_blake2b(); hasher.update(&tx_hash.as_bytes()); hasher.update(&witness_len.to_le_bytes()); hasher.update(&witness.as_slice()); let mut buf = [0u8; 32]; hasher.finalize(&mut buf); H256::from(buf) }; let sig = privkey.sign_recoverable(&message).expect("sign"); let witness = witness .as_builder() .lock(Some(Bytes::from(sig.serialize())).pack()) .build(); tx.as_advanced_builder() .witness(witness.as_bytes().pack()) .build() }
let block: BlockView = node0.get_tip_block(); assert_eq!(block.transactions()[1], tx); node0.connect(&node1); info!("Wait block relay to node1"); let result = wait_until(60, || { let block2: BlockView = node1.get_tip_block(); block2.hash() == block.hash() }); assert!(result, "block can't relay to node1"); } fn modify_ckb_config(&self) -> Box<dyn Fn(&mut CKBAppConfig)> { let lock_arg = self.lock_arg.clone(); Box::new(move |config| { config.network.connect_outbound_interval_secs = 0; config.tx_pool.max_tx_verify_cycles = 5000u64; let block_assembler = new_block_assembler_config(lock_arg.clone(), ScriptHashType::Type); config.block_assembler = Some(block_assembler); }) } } pub struct SendLargeCyclesTxToRelay { privkey: Privkey, lock_arg: Bytes, } impl SendLargeCyclesTxToRelay { #[allow(clippy::new_without_default)] pub fn new() -> Self { let mut generator = Generator::new(); let privkey = generator.gen_privkey(); let pubkey_data = privkey.pubkey().expect("Get pubkey failed").serialize(); let lock_arg = Bytes::from(blake2b_256(&pubkey_data)[0..20].to_vec()); SendLargeCyclesTxToRelay { privkey, lock_arg } } } impl Spec for SendLargeCyclesTxToRelay { crate::name!("send_large_cycles_tx_to_relay"); crate::setup!(num_nodes: 2, connect_all: false); fn run(&self, net: &
random
[ { "content": "pub fn assert_new_block_committed(node: &Node, committed: &[TransactionView]) {\n\n let block = node.new_block(None, None, None);\n\n if committed != &block.transactions()[1..] {\n\n print_proposals_in_window(node);\n\n assert_eq!(committed, &block.transactions()[1..]);\n\n }\n\n}\n", "file_path": "test/src/specs/tx_pool/utils.rs", "rank": 1, "score": 315997.9713784308 }, { "content": "fn _run_spec(spec: &dyn crate::specs::Spec, net: &mut Net) -> ::std::thread::Result<()> {\n\n panic::catch_unwind(panic::AssertUnwindSafe(|| {\n\n spec.init_config(net);\n\n }))?;\n\n\n\n panic::catch_unwind(panic::AssertUnwindSafe(|| {\n\n spec.before_run(net);\n\n }))?;\n\n\n\n spec.start_node(net);\n\n\n\n panic::catch_unwind(panic::AssertUnwindSafe(|| {\n\n spec.run(net);\n\n }))\n\n}\n\n\n\n/// A group of workers\n\npub struct Workers {\n\n workers: Vec<(Sender<Command>, Worker)>,\n\n join_handles: Option<Vec<JoinHandle<()>>>,\n", "file_path": "test/src/worker.rs", "rank": 2, "score": 310395.691993443 }, { "content": "pub fn prepare_tx_family(node: &Node) -> TxFamily {\n\n // Ensure the generated transactions are conform to the cellbase mature rule\n\n let ancestor = node.new_transaction_spend_tip_cellbase();\n\n node.generate_blocks(node.consensus().cellbase_maturity().index() as usize);\n\n\n\n TxFamily::init(ancestor)\n\n}\n\n\n", "file_path": "test/src/specs/tx_pool/utils.rs", "rank": 3, "score": 296176.47573194676 }, { "content": "fn type_lock_script_code_hash() -> H256 {\n\n build_genesis_type_id_script(OUTPUT_INDEX_SECP256K1_BLAKE160_SIGHASH_ALL)\n\n .calc_script_hash()\n\n .unpack()\n\n}\n\n\n", "file_path": "test/src/specs/tx_pool/mod.rs", "rank": 4, "score": 282956.36368979095 }, { "content": "fn type_lock_script_code_hash() -> H256 {\n\n build_genesis_type_id_script(OUTPUT_INDEX_SECP256K1_BLAKE160_MULTISIG_ALL)\n\n .calc_script_hash()\n\n .unpack()\n\n}\n\n\n", "file_path": "test/src/specs/tx_pool/send_multisig_secp_tx.rs", "rank": 5, "score": 281723.82030977565 }, { "content": "pub fn wait_get_blocks(secs: u64, net: &Net) -> bool {\n\n wait_until(secs, || {\n\n if let Ok((_, _, data)) = net.receive_timeout(Duration::from_secs(1)) {\n\n if let Ok(message) = SyncMessage::from_slice(&data) {\n\n return message.to_enum().item_name() == GetBlocks::NAME;\n\n }\n\n }\n\n false\n\n })\n\n}\n", "file_path": "test/src/specs/sync/utils.rs", "rank": 6, "score": 263299.3911669818 }, { "content": "pub fn type_lock_script_code_hash() -> H256 {\n\n build_genesis_type_id_script(OUTPUT_INDEX_SECP256K1_BLAKE160_SIGHASH_ALL)\n\n .calc_script_hash()\n\n .unpack()\n\n}\n\n\n", "file_path": "util/test-chain-utils/src/chain.rs", "rank": 7, "score": 262242.1065909837 }, { "content": "fn new_block_assembler_config(lock_arg: Bytes, hash_type: ScriptHashType) -> BlockAssemblerConfig {\n\n let code_hash = if hash_type == ScriptHashType::Data {\n\n CODE_HASH_SECP256K1_BLAKE160_SIGHASH_ALL.clone()\n\n } else {\n\n type_lock_script_code_hash()\n\n };\n\n BlockAssemblerConfig {\n\n code_hash,\n\n hash_type: hash_type.into(),\n\n args: JsonBytes::from_bytes(lock_arg),\n\n message: Default::default(),\n\n }\n\n}\n", "file_path": "test/src/specs/tx_pool/mod.rs", "rank": 8, "score": 262057.0256769358 }, { "content": "fn new_block_assembler_config(lock_arg: Bytes, hash_type: ScriptHashType) -> BlockAssemblerConfig {\n\n let code_hash = if hash_type == ScriptHashType::Data {\n\n CODE_HASH_SECP256K1_BLAKE160_MULTISIG_ALL.clone()\n\n } else {\n\n type_lock_script_code_hash()\n\n };\n\n BlockAssemblerConfig {\n\n code_hash,\n\n hash_type: hash_type.into(),\n\n args: JsonBytes::from_bytes(lock_arg),\n\n message: Default::default(),\n\n }\n\n}\n", "file_path": "test/src/specs/tx_pool/send_multisig_secp_tx.rs", "rank": 9, "score": 261985.5300698857 }, { "content": "pub fn init(config: Config) -> Result<Guard, String> {\n\n if config.exporter.is_empty() {\n\n return Ok(Guard::Off);\n\n }\n\n\n\n let mut runtime_builder = Builder::new();\n\n runtime_builder\n\n .threaded_scheduler()\n\n .enable_io()\n\n .enable_time();\n\n if config.threads != 0 {\n\n runtime_builder.core_threads(config.threads);\n\n } else {\n\n runtime_builder.core_threads(2);\n\n };\n\n let (signal_sender, mut signal_receiver) = oneshot::channel();\n\n let service = move |_: Handle| async move {\n\n loop {\n\n tokio::select! { _ = &mut signal_receiver => break }\n\n }\n", "file_path": "util/metrics-service/src/lib.rs", "rank": 10, "score": 260386.43028044136 }, { "content": "/// Decompress data\n\npub fn decompress(src: BytesMut) -> Result<Bytes, io::Error> {\n\n Message::from_compressed(src).decompress()\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::{Bytes, BytesMut, Message, COMPRESSION_SIZE_THRESHOLD};\n\n\n\n #[test]\n\n fn test_no_need_compress() {\n\n let cmp_data = Message::from_raw(Bytes::from(\"1222\")).compress();\n\n\n\n let msg = Message::from_compressed(BytesMut::from(cmp_data.as_ref()));\n\n\n\n assert!(!msg.compress_flag());\n\n\n\n let demsg = msg.decompress().unwrap();\n\n\n\n assert_eq!(Bytes::from(\"1222\"), demsg)\n\n }\n", "file_path": "network/src/compress.rs", "rank": 11, "score": 259945.6168745419 }, { "content": "// Convenient way to construct an uncle block\n\nfn construct_uncle(node: &Node) -> BlockView {\n\n node.generate_block(); // Ensure exit IBD mode\n\n let uncle = node.construct_uncle();\n\n node.generate_block();\n\n\n\n uncle\n\n}\n\n\n", "file_path": "test/src/specs/mining/uncle.rs", "rank": 12, "score": 259806.35977962255 }, { "content": "// Check the given transaction aren't committed\n\npub fn assert_transaction_not_committed(node: &Node, transaction: &TransactionView) {\n\n let tip_number = node.get_tip_block_number();\n\n let tx_hash = transaction.hash();\n\n (1..tip_number).for_each(|number| {\n\n let block = node.get_block_by_number(number);\n\n assert!(!block\n\n .transactions()\n\n .iter()\n\n .any(|tx| { tx.hash() == tx_hash }));\n\n });\n\n}\n", "file_path": "test/src/assertion/tx_assertion.rs", "rank": 13, "score": 257689.0940364246 }, { "content": "// Check the given transactions were committed\n\npub fn assert_transactions_committed(node: &Node, transactions: &[TransactionView]) {\n\n let tip_number = node.get_tip_block_number();\n\n let mut hashes: HashSet<_> = transactions.iter().map(|tx| tx.hash()).collect();\n\n (1..tip_number).for_each(|number| {\n\n let block = node.get_block_by_number(number);\n\n block.transactions().iter().skip(1).for_each(|tx| {\n\n hashes.remove(&tx.hash());\n\n });\n\n });\n\n assert!(hashes.is_empty());\n\n}\n\n\n", "file_path": "test/src/assertion/tx_assertion.rs", "rank": 14, "score": 257689.0940364246 }, { "content": "fn is_transaction_existed(node: &Node, tx_hash: Byte32) {\n\n let tx_status = node\n\n .rpc_client()\n\n .get_transaction(tx_hash)\n\n .expect(\"node should contains transaction\");\n\n is_committed(&tx_status);\n\n}\n", "file_path": "test/src/specs/sync/chain_forks.rs", "rank": 15, "score": 253339.22851079848 }, { "content": "pub fn transferred_byte_cycles(bytes: u64) -> u64 {\n\n // Compiler will optimize the divisin here to shifts.\n\n (bytes + BYTES_PER_CYCLE - 1) / BYTES_PER_CYCLE\n\n}\n\n\n", "file_path": "script/src/cost_model.rs", "rank": 16, "score": 253294.48105190226 }, { "content": "fn conflict_transactions(node: &Node) -> (TransactionView, TransactionView) {\n\n let txa = node.new_transaction_spend_tip_cellbase();\n\n let output_data = Bytes::from(b\"b0b\".to_vec());\n\n let output = txa\n\n .output(0)\n\n .unwrap()\n\n .as_builder()\n\n .build_exact_capacity(Capacity::bytes(output_data.len()).unwrap())\n\n .unwrap();\n\n let txb = txa\n\n .as_advanced_builder()\n\n .set_outputs_data(vec![output_data.pack()])\n\n .set_outputs(vec![output])\n\n .build();\n\n assert_ne!(txa.hash(), txb.hash());\n\n (txa, txb)\n\n}\n\n\n", "file_path": "test/src/specs/tx_pool/collision.rs", "rank": 17, "score": 250797.1181859277 }, { "content": "/// Return a block with `proposals = [], transactions = [cellbase], uncles = []`\n\npub fn blank(node: &Node) -> BlockView {\n\n let example = node.new_block(None, None, None);\n\n example\n\n .as_advanced_builder()\n\n .set_proposals(vec![])\n\n .set_transactions(vec![example.transaction(0).unwrap()]) // cellbase\n\n .set_uncles(vec![])\n\n .build()\n\n}\n\n\n", "file_path": "test/src/utils.rs", "rank": 18, "score": 247978.76016872923 }, { "content": "// Convenient way to add all the fork-blocks as uncles into the main chain\n\nfn until_no_uncles_left(node: &Node) {\n\n loop {\n\n let block = node.new_block(None, None, None);\n\n if block.uncles().into_iter().count() == 0 {\n\n break;\n\n }\n\n node.submit_block(&block);\n\n }\n\n}\n", "file_path": "test/src/specs/mining/uncle.rs", "rank": 19, "score": 246181.90182207874 }, { "content": "/// Return a blank block with additional committed transactions\n\npub fn commit(node: &Node, committed: &[&TransactionView]) -> BlockView {\n\n let committed = committed\n\n .iter()\n\n .map(|t| t.to_owned().to_owned())\n\n .collect::<Vec<_>>();\n\n blank(node)\n\n .as_advanced_builder()\n\n .transactions(committed)\n\n .build()\n\n}\n\n\n", "file_path": "test/src/utils.rs", "rank": 20, "score": 245826.09470766532 }, { "content": "/// Return a blank block with additional proposed transactions\n\npub fn propose(node: &Node, proposals: &[&TransactionView]) -> BlockView {\n\n let proposals = proposals.iter().map(|tx| tx.proposal_short_id());\n\n blank(node)\n\n .as_advanced_builder()\n\n .proposals(proposals)\n\n .build()\n\n}\n\n\n", "file_path": "test/src/utils.rs", "rank": 21, "score": 245826.09470766532 }, { "content": "pub fn init(config: Config) -> Result<LoggerInitGuard, SetLoggerError> {\n\n setup_panic_logger();\n\n\n\n let logger = Logger::new(config);\n\n let filter = logger.filter();\n\n log::set_boxed_logger(Box::new(logger)).map(|_| {\n\n log::set_max_level(filter);\n\n LoggerInitGuard\n\n })\n\n}\n\n\n", "file_path": "util/logger-service/src/lib.rs", "rank": 22, "score": 243823.7810901613 }, { "content": "fn secp_lock_arg(privkey: &Privkey) -> Bytes {\n\n let pubkey_data = privkey.pubkey().expect(\"Get pubkey failed\").serialize();\n\n Bytes::from((&blake2b_256(&pubkey_data)[0..20]).to_owned())\n\n}\n\n\n", "file_path": "spec/src/lib.rs", "rank": 23, "score": 241777.18417218598 }, { "content": "pub fn secp_cell() -> &'static (CellOutput, Bytes, Script) {\n\n &SECP_CELL\n\n}\n\n\n", "file_path": "benches/benches/benchmarks/util.rs", "rank": 24, "score": 240975.60058104427 }, { "content": "fn sync_header(net: &Net, peer_id: PeerIndex, block: &BlockView) {\n\n net.send(\n\n SupportProtocols::Sync.protocol_id(),\n\n peer_id,\n\n build_header(&block.header()),\n\n );\n\n}\n\n\n", "file_path": "test/src/specs/sync/block_sync.rs", "rank": 25, "score": 240883.17682253176 }, { "content": "fn sync_block(net: &Net, peer_id: PeerIndex, block: &BlockView) {\n\n net.send(\n\n SupportProtocols::Sync.protocol_id(),\n\n peer_id,\n\n build_block(block),\n\n );\n\n}\n\n\n", "file_path": "test/src/specs/sync/block_sync.rs", "rank": 26, "score": 240883.17682253176 }, { "content": "fn build_forks(node: &Node, offsets: &[u64]) -> Vec<BlockView> {\n\n let rpc_client = node.rpc_client();\n\n let mut blocks = Vec::with_capacity(offsets.len());\n\n for offset in offsets.iter() {\n\n let mut template = rpc_client.get_block_template(None, None, None);\n\n template.current_time = (template.current_time.value() + offset).into();\n\n let block = new_block_with_template(template);\n\n node.submit_block(&block);\n\n\n\n blocks.push(block);\n\n }\n\n blocks\n\n}\n\n\n", "file_path": "test/src/specs/sync/block_sync.rs", "rank": 27, "score": 239940.9454000768 }, { "content": "fn dump_chain(node: &Node) -> Vec<BlockView> {\n\n (1..=node.get_tip_block_number())\n\n .map(|number| node.get_block_by_number(number))\n\n .collect()\n\n}\n", "file_path": "test/src/specs/tx_pool/reorg_proposals.rs", "rank": 28, "score": 239774.16064939363 }, { "content": "/// Generate new blocks and explode these cellbases into `n` live cells\n\npub fn generate_utxo_set(node: &Node, n: usize) -> TXOSet {\n\n // Ensure all the cellbases will be used later are already mature.\n\n let cellbase_maturity = node.consensus().cellbase_maturity();\n\n node.generate_blocks(cellbase_maturity.index() as usize);\n\n\n\n // Explode these mature cellbases into multiple cells\n\n let mut n_outputs = 0;\n\n let mut txs = Vec::new();\n\n while n > n_outputs {\n\n node.generate_block();\n\n let mature_number = node.get_tip_block_number() - cellbase_maturity.index();\n\n let mature_block = node.get_block_by_number(mature_number);\n\n let mature_cellbase = mature_block.transaction(0).unwrap();\n\n if mature_cellbase.outputs().is_empty() {\n\n continue;\n\n }\n\n\n\n let mature_utxos: TXOSet = TXOSet::from(&mature_cellbase);\n\n let tx = mature_utxos.boom(vec![node.always_success_cell_dep()]);\n\n n_outputs += tx.outputs().len();\n", "file_path": "test/src/utils.rs", "rank": 29, "score": 237618.9122197788 }, { "content": "fn print_proposals_in_window(node: &Node) {\n\n let number = node.get_tip_block_number();\n\n let window = node.consensus().tx_proposal_window();\n\n let proposal_start = number.saturating_sub(window.farthest()) + 1;\n\n let proposal_end = number.saturating_sub(window.closest()) + 1;\n\n for number in proposal_start..=proposal_end {\n\n let block = node.get_block_by_number(number);\n\n println!(\n\n \"\\tBlock[#{}].proposals: {:?}\",\n\n number,\n\n block.union_proposal_ids()\n\n );\n\n }\n\n}\n\n\n", "file_path": "test/src/specs/tx_pool/utils.rs", "rank": 30, "score": 235460.92540721758 }, { "content": "// Clear net message channel\n\npub fn clear_messages(net: &Net) {\n\n while net.receive_timeout(Duration::new(3, 0)).is_ok() {}\n\n}\n\n\n", "file_path": "test/src/utils.rs", "rank": 31, "score": 232112.48576449772 }, { "content": "fn consensus_from_spec(spec: &ChainSpec) -> Result<Consensus, ExitCode> {\n\n spec.build_consensus().map_err(|err| {\n\n eprintln!(\"chainspec error: {}\", err);\n\n ExitCode::Config\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::cli::CMD_STATS;\n\n use clap::{App, AppSettings};\n\n\n\n #[test]\n\n fn stats_args() {\n\n let app = App::new(\"stats_args_test\")\n\n .setting(AppSettings::SubcommandRequiredElseHelp)\n\n .subcommand(cli::stats());\n\n\n\n let stats = app.clone().get_matches_from_safe(vec![\"\", CMD_STATS]);\n", "file_path": "util/app-config/src/lib.rs", "rank": 32, "score": 231364.45881078416 }, { "content": "pub fn always_success_cell() -> &'static (CellOutput, Bytes, Script) {\n\n &SUCCESS_CELL\n\n}\n\n\n", "file_path": "util/test-chain-utils/src/chain.rs", "rank": 33, "score": 228230.80557528505 }, { "content": "fn gen_multi_sign_script(keys: &[Privkey], threshold: u8, require_first_n: u8) -> Bytes {\n\n let pubkeys = keys\n\n .iter()\n\n .map(|key| key.pubkey().unwrap())\n\n .collect::<Vec<_>>();\n\n let mut script = vec![0u8, require_first_n, threshold, pubkeys.len() as u8];\n\n pubkeys.iter().for_each(|pubkey| {\n\n script.extend_from_slice(&blake160(&pubkey.serialize()).as_bytes());\n\n });\n\n script.into()\n\n}\n\n\n", "file_path": "test/src/specs/tx_pool/send_multisig_secp_tx.rs", "rank": 34, "score": 227199.6467688642 }, { "content": "/// Gather all cell dep out points and resolved dep group out points\n\npub fn get_related_dep_out_points<F: Fn(&OutPoint) -> Option<Bytes>>(\n\n tx: &TransactionView,\n\n get_cell_data: F,\n\n) -> Result<Vec<OutPoint>, String> {\n\n tx.cell_deps_iter().try_fold(\n\n Vec::with_capacity(tx.cell_deps().len()),\n\n |mut out_points, dep| {\n\n let out_point = dep.out_point();\n\n if dep.dep_type() == DepType::DepGroup.into() {\n\n let data = get_cell_data(&out_point)\n\n .ok_or_else(|| String::from(\"Can not get cell data\"))?;\n\n let sub_out_points =\n\n parse_dep_group_data(&data).map_err(|err| format!(\"Invalid data: {}\", err))?;\n\n out_points.extend(sub_out_points.into_iter());\n\n }\n\n out_points.push(out_point);\n\n Ok(out_points)\n\n },\n\n )\n\n}\n\n\n", "file_path": "util/types/src/core/cell.rs", "rank": 35, "score": 222577.2407762305 }, { "content": "pub fn build_genesis_type_id_script(output_index: u64) -> packed::Script {\n\n build_type_id_script(&packed::CellInput::new_cellbase_input(0), output_index)\n\n}\n\n\n", "file_path": "spec/src/lib.rs", "rank": 36, "score": 221988.1085894048 }, { "content": "pub fn load_input_data_hash_cell() -> &'static (CellOutput, Bytes, Script) {\n\n &LOAD_INPUT_DATA_HASH\n\n}\n\n\n", "file_path": "util/test-chain-utils/src/chain.rs", "rank": 37, "score": 220881.21726938846 }, { "content": "pub fn store_u64<Mac: SupportMachine>(machine: &mut Mac, v: u64) -> Result<u64, VMError> {\n\n let mut buffer = [0u8; std::mem::size_of::<u64>()];\n\n LittleEndian::write_u64(&mut buffer, v);\n\n store_data(machine, &buffer)\n\n}\n", "file_path": "script/src/syscalls/utils.rs", "rank": 38, "score": 220809.327058684 }, { "content": "fn should_receive_get_blocks_message(net: &Net, last_block_hash: Byte32) {\n\n net.should_receive(\n\n |data: &Bytes| {\n\n SyncMessage::from_slice(&data)\n\n .map(|message| match message.to_enum() {\n\n packed::SyncMessageUnion::GetBlocks(get_blocks) => {\n\n let block_hashes = get_blocks.block_hashes();\n\n block_hashes.get(block_hashes.len() - 1).unwrap() == last_block_hash\n\n }\n\n _ => false,\n\n })\n\n .unwrap_or(false)\n\n },\n\n \"Test node should receive GetBlocks message from node0\",\n\n );\n\n}\n", "file_path": "test/src/specs/sync/block_sync.rs", "rank": 39, "score": 220058.51668787005 }, { "content": "// Check the proposed-rewards and committed-rewards is correct\n\npub fn assert_chain_rewards(node: &Node) {\n\n let mut fee_collector = FeeCollector::build(node);\n\n let finalization_delay_length = node.consensus().finalization_delay_length();\n\n let tip_number = node.get_tip_block_number();\n\n assert!(tip_number > finalization_delay_length);\n\n\n\n for block_number in finalization_delay_length + 1..=tip_number {\n\n let block_hash = node.rpc_client().get_block_hash(block_number).unwrap();\n\n let early_number = block_number - finalization_delay_length;\n\n let early_block = node.get_block_by_number(early_number);\n\n let target_hash = early_block.hash();\n\n let txs_fee: u64 = early_block\n\n .transactions()\n\n .iter()\n\n .map(|tx| fee_collector.peek(tx.hash()))\n\n .sum();\n\n let proposed_fee: u64 = early_block\n\n .union_proposal_ids_iter()\n\n .map(|pid| {\n\n let fee = fee_collector.remove(pid);\n", "file_path": "test/src/assertion/reward_assertion.rs", "rank": 40, "score": 219947.1053135515 }, { "content": "pub fn build_type_id_script(input: &packed::CellInput, output_index: u64) -> packed::Script {\n\n let mut blake2b = new_blake2b();\n\n blake2b.update(&input.as_slice());\n\n blake2b.update(&output_index.to_le_bytes());\n\n let mut ret = [0; 32];\n\n blake2b.finalize(&mut ret);\n\n let script_arg = Bytes::from(ret.to_vec());\n\n packed::Script::new_builder()\n\n .code_hash(TYPE_ID_CODE_HASH.pack())\n\n .hash_type(ScriptHashType::Type.into())\n\n .args(script_arg.pack())\n\n .build()\n\n}\n\n\n", "file_path": "spec/src/lib.rs", "rank": 41, "score": 218711.9017044293 }, { "content": "fn sync_get_blocks(net: &Net, peer_id: PeerIndex, hashes: &[Byte32]) {\n\n net.send(\n\n SupportProtocols::Sync.protocol_id(),\n\n peer_id,\n\n build_get_blocks(hashes),\n\n );\n\n}\n\n\n", "file_path": "test/src/specs/sync/block_sync.rs", "rank": 42, "score": 218044.25796993216 }, { "content": "pub fn store_data<Mac: SupportMachine>(machine: &mut Mac, data: &[u8]) -> Result<u64, VMError> {\n\n let addr = machine.registers()[A0].to_u64();\n\n let size_addr = machine.registers()[A1].clone();\n\n let data_len = data.len() as u64;\n\n let offset = cmp::min(data_len, machine.registers()[A2].to_u64());\n\n\n\n let size = machine.memory_mut().load64(&size_addr)?.to_u64();\n\n let full_size = data_len - offset;\n\n let real_size = cmp::min(size, full_size);\n\n machine\n\n .memory_mut()\n\n .store64(&size_addr, &Mac::REG::from_u64(full_size))?;\n\n machine\n\n .memory_mut()\n\n .store_bytes(addr, &data[offset as usize..(offset + real_size) as usize])?;\n\n Ok(real_size)\n\n}\n\n\n", "file_path": "script/src/syscalls/utils.rs", "rank": 43, "score": 216791.13410748003 }, { "content": "pub fn new_blake2b() -> Blake2b {\n\n Blake2bBuilder::new(32)\n\n .personal(CKB_HASH_PERSONALIZATION)\n\n .build()\n\n}\n\n\n", "file_path": "util/hash/src/lib.rs", "rank": 44, "score": 213986.2986393748 }, { "content": "pub fn instruction_cycles(i: Instruction) -> u64 {\n\n match extract_opcode(i) {\n\n insts::OP_JALR => 3,\n\n insts::OP_LD => 2,\n\n insts::OP_LW => 3,\n\n insts::OP_LH => 3,\n\n insts::OP_LB => 3,\n\n insts::OP_LWU => 3,\n\n insts::OP_LHU => 3,\n\n insts::OP_LBU => 3,\n\n insts::OP_SB => 3,\n\n insts::OP_SH => 3,\n\n insts::OP_SW => 3,\n\n insts::OP_SD => 2,\n\n insts::OP_BEQ => 3,\n\n insts::OP_BGE => 3,\n\n insts::OP_BGEU => 3,\n\n insts::OP_BLT => 3,\n\n insts::OP_BLTU => 3,\n\n insts::OP_BNE => 3,\n", "file_path": "script/src/cost_model.rs", "rank": 45, "score": 210548.7167365387 }, { "content": "pub fn assert_send_transaction_fail(node: &Node, transaction: &TransactionView, message: &str) {\n\n let result = node\n\n .rpc_client()\n\n .send_transaction_result(transaction.data().into());\n\n assert!(\n\n result.is_err(),\n\n \"expect error \\\"{}\\\" but got \\\"Ok(())\\\"\",\n\n message,\n\n );\n\n let error = result.expect_err(&format!(\"transaction is invalid since {}\", message));\n\n let error_string = error.to_string();\n\n assert!(\n\n error_string.contains(message),\n\n \"expect error \\\"{}\\\" but got \\\"{}\\\"\",\n\n message,\n\n error_string,\n\n );\n\n}\n\n\n", "file_path": "test/src/utils.rs", "rank": 46, "score": 207834.5563489987 }, { "content": "pub fn create_secp_tx() -> TransactionView {\n\n let (ref secp_data_cell, ref secp_data_cell_data) = secp_data_cell();\n\n let (ref secp_cell, ref secp_cell_data, ref script) = secp_cell();\n\n let outputs = vec![secp_data_cell.clone(), secp_cell.clone()];\n\n let outputs_data = vec![secp_data_cell_data.pack(), secp_cell_data.pack()];\n\n TransactionBuilder::default()\n\n .witness(script.clone().into_witness())\n\n .input(CellInput::new(OutPoint::null(), 0))\n\n .outputs(outputs)\n\n .outputs_data(outputs_data)\n\n .build()\n\n}\n\n\n", "file_path": "benches/benches/benchmarks/util.rs", "rank": 47, "score": 204887.33318321567 }, { "content": "pub fn extract_dao_data(dao: Byte32) -> Result<(u64, Capacity, Capacity, Capacity), Error> {\n\n let data = dao.raw_data();\n\n let c = Capacity::shannons(LittleEndian::read_u64(&data[0..8]));\n\n let ar = LittleEndian::read_u64(&data[8..16]);\n\n let s = Capacity::shannons(LittleEndian::read_u64(&data[16..24]));\n\n let u = Capacity::shannons(LittleEndian::read_u64(&data[24..32]));\n\n Ok((ar, c, s, u))\n\n}\n\n\n", "file_path": "util/dao/utils/src/lib.rs", "rank": 48, "score": 204168.7453930632 }, { "content": "pub fn create_always_success_tx() -> TransactionView {\n\n let (ref always_success_cell, ref always_success_cell_data, ref script) = always_success_cell();\n\n TransactionBuilder::default()\n\n .witness(script.clone().into_witness())\n\n .input(CellInput::new(OutPoint::null(), 0))\n\n .output(always_success_cell.clone())\n\n .output_data(always_success_cell_data.pack())\n\n .build()\n\n}\n\n\n", "file_path": "benches/benches/benchmarks/util.rs", "rank": 49, "score": 201061.7362312206 }, { "content": "pub fn build_relay_tx_hashes(hashes: &[Byte32]) -> Bytes {\n\n let content = RelayTransactionHashes::new_builder()\n\n .tx_hashes(hashes.iter().map(ToOwned::to_owned).pack())\n\n .build();\n\n\n\n RelayMessage::new_builder().set(content).build().as_bytes()\n\n}\n\n\n", "file_path": "test/src/utils.rs", "rank": 50, "score": 199795.11633225158 }, { "content": "fn wait_get_blocks_point(secs: u64, net: &Net) -> (Instant, bool) {\n\n let flag = wait_get_blocks(secs, net);\n\n (Instant::now(), flag)\n\n}\n", "file_path": "test/src/specs/sync/get_blocks.rs", "rank": 51, "score": 198844.21641031647 }, { "content": "fn resolve_transaction_dep<F: FnMut(&OutPoint, bool) -> Result<Option<CellMeta>, Error>>(\n\n cell_dep: &CellDep,\n\n cell_resolver: &mut F,\n\n resolved_cell_deps: &mut Vec<CellMeta>,\n\n resolved_dep_groups: &mut Vec<CellMeta>,\n\n) -> Result<(), Error> {\n\n if cell_dep.dep_type() == DepType::DepGroup.into() {\n\n if let Some((dep_group, cell_deps)) =\n\n resolve_dep_group(&cell_dep.out_point(), cell_resolver)?\n\n {\n\n resolved_dep_groups.push(dep_group);\n\n resolved_cell_deps.extend(cell_deps);\n\n }\n\n } else if let Some(cell_meta) = cell_resolver(&cell_dep.out_point(), true)? {\n\n resolved_cell_deps.push(cell_meta);\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "util/types/src/core/cell.rs", "rank": 52, "score": 196471.17487968883 }, { "content": "fn resolve_dep_group<F: FnMut(&OutPoint, bool) -> Result<Option<CellMeta>, Error>>(\n\n out_point: &OutPoint,\n\n mut cell_resolver: F,\n\n) -> Result<Option<(CellMeta, Vec<CellMeta>)>, Error> {\n\n let dep_group_cell = match cell_resolver(out_point, true)? {\n\n Some(cell_meta) => cell_meta,\n\n None => return Ok(None),\n\n };\n\n let data = dep_group_cell\n\n .mem_cell_data\n\n .clone()\n\n .expect(\"Load cell meta must with data\")\n\n .0;\n\n\n\n let sub_out_points = parse_dep_group_data(&data)\n\n .map_err(|_| OutPointError::InvalidDepGroup(out_point.clone()))?;\n\n let mut resolved_deps = Vec::with_capacity(sub_out_points.len());\n\n for sub_out_point in sub_out_points.into_iter() {\n\n if let Some(sub_cell_meta) = cell_resolver(&sub_out_point, true)? {\n\n resolved_deps.push(sub_cell_meta);\n\n }\n\n }\n\n Ok(Some((dep_group_cell, resolved_deps)))\n\n}\n\n\n", "file_path": "util/types/src/core/cell.rs", "rank": 53, "score": 196471.17487968883 }, { "content": "// Build compact block based on core block, and specific prefilled indices\n\npub fn build_compact_block_with_prefilled(block: &BlockView, prefilled: Vec<usize>) -> Bytes {\n\n let prefilled = prefilled.into_iter().collect();\n\n let compact_block = CompactBlock::build_from_block(block, &prefilled);\n\n\n\n RelayMessage::new_builder()\n\n .set(compact_block)\n\n .build()\n\n .as_bytes()\n\n}\n\n\n", "file_path": "test/src/utils.rs", "rank": 54, "score": 195158.1908876423 }, { "content": "struct ProcessGuard(pub Child);\n\n\n\nimpl Drop for ProcessGuard {\n\n fn drop(&mut self) {\n\n match self.0.kill() {\n\n Err(e) => log::error!(\"Could not kill ckb process: {}\", e),\n\n Ok(_) => log::debug!(\"Successfully killed ckb process\"),\n\n }\n\n let _ = self.0.wait();\n\n }\n\n}\n\n\n\nimpl Node {\n\n pub fn new(\n\n binary: &str,\n\n p2p_port: u16,\n\n rpc_port: u16,\n\n case_name: &str,\n\n node_index: &str,\n\n ) -> Self {\n", "file_path": "test/src/node.rs", "rank": 55, "score": 193579.58996399608 }, { "content": "type ResolveResult = Result<(ResolvedTransaction, usize, Capacity, TxStatus), Error>;\n\n\n", "file_path": "tx-pool/src/process.rs", "rank": 56, "score": 192675.61890722613 }, { "content": "pub fn generate_blocks(\n\n shared: &Shared,\n\n chain_controller: &ChainController,\n\n target_tip: BlockNumber,\n\n) {\n\n let snapshot = shared.snapshot();\n\n let parent_number = snapshot.tip_number();\n\n let mut parent_hash = snapshot.tip_header().hash();\n\n for _ in parent_number..target_tip {\n\n let block = inherit_block(shared, &parent_hash).build();\n\n parent_hash = block.header().hash();\n\n chain_controller\n\n .internal_process_block(Arc::new(block), Switch::DISABLE_ALL)\n\n .expect(\"processing block should be ok\");\n\n }\n\n}\n\n\n", "file_path": "sync/src/tests/util.rs", "rank": 57, "score": 192198.19984813363 }, { "content": "pub fn build_block(block: &BlockView) -> Bytes {\n\n SyncMessage::new_builder()\n\n .set(SendBlock::new_builder().block(block.data()).build())\n\n .build()\n\n .as_bytes()\n\n}\n\n\n", "file_path": "test/src/utils.rs", "rank": 58, "score": 191781.9865532896 }, { "content": "pub fn new_secp_chain(txs_size: usize, chains_num: usize) -> Chains {\n\n let (_, _, secp_script) = secp_cell();\n\n let tx = create_secp_tx();\n\n let dao = genesis_dao_data(vec![&tx]).unwrap();\n\n\n\n // create genesis block with N txs\n\n let transactions: Vec<TransactionView> = (0..txs_size)\n\n .map(|i| {\n\n let data = Bytes::from(i.to_le_bytes().to_vec());\n\n let output = CellOutput::new_builder()\n\n .capacity(capacity_bytes!(50_000).pack())\n\n .lock(secp_script.clone())\n\n .build();\n\n TransactionBuilder::default()\n\n .input(CellInput::new(OutPoint::null(), 0))\n\n .output(output.clone())\n\n .output(output)\n\n .output_data(data.pack())\n\n .output_data(data.pack())\n\n .build()\n", "file_path": "benches/benches/benchmarks/util.rs", "rank": 59, "score": 191120.56890041684 }, { "content": "pub fn calculate_block_reward(epoch_reward: Capacity, epoch_length: BlockNumber) -> Capacity {\n\n let epoch_reward = epoch_reward.as_u64();\n\n Capacity::shannons({\n\n if epoch_reward % epoch_length != 0 {\n\n epoch_reward / epoch_length + 1\n\n } else {\n\n epoch_reward / epoch_length\n\n }\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\npub mod test {\n\n use super::*;\n\n use serde::{Deserialize, Serialize};\n\n use std::collections::HashMap;\n\n\n\n #[derive(Clone, Debug, Serialize, Deserialize)]\n\n struct SystemCell {\n\n pub path: String,\n", "file_path": "spec/src/lib.rs", "rank": 60, "score": 190714.75398387937 }, { "content": "/// Compress data\n\npub fn compress(src: Bytes) -> Bytes {\n\n Message::from_raw(src).compress()\n\n}\n\n\n", "file_path": "network/src/compress.rs", "rank": 61, "score": 188288.68348289927 }, { "content": "/// return special occupied capacity if cell is satoshi's gift\n\n/// otherwise return cell occupied capacity\n\npub fn modified_occupied_capacity(\n\n cell_meta: &CellMeta,\n\n consensus: &Consensus,\n\n) -> CapacityResult<Capacity> {\n\n if let Some(tx_info) = &cell_meta.transaction_info {\n\n if tx_info.is_genesis()\n\n && tx_info.is_cellbase()\n\n && cell_meta.cell_output.lock().args().raw_data() == consensus.satoshi_pubkey_hash.0[..]\n\n {\n\n return Unpack::<Capacity>::unpack(&cell_meta.cell_output.capacity())\n\n .safe_mul_ratio(consensus.satoshi_cell_occupied_ratio);\n\n }\n\n }\n\n cell_meta.occupied_capacity()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use ckb_db::RocksDB;\n", "file_path": "util/dao/src/lib.rs", "rank": 62, "score": 188106.2282274937 }, { "content": "// Build compact block based on core block\n\npub fn build_compact_block(block: &BlockView) -> Bytes {\n\n build_compact_block_with_prefilled(block, Vec::new())\n\n}\n\n\n", "file_path": "test/src/utils.rs", "rank": 63, "score": 187951.6922892995 }, { "content": "pub fn build_block_transactions(block: &BlockView) -> Bytes {\n\n // compact block has always prefilled cellbase\n\n let block_txs = BlockTransactions::new_builder()\n\n .block_hash(block.header().hash())\n\n .transactions(\n\n block\n\n .transactions()\n\n .into_iter()\n\n .map(|view| view.data())\n\n .skip(1)\n\n .pack(),\n\n )\n\n .build();\n\n\n\n RelayMessage::new_builder()\n\n .set(block_txs)\n\n .build()\n\n .as_bytes()\n\n}\n\n\n", "file_path": "test/src/utils.rs", "rank": 64, "score": 187945.8214267085 }, { "content": "pub fn build_genesis_epoch_ext(\n\n epoch_reward: Capacity,\n\n compact_target: u32,\n\n genesis_epoch_length: BlockNumber,\n\n epoch_duration_target: u64,\n\n) -> EpochExt {\n\n let block_reward = Capacity::shannons(epoch_reward.as_u64() / genesis_epoch_length);\n\n let remainder_reward = Capacity::shannons(epoch_reward.as_u64() % genesis_epoch_length);\n\n\n\n let genesis_orphan_count = genesis_epoch_length / 40;\n\n let genesis_hash_rate = compact_to_difficulty(compact_target)\n\n * (genesis_epoch_length + genesis_orphan_count)\n\n / epoch_duration_target;\n\n\n\n EpochExt::new_builder()\n\n .number(0)\n\n .base_block_reward(block_reward)\n\n .remainder_reward(remainder_reward)\n\n .previous_epoch_hash_rate(genesis_hash_rate)\n\n .last_block_hash_in_previous_epoch(Byte32::zero())\n\n .start_number(0)\n\n .length(genesis_epoch_length)\n\n .compact_target(compact_target)\n\n .build()\n\n}\n\n\n", "file_path": "spec/src/consensus.rs", "rank": 65, "score": 187623.7756412332 }, { "content": "pub fn build_genesis_dao_data(\n\n txs: Vec<&TransactionView>,\n\n satoshi_pubkey_hash: &H160,\n\n satoshi_cell_occupied_ratio: Ratio,\n\n genesis_primary_issuance: Capacity,\n\n genesis_secondary_issuance: Capacity,\n\n) -> Byte32 {\n\n genesis_dao_data_with_satoshi_gift(\n\n txs,\n\n satoshi_pubkey_hash,\n\n satoshi_cell_occupied_ratio,\n\n genesis_primary_issuance,\n\n genesis_secondary_issuance,\n\n )\n\n .expect(\"genesis dao data calculation error!\")\n\n}\n\n\n\nimpl ConsensusBuilder {\n\n pub fn new(genesis_block: BlockView, genesis_epoch_ext: EpochExt) -> Self {\n\n ConsensusBuilder {\n", "file_path": "spec/src/consensus.rs", "rank": 66, "score": 187623.7756412332 }, { "content": "pub fn new_always_success_chain(txs_size: usize, chains_num: usize) -> Chains {\n\n let (_, _, always_success_script) = always_success_cell();\n\n let tx = create_always_success_tx();\n\n let dao = genesis_dao_data(vec![&tx]).unwrap();\n\n\n\n // create genesis block with N txs\n\n let transactions: Vec<TransactionView> = (0..txs_size)\n\n .map(|i| {\n\n let data = Bytes::from(i.to_le_bytes().to_vec());\n\n TransactionBuilder::default()\n\n .input(CellInput::new(OutPoint::null(), 0))\n\n .output(\n\n CellOutput::new_builder()\n\n .capacity(capacity_bytes!(50_000).pack())\n\n .lock(always_success_script.clone())\n\n .build(),\n\n )\n\n .output_data(data.pack())\n\n .build()\n\n })\n", "file_path": "benches/benches/benchmarks/util.rs", "rank": 67, "score": 187305.8478352857 }, { "content": "fn wait_get_relay_txs(net: &Net) -> bool {\n\n wait_until(10, || {\n\n if let Ok((_, _, data)) = net.receive_timeout(Duration::from_secs(10)) {\n\n if let Ok(message) = RelayMessage::from_slice(&data) {\n\n return message.to_enum().item_name() == GetRelayTransactions::NAME;\n\n }\n\n }\n\n false\n\n })\n\n}\n\n\n\npub struct TransactionRelayEmptyPeers;\n\n\n\nimpl Spec for TransactionRelayEmptyPeers {\n\n crate::name!(\"transaction_relay_empty_peers\");\n\n\n\n crate::setup!(num_nodes: 2);\n\n\n\n fn run(&self, net: &mut Net) {\n\n net.exit_ibd_mode();\n", "file_path": "test/src/specs/relay/transaction_relay.rs", "rank": 68, "score": 185799.4015450934 }, { "content": "fn commit_window(node: &Node, proposed_number: BlockNumber) -> (BlockNumber, BlockNumber) {\n\n let proposal_window = node.consensus().tx_proposal_window();\n\n (\n\n proposed_number + proposal_window.closest(),\n\n proposed_number + proposal_window.farthest(),\n\n )\n\n}\n", "file_path": "test/src/specs/tx_pool/proposal_expire_rule.rs", "rank": 69, "score": 185480.54781516665 }, { "content": "fn wait_connect_state(node: &Node, expect_num: usize) {\n\n if !wait_until(10, || node.session_num() == expect_num) {\n\n panic!(\n\n \"node session number is {}, not {}\",\n\n node.session_num(),\n\n expect_num\n\n )\n\n }\n\n}\n\n\n", "file_path": "network/src/protocols/test.rs", "rank": 70, "score": 185411.7090625842 }, { "content": "pub fn secp_data_cell() -> &'static (CellOutput, Bytes) {\n\n &SECP_DATA_CELL\n\n}\n\n\n", "file_path": "benches/benches/benchmarks/util.rs", "rank": 71, "score": 184460.09778184246 }, { "content": "pub fn new_block_with_template(template: BlockTemplate) -> BlockView {\n\n Block::from(template)\n\n .as_advanced_builder()\n\n .nonce(rand::random::<u128>().pack())\n\n .build()\n\n}\n\n\n", "file_path": "test/src/utils.rs", "rank": 72, "score": 184372.27412481533 }, { "content": "#[test]\n\npub fn test_capacity_invalid() {\n\n // The outputs capacity is 50 + 100 = 150\n\n let transaction = TransactionBuilder::default()\n\n .outputs(vec![\n\n CellOutput::new_builder()\n\n .capacity(capacity_bytes!(50).pack())\n\n .build(),\n\n CellOutput::new_builder()\n\n .capacity(capacity_bytes!(100).pack())\n\n .build(),\n\n ])\n\n .outputs_data(vec![Bytes::new().pack(); 2])\n\n .build();\n\n\n\n // The inputs capacity is 49 + 100 = 149,\n\n // is less than outputs capacity\n\n let rtx = ResolvedTransaction {\n\n transaction,\n\n resolved_cell_deps: Vec::new(),\n\n resolved_inputs: vec![\n", "file_path": "verification/src/tests/transaction_verifier.rs", "rank": 73, "score": 183706.30440539683 }, { "content": "#[test]\n\npub fn test_capacity_outofbound() {\n\n let data = Bytes::from(vec![1; 51]);\n\n let transaction = TransactionBuilder::default()\n\n .output(\n\n CellOutput::new_builder()\n\n .capacity(capacity_bytes!(50).pack())\n\n .build(),\n\n )\n\n .output_data(data.pack())\n\n .build();\n\n\n\n let rtx = ResolvedTransaction {\n\n transaction,\n\n resolved_cell_deps: Vec::new(),\n\n resolved_inputs: vec![CellMetaBuilder::from_cell_output(\n\n CellOutput::new_builder()\n\n .capacity(capacity_bytes!(50).pack())\n\n .build(),\n\n Bytes::new(),\n\n )\n", "file_path": "verification/src/tests/transaction_verifier.rs", "rank": 74, "score": 183706.30440539683 }, { "content": "#[test]\n\npub fn test_chain_specs() {\n\n use ckb_chain_spec::ChainSpec;\n\n use ckb_resource::{Resource, AVAILABLE_SPECS};\n\n fn load_spec_by_name(name: &str) -> ChainSpec {\n\n let res = Resource::bundled(format!(\"specs/{}.toml\", name));\n\n ChainSpec::load_from(&res).expect(\"load spec by name\")\n\n }\n\n for name in AVAILABLE_SPECS {\n\n let spec = load_spec_by_name(name);\n\n let consensus = spec.build_consensus().expect(\"build consensus\");\n\n let verifier = GenesisVerifier::new();\n\n verifier.verify(&consensus).expect(\"pass verification\");\n\n }\n\n}\n", "file_path": "verification/src/tests/genesis_verifier.rs", "rank": 75, "score": 183246.8448751652 }, { "content": "pub fn check_if_identifier_is_valid(ident: &str) -> Result<(), String> {\n\n const IDENT_PATTERN: &str = r#\"^[0-9a-zA-Z_-]+$\"#;\n\n if ident.is_empty() {\n\n return Err(\"the identifier shouldn't be empty\".to_owned());\n\n }\n\n match Regex::new(IDENT_PATTERN) {\n\n Ok(re) => {\n\n if !re.is_match(&ident) {\n\n return Err(format!(\n\n \"invaild identifier \\\"{}\\\", the identifier pattern is \\\"{}\\\"\",\n\n ident, IDENT_PATTERN\n\n ));\n\n }\n\n }\n\n Err(err) => {\n\n return Err(format!(\n\n \"invalid regular expression \\\"{}\\\": {}\",\n\n IDENT_PATTERN, err\n\n ));\n\n }\n\n }\n\n Ok(())\n\n}\n", "file_path": "util/src/strings.rs", "rank": 76, "score": 182517.40725751937 }, { "content": "pub fn attach_block_cell(txn: &StoreTransaction, block: &BlockView) -> Result<(), Error> {\n\n for tx in block.transactions() {\n\n for cell in tx.input_pts_iter() {\n\n let cell_tx_hash = cell.tx_hash();\n\n if let Some(mut meta) = txn.get_tx_meta(&cell_tx_hash) {\n\n meta.set_dead(cell.index().unpack());\n\n if meta.all_dead() {\n\n txn.delete_cell_set(&cell_tx_hash)?;\n\n } else {\n\n txn.update_cell_set(&cell_tx_hash, &meta.pack())?;\n\n }\n\n }\n\n }\n\n let tx_hash = tx.hash();\n\n let outputs_len = tx.outputs().len();\n\n let meta = if tx.is_cellbase() {\n\n TransactionMeta::new_cellbase(\n\n block.number(),\n\n block.epoch().number(),\n\n block.hash(),\n", "file_path": "chain/src/cell.rs", "rank": 77, "score": 182213.51762197207 }, { "content": "pub fn detach_block_cell(txn: &StoreTransaction, block: &BlockView) -> Result<(), Error> {\n\n for tx in block.transactions().iter().rev() {\n\n txn.delete_cell_set(&tx.hash())?;\n\n\n\n for cell in tx.input_pts_iter() {\n\n let cell_tx_hash = cell.tx_hash();\n\n let index: usize = cell.index().unpack();\n\n\n\n if let Some(mut tx_meta) = txn.get_tx_meta(&cell_tx_hash) {\n\n tx_meta.unset_dead(index);\n\n txn.update_cell_set(&cell_tx_hash, &tx_meta.pack())?;\n\n } else {\n\n // the tx is full dead, deleted from cellset, we need recover it when fork\n\n if let Some((tx, header)) =\n\n txn.get_transaction(&cell_tx_hash)\n\n .and_then(|(tx, block_hash)| {\n\n txn.get_block_header(&block_hash).map(|header| (tx, header))\n\n })\n\n {\n\n let mut meta = if tx.is_cellbase() {\n", "file_path": "chain/src/cell.rs", "rank": 78, "score": 182213.51762197207 }, { "content": "#[proc_macro]\n\npub fn capacity_bytes(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n\n let input = parse_macro_input!(input as syn::LitInt);\n\n let expanded = if let Ok(oc) = Capacity::bytes(input.value() as usize) {\n\n let shannons = syn::LitInt::new(oc.as_u64(), syn::IntSuffix::None, input.span());\n\n quote!(Capacity::shannons(#shannons))\n\n } else {\n\n panic!(\"Occupied capacity is overflow.\");\n\n };\n\n expanded.into()\n\n}\n", "file_path": "util/occupied-capacity/macros/src/lib.rs", "rank": 79, "score": 180202.92780544065 }, { "content": "// grep \"panicked at\" $node_log_path\n\npub fn nodes_panicked(node_dirs: &[String]) -> bool {\n\n node_dirs.iter().any(|node_dir| {\n\n read_to_string(&node_log(&node_dir))\n\n .expect(\"failed to read node's log\")\n\n .contains(\"panicked at\")\n\n })\n\n}\n\n\n", "file_path": "test/src/utils.rs", "rank": 80, "score": 180019.1051033961 }, { "content": "// NOTICE Used for testing only\n\npub fn genesis_dao_data(txs: Vec<&TransactionView>) -> Result<Byte32, Error> {\n\n genesis_dao_data_with_satoshi_gift(\n\n txs,\n\n &H160([0u8; 20]),\n\n Ratio(1, 1),\n\n capacity_bytes!(1_000_000),\n\n capacity_bytes!(1000),\n\n )\n\n}\n\n\n", "file_path": "util/dao/utils/src/lib.rs", "rank": 81, "score": 179331.37419420274 }, { "content": "pub fn build_relay_txs(transactions: &[(TransactionView, u64)]) -> Bytes {\n\n let transactions = transactions.iter().map(|(tx, cycles)| {\n\n RelayTransaction::new_builder()\n\n .cycles(cycles.pack())\n\n .transaction(tx.data())\n\n .build()\n\n });\n\n let txs = RelayTransactions::new_builder()\n\n .transactions(transactions.pack())\n\n .build();\n\n\n\n RelayMessage::new_builder().set(txs).build().as_bytes()\n\n}\n\n\n", "file_path": "test/src/utils.rs", "rank": 82, "score": 179000.7017078683 }, { "content": "pub fn run_app(version: Version) -> Result<(), ExitCode> {\n\n // Always print backtrace on panic.\n\n ::std::env::set_var(\"RUST_BACKTRACE\", \"full\");\n\n\n\n let app_matches = cli::get_matches(&version);\n\n match app_matches.subcommand() {\n\n (cli::CMD_INIT, Some(matches)) => {\n\n return subcommand::init(Setup::init(&matches)?);\n\n }\n\n (cli::CMD_LIST_HASHES, Some(matches)) => {\n\n return subcommand::list_hashes(Setup::root_dir_from_matches(&matches)?, matches);\n\n }\n\n (cli::CMD_PEERID, Some(matches)) => match matches.subcommand() {\n\n (cli::CMD_GEN_SECRET, Some(matches)) => return Setup::gen(&matches),\n\n (cli::CMD_FROM_SECRET, Some(matches)) => {\n\n return subcommand::peer_id(Setup::peer_id(&matches)?);\n\n }\n\n _ => {}\n\n },\n\n _ => {\n", "file_path": "ckb-bin/src/lib.rs", "rank": 83, "score": 178920.97790233017 }, { "content": "// node_log=$node_dir/data/logs/run.log\n\npub fn node_log(node_dir: &str) -> PathBuf {\n\n PathBuf::from(node_dir)\n\n .join(\"data\")\n\n .join(\"logs\")\n\n .join(\"run.log\")\n\n}\n\n\n", "file_path": "test/src/utils.rs", "rank": 94, "score": 176254.45234276963 }, { "content": "#[test]\n\npub fn test_skip_dao_capacity_check() {\n\n let dao_type_script = build_genesis_type_id_script(OUTPUT_INDEX_DAO);\n\n let transaction = TransactionBuilder::default()\n\n .output(\n\n CellOutput::new_builder()\n\n .capacity(capacity_bytes!(500).pack())\n\n .type_(Some(dao_type_script.clone()).pack())\n\n .build(),\n\n )\n\n .output_data(Bytes::new().pack())\n\n .build();\n\n\n\n let rtx = ResolvedTransaction {\n\n transaction,\n\n resolved_cell_deps: Vec::new(),\n\n resolved_inputs: vec![],\n\n resolved_dep_groups: vec![],\n\n };\n\n let verifier = CapacityVerifier::new(&rtx, Some(dao_type_script.calc_script_hash()));\n\n\n\n assert!(verifier.verify().is_ok());\n\n}\n\n\n\n// inputs immature verify\n", "file_path": "verification/src/tests/transaction_verifier.rs", "rank": 95, "score": 175768.8963430436 }, { "content": "#[test]\n\npub fn test_max_block_bytes_verifier() {\n\n let block = BlockBuilder::default()\n\n .header(HeaderBuilder::default().number(2u64.pack()).build())\n\n .build();\n\n\n\n {\n\n let verifier =\n\n BlockBytesVerifier::new(block.data().serialized_size_without_uncle_proposals() as u64);\n\n assert!(verifier.verify(&block).is_ok());\n\n }\n\n\n\n {\n\n let verifier = BlockBytesVerifier::new(\n\n block.data().serialized_size_without_uncle_proposals() as u64 - 1,\n\n );\n\n assert_error_eq!(\n\n verifier.verify(&block).unwrap_err(),\n\n BlockErrorKind::ExceededMaximumBlockBytes,\n\n );\n\n }\n\n}\n\n\n", "file_path": "verification/src/tests/block_verifier.rs", "rank": 96, "score": 175756.13982388188 }, { "content": "#[test]\n\npub fn test_exceeded_maximum_block_bytes() {\n\n let data: Bytes = vec![1; 500].into();\n\n let transaction = TransactionBuilder::default()\n\n .output(\n\n CellOutput::new_builder()\n\n .capacity(capacity_bytes!(50).pack())\n\n .build(),\n\n )\n\n .output_data(data.pack())\n\n .build();\n\n let verifier = SizeVerifier::new(&transaction, 100);\n\n\n\n assert_error_eq!(\n\n verifier.verify().unwrap_err(),\n\n TransactionError::ExceededMaximumBlockBytes {\n\n actual: 661,\n\n limit: 100\n\n },\n\n );\n\n}\n\n\n", "file_path": "verification/src/tests/transaction_verifier.rs", "rank": 97, "score": 175756.13982388188 }, { "content": "#[derive(Default)]\n\nstruct TestNode {\n\n pub peers: Vec<PeerIndex>,\n\n pub protocols: HashMap<ProtocolId, Arc<RwLock<dyn CKBProtocolHandler + Send + Sync>>>,\n\n pub msg_senders: HashMap<(ProtocolId, PeerIndex), SyncSender<Bytes>>,\n\n pub msg_receivers: HashMap<(ProtocolId, PeerIndex), Receiver<Bytes>>,\n\n pub timer_senders: HashMap<(ProtocolId, u64), SyncSender<()>>,\n\n pub timer_receivers: HashMap<(ProtocolId, u64), Receiver<()>>,\n\n}\n\n\n\nimpl TestNode {\n\n pub fn add_protocol(\n\n &mut self,\n\n protocol: ProtocolId,\n\n handler: &Arc<RwLock<dyn CKBProtocolHandler + Send + Sync>>,\n\n timers: &[u64],\n\n ) {\n\n self.protocols.insert(protocol, Arc::clone(handler));\n\n timers.iter().for_each(|timer| {\n\n let (timer_sender, timer_receiver) = sync_channel(DEFAULT_CHANNEL);\n\n self.timer_senders.insert((protocol, *timer), timer_sender);\n", "file_path": "sync/src/tests/mod.rs", "rank": 98, "score": 175710.8152703832 }, { "content": "pub fn jemalloc_profiling_dump(filename: &str) -> Result<(), String> {\n\n let mut filename0 = format!(\"{}\\0\", filename);\n\n let opt_name = \"prof.dump\";\n\n let opt_c_name = ffi::CString::new(opt_name).unwrap();\n\n info!(\"jemalloc profiling dump: {}\", filename);\n\n unsafe {\n\n jemalloc_sys::mallctl(\n\n opt_c_name.as_ptr(),\n\n ptr::null_mut(),\n\n ptr::null_mut(),\n\n &mut filename0 as *mut _ as *mut _,\n\n mem::size_of::<*mut ffi::c_void>(),\n\n );\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "util/memory-tracker/src/jemalloc.rs", "rank": 99, "score": 175542.25048681535 } ]
Rust
src/connectivity/bluetooth/core/bt-gap/src/host_device.rs
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
use { fidl::endpoints::ClientEnd, fidl_fuchsia_bluetooth::DeviceClass, fidl_fuchsia_bluetooth::PeerId as FidlPeerId, fidl_fuchsia_bluetooth_control::{ self as control, HostData, InputCapabilityType, OutputCapabilityType, PairingDelegateMarker, PairingOptions, }, fidl_fuchsia_bluetooth_gatt::ClientProxy, fidl_fuchsia_bluetooth_host::{HostEvent, HostProxy}, fidl_fuchsia_bluetooth_le::CentralProxy, fuchsia_bluetooth::{ inspect::Inspectable, types::{BondingData, HostInfo, Peer, PeerId}, }, fuchsia_syslog::{fx_log_err, fx_log_info}, futures::{future, Future, FutureExt, StreamExt}, parking_lot::RwLock, pin_utils::pin_mut, std::{collections::HashMap, convert::TryInto, path::PathBuf, str::FromStr, sync::Arc}, }; use crate::types::{self, from_fidl_status, Error}; pub struct HostDevice { pub path: PathBuf, host: HostProxy, info: Inspectable<HostInfo>, gatt: HashMap<String, (CentralProxy, ClientProxy)>, } impl HostDevice { pub fn new(path: PathBuf, host: HostProxy, info: Inspectable<HostInfo>) -> Self { HostDevice { path, host, info, gatt: HashMap::new() } } pub fn get_host(&self) -> &HostProxy { &self.host } pub fn set_host_pairing_delegate( &self, input: InputCapabilityType, output: OutputCapabilityType, delegate: ClientEnd<PairingDelegateMarker>, ) { let _ = self.host.set_pairing_delegate(input, output, Some(delegate)); } pub fn get_info(&self) -> &HostInfo { &self.info } pub fn rm_gatt(&mut self, id: String) -> impl Future<Output = types::Result<()>> { let gatt_entry = self.gatt.remove(&id); async move { if let Some((central, _)) = gatt_entry { from_fidl_status(central.disconnect_peripheral(id.as_str()).await) } else { Err(Error::not_found("Unknown Peripheral")) } } } pub fn set_name(&self, mut name: String) -> impl Future<Output = types::Result<()>> { self.host.set_local_name(&mut name).map(from_fidl_status) } pub fn set_device_class( &self, mut cod: DeviceClass, ) -> impl Future<Output = types::Result<()>> { self.host.set_device_class(&mut cod).map(from_fidl_status) } pub fn start_discovery(&mut self) -> impl Future<Output = types::Result<()>> { self.host.start_discovery().map(from_fidl_status) } pub fn connect(&mut self, device_id: String) -> impl Future<Output = types::Result<()>> { self.host.connect(&device_id).map(from_fidl_status) } pub fn disconnect(&mut self, device_id: String) -> impl Future<Output = types::Result<()>> { self.host.disconnect(&device_id).map(from_fidl_status) } pub fn pair( &mut self, mut id: FidlPeerId, options: PairingOptions, ) -> impl Future<Output = types::Result<()>> { self.host.pair(&mut id, options).map(from_fidl_status) } pub fn forget(&mut self, peer_id: String) -> impl Future<Output = types::Result<()>> { self.host.forget(&peer_id).map(from_fidl_status) } pub fn close(&self) -> types::Result<()> { self.host.close().map_err(|e| e.into()) } pub fn restore_bonds( &self, bonds: Vec<BondingData>, ) -> impl Future<Output = types::Result<()>> { let mut bonds: Vec<_> = bonds.into_iter().map(control::BondingData::from).collect(); self.host.add_bonded_devices(&mut bonds.iter_mut()).map(from_fidl_status) } pub fn set_connectable(&self, value: bool) -> impl Future<Output = types::Result<()>> { self.host.set_connectable(value).map(from_fidl_status) } pub fn stop_discovery(&self) -> impl Future<Output = types::Result<()>> { self.host.stop_discovery().map(from_fidl_status) } pub fn set_discoverable(&self, discoverable: bool) -> impl Future<Output = types::Result<()>> { self.host.set_discoverable(discoverable).map(from_fidl_status) } pub fn set_local_data(&self, mut data: HostData) -> types::Result<()> { self.host.set_local_data(&mut data)?; Ok(()) } pub fn enable_privacy(&self, enable: bool) -> types::Result<()> { self.host.enable_privacy(enable).map_err(Error::from) } pub fn enable_background_scan(&self, enable: bool) -> types::Result<()> { self.host.enable_background_scan(enable).map_err(Error::from) } } pub trait HostListener { fn on_peer_updated(&mut self, peer: Peer); fn on_peer_removed(&mut self, id: PeerId); type HostBondFut: Future<Output = Result<(), anyhow::Error>>; fn on_new_host_bond(&mut self, data: BondingData) -> Self::HostBondFut; } pub async fn refresh_host_info(host: Arc<RwLock<HostDevice>>) -> types::Result<()> { let proxy = host.read().host.clone(); let info = proxy.watch_state().await?; host.write().info.update(info.try_into()?); Ok(()) } pub async fn watch_events<H: HostListener>( listener: H, host: Arc<RwLock<HostDevice>>, ) -> types::Result<()> { let handle_fidl = handle_fidl_events(listener, host.clone()); let watch_state = watch_state(host); pin_mut!(handle_fidl); pin_mut!(watch_state); future::select(handle_fidl, watch_state).await.factor_first().0 } async fn handle_fidl_events<H: HostListener>( mut listener: H, host: Arc<RwLock<HostDevice>>, ) -> types::Result<()> { let mut stream = host.read().host.take_event_stream(); while let Some(event) = stream.next().await { match event? { HostEvent::OnDeviceUpdated { device } => listener.on_peer_updated(device.try_into()?), HostEvent::OnDeviceRemoved { identifier } => { listener.on_peer_removed(PeerId::from_str(&identifier)?) } HostEvent::OnNewBondingData { data } => { fx_log_info!("Received bonding data"); let data: BondingData = match data.try_into() { Err(e) => { fx_log_err!("Invalid bonding data, ignoring: {:#?}", e); continue; } Ok(data) => data, }; if let Err(e) = listener.on_new_host_bond(data.into()).await { fx_log_err!("Failed to persist bonding data: {:#?}", e); } } }; } Ok(()) } async fn watch_state(host: Arc<RwLock<HostDevice>>) -> types::Result<()> { loop { refresh_host_info(host.clone()).await?; } }
use { fidl::endpoints::ClientEnd, fidl_fuchsia_bluetooth::DeviceClass, fidl_fuchsia_bluetooth::PeerId as FidlPeerId, fidl_fuchsia_bluetooth_control::{ self as control, HostData, InputCapabilityType, OutputCapabilityType, PairingDelegateMarker, PairingOptions, }, fidl_fuchsia_bluetooth_gatt::ClientProxy, fidl_fuchsia_bluetooth_host::{HostEvent, HostProxy}, fidl_fuchsia_bluetooth_le::CentralProxy, fuchsia_bluetooth::{ inspect::Inspectable, types::{BondingData, HostInfo, Peer, PeerId}, }, fuchsia_syslog::{fx_log_err, fx_log_info}, futures::{future, Future, FutureExt, StreamExt}, parking_lot::RwLock, pin_utils::pin_mut, std::{collections::HashMap, convert::TryInto, path::PathBuf, str::FromStr, sync::Arc}, }; use crate::types::{self, from_fidl_status, Error}; pub struct HostDevice { pub path: PathBuf, host: HostProxy, info: Inspectable<HostInfo>, gatt: HashMap<String, (CentralProxy, ClientProxy)>, } impl HostDevice { pub fn new(path: PathBuf, host: HostProxy, info: Inspectable<HostInfo>) -> Self { HostDevice { path, host, info, gatt: HashMap::new() } } pub fn get_host(&self) -> &HostProxy { &self.host } pub fn set_host_pairing_delegate( &self, input: InputCapabilityType, output: OutputCapabilityType, delegate: ClientEnd<PairingDelegateMarker>, ) { let _ = self.host.set_pairing_delegate(input, output, Some(delegate)); } pub fn get_info(&self) -> &HostInfo { &self.info } pub fn rm_gatt(&mut self, id: String) -> impl Future<Output = types::Result<()>> { let gatt_entry = self.gatt.remove(&id); async move { if let Some((central, _)) = gatt_entry { from_fidl_status(central.disconnect_peripheral(id.as_str()).await) } else { Err(Error::not_found("Unknown Peripheral")) } } } pub fn set_name(&self, mut name: String) -> impl Future<Output = types::Result<()>> { self.host.set_local_name(&mut name).map(from_fidl_status) } pub fn set_device_class( &self, mut cod: DeviceClass, ) -> impl Future<Output = types::Result<()>> { self.host.set_device_class(&mut cod).map(from_fidl_status) } pub fn start_discovery(&mut self) -> impl Future<Output = types::Result<()>> { self.host.start_discovery().map(from_fidl_status) } pub fn connect(&mut self, device_id: String) -> impl Future<Output = types::Result<()>> { self.host.connect(&device_id).map(from_fidl_status) } pub fn disconnect(&mut self, device_id: String) -> impl Future<Output = types::Result<()>> { self.host.disconnect(&device_id).map(from_fidl_status) } pub fn pair( &mut self, mut id: FidlPeerId, options: PairingOptions, ) -> impl Future<Output = types::Result<()>> { self.host.pair(&mut id, options).map(from_fidl_status) } pub fn forget(&mut self, peer_id: String) -> impl Future<Output = types::Result<()>> { self.host.forget(&peer_id).map(from_fidl_status) } pub fn close(&self) -> types::Result<()> { self.host.close().map_err(|e| e.into()) } pub fn restore_bonds( &self, bonds: Vec<BondingData>, ) -> impl Future<Output = types::Result<()>> { let mut bonds: Vec<_> = bonds.into_iter().map(control::BondingData::from).collect(); self.host.add_bonded_devices(&mut bonds.iter_mut()).map(from_fidl_status) } pub fn set_connectable(&self, value: bool) -> impl Future<Output = types::Result<()>> { self.host.set_connectable(value).map(from_fidl_status) } pub fn stop_discovery(&self) -> impl Future<Output = types::Result<()>> { self.host.stop_discovery().map(from_fidl_status) } pub fn set_discoverable(&self, discoverable: bool) -> impl Future<Output = types::Result<()>> { self.host.set_discoverable(discoverable).map(from_fidl_status) } pub fn set_local_data(&self, mut data: HostData) -> types::Result<()> { self.host.set_local_data(&mut data)?; Ok(()) } pub fn enable_privacy(&self, enable: bool) -> types::Result<()> { self.host.enable_privacy(enable).map_err(Error::from) } pub fn enable_background_scan(&self, enable: bool) -> types::Result<()> { self.host.enable_background_scan(enable).map_err(Error::from) } } pub trait HostListener { fn on_peer_updated(&mut self, peer: Peer); fn on_peer_removed(&mut self, id: PeerId); type HostBondFut: Future<Output = Result<(), anyhow::Error>>; fn on_new_host_bond(&mut self, data: BondingData) -> Self::HostBondFut; } pub async fn refresh_host_info(host: Arc<RwLock<HostDevice>>) -> types::Result<()> { let proxy = host.read().host.clone(); let info = proxy.watch_state().await?; host.write().info.update(info.try_into()?); Ok(()) } pub async fn watch_events<H: HostListener>( listener: H, host: Arc<RwLock<HostDevice>>, ) -> types::Result<()> { let handle_fidl = handle_fidl_events(listener, host.clone()); let watch_state = watch_state(host); pin_mut!(handle_fidl); pin_mut!(watch_state); future::select(handle_fidl, watch_state).await.factor_first().0 } async fn handle_fidl_events<H: HostListener>( mut listener: H, host: Arc<RwLock<HostDevice>>, ) -> types::Result<()> { let mut stream = host.read().host.take_event_stream(); while let Some(event) = stream.next().await { match event? { HostEvent::OnDeviceUpdated { device } => listener.on_peer_updated(device.try_into()?), HostEvent::OnDeviceRemoved { identifier } => { listener.on_peer_removed(PeerId::from_str(&identifier)?) } HostEvent::OnNewBondingData { data } => { fx_log_info!("Received bonding data"); let data: BondingData =
; if let Err(e) = listener.on_new_host_bond(data.into()).await { fx_log_err!("Failed to persist bonding data: {:#?}", e); } } }; } Ok(()) } async fn watch_state(host: Arc<RwLock<HostDevice>>) -> types::Result<()> { loop { refresh_host_info(host.clone()).await?; } }
match data.try_into() { Err(e) => { fx_log_err!("Invalid bonding data, ignoring: {:#?}", e); continue; } Ok(data) => data, }
if_condition
[]
Rust
examples/bindless/main.rs
peterwmwong/metal-rs
1aaa9033a22b2af7ff8cae2ed412a4733799c3d3
use metal::*; use objc::rc::autoreleasepool; const BINDLESS_TEXTURE_COUNT: NSUInteger = 100_000; fn main() { autoreleasepool(|| { let device = Device::system_default().expect("no device found"); /* MSL struct Textures { texture2d<float> texture; }; struct BindlessTextures { device Textures *textures; }; */ let tier = device.argument_buffers_support(); println!("Argument buffer support: {:?}", tier); assert_eq!(MTLArgumentBuffersTier::Tier2, tier); let texture_descriptor = TextureDescriptor::new(); texture_descriptor.set_width(1); texture_descriptor.set_height(1); texture_descriptor.set_depth(1); texture_descriptor.set_texture_type(MTLTextureType::D2); texture_descriptor.set_pixel_format(MTLPixelFormat::R8Uint); texture_descriptor.set_storage_mode(MTLStorageMode::Private); println!("Texture descriptor: {:?}", texture_descriptor); let size_and_align = device.heap_texture_size_and_align(&texture_descriptor); let texture_size = (size_and_align.size & (size_and_align.align - 1)) + size_and_align.align; let heap_size = texture_size * BINDLESS_TEXTURE_COUNT; let heap_descriptor = HeapDescriptor::new(); heap_descriptor.set_storage_mode(texture_descriptor.storage_mode()); heap_descriptor.set_size(heap_size); println!("Heap descriptor: {:?}", heap_descriptor); let heap = device.new_heap(&heap_descriptor); println!("Heap: {:?}", heap); let textures = (0..BINDLESS_TEXTURE_COUNT) .map(|i| { heap.new_texture(&texture_descriptor) .expect(&format!("Failed to allocate texture {}", i)) }) .collect::<Vec<_>>(); let descriptor = ArgumentDescriptor::new(); descriptor.set_index(0); descriptor.set_data_type(MTLDataType::Texture); descriptor.set_texture_type(MTLTextureType::D2); descriptor.set_access(MTLArgumentAccess::ReadOnly); println!("Argument descriptor: {:?}", descriptor); let encoder = device.new_argument_encoder(Array::from_slice(&[descriptor])); println!("Encoder: {:?}", encoder); let argument_buffer_size = encoder.encoded_length() * BINDLESS_TEXTURE_COUNT; let argument_buffer = device.new_buffer(argument_buffer_size, MTLResourceOptions::empty()); textures.iter().enumerate().for_each(|(index, texture)| { let offset = index as NSUInteger * encoder.encoded_length(); encoder.set_argument_buffer(&argument_buffer, offset); encoder.set_texture(0, texture); }); let queue = device.new_command_queue(); let command_buffer = queue.new_command_buffer(); let render_pass_descriptor = RenderPassDescriptor::new(); let encoder = command_buffer.new_render_command_encoder(render_pass_descriptor); encoder.set_fragment_buffer(0, Some(&argument_buffer), 0); encoder.use_heap_at(&heap, MTLRenderStages::Fragment); /* // Now instead of binding individual textures each draw call, // you can just bind material information instead: MSL struct Material { int diffuse_texture_index; int normal_texture_index; // ... } fragment float4 pixel( VertexOut v [[stage_in]], constant const BindlessTextures * textures [[buffer(0)]], constant Material * material [[buffer(1)]] ) { if (material->base_color_texture_index != -1) { textures[material->diffuse_texture_index].texture.sampler(...) } if (material->normal_texture_index != -1) { ... } ... } */ encoder.end_encoding(); command_buffer.commit(); }); }
use metal::*; use objc::rc::autoreleasepool; const BINDLESS_TEXTURE_COUNT: NSUInteger = 100_000;
fn main() { autoreleasepool(|| { let device = Device::system_default().expect("no device found"); /* MSL struct Textures { texture2d<float> texture; }; struct BindlessTextures { device Textures *textures; }; */ let tier = device.argument_buffers_support(); println!("Argument buffer support: {:?}", tier); assert_eq!(MTLArgumentBuffersTier::Tier2, tier); let texture_descriptor = TextureDescriptor::new(); texture_descriptor.set_width(1); texture_descriptor.set_height(1); texture_descriptor.set_depth(1); texture_descriptor.set_texture_type(MTLTextureType::D2); texture_descriptor.set_pixel_format(MTLPixelFormat::R8Uint); texture_descriptor.set_storage_mode(MTLStorageMode::Private); println!("Texture descriptor: {:?}", texture_descriptor); let size_and_align = device.heap_texture_size_and_align(&texture_descriptor); let texture_size = (size_and_align.size & (size_and_align.align - 1)) + size_and_align.align; let heap_size = texture_size * BINDLESS_TEXTURE_COUNT; let heap_descriptor = HeapDescriptor::new(); heap_descriptor.set_storage_mode(texture_descriptor.storage_mode()); heap_descriptor.set_size(heap_size); println!("Heap descriptor: {:?}", heap_descriptor); let heap = device.new_heap(&heap_descriptor); println!("Heap: {:?}", heap); let textures = (0..BINDLESS_TEXTURE_COUNT) .map(|i| { heap.new_texture(&texture_descriptor) .expect(&format!("Failed to allocate texture {}", i)) }) .collect::<Vec<_>>(); let descriptor = ArgumentDescriptor::new(); descriptor.set_index(0); descriptor.set_data_type(MTLDataType::Texture); descriptor.set_texture_type(MTLTextureType::D2); descriptor.set_access(MTLArgumentAccess::ReadOnly); println!("Argument descriptor: {:?}", descriptor); let encoder = device.new_argument_encoder(Array::from_slice(&[descriptor])); println!("Encoder: {:?}", encoder); let argument_buffer_size = encoder.encoded_length() * BINDLESS_TEXTURE_COUNT; let argument_buffer = device.new_buffer(argument_buffer_size, MTLResourceOptions::empty()); textures.iter().enumerate().for_each(|(index, texture)| { let offset = index as NSUInteger * encoder.encoded_length(); encoder.set_argument_buffer(&argument_buffer, offset); encoder.set_texture(0, texture); }); let queue = device.new_command_queue(); let command_buffer = queue.new_command_buffer(); let render_pass_descriptor = RenderPassDescriptor::new(); let encoder = command_buffer.new_render_command_encoder(render_pass_descriptor); encoder.set_fragment_buffer(0, Some(&argument_buffer), 0); encoder.use_heap_at(&heap, MTLRenderStages::Fragment); /* // Now instead of binding individual textures each draw call, // you can just bind material information instead: MSL struct Material { int diffuse_texture_index; int normal_texture_index; // ... } fragment float4 pixel( VertexOut v [[stage_in]], constant const BindlessTextures * textures [[buffer(0)]], constant Material * material [[buffer(1)]] ) { if (material->base_color_texture_index != -1) { textures[material->diffuse_texture_index].texture.sampler(...) } if (material->normal_texture_index != -1) { ... } ... } */ encoder.end_encoding(); command_buffer.commit(); }); }
function_block-full_function
[ { "content": "#[allow(non_camel_case_types)]\n\ntype dispatch_block_t = *const Block<(), ()>;\n\n\n\n#[cfg_attr(\n\n any(target_os = \"macos\", target_os = \"ios\"),\n\n link(name = \"System\", kind = \"dylib\")\n\n)]\n\n#[cfg_attr(\n\n not(any(target_os = \"macos\", target_os = \"ios\")),\n\n link(name = \"dispatch\", kind = \"dylib\")\n\n)]\n\n#[allow(improper_ctypes)]\n\nextern \"C\" {\n\n static _dispatch_main_q: dispatch_queue_t;\n\n\n\n fn dispatch_data_create(\n\n buffer: *const std::ffi::c_void,\n\n size: crate::c_size_t,\n\n queue: dispatch_queue_t,\n\n destructor: dispatch_block_t,\n\n ) -> dispatch_data_t;\n\n fn dispatch_release(object: dispatch_data_t); // actually dispatch_object_t\n\n}\n\n\n\n/*type MTLNewLibraryCompletionHandler = extern fn(library: id, error: id);\n", "file_path": "src/device.rs", "rank": 0, "score": 47999.85371361015 }, { "content": " vector_float2 position;\n", "file_path": "examples/texture/shader_types/shader_types.h", "rank": 1, "score": 23409.461431382642 }, { "content": " vector_float2 texture_coord;\n", "file_path": "examples/texture/shader_types/shader_types.h", "rank": 2, "score": 22423.499855959595 }, { "content": "# metal-rs\n\n[![Actions Status](https://github.com/gfx-rs/metal-rs/workflows/ci/badge.svg)](https://github.com/gfx-rs/metal-rs/actions)\n\n[![Crates.io](https://img.shields.io/crates/v/metal.svg?label=metal)](https://crates.io/crates/metal)\n\n\n\nUnsafe Rust bindings for the Metal 3D Graphics API.\n\n\n\n## Examples\n\n\n\nThe [examples](/examples) directory highlights different ways of using the Metal graphics API for rendering\n\nand computation.\n\n\n\nExamples can be run using commands such as:\n\n\n\n```\n\n# Replace `window` with the name of the example that you would like to run\n\ncargo run --example window\n\n```\n\n\n\n## License\n\n\n\nLicensed under either of\n\n\n\n * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)\n\n * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)\n\n\n\nat your option.\n\n\n\n### Contribution\n\n\n\nUnless you explicitly state otherwise, any contribution intentionally submitted\n\nfor inclusion in the work by you, as defined in the Apache-2.0 license, shall be\n\ndual licensed as above, without any additional terms or conditions.\n", "file_path": "README.md", "rank": 3, "score": 20688.17747363572 }, { "content": "fn get_window_layer(window: &Window, device: &Device) -> MetalLayer {\n\n let layer = MetalLayer::new();\n\n\n\n layer.set_device(device);\n\n layer.set_pixel_format(PIXEL_FORMAT);\n\n // Presenting with transactions isn't necessary since we aren't synchonizing with other UIKit\n\n // draw calls.\n\n // https://developer.apple.com/documentation/quartzcore/cametallayer/1478157-presentswithtransaction\n\n layer.set_presents_with_transaction(false);\n\n\n\n layer.set_drawable_size(CGSize::new(\n\n window.inner_size().width as f64,\n\n window.inner_size().height as f64,\n\n ));\n\n\n\n unsafe {\n\n let view = window.ns_view() as cocoa_id;\n\n view.setWantsLayer(true as _);\n\n view.setLayer(std::mem::transmute(layer.as_ref()));\n\n }\n\n\n\n layer\n\n}\n\n\n", "file_path": "examples/texture/src/main.rs", "rank": 4, "score": 20681.379825206022 }, { "content": "Welcome!\n\n\n\nThe `metal-rs` library exposes unsafe Rust bindings for the [Metal 3D graphics API](https://developer.apple.com/metal/), allowing you to write Metal applications entirely in Rust.\n\n\n\nThe `metal-rs` wiki serves as a higher-level guide on getting started with `metal-rs`.\n\n\n\nTo skip straight to full code examples you can check out the [examples] directory.\n\n\n\n[examples]: https://github.com/gfx-rs/metal-rs/tree/master/examples\n", "file_path": "guide/README.md", "rank": 5, "score": 19913.12229160508 }, { "content": "# texture\n\n\n\nThis tutorial ports the Objective-C/Swift [Creating and Sampling Textures] tutorial to Rust.\n\n\n\nWe use a [Cargo build script][build-scripts] to:\n\n\n\n- Generate Rust types from our metal shader type definitions using [rust-bindgen]\n\n - The type generation is cached and only happens when the shader type definitions change.\n\n\n\n- Compile our shaders into a `metallib`\n\n\n\nAfter the build script runs the `main.rs` binary uses the generated types to pass vertex and texture data to the GPU where we\n\nrender a textured quad to a window.\n\n\n\n## To Run\n\n\n\n```\n\ncargo run -p texture\n\n\n\n# If you see an error such as:\n\n# /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.3/include/avx512vlcdintrin.h:49:10: error: invalid conversion between vector type '__m128i' (vector of 2 'long long' values) and integer type 'int' of different size, err: true\n\n#\n\n# Try linking to LLVM's clang instead of Apple's:\n\n# brew install llvm\n\n# LIBCLANG_PATH=/usr/local/opt/llvm/lib cargo run -p texture\n\n```\n\n\n\n## Screenshots\n\n\n\n![Screenshot of example](./screenshot.png)\n\n\n\n[rust-bindgen]: https://github.com/rust-lang/rust-bindgen\n\n[build-scripts]: https://doc.rust-lang.org/cargo/reference/build-scripts.html\n\n[Creating and Sampling Textures]: (https://developer.apple.com/documentation/metal/creating_and_sampling_textures)\n", "file_path": "examples/texture/README.md", "rank": 6, "score": 19195.220897213614 }, { "content": "Under the hood, `metal-rs` is powered by three main dependencies.\n\n\n\n[rust-objc] and [rust-block] and [foreign-types].\n\n\n\nThese dependencies are used to communicate with the [Objective-C runtime] in order to allocate, de-allocate and call methods on the classes and objects that power Metal applications.\n\n\n\n## Memory Management\n\n\n\n`metal-rs` follows Apple's [memory management policy].\n\n\n\nWhen calling a method such as `CaptureManager::shared()`, the implementation looks like this:\n\n\n\n```rust\n\nimpl CaptureManager {\n\n pub fn shared<'a>() -> &'a CaptureManagerRef {\n\n unsafe {\n\n let class = class!(MTLCaptureManager);\n\n msg_send![class, sharedCaptureManager]\n\n }\n\n }\n\n}\n\n```\n\n\n\nNote that a borrowed reference is returned. As such, when the returned reference is dropped, memory will not be deallocated.\n\n\n\nContrast this with the `StencilDescriptor::new()` method.\n\n\n\n```rust\n\nimpl StencilDescriptor {\n\n pub fn new() -> Self {\n\n unsafe {\n\n let class = class!(MTLStencilDescriptor);\n\n msg_send![class, new]\n\n }\n\n }\n\n}\n\n```\n\n\n\nIn this case we are calling the `new` method on a class, which returns an owned object.\n\n\n\nThe macro\n\n\n\n```rust\n\nforeign_obj_type! {\n\n type CType = MTLStencilDescriptor;\n\n pub struct StencilDescriptor;\n\n pub struct StencilDescriptorRef;\n\n}\n\n```\n\n\n\nensures that when the owned `StencilDescriptor` is dropped it will call `release` on the backing Objective-C object, leading to the memory being deallocated.\n\n\n\n[rust-objc]: https://github.com/SSheldon/rust-objc\n\n[rust-block]: https://github.com/SSheldon/rust-block\n\n[foreign-types]: https://github.com/sfackler/foreign-types\n\n[Objective-C runtime]: https://developer.apple.com/documentation/objectivec/objective-c_runtime\n\n[memory management policy]: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html#//apple_ref/doc/uid/20000994-BAJHFBGH\n", "file_path": "guide/internals/README.md", "rank": 7, "score": 19193.668926574635 }, { "content": "## circle\n\n\n\nRenders a circle in a window. As metal primitive types are only limited to point, line and triangle shape, this example shows how we can form complex structures out of primitive types.\n\n\n\n![Screenshot of the final render](./screenshot.png)\n\n\n\n## To Run\n\n\n\n```\n\ncargo run --example circle\n\n```\n", "file_path": "examples/circle/README.md", "rank": 8, "score": 19193.523135376614 }, { "content": "## window\n\n\n\nRenders a spinning triangle to a [winit](https://github.com/rust-windowing/winit) window.\n\n\n\n![Screenshot of the final render](./screenshot.png)\n\n\n\n## To Run\n\n\n\n```\n\ncargo run --example window\n\n```\n", "file_path": "examples/window/README.md", "rank": 9, "score": 19190.44161521935 }, { "content": "# Debugging in Xcode\n\n\n\nIf you only want to enable Metal validation without using Xcode, use the `METAL_DEVICE_WRAPPER_TYPE=1` environment variable when lauching your program. For example, to run the `window` example with Metal validation, use the command `METAL_DEVICE_WRAPPER_TYPE=1 cargo run --example window`.\n\n\n\nLet's walk through an example of debugging the [`texture` example](/examples/texture).\n\n\n\n---\n\n\n\nCreate a new project using the \"External Build System\" template.\n\n\n\n![New project](./new-project.png)\n\n\n\n---\n\n\n\n\n\nSet the build command to be `cargo` and set the working directory to be the `metal-rs` repository.\n\n\n\nSet the arguments to `build --package texture`\n\n\n\n![Build settings](./build-settings.png)\n\n\n\n---\n\n\n\nClick `build` once in order to generate the executable.\n\n\n\n> If you get any shader compilation errors edit your `Build Settings` with `LIBCLANG_PATH=/usr/local/opt/llvm/lib` after running `brew install llvm`.\n\n\n\n`Product > Scheme > Edit Scheme` and choose the `metal-rs/target/texture` executable.\n\n\n\n![Set run target](./set-run-target.png)\n\n\n\n---\n\n\n\nNow when you click `run` you should see the textured quad example in a window.\n\n\n\n![Running window](./running-window.png)\n\n\n\n---\n\n\n\nFrom here you'll be able to use XCode's Metal debugging tools on your running application, such as capturing a GPU frame.\n\n\n\n![Capture GPU frame](./capture-gpu-frame.png)\n\n\n\n---\n\n\n\nSee [Developing and debugging shaders](https://developer.apple.com/documentation/metal/shader_authoring/developing_and_debugging_metal_shaders) for more infromation on\n\ndebugging Metal applications in XCode.\n\n\n\n# Capture GPU Command Data to a File\n\n\n\nYou can also [capture GPU command data programatically](https://developer.apple.com/documentation/metal/frame_capture_debugging_tools/capturing_gpu_command_data_programmatically). \n\n\n\nNote that Xcode has a closed source approach to how it sets the `GT_HOST_URL_MTL` environment variable that is required for captures, so you must run your application within Xcode in order to use the frame capture debugging tools.\n", "file_path": "guide/debugging-in-xcode/README.md", "rank": 10, "score": 18530.08284889612 }, { "content": "## headless-render\n\n\n\nRenders the triangle from the [window example](../window) headlessly and then writes it to a PNG file.\n\n\n\n![Screenshot of the final render](./screenshot.png)\n\n\n\n## To Run\n\n\n\n```\n\ncargo run --example headless-render\n\n```\n", "file_path": "examples/headless-render/README.md", "rank": 11, "score": 18522.78015076755 }, { "content": "use metal::*;\n\nuse std::ffi::c_void;\n\nuse std::mem;\n\n\n\n#[repr(C)]\n", "file_path": "examples/mps/main.rs", "rank": 12, "score": 9.21905408021204 }, { "content": "// Copyright 2016 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse metal::*;\n\nuse objc::rc::autoreleasepool;\n\n\n\nconst PROGRAM: &'static str = \"\n\n #include <metal_stdlib>\\n\\\n\n\n\n using namespace metal;\\n\\\n\n\n\n typedef struct {\\n\\\n\n float2 position;\\n\\\n\n float3 color;\\n\\\n\n } vertex_t;\\n\\\n\n\n", "file_path": "examples/reflection/main.rs", "rank": 13, "score": 8.149405475825557 }, { "content": "use metal::*;\n\n\n\nuse winit::{\n\n event::{Event, WindowEvent},\n\n event_loop::{ControlFlow, EventLoop},\n\n platform::macos::WindowExtMacOS,\n\n};\n\n\n\nuse cocoa::{appkit::NSView, base::id as cocoa_id};\n\nuse core_graphics_types::geometry::CGSize;\n\n\n\nuse objc::{rc::autoreleasepool, runtime::YES};\n\n\n\nuse std::mem;\n\n\n\n// Declare the data structures needed to carry vertex layout to\n\n// metal shading language(MSL) program. Use #[repr(C)], to make\n\n// the data structure compatible with C++ type data structure\n\n// for vertex defined in MSL program as MSL program is broadly\n\n// based on C++\n", "file_path": "examples/circle/main.rs", "rank": 14, "score": 7.797632276993142 }, { "content": "use cocoa::{appkit::NSView, base::id as cocoa_id};\n\nuse core_graphics_types::geometry::CGSize;\n\n\n\nuse metal::*;\n\nuse objc::{rc::autoreleasepool, runtime::YES};\n\n\n\nuse winit::{\n\n event::{Event, WindowEvent},\n\n event_loop::ControlFlow,\n\n platform::macos::WindowExtMacOS,\n\n};\n\n\n\nuse std::mem;\n\n\n", "file_path": "examples/shader-dylib/main.rs", "rank": 15, "score": 7.740034384126883 }, { "content": "// Copyright 2017 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse metal::*;\n\nuse objc::rc::autoreleasepool;\n\nuse std::mem;\n\n\n\nstatic LIBRARY_SRC: &str = include_str!(\"compute-argument-buffer.metal\");\n\n\n", "file_path": "examples/compute/compute-argument-buffer.rs", "rank": 16, "score": 7.636329237380565 }, { "content": "// Copyright 2016 metal-rs developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nextern crate objc;\n\n\n\nuse cocoa::{appkit::NSView, base::id as cocoa_id};\n\nuse core_graphics_types::geometry::CGSize;\n\n\n\nuse metal::*;\n\nuse objc::{rc::autoreleasepool, runtime::YES};\n\nuse std::mem;\n\nuse winit::platform::macos::WindowExtMacOS;\n\n\n\nuse winit::{\n\n event::{Event, WindowEvent},\n\n event_loop::ControlFlow,\n\n};\n\n\n\n#[repr(C)]\n", "file_path": "examples/window/main.rs", "rank": 17, "score": 7.560918871867647 }, { "content": "//! Renders a textured quad to a window and adjusts the GPU buffer that contains the viewport's\n\n//! height and width whenever the window is resized.\n\n\n\nuse std::path::PathBuf;\n\n\n\nuse cocoa::{appkit::NSView, base::id as cocoa_id};\n\nuse objc::rc::autoreleasepool;\n\nuse winit::dpi::LogicalSize;\n\nuse winit::event_loop::{ControlFlow, EventLoop};\n\nuse winit::platform::macos::WindowExtMacOS;\n\nuse winit::window::Window;\n\n\n\nuse metal::{\n\n Buffer, CGSize, CommandQueue, Device, Library, MTLClearColor, MTLLoadAction, MTLOrigin,\n\n MTLPixelFormat, MTLPrimitiveType, MTLRegion, MTLResourceOptions, MTLSize, MTLStoreAction,\n\n MetalLayer, MetalLayerRef, RenderPassDescriptor, RenderPassDescriptorRef,\n\n RenderPipelineDescriptor, RenderPipelineState, Texture, TextureDescriptor, TextureRef,\n\n};\n\nuse shader_bindings::{\n\n TextureIndex_TextureIndexBaseColor as TextureBaseColorIdx, TexturedVertex,\n", "file_path": "examples/texture/src/main.rs", "rank": 18, "score": 7.427007759136709 }, { "content": "// Copyright 2017 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse metal::*;\n\nuse objc::rc::autoreleasepool;\n\nuse std::mem;\n\n\n", "file_path": "examples/compute/main.rs", "rank": 19, "score": 7.057806373496096 }, { "content": " /// # Arguments\n\n /// * `resource`: A resource within an argument buffer.\n\n /// * `usage`: Options for describing how a graphics function uses the resource.\n\n ///\n\n /// See <https://developer.apple.com/documentation/metal/mtlrendercommandencoder/2866168-useresource?language=objc>\n\n #[deprecated(note = \"Use use_resource_at instead\")]\n\n pub fn use_resource(&self, resource: &ResourceRef, usage: MTLResourceUsage) {\n\n unsafe {\n\n msg_send![self,\n\n useResource:resource\n\n usage:usage\n\n ]\n\n }\n\n }\n\n\n\n /// Adds an untracked resource to the render pass, specifying which render stages need it.\n\n ///\n\n /// Availability: iOS 13.0+, macOS 10.15+\n\n ///\n\n /// # Arguments\n", "file_path": "src/encoder.rs", "rank": 20, "score": 6.787479283918847 }, { "content": "// Copyright 2020 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse dispatch::{Queue, QueueAttribute};\n\nuse metal::*;\n\n\n\n/// This example replicates `Synchronizing Events Between a GPU and the CPU` article.\n\n/// See https://developer.apple.com/documentation/metal/synchronization/synchronizing_events_between_a_gpu_and_the_cpu\n", "file_path": "examples/events/main.rs", "rank": 21, "score": 6.7163615807369945 }, { "content": "// Copyright 2017 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse metal::*;\n\nuse objc::rc::autoreleasepool;\n\n\n", "file_path": "examples/compute/embedded-lib.rs", "rank": 22, "score": 6.663093966714921 }, { "content": "// Copyright 2017 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse metal::*;\n\nuse objc::rc::autoreleasepool;\n\n\n", "file_path": "examples/argument-buffer/main.rs", "rank": 23, "score": 6.663093966714921 }, { "content": "// Copyright 2018 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse metal::*;\n\nuse objc::rc::autoreleasepool;\n\n\n", "file_path": "examples/bind/main.rs", "rank": 24, "score": 6.663093966714921 }, { "content": " usage: usage\n\n stages: stages\n\n ]\n\n }\n\n }\n\n\n\n /// Adds the resources in a heap to the render pass.\n\n ///\n\n /// Availability: iOS 11.0+, macOS 10.13+\n\n ///\n\n /// # Arguments:\n\n /// * `heap`: A heap that contains resources within an argument buffer.\n\n ///\n\n /// See <https://developer.apple.com/documentation/metal/mtlrendercommandencoder/2866163-useheap?language=objc>\n\n #[deprecated(note = \"Use use_heap_at instead\")]\n\n pub fn use_heap(&self, heap: &HeapRef) {\n\n unsafe { msg_send![self, useHeap: heap] }\n\n }\n\n\n\n /// Adds the resources in a heap to the render pass, specifying which render stages need them.\n", "file_path": "src/encoder.rs", "rank": 25, "score": 6.616901365730042 }, { "content": " /// * `resource`: A resource within an argument buffer.\n\n /// * `usage`: Options for describing how a graphics function uses the resource.\n\n /// * `stages`: The render stages where the resource must be resident.\n\n ///\n\n /// See <https://developer.apple.com/documentation/metal/mtlrendercommandencoder/3043404-useresource>\n\n pub fn use_resource_at(\n\n &self,\n\n resource: &ResourceRef,\n\n usage: MTLResourceUsage,\n\n stages: MTLRenderStages,\n\n ) {\n\n unsafe {\n\n msg_send![self,\n\n useResource: resource\n\n usage: usage\n\n stages: stages\n\n ]\n\n }\n\n }\n\n\n", "file_path": "src/encoder.rs", "rank": 26, "score": 6.56374589407797 }, { "content": " ///\n\n /// Availability: iOS 11.0+, macOS 10.13+\n\n ///\n\n /// See <https://developer.apple.com/documentation/metal/mtlcomputecommandencoder/2866530-useheap>\n\n ///\n\n /// # Arguments\n\n /// * `heap`: A heap that contains resources within an argument buffer.\n\n pub fn use_heap(&self, heap: &HeapRef) {\n\n unsafe { msg_send![self, useHeap: heap] }\n\n }\n\n\n\n /// Specifies that an array of heaps containing resources in an argument buffer can be safely\n\n /// used by a compute pass.\n\n ///\n\n /// Availability: iOS 11.0+, macOS 10.13+\n\n ///\n\n /// # Arguments\n\n /// * `heaps`: A slice of heaps that contains resources within an argument buffer.\n\n pub fn use_heaps(&self, heaps: &[&HeapRef]) {\n\n unsafe {\n", "file_path": "src/encoder.rs", "rank": 28, "score": 6.393132663011737 }, { "content": " /// Specifies that an array of resources in an argument buffer can be safely used by a compute pass.\n\n ///\n\n /// Availability: iOS 11.0+, macOS 10.13+\n\n ///\n\n /// See <https://developer.apple.com/documentation/metal/mtlcomputecommandencoder/2866561-useresources>\n\n ///\n\n /// # Arguments\n\n /// * `resources`: A slice of resources within an argument buffer.\n\n /// * `usage`: The options that describe how the array of resources will be used by a compute function.\n\n pub fn use_resources(&self, resources: &[&ResourceRef], usage: MTLResourceUsage) {\n\n unsafe {\n\n msg_send![self,\n\n useResources: resources.as_ptr()\n\n count: resources.len() as NSUInteger\n\n usage: usage\n\n ]\n\n }\n\n }\n\n\n\n /// Specifies that a heap containing resources in an argument buffer can be safely used by a compute pass.\n", "file_path": "src/encoder.rs", "rank": 29, "score": 6.389475851904597 }, { "content": "use std::mem;\n\nuse std::path::PathBuf;\n\n\n\nuse std::fs::File;\n\nuse std::io::BufWriter;\n\n\n\nuse metal::{\n\n Buffer, Device, DeviceRef, LibraryRef, MTLClearColor, MTLLoadAction, MTLOrigin, MTLPixelFormat,\n\n MTLPrimitiveType, MTLRegion, MTLResourceOptions, MTLSize, MTLStoreAction, RenderPassDescriptor,\n\n RenderPassDescriptorRef, RenderPipelineDescriptor, RenderPipelineState, Texture,\n\n TextureDescriptor, TextureRef,\n\n};\n\nuse png::ColorType;\n\n\n\nconst VIEW_WIDTH: u64 = 512;\n\nconst VIEW_HEIGHT: u64 = 512;\n\nconst TOTAL_BYTES: usize = (VIEW_WIDTH * VIEW_HEIGHT * 4) as usize;\n\n\n\nconst VERTEX_SHADER: &'static str = \"triangle_vertex\";\n\nconst FRAGMENT_SHADER: &'static str = \"triangle_fragment\";\n", "file_path": "examples/headless-render/main.rs", "rank": 30, "score": 6.010106219353766 }, { "content": "// Copyright 2020 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse metal::*;\n\n\n", "file_path": "examples/fence/main.rs", "rank": 31, "score": 5.8584846962483095 }, { "content": "// Copyright 2017 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse metal::*;\n\n\n", "file_path": "examples/caps/main.rs", "rank": 32, "score": 5.8584846962483095 }, { "content": "\n\n // Serialize the binary archive to disk.\n\n binary_archive\n\n .serialize_to_url(&binary_archive_url)\n\n .unwrap();\n\n\n\n // Set the command queue used to pass commands to the device.\n\n let command_queue = device.new_command_queue();\n\n\n\n // Currently, MetalLayer is the only interface that provide\n\n // layers to carry drawable texture from GPU rendaring through metal\n\n // library to viewable windows.\n\n let layer = MetalLayer::new();\n\n layer.set_device(&device);\n\n layer.set_pixel_format(MTLPixelFormat::BGRA8Unorm);\n\n layer.set_presents_with_transaction(false);\n\n\n\n unsafe {\n\n let view = window.ns_view() as cocoa_id;\n\n view.setWantsLayer(YES);\n", "file_path": "examples/circle/main.rs", "rank": 33, "score": 5.713663117726668 }, { "content": "// Copyright 2020 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse super::*;\n\n\n\nuse objc::runtime::{BOOL, YES};\n\n\n\n#[link(name = \"MetalPerformanceShaders\", kind = \"framework\")]\n\nextern \"C\" {\n\n fn MPSSupportsMTLDevice(device: *const std::ffi::c_void) -> BOOL;\n\n}\n\n\n", "file_path": "src/mps.rs", "rank": 34, "score": 5.694490722787071 }, { "content": "// Copyright 2016 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse metal::*;\n\n\n\nconst PROGRAM: &'static str = \"\";\n\n\n", "file_path": "examples/library/main.rs", "rank": 35, "score": 5.663714847128249 }, { "content": "use std::collections::hash_map::DefaultHasher;\n\nuse std::env;\n\nuse std::hash::{Hash, Hasher};\n\nuse std::path::PathBuf;\n\nuse std::process::Command;\n\n\n", "file_path": "examples/texture/build.rs", "rank": 36, "score": 5.28079879946215 }, { "content": "foreign_obj_type! {\n\n type CType = CAMetalDrawable;\n\n pub struct MetalDrawable;\n\n pub struct MetalDrawableRef;\n\n type ParentType = DrawableRef;\n\n}\n\n\n\nimpl MetalDrawableRef {\n\n pub fn texture(&self) -> &TextureRef {\n\n unsafe { msg_send![self, texture] }\n\n }\n\n}\n\n\n\npub enum CAMetalLayer {}\n\n\n\nforeign_obj_type! {\n\n type CType = CAMetalLayer;\n\n pub struct MetalLayer;\n\n pub struct MetalLayerRef;\n\n}\n", "file_path": "src/lib.rs", "rank": 37, "score": 5.262845230538869 }, { "content": "// Copyright 2020 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse super::*;\n\n\n\nuse std::path::Path;\n\n\n\n/// https://developer.apple.com/documentation/metal/mtlcapturedestination?language=objc\n\n#[repr(u64)]\n\n#[allow(non_camel_case_types)]\n\n#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]\n\npub enum MTLCaptureDestination {\n\n DeveloperTools = 1,\n\n GpuTraceDocument = 2,\n\n}\n\n\n", "file_path": "src/capturedescriptor.rs", "rank": 38, "score": 5.1468722541976994 }, { "content": "// xcrun -sdk macosx metal -c shaders.metal -o shaders.air\n\n// xcrun -sdk macosx metallib shaders.air -o shaders.metallib\n\nfn compile_shaders() {\n\n println!(\"cargo:rerun-if-changed=shaders.metal\");\n\n println!(\"cargo:rerun-if-changed=shader_types.h\");\n\n\n\n let output = Command::new(\"xcrun\")\n\n .arg(\"-sdk\")\n\n .arg(\"macosx\")\n\n .arg(\"metal\")\n\n .args(&[\"-c\", \"shaders.metal\"])\n\n .args(&[\"-o\", \"shaders.air\"])\n\n .spawn()\n\n .unwrap()\n\n .wait_with_output()\n\n .unwrap();\n\n if !output.status.success() {\n\n panic!(\n\n r#\"\n\nstdout: {}\n\nstderr: {}\n\n\"#,\n", "file_path": "examples/texture/build.rs", "rank": 39, "score": 4.655592287693805 }, { "content": "// If we want to draw a circle, we need to draw it out of the three primitive\n\n// types available with metal framework. Triangle is used in this case to form\n\n// the circle. If we consider a circle to be total of 360 degree at center, we\n\n// can form small triangle with one point at origin and two points at the\n\n// perimeter of the circle for each degree. Eventually, if we can take enough\n\n// triangle virtices for total of 360 degree, the triangles together will\n\n// form a circle. This function captures the triangle vertices for each degree\n\n// and push the co-ordinates of the vertices to a rust vector\n\nfn create_vertex_points_for_circle() -> Vec<AAPLVertex> {\n\n let mut v: Vec<AAPLVertex> = Vec::new();\n\n let origin_x: f32 = 0.0;\n\n let origin_y: f32 = 0.0;\n\n\n\n // Size of the circle\n\n let circle_size = 0.8f32;\n\n\n\n for i in 0..720 {\n\n let y = i as f32;\n\n // Get the X co-ordinate of each point on the perimeter of circle\n\n let position_x: f32 = y.to_radians().cos() * 100.0;\n\n let position_x: f32 = position_x.trunc() / 100.0;\n\n // Set the size of the circle\n\n let position_x: f32 = position_x * circle_size;\n\n // Get the Y co-ordinate of each point on the perimeter of circle\n\n let position_y: f32 = y.to_radians().sin() * 100.0;\n\n let position_y: f32 = position_y.trunc() / 100.0;\n\n // Set the size of the circle\n\n let position_y: f32 = position_y * circle_size;\n", "file_path": "examples/circle/main.rs", "rank": 40, "score": 4.636162764931886 }, { "content": " ]\n\n }\n\n }\n\n\n\n /// Specifies that a resource in an argument buffer can be safely used by a compute pass.\n\n ///\n\n /// Availability: iOS 11.0+, macOS 10.13+\n\n ///\n\n /// # Arguments\n\n /// * `resource`: A specific resource within an argument buffer.\n\n /// * `usage`: The options that describe how the resource will be used by a compute function.\n\n pub fn use_resource(&self, resource: &ResourceRef, usage: MTLResourceUsage) {\n\n unsafe {\n\n msg_send![self,\n\n useResource: resource\n\n usage: usage\n\n ]\n\n }\n\n }\n\n\n", "file_path": "src/encoder.rs", "rank": 41, "score": 4.585136599562866 }, { "content": "// Copyright 2017 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse super::*;\n\n\n\nuse foreign_types::ForeignType;\n\nuse objc::runtime::{Object, BOOL, NO, YES};\n\n\n\nuse std::ffi::CStr;\n\nuse std::os::raw::{c_char, c_void};\n\nuse std::ptr;\n\n\n\n/// Only available on (macos(10.12), ios(10.0)\n\n#[repr(u64)]\n\n#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n\npub enum MTLPatchType {\n", "file_path": "src/library.rs", "rank": 42, "score": 4.573367925062103 }, { "content": "// Copyright 2016 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse super::*;\n\nuse block::{Block, RcBlock};\n\nuse std::mem;\n\n\n\n#[cfg(feature = \"dispatch_queue\")]\n\nuse dispatch;\n\n\n", "file_path": "src/sync.rs", "rank": 43, "score": 4.544214639273745 }, { "content": "// Copyright 2017 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\n#![allow(non_snake_case)]\n\n#![allow(non_upper_case_globals)]\n\n\n\n#[macro_use]\n\nextern crate bitflags;\n\n#[macro_use]\n\nextern crate log;\n\n#[macro_use]\n\nextern crate objc;\n\n#[macro_use]\n\nextern crate foreign_types;\n\n\n\nuse std::{\n", "file_path": "src/lib.rs", "rank": 44, "score": 4.529199496656278 }, { "content": " URL::new_with_string(&format!(\"file://{}\", binary_archive_path.display()));\n\n\n\n let binary_archive_descriptor = BinaryArchiveDescriptor::new();\n\n if binary_archive_path.exists() {\n\n binary_archive_descriptor.set_url(&binary_archive_url);\n\n }\n\n\n\n // Set up a binary archive to cache compiled shaders.\n\n let binary_archive = device\n\n .new_binary_archive_with_descriptor(&binary_archive_descriptor)\n\n .unwrap();\n\n\n\n let library_path = std::path::PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"))\n\n .join(\"examples/circle/shaders.metallib\");\n\n\n\n // Use the metallib file generated out of .metal shader file\n\n let library = device.new_library_with_file(library_path).unwrap();\n\n\n\n // The render pipeline generated from the vertex and fragment shaders in the .metal shader file.\n\n let pipeline_state = prepare_pipeline_state(&device, &library, &binary_archive);\n", "file_path": "examples/circle/main.rs", "rank": 45, "score": 4.481389088421225 }, { "content": " attachment.set_alpha_blend_operation(metal::MTLBlendOperation::Add);\n\n attachment.set_source_rgb_blend_factor(metal::MTLBlendFactor::SourceAlpha);\n\n attachment.set_source_alpha_blend_factor(metal::MTLBlendFactor::SourceAlpha);\n\n attachment.set_destination_rgb_blend_factor(metal::MTLBlendFactor::OneMinusSourceAlpha);\n\n attachment.set_destination_alpha_blend_factor(metal::MTLBlendFactor::OneMinusSourceAlpha);\n\n\n\n device\n\n .new_render_pipeline_state(&pipeline_state_descriptor)\n\n .unwrap()\n\n}\n\n\n", "file_path": "examples/window/main.rs", "rank": 46, "score": 4.452396621405236 }, { "content": "#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]\n\npub enum MTLTriangleFillMode {\n\n Fill = 0,\n\n Lines = 1,\n\n}\n\n\n\nbitflags! {\n\n /// https://developer.apple.com/documentation/metal/mtlblitoption\n\n #[allow(non_upper_case_globals)]\n\n pub struct MTLBlitOption: NSUInteger {\n\n /// https://developer.apple.com/documentation/metal/mtlblitoption/mtlblitoptionnone\n\n const None = 0;\n\n /// https://developer.apple.com/documentation/metal/mtlblitoption/mtlblitoptiondepthfromdepthstencil\n\n const DepthFromDepthStencil = 1 << 0;\n\n /// https://developer.apple.com/documentation/metal/mtlblitoption/mtlblitoptionstencilfromdepthstencil\n\n const StencilFromDepthStencil = 1 << 1;\n\n /// https://developer.apple.com/documentation/metal/mtlblitoption/mtlblitoptionrowlinearpvrtc\n\n const RowLinearPVRTC = 1 << 2;\n\n }\n\n}\n", "file_path": "src/encoder.rs", "rank": 47, "score": 4.376428384837162 }, { "content": "\n\nimpl MetalLayer {\n\n pub fn new() -> Self {\n\n unsafe {\n\n let class = class!(CAMetalLayer);\n\n msg_send![class, new]\n\n }\n\n }\n\n}\n\n\n\nimpl MetalLayerRef {\n\n pub fn device(&self) -> &DeviceRef {\n\n unsafe { msg_send![self, device] }\n\n }\n\n\n\n pub fn set_device(&self, device: &DeviceRef) {\n\n unsafe { msg_send![self, setDevice: device] }\n\n }\n\n\n\n pub fn pixel_format(&self) -> MTLPixelFormat {\n", "file_path": "src/lib.rs", "rank": 48, "score": 4.319574963471172 }, { "content": "// Copyright 2017 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse super::*;\n\n\n\nuse block::{Block, ConcreteBlock};\n\nuse foreign_types::ForeignType;\n\nuse objc::runtime::{Object, NO, YES};\n\n\n\nuse std::{ffi::CStr, os::raw::c_char, path::Path, ptr};\n\n\n\n// Available on macOS 10.11+, iOS 8.0+, tvOS 9.0+\n\n#[allow(non_camel_case_types)]\n\n#[repr(u64)]\n\n#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]\n\npub enum MTLFeatureSet {\n", "file_path": "src/device.rs", "rank": 49, "score": 4.214300315298409 }, { "content": "// The `TexturedVertex` type is generated by `build.rs` by parsing `shader_types.h`\n\n// using rust-bindgen\n\nfn vertices() -> [TexturedVertex; 6] {\n\n [\n\n textured_vertex([-200., -200.], [0., 1.]),\n\n textured_vertex([200., -200.], [1., 1.]),\n\n textured_vertex([200., 200.], [1., 0.]),\n\n textured_vertex([-200., -200.], [0., 1.]),\n\n textured_vertex([200., 200.], [1., 0.]),\n\n textured_vertex([-200., 200.], [0., 0.]),\n\n ]\n\n}\n\n\n", "file_path": "examples/texture/src/main.rs", "rank": 50, "score": 3.9023881299582897 }, { "content": "// Original example taken from https://sergeyreznik.github.io/metal-ray-tracer/part-1/index.html\n\nfn main() {\n\n let device = Device::system_default().expect(\"No device found\");\n\n\n\n let library_path =\n\n std::path::PathBuf::from(env!(\"CARGO_MANIFEST_DIR\")).join(\"examples/mps/shaders.metallib\");\n\n let library = device\n\n .new_library_with_file(library_path)\n\n .expect(\"Failed to load shader library\");\n\n\n\n let generate_rays_pipeline = create_pipeline(\"generateRays\", &library, &device);\n\n\n\n let queue = device.new_command_queue();\n\n let command_buffer = queue.new_command_buffer();\n\n\n\n // Simple vertex/index buffer data\n\n\n\n let vertices: [Vertex; 3] = [\n\n Vertex {\n\n xyz: [0.25, 0.25, 0.0],\n\n },\n", "file_path": "examples/mps/main.rs", "rank": 51, "score": 3.87240460827261 }, { "content": "// Copyright 2017 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse super::*;\n\n\n\nmod compute;\n\nmod render;\n\n\n\npub use self::compute::*;\n\npub use self::render::*;\n\n\n\n#[repr(u64)]\n\n#[allow(non_camel_case_types)]\n\n#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n\npub enum MTLMutability {\n\n Default = 0,\n", "file_path": "src/pipeline/mod.rs", "rank": 52, "score": 3.854547582537222 }, { "content": " borrow::{Borrow, ToOwned},\n\n marker::PhantomData,\n\n mem,\n\n ops::Deref,\n\n os::raw::c_void,\n\n};\n\n\n\nuse core_graphics_types::{base::CGFloat, geometry::CGSize};\n\nuse foreign_types::ForeignType;\n\nuse objc::runtime::{Object, NO, YES};\n\n\n\n#[cfg(target_pointer_width = \"64\")]\n\npub type NSInteger = i64;\n\n#[cfg(not(target_pointer_width = \"64\"))]\n\npub type NSInteger = i32;\n\n#[cfg(target_pointer_width = \"64\")]\n\npub type NSUInteger = u64;\n\n#[cfg(target_pointer_width = \"32\")]\n\npub type NSUInteger = u32;\n\n\n", "file_path": "src/lib.rs", "rank": 53, "score": 3.835191630574646 }, { "content": " /// Adds an array of untracked resources to the render pass, specifying which stages need them.\n\n ///\n\n /// When working with color render targets, call this method as late as possible to improve performance.\n\n ///\n\n /// Availability: iOS 13.0+, macOS 10.15+\n\n ///\n\n /// # Arguments\n\n /// * `resources`: A slice of resources within an argument buffer.\n\n /// * `usage`: Options for describing how a graphics function uses the resources.\n\n /// * `stages`: The render stages where the resources must be resident.\n\n pub fn use_resources(\n\n &self,\n\n resources: &[&ResourceRef],\n\n usage: MTLResourceUsage,\n\n stages: MTLRenderStages,\n\n ) {\n\n unsafe {\n\n msg_send![self,\n\n useResources: resources.as_ptr()\n\n count: resources.len() as NSUInteger\n", "file_path": "src/encoder.rs", "rank": 54, "score": 3.7412563797881004 }, { "content": " }\n\n\n\n /// https://developer.apple.com/documentation/metal/mtlcapturedescriptor/3237250-outputurl\n\n pub fn set_output_url<P: AsRef<Path>>(&self, output_url: P) {\n\n let output_url = nsstring_from_str(output_url.as_ref().to_str().unwrap());\n\n\n\n unsafe { msg_send![self, setOutputURL: output_url] }\n\n }\n\n\n\n /// https://developer.apple.com/documentation/metal/mtlcapturedescriptor?language=objc\n\n pub fn destination(&self) -> MTLCaptureDestination {\n\n unsafe { msg_send![self, destination] }\n\n }\n\n\n\n /// https://developer.apple.com/documentation/metal/mtlcapturedescriptor?language=objc\n\n pub fn set_destination(&self, destination: MTLCaptureDestination) {\n\n unsafe { msg_send![self, setDestination: destination] }\n\n }\n\n}\n", "file_path": "src/capturedescriptor.rs", "rank": 55, "score": 3.6617930733515913 }, { "content": "/// This example replicates `Synchronizing Events Between a GPU and the CPU` article.\n\n/// See https://developer.apple.com/documentation/metal/synchronization/synchronizing_events_between_a_gpu_and_the_cpu\n\nfn main() {\n\n let device = Device::system_default().expect(\"No device found\");\n\n\n\n let command_queue = device.new_command_queue();\n\n let command_buffer = command_queue.new_command_buffer();\n\n\n\n // Shareable event\n\n let shared_event = device.new_shared_event();\n\n\n\n // Shareable event listener\n\n let my_queue = Queue::create(\n\n \"com.example.apple-samplecode.MyQueue\",\n\n QueueAttribute::Serial,\n\n );\n\n\n\n // Enable `dispatch` feature to use dispatch queues,\n\n // otherwise unsafe `from_queue_handle` is available for use with native APIs.\n\n let shared_event_listener = SharedEventListener::from_queue(&my_queue);\n\n\n\n // Register CPU work\n", "file_path": "examples/events/main.rs", "rank": 56, "score": 3.550763126248327 }, { "content": "/// https://developer.apple.com/documentation/metal/mtlcapturedescriptor\n\npub enum MTLCaptureDescriptor {}\n\n\n\nforeign_obj_type! {\n\n type CType = MTLCaptureDescriptor;\n\n pub struct CaptureDescriptor;\n\n pub struct CaptureDescriptorRef;\n\n}\n\n\n\nimpl CaptureDescriptor {\n\n pub fn new() -> Self {\n\n unsafe {\n\n let class = class!(MTLCaptureDescriptor);\n\n msg_send![class, new]\n\n }\n\n }\n\n}\n\n\n\nimpl CaptureDescriptorRef {\n\n /// https://developer.apple.com/documentation/metal/mtlcapturedescriptor/3237248-captureobject\n", "file_path": "src/capturedescriptor.rs", "rank": 58, "score": 3.5332884319306284 }, { "content": " ///\n\n /// Availability: iOS 13.0+, macOS 10.15+\n\n ///\n\n /// # Arguments\n\n /// * `heap`: A heap that contains resources within an argument buffer.\n\n /// * `stages`: The render stages where the resources must be resident.\n\n ///\n\n pub fn use_heap_at(&self, heap: &HeapRef, stages: MTLRenderStages) {\n\n unsafe {\n\n msg_send![self,\n\n useHeap: heap\n\n stages: stages\n\n ]\n\n }\n\n }\n\n\n\n /// Adds the resources in an array of heaps to the render pass, specifying which render stages need them.\n\n ///\n\n /// Availability: iOS 13.0+, macOS 10.15+\n\n ///\n", "file_path": "src/encoder.rs", "rank": 59, "score": 3.531211648142505 }, { "content": " pub fn set_capture_device(&self, device: &DeviceRef) {\n\n unsafe { msg_send![self, setCaptureObject: device] }\n\n }\n\n\n\n /// https://developer.apple.com/documentation/metal/mtlcapturedescriptor/3237248-captureobject\n\n pub fn set_capture_scope(&self, scope: &CaptureScopeRef) {\n\n unsafe { msg_send![self, setCaptureObject: scope] }\n\n }\n\n\n\n /// https://developer.apple.com/documentation/metal/mtlcapturedescriptor/3237248-captureobject\n\n pub fn set_capture_command_queue(&self, command_queue: &CommandQueueRef) {\n\n unsafe { msg_send![self, setCaptureObject: command_queue] }\n\n }\n\n\n\n /// https://developer.apple.com/documentation/metal/mtlcapturedescriptor/3237250-outputurl\n\n pub fn output_url(&self) -> &Path {\n\n let output_url = unsafe { msg_send![self, outputURL] };\n\n let output_url = nsstring_as_str(output_url);\n\n\n\n Path::new(output_url)\n", "file_path": "src/capturedescriptor.rs", "rank": 60, "score": 3.387731105407691 }, { "content": " constants::*,\n\n depthstencil::*,\n\n device::*,\n\n drawable::*,\n\n encoder::*,\n\n heap::*,\n\n indirect_encoder::*,\n\n library::*,\n\n pipeline::*,\n\n renderpass::*,\n\n resource::*,\n\n sampler::*,\n\n texture::*,\n\n types::*,\n\n vertexdescriptor::*,\n\n sync::*,\n\n};\n\n\n\n#[cfg(feature = \"mps\")]\n\npub use mps::*;\n", "file_path": "src/lib.rs", "rank": 61, "score": 3.38370899483535 }, { "content": " /// # Arguments\n\n ///\n\n /// * `heaps`: A slice of heaps that contains resources within an argument buffer.\n\n /// * `stages`: The render stages where the resources must be resident.\n\n pub fn use_heaps(&self, heaps: &[&HeapRef], stages: MTLRenderStages) {\n\n unsafe {\n\n msg_send![self,\n\n useHeaps: heaps.as_ptr()\n\n count: heaps.len() as NSUInteger\n\n stages: stages\n\n ]\n\n }\n\n }\n\n\n\n pub fn update_fence(&self, fence: &FenceRef, after_stages: MTLRenderStages) {\n\n unsafe {\n\n msg_send![self,\n\n updateFence: fence\n\n afterStages: after_stages\n\n ]\n", "file_path": "src/encoder.rs", "rank": 62, "score": 3.3677173047536293 }, { "content": " encoder.end_encoding();\n\n\n\n // Schedule a present once the framebuffer is complete using the current drawable.\n\n command_buffer.present_drawable(&drawable);\n\n\n\n // Finalize rendering here & push the command buffer to the GPU.\n\n command_buffer.commit();\n\n }\n\n _ => (),\n\n }\n\n });\n\n });\n\n}\n\n\n", "file_path": "examples/circle/main.rs", "rank": 63, "score": 3.3393249378685055 }, { "content": " pub fn resource_options(&self) -> MTLResourceOptions {\n\n unsafe { msg_send![self, resourceOptions] }\n\n }\n\n\n\n pub fn set_purgeable_state(&self, state: MTLPurgeableState) -> MTLPurgeableState {\n\n unsafe { msg_send![self, setPurgeableState: state] }\n\n }\n\n\n\n pub fn size(&self) -> NSUInteger {\n\n unsafe { msg_send![self, size] }\n\n }\n\n\n\n pub fn used_size(&self) -> NSUInteger {\n\n unsafe { msg_send![self, usedSize] }\n\n }\n\n\n\n /// Only available on macos(10.15), ios(13.0)\n\n pub fn heap_type(&self) -> MTLHeapType {\n\n unsafe { msg_send![self, type] }\n\n }\n", "file_path": "src/heap.rs", "rank": 64, "score": 3.3237490562407808 }, { "content": "// Copyright 2017 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse super::*;\n\n\n\nuse std::ops::Range;\n\n\n\n#[repr(u64)]\n\n#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]\n\npub enum MTLPrimitiveType {\n\n Point = 0,\n\n Line = 1,\n\n LineStrip = 2,\n\n Triangle = 3,\n\n TriangleStrip = 4,\n\n}\n", "file_path": "src/encoder.rs", "rank": 65, "score": 3.3237490562407808 }, { "content": "// Copyright 2016 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse super::*;\n\n\n\nuse block::Block;\n\n\n\n#[repr(u32)]\n\n#[allow(non_camel_case_types)]\n\n#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]\n\npub enum MTLCommandBufferStatus {\n\n NotEnqueued = 0,\n\n Enqueued = 1,\n\n Committed = 2,\n\n Scheduled = 3,\n\n Completed = 4,\n", "file_path": "src/commandbuffer.rs", "rank": 66, "score": 3.259907989004852 }, { "content": " unsafe { msg_send![self, removeAllAnimations] }\n\n }\n\n\n\n pub fn next_drawable(&self) -> Option<&MetalDrawableRef> {\n\n unsafe { msg_send![self, nextDrawable] }\n\n }\n\n\n\n pub fn contents_scale(&self) -> CGFloat {\n\n unsafe { msg_send![self, contentsScale] }\n\n }\n\n\n\n pub fn set_contents_scale(&self, scale: CGFloat) {\n\n unsafe { msg_send![self, setContentsScale: scale] }\n\n }\n\n\n\n /// [framebufferOnly Apple Docs](https://developer.apple.com/documentation/metal/mtltexture/1515749-framebufferonly?language=objc)\n\n pub fn framebuffer_only(&self) -> bool {\n\n unsafe {\n\n match msg_send![self, framebufferOnly] {\n\n YES => true,\n", "file_path": "src/lib.rs", "rank": 67, "score": 3.2429214367303465 }, { "content": "// Copyright 2016 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse crate::DeviceRef;\n\nuse objc::runtime::{NO, YES};\n\n\n\n#[repr(u64)]\n\n#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]\n\npub enum MTLCompareFunction {\n\n Never = 0,\n\n Less = 1,\n\n Equal = 2,\n\n LessEqual = 3,\n\n Greater = 4,\n\n NotEqual = 5,\n\n GreaterEqual = 6,\n", "file_path": "src/depthstencil.rs", "rank": 68, "score": 3.2391691573956525 }, { "content": "// Copyright 2017 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse super::*;\n\n\n\nuse objc::runtime::{NO, YES};\n\n\n\n#[repr(u64)]\n\n#[allow(non_camel_case_types)]\n\n#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n\npub enum MTLAttributeFormat {\n\n Invalid = 0,\n\n UChar2 = 1,\n\n UChar3 = 2,\n\n UChar4 = 3,\n\n Char2 = 4,\n", "file_path": "src/pipeline/compute.rs", "rank": 70, "score": 3.1984731643881688 }, { "content": "// Copyright 2016 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse super::*;\n\n\n\nuse objc::runtime::{NO, YES};\n\n\n\n#[repr(u64)]\n\n#[allow(non_camel_case_types)]\n\n#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]\n\npub enum MTLTextureType {\n\n D1 = 0,\n\n D1Array = 1,\n\n D2 = 2,\n\n D2Array = 3,\n\n D2Multisample = 4,\n", "file_path": "src/texture.rs", "rank": 71, "score": 3.1984731643881688 }, { "content": "// Copyright 2018 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse super::*;\n\nuse std::ffi::CStr;\n\n\n\npub enum MTLCaptureScope {}\n\n\n\nforeign_obj_type! {\n\n type CType = MTLCaptureScope;\n\n pub struct CaptureScope;\n\n pub struct CaptureScopeRef;\n\n}\n\n\n\nimpl CaptureScopeRef {\n\n pub fn begin_scope(&self) {\n", "file_path": "src/capturemanager.rs", "rank": 72, "score": 3.1984731643881688 }, { "content": "// Copyright 2017 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse super::{MTLTextureType, NSUInteger};\n\nuse objc::runtime::{NO, YES};\n\n\n\n#[repr(u64)]\n\n#[allow(non_camel_case_types)]\n\n#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]\n\npub enum MTLDataType {\n\n None = 0,\n\n\n\n Struct = 1,\n\n Array = 2,\n\n\n\n Float = 3,\n", "file_path": "src/argument.rs", "rank": 74, "score": 3.178506243616353 }, { "content": "// Copyright 2016 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse super::{DeviceRef, HeapRef, NSUInteger};\n\nuse objc::runtime::{NO, YES};\n\n\n\n#[repr(u64)]\n\n#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n\npub enum MTLPurgeableState {\n\n KeepCurrent = 1,\n\n NonVolatile = 2,\n\n Volatile = 3,\n\n Empty = 4,\n\n}\n\n\n\n#[repr(u64)]\n", "file_path": "src/resource.rs", "rank": 75, "score": 3.178506243616353 }, { "content": "// Copyright 2017 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse super::*;\n\n\n\nuse objc::runtime::{NO, YES};\n\n\n\n#[repr(u64)]\n\n#[allow(non_camel_case_types)]\n\n#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n\npub enum MTLBlendFactor {\n\n Zero = 0,\n\n One = 1,\n\n SourceColor = 2,\n\n OneMinusSourceColor = 3,\n\n SourceAlpha = 4,\n", "file_path": "src/pipeline/render.rs", "rank": 76, "score": 3.1587870689044673 }, { "content": " argument_encoder.set_buffer(1, &sum, 0);\n\n\n\n let pipeline_state_descriptor = ComputePipelineDescriptor::new();\n\n pipeline_state_descriptor.set_compute_function(Some(&kernel));\n\n\n\n let pipeline_state = device\n\n .new_compute_pipeline_state_with_function(\n\n pipeline_state_descriptor.compute_function().unwrap(),\n\n )\n\n .unwrap();\n\n\n\n encoder.set_compute_pipeline_state(&pipeline_state);\n\n encoder.set_buffer(0, Some(&arg_buffer), 0);\n\n\n\n encoder.use_resource(&buffer, MTLResourceUsage::Read);\n\n encoder.use_resource(&sum, MTLResourceUsage::Write);\n\n\n\n let width = 16;\n\n\n\n let thread_group_count = MTLSize {\n", "file_path": "examples/compute/compute-argument-buffer.rs", "rank": 77, "score": 3.1393110576976224 }, { "content": "/// This example shows how to render headlessly by:\n\n///\n\n/// 1. Rendering a triangle to an MtlDrawable\n\n///\n\n/// 2. Waiting for the render to complete and the color texture to be synchronized with the CPU\n\n/// by using a blit command encoder\n\n///\n\n/// 3. Reading the texture bytes from the MtlTexture\n\n///\n\n/// 4. Saving the texture to a PNG file\n\nfn main() {\n\n let device = Device::system_default().expect(\"No device found\");\n\n\n\n let texture = create_texture(&device);\n\n\n\n let library_path = std::path::PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"))\n\n .join(\"examples/window/shaders.metallib\");\n\n\n\n let library = device.new_library_with_file(library_path).unwrap();\n\n\n\n let pipeline_state = prepare_pipeline_state(&device, &library);\n\n\n\n let command_queue = device.new_command_queue();\n\n\n\n let vertex_buffer = create_vertex_buffer(&device);\n\n\n\n let render_pass_descriptor = RenderPassDescriptor::new();\n\n initialize_color_attachment(&render_pass_descriptor, &texture);\n\n\n\n let command_buffer = command_queue.new_command_buffer();\n", "file_path": "examples/headless-render/main.rs", "rank": 78, "score": 3.133795227550165 }, { "content": "// Copyright 2016 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse super::NSUInteger;\n\nuse std::default::Default;\n\n\n\n#[repr(C)]\n\n#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Default)]\n\npub struct MTLOrigin {\n\n pub x: NSUInteger,\n\n pub y: NSUInteger,\n\n pub z: NSUInteger,\n\n}\n\n\n\n#[repr(C)]\n\n#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Default)]\n", "file_path": "src/types.rs", "rank": 79, "score": 3.0273185332370356 }, { "content": " /// Note that this is equivalent to the \"!=\" operator.\n\n Xor = 4,\n\n /// Accept the intersection if `~(primitive mask ^ ray mask) != 0`.\n\n /// Note that this is equivalent to the \"==\" operator.\n\n NotXor = 5,\n\n /// Accept the intersection if `(primitive mask < ray mask) != 0`.\n\n LessThan = 6,\n\n /// Accept the intersection if `(primitive mask <= ray mask) != 0`.\n\n LessThanOrEqualTo = 7,\n\n /// Accept the intersection if `(primitive mask > ray mask) != 0`.\n\n GreaterThan = 8,\n\n /// Accept the intersection if `(primitive mask >= ray mask) != 0`.\n\n GreaterThanOrEqualTo = 9,\n\n}\n\n\n\npub enum MPSTriangleIntersectionTestType {\n\n /// Use the default ray/triangle intersection test\n\n Default = 0,\n\n /// Use a watertight ray/triangle intersection test which avoids gaps along shared triangle edges.\n\n /// Shared vertices may still have gaps.\n", "file_path": "src/mps.rs", "rank": 80, "score": 3.0273185332370356 }, { "content": "mod library;\n\n#[cfg(feature = \"mps\")]\n\nmod mps;\n\nmod pipeline;\n\nmod renderpass;\n\nmod resource;\n\nmod sampler;\n\nmod sync;\n\nmod texture;\n\nmod types;\n\nmod vertexdescriptor;\n\n\n\n#[rustfmt::skip]\n\npub use {\n\n argument::*,\n\n buffer::*,\n\n capturedescriptor::*,\n\n capturemanager::*,\n\n commandbuffer::*,\n\n commandqueue::*,\n", "file_path": "src/lib.rs", "rank": 81, "score": 2.9867326201914186 }, { "content": "\n\n// [2 bytes position, 3 bytes color] * 3\n\n#[rustfmt::skip]\n\nconst VERTEX_ATTRIBS: [f32; 15] = [\n\n 0.0, 0.5, 1.0, 0.0, 0.0,\n\n -0.5, -0.5, 0.0, 1.0, 0.0,\n\n 0.5, -0.5, 0.0, 0.0, 1.0,\n\n];\n\n\n\n/// This example shows how to render headlessly by:\n\n///\n\n/// 1. Rendering a triangle to an MtlDrawable\n\n///\n\n/// 2. Waiting for the render to complete and the color texture to be synchronized with the CPU\n\n/// by using a blit command encoder\n\n///\n\n/// 3. Reading the texture bytes from the MtlTexture\n\n///\n\n/// 4. Saving the texture to a PNG file\n", "file_path": "examples/headless-render/main.rs", "rank": 82, "score": 2.821238898419197 }, { "content": " const StorageModePrivate = (MTLStorageMode::Private as NSUInteger) << MTLResourceStorageModeShift;\n\n const StorageModeMemoryless = (MTLStorageMode::Memoryless as NSUInteger) << MTLResourceStorageModeShift;\n\n\n\n /// Only available on macos(10.13), ios(10.0)\n\n const HazardTrackingModeDefault = (MTLHazardTrackingMode::Default as NSUInteger) << MTLResourceHazardTrackingModeShift;\n\n /// Only available on macos(10.13), ios(10.0)\n\n const HazardTrackingModeUntracked = (MTLHazardTrackingMode::Untracked as NSUInteger) << MTLResourceHazardTrackingModeShift;\n\n /// Only available on macos(10.15), ios(13.0)\n\n const HazardTrackingModeTracked = (MTLHazardTrackingMode::Tracked as NSUInteger) << MTLResourceHazardTrackingModeShift;\n\n }\n\n}\n\n\n\nbitflags! {\n\n /// Options that describe how a graphics or compute function uses an argument buffer’s resource.\n\n ///\n\n /// Enabling certain options for certain resources determines whether the Metal driver should\n\n /// convert the resource to another format (for example, whether to decompress a color render target).\n\n pub struct MTLResourceUsage: NSUInteger {\n\n /// An option that enables reading from the resource.\n\n const Read = 1 << 0;\n", "file_path": "src/resource.rs", "rank": 83, "score": 2.8199360063643413 }, { "content": "{\n\n fn borrow(&self) -> &ArrayRef<T> {\n\n unsafe { mem::transmute(self.as_ptr()) }\n\n }\n\n}\n\n\n\nimpl<T> ToOwned for ArrayRef<T>\n\nwhere\n\n T: ForeignType + 'static,\n\n T::Ref: objc::Message + 'static,\n\n{\n\n type Owned = Array<T>;\n\n\n\n fn to_owned(&self) -> Array<T> {\n\n unsafe { Array::from_ptr(msg_send![self, retain]) }\n\n }\n\n}\n\n\n\npub enum CAMetalDrawable {}\n\n\n", "file_path": "src/lib.rs", "rank": 84, "score": 2.7808417930592415 }, { "content": " let lib = device\n\n .new_library_with_source(dylib_src.as_str(), &opts)\n\n .unwrap();\n\n\n\n // create dylib\n\n let dylib = device.new_dynamic_library(&lib).unwrap();\n\n dylib.set_label(\"test_dylib\");\n\n\n\n // optional: serialize binary blob that can be loaded later\n\n let blob_url = String::from(\"file://\") + install_path.to_str().unwrap();\n\n let url = URL::new_with_string(&blob_url);\n\n dylib.serialize_to_url(&url).unwrap();\n\n\n\n // create shader that links with dylib\n\n let shader_src_path = std::path::PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"))\n\n .join(\"examples/shader-dylib/test_shader.metal\");\n\n\n\n let shader_src = std::fs::read_to_string(shader_src_path).expect(\"bad shit\");\n\n let opts = metal::CompileOptions::new();\n\n // add dynamic library to link with\n", "file_path": "examples/shader-dylib/main.rs", "rank": 85, "score": 2.740515202262647 }, { "content": " /// Do not provide any reflection information.\n\n const None = 0;\n\n /// An option that requests argument information for buffers, textures, and threadgroup memory.\n\n const ArgumentInfo = 1 << 0;\n\n /// An option that requests detailed buffer type information for buffer arguments.\n\n const BufferTypeInfo = 1 << 1;\n\n /// An option that specifies that Metal should create the pipeline state object only if the\n\n /// compiled shader is present inside the binary archive.\n\n ///\n\n /// Only available on (macos(11.0), ios(14.0))\n\n const FailOnBinaryArchiveMiss = 1 << 2;\n\n }\n\n}\n\n\n\n#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n\n#[repr(C)]\n\npub struct MTLAccelerationStructureSizes {\n\n pub acceleration_structure_size: NSUInteger,\n\n pub build_scratch_buffer_size: NSUInteger,\n\n pub refit_scratch_buffer_size: NSUInteger,\n\n}\n\n\n\n#[link(name = \"Metal\", kind = \"framework\")]\n\nextern \"C\" {\n\n fn MTLCreateSystemDefaultDevice() -> *mut MTLDevice;\n\n #[cfg(not(target_os = \"ios\"))]\n\n fn MTLCopyAllDevices() -> *mut Object; //TODO: Array\n\n}\n\n\n", "file_path": "src/device.rs", "rank": 86, "score": 2.5884092455214485 }, { "content": " msg_send![self,\n\n useHeaps: heaps.as_ptr()\n\n count: heaps.len() as NSUInteger\n\n ]\n\n }\n\n }\n\n\n\n pub fn update_fence(&self, fence: &FenceRef) {\n\n unsafe { msg_send![self, updateFence: fence] }\n\n }\n\n\n\n pub fn wait_for_fence(&self, fence: &FenceRef) {\n\n unsafe { msg_send![self, waitForFence: fence] }\n\n }\n\n}\n\n\n\npub enum MTLArgumentEncoder {}\n\n\n\nforeign_obj_type! {\n\n type CType = MTLArgumentEncoder;\n", "file_path": "src/encoder.rs", "rank": 87, "score": 2.5397821652780563 }, { "content": " y: 20,\n\n width: 100,\n\n height: 100,\n\n });\n\n encoder.set_render_pipeline_state(&clear_rect_pipeline_state);\n\n encoder.set_vertex_buffer(0, Some(&clear_rect_buffer), 0);\n\n encoder.draw_primitives_instanced(\n\n metal::MTLPrimitiveType::TriangleStrip,\n\n 0,\n\n 4,\n\n 1,\n\n );\n\n let physical_size = window.inner_size();\n\n encoder.set_scissor_rect(MTLScissorRect {\n\n x: 0,\n\n y: 0,\n\n width: physical_size.width as _,\n\n height: physical_size.height as _,\n\n });\n\n\n", "file_path": "examples/window/main.rs", "rank": 88, "score": 2.5336242048125905 }, { "content": " VertexInputIndex_VertexInputIndexVertices as VerticesBufferIdx,\n\n VertexInputIndex_VertexInputIndexViewportSize as ViewportSizeBufferIdx,\n\n};\n\nuse winit::event::{Event, WindowEvent};\n\n\n\nmod shader_bindings;\n\n\n\nconst INITIAL_WINDOW_WIDTH: u32 = 800;\n\nconst INITIAL_WINDOW_HEIGHT: u32 = 600;\n\nconst PIXEL_FORMAT: MTLPixelFormat = MTLPixelFormat::BGRA8Unorm;\n\n\n", "file_path": "examples/texture/src/main.rs", "rank": 89, "score": 2.490097975695019 }, { "content": " layer.set_framebuffer_only(false);\n\n unsafe {\n\n let view = window.ns_view() as cocoa_id;\n\n view.setWantsLayer(YES);\n\n view.setLayer(mem::transmute(layer.as_ref()));\n\n }\n\n let draw_size = window.inner_size();\n\n layer.set_drawable_size(CGSize::new(draw_size.width as f64, draw_size.height as f64));\n\n\n\n // compile dynamic lib shader\n\n let dylib_src_path = std::path::PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"))\n\n .join(\"examples/shader-dylib/test_dylib.metal\");\n\n let install_path =\n\n std::path::PathBuf::from(env!(\"CARGO_MANIFEST_DIR\")).join(\"target/test_dylib.metallib\");\n\n\n\n let dylib_src = std::fs::read_to_string(dylib_src_path).expect(\"bad shit\");\n\n let opts = metal::CompileOptions::new();\n\n opts.set_library_type(MTLLibraryType::Dynamic);\n\n opts.set_install_name(install_path.to_str().unwrap());\n\n\n", "file_path": "examples/shader-dylib/main.rs", "rank": 90, "score": 2.475972157953764 }, { "content": " // This method makes the array of resources resident for the selected stages of the render pass.\n\n // Call this method before issuing any draw calls that may access the array of resources.\n\n encoder.use_resources(\n\n &[&buffer1, &buffer2],\n\n MTLResourceUsage::Read,\n\n MTLRenderStages::Vertex,\n\n );\n\n // Bind argument buffer to vertex stage.\n\n encoder.set_vertex_buffer(0, Some(&argument_buffer), 0);\n\n\n\n // Render pass here...\n\n\n\n encoder.end_encoding();\n\n println!(\"Encoder: {:?}\", encoder);\n\n\n\n command_buffer.commit();\n\n });\n\n}\n", "file_path": "examples/argument-buffer/main.rs", "rank": 91, "score": 2.4423203709879657 }, { "content": " }\n\n}\n\n\n\n/// The base class for data structures that are built over geometry and used to accelerate ray tracing.\n\npub enum MPSAccelerationStructure {}\n\n\n\nforeign_obj_type! {\n\n type CType = MPSAccelerationStructure;\n\n pub struct AccelerationStructure;\n\n pub struct AccelerationStructureRef;\n\n}\n\n\n\nimpl AccelerationStructureRef {\n\n pub fn status(&self) -> MPSAccelerationStructureStatus {\n\n unsafe { msg_send![self, status] }\n\n }\n\n\n\n pub fn usage(&self) -> MPSAccelerationStructureUsage {\n\n unsafe { msg_send![self, usage] }\n\n }\n", "file_path": "src/mps.rs", "rank": 92, "score": 2.419112568490368 }, { "content": " | macOS_GPUFamily1_v1\n\n | macOS_GPUFamily2_v1\n\n | macOS_ReadWriteTextureTier2\n\n | tvOS_GPUFamily1_v1\n\n | tvOS_GPUFamily2_v1 => 1,\n\n iOS_GPUFamily1_v2 | iOS_GPUFamily2_v2 | iOS_GPUFamily3_v2 | iOS_GPUFamily4_v2\n\n | macOS_GPUFamily1_v2 | tvOS_GPUFamily1_v2 | tvOS_GPUFamily2_v2 => 2,\n\n iOS_GPUFamily1_v3 | iOS_GPUFamily2_v3 | iOS_GPUFamily3_v3 | macOS_GPUFamily1_v3\n\n | tvOS_GPUFamily1_v3 => 3,\n\n iOS_GPUFamily1_v4 | iOS_GPUFamily2_v4 | iOS_GPUFamily3_v4 | tvOS_GPUFamily1_v4\n\n | macOS_GPUFamily1_v4 => 4,\n\n iOS_GPUFamily1_v5 | iOS_GPUFamily2_v5 => 5,\n\n }\n\n }\n\n\n\n pub fn supports_metal_kit(&self) -> bool {\n\n true\n\n }\n\n\n\n pub fn supports_metal_performance_shaders(&self) -> bool {\n", "file_path": "src/device.rs", "rank": 93, "score": 2.3839237088422154 }, { "content": "use super::*;\n\n\n\nbitflags! {\n\n #[allow(non_upper_case_globals)]\n\n pub struct MTLIndirectCommandType: NSUInteger {\n\n const Draw = 1 << 0;\n\n const DrawIndexed = 1 << 1;\n\n const DrawPatches = 1 << 2;\n\n const DrawIndexedPatches = 1 << 3;\n\n const ConcurrentDispatch = 1 << 4;\n\n const ConcurrentDispatchThreads = 1 << 5;\n\n }\n\n}\n\n\n\npub enum MTLIndirectCommandBufferDescriptor {}\n\n\n\nforeign_obj_type! {\n\n type CType = MTLIndirectCommandBufferDescriptor;\n\n pub struct IndirectCommandBufferDescriptor;\n\n pub struct IndirectCommandBufferDescriptorRef;\n", "file_path": "src/indirect_encoder.rs", "rank": 94, "score": 2.352062158537001 }, { "content": " }\n\n }\n\n}\n\n\n\nbitflags! {\n\n /// The render stages at which a synchronization command is triggered.\n\n ///\n\n /// Render stages provide finer control for specifying when synchronization must occur,\n\n /// allowing for vertex and fragment processing to overlap in execution.\n\n ///\n\n /// See <https://developer.apple.com/documentation/metal/mtlrenderstages>\n\n pub struct MTLRenderStages: NSUInteger {\n\n /// The vertex rendering stage.\n\n const Vertex = 1 << 0;\n\n /// The fragment rendering stage.\n\n const Fragment = 1 << 1;\n\n /// The tile rendering stage.\n\n const Tile = 1 << 2;\n\n }\n\n}\n\n\n\nconst BLOCK_HAS_COPY_DISPOSE: i32 = 0x02000000;\n\nconst BLOCK_HAS_SIGNATURE: i32 = 0x40000000;\n\n\n", "file_path": "src/sync.rs", "rank": 95, "score": 2.348073642583148 }, { "content": " unsafe { msg_send![self, mipmapLevelCount] }\n\n }\n\n\n\n pub fn sample_count(&self) -> NSUInteger {\n\n unsafe { msg_send![self, sampleCount] }\n\n }\n\n\n\n pub fn array_length(&self) -> NSUInteger {\n\n unsafe { msg_send![self, arrayLength] }\n\n }\n\n\n\n pub fn usage(&self) -> MTLTextureUsage {\n\n unsafe { msg_send![self, usage] }\n\n }\n\n\n\n /// [framebufferOnly Apple Docs](https://developer.apple.com/documentation/metal/mtltexture/1515749-framebufferonly?language=objc)\n\n pub fn framebuffer_only(&self) -> bool {\n\n unsafe {\n\n match msg_send![self, isFramebufferOnly] {\n\n YES => true,\n", "file_path": "src/texture.rs", "rank": 96, "score": 2.3058561634929533 }, { "content": "// Copyright 2016 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse super::*;\n\n\n\n#[repr(u64)]\n\n#[derive(Copy, Clone, Debug)]\n\npub enum MTLLoadAction {\n\n DontCare = 0,\n\n Load = 1,\n\n Clear = 2,\n\n}\n\n\n\n#[repr(u64)]\n\n#[derive(Copy, Clone, Debug)]\n\npub enum MTLStoreAction {\n", "file_path": "src/renderpass.rs", "rank": 97, "score": 2.288628371881378 }, { "content": "// Copyright 2016 GFX developers\n\n//\n\n// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or\n\n// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or\n\n// http://opensource.org/licenses/MIT>, at your option. This file may not be\n\n// copied, modified, or distributed except according to those terms.\n\n\n\nuse super::*;\n\n\n\npub enum MTLBuffer {}\n\n\n\nforeign_obj_type! {\n\n type CType = MTLBuffer;\n\n pub struct Buffer;\n\n pub struct BufferRef;\n\n type ParentType = ResourceRef;\n\n}\n\n\n\nimpl BufferRef {\n\n pub fn length(&self) -> u64 {\n", "file_path": "src/buffer.rs", "rank": 98, "score": 2.2682373456007556 }, { "content": "#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]\n\npub enum MTLCounterSamplingPoint {\n\n AtStageBoundary = 0,\n\n AtDrawBoundary = 1,\n\n AtDispatchBoundary = 2,\n\n AtTileDispatchBoundary = 3,\n\n AtBlitBoundary = 4,\n\n}\n\n\n\n/// Only available on (macos(11.0), macCatalyst(14.0), ios(13.0))\n\n#[repr(u64)]\n\n#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]\n\npub enum MTLSparseTextureRegionAlignmentMode {\n\n Outward = 0,\n\n Inward = 1,\n\n}\n\n\n\nbitflags! {\n\n /// Options that determine how Metal prepares the pipeline.\n\n pub struct MTLPipelineOption: NSUInteger {\n", "file_path": "src/device.rs", "rank": 99, "score": 2.265129980190598 } ]
Rust
lib/emscripten/build/emtests.rs
cdetrio/wasmer
b68b109b7de1d27a334591fdeeda475c808c812a
use glob::glob; use std::fs; use std::path::Path; use std::path::PathBuf; use std::process::Command; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; static BANNER: &str = "// Rust test file autogenerated with cargo build (build/emtests.rs). // Please do NOT modify it by hand, as it will be reseted on next build.\n"; const EXTENSIONS: [&str; 2] = ["c", "cpp"]; const EXCLUDES: [&str; 0] = []; pub fn compile(file: &str, ignores: &Vec<String>) -> Option<String> { let mut output_path = PathBuf::from(file); output_path.set_extension("out"); let mut output_path = PathBuf::from(file); output_path.set_extension("js"); let output_str = output_path.to_str().unwrap(); let _wasm_compilation = Command::new("emcc") .arg(file) .arg("-s") .arg("WASM=1") .arg("-o") .arg(output_str) .output() .expect("failed to execute process"); if Path::new(output_str).is_file() { fs::remove_file(output_str).unwrap(); } else { println!("Output JS not found: {}", output_str); } let mut output_path = PathBuf::from(file); output_path.set_extension("output"); let module_name = output_path .file_stem() .unwrap() .to_str() .unwrap() .to_owned(); let rs_module_name = module_name.to_lowercase(); let rust_test_filepath = format!( concat!(env!("CARGO_MANIFEST_DIR"), "/tests/emtests/{}.rs"), rs_module_name.as_str() ); let output_extension = if file.ends_with("c") || module_name.starts_with("test_") { "out" } else { "txt" }; let ignored = if ignores .iter() .any(|i| &i.to_lowercase() == &module_name.to_lowercase()) { "\n#[ignore]" } else { "" }; let module_path = format!("emtests/{}.wasm", module_name); let test_output_path = format!("emtests/{}.{}", module_name, output_extension); if !Path::new(&module_path).is_file() { println!("Path not found to test module: {}", module_path); None } else if !Path::new(&test_output_path).is_file() { println!("Path not found to test output: {}", module_path); None } else { let contents = format!( "#[test]{ignore} fn test_{rs_module_name}() {{ assert_emscripten_output!( \"../../{module_path}\", \"{rs_module_name}\", vec![], \"../../{test_output_path}\" ); }} ", ignore = ignored, module_path = module_path, rs_module_name = rs_module_name, test_output_path = test_output_path ); fs::write(&rust_test_filepath, contents.as_bytes()).unwrap(); Some(rs_module_name) } } pub fn build() { let rust_test_modpath = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/emtests/mod.rs"); let mut modules: Vec<String> = Vec::new(); let ignores = read_ignore_list(); for ext in EXTENSIONS.iter() { for entry in glob(&format!("emtests/*.{}", ext)).unwrap() { match entry { Ok(path) => { let test = path.to_str().unwrap(); if !EXCLUDES.iter().any(|e| test.ends_with(e)) { if let Some(module_name) = compile(test, &ignores) { modules.push(module_name); } } } Err(e) => println!("{:?}", e), } } } modules.sort(); let mut modules: Vec<String> = modules.iter().map(|m| format!("mod {};", m)).collect(); assert!(modules.len() > 0, "Expected > 0 modules found"); modules.insert(0, BANNER.to_string()); modules.insert(1, "// The _common module is not autogenerated, as it provides common macros for the emtests\n#[macro_use]\nmod _common;".to_string()); modules.push("".to_string()); let modfile: String = modules.join("\n"); let source = fs::read(&rust_test_modpath).unwrap(); if source != modfile.as_bytes() { fs::write(&rust_test_modpath, modfile.as_bytes()).unwrap(); } } fn read_ignore_list() -> Vec<String> { let f = File::open("emtests/ignores.txt").unwrap(); let f = BufReader::new(f); f.lines().filter_map(Result::ok).collect() }
use glob::glob; use std::fs; use std::path::Path; use std::path::PathBuf; use std::process::Command; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; static BANNER: &str = "// Rust test file autogenerated with cargo build (build/emtests.rs). // Please do NOT modify it by hand, as it will be reseted on next build.\n"; const EXTENSIONS: [&str; 2] = ["c", "cpp"]; const EXCLUDES: [&str; 0] = []; pub fn compile(file: &str, ignores: &Vec<String>) -> Option<String> { let mut output_path = PathBuf::from(file); output_path.set_extension("out"); let mut output_path = PathBuf::from(file); output_path.set_extension("js"); let output_str = output_path.to_str().unwrap(); let _wasm_compilation = Command::new("emcc") .arg(file) .arg("-s") .arg("WASM=1") .arg("-o") .arg(output_str) .output() .expect("failed to execute process"); if Path::new(output_str).is_file() { fs::remove_file(output_str).unwrap(); } else { println!("Output JS not found: {}", output_str); } let mut output_path = PathBuf::from(file); output_path.set_extension("output"); let module_name = output_path .file_stem() .unwrap() .to_str() .unwrap() .to_owned(); let rs_module_name = module_name.to_lowercase(); let rust_test_filepath = format!( concat!(env!("CARGO_MANIFEST_DIR"), "/tests/emtests/{}.rs"), rs_module_name.as_str() ); let output_extension = if file.ends_with("c") || module_name.starts_with("test_") { "out" } else { "txt" }; let ignored = if ignores .iter() .any(|i| &i.to_lowercase() == &module_name.to_lowercase()) { "\n#[ignore]" } else { "" }; let module_path = format!("emtests/{}.wasm", module_name); let test_output_path = format!("emtests/{}.{}", module_name, output_extension); if !Path::new(
Vec<String> = Vec::new(); let ignores = read_ignore_list(); for ext in EXTENSIONS.iter() { for entry in glob(&format!("emtests/*.{}", ext)).unwrap() { match entry { Ok(path) => { let test = path.to_str().unwrap(); if !EXCLUDES.iter().any(|e| test.ends_with(e)) { if let Some(module_name) = compile(test, &ignores) { modules.push(module_name); } } } Err(e) => println!("{:?}", e), } } } modules.sort(); let mut modules: Vec<String> = modules.iter().map(|m| format!("mod {};", m)).collect(); assert!(modules.len() > 0, "Expected > 0 modules found"); modules.insert(0, BANNER.to_string()); modules.insert(1, "// The _common module is not autogenerated, as it provides common macros for the emtests\n#[macro_use]\nmod _common;".to_string()); modules.push("".to_string()); let modfile: String = modules.join("\n"); let source = fs::read(&rust_test_modpath).unwrap(); if source != modfile.as_bytes() { fs::write(&rust_test_modpath, modfile.as_bytes()).unwrap(); } } fn read_ignore_list() -> Vec<String> { let f = File::open("emtests/ignores.txt").unwrap(); let f = BufReader::new(f); f.lines().filter_map(Result::ok).collect() }
&module_path).is_file() { println!("Path not found to test module: {}", module_path); None } else if !Path::new(&test_output_path).is_file() { println!("Path not found to test output: {}", module_path); None } else { let contents = format!( "#[test]{ignore} fn test_{rs_module_name}() {{ assert_emscripten_output!( \"../../{module_path}\", \"{rs_module_name}\", vec![], \"../../{test_output_path}\" ); }} ", ignore = ignored, module_path = module_path, rs_module_name = rs_module_name, test_output_path = test_output_path ); fs::write(&rust_test_filepath, contents.as_bytes()).unwrap(); Some(rs_module_name) } } pub fn build() { let rust_test_modpath = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/emtests/mod.rs"); let mut modules:
random
[ { "content": "pub fn abort_with_message(ctx: &mut Ctx, message: &str) {\n\n debug!(\"emscripten::abort_with_message\");\n\n println!(\"{}\", message);\n\n _abort(ctx);\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 0, "score": 257234.96267437495 }, { "content": "pub fn _endgrent(_ctx: &mut Ctx) {\n\n debug!(\"emscripten::_endgrent\");\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 1, "score": 224197.33646141062 }, { "content": "pub fn _abort(_ctx: &mut Ctx) {\n\n debug!(\"emscripten::_abort\");\n\n unsafe {\n\n abort();\n\n }\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 2, "score": 224197.33646141062 }, { "content": "pub fn _setgrent(_ctx: &mut Ctx) {\n\n debug!(\"emscripten::_setgrent\");\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 3, "score": 224197.33646141062 }, { "content": "pub fn _llvm_trap(ctx: &mut Ctx) {\n\n debug!(\"emscripten::_llvm_trap\");\n\n abort_with_message(ctx, \"abort!\");\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 4, "score": 219737.55602644448 }, { "content": "#[allow(clippy::cast_ptr_alignment)]\n\npub fn _getgrent(ctx: &mut Ctx) -> c_int {\n\n debug!(\"emscripten::_getgrent\");\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 5, "score": 213925.4123550189 }, { "content": "pub fn _fork(_ctx: &mut Ctx) -> pid_t {\n\n debug!(\"emscripten::_fork\");\n\n // unsafe {\n\n // fork()\n\n // }\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 6, "score": 213925.4123550189 }, { "content": "pub fn _sched_yield(_ctx: &mut Ctx) -> i32 {\n\n debug!(\"emscripten::_sched_yield\");\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 7, "score": 209714.2309654982 }, { "content": "pub fn _llvm_stacksave(_ctx: &mut Ctx) -> i32 {\n\n debug!(\"emscripten::_llvm_stacksave\");\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 8, "score": 209714.2309654982 }, { "content": "type Trampoline = unsafe extern \"C\" fn(*mut Ctx, *const Func, *const u64, *mut u64) -> c_void;\n", "file_path": "lib/win-exception-handler/src/exception_handling.rs", "rank": 9, "score": 209675.63485309185 }, { "content": "#[allow(unreachable_code)]\n\npub fn _exit(_ctx: &mut Ctx, status: c_int) {\n\n // -> !\n\n debug!(\"emscripten::_exit {}\", status);\n\n unsafe { exit(status) }\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 10, "score": 204809.50289906823 }, { "content": "pub fn static_alloc(static_top: &mut u32, size: u32) -> u32 {\n\n let old_static_top = *static_top;\n\n // NOTE: The `4294967280` is a u32 conversion of -16 as gotten from emscripten.\n\n *static_top = (*static_top + size + 15) & 4294967280;\n\n old_static_top\n\n}\n", "file_path": "lib/emscripten/src/storage.rs", "rank": 11, "score": 202216.64754561908 }, { "content": "/// exit\n\npub fn ___syscall1(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) {\n\n debug!(\"emscripten::___syscall1 (exit) {}\", which);\n\n let status: i32 = varargs.get(ctx);\n\n unsafe {\n\n exit(status);\n\n }\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/mod.rs", "rank": 12, "score": 201765.4387725987 }, { "content": "pub fn _llvm_stackrestore(_ctx: &mut Ctx, _one: i32) {\n\n debug!(\"emscripten::_llvm_stackrestore\");\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 13, "score": 200826.69790858394 }, { "content": "pub fn abort_stack_overflow(ctx: &mut Ctx, _what: c_int) {\n\n debug!(\"emscripten::abort_stack_overflow\");\n\n // TODO: Message incomplete. Need to finish em runtime data first\n\n abort_with_message(\n\n ctx,\n\n \"Stack overflow! Attempted to allocate some bytes on the stack\",\n\n );\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 14, "score": 200826.69790858394 }, { "content": "pub fn em_abort(ctx: &mut Ctx, message: u32) {\n\n debug!(\"emscripten::em_abort {}\", message);\n\n let message_addr = emscripten_memory_pointer!(ctx.memory(0), message) as *mut c_char;\n\n unsafe {\n\n let message = CStr::from_ptr(message_addr)\n\n .to_str()\n\n .unwrap_or(\"Unexpected abort\");\n\n\n\n abort_with_message(ctx, message);\n\n }\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 15, "score": 200826.69790858394 }, { "content": "#[allow(clippy::cast_ptr_alignment)]\n\npub fn ___build_environment(ctx: &mut Ctx, environ: c_int) {\n\n debug!(\"emscripten::___build_environment {}\", environ);\n\n const MAX_ENV_VALUES: u32 = 64;\n\n const TOTAL_ENV_SIZE: u32 = 1024;\n\n let environment = emscripten_memory_pointer!(ctx.memory(0), environ) as *mut c_int;\n\n unsafe {\n\n let (pool_offset, _pool_slice): (u32, &mut [u8]) =\n\n allocate_on_stack(ctx, TOTAL_ENV_SIZE as u32);\n\n let (env_offset, _env_slice): (u32, &mut [u8]) =\n\n allocate_on_stack(ctx, (MAX_ENV_VALUES * 4) as u32);\n\n let env_ptr = emscripten_memory_pointer!(ctx.memory(0), env_offset) as *mut c_int;\n\n let mut _pool_ptr = emscripten_memory_pointer!(ctx.memory(0), pool_offset) as *mut c_int;\n\n *env_ptr = pool_offset as i32;\n\n *environment = env_offset as i32;\n\n\n\n // *env_ptr = 0;\n\n };\n\n // unsafe {\n\n // *env_ptr = 0;\n\n // };\n\n}\n\n\n", "file_path": "lib/emscripten/src/env/mod.rs", "rank": 16, "score": 197113.15358653892 }, { "content": "pub fn _raise(_ctx: &mut Ctx, _one: i32) -> i32 {\n\n debug!(\"emscripten::_raise\");\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 17, "score": 196632.268642606 }, { "content": "pub fn _system(_ctx: &mut Ctx, _one: i32) -> c_int {\n\n debug!(\"emscripten::_system\");\n\n // TODO: May need to change this Em impl to a working version\n\n eprintln!(\"Can't call external programs\");\n\n return EAGAIN;\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 18, "score": 196632.268642606 }, { "content": "pub fn _usleep(_ctx: &mut Ctx, _one: i32) -> i32 {\n\n debug!(\"emscripten::_usleep\");\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 19, "score": 196632.268642606 }, { "content": "/// uname\n\n// NOTE: Wondering if we should return custom utsname, like Emscripten.\n\npub fn ___syscall122(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall122 (uname) {}\", which);\n\n -1\n\n}\n", "file_path": "lib/emscripten/src/syscalls/windows.rs", "rank": 20, "score": 195455.11306274828 }, { "content": "#[allow(clippy::cast_ptr_alignment)]\n\npub fn ___syscall142(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall142 (newselect) {}\", which);\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/windows.rs", "rank": 21, "score": 195455.11306274828 }, { "content": "// mkdir\n\npub fn ___syscall39(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall39 (mkdir) {}\", which);\n\n let pathname: u32 = varargs.get(ctx);\n\n let mode: u32 = varargs.get(ctx);\n\n let pathname_addr = emscripten_memory_pointer!(ctx.memory(0), pathname) as *const i8;\n\n unsafe { mkdir(pathname_addr) }\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/windows.rs", "rank": 22, "score": 195455.11306274828 }, { "content": "/// uname\n\n// NOTE: Wondering if we should return custom utsname, like Emscripten.\n\npub fn ___syscall122(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall122 (uname) {}\", which);\n\n let buf: u32 = varargs.get(ctx);\n\n debug!(\"=> buf: {}\", buf);\n\n let buf_addr = emscripten_memory_pointer!(ctx.memory(0), buf) as *mut utsname;\n\n unsafe { uname(buf_addr) }\n\n}\n", "file_path": "lib/emscripten/src/syscalls/unix.rs", "rank": 23, "score": 195455.11306274828 }, { "content": "// mkdir\n\npub fn ___syscall39(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall39 (mkdir) {}\", which);\n\n let pathname: u32 = varargs.get(ctx);\n\n let mode: u32 = varargs.get(ctx);\n\n let pathname_addr = emscripten_memory_pointer!(ctx.memory(0), pathname) as *const i8;\n\n unsafe { mkdir(pathname_addr, mode as _) }\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/unix.rs", "rank": 24, "score": 195455.11306274828 }, { "content": "#[allow(clippy::cast_ptr_alignment)]\n\npub fn ___syscall145(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> i32 {\n\n // -> ssize_t\n\n debug!(\"emscripten::___syscall145 (readv) {}\", which);\n\n // let fd: i32 = varargs.get(ctx);\n\n // let iov: u32 = varargs.get(ctx);\n\n // let iovcnt: i32 = varargs.get(ctx);\n\n // debug!(\"=> fd: {}, iov: {}, iovcnt = {}\", fd, iov, iovcnt);\n\n // let iov_addr = emscripten_memory_pointer!(ctx.memory(0), iov) as *mut iovec;\n\n // unsafe { readv(fd, iov_addr, iovcnt) }\n\n\n\n let fd: i32 = varargs.get(ctx);\n\n let iov: i32 = varargs.get(ctx);\n\n let iovcnt: i32 = varargs.get(ctx);\n\n\n\n #[repr(C)]\n\n struct GuestIovec {\n\n iov_base: i32,\n\n iov_len: i32,\n\n }\n\n\n", "file_path": "lib/emscripten/src/syscalls/mod.rs", "rank": 25, "score": 195455.11306274828 }, { "content": "/// read\n\npub fn ___syscall3(ctx: &mut Ctx, which: i32, mut varargs: VarArgs) -> i32 {\n\n // -> ssize_t\n\n debug!(\"emscripten::___syscall3 (read) {}\", which);\n\n let fd: i32 = varargs.get(ctx);\n\n let buf: u32 = varargs.get(ctx);\n\n let count = varargs.get(ctx);\n\n debug!(\"=> fd: {}, buf_offset: {}, count: {}\", fd, buf, count);\n\n let buf_addr = emscripten_memory_pointer!(ctx.memory(0), buf) as *mut c_void;\n\n let ret = unsafe { read(fd, buf_addr, count) };\n\n debug!(\"=> ret: {}\", ret);\n\n ret as _\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/mod.rs", "rank": 26, "score": 195455.11306274828 }, { "content": "// rmdir\n\npub fn ___syscall40(ctx: &mut Ctx, _which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall40 (rmdir)\");\n\n let pathname: u32 = varargs.get(ctx);\n\n let pathname_addr = emscripten_memory_pointer!(ctx.memory(0), pathname) as *const i8;\n\n unsafe { rmdir(pathname_addr) }\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/mod.rs", "rank": 27, "score": 195455.11306274828 }, { "content": "/// open\n\npub fn ___syscall5(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall5 (open) {}\", which);\n\n let pathname: u32 = varargs.get(ctx);\n\n let flags: i32 = varargs.get(ctx);\n\n let mode: u32 = varargs.get(ctx);\n\n let pathname_addr = emscripten_memory_pointer!(ctx.memory(0), pathname) as *const i8;\n\n let path_str = unsafe { std::ffi::CStr::from_ptr(pathname_addr).to_str().unwrap() };\n\n let fd = unsafe { open(pathname_addr, flags, mode) };\n\n debug!(\n\n \"=> pathname: {}, flags: {}, mode: {} = fd: {}\\npath: {}\",\n\n pathname, flags, mode, fd, path_str\n\n );\n\n fd\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/mod.rs", "rank": 28, "score": 195455.11306274828 }, { "content": "#[allow(clippy::cast_ptr_alignment)]\n\npub fn ___syscall102(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall102 (socketcall) {}\", which);\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/windows.rs", "rank": 29, "score": 195455.11306274828 }, { "content": "// pwrite\n\npub fn ___syscall181(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall181 (pwrite) {}\", which);\n\n let fd: i32 = varargs.get(ctx);\n\n let buf: u32 = varargs.get(ctx);\n\n let count: u32 = varargs.get(ctx);\n\n {\n\n let zero: u32 = varargs.get(ctx);\n\n assert_eq!(zero, 0);\n\n }\n\n let offset: i64 = varargs.get(ctx);\n\n\n\n let buf_ptr = emscripten_memory_pointer!(ctx.memory(0), buf) as _;\n\n let status = unsafe { pwrite(fd, buf_ptr, count as _, offset) as _ };\n\n debug!(\n\n \"=> fd: {}, buf: {}, count: {}, offset: {} = status:{}\",\n\n fd, buf, count, offset, status\n\n );\n\n status\n\n}\n\n\n\n/// wait4\n", "file_path": "lib/emscripten/src/syscalls/unix.rs", "rank": 30, "score": 195455.11306274828 }, { "content": "// fstat64\n\npub fn ___syscall197(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall197 (fstat64) {}\", which);\n\n let fd: c_int = varargs.get(ctx);\n\n let buf: u32 = varargs.get(ctx);\n\n\n\n unsafe {\n\n let mut stat = std::mem::zeroed();\n\n let ret = fstat(fd, &mut stat);\n\n debug!(\"ret: {}\", ret);\n\n if ret != 0 {\n\n return ret;\n\n }\n\n copy_stat_into_wasm(ctx, buf, &stat);\n\n }\n\n\n\n 0\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/mod.rs", "rank": 31, "score": 195455.11306274828 }, { "content": "// setpgid\n\npub fn ___syscall57(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall57 (setpgid) {}\", which);\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/windows.rs", "rank": 32, "score": 195455.11306274828 }, { "content": "/// ioctl\n\npub fn ___syscall54(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall54 (ioctl) {}\", which);\n\n let fd: i32 = varargs.get(ctx);\n\n let request: u32 = varargs.get(ctx);\n\n debug!(\"fd: {}, op: {}\", fd, request);\n\n // Got the equivalents here: https://code.woboq.org/linux/linux/include/uapi/asm-generic/ioctls.h.html\n\n match request as _ {\n\n 21537 => {\n\n // FIONBIO\n\n let argp: u32 = varargs.get(ctx);\n\n let argp_ptr = emscripten_memory_pointer!(ctx.memory(0), argp) as *mut c_void;\n\n let ret = unsafe { ioctl(fd, FIONBIO, argp_ptr) };\n\n debug!(\"ret(FIONBIO): {}\", ret);\n\n ret\n\n // 0\n\n }\n\n 21523 => {\n\n // TIOCGWINSZ\n\n let argp: u32 = varargs.get(ctx);\n\n let argp_ptr = emscripten_memory_pointer!(ctx.memory(0), argp) as *mut c_void;\n", "file_path": "lib/emscripten/src/syscalls/unix.rs", "rank": 33, "score": 195455.11306274828 }, { "content": "#[allow(clippy::cast_ptr_alignment)]\n\npub fn ___syscall146(ctx: &mut Ctx, which: i32, mut varargs: VarArgs) -> i32 {\n\n // -> ssize_t\n\n debug!(\"emscripten::___syscall146 (writev) {}\", which);\n\n let fd: i32 = varargs.get(ctx);\n\n let iov: i32 = varargs.get(ctx);\n\n let iovcnt: i32 = varargs.get(ctx);\n\n\n\n #[repr(C)]\n\n struct GuestIovec {\n\n iov_base: i32,\n\n iov_len: i32,\n\n }\n\n\n\n debug!(\"=> fd: {}, iov: {}, iovcnt = {}\", fd, iov, iovcnt);\n\n let mut ret = 0;\n\n unsafe {\n\n for i in 0..iovcnt {\n\n let guest_iov_addr =\n\n emscripten_memory_pointer!(ctx.memory(0), (iov + i * 8)) as *mut GuestIovec;\n\n let iov_base = emscripten_memory_pointer!(ctx.memory(0), (*guest_iov_addr).iov_base)\n", "file_path": "lib/emscripten/src/syscalls/mod.rs", "rank": 34, "score": 195455.11306274828 }, { "content": "// fcntl64\n\npub fn ___syscall221(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall221 (fcntl64) {}\", which);\n\n // fcntl64\n\n let _fd: i32 = varargs.get(ctx);\n\n let cmd: u32 = varargs.get(ctx);\n\n match cmd {\n\n 2 => 0,\n\n _ => -1,\n\n }\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/mod.rs", "rank": 35, "score": 195455.11306274828 }, { "content": "// stat64\n\npub fn ___syscall195(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall195 (stat64) {}\", which);\n\n let pathname: u32 = varargs.get(ctx);\n\n let buf: u32 = varargs.get(ctx);\n\n\n\n let pathname_addr = emscripten_memory_pointer!(ctx.memory(0), pathname) as *const i8;\n\n\n\n unsafe {\n\n let mut _stat: stat = std::mem::zeroed();\n\n let ret = stat(pathname_addr, &mut _stat);\n\n debug!(\"ret: {}\", ret);\n\n if ret != 0 {\n\n return ret;\n\n }\n\n copy_stat_into_wasm(ctx, buf, &_stat);\n\n }\n\n 0\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/mod.rs", "rank": 36, "score": 195455.11306274828 }, { "content": "// dup2\n\npub fn ___syscall63(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall63 (dup2) {}\", which);\n\n\n\n let src: i32 = varargs.get(ctx);\n\n let dst: i32 = varargs.get(ctx);\n\n\n\n unsafe { dup2(src, dst) }\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/mod.rs", "rank": 37, "score": 195455.11306274828 }, { "content": "/// close\n\npub fn ___syscall6(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall6 (close) {}\", which);\n\n let fd: i32 = varargs.get(ctx);\n\n debug!(\"fd: {}\", fd);\n\n unsafe { close(fd) }\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/mod.rs", "rank": 38, "score": 195455.11306274828 }, { "content": "#[allow(clippy::cast_ptr_alignment)]\n\npub fn ___syscall102(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall102 (socketcall) {}\", which);\n\n let call: u32 = varargs.get(ctx);\n\n let mut socket_varargs: VarArgs = varargs.get(ctx);\n\n\n\n #[repr(C)]\n\n pub struct GuestSockaddrIn {\n\n pub sin_family: sa_family_t, // u16\n\n pub sin_port: in_port_t, // u16\n\n pub sin_addr: GuestInAddr, // u32\n\n pub sin_zero: [u8; 8], // u8 * 8\n\n // 2 + 2 + 4 + 8 = 16\n\n }\n\n\n\n #[repr(C)]\n\n pub struct GuestInAddr {\n\n pub s_addr: in_addr_t, // u32\n\n }\n\n\n\n // debug!(\"GuestSockaddrIn = {}\", size_of::<GuestSockaddrIn>());\n", "file_path": "lib/emscripten/src/syscalls/unix.rs", "rank": 39, "score": 195455.11306274828 }, { "content": "/// dup3\n\npub fn ___syscall330(ctx: &mut Ctx, _which: c_int, mut varargs: VarArgs) -> pid_t {\n\n debug!(\"emscripten::___syscall330 (dup3)\");\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/windows.rs", "rank": 40, "score": 195455.11306274828 }, { "content": "// prlimit64\n\npub fn ___syscall340(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall340 (prlimit64), {}\", which);\n\n // NOTE: Doesn't really matter. Wasm modules cannot exceed WASM_PAGE_SIZE anyway.\n\n let _pid: i32 = varargs.get(ctx);\n\n let _resource: i32 = varargs.get(ctx);\n\n let _new_limit: u32 = varargs.get(ctx);\n\n let old_limit: u32 = varargs.get(ctx);\n\n\n\n if old_limit != 0 {\n\n // just report no limits\n\n let buf_ptr = emscripten_memory_pointer!(ctx.memory(0), old_limit) as *mut u8;\n\n let buf = unsafe { slice::from_raw_parts_mut(buf_ptr, 16) };\n\n\n\n LittleEndian::write_i32(&mut buf[..], -1); // RLIM_INFINITY\n\n LittleEndian::write_i32(&mut buf[4..], -1); // RLIM_INFINITY\n\n LittleEndian::write_i32(&mut buf[8..], -1); // RLIM_INFINITY\n\n LittleEndian::write_i32(&mut buf[12..], -1); // RLIM_INFINITY\n\n }\n\n\n\n 0\n\n}\n", "file_path": "lib/emscripten/src/syscalls/mod.rs", "rank": 41, "score": 195455.11306274828 }, { "content": "/// write\n\npub fn ___syscall4(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall4 (write) {}\", which);\n\n let fd: i32 = varargs.get(ctx);\n\n let buf: u32 = varargs.get(ctx);\n\n let count = varargs.get(ctx);\n\n debug!(\"=> fd: {}, buf: {}, count: {}\", fd, buf, count);\n\n let buf_addr = emscripten_memory_pointer!(ctx.memory(0), buf) as *const c_void;\n\n unsafe { write(fd, buf_addr, count) as i32 }\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/mod.rs", "rank": 42, "score": 195455.11306274828 }, { "content": "// chdir\n\npub fn ___syscall12(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall12 (chdir) {}\", which);\n\n let path_addr: i32 = varargs.get(ctx);\n\n unsafe {\n\n let path_ptr = emscripten_memory_pointer!(ctx.memory(0), path_addr) as *const i8;\n\n let path = std::ffi::CStr::from_ptr(path_ptr);\n\n let ret = chdir(path_ptr);\n\n debug!(\"=> path: {:?}, ret: {}\", path, ret);\n\n ret\n\n }\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/mod.rs", "rank": 43, "score": 195455.11306274828 }, { "content": "// mmap2\n\npub fn ___syscall192(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall192 (mmap2) {}\", which);\n\n let addr: i32 = varargs.get(ctx);\n\n let len: u32 = varargs.get(ctx);\n\n let prot: i32 = varargs.get(ctx);\n\n let flags: i32 = varargs.get(ctx);\n\n let fd: i32 = varargs.get(ctx);\n\n let off: i32 = varargs.get(ctx);\n\n debug!(\n\n \"=> addr: {}, len: {}, prot: {}, flags: {}, fd: {}, off: {}\",\n\n addr, len, prot, flags, fd, off\n\n );\n\n\n\n if fd == -1 {\n\n let ptr = env::call_memalign(ctx, 16384, len);\n\n if ptr == 0 {\n\n return -1;\n\n }\n\n env::call_memset(ctx, ptr, 0, len);\n\n ptr as _\n\n } else {\n\n -1\n\n }\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/mod.rs", "rank": 44, "score": 195455.11306274828 }, { "content": "/// dup3\n\npub fn ___syscall330(ctx: &mut Ctx, _which: c_int, mut varargs: VarArgs) -> pid_t {\n\n // Implementation based on description at https://linux.die.net/man/2/dup3\n\n debug!(\"emscripten::___syscall330 (dup3)\");\n\n let oldfd: c_int = varargs.get(ctx);\n\n let newfd: c_int = varargs.get(ctx);\n\n let flags: c_int = varargs.get(ctx);\n\n\n\n if oldfd == newfd {\n\n return EINVAL;\n\n }\n\n\n\n let res = unsafe { dup2(oldfd, newfd) };\n\n\n\n // Set flags on newfd (https://www.gnu.org/software/libc/manual/html_node/Descriptor-Flags.html)\n\n let mut old_flags = unsafe { fcntl(newfd, F_GETFD, 0) };\n\n\n\n if old_flags > 0 {\n\n old_flags |= flags;\n\n } else if old_flags == 0 {\n\n old_flags &= !flags;\n", "file_path": "lib/emscripten/src/syscalls/unix.rs", "rank": 45, "score": 195455.11306274828 }, { "content": "// chown\n\npub fn ___syscall212(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall212 (chown) {}\", which);\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/windows.rs", "rank": 46, "score": 195455.11306274828 }, { "content": "// pread\n\npub fn ___syscall180(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall180 (pread) {}\", which);\n\n let fd: i32 = varargs.get(ctx);\n\n let buf: u32 = varargs.get(ctx);\n\n let count: u32 = varargs.get(ctx);\n\n {\n\n let zero: u32 = varargs.get(ctx);\n\n assert_eq!(zero, 0);\n\n }\n\n let offset: i64 = varargs.get(ctx);\n\n\n\n let buf_ptr = emscripten_memory_pointer!(ctx.memory(0), buf) as _;\n\n\n\n unsafe { pread(fd, buf_ptr, count as _, offset) as _ }\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/unix.rs", "rank": 47, "score": 195455.11306274828 }, { "content": "#[allow(clippy::cast_ptr_alignment)]\n\npub fn ___syscall114(ctx: &mut Ctx, _which: c_int, mut varargs: VarArgs) -> pid_t {\n\n debug!(\"emscripten::___syscall114 (wait4)\");\n\n -1\n\n}\n\n\n\n// select\n", "file_path": "lib/emscripten/src/syscalls/windows.rs", "rank": 48, "score": 195455.11306274828 }, { "content": "#[allow(clippy::cast_ptr_alignment)]\n\npub fn ___syscall114(ctx: &mut Ctx, _which: c_int, mut varargs: VarArgs) -> pid_t {\n\n debug!(\"emscripten::___syscall114 (wait4)\");\n\n let pid: pid_t = varargs.get(ctx);\n\n let status: u32 = varargs.get(ctx);\n\n let options: c_int = varargs.get(ctx);\n\n let rusage: u32 = varargs.get(ctx);\n\n let status_addr = emscripten_memory_pointer!(ctx.memory(0), status) as *mut c_int;\n\n let rusage_addr = emscripten_memory_pointer!(ctx.memory(0), rusage) as *mut rusage;\n\n let res = unsafe { wait4(pid, status_addr, options, rusage_addr) };\n\n debug!(\n\n \"=> pid: {}, status: {:?}, options: {}, rusage: {:?} = pid: {}\",\n\n pid, status_addr, options, rusage_addr, res\n\n );\n\n res\n\n}\n\n\n\n// select\n", "file_path": "lib/emscripten/src/syscalls/unix.rs", "rank": 49, "score": 195455.11306274828 }, { "content": "#[allow(clippy::cast_ptr_alignment)]\n\npub fn ___syscall142(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall142 (newselect) {}\", which);\n\n\n\n let nfds: i32 = varargs.get(ctx);\n\n let readfds: u32 = varargs.get(ctx);\n\n let writefds: u32 = varargs.get(ctx);\n\n let exceptfds: u32 = varargs.get(ctx);\n\n let _timeout: i32 = varargs.get(ctx);\n\n\n\n assert!(nfds <= 64, \"`nfds` must be less than or equal to 64\");\n\n assert!(exceptfds == 0, \"`exceptfds` is not supporrted\");\n\n\n\n let readfds_ptr = emscripten_memory_pointer!(ctx.memory(0), readfds) as _;\n\n let writefds_ptr = emscripten_memory_pointer!(ctx.memory(0), writefds) as _;\n\n\n\n unsafe { select(nfds, readfds_ptr, writefds_ptr, 0 as _, 0 as _) }\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/unix.rs", "rank": 50, "score": 195455.11306274828 }, { "content": "/// ioctl\n\npub fn ___syscall54(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall54 (ioctl) {}\", which);\n\n -1\n\n}\n\n\n\n// socketcall\n", "file_path": "lib/emscripten/src/syscalls/windows.rs", "rank": 51, "score": 195455.11306274828 }, { "content": "/// lseek\n\npub fn ___syscall140(ctx: &mut Ctx, which: i32, mut varargs: VarArgs) -> i32 {\n\n // -> c_int\n\n debug!(\"emscripten::___syscall140 (lseek) {}\", which);\n\n let fd: i32 = varargs.get(ctx);\n\n let offset = varargs.get(ctx);\n\n let whence: i32 = varargs.get(ctx);\n\n debug!(\"=> fd: {}, offset: {}, whence = {}\", fd, offset, whence);\n\n unsafe { lseek(fd, offset, whence) as _ }\n\n}\n\n\n\n/// readv\n", "file_path": "lib/emscripten/src/syscalls/mod.rs", "rank": 52, "score": 195455.11306274828 }, { "content": "// chown\n\npub fn ___syscall212(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall212 (chown) {}\", which);\n\n\n\n let pathname: u32 = varargs.get(ctx);\n\n let owner: u32 = varargs.get(ctx);\n\n let group: u32 = varargs.get(ctx);\n\n\n\n let pathname_addr = emscripten_memory_pointer!(ctx.memory(0), pathname) as *const i8;\n\n\n\n unsafe { chown(pathname_addr, owner, group) }\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/unix.rs", "rank": 53, "score": 195455.11306274828 }, { "content": "// pread\n\npub fn ___syscall180(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall180 (pread) {}\", which);\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/windows.rs", "rank": 54, "score": 195455.11306274828 }, { "content": "// setpgid\n\npub fn ___syscall57(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall57 (setpgid) {}\", which);\n\n let pid: i32 = varargs.get(ctx);\n\n let pgid: i32 = varargs.get(ctx);\n\n unsafe { setpgid(pid, pgid) }\n\n}\n\n\n", "file_path": "lib/emscripten/src/syscalls/unix.rs", "rank": 55, "score": 195455.11306274828 }, { "content": "// pwrite\n\npub fn ___syscall181(ctx: &mut Ctx, which: c_int, mut varargs: VarArgs) -> c_int {\n\n debug!(\"emscripten::___syscall181 (pwrite) {}\", which);\n\n -1\n\n}\n\n\n\n/// wait4\n", "file_path": "lib/emscripten/src/syscalls/windows.rs", "rank": 56, "score": 195455.11306274828 }, { "content": "fn store_module_arguments(ctx: &mut Ctx, path: &str, args: Vec<&str>) -> (u32, u32) {\n\n let argc = args.len() + 1;\n\n\n\n let mut args_slice = vec![0; argc];\n\n args_slice[0] = unsafe { allocate_cstr_on_stack(ctx, path).0 };\n\n for (slot, arg) in args_slice[1..argc].iter_mut().zip(args.iter()) {\n\n *slot = unsafe { allocate_cstr_on_stack(ctx, &arg).0 };\n\n }\n\n\n\n let (argv_offset, argv_slice): (_, &mut [u32]) =\n\n unsafe { allocate_on_stack(ctx, ((argc + 1) * 4) as u32) };\n\n assert!(!argv_slice.is_empty());\n\n for (slot, arg) in argv_slice[0..argc].iter_mut().zip(args_slice.iter()) {\n\n *slot = *arg\n\n }\n\n argv_slice[argc] = 0;\n\n\n\n (argc as u32, argv_offset)\n\n}\n\n\n", "file_path": "lib/emscripten/src/lib.rs", "rank": 57, "score": 193765.0916312356 }, { "content": "pub fn _sem_wait(_ctx: &mut Ctx, _one: i32) -> i32 {\n\n debug!(\"emscripten::_sem_post\");\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 58, "score": 192859.75288708002 }, { "content": "pub fn _sem_post(_ctx: &mut Ctx, _one: i32) -> i32 {\n\n debug!(\"emscripten::_sem_post\");\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 59, "score": 192859.75288708002 }, { "content": "/// emscripten: _tvset\n\npub fn _tvset(_ctx: &mut Ctx) {\n\n debug!(\"emscripten::_tvset UNIMPLEMENTED\");\n\n}\n\n\n\n/// formats time as a C string\n\n#[allow(clippy::cast_ptr_alignment)]\n\nunsafe fn fmt_time(ctx: &mut Ctx, time: u32) -> *const c_char {\n\n let date = &*(emscripten_memory_pointer!(ctx.memory(0), time) as *mut guest_tm);\n\n\n\n let days = vec![\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n\n let months = vec![\n\n \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\",\n\n ];\n\n let year = 1900 + date.tm_year;\n\n\n\n let time_str = format!(\n\n // NOTE: TODO: Hack! The 14 accompanying chars are needed for some reason\n\n \"{} {} {:2} {:02}:{:02}:{:02} {:4}\\n\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\",\n\n days[date.tm_wday as usize],\n\n months[date.tm_mon as usize],\n\n date.tm_mday,\n\n date.tm_hour,\n\n date.tm_min,\n\n date.tm_sec,\n\n year\n\n );\n\n\n\n time_str[0..26].as_ptr() as _\n\n}\n\n\n", "file_path": "lib/emscripten/src/time.rs", "rank": 60, "score": 184798.90065678017 }, { "content": "pub fn _kill(_ctx: &mut Ctx, _one: i32, _two: i32) -> i32 {\n\n debug!(\"emscripten::_kill\");\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 61, "score": 182484.2227274606 }, { "content": "pub fn _utimes(_ctx: &mut Ctx, _one: i32, _two: i32) -> i32 {\n\n debug!(\"emscripten::_utimes\");\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 62, "score": 182484.2227274606 }, { "content": "pub fn _setgroups(_ctx: &mut Ctx, _one: i32, _two: i32) -> i32 {\n\n debug!(\"emscripten::_setgroups\");\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 63, "score": 182484.2227274606 }, { "content": "pub fn _popen(_ctx: &mut Ctx, _one: i32, _two: i32) -> c_int {\n\n debug!(\"emscripten::_popen\");\n\n // TODO: May need to change this Em impl to a working version\n\n eprintln!(\"Missing function: popen\");\n\n unsafe {\n\n abort();\n\n }\n\n}\n", "file_path": "lib/emscripten/src/process.rs", "rank": 64, "score": 182484.2227274606 }, { "content": "/// emscripten: ___map_file\n\npub fn ___map_file(_ctx: &mut Ctx, _one: u32, _two: u32) -> c_int {\n\n debug!(\"emscripten::___map_file\");\n\n // NOTE: TODO: Em returns -1 here as well. May need to implement properly\n\n -1\n\n}\n", "file_path": "lib/emscripten/src/memory.rs", "rank": 65, "score": 179148.63678961017 }, { "content": "/// emscripten: dlerror() -> *mut c_char\n\npub fn _dlerror(_ctx: &mut Ctx) -> i32 {\n\n debug!(\"emscripten::_dlerror\");\n\n -1\n\n}\n", "file_path": "lib/emscripten/src/linking.rs", "rank": 66, "score": 175661.34491955896 }, { "content": "/// emscripten: _clock\n\npub fn _clock(_ctx: &mut Ctx) -> c_int {\n\n debug!(\"emscripten::_clock\");\n\n 0 // TODO: unimplemented\n\n}\n\n\n", "file_path": "lib/emscripten/src/time.rs", "rank": 67, "score": 175656.5413819867 }, { "content": "#[test]\n\n#[ignore]\n\nfn test_test_em_js() {\n\n assert_emscripten_output!(\n\n \"../../emtests/test_em_js.wasm\",\n\n \"test_em_js\",\n\n vec![],\n\n \"../../emtests/test_em_js.out\"\n\n );\n\n}\n", "file_path": "lib/emscripten/tests/emtests/test_em_js.rs", "rank": 68, "score": 175540.02587008447 }, { "content": "pub fn _emscripten_random(_ctx: &mut Ctx) -> f64 {\n\n debug!(\"emscripten::_emscripten_random\");\n\n -1.0\n\n}\n\n\n", "file_path": "lib/emscripten/src/math.rs", "rank": 69, "score": 172511.96012367163 }, { "content": "/// emscripten: enlargeMemory\n\npub fn enlarge_memory(_ctx: &mut Ctx) -> u32 {\n\n debug!(\"emscripten::enlarge_memory\");\n\n // instance.memories[0].grow(100);\n\n // TODO: Fix implementation\n\n 0\n\n}\n\n\n", "file_path": "lib/emscripten/src/memory.rs", "rank": 70, "score": 172511.96012367163 }, { "content": "pub fn _getpagesize(_ctx: &mut Ctx) -> u32 {\n\n debug!(\"emscripten::_getpagesize\");\n\n 16384\n\n}\n\n\n", "file_path": "lib/emscripten/src/env/mod.rs", "rank": 71, "score": 172511.96012367163 }, { "content": "pub fn nullfunc_i(ctx: &mut Ctx, x: u32) {\n\n debug!(\"emscripten::nullfunc_i {}\", x);\n\n abort_with_message(ctx, \"Invalid function pointer called with signature 'i'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)\");\n\n}\n\n\n", "file_path": "lib/emscripten/src/nullfunc.rs", "rank": 72, "score": 170751.81331555673 }, { "content": "// NOTE: Not implemented by Emscripten\n\npub fn ___lock(_ctx: &mut Ctx, what: c_int) {\n\n debug!(\"emscripten::___lock {}\", what);\n\n}\n\n\n", "file_path": "lib/emscripten/src/lock.rs", "rank": 73, "score": 170751.81331555673 }, { "content": "// NOTE: Not implemented by Emscripten\n\npub fn ___unlock(_ctx: &mut Ctx, what: c_int) {\n\n debug!(\"emscripten::___unlock {}\", what);\n\n}\n\n\n", "file_path": "lib/emscripten/src/lock.rs", "rank": 74, "score": 170751.81331555673 }, { "content": "pub fn nullfunc_v(ctx: &mut Ctx, x: u32) {\n\n debug!(\"emscripten::nullfunc_v {}\", x);\n\n abort_with_message(ctx, \"Invalid function pointer called with signature 'v'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)\");\n\n}\n\n\n", "file_path": "lib/emscripten/src/nullfunc.rs", "rank": 75, "score": 170751.81331555673 }, { "content": "pub fn _waitpid(_ctx: &mut Ctx, _one: i32, _two: i32, _three: i32) -> i32 {\n\n debug!(\"emscripten::_waitpid\");\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 76, "score": 170582.0096667043 }, { "content": "pub fn _execve(_ctx: &mut Ctx, _one: i32, _two: i32, _three: i32) -> i32 {\n\n debug!(\"emscripten::_execve\");\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 77, "score": 170582.0096667043 }, { "content": "pub fn _setitimer(_ctx: &mut Ctx, _one: i32, _two: i32, _three: i32) -> i32 {\n\n debug!(\"emscripten::_setitimer\");\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 78, "score": 170582.0096667043 }, { "content": "/// emscripten: getTotalMemory\n\npub fn get_total_memory(_ctx: &mut Ctx) -> u32 {\n\n debug!(\"emscripten::get_total_memory\");\n\n // instance.memories[0].current_pages()\n\n // TODO: Fix implementation\n\n 16_777_216\n\n}\n\n\n", "file_path": "lib/emscripten/src/memory.rs", "rank": 79, "score": 169537.91251798873 }, { "content": "/// emscripten: abortOnCannotGrowMemory\n\npub fn abort_on_cannot_grow_memory(ctx: &mut Ctx) -> u32 {\n\n debug!(\"emscripten::abort_on_cannot_grow_memory\");\n\n abort_with_message(ctx, \"Cannot enlarge memory arrays!\");\n\n 0\n\n}\n\n\n", "file_path": "lib/emscripten/src/memory.rs", "rank": 80, "score": 169537.91251798873 }, { "content": "pub fn generate_imports() -> ImportObject {\n\n let wasm_binary = wat2wasm(IMPORT_MODULE.as_bytes()).expect(\"WAST not valid or malformed\");\n\n let module = wasmer_runtime_core::compile_with(&wasm_binary[..], &CraneliftCompiler::new())\n\n .expect(\"WASM can't be compiled\");\n\n let instance = module\n\n .instantiate(&ImportObject::new())\n\n .expect(\"WASM can't be instantiated\");\n\n let mut imports = ImportObject::new();\n\n imports.register(\"spectest\", instance);\n\n imports\n\n}\n", "file_path": "lib/spectests/examples/test.rs", "rank": 81, "score": 168220.31976294526 }, { "content": "pub fn nullfunc_viii(ctx: &mut Ctx, x: u32) {\n\n debug!(\"emscripten::nullfunc_viii {}\", x);\n\n abort_with_message(ctx, \"Invalid function pointer called with signature 'viii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)\");\n\n}\n\n\n", "file_path": "lib/emscripten/src/nullfunc.rs", "rank": 82, "score": 167607.2320572417 }, { "content": "pub fn nullfunc_iiiii(ctx: &mut Ctx, x: u32) {\n\n debug!(\"emscripten::nullfunc_iiiii {}\", x);\n\n abort_with_message(ctx, \"Invalid function pointer called with signature 'iiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)\");\n\n}\n\n\n", "file_path": "lib/emscripten/src/nullfunc.rs", "rank": 83, "score": 167607.2320572417 }, { "content": "pub fn nullfunc_iiiiii(ctx: &mut Ctx, x: u32) {\n\n debug!(\"emscripten::nullfunc_iiiiii {}\", x);\n\n abort_with_message(ctx, \"Invalid function pointer called with signature 'iiiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)\");\n\n}\n\n\n", "file_path": "lib/emscripten/src/nullfunc.rs", "rank": 84, "score": 167607.2320572417 }, { "content": "pub fn nullfunc_iii(ctx: &mut Ctx, x: u32) {\n\n debug!(\"emscripten::nullfunc_iii {}\", x);\n\n abort_with_message(ctx, \"Invalid function pointer called with signature 'iii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)\");\n\n}\n\n\n", "file_path": "lib/emscripten/src/nullfunc.rs", "rank": 85, "score": 167607.2320572417 }, { "content": "pub fn nullfunc_vii(ctx: &mut Ctx, x: u32) {\n\n debug!(\"emscripten::nullfunc_vii {}\", x);\n\n abort_with_message(ctx, \"Invalid function pointer called with signature 'vii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)\");\n\n}\n\n\n", "file_path": "lib/emscripten/src/nullfunc.rs", "rank": 86, "score": 167607.2320572417 }, { "content": "pub fn ___seterrno(_ctx: &mut Ctx, value: i32) {\n\n debug!(\"emscripten::___seterrno {}\", value);\n\n // TODO: Incomplete impl\n\n eprintln!(\"failed to set errno!\");\n\n // value\n\n}\n\n\n\n// pub enum ErrnoCodes {\n\n// EPERM = 1,\n\n// ENOENT = 2,\n\n// ESRCH = 3,\n\n// EINTR = 4,\n\n// EIO = 5,\n\n// ENXIO = 6,\n\n// E2BIG = 7,\n\n// ENOEXEC = 8,\n\n// EBADF = 9,\n\n// ECHILD = 10,\n\n// EAGAIN = 11,\n\n// EWOULDBLOCK = 11,\n", "file_path": "lib/emscripten/src/errno.rs", "rank": 87, "score": 167607.2320572417 }, { "content": "pub fn nullfunc_vi(ctx: &mut Ctx, x: u32) {\n\n debug!(\"emscripten::nullfunc_vi {}\", x);\n\n abort_with_message(ctx, \"Invalid function pointer called with signature 'vi'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)\");\n\n}\n\n\n", "file_path": "lib/emscripten/src/nullfunc.rs", "rank": 88, "score": 167607.2320572417 }, { "content": "pub fn nullfunc_iiii(ctx: &mut Ctx, x: u32) {\n\n debug!(\"emscripten::nullfunc_iiii {}\", x);\n\n abort_with_message(ctx, \"Invalid function pointer called with signature 'iiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)\");\n\n}\n\n\n", "file_path": "lib/emscripten/src/nullfunc.rs", "rank": 89, "score": 167607.2320572417 }, { "content": "pub fn nullfunc_viiii(ctx: &mut Ctx, x: u32) {\n\n debug!(\"emscripten::nullfunc_viiii {}\", x);\n\n abort_with_message(ctx, \"Invalid function pointer called with signature 'viiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)\");\n\n}\n\n\n", "file_path": "lib/emscripten/src/nullfunc.rs", "rank": 90, "score": 167607.2320572417 }, { "content": "pub fn nullfunc_ii(ctx: &mut Ctx, x: u32) {\n\n debug!(\"emscripten::nullfunc_ii {}\", x);\n\n abort_with_message(ctx, \"Invalid function pointer called with signature 'ii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)\");\n\n}\n\n\n", "file_path": "lib/emscripten/src/nullfunc.rs", "rank": 91, "score": 167607.2320572417 }, { "content": "pub fn nullfunc_viiiii(ctx: &mut Ctx, _x: u32) {\n\n debug!(\"emscripten::nullfunc_viiiii\");\n\n abort_with_message(ctx, \"Invalid function pointer called with signature 'viiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)\");\n\n}\n\n\n", "file_path": "lib/emscripten/src/nullfunc.rs", "rank": 92, "score": 167607.2320572417 }, { "content": "pub fn nullfunc_viiiiii(ctx: &mut Ctx, _x: u32) {\n\n debug!(\"emscripten::nullfunc_viiiiii\");\n\n abort_with_message(ctx, \"Invalid function pointer called with signature 'viiiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)\");\n\n}\n", "file_path": "lib/emscripten/src/nullfunc.rs", "rank": 93, "score": 167607.2320572417 }, { "content": "pub fn _sem_init(_ctx: &mut Ctx, _one: i32, _two: i32, _three: i32) -> i32 {\n\n debug!(\"emscripten::_sem_init\");\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/process.rs", "rank": 94, "score": 167503.69634353975 }, { "content": "/// putchar\n\npub fn putchar(ctx: &mut Ctx, chr: i32) {\n\n unsafe { libc::putchar(chr) };\n\n}\n\n\n", "file_path": "lib/emscripten/src/io/unix.rs", "rank": 95, "score": 164633.1844515588 }, { "content": "/// putchar\n\npub fn putchar(ctx: &mut Ctx, chr: i32) {\n\n unsafe { libc::putchar(chr) };\n\n}\n\n\n", "file_path": "lib/emscripten/src/io/windows.rs", "rank": 96, "score": 164633.1844515588 }, { "content": "pub fn generate_emscripten_env(globals: &mut EmscriptenGlobals) -> ImportObject {\n\n imports! {\n\n \"env\" => {\n\n \"memory\" => Export::Memory(globals.memory.clone()),\n\n \"table\" => Export::Table(globals.table.clone()),\n\n\n\n // Globals\n\n \"STACKTOP\" => Global::new(Value::I32(globals.data.stacktop as i32)),\n\n \"STACK_MAX\" => Global::new(Value::I32(globals.data.stack_max as i32)),\n\n \"DYNAMICTOP_PTR\" => Global::new(Value::I32(globals.data.dynamictop_ptr as i32)),\n\n \"tableBase\" => Global::new(Value::I32(globals.data.table_base as i32)),\n\n \"__table_base\" => Global::new(Value::I32(globals.data.table_base as i32)),\n\n \"ABORT\" => Global::new(Value::I32(globals.data.abort as i32)),\n\n \"memoryBase\" => Global::new(Value::I32(globals.data.memory_base as i32)),\n\n \"__memory_base\" => Global::new(Value::I32(globals.data.memory_base as i32)),\n\n \"tempDoublePtr\" => Global::new(Value::I32(globals.data.temp_double_ptr as i32)),\n\n\n\n // IO\n\n \"printf\" => func!(crate::io::printf),\n\n \"putchar\" => func!(crate::io::putchar),\n", "file_path": "lib/emscripten/src/lib.rs", "rank": 97, "score": 164048.78347967245 }, { "content": "/// emscripten: dlclose(handle: *mut c_void) -> c_int\n\npub fn _dlclose(_ctx: &mut Ctx, _filename: u32) -> i32 {\n\n debug!(\"emscripten::_dlclose\");\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/linking.rs", "rank": 98, "score": 160443.33756793788 }, { "content": "pub fn _mktime(_ctx: &mut Ctx, _one: i32) -> i32 {\n\n debug!(\"emscripten::_mktime\");\n\n -1\n\n}\n\n\n", "file_path": "lib/emscripten/src/time.rs", "rank": 99, "score": 160438.75518558087 } ]
Rust
src/cpu/addressing_mode.rs
Erj4/nes-emulator
13f5e1bac138802f1a6bb383227b9d4f92b092ea
use crate::{cpu, memory}; #[derive(Debug)] pub enum ResolvableAddress { ZeroPage(cpu::Int), XIndexedZeroPage(cpu::Int), YIndexedZeroPage(cpu::Int), Absolute(memory::Address), XIndexedAbsolute(memory::Address), YIndexedAbsolute(memory::Address), Relative(cpu::Int), Indirect(memory::Address), XIndexedIndirect(cpu::Int), IndirectYIndexed(cpu::Int), } trait SteppableWithCPU { type Output; fn step(resolvable: ResolvableAddress, cpu: &cpu::Cpu) -> Resolvable<Self::Output>; fn resolve(resolvable: ResolvableAddress, cpu: &cpu::Cpu) -> Self::Output { let mut resolvable = resolvable; loop { match Self::step(resolvable, cpu) { Resolvable::Resolved(resolved) => break resolved, Resolvable::Resolvable(unresolved) => resolvable = unresolved, } } } } #[derive(Debug)] pub enum Resolvable<V> { Resolved(V), Resolvable(ResolvableAddress), } impl SteppableWithCPU for Resolvable<cpu::Int> { type Output = cpu::Int; fn step(resolvable: ResolvableAddress, cpu: &cpu::Cpu) -> Resolvable<Self::Output> { ResolvableAddress::step(resolvable, cpu) } } impl SteppableWithCPU for Resolvable<memory::Address> { type Output = memory::Address; fn step(resolvable: ResolvableAddress, cpu: &cpu::Cpu) -> Resolvable<Self::Output> { ResolvableAddress::step_u16(resolvable, cpu) } } impl ResolvableAddress { fn step_unresolved(self, cpu: &cpu::Cpu) -> ResolvableAddress { use ResolvableAddress::*; match self { XIndexedZeroPage(address) => { let address = address + cpu.register.index_x; ZeroPage(address) } YIndexedZeroPage(address) => { let address = address + cpu.register.index_y; ZeroPage(address) } XIndexedAbsolute(address) => { let address = address + memory::Address::from(cpu.register.index_x); Absolute(address) } YIndexedAbsolute(address) => { let address = address + memory::Address::from(cpu.register.index_y); Absolute(address) } Indirect(address) => { let absolute_address = cpu.memory.read_u16(address); Absolute(absolute_address) } XIndexedIndirect(address) => { let address = memory::Address::from(address + cpu.register.index_x); Indirect(address) } IndirectYIndexed(address) => { let address = cpu.memory.read_u16(memory::Address::from(address)); YIndexedAbsolute(address) } _ => unreachable!( "Addressing mode {:#?} is not implemented as unresolved", self ), } } } impl ResolvableAddress { #[must_use] pub fn step(resolvable: ResolvableAddress, cpu: &cpu::Cpu) -> Resolvable<cpu::Int> { use ResolvableAddress::*; use self::Resolvable::*; match resolvable { ZeroPage(address) => Resolved(cpu.memory[memory::Address::from(address)]), Absolute(address) => Resolved(cpu.memory[address]), _ => Resolvable(Self::step_unresolved(resolvable, cpu)), } } #[must_use] pub fn step_u16(resolvable: ResolvableAddress, cpu: &cpu::Cpu) -> Resolvable<memory::Address> { use ResolvableAddress::*; use self::Resolvable::*; match resolvable { ZeroPage(address) => Resolved(cpu.memory.read_u16(memory::Address::from(address))), Absolute(address) => Resolved(cpu.memory.read_u16(address)), _ => Resolvable(Self::step_unresolved(resolvable, cpu)), } } } impl Resolvable<cpu::Int> { pub fn immediate(cpu: &mut cpu::Cpu) -> Self { Self::Resolved(cpu.next_int()) } } impl Resolvable<u8> { pub fn accumulator(cpu: &mut cpu::Cpu) -> Self { Self::Resolved(cpu.register.accumulator) } } impl<T> Resolvable<T> { pub fn zero_page(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::ZeroPage(cpu.next_int())) } pub fn x_indexed_zero_page(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::XIndexedZeroPage(cpu.next_int())) } pub fn y_indexed_zero_page(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::YIndexedZeroPage(cpu.next_int())) } pub fn absolute(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::Absolute(cpu.next_address())) } pub fn x_indexed_absolute(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::XIndexedAbsolute(cpu.next_address())) } pub fn y_indexed_absolute(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::YIndexedAbsolute(cpu.next_address())) } pub fn relative(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::Relative(cpu.next_int())) } pub fn indirect(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::Indirect(cpu.next_address())) } pub fn x_indexed_indirect(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::XIndexedIndirect(cpu.next_int())) } pub fn indirect_y_indexed(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::IndirectYIndexed(cpu.next_int())) } }
use crate::{cpu, memory}; #[derive(Debug)] pub enum ResolvableAddress { ZeroPage(cpu::Int), XIndexedZeroPage(cpu::Int), YIndexedZeroPage(cpu::Int), Absolute(memory::Address), XIndexedAbsolute(memory::Address), YIndexedAbsolute(memory::Address), Relative(cpu::Int), Indirect(memory::Address), XIndexedIndirect(cpu::Int), IndirectYIndexed(cpu::Int), } trait SteppableWithCPU { type Output; fn step(resolvable: ResolvableAddress, cpu: &cpu::Cpu) -> Resolvable<Self::Output>; fn resolve(resolvable: ResolvableAddress, cpu: &cpu::Cpu) -> Self::Output { let mut resolvable = resolvable; loop {
} } } #[derive(Debug)] pub enum Resolvable<V> { Resolved(V), Resolvable(ResolvableAddress), } impl SteppableWithCPU for Resolvable<cpu::Int> { type Output = cpu::Int; fn step(resolvable: ResolvableAddress, cpu: &cpu::Cpu) -> Resolvable<Self::Output> { ResolvableAddress::step(resolvable, cpu) } } impl SteppableWithCPU for Resolvable<memory::Address> { type Output = memory::Address; fn step(resolvable: ResolvableAddress, cpu: &cpu::Cpu) -> Resolvable<Self::Output> { ResolvableAddress::step_u16(resolvable, cpu) } } impl ResolvableAddress { fn step_unresolved(self, cpu: &cpu::Cpu) -> ResolvableAddress { use ResolvableAddress::*; match self { XIndexedZeroPage(address) => { let address = address + cpu.register.index_x; ZeroPage(address) } YIndexedZeroPage(address) => { let address = address + cpu.register.index_y; ZeroPage(address) } XIndexedAbsolute(address) => { let address = address + memory::Address::from(cpu.register.index_x); Absolute(address) } YIndexedAbsolute(address) => { let address = address + memory::Address::from(cpu.register.index_y); Absolute(address) } Indirect(address) => { let absolute_address = cpu.memory.read_u16(address); Absolute(absolute_address) } XIndexedIndirect(address) => { let address = memory::Address::from(address + cpu.register.index_x); Indirect(address) } IndirectYIndexed(address) => { let address = cpu.memory.read_u16(memory::Address::from(address)); YIndexedAbsolute(address) } _ => unreachable!( "Addressing mode {:#?} is not implemented as unresolved", self ), } } } impl ResolvableAddress { #[must_use] pub fn step(resolvable: ResolvableAddress, cpu: &cpu::Cpu) -> Resolvable<cpu::Int> { use ResolvableAddress::*; use self::Resolvable::*; match resolvable { ZeroPage(address) => Resolved(cpu.memory[memory::Address::from(address)]), Absolute(address) => Resolved(cpu.memory[address]), _ => Resolvable(Self::step_unresolved(resolvable, cpu)), } } #[must_use] pub fn step_u16(resolvable: ResolvableAddress, cpu: &cpu::Cpu) -> Resolvable<memory::Address> { use ResolvableAddress::*; use self::Resolvable::*; match resolvable { ZeroPage(address) => Resolved(cpu.memory.read_u16(memory::Address::from(address))), Absolute(address) => Resolved(cpu.memory.read_u16(address)), _ => Resolvable(Self::step_unresolved(resolvable, cpu)), } } } impl Resolvable<cpu::Int> { pub fn immediate(cpu: &mut cpu::Cpu) -> Self { Self::Resolved(cpu.next_int()) } } impl Resolvable<u8> { pub fn accumulator(cpu: &mut cpu::Cpu) -> Self { Self::Resolved(cpu.register.accumulator) } } impl<T> Resolvable<T> { pub fn zero_page(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::ZeroPage(cpu.next_int())) } pub fn x_indexed_zero_page(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::XIndexedZeroPage(cpu.next_int())) } pub fn y_indexed_zero_page(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::YIndexedZeroPage(cpu.next_int())) } pub fn absolute(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::Absolute(cpu.next_address())) } pub fn x_indexed_absolute(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::XIndexedAbsolute(cpu.next_address())) } pub fn y_indexed_absolute(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::YIndexedAbsolute(cpu.next_address())) } pub fn relative(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::Relative(cpu.next_int())) } pub fn indirect(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::Indirect(cpu.next_address())) } pub fn x_indexed_indirect(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::XIndexedIndirect(cpu.next_int())) } pub fn indirect_y_indexed(cpu: &mut cpu::Cpu) -> Self { Self::Resolvable(ResolvableAddress::IndirectYIndexed(cpu.next_int())) } }
match Self::step(resolvable, cpu) { Resolvable::Resolved(resolved) => break resolved, Resolvable::Resolvable(unresolved) => resolvable = unresolved, }
if_condition
[ { "content": "#[derive(Error, Debug)]\n\nenum AddressExprError {\n\n #[error(\n\n \"address {address:#X?} is outside range (expected {:#X?} <= address <= {:#X?})\",\n\n memory::Address::MIN,\n\n memory::Address::MAX\n\n )]\n\n AddressOutOfRange {\n\n address: evalexpr::IntType,\n\n source: std::num::TryFromIntError,\n\n },\n\n #[error(transparent)]\n\n AddressExpressionError(#[from] evalexpr::EvalexprError),\n\n}\n\n\n", "file_path": "src/cli.rs", "rank": 1, "score": 26609.93440595059 }, { "content": "fn eval_address_expression(\n\n expression: &str,\n\n) -> std::result::Result<memory::Address, AddressExprError> {\n\n use AddressExprError::*;\n\n let context: evalexpr::HashMapContext = evalexpr::context_map! {\n\n \"ram\" => evalexpr::IntType::from(memory::constant::RAM_START),\n\n \"ram_size\" => evalexpr::IntType::from(memory::constant::RAM_SIZE),\n\n \"rom\" => evalexpr::IntType::from(memory::constant::PROGRAM_ROM_START),\n\n \"rom_size\" => evalexpr::IntType::from(memory::constant::PROGRAM_ROM_SIZE)\n\n }?;\n\n let result = evalexpr::eval_int_with_context(expression, &context)?;\n\n memory::Address::try_from(result).map_err(|source| AddressOutOfRange {\n\n address: result,\n\n source,\n\n })\n\n}\n", "file_path": "src/cli.rs", "rank": 2, "score": 25310.13621765376 }, { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n let args = cli::Cli::from_args();\n\n\n\n let log_builder = &mut Builder::new();\n\n log_builder.filter_level(LevelFilter::Warn);\n\n\n\n if let Some(filter) = args.log {\n\n log_builder.filter(None, filter);\n\n }\n\n\n\n log_builder.init();\n\n\n\n let mut cpu: cpu::Cpu = cpu::Cpu::default();\n\n\n\n if let Some(path) = args.file {\n\n let mut file = File::open(path)?;\n\n cpu.load_from(&mut file)?;\n\n };\n\n match args.start_address {\n\n None => cpu.start(),\n\n Some(address) => {\n\n info!(\"starting from address {:#X}\", address);\n\n cpu.start_from(address)\n\n }\n\n };\n\n info!(\"exiting successfully\");\n\n\n\n Ok(())\n\n}\n", "file_path": "src/main.rs", "rank": 3, "score": 20491.590417408665 }, { "content": "impl Index<Address> for NES {\n\n type Output = cpu::Int;\n\n\n\n fn index(&self, address: Address) -> &Self::Output {\n\n use crate::memory::Location::*;\n\n\n\n let location = Self::resolve_address(address);\n\n match location {\n\n Ram(address) => &self.ram[address as usize],\n\n ProgramRom(address) => &self.program_rom[address as usize],\n\n }\n\n }\n\n}\n\n\n\nimpl IndexMut<Address> for NES {\n\n fn index_mut(&mut self, address: Address) -> &mut Self::Output {\n\n use crate::memory::Location::*;\n\n\n\n let location = Self::resolve_address(address);\n\n match location {\n\n Ram(address) => &mut self.ram[address as usize],\n\n ProgramRom(address) => &mut self.program_rom[address as usize],\n\n }\n\n }\n\n}\n", "file_path": "src/memory/mod.rs", "rank": 4, "score": 20029.691002262432 }, { "content": "use std::{\n\n fmt,\n\n ops::{Index, IndexMut},\n\n};\n\n\n\nuse crate::cpu;\n\n\n\npub mod constant;\n\n\n\n#[derive(Debug)]\n\npub enum Location {\n\n ProgramRom(Address),\n\n Ram(Address),\n\n}\n\n\n\npub type Address = u16;\n\n\n\npub struct NES {\n\n pub program_rom: [cpu::Int; constant::PROGRAM_ROM_SIZE as usize],\n\n pub ram: [cpu::Int; constant::RAM_SIZE as usize],\n", "file_path": "src/memory/mod.rs", "rank": 5, "score": 20027.31318491572 }, { "content": "\n\n match address {\n\n RAM_START .. RAM_END => Ram(address - RAM_START),\n\n constant::PROGRAM_ROM_START .. => ProgramRom(address - PROGRAM_ROM_START),\n\n _ => todo!(\"Memory location {:#4X}\", address),\n\n }\n\n }\n\n\n\n #[must_use]\n\n pub fn read(&self, addr: u16) -> cpu::Int {\n\n self[addr]\n\n }\n\n\n\n pub fn write(&mut self, addr: u16, data: cpu::Int) {\n\n self[addr] = data;\n\n }\n\n\n\n #[must_use]\n\n pub fn read_u16(&self, addr: u16) -> u16 {\n\n u16::from_le_bytes([self[addr], self[addr + 1]])\n", "file_path": "src/memory/mod.rs", "rank": 6, "score": 20027.029655709197 }, { "content": "}\n\n\n\nimpl fmt::Debug for NES {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.debug_struct(\"Cpu6502\")\n\n .field(\"program_rom\", &format_args!(\"{:X?}\", &self.program_rom))\n\n .field(\"ram\", &format_args!(\"{:X?}\", &self.ram))\n\n .finish()\n\n }\n\n}\n\n\n\nimpl NES {\n\n #[must_use]\n\n /// # Panics\n\n /// This function will panic if it receives an address that is outside of the known memory region ranges\n\n pub fn resolve_address(address: Address) -> Location {\n\n use crate::memory::{\n\n constant::{PROGRAM_ROM_START, RAM_END, RAM_START},\n\n Location::*,\n\n };\n", "file_path": "src/memory/mod.rs", "rank": 7, "score": 20026.149527437796 }, { "content": "use crate::memory::Address;\n\n\n\n// _END locations are EXCLUSIVE\n\n\n\npub const RAM_START: Address = 0x0000;\n\npub const RAM_SIZE: Address = 0x0800;\n\npub const RAM_END: Address = RAM_START + RAM_SIZE;\n\npub const PROGRAM_ROM_START: Address = 0x8000;\n\npub const PROGRAM_ROM_SIZE: Address = 0x8000; // ROM runs to end of memory (0xFFFF inclusive)\n\n\n\n/// Contains address of non-maskable interrupt handler\n\n/// Value is u16, so should be read with [`NES::read_u16`]\n\npub const NON_MASKABLE_INTERRUPT: Address = 0xFFFA;\n\n\n\n/// Contains address to set program counter to on reset interrupt or load\n\n/// This is a u16 value, so should be read with [`NES::read_u16`]\n\npub const PROGRAM_COUNTER_RESET: Address = 0xFFFC;\n\n\n\n/// Contains address of (maskable) interrupt handler, also triggered by BRK instruction\n\n/// Value is u16, so should be read with [`NES::read_u16`]\n\npub const INTERRUPT: Address = 0xFFFE;\n", "file_path": "src/memory/constant.rs", "rank": 8, "score": 20023.94121481733 }, { "content": " }\n\n\n\n pub fn write_u16(&mut self, addr: u16, data: u16) {\n\n let [fst, snd] = u16::to_le_bytes(data);\n\n self[addr] = fst;\n\n self[addr] = snd;\n\n }\n\n}\n\n\n\nimpl Default for NES {\n\n #[inline]\n\n fn default() -> Self {\n\n #[allow(clippy::uninit_assumed_init)] // No guarantees that emulator memory is initialised\n\n Self {\n\n program_rom: [0; constant::PROGRAM_ROM_SIZE as usize],\n\n ram: [0; constant::RAM_SIZE as usize],\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/memory/mod.rs", "rank": 9, "score": 20023.38884409994 }, { "content": "use log::debug;\n\n\n\nuse self::addressing_mode::Resolvable;\n\nuse crate::cpu::{addressing_mode, memory, Cpu, Int};\n\n\n\n#[derive(Debug)]\n\npub enum Operation {\n\n /// Add with carry\n\n ADC(Resolvable<Int>),\n\n /// Bitwise AND with accumulator\n\n AND(Resolvable<Int>),\n\n /// Arithmetic shift accumulator left\n\n ASLAcc,\n\n /// Arithmetic shift left\n\n ASL(Resolvable<memory::Address>),\n\n /// Set flags based on bits\n\n BIT(Resolvable<Int>),\n\n /// Branch if plus\n\n ///\n\n /// Branch if negative flag clear\n", "file_path": "src/cpu/operation.rs", "rank": 10, "score": 14088.470764894433 }, { "content": "use crate::{cpu, memory};\n\n\n\n#[derive(Debug, Default)]\n\npub struct NES {\n\n pub program_counter: memory::Address,\n\n pub stack_pointer: cpu::Int,\n\n pub accumulator: cpu::Int,\n\n pub index_x: cpu::Int,\n\n pub index_y: cpu::Int,\n\n pub status: StatusRegister,\n\n}\n\n\n\n#[derive(Debug, Default)]\n\n/// CPU status flags\n\n///\n\n/// WARNING: some flags (especially N & Z) may be affected by commands in ways that do not follow their defined purpose.\n\n///\n\n#[must_use]\n\npub struct StatusRegister {\n\n pub result_status: ResultStatus,\n", "file_path": "src/cpu/registers.rs", "rank": 11, "score": 14087.509924834034 }, { "content": "#![allow(clippy::identity_op)] // Ignored due to clippy bug\n\n\n\nuse std::io::Read;\n\n\n\nuse log::info;\n\n\n\npub mod addressing_mode;\n\npub mod operation;\n\npub mod registers;\n\n\n\nuse crate::memory;\n\n\n\npub type Cpu = NES;\n\npub type Int = u8;\n\n\n\n#[derive(Debug, Default)]\n\npub struct NES {\n\n pub register: registers::NES,\n\n pub memory: memory::NES,\n\n stop: bool,\n", "file_path": "src/cpu/mod.rs", "rank": 12, "score": 14087.420205594422 }, { "content": " STX(Resolvable<memory::Address>),\n\n // Store accumulator\n\n STY(Resolvable<memory::Address>),\n\n}\n\n\n\nimpl Operation {\n\n #[allow(clippy::too_many_lines)]\n\n fn new(opcode: Int, cpu: &mut Cpu) -> Operation {\n\n use self::{addressing_mode::Resolvable as Addr, Operation::*};\n\n match opcode {\n\n // ADC\n\n 0x69 => ADC(Addr::immediate(cpu)),\n\n 0x65 => ADC(Addr::zero_page(cpu)),\n\n 0x75 => ADC(Addr::x_indexed_zero_page(cpu)),\n\n 0x6D => ADC(Addr::absolute(cpu)),\n\n 0x7D => ADC(Addr::x_indexed_absolute(cpu)),\n\n 0x79 => ADC(Addr::y_indexed_absolute(cpu)),\n\n 0x61 => ADC(Addr::x_indexed_indirect(cpu)),\n\n 0x71 => ADC(Addr::indirect_y_indexed(cpu)),\n\n // AND\n", "file_path": "src/cpu/operation.rs", "rank": 13, "score": 14087.042924065758 }, { "content": "\n\n pub fn resume(&mut self) {\n\n loop {\n\n let operation = self.next_operation();\n\n self.execute(&operation);\n\n if self.stop {\n\n break;\n\n }\n\n info!(\"execution has stopped\")\n\n }\n\n }\n\n\n\n fn next_int(&mut self) -> Int {\n\n let result = self.memory.read(self.register.program_counter);\n\n self.register.program_counter += 1;\n\n result\n\n }\n\n\n\n fn next_address(&mut self) -> memory::Address {\n\n let result = self.memory.read_u16(self.register.program_counter);\n", "file_path": "src/cpu/mod.rs", "rank": 14, "score": 14086.949464303587 }, { "content": " self.register.program_counter += 2;\n\n result\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn load_from() {\n\n let mut cpu = Cpu::default();\n\n\n\n let size = crate::memory::constant::PROGRAM_ROM_SIZE as usize;\n\n let values = vec![1; size];\n\n\n\n assert_eq!(size, cpu.load_from(&mut values.as_slice()).unwrap());\n\n }\n\n #[test]\n\n fn load_from_small() {\n", "file_path": "src/cpu/mod.rs", "rank": 15, "score": 14086.33678521262 }, { "content": " .write_u16(memory::constant::PROGRAM_COUNTER_RESET, 0x8000);\n\n }\n\n\n\n pub fn reset(&mut self) {\n\n self.register = registers::NES::default();\n\n self.register.program_counter = self\n\n .memory\n\n .read_u16(memory::constant::PROGRAM_COUNTER_RESET);\n\n }\n\n\n\n pub fn start(&mut self) {\n\n self.reset();\n\n self.resume()\n\n }\n\n\n\n pub fn start_from(&mut self, instructions: memory::Address) {\n\n self.reset();\n\n self.register.program_counter = instructions;\n\n self.resume()\n\n }\n", "file_path": "src/cpu/mod.rs", "rank": 16, "score": 14086.280436845607 }, { "content": " pub fn execute(self: &mut Cpu, operation: &Operation) {\n\n use self::Operation::*;\n\n debug!(\n\n \"executing operation {:?} at {:#x}\",\n\n operation, self.register.program_counter\n\n );\n\n match operation {\n\n BRK => self.stop = true,\n\n _ => unimplemented!(\"operation {:#?}\", operation),\n\n }\n\n }\n\n}\n", "file_path": "src/cpu/operation.rs", "rank": 17, "score": 14086.218819751968 }, { "content": "}\n\n\n\nimpl NES {\n\n /// Reads a set of bytes into the ROM\n\n ///\n\n /// # Errors\n\n /// Forwards any errors encountered while reading the file\n\n pub fn load_from(&mut self, from: &mut dyn Read) -> std::io::Result<usize> {\n\n let result = from.read(&mut self.memory.program_rom)?;\n\n self\n\n .memory\n\n .write_u16(memory::constant::PROGRAM_COUNTER_RESET, 0x8000);\n\n\n\n Ok(result)\n\n }\n\n\n\n pub fn load(&mut self, program: &[Int]) {\n\n self.memory.program_rom[.. program.len()].copy_from_slice(program);\n\n self\n\n .memory\n", "file_path": "src/cpu/mod.rs", "rank": 18, "score": 14085.961557299564 }, { "content": " let mut cpu = Cpu::default();\n\n\n\n let size = crate::memory::constant::PROGRAM_ROM_SIZE as usize - 1;\n\n let values = vec![1; size];\n\n\n\n assert_eq!(size, cpu.load_from(&mut values.as_slice()).unwrap());\n\n }\n\n\n\n #[test]\n\n fn load_from_too_large() {\n\n let mut cpu = Cpu::default();\n\n\n\n let rom_size = crate::memory::constant::PROGRAM_ROM_SIZE as usize;\n\n let values = vec![1; rom_size + 1];\n\n\n\n assert_eq!(rom_size, cpu.load_from(&mut values.as_slice()).unwrap());\n\n }\n\n}\n", "file_path": "src/cpu/mod.rs", "rank": 19, "score": 14085.907562553855 }, { "content": " 0x86 => STX(Addr::zero_page(cpu)),\n\n 0x96 => STX(Addr::x_indexed_zero_page(cpu)),\n\n 0x8E => STX(Addr::absolute(cpu)),\n\n // STY\n\n 0x84 => STY(Addr::zero_page(cpu)),\n\n 0x94 => STY(Addr::x_indexed_zero_page(cpu)),\n\n 0x8C => STY(Addr::absolute(cpu)),\n\n _ => unimplemented!(\"opcode {:X?}\", opcode),\n\n }\n\n }\n\n}\n\n\n\nimpl Cpu {\n\n pub fn next_operation(self: &mut Cpu) -> Operation {\n\n let opcode: Int = self.memory.read(self.register.program_counter);\n\n self.register.program_counter += 1;\n\n Operation::new(opcode, self)\n\n }\n\n\n\n /// # Panics\n", "file_path": "src/cpu/operation.rs", "rank": 20, "score": 14085.035499331787 }, { "content": " SEI,\n\n /// Clear non-mutable interrupt processor flag\n\n CLI,\n\n /// Clear overflow processor flag\n\n CLV,\n\n /// Set decimal mode processor flag (not implemented on NES)\n\n SED,\n\n /// Clear decimal mode processor flag (not implemented on NES)\n\n CLD,\n\n /// Increment memory\n\n INC(Resolvable<memory::Address>),\n\n /// Jump\n\n JMP(Resolvable<memory::Address>),\n\n /// Jump to SubRoutine\n\n JSR(Resolvable<memory::Address>),\n\n /// Load to accumulator\n\n LDA(Resolvable<Int>),\n\n /// Load to X register\n\n LDX(Resolvable<Int>),\n\n /// Load to Y register\n", "file_path": "src/cpu/operation.rs", "rank": 21, "score": 14084.137677328104 }, { "content": " DEY,\n\n /// Increment Y\n\n INY,\n\n /// Rotate accumulator left\n\n ROLAcc,\n\n /// Rotate left\n\n ROL(Resolvable<memory::Address>),\n\n /// Rotate accumulator left\n\n RORAcc,\n\n /// Rotate right\n\n ROR(Resolvable<memory::Address>),\n\n /// Return from interrupt\n\n RTI,\n\n /// Return from subroutine\n\n RTS,\n\n /// Subtract with carry\n\n SBC(Resolvable<Int>),\n\n // Store accumulator\n\n STA(Resolvable<memory::Address>),\n\n // Store accumulator\n", "file_path": "src/cpu/operation.rs", "rank": 22, "score": 14084.136241528635 }, { "content": " BEQ(Resolvable<Int>),\n\n /// Break\n\n ///\n\n /// Triggers non-maskable interrupt (NMI).\n\n BRK,\n\n /// Compare to accumulator\n\n CMP(Resolvable<Int>),\n\n /// Compare to X register\n\n CPX(Resolvable<Int>),\n\n /// Compare to Y register\n\n CPY(Resolvable<Int>),\n\n /// Decrement memory\n\n DEC(Resolvable<memory::Address>),\n\n /// Bitwise exclusive OR (XOR)\n\n EOR(Resolvable<Int>),\n\n /// Set carry processor flag\n\n SEC,\n\n /// Clear carry processor flag\n\n CLC,\n\n /// Set non-mutable interrupt processor flag\n", "file_path": "src/cpu/operation.rs", "rank": 23, "score": 14083.86531241438 }, { "content": " pub interrupt_status: InterruptStatus,\n\n /// Whether arithmetic should treat values as binary-coded decimal rather than binary values\n\n ///\n\n /// Decimal mode is not supported on NES chips.\n\n decimal_mode: NumberMode,\n\n}\n\n\n\n#[derive(Debug, Default)]\n\npub struct InterruptStatus {\n\n /// Whether *maskable* interrupts should be disabled\n\n ///\n\n /// It can be explicitly set using the 'Set Interrupt Disable' (SEI) instruction and cleared with 'Clear Interrupt Disable' (CLI).\n\n pub enabled: bool,\n\n /// Whether a BRK instruction has been executed and an interrupt has been generated to process it\n\n pub break_command: bool,\n\n}\n\n\n\n#[derive(Debug, Default)]\n\npub struct ResultStatus {\n\n /// Whether result of last operation was zero\n", "file_path": "src/cpu/registers.rs", "rank": 24, "score": 14082.715245102003 }, { "content": " pub zero: bool,\n\n /// Whether result of last operation was \"negative\"\n\n ///\n\n /// This flag is true if the most-significant bit of the result was one.\n\n pub negative: bool,\n\n /// Whether last operation caused an *unsigned* integer overflow\n\n ///\n\n /// This condition is set during arithmetic, comparison and during logical shifts.\n\n /// It can be explicitly set using the 'Set Carry Flag' (SEC) instruction and cleared with 'Clear Carry Flag' (CLC).\n\n pub carry: Carry,\n\n /// Whether last operation caused a *signed* integer overflow\n\n ///\n\n ///\n\n /// For example 0x40 (64) + 0x40 (64) = 0x80 (-128) => `overflow=true`.\n\n ///\n\n /// Cleared with 'Clear Overflow' (CLV) instruction.\n\n /// Only affected by ADC, BIT, CLV, PLP, RTI, and SBC instructions.\n\n pub overflow: Overflow,\n\n}\n\n#[derive(Debug)]\n", "file_path": "src/cpu/registers.rs", "rank": 25, "score": 14082.470089512684 }, { "content": " BPL(Resolvable<Int>),\n\n /// Branch if minus\n\n ///\n\n /// Branch if negative flag set\n\n BMI(Resolvable<Int>),\n\n /// Branch if overflow flag clear\n\n BVC(Resolvable<Int>),\n\n /// Branch if overflow flag set\n\n BVS(Resolvable<Int>),\n\n /// Branch if carry flag clear\n\n BCC(Resolvable<Int>),\n\n /// Branch if carry flag set\n\n BCS(Resolvable<Int>),\n\n /// Branch if not equal\n\n ///\n\n /// Branches if zero flag clear\n\n BNE(Resolvable<Int>),\n\n /// Branch if equal\n\n ///\n\n /// Branch if zero flag set\n", "file_path": "src/cpu/operation.rs", "rank": 26, "score": 14082.352835932483 }, { "content": " 0x50 => BVC(Addr::relative(cpu)),\n\n 0x70 => BVS(Addr::relative(cpu)),\n\n 0x90 => BCC(Addr::relative(cpu)),\n\n 0xB0 => BCS(Addr::relative(cpu)),\n\n 0xD0 => BNE(Addr::relative(cpu)),\n\n 0xF0 => BEQ(Addr::relative(cpu)),\n\n // BRK\n\n 0x00 => BRK,\n\n // CMP\n\n 0xC9 => CMP(Addr::immediate(cpu)),\n\n 0xC5 => CMP(Addr::zero_page(cpu)),\n\n 0xD5 => CMP(Addr::x_indexed_zero_page(cpu)),\n\n 0xCD => CMP(Addr::absolute(cpu)),\n\n 0xDD => CMP(Addr::x_indexed_absolute(cpu)),\n\n 0xD9 => CMP(Addr::y_indexed_absolute(cpu)),\n\n 0xC1 => CMP(Addr::x_indexed_indirect(cpu)),\n\n 0xD1 => CMP(Addr::indirect_y_indexed(cpu)),\n\n // CPX\n\n 0xE0 => CPX(Addr::immediate(cpu)),\n\n 0xE4 => CPX(Addr::zero_page(cpu)),\n", "file_path": "src/cpu/operation.rs", "rank": 27, "score": 14082.125043550377 }, { "content": " 0x29 => AND(Addr::immediate(cpu)),\n\n 0x25 => AND(Addr::zero_page(cpu)),\n\n 0x35 => AND(Addr::x_indexed_zero_page(cpu)),\n\n 0x2D => AND(Addr::absolute(cpu)),\n\n 0x3D => AND(Addr::x_indexed_absolute(cpu)),\n\n 0x39 => AND(Addr::y_indexed_absolute(cpu)),\n\n 0x21 => AND(Addr::x_indexed_indirect(cpu)),\n\n 0x31 => AND(Addr::indirect_y_indexed(cpu)),\n\n // ASL\n\n 0x0A => ASLAcc,\n\n 0x06 => ASL(Addr::zero_page(cpu)),\n\n 0x16 => ASL(Addr::x_indexed_zero_page(cpu)),\n\n 0x0E => ASL(Addr::absolute(cpu)),\n\n 0x1E => ASL(Addr::x_indexed_absolute(cpu)),\n\n // BIT\n\n 0x24 => BIT(Addr::zero_page(cpu)),\n\n 0x2C => BIT(Addr::absolute(cpu)),\n\n // Branch\n\n 0x10 => BPL(Addr::relative(cpu)),\n\n 0x30 => BMI(Addr::relative(cpu)),\n", "file_path": "src/cpu/operation.rs", "rank": 28, "score": 14082.117333713937 }, { "content": " 0xA5 => LDA(Addr::zero_page(cpu)),\n\n 0xB5 => LDA(Addr::x_indexed_zero_page(cpu)),\n\n 0xAD => LDA(Addr::absolute(cpu)),\n\n 0xBD => LDA(Addr::x_indexed_absolute(cpu)),\n\n 0xB9 => LDA(Addr::y_indexed_absolute(cpu)),\n\n 0xA1 => LDA(Addr::x_indexed_indirect(cpu)),\n\n 0xB1 => LDA(Addr::indirect_y_indexed(cpu)),\n\n // LDX\n\n 0xA2 => LDX(Addr::immediate(cpu)),\n\n 0xA6 => LDX(Addr::zero_page(cpu)),\n\n 0xB6 => LDX(Addr::y_indexed_zero_page(cpu)),\n\n 0xAE => LDX(Addr::absolute(cpu)),\n\n 0xBE => LDX(Addr::y_indexed_absolute(cpu)),\n\n // LDY\n\n 0xA0 => LDY(Addr::immediate(cpu)),\n\n 0xA4 => LDY(Addr::zero_page(cpu)),\n\n 0xB4 => LDY(Addr::x_indexed_zero_page(cpu)),\n\n 0xAC => LDY(Addr::absolute(cpu)),\n\n 0xBC => LDY(Addr::x_indexed_absolute(cpu)),\n\n // LSR\n", "file_path": "src/cpu/operation.rs", "rank": 29, "score": 14082.115818289461 }, { "content": " 0xEC => CPX(Addr::absolute(cpu)),\n\n // CPY\n\n 0xC0 => CPY(Addr::immediate(cpu)),\n\n 0xC4 => CPY(Addr::zero_page(cpu)),\n\n 0xCC => CPY(Addr::absolute(cpu)),\n\n // DEC\n\n 0xC6 => DEC(Addr::zero_page(cpu)),\n\n 0xD6 => DEC(Addr::x_indexed_zero_page(cpu)),\n\n 0xCE => DEC(Addr::absolute(cpu)),\n\n 0xDE => DEC(Addr::x_indexed_absolute(cpu)),\n\n // EOR (XOR)\n\n 0x49 => EOR(Addr::immediate(cpu)),\n\n 0x45 => EOR(Addr::zero_page(cpu)),\n\n 0x55 => EOR(Addr::x_indexed_zero_page(cpu)),\n\n 0x4D => EOR(Addr::absolute(cpu)),\n\n 0x5D => EOR(Addr::x_indexed_absolute(cpu)),\n\n 0x59 => EOR(Addr::y_indexed_absolute(cpu)),\n\n 0x41 => EOR(Addr::x_indexed_indirect(cpu)),\n\n 0x51 => EOR(Addr::indirect_y_indexed(cpu)),\n\n // Processor status flags set\n", "file_path": "src/cpu/operation.rs", "rank": 30, "score": 14082.09071657318 }, { "content": " // RTS\n\n 0x60 => RTS,\n\n // SBC\n\n 0xE9 => SBC(Addr::immediate(cpu)),\n\n 0xE5 => SBC(Addr::zero_page(cpu)),\n\n 0xF5 => SBC(Addr::x_indexed_zero_page(cpu)),\n\n 0xED => SBC(Addr::absolute(cpu)),\n\n 0xFD => SBC(Addr::x_indexed_absolute(cpu)),\n\n 0xF9 => SBC(Addr::y_indexed_absolute(cpu)),\n\n 0xE1 => SBC(Addr::x_indexed_indirect(cpu)),\n\n 0xF1 => SBC(Addr::indirect_y_indexed(cpu)),\n\n // STA\n\n 0x85 => STA(Addr::zero_page(cpu)),\n\n 0x95 => STA(Addr::x_indexed_zero_page(cpu)),\n\n 0x8D => STA(Addr::absolute(cpu)),\n\n 0x9D => STA(Addr::x_indexed_absolute(cpu)),\n\n 0x99 => STA(Addr::y_indexed_absolute(cpu)),\n\n 0x81 => STA(Addr::x_indexed_indirect(cpu)),\n\n 0x91 => STA(Addr::indirect_y_indexed(cpu)),\n\n // STX\n", "file_path": "src/cpu/operation.rs", "rank": 31, "score": 14082.082643475731 }, { "content": " 0x4A => LSR(Addr::accumulator(cpu)),\n\n 0x46 => LSR(Addr::zero_page(cpu)),\n\n 0x56 => LSR(Addr::x_indexed_zero_page(cpu)),\n\n 0x4E => LSR(Addr::absolute(cpu)),\n\n 0x5E => LSR(Addr::x_indexed_absolute(cpu)),\n\n // NOP\n\n 0xEA => NOP,\n\n // ORA\n\n 0x09 => ORA(Addr::immediate(cpu)),\n\n 0x05 => ORA(Addr::zero_page(cpu)),\n\n 0x15 => ORA(Addr::x_indexed_zero_page(cpu)),\n\n 0x0D => ORA(Addr::absolute(cpu)),\n\n 0x1D => ORA(Addr::x_indexed_absolute(cpu)),\n\n 0x19 => ORA(Addr::y_indexed_absolute(cpu)),\n\n 0x01 => ORA(Addr::x_indexed_indirect(cpu)),\n\n 0x11 => ORA(Addr::indirect_y_indexed(cpu)),\n\n // Register X\n\n 0xAA => TAX,\n\n 0x8A => TXA,\n\n 0xCA => DEX,\n", "file_path": "src/cpu/operation.rs", "rank": 32, "score": 14082.04056034212 }, { "content": " LDY(Resolvable<Int>),\n\n /// Logical shift right\n\n LSR(Resolvable<Int>),\n\n /// No-op\n\n NOP,\n\n /// Bitwise OR with accumulator\n\n ORA(Resolvable<Int>),\n\n /// Transfer A to X\n\n TAX,\n\n /// Transfer X to A\n\n TXA,\n\n /// Decrement X\n\n DEX,\n\n /// Increment X\n\n INX,\n\n /// Transfer A to Y\n\n TAY,\n\n /// Transfer Y to A\n\n TYA,\n\n /// Decrement Y\n", "file_path": "src/cpu/operation.rs", "rank": 33, "score": 14082.015419135787 }, { "content": " 0x38 => SEC,\n\n 0x78 => SEI,\n\n 0xF8 => SED,\n\n // Processor status flags clear\n\n 0x18 => CLC,\n\n 0x58 => CLI,\n\n 0xB8 => CLV,\n\n 0xD8 => CLD,\n\n // INC\n\n 0xE6 => INC(Addr::zero_page(cpu)),\n\n 0xF6 => INC(Addr::x_indexed_zero_page(cpu)),\n\n 0xEE => INC(Addr::absolute(cpu)),\n\n 0xFE => INC(Addr::x_indexed_absolute(cpu)),\n\n // JMP\n\n 0x4C => JMP(Addr::absolute(cpu)),\n\n 0x6C => JMP(Addr::indirect(cpu)),\n\n // JSR\n\n 0x20 => JSR(Addr::absolute(cpu)),\n\n // LDA\n\n 0xA9 => LDA(Addr::immediate(cpu)),\n", "file_path": "src/cpu/operation.rs", "rank": 34, "score": 14081.934540988193 }, { "content": " 0xE8 => INX,\n\n // Register Y\n\n 0xA8 => TAY,\n\n 0x98 => TYA,\n\n 0x88 => DEY,\n\n 0xC8 => INY,\n\n // ROL\n\n 0x2A => ROLAcc,\n\n 0x26 => ROL(Addr::zero_page(cpu)),\n\n 0x36 => ROL(Addr::x_indexed_zero_page(cpu)),\n\n 0x2E => ROL(Addr::absolute(cpu)),\n\n 0x3E => ROL(Addr::x_indexed_absolute(cpu)),\n\n // ROR\n\n 0x6A => RORAcc,\n\n 0x66 => ROR(Addr::zero_page(cpu)),\n\n 0x76 => ROR(Addr::x_indexed_zero_page(cpu)),\n\n 0x6E => ROR(Addr::absolute(cpu)),\n\n 0x7E => ROR(Addr::x_indexed_absolute(cpu)),\n\n // RTI\n\n 0x40 => RTI,\n", "file_path": "src/cpu/operation.rs", "rank": 35, "score": 14081.889176208753 }, { "content": "pub enum Carry {\n\n NoOverflow,\n\n UnsignedOverflow,\n\n}\n\nimpl Default for Carry {\n\n fn default() -> Self {\n\n Self::NoOverflow\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum NumberMode {\n\n Binary,\n\n BinaryCodedDecimal,\n\n}\n\nimpl Default for NumberMode {\n\n fn default() -> Self {\n\n Self::Binary\n\n }\n\n}\n", "file_path": "src/cpu/registers.rs", "rank": 36, "score": 14081.62439628565 }, { "content": "\n\n#[derive(Debug)]\n\npub enum Overflow {\n\n NoOverflow,\n\n UnsignedOverflow,\n\n}\n\nimpl Default for Overflow {\n\n fn default() -> Self {\n\n Self::NoOverflow\n\n }\n\n}\n", "file_path": "src/cpu/registers.rs", "rank": 37, "score": 14081.464131123324 }, { "content": "#![feature(exclusive_range_pattern)]\n\n#![feature(fn_traits)]\n\n#![feature(half_open_range_patterns)]\n\n#![feature(unboxed_closures)]\n\n#![warn(clippy::pedantic)]\n\n#![allow(clippy::enum_glob_use)]\n\n\n\npub mod cpu;\n\npub mod memory;\n", "file_path": "src/lib.rs", "rank": 47, "score": 8.452099109425276 }, { "content": "#![feature(exclusive_range_pattern)]\n\n#![feature(fn_traits)]\n\n#![feature(half_open_range_patterns)]\n\n#![feature(type_ascription)]\n\n#![feature(unboxed_closures)]\n\n#![warn(clippy::pedantic)]\n\n#![allow(clippy::enum_glob_use)]\n\n\n\nuse std::{error::Error, fs::File};\n\n\n\nuse env_logger::Builder;\n\nuse log::{info, warn, LevelFilter};\n\nuse structopt::StructOpt;\n\n\n\nmod cli;\n\npub mod cpu;\n\npub mod memory;\n\n\n", "file_path": "src/main.rs", "rank": 48, "score": 7.7262844104420125 }, { "content": "use std::{convert::TryFrom, path::PathBuf};\n\n\n\nuse structopt::StructOpt;\n\nuse thiserror::Error;\n\n\n\nuse crate::memory;\n\n\n\n#[derive(Debug, StructOpt)]\n\n#[structopt(\n\n name = env!(\"CARGO_BIN_NAME\"),\n\n version = env!(\"CARGO_PKG_VERSION\"),\n\n author = env!(\"CARGO_PKG_AUTHORS\")\n\n)]\n\npub struct Cli {\n\n #[structopt(long, env = \"NES_LOG_LEVEL\")]\n\n pub log: Option<log::LevelFilter>,\n\n /// Initial address to set program counter to\n\n ///\n\n /// This may be any evalexpr expression which evaluates to a valid memory address integer.\n\n ///\n\n /// The following variables are exposed to be used in the expression: rom, rom_size, ram, ram_size\n\n #[structopt(short, long, parse(try_from_str = eval_address_expression))]\n\n pub start_address: Option<memory::Address>,\n\n /// Program file to load to ROM\n\n #[structopt(name = \"FILE\", parse(from_os_str))]\n\n pub file: Option<PathBuf>,\n\n}\n\n\n\n#[derive(Error, Debug)]\n", "file_path": "src/cli.rs", "rank": 49, "score": 5.159282214571297 }, { "content": "# NES Emulator\n\n\n\nAn NES emulator created to test out the Rust language\n\n\n\n## References\n\n\n\n- Inspired by the [Writing NES Emulator in Rust ebook](https://bugzmanov.github.io/nes_ebook) by [Rafael Bagmanov](https://twitter.com/bugzmanov)\n\n- [NESDoc](http://nesdev.com/NESDoc.pdf) used as reference\n", "file_path": "README.md", "rank": 50, "score": 1.4013298897605817 } ]
Rust
day7/main2.rs
allonsy/advent2017
644dd55ca9cc4319136123126c40330e9ba52de0
mod util; use std::cell::RefCell; use std::collections::HashMap; use std::collections::HashSet; use std::rc::Rc; type Pointer = Rc<RefCell<ProgramTower>>; #[derive(Debug)] struct ProgramTower { name: String, weight: i32, children: HashMap<String, Pointer>, } impl ProgramTower { fn new(name: String, weight: i32, children: HashMap<String, Pointer>) -> ProgramTower { ProgramTower { name: name, weight: weight, children: children, } } } struct ProgramTowerInput { name: String, weight: i32, children: Vec<String>, } impl ProgramTowerInput { fn new(name: String, weight: i32, children: Vec<String>) -> ProgramTowerInput { ProgramTowerInput { name: name, weight: weight, children: children, } } } fn main() { let input = parse_input(); let tower = create_tower(input); let (bad_node, good_weight) = analyze_children(&tower.borrow().children); println!( "new weight is: {}", get_new_balanced_weight(&bad_node.unwrap(), good_weight.unwrap()) ); } fn get_new_balanced_weight(tower: &Pointer, expected_weight: i64) -> i64 { let (bad_child, good_weight) = analyze_children(&tower.borrow().children); if bad_child.is_some() { if good_weight.is_some() { return get_new_balanced_weight(&bad_child.unwrap(), good_weight.unwrap()); } let this_weight = tower.borrow().weight as i64; return get_new_balanced_weight(&bad_child.unwrap(), expected_weight - this_weight); } let bad_weight = get_bad_weight(&tower.borrow().children); if bad_weight.is_none() { let cur_weight = get_tower_weight(tower); let diff = expected_weight - cur_weight; return tower.borrow().weight as i64 + diff; } let (normal_weight, bad_node) = bad_weight.unwrap(); let cur_weight = get_tower_weight(&bad_node); let diff = normal_weight - cur_weight; return bad_node.borrow().weight as i64 + diff; } fn get_tower_weight(tower: &Pointer) -> i64 { let mut sum: i64 = 0; sum += tower.borrow().weight as i64; for (_, child) in &tower.borrow().children { sum += get_tower_weight(&child); } return sum; } fn is_balanced(tower: &Pointer) -> bool { if tower.borrow().children.is_empty() { return true; } if tower.borrow().children.len() == 1 { for (_, child) in &tower.borrow().children { return is_balanced(child); } } let mut child_weight = None; for (_, child) in &tower.borrow().children { if !is_balanced(child) { return false; } let actual_child_weight = get_tower_weight(child); match child_weight { None => { child_weight = Some(actual_child_weight); } Some(wt) => { if wt != actual_child_weight { return false; } } } } return true; } fn analyze_children(children: &HashMap<String, Pointer>) -> (Option<Pointer>, Option<i64>) { let mut bad_child = None; let mut bad_child_name = None; for (child_name, child) in children { if !is_balanced(child) { bad_child = Some(child.clone()); bad_child_name = Some(child.borrow().name.clone()); break; } } if bad_child.is_none() { return (None, None); } let bad_child_name_unwrap = bad_child_name.unwrap(); let mut good_weight = None; for (child_name, child) in children { if *child_name != bad_child_name_unwrap { good_weight = Some(child.borrow().weight as i64); return (bad_child, good_weight); } } return (bad_child, None); } fn get_bad_weight(children: &HashMap<String, Pointer>) -> Option<(i64, Pointer)> { let mut freq_map: HashMap<i64, (i32, Pointer)> = HashMap::new(); for (_, child) in children { let this_weight = get_tower_weight(child); freq_map.entry(this_weight).or_insert((0, child.clone())).0 += 1; } for (wt, freq) in freq_map { if freq.0 == 1 { let bad_child = freq.1; for (name, child) in children { if *name != bad_child.borrow().name { return Some((get_tower_weight(child), bad_child)); } } } } return None; } fn create_tower(input: Vec<ProgramTowerInput>) -> Pointer { let mut roots: HashMap<String, Pointer> = HashMap::new(); let mut already_seen: HashMap<String, Pointer> = HashMap::new(); for node in input { let this_node: Pointer = if already_seen.contains_key(&node.name) { let val = already_seen.get(&node.name).unwrap(); val.borrow_mut().weight = node.weight; val.clone() } else { let new_node = ProgramTower::new(node.name.clone(), node.weight, HashMap::new()); let new_pointer = Rc::new(RefCell::new(new_node)); already_seen.insert(node.name.clone(), new_pointer.clone()); roots.insert(node.name, new_pointer.clone()); new_pointer }; for child_name in node.children { if already_seen.contains_key(&child_name) { let ptr = already_seen.get(&child_name).unwrap(); this_node .borrow_mut() .children .insert(child_name.clone(), ptr.clone()); roots.remove(&child_name); } else { let new_child_node = ProgramTower::new(child_name.clone(), 0, HashMap::new()); let child_ptr = Rc::new(RefCell::new(new_child_node)); already_seen.insert(child_name.clone(), child_ptr.clone()); this_node .borrow_mut() .children .insert(child_name, child_ptr); } } } if roots.len() != 1 { panic!("failing out: {}", roots.len()); } roots.values().next().unwrap().clone() } fn parse_input() -> Vec<ProgramTowerInput> { let input_lines = util::read_file_lines("input.txt"); let mut tower_input = Vec::new(); for line in input_lines { let words: Vec<&str> = line.split(" ").collect(); let prog_name: String = words[0].to_owned(); let weight_full_str: String = words[1].to_owned(); let weight_length = weight_full_str.len(); let weight: String = (&weight_full_str[1..weight_length - 1]).to_owned(); let weight_num = weight.parse::<i32>().unwrap(); if words.len() == 2 { tower_input.push(ProgramTowerInput::new(prog_name, weight_num, Vec::new())); } else { let mut children: Vec<String> = Vec::new(); let child_names = &words[3..]; for child in child_names { let child_str = child.to_owned().to_string(); let child_len = child_str.len(); if last_char_comma(&child_str) { children.push(child_str[..child_len - 1].to_string()); } else { children.push(child_str); } } tower_input.push(ProgramTowerInput::new(prog_name, weight_num, children)); } } return tower_input; } fn last_char_comma(name: &String) -> bool { let bytes = name.clone().into_bytes(); let bytes_len = bytes.len(); bytes[bytes_len - 1] == ',' as u8 }
mod util; use std::cell::RefCell; use std::collections::HashMap; use std::collections::HashSet; use std::rc::Rc; type Pointer = Rc<RefCell<ProgramTower>>; #[derive(Debug)] struct ProgramTower { name: String, weight: i32, children: HashMap<String, Pointer>, } impl ProgramTower { fn new(name: String, weight: i32, children: HashMap<String, Pointer>) -> ProgramTower { ProgramTower { name: name, weight: weight, children: children, } } } struct ProgramTowerInput { name: String, weight: i32, children: Vec<String>, } impl ProgramTowerInput { fn new(name: String, weight: i32, children: Vec<String>) -> ProgramTowerInput { ProgramTowerInput { name: name, weight: weight, children: children, } } } fn main() { let input = parse_input(); let tower = create_tower(input); let (bad_node, good_weight) = analyze_children(&tower.borrow().children); println!( "new weight is: {}", get_new_balanced_weight(&bad_node.unwrap(), good_weight.unwrap()) ); } fn get_new_balanced_weight(tower: &Pointer, expected_weight: i64) -> i64 { let (bad_child, good_weight) = analyze_children(&tower.borrow().children); if bad_child.is_some() { if good_weight.is_some() { return get_new_balanced_weight(&bad_child.unwrap(), good_weight.unwrap()); } let this_weight = tower.borrow().weight as i64; return get_new_balanced_weight(&bad_child.unwrap(), expected_weight - this_weight); } let bad_weight = get_bad_weight(&tower.borrow().children); if bad_weight.is_none() { let cur_weight = get_tower_weight(tower); let diff = expected_weight - cur_weight; return tower.borrow().weight as i64 + diff; } let (normal_weight, bad_node) = bad_weight.unwrap(); let cur_weight = get_tower_weight(&bad_node); let diff = normal_weight - cur_weight; return bad_node.borrow().weight as i64 + diff; } fn get_tower_weight(tower: &Pointer) -> i64 { let mut sum: i64 = 0; sum += tower.borrow().weight as i64; for (_, child) in &tower.borrow().children { sum += get_tower_weight(&child); } return sum; } fn is_balanced(tower: &Pointer) -> bool { if tower.borrow().children.is_empty() { return true; } if tower.borrow().children.len() == 1 { for (_, child) in &tower.borrow().children { return is_balanced(child); } } let mut child_weight = None; for (_, child) in &tower.borrow().children { if !is_balanced(child) { return false; } let actual_child_weight = get_tower_weight(child); match chil
(bad_child, None); } fn get_bad_weight(children: &HashMap<String, Pointer>) -> Option<(i64, Pointer)> { let mut freq_map: HashMap<i64, (i32, Pointer)> = HashMap::new(); for (_, child) in children { let this_weight = get_tower_weight(child); freq_map.entry(this_weight).or_insert((0, child.clone())).0 += 1; } for (wt, freq) in freq_map { if freq.0 == 1 { let bad_child = freq.1; for (name, child) in children { if *name != bad_child.borrow().name { return Some((get_tower_weight(child), bad_child)); } } } } return None; } fn create_tower(input: Vec<ProgramTowerInput>) -> Pointer { let mut roots: HashMap<String, Pointer> = HashMap::new(); let mut already_seen: HashMap<String, Pointer> = HashMap::new(); for node in input { let this_node: Pointer = if already_seen.contains_key(&node.name) { let val = already_seen.get(&node.name).unwrap(); val.borrow_mut().weight = node.weight; val.clone() } else { let new_node = ProgramTower::new(node.name.clone(), node.weight, HashMap::new()); let new_pointer = Rc::new(RefCell::new(new_node)); already_seen.insert(node.name.clone(), new_pointer.clone()); roots.insert(node.name, new_pointer.clone()); new_pointer }; for child_name in node.children { if already_seen.contains_key(&child_name) { let ptr = already_seen.get(&child_name).unwrap(); this_node .borrow_mut() .children .insert(child_name.clone(), ptr.clone()); roots.remove(&child_name); } else { let new_child_node = ProgramTower::new(child_name.clone(), 0, HashMap::new()); let child_ptr = Rc::new(RefCell::new(new_child_node)); already_seen.insert(child_name.clone(), child_ptr.clone()); this_node .borrow_mut() .children .insert(child_name, child_ptr); } } } if roots.len() != 1 { panic!("failing out: {}", roots.len()); } roots.values().next().unwrap().clone() } fn parse_input() -> Vec<ProgramTowerInput> { let input_lines = util::read_file_lines("input.txt"); let mut tower_input = Vec::new(); for line in input_lines { let words: Vec<&str> = line.split(" ").collect(); let prog_name: String = words[0].to_owned(); let weight_full_str: String = words[1].to_owned(); let weight_length = weight_full_str.len(); let weight: String = (&weight_full_str[1..weight_length - 1]).to_owned(); let weight_num = weight.parse::<i32>().unwrap(); if words.len() == 2 { tower_input.push(ProgramTowerInput::new(prog_name, weight_num, Vec::new())); } else { let mut children: Vec<String> = Vec::new(); let child_names = &words[3..]; for child in child_names { let child_str = child.to_owned().to_string(); let child_len = child_str.len(); if last_char_comma(&child_str) { children.push(child_str[..child_len - 1].to_string()); } else { children.push(child_str); } } tower_input.push(ProgramTowerInput::new(prog_name, weight_num, children)); } } return tower_input; } fn last_char_comma(name: &String) -> bool { let bytes = name.clone().into_bytes(); let bytes_len = bytes.len(); bytes[bytes_len - 1] == ',' as u8 }
d_weight { None => { child_weight = Some(actual_child_weight); } Some(wt) => { if wt != actual_child_weight { return false; } } } } return true; } fn analyze_children(children: &HashMap<String, Pointer>) -> (Option<Pointer>, Option<i64>) { let mut bad_child = None; let mut bad_child_name = None; for (child_name, child) in children { if !is_balanced(child) { bad_child = Some(child.clone()); bad_child_name = Some(child.borrow().name.clone()); break; } } if bad_child.is_none() { return (None, None); } let bad_child_name_unwrap = bad_child_name.unwrap(); let mut good_weight = None; for (child_name, child) in children { if *child_name != bad_child_name_unwrap { good_weight = Some(child.borrow().weight as i64); return (bad_child, good_weight); } } return
random
[ { "content": "fn eval_condition(state: &mut HashMap<String, i32>, condition: &Condition) -> bool {\n\n let register_value = get_register_value(state, condition.register.clone());\n\n let operand = condition.operand;\n\n\n\n match condition.relation {\n\n Relation::LT => return register_value < operand,\n\n Relation::LE => return register_value <= operand,\n\n Relation::GT => return register_value > operand,\n\n Relation::GE => return register_value >= operand,\n\n Relation::EQ => return register_value == operand,\n\n Relation::NE => return register_value != operand,\n\n }\n\n}\n\n\n", "file_path": "day8/main1.rs", "rank": 4, "score": 257506.4099386612 }, { "content": "fn create_tower(input: Vec<ProgramTowerInput>) -> Pointer {\n\n let mut roots: HashMap<String, Pointer> = HashMap::new();\n\n let mut already_seen: HashMap<String, Pointer> = HashMap::new();\n\n\n\n for node in input {\n\n let this_node: Pointer = if already_seen.contains_key(&node.name) {\n\n let val = already_seen.get(&node.name).unwrap();\n\n val.borrow_mut().weight = node.weight;\n\n val.clone()\n\n } else {\n\n let new_node = ProgramTower::new(node.name.clone(), node.weight, HashMap::new());\n\n let new_pointer = Rc::new(RefCell::new(new_node));\n\n already_seen.insert(node.name.clone(), new_pointer.clone());\n\n roots.insert(node.name, new_pointer.clone());\n\n new_pointer\n\n };\n\n\n\n for child_name in node.children {\n\n if already_seen.contains_key(&child_name) {\n\n let ptr = already_seen.get(&child_name).unwrap();\n", "file_path": "day7/main1.rs", "rank": 7, "score": 254846.75912424317 }, { "content": "fn get_sum(input: String) -> u32 {\n\n let mut sum = 0;\n\n let mut iter = input.chars();\n\n let firstOption = iter.next();\n\n let mut first: char;\n\n match firstOption {\n\n Some(val) => {\n\n first = val;\n\n }\n\n None => {\n\n return sum;\n\n }\n\n }\n\n\n\n loop {\n\n match iter.next() {\n\n Some(second) => {\n\n if first == second {\n\n let intVal = match char::to_digit(first, 10) {\n\n Some(val) => val,\n", "file_path": "day1/main.rs", "rank": 8, "score": 251303.29519845365 }, { "content": "fn last_char_comma(name: &String) -> bool {\n\n let bytes = name.clone().into_bytes();\n\n let bytes_len = bytes.len();\n\n bytes[bytes_len - 1] == ',' as u8\n\n}\n", "file_path": "day7/main1.rs", "rank": 10, "score": 246494.4648168906 }, { "content": "fn get_register_value(state: &mut HashMap<String, i32>, register: String) -> i32 {\n\n if state.contains_key(&register) {\n\n return *state.get(&register).unwrap();\n\n }\n\n\n\n state.insert(register, 0);\n\n return 0;\n\n}\n\n\n", "file_path": "day8/main1.rs", "rank": 11, "score": 239418.75736405485 }, { "content": "fn get_grid_values(input: String) -> [bool; GRID_DIMENSION] {\n\n let mut row = [false; GRID_DIMENSION];\n\n\n\n let hash = hash::get_knot_hash(&input);\n\n let mut i = 0;\n\n for ch in hash.chars() {\n\n let byte_arr = get_char_bytes(ch);\n\n for j in 0..4 {\n\n row[i + j] = byte_arr[j];\n\n }\n\n i += 4;\n\n }\n\n return row;\n\n}\n\n\n", "file_path": "day14/main2.rs", "rank": 12, "score": 233237.93203575278 }, { "content": "fn get_grid_values(input: String) -> [bool; GRID_DIMENSION] {\n\n let mut row = [false; GRID_DIMENSION];\n\n\n\n let hash = hash::get_knot_hash(&input);\n\n let mut i = 0;\n\n for ch in hash.chars() {\n\n let byte_arr = get_char_bytes(ch);\n\n for j in 0..4 {\n\n row[i + j] = byte_arr[j];\n\n }\n\n i += 4;\n\n }\n\n return row;\n\n}\n\n\n", "file_path": "day14/main1.rs", "rank": 13, "score": 233237.93203575275 }, { "content": "fn get_register_value(state: &mut State, register: String) -> i32 {\n\n if state.cpu.contains_key(&register) {\n\n return *state.cpu.get(&register).unwrap();\n\n }\n\n\n\n state.cpu.insert(register, 0);\n\n update_highest_value(state, 0);\n\n return 0;\n\n}\n\n\n", "file_path": "day8/main2.rs", "rank": 14, "score": 217733.24053367763 }, { "content": "fn run_command(instruction: &Instruction, state: &mut HashMap<String, i32>) {\n\n let cond = &instruction.condition;\n\n if eval_condition(state, cond) {\n\n apply_tranform(\n\n state,\n\n instruction.register.clone(),\n\n &instruction.command,\n\n instruction.operand,\n\n );\n\n }\n\n}\n\n\n", "file_path": "day8/main1.rs", "rank": 15, "score": 210320.08104272228 }, { "content": "fn apply_tranform(state: &mut State, register: String, command: &Command, operand: i32) {\n\n let new_val;\n\n {\n\n let entry = state.cpu.entry(register).or_insert(0);\n\n match *command {\n\n Command::Inc => *entry += operand,\n\n Command::Dec => *entry -= operand,\n\n }\n\n new_val = *entry;\n\n }\n\n update_highest_value(state, new_val);\n\n}\n\n\n", "file_path": "day8/main2.rs", "rank": 16, "score": 199733.87918650045 }, { "content": "fn parse_input() -> Vec<ProgramTowerInput> {\n\n let input_lines = util::read_file_lines(\"input.txt\");\n\n let mut tower_input = Vec::new();\n\n for line in input_lines {\n\n let words: Vec<&str> = line.split(\" \").collect();\n\n let prog_name: String = words[0].to_owned();\n\n let weight_full_str: String = words[1].to_owned();\n\n let weight_length = weight_full_str.len();\n\n let weight: String = (&weight_full_str[1..weight_length - 1]).to_owned();\n\n let weight_num = weight.parse::<i32>().unwrap();\n\n if words.len() == 2 {\n\n // no children\n\n tower_input.push(ProgramTowerInput::new(prog_name, weight_num, Vec::new()));\n\n } else {\n\n let mut children: Vec<String> = Vec::new();\n\n let child_names = &words[3..];\n\n for child in child_names {\n\n let child_str = child.to_owned().to_string();\n\n let child_len = child_str.len();\n\n if last_char_comma(&child_str) {\n", "file_path": "day7/main1.rs", "rank": 18, "score": 197489.17081851792 }, { "content": "fn update_highest_value(state: &mut State, new_val: i32) {\n\n match state.highest_value {\n\n None => state.highest_value = Some(new_val),\n\n Some(old_val) => {\n\n state.highest_value = if old_val < new_val {\n\n Some(new_val)\n\n } else {\n\n Some(old_val)\n\n }\n\n }\n\n };\n\n}\n\n\n", "file_path": "day8/main2.rs", "rank": 19, "score": 194812.83657138815 }, { "content": "fn is_prime(n: i64) -> bool {\n\n if n == 2 {\n\n return true;\n\n }\n\n if n % 2 == 0 {\n\n return false;\n\n }\n\n\n\n let sqrt = (n as f64).sqrt() as i64;\n\n for val in 2..(sqrt + 1) {\n\n if n % val == 0 {\n\n return false;\n\n }\n\n }\n\n\n\n return true;\n\n}\n", "file_path": "day23/main2.rs", "rank": 20, "score": 191965.26897654906 }, { "content": "fn read_input() -> Vec<Vec<i32>> {\n\n let mut f = File::open(FILE_NAME).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n let mut row = Vec::new();\n\n for num_str in fline.split_whitespace() {\n\n row.push(num_str.parse::<i32>().unwrap());\n\n }\n\n rows.push(row);\n\n }\n\n }\n\n return rows;\n\n}\n\n\n", "file_path": "day2/main.rs", "rank": 21, "score": 184700.20738739183 }, { "content": "fn byte_to_int(input: u8) -> i32 {\n\n let zero_byte = '0' as u8;\n\n let u8_result = input - zero_byte;\n\n return u8_result as i32;\n\n}\n", "file_path": "day1/main2.rs", "rank": 22, "score": 183697.59434960067 }, { "content": "struct ProgramTowerInput {\n\n name: String,\n\n weight: i32,\n\n children: Vec<String>,\n\n}\n\n\n\nimpl ProgramTowerInput {\n\n fn new(name: String, weight: i32, children: Vec<String>) -> ProgramTowerInput {\n\n ProgramTowerInput {\n\n name: name,\n\n weight: weight,\n\n children: children,\n\n }\n\n }\n\n}\n\n\n", "file_path": "day7/main1.rs", "rank": 24, "score": 183264.35880454618 }, { "content": "fn swap(hash_vec: &mut Vec<i32>, start_index: i32, end_index: i32) {\n\n let temp = hash_vec[end_index as usize];\n\n hash_vec[end_index as usize] = hash_vec[start_index as usize];\n\n hash_vec[start_index as usize] = temp;\n\n}\n\n\n", "file_path": "day10/main2.rs", "rank": 25, "score": 177832.14126667625 }, { "content": "fn swap(hash_vec: &mut Vec<i32>, start_index: i32, end_index: i32) {\n\n let temp = hash_vec[end_index as usize];\n\n hash_vec[end_index as usize] = hash_vec[start_index as usize];\n\n hash_vec[start_index as usize] = temp;\n\n}\n\n\n", "file_path": "day10/main1.rs", "rank": 26, "score": 177832.14126667625 }, { "content": "fn swap(hash_vec: &mut Vec<i32>, start_index: i32, end_index: i32) {\n\n let temp = hash_vec[end_index as usize];\n\n hash_vec[end_index as usize] = hash_vec[start_index as usize];\n\n hash_vec[start_index as usize] = temp;\n\n}\n\n\n", "file_path": "day14/hash.rs", "rank": 27, "score": 177832.14126667625 }, { "content": "fn create_connection(node_map: &mut HashMap<i32, Node>, from: i32, to: i32) {\n\n if from == to {\n\n if !node_map.contains_key(&from) {\n\n let new_node = Node {\n\n name: from,\n\n connections: HashSet::new(),\n\n };\n\n node_map.insert(from, new_node);\n\n }\n\n }\n\n\n\n if node_map.contains_key(&from) {\n\n node_map.get_mut(&from).unwrap().connections.insert(to);\n\n } else {\n\n let mut new_conns = HashSet::new();\n\n new_conns.insert(to);\n\n let new_node = Node {\n\n name: from,\n\n connections: new_conns,\n\n };\n", "file_path": "day12/main1.rs", "rank": 28, "score": 177184.35793054017 }, { "content": "fn create_connection(node_map: &mut HashMap<i32, Node>, from: i32, to: i32) {\n\n if from == to {\n\n if !node_map.contains_key(&from) {\n\n let new_node = Node {\n\n name: from,\n\n connections: HashSet::new(),\n\n };\n\n node_map.insert(from, new_node);\n\n }\n\n }\n\n\n\n if node_map.contains_key(&from) {\n\n node_map.get_mut(&from).unwrap().connections.insert(to);\n\n } else {\n\n let mut new_conns = HashSet::new();\n\n new_conns.insert(to);\n\n let new_node = Node {\n\n name: from,\n\n connections: new_conns,\n\n };\n", "file_path": "day12/main2.rs", "rank": 29, "score": 177184.35793054017 }, { "content": "fn check_validity(words: Vec<String>) -> bool {\n\n let mut words_seen = HashSet::new();\n\n\n\n for word in words {\n\n if words_seen.contains(&word) {\n\n return false;\n\n }\n\n words_seen.insert(word);\n\n }\n\n return true;\n\n}\n\n\n", "file_path": "day4/main1.rs", "rank": 30, "score": 176943.09698450804 }, { "content": "fn check_validity(words: Vec<String>) -> bool {\n\n let mut words_seen = HashSet::new();\n\n\n\n for mut word in words {\n\n word = alphabetize(word);\n\n if words_seen.contains(&word) {\n\n return false;\n\n }\n\n words_seen.insert(word);\n\n }\n\n return true;\n\n}\n\n\n", "file_path": "day4/main2.rs", "rank": 31, "score": 176943.09698450804 }, { "content": "fn reverse_range(hash_vec: &mut Vec<i32>, start_index: i32, end_index: i32) {\n\n let range = if end_index > start_index {\n\n end_index - start_index\n\n } else {\n\n HASH_SIZE - start_index + end_index\n\n };\n\n\n\n let actual_end_index = mod_index(end_index - 1);\n\n for i in 0..(range / 2) {\n\n let swap_start = mod_index(start_index + i);\n\n let swap_end = mod_index(actual_end_index - i);\n\n swap(hash_vec, swap_start, swap_end);\n\n }\n\n}\n\n\n", "file_path": "day14/hash.rs", "rank": 32, "score": 176004.78282040748 }, { "content": "fn reverse_range(hash_vec: &mut Vec<i32>, start_index: i32, end_index: i32) {\n\n let range = if end_index > start_index {\n\n end_index - start_index\n\n } else {\n\n HASH_SIZE - start_index + end_index\n\n };\n\n\n\n let actual_end_index = mod_index(end_index - 1);\n\n for i in 0..(range / 2) {\n\n let swap_start = mod_index(start_index + i);\n\n let swap_end = mod_index(actual_end_index - i);\n\n swap(hash_vec, swap_start, swap_end);\n\n }\n\n}\n\n\n", "file_path": "day10/main2.rs", "rank": 33, "score": 176004.78282040748 }, { "content": "fn reverse_range(hash_vec: &mut Vec<i32>, start_index: i32, end_index: i32) {\n\n let range = if end_index > start_index {\n\n end_index - start_index\n\n } else {\n\n HASH_SIZE - start_index + end_index\n\n };\n\n\n\n let actual_end_index = mod_index(end_index - 1);\n\n for i in 0..(range / 2) {\n\n let swap_start = mod_index(start_index + i);\n\n let swap_end = mod_index(actual_end_index - i);\n\n swap(hash_vec, swap_start, swap_end);\n\n }\n\n}\n\n\n", "file_path": "day10/main1.rs", "rank": 34, "score": 176004.78282040748 }, { "content": "fn get_str_representation(hash_vec: &Vec<i32>) -> String {\n\n let mut hash = String::new();\n\n\n\n for byte in hash_vec {\n\n let mut hex_byte: String = format!(\"{:x}\", byte);\n\n if hex_byte.len() == 1 {\n\n hex_byte = \"0\".to_string() + &hex_byte;\n\n }\n\n hash += &hex_byte;\n\n }\n\n return hash;\n\n}\n\n\n", "file_path": "day10/main2.rs", "rank": 35, "score": 169973.5327184545 }, { "content": "fn get_str_representation(hash_vec: &Vec<i32>) -> String {\n\n let mut hash = String::new();\n\n\n\n for byte in hash_vec {\n\n let mut hex_byte: String = format!(\"{:x}\", byte);\n\n if hex_byte.len() == 1 {\n\n hex_byte = \"0\".to_string() + &hex_byte;\n\n }\n\n hash += &hex_byte;\n\n }\n\n return hash;\n\n}\n\n\n", "file_path": "day14/hash.rs", "rank": 36, "score": 169973.5327184545 }, { "content": "fn mod_index(index: i32) -> i32 {\n\n if index >= 0 {\n\n index % HASH_SIZE\n\n } else {\n\n HASH_SIZE + (index % HASH_SIZE)\n\n }\n\n}\n\n\n", "file_path": "day14/hash.rs", "rank": 37, "score": 169520.1206551831 }, { "content": "fn mod_index(index: i32) -> i32 {\n\n if index >= 0 {\n\n index % HASH_SIZE\n\n } else {\n\n HASH_SIZE + (index % HASH_SIZE)\n\n }\n\n}\n\n\n", "file_path": "day10/main2.rs", "rank": 38, "score": 169520.1206551831 }, { "content": "fn mod_index(index: i32) -> i32 {\n\n if index >= 0 {\n\n index % HASH_SIZE\n\n } else {\n\n HASH_SIZE + (index % HASH_SIZE)\n\n }\n\n}\n", "file_path": "day10/main1.rs", "rank": 39, "score": 169520.1206551831 }, { "content": "fn get_resultant_direction((old_r, old_c): (i32, i32), (new_r, new_c): (i32, i32)) -> Direction {\n\n if old_r > new_r {\n\n Direction::Up\n\n } else if old_r < new_r {\n\n Direction::Down\n\n } else {\n\n if old_c < new_c {\n\n Direction::Right\n\n } else if old_c > new_c {\n\n Direction::Left\n\n } else {\n\n panic!(\"old and new are the same!\");\n\n }\n\n }\n\n}\n\n\n", "file_path": "day19/main2.rs", "rank": 40, "score": 167918.85705623828 }, { "content": "fn get_resultant_direction((old_r, old_c): (i32, i32), (new_r, new_c): (i32, i32)) -> Direction {\n\n if old_r > new_r {\n\n Direction::Up\n\n } else if old_r < new_r {\n\n Direction::Down\n\n } else {\n\n if old_c < new_c {\n\n Direction::Right\n\n } else if old_c > new_c {\n\n Direction::Left\n\n } else {\n\n panic!(\"old and new are the same!\");\n\n }\n\n }\n\n}\n\n\n", "file_path": "day19/main1.rs", "rank": 41, "score": 167918.85705623828 }, { "content": "fn reset_layers(layers: &mut HashMap<i32, Layer>) {\n\n for (_, layer) in layers {\n\n layer.cur_pos = 0;\n\n }\n\n}\n", "file_path": "day13/main2.rs", "rank": 42, "score": 166960.14405811962 }, { "content": "fn tick_layers(layers: &mut HashMap<i32, Layer>) {\n\n for (_, layer) in layers {\n\n if layer.is_down {\n\n layer.cur_pos += 1;\n\n if layer.cur_pos == layer.range {\n\n layer.is_down = false;\n\n layer.cur_pos -= 2;\n\n if layer.cur_pos < 0 {\n\n layer.cur_pos = 0;\n\n }\n\n }\n\n } else {\n\n layer.cur_pos -= 1;\n\n if layer.cur_pos < 0 {\n\n layer.is_down = true;\n\n layer.cur_pos = if layer.range > 1 { 1 } else { 0 }\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "day13/main2.rs", "rank": 43, "score": 166960.14405811962 }, { "content": "fn tick_layers(layers: &mut HashMap<i32, Layer>) {\n\n for (_, layer) in layers {\n\n if layer.is_down {\n\n layer.cur_pos += 1;\n\n if layer.cur_pos == layer.range {\n\n layer.is_down = false;\n\n layer.cur_pos -= 2;\n\n if layer.cur_pos < 0 {\n\n layer.cur_pos = 0;\n\n }\n\n }\n\n } else {\n\n layer.cur_pos -= 1;\n\n if layer.cur_pos < 0 {\n\n layer.is_down = true;\n\n layer.cur_pos = if layer.range > 1 { 1 } else { 0 }\n\n }\n\n }\n\n }\n\n}\n", "file_path": "day13/main1.rs", "rank": 44, "score": 166960.14405811962 }, { "content": "fn get_max_min(row: &Vec<i32>) -> (i32, i32) {\n\n let mut max = i32::MIN;\n\n let mut min = i32::MAX;\n\n for val in row {\n\n if *val >= max {\n\n max = *val;\n\n }\n\n if *val <= min {\n\n min = *val;\n\n }\n\n }\n\n return (min, max);\n\n}\n", "file_path": "day2/main.rs", "rank": 45, "score": 165730.91338780517 }, { "content": "fn eval_condition(state: &mut State, condition: &Condition) -> bool {\n\n let register_value = get_register_value(state, condition.register.clone());\n\n let operand = condition.operand;\n\n\n\n match condition.relation {\n\n Relation::LT => return register_value < operand,\n\n Relation::LE => return register_value <= operand,\n\n Relation::GT => return register_value > operand,\n\n Relation::GE => return register_value >= operand,\n\n Relation::EQ => return register_value == operand,\n\n Relation::NE => return register_value != operand,\n\n }\n\n}\n\n\n", "file_path": "day8/main2.rs", "rank": 46, "score": 165090.24362263558 }, { "content": "type Pointer = Rc<RefCell<ProgramTower>>;\n\n\n", "file_path": "day7/main1.rs", "rank": 48, "score": 163028.22886774747 }, { "content": "pub fn read_file_string(fname: &str) -> String {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n return contents;\n\n}\n\n\n", "file_path": "util/util.rs", "rank": 49, "score": 162615.3825473423 }, { "content": "fn get_input() -> Vec<i32> {\n\n let mut bytes = Vec::new();\n\n for byte in INPUT.to_string().as_bytes() {\n\n bytes.push(*byte as i32);\n\n }\n\n\n\n bytes.push(17);\n\n bytes.push(31);\n\n bytes.push(73);\n\n bytes.push(47);\n\n bytes.push(23);\n\n return bytes;\n\n}\n", "file_path": "day10/main2.rs", "rank": 50, "score": 157503.32873332762 }, { "content": "fn get_input(input_str: &str) -> Vec<i32> {\n\n let mut bytes = Vec::new();\n\n for byte in input_str.to_string().as_bytes() {\n\n bytes.push(*byte as i32);\n\n }\n\n\n\n bytes.push(17);\n\n bytes.push(31);\n\n bytes.push(73);\n\n bytes.push(47);\n\n bytes.push(23);\n\n return bytes;\n\n}\n", "file_path": "day14/hash.rs", "rank": 51, "score": 153117.49838314613 }, { "content": "pub fn read_file_string(fname: &str) -> String {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n return contents;\n\n}\n\n\n", "file_path": "day23/util.rs", "rank": 52, "score": 152914.15578535612 }, { "content": "pub fn read_file_string(fname: &str) -> String {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n return contents;\n\n}\n\n\n", "file_path": "day21/util.rs", "rank": 53, "score": 152914.15578535612 }, { "content": "pub fn read_file_string(fname: &str) -> String {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n return contents;\n\n}\n", "file_path": "day8/util.rs", "rank": 54, "score": 152914.15578535612 }, { "content": "pub fn read_file_string(fname: &str) -> String {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n return contents;\n\n}\n\n\n", "file_path": "day22/util.rs", "rank": 55, "score": 152914.15578535612 }, { "content": "pub fn read_file_string(fname: &str) -> String {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n return contents;\n\n}\n\n\n", "file_path": "day20/util.rs", "rank": 56, "score": 152914.15578535612 }, { "content": "pub fn read_file_string(fname: &str) -> String {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n return contents;\n\n}\n", "file_path": "day13/util.rs", "rank": 57, "score": 152914.15578535612 }, { "content": "pub fn read_file_string(fname: &str) -> String {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n return contents;\n\n}\n\n\n", "file_path": "day19/util.rs", "rank": 58, "score": 152914.15578535612 }, { "content": "pub fn read_file_string(fname: &str) -> String {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n return contents;\n\n}\n\n\n", "file_path": "day24/util.rs", "rank": 59, "score": 152914.15578535612 }, { "content": "pub fn read_file_string(fname: &str) -> String {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n return contents;\n\n}\n", "file_path": "day11/util.rs", "rank": 60, "score": 152914.15578535612 }, { "content": "pub fn read_file_string(fname: &str) -> String {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n return contents;\n\n}\n", "file_path": "day9/util.rs", "rank": 61, "score": 152914.15578535612 }, { "content": "pub fn read_file_string(fname: &str) -> String {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n return contents;\n\n}\n", "file_path": "day18/util.rs", "rank": 62, "score": 152914.15578535612 }, { "content": "pub fn read_file_string(fname: &str) -> String {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n return contents;\n\n}\n", "file_path": "day12/util.rs", "rank": 63, "score": 152914.15578535612 }, { "content": "pub fn read_file_string(fname: &str) -> String {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n return contents;\n\n}\n", "file_path": "day16/util.rs", "rank": 64, "score": 152914.15578535612 }, { "content": "fn read_input() -> Vec<Vec<i32>> {\n\n let mut f = File::open(FILE_NAME).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n let mut row = Vec::new();\n\n for num_str in fline.split_whitespace() {\n\n row.push(num_str.parse::<i32>().unwrap());\n\n }\n\n rows.push(row);\n\n }\n\n }\n\n return rows;\n\n}\n\n\n", "file_path": "day2/main2.rs", "rank": 65, "score": 151494.3512720646 }, { "content": "pub fn get_knot_hash(input_string: &str) -> String {\n\n let mut hash_vec = generate_start_vec();\n\n\n\n let mut current_pos = 0;\n\n let mut skip_size = 0;\n\n let input_vec = get_input(input_string);\n\n for _ in 0..64 {\n\n for input in &input_vec {\n\n let start_index = current_pos;\n\n let end_index = mod_index(current_pos + input);\n\n if *input != 0 {\n\n reverse_range(&mut hash_vec, start_index, end_index);\n\n }\n\n current_pos = mod_index(current_pos + input + skip_size);\n\n skip_size += 1;\n\n }\n\n }\n\n\n\n let dense = get_dense_hash(&hash_vec);\n\n get_str_representation(&dense)\n\n}\n\n\n", "file_path": "day14/hash.rs", "rank": 66, "score": 150964.80963733213 }, { "content": "type Rulebook = HashMap<String, String>;\n\n\n", "file_path": "day21/main2.rs", "rank": 67, "score": 148569.02219431562 }, { "content": "type Rulebook = HashMap<String, String>;\n\n\n", "file_path": "day21/main1.rs", "rank": 68, "score": 148569.02219431562 }, { "content": "pub fn read_file_lines(fname: &str) -> Vec<String> {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n rows.push(fline.to_owned());\n\n }\n\n }\n\n return rows;\n\n}\n\n\n", "file_path": "util/util.rs", "rank": 69, "score": 148045.46074232442 }, { "content": "fn main() {\n\n let rows = read_input();\n\n let mut sum = 0;\n\n\n\n for row in rows {\n\n let (min, max) = get_max_min(&row);\n\n let diff = max - min;\n\n sum += diff;\n\n }\n\n println!(\"checksum is: {}\", sum);\n\n}\n\n\n", "file_path": "day2/main.rs", "rank": 70, "score": 145481.05521449872 }, { "content": "fn main() {\n\n println!(\"{}\", get_sum(INPUT.to_owned()));\n\n}\n\n\n", "file_path": "day1/main.rs", "rank": 71, "score": 145481.05521449872 }, { "content": "fn manhattan_distance(a: i64, b: i64, c: i64) -> i64 {\n\n return a.abs() + b.abs() + c.abs();\n\n}\n\n\n", "file_path": "day20/main1.rs", "rank": 72, "score": 142914.63937586147 }, { "content": "fn determine_distance(coords: (i32, i32, i32)) -> i32 {\n\n let (x, y, z) = coords;\n\n let absx = x.abs();\n\n let absy = y.abs();\n\n let absz = z.abs();\n\n\n\n if absx >= absy && absx >= absz {\n\n return absx;\n\n }\n\n if absy >= absx && absy >= absz {\n\n return absy;\n\n }\n\n if absz >= absx && absz >= absy {\n\n return absz;\n\n }\n\n panic!(\"no max found!\");\n\n}\n\n\n", "file_path": "day11/main2.rs", "rank": 73, "score": 142098.2553636477 }, { "content": "fn determine_distance(coords: (i32, i32, i32)) -> i32 {\n\n let (x, y, z) = coords;\n\n let absx = x.abs();\n\n let absy = y.abs();\n\n let absz = z.abs();\n\n\n\n if absx >= absy && absx >= absz {\n\n return absx;\n\n }\n\n if absy >= absx && absy >= absz {\n\n return absy;\n\n }\n\n if absz >= absx && absz >= absy {\n\n return absz;\n\n }\n\n panic!(\"no max found!\");\n\n}\n\n\n", "file_path": "day11/main1.rs", "rank": 74, "score": 142098.2553636477 }, { "content": "fn convert_coords((x, y): (i32, i32)) -> (i32, i32) {\n\n let adjust_coord = |c| {\n\n if c < 0 {\n\n (ARRAY_LENGTH as i32) + c\n\n } else {\n\n c\n\n }\n\n };\n\n\n\n (adjust_coord(x), adjust_coord(y))\n\n}\n\n\n", "file_path": "day3/main2.rs", "rank": 75, "score": 141715.54637991582 }, { "content": "fn convert_coords((x, y): (i32, i32)) -> (i32, i32) {\n\n let adjust_coord = |c| {\n\n if c < 0 {\n\n (ARRAY_LENGTH as i32) + c\n\n } else {\n\n c\n\n }\n\n };\n\n\n\n (adjust_coord(x), adjust_coord(y))\n\n}\n", "file_path": "day3/main1.rs", "rank": 76, "score": 141715.54637991582 }, { "content": "fn get_distance((x, y): (i32, i32)) -> i32 {\n\n i32::abs(x) + i32::abs(y)\n\n}\n\n\n", "file_path": "day3/main1.rs", "rank": 77, "score": 139727.982491264 }, { "content": "pub fn read_file_lines(fname: &str) -> Vec<String> {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n rows.push(fline.to_owned());\n\n }\n\n }\n\n return rows;\n\n}\n", "file_path": "day7/util.rs", "rank": 78, "score": 138227.48410253483 }, { "content": "pub fn read_file_lines(fname: &str) -> Vec<String> {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n rows.push(fline.to_owned());\n\n }\n\n }\n\n return rows;\n\n}\n\n\n", "file_path": "day19/util.rs", "rank": 79, "score": 138227.48410253483 }, { "content": "pub fn read_file_lines(fname: &str) -> Vec<String> {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n rows.push(fline.to_owned());\n\n }\n\n }\n\n return rows;\n\n}\n\n\n", "file_path": "day8/util.rs", "rank": 80, "score": 138227.48410253483 }, { "content": "pub fn read_file_lines(fname: &str) -> Vec<String> {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n rows.push(fline.to_owned());\n\n }\n\n }\n\n return rows;\n\n}\n\n\n", "file_path": "day16/util.rs", "rank": 81, "score": 138227.48410253483 }, { "content": "pub fn read_file_lines(fname: &str) -> Vec<String> {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n rows.push(fline.to_owned());\n\n }\n\n }\n\n return rows;\n\n}\n", "file_path": "day5/util.rs", "rank": 82, "score": 138227.48410253483 }, { "content": "pub fn read_file_lines(fname: &str) -> Vec<String> {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n rows.push(fline.to_owned());\n\n }\n\n }\n\n return rows;\n\n}\n\n\n", "file_path": "day12/util.rs", "rank": 83, "score": 138227.48410253483 }, { "content": "pub fn read_file_lines(fname: &str) -> Vec<String> {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n rows.push(fline.to_owned());\n\n }\n\n }\n\n return rows;\n\n}\n\n\n", "file_path": "day9/util.rs", "rank": 84, "score": 138227.48410253483 }, { "content": "pub fn read_file_lines(fname: &str) -> Vec<String> {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n rows.push(fline.to_owned());\n\n }\n\n }\n\n return rows;\n\n}\n\n\n", "file_path": "day21/util.rs", "rank": 85, "score": 138227.48410253483 }, { "content": "pub fn read_file_lines(fname: &str) -> Vec<String> {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n rows.push(fline.to_owned());\n\n }\n\n }\n\n return rows;\n\n}\n\n\n", "file_path": "day22/util.rs", "rank": 86, "score": 138227.48410253483 }, { "content": "pub fn read_file_lines(fname: &str) -> Vec<String> {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n rows.push(fline.to_owned());\n\n }\n\n }\n\n return rows;\n\n}\n\n\n", "file_path": "day18/util.rs", "rank": 87, "score": 138227.48410253483 }, { "content": "pub fn read_file_lines(fname: &str) -> Vec<String> {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n rows.push(fline.to_owned());\n\n }\n\n }\n\n return rows;\n\n}\n\n\n", "file_path": "day13/util.rs", "rank": 88, "score": 138227.48410253483 }, { "content": "pub fn read_file_lines(fname: &str) -> Vec<String> {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n rows.push(fline.to_owned());\n\n }\n\n }\n\n return rows;\n\n}\n", "file_path": "day4/util.rs", "rank": 89, "score": 138227.48410253483 }, { "content": "pub fn read_file_lines(fname: &str) -> Vec<String> {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n rows.push(fline.to_owned());\n\n }\n\n }\n\n return rows;\n\n}\n\n\n", "file_path": "day11/util.rs", "rank": 90, "score": 138227.48410253483 }, { "content": "pub fn read_file_lines(fname: &str) -> Vec<String> {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n rows.push(fline.to_owned());\n\n }\n\n }\n\n return rows;\n\n}\n\n\n", "file_path": "day23/util.rs", "rank": 91, "score": 138227.48410253483 }, { "content": "pub fn read_file_lines(fname: &str) -> Vec<String> {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n rows.push(fline.to_owned());\n\n }\n\n }\n\n return rows;\n\n}\n\n\n", "file_path": "day24/util.rs", "rank": 92, "score": 138227.48410253483 }, { "content": "pub fn read_file_lines(fname: &str) -> Vec<String> {\n\n let mut f = File::open(fname).unwrap();\n\n\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents).unwrap();\n\n\n\n let mut rows = Vec::new();\n\n\n\n for fline in contents.lines() {\n\n if !fline.is_empty() {\n\n rows.push(fline.to_owned());\n\n }\n\n }\n\n return rows;\n\n}\n\n\n", "file_path": "day20/util.rs", "rank": 93, "score": 138227.48410253483 }, { "content": "fn move_hex(coords: (i32, i32, i32), dir: Direction) -> (i32, i32, i32) {\n\n let (x, y, z) = coords;\n\n match dir {\n\n Direction::N => (x, y + 1, z - 1),\n\n Direction::NE => (x + 1, y, z - 1),\n\n Direction::NW => (x - 1, y + 1, z),\n\n Direction::S => (x, y - 1, z + 1),\n\n Direction::SE => (x + 1, y - 1, z),\n\n Direction::SW => (x - 1, y, z + 1),\n\n }\n\n}\n\n\n", "file_path": "day11/main2.rs", "rank": 94, "score": 138000.8169065971 }, { "content": "fn move_hex(coords: (i32, i32, i32), dir: Direction) -> (i32, i32, i32) {\n\n let (x, y, z) = coords;\n\n match dir {\n\n Direction::N => (x, y + 1, z - 1),\n\n Direction::NE => (x + 1, y, z - 1),\n\n Direction::NW => (x - 1, y + 1, z),\n\n Direction::S => (x, y - 1, z + 1),\n\n Direction::SE => (x + 1, y - 1, z),\n\n Direction::SW => (x - 1, y, z + 1),\n\n }\n\n}\n\n\n", "file_path": "day11/main1.rs", "rank": 95, "score": 138000.8169065971 }, { "content": "fn alphabetize(word: String) -> String {\n\n let mut bytes = word.into_bytes();\n\n bytes.sort_unstable();\n\n\n\n String::from_utf8(bytes).unwrap()\n\n}\n\n\n", "file_path": "day4/main2.rs", "rank": 96, "score": 137921.36911500798 }, { "content": "fn main() {\n\n let mut blocks: [i32; ARRAY_SIZE] = [5, 1, 10, 0, 1, 7, 13, 14, 3, 12, 8, 10, 7, 12, 0, 6];\n\n\n\n let mut seen_blocks: HashSet<[i32; ARRAY_SIZE]> = HashSet::new();\n\n seen_blocks.insert(blocks);\n\n let mut num_iterations = 0;\n\n\n\n loop {\n\n let max_idx = get_max_index(&blocks);\n\n let mut distribution = blocks[max_idx];\n\n blocks[max_idx] = 0;\n\n let mut i = (max_idx + 1) % ARRAY_SIZE;\n\n\n\n while distribution > 0 {\n\n blocks[i] += 1;\n\n distribution -= 1;\n\n i += 1;\n\n i %= ARRAY_SIZE;\n\n }\n\n num_iterations += 1;\n\n let seen_before = seen_blocks.insert(blocks);\n\n if seen_before == false {\n\n break;\n\n }\n\n }\n\n println!(\"number of iterations is: {}\", num_iterations);\n\n}\n\n\n", "file_path": "day6/main1.rs", "rank": 97, "score": 137079.6701465652 }, { "content": "fn main() {\n\n let input = parse_input();\n\n let tower = create_tower(input);\n\n println!(\"root is: {}\", tower.borrow().name);\n\n}\n\n\n", "file_path": "day7/main1.rs", "rank": 98, "score": 137079.6701465652 }, { "content": "fn main() {\n\n let mut blocks: [i32; ARRAY_SIZE] = [5, 1, 10, 0, 1, 7, 13, 14, 3, 12, 8, 10, 7, 12, 0, 6];\n\n\n\n let mut seen_blocks: HashMap<[i32; ARRAY_SIZE], i32> = HashMap::new();\n\n seen_blocks.insert(blocks, 0);\n\n let mut num_iterations = 0;\n\n\n\n loop {\n\n let max_idx = get_max_index(&blocks);\n\n let mut distribution = blocks[max_idx];\n\n blocks[max_idx] = 0;\n\n let mut i = (max_idx + 1) % ARRAY_SIZE;\n\n\n\n while distribution > 0 {\n\n blocks[i] += 1;\n\n distribution -= 1;\n\n i += 1;\n\n i %= ARRAY_SIZE;\n\n }\n\n num_iterations += 1;\n", "file_path": "day6/main2.rs", "rank": 99, "score": 137079.6701465652 } ]
Rust
sdk/data_cosmos/src/operations/get_collection.rs
adeschamps/azure-sdk-for-rust
027f111683f02fd1c43bc041ac6902e87edc69d8
use crate::prelude::*; use crate::headers::from_headers::*; use azure_core::headers::{ content_type_from_headers, etag_from_headers, session_token_from_headers, }; use azure_core::{collect_pinned_stream, Context, Response as HttpResponse}; use chrono::{DateTime, Utc}; #[derive(Debug, Clone)] pub struct GetCollectionBuilder { client: CollectionClient, consistency_level: Option<ConsistencyLevel>, context: Context, } impl GetCollectionBuilder { pub(crate) fn new(client: CollectionClient) -> Self { Self { client, consistency_level: None, context: Context::new(), } } setters! { consistency_level: ConsistencyLevel => Some(consistency_level), context: Context => context, } pub fn into_future(self) -> GetCollection { Box::pin(async move { let mut request = self .client .prepare_request_with_collection_name(http::Method::GET); azure_core::headers::add_optional_header2(&self.consistency_level, &mut request)?; let response = self .client .pipeline() .send( self.context.clone().insert(ResourceType::Collections), &mut request, ) .await?; GetCollectionResponse::try_from(response).await }) } } pub type GetCollection = futures::future::BoxFuture<'static, crate::Result<GetCollectionResponse>>; #[cfg(feature = "into_future")] impl std::future::IntoFuture for GetCollectionBuilder { type Future = GetCollection; type Output = <GetCollection as std::future::Future>::Output; fn into_future(self) -> Self::Future { Self::into_future(self) } } #[derive(Debug, Clone)] pub struct GetCollectionResponse { pub collection: Collection, pub last_state_change: DateTime<Utc>, pub etag: String, pub collection_partition_index: u64, pub collection_service_index: u64, pub lsn: u64, pub schema_version: String, pub alt_content_path: String, pub content_path: String, pub global_committed_lsn: u64, pub number_of_read_regions: u32, pub item_lsn: u64, pub transport_request_id: u64, pub cosmos_llsn: u64, pub cosmos_item_llsn: u64, pub charge: f64, pub service_version: String, pub activity_id: uuid::Uuid, pub session_token: String, pub gateway_version: String, pub server: String, pub xp_role: u32, pub content_type: String, pub content_location: String, pub date: DateTime<Utc>, } impl GetCollectionResponse { pub async fn try_from(response: HttpResponse) -> crate::Result<Self> { let (_status_code, headers, pinned_stream) = response.deconstruct(); let body = collect_pinned_stream(pinned_stream).await?; Ok(Self { collection: serde_json::from_slice(&body)?, last_state_change: last_state_change_from_headers(&headers)?, etag: etag_from_headers(&headers)?, collection_partition_index: collection_partition_index_from_headers(&headers)?, collection_service_index: collection_service_index_from_headers(&headers)?, lsn: lsn_from_headers(&headers)?, schema_version: schema_version_from_headers(&headers)?.to_owned(), alt_content_path: alt_content_path_from_headers(&headers)?.to_owned(), content_path: content_path_from_headers(&headers)?.to_owned(), global_committed_lsn: global_committed_lsn_from_headers(&headers)?, number_of_read_regions: number_of_read_regions_from_headers(&headers)?, item_lsn: item_lsn_from_headers(&headers)?, transport_request_id: transport_request_id_from_headers(&headers)?, cosmos_llsn: cosmos_llsn_from_headers(&headers)?, cosmos_item_llsn: cosmos_item_llsn_from_headers(&headers)?, charge: request_charge_from_headers(&headers)?, service_version: service_version_from_headers(&headers)?.to_owned(), activity_id: activity_id_from_headers(&headers)?, session_token: session_token_from_headers(&headers)?, gateway_version: gateway_version_from_headers(&headers)?.to_owned(), server: server_from_headers(&headers)?.to_owned(), xp_role: role_from_headers(&headers)?, content_type: content_type_from_headers(&headers)?.to_owned(), content_location: content_location_from_headers(&headers)?.to_owned(), date: date_from_headers(&headers)?, }) } }
use crate::prelude::*; use crate::headers::from_headers::*; use azure_core::headers::{ content_type_from_headers, etag_from_headers, session_token_from_headers, }; use azure_core::{collect_pinned_stream, Context, Response as HttpResponse}; use chrono::{DateTime, Utc}; #[derive(Debug, Clone)] pub struct GetCollectionBuilder { client: CollectionClient, consistency_level: Option<ConsistencyLevel>, context: Context, } impl GetCollectionBuilder { pub(crate) fn new(client: CollectionClient) -> Self { Self { client, consistency_level: None, context: Context::new(), } } setters! { consistency_level: ConsistencyLevel => Some(consistency_level), context: Context => context, } pub fn into_future(self) -> GetCollection { Box::pin(async move { let mut request = self .client .prepare_request_with_collection_name(http::Method::GET); azure_core::headers::add_optional_header2(&self.consistency_level, &mut request)?; let response = self .client .pipeline() .send( self.context.clone().insert(ResourceType::Collections), &mut request, ) .await?; GetCollectionResponse::try_from(response).await }) } } pub type GetCollection = futures::future::BoxFuture<'static, crate::Result<GetCollectionResponse>>; #[cfg(feature = "into_future")] impl std::future::IntoFuture for GetCollectionBuilder { type Future = GetCollection; type Output = <GetCollection as std::future::Future>::Output; fn into_future(self) -> Self::Future { Self::into_future(self) } } #[derive(Debug, Clone)] pub struct GetCollectionResponse { pub collection: Collection, pub last_state_change: DateTime<Utc>, pub etag: String, pub collection_partition_index: u64, pub collection_service_index: u64, pub lsn: u64, pub schema_version: String, pub alt_content_path: String, pub content_path: String, pub global_committed_lsn: u64, pub number_of_read_regions: u32, pub item_lsn: u64, pub transport_request_id: u64, pub cosmos_llsn: u64, pub cosmos_item_llsn: u64, pub charge: f64, pub service_version: String, pub activity_id: uuid::Uuid, pub session_token: String, pub gateway_version: String, pub server: String, pub xp_role: u32, pub content_type: String, pub content_location: String, pub date: DateTime<Utc>, } impl GetCollectionResponse { pub async fn try_from(response: HttpResponse) -> crate::Result<Self> { let (_status_code, headers, pinned_stream) = response.deconstruct(); let body = collect_pinned_stream(pinned_stream).await?;
} }
Ok(Self { collection: serde_json::from_slice(&body)?, last_state_change: last_state_change_from_headers(&headers)?, etag: etag_from_headers(&headers)?, collection_partition_index: collection_partition_index_from_headers(&headers)?, collection_service_index: collection_service_index_from_headers(&headers)?, lsn: lsn_from_headers(&headers)?, schema_version: schema_version_from_headers(&headers)?.to_owned(), alt_content_path: alt_content_path_from_headers(&headers)?.to_owned(), content_path: content_path_from_headers(&headers)?.to_owned(), global_committed_lsn: global_committed_lsn_from_headers(&headers)?, number_of_read_regions: number_of_read_regions_from_headers(&headers)?, item_lsn: item_lsn_from_headers(&headers)?, transport_request_id: transport_request_id_from_headers(&headers)?, cosmos_llsn: cosmos_llsn_from_headers(&headers)?, cosmos_item_llsn: cosmos_item_llsn_from_headers(&headers)?, charge: request_charge_from_headers(&headers)?, service_version: service_version_from_headers(&headers)?.to_owned(), activity_id: activity_id_from_headers(&headers)?, session_token: session_token_from_headers(&headers)?, gateway_version: gateway_version_from_headers(&headers)?.to_owned(), server: server_from_headers(&headers)?.to_owned(), xp_role: role_from_headers(&headers)?, content_type: content_type_from_headers(&headers)?.to_owned(), content_location: content_location_from_headers(&headers)?.to_owned(), date: date_from_headers(&headers)?, })
call_expression
[]
Rust
libchordr/src/test_helpers.rs
chorddown/chordr
f28327dfd2d026076d557a926ca8a33063af82fc
use crate::models::meta::BNotation; use crate::models::user::{User, Username}; use crate::parser::{MetaInformation, Node}; use crate::prelude::Password; use crate::tokenizer::{Modifier, Token}; #[cfg(test)] pub fn get_test_parser_input() -> Vec<Token> { vec![ Token::headline(1, "Swing Low Sweet Chariot", Modifier::None), Token::newline(), Token::headline(2, "Chorus", Modifier::Chorus), Token::literal("Swing "), Token::chord("D"), Token::literal("low, sweet "), Token::chord("G"), Token::literal("chari"), Token::chord("D"), Token::literal("ot,"), Token::literal("Comin’ for to carry me "), Token::chord("A7"), Token::literal("home."), Token::literal("Swing "), Token::chord("D7"), Token::headline(2, "Verse", Modifier::None), Token::chord("E"), Token::literal("low, sweet "), Token::chord("G"), Token::literal("chari"), Token::chord("D"), Token::literal("ot,"), Token::chord("E"), Token::chord("A"), Token::newline(), Token::chord("B"), Token::chord("H"), ] } pub fn get_test_tokens() -> Vec<Token> { vec![ Token::headline(1, "Swing Low Sweet Chariot", Modifier::None), Token::newline(), Token::newline(), Token::headline(2, "Chorus", Modifier::Chorus), Token::newline(), Token::literal("Swing "), Token::chord("D"), Token::literal("low, sweet "), Token::chord("G"), Token::literal("chari"), Token::chord("D"), Token::literal("ot,"), Token::newline(), Token::literal("Comin’ for to carry me "), Token::chord("A7"), Token::literal("home."), Token::newline(), Token::literal("Swing "), Token::chord("D7"), Token::literal("low, sweet "), Token::chord("G"), Token::literal("chari"), Token::chord("D"), Token::literal("ot,"), Token::newline(), Token::literal("Comin’ for to "), Token::chord("A7"), Token::literal("carry me "), Token::chord("D"), Token::literal("home."), Token::newline(), Token::newline(), Token::newline(), Token::headline(2, "Verse 1", Modifier::None), Token::newline(), Token::newline(), Token::literal("I "), Token::chord("D"), Token::literal("looked over Jordan, and "), Token::chord("G"), Token::literal("what did I "), Token::chord("D"), Token::literal("see,"), Token::newline(), Token::literal("Comin’ for to carry me "), Token::chord("A7"), Token::literal("home."), Token::newline(), Token::literal("A "), Token::chord("D"), Token::literal("band of angels "), Token::chord("G"), Token::literal("comin’ after "), Token::chord("D"), Token::literal("me,"), Token::newline(), Token::literal("Comin’ for to "), Token::chord("A7"), Token::literal("carry me "), Token::chord("D"), Token::literal("home."), Token::newline(), Token::newline(), Token::quote("Chorus"), Token::newline(), ] } pub fn get_test_ast() -> Node { Node::Document(vec![ Node::section( 1, "Swing Low Sweet Chariot", Modifier::None, vec![Node::newline()], ), Node::section( 2, "Chorus", Modifier::Chorus, vec![ Node::newline(), Node::text("Swing "), Node::chord_text_pair("D", "low, sweet ").unwrap(), Node::chord_text_pair("G", "chari").unwrap(), Node::chord_text_pair_last_in_line("D", "ot,").unwrap(), Node::newline(), Node::text("Comin’ for to carry me "), Node::chord_text_pair_last_in_line("A7", "home.").unwrap(), Node::newline(), Node::text("Swing "), Node::chord_text_pair("D7", "low, sweet ").unwrap(), Node::chord_text_pair("G", "chari").unwrap(), Node::chord_text_pair_last_in_line("D", "ot,").unwrap(), Node::newline(), Node::text("Comin’ for to "), Node::chord_text_pair("A7", "carry me ").unwrap(), Node::chord_text_pair_last_in_line("D", "home.").unwrap(), Node::newline(), ], ), Node::section( 2, "Verse 1", Modifier::None, vec![ Node::newline(), Node::text("I "), Node::chord_text_pair("D", "looked over Jordan, and ").unwrap(), Node::chord_text_pair("G", "what did I ").unwrap(), Node::chord_text_pair_last_in_line("D", "see,").unwrap(), Node::newline(), Node::text("Comin’ for to carry me "), Node::chord_text_pair_last_in_line("A7", "home.").unwrap(), Node::newline(), Node::text("A "), Node::chord_text_pair("D", "band of angels ").unwrap(), Node::chord_text_pair("G", "comin’ after ").unwrap(), Node::chord_text_pair_last_in_line("D", "me,").unwrap(), Node::newline(), Node::text("Comin’ for to "), Node::chord_text_pair("A7", "carry me ").unwrap(), Node::chord_text_pair_last_in_line("D", "home.").unwrap(), Node::newline(), ], ), Node::quote("Chorus"), Node::newline(), ]) } pub fn get_test_ast_with_quote() -> Node { Node::Document(vec![ Node::section( 1, "Swing Low Sweet Chariot", Modifier::None, vec![Node::newline()], ), Node::quote("Play slowly"), Node::newline(), Node::section( 2, "Chorus", Modifier::Chorus, vec![ Node::newline(), Node::text("Swing "), Node::chord_text_pair("D", "low, sweet ").unwrap(), Node::chord_text_pair("G", "chari").unwrap(), Node::chord_text_pair("D", "ot.").unwrap(), ], ), ]) } pub fn get_test_ast_w_inline_metadata() -> Node { Node::Document(vec![ Node::section( 1, "Swing Low Sweet Chariot", Modifier::None, vec![Node::newline()], ), Node::meta("Artist: The Fantastic Corns").unwrap(), Node::newline(), Node::meta("Composer: Daniel Corn").unwrap(), Node::newline(), Node::section( 2, "Chorus", Modifier::Chorus, vec![ Node::newline(), Node::text("Swing "), Node::chord_text_pair("D", "low, sweet ").unwrap(), Node::chord_text_pair("G", "chari").unwrap(), Node::chord_text_pair("D", "ot.").unwrap(), ], ), ]) } pub fn get_test_metadata() -> MetaInformation { MetaInformation { title: Some("Great new song".to_owned()), subtitle: Some("Originally known as 'Swing low sweet chariot'".to_owned()), artist: Some("Me".to_owned()), composer: Some("Wallace Willis".to_owned()), lyricist: Some("Wallace Willis".to_owned()), copyright: None, album: None, year: Some("1865".to_owned()), key: None, key_raw: None, original_key: None, original_key_raw: None, time: None, tempo: None, duration: None, capo: Some("1".to_owned()), original_title: None, alternative_title: None, ccli_song_id: None, b_notation: BNotation::B, } } pub fn get_test_user() -> User { User::new( Username::new("my-username").unwrap(), "Daniel".to_string(), "Corn".to_string(), Password::new("mypass123").unwrap(), ) }
use crate::models::meta::BNotation; use crate::models::user::{User, Username}; use crate::parser::{MetaInformation, Node}; use crate::prelude::Password; use crate::tokenizer::{Modifier, Token}; #[cfg(test)] pub fn get_test_parser_input() -> Vec<Token> { vec![ Token::headline(1, "Swing Low Sweet Chariot", Modifier::None), Token::newline(), Token::headline(2, "Chorus", Modifier::Chorus), Token::literal("Swing "), Token::chord("D"), Token::literal("low, sweet "), Token::chord("G"), Token::literal("chari"), Token::chord("D"), Token::literal("ot,"), Token::literal("Comin’ for to carry me "), Token::chord("A7"), Token::literal("home."), Token::literal("Swing "), Token::chord("D7"), Token::headline(2, "Verse", Modifier::None), Token::chord("E"), Token::literal("low, sweet "), Token::chord("G"), Token::literal("chari"), Token::chord("D"), Token::literal("ot,"), Token::chord("E"), Token::chord("A"), Token::newline(), Token::chord("B"), Token::chord("H"), ] } pub fn get_test_tokens() -> Vec<Token> { vec![ Token::headline(1, "Swing Low Sweet Chariot", Modifier::None), Token::newline(), Token::newline(), Token::headline(2, "Chorus", Modifier::Chorus), Token::newline(), Token::literal("Swing "), Token::chord("D"), Token::literal("low, sweet "), Token::chord("G"), Token::literal("chari"), Token::chord("D"), Token::literal("ot,"), Token::newline(), Token::literal("Comin’ for to carry me "), Token::chord("A7"), Token::literal("home."), Token::newline(), Token::literal("Swing "), Token::chord("D7"), Token::literal("low, sweet "), Token::chord("G"), Token::literal("chari"), Token::chord("D"), Token::literal("ot,"), Token::newline(), Token::literal("Comin’ for to "), Token::chord("A7"), Token::literal("carry me "), Token::chord("D"), Token::literal("home."), Token::newline(), Token::newline(), Token::newline(), Token::headline(2, "Verse 1", Modifier::None), Token::newline(), Token::newline(), Token::literal("I "), Token::chord("D"), Token::literal("looked over Jordan, and "), Token::chord("G"), Token::literal("what did I "), Token::chord("D"), Token::literal("see,"), Token::newline(), Token::literal("Comin’ for to carry me "), Token::chord("A7"), Token::literal("home."), Token::newline(), Token::literal("A "), Token::chord("D"), Token::literal("band of angels "), Token::chord("G"), Token::literal("comin’ after "), Token::chord("D"), Token::literal("me,"), Token::newline(), Token::literal("Comin’ for to "), Token::chord("A7"), Token::literal("carry me "), Token::chord("D"), Token::literal("home."), Token::newline(), Token::newline(), Token::quote("Chorus"), Token::newline(), ] } pub fn get_test_ast() -> Node { Node::Document(vec![ Node::section( 1, "Swing Low Sweet Chariot", Modifier::None, vec![Node::newline()], ), Node::section( 2, "Chorus", Modifier::Chorus, vec![ Node::newline(), Node::text("Swing "), Node::chord_text_pair("D", "low, sweet ").unwrap(), Node::chord_text_pair("G", "chari").unwrap(), Node::chord_text_pair_last_in_line("D", "ot,").unwrap(), Node::newline(), Node::text("Comin’ for to carry me "), Node::chord_text_pair_last_in_line("A7", "home.").unwrap(), Node::newline(), Node::text("Swing "), Node::chord_text_pair("D7", "low, sweet ").unwrap(), Node::chord_text_pair("G", "chari").unwrap(), Node::chord_text_pair_last_in_line("D", "ot,").unwrap(), Node::newline(), Node::text("Comin’ for to "), Node::chord_text_pair("A7", "carry me ").unwrap(), Node::chord_text_pair_last_in_line("D", "home.").unwrap(), Node::newline(), ], ), Node::section( 2, "Verse 1", Modifier::None, vec![ Node::newline(), Node::text("I "), Node::chord_text_pair("D", "looked over Jordan, and ").unwrap(), Node::chord_text_pair("G", "what did I ").unwrap(), Node::chord_text_pair_last_in_line("D", "see,").unwrap(), Node::newline(), Node::text("Comin’ for to carry me "), Node::chord_text_pair_last_in_line("A7", "home.").unwrap(), Node::newline(), Node::text("A "), Node::chord_text_pair("D", "band of angels ").unwrap(), Node::chord_text_pair("G", "comin’ after ").unwrap(), Node::chord_text_pair_last_in_line("D", "me,").unwrap(), Node::newline(), Node::text("Comin’ for to "), Node::chord_text_pair("A7", "carry me ").unwrap(), Node::chord_text_pair_last_in_line("D", "home.").unwrap(), Node::newline(), ], ), Node::quote("Chorus"), Node::newline(), ]) } pub fn get_test_ast_with_quote() -> Node { Node::Document(vec![ Node::section( 1, "Swing Low Sweet Chariot", Modifier::None, vec![Node::newline()], ), Node::quote("Play slowly"), Node::newline(), Node::section( 2, "Chorus",
pub fn get_test_ast_w_inline_metadata() -> Node { Node::Document(vec![ Node::section( 1, "Swing Low Sweet Chariot", Modifier::None, vec![Node::newline()], ), Node::meta("Artist: The Fantastic Corns").unwrap(), Node::newline(), Node::meta("Composer: Daniel Corn").unwrap(), Node::newline(), Node::section( 2, "Chorus", Modifier::Chorus, vec![ Node::newline(), Node::text("Swing "), Node::chord_text_pair("D", "low, sweet ").unwrap(), Node::chord_text_pair("G", "chari").unwrap(), Node::chord_text_pair("D", "ot.").unwrap(), ], ), ]) } pub fn get_test_metadata() -> MetaInformation { MetaInformation { title: Some("Great new song".to_owned()), subtitle: Some("Originally known as 'Swing low sweet chariot'".to_owned()), artist: Some("Me".to_owned()), composer: Some("Wallace Willis".to_owned()), lyricist: Some("Wallace Willis".to_owned()), copyright: None, album: None, year: Some("1865".to_owned()), key: None, key_raw: None, original_key: None, original_key_raw: None, time: None, tempo: None, duration: None, capo: Some("1".to_owned()), original_title: None, alternative_title: None, ccli_song_id: None, b_notation: BNotation::B, } } pub fn get_test_user() -> User { User::new( Username::new("my-username").unwrap(), "Daniel".to_string(), "Corn".to_string(), Password::new("mypass123").unwrap(), ) }
Modifier::Chorus, vec![ Node::newline(), Node::text("Swing "), Node::chord_text_pair("D", "low, sweet ").unwrap(), Node::chord_text_pair("G", "chari").unwrap(), Node::chord_text_pair("D", "ot.").unwrap(), ], ), ]) }
function_block-function_prefix_line
[ { "content": "#[deprecated(note = \"Please use the `Token`s directly\")]\n\npub fn token_lines_to_tokens(token_lines: Vec<Vec<Token>>) -> Vec<Token> {\n\n let mut stream = vec![];\n\n for line in token_lines {\n\n for token in line {\n\n stream.push(token);\n\n }\n\n }\n\n\n\n stream\n\n}\n\n\n", "file_path": "libchordr/src/helper.rs", "rank": 0, "score": 289176.27869682375 }, { "content": "fn parse(test_tokens: Vec<Token>) -> () {\n\n let mut parser = Parser::new();\n\n assert!(parser.parse(test_tokens).is_ok());\n\n}\n\n\n", "file_path": "libchordr/benches/parse_benchmark.rs", "rank": 4, "score": 209053.47012053232 }, { "content": "fn token_is_start_of_section(token: &Token) -> bool {\n\n matches!(\n\n token,\n\n Token::Headline {\n\n level: _,\n\n text: _,\n\n modifier: _,\n\n } | Token::Quote(_)\n\n )\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::test_helpers::{get_test_ast, get_test_tokens};\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn test_parse() {\n\n let mut parser = NodeParser::with_b_notation(BNotation::B);\n\n let result = parser.parse(get_test_tokens());\n\n\n\n assert!(result.is_ok());\n\n let ast = result.unwrap();\n\n\n\n assert_eq!(ast, get_test_ast());\n\n }\n\n}\n", "file_path": "libchordr/src/parser/node_parser.rs", "rank": 7, "score": 189829.90832422575 }, { "content": "pub fn get_routes() -> Vec<rocket::Route> {\n\n routes![\n\n crate::routes::setlist::setlist_index,\n\n crate::routes::setlist::setlist_list,\n\n crate::routes::setlist::setlist_get,\n\n crate::routes::setlist::setlist_get_latest,\n\n crate::routes::setlist::setlist_put,\n\n crate::routes::setlist::setlist_delete\n\n ]\n\n}\n\n\n\n#[get(\"/\")]\n\npub async fn setlist_index(conn: DbConn) -> Json<Vec<Setlist>> {\n\n conn.run(move |conn| Json(SetlistRepository::new().find_all(conn).unwrap()))\n\n .await\n\n}\n\n\n\n#[get(\"/<username>\")]\n\npub async fn setlist_list(\n\n username: String,\n", "file_path": "srvchord/src/routes/setlist.rs", "rank": 8, "score": 188444.90731500616 }, { "content": "pub fn get_routes() -> Vec<rocket::Route> {\n\n routes![crate::routes::status::index,]\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n\npub struct Status {\n\n version: &'static str,\n\n running: bool,\n\n}\n\n\n", "file_path": "srvchord/src/routes/status.rs", "rank": 9, "score": 188444.90731500616 }, { "content": "pub fn get_routes() -> Vec<rocket::Route> {\n\n routes![crate::routes::user::index, crate::routes::user::data,]\n\n}\n\n\n", "file_path": "srvchord/src/routes/user.rs", "rank": 10, "score": 188444.90731500616 }, { "content": "/// Build a new Tokenizer instance\n\npub fn build_tokenizer() -> impl Tokenizer {\n\n ChorddownTokenizer::new()\n\n}\n", "file_path": "libchordr/src/tokenizer/mod.rs", "rank": 11, "score": 184263.09191139753 }, { "content": "/// Return the indexes for the given [Song]s\n\npub fn build_indexes(songs: Vec<&Song>, root_chars: &str) -> Vec<Index> {\n\n let prefix_length = root_chars.len() + 1;\n\n let indexes: Vec<String> = songs\n\n .iter()\n\n .map(|s| get_prefix(s.title(), prefix_length))\n\n .collect();\n\n // indexes.sort();\n\n\n\n let mut map: BTreeMap<String, Index> = BTreeMap::new();\n\n for chars in indexes {\n\n match map.get_mut(&chars) {\n\n Some(mut index) => {\n\n index.count += 1;\n\n }\n\n None if chars.is_empty() => { /* do nothing */ }\n\n None => {\n\n map.insert(chars.clone(), Index::new(chars.clone(), 1));\n\n }\n\n }\n\n }\n\n\n\n map.values().cloned().collect()\n\n}\n\n\n", "file_path": "webchordr/song-browser/src/index.rs", "rank": 12, "score": 180552.50374686634 }, { "content": "fn convert_to_html(node: Node) -> () {\n\n let converter = Converter::get_converter(Format::HTML);\n\n assert!(converter\n\n .convert(&node, &get_test_metadata(), Formatting::default())\n\n .is_ok());\n\n}\n\n\n", "file_path": "libchordr/benches/converter_benchmark.rs", "rank": 13, "score": 155769.61348870795 }, { "content": "fn convert_to_text(node: Node) -> () {\n\n let converter = Converter::get_converter(Format::Text);\n\n assert!(converter\n\n .convert(&node, &get_test_metadata(), Formatting::default())\n\n .is_ok());\n\n}\n\n\n", "file_path": "libchordr/benches/converter_benchmark.rs", "rank": 14, "score": 155769.61348870795 }, { "content": "fn convert_to_chorddown(node: Node) -> () {\n\n let converter = Converter::get_converter(Format::Chorddown);\n\n assert!(converter\n\n .convert(&node, &get_test_metadata(), Formatting::default())\n\n .is_ok());\n\n}\n\n\n", "file_path": "libchordr/benches/converter_benchmark.rs", "rank": 15, "score": 155769.61348870795 }, { "content": "pub fn parse_propfind_response<R: Read>(read: R) -> Result<Vec<TempFileEntry>> {\n\n #[derive(Debug, PartialEq)]\n\n enum Field {\n\n Href,\n\n LastModified,\n\n Size,\n\n ResourceType,\n\n Ignored,\n\n }\n\n\n\n #[derive(Debug)]\n\n enum State {\n\n Items,\n\n Item {\n\n item: TempFileEntry,\n\n field: Option<Field>,\n\n },\n\n Start,\n\n End,\n\n }\n", "file_path": "synchord/src/service/web_dav_service/propfind_parser.rs", "rank": 16, "score": 149594.78460469638 }, { "content": "pub fn json_format<T: Into<JsonTemplateValue>>(format: &str, values: Vec<T>) -> String {\n\n let mut output = format.to_owned();\n\n for value in values {\n\n output = output.replacen(\"$\", &value.into().to_string(), 1);\n\n }\n\n\n\n output\n\n}\n", "file_path": "srvchord/src/test_helpers/json_formatting.rs", "rank": 17, "score": 148035.87294858534 }, { "content": "pub fn download(\n\n service: &Services,\n\n service_config: &AbstractServiceConfig,\n\n) -> Result<Vec<FileEntry>> {\n\n let files = service.list_files()?;\n\n if files.is_empty() {\n\n info!(\"No files found\");\n\n }\n\n for file in &files {\n\n let destination = destination_for_file(&file.path(), service_config)?;\n\n if let Err(e) = check_if_should_download(file, &destination) {\n\n warn!(\"Skip download file {}: {}\", file.path(), e)\n\n } else {\n\n match service.download(file.clone(), &destination) {\n\n Ok(_) => info!(\"Downloaded file {}\", file.path()),\n\n Err(e) => error!(\"Could not download file {}: {}\", file.path(), e),\n\n }\n\n }\n\n }\n\n Ok(files)\n\n}\n\n\n", "file_path": "synchord/src/helper.rs", "rank": 18, "score": 144847.49908345897 }, { "content": "pub fn create_test_password() -> Password {\n\n Password::new(\"a-super-nice-password\").unwrap()\n\n}\n", "file_path": "srvchord/src/test_helpers.rs", "rank": 20, "score": 132038.0521441406 }, { "content": "pub fn run_test_fn<F>(test_body: F) -> ()\n\nwhere\n\n F: Fn(Client, DummyDb) -> (),\n\n{\n\n let _lock = crate::test_helpers::DB_LOCK.lock();\n\n let rocket = crate::rocket_build();\n\n let conn = get_database(&rocket);\n\n let client = Client::untracked(rocket).expect(\"Rocket client\");\n\n\n\n test_body(client, DummyDb(conn))\n\n}\n\n\n", "file_path": "srvchord/src/test_helpers.rs", "rank": 21, "score": 131720.50656025787 }, { "content": "#[get(\"/\")]\n\npub fn index() -> Json<Status> {\n\n Json(Status {\n\n version: env!(\"CARGO_PKG_VERSION\"),\n\n running: true,\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::test_helpers::{json_format, run_test_fn, JsonTemplateValue};\n\n use rocket::http::Status;\n\n\n\n #[test]\n\n fn test_index() {\n\n run_test_fn(|client, _conn| {\n\n let get_response = client.get(\"/status/\").dispatch();\n\n assert_eq!(get_response.status(), Status::Ok);\n\n\n\n let response_body = get_response.into_string().unwrap();\n\n\n", "file_path": "srvchord/src/routes/status.rs", "rank": 22, "score": 130712.60028605442 }, { "content": "pub fn create_setlist<S: AsRef<str>>(conn: &ConnectionType, id: i32, username: S) -> Setlist {\n\n let now = Utc::now();\n\n\n\n let setlist = Setlist::new(\n\n \"My setlist\",\n\n id,\n\n User::new(\n\n Username::new(username.as_ref()).unwrap(),\n\n \"Saul\",\n\n \"Doe\",\n\n create_test_password(),\n\n ),\n\n None,\n\n None,\n\n now,\n\n now,\n\n vec![\n\n SetlistEntry::new(\"song-1\", FileType::Chorddown, \"Song 1\", None),\n\n SetlistEntry::new(\"song-2\", FileType::Chorddown, \"Song 2\", None),\n\n SetlistEntry::new(\"song-3\", FileType::Chorddown, \"Song 3\", None),\n", "file_path": "srvchord/src/test_helpers.rs", "rank": 24, "score": 128991.64257184908 }, { "content": "pub fn convert_to_format<R: BufRead>(\n\n contents: R,\n\n meta: &dyn SongMetaTrait,\n\n formatting: Formatting,\n\n) -> Result<String> {\n\n Converter::new().convert(parse_content(contents)?.node_as_ref(), meta, formatting)\n\n}\n\n\n", "file_path": "libchordr/src/helper.rs", "rank": 25, "score": 128654.25214210775 }, { "content": "pub fn transpose_and_convert_to_format<R: BufRead>(\n\n contents: R,\n\n semitones: isize,\n\n _meta: &dyn SongMetaTrait,\n\n formatting: Formatting,\n\n) -> Result<String> {\n\n let result = transpose_content(contents, semitones)?;\n\n Converter::new().convert(result.node_as_ref(), result.meta_as_ref(), formatting)\n\n}\n\n\n\n#[allow(unused)]\n\npub(crate) fn is_valid_model_identifier(id: &str) -> bool {\n\n validate_model_identifier(id).is_ok()\n\n}\n\n\n\npub(crate) fn validate_model_identifier(id: &str) -> Result<(), &'static str> {\n\n if id.is_empty() {\n\n return Err(\"Identifier must not be empty\");\n\n }\n\n if !id.is_ascii() {\n", "file_path": "libchordr/src/helper.rs", "rank": 26, "score": 126699.2785597943 }, { "content": "pub fn window() -> web_sys::Window {\n\n web_sys::window().expect(\"Could not detect the JS window object\")\n\n}\n", "file_path": "webchordr/common/src/helpers/window.rs", "rank": 27, "score": 126699.2785597943 }, { "content": "pub trait Tokenizer {\n\n /// Tokenize the given input\n\n fn tokenize<R: BufRead>(&self, input: R) -> Result<Vec<Token>, Error>;\n\n}\n\n\n", "file_path": "libchordr/src/tokenizer/mod.rs", "rank": 28, "score": 125396.83072945013 }, { "content": "fn sort_setlist_by_date(setlists: &mut Vec<Setlist>) {\n\n setlists.sort_by(|a, b| {\n\n a.modification_date()\n\n .partial_cmp(&b.modification_date())\n\n .unwrap()\n\n });\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::test_helpers::{create_random_user, json_format, run_test_fn, JsonTemplateValue};\n\n use rocket::http::Header;\n\n use rocket::http::Status;\n\n\n\n #[test]\n\n fn test_index() {\n\n run_test_fn(|client, conn| {\n\n let user = create_random_user(&conn.0);\n\n let username = user.username;\n\n let password = user.password_hash;\n", "file_path": "srvchord/src/routes/user.rs", "rank": 29, "score": 123636.49194863345 }, { "content": "pub fn run_database_test<F>(test_body: F) -> ()\n\nwhere\n\n F: Fn(ConnectionType) -> (),\n\n{\n\n let _lock = crate::test_helpers::DB_LOCK.lock();\n\n\n\n let database_url = match USE_DATABASE {\n\n UseDatabase::InMemory => \":memory:\".to_owned(),\n\n UseDatabase::FromString => \"db/test-db.sqlite\".to_owned(),\n\n UseDatabase::FromConfig => {\n\n unimplemented!();\n\n // let missing_database_error = \"Failed to get database connection for testing\";\n\n // let config = RocketConfig::read().unwrap().active().clone();\n\n // let database_url = config\n\n // .get_table(\"databases\")\n\n // .expect(missing_database_error)\n\n // .get(\"main_database\")\n\n // .expect(missing_database_error)\n\n // .get(\"url\")\n\n // .expect(missing_database_error);\n", "file_path": "srvchord/src/test_helpers.rs", "rank": 30, "score": 120083.78352912921 }, { "content": "fn tokenize(content: &str) -> () {\n\n let _ = build_tokenizer().tokenize(content.as_bytes()).unwrap();\n\n}\n\n\n", "file_path": "libchordr/benches/tokenize_benchmark.rs", "rank": 31, "score": 118875.82085041565 }, { "content": "pub fn create_random_user(conn: &ConnectionType) -> UserDb {\n\n let mut rng = thread_rng();\n\n let random_user_id = rng.gen_range(10000, i32::MAX);\n\n let username = format!(\"daniel-{}\", random_user_id);\n\n\n\n let password: String = rng\n\n .sample_iter(&rand::distributions::Alphanumeric)\n\n .take(30)\n\n .collect();\n\n\n\n let user = UserDb {\n\n username: username.clone(),\n\n first_name: \"Daniel\".to_string(),\n\n last_name: \"Corn\".to_string(),\n\n password_hash: password.clone(),\n\n };\n\n\n\n UserRepository::new().add(conn, user.clone()).unwrap();\n\n\n\n user\n\n}\n\n\n", "file_path": "srvchord/src/test_helpers.rs", "rank": 32, "score": 118396.17443691683 }, { "content": "pub fn get_database(rocket: &Rocket<Build>) -> SqliteConnection {\n\n use diesel::prelude::*;\n\n\n\n let error = \"Failed to get database connection for testing\";\n\n\n\n let database_url: String = rocket\n\n .figment()\n\n .extract_inner(\"databases.main_database.url\")\n\n .expect(error);\n\n\n\n SqliteConnection::establish(&database_url).expect(error)\n\n}\n\n\n\npub struct DummyDb(pub SqliteConnection);\n", "file_path": "srvchord/src/test_helpers.rs", "rank": 33, "score": 117429.31128984193 }, { "content": "pub fn check_if_should_download(source: &FileEntry, destination: &Path) -> Result<()> {\n\n if !(destination.exists()) {\n\n return Ok(());\n\n }\n\n\n\n match destination.metadata() {\n\n Err(_) => Err(Error::download_error(\"Could not fetch metadata\")),\n\n Ok(metadata) => match metadata.modified() {\n\n Err(_) => Err(Error::download_error(\"Could not fetch modification time\")),\n\n Ok(modified) => {\n\n let remote_time = source.modified_date();\n\n let local_time: DateTime<Utc> = DateTime::from(modified);\n\n let local_time_utc = local_time.with_timezone(&remote_time.timezone());\n\n\n\n debug!(\n\n \"Compare remote vs local file time: {} vs {}\",\n\n remote_time, local_time_utc\n\n );\n\n if local_time_utc < remote_time {\n\n info!(\"Remote file is newer than local file, will overwrite\");\n\n Ok(())\n\n } else {\n\n Err(Error::skip_download(\"Local file is newer than remote\"))\n\n }\n\n }\n\n },\n\n }\n\n}\n\n\n", "file_path": "synchord/src/helper.rs", "rank": 34, "score": 115054.06552568162 }, { "content": "#[get(\"/\")]\n\npub fn index(user: UserDb) -> Option<Json<User>> {\n\n match user.try_to_user() {\n\n Ok(u) => Some(Json(u)),\n\n Err(_) => None,\n\n }\n\n}\n\n\n\n#[get(\"/data\")]\n\npub async fn data(user_db: UserDb, conn: DbConn) -> Option<Json<MainData>> {\n\n conn.run(move |conn| match user_db.try_to_user() {\n\n Ok(user) => {\n\n let username = user.username();\n\n let latest_setlist = match SetlistRepository::new().find_by_username(conn, username) {\n\n Ok(setlists) if setlists.is_empty() => None,\n\n Ok(mut setlists) => {\n\n sort_setlist_by_date(&mut setlists);\n\n\n\n Some(setlists.pop().unwrap())\n\n }\n\n Err(e) => {\n", "file_path": "srvchord/src/routes/user.rs", "rank": 35, "score": 115054.06552568162 }, { "content": "pub fn verify_password(credentials: &Credentials, user: &UserDb) -> bool {\n\n let password_data = &user.password_hash;\n\n let parts: Vec<&str> = password_data.splitn(3, ':').collect();\n\n if parts.len() < 3 {\n\n warn!(\"Check un-hashed password\");\n\n\n\n return password_data == &credentials.password().to_string();\n\n }\n\n\n\n let algorithm = parts[0];\n\n let salt = parts[1];\n\n let hash = parts[2];\n\n if algorithm == \"argon2\" {\n\n match verify_password_argon2(&credentials.password().to_string(), hash, salt) {\n\n Ok(r) => r,\n\n Err(e) => {\n\n error!(\"{}\", e);\n\n false\n\n }\n\n }\n\n } else {\n\n error!(\"Unsupported password hashing algorithm: {}\", algorithm);\n\n false\n\n }\n\n}\n\n\n", "file_path": "srvchord/src/authentication/mod.rs", "rank": 36, "score": 113366.45643346924 }, { "content": "pub fn parse_content<R: BufRead>(contents: R) -> Result<ParserResult> {\n\n let tokens = build_tokenizer().tokenize(contents)?;\n\n Parser::new().parse(tokens)\n\n}\n\n\n", "file_path": "libchordr/src/helper.rs", "rank": 37, "score": 109617.99051694572 }, { "content": "pub fn entry<S: Into<String>>(id: S) -> SetlistEntry {\n\n SetlistEntry::from_song_with_settings(&test_song(id), SongSettings::default())\n\n}\n\n\n", "file_path": "webchordr/persistence/src/test_helpers/mod.rs", "rank": 38, "score": 109617.99051694572 }, { "content": "Comin’ for to carry me home.\n\n---\n\nI looked over Jordan, and what did I see,\n\nComin’ for to carry me home.\n\nA band of angels comin’ after me,\n\nComin’ for to carry me home.\n\n\"#\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_convert_w_inline_metadata() {\n\n let converter = SongBeamerConverter {};\n\n let ast = get_test_ast_w_inline_metadata();\n\n let result = converter.convert(\n\n &ast,\n\n &get_test_metadata(),\n\n Formatting::with_format(Format::SongBeamer),\n\n );\n\n\n\n assert!(result.is_ok());\n\n let source = result.unwrap();\n\n\n\n assert_eq!(\n\n source,\n\n r#\"#LangCount=1\n", "file_path": "libchordr/src/converter/songbeamer/mod.rs", "rank": 39, "score": 109609.24497961879 }, { "content": "fn check_username(username: &str, user: &UserDb) -> Result<Username, ()> {\n\n if user.username != username {\n\n warn!(\n\n \"Logged in user {} has no access to setlists of user {}\",\n\n user.username, username\n\n );\n\n\n\n Err(())\n\n } else {\n\n match Username::new(username) {\n\n Ok(u) => Ok(u),\n\n Err(_) => Err(()),\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::domain::setlist::repository::SetlistRepository;\n\n use crate::test_helpers::{\n", "file_path": "srvchord/src/routes/setlist.rs", "rank": 40, "score": 109177.67207246585 }, { "content": "pub fn sort_by_title<T: SongData>(collection: &mut [T]) -> &[T] {\n\n collection.sort_by(|a, b| a.title().partial_cmp(&b.title()).unwrap());\n\n collection\n\n}\n\n\n", "file_path": "libchordr/src/models/song_sorting.rs", "rank": 41, "score": 108079.26483750352 }, { "content": "pub fn test_song<S: Into<String>>(id: S) -> TestSong {\n\n TestSong { id: id.into() }\n\n}\n\n\n\npub struct TestSong {\n\n id: String,\n\n}\n\n\n\nimpl SongIdTrait for TestSong {}\n\n\n\nimpl ListEntryTrait for TestSong {\n\n type Id = SongId;\n\n fn id(&self) -> SongId {\n\n self.id.as_str().into()\n\n }\n\n}\n\n\n\nimpl SongData for TestSong {\n\n fn title(&self) -> String {\n\n self.id.clone()\n", "file_path": "webchordr/persistence/src/test_helpers/mod.rs", "rank": 42, "score": 108079.26483750352 }, { "content": "pub fn insert_test_user<S1: Into<String>, S2: Into<String>, S3: Into<String>>(\n\n conn: &ConnectionType,\n\n username: S1,\n\n first_name: S2,\n\n last_name: S3,\n\n) -> UserDb {\n\n let username = username.into();\n\n let first_name = first_name.into();\n\n let last_name = last_name.into();\n\n let new_user = UserDb {\n\n username,\n\n first_name,\n\n last_name,\n\n password_hash: create_test_password().to_string(),\n\n };\n\n\n\n CommandExecutor::perform(\n\n &UserCommandExecutor::with_connection(conn),\n\n Command::add(new_user.clone()),\n\n )\n\n .unwrap();\n\n\n\n new_user\n\n}\n\n\n", "file_path": "srvchord/src/test_helpers.rs", "rank": 43, "score": 104319.14407213649 }, { "content": "fn criterion_benchmark(c: &mut Criterion) {\n\n c.bench_function(\"Tokenize Swing Low Sweet Chariot\", |b| {\n\n b.iter(|| {\n\n tokenize(black_box(include_str!(\n\n \"../tests/resources/swing_low_sweet_chariot.chorddown\"\n\n )))\n\n })\n\n });\n\n}\n\n\n\ncriterion_group!(benches, criterion_benchmark);\n\ncriterion_main!(benches);\n", "file_path": "libchordr/benches/tokenize_benchmark.rs", "rank": 44, "score": 104203.19766642978 }, { "content": "pub fn transpose_content<R: BufRead>(contents: R, semitones: isize) -> Result<ParserResult> {\n\n let ParserResult { node, meta } = parse_content(contents)?;\n\n\n\n let transposed_node = node.transpose(semitones);\n\n let transposed_meta = meta.transpose(semitones);\n\n\n\n Ok(ParserResult::new(transposed_node, transposed_meta))\n\n}\n\n\n", "file_path": "libchordr/src/helper.rs", "rank": 45, "score": 102914.65826149986 }, { "content": "fn get_username(args: &ArgMatches<'_>) -> Result<String> {\n\n match args.value_of(\"USERNAME\") {\n\n Some(val) => Ok(val.to_owned()),\n\n None => Err(Error::missing_argument_error(\"No username provided\")),\n\n }\n\n}\n\n\n", "file_path": "synchord/src/bin.rs", "rank": 46, "score": 97821.22779840417 }, { "content": "pub fn build_combined_key<N: AsRef<str>, K: AsRef<str>>(namespace: &N, key: &K) -> String {\n\n if namespace.as_ref().is_empty() {\n\n key.as_ref().to_string()\n\n } else {\n\n format!(\"{}.{}\", namespace.as_ref(), key.as_ref())\n\n }\n\n}\n", "file_path": "webchordr/persistence/src/storage_key_utility.rs", "rank": 47, "score": 91993.2408786121 }, { "content": "fn main() {\n\n println!(\n\n \"cargo:rustc-env=CUNDD_BUILD_REVISION={}\",\n\n Local::now().format(\"%Y-%m-%d %H:%M:%S\")\n\n )\n\n}\n", "file_path": "webchordr/app/build.rs", "rank": 48, "score": 74530.9497522578 }, { "content": "fn main() {\n\n let output_arg = Arg::with_name(\"output\")\n\n .required(true)\n\n .help(\"Output file name\");\n\n let verbosity_arg = Arg::with_name(\"verbosity\")\n\n .short(\"v\")\n\n .multiple(true)\n\n .help(\"Set the output verbosity\");\n\n\n\n let format_help = get_output_format_help();\n\n let subcommand_convert = SubCommand::with_name(\"convert\")\n\n .about(\"Convert chorddown files\")\n\n .arg(\n\n Arg::with_name(\"input\")\n\n .required(true)\n\n .help(\"Chorddown file to parse\"),\n\n )\n\n .arg(output_arg.clone())\n\n .arg(Arg::with_name(\"format\").help(&format_help))\n\n .arg(\n", "file_path": "chordr/src/bin.rs", "rank": 49, "score": 74530.9497522578 }, { "content": "fn main() {\n\n let output_arg = Arg::with_name(\"OUTPUT\")\n\n .required(true)\n\n .help(\"Output directory path\");\n\n let service_arg = Arg::with_name(\"SERVICE\")\n\n .required(true)\n\n .help(\"Online service to use (dropbox, WebDAV)\");\n\n let api_token_arg = Arg::with_name(\"API_TOKEN\")\n\n .long(\"api-key\")\n\n .takes_value(true)\n\n .help(\"API key to authenticate with the service\");\n\n let username_arg = Arg::with_name(\"USERNAME\")\n\n .long(\"username\")\n\n .short(\"u\")\n\n .takes_value(true)\n\n .help(\"Username to authenticate with the service\");\n\n let password_arg = Arg::with_name(\"PASSWORD\")\n\n .long(\"password\")\n\n .short(\"p\")\n\n .takes_value(true)\n", "file_path": "synchord/src/bin.rs", "rank": 50, "score": 74530.9497522578 }, { "content": "fn main() {\n\n wasm_logger::init(wasm_logger::Config::default());\n\n yew::start_app::<handler::Handler>();\n\n}\n", "file_path": "webchordr/app/src/main.rs", "rank": 51, "score": 73251.60605256766 }, { "content": "fn main() {\n\n if let Err(e) = run() {\n\n eprintln!(\"{}\", e);\n\n exit(1);\n\n }\n\n}\n\n\n", "file_path": "chordr-runner/src/bin.rs", "rank": 52, "score": 73251.60605256766 }, { "content": "pub trait ServiceTrait {\n\n type Configuration: ServiceConfigurationTrait;\n\n\n\n /// Build a new Service instance from the [`Service`]'s [`Configuration`]\n\n fn new(configuration: Self::Configuration) -> Result<Self>\n\n where\n\n Self: Sized;\n\n\n\n fn identifier(&self) -> ServiceIdentifier;\n\n fn list_files(&self) -> Result<Vec<FileEntry>>;\n\n fn download(&self, file: FileEntry, destination: &Path) -> Result<()>;\n\n}\n\n\n\npub enum Services {\n\n DropboxService(DropboxService),\n\n WebDAVService(WebDAVService),\n\n}\n\n\n\nimpl ServiceTrait for Services {\n\n type Configuration = AbstractServiceConfig;\n", "file_path": "synchord/src/service/mod.rs", "rank": 53, "score": 71371.37051897137 }, { "content": "pub trait EventTrait {}\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n\npub enum Event {\n\n /// Sorting of entries in the Setlist changed\n\n SortingChange(SortingChange),\n\n\n\n /// Events related to [`SongSettings`]\n\n SettingsEvent(SettingsEvent),\n\n\n\n /// Events related to [`Setlist`s]\n\n SetlistEvent(SetlistEvent),\n\n\n\n /// A pair of events triggered at once\n\n Pair(Box<Event>, Box<Event>),\n\n}\n\n\n\nimpl From<SortingChange> for Event {\n\n fn from(s: SortingChange) -> Self {\n\n Event::SortingChange(s)\n", "file_path": "webchordr/events/src/lib.rs", "rank": 54, "score": 71371.37051897137 }, { "content": "pub trait CommandExecutor {\n\n type RecordType: RecordTrait;\n\n type Error;\n\n\n\n fn perform(&self, command: Command<Self::RecordType>) -> Result<(), Self::Error> {\n\n match command.command_type() {\n\n CommandType::Add => self.add(command),\n\n CommandType::Update => self.update(command),\n\n CommandType::Delete => self.delete(command),\n\n }\n\n }\n\n\n\n fn add(&self, command: Command<Self::RecordType>) -> Result<(), Self::Error>;\n\n fn update(&self, command: Command<Self::RecordType>) -> Result<(), Self::Error>;\n\n fn delete(&self, command: Command<Self::RecordType>) -> Result<(), Self::Error>;\n\n}\n", "file_path": "cqrs/src/command_executor.rs", "rank": 55, "score": 71371.37051897137 }, { "content": "/// Trait for converting between formats\n\npub trait ConverterTrait {\n\n fn convert(\n\n &self,\n\n node: &Node,\n\n meta: &dyn SongMetaTrait,\n\n formatting: Formatting,\n\n ) -> Result<String>;\n\n}\n\n\n\npub struct Converter {}\n\n\n\nimpl Converter {\n\n pub fn new() -> Self {\n\n Self {}\n\n }\n\n\n\n /// Build a Converter for the given format\n\n ///\n\n /// Factory method to build a `ConverterTrait` implementor instance to convert a [`Node`]\n\n /// structure into the output format\n", "file_path": "libchordr/src/converter/mod.rs", "rank": 56, "score": 71371.37051897137 }, { "content": "pub trait ParserTrait {\n\n type OkType;\n\n\n\n /// Parse the given tokens into the Parser's result\n\n fn parse(&mut self, tokens: Vec<Token>) -> Result<Self::OkType, Error>;\n\n}\n\n\n\npub struct Parser {}\n\n\n\nimpl Parser {\n\n pub fn new() -> Self {\n\n Self {}\n\n }\n\n}\n\n\n\nimpl Default for Parser {\n\n fn default() -> Self {\n\n Self {}\n\n }\n\n}\n", "file_path": "libchordr/src/parser/mod.rs", "rank": 57, "score": 71371.37051897137 }, { "content": "pub trait RepositoryTrait {\n\n type ManagedType: RecordTrait;\n\n type Error;\n\n\n\n /// Find all instances of `ManagedType` in the `Repository`\n\n fn find_all(&self, connection: &ConnectionType) -> Result<Vec<Self::ManagedType>, Self::Error>;\n\n\n\n /// Count all instances of `ManagedType` in the `Repository`\n\n fn count_all(&self, connection: &ConnectionType) -> Result<Count, Self::Error>;\n\n\n\n /// Find an instance of `ManagedType` with `id` inside the `Repository`\n\n fn find_by_id(\n\n &self,\n\n connection: &ConnectionType,\n\n id: <Self::ManagedType as RecordTrait>::Id,\n\n ) -> Result<Self::ManagedType, Self::Error>;\n\n\n\n /// Add the instance of `ManagedType` to the `Repository`\n\n ///\n\n /// # Errors\n", "file_path": "srvchord/src/traits/repository.rs", "rank": 58, "score": 71371.37051897137 }, { "content": "fn set_timeout(callback: &Closure<dyn Fn()>, milliseconds: i32) -> Result<(), WebError> {\n\n match window().set_timeout_with_callback_and_timeout_and_arguments_0(\n\n callback.as_ref().unchecked_ref(),\n\n milliseconds,\n\n ) {\n\n Ok(_) => Ok(()),\n\n Err(e) => Err(e.into()),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use js_sys::Date;\n\n use wasm_bindgen_test::wasm_bindgen_test_configure;\n\n use wasm_bindgen_test::*;\n\n\n\n use super::*;\n\n\n\n wasm_bindgen_test_configure!(run_in_browser);\n\n\n", "file_path": "webchordr/common/src/lock/request_tick.rs", "rank": 59, "score": 70636.01817782423 }, { "content": "pub trait NoteDisplay {\n\n fn note_format(&self, format: Formatting) -> String;\n\n}\n", "file_path": "libchordr/src/models/chord/fmt.rs", "rank": 60, "score": 70283.13454844372 }, { "content": "/// Trait for struct's that have a unique identifier\n\n///\n\n/// See also http://docs.diesel.rs/diesel/associations/trait.Identifiable.html\n\npub trait RecordTrait {\n\n /// The type of this struct's identifier\n\n ///\n\n /// For single-field primary keys, this is typically `&'a i32`, or `&'a String`\n\n /// For composite primary keys, this is typically `(&'a i32, &'a i32)`\n\n /// or `(&'a String, &'a String)`, etc.\n\n type Id: Hash + Eq;\n\n\n\n /// Returns the identifier for this record.\n\n ///\n\n /// This takes `self` by value, not reference.\n\n /// This is because composite primary keys\n\n /// are typically stored as multiple fields.\n\n /// We could not return `&(String, String)` if each string is a separate field.\n\n ///\n\n /// Because of Rust's rules about specifying lifetimes,\n\n /// this means that `RecordTrait` is usually implemented on references\n\n /// so that we have a lifetime to use for `Id`.\n\n fn id(self) -> Self::Id;\n\n}\n\n\n\nimpl RecordTrait for i32 {\n\n type Id = i32;\n\n\n\n fn id(self) -> Self::Id {\n\n self\n\n }\n\n}\n", "file_path": "libchordr/src/models/record_trait.rs", "rank": 61, "score": 70283.13454844372 }, { "content": "pub trait TransposableTrait {\n\n fn transpose(self, semitones: isize) -> Self;\n\n}\n", "file_path": "libchordr/src/models/chord/transposition.rs", "rank": 62, "score": 70283.13454844372 }, { "content": "pub trait TaskTrait {\n\n fn with_configuration(configuration: Configuration) -> Result<Self>\n\n where\n\n Self: std::marker::Sized;\n\n}\n\n\n", "file_path": "chordr-runner/src/task/mod.rs", "rank": 63, "score": 70283.13454844372 }, { "content": "fn run() -> Result<()> {\n\n let app = App::new(env!(\"CARGO_PKG_NAME\"))\n\n .version(env!(\"CARGO_PKG_VERSION\"))\n\n .author(\"Daniel Corn <[email protected]>\")\n\n .about(\"Service for chorddown file synchronization and catalog building\")\n\n .arg(\n\n Arg::with_name(\"configuration\")\n\n .help(\"File containing the configuration\")\n\n .short(\"c\")\n\n .long(\"configuration\")\n\n .required(true)\n\n .takes_value(true),\n\n )\n\n .arg(\n\n Arg::with_name(\"pretty\")\n\n .help(\"Output indented JSON\")\n\n .short(\"p\")\n\n .long(\"pretty\"),\n\n )\n\n .arg(\n", "file_path": "chordr-runner/src/bin.rs", "rank": 64, "score": 69904.23614833721 }, { "content": "pub trait FromHeader: Sized {\n\n type Err;\n\n\n\n /// Try to create an instance of `Self` from the given headers\n\n fn from_headers(headers: Vec<&str>) -> FromHeaderResult<Self, Self::Err> {\n\n for header in headers {\n\n match Self::from_header(header) {\n\n FromHeaderResult::None => { /* continue */ }\n\n FromHeaderResult::Ok(c) => return FromHeaderResult::Ok(c),\n\n FromHeaderResult::Err(e) => return FromHeaderResult::Err(e),\n\n }\n\n }\n\n\n\n FromHeaderResult::None\n\n }\n\n\n\n /// Try to create an instance of `Self` from the given header\n\n fn from_header(header: &str) -> FromHeaderResult<Self, Self::Err>;\n\n}\n", "file_path": "srvchord/src/traits/header.rs", "rank": 65, "score": 69359.05976051625 }, { "content": "pub trait ServiceConfigurationTrait {\n\n /// Build a new instance of the Service Configuration from the values of the given [`AbstractServiceConfig`]\n\n fn from_service_config(service_config: AbstractServiceConfig) -> Result<Self>\n\n where\n\n Self: Sized;\n\n\n\n /// Return the identifier for the associated service type\n\n fn identifier(&self) -> ServiceIdentifier;\n\n\n\n /// Return the local directory\n\n fn local_directory(&self) -> &Path;\n\n}\n", "file_path": "synchord/src/service/service_configuration.rs", "rank": 66, "score": 69250.95982796277 }, { "content": "pub trait ListTrait {\n\n type Item: ListEntryTrait;\n\n fn contains(&self, item: &<Self as ListTrait>::Item) -> bool {\n\n self.get(item.id()).is_some()\n\n }\n\n\n\n fn contains_id(&self, id: <<Self as ListTrait>::Item as ListEntryTrait>::Id) -> bool {\n\n self.get(id).is_some()\n\n }\n\n\n\n fn get(\n\n &self,\n\n id: <<Self as ListTrait>::Item as ListEntryTrait>::Id,\n\n ) -> Option<&<Self as ListTrait>::Item>;\n\n\n\n /// Return the number of entries in the list\n\n fn len(&self) -> usize;\n\n\n\n // Return if the list is empty\n\n fn is_empty(&self) -> bool;\n", "file_path": "libchordr/src/models/list/list_trait.rs", "rank": 67, "score": 69250.95982796277 }, { "content": "#[async_trait(? Send)]\n\npub trait BackendTrait {\n\n /// Store `value` with the given `key` in the `namespace`\n\n ///\n\n /// `value` will be serialized before it is stored\n\n async fn store<T: Serialize + RecordTrait, N: AsRef<str>, K: AsRef<str>>(\n\n &self,\n\n namespace: N,\n\n key: K,\n\n value: &T,\n\n ) -> Result<(), WebError>;\n\n\n\n /// Load the stored value with the given `key` in the `namespace`\n\n async fn load<T, N: AsRef<str>, K: AsRef<str>>(&self, namespace: N, key: K) -> Tri<T, WebError>\n\n where\n\n T: for<'a> Deserialize<'a>;\n\n\n\n // /// Load the stored value with the given `key` in the `namespace`\n\n // async fn find_by_identifier<T, I, ID, N: AsRef<str>, K: AsRef<str>>(\n\n // &self,\n\n // namespace: N,\n", "file_path": "webchordr/persistence/src/backend/backend_trait.rs", "rank": 68, "score": 69250.95982796277 }, { "content": "type SortingChangeFn = dyn Fn(i32, i32);\n\n\n\n/// Service to make a HtmlElement sortable using [Shopify/draggable](https://github.com/Shopify/draggable)\n\npub struct SortableService {}\n\n\n\n#[must_use]\n\npub struct SortableHandle {\n\n sortable: SortableWrapper,\n\n _closure: Closure<SortingChangeFn>,\n\n}\n\n\n\nimpl SortableHandle {\n\n pub fn destroy(&mut self) {\n\n self.sortable.destroy();\n\n }\n\n}\n\n\n\nimpl Drop for SortableHandle {\n\n fn drop(&mut self) {\n\n self.sortable.destroy();\n", "file_path": "webchordr/song-list/src/sortable_service/mod.rs", "rank": 69, "score": 69135.599328919 }, { "content": "fn assign_owner_to_populated_result(\n\n populate_entry: PopulateResult,\n\n users: &[User],\n\n) -> Result<Setlist, SrvError> {\n\n let setlist_db = populate_entry.0;\n\n\n\n let team = match setlist_db.team {\n\n // TODO: Add support for Teams\n\n Some(_) => unimplemented!(\"Load teams\"),\n\n None => None,\n\n };\n\n\n\n let owner = users\n\n .iter()\n\n .find(|user| user.username().as_ref() == setlist_db.owner);\n\n\n\n match owner {\n\n Some(owner) => Ok(setlist_from_data(\n\n setlist_db,\n\n populate_entry.1,\n", "file_path": "srvchord/src/domain/setlist/repository.rs", "rank": 70, "score": 68793.2942602357 }, { "content": "#[deprecated(note = \"use RecordTrait\")]\n\npub trait RecordIdTrait {\n\n /// The type of this struct's identifier\n\n ///\n\n /// For single-field primary keys, this is typically `&'a i32`, or `&'a String`\n\n /// For composite primary keys, this is typically `(&'a i32, &'a i32)`\n\n /// or `(&'a String, &'a String)`, etc.\n\n type Id: Hash + Eq;\n\n\n\n /// Returns the identifier for this record.\n\n ///\n\n /// This takes `self` by value, not reference.\n\n /// This is because composite primary keys\n\n /// are typically stored as multiple fields.\n\n /// We could not return `&(String, String)` if each string is a separate field.\n\n ///\n\n /// Because of Rust's rules about specifying lifetimes,\n\n /// this means that `RecordIdTrait` is usually implemented on references\n\n /// so that we have a lifetime to use for `Id`.\n\n fn id(self) -> Self::Id;\n\n}\n\n\n\n#[allow(deprecated)]\n\nimpl RecordIdTrait for i32 {\n\n type Id = i32;\n\n\n\n fn id(self) -> Self::Id {\n\n self\n\n }\n\n}\n", "file_path": "libchordr/src/models/record_id_trait.rs", "rank": 71, "score": 68275.41213768945 }, { "content": "pub trait CatalogHandler {\n\n fn fetch_catalog(&mut self);\n\n\n\n fn commit_changes(&mut self);\n\n}\n", "file_path": "webchordr/app/src/handler_traits/catalog_handler.rs", "rank": 72, "score": 68270.623087161 }, { "content": "pub trait SettingsHandler {\n\n /// Handle the given [`SongSettings`] related event\n\n fn handle_settings_event(&mut self, event: SettingsEvent);\n\n\n\n /// Invoked when the [`SongSettings`] for the Song with the given [`SongId`] changed\n\n fn song_settings_change(&mut self, song_id: SongId, settings: SongSettings);\n\n\n\n /// Replace the locally stored collection of [`SongSettings`]\n\n fn song_settings_replace(&mut self, settings: SongSettingsMap);\n\n\n\n /// Load the [`SongSettings`] from the persistent storage\n\n fn fetch_song_settings(&mut self);\n\n\n\n /// Commit the [`SongSettings`] to the persistent storage\n\n fn commit_changes(&mut self);\n\n}\n", "file_path": "webchordr/app/src/handler_traits/settings_handler.rs", "rank": 73, "score": 68270.623087161 }, { "content": "pub trait ListEntryTrait {\n\n type Id: Hash + Eq;\n\n fn id(&self) -> Self::Id;\n\n}\n\n\n", "file_path": "libchordr/src/models/list/list_trait.rs", "rank": 74, "score": 68270.623087161 }, { "content": "pub trait SetlistHandler {\n\n /// Handle the given [`Setlist`] related event\n\n fn handle_setlist_event(&mut self, event: SetlistEvent);\n\n\n\n /// Add a new entry to the [`Setlist`]\n\n fn setlist_add(&mut self, song: SetlistEntry);\n\n\n\n /// Remove an entry from the [`Setlist`]\n\n fn setlist_remove(&mut self, song_id: SongId);\n\n\n\n /// Invoked when the [`SongSettings`] for the Song with the given [`SongId`] changed\n\n fn setlist_settings_changed(&mut self, song_id: SongId, song_settings: SongSettings);\n\n\n\n /// Replace the locally stored [`Setlist`]\n\n fn setlist_replace(&mut self, setlist: Setlist);\n\n\n\n /// Invoked when the sorting of entries in the [`Setlist`] changed\n\n fn setlist_sorting_changed(&mut self, sorting_change: SortingChange);\n\n\n\n /// Load the [`Setlist`] from the persistent storage\n\n fn fetch_setlist(&mut self);\n\n\n\n /// Commit the [`Setlist`] to the persistent storage\n\n fn commit_changes(&mut self);\n\n}\n", "file_path": "webchordr/app/src/handler_traits/setlist_handler.rs", "rank": 75, "score": 68270.623087161 }, { "content": "#[launch]\n\nfn rocket() -> Rocket<Build> {\n\n rocket_build()\n\n}\n", "file_path": "srvchord/src/main.rs", "rank": 76, "score": 68049.79677976249 }, { "content": "fn get_song_metadata_content(\n\n metadata_token: &Meta,\n\n song_metadata: &dyn MetaTrait,\n\n formatting: Formatting,\n\n) -> Option<String> {\n\n match metadata_token {\n\n Meta::Subtitle(_) => song_metadata.subtitle(),\n\n Meta::Artist(_) => song_metadata.artist(),\n\n Meta::Composer(_) => song_metadata.composer(),\n\n Meta::Lyricist(_) => song_metadata.lyricist(),\n\n Meta::Copyright(_) => song_metadata.copyright(),\n\n Meta::Album(_) => song_metadata.album(),\n\n Meta::Year(_) => song_metadata.year(),\n\n Meta::Key(_) => song_metadata.key().map(|c| c.note_format(formatting)),\n\n Meta::OriginalKey(_) => song_metadata\n\n .original_key()\n\n .map(|c| c.note_format(formatting)),\n\n Meta::Time(_) => song_metadata.time(),\n\n Meta::Tempo(_) => song_metadata.tempo(),\n\n Meta::Duration(_) => song_metadata.duration(),\n\n Meta::Capo(_) => song_metadata.capo(),\n\n Meta::OriginalTitle(_) => song_metadata.original_title(),\n\n Meta::AlternativeTitle(_) => song_metadata.alternative_title(),\n\n Meta::CCLISongId(_) => song_metadata.ccli_song_id(),\n\n Meta::BNotation(_) => Some(song_metadata.b_notation().to_string()),\n\n }\n\n}\n\n\n", "file_path": "libchordr/src/converter/html/tag_provider.rs", "rank": 77, "score": 67818.65741872403 }, { "content": "fn get_output_format_help() -> String {\n\n format!(\"Output format (one of {})\", get_valid_output_format_help())\n\n}\n\n\n", "file_path": "chordr/src/bin.rs", "rank": 78, "score": 67680.0158666734 }, { "content": "fn rocket_build() -> Rocket<Build> {\n\n rocket::build()\n\n .attach(self::cors::Cors)\n\n .attach(DbConn::fairing())\n\n .attach(AdHoc::on_ignite(\"Database Migrations\", run_db_migrations))\n\n .attach(AdHoc::on_ignite(\n\n \"Build application configuration\",\n\n |rocket| async {\n\n let config = build_application_config(&rocket);\n\n rocket.manage(config)\n\n },\n\n ))\n\n .attach(AdHoc::on_ignite(\"Static Files config\", |rocket| async {\n\n let config = build_application_config(&rocket);\n\n rocket.mount(\"/\", FileServer::from(config.static_files_dir))\n\n }))\n\n .mount(\"/\", routes![index, catalog])\n\n .mount(\"/status\", crate::routes::status::get_routes())\n\n .mount(\"/setlist\", crate::routes::setlist::get_routes())\n\n .mount(\"/user\", crate::routes::user::get_routes())\n\n}\n\n\n", "file_path": "srvchord/src/main.rs", "rank": 79, "score": 66907.48521883789 }, { "content": "fn get_serialization_formatting() -> Formatting {\n\n Formatting {\n\n b_notation: get_serialization_b_notation(),\n\n semitone_notation: SemitoneNotation::Sharp,\n\n format: Format::HTML,\n\n }\n\n}\n\n\n\nimpl Serialize for Chord {\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: Serializer,\n\n {\n\n serializer.serialize_str(&self.note_format(get_serialization_formatting()))\n\n }\n\n}\n\n\n", "file_path": "libchordr/src/models/chord/mod.rs", "rank": 80, "score": 66653.84244320769 }, { "content": "fn get_valid_output_format_help() -> String {\n\n Format::get_all()\n\n .iter()\n\n .map(|f| f.to_string())\n\n .collect::<Vec<String>>()\n\n .join(\", \")\n\n}\n\n\n", "file_path": "chordr/src/bin.rs", "rank": 81, "score": 66653.84244320769 }, { "content": "#[async_trait(? Send)]\n\npub trait WebRepositoryTrait {\n\n type ManagedType: RecordTrait;\n\n\n\n /// Return the `namespace` part of the storage key\n\n fn namespace() -> &'static str;\n\n\n\n /// Return the `key` part of the storage key\n\n fn key() -> &'static str;\n\n\n\n /// Store the given `value`\n\n async fn store(&mut self, value: &Self::ManagedType) -> Result<(), WebError>;\n\n\n\n /// Load the stored value\n\n async fn load(&mut self) -> Tri<Self::ManagedType, WebError>;\n\n}\n", "file_path": "webchordr/persistence/src/web_repository/web_repository_trait.rs", "rank": 82, "score": 66450.59005019696 }, { "content": "/// Trait mirroring the API for Browser Storage\n\n///\n\n/// https://developer.mozilla.org/en-US/docs/Web/API/Storage\n\npub trait BrowserStorageTrait {\n\n // /// When passed a number n, this method will return the name of the nth key in the storage\n\n // fn key(&self, index: usize) -> Option<String>;\n\n\n\n /// When passed a key name, will return that key's value\n\n fn get_item<S: AsRef<str>>(&self, key_name: S) -> Option<String>;\n\n\n\n /// When passed a key name and value, will add that key to the storage, or update that key's value if it already exists\n\n fn set_item<S: Into<String>, V: Into<String>>(\n\n &mut self,\n\n key_name: S,\n\n key_value: V,\n\n ) -> Result<(), WebError>;\n\n\n\n /// When passed a key name, will remove that key from the storage\n\n fn remove_item<S: AsRef<str>>(&mut self, key_name: S) -> Result<(), WebError>;\n\n\n\n /// When invoked, will empty all keys out of the storage\n\n fn clear(&mut self) -> Result<(), WebError>;\n\n\n\n /// Return the number of pairs in the storage\n\n fn len(&self) -> usize;\n\n\n\n /// Return `true` if the storage is empty\n\n fn is_empty(&self) -> bool {\n\n self.len() == 0\n\n }\n\n}\n", "file_path": "webchordr/persistence/src/browser_storage/browser_storage_trait.rs", "rank": 83, "score": 66450.59005019696 }, { "content": "pub trait MetaTrait: Debug {\n\n fn title(&self) -> Option<String>;\n\n fn subtitle(&self) -> Option<String>;\n\n fn artist(&self) -> Option<String>;\n\n fn composer(&self) -> Option<String>;\n\n fn lyricist(&self) -> Option<String>;\n\n fn copyright(&self) -> Option<String>;\n\n fn album(&self) -> Option<String>;\n\n fn year(&self) -> Option<String>;\n\n fn key(&self) -> Option<Chord>;\n\n fn original_key(&self) -> Option<Chord>;\n\n fn time(&self) -> Option<String>;\n\n fn tempo(&self) -> Option<String>;\n\n fn duration(&self) -> Option<String>;\n\n fn capo(&self) -> Option<String>;\n\n fn original_title(&self) -> Option<String>;\n\n fn alternative_title(&self) -> Option<String>;\n\n fn ccli_song_id(&self) -> Option<String>;\n\n fn b_notation(&self) -> BNotation;\n\n}\n", "file_path": "libchordr/src/models/meta/meta_trait.rs", "rank": 84, "score": 66258.31232870588 }, { "content": "fn get_serialization_b_notation() -> BNotation {\n\n BNotation::B\n\n}\n\n\n", "file_path": "libchordr/src/models/chord/mod.rs", "rank": 85, "score": 65679.20560169601 }, { "content": "pub trait SongData: SongIdTrait {\n\n fn title(&self) -> String;\n\n\n\n fn file_type(&self) -> FileType;\n\n}\n", "file_path": "libchordr/src/models/song_data.rs", "rank": 86, "score": 65326.004108963054 }, { "content": "pub trait RecurringTaskTrait: TaskTrait {\n\n fn run(&self) -> Result<()>;\n\n}\n", "file_path": "chordr-runner/src/task/mod.rs", "rank": 87, "score": 65326.004108963054 }, { "content": "fn get_default_options() -> RequestInit {\n\n let mut options = RequestInit::new();\n\n options.method(\"GET\");\n\n options.mode(RequestMode::Cors);\n\n options\n\n}\n", "file_path": "webchordr/common/src/fetch_helper/mod.rs", "rank": 88, "score": 64752.31803257116 }, { "content": "fn criterion_benchmark(c: &mut Criterion) {\n\n c.bench_function(\"Convert Swing Low Sweet Chariot to Chorddown\", |b| {\n\n b.iter(|| convert_to_chorddown(black_box(get_test_ast())))\n\n });\n\n\n\n c.bench_function(\"Convert Swing Low Sweet Chariot to HTML\", |b| {\n\n b.iter(|| convert_to_html(black_box(get_test_ast())))\n\n });\n\n\n\n c.bench_function(\"Convert Swing Low Sweet Chariot to Text\", |b| {\n\n b.iter(|| convert_to_text(black_box(get_test_ast())))\n\n });\n\n}\n\n\n\ncriterion_group!(benches, criterion_benchmark);\n\ncriterion_main!(benches);\n", "file_path": "libchordr/benches/converter_benchmark.rs", "rank": 89, "score": 64202.75326592541 }, { "content": "fn criterion_benchmark(c: &mut Criterion) {\n\n c.bench_function(\"Parse Swing Low Sweet Chariot\", |b| {\n\n b.iter(|| parse(black_box(get_test_tokens())))\n\n });\n\n}\n\n\n\ncriterion_group!(benches, criterion_benchmark);\n\ncriterion_main!(benches);\n", "file_path": "libchordr/benches/parse_benchmark.rs", "rank": 90, "score": 64202.75326592541 }, { "content": "fn criterion_benchmark(c: &mut Criterion) {\n\n c.bench_function(\"Transpose Swing Low Sweet Chariot\", |b| {\n\n b.iter(|| get_test_ast().transpose(black_box(2)))\n\n });\n\n}\n\n\n\ncriterion_group!(benches, criterion_benchmark);\n\ncriterion_main!(benches);\n", "file_path": "libchordr/benches/transpose_benchmark.rs", "rank": 91, "score": 64202.75326592541 }, { "content": "fn handle_error_output(error: CatalogBuildError) {\n\n let header = format!(\n\n \"Error during analysis of file {}:\",\n\n error.path().to_string_lossy()\n\n );\n\n let description = match error.source() {\n\n Some(s) => s.to_string(),\n\n None => error.message().to_owned(),\n\n };\n\n\n\n if atty::is(Stream::Stderr) {\n\n eprintln!(\"{}\", Colour::White.on(Colour::Red).paint(header));\n\n eprintln!(\"{}\", Colour::Red.paint(description));\n\n } else {\n\n eprintln!(\"{}\", header);\n\n eprintln!(\"{}\", description);\n\n }\n\n}\n\n\n", "file_path": "chordr/src/bin.rs", "rank": 92, "score": 63824.76623312129 }, { "content": "type PopulateResult = (SetlistDb, Vec<SetlistDbEntry>);\n\n\n\nimpl SetlistRepository {\n\n pub fn new() -> Self {\n\n Self {}\n\n }\n\n\n\n /// Return all [`Setlist`]'s for the given [`Username`]\n\n pub fn find_by_username(\n\n &self,\n\n connection: &ConnectionType,\n\n username: &Username,\n\n ) -> Result<Vec<Setlist>, SrvError> {\n\n let search = all_setlists\n\n .order(setlist::sorting.asc())\n\n .filter(crate::schema::setlist::owner.eq(&username.to_string()))\n\n .load::<SetlistDb>(connection)?;\n\n\n\n let owner = UserRepository::new()\n\n .find_by_name(connection, username.to_string())?\n", "file_path": "srvchord/src/domain/setlist/repository.rs", "rank": 93, "score": 63699.357732098535 }, { "content": "pub trait SongSorting<T: SongData> {\n\n fn sort_by_title(self) -> Vec<T>;\n\n}\n", "file_path": "libchordr/src/models/song_sorting.rs", "rank": 94, "score": 63565.027339103464 }, { "content": "fn start_loop(configuration: &Configuration) -> Result<()> {\n\n let sleep_interval = time::Duration::from_secs(configuration.service.sync_interval);\n\n let download_task = DownloadTask::with_configuration(configuration.clone())?;\n\n let build_catalog_task = BuildCatalogTask::with_configuration(configuration.clone())?;\n\n\n\n let collection_task = CollectionTask::new(vec![&download_task, &build_catalog_task]);\n\n info!(\n\n \"Start task loop with an interval of {} seconds\",\n\n configuration.service.sync_interval\n\n );\n\n loop {\n\n info!(\"Run tasks\");\n\n if let Err(e) = collection_task.run() {\n\n error!(\"{}\", e);\n\n }\n\n thread::sleep(sleep_interval);\n\n }\n\n}\n\n\n", "file_path": "chordr-runner/src/bin.rs", "rank": 95, "score": 63176.57984245969 }, { "content": "pub trait SongListTrait: ListTrait {}\n", "file_path": "libchordr/src/models/song_list/song_list_trait.rs", "rank": 96, "score": 62784.37167471233 }, { "content": "#[async_trait(? Send)]\n\npub trait PersistenceManagerTrait: BackendTrait {}\n", "file_path": "webchordr/persistence/src/persistence_manager/persistence_manager_trait.rs", "rank": 97, "score": 62784.37167471233 }, { "content": "fn download(args: &ArgMatches<'_>) -> Result<()> {\n\n let service_config = build_service_config(args)?;\n\n let service = Services::new(service_config.clone())?;\n\n\n\n helper::download(&service, &service_config)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "synchord/src/bin.rs", "rank": 98, "score": 62770.70406552231 }, { "content": " r#\"Great new song\n\nSubtitle: Originally known as 'Swing low sweet chariot'\n\nArtist: Me\n\nComposer: Wallace Willis\n\nLyricist: Wallace Willis\n\nYear: 1865\n\nCapo: 1\n\n\n\nSwing low, sweet chariot,\n\nComin’ for to carry me home.\n\nSwing low, sweet chariot,\n\nComin’ for to carry me home.\n\n\n\nI looked over Jordan, and what did I see,\n\nComin’ for to carry me home.\n\nA band of angels comin’ after me,\n\nComin’ for to carry me home.\n\n\"#\n\n );\n\n }\n", "file_path": "libchordr/src/converter/text/mod.rs", "rank": 99, "score": 44.3186123191613 } ]
Rust
vulkano/src/renderer_vulkano.rs
paulpage/rust_ldraw
bed7a738bc95b71b59e5d6d0b3485139a1cfe66d
use cgmath::{Matrix3, Matrix4, Point3, Rad, Vector3}; use vulkano::buffer::cpu_pool::CpuBufferPool; use std::iter; use vulkano::buffer::{BufferUsage, CpuAccessibleBuffer}; use vulkano::command_buffer::{AutoCommandBufferBuilder, DynamicState}; use vulkano::descriptor::descriptor_set::PersistentDescriptorSet; use vulkano::device::{Device, DeviceExtensions, Queue}; use vulkano::format::Format; use vulkano::framebuffer::{Framebuffer, FramebufferAbstract, RenderPassAbstract, Subpass}; use vulkano::image::attachment::AttachmentImage; use vulkano::image::SwapchainImage; use vulkano::instance::{Instance, PhysicalDevice}; use vulkano::pipeline::vertex::SingleBufferDefinition; use vulkano::pipeline::viewport::Viewport; use vulkano::pipeline::{GraphicsPipeline, GraphicsPipelineAbstract}; use vulkano::swapchain::{ self, AcquireError, PresentMode, SurfaceTransform, Swapchain, SwapchainCreationError, }; use vulkano::sync::{self, FlushError, GpuFuture}; use vulkano_win::VkSurfaceBuild; use winit::window::{Window, WindowBuilder}; use winit::event_loop::{EventLoop}; use std::sync::Arc; #[derive(Default, Debug, Clone)] pub struct Vertex { pub position: [f32; 3], pub normal: [f32; 3], pub color: [f32; 4], } pub mod vs { vulkano_shaders::shader! { ty: "vertex", src: " #version 450 layout(location = 0) in vec3 position; layout(location = 1) in vec3 normal; layout(location = 2) in vec4 color; layout(location = 0) out vec3 v_normal; layout(location = 1) out vec4 v_color; layout(set = 0, binding = 0) uniform Data { mat4 world; mat4 view; mat4 proj; } uniforms; void main() { mat4 worldview = uniforms.view * uniforms.world; v_normal = transpose(inverse(mat3(worldview))) * normal; v_color = color; gl_Position = uniforms.proj * worldview * vec4(position, 1.0); }" } } pub mod fs { vulkano_shaders::shader! { ty: "fragment", src: " #version 450 layout(location = 0) in vec3 v_normal; layout(location = 1) in vec4 v_color; layout(location = 0) out vec4 f_color; const vec3 LIGHT = vec3(0.8, 0.8, 0.8); void main() { float brightness = dot(normalize(v_normal), normalize(LIGHT)); vec3 dark_color = v_color.xyz * 0.1; vec3 regular_color = v_color.xyz; f_color = vec4(mix(dark_color, regular_color, brightness), v_color.w); }" } } pub struct VulkanoRenderer { vertices: Vec<Vertex>, previous_frame_end: Box<dyn GpuFuture>, recreate_swapchain: bool, dimensions: [u32; 2], window: Window, device: Arc<Device>, vs: vs::Shader, fs: fs::Shader, pipeline: Arc<dyn GraphicsPipelineAbstract + Send + Sync>, framebuffers: Vec<Arc<dyn FramebufferAbstract + Send + Sync>>, uniform_buffer: CpuBufferPool<vs::ty::Data>, render_pass: Arc<dyn RenderPassAbstract + Send + Sync>, queue: Arc<Queue>, vertex_buffer: Arc<CpuAccessibleBuffer<[Vertex]>>, swapchain: Arc<Swapchain<Window>>, } impl VulkanoRenderer { pub fn new(vertices: Vec<Vertex>, event_loop: &EventLoop<()>) -> Self { let instance = { let extensions = vulkano_win::required_extensions(); Instance::new(None, &extensions, None).expect("failed to create Vulkan instance") }; let physical = PhysicalDevice::enumerate(&instance).next().unwrap(); let surface = WindowBuilder::new() .build_vk_surface(&event_loop, instance.clone()) .unwrap(); let window = surface.window(); let mut dimensions = if let Some(dimensions) = window.get_inner_size() { let dimensions: (u32, u32) = dimensions.to_physical(window.get_hidpi_factor()).into(); [dimensions.0, dimensions.1] } else { panic!("Failed to set window dimensions."); }; let queue_family = physical .queue_families() .find(|&q| q.supports_graphics() && surface.is_supported(q).unwrap_or(false)) .unwrap(); let device_ext = DeviceExtensions { khr_swapchain: true, ..DeviceExtensions::none() }; let (device, mut queues) = Device::new( physical, physical.supported_features(), &device_ext, [(queue_family, 0.5)].iter().cloned(), ) .unwrap(); let queue = queues.next().unwrap(); let (mut swapchain, images) = { let caps = surface.capabilities(physical).unwrap(); let usage = caps.supported_usage_flags; let format = caps.supported_formats[0].0; let alpha = caps.supported_composite_alpha.iter().next().unwrap(); let initial_dimensions = if let Some(dimensions) = window.get_inner_size() { let dimensions: (u32, u32) = dimensions.to_physical(window.get_hidpi_factor()).into(); [dimensions.0, dimensions.1] } else { panic!("Failed to set window dimensions."); }; Swapchain::new( device.clone(), surface.clone(), caps.min_image_count, format, initial_dimensions, 1, usage, &queue, SurfaceTransform::Identity, alpha, PresentMode::Fifo, true, None, ) .unwrap() }; let vertex_buffer = { vulkano::impl_vertex!(Vertex, position, normal, color); CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::all(), vertices.iter().cloned()) .unwrap() }; let uniform_buffer = CpuBufferPool::<vs::ty::Data>::new(device.clone(), BufferUsage::all()); let vs = vs::Shader::load(device.clone()).expect("failed to create shader module"); let fs = fs::Shader::load(device.clone()).expect("failed to create shader module"); let render_pass = Arc::new( vulkano::single_pass_renderpass!(device.clone(), attachments: { color: { load: Clear, store: Store, format: swapchain.format(), samples: 1, }, depth: { load: Clear, store: DontCare, format: Format::D16Unorm, samples: 1, } }, pass: { color: [color], depth_stencil: {depth} } ) .unwrap(), ); let (mut pipeline, mut framebuffers) = window_size_dependent_setup(device.clone(), &vs, &fs, &images, render_pass.clone()); let mut recreate_swapchain = false; let mut previous_frame_end = Box::new(sync::now(device.clone())) as Box<dyn GpuFuture>; VulkanoRenderer { vertices, previous_frame_end, recreate_swapchain, dimensions, swapchain, device, vs, fs, render_pass, pipeline, uniform_buffer, framebuffers, queue, vertex_buffer, window: *window, } } pub fn draw(&mut self, rotation: Vector3<f32>, d_rotation: Vector3<f32>, camera_position: Point3<f32>, camera_relative: Vector3<f32>, d_camera_position: Point3<f32>, d_camera_relative: Vector3<f32>) { self.previous_frame_end.cleanup_finished(); if self.recreate_swapchain { self.dimensions = if let Some(dimensions) = self.window.get_inner_size() { let dimensions: (u32, u32) = dimensions.to_physical(self.window.get_hidpi_factor()).into(); [dimensions.0, dimensions.1] } else { return; }; let (new_swapchain, new_images) = match self.swapchain.recreate_with_dimension(self.dimensions) { Ok(r) => r, Err(SwapchainCreationError::UnsupportedDimensions) => return, Err(err) => panic!("{:?}", err), }; self.swapchain = new_swapchain; let (new_pipeline, new_framebuffers) = window_size_dependent_setup( self.device.clone(), &self.vs, &self.fs, &new_images, self.render_pass.clone(), ); self.pipeline = new_pipeline; self.framebuffers = new_framebuffers; self.recreate_swapchain = false; } let uniform_buffer_subbuffer = { let rotation = Matrix3::from_angle_y(Rad(rotation.y + d_rotation.y)) * Matrix3::from_angle_x(Rad(rotation.x + d_rotation.x)); let aspect_ratio = self.dimensions[0] as f32 / self.dimensions[1] as f32; let proj = cgmath::perspective(Rad(std::f32::consts::FRAC_PI_2), aspect_ratio, 0.01, 100.0); let z = camera_relative.x * camera_relative.y.sin() * camera_relative.z.cos(); let x = camera_relative.x * camera_relative.y.sin() * camera_relative.z.sin(); let y = camera_relative.x * camera_relative.y.cos(); let mut eye = camera_position; eye.x += x; eye.y += y; eye.z += z; let view = Matrix4::look_at( eye, camera_position, Vector3::new(0.0, 1.0, 0.0), ); let scale = Matrix4::from_scale(0.01); let uniform_data = vs::ty::Data { world: Matrix4::from(rotation).into(), view: (view * scale).into(), proj: proj.into(), }; self.uniform_buffer.next(uniform_data).unwrap() }; let set = Arc::new( PersistentDescriptorSet::start(self.pipeline.clone(), 0) .add_buffer(uniform_buffer_subbuffer) .unwrap() .build() .unwrap(), ); let (image_num, acquire_future) = match swapchain::acquire_next_image(self.swapchain.clone(), None) { Ok(r) => r, Err(AcquireError::OutOfDate) => { self.recreate_swapchain = true; return; } Err(err) => panic!("{:?}", err), }; let command_buffer = AutoCommandBufferBuilder::primary_one_time_submit(self.device.clone(), self.queue.family()) .unwrap() .begin_render_pass( self.framebuffers[image_num].clone(), false, vec![[0.0, 1.0, 1.0, 1.0].into(), 1f32.into()], ) .unwrap() .draw( self.pipeline.clone(), &DynamicState::none(), vec![self.vertex_buffer.clone()], set.clone(), (), ) .unwrap() .end_render_pass() .unwrap() .build() .unwrap(); let future = &self.previous_frame_end .join(acquire_future) .then_execute(self.queue.clone(), command_buffer) .unwrap() .then_swapchain_present(self.queue.clone(), self.swapchain.clone(), image_num) .then_signal_fence_and_flush(); match future { Ok(future) => { future.wait(None).unwrap(); self.previous_frame_end = future.boxed(); } Err(FlushError::OutOfDate) => { self.recreate_swapchain = true; self.previous_frame_end = Box::new(sync::now(self.device.clone())) as Box<_>; } Err(_) => { self.previous_frame_end = Box::new(sync::now(self.device.clone())) as Box<_>; } } } pub fn resize_window(&mut self) { self.recreate_swapchain = true; } } pub fn window_size_dependent_setup( device: Arc<Device>, vs: &vs::Shader, fs: &fs::Shader, images: &[Arc<SwapchainImage<Window>>], render_pass: Arc<dyn RenderPassAbstract + Send + Sync>, ) -> ( Arc<dyn GraphicsPipelineAbstract + Send + Sync>, Vec<Arc<dyn FramebufferAbstract + Send + Sync>>, ) { let dimensions = images[0].dimensions(); let depth_buffer = AttachmentImage::transient(device.clone(), dimensions, Format::D16Unorm).unwrap(); let framebuffers = images .iter() .map(|image| { Arc::new( Framebuffer::start(render_pass.clone()) .add(image.clone()) .unwrap() .add(depth_buffer.clone()) .unwrap() .build() .unwrap(), ) as Arc<dyn FramebufferAbstract + Send + Sync> }) .collect::<Vec<_>>(); let pipeline = Arc::new( GraphicsPipeline::start() .vertex_input(SingleBufferDefinition::<Vertex>::new()) .vertex_shader(vs.main_entry_point(), ()) .triangle_list() .viewports_dynamic_scissors_irrelevant(1) .viewports(iter::once(Viewport { origin: [0.0, 0.0], dimensions: [dimensions[0] as f32, dimensions[1] as f32], depth_range: 0.0..1.0, })) .fragment_shader(fs.main_entry_point(), ()) .depth_stencil_simple_depth() .render_pass(Subpass::from(render_pass.clone(), 0).unwrap()) .build(device.clone()) .unwrap(), ); (pipeline, framebuffers) }
use cgmath::{Matrix3, Matrix4, Point3, Rad, Vector3}; use vulkano::buffer::cpu_pool::CpuBufferPool; use std::iter; use vulkano::buffer::{BufferUsage, CpuAccessibleBuffer}; use vulkano::command_buffer::{AutoCommandBufferBuilder, DynamicState}; use vulkano::descriptor::descriptor_set::PersistentDescriptorSet; use vulkano::device::{Device, DeviceExtensions, Queue}; use vulkano::format::Format; use vulkano::framebuffer::{Framebuffer, FramebufferAbstract, RenderPassAbstract, Subpass}; use vulkano::image::attachment::AttachmentImage; use vulkano::image::SwapchainImage; use vulkano::instance::{Instance, PhysicalDevice}; use vulkano::pipeline::vertex::SingleBufferDefinition; use vulkano::pipeline::viewport::Viewport; use vulkano::pipeline::{GraphicsPipeline, GraphicsPipelineAbstract}; use vulkano::swapchain::{ self, AcquireError, PresentMode, SurfaceTransform, Swapchain, SwapchainCreationError, }; use vulkano::sync::{self, FlushError, GpuFuture}; use vulkano_win::VkSurfaceBuild; use winit::window::{Window, WindowBuilder}; use winit::event_loop::{EventLoop}; use std::sync::Arc; #[derive(Default, Debug, Clone)] pub struct Vertex { pub position: [f32; 3], pub normal: [f32; 3], pub color: [f32; 4], } pub mod vs { vulkano_shaders::shader! { ty: "vertex", src: " #version 450 layout(location = 0) in vec3 position; layout(location = 1) in vec3 normal; layout(location = 2) in vec4 color; layout(location = 0) out vec3 v_normal; layout(location = 1) out vec4 v_color; layout(set = 0, binding = 0) uniform Data { mat4 world; mat4 view; mat4 proj; } uniforms; void main() { mat4 worldview = uniforms.view * uniforms.world; v_normal = transpose(inverse(mat3(worldview))) * normal; v_color = color; gl_Position = uniforms.proj * worldview * vec4(position, 1.0); }" } } pub mod fs { vulkano_shaders::shader! { ty: "fragment", src: " #version 450 layout(location = 0) in vec3 v_normal; layout(location = 1) in vec4 v_color; layout(location = 0) out vec4 f_color; const vec3 LIGHT = vec3(0.8, 0.8, 0.8); void main() { float brightness = dot(normalize(v_normal), normalize(LIGHT)); vec3 dark_color = v_color.xyz * 0.1; vec3 regular_color = v_color.xyz; f_color = vec4(mix(dark_color, regular_color, brightness), v_color.w); }" } } pub struct VulkanoRenderer { vertices: Vec<Vertex>, previous_frame_end: Box<dyn GpuFuture>, recreate_swapchain: bool, dimensions: [u32; 2], window: Window, device: Arc<Device>, vs: vs::Shader, fs: fs::Shader, pipeline: Arc<dyn GraphicsPipelineAbstract + Send + Sync>, framebuffers: Vec<Arc<dyn FramebufferAbstract + Send + Sync>>, uniform_buffer: CpuBufferPool<vs::ty::Data>, render_pass: Arc<dyn RenderPassAbstract + Send + Sync>, queue: Arc<Queue>, vertex_buffer: Arc<CpuAccessibleBuffer<[Vertex]>>, swapchain: Arc<Swapchain<Window>>, } impl VulkanoRenderer { pub fn new(vertices: Vec<Vertex>, event_loop: &EventLoop<()>) -> Self { let instance = { let extensions = vulkano_win::required_extensions(); Instance::new(None, &extensions, None).expect("failed to create Vulkan instance") }; let physical = PhysicalDevice::enumerate(&instance).next().unwrap(); let surface = WindowBuilder::new() .build_vk_surface(&event_loop, instance.clone()) .unwrap(); let window = surface.window(); let mut dimensions = if let Some(dimensions) = window.get_inner_size() { let dimensions: (u32, u32) = dimensions.to_physical(window.get_hidpi_factor()).into(); [dimensions.0, dimensions.1] } else { panic!("Failed to set window dimensions."); }; let queue_family = physical .queue_families() .find(|&q| q.supports_graphics() && surface.is_supported(q).unwrap_or(false)) .unwrap(); let device_ext = DeviceExtensions { khr_swapchain: true, ..DeviceExtensions::none() }; let (device, mut queues) = Device::new( physical, physical.supported_features(), &device_ext, [(queue_family, 0.5)].iter().cloned(), ) .unwrap(); let queue = queues.next().unwrap(); let (mut swapchain, images) = { let caps = surface.capabilities(physical).unwrap(); let usage = caps.supported_usage_flags; let format = caps.supported_formats[0].0; let alpha = caps.supported_composite_alpha.iter().next().unwrap(); let initial_dimensions = if let Some(dimensions) = window.get_inner_size() { let dimensions: (u32, u32) = dimensions.to_physical(window.get_hidpi_factor()).into(); [dimensions.0, dimensions.1] } else { panic!("Failed to set window dimensions."); }; Swapchain::new( device.clone(), surface.clone(), caps.min_image_count, format, initial_dimensions, 1, usage, &queue, SurfaceTransform::Identity, alpha, PresentMode::Fifo, true, None, ) .unwrap() }; let vertex_buffer = { vulkano::impl_vertex!(Vertex, position, normal, color); CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::all(), vertices.iter().cloned()) .unwrap() }; let uniform_buffer = CpuBufferPool::<vs::ty::Data>::new(device.clone(), BufferUsage::all()); let vs = vs::Shader::load(device.clone()).expect("failed to create shader module"); let fs = fs::Shader::load(device.clone()).expect("failed to create shader module"); let render_pass = Arc::new( vulkano::single_pass_renderpass!(device.clone(), attachments: { color: { load: Clear, store: Store, format: swapchain.format(), samples: 1, }, depth: { load: Clear, store: DontCare, format: Format::D16Unorm, samples: 1, } }, pass: { color: [color], depth_stencil: {depth} } ) .unwrap(), ); let (mut pipeline, mut framebuffers) = window_size_dependent_setup(device.clone(), &vs, &fs, &images, render_pass.clone()); let mut recreate_swapchain = false; let mut previous_frame_end = Box::new(sync::now(device.clone())) as Box<dyn GpuFuture>; VulkanoRenderer { vertices, previous_frame_end, recreate_swapchain, dimensions, swapchain, device, vs, fs, render_pass, pipeline, uniform_buffer, framebuffers, queue, vertex_buffer, window: *window, } } pub fn draw(&mut self, rotation: Vector3<f32>, d_rotation: Vector3<f32>, camera_position: Point3<f32>, camera_relative: Vector3<f32>, d_camera_position: Point3<f32>, d_camera_relative: Vector3<f32>) { self.previous_frame_end.cleanup_finished(); if self.recreate_swapchain { self.dimensions = if let Some(dimensions) = self.window.get_inner_size() { let dimensions: (u32, u32) = dimensions.to_physical(self.window.get_hidpi_factor()).into(); [dimensions.0, dimensions.1] } else { return; }; let (new_swapchain, new_images) = match self.swapchain.recreate_with_dimension(self.dimensions) { Ok(r) => r, Err(SwapchainCreationError::UnsupportedDimensions) => return, Err(err) => panic!("{:?}", err), }; self.swapchain = new_swapchain; let (new_pipeline, new_framebuffers) = window_size_dependent_setup( self.device.clone(), &self.vs, &self.fs, &new_images, self.render_pass.clone(), ); self.pipeline = new_pipeline; self.framebuffers = new_framebuffers; self.recreate_swapchain = false; } let uniform_buffer_subbuffer = { let rotation = Matrix3::from_angle_y(Rad(rotation.y + d_rotation.y)) * Matrix3::from_angle_x(Rad(rotation.x + d_rotation.x)); let aspect_ratio = self.dimensions[0] as f32 / self.dimensions[1] as f32; let proj = cgmath::perspective(Rad(std::f32::consts::FRAC_PI_2), aspect_ratio, 0.01, 100.0); let z = camera_relative.x * camera_relative.y.sin() * camera_relative.z.cos(); let x = camera_relative.x * camera_relative.y.sin() * camera_relative.z.sin(); let y = camera_relative.x * camera_relative.y.cos(); let mut eye = camera_position; eye.x += x; eye.y += y; eye.z += z; let view = Matrix4::look_at( eye, camera_position, Vector3::new(0.0, 1.0, 0.0), ); let scale = Matrix4::from_scale(0.01); let uniform_data = vs::ty::Data { world: Matrix4::from(rotation).into(), view: (view * scale).into(), proj: proj.into(), }; self.uniform_buffer.next(uniform_data).unwrap() }; let set = Arc::new( PersistentDescriptorSet::start(self.pipeline.clone(), 0) .add_buffer(uniform_buffer_subbuffer) .unwrap() .build() .unwrap(), ); let (image_num, acquire_future) = match swapchain::acquire_next_image(self.swapchain.clone(), None) { Ok(r) => r, Err(AcquireError::OutOfDate) => { self.recreate_swapchain = true; return; } Err(err) => panic!("{:?}", err), }; let command_buffer = AutoCommandBufferBuilder::primary_one_time_submit(self.device.clone(), self.queue.family()) .unwrap() .begin_render_pass( self.framebuffers[image_num].clone(), false, vec![[0.0, 1.0, 1.0, 1.0].into(), 1f32.into()], ) .unwrap() .draw( self.pipeline.clone(), &DynamicState::none(), vec![self.vertex_buffer.clone()], set.clone(), (), ) .unwrap() .end_render_pass() .unwrap() .build() .unwrap(); let future = &self.previous_frame_end .join(acquire_future) .then_execute(self.queue.clone(), command_buffer) .unwrap() .then_swapchain_present(self.queue.clone(), self.swapchain.clone(), image_num) .then_signal_fence_and_flush(); match future { Ok(future) => { future.wait(None).unwrap(); self.previous_frame_end = future.boxed(); } Err(FlushError::OutOfDate) => { self.recreate_swapchain = true; self.previous_frame_end = Box::new(sync::now(self.device.clone())) as Box<_>; } Err(_) => { self.previous_frame_end = Box::new(sync::now(self.device.clone())) as Box<_>; } } } pub fn resize_window(&mut self) { self.recreate_swapchain = true; } } pub fn window_size_dependent_setup( device: Arc<Device>, vs: &vs::Shader, fs: &fs::Shader, images: &[Arc<SwapchainImage<Window>>], render_pass: Arc<dyn RenderPassAbstract + Send + Sync>, ) -> ( Arc<dyn GraphicsPipelineAbstract + Send + Sync>, Vec<Arc<dyn FramebufferAbstract + Send + Sync>>, ) { let dimensions = images[0].dimensions(); let depth_buffer = AttachmentImage::transient(device.clone(), dimensions, Format::D16Unorm).unwrap(); let framebuffers = image
s .iter() .map(|image| { Arc::new( Framebuffer::start(render_pass.clone()) .add(image.clone()) .unwrap() .add(depth_buffer.clone()) .unwrap() .build() .unwrap(), ) as Arc<dyn FramebufferAbstract + Send + Sync> }) .collect::<Vec<_>>(); let pipeline = Arc::new( GraphicsPipeline::start() .vertex_input(SingleBufferDefinition::<Vertex>::new()) .vertex_shader(vs.main_entry_point(), ()) .triangle_list() .viewports_dynamic_scissors_irrelevant(1) .viewports(iter::once(Viewport { origin: [0.0, 0.0], dimensions: [dimensions[0] as f32, dimensions[1] as f32], depth_range: 0.0..1.0, })) .fragment_shader(fs.main_entry_point(), ()) .depth_stencil_simple_depth() .render_pass(Subpass::from(render_pass.clone(), 0).unwrap()) .build(device.clone()) .unwrap(), ); (pipeline, framebuffers) }
function_block-function_prefixed
[ { "content": "fn unproject(source: Vector3<f32>, view: Matrix4<f32>, proj: Matrix4<f32>) -> Vector3<f32> {\n\n let view_proj = (proj * view).invert().unwrap();\n\n let q = view_proj * Vector4::new(source.x, source.y, source.z, 1.0);\n\n Vector3::new(q.x / q.w, q.y / q.w, q.z / q.w)\n\n}\n\n\n", "file_path": "src/graphics.rs", "rank": 0, "score": 202968.88952742802 }, { "content": "fn get_mouse_ray(aspect_ratio: f32, mouse_position: Vector2<f32>, camera: &Camera) -> (Point3<f32>, Vector3<f32>) {\n\n let view = Matrix4::look_at(camera.position(), camera.focus, Vector3::new(0.0, 1.0, 0.0));\n\n let proj = cgmath::perspective(Deg(camera.fovy), aspect_ratio, 0.01, 100.0);\n\n let near = unproject(Vector3::new(mouse_position.x, mouse_position.y, 0.0), view, proj);\n\n let far = unproject(Vector3::new(mouse_position.x, mouse_position.y, 1.0), view, proj);\n\n let direction = far - near;\n\n (camera.position(), direction)\n\n}\n\n\n\npub mod gl {\n\n pub use self::Gles2 as Gl;\n\n include!(concat!(env!(\"OUT_DIR\"), \"/gl_bindings.rs\"));\n\n}\n\n\n\npub struct Graphics {\n\n pub windowed_context: glutin::ContextWrapper<PossiblyCurrent, Window>,\n\n pub window_width: i32,\n\n pub window_height: i32,\n\n program: u32,\n\n program_2d: u32,\n\n program_text: u32,\n\n program_texture: u32,\n\n pub gl: gl::Gl,\n\n uniforms: Uniforms,\n\n font: rusttype::Font<'static>,\n\n}\n\n\n", "file_path": "src/graphics.rs", "rank": 1, "score": 139653.77441340804 }, { "content": "fn point_from(data: &[&str], x: usize, y: usize, z: usize) -> Point3<f32> {\n\n Point3 {\n\n x: data[x].parse::<f32>().unwrap(),\n\n y: data[y].parse::<f32>().unwrap(),\n\n z: data[z].parse::<f32>().unwrap(),\n\n }\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 2, "score": 135214.53259188132 }, { "content": "pub fn norm(p: &Polygon) -> Vector3<f32> {\n\n let u = Vector3 {\n\n x: p.points[1].x - p.points[0].x,\n\n y: p.points[1].y - p.points[0].y,\n\n z: p.points[1].z - p.points[0].z,\n\n };\n\n let v = Vector3 {\n\n x: p.points[2].x - p.points[0].x,\n\n y: p.points[2].y - p.points[0].y,\n\n z: p.points[2].z - p.points[0].z,\n\n };\n\n Vector3 {\n\n x: (u.y * v.z - u.z * v.y),\n\n y: (u.x * v.z - u.z * v.x) * -1.0,\n\n z: (u.x * v.y - u.y * v.x),\n\n }\n\n}\n\n\n\n#[derive(Hash, PartialEq, Debug)]\n\npub struct CacheKey {\n\n name: String,\n\n inverted: bool,\n\n}\n\n\n\n// TODO can probably just derive Eq\n\nimpl Eq for CacheKey {}\n\n\n\n\n", "file_path": "src/parser.rs", "rank": 3, "score": 133623.95914001955 }, { "content": "fn mat_to_array(m: Matrix4<f32>) -> [f32; 16] {\n\n [\n\n // OpenGL is column-major by default\n\n m.x.x, m.x.y, m.x.z, m.x.w,\n\n m.y.x, m.y.y, m.y.z, m.y.w,\n\n m.z.x, m.z.y, m.z.z, m.z.w,\n\n m.w.x, m.w.y, m.w.z, m.w.w,\n\n ]\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 4, "score": 132849.6147789924 }, { "content": "fn point_from(data: &[&str], x: usize, y: usize, z: usize) -> Point3<f32> {\n\n Point3 {\n\n x: data[x].parse::<f32>().unwrap(),\n\n y: data[y].parse::<f32>().unwrap(),\n\n z: data[z].parse::<f32>().unwrap(),\n\n }\n\n}\n\n\n", "file_path": "vulkano/src/parser.rs", "rank": 5, "score": 131960.1827200589 }, { "content": "fn get_global_transforms(state: &State) -> (Matrix4<f32>, Matrix4<f32>) {\n\n let view = Matrix4::look_at(\n\n state.camera.position(),\n\n state.camera.focus,\n\n Vector3::new(0.0, 1.0, 0.0)\n\n );\n\n let proj = cgmath::perspective(Deg(state.camera.fovy), state.aspect_ratio, 0.01, 100.0);\n\n (view, proj)\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 6, "score": 129653.80889154629 }, { "content": "pub fn norm(p: &Polygon) -> Vector3<f32> {\n\n let u = Vector3 {\n\n x: p.points[1].x - p.points[0].x,\n\n y: p.points[1].y - p.points[0].y,\n\n z: p.points[1].z - p.points[0].z,\n\n };\n\n let v = Vector3 {\n\n x: p.points[2].x - p.points[0].x,\n\n y: p.points[2].y - p.points[0].y,\n\n z: p.points[2].z - p.points[0].z,\n\n };\n\n Vector3 {\n\n x: (u.y * v.z - u.z * v.y),\n\n y: (u.x * v.z - u.z * v.x) * -1.0,\n\n z: (u.x * v.y - u.y * v.x),\n\n }\n\n}\n\n\n", "file_path": "vulkano/src/parser.rs", "rank": 7, "score": 129311.96445730561 }, { "content": "fn load_ldraw_file(gl: &mut Graphics, parser: &mut Parser, filename: &str, custom_color: Option<[f32; 4]>) -> Model {\n\n let polygons = parser.load(filename);\n\n let mut vertices = Vec::new();\n\n let mut bounding_box = BoundingBox {\n\n min: Point3::new(f32::MAX, f32::MAX, f32::MAX),\n\n max: Point3::new(f32::MIN, f32::MIN, f32::MIN),\n\n };\n\n for polygon in &polygons {\n\n let mut color = match polygon.color {\n\n parser::LdrawColor::RGBA(r, g, b, a) => [r, g, b, a],\n\n _ => [0.0, 1.0, 0.0, 1.0],\n\n };\n\n if let Some(c) = custom_color {\n\n color = c;\n\n }\n\n\n\n if polygon.points.len() == 3 {\n\n let n = parser::norm(polygon);\n\n for point in &polygon.points {\n\n\n", "file_path": "src/main.rs", "rank": 8, "score": 126879.0299162626 }, { "content": "fn main() {\n\n let dest = PathBuf::from(&env::var(\"OUT_DIR\").unwrap());\n\n\n\n println!(\"cargo:rerun-if-changed=build.rs\");\n\n\n\n let mut file = File::create(&dest.join(\"gl_bindings.rs\")).unwrap();\n\n Registry::new(Api::Gles2, (3, 3), Profile::Core, Fallbacks::All, [])\n\n .write_bindings(gl_generator::StructGenerator, &mut file)\n\n .unwrap();\n\n}\n", "file_path": "build.rs", "rank": 9, "score": 110176.50297412366 }, { "content": "fn fmax(a: f32, b: f32) -> f32 {\n\n if b > a { b } else { a }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 10, "score": 108652.20920616595 }, { "content": "fn fmin(a: f32, b: f32) -> f32 {\n\n if b < a { b } else { a }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 11, "score": 108652.20920616595 }, { "content": "fn create_shader(gl: &gl::Gl, shader_type: u32, source: &'static [u8]) -> u32 {\n\n unsafe {\n\n let id = gl.CreateShader(shader_type);\n\n gl.ShaderSource(\n\n id,\n\n 1,\n\n [source.as_ptr() as *const _].as_ptr(),\n\n std::ptr::null()\n\n );\n\n gl.CompileShader(id);\n\n let mut success: gl::types::GLint = 1;\n\n gl.GetShaderiv(id, gl::COMPILE_STATUS, &mut success);\n\n if success == 0 {\n\n let mut len: gl::types::GLint = 0;\n\n gl.GetShaderiv(id, gl::INFO_LOG_LENGTH, &mut len);\n\n let error = {\n\n let mut buffer: Vec<u8> = Vec::with_capacity(len as usize + 1);\n\n buffer.extend([b' '].iter().cycle().take(len as usize));\n\n CString::from_vec_unchecked(buffer)\n\n };\n\n gl.GetShaderInfoLog(id, len, std::ptr::null_mut(), error.as_ptr() as *mut gl::types::GLchar);\n\n eprintln!(\"{}\", error.to_string_lossy());\n\n }\n\n id\n\n }\n\n}\n\n\n", "file_path": "src/graphics.rs", "rank": 13, "score": 103131.11317717805 }, { "content": "struct Light {\n\n vec3 position;\n\n vec3 direction;\n\n\n\n vec3 ambient;\n\n vec3 diffuse;\n\n vec3 specular;\n\n};\n\n\n\nuniform vec3 view_position;\n\nuniform Light light;\n\n\n\n// const vec3 LIGHT = vec3(1.0, 1.0, 1.0);\n\n\n\nvoid main() {\n\n\n\n vec3 norm = normalize(v_normal);\n\n vec3 light_direction = normalize(light.position - fragment_position);\n\n vec3 view_direction = normalize(view_position - fragment_position);\n\n vec3 reflection_direction = reflect(-light_direction, norm);\n", "file_path": "src/graphics.rs", "rank": 14, "score": 101255.91001048929 }, { "content": "fn main() {\n\n\n\n let mut parser = Parser::new(\"/home/paul/Downloads/ldraw\");\n\n let event_loop = EventLoop::new();\n\n let mut graphics = graphics::init(&event_loop);\n\n\n\n let mut state = State::new();\n\n let mut input = InputState::new();\n\n let mut models = Vec::new();\n\n\n\n let start = Instant::now();\n\n\n\n let mut new_position = Vector3::new(0, 0, 0);\n\n // // models.push(load_ldraw_file(ldraw_dir, \"car.ldr\", None));\n\n\n\n println!(\n\n \"load time: {} ms\",\n\n start.elapsed().as_millis(),\n\n );\n\n\n", "file_path": "src/main.rs", "rank": 15, "score": 95313.59231420085 }, { "content": "fn main() {\n\n let start = Instant::now();\n\n let polygons = read_file(\"/home/paul/Downloads/ldraw/\", \"3001.dat\", false);\n\n println!(\n\n \"Loaded {} polygons in {} ms.\",\n\n polygons.len(),\n\n start.elapsed().as_millis()\n\n );\n\n\n\n let mut vertices = Vec::new();\n\n\n\n for polygon in &polygons {\n\n let color = match polygon.color {\n\n LdrawColor::RGBA(r, g, b, a) => [r, g, b, a],\n\n _ => [0.0, 1.0, 0.0, 1.0],\n\n };\n\n if polygon.points.len() == 3 {\n\n let n = norm(polygon);\n\n vertices.push(Vertex {\n\n position: [\n", "file_path": "vulkano/src/main.rs", "rank": 16, "score": 91896.68260465973 }, { "content": "pub fn init(\n\n event_loop: &EventLoop<()>\n\n) -> Graphics {\n\n\n\n let windowed_context = {\n\n let window_builder = WindowBuilder::new().with_title(\"Bricks\");\n\n let windowed_context =\n\n ContextBuilder::new().with_vsync(true).build_windowed(window_builder, event_loop).unwrap();\n\n unsafe { windowed_context.make_current().unwrap() }\n\n };\n\n let gl_context = windowed_context.context();\n\n let (window_width, window_height) = {\n\n let size = windowed_context.window().inner_size(); \n\n (size.width as i32, size.height as i32)\n\n };\n\n\n\n let gl = gl::Gl::load_with(|ptr| gl_context.get_proc_address(ptr) as *const _);\n\n let font = rusttype::Font::try_from_bytes(include_bytes!(\"../data/LiberationSans-Regular.ttf\") as &[u8]).unwrap();\n\n\n\n unsafe {\n", "file_path": "src/graphics.rs", "rank": 17, "score": 81147.04534462366 }, { "content": "struct State {\n\n camera: Camera,\n\n aspect_ratio: f32,\n\n active_model_idx: usize,\n\n}\n\n\n\nimpl State {\n\n fn new() -> Self {\n\n Self {\n\n aspect_ratio: 1.0,\n\n camera: Camera::new(),\n\n active_model_idx: 0,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 18, "score": 79474.73814312607 }, { "content": "pub fn read_file(ldraw_directory: &str, filename: &str, inverted: bool) -> Vec<Polygon> {\n\n let mut polygons = Vec::new();\n\n // TODO: Also allow current part's directory\n\n let filename = filename.to_lowercase();\n\n let paths: Vec<PathBuf> = vec![\n\n PathBuf::new().join(ldraw_directory).join(&filename),\n\n PathBuf::new()\n\n .join(ldraw_directory)\n\n .join(\"parts\")\n\n .join(&filename),\n\n PathBuf::new()\n\n .join(ldraw_directory)\n\n .join(\"p\")\n\n .join(&filename),\n\n PathBuf::new()\n\n .join(ldraw_directory)\n\n .join(\"models\")\n\n .join(&filename),\n\n PathBuf::new().join(\".\").join(&filename),\n\n ];\n", "file_path": "vulkano/src/parser.rs", "rank": 19, "score": 75342.14362234532 }, { "content": "fn create_program(\n\n gl: &gl::Gl,\n\n vertex_shader: &'static [u8],\n\n fragment_shader: &'static [u8],\n\n) -> u32 {\n\n let vs = create_shader(gl, gl::VERTEX_SHADER, vertex_shader);\n\n let fs = create_shader(gl, gl::FRAGMENT_SHADER, fragment_shader);\n\n \n\n unsafe {\n\n let program = gl.CreateProgram();\n\n gl.AttachShader(program, vs);\n\n gl.AttachShader(program, fs);\n\n gl.LinkProgram(program);\n\n let mut success: gl::types::GLint = 1;\n\n gl.GetProgramiv(program, gl::LINK_STATUS, &mut success);\n\n if success == 0 {\n\n let mut len: gl::types::GLint = 0;\n\n gl.GetShaderiv(program, gl::INFO_LOG_LENGTH, &mut len);\n\n let error = {\n\n let mut buffer: Vec<u8> = Vec::with_capacity(len as usize + 1);\n", "file_path": "src/graphics.rs", "rank": 20, "score": 64438.311042123205 }, { "content": "fn read_file(cache: &mut HashMap<CacheKey, Vec<Polygon>>, ldraw_directory: &str, filename: &str, inverted: bool) -> Vec<Polygon> {\n\n if let Some(polygon) = cache.get(&CacheKey { name: filename.into(), inverted }) {\n\n return polygon.clone();\n\n }\n\n let mut polygons = Vec::new();\n\n // TODO: Also allow current part's directory\n\n let filename = filename.to_lowercase();\n\n let paths: Vec<PathBuf> = vec![\n\n PathBuf::new().join(ldraw_directory).join(&filename),\n\n PathBuf::new()\n\n .join(ldraw_directory)\n\n .join(\"parts\")\n\n .join(&filename),\n\n PathBuf::new()\n\n .join(ldraw_directory)\n\n .join(\"p\")\n\n .join(&filename),\n\n PathBuf::new()\n\n .join(ldraw_directory)\n\n .join(\"models\")\n", "file_path": "src/parser.rs", "rank": 21, "score": 62266.56507934057 }, { "content": "pub fn write_obj(polygons: &[Polygon], filename: &str) -> Result<()> {\n\n let start = Instant::now();\n\n let output = OpenOptions::new()\n\n .write(true)\n\n .create(true)\n\n .truncate(true)\n\n .open(filename)?;\n\n let mut output = BufWriter::new(output);\n\n // writeln!(output, \"mtllib test.mtl\")?;\n\n\n\n for p in polygons {\n\n for v in &p.points {\n\n writeln!(output, \"v {} {} {}\", v.x, v.y * -1.0, v.z)?;\n\n }\n\n }\n\n let norms: Vec<Vector3<f32>> = polygons.iter().map(|p| norm(p)).collect();\n\n for n in &norms {\n\n writeln!(output, \"vn {} {} {}\", n.x, n.y, n.z)?;\n\n }\n\n\n", "file_path": "src/parser.rs", "rank": 22, "score": 59145.49053797184 }, { "content": "pub fn write_obj(polygons: &[Polygon], filename: &str) -> Result<()> {\n\n let start = Instant::now();\n\n let output = OpenOptions::new()\n\n .write(true)\n\n .create(true)\n\n .truncate(true)\n\n .open(filename)?;\n\n let mut output = BufWriter::new(output);\n\n // writeln!(output, \"mtllib test.mtl\")?;\n\n\n\n for p in polygons {\n\n for v in &p.points {\n\n writeln!(output, \"v {} {} {}\", v.x, v.y * -1.0, v.z)?;\n\n }\n\n }\n\n let norms: Vec<Vector3<f32>> = polygons.iter().map(|p| norm(p)).collect();\n\n for n in &norms {\n\n writeln!(output, \"vn {} {} {}\", n.x, n.y, n.z)?;\n\n }\n\n\n", "file_path": "vulkano/src/parser.rs", "rank": 23, "score": 57406.84755542189 }, { "content": " 1.0, 1.0, 1.0,\n\n\n\n 0.1, 0.1, 0.1,\n\n 0.8, 0.8, 0.8,\n\n 1.0, 1.0, 1.0,\n\n ];\n\n graphics.clear(Color::new(0, 255, 255, 255));\n\n let (view, proj) = get_global_transforms(&state);\n\n graphics.start_3d();\n\n graphics.draw_model(baseplate.vao, baseplate.vertex_buffer_length, mat_to_array(baseplate.transform), mat_to_array(view), mat_to_array(proj), view_position, light);\n\n for model in &mut models {\n\n graphics.draw_model(model.vao, model.vertex_buffer_length,mat_to_array(model.transform), mat_to_array(view), mat_to_array(proj), view_position, light);\n\n\n\n if model.rotation_offset.y.abs() > std::f32::EPSILON {\n\n let direction = model.rotation_offset.y / model.rotation_offset.y.abs();\n\n model.rotation_offset.y -= 15.0 * direction;\n\n if model.rotation_offset.y < 15.0 {\n\n model.rotation_offset.y = 0.0;\n\n }\n\n model.set_transform();\n", "file_path": "src/main.rs", "rank": 24, "score": 35524.83404656307 }, { "content": " }\n\n\n\n let (vao, vertex_buffer_length) = gl.load_model(&vertices);\n\n\n\n Model {\n\n vao,\n\n vertex_buffer_length,\n\n position: Vector3::new(0, 0, 0),\n\n rotation: Vector3::new(0, 0, 0),\n\n transform: Matrix4::identity(),\n\n position_offset: Vector3::new(0.0, 0.0, 0.0),\n\n rotation_offset: Vector3::new(0.0, 0.0, 0.0),\n\n bounding_box,\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 25, "score": 35522.170958560906 }, { "content": " MouseScrollDelta::PixelDelta(d) => {\n\n state.camera.distance *= (100.0 - d.y as f32) / 100.0;\n\n }\n\n }\n\n }\n\n WindowEvent::CursorMoved { position, .. } => {\n\n let dx = input.mouse_delta_x as f32;\n\n let dy = input.mouse_delta_y as f32;\n\n if input.mouse_middle_down {\n\n state.camera.rotate(dx * -0.005, dy * -0.005);\n\n }\n\n }\n\n _ => (),\n\n },\n\n Event::MainEventsCleared => {\n\n let start = Instant::now();\n\n let p = state.camera.position();\n\n let view_position = [p.x, p.y, p.z];\n\n let light = [\n\n -5.0, -5.0, -5.0,\n", "file_path": "src/main.rs", "rank": 26, "score": 35520.13797435734 }, { "content": "\n\n match event {\n\n Event::LoopDestroyed => *control_flow = ControlFlow::Exit,\n\n Event::WindowEvent { event, .. } => match event {\n\n WindowEvent::Resized(physical_size) => {\n\n graphics.resize(physical_size);\n\n state.aspect_ratio = graphics.window_width as f32 / graphics.window_height as f32\n\n }\n\n WindowEvent::CloseRequested => {\n\n *control_flow = ControlFlow::Exit\n\n }\n\n WindowEvent::KeyboardInput { input, .. } => {\n\n let pressed = input.state == ElementState::Pressed;\n\n match input.virtual_keycode {\n\n Some(Key::T) => {\n\n if pressed {\n\n let mut model = load_ldraw_file(&mut graphics, &mut parser, \"3005.dat\", Some([1.0, 0.0, 0.0, 1.0]));\n\n model.position = new_brick_position;\n\n new_brick_position.y += 3;\n\n new_brick_position.z += 1;\n", "file_path": "src/main.rs", "rank": 27, "score": 35519.255991656195 }, { "content": "use glutin::event::{Event, WindowEvent, ElementState, MouseScrollDelta};\n\nuse glutin::event::VirtualKeyCode as Key;\n\nuse glutin::event_loop::{ControlFlow, EventLoop};\n\nuse glutin::window::WindowBuilder;\n\nuse glutin::ContextBuilder;\n\nuse cgmath::{Matrix4, Deg, Vector3, Point3, SquareMatrix};\n\nuse std::time::Instant;\n\n\n\nmod graphics;\n\nuse graphics::{BoundingBox, Camera, Graphics, Model};\n\n\n\nmod parser;\n\nuse parser::Parser;\n\n\n\nmod input;\n\nuse input::InputState;\n\n\n\nmod util;\n\nuse util::{Rect, Color};\n\n\n", "file_path": "src/main.rs", "rank": 28, "score": 35518.52043415927 }, { "content": " let baseplate = load_ldraw_file(&mut graphics, &mut parser, \"3811.dat\", None);\n\n for x in 0..20 {\n\n for y in 0..20 {\n\n for z in 0..20 {\n\n let mut model = load_ldraw_file(&mut graphics, &mut parser, \"3005.dat\", Some([1.0, 0.0, 0.0, 0.5]));\n\n model.position = new_position;\n\n new_position.x = x;\n\n new_position.y = y * 3;\n\n new_position.z = z;\n\n model.set_transform();\n\n models.push(model);\n\n }\n\n }\n\n }\n\n\n\n let mut new_brick_position = Vector3::new(2, 2, 2);\n\n\n\n event_loop.run(move |event, _, control_flow| {\n\n *control_flow = ControlFlow::Poll;\n\n\n", "file_path": "src/main.rs", "rank": 29, "score": 35518.110106923836 }, { "content": " model.set_transform();\n\n models.push(model);\n\n state.active_model_idx = models.len() - 1;\n\n }\n\n }\n\n Some(Key::R) => {\n\n if pressed {\n\n models[state.active_model_idx].rotation.y += 1;\n\n models[state.active_model_idx].rotation_offset.y = 90.0;\n\n models[state.active_model_idx].set_transform();\n\n }\n\n }\n\n _ => {}\n\n }\n\n }\n\n WindowEvent::MouseWheel { delta, .. } => {\n\n match delta {\n\n MouseScrollDelta::LineDelta(_x, y) => {\n\n state.camera.distance *= (10.0 - y as f32) / 10.0;\n\n }\n", "file_path": "src/main.rs", "rank": 30, "score": 35515.51182221982 }, { "content": " }\n\n }\n\n graphics.draw_rect(Rect::new(0, 0, 100, 100), Color::new(0, 0, 0, 255));\n\n graphics.draw_text(\n\n &format!(\"Frame time: {}\", start.elapsed().as_millis()),\n\n 20, 20, 256.0, Color::new(255, 0, 128, 255));\n\n graphics.swap();\n\n },\n\n _ => (),\n\n }\n\n });\n\n}\n", "file_path": "src/main.rs", "rank": 31, "score": 35511.15980016036 }, { "content": " vertices.push(point.x / 40.0);\n\n vertices.push(point.y / -40.0);\n\n vertices.push(point.z / 40.0);\n\n vertices.push(n.x);\n\n vertices.push(n.y);\n\n vertices.push(n.z);\n\n // TODO Might have to sort transparent faces\n\n vertices.push(color[0]);\n\n vertices.push(color[1]);\n\n vertices.push(color[2]);\n\n vertices.push(color[3]);\n\n\n\n bounding_box.min.x = fmin(bounding_box.min.x, point.x / 40.0);\n\n bounding_box.min.y = fmin(bounding_box.min.y, point.y / -40.0);\n\n bounding_box.min.z = fmin(bounding_box.min.z, point.z / 40.0);\n\n bounding_box.max.x = fmax(bounding_box.max.x, point.x / 40.0);\n\n bounding_box.max.y = fmax(bounding_box.max.y, point.y / -40.0);\n\n bounding_box.max.z = fmax(bounding_box.max.z, point.z / 40.0);\n\n }\n\n }\n", "file_path": "src/main.rs", "rank": 32, "score": 35511.08259284016 }, { "content": " input.update(&event);\n\n\n\n if input.key_down(Key::A) {\n\n state.camera.rot_horizontal += 0.02;\n\n }\n\n if input.key_down(Key::D) {\n\n state.camera.rot_horizontal -= 0.02;\n\n }\n\n if input.key_down(Key::W) {\n\n state.camera.rot_vertical -= 0.02;\n\n if state.camera.rot_vertical < 0.001 {\n\n state.camera.rot_vertical = 0.001;\n\n }\n\n }\n\n if input.key_down(Key::S) {\n\n state.camera.rot_vertical += 0.02;\n\n if state.camera.rot_vertical > std::f32::consts::PI {\n\n state.camera.rot_vertical = std::f32::consts::PI - 0.001;\n\n }\n\n }\n", "file_path": "src/main.rs", "rank": 33, "score": 35510.52620188779 }, { "content": " polygon.points[2].z * 0.5,\n\n ],\n\n normal: [n.x, n.y, n.z],\n\n color: color,\n\n });\n\n }\n\n }\n\n\n\n ////////////////////\n\n\n\n let mut event_loop = EventLoop::new();\n\n let mut renderer = VulkanoRenderer::new(vertices, &event_loop);\n\n\n\n //////////////////////\n\n\n\n let mut rotation = Vector3::new(0.0, 0.0, 0.0);\n\n let mut d_rotation = Vector3::new(0.0, 0.0, 0.0);\n\n let mut camera_position = Point3::new(0.0, 0.0, 0.0);\n\n let mut camera_relative: Vector3<f32> = Vector3::new(1.23, 2.52, 4.12);\n\n let mut d_camera_position = Point3::new(0.0, 0.0, 0.0);\n", "file_path": "vulkano/src/main.rs", "rank": 34, "score": 33192.84140218128 }, { "content": "use cgmath::{Point3, Vector3};\n\nuse std::time::Instant;\n\nuse std::f32::consts::PI;\n\nuse winit::event::{DeviceEvent, ElementState, Event, WindowEvent};\n\nuse winit::event_loop::{ControlFlow, EventLoop};\n\n\n\nmod parser;\n\nuse parser::{norm, read_file, LdrawColor};\n\n\n\nmod renderer_vulkano;\n\nuse renderer_vulkano::{VulkanoRenderer, Vertex};\n\n\n", "file_path": "vulkano/src/main.rs", "rank": 35, "score": 33188.56684951484 }, { "content": " polygon.points[0].x * 0.5,\n\n polygon.points[0].y * 0.5,\n\n polygon.points[0].z * 0.5,\n\n ],\n\n normal: [n.x, n.y, n.z],\n\n color: color,\n\n });\n\n vertices.push(Vertex {\n\n position: [\n\n polygon.points[1].x * 0.5,\n\n polygon.points[1].y * 0.5,\n\n polygon.points[1].z * 0.5,\n\n ],\n\n normal: [n.x, n.y, n.z],\n\n color: color,\n\n });\n\n vertices.push(Vertex {\n\n position: [\n\n polygon.points[2].x * 0.5,\n\n polygon.points[2].y * 0.5,\n", "file_path": "vulkano/src/main.rs", "rank": 36, "score": 33186.214530031044 }, { "content": " let mut d_camera_relative = Vector3::new(0.0, 0.0, 0.0);\n\n\n\n let mut left = 0.0;\n\n let mut right = 0.0;\n\n let mut up = 0.0;\n\n let mut down = 0.0;\n\n let mut zoom_in = 0.0;\n\n let mut zoom_out = 0.0;\n\n\n\n loop {\n\n\n\n rotation.x += d_rotation.x;\n\n rotation.y += d_rotation.y;\n\n camera_position.x += d_camera_position.x;\n\n camera_position.y += d_camera_position.y;\n\n camera_position.z += d_camera_position.z;\n\n camera_relative.x += zoom_in - zoom_out;\n\n camera_relative.y += down - up;\n\n camera_relative.z += left - right;\n\n if camera_relative.x < 0.01 {\n", "file_path": "vulkano/src/main.rs", "rank": 37, "score": 33183.624434069694 }, { "content": " 18 => zoom_in = 0.1,\n\n 30 => left = 0.1,\n\n 31 => down = 0.1,\n\n 32 => right = 0.1,\n\n k => println!(\"Keycode: {}\", k),\n\n }\n\n }\n\n }\n\n }\n\n _ => (),\n\n }\n\n\n\n renderer.draw(rotation, d_rotation, camera_position, camera_relative, d_camera_position, d_camera_relative);\n\n });\n\n\n\n }\n\n}\n", "file_path": "vulkano/src/main.rs", "rank": 38, "score": 33180.743027047494 }, { "content": " Event::DeviceEvent {\n\n event: DeviceEvent::Key(s),\n\n ..\n\n } => {\n\n match s.state {\n\n ElementState::Released => {\n\n match s.scancode {\n\n 16 => zoom_out = 0.0,\n\n 17 => up = 0.0,\n\n 18 => zoom_in = 0.0,\n\n 30 => left = 0.0,\n\n 31 => down = 0.0,\n\n 32 => right = 0.0,\n\n _ => {}\n\n }\n\n }\n\n ElementState::Pressed => {\n\n match s.scancode {\n\n 16 => zoom_out = 0.1,\n\n 17 => up = 0.1,\n", "file_path": "vulkano/src/main.rs", "rank": 39, "score": 33178.38394181362 }, { "content": " camera_relative.x = 0.01;\n\n }\n\n if camera_relative.y < 0.001 {\n\n camera_relative.y = 0.001;\n\n }\n\n if camera_relative.y > PI - 0.001 {\n\n camera_relative.y = PI - 0.001;\n\n }\n\n\n\n let mut done = false;\n\n event_loop.run(move |ev, _, control_flow| {\n\n match ev {\n\n Event::WindowEvent {\n\n event: WindowEvent::CloseRequested,\n\n ..\n\n } => *control_flow = ControlFlow::Exit,\n\n Event::WindowEvent {\n\n event: WindowEvent::Resized(_),\n\n ..\n\n } => renderer.resize_window(),\n", "file_path": "vulkano/src/main.rs", "rank": 40, "score": 33178.339533299186 }, { "content": "use gl_generator::{Api, Fallbacks, Profile, Registry};\n\nuse std::env;\n\nuse std::fs::File;\n\nuse std::path::PathBuf;\n\n\n", "file_path": "build.rs", "rank": 41, "score": 29689.7761867392 }, { "content": "const VS_SRC: &[u8] = b\"\n\n#version 330 core\n\n\n\nlayout (location = 0) in vec3 position;\n\nlayout (location = 1) in vec3 normal;\n\nlayout (location = 2) in vec4 color;\n\n\n\nuniform mat4 world;\n\nuniform mat4 view;\n\nuniform mat4 proj;\n\n\n\nout vec3 v_normal;\n\nout vec4 v_color;\n\nout vec3 fragment_position;\n\n\n\nvoid main() {\n\n mat4 worldview = view * world;\n\n v_normal = transpose(inverse(mat3(worldview))) * normal;\n\n v_color = color;\n\n // TODO check if world is correct to use below, original said model\n", "file_path": "src/graphics.rs", "rank": 42, "score": 8938.391553792906 }, { "content": " fragment_position = vec3(world * vec4(position, 1.0));\n\n // fragment_position = position;\n\n gl_Position = proj * worldview * vec4(position, 1.0);\n\n}\n\n\\0\";\n\n\n\nconst FS_SRC: &[u8] = b\"\n\n#version 330 core\n\n\n\nin vec3 v_normal;\n\nin vec4 v_color;\n\nin vec3 fragment_position;\n\n\n", "file_path": "src/graphics.rs", "rank": 43, "score": 8931.413933014248 }, { "content": " }\n\n\n\n pub fn start_3d(&self) {\n\n unsafe {\n\n self.gl.UseProgram(self.program);\n\n }\n\n }\n\n\n\n pub fn draw_model(&self, vao: GLuint, vertex_buffer_length: i32, world: [f32; 16], view: [f32; 16], proj: [f32; 16], view_position: [f32; 3], light: [f32; 15]) {\n\n let gl = &self.gl;\n\n unsafe {\n\n gl.Enable(gl::DEPTH_TEST);\n\n gl.BlendFunc(gl::ONE, gl::ONE_MINUS_SRC_ALPHA);\n\n // gl.UseProgram(self.program);\n\n\n\n gl.UniformMatrix4fv(self.uniforms.world, 1, gl::FALSE, world.as_ptr());\n\n gl.UniformMatrix4fv(self.uniforms.view, 1, gl::FALSE, view.as_ptr());\n\n gl.UniformMatrix4fv(self.uniforms.proj, 1, gl::FALSE, proj.as_ptr());\n\n gl.Uniform3f(self.uniforms.view_position, view_position[0], view_position[1], view_position[2]);\n\n gl.Uniform3f(self.uniforms.light_position, light[0], light[1], light[2]);\n", "file_path": "src/graphics.rs", "rank": 44, "score": 8927.674199795938 }, { "content": " pub fn resize(&mut self, physical_size: PhysicalSize<u32>) {\n\n self.windowed_context.resize(physical_size);\n\n let (x, y) = (physical_size.width as i32, physical_size.height as i32);\n\n unsafe {\n\n self.gl.Viewport(0, 0, x, y);\n\n }\n\n self.window_width = x;\n\n self.window_height = y;\n\n }\n\n\n\n // pub fn draw_bounding_box(&self, a: [f32; 3], b: [f32; 3], world: [f32; 16], view: [f32; 16], proj: [f32; 16], view_position: [f32; 3], light: [f32; 15]) {\n\n // let c = vec![0.0, 1.0, 1.0, 0.3];\n\n // let vertices = vec![\n\n // a[0], a[1], a[2], 0.0, 1.0, 0.0, c[0], c[1], c[2], c[3],\n\n // a[0], a[1], b[2], 0.0, 1.0, 0.0, c[0], c[1], c[2], c[3],\n\n // a[0], b[1], b[2], 0.0, 1.0, 0.0, c[0], c[1], c[2], c[3],\n\n // a[0], a[1], a[2], 0.0, 1.0, 0.0, c[0], c[1], c[2], c[3],\n\n // a[0], b[1], b[2], 0.0, 1.0, 0.0, c[0], c[1], c[2], c[3],\n\n // a[0], b[1], a[2], 0.0, 1.0, 0.0, c[0], c[1], c[2], c[3],\n\n // a[0], a[1], a[2], 0.0, 1.0, 0.0, c[0], c[1], c[2], c[3],\n", "file_path": "src/graphics.rs", "rank": 45, "score": 8927.374105840163 }, { "content": " )\n\n }\n\n}\n\n\n\npub struct Model {\n\n pub vao: u32,\n\n pub vertex_buffer_length: i32,\n\n pub position: Vector3<i32>,\n\n pub rotation: Vector3<i32>,\n\n pub transform: Matrix4<f32>,\n\n pub position_offset: Vector3<f32>,\n\n pub rotation_offset: Vector3<f32>,\n\n pub bounding_box: BoundingBox,\n\n}\n\n\n\nimpl Model {\n\n pub fn set_transform(&mut self) {\n\n let position = Vector3::new(self.position.x as f32 * 0.5, self.position.y as f32 * 0.2, self.position.z as f32 * 0.5);\n\n self.transform = Matrix4::from_translation(position - self.position_offset)\n\n * Matrix4::from_angle_x(Deg((self.rotation.x * 90) as f32 - self.rotation_offset.x))\n", "file_path": "src/graphics.rs", "rank": 46, "score": 8926.026360585553 }, { "content": " * Matrix4::from_angle_y(Deg((self.rotation.y * 90) as f32 - self.rotation_offset.y))\n\n * Matrix4::from_angle_z(Deg((self.rotation.z * 90) as f32 - self.rotation_offset.z))\n\n }\n\n}\n\n\n\npub struct BoundingBox {\n\n pub min: Point3<f32>,\n\n pub max: Point3<f32>,\n\n}\n\n\n\npub struct Uniforms {\n\n world: GLint,\n\n view: GLint,\n\n proj: GLint,\n\n view_position: GLint,\n\n light_position: GLint,\n\n light_direction: GLint,\n\n light_ambient: GLint,\n\n light_diffuse: GLint,\n\n light_specular: GLint,\n\n}\n\n\n", "file_path": "src/graphics.rs", "rank": 47, "score": 8925.12476493572 }, { "content": " // a[0], b[1], a[2], 0.0, 1.0, 0.0, c[0], c[1], c[2], c[3],\n\n // b[0], b[1], b[2], 0.0, 1.0, 0.0, c[0], c[1], c[2], c[3],\n\n // b[0], b[1], a[2], 0.0, 1.0, 0.0, c[0], c[1], c[2], c[3],\n\n // a[0], a[1], b[2], 0.0, 1.0, 0.0, c[0], c[1], c[2], c[3],\n\n // a[0], b[1], b[2], 0.0, 1.0, 0.0, c[0], c[1], c[2], c[3],\n\n // b[0], b[1], b[2], 0.0, 1.0, 0.0, c[0], c[1], c[2], c[3],\n\n // a[0], a[1], b[2], 0.0, 1.0, 0.0, c[0], c[1], c[2], c[3],\n\n // b[0], b[1], b[2], 0.0, 1.0, 0.0, c[0], c[1], c[2], c[3],\n\n // b[0], a[1], b[2], 0.0, 1.0, 0.0, c[0], c[1], c[2], c[3]\n\n // ];\n\n // self.draw_model(&vertices, world, view, proj, view_position, light);\n\n // }\n\n\n\n pub fn load_model(&mut self, vertices: &[f32]) -> (u32, i32) {\n\n // TODO there is no \"unload_model\" right now because this is meant to be run once for each\n\n // model, and all the memory can be cleaned up when the program exits.\n\n let gl = &self.gl;\n\n let (mut vao, mut vbo) = (0, 0);\n\n unsafe {\n\n gl.GenVertexArrays(1, &mut vao);\n", "file_path": "src/graphics.rs", "rank": 48, "score": 8925.059187477143 }, { "content": " gl.Enable(gl::DEPTH_TEST);\n\n gl.DepthFunc(gl::LESS);\n\n gl.Disable(gl::CULL_FACE);\n\n gl.Enable(gl::BLEND);\n\n gl.BlendFunc(gl::ONE, gl::ONE_MINUS_SRC_ALPHA);\n\n\n\n gl.Viewport(0, 0, window_width, window_height);\n\n }\n\n\n\n let program = create_program(&gl, VS_SRC, FS_SRC);\n\n let program_2d = create_program(&gl, VS_SRC_2D, FS_SRC_2D);\n\n let program_text = create_program(&gl, VS_SRC_TEXT, FS_SRC_TEXT);\n\n let program_texture = create_program(&gl, VS_SRC_2D_TEXTURE, FS_SRC_2D_TEXTURE);\n\n\n\n let uniforms = unsafe {\n\n Uniforms {\n\n world: gl.GetUniformLocation(program, b\"world\\0\".as_ptr() as *const _),\n\n view: gl.GetUniformLocation(program, b\"view\\0\".as_ptr() as *const _),\n\n proj: gl.GetUniformLocation(program, b\"proj\\0\".as_ptr() as *const _),\n\n view_position: gl.GetUniformLocation(program, b\"view_position\\0\".as_ptr() as *const _),\n", "file_path": "src/graphics.rs", "rank": 49, "score": 8923.913432570162 }, { "content": "use cgmath::prelude::*;\n\nuse cgmath::{Matrix4, Point3, Vector3};\n\nuse std::fs::{File, OpenOptions};\n\nuse std::io::{BufRead, BufReader, BufWriter, Result, Write};\n\nuse std::path::PathBuf;\n\nuse std::time::Instant;\n\nuse std::collections::HashMap;\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Polygon {\n\n pub points: Vec<Point3<f32>>,\n\n pub color: LdrawColor,\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub enum LdrawColor {\n\n Main,\n\n Complement,\n\n RGBA(f32, f32, f32, f32),\n\n}\n", "file_path": "src/parser.rs", "rank": 50, "score": 8923.540964527605 }, { "content": "layout (location = 1) in vec4 color;\n\n\n\nout vec4 v_color;\n\n\n\nvoid main() {\n\n v_color = color;\n\n gl_Position = vec4(position, 0.0, 1.0);\n\n}\n\n\\0\";\n\n\n\nconst FS_SRC_2D: &[u8] = b\"\n\n#version 330 core\n\n\n\nin vec4 v_color;\n\n\n\nvoid main() {\n\n gl_FragColor = v_color;\n\n}\n\n\\0\";\n\n\n", "file_path": "src/graphics.rs", "rank": 51, "score": 8922.949520147726 }, { "content": " gl_Position = vec4(position, 0.0, 1.0);\n\n v_tex_coords = tex_coords;\n\n v_color = color;\n\n}\n\n\\0\";\n\n\n\nconst FS_SRC_TEXT: &[u8] = b\"\n\n#version 330 core\n\n\n\nuniform sampler2D tex;\n\nin vec2 v_tex_coords;\n\nin vec4 v_color;\n\nout vec4 f_color;\n\n\n\nvoid main() {\n\n f_color = v_color * vec4(1.0, 1.0, 1.0, texture(tex, v_tex_coords).r);\n\n}\n\n\\0\";\n\n\n\nconst VS_SRC_2D_TEXTURE: &[u8] = b\"\n", "file_path": "src/graphics.rs", "rank": 52, "score": 8922.764861147869 }, { "content": "\n\n vec3 ambient = light.ambient; \n\n vec3 diffuse = light.diffuse * max(dot(norm, light_direction), 0.0);\n\n vec3 specular = light.specular * pow(max(dot(view_direction, reflection_direction), 0.0), 32);\n\n\n\n gl_FragColor = vec4((ambient + diffuse + specular), 1.0) * v_color;\n\n}\n\n\\0\";\n\n\n\nconst VS_SRC_TEXT: &[u8] = b\"\n\n#version 330 core\n\n\n\nlayout (location = 0) in vec2 position;\n\nlayout (location = 1) in vec2 tex_coords;\n\nlayout (location = 2) in vec4 color;\n\n\n\nout vec2 v_tex_coords;\n\nout vec4 v_color;\n\n\n\nvoid main() {\n", "file_path": "src/graphics.rs", "rank": 53, "score": 8922.067915113199 }, { "content": "void main() {\n\n f_color = texture(tex, v_tex_coords);\n\n}\n\n\\0\";\n\n\n\npub struct Camera {\n\n pub focus: Point3<f32>,\n\n pub distance: f32,\n\n pub rot_horizontal: f32,\n\n pub rot_vertical: f32,\n\n pub fovy: f32,\n\n}\n\n\n\nimpl Camera {\n\n pub fn new() -> Self {\n\n Self {\n\n focus: Point3::new(0.0, 0.0, 0.0),\n\n distance: 10.0,\n\n rot_horizontal: 0.5,\n\n rot_vertical: 0.5,\n", "file_path": "src/graphics.rs", "rank": 54, "score": 8922.034871379501 }, { "content": " gl.Uniform3f(self.uniforms.light_direction, light[3], light[4], light[5]);\n\n gl.Uniform3f(self.uniforms.light_ambient, light[6], light[7], light[8]);\n\n gl.Uniform3f(self.uniforms.light_diffuse, light[9], light[10], light[11]);\n\n gl.Uniform3f(self.uniforms.light_specular, light[12], light[13], light[14]);\n\n\n\n gl.BindVertexArray(vao);\n\n gl.DrawArrays(gl::TRIANGLES, 0, vertex_buffer_length as GLsizei);\n\n // gl.BindVertexArray(0);\n\n gl.Disable(gl::DEPTH_TEST);\n\n }\n\n }\n\n\n\n pub fn draw_texture(&self, src_rect: Rect, dest_rect: Rect, buffer: Vec<u8>) {\n\n let gl = &self.gl;\n\n\n\n let x = dest_rect.x as f32 * 2.0 / self.window_width as f32 - 1.0;\n\n let y = 1.0 - dest_rect.y as f32 * 2.0 / self.window_height as f32;\n\n let src_width = src_rect.width as usize;\n\n let src_height = src_rect.height as usize;\n\n\n", "file_path": "src/graphics.rs", "rank": 55, "score": 8921.217831959662 }, { "content": "#![allow(dead_code)]\n\n\n\nuse glutin::window::WindowBuilder;\n\nuse glutin::dpi::PhysicalSize;\n\nuse glutin::window::Window;\n\nuse glutin::ContextBuilder;\n\nuse glutin::event_loop::EventLoop;\n\nuse std::ffi::CString;\n\nuse std::{ptr, mem};\n\nuse cgmath::{Matrix4, Vector2, Deg, Vector3, Point3, SquareMatrix, Vector4};\n\nuse glutin::{self, PossiblyCurrent};\n\nuse self::gl::types::*;\n\nuse rusttype::{point, Scale, PositionedGlyph};\n\n\n\nuse super::util::{Rect, Color};\n\n\n\nconst VS_SRC_2D: &[u8] = b\"\n\n#version 330 core\n\n\n\nlayout (location = 0) in vec2 position;\n", "file_path": "src/graphics.rs", "rank": 56, "score": 8919.985542241182 }, { "content": "\n\nimpl Graphics {\n\n\n\n pub fn clear(&self, color: Color) {\n\n unsafe {\n\n let color = [\n\n color.r as f32 / 255.0,\n\n color.g as f32 / 255.0,\n\n color.b as f32 / 255.0,\n\n color.a as f32 / 255.0,\n\n ];\n\n self.gl.ClearColor(color[0], color[1], color[2], color[3]);\n\n self.gl.Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);\n\n }\n\n }\n\n\n\n pub fn draw_rect(&self, rect: Rect, color: Color) {\n\n let gl = &self.gl;\n\n\n\n let x = rect.x as f32 * 2.0 / self.window_width as f32 - 1.0;\n", "file_path": "src/graphics.rs", "rank": 57, "score": 8919.75278767074 }, { "content": "#version 330 core\n\n\n\nlayout (location = 0) in vec2 position;\n\nlayout (location = 1) in vec2 tex_coords;\n\n\n\nout vec2 v_tex_coords;\n\n\n\nvoid main() {\n\n gl_Position = vec4(position, 0.0, 1.0);\n\n v_tex_coords = tex_coords;\n\n}\n\n\\0\";\n\n\n\nconst FS_SRC_2D_TEXTURE: &[u8] = b\"\n\n#version 330 core\n\n\n\nuniform sampler2D tex;\n\nin vec2 v_tex_coords;\n\nout vec4 f_color;\n\n\n", "file_path": "src/graphics.rs", "rank": 58, "score": 8919.141686388064 }, { "content": " && data[1] == \"CW\"\n\n {\n\n vertex_direction = \"CW\";\n\n }\n\n } // TODO 0 on the first line is the title\n\n \"1\" => {\n\n let color = LdrawColor::from_str(maybe_color);\n\n let mut invert_this = if invert_next { !inverted } else { inverted };\n\n let t = Matrix4::new(\n\n data[3].parse::<f32>().unwrap(), //a\n\n data[6].parse::<f32>().unwrap(), //d\n\n data[9].parse::<f32>().unwrap(), //g\n\n 0.0,\n\n data[4].parse::<f32>().unwrap(), //b\n\n data[7].parse::<f32>().unwrap(), //e\n\n data[10].parse::<f32>().unwrap(), //h\n\n 0.0,\n\n data[5].parse::<f32>().unwrap(), //c\n\n data[8].parse::<f32>().unwrap(), //f\n\n data[11].parse::<f32>().unwrap(), //i\n", "file_path": "src/parser.rs", "rank": 59, "score": 8918.483074758635 }, { "content": " gl.EnableVertexAttribArray(2);\n\n gl.VertexAttribPointer(2, 4, gl::FLOAT, gl::FALSE, stride, (4 * mem::size_of::<GLfloat>()) as *const _);\n\n\n\n gl.UseProgram(self.program_text);\n\n\n\n gl.DrawArrays(gl::TRIANGLES, 0, vertices.len() as GLsizei);\n\n\n\n gl.BindBuffer(gl::ARRAY_BUFFER, 0);\n\n gl.BindVertexArray(0);\n\n }\n\n\n\n unsafe {\n\n gl.DeleteBuffers(1, &mut vbo);\n\n gl.DeleteVertexArrays(1, &mut vao);\n\n gl.DeleteTextures(1, &mut id);\n\n }\n\n\n\n Rect::new(input_x, input_y, glyphs_width as u32, glyphs_height as u32)\n\n }\n\n\n\n pub fn swap(&mut self) {\n\n self.windowed_context.swap_buffers().unwrap();\n\n }\n\n}\n", "file_path": "src/graphics.rs", "rank": 60, "score": 8917.704742144311 }, { "content": " fovy: 45.0,\n\n }\n\n }\n\n\n\n pub fn rotate(&mut self, horizontal: f32, vertical: f32) {\n\n self.rot_horizontal += horizontal;\n\n self.rot_vertical += vertical;\n\n if self.rot_vertical < 0.001 {\n\n self.rot_vertical = 0.001;\n\n }\n\n if self.rot_vertical > std::f32::consts::PI {\n\n self.rot_vertical = std::f32::consts::PI - 0.001;\n\n }\n\n }\n\n\n\n pub fn position(&self) -> Point3<f32> {\n\n Point3::new(\n\n self.focus.z + self.distance * self.rot_vertical.sin() * self.rot_horizontal.sin(),\n\n self.focus.y + self.distance * self.rot_vertical.cos(),\n\n self.focus.x + self.distance * self.rot_vertical.sin() * self.rot_horizontal.cos()\n", "file_path": "src/graphics.rs", "rank": 61, "score": 8916.391818898252 }, { "content": " pub width: u32,\n\n pub height: u32,\n\n}\n\n\n\nimpl Rect {\n\n pub fn new(x: i32, y: i32, width: u32, height: u32) -> Self {\n\n Self {\n\n x,\n\n y,\n\n width,\n\n height,\n\n }\n\n }\n\n\n\n pub fn contains_point(&self, x: i32, y: i32) -> bool {\n\n x >= self.x && x < self.x + self.width as i32 && y >= self.y && y < self.y + self.height as i32\n\n }\n\n}\n\n\n\n#[derive(Copy, Clone, PartialEq)]\n", "file_path": "src/util.rs", "rank": 62, "score": 8915.86215099085 }, { "content": " self.gl.DrawArrays(gl::TRIANGLES, 0, vertices.len() as GLsizei);\n\n\n\n gl.BindBuffer(gl::ARRAY_BUFFER, 0);\n\n gl.BindVertexArray(0);\n\n }\n\n\n\n unsafe {\n\n gl.DeleteVertexArrays(1, &mut vao_2d);\n\n gl.DeleteBuffers(1, &mut vbo_2d);\n\n }\n\n }\n\n\n\n // TODO remove this function, figure out what we want to do with drawing 2d\n\n pub fn draw_2d(&self) {\n\n unsafe {\n\n // 2d\n\n self.gl.BindVertexArray(0);\n\n }\n\n }\n\n\n", "file_path": "src/graphics.rs", "rank": 63, "score": 8915.038086821143 }, { "content": " gl.Disable(gl::DEPTH_TEST);\n\n\n\n gl.GenVertexArrays(1, &mut vao_2d);\n\n gl.GenBuffers(1, &mut vbo_2d);\n\n gl.BindBuffer(gl::ARRAY_BUFFER, vbo_2d);\n\n gl.BufferData(\n\n gl::ARRAY_BUFFER,\n\n (vertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr,\n\n vertices.as_ptr() as *const _,\n\n gl::STATIC_DRAW\n\n );\n\n gl.BindVertexArray(vao_2d);\n\n let stride = 6 * mem::size_of::<GLfloat>() as GLsizei;\n\n gl.EnableVertexAttribArray(0);\n\n gl.VertexAttribPointer(0, 2, gl::FLOAT, gl::FALSE, stride, ptr::null());\n\n gl.EnableVertexAttribArray(1);\n\n gl.VertexAttribPointer(1, 4, gl::FLOAT, gl::FALSE, stride, (2 * mem::size_of::<GLfloat>()) as *const _);\n\n\n\n self.gl.UseProgram(self.program_2d);\n\n self.gl.BindVertexArray(vao_2d);\n", "file_path": "src/graphics.rs", "rank": 64, "score": 8914.695312537131 }, { "content": " let y = 1.0 - rect.y as f32 * 2.0 / self.window_height as f32;\n\n let width = rect.width as f32 * 2.0 / self.window_width as f32;\n\n let height = -1.0 * rect.height as f32 * 2.0 / self.window_height as f32;\n\n let color = [\n\n color.r as f32 / 255.0,\n\n color.g as f32 / 255.0,\n\n color.b as f32 / 255.0,\n\n color.a as f32 / 255.0,\n\n ];\n\n\n\n let (mut vao_2d, mut vbo_2d) = (0, 0);\n\n let vertices = [\n\n x, y, color[0], color[1], color[2], color[3],\n\n x + width, y, color[0], color[1], color[2], color[3],\n\n x + width, y + height, color[0], color[1], color[2], color[3],\n\n x, y, color[0], color[1], color[2], color[3],\n\n x + width, y + height, color[0], color[1], color[2], color[3],\n\n x, y + height, color[0], color[1], color[2], color[3], \n\n ];\n\n unsafe {\n", "file_path": "src/graphics.rs", "rank": 65, "score": 8914.394415287306 }, { "content": " gl.BindTexture(gl::TEXTURE_2D, id);\n\n gl.Uniform1i(uniform, 0);\n\n\n\n gl.EnableVertexAttribArray(0);\n\n gl.VertexAttribPointer(0, 2, gl::FLOAT, gl::FALSE, stride, ptr::null());\n\n gl.EnableVertexAttribArray(1);\n\n gl.VertexAttribPointer(1, 2, gl::FLOAT, gl::FALSE, stride, (2 * mem::size_of::<GLfloat>()) as *const _);\n\n\n\n gl.UseProgram(self.program_texture);\n\n\n\n gl.DrawArrays(gl::TRIANGLES, 0, vertices.len() as GLsizei);\n\n\n\n gl.BindBuffer(gl::ARRAY_BUFFER, 0);\n\n gl.BindVertexArray(0);\n\n }\n\n\n\n unsafe {\n\n gl.DeleteBuffers(1, &mut vbo);\n\n gl.DeleteVertexArrays(1, &mut vao);\n\n gl.DeleteTextures(1, &mut id);\n", "file_path": "src/graphics.rs", "rank": 66, "score": 8914.26851823781 }, { "content": " let height = glyphs_height as f32 * 2.0 / self.window_height as f32;\n\n let width = glyphs_width as f32 * 2.0 / self.window_width as f32;\n\n let y = y - height;\n\n let color = [\n\n color.r as f32 / 255.0,\n\n color.g as f32 / 255.0,\n\n color.b as f32 / 255.0,\n\n color.a as f32 / 255.0,\n\n ];\n\n let vertices = [\n\n x, y, 0.0, 1.0, color[0], color[1], color[2], color[3],\n\n x + width, y, 1.0, 1.0, color[0], color[1], color[2], color[3],\n\n x + width, y + height, 1.0, 0.0, color[0], color[1], color[2], color[3],\n\n x, y, 0.0, 1.0, color[0], color[1], color[2], color[3],\n\n x + width, y + height, 1.0, 0.0, color[0], color[1], color[2], color[3],\n\n x, y + height, 0.0, 0.0, color[0], color[1], color[2], color[3],\n\n ];\n\n\n\n let (mut vao, mut vbo) = (0, 0);\n\n unsafe {\n", "file_path": "src/graphics.rs", "rank": 67, "score": 8914.002262181424 }, { "content": " gl.GenVertexArrays(1, &mut vao);\n\n gl.GenBuffers(1, &mut vbo);\n\n gl.BindBuffer(gl::ARRAY_BUFFER, vbo);\n\n gl.BufferData(\n\n gl::ARRAY_BUFFER,\n\n (vertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr,\n\n vertices.as_ptr() as *const _,\n\n gl::STATIC_DRAW\n\n );\n\n gl.BindVertexArray(vao);\n\n let stride = 8 * mem::size_of::<GLfloat>() as GLsizei;\n\n\n\n gl.ActiveTexture(gl::TEXTURE0);\n\n gl.BindTexture(gl::TEXTURE_2D, id);\n\n gl.Uniform1i(uniform, 0);\n\n\n\n gl.EnableVertexAttribArray(0);\n\n gl.VertexAttribPointer(0, 2, gl::FLOAT, gl::FALSE, stride, ptr::null());\n\n gl.EnableVertexAttribArray(1);\n\n gl.VertexAttribPointer(1, 2, gl::FLOAT, gl::FALSE, stride, (2 * mem::size_of::<GLfloat>()) as *const _);\n", "file_path": "src/graphics.rs", "rank": 68, "score": 8913.475349634426 }, { "content": " .iter()\n\n .map(|p| t.transform_point(*p))\n\n .collect();\n\n match &new_polygon.color {\n\n LdrawColor::Main => {\n\n new_polygon.color = color.clone();\n\n }\n\n _ => {}\n\n };\n\n polygons.push(new_polygon);\n\n }\n\n }\n\n \"2\" => {\n\n // TODO line\n\n }\n\n \"3\" => {\n\n if data.len() == 9 {\n\n let mut polygon = Polygon {\n\n points: Vec::new(),\n\n color: LdrawColor::from_str(maybe_color),\n", "file_path": "src/parser.rs", "rank": 69, "score": 8913.43802890624 }, { "content": " let mut invert_next = false;\n\n for line in input.lines() {\n\n let line = line.unwrap();\n\n // TODO: This is not correct because some whitespace (e.g. filenames)\n\n // should not be tokenized.\n\n let blocks: Vec<&str> = line.split_whitespace().collect();\n\n match blocks.len() {\n\n 0..=2 => {}\n\n _ => {\n\n let command_type = blocks[0];\n\n let maybe_color = blocks[1];\n\n let data: Vec<&str> = blocks[2..].to_vec();\n\n match command_type {\n\n \"0\" => {\n\n if maybe_color == \"BFC\" && data[0] == \"INVERTNEXT\" {\n\n invert_next = true;\n\n }\n\n if maybe_color == \"BFC\"\n\n && data.len() == 2\n\n && data[0] == \"CERTIFY\"\n", "file_path": "src/parser.rs", "rank": 70, "score": 8913.058521118834 }, { "content": " gl.GenBuffers(1, &mut vbo);\n\n gl.BindBuffer(gl::ARRAY_BUFFER, vbo);\n\n gl.BufferData(\n\n gl::ARRAY_BUFFER,\n\n (vertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr,\n\n vertices.as_ptr() as *const _,\n\n gl::STATIC_DRAW\n\n );\n\n gl.BindVertexArray(vao);\n\n let stride = 10 * mem::size_of::<GLfloat>() as GLsizei;\n\n gl.EnableVertexAttribArray(0);\n\n gl.VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, stride, ptr::null());\n\n gl.EnableVertexAttribArray(1);\n\n gl.VertexAttribPointer(1, 3, gl::FLOAT, gl::FALSE, stride, (3 * mem::size_of::<GLfloat>()) as *const _);\n\n gl.EnableVertexAttribArray(2);\n\n gl.VertexAttribPointer(2, 4, gl::FLOAT, gl::FALSE, stride, (6 * mem::size_of::<GLfloat>()) as *const _);\n\n gl.BindBuffer(gl::ARRAY_BUFFER, 0);\n\n gl.BindVertexArray(0);\n\n }\n\n (vao, vertices.len() as i32)\n", "file_path": "src/graphics.rs", "rank": 71, "score": 8912.83058224892 }, { "content": " }\n\n }\n\n\n\n pub fn layout_text(&self, text: &str, scale: f32) -> (Vec<PositionedGlyph<'_>>, usize, usize) {\n\n let font_scale = Scale::uniform(scale);\n\n let v_metrics = self.font.v_metrics(font_scale);\n\n let glyphs: Vec<_> = self.font\n\n .layout(text, font_scale, point(0.0, 0.0 + v_metrics.ascent))\n\n .collect();\n\n\n\n let height = (v_metrics.ascent - v_metrics.descent).ceil() as usize;\n\n let width = glyphs\n\n .iter()\n\n .rev()\n\n .map(|g| g.position().x as f32 + g.unpositioned().h_metrics().advance_width)\n\n .next()\n\n .unwrap_or(0.0)\n\n .ceil() as usize;\n\n (glyphs, width, height)\n\n }\n", "file_path": "src/graphics.rs", "rank": 72, "score": 8912.729383991998 }, { "content": "pub struct Color {\n\n pub r: u8,\n\n pub g: u8,\n\n pub b: u8,\n\n pub a: u8,\n\n}\n\n\n\nimpl Color {\n\n pub fn new(r: u8, g: u8, b: u8, a: u8) -> Self {\n\n Self { r, g, b, a }\n\n }\n\n\n\n pub fn from_hex(color_hex_str: &str) -> Result<Self, std::num::ParseIntError> {\n\n let color = i32::from_str_radix(color_hex_str, 16)?;\n\n let b = color % 0x100;\n\n let g = (color - b) / 0x100 % 0x100;\n\n let r = (color - g) / 0x10000;\n\n\n\n Ok(Self {\n\n r: r as u8,\n", "file_path": "src/util.rs", "rank": 73, "score": 8912.686541976325 }, { "content": " src_width as GLint,\n\n src_height as GLint,\n\n 0,\n\n gl::RGBA,\n\n gl::UNSIGNED_BYTE,\n\n buffer.as_ptr() as *const _\n\n );\n\n let uniform = gl.GetUniformLocation(self.program_texture, b\"tex\\0\".as_ptr() as *const _);\n\n\n\n (uniform, id)\n\n };\n\n\n\n let dest_width = dest_rect.width as f32 * 2.0 / self.window_width as f32;\n\n let dest_height = dest_rect.height as f32 * 2.0 / self.window_height as f32;\n\n let y = y - dest_height;\n\n\n\n let vertices = [\n\n x, y, 0.0, 1.0,\n\n x + dest_width, y, 1.0, 1.0,\n\n x + dest_width, y + dest_height, 1.0, 0.0,\n", "file_path": "src/graphics.rs", "rank": 74, "score": 8912.511206970423 }, { "content": " light_position: gl.GetUniformLocation(program, b\"light.position\\0\".as_ptr() as *const _),\n\n light_direction: gl.GetUniformLocation(program, b\"light.direction\\0\".as_ptr() as *const _),\n\n light_ambient: gl.GetUniformLocation(program, b\"light.ambient\\0\".as_ptr() as *const _),\n\n light_diffuse: gl.GetUniformLocation(program, b\"light.diffuse\\0\".as_ptr() as *const _),\n\n light_specular: gl.GetUniformLocation(program, b\"light.specular\\0\".as_ptr() as *const _),\n\n }\n\n };\n\n Graphics {\n\n windowed_context,\n\n window_height,\n\n window_width,\n\n program,\n\n program_2d,\n\n program_text,\n\n program_texture,\n\n gl,\n\n uniforms,\n\n font,\n\n }\n\n}\n", "file_path": "src/graphics.rs", "rank": 75, "score": 8912.423307107634 }, { "content": " ldraw_directory: String,\n\n}\n\n\n\nimpl Parser {\n\n pub fn new(ldraw_directory: &str) -> Self {\n\n Self {\n\n cache: HashMap::new(),\n\n ldraw_directory: ldraw_directory.into(),\n\n }\n\n }\n\n\n\n pub fn load(&mut self, filename: &str) -> Vec<Polygon> {\n\n read_file(&mut self.cache, &self.ldraw_directory, filename, false)\n\n }\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 76, "score": 8912.37784229675 }, { "content": " x, y, 0.0, 1.0,\n\n x + dest_width, y + dest_height, 1.0, 0.0,\n\n x, y + dest_height, 0.0, 0.0,\n\n ];\n\n\n\n let (mut vao, mut vbo) = (0, 0);\n\n unsafe {\n\n gl.GenVertexArrays(1, &mut vao);\n\n gl.GenBuffers(1, &mut vbo);\n\n gl.BindBuffer(gl::ARRAY_BUFFER, vbo);\n\n gl.BufferData(\n\n gl::ARRAY_BUFFER,\n\n (vertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr,\n\n vertices.as_ptr() as *const _,\n\n gl::STATIC_DRAW\n\n );\n\n gl.BindVertexArray(vao);\n\n let stride = 4 * mem::size_of::<GLfloat>() as GLsizei;\n\n\n\n gl.ActiveTexture(gl::TEXTURE0);\n", "file_path": "src/graphics.rs", "rank": 77, "score": 8912.228505543644 }, { "content": "\n\nimpl LdrawColor {\n\n fn from_str(s: &str) -> Self {\n\n match s {\n\n \"16\" => Self::Main,\n\n \"24\" => Self::Complement,\n\n \"0\" => Self::RGBA(0.105882, 0.164706, 0.203922, 1.000000),\n\n \"1\" => Self::RGBA(0.117647, 0.352941, 0.658824, 1.000000),\n\n \"2\" => Self::RGBA(0.000000, 0.521569, 0.168627, 1.000000),\n\n \"3\" => Self::RGBA(0.023529, 0.615686, 0.623529, 1.000000),\n\n \"4\" => Self::RGBA(0.705882, 0.000000, 0.000000, 1.000000),\n\n \"5\" => Self::RGBA(0.827451, 0.207843, 0.615686, 1.000000),\n\n \"6\" => Self::RGBA(0.329412, 0.200000, 0.141176, 1.000000),\n\n \"7\" => Self::RGBA(0.541176, 0.572549, 0.552941, 1.000000),\n\n \"8\" => Self::RGBA(0.329412, 0.349020, 0.333333, 1.000000),\n\n \"9\" => Self::RGBA(0.592157, 0.796078, 0.850980, 1.000000),\n\n \"10\" => Self::RGBA(0.345098, 0.670588, 0.254902, 1.000000),\n\n \"11\" => Self::RGBA(0.000000, 0.666667, 0.643137, 1.000000),\n\n \"12\" => Self::RGBA(0.941176, 0.427451, 0.380392, 1.000000),\n\n \"13\" => Self::RGBA(0.964706, 0.662745, 0.733333, 1.000000),\n", "file_path": "src/parser.rs", "rank": 78, "score": 8912.155833040135 }, { "content": " let y = std::cmp::max(y as i32 + min_y, 1) as usize - 1;\n\n let index = y * glyphs_width + x;\n\n buffer[index] = v;\n\n });\n\n }\n\n }\n\n\n\n // Load the texture from the buffer\n\n let (uniform, mut id) = unsafe {\n\n gl.BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);\n\n gl.Disable(gl::DEPTH_TEST);\n\n\n\n let mut id: u32 = 0;\n\n gl.GenTextures(1, &mut id);\n\n gl.ActiveTexture(gl::TEXTURE0);\n\n gl.BindTexture(gl::TEXTURE_2D, id);\n\n\n\n // TODO Decide what these should be.\n\n gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as GLint);\n\n gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as GLint);\n", "file_path": "src/graphics.rs", "rank": 79, "score": 8912.132120275704 }, { "content": "#![allow(dead_code)]\n\n\n\npub struct Point {\n\n pub x: i32,\n\n pub y: i32,\n\n}\n\n\n\nimpl Point {\n\n pub fn new(x: i32, y: i32) -> Self {\n\n Self {\n\n x,\n\n y,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Copy, Clone)]\n\npub struct Rect {\n\n pub x: i32,\n\n pub y: i32,\n", "file_path": "src/util.rs", "rank": 80, "score": 8912.0226927545 }, { "content": "\n\n pub fn draw_text(&self, text: &str, x: i32, y: i32, scale: f32, color: Color) -> Rect {\n\n let gl = &self.gl;\n\n\n\n // Save the original parameters to return in the rect\n\n let input_x = x;\n\n let input_y = y;\n\n\n\n let (glyphs, glyphs_width, glyphs_height) = self.layout_text(text, scale);\n\n \n\n let mut buffer: Vec<f32> = vec![0.0; glyphs_width * glyphs_height];\n\n\n\n for glyph in glyphs {\n\n if let Some(bounding_box) = glyph.pixel_bounding_box() {\n\n\n\n let min_x = bounding_box.min.x;\n\n let min_y = bounding_box.min.y;\n\n\n\n glyph.draw(|x, y, v| {\n\n let x = std::cmp::max(x as i32 + min_x, 1) as usize - 1;\n", "file_path": "src/graphics.rs", "rank": 81, "score": 8911.72923417621 }, { "content": " 0.0,\n\n data[0].parse::<f32>().unwrap(), //x\n\n data[1].parse::<f32>().unwrap(), //y\n\n data[2].parse::<f32>().unwrap(), //z\n\n 1.0,\n\n );\n\n if t.determinant() < 0.0 {\n\n invert_this = !invert_this;\n\n }\n\n let sub_polygons = read_file(\n\n cache,\n\n ldraw_directory,\n\n &str::replace(data[12], \"\\\\\", \"/\"),\n\n invert_this,\n\n );\n\n invert_next = false;\n\n for polygon in sub_polygons {\n\n let mut new_polygon = polygon;\n\n new_polygon.points = new_polygon\n\n .points\n", "file_path": "src/parser.rs", "rank": 82, "score": 8911.604406018982 }, { "content": "use std::collections::HashMap;\n\nuse glutin::event::{Event, WindowEvent, VirtualKeyCode, ElementState, MouseButton};\n\n\n\npub struct InputState {\n\n pub mouse_left_down: bool,\n\n pub mouse_right_down: bool,\n\n pub mouse_middle_down: bool,\n\n pub mouse_left_pressed: bool,\n\n pub mouse_right_pressed: bool,\n\n pub mouse_middle_pressed: bool,\n\n pub mouse_left_released: bool,\n\n pub mouse_right_released: bool,\n\n pub mouse_middle_released: bool,\n\n scroll_delta_x: i32,\n\n scroll_delta_y: i32,\n\n pub mouse_x: f64,\n\n pub mouse_y: f64,\n\n pub mouse_delta_x: f64,\n\n pub mouse_delta_y: f64,\n\n keys_down: HashMap<VirtualKeyCode, ()>,\n", "file_path": "src/input.rs", "rank": 83, "score": 8910.932939651178 }, { "content": " WindowEvent::CursorMoved { position, .. } => {\n\n self.mouse_delta_x = position.x - self.mouse_x;\n\n self.mouse_delta_y = position.y - self.mouse_y;\n\n self.mouse_x = position.x;\n\n self.mouse_y = position.y;\n\n }\n\n _ => {}\n\n }\n\n }\n\n }\n\n\n\n pub fn get_scroll_delta_x(&mut self) -> i32 {\n\n let delta = self.scroll_delta_x;\n\n self.scroll_delta_x = 0;\n\n return delta;\n\n }\n\n pub fn get_scroll_delta_y(&mut self) -> i32 {\n\n let delta = self.scroll_delta_y;\n\n self.scroll_delta_y = 0;\n\n return delta;\n", "file_path": "src/input.rs", "rank": 84, "score": 8910.828683459564 }, { "content": " };\n\n if (vertex_direction == \"CW\" && !inverted)\n\n || (vertex_direction == \"CCW\" && inverted)\n\n {\n\n polygon.points.push(point_from(&data, 6, 7, 8));\n\n polygon.points.push(point_from(&data, 3, 4, 5));\n\n polygon.points.push(point_from(&data, 0, 1, 2));\n\n } else {\n\n polygon.points.push(point_from(&data, 0, 1, 2));\n\n polygon.points.push(point_from(&data, 3, 4, 5));\n\n polygon.points.push(point_from(&data, 6, 7, 8));\n\n }\n\n polygons.push(polygon);\n\n }\n\n }\n\n \"4\" => {\n\n if data.len() == 12 {\n\n let mut polygon = Polygon {\n\n points: Vec::new(),\n\n color: LdrawColor::from_str(maybe_color),\n", "file_path": "src/parser.rs", "rank": 85, "score": 8910.596075687981 }, { "content": " // Load the texture from the buffer\n\n let (uniform, mut id) = unsafe {\n\n gl.BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);\n\n gl.Disable(gl::DEPTH_TEST);\n\n\n\n let mut id: u32 = 0;\n\n gl.GenTextures(1, &mut id);\n\n gl.ActiveTexture(gl::TEXTURE0);\n\n gl.BindTexture(gl::TEXTURE_2D, id);\n\n\n\n // TODO Decide what these should be.\n\n gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as GLint);\n\n gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as GLint);\n\n gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::CLAMP_TO_EDGE as GLint);\n\n gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::CLAMP_TO_EDGE as GLint);\n\n\n\n gl.TexImage2D(\n\n gl::TEXTURE_2D,\n\n 0,\n\n gl::RGBA as GLint,\n", "file_path": "src/graphics.rs", "rank": 86, "score": 8910.159078719003 }, { "content": " };\n\n let mut polygon2 = Polygon {\n\n points: Vec::new(),\n\n color: LdrawColor::from_str(maybe_color),\n\n };\n\n if (vertex_direction == \"CW\" && !inverted)\n\n || (vertex_direction == \"CCW\" && inverted)\n\n {\n\n polygon.points.push(point_from(&data, 9, 10, 11));\n\n polygon.points.push(point_from(&data, 6, 7, 8));\n\n polygon.points.push(point_from(&data, 3, 4, 5));\n\n polygon2.points.push(point_from(&data, 3, 4, 5));\n\n polygon2.points.push(point_from(&data, 0, 1, 2));\n\n polygon2.points.push(point_from(&data, 9, 10, 11));\n\n } else {\n\n polygon.points.push(point_from(&data, 0, 1, 2));\n\n polygon.points.push(point_from(&data, 3, 4, 5));\n\n polygon.points.push(point_from(&data, 6, 7, 8));\n\n polygon2.points.push(point_from(&data, 6, 7, 8));\n\n polygon2.points.push(point_from(&data, 9, 10, 11));\n", "file_path": "src/parser.rs", "rank": 87, "score": 8909.89808103466 }, { "content": " buffer.extend([b' '].iter().cycle().take(len as usize));\n\n CString::from_vec_unchecked(buffer)\n\n };\n\n gl.GetProgramInfoLog(program, len, std::ptr::null_mut(), error.as_ptr() as *mut gl::types::GLchar);\n\n eprintln!(\"{}\", error.to_string_lossy());\n\n }\n\n gl.DeleteShader(vs);\n\n gl.DeleteShader(fs);\n\n program\n\n }\n\n\n\n}\n\n\n", "file_path": "src/graphics.rs", "rank": 88, "score": 8909.264169452284 }, { "content": " gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::CLAMP_TO_EDGE as GLint);\n\n gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::CLAMP_TO_EDGE as GLint);\n\n\n\n gl.TexImage2D(\n\n gl::TEXTURE_2D,\n\n 0,\n\n gl::RED as GLint,\n\n glyphs_width as GLint,\n\n glyphs_height as GLint,\n\n 0,\n\n gl::RED,\n\n gl::FLOAT,\n\n buffer.as_ptr() as *const _\n\n );\n\n let uniform = gl.GetUniformLocation(self.program_text, b\"tex\\0\".as_ptr() as *const _);\n\n (uniform, id)\n\n };\n\n\n\n let x = x as f32 * 2.0 / self.window_width as f32 - 1.0;\n\n let y = 1.0 - y as f32 * 2.0 / self.window_height as f32;\n", "file_path": "src/graphics.rs", "rank": 89, "score": 8909.091355943894 }, { "content": " g: g as u8,\n\n b: b as u8,\n\n a: 255,\n\n })\n\n }\n\n\n\n pub const BLACK: Self = Self {\n\n r: 0,\n\n g: 0,\n\n b: 0,\n\n a: 255,\n\n };\n\n pub const WHITE: Self = Self {\n\n r: 255,\n\n g: 255,\n\n b: 255,\n\n a: 255,\n\n };\n\n pub const GRAY: Self = Self {\n\n r: 150,\n\n g: 150,\n\n b: 150,\n\n a: 255,\n\n };\n\n\n\n}\n", "file_path": "src/util.rs", "rank": 90, "score": 8908.829356139746 }, { "content": " mouse_y: 0.0,\n\n mouse_delta_x: 0.0,\n\n mouse_delta_y: 0.0,\n\n keys_down: HashMap::new(),\n\n keys_pressed: HashMap::new(),\n\n keys_released: HashMap::new(),\n\n }\n\n }\n\n\n\n pub fn update(&mut self, event: &Event<()>) {\n\n self.mouse_left_pressed = false;\n\n self.mouse_left_released = false;\n\n self.mouse_right_pressed = false;\n\n self.mouse_right_released = false;\n\n self.mouse_middle_pressed = false;\n\n self.mouse_middle_released = false;\n\n self.keys_pressed.clear();\n\n self.keys_released.clear();\n\n if let Event::WindowEvent { event, .. } = event {\n\n match event {\n", "file_path": "src/input.rs", "rank": 91, "score": 8908.430018583513 }, { "content": " .join(&filename),\n\n PathBuf::new().join(\".\").join(&filename),\n\n ];\n\n let mut my_path = PathBuf::new();\n\n for path in paths {\n\n if path.exists() {\n\n my_path = path.clone();\n\n break;\n\n }\n\n }\n\n\n\n if !my_path.exists() {\n\n println!(\"WARNING: Couldn't find part: {}. Skipping...\", filename);\n\n return polygons;\n\n }\n\n let input = File::open(my_path).unwrap();\n\n\n\n let input = BufReader::new(input);\n\n\n\n let mut vertex_direction = \"CCW\";\n", "file_path": "src/parser.rs", "rank": 92, "score": 8908.097740189796 }, { "content": " // writeln!(output, \"g thing\")?;\n\n // writeln!(output, \"usemtl red\")?;\n\n\n\n let mut vertex_count = 1;\n\n // writeln!(output, \"s off\");\n\n for (polygon_count, p) in polygons.iter().enumerate() {\n\n write!(output, \"f\")?;\n\n for _ in &p.points {\n\n write!(\n\n output,\n\n \" {}/{}/{}\",\n\n vertex_count,\n\n vertex_count,\n\n polygon_count + 1\n\n )?;\n\n vertex_count += 1;\n\n }\n\n writeln!(output)?;\n\n }\n\n println!(\n\n \"Wrote {} vertices, {} norms, and {} faces in {} ms.\",\n\n vertex_count - 1,\n\n norms.len(),\n\n polygons.len(),\n\n start.elapsed().as_millis()\n\n );\n\n Ok(())\n\n}\n", "file_path": "src/parser.rs", "rank": 93, "score": 8907.337739029605 }, { "content": " }\n\n pub fn key_down(&self, key: VirtualKeyCode) -> bool {\n\n self.keys_down.contains_key(&key)\n\n }\n\n pub fn key_pressed(&self, key: VirtualKeyCode) -> bool {\n\n self.keys_pressed.contains_key(&key)\n\n }\n\n pub fn key_released(&self, key: VirtualKeyCode) -> bool {\n\n self.keys_released.contains_key(&key)\n\n }\n\n}\n", "file_path": "src/input.rs", "rank": 94, "score": 8907.225068689642 }, { "content": " WindowEvent::MouseInput { button, state, .. } => {\n\n match (button, state) {\n\n (MouseButton::Left, ElementState::Pressed) => {\n\n self.mouse_left_down = true;\n\n self.mouse_left_pressed = true;\n\n }\n\n (MouseButton::Right, ElementState::Pressed) => {\n\n self.mouse_right_down = true;\n\n self.mouse_right_pressed = true;\n\n }\n\n (MouseButton::Middle, ElementState::Pressed) => {\n\n self.mouse_middle_down = true;\n\n self.mouse_middle_pressed = true;\n\n }\n\n (MouseButton::Left, ElementState::Released) => {\n\n self.mouse_left_down = false;\n\n self.mouse_left_released = true;\n\n }\n\n (MouseButton::Right, ElementState::Released) => {\n\n self.mouse_right_down = false;\n", "file_path": "src/input.rs", "rank": 95, "score": 8906.976809613687 }, { "content": " \"375\" => Self::RGBA(0.541176, 0.572549, 0.552941, 1.000000),\n\n \"406\" => Self::RGBA(0.098039, 0.196078, 0.352941, 1.000000),\n\n \"449\" => Self::RGBA(0.403922, 0.121569, 0.505882, 1.000000),\n\n \"490\" => Self::RGBA(0.647059, 0.792157, 0.094118, 1.000000),\n\n \"496\" => Self::RGBA(0.588235, 0.588235, 0.588235, 1.000000),\n\n \"504\" => Self::RGBA(0.537255, 0.529412, 0.533333, 1.000000),\n\n \"511\" => Self::RGBA(0.956863, 0.956863, 0.956863, 1.000000),\n\n \"10002\" => Self::RGBA(0.345098, 0.670588, 0.254902, 1.000000),\n\n \"10026\" => Self::RGBA(0.564706, 0.121569, 0.462745, 1.000000),\n\n \"10030\" => Self::RGBA(0.627451, 0.431373, 0.725490, 1.000000),\n\n \"10031\" => Self::RGBA(0.803922, 0.643137, 0.870588, 1.000000),\n\n \"10070\" => Self::RGBA(0.372549, 0.192157, 0.035294, 1.000000),\n\n \"10226\" => Self::RGBA(1.000000, 0.925490, 0.423529, 1.000000),\n\n \"10308\" => Self::RGBA(0.207843, 0.129412, 0.000000, 1.000000),\n\n \"10320\" => Self::RGBA(0.447059, 0.000000, 0.070588, 1.000000),\n\n \"10321\" => Self::RGBA(0.274510, 0.607843, 0.764706, 1.000000),\n\n \"10322\" => Self::RGBA(0.407843, 0.764706, 0.886275, 1.000000),\n\n \"10323\" => Self::RGBA(0.827451, 0.949020, 0.917647, 1.000000),\n\n \"10484\" => Self::RGBA(0.568627, 0.313726, 0.109804, 1.000000),\n\n \"32\" => Self::RGBA(0.000000, 0.000000, 0.000000, 0.823529),\n\n \"493\" => Self::RGBA(0.396078, 0.403922, 0.380392, 1.000000),\n\n \"494\" => Self::RGBA(0.815686, 0.815686, 0.815686, 1.000000),\n\n \"495\" => Self::RGBA(0.682353, 0.478431, 0.349020, 1.000000),\n\n \"10047\" => Self::RGBA(1.000000, 1.000000, 1.000000, 0.062745),\n\n _ => Self::Main,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 96, "score": 8906.944403185253 }, { "content": " keys_pressed: HashMap<VirtualKeyCode, ()>,\n\n keys_released: HashMap<VirtualKeyCode, ()>,\n\n}\n\n\n\n#[allow(dead_code)]\n\nimpl InputState {\n\n pub fn new() -> Self {\n\n Self {\n\n mouse_left_down: false,\n\n mouse_right_down: false,\n\n mouse_middle_down: false,\n\n mouse_left_pressed: false,\n\n mouse_right_pressed: false,\n\n mouse_middle_pressed: false,\n\n mouse_left_released: false,\n\n mouse_right_released: false,\n\n mouse_middle_released: false,\n\n scroll_delta_x: 0,\n\n scroll_delta_y: 0,\n\n mouse_x: 0.0,\n", "file_path": "src/input.rs", "rank": 97, "score": 8905.811658410117 }, { "content": " \"14\" => Self::RGBA(0.980392, 0.784314, 0.039216, 1.000000),\n\n \"15\" => Self::RGBA(0.956863, 0.956863, 0.956863, 1.000000),\n\n \"17\" => Self::RGBA(0.678431, 0.850980, 0.658824, 1.000000),\n\n \"18\" => Self::RGBA(1.000000, 0.839216, 0.498039, 1.000000),\n\n \"19\" => Self::RGBA(0.690196, 0.627451, 0.435294, 1.000000),\n\n \"20\" => Self::RGBA(0.686275, 0.745098, 0.839216, 1.000000),\n\n \"22\" => Self::RGBA(0.403922, 0.121569, 0.505882, 1.000000),\n\n \"23\" => Self::RGBA(0.054902, 0.243137, 0.603922, 1.000000),\n\n \"25\" => Self::RGBA(0.839216, 0.474510, 0.137255, 1.000000),\n\n \"26\" => Self::RGBA(0.564706, 0.121569, 0.462745, 1.000000),\n\n \"27\" => Self::RGBA(0.647059, 0.792157, 0.094118, 1.000000),\n\n \"28\" => Self::RGBA(0.537255, 0.490196, 0.384314, 1.000000),\n\n \"29\" => Self::RGBA(1.000000, 0.619608, 0.803922, 1.000000),\n\n \"30\" => Self::RGBA(0.627451, 0.431373, 0.725490, 1.000000),\n\n \"31\" => Self::RGBA(0.803922, 0.643137, 0.870588, 1.000000),\n\n \"68\" => Self::RGBA(0.992157, 0.764706, 0.513726, 1.000000),\n\n \"69\" => Self::RGBA(0.541176, 0.070588, 0.658824, 1.000000),\n\n \"70\" => Self::RGBA(0.372549, 0.192157, 0.035294, 1.000000),\n\n \"71\" => Self::RGBA(0.588235, 0.588235, 0.588235, 1.000000),\n\n \"72\" => Self::RGBA(0.392157, 0.392157, 0.392157, 1.000000),\n", "file_path": "src/parser.rs", "rank": 98, "score": 8905.450748167197 }, { "content": " \"73\" => Self::RGBA(0.450980, 0.588235, 0.784314, 1.000000),\n\n \"74\" => Self::RGBA(0.498039, 0.768627, 0.458824, 1.000000),\n\n \"77\" => Self::RGBA(0.996078, 0.800000, 0.811765, 1.000000),\n\n \"78\" => Self::RGBA(1.000000, 0.788235, 0.584314, 1.000000),\n\n \"84\" => Self::RGBA(0.666667, 0.490196, 0.333333, 1.000000),\n\n \"85\" => Self::RGBA(0.266667, 0.101961, 0.568627, 1.000000),\n\n \"86\" => Self::RGBA(0.678431, 0.380392, 0.250980, 1.000000),\n\n \"89\" => Self::RGBA(0.109804, 0.345098, 0.654902, 1.000000),\n\n \"92\" => Self::RGBA(0.733333, 0.501961, 0.352941, 1.000000),\n\n \"100\" => Self::RGBA(0.976471, 0.717647, 0.647059, 1.000000),\n\n \"110\" => Self::RGBA(0.149020, 0.274510, 0.603922, 1.000000),\n\n \"112\" => Self::RGBA(0.282353, 0.380392, 0.674510, 1.000000),\n\n \"115\" => Self::RGBA(0.717647, 0.831373, 0.145098, 1.000000),\n\n \"118\" => Self::RGBA(0.611765, 0.839216, 0.800000, 1.000000),\n\n \"120\" => Self::RGBA(0.870588, 0.917647, 0.572549, 1.000000),\n\n \"125\" => Self::RGBA(0.976471, 0.654902, 0.466667, 1.000000),\n\n \"128\" => Self::RGBA(0.678431, 0.380392, 0.250980, 1.000000),\n\n \"151\" => Self::RGBA(0.784314, 0.784314, 0.784314, 1.000000),\n\n \"191\" => Self::RGBA(0.988235, 0.674510, 0.000000, 1.000000),\n\n \"212\" => Self::RGBA(0.615686, 0.764706, 0.968627, 1.000000),\n", "file_path": "src/parser.rs", "rank": 99, "score": 8905.450748167197 } ]
Rust
src/scope.rs
redzic/grass
37c1ada66418fdbb87968ede91efb9be83a80afa
use std::collections::HashMap; use codemap::Spanned; use crate::{ atrule::{Function, Mixin}, builtin::GLOBAL_FUNCTIONS, common::Identifier, error::SassResult, value::Value, }; #[derive(Debug, Clone, Default)] pub(crate) struct Scope { vars: HashMap<Identifier, Spanned<Value>>, mixins: HashMap<Identifier, Mixin>, functions: HashMap<Identifier, Function>, } impl Scope { #[must_use] pub fn new() -> Self { Self { vars: HashMap::new(), mixins: HashMap::new(), functions: HashMap::new(), } } fn get_var_no_global(&self, name: &Spanned<Identifier>) -> SassResult<Spanned<Value>> { match self.vars.get(&name.node) { Some(v) => Ok(v.clone()), None => Err(("Undefined variable.", name.span).into()), } } pub fn get_var<T: Into<Identifier>>( &self, name: Spanned<T>, global_scope: &Scope, ) -> SassResult<Spanned<Value>> { let name = name.map_node(Into::into); match self.vars.get(&name.node) { Some(v) => Ok(v.clone()), None => global_scope.get_var_no_global(&name), } } pub fn insert_var<T: Into<Identifier>>( &mut self, s: T, v: Spanned<Value>, ) -> Option<Spanned<Value>> { self.vars.insert(s.into(), v) } pub fn var_exists_no_global(&self, name: &Identifier) -> bool { self.vars.contains_key(name) } pub fn var_exists<'a, T: Into<&'a Identifier>>(&self, v: T, global_scope: &Scope) -> bool { let name = v.into(); self.vars.contains_key(name) || global_scope.var_exists_no_global(name) } fn get_mixin_no_global(&self, name: &Spanned<Identifier>) -> SassResult<Mixin> { match self.mixins.get(&name.node) { Some(v) => Ok(v.clone()), None => Err(("Undefined mixin.", name.span).into()), } } pub fn get_mixin<T: Into<Identifier>>( &self, name: Spanned<T>, global_scope: &Scope, ) -> SassResult<Mixin> { let name = name.map_node(Into::into); match self.mixins.get(&name.node) { Some(v) => Ok(v.clone()), None => global_scope.get_mixin_no_global(&name), } } pub fn insert_mixin<T: Into<Identifier>>(&mut self, s: T, v: Mixin) -> Option<Mixin> { self.mixins.insert(s.into(), v) } fn mixin_exists_no_global(&self, name: &Identifier) -> bool { self.mixins.contains_key(name) } pub fn mixin_exists<T: Into<Identifier>>(&self, v: T, global_scope: &Scope) -> bool { let name = v.into(); self.mixins.contains_key(&name) || global_scope.mixin_exists_no_global(&name) } fn get_fn_no_global(&self, name: &Spanned<Identifier>) -> SassResult<Function> { match self.functions.get(&name.node) { Some(v) => Ok(v.clone()), None => Err(("Undefined function.", name.span).into()), } } pub fn get_fn<T: Into<Identifier>>( &self, name: Spanned<T>, global_scope: &Scope, ) -> SassResult<Function> { let name = name.map_node(Into::into); match self.functions.get(&name.node) { Some(v) => Ok(v.clone()), None => global_scope.get_fn_no_global(&name), } } pub fn insert_fn<T: Into<Identifier>>(&mut self, s: T, v: Function) -> Option<Function> { self.functions.insert(s.into(), v) } fn fn_exists_no_global(&self, name: &Identifier) -> bool { self.functions.contains_key(name) } pub fn fn_exists<T: Into<Identifier>>(&self, v: T, global_scope: &Scope) -> bool { let name = v.into(); self.functions.contains_key(&name) || global_scope.fn_exists_no_global(&name) || GLOBAL_FUNCTIONS.contains_key(name.clone().into_inner().as_str()) } }
use std::collections::HashMap; use codemap::Spanned; use crate::{ atrule::{Function, Mixin}, builtin::GLOBAL_FUNCTIONS, common::Identifier, error::SassResult, value::Value, }; #[derive(Debug, Clone, Default)] pub(crate) struct Scope { vars: HashMap<Identifier, Spanned<Value>>, mixins: HashMap<Identifier, Mixin>, functions: HashMap<Identifier, Function>, } impl Scope { #[must_use] pub fn new() -> Self { Self { vars: HashMap::new(), mixins: HashMap::new(), functions: HashMap::new(), } } fn get_var_no_global(&self, name: &Spanned<Identifier>) -> SassResult<Spanned<Value>> { match self.vars.get(&name.node) { Some(v) => Ok(v.clone()), None => Err(("Undefined variable.", name.span).into()), } } pub fn get_var<T: Into<Identifier>>( &self, name: Spanned<T>, global_scope: &Scope, ) -> SassResult<Spanned<Value>> { let name = name.map_node(Into::into); match self.vars.get(&name.node) { Some(v) => Ok(v.clone()), None => global_scope.get_var_no_global(&name), } } pub fn insert_var<T: Into<Identifier>>( &mut self, s: T, v: Spanned<Value>, ) -> Option<Spanned<Value>> { self.vars.insert(s.into(), v) } pub fn var_exists_no_global(&self, name: &Identifier) -> bool { self.vars.contains_key(name) } pub fn var_exists<'a, T: Into<&'a Identifier>>(&self, v: T, global_scope: &Scope) -> bool { let name = v.into(); self.vars.contains_key(name) || global_scope.var_exists_no_global(name) } fn get_mixin_no_global(&self, name: &Spanned<Identifier>) -> SassResult<Mixin> { match self.mixins.get(&name.node) { Some(v) => Ok(v.clone()), None => Err(("Undefined mixin.", name.span).into()), } } pub fn get_mixin<T: Into<Identifier>>( &self, name: Spanned<T>, global_scope: &Scope, ) -> SassResult<Mixin> { let name = name.map_node(Into::into); match self.mixins.get(&name.node) { Some(v) => Ok(v.clone()), None => global_scope.get_mixin_no_global(&name), } } pub fn insert_mixin<T: Into<Identifier>>(&mut self, s: T, v: Mixin) -> Option<Mixin> { self.mixins.insert(s.into(), v) } fn mixin_exists_no_global(&self, name: &Identifier) -> bool { self.mixins.contains_key(name) } pub fn mixin_exists<T: Into<Identifier>>(&self, v: T, global_scope: &Scope) -> bool { let name = v.into(); self.mixins.contains_key(&name) || global_scope.mixin_exists_no_global(&name) }
pub fn get_fn<T: Into<Identifier>>( &self, name: Spanned<T>, global_scope: &Scope, ) -> SassResult<Function> { let name = name.map_node(Into::into); match self.functions.get(&name.node) { Some(v) => Ok(v.clone()), None => global_scope.get_fn_no_global(&name), } } pub fn insert_fn<T: Into<Identifier>>(&mut self, s: T, v: Function) -> Option<Function> { self.functions.insert(s.into(), v) } fn fn_exists_no_global(&self, name: &Identifier) -> bool { self.functions.contains_key(name) } pub fn fn_exists<T: Into<Identifier>>(&self, v: T, global_scope: &Scope) -> bool { let name = v.into(); self.functions.contains_key(&name) || global_scope.fn_exists_no_global(&name) || GLOBAL_FUNCTIONS.contains_key(name.clone().into_inner().as_str()) } }
fn get_fn_no_global(&self, name: &Spanned<Identifier>) -> SassResult<Function> { match self.functions.get(&name.node) { Some(v) => Ok(v.clone()), None => Err(("Undefined function.", name.span).into()), } }
function_block-full_function
[ { "content": "pub fn many_variable_redeclarations(c: &mut Criterion) {\n\n c.bench_function(\"many_variable_redeclarations\", |b| {\n\n b.iter(|| {\n\n StyleSheet::new(black_box(\n\n include_str!(\"many_variable_redeclarations.scss\").to_string(),\n\n ))\n\n })\n\n });\n\n}\n\n\n\ncriterion_group!(benches, many_variable_redeclarations);\n\ncriterion_main!(benches);\n", "file_path": "benches/variables.rs", "rank": 0, "score": 251083.7916173572 }, { "content": "pub fn many_named_colors(c: &mut Criterion) {\n\n c.bench_function(\"many_named_colors\", |b| {\n\n b.iter(|| {\n\n StyleSheet::new(black_box(\n\n include_str!(\"many_named_colors.scss\").to_string(),\n\n ))\n\n })\n\n });\n\n}\n\n\n\ncriterion_group!(benches, many_hsla, many_named_colors,);\n\ncriterion_main!(benches);\n", "file_path": "benches/colors.rs", "rank": 1, "score": 239482.38586622328 }, { "content": "/// Returns whether `name` is the name of a pseudo-element that can be written\n\n/// with pseudo-class syntax (`:before`, `:after`, `:first-line`, or\n\n/// `:first-letter`)\n\nfn is_fake_pseudo_element(name: &str) -> bool {\n\n match name.as_bytes().get(0) {\n\n Some(b'a') | Some(b'A') => name.to_ascii_lowercase() == \"after\",\n\n Some(b'b') | Some(b'B') => name.to_ascii_lowercase() == \"before\",\n\n Some(b'f') | Some(b'F') => match name.to_ascii_lowercase().as_str() {\n\n \"first-line\" | \"first-letter\" => true,\n\n _ => false,\n\n },\n\n _ => false,\n\n }\n\n}\n", "file_path": "src/selector/parse.rs", "rank": 2, "score": 203605.38392226864 }, { "content": "pub fn many_integers(c: &mut Criterion) {\n\n c.bench_function(\"many_integers\", |b| {\n\n b.iter(|| StyleSheet::new(black_box(include_str!(\"many_integers.scss\").to_string())))\n\n });\n\n}\n\n\n", "file_path": "benches/numbers.rs", "rank": 3, "score": 201884.55756371026 }, { "content": "pub fn many_foo(c: &mut Criterion) {\n\n c.bench_function(\"many_foo\", |b| {\n\n b.iter(|| StyleSheet::new(black_box(include_str!(\"many_foo.scss\").to_string())))\n\n });\n\n}\n\n\n\ncriterion_group!(benches, many_foo);\n\ncriterion_main!(benches);\n", "file_path": "benches/styles.rs", "rank": 4, "score": 201884.55756371026 }, { "content": "pub fn many_hsla(c: &mut Criterion) {\n\n c.bench_function(\"many_hsla\", |b| {\n\n b.iter(|| StyleSheet::new(black_box(include_str!(\"many_hsla.scss\").to_string())))\n\n });\n\n}\n\n\n", "file_path": "benches/colors.rs", "rank": 5, "score": 201884.55756371026 }, { "content": "pub fn many_floats(c: &mut Criterion) {\n\n c.bench_function(\"many_floats\", |b| {\n\n b.iter(|| StyleSheet::new(black_box(include_str!(\"many_floats.scss\").to_string())))\n\n });\n\n}\n\n\n", "file_path": "benches/numbers.rs", "rank": 6, "score": 201884.55756371026 }, { "content": "pub fn big_for(c: &mut Criterion) {\n\n c.bench_function(\"big_for\", |b| {\n\n b.iter(|| StyleSheet::new(black_box(include_str!(\"big_for.scss\").to_string())))\n\n });\n\n}\n\n\n\ncriterion_group!(benches, big_for);\n\ncriterion_main!(benches);\n", "file_path": "benches/control_flow.rs", "rank": 7, "score": 201884.55756371026 }, { "content": "pub fn many_small_integers(c: &mut Criterion) {\n\n c.bench_function(\"many_small_integers\", |b| {\n\n b.iter(|| {\n\n StyleSheet::new(black_box(\n\n include_str!(\"many_small_integers.scss\").to_string(),\n\n ))\n\n })\n\n });\n\n}\n\n\n\ncriterion_group!(benches, many_floats, many_integers, many_small_integers);\n\ncriterion_main!(benches);\n", "file_path": "benches/numbers.rs", "rank": 8, "score": 198436.13650832762 }, { "content": "/// Returns all pseudo selectors in `compound` that have a selector argument,\n\n/// and that have the given `name`.\n\n// todo: return `impl Iterator<Item = Pseudo>`\n\nfn selector_pseudos_named(compound: CompoundSelector, name: &str, is_class: bool) -> Vec<Pseudo> {\n\n compound\n\n .components\n\n .into_iter()\n\n .filter_map(|c| {\n\n if let SimpleSelector::Pseudo(p) = c {\n\n Some(p)\n\n } else {\n\n None\n\n }\n\n })\n\n .filter(|p| p.is_class == is_class && p.selector.is_some() && p.name == name)\n\n .collect()\n\n}\n", "file_path": "src/selector/simple.rs", "rank": 9, "score": 183618.42527469585 }, { "content": "/// Returns all orderings of initial subseqeuences of `queue_one` and `queue_two`.\n\n///\n\n/// The `done` callback is used to determine the extent of the initial\n\n/// subsequences. It's called with each queue until it returns `true`.\n\n///\n\n/// This destructively removes the initial subsequences of `queue_one` and\n\n/// `queue_two`.\n\n///\n\n/// For example, given `(A B C | D E)` and `(1 2 | 3 4 5)` (with `|` denoting\n\n/// the boundary of the initial subsequence), this would return `[(A B C 1 2),\n\n/// (1 2 A B C)]`. The queues would then contain `(D E)` and `(3 4 5)`.\n\nfn chunks<T: Clone>(\n\n queue_one: &mut VecDeque<T>,\n\n queue_two: &mut VecDeque<T>,\n\n done: impl Fn(&VecDeque<T>) -> bool,\n\n) -> Vec<Vec<T>> {\n\n let mut chunk_one = Vec::new();\n\n while !done(queue_one) {\n\n chunk_one.push(queue_one.pop_front().unwrap());\n\n }\n\n\n\n let mut chunk_two = Vec::new();\n\n while !done(queue_two) {\n\n chunk_two.push(queue_two.pop_front().unwrap());\n\n }\n\n\n\n match (chunk_one.is_empty(), chunk_two.is_empty()) {\n\n (true, true) => Vec::new(),\n\n (true, false) => vec![chunk_two],\n\n (false, true) => vec![chunk_one],\n\n (false, false) => {\n", "file_path": "src/selector/extend/functions.rs", "rank": 10, "score": 182242.879290837 }, { "content": "/// Returns whether a `CompoundSelector` may contain only one simple selector of\n\n/// the same type as `simple`.\n\nfn is_unique(simple: &SimpleSelector) -> bool {\n\n matches!(simple, SimpleSelector::Id(..) | SimpleSelector::Pseudo(Pseudo { is_class: false, .. }))\n\n}\n", "file_path": "src/selector/extend/functions.rs", "rank": 11, "score": 172699.00705677737 }, { "content": "/// Returns whether or not `compound` contains a `::root` selector.\n\nfn has_root(compound: &CompoundSelector) -> bool {\n\n compound.components.iter().any(|simple| {\n\n if let SimpleSelector::Pseudo(pseudo) = simple {\n\n pseudo.is_class && &*pseudo.normalized_name == \"root\"\n\n } else {\n\n false\n\n }\n\n })\n\n}\n\n\n", "file_path": "src/selector/extend/functions.rs", "rank": 12, "score": 172699.00705677737 }, { "content": "#[allow(clippy::cognitive_complexity)]\n\nfn inner_rgb(name: &'static str, mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n if args.is_empty() {\n\n return Err((\"Missing argument $channels.\", args.span()).into());\n\n }\n\n\n\n if args.len() == 1 {\n\n let mut channels = match parser.arg(&mut args, 0, \"channels\")? {\n\n Value::List(v, ..) => v,\n\n _ => return Err((\"Missing argument $channels.\", args.span()).into()),\n\n };\n\n\n\n if channels.len() > 3 {\n\n return Err((\n\n format!(\n\n \"Only 3 elements allowed, but {} were passed.\",\n\n channels.len()\n\n ),\n\n args.span(),\n\n )\n\n .into());\n", "file_path": "src/builtin/color/rgb.rs", "rank": 13, "score": 170313.1064320451 }, { "content": "fn inner_hsl(name: &'static str, mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n if args.is_empty() {\n\n return Err((\"Missing argument $channels.\", args.span()).into());\n\n }\n\n\n\n if args.len() == 1 {\n\n let mut channels = match parser.arg(&mut args, 0, \"channels\")? {\n\n Value::List(v, ..) => v,\n\n _ => return Err((\"Missing argument $channels.\", args.span()).into()),\n\n };\n\n\n\n if channels.len() > 3 {\n\n return Err((\n\n format!(\n\n \"Only 3 elements allowed, but {} were passed.\",\n\n channels.len()\n\n ),\n\n args.span(),\n\n )\n\n .into());\n", "file_path": "src/builtin/color/hsl.rs", "rank": 14, "score": 170313.1064320451 }, { "content": "fn visit_quoted_string(buf: &mut String, force_double_quote: bool, string: &str) {\n\n let mut has_single_quote = false;\n\n let mut has_double_quote = false;\n\n\n\n let mut buffer = String::new();\n\n\n\n if force_double_quote {\n\n buffer.push('\"');\n\n }\n\n let mut iter = string.chars().peekable();\n\n while let Some(c) = iter.next() {\n\n match c {\n\n '\\'' => {\n\n if force_double_quote {\n\n buffer.push('\\'');\n\n } else if has_double_quote {\n\n return visit_quoted_string(buf, true, string);\n\n } else {\n\n has_single_quote = true;\n\n buffer.push('\\'');\n", "file_path": "src/value/mod.rs", "rank": 15, "score": 169828.6353939164 }, { "content": "#[allow(clippy::cast_sign_loss, clippy::cast_possible_wrap)]\n\nfn longest_common_subsequence<T: PartialEq + Clone>(\n\n list_one: &[T],\n\n list_two: &[T],\n\n select: Option<&dyn Fn(T, T) -> Option<T>>,\n\n) -> Vec<T> {\n\n let select = select.unwrap_or(&|element_one, element_two| {\n\n if element_one == element_two {\n\n Some(element_one)\n\n } else {\n\n None\n\n }\n\n });\n\n\n\n let mut lengths = vec![vec![0; list_two.len() + 1]; list_one.len() + 1];\n\n\n\n let mut selections: Vec<Vec<Option<T>>> = vec![vec![None; list_two.len()]; list_one.len()];\n\n\n\n for i in 0..list_one.len() {\n\n for j in 0..list_two.len() {\n\n let selection = select(\n", "file_path": "src/selector/extend/functions.rs", "rank": 16, "score": 166847.95853854416 }, { "content": "fn peek_whitespace<I: Iterator<Item = W>, W: IsWhitespace>(s: &mut PeekMoreIterator<I>) -> bool {\n\n let mut found_whitespace = false;\n\n while let Some(w) = s.peek() {\n\n if !w.is_whitespace() {\n\n break;\n\n }\n\n found_whitespace = true;\n\n s.advance_cursor();\n\n }\n\n found_whitespace\n\n}\n\n\n\npub(crate) fn peek_escape<I: Iterator<Item = Token>>(\n\n toks: &mut PeekMoreIterator<I>,\n\n) -> SassResult<String> {\n\n let mut value = 0;\n\n let first = match toks.peek() {\n\n Some(t) => *t,\n\n None => return Ok(String::new()),\n\n };\n", "file_path": "src/utils/peek_until.rs", "rank": 17, "score": 163094.85624715738 }, { "content": "fn variable_exists(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"name\")? {\n\n Value::String(s, _) => Ok(Value::bool(\n\n parser\n\n .scopes\n\n .last()\n\n .var_exists(&s.into(), parser.global_scope),\n\n )),\n\n v => Err((\n\n format!(\"$name: {} is not a string.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/meta.rs", "rank": 18, "score": 161006.13689536368 }, { "content": "fn mixin_exists(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n match parser.arg(&mut args, 0, \"name\")? {\n\n Value::String(s, _) => Ok(Value::bool(\n\n parser.scopes.last().mixin_exists(&s, parser.global_scope),\n\n )),\n\n v => Err((\n\n format!(\"$name: {} is not a string.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/meta.rs", "rank": 19, "score": 160981.8731236958 }, { "content": "fn get_function(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(3)?;\n\n let name = match parser.arg(&mut args, 0, \"name\")? {\n\n Value::String(s, _) => s,\n\n v => {\n\n return Err((\n\n format!(\"$name: {} is not a string.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n let css = parser\n\n .default_arg(&mut args, 1, \"css\", Value::False)?\n\n .is_true();\n\n let module = match parser.default_arg(&mut args, 2, \"module\", Value::Null)? {\n\n Value::String(s, ..) => Some(s),\n\n Value::Null => None,\n\n v => {\n\n return Err((\n", "file_path": "src/builtin/meta.rs", "rank": 20, "score": 160783.20598667892 }, { "content": "fn function_exists(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n match parser.arg(&mut args, 0, \"name\")? {\n\n Value::String(s, _) => Ok(Value::bool(\n\n parser.scopes.last().fn_exists(&s, parser.global_scope),\n\n )),\n\n v => Err((\n\n format!(\"$name: {} is not a string.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/meta.rs", "rank": 21, "score": 160783.20598667892 }, { "content": "fn global_variable_exists(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"name\")? {\n\n Value::String(s, _) => Ok(Value::bool(\n\n parser.global_scope.var_exists_no_global(&s.into()),\n\n )),\n\n v => Err((\n\n format!(\"$name: {} is not a string.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/meta.rs", "rank": 22, "score": 158749.42654168748 }, { "content": "/// Rotates the element in list from `start` (inclusive) to `end` (exclusive)\n\n/// one index higher, looping the final element back to `start`.\n\nfn rotate_slice<T: Clone>(list: &mut VecDeque<T>, start: usize, end: usize) {\n\n let mut element = list.get(end - 1).unwrap().clone();\n\n for i in start..end {\n\n let next = list.get(i).unwrap().clone();\n\n list[i] = element;\n\n element = next;\n\n }\n\n}\n\n\n", "file_path": "src/selector/extend/mod.rs", "rank": 23, "score": 158348.03030058625 }, { "content": "fn attribute_name(parser: &mut Parser<'_>, start: Span) -> SassResult<QualifiedName> {\n\n let next = parser.toks.peek().ok_or((\"Expected identifier.\", start))?;\n\n if next.kind == '*' {\n\n let pos = next.pos;\n\n parser.toks.next();\n\n if parser.toks.peek().ok_or((\"expected \\\"|\\\".\", pos))?.kind != '|' {\n\n return Err((\"expected \\\"|\\\".\", pos).into());\n\n }\n\n\n\n parser.span_before = parser.toks.next().unwrap().pos();\n\n\n\n let ident = parser.parse_identifier()?.node;\n\n return Ok(QualifiedName {\n\n ident,\n\n namespace: Namespace::Asterisk,\n\n });\n\n }\n\n parser.span_before = next.pos;\n\n let name_or_namespace = parser.parse_identifier()?;\n\n match parser.toks.peek() {\n", "file_path": "src/selector/attribute.rs", "rank": 24, "score": 157367.94742755778 }, { "content": "/// If the first element of `queue` has a `::root` selector, removes and returns\n\n/// that element.\n\nfn first_if_root(queue: &mut VecDeque<ComplexSelectorComponent>) -> Option<CompoundSelector> {\n\n if queue.is_empty() {\n\n return None;\n\n }\n\n if let Some(ComplexSelectorComponent::Compound(c)) = queue.get(0) {\n\n if !has_root(c) {\n\n return None;\n\n }\n\n let compound = c.clone();\n\n queue.pop_front();\n\n Some(compound)\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "src/selector/extend/functions.rs", "rank": 25, "score": 143286.29576773106 }, { "content": "#[derive(Debug)]\n\nstruct VariableValue {\n\n value: Spanned<Value>,\n\n global: bool,\n\n default: bool,\n\n}\n\n\n\nimpl VariableValue {\n\n pub const fn new(value: Spanned<Value>, global: bool, default: bool) -> Self {\n\n Self {\n\n value,\n\n global,\n\n default,\n\n }\n\n }\n\n}\n\n\n\nimpl<'a> Parser<'a> {\n\n pub(super) fn parse_variable_declaration(&mut self) -> SassResult<()> {\n\n assert!(matches!(self.toks.next(), Some(Token { kind: '$', .. })));\n\n let ident: Identifier = self.parse_identifier_no_interpolation(false)?.node.into();\n", "file_path": "src/parse/variable.rs", "rank": 26, "score": 135898.23642589938 }, { "content": "/// Returns whether `c` can start a simple selector other than a type\n\n/// selector.\n\nfn is_simple_selector_start(c: char) -> bool {\n\n matches!(c, '*' | '[' | '.' | '#' | '%' | ':')\n\n}\n\n\n", "file_path": "src/selector/parse.rs", "rank": 27, "score": 135205.3274363767 }, { "content": "#[cfg_attr(feature = \"profiling\", inline(never))]\n\n#[cfg_attr(not(feature = \"profiling\"), inline)]\n\n#[cfg(not(feature = \"wasm\"))]\n\npub fn from_string(p: String) -> Result<String> {\n\n let mut map = CodeMap::new();\n\n let file = map.add_file(\"stdin\".into(), p);\n\n let empty_span = file.span.subspan(0, 0);\n\n let stmts = Parser {\n\n toks: &mut Lexer::new(&file)\n\n .collect::<Vec<Token>>()\n\n .into_iter()\n\n .peekmore(),\n\n map: &mut map,\n\n path: Path::new(\"\"),\n\n scopes: &mut NeverEmptyVec::new(Scope::new()),\n\n global_scope: &mut Scope::new(),\n\n super_selectors: &mut NeverEmptyVec::new(Selector::new(empty_span)),\n\n span_before: empty_span,\n\n content: &mut Vec::new(),\n\n flags: ContextFlags::empty(),\n\n at_root: true,\n\n at_root_has_selector: false,\n\n extender: &mut Extender::new(empty_span),\n\n }\n\n .parse()\n\n .map_err(|e| raw_to_parse_error(&map, *e))?;\n\n\n\n Css::from_stmts(stmts, false)\n\n .map_err(|e| raw_to_parse_error(&map, *e))?\n\n .pretty_print(&map)\n\n .map_err(|e| raw_to_parse_error(&map, *e))\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 28, "score": 132815.16290312083 }, { "content": "#[cfg_attr(feature = \"profiling\", inline(never))]\n\n#[cfg_attr(not(feature = \"profiling\"), inline)]\n\n#[cfg(not(feature = \"wasm\"))]\n\npub fn from_path(p: &str) -> Result<String> {\n\n let mut map = CodeMap::new();\n\n let file = map.add_file(p.into(), String::from_utf8(fs::read(p)?)?);\n\n let empty_span = file.span.subspan(0, 0);\n\n\n\n let stmts = Parser {\n\n toks: &mut Lexer::new(&file)\n\n .collect::<Vec<Token>>()\n\n .into_iter()\n\n .peekmore(),\n\n map: &mut map,\n\n path: p.as_ref(),\n\n scopes: &mut NeverEmptyVec::new(Scope::new()),\n\n global_scope: &mut Scope::new(),\n\n super_selectors: &mut NeverEmptyVec::new(Selector::new(empty_span)),\n\n span_before: empty_span,\n\n content: &mut Vec::new(),\n\n flags: ContextFlags::empty(),\n\n at_root: true,\n\n at_root_has_selector: false,\n", "file_path": "src/lib.rs", "rank": 29, "score": 132815.16290312083 }, { "content": "fn if_(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(3)?;\n\n if parser.arg(&mut args, 0, \"condition\")?.is_true() {\n\n Ok(parser.arg(&mut args, 1, \"if-true\")?)\n\n } else {\n\n Ok(parser.arg(&mut args, 2, \"if-false\")?)\n\n }\n\n}\n\n\n", "file_path": "src/builtin/meta.rs", "rank": 30, "score": 129730.22053820067 }, { "content": "/// When `style` is `OutputStyle::compressed`, omit spaces around combinators.\n\nfn omit_spaces_around(component: &ComplexSelectorComponent) -> bool {\n\n // todo: compressed\n\n let is_compressed = false;\n\n is_compressed && matches!(component, ComplexSelectorComponent::Combinator(..))\n\n}\n\n\n\nimpl ComplexSelector {\n\n pub fn max_specificity(&self) -> i32 {\n\n self.specificity().min\n\n }\n\n\n\n pub fn min_specificity(&self) -> i32 {\n\n self.specificity().max\n\n }\n\n\n\n pub fn specificity(&self) -> Specificity {\n\n let mut min = 0;\n\n let mut max = 0;\n\n for component in &self.components {\n\n if let ComplexSelectorComponent::Compound(compound) = component {\n", "file_path": "src/selector/complex.rs", "rank": 31, "score": 129001.44775203429 }, { "content": "fn percentage(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n let num = match parser.arg(&mut args, 0, \"number\")? {\n\n Value::Dimension(n, Unit::None) => n * Number::from(100),\n\n v @ Value::Dimension(..) => {\n\n return Err((\n\n format!(\n\n \"$number: Expected {} to have no units.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n v => {\n\n return Err((\n\n format!(\n\n \"$number: {} is not a number.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n Ok(Value::Dimension(num, Unit::Percent))\n\n}\n\n\n", "file_path": "src/builtin/math.rs", "rank": 32, "score": 128125.69617915756 }, { "content": "fn is_superselector(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let parent_selector = parser\n\n .arg(&mut args, 0, \"super\")?\n\n .to_selector(parser, \"super\", false)?;\n\n let child_selector = parser\n\n .arg(&mut args, 1, \"sub\")?\n\n .to_selector(parser, \"sub\", false)?;\n\n\n\n Ok(Value::bool(\n\n parent_selector.is_super_selector(&child_selector),\n\n ))\n\n}\n\n\n", "file_path": "src/builtin/selector.rs", "rank": 33, "score": 128125.69617915756 }, { "content": "fn unitless(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n #[allow(clippy::match_same_arms)]\n\n Ok(match parser.arg(&mut args, 0, \"number\")? {\n\n Value::Dimension(_, Unit::None) => Value::True,\n\n Value::Dimension(_, _) => Value::False,\n\n _ => Value::True,\n\n })\n\n}\n\n\n", "file_path": "src/builtin/meta.rs", "rank": 34, "score": 128125.69617915756 }, { "content": "fn length(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n Ok(Value::Dimension(\n\n Number::from(parser.arg(&mut args, 0, \"list\")?.as_list().len()),\n\n Unit::None,\n\n ))\n\n}\n\n\n", "file_path": "src/builtin/list.rs", "rank": 35, "score": 128125.69617915756 }, { "content": "fn is_bracketed(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n Ok(Value::bool(match parser.arg(&mut args, 0, \"list\")? {\n\n Value::List(.., brackets) => match brackets {\n\n Brackets::Bracketed => true,\n\n Brackets::None => false,\n\n },\n\n _ => false,\n\n }))\n\n}\n\n\n", "file_path": "src/builtin/list.rs", "rank": 36, "score": 128125.69617915756 }, { "content": "#[cfg(feature = \"random\")]\n\nfn random(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n let limit = match parser.default_arg(&mut args, 0, \"limit\", Value::Null)? {\n\n Value::Dimension(n, _) => n,\n\n Value::Null => {\n\n let mut rng = rand::thread_rng();\n\n return Ok(Value::Dimension(\n\n Number::from(rng.gen_range(0.0, 1.0)),\n\n Unit::None,\n\n ));\n\n }\n\n v => {\n\n return Err((\n\n format!(\"$limit: {} is not a number.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n\n", "file_path": "src/builtin/math.rs", "rank": 37, "score": 128125.69617915756 }, { "content": "fn inspect(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n Ok(Value::String(\n\n parser\n\n .arg(&mut args, 0, \"value\")?\n\n .inspect(args.span())?\n\n .into_owned(),\n\n QuoteKind::None,\n\n ))\n\n}\n\n\n", "file_path": "src/builtin/meta.rs", "rank": 38, "score": 128125.69617915756 }, { "content": "fn append(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(3)?;\n\n let (mut list, sep, brackets) = match parser.arg(&mut args, 0, \"list\")? {\n\n Value::List(v, sep, b) => (v, sep, b),\n\n v => (vec![v], ListSeparator::Space, Brackets::None),\n\n };\n\n let val = parser.arg(&mut args, 1, \"val\")?;\n\n let sep = match parser.default_arg(\n\n &mut args,\n\n 2,\n\n \"separator\",\n\n Value::String(\"auto\".to_owned(), QuoteKind::None),\n\n )? {\n\n Value::String(s, ..) => match s.as_str() {\n\n \"auto\" => sep,\n\n \"comma\" => ListSeparator::Comma,\n\n \"space\" => ListSeparator::Space,\n\n _ => {\n\n return Err((\n\n \"$separator: Must be \\\"space\\\", \\\"comma\\\", or \\\"auto\\\".\",\n", "file_path": "src/builtin/list.rs", "rank": 39, "score": 128125.69617915756 }, { "content": "fn nth(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let mut list = parser.arg(&mut args, 0, \"list\")?.as_list();\n\n let n = match parser.arg(&mut args, 1, \"n\")? {\n\n Value::Dimension(num, _) => num,\n\n v => {\n\n return Err((\n\n format!(\"$n: {} is not a number.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n\n\n if n.is_zero() {\n\n return Err((\"$n: List index may not be 0.\", args.span()).into());\n\n }\n\n\n\n if n.abs() > Number::from(list.len()) {\n\n return Err((\n", "file_path": "src/builtin/list.rs", "rank": 40, "score": 128125.69617915756 }, { "content": "fn call(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n let func = match parser.arg(&mut args, 0, \"function\")? {\n\n Value::FunctionRef(f) => f,\n\n v => {\n\n return Err((\n\n format!(\n\n \"$function: {} is not a function reference.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n func.call(args.decrement(), parser)\n\n}\n\n\n", "file_path": "src/builtin/meta.rs", "rank": 41, "score": 128125.69617915756 }, { "content": "fn ceil(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"number\")? {\n\n Value::Dimension(n, u) => Ok(Value::Dimension(n.ceil(), u)),\n\n v => Err((\n\n format!(\n\n \"$number: {} is not a number.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/math.rs", "rank": 42, "score": 128125.69617915756 }, { "content": "fn round(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"number\")? {\n\n Value::Dimension(n, u) => Ok(Value::Dimension(n.round(), u)),\n\n v => Err((\n\n format!(\n\n \"$number: {} is not a number.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/math.rs", "rank": 43, "score": 128125.69617915756 }, { "content": "fn comparable(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let unit1 = match parser.arg(&mut args, 0, \"number1\")? {\n\n Value::Dimension(_, u) => u,\n\n v => {\n\n return Err((\n\n format!(\n\n \"$number1: {} is not a number.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n let unit2 = match parser.arg(&mut args, 1, \"number2\")? {\n\n Value::Dimension(_, u) => u,\n\n v => {\n\n return Err((\n\n format!(\n", "file_path": "src/builtin/math.rs", "rank": 44, "score": 128125.69617915756 }, { "content": "fn unquote(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"string\")? {\n\n i @ Value::String(..) => Ok(i.unquote()),\n\n v => Err((\n\n format!(\n\n \"$string: {} is not a string.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/string.rs", "rank": 45, "score": 128125.69617915756 }, { "content": "fn abs(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"number\")? {\n\n Value::Dimension(n, u) => Ok(Value::Dimension(n.abs(), u)),\n\n v => Err((\n\n format!(\n\n \"$number: {} is not a number.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/math.rs", "rank": 46, "score": 128125.69617915756 }, { "content": "fn quote(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"string\")? {\n\n Value::String(i, _) => Ok(Value::String(i, QuoteKind::Quoted)),\n\n v => Err((\n\n format!(\n\n \"$string: {} is not a string.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/string.rs", "rank": 47, "score": 128125.69617915756 }, { "content": "fn unit(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n let unit = match parser.arg(&mut args, 0, \"number\")? {\n\n Value::Dimension(_, u) => u.to_string(),\n\n v => {\n\n return Err((\n\n format!(\n\n \"$number: {} is not a number.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n Ok(Value::String(unit, QuoteKind::Quoted))\n\n}\n\n\n", "file_path": "src/builtin/meta.rs", "rank": 48, "score": 128125.69617915756 }, { "content": "fn type_of(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n let value = parser.arg(&mut args, 0, \"value\")?;\n\n Ok(Value::String(value.kind().to_owned(), QuoteKind::None))\n\n}\n\n\n", "file_path": "src/builtin/meta.rs", "rank": 49, "score": 128125.69617915756 }, { "content": "fn join(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(4)?;\n\n let (mut list1, sep1, brackets) = match parser.arg(&mut args, 0, \"list1\")? {\n\n Value::List(v, sep, brackets) => (v, sep, brackets),\n\n Value::Map(m) => (m.as_list(), ListSeparator::Comma, Brackets::None),\n\n v => (vec![v], ListSeparator::Space, Brackets::None),\n\n };\n\n let (list2, sep2) = match parser.arg(&mut args, 1, \"list2\")? {\n\n Value::List(v, sep, ..) => (v, sep),\n\n Value::Map(m) => (m.as_list(), ListSeparator::Comma),\n\n v => (vec![v], ListSeparator::Space),\n\n };\n\n let sep = match parser.default_arg(\n\n &mut args,\n\n 2,\n\n \"separator\",\n\n Value::String(\"auto\".to_owned(), QuoteKind::None),\n\n )? {\n\n Value::String(s, ..) => match s.as_str() {\n\n \"auto\" => {\n", "file_path": "src/builtin/list.rs", "rank": 50, "score": 128125.69617915756 }, { "content": "fn index(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let list = parser.arg(&mut args, 0, \"list\")?.as_list();\n\n let value = parser.arg(&mut args, 1, \"value\")?;\n\n // TODO: find a way to propagate any errors here\n\n // Potential input to fuzz: index(1px 1in 1cm, 96px + 1rem)\n\n let index = match list.into_iter().position(|v| {\n\n ValueVisitor::new(parser, args.span())\n\n .equal(\n\n HigherIntermediateValue::Literal(v),\n\n HigherIntermediateValue::Literal(value.clone()),\n\n )\n\n .map_or(false, |v| v.is_true())\n\n }) {\n\n Some(v) => Number::from(v + 1),\n\n None => return Ok(Value::Null),\n\n };\n\n Ok(Value::Dimension(index, Unit::None))\n\n}\n\n\n", "file_path": "src/builtin/list.rs", "rank": 51, "score": 128125.69617915756 }, { "content": "fn floor(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"number\")? {\n\n Value::Dimension(n, u) => Ok(Value::Dimension(n.floor(), u)),\n\n v => Err((\n\n format!(\n\n \"$number: {} is not a number.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/math.rs", "rank": 52, "score": 128125.69617915756 }, { "content": "fn feature_exists(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"feature\")? {\n\n #[allow(clippy::match_same_arms)]\n\n Value::String(s, _) => Ok(match s.as_str() {\n\n // A local variable will shadow a global variable unless\n\n // `!global` is used.\n\n \"global-variable-shadowing\" => Value::True,\n\n // the @extend rule will affect selectors nested in pseudo-classes\n\n // like :not()\n\n \"extend-selector-pseudoclass\" => Value::True,\n\n // Full support for unit arithmetic using units defined in the\n\n // [Values and Units Level 3][] spec.\n\n \"units-level-3\" => Value::True,\n\n // The Sass `@error` directive is supported.\n\n \"at-error\" => Value::True,\n\n // The \"Custom Properties Level 1\" spec is supported. This means\n\n // that custom properties are parsed statically, with only\n\n // interpolation treated as SassScript.\n\n \"custom-property\" => Value::False,\n", "file_path": "src/builtin/meta.rs", "rank": 53, "score": 126583.73620938795 }, { "content": "fn opacify(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let color = match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => c,\n\n v => {\n\n return Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n let amount = match parser.arg(&mut args, 1, \"amount\")? {\n\n Value::Dimension(n, u) => bound!(args, \"amount\", n, u, 0, 1),\n\n v => {\n\n return Err((\n\n format!(\n\n \"$amount: {} is not a number.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n Ok(Value::Color(Box::new(color.fade_in(amount))))\n\n}\n\n\n", "file_path": "src/builtin/color/opacity.rs", "rank": 54, "score": 126583.73620938795 }, { "content": "fn map_merge(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let mut map1 = match parser.arg(&mut args, 0, \"map1\")? {\n\n Value::Map(m) => m,\n\n Value::List(v, ..) if v.is_empty() => SassMap::new(),\n\n v => {\n\n return Err((\n\n format!(\"$map1: {} is not a map.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n let map2 = match parser.arg(&mut args, 1, \"map2\")? {\n\n Value::Map(m) => m,\n\n Value::List(v, ..) if v.is_empty() => SassMap::new(),\n\n v => {\n\n return Err((\n\n format!(\"$map2: {} is not a map.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n map1.merge(map2);\n\n Ok(Value::Map(map1))\n\n}\n\n\n", "file_path": "src/builtin/map.rs", "rank": 55, "score": 126583.73620938795 }, { "content": "fn saturation(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => Ok(Value::Dimension(c.saturation(), Unit::Percent)),\n\n v => Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/color/hsl.rs", "rank": 56, "score": 126583.73620938795 }, { "content": "fn change_color(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n if parser.positional_arg(&mut args, 1).is_some() {\n\n return Err((\n\n \"Only one positional argument is allowed. All other arguments must be passed by name.\",\n\n args.span(),\n\n )\n\n .into());\n\n }\n\n\n\n let color = match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => c,\n\n v => {\n\n return Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n\n", "file_path": "src/builtin/color/other.rs", "rank": 57, "score": 126583.73620938795 }, { "content": "fn selector_unify(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let selector1 =\n\n parser\n\n .arg(&mut args, 0, \"selector1\")?\n\n .to_selector(parser, \"selector1\", false)?;\n\n\n\n if selector1.contains_parent_selector() {\n\n return Err((\n\n \"$selector1: Parent selectors aren't allowed here.\",\n\n args.span(),\n\n )\n\n .into());\n\n }\n\n\n\n let selector2 =\n\n parser\n\n .arg(&mut args, 1, \"selector2\")?\n\n .to_selector(parser, \"selector2\", false)?;\n\n\n", "file_path": "src/builtin/selector.rs", "rank": 58, "score": 126583.73620938795 }, { "content": "fn blue(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => Ok(Value::Dimension(c.blue(), Unit::None)),\n\n v => Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/color/rgb.rs", "rank": 59, "score": 126583.73620938795 }, { "content": "fn to_lower_case(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"string\")? {\n\n Value::String(mut i, q) => {\n\n i.make_ascii_lowercase();\n\n Ok(Value::String(i, q))\n\n }\n\n v => Err((\n\n format!(\n\n \"$string: {} is not a string.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/string.rs", "rank": 60, "score": 126583.73620938795 }, { "content": "fn str_index(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let s1 = match parser.arg(&mut args, 0, \"string\")? {\n\n Value::String(i, _) => i,\n\n v => {\n\n return Err((\n\n format!(\n\n \"$string: {} is not a string.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n\n\n let substr = match parser.arg(&mut args, 1, \"substring\")? {\n\n Value::String(i, _) => i,\n\n v => {\n\n return Err((\n", "file_path": "src/builtin/string.rs", "rank": 61, "score": 126583.73620938795 }, { "content": "fn selector_parse(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n Ok(parser\n\n .arg(&mut args, 0, \"selector\")?\n\n .to_selector(parser, \"selector\", false)?\n\n .into_value())\n\n}\n\n\n", "file_path": "src/builtin/selector.rs", "rank": 62, "score": 126583.73620938795 }, { "content": "fn lighten(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let color = match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => c,\n\n v => {\n\n return Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n let amount = match parser.arg(&mut args, 1, \"amount\")? {\n\n Value::Dimension(n, u) => bound!(args, \"amount\", n, u, 0, 100) / Number::from(100),\n\n v => {\n\n return Err((\n\n format!(\n\n \"$amount: {} is not a number.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n Ok(Value::Color(Box::new(color.lighten(amount))))\n\n}\n\n\n", "file_path": "src/builtin/color/hsl.rs", "rank": 63, "score": 126583.73620938795 }, { "content": "fn selector_replace(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(3)?;\n\n let selector = parser\n\n .arg(&mut args, 0, \"selector\")?\n\n .to_selector(parser, \"selector\", false)?;\n\n let target = parser\n\n .arg(&mut args, 1, \"original\")?\n\n .to_selector(parser, \"original\", false)?;\n\n let source =\n\n parser\n\n .arg(&mut args, 2, \"replacement\")?\n\n .to_selector(parser, \"replacement\", false)?;\n\n Ok(Extender::replace(selector.0, source.0, target.0, args.span())?.to_sass_list())\n\n}\n\n\n", "file_path": "src/builtin/selector.rs", "rank": 64, "score": 126583.73620938795 }, { "content": "fn str_slice(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(3)?;\n\n let (string, quotes) = match parser.arg(&mut args, 0, \"string\")? {\n\n Value::String(s, q) => (s, q),\n\n v => {\n\n return Err((\n\n format!(\n\n \"$string: {} is not a string.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n let str_len = string.chars().count();\n\n let start = match parser.arg(&mut args, 1, \"start-at\")? {\n\n Value::Dimension(n, Unit::None) if n.is_decimal() => {\n\n return Err((format!(\"{} is not an int.\", n), args.span()).into())\n\n }\n", "file_path": "src/builtin/string.rs", "rank": 65, "score": 126583.73620938795 }, { "content": "fn map_remove(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n let mut map = match parser.arg(&mut args, 0, \"map\")? {\n\n Value::Map(m) => m,\n\n Value::List(v, ..) if v.is_empty() => SassMap::new(),\n\n v => {\n\n return Err((\n\n format!(\"$map: {} is not a map.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n let keys = parser.variadic_args(args)?;\n\n for key in keys {\n\n map.remove(&key);\n\n }\n\n Ok(Value::Map(map))\n\n}\n\n\n\npub(crate) fn declare(f: &mut GlobalFunctionMap) {\n\n f.insert(\"map-get\", Builtin::new(map_get));\n\n f.insert(\"map-has-key\", Builtin::new(map_has_key));\n\n f.insert(\"map-keys\", Builtin::new(map_keys));\n\n f.insert(\"map-values\", Builtin::new(map_values));\n\n f.insert(\"map-merge\", Builtin::new(map_merge));\n\n f.insert(\"map-remove\", Builtin::new(map_remove));\n\n}\n", "file_path": "src/builtin/map.rs", "rank": 66, "score": 126583.73620938795 }, { "content": "fn to_upper_case(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"string\")? {\n\n Value::String(mut i, q) => {\n\n i.make_ascii_uppercase();\n\n Ok(Value::String(i, q))\n\n }\n\n v => Err((\n\n format!(\n\n \"$string: {} is not a string.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/string.rs", "rank": 67, "score": 126583.73620938795 }, { "content": "fn str_length(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"string\")? {\n\n Value::String(i, _) => Ok(Value::Dimension(\n\n Number::from(i.chars().count()),\n\n Unit::None,\n\n )),\n\n v => Err((\n\n format!(\n\n \"$string: {} is not a string.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/string.rs", "rank": 68, "score": 126583.73620938795 }, { "content": "fn green(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => Ok(Value::Dimension(c.green(), Unit::None)),\n\n v => Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/color/rgb.rs", "rank": 69, "score": 126583.73620938795 }, { "content": "fn str_insert(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(3)?;\n\n let (s1, quotes) = match parser.arg(&mut args, 0, \"string\")? {\n\n Value::String(i, q) => (i, q),\n\n v => {\n\n return Err((\n\n format!(\n\n \"$string: {} is not a string.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n\n\n let substr = match parser.arg(&mut args, 1, \"insert\")? {\n\n Value::String(i, _) => i,\n\n v => {\n\n return Err((\n", "file_path": "src/builtin/string.rs", "rank": 70, "score": 126583.73620938795 }, { "content": "fn opacity(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => Ok(Value::Dimension(c.alpha(), Unit::None)),\n\n Value::Dimension(num, unit) => Ok(Value::String(\n\n format!(\"opacity({}{})\", num, unit),\n\n QuoteKind::None,\n\n )),\n\n v => Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/color/opacity.rs", "rank": 71, "score": 126583.73620938795 }, { "content": "// todo: refactor into rgb and hsl?\n\nfn scale_color(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n fn scale(val: Number, by: Number, max: Number) -> Number {\n\n if by.is_zero() {\n\n return val;\n\n }\n\n val.clone() + (if by.is_positive() { max - val } else { val }) * by\n\n }\n\n\n\n let span = args.span();\n\n let color = match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => c,\n\n v => {\n\n return Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(span)?),\n\n span,\n\n )\n\n .into())\n\n }\n\n };\n\n\n", "file_path": "src/builtin/color/other.rs", "rank": 72, "score": 126583.73620938795 }, { "content": "fn simple_selectors(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n // todo: Value::to_compound_selector\n\n let selector = parser\n\n .arg(&mut args, 0, \"selector\")?\n\n .to_selector(parser, \"selector\", false)?;\n\n\n\n if selector.0.components.len() != 1 {\n\n return Err((\"$selector: expected selector.\", args.span()).into());\n\n }\n\n\n\n let compound = if let Some(ComplexSelectorComponent::Compound(compound)) =\n\n selector.0.components[0].components.get(0).cloned()\n\n {\n\n compound\n\n } else {\n\n todo!()\n\n };\n\n\n\n Ok(Value::List(\n\n compound\n\n .components\n\n .into_iter()\n\n .map(|simple| Value::String(simple.to_string(), QuoteKind::None))\n\n .collect(),\n\n ListSeparator::Comma,\n\n Brackets::None,\n\n ))\n\n}\n\n\n", "file_path": "src/builtin/selector.rs", "rank": 73, "score": 126583.73620938795 }, { "content": "fn mix(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(3)?;\n\n let color1 = match parser.arg(&mut args, 0, \"color1\")? {\n\n Value::Color(c) => c,\n\n v => {\n\n return Err((\n\n format!(\"$color1: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n\n\n let color2 = match parser.arg(&mut args, 1, \"color2\")? {\n\n Value::Color(c) => c,\n\n v => {\n\n return Err((\n\n format!(\"$color2: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n", "file_path": "src/builtin/color/rgb.rs", "rank": 74, "score": 126583.73620938795 }, { "content": "fn alpha(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => Ok(Value::Dimension(c.alpha(), Unit::None)),\n\n v => Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/color/opacity.rs", "rank": 75, "score": 126583.73620938795 }, { "content": "fn map_has_key(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let key = parser.arg(&mut args, 1, \"key\")?;\n\n let map = match parser.arg(&mut args, 0, \"map\")? {\n\n Value::Map(m) => m,\n\n Value::List(v, ..) if v.is_empty() => SassMap::new(),\n\n v => {\n\n return Err((\n\n format!(\"$map: {} is not a map.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n Ok(Value::bool(map.get(&key, args.span(), parser)?.is_some()))\n\n}\n\n\n", "file_path": "src/builtin/map.rs", "rank": 76, "score": 126583.73620938795 }, { "content": "fn fade_in(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let color = match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => c,\n\n v => {\n\n return Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n let amount = match parser.arg(&mut args, 1, \"amount\")? {\n\n Value::Dimension(n, u) => bound!(args, \"amount\", n, u, 0, 1),\n\n v => {\n\n return Err((\n\n format!(\n\n \"$amount: {} is not a number.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n Ok(Value::Color(Box::new(color.fade_in(amount))))\n\n}\n\n\n", "file_path": "src/builtin/color/opacity.rs", "rank": 77, "score": 126583.73620938795 }, { "content": "fn map_keys(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n let map = match parser.arg(&mut args, 0, \"map\")? {\n\n Value::Map(m) => m,\n\n Value::List(v, ..) if v.is_empty() => SassMap::new(),\n\n v => {\n\n return Err((\n\n format!(\"$map: {} is not a map.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n Ok(Value::List(\n\n map.keys(),\n\n ListSeparator::Comma,\n\n Brackets::None,\n\n ))\n\n}\n\n\n", "file_path": "src/builtin/map.rs", "rank": 78, "score": 126583.73620938795 }, { "content": "fn adjust_color(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n let color = match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => c,\n\n v => {\n\n return Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n\n\n opt_rgba!(args, alpha, \"alpha\", -1, 1, parser);\n\n opt_rgba!(args, red, \"red\", -255, 255, parser);\n\n opt_rgba!(args, green, \"green\", -255, 255, parser);\n\n opt_rgba!(args, blue, \"blue\", -255, 255, parser);\n\n\n\n if red.is_some() || green.is_some() || blue.is_some() {\n\n return Ok(Value::Color(Box::new(Color::from_rgba(\n\n color.red() + red.unwrap_or_else(Number::zero),\n", "file_path": "src/builtin/color/other.rs", "rank": 79, "score": 126583.73620938795 }, { "content": "fn hue(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => Ok(Value::Dimension(c.hue(), Unit::Deg)),\n\n v => Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/color/hsl.rs", "rank": 80, "score": 126583.73620938795 }, { "content": "fn red(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => Ok(Value::Dimension(c.red(), Unit::None)),\n\n v => Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/color/rgb.rs", "rank": 81, "score": 126583.73620938795 }, { "content": "fn map_get(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let key = parser.arg(&mut args, 1, \"key\")?;\n\n let map = match parser.arg(&mut args, 0, \"map\")? {\n\n Value::Map(m) => m,\n\n Value::List(v, ..) if v.is_empty() => SassMap::new(),\n\n v => {\n\n return Err((\n\n format!(\"$map: {} is not a map.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n Ok(map.get(&key, args.span(), parser)?.unwrap_or(Value::Null))\n\n}\n\n\n", "file_path": "src/builtin/map.rs", "rank": 82, "score": 126583.73620938795 }, { "content": "fn list_separator(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n Ok(Value::String(\n\n match parser.arg(&mut args, 0, \"list\")? {\n\n Value::List(_, sep, ..) => sep.name(),\n\n _ => ListSeparator::Space.name(),\n\n }\n\n .to_owned(),\n\n QuoteKind::None,\n\n ))\n\n}\n\n\n", "file_path": "src/builtin/list.rs", "rank": 83, "score": 126583.73620938795 }, { "content": "fn lightness(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => Ok(Value::Dimension(c.lightness(), Unit::Percent)),\n\n v => Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into()),\n\n }\n\n}\n\n\n", "file_path": "src/builtin/color/hsl.rs", "rank": 84, "score": 126583.73620938795 }, { "content": "fn transparentize(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let color = match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => c,\n\n v => {\n\n return Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n let amount = match parser.arg(&mut args, 1, \"amount\")? {\n\n Value::Dimension(n, u) => bound!(args, \"amount\", n, u, 0, 1),\n\n v => {\n\n return Err((\n\n format!(\n\n \"$amount: {} is not a number.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n Ok(Value::Color(Box::new(color.fade_out(amount))))\n\n}\n\n\n", "file_path": "src/builtin/color/opacity.rs", "rank": 85, "score": 126583.73620938795 }, { "content": "fn desaturate(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let color = match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => c,\n\n v => {\n\n return Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n let amount = match parser.arg(&mut args, 1, \"amount\")? {\n\n Value::Dimension(n, u) => bound!(args, \"amount\", n, u, 0, 100) / Number::from(100),\n\n v => {\n\n return Err((\n\n format!(\n\n \"$amount: {} is not a number.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n Ok(Value::Color(Box::new(color.desaturate(amount))))\n\n}\n\n\n", "file_path": "src/builtin/color/hsl.rs", "rank": 86, "score": 126583.73620938795 }, { "content": "fn grayscale(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n let color = match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => c,\n\n Value::Dimension(n, u) => {\n\n return Ok(Value::String(\n\n format!(\"grayscale({}{})\", n, u),\n\n QuoteKind::None,\n\n ))\n\n }\n\n v => {\n\n return Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n Ok(Value::Color(Box::new(color.desaturate(Number::one()))))\n\n}\n\n\n", "file_path": "src/builtin/color/hsl.rs", "rank": 87, "score": 126583.73620938795 }, { "content": "fn invert(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let weight = match parser.default_arg(\n\n &mut args,\n\n 1,\n\n \"weight\",\n\n Value::Dimension(Number::from(100), Unit::Percent),\n\n )? {\n\n Value::Dimension(n, u) => bound!(args, \"weight\", n, u, 0, 100) / Number::from(100),\n\n v => {\n\n return Err((\n\n format!(\n\n \"$weight: {} is not a number.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n", "file_path": "src/builtin/color/hsl.rs", "rank": 88, "score": 126583.73620938795 }, { "content": "fn map_values(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n let map = match parser.arg(&mut args, 0, \"map\")? {\n\n Value::Map(m) => m,\n\n Value::List(v, ..) if v.is_empty() => SassMap::new(),\n\n v => {\n\n return Err((\n\n format!(\"$map: {} is not a map.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n Ok(Value::List(\n\n map.values(),\n\n ListSeparator::Comma,\n\n Brackets::None,\n\n ))\n\n}\n\n\n", "file_path": "src/builtin/map.rs", "rank": 89, "score": 126583.73620938795 }, { "content": "fn set_nth(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(3)?;\n\n let (mut list, sep, brackets) = match parser.arg(&mut args, 0, \"list\")? {\n\n Value::List(v, sep, b) => (v, sep, b),\n\n Value::Map(m) => (m.as_list(), ListSeparator::Comma, Brackets::None),\n\n v => (vec![v], ListSeparator::Space, Brackets::None),\n\n };\n\n let n = match parser.arg(&mut args, 1, \"n\")? {\n\n Value::Dimension(num, _) => num,\n\n v => {\n\n return Err((\n\n format!(\"$n: {} is not a number.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n\n\n if n.is_zero() {\n\n return Err((\"$n: List index may not be 0.\", args.span()).into());\n", "file_path": "src/builtin/list.rs", "rank": 90, "score": 126583.73620938795 }, { "content": "fn fade_out(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let color = match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => c,\n\n v => {\n\n return Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n let amount = match parser.arg(&mut args, 1, \"amount\")? {\n\n Value::Dimension(n, u) => bound!(args, \"amount\", n, u, 0, 1),\n\n v => {\n\n return Err((\n\n format!(\n\n \"$amount: {} is not a number.\",\n\n v.to_css_string(args.span())?\n\n ),\n", "file_path": "src/builtin/color/opacity.rs", "rank": 91, "score": 126583.73620938795 }, { "content": "fn darken(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let color = match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => c,\n\n v => {\n\n return Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n let amount = match parser.arg(&mut args, 1, \"amount\")? {\n\n Value::Dimension(n, u) => bound!(args, \"amount\", n, u, 0, 100) / Number::from(100),\n\n v => {\n\n return Err((\n\n format!(\n\n \"$amount: {} is not a number.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n Ok(Value::Color(Box::new(color.darken(amount))))\n\n}\n\n\n", "file_path": "src/builtin/color/hsl.rs", "rank": 92, "score": 126583.73620938795 }, { "content": "fn saturate(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n if args.len() == 1 {\n\n return Ok(Value::String(\n\n format!(\n\n \"saturate({})\",\n\n parser\n\n .arg(&mut args, 0, \"amount\")?\n\n .to_css_string(args.span())?\n\n ),\n\n QuoteKind::None,\n\n ));\n\n }\n\n\n\n let amount = match parser.arg(&mut args, 1, \"amount\")? {\n\n Value::Dimension(n, u) => bound!(args, \"amount\", n, u, 0, 100) / Number::from(100),\n\n v => {\n\n return Err((\n\n format!(\n\n \"$amount: {} is not a number.\",\n", "file_path": "src/builtin/color/hsl.rs", "rank": 93, "score": 126583.73620938795 }, { "content": "fn complement(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n let color = match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => c,\n\n v => {\n\n return Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n Ok(Value::Color(Box::new(color.complement())))\n\n}\n\n\n", "file_path": "src/builtin/color/hsl.rs", "rank": 94, "score": 126583.73620938795 }, { "content": "fn selector_extend(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(3)?;\n\n let selector = parser\n\n .arg(&mut args, 0, \"selector\")?\n\n .to_selector(parser, \"selector\", false)?;\n\n let target = parser\n\n .arg(&mut args, 1, \"extendee\")?\n\n .to_selector(parser, \"extendee\", false)?;\n\n let source = parser\n\n .arg(&mut args, 2, \"extender\")?\n\n .to_selector(parser, \"extender\", false)?;\n\n\n\n Ok(Extender::extend(selector.0, source.0, target.0, args.span())?.to_sass_list())\n\n}\n\n\n", "file_path": "src/builtin/selector.rs", "rank": 95, "score": 126583.73620938795 }, { "content": "fn ie_hex_str(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(1)?;\n\n let color = match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => c,\n\n v => {\n\n return Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n Ok(Value::String(color.to_ie_hex_str(), QuoteKind::None))\n\n}\n\n\n\npub(crate) fn declare(f: &mut GlobalFunctionMap) {\n\n f.insert(\"change-color\", Builtin::new(change_color));\n\n f.insert(\"adjust-color\", Builtin::new(adjust_color));\n\n f.insert(\"scale-color\", Builtin::new(scale_color));\n\n f.insert(\"ie-hex-str\", Builtin::new(ie_hex_str));\n\n}\n", "file_path": "src/builtin/color/other.rs", "rank": 96, "score": 125100.62930224853 }, { "content": "fn adjust_hue(mut args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {\n\n args.max_args(2)?;\n\n let color = match parser.arg(&mut args, 0, \"color\")? {\n\n Value::Color(c) => c,\n\n v => {\n\n return Err((\n\n format!(\"$color: {} is not a color.\", v.to_css_string(args.span())?),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n let degrees = match parser.arg(&mut args, 1, \"degrees\")? {\n\n Value::Dimension(n, _) => n,\n\n v => {\n\n return Err((\n\n format!(\n\n \"$degrees: {} is not a number.\",\n\n v.to_css_string(args.span())?\n\n ),\n\n args.span(),\n\n )\n\n .into())\n\n }\n\n };\n\n Ok(Value::Color(Box::new(color.adjust_hue(degrees))))\n\n}\n\n\n", "file_path": "src/builtin/color/hsl.rs", "rank": 97, "score": 125100.62930224853 }, { "content": "#[cfg(feature = \"wasm\")]\n\n#[wasm_bindgen]\n\npub fn from_string(p: String) -> std::result::Result<String, JsValue> {\n\n let mut map = CodeMap::new();\n\n let file = map.add_file(\"stdin\".into(), p);\n\n let empty_span = file.span.subspan(0, 0);\n\n\n\n let stmts = Parser {\n\n toks: &mut Lexer::new(&file)\n\n .collect::<Vec<Token>>()\n\n .into_iter()\n\n .peekmore(),\n\n map: &mut map,\n\n path: Path::new(\"\"),\n\n scopes: &mut NeverEmptyVec::new(Scope::new()),\n\n global_scope: &mut Scope::new(),\n\n super_selectors: &mut NeverEmptyVec::new(Selector::new(empty_span)),\n\n span_before: empty_span,\n\n content: &mut Vec::new(),\n\n flags: ContextFlags::empty(),\n\n at_root: true,\n\n at_root_has_selector: false,\n", "file_path": "src/lib.rs", "rank": 98, "score": 118747.00424334226 }, { "content": "#[test]\n\nfn imports_variable() {\n\n let input = \"@import \\\"imports_variable\\\";\\na {\\n color: $a;\\n}\";\n\n tempfile!(\"imports_variable\", \"$a: red;\");\n\n assert_eq!(\n\n \"a {\\n color: red;\\n}\\n\",\n\n &grass::from_string(input.to_string()).expect(input)\n\n );\n\n}\n\n\n", "file_path": "tests/imports.rs", "rank": 99, "score": 118480.35833264297 } ]
Rust
src/advisories/diags.rs
svenstaro/cargo-deny
4d7a236d6b4db82fc62052bc67dd808695498426
use crate::{ diag::{Check, Diag, Diagnostic, KrateCoord, Label, Pack, Severity}, Krate, LintLevel, }; use rustsec::advisory::{Id, Informational, Metadata, Versions}; fn get_notes_from_advisory(advisory: &Metadata) -> Vec<String> { let mut n = vec![format!("ID: {}", advisory.id)]; if let Some(url) = advisory.id.url() { n.push(format!("Advisory: {}", &url)); } n.push(advisory.description.clone()); if let Some(ref url) = advisory.url { n.push(format!("Announcement: {}", url)); } n } impl<'a> crate::CheckCtx<'a, super::cfg::ValidConfig> { pub(crate) fn diag_for_advisory<F>( &self, krate: &crate::Krate, krate_index: krates::NodeId, advisory: &Metadata, versions: Option<&Versions>, mut on_ignore: F, ) -> Pack where F: FnMut(usize), { #[derive(Clone, Copy)] enum AdvisoryType { Vulnerability, Notice, Unmaintained, Unsound, } let (severity, ty) = { let (lint_level, msg) = match &advisory.informational { None => (self.cfg.vulnerability, AdvisoryType::Vulnerability), Some(info) => match info { Informational::Notice => (self.cfg.notice, AdvisoryType::Notice), Informational::Unmaintained => { (self.cfg.unmaintained, AdvisoryType::Unmaintained) } Informational::Unsound => (self.cfg.unsound, AdvisoryType::Unsound), Informational::Other(_) => { unreachable!("rustsec only returns these if we ask, and there are none at the moment to ask for"); } _ => unreachable!("unknown advisory type encountered"), }, }; let lint_level = if let Ok(index) = self .cfg .ignore .binary_search_by(|i| i.value.cmp(&advisory.id)) { on_ignore(index); LintLevel::Allow } else if let Some(severity_threshold) = self.cfg.severity_threshold { if let Some(advisory_severity) = advisory.cvss.as_ref().map(|cvss| cvss.severity()) { if advisory_severity < severity_threshold { LintLevel::Allow } else { lint_level } } else { lint_level } } else { lint_level }; ( match lint_level { LintLevel::Warn => Severity::Warning, LintLevel::Deny => Severity::Error, LintLevel::Allow => Severity::Help, }, msg, ) }; let mut notes = get_notes_from_advisory(advisory); if let Some(versions) = versions { if versions.patched().is_empty() { notes.push("Solution: No safe upgrade is available!".to_owned()); } else { notes.push(format!( "Solution: Upgrade to {}", versions .patched() .iter() .map(ToString::to_string) .collect::<Vec<_>>() .as_slice() .join(" OR ") )); } }; let mut pack = Pack::with_kid(Check::Advisories, krate.id.clone()); let (message, code) = match ty { AdvisoryType::Vulnerability => ("security vulnerability detected", "A001"), AdvisoryType::Notice => ("notice advisory detected", "A002"), AdvisoryType::Unmaintained => ("unmaintained advisory detected", "A003"), AdvisoryType::Unsound => ("unsound advisory detected", "A004"), }; let diag = pack.push( Diagnostic::new(severity) .with_message(advisory.title.clone()) .with_labels(vec![self .krate_spans .label_for_index(krate_index.index(), message)]) .with_code(code) .with_notes(notes), ); if self.serialize_extra { diag.extra = serde_json::to_value(&advisory) .ok() .map(|v| ("advisory", v)); } pack } pub(crate) fn diag_for_yanked( &self, krate: &crate::Krate, krate_index: krates::NodeId, ) -> Pack { let mut pack = Pack::with_kid(Check::Advisories, krate.id.clone()); pack.push( Diagnostic::new(match self.cfg.yanked.value { LintLevel::Allow => Severity::Help, LintLevel::Deny => Severity::Error, LintLevel::Warn => Severity::Warning, }) .with_message("detected yanked crate") .with_code("A005") .with_labels(vec![self .krate_spans .label_for_index(krate_index.index(), "yanked version")]), ); pack } pub(crate) fn diag_for_index_failure<D: std::fmt::Display>(&self, error: D) -> Pack { ( Check::Advisories, Diagnostic::new(Severity::Warning) .with_message(format!("unable to check for yanked crates: {}", error)) .with_code("A006") .with_labels(vec![Label::primary( self.cfg.file_id, self.cfg.yanked.span.clone(), ) .with_message("lint level defined here")]), ) .into() } pub(crate) fn diag_for_advisory_not_encountered( &self, not_hit: &crate::cfg::Spanned<Id>, ) -> Pack { ( Check::Advisories, Diagnostic::new(Severity::Warning) .with_message("advisory was not encountered") .with_code("A007") .with_labels(vec![Label::primary(self.cfg.file_id, not_hit.span.clone()) .with_message("no crate matched advisory criteria")]), ) .into() } pub(crate) fn diag_for_unknown_advisory(&self, unknown: &crate::cfg::Spanned<Id>) -> Pack { ( Check::Advisories, Diagnostic::new(Severity::Warning) .with_message("advisory not found in any advisory database") .with_code("A008") .with_labels(vec![Label::primary(self.cfg.file_id, unknown.span.clone()) .with_message("unknown advisory")]), ) .into() } pub(crate) fn diag_for_prerelease_skipped( &self, krate: &crate::Krate, krate_index: krates::NodeId, advisory: &Metadata, matched: &semver::VersionReq, ) -> Pack { let mut pack = Pack::with_kid(Check::Advisories, krate.id.clone()); let notes = { let mut n = vec![format!("ID: {}", advisory.id)]; if let Some(url) = advisory.id.url() { n.push(format!("Advisory: {}", &url)); } n.push(format!("Satisfied version requirement: {}", matched)); n }; pack.push( Diagnostic::new(Severity::Warning) .with_message( "advisory for a crate with a pre-release was skipped as it matched a patch", ) .with_code("A009") .with_notes(notes) .with_labels(vec![self .krate_spans .label_for_index(krate_index.index(), "pre-release crate")]), ); pack } } pub(crate) struct NoAvailablePatches<'a> { pub(crate) affected_krate_coord: KrateCoord, pub(crate) advisory: &'a Metadata, } impl<'a> From<NoAvailablePatches<'a>> for Diag { fn from(nap: NoAvailablePatches<'a>) -> Self { let notes = get_notes_from_advisory(nap.advisory); Diagnostic::new(Severity::Error) .with_message("advisory has no available patches") .with_code("AF001") .with_labels(vec![nap .affected_krate_coord .into_label() .with_message("affected crate")]) .with_notes(notes) .into() } } pub(crate) struct NoAvailablePatchedVersions<'a> { pub(crate) affected_krate_coord: KrateCoord, pub(crate) advisory: &'a Metadata, } impl<'a> From<NoAvailablePatchedVersions<'a>> for Diag { fn from(napv: NoAvailablePatchedVersions<'a>) -> Self { let notes = get_notes_from_advisory(napv.advisory); Diagnostic::new(Severity::Error) .with_message("affected crate has no available patched versions") .with_code("AF002") .with_labels(vec![napv .affected_krate_coord .into_label() .with_message("affected crate")]) .with_notes(notes) .into() } } pub(crate) struct UnableToFindMatchingVersion<'a> { pub(crate) parent_krate: &'a Krate, pub(crate) dep: &'a Krate, pub(crate) reason: super::fix::NoVersionReason, } impl<'a> From<UnableToFindMatchingVersion<'a>> for Diag { fn from(ufmv: UnableToFindMatchingVersion<'a>) -> Self { let mut diag: Diag = Diagnostic::new(Severity::Error) .with_message(format!( "unable to patch {} => {}: {}", ufmv.parent_krate, ufmv.dep.name, ufmv.reason )) .with_code("AF003") .into(); diag.kids.push(ufmv.dep.id.clone()); diag } } pub(crate) struct UnpatchableSource<'a> { pub(crate) parent_krate: &'a Krate, } impl<'a> From<UnpatchableSource<'a>> for Diag { fn from(us: UnpatchableSource<'a>) -> Self { let mut diag: Diag = Diagnostic::new(Severity::Error) .with_message(format!( "unable to patch '{}', not a 'registry' or 'local'", us.parent_krate )) .with_code("AF004") .into(); diag.kids.push(us.parent_krate.id.clone()); diag } } fn to_string<T: std::fmt::Display>(v: &[T]) -> String { let mut dv = String::with_capacity(64); for req in v { use std::fmt::Write; write!(&mut dv, "{}, ", req).expect("failed to write string"); } dv.truncate(dv.len() - 2); dv } pub(crate) struct IncompatibleLocalKrate<'a> { pub(crate) local_krate: &'a Krate, pub(crate) dep_req: &'a semver::VersionReq, pub(crate) dep: &'a Krate, pub(crate) required_versions: &'a [semver::Version], } impl<'a> From<IncompatibleLocalKrate<'a>> for Diag { fn from(ilk: IncompatibleLocalKrate<'a>) -> Self { let mut diag: Diag = Diagnostic::new(Severity::Warning) .with_message(format!( "local crate {} has a requirement of '{}' on '{}', which does not match any required version", ilk.local_krate, ilk.dep_req, ilk.dep.name, )) .with_notes(vec![format!("Required versions: [{}]", to_string(ilk.required_versions))]) .with_code("AF005") .into(); diag.kids.push(ilk.dep.id.clone()); diag } } pub(crate) struct NoNewerVersionAvailable<'a> { pub(crate) local_krate: &'a Krate, pub(crate) dep: &'a Krate, } impl<'a> From<NoNewerVersionAvailable<'a>> for Diag { fn from(nnva: NoNewerVersionAvailable<'a>) -> Self { Diagnostic::new(Severity::Warning) .with_message(format!( "unable to patch '{}' => '{}', no newer versions of '{}' are available", nnva.local_krate, nnva.dep, nnva.dep.name, )) .with_code("AF006") .into() } }
use crate::{ diag::{Check, Diag, Diagnostic, KrateCoord, Label, Pack, Severity}, Krate, LintLevel, }; use rustsec::advisory::{Id, Informational, Metadata, Versions}; fn get_notes_from_advisory(advisory: &Metadata) -> Vec<String> { let mut n = vec![format!("ID: {}", advisory.id)]; if let Some(url) = advisory.id.url() { n.push(format!("Advisory: {}", &url)); } n.push(advisory.description.clone()); if let Some(ref url) = advisory.url { n.push(format!("Announcement: {}", url)); } n } impl<'a> crate::CheckCtx<'a, super::cfg::ValidConfig> { pub(crate) fn diag_for_advisory<F>( &self, krate: &crate::Krate, krate_index: krates::NodeId, advisory: &Metadata, versions: Option<&Versions>, mut on_ignore: F, ) -> Pack where F: FnMut(usize), { #[derive(Clone, Copy)] enum AdvisoryType { Vulnerability, Notice, Unmaintained, Unsound, } let (severity, ty) = { let (lint_level, msg) = match &advisory.informational { None => (self.cfg.vulnerability, AdvisoryType::Vulnerability), Some(info) => match info { Informational::Notice => (self.cfg.notice, AdvisoryType::Notice), Informational::Unmaintained => { (self.cfg.unmaintained, AdvisoryType::Unmaintained) } Informational::Unsound => (self.cfg.unsound, AdvisoryType::Unsound), Informational::Other(_) => { unreachable!("rustsec only returns these if we ask, and there are none at the moment to ask for"); } _ => unreachable!("unknown advisory type encountered"), }, }; let lint_level = if let Ok(index) = self .cfg .ignore .binary_search_by(|i| i.value.cmp(&advisory.id)) { on_ignore(index); LintLevel::Allow } else if let Some(severity_threshold) = self.cfg.severity_threshold { if let Some(advisory_severity) = advisory.cvss.as_ref().map(|cvss| cvss.severity()) { if advisory_severity < severity_threshold { LintLevel::Allow } else { lint_level } } else { lint_level } } else { lint_level }; ( match lint_level { LintLevel::Warn => Severity::Warning, LintLevel::Deny => Severity::Error, LintLevel::Allow => Severity::Help, }, msg, ) }; let mut notes = get_notes_from_advisory(advisory); if let Some(versions) = versions { if versions.patched().is_empty() { notes.push("Solution: No safe upgrade is available!".to_owned()); } else { notes.push(format!( "Solution: Upgrade to {}", versions .patched() .iter() .map(ToString::to_string) .collect::<Vec<_>>() .as_slice() .join(" OR ") )); } }; let mut pack = Pack::with_kid(Check::Advisories, krate.id.clone()); let (message, code) = match ty { AdvisoryType::Vulnerability => ("security vulnerability detected", "A001"), AdvisoryType::Notice => ("notice advisory detected", "A002"), AdvisoryType::Unmaintained => ("unmaintained advisory detected", "A003"), AdvisoryType::Unsound => ("unsound advisory detected", "A004"), }; let diag = pack.push( Diagnostic::new(severity) .with_message(advisory.title.clone()) .with_labels(vec![self .krate_spans .label_for_index(krate_index.index(), message)]) .with_code(code) .with_notes(notes), ); if self.serialize_extra { diag.extra = serde_json::to_value(&advisory) .ok() .map(|v| ("advisory", v)); } pack } pub(crate) fn diag_for_yanked( &self, krate: &crate::Krate, krate_index: krates::NodeId, ) -> Pack { let mut pack = Pack::with_kid(Check::Advisories, krate.id.clone()); pack.push( Diagnostic::new(
) .with_message("detected yanked crate") .with_code("A005") .with_labels(vec![self .krate_spans .label_for_index(krate_index.index(), "yanked version")]), ); pack } pub(crate) fn diag_for_index_failure<D: std::fmt::Display>(&self, error: D) -> Pack { ( Check::Advisories, Diagnostic::new(Severity::Warning) .with_message(format!("unable to check for yanked crates: {}", error)) .with_code("A006") .with_labels(vec![Label::primary( self.cfg.file_id, self.cfg.yanked.span.clone(), ) .with_message("lint level defined here")]), ) .into() } pub(crate) fn diag_for_advisory_not_encountered( &self, not_hit: &crate::cfg::Spanned<Id>, ) -> Pack { ( Check::Advisories, Diagnostic::new(Severity::Warning) .with_message("advisory was not encountered") .with_code("A007") .with_labels(vec![Label::primary(self.cfg.file_id, not_hit.span.clone()) .with_message("no crate matched advisory criteria")]), ) .into() } pub(crate) fn diag_for_unknown_advisory(&self, unknown: &crate::cfg::Spanned<Id>) -> Pack { ( Check::Advisories, Diagnostic::new(Severity::Warning) .with_message("advisory not found in any advisory database") .with_code("A008") .with_labels(vec![Label::primary(self.cfg.file_id, unknown.span.clone()) .with_message("unknown advisory")]), ) .into() } pub(crate) fn diag_for_prerelease_skipped( &self, krate: &crate::Krate, krate_index: krates::NodeId, advisory: &Metadata, matched: &semver::VersionReq, ) -> Pack { let mut pack = Pack::with_kid(Check::Advisories, krate.id.clone()); let notes = { let mut n = vec![format!("ID: {}", advisory.id)]; if let Some(url) = advisory.id.url() { n.push(format!("Advisory: {}", &url)); } n.push(format!("Satisfied version requirement: {}", matched)); n }; pack.push( Diagnostic::new(Severity::Warning) .with_message( "advisory for a crate with a pre-release was skipped as it matched a patch", ) .with_code("A009") .with_notes(notes) .with_labels(vec![self .krate_spans .label_for_index(krate_index.index(), "pre-release crate")]), ); pack } } pub(crate) struct NoAvailablePatches<'a> { pub(crate) affected_krate_coord: KrateCoord, pub(crate) advisory: &'a Metadata, } impl<'a> From<NoAvailablePatches<'a>> for Diag { fn from(nap: NoAvailablePatches<'a>) -> Self { let notes = get_notes_from_advisory(nap.advisory); Diagnostic::new(Severity::Error) .with_message("advisory has no available patches") .with_code("AF001") .with_labels(vec![nap .affected_krate_coord .into_label() .with_message("affected crate")]) .with_notes(notes) .into() } } pub(crate) struct NoAvailablePatchedVersions<'a> { pub(crate) affected_krate_coord: KrateCoord, pub(crate) advisory: &'a Metadata, } impl<'a> From<NoAvailablePatchedVersions<'a>> for Diag { fn from(napv: NoAvailablePatchedVersions<'a>) -> Self { let notes = get_notes_from_advisory(napv.advisory); Diagnostic::new(Severity::Error) .with_message("affected crate has no available patched versions") .with_code("AF002") .with_labels(vec![napv .affected_krate_coord .into_label() .with_message("affected crate")]) .with_notes(notes) .into() } } pub(crate) struct UnableToFindMatchingVersion<'a> { pub(crate) parent_krate: &'a Krate, pub(crate) dep: &'a Krate, pub(crate) reason: super::fix::NoVersionReason, } impl<'a> From<UnableToFindMatchingVersion<'a>> for Diag { fn from(ufmv: UnableToFindMatchingVersion<'a>) -> Self { let mut diag: Diag = Diagnostic::new(Severity::Error) .with_message(format!( "unable to patch {} => {}: {}", ufmv.parent_krate, ufmv.dep.name, ufmv.reason )) .with_code("AF003") .into(); diag.kids.push(ufmv.dep.id.clone()); diag } } pub(crate) struct UnpatchableSource<'a> { pub(crate) parent_krate: &'a Krate, } impl<'a> From<UnpatchableSource<'a>> for Diag { fn from(us: UnpatchableSource<'a>) -> Self { let mut diag: Diag = Diagnostic::new(Severity::Error) .with_message(format!( "unable to patch '{}', not a 'registry' or 'local'", us.parent_krate )) .with_code("AF004") .into(); diag.kids.push(us.parent_krate.id.clone()); diag } } fn to_string<T: std::fmt::Display>(v: &[T]) -> String { let mut dv = String::with_capacity(64); for req in v { use std::fmt::Write; write!(&mut dv, "{}, ", req).expect("failed to write string"); } dv.truncate(dv.len() - 2); dv } pub(crate) struct IncompatibleLocalKrate<'a> { pub(crate) local_krate: &'a Krate, pub(crate) dep_req: &'a semver::VersionReq, pub(crate) dep: &'a Krate, pub(crate) required_versions: &'a [semver::Version], } impl<'a> From<IncompatibleLocalKrate<'a>> for Diag { fn from(ilk: IncompatibleLocalKrate<'a>) -> Self { let mut diag: Diag = Diagnostic::new(Severity::Warning) .with_message(format!( "local crate {} has a requirement of '{}' on '{}', which does not match any required version", ilk.local_krate, ilk.dep_req, ilk.dep.name, )) .with_notes(vec![format!("Required versions: [{}]", to_string(ilk.required_versions))]) .with_code("AF005") .into(); diag.kids.push(ilk.dep.id.clone()); diag } } pub(crate) struct NoNewerVersionAvailable<'a> { pub(crate) local_krate: &'a Krate, pub(crate) dep: &'a Krate, } impl<'a> From<NoNewerVersionAvailable<'a>> for Diag { fn from(nnva: NoNewerVersionAvailable<'a>) -> Self { Diagnostic::new(Severity::Warning) .with_message(format!( "unable to patch '{}' => '{}', no newer versions of '{}' are available", nnva.local_krate, nnva.dep, nnva.dep.name, )) .with_code("AF006") .into() } }
match self.cfg.yanked.value { LintLevel::Allow => Severity::Help, LintLevel::Deny => Severity::Error, LintLevel::Warn => Severity::Warning, }
if_condition
[ { "content": "#[inline]\n\nfn matches<'v>(arr: &'v [cfg::Skrate], details: &Krate) -> Option<Vec<ReqMatch<'v>>> {\n\n let matches: Vec<_> = arr\n\n .iter()\n\n .enumerate()\n\n .filter_map(|(index, req)| {\n\n if req.value.name == details.name\n\n && crate::match_req(&details.version, req.value.version.as_ref())\n\n {\n\n Some(ReqMatch { id: req, index })\n\n } else {\n\n None\n\n }\n\n })\n\n .collect();\n\n\n\n if matches.is_empty() {\n\n None\n\n } else {\n\n Some(matches)\n\n }\n\n}\n\n\n", "file_path": "src/bans.rs", "rank": 1, "score": 205723.29406221342 }, { "content": "fn iter_notes(diag: &serde_json::Value) -> Option<impl Iterator<Item = &str>> {\n\n diag.pointer(\"/fields/notes\")\n\n .and_then(|notes| notes.as_array())\n\n .map(|array| array.iter().filter_map(|s| s.as_str()))\n\n}\n\n\n", "file_path": "tests/advisories.rs", "rank": 2, "score": 189922.78553839342 }, { "content": "/// Convert an advisory url to a directory underneath a specified root\n\nfn url_to_path(mut db_path: PathBuf, url: &Url) -> Result<PathBuf, Error> {\n\n let (ident, _) = crate::index::url_to_local_dir(url.as_str())?;\n\n db_path.push(ident);\n\n\n\n Ok(db_path)\n\n}\n\n\n", "file_path": "src/advisories/helpers.rs", "rank": 3, "score": 185173.4584565478 }, { "content": "#[test]\n\n#[ignore]\n\nfn detects_unsound() {\n\n let TestCtx { dbs, lock, krates } = load();\n\n\n\n let cfg = \"unsound = 'warn'\";\n\n\n\n let diags = utils::gather_diagnostics::<cfg::Config, _, _>(\n\n krates,\n\n \"detects_unsound\",\n\n Some(cfg),\n\n None,\n\n |ctx, _, tx| {\n\n advisories::check(\n\n ctx,\n\n &dbs,\n\n lock,\n\n Option::<advisories::NoneReporter>::None,\n\n tx,\n\n );\n\n },\n\n )\n", "file_path": "tests/advisories.rs", "rank": 4, "score": 177587.13421362478 }, { "content": "#[test]\n\n#[ignore]\n\nfn detects_vulnerabilities() {\n\n let TestCtx { dbs, lock, krates } = load();\n\n\n\n let cfg = \"vulnerability = 'deny'\";\n\n\n\n let diags = utils::gather_diagnostics::<cfg::Config, _, _>(\n\n krates,\n\n \"detects_vulnerabilities\",\n\n Some(cfg),\n\n None,\n\n |ctx, _, tx| {\n\n advisories::check(\n\n ctx,\n\n &dbs,\n\n lock,\n\n Option::<advisories::NoneReporter>::None,\n\n tx,\n\n );\n\n },\n\n )\n", "file_path": "tests/advisories.rs", "rank": 5, "score": 177587.1342136248 }, { "content": "#[test]\n\n#[ignore]\n\nfn detects_unmaintained() {\n\n let TestCtx { dbs, lock, krates } = load();\n\n\n\n let cfg = \"unmaintained = 'warn'\";\n\n\n\n let diags = utils::gather_diagnostics::<cfg::Config, _, _>(\n\n krates,\n\n \"detects_unmaintained\",\n\n Some(cfg),\n\n None,\n\n |ctx, _, tx| {\n\n advisories::check(\n\n ctx,\n\n &dbs,\n\n lock,\n\n Option::<advisories::NoneReporter>::None,\n\n tx,\n\n );\n\n },\n\n )\n", "file_path": "tests/advisories.rs", "rank": 6, "score": 177587.13421362478 }, { "content": "fn get_org(url: &url::Url) -> Option<(OrgType, &str)> {\n\n url.domain().and_then(|domain| {\n\n let org_type = if domain.eq_ignore_ascii_case(\"github.com\") {\n\n OrgType::Github\n\n } else if domain.eq_ignore_ascii_case(\"gitlab.com\") {\n\n OrgType::Gitlab\n\n } else if domain.eq_ignore_ascii_case(\"bitbucket.org\") {\n\n OrgType::Bitbucket\n\n } else {\n\n return None;\n\n };\n\n\n\n url.path_segments()\n\n .and_then(|mut f| f.next())\n\n .map(|org| (org_type, org))\n\n })\n\n}\n", "file_path": "src/sources.rs", "rank": 7, "score": 158582.0810295852 }, { "content": "pub fn check(ctx: crate::CheckCtx<'_, ValidConfig>, mut sink: ErrorSink) {\n\n use bitvec::prelude::*;\n\n\n\n // early out if everything is allowed\n\n if ctx.cfg.unknown_registry == LintLevel::Allow && ctx.cfg.unknown_git == LintLevel::Allow {\n\n return;\n\n }\n\n\n\n // scan through each crate and check the source of it\n\n\n\n // keep track of which sources are actually encountered, so we can emit a\n\n // warning if the user has listed a source that no crates are actually using\n\n let mut source_hits: BitVec = BitVec::repeat(false, ctx.cfg.allowed_sources.len());\n\n let mut org_hits: BitVec = BitVec::repeat(false, ctx.cfg.allowed_orgs.len());\n\n\n\n let min_git_spec = ctx.cfg.required_git_spec.as_ref().map(|rgs| {\n\n (\n\n rgs.value,\n\n CfgCoord {\n\n span: rgs.span.clone(),\n", "file_path": "src/sources.rs", "rank": 8, "score": 153246.55440512166 }, { "content": "#[allow(clippy::reversed_empty_ranges)]\n\nfn yanked() -> Spanned<LintLevel> {\n\n Spanned::new(LintLevel::Warn, 0..0)\n\n}\n\n\n\n#[derive(Deserialize)]\n\n#[serde(rename_all = \"kebab-case\", deny_unknown_fields)]\n\npub struct Config {\n\n /// Path to the root directory where advisory databases are stored (default: $CARGO_HOME/advisory-dbs)\n\n pub db_path: Option<PathBuf>,\n\n /// URL to the advisory database's git repo (default: https://github.com/RustSec/advisory-db)\n\n pub db_url: Option<Spanned<String>>,\n\n /// List of urls to git repositories of different advisory databases.\n\n #[serde(default)]\n\n pub db_urls: Vec<Spanned<String>>,\n\n /// How to handle crates that have a security vulnerability\n\n #[serde(default = \"crate::lint_deny\")]\n\n pub vulnerability: LintLevel,\n\n /// How to handle crates that have been marked as unmaintained in an advisory database\n\n #[serde(default = \"crate::lint_warn\")]\n\n pub unmaintained: LintLevel,\n", "file_path": "src/advisories/cfg.rs", "rank": 9, "score": 150054.8485477282 }, { "content": "#[inline]\n\npub fn match_req(version: &Version, req: Option<&semver::VersionReq>) -> bool {\n\n req.map_or(true, |req| req.matches(version))\n\n}\n", "file_path": "src/lib.rs", "rank": 10, "score": 146142.6454824572 }, { "content": "#[test]\n\n#[ignore]\n\nfn detects_yanked() {\n\n // Force fetch the index just in case\n\n rustsec::registry::Index::fetch().unwrap();\n\n\n\n let TestCtx { dbs, lock, krates } = load();\n\n\n\n let cfg = \"yanked = 'deny'\n\n unmaintained = 'allow'\n\n vulnerability = 'allow'\n\n \";\n\n\n\n let diags = utils::gather_diagnostics::<cfg::Config, _, _>(\n\n krates,\n\n \"detects_yanked\",\n\n Some(cfg),\n\n None,\n\n |ctx, _, tx| {\n\n advisories::check(\n\n ctx,\n\n &dbs,\n", "file_path": "tests/advisories.rs", "rank": 11, "score": 138440.61796350067 }, { "content": "fn find_by_code<'a>(\n\n diags: &'a [serde_json::Value],\n\n code: &'_ str,\n\n) -> Option<&'a serde_json::Value> {\n\n diags.iter().find(|v| match iter_notes(v) {\n\n Some(mut notes) => notes.any(|note| note.contains(code)),\n\n None => false,\n\n })\n\n}\n\n\n", "file_path": "tests/advisories.rs", "rank": 12, "score": 136768.1777793898 }, { "content": "#[cfg(feature = \"standalone\")]\n\nfn get_metadata(opts: MetadataOptions) -> Result<krates::cm::Metadata, anyhow::Error> {\n\n use anyhow::Context;\n\n use cargo::{core, ops, util};\n\n\n\n let mut config = util::Config::default()?;\n\n\n\n config.configure(\n\n 0,\n\n true,\n\n None,\n\n opts.frozen,\n\n opts.locked,\n\n opts.offline,\n\n &None,\n\n &[],\n\n &[],\n\n )?;\n\n\n\n let mut manifest_path = opts.manifest_path;\n\n\n", "file_path": "src/cargo-deny/common.rs", "rank": 13, "score": 133523.07905245194 }, { "content": "type CsDiag = codespan_reporting::diagnostic::Diagnostic<FileId>;\n\n\n\npub struct Human<'a> {\n\n stream: term::termcolor::StandardStream,\n\n grapher: Option<diag::TextGrapher<'a>>,\n\n config: term::Config,\n\n}\n\n\n\npub enum StdioStream {\n\n //Out(std::io::Stdout),\n\n Err(std::io::Stderr),\n\n}\n\n\n\nimpl StdioStream {\n\n pub fn lock(&self) -> StdLock<'_> {\n\n match self {\n\n //Self::Out(o) => StdLock::Out(o.lock()),\n\n Self::Err(o) => StdLock::Err(o.lock()),\n\n }\n\n }\n\n}\n\n\n\npub struct Json<'a> {\n\n stream: StdioStream,\n\n grapher: Option<diag::ObjectGrapher<'a>>,\n\n}\n\n\n", "file_path": "src/cargo-deny/common.rs", "rank": 15, "score": 125083.78371657671 }, { "content": "fn load_db(db_url: &Url, root_db_path: PathBuf, fetch: Fetch) -> Result<Database, Error> {\n\n use rustsec::repository::git::Repository;\n\n let db_path = url_to_path(root_db_path, db_url)?;\n\n\n\n let db_repo = match fetch {\n\n Fetch::Allow => {\n\n debug!(\"Fetching advisory database from '{}'\", db_url);\n\n\n\n Repository::fetch(db_url.as_str(), &db_path, true /* ensure_fresh */)\n\n .context(\"failed to fetch advisory database\")?\n\n }\n\n Fetch::Disallow => {\n\n debug!(\"Opening advisory database at '{}'\", db_path.display());\n\n\n\n Repository::open(&db_path).context(\"failed to open advisory database\")?\n\n }\n\n };\n\n\n\n debug!(\"loading advisory database from {}\", db_path.display());\n\n\n\n let res = Database::load_from_repo(&db_repo).context(\"failed to load advisory database\");\n\n\n\n debug!(\n\n \"finished loading advisory database from {}\",\n\n db_path.display()\n\n );\n\n\n\n res\n\n}\n\n\n", "file_path": "src/advisories/helpers.rs", "rank": 16, "score": 119428.09316126797 }, { "content": "pub fn cmd(args: Args, ctx: crate::common::KrateContext) -> Result<(), Error> {\n\n let cfg_path = args.config.unwrap_or_else(|| PathBuf::from(\"deny.toml\"));\n\n let cfg_path = ctx\n\n .get_config_path(Some(cfg_path))\n\n .context(\"unable to get full path to config\")?;\n\n\n\n // make sure the file does not exist yet\n\n ensure!(\n\n std::fs::metadata(&cfg_path).is_err(),\n\n \"unable to initialize cargo-deny config: '{}' already exists\",\n\n cfg_path.display(),\n\n );\n\n\n\n // make sure the path does not terminate in '..'; we need a file name.\n\n ensure!(\n\n cfg_path.file_name().is_some(),\n\n \"unable to create cargo-deny config: '{}' has an invalid filename\",\n\n cfg_path.display(),\n\n );\n\n\n\n std::fs::write(&cfg_path, CONTENTS).context(\"unable to write config file\")?;\n\n log::info!(\"saved config file to: {}\", cfg_path.display());\n\n\n\n Ok(())\n\n}\n", "file_path": "src/cargo-deny/init.rs", "rank": 17, "score": 114922.30095343094 }, { "content": "#[allow(clippy::trivially_copy_pass_by_ref)]\n\nfn is_false(v: &bool) -> bool {\n\n !v\n\n}\n\n\n", "file_path": "src/diag/obj_grapher.rs", "rank": 18, "score": 112505.24301459652 }, { "content": "pub fn cs_diag_to_json(diag: CsDiag, files: &Files) -> serde_json::Value {\n\n let mut val = serde_json::json!({\n\n \"type\": \"diagnostic\",\n\n \"fields\": {\n\n \"severity\": match diag.severity {\n\n Severity::Error => \"error\",\n\n Severity::Warning => \"warning\",\n\n Severity::Note => \"note\",\n\n Severity::Help => \"help\",\n\n Severity::Bug => \"bug\",\n\n },\n\n \"message\": diag.message,\n\n },\n\n });\n\n\n\n {\n\n let obj = val.as_object_mut().unwrap();\n\n let obj = obj.get_mut(\"fields\").unwrap().as_object_mut().unwrap();\n\n\n\n if let Some(code) = diag.code {\n", "file_path": "src/diag/obj_grapher.rs", "rank": 19, "score": 108804.36967005517 }, { "content": "fn is_normal(v: &'static str) -> bool {\n\n v.is_empty()\n\n}\n\n\n", "file_path": "src/diag/obj_grapher.rs", "rank": 20, "score": 107731.47256540836 }, { "content": "fn write_min_stats(mut summary: &mut String, stats: &AllStats, color: bool) {\n\n let mut print_stats = |check: &str, stats: Option<&Stats>| {\n\n use std::fmt::Write;\n\n\n\n if let Some(stats) = stats {\n\n write!(&mut summary, \"{} \", check).unwrap();\n\n\n\n if color {\n\n write!(\n\n &mut summary,\n\n \"{}, \",\n\n if stats.errors > 0 {\n\n ansi_term::Color::Red.paint(\"FAILED\")\n\n } else {\n\n ansi_term::Color::Green.paint(\"ok\")\n\n }\n\n )\n\n .unwrap();\n\n } else {\n\n write!(\n", "file_path": "src/cargo-deny/stats.rs", "rank": 21, "score": 107542.62868082646 }, { "content": "#[allow(clippy::ptr_arg)]\n\nfn is_empty(v: &Vec<GraphNode>) -> bool {\n\n v.is_empty()\n\n}\n\n\n\n/// As with the textgrapher, only crates inclusion graphs, but in the form of\n\n/// a serializable object rather than a text string\n\npub struct ObjectGrapher<'a> {\n\n krates: &'a Krates,\n\n}\n\n\n\nimpl<'a> ObjectGrapher<'a> {\n\n pub fn new(krates: &'a Krates) -> Self {\n\n Self { krates }\n\n }\n\n\n\n pub fn write_graph(&self, id: &Kid) -> Result<GraphNode, Error> {\n\n let mut visited = HashSet::new();\n\n\n\n let node_id = self.krates.nid_for_kid(id).context(\"unable to find node\")?;\n\n let krate = &self.krates[node_id];\n", "file_path": "src/diag/obj_grapher.rs", "rank": 22, "score": 105686.08256032167 }, { "content": "enum PackFileData {\n\n Good(LicenseFile),\n\n Bad(std::io::Error),\n\n}\n\n\n", "file_path": "src/licenses/gather.rs", "rank": 23, "score": 103729.71389750148 }, { "content": "pub fn load_lockfile(path: &krates::Utf8Path) -> Result<Lockfile, Error> {\n\n let mut lockfile = Lockfile::load(path)?;\n\n\n\n // Remove the metadata as it is irrelevant\n\n lockfile.metadata = Default::default();\n\n\n\n Ok(lockfile)\n\n}\n\n\n\npub struct PrunedLockfile(pub(crate) Lockfile);\n\n\n\nimpl PrunedLockfile {\n\n pub fn prune(mut lf: Lockfile, krates: &Krates) -> Self {\n\n // Remove any packages from the rustsec's view of the lockfile that we\n\n // have filtered out of the graph we are actually checking\n\n lf.packages\n\n .retain(|pkg| krate_for_pkg(krates, pkg).is_some());\n\n\n\n Self(lf)\n\n }\n", "file_path": "src/advisories/helpers.rs", "rank": 24, "score": 102017.53761896666 }, { "content": "pub fn diag_to_json(\n\n diag: Diag,\n\n files: &Files,\n\n grapher: Option<&ObjectGrapher<'_>>,\n\n) -> serde_json::Value {\n\n let mut to_print = cs_diag_to_json(diag.diag, files);\n\n\n\n let obj = to_print.as_object_mut().unwrap();\n\n let fields = obj.get_mut(\"fields\").unwrap().as_object_mut().unwrap();\n\n\n\n if let Some(grapher) = &grapher {\n\n let mut graphs = Vec::new();\n\n for kid in diag.kids {\n\n if let Ok(graph) = grapher.write_graph(&kid) {\n\n if let Ok(sgraph) = serde_json::value::to_value(graph) {\n\n graphs.push(sgraph);\n\n }\n\n }\n\n }\n\n\n\n fields.insert(\"graphs\".to_owned(), serde_json::Value::Array(graphs));\n\n }\n\n\n\n if let Some((key, val)) = diag.extra {\n\n fields.insert(key.to_owned(), val);\n\n }\n\n\n\n to_print\n\n}\n", "file_path": "src/diag/obj_grapher.rs", "rank": 25, "score": 100630.93440271188 }, { "content": "pub fn safety_first(v: u32) -> u32 {\n\n if v != 1 {\n\n dangerous_dep::panic_if_one(v)\n\n } else {\n\n v\n\n }\n\n}\n", "file_path": "tests/test_data/allow_wrappers/safe-wrapper/src/lib.rs", "rank": 26, "score": 97644.26826596682 }, { "content": "#[test]\n\n#[ignore]\n\nfn downgrades_lint_levels() {\n\n let TestCtx { dbs, lock, krates } = load();\n\n\n\n let cfg = \"unmaintained = 'warn'\n\n ignore = ['RUSTSEC-2016-0004', 'RUSTSEC-2019-0001']\";\n\n\n\n let diags = utils::gather_diagnostics::<cfg::Config, _, _>(\n\n krates,\n\n \"downgrades_lint_levels\",\n\n Some(cfg),\n\n None,\n\n |ctx, _, tx| {\n\n advisories::check(\n\n ctx,\n\n &dbs,\n\n lock,\n\n Option::<advisories::NoneReporter>::None,\n\n tx,\n\n );\n\n },\n", "file_path": "tests/advisories.rs", "rank": 27, "score": 96666.53423911188 }, { "content": "fn main() {\n\n println!(\"Hello, world!\");\n\n}\n", "file_path": "examples/06_advisories/src/main.rs", "rank": 28, "score": 96661.78254619331 }, { "content": "#[inline]\n\nfn iter_clarifications<'a>(\n\n all: &'a [ValidClarification],\n\n krate: &'a Krate,\n\n) -> impl Iterator<Item = &'a ValidClarification> {\n\n all.iter().filter(move |vc| {\n\n if vc.name == krate.name {\n\n return crate::match_req(&krate.version, vc.version.as_ref());\n\n }\n\n\n\n false\n\n })\n\n}\n\n\n\nimpl fmt::Debug for FileSource {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.debug_struct(\"FileSource\")\n\n .field(\"path\", &self.path)\n\n .field(\"hash\", &format_args!(\"{:#x}\", self.hash))\n\n .finish()\n\n }\n\n}\n\n\n", "file_path": "src/licenses/gather.rs", "rank": 29, "score": 95944.97511605843 }, { "content": "pub fn gather_diagnostics<\n\n C: serde::de::DeserializeOwned + Default + cargo_deny::UnvalidatedConfig<ValidCfg = VC>,\n\n VC: Send,\n\n R: FnOnce(CheckCtx<'_, VC>, CargoSpans, ErrorSink) + Send,\n\n>(\n\n krates: cargo_deny::Krates,\n\n test_name: &str,\n\n cfg: Option<&str>,\n\n timeout: Option<std::time::Duration>,\n\n runner: R,\n\n) -> Result<Vec<serde_json::Value>, Error> {\n\n let (spans, content, hashmap) = KrateSpans::synthesize(&krates);\n\n let mut files = Files::new();\n\n\n\n let spans_id = files.add(format!(\"{}/Cargo.lock\", test_name), content);\n\n\n\n let spans = KrateSpans::with_spans(spans, spans_id);\n\n\n\n let (config, cfg_id) = match cfg {\n\n Some(cfg) => {\n", "file_path": "tests/utils.rs", "rank": 30, "score": 95935.61825044896 }, { "content": "#[allow(clippy::too_many_arguments)]\n\nfn print_diagnostics(\n\n rx: crossbeam::channel::Receiver<cargo_deny::diag::Pack>,\n\n log_ctx: crate::common::LogContext,\n\n krates: Option<&cargo_deny::Krates>,\n\n files: Files,\n\n stats: &mut AllStats,\n\n) {\n\n use cargo_deny::diag::Check;\n\n\n\n match crate::common::DiagPrinter::new(log_ctx, krates) {\n\n Some(printer) => {\n\n for pack in rx {\n\n let mut lock = printer.lock();\n\n\n\n let check_stats = match pack.check {\n\n Check::Advisories => stats.advisories.as_mut().unwrap(),\n\n Check::Bans => stats.bans.as_mut().unwrap(),\n\n Check::Licenses => stats.licenses.as_mut().unwrap(),\n\n Check::Sources => stats.sources.as_mut().unwrap(),\n\n };\n", "file_path": "src/cargo-deny/check.rs", "rank": 31, "score": 95093.04643161871 }, { "content": "fn load() -> TestCtx {\n\n let md: krates::cm::Metadata = serde_json::from_str(\n\n &std::fs::read_to_string(\"tests/test_data/advisories/06_advisories.json\").unwrap(),\n\n )\n\n .unwrap();\n\n\n\n let krates: Krates = krates::Builder::new()\n\n .build_with_metadata(md, krates::NoneFilter)\n\n .unwrap();\n\n\n\n let lock = advisories::load_lockfile(krates::Utf8Path::new(\n\n \"tests/test_data/advisories/06_Cargo.lock\",\n\n ))\n\n .unwrap();\n\n\n\n let db = {\n\n let tmp = tempfile::tempdir().unwrap();\n\n advisories::DbSet::load(Some(tmp), vec![], advisories::Fetch::Allow).unwrap()\n\n };\n\n\n\n let lockfile = advisories::PrunedLockfile::prune(lock, &krates);\n\n\n\n TestCtx {\n\n dbs: db,\n\n lock: lockfile,\n\n krates,\n\n }\n\n}\n\n\n", "file_path": "tests/advisories.rs", "rank": 32, "score": 94994.094055001 }, { "content": "/// Check crates against the advisory database to detect vulnerabilities or\n\n/// unmaintained crates\n\npub fn check<R>(\n\n ctx: crate::CheckCtx<'_, cfg::ValidConfig>,\n\n advisory_dbs: &DbSet,\n\n lockfile: PrunedLockfile,\n\n audit_compatible_reporter: Option<R>,\n\n mut sink: diag::ErrorSink,\n\n) where\n\n R: AuditReporter,\n\n{\n\n use rustsec::{advisory::Metadata, advisory::Versions, package::Package};\n\n\n\n let emit_audit_compatible_reports = audit_compatible_reporter.is_some();\n\n\n\n let (report, yanked) = rayon::join(\n\n || Report::generate(advisory_dbs, &lockfile, emit_audit_compatible_reports),\n\n || {\n\n let index = rustsec::registry::Index::open()?;\n\n let mut yanked = Vec::new();\n\n\n\n for package in &lockfile.0.packages {\n", "file_path": "src/advisories.rs", "rank": 33, "score": 93576.17494089318 }, { "content": "fn merge_dependencies(old_dep: &mut toml_edit::Item, new: &dep::Dependency) {\n\n assert!(!old_dep.is_none());\n\n\n\n let new_toml = new.to_toml().1;\n\n\n\n if str_or_1_len_table(old_dep) {\n\n // The old dependency is just a version/git/path. We are safe to overwrite.\n\n *old_dep = new_toml;\n\n } else if old_dep.is_table_like() {\n\n for key in &[\"version\", \"path\", \"git\"] {\n\n // remove this key/value pairs\n\n old_dep[key] = toml_edit::Item::None;\n\n }\n\n if let Some(name) = new_toml.as_str() {\n\n old_dep[\"version\"] = toml_edit::value(name);\n\n } else {\n\n merge_inline_table(old_dep, &new_toml);\n\n }\n\n } else {\n\n unreachable!(\"Invalid old dependency type\");\n", "file_path": "src/manifest.rs", "rank": 34, "score": 92998.83524258411 }, { "content": "fn color_to_choice(color: crate::Color, stream: atty::Stream) -> ColorChoice {\n\n match color {\n\n crate::Color::Auto => {\n\n // The termcolor crate doesn't check the stream to see if it's a TTY\n\n // which doesn't really fit with how the rest of the coloring works\n\n if atty::is(stream) {\n\n ColorChoice::Auto\n\n } else {\n\n ColorChoice::Never\n\n }\n\n }\n\n crate::Color::Always => ColorChoice::Always,\n\n crate::Color::Never => ColorChoice::Never,\n\n }\n\n}\n\n\n", "file_path": "src/cargo-deny/common.rs", "rank": 35, "score": 91575.76870739264 }, { "content": "fn write_full_stats(summary: &mut String, stats: &AllStats, color: bool) {\n\n let column = {\n\n let mut max = 0;\n\n let mut count = |check: &str, s: Option<&Stats>| {\n\n max = std::cmp::max(\n\n max,\n\n s.map_or(0, |s| {\n\n let status = if s.errors > 0 {\n\n \"FAILED\".len()\n\n } else {\n\n \"ok\".len()\n\n };\n\n\n\n status + check.len()\n\n }),\n\n );\n\n };\n\n\n\n count(\"advisories\", stats.advisories.as_ref());\n\n count(\"bans\", stats.bans.as_ref());\n", "file_path": "src/cargo-deny/stats.rs", "rank": 36, "score": 91451.16461166117 }, { "content": "fn merge_inline_table(old_dep: &mut toml_edit::Item, new: &toml_edit::Item) {\n\n for (k, v) in new\n\n .as_inline_table()\n\n .expect(\"expected an inline table\")\n\n .iter()\n\n {\n\n old_dep[k] = toml_edit::value(v.clone());\n\n }\n\n}\n\n\n", "file_path": "src/manifest.rs", "rank": 37, "score": 89983.31965850436 }, { "content": "fn crate_name_to_relative_path(crate_name: &str) -> Option<String> {\n\n if !crate_name.is_ascii() {\n\n return None;\n\n }\n\n\n\n let name_lower = crate_name.to_ascii_lowercase();\n\n let mut rel_path = String::with_capacity(crate_name.len() + 6);\n\n match name_lower.len() {\n\n 0 => return None,\n\n 1 => rel_path.push('1'),\n\n 2 => rel_path.push('2'),\n\n 3 => {\n\n rel_path.push('3');\n\n rel_path.push(std::path::MAIN_SEPARATOR);\n\n rel_path.push_str(&name_lower[0..1]);\n\n }\n\n _ => {\n\n rel_path.push_str(&name_lower[0..2]);\n\n rel_path.push(std::path::MAIN_SEPARATOR);\n\n rel_path.push_str(&name_lower[2..4]);\n\n }\n\n };\n\n rel_path.push(std::path::MAIN_SEPARATOR);\n\n rel_path.push_str(&name_lower);\n\n\n\n Some(rel_path)\n\n}\n\n\n", "file_path": "src/index/bare.rs", "rank": 38, "score": 88498.1968722721 }, { "content": "#[inline]\n\nfn default_allow_registry() -> Vec<Spanned<String>> {\n\n // This is always valid, so we don't have to worry about the span being fake,\n\n // this is actually a lie though because if we try to print this span it will\n\n // fail if it falls outside of the range of the config file, and even if it\n\n // doesn't will just point to whatever text happens to be there, so we instead\n\n // lie and just ignore it instead since a vast majority of usage should\n\n // use this source\n\n vec![Spanned::new(\n\n super::CRATES_IO_URL.to_owned(),\n\n 0..super::CRATES_IO_URL.len(),\n\n )]\n\n}\n\n\n\nimpl Default for Config {\n\n fn default() -> Self {\n\n Self {\n\n unknown_registry: LintLevel::Warn,\n\n unknown_git: LintLevel::Warn,\n\n allow_registry: default_allow_registry(),\n\n allow_git: Vec::new(),\n", "file_path": "src/sources/cfg.rs", "rank": 39, "score": 83370.35805245777 }, { "content": "pub fn get_test_data_krates(name: &str) -> Result<cargo_deny::Krates, Error> {\n\n let project_dir = std::path::Path::new(\"./tests/test_data\").join(name);\n\n\n\n let mut metadata_cmd = krates::Cmd::new();\n\n metadata_cmd.current_dir(&project_dir);\n\n\n\n krates::Builder::new()\n\n .build(metadata_cmd, krates::NoneFilter)\n\n .context(\"failed to build crate graph\")\n\n}\n\n\n", "file_path": "tests/utils.rs", "rank": 40, "score": 82740.4040276593 }, { "content": "pub fn log_level_to_severity(log_level: log::LevelFilter) -> Option<Severity> {\n\n match log_level {\n\n log::LevelFilter::Off => None,\n\n log::LevelFilter::Error => Some(Severity::Error),\n\n log::LevelFilter::Warn => Some(Severity::Warning),\n\n log::LevelFilter::Info => Some(Severity::Note),\n\n log::LevelFilter::Debug | log::LevelFilter::Trace => Some(Severity::Help),\n\n }\n\n}\n\n\n\nuse codespan_reporting::term::{self, termcolor::ColorChoice};\n\nuse std::io::Write;\n\n\n", "file_path": "src/cargo-deny/common.rs", "rank": 41, "score": 82132.74045266572 }, { "content": " let mut ignored: Vec<_> = self.ignore.into_iter().map(AdvisoryId::from).collect();\n\n ignored.sort();\n\n\n\n let mut db_urls: Vec<_> = self\n\n .db_urls\n\n .into_iter()\n\n .filter_map(|dburl| match crate::cfg::parse_url(cfg_file, dburl) {\n\n Ok(u) => Some(u),\n\n Err(diag) => {\n\n diags.push(diag);\n\n None\n\n }\n\n })\n\n .collect();\n\n\n\n if let Some(db_url) = self.db_url {\n\n diags.push(\n\n Diagnostic::warning()\n\n .with_message(\"'db_url' is deprecated, use 'db_urls' instead\")\n\n .with_labels(vec![Label::primary(cfg_file, db_url.span.clone())]),\n", "file_path": "src/advisories/cfg.rs", "rank": 60, "score": 79308.03834725125 }, { "content": " if url.value.scheme() != \"https\" {\n\n diags.push(\n\n Diagnostic::error()\n\n .with_message(\"advisory database url is not https\")\n\n .with_labels(vec![Label::secondary(cfg_file, url.span.clone())]),\n\n );\n\n }\n\n }\n\n\n\n ValidConfig {\n\n file_id: cfg_file,\n\n db_path: self.db_path,\n\n db_urls,\n\n ignore: ignored,\n\n vulnerability: self.vulnerability,\n\n unmaintained: self.unmaintained,\n\n unsound: self.unsound,\n\n yanked: self.yanked,\n\n notice: self.notice,\n\n severity_threshold: self.severity_threshold,\n", "file_path": "src/advisories/cfg.rs", "rank": 61, "score": 79305.15345822027 }, { "content": " fn default() -> Self {\n\n Self {\n\n db_path: None,\n\n db_url: None,\n\n db_urls: Vec::new(),\n\n ignore: Vec::new(),\n\n vulnerability: LintLevel::Deny,\n\n unmaintained: LintLevel::Warn,\n\n unsound: LintLevel::Warn,\n\n yanked: yanked(),\n\n notice: LintLevel::Warn,\n\n severity_threshold: None,\n\n }\n\n }\n\n}\n\n\n\nimpl crate::cfg::UnvalidatedConfig for Config {\n\n type ValidCfg = ValidConfig;\n\n\n\n fn validate(self, cfg_file: FileId, diags: &mut Vec<Diagnostic>) -> Self::ValidCfg {\n", "file_path": "src/advisories/cfg.rs", "rank": 62, "score": 79301.82623361245 }, { "content": " );\n\n\n\n match crate::cfg::parse_url(cfg_file, db_url) {\n\n Ok(url) => db_urls.push(url),\n\n Err(diag) => {\n\n diags.push(diag);\n\n }\n\n }\n\n }\n\n\n\n db_urls.sort();\n\n\n\n // Warn about duplicates before removing them so the user can cleanup their config\n\n if db_urls.len() > 1 {\n\n for window in db_urls.windows(2) {\n\n if window[0] == window[1] {\n\n diags.push(\n\n Diagnostic::warning()\n\n .with_message(\"duplicate advisory database url detected\")\n\n .with_labels(vec![\n", "file_path": "src/advisories/cfg.rs", "rank": 63, "score": 79292.87533538076 }, { "content": " }\n\n }\n\n}\n\n\n\npub(crate) type AdvisoryId = Spanned<advisory::Id>;\n\n\n\npub struct ValidConfig {\n\n pub file_id: FileId,\n\n pub db_path: Option<PathBuf>,\n\n pub db_urls: Vec<Spanned<Url>>,\n\n pub(crate) ignore: Vec<AdvisoryId>,\n\n pub vulnerability: LintLevel,\n\n pub unmaintained: LintLevel,\n\n pub unsound: LintLevel,\n\n pub yanked: Spanned<LintLevel>,\n\n pub notice: LintLevel,\n\n pub severity_threshold: Option<advisory::Severity>,\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/advisories/cfg.rs", "rank": 64, "score": 79287.75475109417 }, { "content": "mod test {\n\n use super::*;\n\n use crate::cfg::{test::*, Fake, UnvalidatedConfig};\n\n use std::borrow::Cow;\n\n\n\n #[test]\n\n fn works() {\n\n #[derive(Deserialize)]\n\n #[serde(deny_unknown_fields)]\n\n struct Advisories {\n\n advisories: Config,\n\n }\n\n\n\n let cd: ConfigData<Advisories> = load(\"tests/cfg/advisories.toml\");\n\n let mut diags = Vec::new();\n\n let validated = cd.config.advisories.validate(cd.id, &mut diags);\n\n assert!(\n\n !diags\n\n .iter()\n\n .any(|d| d.severity >= crate::diag::Severity::Error),\n", "file_path": "src/advisories/cfg.rs", "rank": 65, "score": 79286.09099265457 }, { "content": " /// How to handle crates that have been marked as unsound in an advisory database\n\n #[serde(default = \"crate::lint_warn\")]\n\n pub unsound: LintLevel,\n\n /// How to handle crates that have been yanked from eg crates.io\n\n #[serde(default = \"yanked\")]\n\n pub yanked: Spanned<LintLevel>,\n\n /// How to handle crates that have been marked with a notice in the advisory database\n\n #[serde(default = \"crate::lint_warn\")]\n\n pub notice: LintLevel,\n\n /// Ignore advisories for the given IDs\n\n #[serde(default)]\n\n pub ignore: Vec<Spanned<advisory::Id>>,\n\n /// CVSS Qualitative Severity Rating Scale threshold to alert at.\n\n ///\n\n /// Vulnerabilities with explicit CVSS info which have a severity below\n\n /// this threshold will be ignored.\n\n pub severity_threshold: Option<advisory::Severity>,\n\n}\n\n\n\nimpl Default for Config {\n", "file_path": "src/advisories/cfg.rs", "rank": 66, "score": 79284.45732814999 }, { "content": " Label::secondary(cfg_file, window[0].span.clone()),\n\n Label::secondary(cfg_file, window[1].span.clone()),\n\n ]),\n\n );\n\n }\n\n }\n\n }\n\n\n\n db_urls.dedup();\n\n\n\n // Require that each url has a valid domain name for when we splat it to a local path\n\n for url in &db_urls {\n\n if url.value.domain().is_none() {\n\n diags.push(\n\n Diagnostic::error()\n\n .with_message(\"advisory database url doesn't have a domain name\")\n\n .with_labels(vec![Label::secondary(cfg_file, url.span.clone())]),\n\n );\n\n }\n\n\n", "file_path": "src/advisories/cfg.rs", "rank": 67, "score": 79283.35655131047 }, { "content": "use crate::{\n\n diag::{Diagnostic, FileId, Label},\n\n LintLevel, Spanned,\n\n};\n\nuse rustsec::advisory;\n\nuse serde::Deserialize;\n\nuse std::path::PathBuf;\n\nuse url::Url;\n\n\n\n#[allow(clippy::reversed_empty_ranges)]\n", "file_path": "src/advisories/cfg.rs", "rank": 68, "score": 79280.49891591648 }, { "content": " \"{:#?}\",\n\n diags\n\n );\n\n\n\n assert_eq!(validated.file_id, cd.id);\n\n assert!(validated\n\n .db_path\n\n .iter()\n\n .map(|dp| dp.to_string_lossy())\n\n .eq(vec![Cow::Borrowed(\"~/.cargo/advisory-dbs\")]));\n\n assert!(validated.db_urls.iter().eq(vec![&Url::parse(\n\n \"https://github.com/RustSec/advisory-db\"\n\n )\n\n .unwrap()\n\n .fake()]));\n\n assert_eq!(validated.vulnerability, LintLevel::Deny);\n\n assert_eq!(validated.unmaintained, LintLevel::Warn);\n\n assert_eq!(validated.unsound, LintLevel::Warn);\n\n assert_eq!(validated.yanked, LintLevel::Warn);\n\n assert_eq!(validated.notice, LintLevel::Warn);\n", "file_path": "src/advisories/cfg.rs", "rank": 69, "score": 79277.8788445616 }, { "content": " assert_eq!(\n\n validated.ignore,\n\n vec![\"RUSTSEC-0000-0000\"\n\n .parse::<rustsec::advisory::Id>()\n\n .unwrap()]\n\n );\n\n assert_eq!(\n\n validated.severity_threshold,\n\n Some(rustsec::advisory::Severity::Medium)\n\n );\n\n }\n\n}\n", "file_path": "src/advisories/cfg.rs", "rank": 70, "score": 79265.53981594845 }, { "content": "fn get_file_source(path: Utf8PathBuf) -> PackFile {\n\n use std::io::BufRead;\n\n\n\n // Normalize on plain newlines to handle terrible Windows conventions\n\n let content = {\n\n let file = match std::fs::File::open(&path) {\n\n Ok(f) => f,\n\n Err(e) => {\n\n return PackFile {\n\n path,\n\n data: PackFileData::Bad(e),\n\n }\n\n }\n\n };\n\n\n\n let mut s =\n\n String::with_capacity(file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0));\n\n\n\n let mut br = std::io::BufReader::new(file);\n\n let mut min = 0;\n", "file_path": "src/licenses/gather.rs", "rank": 71, "score": 78605.1089146489 }, { "content": "pub fn panic_if_one(v: u32) -> u32 {\n\n if v == 1 {\n\n panic!(\"oops\");\n\n } else {\n\n v\n\n }\n\n}\n", "file_path": "tests/test_data/allow_wrappers/dangerous-dep/src/lib.rs", "rank": 72, "score": 68860.4813890428 }, { "content": "#[derive(StructOpt, Debug)]\n\nenum Command {\n\n /// Checks a project's crate graph\n\n #[structopt(name = \"check\")]\n\n Check(check::Args),\n\n /// Fetches remote data\n\n #[structopt(name = \"fetch\")]\n\n Fetch(fetch::Args),\n\n /// Attempts to fix security advisories by updating Cargo.toml manifests\n\n #[structopt(name = \"fix\")]\n\n Fix(fix::Args),\n\n /// Creates a cargo-deny config from a template\n\n #[structopt(name = \"init\")]\n\n Init(init::Args),\n\n /// Outputs a listing of all licenses and the crates that use them\n\n #[structopt(name = \"list\")]\n\n List(list::Args),\n\n}\n\n\n\n#[derive(StructOpt, Copy, Clone, Debug, PartialEq)]\n\npub enum Format {\n", "file_path": "src/cargo-deny/main.rs", "rank": 73, "score": 68507.87582163353 }, { "content": "#[derive(Debug, PartialEq, Eq, Clone)]\n\nenum DependencySource {\n\n Version {\n\n version: Option<String>,\n\n path: Option<String>,\n\n registry: Option<String>,\n\n },\n\n Git {\n\n repo: String,\n\n spec: Option<(GitSpec, String)>,\n\n },\n\n}\n\n\n\n/// A dependency handled by Cargo\n\n#[derive(Debug, PartialEq, Eq, Clone)]\n\npub struct Dependency {\n\n /// The name of the dependency (as it is set in its `Cargo.toml` and known to crates.io)\n\n pub name: String,\n\n optional: bool,\n\n /// List of features to add (or None to keep features unchanged).\n\n pub features: Option<Vec<String>>,\n", "file_path": "src/manifest/dependency.rs", "rank": 74, "score": 68507.87582163353 }, { "content": "enum MismatchReason<'a> {\n\n /// The specified file was not found when gathering license files\n\n FileNotFound,\n\n /// Encountered an I/O error trying to read the file contents\n\n Error(&'a std::io::Error),\n\n /// The hash of the license file doesn't match the expected hash\n\n HashDiffers,\n\n}\n\n\n", "file_path": "src/licenses/gather.rs", "rank": 75, "score": 66263.63421752136 }, { "content": "#[allow(clippy::large_enum_variant)]\n\nenum OutputFormat<'a> {\n\n Human(Human<'a>),\n\n Json(Json<'a>),\n\n}\n\n\n\nimpl<'a> OutputFormat<'a> {\n\n fn lock(&'a self, max_severity: Severity) -> OutputLock<'a, '_> {\n\n match self {\n\n Self::Human(ref human) => OutputLock::Human(human, max_severity, human.stream.lock()),\n\n Self::Json(ref json) => OutputLock::Json(json, max_severity, json.stream.lock()),\n\n }\n\n }\n\n}\n\n\n\npub enum StdLock<'a> {\n\n Err(std::io::StderrLock<'a>),\n\n //Out(std::io::StdoutLock<'a>),\n\n}\n\n\n\nimpl<'a> Write for StdLock<'a> {\n", "file_path": "src/cargo-deny/common.rs", "rank": 76, "score": 65000.586444099055 }, { "content": "fn evaluate_expression(\n\n cfg: &ValidConfig,\n\n krate_lic_nfo: &KrateLicense<'_>,\n\n expr: &spdx::Expression,\n\n nfo: &LicenseExprInfo,\n\n hits: &mut Hits,\n\n) -> Diagnostic {\n\n // TODO: If an expression with the same hash is encountered\n\n // just use the same result as a memoized one\n\n #[derive(Debug)]\n\n enum Reason {\n\n Denied,\n\n IsFsfFree,\n\n IsOsiApproved,\n\n IsBothFreeAndOsi,\n\n ExplicitAllowance,\n\n ExplicitException,\n\n IsCopyleft,\n\n Default,\n\n }\n", "file_path": "src/licenses.rs", "rank": 77, "score": 61167.86824986498 }, { "content": "fn main() {\n\n use std::process::Command;\n\n\n\n let td = std::env::temp_dir().join(\"deny-repos\");\n\n // This kind of doesn't work on windows!\n\n if td.exists() {\n\n std::fs::remove_dir_all(&td).unwrap();\n\n }\n\n std::fs::create_dir_all(&td).unwrap();\n\n\n\n // Fetch external sources once\n\n if !Command::new(\"cargo\")\n\n .args(&[\"deny\", \"-L\", \"debug\", \"fetch\", \"all\"])\n\n .status()\n\n .expect(\"failed to run cargo deny fetch\")\n\n .success()\n\n {\n\n panic!(\"failed to run cargo deny fetch\");\n\n }\n\n\n", "file_path": "scripts/check_external.rs", "rank": 78, "score": 61167.86824986498 }, { "content": "#[test]\n\nfn allows_git() {\n\n let cfg = \"unknown-git = 'deny'\n\n allow-git = [\n\n 'https://gitlab.com/amethyst-engine/amethyst',\n\n 'https://github.com/EmbarkStudios/krates',\n\n 'https://bitbucket.org/marshallpierce/line-wrap-rs',\n\n ]\";\n\n\n\n let krates = utils::get_test_data_krates(\"sources\").unwrap();\n\n let diags = utils::gather_diagnostics::<sources::Config, _, _>(\n\n krates,\n\n \"fails_unknown_git\",\n\n Some(cfg),\n\n None,\n\n |ctx, _, tx| {\n\n sources::check(ctx, tx);\n\n },\n\n )\n\n .unwrap();\n\n\n", "file_path": "tests/sources.rs", "rank": 79, "score": 61167.86824986498 }, { "content": "#[test]\n\nfn disallows_denied() {\n\n let diags = utils::gather_diagnostics::<cfg::Config, _, _>(\n\n utils::get_test_data_krates(\"allow_wrappers/maincrate\").unwrap(),\n\n \"disallows_denied\",\n\n Some(\n\n r#\"\n\n[[deny]]\n\nname = \"dangerous-dep\"\n\n\"#,\n\n ),\n\n None,\n\n |ctx, cs, tx| {\n\n bans::check(ctx, None, cs, tx);\n\n },\n\n )\n\n .unwrap();\n\n\n\n let diag = diags\n\n .iter()\n\n .find(|d| field_eq!(d, \"/fields/severity\", \"error\"))\n", "file_path": "tests/bans.rs", "rank": 80, "score": 61167.86824986498 }, { "content": "#[test]\n\nfn allow_wrappers() {\n\n let diags = utils::gather_diagnostics::<cfg::Config, _, _>(\n\n utils::get_test_data_krates(\"allow_wrappers/maincrate\").unwrap(),\n\n \"allow_wrappers\",\n\n Some(\n\n r#\"\n\n[[deny]]\n\nname = \"dangerous-dep\"\n\nwrappers = [\"safe-wrapper\"]\n\n\"#,\n\n ),\n\n None,\n\n |ctx, cs, tx| {\n\n bans::check(ctx, None, cs, tx);\n\n },\n\n )\n\n .unwrap();\n\n\n\n let diag = diags\n\n .iter()\n", "file_path": "tests/bans.rs", "rank": 81, "score": 61167.86824986498 }, { "content": "#[test]\n\nfn deny_wildcards() {\n\n let diags = utils::gather_diagnostics::<cfg::Config, _, _>(\n\n utils::get_test_data_krates(\"wildcards/maincrate\").unwrap(),\n\n \"deny_wildcards\",\n\n Some(\"wildcards = 'deny'\"),\n\n Some(std::time::Duration::from_millis(10000)),\n\n |ctx, cs, tx| {\n\n bans::check(ctx, None, cs, tx);\n\n },\n\n )\n\n .unwrap();\n\n\n\n let expected = [\"wildcards-test-crate\", \"wildcards-test-dep\"];\n\n\n\n for exp in &expected {\n\n assert!(\n\n diags.iter().any(|v| {\n\n field_eq!(v, \"/fields/severity\", \"error\")\n\n && field_eq!(\n\n v,\n\n \"/fields/message\",\n\n format!(\"found 1 wildcard dependency for crate '{}'\", exp)\n\n )\n\n }),\n\n \"unable to find error diagnostic for '{}'\",\n\n exp\n\n );\n\n }\n\n}\n", "file_path": "tests/bans.rs", "rank": 82, "score": 61167.86824986498 }, { "content": "fn main() {\n\n match real_main() {\n\n Ok(_) => {}\n\n Err(e) => {\n\n log::error!(\"{:#}\", e);\n\n std::process::exit(1);\n\n }\n\n }\n\n}\n", "file_path": "src/cargo-deny/main.rs", "rank": 83, "score": 59836.5373002295 }, { "content": "fn main() {\n\n println!(\"Hello, world!\");\n\n}\n", "file_path": "examples/09_bans/src/main.rs", "rank": 84, "score": 59836.5373002295 }, { "content": "fn main() {}\n", "file_path": "examples/01_allow_license/main.rs", "rank": 85, "score": 59836.5373002295 }, { "content": "#[test]\n\nfn allows_bitbucket_org() {\n\n let cfg = \"unknown-git = 'deny'\n\n [allow-org]\n\n bitbucket = ['marshallpierce']\n\n \";\n\n\n\n let krates = utils::get_test_data_krates(\"sources\").unwrap();\n\n let diags = utils::gather_diagnostics::<sources::Config, _, _>(\n\n krates,\n\n \"allows_bitbucket_org\",\n\n Some(cfg),\n\n None,\n\n |ctx, _, tx| {\n\n sources::check(ctx, tx);\n\n },\n\n )\n\n .unwrap();\n\n\n\n let allowed_by_org = [\"https://bitbucket.org/marshallpierce/line-wrap-rs\"];\n\n\n", "file_path": "tests/sources.rs", "rank": 86, "score": 59836.5373002295 }, { "content": "#[test]\n\nfn allows_github_org() {\n\n // We shouldn't have any errors for the embark urls now\n\n let cfg = \"unknown-git = 'deny'\n\n [allow-org]\n\n github = ['EmbarkStudios']\n\n \";\n\n\n\n let krates = utils::get_test_data_krates(\"sources\").unwrap();\n\n let diags = utils::gather_diagnostics::<sources::Config, _, _>(\n\n krates,\n\n \"allows_github_org\",\n\n Some(cfg),\n\n None,\n\n |ctx, _, tx| {\n\n sources::check(ctx, tx);\n\n },\n\n )\n\n .unwrap();\n\n\n\n let allowed_by_org = [\n", "file_path": "tests/sources.rs", "rank": 87, "score": 59836.5373002295 }, { "content": "fn main() {}\n", "file_path": "examples/02_deny_license/main.rs", "rank": 88, "score": 59836.5373002295 }, { "content": "#[test]\n\nfn allows_gitlab_org() {\n\n let cfg = \"unknown-git = 'deny'\n\n [allow-org]\n\n gitlab = ['amethyst-engine']\n\n \";\n\n\n\n let krates = utils::get_test_data_krates(\"sources\").unwrap();\n\n let diags = utils::gather_diagnostics::<sources::Config, _, _>(\n\n krates,\n\n \"allows_gitlab_org\",\n\n Some(cfg),\n\n None,\n\n |ctx, _, tx| {\n\n sources::check(ctx, tx);\n\n },\n\n )\n\n .unwrap();\n\n\n\n let allowed_by_org = [\"https://gitlab.com/amethyst-engine\"];\n\n\n", "file_path": "tests/sources.rs", "rank": 89, "score": 59836.5373002295 }, { "content": "fn main() {}\n", "file_path": "examples/03_deny_copyleft/main.rs", "rank": 90, "score": 59836.5373002295 }, { "content": "#[test]\n\nfn fails_unknown_git() {\n\n let cfg = \"unknown-git = 'deny'\";\n\n\n\n let krates = utils::get_test_data_krates(\"sources\").unwrap();\n\n let diags = utils::gather_diagnostics::<sources::Config, _, _>(\n\n krates,\n\n \"fails_unknown_git\",\n\n Some(cfg),\n\n None,\n\n |ctx, _, tx| {\n\n sources::check(ctx, tx);\n\n },\n\n )\n\n .unwrap();\n\n\n\n let failed_urls = [\n\n // Note this one is used by multiple crates, but that's ok\n\n \"https://gitlab.com/amethyst-engine/amethyst\",\n\n \"https://github.com/EmbarkStudios/krates\",\n\n \"https://bitbucket.org/marshallpierce/line-wrap-rs\",\n", "file_path": "tests/sources.rs", "rank": 91, "score": 59836.5373002295 }, { "content": "fn main() {}\n", "file_path": "examples/04_gnu_licenses/main.rs", "rank": 92, "score": 59836.5373002295 }, { "content": "pub fn check(\n\n ctx: crate::CheckCtx<'_, ValidConfig>,\n\n summary: Summary<'_>,\n\n mut sink: crate::diag::ErrorSink,\n\n) {\n\n let mut hits = Hits {\n\n allowed: BitVec::repeat(false, ctx.cfg.allowed.len()),\n\n exceptions: BitVec::repeat(false, ctx.cfg.exceptions.len()),\n\n };\n\n\n\n let private_registries: Vec<_> = ctx\n\n .cfg\n\n .private\n\n .registries\n\n .iter()\n\n .map(|s| s.as_str())\n\n .collect();\n\n\n\n for krate_lic_nfo in summary.nfos {\n\n let mut pack = Pack::with_kid(Check::Licenses, krate_lic_nfo.krate.id.clone());\n", "file_path": "src/licenses.rs", "rank": 93, "score": 59500.17975867266 }, { "content": "pub fn check(\n\n ctx: crate::CheckCtx<'_, ValidConfig>,\n\n output_graph: Option<Box<OutputGraph>>,\n\n cargo_spans: diag::CargoSpans,\n\n mut sink: diag::ErrorSink,\n\n) {\n\n let wildcard = VersionReq::parse(\"*\").expect(\"Parsing wildcard mustnt fail\");\n\n\n\n let ValidConfig {\n\n file_id,\n\n denied,\n\n allowed,\n\n skipped,\n\n multiple_versions,\n\n highlight,\n\n tree_skipped,\n\n wildcards,\n\n } = ctx.cfg;\n\n\n\n let krate_spans = &ctx.krate_spans;\n", "file_path": "src/bans.rs", "rank": 94, "score": 59500.17975867266 }, { "content": "fn main() {\n\n println!(\"Hello, world!\");\n\n}\n", "file_path": "examples/08_target_filtering/src/main.rs", "rank": 95, "score": 58594.62865782876 }, { "content": "#[test]\n\nfn validates_git_source_specs() {\n\n use sources::GitSpec;\n\n\n\n assert!(GitSpec::Rev > GitSpec::Tag);\n\n assert!(GitSpec::Tag > GitSpec::Branch);\n\n assert!(GitSpec::Branch > GitSpec::Any);\n\n\n\n let levels = [\n\n (GitSpec::Rev, \"https://gitlab.com/amethyst-engine/amethyst\"),\n\n (GitSpec::Tag, \"https://github.com/EmbarkStudios/spdx\"),\n\n (GitSpec::Branch, \"https://github.com/EmbarkStudios/krates\"),\n\n (\n\n GitSpec::Any,\n\n \"https://bitbucket.org/marshallpierce/line-wrap-rs\",\n\n ),\n\n ];\n\n\n\n for (i, (spec, _url)) in levels.iter().enumerate() {\n\n let cfg = format!(\n\n \"unknown-git = 'allow'\n", "file_path": "tests/sources.rs", "rank": 96, "score": 58594.62865782876 }, { "content": "fn setup_logger(\n\n level: log::LevelFilter,\n\n format: Format,\n\n color: bool,\n\n) -> Result<(), fern::InitError> {\n\n use ansi_term::Color::{Blue, Green, Purple, Red, Yellow};\n\n use log::Level::{Debug, Error, Info, Trace, Warn};\n\n\n\n match format {\n\n Format::Human => {\n\n if color {\n\n fern::Dispatch::new()\n\n .level(level)\n\n .format(move |out, message, record| {\n\n out.finish(format_args!(\n\n \"{date} [{level}] {message}\\x1B[0m\",\n\n date = chrono::Utc::now().format(\"%Y-%m-%d %H:%M:%S\"),\n\n level = match record.level() {\n\n Error => Red.paint(\"ERROR\"),\n\n Warn => Yellow.paint(\"WARN\"),\n", "file_path": "src/cargo-deny/main.rs", "rank": 97, "score": 58594.62865782876 }, { "content": "fn main() {\n\n println!(\"Hello, world!\");\n\n}\n", "file_path": "examples/07_deny_sources/src/main.rs", "rank": 98, "score": 58594.62865782876 }, { "content": "# Advisories Diagnostics\n\n\n\n### `A001` - security vulnerability detected\n\n\n\nA [`vulnerability`](cfg.md#the-vulnerability-field-optional) advisory was detected for a crate.\n\n\n\n### `A002` - notice advisory detected\n\n\n\nA [`notice`](cfg.md#the-notice-field-optional) advisory was detected for a crate.\n\n\n\n### `A003` - unmaintained advisory detected\n\n\n\nAn [`unmaintained`](cfg.md#the-unmaintained-field-optional) advisory was detected for a crate.\n\n\n\n### `A004` - unsound advisory detected\n\n\n\nAn [`unsound`](cfg.md#the-unsound-field-optional) advisory was detected for a crate.\n\n\n\n### `A005` - detected yanked crate\n\n\n\nA crate using a version that has been [yanked](cfg.md#the-yanked-field-optional) from the registry index was detected.\n\n\n\n### `A006` - unable to check for yanked crates\n\n\n\nAn error occurred trying to read or update the registry index (typically crates.io) so cargo-deny was unable to check the current yanked status for any crate.\n\n\n\n### `A007` - advisory was not encountered\n\n\n\nAn advisory in [`advisories.ignore`](cfg.md#the-ignore-field-optional) didn't apply to any crate.\n\n\n\n### `A008` - advisory not found in any advisory database\n\n\n\nAn advisory in [`advisories.ignore`](cfg.md#the-ignore-field-optional) wasn't found in any of the configured advisory databases.\n", "file_path": "docs/src/checks/advisories/diags.md", "rank": 99, "score": 62.55259599508195 } ]
Rust
wrflib/examples/example_charts/src/lines_basic.rs
cruise-automation/webviz-rust-framework
09bc1e0f72eb95a3ace45d2284bb4eb4ea5eb3c8
use wrflib::*; use wrflib_components::*; use crate::ChartExample; pub(crate) struct LinesBasic { pub(crate) chart: Chart, pub(crate) datasets: Vec<Vec<f32>>, pub(crate) randomize_btn: Button, pub(crate) add_dataset_btn: Button, pub(crate) add_data_btn: Button, pub(crate) remove_dataset_btn: Button, pub(crate) remove_data_btn: Button, pub(crate) reset_view_btn: Button, pub(crate) style: ChartStyle, pub(crate) tooltip: ChartTooltipConfig, pub(crate) pan_enabled: bool, pub(crate) zoom_enabled: bool, } impl Default for LinesBasic { fn default() -> Self { let mut ret = Self { chart: Chart::default(), datasets: vec![], randomize_btn: Button::default(), add_dataset_btn: Button::default(), add_data_btn: Button::default(), remove_dataset_btn: Button::default(), remove_data_btn: Button::default(), reset_view_btn: Button::default(), style: CHART_STYLE_LIGHT, tooltip: Default::default(), pan_enabled: false, zoom_enabled: false, }; ret.add_dataset(); ret.add_dataset(); ret } } impl LinesBasic { pub(crate) fn with_dark_style() -> Self { Self { style: CHART_STYLE_DARK, ..Self::default() } } pub(crate) fn with_zoom() -> Self { Self { zoom_enabled: true, ..Self::default() } } pub(crate) fn with_pan() -> Self { Self { pan_enabled: true, ..Self::default() } } pub(crate) fn with_zoom_and_pan() -> Self { Self { zoom_enabled: true, pan_enabled: true, ..Self::default() } } fn get_random_data(count: usize) -> Vec<f32> { if count == 0 { vec![] } else { (0..count).into_iter().map(|_| -100. + 200. * (universal_rand::random_128() as f32 / f32::MAX)).collect() } } fn randomize(&mut self) { if self.datasets.is_empty() { return; } let data_count = self.datasets[0].len(); for data in &mut self.datasets { *data = Self::get_random_data(data_count); } } fn add_dataset(&mut self) { let data_count = { if self.datasets.is_empty() { 7 } else { self.datasets[0].len() } }; self.datasets.push(Self::get_random_data(data_count)); } fn add_data(&mut self) { for data in &mut self.datasets { data.push(Self::get_random_data(1)[0]) } } fn remove_dataset(&mut self) { if self.datasets.is_empty() { return; } self.datasets.pop(); } fn remove_data(&mut self) { for data in &mut self.datasets { data.pop(); } } fn draw_chart(&mut self, cx: &mut Cx) { cx.begin_row(Width::Fill, Height::Fix(cx.get_height_left() - 70.)); cx.begin_padding_box(Padding::top(20.)); let colors = vec![COLOR_RED, COLOR_ORANGE, COLOR_YELLOW, COLOR_GREEN, COLOR_BLUE, COLOR_PURPLE, COLOR_GRAY]; let months = vec![ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; let datasets: Vec<ChartDataset> = self .datasets .iter() .enumerate() .map(|(i, data)| ChartDataset { label: format!("Dataset {}", i), data: ChartData::from_values(data), point_background_color: colors[i % colors.len()], point_radius: 4., border_color: colors[i % colors.len()], border_width: 2., ..ChartDataset::default() }) .collect(); let mut labels = vec![]; if let Some(data_count) = datasets.iter().map(|ds| ds.data.len()).max() { for i in 0..data_count { labels.push(months[i % months.len()].to_string()); } } let config = ChartConfig { labels, chart_type: ChartType::Line, datasets, style: self.style.clone(), tooltip: self.tooltip.clone(), zoom_enabled: self.zoom_enabled, pan_enabled: self.pan_enabled, ..ChartConfig::default() }; self.chart.draw(cx, &config); cx.end_padding_box(); cx.end_row(); } pub fn draw_bottom_bar(&mut self, cx: &mut Cx) { cx.begin_row(Width::Fill, Height::Fix(50.)); self.randomize_btn.draw(cx, "Randomize"); self.add_dataset_btn.draw(cx, "Add Dataset"); self.add_data_btn.draw(cx, "Add Data"); self.remove_dataset_btn.draw(cx, "Remove Dataset"); self.remove_data_btn.draw(cx, "Remove Data"); if self.zoom_enabled || self.pan_enabled { self.reset_view_btn.draw(cx, "Reset View"); } cx.end_row(); } } impl ChartExample for LinesBasic { fn handle(&mut self, cx: &mut Cx, event: &mut Event) -> ChartEvent { if let ButtonEvent::Clicked = self.randomize_btn.handle(cx, event) { self.randomize(); } if let ButtonEvent::Clicked = self.add_dataset_btn.handle(cx, event) { self.add_dataset(); } if let ButtonEvent::Clicked = self.add_data_btn.handle(cx, event) { self.add_data(); } if let ButtonEvent::Clicked = self.remove_dataset_btn.handle(cx, event) { self.remove_dataset(); } if let ButtonEvent::Clicked = self.remove_data_btn.handle(cx, event) { self.remove_data(); } if let ButtonEvent::Clicked = self.reset_view_btn.handle(cx, event) { self.chart.reset_zoom_pan(); } self.chart.handle(cx, event) } fn draw(&mut self, cx: &mut Cx) { cx.begin_column(Width::Fill, Height::Fill); self.draw_chart(cx); self.draw_bottom_bar(cx); cx.end_column(); } }
use wrflib::*; use wrflib_components::*; use crate::ChartExample; pub(crate) struct LinesBasic { pub(crate) chart: Chart, pub(crate) datasets: Vec<Vec<f32>>, pub(crate) randomize_btn: Button, pub(crate) add_dataset_btn: Button, pub(crate) add_data_btn: Button, pub(crate) remove_dataset_btn: Button, pub(crate) remove_data_btn: Button, pub(crate) reset_view_btn: Button, pub(crate) style: ChartStyle, pub(crate) tooltip: ChartTooltipConfig, pub(crate) pan_enabled: bool, pub(crate) zoom_enabled: bool, } impl Default for LinesBasic { fn default() -> Self {
ret.add_dataset(); ret.add_dataset(); ret } } impl LinesBasic { pub(crate) fn with_dark_style() -> Self { Self { style: CHART_STYLE_DARK, ..Self::default() } } pub(crate) fn with_zoom() -> Self { Self { zoom_enabled: true, ..Self::default() } } pub(crate) fn with_pan() -> Self { Self { pan_enabled: true, ..Self::default() } } pub(crate) fn with_zoom_and_pan() -> Self { Self { zoom_enabled: true, pan_enabled: true, ..Self::default() } } fn get_random_data(count: usize) -> Vec<f32> { if count == 0 { vec![] } else { (0..count).into_iter().map(|_| -100. + 200. * (universal_rand::random_128() as f32 / f32::MAX)).collect() } } fn randomize(&mut self) { if self.datasets.is_empty() { return; } let data_count = self.datasets[0].len(); for data in &mut self.datasets { *data = Self::get_random_data(data_count); } } fn add_dataset(&mut self) { let data_count = { if self.datasets.is_empty() { 7 } else { self.datasets[0].len() } }; self.datasets.push(Self::get_random_data(data_count)); } fn add_data(&mut self) { for data in &mut self.datasets { data.push(Self::get_random_data(1)[0]) } } fn remove_dataset(&mut self) { if self.datasets.is_empty() { return; } self.datasets.pop(); } fn remove_data(&mut self) { for data in &mut self.datasets { data.pop(); } } fn draw_chart(&mut self, cx: &mut Cx) { cx.begin_row(Width::Fill, Height::Fix(cx.get_height_left() - 70.)); cx.begin_padding_box(Padding::top(20.)); let colors = vec![COLOR_RED, COLOR_ORANGE, COLOR_YELLOW, COLOR_GREEN, COLOR_BLUE, COLOR_PURPLE, COLOR_GRAY]; let months = vec![ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; let datasets: Vec<ChartDataset> = self .datasets .iter() .enumerate() .map(|(i, data)| ChartDataset { label: format!("Dataset {}", i), data: ChartData::from_values(data), point_background_color: colors[i % colors.len()], point_radius: 4., border_color: colors[i % colors.len()], border_width: 2., ..ChartDataset::default() }) .collect(); let mut labels = vec![]; if let Some(data_count) = datasets.iter().map(|ds| ds.data.len()).max() { for i in 0..data_count { labels.push(months[i % months.len()].to_string()); } } let config = ChartConfig { labels, chart_type: ChartType::Line, datasets, style: self.style.clone(), tooltip: self.tooltip.clone(), zoom_enabled: self.zoom_enabled, pan_enabled: self.pan_enabled, ..ChartConfig::default() }; self.chart.draw(cx, &config); cx.end_padding_box(); cx.end_row(); } pub fn draw_bottom_bar(&mut self, cx: &mut Cx) { cx.begin_row(Width::Fill, Height::Fix(50.)); self.randomize_btn.draw(cx, "Randomize"); self.add_dataset_btn.draw(cx, "Add Dataset"); self.add_data_btn.draw(cx, "Add Data"); self.remove_dataset_btn.draw(cx, "Remove Dataset"); self.remove_data_btn.draw(cx, "Remove Data"); if self.zoom_enabled || self.pan_enabled { self.reset_view_btn.draw(cx, "Reset View"); } cx.end_row(); } } impl ChartExample for LinesBasic { fn handle(&mut self, cx: &mut Cx, event: &mut Event) -> ChartEvent { if let ButtonEvent::Clicked = self.randomize_btn.handle(cx, event) { self.randomize(); } if let ButtonEvent::Clicked = self.add_dataset_btn.handle(cx, event) { self.add_dataset(); } if let ButtonEvent::Clicked = self.add_data_btn.handle(cx, event) { self.add_data(); } if let ButtonEvent::Clicked = self.remove_dataset_btn.handle(cx, event) { self.remove_dataset(); } if let ButtonEvent::Clicked = self.remove_data_btn.handle(cx, event) { self.remove_data(); } if let ButtonEvent::Clicked = self.reset_view_btn.handle(cx, event) { self.chart.reset_zoom_pan(); } self.chart.handle(cx, event) } fn draw(&mut self, cx: &mut Cx) { cx.begin_column(Width::Fill, Height::Fill); self.draw_chart(cx); self.draw_bottom_bar(cx); cx.end_column(); } }
let mut ret = Self { chart: Chart::default(), datasets: vec![], randomize_btn: Button::default(), add_dataset_btn: Button::default(), add_data_btn: Button::default(), remove_dataset_btn: Button::default(), remove_data_btn: Button::default(), reset_view_btn: Button::default(), style: CHART_STYLE_LIGHT, tooltip: Default::default(), pan_enabled: false, zoom_enabled: false, };
assignment_statement
[ { "content": "#[derive(Default)]\n\nstruct Tooltip {\n\n value: f32,\n\n path: String,\n\n}\n\n\n\nimpl ChartTooltipRenderer for Tooltip {\n\n fn draw_tooltip(&self, cx: &mut Cx, config: &ChartConfig, pos: Vec2) {\n\n let text_props =\n\n TextInsProps { text_style: TEXT_STYLE_MONO, color: config.style.background_color, ..TextInsProps::DEFAULT };\n\n\n\n TextIns::draw_str(cx, \"This is a custom tooltip\", pos + vec2(10., 10.), &text_props);\n\n TextIns::draw_str(cx, &format!(\"Value: {}\", self.value), pos + vec2(10., 25.), &text_props);\n\n TextIns::draw_str(cx, &format!(\"Path: {}\", self.path), pos + vec2(10., 40.), &text_props);\n\n }\n\n}\n\n\n\npub(crate) struct TooltipCustomExample {\n\n base: LinesBasic,\n\n tooltip: Arc<RwLock<Tooltip>>,\n\n}\n", "file_path": "wrflib/examples/example_charts/src/tooltip_custom.rs", "rank": 0, "score": 268787.24470589496 }, { "content": "/// See https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button#return_value\n\nfn get_mouse_button(button: usize) -> MouseButton {\n\n return match button {\n\n 0 => MouseButton::Left,\n\n 2 => MouseButton::Right,\n\n _ => MouseButton::Other,\n\n };\n\n}\n\n\n\n// storage buffers for graphics API related platform\n\npub(crate) struct CxPlatform {\n\n pub(crate) is_initialized: bool,\n\n pub(crate) window_geom: WindowGeom,\n\n pub(crate) zerde_eventloop_msgs: ZerdeEventloopMsgs,\n\n pub(crate) vertex_buffers: usize,\n\n pub(crate) index_buffers: usize,\n\n pub(crate) vaos: usize,\n\n pub(crate) pointers_down: Vec<bool>,\n\n call_rust_in_same_thread_sync_fn: RwLock<Option<CallRustInSameThreadSyncFn>>,\n\n // pub(crate) xr_last_left_input: XRInput,\n\n // pub(crate) xr_last_right_input: XRInput,\n", "file_path": "wrflib/main/src/cx_wasm32.rs", "rank": 1, "score": 189234.55083229765 }, { "content": "struct ChartItem {\n\n name: String,\n\n checked: bool,\n\n checkbox: Checkbox,\n\n}\n\n\n\nimpl ChartItem {\n\n fn with_name(name: &str) -> Self {\n\n Self { name: String::from(name), checked: false, checkbox: Checkbox::default() }\n\n }\n\n}\n\n\n\npub(crate) enum ChartListEvent<'a> {\n\n None,\n\n ChartSelected(&'a str),\n\n}\n\n\n\npub(crate) struct ChartList {\n\n background: Background,\n\n view: View,\n", "file_path": "wrflib/examples/example_charts/src/chart_list.rs", "rank": 2, "score": 175496.63406478515 }, { "content": "fn optional_bool_to_cef_state(val: Option<bool>) -> cef_state_t {\n\n match val {\n\n None => wrflib_cef_sys::cef_state_t::STATE_DEFAULT,\n\n Some(false) => wrflib_cef_sys::cef_state_t::STATE_DISABLED,\n\n Some(true) => wrflib_cef_sys::cef_state_t::STATE_ENABLED,\n\n }\n\n}\n\n\n\n#[derive(Debug, Copy, Clone)]\n\npub struct BrowserSettings<'a> {\n\n pub windowless_frame_rate: i32,\n\n pub standard_font_family: Option<&'a str>,\n\n pub fixed_font_family: Option<&'a str>,\n\n pub serif_font_family: Option<&'a str>,\n\n pub sans_serif_font_family: Option<&'a str>,\n\n pub cursive_font_family: Option<&'a str>,\n\n pub fantasy_font_family: Option<&'a str>,\n\n pub default_font_size: i32,\n\n pub default_fixed_font_size: i32,\n\n pub minimum_font_size: i32,\n", "file_path": "wrflib/main/cef/src/window.rs", "rank": 3, "score": 175330.64231252923 }, { "content": "/// Hacky function for determining what is a URL and what isn't.\n\nfn is_absolute_url(path: &str) -> bool {\n\n path.starts_with(\"http://\") || path.starts_with(\"https://\")\n\n}\n\n\n\n/// Actually set [`UniversalFileInner::LocalFile::file`] if it hasn't been set yet.\n", "file_path": "wrflib/main/src/universal_file.rs", "rank": 4, "score": 173389.7498062651 }, { "content": "/// Version of [`std::thread::spawn`] that also works in WebAssembly.\n\n///\n\n/// See also [`Thread::spawn`].\n\npub fn spawn(f: impl FnOnce() + Send + 'static) {\n\n UniversalThread::spawn(f);\n\n}\n\n\n", "file_path": "wrflib/main/src/universal_thread.rs", "rank": 5, "score": 172925.5414222119 }, { "content": "pub fn currently_on(id: ThreadId) -> bool {\n\n unsafe { cef_currently_on(id) > 0 }\n\n}\n\n\n", "file_path": "wrflib/main/cef/src/thread.rs", "rank": 6, "score": 166957.93891100126 }, { "content": "#[derive(Default)]\n\nstruct SingleButtonExampleApp {\n\n window: Window,\n\n pass: Pass,\n\n main_view: View,\n\n single_button: SingleButton,\n\n}\n\n\n\nimpl SingleButtonExampleApp {\n\n fn new(_cx: &mut Cx) -> Self {\n\n Self::default()\n\n }\n\n\n\n fn handle(&mut self, cx: &mut Cx, event: &mut Event) {\n\n self.single_button.handle(cx, event);\n\n }\n\n\n\n fn draw(&mut self, cx: &mut Cx) {\n\n self.window.begin_window(cx);\n\n self.pass.begin_pass(cx, Vec4::color(\"300\"));\n\n self.main_view.begin_view(cx, LayoutSize::FILL);\n", "file_path": "wrflib/examples/example_single_button/src/main.rs", "rank": 7, "score": 166349.2265207526 }, { "content": "#[derive(Clone, Default)]\n\n#[repr(C)]\n\nstruct BgIns {\n\n base: QuadIns,\n\n hover: f32,\n\n down: f32,\n\n}\n\n\n\nstatic SHADER: Shader = Shader {\n\n build_geom: Some(QuadIns::build_geom),\n\n code_to_concatenate: &[\n\n Cx::STD_SHADER,\n\n QuadIns::SHADER,\n\n code_fragment!(\n\n r#\"\n\n instance hover: float;\n\n instance down: float;\n\n\n\n const shadow: float = 3.0;\n\n const border_radius: float = 2.5;\n\n\n\n fn pixel() -> vec4 {\n", "file_path": "wrflib/components/src/button.rs", "rank": 8, "score": 163453.98344291328 }, { "content": "#[derive(Clone, Default)]\n\n#[repr(C)]\n\nstruct DesktopButtonIns {\n\n base: QuadIns,\n\n hover: f32,\n\n down: f32,\n\n button_type: f32,\n\n}\n\n\n\nstatic SHADER: Shader = Shader {\n\n build_geom: Some(QuadIns::build_geom),\n\n code_to_concatenate: &[\n\n Cx::STD_SHADER,\n\n QuadIns::SHADER,\n\n code_fragment!(\n\n r#\"\n\n instance hover: float;\n\n instance down: float;\n\n instance button_type: float;\n\n\n\n fn pixel() -> vec4 {\n\n let df = Df::viewport(pos * rect_size);\n", "file_path": "wrflib/components/src/internal/desktopbutton.rs", "rank": 9, "score": 159092.0596968452 }, { "content": "type SetProcessDPIAware = unsafe extern \"system\" fn() -> BOOL;\n", "file_path": "wrflib/main/src/cx_win32.rs", "rank": 10, "score": 157687.10111145978 }, { "content": "pub fn post_task<F: FnOnce()>(id: ThreadId, func: F) -> Result<(), bool> {\n\n if currently_on(id) {\n\n // Execute it now\n\n func();\n\n return Ok(());\n\n }\n\n\n\n let task = wrap_ptr(move |base| TaskWrapper {\n\n _base: cef_task_t { base, execute: Some(TaskWrapper::<F>::execute) },\n\n func: Some(func),\n\n });\n\n\n\n let ok = unsafe { cef_post_task(id, task) };\n\n if ok > 0 {\n\n Ok(())\n\n } else {\n\n Err(false)\n\n }\n\n}\n\n\n", "file_path": "wrflib/main/cef/src/thread.rs", "rank": 11, "score": 155679.60780329912 }, { "content": "struct WidgetExampleApp {\n\n desktop_window: DesktopWindow,\n\n menu: Menu,\n\n button: Button,\n\n buttons: Vec<Button>,\n\n}\n\n\n\nimpl WidgetExampleApp {\n\n fn new(_cx: &mut Cx) -> Self {\n\n Self {\n\n desktop_window: DesktopWindow::default(),\n\n button: Button::default(),\n\n buttons: (0..1000).map(|_| Button::default()).collect(),\n\n menu: Menu::main(vec![Menu::sub(\"Example\", vec![Menu::line(), Menu::item(\"Quit Example\", Cx::COMMAND_QUIT)])]),\n\n }\n\n }\n\n\n\n fn handle(&mut self, cx: &mut Cx, event: &mut Event) {\n\n self.desktop_window.handle(cx, event);\n\n\n", "file_path": "wrflib/examples/example_lots_of_buttons/src/main.rs", "rank": 12, "score": 155021.9363826445 }, { "content": "fn create_array_buffer<T: Default + Clone>(count: i32) -> V8Value {\n\n let callback = Arc::new(MyV8ArrayBufferReleaseCallback::<T> { buffer: Arc::new(vec![T::default(); count as usize]) });\n\n\n\n let value = V8Value::create_array(2);\n\n let arc_ptr = V8Value::create_uint(Arc::as_ptr(&callback.buffer) as u32);\n\n let v8_buffer = V8Value::create_array_buffer(\n\n callback.buffer.as_ptr() as *const u8,\n\n callback.buffer.len() * std::mem::size_of::<T>(),\n\n callback,\n\n );\n\n value.set_value_byindex(0, &v8_buffer);\n\n value.set_value_byindex(1, &arc_ptr);\n\n value\n\n}\n\n\n\nimpl RenderProcessHandler for MyRenderProcessHandler {\n\n fn on_process_message_received(\n\n &self,\n\n _browser: &Browser,\n\n frame: &Frame,\n", "file_path": "wrflib/main/src/cef_browser.rs", "rank": 13, "score": 152682.28853057098 }, { "content": "fn keycode_to_menu_key(keycode: KeyCode, shift: bool) -> &'static str {\n\n if !shift {\n\n match keycode {\n\n KeyCode::Backtick => \"`\",\n\n KeyCode::Key0 => \"0\",\n\n KeyCode::Key1 => \"1\",\n\n KeyCode::Key2 => \"2\",\n\n KeyCode::Key3 => \"3\",\n\n KeyCode::Key4 => \"4\",\n\n KeyCode::Key5 => \"5\",\n\n KeyCode::Key6 => \"6\",\n\n KeyCode::Key7 => \"7\",\n\n KeyCode::Key8 => \"8\",\n\n KeyCode::Key9 => \"9\",\n\n KeyCode::Minus => \"-\",\n\n KeyCode::Equals => \"=\",\n\n\n\n KeyCode::KeyQ => \"q\",\n\n KeyCode::KeyW => \"w\",\n\n KeyCode::KeyE => \"e\",\n", "file_path": "wrflib/main/src/cx_cocoa.rs", "rank": 14, "score": 152646.75815753965 }, { "content": "#[derive(Debug)]\n\nstruct FnDefAnalyser<'a> {\n\n builtins: &'a HashMap<Ident, Builtin>,\n\n shader: &'a ShaderAst,\n\n decl: &'a FnDecl,\n\n env: &'a mut Env,\n\n is_inside_loop: bool,\n\n}\n\n\n\nimpl<'a> FnDefAnalyser<'a> {\n\n fn ty_checker(&self) -> TyChecker {\n\n TyChecker { builtins: self.builtins, shader: self.shader, env: self.env }\n\n }\n\n\n\n fn const_evaluator(&self) -> ConstEvaluator {\n\n ConstEvaluator { shader: self.shader }\n\n }\n\n\n\n fn dep_analyser(&self) -> DepAnalyser {\n\n DepAnalyser { shader: self.shader, decl: self.decl, env: self.env }\n\n }\n", "file_path": "wrflib/main/shader_compiler/src/analyse.rs", "rank": 15, "score": 152620.03818946448 }, { "content": "struct FnDeclGenerator<'a> {\n\n shader: &'a ShaderAst,\n\n decl: &'a FnDecl,\n\n visited: &'a mut HashSet<IdentPath>,\n\n string: &'a mut String,\n\n backend_writer: &'a dyn BackendWriter,\n\n}\n\n\n\nimpl<'a> FnDeclGenerator<'a> {\n\n fn generate_fn_decl(&mut self) {\n\n if self.visited.contains(&self.decl.ident_path) {\n\n return;\n\n }\n\n for &callee in self.decl.callees.borrow().as_ref().unwrap().iter() {\n\n FnDeclGenerator {\n\n backend_writer: self.backend_writer,\n\n shader: self.shader,\n\n decl: self.shader.find_fn_decl(callee).unwrap(),\n\n visited: self.visited,\n\n string: self.string,\n", "file_path": "wrflib/main/shader_compiler/src/generate_hlsl.rs", "rank": 16, "score": 150630.35090738704 }, { "content": "struct FnDeclGenerator<'a> {\n\n shader: &'a ShaderAst,\n\n decl: &'a FnDecl,\n\n visited: &'a mut HashSet<IdentPath>,\n\n string: &'a mut String,\n\n backend_writer: &'a dyn BackendWriter,\n\n}\n\n\n\nimpl<'a> FnDeclGenerator<'a> {\n\n fn generate_fn_decl(&mut self) {\n\n if self.visited.contains(&self.decl.ident_path) {\n\n return;\n\n }\n\n for &callee in self.decl.callees.borrow().as_ref().unwrap().iter() {\n\n FnDeclGenerator {\n\n shader: self.shader,\n\n backend_writer: self.backend_writer,\n\n decl: self.shader.find_fn_decl(callee).unwrap(),\n\n visited: self.visited,\n\n string: self.string,\n", "file_path": "wrflib/main/shader_compiler/src/generate_metal.rs", "rank": 17, "score": 150630.35090738704 }, { "content": "struct FnDeclGenerator<'a> {\n\n shader: &'a ShaderAst,\n\n decl: &'a FnDecl,\n\n visited: &'a mut HashSet<IdentPath>,\n\n string: &'a mut String,\n\n backend_writer: &'a dyn BackendWriter,\n\n}\n\n\n\nimpl<'a> FnDeclGenerator<'a> {\n\n fn generate_fn_decl(&mut self) {\n\n if self.visited.contains(&self.decl.ident_path) {\n\n return;\n\n }\n\n for &callee in self.decl.callees.borrow().as_ref().unwrap().iter() {\n\n FnDeclGenerator {\n\n shader: self.shader,\n\n decl: self.shader.find_fn_decl(callee).unwrap(),\n\n visited: self.visited,\n\n backend_writer: self.backend_writer,\n\n string: self.string,\n", "file_path": "wrflib/main/shader_compiler/src/generate_glsl.rs", "rank": 18, "score": 150630.35090738704 }, { "content": "/// In x11, 1 is left, 3 is right, and 2 is middle click.\n\n/// Refer: <http://xahlee.info/linux/linux_x11_mouse_button_number.html>\n\n/// Double checked this using `xev` command in ubuntu.\n\nfn get_mouse_button_from_digit(digit: usize) -> MouseButton {\n\n match digit {\n\n 1 => MouseButton::Left,\n\n 3 => MouseButton::Right,\n\n _ => MouseButton::Other,\n\n }\n\n}\n\n\n\nimpl XlibWindow {\n\n pub(crate) fn new(xlib_app: &mut XlibApp, window_id: usize) -> XlibWindow {\n\n let mut pointers_down = Vec::new();\n\n pointers_down.resize(NUM_POINTERS, false);\n\n\n\n XlibWindow {\n\n window: None,\n\n xic: None,\n\n attributes: None,\n\n visual_info: None,\n\n child_windows: Vec::new(),\n\n window_id,\n", "file_path": "wrflib/main/src/cx_xlib.rs", "rank": 19, "score": 150573.03775450066 }, { "content": "export function addDefaultStyles(): void {\n\n const style = document.createElement(\"style\");\n\n style.innerHTML = `\n\n * {\n\n user-select: none;\n\n }\n\n html, body {\n\n overflow: hidden;\n\n background-color: #333;\n\n }\n\n body {\n\n margin: 0;\n\n position: fixed;\n\n width: 100%;\n\n height: 100%;\n\n }\n\n\n\n #wrflib_js_root {\n\n position: absolute; /* For z-index */\n\n z-index: 0; /* New stacking context */\n\n left: 0;\n\n right: 0;\n\n top: 0;\n\n bottom: 0;\n\n pointer-events: none;\n\n }`;\n\n document.body.appendChild(style);\n\n}\n", "file_path": "wrflib/web/default_styles.ts", "rank": 20, "score": 148653.3791328149 }, { "content": "#[test]\n\nfn bindgen_test_layout_XIMStyles() {\n\n assert_eq!(\n\n ::std::mem::size_of::<XIMStyles>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(XIMStyles))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<XIMStyles>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(XIMStyles))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<XIMStyles>())).count_styles as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(XIMStyles),\n\n \"::\",\n\n stringify!(count_styles)\n\n )\n", "file_path": "wrflib/main/bind/glx-sys/src/bindings.rs", "rank": 21, "score": 148037.82204325538 }, { "content": "#[test]\n\nfn bindgen_test_layout_XIMStyles() {\n\n assert_eq!(\n\n ::std::mem::size_of::<XIMStyles>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(XIMStyles))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<XIMStyles>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(XIMStyles))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<XIMStyles>())).count_styles as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(XIMStyles),\n\n \"::\",\n\n stringify!(count_styles)\n\n )\n", "file_path": "wrflib/main/bind/x11-sys/src/bindings.rs", "rank": 22, "score": 148037.82204325538 }, { "content": "type EnableNonClientDpiScaling = unsafe extern \"system\" fn(hwnd: HWND) -> BOOL;\n\n\n", "file_path": "wrflib/main/src/cx_win32.rs", "rank": 23, "score": 146490.3349083952 }, { "content": "#[test]\n\nfn bindgen_test_layout_XButtonEvent() {\n\n assert_eq!(\n\n ::std::mem::size_of::<XButtonEvent>(),\n\n 96usize,\n\n concat!(\"Size of: \", stringify!(XButtonEvent))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<XButtonEvent>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(XButtonEvent))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<XButtonEvent>())).type_ as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(XButtonEvent),\n\n \"::\",\n\n stringify!(type_)\n\n )\n", "file_path": "wrflib/main/bind/x11-sys/src/bindings.rs", "rank": 24, "score": 146222.74870788064 }, { "content": "#[test]\n\nfn bindgen_test_layout_XButtonEvent() {\n\n assert_eq!(\n\n ::std::mem::size_of::<XButtonEvent>(),\n\n 96usize,\n\n concat!(\"Size of: \", stringify!(XButtonEvent))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<XButtonEvent>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(XButtonEvent))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<XButtonEvent>())).type_ as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(XButtonEvent),\n\n \"::\",\n\n stringify!(type_)\n\n )\n", "file_path": "wrflib/main/bind/glx-sys/src/bindings.rs", "rank": 25, "score": 146222.74870788064 }, { "content": "#[test]\n\nfn bindgen_test_layout_XCharStruct() {\n\n assert_eq!(\n\n ::std::mem::size_of::<XCharStruct>(),\n\n 12usize,\n\n concat!(\"Size of: \", stringify!(XCharStruct))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<XCharStruct>(),\n\n 2usize,\n\n concat!(\"Alignment of \", stringify!(XCharStruct))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<XCharStruct>())).lbearing as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(XCharStruct),\n\n \"::\",\n\n stringify!(lbearing)\n\n )\n", "file_path": "wrflib/main/bind/x11-sys/src/bindings.rs", "rank": 26, "score": 146114.0119987146 }, { "content": "#[test]\n\nfn bindgen_test_layout_XFontStruct() {\n\n assert_eq!(\n\n ::std::mem::size_of::<XFontStruct>(),\n\n 96usize,\n\n concat!(\"Size of: \", stringify!(XFontStruct))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<XFontStruct>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(XFontStruct))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<XFontStruct>())).ext_data as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(XFontStruct),\n\n \"::\",\n\n stringify!(ext_data)\n\n )\n", "file_path": "wrflib/main/bind/x11-sys/src/bindings.rs", "rank": 27, "score": 146114.0119987146 }, { "content": "#[test]\n\nfn bindgen_test_layout_XCharStruct() {\n\n assert_eq!(\n\n ::std::mem::size_of::<XCharStruct>(),\n\n 12usize,\n\n concat!(\"Size of: \", stringify!(XCharStruct))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<XCharStruct>(),\n\n 2usize,\n\n concat!(\"Alignment of \", stringify!(XCharStruct))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<XCharStruct>())).lbearing as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(XCharStruct),\n\n \"::\",\n\n stringify!(lbearing)\n\n )\n", "file_path": "wrflib/main/bind/glx-sys/src/bindings.rs", "rank": 28, "score": 146114.0119987146 }, { "content": "#[test]\n\nfn bindgen_test_layout_XFontStruct() {\n\n assert_eq!(\n\n ::std::mem::size_of::<XFontStruct>(),\n\n 96usize,\n\n concat!(\"Size of: \", stringify!(XFontStruct))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<XFontStruct>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(XFontStruct))\n\n );\n\n assert_eq!(\n\n unsafe { &(*(::std::ptr::null::<XFontStruct>())).ext_data as *const _ as usize },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(XFontStruct),\n\n \"::\",\n\n stringify!(ext_data)\n\n )\n", "file_path": "wrflib/main/bind/glx-sys/src/bindings.rs", "rank": 29, "score": 146114.0119987146 }, { "content": "type SetProcessDpiAwarenessContext = unsafe extern \"system\" fn(value: DPI_AWARENESS_CONTEXT) -> BOOL;\n", "file_path": "wrflib/main/src/cx_win32.rs", "rank": 30, "score": 143459.3262701732 }, { "content": "#[test]\n\nfn bindgen_test_layout__XIMStatusDrawCallbackStruct() {\n\n assert_eq!(\n\n ::std::mem::size_of::<_XIMStatusDrawCallbackStruct>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(_XIMStatusDrawCallbackStruct))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<_XIMStatusDrawCallbackStruct>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(_XIMStatusDrawCallbackStruct))\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<_XIMStatusDrawCallbackStruct>())).type_ as *const _ as usize\n\n },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(_XIMStatusDrawCallbackStruct),\n\n \"::\",\n", "file_path": "wrflib/main/bind/x11-sys/src/bindings.rs", "rank": 31, "score": 142686.34118967556 }, { "content": "#[test]\n\nfn bindgen_test_layout__XIMStringConversionCallbackStruct() {\n\n assert_eq!(\n\n ::std::mem::size_of::<_XIMStringConversionCallbackStruct>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(_XIMStringConversionCallbackStruct))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<_XIMStringConversionCallbackStruct>(),\n\n 8usize,\n\n concat!(\n\n \"Alignment of \",\n\n stringify!(_XIMStringConversionCallbackStruct)\n\n )\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<_XIMStringConversionCallbackStruct>())).position as *const _\n\n as usize\n\n },\n\n 0usize,\n", "file_path": "wrflib/main/bind/x11-sys/src/bindings.rs", "rank": 32, "score": 142686.34118967556 }, { "content": "#[test]\n\nfn bindgen_test_layout__XIMStringConversionCallbackStruct() {\n\n assert_eq!(\n\n ::std::mem::size_of::<_XIMStringConversionCallbackStruct>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(_XIMStringConversionCallbackStruct))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<_XIMStringConversionCallbackStruct>(),\n\n 8usize,\n\n concat!(\n\n \"Alignment of \",\n\n stringify!(_XIMStringConversionCallbackStruct)\n\n )\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<_XIMStringConversionCallbackStruct>())).position as *const _\n\n as usize\n\n },\n\n 0usize,\n", "file_path": "wrflib/main/bind/glx-sys/src/bindings.rs", "rank": 33, "score": 142686.34118967556 }, { "content": "#[test]\n\nfn bindgen_test_layout__XIMPreeditDrawCallbackStruct() {\n\n assert_eq!(\n\n ::std::mem::size_of::<_XIMPreeditDrawCallbackStruct>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(_XIMPreeditDrawCallbackStruct))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<_XIMPreeditDrawCallbackStruct>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(_XIMPreeditDrawCallbackStruct))\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<_XIMPreeditDrawCallbackStruct>())).caret as *const _ as usize\n\n },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(_XIMPreeditDrawCallbackStruct),\n\n \"::\",\n", "file_path": "wrflib/main/bind/glx-sys/src/bindings.rs", "rank": 34, "score": 142686.34118967556 }, { "content": "#[test]\n\nfn bindgen_test_layout__XIMPreeditDrawCallbackStruct() {\n\n assert_eq!(\n\n ::std::mem::size_of::<_XIMPreeditDrawCallbackStruct>(),\n\n 24usize,\n\n concat!(\"Size of: \", stringify!(_XIMPreeditDrawCallbackStruct))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<_XIMPreeditDrawCallbackStruct>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(_XIMPreeditDrawCallbackStruct))\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<_XIMPreeditDrawCallbackStruct>())).caret as *const _ as usize\n\n },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(_XIMPreeditDrawCallbackStruct),\n\n \"::\",\n", "file_path": "wrflib/main/bind/x11-sys/src/bindings.rs", "rank": 35, "score": 142686.34118967556 }, { "content": "#[test]\n\nfn bindgen_test_layout__XIMStatusDrawCallbackStruct() {\n\n assert_eq!(\n\n ::std::mem::size_of::<_XIMStatusDrawCallbackStruct>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(_XIMStatusDrawCallbackStruct))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<_XIMStatusDrawCallbackStruct>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(_XIMStatusDrawCallbackStruct))\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<_XIMStatusDrawCallbackStruct>())).type_ as *const _ as usize\n\n },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(_XIMStatusDrawCallbackStruct),\n\n \"::\",\n", "file_path": "wrflib/main/bind/glx-sys/src/bindings.rs", "rank": 36, "score": 142686.34118967556 }, { "content": "#[test]\n\nfn bindgen_test_layout__XIMPreeditCaretCallbackStruct() {\n\n assert_eq!(\n\n ::std::mem::size_of::<_XIMPreeditCaretCallbackStruct>(),\n\n 12usize,\n\n concat!(\"Size of: \", stringify!(_XIMPreeditCaretCallbackStruct))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<_XIMPreeditCaretCallbackStruct>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(_XIMPreeditCaretCallbackStruct))\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<_XIMPreeditCaretCallbackStruct>())).position as *const _ as usize\n\n },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(_XIMPreeditCaretCallbackStruct),\n\n \"::\",\n", "file_path": "wrflib/main/bind/x11-sys/src/bindings.rs", "rank": 37, "score": 142686.34118967556 }, { "content": "#[test]\n\nfn bindgen_test_layout__XIMPreeditCaretCallbackStruct() {\n\n assert_eq!(\n\n ::std::mem::size_of::<_XIMPreeditCaretCallbackStruct>(),\n\n 12usize,\n\n concat!(\"Size of: \", stringify!(_XIMPreeditCaretCallbackStruct))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<_XIMPreeditCaretCallbackStruct>(),\n\n 4usize,\n\n concat!(\"Alignment of \", stringify!(_XIMPreeditCaretCallbackStruct))\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<_XIMPreeditCaretCallbackStruct>())).position as *const _ as usize\n\n },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(_XIMPreeditCaretCallbackStruct),\n\n \"::\",\n", "file_path": "wrflib/main/bind/glx-sys/src/bindings.rs", "rank": 38, "score": 142686.34118967556 }, { "content": "#[test]\n\nfn bindgen_test_layout__XIMPreeditStateNotifyCallbackStruct() {\n\n assert_eq!(\n\n ::std::mem::size_of::<_XIMPreeditStateNotifyCallbackStruct>(),\n\n 8usize,\n\n concat!(\n\n \"Size of: \",\n\n stringify!(_XIMPreeditStateNotifyCallbackStruct)\n\n )\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<_XIMPreeditStateNotifyCallbackStruct>(),\n\n 8usize,\n\n concat!(\n\n \"Alignment of \",\n\n stringify!(_XIMPreeditStateNotifyCallbackStruct)\n\n )\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<_XIMPreeditStateNotifyCallbackStruct>())).state as *const _\n", "file_path": "wrflib/main/bind/glx-sys/src/bindings.rs", "rank": 39, "score": 141052.20824205666 }, { "content": "#[test]\n\nfn bindgen_test_layout__XIMPreeditStateNotifyCallbackStruct() {\n\n assert_eq!(\n\n ::std::mem::size_of::<_XIMPreeditStateNotifyCallbackStruct>(),\n\n 8usize,\n\n concat!(\n\n \"Size of: \",\n\n stringify!(_XIMPreeditStateNotifyCallbackStruct)\n\n )\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<_XIMPreeditStateNotifyCallbackStruct>(),\n\n 8usize,\n\n concat!(\n\n \"Alignment of \",\n\n stringify!(_XIMPreeditStateNotifyCallbackStruct)\n\n )\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<_XIMPreeditStateNotifyCallbackStruct>())).state as *const _\n", "file_path": "wrflib/main/bind/x11-sys/src/bindings.rs", "rank": 40, "score": 141052.20824205666 }, { "content": "#[test]\n\nfn bindgen_test_layout__XIMStatusDrawCallbackStruct__bindgen_ty_1() {\n\n assert_eq!(\n\n ::std::mem::size_of::<_XIMStatusDrawCallbackStruct__bindgen_ty_1>(),\n\n 8usize,\n\n concat!(\n\n \"Size of: \",\n\n stringify!(_XIMStatusDrawCallbackStruct__bindgen_ty_1)\n\n )\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<_XIMStatusDrawCallbackStruct__bindgen_ty_1>(),\n\n 8usize,\n\n concat!(\n\n \"Alignment of \",\n\n stringify!(_XIMStatusDrawCallbackStruct__bindgen_ty_1)\n\n )\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<_XIMStatusDrawCallbackStruct__bindgen_ty_1>())).text as *const _\n", "file_path": "wrflib/main/bind/x11-sys/src/bindings.rs", "rank": 41, "score": 139467.9658155979 }, { "content": "#[test]\n\nfn bindgen_test_layout__XIMStatusDrawCallbackStruct__bindgen_ty_1() {\n\n assert_eq!(\n\n ::std::mem::size_of::<_XIMStatusDrawCallbackStruct__bindgen_ty_1>(),\n\n 8usize,\n\n concat!(\n\n \"Size of: \",\n\n stringify!(_XIMStatusDrawCallbackStruct__bindgen_ty_1)\n\n )\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<_XIMStatusDrawCallbackStruct__bindgen_ty_1>(),\n\n 8usize,\n\n concat!(\n\n \"Alignment of \",\n\n stringify!(_XIMStatusDrawCallbackStruct__bindgen_ty_1)\n\n )\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<_XIMStatusDrawCallbackStruct__bindgen_ty_1>())).text as *const _\n", "file_path": "wrflib/main/bind/glx-sys/src/bindings.rs", "rank": 42, "score": 139467.9658155979 }, { "content": "export function addDefaultStyles(): void {\n\n const style = document.createElement(\"style\");\n\n style.innerHTML = `\n\n * {\n\n user-select: none;\n\n }\n\n html, body {\n\n overflow: hidden;\n\n background-color: #333;\n\n }\n\n body {\n\n margin: 0;\n\n position: fixed;\n\n width: 100%;\n\n height: 100%;\n\n }\n\n\n\n #wrflib_js_root {\n\n position: absolute; /* For z-index */\n\n z-index: 0; /* New stacking context */\n\n left: 0;\n\n right: 0;\n\n top: 0;\n\n bottom: 0;\n\n pointer-events: none;\n\n }`;\n\n document.body.appendChild(style);\n", "file_path": "wrflib/web/default_styles.ts", "rank": 43, "score": 136591.2407692962 }, { "content": "fn make_timer(target: id, selector: Sel, time_to_wait: Duration, repeats: bool, user_info: id) -> id {\n\n unsafe {\n\n let pool: id = msg_send![class!(NSAutoreleasePool), new];\n\n let timer: id = msg_send![\n\n class!(NSTimer),\n\n timerWithTimeInterval: time_to_wait.as_secs_f64()\n\n target: target\n\n selector: selector\n\n userInfo: user_info\n\n repeats: repeats\n\n ];\n\n let ns_run_loop: id = msg_send![class!(NSRunLoop), mainRunLoop];\n\n let () = msg_send![ns_run_loop, addTimer: timer forMode: NSRunLoopCommonModes];\n\n let () = msg_send![pool, release];\n\n timer\n\n }\n\n}\n", "file_path": "wrflib/main/src/cx_cocoa.rs", "rank": 44, "score": 133198.53183295063 }, { "content": "/// Renders a tooltip's content\n\n///\n\n/// Implement this trait to render the elements that are shown inside a tooltip. The\n\n/// tooltip's background and current element indicator (small triangle) are not rendered\n\n/// by this function.\n\n///\n\n/// See [`ChartTooltipConfig`] for comments about size and other settings for tooltips.\n\npub trait ChartTooltipRenderer {\n\n /// Draw the tooltip's content\n\n ///\n\n /// Use `pos` to position the elements that need to be rendered.\n\n ///\n\n /// TODO(Hernan): Add support for boxes and other layout mechanisms.\n\n fn draw_tooltip(&self, cx: &mut Cx, config: &ChartConfig, pos: Vec2);\n\n}\n\n\n", "file_path": "wrflib/components/src/chart.rs", "rank": 45, "score": 131557.6050506264 }, { "content": "/// Adapted from [`std::io::Cursor`].\n\nfn update_pos(pos: &mut u64, size: u64, style: std::io::SeekFrom) -> std::io::Result<u64> {\n\n let (base_pos, offset) = match style {\n\n std::io::SeekFrom::Start(n) => {\n\n *pos = n;\n\n return Ok(n);\n\n }\n\n std::io::SeekFrom::End(n) => (size, n),\n\n std::io::SeekFrom::Current(n) => (*pos, n),\n\n };\n\n let new_pos =\n\n if offset >= 0 { base_pos.checked_add(offset as u64) } else { base_pos.checked_sub((offset.wrapping_neg()) as u64) };\n\n match new_pos {\n\n Some(n) => {\n\n *pos = n;\n\n Ok(*pos)\n\n }\n\n None => Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, \"invalid seek to a negative or overflowing position\")),\n\n }\n\n}\n\nimpl std::io::Seek for UniversalFile {\n", "file_path": "wrflib/main/src/universal_file.rs", "rank": 46, "score": 130015.75882490014 }, { "content": "// Helper function to dynamically load function pointer.\n\n// `library` and `function` must be zero-terminated.\n\nfn get_function_impl(library: &str, function: &str) -> Option<*const c_void> {\n\n // Library names we will use are ASCII so we can use the A version to avoid string conversion.\n\n let module = unsafe { LoadLibraryA(library.as_ptr() as LPCSTR) };\n\n if module.is_null() {\n\n return None;\n\n }\n\n\n\n let function_ptr = unsafe { GetProcAddress(module, function.as_ptr() as LPCSTR) };\n\n if function_ptr.is_null() {\n\n return None;\n\n }\n\n\n\n Some(function_ptr as _)\n\n}\n\n\n\nmacro_rules! get_function {\n\n ( $ lib: expr, $ func: ident) => {\n\n get_function_impl(concat!($lib, '\\0'), concat!(stringify!($func), '\\0'))\n\n .map(|f| unsafe { mem::transmute::<*const _, $func>(f) })\n\n };\n", "file_path": "wrflib/main/src/cx_win32.rs", "rank": 47, "score": 126552.7172565995 }, { "content": "pub fn derive_ser_json_impl(input: TokenStream) -> TokenStream {\n\n let mut parser = TokenParser::new(input);\n\n let mut tb = TokenBuilder::new();\n\n\n\n parser.eat_ident(\"pub\");\n\n if parser.eat_ident(\"struct\") {\n\n if let Some(name) = parser.eat_any_ident() {\n\n let generic = parser.eat_generic();\n\n let types = parser.eat_all_types();\n\n let where_clause = parser.eat_where_clause(Some(\"SerJson\"));\n\n\n\n tb.add(\"impl\").stream(generic.clone());\n\n tb.add(\"SerJson for\").ident(&name).stream(generic).stream(where_clause);\n\n tb.add(\"{ fn ser_json ( & self , d : usize , s : & mut bigedit_microserde :: SerJsonState ) {\");\n\n\n\n if let Some(types) = types {\n\n tb.add(\"s . out . push (\").chr('[').add(\") ;\");\n\n for i in 0..types.len() {\n\n tb.add(\"self .\").unsuf_usize(i).add(\". ser_json ( d , s ) ;\");\n\n if i != types.len() - 1 {\n", "file_path": "wrflib/examples/example_bigedit/microserde/derive/src/derive_json.rs", "rank": 48, "score": 125130.17482242936 }, { "content": "pub fn derive_de_json_impl(input: TokenStream) -> TokenStream {\n\n let mut parser = TokenParser::new(input);\n\n let mut tb = TokenBuilder::new();\n\n\n\n parser.eat_ident(\"pub\");\n\n if parser.eat_ident(\"struct\") {\n\n if let Some(name) = parser.eat_any_ident() {\n\n let generic = parser.eat_generic();\n\n let types = parser.eat_all_types();\n\n let where_clause = parser.eat_where_clause(Some(\"DeJson\"));\n\n\n\n tb.add(\"impl\").stream(generic.clone());\n\n tb.add(\"DeJson for\").ident(&name).stream(generic).stream(where_clause);\n\n tb.add(\"{ fn de_json ( s : & mut bigedit_microserde :: DeJsonState , i : & mut std :: str :: Chars )\");\n\n tb.add(\"-> std :: result :: Result < Self , bigedit_microserde :: DeJsonErr > { \");\n\n\n\n if let Some(types) = types {\n\n tb.add(\"s . block_open ( i ) ? ;\");\n\n tb.add(\"let r = Self\");\n\n tb.add(\"(\");\n", "file_path": "wrflib/examples/example_bigedit/microserde/derive/src/derive_json.rs", "rank": 49, "score": 125130.17482242936 }, { "content": "pub fn derive_de_ron_impl(input: TokenStream) -> TokenStream {\n\n let mut parser = TokenParser::new(input);\n\n let mut tb = TokenBuilder::new();\n\n parser.eat_ident(\"pub\");\n\n if parser.eat_ident(\"struct\") {\n\n if let Some(name) = parser.eat_any_ident() {\n\n let generic = parser.eat_generic();\n\n let types = parser.eat_all_types();\n\n let where_clause = parser.eat_where_clause(Some(\"DeRon\"));\n\n\n\n tb.add(\"impl\").stream(generic.clone());\n\n tb.add(\"DeRon for\").ident(&name).stream(generic).stream(where_clause);\n\n tb.add(\"{ fn de_ron ( s : & mut bigedit_microserde :: DeRonState , i : & mut std :: str :: Chars )\");\n\n tb.add(\"-> std :: result :: Result < Self , bigedit_microserde :: DeRonErr > { \");\n\n\n\n if let Some(types) = types {\n\n tb.add(\"s . paren_open ( i ) ? ;\");\n\n tb.add(\"let r = Self\");\n\n tb.add(\"(\");\n\n for _ in 0..types.len() {\n", "file_path": "wrflib/examples/example_bigedit/microserde/derive/src/derive_ron.rs", "rank": 50, "score": 125130.17482242936 }, { "content": "pub fn derive_de_bin_impl(input: TokenStream) -> TokenStream {\n\n let mut parser = TokenParser::new(input);\n\n let mut tb = TokenBuilder::new();\n\n\n\n parser.eat_ident(\"pub\");\n\n if parser.eat_ident(\"struct\") {\n\n if let Some(name) = parser.eat_any_ident() {\n\n let generic = parser.eat_generic();\n\n let types = parser.eat_all_types();\n\n let where_clause = parser.eat_where_clause(Some(\"DeBin\"));\n\n\n\n tb.add(\"impl\").stream(generic.clone());\n\n tb.add(\"DeBin for\").ident(&name).stream(generic).stream(where_clause);\n\n tb.add(\"{ fn de_bin ( o : & mut usize , d : & [ u8 ] )\");\n\n tb.add(\"-> std :: result :: Result < Self , bigedit_microserde :: DeBinErr > { \");\n\n tb.add(\"std :: result :: Result :: Ok ( Self\");\n\n\n\n if let Some(types) = types {\n\n tb.add(\"(\");\n\n for _ in 0..types.len() {\n", "file_path": "wrflib/examples/example_bigedit/microserde/derive/src/derive_bin.rs", "rank": 51, "score": 125130.17482242936 }, { "content": "pub fn derive_ser_ron_impl(input: TokenStream) -> TokenStream {\n\n let mut parser = TokenParser::new(input);\n\n let mut tb = TokenBuilder::new();\n\n\n\n parser.eat_ident(\"pub\");\n\n if parser.eat_ident(\"struct\") {\n\n if let Some(name) = parser.eat_any_ident() {\n\n let generic = parser.eat_generic();\n\n let types = parser.eat_all_types();\n\n let where_clause = parser.eat_where_clause(Some(\"SerRon\"));\n\n\n\n tb.add(\"impl\").stream(generic.clone());\n\n tb.add(\"SerRon for\").ident(&name).stream(generic).stream(where_clause);\n\n tb.add(\"{ fn ser_ron ( & self , d : usize , s : & mut bigedit_microserde :: SerRonState ) {\");\n\n\n\n if let Some(types) = types {\n\n tb.add(\"s . out . push (\").chr('(').add(\") ;\");\n\n for i in 0..types.len() {\n\n tb.add(\"self .\").unsuf_usize(i).add(\". ser_ron ( d , s ) ;\");\n\n if i != types.len() - 1 {\n", "file_path": "wrflib/examples/example_bigedit/microserde/derive/src/derive_ron.rs", "rank": 52, "score": 125130.17482242936 }, { "content": "pub fn derive_ser_bin_impl(input: TokenStream) -> TokenStream {\n\n let mut parser = TokenParser::new(input);\n\n let mut tb = TokenBuilder::new();\n\n\n\n parser.eat_ident(\"pub\");\n\n if parser.eat_ident(\"struct\") {\n\n if let Some(name) = parser.eat_any_ident() {\n\n let generic = parser.eat_generic();\n\n let types = parser.eat_all_types();\n\n let where_clause = parser.eat_where_clause(Some(\"SerBin\"));\n\n\n\n tb.add(\"impl\").stream(generic.clone());\n\n tb.add(\"SerBin for\").ident(&name).stream(generic).stream(where_clause);\n\n tb.add(\"{ fn ser_bin ( & self , s : & mut Vec < u8 > ) {\");\n\n\n\n if let Some(types) = types {\n\n for i in 0..types.len() {\n\n tb.add(\"self .\").unsuf_usize(i).add(\". ser_bin ( s ) ;\");\n\n }\n\n } else if let Some(fields) = parser.eat_all_struct_fields() {\n", "file_path": "wrflib/examples/example_bigedit/microserde/derive/src/derive_bin.rs", "rank": 53, "score": 125130.17482242936 }, { "content": "\n\nimpl Default for TooltipCustomExample {\n\n fn default() -> Self {\n\n let tooltip = Arc::new(RwLock::new(Tooltip::default()));\n\n Self {\n\n base: LinesBasic {\n\n tooltip: ChartTooltipConfig { size: vec2(200., 60.), renderer: Some(tooltip.clone()) },\n\n ..LinesBasic::default()\n\n },\n\n tooltip,\n\n }\n\n }\n\n}\n\n\n\nimpl ChartExample for TooltipCustomExample {\n\n fn handle(&mut self, cx: &mut Cx, event: &mut Event) -> ChartEvent {\n\n if let ChartEvent::PointerHover { current_element: Some(current_element), .. } = self.base.handle(cx, event) {\n\n let mut write = self.tooltip.write().unwrap();\n\n write.value = current_element.data_point.y;\n\n write.path = format!(\"{:.0}\", current_element.data_point.x);\n", "file_path": "wrflib/examples/example_charts/src/tooltip_custom.rs", "rank": 54, "score": 121141.20591803826 }, { "content": "use std::sync::{Arc, RwLock};\n\n\n\nuse wrflib::*;\n\n\n\nuse crate::*;\n\n\n\n#[derive(Default)]\n", "file_path": "wrflib/examples/example_charts/src/tooltip_custom.rs", "rank": 55, "score": 121131.73069457935 }, { "content": " }\n\n\n\n ChartEvent::None\n\n }\n\n\n\n fn draw(&mut self, cx: &mut Cx) {\n\n self.base.draw(cx);\n\n }\n\n}\n", "file_path": "wrflib/examples/example_charts/src/tooltip_custom.rs", "rank": 56, "score": 121118.2093519112 }, { "content": "#[derive(Default, Debug)]\n\nstruct BuildOpts {\n\n release: bool,\n\n use_simd128: bool,\n\n all_targets: bool,\n\n workspace: bool,\n\n package: String,\n\n features: String,\n\n}\n\n\n", "file_path": "wrflib/cargo-wrflib/src/main.rs", "rank": 57, "score": 105733.06299742885 }, { "content": "#[derive(Clone, Default)]\n\n#[repr(C)]\n\nstruct BorderIns {\n\n quad: QuadIns,\n\n}\n\n\n\n/// Draws small border around the provided rect with transparent background\n\nstatic BORDER_SHADER: Shader = Shader {\n\n build_geom: Some(QuadIns::build_geom),\n\n code_to_concatenate: &[\n\n Cx::STD_SHADER,\n\n QuadIns::SHADER,\n\n code_fragment!(\n\n r#\"\n\n fn pixel() -> vec4 {\n\n let transparent = vec4(0.0, 0.0, 0.0, 0.0);\n\n let m = 1.0;\n\n let abs_pos = pos * rect_size;\n\n if abs_pos.x < m || abs_pos.y < m || abs_pos.x > rect_size.x - m || abs_pos.y > rect_size.y - m {\n\n return vec4(1., 1., 0.5, 1.0);\n\n } else {\n\n return transparent;\n", "file_path": "wrflib/main/src/debugger.rs", "rank": 58, "score": 105376.27665866252 }, { "content": "#[derive(Clone, Default)]\n\n#[repr(C)]\n\nstruct CheckboxIns {\n\n base: QuadIns,\n\n checked: f32,\n\n loaded: f32,\n\n errored: f32,\n\n hover: f32,\n\n down: f32,\n\n}\n\n\n\nstatic SHADER: Shader = Shader {\n\n build_geom: Some(QuadIns::build_geom),\n\n code_to_concatenate: &[\n\n Cx::STD_SHADER,\n\n QuadIns::SHADER,\n\n code_fragment!(\n\n r#\"\n\n uniform time: float;\n\n instance checked: float;\n\n instance loaded: float;\n\n instance errored: float;\n", "file_path": "wrflib/components/src/checkbox.rs", "rank": 59, "score": 105376.27665866252 }, { "content": "#[derive(Clone, Default)]\n\n#[repr(C)]\n\nstruct TabIns {\n\n base: QuadIns,\n\n color: Vec4,\n\n border_color: Vec4,\n\n}\n\n\n\nstatic SHADER: Shader = Shader {\n\n build_geom: Some(QuadIns::build_geom),\n\n code_to_concatenate: &[\n\n Cx::STD_SHADER,\n\n QuadIns::SHADER,\n\n code_fragment!(\n\n r#\"\n\n instance color: vec4;\n\n instance border_color: vec4;\n\n const border_width: float = 1.0;\n\n\n\n fn pixel() -> vec4 {\n\n let df = Df::viewport(pos * rect_size);\n\n df.rect(vec2(-1.), rect_size + 2.);\n", "file_path": "wrflib/components/src/tab.rs", "rank": 60, "score": 105376.27665866252 }, { "content": "#[derive(Clone, Default)]\n\n#[repr(C)]\n\nstruct BackgroundIns {\n\n quad: QuadIns,\n\n color: Vec4,\n\n radius: f32,\n\n}\n\n\n\nstatic SHADER: Shader = Shader {\n\n build_geom: Some(QuadIns::build_geom),\n\n code_to_concatenate: &[\n\n Cx::STD_SHADER,\n\n QuadIns::SHADER,\n\n code_fragment!(\n\n r#\"\n\n instance color: vec4;\n\n instance radius: float;\n\n fn pixel() -> vec4 {\n\n // TODO(JP): Giant hack! We should just be able to call df.box with radius=0\n\n // and then df.fill, but df.box with radius=0 seems totally broken, and even\n\n // using df.rect with df.fill seems to leave a gap around the border..\n\n if radius < 0.001 {\n", "file_path": "wrflib/components/src/background.rs", "rank": 61, "score": 105376.27665866252 }, { "content": "struct MyClient {\n\n context_menu_handler: Arc<MyContextMenuHandler>,\n\n #[cfg(feature = \"cef-server\")]\n\n request_handler: Arc<MyRequestHandler>,\n\n}\n\nimpl Client for MyClient {\n\n type OutContextMenuHandler = MyContextMenuHandler;\n\n type OutRequestHandler = MyRequestHandler;\n\n\n\n fn get_context_menu_handler(&self) -> Option<Arc<Self::OutContextMenuHandler>> {\n\n Some(self.context_menu_handler.clone())\n\n }\n\n\n\n fn get_request_handler(&self) -> Option<Arc<Self::OutRequestHandler>> {\n\n #[cfg(not(feature = \"cef-server\"))]\n\n {\n\n None\n\n }\n\n\n\n #[cfg(feature = \"cef-server\")]\n", "file_path": "wrflib/main/src/cef_browser.rs", "rank": 62, "score": 105369.87051995563 }, { "content": "struct MyApp {\n\n render_process_handler: Arc<MyRenderProcessHandler>,\n\n browser_process_handler: Arc<MyBrowserProcessHandler>,\n\n}\n\n\n\nimpl App for MyApp {\n\n type OutBrowserProcessHandler = MyBrowserProcessHandler;\n\n type OutRenderProcessHandler = MyRenderProcessHandler;\n\n\n\n fn on_before_command_line_processing(&self, _process_type: &str, command_line: &CommandLine) {\n\n // Disable the macOS keychain prompt. Cookies will not be encrypted.\n\n #[cfg(target_os = \"macos\")]\n\n command_line.append_switch(\"use-mock-keychain\");\n\n\n\n // We use the `--single-process` flag in Chromium, which the docs say is not very well supported,\n\n // but which seems to be (kind of) used in Android Webviews anyway so it might not be too bad.\n\n // If we don't do this we will get different processes for managing the window vs rendering, which\n\n // will require a major overhaul of wrflib.\n\n command_line.append_switch(\"single-process\");\n\n }\n\n\n\n fn get_render_process_handler(&self) -> Option<Arc<Self::OutRenderProcessHandler>> {\n\n Some(self.render_process_handler.clone())\n\n }\n\n\n\n fn get_browser_process_handler(&self) -> Option<Arc<Self::OutBrowserProcessHandler>> {\n\n Some(self.browser_process_handler.clone())\n\n }\n\n}\n\n\n", "file_path": "wrflib/main/src/cef_browser.rs", "rank": 63, "score": 105369.87051995563 }, { "content": "#[derive(Default)]\n\nstruct MetalBuffer {\n\n inner: Option<MetalBufferInner>,\n\n}\n\n\n\nimpl MetalBuffer {\n\n fn update<T>(&mut self, metal_cx: &MetalCx, data: &[T]) {\n\n let len = data.len() * std::mem::size_of::<T>();\n\n if len == 0 {\n\n self.inner = None;\n\n return;\n\n }\n\n if self.inner.as_ref().map_or(0, |inner| inner.len) < len {\n\n self.inner = Some(MetalBufferInner {\n\n len,\n\n buffer: RcObjcId::from_owned(\n\n NonNull::new(unsafe {\n\n msg_send![\n\n metal_cx.device,\n\n newBufferWithLength: len as u64\n\n options: nil\n", "file_path": "wrflib/main/src/cx_metal.rs", "rank": 64, "score": 104202.47799297646 }, { "content": "#[derive(Clone, Default)]\n\n#[repr(C)]\n\nstruct ScrollShadowIns {\n\n base: QuadIns,\n\n shadow_top: f32,\n\n}\n\n\n\nstatic SHADER: Shader = Shader {\n\n build_geom: Some(QuadIns::build_geom),\n\n code_to_concatenate: &[\n\n Cx::STD_SHADER,\n\n QuadIns::SHADER,\n\n code_fragment!(\n\n r#\"\n\n instance shadow_top: float;\n\n varying is_viz: float;\n\n\n\n fn scroll() -> vec2 {\n\n if shadow_top > 0.5 {\n\n is_viz = clamp(draw_local_scroll.y * 0.1, 0., 1.);\n\n }\n\n else {\n", "file_path": "wrflib/components/src/scrollshadow.rs", "rank": 65, "score": 104202.30450396056 }, { "content": "#[derive(Clone, Default)]\n\n#[repr(C)]\n\nstruct FoldCaptionIns {\n\n base: QuadIns,\n\n hover: f32,\n\n down: f32,\n\n open: f32,\n\n}\n\n\n\nstatic SHADER: Shader = Shader {\n\n build_geom: Some(QuadIns::build_geom),\n\n code_to_concatenate: &[\n\n Cx::STD_SHADER,\n\n QuadIns::SHADER,\n\n code_fragment!(\n\n r#\"\n\n instance hover: float;\n\n instance down: float;\n\n instance open: float;\n\n\n\n const shadow: float = 3.0;\n\n const border_radius: float = 2.5;\n", "file_path": "wrflib/components/src/foldcaption.rs", "rank": 66, "score": 104202.30450396056 }, { "content": "#[derive(Clone, Default)]\n\n#[repr(C)]\n\nstruct FloatSliderIns {\n\n base: QuadIns,\n\n norm_value: f32,\n\n hover: f32,\n\n down: f32,\n\n}\n\n\n\npub enum FloatSliderEvent {\n\n Change { scaled_value: f32 },\n\n DoneChanging,\n\n None,\n\n}\n\n\n\npub struct FloatSlider {\n\n component_id: ComponentId,\n\n scaled_value: f32,\n\n norm_value: f32,\n\n animator: Animator,\n\n min: f32,\n\n max: f32,\n", "file_path": "wrflib/components/src/floatslider.rs", "rank": 67, "score": 104202.30450396056 }, { "content": "struct MyResourceHandler {\n\n url: RwLock<String>,\n\n mime_type: RwLock<Option<String>>,\n\n contents: RwLock<Option<BufReader<File>>>,\n\n get_resource_url_callback: Option<GetResourceUrlCallback>,\n\n}\n\n\n\nimpl ResourceHandler for MyResourceHandler {\n\n fn open(&self, url: &str) -> bool {\n\n if self.contents.read().unwrap().is_some() {\n\n panic!(\"Already loading this file!!!\")\n\n }\n\n\n\n let url = {\n\n if let Some(callback) = self.get_resource_url_callback {\n\n #[cfg(not(all(target_os = \"macos\", feature = \"cef-server\")))]\n\n let current_directory = \"\".to_string();\n\n\n\n #[cfg(all(target_os = \"macos\", feature = \"cef-server\"))]\n\n let current_directory = get_bundle_directory();\n", "file_path": "wrflib/main/src/cef_browser.rs", "rank": 68, "score": 104195.89836525367 }, { "content": "struct DndAtoms {\n\n action_private: X11_sys::Atom,\n\n aware: X11_sys::Atom,\n\n drop: X11_sys::Atom,\n\n enter: X11_sys::Atom,\n\n leave: X11_sys::Atom,\n\n none: X11_sys::Atom,\n\n position: X11_sys::Atom,\n\n selection: X11_sys::Atom,\n\n status: X11_sys::Atom,\n\n type_list: X11_sys::Atom,\n\n uri_list: X11_sys::Atom,\n\n}\n\n\n\nimpl DndAtoms {\n\n unsafe fn new(display: *mut X11_sys::Display) -> DndAtoms {\n\n DndAtoms {\n\n action_private: X11_sys::XInternAtom(display, CString::new(\"XdndActionPrivate\").unwrap().as_ptr(), 0),\n\n aware: X11_sys::XInternAtom(display, CString::new(\"XdndAware\").unwrap().as_ptr(), 0),\n\n drop: X11_sys::XInternAtom(display, CString::new(\"XdndDrop\").unwrap().as_ptr(), 0),\n", "file_path": "wrflib/main/src/cx_xlib.rs", "rank": 69, "score": 104195.89836525367 }, { "content": "#[cfg(target_arch = \"wasm32\")]\n\nstruct WorkerContext {\n\n func: Box<dyn FnOnce() + Send>,\n\n}\n\n\n\n#[cfg(target_arch = \"wasm32\")]\n\nimpl Thread for UniversalThread {\n\n /// See [`Thread::spawn`].\n\n fn spawn(f: impl FnOnce() + Send + 'static) {\n\n let context = Box::into_raw(Box::new(WorkerContext { func: Box::new(f) })) as usize;\n\n\n\n unsafe {\n\n threadSpawn(context as u64);\n\n }\n\n }\n\n\n\n /// See [`Thread::sleep`].\n\n fn sleep(dur: Duration) {\n\n thread::sleep(dur);\n\n }\n\n}\n", "file_path": "wrflib/main/src/universal_thread.rs", "rank": 70, "score": 104195.89836525367 }, { "content": "struct MyRequestHandler {\n\n handlers: RwLock<Vec<Arc<MyResourceRequestHandler>>>,\n\n get_resource_url_callback: Option<GetResourceUrlCallback>,\n\n}\n\n\n\nimpl RequestHandler for MyRequestHandler {\n\n type OutResourceRequestHandler = MyResourceRequestHandler;\n\n\n\n fn get_resource_request_handler(&self, url: &str) -> Option<Arc<Self::OutResourceRequestHandler>> {\n\n let handler = Arc::new(MyResourceRequestHandler {\n\n resource_handler: Arc::new(MyResourceHandler {\n\n url: RwLock::new(url.to_string()),\n\n mime_type: RwLock::new(None),\n\n contents: RwLock::new(None),\n\n get_resource_url_callback: self.get_resource_url_callback,\n\n }),\n\n });\n\n\n\n self.handlers.write().unwrap().push(handler.clone());\n\n Some(handler)\n\n }\n\n}\n\n\n", "file_path": "wrflib/main/src/cef_browser.rs", "rank": 71, "score": 104195.89836525367 }, { "content": "#[repr(C)]\n\nstruct DrawLines3dUniforms {\n\n vertex_transform: Mat4,\n\n}\n\n\n\n/// Renderer for line markers.\n\n///\n\n/// In order to support custom like thickness, we render each line segment using 2D quads\n\n/// which are transformed accordingly. Line segments are represented by two 3D points\n\n/// (start and end) and each of them can have different colors to support gradients. In addition,\n\n/// each line segment also gets the point before and the point after, so we can compute the corners\n\n/// correctly. For individual line segments, we don't need to handle the corner.\n\n///\n\n/// Each of the 4 points in the 2D quad is transformed by computing a normal vector multipled\n\n/// by a thickness value.\n\n///\n\n/// Roughly an individual line segment looks like:\n\n/// TL - - - .TR\n\n/// | ,.-' |\n\n/// A/B - - -,.-' - - C/D\n\n/// | ,.-' |\n", "file_path": "wrflib/components/src/drawlines3d.rs", "rank": 72, "score": 104195.89836525367 }, { "content": "#[derive(Clone, Copy, Debug)]\n\nstruct Event {\n\n point: Point,\n\n pending_segment: Option<PendingSegment>,\n\n}\n\n\n\nimpl Eq for Event {}\n\n\n\nimpl Ord for Event {\n\n fn cmp(&self, other: &Event) -> Ordering {\n\n self.point.partial_cmp(&other.point).unwrap().reverse()\n\n }\n\n}\n\n\n\nimpl PartialEq for Event {\n\n fn eq(&self, other: &Event) -> bool {\n\n self.cmp(other) == Ordering::Equal\n\n }\n\n}\n\n\n\nimpl PartialOrd for Event {\n\n fn partial_cmp(&self, other: &Event) -> Option<Ordering> {\n\n Some(self.cmp(other))\n\n }\n\n}\n\n\n", "file_path": "wrflib/main/vector/src/trapezoidator/mod.rs", "rank": 73, "score": 104195.89836525367 }, { "content": "#[derive(Debug)]\n\nstruct Interner {\n\n strings: Vec<String>,\n\n indices: HashMap<String, usize>,\n\n}\n\n\n\nstatic mut INTERNER: *mut Interner = std::ptr::null_mut();\n\n\n\nimpl Interner {\n\n fn get_singleton() -> &'static mut Interner {\n\n unsafe {\n\n if INTERNER.is_null() {\n\n INTERNER = Box::into_raw(Box::new(Interner {\n\n strings: {\n\n let mut v = Vec::new();\n\n v.push(\"\".to_string());\n\n v\n\n },\n\n indices: {\n\n let mut h = HashMap::new();\n\n h.insert(\"\".to_string(), 0);\n", "file_path": "wrflib/main/shader_compiler/src/ident.rs", "rank": 74, "score": 104195.89836525367 }, { "content": "#[derive(Clone, Copy, PartialEq)]\n\n#[repr(C)]\n\nstruct MwmHints {\n\n pub(crate) flags: c_ulong,\n\n pub(crate) functions: c_ulong,\n\n pub(crate) decorations: c_ulong,\n\n pub(crate) input_mode: c_long,\n\n pub(crate) status: c_ulong,\n\n}\n\n\n\nconst MWM_HINTS_FUNCTIONS: c_ulong = 1 << 0;\n\nconst MWM_HINTS_DECORATIONS: c_ulong = 1 << 1;\n\n\n\nconst MWM_FUNC_ALL: c_ulong = 1 << 0;\n\nconst MWM_FUNC_RESIZE: c_ulong = 1 << 1;\n\nconst MWM_FUNC_MOVE: c_ulong = 1 << 2;\n\nconst MWM_FUNC_MINIMIZE: c_ulong = 1 << 3;\n\nconst MWM_FUNC_MAXIMIZE: c_ulong = 1 << 4;\n\nconst MWM_FUNC_CLOSE: c_ulong = 1 << 5;\n\nconst _NET_WM_MOVERESIZE_SIZE_TOPLEFT: c_long = 0;\n\nconst _NET_WM_MOVERESIZE_SIZE_TOP: c_long = 1;\n\nconst _NET_WM_MOVERESIZE_SIZE_TOPRIGHT: c_long = 2;\n", "file_path": "wrflib/main/src/cx_xlib.rs", "rank": 75, "score": 104195.89836525367 }, { "content": "#[repr(C)]\n\nstruct DrawPoints3dUniforms {\n\n rect_size: Vec2,\n\n use_screen_space: f32,\n\n point_style: f32,\n\n vertex_transform: Mat4,\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub enum DrawPoints3dStyle {\n\n Quad,\n\n Circle,\n\n}\n\n\n\nconst POINT_STYLE_QUAD: f32 = 0.0;\n\nconst POINT_STYLE_CIRCLE: f32 = 1.0;\n\n\n\npub struct DrawPoints3dOptions {\n\n pub use_screen_space: bool,\n\n pub point_style: DrawPoints3dStyle,\n\n /// Custom transformation to do on all vertices\n", "file_path": "wrflib/components/src/drawpoints3d.rs", "rank": 76, "score": 104195.89836525367 }, { "content": "struct PerfPoint {\n\n timestamp: f64,\n\n value: f64,\n\n}\n\n\n\nconst AVERAGE_RANGE: f64 = 5.;\n\nconst TOP_PADDING: f32 = 5.;\n\nconst NUM_SAMPLES: usize = 300;\n\n\n", "file_path": "wrflib/components/src/fps_counter.rs", "rank": 77, "score": 104195.89836525367 }, { "content": "#[repr(C)]\n\n#[derive(Debug, Clone)]\n\nstruct Instance {\n\n normal: Vec3,\n\n}\n\n\n\nstatic SHADER: Shader = Shader {\n\n code_to_concatenate: &[\n\n Cx::STD_SHADER,\n\n Geometry3d::SHADER,\n\n code_fragment!(\n\n r#\"\n\n // TODO(JP): Make it so you can just render a single geometry without having to use instancing.\n\n // Since we still need instancing we need a dummy value here.\n\n instance _dummy: float;\n\n\n\n fn vertex() -> vec4 {\n\n return camera_projection * camera_view * vec4(geom_pos, 1.);\n\n }\n\n\n\n fn pixel() -> vec4 {\n\n let lightPosition = vec3(20.,0.,30.);\n\n let lightDirection = normalize(geom_pos - lightPosition);\n\n return vec4(vec3(clamp(dot(-lightDirection, geom_normal), 0.2, 1.0)),1.0);\n\n }\n\n \"#\n\n ),\n\n ],\n\n ..Shader::DEFAULT\n\n};\n\n\n", "file_path": "wrflib/examples/test_geometry/src/main.rs", "rank": 78, "score": 104195.89836525367 }, { "content": "#[derive(Clone)]\n\n#[repr(C)]\n\nstruct IndentLinesIns {\n\n quad: QuadIns,\n\n color: Vec4,\n\n indent_id: f32,\n\n}\n\npub struct IndentLines {\n\n indent_sel: f32,\n\n area: Area,\n\n instances: Vec<IndentLinesIns>,\n\n}\n\nimpl IndentLines {\n\n fn new() -> Self {\n\n Self { area: Area::Empty, indent_sel: Default::default(), instances: Default::default() }\n\n }\n\n fn write_uniforms(&self, cx: &mut Cx) {\n\n self.area.write_user_uniforms(cx, self.indent_sel);\n\n }\n\n fn set_indent_sel(&mut self, cx: &mut Cx, v: f32) {\n\n self.indent_sel = v;\n\n self.write_uniforms(cx);\n", "file_path": "wrflib/components/src/texteditor.rs", "rank": 79, "score": 104195.89836525367 }, { "content": "/// See [`Thread`].\n\nstruct UniversalThread();\n\n\n", "file_path": "wrflib/main/src/universal_thread.rs", "rank": 80, "score": 104195.89836525367 }, { "content": "#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\n\nstruct Region {\n\n is_inside: bool,\n\n winding: i32,\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::geometry::{Point, Transform, Transformation};\n\n use crate::path::PathCommand;\n\n use crate::path::PathIterator;\n\n use std::iter::Cloned;\n\n use std::slice::Iter;\n\n\n\n /// A sequence of commands that defines a set of contours, each of which consists of a sequence of\n\n /// curve segments. Each contour is either open or closed.\n\n #[derive(Clone, Debug, Default, PartialEq)]\n\n pub(crate) struct Path {\n\n verbs: Vec<Verb>,\n\n points: Vec<Point>,\n", "file_path": "wrflib/main/vector/src/trapezoidator/mod.rs", "rank": 81, "score": 104195.89836525367 }, { "content": "#[derive(Clone)]\n\n#[repr(C)]\n\nstruct ColorBackgroundIns {\n\n quad: QuadIns,\n\n color: Vec4,\n\n}\n\npub struct ColorBackground {\n\n shader: &'static Shader,\n\n color: Vec4,\n\n}\n\nimpl ColorBackground {\n\n fn new(shader: &'static Shader) -> Self {\n\n Self { shader, color: Default::default() }\n\n }\n\n\n\n fn draw_quad_abs(&self, cx: &mut Cx, rect: Rect) {\n\n cx.add_instances(self.shader, &[ColorBackgroundIns { quad: QuadIns::from_rect(rect), color: self.color }]);\n\n }\n\n}\n\n\n", "file_path": "wrflib/components/src/texteditor.rs", "rank": 82, "score": 104195.89836525367 }, { "content": "fn main() {\n\n let matches = App::new(\"WRFlib Command Line Tool\")\n\n .setting(AppSettings::ArgRequiredElseHelp)\n\n .about(env![\"CARGO_PKG_DESCRIPTION\"])\n\n .version(env!(\"CARGO_PKG_VERSION\"))\n\n // When running as a cargo command, the second argument is the name of the program\n\n // and we want to ignore it when displaying help\n\n .arg(Arg::new(\"crate-version\").hide(true))\n\n .subcommand(\n\n App::new(\"install-deps\")\n\n .arg(\n\n Arg::new(\"devel\")\n\n .short('D')\n\n .long(\"devel\")\n\n .takes_value(false)\n\n .help(\"Install additional dependencies for WRFlib development.\"),\n\n )\n\n .arg(Arg::new(\"ci\").long(\"ci\").takes_value(false).help(\"Install dependencies for CI\")),\n\n )\n\n .subcommand(\n", "file_path": "wrflib/cargo-wrflib/src/main.rs", "rank": 83, "score": 103632.78894828216 }, { "content": "#[derive(Default)]\n\nstruct App {\n\n window: Window,\n\n pass: Pass,\n\n view: View,\n\n button: Button,\n\n counter: i32,\n\n slider: FloatSlider,\n\n scroll_view: ScrollView,\n\n}\n\n\n\nimpl App {\n\n fn new(_cx: &mut Cx) -> Self {\n\n App { scroll_view: ScrollView::new_standard_vh(), ..Self::default() }\n\n }\n\n\n\n fn handle(&mut self, cx: &mut Cx, event: &mut Event) {\n\n if let ButtonEvent::Clicked = self.button.handle(cx, event) {\n\n self.counter += 1;\n\n cx.request_draw();\n\n }\n", "file_path": "wrflib/examples/tutorial_ui_components/src/main.rs", "rank": 84, "score": 103070.05593677296 }, { "content": "#[derive(Default)]\n\nstruct App {\n\n window: Window,\n\n pass: Pass,\n\n view: View,\n\n viewport_3d: Viewport3D,\n\n geometry: Option<GpuGeometry>,\n\n}\n\n\n", "file_path": "wrflib/examples/tutorial_3d_rendering/step3/src/main.rs", "rank": 85, "score": 103070.05593677296 }, { "content": "#[derive(Default)]\n\nstruct App {\n\n window: Window,\n\n pass: Pass,\n\n view: View,\n\n}\n\n\n\nimpl App {\n\n fn new(_cx: &mut Cx) -> Self {\n\n Self::default()\n\n }\n\n\n\n fn handle(&mut self, _cx: &mut Cx, _event: &mut Event) {}\n\n\n\n fn draw(&mut self, cx: &mut Cx) {\n\n self.window.begin_window(cx);\n\n self.pass.begin_pass(cx, Vec4::color(\"0\"));\n\n self.view.begin_view(cx, LayoutSize::FILL);\n\n\n\n let rect1 = RectIns {\n\n quad: QuadIns { rect_pos: vec2(50., 50.), rect_size: vec2(400., 200.), draw_depth: 0. },\n", "file_path": "wrflib/examples/tutorial_2d_rendering/step3/src/main.rs", "rank": 86, "score": 103070.05593677296 }, { "content": "#[derive(Default)]\n\nstruct App {\n\n window: Window,\n\n pass: Pass,\n\n view: View,\n\n}\n\n\n\nimpl App {\n\n fn new(_cx: &mut Cx) -> Self {\n\n Self::default()\n\n }\n\n\n\n fn handle(&mut self, _cx: &mut Cx, _event: &mut Event) {}\n\n\n\n fn draw(&mut self, cx: &mut Cx) {\n\n self.window.begin_window(cx);\n\n self.pass.begin_pass(cx, Vec4::color(\"0\"));\n\n self.view.begin_view(cx, LayoutSize::FILL);\n\n\n\n let color = vec4(1., 0., 0., 1.);\n\n cx.add_instances(&SHADER, &[RectIns { color }]);\n\n\n\n self.view.end_view(cx);\n\n self.pass.end_pass(cx);\n\n self.window.end_window(cx);\n\n }\n\n}\n\n\n\nmain_app!(App);\n", "file_path": "wrflib/examples/tutorial_2d_rendering/step1/src/main.rs", "rank": 87, "score": 103070.05593677296 }, { "content": "#[derive(Default)]\n\nstruct App {\n\n window: Window,\n\n pass: Pass,\n\n view: View,\n\n}\n\n\n\nimpl App {\n\n fn new(_cx: &mut Cx) -> Self {\n\n Self::default()\n\n }\n\n\n\n fn handle(&mut self, _cx: &mut Cx, _event: &mut Event) {}\n\n\n\n fn draw(&mut self, cx: &mut Cx) {\n\n self.window.begin_window(cx);\n\n self.pass.begin_pass(cx, Vec4::color(\"0\"));\n\n self.view.begin_view(cx, LayoutSize::FILL);\n\n\n\n let rect1 = RectIns { color: vec4(1., 0., 0., 1.), rect_pos: vec2(50., 50.), rect_size: vec2(400., 200.) };\n\n let rect2 = RectIns { color: vec4(0., 0., 1., 1.), rect_pos: vec2(100., 100.), rect_size: vec2(200., 400.) };\n", "file_path": "wrflib/examples/tutorial_2d_rendering/step2/src/main.rs", "rank": 88, "score": 103070.05593677296 }, { "content": "#[derive(Default)]\n\nstruct App {\n\n window: Window,\n\n}\n\n\n\nimpl App {\n\n fn new(_cx: &mut Cx) -> Self {\n\n Self { window: Window { create_add_drop_target_for_app_open_files: true, ..Window::default() } }\n\n }\n\n\n\n fn handle(&mut self, _cx: &mut Cx, event: &mut Event) {\n\n if let Event::AppOpenFiles(aof) = event {\n\n // Get a copy of the file handle for use in the thread.\n\n let mut file = aof.user_files[0].file.clone();\n\n\n\n universal_thread::spawn(move || {\n\n let mut contents = String::new();\n\n file.read_to_string(&mut contents).unwrap();\n\n log!(\"Contents of dropped file: {contents}\");\n\n });\n\n }\n\n }\n\n\n\n fn draw(&mut self, cx: &mut Cx) {\n\n self.window.begin_window(cx);\n\n self.window.end_window(cx);\n\n }\n\n}\n\n\n\nmain_app!(App);\n", "file_path": "wrflib/examples/tutorial_hello_thread/src/main.rs", "rank": 89, "score": 103070.05593677296 }, { "content": "#[derive(Default)]\n\nstruct App {\n\n window: Window,\n\n pass: Pass,\n\n view: View,\n\n button_inc: Button,\n\n button_dec: Button,\n\n counter: i32,\n\n slider: FloatSlider,\n\n scroll_view: ScrollView,\n\n splitter: Splitter,\n\n}\n\n\n\nimpl App {\n\n fn new(_cx: &mut Cx) -> Self {\n\n let mut splitter = Splitter::default();\n\n splitter.set_splitter_state(SplitterAlign::First, 300., Axis::Vertical);\n\n App { scroll_view: ScrollView::new_standard_vh(), splitter, ..Self::default() }\n\n }\n\n\n\n fn handle(&mut self, cx: &mut Cx, event: &mut Event) {\n", "file_path": "wrflib/examples/tutorial_ui_layout/src/main.rs", "rank": 90, "score": 103070.05593677296 }, { "content": "#[derive(Default)]\n\n#[repr(C)]\n\nstruct ExampleQuad {\n\n base: Background,\n\n}\n\nimpl ExampleQuad {\n\n fn begin_fill(&mut self, cx: &mut Cx, label: &str, color: Vec4) {\n\n self.base.begin_draw(cx, Width::Fill, Height::Fill, color);\n\n TextIns::draw_walk(cx, label, &TextInsProps::DEFAULT);\n\n }\n\n\n\n fn end_fill(&mut self, cx: &mut Cx) {\n\n self.base.end_draw(cx);\n\n }\n\n}\n\n\n", "file_path": "wrflib/examples/test_padding/src/main.rs", "rank": 91, "score": 103069.93925186187 }, { "content": "#[derive(Default)]\n\n#[repr(C)]\n\nstruct ExampleQuad {\n\n base: Background,\n\n}\n\nimpl ExampleQuad {\n\n fn draw(&mut self, cx: &mut Cx, label: &str) {\n\n cx.begin_padding_box(Padding::all(1.0));\n\n self.base.begin_draw(cx, Width::Compute, Height::Compute, vec4(0.8, 0.2, 0.4, 1.));\n\n cx.begin_padding_box(Padding::vh(12., 16.));\n\n TextIns::draw_walk(cx, label, &TextInsProps::DEFAULT);\n\n cx.end_padding_box();\n\n self.base.end_draw(cx);\n\n cx.end_padding_box();\n\n }\n\n}\n\n\n", "file_path": "wrflib/examples/test_layout/src/main.rs", "rank": 92, "score": 103069.93925186187 }, { "content": "#[derive(Clone, Default)]\n\n#[repr(C)]\n\nstruct TabCloseIns {\n\n base: QuadIns,\n\n color: Vec4,\n\n hover: f32,\n\n down: f32,\n\n}\n\n\n\nstatic SHADER: Shader = Shader {\n\n build_geom: Some(QuadIns::build_geom),\n\n code_to_concatenate: &[\n\n Cx::STD_SHADER,\n\n QuadIns::SHADER,\n\n code_fragment!(\n\n r#\"\n\n instance color: vec4;\n\n instance hover: float;\n\n instance down: float;\n\n\n\n fn pixel() -> vec4 {\n\n let df = Df::viewport(pos * rect_size);\n", "file_path": "wrflib/components/src/internal/tabclose.rs", "rank": 93, "score": 103069.88244775706 }, { "content": "#[derive(Clone, Default)]\n\n#[repr(C)]\n\nstruct ScrollBarIns {\n\n base: QuadIns,\n\n color: Vec4,\n\n is_vertical: f32,\n\n norm_handle: f32,\n\n norm_scroll: f32,\n\n}\n\n\n\nstatic SHADER: Shader = Shader {\n\n build_geom: Some(QuadIns::build_geom),\n\n code_to_concatenate: &[\n\n Cx::STD_SHADER,\n\n QuadIns::SHADER,\n\n code_fragment!(\n\n r#\"\n\n instance color: vec4;\n\n instance is_vertical: float;\n\n instance norm_handle: float;\n\n instance norm_scroll: float;\n\n const border_radius: float = 1.5;\n", "file_path": "wrflib/components/src/internal/scrollbar.rs", "rank": 94, "score": 103069.88244775706 }, { "content": "#[derive(Clone)]\n\nstruct TextIndex {\n\n nodes: Vec<TextIndexNode>,\n\n}\n\n\n\nimpl Default for TextIndex {\n\n fn default() -> Self {\n\n Self { nodes: vec![TextIndexNode::default()] }\n\n }\n\n}\n\n\n\nimpl TextIndex {\n\n fn write(&mut self, what: &[char], text_buffer_id: MakepadTextBufferId, mut_id: u16, prio: u16, token: u32) {\n\n let mut o = 0;\n\n let mut id = 0;\n\n loop {\n\n if self.nodes[id].used > 0 {\n\n // we have a stem to compare/split\n\n for s in 0..self.nodes[id].used {\n\n // read stem\n\n let sc = self.nodes[id].stem[s];\n", "file_path": "wrflib/examples/example_bigedit/src/searchindex.rs", "rank": 95, "score": 103063.47630905017 }, { "content": "struct ShaderEditor {\n\n component_id: ComponentId,\n\n window: Window,\n\n pass: Pass,\n\n main_view: View,\n\n quad: ShaderQuadIns,\n\n quad_area: Area,\n\n primary_color_picker: ColorSliders,\n\n secondary_color_picker: ColorSliders,\n\n}\n\n\n\nimpl ShaderEditor {\n\n fn new(_cx: &mut Cx) -> Self {\n\n Self {\n\n component_id: Default::default(),\n\n window: Window::default(),\n\n pass: Pass::default(),\n\n quad: ShaderQuadIns::default(),\n\n quad_area: Area::Empty,\n\n main_view: View::default(),\n", "file_path": "wrflib/examples/example_shader/src/main.rs", "rank": 96, "score": 103063.47630905017 }, { "content": "struct LogoApp {\n\n window: Window,\n\n pass: Pass,\n\n main_view: View,\n\n quad: ShaderQuadIns,\n\n quad_area: Area,\n\n knob_ids: [ComponentId; 3],\n\n knob_drag_offset: [Vec2; 3],\n\n #[cfg(not(feature = \"disable-interaction\"))]\n\n folded: bool,\n\n #[cfg(not(feature = \"disable-interaction\"))]\n\n splitter: Splitter,\n\n #[cfg(not(feature = \"disable-interaction\"))]\n\n text_editor: TextEditor,\n\n #[cfg(not(feature = \"disable-interaction\"))]\n\n text_buffer: TextBuffer,\n\n #[cfg(not(feature = \"disable-interaction\"))]\n\n error_message: String,\n\n}\n\n\n", "file_path": "wrflib/examples/example_lightning/src/main.rs", "rank": 97, "score": 103063.47630905017 }, { "content": "struct ColorSliders {\n\n label: String,\n\n slider_r: FloatSlider,\n\n slider_g: FloatSlider,\n\n slider_b: FloatSlider,\n\n}\n\n\n\nimpl ColorSliders {\n\n fn handle_event(&mut self, cx: &mut Cx, event: &mut Event, color: Vec4) -> Option<Vec4> {\n\n if let FloatSliderEvent::Change { scaled_value } = self.slider_r.handle(cx, event) {\n\n Some(Vec4 { x: scaled_value, ..color })\n\n } else if let FloatSliderEvent::Change { scaled_value } = self.slider_g.handle(cx, event) {\n\n Some(Vec4 { y: scaled_value, ..color })\n\n } else if let FloatSliderEvent::Change { scaled_value } = self.slider_b.handle(cx, event) {\n\n Some(Vec4 { z: scaled_value, ..color })\n\n } else {\n\n None\n\n }\n\n }\n\n\n", "file_path": "wrflib/examples/example_shader/src/main.rs", "rank": 98, "score": 103063.47630905017 }, { "content": "#[repr(C)]\n\nstruct FpsCounterUniforms {\n\n sample_length: f32,\n\n max_fps: f32,\n\n}\n\n\n\nstatic SHADER: Shader = Shader {\n\n build_geom: Some(QuadIns::build_geom),\n\n code_to_concatenate: &[\n\n Cx::STD_SHADER,\n\n QuadIns::SHADER,\n\n code_fragment!(\n\n r#\"\n\n texture texture: texture2D;\n\n uniform sample_length: float;\n\n uniform max_fps: float;\n\n\n\n const line_width: float = 0.05;\n\n\n\n fn plot(position: vec2, point: float) -> float {\n\n return smoothstep(point - line_width, point, position.y) - smoothstep(point, point + line_width, position.y);\n", "file_path": "wrflib/components/src/fps_counter.rs", "rank": 99, "score": 103063.47630905017 } ]
Rust
age/src/error.rs
str4d/rage
456ce707f6db01f2f953c9e22c058964f3437795
use i18n_embed_fl::fl; use std::fmt; use std::io; use crate::{wfl, wlnfl}; #[cfg(feature = "plugin")] use age_core::format::Stanza; #[cfg(feature = "plugin")] #[cfg_attr(docsrs, doc(cfg(feature = "plugin")))] #[derive(Clone, Debug)] pub enum PluginError { Identity { binary_name: String, message: String, }, Recipient { binary_name: String, recipient: String, message: String, }, Other { kind: String, metadata: Vec<String>, message: String, }, } #[cfg(feature = "plugin")] impl From<Stanza> for PluginError { fn from(mut s: Stanza) -> Self { assert!(s.tag == "error"); let kind = s.args.remove(0); PluginError::Other { kind, metadata: s.args, message: String::from_utf8_lossy(&s.body).to_string(), } } } #[cfg(feature = "plugin")] impl fmt::Display for PluginError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { PluginError::Identity { binary_name, message, } => write!( f, "{}", fl!( crate::i18n::LANGUAGE_LOADER, "err-plugin-identity", plugin_name = binary_name.as_str(), message = message.as_str() ) ), PluginError::Recipient { binary_name, recipient, message, } => write!( f, "{}", fl!( crate::i18n::LANGUAGE_LOADER, "err-plugin-recipient", plugin_name = binary_name.as_str(), recipient = recipient.as_str(), message = message.as_str() ) ), PluginError::Other { kind, metadata, message, } => { write!(f, "({}", kind)?; for d in metadata { write!(f, " {}", d)?; } write!(f, ")")?; if !message.is_empty() { write!(f, " {}", message)?; } Ok(()) } } } } #[derive(Debug)] pub enum EncryptError { EncryptedIdentities(DecryptError), Io(io::Error), #[cfg(feature = "plugin")] #[cfg_attr(docsrs, doc(cfg(feature = "plugin")))] MissingPlugin { binary_name: String, }, #[cfg(feature = "plugin")] #[cfg_attr(docsrs, doc(cfg(feature = "plugin")))] Plugin(Vec<PluginError>), } impl From<io::Error> for EncryptError { fn from(e: io::Error) -> Self { EncryptError::Io(e) } } impl Clone for EncryptError { fn clone(&self) -> Self { match self { Self::EncryptedIdentities(e) => Self::EncryptedIdentities(e.clone()), Self::Io(e) => Self::Io(io::Error::new(e.kind(), e.to_string())), #[cfg(feature = "plugin")] Self::MissingPlugin { binary_name } => Self::MissingPlugin { binary_name: binary_name.clone(), }, #[cfg(feature = "plugin")] Self::Plugin(e) => Self::Plugin(e.clone()), } } } impl fmt::Display for EncryptError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { EncryptError::EncryptedIdentities(e) => e.fmt(f), EncryptError::Io(e) => e.fmt(f), #[cfg(feature = "plugin")] EncryptError::MissingPlugin { binary_name } => { writeln!( f, "{}", fl!( crate::i18n::LANGUAGE_LOADER, "err-missing-plugin", plugin_name = binary_name.as_str() ) )?; wfl!(f, "rec-missing-plugin") } #[cfg(feature = "plugin")] EncryptError::Plugin(errors) => match &errors[..] { [] => unreachable!(), [e] => write!(f, "{}", e), _ => { wlnfl!(f, "err-plugin-multiple")?; for e in errors { writeln!(f, "- {}", e)?; } Ok(()) } }, } } } impl std::error::Error for EncryptError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { EncryptError::EncryptedIdentities(inner) => Some(inner), EncryptError::Io(inner) => Some(inner), #[cfg(feature = "plugin")] _ => None, } } } #[derive(Debug)] pub enum DecryptError { DecryptionFailed, ExcessiveWork { required: u8, target: u8, }, InvalidHeader, InvalidMac, Io(io::Error), KeyDecryptionFailed, #[cfg(feature = "plugin")] #[cfg_attr(docsrs, doc(cfg(feature = "plugin")))] MissingPlugin { binary_name: String, }, NoMatchingKeys, #[cfg(feature = "plugin")] #[cfg_attr(docsrs, doc(cfg(feature = "plugin")))] Plugin(Vec<PluginError>), UnknownFormat, } impl Clone for DecryptError { fn clone(&self) -> Self { match self { Self::DecryptionFailed => Self::DecryptionFailed, Self::ExcessiveWork { required, target } => Self::ExcessiveWork { required: *required, target: *target, }, Self::InvalidHeader => Self::InvalidHeader, Self::InvalidMac => Self::InvalidMac, Self::Io(e) => Self::Io(io::Error::new(e.kind(), e.to_string())), Self::KeyDecryptionFailed => Self::KeyDecryptionFailed, #[cfg(feature = "plugin")] Self::MissingPlugin { binary_name } => Self::MissingPlugin { binary_name: binary_name.clone(), }, Self::NoMatchingKeys => Self::NoMatchingKeys, #[cfg(feature = "plugin")] Self::Plugin(e) => Self::Plugin(e.clone()), Self::UnknownFormat => Self::UnknownFormat, } } } impl fmt::Display for DecryptError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { DecryptError::DecryptionFailed => wfl!(f, "err-decryption-failed"), DecryptError::ExcessiveWork { required, target } => { wlnfl!(f, "err-excessive-work")?; write!( f, "{}", fl!( crate::i18n::LANGUAGE_LOADER, "rec-excessive-work", duration = (1 << (required - target)) ) ) } DecryptError::InvalidHeader => wfl!(f, "err-header-invalid"), DecryptError::InvalidMac => wfl!(f, "err-header-mac-invalid"), DecryptError::Io(e) => e.fmt(f), DecryptError::KeyDecryptionFailed => wfl!(f, "err-key-decryption"), #[cfg(feature = "plugin")] DecryptError::MissingPlugin { binary_name } => { writeln!( f, "{}", fl!( crate::i18n::LANGUAGE_LOADER, "err-missing-plugin", plugin_name = binary_name.as_str() ) )?; wfl!(f, "rec-missing-plugin") } DecryptError::NoMatchingKeys => wfl!(f, "err-no-matching-keys"), #[cfg(feature = "plugin")] DecryptError::Plugin(errors) => match &errors[..] { [] => unreachable!(), [e] => write!(f, "{}", e), _ => { wlnfl!(f, "err-plugin-multiple")?; for e in errors { writeln!(f, "- {}", e)?; } Ok(()) } }, DecryptError::UnknownFormat => { wlnfl!(f, "err-unknown-format")?; wfl!(f, "rec-unknown-format") } } } } impl From<chacha20poly1305::aead::Error> for DecryptError { fn from(_: chacha20poly1305::aead::Error) -> Self { DecryptError::DecryptionFailed } } impl From<io::Error> for DecryptError { fn from(e: io::Error) -> Self { DecryptError::Io(e) } } impl From<hmac::crypto_mac::MacError> for DecryptError { fn from(_: hmac::crypto_mac::MacError) -> Self { DecryptError::InvalidMac } } #[cfg(feature = "ssh")] #[cfg_attr(docsrs, doc(cfg(feature = "ssh")))] impl From<rsa::errors::Error> for DecryptError { fn from(_: rsa::errors::Error) -> Self { DecryptError::DecryptionFailed } } impl std::error::Error for DecryptError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { DecryptError::Io(inner) => Some(inner), _ => None, } } }
use i18n_embed_fl::fl; use std::fmt; use std::io; use crate::{wfl, wlnfl}; #[cfg(feature = "plugin")] use age_core::format::Stanza; #[cfg(feature = "plugin")] #[cfg_attr(docsrs, doc(cfg(feature = "plugin")))] #[derive(Clone, Debug)] pub enum PluginError { Identity { binary_name: String, message: String, }, Recipient { binary_name: String, recipient: String,
e) => e.fmt(f), DecryptError::KeyDecryptionFailed => wfl!(f, "err-key-decryption"), #[cfg(feature = "plugin")] DecryptError::MissingPlugin { binary_name } => { writeln!( f, "{}", fl!( crate::i18n::LANGUAGE_LOADER, "err-missing-plugin", plugin_name = binary_name.as_str() ) )?; wfl!(f, "rec-missing-plugin") } DecryptError::NoMatchingKeys => wfl!(f, "err-no-matching-keys"), #[cfg(feature = "plugin")] DecryptError::Plugin(errors) => match &errors[..] { [] => unreachable!(), [e] => write!(f, "{}", e), _ => { wlnfl!(f, "err-plugin-multiple")?; for e in errors { writeln!(f, "- {}", e)?; } Ok(()) } }, DecryptError::UnknownFormat => { wlnfl!(f, "err-unknown-format")?; wfl!(f, "rec-unknown-format") } } } } impl From<chacha20poly1305::aead::Error> for DecryptError { fn from(_: chacha20poly1305::aead::Error) -> Self { DecryptError::DecryptionFailed } } impl From<io::Error> for DecryptError { fn from(e: io::Error) -> Self { DecryptError::Io(e) } } impl From<hmac::crypto_mac::MacError> for DecryptError { fn from(_: hmac::crypto_mac::MacError) -> Self { DecryptError::InvalidMac } } #[cfg(feature = "ssh")] #[cfg_attr(docsrs, doc(cfg(feature = "ssh")))] impl From<rsa::errors::Error> for DecryptError { fn from(_: rsa::errors::Error) -> Self { DecryptError::DecryptionFailed } } impl std::error::Error for DecryptError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { DecryptError::Io(inner) => Some(inner), _ => None, } } }
message: String, }, Other { kind: String, metadata: Vec<String>, message: String, }, } #[cfg(feature = "plugin")] impl From<Stanza> for PluginError { fn from(mut s: Stanza) -> Self { assert!(s.tag == "error"); let kind = s.args.remove(0); PluginError::Other { kind, metadata: s.args, message: String::from_utf8_lossy(&s.body).to_string(), } } } #[cfg(feature = "plugin")] impl fmt::Display for PluginError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { PluginError::Identity { binary_name, message, } => write!( f, "{}", fl!( crate::i18n::LANGUAGE_LOADER, "err-plugin-identity", plugin_name = binary_name.as_str(), message = message.as_str() ) ), PluginError::Recipient { binary_name, recipient, message, } => write!( f, "{}", fl!( crate::i18n::LANGUAGE_LOADER, "err-plugin-recipient", plugin_name = binary_name.as_str(), recipient = recipient.as_str(), message = message.as_str() ) ), PluginError::Other { kind, metadata, message, } => { write!(f, "({}", kind)?; for d in metadata { write!(f, " {}", d)?; } write!(f, ")")?; if !message.is_empty() { write!(f, " {}", message)?; } Ok(()) } } } } #[derive(Debug)] pub enum EncryptError { EncryptedIdentities(DecryptError), Io(io::Error), #[cfg(feature = "plugin")] #[cfg_attr(docsrs, doc(cfg(feature = "plugin")))] MissingPlugin { binary_name: String, }, #[cfg(feature = "plugin")] #[cfg_attr(docsrs, doc(cfg(feature = "plugin")))] Plugin(Vec<PluginError>), } impl From<io::Error> for EncryptError { fn from(e: io::Error) -> Self { EncryptError::Io(e) } } impl Clone for EncryptError { fn clone(&self) -> Self { match self { Self::EncryptedIdentities(e) => Self::EncryptedIdentities(e.clone()), Self::Io(e) => Self::Io(io::Error::new(e.kind(), e.to_string())), #[cfg(feature = "plugin")] Self::MissingPlugin { binary_name } => Self::MissingPlugin { binary_name: binary_name.clone(), }, #[cfg(feature = "plugin")] Self::Plugin(e) => Self::Plugin(e.clone()), } } } impl fmt::Display for EncryptError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { EncryptError::EncryptedIdentities(e) => e.fmt(f), EncryptError::Io(e) => e.fmt(f), #[cfg(feature = "plugin")] EncryptError::MissingPlugin { binary_name } => { writeln!( f, "{}", fl!( crate::i18n::LANGUAGE_LOADER, "err-missing-plugin", plugin_name = binary_name.as_str() ) )?; wfl!(f, "rec-missing-plugin") } #[cfg(feature = "plugin")] EncryptError::Plugin(errors) => match &errors[..] { [] => unreachable!(), [e] => write!(f, "{}", e), _ => { wlnfl!(f, "err-plugin-multiple")?; for e in errors { writeln!(f, "- {}", e)?; } Ok(()) } }, } } } impl std::error::Error for EncryptError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { EncryptError::EncryptedIdentities(inner) => Some(inner), EncryptError::Io(inner) => Some(inner), #[cfg(feature = "plugin")] _ => None, } } } #[derive(Debug)] pub enum DecryptError { DecryptionFailed, ExcessiveWork { required: u8, target: u8, }, InvalidHeader, InvalidMac, Io(io::Error), KeyDecryptionFailed, #[cfg(feature = "plugin")] #[cfg_attr(docsrs, doc(cfg(feature = "plugin")))] MissingPlugin { binary_name: String, }, NoMatchingKeys, #[cfg(feature = "plugin")] #[cfg_attr(docsrs, doc(cfg(feature = "plugin")))] Plugin(Vec<PluginError>), UnknownFormat, } impl Clone for DecryptError { fn clone(&self) -> Self { match self { Self::DecryptionFailed => Self::DecryptionFailed, Self::ExcessiveWork { required, target } => Self::ExcessiveWork { required: *required, target: *target, }, Self::InvalidHeader => Self::InvalidHeader, Self::InvalidMac => Self::InvalidMac, Self::Io(e) => Self::Io(io::Error::new(e.kind(), e.to_string())), Self::KeyDecryptionFailed => Self::KeyDecryptionFailed, #[cfg(feature = "plugin")] Self::MissingPlugin { binary_name } => Self::MissingPlugin { binary_name: binary_name.clone(), }, Self::NoMatchingKeys => Self::NoMatchingKeys, #[cfg(feature = "plugin")] Self::Plugin(e) => Self::Plugin(e.clone()), Self::UnknownFormat => Self::UnknownFormat, } } } impl fmt::Display for DecryptError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { DecryptError::DecryptionFailed => wfl!(f, "err-decryption-failed"), DecryptError::ExcessiveWork { required, target } => { wlnfl!(f, "err-excessive-work")?; write!( f, "{}", fl!( crate::i18n::LANGUAGE_LOADER, "rec-excessive-work", duration = (1 << (required - target)) ) ) } DecryptError::InvalidHeader => wfl!(f, "err-header-invalid"), DecryptError::InvalidMac => wfl!(f, "err-header-mac-invalid"), DecryptError::Io(
random
[ { "content": "/// Runs the plugin state machine defined by `state_machine`.\n\n///\n\n/// This should be triggered if the `--age-plugin=state_machine` flag is provided as an\n\n/// argument when starting the plugin.\n\npub fn run_state_machine<R: recipient::RecipientPluginV1, I: identity::IdentityPluginV1>(\n\n state_machine: &str,\n\n recipient_v1: impl FnOnce() -> R,\n\n identity_v1: impl FnOnce() -> I,\n\n) -> io::Result<()> {\n\n use age_core::plugin::{IDENTITY_V1, RECIPIENT_V1};\n\n\n\n match state_machine {\n\n RECIPIENT_V1 => recipient::run_v1(recipient_v1()),\n\n IDENTITY_V1 => identity::run_v1(identity_v1()),\n\n _ => Err(io::Error::new(\n\n io::ErrorKind::InvalidInput,\n\n \"unknown plugin state machine\",\n\n )),\n\n }\n\n}\n\n\n", "file_path": "age-plugin/src/lib.rs", "rank": 0, "score": 161148.54016284482 }, { "content": "/// Prints the newly-created identity and corresponding recipient to standard out.\n\n///\n\n/// A \"created\" time is included in the output, set to the current local time.\n\npub fn print_new_identity(plugin_name: &str, identity: &[u8], recipient: &[u8]) {\n\n use bech32::ToBase32;\n\n\n\n println!(\n\n \"# created: {}\",\n\n chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)\n\n );\n\n println!(\n\n \"# recipient: {}\",\n\n bech32::encode(\n\n &format!(\"{}{}\", PLUGIN_RECIPIENT_PREFIX, plugin_name),\n\n recipient.to_base32(),\n\n Variant::Bech32\n\n )\n\n .expect(\"HRP is valid\")\n\n );\n\n println!(\n\n \"{}\",\n\n bech32::encode(\n\n &format!(\"{}{}-\", PLUGIN_IDENTITY_PREFIX, plugin_name),\n\n identity.to_base32(),\n\n Variant::Bech32,\n\n )\n\n .expect(\"HRP is valid\")\n\n .to_uppercase()\n\n );\n\n}\n\n\n", "file_path": "age-plugin/src/lib.rs", "rank": 1, "score": 149981.65874798893 }, { "content": "/// The interface that age implementations will use to interact with an age plugin.\n\npub trait RecipientPluginV1 {\n\n /// Stores a recipient that the user would like to encrypt age files to.\n\n ///\n\n /// `plugin_name` is the name of the binary that resolved to this plugin.\n\n ///\n\n /// Returns an error if the recipient is unknown or invalid.\n\n fn add_recipient(&mut self, index: usize, plugin_name: &str, bytes: &[u8])\n\n -> Result<(), Error>;\n\n\n\n /// Stores an identity that the user would like to encrypt age files to.\n\n ///\n\n /// `plugin_name` is the name of the binary that resolved to this plugin.\n\n ///\n\n /// Returns an error if the identity is unknown or invalid.\n\n fn add_identity(&mut self, index: usize, plugin_name: &str, bytes: &[u8]) -> Result<(), Error>;\n\n\n\n /// Wraps each `file_key` to all recipients and identities previously added via\n\n /// `add_recipient` and `add_identity`.\n\n ///\n\n /// Returns either one stanza per recipient and identity for each file key, or any\n", "file_path": "age-plugin/src/recipient.rs", "rank": 2, "score": 145053.5768251783 }, { "content": "/// The interface that age implementations will use to interact with an age plugin.\n\npub trait IdentityPluginV1 {\n\n /// Stores an identity that the user would like to use for decrypting age files.\n\n ///\n\n /// `plugin_name` is the name of the binary that resolved to this plugin.\n\n ///\n\n /// Returns an error if the identity is unknown or invalid.\n\n fn add_identity(&mut self, index: usize, plugin_name: &str, bytes: &[u8]) -> Result<(), Error>;\n\n\n\n /// Attempts to unwrap the file keys contained within the given age recipient stanzas,\n\n /// using identities previously stored via [`add_identity`].\n\n ///\n\n /// Returns a `HashMap` containing the unwrapping results for each file:\n\n ///\n\n /// - A list of errors, if any stanzas for a file cannot be unwrapped that detectably\n\n /// should be unwrappable.\n\n ///\n\n /// - A [`FileKey`], if any stanza for a file can be successfully unwrapped.\n\n ///\n\n /// Note that if all known and valid stanzas for a given file cannot be unwrapped, and\n\n /// none are expected to be unwrappable, that file has no entry in the `HashMap`. That\n", "file_path": "age-plugin/src/identity.rs", "rank": 3, "score": 144766.6567324884 }, { "content": "/// A public key or other value that can wrap an opaque file key to a recipient stanza.\n\n///\n\n/// Implementations of this trait might represent more than one recipient.\n\npub trait Recipient {\n\n /// Wraps the given file key, returning stanzas to be placed in an age file header.\n\n ///\n\n /// Implementations MUST NOT return more than one stanza per \"actual recipient\".\n\n ///\n\n /// This method is part of the `Recipient` trait to expose age's [one joint] for\n\n /// external implementations. You should not need to call this directly; instead, pass\n\n /// recipients to [`Encryptor::with_recipients`].\n\n ///\n\n /// [one joint]: https://www.imperialviolet.org/2016/05/16/agility.html\n\n fn wrap_file_key(&self, file_key: &FileKey) -> Result<Vec<Stanza>, EncryptError>;\n\n}\n\n\n", "file_path": "age/src/lib.rs", "rank": 4, "score": 98205.43547172773 }, { "content": "/// A private key or other value that can unwrap an opaque file key from a recipient\n\n/// stanza.\n\npub trait Identity {\n\n /// Attempts to unwrap the given stanza with this identity.\n\n ///\n\n /// This method is part of the `Identity` trait to expose age's [one joint] for\n\n /// external implementations. You should not need to call this directly; instead, pass\n\n /// identities to [`RecipientsDecryptor::decrypt`].\n\n ///\n\n /// Returns:\n\n /// - `Some(Ok(file_key))` on success.\n\n /// - `Some(Err(e))` if a decryption error occurs.\n\n /// - `None` if the recipient stanza does not match this key.\n\n ///\n\n /// [one joint]: https://www.imperialviolet.org/2016/05/16/agility.html\n\n /// [`RecipientsDecryptor::decrypt`]: protocol::decryptor::RecipientsDecryptor::decrypt\n\n fn unwrap_stanza(&self, stanza: &Stanza) -> Option<Result<FileKey, DecryptError>>;\n\n\n\n /// Attempts to unwrap any of the given stanzas, which are assumed to come from the\n\n /// same age file header, and therefore contain the same file key.\n\n ///\n\n /// This method is part of the `Identity` trait to expose age's [one joint] for\n", "file_path": "age/src/lib.rs", "rank": 5, "score": 97961.50822425478 }, { "content": "fn binary_name(plugin_name: &str) -> String {\n\n format!(\"age-plugin-{}\", plugin_name)\n\n}\n\n\n\n/// A plugin-compatible recipient.\n\n#[derive(Clone)]\n\npub struct Recipient {\n\n /// The plugin name, extracted from `recipient`.\n\n name: String,\n\n /// The recipient.\n\n recipient: String,\n\n}\n\n\n\nimpl std::str::FromStr for Recipient {\n\n type Err = &'static str;\n\n\n\n /// Parses a plugin recipient from a string.\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n parse_bech32(s)\n\n .ok_or(\"invalid Bech32 encoding\")\n", "file_path": "age/src/plugin.rs", "rank": 6, "score": 96510.86355521173 }, { "content": "/// Reads identities from the provided files.\n\npub fn read_identities(\n\n filenames: Vec<String>,\n\n max_work_factor: Option<u8>,\n\n) -> Result<Vec<Box<dyn Identity>>, ReadError> {\n\n let mut identities: Vec<Box<dyn Identity>> = vec![];\n\n\n\n for filename in filenames {\n\n // Try parsing as an encrypted age identity.\n\n if let Ok(identity) = crate::encrypted::Identity::from_buffer(\n\n ArmoredReader::new(BufReader::new(File::open(&filename)?)),\n\n Some(filename.clone()),\n\n UiCallbacks,\n\n max_work_factor,\n\n ) {\n\n if let Some(identity) = identity {\n\n identities.push(Box::new(identity));\n\n continue;\n\n } else {\n\n return Err(ReadError::IdentityEncryptedWithoutPassphrase(filename));\n\n }\n", "file_path": "age/src/cli_common.rs", "rank": 7, "score": 93622.73140880224 }, { "content": "/// The interface that age plugins can use to interact with an age implementation.\n\npub trait Callbacks<E> {\n\n /// Shows a message to the user.\n\n ///\n\n /// This can be used to prompt the user to take some physical action, such as\n\n /// inserting a hardware key.\n\n fn message(&mut self, message: &str) -> age_core::plugin::Result<()>;\n\n\n\n /// Requests a non-secret value from the user.\n\n ///\n\n /// `message` will be displayed to the user, providing context for the request.\n\n ///\n\n /// To request secrets, use [`Callbacks::request_secret`].\n\n fn request_public(&mut self, message: &str) -> age_core::plugin::Result<String>;\n\n\n\n /// Requests a secret value from the user, such as a passphrase.\n\n ///\n\n /// `message` will be displayed to the user, providing context for the request.\n\n fn request_secret(&mut self, message: &str) -> age_core::plugin::Result<SecretString>;\n\n\n\n /// Sends an error.\n\n ///\n\n /// Note: This API may be removed in a subsequent API refactor, after we've figured\n\n /// out how errors should be handled overall, and how to distinguish between hard and\n\n /// soft errors.\n\n fn error(&mut self, error: E) -> age_core::plugin::Result<()>;\n\n}\n", "file_path": "age-plugin/src/lib.rs", "rank": 8, "score": 91038.4788072289 }, { "content": "/// The state of the encrypted age identity.\n\nenum IdentityState<R: io::Read> {\n\n Encrypted {\n\n decryptor: PassphraseDecryptor<R>,\n\n max_work_factor: Option<u8>,\n\n },\n\n Decrypted(Vec<IdentityFileEntry>),\n\n\n\n /// The file was not correctly encrypted, or did not contain age identities. We cache\n\n /// this error in case the caller tries to use this identity again. The `Option` is to\n\n /// enable implementing `Default` so we can use `Cell::take`, but we don't ever allow\n\n /// the `None` case to persist.\n\n Poisoned(Option<DecryptError>),\n\n}\n\n\n\nimpl<R: io::Read> Default for IdentityState<R> {\n\n fn default() -> Self {\n\n Self::Poisoned(None)\n\n }\n\n}\n\n\n", "file_path": "age/src/encrypted.rs", "rank": 9, "score": 88902.63140959876 }, { "content": "struct RecipientPlugin;\n\n\n\nimpl RecipientPluginV1 for RecipientPlugin {\n\n fn add_recipient(\n\n &mut self,\n\n index: usize,\n\n plugin_name: &str,\n\n _bytes: &[u8],\n\n ) -> Result<(), recipient::Error> {\n\n if plugin_name == PLUGIN_NAME {\n\n // A real plugin would store the recipient here.\n\n Ok(())\n\n } else {\n\n Err(recipient::Error::Recipient {\n\n index,\n\n message: \"invalid recipient\".to_owned(),\n\n })\n\n }\n\n }\n\n\n", "file_path": "age-plugin/examples/age-plugin-unencrypted.rs", "rank": 10, "score": 82352.68884710076 }, { "content": "struct IdentityPlugin;\n\n\n\nimpl IdentityPluginV1 for IdentityPlugin {\n\n fn add_identity(\n\n &mut self,\n\n index: usize,\n\n plugin_name: &str,\n\n _bytes: &[u8],\n\n ) -> Result<(), identity::Error> {\n\n if plugin_name == PLUGIN_NAME {\n\n // A real plugin would store the identity.\n\n Ok(())\n\n } else {\n\n Err(identity::Error::Identity {\n\n index,\n\n message: \"invalid identity\".to_owned(),\n\n })\n\n }\n\n }\n\n\n", "file_path": "age-plugin/examples/age-plugin-unencrypted.rs", "rank": 11, "score": 82129.8004241819 }, { "content": " fn error(&mut self, error: Error) -> plugin::Result<()> {\n\n error.send(self.0).map(|()| Ok(()))\n\n }\n\n}\n\n\n\n/// The kinds of errors that can occur within the recipient plugin state machine.\n\npub enum Error {\n\n /// An error caused by a specific recipient.\n\n Recipient {\n\n /// The index of the recipient.\n\n index: usize,\n\n /// The error message.\n\n message: String,\n\n },\n\n /// An error caused by a specific identity.\n\n Identity {\n\n /// The index of the identity.\n\n index: usize,\n\n /// The error message.\n\n message: String,\n", "file_path": "age-plugin/src/recipient.rs", "rank": 12, "score": 76734.61876341108 }, { "content": "//! Recipient plugin helpers.\n\n\n\nuse age_core::{\n\n format::{FileKey, Stanza, FILE_KEY_BYTES},\n\n plugin::{self, BidirSend, Connection},\n\n secrecy::SecretString,\n\n};\n\nuse bech32::FromBase32;\n\nuse std::convert::TryInto;\n\nuse std::io;\n\n\n\nuse crate::{Callbacks, PLUGIN_IDENTITY_PREFIX, PLUGIN_RECIPIENT_PREFIX};\n\n\n\nconst ADD_RECIPIENT: &str = \"add-recipient\";\n\nconst ADD_IDENTITY: &str = \"add-identity\";\n\nconst WRAP_FILE_KEY: &str = \"wrap-file-key\";\n\nconst RECIPIENT_STANZA: &str = \"recipient-stanza\";\n\n\n\n/// The interface that age implementations will use to interact with an age plugin.\n", "file_path": "age-plugin/src/recipient.rs", "rank": 13, "score": 76730.50455752792 }, { "content": " .unwrap();\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\n/// Runs the recipient plugin v1 protocol.\n\npub(crate) fn run_v1<P: RecipientPluginV1>(mut plugin: P) -> io::Result<()> {\n\n let mut conn = Connection::accept();\n\n\n\n // Phase 1: collect recipients, and file keys to be wrapped\n\n let ((recipients, identities), file_keys) = {\n\n let (recipients, identities, file_keys) = conn.unidir_receive(\n\n (ADD_RECIPIENT, |s| match (&s.args[..], &s.body[..]) {\n\n ([recipient], []) => Ok(recipient.clone()),\n\n _ => Err(Error::Internal {\n\n message: format!(\n\n \"{} command must have exactly one metadata argument and no data\",\n\n ADD_RECIPIENT\n\n ),\n", "file_path": "age-plugin/src/recipient.rs", "rank": 14, "score": 76727.98183281062 }, { "content": " |hrp| hrp.strip_prefix(PLUGIN_RECIPIENT_PREFIX),\n\n |index| Error::Recipient {\n\n index,\n\n message: \"Invalid recipient encoding\".to_owned(),\n\n },\n\n |index, plugin_name, bytes| plugin.add_recipient(index, &plugin_name, &bytes),\n\n );\n\n let identities = parse_and_add(\n\n identities,\n\n |hrp| {\n\n if hrp.starts_with(PLUGIN_IDENTITY_PREFIX) && hrp.ends_with('-') {\n\n Some(&hrp[PLUGIN_IDENTITY_PREFIX.len()..hrp.len() - 1])\n\n } else {\n\n None\n\n }\n\n },\n\n |index| Error::Identity {\n\n index,\n\n message: \"Invalid identity encoding\".to_owned(),\n\n },\n", "file_path": "age-plugin/src/recipient.rs", "rank": 15, "score": 76727.43441232987 }, { "content": " },\n\n /// A general error that occured inside the state machine.\n\n Internal {\n\n /// The error message.\n\n message: String,\n\n },\n\n}\n\n\n\nimpl Error {\n\n fn kind(&self) -> &str {\n\n match self {\n\n Error::Recipient { .. } => \"recipient\",\n\n Error::Identity { .. } => \"identity\",\n\n Error::Internal { .. } => \"internal\",\n\n }\n\n }\n\n\n\n fn message(&self) -> &str {\n\n match self {\n\n Error::Recipient { message, .. } => &message,\n", "file_path": "age-plugin/src/recipient.rs", "rank": 16, "score": 76726.35950399865 }, { "content": " Error::Identity { message, .. } => &message,\n\n Error::Internal { message } => &message,\n\n }\n\n }\n\n\n\n fn send<R: io::Read, W: io::Write>(self, phase: &mut BidirSend<R, W>) -> io::Result<()> {\n\n let index = match self {\n\n Error::Recipient { index, .. } | Error::Identity { index, .. } => {\n\n Some(index.to_string())\n\n }\n\n Error::Internal { .. } => None,\n\n };\n\n\n\n let metadata = match &index {\n\n Some(index) => vec![self.kind(), &index],\n\n None => vec![self.kind()],\n\n };\n\n\n\n phase\n\n .send(\"error\", &metadata, self.message().as_bytes())?\n", "file_path": "age-plugin/src/recipient.rs", "rank": 17, "score": 76723.8016667252 }, { "content": "\n\n match plugin.wrap_file_keys(file_keys, BidirCallbacks(&mut phase))? {\n\n Ok(files) => {\n\n for (file_index, stanzas) in files.into_iter().enumerate() {\n\n // The plugin MUST generate an error if one or more recipients or\n\n // identities cannot be wrapped to. And it's a programming error\n\n // to return more stanzas than recipients and identities.\n\n assert_eq!(stanzas.len(), expected_stanzas);\n\n\n\n for stanza in stanzas {\n\n phase\n\n .send_stanza(RECIPIENT_STANZA, &[&file_index.to_string()], &stanza)?\n\n .unwrap();\n\n }\n\n }\n\n }\n\n Err(errors) => {\n\n for error in errors {\n\n error.send(&mut phase)?;\n\n }\n\n }\n\n }\n\n\n\n Ok(())\n\n })\n\n}\n", "file_path": "age-plugin/src/recipient.rs", "rank": 18, "score": 76723.7836378709 }, { "content": " |index, plugin_name, bytes| plugin.add_identity(index, &plugin_name, &bytes),\n\n );\n\n\n\n // Phase 2: wrap the file keys or return errors\n\n conn.bidir_send(|mut phase| {\n\n let (expected_stanzas, file_keys) = match (recipients, identities, file_keys) {\n\n (Ok(recipients), Ok(identities), Ok(file_keys)) => (recipients + identities, file_keys),\n\n (recipients, identities, file_keys) => {\n\n for error in recipients\n\n .err()\n\n .into_iter()\n\n .chain(identities.err())\n\n .chain(file_keys.err())\n\n .flatten()\n\n {\n\n error.send(&mut phase)?;\n\n }\n\n return Ok(());\n\n }\n\n };\n", "file_path": "age-plugin/src/recipient.rs", "rank": 19, "score": 76722.52810526198 }, { "content": " };\n\n\n\n // Now that we have the full list of recipients and identities, parse them as Bech32\n\n // and add them to the plugin.\n\n fn parse_and_add(\n\n items: Result<Vec<String>, Vec<Error>>,\n\n plugin_name: impl Fn(&str) -> Option<&str>,\n\n error: impl Fn(usize) -> Error,\n\n mut adder: impl FnMut(usize, &str, Vec<u8>) -> Result<(), Error>,\n\n ) -> Result<usize, Vec<Error>> {\n\n items.and_then(|items| {\n\n let count = items.len();\n\n let errors: Vec<_> = items\n\n .into_iter()\n\n .enumerate()\n\n .map(|(index, item)| {\n\n let decoded = bech32::decode(&item).ok();\n\n decoded\n\n .as_ref()\n\n .and_then(|(hrp, data, variant)| match (plugin_name(hrp), variant) {\n", "file_path": "age-plugin/src/recipient.rs", "rank": 20, "score": 76721.12930303968 }, { "content": " (\n\n match (recipients, identities) {\n\n (Ok(r), Ok(i)) if r.is_empty() && i.is_empty() => (\n\n Err(vec![Error::Internal {\n\n message: format!(\n\n \"Need at least one {} or {} command\",\n\n ADD_RECIPIENT, ADD_IDENTITY\n\n ),\n\n }]),\n\n Err(vec![]),\n\n ),\n\n r => r,\n\n },\n\n match file_keys.unwrap() {\n\n Ok(f) if f.is_empty() => Err(vec![Error::Internal {\n\n message: format!(\"Need at least one {} command\", WRAP_FILE_KEY),\n\n }]),\n\n r => r,\n\n },\n\n )\n", "file_path": "age-plugin/src/recipient.rs", "rank": 21, "score": 76721.00954798548 }, { "content": " })\n\n .map(Ok),\n\n Err(e) => Ok(Err(e)),\n\n })\n\n }\n\n\n\n /// Requests a secret value from the user, such as a passphrase.\n\n ///\n\n /// `message` will be displayed to the user, providing context for the request.\n\n fn request_secret(&mut self, message: &str) -> plugin::Result<SecretString> {\n\n self.0\n\n .send(\"request-secret\", &[], message.as_bytes())\n\n .and_then(|res| match res {\n\n Ok(s) => String::from_utf8(s.body)\n\n .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, \"secret is not UTF-8\"))\n\n .map(|s| Ok(SecretString::new(s))),\n\n Err(e) => Ok(Err(e)),\n\n })\n\n }\n\n\n", "file_path": "age-plugin/src/recipient.rs", "rank": 22, "score": 76720.45126068749 }, { "content": " /// errors if one or more recipients or identities could not be wrapped to.\n\n ///\n\n /// `callbacks` can be used to interact with the user, to have them take some physical\n\n /// action or request a secret value.\n\n fn wrap_file_keys(\n\n &mut self,\n\n file_keys: Vec<FileKey>,\n\n callbacks: impl Callbacks<Error>,\n\n ) -> io::Result<Result<Vec<Vec<Stanza>>, Vec<Error>>>;\n\n}\n\n\n", "file_path": "age-plugin/src/recipient.rs", "rank": 23, "score": 76718.45788505294 }, { "content": " (Some(plugin_name), &bech32::Variant::Bech32) => {\n\n Vec::from_base32(&data).ok().map(|data| (plugin_name, data))\n\n }\n\n _ => None,\n\n })\n\n .ok_or_else(|| error(index))\n\n .and_then(|(plugin_name, bytes)| adder(index, plugin_name, bytes))\n\n })\n\n .filter_map(|res| res.err())\n\n .collect();\n\n\n\n if errors.is_empty() {\n\n Ok(count)\n\n } else {\n\n Err(errors)\n\n }\n\n })\n\n }\n\n let recipients = parse_and_add(\n\n recipients,\n", "file_path": "age-plugin/src/recipient.rs", "rank": 24, "score": 76717.29158087564 }, { "content": " }),\n\n }),\n\n (ADD_IDENTITY, |s| match (&s.args[..], &s.body[..]) {\n\n ([identity], []) => Ok(identity.clone()),\n\n _ => Err(Error::Internal {\n\n message: format!(\n\n \"{} command must have exactly one metadata argument and no data\",\n\n ADD_IDENTITY\n\n ),\n\n }),\n\n }),\n\n (Some(WRAP_FILE_KEY), |s| {\n\n // TODO: Should we ignore file key commands with unexpected metadata args?\n\n TryInto::<[u8; FILE_KEY_BYTES]>::try_into(&s.body[..])\n\n .map_err(|_| Error::Internal {\n\n message: \"invalid file key length\".to_owned(),\n\n })\n\n .map(FileKey::from)\n\n }),\n\n )?;\n", "file_path": "age-plugin/src/recipient.rs", "rank": 25, "score": 76717.0592818942 }, { "content": "//! Identity plugin helpers.\n\n\n\nuse age_core::{\n\n format::{FileKey, Stanza},\n\n plugin::{self, BidirSend, Connection},\n\n secrecy::{ExposeSecret, SecretString},\n\n};\n\nuse bech32::FromBase32;\n\nuse std::collections::HashMap;\n\nuse std::io;\n\n\n\nuse crate::{Callbacks, PLUGIN_IDENTITY_PREFIX};\n\n\n\nconst ADD_IDENTITY: &str = \"add-identity\";\n\nconst RECIPIENT_STANZA: &str = \"recipient-stanza\";\n\n\n\n/// The interface that age implementations will use to interact with an age plugin.\n", "file_path": "age-plugin/src/identity.rs", "rank": 26, "score": 76479.32571126177 }, { "content": " fn error(&mut self, error: Error) -> plugin::Result<()> {\n\n error.send(self.0).map(|()| Ok(()))\n\n }\n\n}\n\n\n\n/// The kinds of errors that can occur within the identity plugin state machine.\n\npub enum Error {\n\n /// An error caused by a specific identity.\n\n Identity {\n\n /// The index of the identity.\n\n index: usize,\n\n /// The error message.\n\n message: String,\n\n },\n\n /// A general error that occured inside the state machine.\n\n Internal {\n\n /// The error message.\n\n message: String,\n\n },\n\n /// An error caused by a specific stanza.\n", "file_path": "age-plugin/src/identity.rs", "rank": 27, "score": 76478.77403535512 }, { "content": " message: format!(\n\n \"first metadata argument to {} must be an integer\",\n\n RECIPIENT_STANZA\n\n ),\n\n })\n\n } else {\n\n Err(Error::Internal {\n\n message: format!(\n\n \"{} command must have at least two metadata arguments\",\n\n RECIPIENT_STANZA\n\n ),\n\n })\n\n }\n\n }),\n\n (None, |_| Ok(())),\n\n )?;\n\n\n\n // Now that we have the full list of identities, parse them as Bech32 and add them\n\n // to the plugin.\n\n let identities = identities.and_then(|items| {\n", "file_path": "age-plugin/src/identity.rs", "rank": 28, "score": 76474.37539479231 }, { "content": " };\n\n\n\n let metadata = match &index {\n\n Some((file_index, Some(stanza_index))) => vec![self.kind(), &file_index, &stanza_index],\n\n Some((index, None)) => vec![self.kind(), &index],\n\n None => vec![self.kind()],\n\n };\n\n\n\n phase\n\n .send(\"error\", &metadata, self.message().as_bytes())?\n\n .unwrap();\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\n/// Runs the identity plugin v1 protocol.\n\npub(crate) fn run_v1<P: IdentityPluginV1>(mut plugin: P) -> io::Result<()> {\n\n let mut conn = Connection::accept();\n\n\n", "file_path": "age-plugin/src/identity.rs", "rank": 29, "score": 76472.42488921742 }, { "content": " ///\n\n /// Note that unknown stanzas MUST be ignored by plugins; this error is only for\n\n /// stanzas that have a supported tag but are otherwise invalid (indicating an invalid\n\n /// age file).\n\n Stanza {\n\n /// The index of the file containing the stanza.\n\n file_index: usize,\n\n /// The index of the stanza within the file.\n\n stanza_index: usize,\n\n /// The error message.\n\n message: String,\n\n },\n\n}\n\n\n\nimpl Error {\n\n fn kind(&self) -> &str {\n\n match self {\n\n Error::Identity { .. } => \"identity\",\n\n Error::Internal { .. } => \"internal\",\n\n Error::Stanza { .. } => \"stanza\",\n", "file_path": "age-plugin/src/identity.rs", "rank": 30, "score": 76472.13988517261 }, { "content": " }\n\n }\n\n\n\n fn message(&self) -> &str {\n\n match self {\n\n Error::Identity { message, .. } => &message,\n\n Error::Internal { message } => &message,\n\n Error::Stanza { message, .. } => &message,\n\n }\n\n }\n\n\n\n fn send<R: io::Read, W: io::Write>(self, phase: &mut BidirSend<R, W>) -> io::Result<()> {\n\n let index = match self {\n\n Error::Identity { index, .. } => Some((index.to_string(), None)),\n\n Error::Internal { .. } => None,\n\n Error::Stanza {\n\n file_index,\n\n stanza_index,\n\n ..\n\n } => Some((file_index.to_string(), Some(stanza_index.to_string()))),\n", "file_path": "age-plugin/src/identity.rs", "rank": 31, "score": 76471.14992536012 }, { "content": " // Phase 1: receive identities and stanzas\n\n let (identities, recipient_stanzas) = {\n\n let (identities, stanzas, _) = conn.unidir_receive(\n\n (ADD_IDENTITY, |s| match (&s.args[..], &s.body[..]) {\n\n ([identity], []) => Ok(identity.clone()),\n\n _ => Err(Error::Internal {\n\n message: format!(\n\n \"{} command must have exactly one metadata argument and no data\",\n\n ADD_IDENTITY\n\n ),\n\n }),\n\n }),\n\n (RECIPIENT_STANZA, |mut s| {\n\n if s.args.len() >= 2 {\n\n let file_index = s.args.remove(0);\n\n s.tag = s.args.remove(0);\n\n file_index\n\n .parse::<usize>()\n\n .map(|i| (i, s))\n\n .map_err(|_| Error::Internal {\n", "file_path": "age-plugin/src/identity.rs", "rank": 32, "score": 76469.46381061836 }, { "content": " })\n\n .map(Ok),\n\n Err(e) => Ok(Err(e)),\n\n })\n\n }\n\n\n\n /// Requests a secret value from the user, such as a passphrase.\n\n ///\n\n /// `message` will be displayed to the user, providing context for the request.\n\n fn request_secret(&mut self, message: &str) -> plugin::Result<SecretString> {\n\n self.0\n\n .send(\"request-secret\", &[], message.as_bytes())\n\n .and_then(|res| match res {\n\n Ok(s) => String::from_utf8(s.body)\n\n .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, \"secret is not UTF-8\"))\n\n .map(|s| Ok(SecretString::new(s))),\n\n Err(e) => Ok(Err(e)),\n\n })\n\n }\n\n\n", "file_path": "age-plugin/src/identity.rs", "rank": 33, "score": 76469.42371456392 }, { "content": " .and_then(|(hrp, bytes)| {\n\n plugin.add_identity(\n\n index,\n\n &hrp[PLUGIN_IDENTITY_PREFIX.len()..hrp.len() - 1],\n\n &bytes,\n\n )\n\n })\n\n })\n\n .filter_map(|res| res.err())\n\n .collect();\n\n\n\n if errors.is_empty() {\n\n Ok(())\n\n } else {\n\n Err(errors)\n\n }\n\n });\n\n\n\n let stanzas = stanzas.and_then(|recipient_stanzas| {\n\n let mut stanzas: Vec<Vec<Stanza>> = Vec::new();\n", "file_path": "age-plugin/src/identity.rs", "rank": 34, "score": 76469.32130251841 }, { "content": " let errors: Vec<_> = items\n\n .into_iter()\n\n .enumerate()\n\n .map(|(index, item)| {\n\n bech32::decode(&item)\n\n .ok()\n\n .and_then(|(hrp, data, variant)| {\n\n if hrp.starts_with(PLUGIN_IDENTITY_PREFIX)\n\n && hrp.ends_with('-')\n\n && variant == bech32::Variant::Bech32\n\n {\n\n Vec::from_base32(&data).ok().map(|data| (hrp, data))\n\n } else {\n\n None\n\n }\n\n })\n\n .ok_or_else(|| Error::Identity {\n\n index,\n\n message: \"Invalid identity encoding\".to_owned(),\n\n })\n", "file_path": "age-plugin/src/identity.rs", "rank": 35, "score": 76468.53056894493 }, { "content": " /// is, file keys that cannot be unwrapped are implicit.\n\n ///\n\n /// `callbacks` can be used to interact with the user, to have them take some physical\n\n /// action or request a secret value.\n\n ///\n\n /// [`add_identity`]: IdentityPluginV1::add_identity\n\n fn unwrap_file_keys(\n\n &mut self,\n\n files: Vec<Vec<Stanza>>,\n\n callbacks: impl Callbacks<Error>,\n\n ) -> io::Result<HashMap<usize, Result<FileKey, Vec<Error>>>>;\n\n}\n\n\n", "file_path": "age-plugin/src/identity.rs", "rank": 36, "score": 76468.42321661585 }, { "content": " let mut errors: Vec<Error> = vec![];\n\n for (file_index, stanza) in recipient_stanzas {\n\n if let Some(file) = stanzas.get_mut(file_index) {\n\n file.push(stanza);\n\n } else if stanzas.len() == file_index {\n\n stanzas.push(vec![stanza]);\n\n } else {\n\n errors.push(Error::Internal {\n\n message: format!(\n\n \"{} file indices are not ordered and monotonically increasing\",\n\n RECIPIENT_STANZA\n\n ),\n\n });\n\n }\n\n }\n\n if errors.is_empty() {\n\n Ok(stanzas)\n\n } else {\n\n Err(errors)\n\n }\n", "file_path": "age-plugin/src/identity.rs", "rank": 37, "score": 76464.59954358058 }, { "content": " });\n\n\n\n (identities, stanzas)\n\n };\n\n\n\n // Phase 2: interactively unwrap\n\n conn.bidir_send(|mut phase| {\n\n let stanzas = match (identities, recipient_stanzas) {\n\n (Ok(()), Ok(stanzas)) => stanzas,\n\n (Err(errors1), Err(errors2)) => {\n\n for error in errors1.into_iter().chain(errors2.into_iter()) {\n\n error.send(&mut phase)?;\n\n }\n\n return Ok(());\n\n }\n\n (Err(errors), _) | (_, Err(errors)) => {\n\n for error in errors {\n\n error.send(&mut phase)?;\n\n }\n\n return Ok(());\n", "file_path": "age-plugin/src/identity.rs", "rank": 38, "score": 76464.46191687559 }, { "content": " }\n\n };\n\n\n\n let unwrapped = plugin.unwrap_file_keys(stanzas, BidirCallbacks(&mut phase))?;\n\n\n\n for (file_index, file_key) in unwrapped {\n\n match file_key {\n\n Ok(file_key) => {\n\n phase\n\n .send(\n\n \"file-key\",\n\n &[&format!(\"{}\", file_index)],\n\n file_key.expose_secret(),\n\n )?\n\n .unwrap();\n\n }\n\n Err(errors) => {\n\n for error in errors {\n\n error.send(&mut phase)?;\n\n }\n\n }\n\n }\n\n }\n\n\n\n Ok(())\n\n })\n\n}\n", "file_path": "age-plugin/src/identity.rs", "rank": 39, "score": 76460.36545294717 }, { "content": "/// An age plugin.\n\nstruct Plugin(PathBuf);\n\n\n\nimpl Plugin {\n\n /// Finds the age plugin with the given name in `$PATH`.\n\n ///\n\n /// On error, returns the binary name that could not be located.\n\n fn new(name: &str) -> Result<Self, String> {\n\n let binary_name = binary_name(name);\n\n which::which(&binary_name)\n\n .or_else(|e| {\n\n // If we are running in WSL, try appending `.exe`; plugins installed in\n\n // the Windows host are available to us, but `which` only trials PATHEXT\n\n // extensions automatically when compiled for Windows.\n\n if wsl::is_wsl() {\n\n which::which(format!(\"{}.exe\", binary_name)).map_err(|_| e)\n\n } else {\n\n Err(e)\n\n }\n\n })\n\n .map(Plugin)\n", "file_path": "age/src/plugin.rs", "rank": 40, "score": 68952.91391958411 }, { "content": "/// Handles the various types of age encryption.\n\nenum EncryptorType {\n\n /// Encryption to a list of recipients identified by keys.\n\n Keys(Vec<Box<dyn Recipient>>),\n\n /// Encryption to a passphrase.\n\n Passphrase(SecretString),\n\n}\n\n\n\n/// Encryptor for creating an age file.\n\npub struct Encryptor(EncryptorType);\n\n\n\nimpl Encryptor {\n\n /// Returns an `Encryptor` that will create an age file encrypted to a list of\n\n /// recipients.\n\n pub fn with_recipients(recipients: Vec<Box<dyn Recipient>>) -> Self {\n\n Encryptor(EncryptorType::Keys(recipients))\n\n }\n\n\n\n /// Returns an `Encryptor` that will create an age file encrypted with a passphrase.\n\n /// Anyone with the passphrase can decrypt the file.\n\n ///\n", "file_path": "age/src/protocol.rs", "rank": 41, "score": 63939.109338761715 }, { "content": "#[allow(clippy::enum_variant_names)]\n\n#[derive(Clone, Copy, Debug)]\n\nenum OpenSshCipher {\n\n Aes256Cbc,\n\n Aes128Ctr,\n\n Aes192Ctr,\n\n Aes256Ctr,\n\n}\n\n\n\nimpl OpenSshCipher {\n\n fn decrypt(\n\n self,\n\n kdf: &OpenSshKdf,\n\n p: SecretString,\n\n ct: &[u8],\n\n ) -> Result<Vec<u8>, DecryptError> {\n\n match self {\n\n OpenSshCipher::Aes256Cbc => decrypt::aes_cbc::<Aes256>(kdf, p, ct, 32),\n\n OpenSshCipher::Aes128Ctr => Ok(decrypt::aes_ctr::<Aes128Ctr>(kdf, p, ct, 16)),\n\n OpenSshCipher::Aes192Ctr => Ok(decrypt::aes_ctr::<Aes192Ctr>(kdf, p, ct, 24)),\n\n OpenSshCipher::Aes256Ctr => Ok(decrypt::aes_ctr::<Aes256Ctr>(kdf, p, ct, 32)),\n\n }\n\n }\n\n}\n\n\n\n/// OpenSSH-supported KDFs.\n", "file_path": "age/src/ssh.rs", "rank": 42, "score": 62821.302120825494 }, { "content": "#[derive(Debug)]\n\nenum StartPos {\n\n /// An offset that we can subtract from the current position.\n\n Implicit(u64),\n\n /// The precise start position.\n\n Explicit(u64),\n\n}\n\n\n\n/// Reader that will parse the age ASCII armor format if detected.\n\n#[pin_project]\n\npub struct ArmoredReader<R> {\n\n #[pin]\n\n inner: R,\n\n start: StartPos,\n\n is_armored: Option<bool>,\n\n line_buf: Zeroizing<String>,\n\n byte_buf: Zeroizing<[u8; ARMORED_BYTES_PER_LINE]>,\n\n byte_start: usize,\n\n byte_end: usize,\n\n found_short_line: bool,\n\n found_end: bool,\n", "file_path": "age/src/primitives/armor.rs", "rank": 43, "score": 62817.055253376035 }, { "content": "#[derive(Clone, Debug)]\n\nenum OpenSshKdf {\n\n Bcrypt { salt: Vec<u8>, rounds: u32 },\n\n}\n\n\n\nimpl OpenSshKdf {\n\n fn derive(&self, passphrase: SecretString, out_len: usize) -> Vec<u8> {\n\n match self {\n\n OpenSshKdf::Bcrypt { salt, rounds } => {\n\n let mut output = vec![0; out_len];\n\n bcrypt_pbkdf(passphrase.expose_secret(), &salt, *rounds, &mut output)\n\n .expect(\"parameters are valid\");\n\n output\n\n }\n\n }\n\n }\n\n}\n\n\n\n/// An encrypted SSH private key.\n\npub struct EncryptedKey {\n\n ssh_key: Vec<u8>,\n", "file_path": "age/src/ssh.rs", "rank": 44, "score": 62817.01970570418 }, { "content": "/// The position in the underlying reader corresponding to the start of the stream.\n\n///\n\n/// To impl Seek for StreamReader, we need to know the point in the reader corresponding\n\n/// to the first byte of the stream. But we can't query the reader for its current\n\n/// position without having a specific constructor for `R: Read + Seek`, which makes the\n\n/// higher-level API more complex. Instead, we count the number of bytes that have been\n\n/// read from the reader until we first need to seek, and then inside `impl Seek` we can\n\n/// query the reader's current position and figure out where the start was.\n\nenum StartPos {\n\n /// An offset that we can subtract from the current position.\n\n Implicit(u64),\n\n /// The precise start position.\n\n Explicit(u64),\n\n}\n\n\n\n/// Provides access to a decrypted age file.\n\n#[pin_project]\n\npub struct StreamReader<R> {\n\n stream: Stream,\n\n #[pin]\n\n inner: R,\n\n encrypted_chunk: Vec<u8>,\n\n encrypted_pos: usize,\n\n start: StartPos,\n\n plaintext_len: Option<u64>,\n\n cur_plaintext_pos: u64,\n\n chunk: Option<SecretVec<u8>>,\n\n}\n", "file_path": "age/src/primitives/stream.rs", "rank": 45, "score": 62812.35678249631 }, { "content": "/// Callbacks that might be triggered during encryption or decryption.\n\n///\n\n/// Structs that implement this trait should be given directly to the individual\n\n/// `Recipient` or `Identity` implementations that require them.\n\npub trait Callbacks {\n\n /// Shows a message to the user.\n\n ///\n\n /// This can be used to prompt the user to take some physical action, such as\n\n /// inserting a hardware key.\n\n fn display_message(&self, message: &str);\n\n\n\n /// Requests non-private input from the user.\n\n ///\n\n /// To request private inputs, use [`Callbacks::request_passphrase`].\n\n fn request_public_string(&self, description: &str) -> Option<String>;\n\n\n\n /// Requests a passphrase to decrypt a key.\n\n fn request_passphrase(&self, description: &str) -> Option<SecretString>;\n\n}\n\n\n\n/// Helper for fuzzing the Header parser and serializer.\n", "file_path": "age/src/lib.rs", "rank": 46, "score": 60558.337808201206 }, { "content": "#[pin_project(project = ArmorIsProj)]\n\nenum ArmorIs<W> {\n\n Enabled {\n\n #[pin]\n\n inner: LineEndingWriter<W>,\n\n byte_buf: Option<Vec<u8>>,\n\n encoded_buf: [u8; BASE64_CHUNK_SIZE_COLUMNS],\n\n #[cfg(feature = \"async\")]\n\n #[cfg_attr(docsrs, doc(cfg(feature = \"async\")))]\n\n encoded_line: Option<EncodedBytes>,\n\n },\n\n\n\n Disabled {\n\n #[pin]\n\n inner: W,\n\n },\n\n}\n\n\n\n/// Writer that optionally applies the age ASCII armor format.\n\n#[pin_project]\n\npub struct ArmoredWriter<W>(#[pin] ArmorIs<W>);\n", "file_path": "age/src/primitives/armor.rs", "rank": 47, "score": 60396.056298080875 }, { "content": "/// `decrypt[key](ciphertext)` - decrypts a message of an expected fixed size.\n\n///\n\n/// ChaCha20-Poly1305 from [RFC 7539] with a zero nonce.\n\n///\n\n/// The message size is limited to mitigate multi-key attacks, where a ciphertext can be\n\n/// crafted that decrypts successfully under multiple keys. Short ciphertexts can only\n\n/// target two keys, which has limited impact.\n\n///\n\n/// [RFC 7539]: https://tools.ietf.org/html/rfc7539\n\npub fn aead_decrypt(\n\n key: &[u8; 32],\n\n size: usize,\n\n ciphertext: &[u8],\n\n) -> Result<Vec<u8>, aead::Error> {\n\n if ciphertext.len() != size + <ChaCha20Poly1305 as AeadCore>::TagSize::to_usize() {\n\n return Err(aead::Error);\n\n }\n\n\n\n let c = ChaCha20Poly1305::new(key.into());\n\n c.decrypt(&[0; 12].into(), ciphertext)\n\n}\n\n\n", "file_path": "age-core/src/primitives.rs", "rank": 48, "score": 58372.845676499535 }, { "content": "/// Requests a secret from the user.\n\n///\n\n/// If a `pinentry` binary is available on the system, it is used to request the secret.\n\n/// If not, we fall back to requesting directly in the CLI via a TTY.\n\n///\n\n/// This API does not take the secret directly from stdin, because it is specifically\n\n/// intended to take the secret from a human.\n\n///\n\n/// # Parameters\n\n///\n\n/// - `description` is the primary information provided to the user about the secret\n\n/// being requested. It is printed in all cases.\n\n/// - `prompt` is a short phrase such as \"Passphrase\" or \"PIN\". It is printed in front of\n\n/// the input field when `pinentry` is used.\n\n/// - `confirm` is an optional short phrase such as \"Confirm passphrase\". Setting it\n\n/// enables input confirmation.\n\n/// - If `confirm.is_some()` then an empty secret is allowed.\n\npub fn read_secret(\n\n description: &str,\n\n prompt: &str,\n\n confirm: Option<&str>,\n\n) -> pinentry::Result<SecretString> {\n\n if let Some(mut input) = PassphraseInput::with_default_binary() {\n\n // pinentry binary is available!\n\n let mismatch_error = fl!(\"cli-secret-input-mismatch\");\n\n let empty_error = fl!(\"cli-secret-input-required\");\n\n input\n\n .with_description(description)\n\n .with_prompt(prompt)\n\n .with_timeout(30);\n\n if let Some(confirm_prompt) = confirm {\n\n input.with_confirmation(confirm_prompt, &mismatch_error);\n\n } else {\n\n input.required(&empty_error);\n\n }\n\n input.interact()\n\n } else {\n", "file_path": "age/src/cli_common.rs", "rank": 49, "score": 58372.42394516492 }, { "content": "/// Creates a random recipient stanza that exercises the joint in the age v1 format.\n\n///\n\n/// This function is guaranteed to return a valid stanza, but makes no other guarantees\n\n/// about the stanza's fields.\n\npub fn grease_the_joint() -> Stanza {\n\n // Generate arbitrary strings between 1 and 9 characters long.\n\n fn gen_arbitrary_string<R: RngCore>(rng: &mut R) -> String {\n\n let length = Uniform::from(1..9).sample(rng);\n\n Uniform::from(33..=126)\n\n .sample_iter(rng)\n\n .map(char::from)\n\n .take(length)\n\n .collect()\n\n }\n\n\n\n let mut rng = thread_rng();\n\n\n\n // Add a suffix to the random tag so users know what is going on.\n\n let tag = format!(\"{}-grease\", gen_arbitrary_string(&mut rng));\n\n\n\n // Between this and the above generation bounds, the first line of the recipient\n\n // stanza will be between eight and 66 characters.\n\n let args = (0..Uniform::from(0..5).sample(&mut rng))\n\n .map(|_| gen_arbitrary_string(&mut rng))\n", "file_path": "age-core/src/format.rs", "rank": 50, "score": 55440.881743013684 }, { "content": "/// The interface that age plugins can use to interact with an age implementation.\n\nstruct BidirCallbacks<'a, 'b, R: io::Read, W: io::Write>(&'b mut BidirSend<'a, R, W>);\n\n\n\nimpl<'a, 'b, R: io::Read, W: io::Write> Callbacks<Error> for BidirCallbacks<'a, 'b, R, W> {\n\n /// Shows a message to the user.\n\n ///\n\n /// This can be used to prompt the user to take some physical action, such as\n\n /// inserting a hardware key.\n\n fn message(&mut self, message: &str) -> plugin::Result<()> {\n\n self.0\n\n .send(\"msg\", &[], message.as_bytes())\n\n .map(|res| res.map(|_| ()))\n\n }\n\n\n\n fn request_public(&mut self, message: &str) -> plugin::Result<String> {\n\n self.0\n\n .send(\"request-public\", &[], message.as_bytes())\n\n .and_then(|res| match res {\n\n Ok(s) => String::from_utf8(s.body)\n\n .map_err(|_| {\n\n io::Error::new(io::ErrorKind::InvalidData, \"response is not UTF-8\")\n", "file_path": "age-plugin/src/recipient.rs", "rank": 51, "score": 54399.68922762991 }, { "content": "/// The interface that age plugins can use to interact with an age implementation.\n\nstruct BidirCallbacks<'a, 'b, R: io::Read, W: io::Write>(&'b mut BidirSend<'a, R, W>);\n\n\n\nimpl<'a, 'b, R: io::Read, W: io::Write> Callbacks<Error> for BidirCallbacks<'a, 'b, R, W> {\n\n /// Shows a message to the user.\n\n ///\n\n /// This can be used to prompt the user to take some physical action, such as\n\n /// inserting a hardware key.\n\n fn message(&mut self, message: &str) -> plugin::Result<()> {\n\n self.0\n\n .send(\"msg\", &[], message.as_bytes())\n\n .map(|res| res.map(|_| ()))\n\n }\n\n\n\n fn request_public(&mut self, message: &str) -> plugin::Result<String> {\n\n self.0\n\n .send(\"request-public\", &[], message.as_bytes())\n\n .and_then(|res| match res {\n\n Ok(s) => String::from_utf8(s.body)\n\n .map_err(|_| {\n\n io::Error::new(io::ErrorKind::InvalidData, \"response is not UTF-8\")\n", "file_path": "age-plugin/src/identity.rs", "rank": 52, "score": 54221.69396194972 }, { "content": "#[cfg(fuzzing)]\n\npub fn fuzz_header(data: &[u8]) {\n\n if let Ok(header) = format::Header::read(data) {\n\n let mut buf = Vec::with_capacity(data.len());\n\n header.write(&mut buf).expect(\"can write header\");\n\n assert_eq!(&buf[..], &data[..buf.len()]);\n\n }\n\n}\n", "file_path": "age/src/lib.rs", "rank": 53, "score": 53807.69446879418 }, { "content": "/// Returns the [`Localizer`] to be used for localizing this library.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// // Fetch the set of languages that the user's desktop environment requests.\n\n/// let requested_languages = i18n_embed::DesktopLanguageRequester::requested_languages();\n\n///\n\n/// // Localize the age crate based on the requested languages.\n\n/// //\n\n/// // If none of the requested languages are available, or if this function\n\n/// // is not called, age defaults to en-US.\n\n/// age::localizer().select(&requested_languages).unwrap();\n\n/// ```\n\npub fn localizer() -> Box<dyn Localizer> {\n\n Box::from(DefaultLocalizer::new(&*LANGUAGE_LOADER, &TRANSLATIONS))\n\n}\n", "file_path": "age/src/i18n.rs", "rank": 54, "score": 52418.77207567965 }, { "content": "fn generate_manpage(page: String, name: &str) {\n\n let file = File::create(format!(\"{}/{}.1.gz\", MANPAGES_DIR, name))\n\n .expect(\"Should be able to open file in target directory\");\n\n let mut encoder = GzEncoder::new(file, Compression::best());\n\n encoder\n\n .write_all(page.as_bytes())\n\n .expect(\"Should be able to write to file in target directory\");\n\n}\n\n\n", "file_path": "rage/examples/generate-docs.rs", "rank": 55, "score": 51631.41232783404 }, { "content": "fn generate_completion<G: Generator, S: Into<String>>(\n\n app: &mut App,\n\n bin_name: S,\n\n file_name: String,\n\n) {\n\n let mut file = File::create(format!(\"{}/{}\", COMPLETIONS_DIR, file_name))\n\n .expect(\"Should be able to open file in target directory\");\n\n generate::<G, _>(app, bin_name, &mut file);\n\n}\n\n\n", "file_path": "rage/examples/generate-completions.rs", "rank": 56, "score": 50365.7580022155 }, { "content": "/// Reads a passphrase from stdin, or generates a secure one if none is provided.\n\npub fn read_or_generate_passphrase() -> pinentry::Result<Passphrase> {\n\n let res = read_secret(\n\n &fl!(\"cli-passphrase-desc\"),\n\n &fl!(\"cli-passphrase-prompt\"),\n\n Some(&fl!(\"cli-passphrase-confirm\")),\n\n )?;\n\n\n\n if res.expose_secret().is_empty() {\n\n Ok(Passphrase::random(OsRng))\n\n } else {\n\n Ok(Passphrase::Typed(res))\n\n }\n\n}\n", "file_path": "age/src/cli_common.rs", "rank": 57, "score": 49727.643849637476 }, { "content": "#[derive(Debug, Options)]\n\nstruct PluginOptions {\n\n #[options(help = \"print help message\")]\n\n help: bool,\n\n\n\n #[options(help = \"run the given age plugin state machine\", no_short)]\n\n age_plugin: Option<String>,\n\n}\n\n\n", "file_path": "age-plugin/examples/age-plugin-unencrypted.rs", "rank": 58, "score": 47872.2900183572 }, { "content": "use age_core::{\n\n format::{FileKey, Stanza},\n\n secrecy::ExposeSecret,\n\n};\n\nuse age_plugin::{\n\n identity::{self, IdentityPluginV1},\n\n print_new_identity,\n\n recipient::{self, RecipientPluginV1},\n\n run_state_machine, Callbacks,\n\n};\n\nuse gumdrop::Options;\n\nuse std::collections::HashMap;\n\nuse std::convert::TryInto;\n\nuse std::io;\n\n\n\nconst PLUGIN_NAME: &str = \"unencrypted\";\n\nconst RECIPIENT_TAG: &str = PLUGIN_NAME;\n\n\n", "file_path": "age-plugin/examples/age-plugin-unencrypted.rs", "rank": 59, "score": 44923.29956364675 }, { "content": " fn add_identity(\n\n &mut self,\n\n index: usize,\n\n plugin_name: &str,\n\n _bytes: &[u8],\n\n ) -> Result<(), recipient::Error> {\n\n if plugin_name == PLUGIN_NAME {\n\n // A real plugin would store the identity.\n\n Ok(())\n\n } else {\n\n Err(recipient::Error::Identity {\n\n index,\n\n message: \"invalid identity\".to_owned(),\n\n })\n\n }\n\n }\n\n\n\n fn wrap_file_keys(\n\n &mut self,\n\n file_keys: Vec<FileKey>,\n", "file_path": "age-plugin/examples/age-plugin-unencrypted.rs", "rank": 60, "score": 44921.74669046855 }, { "content": " mut callbacks: impl Callbacks<recipient::Error>,\n\n ) -> io::Result<Result<Vec<Vec<Stanza>>, Vec<recipient::Error>>> {\n\n // A real plugin would wrap the file key here.\n\n let _ = callbacks\n\n .message(\"This plugin doesn't have any recipient-specific logic. It's unencrypted!\")?;\n\n Ok(Ok(file_keys\n\n .into_iter()\n\n .map(|file_key| {\n\n // TODO: This should return one stanza per recipient and identity.\n\n vec![Stanza {\n\n tag: RECIPIENT_TAG.to_owned(),\n\n args: vec![\"does\".to_owned(), \"nothing\".to_owned()],\n\n body: file_key.expose_secret().to_vec(),\n\n }]\n\n })\n\n .collect()))\n\n }\n\n}\n\n\n", "file_path": "age-plugin/examples/age-plugin-unencrypted.rs", "rank": 61, "score": 44919.06010611857 }, { "content": " fn unwrap_file_keys(\n\n &mut self,\n\n files: Vec<Vec<Stanza>>,\n\n mut callbacks: impl Callbacks<identity::Error>,\n\n ) -> io::Result<HashMap<usize, Result<FileKey, Vec<identity::Error>>>> {\n\n let mut file_keys = HashMap::with_capacity(files.len());\n\n for (file_index, stanzas) in files.into_iter().enumerate() {\n\n for stanza in stanzas {\n\n if stanza.tag == RECIPIENT_TAG {\n\n // A real plugin would attempt to unwrap the file key with the stored\n\n // identities.\n\n let _ = callbacks.message(\"This identity does nothing!\")?;\n\n file_keys.entry(file_index).or_insert(Ok(FileKey::from(\n\n TryInto::<[u8; 16]>::try_into(&stanza.body[..]).unwrap(),\n\n )));\n\n break;\n\n }\n\n }\n\n }\n\n Ok(file_keys)\n\n }\n\n}\n\n\n", "file_path": "age-plugin/examples/age-plugin-unencrypted.rs", "rank": 62, "score": 44917.04542555934 }, { "content": "/// `encrypt[key](plaintext)` - encrypts a message with a one-time key.\n\n///\n\n/// ChaCha20-Poly1305 from [RFC 7539] with a zero nonce.\n\n///\n\n/// [RFC 7539]: https://tools.ietf.org/html/rfc7539\n\npub fn aead_encrypt(key: &[u8; 32], plaintext: &[u8]) -> Vec<u8> {\n\n let c = ChaCha20Poly1305::new(key.into());\n\n c.encrypt(&[0; 12].into(), plaintext)\n\n .expect(\"we won't overflow the ChaCha20 block counter\")\n\n}\n\n\n", "file_path": "age-core/src/primitives.rs", "rank": 63, "score": 44159.2478590681 }, { "content": "struct DecryptableIdentity<C: Callbacks> {\n\n identity: Identity,\n\n callbacks: C,\n\n}\n\n\n\nimpl<C: Callbacks> crate::Identity for DecryptableIdentity<C> {\n\n fn unwrap_stanza(&self, stanza: &Stanza) -> Option<Result<FileKey, DecryptError>> {\n\n match &self.identity {\n\n Identity::Unencrypted(key) => key.unwrap_stanza(stanza),\n\n Identity::Encrypted(enc) => {\n\n let passphrase = self.callbacks.request_passphrase(&fl!(\n\n crate::i18n::LANGUAGE_LOADER,\n\n \"ssh-passphrase-prompt\",\n\n filename = enc.filename.as_deref().unwrap_or_default()\n\n ))?;\n\n let decrypted = match enc.decrypt(passphrase) {\n\n Ok(d) => d,\n\n Err(e) => return Some(Err(e)),\n\n };\n\n decrypted.unwrap_stanza(stanza)\n\n }\n\n Identity::Unsupported(_) => None,\n\n }\n\n }\n\n}\n\n\n", "file_path": "age/src/ssh/identity.rs", "rank": 64, "score": 44105.054083052804 }, { "content": "/// `HKDF[salt, label](key, 32)`\n\n///\n\n/// HKDF from [RFC 5869] with SHA-256.\n\n///\n\n/// [RFC 5869]: https://tools.ietf.org/html/rfc5869\n\npub fn hkdf(salt: &[u8], label: &[u8], ikm: &[u8]) -> [u8; 32] {\n\n let mut okm = [0; 32];\n\n Hkdf::<Sha256>::new(Some(salt), ikm)\n\n .expand(label, &mut okm)\n\n .expect(\"okm is the correct length\");\n\n okm\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{aead_decrypt, aead_encrypt};\n\n\n\n #[test]\n\n fn aead_round_trip() {\n\n let key = [14; 32];\n\n let plaintext = b\"12345678\";\n\n let encrypted = aead_encrypt(&key, plaintext);\n\n let decrypted = aead_decrypt(&key, plaintext.len(), &encrypted).unwrap();\n\n assert_eq!(decrypted, plaintext);\n\n }\n\n}\n", "file_path": "age-core/src/primitives.rs", "rank": 65, "score": 43421.63552658592 }, { "content": "fn main() -> io::Result<()> {\n\n let opts = PluginOptions::parse_args_default_or_exit();\n\n\n\n if let Some(state_machine) = opts.age_plugin {\n\n run_state_machine(&state_machine, || RecipientPlugin, || IdentityPlugin)\n\n } else {\n\n // A real plugin would generate a new identity here.\n\n print_new_identity(PLUGIN_NAME, &[], &[]);\n\n Ok(())\n\n }\n\n}\n", "file_path": "age-plugin/examples/age-plugin-unencrypted.rs", "rank": 66, "score": 42516.91057848511 }, { "content": "fn openssh_privkey(input: &str) -> IResult<&str, Identity> {\n\n preceded(\n\n pair(tag(\"-----BEGIN OPENSSH PRIVATE KEY-----\"), line_ending),\n\n terminated(\n\n map_opt(wrapped_str_while_encoded(base64::STANDARD), |privkey| {\n\n read_ssh::openssh_privkey(&privkey).ok().map(|(_, key)| key)\n\n }),\n\n pair(line_ending, tag(\"-----END OPENSSH PRIVATE KEY-----\")),\n\n ),\n\n )(input)\n\n}\n\n\n\npub(crate) fn ssh_identity(input: &str) -> IResult<&str, Identity> {\n\n alt((rsa_privkey, openssh_privkey))(input)\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod tests {\n\n use age_core::secrecy::ExposeSecret;\n\n use std::io::BufReader;\n", "file_path": "age/src/ssh/identity.rs", "rank": 67, "score": 41840.95470891687 }, { "content": "fn rsa_privkey(input: &str) -> IResult<&str, Identity> {\n\n preceded(\n\n pair(tag(\"-----BEGIN RSA PRIVATE KEY-----\"), line_ending),\n\n terminated(\n\n map_opt(\n\n pair(\n\n opt(terminated(rsa_pem_encryption_header, line_ending)),\n\n wrapped_str_while_encoded(base64::STANDARD),\n\n ),\n\n |(enc_header, privkey)| {\n\n if enc_header.is_some() {\n\n Some(UnsupportedKey::EncryptedPem.into())\n\n } else {\n\n read_asn1::rsa_privkey(&privkey).ok().map(|(_, privkey)| {\n\n let mut ssh_key = vec![];\n\n cookie_factory::gen(\n\n write_ssh::rsa_pubkey(&privkey.to_public_key()),\n\n &mut ssh_key,\n\n )\n\n .expect(\"can write into a Vec\");\n\n UnencryptedKey::SshRsa(ssh_key, Box::new(privkey)).into()\n\n })\n\n }\n\n },\n\n ),\n\n pair(line_ending, tag(\"-----END RSA PRIVATE KEY-----\")),\n\n ),\n\n )(input)\n\n}\n\n\n", "file_path": "age/src/ssh/identity.rs", "rank": 68, "score": 41840.95470891687 }, { "content": "fn ssh_ed25519_pubkey(input: &str) -> IResult<&str, Option<Recipient>> {\n\n preceded(\n\n pair(tag(SSH_ED25519_KEY_PREFIX), tag(\" \")),\n\n map_opt(\n\n encoded_str(51, base64::STANDARD_NO_PAD),\n\n |ssh_key| match read_ssh::ed25519_pubkey(&ssh_key) {\n\n Ok((_, pk)) => Some(Some(Recipient::SshEd25519(ssh_key, pk))),\n\n Err(_) => None,\n\n },\n\n ),\n\n )(input)\n\n}\n\n\n", "file_path": "age/src/ssh/recipient.rs", "rank": 69, "score": 40719.60599451083 }, { "content": "fn ssh_ignore_pubkey(input: &str) -> IResult<&str, Option<Recipient>> {\n\n // We rely on the invariant that SSH public keys are always of the form\n\n // `key_type Base64(string(key_type) || ...)` to detect valid pubkeys.\n\n map_opt(\n\n separated_pair(\n\n is_not(\" \"),\n\n tag(\" \"),\n\n str_while_encoded(base64::STANDARD_NO_PAD),\n\n ),\n\n |(key_type, ssh_key)| read_ssh::string_tag(key_type)(&ssh_key).map(|_| None).ok(),\n\n )(input)\n\n}\n\n\n\npub(crate) fn ssh_recipient(input: &str) -> IResult<&str, Option<Recipient>> {\n\n alt((ssh_rsa_pubkey, ssh_ed25519_pubkey, ssh_ignore_pubkey))(input)\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod tests {\n\n use super::{ParseRecipientKeyError, Recipient};\n", "file_path": "age/src/ssh/recipient.rs", "rank": 70, "score": 40719.60599451083 }, { "content": "fn ssh_rsa_pubkey(input: &str) -> IResult<&str, Option<Recipient>> {\n\n preceded(\n\n pair(tag(SSH_RSA_KEY_PREFIX), tag(\" \")),\n\n map_opt(\n\n str_while_encoded(base64::STANDARD_NO_PAD),\n\n |ssh_key| match read_ssh::rsa_pubkey(&ssh_key) {\n\n Ok((_, pk)) => Some(Some(Recipient::SshRsa(ssh_key, pk))),\n\n Err(_) => None,\n\n },\n\n ),\n\n )(input)\n\n}\n\n\n", "file_path": "age/src/ssh/recipient.rs", "rank": 71, "score": 40719.60599451083 }, { "content": " IdentityFileEntry::Native(i) => Ok(Box::new(i.to_public())),\n\n #[cfg(feature = \"plugin\")]\n\n IdentityFileEntry::Plugin(i) => Ok(Box::new(crate::plugin::RecipientPluginV1::new(\n\n &i.plugin().to_owned(),\n\n &[],\n\n &[i.clone()],\n\n callbacks,\n\n )?)),\n\n }\n\n }\n\n}\n\n\n\n/// A list of identities that has been parsed from some input file.\n\npub struct IdentityFile {\n\n identities: Vec<IdentityFileEntry>,\n\n}\n\n\n\nimpl IdentityFile {\n\n /// Parses one or more identities from a file containing valid UTF-8.\n\n pub fn from_file(filename: String) -> io::Result<Self> {\n", "file_path": "age/src/identity.rs", "rank": 72, "score": 39866.08424539374 }, { "content": "use std::fs::File;\n\nuse std::io;\n\n\n\nuse crate::{x25519, Callbacks, DecryptError, EncryptError};\n\n\n\n#[cfg(feature = \"plugin\")]\n\nuse crate::plugin;\n\n\n\n/// The supported kinds of identities within an [`IdentityFile`].\n\n#[derive(Clone)]\n\npub enum IdentityFileEntry {\n\n /// The standard age identity type.\n\n Native(x25519::Identity),\n\n /// A plugin-compatible identity.\n\n #[cfg(feature = \"plugin\")]\n\n #[cfg_attr(docsrs, doc(cfg(feature = \"plugin\")))]\n\n Plugin(plugin::Identity),\n\n}\n\n\n\nimpl IdentityFileEntry {\n", "file_path": "age/src/identity.rs", "rank": 73, "score": 39863.92867398104 }, { "content": " pub(crate) fn into_identity(\n\n self,\n\n callbacks: impl Callbacks + 'static,\n\n ) -> Result<Box<dyn crate::Identity>, DecryptError> {\n\n match self {\n\n IdentityFileEntry::Native(i) => Ok(Box::new(i)),\n\n #[cfg(feature = \"plugin\")]\n\n IdentityFileEntry::Plugin(i) => Ok(Box::new(crate::plugin::IdentityPluginV1::new(\n\n &i.plugin().to_owned(),\n\n &[i],\n\n callbacks,\n\n )?)),\n\n }\n\n }\n\n\n\n pub(crate) fn to_recipient(\n\n &self,\n\n callbacks: impl Callbacks + 'static,\n\n ) -> Result<Box<dyn crate::Recipient>, EncryptError> {\n\n match self {\n", "file_path": "age/src/identity.rs", "rank": 74, "score": 39863.66367159962 }, { "content": " }\n\n\n\n /// Returns the identities in this file.\n\n pub fn into_identities(self) -> Vec<IdentityFileEntry> {\n\n self.identities\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod tests {\n\n use age_core::secrecy::ExposeSecret;\n\n use std::io::BufReader;\n\n\n\n use super::{IdentityFile, IdentityFileEntry};\n\n\n\n pub(crate) const TEST_SK: &str =\n\n \"AGE-SECRET-KEY-1GQ9778VQXMMJVE8SK7J6VT8UJ4HDQAJUVSFCWCM02D8GEWQ72PVQ2Y5J33\";\n\n\n\n fn valid_secret_key_encoding(keydata: &str, num_keys: usize) {\n\n let buf = BufReader::new(keydata.as_bytes());\n", "file_path": "age/src/identity.rs", "rank": 75, "score": 39859.56079034345 }, { "content": " let f = IdentityFile::from_buffer(buf).unwrap();\n\n assert_eq!(f.identities.len(), num_keys);\n\n match &f.identities[0] {\n\n IdentityFileEntry::Native(identity) => {\n\n assert_eq!(identity.to_string().expose_secret(), TEST_SK)\n\n }\n\n #[cfg(feature = \"plugin\")]\n\n IdentityFileEntry::Plugin(_) => panic!(),\n\n }\n\n }\n\n\n\n #[test]\n\n fn secret_key_encoding() {\n\n valid_secret_key_encoding(TEST_SK, 1);\n\n }\n\n\n\n #[test]\n\n fn secret_key_lf() {\n\n valid_secret_key_encoding(&format!(\"{}\\n\", TEST_SK), 1);\n\n }\n", "file_path": "age/src/identity.rs", "rank": 76, "score": 39857.943599387465 }, { "content": " File::open(&filename)\n\n .map(io::BufReader::new)\n\n .and_then(|data| IdentityFile::parse_identities(Some(filename), data))\n\n }\n\n\n\n /// Parses one or more identities from a buffered input containing valid UTF-8.\n\n pub fn from_buffer<R: io::BufRead>(data: R) -> io::Result<Self> {\n\n Self::parse_identities(None, data)\n\n }\n\n\n\n fn parse_identities<R: io::BufRead>(filename: Option<String>, data: R) -> io::Result<Self> {\n\n let mut identities = vec![];\n\n\n\n for (line_number, line) in data.lines().enumerate() {\n\n let line = line?;\n\n if line.is_empty() || line.starts_with('#') {\n\n continue;\n\n }\n\n\n\n if let Ok(identity) = line.parse::<x25519::Identity>() {\n", "file_path": "age/src/identity.rs", "rank": 77, "score": 39856.24446550444 }, { "content": " identities.push(IdentityFileEntry::Native(identity));\n\n } else if let Some(identity) = {\n\n #[cfg(feature = \"plugin\")]\n\n {\n\n line.parse::<plugin::Identity>().ok()\n\n }\n\n\n\n #[cfg(not(feature = \"plugin\"))]\n\n None\n\n } {\n\n #[cfg(feature = \"plugin\")]\n\n {\n\n identities.push(IdentityFileEntry::Plugin(identity));\n\n }\n\n\n\n // Add a binding to provide a type when plugins are disabled.\n\n #[cfg(not(feature = \"plugin\"))]\n\n let _: () = identity;\n\n } else {\n\n // Return a line number in place of the line, so we don't leak the file\n", "file_path": "age/src/identity.rs", "rank": 78, "score": 39856.10931718351 }, { "content": " // contents in error messages.\n\n return Err(io::Error::new(\n\n io::ErrorKind::InvalidData,\n\n if let Some(filename) = filename {\n\n format!(\n\n \"identity file {} contains non-identity data on line {}\",\n\n filename,\n\n line_number + 1\n\n )\n\n } else {\n\n format!(\n\n \"identity file contains non-identity data on line {}\",\n\n line_number + 1\n\n )\n\n },\n\n ));\n\n }\n\n }\n\n\n\n Ok(IdentityFile { identities })\n", "file_path": "age/src/identity.rs", "rank": 79, "score": 39854.14760550638 }, { "content": " }\n\n\n\n #[test]\n\n fn two_secret_keys_crlf() {\n\n valid_secret_key_encoding(&format!(\"{}\\r\\n{}\", TEST_SK, TEST_SK), 2);\n\n }\n\n\n\n #[test]\n\n fn secret_key_with_comment_crlf() {\n\n valid_secret_key_encoding(&format!(\"# Foo bar baz\\r\\n{}\", TEST_SK), 1);\n\n valid_secret_key_encoding(&format!(\"{}\\r\\n# Foo bar baz\", TEST_SK), 1);\n\n }\n\n\n\n #[test]\n\n fn secret_key_with_empty_line_crlf() {\n\n valid_secret_key_encoding(&format!(\"\\r\\n\\r\\n{}\", TEST_SK), 1);\n\n }\n\n\n\n #[test]\n\n fn incomplete_secret_key_encoding() {\n\n let buf = BufReader::new(&TEST_SK.as_bytes()[..4]);\n\n assert!(IdentityFile::from_buffer(buf).is_err());\n\n }\n\n}\n", "file_path": "age/src/identity.rs", "rank": 80, "score": 39848.19750395065 }, { "content": "\n\n #[test]\n\n fn two_secret_keys_lf() {\n\n valid_secret_key_encoding(&format!(\"{}\\n{}\", TEST_SK, TEST_SK), 2);\n\n }\n\n\n\n #[test]\n\n fn secret_key_with_comment_lf() {\n\n valid_secret_key_encoding(&format!(\"# Foo bar baz\\n{}\", TEST_SK), 1);\n\n valid_secret_key_encoding(&format!(\"{}\\n# Foo bar baz\", TEST_SK), 1);\n\n }\n\n\n\n #[test]\n\n fn secret_key_with_empty_line_lf() {\n\n valid_secret_key_encoding(&format!(\"\\n\\n{}\", TEST_SK), 1);\n\n }\n\n\n\n #[test]\n\n fn secret_key_crlf() {\n\n valid_secret_key_encoding(&format!(\"{}\\r\\n\", TEST_SK), 1);\n", "file_path": "age/src/identity.rs", "rank": 81, "score": 39845.282253604004 }, { "content": "\n\nimpl Recipient {\n\n /// Returns the plugin name for this recipient.\n\n pub fn plugin(&self) -> &str {\n\n &self.name\n\n }\n\n}\n\n\n\n/// A plugin-compatible identity.\n\n#[derive(Clone)]\n\npub struct Identity {\n\n /// The plugin name, extracted from `identity`.\n\n name: String,\n\n /// The identity.\n\n identity: String,\n\n}\n\n\n\nimpl std::str::FromStr for Identity {\n\n type Err = &'static str;\n\n\n", "file_path": "age/src/plugin.rs", "rank": 82, "score": 39127.29593163783 }, { "content": " kind: \"internal\".to_owned(),\n\n metadata: vec![],\n\n message: format!(\n\n \"{} command must have at least two metadata arguments\",\n\n CMD_RECIPIENT_STANZA\n\n ),\n\n });\n\n }\n\n reply.ok(None)\n\n }\n\n CMD_ERROR => {\n\n if command.args.len() == 2 && command.args[0] == \"recipient\" {\n\n let index: usize = command.args[1].parse().unwrap();\n\n errors.push(PluginError::Recipient {\n\n binary_name: binary_name(&self.recipients[index].name),\n\n recipient: self.recipients[index].recipient.clone(),\n\n message: String::from_utf8_lossy(&command.body).to_string(),\n\n });\n\n } else if command.args.len() == 2 && command.args[0] == \"identity\" {\n\n let index: usize = command.args[1].parse().unwrap();\n", "file_path": "age/src/plugin.rs", "rank": 83, "score": 39122.54212686249 }, { "content": " /// Creates an age plugin from a plugin name and lists of recipients and identities.\n\n ///\n\n /// The lists of recipients and identities will be filtered by the plugin name;\n\n /// recipients that don't match will be ignored.\n\n ///\n\n /// Returns an error if the plugin's binary cannot be found in `$PATH`.\n\n pub fn new(\n\n plugin_name: &str,\n\n recipients: &[Recipient],\n\n identities: &[Identity],\n\n callbacks: C,\n\n ) -> Result<Self, EncryptError> {\n\n Plugin::new(plugin_name)\n\n .map_err(|binary_name| EncryptError::MissingPlugin { binary_name })\n\n .map(|plugin| RecipientPluginV1 {\n\n plugin,\n\n recipients: recipients\n\n .iter()\n\n .filter(|r| r.name == plugin_name)\n\n .cloned()\n", "file_path": "age/src/plugin.rs", "rank": 84, "score": 39121.84193253541 }, { "content": " .map_err(|_| binary_name)\n\n }\n\n\n\n fn connect(&self, state_machine: &str) -> io::Result<Connection<ChildStdout, ChildStdin>> {\n\n Connection::open(&self.0, state_machine)\n\n }\n\n}\n\n\n\n/// An age plugin with an associated set of recipients.\n\n///\n\n/// This struct implements [`Recipient`], enabling the plugin to encrypt a file to the\n\n/// entire set of recipients.\n\npub struct RecipientPluginV1<C: Callbacks> {\n\n plugin: Plugin,\n\n recipients: Vec<Recipient>,\n\n identities: Vec<Identity>,\n\n callbacks: C,\n\n}\n\n\n\nimpl<C: Callbacks> RecipientPluginV1<C> {\n", "file_path": "age/src/plugin.rs", "rank": 85, "score": 39121.12445975584 }, { "content": " errors.push(PluginError::Identity {\n\n binary_name: binary_name(&self.identities[index].name),\n\n message: String::from_utf8_lossy(&command.body).to_string(),\n\n });\n\n } else {\n\n errors.push(PluginError::from(command));\n\n }\n\n reply.ok(None)\n\n }\n\n _ => unreachable!(),\n\n },\n\n ) {\n\n return Err(e.into());\n\n };\n\n match (stanzas.is_empty(), errors.is_empty()) {\n\n (false, true) => Ok(stanzas),\n\n (a, b) => {\n\n if a & b {\n\n errors.push(PluginError::Other {\n\n kind: \"internal\".to_owned(),\n", "file_path": "age/src/plugin.rs", "rank": 86, "score": 39120.261021959726 }, { "content": " CMD_ERROR => {\n\n if command.args.len() == 2 && command.args[0] == \"identity\" {\n\n let index: usize = command.args[1].parse().unwrap();\n\n errors.push(PluginError::Identity {\n\n binary_name: binary_name(&self.identities[index].name),\n\n message: String::from_utf8_lossy(&command.body).to_string(),\n\n });\n\n } else {\n\n errors.push(PluginError::from(command));\n\n }\n\n reply.ok(None)\n\n }\n\n _ => unreachable!(),\n\n },\n\n ) {\n\n return Some(Err(e.into()));\n\n };\n\n\n\n if file_key.is_none() && !errors.is_empty() {\n\n Some(Err(DecryptError::Plugin(errors)))\n", "file_path": "age/src/plugin.rs", "rank": 87, "score": 39120.21032210955 }, { "content": "//! Support for the age plugin system.\n\n\n\nuse age_core::{\n\n format::{FileKey, Stanza},\n\n plugin::{Connection, IDENTITY_V1, RECIPIENT_V1},\n\n secrecy::ExposeSecret,\n\n};\n\nuse bech32::Variant;\n\nuse std::convert::TryInto;\n\nuse std::fmt;\n\nuse std::io;\n\nuse std::iter;\n\nuse std::path::PathBuf;\n\nuse std::process::{ChildStdin, ChildStdout};\n\n\n\nuse crate::{\n\n error::{DecryptError, EncryptError, PluginError},\n\n util::parse_bech32,\n\n Callbacks,\n\n};\n", "file_path": "age/src/plugin.rs", "rank": 88, "score": 39119.500160411124 }, { "content": " } else {\n\n file_key\n\n }\n\n }\n\n}\n\n\n\nimpl<C: Callbacks> crate::Identity for IdentityPluginV1<C> {\n\n fn unwrap_stanza(&self, stanza: &Stanza) -> Option<Result<FileKey, DecryptError>> {\n\n self.unwrap_stanzas(iter::once(stanza))\n\n }\n\n\n\n fn unwrap_stanzas(&self, stanzas: &[Stanza]) -> Option<Result<FileKey, DecryptError>> {\n\n self.unwrap_stanzas(stanzas.iter())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::Identity;\n\n\n\n #[test]\n\n fn default_for_plugin() {\n\n assert_eq!(\n\n Identity::default_for_plugin(\"foobar\").to_string(),\n\n \"AGE-PLUGIN-FOOBAR-1QVHULF\",\n\n );\n\n }\n\n}\n", "file_path": "age/src/plugin.rs", "rank": 89, "score": 39119.30176634499 }, { "content": " metadata: vec![],\n\n message: \"Plugin returned neither stanzas nor errors\".to_owned(),\n\n });\n\n } else if !a & !b {\n\n errors.push(PluginError::Other {\n\n kind: \"internal\".to_owned(),\n\n metadata: vec![],\n\n message: \"Plugin returned both stanzas and errors\".to_owned(),\n\n });\n\n }\n\n Err(EncryptError::Plugin(errors))\n\n }\n\n }\n\n }\n\n}\n\n\n\n/// An age plugin with an associated set of identities.\n\n///\n\n/// This struct implements [`Identity`], enabling the plugin to decrypt a file with any\n\n/// identity in the set of identities.\n", "file_path": "age/src/plugin.rs", "rank": 90, "score": 39118.15671474497 }, { "content": "pub struct IdentityPluginV1<C: Callbacks> {\n\n plugin: Plugin,\n\n identities: Vec<Identity>,\n\n callbacks: C,\n\n}\n\n\n\nimpl<C: Callbacks> IdentityPluginV1<C> {\n\n /// Creates an age plugin from a plugin name and a list of identities.\n\n ///\n\n /// The list of identities will be filtered by the plugin name; identities that don't\n\n /// match will be ignored.\n\n ///\n\n /// Returns an error if the plugin's binary cannot be found in `$PATH`.\n\n pub fn new(\n\n plugin_name: &str,\n\n identities: &[Identity],\n\n callbacks: C,\n\n ) -> Result<Self, DecryptError> {\n\n Plugin::new(plugin_name)\n\n .map_err(|binary_name| DecryptError::MissingPlugin { binary_name })\n", "file_path": "age/src/plugin.rs", "rank": 91, "score": 39118.12756575722 }, { "content": " }\n\n}\n\n\n\nimpl fmt::Display for Identity {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{}\", self.identity)\n\n }\n\n}\n\n\n\nimpl Identity {\n\n /// Returns the identity corresponding to the given plugin name in its default mode.\n\n pub fn default_for_plugin(plugin_name: &str) -> Self {\n\n bech32::encode(\n\n &format!(\"{}{}-\", PLUGIN_IDENTITY_PREFIX, plugin_name),\n\n &[],\n\n Variant::Bech32,\n\n )\n\n .expect(\"HRP is valid\")\n\n .to_uppercase()\n\n .parse()\n\n .unwrap()\n\n }\n\n\n\n /// Returns the plugin name for this identity.\n\n pub fn plugin(&self) -> &str {\n\n &self.name\n\n }\n\n}\n\n\n", "file_path": "age/src/plugin.rs", "rank": 92, "score": 39118.06451355313 }, { "content": " .collect(),\n\n identities: identities\n\n .iter()\n\n .filter(|r| r.name == plugin_name)\n\n .cloned()\n\n .collect(),\n\n callbacks,\n\n })\n\n }\n\n}\n\n\n\nimpl<C: Callbacks> crate::Recipient for RecipientPluginV1<C> {\n\n fn wrap_file_key(&self, file_key: &FileKey) -> Result<Vec<Stanza>, EncryptError> {\n\n // Open connection\n\n let mut conn = self.plugin.connect(RECIPIENT_V1)?;\n\n\n\n // Phase 1: add recipients, identities, and file key to wrap\n\n conn.unidir_send(|mut phase| {\n\n for recipient in &self.recipients {\n\n phase.send(\"add-recipient\", &[&recipient.recipient], &[])?;\n", "file_path": "age/src/plugin.rs", "rank": 93, "score": 39117.81764421497 }, { "content": " /// Parses a plugin identity from a string.\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n parse_bech32(s)\n\n .ok_or(\"invalid Bech32 encoding\")\n\n .and_then(|(hrp, _)| {\n\n if hrp.len() > PLUGIN_IDENTITY_PREFIX.len()\n\n && hrp.starts_with(PLUGIN_IDENTITY_PREFIX)\n\n {\n\n Ok(Identity {\n\n name: hrp\n\n .split_at(PLUGIN_IDENTITY_PREFIX.len())\n\n .1\n\n .trim_end_matches('-')\n\n .to_owned(),\n\n identity: s.to_owned(),\n\n })\n\n } else {\n\n Err(\"invalid HRP\")\n\n }\n\n })\n", "file_path": "age/src/plugin.rs", "rank": 94, "score": 39116.99042653529 }, { "content": "\n\n// Plugin HRPs are age1[name] and AGE-PLUGIN-[NAME]-\n\nconst PLUGIN_RECIPIENT_PREFIX: &str = \"age1\";\n\nconst PLUGIN_IDENTITY_PREFIX: &str = \"age-plugin-\";\n\n\n\nconst CMD_ERROR: &str = \"error\";\n\nconst CMD_RECIPIENT_STANZA: &str = \"recipient-stanza\";\n\nconst CMD_MSG: &str = \"msg\";\n\nconst CMD_REQUEST_PUBLIC: &str = \"request-public\";\n\nconst CMD_REQUEST_SECRET: &str = \"request-secret\";\n\nconst CMD_FILE_KEY: &str = \"file-key\";\n\n\n", "file_path": "age/src/plugin.rs", "rank": 95, "score": 39116.424570028255 }, { "content": " } else {\n\n reply.fail()\n\n }\n\n }\n\n CMD_RECIPIENT_STANZA => {\n\n if command.args.len() >= 2 {\n\n // We only requested one file key be wrapped.\n\n if command.args.remove(0) == \"0\" {\n\n command.tag = command.args.remove(0);\n\n stanzas.push(command);\n\n } else {\n\n errors.push(PluginError::Other {\n\n kind: \"internal\".to_owned(),\n\n metadata: vec![],\n\n message: \"plugin wrapped file key to a file we didn't provide\"\n\n .to_owned(),\n\n });\n\n }\n\n } else {\n\n errors.push(PluginError::Other {\n", "file_path": "age/src/plugin.rs", "rank": 96, "score": 39114.97487512776 }, { "content": " .map(|plugin| IdentityPluginV1 {\n\n plugin,\n\n identities: identities\n\n .iter()\n\n .filter(|r| r.name == plugin_name)\n\n .cloned()\n\n .collect(),\n\n callbacks,\n\n })\n\n }\n\n\n\n fn unwrap_stanzas<'a>(\n\n &self,\n\n stanzas: impl Iterator<Item = &'a Stanza>,\n\n ) -> Option<Result<FileKey, DecryptError>> {\n\n // Open connection. If the plugin doesn't know how to unwrap identities, skip it\n\n // by returning `None`.\n\n let mut conn = self.plugin.connect(IDENTITY_V1).ok()?;\n\n\n\n // Phase 1: add identities and stanzas\n", "file_path": "age/src/plugin.rs", "rank": 97, "score": 39113.82387792583 }, { "content": " .and_then(|(hrp, _)| {\n\n if hrp.len() > PLUGIN_RECIPIENT_PREFIX.len()\n\n && hrp.starts_with(PLUGIN_RECIPIENT_PREFIX)\n\n {\n\n Ok(Recipient {\n\n name: hrp.split_at(PLUGIN_RECIPIENT_PREFIX.len()).1.to_owned(),\n\n recipient: s.to_owned(),\n\n })\n\n } else {\n\n Err(\"invalid HRP\")\n\n }\n\n })\n\n }\n\n}\n\n\n\nimpl fmt::Display for Recipient {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{}\", self.recipient)\n\n }\n\n}\n", "file_path": "age/src/plugin.rs", "rank": 98, "score": 39113.59966807728 }, { "content": " self.callbacks\n\n .display_message(&String::from_utf8_lossy(&command.body));\n\n reply.ok(None)\n\n }\n\n CMD_REQUEST_PUBLIC => {\n\n if let Some(value) = self\n\n .callbacks\n\n .request_public_string(&String::from_utf8_lossy(&command.body))\n\n {\n\n reply.ok(Some(value.as_bytes()))\n\n } else {\n\n reply.fail()\n\n }\n\n }\n\n CMD_REQUEST_SECRET => {\n\n if let Some(secret) = self\n\n .callbacks\n\n .request_passphrase(&String::from_utf8_lossy(&command.body))\n\n {\n\n reply.ok(Some(secret.expose_secret().as_bytes()))\n", "file_path": "age/src/plugin.rs", "rank": 99, "score": 39111.78957070656 } ]
Rust
src/composable.rs
lostmsu/allocators
fb273782383a1b287bcd0498454cec68c237af46
use super::{Allocator, Error, Block, BlockOwner}; pub struct NullAllocator; unsafe impl Allocator for NullAllocator { unsafe fn allocate_raw(&self, _size: usize, _align: usize) -> Result<Block, Error> { Err(Error::OutOfMemory) } unsafe fn reallocate_raw<'a>(&'a self, block: Block<'a>, _new_size: usize) -> Result<Block<'a>, (Error, Block<'a>)> { Err((Error::OutOfMemory, block)) } unsafe fn deallocate_raw(&self, _block: Block) { panic!("Attempted to deallocate using null allocator.") } } impl BlockOwner for NullAllocator { fn owns_block(&self, _block: &Block) -> bool { false } } pub struct Fallback<M: BlockOwner, F: BlockOwner> { main: M, fallback: F, } impl<M: BlockOwner, F: BlockOwner> Fallback<M, F> { pub fn new(main: M, fallback: F) -> Self { Fallback { main: main, fallback: fallback, } } } unsafe impl<M: BlockOwner, F: BlockOwner> Allocator for Fallback<M, F> { unsafe fn allocate_raw(&self, size: usize, align: usize) -> Result<Block, Error> { match self.main.allocate_raw(size, align) { Ok(block) => Ok(block), Err(_) => self.fallback.allocate_raw(size, align), } } unsafe fn reallocate_raw<'a>(&'a self, block: Block<'a>, new_size: usize) -> Result<Block<'a>, (Error, Block<'a>)> { if self.main.owns_block(&block) { self.main.reallocate_raw(block, new_size) } else if self.fallback.owns_block(&block) { self.fallback.reallocate_raw(block, new_size) } else { Err((Error::AllocatorSpecific("Neither fallback nor main owns this block.".into()), block)) } } unsafe fn deallocate_raw(&self, block: Block) { if self.main.owns_block(&block) { self.main.deallocate_raw(block); } else if self.fallback.owns_block(&block) { self.fallback.deallocate_raw(block); } } } impl<M: BlockOwner, F: BlockOwner> BlockOwner for Fallback<M, F> { fn owns_block(&self, block: &Block) -> bool { self.main.owns_block(block) || self.fallback.owns_block(block) } } pub trait ProxyLogger { fn allocate_success(&self, block: &Block); fn allocate_fail(&self, err: &Error, size: usize, align: usize); fn deallocate(&self, block: &Block); fn reallocate_success(&self, old_block: &Block, new_block: &Block); fn reallocate_fail(&self, err: &Error, block: &Block, req_size: usize); } pub struct Proxy<A, L> { alloc: A, logger: L, } impl<A: Allocator, L: ProxyLogger> Proxy<A, L> { pub fn new(alloc: A, logger: L) -> Self { Proxy { alloc: alloc, logger: logger, } } } unsafe impl<A: Allocator, L: ProxyLogger> Allocator for Proxy<A, L> { unsafe fn allocate_raw(&self, size: usize, align: usize) -> Result<Block, Error> { match self.alloc.allocate_raw(size, align) { Ok(block) => { self.logger.allocate_success(&block); Ok(block) } Err(err) => { self.logger.allocate_fail(&err, size, align); Err(err) } } } unsafe fn reallocate_raw<'a>(&'a self, block: Block<'a>, new_size: usize) -> Result<Block<'a>, (Error, Block<'a>)> { let old_copy = Block::new(block.ptr(), block.size(), block.align()); match self.alloc.reallocate_raw(block, new_size) { Ok(new_block) => { self.logger.reallocate_success(&old_copy, &new_block); Ok(new_block) } Err((err, old)) => { self.logger.reallocate_fail(&err, &old, new_size); Err((err, old)) } } } unsafe fn deallocate_raw(&self, block: Block) { self.logger.deallocate(&block); self.alloc.deallocate_raw(block); } } #[cfg(test)] mod tests { use super::super::*; #[test] #[should_panic] fn null_allocate() { let alloc = NullAllocator; alloc.allocate(1i32).unwrap(); } }
use super::{Allocator, Error, Block, BlockOwner}; pub struct NullAllocator; unsafe impl Allocator for NullAllocator { unsafe fn allocate_raw(&self, _size: usize, _align: usize) -> Result<Block, Error> { Err(Error::OutOfMemory) } unsafe fn reallocate_raw<'a>(&'a self, block: Block<'a>, _new_size: usize) -> Result<Block<'a>, (Error, Block<'a>)> { Err((Error::OutOfMemory, block)) } unsafe fn deallocate_raw(&self, _block: Block) { panic!("Attempted to deallocate using null allocator.") } } impl BlockOwner for NullAllocator { fn owns_block(&self, _block: &Block) -> bool { false } } pub struct Fallback<M: BlockOwner, F: BlockOwner> { main: M, fallback: F, } impl<M: BlockOwner, F: BlockOwner> Fallback<M, F> {
} unsafe impl<M: BlockOwner, F: BlockOwner> Allocator for Fallback<M, F> { unsafe fn allocate_raw(&self, size: usize, align: usize) -> Result<Block, Error> { match self.main.allocate_raw(size, align) { Ok(block) => Ok(block), Err(_) => self.fallback.allocate_raw(size, align), } } unsafe fn reallocate_raw<'a>(&'a self, block: Block<'a>, new_size: usize) -> Result<Block<'a>, (Error, Block<'a>)> { if self.main.owns_block(&block) { self.main.reallocate_raw(block, new_size) } else if self.fallback.owns_block(&block) { self.fallback.reallocate_raw(block, new_size) } else { Err((Error::AllocatorSpecific("Neither fallback nor main owns this block.".into()), block)) } } unsafe fn deallocate_raw(&self, block: Block) { if self.main.owns_block(&block) { self.main.deallocate_raw(block); } else if self.fallback.owns_block(&block) { self.fallback.deallocate_raw(block); } } } impl<M: BlockOwner, F: BlockOwner> BlockOwner for Fallback<M, F> { fn owns_block(&self, block: &Block) -> bool { self.main.owns_block(block) || self.fallback.owns_block(block) } } pub trait ProxyLogger { fn allocate_success(&self, block: &Block); fn allocate_fail(&self, err: &Error, size: usize, align: usize); fn deallocate(&self, block: &Block); fn reallocate_success(&self, old_block: &Block, new_block: &Block); fn reallocate_fail(&self, err: &Error, block: &Block, req_size: usize); } pub struct Proxy<A, L> { alloc: A, logger: L, } impl<A: Allocator, L: ProxyLogger> Proxy<A, L> { pub fn new(alloc: A, logger: L) -> Self { Proxy { alloc: alloc, logger: logger, } } } unsafe impl<A: Allocator, L: ProxyLogger> Allocator for Proxy<A, L> { unsafe fn allocate_raw(&self, size: usize, align: usize) -> Result<Block, Error> { match self.alloc.allocate_raw(size, align) { Ok(block) => { self.logger.allocate_success(&block); Ok(block) } Err(err) => { self.logger.allocate_fail(&err, size, align); Err(err) } } } unsafe fn reallocate_raw<'a>(&'a self, block: Block<'a>, new_size: usize) -> Result<Block<'a>, (Error, Block<'a>)> { let old_copy = Block::new(block.ptr(), block.size(), block.align()); match self.alloc.reallocate_raw(block, new_size) { Ok(new_block) => { self.logger.reallocate_success(&old_copy, &new_block); Ok(new_block) } Err((err, old)) => { self.logger.reallocate_fail(&err, &old, new_size); Err((err, old)) } } } unsafe fn deallocate_raw(&self, block: Block) { self.logger.deallocate(&block); self.alloc.deallocate_raw(block); } } #[cfg(test)] mod tests { use super::super::*; #[test] #[should_panic] fn null_allocate() { let alloc = NullAllocator; alloc.allocate(1i32).unwrap(); } }
pub fn new(main: M, fallback: F) -> Self { Fallback { main: main, fallback: fallback, } }
function_block-full_function
[ { "content": "pub fn make_place<A: ?Sized + Allocator, T>(alloc: &A) -> Result<Place<T, A>, super::Error> {\n\n let (size, align) = (mem::size_of::<T>(), mem::align_of::<T>());\n\n match unsafe { alloc.allocate_raw(size, align) } {\n\n Ok(block) => {\n\n Ok(Place {\n\n allocator: alloc,\n\n block: block,\n\n _marker: PhantomData,\n\n })\n\n }\n\n Err(e) => Err(e),\n\n }\n\n}\n\n\n\n/// A place for allocating into.\n\n/// This is only used for in-place allocation,\n\n/// e.g. `let val = in (alloc.make_place().unwrap()) { EXPR }`\n\npub struct Place<'a, T: 'a, A: 'a + ?Sized + Allocator> {\n\n allocator: &'a A,\n\n block: Block<'a>,\n", "file_path": "src/boxed.rs", "rank": 0, "score": 78617.48159399186 }, { "content": "/// An allocator that knows which blocks have been issued by it.\n\npub trait BlockOwner: Allocator {\n\n /// Whether this allocator owns this allocated value. \n\n fn owns<'a, T, A: Allocator>(&self, val: &AllocBox<'a, T, A>) -> bool {\n\n self.owns_block(& unsafe { val.as_block() })\n\n }\n\n\n\n /// Whether this allocator owns the block passed to it.\n\n fn owns_block(&self, block: &Block) -> bool;\n\n\n\n /// Joins this allocator with a fallback allocator.\n\n // TODO: Maybe not the right place for this?\n\n // Right now I've been more focused on shaking out the\n\n // specifics of allocation than crafting a fluent API.\n\n fn with_fallback<O: BlockOwner>(self, other: O) -> Fallback<Self, O>\n\n where Self: Sized\n\n {\n\n Fallback::new(self, other)\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 1, "score": 65132.68892614974 }, { "content": "#[inline]\n\nfn align_forward(ptr: *mut u8, align: usize) -> *mut u8 {\n\n ((ptr as usize + align - 1) & !(align - 1)) as *mut u8\n\n}\n\n\n\n// implementations for trait object types.\n\n\n\nunsafe impl<'a, A: ?Sized + Allocator + 'a> Allocator for Box<A> {\n\n unsafe fn allocate_raw(&self, size: usize, align: usize) -> Result<Block, Error> {\n\n (**self).allocate_raw(size, align)\n\n }\n\n\n\n unsafe fn reallocate_raw<'b>(&'b self, block: Block<'b>, new_size: usize) -> Result<Block<'b>, (Error, Block<'b>)> {\n\n (**self).reallocate_raw(block, new_size)\n\n }\n\n\n\n unsafe fn deallocate_raw(&self, block: Block) {\n\n (**self).deallocate_raw(block)\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 2, "score": 36614.366089851814 }, { "content": "## Scoped Allocator\n\nThis is useful for reusing a block of memory for temporary allocations in a tight loop. Scopes can be nested and values allocated in a scope cannot be moved outside it.\n\n\n\n```rust\n\n#![feature(placement_in_syntax)]\n\nuse allocators::{Allocator, Scoped};\n\n#[derive(Debug)]\n\nstruct Bomb(u8);\n\nimpl Drop for Bomb {\n\n fn drop(&mut self) {\n\n println!(\"Boom! {}\", self.0);\n\n }\n\n}\n\n// new scoped allocator with a kilobyte of memory.\n\nlet alloc = Scoped::new(1024).unwrap();\n\nalloc.scope(|inner| {\n\n let mut bombs = Vec::new();\n\n // allocate_val makes the value on the stack first.\n\n for i in 0..100 { bombs.push(inner.allocate(Bomb(i)).unwrap())}\n\n // watch the bombs go off!\n\n});\n\n// Allocators also have placement-in syntax.\n\nlet my_int = in alloc.make_place().unwrap() { 23 };\n\nprintln!(\"My int: {}\", *my_int);\n\n```\n\n\n\n## Free List Allocator\n\nThis allocator maintains a list of free blocks of a given size.\n\n```rust\n\nuse allocators::{Allocator, FreeList};\n\n\n\n// create a FreeList allocator with 64 blocks of 1024 bytes.\n\nlet alloc = FreeList::new(1024, 64).unwrap();\n\nfor _ in 0..10 {\n\n // allocate every block\n\n let mut v = Vec::new();\n\n for i in 0u8..64 {\n\n v.push(alloc.allocate([i; 1024]).unwrap());\n\n }\n\n // no more blocks :(.\n\n assert!(alloc.allocate([0; 1024]).is_err());\n\n\n\n // all the blocks get pushed back onto the freelist at the end here, \n\n // memory gets reused efficiently in the next iteration.\n\n}\n\n```\n\n\n\nThis allocator can yield very good performance for situations like the above, where each block's space is being fully used.\n\n\n\n# Composable Primitives\n\nThese are very underdeveloped at the moment, and lack a fluent API as well. They are definitely a back-burner feature at the moment, since the idea of composable allocators hasn't really proved its value yet.\n\n\n\n## Null Allocator\n\nThis will probably get a new name since \"Null\" has some misleading connotations.\n\n\n\nIt fails to allocate any request made to it, and panics when deallocated with.\n\n\n", "file_path": "README.md", "rank": 4, "score": 14484.60047510043 }, { "content": "## Fallback Allocator\n\nThis composes two `BlockOwners`: a main allocator and a fallback. If the main allocator fails to allocate, it turns to the fallback.\n\n\n\n## Proxy Allocator\n", "file_path": "README.md", "rank": 5, "score": 14484.04100362495 }, { "content": "# Allocators \n\n[![Build Status](https://travis-ci.org/rphmeier/allocators.svg)](https://travis-ci.org/rphmeier/allocators) [![Crates.io](https://img.shields.io/crates/v/allocators.svg)](https://crates.io/crates/allocators)\n\n\n\n## [Documentation](https://rphmeier.github.io/allocators/allocators/)\n\n\n\nThis crate provides a few different memory allocators, as well as an \n\n`Allocator` trait for creating other custom allocators. A main goal of allocators is composability. For this reason, it also provides some composable primitives to be used as building blocks for chained allocators. This crate leans heavily on unsafe/unstable code at the moment, and should be considered very experimental.\n\nIn light of [RFC 1398 (Allocators, Take III)](https://github.com/rust-lang/rfcs/pull/1398), this crate has been made more or less obsolete in its current state, and will probably be revised to contain instead a collection of custom allocators without providing the framework.\n\n\n\n# Why?\n\nUsers often need to have more fine-grained control over the way memory is allocated in their programs. This crate is a proof-of-concept that these mechanisms can be implemented in Rust and provide a safe interface to their users.\n\n\n\n# Allocator Traits\n\n## Allocator\n\nThis is the core trait for allocators to implement. All a type has to do is implement two unsafe functions: `allocate_raw` and `deallocate_raw`. This will likely require `reallocate_raw` in the future.\n\n\n\n## BlockOwner\n\nAllocators that implement this can say definitively whether they own a block.\n\n\n\n# Allocator Types\n", "file_path": "README.md", "rank": 6, "score": 14480.55556927583 }, { "content": " };\n\n\n\n // set the current pointer to null as a flag to indicate\n\n // that this allocator is being scoped.\n\n self.current.set(ptr::null_mut());\n\n let u = f(&alloc);\n\n self.current.set(old);\n\n\n\n mem::forget(alloc);\n\n Ok(u)\n\n }\n\n\n\n // Whether this allocator is currently scoped.\n\n pub fn is_scoped(&self) -> bool {\n\n self.current.get().is_null()\n\n }\n\n}\n\n\n\nunsafe impl<'a, A: Allocator> Allocator for Scoped<'a, A> {\n\n unsafe fn allocate_raw(&self, size: usize, align: usize) -> Result<Block, Error> {\n", "file_path": "src/scoped.rs", "rank": 11, "score": 17.32265766299932 }, { "content": "unsafe impl<'a, 'b: 'a, A: ?Sized + Allocator + 'b> Allocator for &'a A {\n\n unsafe fn allocate_raw(&self, size: usize, align: usize) -> Result<Block, Error> {\n\n (**self).allocate_raw(size, align)\n\n }\n\n\n\n unsafe fn reallocate_raw<'c>(&'c self, block: Block<'c>, new_size: usize) -> Result<Block<'c>, (Error, Block<'c>)> {\n\n (**self).reallocate_raw(block, new_size)\n\n }\n\n\n\n unsafe fn deallocate_raw(&self, block: Block) {\n\n (**self).deallocate_raw(block)\n\n }\n\n}\n\n\n\nunsafe impl<'a, 'b: 'a, A: ?Sized + Allocator + 'b> Allocator for &'a mut A {\n\n unsafe fn allocate_raw(&self, size: usize, align: usize) -> Result<Block, Error> {\n\n (**self).allocate_raw(size, align)\n\n }\n\n\n\n unsafe fn reallocate_raw<'c>(&'c self, block: Block<'c>, new_size: usize) -> Result<Block<'c>, (Error, Block<'c>)> {\n", "file_path": "src/lib.rs", "rank": 12, "score": 16.289015842809302 }, { "content": "/// A block of memory created by an allocator.\n\npub struct Block<'a> {\n\n ptr: Unique<u8>,\n\n size: usize,\n\n align: usize,\n\n _marker: PhantomData<&'a [u8]>,\n\n}\n\n\n\nimpl<'a> Block<'a> {\n\n /// Create a new block from the supplied parts.\n\n /// The pointer cannot be null.\n\n ///\n\n /// # Panics\n\n /// Panics if the pointer passed is null.\n\n pub fn new(ptr: *mut u8, size: usize, align: usize) -> Self {\n\n assert!(!ptr.is_null());\n\n Block {\n\n ptr: unsafe { Unique::new(ptr) },\n\n size: size,\n\n align: align,\n", "file_path": "src/lib.rs", "rank": 13, "score": 15.731448022769868 }, { "content": "//! A Free List allocator.\n\n\n\nuse std::cell::Cell;\n\nuse std::mem;\n\nuse std::ptr;\n\n\n\nuse super::{Allocator, Error, Block, HeapAllocator, HEAP};\n\n\n\n/// A `FreeList` allocator manages a list of free memory blocks of uniform size.\n\n/// Whenever a block is requested, it returns the first free block.\n\npub struct FreeList<'a, A: 'a + Allocator> {\n\n alloc: &'a A,\n\n block_size: usize,\n\n free_list: Cell<*mut u8>,\n\n}\n\n\n\nimpl FreeList<'static, HeapAllocator> {\n\n /// Creates a new `FreeList` backed by the heap. `block_size` must be greater\n\n /// than or equal to the size of a pointer.\n\n pub fn new(block_size: usize, num_blocks: usize) -> Result<Self, Error> {\n", "file_path": "src/freelist.rs", "rank": 14, "score": 15.439101184620768 }, { "content": " pub fn new(size: usize) -> Result<Self, Error> {\n\n Scoped::new_from(HEAP, size)\n\n }\n\n}\n\n\n\nimpl<'parent, A: Allocator> Scoped<'parent, A> {\n\n /// Creates a new `Scoped` backed by `size` bytes from the allocator supplied.\n\n pub fn new_from(alloc: &'parent A, size: usize) -> Result<Self, Error> {\n\n // Create a memory buffer with the desired size and maximal align from the parent.\n\n match unsafe { alloc.allocate_raw(size, mem::align_of::<usize>()) } {\n\n Ok(block) => Ok(Scoped {\n\n allocator: alloc,\n\n current: Cell::new(block.ptr()),\n\n end: unsafe { block.ptr().offset(block.size() as isize) },\n\n root: true,\n\n start: block.ptr(),\n\n }),\n\n Err(err) => Err(err),\n\n }\n\n }\n", "file_path": "src/scoped.rs", "rank": 15, "score": 15.321717480598144 }, { "content": " FreeList::new_from(HEAP, block_size, num_blocks)\n\n }\n\n}\n\nimpl<'a, A: 'a + Allocator> FreeList<'a, A> {\n\n /// Creates a new `FreeList` backed by another allocator. `block_size` must be greater\n\n /// than or equal to the size of a pointer.\n\n pub fn new_from(alloc: &'a A,\n\n block_size: usize,\n\n num_blocks: usize)\n\n -> Result<Self, Error> {\n\n if block_size < mem::size_of::<*mut u8>() {\n\n return Err(Error::AllocatorSpecific(\"Block size too small.\".into()));\n\n }\n\n\n\n let mut free_list = ptr::null_mut();\n\n\n\n // allocate each block with maximal alignment.\n\n for _ in 0..num_blocks {\n\n\n\n match unsafe { alloc.allocate_raw(block_size, mem::align_of::<*mut u8>()) } {\n", "file_path": "src/freelist.rs", "rank": 17, "score": 15.065383692954097 }, { "content": " #[inline]\n\n unsafe fn allocate_raw(&self, size: usize, align: usize) -> Result<Block, Error> {\n\n if size != 0 {\n\n let ptr = heap::allocate(size, align);\n\n if !ptr.is_null() {\n\n Ok(Block::new(ptr, size, align))\n\n } else {\n\n Err(Error::OutOfMemory)\n\n }\n\n } else {\n\n Ok(Block::empty())\n\n }\n\n }\n\n\n\n #[inline]\n\n unsafe fn reallocate_raw<'a>(&'a self, block: Block<'a>, new_size: usize) -> Result<Block<'a>, (Error, Block<'a>)> {\n\n if new_size == 0 {\n\n self.deallocate_raw(block);\n\n Ok(Block::empty())\n\n } else if block.is_empty() {\n", "file_path": "src/lib.rs", "rank": 18, "score": 14.332099236735187 }, { "content": " block_size: block_size,\n\n free_list: Cell::new(free_list),\n\n })\n\n }\n\n}\n\n\n\nunsafe impl<'a, A: 'a + Allocator> Allocator for FreeList<'a, A> {\n\n unsafe fn allocate_raw(&self, size: usize, align: usize) -> Result<Block, Error> {\n\n if size == 0 {\n\n return Ok(Block::empty());\n\n } else if size > self.block_size {\n\n return Err(Error::OutOfMemory);\n\n }\n\n\n\n if align > mem::align_of::<*mut u8>() {\n\n return Err(Error::UnsupportedAlignment);\n\n }\n\n\n\n let free_list = self.free_list.get();\n\n if !free_list.is_null() {\n", "file_path": "src/freelist.rs", "rank": 19, "score": 13.820596000239394 }, { "content": " /// # Safety\n\n /// Never use the block's pointer outside of the lifetime of the allocator.\n\n /// It must be deallocated with the same allocator as it was allocated with.\n\n /// It is undefined behavior to provide a non power-of-two align.\n\n unsafe fn allocate_raw(&self, size: usize, align: usize) -> Result<Block, Error>;\n\n\n\n /// Reallocate a block of memory.\n\n ///\n\n /// This either returns a new, possibly moved block with the requested size,\n\n /// or the old block back.\n\n /// The new block will have the same alignment as the old.\n\n ///\n\n /// # Safety\n\n /// If given an empty block, it must return it back instead of allocating the new size,\n\n /// since the alignment is unknown.\n\n ///\n\n /// If the requested size is 0, it must deallocate the old block and return an empty one.\n\n unsafe fn reallocate_raw<'a>(&'a self, block: Block<'a>, new_size: usize) -> Result<Block<'a>, (Error, Block<'a>)>;\n\n\n\n /// Deallocate the memory referred to by this block.\n\n ///\n\n /// # Safety\n\n /// This block must have been allocated by this allocator.\n\n unsafe fn deallocate_raw(&self, block: Block);\n\n}\n\n\n\n/// An allocator that knows which blocks have been issued by it.\n", "file_path": "src/lib.rs", "rank": 20, "score": 13.794027552311062 }, { "content": " let size = self.end as usize - self.start as usize;\n\n // only free if this allocator is the root to make sure\n\n // that memory is freed after destructors for allocated objects\n\n // are called in case of unwind\n\n if self.root && size > 0 {\n\n unsafe {\n\n self.allocator\n\n .deallocate_raw(Block::new(self.start, size, mem::align_of::<usize>()))\n\n }\n\n }\n\n }\n\n}\n\n\n\nunsafe impl<'a, A: 'a + Allocator + Sync> Send for Scoped<'a, A> {}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::super::*;\n\n\n\n #[test]\n", "file_path": "src/scoped.rs", "rank": 22, "score": 13.183101285169151 }, { "content": " self.size\n\n }\n\n /// Get the align of this block.\n\n pub fn align(&self) -> usize {\n\n self.align\n\n }\n\n /// Whether this block is empty.\n\n pub fn is_empty(&self) -> bool {\n\n self.size == 0\n\n }\n\n}\n\n\n\n/// Errors that can occur while creating an allocator\n\n/// or allocating from it.\n\n#[derive(Debug, Eq, PartialEq)]\n\npub enum Error {\n\n /// The allocator failed to allocate the amount of memory requested of it.\n\n OutOfMemory,\n\n /// The allocator does not support the requested alignment.\n\n UnsupportedAlignment,\n", "file_path": "src/lib.rs", "rank": 23, "score": 12.396353799922943 }, { "content": "//! A scoped linear allocator. This is something of a cross between a stack allocator\n\n//! and a traditional linear allocator.\n\n\n\nuse std::cell::Cell;\n\nuse std::mem;\n\nuse std::ptr;\n\n\n\nuse super::{Allocator, Error, Block, BlockOwner, HeapAllocator, HEAP};\n\n\n\n/// A scoped linear allocator.\n\npub struct Scoped<'parent, A: 'parent + Allocator> {\n\n allocator: &'parent A,\n\n current: Cell<*mut u8>,\n\n end: *mut u8,\n\n root: bool,\n\n start: *mut u8,\n\n}\n\n\n\nimpl Scoped<'static, HeapAllocator> {\n\n /// Creates a new `Scoped` backed by `size` bytes from the heap.\n", "file_path": "src/scoped.rs", "rank": 24, "score": 12.122051970536774 }, { "content": "\n\n /// Calls the supplied function with a new scope of the allocator.\n\n ///\n\n /// Returns the result of the closure or an error if this allocator\n\n /// has already been scoped.\n\n pub fn scope<F, U>(&self, f: F) -> Result<U, ()>\n\n where F: FnMut(&Self) -> U\n\n {\n\n if self.is_scoped() {\n\n return Err(());\n\n }\n\n\n\n let mut f = f;\n\n let old = self.current.get();\n\n let alloc = Scoped {\n\n allocator: self.allocator,\n\n current: self.current.clone(),\n\n end: self.end,\n\n root: false,\n\n start: old,\n", "file_path": "src/scoped.rs", "rank": 25, "score": 12.010326182892008 }, { "content": " pub fn take(self) -> T where T: Sized {\n\n let val = unsafe { ::std::ptr::read(self.item.as_ptr()) };\n\n let block = Block::new(self.item.as_ptr() as *mut u8, self.size, self.align);\n\n unsafe { self.allocator.deallocate_raw(block) };\n\n mem::forget(self);\n\n val\n\n }\n\n\n\n /// Gets a handle to the block of memory this manages.\n\n pub unsafe fn as_block(&self) -> Block {\n\n Block::new(self.item.as_ptr() as *mut u8, self.size, self.align)\n\n }\n\n}\n\n\n\nimpl<'a, T: ?Sized, A: ?Sized + Allocator> Deref for AllocBox<'a, T, A> {\n\n type Target = T;\n\n\n\n fn deref(&self) -> &T {\n\n unsafe { self.item.as_ref() }\n\n }\n", "file_path": "src/boxed.rs", "rank": 26, "score": 11.431730232176701 }, { "content": "\n\n unsafe fn deallocate_raw(&self, block: Block) {\n\n if !block.is_empty() {\n\n let first = self.free_list.get();\n\n let ptr = block.ptr();\n\n *(ptr as *mut *mut u8) = first;\n\n self.free_list.set(ptr);\n\n }\n\n }\n\n}\n\n\n\nimpl<'a, A: 'a + Allocator> Drop for FreeList<'a, A> {\n\n fn drop(&mut self) {\n\n let mut free_list = self.free_list.get();\n\n //free all the blocks in the list.\n\n while !free_list.is_null() {\n\n unsafe {\n\n let next = *(free_list as *mut *mut u8);\n\n self.alloc.deallocate_raw(Block::new(free_list,\n\n self.block_size,\n", "file_path": "src/freelist.rs", "rank": 27, "score": 11.00723241411514 }, { "content": "use std::any::Any;\n\nuse std::borrow::{Borrow, BorrowMut};\n\nuse std::marker::{PhantomData, Unsize};\n\nuse std::mem;\n\nuse std::ops::{CoerceUnsized, Deref, DerefMut, InPlace, Placer};\n\nuse std::ops::Place as StdPlace;\n\nuse std::ptr::Unique;\n\n\n\nuse super::{Allocator, Block};\n\n\n\n/// An item allocated by a custom allocator.\n\npub struct AllocBox<'a, T: 'a + ?Sized, A: 'a + ?Sized + Allocator> {\n\n item: Unique<T>,\n\n size: usize,\n\n align: usize,\n\n allocator: &'a A,\n\n}\n\n\n\nimpl<'a, T: ?Sized, A: ?Sized + Allocator> AllocBox<'a, T, A> {\n\n /// Consumes this allocated value, yielding the value it manages.\n", "file_path": "src/boxed.rs", "rank": 28, "score": 10.560523698566424 }, { "content": " }\n\n}\n\n\n\nimpl<'a, T: ?Sized, A: ?Sized + Allocator> Drop for AllocBox<'a, T, A> {\n\n #[inline]\n\n fn drop(&mut self) {\n\n use std::intrinsics::drop_in_place;\n\n unsafe {\n\n drop_in_place(self.item.as_ptr());\n\n self.allocator.deallocate_raw(Block::new(self.item.as_ptr() as *mut u8, self.size, self.align));\n\n }\n\n\n\n }\n\n}\n\n\n\n\n", "file_path": "src/boxed.rs", "rank": 29, "score": 10.540606965597313 }, { "content": " (**self).reallocate_raw(block, new_size)\n\n }\n\n\n\n unsafe fn deallocate_raw(&self, block: Block) {\n\n (**self).deallocate_raw(block)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\n\n use std::any::Any;\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn heap_lifetime() {\n\n let my_int;\n\n {\n\n my_int = HEAP.allocate(0i32).unwrap();\n", "file_path": "src/lib.rs", "rank": 30, "score": 10.536729594410701 }, { "content": " Err((Error::UnsupportedAlignment, block))\n\n } else {\n\n let new_ptr = heap::reallocate(block.ptr(), block.size(), new_size, block.align());\n\n\n\n if new_ptr.is_null() {\n\n Err((Error::OutOfMemory, block))\n\n } else {\n\n Ok(Block::new(new_ptr, new_size, block.align()))\n\n }\n\n }\n\n }\n\n\n\n #[inline]\n\n unsafe fn deallocate_raw(&self, block: Block) {\n\n if !block.is_empty() {\n\n heap::deallocate(block.ptr(), block.size(), block.align())\n\n }\n\n }\n\n}\n\n\n\n// aligns a pointer forward to the next value aligned with `align`.\n", "file_path": "src/lib.rs", "rank": 31, "score": 10.240929665536633 }, { "content": " _marker: PhantomData<T>,\n\n}\n\n\n\nimpl<'a, T: 'a, A: 'a + ?Sized + Allocator> Placer<T> for Place<'a, T, A> {\n\n type Place = Self;\n\n fn make_place(self) -> Self {\n\n self\n\n }\n\n}\n\n\n\nimpl<'a, T: 'a, A: 'a + ?Sized + Allocator> InPlace<T> for Place<'a, T, A> {\n\n type Owner = AllocBox<'a, T, A>;\n\n unsafe fn finalize(self) -> Self::Owner {\n\n let allocated = AllocBox {\n\n item: Unique::new(self.block.ptr() as *mut T),\n\n size: self.block.size(),\n\n align: self.block.align(),\n\n allocator: self.allocator,\n\n };\n\n\n", "file_path": "src/boxed.rs", "rank": 32, "score": 10.191890274427738 }, { "content": " /// ```rust\n\n /// #![feature(placement_in_syntax)]\n\n /// use allocators::{Allocator, AllocBox};\n\n /// fn alloc_array<A: Allocator>(allocator: &A) -> AllocBox<[u8; 1000], A> {\n\n /// // if 1000 bytes were enough to smash the stack, this would still work.\n\n /// in allocator.make_place().unwrap() { [0; 1000] }\n\n /// }\n\n /// ```\n\n fn make_place<T>(&self) -> Result<Place<T, Self>, Error>\n\n where Self: Sized\n\n {\n\n boxed::make_place(self)\n\n }\n\n \n\n /// Attempt to allocate a block of memory.\n\n ///\n\n /// Returns either a block of memory allocated\n\n /// or an Error. If `size` is equal to 0, the block returned must\n\n /// be created by `Block::empty()`\n\n ///\n", "file_path": "src/lib.rs", "rank": 33, "score": 10.107136590653495 }, { "content": " }\n\n AllocatorSpecific(ref reason) => {\n\n reason\n\n }\n\n }\n\n }\n\n}\n\n\n\n/// Allocator stub that just forwards to heap allocation.\n\n/// It is recommended to use the `HEAP` constant instead\n\n/// of creating a new instance of this, to benefit from\n\n/// the static lifetime that it provides.\n\n#[derive(Debug)]\n\npub struct HeapAllocator;\n\n\n\n// A constant for allocators to use the heap as a root.\n\n// Values allocated with this are effectively `Box`es.\n\npub const HEAP: &'static HeapAllocator = &HeapAllocator;\n\n\n\nunsafe impl Allocator for HeapAllocator {\n", "file_path": "src/lib.rs", "rank": 34, "score": 9.444374624243583 }, { "content": "pub mod composable;\n\npub mod freelist;\n\npub mod scoped;\n\n\n\npub use boxed::{AllocBox, Place};\n\npub use composable::*;\n\npub use freelist::FreeList;\n\npub use scoped::Scoped;\n\n\n\n/// A custom memory allocator.\n\npub unsafe trait Allocator {\n\n /// Attempts to allocate the value supplied to it.\n\n ///\n\n /// # Examples\n\n /// ```rust\n\n /// use allocators::{Allocator, AllocBox};\n\n /// fn alloc_array<A: Allocator>(allocator: &A) -> AllocBox<[u8; 1000], A> {\n\n /// allocator.allocate([0; 1000]).ok().unwrap()\n\n /// }\n\n /// ```\n", "file_path": "src/lib.rs", "rank": 35, "score": 9.347573304785676 }, { "content": " _marker: PhantomData,\n\n }\n\n }\n\n\n\n /// Creates an empty block.\n\n pub fn empty() -> Self {\n\n Block {\n\n ptr: Unique::empty(),\n\n size: 0,\n\n align: 0,\n\n _marker: PhantomData,\n\n }\n\n }\n\n\n\n /// Get the pointer from this block.\n\n pub fn ptr(&self) -> *mut u8 {\n\n self.ptr.as_ptr()\n\n }\n\n /// Get the size of this block.\n\n pub fn size(&self) -> usize {\n", "file_path": "src/lib.rs", "rank": 36, "score": 9.313387253932007 }, { "content": " }\n\n } else {\n\n // try to allocate a new block at the end, and copy the old mem over.\n\n // this will lead to some fragmentation.\n\n match self.allocate_raw(new_size, block.align()) {\n\n Ok(new_block) => {\n\n ptr::copy_nonoverlapping(block.ptr(), new_block.ptr(), block.size());\n\n Ok(new_block)\n\n }\n\n Err(err) => {\n\n Err((err, block))\n\n }\n\n }\n\n }\n\n }\n\n\n\n unsafe fn deallocate_raw(&self, block: Block) {\n\n if block.is_empty() || block.ptr().is_null() {\n\n return;\n\n }\n", "file_path": "src/scoped.rs", "rank": 37, "score": 9.056304593802722 }, { "content": " /// An allocator-specific error message.\n\n AllocatorSpecific(String),\n\n}\n\n\n\nimpl fmt::Display for Error {\n\n fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n\n formatter.write_str(self.description())\n\n }\n\n}\n\n\n\nimpl StdError for Error {\n\n fn description(&self) -> &str {\n\n use Error::*;\n\n\n\n match *self {\n\n OutOfMemory => {\n\n \"Allocator out of memory.\"\n\n }\n\n UnsupportedAlignment => {\n\n \"Attempted to allocate with unsupported alignment.\"\n", "file_path": "src/lib.rs", "rank": 38, "score": 8.561263239714778 }, { "content": " }\n\n\n\n /// Because of the way this allocator is designed, reallocating a block that is not \n\n /// the most recent will lead to fragmentation.\n\n unsafe fn reallocate_raw<'b>(&'b self, block: Block<'b>, new_size: usize) -> Result<Block<'b>, (Error, Block<'b>)> {\n\n let current_ptr = self.current.get();\n\n\n\n if new_size == 0 {\n\n Ok(Block::empty())\n\n } else if block.is_empty() {\n\n Err((Error::UnsupportedAlignment, block))\n\n } else if block.ptr().offset(block.size() as isize) == current_ptr {\n\n // if this block is the last allocated, resize it if we can.\n\n // otherwise, we are out of memory.\n\n let new_cur = current_ptr.offset((new_size - block.size()) as isize);\n\n if new_cur < self.end {\n\n self.current.set(new_cur);\n\n Ok(Block::new(block.ptr(), new_size, block.align()))\n\n } else {\n\n Err((Error::OutOfMemory, block))\n", "file_path": "src/scoped.rs", "rank": 39, "score": 8.503325044106795 }, { "content": " mem::forget(self);\n\n allocated\n\n }\n\n}\n\n\n\nimpl<'a, T: 'a, A: 'a + ?Sized + Allocator> StdPlace<T> for Place<'a, T, A> {\n\n fn pointer(&mut self) -> *mut T {\n\n self.block.ptr() as *mut T\n\n }\n\n}\n\n\n\nimpl<'a, T: 'a, A: 'a + ?Sized + Allocator> Drop for Place<'a, T, A> {\n\n #[inline]\n\n fn drop(&mut self) {\n\n // almost identical to AllocBox::Drop, but we don't drop\n\n // the value in place. If the finalize\n\n // method was never called, the expression\n\n // to create the value failed and the memory at the\n\n // pointer is still uninitialized, which we don't want to drop.\n\n unsafe {\n\n self.allocator.deallocate_raw(mem::replace(&mut self.block, Block::empty()));\n\n }\n\n\n\n }\n\n}", "file_path": "src/boxed.rs", "rank": 40, "score": 8.464681669996523 }, { "content": " mem::align_of::<*mut u8>()));\n\n free_list = next;\n\n }\n\n }\n\n }\n\n}\n\n\n\nunsafe impl<'a, A: 'a + Allocator + Sync> Send for FreeList<'a, A> {}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::super::*;\n\n\n\n #[test]\n\n fn it_works() {\n\n let alloc = FreeList::new(1024, 64).ok().unwrap();\n\n let mut blocks = Vec::new();\n\n for _ in 0..64 {\n\n blocks.push(alloc.allocate([0u8; 1024]).ok().unwrap());\n\n }\n\n assert!(alloc.allocate([0u8; 1024]).is_err());\n\n drop(blocks);\n\n assert!(alloc.allocate([0u8; 1024]).is_ok());\n\n }\n\n}\n", "file_path": "src/freelist.rs", "rank": 41, "score": 8.430529470522337 }, { "content": "}\n\n\n\nimpl<'a, T: ?Sized, A: ?Sized + Allocator> DerefMut for AllocBox<'a, T, A> {\n\n fn deref_mut(&mut self) -> &mut T {\n\n unsafe { self.item.as_mut() }\n\n }\n\n}\n\n\n\n// AllocBox can store trait objects!\n\nimpl<'a, T: ?Sized + Unsize<U>, U: ?Sized, A: ?Sized + Allocator> CoerceUnsized<AllocBox<'a, U, A>> for AllocBox<'a, T, A> {}\n\n\n\nimpl<'a, A: ?Sized + Allocator> AllocBox<'a, Any, A> {\n\n /// Attempts to downcast this `AllocBox` to a concrete type.\n\n pub fn downcast<T: Any>(self) -> Result<AllocBox<'a, T, A>, AllocBox<'a, Any, A>> {\n\n use std::raw::TraitObject;\n\n if self.is::<T>() {\n\n let obj: TraitObject = unsafe { mem::transmute::<*mut Any, TraitObject>(self.item.as_ptr()) };\n\n let new_allocated = AllocBox {\n\n item: unsafe { Unique::new(obj.data as *mut T) },\n\n size: self.size,\n", "file_path": "src/boxed.rs", "rank": 42, "score": 8.362712040200414 }, { "content": " let next_block = *(free_list as *mut *mut u8);\n\n self.free_list.set(next_block);\n\n\n\n Ok(Block::new(free_list, size, align))\n\n } else {\n\n Err(Error::OutOfMemory)\n\n }\n\n }\n\n\n\n unsafe fn reallocate_raw<'b>(&'b self, block: Block<'b>, new_size: usize) -> Result<Block<'b>, (Error, Block<'b>)> {\n\n if new_size == 0 {\n\n Ok(Block::empty())\n\n } else if block.is_empty() {\n\n Err((Error::UnsupportedAlignment, block))\n\n } else if new_size <= self.block_size {\n\n Ok(Block::new(block.ptr(), new_size, block.align()))\n\n } else {\n\n Err((Error::OutOfMemory, block))\n\n }\n\n }\n", "file_path": "src/freelist.rs", "rank": 43, "score": 8.218074851488304 }, { "content": " // no op for this unless this is the last allocation.\n\n // The memory gets reused when the scope is cleared.\n\n let current_ptr = self.current.get();\n\n if !self.is_scoped() && block.ptr().offset(block.size() as isize) == current_ptr {\n\n self.current.set(block.ptr());\n\n }\n\n }\n\n}\n\n\n\nimpl<'a, A: Allocator> BlockOwner for Scoped<'a, A> {\n\n fn owns_block(&self, block: &Block) -> bool {\n\n let ptr = block.ptr();\n\n\n\n ptr >= self.start && ptr <= self.end\n\n }\n\n}\n\n\n\nimpl<'a, A: Allocator> Drop for Scoped<'a, A> {\n\n /// Drops the `Scoped`\n\n fn drop(&mut self) {\n", "file_path": "src/scoped.rs", "rank": 45, "score": 7.8942915066020145 }, { "content": " #[inline]\n\n fn allocate<T>(&self, val: T) -> Result<AllocBox<T, Self>, (Error, T)>\n\n where Self: Sized\n\n {\n\n match self.make_place() {\n\n Ok(place) => {\n\n Ok(in place { val })\n\n }\n\n Err(err) => {\n\n Err((err, val))\n\n }\n\n }\n\n }\n\n\n\n /// Attempts to create a place to allocate into.\n\n /// For the general purpose, calling `allocate` on the allocator is enough.\n\n /// However, when you know the value you are allocating is too large\n\n /// to be constructed on the stack, you should use in-place allocation.\n\n /// \n\n /// # Examples\n", "file_path": "src/lib.rs", "rank": 46, "score": 7.490103729255695 }, { "content": "//! Custom memory allocators and utilities for using them.\n\n//!\n\n//! # Examples\n\n//! ```rust\n\n//! #![feature(placement_in_syntax)]\n\n//!\n\n//! use std::io;\n\n//! use allocators::{Allocator, Scoped, BlockOwner, FreeList, Proxy};\n\n//!\n\n//! #[derive(Debug)]\n\n//! struct Bomb(u8);\n\n//!\n\n//! impl Drop for Bomb {\n\n//! fn drop(&mut self) {\n\n//! println!(\"Boom! {}\", self.0);\n\n//! }\n\n//! }\n\n//! // new scoped allocator with 4 kilobytes of memory.\n\n//! let alloc = Scoped::new(4 * 1024).unwrap();\n\n//!\n", "file_path": "src/lib.rs", "rank": 47, "score": 7.38811516481349 }, { "content": " alloc,\n\n coerce_unsized,\n\n heap_api,\n\n placement_new_protocol,\n\n placement_in_syntax,\n\n raw,\n\n unique,\n\n unsize,\n\n)]\n\n\n\nuse std::error::Error as StdError;\n\nuse std::fmt;\n\nuse std::marker::PhantomData;\n\nuse std::ptr::Unique;\n\n\n\nuse alloc::heap;\n\n\n\nextern crate alloc;\n\n\n\nmod boxed;\n", "file_path": "src/lib.rs", "rank": 48, "score": 7.157560623990092 }, { "content": " if self.is_scoped() {\n\n return Err(Error::AllocatorSpecific(\"Called allocate on already scoped \\\n\n allocator.\"\n\n .into()));\n\n }\n\n\n\n if size == 0 {\n\n return Ok(Block::empty());\n\n }\n\n\n\n let current_ptr = self.current.get();\n\n let aligned_ptr = super::align_forward(current_ptr, align);\n\n let end_ptr = aligned_ptr.offset(size as isize);\n\n\n\n if end_ptr > self.end {\n\n Err(Error::OutOfMemory)\n\n } else {\n\n self.current.set(end_ptr);\n\n Ok(Block::new(aligned_ptr, size, align))\n\n }\n", "file_path": "src/scoped.rs", "rank": 49, "score": 5.573660904250468 }, { "content": " Ok(block) => {\n\n let ptr: *mut *mut u8 = block.ptr() as *mut *mut u8;\n\n unsafe { *ptr = free_list }\n\n free_list = block.ptr();\n\n }\n\n Err(err) => {\n\n // destructor cleans up after us.\n\n drop(FreeList {\n\n alloc: alloc,\n\n block_size: block_size,\n\n free_list: Cell::new(free_list),\n\n });\n\n\n\n return Err(err);\n\n }\n\n }\n\n }\n\n\n\n Ok(FreeList {\n\n alloc: alloc,\n", "file_path": "src/freelist.rs", "rank": 50, "score": 5.50611473440892 }, { "content": " #[should_panic]\n\n fn use_outer() {\n\n let alloc = Scoped::new(4).unwrap();\n\n let mut outer_val = alloc.allocate(0i32).unwrap();\n\n alloc.scope(|_inner| {\n\n // using outer allocator is dangerous and should fail.\n\n outer_val = alloc.allocate(1i32).unwrap();\n\n })\n\n .unwrap();\n\n }\n\n\n\n #[test]\n\n fn scope_scope() {\n\n let alloc = Scoped::new(64).unwrap();\n\n let _ = alloc.allocate(0).unwrap();\n\n alloc.scope(|inner| {\n\n let _ = inner.allocate(32);\n\n inner.scope(|bottom| {\n\n let _ = bottom.allocate(23);\n\n })\n", "file_path": "src/scoped.rs", "rank": 51, "score": 4.0726795963318105 }, { "content": " #[test]\n\n fn owning() {\n\n let alloc = Scoped::new(64).unwrap();\n\n\n\n let val = alloc.allocate(1i32).unwrap();\n\n assert!(alloc.owns(&val));\n\n\n\n alloc.scope(|inner| {\n\n let in_val = inner.allocate(2i32).unwrap();\n\n assert!(inner.owns(&in_val));\n\n assert!(!inner.owns(&val));\n\n })\n\n .unwrap();\n\n }\n\n\n\n #[test]\n\n fn mutex_sharing() {\n\n use std::thread;\n\n use std::sync::{Arc, Mutex};\n\n let alloc = Scoped::new(64).unwrap();\n", "file_path": "src/scoped.rs", "rank": 52, "score": 3.9872656393940824 }, { "content": " align: self.align,\n\n allocator: self.allocator,\n\n };\n\n mem::forget(self);\n\n Ok(new_allocated)\n\n } else {\n\n Err(self)\n\n }\n\n }\n\n}\n\n\n\nimpl<'a, T: ?Sized, A: ?Sized + Allocator> Borrow<T> for AllocBox<'a, T, A> {\n\n fn borrow(&self) -> &T {\n\n &**self\n\n }\n\n}\n\n\n\nimpl<'a, T: ?Sized, A: ?Sized + Allocator> BorrowMut<T> for AllocBox<'a, T, A> {\n\n fn borrow_mut(&mut self) -> &mut T {\n\n &mut **self\n", "file_path": "src/boxed.rs", "rank": 53, "score": 3.9706514411851836 }, { "content": " .unwrap();\n\n })\n\n .unwrap();\n\n }\n\n\n\n #[test]\n\n fn out_of_memory() {\n\n // allocate more memory than the allocator has.\n\n let alloc = Scoped::new(0).unwrap();\n\n let (err, _) = alloc.allocate(1i32).err().unwrap();\n\n assert_eq!(err, Error::OutOfMemory);\n\n }\n\n\n\n #[test]\n\n fn placement_in() {\n\n let alloc = Scoped::new(8_000_000).unwrap();\n\n // this would smash the stack otherwise.\n\n let _big = in alloc.make_place().unwrap() { [0u8; 8_000_000] };\n\n }\n\n\n", "file_path": "src/scoped.rs", "rank": 54, "score": 3.5414130486465973 }, { "content": " let my_foo: AllocBox<Any, _> = HEAP.allocate(Bomb).unwrap();\n\n let _: AllocBox<Bomb, _> = my_foo.downcast().ok().unwrap();\n\n }\n\n\n\n #[test]\n\n fn take_out() {\n\n let _: [u8; 1024] = HEAP.allocate([0; 1024]).ok().unwrap().take();\n\n }\n\n\n\n #[test]\n\n fn boxed_allocator() {\n\n #[derive(Debug)]\n\n struct Increment<'a>(&'a mut i32);\n\n impl<'a> Drop for Increment<'a> {\n\n fn drop(&mut self) {\n\n *self.0 += 1;\n\n }\n\n }\n\n\n\n let mut i = 0;\n\n let alloc: Box<Allocator> = Box::new(HEAP);\n\n {\n\n let _ = alloc.allocate(Increment(&mut i)).unwrap();\n\n }\n\n assert_eq!(i, 1);\n\n }\n\n}\n", "file_path": "src/lib.rs", "rank": 55, "score": 3.2812525013592317 }, { "content": " }\n\n\n\n assert_eq!(*my_int, 0);\n\n }\n\n #[test]\n\n fn heap_in_place() {\n\n let big = in HEAP.make_place().unwrap() { [0u8; 8_000_000] };\n\n assert_eq!(big.len(), 8_000_000);\n\n }\n\n\n\n #[test]\n\n fn unsizing() {\n\n #[derive(Debug)]\n\n struct Bomb;\n\n impl Drop for Bomb {\n\n fn drop(&mut self) {\n\n println!(\"Boom\")\n\n }\n\n }\n\n\n", "file_path": "src/lib.rs", "rank": 56, "score": 1.90537379021228 }, { "content": "//! alloc.scope(|inner| {\n\n//! let mut bombs = Vec::new();\n\n//! // allocate makes the value on the stack first.\n\n//! for i in 0..100 { bombs.push(inner.allocate(Bomb(i)).unwrap())}\n\n//! // there's also in-place allocation!\n\n//! let bomb_101 = in inner.make_place().unwrap() { Bomb(101) };\n\n//! // watch the bombs go off!\n\n//! });\n\n//!\n\n//!\n\n//! // You can make allocators backed by other allocators.\n\n//! {\n\n//! let secondary_alloc = FreeList::new_from(&alloc, 128, 8).unwrap();\n\n//! let mut val = secondary_alloc.allocate(0i32).unwrap();\n\n//! *val = 1;\n\n//! }\n\n//!\n\n//! ```\n\n\n\n#![feature(\n", "file_path": "src/lib.rs", "rank": 57, "score": 1.744400265379894 }, { "content": " let data = Arc::new(Mutex::new(alloc));\n\n for i in 0..10 {\n\n let data = data.clone();\n\n thread::spawn(move || {\n\n let alloc_handle = data.lock().unwrap();\n\n let _ = alloc_handle.allocate(i).unwrap();\n\n });\n\n }\n\n }\n\n}\n", "file_path": "src/scoped.rs", "rank": 58, "score": 1.6652051775933652 } ]
Rust
src/bvh.rs
ItsHoff/Rusty
f0418d775442d553b69d8e342a15c597a7786451
use std::ops::{Index, Range}; use cgmath::Point3; use crate::aabb::Aabb; use crate::consts; use crate::float::*; use crate::intersect::{Intersect, Ray}; use crate::stats; use crate::triangle::Triangle; const MAX_LEAF_SIZE: usize = 8; #[allow(dead_code)] #[derive(Clone, Copy, Debug)] pub enum SplitMode { Object, Spatial, Sah, } enum Indices { Inner(u32, u32), Leaf(u32, u32), } #[repr(align(64))] pub struct BvhNode { aabb: Aabb, indices: Indices, } impl BvhNode { fn new(triangles: &Triangles) -> BvhNode { let start_i = triangles.start_i as u32; let end_i = start_i + triangles.len() as u32; BvhNode { aabb: triangles.aabb.clone(), indices: Indices::Leaf(start_i, end_i), } } fn convert_to_inner(&mut self, left_child: usize, right_child: usize) { self.indices = Indices::Inner(left_child as u32, right_child as u32); } pub fn range(&self) -> Option<Range<usize>> { match self.indices { Indices::Leaf(start_i, end_i) => Some(start_i as usize..end_i as usize), Indices::Inner(_, _) => None, } } } impl Intersect<'_, Float> for BvhNode { fn intersect(&self, ray: &Ray) -> Option<Float> { self.aabb.intersect(ray) } } struct Triangles<'a> { triangles: &'a [Triangle], centers: &'a [Point3<Float>], indices: &'a mut [usize], aabb: Aabb, start_i: usize, sorted_axis: usize, } impl<'a> Triangles<'a> { fn new( triangles: &'a [Triangle], centers: &'a [Point3<Float>], indices: &'a mut [usize], start_i: usize, ) -> Triangles<'a> { let mut aabb = Aabb::empty(); for &i in indices.iter() { let tri = &triangles[i]; aabb.add_aabb(&tri.aabb()); } Triangles { triangles, centers, indices, aabb, start_i, sorted_axis: 42, } } fn sort_longest_axis(&mut self) { let axis_i = self.aabb.longest_edge_i(); self.sort(axis_i); } fn sort(&mut self, axis_i: usize) { if axis_i == self.sorted_axis { return; } let centers = self.centers; self.indices.sort_unstable_by(|&i1, &i2| { let c1 = centers[i1][axis_i]; let c2 = centers[i2][axis_i]; c1.partial_cmp(&c2).unwrap() }); self.sorted_axis = axis_i; } fn split(self, i: usize) -> (Triangles<'a>, Triangles<'a>) { let (i1, i2) = self.indices.split_at_mut(i); let mut node1 = Triangles::new(self.triangles, self.centers, i1, self.start_i); let mut node2 = Triangles::new(self.triangles, self.centers, i2, self.start_i + i); node1.sorted_axis = self.sorted_axis; node2.sorted_axis = self.sorted_axis; (node1, node2) } fn len(&self) -> usize { self.indices.len() } fn last(&self) -> &Triangle { let &i = self.indices.last().unwrap(); &self.triangles[i] } } impl Index<usize> for Triangles<'_> { type Output = Triangle; fn index(&self, i: usize) -> &Triangle { let i = self.indices[i]; &self.triangles[i] } } pub struct Bvh { nodes: Vec<BvhNode>, } impl Bvh { pub fn build(triangles: &[Triangle], split_mode: SplitMode) -> (Bvh, Vec<usize>) { assert!( !triangles.is_empty(), "Scene doesn't contain any triangles!" ); assert!( triangles.len() <= 2usize.pow(32), "Scene can contain maximum of 2^32 triangles! This scene has {} triangles.", triangles.len() ); stats::start_bvh(); let centers: Vec<Point3<Float>> = triangles.iter().map(|tri| tri.center()).collect(); let mut permutation: Vec<usize> = (0..triangles.len()).collect(); let tris = Triangles::new(triangles, &centers, &mut permutation, 0); let mut nodes = Vec::with_capacity(Float::log2(triangles.len().to_float()) as usize); nodes.push(BvhNode::new(&tris)); let mut split_stack = vec![(0usize, tris)]; while let Some((node_i, mut tris)) = split_stack.pop() { let mid_offset = match split_mode { SplitMode::Object => object_split(&mut tris), SplitMode::Spatial => spatial_split(&mut tris), SplitMode::Sah => sah_split(&mut tris), }; let (t1, t2) = if let Some(offset) = mid_offset { tris.split(offset) } else { continue; }; let left_child = BvhNode::new(&t1); let left_child_i = nodes.len(); if t1.len() > MAX_LEAF_SIZE { split_stack.push((nodes.len(), t1)); } nodes.push(left_child); let right_child = BvhNode::new(&t2); let right_child_i = nodes.len(); if t2.len() > MAX_LEAF_SIZE { split_stack.push((nodes.len(), t2)); } nodes.push(right_child); nodes[node_i].convert_to_inner(left_child_i, right_child_i); } nodes.shrink_to_fit(); let bvh = Bvh { nodes }; stats::stop_bvh(&bvh, triangles.len()); (bvh, permutation) } pub fn get_children(&self, node: &BvhNode) -> Option<(&BvhNode, &BvhNode)> { match node.indices { Indices::Leaf(_, _) => None, Indices::Inner(left_i, right_i) => { Some((&self.nodes[left_i as usize], &self.nodes[right_i as usize])) } } } pub fn root(&self) -> &BvhNode { &self.nodes[0] } pub fn size(&self) -> usize { self.nodes.len() } } fn object_split(triangles: &mut Triangles) -> Option<usize> { triangles.sort_longest_axis(); Some(triangles.len() / 2) } fn spatial_split(triangles: &mut Triangles) -> Option<usize> { let aabb = &triangles.aabb; let axis_i = aabb.longest_edge_i(); let mid_val = aabb.center()[axis_i]; triangles.sort(axis_i); let centers = triangles.centers; let i = triangles .indices .binary_search_by(|&i| { let c = centers[i][axis_i]; c.partial_cmp(&mid_val).unwrap() }) .unwrap_or_else(|e| e); if i == 0 || i == triangles.len() { object_split(triangles) } else { Some(i) } } fn sah_split(triangles: &mut Triangles) -> Option<usize> { let mut min_score = consts::MAX; let mut min_axis = 0; let mut min_i = 0; let sorted_axis = triangles.sorted_axis; for offset in 0..3 { let axis = (sorted_axis + offset) % 3; triangles.sort(axis); let mut right_bbs = Vec::with_capacity(triangles.len()); right_bbs.push(triangles.last().aabb()); for i in 1..triangles.len() { let mut new_bb = right_bbs[i - 1].clone(); new_bb.add_aabb(&triangles[triangles.len() - 1 - i].aabb()); right_bbs.push(new_bb); } let mut left_bb = Aabb::empty(); for i in 0..triangles.len() { left_bb.add_aabb(&triangles[i].aabb()); let right_bb = &right_bbs[right_bbs.len() - 1 - i]; let n_left = i.to_float(); let n_right = (triangles.len() - i).to_float(); let score = n_left * left_bb.area() + n_right * right_bb.area(); if score < min_score { min_score = score; min_axis = axis; min_i = i; } } } if min_i == 0 { None } else { triangles.sort(min_axis); Some(min_i) } }
use std::ops::{Index, Range}; use cgmath::Point3; use crate::aabb::Aabb; use crate::consts; use crate::float::*; use crate::intersect::{Intersect, Ray}; use crate::stats; use crate::triangle::Triangle; const MAX_LEAF_SIZE: usize = 8; #[allow(dead_code)] #[derive(Clone, Copy, Debug)] pub enum SplitMode { Object, Spatial, Sah, } enum Indices { Inner(u32, u32), Leaf(u32, u32), } #[repr(align(64))] pub struct BvhNode { aabb: Aabb, indices: Indices, } impl BvhNode { fn new(triangles: &Triangles) -> BvhNode { let start_i = triangles.start_i as u32; let end_i = start_i + triangles.len() as u32; BvhNode { aabb: triangles.aabb.clone(), indices: Indices::Leaf(start_i, end_i), } } fn convert_to_inner(&mut self, left_child: usize, right_child: usize) { self.indices = Indices::Inner(left_child as u32, right_child as u32); } pub fn range(&self) -> Option<Range<usize>> { match self.indices { Indices::Leaf(start_i, end_i) => Some(start_i as usize..end_i as usize), Indices::Inner(_, _) => None, } } } impl Intersect<'_, Float> for BvhNode { fn intersect(&self, ray: &Ray) -> Option<Float> { self.aabb.intersect(ray) } } struct Triangles<'a> { triangles: &'a [Triangle], centers: &'a [Point3<Float>], indices: &'a mut [usize], aabb: Aabb, start_i: usize, sorted_axis: usize, } impl<'a> Triangles<'a> { fn new( triangles: &'a [Triangle], centers: &'a [Point3<Float>], indices: &'a mut [usize], start_i: usize, ) -> Triangles<'a> { let mut aabb = Aabb::empty(); for &i in indices.iter() { let tri = &triangles[i]; aabb.add_aabb(&tri.aabb()); } Triangles { triangles, centers, indices, aabb, start_i, sorted_axis: 42, } } fn sort_longest_axis(&mut self) { let axis_i = self.aabb.longest_edge_i(); self.sort(axis_i); } fn sort(&mut self, axis_i: usize) { if axis_i == self.sorted_axis { return; } let centers = self.centers; self.indices.sort_unstable_by(|&i1, &i2| { let c1 = centers[i1][axis_i]; let c2 = centers[i2][axis_i]; c1.partial_cmp(&c2).unwrap() }); self.sorted_axis = axis_i; } fn split(self, i: usize) -> (Triangles<'a>, Triangles<'a>) { let (i1, i2) = self.indices.split_at_mut(i); let mut node1 = Triangles::new(self.triangles, self.centers, i1, self.start_i); let mut node2 = Triangles::new(self.triangles, self.centers, i2, self.start_i + i); node1.sorted_axis = self.sorted_axis; node2.sorted_axis = self.sorted_axis; (node1, node2) } fn len(&self) -> usize { self.indices.len() } fn last(&self) -> &Triangle { let &i = self.indices.last().unwrap(); &self.triangles[i] } } impl Index<usize> for Triangles<'_> { type Output = Triangle; fn index(&self, i: usize) -> &Triangle { let i = self.indices[i]; &self.triangles[i] } } pub struct Bvh { nodes: Vec<BvhNode>, } impl Bvh { pub fn build(triangles: &[Triangle], split_mode: SplitMode) -> (Bvh, Vec<usize>) { assert!( !triangles.is_empty(), "Scene doesn't contain any triangles!" ); assert!( triangles.len() <= 2usize.pow(32), "Scene can contain maximum of 2^32 triangles! This scene has {} triangles.", triangles.len() ); stats::start_bvh(); let centers: Vec<Point3<Float>> = triangles.iter().map(|tri| tri.center()).collect(); let mut permutation: Vec<usize> = (0..triangles.len()).collect(); let tris = Triangles::new(triangles, &centers, &mut permutation, 0); let mut nodes = Vec::with_capacity(Float::log2(triangles.len().to_float()) as usize); nodes.push(BvhNode::new(&tris)); let mut split_stack = vec![(0usize, tris)]; while let Some((node_i, mut tris)) = split_stack.pop() { let mid_offset = match split_mode { SplitMode::Object => object_split(&mut tris), SplitMode::Spatial => spatial_split(&mut tris), SplitMode::Sah => sah_split(&mut tris), }; let (t1, t2) = if let Some(offset) = mid_offset { tris.split(offset) } else { continue; }; let left_child = BvhNode::new(&t1); let left_child_i = nodes.len(); if t1.len() > MAX_LEAF_SIZE { split_stack.push((nodes.len(), t1)); } nodes.push(left_child); let right_child = BvhNode::new(&t2); let right_child_i = nodes.len(); if t2.len() > MAX_LEAF_SIZE { split_stack.push((nodes.len(), t2)); } nodes.push(right_child); nodes[node_i].convert_to_inner(left_child_i, right_child_i); } nodes.shrink_to_fit(); let bvh = Bvh { nodes }; stats::stop_bvh(&bvh, triangles.len()); (bvh, permutation) } pub fn get_children(&self, node: &BvhNode) -> Option<(&BvhNode, &BvhNode)> { match node.indices { Indices::Leaf(_, _) => None, Indices::Inner(left_i, right_i) => { Some((&self.nodes[left_i as usize], &self.nodes[right_i as usize])) } } } pub fn root(&self) -> &BvhNode { &self.nodes[0] } pub fn size(&self) -> usize { self.nodes.len() } } fn object_split(triangles: &mut Triangles) -> Option<usize> { triangles.sort_longest_axis(); Some(triangles.len() / 2) } fn spatial_split(triangles: &mut Triangles) -> Option<usize> { let aabb = &triangles.aabb; let axis_i = aabb.longest_edge_i(); let mid_val = aabb.center()[axis_i]; triangles.sort(axis_i); let centers = triangles.centers; let i = triangles .indices .binary_search_by(|&i| { let c = centers[i][axis_i]; c.partial_cmp(&mid_val).unwrap() }) .unwrap_or_else(|e| e); if i == 0 || i == triangles.len() { object_split(triangles) } else { Some(i) } } fn sah_split(triangles: &mut Triangles) -> Option<usize> { let mut min_score = consts::MAX; let mut min_axis = 0; let mut min_i = 0; let sorted_axis = triangles.sorted_axis; for offset in 0..3 { let axis = (sorted_axis + offset) % 3; triangles.sort(axis); let mut right_bbs = Vec::with_capacity(triangles.len()); right_bbs.push(triangles.last().aabb()); for i in 1..triangles.len() { let mut new_bb = right_bbs[i - 1].clone(); new_bb.add_aabb(&triangles[triangles.len() - 1 - i].aabb());
right_bbs.push(new_bb); } let mut left_bb = Aabb::empty(); for i in 0..triangles.len() { left_bb.add_aabb(&triangles[i].aabb()); let right_bb = &right_bbs[right_bbs.len() - 1 - i]; let n_left = i.to_float(); let n_right = (triangles.len() - i).to_float(); let score = n_left * left_bb.area() + n_right * right_bb.area(); if score < min_score { min_score = score; min_axis = axis; min_i = i; } } } if min_i == 0 { None } else { triangles.sort(min_axis); Some(min_i) } }
function_block-function_prefix_line
[ { "content": "#[allow(dead_code)]\n\npub fn gamma(n: u32) -> Float {\n\n let n = n.to_float();\n\n n * consts::MACHINE_EPSILON / (1.0 - n * consts::MACHINE_EPSILON)\n\n}\n\n\n", "file_path": "src/float.rs", "rank": 3, "score": 211379.58543044538 }, { "content": "#[allow(dead_code)]\n\npub fn previous_ulp(mut x: Float) -> Float {\n\n if x.is_infinite() && x < 0.0 {\n\n return x;\n\n }\n\n if x == 0.0 {\n\n x = -0.0\n\n }\n\n let mut bits = x.to_bits();\n\n bits = if x >= 0.0 { bits - 1 } else { bits + 1 };\n\n Float::from_bits(bits)\n\n}\n\n\n\nimpl ToFloat for u8 {\n\n fn to_float(self) -> Float {\n\n self.into()\n\n }\n\n}\n\n\n\nimpl ToFloat for u32 {\n\n #[allow(clippy::cast_lossless)]\n", "file_path": "src/float.rs", "rank": 4, "score": 209850.19162032037 }, { "content": "#[allow(dead_code)]\n\npub fn next_ulp(mut x: Float) -> Float {\n\n if x.is_infinite() && x > 0.0 {\n\n return x;\n\n }\n\n if x == -0.0 {\n\n x = 0.0\n\n }\n\n let mut bits = x.to_bits();\n\n bits = if x >= 0.0 { bits + 1 } else { bits - 1 };\n\n Float::from_bits(bits)\n\n}\n\n\n", "file_path": "src/float.rs", "rank": 5, "score": 209850.19162032037 }, { "content": "pub fn stop_bvh(bvh: &Bvh, n_tris: usize) {\n\n stop_timer(\"Bvh\");\n\n current_scene!().analyze_bvh(bvh, n_tris);\n\n}\n\n\n", "file_path": "src/stats.rs", "rank": 6, "score": 188095.90701267667 }, { "content": "/// Convert u8 color to float color in range [0, 1]\n\npub fn component_to_float(c: u8) -> Float {\n\n c.to_float() / std::u8::MAX.to_float()\n\n}\n\n\n", "file_path": "src/color.rs", "rank": 7, "score": 176557.9556432687 }, { "content": "pub fn min_point(p1: &Point3<Float>, p2: &Point3<Float>) -> Point3<Float> {\n\n let mut p_min = Point3::max_value();\n\n for i in 0..3 {\n\n p_min[i] = p1[i].min(p2[i]);\n\n }\n\n p_min\n\n}\n\n\n", "file_path": "src/aabb.rs", "rank": 8, "score": 166179.81158655474 }, { "content": "pub fn max_point(p1: &Point3<Float>, p2: &Point3<Float>) -> Point3<Float> {\n\n let mut p_max = Point3::min_value();\n\n for i in 0..3 {\n\n p_max[i] = p1[i].max(p2[i]);\n\n }\n\n p_max\n\n}\n", "file_path": "src/aabb.rs", "rank": 9, "score": 166179.81158655474 }, { "content": "pub fn new_scene(name: &str) {\n\n let mut vec = get_stats_vec!();\n\n vec.push(Statistics::new(name));\n\n}\n\n\n", "file_path": "src/statistics.rs", "rank": 10, "score": 156618.72967228206 }, { "content": "pub fn new_scene(name: &str) {\n\n stats!().new_scene(name);\n\n}\n\n\n", "file_path": "src/stats.rs", "rank": 11, "score": 156618.72967228206 }, { "content": "/// Calculate planar normal for a triangle\n\nfn calculate_normal(triangle: &obj_load::Triangle, obj: &obj_load::Object) -> [f32; 3] {\n\n let pos_i1 = triangle.index_vertices[0].pos_i;\n\n let pos_i2 = triangle.index_vertices[1].pos_i;\n\n let pos_i3 = triangle.index_vertices[2].pos_i;\n\n let pos_1 = Vector3::from_array(obj.positions[pos_i1]);\n\n let pos_2 = Vector3::from_array(obj.positions[pos_i2]);\n\n let pos_3 = Vector3::from_array(obj.positions[pos_i3]);\n\n let u = pos_2 - pos_1;\n\n let v = pos_3 - pos_1;\n\n let normal = u.cross(v).normalize();\n\n normal.into_array()\n\n}\n\n\n\nimpl Scene {\n\n fn empty() -> Arc<Self> {\n\n Arc::new(Self {\n\n vertices: Vec::new(),\n\n meshes: Vec::new(),\n\n materials: Vec::new(),\n\n triangles: Vec::new(),\n", "file_path": "src/scene.rs", "rank": 12, "score": 155200.85179262923 }, { "content": "pub fn uniform_sphere_pdf() -> Float {\n\n 1.0 / (4.0 * consts::PI)\n\n}\n", "file_path": "src/sample.rs", "rank": 13, "score": 153049.12359645008 }, { "content": "pub fn cosine_hemisphere_pdf(abs_cos_t: Float) -> Float {\n\n abs_cos_t / consts::PI\n\n}\n\n\n", "file_path": "src/sample.rs", "rank": 14, "score": 153039.24745066988 }, { "content": "pub fn tan2_t(vec: Vector3<Float>) -> Float {\n\n sin2_t(vec) / cos2_t(vec)\n\n}\n", "file_path": "src/bsdf/util.rs", "rank": 15, "score": 152388.82605882303 }, { "content": "pub fn sin2_t(vec: Vector3<Float>) -> Float {\n\n 1.0 - cos2_t(vec)\n\n}\n\n\n", "file_path": "src/bsdf/util.rs", "rank": 16, "score": 152388.82605882303 }, { "content": "pub fn sin_t(vec: Vector3<Float>) -> Float {\n\n sin2_t(vec).sqrt()\n\n}\n\n\n", "file_path": "src/bsdf/util.rs", "rank": 17, "score": 152388.82605882303 }, { "content": "pub fn cos_t(vec: Vector3<Float>) -> Float {\n\n vec.z\n\n}\n\n\n", "file_path": "src/bsdf/util.rs", "rank": 18, "score": 152388.82605882303 }, { "content": "pub fn cos2_t(vec: Vector3<Float>) -> Float {\n\n vec.z * vec.z\n\n}\n\n\n", "file_path": "src/bsdf/util.rs", "rank": 19, "score": 152388.82605882303 }, { "content": "/// Compute the total index of refraction for incident direction w.\n\npub fn eta(w: Vector3<Float>, eta_mat: Float) -> Float {\n\n if w.z > 0.0 {\n\n 1.0 / eta_mat\n\n } else {\n\n eta_mat\n\n }\n\n}\n\n\n\n// Trigonometric functions\n\n\n", "file_path": "src/bsdf/util.rs", "rank": 20, "score": 150902.40130558982 }, { "content": "/// Convert area pdf to solid angle pdf\n\npub fn to_dir_pdf(pdf_a: Float, dist2: Float, abs_cos_t: Float) -> Float {\n\n pdf_a * dist2 / abs_cos_t\n\n}\n\n\n", "file_path": "src/sample.rs", "rank": 21, "score": 150254.9758645318 }, { "content": "/// Cosine sample either (0, 0, 1) or (0, 0, -1) hemisphere decided by sign\n\npub fn cosine_sample_hemisphere(sign: Float) -> Vector3<Float> {\n\n let phi = 2.0 * consts::PI * rand::random::<Float>();\n\n let r = rand::random::<Float>().sqrt();\n\n let x = r * phi.cos();\n\n let y = r * phi.sin();\n\n // Make sure sampled vector is in the correct hemisphere\n\n // Use signum to ensure correct length\n\n let z = sign.signum() * (1.0 - r.powi(2)).sqrt();\n\n Vector3::new(x, y, z)\n\n}\n\n\n", "file_path": "src/sample.rs", "rank": 22, "score": 149626.48897864984 }, { "content": "/// Compute an orthonormal coordinate frame where n defines is the z-axis\n\npub fn local_to_world(n: Vector3<Float>) -> Matrix3<Float> {\n\n let nx = if n.x.abs() > n.y.abs() {\n\n Vector3::new(n.z, 0.0, -n.x).normalize()\n\n } else {\n\n Vector3::new(0.0, -n.z, n.y).normalize()\n\n };\n\n let ny = n.cross(nx).normalize();\n\n Matrix3::from_cols(nx, ny, n)\n\n}\n\n\n", "file_path": "src/sample.rs", "rank": 23, "score": 149335.16624647458 }, { "content": "/// Reflect w around n\n\npub fn reflect_n(w: Vector3<Float>) -> Vector3<Float> {\n\n Vector3::new(-w.x, -w.y, w.z)\n\n}\n\n\n", "file_path": "src/bsdf/util.rs", "rank": 24, "score": 149331.167535019 }, { "content": "/// Convert solid angle pdf to area pdf\n\npub fn to_area_pdf(pdf_dir: Float, dist2: Float, abs_cos_t: Float) -> Float {\n\n pdf_dir * abs_cos_t / dist2\n\n}\n\n\n\n#[allow(clippy::many_single_char_names)]\n", "file_path": "src/sample.rs", "rank": 25, "score": 148217.31281791988 }, { "content": "pub fn uniform_sample_sphere() -> Vector3<Float> {\n\n let phi = 2.0 * consts::PI * rand::random::<Float>();\n\n let z = 1.0 - 2.0 * rand::random::<Float>();\n\n let r = (1.0 - z.powi(2)).sqrt();\n\n Vector3::new(r * phi.cos(), r * phi.sin(), z)\n\n}\n\n\n", "file_path": "src/sample.rs", "rank": 26, "score": 145220.4691224141 }, { "content": "/// Convert srgb color to linear color\n\nfn to_linear(c: Float) -> Float {\n\n c.powf(2.2)\n\n}\n\n\n", "file_path": "src/color.rs", "rank": 27, "score": 143950.91282154742 }, { "content": "fn to_srgb(c: Float) -> Float {\n\n c.powf(1.0 / 2.2)\n\n}\n\n\n\n#[derive(Clone, Copy, Debug)]\n\npub struct SrgbColor(BaseColor);\n\n\n\nimpl SrgbColor {\n\n pub fn from_pixel(pixel: image::Rgb<u8>) -> Self {\n\n Self(BaseColor::from_pixel(pixel))\n\n }\n\n\n\n pub fn is_gray(&self) -> bool {\n\n self.0.is_gray()\n\n }\n\n\n\n pub fn to_linear(self) -> Color {\n\n Color(self.0.to_linear())\n\n }\n\n\n", "file_path": "src/color.rs", "rank": 28, "score": 143950.91282154742 }, { "content": "/// Reflect w around wh\n\npub fn reflect(w: Vector3<Float>, wh: Vector3<Float>) -> Vector3<Float> {\n\n -w + 2.0 * wh.dot(w) * wh\n\n}\n\n\n", "file_path": "src/bsdf/util.rs", "rank": 29, "score": 143902.48764674744 }, { "content": "/// Refract w around the shading normal (0, 0, 1)\n\npub fn refract_n(w: Vector3<Float>, eta_mat: Float) -> Option<Vector3<Float>> {\n\n // Make sure normal is in the same hemisphere as w\n\n let n = w.z.signum() * Vector3::unit_z();\n\n refract(w, n, eta_mat)\n\n}\n\n\n", "file_path": "src/bsdf/util.rs", "rank": 30, "score": 141675.60492921766 }, { "content": "pub fn start_bvh() {\n\n let mut handle = time(\"Bvh\");\n\n handle.deactivate();\n\n}\n\n\n", "file_path": "src/stats.rs", "rank": 31, "score": 140187.17515556508 }, { "content": "/// Refract w around wh, which is assumed to be in the same hemisphere as w.\n\n/// eta_mat defines the index of refraction inside the material (outside is assumed to be air).\n\npub fn refract(w: Vector3<Float>, wh: Vector3<Float>, eta_mat: Float) -> Option<Vector3<Float>> {\n\n // Determine if w is entering or exiting the material\n\n let eta = eta(w, eta_mat);\n\n let cos_ti = w.dot(wh).abs();\n\n let sin2_ti = (1.0 - cos_ti.powi(2)).max(0.0);\n\n let sin2_tt = eta.powi(2) * sin2_ti;\n\n // Total internal reflection\n\n if sin2_tt >= 1.0 {\n\n return None;\n\n }\n\n let cos_tt = (1.0 - sin2_tt).sqrt();\n\n Some(-w * eta + (eta * cos_ti - cos_tt) * wh)\n\n}\n\n\n", "file_path": "src/bsdf/util.rs", "rank": 33, "score": 136768.04330801516 }, { "content": "pub fn debug_trace<'a>(\n\n ray: Ray,\n\n mode: &DebugMode,\n\n scene: &'a Scene,\n\n config: &RenderConfig,\n\n node_stack: &mut Vec<(&'a BvhNode, Float)>,\n\n) -> Color {\n\n match mode {\n\n DebugMode::Normals => trace_normals(ray, scene, config, node_stack, false),\n\n DebugMode::ForwardNormals => trace_normals(ray, scene, config, node_stack, true),\n\n }\n\n}\n\n\n", "file_path": "src/pt_renderer/tracers/debug.rs", "rank": 34, "score": 136425.65396945248 }, { "content": "/// Check if the vectors are in the same hemisphere\n\npub fn same_hemisphere(w1: Vector3<Float>, w2: Vector3<Float>) -> bool {\n\n w1.z * w2.z > 0.0\n\n}\n\n\n", "file_path": "src/bsdf/util.rs", "rank": 35, "score": 136272.54922826425 }, { "content": "/// Parse a single integer from the split input line\n\nfn parse_int(split_line: &mut SplitWhitespace) -> Option<u32> {\n\n let item = split_line.next()?;\n\n item.parse().ok()\n\n}\n\n\n", "file_path": "src/obj_load.rs", "rank": 37, "score": 131605.7375070054 }, { "content": "pub fn schlick(w: Vector3<Float>, specular: Color) -> Color {\n\n let cos_t = util::cos_t(w).abs();\n\n specular + (1.0 - cos_t).powi(5) * (Color::white() - specular)\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct FresnelBSDF<R: BsdfTrait, T: BsdfTrait> {\n\n pub brdf: R,\n\n pub btdf: T,\n\n pub eta: Float,\n\n}\n\n\n\nimpl<R: BsdfTrait, T: BsdfTrait> BsdfTrait for FresnelBSDF<R, T> {\n\n fn is_specular(&self) -> bool {\n\n self.brdf.is_specular() || self.btdf.is_specular()\n\n }\n\n\n\n fn brdf(&self, wo: Vector3<Float>, wi: Vector3<Float>) -> Color {\n\n let fr = dielectric(wo, self.eta);\n\n fr * self.brdf.brdf(wo, wi)\n", "file_path": "src/bsdf/fresnel.rs", "rank": 38, "score": 126116.5052284537 }, { "content": "pub fn cpu_scene_from_name(name: &str, config: &RenderConfig) -> (Arc<Scene>, Camera) {\n\n let _t = stats::time(\"Load\");\n\n let info = SCENE_LIBRARY.get(name).unwrap();\n\n cpu_scene(&info.path, info.camera_pos, config)\n\n}\n\n\n", "file_path": "src/load.rs", "rank": 39, "score": 125548.0134454565 }, { "content": "pub fn vector_to_pixel(vec: Vector3<Float>) -> image::Rgb<u8> {\n\n let conv = |f: Float| (f * std::u8::MAX.to_float()) as u8;\n\n image::Rgb([conv(vec.x), conv(vec.y), conv(vec.z)])\n\n}\n\n\n", "file_path": "src/color.rs", "rank": 40, "score": 123484.60017640138 }, { "content": "pub fn pixel_to_vector(pixel: image::Rgb<u8>) -> Vector3<Float> {\n\n let channels = pixel.channels();\n\n Vector3::new(\n\n component_to_float(channels[0]),\n\n component_to_float(channels[1]),\n\n component_to_float(channels[2]),\n\n )\n\n}\n\n\n", "file_path": "src/color.rs", "rank": 41, "score": 123484.60017640138 }, { "content": "pub fn gpu_scene_from_key<F: Facade>(\n\n facade: &F,\n\n key: VirtualKeyCode,\n\n config: &RenderConfig,\n\n) -> Option<(Arc<Scene>, GPUScene, Camera)> {\n\n let name = SCENE_LIBRARY.key_to_name(key)?;\n\n stats::new_scene(name);\n\n let info = SCENE_LIBRARY.get(name).unwrap();\n\n let res = gpu_scene(facade, &info.path, info.camera_pos, config);\n\n println!(\"Loaded scene {}\", name);\n\n Some(res)\n\n}\n", "file_path": "src/load.rs", "rank": 42, "score": 123142.11003833196 }, { "content": "pub fn gpu_scene_from_path<F: Facade>(\n\n facade: &F,\n\n path: &Path,\n\n config: &RenderConfig,\n\n) -> Option<(Arc<Scene>, GPUScene, Camera)> {\n\n if let Some(\"obj\") = util::lowercase_extension(path).as_deref() {\n\n stats::new_scene(path.to_str().unwrap());\n\n let res = gpu_scene(facade, path, CameraPos::Offset, config);\n\n println!(\"Loaded scene from {:?}\", path);\n\n Some(res)\n\n } else {\n\n println!(\"{:?} is not object file (.obj)\", path);\n\n None\n\n }\n\n}\n\n\n", "file_path": "src/load.rs", "rank": 43, "score": 123142.11003833196 }, { "content": "/// Load an object found at the given path\n\npub fn load_obj(obj_path: &Path) -> Result<Object, Box<dyn Error>> {\n\n let _t = stats::time(\"Load obj\");\n\n let mut obj = Object::new();\n\n let mut state = ParseState::new();\n\n let obj_dir = obj_path.parent().ok_or(\"Couldn't get object directory\")?;\n\n let obj_file = File::open(obj_path)?;\n\n let obj_reader = BufReader::new(obj_file);\n\n for line in obj_reader.lines() {\n\n let line = line.expect(\"Failed to unwrap line\");\n\n let mut split_line = line.split_whitespace();\n\n // Find the keyword of the line\n\n if let Some(key) = split_line.next() {\n\n match key {\n\n \"f\" => {\n\n if let Some(polygon) = parse_polygon(&mut split_line, &obj, &state) {\n\n // Auto convert to triangles\n\n // TODO: Make triangle conversion optional\n\n obj.triangles.append(&mut polygon.to_triangles());\n\n }\n\n }\n", "file_path": "src/obj_load.rs", "rank": 44, "score": 115695.64396168568 }, { "content": "/// Fresnel reflection for w\n\nfn dielectric(w: Vector3<Float>, eta_mat: Float) -> Float {\n\n // Determine if w is entering or exiting the material\n\n let (eta_i, eta_t) = if w.z > 0.0 {\n\n (1.0, eta_mat)\n\n } else {\n\n (eta_mat, 1.0)\n\n };\n\n let cos_ti = util::cos_t(w).abs();\n\n let sin2_ti = (1.0 - cos_ti.powi(2)).max(0.0);\n\n let sin2_tt = (eta_i / eta_t).powi(2) * sin2_ti;\n\n // Total internal reflection\n\n if sin2_tt >= 1.0 {\n\n return 1.0;\n\n }\n\n let cos_tt = (1.0 - sin2_tt).sqrt();\n\n let paral = (eta_t * cos_ti - eta_i * cos_tt) / (eta_t * cos_ti + eta_i * cos_tt);\n\n let perp = (eta_i * cos_ti - eta_t * cos_tt) / (eta_i * cos_ti + eta_t * cos_tt);\n\n (paral.powi(2) + perp.powi(2)) / 2.0\n\n}\n\n\n", "file_path": "src/bsdf/fresnel.rs", "rank": 45, "score": 112579.85755819791 }, { "content": "pub trait Light: Debug {\n\n /// Total emissive power of the light\n\n fn power(&self) -> Color;\n\n\n\n /// Emitted radiance to dir\n\n fn le(&self, dir: Vector3<Float>) -> Color;\n\n\n\n /// Evaluate the geometric cosine with dir\n\n fn cos_g(&self, dir: Vector3<Float>) -> Float;\n\n\n\n /// Check if light position contains a delta distribution\n\n fn delta_pos(&self) -> bool;\n\n\n\n /// Sample a position on the lights surface\n\n /// Return point and area pdf\n\n fn sample_pos(&self) -> (Point3<Float>, Float);\n\n\n\n /// Pdf of position sampling in area measure\n\n fn pdf_pos(&self) -> Float;\n\n\n", "file_path": "src/light.rs", "rank": 46, "score": 112468.2569213894 }, { "content": "pub fn print() {\n\n let vec = get_stats_vec!();\n\n for stats in &*vec {\n\n let (labels, durations) = stats.stopwatch_string();\n\n ptable!([labels, durations]);\n\n }\n\n}\n\n\n", "file_path": "src/statistics.rs", "rank": 47, "score": 110423.51029065673 }, { "content": "/// Parse a single float from the split input line\n\nfn parse_float(split_line: &mut SplitWhitespace) -> Option<f32> {\n\n let item = split_line.next()?;\n\n item.parse().ok()\n\n}\n\n\n\n/// Parse two floats from the split input line\n", "file_path": "src/obj_load.rs", "rank": 48, "score": 110228.94269922585 }, { "content": "pub fn start_render() {\n\n let mut handle = time(\"Render\");\n\n Ray::reset_count();\n\n handle.deactivate();\n\n}\n\n\n", "file_path": "src/stats.rs", "rank": 49, "score": 107671.60255421586 }, { "content": "pub fn stop_render() {\n\n stop_timer(\"Render\");\n\n current_scene!().ray_count = Ray::count();\n\n}\n\n\n", "file_path": "src/stats.rs", "rank": 50, "score": 107671.60255421586 }, { "content": "#[allow(clippy::needless_range_loop)]\n\nfn parse_float2(split_line: &mut SplitWhitespace) -> Option<[f32; 2]> {\n\n let mut float2 = [0.0f32; 2];\n\n for i in 0..2 {\n\n let item = split_line.next()?;\n\n float2[i] = item.parse().ok()?;\n\n }\n\n Some(float2)\n\n}\n\n\n\n/// Parse three floats from the split input line\n", "file_path": "src/obj_load.rs", "rank": 51, "score": 103018.0940370131 }, { "content": "#[allow(clippy::needless_range_loop)]\n\nfn parse_float3(split_line: &mut SplitWhitespace) -> Option<[f32; 3]> {\n\n let mut float3 = [0.0f32; 3];\n\n for i in 0..3 {\n\n let item = split_line.next()?;\n\n float3[i] = item.parse().ok()?;\n\n }\n\n Some(float3)\n\n}\n\n\n", "file_path": "src/obj_load.rs", "rank": 52, "score": 102979.11891648574 }, { "content": "pub trait ToFloat {\n\n fn to_float(self) -> Float;\n\n}\n\n\n\n#[cfg(not(feature = \"single_precision\"))]\n\nmod double {\n\n pub type Float = f64;\n\n use super::*;\n\n\n\n impl ToFloat for f32 {\n\n fn to_float(self) -> Float {\n\n self.into()\n\n }\n\n }\n\n\n\n impl ToFloat for f64 {\n\n fn to_float(self) -> Float {\n\n self\n\n }\n\n }\n", "file_path": "src/float.rs", "rank": 53, "score": 100060.70514959653 }, { "content": "// TODO: avoid allocations\n\npub fn bdpt<'a>(\n\n camera_ray: Ray,\n\n scene: &'a Scene,\n\n camera: &'a PTCamera,\n\n config: &RenderConfig,\n\n node_stack: &mut Vec<(&'a BvhNode, Float)>,\n\n splats: &mut Vec<(Point2<Float>, Color)>,\n\n) -> Color {\n\n let camera_vertex = CameraVertex::new(camera, camera_ray);\n\n let (beta, ray) = camera_vertex.sample_next();\n\n let camera_path = generate_path(beta, ray, PathType::Camera, scene, config, node_stack);\n\n let (light, light_pdf) = match config.light_mode {\n\n LightMode::Scene => scene.sample_light().unwrap_or((camera.flash(), 1.0)),\n\n LightMode::Camera => (camera.flash(), 1.0),\n\n };\n\n let (light_pos, pos_pdf) = light.sample_pos();\n\n let light_vertex = LightVertex::new(light, light_pos, light_pdf * pos_pdf);\n\n let (beta, ray) = light_vertex.sample_next();\n\n let light_path = generate_path(beta, ray, PathType::Light, scene, config, node_stack);\n\n let bd_path = BDPath::new(\n", "file_path": "src/pt_renderer/tracers/bdpt.rs", "rank": 54, "score": 99448.48778774745 }, { "content": "/// Get the area pdf of forward and backward scattering v1 -> v2 -> v3\n\n/// Return None if pdf is a delta distribution\n\n/// This used for scatterings along pure paths (only camera or light and not mixed),\n\n/// which means that the rays that generated v2 and v3 contain the correct direction\n\n/// and lengths. This is more efficient that computing them again, but more importantly\n\n/// recomputing the direction will cause subtle errors since the computed direction won't\n\n/// match the real sampled direction due to ray origin shift.\n\n/// r_\n\n/// exaggerated | \\_\n\n/// visualization | \\_ != x -----> o\n\n/// x \\-> o\n\npub fn pdf_precompute(\n\n v1: &dyn Vertex,\n\n v2: &SurfaceVertex,\n\n v3: &SurfaceVertex,\n\n) -> (Option<Float>, Option<Float>) {\n\n if v2.delta_dir() {\n\n return (None, None);\n\n }\n\n let wo = -v2.ray.dir;\n\n let wi = v3.ray.dir;\n\n let mut pdf_fwd = v2.isect.pdf(wo, wi);\n\n let mut pdf_rev = v2.isect.pdf(wi, wo);\n\n pdf_fwd = sample::to_area_pdf(pdf_fwd, v3.ray.length.powi(2), v3.cos_g(wi).abs());\n\n pdf_rev = sample::to_area_pdf(pdf_rev, v2.ray.length.powi(2), v1.cos_g(wo).abs());\n\n (Some(pdf_fwd), Some(pdf_rev))\n\n}\n\n\n\npub struct BDPath<'a> {\n\n light_vertex: &'a LightVertex<'a>,\n\n light_path: &'a [SurfaceVertex<'a>],\n", "file_path": "src/pt_renderer/tracers/bdpt/vertex.rs", "rank": 55, "score": 98642.60259979262 }, { "content": "fn initialize_camera(scene: &Scene, pos: CameraPos, config: &RenderConfig) -> Camera {\n\n let mut camera = match pos {\n\n CameraPos::Center => Camera::new(scene.center(), Quaternion::one()),\n\n CameraPos::Offset => Camera::new(\n\n scene.center() + scene.size() * Vector3::new(0.0, 0.0, 1.0),\n\n Quaternion::one(),\n\n ),\n\n // Normalize the rotation because its magnitude is probably slightly off\n\n CameraPos::Defined(pos, rot) => Camera::new(pos, rot.normalize()),\n\n };\n\n camera.set_scale(scene.size());\n\n camera.update_viewport(config.dimensions());\n\n camera\n\n}\n\n\n", "file_path": "src/load.rs", "rank": 56, "score": 98349.29084142075 }, { "content": "#[derive(Debug)]\n\nstruct StopwatchNode {\n\n name: String,\n\n duration: SumAccumulator<Duration>,\n\n children: Vec<usize>,\n\n}\n\n\n\nimpl StopwatchNode {\n\n fn new(name: &str) -> Self {\n\n Self {\n\n name: name.to_string(),\n\n duration: SumAccumulator::new(),\n\n children: Vec::new(),\n\n }\n\n }\n\n}\n\n\n\npub struct Stopwatch {\n\n name: String,\n\n start: Option<Instant>,\n\n duration: SumAccumulator<Duration>,\n", "file_path": "src/statistics.rs", "rank": 57, "score": 97896.15203221273 }, { "content": "struct SceneLibrary {\n\n scene_map: HashMap<String, SceneInfo>,\n\n key_map: HashMap<VirtualKeyCode, String>,\n\n}\n\n\n\nimpl SceneLibrary {\n\n fn new() -> SceneLibrary {\n\n SceneLibrary {\n\n scene_map: HashMap::new(),\n\n key_map: HashMap::new(),\n\n }\n\n }\n\n\n\n fn add_scene(\n\n &mut self,\n\n name: String,\n\n path: PathBuf,\n\n camera_pos: CameraPos,\n\n key: Option<VirtualKeyCode>,\n\n ) {\n", "file_path": "src/load.rs", "rank": 58, "score": 97466.10064386953 }, { "content": "struct SceneStatistics {\n\n scene: String,\n\n timers: Vec<(Timer, usize)>,\n\n active_timers: Vec<usize>,\n\n ray_count: usize,\n\n n_tris: usize,\n\n bvh_size: usize,\n\n}\n\n\n\nimpl SceneStatistics {\n\n fn new(name: &str) -> SceneStatistics {\n\n SceneStatistics {\n\n scene: name.to_string(),\n\n timers: Vec::new(),\n\n active_timers: Vec::new(),\n\n ray_count: 0,\n\n n_tris: 0,\n\n bvh_size: 0,\n\n }\n\n }\n", "file_path": "src/stats.rs", "rank": 59, "score": 97466.10064386953 }, { "content": "struct SceneInfo {\n\n path: PathBuf,\n\n camera_pos: CameraPos,\n\n}\n\n\n", "file_path": "src/load.rs", "rank": 60, "score": 97466.10064386953 }, { "content": "/// Get the area pdf of scattering v1 -> v2 -> v3\n\n/// Return None if pdf is a delta distribution\n\npub fn pdf_scatter(v1: &dyn Vertex, v2: &SurfaceVertex, v3: &dyn Vertex) -> Option<Float> {\n\n if v2.delta_dir() {\n\n return None;\n\n }\n\n let (wo, _) = dir_and_dist(v2, v1);\n\n let (wi, dist) = dir_and_dist(v2, v3);\n\n let pdf_dir = v2.isect.pdf(wo, wi);\n\n Some(sample::to_area_pdf(\n\n pdf_dir,\n\n dist.powi(2),\n\n v3.cos_g(wi).abs(),\n\n ))\n\n}\n\n\n", "file_path": "src/pt_renderer/tracers/bdpt/vertex.rs", "rank": 61, "score": 97393.04758323113 }, { "content": "pub fn print_and_save(path: &Path) {\n\n let table = stats!().table();\n\n table.printstd();\n\n let mut stats_file = File::create(path).unwrap();\n\n table.print(&mut stats_file).unwrap();\n\n}\n\n\n", "file_path": "src/stats.rs", "rank": 62, "score": 96566.1760431984 }, { "content": "pub fn path_trace<'a>(\n\n mut ray: Ray,\n\n scene: &'a Scene,\n\n flash: &dyn Light,\n\n config: &RenderConfig,\n\n node_stack: &mut Vec<(&'a BvhNode, Float)>,\n\n) -> Color {\n\n let mut c = Color::black();\n\n let mut beta = Color::white();\n\n let mut bounce = 0;\n\n let mut specular_bounce = false;\n\n while let Some(hit) = scene.intersect(&mut ray, node_stack) {\n\n let isect = hit.interaction(config);\n\n if bounce == 0 || specular_bounce {\n\n c += beta * isect.le(-ray.dir);\n\n }\n\n let (le, mut shadow_ray, light_pdf) = sample_light(&isect, scene, flash, config);\n\n let bsdf = isect.bsdf(-ray.dir, shadow_ray.dir, PathType::Camera);\n\n if !bsdf.is_black() && !scene.intersect_shadow(&mut shadow_ray, node_stack) {\n\n let cos_t = isect.cos_s(shadow_ray.dir).abs();\n", "file_path": "src/pt_renderer/tracers/path_tracer.rs", "rank": 63, "score": 95274.66400348584 }, { "content": "pub trait Vertex: std::fmt::Debug {\n\n /// Get the position of the vertex\n\n fn pos(&self) -> Point3<Float>;\n\n\n\n /// Get the shadow ray origin for dir\n\n fn shadow_origin(&self, dir: Vector3<Float>) -> Point3<Float>;\n\n\n\n /// Geometric cosine\n\n fn cos_g(&self, dir: Vector3<Float>) -> Float;\n\n\n\n /// Shading cosine\n\n fn cos_s(&self, dir: Vector3<Float>) -> Float;\n\n\n\n /// Is the directional distribution a delta distribution\n\n fn delta_dir(&self) -> bool;\n\n\n\n /// Evaluate the throughput for a path continuing in dir\n\n fn path_throughput(&self, dir: Vector3<Float>) -> Color;\n\n\n\n /// Connect vertex to a surface vertex.\n", "file_path": "src/pt_renderer/tracers/bdpt/vertex.rs", "rank": 64, "score": 93264.4672980631 }, { "content": "pub fn time(name: &str) -> TimerHandle {\n\n current_scene!().start_timer(name)\n\n}\n\n\n", "file_path": "src/stats.rs", "rank": 65, "score": 91898.4409298618 }, { "content": "pub trait IntoArray {\n\n type Array;\n\n fn into_array(self) -> Self::Array;\n\n}\n\n\n", "file_path": "src/float.rs", "rank": 66, "score": 90848.28355434258 }, { "content": "fn dir_and_dist(from: &dyn Vertex, to: &dyn Vertex) -> (Vector3<Float>, Float) {\n\n let to_next = to.pos() - from.pos();\n\n let dist = to_next.magnitude();\n\n let dir = to_next / dist;\n\n (dir, dist)\n\n}\n\n\n", "file_path": "src/pt_renderer/tracers/bdpt/vertex.rs", "rank": 67, "score": 90383.0960504936 }, { "content": "pub fn lowercase_extension(path: &Path) -> Option<String> {\n\n let ext = path.extension()?;\n\n let s = ext.to_str()?;\n\n Some(s.to_lowercase())\n\n}\n", "file_path": "src/util.rs", "rank": 68, "score": 87693.91098839548 }, { "content": "fn normal_to_pixel(n: Vector3<Float>) -> Rgb<u8> {\n\n let vec = (0.5 * n).add_element_wise(0.5);\n\n color::vector_to_pixel(vec)\n\n}\n\n\n", "file_path": "src/texture/normal_map.rs", "rank": 69, "score": 87399.29150463003 }, { "content": "pub trait FromArray: IntoArray {\n\n fn from_array(array: Self::Array) -> Self;\n\n}\n\n\n\nimpl IntoArray for Matrix4<Float> {\n\n type Array = [[f32; 4]; 4];\n\n\n\n fn into_array(self) -> Self::Array {\n\n [\n\n self.x.into_array(),\n\n self.y.into_array(),\n\n self.z.into_array(),\n\n self.w.into_array(),\n\n ]\n\n }\n\n}\n\n\n\nimpl IntoArray for Vector4<Float> {\n\n type Array = [f32; 4];\n\n\n", "file_path": "src/float.rs", "rank": 70, "score": 86247.47827397194 }, { "content": "/// Parse a string from the split input line\n\nfn parse_string(split_line: &mut SplitWhitespace) -> Option<String> {\n\n let string = split_line.next()?;\n\n Some(string.to_string())\n\n}\n\n\n", "file_path": "src/obj_load.rs", "rank": 71, "score": 85363.49429186777 }, { "content": "/// MTL bump map might refer to bump map or normal map.\n\n/// Normal maps are returned as is and bump maps are converted to normal maps.\n\npub fn load_normal_map(path: &Path) -> NormalMap {\n\n use image::DynamicImage::*;\n\n\n\n let image = super::load_image(path).unwrap();\n\n let map = match image {\n\n ImageLuma8(map) => bump_to_normal(&map),\n\n ImageLumaA8(_) => bump_to_normal(&image.to_luma8()),\n\n _ => {\n\n let rgb_image = image.to_rgb8();\n\n if is_grayscale(&rgb_image) {\n\n println!(\"Found non-grayscale bump map {:?}\", path);\n\n bump_to_normal(&image.to_luma8())\n\n } else {\n\n rgb_image\n\n }\n\n }\n\n };\n\n // TODO: implement proper caching for converted maps\n\n // if let Some(name) = path.file_name() {\n\n // let mut s = name.to_str().unwrap().to_string();\n\n // s.insert_str(0, \"to_normal_\");\n\n // let save_path = path.with_file_name(s).with_extension(\"png\");\n\n // map.save(&save_path).unwrap();\n\n // println!(\"saved {:?}\", save_path);\n\n // }\n\n NormalMap { map }\n\n}\n\n\n", "file_path": "src/texture/normal_map.rs", "rank": 72, "score": 84640.77925334487 }, { "content": "#[rustfmt::skip]\n\npub fn bump_to_normal(bump: &GrayImage) -> RgbImage {\n\n let w = bump.width();\n\n let h = bump.height();\n\n let mut nm = RgbImage::new(w, h);\n\n for y in 0..h {\n\n for x in 0..w {\n\n // Wrapping access to the offset pixels\n\n let offset = |dx: i32, dy: i32| {\n\n let i = ((x as i32) + dx).rem_euclid(w as i32) as u32;\n\n let j = ((y as i32) + dy).rem_euclid(h as i32) as u32;\n\n bump.get_color(i, j)\n\n };\n\n // Use sobel filters to compute the gradient\n\n // [1, 0, -1] [ 1, 2, 1]\n\n // [2, 0, -2] [ 0, 0, 0]\n\n // [1, 0, -1], [-1, -2, -1]\n\n let dx = offset(-1, 1) + 2.0 * offset(-1, 0) + offset(-1, -1)\n\n - offset(1, 1) - 2.0 * offset(1, 0) - offset(1, -1);\n\n let dy = offset(1, -1) + 2.0 * offset(0, -1) + offset(-1, -1)\n\n - offset(1, 1) - 2.0 * offset(0, 1) - offset(-1, 1);\n", "file_path": "src/texture/normal_map.rs", "rank": 73, "score": 84637.41716307536 }, { "content": "/// Parse a path from the split input line\n\nfn parse_path(split_line: &mut SplitWhitespace) -> Option<PathBuf> {\n\n let path_str = split_line.next()?;\n\n Some(str_to_path(path_str))\n\n}\n\n\n", "file_path": "src/obj_load.rs", "rank": 74, "score": 83815.42497751412 }, { "content": "/// Parse a texture ignoring the potential options\n\nfn parse_texture(split_line: &mut SplitWhitespace) -> Option<PathBuf> {\n\n let mut next_item = split_line.next();\n\n while let Some(next) = next_item {\n\n // Ignore potential switches\n\n // TODO: handle more switches\n\n // TODO: handle switches properly\n\n match next {\n\n \"-bm\" => next_item = split_line.nth(1),\n\n path_str => return Some(str_to_path(path_str)),\n\n }\n\n }\n\n None\n\n}\n\n\n", "file_path": "src/obj_load.rs", "rank": 75, "score": 83815.42497751412 }, { "content": "fn offline_render(scenes: &[&str], tag: &str, output_dir: &Path, config: RenderConfig) {\n\n let tag = if tag.is_empty() {\n\n tag.to_string()\n\n } else {\n\n format!(\"_{}\", tag)\n\n };\n\n let root_dir = PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"));\n\n let output_dir = root_dir.join(output_dir);\n\n std::fs::create_dir_all(output_dir.clone()).unwrap();\n\n let time_stamp = Local::now().format(\"%F_%H%M%S\").to_string();\n\n\n\n // Initialize an OpenGL context that is needed for post-processing\n\n let events_loop = glium::glutin::event_loop::EventLoop::new();\n\n // Preferably this wouldn't need use a window at all but alas this is the closest I have gotten.\n\n // There exists HeadlessContext but that still pops up a window (atleast on Windows).\n\n // TODO: Maybe change this such that the window displays the current render?\n\n let window = glium::glutin::window::WindowBuilder::new()\n\n .with_inner_size(glium::glutin::dpi::LogicalSize::new(0.0, 0.0))\n\n .with_visible(false)\n\n .with_decorations(false)\n", "file_path": "src/main.rs", "rank": 76, "score": 83087.8924068092 }, { "content": "fn cpu_scene(path: &Path, camera_pos: CameraPos, config: &RenderConfig) -> (Arc<Scene>, Camera) {\n\n let scene = SceneBuilder::new(config).build(path);\n\n let camera = initialize_camera(&scene, camera_pos, config);\n\n (scene, camera)\n\n}\n\n\n", "file_path": "src/load.rs", "rank": 77, "score": 82833.11797303005 }, { "content": "fn bilinear_interp<T, I>(image: &I, tex_coords: Point2<Float>) -> T\n\nwhere\n\n T: std::ops::Mul<Float, Output = T> + std::ops::Add<Output = T>,\n\n I: GetColor<T> + GenericImage,\n\n{\n\n let (width, height) = image.dimensions();\n\n let x = tex_coords.x.rem_euclid(1.0) * (width - 1).to_float();\n\n let y = (1.0 - tex_coords.y.rem_euclid(1.0)) * (height - 1).to_float();\n\n let x_fract = x.fract();\n\n let y_fract = y.fract();\n\n // Make sure that pixel coordinates don't overflow\n\n let (left, right) = if x >= (width - 1).to_float() {\n\n (width - 1, width - 1)\n\n } else {\n\n (x.floor() as u32, x.ceil() as u32)\n\n };\n\n let (top, bottom) = if y >= (height - 1).to_float() {\n\n (height - 1, height - 1)\n\n } else {\n\n (y.floor() as u32, y.ceil() as u32)\n", "file_path": "src/texture.rs", "rank": 78, "score": 80212.76587403635 }, { "content": "fn gpu_scene<F: Facade>(\n\n facade: &F,\n\n path: &Path,\n\n camera_pos: CameraPos,\n\n config: &RenderConfig,\n\n) -> (Arc<Scene>, GPUScene, Camera) {\n\n let (scene, camera) = cpu_scene(path, camera_pos, config);\n\n let gpu_scene = scene.upload_data(facade);\n\n (scene, gpu_scene, camera)\n\n}\n\n\n", "file_path": "src/load.rs", "rank": 79, "score": 79961.35323058802 }, { "content": "fn trace_normals<'a>(\n\n mut ray: Ray,\n\n scene: &'a Scene,\n\n config: &RenderConfig,\n\n node_stack: &mut Vec<(&'a BvhNode, Float)>,\n\n forward_only: bool,\n\n) -> Color {\n\n let mut c = Color::black();\n\n if let Some(hit) = scene.intersect(&mut ray, node_stack) {\n\n let isect = hit.interaction(config);\n\n if !forward_only || isect.ns.dot(ray.dir) > 0.0 {\n\n c = Color::from_normal(isect.ns);\n\n }\n\n }\n\n c\n\n}\n", "file_path": "src/pt_renderer/tracers/debug.rs", "rank": 80, "score": 79467.64306876871 }, { "content": "/// Load materials from the material library to a map\n\npub fn load_matlib(matlib_path: &Path) -> Result<HashMap<String, Material>, Box<dyn Error>> {\n\n let mut materials = HashMap::new();\n\n let mut current_material: Option<Material> = None;\n\n let matlib_dir = matlib_path\n\n .parent()\n\n .ok_or(\"Couldn't get material directory\")?;\n\n let matlib_file = File::open(matlib_path)?;\n\n let matlib_reader = BufReader::new(matlib_file);\n\n for line in matlib_reader.lines() {\n\n let line = line.unwrap();\n\n let mut split_line = line.split_whitespace();\n\n // Find the keyword of the line\n\n if let Some(key) = split_line.next().map(str::to_lowercase) {\n\n if key == \"newmtl\" {\n\n if let Some(material) = current_material {\n\n materials.insert(material.name.clone(), material);\n\n }\n\n let material_name = parse_string(&mut split_line)\n\n .ok_or(\"Tried to define a material with no name\")?;\n\n current_material = Some(Material::new(&material_name));\n", "file_path": "src/obj_load.rs", "rank": 81, "score": 67763.11025302233 }, { "content": "struct Statistics {\n\n name: String,\n\n nodes: Vec<StopwatchNode>,\n\n node_map: HashMap<String, usize>,\n\n}\n\n\n\nimpl Statistics {\n\n fn new(name: &str) -> Self {\n\n let mut stats = Self::empty(name);\n\n let total = stats.add_stopwatch(\"Total\", None);\n\n let load = stats.add_stopwatch(\"Load\", Some(total));\n\n stats.add_stopwatch(\"Loab obj\", Some(load));\n\n stats.add_stopwatch(\"Bvh\", Some(load));\n\n stats.add_stopwatch(\"Render\", Some(total));\n\n stats\n\n }\n\n\n\n fn empty(name: &str) -> Self {\n\n Statistics {\n\n name: name.to_string(),\n", "file_path": "src/statistics.rs", "rank": 82, "score": 65275.811090260046 }, { "content": "struct Statistics {\n\n scene_stats: Vec<SceneStatistics>,\n\n}\n\n\n\nimpl Statistics {\n\n fn new() -> Statistics {\n\n Statistics {\n\n scene_stats: Vec::new(),\n\n }\n\n }\n\n\n\n fn new_scene(&mut self, name: &str) {\n\n self.scene_stats.push(SceneStatistics::new(name));\n\n }\n\n\n\n fn current(&mut self) -> Option<&mut SceneStatistics> {\n\n self.scene_stats.iter_mut().last()\n\n }\n\n\n\n fn table(&self) -> Table {\n", "file_path": "src/stats.rs", "rank": 83, "score": 65275.811090260046 }, { "content": "#[allow(dead_code)]\n\n#[derive(Clone, Copy)]\n\nenum CameraPos {\n\n Center,\n\n Offset,\n\n Defined(Point3<Float>, Quaternion<Float>),\n\n}\n\n\n", "file_path": "src/load.rs", "rank": 84, "score": 64298.61510911939 }, { "content": "#[derive(Clone, Copy, Debug)]\n\nstruct BaseColor {\n\n color: Vector3<Float>,\n\n}\n\n\n\nimpl BaseColor {\n\n fn new(r: Float, g: Float, b: Float) -> Self {\n\n Self {\n\n color: Vector3::new(r, g, b),\n\n }\n\n }\n\n\n\n fn black() -> Self {\n\n Self::new(0.0, 0.0, 0.0)\n\n }\n\n\n\n fn white() -> Self {\n\n Self::new(1.0, 1.0, 1.0)\n\n }\n\n\n\n fn from_pixel(pixel: image::Rgb<u8>) -> Self {\n", "file_path": "src/color.rs", "rank": 85, "score": 63738.75606340599 }, { "content": "#[derive(Clone, Debug)]\n\nstruct Ggx {\n\n alpha: Float,\n\n}\n\n\n\n// TODO: maybe just keep alpha^2\n\nimpl Ggx {\n\n fn from_exponent(exponent: Float) -> Self {\n\n // Specular exponent to alpha conversion from\n\n // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n\n Self {\n\n alpha: (2.0 / (exponent + 2.0)).sqrt(),\n\n }\n\n }\n\n\n\n fn d_wh(&self, wh: Vector3<Float>) -> Float {\n\n let cos2_t = util::cos2_t(wh);\n\n let a2 = self.alpha.powi(2);\n\n let denom = consts::PI * (cos2_t * (a2 - 1.0) + 1.0).powi(2);\n\n a2 / denom\n\n }\n", "file_path": "src/bsdf/microfacet.rs", "rank": 86, "score": 63734.694556189774 }, { "content": "enum PTResult {\n\n Block(Rect, Vec<f32>),\n\n Splat(Point2<u32>, [f32; 3]),\n\n}\n\n\n\npub struct PTRenderer {\n\n image: TracedImage,\n\n result_rx: Receiver<PTResult>,\n\n message_txs: Vec<Sender<()>>,\n\n thread_handles: Vec<JoinHandle<()>>,\n\n}\n\n\n\nimpl PTRenderer {\n\n pub fn start_render<F: Facade>(\n\n facade: &F,\n\n scene: &Arc<Scene>,\n\n camera: &Camera,\n\n config: &RenderConfig,\n\n ) -> Self {\n\n stats::start_render();\n", "file_path": "src/pt_renderer.rs", "rank": 87, "score": 62873.29061515244 }, { "content": "#[derive(Default)]\n\nstruct ParseState {\n\n /// Paths to the material libraries defined in the object file\n\n mat_libs: Vec<PathBuf>,\n\n /// Group that is currently active\n\n current_group: Option<Range>,\n\n /// Smoothing group that is currently active\n\n current_smoothing_group: Option<u32>,\n\n /// Material that is currently active\n\n current_material: Option<Range>,\n\n}\n\n\n\nimpl ParseState {\n\n fn new() -> ParseState {\n\n ParseState {\n\n ..Default::default()\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/obj_load.rs", "rank": 88, "score": 62314.03607113307 }, { "content": "struct Visualizer {\n\n shader: glium::Program,\n\n vertex_buffer: VertexBuffer<RawVertex>,\n\n index_buffer: IndexBuffer<u32>,\n\n tone_map: bool,\n\n}\n\n\n\nimpl Visualizer {\n\n fn new<F: Facade>(facade: &F, config: &RenderConfig) -> Self {\n\n let vertices = vec![\n\n RawVertex {\n\n pos: [-1.0, -1.0, 0.0],\n\n normal: [0.0, 0.0, 0.0],\n\n tex_coords: [0.0, 0.0],\n\n },\n\n RawVertex {\n\n pos: [1.0, -1.0, 0.0],\n\n normal: [0.0, 0.0, 0.0],\n\n tex_coords: [1.0, 0.0],\n\n },\n", "file_path": "src/pt_renderer/traced_image.rs", "rank": 89, "score": 61010.76173559785 }, { "content": "// TODO: add comparison mode\n\nfn main() {\n\n match std::env::args().nth(1).as_deref() {\n\n Some(\"hq\") => high_quality(),\n\n Some(\"pt\") => high_quality_pt(),\n\n Some(\"comp\") => compare(),\n\n Some(\"b\") => benchmark(\"bdpt\", RenderConfig::bdpt_benchmark()),\n\n Some(_) => benchmark(\"\", RenderConfig::benchmark()),\n\n None => online_render(),\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 90, "score": 56377.857047138 }, { "content": "fn compare() {\n\n let scenes = [\n\n \"cornell-sphere\",\n\n \"cornell-glossy\",\n\n \"cornell-water\",\n\n \"indirect\",\n\n \"conference\",\n\n \"sponza\",\n\n ];\n\n let mut config = RenderConfig::benchmark();\n\n config.samples_per_dir *= 4;\n\n config.width /= 2;\n\n config.height /= 2;\n\n let output_dir = PathBuf::from(\"results\").join(\"compare\");\n\n offline_render(&scenes, \"pt\", &output_dir, config);\n\n config = RenderConfig::bdpt_benchmark();\n\n config.samples_per_dir *= 4;\n\n config.width /= 2;\n\n config.height /= 2;\n\n offline_render(&scenes, \"bdpt\", &output_dir, config.clone());\n\n config.mis = false;\n\n offline_render(&scenes, \"no_mis\", &output_dir, config);\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 91, "score": 56377.857047138 }, { "content": "pub trait Zero {\n\n fn zero() -> Self;\n\n}\n\n\n\nimpl Zero for Duration {\n\n fn zero() -> Duration {\n\n Duration::new(0, 0)\n\n }\n\n}\n", "file_path": "src/statistics/accumulator.rs", "rank": 92, "score": 55957.12224628756 }, { "content": "/// Trait for handling local light transport.\n\n/// Directions should both point away from the intersection.\n\n/// Directions should be given in a surface local coordinate system,\n\n/// where (0, 0, 1) is the normal pointing outwards\n\npub trait BsdfTrait {\n\n fn is_specular(&self) -> bool;\n\n /// Evaluate reflected radiance\n\n fn brdf(&self, wo: Vector3<Float>, wi: Vector3<Float>) -> Color;\n\n /// Evaluate transmitted radiance\n\n fn btdf(&self, wo: Vector3<Float>, wi: Vector3<Float>, path_type: PathType) -> Color;\n\n /// Evaluate the pdf\n\n fn pdf(&self, wo: Vector3<Float>, wi: Vector3<Float>) -> Float;\n\n /// Sample the distribution\n\n fn sample(\n\n &self,\n\n wo: Vector3<Float>,\n\n path_type: PathType,\n\n ) -> Option<(Color, Vector3<Float>, Float)>;\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub enum BSDF {\n\n Fbr(FresnelBlendBRDF),\n\n Lr(LambertianBRDF),\n", "file_path": "src/bsdf.rs", "rank": 93, "score": 55957.12224628756 }, { "content": "/// Scattering model over the whole surface\n\npub trait ScatteringT {\n\n /// Get the local scattering functions\n\n fn local(&self, tex_coords: Point2<Float>) -> BSDF;\n\n /// The texture to use for preview rendering\n\n fn preview_texture(&self) -> &Texture;\n\n}\n\n\n\n#[derive(Debug)]\n\n#[allow(dead_code)]\n\npub enum Scattering {\n\n DR(DiffuseReflection),\n\n GB(GlossyBlend),\n\n GR(GlossyReflection),\n\n GT(GlossyTransmission),\n\n SR(SpecularReflection),\n\n ST(SpecularTransmission),\n\n}\n\n\n", "file_path": "src/scattering.rs", "rank": 94, "score": 55957.12224628756 }, { "content": "fn high_quality() {\n\n // TODO: Add command line switches to select scenes and config settings\n\n let scenes = [\n\n // \"cornell-sphere\",\n\n // \"cornell-glossy\",\n\n // \"cornell-water\",\n\n // \"indirect\",\n\n \"conference\",\n\n // \"sponza\",\n\n ];\n\n let tag = \"hq\";\n\n let config = RenderConfig::high_quality();\n\n let output_dir = PathBuf::from(\"results\").join(\"hq\");\n\n offline_render(&scenes, tag, &output_dir, config);\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 95, "score": 54888.50166648599 }, { "content": "fn online_render() {\n\n let mut config = RenderConfig::bdpt();\n\n let events_loop = glium::glutin::event_loop::EventLoop::new();\n\n let window = glium::glutin::window::WindowBuilder::new()\n\n .with_inner_size(config.dimensions())\n\n .with_resizable(false); // TODO: enable resizing\n\n let context = glium::glutin::ContextBuilder::new().with_depth_buffer(24);\n\n let display =\n\n glium::Display::new(window, context, &events_loop).expect(\"Failed to create display\");\n\n\n\n let (mut scene, mut gpu_scene, mut camera) =\n\n load::gpu_scene_from_key(&display, VirtualKeyCode::Key1, &config).unwrap();\n\n let gl_renderer = GLRenderer::new(&display);\n\n let mut pt_renderer: Option<PTRenderer> = None;\n\n\n\n let mut input = InputState::new();\n\n let mut last_frame = Instant::now();\n\n\n\n events_loop.run(move |event, _window_target, control_flow| {\n\n let mut target = display.draw();\n", "file_path": "src/main.rs", "rank": 96, "score": 54888.50166648599 }, { "content": "fn high_quality_pt() {\n\n // TODO: Add command line switches to select scenes and config settings\n\n let scenes = [\n\n // \"cornell-sphere\",\n\n // \"cornell-glossy\",\n\n // \"cornell-water\",\n\n // \"indirect\",\n\n \"conference\",\n\n // \"sponza\",\n\n ];\n\n let tag = \"pt_hq\";\n\n let config = RenderConfig::high_quality_pt();\n\n let output_dir = PathBuf::from(\"results\").join(\"hq\");\n\n offline_render(&scenes, tag, &output_dir, config);\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 97, "score": 53523.19133873566 }, { "content": "/// Parse a polygon from the split input line\n\nfn parse_polygon(\n\n split_line: &mut SplitWhitespace,\n\n obj: &Object,\n\n state: &ParseState,\n\n) -> Option<Polygon> {\n\n let mut polygon = Polygon::new(state);\n\n for item in split_line {\n\n let mut index_vertex = IndexVertex::new();\n\n for (i, num) in item.split('/').enumerate() {\n\n if i >= 3 {\n\n println!(\"Vertex with more than three properties\");\n\n break;\n\n }\n\n if !num.is_empty() {\n\n let num: isize = num.parse().ok()?;\n\n if num < 0 {\n\n match i {\n\n 0 => index_vertex.pos_i = (obj.positions.len() as isize + num) as usize,\n\n 1 => {\n\n index_vertex.tex_i =\n", "file_path": "src/obj_load.rs", "rank": 98, "score": 53523.19133873566 }, { "content": "pub trait Intersect<'a, H> {\n\n fn intersect(&'a self, ray: &Ray) -> Option<H>;\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Ray {\n\n pub orig: Point3<Float>,\n\n pub dir: Vector3<Float>,\n\n pub length: Float,\n\n // For more efficient ray box intersections\n\n pub reciprocal_dir: Vector3<Float>,\n\n pub neg_dir: [bool; 3],\n\n}\n\n\n\nimpl Ray {\n\n fn new(orig: Point3<Float>, dir: Vector3<Float>, length: Float) -> Ray {\n\n let reciprocal_dir = 1.0 / dir;\n\n let neg_dir = [dir.x < 0.0, dir.y < 0.0, dir.z < 0.0];\n\n Ray {\n\n orig,\n", "file_path": "src/intersect.rs", "rank": 99, "score": 52575.04899843107 } ]
Rust
core/src/service/file_service.rs
lockbook/lockbook
2aac315bad5989617308311d92e52bf82679d919
use sha2::{Digest, Sha256}; use uuid::Uuid; use crate::model::state::Config; use crate::repo::document_repo; use crate::repo::file_metadata_repo; use crate::repo::{account_repo, local_changes_repo}; use crate::service::file_compression_service; use crate::service::file_encryption_service; use crate::CoreError; use lockbook_crypto::clock_service; use lockbook_models::crypto::DecryptedDocument; use lockbook_models::file_metadata::FileType::{Document, Folder}; use lockbook_models::file_metadata::{FileMetadata, FileType}; use std::fs::OpenOptions; use std::io::Write; use std::path::Path; pub fn create( config: &Config, name: &str, parent: Uuid, file_type: FileType, ) -> Result<FileMetadata, CoreError> { if name.is_empty() { return Err(CoreError::FileNameEmpty); } if name.contains('/') { return Err(CoreError::FileNameContainsSlash); } let _account = account_repo::get_account(config)?; let parent = file_metadata_repo::maybe_get(config, parent)?.ok_or(CoreError::FileParentNonexistent)?; if parent.file_type == Document { return Err(CoreError::FileNotFolder); } for child in file_metadata_repo::get_children_non_recursively(config, parent.id)? { if file_encryption_service::get_name(config, &child)? == name { return Err(CoreError::PathTaken); } } let new_metadata = file_encryption_service::create_file_metadata(config, name, file_type, parent.id)?; file_metadata_repo::insert(config, &new_metadata)?; local_changes_repo::track_new_file(config, new_metadata.id, clock_service::get_time)?; if file_type == Document { write_document(config, new_metadata.id, &[])?; } Ok(new_metadata) } pub fn write_document(config: &Config, id: Uuid, content: &[u8]) -> Result<(), CoreError> { let _account = account_repo::get_account(config)?; let file_metadata = file_metadata_repo::maybe_get(config, id)?.ok_or(CoreError::FileNonexistent)?; if file_metadata.file_type == Folder { return Err(CoreError::FileNotDocument); } let compressed_content = file_compression_service::compress(content)?; let new_file = file_encryption_service::write_to_document(config, &compressed_content, &file_metadata)?; file_metadata_repo::insert(config, &file_metadata)?; if let Some(old_encrypted) = document_repo::maybe_get(config, id)? { let decrypted = file_encryption_service::read_document(config, &old_encrypted, &file_metadata)?; let decompressed = file_compression_service::decompress(&decrypted)?; let permanent_access_info = file_encryption_service::get_key_for_user(config, id)?; local_changes_repo::track_edit( config, file_metadata.id, &old_encrypted, &permanent_access_info, Sha256::digest(&decompressed).to_vec(), Sha256::digest(content).to_vec(), clock_service::get_time, )?; }; document_repo::insert(config, file_metadata.id, &new_file)?; Ok(()) } pub fn rename_file(config: &Config, id: Uuid, new_name: &str) -> Result<(), CoreError> { if new_name.is_empty() { return Err(CoreError::FileNameEmpty); } if new_name.contains('/') { return Err(CoreError::FileNameContainsSlash); } match file_metadata_repo::maybe_get(config, id)? { None => Err(CoreError::FileNonexistent), Some(mut file) => { if file.id == file.parent { return Err(CoreError::RootModificationInvalid); } let siblings = file_metadata_repo::get_children_non_recursively(config, file.parent)?; for child in siblings { if file_encryption_service::get_name(config, &child)? == new_name { return Err(CoreError::PathTaken); } } let old_file_name = file_encryption_service::get_name(config, &file)?; local_changes_repo::track_rename( config, file.id, &old_file_name, new_name, clock_service::get_time, )?; file.name = file_encryption_service::create_name(config, &file, new_name)?; file_metadata_repo::insert(config, &file)?; Ok(()) } } } pub fn move_file(config: &Config, id: Uuid, new_parent: Uuid) -> Result<(), CoreError> { let _account = account_repo::get_account(config)?; let mut file = file_metadata_repo::maybe_get(config, id)?.ok_or(CoreError::FileNonexistent)?; if file.id == file.parent { return Err(CoreError::RootModificationInvalid); } let parent_metadata = file_metadata_repo::maybe_get(config, new_parent)? .ok_or(CoreError::FileParentNonexistent)?; if parent_metadata.file_type == Document { return Err(CoreError::FileNotFolder); } let siblings = file_metadata_repo::get_children_non_recursively(config, parent_metadata.id)?; let new_name = file_encryption_service::rekey_secret_filename(config, &file, &parent_metadata)?; for child in siblings { if child.name == new_name { return Err(CoreError::PathTaken); } } if file.file_type == FileType::Folder { let children = file_metadata_repo::get_and_get_children_recursively(config, id)?; for child in children { if child.id == new_parent { return Err(CoreError::FolderMovedIntoSelf); } } } let access_key = file_encryption_service::decrypt_key_for_file(config, file.id)?; let new_access_info = file_encryption_service::re_encrypt_key_for_file(config, access_key, parent_metadata.id)?; local_changes_repo::track_move( config, file.id, file.parent, parent_metadata.id, clock_service::get_time, )?; file.parent = parent_metadata.id; file.folder_access_keys = new_access_info; file.name = new_name; file_metadata_repo::insert(config, &file)?; Ok(()) } pub fn read_document(config: &Config, id: Uuid) -> Result<DecryptedDocument, CoreError> { let _account = account_repo::get_account(config)?; let file_metadata = file_metadata_repo::maybe_get(config, id)?.ok_or(CoreError::FileNonexistent)?; if file_metadata.file_type == Folder { return Err(CoreError::FileNotDocument); } let document = document_repo::get(config, id)?; let compressed_content = file_encryption_service::read_document(config, &document, &file_metadata)?; let content = file_compression_service::decompress(&compressed_content)?; Ok(content) } pub fn save_document_to_disk(config: &Config, id: Uuid, location: String) -> Result<(), CoreError> { let document_content = read_document(config, id)?; let mut file = OpenOptions::new() .write(true) .create_new(true) .open(Path::new(&location)) .map_err(CoreError::from)?; file.write_all(document_content.as_slice()) .map_err(CoreError::from) } pub fn delete_document(config: &Config, id: Uuid) -> Result<(), CoreError> { let mut file_metadata = file_metadata_repo::maybe_get(config, id)?.ok_or(CoreError::FileNonexistent)?; if file_metadata.file_type == Folder { return Err(CoreError::FileNotDocument); } let new = if let Some(change) = local_changes_repo::get_local_changes(config, id)? { change.new } else { false }; if !new { file_metadata.deleted = true; file_metadata_repo::insert(config, &file_metadata)?; } else { file_metadata_repo::non_recursive_delete(config, id)?; } document_repo::delete(config, id)?; local_changes_repo::track_delete(config, id, file_metadata.file_type, clock_service::get_time)?; Ok(()) } pub fn delete_folder(config: &Config, id: Uuid) -> Result<(), CoreError> { let file_metadata = file_metadata_repo::maybe_get(config, id)?.ok_or(CoreError::FileNonexistent)?; if file_metadata.id == file_metadata.parent { return Err(CoreError::RootModificationInvalid); } if file_metadata.file_type == Document { return Err(CoreError::FileNotFolder); } local_changes_repo::track_delete(config, id, file_metadata.file_type, clock_service::get_time)?; let files_to_delete = file_metadata_repo::get_and_get_children_recursively(config, id)?; for mut file in files_to_delete { if file.file_type == Document { document_repo::delete(config, file.id)?; } let moved = if let Some(change) = local_changes_repo::get_local_changes(config, file.id)? { change.moved.is_some() } else { false }; if file.id != id && !moved { file_metadata_repo::non_recursive_delete(config, file.id)?; local_changes_repo::delete(config, file.id)?; } else { file.deleted = true; file_metadata_repo::insert(config, &file)?; } } Ok(()) }
use sha2::{Digest, Sha256}; use uuid::Uuid; use crate::model::state::Config; use crate::repo::document_repo; use crate::repo::file_metadata_repo; use crate::repo::{account_repo, local_changes_repo}; use crate::service::file_compression_service; use crate::service::file_encryption_service; use crate::CoreError; use lockbook_crypto::clock_service; use lockbook_models::crypto::DecryptedDocument; use lockbook_models::file_metadata::FileType::{Document, Folder}; use lockbook_models::file_metadata::{FileMetadata, FileType}; use std::fs::OpenOptions; use std::io::Write; use std::path::Path; pub fn create( config: &Config, name: &str, parent: Uuid, file_type: FileType, ) -> Result<FileMetadata, CoreError> { if name.is_empty() { return Err(CoreError::FileNameEmpty); } if name.contains('/') { return Err(CoreError::FileNameContainsSlash); } let _account = account_repo::get_account(config)?; let parent = file_metadata_repo::maybe_get(config, parent)?.ok_or(CoreError::FileParentNonexistent)?; if parent.file_type == Document { return Err(CoreError::FileNotFolder); } for child in file_metadata_repo::get_children_non_recursively(config, parent.id)? { if file_encryption_service::get_name(config, &child)? == name { return Err(CoreError::PathTaken); } } let new_metadata = file_encryption_service::create_file_metadata(config, name, file_type, parent.id)?; file_metadata_repo::insert(config, &new_metadata)?; local_changes_repo::track_new_file(config, new_metadata.id, clock_service::get_time)?; if file_type == Document { write_document(config, new_metadata.id, &[])?; } Ok(new_metadata) } pub fn write_document(config: &Config, id: Uuid, content: &[u8]) -> Result<(), CoreError> { let _account = account_repo::get_account(config)?; let file_metadata = file_metadata_repo::maybe_get(config, id)?.ok_or(CoreError::FileNonexistent)?; if file_metadata.file_type == Folder { return Err(CoreError::FileNotDocument); } let compressed_content = file_compression_service::compress(content)?; let new_file = file_encryption_service::write_to_document(config, &compressed_content, &file_metadata)?; file_metadata_repo::insert(config, &file_metadata)?; if let Some(old_encrypted) = document_repo::maybe_get(config, id)? { let decrypted = file_encryption_service::read_document(config, &old_encrypted, &file_metadata)?; let decompressed = file_compression_service::decompress(&decrypted)?; let permanent_access_info = file_encryption_service::get_key_for_user(config, id)?; local_changes_repo::track_edit( config, file_metadata.id, &old_encrypted, &permanent_access_info, Sha256::digest(&decompressed).to_vec(), Sha256::digest(content).to_vec(), clock_service::get_time, )?; }; document_repo::insert(config, file_metadata.id, &new_file)?; Ok(()) } pub fn rename_file(config: &Config, id: Uuid, new_name: &str) -> Result<(), CoreError> { if new_name.is_empty() { return Err(CoreError::FileNameEmpty); } if new_name.contains('/') { return Err(CoreError::FileNameContai
pub fn move_file(config: &Config, id: Uuid, new_parent: Uuid) -> Result<(), CoreError> { let _account = account_repo::get_account(config)?; let mut file = file_metadata_repo::maybe_get(config, id)?.ok_or(CoreError::FileNonexistent)?; if file.id == file.parent { return Err(CoreError::RootModificationInvalid); } let parent_metadata = file_metadata_repo::maybe_get(config, new_parent)? .ok_or(CoreError::FileParentNonexistent)?; if parent_metadata.file_type == Document { return Err(CoreError::FileNotFolder); } let siblings = file_metadata_repo::get_children_non_recursively(config, parent_metadata.id)?; let new_name = file_encryption_service::rekey_secret_filename(config, &file, &parent_metadata)?; for child in siblings { if child.name == new_name { return Err(CoreError::PathTaken); } } if file.file_type == FileType::Folder { let children = file_metadata_repo::get_and_get_children_recursively(config, id)?; for child in children { if child.id == new_parent { return Err(CoreError::FolderMovedIntoSelf); } } } let access_key = file_encryption_service::decrypt_key_for_file(config, file.id)?; let new_access_info = file_encryption_service::re_encrypt_key_for_file(config, access_key, parent_metadata.id)?; local_changes_repo::track_move( config, file.id, file.parent, parent_metadata.id, clock_service::get_time, )?; file.parent = parent_metadata.id; file.folder_access_keys = new_access_info; file.name = new_name; file_metadata_repo::insert(config, &file)?; Ok(()) } pub fn read_document(config: &Config, id: Uuid) -> Result<DecryptedDocument, CoreError> { let _account = account_repo::get_account(config)?; let file_metadata = file_metadata_repo::maybe_get(config, id)?.ok_or(CoreError::FileNonexistent)?; if file_metadata.file_type == Folder { return Err(CoreError::FileNotDocument); } let document = document_repo::get(config, id)?; let compressed_content = file_encryption_service::read_document(config, &document, &file_metadata)?; let content = file_compression_service::decompress(&compressed_content)?; Ok(content) } pub fn save_document_to_disk(config: &Config, id: Uuid, location: String) -> Result<(), CoreError> { let document_content = read_document(config, id)?; let mut file = OpenOptions::new() .write(true) .create_new(true) .open(Path::new(&location)) .map_err(CoreError::from)?; file.write_all(document_content.as_slice()) .map_err(CoreError::from) } pub fn delete_document(config: &Config, id: Uuid) -> Result<(), CoreError> { let mut file_metadata = file_metadata_repo::maybe_get(config, id)?.ok_or(CoreError::FileNonexistent)?; if file_metadata.file_type == Folder { return Err(CoreError::FileNotDocument); } let new = if let Some(change) = local_changes_repo::get_local_changes(config, id)? { change.new } else { false }; if !new { file_metadata.deleted = true; file_metadata_repo::insert(config, &file_metadata)?; } else { file_metadata_repo::non_recursive_delete(config, id)?; } document_repo::delete(config, id)?; local_changes_repo::track_delete(config, id, file_metadata.file_type, clock_service::get_time)?; Ok(()) } pub fn delete_folder(config: &Config, id: Uuid) -> Result<(), CoreError> { let file_metadata = file_metadata_repo::maybe_get(config, id)?.ok_or(CoreError::FileNonexistent)?; if file_metadata.id == file_metadata.parent { return Err(CoreError::RootModificationInvalid); } if file_metadata.file_type == Document { return Err(CoreError::FileNotFolder); } local_changes_repo::track_delete(config, id, file_metadata.file_type, clock_service::get_time)?; let files_to_delete = file_metadata_repo::get_and_get_children_recursively(config, id)?; for mut file in files_to_delete { if file.file_type == Document { document_repo::delete(config, file.id)?; } let moved = if let Some(change) = local_changes_repo::get_local_changes(config, file.id)? { change.moved.is_some() } else { false }; if file.id != id && !moved { file_metadata_repo::non_recursive_delete(config, file.id)?; local_changes_repo::delete(config, file.id)?; } else { file.deleted = true; file_metadata_repo::insert(config, &file)?; } } Ok(()) }
nsSlash); } match file_metadata_repo::maybe_get(config, id)? { None => Err(CoreError::FileNonexistent), Some(mut file) => { if file.id == file.parent { return Err(CoreError::RootModificationInvalid); } let siblings = file_metadata_repo::get_children_non_recursively(config, file.parent)?; for child in siblings { if file_encryption_service::get_name(config, &child)? == new_name { return Err(CoreError::PathTaken); } } let old_file_name = file_encryption_service::get_name(config, &file)?; local_changes_repo::track_rename( config, file.id, &old_file_name, new_name, clock_service::get_time, )?; file.name = file_encryption_service::create_name(config, &file, new_name)?; file_metadata_repo::insert(config, &file)?; Ok(()) } } }
function_block-function_prefixed
[ { "content": "pub fn decompress(content: &[u8]) -> SharedResult<Vec<u8>> {\n\n let mut decoder = ZlibDecoder::new(content);\n\n let mut result = Vec::<u8>::new();\n\n decoder\n\n .read_to_end(&mut result)\n\n .map_err(|_| SharedErrorKind::Unexpected(\"unexpected decompression error\"))?;\n\n Ok(result)\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/shared/src/compression_service.rs", "rank": 0, "score": 391682.19227896724 }, { "content": "pub fn write_path(c: &Core, path: &str, content: &[u8]) -> Result<(), String> {\n\n let target = c.get_by_path(path).map_err(err_to_string)?;\n\n c.write_document(target.id, content).map_err(err_to_string)\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/test_utils/src/lib.rs", "rank": 1, "score": 356074.9987911555 }, { "content": "pub fn all_document_contents(db: &Core, expected_contents_by_path: &[(&str, &[u8])]) {\n\n let expected_contents_by_path = expected_contents_by_path\n\n .iter()\n\n .map(|&(path, contents)| (path.to_string(), contents.to_vec()))\n\n .collect::<Vec<(String, Vec<u8>)>>();\n\n let actual_contents_by_path = db\n\n .list_paths(Some(DocumentsOnly))\n\n .unwrap()\n\n .iter()\n\n .map(|path| (path.clone(), db.read_document(db.get_by_path(path).unwrap().id).unwrap()))\n\n .collect::<Vec<(String, Vec<u8>)>>();\n\n if !slices_equal_ignore_order(&actual_contents_by_path, &expected_contents_by_path) {\n\n panic!(\n\n \"document contents did not match expectation. expected={:?}; actual={:?}\",\n\n expected_contents_by_path\n\n .into_iter()\n\n .map(|(path, contents)| (path, String::from_utf8_lossy(&contents).to_string()))\n\n .collect::<Vec<(String, String)>>(),\n\n actual_contents_by_path\n\n .into_iter()\n\n .map(|(path, contents)| (path, String::from_utf8_lossy(&contents).to_string()))\n\n .collect::<Vec<(String, String)>>(),\n\n );\n\n }\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/test_utils/src/assert.rs", "rank": 2, "score": 343369.594738445 }, { "content": "pub fn file_name(name: &str) -> SharedResult<()> {\n\n if name.is_empty() {\n\n Err(SharedErrorKind::FileNameEmpty)?;\n\n }\n\n if name.contains('/') {\n\n Err(SharedErrorKind::FileNameContainsSlash)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/shared/src/validate.rs", "rank": 3, "score": 337716.8723655222 }, { "content": "pub fn compress(content: &[u8]) -> SharedResult<Vec<u8>> {\n\n let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());\n\n encoder\n\n .write_all(content)\n\n .map_err(|_| SharedErrorKind::Unexpected(\"unexpected compression error\"))?;\n\n encoder\n\n .finish()\n\n .map_err(|_| SharedErrorKind::Unexpected(\"unexpected compression error\").into())\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/shared/src/compression_service.rs", "rank": 4, "score": 325275.35966352373 }, { "content": "pub fn init(config: &Config) -> Result<(), UnexpectedError> {\n\n let core = FfiCore::init(config)?;\n\n STATE\n\n .write()\n\n .map_err(|err| unexpected_only!(\"{:#?}\", err))?\n\n .replace(core);\n\n Ok(())\n\n}\n\n\n", "file_path": "libs/lb/lb_external_interface/src/static_state.rs", "rank": 5, "score": 300031.69879013393 }, { "content": "pub fn rename_path(c: &Core, path: &str, new_name: &str) -> Result<(), String> {\n\n let target = c.get_by_path(path).map_err(err_to_string)?;\n\n c.rename_file(target.id, new_name).map_err(err_to_string)\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/test_utils/src/lib.rs", "rank": 6, "score": 297655.656347544 }, { "content": "pub fn all_children_ids(core: &Core, id: Uuid, expected_ids: &[Uuid]) {\n\n let mut expected_ids: Vec<Uuid> = expected_ids.to_vec();\n\n let mut actual_ids: Vec<Uuid> = core\n\n .get_children(id)\n\n .unwrap()\n\n .iter()\n\n .map(|f| f.id)\n\n .collect();\n\n\n\n actual_ids.sort();\n\n expected_ids.sort();\n\n if actual_ids != expected_ids {\n\n panic!(\n\n \"ids did not match expectation. expected={:?}; actual={:?}\",\n\n expected_ids, actual_ids\n\n );\n\n }\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/test_utils/src/assert.rs", "rank": 7, "score": 295877.69907163107 }, { "content": "pub fn all_recursive_children_ids(core: &Core, id: Uuid, expected_ids: &[Uuid]) {\n\n let mut expected_ids: Vec<Uuid> = expected_ids.to_vec();\n\n let mut actual_ids: Vec<Uuid> = core\n\n .get_and_get_children_recursively(id)\n\n .unwrap()\n\n .iter()\n\n .map(|f| f.id)\n\n .collect();\n\n\n\n actual_ids.sort();\n\n expected_ids.sort();\n\n if actual_ids != expected_ids {\n\n panic!(\n\n \"ids did not match expectation. expected={:?}; actual={:?}\",\n\n expected_ids, actual_ids\n\n );\n\n }\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/test_utils/src/assert.rs", "rank": 8, "score": 293104.5234703902 }, { "content": "pub fn key_path(writeable_path: &str, key: &Uuid, hmac: &DocumentHmac) -> String {\n\n let hmac = base64::encode_config(hmac, base64::URL_SAFE);\n\n format!(\"{}/{}-{}\", namespace_path(writeable_path), key, hmac)\n\n}\n", "file_path": "libs/lb/lb-rs/libs/shared/src/document_repo.rs", "rank": 9, "score": 287328.52485526295 }, { "content": "pub fn init(config: &Config) -> LbResult<()> {\n\n if config.logs {\n\n let lockbook_log_level = env::var(\"LOG_LEVEL\")\n\n .ok()\n\n .and_then(|s| s.as_str().parse().ok())\n\n .unwrap_or(LevelFilter::DEBUG);\n\n\n\n let subscriber =\n\n tracing_subscriber::Registry::default()\n\n .with(\n\n fmt::Layer::new()\n\n .with_span_events(FmtSpan::ACTIVE)\n\n .with_ansi(config.colored_logs)\n\n .with_target(false)\n\n .with_writer(tracing_appender::rolling::never(\n\n &config.writeable_path,\n\n LOG_FILE,\n\n ))\n\n .with_filter(lockbook_log_level)\n\n .with_filter(filter::filter_fn(|metadata| {\n", "file_path": "libs/lb/lb-rs/src/service/log_service.rs", "rank": 10, "score": 281766.9449120695 }, { "content": "pub fn d_to_subpath(data: &str) -> Subpath<ManipulatorGroupId> {\n\n let mut start = (0.0, 0.0);\n\n let mut subpath: Subpath<ManipulatorGroupId> = Subpath::new(vec![], false);\n\n\n\n for segment in svgtypes::SimplifyingPathParser::from(data) {\n\n let segment = match segment {\n\n Ok(v) => v,\n\n Err(_) => break,\n\n };\n\n\n\n match segment {\n\n svgtypes::SimplePathSegment::MoveTo { x, y } => {\n\n start = (x, y);\n\n }\n\n svgtypes::SimplePathSegment::CurveTo { x1, y1, x2, y2, x, y } => {\n\n let bez = Bezier::from_cubic_coordinates(start.0, start.1, x1, y1, x2, y2, x, y);\n\n subpath.append_bezier(&bez, bezier_rs::AppendType::IgnoreStart);\n\n start = (x, y)\n\n }\n\n svgtypes::SimplePathSegment::LineTo { x, y } => {\n", "file_path": "libs/content/workspace/src/tab/svg_editor/util.rs", "rank": 11, "score": 281742.62192790525 }, { "content": "pub fn file(core: &Core, id: Uuid) -> Res<()> {\n\n let maybe_confirm = Confirm::with_theme(&ColorfulTheme::default())\n\n .with_prompt(format!(\"Are you sure you want to delete '{}'?\", id))\n\n .interact_opt()?;\n\n\n\n if maybe_confirm.unwrap_or(false) {\n\n core.admin_disappear_file(id)?;\n\n\n\n println!(\"File disappeared\");\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "clients/admin/src/disappear.rs", "rank": 12, "score": 281679.7657880423 }, { "content": "pub fn file(core: &Core, id: Uuid) -> Res<()> {\n\n let info = core.admin_file_info(id)?;\n\n println!(\"id:\\t\\t\\t{}\", info.file.id());\n\n println!(\"file_type:\\t\\t{:?}\", info.file.file_type());\n\n println!(\"parent:\\t\\t\\t{}\", info.file.parent());\n\n println!(\n\n \"owner:\\t\\t\\t{}\",\n\n core.admin_get_account_info(AccountIdentifier::PublicKey(info.file.owner().0))?\n\n .username\n\n );\n\n println!(\"explicitly_deleted:\\t{}\", info.file.explicitly_deleted());\n\n println!(\"document_hmac:\\t\\t{}\", info.file.document_hmac().is_some());\n\n println!(\"user_access_keys:\");\n\n for k in info.file.user_access_keys() {\n\n println!(\n\n \"->\\tencrypted_by: {}\",\n\n core.admin_get_account_info(AccountIdentifier::PublicKey(k.encrypted_by))?\n\n .username\n\n );\n\n println!(\n", "file_path": "clients/admin/src/info.rs", "rank": 13, "score": 281679.7657880423 }, { "content": "// todo: use relative path (caller responsibilty?)\n\n// todo: use background thread\n\n// todo: refresh file tree view\n\npub fn import_image(core: &lb_rs::Core, open_file: Uuid, data: &[u8]) -> File {\n\n println!(\"importing image\");\n\n\n\n let file = core\n\n .get_file_by_id(open_file)\n\n .expect(\"get lockbook file for image\");\n\n let siblings = core\n\n .get_children(file.parent)\n\n .expect(\"get lockbook siblings for image\");\n\n\n\n let imports_folder = {\n\n let mut imports_folder = None;\n\n for sibling in siblings {\n\n if sibling.name == \"imports\" {\n\n imports_folder = Some(sibling);\n\n break;\n\n }\n\n }\n\n imports_folder.unwrap_or_else(|| {\n\n core.create_file(\"imports\", file.parent, FileType::Folder)\n", "file_path": "libs/content/workspace/src/tab/mod.rs", "rank": 14, "score": 274147.13333898707 }, { "content": "pub fn find_by_name(core: &CoreIP, name: &str) -> File {\n\n let mut possible_matches = core.list_metadatas().unwrap();\n\n if name == \"root\" {\n\n possible_matches.retain(|meta| meta.parent == meta.id);\n\n } else {\n\n possible_matches.retain(|meta| meta.name == name);\n\n }\n\n if possible_matches.len() > 1 {\n\n eprintln!(\"Multiple matches for a file name found: {}\", name);\n\n } else if possible_matches.is_empty() {\n\n panic!(\"No file matched name: {}\", name);\n\n }\n\n\n\n possible_matches[0].clone()\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/tests/exhaustive_sync/utils.rs", "rank": 15, "score": 273844.97656863276 }, { "content": "pub fn delete(core: &Core, target: Uuid) -> Result<(), CliError> {\n\n ensure_account_and_root(core)?;\n\n\n\n let share = core\n\n .get_pending_shares()?\n\n .into_iter()\n\n .find(|f| f.id == target)\n\n .ok_or_else(|| CliError::from(format!(\"Could not find {target} in pending shares\")))?;\n\n core.delete_pending_share(share.id)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "clients/cli/src/share.rs", "rank": 16, "score": 267223.670607375 }, { "content": "pub fn init(config: &Config) {\n\n let log_level = env::var(\"LOG_LEVEL\")\n\n .ok()\n\n .and_then(|s| s.as_str().parse().ok())\n\n .unwrap_or(LevelFilter::DEBUG);\n\n let subscriber = tracing_subscriber::Registry::default()\n\n // Logger for stdout (local development)\n\n .with(\n\n fmt::Layer::new()\n\n .pretty()\n\n .with_target(false)\n\n .with_filter(log_level)\n\n .with_filter(server_logs()),\n\n )\n\n // Logger for file (verbose and sent to loki)\n\n .with(\n\n fmt::Layer::new()\n\n .with_writer(file_logger(config))\n\n .with_ansi(false)\n\n .with_filter(LevelFilter::DEBUG)\n", "file_path": "server/server/src/loggers.rs", "rank": 17, "score": 264018.9479638075 }, { "content": "fn save_temp_file_contents<P: AsRef<Path>>(core: &Core, id: Uuid, path: P) -> Result<(), CliError> {\n\n let secret = fs::read_to_string(&path)\n\n .map_err(|err| {\n\n CliError::from(format!(\n\n \"could not read from temporary file, not deleting {}, err: {:#?}\",\n\n path.as_ref().display(),\n\n err\n\n ))\n\n })?\n\n .into_bytes();\n\n\n\n core.write_document(id, &secret)?;\n\n Ok(())\n\n}\n", "file_path": "clients/cli/src/edit.rs", "rank": 18, "score": 262829.3186090484 }, { "content": "pub fn move_by_path(c: &Core, src: &str, dest: &str) -> Result<(), String> {\n\n let src = c.get_by_path(src).map_err(err_to_string)?;\n\n let dest = c.get_by_path(dest).map_err(err_to_string)?;\n\n c.move_file(src.id, dest.id).map_err(err_to_string)\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/test_utils/src/lib.rs", "rank": 19, "score": 262621.60598261864 }, { "content": "pub fn doc_repo_get_all(config: &Config) -> Vec<EncryptedDocument> {\n\n let mut docs = vec![];\n\n for file in list_files(config) {\n\n let content = fs::read(file).unwrap();\n\n docs.push(bincode::deserialize(&content).unwrap());\n\n }\n\n docs\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/test_utils/src/lib.rs", "rank": 20, "score": 262384.23522771546 }, { "content": "pub fn all_ids(core: &Core, expected_ids: &[Uuid]) {\n\n let mut expected_ids: Vec<Uuid> = expected_ids.to_vec();\n\n let mut actual_ids: Vec<Uuid> = core\n\n .list_metadatas()\n\n .unwrap()\n\n .iter()\n\n .map(|f| f.id)\n\n .collect();\n\n\n\n actual_ids.sort();\n\n expected_ids.sort();\n\n if actual_ids != expected_ids {\n\n panic!(\n\n \"ids did not match expectation. expected={:?}; actual={:?}\",\n\n expected_ids, actual_ids\n\n );\n\n }\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/test_utils/src/assert.rs", "rank": 21, "score": 256361.60023430546 }, { "content": "pub fn create_release() -> CliResult<()> {\n\n let gh = Github::env();\n\n\n\n let client = ReleaseClient::new(gh.0).unwrap();\n\n\n\n let tag_info = TagInfo {\n\n tag: lb_version(),\n\n message: \"\".to_string(),\n\n object: utils::commit_hash(),\n\n type_tagged: \"commit\".to_string(),\n\n };\n\n\n\n client.create_a_tag(&lb_repo(), &tag_info).unwrap();\n\n\n\n let release_info = CreateReleaseInfo {\n\n tag_name: lb_version(),\n\n target_commitish: None,\n\n name: Some(lb_version()),\n\n body: None,\n\n draft: None,\n\n prerelease: None,\n\n discussion_category_name: None,\n\n generate_release_notes: Some(true),\n\n make_latest: Some(\"true\".to_string()),\n\n };\n\n\n\n client.create_a_release(&lb_repo(), &release_info).unwrap();\n\n Ok(())\n\n}\n", "file_path": "utils/releaser/src/github.rs", "rank": 22, "score": 255422.7654350853 }, { "content": "pub fn path(path: &str) -> SharedResult<()> {\n\n if path.contains(\"//\") || path.is_empty() {\n\n Err(SharedErrorKind::PathContainsEmptyFileName)?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\nimpl<T, Base, Local> LazyTree<T>\n\nwhere\n\n T: StagedTreeLike<Base = Base, Staged = Local>,\n\n Base: TreeLike<F = T::F>,\n\n Local: TreeLike<F = T::F>,\n\n{\n\n pub fn validate(&mut self, owner: Owner) -> SharedResult<()> {\n\n // point checks\n\n self.assert_no_root_changes()?;\n\n self.assert_no_changes_to_deleted_files()?;\n\n self.assert_all_filenames_size_limit()?;\n\n self.assert_all_files_decryptable(owner)?;\n", "file_path": "libs/lb/lb-rs/libs/shared/src/validate.rs", "rank": 23, "score": 254955.7761744251 }, { "content": "pub fn is_supported_image_fmt(ext: &str) -> bool {\n\n // todo see if this list is incomplete\n\n const IMG_FORMATS: [&str; 7] = [\"png\", \"jpeg\", \"jpg\", \"gif\", \"webp\", \"bmp\", \"ico\"];\n\n IMG_FORMATS.contains(&ext)\n\n}\n", "file_path": "libs/content/workspace/src/tab/image_viewer.rs", "rank": 24, "score": 253754.44924470055 }, { "content": "pub fn delete_path(c: &Core, path: &str) -> Result<(), String> {\n\n let target = c.get_by_path(path).map_err(err_to_string)?;\n\n c.delete_file(target.id).map_err(err_to_string)\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/test_utils/src/lib.rs", "rank": 25, "score": 253026.00278026855 }, { "content": "pub fn id_completor(core: &Core, prompt: &str, filter: Option<Filter>) -> CliResult<Vec<String>> {\n\n // todo: potential optimization opportunity inside core\n\n Ok(core\n\n .list_metadatas()?\n\n .into_iter()\n\n .filter(|f| match filter {\n\n Some(Filter::FoldersOnly) => f.is_folder(),\n\n Some(Filter::DocumentsOnly) => f.is_document(),\n\n _ => true,\n\n })\n\n .map(|f| f.id.to_string())\n\n .filter(|cand| cand.starts_with(prompt))\n\n .collect())\n\n}\n\n\n", "file_path": "clients/cli/src/input.rs", "rank": 26, "score": 251029.74562343676 }, { "content": "pub fn main() -> Result<()> {\n\n env_logger::init();\n\n\n\n let instance = unsafe { GetModuleHandleA(None)? };\n\n\n\n let icon_bytes = include_bytes!(\"../lockbook.png\");\n\n let icon = unsafe {\n\n CreateIconFromResourceEx(icon_bytes, true, 0x00030000, 128, 128, LR_DEFAULTCOLOR)\n\n }\n\n .expect(\"create icon\");\n\n\n\n let wc = WNDCLASSEXA {\n\n cbSize: std::mem::size_of::<WNDCLASSEXA>() as u32,\n\n style: CS_HREDRAW | CS_VREDRAW,\n\n lpfnWndProc: Some(handle_messages), // \"Long Pointer to FuNction WiNDows PROCedure\" (message handling callback)\n\n hInstance: instance.into(),\n\n hCursor: unsafe { LoadCursorW(None, IDC_ARROW) }?,\n\n lpszClassName: s!(\"Lockbook\"),\n\n hIcon: icon,\n\n ..Default::default()\n", "file_path": "clients/windows/src/window.rs", "rank": 27, "score": 250344.52752757614 }, { "content": "pub fn calc(text: &str) -> UnicodeSegs {\n\n let mut result = UnicodeSegs::default();\n\n if !text.is_empty() {\n\n result\n\n .grapheme_indexes\n\n .extend(text.grapheme_indices(true).map(|t| DocByteOffset(t.0)));\n\n }\n\n result.grapheme_indexes.push(DocByteOffset(text.len()));\n\n result\n\n}\n\n\n\nimpl UnicodeSegs {\n\n pub fn offset_to_byte(&self, i: DocCharOffset) -> DocByteOffset {\n\n if self.grapheme_indexes.is_empty() && i.0 == 0 {\n\n return DocByteOffset(0);\n\n }\n\n self.grapheme_indexes[i.0]\n\n }\n\n\n\n pub fn range_to_byte(\n", "file_path": "libs/content/workspace/src/tab/markdown_editor/unicode_segs.rs", "rank": 28, "score": 250187.84383503732 }, { "content": "pub fn namespace_path(writeable_path: &str) -> String {\n\n format!(\"{}/documents\", writeable_path)\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/shared/src/document_repo.rs", "rank": 29, "score": 247899.68897149322 }, { "content": "pub fn deserialize_transform(transform: &str) -> [f64; 6] {\n\n for segment in svgtypes::TransformListParser::from(transform) {\n\n let segment = match segment {\n\n Ok(v) => v,\n\n Err(_) => break,\n\n };\n\n if let svgtypes::TransformListToken::Matrix { a, b, c, d, e, f } = segment {\n\n return [a, b, c, d, e, f];\n\n }\n\n }\n\n [1, 0, 0, 1, 0, 0].map(|f| f as f64)\n\n}\n\n\n", "file_path": "libs/content/workspace/src/tab/svg_editor/util.rs", "rank": 30, "score": 247653.225805606 }, { "content": "fn env_or_panic(var_name: &str) -> String {\n\n env::var(var_name).unwrap_or_else(|_| panic!(\"Missing environment variable {}\", var_name))\n\n}\n\n\n", "file_path": "server/server/src/config.rs", "rank": 31, "score": 246813.3201101374 }, { "content": "pub fn test_config() -> Config {\n\n Config { writeable_path: format!(\"/tmp/{}\", Uuid::new_v4()), logs: false, colored_logs: false }\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/test_utils/src/lib.rs", "rank": 32, "score": 244728.5476733242 }, { "content": "pub fn parse_drawing(drawing_bytes: &[u8]) -> LbResult<Drawing> {\n\n // represent an empty string as an empty drawing, rather than returning an error\n\n if drawing_bytes.is_empty() {\n\n return Ok(Drawing::default());\n\n }\n\n let drawing =\n\n serde_json::from_slice::<Drawing>(drawing_bytes).map_err(|err| match err.classify() {\n\n Category::Io => CoreError::Unexpected(String::from(\"json io\")),\n\n Category::Syntax | Category::Data | Category::Eof => CoreError::DrawingInvalid,\n\n })?;\n\n validate(&drawing)?;\n\n Ok(drawing)\n\n}\n\n\n\n#[derive(Deserialize, Debug)]\n\npub enum SupportedImageFormats {\n\n Png,\n\n Jpeg,\n\n Pnm,\n\n Tga,\n", "file_path": "libs/lb/lb-rs/src/model/drawing.rs", "rank": 33, "score": 241952.3209229768 }, { "content": "#[test]\n\nfn concurrent_create_document_then_folder_with_child() {\n\n let c1 = test_core_with_account();\n\n let c2 = another_client(&c1);\n\n c2.sync(None).unwrap();\n\n c1.create_at_path(\"/a.md\").unwrap();\n\n c2.create_at_path(\"/a.md/child/\").unwrap();\n\n\n\n sync_and_assert_stuff(&c1, &c2);\n\n assert::all_paths(&c2, &[\"/\", \"/a.md\", \"/a-1.md/\", \"/a-1.md/child/\"]);\n\n assert::all_document_contents(&c2, &[(\"/a.md\", b\"\")]);\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/tests/sync_service_path_conflict_resolution_tests.rs", "rank": 34, "score": 241302.91432368805 }, { "content": "#[test]\n\nfn concurrent_create_folder_with_child_then_document() {\n\n let c1 = test_core_with_account();\n\n let c2 = another_client(&c1);\n\n c2.sync(None).unwrap();\n\n c1.create_at_path(\"/a.md/child/\").unwrap();\n\n c2.create_at_path(\"/a.md\").unwrap();\n\n\n\n sync_and_assert_stuff(&c1, &c2);\n\n assert::all_paths(&c2, &[\"/\", \"/a.md/\", \"/a.md/child/\", \"/a-1.md\"]);\n\n assert::all_document_contents(&c2, &[(\"/a-1.md\", b\"\")]);\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/tests/sync_service_path_conflict_resolution_tests.rs", "rank": 35, "score": 241302.9143236881 }, { "content": "pub fn all_pending_shares(core: &Core, expected_names: &[&str]) {\n\n if expected_names.iter().any(|&path| path.contains('/')) {\n\n panic!(\n\n \"improper call to assert_all_pending_shares; expected_names must not contain with '/'. expected_names={:?}\",\n\n expected_names\n\n );\n\n }\n\n let mut expected_names: Vec<String> = expected_names\n\n .iter()\n\n .map(|&name| String::from(name))\n\n .collect();\n\n let mut actual_names: Vec<String> = core\n\n .get_pending_shares()\n\n .unwrap()\n\n .into_iter()\n\n .map(|f| f.name)\n\n .collect();\n\n actual_names.sort();\n\n expected_names.sort();\n\n if actual_names != expected_names {\n\n panic!(\n\n \"pending share names did not match expectation. expected={:?}; actual={:?}\",\n\n expected_names, actual_names\n\n );\n\n }\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/test_utils/src/assert.rs", "rank": 36, "score": 238600.1913154428 }, { "content": "fn env_or_empty(var_name: &str) -> Option<String> {\n\n match env::var(var_name) {\n\n Ok(var) => Some(var),\n\n Err(_err) => None,\n\n }\n\n}\n", "file_path": "server/server/src/config.rs", "rank": 37, "score": 237837.7808885451 }, { "content": "#[test]\n\nfn create_link_then_move_to_owned_folder_and_create_file_with_conflicting_name_in_prior_parent() {\n\n let mut cores = [vec![test_core_with_account()], vec![test_core_with_account()]];\n\n let new_client = another_client(&cores[1][0]);\n\n cores[1].push(new_client);\n\n let accounts = cores\n\n .iter()\n\n .map(|cores| cores[0].get_account().unwrap())\n\n .collect::<Vec<_>>();\n\n\n\n let grandparent = cores[0][0].create_at_path(\"/grandparent/\").unwrap();\n\n let parent = cores[0][0].create_at_path(\"/grandparent/parent/\").unwrap();\n\n let folder = cores[0][0]\n\n .create_at_path(\"/grandparent/parent/folder/\")\n\n .unwrap();\n\n cores[0][0]\n\n .share_file(grandparent.id, &accounts[1].username, ShareMode::Write)\n\n .unwrap();\n\n cores[0][0]\n\n .share_file(folder.id, &accounts[1].username, ShareMode::Read)\n\n .unwrap();\n", "file_path": "libs/lb/lb-rs/tests/sync_service_concurrent_change_tests.rs", "rank": 38, "score": 236766.08272650125 }, { "content": "fn jstring_to_string(env: &JNIEnv, json: JString, name: &str) -> Result<String, jstring> {\n\n env.get_string(json).map(|ok| ok.into()).map_err(|err| {\n\n string_to_jstring(\n\n env,\n\n translate::<(), Error<()>>(Err(Error::<()>::Unexpected(format!(\n\n \"Could not parse {} jstring: {:?}\",\n\n name, err\n\n )))),\n\n )\n\n })\n\n}\n\n\n", "file_path": "libs/lb/lb_external_interface/src/java_interface.rs", "rank": 39, "score": 231518.96240317397 }, { "content": "pub fn accept(core: &Core, target: Uuid, dest: FileInput) -> CliResult<()> {\n\n ensure_account_and_root(core)?;\n\n\n\n let share = core\n\n .get_pending_shares()?\n\n .into_iter()\n\n .find(|f| f.id == target)\n\n .ok_or_else(|| CliError::from(format!(\"Could not find {target} in pending shares\")))?;\n\n let parent = dest.find(core)?;\n\n\n\n core.create_file(&share.name, parent.id, lb::FileType::Link { target: share.id })\n\n .map_err(|err| CliError::from(format!(\"{:?}\", err)))?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "clients/cli/src/share.rs", "rank": 40, "score": 231383.54575712694 }, { "content": "pub fn node_by_id(root: &mut Element, id: String) -> Option<&mut Element> {\n\n root.children_mut().find(\n\n |e| {\n\n if let Some(id_attr) = e.attr(\"id\") {\n\n id_attr == id\n\n } else {\n\n false\n\n }\n\n },\n\n )\n\n}\n\n\n", "file_path": "libs/content/workspace/src/tab/svg_editor/util.rs", "rank": 41, "score": 228217.1152768529 }, { "content": "pub fn copy(core: &Core, disk: PathBuf, parent: FileInput) -> CliResult<()> {\n\n ensure_account_and_root(core)?;\n\n\n\n let parent = parent.find(core)?.id;\n\n\n\n let total = Cell::new(0);\n\n let nth_file = Cell::new(0);\n\n let update_status = move |status: ImportStatus| match status {\n\n ImportStatus::CalculatedTotal(n_files) => total.set(n_files),\n\n ImportStatus::StartingItem(disk_path) => {\n\n nth_file.set(nth_file.get() + 1);\n\n print!(\"({}/{}) importing: {}... \", nth_file.get(), total.get(), disk_path);\n\n io::stdout().flush().unwrap();\n\n }\n\n ImportStatus::FinishedItem(_meta) => println!(\"done.\"),\n\n };\n\n\n\n core.import_files(&[disk], parent, &update_status)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "clients/cli/src/imex.rs", "rank": 42, "score": 227949.31905481085 }, { "content": "pub fn chop(u: Uuid) -> u64 {\n\n u.as_u64_pair().0\n\n}\n\n\n", "file_path": "libs/lb-fs/src/utils.rs", "rank": 43, "score": 227722.7444711724 }, { "content": "pub fn generate_nonce() -> [u8; 12] {\n\n let mut result = [0u8; 12];\n\n OsRng.fill_bytes(&mut result);\n\n result\n\n}\n\n\n\n#[cfg(test)]\n\nmod unit_tests {\n\n use uuid::Uuid;\n\n\n\n use crate::symkey::{decrypt, encrypt, generate_key};\n\n\n\n #[test]\n\n fn test_generate_encrypt_decrypt() {\n\n let key = generate_key();\n\n let test_value = Uuid::new_v4().to_string();\n\n let encrypted = encrypt(&key, &test_value).unwrap();\n\n let decrypted = decrypt(&key, &encrypted).unwrap();\n\n assert_eq!(test_value, decrypted)\n\n }\n\n}\n", "file_path": "libs/lb/lb-rs/libs/shared/src/symkey.rs", "rank": 44, "score": 225216.81017314672 }, { "content": "#[test]\n\nfn create_document_duplicate_id() {\n\n let core = test_core_with_account();\n\n let account = core.get_account().unwrap();\n\n\n\n let id = core.create_at_path(\"test.md\").unwrap().id;\n\n let doc = core\n\n .in_tx(|s| Ok(s.db.local_metadata.get().get(&id).cloned().unwrap()))\n\n .unwrap();\n\n\n\n core.sync(None).unwrap();\n\n\n\n // create document with same id and key\n\n core.in_tx(|s| {\n\n let result = s\n\n .client\n\n .request(&account, UpsertRequest { updates: vec![FileDiff::new(&doc)] });\n\n assert_matches!(\n\n result,\n\n Err(ApiError::<UpsertError>::Endpoint(UpsertError::OldVersionRequired))\n\n );\n\n Ok(())\n\n })\n\n .unwrap();\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/tests/api_create_file_tests.rs", "rank": 45, "score": 225067.68250173022 }, { "content": "pub fn get_code_version() -> &'static str {\n\n env!(\"CARGO_PKG_VERSION\")\n\n}\n\n\n\npub static DEFAULT_API_LOCATION: &str = \"https://api.prod.lockbook.net\";\n\npub static CORE_CODE_VERSION: &str = env!(\"CARGO_PKG_VERSION\");\n", "file_path": "libs/lb/lb-rs/src/lib.rs", "rank": 46, "score": 225064.33158887678 }, { "content": "#[test]\n\nfn create_document_parent_not_found() {\n\n let core = test_core_with_account();\n\n let account = core.get_account().unwrap();\n\n // create document\n\n let id = core.create_at_path(\"parent/test.md\").unwrap().id;\n\n let doc = core\n\n .in_tx(|s| Ok(s.db.local_metadata.get().get(&id).cloned().unwrap()))\n\n .unwrap();\n\n\n\n core.in_tx(|s| {\n\n let result = s\n\n .client\n\n .request(&account, UpsertRequest { updates: vec![FileDiff::new(&doc)] });\n\n assert_matches!(\n\n result,\n\n Err(ApiError::<UpsertError>::Endpoint(UpsertError::Validation(\n\n ValidationFailure::Orphan(_)\n\n )))\n\n );\n\n Ok(())\n\n })\n\n .unwrap();\n\n}\n", "file_path": "libs/lb/lb-rs/tests/api_create_file_tests.rs", "rank": 47, "score": 225057.31876386507 }, { "content": "pub fn fmt(id: u64) -> String {\n\n Uuid::from_u64_pair(id, 0).to_string()\n\n}\n\n\n", "file_path": "libs/lb-fs/src/utils.rs", "rank": 48, "score": 224359.35261045062 }, { "content": "pub fn username_is_valid(username: &str) -> bool {\n\n !username.is_empty()\n\n && username.len() <= MAX_USERNAME_LENGTH\n\n && username\n\n .to_lowercase()\n\n .chars()\n\n .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())\n\n}\n\n\n", "file_path": "server/server/src/utils.rs", "rank": 49, "score": 224224.16244108975 }, { "content": "pub fn sha_file(file: &str) -> String {\n\n let bytes = fs::read(file).unwrap();\n\n let mut hasher = Sha256::new();\n\n hasher.update(bytes);\n\n let result = hasher.finalize();\n\n hex::encode(result)\n\n}\n\n\n", "file_path": "utils/releaser/src/utils.rs", "rank": 50, "score": 224224.16244108975 }, { "content": "pub fn data_dir() -> Result<String, String> {\n\n match (env::var(\"LOCKBOOK_PATH\"), env::var(\"HOME\"), env::var(\"HOMEPATH\")) {\n\n (Ok(s), _, _) => Ok(s),\n\n (Err(_), Ok(s), _) => Ok(format!(\"{s}/.lockbook\")),\n\n (Err(_), Err(_), Ok(s)) => Ok(format!(\"{s}/.lockbook\")),\n\n _ => Err(\"Unable to determine a Lockbook data directory. Please consider setting the LOCKBOOK_PATH environment variable.\".to_string()),\n\n }\n\n}\n", "file_path": "clients/egui/src/util.rs", "rank": 51, "score": 224172.78803392703 }, { "content": "fn deserialize_id(env: &JNIEnv, json: JString) -> Result<Uuid, jstring> {\n\n let json_string = jstring_to_string(env, json, \"id\")?;\n\n\n\n Uuid::parse_str(&json_string).map_err(|err| {\n\n string_to_jstring(\n\n env,\n\n translate::<(), Error<()>>(Err(Error::<()>::Unexpected(format!(\n\n \"Couldn't deserialize id: {:?}\",\n\n err\n\n )))),\n\n )\n\n })\n\n}\n\n\n", "file_path": "libs/lb/lb_external_interface/src/java_interface.rs", "rank": 52, "score": 223404.238451051 }, { "content": "pub fn get_dirty_ids(db: &Core, server: bool) -> Vec<Uuid> {\n\n db.calculate_work()\n\n .unwrap()\n\n .work_units\n\n .into_iter()\n\n .filter_map(|wu| match wu {\n\n WorkUnit::LocalChange(id) if !server => Some(id),\n\n WorkUnit::ServerChange(id) if server => Some(id),\n\n _ => None,\n\n })\n\n .unique()\n\n .collect()\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/test_utils/src/lib.rs", "rank": 53, "score": 222578.35338590204 }, { "content": "pub fn api_url(port: &str) -> String {\n\n format!(\"http://localhost:{}\", port)\n\n}\n\n\n", "file_path": "utils/dev-tool/src/utils.rs", "rank": 54, "score": 221010.04921800224 }, { "content": "fn upload<P: AsRef<Path>>(gh: &Github, name: &str, fpath: P) -> CliResult<()> {\n\n let client = ReleaseClient::new(gh.0.clone()).unwrap();\n\n\n\n let release = client\n\n .get_release_by_tag_name(&lb_repo(), &lb_version())\n\n .unwrap();\n\n\n\n let file = File::open(fpath).unwrap();\n\n client\n\n .upload_release_asset(\n\n &lb_repo(),\n\n release.id,\n\n name,\n\n \"application/vnd.microsoft.portable-executable\",\n\n file,\n\n None,\n\n )\n\n .unwrap();\n\n\n\n Ok(())\n\n}\n", "file_path": "utils/releaser/src/windows/desktop.rs", "rank": 55, "score": 218546.543674348 }, { "content": "pub fn build_info_address(port: &str) -> String {\n\n format!(\"{}/get-build-info\", api_url(port))\n\n}\n", "file_path": "utils/dev-tool/src/utils.rs", "rank": 56, "score": 217941.03382693842 }, { "content": "fn deserialize<U: DeserializeOwned>(env: &JNIEnv, json: JString, name: &str) -> Result<U, jstring> {\n\n let json_string = jstring_to_string(env, json, name)?;\n\n\n\n serde_json::from_str::<U>(&json_string).map_err(|err| {\n\n string_to_jstring(\n\n env,\n\n translate::<(), UnexpectedError>(Err(unexpected_only!(\n\n \"Couldn't deserialize {}: {:?}\",\n\n name,\n\n err\n\n ))),\n\n )\n\n })\n\n}\n\n\n\n#[no_mangle]\n\npub extern \"system\" fn Java_app_lockbook_core_CoreKt_init(\n\n env: JNIEnv, _: JClass, jconfig: JString,\n\n) -> jstring {\n\n let config = match deserialize::<Config>(&env, jconfig, \"config\") {\n", "file_path": "libs/lb/lb_external_interface/src/java_interface.rs", "rank": 57, "score": 217778.8075471577 }, { "content": "pub fn subscription(\n\n ui: &mut egui::Ui, maybe_sub_info: &Option<lb_rs::SubscriptionInfo>,\n\n metrics: &lb_rs::UsageMetrics, maybe_uncompressed: Option<&lb_rs::UsageItemMetric>,\n\n) -> Option<SubscriptionResponse> {\n\n let stroke_color = ui.visuals().extreme_bg_color;\n\n let bg = ui.visuals().faint_bg_color;\n\n\n\n egui::Frame::none()\n\n .fill(bg)\n\n .stroke(egui::Stroke::new(2.0, stroke_color))\n\n .rounding(egui::Rounding::same(4.0))\n\n .inner_margin(12.0)\n\n .show(ui, |ui| {\n\n let resp = subscription_info(ui, maybe_sub_info);\n\n ui.add_space(12.0);\n\n usage_bar(ui, metrics, maybe_uncompressed);\n\n resp\n\n })\n\n .inner\n\n}\n\n\n", "file_path": "libs/content/workspace/src/widgets/subscription.rs", "rank": 58, "score": 216218.33794356618 }, { "content": "pub fn decrypt<T: DeserializeOwned>(key: &AESKey, to_decrypt: &AESEncrypted<T>) -> SharedResult<T> {\n\n let nonce = GenericArray::from_slice(&to_decrypt.nonce);\n\n let decrypted = convert_key(key)\n\n .decrypt(nonce, aead::Payload { msg: &to_decrypt.value, aad: &[] })\n\n .map_err(SharedErrorKind::Decryption)?;\n\n let deserialized = bincode::deserialize(&decrypted)?;\n\n Ok(deserialized)\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/shared/src/symkey.rs", "rank": 59, "score": 215094.89734868222 }, { "content": "#[test]\n\nfn create_document_in_target_folder_by_sharee() {\n\n let cores = [test_core_with_account(), test_core_with_account()];\n\n let accounts = cores\n\n .iter()\n\n .map(|core| core.get_account().unwrap())\n\n .collect::<Vec<_>>();\n\n\n\n let folder1 = cores[0].create_at_path(\"/folder/\").unwrap();\n\n\n\n cores[0]\n\n .share_file(folder1.id, &accounts[1].username, ShareMode::Write)\n\n .unwrap();\n\n\n\n cores[0].sync(None).unwrap();\n\n cores[1].sync(None).unwrap();\n\n\n\n cores[1].create_link_at_path(\"/link1\", folder1.id).unwrap();\n\n cores[1]\n\n .create_file(\"document1\", folder1.id, FileType::Document)\n\n .unwrap();\n\n\n\n cores[1].sync(None).unwrap();\n\n cores[0].sync(None).unwrap();\n\n\n\n assert::all_paths(&cores[1], &[\"/\", \"/link1/\", \"/link1/document1\"]);\n\n assert::all_paths(&cores[0], &[\"/\", \"/folder/\", \"/folder/document1\"]);\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/tests/sharing_tests.rs", "rank": 60, "score": 214925.9600861887 }, { "content": "#[test]\n\nfn create_document_in_link_folder_by_sharee() {\n\n let cores: Vec<Core> = vec![test_core_with_account(), test_core_with_account()];\n\n let accounts = cores\n\n .iter()\n\n .map(|core| core.get_account().unwrap())\n\n .collect::<Vec<_>>();\n\n\n\n let folder1 = cores[0].create_at_path(\"/folder/\").unwrap();\n\n\n\n cores[0]\n\n .share_file(folder1.id, &accounts[1].username, ShareMode::Write)\n\n .unwrap();\n\n\n\n cores[0].sync(None).unwrap();\n\n cores[1].sync(None).unwrap();\n\n\n\n let link = cores[1].create_link_at_path(\"/link1\", folder1.id).unwrap();\n\n let result = cores[1]\n\n .create_file(\"document1\", link.id, FileType::Document)\n\n .unwrap_err();\n\n\n\n assert_eq!(result.kind, CoreError::FileNotFolder);\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/tests/sharing_tests.rs", "rank": 61, "score": 214925.9600861887 }, { "content": "#[test]\n\nfn create_document_in_target_folder_by_sharer() {\n\n let cores = [test_core_with_account(), test_core_with_account()];\n\n let accounts = cores\n\n .iter()\n\n .map(|core| core.get_account().unwrap())\n\n .collect::<Vec<_>>();\n\n\n\n let folder1 = cores[0].create_at_path(\"/folder/\").unwrap();\n\n\n\n cores[0]\n\n .share_file(folder1.id, &accounts[1].username, ShareMode::Write)\n\n .unwrap();\n\n\n\n cores[0].sync(None).unwrap();\n\n cores[1].sync(None).unwrap();\n\n\n\n cores[1].create_link_at_path(\"/link1\", folder1.id).unwrap();\n\n cores[0]\n\n .create_file(\"document1\", folder1.id, FileType::Document)\n\n .unwrap();\n\n\n\n cores[0].sync(None).unwrap();\n\n cores[1].sync(None).unwrap();\n\n\n\n assert::all_paths(&cores[1], &[\"/\", \"/link1/\", \"/link1/document1\"]);\n\n assert::all_paths(&cores[0], &[\"/\", \"/folder/\", \"/folder/document1\"]);\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/tests/sharing_tests.rs", "rank": 62, "score": 214925.9600861887 }, { "content": "#[test]\n\nfn create_document_in_link_folder_by_sharer() {\n\n let cores: Vec<Core> = vec![test_core_with_account(), test_core_with_account()];\n\n let accounts = cores\n\n .iter()\n\n .map(|core| core.get_account().unwrap())\n\n .collect::<Vec<_>>();\n\n\n\n let folder1 = cores[0].create_at_path(\"/folder/\").unwrap();\n\n\n\n cores[0]\n\n .share_file(folder1.id, &accounts[1].username, ShareMode::Write)\n\n .unwrap();\n\n\n\n cores[0].sync(None).unwrap();\n\n cores[1].sync(None).unwrap();\n\n\n\n let link = cores[1].create_link_at_path(\"/link1\", folder1.id).unwrap();\n\n cores[1].sync(None).unwrap();\n\n cores[0].sync(None).unwrap();\n\n let result = cores[0]\n\n .create_file(\"document1\", link.id, FileType::Document)\n\n .unwrap_err();\n\n\n\n assert_eq!(result.kind, CoreError::FileNonexistent);\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/tests/sharing_tests.rs", "rank": 63, "score": 214925.9600861887 }, { "content": "pub fn whoami(core: &Core) -> Result<(), CliError> {\n\n ensure_account(core)?;\n\n\n\n println!(\"{}\", core.get_account()?.username);\n\n Ok(())\n\n}\n\n\n", "file_path": "clients/cli/src/debug.rs", "rank": 64, "score": 214857.26472529603 }, { "content": "pub fn subscribe(core: &Core) -> Result<(), CliError> {\n\n ensure_account(core)?;\n\n\n\n println!(\"checking for existing payment methods...\");\n\n let existing_card =\n\n core.get_subscription_info()?\n\n .and_then(|info| match info.payment_platform {\n\n lb::PaymentPlatform::Stripe { card_last_4_digits } => Some(card_last_4_digits),\n\n lb::PaymentPlatform::GooglePlay { .. } => None,\n\n lb::PaymentPlatform::AppStore { .. } => None,\n\n });\n\n\n\n let mut use_old_card = false;\n\n if let Some(card) = existing_card {\n\n let answer: String = input::std_in(format!(\"do you want use *{}? [y/n]: \", card))?;\n\n if answer == \"y\" || answer == \"Y\" {\n\n use_old_card = true;\n\n }\n\n } else {\n\n println!(\"no existing cards found...\");\n", "file_path": "clients/cli/src/account.rs", "rank": 65, "score": 214857.26472529603 }, { "content": "pub fn status(core: &Core) -> Result<(), CliError> {\n\n ensure_account(core)?;\n\n\n\n let last_synced = core.get_last_synced_human_string()?;\n\n println!(\"files last synced: {last_synced}\");\n\n\n\n let core_status = core.calculate_work()?;\n\n let local = core_status\n\n .work_units\n\n .iter()\n\n .filter_map(|wu| match wu {\n\n WorkUnit::LocalChange(id) => Some(id),\n\n WorkUnit::ServerChange(_) => None,\n\n })\n\n .count();\n\n let server = core_status\n\n .work_units\n\n .iter()\n\n .filter_map(|wu| match wu {\n\n WorkUnit::ServerChange(id) => Some(id),\n", "file_path": "clients/cli/src/account.rs", "rank": 66, "score": 214857.26472529603 }, { "content": "pub fn whereami(core: &Core) -> Result<(), CliError> {\n\n ensure_account(core)?;\n\n\n\n let account = core.get_account()?;\n\n let config = &core.get_config()?;\n\n println!(\"Server: {}\", account.api_url);\n\n println!(\"Core: {}\", config.writeable_path);\n\n Ok(())\n\n}\n", "file_path": "clients/cli/src/debug.rs", "rank": 67, "score": 214857.26472529603 }, { "content": "pub fn unsubscribe(core: &Core) -> Result<(), CliError> {\n\n ensure_account(core)?;\n\n\n\n let answer: String =\n\n input::std_in(\"are you sure you would like to cancel your subscription? [y/n]: \")?;\n\n if answer == \"y\" || answer == \"Y\" {\n\n println!(\"cancelling subscription... \");\n\n core.cancel_subscription()?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "clients/cli/src/account.rs", "rank": 68, "score": 214857.26472529603 }, { "content": "pub fn file_completor(core: &Core, prompt: &str, filter: Option<Filter>) -> CliResult<Vec<String>> {\n\n if !prompt.is_empty() && prompt.chars().all(|c| c == '-' || c.is_ascii_hexdigit()) {\n\n return id_completor(core, prompt, filter);\n\n }\n\n\n\n let working_dir = prompt\n\n .rfind('/')\n\n .map(|last| &prompt[..last + 1])\n\n .unwrap_or(\"\");\n\n\n\n let parent = core.get_by_path(working_dir)?;\n\n\n\n let candidates = core\n\n .get_children(parent.id)?\n\n .into_iter()\n\n .filter(|f| match filter {\n\n Some(Filter::FoldersOnly) => f.is_folder(),\n\n // documents could be inside folders\n\n // leaf nodes only doesn't make sense in this context\n\n _ => true,\n", "file_path": "clients/cli/src/input.rs", "rank": 69, "score": 211587.92611120496 }, { "content": "#[test]\n\nfn decrypt_child_name_insert() {\n\n let account = Account::new(random_name(), url());\n\n let root = FileMetadata::create_root(&account).unwrap();\n\n let mut files = vec![root.clone()].to_lazy();\n\n let key = files.decrypt_key(root.id(), &account).unwrap();\n\n let child = FileMetadata::create(\n\n Uuid::new_v4(),\n\n symkey::generate_key(),\n\n &account.public_key(),\n\n root.id,\n\n &key,\n\n \"test\",\n\n FileType::Document,\n\n )\n\n .unwrap();\n\n files = files.stage(Some(child.clone())).promote().unwrap();\n\n assert_eq!(files.name_using_links(child.id(), &account).unwrap(), \"test\");\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/shared/tests/lazy_tests.rs", "rank": 70, "score": 211342.22447565832 }, { "content": "#[test]\n\nfn decrypt_child_name_basic() {\n\n let account = Account::new(random_name(), url());\n\n let root = FileMetadata::create_root(&account).unwrap();\n\n let mut files = vec![root.clone()].to_lazy();\n\n let key = files.decrypt_key(root.id(), &account).unwrap();\n\n let child = FileMetadata::create(\n\n Uuid::new_v4(),\n\n symkey::generate_key(),\n\n &account.public_key(),\n\n root.id,\n\n &key,\n\n \"test\",\n\n FileType::Document,\n\n )\n\n .unwrap();\n\n let mut files = vec![root.clone(), child.clone()].to_lazy();\n\n assert_eq!(files.name_using_links(child.id(), &account).unwrap(), \"test\");\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/shared/tests/lazy_tests.rs", "rank": 71, "score": 211342.22447565832 }, { "content": "#[test]\n\nfn decrypt_child_name_staged() {\n\n let account = Account::new(random_name(), url());\n\n let root = FileMetadata::create_root(&account).unwrap();\n\n let mut files = vec![root.clone()].to_lazy();\n\n let key = files.decrypt_key(root.id(), &account).unwrap();\n\n let child = FileMetadata::create(\n\n Uuid::new_v4(),\n\n symkey::generate_key(),\n\n &account.public_key(),\n\n root.id,\n\n &key,\n\n \"test\",\n\n FileType::Document,\n\n )\n\n .unwrap();\n\n let mut files = files.stage(Some(child.clone()));\n\n assert_eq!(files.name_using_links(child.id(), &account).unwrap(), \"test\");\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/shared/tests/lazy_tests.rs", "rank": 72, "score": 211342.22447565832 }, { "content": "#[test]\n\nfn get_path_by_id_document_in_folder() {\n\n let core = test_core_with_account();\n\n let document = core.create_at_path(\"/folder/document\").unwrap();\n\n let document_path = core.get_path_by_id(document.id).unwrap();\n\n assert_eq!(&document_path, \"/folder/document\");\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/tests/path_service_tests.rs", "rank": 73, "score": 211124.16105403373 }, { "content": "pub fn deploy() -> CliResult<()> {\n\n build_server();\n\n backup_old_server();\n\n replace_old_server();\n\n restart_server();\n\n check_server_status();\n\n upload();\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "utils/releaser/src/server.rs", "rank": 74, "score": 211053.47251168682 }, { "content": "pub fn get() -> Result<FfiCore, UnexpectedError> {\n\n STATE\n\n .read()\n\n .map_err(|err| unexpected_only!(\"{:#?}\", err))?\n\n .clone()\n\n .ok_or_else(|| unexpected_only!(\"Did not initialize core prior to using it!\"))\n\n}\n", "file_path": "libs/lb/lb_external_interface/src/static_state.rs", "rank": 75, "score": 209469.59099522512 }, { "content": "pub fn captured(\n\n cursor: Cursor, paragraphs: &Paragraphs, ast: &Ast, text_range: &AstTextRange,\n\n hover_syntax_reveal_debounce_state: HoverSyntaxRevealDebounceState, appearance: &Appearance,\n\n cursor_paragraphs: (usize, usize),\n\n) -> bool {\n\n let ast_node_range = ast.nodes[*text_range.ancestors.last().unwrap()].range;\n\n let intersects_selection = ast_node_range.intersects_allow_empty(&cursor.selection);\n\n\n\n let debounce_satisfied = hover_syntax_reveal_debounce_state.pointer_offset_updated_at\n\n < Instant::now() - HOVER_SYNTAX_REVEAL_DEBOUNCE;\n\n let intersects_pointer = debounce_satisfied\n\n && hover_syntax_reveal_debounce_state\n\n .pointer_offset\n\n .map(|pointer_offset| {\n\n ast_node_range.intersects(&(pointer_offset, pointer_offset), true)\n\n })\n\n .unwrap_or(false);\n\n\n\n let text_range_paragraphs = paragraphs.find_intersecting(text_range.range, true);\n\n let in_capture_disabled_paragraph = appearance.markdown_capture_disabled_for_cursor_paragraph\n", "file_path": "libs/content/workspace/src/tab/markdown_editor/bounds.rs", "rank": 76, "score": 209380.81782665633 }, { "content": "pub fn calc(\n\n ast: &Ast, prior_cache: &ImageCache, client: &reqwest::blocking::Client, core: &lb_rs::Core,\n\n ui: &Ui,\n\n) -> ImageCache {\n\n let mut result = ImageCache::default();\n\n\n\n let mut prior_cache = prior_cache.clone();\n\n for node in &ast.nodes {\n\n if let MarkdownNode::Inline(InlineNode::Image(_, url, title)) = &node.node_type {\n\n let (url, title) = (url.clone(), title.clone());\n\n\n\n if result.map.contains_key(&url) {\n\n // the second removal of the same image from the prior cache is always a cache miss and causes performance issues\n\n // we need to remove cache hits from the prior cache to avoid freeing them from the texture manager\n\n continue;\n\n }\n\n\n\n if let Some(cached) = prior_cache.map.remove(&url) {\n\n // re-use image from previous cache (even it if failed to load)\n\n result.map.insert(url, cached);\n", "file_path": "libs/content/workspace/src/tab/markdown_editor/images.rs", "rank": 77, "score": 209380.81782665633 }, { "content": "pub fn calc(\n\n ast: &Ast, buffer: &SubBuffer, bounds: &Bounds, images: &ImageCache, appearance: &Appearance,\n\n hover_syntax_reveal_debounce_state: HoverSyntaxRevealDebounceState, ui: &mut Ui,\n\n) -> Galleys {\n\n let cursor_paragraphs = bounds\n\n .paragraphs\n\n .find_intersecting(buffer.cursor.selection, true);\n\n\n\n let mut result: Galleys = Default::default();\n\n\n\n let mut head_size: RelCharOffset = 0.into();\n\n let mut annotation: Option<Annotation> = Default::default();\n\n let mut annotation_text_format = Default::default();\n\n let mut layout: LayoutJob = Default::default();\n\n\n\n // join ast text ranges, paragraphs, plaintext links, selection, and whole document (to ensure everything is captured)\n\n // emit one galley per paragraph; other data is used to determine style\n\n let ast_ranges = bounds\n\n .ast\n\n .iter()\n", "file_path": "libs/content/workspace/src/tab/markdown_editor/galleys.rs", "rank": 78, "score": 209380.81782665633 }, { "content": "#[test]\n\nfn decrypt_child_name_stage_promote() {\n\n let account = Account::new(random_name(), url());\n\n let root = FileMetadata::create_root(&account).unwrap();\n\n let mut files = vec![root.clone()].to_lazy();\n\n let key = files.decrypt_key(root.id(), &account).unwrap();\n\n let child = FileMetadata::create(\n\n Uuid::new_v4(),\n\n symkey::generate_key(),\n\n &account.public_key(),\n\n root.id,\n\n &key,\n\n \"test\",\n\n FileType::Document,\n\n )\n\n .unwrap();\n\n let mut files = files.stage(Some(child.clone())).promote().unwrap();\n\n assert_eq!(files.name_using_links(child.id(), &account).unwrap(), \"test\");\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/shared/tests/lazy_tests.rs", "rank": 79, "score": 207582.11005695848 }, { "content": "pub fn release() -> CliResult<()> {\n\n let gh = Github::env();\n\n build_x86()?;\n\n upload(\n\n &gh,\n\n \"lockbook-windows-setup-x86_64.exe\",\n\n \"target/x86_64-pc-windows-msvc/release/winstaller.exe\",\n\n )?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "utils/releaser/src/windows/desktop.rs", "rank": 80, "score": 207518.52314812614 }, { "content": "pub fn release() -> CliResult<()> {\n\n cli::release()?;\n\n desktop::release()?;\n\n\n\n Ok(())\n\n}\n", "file_path": "utils/releaser/src/linux/mod.rs", "rank": 81, "score": 207518.52314812617 }, { "content": "pub fn release() -> CliResult<()> {\n\n let build_dir = Path::new(\"windows-build\");\n\n if !build_dir.exists() {\n\n fs::create_dir(\"windows-build\").unwrap();\n\n }\n\n cli::release()?;\n\n desktop::release()?;\n\n\n\n fs::remove_dir_all(\"windows-build\").unwrap();\n\n Ok(())\n\n}\n", "file_path": "utils/releaser/src/windows/mod.rs", "rank": 82, "score": 207518.52314812614 }, { "content": "pub fn release() -> CliResult<()> {\n\n update_aur();\n\n update_snap();\n\n build_x86();\n\n upload();\n\n Ok(())\n\n}\n\n\n", "file_path": "utils/releaser/src/linux/desktop.rs", "rank": 83, "score": 207518.52314812617 }, { "content": "pub fn release() -> CliResult<()> {\n\n build()?;\n\n zip_binary()?;\n\n upload()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "utils/releaser/src/windows/cli.rs", "rank": 84, "score": 207518.52314812614 }, { "content": "pub fn release() -> CliResult<()> {\n\n cli::release();\n\n core::build();\n\n ws::build();\n\n clean_build_dir();\n\n ios::release();\n\n mac::release();\n\n Ok(())\n\n}\n\n\n", "file_path": "utils/releaser/src/apple/mod.rs", "rank": 85, "score": 207518.52314812614 }, { "content": "pub fn release() -> CliResult<()> {\n\n upload_deb()?;\n\n bin_gh()?;\n\n update_aur()?;\n\n update_snap()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "utils/releaser/src/linux/cli.rs", "rank": 86, "score": 207518.52314812614 }, { "content": "pub fn release() -> CliResult<()> {\n\n let mut path = work_dir();\n\n\n\n clone(&mut path);\n\n checkout(&path);\n\n remove_old(&path);\n\n copy_public_site(&path);\n\n push(&path);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "utils/releaser/src/public_site.rs", "rank": 87, "score": 207518.52314812614 }, { "content": "pub fn release() -> CliResult<()> {\n\n core::build_libs();\n\n ws::build();\n\n build_android();\n\n release_gh();\n\n release_play_store();\n\n Ok(())\n\n}\n\n\n", "file_path": "utils/releaser/src/android/mod.rs", "rank": 88, "score": 207518.52314812617 }, { "content": "pub fn is_folder<F: FileLike>(file: &F) -> SharedResult<()> {\n\n if file.is_folder() {\n\n Ok(())\n\n } else {\n\n Err(SharedErrorKind::FileNotFolder.into())\n\n }\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/shared/src/validate.rs", "rank": 89, "score": 207165.97853197315 }, { "content": "pub fn is_document<F: FileLike>(file: &F) -> SharedResult<()> {\n\n if file.is_document() {\n\n Ok(())\n\n } else {\n\n Err(SharedErrorKind::FileNotDocument.into())\n\n }\n\n}\n\n\n", "file_path": "libs/lb/lb-rs/libs/shared/src/validate.rs", "rank": 90, "score": 207116.61140423355 }, { "content": "/// processes `combined_events` and returns a boolean representing whether text was updated, new contents for clipboard\n\n/// (optional), and a link that was opened (optional)\n\npub fn process(\n\n combined_events: &[Modification], galleys: &Galleys, bounds: &Bounds, ast: &Ast,\n\n buffer: &mut Buffer, debug: &mut DebugInfo, appearance: &mut Appearance,\n\n) -> (bool, Option<String>, Option<String>) {\n\n combined_events\n\n .iter()\n\n .cloned()\n\n .map(|m| match input::mutation::calc(m, &buffer.current, galleys, bounds, ast) {\n\n EditorMutation::Buffer(mutations) if mutations.is_empty() => (false, None, None),\n\n EditorMutation::Buffer(mutations) => buffer.apply(mutations, debug, appearance),\n\n EditorMutation::Undo => {\n\n buffer.undo(debug, appearance);\n\n (true, None, None)\n\n }\n\n EditorMutation::Redo => {\n\n buffer.redo(debug, appearance);\n\n (true, None, None)\n\n }\n\n })\n\n .reduce(\n", "file_path": "libs/content/workspace/src/tab/markdown_editor/input/events.rs", "rank": 91, "score": 206209.48440105512 }, { "content": "pub fn calc(\n\n event: &Event, click_checker: impl ClickChecker, pointer_state: &mut PointerState,\n\n now: Instant, touch_mode: bool, appearance: &appearance::Appearance,\n\n) -> Option<Modification> {\n\n match event {\n\n Event::Key { key, pressed: true, modifiers, .. }\n\n if matches!(key, Key::ArrowUp | Key::ArrowDown) && !cfg!(target_os = \"ios\") =>\n\n {\n\n Some(Modification::Select {\n\n region: Region::ToOffset {\n\n offset: if modifiers.mac_cmd {\n\n Offset::To(Bound::Doc)\n\n } else {\n\n Offset::By(Increment::Line)\n\n },\n\n backwards: key == &Key::ArrowUp,\n\n extend_selection: modifiers.shift,\n\n },\n\n })\n\n }\n", "file_path": "libs/content/workspace/src/tab/markdown_editor/input/canonical.rs", "rank": 92, "score": 206198.9085649083 }, { "content": "pub fn calc_words(\n\n buffer: &SubBuffer, ast: &Ast, ast_ranges: &AstTextRanges, appearance: &Appearance,\n\n) -> Words {\n\n let mut result = vec![];\n\n\n\n for text_range in ast_ranges {\n\n if text_range.range_type != AstTextRangeType::Text\n\n && appearance.markdown_capture(text_range.node(ast).node_type())\n\n == CaptureCondition::Always\n\n {\n\n // skip always-captured syntax sequences\n\n continue;\n\n } else if text_range.range_type != AstTextRangeType::Text\n\n && !text_range.node(ast).node_type().syntax_includes_text()\n\n {\n\n // syntax sequences for node types without text count as single words\n\n result.push(text_range.range);\n\n } else {\n\n // remaining text and syntax sequences (including link URLs etc) are split into words\n\n let mut prev_char_offset = text_range.range.0;\n", "file_path": "libs/content/workspace/src/tab/markdown_editor/bounds.rs", "rank": 93, "score": 206198.9085649083 }, { "content": "pub fn calc(\n\n modification: Modification, buffer: &SubBuffer, galleys: &Galleys, bounds: &Bounds, ast: &Ast,\n\n) -> EditorMutation {\n\n let current_cursor = buffer.cursor;\n\n let mut mutation = Vec::new();\n\n\n\n match modification {\n\n Modification::Select { region } => mutation.push(SubMutation::Cursor {\n\n cursor: region_to_cursor(region, current_cursor, buffer, galleys, bounds),\n\n }),\n\n Modification::StageMarked { highlighted, text } => {\n\n let mut cursor = current_cursor;\n\n let text_length = text.grapheme_indices(true).count();\n\n\n\n // when inserting text, replacing existing marked text if any\n\n if let Some(mark) = cursor.mark {\n\n cursor.selection = mark;\n\n }\n\n\n\n // mark inserted text\n", "file_path": "libs/content/workspace/src/tab/markdown_editor/input/mutation.rs", "rank": 94, "score": 206198.9085649083 }, { "content": "pub fn calc_text(\n\n ast: &Ast, ast_ranges: &AstTextRanges, paragraphs: &Paragraphs, appearance: &Appearance,\n\n segs: &UnicodeSegs, cursor: Cursor,\n\n hover_syntax_reveal_debounce_state: HoverSyntaxRevealDebounceState,\n\n) -> Text {\n\n let cursor_paragraphs = paragraphs.find_intersecting(cursor.selection, true);\n\n\n\n let mut result = vec![];\n\n let mut last_range_pushed = false;\n\n for text_range in ast_ranges {\n\n let captured = captured(\n\n cursor,\n\n paragraphs,\n\n ast,\n\n text_range,\n\n hover_syntax_reveal_debounce_state,\n\n appearance,\n\n cursor_paragraphs,\n\n );\n\n\n", "file_path": "libs/content/workspace/src/tab/markdown_editor/bounds.rs", "rank": 95, "score": 206198.9085649083 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn combine(\n\n events: &[Event], custom_events: &[crate::Event], click_checker: impl ClickChecker + Copy,\n\n touch_mode: bool, appearance: &Appearance, pointer_state: &mut PointerState,\n\n core: &mut lb_rs::Core, open_file: Uuid,\n\n) -> Vec<Modification> {\n\n let canonical_egui_events = events.iter().filter_map(|e| {\n\n input::canonical::calc(\n\n e,\n\n click_checker,\n\n pointer_state,\n\n Instant::now(),\n\n touch_mode,\n\n appearance,\n\n )\n\n });\n\n\n\n custom_events\n\n .iter()\n\n .cloned()\n\n .flat_map(|event| handle_custom_event(event, core, open_file))\n\n .chain(canonical_egui_events)\n\n .collect()\n\n}\n\n\n", "file_path": "libs/content/workspace/src/tab/markdown_editor/input/events.rs", "rank": 96, "score": 206198.9085649083 }, { "content": "pub fn update_snap() -> CliResult<()> {\n\n let version = lb_version();\n\n let snap_name = format!(\"lockbook_{version}_amd64.snap\");\n\n\n\n let new_content = format!(\n\n r#\"\n\nname: lockbook\n\nbase: core20\n\nversion: '{version}'\n\nsummary: The CLI version of Lockbook\n\ndescription: |\n\n The private, polished note-taking platform.\n\ngrade: stable\n\nconfinement: strict\n\n\n\nparts:\n\n lockbook:\n\n plugin: rust\n\n source: https://github.com/lockbook/lockbook.git\n\n source-tag: {version}\n", "file_path": "utils/releaser/src/linux/cli.rs", "rank": 97, "score": 204150.70018297323 }, { "content": "pub fn bin_gh() -> CliResult<()> {\n\n build_x86();\n\n let gh = Github::env();\n\n\n\n let client = ReleaseClient::new(gh.0).unwrap();\n\n let release = client\n\n .get_release_by_tag_name(&lb_repo(), &lb_version())\n\n .unwrap();\n\n let file = File::open(\"target/x86_64-unknown-linux-gnu/release/lockbook\").unwrap();\n\n client\n\n .upload_release_asset(\n\n &lb_repo(),\n\n release.id,\n\n \"lockbook-cli-linux\",\n\n \"application/octet-stream\",\n\n file,\n\n None,\n\n )\n\n .unwrap();\n\n Ok(())\n\n}\n\n\n", "file_path": "utils/releaser/src/linux/cli.rs", "rank": 98, "score": 204150.70018297323 }, { "content": "pub fn upload_deb() -> CliResult<()> {\n\n let lb_version = &lb_version();\n\n let gh = Github::env();\n\n\n\n let deb_scripts_location = \"utils/releaser/debian-build-scripts/ppa-lockbook/\";\n\n Command::new(\"dch\")\n\n .args([\n\n \"--newversion\",\n\n lb_version,\n\n \"see changelog at https://github.com/lockbook/lockbook/releases/latest\",\n\n ])\n\n .current_dir(deb_scripts_location)\n\n .env(\"DEBEMAIL\", \"Parth<[email protected]>\")\n\n .assert_success();\n\n\n\n let new_control = format!(\n\n r#\"\n\nSource: lockbook\n\nSection: utils\n\nPriority: extra\n", "file_path": "utils/releaser/src/linux/cli.rs", "rank": 99, "score": 204150.7001829732 } ]
Rust
src/day15.rs
codedstructure/aoc2021
27e151e4c8cbcda78b29fe734df6733818783461
use std::{ collections::{HashMap, HashSet}, fs::File, io::{BufRead, BufReader}, }; pub fn read_list(filename: &str) -> Vec<String> { let f = File::open(filename).expect("Could not read file"); BufReader::new(f).lines().map(|l| l.expect("Err")).collect() } #[derive(Debug)] struct RiskMaze { risk: Vec<Vec<i32>>, line_width: usize, } impl RiskMaze { fn new(filename: &str) -> Self { let mut risk = vec![]; let mut line_width = 0; for line in read_list(filename) { line_width = line.len(); risk.push( line.chars() .map(|x| x.to_string().parse::<i32>().unwrap()) .collect(), ); } Self { risk, line_width } } fn expand(&mut self) { let mut new_grid = vec![]; for row in 0..5 * self.risk.len() { let mut new_row = vec![]; for col in 0..5 * self.line_width { let section = col / self.line_width + row / self.risk.len(); let mut raw = self.risk[row % self.risk.len()][col % self.line_width]; for _ in 0..section { raw += 1; if raw > 9 { raw = 1; } } new_row.push(raw); } new_grid.push(new_row); } self.risk = new_grid; self.line_width *= 5; } fn neighbours(&self, pos: (usize, usize)) -> HashSet<(usize, usize)> { let mut n = HashSet::new(); let row = pos.0; let col = pos.1; if row >= 1 { n.insert((row - 1, col)); } if row < self.risk.len() - 1 { n.insert((row + 1, col)); } if col >= 1 { n.insert((row, col - 1)); } if col < self.line_width - 1 { n.insert((row, col + 1)); } n } fn _broken_populate(&self) -> i32 { let mut boundary = HashSet::new(); let mut already = HashSet::new(); let start = (0, 0); let target = (self.risk.len() - 1, self.line_width - 1); already.insert(start); let mut risk = HashMap::new(); risk.insert(start, 0); boundary.insert((1, 0)); boundary.insert((0, 1)); while risk.get(&target).is_none() { let mut new_boundary = HashSet::new(); for b in &boundary { new_boundary.extend( self.neighbours(*b) .difference(&already) .copied() .collect::<HashSet<(usize, usize)>>(), ); } for pos in boundary.clone() { let pos_risk = self.risk[pos.0][pos.1]; let mut min_risk = 99999999; for n in self.neighbours(pos) { if already.contains(&n) { let candidate = risk.get(&n).unwrap(); if candidate < &min_risk { min_risk = *candidate; } } } let pos_min_risk = min_risk + pos_risk; if let Some(t) = risk.get(&pos) { if pos_min_risk < *t { risk.insert(pos, pos_min_risk); } } else { risk.insert(pos, pos_min_risk); } } already.extend(&boundary); boundary = new_boundary; } *risk.get(&target).unwrap() } fn bellman_ford(&self) -> i32 { let start = (0, 0); let target = (self.risk.len() - 1, self.line_width - 1); let mut risk = HashMap::new(); for row in 0..self.risk.len() { for col in 0..self.line_width { risk.insert((row, col), 99999); } } risk.insert(start, 0); let mut keep_going; loop { keep_going = false; for row in 0..self.risk.len() { for col in 0..self.line_width { let a = (row, col); for b in self.neighbours((row, col)) { let w = self.risk[b.0][b.1]; let min_dist = risk.get(&a).unwrap() + w; if min_dist < *risk.get(&b).unwrap() { risk.insert(b, min_dist); keep_going = true; } } } } if !keep_going { break; } } *risk.get(&target).unwrap() } } pub fn step1() { let rm = RiskMaze::new("inputs/day15.txt"); println!("{}", rm.bellman_ford()); } pub fn step2() { let mut rm = RiskMaze::new("inputs/day15.txt"); rm.expand(); println!("{}", rm.bellman_ford()); }
use std::{ collections::{HashMap, HashSet}, fs::File, io::{BufRead, BufReader}, }; pub fn read_list(filename: &str) -> Vec<String> { let f = File::open(filename).expect("Could not read file"); BufReader::new(f).lines().map(|l| l.expect("Err")).collect() } #[derive(Debug)] struct RiskMaze { risk: Vec<Vec<i32>>, line_width: usize, } impl RiskMaze { fn new(filename: &str) -> Self { let mut risk = vec![]; let mut line_width = 0; for line in read_list(filename) { line_width = line.len(); risk.push( line.chars() .map(|x| x.to_string().parse::<i32>().unwrap()) .collect(), ); } Self { risk, line_width } } fn expand(&mut self) { let mut new_grid = vec![]; for row in 0..5 * self.risk.len() { let mut new_row = vec![]; for col in 0..5 * self.line_width { let section = col / self.line_width + row / self.risk.len(); let mut raw = self.risk[row % self.risk.len()][col % self.line_width]; for _ in 0..section { raw += 1; if raw > 9 { raw = 1; } } new_row.push(raw); } new_grid.push(new_row); } self.risk = new_grid; self.line_width *= 5; } fn neighbours(&self, pos: (usize, usize)) -> HashSet<(usize, usize)> { let mut n = HashSet::new(); let row = pos.0; let col = pos.1; if row >= 1 { n.insert((row - 1, col)); } if row < self.risk.len() - 1 { n.insert((row + 1, col)); } if col >= 1 { n.insert((row, col - 1)); } if col < self.line_width - 1 { n.insert((row, col + 1)); } n } fn _broken_populate(&self) -> i32 { let mut boundary = HashSet::new(); let mut already = HashSet::new(); let start = (0, 0); let target = (self.risk.len() - 1, self.line_width - 1); already.insert(start); let mut risk = HashMap::new(); risk.insert(start,
fn bellman_ford(&self) -> i32 { let start = (0, 0); let target = (self.risk.len() - 1, self.line_width - 1); let mut risk = HashMap::new(); for row in 0..self.risk.len() { for col in 0..self.line_width { risk.insert((row, col), 99999); } } risk.insert(start, 0); let mut keep_going; loop { keep_going = false; for row in 0..self.risk.len() { for col in 0..self.line_width { let a = (row, col); for b in self.neighbours((row, col)) { let w = self.risk[b.0][b.1]; let min_dist = risk.get(&a).unwrap() + w; if min_dist < *risk.get(&b).unwrap() { risk.insert(b, min_dist); keep_going = true; } } } } if !keep_going { break; } } *risk.get(&target).unwrap() } } pub fn step1() { let rm = RiskMaze::new("inputs/day15.txt"); println!("{}", rm.bellman_ford()); } pub fn step2() { let mut rm = RiskMaze::new("inputs/day15.txt"); rm.expand(); println!("{}", rm.bellman_ford()); }
0); boundary.insert((1, 0)); boundary.insert((0, 1)); while risk.get(&target).is_none() { let mut new_boundary = HashSet::new(); for b in &boundary { new_boundary.extend( self.neighbours(*b) .difference(&already) .copied() .collect::<HashSet<(usize, usize)>>(), ); } for pos in boundary.clone() { let pos_risk = self.risk[pos.0][pos.1]; let mut min_risk = 99999999; for n in self.neighbours(pos) { if already.contains(&n) { let candidate = risk.get(&n).unwrap(); if candidate < &min_risk { min_risk = *candidate; } } } let pos_min_risk = min_risk + pos_risk; if let Some(t) = risk.get(&pos) { if pos_min_risk < *t { risk.insert(pos, pos_min_risk); } } else { risk.insert(pos, pos_min_risk); } } already.extend(&boundary); boundary = new_boundary; } *risk.get(&target).unwrap() }
function_block-function_prefixed
[ { "content": "pub fn read_csv_ints(filename: &str) -> Vec<i32> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n let mut line = String::new();\n\n BufReader::new(f).read_line(&mut line).unwrap();\n\n // parse() breaks on line ending, so need to trim that...\n\n line.retain(|c| !c.is_whitespace());\n\n line.split(',').map(|x| x.parse::<i32>().unwrap()).collect()\n\n}\n\n\n", "file_path": "src/day07.rs", "rank": 0, "score": 213282.12551770644 }, { "content": "pub fn read_csv_ints(filename: &str) -> Vec<usize> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n let mut line = String::new();\n\n BufReader::new(f).read_line(&mut line).unwrap();\n\n // parse() breaks on line ending, so need to trim that...\n\n line.retain(|c| !c.is_whitespace());\n\n line.split(',').map(|x| {x.parse::<usize>().unwrap()}).collect()\n\n}\n\n\n", "file_path": "src/day06.rs", "rank": 1, "score": 194429.6019802069 }, { "content": "pub fn read_int_list(filename: &str) -> Result<Vec<i32>, Error> {\n\n let f = File::open(filename)?;\n\n Ok(BufReader::new(f)\n\n .lines()\n\n .map(|l| l.expect(\"Err\"))\n\n .map(|l| l.parse::<i32>().unwrap())\n\n .collect())\n\n}\n\n\n", "file_path": "src/day01.rs", "rank": 2, "score": 192746.07552376407 }, { "content": "pub fn read_list(filename: &str) -> Vec<String> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n BufReader::new(f).lines().map(|l| l.expect(\"Err\")).collect()\n\n}\n\n\n", "file_path": "src/day18.rs", "rank": 3, "score": 177418.63435351753 }, { "content": "pub fn read_list(filename: &str) -> Vec<String> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n BufReader::new(f).lines().map(|l| l.expect(\"Err\")).collect()\n\n}\n\n\n", "file_path": "src/day05.rs", "rank": 4, "score": 177418.63435351753 }, { "content": "pub fn read_list(filename: &str) -> Vec<String> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n BufReader::new(f).lines().map(|l| l.expect(\"Err\")).collect()\n\n}\n\n\n", "file_path": "src/day10.rs", "rank": 5, "score": 177418.6343535175 }, { "content": "pub fn read_list(filename: &str) -> Vec<String> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n BufReader::new(f).lines().map(|l| l.expect(\"Err\")).collect()\n\n}\n\n\n", "file_path": "src/day19.rs", "rank": 6, "score": 177418.63435351753 }, { "content": "pub fn read_list(filename: &str) -> Vec<String> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n BufReader::new(f)\n\n .lines()\n\n .map(|l| l.expect(\"Err\"))\n\n .collect()\n\n}\n\n\n", "file_path": "src/day02.rs", "rank": 7, "score": 177418.6343535175 }, { "content": "pub fn read_list(filename: &str) -> Vec<String> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n BufReader::new(f).lines().map(|l| l.expect(\"Err\")).collect()\n\n}\n\n\n", "file_path": "src/day12.rs", "rank": 8, "score": 177418.63435351753 }, { "content": "pub fn read_list(filename: &str) -> Vec<String> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n BufReader::new(f).lines().map(|l| l.expect(\"Err\")).collect()\n\n}\n\n\n", "file_path": "src/day17.rs", "rank": 9, "score": 177418.6343535175 }, { "content": "pub fn read_list(filename: &str) -> Vec<String> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n BufReader::new(f).lines().map(|l| l.expect(\"Err\")).collect()\n\n}\n\n\n", "file_path": "src/day08.rs", "rank": 10, "score": 177418.63435351753 }, { "content": "pub fn read_list(filename: &str) -> Vec<String> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n BufReader::new(f).lines().map(|l| l.expect(\"Err\")).collect()\n\n}\n\n\n", "file_path": "src/day04.rs", "rank": 11, "score": 177418.6343535175 }, { "content": "pub fn read_list(filename: &str) -> Vec<String> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n BufReader::new(f)\n\n .lines()\n\n .map(|l| l.expect(\"Err\"))\n\n .collect()\n\n}\n\n\n", "file_path": "src/day03.rs", "rank": 12, "score": 177418.63435351753 }, { "content": "pub fn read_list(filename: &str) -> Vec<String> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n BufReader::new(f).lines().map(|l| l.expect(\"Err\")).collect()\n\n}\n\n\n", "file_path": "src/day20.rs", "rank": 13, "score": 177418.63435351753 }, { "content": "pub fn read_list(filename: &str) -> Vec<String> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n BufReader::new(f).lines().map(|l| l.expect(\"Err\")).collect()\n\n}\n\n\n", "file_path": "src/day09.rs", "rank": 15, "score": 177418.63435351753 }, { "content": "pub fn read_list(filename: &str) -> Vec<String> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n BufReader::new(f).lines().map(|l| l.expect(\"Err\")).collect()\n\n}\n\n\n", "file_path": "src/day11.rs", "rank": 16, "score": 177418.63435351753 }, { "content": "pub fn read_list(filename: &str) -> Vec<String> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n BufReader::new(f).lines().map(|l| l.expect(\"Err\")).collect()\n\n}\n\n\n", "file_path": "src/day13.rs", "rank": 17, "score": 177418.6343535175 }, { "content": "pub fn read_list(filename: &str) -> Vec<String> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n BufReader::new(f).lines().map(|l| l.expect(\"Err\")).collect()\n\n}\n\n\n", "file_path": "src/day14.rs", "rank": 18, "score": 177418.63435351753 }, { "content": "pub fn read_list(filename: &str) -> Vec<String> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n BufReader::new(f).lines().map(|l| l.expect(\"Err\")).collect()\n\n}\n\n\n", "file_path": "src/day22.rs", "rank": 19, "score": 177418.6343535175 }, { "content": "pub fn read_hex_chars(filename: &str) -> Vec<char> {\n\n let f = File::open(filename).expect(\"Could not read file\");\n\n let mut line = String::new();\n\n BufReader::new(f).read_line(&mut line).unwrap();\n\n line.chars().collect()\n\n}\n\n\n", "file_path": "src/day16.rs", "rank": 20, "score": 173013.44367933727 }, { "content": "#[derive(Debug, Hash, PartialEq, Eq, Clone)]\n\nstruct Delta(i32, i32, i32);\n\n\n\nimpl From<Vec<i32>> for Delta {\n\n fn from(item: Vec<i32>) -> Self {\n\n assert!(item.len() == 3);\n\n Delta(item[0], item[1], item[2])\n\n }\n\n}\n\n\n\nimpl Delta {\n\n fn translate(&self, other: &Self) -> Self {\n\n Self(self.0 + other.0, self.1 + other.1, self.2 + other.2)\n\n }\n\n\n\n fn delta(&self, other: &Self) -> Self {\n\n Self(other.0 - self.0, other.1 - self.1, other.2 - self.2)\n\n }\n\n\n\n fn rotate(&self, dir: i32) -> Self {\n\n match dir {\n", "file_path": "src/day19.rs", "rank": 21, "score": 120655.49701969197 }, { "content": "#[derive(Debug, Copy, Clone)]\n\nstruct Line {\n\n start: Point,\n\n end: Point,\n\n\n\n dx: i32,\n\n dy: i32,\n\n}\n\n\n\nimpl Line {\n\n fn from_line(l: &str) -> Self {\n\n let mut line_iter = l.split(\" -> \");\n\n let mut first = line_iter\n\n .next()\n\n .unwrap()\n\n .split(',')\n\n .map(|x| x.parse::<i32>().unwrap());\n\n let mut second = line_iter\n\n .next()\n\n .unwrap()\n\n .split(',')\n", "file_path": "src/day05.rs", "rank": 22, "score": 117065.06806198217 }, { "content": "fn decode_entry(entry: &str) -> usize {\n\n let mut entry_parts = entry.split(\" | \");\n\n let mut map = HashMap::new();\n\n let controls = entry_parts.next().unwrap().split(' ').map(|s| digitize(s));\n\n let outputs = entry_parts.next().unwrap().split(' ').map(|s| digitize(s));\n\n\n\n let mut one_pattern = 0;\n\n let mut four_pattern = 0;\n\n for sample in controls.clone() {\n\n match sample.count_ones() {\n\n 2 => {\n\n one_pattern = sample;\n\n map.insert(sample, 1);\n\n } // 2 segments => '1'\n\n 3 => {\n\n map.insert(sample, 7);\n\n } // 3 segments => '7'\n\n 4 => {\n\n four_pattern = sample;\n\n map.insert(sample, 4);\n", "file_path": "src/day08.rs", "rank": 23, "score": 111702.03511372107 }, { "content": "fn count_v<T: PartialEq>(i: &Vec<Vec<T>>, bit_pos: usize, value: T) -> usize {\n\n let mut c = 0;\n\n for x in i.iter() {\n\n if x[bit_pos] == value {\n\n c += 1;\n\n }\n\n }\n\n c\n\n //i.iter().filter(|&x| *x == value).count()\n\n}\n\n\n", "file_path": "src/day03.rs", "rank": 24, "score": 101502.22340085043 }, { "content": "pub fn step1() {\n\n let sm = ScannerMap::new(\"inputs/day19.txt\");\n\n\n\n let (fixed, _) = sm.build_map();\n\n\n\n let mut beacons_fixed = HashSet::new();\n\n for smf in fixed.values() {\n\n for bf in &smf.beacons {\n\n beacons_fixed.insert(bf);\n\n }\n\n }\n\n println!(\"Beacon count: {}\", beacons_fixed.len());\n\n}\n\n\n", "file_path": "src/day19.rs", "rank": 25, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let mut game = Game::new(\"inputs/day04.txt\");\n\n\n\n println!(\"Losing score: {}\", game.play_to_lose());\n\n}\n", "file_path": "src/day04.rs", "rank": 26, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let mut im = Image::new(\"inputs/day20.txt\");\n\n\n\n for _ in 0..50 {\n\n im = im.enhance();\n\n }\n\n println!(\"Lit pixels {}\", im.count_lit());\n\n}\n", "file_path": "src/day20.rs", "rank": 27, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let mut count = 0;\n\n let mut previous = 0;\n\n let mut current;\n\n let mut window: Vec<i32> = vec![];\n\n for value in read_int_list(\"inputs/day01.txt\").unwrap() {\n\n if window.len() < 3 {\n\n window.push(value);\n\n continue;\n\n } else {\n\n window.remove(0); // fine for a 3-element list\n\n window.push(value);\n\n }\n\n assert!(window.len() == 3);\n\n current = window.iter().sum();\n\n if current > previous {\n\n count += 1;\n\n }\n\n previous = current;\n\n }\n\n count -= 1; // because we shouldn't count the first 0->anything transition\n\n println!(\"Windowed Increment count: {}\", count);\n\n}\n", "file_path": "src/day01.rs", "rank": 28, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let mut pr = PacketReader::new(read_hex_chars(\"inputs/day16.txt\"));\n\n\n\n // 12883091136209\n\n println!(\"Final result: {}\", pr.read_packet());\n\n}\n", "file_path": "src/day16.rs", "rank": 29, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let mut im = Image::new(\"inputs/day20.txt\");\n\n\n\n im = im.enhance();\n\n im = im.enhance();\n\n println!(\"Lit pixels {}\", im.count_lit());\n\n}\n\n\n", "file_path": "src/day20.rs", "rank": 31, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n // Rust: the by_ref() tripped me up for a while.\n\n // I guess iterators which 'generate' rather than 'traverse' would\n\n // normally want this, but rust only has the one Trait for both...\n\n let mut dd: DetDie = Default::default();\n\n let dd = dd.by_ref();\n\n\n\n // Player 1 starting position: 8\n\n // Player 2 starting position: 6\n\n let mut p1 = Player::new(8);\n\n let mut p2 = Player::new(6);\n\n\n\n let losing_score = loop {\n\n p1.advance(dd.take(3).sum());\n\n if p1.score >= 1000 {\n\n break p2.score;\n\n }\n\n p2.advance(dd.take(3).sum());\n\n if p2.score >= 1000 {\n\n break p1.score;\n\n }\n\n };\n\n\n\n println!(\"Final result: {}\", dd.roll_count * losing_score);\n\n}\n\n\n", "file_path": "src/day21.rs", "rank": 32, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let grid = Grid::new(\"inputs/day05.txt\", false);\n\n\n\n println!(\"All danger points: {}\", grid.count_danger_points());\n\n}\n", "file_path": "src/day05.rs", "rank": 33, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let mut count = 0;\n\n let mut current = None;\n\n for value in read_int_list(\"inputs/day01.txt\").unwrap() {\n\n if let Some(old_val) = current {\n\n if old_val < value {\n\n count += 1;\n\n }\n\n }\n\n current = Some(value);\n\n }\n\n println!(\"Increment count: {}\", count);\n\n}\n\n\n", "file_path": "src/day01.rs", "rank": 34, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let hm = HeightMap::new(\"inputs/day09.txt\");\n\n\n\n println!(\"{}\", hm.risk_level());\n\n}\n\n\n", "file_path": "src/day09.rs", "rank": 35, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let nav = NavSystem::new(\"inputs/day10.txt\");\n\n\n\n println!(\"{}\", nav.autocomplete_score());\n\n}\n", "file_path": "src/day10.rs", "rank": 36, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let cg = CaveGraph::new(\"inputs/day12.txt\");\n\n\n\n cg.count_paths_alt();\n\n}\n", "file_path": "src/day12.rs", "rank": 37, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let mut max_mag = 0;\n\n for line1 in read_list(\"inputs/day18.txt\") {\n\n for line2 in read_list(\"inputs/day18.txt\") {\n\n if line1 == line2 {\n\n continue;\n\n }\n\n let mag = Sfn::from_str(&line1)\n\n .add(Sfn::from_str(&line2))\n\n .reduce()\n\n .magnitude();\n\n if mag > max_mag {\n\n max_mag = mag;\n\n }\n\n }\n\n }\n\n // 4616\n\n println!(\"Max Magnitude: {}\", max_mag);\n\n}\n\n\n", "file_path": "src/day18.rs", "rank": 38, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let mut game = Game::new(\"inputs/day04.txt\");\n\n\n\n println!(\"Winning score: {}\", game.play());\n\n}\n\n\n", "file_path": "src/day04.rs", "rank": 39, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let mut sim = LanternSim::new(\"inputs/day06.txt\");\n\n\n\n for _ in 0..80 {\n\n sim.step();\n\n }\n\n\n\n println!(\"Fish: {}\", sim.total_fish());\n\n}\n\n\n", "file_path": "src/day06.rs", "rank": 40, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let mut xpos = 0;\n\n let mut depth = 0;\n\n for instr in read_list(\"inputs/day02.txt\") {\n\n let mut instr_iter = instr.split_whitespace();\n\n let movement = instr_iter.next().unwrap();\n\n let amount: i32 = instr_iter.next().unwrap().parse().unwrap();\n\n match movement {\n\n \"up\" => depth -= amount,\n\n \"down\" => depth += amount,\n\n \"forward\" => xpos += amount,\n\n _ => ()\n\n }\n\n }\n\n println!(\"xpos * depth = {}\", xpos * depth);\n\n}\n\n\n", "file_path": "src/day02.rs", "rank": 41, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n // yes it is silly rebuilding this again for part2 since it's slow,\n\n // but I'm going for consistency of the 'framework'... :)\n\n let sm = ScannerMap::new(\"inputs/day19.txt\");\n\n\n\n let (_, offsets) = sm.build_map();\n\n\n\n let mut max_distance = 0;\n\n for s1 in &offsets {\n\n for s2 in &offsets {\n\n if s1 == s2 {\n\n continue;\n\n }\n\n let distance = s1.mdist(s2);\n\n if distance > max_distance {\n\n max_distance = distance;\n\n }\n\n }\n\n }\n\n println!(\"Max distance: {}\", max_distance);\n\n}\n", "file_path": "src/day19.rs", "rank": 42, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let grid = Grid::new(\"inputs/day05.txt\", true);\n\n\n\n println!(\"Orthogonal danger points: {}\", grid.count_danger_points());\n\n}\n\n\n", "file_path": "src/day05.rs", "rank": 44, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let mut reactor = Reactor::new(\"inputs/day22.txt\");\n\n\n\n reactor.evaluate(false);\n\n // 561032\n\n println!(\n\n \"total_volume (init only) {}\",\n\n reactor.regions.total_volume()\n\n );\n\n}\n\n\n", "file_path": "src/day22.rs", "rank": 45, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let mut result: Option<Sfn> = None;\n\n\n\n for line in read_list(\"inputs/day18.txt\") {\n\n let next_sfn = Sfn::from_str(&line);\n\n if let Some(sfn) = result {\n\n result = Some(sfn.add(next_sfn).reduce());\n\n } else {\n\n result = Some(next_sfn);\n\n }\n\n }\n\n\n\n // 3359\n\n println!(\"Magnitude: {}\", result.unwrap().magnitude());\n\n}\n\n\n", "file_path": "src/day18.rs", "rank": 46, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let nav = NavSystem::new(\"inputs/day10.txt\");\n\n\n\n println!(\"{}\", nav.syntax_error_score());\n\n}\n\n\n", "file_path": "src/day10.rs", "rank": 47, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let mut pd = PaperDots::new(\"inputs/day13.txt\");\n\n\n\n pd.fold_all();\n\n pd.draw();\n\n}\n", "file_path": "src/day13.rs", "rank": 48, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let mut reactor = Reactor::new(\"inputs/day22.txt\");\n\n\n\n reactor.evaluate(true);\n\n // 1322825263376414\n\n println!(\"total_volume {}\", reactor.regions.total_volume());\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_from_str() {\n\n let i = Instruction::from_str(\"on x=1..10,y=11..20,z=-21..30\");\n\n assert_eq!(i.r.x, (1, 10));\n\n assert_eq!(i.r.y, (11, 20));\n\n assert_eq!(i.r.z, (-21, 30));\n\n assert_eq!(i.on, true);\n\n }\n", "file_path": "src/day22.rs", "rank": 49, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n // Player 1 starting position: 8\n\n // Player 2 starting position: 6\n\n let mut p1_throw_ways = HashMap::new();\n\n let p1_complete = run_game(21, 8, 1, 0, &mut p1_throw_ways);\n\n println!(\"p1: {}\", p1_complete);\n\n println!(\"{:?}\", p1_throw_ways);\n\n\n\n let mut p2_throw_ways = HashMap::new();\n\n let p2_complete = run_game(21, 6, 1, 0, &mut p2_throw_ways);\n\n println!(\"p2: {}\", p2_complete);\n\n println!(\"{:?}\", p2_throw_ways);\n\n\n\n let mut p1_win_count = 0;\n\n let mut p2_win_count = 0;\n\n let mut total_universes_p1 = 1;\n\n let mut total_universes_p2 = 1;\n\n\n\n // 10 rounds is sufficient for this input data\n\n for round in 1..=10 {\n", "file_path": "src/day21.rs", "rank": 50, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let mut xpos = 0;\n\n let mut depth = 0;\n\n let mut aim = 0;\n\n for instr in read_list(\"inputs/day02.txt\") {\n\n let mut instr_iter = instr.split_whitespace();\n\n let movement = instr_iter.next().unwrap();\n\n let amount: i32 = instr_iter.next().unwrap().parse().unwrap();\n\n match movement {\n\n \"up\" => aim -= amount,\n\n \"down\" => aim += amount,\n\n \"forward\" => {\n\n xpos += amount;\n\n depth += aim * amount;\n\n }\n\n _ => ()\n\n }\n\n }\n\n println!(\"xpos * depth = {}\", xpos * depth);\n\n}\n", "file_path": "src/day02.rs", "rank": 51, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let mut sim = LanternSim::new(\"inputs/day06.txt\");\n\n\n\n for _ in 0..256 {\n\n sim.step();\n\n }\n\n\n\n println!(\"Fish: {}\", sim.total_fish());\n\n}\n", "file_path": "src/day06.rs", "rank": 52, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let mut om = OctoMap::new(\"inputs/day11.txt\");\n\n\n\n for _ in 0..100 {\n\n om.step();\n\n }\n\n\n\n println!(\"{}\", om.flash_count);\n\n}\n\n\n", "file_path": "src/day11.rs", "rank": 53, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let subs = CrabSumSwarm::new(\"inputs/day07.txt\");\n\n\n\n println!(\"Min Cost: {}\", subs.min_cost_naive(false));\n\n}\n\n\n", "file_path": "src/day07.rs", "rank": 54, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let subs = CrabSumSwarm::new(\"inputs/day07.txt\");\n\n\n\n println!(\"Min Cost - new calc: {}\", subs.min_cost_naive(true));\n\n}\n", "file_path": "src/day07.rs", "rank": 55, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let mut gamma = 0;\n\n let mut epsilon = 0;\n\n let mut one_count = [0; 12];\n\n let mut zero_count = [0; 12];\n\n for reading in read_list(\"inputs/day03.txt\") {\n\n for idx in 0..12 {\n\n match reading.as_str().chars().nth(idx) {\n\n Some('1') => one_count[idx] += 1,\n\n Some('0') => zero_count[idx] += 1,\n\n _ => ()\n\n }\n\n }\n\n }\n\n println!(\"one_count: {:?}\", one_count);\n\n println!(\"zero_count: {:?}\", zero_count);\n\n for idx in 0..12 {\n\n let bit = 11 - idx;\n\n if one_count[idx] > zero_count[idx] {\n\n gamma |= 1 << bit;\n\n } else {\n\n epsilon |= 1 << bit;\n\n }\n\n }\n\n println!(\"gamma: {:?}\", gamma);\n\n println!(\"epsilon: {:?}\", epsilon);\n\n println!(\"epsilon * gamma = {}\", gamma * epsilon);\n\n}\n\n\n", "file_path": "src/day03.rs", "rank": 56, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let mut pd = PaperDots::new(\"inputs/day13.txt\");\n\n\n\n let x = pd.instructions.get(0).unwrap();\n\n // Rust question - what's the 'deep-copy' equivalent for a Tuple?\n\n // or should I have pulled the tuple out to a struct deriving Clone?\n\n let x: (String, i32) = (x.0.clone(), x.1);\n\n pd.fold_step(&x);\n\n\n\n println!(\"{}\", pd.dots.len());\n\n}\n\n\n", "file_path": "src/day13.rs", "rank": 57, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let mut om = OctoMap::new(\"inputs/day11.txt\");\n\n let mut counter = 1; // pesky off-by-one errors...\n\n loop {\n\n if om.step() {\n\n break;\n\n }\n\n counter += 1;\n\n }\n\n\n\n println!(\"{}\", counter);\n\n}\n", "file_path": "src/day11.rs", "rank": 58, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let mut total = 0;\n\n\n\n assert!(\n\n 5353 == decode_entry(\n\n \"acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf\"\n\n )\n\n );\n\n\n\n for entry in read_list(\"inputs/day08.txt\") {\n\n total += decode_entry(&entry);\n\n }\n\n println!(\"Total: {}\", total);\n\n}\n", "file_path": "src/day08.rs", "rank": 59, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let hm = HeightMap::new(\"inputs/day09.txt\");\n\n\n\n println!(\"{}\", hm.biggest_basin_mult());\n\n}\n", "file_path": "src/day09.rs", "rank": 60, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let mut o2_rating = 0;\n\n let mut co2_rating = 0;\n\n\n\n // Part 2\n\n let mut o2_readings: Vec<Vec<_>> = read_list(\"inputs/day03.txt\").iter()\n\n .map(|l| l.as_str().chars().collect())\n\n .collect();\n\n\n\n //let mut co2_readings = o2_readings.clone();\n\n let mut co2_readings: Vec<Vec<_>> = read_list(\"inputs/day03.txt\").iter()\n\n .map(|l| l.as_str().chars().collect())\n\n .collect();\n\n\n\n let mut test_pos = 0;\n\n while o2_readings.len() > 1 && test_pos < 12 {\n\n // annoyance: why aren't vectors their own iterators?\n\n // e.g. iter/collect would be nice if inferred...\n\n //o2_readings = o2_readings.iter().filter(|r| criteria(r[test_pos]));\n\n //\n", "file_path": "src/day03.rs", "rank": 61, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let mut polymer = EfficientPolymer::new(\"inputs/day14.txt\");\n\n\n\n for _ in 0..40 {\n\n polymer.polymerize();\n\n }\n\n println!(\n\n \"{}\",\n\n polymer.most_common_count() - polymer.least_common_count()\n\n );\n\n}\n", "file_path": "src/day14.rs", "rank": 62, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let mut count = 0;\n\n for entry in read_list(\"inputs/day08.txt\") {\n\n let mut entry_parts = entry.split(\" | \");\n\n let _controls = entry_parts.next().unwrap();\n\n let outputs = entry_parts.next().unwrap();\n\n for out in outputs.split(' ') {\n\n match out.len() {\n\n 2 | 3 | 4 | 7 => count += 1,\n\n _ => (),\n\n }\n\n }\n\n }\n\n println!(\"Count: {}\", count);\n\n}\n\n\n", "file_path": "src/day08.rs", "rank": 63, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let mut polymer = Polymer::new(\"inputs/day14.txt\");\n\n\n\n for _ in 0..10 {\n\n polymer.polymerize();\n\n }\n\n println!(\n\n \"{}\",\n\n polymer.most_common_count() - polymer.least_common_count()\n\n );\n\n}\n\n\n", "file_path": "src/day14.rs", "rank": 64, "score": 99588.71722442278 }, { "content": "pub fn step2() {\n\n let mut probe = Probe::new(\"inputs/day17.txt\");\n\n\n\n // 968\n\n println!(\"Count: {}\", probe.count_good());\n\n}\n", "file_path": "src/day17.rs", "rank": 65, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let mut pr = PacketReader::new(read_hex_chars(\"inputs/day16.txt\"));\n\n\n\n let _ = pr.read_packet();\n\n // 967\n\n println!(\"Total version: {}\", pr.total_ver);\n\n}\n\n\n", "file_path": "src/day16.rs", "rank": 66, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let cg = CaveGraph::new(\"inputs/day12.txt\");\n\n\n\n cg.count_paths();\n\n}\n\n\n", "file_path": "src/day12.rs", "rank": 67, "score": 99588.71722442278 }, { "content": "pub fn step1() {\n\n let mut probe = Probe::new(\"inputs/day17.txt\");\n\n\n\n // 5151\n\n println!(\"Max height: {}\", probe.search());\n\n}\n\n\n", "file_path": "src/day17.rs", "rank": 68, "score": 99588.71722442278 }, { "content": "fn digitize(value: &str) -> u8 {\n\n let mut result = 0;\n\n for ch in value.chars() {\n\n match ch {\n\n 'a' => result |= 1,\n\n 'b' => result |= 2,\n\n 'c' => result |= 4,\n\n 'd' => result |= 8,\n\n 'e' => result |= 16,\n\n 'f' => result |= 32,\n\n 'g' => result |= 64,\n\n _ => unimplemented!(\"invalid char\"),\n\n }\n\n }\n\n result\n\n}\n\n\n", "file_path": "src/day08.rs", "rank": 69, "score": 89585.22592061377 }, { "content": "struct LineSpan {\n\n line: Line,\n\n cursor: Option<Point>,\n\n}\n\n\n\nimpl LineSpan {\n\n fn new(line: Line) -> Self {\n\n Self {\n\n line,\n\n cursor: Some(line.start),\n\n }\n\n }\n\n}\n\n\n\nimpl Iterator for LineSpan {\n\n type Item = Point;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n let item = self.cursor;\n\n if self.cursor == Some(self.line.end) {\n\n self.cursor = None;\n\n } else if let Some(mut cursor) = item {\n\n cursor.x += self.line.dx.signum();\n\n cursor.y += self.line.dy.signum();\n\n self.cursor = Some(cursor);\n\n }\n\n item\n\n }\n\n}\n\n\n", "file_path": "src/day05.rs", "rank": 71, "score": 84327.00013134381 }, { "content": "#[derive(Debug)]\n\nstruct Grid {\n\n lines: Vec<Line>,\n\n}\n\n\n\nimpl Grid {\n\n fn new(filename: &str, orthogonal: bool) -> Self {\n\n let mut lines = vec![];\n\n for line in read_list(filename) {\n\n let candidate = Line::from_line(&line);\n\n if !orthogonal || (candidate.is_horizontal() || candidate.is_vertical()) {\n\n lines.push(candidate);\n\n }\n\n }\n\n\n\n Self { lines }\n\n }\n\n\n\n fn count_danger_points(&self) -> i32 {\n\n let mut count = 0;\n\n let mut map = HashMap::new();\n", "file_path": "src/day05.rs", "rank": 72, "score": 57528.300099777334 }, { "content": "#[derive(Debug)]\n\nstruct Reactor {\n\n instructions: Vec<Instruction>,\n\n\n\n regions: RegionSet,\n\n}\n\n\n\nimpl Reactor {\n\n fn new(filename: &str) -> Self {\n\n let mut instructions = vec![];\n\n for line in read_list(filename) {\n\n let instr = Instruction::from_str(&line);\n\n instructions.push(instr);\n\n }\n\n\n\n let regions = RegionSet::new();\n\n\n\n Self {\n\n instructions,\n\n regions,\n\n }\n", "file_path": "src/day22.rs", "rank": 73, "score": 57528.300099777334 }, { "content": "#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]\n\nstruct Region {\n\n x: (i64, i64),\n\n y: (i64, i64),\n\n z: (i64, i64),\n\n}\n\n\n\nimpl Region {\n\n fn from_str(s: &str) -> Self {\n\n let mut extents = s.split(',');\n\n let x = extents.next().unwrap().strip_prefix(\"x=\").unwrap();\n\n let y = extents.next().unwrap().strip_prefix(\"y=\").unwrap();\n\n let z = extents.next().unwrap().strip_prefix(\"z=\").unwrap();\n\n\n\n let pairify = |v: Vec<i64>| {\n\n let mut vi = v.iter();\n\n (*vi.next().unwrap(), *vi.next().unwrap())\n\n };\n\n Region {\n\n x: pairify(x.split(\"..\").map(|v| v.parse::<i64>().unwrap()).collect()),\n\n y: pairify(y.split(\"..\").map(|v| v.parse::<i64>().unwrap()).collect()),\n", "file_path": "src/day22.rs", "rank": 74, "score": 57528.300099777334 }, { "content": "#[derive(Debug, Copy, Clone)]\n\nstruct Instruction {\n\n r: Region,\n\n on: bool,\n\n}\n\n\n\nimpl Instruction {\n\n fn from_str(s: &str) -> Self {\n\n let mut words = s.split_whitespace();\n\n let on = match words.next() {\n\n Some(\"on\") => true,\n\n Some(\"off\") => false,\n\n _ => panic!(\"Invalid region state\"),\n\n };\n\n let r = Region::from_str(words.next().unwrap());\n\n Instruction { r, on }\n\n }\n\n}\n\n\n", "file_path": "src/day22.rs", "rank": 75, "score": 57528.300099777334 }, { "content": "#[derive(Debug, Default)]\n\nstruct Probe {\n\n xpos: i32,\n\n ypos: i32,\n\n\n\n xvel: i32,\n\n yvel: i32,\n\n\n\n targetx: (i32, i32),\n\n targety: (i32, i32),\n\n max_height: i32,\n\n}\n\n\n\nimpl Probe {\n\n fn new(filename: &str) -> Self {\n\n let desc = &read_list(filename)[0];\n\n\n\n let mut parts = desc.split(' ');\n\n parts.next(); // 'target'\n\n parts.next(); // 'area:'\n\n let tx = parts.next().unwrap(); // xx..xx,\n", "file_path": "src/day17.rs", "rank": 76, "score": 57528.300099777334 }, { "content": "#[derive(Debug, Default, PartialEq, Clone)]\n\nstruct Scanner {\n\n beacons: HashSet<Delta>,\n\n\n\n ident: i32,\n\n}\n\n\n\nimpl Scanner {\n\n fn new(lines: Vec<String>, ident: i32) -> Self {\n\n let mut beacons = HashSet::new();\n\n for beacon in lines {\n\n let d: Delta = beacon\n\n .split(',')\n\n .map(|x| x.parse::<i32>().unwrap())\n\n .collect::<Vec<i32>>()\n\n .into();\n\n\n\n beacons.insert(d);\n\n }\n\n Self { beacons, ident }\n\n }\n", "file_path": "src/day19.rs", "rank": 77, "score": 57528.300099777334 }, { "content": "struct Player {\n\n position: i32,\n\n score: i32,\n\n}\n\n\n\nimpl Player {\n\n fn new(start: i32) -> Self {\n\n Self {\n\n position: (start - 1) % 10,\n\n score: 0,\n\n }\n\n }\n\n\n\n fn advance(&mut self, amount: i32) {\n\n self.position = (self.position + amount) % 10;\n\n self.score += self.position + 1; // position is zero-based\n\n }\n\n}\n\n\n", "file_path": "src/day21.rs", "rank": 78, "score": 57528.300099777334 }, { "content": "#[derive(Debug, Clone)]\n\nstruct Image {\n\n pixels: Vec<Vec<u8>>,\n\n algorithm: Vec<u8>,\n\n background: u8,\n\n line_width: usize,\n\n}\n\n\n\nimpl Image {\n\n fn new(filename: &str) -> Self {\n\n let mut pixels = vec![];\n\n let mut algorithm = vec![];\n\n let background = 0u8;\n\n let mut line_width = 0;\n\n\n\n for line in read_list(filename) {\n\n if line.is_empty() {\n\n continue;\n\n }\n\n if algorithm.is_empty() {\n\n algorithm = line\n", "file_path": "src/day20.rs", "rank": 79, "score": 57528.300099777334 }, { "content": "#[derive(Debug)]\n\nstruct Polymer {\n\n template: String,\n\n rules: HashMap<String, String>,\n\n}\n\n\n\nimpl Polymer {\n\n fn new(filename: &str) -> Self {\n\n let mut lines = read_list(filename).into_iter();\n\n\n\n let template = lines.next().unwrap();\n\n lines.next(); // skip blank line\n\n\n\n let mut rules = HashMap::new();\n\n for line in lines {\n\n let mut rule = line.split(\" -> \");\n\n let before = rule.next().unwrap();\n\n let after = rule.next().unwrap();\n\n\n\n // Rust: seems there's a choice between noisy 'to_string()'\n\n // everywhere or noisy lifetimes everywhere?\n", "file_path": "src/day14.rs", "rank": 80, "score": 57528.300099777334 }, { "content": "struct Game {\n\n boards: Vec<BingoBoard>,\n\n sequence: Vec<i32>,\n\n}\n\n\n\nimpl Game {\n\n fn new(filename: &str) -> Self {\n\n let mut boards = vec![];\n\n let mut sequence = vec![];\n\n let mut board: Vec<i32> = vec![];\n\n for (idx, line) in read_list(filename).iter().enumerate() {\n\n if idx == 0 {\n\n sequence = line.split(',').map(|x| x.parse::<i32>().unwrap()).collect();\n\n } else {\n\n if line.len() == 0 {\n\n continue;\n\n }\n\n board.extend::<Vec<i32>>(\n\n line.split_whitespace()\n\n .map(|x| x.parse::<i32>().unwrap())\n", "file_path": "src/day04.rs", "rank": 81, "score": 57528.300099777334 }, { "content": "#[derive(Debug, PartialEq, Clone, Copy, Hash, Eq)]\n\nstruct Point {\n\n pub x: i32,\n\n pub y: i32,\n\n}\n\n\n\nimpl Point {\n\n fn new(x: i32, y: i32) -> Self {\n\n Self { x, y }\n\n }\n\n}\n\n\n", "file_path": "src/day05.rs", "rank": 82, "score": 57528.300099777334 }, { "content": "#[derive(Debug)]\n\nstruct CaveGraph {\n\n // Using String here rather than &str to avoid caring about lifetimes.\n\n adj_map: HashMap<String, HashSet<String>>,\n\n}\n\n\n\nimpl CaveGraph {\n\n fn new(filename: &str) -> Self {\n\n let mut adj_map = HashMap::new();\n\n for line in read_list(filename) {\n\n // There must be a better way of 'splitting to a pair' (without\n\n // resorting to regex...)\n\n let mut line_parts = line.split('-');\n\n let from = line_parts.next().unwrap();\n\n let to = line_parts.next().unwrap();\n\n\n\n // since this is not a directed graph, add both directions\n\n let from_set = adj_map.entry(from.to_string()).or_insert_with(HashSet::new);\n\n from_set.insert(to.to_string());\n\n\n\n let to_set = adj_map.entry(to.to_string()).or_insert_with(HashSet::new);\n", "file_path": "src/day12.rs", "rank": 83, "score": 55943.23505148223 }, { "content": "struct PacketReader {\n\n bits: BitIter,\n\n total_ver: i128,\n\n bit_pos: i32,\n\n}\n\n\n\nimpl PacketReader {\n\n fn new(input: Vec<char>) -> Self {\n\n Self {\n\n bits: BitIter::new(input),\n\n total_ver: 0,\n\n bit_pos: 0,\n\n }\n\n }\n\n\n\n fn read_packet(&mut self) -> i128 {\n\n let pver = self.bits_value(3);\n\n self.total_ver += pver as i128;\n\n let ptype = self.bits_value(3);\n\n if ptype == 4 {\n", "file_path": "src/day16.rs", "rank": 84, "score": 55943.23505148223 }, { "content": "#[derive(Debug)]\n\nstruct NavSystem {\n\n lines: Vec<String>,\n\n}\n\n\n\nimpl NavSystem {\n\n fn new(filename: &str) -> Self {\n\n Self {\n\n lines: read_list(filename),\n\n }\n\n }\n\n\n\n // given line, return remaining stack and optional illegal character\n\n fn preprocess(&self, line: &str) -> (Vec<char>, Option<char>) {\n\n let mut stack = vec![];\n\n let mut illegal = None;\n\n for ch in line.chars() {\n\n match ch {\n\n '(' | '[' | '{' | '<' => stack.push(ch),\n\n // These following patterns are painful...\n\n ')' => {\n", "file_path": "src/day10.rs", "rank": 85, "score": 55943.23505148223 }, { "content": "struct BitIter {\n\n input: Box<dyn Iterator<Item = char>>,\n\n current_char: Option<u32>,\n\n nibble_offset: i32,\n\n}\n\n\n\nimpl BitIter {\n\n fn new(input: Vec<char>) -> Self {\n\n Self {\n\n input: Box::new(input.into_iter()),\n\n current_char: None,\n\n nibble_offset: 0,\n\n }\n\n }\n\n}\n\n\n\nimpl Iterator for BitIter {\n\n type Item = i32;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n", "file_path": "src/day16.rs", "rank": 86, "score": 55943.23505148223 }, { "content": "#[derive(Debug)]\n\nstruct EfficientPolymer {\n\n pair_count: HashMap<String, i64>,\n\n element_count: HashMap<char, i64>,\n\n rules: HashMap<String, String>,\n\n}\n\n\n\nimpl EfficientPolymer {\n\n fn new(filename: &str) -> Self {\n\n let mut lines = read_list(filename).into_iter();\n\n\n\n let mut pair_count = HashMap::new();\n\n let mut element_count = HashMap::new();\n\n\n\n let template = lines.next().unwrap();\n\n let mut ch_iter = template.chars();\n\n let mut last_ch = ch_iter.next().unwrap();\n\n\n\n // I missed this to begin with, resulting in an off-by-one error :(\n\n *element_count.entry(last_ch).or_insert(0) += 1;\n\n\n", "file_path": "src/day14.rs", "rank": 87, "score": 55943.23505148223 }, { "content": "#[derive(Debug)]\n\nstruct BingoBoard {\n\n numbers: Vec<i32>,\n\n // marked is a bitmap - bit 0 is the first (top-left) number\n\n marked: u32,\n\n}\n\n\n\nimpl BingoBoard {\n\n fn new(numbers: Vec<i32>) -> Self {\n\n Self { numbers, marked: 0 }\n\n }\n\n\n\n fn complete(&self) -> bool {\n\n let bingo_mask = vec![\n\n 0b00000_00000_00000_00000_11111,\n\n 0b00000_00000_00000_11111_00000,\n\n 0b00000_00000_11111_00000_00000,\n\n 0b00000_11111_00000_00000_00000,\n\n 0b11111_00000_00000_00000_00000,\n\n 0b00001_00001_00001_00001_00001,\n\n 0b00010_00010_00010_00010_00010,\n", "file_path": "src/day04.rs", "rank": 88, "score": 55943.23505148223 }, { "content": "#[derive(Debug)]\n\nstruct LanternSim {\n\n remaining: [usize; 9],\n\n}\n\n\n\nimpl LanternSim {\n\n fn new(filename: &str) -> Self {\n\n let fish = read_csv_ints(filename);\n\n let mut remaining = [0; 9];\n\n for f in fish {\n\n remaining[f] += 1;\n\n }\n\n Self {\n\n remaining\n\n }\n\n }\n\n\n\n fn step(&mut self) {\n\n let mut next_remaining = [0; 9];\n\n for idx in 0..9 {\n\n if idx == 0 {\n", "file_path": "src/day06.rs", "rank": 89, "score": 55943.23505148223 }, { "content": "#[derive(Default, Debug, Clone)]\n\nstruct DetDie {\n\n state: i32,\n\n roll_count: i32,\n\n}\n\n\n\nimpl Iterator for DetDie {\n\n type Item = i32;\n\n\n\n fn next(&mut self) -> Option<i32> {\n\n self.roll_count += 1;\n\n let value = self.state + 1;\n\n self.state = (self.state + 1) % 100;\n\n Some(value)\n\n }\n\n}\n\n\n", "file_path": "src/day21.rs", "rank": 90, "score": 55943.23505148223 }, { "content": "#[derive(Debug)]\n\nstruct OctoMap {\n\n energy: [[u8; 10]; 10],\n\n\n\n flash_count: i32,\n\n}\n\n\n\nimpl OctoMap {\n\n fn new(filename: &str) -> Self {\n\n let mut energy: [[u8; 10]; 10] = Default::default();\n\n for (idx, line) in read_list(filename).iter().enumerate() {\n\n energy[idx] = line\n\n .chars()\n\n .map(|x| x.to_string().parse::<u8>().unwrap())\n\n .collect::<Vec<u8>>()\n\n .try_into()\n\n .unwrap();\n\n }\n\n Self {\n\n energy,\n\n flash_count: 0,\n", "file_path": "src/day11.rs", "rank": 91, "score": 55943.23505148223 }, { "content": "#[derive(Debug)]\n\nstruct PaperDots {\n\n dots: HashSet<(i32, i32)>,\n\n\n\n instructions: Vec<(String, i32)>,\n\n}\n\n\n\nimpl PaperDots {\n\n fn new(filename: &str) -> Self {\n\n let mut dots = HashSet::new();\n\n let mut instructions = Vec::new();\n\n // Rust TIL: I've been using iter() too much when I should be using\n\n // into_iter()...\n\n let mut lines = read_list(filename).into_iter();\n\n // Rust TIL: iteration takes ownership of iterator, so can't just\n\n // re-use after break. Using `by_ref()` solves that.\n\n // https://stackoverflow.com/a/57172670\n\n for line in lines.by_ref() {\n\n if line.is_empty() {\n\n break;\n\n }\n", "file_path": "src/day13.rs", "rank": 92, "score": 55943.23505148223 }, { "content": "#[derive(Debug)]\n\nstruct HeightMap {\n\n height: Vec<Vec<u8>>,\n\n\n\n line_width: usize,\n\n}\n\n\n\nimpl HeightMap {\n\n fn new(filename: &str) -> Self {\n\n let mut height = vec![];\n\n let mut line_width = 0;\n\n for line in read_list(filename) {\n\n line_width = line.len(); // don't care about repeated setting\n\n height.push(\n\n line.chars()\n\n .map(|x| x.to_string().parse::<u8>().unwrap())\n\n .collect(),\n\n );\n\n }\n\n Self { height, line_width }\n\n }\n", "file_path": "src/day09.rs", "rank": 93, "score": 55943.23505148223 }, { "content": "#[derive(Debug)]\n\nstruct ScannerMap {\n\n scanners: Vec<Scanner>,\n\n}\n\n\n\nimpl ScannerMap {\n\n fn new(filename: &str) -> Self {\n\n let mut scanners: Vec<Scanner> = vec![];\n\n let mut delta_lines: Vec<String> = vec![];\n\n let mut s_id = 0;\n\n for line in read_list(filename) {\n\n if line.starts_with(\"---\") {\n\n delta_lines = vec![];\n\n } else if line.is_empty() {\n\n scanners.push(Scanner::new(delta_lines.clone(), s_id));\n\n s_id += 1;\n\n } else {\n\n delta_lines.push(line);\n\n }\n\n }\n\n // don't forget the last set of data\n", "file_path": "src/day19.rs", "rank": 94, "score": 55943.23505148223 }, { "content": "#[derive(Debug)]\n\nstruct RegionSet {\n\n regions: HashSet<Region>,\n\n}\n\n\n\nimpl RegionSet {\n\n fn new() -> Self {\n\n Self {\n\n regions: HashSet::new(),\n\n }\n\n }\n\n\n\n fn total_volume(&self) -> i64 {\n\n self.check_disjoint();\n\n self.regions.iter().map(|r| r.volume()).sum()\n\n }\n\n\n\n fn check_disjoint(&self) {\n\n for r in &self.regions {\n\n for s in &self.regions {\n\n if s == r {\n", "file_path": "src/day22.rs", "rank": 95, "score": 55943.23505148223 }, { "content": "#[derive(Debug)]\n\nstruct CrabSumSwarm {\n\n crabsubs: Vec<i32>,\n\n}\n\n\n\nimpl CrabSumSwarm {\n\n fn new(filename: &str) -> Self {\n\n let crabsubs = read_csv_ints(filename);\n\n Self { crabsubs }\n\n }\n\n\n\n fn cost(&self, pos: i32) -> i32 {\n\n let mut total = 0;\n\n for cs in &self.crabsubs {\n\n total += (cs - pos).abs();\n\n }\n\n total\n\n }\n\n\n\n fn cost_2(&self, pos: i32) -> i32 {\n\n let mut total = 0;\n", "file_path": "src/day07.rs", "rank": 96, "score": 54520.70545893235 }, { "content": "fn main() {\n\n day22::step1();\n\n day22::step2();\n\n}\n", "file_path": "src/main.rs", "rank": 97, "score": 53632.999195697426 }, { "content": "fn run_game(\n\n remain: i32,\n\n pos: i32,\n\n ways: i128,\n\n throw_count: i32,\n\n throw_way_map: &mut HashMap<i32, i128>,\n\n) -> i128 {\n\n let roll_dist: HashMap<i32, i128> =\n\n HashMap::from_iter([(3, 1), (4, 3), (5, 6), (6, 7), (7, 6), (8, 3), (9, 1)]);\n\n\n\n if remain > 0 {\n\n let mut new_ways = 0;\n\n for roll_sum in 3..=9 {\n\n let possibilities = roll_dist.get(&roll_sum).unwrap();\n\n let new_pos = ((pos - 1) + roll_sum) % 10 + 1;\n\n new_ways += run_game(\n\n remain - new_pos,\n\n new_pos,\n\n ways * possibilities,\n\n throw_count + 1,\n", "file_path": "src/day21.rs", "rank": 98, "score": 52113.14182712945 } ]
Rust
src/day25.rs
marty777/adventofcode2019
b2edc81b6f50ea3d0f64c056d8e9617d3ef6424d
use std::collections::HashMap; #[derive(PartialEq, Copy, Clone)] enum Dir { North, East, South, West, } struct TextNode { north: i64, east: i64, west: i64, south: i64, name: String, explored:bool, dest:bool, } #[derive(Clone)] struct DNode { dist:usize, path:Vec<Dir> } fn dijkstra(nodes: &mut Vec<TextNode>, start:usize, end:usize, error:&mut bool)->Dir { *error = false; let mut frontier:HashMap<usize, DNode> = HashMap::new(); let mut frontier_next:HashMap<usize, DNode> = HashMap::new(); let mut explored:HashMap<usize, DNode> = HashMap::new(); frontier_next.insert(start, DNode{dist:0, path:Vec::new()}); while frontier_next.len() > 0 { frontier.clear(); for key in frontier_next.keys() { let node = frontier_next.get(key).unwrap(); let node2 = (*node).clone(); frontier.insert(*key, node2); } frontier_next.clear(); for key in frontier.keys() { let node = frontier.get(key).unwrap(); if *key == end { if (*node).path.len() > 0 { let path_index = 0; return (*node).path[path_index]; } else { *error = true; return Dir::North; } } if let Some(explored_node) = explored.get_mut(key) { if (*explored_node).dist > (*node).dist { (*explored_node).path.clear(); for i in 0..(*node).path.len() { (*explored_node).path.push((*node).path[i]); } (*explored_node).dist = (*node).dist; } } else { let new_node = (*node).clone(); explored.insert(*key, new_node); } if (*nodes)[*key].north >= 0 { let next_index = (*nodes)[*key].north as usize; if !explored.contains_key(&next_index) { let mut path:Vec<Dir> = Vec::new(); let dist = (*node).dist + 1; for i in 0..(*node).path.len() { path.push((*node).path[i]); } path.push(Dir::North); frontier_next.insert(next_index, DNode{dist: dist, path:path}); } } if (*nodes)[*key].east >= 0 { let next_index = (*nodes)[*key].east as usize; if !explored.contains_key(&next_index) { let mut path:Vec<Dir> = Vec::new(); let dist = (*node).dist + 1; for i in 0..(*node).path.len() { path.push((*node).path[i]); } path.push(Dir::East); frontier_next.insert(next_index, DNode{dist: dist, path:path}); } } if (*nodes)[*key].south >= 0 { let next_index = (*nodes)[*key].south as usize; if !explored.contains_key(&next_index) { let mut path:Vec<Dir> = Vec::new(); let dist = (*node).dist + 1; for i in 0..(*node).path.len() { path.push((*node).path[i]); } path.push(Dir::South); frontier_next.insert(next_index, DNode{dist: dist, path:path}); } } if (*nodes)[*key].west >= 0 { let next_index = (*nodes)[*key].west as usize; if !explored.contains_key(&next_index) { let mut path:Vec<Dir> = Vec::new(); let dist = (*node).dist + 1; for i in 0..(*node).path.len() { path.push((*node).path[i]); } path.push(Dir::West); frontier_next.insert(next_index, DNode{dist: dist, path:path}); } } } } return Dir::North; } fn read_node(nodes:&mut Vec<TextNode>, input:String, index:usize, items: &mut Vec<String>) { let lines:Vec<&str> = input.as_str().split(10 as char).collect(); let mut mode = 0; if nodes[index].explored { return; } for i in 0..lines.len() { let bytes = lines[i].as_bytes(); if bytes.len() < 2 { continue; } if mode == 0 && bytes[0] == '=' as u8 && bytes[1] == '=' as u8{ let mut str_index:usize = 2; for _j in 0..bytes.len() { if bytes[str_index] != '=' as u8 { str_index += 1; } else { break; } } let name = String::from(&lines[i][3..(str_index-1)]); (*nodes)[index].name = name; mode += 1; } else if mode == 1 { if lines[i] == "Doors here lead:" { mode += 1; } } else if mode == 2 { if lines[i] == "Items here:" { mode += 1; continue; } let mut dest = false; if (*nodes)[index].name == "Security Checkpoint" { dest = true; } if lines[i] == "- north" { if (*nodes)[index].north == -1 { (*nodes).push(TextNode{north:-1, east:-1, south:index as i64, west:-1, name:String::from("unknown"), explored:false, dest:dest}); (*nodes)[index].north = ((*nodes).len() - 1) as i64; } } else if lines[i] == "- east" { if (*nodes)[index].east == -1 { (*nodes).push(TextNode{north:-1, east:-1, south:-1, west:index as i64, name:String::from("unknown"), explored:false, dest:dest}); (*nodes)[index].east = ((*nodes).len() - 1) as i64; } } else if lines[i] == "- south" { if (*nodes)[index].south == -1 { (*nodes).push(TextNode{north:index as i64, east:-1, south:-1, west:-1, name:String::from("unknown"), explored:false, dest:dest}); (*nodes)[index].south = ((*nodes).len() - 1) as i64; } } else if lines[i] == "- west" { if (*nodes)[index].west == -1 { (*nodes).push(TextNode{north:-1, east:index as i64, south:-1, west:-1, name:String::from("unknown"), explored:false, dest:dest}); (*nodes)[index].west = ((*nodes).len() - 1) as i64; } } } else if mode == 3 { if &lines[i][0..2] != "- " { mode += 1; } else { (*items).push(String::from(&lines[i][2..])); } } else { continue; } } (*nodes)[index].explored = true; } fn run_command(prog:&mut super::utility::IntcodeProgram, command:&String, exit:&mut bool, verbose:bool)->String { let mut in_buffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0}; let mut out_buffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0}; let mut exit1:bool = false; if command.len() > 0 { let bytes = (*command).as_bytes(); in_buffer.buff.clear(); in_buffer.read_pos = 0; in_buffer.write_pos = 0; for i in 0..bytes.len() { if bytes[i] == 13 { continue; } in_buffer.buff.push(bytes[i] as i64); } if bytes[bytes.len() - 1] != 10 { in_buffer.buff.push(10); } in_buffer.write_pos = in_buffer.buff.len() - 1; } super::utility::intcode_execute(prog, &mut in_buffer, &mut out_buffer, &mut exit1); (*exit) = exit1; let mut ret:String = String::from(""); for i in out_buffer.read_pos..out_buffer.write_pos { ret.push(out_buffer.buff[i] as u8 as char); } if verbose { println!("##### RUN COMMAND #####"); println!("INPUT: {}", *command); println!("OUTPUT:\n{}\n###############", ret); } return ret; } fn run_text_adventure(prog:&mut super::utility::IntcodeProgram) { let mut nodes:Vec<TextNode> = Vec::new(); let mut exit:bool = false; let mut dangerous_goods:Vec<String> = Vec::new(); dangerous_goods.push(String::from("escape pod")); dangerous_goods.push(String::from("giant electromagnet")); dangerous_goods.push(String::from("infinite loop")); dangerous_goods.push(String::from("photons")); dangerous_goods.push(String::from("molten lava")); let mut inventory:Vec<String> = Vec::new(); let blank_string = String::from(""); let result = run_command(prog, &blank_string, &mut exit, false); nodes.push(TextNode{north:-1, east:-1, south:-1, west:-1, name:String::from("unexplored"), explored:false, dest:false}); let mut items:Vec<String> = Vec::new(); read_node(&mut nodes, result, 0, &mut items); let mut curr_index = 0; let mut unexplored = 0; for i in 0..nodes.len() { if !nodes[i].explored && !nodes[i].dest { unexplored += 1; } } while unexplored > 0 { let mut dest_index = 0; for i in 0..nodes.len() { if !nodes[i].explored && !nodes[i].dest { dest_index = i; break; } } let mut error:bool = false; let next_dir = dijkstra(&mut nodes, curr_index, dest_index, &mut error); if error { println!("Pathfinding error between indexes {} and {}", curr_index, dest_index); break; } let move_command:String; let next_index:usize; match next_dir { Dir::North=>{move_command = String::from("north"); next_index = nodes[curr_index].north as usize}, Dir::East=>{move_command = String::from("east"); next_index = nodes[curr_index].east as usize}, Dir::South=>{move_command = String::from("south"); next_index = nodes[curr_index].south as usize}, _=>{move_command = String::from("west"); next_index = nodes[curr_index].west as usize}, } let result1 = run_command(prog, &move_command, &mut exit, false); if exit { println!("Program exited with output:\n{}\non command: {}", result1, move_command); break; } let mut items1:Vec<String> = Vec::new(); read_node(&mut nodes, result1, next_index, &mut items1); curr_index = next_index; for i in 0..items1.len() { let mut dangerous:bool = false; for j in 0..dangerous_goods.len() { if items1[i] == dangerous_goods[j] { dangerous = true; break; } } if !dangerous { let mut take_command = String::from("take "); take_command.push_str(items1[i].as_str()); let result2 = run_command(prog, &take_command, &mut exit, false); if exit { println!("Program exited with output:\n{}\non command: {}", result2, take_command); return; } let new_string = String::from(items1[i].as_str()); inventory.push(new_string); } } unexplored = 0; for i in 0..nodes.len() { if !nodes[i].explored && !nodes[i].dest { unexplored += 1; } } } let mut dest_index:usize = 0; let mut security_index:usize = 0; for i in 0..nodes.len() { if nodes[i].dest { dest_index = i; } else if nodes[i].name == "Security Checkpoint"{ security_index = i; } } while curr_index != security_index { let mut error:bool = false; let next_dir = dijkstra(&mut nodes, curr_index, security_index, &mut error); if error { println!("Pathfinding error between indexes {} and {}", curr_index, dest_index); return; } let move_command:String; let next_index:usize; match next_dir { Dir::North=>{move_command = String::from("north"); next_index = nodes[curr_index].north as usize}, Dir::East=>{move_command = String::from("east"); next_index = nodes[curr_index].east as usize}, Dir::South=>{move_command = String::from("south"); next_index = nodes[curr_index].south as usize}, _=>{move_command = String::from("west"); next_index = nodes[curr_index].west as usize}, } let result1 = run_command(prog, &move_command, &mut exit, false); if exit { println!("Program exited with output:\n{}\non command: {}", result1, move_command); return; } curr_index = next_index; } let end_dir_command:String; if nodes[security_index].north == dest_index as i64 { end_dir_command = String::from("north"); } else if nodes[security_index].east == dest_index as i64 { end_dir_command = String::from("east"); } else if nodes[security_index].south == dest_index as i64 { end_dir_command = String::from("south"); } else { end_dir_command = String::from("west"); } let mut state:Vec<bool> = Vec::new(); for _i in 0..inventory.len() { state.push(true); } for i in 1..256 { for j in 0..state.len() { let mut have = false; if i >> j & 0x01 == 1 { have = true; } if have && !state[j] { let mut command = String::from("take "); command.insert_str(5, inventory[j].as_str()); run_command(prog, &command, &mut exit, false); } else if !have && state[j] { let mut command = String::from("drop "); command.insert_str(5, inventory[j].as_str()); run_command(prog, &command, &mut exit, false); } state[j] = have; } let result = run_command(prog, &end_dir_command, &mut exit, false); if result.contains("heavier") || result.contains("lighter") { continue; } else { let mut digits:Vec<u8> = Vec::new(); let bytes = result.as_bytes(); for i in 0..bytes.len() { if bytes[i] >= '0' as u8 && bytes[i] <= '9' as u8 { digits.push(bytes[i]); } } print!("Result: "); for i in 0..digits.len() { print!("{}", digits[i] as char); } println!(); break; } } } pub fn run(file_path:&str) { let vec = super::utility::util_fread(file_path); let intcodes_str:Vec<&str> = vec[0].split(",").collect(); let mut prog:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0}; prog.mem.reserve(intcodes_str.len()); for code in intcodes_str { let temp: i64 = code.parse::<i64>().unwrap(); prog.mem.push(temp); } run_text_adventure(&mut prog); }
use std::collections::HashMap; #[derive(PartialEq, Copy, Clone)] enum Dir { North, East, South, West, } struct TextNode { north: i64, east: i64, west: i64, south: i64, name: String, explored:bool, dest:bool, } #[derive(Clone)] struct DNode { dist:usize, path:Vec<Dir> } fn dijkstra(nodes: &mut Vec<TextNode>, start:usize, end:usize, error:&mut bool)->Dir { *error = false; let mut frontier:HashMap<usize, DNode> = HashMap::new(); let mut frontier_next:HashMap<usize, DNode> = HashMap::new(); let mut explored:HashMap<usize, DNode> = HashMap::new(); frontier_next.insert(start, DNode{dist:0, path:Vec::new()}); while frontier_next.len() > 0 { frontier.clear(); for key in frontier_next.keys() { let node = frontier_next.get(key).unwrap(); let node2 = (*node).clone(); frontier.insert(*key, node2); } frontier_next.clear(); for key in frontier.keys() { let node = frontier.get(key).unwrap(); if *key == end { if (*node).path.len() > 0 { let path_index = 0; return (*node).path[path_index]; } else { *error = true; return Dir::North; } } if let Some(explored_node) = explored.get_mut(key) { if (*explored_node).dist > (*node).dist { (*explored_node).path.clear(); for i in 0..(*node).path.len() { (*explored_node).path.push((*node).path[i]); } (*explored_node).dist = (*node).dist; } } else { let new_node = (*node).clone(); explored.insert(*key, new_node); } if (*nodes)[*key].north >= 0 { let next_index = (*nodes)[*key].north as usize; if !explored.contains_key(&next_index) { let mut path:Vec<Dir> = Vec::new(); let dist = (*node).dist + 1; for i in 0..(*node).path.len() { path.push((*node).path[i]); } path.push(Dir::North); frontier_next.insert(next_index, DNode{dist: dist, path:path}); } } if (*nodes)[*key].east >= 0 { let next_index = (*nodes)[*key].east as usize; if !explored.contains_key(&next_index) { let mut path:Vec<Dir> = Vec::new(); let dist = (*node).dist + 1; for i in 0..(*node).path.len() { path.push((*node).path[i]); } path.push(Dir::East); frontier_next.insert(next_index, DNode{dist: dist, path:path}); } } if (*nodes)[*key].south >= 0 { let next_index = (*nodes)[*key].south as usize; if !explored.contains_key(&next_index) { let mut path:Vec<Dir> = Vec::new(); let dist = (*node).dist + 1; for i in 0..(*node).path.len() { path.push((*node).path[i]); } path.push(Dir::South); frontier_next.insert(next_index, DNode{dist: dist, path:path}); } } if (*nodes)[*key].west >= 0 { let next_index = (*nodes)[*key].west as usize; if !explored.contains_key(&next_index) { let mut path:Vec<Dir> = Vec::new(); let dist = (*node).dist + 1; for i in 0..(*node).path.len() { path.push((*node).path[i]); } path.push(Dir::West); frontier_next.insert(next_index, DNode{dist: dist, path:path}); } } } } return Dir::North; } fn read_node(nodes:&mut Vec<TextNode>, input:String, index:usize, items: &mut Vec<String>) { let lines:Vec<&str> = input.as_str().split(10 as char).collect(); let mut mode = 0; if nodes[index].explored { return; } for i in 0..lines.len() { let bytes = lines[i].as_bytes(); if bytes.len() < 2 { continue; } if mode == 0 && bytes[0] == '=' as u8 && bytes[1] == '=' as u8{ let mut str_index:usize = 2; for _j in 0..bytes.len() { if bytes[str_index] != '=' as u8 { str_index += 1; } else { break; } } let name = String::from(&lines[i][3..(str_index-1)]); (*nodes)[index].name = name; mode += 1; } else if mode == 1 { if lines[i] == "Doors here lead:" { mode += 1; } } else if mode == 2 { if lines[i] == "Items here:" { mode += 1; continue; } let mut dest = false; if (*nodes)[index].name == "Security Checkpoint" { dest = true; } if lines[i] == "- north" { if (*nodes)[index].north == -1 { (*nodes).push(TextNode{north:-1, east:-1, south:index as i64, west:-1, name:String::from("unknown"), explored:false, dest:dest}); (*nodes)[index].north = ((*nodes).len() - 1) as i64; } } else if lines[i] == "- east" { if (*nodes)[index].east == -1 { (*nodes).push(TextNode{north:-1, east:-1, south:-1, west:index as i64, name:String::from("unknown"), explored:false, dest:dest}); (*nodes)[index].east = ((*nodes).len() - 1) as i64; } } else if lines[i] == "- south" { if (*nodes)[index].south == -1 { (*nodes).push(TextNode{north:index as i64, east:-1, south:-1, west:-1, name:String::from("unknown"), explored:false, dest:dest}); (*nodes)[index].south = ((*nodes).len() - 1) as i64; } } else if lines[i] == "- west" { if (*nodes)[index].west == -1 { (*nodes).push(TextNode{north:-1, east:index as i64, south:-1, west:-1, name:String::from("unknown"), explored:false, dest:dest}); (*nodes)[index].west = ((*nodes).len() - 1) as i64; } } } else if mode == 3 { if &lines[i][0..2] != "- " { mode += 1; } else { (*items).push(String::from(&lines[i][2..])); } } else { continue; } } (*nodes)[index].explored = true; } fn run_command(prog:&mut super::utility::IntcodeProgram, command:&String, exit:&mut bool, verbose:bool)->String { let mut in_buffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0}; let mut out_buffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0}; let mut exit1:bool = false; if command.len() > 0 { let bytes = (*command).as_bytes(); in_buffer.buff.clear(); in_buffer.read_pos = 0; in_buffer.write_pos = 0; for i in 0..bytes.len() { if bytes[i] == 13 { continue; } in_buffer.buff.push(bytes[i] as i64); } if bytes[bytes.len() - 1] != 10 { in_buffer.buff.push(10); } in_buffer.write_pos = in_buffer.buff.len() - 1; } super::utility::intcode_execute(prog, &mut in_buffer, &mut out_buffer, &mut exit1); (*exit) = exit1; let mut ret:String = String::from(""); for i in out_buffer.read_pos..out_buffer.write_pos { ret.push(out_buffer.buff[i] as u8 as char); } if verbose { println!("##### RUN COMMAND #####"); println!("INPUT: {}", *command); println!("OUTPUT:\n{}\n###############", ret); } return ret; } fn run_text_adventure(prog:&mut super::utility::IntcodeProgram) { let mut nodes:Vec<TextNode> = Vec::new(); let mut exit:bool = false; let mut dangerous_goods:Vec<String> = Vec::new(); dangerous_goods.push(String::from("escape pod")); dangerous_goods.push(String::from("giant electromagnet")); dangerous_goods.push(String::from("infinite loop")); dangerous_goods.push(String::from("photons")); dangerous_goods.push(String::from("molten lava")); let mut inventory:Vec<String> = Vec::new(); let blank_string = String::from(""); let result = run_command(prog, &blank_string, &mut exit, false); nodes.push(TextNode{north:-1, east:-1, south:-1, west:-1, name:String::from("unexplored"), explored:false, dest:false}); let mut items:Vec<String> = Vec::new(); read_node(&mut nodes, result, 0, &mut items); let mut curr_index = 0; let mut unexplored = 0; for i in 0..nodes.len() { if !nodes[i].explored && !nodes[i].dest { unexplored += 1; } } while unexplored > 0 { let mut dest_index = 0; for i in 0..nodes.len() { if !nodes[i].explored && !nodes[i].dest { dest_index = i; break; } } let mut error:bool = false; let next_dir = dijkstra(&mut nodes, curr_index, dest_index, &mut error); if error { println!("Pathfinding error between indexes {} and {}", curr_index, dest_index); break; } let move_command:String; let next_index:usize; match next_dir { Dir::North=>{move_command = String::from("north"); next_index = nodes[curr_index].north as usize}, Dir::East=>{move_command = String::from("east"); next_index = nodes[curr_index].east as usize}, Dir::South=>{move_command = String::from("south"); next_index = nodes[curr_index].south as usize}, _=>{move_command = String::from("west"); next_index = nodes[curr_index].west as usize}, } let result1 = run_command(prog, &move_command, &mut exit, false); if exit { println!("Program exited with output:\n{}\non command: {}", result1, move_command); break; } let mut items1:Vec<String> = Vec::new(); read_node(&mut nodes, result1, next_index, &mut items1); curr_index = next_index; for i in 0..items1.len() { let mut dangerous:bool = false; for j in 0..dangerous_goods.len() { if items1[i] == dangerous_goods[j] { dangerous = true; break; } } if !dangerous { let mut take_command = String::from("take "); take_command.push_str(items1[i].as_str()); let result2 = run_command(prog, &take_command, &mut exit, false); if exit { println!("Program exited with output:\n{}\non command: {}", result2, take_command); return; } let new_string = String::from(items1[i].as_str()); inventory.push(new_string); } } unexplored = 0; for i in 0..nodes.len() { if !nodes[i].explored && !nodes[i].dest { unexplored += 1; } } } let mut dest_index:usize = 0; let mut security_index:usize = 0; for i in 0..nodes.len() { if nodes[i].dest { dest_index = i; } else if nodes[i].name == "Security Checkpoint"{ security_index = i; } } while curr_index != security_index { let mut error:bool = false; let next_dir = dijkstra(&mut nodes, curr_index, security_index, &mut error); if error { println!("Pathfinding error between indexes {} and {}", curr_index, dest_index); return; } let move_command:String; let next_index:usize; match next_dir { Dir::North=>{move_command = String::from("north"); next_index = nodes[curr_index].north as usize}, Dir::East=>{move_command = String::from("east"); next_index = nodes[curr_index].east as usize}, Dir::South=>{move_command = String::from("south"); next_index = nodes[curr_index].south as usize}, _=>{move_command = String::from("west"); next_index = nodes[curr_index].west as usize}, } let result1 = run_command(prog, &move_command, &mut exit, false); if exit { println!("Program exited with output:\n{}\non command: {}", result1, move_command); return; } curr_index = next_index; } let end_dir_command:String; if nodes[security_index].north == dest_index as i64 { end_dir_command = String::from("north"); } else if nodes[security_index].east == dest_index as i64 { end_dir_command = String::from("east"); } else if nodes[security_index].south == dest_index as i64 { end_dir_command = String::from("south"); } else { end_dir_command = String::from("west"); } let mut state:Vec<bool> = Vec::new(); for _i in 0..inventory.len() { state.push(true); } for i in 1..256 { for j in 0..state.len() { let mut have = false; if i >> j & 0x01 == 1 { have = true; } if have && !state[j] { let mut command = String::from("take "); command.insert_str(5, inventory[j].as_str()); run_command(prog, &command, &mut exit, false); } else if !have && state[j] { let mut command = String::from("drop "); command.insert_str(5, inventory[j].as_str()); run_command(prog, &command, &mut exit, false); } state[j] = have; } let result = run_command(prog, &end_dir_command, &mut exit, false); if result.contains("heavier") || result.contains("lighter") { continue; } else { let mut digits:Vec<u8> = Vec::new(); let bytes = result.as_bytes(); for i in 0..bytes.len() { if bytes[i] >= '0' as u8 && bytes[i] <= '9' as u8 { digits.push(bytes[i]); } } print!("Result: "); for i in 0..digits.len() { print!("{}", digits[i] as char); } println!(); break; } } } pub fn run(file_path:&str) { l
: i64 = code.parse::<i64>().unwrap(); prog.mem.push(temp); } run_text_adventure(&mut prog); }
et vec = super::utility::util_fread(file_path); let intcodes_str:Vec<&str> = vec[0].split(",").collect(); let mut prog:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0}; prog.mem.reserve(intcodes_str.len()); for code in intcodes_str { let temp
function_block-random_span
[ { "content": "pub fn execute_amp2(intcodes: &mut Vec<i64>, input_signal:i64, phase:i64, input_count:&mut u64, pos: &mut usize, exit:&mut bool) -> i64 {\n\n\tlet mut op_pos: usize = *pos;\n\n\tlet mut output:i64 = 0;\n\n\tlet mut input_signal_used = false;\n\n\tlet mut exit_found = false;\n\n\tloop {\n\n\t\tlet opcode = intcodes[op_pos] % 100;\n\n\t\tlet mode1 = ((intcodes[op_pos] - opcode) % 1000)/100;\n\n\t\tlet mode2 = ((intcodes[op_pos] - opcode - 100*mode1) % 10000)/1000;\n\n\t\tlet _mode3 = ((intcodes[op_pos] - opcode - 100*mode1 - 1000*mode2) % 100000)/10000; // presumably this will be used in future opcodes. Unused at the moment.\n\n\t\t\n\n\t\tmatch opcode {\n\n\t\t\t1 => { // add\n\n\t\t\t\tlet param1 = intcodes[op_pos + 1];\n\n\t\t\t\tlet param2 = intcodes[op_pos + 2];\n\n\t\t\t\tlet param3 = intcodes[op_pos + 3];\n\n\t\t\t\tintcodes[param3 as usize] = (if mode1 == 1 {param1} else {intcodes[param1 as usize]} ) + (if mode2 == 1 {param2} else {intcodes[param2 as usize]} );\n\n\t\t\t\top_pos += 4;\n\n\t\t\t},\n\n\t\t\t2 => { // mul \n", "file_path": "src/day7.rs", "rank": 2, "score": 210651.7697645728 }, { "content": "fn dijkstra_a(maze: &mut Maze, start_x:usize, start_y:usize, end_x:usize, end_y:usize, doors:&mut Vec<usize>, keys:&mut Vec<usize>, ret_doors_keys:bool)->i64 {\n\n\tlet mut explored:HashMap<usize, DNode> = HashMap::new();\n\n\t\n\n\tlet mut frontier:HashMap<usize,DNode> = HashMap::new();\n\n\tlet mut frontier_next:HashMap<usize,DNode> = HashMap::new();\n\n\t\n\n\tfrontier_next.insert(exploredindex(maze, start_x, start_y), DNode{x:start_x, y:start_y, dist:0, parent_x:start_x, parent_y:start_y});\n\n\t\n\n\tlet dest_key = exploredindex(maze, end_x, end_y);\n\n\t\n\n\twhile frontier_next.len() > 0 {\n\n\t\t\n\n\t\tfrontier.clear();\n\n\t\tfor key in frontier_next.keys() {\n\n\t\t\tlet node = frontier_next.get(key).unwrap();\n\n\t\t\tlet new_node = (*node).clone();\n\n\t\t\tfrontier.insert(*key, new_node);\n\n\t\t}\n\n\t\tfrontier_next.clear();\n\n\t\t\n", "file_path": "src/day18.rs", "rank": 3, "score": 210207.09699771344 }, { "content": "pub fn intcode_execute_once(prog: &mut IntcodeProgram, input:&mut IOBuffer, output:&mut IOBuffer, exit:&mut bool, io_wait:&mut bool, error: &mut bool) {\n\n\tlet mut err:bool = false;\n\n\t\n\n\tlet memval = get(prog, (*prog).pos, 1, &mut err);\n\n\tlet opcode = memval % 100;\n\n\tlet mode1 = ((memval - opcode) % 1000)/100;\n\n\tlet mode2 = ((memval - opcode - 100*mode1) % 10000)/1000;\n\n\tlet mode3 = ((memval - opcode - 100*mode1 - 1000*mode2) % 100000)/10000; // presumably this will be used in future opcodes. Unused at the moment.\n\n\t\n\n\t\n\n\tmatch opcode {\n\n\t\t1 => { // add\n\n\t\t\tlet param1 = get(prog, (*prog).pos + 1, mode1, &mut err);\n\n\t\t\tlet param2 = get(prog, (*prog).pos + 2, mode2, &mut err);\n\n\t\t\t\n\n\t\t\tlet val = param1 + param2;\n\n\t\t\tset(prog, (*prog).pos + 3, mode3, val, &mut err);\n\n\t\t\t\n\n\t\t\t(*prog).pos += 4;\n\n\t\t},\n", "file_path": "src/utility.rs", "rank": 4, "score": 199979.68039500632 }, { "content": "fn grid_has_scaffold(grid:&mut Vec<u8>, x:i64, y:i64, width:usize, height:usize)->bool{\n\n\tif x < 0 || x >= (width as i64) {\n\n\t\treturn false;\n\n\t}\n\n\tif y < 0 || y >= (height as i64) {\n\n\t\treturn false;\n\n\t}\n\n\tif (*grid)[((y*(width as i64)) + x) as usize] == 35 {\n\n\t\treturn true;\n\n\t}\n\n\treturn false;\n\n}\n\n\n", "file_path": "src/day17.rs", "rank": 6, "score": 182088.35706190794 }, { "content": "fn get(program:&mut IntcodeProgram, pos:i64, mode:i64, err:&mut bool) -> i64 {\n\n\t// if address outside range, expand memory\n\n\tif pos < 0 {\n\n\t\t*err = true;\n\n\t\treturn 0;\n\n\t}\n\n\texpand_mem(program, pos as usize);\n\n\tlet val = (*program).mem[pos as usize];\n\n\tmatch mode {\n\n\t\t0=>{expand_mem(program, val as usize);return (*program).mem[val as usize];},\n\n\t\t1=>{return val;},\n\n\t\t2=>{expand_mem(program, (val + (*program).relative_base) as usize); return (*program).mem[(val + (*program).relative_base) as usize];},\n\n\t\t_=>{*err = true; return 0;}\n\n\t}\n\n}\n\n\n", "file_path": "src/utility.rs", "rank": 7, "score": 177819.75395111524 }, { "content": "// GCD and MMI functions taken from extended euclidean algorithm implementations given at https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/\n\n// recursion may be slow \n\nfn gcd(a:usize, b:usize, x:&mut i64, y:&mut i64)->usize {\n\n if a == 0 \n\n { \n\n *x = 0;\n\n\t\t*y = 1; \n\n return b; \n\n } \n\n\t\n\n\tlet mut x1:i64 = 0;\n\n\tlet mut y1:i64 = 0;\n\n\tlet gcd = gcd(b%a, a, &mut x1, &mut y1);\n\n \n\n // Update x and y using results of recursive call \n\n *x = y1 - ((b/a) as i64) * x1; \n\n *y = x1; \n\n return gcd; \n\n}\n\n\n", "file_path": "src/day22.rs", "rank": 8, "score": 177273.95953374484 }, { "content": "fn set(program: &mut IntcodeProgram, pos:i64, mode:i64, value: i64, err: &mut bool) {\n\n\tif mode == 1 {\n\n\t\t*err = true;\n\n\t\treturn;\n\n\t}\n\n\tif pos < 0 {\n\n\t\t*err = true;\n\n\t\treturn;\n\n\t}\n\n\texpand_mem(program, pos as usize);\n\n\tlet val = (*program).mem[pos as usize];\n\n\tmatch mode {\n\n\t\t0=>{expand_mem(program, val as usize);(*program).mem[val as usize] = value;},\n\n\t\t2=>{expand_mem(program, (val + (*program).relative_base) as usize); (*program).mem[(val + (*program).relative_base) as usize] = value; },\n\n\t\t_=>{*err = true;}\n\n\t}\n\n\treturn;\n\n}\n\n\n", "file_path": "src/utility.rs", "rank": 9, "score": 171606.24292791064 }, { "content": "pub fn intcode_execute(prog: &mut IntcodeProgram, input:&mut IOBuffer, output:&mut IOBuffer, exit:&mut bool) {\n\n\tlet mut instruction_error = false;\n\n\tlet mut instruction_exit = false;\n\n\tlet mut instruction_io_wait = false;\n\n\tloop {\n\n\t\tintcode_execute_once(prog, input, output, &mut instruction_exit, &mut instruction_io_wait, &mut instruction_error);\n\n\t\tif instruction_exit {\n\n\t\t\t*exit = true;\n\n\t\t\treturn;\n\n\t\t}\n\n\t\telse if instruction_io_wait || instruction_error {\n\n\t\t\t*exit = false;\n\n\t\t\treturn;\n\n\t\t}\n\n\t}\n\n}\n\n\n", "file_path": "src/utility.rs", "rank": 10, "score": 169314.71711859078 }, { "content": "fn print_signal(input:&mut Vec<i64>, offset:usize) {\n\n\tfor i in offset..offset+8 {\n\n\t\tprint!(\"{}\",(*input)[i]);\n\n\t}\n\n\tprintln!();\n\n}\n\n\n", "file_path": "src/day16.rs", "rank": 11, "score": 159677.06461887597 }, { "content": "fn dijkstra_c(maze:&Maze, start_index:usize, end_index:usize, levels:bool)->i64 {\n\n\tlet mut frontier:HashMap<LevelPortalIndex, DNode> = HashMap::new();\n\n\tlet mut frontier_next:HashMap<LevelPortalIndex, DNode> = HashMap::new();\n\n\tlet mut explored:HashMap<LevelPortalIndex, DNode> = HashMap::new();\n\n\t\n\n\tlet mut start_coord = (*maze).portal_positions[start_index].entry_coord;\n\n\tlet mut end_coord = (*maze).portal_positions[end_index].entry_coord;\n\n\t\n\n\tstart_coord.x -= 2;\n\n\tstart_coord.y -= 2;\n\n\tend_coord.x -= 2;\n\n\tend_coord.y -= 2;\n\n\t\n\n\tlet endlevelindex = LevelPortalIndex{index:end_index, level:0};\n\n\t\n\n\tfrontier_next.insert(LevelPortalIndex{index:start_index, level:0}, DNode{positions:Vec::new(), dist:0});\n\n\n\n\t\n\n\twhile frontier_next.len() > 0 {\n\n\t\t// copy to frontier\n", "file_path": "src/day20.rs", "rank": 12, "score": 159472.9481835403 }, { "content": "pub fn execute_amp(intcodes: &mut Vec<i64>, input_signal:i64, phase:i64) -> i64 {\n\n\tlet mut exit = false;\n\n\tlet mut input_count = 0;\n\n\tlet mut op_pos:usize = 0;\n\n\treturn execute_amp2(intcodes, input_signal, phase, &mut input_count, &mut op_pos, &mut exit);\n\n}\n\n\n", "file_path": "src/day7.rs", "rank": 13, "score": 158266.38353727385 }, { "content": "fn matching_portal_index(maze:&Maze, index:usize)->i64 {\n\n\tif index >= (*maze).portal_positions.len() {\n\n\t\treturn -1;\n\n\t}\n\n\tfor i in 0..(*maze).portal_positions.len() {\n\n\t\tif i == index {\n\n\t\t\tcontinue;\n\n\t\t}\n\n\t\tif (*maze).portal_positions[i].symbol_a == (*maze).portal_positions[index].symbol_a && (*maze).portal_positions[i].symbol_b == (*maze).portal_positions[index].symbol_b {\n\n\t\t\treturn i as i64;\n\n\t\t}\n\n\t}\n\n\t\n\n\treturn -1;\n\n}\n\n\n", "file_path": "src/day20.rs", "rank": 14, "score": 153022.22265045965 }, { "content": "// can only be used with a large offset\n\nfn phase_b(input:&mut Vec<i64>, output: &mut Vec<i64>, offset:usize) {\n\n\tlet mut i:usize = (input.len()) - 1;\n\n\toutput[i] = input[i];\n\n\ti-=1;\n\n\twhile i >= offset {\n\n\t\toutput[i] = (input[i] + output[i+1]) % 10;\n\n\t\ti-=1;\n\n\t}\n\n}\n\n\n", "file_path": "src/day16.rs", "rank": 15, "score": 151930.3607645499 }, { "content": "fn phase_a(input:&mut Vec<i64>, output: &mut Vec<i64>, offset:usize) {\n\n\tlet mut i:i64 = (input.len() as i64) - 1;\n\n\twhile i >= offset as i64 {\n\n\t\tlet mut sum:i64 = 0;\n\n\t\tlet mut j:i64 = (input.len() as i64) - 1;\n\n\t\twhile j >= i{\n\n\t\t\tlet coefficient_pos = (j+1)/(i+1);\n\n\t\t\tlet coefficient:i64;\n\n\t\t\tif coefficient_pos % 4 == 1 {\n\n\t\t\t\tcoefficient = 1;\n\n\t\t\t}\n\n\t\t\telse if coefficient_pos % 4 == 3 {\n\n\t\t\t\tcoefficient = -1;\n\n\t\t\t}\n\n\t\t\telse {\n\n\t\t\t\tcoefficient = 0;\n\n\t\t\t}\n\n\t\t\tif coefficient == -1 {\n\n\t\t\t\tsum -= (*input)[j as usize];\n\n\t\t\t}\n", "file_path": "src/day16.rs", "rank": 16, "score": 151926.76219564938 }, { "content": "fn keynodeindex(maze:&mut Maze, keys: &Vec<usize>, at: &Vec<usize>)->String {\n\n\tlet mut ret = String::from(\"\");\n\n\tlet mut keys2 = Vec::new();\n\n\tfor i in 0..keys.len() {\n\n\t\tkeys2.push((*maze).keys[(*keys)[i]].symbol);\n\n\t}\n\n\tkeys2.sort();\n\n\tfor i in 0..(*at).len() {\n\n\t\tret.push((*maze).keys[(*at)[i]].symbol);\n\n\t}\n\n\tret.push('|');\n\n\tfor i in 0..keys2.len() {\n\n\t\tret.push(keys2[i]);\n\n\t}\n\n\treturn ret;\n\n}\n\n\n", "file_path": "src/day18.rs", "rank": 17, "score": 147657.57650964567 }, { "content": "fn determine_turn(dir:u8, desired_dir:u8)->String {\n\n\tlet mut change = (desired_dir as i64) - (dir as i64);\n\n\tif change < 0 {\n\n\t\tchange += 4;\n\n\t}\n\n\tchange = change % 4;\n\n\tif change == 1 {\n\n\t\treturn String::from(\"R\");\n\n\t}\n\n\telse if change == 3 {\n\n\t\treturn String::from(\"L\");\n\n\t}\n\n\telse {\n\n\t\treturn String::from(\"ERROR\");\n\n\t}\n\n}\n\n\n", "file_path": "src/day17.rs", "rank": 18, "score": 145416.6576746476 }, { "content": "fn run_bot(prog:&mut super::utility::IntcodeProgram, part_a:bool)->i64 {\n\n\tlet mut exit:bool = false;\n\n\tlet mut in_buffer:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\tlet mut out_buffer:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\t\n\n\tlet mut grid:Vec<u8> = Vec::new();\n\n\t\n\n\t\n\n\tin_buffer.buff.clear();\n\n\tin_buffer.read_pos = 0;\n\n\tin_buffer.write_pos = 0;\n\n\tout_buffer.buff.clear();\n\n\tout_buffer.read_pos = 0;\n\n\tout_buffer.write_pos = 0;\n\n\t\n\n\tif part_a {\n\n\t\tsuper::utility::intcode_execute(prog, &mut in_buffer, &mut out_buffer, &mut exit);\n\n\t\t\n\n\t\tfor i in 0..out_buffer.buff.len() {\n\n\t\t\tgrid.push(out_buffer.buff[i] as u8);\n", "file_path": "src/day17.rs", "rank": 19, "score": 141015.36304051155 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet intcodes_str:Vec<&str> = vec[0].split(\",\").collect(); \n\n\tlet mut prog_a:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tlet mut prog_b:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tprog_a.mem.reserve(intcodes_str.len());\n\n\tprog_b.mem.reserve(intcodes_str.len());\n\n\tfor code in intcodes_str {\n\n\t\tlet temp: i64 = code.parse::<i64>().unwrap();\n\n\t\tprog_a.mem.push(temp);\n\n\t\tprog_b.mem.push(temp);\n\n\t}\n\n\t\n\n\trun_network(&mut prog_a, false);\n\n\trun_network(&mut prog_b, true);\n\n\t\n\n}", "file_path": "src/day23.rs", "rank": 20, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet mut maze = Maze{grid:Vec::new(), portal_positions:Vec::new(), cached_distances:Vec::new(), width:0, height:0};\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\t\n\n\tread_maze(vec, &mut maze);\n\n\t\n\n\treturn;\n\n}", "file_path": "src/day20.rs", "rank": 21, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet intcodes_str:Vec<&str> = vec[0].split(\",\").collect(); \n\n\tlet mut prog_a:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tlet mut prog_b:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tprog_a.mem.reserve(intcodes_str.len());\n\n\tprog_b.mem.reserve(intcodes_str.len());\n\n\tfor code in intcodes_str {\n\n\t\tlet temp: i64 = code.parse::<i64>().unwrap();\n\n\t\tprog_a.mem.push(temp);\n\n\t\tprog_b.mem.push(temp);\n\n\t}\n\n\t\n\n\tlet mut in_buffer_a:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\tlet mut out_buffer_a:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\tin_buffer_a.buff.push(1);\n\n\tin_buffer_a.write_pos = 1;\n\n\t\n\n\tlet mut in_buffer_b:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\tlet mut out_buffer_b:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n", "file_path": "src/day9.rs", "rank": 22, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\t\n\n\trun_instructions(vec);\n\n\t\n\n\treturn;\n\n}", "file_path": "src/day22.rs", "rank": 23, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet intcodes_str:Vec<&str> = vec[0].split(\",\").collect(); \n\n\tlet mut prog_a:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tlet mut prog_b:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tprog_a.mem.reserve(intcodes_str.len());\n\n\tprog_b.mem.reserve(intcodes_str.len());\n\n\tfor code in intcodes_str {\n\n\t\tlet temp: i64 = code.parse::<i64>().unwrap();\n\n\t\tprog_a.mem.push(temp);\n\n\t\tprog_b.mem.push(temp);\n\n\t}\n\n\t\n\n\tprintln!(\"Result A: {}\", run_robot(&mut prog_a, false));\n\n\t\n\n\tprintln!(\"Result B: \\n\");\n\n\t\n\n\trun_robot(&mut prog_b, true);\n\n}", "file_path": "src/day11.rs", "rank": 24, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet mut moons:Vec<Moon> = Vec::new();\n\n\tlet mut moons_start:Vec<Moon> = Vec::new();\n\n\tfor line in 0..vec.len() {\n\n\t\tlet mut index0:usize = 0;\n\n\t\tlet mut index1:usize = 0;\n\n\t\tlet mut index2:usize = 0;\n\n\t\tlet mut index3:usize = 0;\n\n\t\tlet mut index4:usize = 0;\n\n\t\tlet mut index5:usize = 0;\n\n\t\tfor (i,c) in vec[line].chars().enumerate() {\n\n\t\t\tif c == '=' {\n\n\t\t\t\tif index0 == 0 {\n\n\t\t\t\t\tindex0 = i;\n\n\t\t\t\t}\n\n\t\t\t\telse if index2 == 0 {\n\n\t\t\t\t\tindex2 = i;\n\n\t\t\t\t}\n\n\t\t\t\telse if index4 == 0 {\n", "file_path": "src/day12.rs", "rank": 25, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet mut reactant_ids:Vec<&str> = Vec::new();\n\n\tlet mut reactant_distances:Vec<i64> = Vec::new();\n\n\tlet mut reactions:Vec<Reaction> = Vec::new();\n\n\tfor line in 0..vec.len() {\n\n\t\tlet parts:Vec<&str> = vec[line].split(\" => \").collect();\n\n\t\tlet part_a:Vec<&str> = parts[0].split(\", \").collect();\n\n\t\tlet mut output_n:u64 = 0;\n\n\t\tlet mut output_s:&str = \"\";\n\n\t\tfor i in 0..parts[1].len() {\n\n\t\t\tif &parts[1][i..i+1] == \" \" {\n\n\t\t\t\toutput_s = &parts[1][i+1..];\n\n\t\t\t\toutput_n = parts[1][..i].parse::<u64>().unwrap();\n\n\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t}\n\n\t\tlet mut output_found = false;\n\n\t\tlet mut output_id:usize = 0;\n\n\t\tfor i in 0..reactant_ids.len() {\n", "file_path": "src/day14.rs", "rank": 26, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet range_str:Vec<&str> = vec[0].split(\"-\").collect(); \n\n\tlet min = range_str[0].parse::<u32>().unwrap();\n\n\tlet max = range_str[1].parse::<u32>().unwrap();\n\n\t\n\n\tlet mut count_a = 0;\n\n\tlet mut count_b = 0;\n\n\tfor i in min..max {\n\n\t\tlet a:u32 = i/100000;\n\n\t\tlet b:u32 = (i - 100000*a)/10000;\n\n\t\tlet c:u32 = (i - 100000*a - 10000*b)/1000;\n\n\t\tlet d:u32 = (i - 100000*a - 10000*b - 1000*c)/100;\n\n\t\tlet e:u32 = (i - 100000*a - 10000*b - 1000*c - d*100)/10;\n\n\t\tlet f:u32 = i - 100000*a - 10000*b - 1000*c - d*100 - 10*e;\n\n\t\t\n\n\t\tif !(a <= b && b <= c && c <= d && d <= e && e <= f) {\n\n\t\t\tcontinue;\n\n\t\t}\n\n\t\tif !(a == b || b == c || c == d || d == e || e == f ) {\n", "file_path": "src/day4.rs", "rank": 27, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet intcodes_str:Vec<&str> = vec[0].split(\",\").collect(); \n\n\tlet mut prog_a:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tlet mut prog_b:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tprog_a.mem.reserve(intcodes_str.len());\n\n\tprog_b.mem.reserve(intcodes_str.len());\n\n\tfor code in intcodes_str {\n\n\t\tlet temp: i64 = code.parse::<i64>().unwrap();\n\n\t\tprog_a.mem.push(temp);\n\n\t\tprog_b.mem.push(temp);\n\n\t}\n\n\t\n\n\tprintln!(\"Result A: {}\", run_game(&mut prog_a, false));\n\n\t\n\n\tprog_b.mem[0] = 2;\n\n\tprintln!(\"Result B: {}\", run_game(&mut prog_b, true));\n\n}", "file_path": "src/day13.rs", "rank": 29, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet mut grid = BugGrid{grid:Vec::new(), width:0, height:0};\n\n\tgrid.height = vec.len();\n\n\tgrid.width = vec[0].len();\n\n\tfor y in 0..vec.len() {\n\n\t\tgrid.grid.push(Vec::new());\n\n\t\tlet bytes = vec[y].as_bytes();\n\n\t\tfor x in 0..bytes.len() {\n\n\t\t\tif bytes[x] == '.' as u8 {\n\n\t\t\t\tgrid.grid[y].push(false);\n\n\t\t\t}\n\n\t\t\telse {\n\n\t\t\t\tgrid.grid[y].push(true);\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tlet mut biodiversity:HashMap<u64, usize> = HashMap::new();\n\n\tbiodiversity.insert(grid_biodiversity(&mut grid), 1);\n\n\tloop {\n", "file_path": "src/day24.rs", "rank": 30, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet intcodes_str:Vec<&str> = vec[0].split(\",\").collect(); \n\n\tlet mut prog_a:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tlet mut prog_b:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tprog_a.mem.reserve(intcodes_str.len());\n\n\tprog_b.mem.reserve(intcodes_str.len());\n\n\tfor code in intcodes_str {\n\n\t\tlet temp: i64 = code.parse::<i64>().unwrap();\n\n\t\tprog_a.mem.push(temp);\n\n\t\tprog_b.mem.push(temp);\n\n\t}\n\n\t\n\n\trun_bot(&mut prog_a);\n\n}", "file_path": "src/day15.rs", "rank": 31, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet intcodes_str:Vec<&str> = vec[0].split(\",\").collect(); \n\n\tlet mut prog_a:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tlet mut prog_b:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tprog_a.mem.reserve(intcodes_str.len());\n\n\tprog_b.mem.reserve(intcodes_str.len());\n\n\tfor code in intcodes_str {\n\n\t\tlet temp: i64 = code.parse::<i64>().unwrap();\n\n\t\tprog_a.mem.push(temp);\n\n\t\tprog_b.mem.push(temp);\n\n\t}\n\n\t\n\n\t\n\n\trun_probe(&mut prog_a);\n\n\t\n\n\t\n\n\n\n}", "file_path": "src/day19.rs", "rank": 32, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet intcodes_str = vec[0].split(\",\"); \n\n\tlet mut intcodes: Vec<i64> = Vec::new();\n\n\tfor code in intcodes_str {\n\n\t\tlet temp: i64 = code.parse::<i64>().unwrap();\n\n\t\tintcodes.push(temp);\n\n\t}\n\n\t\n\n\tlet mut max_output = 0;\n\n\tlet mut last_output:i64;\n\n\tfor a in 0..5 {\n\n\t\tfor b in 0..5 {\n\n\t\t\tif b == a {\n\n\t\t\t\tcontinue;\n\n\t\t\t}\n\n\t\t\tfor c in 0..5 {\n\n\t\t\t\tif c==a || c==b {\n\n\t\t\t\t\tcontinue;\n\n\t\t\t\t}\n", "file_path": "src/day7.rs", "rank": 33, "score": 135295.11408535315 }, { "content": "// day 1\n\npub fn run(file_path:&str) {\n\n\t\tlet mut fuel_a:i32 = 0;\n\n\t\tlet mut fuel_b:i32 = 0;\n\n\t\tlet vec = super::utility::util_fread(file_path);\n\n\t\tfor line in vec {\n\n\t\t\tlet mut mass:i32 = line.parse::<i32>().unwrap();\n\n\t\t\tfuel_a += (mass/3)-2;\n\n\t\t\tlet mut fuelmass:i32 = 0;\n\n\t\t\twhile (mass/3)-2 >= 0 {\n\n\t\t\t\tmass = (mass/3)-2;\n\n\t\t\t\tfuelmass += mass;\n\n\t\t\t}\n\n\t\t\tfuel_b += fuelmass;\n\n\t\t}\n\n\t\tprintln!(\"Part A result: {}\", fuel_a);\n\n\t\tprintln!(\"Part B result: {}\", fuel_b);\n\n}", "file_path": "src/day1.rs", "rank": 34, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet mut input:Vec<i64> = Vec::new();\n\n\tlet mut phase1:Vec<i64> = Vec::new();\n\n\tlet mut phase2:Vec<i64> = Vec::new();\n\n\tfor i in 0..vec[0].len() {\n\n\t\tlet temp = vec[0][i..i+1].parse::<i64>().unwrap();\n\n\t\tinput.push(temp);\n\n\t\tphase1.push(temp);\n\n\t\tphase2.push(temp);\n\n\t}\n\n\t\n\n\tlet phases = 100;\n\n\tlet mut phase_count = 0;\n\n\twhile phase_count < phases {\n\n\t\tif phase_count % 2 == 0 {\n\n\t\t\tphase_a(&mut phase1, &mut phase2, 0);\n\n\t\t}\n\n\t\telse {\n\n\t\t\tphase_a(&mut phase2, &mut phase1, 0);\n", "file_path": "src/day16.rs", "rank": 35, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet intcodes_str:Vec<&str> = vec[0].split(\",\").collect(); \n\n\tlet mut prog_a:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tlet mut prog_b:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tprog_a.mem.reserve(intcodes_str.len());\n\n\tprog_b.mem.reserve(intcodes_str.len());\n\n\tfor code in intcodes_str {\n\n\t\tlet temp: i64 = code.parse::<i64>().unwrap();\n\n\t\tprog_a.mem.push(temp);\n\n\t\tprog_b.mem.push(temp);\n\n\t}\n\n\t\n\n\trun_droid(&mut prog_a, false);\n\n\trun_droid(&mut prog_b, true);\n\n}", "file_path": "src/day21.rs", "rank": 36, "score": 135295.11408535315 }, { "content": "// day 2 \n\npub fn run(file_path:&str) {\n\n\t\tlet vec = super::utility::util_fread(file_path);\n\n\t\tlet intcodes_str = vec[0].split(\",\"); \n\n\t\tlet mut intcodes: Vec<usize> = Vec::new();\n\n\t\tlet mut intcodes_b: Vec<usize> = Vec::new();\n\n\t\tfor code in intcodes_str {\n\n\t\t\tlet temp: usize = code.parse::<usize>().unwrap();\n\n\t\t\tintcodes.push(temp);\n\n\t\t\tintcodes_b.push(temp);\n\n\t\t}\n\n\t\tlet mut op_pos: usize = 0;\n\n\t\t// starting condition modification\n\n\t\tintcodes[1] = 12;\n\n\t\tintcodes[2] = 2;\n\n\t\twhile intcodes[op_pos] != 99 {\n\n\t\t\tlet op1:usize = intcodes[op_pos + 1];\n\n\t\t\tlet op2:usize = intcodes[op_pos + 2];\n\n\t\t\tlet op3:usize = intcodes[op_pos + 3];\n\n\t\t\tif intcodes[op_pos] == 1 {\n\n\t\t\t\tintcodes[op3] = intcodes[op1] + intcodes[op2];\n", "file_path": "src/day2.rs", "rank": 37, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet intcodes_str:Vec<&str> = vec[0].split(\",\").collect(); \n\n\tlet mut prog_a:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tlet mut prog_b:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tprog_a.mem.reserve(intcodes_str.len());\n\n\tprog_b.mem.reserve(intcodes_str.len());\n\n\tfor code in intcodes_str {\n\n\t\tlet temp: i64 = code.parse::<i64>().unwrap();\n\n\t\tprog_a.mem.push(temp);\n\n\t\tprog_b.mem.push(temp);\n\n\t}\n\n\tlet mut exit:bool = false;\n\n\tlet mut in_buffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\tlet mut out_buffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\t\n\n\tin_buffer.buff.push(1);\n\n\tin_buffer.write_pos = 1;\n\n\tsuper::utility::intcode_execute(&mut prog_a, &mut in_buffer, &mut out_buffer, &mut exit);\n\n\tprintln!(\"Result A: {}\", out_buffer.buff[out_buffer.buff.len() - 1]);\n", "file_path": "src/day5.rs", "rank": 38, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet x_dim:i32 = vec[0].len() as i32;\n\n\tlet y_dim:i32 = vec.len() as i32;\n\n\tlet mut asteroids:Vec<Asteroid> = Vec::new();\n\n\tfor y in 0..vec.len() {\n\n\t\tlet bytes = vec[y].as_bytes();\n\n\t\tfor x in 0..bytes.len() {\n\n\t\t\tif bytes[x] == 0x23 { // #\n\n\t\t\t\tasteroids.push(Asteroid{x: x as i32, y:y as i32});\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t\n\n\tlet mut max_asteroid_count = 0;\n\n\tlet mut max_index = 0;\n\n\t\n\n\tlet mut asteroid_map = vec![false; (x_dim * y_dim) as usize];\n\n\tfor i in 0..asteroids.len() {\n\n\t\tasteroid_map[(asteroids[i].y * x_dim + asteroids[i].x) as usize] = true;\n", "file_path": "src/day10.rs", "rank": 39, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet intcodes_str:Vec<&str> = vec[0].split(\",\").collect(); \n\n\tlet mut prog_a:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tlet mut prog_b:super::utility::IntcodeProgram = super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0};\n\n\tprog_a.mem.reserve(intcodes_str.len());\n\n\tprog_b.mem.reserve(intcodes_str.len());\n\n\tfor code in intcodes_str {\n\n\t\tlet temp: i64 = code.parse::<i64>().unwrap();\n\n\t\tprog_a.mem.push(temp);\n\n\t\tprog_b.mem.push(temp);\n\n\t}\n\n\t\n\n\t\n\n\trun_bot(&mut prog_a, true);\n\n\t\n\n\tprog_b.mem[0] = 2;\n\n\trun_bot(&mut prog_b, false);\n\n\t\n\n\n\n}", "file_path": "src/day17.rs", "rank": 40, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\t\tlet vec = super::utility::util_fread(file_path);\n\n\t\tlet dirs1_str = vec[0].split(\",\"); \n\n\t\tlet dirs2_str = vec[1].split(\",\"); \n\n\t\tlet mut path1: Vec<WirePath> = Vec::new();\n\n\t\tlet mut path2: Vec<WirePath> = Vec::new();\n\n\t\tfor dirstr in dirs1_str {\n\n\t\t\tlet substr: String = dirstr.chars().skip(1).take(dirstr.chars().count() - 1).collect();\n\n\t\t\tlet len = substr.parse::<i32>().unwrap();\n\n\t\t\tlet dir = dirstr.chars().next().unwrap();\n\n\t\t\tpath1.push( WirePath{dir:dir,len:len});\n\n\t\t}\n\n\t\tfor dirstr in dirs2_str {\n\n\t\t\tlet substr: String = dirstr.chars().skip(1).take(dirstr.chars().count() - 1).collect();\n\n\t\t\tlet len = substr.parse::<i32>().unwrap();\n\n\t\t\tlet dir = dirstr.chars().next().unwrap();\n\n\t\t\tpath2.push(WirePath{dir:dir,len:len});\n\n\t\t}\n\n\t\t\n\n\t\t// determine bounds\n", "file_path": "src/day3.rs", "rank": 41, "score": 135295.11408535315 }, { "content": "// day 8 \n\npub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet bytes = vec[0].as_bytes();\n\n\tlet width = 25;\n\n\tlet height = 6;\n\n\n\n\tlet total_pixels = bytes.len(); \n\n\tlet layers = total_pixels/(width*height);\n\n\t\n\n\tlet mut final_bytes:[u8;150] = [2; 150];\n\n\t\n\n\tlet mut min_zeros = width*height;\n\n\tlet mut result_a = 0;\n\n\tfor i in 0..layers {\n\n\t\tlet mut zero_count = 0;\n\n\t\tlet mut one_count = 0;\n\n\t\tlet mut two_count = 0;\n\n\t\tfor j in i * width * height .. (i+1) * width * height {\n\n\t\t\tif bytes[j] == 0x30 { // 0\n\n\t\t\t\tzero_count += 1;\n", "file_path": "src/day8.rs", "rank": 42, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet mut orbit_infos:Vec<OrbitInfo> = Vec::new();\n\n\tlet mut bodies:Vec<String> = Vec::new();\n\n\tfor line in vec {\n\n\t\tlet body_codes:Vec<&str> = line.split(\")\").collect();\n\n\t\torbit_infos.push(OrbitInfo{parent: String::from(body_codes[0]), child: String::from(body_codes[1])});\n\n\t}\n\n\t\n\n\t// build a list of bodies\n\n\tfor i in 0..orbit_infos.len() {\n\n\t\tlet mut found_parent:bool = false;\n\n\t\tlet mut found_child:bool = false;\n\n\t\tfor j in 0..bodies.len() {\n\n\t\t\tif bodies[j] == orbit_infos[i].parent {\n\n\t\t\t\tfound_parent = true;\n\n\t\t\t}\n\n\t\t\tif bodies[j] == orbit_infos[i].child {\n\n\t\t\t\tfound_child = true;\n\n\t\t\t}\n", "file_path": "src/day6.rs", "rank": 43, "score": 135295.11408535315 }, { "content": "pub fn run(file_path:&str) {\n\n\tlet mut maze = Maze{grid:Vec::new(), keys:Vec::new(), doors:Vec::new(), cached:HashMap::new(), height: 0, width: 0};\n\n\tlet mut maze2 = Maze{grid:Vec::new(), keys:Vec::new(), doors:Vec::new(), cached:HashMap::new(), height: 0, width: 0};\n\n\tlet vec = super::utility::util_fread(file_path);\n\n\tlet mut vec2:Vec<String> = Vec::new();\n\n\t\n\n\t\n\n\tlet mut ox = 0;\n\n\tlet mut oy = 0;\n\n\t\n\n\tif vec.len() == 0 {\n\n\t\tprintln!(\"Input not read properly\");\n\n\t\treturn;\n\n\t}\n\n\t\n\n\t// test if maze is set up for part B\n\n\tfor line in 0..vec.len() {\n\n\t\tlet bytes = vec[line].as_bytes();\n\n\t\tfor pos in 0..bytes.len() {\n\n\t\t\tif bytes[pos] == '@' as u8 {\n", "file_path": "src/day18.rs", "rank": 44, "score": 135295.11408535315 }, { "content": "fn run_bot(prog:&mut super::utility::IntcodeProgram)->i64 {\n\n\tlet mut exit:bool = false;\n\n\tlet mut in_buffer:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\tlet mut out_buffer:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\t\n\n\tlet mut grid:Vec<MazeNode> = Vec::new();\n\n\tfor _y in MIN_Y..MAX_Y {\n\n\t\tfor _x in MIN_X..MAX_X {\n\n\t\t\tgrid.push(MazeNode{visited:false, parent_coord:Coord{x:0,y:0}, o2:false, obstacle:false});\n\n\t\t}\n\n\t}\n\n\t\n\n\t\n\n\tgrid[gridindex(0,0)].visited = true;\n\n\tlet mut position:Coord = Coord{x:0,y:0};\n\n\tlet mut possibles:Vec<Coord> = Vec::new();\n\n\tpossibles.push(Coord{x:-1,y:0});\n\n\tpossibles.push(Coord{x:0,y:-1});\n\n\tpossibles.push(Coord{x:1,y:0});\n\n\tpossibles.push(Coord{x:0,y:1});\n", "file_path": "src/day15.rs", "rank": 45, "score": 131663.6646109702 }, { "content": "fn read_maze(input: Vec<String>, maze:&mut Maze)->usize {\n\n\t(*maze).width = input[0].len();\n\n\t(*maze).height = input.len();\n\n\t\n\n\t// read origin, obstacles, doors and keys\n\n\tfor y in 0..(*maze).height {\n\n\t\t(*maze).grid.push(Vec::new());\n\n\t\tfor x in 0..(*maze).width {\n\n\t\t\tlet byte = input[y].as_bytes()[x];\n\n\t\t\tmatch byte {\n\n\t\t\t\t35=>(*maze).grid[y].push(MazeNode{obstacle:true, door_index: -1, key_index: -1}),\n\n\t\t\t\t46=>(*maze).grid[y].push(MazeNode{obstacle:false, door_index: -1, key_index: -1}),\n\n\t\t\t\t65..=90=> {(*maze).doors.push(Door{_x:x,_y:y,symbol:(byte as char),key_index:0}); (*maze).grid[y].push(MazeNode{obstacle:false, door_index: ((*maze).doors.len() - 1) as i64, key_index: -1}); },\n\n\t\t\t\t97..=122=> {(*maze).keys.push(Key{x:x,y:y,symbol:((byte-32) as char)}); (*maze).grid[y].push(MazeNode{obstacle:false, door_index: -1, key_index: ((*maze).keys.len() - 1) as i64}); },\n\n\t\t\t\t_=>{(*maze).keys.push(Key{x:x, y:y, symbol:(byte as char)}); (*maze).grid[y].push(MazeNode{obstacle:false, door_index: -1, key_index: ((*maze).keys.len() - 1) as i64});},\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t\n\n\t// quick lookup for door/key correspondance\n", "file_path": "src/day18.rs", "rank": 46, "score": 129304.65140886724 }, { "content": "fn read_maze(input: Vec<String>, maze:&mut Maze)->usize {\n\n\t\n\n\tif input.len() == 0 {\n\n\t\treturn 0;\n\n\t}\n\n\t\n\n\t// find all the portals\n\n\tlet char_width = input[0].len();\n\n\tlet char_height = input.len();\n\n\tlet mut chars:Vec<Vec<char>> = Vec::new();\n\n\tfor y in 0..input.len() {\n\n\t\tchars.push(Vec::new());\n\n\t\tlet line = input[y].as_bytes();\n\n\t\tfor x in 0..line.len() {\n\n\t\t\tchars[y].push(line[x] as char);\n\n\t\t}\n\n\t}\n\n\t\n\n\tlet mut start_portal_index = 0;\n\n\tlet mut end_portal_index = 0;\n", "file_path": "src/day20.rs", "rank": 47, "score": 129304.65140886724 }, { "content": "fn step(moons: &mut Vec<Moon>)->i64 {\n\n\tlet mut accel:Vec<Acceleration> = Vec::new();\n\n\tfor _i in 0..(*moons).len() {\n\n\t\taccel.push(Acceleration{dx:0,dy:0,dz:0});\n\n\t}\n\n\tfor i in 0..(*moons).len() {\n\n\t\tfor j in 0..(*moons).len() {\n\n\t\t\tif j == i {\n\n\t\t\t\tcontinue;\n\n\t\t\t}\n\n\t\t\tlet dx:i64;\n\n\t\t\tlet dy:i64;\n\n\t\t\tlet dz:i64;\n\n\t\t\tif (*moons)[i].x < (*moons)[j].x {dx = 1;} else if (*moons)[i].x == (*moons)[j].x {dx = 0;} else {dx = -1;}\n\n\t\t\tif (*moons)[i].y < (*moons)[j].y {dy = 1;} else if (*moons)[i].y == (*moons)[j].y {dy = 0;} else {dy = -1;}\n\n\t\t\tif (*moons)[i].z < (*moons)[j].z {dz = 1;} else if (*moons)[i].z == (*moons)[j].z {dz = 0;} else {dz = -1;}\n\n\t\t\t//println!(\"({} {} {})\", dx, dy, dz);\n\n\t\t\taccel[i].dx += dx;\n\n\t\t\taccel[i].dy += dy;\n\n\t\t\taccel[i].dz += dz;\n", "file_path": "src/day12.rs", "rank": 48, "score": 123796.28118538347 }, { "content": "fn run_robot(prog:&mut super::utility::IntcodeProgram, part_b:bool)->usize {\n\n\tlet mut x_pos:i64 = 0;\n\n\tlet mut y_pos:i64 = 0;\n\n\tlet mut dir: u8 = 0; // 0 - N, 1 - E, 2 - S, 3 - W\n\n\t\n\n\tlet mut panels:Vec<Panel> = Vec::new();\n\n\tlet mut exit:bool = false;\n\n\tlet mut in_buffer:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\tlet mut out_buffer:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\tlet mut white_start = false;\n\n\tif part_b {\n\n\t\twhite_start = true;\n\n\t}\n\n\twhile !exit {\n\n\t\t// determine current panel color\n\n\t\tlet mut found:bool = false;\n\n\t\tlet mut found_index = 0;\n\n\t\tfor i in 0..panels.len() {\n\n\t\t\tif panels[i].x == x_pos && panels[i].y == y_pos {\n\n\t\t\t\tfound = true;\n", "file_path": "src/day11.rs", "rank": 49, "score": 123034.08552769446 }, { "content": "#[derive(PartialEq)]\n\nenum Dir {\n\n\tNorth,\n\n\tEast,\n\n\tSouth,\n\n\tWest\n\n}\n\n\n", "file_path": "src/day20.rs", "rank": 51, "score": 121218.83278930376 }, { "content": "struct Door {\n\n\t_x: usize,\n\n\t_y: usize,\n\n\tsymbol: char,\n\n\tkey_index: usize,\n\n}\n\n\n", "file_path": "src/day18.rs", "rank": 52, "score": 119208.44843368462 }, { "content": "struct Key {\n\n\tx: usize,\n\n\ty: usize,\n\n\tsymbol: char,\n\n}\n\n\n", "file_path": "src/day18.rs", "rank": 53, "score": 119190.9511246656 }, { "content": "fn get_coord(prog:&mut super::utility::IntcodeProgram, x:i64, y:i64)->i64 {\n\n\tlet mut exit:bool = false;\n\n\tlet mut prog2 = super::utility::IntcodeProgram{mem:Vec::new(), pos:prog.pos, relative_base:prog.relative_base};\n\n\tfor i in 0..prog.mem.len() {\n\n\t\tprog2.mem.push(prog.mem[i]);\n\n\t}\n\n\tlet mut in_buffer:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\tlet mut out_buffer:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\tin_buffer.buff.push(x);\n\n\tin_buffer.buff.push(y);\n\n\tsuper::utility::intcode_execute(&mut prog2, &mut in_buffer, &mut out_buffer, &mut exit);\n\n\treturn out_buffer.buff[0];\n\n}\n\n\n", "file_path": "src/day19.rs", "rank": 54, "score": 116900.26846482727 }, { "content": "#[derive(Clone)]\n\nstruct DNode {\n\n\tx: usize,\n\n\ty: usize,\n\n\tdist: usize,\n\n\tparent_x:usize,\n\n\tparent_y:usize\n\n}\n\n\n", "file_path": "src/day18.rs", "rank": 55, "score": 115383.89516605627 }, { "content": "struct DNode {\n\n\tpositions:Vec<usize>,\n\n\tdist: usize,\n\n}\n\n\n", "file_path": "src/day20.rs", "rank": 57, "score": 115380.0421796201 }, { "content": "fn run_instructions(input: Vec<String>) {\n\n\tlet mut instructions:Vec<Instruction> = Vec::new();\n\n\t\n\n\tlet newstack_str = \"deal into new stack\";\n\n\tlet deal_str = \"deal with increment \";\n\n\tlet cut_str = \"cut \";\n\n\t\n\n\tfor i in 0..input.len() {\n\n\t\tif input[i] == newstack_str {\n\n\t\t\tinstructions.push(Instruction{instruction:Technique::NewDeck, argument: 0});\n\n\t\t}\n\n\t\telse if input[i].len() > deal_str.len() && &input[i][..deal_str.len()] == deal_str {\n\n\t\t\tlet substr = &input[i][deal_str.len()..];\n\n\t\t\tlet arg = substr.trim().parse::<i64>().unwrap();\n\n\t\t\tinstructions.push(Instruction{instruction:Technique::Deal, argument: arg});\n\n\t\t}\n\n\t\telse if input[i].len() > cut_str.len() && &input[i][..cut_str.len()] == cut_str {\n\n\t\t\tlet substr = &input[i][cut_str.len()..];\n\n\t\t\tlet arg = substr.trim().parse::<i64>().unwrap();\n\n\t\t\tinstructions.push(Instruction{instruction:Technique::Cut, argument: arg});\n", "file_path": "src/day22.rs", "rank": 58, "score": 113783.5161631972 }, { "content": "fn exploredindex(maze: &mut Maze, x: usize, y:usize)->usize {\n\n\treturn ((*maze).width * y) + x;\n\n}\n\n\n", "file_path": "src/day18.rs", "rank": 59, "score": 111643.4684557088 }, { "content": "fn run_droid(prog:&mut super::utility::IntcodeProgram, part_b:bool) {\n\n\t\n\n\tlet mut exit:bool = false;\n\n\tlet mut in_buffer:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\tlet mut out_buffer:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\t\n\n\tlet part_char:char;\n\n\tif part_b {\n\n\t\tpart_char = 'B';\n\n\t}\n\n\telse {\n\n\t\tpart_char = 'A';\n\n\t}\n\n\t\n\n\t\n\n\tlet mut springscript:Vec<&str> = Vec::new();\n\n\tif !part_b {\n\n\t\t// jump is 4 spaces\n\n\t\t// if D available and A B or C is not -> jump\n\n\t\t// T and J reset to false each cycle\n", "file_path": "src/day21.rs", "rank": 60, "score": 109515.81124374445 }, { "content": "fn run_network(prog:&mut super::utility::IntcodeProgram, part_b:bool) {\n\n\tlet num_nics = 50;\n\n\tlet idle_detection_cycles = 300;\n\n\tlet mut idle_detection_count = 0;\n\n\tlet mut network:Vec<Nic> = Vec::new();\n\n\tlet mut nat_packet = Packet{address:0, x:0, y:0};\n\n\tlet mut last_nat_packet = Packet{address:0, x:0, y:0};\n\n\tlet mut num_nat_packets_delivered = 0;\n\n\t// set up each nic and pre-load input with network address\n\n\tfor i in 0..num_nics {\n\n\t\tlet mut nic:Nic = Nic{\tprog:super::utility::IntcodeProgram{mem:Vec::new(), pos:0, relative_base:0}, \n\n\t\t\t\t\t\t\t\tin_buffer:super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0}, \n\n\t\t\t\t\t\t\t\tout_buffer:super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0},\n\n\t\t\t\t\t\t\t\tpacket_buffer:Vec::new(),\n\n\t\t\t\t\t\t\t\tis_waiting:false,\n\n\t\t\t\t\t\t\t\tis_exited:false};\n\n\t\tfor i in 0..(*prog).mem.len() {\n\n\t\t\tnic.prog.mem.push((*prog).mem[i]);\n\n\t\t}\n\n\t\tnic.prog.pos = (*prog).pos;\n", "file_path": "src/day23.rs", "rank": 61, "score": 109515.81124374445 }, { "content": "fn run_grid(grid:&mut BugGrid) {\n\n\tlet mut adjacency:Vec<Vec<usize>> = Vec::new();\n\n\tfor y in 0..(*grid).height {\n\n\t\tadjacency.push(Vec::new());\n\n\t\tfor x in 0..(*grid).width {\n\n\t\t\tlet mut count = 0;\n\n\t\t\tif y > 0 && (*grid).grid[y-1][x] {\n\n\t\t\t\tcount += 1;\n\n\t\t\t}\n\n\t\t\tif x > 0 && (*grid).grid[y][x-1]{\n\n\t\t\t\tcount += 1;\n\n\t\t\t}\n\n\t\t\tif y < (*grid).height-1 && (*grid).grid[y+1][x] {\n\n\t\t\t\tcount += 1;\n\n\t\t\t}\n\n\t\t\tif x < (*grid).width-1 && (*grid).grid[y][x+1] {\n\n\t\t\t\tcount += 1;\n\n\t\t\t}\n\n\t\t\tadjacency[y].push(count);\n\n\t\t}\n", "file_path": "src/day24.rs", "rank": 62, "score": 108572.98815271122 }, { "content": "// read by line, returning a vector of Strings\n\npub fn util_fread(file_path:&str) -> std::vec::Vec<String>{\n\n\tlet mut vec:Vec<String> = Vec::new();\n\n\t\n\n\tlet file = File::open(file_path).unwrap();\n\n let reader = BufReader::new(file);\n\n // Read the file line by line using the lines() iterator from std::io::BufRead.\n\n for (_index, line) in reader.lines().enumerate() {\n\n let line = line.unwrap(); // Ignore errors.\n\n\t\tvec.push(line);\n\n }\n\n\t\n\n\treturn vec;\n\n}", "file_path": "src/utility.rs", "rank": 63, "score": 107452.98497668025 }, { "content": "fn run_game(prog:&mut super::utility::IntcodeProgram, part_b:bool)->u64 {\n\n\tlet mut exit:bool = false;\n\n\tlet mut in_buffer:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\tlet mut out_buffer:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\n\n\tif !part_b {\n\n\t\twhile !exit {\n\n\t\t\tout_buffer.buff.clear();\n\n\t\t\tout_buffer.write_pos = 0;\n\n\t\t\tsuper::utility::intcode_execute(prog, &mut in_buffer, &mut out_buffer, &mut exit);\n\n\t\t\t\n\n\t\t}\n\n\t\tlet mut i = 0;\n\n\n\n\t\tlet mut block_count:u64 = 0;\n\n\t\twhile i < out_buffer.buff.len() {\n\n\t\t\tif out_buffer.buff[i+2] == 2 {\n\n\t\t\t\tblock_count += 1;\n\n\t\t\t}\n\n\t\t\ti += 3;\n", "file_path": "src/day13.rs", "rank": 64, "score": 104678.82237475232 }, { "content": "fn gridindex(x:i64, y:i64)->usize {\n\n\treturn (((y - (MIN_Y))*(MAX_X - MIN_X)) + (x - (MIN_X))) as usize;\n\n}\n\n\n\n\n", "file_path": "src/day15.rs", "rank": 65, "score": 103825.87188206293 }, { "content": "fn dijkstra_b(maze:&mut Maze, origins:&Vec<usize>)->usize {\n\n\tlet mut frontier:HashMap<String, DNodeB> = HashMap::new();\n\n\tlet mut frontier_next:HashMap<String, DNodeB> = HashMap::new();\n\n\tlet mut explored:HashMap<String, DNodeB> = HashMap::new();\n\n\tlet mut candidates:HashMap<String, usize> = HashMap::new();\n\n\t\n\n\tlet mut start = DNodeB{at:Vec::new(), keys:Vec::new(), dist:0};\n\n\tfor i in 0..(*origins).len() {\n\n\t\tstart.at.push((*origins)[i]);\n\n\t\tstart.keys.push((*origins)[i]);\n\n\t}\n\n\tfrontier_next.insert(keynodeindex(maze, &(start.keys), &(start.at)), start);\n\n\t\n\n\twhile frontier_next.len() > 0 {\n\n\t\tfrontier.clear();\n\n\t\tfor key in frontier_next.keys() {\n\n\t\t\tlet node = frontier_next.get(key).unwrap();\n\n\t\t\tlet node2 = (*node).clone();\n\n\t\t\tfrontier.insert(key.to_string(), node2);\n\n\t\t}\n", "file_path": "src/day18.rs", "rank": 66, "score": 103246.3864783154 }, { "content": "fn run_grids(grids: &mut Vec<BugGrid>) {\n\n\tlet mut adjacency:Vec<Vec<Vec<usize>>> = Vec::new();\n\n\tadjacency.push(Vec::new());\n\n\tfor i in 1..(*grids).len()-1 { // we don't compute the outer two layers of pre-allocated grid\n\n\t\tadjacency.push(Vec::new());\n\n\t\tfor y in 0..(*grids)[i].grid.len() {\n\n\t\t\tadjacency[i].push(Vec::new());\n\n\t\t\tfor x in 0..(*grids)[i].grid[y].len() {\n\n\t\t\t\tlet mut count:usize = 0;\n\n\t\t\t\t// north\n\n\t\t\t\tif y == 0 {\n\n\t\t\t\t\tcount += (*grids)[i-1].grid[1][2] as usize;\n\n\t\t\t\t}\n\n\t\t\t\telse if y == 3 && x == 2 {\n\n\t\t\t\t\tcount += (*grids)[i+1].grid[4][0] as usize;\n\n\t\t\t\t\tcount += (*grids)[i+1].grid[4][1] as usize;\n\n\t\t\t\t\tcount += (*grids)[i+1].grid[4][2] as usize;\n\n\t\t\t\t\tcount += (*grids)[i+1].grid[4][3] as usize;\n\n\t\t\t\t\tcount += (*grids)[i+1].grid[4][4] as usize;\n\n\t\t\t\t}\n", "file_path": "src/day24.rs", "rank": 67, "score": 102695.6435323951 }, { "content": "fn how_much_ore(reactions:&mut Vec<Reaction>, reactant_distances:&mut Vec<i64>, reactant_ids:&mut Vec<&str>, fuel_quantity:u64 )->u64 {\n\n\tlet mut fuel_id:usize = 0;\n\n\tlet mut ore_id:usize = 0;\n\n\tfor i in 0..reactant_ids.len() {\n\n\t\tif (*reactant_ids)[i] == \"FUEL\" {\n\n\t\t\tfuel_id = i;\n\n\t\t}\n\n\t\telse if (*reactant_ids)[i] == \"ORE\" {\n\n\t\t\tore_id = i;\n\n\t\t}\n\n\t\tif fuel_id > 0 && ore_id > 0 {// little lazy, should work\n\n\t\t\tbreak;\n\n\t\t}\n\n\t}\n\n\t\n\n\tlet mut requirements:Vec<Reactant> = Vec::new();\n\n\trequirements.push(Reactant{id:fuel_id, quantity:fuel_quantity});\n\n\trequirements.push(Reactant{id:ore_id, quantity:0});\n\n\t\n\n\tloop {\n", "file_path": "src/day14.rs", "rank": 68, "score": 101707.61718788858 }, { "content": "fn expand_mem(program: &mut IntcodeProgram, pos:usize) {\n\n\tif (*program).mem.len() <= pos {\n\n\t\t(*program).mem.reserve(pos + 1 - (*program).mem.len());\n\n\t\tfor _i in (*program).mem.len().. ((pos+1)) {\n\n\t\t\t(*program).mem.push(0);\n\n\t\t}\n\n\t}\n\n}\n\n\n", "file_path": "src/utility.rs", "rank": 69, "score": 100091.39231245237 }, { "content": "// path between two points on map, following no portals. used to build cached distances\n\nfn dijkstra_a(maze:&Maze, start:Coord, end:Coord)->i64 {\n\n\tlet mut frontier:HashMap<LevelCoord, usize> = HashMap::new(); \n\n\tlet mut frontier_next:HashMap<LevelCoord, usize> = HashMap::new();\n\n\tlet mut explored:HashMap<LevelCoord, usize> = HashMap::new();\n\n\t\n\n\tfrontier_next.insert(LevelCoord{x:start.x, y:start.y, level:0}, 0);\n\n\tlet end_coord = LevelCoord{x:end.x, y:end.y, level:0};\n\n\twhile frontier_next.len() > 0 {\n\n\t\t// copy to frontier\n\n\t\tfrontier.clear();\n\n\t\tfor key in frontier_next.keys() {\n\n\t\t\tfrontier.insert(*key, *(frontier_next.get(key).unwrap()));\n\n\t\t}\n\n\t\tfrontier_next.clear();\n\n\t\t\n\n\t\t// try all possible next moves\n\n\t\tfor coord in frontier.keys() {\n\n\t\t\tlet curr_dist:usize = *frontier.get(coord).unwrap();\n\n\t\t\t// update explored for coord\n\n\t\t\tif !explored.contains_key(coord) || (explored.contains_key(coord) && *(explored.get(coord).unwrap()) > curr_dist) {\n", "file_path": "src/day20.rs", "rank": 70, "score": 98953.21032847537 }, { "content": "// start must be an explored position, end does not need to be as long as it has an explored neighbor\n\nfn trace_path(grid:&mut Vec<MazeNode>, start:Coord, end:Coord)->Vec<Coord> {\n\n\t\n\n\tlet mut path:Vec<Coord> = Vec::new();\n\n\t// check if start and end are the same\n\n\tif start.x == end.x && start.y == end.y {\n\n\t\treturn path;\n\n\t}\n\n\t// check if adjacent \n\n\tif \t(start.x == end.x - 1 && start.y == end.y) ||\n\n\t\t(start.x == end.x + 1 && start.y == end.y) ||\n\n\t\t(start.x == end.x && start.y == end.y - 1) ||\n\n\t\t(start.x == end.x && start.y == end.y + 1)\n\n\t\t{\n\n\t\tpath.push(end);\n\n\t\treturn path;\n\n\t}\n\n\t\n\n\tlet end2:Coord;\n\n\tlet mut end_explored = true;\n\n\tif !(*grid)[gridindex(end.x, end.y)].visited {\n", "file_path": "src/day15.rs", "rank": 71, "score": 98117.3936967384 }, { "content": "fn run_probe(prog:&mut super::utility::IntcodeProgram) {\n\n\tlet width = 50;\n\n\tlet height = 50;\n\n\t\n\n\tlet mut exit:bool = false;\n\n\tlet mut in_buffer:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\tlet mut out_buffer:super::utility::IOBuffer = super::utility::IOBuffer{buff:Vec::new(), write_pos:0, read_pos:0};\n\n\tlet mut grid:Vec<u8> = Vec::new();\n\n\tfor _i in 0..(width * height) {\n\n\t\tgrid.push(0);\n\n\t}\n\n\t\n\n\tlet mut tractor_count = 0;\n\n\tfor y in 0..height {\n\n\t\tfor x in 0..width {\n\n\t\t\t// copy the program because it only runs once.\n\n\t\t\tlet mut prog2 = super::utility::IntcodeProgram{mem:Vec::new(), pos:prog.pos, relative_base:prog.relative_base};\n\n\t\t\tfor i in 0..prog.mem.len() {\n\n\t\t\t\tprog2.mem.push(prog.mem[i]);\n\n\t\t\t}\n", "file_path": "src/day19.rs", "rank": 72, "score": 97442.23917168543 }, { "content": "struct MazeNode {\n\n\tobstacle: bool,\n\n\tkey_index: i64,\n\n\tdoor_index: i64,\n\n}\n\n\n", "file_path": "src/day18.rs", "rank": 74, "score": 85044.36799909851 }, { "content": "struct MazeNode {\n\n\tvisited:bool,\n\n\tparent_coord:Coord,\n\n\to2:bool,\n\n\tobstacle:bool,\n\n}\n\n\n", "file_path": "src/day15.rs", "rank": 75, "score": 85044.36799909851 }, { "content": "struct MazeNode {\n\n\tcoord: Coord,\n\n\tn:MazeEdge,\n\n\te:MazeEdge,\n\n\ts:MazeEdge,\n\n\tw:MazeEdge,\n\n}\n\n\n", "file_path": "src/day20.rs", "rank": 76, "score": 85044.36799909851 }, { "content": "#[derive(Copy,Clone, Hash)]\n\nstruct LevelPortalIndex {\n\n\tindex:usize,\n\n\tlevel:usize,\n\n}\n\n\n\nimpl PartialEq for LevelPortalIndex {\n\n\tfn eq(&self, other: &Self) -> bool {\n\n return self.index == other.index && self.level == other.level;\n\n }\n\n}\n\n\n\nimpl Eq for LevelPortalIndex {}\n\n\n", "file_path": "src/day20.rs", "rank": 78, "score": 81990.99480153687 }, { "content": "#[derive(Clone)]\n\nstruct DNodeB {\n\n\tat:Vec<usize>,\n\n\tkeys:Vec<usize>,\n\n\tdist:usize\n\n}\n\n\n", "file_path": "src/day18.rs", "rank": 79, "score": 81882.0909388665 }, { "content": "fn mod_inverse(a:usize, m:usize)->usize {\n\n\tlet mut x:i64 = 0;\n\n\tlet mut y:i64 = 0;\n\n\tlet g = gcd(a,m,&mut x, &mut y);\n\n\tif g != 1 {\n\n\t\treturn 0;\n\n\t}\n\n\telse {\n\n\t\tlet x1 = positive_modulo(x, m as u64);\n\n\t\treturn ( x1 as usize % m ) + m % m;\n\n\t}\n\n} \n\n\n", "file_path": "src/day22.rs", "rank": 80, "score": 81463.77316610923 }, { "content": "fn grid_biodiversity(grid:&mut BugGrid)->u64 {\n\n\tif (*grid).width * (*grid).height >= 64 {\n\n\t\treturn 0;\n\n\t}\n\n\tlet mut accumulator:u64 = 0;\n\n\tlet pow = 1;\n\n\tfor y in 0..(*grid).height {\n\n\t\tfor x in 0..(*grid).width {\n\n\t\t\tif (*grid).grid[y][x] {\n\n\t\t\t\taccumulator += pow << (y * (*grid).width + x);\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn accumulator;\n\n}\n\n\n", "file_path": "src/day24.rs", "rank": 81, "score": 81182.04110417902 }, { "content": "fn add_once(vec:&mut Vec<Coord>, coord:Coord) {\n\n\tlet mut found = false;\n\n\tfor i in 0..(*vec).len() {\n\n\t\tif vec[i].x == coord.x && vec[i].y == coord.y {\n\n\t\t\tfound = true;\n\n\t\t\tbreak;\n\n\t\t}\n\n\t}\n\n\tif !found {\n\n\t\t(*vec).push(coord);\n\n\t}\n\n}\n\n\n", "file_path": "src/day15.rs", "rank": 82, "score": 78733.3863083728 }, { "content": "fn to_iobuffer(iobuff:&mut super::utility::IOBuffer, input:&str) {\n\n\tfor c in input.chars() {\n\n\t\tlet val = c as u8;\n\n\t\t(*iobuff).buff.push(val as i64);\n\n\t\t(*iobuff).write_pos += 1;\n\n\t}\n\n}\n\n\n", "file_path": "src/day17.rs", "rank": 83, "score": 71094.43809676892 }, { "content": "fn intersect_count (vec_a:&Vec<usize>, vec_b:&Vec<usize>)->usize {\n\n\tlet mut count = 0;\n\n\tfor i in 0..vec_a.len() {\n\n\t\tfor j in 0..vec_b.len() {\n\n\t\t\tif vec_b[j] == vec_a[i] {\n\n\t\t\t\tcount+=1;\n\n\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn count;\n\n}\n\n\n", "file_path": "src/day18.rs", "rank": 84, "score": 69374.69825354932 }, { "content": "fn positive_modulo(a:i64, m:u64)->u64 {\n\n\treturn ((( a % m as i64 ) + m as i64) % m as i64) as u64;\n\n}\n\n\n", "file_path": "src/day22.rs", "rank": 85, "score": 66381.02196365737 }, { "content": "#[derive(PartialEq)]\n\nenum Technique {\n\n\tNewDeck,\n\n\tCut,\n\n\tDeal,\n\n}\n\n\n", "file_path": "src/day22.rs", "rank": 86, "score": 60617.98303647234 }, { "content": "#[derive(Copy, Clone)]\n\nstruct Coord {\n\n\tx:i64,\n\n\ty:i64,\n\n}\n\n\n", "file_path": "src/day15.rs", "rank": 87, "score": 58472.473813041994 }, { "content": "#[derive(Copy,Clone, Hash)]\n\nstruct Coord {\n\n\tx: usize,\n\n\ty: usize,\n\n}\n\n\n\nimpl PartialEq for Coord {\n\n\tfn eq(&self, other: &Self) -> bool {\n\n return self.x == other.x && self.y == other.y;\n\n }\n\n}\n\n\n\nimpl Eq for Coord {}\n\n\n", "file_path": "src/day20.rs", "rank": 88, "score": 58472.23023499978 }, { "content": "struct Maze {\n\n\tgrid: Vec<Vec<MazeNode>>,\n\n\tkeys: Vec<Key>,\n\n\tdoors: Vec<Door>,\n\n\tcached: HashMap<usize, HashMap<usize, CachedPath>>,\n\n\twidth: usize,\n\n\theight: usize,\n\n}\n\n\n", "file_path": "src/day18.rs", "rank": 89, "score": 58465.00571960029 }, { "content": "struct Packet {\n\n\taddress:i64,\n\n\tx:i64,\n\n\ty:i64,\n\n}\n\n\n", "file_path": "src/day23.rs", "rank": 90, "score": 58465.00571960029 }, { "content": "struct Panel {\n\n\tx: i64,\n\n\ty: i64,\n\n\tcolor: bool,\n\n}\n\n\n", "file_path": "src/day11.rs", "rank": 91, "score": 58465.00571960029 }, { "content": "struct Target {\n\n\tx:i32,\n\n\ty:i32,\n\n\tbearing:f64,\n\n\tdist2:f64, // distance squared\n\n\tdestroyed:bool,\n\n}\n\n\n", "file_path": "src/day10.rs", "rank": 92, "score": 58465.00571960029 }, { "content": "struct Moon {\n\n\tx:i64,\n\n\ty:i64,\n\n\tz:i64,\n\n\tv_x:i64,\n\n\tv_y:i64,\n\n\tv_z:i64,\n\n}\n\n\n", "file_path": "src/day12.rs", "rank": 93, "score": 58465.00571960029 }, { "content": "struct Acceleration {\n\n\tdx:i64,\n\n\tdy:i64,\n\n\tdz:i64,\n\n}\n\n\n", "file_path": "src/day12.rs", "rank": 94, "score": 58465.00571960029 }, { "content": "struct Asteroid {\n\n\tx:i32,\n\n\ty:i32,\n\n}\n\n\n", "file_path": "src/day10.rs", "rank": 95, "score": 58465.00571960029 }, { "content": "struct Instruction {\n\n\tinstruction:Technique,\n\n\targument:i64,\n\n}\n\n\n", "file_path": "src/day22.rs", "rank": 96, "score": 58465.00571960029 }, { "content": "struct Reactant {\n\n\tid: usize,\n\n\tquantity: u64,\n\n}\n\n\n", "file_path": "src/day14.rs", "rank": 97, "score": 58465.00571960029 }, { "content": "struct Reaction {\n\n\tinputs:Vec<Reactant>,\n\n\toutput:Reactant,\n\n}\n\n\n", "file_path": "src/day14.rs", "rank": 98, "score": 58465.00571960029 }, { "content": "struct Nic {\n\n\tprog:super::utility::IntcodeProgram,\n\n\tin_buffer:super::utility::IOBuffer,\n\n\tout_buffer:super::utility::IOBuffer,\n\n\tpacket_buffer:Vec<Packet>,\n\n\tis_waiting:bool,\n\n\tis_exited:bool,\n\n}\n\n\n", "file_path": "src/day23.rs", "rank": 99, "score": 58465.00571960029 } ]
Rust
src/ewmh.rs
aniketfuryrocks/worm
bc3793c68258e208cd95eaa13bae7b57b32ab096
extern crate x11rb; use protocol::xproto; use protocol::xproto::ConnectionExt; use x11rb::*; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; pub enum Net { ActiveWindow, Supported, SystemTray, SystemTrayOP, SystemTrayOrientation, SystemTrayOrientationHorz, WMName, WMState, WMStateAbove, WMStateSticky, WMStateModal, SupportingWMCheck, WMStateFullScreen, ClientList, WMStrutPartial, WMWindowType, WMWindowTypeNormal, WMWindowTypeDialog, WMWindowTypeUtility, WMWindowTypeToolbar, WMWindowTypeSplash, WMWindowTypeMenu, WMWindowTypeDropdownMenu, WMWindowTypePopupMenu, WMWindowTypeTooltip, WMWindowTypeNotification, WMWindowTypeDock, WMWindowOpacity, WMDesktop, DesktopViewport, NumberOfDesktops, CurrentDesktop, DesktopNames, FrameExtents, Last, } pub fn get_ewmh_atoms<C>(conn: &C) -> Result<[xproto::Atom; Net::Last as usize]> where C: connection::Connection, { Ok([ conn.intern_atom(false, b"_NET_ACTIVE_WINDOW")? .reply()? .atom, conn.intern_atom(false, b"_NET_SUPPORTED")?.reply()?.atom, conn.intern_atom(false, b"_NET_SYSTEM_TRAY_S0")? .reply()? .atom, conn.intern_atom(false, b"_NET_SYSTEM_TRAY_OPCODE")? .reply()? .atom, conn.intern_atom(false, b"_NET_SYSTEM_TRAY_ORIENTATION")? .reply()? .atom, conn.intern_atom(false, b"_NET_SYSTEM_TRAY_ORIENTATION_HORZ")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_NAME")?.reply()?.atom, conn.intern_atom(false, b"_NET_WM_STATE")?.reply()?.atom, conn.intern_atom(false, b"_NET_WM_STATE_ABOVE")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_STATE_STICKY")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_STATE_MODAL")? .reply()? .atom, conn.intern_atom(false, b"_NET_SUPPORTING_WM_CHECK")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_STATE_FULLSCREEN")? .reply()? .atom, conn.intern_atom(false, b"_NET_CLIENT_LIST")?.reply()?.atom, conn.intern_atom(false, b"_NET_WM_STRUT_PARTIAL")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_NORMAL")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_DIALOG")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_UTILITY")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_TOOLBAR")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_SPLASH")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_MENU")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_POPUP_MENU")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_TOOLTIP")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_NOTIFICATION")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_DOCK")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_OPACITY")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_DESKTOP")?.reply()?.atom, conn.intern_atom(false, b"_NET_DESKTOP_VIEWPORT")? .reply()? .atom, conn.intern_atom(false, b"_NET_NUMBER_OF_DESKTOPS")? .reply()? .atom, conn.intern_atom(false, b"_NET_CURRENT_DESKTOP")? .reply()? .atom, conn.intern_atom(false, b"_NET_DESKTOP_NAMES")? .reply()? .atom, conn.intern_atom(false, b"_NET_FRAME_EXTENTS")? .reply()? .atom, ]) }
extern crate x11rb; use protocol::xproto; use protocol::xproto::ConnectionExt; use x11rb::*; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; pub enum Net { ActiveWindow, Supported, SystemTray, SystemTrayOP, SystemTrayOrientation, SystemTrayOrientationHorz, WMName, WMState, WMStateAbove, WMStateSticky, WMStateModal, SupportingWMCheck, WMStateFullScreen, ClientList, WMStrutPartial, WMWindowType, WMWindowTypeNormal, WMWindowTypeDialog, WMWindowTypeUtility, WMWindowTypeToolbar, WMWindowTypeSplash, WMWindowTypeMenu, WMWindowTypeDropdownMenu, WMWindowTypePopupMenu, WMWindowTypeTooltip, WMWindowTypeNotification, WMWindowTypeDock, WMWindowOpacity, WMDesktop, DesktopViewport, NumberOfDesktops, CurrentDesktop, DesktopNames, FrameExtents, Last, }
pub fn get_ewmh_atoms<C>(conn: &C) -> Result<[xproto::Atom; Net::Last as usize]> where C: connection::Connection, { Ok([ conn.intern_atom(false, b"_NET_ACTIVE_WINDOW")? .reply()? .atom, conn.intern_atom(false, b"_NET_SUPPORTED")?.reply()?.atom, conn.intern_atom(false, b"_NET_SYSTEM_TRAY_S0")? .reply()? .atom, conn.intern_atom(false, b"_NET_SYSTEM_TRAY_OPCODE")? .reply()? .atom, conn.intern_atom(false, b"_NET_SYSTEM_TRAY_ORIENTATION")? .reply()? .atom, conn.intern_atom(false, b"_NET_SYSTEM_TRAY_ORIENTATION_HORZ")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_NAME")?.reply()?.atom, conn.intern_atom(false, b"_NET_WM_STATE")?.reply()?.atom, conn.intern_atom(false, b"_NET_WM_STATE_ABOVE")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_STATE_STICKY")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_STATE_MODAL")? .reply()? .atom, conn.intern_atom(false, b"_NET_SUPPORTING_WM_CHECK")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_STATE_FULLSCREEN")? .reply()? .atom, conn.intern_atom(false, b"_NET_CLIENT_LIST")?.reply()?.atom, conn.intern_atom(false, b"_NET_WM_STRUT_PARTIAL")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_NORMAL")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_DIALOG")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_UTILITY")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_TOOLBAR")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_SPLASH")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_MENU")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_POPUP_MENU")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_TOOLTIP")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_NOTIFICATION")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE_DOCK")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_WINDOW_OPACITY")? .reply()? .atom, conn.intern_atom(false, b"_NET_WM_DESKTOP")?.reply()?.atom, conn.intern_atom(false, b"_NET_DESKTOP_VIEWPORT")? .reply()? .atom, conn.intern_atom(false, b"_NET_NUMBER_OF_DESKTOPS")? .reply()? .atom, conn.intern_atom(false, b"_NET_CURRENT_DESKTOP")? .reply()? .atom, conn.intern_atom(false, b"_NET_DESKTOP_NAMES")? .reply()? .atom, conn.intern_atom(false, b"_NET_FRAME_EXTENTS")? .reply()? .atom, ]) }
function_block-full_function
[ { "content": "pub fn get_ipc_atoms<C>(conn: &C) -> Result<[xproto::Atom; IPC::Last as usize]>\n\nwhere\n\n C: connection::Connection,\n\n{\n\n // see notes on ewmh.rs, exact same thing here\n\n\n\n Ok([\n\n conn.intern_atom(false, b\"_WORM_CLIENT_MESSAGE\")?\n\n .reply()?\n\n .atom,\n\n conn.intern_atom(false, b\"_WORM_KILL_ACTIVE_CLIENT\")?\n\n .reply()?\n\n .atom,\n\n conn.intern_atom(false, b\"_WORM_SWITCH_TAG\")?.reply()?.atom,\n\n conn.intern_atom(false, b\"_WORM_BORDER_PIXEL\")?\n\n .reply()?\n\n .atom,\n\n conn.intern_atom(false, b\"_WORM_BORDER_WIDTH\")?\n\n .reply()?\n\n .atom,\n", "file_path": "src/ipc.rs", "rank": 1, "score": 30164.227227930474 }, { "content": "type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;\n\n\n\npub enum IPC {\n\n ClientMessage,\n\n KillActiveClient,\n\n SwitchTag,\n\n BorderPixel,\n\n BorderWidth,\n\n BackgroundPixel,\n\n TitleHeight,\n\n SwitchActiveWindowTag,\n\n Last,\n\n}\n\n\n\n// Lots of these atoms we don't use, like the IPC ones. Instead, we use the offset in the IPC enum. Need to figure out better way to manage this.\n\n\n", "file_path": "src/ipc.rs", "rank": 3, "score": 16241.136371403707 }, { "content": "type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;\n\n\n", "file_path": "src/wormc.rs", "rank": 4, "score": 16241.136371403707 }, { "content": "extern crate x11rb;\n\nuse connection::Connection;\n\nuse protocol::xproto::{self, ConnectionExt};\n\nuse x11rb::*;\n\npub mod ipc;\n\n\n", "file_path": "src/wormc.rs", "rank": 5, "score": 13.964574696578197 }, { "content": "extern crate x11rb;\n\n\n\nuse protocol::xproto;\n\nuse protocol::xproto::ConnectionExt;\n\nuse x11rb::*;\n\n\n", "file_path": "src/ipc.rs", "rank": 6, "score": 11.76515323111131 }, { "content": "use crate::{ewmh, ipc};\n\nuse anyhow::{bail, Context, Result};\n\nuse protocol::{\n\n xinerama,\n\n xproto::{self, ConnectionExt},\n\n};\n\nuse x11rb::wrapper::ConnectionExt as OtherConnectionExt;\n\nuse x11rb::*;\n\n\n\n#[derive(Clone, Debug)]\n", "file_path": "src/wm.rs", "rank": 8, "score": 8.514262453776087 }, { "content": "use crate::args::Args;\n\nuse anyhow::{bail, Context, Result};\n\nuse clap::Clap;\n\n\n\nmod args;\n\nmod ewmh;\n\nmod ipc;\n\nmod wm;\n\n\n\npub const NAME: &'static str = \"worm\";\n\npub const CONFIG_FILE: &'static str = \"config\";\n\n\n", "file_path": "src/main.rs", "rank": 9, "score": 7.976348876479882 }, { "content": " xproto::AtomEnum::WINDOW,\n\n &[screen.root],\n\n )?\n\n .check()?;\n\n conn.change_property32(\n\n xproto::PropMode::REPLACE,\n\n screen.root,\n\n net_atoms[ewmh::Net::Supported as usize],\n\n xproto::AtomEnum::ATOM,\n\n &net_atoms,\n\n )?\n\n .check()?;\n\n conn.change_property32(\n\n xproto::PropMode::REPLACE,\n\n screen.root,\n\n net_atoms[ewmh::Net::NumberOfDesktops as usize],\n\n xproto::AtomEnum::CARDINAL,\n\n &[9],\n\n )?\n\n .check()?;\n", "file_path": "src/wm.rs", "rank": 10, "score": 7.687126249583775 }, { "content": "\n\n pub fn switch_tag(&mut self, tag: usize) {\n\n for tag in self.data.iter_mut() {\n\n *tag = false;\n\n }\n\n self.data[tag] = true;\n\n }\n\n}\n\n\n\npub struct WindowManager<'a, C>\n\nwhere\n\n C: connection::Connection,\n\n{\n\n conn: &'a C,\n\n scrno: usize,\n\n button_press_geometry: Option<Geometry>,\n\n mouse_move_start: Option<MouseMoveStart>,\n\n clients: Vec<Client>,\n\n net_atoms: [xproto::Atom; ewmh::Net::Last as usize],\n\n ipc_atoms: [xproto::Atom; ipc::IPC::Last as usize],\n", "file_path": "src/wm.rs", "rank": 11, "score": 7.073871942965713 }, { "content": " self.conn.map_window(ev.window)?.check()?;\n\n // but it's still a client, so don't change any frame stuff, early return\n\n return Ok(()); // not really an error\n\n }\n\n // check the window type, no dock windows\n\n let reply = self\n\n .conn\n\n .get_property(\n\n false,\n\n ev.window,\n\n self.net_atoms[ewmh::Net::WMWindowType as usize],\n\n xproto::AtomEnum::ATOM,\n\n 0,\n\n 1024,\n\n )?\n\n .reply()?;\n\n for prop in reply.value {\n\n if prop == self.net_atoms[ewmh::Net::WMWindowTypeDock as usize] as u8 {\n\n self.conn.map_window(ev.window)?.check()?;\n\n return Ok(());\n", "file_path": "src/wm.rs", "rank": 12, "score": 6.799830427960162 }, { "content": "use std::path::PathBuf;\n\n\n\nuse clap::Clap;\n\n\n\n#[derive(Clap)]\n\n#[clap(\n\n version = \"0.1.0\",\n\n author = \"Aniket Prajapati <[email protected]>\"\n\n)]\n\npub struct Args {\n\n /// Sets a custom config file. Could have been an Option<T> with no default too\n\n #[clap(short, long)]\n\n pub config: Option<PathBuf>,\n\n}\n", "file_path": "src/args.rs", "rank": 15, "score": 5.41901957576407 }, { "content": " .x(0)\n\n .y(0)\n\n .width(ss.width)\n\n .height(ss.height)\n\n .border_width(0),\n\n )?;\n\n }\n\n // And we should change the appropriate property on the window, indicating that\n\n // we have successfully recieved and acted on the fullscreen request\n\n self.conn\n\n .change_property32(\n\n xproto::PropMode::REPLACE,\n\n client.window,\n\n self.net_atoms[ewmh::Net::WMState as usize],\n\n xproto::AtomEnum::ATOM,\n\n &[self.net_atoms[ewmh::Net::WMStateFullScreen as usize]],\n\n )?\n\n .check()?;\n\n } else {\n\n client.fullscreen = false;\n", "file_path": "src/wm.rs", "rank": 17, "score": 4.672972559269323 }, { "content": " xproto::EventMask::SUBSTRUCTURE_REDIRECT\n\n | xproto::EventMask::SUBSTRUCTURE_NOTIFY\n\n | xproto::EventMask::EXPOSURE\n\n | xproto::EventMask::STRUCTURE_NOTIFY\n\n | xproto::EventMask::PROPERTY_CHANGE,\n\n ),\n\n )?\n\n .check().context(\n\n \"a window manager is already running on this display (failed to capture SubstructureRedirect|SubstructureNotify on root window)\",\n\n )?;\n\n\n\n let net_atoms = match ewmh::get_ewmh_atoms(conn) {\n\n Ok(net_atoms) => net_atoms,\n\n Err(err) => bail!(\"{}\", err),\n\n };\n\n\n\n conn.change_property32(\n\n xproto::PropMode::REPLACE,\n\n screen.root,\n\n net_atoms[ewmh::Net::SupportingWMCheck as usize],\n", "file_path": "src/wm.rs", "rank": 20, "score": 4.385375440465111 }, { "content": " conn.change_property32(\n\n xproto::PropMode::REPLACE,\n\n screen.root,\n\n net_atoms[ewmh::Net::CurrentDesktop as usize],\n\n xproto::AtomEnum::CARDINAL,\n\n &[0],\n\n )?\n\n .check()?;\n\n Ok(Self {\n\n conn,\n\n scrno,\n\n button_press_geometry: None,\n\n mouse_move_start: None,\n\n clients: Vec::new(),\n\n net_atoms,\n\n ipc_atoms: match ipc::get_ipc_atoms(conn) {\n\n Ok(ipc_atoms) => ipc_atoms,\n\n Err(err) => bail!(\"{}\", err),\n\n },\n\n config: Config {\n", "file_path": "src/wm.rs", "rank": 21, "score": 4.304713284264018 }, { "content": " }\n\n }\n\n // Start off by setting _NET_FRAME_EXTENTS\n\n self.conn\n\n .change_property32(\n\n xproto::PropMode::REPLACE,\n\n ev.window,\n\n self.net_atoms[ewmh::Net::FrameExtents as usize],\n\n xproto::AtomEnum::CARDINAL,\n\n &[\n\n self.config.border_width as u32,\n\n self.config.border_width as u32,\n\n (self.config.border_width + self.config.title_height) as u32,\n\n self.config.border_width as u32,\n\n ],\n\n )?\n\n .check()?;\n\n let screen = &self.conn.setup().roots[self.scrno];\n\n let geom = self.conn.get_geometry(ev.window)?.reply()?;\n\n let attr = self.conn.get_window_attributes(ev.window)?.reply()?;\n", "file_path": "src/wm.rs", "rank": 22, "score": 4.117527025350752 }, { "content": " let tag_idx = tag_idx.context(\"map_request: not on any tag\")?;\n\n\n\n self.conn\n\n .change_property32(\n\n xproto::PropMode::REPLACE,\n\n ev.window,\n\n self.net_atoms[ewmh::Net::WMDesktop as usize],\n\n xproto::AtomEnum::CARDINAL,\n\n &[tag_idx as u32],\n\n )?\n\n .check()?;\n\n self.conn\n\n .change_window_attributes(\n\n ev.window,\n\n &xproto::ChangeWindowAttributesAux::new()\n\n .event_mask(xproto::EventMask::PROPERTY_CHANGE),\n\n )?\n\n .check()?;\n\n Ok(())\n\n }\n", "file_path": "src/wm.rs", "rank": 23, "score": 4.055105330377059 }, { "content": " Ok(())\n\n }\n\n\n\n fn handle_client_message(&mut self, ev: &xproto::ClientMessageEvent) -> Result<()> {\n\n // EWMH § _NET_WM_STATE; sent as a ClientMessage. in this the only thing we handle right\n\n // now is fullscreen messages.\n\n if ev.type_ == self.net_atoms[ewmh::Net::WMState as usize] {\n\n if ev.format != 32 {\n\n // The spec specifies the format must be 32, this is a buggy and misbehaving\n\n // application\n\n bail!(\"client_message: ev.format != 32, ignoring\");\n\n }\n\n let (_, client_idx) = self\n\n .find_client_mut(|client| client.window == ev.window)\n\n .context(\"client_message: unmap on non client window, ignoring\")?;\n\n let mut client = &mut self.clients[client_idx]; // we can't use the &mut Client we get & ignore from the find_client_mut method, because then we get errors about multiple mutable borrows... ugh!\n\n let data = ev.data.as_data32(); // it looks like it's not a simple getter but pulls out the bits and manipulates them, so I don't want to keep fetching it; cache it into an immutable stack local\n\n if data[1] == self.net_atoms[ewmh::Net::WMStateFullScreen as usize]\n\n || data[2] == self.net_atoms[ewmh::Net::WMStateFullScreen as usize]\n\n // EWMH § _NET_WM_STATE § _NET_WM_STATE_FULLSCREEN\n", "file_path": "src/wm.rs", "rank": 24, "score": 3.9626555829487904 }, { "content": "# worm\n\n*worm* is a floating, tag-based window manager for X11. It is written in the Rust programming language, using the X11RB library.\n\n\n\nA window manager is a program that manages windows, by letting the user move them, resize them, drawing titlebars, etc. It also provides functionality like workspaces and supports client side protocols, like EWMH and ICCCM in the X11 case. This lets the program do things like fullscreen itself.\n\n\n\nA floating window manager, like the \\*box family of window managers as well as Windows and MacOS (and of course worm), simply draws windows wherever they ask to be drawn and lets the user move them around. This is in contrast to a tiling window manager, which draws windows in a specific layout. Worm plans to eventually gain the ability to tile.\n\n\n\nTags are a unique concept borrowed from window managers like DWM and Awesome. Instead of workspaces having windows, windows have tags. This is a very unique concept. You can view 3 separate tags at a time, or have a window on 3 separate tags. Right now only the use case of being used like workspaces is supported, but internally the foundation for tags is there; just needs to be exposed to the user with IPC support.\n\n\n\n## Building\n\nBuilding requires cargo/rust to be installed on your system.\n\nSimply clone this git repository and build with cargo:\n\n```\n\n$ git clone https://github.com/codic12/worm\n\n$ cd worm\n\n$ cargo build --release\n\n```\n\n\n\nYou'll find the binaries in the `target/release` directory.\n\n\n\n## Installing\n\nAfter building, copy `worm` and `wormc` to a directory listed in the PATH variable.\n\n(typically you'd put it into `/usr/local/bin`)\n\n\n\n```\n\n$ sudo cp target/release/{worm,wormc} /usr/local/bin/\n\n```\n\n\n\nFor those of you using a display manager, you can copy the `worm.desktop` file located in `assets` to your xsessions directoy.\n\n\n\n```\n\n$ sudo cp assets/worm.desktop /usr/share/xsessions/\n\n```\n\n\n\nIf you're running an Arch-based distribution, you can use the [worm-git](https://aur.archlinux.org/packages/worm-git/) AUR package to build and install worm.\n\n\n\n\n", "file_path": "README.md", "rank": 25, "score": 3.720847779773341 }, { "content": " .border_width(0),\n\n )?;\n\n // Change the property on the window, indicating we've successfully recieved\n\n // and gone through with the request to un-fullscreen\n\n self.conn\n\n .change_property32(\n\n xproto::PropMode::REPLACE,\n\n client.window,\n\n self.net_atoms[ewmh::Net::WMState as usize],\n\n xproto::AtomEnum::ATOM,\n\n &[],\n\n )?\n\n .check()?;\n\n client.before_geom = None; // so that if somehow this case is hit but before_geom is not set, then the condition at the top returns early with an error\n\n }\n\n }\n\n } else if ev.type_ == self.ipc_atoms[ipc::IPC::ClientMessage as usize] {\n\n let data = ev.data.as_data32();\n\n match data {\n\n data if data[0] == ipc::IPC::KillActiveClient as u32 => {\n", "file_path": "src/wm.rs", "rank": 26, "score": 3.6829888822205046 }, { "content": " let focused = self\n\n .focused\n\n .context(\"client_message: no focused window to kill\")?; // todo: get-input_focus\n\n if focused > (self.clients.len() - 1) {\n\n self.focused = None;\n\n return Ok(()); // It looks like we hit a race condition... some very fast bad user, or more likely a crappy slow X11 server\n\n }\n\n self.conn\n\n .kill_client(self.clients[focused].window)?\n\n .check()?;\n\n }\n\n data if data[0] == ipc::IPC::SwitchTag as u32 => {\n\n let screen = &self.conn.setup().roots[self.scrno];\n\n self.tags.switch_tag((data[1] - 1) as usize);\n\n self.conn\n\n .change_property32(\n\n xproto::PropMode::REPLACE,\n\n screen.root,\n\n self.net_atoms[ewmh::Net::CurrentDesktop as usize],\n\n xproto::AtomEnum::CARDINAL,\n", "file_path": "src/wm.rs", "rank": 27, "score": 3.532304609531821 }, { "content": " border_width: 3,\n\n title_height: 15,\n\n border_pixel: 0xFFC3A070,\n\n background_pixel: 0xFF291E1B,\n\n //background_pixel: 0xFFFFFFFF,\n\n },\n\n tags: TagSet::default(),\n\n focused: None,\n\n })\n\n }\n\n\n\n pub fn event_loop(&mut self) {\n\n loop {\n\n let _ = self.conn.flush();\n\n let ev = match self.conn.wait_for_event() {\n\n Ok(ev) => ev,\n\n\n\n Err(_) => continue,\n\n };\n\n let _ = self.dispatch_event(&ev);\n", "file_path": "src/wm.rs", "rank": 28, "score": 1.972788446815644 }, { "content": "## Autostart / configuration\n\nWorm will try to execute the file `~/.config/worm/autostart` on startup. \n\nSimply create it as a shell-script to execute your favorite applications with worm. \n\n(don't forget to make it executable)\n\n\n\nAn example can be found [here](examples/autostart)\n\n\n\n## Screenshots\n\nCheck the wiki page.\n\n\n\n## Contribute\n\nUse it! Spread the word! Report issues! Submit pull requests!\n\n\n\n## License\n\nWorm is distributed under the [MIT License](LICENSE); you may obtain a copy [here](https://mit-license.org/).\n", "file_path": "README.md", "rank": 29, "score": 1.7083034583339636 }, { "content": " config: Config,\n\n tags: TagSet,\n\n focused: Option<usize>,\n\n}\n\n\n\nimpl<'a, C> WindowManager<'a, C>\n\nwhere\n\n C: connection::Connection,\n\n{\n\n pub fn new(conn: &'a C, scrno: usize) -> Result<Self> {\n\n let screen = &conn.setup().roots[scrno];\n\n for button in [xproto::ButtonIndex::M1, xproto::ButtonIndex::M3] {\n\n match conn\n\n .grab_button(\n\n false,\n\n screen.root,\n\n u32::from(\n\n xproto::EventMask::BUTTON_PRESS\n\n | xproto::EventMask::BUTTON_RELEASE\n\n | xproto::EventMask::POINTER_MOTION,\n", "file_path": "src/wm.rs", "rank": 30, "score": 1.6396011627541456 }, { "content": " .height(height as u32),\n\n )?;\n\n // ICCCM § 4.2.3; otherwise, things like firefox menus will be offset when you move but not resize, so we have to send a synthetic ConfigureNotify. a lot of these fields are not specified so I just ignore them with what seems like sensible default values; I doubt the client looks at those anyways.\n\n self.conn\n\n .send_event(\n\n false,\n\n client.window,\n\n xproto::EventMask::STRUCTURE_NOTIFY,\n\n xproto::ConfigureNotifyEvent {\n\n above_sibling: NONE,\n\n border_width: 0,\n\n event: client.window,\n\n window: client.window,\n\n x: x as i16,\n\n y: y as i16,\n\n width: width as u16,\n\n height: height as u16,\n\n override_redirect: false,\n\n response_type: xproto::CONFIGURE_NOTIFY_EVENT,\n\n sequence: 0,\n", "file_path": "src/wm.rs", "rank": 31, "score": 1.4908181821497828 } ]
Rust
generative_design/random_and_noise/m_1_3_03.rs
nfletton/nannou
c7c99328a16221a4d0b196c52647f30d75170b14
/** * creates a texture based on noise values * * MOUSE * position x/y : specify noise input range * * KEYS * 1-2 : set noise mode * arrow up : noise falloff + * arrow down : noise falloff - * arrow left : noise octaves - * arrow right : noise octaves + * s : save png */ use nannou::image; use nannou::noise::{MultiFractal, NoiseFn, Seedable}; use nannou::prelude::*; fn main() { nannou::app(model).run(); } struct Model { octaves: usize, falloff: f32, noise_mode: u8, noise_random_seed: u32, texture: wgpu::Texture, } fn model(app: &App) -> Model { let _window = app .new_window() .size(512, 512) .view(view) .key_pressed(key_pressed) .key_released(key_released) .build() .unwrap(); let window = app.main_window(); let win = window.rect(); let texture = wgpu::TextureBuilder::new() .size([win.w() as u32, win.h() as u32]) .format(wgpu::TextureFormat::Rgba8Unorm) .usage(wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING) .build(window.device()); Model { octaves: 4, falloff: 0.5, noise_mode: 1, noise_random_seed: 392, texture, } } fn view(app: &App, model: &Model, frame: Frame) { frame.clear(BLACK); let win = app.window_rect(); let noise = nannou::noise::Fbm::new() .set_seed(model.noise_random_seed) .set_octaves(model.octaves) .set_persistence(model.falloff as f64); let noise_x_range = map_range(app.mouse.x, win.left(), win.right(), 0.0, win.w() / 10.0); let noise_y_range = map_range(app.mouse.y, win.top(), win.bottom(), 0.0, win.h() / 10.0); let image = image::ImageBuffer::from_fn(win.w() as u32, win.h() as u32, |x, y| { let noise_x = map_range(x, 0, win.w() as u32, 0.0, noise_x_range) as f64; let noise_y = map_range(y, 0, win.h() as u32, 0.0, noise_y_range) as f64; let mut noise_value = 0.0; if model.noise_mode == 1 { noise_value = map_range( noise.get([noise_x, noise_y]), 1.0, -1.0, 0.0, std::u8::MAX as f64, ); } else if model.noise_mode == 2 { let n = map_range( noise.get([noise_x, noise_y]), -1.0, 1.0, 0.0, std::u8::MAX as f64 / 10.0, ); noise_value = (n - n.floor()) * std::u8::MAX as f64; } let n = noise_value as u8; nannou::image::Rgba([n, n, n, std::u8::MAX]) }); let flat_samples = image.as_flat_samples(); model.texture.upload_data( app.main_window().device(), &mut *frame.command_encoder(), &flat_samples.as_slice(), ); let draw = app.draw(); draw.texture(&model.texture); draw.to_frame(app, &frame).unwrap(); } fn key_released(app: &App, model: &mut Model, key: Key) { match key { Key::S => { app.main_window() .capture_frame(app.exe_name().unwrap() + ".png"); } Key::Space => { model.noise_random_seed = (random_f32() * 100000.0) as u32; } Key::Key1 => { model.noise_mode = 1; } Key::Key2 => { model.noise_mode = 2; } _otherkey => (), } } fn key_pressed(_app: &App, model: &mut Model, key: Key) { match key { Key::Up => { model.falloff += 0.05; } Key::Down => { model.falloff -= 0.05; } Key::Left => { model.octaves -= 1; } Key::Right => { model.octaves += 1; } _otherkey => (), } if model.falloff > 1.0 { model.falloff = 1.0; } if model.falloff <= 0.0 { model.falloff = 0.0; } if model.octaves <= 1 { model.octaves = 1; } }
/** * creates a texture based on noise values * * MOUSE * position x/y : specify noise input range * * KEYS * 1-2 : set noise mode * arrow up : noise falloff + * arrow down : noise falloff - * arrow left : noise octaves - * arrow right : noise octaves + * s : save png */ use nannou::image; use nannou::noise::{MultiFractal, NoiseFn, Seedable}; use nannou::prelude::*; fn main() { nannou::app(model).run(); } struct Model {
model.octaves -= 1; } Key::Right => { model.octaves += 1; } _otherkey => (), } if model.falloff > 1.0 { model.falloff = 1.0; } if model.falloff <= 0.0 { model.falloff = 0.0; } if model.octaves <= 1 { model.octaves = 1; } }
octaves: usize, falloff: f32, noise_mode: u8, noise_random_seed: u32, texture: wgpu::Texture, } fn model(app: &App) -> Model { let _window = app .new_window() .size(512, 512) .view(view) .key_pressed(key_pressed) .key_released(key_released) .build() .unwrap(); let window = app.main_window(); let win = window.rect(); let texture = wgpu::TextureBuilder::new() .size([win.w() as u32, win.h() as u32]) .format(wgpu::TextureFormat::Rgba8Unorm) .usage(wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING) .build(window.device()); Model { octaves: 4, falloff: 0.5, noise_mode: 1, noise_random_seed: 392, texture, } } fn view(app: &App, model: &Model, frame: Frame) { frame.clear(BLACK); let win = app.window_rect(); let noise = nannou::noise::Fbm::new() .set_seed(model.noise_random_seed) .set_octaves(model.octaves) .set_persistence(model.falloff as f64); let noise_x_range = map_range(app.mouse.x, win.left(), win.right(), 0.0, win.w() / 10.0); let noise_y_range = map_range(app.mouse.y, win.top(), win.bottom(), 0.0, win.h() / 10.0); let image = image::ImageBuffer::from_fn(win.w() as u32, win.h() as u32, |x, y| { let noise_x = map_range(x, 0, win.w() as u32, 0.0, noise_x_range) as f64; let noise_y = map_range(y, 0, win.h() as u32, 0.0, noise_y_range) as f64; let mut noise_value = 0.0; if model.noise_mode == 1 { noise_value = map_range( noise.get([noise_x, noise_y]), 1.0, -1.0, 0.0, std::u8::MAX as f64, ); } else if model.noise_mode == 2 { let n = map_range( noise.get([noise_x, noise_y]), -1.0, 1.0, 0.0, std::u8::MAX as f64 / 10.0, ); noise_value = (n - n.floor()) * std::u8::MAX as f64; } let n = noise_value as u8; nannou::image::Rgba([n, n, n, std::u8::MAX]) }); let flat_samples = image.as_flat_samples(); model.texture.upload_data( app.main_window().device(), &mut *frame.command_encoder(), &flat_samples.as_slice(), ); let draw = app.draw(); draw.texture(&model.texture); draw.to_frame(app, &frame).unwrap(); } fn key_released(app: &App, model: &mut Model, key: Key) { match key { Key::S => { app.main_window() .capture_frame(app.exe_name().unwrap() + ".png"); } Key::Space => { model.noise_random_seed = (random_f32() * 100000.0) as u32; } Key::Key1 => { model.noise_mode = 1; } Key::Key2 => { model.noise_mode = 2; } _otherkey => (), } } fn key_pressed(_app: &App, model: &mut Model, key: Key) { match key { Key::Up => { model.falloff += 0.05; } Key::Down => { model.falloff -= 0.05; } Key::Left => {
random
[]
Rust
systeroid-tui/src/command.rs
orhun/systeroid
ba32367beb5cbe052d2cce6cc98b2babe742df28
use crate::options::{Direction, ScrollArea}; use std::str::FromStr; use termion::event::Key; #[derive(Debug, PartialEq)] pub enum Command { Help, Select, Set(String, String), Scroll(ScrollArea, Direction, u8), MoveCursor(Direction), Search, ProcessInput, UpdateInput(char), ClearInput(bool), Copy, Refresh, Cancel, Exit, Nothing, } impl FromStr for Command { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "help" => Ok(Command::Help), "search" => Ok(Command::Search), "select" => Ok(Command::Select), "copy" => Ok(Command::Copy), "refresh" => Ok(Command::Refresh), "exit" | "quit" | "q" | "q!" => Ok(Command::Exit), _ => { if s.starts_with("set") { let values: Vec<&str> = s .trim_start_matches("set") .trim() .split_whitespace() .collect(); Ok(Command::Set( values.first().ok_or(())?.to_string(), values[1..].join(" "), )) } else if s.starts_with("scroll") { let mut values = s.trim_start_matches("scroll").trim().split_whitespace(); Ok(Command::Scroll( ScrollArea::try_from(values.next().ok_or(())?)?, Direction::try_from(values.next().ok_or(())?)?, values.next().and_then(|v| v.parse().ok()).unwrap_or(1), )) } else { Err(()) } } } } } impl Command { pub fn parse(key: Key, input_mode: bool) -> Self { if input_mode { match key { Key::Char('\n') => Command::ProcessInput, Key::Char(c) => Command::UpdateInput(c), Key::Backspace => Command::ClearInput(false), Key::Delete => Command::ClearInput(true), Key::Left => Command::MoveCursor(Direction::Left), Key::Right => Command::MoveCursor(Direction::Right), Key::Esc => Command::Cancel, _ => Command::Nothing, } } else { match key { Key::Char('?') | Key::F(1) => Command::Help, Key::Up | Key::Char('k') => Command::Scroll(ScrollArea::List, Direction::Up, 1), Key::Down | Key::Char('j') => Command::Scroll(ScrollArea::List, Direction::Down, 1), Key::PageUp => Command::Scroll(ScrollArea::List, Direction::Up, 4), Key::PageDown => Command::Scroll(ScrollArea::List, Direction::Down, 4), Key::Char('t') => Command::Scroll(ScrollArea::List, Direction::Top, 0), Key::Char('b') => Command::Scroll(ScrollArea::List, Direction::Bottom, 0), Key::Left | Key::Char('h') => { Command::Scroll(ScrollArea::Documentation, Direction::Up, 1) } Key::Right | Key::Char('l') => { Command::Scroll(ScrollArea::Documentation, Direction::Down, 1) } Key::Char('`') => Command::Scroll(ScrollArea::Section, Direction::Left, 1), Key::Char('\t') => Command::Scroll(ScrollArea::Section, Direction::Right, 1), Key::Char(':') => Command::UpdateInput(' '), Key::Char('/') | Key::Char('s') => Command::Search, Key::Char('\n') => Command::Select, Key::Char('c') => Command::Copy, Key::Char('r') | Key::F(5) => Command::Refresh, Key::Esc => Command::Cancel, Key::Char('q') | Key::Ctrl('c') | Key::Ctrl('d') => Command::Exit, _ => Command::Nothing, } } } } #[cfg(test)] mod tests { use super::*; macro_rules! assert_command_parser { (input_mode: $input_mode: expr, $($key: expr => $command: expr,)+ ) => { $(assert_eq!($command, Command::parse($key, $input_mode)));+ }; } #[test] fn test_command() { for (command, value) in vec![ (Command::Help, "help"), (Command::Search, "search"), (Command::Select, "select"), (Command::Copy, "copy"), (Command::Refresh, "refresh"), (Command::Exit, "quit"), ( Command::Set(String::from("a"), String::from("b c")), "set a b c", ), ( Command::Scroll(ScrollArea::List, Direction::Up, 1), "scroll list up 1", ), ( Command::Scroll(ScrollArea::Documentation, Direction::Down, 4), "scroll docs down 4", ), ( Command::Scroll(ScrollArea::Section, Direction::Top, 1), "scroll section top 1", ), ( Command::Scroll(ScrollArea::List, Direction::Bottom, 1), "scroll list bottom 1", ), ] { assert_eq!(command, Command::from_str(value).unwrap()); } assert!(Command::from_str("---").is_err()); assert_command_parser! { input_mode: true, Key::Char('\n') => Command::ProcessInput, Key::Char('a') => Command::UpdateInput('a'), Key::Backspace => Command::ClearInput(false), Key::Delete => Command::ClearInput(true), Key::Left => Command::MoveCursor(Direction::Left), Key::Right => Command::MoveCursor(Direction::Right), Key::Esc => Command::Cancel, } assert_command_parser! { input_mode: false, Key::Char('?') => Command::Help, Key::Up => Command::Scroll(ScrollArea::List, Direction::Up, 1), Key::Down => Command::Scroll(ScrollArea::List, Direction::Down, 1), Key::PageUp => Command::Scroll(ScrollArea::List, Direction::Up, 4), Key::PageDown => Command::Scroll(ScrollArea::List, Direction::Down, 4), Key::Char('t') => Command::Scroll(ScrollArea::List, Direction::Top, 0), Key::Char('b') => Command::Scroll(ScrollArea::List, Direction::Bottom, 0), Key::Left => Command::Scroll(ScrollArea::Documentation, Direction::Up, 1), Key::Right => Command::Scroll(ScrollArea::Documentation, Direction::Down, 1), Key::Char('`') => Command::Scroll(ScrollArea::Section, Direction::Left, 1), Key::Char('\t') => Command::Scroll(ScrollArea::Section, Direction::Right, 1), Key::Char(':') => Command::UpdateInput(' '), Key::Char('/') => Command::Search, Key::Char('\n') => Command::Select, Key::Char('c') => Command::Copy, Key::Char('r') => Command::Refresh, Key::Esc => Command::Cancel, Key::Ctrl('c') => Command::Exit, } assert_eq!(Command::Nothing, Command::parse(Key::PageDown, true)); assert_eq!(Command::Nothing, Command::parse(Key::Char('#'), false)); } }
use crate::options::{Direction, ScrollArea}; use std::str::FromStr; use termion::event::Key; #[derive(Debug, PartialEq)] pub enum Command { Help, Select, Set(String, String), Scroll(ScrollArea, Direction, u8), MoveCursor(Direction), Search, ProcessInput, UpdateInput(char), ClearInput(bool), Copy, Refresh, Cancel, Exit, Nothing, } impl FromStr for Command { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "help" => Ok(Command::Help), "search" => Ok(Command::Search), "select" => Ok(Command::Select), "copy" => Ok(Command::Copy), "refresh" => Ok(Command::Refresh), "exit" | "quit" | "q" | "q!" => Ok(Command::Exit), _ => {
} } } } impl Command { pub fn parse(key: Key, input_mode: bool) -> Self { if input_mode { match key { Key::Char('\n') => Command::ProcessInput, Key::Char(c) => Command::UpdateInput(c), Key::Backspace => Command::ClearInput(false), Key::Delete => Command::ClearInput(true), Key::Left => Command::MoveCursor(Direction::Left), Key::Right => Command::MoveCursor(Direction::Right), Key::Esc => Command::Cancel, _ => Command::Nothing, } } else { match key { Key::Char('?') | Key::F(1) => Command::Help, Key::Up | Key::Char('k') => Command::Scroll(ScrollArea::List, Direction::Up, 1), Key::Down | Key::Char('j') => Command::Scroll(ScrollArea::List, Direction::Down, 1), Key::PageUp => Command::Scroll(ScrollArea::List, Direction::Up, 4), Key::PageDown => Command::Scroll(ScrollArea::List, Direction::Down, 4), Key::Char('t') => Command::Scroll(ScrollArea::List, Direction::Top, 0), Key::Char('b') => Command::Scroll(ScrollArea::List, Direction::Bottom, 0), Key::Left | Key::Char('h') => { Command::Scroll(ScrollArea::Documentation, Direction::Up, 1) } Key::Right | Key::Char('l') => { Command::Scroll(ScrollArea::Documentation, Direction::Down, 1) } Key::Char('`') => Command::Scroll(ScrollArea::Section, Direction::Left, 1), Key::Char('\t') => Command::Scroll(ScrollArea::Section, Direction::Right, 1), Key::Char(':') => Command::UpdateInput(' '), Key::Char('/') | Key::Char('s') => Command::Search, Key::Char('\n') => Command::Select, Key::Char('c') => Command::Copy, Key::Char('r') | Key::F(5) => Command::Refresh, Key::Esc => Command::Cancel, Key::Char('q') | Key::Ctrl('c') | Key::Ctrl('d') => Command::Exit, _ => Command::Nothing, } } } } #[cfg(test)] mod tests { use super::*; macro_rules! assert_command_parser { (input_mode: $input_mode: expr, $($key: expr => $command: expr,)+ ) => { $(assert_eq!($command, Command::parse($key, $input_mode)));+ }; } #[test] fn test_command() { for (command, value) in vec![ (Command::Help, "help"), (Command::Search, "search"), (Command::Select, "select"), (Command::Copy, "copy"), (Command::Refresh, "refresh"), (Command::Exit, "quit"), ( Command::Set(String::from("a"), String::from("b c")), "set a b c", ), ( Command::Scroll(ScrollArea::List, Direction::Up, 1), "scroll list up 1", ), ( Command::Scroll(ScrollArea::Documentation, Direction::Down, 4), "scroll docs down 4", ), ( Command::Scroll(ScrollArea::Section, Direction::Top, 1), "scroll section top 1", ), ( Command::Scroll(ScrollArea::List, Direction::Bottom, 1), "scroll list bottom 1", ), ] { assert_eq!(command, Command::from_str(value).unwrap()); } assert!(Command::from_str("---").is_err()); assert_command_parser! { input_mode: true, Key::Char('\n') => Command::ProcessInput, Key::Char('a') => Command::UpdateInput('a'), Key::Backspace => Command::ClearInput(false), Key::Delete => Command::ClearInput(true), Key::Left => Command::MoveCursor(Direction::Left), Key::Right => Command::MoveCursor(Direction::Right), Key::Esc => Command::Cancel, } assert_command_parser! { input_mode: false, Key::Char('?') => Command::Help, Key::Up => Command::Scroll(ScrollArea::List, Direction::Up, 1), Key::Down => Command::Scroll(ScrollArea::List, Direction::Down, 1), Key::PageUp => Command::Scroll(ScrollArea::List, Direction::Up, 4), Key::PageDown => Command::Scroll(ScrollArea::List, Direction::Down, 4), Key::Char('t') => Command::Scroll(ScrollArea::List, Direction::Top, 0), Key::Char('b') => Command::Scroll(ScrollArea::List, Direction::Bottom, 0), Key::Left => Command::Scroll(ScrollArea::Documentation, Direction::Up, 1), Key::Right => Command::Scroll(ScrollArea::Documentation, Direction::Down, 1), Key::Char('`') => Command::Scroll(ScrollArea::Section, Direction::Left, 1), Key::Char('\t') => Command::Scroll(ScrollArea::Section, Direction::Right, 1), Key::Char(':') => Command::UpdateInput(' '), Key::Char('/') => Command::Search, Key::Char('\n') => Command::Select, Key::Char('c') => Command::Copy, Key::Char('r') => Command::Refresh, Key::Esc => Command::Cancel, Key::Ctrl('c') => Command::Exit, } assert_eq!(Command::Nothing, Command::parse(Key::PageDown, true)); assert_eq!(Command::Nothing, Command::parse(Key::Char('#'), false)); } }
if s.starts_with("set") { let values: Vec<&str> = s .trim_start_matches("set") .trim() .split_whitespace() .collect(); Ok(Command::Set( values.first().ok_or(())?.to_string(), values[1..].join(" "), )) } else if s.starts_with("scroll") { let mut values = s.trim_start_matches("scroll").trim().split_whitespace(); Ok(Command::Scroll( ScrollArea::try_from(values.next().ok_or(())?)?, Direction::try_from(values.next().ok_or(())?)?, values.next().and_then(|v| v.parse().ok()).unwrap_or(1), )) } else { Err(()) }
if_condition
[ { "content": "/// Renders the user interface.\n\npub fn render<B: Backend>(frame: &mut Frame<'_, B>, app: &mut App, colors: &Colors) {\n\n let documentation = app\n\n .parameter_list\n\n .selected()\n\n .and_then(|parameter| parameter.get_documentation());\n\n let rect = frame.size();\n\n let chunks = Layout::default()\n\n .direction(Direction::Horizontal)\n\n .constraints(if documentation.is_some() {\n\n [Constraint::Percentage(50), Constraint::Percentage(50)]\n\n } else {\n\n [Constraint::Percentage(100), Constraint::Min(0)]\n\n })\n\n .split(rect);\n\n {\n\n let chunks = Layout::default()\n\n .direction(Direction::Vertical)\n\n .constraints(if app.input.is_some() {\n\n [Constraint::Min(rect.height - 3), Constraint::Min(3)]\n\n } else {\n", "file_path": "systeroid-tui/src/ui.rs", "rank": 0, "score": 53196.61393958135 }, { "content": "/// Parses the kernel documentation using the defined parsers.\n\npub fn parse_kernel_docs(kernel_docs: &Path) -> Result<Vec<Document>> {\n\n PARSERS\n\n .par_iter()\n\n .try_fold(Vec::new, |mut documents, parser| {\n\n documents.extend(parser.parse(kernel_docs)?);\n\n Ok::<Vec<Document>, Error>(documents)\n\n })\n\n .try_reduce(Vec::new, |mut v1, v2| {\n\n v1.extend(v2);\n\n Ok(v1)\n\n })\n\n}\n", "file_path": "systeroid-core/src/parsers.rs", "rank": 1, "score": 52818.21240670502 }, { "content": "/// Runs `systeroid-tui`.\n\npub fn run<B: Backend>(args: Args, backend: B) -> Result<()> {\n\n let mut sysctl = Sysctl::init(Config::default())?;\n\n if !args.no_docs {\n\n sysctl.update_docs_from_cache(args.kernel_docs.as_ref(), &Cache::init()?)?;\n\n }\n\n let mut terminal = Terminal::new(backend)?;\n\n terminal.hide_cursor()?;\n\n terminal.clear()?;\n\n let event_handler = EventHandler::new(args.tick_rate);\n\n let mut app = App::new(&mut sysctl);\n\n if let Some(section) = args.section {\n\n app.section_list.state.select(Some(\n\n app.section_list\n\n .items\n\n .iter()\n\n .position(|r| r == &section.to_string())\n\n .unwrap_or(0),\n\n ));\n\n app.search();\n\n }\n", "file_path": "systeroid-tui/src/lib.rs", "rank": 2, "score": 52720.46193526554 }, { "content": "/// Runs `systeroid`.\n\npub fn run<Output: Write>(args: Args, output: &mut Output) -> Result<()> {\n\n let config = Config {\n\n verbose: args.verbose,\n\n ignore_errors: args.ignore_errors,\n\n quiet: args.quiet,\n\n no_pager: args.no_pager,\n\n display_type: args.display_type,\n\n ..Default::default()\n\n };\n\n let mut sysctl = Sysctl::init(config)?;\n\n if args.explain {\n\n sysctl.update_docs_from_cache(args.kernel_docs.as_ref(), &Cache::init()?)?;\n\n }\n\n let mut app = App::new(&mut sysctl, output, args.output_type);\n\n\n\n if args.preload_system_files {\n\n app.preload_from_system()?;\n\n } else if args.values.is_empty() {\n\n app.display_parameters(args.pattern, args.display_deprecated, args.explain)?;\n\n } else if args.explain {\n", "file_path": "systeroid/src/lib.rs", "rank": 3, "score": 52113.03372823895 }, { "content": "/// Renders the text for displaying help.\n\nfn render_help_text<B: Backend>(\n\n frame: &mut Frame<'_, B>,\n\n rect: Rect,\n\n key_bindings: &mut SelectableList<&KeyBinding>,\n\n colors: &Colors,\n\n) {\n\n let (percent_x, percent_y) = (50, 50);\n\n let popup_layout = Layout::default()\n\n .direction(Direction::Vertical)\n\n .constraints(\n\n [\n\n Constraint::Percentage((100 - percent_y) / 2),\n\n Constraint::Percentage(percent_y),\n\n Constraint::Percentage((100 - percent_y) / 2),\n\n ]\n\n .as_ref(),\n\n )\n\n .split(rect);\n\n let rect = Layout::default()\n\n .direction(Direction::Horizontal)\n", "file_path": "systeroid-tui/src/ui.rs", "rank": 4, "score": 51110.42801491629 }, { "content": "/// Renders the text for displaying the selected index.\n\nfn render_selection_text<B: Backend>(\n\n frame: &mut Frame<'_, B>,\n\n rect: Rect,\n\n selection_text: String,\n\n colors: &Colors,\n\n) {\n\n let selection_text_width = u16::try_from(selection_text.width()).unwrap_or_default();\n\n if let Some(horizontal_area_width) = rect.width.checked_sub(selection_text_width + 2) {\n\n let vertical_area = Layout::default()\n\n .direction(Direction::Vertical)\n\n .constraints(\n\n [\n\n Constraint::Min(rect.height.checked_sub(2).unwrap_or(rect.height)),\n\n Constraint::Min(1),\n\n Constraint::Min(1),\n\n ]\n\n .as_ref(),\n\n )\n\n .split(rect);\n\n let horizontal_area = Layout::default()\n", "file_path": "systeroid-tui/src/ui.rs", "rank": 5, "score": 51110.34820986737 }, { "content": "fn main() {\n\n if let Some(args) = Args::parse(env::args().collect()) {\n\n if args.show_tui {\n\n let bin = format!(\"{}-tui\", env!(\"CARGO_PKG_NAME\"));\n\n let mut command = Command::new(&bin);\n\n if let Some(kernel_docs) = args.kernel_docs {\n\n command.arg(\"--docs\").arg(kernel_docs);\n\n }\n\n match command.spawn().map(|mut child| child.wait()) {\n\n Ok(_) => process::exit(0),\n\n Err(e) => {\n\n eprintln!(\"Cannot run `{}` ({})\", bin, e);\n\n process::exit(1)\n\n }\n\n }\n\n } else {\n\n let mut stdout = io::stdout();\n\n match systeroid::run(args, &mut stdout) {\n\n Ok(_) => process::exit(0),\n\n Err(e) => {\n\n eprintln!(\"{}\", e);\n\n process::exit(1)\n\n }\n\n }\n\n }\n\n }\n\n}\n", "file_path": "systeroid/src/main.rs", "rank": 6, "score": 33712.335851402 }, { "content": "fn main() -> Result<()> {\n\n if let Some(args) = Args::parse(env::args().collect()) {\n\n let output = io::stderr();\n\n let output = output.into_raw_mode()?;\n\n let output = MouseTerminal::from(output);\n\n let output = AlternateScreen::from(output);\n\n let backend = TermionBackend::new(output);\n\n match systeroid_tui::run(args, backend) {\n\n Ok(_) => process::exit(0),\n\n Err(e) => {\n\n eprintln!(\"{}\", e);\n\n process::exit(1)\n\n }\n\n }\n\n }\n\n Ok(())\n\n}\n", "file_path": "systeroid-tui/src/main.rs", "rank": 7, "score": 30719.08316523953 }, { "content": "#[cfg_attr(not(feature = \"live-tests\"), ignore)]\n\n#[test]\n\nfn test_systeroid() -> Result<()> {\n\n let args = Args::default();\n\n let mut output = Vec::new();\n\n systeroid::run(args, &mut output)?;\n\n assert!(String::from_utf8_lossy(&output).contains(\"kernel.watchdog =\"));\n\n\n\n let args = Args {\n\n values: vec![String::from(\"vm.zone_reclaim_mode=0\")],\n\n display_type: DisplayType::Binary,\n\n ..Args::default()\n\n };\n\n let mut output = Vec::new();\n\n systeroid::run(args, &mut output)?;\n\n assert_eq!(\"0\", String::from_utf8_lossy(&output));\n\n\n\n let args = Args {\n\n preload_system_files: true,\n\n ..Args::default()\n\n };\n\n systeroid::run(args, &mut Vec::new())?;\n", "file_path": "systeroid/tests/live_test.rs", "rank": 8, "score": 29581.86356948709 }, { "content": "#[test]\n\nfn test_render_tui() -> Result<()> {\n\n let mut sysctl = Sysctl {\n\n parameters: vec![\n\n Parameter {\n\n name: String::from(\"user.name\"),\n\n value: String::from(\"system\"),\n\n description: None,\n\n section: Section::User,\n\n docs_path: PathBuf::new(),\n\n docs_title: String::new(),\n\n },\n\n Parameter {\n\n name: String::from(\"kernel.fictional.test_param\"),\n\n value: String::from(\"0\"),\n\n description: Some(String::from(\"This is a fictional parameter for testing\")),\n\n section: Section::Kernel,\n\n docs_path: PathBuf::from(\"/etc/cosmos\"),\n\n docs_title: String::from(\"Test Parameter\"),\n\n },\n\n Parameter {\n", "file_path": "systeroid-tui/tests/integration_test.rs", "rank": 19, "score": 27575.19992233089 }, { "content": "/// Renders the documentation of the selected sysctl parameter.\n\nfn render_parameter_documentation<B: Backend>(\n\n frame: &mut Frame<'_, B>,\n\n rect: Rect,\n\n documentation: String,\n\n scroll_amount: &mut u16,\n\n colors: &Colors,\n\n) {\n\n match (documentation.lines().count() * 2).checked_sub(rect.height.into()) {\n\n Some(scroll_overflow) => {\n\n if scroll_overflow < (*scroll_amount).into() {\n\n *scroll_amount = scroll_overflow as u16;\n\n }\n\n }\n\n None => {\n\n *scroll_amount = scroll_amount.checked_sub(1).unwrap_or_default();\n\n }\n\n }\n\n frame.render_widget(\n\n Paragraph::new(Text::styled(documentation, colors.get_fg_style()))\n\n .block(\n", "file_path": "systeroid-tui/src/ui.rs", "rank": 20, "score": 27255.393605342106 }, { "content": "/// Renders the input prompt for running commands.\n\nfn render_input_prompt<B: Backend>(\n\n frame: &mut Frame<'_, B>,\n\n rect: Rect,\n\n cursor_y: u16,\n\n app: &App,\n\n colors: &Colors,\n\n) {\n\n let text = match app.input.clone() {\n\n Some(mut input) => {\n\n if app.input_time.is_some() {\n\n format!(\"MSG: {}\", input)\n\n } else {\n\n let mut skip_chars = 0;\n\n if let Some(width_overflow) = (input.width() as u16 + 4)\n\n .checked_sub(app.input_cursor)\n\n .and_then(|v| v.checked_sub(rect.width))\n\n {\n\n skip_chars = width_overflow;\n\n input.replace_range(skip_chars as usize..(skip_chars + 1) as usize, \"\\u{2026}\");\n\n if let Some(cursor_x_end) = rect.width.checked_sub(2) {\n", "file_path": "systeroid-tui/src/ui.rs", "rank": 21, "score": 27255.336102173795 }, { "content": "/// Renders the list that contains the sysctl parameters.\n\nfn render_parameter_list<B: Backend>(\n\n frame: &mut Frame<'_, B>,\n\n rect: Rect,\n\n app: &mut App,\n\n colors: &Colors,\n\n) {\n\n let max_width = app\n\n .parameter_list\n\n .items\n\n .iter()\n\n .map(|p| p.name.len())\n\n .max_by(|x, y| x.cmp(y))\n\n .and_then(|v| u16::try_from(v).ok())\n\n .unwrap_or(1);\n\n let minimize_rows = rect.width < max_width + 10;\n\n let rows = app.parameter_list.items.iter().map(|item| {\n\n let value = item.value.replace('\\t', \" \");\n\n Row::new(if minimize_rows {\n\n vec![Cell::from(Span::styled(\n\n format!(\"{} = {}\", item.name, value),\n", "file_path": "systeroid-tui/src/ui.rs", "rank": 22, "score": 27251.677652746 }, { "content": "/// Renders the text for displaying the parameter section.\n\nfn render_section_text<B: Backend>(\n\n frame: &mut Frame<'_, B>,\n\n rect: Rect,\n\n section: &str,\n\n colors: &Colors,\n\n) {\n\n let section = format!(\"|{}|\", section);\n\n let text_width: u16 = section.width().try_into().unwrap_or(1);\n\n let vertical_area = Layout::default()\n\n .direction(Direction::Vertical)\n\n .constraints(\n\n [\n\n Constraint::Min(1),\n\n Constraint::Min(rect.height.checked_sub(1).unwrap_or(rect.height)),\n\n ]\n\n .as_ref(),\n\n )\n\n .split(rect);\n\n let area = Layout::default()\n\n .direction(Direction::Horizontal)\n", "file_path": "systeroid-tui/src/ui.rs", "rank": 23, "score": 27251.677652746 }, { "content": "/// Renders a list as a popup for showing options.\n\nfn render_options_menu<B: Backend>(\n\n frame: &mut Frame<'_, B>,\n\n rect: Rect,\n\n options: &mut SelectableList<&str>,\n\n colors: &Colors,\n\n) {\n\n let (length_x, length_y) = (\n\n 25,\n\n u16::try_from(options.items.len()).unwrap_or_default() + 2,\n\n );\n\n let popup_layout = Layout::default()\n\n .direction(Direction::Vertical)\n\n .constraints(\n\n [\n\n Constraint::Length((rect.height.checked_sub(length_y)).unwrap_or_default() / 2),\n\n Constraint::Min(length_y),\n\n Constraint::Length((rect.height.checked_sub(length_y)).unwrap_or_default() / 2),\n\n ]\n\n .as_ref(),\n\n )\n", "file_path": "systeroid-tui/src/ui.rs", "rank": 24, "score": 27251.677652746 }, { "content": "fn assert_buffer(mut buffer: Buffer, backend: &TestBackend) -> Result<()> {\n\n assert_eq!(buffer.area, backend.size()?);\n\n for x in 0..buffer.area().width {\n\n for y in 0..buffer.area().height {\n\n buffer\n\n .get_mut(x, y)\n\n .set_style(backend.buffer().get(x, y).style());\n\n }\n\n }\n\n backend.assert_buffer(&buffer);\n\n Ok(())\n\n}\n\n\n", "file_path": "systeroid-tui/tests/integration_test.rs", "rank": 25, "score": 22487.24986580936 }, { "content": "#### Running commands\n\n\n\nPress <kbd>:</kbd> to open the command prompt for running a command. Available commands are:\n\n\n\n| Command | Description |\n\n| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |\n\n| `:help` | Show help |\n\n| `:search` | Enable search |\n\n| `:select` | Select the current parameter in the list |\n\n| `:set <name> <value>` | Set parameter value |\n\n| `:scroll [area] [direction] <amount>` | Scroll the list or text<br>- areas: `list`, `docs`, `section`<br>- directions: `up`, `down`, `top`, `bottom`, `right`, `left` |\n\n| `:copy` | Copy to clipboard |\n\n| `:refresh` | Refresh values |\n\n| `:quit`, `:q` | Quit |\n\n\n", "file_path": "README.md", "rank": 26, "score": 24.578748587402835 }, { "content": " .find(|v| value == v.as_str())\n\n .copied()\n\n .ok_or(())\n\n }\n\n }\n\n\n\n impl $name {\n\n /// Returns the variants.\n\n pub fn variants() -> &'static [Self] {\n\n &[$(Self::$variant,)+]\n\n }\n\n\n\n /// Returns the string representation.\n\n pub fn as_str(&self) -> &'static str {\n\n match self {\n\n $(Self::$variant => $str_repr,)+\n\n }\n\n }\n\n }\n\n };\n", "file_path": "systeroid-tui/src/options.rs", "rank": 27, "score": 18.68820630019787 }, { "content": " /// Runs the given command and updates the application.\n\n pub fn run_command(&mut self, command: Command) -> Result<()> {\n\n let mut hide_popup = true;\n\n match command {\n\n Command::Help => {\n\n self.options = None;\n\n self.key_bindings = SelectableList::with_items(KEY_BINDINGS.to_vec());\n\n self.key_bindings.state.select(None);\n\n self.show_help = true;\n\n hide_popup = false;\n\n }\n\n Command::Select => {\n\n if let Some(copy_option) = self\n\n .options\n\n .as_ref()\n\n .and_then(|v| v.selected())\n\n .and_then(|v| CopyOption::try_from(*v).ok())\n\n {\n\n self.copy_to_clipboard(copy_option)?;\n\n self.options = None;\n", "file_path": "systeroid-tui/src/app.rs", "rank": 28, "score": 18.64425269807488 }, { "content": "use crate::command::Command;\n\nuse crate::error::Result;\n\nuse crate::options::{CopyOption, Direction, ScrollArea};\n\nuse crate::widgets::SelectableList;\n\n#[cfg(feature = \"clipboard\")]\n\nuse copypasta_ext::{display::DisplayServer, prelude::ClipboardProvider};\n\nuse std::str::FromStr;\n\nuse std::time::Instant;\n\nuse systeroid_core::sysctl::controller::Sysctl;\n\nuse systeroid_core::sysctl::parameter::Parameter;\n\nuse systeroid_core::sysctl::section::Section;\n\nuse unicode_width::UnicodeWidthStr;\n\n\n\n/// Representation of a key binding.\n\npub struct KeyBinding<'a> {\n\n /// Pressed key.\n\n pub key: &'a str,\n\n /// Action to perform.\n\n pub action: &'a str,\n\n}\n", "file_path": "systeroid-tui/src/app.rs", "rank": 29, "score": 18.435155499408765 }, { "content": " {\n\n parameter.value = param.value.to_string();\n\n }\n\n });\n\n }\n\n Command::Cancel => {\n\n if self.input.is_some() {\n\n self.input = None;\n\n self.input_time = None;\n\n } else if self.options.is_none() && !self.show_help {\n\n self.running = false;\n\n }\n\n }\n\n Command::Exit => {\n\n self.running = false;\n\n }\n\n Command::Nothing => {}\n\n }\n\n if hide_popup {\n\n self.options = None;\n", "file_path": "systeroid-tui/src/app.rs", "rank": 30, "score": 17.42876018557299 }, { "content": " \"fg-color\",\n\n \"set the foreground color [default: white]\",\n\n \"<color>\",\n\n );\n\n opts.optflag(\"n\", \"no-docs\", \"do not show the kernel documentation\");\n\n opts.optflag(\"h\", \"help\", \"display this help and exit\");\n\n opts.optflag(\"V\", \"version\", \"output version information and exit\");\n\n opts\n\n }\n\n\n\n /// Parses the command-line arguments.\n\n pub fn parse(env_args: Vec<String>) -> Option<Self> {\n\n let opts = Self::get_options();\n\n let matches = opts\n\n .parse(&env_args[1..])\n\n .map_err(|e| eprintln!(\"error: `{}`\", e))\n\n .ok()?;\n\n if matches.opt_present(\"h\") {\n\n let usage = opts.usage_with_format(|opts| {\n\n HELP_MESSAGE\n", "file_path": "systeroid-tui/src/args.rs", "rank": 31, "score": 16.343250196574914 }, { "content": " {\n\n copy_options.retain(|v| v != &CopyOption::Documentation)\n\n }\n\n self.options = Some(SelectableList::with_items(\n\n copy_options.iter().map(|v| v.as_str()).collect(),\n\n ));\n\n hide_popup = false;\n\n self.show_help = false;\n\n } else {\n\n self.input = Some(String::from(\"No parameter is selected\"));\n\n self.input_time = Some(Instant::now());\n\n }\n\n }\n\n Command::Refresh => {\n\n self.input = None;\n\n self.docs_scroll_amount = 0;\n\n let parameters = Sysctl::init(self.sysctl.config.clone())?.parameters;\n\n self.sysctl.parameters.iter_mut().for_each(|parameter| {\n\n if let Some(param) =\n\n parameters.iter().find(|param| param.name == parameter.name)\n", "file_path": "systeroid-tui/src/app.rs", "rank": 32, "score": 16.284502625725477 }, { "content": " .unwrap_or(self.docs_scroll_amount);\n\n }\n\n Command::Scroll(ScrollArea::Section, direction, _) => {\n\n match direction {\n\n Direction::Right => self.section_list.next(),\n\n _ => self.section_list.previous(),\n\n }\n\n self.search();\n\n if self.parameter_list.items.is_empty() {\n\n self.parameter_list.state.select(None);\n\n } else {\n\n self.parameter_list.state.select(Some(0));\n\n }\n\n }\n\n Command::Scroll(_, _, _) => {}\n\n Command::Search => {\n\n if self.input_time.is_some() {\n\n self.input_time = None;\n\n }\n\n self.search_mode = true;\n", "file_path": "systeroid-tui/src/app.rs", "rank": 33, "score": 16.258116301923927 }, { "content": " } else if self.show_help {\n\n self.key_bindings.state.select(None);\n\n } else if let Some(parameter) = self.parameter_list.selected() {\n\n self.search_mode = false;\n\n self.input_time = None;\n\n self.input = Some(format!(\"set {} {}\", parameter.name, parameter.value));\n\n }\n\n }\n\n Command::Set(param_name, new_value) => {\n\n if let Some(parameter) = self\n\n .parameter_list\n\n .items\n\n .iter_mut()\n\n .find(|param| param.name == param_name)\n\n {\n\n match parameter.update_value(&new_value, &self.sysctl.config, &mut Vec::new()) {\n\n Ok(()) => {\n\n self.run_command(Command::Refresh)?;\n\n }\n\n Err(e) => {\n", "file_path": "systeroid-tui/src/app.rs", "rank": 34, "score": 16.241400131160336 }, { "content": " },\n\n &KeyBinding {\n\n key: \"[/]\",\n\n action: \"search\",\n\n },\n\n &KeyBinding {\n\n key: \"enter\",\n\n action: \"select / set value\",\n\n },\n\n &KeyBinding {\n\n key: \"c\",\n\n action: \"copy to clipboard\",\n\n },\n\n &KeyBinding {\n\n key: \"r, f5\",\n\n action: \"refresh\",\n\n },\n\n &KeyBinding {\n\n key: \"esc\",\n\n action: \"cancel / exit\",\n", "file_path": "systeroid-tui/src/app.rs", "rank": 35, "score": 15.747151242110704 }, { "content": " opts.optflag(\"V\", \"version\", \"output version information and exit\");\n\n opts\n\n }\n\n\n\n /// Parses the command-line arguments.\n\n pub fn parse(env_args: Vec<String>) -> Option<Self> {\n\n let opts = Self::get_options();\n\n let mut matches = opts\n\n .parse(&env_args[1..])\n\n .map_err(|e| eprintln!(\"error: `{}`\", e))\n\n .ok()?;\n\n\n\n let preload_files = matches.opt_present(\"p\") || matches.opt_present(\"f\");\n\n let show_help = matches.opt_present(\"h\") || matches.opt_present(\"d\");\n\n let display_all = matches.opt_present(\"a\")\n\n || matches.opt_present(\"A\")\n\n || matches.opt_present(\"X\")\n\n || matches.opt_present(\"N\")\n\n || matches.opt_present(\"n\")\n\n || matches.opt_present(\"b\");\n", "file_path": "systeroid/src/args.rs", "rank": 36, "score": 15.018592251908169 }, { "content": "### Key Bindings\n\n\n\n| Key | Action |\n\n| ---------------------------------------------------------- | ---------------------------- |\n\n| <kbd>?</kbd>, <kbd>f1</kbd> | show help |\n\n| <kbd>up/down</kbd>, <kbd>k/j</kbd>, <kbd>pgup/pgdown</kbd> | scroll list |\n\n| <kbd>t/b</kbd> | scroll to top/bottom |\n\n| <kbd>left/right</kbd>, <kbd>h/l</kbd> | scroll documentation |\n\n| <kbd>tab</kbd>, <kbd>`</kbd> | next/previous section |\n\n| <kbd>:</kbd> | command |\n\n| <kbd>/</kbd>, <kbd>s</kbd> | search |\n\n| <kbd>enter</kbd> | select / set parameter value |\n\n| <kbd>c</kbd> | copy to clipboard |\n\n| <kbd>r</kbd>, <kbd>f5</kbd> | refresh |\n\n| <kbd>esc</kbd> | cancel / exit |\n\n| <kbd>q</kbd>, <kbd>ctrl-c/ctrl-d</kbd> | exit |\n\n\n\n### Examples\n\n\n\n#### Launching\n\n\n\nSimply run `systeroid-tui` to launch the terminal user interface. Alternatively, you can use `systeroid --tui` command (which runs `systeroid-tui` under the hood if it is found in [`PATH`](<https://en.wikipedia.org/wiki/PATH_(variable)>)).\n\n\n\n#### Showing help\n\n\n\nHelp menu and key bindings can be shown via pressing <kbd>?</kbd>:\n\n\n\n![Help](assets/systeroid-tui-help.gif)\n\n\n", "file_path": "README.md", "rank": 37, "score": 14.872886854050716 }, { "content": " search_query: matches.opt_str(\"q\"),\n\n colors: Colors::new(\n\n matches.opt_str(\"bg-color\").as_deref().unwrap_or(\"black\"),\n\n matches.opt_str(\"fg-color\").as_deref().unwrap_or(\"white\"),\n\n )\n\n .map_err(|e| eprintln!(\"error: `{}`\", e))\n\n .ok()?,\n\n no_docs: matches.opt_present(\"n\"),\n\n })\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_args() {\n\n for env_args in [\n", "file_path": "systeroid-tui/src/args.rs", "rank": 38, "score": 14.49879197193616 }, { "content": "use crate::app::{App, KeyBinding, HELP_TEXT};\n\nuse crate::style::Colors;\n\nuse crate::widgets::SelectableList;\n\nuse tui::backend::Backend;\n\nuse tui::layout::{Alignment, Constraint, Direction, Layout, Rect};\n\nuse tui::text::{Span, Text};\n\nuse tui::widgets::{Block, BorderType, Borders, Cell, Clear, Paragraph, Row, Table, Wrap};\n\nuse tui::Frame;\n\nuse unicode_width::UnicodeWidthStr;\n\n\n\n/// Renders the user interface.\n", "file_path": "systeroid-tui/src/ui.rs", "rank": 39, "score": 14.386175961874375 }, { "content": "use crate::config::Config;\n\nuse crate::error::Result;\n\nuse crate::sysctl::display::DisplayType;\n\nuse crate::sysctl::section::Section;\n\nuse colored::*;\n\nuse serde::{Deserialize, Serialize};\n\nuse std::io::Write;\n\nuse std::path::PathBuf;\n\nuse sysctl::{Ctl, Sysctl as SysctlImpl};\n\n\n\n/// Representation of a kernel parameter.\n\n#[derive(Clone, Debug, Serialize, Deserialize)]\n\npub struct Parameter {\n\n /// Name of the kernel parameter.\n\n pub name: String,\n\n /// Value of the kernel parameter.\n\n #[serde(skip)]\n\n pub value: String,\n\n /// Description of the kernel parameter\n\n pub description: Option<String>,\n", "file_path": "systeroid-core/src/sysctl/parameter.rs", "rank": 40, "score": 14.36477605106382 }, { "content": "\n\nimpl<'a> App<'a> {\n\n /// Constructs a new instance.\n\n pub fn new(sysctl: &'a mut Sysctl) -> Self {\n\n let mut app = Self {\n\n running: true,\n\n show_help: false,\n\n input: None,\n\n input_time: None,\n\n input_cursor: 0,\n\n search_mode: false,\n\n docs_scroll_amount: 0,\n\n options: None,\n\n parameter_list: SelectableList::default(),\n\n section_list: SelectableList::with_items({\n\n let mut sections = Section::variants()\n\n .iter()\n\n .map(|v| v.to_string())\n\n .collect::<Vec<String>>();\n\n sections.insert(0, String::from(\"all\"));\n", "file_path": "systeroid-tui/src/app.rs", "rank": 41, "score": 14.263571476157828 }, { "content": "use crate::error::Result;\n\nuse colorsys::{ParseError, Rgb};\n\nuse std::result::Result as StdResult;\n\nuse std::str::FromStr;\n\nuse tui::style::{Color as TuiColor, Style};\n\n\n\n/// Color configuration.\n\n#[derive(Clone, Copy, Debug, Default, PartialEq)]\n\npub struct Colors {\n\n /// Background color.\n\n bg: Color,\n\n /// Foreground color.\n\n fg: Color,\n\n}\n\n\n\nimpl Colors {\n\n /// Constructs a new instance.\n\n pub fn new(background: &str, foreground: &str) -> Result<Self> {\n\n Ok(Self {\n\n bg: Color::from_str(background)?,\n", "file_path": "systeroid-tui/src/style.rs", "rank": 42, "score": 14.213409985504406 }, { "content": "use crate::output::OutputType;\n\nuse getopts::Options;\n\nuse std::env;\n\nuse std::path::PathBuf;\n\nuse systeroid_core::parseit::regex::Regex;\n\nuse systeroid_core::sysctl::display::DisplayType;\n\nuse systeroid_core::sysctl::{DEFAULT_PRELOAD, KERNEL_DOCS_ENV};\n\n\n\n/// Help message for the arguments.\n\nconst HELP_MESSAGE: &str = r#\"\n\nUsage:\n\n {bin} [options] [variable[=value] ...] --load[=<file>]\n\n\n\nOptions:\n\n{usage}\n\n\n\nFor more details see {bin}(8).\"#;\n\n\n\n/// Command-line arguments.\n\n#[derive(Debug, Default)]\n", "file_path": "systeroid/src/args.rs", "rank": 43, "score": 13.636384157628775 }, { "content": " self.search();\n\n self.input = Some(String::new());\n\n }\n\n Command::ProcessInput => {\n\n if self.input_time.is_some() {\n\n return Ok(());\n\n } else if self.search_mode {\n\n self.input = None;\n\n self.search_mode = false;\n\n } else if let Some(input) = &self.input {\n\n if let Ok(command) = Command::from_str(input) {\n\n self.input = None;\n\n self.run_command(command)?;\n\n hide_popup = false;\n\n } else {\n\n self.input = Some(String::from(\"Unknown command\"));\n\n self.input_time = Some(Instant::now());\n\n }\n\n }\n\n }\n", "file_path": "systeroid-tui/src/app.rs", "rank": 44, "score": 13.613320400467046 }, { "content": "use crate::style::Colors;\n\nuse getopts::Options;\n\nuse std::env;\n\nuse std::path::PathBuf;\n\nuse systeroid_core::sysctl::section::Section;\n\nuse systeroid_core::sysctl::KERNEL_DOCS_ENV;\n\n\n\n/// Help message for the arguments.\n\nconst HELP_MESSAGE: &str = r#\"\n\nUsage:\n\n {bin} [options]\n\n\n\nOptions:\n\n{usage}\n\n\n\nFor more details see {bin}(8).\"#;\n\n\n\n/// Command-line arguments.\n\n#[derive(Debug, Default)]\n\npub struct Args {\n", "file_path": "systeroid-tui/src/args.rs", "rank": 45, "score": 13.541185717153402 }, { "content": " }\n\n Command::MoveCursor(direction) => {\n\n if let Some(input) = &self.input {\n\n if direction == Direction::Right {\n\n if let Some(cursor_position) = self.input_cursor.checked_sub(1) {\n\n self.input_cursor = cursor_position as u16;\n\n }\n\n } else if self.input_cursor != input.width() as u16 {\n\n self.input_cursor += 1;\n\n }\n\n }\n\n }\n\n Command::Copy => {\n\n if self.parameter_list.selected().is_some() {\n\n let mut copy_options = CopyOption::variants().to_vec();\n\n if self\n\n .parameter_list\n\n .selected()\n\n .and_then(|parameter| parameter.get_documentation())\n\n .is_none()\n", "file_path": "systeroid-tui/src/app.rs", "rank": 46, "score": 13.456709894967755 }, { "content": " /// Cursor position.\n\n pub input_cursor: u16,\n\n /// Whether if the search mode is enabled.\n\n pub search_mode: bool,\n\n /// Y-scroll offset for the documentation.\n\n pub docs_scroll_amount: u16,\n\n /// Entries of the options menu.\n\n pub options: Option<SelectableList<&'a str>>,\n\n /// List of sysctl parameters.\n\n pub parameter_list: SelectableList<Parameter>,\n\n /// List of sysctl sections.\n\n pub section_list: SelectableList<String>,\n\n /// List of key bindings.\n\n pub key_bindings: SelectableList<&'a KeyBinding<'a>>,\n\n #[cfg(feature = \"clipboard\")]\n\n /// Clipboard context.\n\n clipboard: Option<Box<dyn ClipboardProvider>>,\n\n /// Sysctl controller.\n\n sysctl: &'a mut Sysctl,\n\n}\n", "file_path": "systeroid-tui/src/app.rs", "rank": 47, "score": 13.42070131073805 }, { "content": " docs_title: String::new(),\n\n })\n\n }\n\n}\n\n\n\nimpl Parameter {\n\n /// Returns the absolute name of the parameter, without the sections.\n\n pub fn get_absolute_name(&self) -> Option<&str> {\n\n self.name.split('.').collect::<Vec<&str>>().last().copied()\n\n }\n\n\n\n /// Returns the parameter name with corresponding section colors.\n\n pub fn get_colored_name(&self, config: &Config) -> String {\n\n let section_color = *(config\n\n .section_colors\n\n .get(&self.section)\n\n .unwrap_or(&config.default_color));\n\n let fields = self.name.split('.').collect::<Vec<&str>>();\n\n fields\n\n .iter()\n", "file_path": "systeroid-core/src/sysctl/parameter.rs", "rank": 48, "score": 13.125682439865125 }, { "content": "use std::convert::TryFrom;\n\n\n\nmacro_rules! generate_option {\n\n ($name: ident,\n\n $($variant: ident => $str_repr: expr,)+\n\n ) => {\n\n /// Available options.\n\n #[derive(Clone, Copy, Debug, PartialEq)]\n\n pub enum $name {\n\n $(\n\n /// Option.\n\n $variant\n\n ),+\n\n }\n\n\n\n impl<'a> TryFrom<&'a str> for $name {\n\n type Error = ();\n\n fn try_from(value: &'a str) -> Result<Self, Self::Error> {\n\n Self::variants()\n\n .iter()\n", "file_path": "systeroid-tui/src/options.rs", "rank": 49, "score": 13.020770951111071 }, { "content": " Command::UpdateInput(v) => {\n\n match self.input.as_mut() {\n\n Some(input) => {\n\n if self.input_time.is_some() {\n\n self.input_time = None;\n\n self.input = Some(String::new());\n\n } else {\n\n input.insert(input.width() - self.input_cursor as usize, v);\n\n }\n\n }\n\n None => {\n\n self.input = Some(String::new());\n\n self.search_mode = false;\n\n }\n\n }\n\n if self.search_mode {\n\n self.search();\n\n }\n\n }\n\n Command::ClearInput(remove_end) => {\n", "file_path": "systeroid-tui/src/app.rs", "rank": 50, "score": 12.817441011132946 }, { "content": " /// Refresh rate of the terminal.\n\n pub tick_rate: u64,\n\n /// Path of the Linux kernel documentation.\n\n pub kernel_docs: Option<PathBuf>,\n\n /// Sysctl section to filter.\n\n pub section: Option<Section>,\n\n /// Query to search on startup.\n\n pub search_query: Option<String>,\n\n /// Background/foreground colors.\n\n pub colors: Colors,\n\n /// Do not parse/show Linux kernel documentation.\n\n pub no_docs: bool,\n\n}\n\n\n\nimpl Args {\n\n /// Returns the available options.\n\n fn get_options() -> Options {\n\n let mut opts = Options::new();\n\n opts.optopt(\n\n \"t\",\n", "file_path": "systeroid-tui/src/args.rs", "rank": 51, "score": 12.735438186083776 }, { "content": " pub preload_system_files: bool,\n\n /// Pattern for matching the variables.\n\n pub pattern: Option<Regex>,\n\n /// Whether if the documentation should be shown.\n\n pub explain: bool,\n\n /// Output type of the application.\n\n pub output_type: OutputType,\n\n /// Whether if the TUI will be shown.\n\n pub show_tui: bool,\n\n /// Free string fragments.\n\n pub values: Vec<String>,\n\n}\n\n\n\nimpl Args {\n\n /// Returns the available options.\n\n fn get_options() -> Options {\n\n let mut opts = Options::new();\n\n opts.optflag(\"a\", \"all\", \"display all variables (-A,-X)\");\n\n opts.optflag(\"T\", \"tree\", \"display the variables in a tree-like format\");\n\n opts.optflag(\"J\", \"json\", \"display the variables in JSON format\");\n", "file_path": "systeroid/src/args.rs", "rank": 52, "score": 12.518081569455068 }, { "content": "use colored::*;\n\nuse std::fmt::Display;\n\nuse std::io::{Result as IoResult, Write};\n\n\n\n/// Vertical connector.\n\nconst VERTICAL_STR: &str = \"│\";\n\n/// Horizontal connector.\n\nconst HORIZONTAL_STR: &str = \"├──\";\n\n/// Horizontal connector for the last node.\n\nconst LAST_HORIZONTAL_STR: &str = \"└──\";\n\n\n\n/// Representation of a tree node.\n\n#[derive(Debug, Default, PartialEq, Eq)]\n\npub struct TreeNode {\n\n /// Value of the node.\n\n value: String,\n\n /// Childs of the node.\n\n pub childs: Vec<TreeNode>,\n\n}\n\n\n", "file_path": "systeroid-core/src/tree.rs", "rank": 53, "score": 12.451109787762014 }, { "content": " .map_err(|e| crate::error::Error::ClipboardError(e.to_string()))?;\n\n String::from(\"Copied to clipboard!\")\n\n } else {\n\n String::from(\"No parameter is selected\")\n\n }\n\n } else {\n\n String::from(\"Clipboard is not initialized\")\n\n });\n\n self.input_time = Some(Instant::now());\n\n Ok(())\n\n }\n\n\n\n /// Shows a message about clipboard being not enabled.\n\n #[cfg(not(feature = \"clipboard\"))]\n\n fn copy_to_clipboard(&mut self, _: CopyOption) -> Result<()> {\n\n self.input = Some(String::from(\"Clipboard support is not enabled\"));\n\n self.input_time = Some(Instant::now());\n\n Ok(())\n\n }\n\n\n", "file_path": "systeroid-tui/src/app.rs", "rank": 54, "score": 12.253928075675695 }, { "content": " assert_buffer(\n\n Buffer::with_lines(vec![\n\n \"╭Parameters─────────────────────|user|─╮\",\n\n \"│user.name system │\",\n\n \"│ │\",\n\n \"│ │\",\n\n \"│ │\",\n\n \"│ │\",\n\n \"│ │\",\n\n \"│ │\",\n\n \"│ 1/1 │\",\n\n \"╰──────────────────────────────────────╯\",\n\n ]),\n\n terminal.backend(),\n\n )?;\n\n app.run_command(Command::Scroll(ScrollArea::Section, Direction::Right, 1))?;\n\n app.run_command(Command::Scroll(ScrollArea::Section, Direction::Right, 1))?;\n\n\n\n app.input = Some(String::new());\n\n app.run_command(Command::Search)?;\n", "file_path": "systeroid-tui/tests/integration_test.rs", "rank": 55, "score": 12.205886381580347 }, { "content": "use tui::widgets::TableState as State;\n\n\n\n/// List widget with TUI controlled states.\n\n#[derive(Debug)]\n\npub struct SelectableList<T> {\n\n /// List items.\n\n pub items: Vec<T>,\n\n /// State that can be modified by TUI.\n\n pub state: State,\n\n}\n\n\n\nimpl<T> Default for SelectableList<T> {\n\n fn default() -> Self {\n\n Self::with_items(Vec::new())\n\n }\n\n}\n\n\n\nimpl<T> SelectableList<T> {\n\n /// Constructs a new instance of `SelectableList`.\n\n pub fn new(items: Vec<T>, mut state: State) -> SelectableList<T> {\n", "file_path": "systeroid-tui/src/widgets.rs", "rank": 56, "score": 12.131735873862189 }, { "content": " Buffer::with_lines(vec![\n\n \"╭Parameters──────────────────────|all|─╮\",\n\n \"│user.name system │\",\n\n \"│kernel.fictional.test_param 0 │\",\n\n \"│vm.stat_interval 1 │\",\n\n \"│ │\",\n\n \"│ │\",\n\n \"│ │\",\n\n \"│ │\",\n\n \"│ 1/3 │\",\n\n \"╰──────────────────────────────────────╯\",\n\n ]),\n\n terminal.backend(),\n\n )?;\n\n\n\n app.run_command(Command::Search)?;\n\n app.run_command(Command::Cancel)?;\n\n app.run_command(Command::Copy)?;\n\n terminal.draw(|frame| render(frame, &mut app, &colors))?;\n\n assert_buffer(\n", "file_path": "systeroid-tui/tests/integration_test.rs", "rank": 57, "score": 11.442823301389346 }, { "content": " },\n\n &KeyBinding {\n\n key: \"q, ctrl-c/ctrl-d\",\n\n action: \"exit\",\n\n },\n\n];\n\n\n\n/// Duration of prompt messages.\n\nconst MESSAGE_DURATION: u128 = 1750;\n\n\n\n/// Application controller.\n\npub struct App<'a> {\n\n /// Whether if the application is running.\n\n pub running: bool,\n\n /// Whether if the help message is shown.\n\n pub show_help: bool,\n\n /// Input buffer.\n\n pub input: Option<String>,\n\n /// Time tracker for measuring the time for clearing the input.\n\n pub input_time: Option<Instant>,\n", "file_path": "systeroid-tui/src/app.rs", "rank": 58, "score": 11.415582091342317 }, { "content": " Buffer::with_lines(vec![\n\n \"╭Parameters──────────────────────|all|─╮\",\n\n \"│user.name system │\",\n\n \"│kernel.fictional.test_param 0 │\",\n\n \"│vm.sta╭───Copy to clipboard────╮ │\",\n\n \"│ │Parameter name │ │\",\n\n \"│ │Parameter value │ │\",\n\n \"│ ╰────────────────────────╯ │\",\n\n \"│ │\",\n\n \"│ 1/3 │\",\n\n \"╰──────────────────────────────────────╯\",\n\n ]),\n\n terminal.backend(),\n\n )?;\n\n\n\n app.run_command(Command::Scroll(ScrollArea::List, Direction::Down, 1))?;\n\n app.run_command(Command::Scroll(ScrollArea::List, Direction::Up, 1))?;\n\n app.run_command(Command::Select)?;\n\n terminal.draw(|frame| render(frame, &mut app, &colors))?;\n\n assert_buffer(\n", "file_path": "systeroid-tui/tests/integration_test.rs", "rank": 59, "score": 11.282996618285441 }, { "content": " }\n\n app\n\n }\n\n\n\n /// Returns true if the app is in input mode.\n\n pub fn is_input_mode(&self) -> bool {\n\n self.input.is_some() && self.input_time.is_none()\n\n }\n\n\n\n /// Performs a search operation in the kernel parameter list.\n\n pub fn search(&mut self) {\n\n let section = self\n\n .section_list\n\n .selected()\n\n .map(|v| Section::from(v.to_string()))\n\n .unwrap_or(Section::Unknown);\n\n if let Some(query) = &self.input {\n\n self.parameter_list.items = self\n\n .sysctl\n\n .parameters\n", "file_path": "systeroid-tui/src/app.rs", "rank": 60, "score": 11.109207954115336 }, { "content": "use std::io;\n\nuse std::sync::mpsc::{self, Receiver, RecvError, Sender};\n\nuse std::thread;\n\nuse std::time::Duration;\n\nuse termion::event::Key;\n\nuse termion::input::TermRead;\n\n\n\n/// Representation of terminal events.\n\n#[derive(Clone, Copy, Debug)]\n\npub enum Event {\n\n /// A key press event.\n\n KeyPress(Key),\n\n /// A terminal refresh event.\n\n Tick,\n\n}\n\n\n\n/// [`Event`] handler.\n\n#[derive(Debug)]\n\npub struct EventHandler {\n\n /// Sender channel for the events.\n", "file_path": "systeroid-tui/src/event.rs", "rank": 61, "score": 11.026984050930029 }, { "content": " \"│ ││- │\",\n\n \"│ 2/2 ││Parameter: │\",\n\n \"╰──────────────────╯╰──────────────────╯\",\n\n ]),\n\n terminal.backend(),\n\n )?;\n\n\n\n app.run_command(Command::Nothing)?;\n\n app.run_command(Command::Exit)?;\n\n assert!(!app.running);\n\n\n\n Ok(())\n\n}\n", "file_path": "systeroid-tui/tests/integration_test.rs", "rank": 62, "score": 10.79793934621191 }, { "content": " } else if matches.opt_present(\"n\") {\n\n DisplayType::Value\n\n } else if matches.opt_present(\"b\") {\n\n DisplayType::Binary\n\n } else {\n\n DisplayType::Default\n\n };\n\n let output_type = if matches.opt_present(\"T\") {\n\n OutputType::Tree\n\n } else if matches.opt_present(\"J\") {\n\n OutputType::Json\n\n } else {\n\n OutputType::Default\n\n };\n\n if preload_files && matches.free.is_empty() {\n\n matches.free = vec![DEFAULT_PRELOAD.to_string()];\n\n }\n\n Some(Args {\n\n verbose: matches.opt_present(\"v\"),\n\n quiet: matches.opt_present(\"q\"),\n", "file_path": "systeroid/src/args.rs", "rank": 63, "score": 10.767333487913774 }, { "content": " } else {\n\n i + 1\n\n }\n\n }\n\n None => 0,\n\n };\n\n self.state.select(Some(i));\n\n }\n\n\n\n /// Selects the previous item.\n\n pub fn previous(&mut self) {\n\n let i = match self.state.selected() {\n\n Some(i) => {\n\n if i == 0 {\n\n self.items.len() - 1\n\n } else {\n\n i - 1\n\n }\n\n }\n\n None => 0,\n", "file_path": "systeroid-tui/src/widgets.rs", "rank": 64, "score": 10.621674669589805 }, { "content": " .collect::<Vec<String>>()\n\n .join(\"\\n\"),\n\n )\n\n });\n\n println!(\"{}\", usage);\n\n None\n\n } else if matches.opt_present(\"V\") {\n\n println!(\"{} {}\", env!(\"CARGO_PKG_NAME\"), env!(\"CARGO_PKG_VERSION\"));\n\n None\n\n } else if !required_args_present {\n\n eprintln!(\n\n \"{}: no variables specified\\n\\\n\n Try `{} --help' for more information.\",\n\n env!(\"CARGO_PKG_NAME\"),\n\n env!(\"CARGO_PKG_NAME\")\n\n );\n\n None\n\n } else {\n\n let display_type = if matches.opt_present(\"N\") {\n\n DisplayType::Name\n", "file_path": "systeroid/src/args.rs", "rank": 65, "score": 10.530115827459571 }, { "content": " .replace(\"{bin}\", env!(\"CARGO_PKG_NAME\"))\n\n .replace(\"{usage}\", &opts.collect::<Vec<String>>().join(\"\\n\"))\n\n });\n\n println!(\"{}\", usage);\n\n None\n\n } else if matches.opt_present(\"V\") {\n\n println!(\"{} {}\", env!(\"CARGO_PKG_NAME\"), env!(\"CARGO_PKG_VERSION\"));\n\n None\n\n } else {\n\n Some(Args {\n\n tick_rate: matches\n\n .opt_get(\"t\")\n\n .map_err(|e| eprintln!(\"error: `{}`\", e))\n\n .ok()?\n\n .unwrap_or(250),\n\n kernel_docs: matches\n\n .opt_str(\"D\")\n\n .or_else(|| env::var(KERNEL_DOCS_ENV).ok())\n\n .map(PathBuf::from),\n\n section: matches.opt_str(\"s\").map(Section::from),\n", "file_path": "systeroid-tui/src/args.rs", "rank": 66, "score": 10.297998944811573 }, { "content": " <summary>Table of Contents</summary>\n\n\n\n- [Requirements](#requirements)\n\n- [Installation](#installation)\n\n - [Cargo](#cargo)\n\n - [Arch Linux](#arch-linux)\n\n - [Binary releases](#binary-releases)\n\n - [Building from source](#building-from-source)\n\n - [Docker](#docker)\n\n - [Images](#images)\n\n - [Usage](#usage)\n\n - [Building](#building)\n\n- [Usage](#usage-1)\n\n - [Options](#options)\n\n - [Examples](#examples)\n\n - [Listing parameters](#listing-parameters)\n\n - [Filtering by section](#filtering-by-section)\n\n - [Displaying values](#displaying-values)\n\n - [Setting values](#setting-values)\n\n - [Loading values from a file](#loading-values-from-a-file)\n\n - [Loading values from the system directories](#loading-values-from-the-system-directories)\n\n - [Searching parameters](#searching-parameters)\n\n - [Showing information about parameters](#showing-information-about-parameters)\n\n- [TUI](#tui)\n\n - [Usage](#usage-2)\n\n - [Key Bindings](#key-bindings)\n\n - [Examples](#examples-1)\n\n - [Launching](#launching)\n\n - [Showing help](#showing-help)\n\n - [Scrolling](#scrolling)\n\n - [Toggling the kernel section](#toggling-the-kernel-section)\n\n - [Searching](#searching)\n\n - [Setting values](#setting-values-1)\n\n - [Running commands](#running-commands)\n\n - [Copying to clipboard](#copying-to-clipboard)\n\n - [Changing the colors](#changing-the-colors)\n\n - [Viewing the parameter documentation](#viewing-the-parameter-documentation)\n\n - [Setting the refresh rate](#setting-the-refresh-rate)\n\n- [Resources](#resources)\n\n - [References](#references)\n\n - [Logo](#logo)\n\n - [Social Links](#social-links)\n\n - [Funding](#funding)\n\n- [Contributing](#contributing)\n\n- [License](#license)\n\n- [Copyright](#copyright)\n\n\n\n</details>\n\n\n", "file_path": "README.md", "rank": 67, "score": 10.29655488601072 }, { "content": " } else {\n\n self.parameter_list.state.select(\n\n self.parameter_list\n\n .state\n\n .selected()\n\n .and_then(|v| v.checked_sub(amount.into()))\n\n .or(Some(0)),\n\n )\n\n }\n\n }\n\n }\n\n Command::Scroll(ScrollArea::List, Direction::Down, amount) => {\n\n if self.show_help {\n\n self.key_bindings.next();\n\n hide_popup = false;\n\n } else if let Some(options) = self.options.as_mut() {\n\n options.next();\n\n hide_popup = false;\n\n } else if !self.parameter_list.items.is_empty() {\n\n self.docs_scroll_amount = 0;\n", "file_path": "systeroid-tui/src/app.rs", "rank": 68, "score": 10.279085580515385 }, { "content": " state.select(Some(0));\n\n Self { items, state }\n\n }\n\n\n\n /// Construct a new `SelectableList` with given items.\n\n pub fn with_items(items: Vec<T>) -> SelectableList<T> {\n\n Self::new(items, State::default())\n\n }\n\n\n\n /// Returns the selected item.\n\n pub fn selected(&self) -> Option<&T> {\n\n self.items.get(self.state.selected()?)\n\n }\n\n\n\n /// Selects the next item.\n\n pub fn next(&mut self) {\n\n let i = match self.state.selected() {\n\n Some(i) => {\n\n if i >= self.items.len() - 1 {\n\n 0\n", "file_path": "systeroid-tui/src/widgets.rs", "rank": 69, "score": 10.225224831342377 }, { "content": "#### Scrolling\n\n\n\nUse <kbd>up/down</kbd> keys to scroll the parameter list. Alternatively, use <kbd>t/b</kbd> to scroll to the top/bottom.\n\n\n\n![Scroll list](assets/systeroid-tui-scroll-list.gif)\n\n\n\nUse <kbd>left/right</kbd> to scroll the parameter documentation.\n\n\n\n![Scroll documentation](assets/systeroid-tui-scroll-documentation.gif)\n\n\n\n#### Toggling the kernel section\n\n\n\nPress <kbd>tab</kbd> or <kbd>`</kbd> to toggle the kernel section for filtering entries in the parameter list.\n\n\n\nOrder of the sections is `all`-`abi`-`fs`-`kernel`-`net`-`sunrpc`-`user`-`vm`.\n\n\n\n![Toggle section](assets/systeroid-tui-toggle-section.gif)\n\n\n\n`--section` argument can be used to start **systeroid-tui** with the specified section for filtering.\n\n\n\n```sh\n\nsysteroid-tui --section kernel\n\n```\n\n\n\n![Section option](assets/systeroid-tui-section.gif)\n\n\n\n#### Searching\n\n\n\nPress <kbd>/</kbd> and type in your query to search for parameters.\n\n\n\n![Search](assets/systeroid-tui-search.gif)\n\n\n\nAlternatively, you can start **systeroid-tui** with a pre-defined search query by using `--query` argument.\n\n\n\n```sh\n\nsysteroid-tui --query \"fs.quota\"\n\n```\n\n\n\n![Query option](assets/systeroid-tui-query.gif)\n\n\n\n#### Setting values\n\n\n\nPress <kbd>enter</kbd> to select a parameter and set its value via command prompt.\n\n\n\n![Set value](assets/systeroid-tui-set-value.gif)\n\n\n\nYou can press <kbd>r</kbd> to refresh the values in the parameter list.\n\n\n", "file_path": "README.md", "rank": 70, "score": 9.997189865166149 }, { "content": " self.inner\n\n }\n\n}\n\n\n\nimpl FromStr for Color {\n\n type Err = ParseError;\n\n fn from_str(s: &str) -> StdResult<Self, Self::Err> {\n\n Ok(Self {\n\n inner: match s.to_lowercase().as_ref() {\n\n \"reset\" => TuiColor::Reset,\n\n \"black\" => TuiColor::Black,\n\n \"red\" => TuiColor::Red,\n\n \"green\" => TuiColor::Green,\n\n \"yellow\" => TuiColor::Yellow,\n\n \"blue\" => TuiColor::Blue,\n\n \"magenta\" => TuiColor::Magenta,\n\n \"cyan\" => TuiColor::Cyan,\n\n \"gray\" => TuiColor::Gray,\n\n \"darkgray\" => TuiColor::DarkGray,\n\n \"lightred\" => TuiColor::LightRed,\n", "file_path": "systeroid-tui/src/style.rs", "rank": 71, "score": 9.86164197806941 }, { "content": " terminal.backend(),\n\n )?;\n\n\n\n app.run_command(Command::Scroll(ScrollArea::List, Direction::Bottom, 1))?;\n\n app.run_command(Command::Scroll(ScrollArea::List, Direction::Up, 1))?;\n\n app.run_command(Command::Scroll(ScrollArea::List, Direction::Up, 2))?;\n\n app.run_command(Command::Scroll(ScrollArea::List, Direction::Top, 1))?;\n\n app.run_command(Command::Scroll(ScrollArea::List, Direction::Down, 1))?;\n\n app.run_command(Command::Scroll(ScrollArea::List, Direction::Down, 2))?;\n\n app.run_command(Command::Refresh)?;\n\n terminal.draw(|frame| render(frame, &mut app, &colors))?;\n\n assert_buffer(\n\n Buffer::with_lines(vec![\n\n \"╭Parameters──|all|─╮╭──Documentation───╮\",\n\n \"│kernel.fictional.t││stat_interval │\",\n\n \"│vm.stat_interval =││============= │\",\n\n \"│ ││The time interval │\",\n\n \"│ ││between which vm │\",\n\n \"│ ││statistics are │\",\n\n \"│ ││updated │\",\n", "file_path": "systeroid-tui/tests/integration_test.rs", "rank": 72, "score": 9.8048537760477 }, { "content": " write: matches.opt_present(\"w\"),\n\n kernel_docs: matches\n\n .opt_str(\"D\")\n\n .or_else(|| env::var(KERNEL_DOCS_ENV).ok())\n\n .map(PathBuf::from),\n\n display_type,\n\n display_deprecated: matches.opt_present(\"deprecated\"),\n\n ignore_errors: matches.opt_present(\"e\"),\n\n no_pager: matches.opt_present(\"P\"),\n\n preload_files,\n\n preload_system_files: matches.opt_present(\"S\"),\n\n pattern: matches\n\n .opt_str(\"r\")\n\n .map(|v| Regex::new(&v).expect(\"invalid regex\")),\n\n explain: matches.opt_present(\"E\"),\n\n output_type,\n\n show_tui: matches.opt_present(\"tui\"),\n\n values: matches.free,\n\n })\n\n }\n", "file_path": "systeroid/src/args.rs", "rank": 73, "score": 9.758250150628575 }, { "content": "//! A terminal user interface for managing kernel parameters.\n\n\n\n#![warn(missing_docs, clippy::unwrap_used)]\n\n\n\n/// Main application.\n\npub mod app;\n\n/// Command-line argument parser.\n\npub mod args;\n\n/// Application commands.\n\npub mod command;\n\n/// Error implementation.\n\npub mod error;\n\n/// Event handling.\n\npub mod event;\n\n/// Application options.\n\npub mod options;\n\n/// Style helper.\n\npub mod style;\n\n/// User interface renderer.\n\npub mod ui;\n", "file_path": "systeroid-tui/src/lib.rs", "rank": 74, "score": 9.737498892063687 }, { "content": " Vm,\n\n /// Unknown.\n\n Unknown,\n\n}\n\n\n\nimpl Section {\n\n /// Returns the section of the given parameter name.\n\n pub fn from_name(name: String) -> Self {\n\n for section in Self::variants() {\n\n if name.starts_with(&format!(\"{}.\", section)) {\n\n return *section;\n\n }\n\n }\n\n Self::Unknown\n\n }\n\n}\n\n\n\nimpl From<String> for Section {\n\n fn from(value: String) -> Self {\n\n for section in Self::variants() {\n", "file_path": "systeroid-core/src/sysctl/section.rs", "rank": 75, "score": 9.624850726862743 }, { "content": " self.input = Some(e.to_string());\n\n self.input_time = Some(Instant::now());\n\n }\n\n }\n\n } else {\n\n self.input = Some(String::from(\"Unknown parameter\"));\n\n self.input_time = Some(Instant::now());\n\n }\n\n }\n\n Command::Scroll(ScrollArea::List, Direction::Up, amount) => {\n\n if self.show_help {\n\n self.key_bindings.previous();\n\n hide_popup = false;\n\n } else if let Some(options) = self.options.as_mut() {\n\n options.previous();\n\n hide_popup = false;\n\n } else if !self.parameter_list.items.is_empty() {\n\n self.docs_scroll_amount = 0;\n\n if amount == 1 {\n\n self.parameter_list.previous();\n", "file_path": "systeroid-tui/src/app.rs", "rank": 76, "score": 9.55504892644597 }, { "content": " \"│user.name system │\",\n\n \"│kernel.fictional.test_param 0 │\",\n\n \"│vm.stat_interval 1 │\",\n\n \"│ │\",\n\n \"│ │\",\n\n \"│ │\",\n\n \"│ │\",\n\n \"│ 1/3 │\",\n\n \"╰──────────────────────────────────────╯\",\n\n ]),\n\n terminal.backend(),\n\n )?;\n\n\n\n app.run_command(Command::Help)?;\n\n app.run_command(Command::Scroll(ScrollArea::List, Direction::Down, 1))?;\n\n app.run_command(Command::Scroll(ScrollArea::List, Direction::Up, 1))?;\n\n terminal.draw(|frame| render(frame, &mut app, &colors))?;\n\n assert_buffer(\n\n Buffer::with_lines(vec![\n\n \"╭Parameters──────────────────────|all|─╮\",\n", "file_path": "systeroid-tui/tests/integration_test.rs", "rank": 77, "score": 9.462579198462695 }, { "content": "/// Custom widgets.\n\npub mod widgets;\n\n\n\nuse crate::app::App;\n\nuse crate::args::Args;\n\nuse crate::command::Command;\n\nuse crate::error::Result;\n\nuse crate::event::{Event, EventHandler};\n\nuse systeroid_core::cache::Cache;\n\nuse systeroid_core::config::Config;\n\nuse systeroid_core::sysctl::controller::Sysctl;\n\nuse tui::backend::Backend;\n\nuse tui::terminal::Terminal;\n\n\n\n/// Runs `systeroid-tui`.\n", "file_path": "systeroid-tui/src/lib.rs", "rank": 78, "score": 9.377165204674323 }, { "content": " self.docs_scroll_amount = 0;\n\n self.parameter_list.state.select(Some(0));\n\n }\n\n }\n\n Command::Scroll(ScrollArea::List, Direction::Bottom, _) => {\n\n if let Some(last_index) = self.parameter_list.items.len().checked_sub(1) {\n\n self.docs_scroll_amount = 0;\n\n self.parameter_list.state.select(Some(last_index))\n\n }\n\n }\n\n Command::Scroll(ScrollArea::Documentation, Direction::Up, amount) => {\n\n self.docs_scroll_amount = self\n\n .docs_scroll_amount\n\n .checked_sub(amount.into())\n\n .unwrap_or_default();\n\n }\n\n Command::Scroll(ScrollArea::Documentation, Direction::Down, amount) => {\n\n self.docs_scroll_amount = self\n\n .docs_scroll_amount\n\n .checked_add(amount.into())\n", "file_path": "systeroid-tui/src/app.rs", "rank": 79, "score": 9.337320036743492 }, { "content": "//! A more powerful alternative to sysctl.\n\n\n\n#![warn(missing_docs, clippy::unwrap_used)]\n\n\n\n/// Main application.\n\npub mod app;\n\n/// Command-line argument parser.\n\npub mod args;\n\n/// Application output types.\n\npub mod output;\n\n\n\nuse crate::app::App;\n\nuse crate::args::Args;\n\nuse std::io::Write;\n\nuse std::path::PathBuf;\n\nuse systeroid_core::cache::Cache;\n\nuse systeroid_core::config::Config;\n\nuse systeroid_core::error::Result;\n\nuse systeroid_core::sysctl::controller::Sysctl;\n\n\n\n/// Runs `systeroid`.\n", "file_path": "systeroid/src/lib.rs", "rank": 80, "score": 9.274747757443578 }, { "content": "\n\n/// Help text to show.\n\npub const HELP_TEXT: &str = concat!(\n\n \"\\u{2800} _ __/_ _ '_/\\n\",\n\n \"_) (/_) /(-/ ()/(/\\n\",\n\n \"/ \\u{2800}\\n\",\n\n env!(\"CARGO_PKG_NAME\"),\n\n \" v\",\n\n env!(\"CARGO_PKG_VERSION\"),\n\n \"\\n\",\n\n env!(\"CARGO_PKG_REPOSITORY\"),\n\n \"\\nwritten by \",\n\n env!(\"CARGO_PKG_AUTHORS\"),\n\n);\n\n\n\n/// Key bindings of the application.\n\npub const KEY_BINDINGS: &[&KeyBinding] = &[\n\n &KeyBinding {\n\n key: \"[?], f1\",\n\n action: \"show help\",\n", "file_path": "systeroid-tui/src/app.rs", "rank": 81, "score": 9.274232576434681 }, { "content": "use crate::error::{Error, Result};\n\nuse parseit::reader;\n\nuse serde::de::DeserializeOwned;\n\nuse serde::{Deserialize, Serialize};\n\nuse std::fs::{self, File};\n\nuse std::io::Write;\n\nuse std::path::{Path, PathBuf};\n\nuse std::time::SystemTime;\n\n\n\n/// Cache data to store on the file system.\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct CacheData<Data> {\n\n /// Cache data.\n\n pub data: Data,\n\n /// Timestamp of the data.\n\n pub timestamp: u64,\n\n}\n\n\n\nimpl<Data> CacheData<Data> {\n\n /// Constructs a new instance.\n", "file_path": "systeroid-core/src/cache.rs", "rank": 82, "score": 9.197074921241565 }, { "content": " if args.search_query.is_some() {\n\n app.input = args.search_query;\n\n app.search();\n\n app.input = None;\n\n }\n\n while app.running {\n\n terminal.draw(|frame| ui::render(frame, &mut app, &args.colors))?;\n\n match event_handler.next()? {\n\n Event::KeyPress(key) => {\n\n let command = Command::parse(key, app.is_input_mode());\n\n app.run_command(command)?;\n\n }\n\n #[cfg(not(test))]\n\n Event::Tick => {\n\n app.tick();\n\n }\n\n #[cfg(test)]\n\n Event::Tick => {\n\n app.running = false;\n\n }\n", "file_path": "systeroid-tui/src/lib.rs", "rank": 83, "score": 9.175806953907994 }, { "content": " if value.to_lowercase() == section.to_string() {\n\n return *section;\n\n }\n\n }\n\n Self::Unknown\n\n }\n\n}\n\n\n\nimpl<'a> From<&'a Path> for Section {\n\n fn from(value: &'a Path) -> Self {\n\n if value.components().any(|v| v.as_os_str() == \"networking\") {\n\n return Self::Net;\n\n }\n\n for section in Self::variants() {\n\n if let Some(file_stem) = value.file_stem().and_then(|v| v.to_str()) {\n\n if file_stem.starts_with(&section.to_string().to_lowercase()) {\n\n return *section;\n\n }\n\n }\n\n }\n", "file_path": "systeroid-core/src/sysctl/section.rs", "rank": 84, "score": 9.120330283873272 }, { "content": "use crate::output::OutputType;\n\nuse std::env;\n\nuse std::io::{self, BufRead, Write};\n\nuse std::path::PathBuf;\n\nuse std::process::{Command, Stdio};\n\nuse systeroid_core::error::Result;\n\nuse systeroid_core::parseit::globwalk;\n\nuse systeroid_core::parseit::reader;\n\nuse systeroid_core::parseit::regex::Regex;\n\nuse systeroid_core::sysctl::controller::Sysctl;\n\nuse systeroid_core::sysctl::parameter::Parameter;\n\nuse systeroid_core::sysctl::{DEPRECATED_PARAMS, SYSTEM_PRELOAD};\n\nuse systeroid_core::tree::{Tree, TreeNode};\n\n\n\n/// Application controller.\n\n#[derive(Debug)]\n\npub struct App<'a, Output: Write> {\n\n /// Sysctl controller.\n\n sysctl: &'a mut Sysctl,\n\n /// Standard output.\n", "file_path": "systeroid/src/app.rs", "rank": 85, "score": 9.079801925354221 }, { "content": " let required_args_present = !matches.free.is_empty()\n\n || display_all\n\n || preload_files\n\n || matches.opt_present(\"S\")\n\n || matches.opt_present(\"r\")\n\n || matches.opt_present(\"E\")\n\n || matches.opt_present(\"T\")\n\n || matches.opt_present(\"J\")\n\n || matches.opt_present(\"tui\");\n\n\n\n if show_help || env_args.len() == 1 {\n\n let usage = opts.usage_with_format(|opts| {\n\n HELP_MESSAGE\n\n .replace(\"{bin}\", env!(\"CARGO_PKG_NAME\"))\n\n .replace(\n\n \"{usage}\",\n\n &opts\n\n .filter(|msg| {\n\n !(msg.contains(\"alias of\") || msg.contains(\"does nothing\"))\n\n })\n", "file_path": "systeroid/src/args.rs", "rank": 86, "score": 9.066882813778001 }, { "content": "/// Wrapper for widget colors.\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub struct Color {\n\n /// Inner type.\n\n inner: TuiColor,\n\n}\n\n\n\nimpl Default for Color {\n\n fn default() -> Self {\n\n Self {\n\n inner: TuiColor::Reset,\n\n }\n\n }\n\n}\n\n\n\nimpl Color {\n\n /// Returns the underlying [`Color`] type.\n\n ///\n\n /// [`Color`]: tui::style::Color\n\n pub fn get(self) -> TuiColor {\n", "file_path": "systeroid-tui/src/style.rs", "rank": 87, "score": 8.990796946648022 }, { "content": " pub ignore_errors: bool,\n\n /// Whether if the quiet mode is enabled.\n\n pub quiet: bool,\n\n /// Whether if the pager is disabled.\n\n pub no_pager: bool,\n\n /// Sections and the corresponding colors.\n\n pub section_colors: HashMap<Section, Color>,\n\n /// Default color for the output\n\n pub default_color: Color,\n\n /// Display type of the kernel parameters.\n\n pub display_type: DisplayType,\n\n}\n\n\n\nimpl Default for Config {\n\n fn default() -> Self {\n\n Self {\n\n verbose: false,\n\n ignore_errors: false,\n\n quiet: false,\n\n no_pager: false,\n", "file_path": "systeroid-core/src/config.rs", "rank": 88, "score": 8.957432157089194 }, { "content": " .into_iter()\n\n .filter(|param| section == Section::Unknown || param.section == section)\n\n .collect(),\n\n );\n\n }\n\n self.docs_scroll_amount = 0;\n\n }\n\n\n\n /// Copies the selected entry to the clipboard.\n\n #[cfg(feature = \"clipboard\")]\n\n fn copy_to_clipboard(&mut self, copy_option: CopyOption) -> Result<()> {\n\n self.input = Some(if let Some(clipboard) = self.clipboard.as_mut() {\n\n if let Some(parameter) = self.parameter_list.selected() {\n\n match copy_option {\n\n CopyOption::Name => clipboard.set_contents(parameter.name.clone()),\n\n CopyOption::Value => clipboard.set_contents(parameter.value.clone()),\n\n CopyOption::Documentation => {\n\n clipboard.set_contents(parameter.get_documentation().unwrap_or_default())\n\n }\n\n }\n", "file_path": "systeroid-tui/src/app.rs", "rank": 89, "score": 8.884373339842497 }, { "content": " let pager = env::var(\"PAGER\").unwrap_or_else(|_| String::from(\"less\"));\n\n match Command::new(&pager).stdin(Stdio::piped()).spawn() {\n\n Ok(mut process) => {\n\n if let Some(stdin) = process.stdin.as_mut() {\n\n parameter.display_documentation(stdin)?;\n\n process.wait()?;\n\n } else {\n\n fallback_to_default = true;\n\n }\n\n }\n\n Err(e) => {\n\n if !pager.is_empty() {\n\n eprintln!(\"pager error: `{}`\", e);\n\n }\n\n fallback_to_default = true;\n\n }\n\n }\n\n if fallback_to_default {\n\n parameter.display_documentation(self.output)?;\n\n }\n", "file_path": "systeroid/src/app.rs", "rank": 90, "score": 8.87993365135485 }, { "content": " /// Configuration.\n\n pub config: Config,\n\n}\n\n\n\nimpl Sysctl {\n\n /// Constructs a new instance by fetching the available kernel parameters.\n\n pub fn init(config: Config) -> Result<Self> {\n\n let mut parameters = Vec::new();\n\n for ctl in CtlIter::root().filter_map(StdResult::ok).filter(|ctl| {\n\n ctl.flags()\n\n .map(|flags| !flags.contains(CtlFlags::SKIP))\n\n .unwrap_or(false)\n\n }) {\n\n match Parameter::try_from(&ctl) {\n\n Ok(parameter) => {\n\n parameters.push(parameter);\n\n }\n\n Err(e) => {\n\n if config.verbose {\n\n eprintln!(\"{} ({})\", e, ctl.name()?);\n", "file_path": "systeroid-core/src/sysctl/controller.rs", "rank": 91, "score": 8.788705873407224 }, { "content": "use std::path::PathBuf;\n\nuse std::thread;\n\nuse std::time::Duration;\n\nuse systeroid_core::config::Config;\n\nuse systeroid_core::sysctl::controller::Sysctl;\n\nuse systeroid_core::sysctl::parameter::Parameter;\n\nuse systeroid_core::sysctl::section::Section;\n\nuse systeroid_tui::app::App;\n\nuse systeroid_tui::command::Command;\n\nuse systeroid_tui::error::Result;\n\nuse systeroid_tui::options::{Direction, ScrollArea};\n\nuse systeroid_tui::style::Colors;\n\nuse systeroid_tui::ui::render;\n\nuse tui::backend::{Backend, TestBackend};\n\nuse tui::buffer::Buffer;\n\nuse tui::Terminal;\n\n\n", "file_path": "systeroid-tui/tests/integration_test.rs", "rank": 92, "score": 8.736070978542372 }, { "content": "impl TreeNode {\n\n /// Adds new child nodes to the tree node.\n\n pub fn add<'a, I>(&mut self, values: &mut I)\n\n where\n\n I: Iterator<Item = &'a str>,\n\n {\n\n if let Some(value) = values.next() {\n\n let mut found = false;\n\n for child in self.childs.iter_mut() {\n\n if &*child.value == value {\n\n child.add(values);\n\n found = true;\n\n break;\n\n }\n\n }\n\n if !found {\n\n let new_child = TreeNode {\n\n value: value.to_string(),\n\n childs: Vec::new(),\n\n };\n", "file_path": "systeroid-core/src/tree.rs", "rank": 93, "score": 8.711696829972741 }, { "content": " output: &'a mut Output,\n\n /// Output type.\n\n output_type: OutputType,\n\n}\n\n\n\nimpl<'a, Output: Write> App<'a, Output> {\n\n /// Constructs a new instance.\n\n pub fn new(sysctl: &'a mut Sysctl, output: &'a mut Output, output_type: OutputType) -> Self {\n\n Self {\n\n sysctl,\n\n output,\n\n output_type,\n\n }\n\n }\n\n\n\n /// Prints the given parameters to stdout.\n\n fn print_parameters<'b, I>(&mut self, parameters: &mut I) -> Result<()>\n\n where\n\n I: Iterator<Item = &'b Parameter>,\n\n {\n", "file_path": "systeroid/src/app.rs", "rank": 94, "score": 8.50293722395815 }, { "content": "use crate::sysctl::display::DisplayType;\n\nuse crate::sysctl::section::Section;\n\nuse colored::Color;\n\nuse std::collections::HashMap;\n\n\n\n/* Macro for the concise initialization of HashMap */\n\nmacro_rules! map {\n\n ($( $key: expr => $val: expr ),*) => {{\n\n let mut map = ::std::collections::HashMap::new();\n\n $( map.insert($key, $val); )*\n\n map\n\n }}\n\n}\n\n\n\n/// Configuration.\n\n#[derive(Clone, Debug)]\n\npub struct Config {\n\n /// Whether if the verbose logging is enabled.\n\n pub verbose: bool,\n\n /// Whether if the errors should be ignored.\n", "file_path": "systeroid-core/src/config.rs", "rank": 95, "score": 8.400446717024321 }, { "content": "#### Copying to clipboard\n\n\n\nPress <kbd>c</kbd> to show the options menu for copying the name, value, or documentation of the selected parameter.\n\n\n\n![Copy to clipboard](assets/systeroid-tui-copy.gif)\n\n\n\n\\* **systeroid-tui** should be built with `clipboard` feature for enabling the clipboard support.\n\n\n\n#### Changing the colors\n\n\n\nUse `--bg-color` and `--fg-color` arguments to customize the colors of the terminal user interface.\n\n\n\n```sh\n\n# use a color name for setting the foreground color\n\nsysteroid-tui --fg-color blue\n\n\n\n# use hexadecimal values for setting foreground/background colors\n\nsysteroid-tui --bg-color ffff99 --fg-color 003366\n\n```\n\n\n\n![Change colors](assets/systeroid-tui-colors.gif)\n\n\n\n#### Viewing the parameter documentation\n\n\n\nTo view the documentation as parameters are being selected on the list, kernel documentation should be parsed as explained in the \"[Showing information about parameters](#showing-information-about-parameters)\" section. A specific path for kernel documentation can be given via `--docs` argument or `KERNEL_DOCS` environment variable if it is not found in one of the locations that are checked as default.\n\n\n\nTo disable this feature altogether, use `--no-docs` flag.\n\n\n\n#### Setting the refresh rate\n\n\n\nIt is possible to specify a value in milliseconds via `--tick-rate` argument for tweaking the refresh rate of the terminal which might be necessary in some cases where better performance is desired.\n\n\n\n```sh\n\nsysteroid-tui --tick-rate 500\n\n```\n\n\n\n## Resources\n\n\n\n### References\n\n\n\n- [sysctl - source code](https://gitlab.com/procps-ng/procps/-/blob/newlib/sysctl.c)\n\n- [sysctl - Wikipedia](https://en.wikipedia.org/wiki/Sysctl)\n\n- [sysctl - ArchWiki](https://wiki.archlinux.org/title/Sysctl)\n\n\n", "file_path": "README.md", "rank": 96, "score": 8.394817176437131 }, { "content": " String::from(\"-w\"),\n\n String::from(\"-A\"),\n\n String::from(\"-T\"),\n\n ])\n\n .unwrap();\n\n assert!(args.verbose);\n\n assert!(args.write);\n\n assert_eq!(OutputType::Tree, args.output_type);\n\n\n\n assert!(!Args::parse(vec![String::new(), String::from(\"-p\")])\n\n .unwrap()\n\n .values\n\n .is_empty());\n\n\n\n assert_eq!(\n\n DisplayType::Binary,\n\n Args::parse(vec![String::new(), String::from(\"-A\"), String::from(\"-b\")])\n\n .unwrap()\n\n .display_type\n\n );\n\n }\n\n}\n", "file_path": "systeroid/src/args.rs", "rank": 97, "score": 8.350675843477203 }, { "content": " for parameter in contents\n\n .lines()\n\n .filter(|v| !(v.starts_with('#') || v.starts_with(';') || v.is_empty()))\n\n {\n\n let process_result =\n\n self.process_parameter(parameter.trim_start_matches('-').to_string(), false, false);\n\n if !parameter.starts_with('-') {\n\n process_result?;\n\n } else if let Err(e) = process_result {\n\n eprintln!(\"{}: {}\", env!(\"CARGO_PKG_NAME\"), e);\n\n }\n\n }\n\n Ok(())\n\n }\n\n\n\n /// Processes the parameters in files that are in predefined system directories.\n\n pub fn preload_from_system(&mut self) -> Result<()> {\n\n for preload_path in SYSTEM_PRELOAD\n\n .iter()\n\n .map(|v| PathBuf::from(v).join(\"*.conf\"))\n", "file_path": "systeroid/src/app.rs", "rank": 98, "score": 8.343758832529948 }, { "content": " self.value.replace('\\n', \" \").bold()\n\n );\n\n }\n\n });\n\n components\n\n }\n\n\n\n /// Prints the kernel parameter to given output.\n\n pub fn display_value<Output: Write>(&self, config: &Config, output: &mut Output) -> Result<()> {\n\n match config.display_type {\n\n DisplayType::Name => {\n\n writeln!(output, \"{}\", self.get_colored_name(config))?;\n\n }\n\n DisplayType::Value => {\n\n writeln!(output, \"{}\", self.value.bold())?;\n\n }\n\n DisplayType::Binary => {\n\n write!(output, \"{}\", self.value.bold())?;\n\n }\n\n DisplayType::Default => {\n", "file_path": "systeroid-core/src/sysctl/parameter.rs", "rank": 99, "score": 8.323711449929245 } ]
Rust
cli/src/main.rs
asm0dey/cb
b68417ded4f52d8af1541296485bf39b95c0cf6c
#[macro_use] extern crate common; const VERSION: &str = env!("CARGO_PKG_VERSION"); use cli::Handler; use common::constants::SOCKET_PATH; use common::errors::StringErrorResult; use gumdrop::Options; use server; use std::env::current_exe; use std::io::{self, Read}; use std::os::unix::net::UnixStream; use std::process::Command; use std::thread::sleep; use std::time::Duration; #[derive(Options)] struct AppOptions { #[options(help = "Prints the help message", short = "h", long = "help")] pub help: bool, #[options(help = "Prints the version", short = "V", long = "version")] pub version: bool, #[options(help = "Pastes the content of clipboard", short = "p", long = "paste")] pub paste: bool, #[options(help = "Clears the content of clipboard", short = "c", long = "clear")] pub clear: bool, #[options(help = "Starts server as a daemon", short = "s", long = "server")] pub server: bool, #[options( help = "Do not print newline after pasting the content", short = "r", long = "raw" )] pub raw: bool, #[options( help = "Store TEXT into clipboard", meta = "TEXT", short = "t", long = "text" )] pub text: Option<String>, } fn try_connect(try_run: bool) -> Result<UnixStream, String> { match UnixStream::connect(SOCKET_PATH) { Ok(stream) => Ok(stream), err => { if try_run { let _ = Command::new(current_exe().unwrap()) .arg("-s") .spawn() .error_to_string()? .wait() .error_to_string()?; sleep(Duration::from_secs(1)); try_connect(false) } else { err.error_to_string() } } } } fn main() { let mut opts = AppOptions::parse_args_default_or_exit(); if opts.server { server::start(); } if opts.help { exit!("{}", AppOptions::usage()); } if opts.version { exit!("{}", VERSION); } let mut handler = Handler::new(match try_connect(true) { Ok(stream) => stream, Err(e) => { oops!("[error] unable to connect to server: {}", e); } }); if opts.clear { if handler.clear() { std::process::exit(0); } else { oops!("[error] an error occurred"); } } if opts.paste { match handler.get() { Some(content) => { if opts.raw { print!("{}", content); std::process::exit(0); } else { exit!("{}", content); } } None => { oops!("[error] an error occurred"); } } } if opts.text.is_some() { if handler.set(opts.text.take()) { std::process::exit(0); } else { oops!("[error] an error occurred"); } } let mut buffer = String::new(); let stdin = io::stdin(); let mut handle = stdin.lock(); if let Err(e) = handle.read_to_string(&mut buffer) { oops!("[error] unable to read piped text: {}", e); } if handler.set(Some(buffer)) { std::process::exit(0); } else { oops!("[error] an error occurred"); } }
#[macro_use] extern crate common; const VERSION: &str = env!("CARGO_PKG_VERSION"); use cli::Handler; use common::constants::SOCKET_PATH; use common::errors::StringErrorResult; use gumdrop::Options; use server; use std::env::current_exe; use std::io::{self, Read}; use std::os::unix::net::UnixStream; use std::process::Command; use std::thread::sleep; use std::time::Duration; #[derive(Options)] struct AppOptions { #[options(help = "Prints the help message", short = "h", long = "help")] pub help: bool, #[options(help = "Prints the version", short = "V", long = "version")] pub version: bool, #[options(help = "Pastes the content of clipboard", short = "p", long = "paste")] pub paste: bool, #[options(help = "Clears the content of clipboard", short = "c", long = "clear")] pub clear: bool, #[options(help = "Starts server as a daemon", short = "s", long = "server")] pub server: bool, #[options( help = "Do not print newline after pasting the content", short = "r", long = "raw" )] pub raw: bool, #[options( help = "Store TEXT into clipboard", meta = "TEXT", short = "t", long = "text" )] pub text: Option<String>, }
fn main() { let mut opts = AppOptions::parse_args_default_or_exit(); if opts.server { server::start(); } if opts.help { exit!("{}", AppOptions::usage()); } if opts.version { exit!("{}", VERSION); } let mut handler = Handler::new(match try_connect(true) { Ok(stream) => stream, Err(e) => { oops!("[error] unable to connect to server: {}", e); } }); if opts.clear { if handler.clear() { std::process::exit(0); } else { oops!("[error] an error occurred"); } } if opts.paste { match handler.get() { Some(content) => { if opts.raw { print!("{}", content); std::process::exit(0); } else { exit!("{}", content); } } None => { oops!("[error] an error occurred"); } } } if opts.text.is_some() { if handler.set(opts.text.take()) { std::process::exit(0); } else { oops!("[error] an error occurred"); } } let mut buffer = String::new(); let stdin = io::stdin(); let mut handle = stdin.lock(); if let Err(e) = handle.read_to_string(&mut buffer) { oops!("[error] unable to read piped text: {}", e); } if handler.set(Some(buffer)) { std::process::exit(0); } else { oops!("[error] an error occurred"); } }
fn try_connect(try_run: bool) -> Result<UnixStream, String> { match UnixStream::connect(SOCKET_PATH) { Ok(stream) => Ok(stream), err => { if try_run { let _ = Command::new(current_exe().unwrap()) .arg("-s") .spawn() .error_to_string()? .wait() .error_to_string()?; sleep(Duration::from_secs(1)); try_connect(false) } else { err.error_to_string() } } } }
function_block-full_function
[ { "content": "/// Starts server as a daemon\n\npub fn start() {\n\n env_logger::init();\n\n\n\n let socket_path = Path::new(SOCKET_PATH);\n\n\n\n let (username, group) = match get_user_group() {\n\n Ok(ug) => ug,\n\n Err(e) => {\n\n fatal!(\"{}\", e);\n\n }\n\n };\n\n\n\n let daemonize = Daemonize::new()\n\n .user(username.as_str())\n\n .group(group.as_str())\n\n .umask(0o000);\n\n\n\n if let Err(e) = daemonize.start() {\n\n fatal!(\"unable to run as daemon: {}\", e);\n\n }\n", "file_path": "server/src/lib.rs", "rank": 0, "score": 85528.80069653408 }, { "content": "/// Handles actions and returns the response of action\n\npub fn handle_action(data: BytesMut) -> Result<BytesMut, String> {\n\n match handle_action_by_error(data) {\n\n Ok(res) => res,\n\n Err(e) => {\n\n error!(\"unable to perform action: {}\", e);\n\n Response {\n\n status: false,\n\n content: None,\n\n }\n\n }\n\n }\n\n .try_into()\n\n}\n", "file_path": "server/src/clipboard_handler.rs", "rank": 2, "score": 52796.88828683403 }, { "content": "/// An interface to be implemented by transmitters\n\npub trait Transmitter {\n\n /// Starts listening\n\n fn listen(self) -> Result<(), String>;\n\n}\n", "file_path": "server/src/transmitter.rs", "rank": 3, "score": 50601.28325019439 }, { "content": "mod action;\n\nmod response;\n\n\n\npub use action::*;\n\npub use response::*;\n", "file_path": "common/src/message.rs", "rank": 4, "score": 44713.82587765377 }, { "content": "use crate::errors::StringErrorResult;\n\nuse bincode::{deserialize, serialize};\n\nuse bytes::BytesMut;\n\nuse std::convert::TryFrom;\n\nuse std::convert::TryInto;\n\n\n\n/// Represents variant types of content action\n\n#[derive(Serialize, Deserialize)]\n\npub enum Action {\n\n /// An action to clear clipboard\n\n Clear,\n\n\n\n /// An action to get content from clipboard\n\n Get,\n\n\n\n /// An action to set a content to clipboard\n\n Set(String),\n\n}\n\n\n\nimpl TryInto<BytesMut> for Action {\n", "file_path": "common/src/message/action.rs", "rank": 5, "score": 42930.41320285306 }, { "content": "use crate::errors::StringErrorResult;\n\nuse bincode::{deserialize, serialize};\n\nuse bytes::BytesMut;\n\nuse std::convert::TryFrom;\n\nuse std::convert::TryInto;\n\n\n\n/// Represents the response of clipboard action,\n\n#[derive(Serialize, Deserialize)]\n\npub struct Response {\n\n /// A `true` value represents a successful action\n\n pub status: bool,\n\n\n\n /// A `None` value is used for set and clear actions\n\n pub content: Option<String>,\n\n}\n\n\n\nimpl TryInto<BytesMut> for Response {\n\n type Error = String;\n\n\n\n fn try_into(self) -> Result<BytesMut, Self::Error> {\n", "file_path": "common/src/message/response.rs", "rank": 6, "score": 42930.307769702384 }, { "content": " Ok(BytesMut::from(serialize(&self).error_to_string()?))\n\n }\n\n}\n\n\n\nimpl TryFrom<BytesMut> for Response {\n\n type Error = String;\n\n\n\n fn try_from(value: BytesMut) -> Result<Self, Self::Error> {\n\n Ok(deserialize(&value).error_to_string()?)\n\n }\n\n}\n", "file_path": "common/src/message/response.rs", "rank": 7, "score": 42919.611196662 }, { "content": " type Error = String;\n\n\n\n fn try_into(self) -> Result<BytesMut, Self::Error> {\n\n Ok(BytesMut::from(serialize(&self).error_to_string()?))\n\n }\n\n}\n\n\n\nimpl TryFrom<BytesMut> for Action {\n\n type Error = String;\n\n\n\n fn try_from(value: BytesMut) -> Result<Self, Self::Error> {\n\n Ok(deserialize(&value).error_to_string()?)\n\n }\n\n}\n", "file_path": "common/src/message/action.rs", "rank": 8, "score": 42919.611196662 }, { "content": "use bytes::BytesMut;\n\nuse clipboard::{ClipboardContext, ClipboardProvider};\n\nuse common::message::{Action, Response};\n\nuse std::convert::TryFrom;\n\nuse std::convert::TryInto;\n\n\n", "file_path": "server/src/clipboard_handler.rs", "rank": 9, "score": 41889.19345896507 }, { "content": "/// Returns current (username, group_name)\n\npub fn get_user_group() -> Result<(String, String), String> {\n\n Ok((\n\n users::get_current_username()\n\n .ok_or_else(|| String::from(\"unable to get username\"))?\n\n .to_str()\n\n .ok_or_else(|| String::from(\"unable to encode username\"))?\n\n .to_string(),\n\n users::get_current_groupname()\n\n .ok_or_else(|| String::from(\"unable to get group\"))?\n\n .to_str()\n\n .ok_or_else(|| String::from(\"unable to encode group\"))?\n\n .to_string(),\n\n ))\n\n}\n", "file_path": "server/src/internal.rs", "rank": 10, "score": 40090.43481133711 }, { "content": "/// An interface to convert Result<T, E> to Result<T, String>\n\npub trait StringErrorResult<T, E: Error> {\n\n /// Converts Result<T, E> to Result<T, String>\n\n fn error_to_string(self) -> Result<T, String>;\n\n}\n\n\n\nimpl<T, E: Error> StringErrorResult<T, E> for Result<T, E> {\n\n fn error_to_string(self) -> Result<T, String> {\n\n self.map_err(|e| e.description().to_string())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::io::{Error, ErrorKind};\n\n\n\n #[test]\n\n fn test_error_to_string() {\n\n let res: Result<(), Error> = Err(Error::new(ErrorKind::Other, \"a custom error\"));\n\n if let Err(e) = res.error_to_string() {\n\n assert_eq!(e, \"a custom error\");\n\n } else {\n\n panic!(\"An error is expected\");\n\n }\n\n }\n\n}\n", "file_path": "common/src/errors/string_error_result.rs", "rank": 11, "score": 39716.39200098092 }, { "content": "fn handle_action_by_error(data: BytesMut) -> Result<Response, String> {\n\n let mut ctx: ClipboardContext =\n\n ClipboardProvider::new().map_err(|e| e.description().to_string())?;\n\n let content = match Action::try_from(data)? {\n\n Action::Clear => {\n\n ctx.set_contents(String::new())\n\n .map_err(|e| e.description().to_string())?;\n\n None\n\n }\n\n Action::Get => Some(\n\n ctx.get_contents()\n\n .map_err(|e| e.description().to_string())?,\n\n ),\n\n Action::Set(msg) => {\n\n ctx.set_contents(msg)\n\n .map_err(|e| e.description().to_string())?;\n\n None\n\n }\n\n };\n\n Ok(Response {\n\n status: true,\n\n content,\n\n })\n\n}\n\n\n", "file_path": "server/src/clipboard_handler.rs", "rank": 12, "score": 30790.534813563147 }, { "content": "#[macro_use]\n\nextern crate lazy_static;\n\n#[macro_use]\n\nextern crate serde_derive;\n\n\n\npub mod constants;\n\npub mod errors;\n\npub mod macros;\n\npub mod message;\n", "file_path": "common/src/lib.rs", "rank": 14, "score": 21665.60748509739 }, { "content": "/// The UNIX domain socket path\n\npub const SOCKET_PATH: &str = \"/tmp/cb.sock\";\n\n\n\n/// The buffer size to read from socket\n\npub const BUFFER_SIZE: usize = 2048;\n\n\n\n/// The splitter to frame byte stream\n\npub const SPLITTER: &[u8] = b\"\\r\\n\";\n\n\n\nlazy_static! {\n\n /// The length of splitter\n\n pub static ref SPLITTER_LEN: usize = SPLITTER.len();\n\n}\n", "file_path": "common/src/constants.rs", "rank": 15, "score": 21659.593661718252 }, { "content": "mod string_error_result;\n\n\n\npub use string_error_result::*;\n", "file_path": "common/src/errors.rs", "rank": 16, "score": 21658.53747828683 }, { "content": "pub mod exit;\n\npub mod fatal;\n\npub mod oops;\n", "file_path": "common/src/macros.rs", "rank": 17, "score": 21657.142567456372 }, { "content": "/// Prints a message to stderr and terminates the process by exit status code of 1\n\n///\n\n/// # Examples\n\n///\n\n/// ```rust,ignore\n\n/// oops!(\"A message: {}\", \"a general text\");\n\n/// ```\n\n#[macro_export]\n\nmacro_rules! oops {\n\n ($($arg:tt)*) => {\n\n eprintln!($($arg)*);\n\n std::process::exit(1);\n\n }\n\n}\n", "file_path": "common/src/macros/oops.rs", "rank": 18, "score": 20793.448114057577 }, { "content": "/// Prints a message to stdout and terminates the process by exit status code of 0\n\n///\n\n/// # Examples\n\n///\n\n/// ```rust,ignore\n\n/// exit!(\"A message: {}\", \"a general text\");\n\n/// ```\n\n#[macro_export]\n\nmacro_rules! exit {\n\n ($($arg:tt)*) => {\n\n println!($($arg)*);\n\n std::process::exit(0);\n\n }\n\n}\n", "file_path": "common/src/macros/exit.rs", "rank": 19, "score": 20793.448114057577 }, { "content": "/// Logs an error message and terminates the process by exit status code of 1\n\n///\n\n/// # Examples\n\n///\n\n/// ```rust,ignore\n\n/// fatal!(\"An error message: {}\", \"a general error\");\n\n/// ```\n\n#[macro_export]\n\nmacro_rules! fatal {\n\n ($($arg:tt)*) => {\n\n error!($($arg)*);\n\n std::process::exit(1);\n\n }\n\n}\n", "file_path": "common/src/macros/fatal.rs", "rank": 20, "score": 20790.082596014578 }, { "content": "#[macro_use]\n\nextern crate log;\n\n#[macro_use]\n\nextern crate common;\n\n\n\nmod clipboard_handler;\n\nmod transmitter;\n\n\n\npub mod internal;\n\n\n\npub use transmitter::*;\n\n\n\nuse common::constants::SOCKET_PATH;\n\nuse ctrlc;\n\nuse daemonize::Daemonize;\n\nuse internal::get_user_group;\n\nuse std::fs;\n\nuse std::path::Path;\n\nuse transmitter::{AsyncUnix, Transmitter};\n\n\n\n/// Removes created files\n", "file_path": "server/src/lib.rs", "rank": 21, "score": 20307.678149208812 }, { "content": "mod async_unix;\n\n\n\npub use async_unix::*;\n\n\n\n/// An interface to be implemented by transmitters\n", "file_path": "server/src/transmitter.rs", "rank": 22, "score": 20298.882157839085 }, { "content": "\n\n if let Err(e) = ctrlc::set_handler(move || {\n\n clean();\n\n std::process::exit(0);\n\n }) {\n\n fatal!(\"unable to set handler of CTRL-C signals: {}\", e);\n\n }\n\n\n\n if socket_path.exists() {\n\n if let Err(e) = fs::remove_file(socket_path) {\n\n fatal!(\"unable to delete UNIX domain socket file: {}\", e);\n\n }\n\n }\n\n\n\n if let Err(e) = AsyncUnix::new(socket_path).and_then(Transmitter::listen) {\n\n fatal!(\"unable to start transmitter: {}\", e);\n\n }\n\n\n\n clean();\n\n}\n", "file_path": "server/src/lib.rs", "rank": 23, "score": 20297.41128134942 }, { "content": "use users;\n\n\n\n/// Returns current (username, group_name)\n", "file_path": "server/src/internal.rs", "rank": 24, "score": 20296.932181079403 }, { "content": "/// Removes created files\n\nfn clean() {\n\n let _ = fs::remove_file(Path::new(SOCKET_PATH));\n\n}\n\n\n", "file_path": "server/src/lib.rs", "rank": 25, "score": 19482.583740397247 }, { "content": "use std::error::Error;\n\n\n\n/// An interface to convert Result<T, E> to Result<T, String>\n", "file_path": "common/src/errors/string_error_result.rs", "rank": 26, "score": 19249.330282380888 }, { "content": "mod codec;\n\nmod handler;\n\nmod peer;\n\n\n\nuse super::Transmitter;\n\nuse common::errors::StringErrorResult;\n\nuse futures::stream::Stream;\n\nuse std::path::Path;\n\nuse tokio;\n\nuse tokio::net::UnixListener;\n\n\n\n/// Represents an async unix domain socket transmitter\n\npub struct AsyncUnix {\n\n socket: UnixListener,\n\n}\n\n\n\nimpl AsyncUnix {\n\n pub fn new<P: AsRef<Path>>(path: P) -> Result<Self, String> {\n\n Ok(AsyncUnix {\n\n socket: UnixListener::bind(path).error_to_string()?,\n", "file_path": "server/src/transmitter/async_unix.rs", "rank": 27, "score": 18739.45347994005 }, { "content": " })\n\n }\n\n}\n\n\n\nimpl Transmitter for AsyncUnix {\n\n fn listen(self) -> Result<(), String> {\n\n let server = self\n\n .socket\n\n .incoming()\n\n .map_err(handler::on_error)\n\n .for_each(move |client| {\n\n handler::on_accept(client);\n\n Ok(())\n\n });\n\n\n\n tokio::run(server);\n\n\n\n Ok(())\n\n }\n\n}\n", "file_path": "server/src/transmitter/async_unix.rs", "rank": 28, "score": 18735.29074138778 }, { "content": "use super::codec::Codec;\n\nuse crate::clipboard_handler::handle_action;\n\nuse futures::future::Future;\n\nuse futures::stream::Stream;\n\nuse futures::Poll;\n\nuse tokio::prelude::Async;\n\n\n\n/// Represents the state for the connected client\n\npub(crate) struct Peer {\n\n /// The UNIX domain socket to send and receive data\n\n codec: Codec,\n\n}\n\n\n\nimpl Peer {\n\n /// Creates a new instance of `Peer`\n\n pub fn new(codec: Codec) -> Self {\n\n Peer { codec }\n\n }\n\n}\n\n\n", "file_path": "server/src/transmitter/async_unix/peer.rs", "rank": 29, "score": 18045.803350238355 }, { "content": "use bytes::buf::BufMut;\n\nuse bytes::BytesMut;\n\nuse common::constants::{BUFFER_SIZE, SPLITTER, SPLITTER_LEN};\n\nuse hex;\n\nuse std::error::Error;\n\nuse std::net::Shutdown;\n\nuse tokio::net::UnixStream;\n\nuse tokio::prelude::{Async, AsyncRead, AsyncWrite, Poll, Stream};\n\n\n\n/// Represents a UNIX socket poller to send and receive data by splitter\n\n#[derive(Debug)]\n\npub(crate) struct Codec {\n\n /// The UNIX socket to send and receive data\n\n socket: UnixStream,\n\n\n\n /// The buffer for reading data\n\n read_buf: BytesMut,\n\n\n\n /// The buffer for writing data\n\n write_buf: BytesMut,\n", "file_path": "server/src/transmitter/async_unix/codec.rs", "rank": 30, "score": 18045.776990834707 }, { "content": "use super::codec::Codec;\n\nuse super::peer::Peer;\n\nuse futures::future::Future;\n\nuse std::error::Error;\n\nuse tokio::net::UnixStream;\n\n\n\n/// Error handler of UNIX domain socket\n\npub(crate) fn on_error(e: impl Error) {\n\n error!(\"unable to accept a client: {}\", e);\n\n}\n\n\n\n/// Client handler of UNIX domain socket\n\npub(crate) fn on_accept(client: UnixStream) {\n\n tokio::spawn(\n\n Peer::new(Codec::new(client)).map_err(|e| error!(\"unable to read from tunnel: {}\", e)),\n\n );\n\n}\n", "file_path": "server/src/transmitter/async_unix/handler.rs", "rank": 31, "score": 18045.387681099943 }, { "content": "}\n\n\n\nimpl Codec {\n\n /// Creates a new instance of `Codec`\n\n pub fn new(stream: UnixStream) -> Self {\n\n Codec {\n\n socket: stream,\n\n read_buf: BytesMut::new(),\n\n write_buf: BytesMut::new(),\n\n }\n\n }\n\n\n\n /// Reads data from socket\n\n fn read_data(&mut self) -> Poll<(), String> {\n\n loop {\n\n self.read_buf.reserve(BUFFER_SIZE);\n\n let n = match self.socket.read_buf(&mut self.read_buf) {\n\n Ok(Async::Ready(t)) => t,\n\n Ok(Async::NotReady) => return Ok(Async::NotReady),\n\n Err(e) => return Err(e.description().to_string()),\n", "file_path": "server/src/transmitter/async_unix/codec.rs", "rank": 32, "score": 18042.40888321215 }, { "content": " let is_closed = self.read_data()?.is_ready();\n\n let splitter_pos = self\n\n .read_buf\n\n .windows(*SPLITTER_LEN)\n\n .enumerate()\n\n .find(|&(_, b)| b == SPLITTER)\n\n .map(|(i, _)| i);\n\n if let Some(pos) = splitter_pos {\n\n let mut data = self.read_buf.split_to(pos + *SPLITTER_LEN);\n\n let _ = data.split_off(pos);\n\n if let Ok(hex_decoded) = hex::decode(&data) {\n\n return Ok(Async::Ready(Some(BytesMut::from(hex_decoded))));\n\n }\n\n }\n\n if is_closed {\n\n Ok(Async::Ready(None))\n\n } else {\n\n Ok(Async::NotReady)\n\n }\n\n }\n\n}\n", "file_path": "server/src/transmitter/async_unix/codec.rs", "rank": 33, "score": 18040.977386262923 }, { "content": " };\n\n if n == 0 {\n\n return Ok(Async::Ready(()));\n\n }\n\n }\n\n }\n\n\n\n /// Writes `data` to write buffer\n\n pub fn buffer(&mut self, data: BytesMut) {\n\n let hex_buf = hex::encode(&data).into_bytes();\n\n self.write_buf.reserve(hex_buf.len());\n\n self.write_buf.put(hex_buf);\n\n self.write_buf.extend_from_slice(SPLITTER);\n\n }\n\n\n\n /// Flushes write buffer to the socket\n\n pub fn poll_flush(&mut self) -> Poll<(), String> {\n\n while !self.write_buf.is_empty() {\n\n let size = match self.socket.poll_write(&self.write_buf) {\n\n Ok(Async::Ready(t)) => t,\n", "file_path": "server/src/transmitter/async_unix/codec.rs", "rank": 34, "score": 18040.338127980856 }, { "content": " Ok(Async::NotReady) => return Ok(Async::NotReady),\n\n Err(e) => return Err(e.description().to_string()),\n\n };\n\n if size == 0 {\n\n return Err(String::from(\"writing zero bytes to the socket\"));\n\n }\n\n let _ = self.write_buf.split_to(size);\n\n if self.write_buf.is_empty() {\n\n let _ = self.socket.shutdown(Shutdown::Both);\n\n }\n\n }\n\n Ok(Async::Ready(()))\n\n }\n\n}\n\n\n\nimpl Stream for Codec {\n\n type Item = BytesMut;\n\n type Error = String;\n\n\n\n fn poll(&mut self) -> Result<Async<Option<Self::Item>>, Self::Error> {\n", "file_path": "server/src/transmitter/async_unix/codec.rs", "rank": 35, "score": 18040.05976430771 }, { "content": "impl Future for Peer {\n\n type Item = ();\n\n type Error = String;\n\n\n\n fn poll(&mut self) -> Poll<Self::Item, Self::Error> {\n\n while let Async::Ready(data) = self.codec.poll()? {\n\n if let Some(data) = data {\n\n self.codec.buffer(handle_action(data).unwrap_or_default());\n\n } else {\n\n // EOF has been received\n\n return Ok(Async::Ready(()));\n\n }\n\n }\n\n let _ = self.codec.poll_flush()?;\n\n Ok(Async::NotReady)\n\n }\n\n}\n", "file_path": "server/src/transmitter/async_unix/peer.rs", "rank": 36, "score": 18038.81048782814 }, { "content": "# cb\n\n\n\n[![Build Status](https://travis-ci.org/yaa110/cb.svg?branch=master)](https://travis-ci.org/yaa110/cb) [![Download](https://img.shields.io/badge/download-0.1.0-blue.svg)](https://github.com/yaa110/cb/releases/download/0.1.0/cb)\n\n\n\nCommand line interface to manage clipboard\n\n\n\n## How to install\n\n\n\n### Pre-Compiled\n\n\n\nyou can download a [pre-compiled executable](https://github.com/yaa110/cb/releases), then you should copy that executable to `/usr/bin` or add it to your `$PATH` env. Do not forget to `chmod +x cb`.\n\n\n\n#### Distribution packages\n\n\n\nUsers of **Arch Linux** can install package from AUR:\n\n\n\n* Precompiled release: [cb-bin](https://aur.archlinux.org/packages/cb-bin/) (*Only x64 is supported*)\n\n* Build latest release: [cb](https://aur.archlinux.org/packages/cb/)\n\n* Build from master: [cb-git](https://aur.archlinux.org/packages/cb-git/)\n\n\n\n### Build Manually\n\n\n\n- Install rust: `curl -sSf https://sh.rustup.rs | sh`\n\n- Install packages: `xorg-dev` and `build-essential`\n\n- Run `make && sudo make install`\n\n\n\n## How to use\n\n\n\n- Copy text: `cb -t \"Text to be copied\"`\n\n- Paste copied text: `cb -p`\n\n- Copy from stdin: `cat file | cb`\n\n\n\n## Usage\n\n\n\n```sh\n\nUsage: cb [OPTIONS]\n\n\n\nOptional arguments:\n\n -h, --help Prints the help message\n\n -V, --version Prints the version\n\n -p, --paste Pastes the content of clipboard\n\n -c, --clear Clears the content of clipboard\n\n -s, --server Starts server as a daemon\n\n -r, --raw Do not print newline after pasting the content\n\n -t, --text TEXT Store TEXT into clipboard\n\n```\n", "file_path": "README.md", "rank": 38, "score": 15.196157612874375 }, { "content": " .unwrap_or(Action::Clear),\n\n )\n\n .ok()\n\n .and_then(|res| Some(res.status))\n\n .unwrap_or(false)\n\n }\n\n\n\n /// Retrieves the content of clipboard\n\n pub fn get(&mut self) -> Option<String> {\n\n let res = self.send_action(Action::Get).ok()?;\n\n if res.status {\n\n res.content\n\n } else {\n\n None\n\n }\n\n }\n\n\n\n /// Clears the content of clipboard\n\n pub fn clear(&mut self) -> bool {\n\n self.set(None)\n\n }\n\n}\n", "file_path": "cli/src/handler.rs", "rank": 40, "score": 11.58622251188101 }, { "content": "use bytes::buf::BufMut;\n\nuse bytes::BytesMut;\n\nuse common::constants::{SPLITTER, SPLITTER_LEN};\n\nuse common::errors::StringErrorResult;\n\nuse common::message::{Action, Response};\n\nuse hex;\n\nuse std::convert::TryFrom;\n\nuse std::convert::TryInto;\n\nuse std::io::{Read, Write};\n\n\n\n/// Represents clipboard handler\n\npub struct Handler<T: Read + Write> {\n\n stream: T,\n\n}\n\n\n\nimpl<T: Read + Write> Handler<T> {\n\n pub fn new(stream: T) -> Self {\n\n Handler { stream }\n\n }\n\n\n", "file_path": "cli/src/handler.rs", "rank": 41, "score": 10.153044726403316 }, { "content": " /// Sends action to server and receives the response\n\n fn send_action(&mut self, action: Action) -> Result<Response, String> {\n\n let buf: BytesMut = action.try_into()?;\n\n let hex_buf = hex::encode(&buf).into_bytes();\n\n let mut data = BytesMut::with_capacity(hex_buf.len() + *SPLITTER_LEN);\n\n data.put(hex_buf);\n\n data.put(SPLITTER);\n\n self.stream.write_all(&data).error_to_string()?;\n\n let mut res = Vec::new();\n\n self.stream.read_to_end(&mut res).error_to_string()?;\n\n Response::try_from(BytesMut::from(\n\n hex::decode(&res[..res.len() - *SPLITTER_LEN]).error_to_string()?,\n\n ))\n\n }\n\n\n\n /// Stores `content` to clipboard\n\n pub fn set(&mut self, content: Option<String>) -> bool {\n\n self.send_action(\n\n content\n\n .and_then(|content| Some(Action::Set(content)))\n", "file_path": "cli/src/handler.rs", "rank": 43, "score": 8.224074530544307 }, { "content": "mod handler;\n\n\n\npub use handler::*;\n", "file_path": "cli/src/lib.rs", "rank": 44, "score": 4.522290144799044 } ]
Rust
aer_data/src/metadata/chocolatey.rs
WormieCorp/aer
9eaf1d86c36016cac1afd7125bb60c592bdd960a
#![cfg_attr(docsrs, doc(cfg(feature = "chocolatey")))] use std::collections::HashMap; use std::fmt::Display; use aer_version::Versions; #[cfg(feature = "serialize")] use serde::{Deserialize, Serialize}; use url::Url; use crate::prelude::Description; #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "serialize", derive(Deserialize, Serialize))] #[non_exhaustive] pub struct ChocolateyMetadata { #[cfg_attr( feature = "serialize", serde(default = "crate::defaults::boolean_true") )] lowercase_id: bool, pub title: Option<String>, pub copyright: Option<String>, #[cfg_attr( feature = "serialize", serde(default = "crate::defaults::empty_version") )] pub version: Versions, authors: Vec<String>, pub description: Description, #[cfg_attr( feature = "serialize", serde(default = "crate::defaults::boolean_true") )] pub require_license_acceptance: bool, pub documentation_url: Option<Url>, pub issues_url: Option<Url>, #[cfg_attr(feature = "serialize", serde(default))] tags: Vec<String>, #[cfg_attr(feature = "serialize", serde(default))] release_notes: Option<String>, #[cfg_attr(feature = "serialize", serde(default))] dependencies: HashMap<String, Versions>, } impl ChocolateyMetadata { pub fn new() -> ChocolateyMetadata { ChocolateyMetadata { lowercase_id: crate::defaults::boolean_true(), title: None, copyright: None, version: crate::defaults::empty_version(), authors: vec![], description: Description::None, require_license_acceptance: true, documentation_url: None, issues_url: None, tags: vec![], release_notes: None, dependencies: HashMap::new(), } } pub fn lowercase_id(&self) -> bool { self.lowercase_id } pub fn authors(&self) -> &[String] { self.authors.as_slice() } pub fn description(&self) -> &Description { &self.description } pub fn set_description(&mut self, description: Description) { self.description = description; } pub fn set_description_str(&mut self, description: &str) { self.set_description(Description::Text(description.into())); } pub fn set_title(&mut self, title: &str) { if let Some(ref mut self_title) = self.title { self_title.clear(); self_title.push_str(title); } else { self.title = Some(title.into()); } } pub fn set_copyright(&mut self, copyright: &str) { if let Some(ref mut self_copyright) = self.copyright { self_copyright.clear(); self_copyright.push_str(copyright); } else { self.copyright = Some(copyright.into()); } } pub fn set_release_notes(&mut self, release_notes: &str) { if let Some(ref mut self_release_notes) = self.release_notes { self_release_notes.clear(); self_release_notes.push_str(release_notes); } else { self.release_notes = Some(release_notes.into()); } } pub fn add_dependencies(&mut self, id: &str, version: &str) { self.dependencies .insert(id.into(), Versions::parse(version).unwrap()); } pub fn set_dependencies(&mut self, dependencies: HashMap<String, Versions>) { self.dependencies = dependencies; } pub fn set_tags<T>(&mut self, tags: &[T]) -> &Self where T: Display, { self.tags.clear(); for tag in tags.iter() { self.tags.push(tag.to_string()); } self } pub fn with_authors<T>(values: &[T]) -> Self where T: Display, { if values.is_empty() { panic!("Invalid usage: Authors can not be empty!"); } let mut data = Self::new(); let mut new_authors = Vec::<String>::with_capacity(values.len()); for val in values.iter() { new_authors.push(val.to_string()); } data.authors = new_authors; data } } impl Default for ChocolateyMetadata { fn default() -> ChocolateyMetadata { ChocolateyMetadata::new() } } #[cfg(test)] mod tests { use super::*; #[test] fn new_should_create_with_expected_values() { let expected = ChocolateyMetadata { lowercase_id: true, title: None, copyright: None, version: crate::defaults::empty_version(), authors: vec![], description: Description::None, require_license_acceptance: true, documentation_url: None, issues_url: None, tags: vec![], release_notes: None, dependencies: HashMap::new(), }; let actual = ChocolateyMetadata::new(); assert_eq!(actual, expected); } #[test] fn default_should_create_with_expected_values() { let expected = ChocolateyMetadata { lowercase_id: true, title: None, copyright: None, version: crate::defaults::empty_version(), authors: vec![], description: Description::None, require_license_acceptance: true, documentation_url: None, issues_url: None, tags: vec![], release_notes: None, dependencies: HashMap::new(), }; let actual = ChocolateyMetadata::default(); assert_eq!(actual, expected); } #[test] #[allow(non_snake_case)] fn with_authors_should_set_specified_authors_using_String() { let authors = [ String::from("AdmiringWorm"), String::from("Chocolatey-Community"), ]; let actual = ChocolateyMetadata::with_authors(&authors); assert_eq!(actual.authors(), authors); } #[test] fn with_authors_should_set_specified_authors_using_reference_str() { let authors = ["AdmiringWorm", "Chocolatey"]; let actual = ChocolateyMetadata::with_authors(&authors); assert_eq!(actual.authors(), authors); } #[test] #[should_panic(expected = "Invalid usage: Authors can not be empty!")] fn with_authors_should_panic_on_empty_vector() { let val: Vec<String> = vec![]; ChocolateyMetadata::with_authors(&val); } #[test] #[should_panic(expected = "Invalid usage: Authors can not be empty!")] fn with_authors_should_panic_on_empty_array() { let val: [&str; 0] = []; ChocolateyMetadata::with_authors(&val); } #[test] fn lowercase_id_should_return_set_values() { let mut data = ChocolateyMetadata::new(); assert_eq!(data.lowercase_id(), true); data.lowercase_id = false; let actual = data.lowercase_id(); assert_eq!(actual, false); } #[test] fn description_should_return_set_values() { let mut data = ChocolateyMetadata::new(); assert_eq!(data.description(), &Description::None); data.description = Description::Text("Some kind of description".into()); let actual = data.description(); assert_eq!(actual, "Some kind of description"); } #[test] fn set_description_should_set_expected_value() { let mut data = ChocolateyMetadata::new(); data.set_description_str("My awesome description"); assert_eq!(data.description(), "My awesome description"); } }
#![cfg_attr(docsrs, doc(cfg(feature = "chocolatey")))] use std::collections::HashMap; use std::fmt::Display; use aer_version::Versions; #[cfg(feature = "serialize")] use serde::{Deserialize, Serialize}; use url::Url; use crate::prelude::Description; #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "serialize", derive(Deserialize, Serialize))] #[non_exhaustive] pub struct ChocolateyMetadata { #[cfg_attr( feature = "serialize", serde(default = "crate::defaults::boolean_true") )] lowercase_id: bool, pub title: Option<String>, pub copyright: Option<String>, #[cfg_attr( feature = "serialize", serde(default = "crate::defaults::empty_version") )] pub version: Versions,
on::Text(description.into())); } pub fn set_title(&mut self, title: &str) { if let Some(ref mut self_title) = self.title { self_title.clear(); self_title.push_str(title); } else { self.title = Some(title.into()); } } pub fn set_copyright(&mut self, copyright: &str) { if let Some(ref mut self_copyright) = self.copyright { self_copyright.clear(); self_copyright.push_str(copyright); } else { self.copyright = Some(copyright.into()); } } pub fn set_release_notes(&mut self, release_notes: &str) { if let Some(ref mut self_release_notes) = self.release_notes { self_release_notes.clear(); self_release_notes.push_str(release_notes); } else { self.release_notes = Some(release_notes.into()); } } pub fn add_dependencies(&mut self, id: &str, version: &str) { self.dependencies .insert(id.into(), Versions::parse(version).unwrap()); } pub fn set_dependencies(&mut self, dependencies: HashMap<String, Versions>) { self.dependencies = dependencies; } pub fn set_tags<T>(&mut self, tags: &[T]) -> &Self where T: Display, { self.tags.clear(); for tag in tags.iter() { self.tags.push(tag.to_string()); } self } pub fn with_authors<T>(values: &[T]) -> Self where T: Display, { if values.is_empty() { panic!("Invalid usage: Authors can not be empty!"); } let mut data = Self::new(); let mut new_authors = Vec::<String>::with_capacity(values.len()); for val in values.iter() { new_authors.push(val.to_string()); } data.authors = new_authors; data } } impl Default for ChocolateyMetadata { fn default() -> ChocolateyMetadata { ChocolateyMetadata::new() } } #[cfg(test)] mod tests { use super::*; #[test] fn new_should_create_with_expected_values() { let expected = ChocolateyMetadata { lowercase_id: true, title: None, copyright: None, version: crate::defaults::empty_version(), authors: vec![], description: Description::None, require_license_acceptance: true, documentation_url: None, issues_url: None, tags: vec![], release_notes: None, dependencies: HashMap::new(), }; let actual = ChocolateyMetadata::new(); assert_eq!(actual, expected); } #[test] fn default_should_create_with_expected_values() { let expected = ChocolateyMetadata { lowercase_id: true, title: None, copyright: None, version: crate::defaults::empty_version(), authors: vec![], description: Description::None, require_license_acceptance: true, documentation_url: None, issues_url: None, tags: vec![], release_notes: None, dependencies: HashMap::new(), }; let actual = ChocolateyMetadata::default(); assert_eq!(actual, expected); } #[test] #[allow(non_snake_case)] fn with_authors_should_set_specified_authors_using_String() { let authors = [ String::from("AdmiringWorm"), String::from("Chocolatey-Community"), ]; let actual = ChocolateyMetadata::with_authors(&authors); assert_eq!(actual.authors(), authors); } #[test] fn with_authors_should_set_specified_authors_using_reference_str() { let authors = ["AdmiringWorm", "Chocolatey"]; let actual = ChocolateyMetadata::with_authors(&authors); assert_eq!(actual.authors(), authors); } #[test] #[should_panic(expected = "Invalid usage: Authors can not be empty!")] fn with_authors_should_panic_on_empty_vector() { let val: Vec<String> = vec![]; ChocolateyMetadata::with_authors(&val); } #[test] #[should_panic(expected = "Invalid usage: Authors can not be empty!")] fn with_authors_should_panic_on_empty_array() { let val: [&str; 0] = []; ChocolateyMetadata::with_authors(&val); } #[test] fn lowercase_id_should_return_set_values() { let mut data = ChocolateyMetadata::new(); assert_eq!(data.lowercase_id(), true); data.lowercase_id = false; let actual = data.lowercase_id(); assert_eq!(actual, false); } #[test] fn description_should_return_set_values() { let mut data = ChocolateyMetadata::new(); assert_eq!(data.description(), &Description::None); data.description = Description::Text("Some kind of description".into()); let actual = data.description(); assert_eq!(actual, "Some kind of description"); } #[test] fn set_description_should_set_expected_value() { let mut data = ChocolateyMetadata::new(); data.set_description_str("My awesome description"); assert_eq!(data.description(), "My awesome description"); } }
authors: Vec<String>, pub description: Description, #[cfg_attr( feature = "serialize", serde(default = "crate::defaults::boolean_true") )] pub require_license_acceptance: bool, pub documentation_url: Option<Url>, pub issues_url: Option<Url>, #[cfg_attr(feature = "serialize", serde(default))] tags: Vec<String>, #[cfg_attr(feature = "serialize", serde(default))] release_notes: Option<String>, #[cfg_attr(feature = "serialize", serde(default))] dependencies: HashMap<String, Versions>, } impl ChocolateyMetadata { pub fn new() -> ChocolateyMetadata { ChocolateyMetadata { lowercase_id: crate::defaults::boolean_true(), title: None, copyright: None, version: crate::defaults::empty_version(), authors: vec![], description: Description::None, require_license_acceptance: true, documentation_url: None, issues_url: None, tags: vec![], release_notes: None, dependencies: HashMap::new(), } } pub fn lowercase_id(&self) -> bool { self.lowercase_id } pub fn authors(&self) -> &[String] { self.authors.as_slice() } pub fn description(&self) -> &Description { &self.description } pub fn set_description(&mut self, description: Description) { self.description = description; } pub fn set_description_str(&mut self, description: &str) { self.set_description(Descripti
random
[ { "content": "#[cfg(feature = \"chocolatey\")]\n\npub fn boolean_true() -> bool {\n\n true\n\n}\n\n\n", "file_path": "aer_data/src/defaults.rs", "rank": 0, "score": 93514.10413531325 }, { "content": "pub trait FixVersion {\n\n fn is_fix_version(&self) -> bool;\n\n fn add_fix(&mut self) -> Result<(), std::num::ParseIntError>;\n\n}\n", "file_path": "aer_version/src/versions.rs", "rank": 1, "score": 89057.26303696276 }, { "content": "fn num_is_fix<T: std::cmp::Ord + From<u32>>(num: T) -> bool {\n\n num.ge(&T::from(FIX_THRESHOLD))\n\n}\n\n\n\nimpl FixVersion for ChocoVersion {\n\n fn is_fix_version(&self) -> bool {\n\n if let Some(build) = self.build {\n\n // We will assume it is a fix version if the build part is higher than the\n\n // threshold\n\n num_is_fix(build)\n\n } else if let Some(Identifier::Numeric(num)) = self.pre_release.last() {\n\n num_is_fix(*num)\n\n } else {\n\n false\n\n }\n\n }\n\n\n\n fn add_fix(&mut self) -> Result<(), std::num::ParseIntError> {\n\n if self.build.is_none() || self.is_fix_version() {\n\n let fix = format!(\"{}\", chrono::Local::today().format(\"%Y%m%d\"));\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 2, "score": 83616.53370956155 }, { "content": "#[cfg(feature = \"chocolatey\")]\n\npub fn empty_version() -> Versions {\n\n Versions::SemVer(SemVersion::new(0, 0, 0))\n\n}\n\n\n", "file_path": "aer_data/src/defaults.rs", "rank": 3, "score": 80764.49115084877 }, { "content": "// Copyright (c) 2021 Kim J. Nordmo and WormieCorp.\n\n// Licensed under the MIT license. See LICENSE.txt file in the project\n\n\n\n#![cfg(feature = \"chocolatey\")]\n\n#![cfg_attr(docsrs, doc(cfg(feature = \"chocolatey\")))]\n\n\n\nuse std::cmp::Ordering;\n\nuse std::fmt::Display;\n\n\n\nuse semver::Identifier;\n\n#[cfg(feature = \"serialize\")]\n\nuse serde::de::{self, Visitor};\n\n#[cfg(feature = \"serialize\")]\n\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\n\n\n\nuse crate::{FixVersion, SemVersion, SemanticVersionError};\n\n\n\n#[allow(clippy::inconsistent_digit_grouping)] // We want it to be shown in the ISO date format\n\nconst FIX_THRESHOLD: u32 = 2007_01_01;\n\n\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 4, "score": 66556.26078477707 }, { "content": " } else if build > 0 {\n\n ver_str.push_str(&format!(\"{}{}\", delim, build));\n\n }\n\n\n\n SemVersion::parse(&ver_str).unwrap()\n\n }\n\n}\n\n\n\n#[cfg(feature = \"serialize\")]\n\n#[cfg_attr(docsrs, doc(cfg(feature = \"serialize\")))]\n\nimpl Serialize for ChocoVersion {\n\n fn serialize<S>(&self, serialize: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: Serializer,\n\n {\n\n // Serialize ChocoVersion as a string\n\n serialize.collect_str(self)\n\n }\n\n}\n\n\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 5, "score": 66548.83789496013 }, { "content": "/// Holds the relevant portions of a version that is compatible with the\n\n/// chocolatey package manager.\n\n///\n\n/// This structure also handles parsing different kind of versions and making\n\n/// these compatible with chocolatey, converting between chocolatey and semver\n\n/// as well as allowing fix versions to be created for both stable and unstable\n\n/// versions.\n\n#[derive(Default, Debug, Clone, Eq)]\n\npub struct ChocoVersion {\n\n major: u8,\n\n minor: u8,\n\n patch: Option<u8>,\n\n /// The build part of the version, this is specified as an unsigned 32bit\n\n /// integer to allow fix versions.\n\n build: Option<u32>,\n\n pre_release: Vec<Identifier>,\n\n}\n\n\n\nimpl ChocoVersion {\n\n /// Creates a new instance of the [ChocoVersion] structure with the major\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 6, "score": 66548.65794929709 }, { "content": "#[cfg(feature = \"serialize\")]\n\n#[cfg_attr(docsrs, doc(cfg(feature = \"serialize\")))]\n\nimpl<'de> Deserialize<'de> for ChocoVersion {\n\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n\n where\n\n D: Deserializer<'de>,\n\n {\n\n struct ChocoVersionVisitor;\n\n\n\n // Deserialize ChocoVersion from a string.\n\n impl<'de> Visitor<'de> for ChocoVersionVisitor {\n\n type Value = ChocoVersion;\n\n\n\n fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {\n\n formatter.write_str(\"a Chocolatey version as a string\")\n\n }\n\n\n\n fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>\n\n where\n\n E: de::Error,\n\n {\n\n ChocoVersion::parse(v).map_err(de::Error::custom)\n\n }\n\n }\n\n\n\n deserializer.deserialize_str(ChocoVersionVisitor)\n\n }\n\n}\n\n\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 7, "score": 66548.18868197485 }, { "content": " }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use rstest::rstest;\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn display_should_output_major_and_minor_version() {\n\n let version = ChocoVersion::new(1, 2);\n\n let expected = \"1.2\";\n\n\n\n let actual = version.to_string();\n\n\n\n assert_eq!(actual, expected);\n\n }\n\n\n\n #[test]\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 8, "score": 66545.10796744745 }, { "content": " patch,\n\n build,\n\n pre_release: pre,\n\n };\n\n\n\n Ok(result)\n\n }\n\n\n\n /// Specifically sets the patch version (third part of the version).\n\n pub fn set_patch(&mut self, patch: u8) {\n\n self.patch = Some(patch);\n\n }\n\n\n\n /// Specifically sets the build version (fourth part of the version).\n\n pub fn set_build(&mut self, build: u32) {\n\n if self.patch.is_none() {\n\n self.patch = Some(0);\n\n }\n\n\n\n self.build = Some(build);\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 9, "score": 66544.57611343937 }, { "content": " /// and minor version set to the specified values (`major.minor`).\n\n pub fn new(major: u8, minor: u8) -> ChocoVersion {\n\n ChocoVersion {\n\n major,\n\n minor,\n\n ..Default::default()\n\n }\n\n }\n\n\n\n /// Creates a new instance of the [ChocoVersion] structure with the\n\n /// specified major, minor and patch versions (`major.minor.patch`).\n\n pub fn with_patch(major: u8, minor: u8, patch: u8) -> ChocoVersion {\n\n let mut choco = ChocoVersion::new(major, minor);\n\n choco.set_patch(patch);\n\n choco\n\n }\n\n\n\n /// Creates a new instance of the [ChocoVersion] structure with the\n\n /// specified major, minor, patch and build versions\n\n /// (`major.minor.patch.build`).\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 10, "score": 66544.22808958168 }, { "content": " pub fn with_build(major: u8, minor: u8, patch: u8, build: u32) -> ChocoVersion {\n\n let mut choco = ChocoVersion::with_patch(major, minor, patch);\n\n choco.set_build(build);\n\n choco\n\n }\n\n\n\n /// Parses the specified string reference and tries to extract a new\n\n /// instance of [ChocoVersion]. Returns a failure if the parsing of the\n\n /// string was not successful.\n\n pub fn parse(val: &str) -> Result<ChocoVersion, Box<dyn std::error::Error>> {\n\n if val.is_empty() {\n\n return Err(Box::new(SemanticVersionError::ParseError(\n\n \"There is no version string to parse\".into(),\n\n )));\n\n } else if !val.chars().next().unwrap_or('.').is_digit(10) {\n\n return Err(Box::new(SemanticVersionError::ParseError(\n\n \"The version string do not start with a number\".into(),\n\n )));\n\n }\n\n\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 11, "score": 66543.91110403842 }, { "content": " }\n\n\n\n /// Sets and replaces the pre-release part of the version, without doing any\n\n /// parsing.\n\n pub fn set_prerelease(&mut self, pre: Vec<Identifier>) {\n\n self.pre_release = pre;\n\n }\n\n\n\n /// Sets and replaces the pre-release part of the version, without doing any\n\n /// parsing. Will move the current [ChocoVersion] instance to a new\n\n /// instance.\n\n pub fn with_prerelease(mut self, pre: Vec<Identifier>) -> Self {\n\n self.set_prerelease(pre);\n\n self\n\n }\n\n}\n\n\n\nimpl Ord for ChocoVersion {\n\n fn cmp(&self, other: &Self) -> Ordering {\n\n let major_cmp = self.major.cmp(&other.major);\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 12, "score": 66543.89544035468 }, { "content": " }\n\n\n\n #[test]\n\n fn add_fix_should_not_create_fix_version_when_build_is_in_use() {\n\n let mut version = ChocoVersion::new(0, 2);\n\n version.set_build(5);\n\n version.add_fix().unwrap();\n\n let expected = \"0.2.0.5\";\n\n\n\n let actual = version.to_string();\n\n\n\n assert_eq!(actual, expected);\n\n }\n\n\n\n #[test]\n\n fn add_fix_should_replace_old_date_fix_with_new_date() {\n\n let mut version = ChocoVersion::new(3, 3);\n\n version.set_build(20200826);\n\n version.add_fix().unwrap();\n\n let expected = format!(\"3.3.0.{}\", chrono::Local::now().format(\"%Y%m%d\"));\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 13, "score": 66543.83567111775 }, { "content": " test, expected,\n\n case(\"3.0.0-beta-0050\", SemVersion::parse(\"3.0.0-beta.50\").unwrap()),\n\n case(\"1.2.2.5-unstable-0050\", SemVersion::parse(\"1.2.2-unstable.50+5\").unwrap()),\n\n case(\"5.1-beta0995\", SemVersion::parse(\"5.1.0-beta.995\").unwrap()),\n\n case(\"1.0-alpha-0002-rc0005\", SemVersion::parse(\"1.0.0-alpha-rc-2.5\").unwrap()), // This ending version is due to chocolatey parsing\n\n case(\"5.0-beta-ceta\", SemVersion::parse(\"5.0.0-beta-ceta\").unwrap()),\n\n case(\"1.5-0033\", SemVersion::parse(\"1.5.0-unstable.33\").unwrap()) // This should actually never happen\n\n )]\n\n fn from_should_create_sematic_version(test: &str, expected: SemVersion) {\n\n let actual = SemVersion::from(ChocoVersion::parse(test).unwrap());\n\n\n\n assert_eq!(actual, expected);\n\n }\n\n\n\n #[test]\n\n fn should_sort_versions() {\n\n let mut versions = vec![\n\n ChocoVersion::parse(\"1.2.0-55\").unwrap(),\n\n ChocoVersion::parse(\"1.2\").unwrap(),\n\n ChocoVersion::parse(\"0.4.2.1\").unwrap(),\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 14, "score": 66543.35993698814 }, { "content": "impl PartialOrd for ChocoVersion {\n\n fn partial_cmp(&self, other: &Self) -> std::option::Option<std::cmp::Ordering> {\n\n Some(self.cmp(&other))\n\n }\n\n}\n\n\n\nimpl PartialEq for ChocoVersion {\n\n fn eq(&self, other: &Self) -> bool {\n\n self.major == other.major\n\n && self.minor == other.minor\n\n && self.patch.unwrap_or(0) == other.patch.unwrap_or(0)\n\n && self.build.unwrap_or(0) == other.build.unwrap_or(0)\n\n }\n\n}\n\n\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 15, "score": 66543.25542422761 }, { "content": " assert_eq!(actual, expected);\n\n }\n\n\n\n #[test]\n\n fn is_fix_version_should_be_true_on_high_build_version() {\n\n let version = ChocoVersion::parse(\"3.5.2.20100506\").unwrap();\n\n\n\n assert_eq!(version.is_fix_version(), true);\n\n }\n\n\n\n #[test]\n\n fn is_fix_version_should_be_false_on_empty_build_version() {\n\n let version = ChocoVersion::parse(\"2.2.1\").unwrap();\n\n\n\n assert_eq!(version.is_fix_version(), false);\n\n }\n\n\n\n #[test]\n\n fn is_fix_version_should_be_false_on_non_high_build_version() {\n\n let version = ChocoVersion::parse(\"3.2.6.55\").unwrap();\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 16, "score": 66542.06103445603 }, { "content": "\n\n assert_eq!(version.is_fix_version(), false);\n\n }\n\n\n\n #[test]\n\n fn is_fix_version_should_be_true_on_prerelease_fix_version() {\n\n let version = ChocoVersion::parse(\"5.2-beta-20210407\").unwrap();\n\n\n\n assert_eq!(version.is_fix_version(), true);\n\n }\n\n\n\n #[test]\n\n fn add_fix_should_create_correct_fix_version() {\n\n let mut version = ChocoVersion::new(2, 1);\n\n version.add_fix().unwrap();\n\n let expected = format!(\"2.1.0.{}\", chrono::Local::now().format(\"%Y%m%d\"));\n\n\n\n let actual = version.to_string();\n\n\n\n assert_eq!(actual, expected);\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 17, "score": 66541.94967175095 }, { "content": " ChocoVersion::parse(\"6.2.0\").unwrap(),\n\n ChocoVersion::parse(\"1.0.0-rc\").unwrap(),\n\n ChocoVersion::parse(\"1.0.0-alpha\").unwrap(),\n\n ChocoVersion::parse(\"5.0-beta.56\").unwrap(),\n\n ChocoVersion::parse(\"5.0-beta.55\").unwrap(),\n\n ];\n\n let expected = vec![\n\n ChocoVersion::parse(\"0.4.2.1\").unwrap(),\n\n ChocoVersion::parse(\"1.0.0-alpha\").unwrap(),\n\n ChocoVersion::parse(\"1.0.0-rc\").unwrap(),\n\n ChocoVersion::parse(\"1.2.0-55\").unwrap(),\n\n ChocoVersion::parse(\"1.2\").unwrap(),\n\n ChocoVersion::parse(\"5.0-beta.55\").unwrap(),\n\n ChocoVersion::parse(\"5.0-beta.56\").unwrap(),\n\n ChocoVersion::parse(\"6.2.0\").unwrap(),\n\n ];\n\n\n\n versions.sort();\n\n\n\n assert_eq!(versions, expected);\n\n }\n\n}\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 18, "score": 66541.93297228742 }, { "content": " fn display_should_output_major_minor_and_patch_version() {\n\n let mut version = ChocoVersion::new(1, 6);\n\n version.set_patch(10);\n\n let expected = \"1.6.10\";\n\n\n\n let actual = version.to_string();\n\n\n\n assert_eq!(actual, expected);\n\n }\n\n\n\n #[test]\n\n fn display_should_output_major_minor_patch_and_build_version() {\n\n let mut version = ChocoVersion::new(0, 8);\n\n version.set_patch(3);\n\n version.set_build(99);\n\n let expected = \"0.8.3.99\";\n\n\n\n let actual = version.to_string();\n\n\n\n assert_eq!(actual, expected);\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 19, "score": 66541.91016293112 }, { "content": " }\n\n\n\n #[test]\n\n fn set_build_should_also_set_default_patch_number() {\n\n let mut version = ChocoVersion::new(1, 1);\n\n version.set_build(5);\n\n let expected = \"1.1.0.5\";\n\n\n\n let actual = version.to_string();\n\n\n\n assert_eq!(actual, expected);\n\n }\n\n\n\n #[test]\n\n fn with_build_should_set_full_build_version() {\n\n let version = ChocoVersion::with_build(5, 1, 1, 3);\n\n let expected = \"5.1.1.3\";\n\n\n\n let actual = version.to_string();\n\n\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 20, "score": 66541.83994306657 }, { "content": "\n\n let actual = version.to_string();\n\n\n\n assert_eq!(actual, expected);\n\n }\n\n\n\n #[test]\n\n fn add_fix_should_create_prerelease_fix_version() {\n\n let mut version = ChocoVersion::parse(\"3.1.1-alpha\").unwrap();\n\n version.add_fix().unwrap();\n\n let expected = format!(\"3.1.1-alpha-{}\", chrono::Local::now().format(\"%Y%m%d\"));\n\n\n\n let actual = format!(\"{}\", version);\n\n\n\n assert_eq!(actual, expected);\n\n }\n\n\n\n #[test]\n\n fn add_fix_should_replace_old_prelease_date_fix_with_new_date() {\n\n let mut version = ChocoVersion::parse(\"5.1.7-ceta-20100602\").unwrap();\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 21, "score": 66541.62688081914 }, { "content": " v,\n\n expected,\n\n case(\"3\", \"3.0\"),\n\n case(\"1.0\", \"1.0\"),\n\n case(\"0.2.65\", \"0.2.65\"),\n\n case(\"3.5.0.2342\", \"3.5.0.2342\"),\n\n case(\"3.3-alpha001\", \"3.3-alpha0001\"),\n\n case(\"3.2-alpha.10\", \"3.2-alpha0010\"),\n\n case(\"3.3.5-beta-11\", \"3.3.5-beta0011\"),\n\n case(\"3.1.1+55\", \"3.1.1\"),\n\n case(\"4.0.0.2-beta.5\", \"4.0.0.2-beta0005\"),\n\n case(\"0.1.0-55\", \"0.1.0-unstable0055\"),\n\n case(\"4.2.1-alpha54.2\", \"4.2.1-alpha0054-0002\"),\n\n case(\"6.1.0-55-alpha\", \"6.1.0-alpha0055\")\n\n )]\n\n fn parse_should_create_correct_versions(v: &str, expected: &str) {\n\n let version = ChocoVersion::parse(v).unwrap();\n\n let version = version.to_string();\n\n\n\n assert_eq!(version, expected);\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 22, "score": 66541.55007658429 }, { "content": " }\n\n\n\n #[rstest(\n\n val,\n\n case(\"\"),\n\n case(\"6.2.2.2.1\"),\n\n case(\"no-version\"),\n\n case(\"6.2.1.1.3.4\")\n\n )]\n\n #[should_panic]\n\n fn parse_should_return_none(val: &str) {\n\n let _ = ChocoVersion::parse(val).unwrap();\n\n }\n\n\n\n #[test]\n\n fn from_should_create_choco_version() {\n\n let expected = ChocoVersion {\n\n major: 5,\n\n minor: 3,\n\n patch: Some(1),\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 23, "score": 66541.5029644907 }, { "content": " version.add_fix().unwrap();\n\n let expected = format!(\"5.1.7-ceta-{}\", chrono::Local::now().format(\"%Y%m%d\"));\n\n\n\n let actual = format!(\"{}\", version);\n\n\n\n assert_eq!(actual, expected);\n\n }\n\n\n\n #[test]\n\n fn add_fix_should_not_replace_non_date_number_in_prerelease() {\n\n let mut version = ChocoVersion::parse(\"2.1.1-alpha-0010\").unwrap();\n\n version.add_fix().unwrap();\n\n let expected = format!(\"2.1.1-alpha0010-{}\", chrono::Local::now().format(\"%Y%m%d\"));\n\n\n\n let actual = format!(\"{}\", version);\n\n\n\n assert_eq!(actual, expected);\n\n }\n\n\n\n #[rstest(\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 24, "score": 66541.42952403176 }, { "content": " ),\n\n case(\n\n \"1.2.3-beta50\",\n\n ChocoVersion::with_patch(1, 2, 3).with_prerelease(vec![Identifier::AlphaNumeric(\"beta\".into()), Identifier::Numeric(50)])\n\n ),\n\n case(\n\n \"3.0.0-666\",\n\n ChocoVersion::with_patch(3, 0, 0).with_prerelease(vec![Identifier::AlphaNumeric(\"unstable\".into()), Identifier::Numeric(666)])\n\n ),\n\n case(\"2.0.0-55beta\", ChocoVersion::with_patch(2, 0, 0).with_prerelease(vec![Identifier::AlphaNumeric(\"beta\".into()), Identifier::Numeric(55)])),\n\n case(\"4.2.1-alpha54.2\", ChocoVersion::with_patch(4, 2, 1).with_prerelease(vec![Identifier::AlphaNumeric(\"alpha\".into()), Identifier::Numeric(54), Identifier::Numeric(2)])),\n\n case(\"6.1.0-55-alpha\", ChocoVersion::with_patch(6, 1, 0).with_prerelease(vec![Identifier::AlphaNumeric(\"alpha\".into()).into(), Identifier::Numeric(55)]))\n\n )]\n\n fn from_should_create_choco_version_with_prerelease(test: &str, expected: ChocoVersion) {\n\n let actual = ChocoVersion::from(SemVersion::parse(test).unwrap());\n\n\n\n assert_eq!(actual, expected);\n\n }\n\n\n\n #[rstest(\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 25, "score": 66541.42481687023 }, { "content": " ..Default::default()\n\n };\n\n\n\n let actual = ChocoVersion::from(SemVersion::parse(\"5.3.1\").unwrap());\n\n\n\n assert_eq!(actual, expected);\n\n }\n\n\n\n #[rstest(test, expected,\n\n case(\n\n \"1.255.3-alpha+446\",\n\n ChocoVersion::with_patch(1, 255, 3).with_prerelease(vec![Identifier::AlphaNumeric(\"alpha\".into())])\n\n ),\n\n case(\n\n \"0.3.0-unstable-001\",\n\n ChocoVersion::with_patch(0, 3, 0).with_prerelease(vec![Identifier::AlphaNumeric(\"unstable\".into()), Identifier::Numeric(1)])\n\n ),\n\n case(\n\n \"5.1.1-alpha.5\",\n\n ChocoVersion::with_patch(5, 1, 1).with_prerelease(vec![Identifier::AlphaNumeric(\"alpha\".into()), Identifier::Numeric(5)])\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 26, "score": 66541.27658299606 }, { "content": " return Err(Box::new(SemanticVersionError::ParseError(\n\n \"There were additional numeric characters after the first 4 parts of the \\\n\n version\"\n\n .into(),\n\n )));\n\n }\n\n };\n\n ver_str.clear();\n\n }\n\n\n\n let subst: String = val\n\n .chars()\n\n .skip_while(|ch| ch.is_digit(10) || *ch == '.')\n\n .collect();\n\n\n\n let pre = { extract_prerelease(&subst) };\n\n\n\n let result = ChocoVersion {\n\n major,\n\n minor,\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 27, "score": 66541.0618444532 }, { "content": "\n\n choco.set_prerelease(pre_releases);\n\n\n\n choco\n\n }\n\n}\n\n\n\nimpl From<ChocoVersion> for SemVersion {\n\n fn from(choco: ChocoVersion) -> Self {\n\n let mut ver_str = format!(\n\n \"{}.{}.{}\",\n\n choco.major,\n\n choco.minor,\n\n choco.patch.unwrap_or(0)\n\n );\n\n\n\n let mut build = 0;\n\n for pre in choco.pre_release {\n\n match pre {\n\n Identifier::AlphaNumeric(s) => {\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 28, "score": 66541.0402438399 }, { "content": " let num_fix = fix.parse()?;\n\n\n\n if self.pre_release.is_empty() {\n\n self.set_build(num_fix);\n\n } else if let Some(Identifier::Numeric(num)) = self.pre_release.last_mut() {\n\n if num_is_fix(*num) {\n\n *num = num_fix as u64;\n\n } else {\n\n self.pre_release.push(Identifier::Numeric(num_fix as u64));\n\n }\n\n } else {\n\n self.pre_release.push(Identifier::Numeric(num_fix as u64));\n\n }\n\n }\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl From<SemVersion> for ChocoVersion {\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 29, "score": 66540.36023112059 }, { "content": " let mut major = 0;\n\n let mut minor = 0;\n\n let mut patch = None;\n\n let mut build = None;\n\n let mut i = 0;\n\n let mut ver_str = String::new();\n\n\n\n for ch in val.chars() {\n\n if ch.is_digit(10) {\n\n ver_str.push(ch);\n\n } else if ch == '.' {\n\n match i {\n\n 0 => major = ver_str.parse()?,\n\n 1 => minor = ver_str.parse()?,\n\n 2 => patch = Some(ver_str.parse()?),\n\n 3 => build = Some(ver_str.parse()?),\n\n _ => {\n\n return Err(Box::new(SemanticVersionError::ParseError(\n\n \"There were additional numeric characters after the first 4 parts of \\\n\n the version\"\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 30, "score": 66540.13699052662 }, { "content": " result.remove(0);\n\n next = current.clone();\n\n current.clear();\n\n }\n\n current.push(ch);\n\n }\n\n\n\n if let Some(res) = get_identifier(&current) {\n\n result.push(res);\n\n }\n\n\n\n if let Some(res) = get_identifier(&next) {\n\n result.push(res);\n\n }\n\n\n\n result\n\n}\n\n\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 31, "score": 66540.1277429084 }, { "content": " fn from(semver: SemVersion) -> Self {\n\n let mut choco = ChocoVersion::new(\n\n get_val(semver.major, u8::MAX as u64) as u8,\n\n get_val(semver.minor, u8::MAX as u64) as u8,\n\n );\n\n choco.set_patch(get_val(semver.patch, u8::MAX as u64) as u8);\n\n let mut pre_releases = vec![];\n\n for identifier in semver.pre {\n\n match identifier {\n\n Identifier::AlphaNumeric(val) => {\n\n pre_releases.extend(extract_prerelease(&val));\n\n }\n\n Identifier::Numeric(val) => {\n\n if pre_releases.is_empty() {\n\n pre_releases.push(Identifier::AlphaNumeric(\"unstable\".into()));\n\n }\n\n pre_releases.push(Identifier::Numeric(val));\n\n }\n\n }\n\n }\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 32, "score": 66539.84781813383 }, { "content": " if nums.is_empty() {\n\n Some(Identifier::AlphaNumeric(vals))\n\n } else if let Ok(nums) = nums.parse::<u32>() {\n\n Some(Identifier::AlphaNumeric(format!(\"{}{:04}\", vals, nums)))\n\n } else {\n\n Some(Identifier::AlphaNumeric(format!(\"{}{}\", vals, nums)))\n\n }\n\n}\n\n\n\nimpl Display for ChocoVersion {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {\n\n write!(f, \"{}.{}\", self.major, self.minor)?;\n\n if let Some(patch) = self.patch {\n\n write!(f, \".{}\", patch)?;\n\n }\n\n\n\n if let Some(build) = self.build {\n\n write!(f, \".{}\", build)?;\n\n }\n\n\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 33, "score": 66539.38116359407 }, { "content": " let mut prev_alpha = false;\n\n\n\n for pre in &self.pre_release {\n\n match pre {\n\n Identifier::Numeric(num) => {\n\n if prev_alpha && !num_is_fix(*num) {\n\n write!(f, \"{:04}\", num)?;\n\n } else {\n\n write!(f, \"-{:04}\", num)?;\n\n }\n\n prev_alpha = false;\n\n }\n\n num => {\n\n write!(f, \"-{}\", num)?;\n\n prev_alpha = true;\n\n }\n\n }\n\n }\n\n\n\n Ok(())\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 34, "score": 66537.19404232861 }, { "content": " .into(),\n\n )));\n\n }\n\n };\n\n\n\n i += 1;\n\n\n\n ver_str.clear();\n\n } else {\n\n break;\n\n }\n\n }\n\n\n\n if !ver_str.is_empty() {\n\n match i {\n\n 0 => major = ver_str.parse()?,\n\n 1 => minor = ver_str.parse()?,\n\n 2 => patch = Some(ver_str.parse()?),\n\n 3 => build = Some(ver_str.parse()?),\n\n _ => {\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 35, "score": 66537.19404232861 }, { "content": " let prefix: String = s.chars().take_while(|ch| !ch.is_digit(10)).collect();\n\n let suffix: String = s.chars().skip_while(|ch| !ch.is_digit(10)).collect();\n\n if !prefix.is_empty() {\n\n ver_str.push_str(&format!(\"-{}\", prefix));\n\n }\n\n if let Ok(num) = suffix.parse() {\n\n if build > 0 {\n\n ver_str.push_str(&format!(\"-{}\", build));\n\n }\n\n build = num;\n\n } else if !suffix.is_empty() {\n\n if prefix.is_empty() {\n\n ver_str.push_str(&format!(\"-{}\", suffix));\n\n } else {\n\n ver_str.push_str(&suffix);\n\n }\n\n }\n\n }\n\n Identifier::Numeric(num) => {\n\n if build > 0 {\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 36, "score": 66537.19404232861 }, { "content": " result.push(Identifier::AlphaNumeric(NORMAL_PRE.into()));\n\n } else if current.chars().any(|ch| !ch.is_digit(10)) {\n\n if let Some(res) = get_identifier(&current) {\n\n current.clear();\n\n result.push(res);\n\n }\n\n }\n\n } else if ch.is_digit(10) && result.is_empty() && current.is_empty() {\n\n result.push(Identifier::AlphaNumeric(NORMAL_PRE.into()));\n\n } else if !ch.is_digit(10)\n\n && current.is_empty()\n\n && result.len() > 1\n\n && result.first() == Some(&Identifier::AlphaNumeric(NORMAL_PRE.into()))\n\n {\n\n result.remove(0);\n\n next = result.pop().unwrap().to_string();\n\n } else if !ch.is_digit(10)\n\n && !current.is_empty()\n\n && result.first() == Some(&Identifier::AlphaNumeric(NORMAL_PRE.into()))\n\n {\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 37, "score": 66537.19404232861 }, { "content": " if major_cmp != Ordering::Equal {\n\n return major_cmp;\n\n }\n\n let minor_cmp = self.minor.cmp(&other.minor);\n\n if minor_cmp != Ordering::Equal {\n\n return minor_cmp;\n\n }\n\n let patch_cmp = self.patch.unwrap_or(0).cmp(&other.patch.unwrap_or(0));\n\n if patch_cmp != Ordering::Equal {\n\n return patch_cmp;\n\n }\n\n let build_cmp = self.build.unwrap_or(0).cmp(&other.build.unwrap_or(0));\n\n if build_cmp != Ordering::Equal {\n\n return build_cmp;\n\n }\n\n\n\n self.pre_release.cmp(&other.pre_release)\n\n }\n\n}\n\n\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 38, "score": 66537.19404232861 }, { "content": " ver_str.push_str(&format!(\"-{}\", build));\n\n }\n\n build = num\n\n }\n\n }\n\n }\n\n\n\n let (delim, alt_delim) = if ver_str.contains('-') {\n\n ('.', '+')\n\n } else {\n\n ('+', '-')\n\n };\n\n\n\n if let Some(b) = choco.build {\n\n if build > 0 {\n\n ver_str.push_str(&format!(\"{}{}\", delim, build));\n\n ver_str.push_str(&format!(\"{}{}\", alt_delim, b));\n\n } else {\n\n ver_str.push_str(&format!(\"{}{}\", delim, b));\n\n }\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 39, "score": 66537.19404232861 }, { "content": "// Copyright (c) 2021 Kim J. Nordmo and WormieCorp.\n\n// Licensed under the MIT license. See LICENSE.txt file in the project\n\n\n\nuse aer_version::chocolatey::ChocoVersion;\n\nuse aer_version::{FixVersion, SemVersion};\n\n\n", "file_path": "aer_version/examples/chocolatey.rs", "rank": 40, "score": 60329.91339642843 }, { "content": " for val in VALUES.iter() {\n\n let choco = ChocoVersion::parse(val).unwrap();\n\n println!(\"{:>20} => {}\", val, choco);\n\n chocos.push(choco);\n\n }\n\n\n\n println!(\"And finally an example of creating a fix version\");\n\n\n\n let mut choco = ChocoVersion::new(4, 2);\n\n choco.add_fix().unwrap();\n\n println!(\"\\n{:>20} => {}\", \"4.2\", choco);\n\n chocos.push(choco);\n\n\n\n let mut choco = ChocoVersion::parse(\"1.0-alpha\").unwrap();\n\n choco.add_fix().unwrap();\n\n println!(\"{:>20} => {}\", \"1.0-alpha\", choco);\n\n chocos.push(choco);\n\n\n\n println!(\"And then converting all of the choco versions back to semver!\");\n\n\n\n for choco in chocos {\n\n let choco_clone = choco.clone();\n\n let semver: SemVersion = choco.into();\n\n println!(\"{:>20} => {}\", choco_clone, semver);\n\n }\n\n}\n", "file_path": "aer_version/examples/chocolatey.rs", "rank": 41, "score": 60323.54131600078 }, { "content": "fn main() {\n\n println!(\n\n \"The following are examples of converting raw strings to chocolatey compatible versions:\"\n\n );\n\n const VALUES: [&str; 11] = [\n\n \"1\",\n\n \"2.0\",\n\n \"3.1.5\",\n\n \"2.2.1.0\",\n\n \"3.0-alpha\",\n\n \"2.5-beta.34\",\n\n \"1.5-ceta-50\",\n\n \"0.8-numero-uno-5\",\n\n \"1.0.0-alpha65\",\n\n \"2.2-55\",\n\n \"1.5.2.6-alpha.22+some-metadata\",\n\n ];\n\n\n\n let mut chocos = vec![];\n\n\n", "file_path": "aer_version/examples/chocolatey.rs", "rank": 42, "score": 57606.989708350215 }, { "content": "#[derive(Copy, Clone)]\n\nstruct Colors {\n\n trace: Style,\n\n debug: Style,\n\n info: Style,\n\n warn: Style,\n\n error: Style,\n\n}\n\n\n\nimpl Colors {\n\n fn from_level(&self, level: &Level) -> &Style {\n\n match level {\n\n Level::Trace => &self.trace,\n\n Level::Debug => &self.debug,\n\n Level::Warn => &self.warn,\n\n Level::Error => &self.error,\n\n _ => &self.info,\n\n }\n\n }\n\n\n\n fn paint<T>(&self, level: &Level, value: T) -> Paint<T> {\n", "file_path": "aer/src/logging.rs", "rank": 43, "score": 56096.04938909379 }, { "content": "#[derive(StructOpt)]\n\n#[structopt(author = env!(\"CARGO_PKG_AUTHORS\"))]\n\nstruct Arguments {\n\n /// The files containing the necessary data (metadata+updater data) that\n\n /// should be used during the run.\n\n #[structopt(required = true, parse(from_os_str))]\n\n package_files: Vec<PathBuf>,\n\n\n\n #[structopt(flatten)]\n\n log: LogData,\n\n}\n\n\n", "file_path": "aer/src/main.rs", "rank": 44, "score": 56095.73120861671 }, { "content": "fn extract_prerelease(val: &str) -> Vec<Identifier> {\n\n const NORMAL_PRE: &str = \"unstable\";\n\n let mut result = vec![];\n\n let mut current = String::new();\n\n let mut next = String::new();\n\n\n\n for ch in val.chars().take_while(|ch| *ch != '+') {\n\n if ch == '-' || ch == '.' {\n\n if let Some(res) = get_identifier(&current) {\n\n current.clear();\n\n result.push(res);\n\n }\n\n if let Some(res) = get_identifier(&next) {\n\n result.push(res);\n\n next.clear();\n\n }\n\n\n\n continue;\n\n } else if ch.is_digit(10) {\n\n if result.is_empty() && current.is_empty() {\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 45, "score": 54766.70276849594 }, { "content": "fn get_identifier(value: &str) -> Option<Identifier> {\n\n if value.is_empty() {\n\n return None;\n\n }\n\n\n\n if value.chars().all(|ch| ch.is_digit(10)) {\n\n if let Ok(num) = value.parse() {\n\n return Some(Identifier::Numeric(num));\n\n }\n\n }\n\n let (mut vals, mut nums) = (String::new(), String::new());\n\n\n\n for ch in value.chars() {\n\n if ch.is_digit(10) {\n\n nums.push(ch);\n\n } else {\n\n vals.push(ch);\n\n }\n\n }\n\n\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 46, "score": 54766.70276849594 }, { "content": "/// Common trait to allow multiple response types to have the same functions to\n\n/// be used.\n\n///\n\n/// ### See also\n\n///\n\n/// The following structures implements the [WebResponse] trait.\n\n///\n\n/// - [HtmlResponse](HtmlResponse): _Responsible of parsing html sites,\n\n/// generally for aquiring links on a web page_.\n\n/// - [BinaryResponse](BinaryResponse): _Responsible for downloading a remote\n\n/// file to a specified location_\n\npub trait WebResponse {\n\n /// The response content that will be returned by any implementation of\n\n /// [WebResponse]. This can be anything that would be expected by the\n\n /// response parser.\n\n type ResponseContent;\n\n\n\n /// Returns the actual response that was created by\n\n /// [WebRequest](crate::WebRequest).\n\n fn response(&self) -> &Response;\n\n\n\n /// Returns all of the headers that was returned by the web server.\n\n /// The headers can alternatively be gotten through the\n\n /// [response](WebResponse::response) function.\n\n fn get_headers(&self) -> HashMap<&str, &str> {\n\n let response = self.response();\n\n let mut headers = HashMap::with_capacity(response.headers().len());\n\n\n\n for (key, value) in response.headers() {\n\n if let Ok(val) = value.to_str() {\n\n headers.insert(key.as_str(), val);\n", "file_path": "aer_web/src/response.rs", "rank": 47, "score": 48688.845881970854 }, { "content": "pub trait ScriptRunner {\n\n fn can_run(&self, script_path: &Path) -> bool;\n\n fn run<'a, T: RunnerCombiner + Debug>(\n\n &self,\n\n work_dir: &'a Path,\n\n script_path: PathBuf,\n\n data: &'a mut T,\n\n ) -> Result<(), String>;\n\n}\n\n\n\n#[cfg(any(feature = \"powershell\"))]\n\n#[cfg_attr(docsrs, doc(cfg(any(feature = \"powershell\"))))]\n\nmacro_rules! call_runners {\n\n ($work_dir:ident,$script_path:ident,$data:ident,$($runner:expr=>$feature:literal),+) => {\n\n let script_path = $script_path.canonicalize().unwrap();\n\n let work_dir = $work_dir.canonicalize().unwrap();\n\n $(\n\n #[cfg(feature = $feature)]\n\n if $runner.can_run(&script_path) {\n\n return $runner.run(&work_dir, script_path, $data);\n\n }\n\n )*\n\n };\n\n}\n\n\n", "file_path": "aer_upd/src/runners.rs", "rank": 48, "score": 48686.43506598599 }, { "content": "pub trait LogDataTrait {\n\n fn path(&self) -> &Path;\n\n fn level(&self) -> &LevelFilter;\n\n}\n\n\n", "file_path": "aer/src/logging.rs", "rank": 49, "score": 48686.43506598599 }, { "content": "/// Parsers implementing this trait are able to read and transform a specific\n\n/// structure to the [PackageData] type.\n\npub trait DataReader {\n\n /// Function to decide if the implemented structure can handle a certain\n\n /// file (usually by file extension).\n\n fn can_handle_file(&self, path: &Path) -> bool;\n\n\n\n /// Read and Deserialize the specified file, calling the implemented\n\n /// structure that handle the Deserialization.\n\n fn read_file(&self, path: &Path) -> Result<PackageData, errors::ParserError> {\n\n if !self.can_handle_file(path) {\n\n let error = IoError::new(\n\n ErrorKind::InvalidData,\n\n format!(\"The file '{}' is not a supported type.\", path.display()),\n\n );\n\n warn!(\"{}\", error);\n\n return Err(errors::ParserError::Loading(error));\n\n }\n\n\n\n if !path.exists() {\n\n let error = IoError::new(\n\n ErrorKind::NotFound,\n", "file_path": "aer_upd/src/parsers.rs", "rank": 50, "score": 48686.43506598599 }, { "content": "pub trait RunnerCombiner {\n\n fn to_runner_data(&self) -> RunnerData;\n\n\n\n fn from_runner_data(&mut self, data: RunnerData);\n\n}\n\n\n\nimpl RunnerCombiner for aer_data::PackageData {\n\n fn to_runner_data(&self) -> RunnerData {\n\n let mut data = RunnerData::new();\n\n\n\n {\n\n let metadata = self.metadata();\n\n data.insert(\"id\", metadata.id());\n\n data.insert(\"url\", metadata.project_url());\n\n\n\n let license = metadata.license();\n\n let mut license_child = RunnerData::new();\n\n\n\n if let Some(url) = license.license_url() {\n\n license_child.insert(\"url\", url);\n", "file_path": "aer_upd/src/runners.rs", "rank": 51, "score": 48686.43506598599 }, { "content": "fn get_val<T: num::PrimInt>(value: T, max_value: T) -> T {\n\n if value > max_value { max_value } else { value }\n\n}\n\n\n", "file_path": "aer_version/src/versions/chocolatey.rs", "rank": 52, "score": 46611.93514221651 }, { "content": "pub fn maintainer() -> Vec<String> {\n\n vec![match std::env::var(\"AER_MAINTAINER\") {\n\n Ok(maintainer) => maintainer,\n\n Err(_) => whoami::username(),\n\n }]\n\n}\n", "file_path": "aer_data/src/defaults.rs", "rank": 53, "score": 44674.842336632486 }, { "content": "#[cfg(any(feature = \"powershell\"))]\n\n#[cfg_attr(docsrs, doc(cfg(any(feature = \"powershell\"))))]\n\npub fn run_script<T: RunnerCombiner + Debug>(\n\n work_dir: &Path,\n\n script_path: PathBuf,\n\n data: &mut T,\n\n) -> Result<(), String> {\n\n if !work_dir.exists() {\n\n if let Err(err) = std::fs::create_dir_all(work_dir) {\n\n let msg = format!(\"Failed to create work directory: '{}'\", err);\n\n log::error!(\"{}\", msg);\n\n return Err(msg);\n\n }\n\n }\n\n\n\n let work_dir = &if work_dir.is_absolute() {\n\n work_dir.to_path_buf()\n\n } else {\n\n work_dir.canonicalize().unwrap()\n\n };\n\n\n\n if !work_dir.is_dir() {\n", "file_path": "aer_upd/src/runners.rs", "rank": 54, "score": 40705.811721509424 }, { "content": "// Copyright (c) 2021 Kim J. Nordmo and WormieCorp.\n\n// Licensed under the MIT license. See LICENSE.txt file in the project\n\n\n\npub mod chocolatey;\n\n\n", "file_path": "aer_version/src/versions.rs", "rank": 55, "score": 38944.18926779395 }, { "content": "#[cfg(any(feature = \"toml_data\"))]\n\n#[cfg_attr(docsrs, doc(cfg(any(feature = \"toml_data\"))))]\n\npub fn read_file(path: &Path) -> Result<PackageData, errors::ParserError> {\n\n call_parsers!(path, toml::TomlParser => \"toml_data\");\n\n\n\n Err(errors::ParserError::NoParsers(path.to_owned()))\n\n}\n", "file_path": "aer_upd/src/parsers.rs", "rank": 56, "score": 35010.886483649636 }, { "content": "fn parse_version(captures: Captures<'_>) -> Option<Versions> {\n\n Versions::parse(captures.name(\"version\")?.as_str()).ok()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::collections::HashMap;\n\n\n\n use super::*;\n\n use crate::WebRequest;\n\n\n\n #[test]\n\n fn read_should_get_links_from_page() {\n\n let request = WebRequest::create();\n\n let url = Url::parse(\"https://httpbin.org/links/4/1\").unwrap();\n\n let response = request.get_html_response(url.as_ref()).unwrap();\n\n\n\n let (parent, links) = response.read(None).unwrap();\n\n\n\n assert_eq!(parent, LinkElement::new(url, LinkType::Html));\n", "file_path": "aer_web/src/response/html.rs", "rank": 57, "score": 32121.92392683853 }, { "content": "pub fn setup_logging<T: LogDataTrait>(log: &T) -> Result<(), Box<dyn std::error::Error>> {\n\n let colors = Colors::default();\n\n\n\n let cli_dispatch = configure_cli_dispatch(colors, log);\n\n\n\n if log.path().exists() {\n\n let _ = std::fs::remove_file(log.path());\n\n }\n\n\n\n let mut file_log = fern::Dispatch::new()\n\n .format(move |out, message, record| {\n\n out.finish(format_args!(\n\n \"[{}] {} T[{:?}] [{}] {}:{}: {}\",\n\n chrono::Local::now().format(\"%Y-%m-%d %H:%M:%S%.6f %:z\"),\n\n record.level(),\n\n std::thread::current().name().unwrap_or(\"<unnamed>\"),\n\n record.module_path().unwrap_or(\"<unnamed>\"),\n\n record.file().unwrap_or(\"<unnamed>\"),\n\n record.line().unwrap_or(0),\n\n Paint::wrapping(message).wrap()\n", "file_path": "aer/src/logging.rs", "rank": 58, "score": 30698.448843288497 }, { "content": "// Copyright (c) 2021 Kim J. Nordmo and WormieCorp.\n\n// Licensed under the MIT license. See LICENSE.txt file in the project\n\n#![cfg_attr(docsrs, feature(doc_cfg))]\n\n\n\nmod versions;\n\n\n\nuse std::error::Error;\n\nuse std::fmt::Display;\n\n\n\npub use semver::Version as SemVersion;\n\n#[cfg(feature = \"serialize\")]\n\nuse serde::{Deserialize, Serialize};\n\n#[cfg(feature = \"chocolatey\")]\n\npub use versions::chocolatey;\n\npub use versions::FixVersion;\n\n\n\n#[cfg_attr(feature = \"serialize\", derive(Deserialize, Serialize), serde(untagged))]\n\n#[derive(Debug, Clone, PartialEq)]\n\npub enum Versions {\n\n SemVer(SemVersion),\n", "file_path": "aer_version/src/lib.rs", "rank": 59, "score": 30242.050669990575 }, { "content": "\n\n #[cfg(feature = \"chocolatey\")]\n\n #[cfg_attr(docsrs, doc(cfg(feature = \"chocolatey\")))]\n\n pub fn to_choco(&self) -> chocolatey::ChocoVersion {\n\n match self {\n\n Versions::SemVer(semver) => chocolatey::ChocoVersion::from(semver.clone()),\n\n Versions::Choco(ver) => ver.clone(),\n\n }\n\n }\n\n\n\n pub fn to_semver(&self) -> SemVersion {\n\n match self {\n\n Versions::SemVer(semver) => semver.clone(),\n\n #[cfg(feature = \"chocolatey\")]\n\n #[cfg_attr(docsrs, doc(cfg(feature = \"chocolatey\")))]\n\n Versions::Choco(ver) => SemVersion::from(ver.clone()),\n\n }\n\n }\n\n}\n\n\n", "file_path": "aer_version/src/lib.rs", "rank": 60, "score": 30236.122599816208 }, { "content": "impl Display for Versions {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {\n\n match self {\n\n Versions::SemVer(version) => version.fmt(f),\n\n #[cfg(feature = \"chocolatey\")]\n\n Versions::Choco(version) => version.fmt(f),\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use rstest::rstest;\n\n\n\n use super::*;\n\n\n\n #[test]\n\n #[cfg(feature = \"chocolatey\")]\n\n fn parse_should_use_chocolatey_version_on_4_part_versions() {\n\n let expected = Versions::Choco(chocolatey::ChocoVersion::with_build(5, 1, 6, 4));\n", "file_path": "aer_version/src/lib.rs", "rank": 61, "score": 30231.703779415097 }, { "content": " #[cfg(feature = \"chocolatey\")]\n\n #[cfg_attr(docsrs, doc(cfg(feature = \"chocolatey\")))]\n\n Choco(chocolatey::ChocoVersion),\n\n}\n\n\n\n/// An error type for this crate\n\n///\n\n/// Currently, just a generic error.\n\n#[derive(Clone, PartialEq, Debug, PartialOrd)]\n\npub enum SemanticVersionError {\n\n /// An error occurred while parsing.\n\n ParseError(String),\n\n}\n\n\n\nimpl Display for SemanticVersionError {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {\n\n match self {\n\n SemanticVersionError::ParseError(ref m) => write!(f, \"{}\", m),\n\n }\n\n }\n", "file_path": "aer_version/src/lib.rs", "rank": 62, "score": 30230.817416463567 }, { "content": " let actual = version.to_semver();\n\n\n\n assert_eq!(actual, expected);\n\n }\n\n\n\n #[test]\n\n #[cfg(feature = \"chocolatey\")]\n\n fn to_choco_should_create_chocolatey_version_from_semver() {\n\n let version = Versions::SemVer(SemVersion::parse(\"1.0.5-beta.55+99\").unwrap());\n\n let expected = chocolatey::ChocoVersion::parse(\"1.0.5-beta0055\").unwrap();\n\n\n\n let actual = version.to_choco();\n\n\n\n assert_eq!(actual, expected);\n\n }\n\n\n\n #[test]\n\n #[cfg(feature = \"chocolatey\")]\n\n fn to_choco_should_returned_cloned_version_of_choco() {\n\n let version =\n", "file_path": "aer_version/src/lib.rs", "rank": 63, "score": 30230.635803680536 }, { "content": " let version = Versions::parse(\"5.1.6.4\").unwrap();\n\n\n\n assert_eq!(version, expected);\n\n }\n\n\n\n #[test]\n\n fn parse_should_use_semver_version_on_3_part_versions() {\n\n let expected = Versions::SemVer(SemVersion::new(5, 1, 0));\n\n let version = Versions::parse(\"5.1.0\").unwrap();\n\n\n\n assert_eq!(version, expected);\n\n }\n\n\n\n #[test]\n\n #[cfg_attr(\n\n feature = \"chocolatey\",\n\n should_panic(expected = \"The version string do not start with a number\")\n\n )]\n\n #[cfg_attr(\n\n not(feature = \"chocolatey\"),\n", "file_path": "aer_version/src/lib.rs", "rank": 64, "score": 30230.145610276933 }, { "content": "}\n\n\n\nimpl Error for SemanticVersionError {}\n\n\n\nimpl Versions {\n\n pub fn parse(val: &str) -> Result<Versions, Box<dyn std::error::Error>> {\n\n #[cfg(not(feature = \"chocolatey\"))]\n\n {\n\n Ok(Versions::SemVer(SemVersion::parse(val)?))\n\n }\n\n #[cfg(feature = \"chocolatey\")]\n\n {\n\n if let Ok(semver) = SemVersion::parse(val) {\n\n Ok(Versions::SemVer(semver))\n\n } else {\n\n let val = chocolatey::ChocoVersion::parse(val)?;\n\n Ok(Versions::Choco(val))\n\n }\n\n }\n\n }\n", "file_path": "aer_version/src/lib.rs", "rank": 65, "score": 30229.96427859686 }, { "content": " Versions::parse(\"2.0.2.5.1\").unwrap();\n\n }\n\n\n\n #[test]\n\n #[cfg(feature = \"chocolatey\")]\n\n fn to_semver_should_create_semversion_from_choco_version() {\n\n let version =\n\n Versions::Choco(chocolatey::ChocoVersion::parse(\"2.1.0.5-alpha0055\").unwrap());\n\n let expected = SemVersion::parse(\"2.1.0-alpha.55+5\").unwrap();\n\n\n\n let actual = version.to_semver();\n\n\n\n assert_eq!(actual, expected);\n\n }\n\n\n\n #[test]\n\n fn to_semver_should_return_cloned_version_of_semver() {\n\n let version = Versions::SemVer(SemVersion::parse(\"5.2.2-alpha.5+55\").unwrap());\n\n let expected = SemVersion::parse(\"5.2.2-alpha.5+55\").unwrap();\n\n\n", "file_path": "aer_version/src/lib.rs", "rank": 66, "score": 30228.641587289792 }, { "content": " #[rstest]\n\n #[case(\"4.2.1-alpha.5+6\", \"4.2.1-alpha.5+6\")]\n\n #[cfg_attr(feature = \"chocolatey\", case(\"3.2\", \"3.2\"))]\n\n #[cfg_attr(feature = \"chocolatey\", case(\"5.2.1.6-beta-0005\", \"5.2.1.6-beta0005\"))]\n\n fn display_version(#[case] test: &str, #[case] expected: &str) {\n\n let version = Versions::parse(test).unwrap();\n\n\n\n assert_eq!(version.to_string(), expected);\n\n }\n\n}\n", "file_path": "aer_version/src/lib.rs", "rank": 67, "score": 30227.84795833775 }, { "content": " Versions::Choco(chocolatey::ChocoVersion::parse(\"5.2.1.56-unstable-0050\").unwrap());\n\n let expected = chocolatey::ChocoVersion::parse(\"5.2.1.56-unstable0050\").unwrap();\n\n\n\n let actual = version.to_choco();\n\n\n\n assert_eq!(actual, expected);\n\n }\n\n\n\n #[test]\n\n #[cfg(feature = \"chocolatey\")]\n\n fn display_choco_version() {\n\n let version =\n\n Versions::Choco(chocolatey::ChocoVersion::parse(\"2.1.0-unstable-0050\").unwrap());\n\n let expected = \"2.1.0-unstable0050\";\n\n\n\n let actual = version.to_string();\n\n\n\n assert_eq!(actual, expected);\n\n }\n\n\n", "file_path": "aer_version/src/lib.rs", "rank": 68, "score": 30227.545686081576 }, { "content": " should_panic(expected = \"encountered unexpected token: AlphaNumeric\")\n\n )]\n\n fn parse_should_return_error_on_invalid_version() {\n\n Versions::parse(\"invalid\").unwrap();\n\n }\n\n\n\n #[test]\n\n #[cfg_attr(\n\n feature = \"chocolatey\",\n\n should_panic(\n\n expected = \"There were additional numeric characters after the first 4 parts of the \\\n\n version\"\n\n )\n\n )]\n\n #[cfg_attr(\n\n not(feature = \"chocolatey\"),\n\n should_panic(expected = \"expected end of input, but got:\")\n\n )]\n\n fn parse_should_return_error_on_5_part_version() {\n\n // This may be valid at a later date, if/when python support is added\n", "file_path": "aer_version/src/lib.rs", "rank": 69, "score": 30226.81688748625 }, { "content": "// Copyright (c) 2021 Kim J. Nordmo and WormieCorp.\n\n// Licensed under the MIT license. See LICENSE.txt file in the project\n\n\n\n#![cfg_attr(docsrs, doc(cfg(feature = \"chocolatey\")))]\n\n\n\nuse std::collections::HashMap;\n\n\n\n#[cfg(feature = \"serialize\")]\n\nuse serde::{Deserialize, Serialize};\n\nuse url::Url;\n\n\n\n#[derive(Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize\", derive(Deserialize, Serialize))]\n\npub enum ChocolateyUpdaterType {\n\n None,\n\n Installer,\n\n Archive,\n\n}\n\n\n\nimpl Default for ChocolateyUpdaterType {\n", "file_path": "aer_data/src/updater/chocolatey.rs", "rank": 71, "score": 28767.828966289446 }, { "content": " fn default() -> Self {\n\n Self::None\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize\", derive(Deserialize, Serialize), serde(untagged))]\n\npub enum ChocolateyParseUrl {\n\n UrlWithRegex { url: Url, regex: String },\n\n Url(Url),\n\n}\n\n\n\n#[derive(Debug, Default, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize\", derive(Deserialize, Serialize))]\n\n#[non_exhaustive]\n\npub struct ChocolateyUpdaterData {\n\n #[cfg_attr(feature = \"serialize\", serde(default))]\n\n pub embedded: bool,\n\n #[cfg_attr(feature = \"serialize\", serde(default, rename = \"type\"))]\n\n pub updater_type: ChocolateyUpdaterType,\n", "file_path": "aer_data/src/updater/chocolatey.rs", "rank": 72, "score": 28766.812199037304 }, { "content": " pub parse_url: Option<ChocolateyParseUrl>,\n\n\n\n regexes: HashMap<String, String>,\n\n}\n\n\n\nimpl ChocolateyUpdaterData {\n\n pub fn new() -> ChocolateyUpdaterData {\n\n ChocolateyUpdaterData {\n\n embedded: false,\n\n updater_type: ChocolateyUpdaterType::default(),\n\n parse_url: None,\n\n regexes: HashMap::new(),\n\n }\n\n }\n\n\n\n pub fn regexes(&self) -> &HashMap<String, String> {\n\n &self.regexes\n\n }\n\n\n\n pub fn add_regex(&mut self, name: &str, value: &str) {\n", "file_path": "aer_data/src/updater/chocolatey.rs", "rank": 80, "score": 28755.419105200115 }, { "content": " self.regexes.insert(name.into(), value.into());\n\n }\n\n\n\n pub fn set_regexes(&mut self, values: HashMap<String, String>) {\n\n self.regexes = values;\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn new_should_create_data_with_expected_values() {\n\n let expected = ChocolateyUpdaterData {\n\n embedded: false,\n\n updater_type: ChocolateyUpdaterType::default(),\n\n parse_url: None,\n\n regexes: HashMap::new(),\n\n };\n", "file_path": "aer_data/src/updater/chocolatey.rs", "rank": 81, "score": 28755.171994171 }, { "content": "\n\n let actual = ChocolateyUpdaterData::new();\n\n\n\n assert_eq!(actual, expected);\n\n }\n\n\n\n #[test]\n\n fn set_regexes_should_set_expected_values() {\n\n let mut expected = HashMap::new();\n\n expected.insert(\"arch32\".to_string(), \"test-regex-1\".to_string());\n\n expected.insert(\"arch64\".to_string(), \"test-regex-2\".to_string());\n\n\n\n let mut data = ChocolateyUpdaterData::new();\n\n data.set_regexes(expected.clone());\n\n\n\n assert_eq!(data.regexes(), &expected);\n\n }\n\n\n\n #[test]\n\n fn add_regex_should_include_new_regex() {\n", "file_path": "aer_data/src/updater/chocolatey.rs", "rank": 88, "score": 28752.592016724542 }, { "content": " let mut expected = HashMap::new();\n\n expected.insert(\"some\".to_string(), \"test-addition-regex\".to_string());\n\n\n\n let mut data = ChocolateyUpdaterData::new();\n\n data.add_regex(\"some\", \"test-addition-regex\");\n\n\n\n assert_eq!(data.regexes(), &expected);\n\n }\n\n}\n", "file_path": "aer_data/src/updater/chocolatey.rs", "rank": 92, "score": 28750.21015117678 }, { "content": "#[test]\n\nfn testing_multiple_versions() -> Result<(), Box<dyn std::error::Error>> {\n\n let mut cmd = Command::cargo_bin(\"aer-ver\")?;\n\n let log_path = LOG_DIR.join(\"aer-ver-tests-multiple.log\");\n\n\n\n cmd.args(&[\"3.2.1\", \"5.2-alpha.5\", \"--log\", log_path.to_str().unwrap()])\n\n .env(\"NO_COLOR\", \"true\");\n\n\n\n cmd.assert().success().stdout(predicate::eq(\n\n \"Checking 2 versions...\n\n\n\n Raw Version : 3.2.1\n\n\n\n Chocolatey : 3.2.1\n\n SemVer from Choco : 3.2.1\n\n\n\n SemVer : 3.2.1\n\n Choco from SemVer : 3.2.1\n\n\n\n Raw Version : 5.2-alpha.5\n\n\n", "file_path": "aer/tests/aer-ver.rs", "rank": 93, "score": 21230.657680352153 }, { "content": "#[test]\n\nfn testing_single_item_with_invalid_versions() -> Result<(), Box<dyn std::error::Error>> {\n\n let mut cmd = Command::cargo_bin(\"aer-ver\")?;\n\n let log_path = LOG_DIR.join(\"aer-ver-tests-parse-single-invalid.log\");\n\n\n\n cmd.args(&[\"invalid-ver\", \"--log\", log_path.to_str().unwrap()])\n\n .env(\"NO_COLOR\", \"true\");\n\n\n\n cmd.assert().success().stdout(predicate::eq(\n\n \"Checking 1 version...\n\n\n\n Raw Version : invalid-ver\n\n\n\n Chocolatey : None\n\n SemVer from Choco : None\n\n\n\n SemVer : None\n\n Choco from SemVer : None\n\n\",\n\n ));\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "aer/tests/aer-ver.rs", "rank": 94, "score": 19914.583119819985 }, { "content": "#[test]\n\nfn testing_single_item_with_valid_version() -> Result<(), Box<dyn std::error::Error>> {\n\n let mut cmd = Command::cargo_bin(\"aer-ver\")?;\n\n let log_path = LOG_DIR.join(\"aer-ver-tests-parse-single-valid.log\");\n\n\n\n cmd.args(&[\"4.5.1\", \"--log\", log_path.to_str().unwrap()])\n\n .env(\"NO_COLOR\", \"true\");\n\n\n\n cmd.assert().success().stdout(predicate::eq(\n\n \"Checking 1 version...\n\n\n\n Raw Version : 4.5.1\n\n\n\n Chocolatey : 4.5.1\n\n SemVer from Choco : 4.5.1\n\n\n\n SemVer : 4.5.1\n\n Choco from SemVer : 4.5.1\n\n\",\n\n ));\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "aer/tests/aer-ver.rs", "rank": 95, "score": 19914.583119819985 }, { "content": "// Copyright (c) 2021 Kim J. Nordmo and WormieCorp.\n\n// Licensed under the MIT license. See LICENSE.txt file in the project\n\n\n\n#[cfg(feature = \"chocolatey\")]\n\npub mod chocolatey;\n\n\n\nuse std::borrow::Cow;\n\nuse std::fmt::Display;\n\nuse std::path::PathBuf;\n\n\n\nuse aer_license::LicenseType;\n\n#[cfg(feature = \"serialize\")]\n\nuse serde::{Deserialize, Serialize};\n\nuse url::Url;\n\n\n\n#[derive(Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serialize\", derive(Deserialize, Serialize), serde(untagged))]\n\npub enum Description {\n\n None,\n\n Location {\n", "file_path": "aer_data/src/metadata.rs", "rank": 96, "score": 20.663286821761787 }, { "content": "// Copyright (c) 2021 Kim J. Nordmo and WormieCorp.\n\n// Licensed under the MIT license. See LICENSE.txt file in the project\n\n\n\npub use aer_license::LicenseType;\n\npub use aer_version::{FixVersion, SemVersion, Versions};\n\npub use url::Url;\n\n\n\npub use crate::metadata::{Description, PackageMetadata};\n\npub use crate::updater::PackageUpdateData;\n\npub use crate::PackageData;\n\n\n\n/// Re-Exports of usable chocolatey types.\n\n#[cfg(feature = \"chocolatey\")]\n\n#[cfg_attr(docsrs, doc(cfg(feature = \"chocolatey\")))]\n\npub mod chocolatey {\n\n pub use aer_version::chocolatey::ChocoVersion;\n\n\n\n pub use crate::metadata::chocolatey::ChocolateyMetadata;\n\n pub use crate::updater::chocolatey::{\n\n ChocolateyParseUrl, ChocolateyUpdaterData, ChocolateyUpdaterType,\n\n };\n\n}\n", "file_path": "aer_data/src/prelude.rs", "rank": 97, "score": 20.429871841518008 }, { "content": "// Copyright (c) 2021 Kim J. Nordmo and WormieCorp.\n\n// Licensed under the MIT license. See LICENSE.txt file in the project\n\n\n\npub mod chocolatey;\n\n\n\nuse std::borrow::Cow;\n\n\n\n#[cfg(feature = \"serialize\")]\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[derive(Debug, Default, PartialEq)]\n\n#[cfg_attr(feature = \"serialize\", derive(Deserialize, Serialize))]\n\n#[non_exhaustive]\n\npub struct PackageUpdateData {\n\n #[cfg(feature = \"chocolatey\")]\n\n #[cfg_attr(docsrs, doc(cfg(feature = \"chocolatey\")))]\n\n chocolatey: Option<chocolatey::ChocolateyUpdaterData>,\n\n}\n\n\n\nimpl PackageUpdateData {\n", "file_path": "aer_data/src/updater.rs", "rank": 98, "score": 19.164098342478802 }, { "content": "// Copyright (c) 2021 Kim J. Nordmo and WormieCorp.\n\n// Licensed under the MIT license. See LICENSE.txt file in the project\n\n\n\n#[cfg(feature = \"chocolatey\")]\n\nuse aer_version::{SemVersion, Versions};\n\n\n\n#[cfg(feature = \"chocolatey\")]\n", "file_path": "aer_data/src/defaults.rs", "rank": 99, "score": 17.153994571359917 } ]
Rust
src/librustdoc/html/highlight.rs
Kroisse/rust
5716abe3f019ab7d9c8cdde9879332040191cf88
use std::str; use std::io; use syntax::parse; use syntax::parse::lexer; use syntax::codemap::{BytePos, Span}; use html::escape::Escape; use t = syntax::parse::token; pub fn highlight(src: &str, class: Option<&str>, id: Option<&str>) -> String { debug!("highlighting: ================\n{}\n==============", src); let sess = parse::new_parse_sess(); let fm = parse::string_to_filemap(&sess, src.to_string(), "<stdin>".to_string()); let mut out = io::MemWriter::new(); doit(&sess, lexer::StringReader::new(&sess.span_diagnostic, fm), class, id, &mut out).unwrap(); str::from_utf8_lossy(out.unwrap().as_slice()).to_string() } fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader, class: Option<&str>, id: Option<&str>, out: &mut Writer) -> io::IoResult<()> { use syntax::parse::lexer::Reader; try!(write!(out, "<pre ")); match id { Some(id) => try!(write!(out, "id='{}' ", id)), None => {} } try!(write!(out, "class='rust {}'>\n", class.unwrap_or(""))); let mut last = BytePos(0); let mut is_attribute = false; let mut is_macro = false; let mut is_macro_nonterminal = false; loop { let next = lexer.next_token(); let test = if next.tok == t::EOF {lexer.pos} else {next.sp.lo}; if test > last { let snip = sess.span_diagnostic.cm.span_to_snippet(Span { lo: last, hi: test, expn_info: None, }).unwrap(); if snip.as_slice().contains("/") { try!(write!(out, "<span class='comment'>{}</span>", Escape(snip.as_slice()))); } else { try!(write!(out, "{}", Escape(snip.as_slice()))); } } last = next.sp.hi; if next.tok == t::EOF { break } let klass = match next.tok { t::BINOP(t::AND) if lexer.peek().sp.lo == next.sp.hi => "kw-2", t::AT | t::TILDE => "kw-2", t::NOT if is_macro => { is_macro = false; "macro" } t::EQ | t::LT | t::LE | t::EQEQ | t::NE | t::GE | t::GT | t::ANDAND | t::OROR | t::NOT | t::BINOP(..) | t::RARROW | t::BINOPEQ(..) | t::FAT_ARROW => "op", t::DOT | t::DOTDOT | t::DOTDOTDOT | t::COMMA | t::SEMI | t::COLON | t::MOD_SEP | t::LARROW | t::LPAREN | t::RPAREN | t::LBRACKET | t::LBRACE | t::RBRACE | t::QUESTION => "", t::DOLLAR => { if t::is_ident(&lexer.peek().tok) { is_macro_nonterminal = true; "macro-nonterminal" } else { "" } } t::POUND => { is_attribute = true; try!(write!(out, r"<span class='attribute'>#")); continue } t::RBRACKET => { if is_attribute { is_attribute = false; try!(write!(out, "]</span>")); continue } else { "" } } t::LIT_BYTE(..) | t::LIT_BINARY(..) | t::LIT_BINARY_RAW(..) | t::LIT_CHAR(..) | t::LIT_STR(..) | t::LIT_STR_RAW(..) => "string", t::LIT_INT(..) | t::LIT_UINT(..) | t::LIT_INT_UNSUFFIXED(..) | t::LIT_FLOAT(..) | t::LIT_FLOAT_UNSUFFIXED(..) => "number", t::IDENT(ident, _is_mod_sep) => { match t::get_ident(ident).get() { "ref" | "mut" => "kw-2", "self" => "self", "false" | "true" => "boolval", "Option" | "Result" => "prelude-ty", "Some" | "None" | "Ok" | "Err" => "prelude-val", _ if t::is_any_keyword(&next.tok) => "kw", _ => { if is_macro_nonterminal { is_macro_nonterminal = false; "macro-nonterminal" } else if lexer.peek().tok == t::NOT { is_macro = true; "macro" } else { "ident" } } } } t::LIFETIME(..) => "lifetime", t::DOC_COMMENT(..) => "doccomment", t::UNDERSCORE | t::EOF | t::INTERPOLATED(..) => "", }; let snip = sess.span_diagnostic.cm.span_to_snippet(next.sp).unwrap(); if klass == "" { try!(write!(out, "{}", Escape(snip.as_slice()))); } else { try!(write!(out, "<span class='{}'>{}</span>", klass, Escape(snip.as_slice()))); } } write!(out, "</pre>\n") }
use std::str; use std::io; use syntax::parse; use syntax::parse::lexer; use syntax::codemap::{BytePos, Span}; use html::escape::Escape; use t = syntax::parse::token; pub fn highlight(src: &str, class: Option<&str>, id: Option<&str>) -> String { debug!("highlighting: ================\n{}\n==============", src); let sess = parse::new_parse_sess(); let fm = parse::string_to_filemap(&sess, src.to_string(), "<stdin>".to_string()); let mut out = io::MemWriter::new(); doit(&sess, lexer::StringReader::new(&sess.span_diagnostic, fm), class, id, &mut out).unwrap(); str::from_utf8_lossy(out.unwrap().as_slice()).to_string() } fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader, class: Option<&str>, id: Option<&str>, out: &mut Writer) -> io::IoResult<()> { use syntax::parse::lexer::Reader; try!(write!(out, "<pre ")); match id { Some(id) => try!(write!(out, "id='{}' ", id)), None => {} } try!(write!(out, "class='rust {}'>\n", class.unwrap_or(""))); let mut last = BytePos(0); let mut is_attribute = false; let mut is_macro = false; let mut is_macro_nonterminal = false; loop { let next = lexer.next_token(); let test = if next.tok == t::EOF {lexer.pos} else {next.sp.lo}; if test > last { let snip = sess.span_diagnostic.cm.span_to_snippet(Span { lo: last, hi: test, expn_info: None, }).unwrap(); if snip.as_slice().contains("/") { try!(write!(out, "<span class='comment'>{}</span>", Escape(snip.as_slice()))); } else { try!(write!(out, "{}", Escape(snip.as_slice()))); } } last = next.sp.hi; if next.tok == t::EOF { break } let klass = match next.tok { t::BINOP(t::AND) if lexer.peek().sp.lo == next.sp.hi => "kw-2", t::AT | t::TILDE => "kw-
2", t::NOT if is_macro => { is_macro = false; "macro" } t::EQ | t::LT | t::LE | t::EQEQ | t::NE | t::GE | t::GT | t::ANDAND | t::OROR | t::NOT | t::BINOP(..) | t::RARROW | t::BINOPEQ(..) | t::FAT_ARROW => "op", t::DOT | t::DOTDOT | t::DOTDOTDOT | t::COMMA | t::SEMI | t::COLON | t::MOD_SEP | t::LARROW | t::LPAREN | t::RPAREN | t::LBRACKET | t::LBRACE | t::RBRACE | t::QUESTION => "", t::DOLLAR => { if t::is_ident(&lexer.peek().tok) { is_macro_nonterminal = true; "macro-nonterminal" } else { "" } } t::POUND => { is_attribute = true; try!(write!(out, r"<span class='attribute'>#")); continue } t::RBRACKET => { if is_attribute { is_attribute = false; try!(write!(out, "]</span>")); continue } else { "" } } t::LIT_BYTE(..) | t::LIT_BINARY(..) | t::LIT_BINARY_RAW(..) | t::LIT_CHAR(..) | t::LIT_STR(..) | t::LIT_STR_RAW(..) => "string", t::LIT_INT(..) | t::LIT_UINT(..) | t::LIT_INT_UNSUFFIXED(..) | t::LIT_FLOAT(..) | t::LIT_FLOAT_UNSUFFIXED(..) => "number", t::IDENT(ident, _is_mod_sep) => { match t::get_ident(ident).get() { "ref" | "mut" => "kw-2", "self" => "self", "false" | "true" => "boolval", "Option" | "Result" => "prelude-ty", "Some" | "None" | "Ok" | "Err" => "prelude-val", _ if t::is_any_keyword(&next.tok) => "kw", _ => { if is_macro_nonterminal { is_macro_nonterminal = false; "macro-nonterminal" } else if lexer.peek().tok == t::NOT { is_macro = true; "macro" } else { "ident" } } } } t::LIFETIME(..) => "lifetime", t::DOC_COMMENT(..) => "doccomment", t::UNDERSCORE | t::EOF | t::INTERPOLATED(..) => "", }; let snip = sess.span_diagnostic.cm.span_to_snippet(next.sp).unwrap(); if klass == "" { try!(write!(out, "{}", Escape(snip.as_slice()))); } else { try!(write!(out, "<span class='{}'>{}</span>", klass, Escape(snip.as_slice()))); } } write!(out, "</pre>\n") }
function_block-function_prefixed
[ { "content": "pub fn main() { loop { int_id(break); } }\n", "file_path": "src/test/run-pass/break-value.rs", "rank": 1, "score": 533837.206130467 }, { "content": "/// Run any tests/code examples in the markdown file `input`.\n\npub fn test(input: &str, libs: HashSet<Path>, mut test_args: Vec<String>) -> int {\n\n let input_str = load_or_return!(input, 1, 2);\n\n\n\n let mut collector = Collector::new(input.to_string(), libs, true);\n\n find_testable_code(input_str.as_slice(), &mut collector);\n\n test_args.unshift(\"rustdoctest\".to_string());\n\n testing::test_main(test_args.as_slice(), collector.tests);\n\n 0\n\n}\n", "file_path": "src/librustdoc/markdown.rs", "rank": 2, "score": 521825.2148057672 }, { "content": "pub fn main() { let mut n; n = 1i; println!(\"{}\", n); }\n", "file_path": "src/test/run-pass/simple-infer.rs", "rank": 3, "score": 502757.09762303624 }, { "content": "pub fn main() { let _x = some(\"hi\".to_string()); }\n", "file_path": "src/test/run-pass/generic-tag-corruption.rs", "rank": 4, "score": 498839.8822640007 }, { "content": "pub fn hi_str() -> String {\n\n \"Hi!\".to_string()\n\n}\n\n\n", "file_path": "src/test/compile-fail/circular_modules_main.rs", "rank": 5, "score": 490412.88217631483 }, { "content": "pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {\n\n Span {lo: lo, hi: hi, expn_info: None}\n\n}\n\n\n", "file_path": "src/libsyntax/codemap.rs", "rank": 6, "score": 487608.97629949846 }, { "content": "pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) {\n\n extern fn block(_ob: *mut hoedown_buffer,\n\n text: *const hoedown_buffer,\n\n lang: *const hoedown_buffer,\n\n opaque: *mut libc::c_void) {\n\n unsafe {\n\n if text.is_null() { return }\n\n let block_info = if lang.is_null() {\n\n LangString::all_false()\n\n } else {\n\n slice::raw::buf_as_slice((*lang).data,\n\n (*lang).size as uint, |lang| {\n\n let s = str::from_utf8(lang).unwrap();\n\n LangString::parse(s)\n\n })\n\n };\n\n if block_info.notrust { return }\n\n slice::raw::buf_as_slice((*text).data, (*text).size as uint, |text| {\n\n let opaque = opaque as *mut hoedown_html_renderer_state;\n\n let tests = &mut *((*opaque).opaque as *mut ::test::Collector);\n", "file_path": "src/librustdoc/html/markdown.rs", "rank": 7, "score": 484661.12894267053 }, { "content": "pub fn opt_str1<'a>(maybestr: &'a Option<String>) -> &'a str {\n\n match *maybestr {\n\n None => \"(none)\",\n\n Some(ref s) => {\n\n let s: &'a str = s.as_slice();\n\n s\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/test/compile-fail/lub-match.rs", "rank": 9, "score": 476170.3145121926 }, { "content": "pub fn opt_str0<'a>(maybestr: &'a Option<String>) -> &'a str {\n\n match *maybestr {\n\n Some(ref s) => {\n\n let s: &'a str = s.as_slice();\n\n s\n\n }\n\n None => \"(none)\",\n\n }\n\n}\n\n\n", "file_path": "src/test/compile-fail/lub-match.rs", "rank": 10, "score": 476170.31451219274 }, { "content": "fn test_break() { loop { let _x: Gc<int> = break; } }\n\n\n", "file_path": "src/test/run-pass/terminate-in-initializer.rs", "rank": 11, "score": 474924.2975802292 }, { "content": "/// Fetches the environment variable `n` from the current process, returning\n\n/// None if the variable isn't set.\n\n///\n\n/// Any invalid UTF-8 bytes in the value are replaced by \\uFFFD. See\n\n/// `str::from_utf8_lossy()` for details.\n\n///\n\n/// # Failure\n\n///\n\n/// Fails if `n` has any interior NULs.\n\n///\n\n/// # Example\n\n///\n\n/// ```rust\n\n/// use std::os;\n\n///\n\n/// let key = \"HOME\";\n\n/// match os::getenv(key) {\n\n/// Some(val) => println!(\"{}: {}\", key, val),\n\n/// None => println!(\"{} is not defined in the environment.\", key)\n\n/// }\n\n/// ```\n\npub fn getenv(n: &str) -> Option<String> {\n\n getenv_as_bytes(n).map(|v| String::from_str(str::from_utf8_lossy(v.as_slice()).as_slice()))\n\n}\n\n\n\n#[cfg(unix)]\n", "file_path": "src/libstd/os.rs", "rank": 12, "score": 472975.37378679716 }, { "content": "pub fn opt_str2<'a>(maybestr: &'a Option<String>) -> &'static str {\n\n match *maybestr { //~ ERROR mismatched types\n\n None => \"(none)\",\n\n Some(ref s) => {\n\n let s: &'a str = s.as_slice();\n\n s\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/test/compile-fail/lub-match.rs", "rank": 13, "score": 469173.1907195663 }, { "content": "pub fn opt_str3<'a>(maybestr: &'a Option<String>) -> &'static str {\n\n match *maybestr { //~ ERROR mismatched types\n\n Some(ref s) => {\n\n let s: &'a str = s.as_slice();\n\n s\n\n }\n\n None => \"(none)\",\n\n }\n\n}\n\n\n", "file_path": "src/test/compile-fail/lub-match.rs", "rank": 14, "score": 469173.1907195663 }, { "content": "pub fn main() { let x = (); match x { () => { } } }\n", "file_path": "src/test/run-pass/nil-pattern.rs", "rank": 15, "score": 466871.0245214257 }, { "content": "pub fn strip_doc_comment_decoration(comment: &str) -> String {\n\n /// remove whitespace-only lines from the start/end of lines\n\n fn vertical_trim(lines: Vec<String> ) -> Vec<String> {\n\n let mut i = 0u;\n\n let mut j = lines.len();\n\n // first line of all-stars should be omitted\n\n if lines.len() > 0 &&\n\n lines.get(0).as_slice().chars().all(|c| c == '*') {\n\n i += 1;\n\n }\n\n while i < j && lines.get(i).as_slice().trim().is_empty() {\n\n i += 1;\n\n }\n\n // like the first, a last line of all stars should be omitted\n\n if j > i && lines.get(j - 1)\n\n .as_slice()\n\n .chars()\n\n .skip(1)\n\n .all(|c| c == '*') {\n\n j -= 1;\n", "file_path": "src/libsyntax/parse/lexer/comments.rs", "rank": 16, "score": 459662.7583735973 }, { "content": "fn f2(ref_string: &str) -> String {\n\n match ref_string {\n\n \"a\" => \"found a\".to_string(),\n\n \"b\" => \"found b\".to_string(),\n\n s => format!(\"not found ({})\", s)\n\n }\n\n}\n\n\n", "file_path": "src/test/run-pass/match-borrowed_str.rs", "rank": 17, "score": 456902.9236708946 }, { "content": "fn f1(ref_string: &str) -> String {\n\n match ref_string {\n\n \"a\" => \"found a\".to_string(),\n\n \"b\" => \"found b\".to_string(),\n\n _ => \"not found\".to_string()\n\n }\n\n}\n\n\n", "file_path": "src/test/run-pass/match-borrowed_str.rs", "rank": 18, "score": 456902.9236708946 }, { "content": "#[cfg(stage0)]\n\npub fn to_str(f: |&mut State| -> IoResult<()>) -> String {\n\n let mut s = rust_printer(box MemWriter::new());\n\n f(&mut s).unwrap();\n\n eof(&mut s.s).unwrap();\n\n unsafe {\n\n // FIXME(pcwalton): A nasty function to extract the string from an `io::Writer`\n\n // that we \"know\" to be a `MemWriter` that works around the lack of checked\n\n // downcasts.\n\n let (_, wr): (uint, Box<MemWriter>) = mem::transmute_copy(&s.s.out);\n\n let result =\n\n str::from_utf8_owned(Vec::from_slice(wr.get_ref())).unwrap();\n\n mem::forget(wr);\n\n result.to_string()\n\n }\n\n}\n\n\n", "file_path": "src/libsyntax/print/pprust.rs", "rank": 19, "score": 454004.74283801496 }, { "content": "/// Replace all occurrences of one string with another\n\n///\n\n/// # Arguments\n\n///\n\n/// * s - The string containing substrings to replace\n\n/// * from - The string to replace\n\n/// * to - The replacement string\n\n///\n\n/// # Return value\n\n///\n\n/// The original string with all occurrences of `from` replaced with `to`\n\npub fn replace(s: &str, from: &str, to: &str) -> String {\n\n let mut result = String::new();\n\n let mut last_end = 0;\n\n for (start, end) in s.match_indices(from) {\n\n result.push_str(unsafe{raw::slice_bytes(s, last_end, start)});\n\n result.push_str(to);\n\n last_end = end;\n\n }\n\n result.push_str(unsafe{raw::slice_bytes(s, last_end, s.len())});\n\n result\n\n}\n\n\n\n/*\n\nSection: Misc\n\n*/\n\n\n", "file_path": "src/libcollections/str.rs", "rank": 20, "score": 448862.6845455315 }, { "content": "pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {\n\n let err = |s: &str| {\n\n match (sp, sess) {\n\n (_, None) => fail!(\"{}\", s),\n\n (Some(sp), Some(sess)) => sess.span_err(sp, s),\n\n (None, Some(sess)) => sess.err(s),\n\n }\n\n };\n\n if s.len() == 0 {\n\n err(\"crate name must not be empty\");\n\n }\n\n for c in s.chars() {\n\n if c.is_alphanumeric() { continue }\n\n if c == '_' || c == '-' { continue }\n\n err(format!(\"invalid character `{}` in crate name: `{}`\", c, s).as_slice());\n\n }\n\n match sess {\n\n Some(sess) => sess.abort_if_errors(),\n\n None => {}\n\n }\n\n}\n\n\n", "file_path": "src/librustc/metadata/creader.rs", "rank": 21, "score": 448717.74194034224 }, { "content": "pub fn redirect(dst: &mut io::Writer, url: &str) -> io::IoResult<()> {\n\n write!(dst,\n\nr##\"<!DOCTYPE html>\n\n<html lang=\"en\">\n\n<head>\n\n <meta http-equiv=\"refresh\" content=\"0;URL={url}\">\n\n</head>\n\n<body>\n\n</body>\n\n</html>\"##,\n\n url = url,\n\n )\n\n}\n", "file_path": "src/librustdoc/html/layout.rs", "rank": 22, "score": 448412.0607843678 }, { "content": "pub fn main() { let _kitty = cat(\"Spotty\".to_string()); }\n", "file_path": "src/test/run-pass/class-attributes-1.rs", "rank": 23, "score": 445945.12825480686 }, { "content": "/// Prints version information and returns None on success or an error\n\n/// message on failure.\n\npub fn version(binary: &str, matches: &getopts::Matches) -> Option<String> {\n\n let verbose = match matches.opt_str(\"version\").as_ref().map(|s| s.as_slice()) {\n\n None => false,\n\n Some(\"verbose\") => true,\n\n Some(s) => return Some(format!(\"Unrecognized argument: {}\", s))\n\n };\n\n\n\n println!(\"{} {}\", binary, env!(\"CFG_VERSION\"));\n\n if verbose {\n\n println!(\"binary: {}\", binary);\n\n println!(\"commit-hash: {}\", option_env!(\"CFG_VER_HASH\").unwrap_or(\"unknown\"));\n\n println!(\"commit-date: {}\", option_env!(\"CFG_VER_DATE\").unwrap_or(\"unknown\"));\n\n println!(\"host: {}\", driver::host_triple());\n\n println!(\"release: {}\", env!(\"CFG_RELEASE\"));\n\n }\n\n None\n\n}\n\n\n", "file_path": "src/librustc/driver/mod.rs", "rank": 24, "score": 443713.6654577117 }, { "content": "fn g1(ref_1: &str, ref_2: &str) -> String {\n\n match (ref_1, ref_2) {\n\n (\"a\", \"b\") => \"found a,b\".to_string(),\n\n (\"b\", \"c\") => \"found b,c\".to_string(),\n\n _ => \"not found\".to_string()\n\n }\n\n}\n\n\n", "file_path": "src/test/run-pass/match-borrowed_str.rs", "rank": 25, "score": 443255.28676632553 }, { "content": "fn g2(ref_1: &str, ref_2: &str) -> String {\n\n match (ref_1, ref_2) {\n\n (\"a\", \"b\") => \"found a,b\".to_string(),\n\n (\"b\", \"c\") => \"found b,c\".to_string(),\n\n (s1, s2) => format!(\"not found ({}, {})\", s1, s2)\n\n }\n\n}\n\n\n", "file_path": "src/test/run-pass/match-borrowed_str.rs", "rank": 26, "score": 443255.28676632553 }, { "content": "pub fn unindent(s: &str) -> String {\n\n let lines = s.lines_any().collect::<Vec<&str> >();\n\n let mut saw_first_line = false;\n\n let mut saw_second_line = false;\n\n let min_indent = lines.iter().fold(uint::MAX, |min_indent, line| {\n\n\n\n // After we see the first non-whitespace line, look at\n\n // the line we have. If it is not whitespace, and therefore\n\n // part of the first paragraph, then ignore the indentation\n\n // level of the first line\n\n let ignore_previous_indents =\n\n saw_first_line &&\n\n !saw_second_line &&\n\n !line.is_whitespace();\n\n\n\n let min_indent = if ignore_previous_indents {\n\n uint::MAX\n\n } else {\n\n min_indent\n\n };\n", "file_path": "src/librustdoc/passes.rs", "rank": 27, "score": 440974.24821195897 }, { "content": "pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> String {\n\n with_path(cx, id, |path| ast_map::path_to_string(path)).to_string()\n\n}\n\n\n\npub enum DtorKind {\n\n NoDtor,\n\n TraitDtor(DefId, bool)\n\n}\n\n\n\nimpl DtorKind {\n\n pub fn is_not_present(&self) -> bool {\n\n match *self {\n\n NoDtor => true,\n\n _ => false\n\n }\n\n }\n\n\n\n pub fn is_present(&self) -> bool {\n\n !self.is_not_present()\n\n }\n", "file_path": "src/librustc/middle/ty.rs", "rank": 28, "score": 439687.4879155598 }, { "content": "// does the given string match the pattern? whitespace in the first string\n\n// may be deleted or replaced with other whitespace to match the pattern.\n\n// this function is unicode-ignorant; fortunately, the careful design of\n\n// UTF-8 mitigates this ignorance. In particular, this function only collapses\n\n// sequences of \\n, \\r, ' ', and \\t, but it should otherwise tolerate unicode\n\n// chars. Unsurprisingly, it doesn't do NKF-normalization(?).\n\npub fn matches_codepattern(a : &str, b : &str) -> bool {\n\n let mut idx_a = 0;\n\n let mut idx_b = 0;\n\n loop {\n\n if idx_a == a.len() && idx_b == b.len() {\n\n return true;\n\n }\n\n else if idx_a == a.len() {return false;}\n\n else if idx_b == b.len() {\n\n // maybe the stuff left in a is all ws?\n\n if is_whitespace(a.char_at(idx_a)) {\n\n return scan_for_non_ws_or_end(a,idx_a) == a.len();\n\n } else {\n\n return false;\n\n }\n\n }\n\n // ws in both given and pattern:\n\n else if is_whitespace(a.char_at(idx_a))\n\n && is_whitespace(b.char_at(idx_b)) {\n\n idx_a = scan_for_non_ws_or_end(a,idx_a);\n", "file_path": "src/libsyntax/util/parser_testing.rs", "rank": 29, "score": 438487.96089725615 }, { "content": "/// Render `input` (e.g. \"foo.md\") into an HTML file in `output`\n\n/// (e.g. output = \"bar\" => \"bar/foo.html\").\n\npub fn render(input: &str, mut output: Path, matches: &getopts::Matches,\n\n external_html: &ExternalHtml) -> int {\n\n let input_p = Path::new(input);\n\n output.push(input_p.filestem().unwrap());\n\n output.set_extension(\"html\");\n\n\n\n let mut css = String::new();\n\n for name in matches.opt_strs(\"markdown-css\").iter() {\n\n let s = format!(\"<link rel=\\\"stylesheet\\\" type=\\\"text/css\\\" href=\\\"{}\\\">\\n\", name);\n\n css.push_str(s.as_slice())\n\n }\n\n\n\n let input_str = load_or_return!(input, 1, 2);\n\n let playground = matches.opt_str(\"markdown-playground-url\");\n\n if playground.is_some() {\n\n markdown::playground_krate.replace(Some(None));\n\n }\n\n let playground = playground.unwrap_or(\"\".to_string());\n\n\n\n let mut out = match io::File::create(&output) {\n", "file_path": "src/librustdoc/markdown.rs", "rank": 30, "score": 436973.5225846636 }, { "content": "// given a session and a string, add the string to\n\n// the session's codemap and return the new filemap\n\npub fn string_to_filemap(sess: &ParseSess, source: String, path: String)\n\n -> Rc<FileMap> {\n\n sess.span_diagnostic.cm.new_filemap(path, source)\n\n}\n\n\n", "file_path": "src/libsyntax/parse/mod.rs", "rank": 31, "score": 435970.85300146125 }, { "content": "pub fn main() { let x: int = 42; let y: int = id(x); assert!((x == y)); }\n", "file_path": "src/test/run-pass/generic-fn-infer.rs", "rank": 32, "score": 434695.9995394725 }, { "content": "/// Escapes all regular expression meta characters in `text`.\n\n///\n\n/// The string returned may be safely used as a literal in a regular\n\n/// expression.\n\npub fn quote(text: &str) -> String {\n\n let mut quoted = String::with_capacity(text.len());\n\n for c in text.chars() {\n\n if parse::is_punct(c) {\n\n quoted.push_char('\\\\')\n\n }\n\n quoted.push_char(c);\n\n }\n\n quoted\n\n}\n\n\n", "file_path": "src/libregex/re.rs", "rank": 33, "score": 434654.665216287 }, { "content": "// Name sanitation. LLVM will happily accept identifiers with weird names, but\n\n// gas doesn't!\n\n// gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $\n\npub fn sanitize(s: &str) -> String {\n\n let mut result = String::new();\n\n for c in s.chars() {\n\n match c {\n\n // Escape these with $ sequences\n\n '@' => result.push_str(\"$SP$\"),\n\n '~' => result.push_str(\"$UP$\"),\n\n '*' => result.push_str(\"$RP$\"),\n\n '&' => result.push_str(\"$BP$\"),\n\n '<' => result.push_str(\"$LT$\"),\n\n '>' => result.push_str(\"$GT$\"),\n\n '(' => result.push_str(\"$LP$\"),\n\n ')' => result.push_str(\"$RP$\"),\n\n ',' => result.push_str(\"$C$\"),\n\n\n\n // '.' doesn't occur in types and functions, so reuse it\n\n // for ':' and '-'\n\n '-' | ':' => result.push_char('.'),\n\n\n\n // These are legal symbols\n", "file_path": "src/librustc/back/link.rs", "rank": 34, "score": 434641.8827951682 }, { "content": "pub fn main() { let c = a(2); match c { a::<int>(_) => { } } }\n", "file_path": "src/test/run-pass/simple-generic-match.rs", "rank": 35, "score": 434568.73212598497 }, { "content": "// All rust symbols are in theory lists of \"::\"-separated identifiers. Some\n\n// assemblers, however, can't handle these characters in symbol names. To get\n\n// around this, we use C++-style mangling. The mangling method is:\n\n//\n\n// 1. Prefix the symbol with \"_ZN\"\n\n// 2. For each element of the path, emit the length plus the element\n\n// 3. End the path with \"E\"\n\n//\n\n// For example, \"_ZN4testE\" => \"test\" and \"_ZN3foo3bar\" => \"foo::bar\".\n\n//\n\n// We're the ones printing our backtraces, so we can't rely on anything else to\n\n// demangle our symbols. It's *much* nicer to look at demangled symbols, so\n\n// this function is implemented to give us nice pretty output.\n\n//\n\n// Note that this demangler isn't quite as fancy as it could be. We have lots\n\n// of other information in our symbols like hashes, version, type information,\n\n// etc. Additionally, this doesn't handle glue symbols at all.\n\nfn demangle(writer: &mut Writer, s: &str) -> IoResult<()> {\n\n // First validate the symbol. If it doesn't look like anything we're\n\n // expecting, we just print it literally. Note that we must handle non-rust\n\n // symbols because we could have any function in the backtrace.\n\n let mut valid = true;\n\n if s.len() > 4 && s.starts_with(\"_ZN\") && s.ends_with(\"E\") {\n\n let mut chars = s.slice(3, s.len() - 1).chars();\n\n while valid {\n\n let mut i = 0;\n\n for c in chars {\n\n if c.is_digit() {\n\n i = i * 10 + c as uint - '0' as uint;\n\n } else {\n\n break\n\n }\n\n }\n\n if i == 0 {\n\n valid = chars.next().is_none();\n\n break\n\n } else if chars.by_ref().take(i - 1).count() != i - 1 {\n", "file_path": "src/libstd/rt/backtrace.rs", "rank": 36, "score": 434504.5223313254 }, { "content": "// map string to parser (via tts)\n\npub fn string_to_parser<'a>(ps: &'a ParseSess, source_str: String) -> Parser<'a> {\n\n new_parser_from_source_str(ps,\n\n Vec::new(),\n\n \"bogofile\".to_string(),\n\n source_str)\n\n}\n\n\n", "file_path": "src/libsyntax/util/parser_testing.rs", "rank": 37, "score": 433490.3432122 }, { "content": "pub fn main() { mk_raw_ty(ty_nil, None::<String>); }\n", "file_path": "src/test/run-pass/alias-uninit-value.rs", "rank": 38, "score": 430775.93256231485 }, { "content": "pub fn opt_str0<'a>(maybestr: &'a Option<String>) -> &'a str {\n\n if maybestr.is_none() {\n\n \"(none)\"\n\n } else {\n\n let s: &'a str = maybestr.get_ref().as_slice();\n\n s\n\n }\n\n}\n\n\n", "file_path": "src/test/compile-fail/lub-if.rs", "rank": 39, "score": 429984.0766406022 }, { "content": "pub fn opt_str1<'a>(maybestr: &'a Option<String>) -> &'a str {\n\n if maybestr.is_some() {\n\n let s: &'a str = maybestr.get_ref().as_slice();\n\n s\n\n } else {\n\n \"(none)\"\n\n }\n\n}\n\n\n", "file_path": "src/test/compile-fail/lub-if.rs", "rank": 40, "score": 429984.0766406022 }, { "content": "pub fn mk_sugared_doc_attr(id: AttrId, text: InternedString, lo: BytePos,\n\n hi: BytePos)\n\n -> Attribute {\n\n let style = doc_comment_style(text.get());\n\n let lit = spanned(lo, hi, ast::LitStr(text, ast::CookedStr));\n\n let attr = Attribute_ {\n\n id: id,\n\n style: style,\n\n value: box(GC) spanned(lo, hi, MetaNameValue(InternedString::new(\"doc\"),\n\n lit)),\n\n is_sugared_doc: true\n\n };\n\n spanned(lo, hi, attr)\n\n}\n\n\n\n/* Searching */\n", "file_path": "src/libsyntax/attr.rs", "rank": 41, "score": 429507.736841118 }, { "content": "#[cfg(not(target_os=\"ios\"))]\n\npub fn dll_filename(base: &str) -> String {\n\n format!(\"{}{}{}\", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)\n\n}\n\n\n", "file_path": "src/libstd/os.rs", "rank": 42, "score": 428623.9640169675 }, { "content": "#[deprecated=\"use `Url::parse`\"]\n\npub fn from_str(s: &str) -> Result<Url, String> {\n\n Url::parse(s)\n\n}\n\n\n\nimpl Path {\n\n pub fn new(path: String,\n\n query: Query,\n\n fragment: Option<String>)\n\n -> Path {\n\n Path {\n\n path: path,\n\n query: query,\n\n fragment: fragment,\n\n }\n\n }\n\n\n\n /// Parses a URL path, converting it from a string to a `Path` representation.\n\n ///\n\n /// # Arguments\n\n /// * rawpath - a string representing the path component of a URL.\n", "file_path": "src/liburl/lib.rs", "rank": 43, "score": 426896.426970042 }, { "content": "pub fn ident_to_string(id: &ast::Ident) -> String {\n\n to_string(|s| s.print_ident(*id))\n\n}\n\n\n", "file_path": "src/libsyntax/print/pprust.rs", "rank": 44, "score": 424885.85783979465 }, { "content": "pub fn opt_str2<'a>(maybestr: &'a Option<String>) -> &'static str {\n\n if maybestr.is_none() { //~ ERROR mismatched types\n\n \"(none)\"\n\n } else {\n\n let s: &'a str = maybestr.get_ref().as_slice();\n\n s\n\n }\n\n}\n\n\n", "file_path": "src/test/compile-fail/lub-if.rs", "rank": 45, "score": 423872.05752036266 }, { "content": "pub fn opt_str3<'a>(maybestr: &'a Option<String>) -> &'static str {\n\n if maybestr.is_some() { //~ ERROR mismatched types\n\n let s: &'a str = maybestr.get_ref().as_slice();\n\n s\n\n } else {\n\n \"(none)\"\n\n }\n\n}\n\n\n\n\n", "file_path": "src/test/compile-fail/lub-if.rs", "rank": 46, "score": 423872.05752036266 }, { "content": "pub fn expr_span(cx: &ctxt, id: NodeId) -> Span {\n\n match cx.map.find(id) {\n\n Some(ast_map::NodeExpr(e)) => {\n\n e.span\n\n }\n\n Some(f) => {\n\n cx.sess.bug(format!(\"Node id {} is not an expr: {:?}\",\n\n id,\n\n f).as_slice());\n\n }\n\n None => {\n\n cx.sess.bug(format!(\"Node id {} is not present \\\n\n in the node map\", id).as_slice());\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/librustc/middle/ty.rs", "rank": 47, "score": 423704.1170688254 }, { "content": "fn unwrap(x: X) -> String {\n\n let X { x: y } = x; //~ ERROR cannot move out of type\n\n y\n\n}\n\n\n", "file_path": "src/test/compile-fail/disallowed-deconstructing-destructing-struct-let.rs", "rank": 48, "score": 423489.0282476137 }, { "content": "#[cfg(target_os = \"win32\")]\n\npub fn make_new_path(path: &str) -> String {\n\n\n\n // Windows just uses PATH as the library search path, so we have to\n\n // maintain the current value while adding our own\n\n match getenv(lib_path_env_var()) {\n\n Some(curr) => {\n\n format!(\"{}{}{}\", path, path_div(), curr)\n\n }\n\n None => path.to_string()\n\n }\n\n}\n\n\n", "file_path": "src/compiletest/util.rs", "rank": 49, "score": 422897.63757351553 }, { "content": "pub fn maketest(s: &str, cratename: Option<&str>, lints: bool, dont_insert_main: bool) -> String {\n\n let mut prog = String::new();\n\n if lints {\n\n prog.push_str(r\"\n\n#![deny(warnings)]\n\n#![allow(unused_variable, dead_assignment, unused_mut, unused_attribute, dead_code)]\n\n\");\n\n }\n\n\n\n // Don't inject `extern crate std` because it's already injected by the\n\n // compiler.\n\n if !s.contains(\"extern crate\") && cratename != Some(\"std\") {\n\n match cratename {\n\n Some(cratename) => {\n\n if s.contains(cratename) {\n\n prog.push_str(format!(\"extern crate {};\\n\",\n\n cratename).as_slice());\n\n }\n\n }\n\n None => {}\n", "file_path": "src/librustdoc/test.rs", "rank": 50, "score": 422482.4137873337 }, { "content": "#[deprecated=\"use `Path::parse`\"]\n\npub fn path_from_str(s: &str) -> Result<Path, String> {\n\n Path::parse(s)\n\n}\n\n\n\nimpl UserInfo {\n\n #[inline]\n\n pub fn new(user: String, pass: Option<String>) -> UserInfo {\n\n UserInfo { user: user, pass: pass }\n\n }\n\n}\n\n\n", "file_path": "src/liburl/lib.rs", "rank": 51, "score": 421406.9073778462 }, { "content": "/// Process command line options. Emits messages as appropriate. If compilation\n\n/// should continue, returns a getopts::Matches object parsed from args, otherwise\n\n/// returns None.\n\npub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {\n\n // Throw away the first argument, the name of the binary\n\n let _binary = args.shift().unwrap();\n\n\n\n if args.is_empty() {\n\n usage();\n\n return None;\n\n }\n\n\n\n let matches =\n\n match getopts::getopts(args.as_slice(), config::optgroups().as_slice()) {\n\n Ok(m) => m,\n\n Err(f) => {\n\n early_error(f.to_string().as_slice());\n\n }\n\n };\n\n\n\n if matches.opt_present(\"h\") || matches.opt_present(\"help\") {\n\n usage();\n\n return None;\n", "file_path": "src/librustc/driver/mod.rs", "rank": 52, "score": 420589.2221808505 }, { "content": "pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> {\n\n respan(mk_sp(lo, hi), t)\n\n}\n\n\n", "file_path": "src/libsyntax/codemap.rs", "rank": 53, "score": 420332.01816168666 }, { "content": "pub fn main() { let x = 10; test(x); }\n", "file_path": "src/test/run-pass/move-arg.rs", "rank": 54, "score": 417788.00617703237 }, { "content": "pub fn get_ar_prog(sess: &Session) -> String {\n\n match sess.opts.cg.ar {\n\n Some(ref ar) => (*ar).clone(),\n\n None => \"ar\".to_string()\n\n }\n\n}\n\n\n", "file_path": "src/librustc/back/link.rs", "rank": 55, "score": 417651.39321020915 }, { "content": "pub fn get_cc_prog(sess: &Session) -> String {\n\n match sess.opts.cg.linker {\n\n Some(ref linker) => return linker.to_string(),\n\n None => {}\n\n }\n\n\n\n // In the future, FreeBSD will use clang as default compiler.\n\n // It would be flexible to use cc (system's default C compiler)\n\n // instead of hard-coded gcc.\n\n // For win32, there is no cc command, so we add a condition to make it use gcc.\n\n match sess.targ_cfg.os {\n\n abi::OsWin32 => \"gcc\",\n\n _ => \"cc\",\n\n }.to_string()\n\n}\n\n\n", "file_path": "src/librustc/back/link.rs", "rank": 56, "score": 417651.39321020915 }, { "content": "pub fn main() { let mut v = vec!(1i, 2, 3); v.push(1); }\n", "file_path": "src/test/run-pass/vec-push.rs", "rank": 57, "score": 417404.8717861393 }, { "content": "/// Parses the time from the string according to the format string.\n\npub fn strptime(s: &str, format: &str) -> Result<Tm, String> {\n\n fn match_str(s: &str, pos: uint, needle: &str) -> bool {\n\n let mut i = pos;\n\n for ch in needle.bytes() {\n\n if s.as_bytes()[i] != ch {\n\n return false;\n\n }\n\n i += 1u;\n\n }\n\n return true;\n\n }\n\n\n\n fn match_strs(ss: &str, pos: uint, strs: &[(String, i32)])\n\n -> Option<(i32, uint)> {\n\n let mut i = 0u;\n\n let len = strs.len();\n\n while i < len {\n\n match strs[i] { // can't use let due to let-pattern bugs\n\n (ref needle, value) => {\n\n if match_str(ss, pos, needle.as_slice()) {\n", "file_path": "src/libtime/lib.rs", "rank": 58, "score": 417396.77991225023 }, { "content": "#[no_mangle]\n\npub fn test() {\n\n let _x = \"hello\";\n\n}\n", "file_path": "src/test/codegen/stack-alloc-string-slice.rs", "rank": 59, "score": 417002.2891818661 }, { "content": "// parse a string, return a crate.\n\npub fn string_to_crate (source_str : String) -> ast::Crate {\n\n with_error_checking_parse(source_str, |p| {\n\n p.parse_crate_mod()\n\n })\n\n}\n\n\n", "file_path": "src/libsyntax/util/parser_testing.rs", "rank": 60, "score": 416725.5413534 }, { "content": "pub fn to_string(f: |&mut State| -> IoResult<()>) -> String {\n\n let mut s = rust_printer(box MemWriter::new());\n\n f(&mut s).unwrap();\n\n eof(&mut s.s).unwrap();\n\n unsafe {\n\n // FIXME(pcwalton): A nasty function to extract the string from an `io::Writer`\n\n // that we \"know\" to be a `MemWriter` that works around the lack of checked\n\n // downcasts.\n\n let (_, wr): (uint, Box<MemWriter>) = mem::transmute_copy(&s.s.out);\n\n let result =\n\n str::from_utf8_owned(Vec::from_slice(wr.get_ref())).unwrap();\n\n mem::forget(wr);\n\n result.to_string()\n\n }\n\n}\n\n\n", "file_path": "src/libsyntax/print/pprust.rs", "rank": 61, "score": 415953.14253455086 }, { "content": "fn escape_str(writer: &mut io::Writer, v: &str) -> Result<(), io::IoError> {\n\n escape_bytes(writer, v.as_bytes())\n\n}\n\n\n", "file_path": "src/libserialize/json.rs", "rank": 62, "score": 415788.8558940655 }, { "content": "#[cfg(target_os=\"macos\")]\n\nfn libname(mut n: String) -> String {\n\n n.push_str(\".dylib\");\n\n n\n\n}\n\n\n", "file_path": "src/librustdoc/plugins.rs", "rank": 63, "score": 413986.82610670564 }, { "content": "pub fn cs_cmp(cx: &mut ExtCtxt, span: Span,\n\n substr: &Substructure) -> Gc<Expr> {\n\n let test_id = cx.ident_of(\"__test\");\n\n let equals_path = ordering_const(cx, span, Equal);\n\n\n\n /*\n\n Builds:\n\n\n\n let __test = self_field1.cmp(&other_field2);\n\n if other == ::std::cmp::Equal {\n\n let __test = self_field2.cmp(&other_field2);\n\n if __test == ::std::cmp::Equal {\n\n ...\n\n } else {\n\n __test\n\n }\n\n } else {\n\n __test\n\n }\n\n\n", "file_path": "src/libsyntax/ext/deriving/cmp/totalord.rs", "rank": 64, "score": 413160.20157970453 }, { "content": "pub fn main() { let mut _v: Vec<int> = Vec::new(); }\n", "file_path": "src/test/run-pass/empty-mutable-vec.rs", "rank": 65, "score": 412415.8139500927 }, { "content": "pub fn main() { let mut x = b(box(GC) 10); x = a; }\n", "file_path": "src/test/run-pass/leak-tag-copy.rs", "rank": 66, "score": 411292.39567318 }, { "content": "pub fn encode_def_id(ebml_w: &mut Encoder, id: DefId) {\n\n ebml_w.wr_tagged_str(tag_def_id, def_to_string(id).as_slice());\n\n}\n\n\n", "file_path": "src/librustc/metadata/encoder.rs", "rank": 67, "score": 410293.7331620997 }, { "content": "pub fn cs_partial_cmp(cx: &mut ExtCtxt, span: Span,\n\n substr: &Substructure) -> Gc<Expr> {\n\n let test_id = cx.ident_of(\"__test\");\n\n let equals_expr = some_ordering_const(cx, span, Equal);\n\n\n\n /*\n\n Builds:\n\n\n\n let __test = self_field1.partial_cmp(&other_field2);\n\n if __test == ::std::option::Some(::std::cmp::Equal) {\n\n let __test = self_field2.partial_cmp(&other_field2);\n\n if __test == ::std::option::Some(::std::cmp::Equal) {\n\n ...\n\n } else {\n\n __test\n\n }\n\n } else {\n\n __test\n\n }\n\n\n", "file_path": "src/libsyntax/ext/deriving/cmp/ord.rs", "rank": 68, "score": 408903.09993789275 }, { "content": "pub fn llvm_err(sess: &Session, msg: String) -> ! {\n\n unsafe {\n\n let cstr = llvm::LLVMRustGetLastError();\n\n if cstr == ptr::null() {\n\n sess.fatal(msg.as_slice());\n\n } else {\n\n let err = CString::new(cstr, true);\n\n let err = str::from_utf8_lossy(err.as_bytes());\n\n sess.fatal(format!(\"{}: {}\",\n\n msg.as_slice(),\n\n err.as_slice()).as_slice());\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/librustc/back/link.rs", "rank": 69, "score": 408212.13319999323 }, { "content": "pub fn main() {\n\n match \"test\" { \"not-test\" => fail!(), \"test\" => (), _ => fail!() }\n\n\n\n enum t { tag1(String), tag2, }\n\n\n\n\n\n match tag1(\"test\".to_string()) {\n\n tag2 => fail!(),\n\n tag1(ref s) if \"test\" != s.as_slice() => fail!(),\n\n tag1(ref s) if \"test\" == s.as_slice() => (),\n\n _ => fail!()\n\n }\n\n\n\n let x = match \"a\" { \"a\" => 1i, \"b\" => 2i, _ => fail!() };\n\n assert_eq!(x, 1);\n\n\n\n match \"a\" { \"a\" => { } \"b\" => { }, _ => fail!() }\n\n\n\n}\n", "file_path": "src/test/run-pass/match-str.rs", "rank": 70, "score": 407082.36001531454 }, { "content": "pub fn opt_str<'a>(maybestr: &'a Option<String>) -> &'a str {\n\n match *maybestr {\n\n None => \"(none)\",\n\n Some(ref s) => s.as_slice(),\n\n }\n\n}\n\n\n", "file_path": "src/compiletest/compiletest.rs", "rank": 71, "score": 406490.63597446453 }, { "content": "/// Formats the time according to the format string.\n\npub fn strftime(format: &str, tm: &Tm) -> String {\n\n fn days_in_year(year: int) -> i32 {\n\n if (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) {\n\n 366 /* Days in a leap year */\n\n } else {\n\n 365 /* Days in a non-leap year */\n\n }\n\n }\n\n\n\n fn iso_week_days(yday: i32, wday: i32) -> int {\n\n /* The number of days from the first day of the first ISO week of this\n\n * year to the year day YDAY with week day WDAY.\n\n * ISO weeks start on Monday. The first ISO week has the year's first\n\n * Thursday.\n\n * YDAY may be as small as yday_minimum.\n\n */\n\n let yday: int = yday as int;\n\n let wday: int = wday as int;\n\n let iso_week_start_wday: int = 1; /* Monday */\n\n let iso_week1_wday: int = 4; /* Thursday */\n", "file_path": "src/libtime/lib.rs", "rank": 72, "score": 404918.0165254097 }, { "content": "// parse a string, return a pat. Uses \"irrefutable\"... which doesn't\n\n// (currently) affect parsing.\n\npub fn string_to_pat(source_str: String) -> Gc<ast::Pat> {\n\n string_to_parser(&new_parse_sess(), source_str).parse_pat()\n\n}\n\n\n", "file_path": "src/libsyntax/util/parser_testing.rs", "rank": 73, "score": 404699.3152336113 }, { "content": "// parse a string, return a stmt\n\npub fn string_to_stmt(source_str : String) -> Gc<ast::Stmt> {\n\n with_error_checking_parse(source_str, |p| {\n\n p.parse_stmt(Vec::new())\n\n })\n\n}\n\n\n", "file_path": "src/libsyntax/util/parser_testing.rs", "rank": 74, "score": 404693.1451686152 }, { "content": "// parse a string, return an expr\n\npub fn string_to_expr (source_str : String) -> Gc<ast::Expr> {\n\n with_error_checking_parse(source_str, |p| {\n\n p.parse_expr()\n\n })\n\n}\n\n\n", "file_path": "src/libsyntax/util/parser_testing.rs", "rank": 75, "score": 404693.1451686152 }, { "content": "pub fn check_struct(ccx: &CrateCtxt, id: ast::NodeId, span: Span) {\n\n let tcx = ccx.tcx;\n\n\n\n check_representable(tcx, span, id, \"struct\");\n\n check_instantiable(tcx, span, id);\n\n\n\n // Check there are no overlapping fields in super-structs\n\n check_for_field_shadowing(tcx, local_def(id));\n\n\n\n if ty::lookup_simd(tcx, local_def(id)) {\n\n check_simd(tcx, span, id);\n\n }\n\n}\n\n\n", "file_path": "src/librustc/middle/typeck/check/mod.rs", "rank": 76, "score": 404081.63326424063 }, { "content": "/// Get a string representing the platform-dependent last error\n\npub fn last_os_error() -> String {\n\n error_string(errno() as uint)\n\n}\n\n\n\nstatic mut EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;\n\n\n\n/**\n\n * Sets the process exit code\n\n *\n\n * Sets the exit code returned by the process if all supervised tasks\n\n * terminate successfully (without failing). If the current root task fails\n\n * and is supervised by the scheduler then any user-specified exit status is\n\n * ignored and the process exits with the default failure status.\n\n *\n\n * Note that this is not synchronized against modifications of other threads.\n\n */\n", "file_path": "src/libstd/os.rs", "rank": 77, "score": 401034.8679093169 }, { "content": "pub fn check_struct_pat(pcx: &pat_ctxt, _pat_id: ast::NodeId, span: Span,\n\n _expected: ty::t, _path: &ast::Path,\n\n fields: &[ast::FieldPat], etc: bool,\n\n struct_id: ast::DefId,\n\n substitutions: &subst::Substs) {\n\n let _fcx = pcx.fcx;\n\n let tcx = pcx.fcx.ccx.tcx;\n\n\n\n let class_fields = ty::lookup_struct_fields(tcx, struct_id);\n\n\n\n check_struct_pat_fields(pcx, span, fields, class_fields, struct_id,\n\n substitutions, etc);\n\n}\n\n\n", "file_path": "src/librustc/middle/typeck/check/_match.rs", "rank": 78, "score": 400257.16833862173 }, { "content": "pub fn main() {\n\n let _i = 0u;\n\n loop {\n\n break;\n\n }\n\n assert!(true);\n\n}\n", "file_path": "src/test/run-pass/loop-break-cont-1.rs", "rank": 79, "score": 399903.3998543807 }, { "content": "pub fn main() {\n\n test();\n\n}\n", "file_path": "src/test/run-pass/liveness-loop-break.rs", "rank": 80, "score": 399903.3998543807 }, { "content": "pub fn main() {\n\n let mut i = 0u;\n\n loop {\n\n println!(\"a\");\n\n i += 1u;\n\n if i == 10u {\n\n break;\n\n }\n\n }\n\n assert_eq!(i, 10u);\n\n let mut is_even = false;\n\n loop {\n\n if i == 21u {\n\n break;\n\n }\n\n println!(\"b\");\n\n is_even = false;\n\n i += 1u;\n\n if i % 2u != 0u {\n\n continue;\n", "file_path": "src/test/run-pass/loop-break-cont.rs", "rank": 81, "score": 399903.3998543807 }, { "content": "pub fn main() {\n\n fn invoke(f: ||) { f(); }\n\n let k = box 22i;\n\n let _u = A {a: k.clone()};\n\n invoke(|| println!(\"{:?}\", k.clone()) )\n\n}\n", "file_path": "src/test/run-pass/last-use-is-capture.rs", "rank": 82, "score": 399884.9019162417 }, { "content": "pub fn main() {}\n", "file_path": "src/test/run-pass/last-use-in-block.rs", "rank": 83, "score": 399884.9019162416 }, { "content": "pub fn main() {\n\n let _nyan = cat(\"nyan\".to_string());\n\n}\n", "file_path": "src/test/run-pass/class-str-field.rs", "rank": 84, "score": 399765.70963981265 }, { "content": "pub fn main() {\n\n assert_eq!(f1(\"b\"), \"found b\".to_string());\n\n assert_eq!(f1(\"c\"), \"not found\".to_string());\n\n assert_eq!(f1(\"d\"), \"not found\".to_string());\n\n assert_eq!(f2(\"b\"), \"found b\".to_string());\n\n assert_eq!(f2(\"c\"), \"not found (c)\".to_string());\n\n assert_eq!(f2(\"d\"), \"not found (d)\".to_string());\n\n assert_eq!(g1(\"b\", \"c\"), \"found b,c\".to_string());\n\n assert_eq!(g1(\"c\", \"d\"), \"not found\".to_string());\n\n assert_eq!(g1(\"d\", \"e\"), \"not found\".to_string());\n\n assert_eq!(g2(\"b\", \"c\"), \"found b,c\".to_string());\n\n assert_eq!(g2(\"c\", \"d\"), \"not found (c, d)\".to_string());\n\n assert_eq!(g2(\"d\", \"e\"), \"not found (d, e)\".to_string());\n\n}\n", "file_path": "src/test/run-pass/match-borrowed_str.rs", "rank": 85, "score": 399679.6548852566 }, { "content": "/// Derive a usage message from a set of long options.\n\npub fn usage(brief: &str, opts: &[OptGroup]) -> String {\n\n\n\n let desc_sep = format!(\"\\n{}\", \" \".repeat(24));\n\n\n\n let mut rows = opts.iter().map(|optref| {\n\n let OptGroup{short_name: short_name,\n\n long_name: long_name,\n\n hint: hint,\n\n desc: desc,\n\n hasarg: hasarg,\n\n ..} = (*optref).clone();\n\n\n\n let mut row = \" \".repeat(4);\n\n\n\n // short option\n\n match short_name.len() {\n\n 0 => {}\n\n 1 => {\n\n row.push_char('-');\n\n row.push_str(short_name.as_slice());\n", "file_path": "src/libgetopts/lib.rs", "rank": 86, "score": 399455.5160032681 }, { "content": "/// Return open file for `term`\n\npub fn open(term: &str) -> Result<File, String> {\n\n match get_dbpath_for_term(term) {\n\n Some(x) => {\n\n match File::open(x) {\n\n Ok(file) => Ok(file),\n\n Err(e) => Err(format!(\"error opening file: {}\", e)),\n\n }\n\n }\n\n None => {\n\n Err(format!(\"could not find terminfo entry for {}\", term))\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/libterm/terminfo/searcher.rs", "rank": 87, "score": 399455.5160032681 }, { "content": "// map a string to tts, using a made-up filename:\n\npub fn string_to_tts(source_str: String) -> Vec<ast::TokenTree> {\n\n let ps = new_parse_sess();\n\n filemap_to_tts(&ps,\n\n string_to_filemap(&ps, source_str, \"bogofile\".to_string()))\n\n}\n\n\n", "file_path": "src/libsyntax/util/parser_testing.rs", "rank": 88, "score": 399222.6548314989 }, { "content": "// Traverse the crate, collecting all the test functions, eliding any\n\n// existing main functions, and synthesizing a main test harness\n\npub fn modify_for_testing(sess: &Session,\n\n krate: ast::Crate) -> ast::Crate {\n\n // We generate the test harness when building in the 'test'\n\n // configuration, either with the '--test' or '--cfg test'\n\n // command line options.\n\n let should_test = attr::contains_name(krate.config.as_slice(), \"test\");\n\n\n\n if should_test {\n\n generate_test_harness(sess, krate)\n\n } else {\n\n strip_test_functions(krate)\n\n }\n\n}\n\n\n", "file_path": "src/librustc/front/test.rs", "rank": 89, "score": 398788.71812355216 }, { "content": "/// Prints a string to the stdout of the current process. No newline is emitted\n\n/// after the string is printed.\n\npub fn print(s: &str) {\n\n with_task_stdout(|io| io.write(s.as_bytes()))\n\n}\n\n\n", "file_path": "src/libstd/io/stdio.rs", "rank": 90, "score": 398734.2613364045 }, { "content": "/// Prints a string as a line. to the stdout of the current process. A literal\n\n/// `\\n` character is printed to the console after the string.\n\npub fn println(s: &str) {\n\n with_task_stdout(|io| {\n\n io.write(s.as_bytes()).and_then(|()| io.write(['\\n' as u8]))\n\n })\n\n}\n\n\n", "file_path": "src/libstd/io/stdio.rs", "rank": 91, "score": 398734.16154840146 }, { "content": "#[bench]\n\nfn match_class(b: &mut Bencher) {\n\n let re = regex!(\"[abcdw]\");\n\n let text = format!(\"{}w\", \"xxxx\".repeat(20));\n\n bench_assert_match(b, re, text.as_slice());\n\n}\n\n\n", "file_path": "src/libregex/test/bench.rs", "rank": 92, "score": 397786.2850764409 }, { "content": "pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString {\n\n match cx.map.find(id) {\n\n Some(ast_map::NodeLocal(pat)) => {\n\n match pat.node {\n\n ast::PatIdent(_, ref path1, _) => {\n\n token::get_ident(path1.node)\n\n }\n\n _ => {\n\n cx.sess.bug(\n\n format!(\"Variable id {} maps to {:?}, not local\",\n\n id,\n\n pat).as_slice());\n\n }\n\n }\n\n }\n\n r => {\n\n cx.sess.bug(format!(\"Variable id {} maps to {:?}, not local\",\n\n id,\n\n r).as_slice());\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/librustc/middle/ty.rs", "rank": 93, "score": 396764.96045121335 }, { "content": "// return the next token from the TtReader.\n\n// EFFECT: advances the reader's token field\n\npub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan {\n\n // FIXME(pcwalton): Bad copy?\n\n let ret_val = TokenAndSpan {\n\n tok: r.cur_tok.clone(),\n\n sp: r.cur_span.clone(),\n\n };\n\n loop {\n\n let should_pop = match r.stack.last() {\n\n None => {\n\n assert_eq!(ret_val.tok, EOF);\n\n return ret_val;\n\n }\n\n Some(frame) => {\n\n if frame.idx < frame.forest.len() {\n\n break;\n\n }\n\n !frame.dotdotdoted ||\n\n *r.repeat_idx.last().unwrap() == *r.repeat_len.last().unwrap() - 1\n\n }\n\n };\n", "file_path": "src/libsyntax/ext/tt/transcribe.rs", "rank": 94, "score": 396542.9247767392 }, { "content": "/// Remove a variable from the environment entirely.\n\npub fn unsetenv(n: &str) {\n\n #[cfg(unix)]\n\n fn _unsetenv(n: &str) {\n\n unsafe {\n\n with_env_lock(|| {\n\n n.with_c_str(|nbuf| {\n\n libc::funcs::posix01::unistd::unsetenv(nbuf);\n\n })\n\n })\n\n }\n\n }\n\n\n\n #[cfg(windows)]\n\n fn _unsetenv(n: &str) {\n\n let n: Vec<u16> = n.utf16_units().collect();\n\n let n = n.append_one(0);\n\n unsafe {\n\n with_env_lock(|| {\n\n libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null());\n\n })\n\n }\n\n }\n\n _unsetenv(n);\n\n}\n\n\n", "file_path": "src/libstd/os.rs", "rank": 95, "score": 396093.7426743272 }, { "content": "pub fn run(input: &str,\n\n cfgs: Vec<String>,\n\n libs: HashSet<Path>,\n\n mut test_args: Vec<String>)\n\n -> int {\n\n let input_path = Path::new(input);\n\n let input = driver::FileInput(input_path.clone());\n\n\n\n let sessopts = config::Options {\n\n maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),\n\n addl_lib_search_paths: RefCell::new(libs.clone()),\n\n crate_types: vec!(config::CrateTypeDylib),\n\n ..config::basic_options().clone()\n\n };\n\n\n\n\n\n let codemap = CodeMap::new();\n\n let diagnostic_handler = diagnostic::default_handler(diagnostic::Auto);\n\n let span_diagnostic_handler =\n\n diagnostic::mk_span_handler(diagnostic_handler, codemap);\n", "file_path": "src/librustdoc/test.rs", "rank": 96, "score": 395363.4627002856 }, { "content": "pub fn get_symbol(data: &[u8], id: ast::NodeId) -> String {\n\n return item_symbol(lookup_item(id, data));\n\n}\n\n\n\n// Something that a name can resolve to.\n\n#[deriving(Clone)]\n\npub enum DefLike {\n\n DlDef(def::Def),\n\n DlImpl(ast::DefId),\n\n DlField\n\n}\n\n\n", "file_path": "src/librustc/metadata/decoder.rs", "rank": 97, "score": 394095.28349150054 }, { "content": " Some(&DefLabel(loop_id)) => loop_id,\n\n _ => self.ir.tcx.sess.span_bug(sp, \"label on break/loop \\\n\n doesn't refer to a loop\")\n\n }\n\n }\n\n None => {\n\n // Vanilla 'break' or 'loop', so use the enclosing\n\n // loop scope\n\n if self.loop_scope.len() == 0 {\n\n self.ir.tcx.sess.span_bug(sp, \"break outside loop\");\n\n } else {\n\n *self.loop_scope.last().unwrap()\n\n }\n\n }\n\n }\n\n }\n\n\n\n #[allow(unused_must_use)]\n\n fn ln_str(&self, ln: LiveNode) -> String {\n\n let mut wr = io::MemWriter::new();\n", "file_path": "src/librustc/middle/liveness.rs", "rank": 98, "score": 71.26463997230523 }, { "content": " // are incompatible with spans over other filemaps.\n\n let filemap = self.sess.codemap().new_filemap(String::from_str(\"<anon-dxr>\"),\n\n self.snippet(span));\n\n let s = self.sess;\n\n lexer::StringReader::new(s.diagnostic(), filemap)\n\n }\n\n\n\n // Re-parses a path and returns the span for the last identifier in the path\n\n pub fn span_for_last_ident(&self, span: Span) -> Option<Span> {\n\n let mut result = None;\n\n\n\n let mut toks = self.retokenise_span(span);\n\n let mut bracket_count = 0u;\n\n loop {\n\n let ts = toks.next_token();\n\n if ts.tok == token::EOF {\n\n return self.make_sub_span(span, result)\n\n }\n\n if bracket_count == 0 &&\n\n (is_ident(&ts.tok) || is_keyword(keywords::Self, &ts.tok)) {\n", "file_path": "src/librustc/middle/save/span_utils.rs", "rank": 99, "score": 57.307162778176725 } ]
Rust
dao_vault/lib.rs
RainbowDAO/RainbowDAO-Protocol-Ink-Test-Version-05
b17ecb5c37c868ca99a23e36957ac9e012474c29
#![cfg_attr(not(feature = "std"), no_std)] use ink_lang as ink; extern crate alloc; pub use self::dao_vault::DaoVault; #[ink::contract] mod dao_vault { use alloc::string::String; use alloc::vec::Vec; use erc20::Erc20; use ink_storage::{ collections::HashMap as StorageHashMap, traits::{PackedLayout,SpreadLayout}, }; #[derive( Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode, SpreadLayout, PackedLayout,Default )] #[cfg_attr( feature = "std", derive(::scale_info::TypeInfo, ::ink_storage::traits::StorageLayout) )] pub struct Transfer { transfer_id:u64, transfer_direction:u64, token_name: String, from_address:AccountId, to_address:AccountId, value: u64, transfer_time:u64, } #[derive( Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode, SpreadLayout, PackedLayout,Default )] #[cfg_attr( feature = "std", derive(::scale_info::TypeInfo, ::ink_storage::traits::StorageLayout) )] pub struct TokenInfo { erc20: AccountId, symbol: String, name: String, balance: u64, } #[ink(storage)] #[derive(Default)] pub struct DaoVault { value_manager:AccountId, vault_contract_address:AccountId, transfer_history:StorageHashMap<u64,Transfer>, tokens: StorageHashMap<AccountId, AccountId>, } #[ink(event)] pub struct AddVaultTokenEvent { #[ink(topic)] token_address: AccountId, } #[ink(event)] pub struct RemoveVaultTokenEvent { #[ink(topic)] token_address: AccountId, } #[ink(event)] pub struct DepositTokenEvent { #[ink(topic)] token_name:String, #[ink(topic)] from_address:AccountId, #[ink(topic)] value:u64, } #[ink(event)] pub struct WithdrawTokenEvent { #[ink(topic)] token_name:String, #[ink(topic)] to_address:AccountId, #[ink(topic)] value:u64, } impl DaoVault { #[ink(constructor)] pub fn new() -> Self { let contract_address = Self::env().account_id(); Self { value_manager:Self::env().caller(), vault_contract_address:contract_address, transfer_history:StorageHashMap::new(), tokens: StorageHashMap::default(), } } pub fn get_erc20_by_address(&self, address:AccountId) -> Erc20 { let erc20_instance: Erc20 = ink_env::call::FromAccountId::from_account_id(address); erc20_instance } #[ink(constructor)] pub fn default() -> Self { Self::new(Default::default()) } #[ink(message)] pub fn deposit(&mut self, erc_20_address:AccountId, from_address:AccountId,value:u64) -> bool { let to_address = self.vault_contract_address; if self.tokens.contains_key(&erc_20_address){ let mut erc_20 = self.get_erc20_by_address(erc_20_address); let token_name=(&erc_20).name(); let transfer_result=erc_20.transfer_from(from_address,to_address,value.into()); let transfer_id:u64 = (self.transfer_history.len()+1).into(); let transfer_time: u64 = self.env().block_timestamp(); self.transfer_history.insert(transfer_id, Transfer{ transfer_direction:2, token_name:token_name.clone(), transfer_id:transfer_id, from_address:from_address, to_address:to_address, value, transfer_time}); self.env().emit_event(DepositTokenEvent{ token_name: token_name.clone(), from_address:from_address, value:value}); true } else{ false } } #[ink(message)] pub fn withdraw(&mut self,erc_20_address:AccountId,to_address:AccountId,value:u64) -> bool { let from_address = self.vault_contract_address; if self.tokens.contains_key(&erc_20_address) { let mut erc_20 = self.get_erc20_by_address(erc_20_address); let token_name=(&erc_20).name(); let transfer_result=erc_20.transfer_from(from_address,to_address,value.into()); let transfer_id:u64 = (self.transfer_history.len()+1).into(); let transfer_time: u64 = self.env().block_timestamp(); self.transfer_history.insert(transfer_id, Transfer{ transfer_direction:1, token_name: token_name.clone(), transfer_id:transfer_id, from_address:from_address, to_address:to_address, value:value, transfer_time:transfer_time}); self.env().emit_event(WithdrawTokenEvent{ token_name: token_name.clone(), to_address:to_address, value:value,}); true } else{ false } } #[ink(message)] pub fn add_vault_token(&mut self,erc_20_address:AccountId) -> bool { self.tokens.insert(erc_20_address,self.vault_contract_address); self.env().emit_event(AddVaultTokenEvent{ token_address:erc_20_address, }); true } #[ink(message)] pub fn remove_vault_token(&mut self,erc_20_address: AccountId) -> bool { let contract_address=self.vault_contract_address; self.env().emit_event(RemoveVaultTokenEvent{ token_address:erc_20_address, }); true } #[ink(message)] pub fn value_owner(&self) -> AccountId { self.value_manager.clone() } } }
#![cfg_attr(not(feature = "std"), no_std)] use ink_lang as ink; extern crate alloc; pub use self::dao_vault::DaoVault; #[ink::contract] mod dao_vault { use alloc::string::String; use alloc::vec::Vec; use erc20::Erc20; use ink_storage::{ collections::HashMap as StorageHashMap, traits::{PackedLayout,SpreadLayout}, }; #[derive( Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode, SpreadLayout, PackedLayout,Default )] #[cfg_attr( feature = "std", derive(::scale_info::TypeInfo, ::ink_storage::traits::StorageLayout) )] pub struct Transfer { transfer_id:u64, transfer_direction:u64, token_name: String, from_address:AccountId, to_address:AccountId, value: u64, transfer_time:u64, } #[derive( Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode, SpreadLayout, PackedLayout,Default )] #[cfg_attr( feature = "std", derive(::scale_info::TypeInfo, ::ink_storage::traits::StorageLayout) )] pub struct TokenInfo { erc20: AccountId, symbol: String, name: String, balance: u64, } #[ink(storage)] #[derive(Default)] pub struct DaoVault { value_manager:AccountId, vault_contract_address:AccountId, transfer_history:StorageHashMap<u64,Transfer>, tokens: StorageHashMap<AccountId, AccountId>, } #[ink(event)] pub struct AddVaultTokenEvent { #[ink(topic)] token_address: AccountId, } #[ink(event)] pub struct RemoveVaultTokenEvent { #[ink(topic)] token_address: AccountId, } #[ink(event)] pub struct DepositTokenEvent { #[ink(topic)] token_name:String, #[ink(topic)] from_address:AccountId, #[ink(topic)] value:u64, } #[ink(event)] pub struct WithdrawTokenEvent { #[ink(topic)] token_name:String, #[ink(topic)] to_address:AccountId, #[ink(topic)] value:u64, } impl DaoVault { #[ink(constructor)] pub fn new() -> Self { let contract_address = Self::env().account_id(); Self { value_manager:Self::env().caller(), vault_contract_address:contract_address, transfer_history:StorageHashMap::new(), tokens: StorageHashMap::default(), } } pub fn get_erc20_by_address(&self, address:AccountId) -> Erc20 { let erc20_instance: Erc20 = ink_env::call::FromAccountId::from_account_id(address); erc20_instance } #[ink(constructor)] pub fn default() -> Self { Self::new(Default::default()) } #[ink(message)] pub fn deposit(&mut self, erc_20_address:AccountId, from_address:AccountId,value:u64) -> bool { let to_address = self.vault_contract_address; if self.tokens.contains_key(&erc_20_address){ let mut erc_20 = self.get_erc20_by_address(erc_20_address); let token_name=(&erc_20).name(); let transfer_result=erc_20.transfer_from(from_address,to_address,value.into()); let transfer_id:u64 = (self.transfer_history.len()+1).into(); let transfer_time: u64 = self.env().block_timestamp(); self.transfer_history.insert(transfer_id, Transfer{ transfer_direction:2, token_name:token_name.clone(), transfer_id:transfer_id, from_address:from_address, to_address:to_address, value, transfer_time}); self.env().emit_event(DepositTokenEvent{ token_name: token_name.clon
#[ink(message)] pub fn withdraw(&mut self,erc_20_address:AccountId,to_address:AccountId,value:u64) -> bool { let from_address = self.vault_contract_address; if self.tokens.contains_key(&erc_20_address) { let mut erc_20 = self.get_erc20_by_address(erc_20_address); let token_name=(&erc_20).name(); let transfer_result=erc_20.transfer_from(from_address,to_address,value.into()); let transfer_id:u64 = (self.transfer_history.len()+1).into(); let transfer_time: u64 = self.env().block_timestamp(); self.transfer_history.insert(transfer_id, Transfer{ transfer_direction:1, token_name: token_name.clone(), transfer_id:transfer_id, from_address:from_address, to_address:to_address, value:value, transfer_time:transfer_time}); self.env().emit_event(WithdrawTokenEvent{ token_name: token_name.clone(), to_address:to_address, value:value,}); true } else{ false } } #[ink(message)] pub fn add_vault_token(&mut self,erc_20_address:AccountId) -> bool { self.tokens.insert(erc_20_address,self.vault_contract_address); self.env().emit_event(AddVaultTokenEvent{ token_address:erc_20_address, }); true } #[ink(message)] pub fn remove_vault_token(&mut self,erc_20_address: AccountId) -> bool { let contract_address=self.vault_contract_address; self.env().emit_event(RemoveVaultTokenEvent{ token_address:erc_20_address, }); true } #[ink(message)] pub fn value_owner(&self) -> AccountId { self.value_manager.clone() } } }
e(), from_address:from_address, value:value}); true } else{ false } }
function_block-function_prefixed
[ { "content": " }\n\n\n\n /// The ERC-20 error types.\n\n #[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)]\n\n #[cfg_attr(feature = \"std\", derive(scale_info::TypeInfo))]\n\n pub enum Error {\n\n /// Returned if not enough balance to fulfill a request is available.\n\n InsufficientBalance,\n\n /// Returned if not enough allowance to fulfill a request is available.\n\n InsufficientAllowance,\n\n }\n\n\n\n /// The ERC-20 result type.\n\n pub type Result<T> = core::result::Result<T, Error>;\n\n\n\n impl Erc20 {\n\n /// Creates a new ERC-20 contract with the specified initial supply.\n\n #[ink(constructor)]\n\n pub fn new(initial_supply: Balance,name:String,symbol:String,decimals:u8,owner:AccountId) -> Self {\n\n let mut balances = StorageHashMap::new();\n", "file_path": "erc20/lib.rs", "rank": 0, "score": 28193.58193274234 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\nextern crate alloc;\n\nuse ink_lang as ink;\n\npub use self::erc20::{\n\n Erc20\n\n};\n\n#[ink::contract]\n\nmod erc20 {\n\n\n\n use alloc::string::String;\n\n use ink_storage::{\n\n collections::HashMap as StorageHashMap,\n\n traits::{\n\n PackedLayout,\n\n SpreadLayout,\n\n }\n\n };\n\n\n\n /// Indicates whether a transaction is already confirmed or needs further confirmations.\n\n #[derive(scale::Encode, scale::Decode, Clone, SpreadLayout, PackedLayout)]\n", "file_path": "erc20/lib.rs", "rank": 1, "score": 28192.99904567634 }, { "content": " assert_transfer_event(\n\n &emitted_events[0],\n\n None,\n\n Some(AccountId::from([0x01; 32])),\n\n 100,\n\n );\n\n let accounts =\n\n ink_env::test::default_accounts::<ink_env::DefaultEnvironment>()\n\n .expect(\"Cannot get accounts\");\n\n // Alice owns all the tokens on deployment\n\n assert_eq!(erc20.balance_of(accounts.alice), 100);\n\n // Bob does not owns tokens\n\n assert_eq!(erc20.balance_of(accounts.bob), 0);\n\n }\n\n\n\n #[ink::test]\n\n fn transfer_works() {\n\n // Constructor works.\n\n let mut erc20 = Erc20::new(100,String::from(\"test\"),String::from(\"test\"),8,AccountId::from([0x01; 32]));\n\n // Transfer event triggered during initial construction.\n", "file_path": "erc20/lib.rs", "rank": 2, "score": 28185.643457403174 }, { "content": " });\n\n Ok(())\n\n }\n\n #[ink(message)]\n\n pub fn mint_token_by_owner(\n\n &mut self,\n\n to: AccountId,\n\n value: u64,\n\n ) -> bool {\n\n let caller = self.env().caller();\n\n assert_eq!(caller == self.owner, true);\n\n self._mint_token(to, value)\n\n }\n\n #[ink(message)]\n\n pub fn transfer_owner(\n\n &mut self,\n\n to: AccountId,\n\n ) -> bool {\n\n let caller = self.env().caller();\n\n assert_eq!(caller == self.owner, true);\n", "file_path": "erc20/lib.rs", "rank": 3, "score": 28185.34371520179 }, { "content": " #[cfg_attr(\n\n feature = \"std\",\n\n derive(scale_info::TypeInfo, ink_storage::traits::StorageLayout)\n\n )]\n\n\n\n #[derive(Debug)]\n\n pub struct Checkpoint {\n\n from_block:u32,\n\n votes:u128\n\n }\n\n /// A simple ERC-20 contract.\n\n #[ink(storage)]\n\n #[derive(Default)]\n\n pub struct Erc20 {\n\n /// Total token supply.\n\n total_supply: Lazy<Balance>,\n\n /// Mapping from owner to number of owned token.\n\n balances: StorageHashMap<AccountId, Balance>,\n\n /// Mapping of the token amount which an account is allowed to withdraw\n\n /// from another account.\n", "file_path": "erc20/lib.rs", "rank": 4, "score": 28184.981739618685 }, { "content": " allowances: StorageHashMap<(AccountId, AccountId), Balance>,\n\n name: String,\n\n symbol: String,\n\n decimals: u8,\n\n owner: AccountId,\n\n num_check_points:StorageHashMap<AccountId,u32>,\n\n check_points:StorageHashMap<(AccountId, u32), Checkpoint>,\n\n delegates:StorageHashMap<AccountId,AccountId>,\n\n }\n\n\n\n #[derive(scale::Encode, scale::Decode, Clone)]\n\n #[cfg_attr(\n\n feature = \"std\",\n\n derive(scale_info::TypeInfo, ink_storage::traits::StorageLayout)\n\n )]\n\n pub struct TokenInfo {\n\n name: String,\n\n symbol: String,\n\n total_supply: u64,\n\n decimals: u8,\n", "file_path": "erc20/lib.rs", "rank": 5, "score": 28184.922218949836 }, { "content": " ///\n\n /// Returns `0` if no allowance has been set `0`.\n\n #[ink(message)]\n\n pub fn allowance(&self, owner: AccountId, spender: AccountId) -> Balance {\n\n self.allowances.get(&(owner, spender)).copied().unwrap_or(0)\n\n }\n\n\n\n /// Transfers `value` amount of tokens from the caller's account to account `to`.\n\n ///\n\n /// On success a `Transfer` event is emitted.\n\n ///\n\n /// # Errors\n\n ///\n\n /// Returns `InsufficientBalance` error if there are not enough tokens on\n\n /// the caller's account balance.\n\n #[ink(message)]\n\n pub fn name(&self) -> String {\n\n self.name.clone()\n\n }\n\n\n", "file_path": "erc20/lib.rs", "rank": 6, "score": 28183.833776370935 }, { "content": " // Create call\n\n let mut data =\n\n ink_env::test::CallData::new(ink_env::call::Selector::new([0x00; 4])); // balance_of\n\n data.push_arg(&accounts.bob);\n\n // Push the new execution context to set Bob as caller\n\n ink_env::test::push_execution_context::<ink_env::DefaultEnvironment>(\n\n accounts.bob,\n\n callee,\n\n 1000000,\n\n 1000000,\n\n data,\n\n );\n\n\n\n // Bob fails to transfers 10 tokens to Eve.\n\n assert_eq!(\n\n erc20.transfer(accounts.eve, 10),\n\n Err(Error::InsufficientBalance)\n\n );\n\n // Alice owns all the tokens.\n\n assert_eq!(erc20.balance_of(accounts.alice), 100);\n", "file_path": "erc20/lib.rs", "rank": 7, "score": 28183.326430791287 }, { "content": " fn transfer_works() {\n\n // Constructor works.\n\n let mut erc20 = Erc20::new(100);\n\n // Transfer event triggered during initial construction.\n\n let accounts =\n\n ink_env::test::default_accounts::<ink_env::DefaultEnvironment>();\n\n\n\n assert_eq!(erc20.balance_of(accounts.bob), 0);\n\n // Alice transfers 10 tokens to Bob.\n\n assert_eq!(erc20.transfer(accounts.bob, 10), Ok(()));\n\n // Bob owns 10 tokens.\n\n assert_eq!(erc20.balance_of(accounts.bob), 10);\n\n\n\n let emitted_events = ink_env::test::recorded_events().collect::<Vec<_>>();\n\n assert_eq!(emitted_events.len(), 2);\n\n // Check first transfer event related to ERC-20 instantiation.\n\n assert_transfer_event(\n\n &emitted_events[0],\n\n None,\n\n Some(AccountId::from([0x01; 32])),\n", "file_path": "erc20/lib.rs", "rank": 8, "score": 28183.030903121715 }, { "content": " assert_transfer_event(\n\n &emitted_events[1],\n\n Some(AccountId::from([0x01; 32])),\n\n Some(AccountId::from([0x02; 32])),\n\n 10,\n\n );\n\n }\n\n\n\n #[ink::test]\n\n fn invalid_transfer_should_fail() {\n\n // Constructor works.\n\n let mut erc20 = Erc20::new(100,String::from(\"test\"),String::from(\"test\"),8,AccountId::from([0x01; 32]));\n\n let accounts =\n\n ink_env::test::default_accounts::<ink_env::DefaultEnvironment>()\n\n .expect(\"Cannot get accounts\");\n\n\n\n assert_eq!(erc20.balance_of(accounts.bob), 0);\n\n // Get contract address.\n\n let callee = ink_env::account_id::<ink_env::DefaultEnvironment>()\n\n .unwrap_or_else(|_| [0x0; 32].into());\n", "file_path": "erc20/lib.rs", "rank": 9, "score": 28181.710399013024 }, { "content": " ink_env::test::default_accounts::<ink_env::DefaultEnvironment>()\n\n .expect(\"Cannot get accounts\");\n\n\n\n // Bob fails to transfer tokens owned by Alice.\n\n assert_eq!(\n\n erc20.transfer_from(accounts.alice, accounts.eve, 10),\n\n Err(Error::InsufficientAllowance)\n\n );\n\n // Alice approves Bob for token transfers on her behalf.\n\n assert_eq!(erc20.approve(accounts.bob, 10), Ok(()));\n\n\n\n // The approve event takes place.\n\n assert_eq!(ink_env::test::recorded_events().count(), 2);\n\n\n\n // Get contract address.\n\n let callee = ink_env::account_id::<ink_env::DefaultEnvironment>()\n\n .unwrap_or_else(|_| [0x0; 32].into());\n\n // Create call.\n\n let mut data =\n\n ink_env::test::CallData::new(ink_env::call::Selector::new([0x00; 4])); // balance_of\n", "file_path": "erc20/lib.rs", "rank": 10, "score": 28181.581127145375 }, { "content": " fn balance_of_works() {\n\n // Constructor works\n\n let erc20 = Erc20::new(100);\n\n // Transfer event triggered during initial construction\n\n let emitted_events = ink_env::test::recorded_events().collect::<Vec<_>>();\n\n assert_transfer_event(\n\n &emitted_events[0],\n\n None,\n\n Some(AccountId::from([0x01; 32])),\n\n 100,\n\n );\n\n let accounts =\n\n ink_env::test::default_accounts::<ink_env::DefaultEnvironment>();\n\n // Alice owns all the tokens on deployment\n\n assert_eq!(erc20.balance_of(accounts.alice), 100);\n\n // Bob does not owns tokens\n\n assert_eq!(erc20.balance_of(accounts.bob), 0);\n\n }\n\n\n\n #[ink::test]\n", "file_path": "erc20/lib.rs", "rank": 11, "score": 28181.575864082188 }, { "content": " assert_eq!(erc20.balance_of(accounts.bob), 0);\n\n assert_eq!(erc20.balance_of(accounts.eve), 0);\n\n\n\n // Transfer event triggered during initial construction.\n\n let emitted_events = ink_env::test::recorded_events().collect::<Vec<_>>();\n\n assert_eq!(emitted_events.len(), 1);\n\n assert_transfer_event(\n\n &emitted_events[0],\n\n None,\n\n Some(AccountId::from([0x01; 32])),\n\n 100,\n\n );\n\n }\n\n\n\n #[ink::test]\n\n fn transfer_from_works() {\n\n // Constructor works.\n\n let mut erc20 = Erc20::new(100,String::from(\"test\"),String::from(\"test\"),8,AccountId::from([0x01; 32]));\n\n // Transfer event triggered during initial construction.\n\n let accounts =\n", "file_path": "erc20/lib.rs", "rank": 12, "score": 28181.392657577228 }, { "content": " // Set the contract as callee and Bob as caller.\n\n let contract = ink_env::account_id::<ink_env::DefaultEnvironment>()?;\n\n ink_env::test::set_callee::<ink_env::DefaultEnvironment>(contract);\n\n ink_env::test::set_caller::<ink_env::DefaultEnvironment>(accounts.bob);\n\n\n\n // Bob fails to transfers 10 tokens to Eve.\n\n assert_eq!(\n\n erc20.transfer(accounts.eve, 10),\n\n Err(Error::InsufficientBalance)\n\n );\n\n // Alice owns all the tokens.\n\n assert_eq!(erc20.balance_of(accounts.alice), 100);\n\n assert_eq!(erc20.balance_of(accounts.bob), 0);\n\n assert_eq!(erc20.balance_of(accounts.eve), 0);\n\n\n\n // Transfer event triggered during initial construction.\n\n let emitted_events = ink_env::test::recorded_events().collect::<Vec<_>>();\n\n assert_eq!(emitted_events.len(), 1);\n\n assert_transfer_event(\n\n &emitted_events[0],\n", "file_path": "erc20/lib.rs", "rank": 13, "score": 28180.882879752615 }, { "content": " None,\n\n Some(AccountId::from([0x01; 32])),\n\n 100,\n\n );\n\n }\n\n\n\n #[ink::test]\n\n fn transfer_from_works() {\n\n // Constructor works.\n\n let mut erc20 = Erc20::new(100);\n\n // Transfer event triggered during initial construction.\n\n let accounts =\n\n ink_env::test::default_accounts::<ink_env::DefaultEnvironment>();\n\n\n\n // Bob fails to transfer tokens owned by Alice.\n\n assert_eq!(\n\n erc20.transfer_from(accounts.alice, accounts.eve, 10),\n\n Err(Error::InsufficientAllowance)\n\n );\n\n // Alice approves Bob for token transfers on her behalf.\n", "file_path": "erc20/lib.rs", "rank": 14, "score": 28180.869642313948 }, { "content": " let erc20 = Erc20::new(100,String::from(\"test\"),String::from(\"test\"),8,AccountId::from([0x01; 32]));\n\n // Transfer event triggered during initial construction.\n\n let emitted_events = ink_env::test::recorded_events().collect::<Vec<_>>();\n\n assert_transfer_event(\n\n &emitted_events[0],\n\n None,\n\n Some(AccountId::from([0x01; 32])),\n\n 100,\n\n );\n\n // Get the token total supply.\n\n assert_eq!(erc20.total_supply(), 100);\n\n }\n\n\n\n /// Get the actual balance of an account.\n\n #[ink::test]\n\n fn balance_of_works() {\n\n // Constructor works\n\n let erc20 = Erc20::new(100,String::from(\"test\"),String::from(\"test\"),8,AccountId::from([0x01; 32]));\n\n // Transfer event triggered during initial construction\n\n let emitted_events = ink_env::test::recorded_events().collect::<Vec<_>>();\n", "file_path": "erc20/lib.rs", "rank": 15, "score": 28180.703483976366 }, { "content": " 100,\n\n );\n\n // Check the second transfer event relating to the actual trasfer.\n\n assert_transfer_event(\n\n &emitted_events[1],\n\n Some(AccountId::from([0x01; 32])),\n\n Some(AccountId::from([0x02; 32])),\n\n 10,\n\n );\n\n }\n\n\n\n #[ink::test]\n\n fn invalid_transfer_should_fail() {\n\n // Constructor works.\n\n let mut erc20 = Erc20::new(100);\n\n let accounts =\n\n ink_env::test::default_accounts::<ink_env::DefaultEnvironment>();\n\n\n\n assert_eq!(erc20.balance_of(accounts.bob), 0);\n\n\n", "file_path": "erc20/lib.rs", "rank": 16, "score": 28180.555669062218 }, { "content": " value\n\n );\n\n\n\n self.env().emit_event(Transfer {\n\n from: Some(from),\n\n to: Some(to),\n\n value,\n\n });\n\n Ok(())\n\n }\n\n\n\n fn _mint_token(\n\n &mut self,\n\n to: AccountId,\n\n amount: Balance,\n\n ) -> bool {\n\n let total_supply = self.total_supply();\n\n assert_eq!(total_supply + amount >= total_supply, true);\n\n let to_balance = self.balance_of_or_zero(&to);\n\n assert_eq!(to_balance + amount >= to_balance, true);\n", "file_path": "erc20/lib.rs", "rank": 17, "score": 28180.50934446778 }, { "content": " }\n\n }\n\n\n\n #[cfg(feature = \"ink-experimental-engine\")]\n\n #[cfg(test)]\n\n mod tests_experimental_engine {\n\n use super::*;\n\n\n\n use ink_env::Clear;\n\n use ink_lang as ink;\n\n\n\n type Event = <Erc20 as ::ink_lang::BaseEvent>::Type;\n\n\n\n fn assert_transfer_event(\n\n event: &ink_env::test::EmittedEvent,\n\n expected_from: Option<AccountId>,\n\n expected_to: Option<AccountId>,\n\n expected_value: Balance,\n\n ) {\n\n let decoded_event = <Event as scale::Decode>::decode(&mut &event.data[..])\n", "file_path": "erc20/lib.rs", "rank": 18, "score": 28180.465091283477 }, { "content": " ink_env::test::default_accounts::<ink_env::DefaultEnvironment>()\n\n .expect(\"Cannot get accounts\");\n\n\n\n // Alice approves Bob for token transfers on her behalf.\n\n let alice_balance = erc20.balance_of(accounts.alice);\n\n let initial_allowance = alice_balance + 2;\n\n assert_eq!(erc20.approve(accounts.bob, initial_allowance), Ok(()));\n\n\n\n // Get contract address.\n\n let callee = ink_env::account_id::<ink_env::DefaultEnvironment>()\n\n .unwrap_or_else(|_| [0x0; 32].into());\n\n // Create call.\n\n let mut data =\n\n ink_env::test::CallData::new(ink_env::call::Selector::new([0x00; 4])); // balance_of\n\n data.push_arg(&accounts.bob);\n\n // Push the new execution context to set Bob as caller.\n\n ink_env::test::push_execution_context::<ink_env::DefaultEnvironment>(\n\n accounts.bob,\n\n callee,\n\n 1000000,\n", "file_path": "erc20/lib.rs", "rank": 19, "score": 28180.181655402914 }, { "content": " balances.insert(owner, initial_supply);\n\n let instance = Self {\n\n total_supply: Lazy::new(initial_supply),\n\n balances,\n\n allowances: StorageHashMap::new(),\n\n name,\n\n symbol,\n\n decimals,\n\n owner,\n\n check_points:StorageHashMap::new(),\n\n num_check_points:StorageHashMap::new(),\n\n delegates:StorageHashMap::new()\n\n };\n\n Self::env().emit_event(Transfer {\n\n from: None,\n\n to: Some(owner),\n\n value: initial_supply,\n\n });\n\n instance._mint_token(owner, initial_supply);\n\n instance\n", "file_path": "erc20/lib.rs", "rank": 20, "score": 28179.923752676947 }, { "content": " }\n\n #[ink(constructor)]\n\n pub fn default() -> Self {\n\n Self::new(Default::default(),Default::default(),Default::default(),Default::default(),Default::default())\n\n }\n\n /// Returns the total token supply.\n\n #[ink(message)]\n\n pub fn total_supply(&self) -> Balance {\n\n *self.total_supply\n\n }\n\n\n\n /// Returns the account balance for the specified `owner`.\n\n ///\n\n /// Returns `0` if the account is non-existent.\n\n #[ink(message)]\n\n pub fn balance_of(&self, owner: AccountId) -> Balance {\n\n self.balances.get(&owner).copied().unwrap_or(0)\n\n }\n\n\n\n /// Returns the amount which `spender` is still allowed to withdraw from `owner`.\n", "file_path": "erc20/lib.rs", "rank": 21, "score": 28179.769689949393 }, { "content": " ink_env::test::default_accounts::<ink_env::DefaultEnvironment>();\n\n\n\n // Alice approves Bob for token transfers on her behalf.\n\n let alice_balance = erc20.balance_of(accounts.alice);\n\n let initial_allowance = alice_balance + 2;\n\n assert_eq!(erc20.approve(accounts.bob, initial_allowance), Ok(()));\n\n\n\n // Get contract address.\n\n let callee = ink_env::account_id::<ink_env::DefaultEnvironment>()?;\n\n ink_env::test::set_callee::<ink_env::DefaultEnvironment>(callee);\n\n ink_env::test::set_caller::<ink_env::DefaultEnvironment>(accounts.bob);\n\n\n\n // Bob tries to transfer tokens from Alice to Eve.\n\n let emitted_events_before =\n\n ink_env::test::recorded_events().collect::<Vec<_>>();\n\n assert_eq!(\n\n erc20.transfer_from(accounts.alice, accounts.eve, alice_balance + 1),\n\n Err(Error::InsufficientBalance)\n\n );\n\n // Allowance must have stayed the same\n", "file_path": "erc20/lib.rs", "rank": 22, "score": 28179.623951747082 }, { "content": " data.push_arg(&accounts.bob);\n\n // Push the new execution context to set Bob as caller.\n\n ink_env::test::push_execution_context::<ink_env::DefaultEnvironment>(\n\n accounts.bob,\n\n callee,\n\n 1000000,\n\n 1000000,\n\n data,\n\n );\n\n\n\n // Bob transfers tokens from Alice to Eve.\n\n assert_eq!(\n\n erc20.transfer_from(accounts.alice, accounts.eve, 10),\n\n Ok(())\n\n );\n\n // Eve owns tokens.\n\n assert_eq!(erc20.balance_of(accounts.eve), 10);\n\n\n\n // Check all transfer events that happened during the previous calls:\n\n let emitted_events = ink_env::test::recorded_events().collect::<Vec<_>>();\n", "file_path": "erc20/lib.rs", "rank": 23, "score": 28179.608617439837 }, { "content": " }\n\n\n\n }\n\n\n\n /// Unit tests.\n\n #[cfg(not(feature = \"ink-experimental-engine\"))]\n\n #[cfg(test)]\n\n mod tests {\n\n /// Imports all the definitions from the outer scope so we can use them here.\n\n use super::*;\n\n\n\n type Event = <Erc20 as ::ink_lang::BaseEvent>::Type;\n\n\n\n use ink_lang as ink;\n\n\n\n fn assert_transfer_event(\n\n event: &ink_env::test::EmittedEvent,\n\n expected_from: Option<AccountId>,\n\n expected_to: Option<AccountId>,\n\n expected_value: Balance,\n", "file_path": "erc20/lib.rs", "rank": 24, "score": 28179.33016138257 }, { "content": " let accounts =\n\n ink_env::test::default_accounts::<ink_env::DefaultEnvironment>()\n\n .expect(\"Cannot get accounts\");\n\n\n\n assert_eq!(erc20.balance_of(accounts.bob), 0);\n\n // Alice transfers 10 tokens to Bob.\n\n assert_eq!(erc20.transfer(accounts.bob, 10), Ok(()));\n\n // Bob owns 10 tokens.\n\n assert_eq!(erc20.balance_of(accounts.bob), 10);\n\n\n\n let emitted_events = ink_env::test::recorded_events().collect::<Vec<_>>();\n\n assert_eq!(emitted_events.len(), 2);\n\n // Check first transfer event related to ERC-20 instantiation.\n\n assert_transfer_event(\n\n &emitted_events[0],\n\n None,\n\n Some(AccountId::from([0x01; 32])),\n\n 100,\n\n );\n\n // Check the second transfer event relating to the actual trasfer.\n", "file_path": "erc20/lib.rs", "rank": 25, "score": 28179.2679474653 }, { "content": " self.owner = to;\n\n true\n\n }\n\n\n\n /// Transfers `value` tokens on the behalf of `from` to the account `to`.\n\n ///\n\n /// This can be used to allow a contract to transfer tokens on ones behalf and/or\n\n /// to charge fees in sub-currencies, for example.\n\n ///\n\n /// On success a `Transfer` event is emitted.\n\n ///\n\n /// # Errors\n\n ///\n\n /// Returns `InsufficientAllowance` error if there are not enough tokens allowed\n\n /// for the caller to withdraw from `from`.\n\n ///\n\n /// Returns `InsufficientBalance` error if there are not enough tokens on\n\n /// the account balance of `from`.\n\n #[ink(message)]\n\n pub fn transfer_from(\n", "file_path": "erc20/lib.rs", "rank": 26, "score": 28178.780918531476 }, { "content": " assert_eq!(erc20.approve(accounts.bob, 10), Ok(()));\n\n\n\n // The approve event takes place.\n\n assert_eq!(ink_env::test::recorded_events().count(), 2);\n\n\n\n // Set the contract as callee and Bob as caller.\n\n let contract = ink_env::account_id::<ink_env::DefaultEnvironment>()?;\n\n ink_env::test::set_callee::<ink_env::DefaultEnvironment>(contract);\n\n ink_env::test::set_caller::<ink_env::DefaultEnvironment>(accounts.bob);\n\n\n\n // Bob transfers tokens from Alice to Eve.\n\n assert_eq!(\n\n erc20.transfer_from(accounts.alice, accounts.eve, 10),\n\n Ok(())\n\n );\n\n // Eve owns tokens.\n\n assert_eq!(erc20.balance_of(accounts.eve), 10);\n\n\n\n // Check all transfer events that happened during the previous calls:\n\n let emitted_events = ink_env::test::recorded_events().collect::<Vec<_>>();\n", "file_path": "erc20/lib.rs", "rank": 27, "score": 28178.667997151817 }, { "content": " ///\n\n /// Returns `InsufficientBalance` error if there are not enough tokens on\n\n /// the caller's account balance.\n\n fn transfer_from_to(\n\n &mut self,\n\n from: AccountId,\n\n to: AccountId,\n\n value: Balance,\n\n ) -> Result<()> {\n\n let from_balance = self.balance_of(from);\n\n if from_balance < value {\n\n return Err(Error::InsufficientBalance)\n\n }\n\n self.balances.insert(from, from_balance - value);\n\n let to_balance = self.balance_of(to);\n\n self.balances.insert(to, to_balance + value);\n\n\n\n self.move_delegates(\n\n self.delegates.get(&from).unwrap_or(&AccountId::default()).clone() ,\n\n self.delegates.get(&to).unwrap_or(&AccountId::default()).clone(),\n", "file_path": "erc20/lib.rs", "rank": 28, "score": 28177.5120234821 }, { "content": " owner: AccountId,\n\n }\n\n\n\n\n\n\n\n\n\n /// Event emitted when a token transfer occurs.\n\n #[ink(event)]\n\n pub struct Transfer {\n\n #[ink(topic)]\n\n from: Option<AccountId>,\n\n #[ink(topic)]\n\n to: Option<AccountId>,\n\n value: Balance,\n\n }\n\n\n\n /// Event emitted when an approval occurs that `spender` is allowed to withdraw\n\n /// up to the amount of `value` tokens from `owner`.\n\n #[ink(event)]\n\n pub struct Approval {\n", "file_path": "erc20/lib.rs", "rank": 29, "score": 28177.48323558913 }, { "content": "\n\n /// The total supply was applied.\n\n #[ink::test]\n\n fn total_supply_works() {\n\n // Constructor works.\n\n let erc20 = Erc20::new(100);\n\n // Transfer event triggered during initial construction.\n\n let emitted_events = ink_env::test::recorded_events().collect::<Vec<_>>();\n\n assert_transfer_event(\n\n &emitted_events[0],\n\n None,\n\n Some(AccountId::from([0x01; 32])),\n\n 100,\n\n );\n\n // Get the token total supply.\n\n assert_eq!(erc20.total_supply(), 100);\n\n }\n\n\n\n /// Get the actual balance of an account.\n\n #[ink::test]\n", "file_path": "erc20/lib.rs", "rank": 30, "score": 28177.26577388408 }, { "content": " #[ink(message)]\n\n pub fn transfer(&mut self, to: AccountId, value: Balance) -> Result<()> {\n\n let from = self.env().caller();\n\n self.transfer_from_to(from, to, value)\n\n }\n\n\n\n /// Allows `spender` to withdraw from the caller's account multiple times, up to\n\n /// the `value` amount.\n\n ///\n\n /// If this function is called again it overwrites the current allowance with `value`.\n\n ///\n\n /// An `Approval` event is emitted.\n\n #[ink(message)]\n\n pub fn approve(&mut self, spender: AccountId, value: Balance) -> Result<()> {\n\n let owner = self.env().caller();\n\n self.allowances.insert((owner, spender), value);\n\n self.env().emit_event(Approval {\n\n owner,\n\n spender,\n\n value,\n", "file_path": "erc20/lib.rs", "rank": 31, "score": 28176.990419113565 }, { "content": " assert_eq!(emitted_events.len(), 3);\n\n assert_transfer_event(\n\n &emitted_events[0],\n\n None,\n\n Some(AccountId::from([0x01; 32])),\n\n 100,\n\n );\n\n // The second event `emitted_events[1]` is an Approve event that we skip checking.\n\n assert_transfer_event(\n\n &emitted_events[2],\n\n Some(AccountId::from([0x01; 32])),\n\n Some(AccountId::from([0x05; 32])),\n\n 10,\n\n );\n\n }\n\n\n\n #[ink::test]\n\n fn allowance_must_not_change_on_failed_transfer() {\n\n let mut erc20 = Erc20::new(100,String::from(\"test\"),String::from(\"test\"),8,AccountId::from([0x01; 32]));\n\n let accounts =\n", "file_path": "erc20/lib.rs", "rank": 32, "score": 28176.897637981587 }, { "content": " 1000000,\n\n data,\n\n );\n\n\n\n // Bob tries to transfer tokens from Alice to Eve.\n\n let emitted_events_before = ink_env::test::recorded_events();\n\n assert_eq!(\n\n erc20.transfer_from(accounts.alice, accounts.eve, alice_balance + 1),\n\n Err(Error::InsufficientBalance)\n\n );\n\n // Allowance must have stayed the same\n\n assert_eq!(\n\n erc20.allowance(accounts.alice, accounts.bob),\n\n initial_allowance\n\n );\n\n // No more events must have been emitted\n\n let emitted_events_after = ink_env::test::recorded_events();\n\n assert_eq!(emitted_events_before.count(), emitted_events_after.count());\n\n }\n\n }\n", "file_path": "erc20/lib.rs", "rank": 33, "score": 28175.858801504233 }, { "content": " fn new_works() {\n\n // Constructor works.\n\n let _erc20 = Erc20::new(100,String::from(\"test\"),String::from(\"test\"),8,AccountId::from([0x01; 32]));\n\n\n\n // Transfer event triggered during initial construction.\n\n let emitted_events = ink_env::test::recorded_events().collect::<Vec<_>>();\n\n assert_eq!(1, emitted_events.len());\n\n\n\n assert_transfer_event(\n\n &emitted_events[0],\n\n None,\n\n Some(AccountId::from([0x01; 32])),\n\n 100,\n\n );\n\n }\n\n\n\n /// The total supply was applied.\n\n #[ink::test]\n\n fn total_supply_works() {\n\n // Constructor works.\n", "file_path": "erc20/lib.rs", "rank": 34, "score": 28175.772122003797 }, { "content": " ) {\n\n let decoded_event = <Event as scale::Decode>::decode(&mut &event.data[..])\n\n .expect(\"encountered invalid contract event data buffer\");\n\n if let Event::Transfer(Transfer { from, to, value }) = decoded_event {\n\n assert_eq!(from, expected_from, \"encountered invalid Transfer.from\");\n\n assert_eq!(to, expected_to, \"encountered invalid Transfer.to\");\n\n assert_eq!(value, expected_value, \"encountered invalid Trasfer.value\");\n\n } else {\n\n panic!(\"encountered unexpected event kind: expected a Transfer event\")\n\n }\n\n let expected_topics = vec![\n\n encoded_into_hash(&PrefixedValue {\n\n value: b\"Erc20::Transfer\",\n\n prefix: b\"\",\n\n }),\n\n encoded_into_hash(&PrefixedValue {\n\n prefix: b\"Erc20::Transfer::from\",\n\n value: &expected_from,\n\n }),\n\n encoded_into_hash(&PrefixedValue {\n", "file_path": "erc20/lib.rs", "rank": 35, "score": 28175.57637833235 }, { "content": " }),\n\n encoded_into_hash(&PrefixedValue {\n\n prefix: b\"Erc20::Transfer::value\",\n\n value: &expected_value,\n\n }),\n\n ];\n\n\n\n let topics = event.topics.clone();\n\n for (n, (actual_topic, expected_topic)) in\n\n topics.iter().zip(expected_topics).enumerate()\n\n {\n\n let mut topic_hash = Hash::clear();\n\n let len = actual_topic.len();\n\n topic_hash.as_mut()[0..len].copy_from_slice(&actual_topic[0..len]);\n\n\n\n assert_eq!(\n\n topic_hash, expected_topic,\n\n \"encountered invalid topic at {}\",\n\n n\n\n );\n", "file_path": "erc20/lib.rs", "rank": 36, "score": 28175.142459749106 }, { "content": " &mut self,\n\n from: AccountId,\n\n to: AccountId,\n\n value: Balance,\n\n ) -> Result<()> {\n\n let caller = self.env().caller();\n\n let allowance = self.allowance(from, caller);\n\n if allowance < value {\n\n return Err(Error::InsufficientAllowance)\n\n }\n\n self.transfer_from_to(from, to, value)?;\n\n self.allowances.insert((from, caller), allowance - value);\n\n Ok(())\n\n }\n\n\n\n /// Transfers `value` amount of tokens from the caller's account to account `to`.\n\n ///\n\n /// On success a `Transfer` event is emitted.\n\n ///\n\n /// # Errors\n", "file_path": "erc20/lib.rs", "rank": 37, "score": 28174.850232491346 }, { "content": " assert_eq!(emitted_events.len(), 3);\n\n assert_transfer_event(\n\n &emitted_events[0],\n\n None,\n\n Some(AccountId::from([0x01; 32])),\n\n 100,\n\n );\n\n // The second event `emitted_events[1]` is an Approve event that we skip checking.\n\n assert_transfer_event(\n\n &emitted_events[2],\n\n Some(AccountId::from([0x01; 32])),\n\n Some(AccountId::from([0x05; 32])),\n\n 10,\n\n );\n\n }\n\n\n\n #[ink::test]\n\n fn allowance_must_not_change_on_failed_transfer() {\n\n let mut erc20 = Erc20::new(100);\n\n let accounts =\n", "file_path": "erc20/lib.rs", "rank": 38, "score": 28174.767596971084 }, { "content": " lower = center;\n\n } else {\n\n upper = center - 1;\n\n }\n\n }\n\n let outer_cp:Checkpoint = self.check_points.get(&(account,lower)).unwrap().clone();\n\n return outer_cp.votes;\n\n }\n\n #[ink(message)]\n\n pub fn delegate(&mut self,delegatee:AccountId) -> bool {\n\n let delegator = self.env().caller();\n\n let current_delegate = self.delegates.get(&delegator).unwrap_or(&AccountId::default()).clone();\n\n let delegator_balance = self.balance_of(delegator);\n\n self.delegates.insert(delegator,delegatee);\n\n Self::env().emit_event(DelegateChanged {\n\n delegator,\n\n current_delegate,\n\n delegatee\n\n });\n\n self.move_delegates(current_delegate, delegatee, delegator_balance);\n", "file_path": "erc20/lib.rs", "rank": 39, "score": 28174.74155636588 }, { "content": " .expect(\"encountered invalid contract event data buffer\");\n\n if let Event::Transfer(Transfer { from, to, value }) = decoded_event {\n\n assert_eq!(from, expected_from, \"encountered invalid Transfer.from\");\n\n assert_eq!(to, expected_to, \"encountered invalid Transfer.to\");\n\n assert_eq!(value, expected_value, \"encountered invalid Trasfer.value\");\n\n } else {\n\n panic!(\"encountered unexpected event kind: expected a Transfer event\")\n\n }\n\n let expected_topics = vec![\n\n encoded_into_hash(&PrefixedValue {\n\n value: b\"Erc20::Transfer\",\n\n prefix: b\"\",\n\n }),\n\n encoded_into_hash(&PrefixedValue {\n\n prefix: b\"Erc20::Transfer::from\",\n\n value: &expected_from,\n\n }),\n\n encoded_into_hash(&PrefixedValue {\n\n prefix: b\"Erc20::Transfer::to\",\n\n value: &expected_to,\n", "file_path": "erc20/lib.rs", "rank": 40, "score": 28174.6762318141 }, { "content": " }\n\n }\n\n\n\n /// The default constructor does its job.\n\n #[ink::test]\n\n fn new_works() {\n\n // Constructor works.\n\n let _erc20 = Erc20::new(100);\n\n\n\n // Transfer event triggered during initial construction.\n\n let emitted_events = ink_env::test::recorded_events().collect::<Vec<_>>();\n\n assert_eq!(1, emitted_events.len());\n\n\n\n assert_transfer_event(\n\n &emitted_events[0],\n\n None,\n\n Some(AccountId::from([0x01; 32])),\n\n 100,\n\n );\n\n }\n", "file_path": "erc20/lib.rs", "rank": 41, "score": 28173.8762330138 }, { "content": " prefix: b\"Erc20::Transfer::to\",\n\n value: &expected_to,\n\n }),\n\n encoded_into_hash(&PrefixedValue {\n\n prefix: b\"Erc20::Transfer::value\",\n\n value: &expected_value,\n\n }),\n\n ];\n\n for (n, (actual_topic, expected_topic)) in\n\n event.topics.iter().zip(expected_topics).enumerate()\n\n {\n\n let topic = actual_topic\n\n .decode::<Hash>()\n\n .expect(\"encountered invalid topic encoding\");\n\n assert_eq!(topic, expected_topic, \"encountered invalid topic at {}\", n);\n\n }\n\n }\n\n\n\n /// The default constructor does its job.\n\n #[ink::test]\n", "file_path": "erc20/lib.rs", "rank": 42, "score": 28173.545158505956 }, { "content": " self.total_supply += amount;\n\n self.balances.insert(to, to_balance + amount);\n\n self.env().emit_event(Transfer {\n\n from: None,\n\n to: Some(to),\n\n value: amount,\n\n });\n\n true\n\n }\n\n\n\n #[ink(message)]\n\n pub fn get_current_votes(&self,user:AccountId) -> u128 {\n\n let n_checkpoints = self.num_check_points.get(&user).unwrap().clone();\n\n let check_point:Checkpoint = self.check_points.get(&(user,n_checkpoints - 1)).unwrap().clone();\n\n return if n_checkpoints > 0 {check_point.votes} else { 0 } ;\n\n }\n\n #[ink(message)]\n\n pub fn get_prior_votes(&self,account:AccountId,block_number:u32) -> u128 {\n\n assert!(block_number < self.env().block_number());\n\n let n_checkpoints = self.num_check_points.get(&account).unwrap().clone();\n", "file_path": "erc20/lib.rs", "rank": 43, "score": 28173.40836329784 }, { "content": " #[ink(topic)]\n\n owner: AccountId,\n\n #[ink(topic)]\n\n spender: AccountId,\n\n value: Balance,\n\n }\n\n\n\n #[ink(event)]\n\n pub struct DelegateVotesChanged {\n\n #[ink(topic)]\n\n delegate: AccountId,\n\n #[ink(topic)]\n\n old_votes: u128,\n\n new_votes: u128,\n\n }\n\n #[ink(event)]\n\n pub struct DelegateChanged {\n\n delegator:AccountId,\n\n current_delegate:AccountId,\n\n delegatee:AccountId\n", "file_path": "erc20/lib.rs", "rank": 44, "score": 28172.080278337293 }, { "content": "\n\n /// For calculating the event topic hash.\n\n struct PrefixedValue<'a, 'b, T> {\n\n pub prefix: &'a [u8],\n\n pub value: &'b T,\n\n }\n\n\n\n impl<X> scale::Encode for PrefixedValue<'_, '_, X>\n\n where\n\n X: scale::Encode,\n\n {\n\n #[inline]\n\n fn size_hint(&self) -> usize {\n\n self.prefix.size_hint() + self.value.size_hint()\n\n }\n\n\n\n #[inline]\n\n fn encode_to<T: scale::Output + ?Sized>(&self, dest: &mut T) {\n\n self.prefix.encode_to(dest);\n\n self.value.encode_to(dest);\n", "file_path": "erc20/lib.rs", "rank": 45, "score": 28171.146828205896 }, { "content": " }\n\n }\n\n true\n\n }\n\n\n\n fn write_check_point(&mut self,delegatee:AccountId,n_checkpoints:u32,old_votes:u128,new_votes:u128) -> bool {\n\n let block_number = self.env().block_number();\n\n let check_point:Checkpoint = self.check_points.get(&(delegatee,n_checkpoints - 1)).unwrap().clone();\n\n if n_checkpoints>0 && check_point.from_block == block_number {\n\n self.check_points.insert((delegatee, n_checkpoints - 1), Checkpoint{from_block:check_point.from_block,votes:new_votes});\n\n } else {\n\n self.check_points.insert((delegatee, n_checkpoints),Checkpoint{from_block:block_number,votes:new_votes});\n\n self.num_check_points.insert(delegatee,n_checkpoints + 1 );\n\n }\n\n Self::env().emit_event(DelegateVotesChanged {\n\n delegate: delegatee,\n\n old_votes,\n\n new_votes,\n\n });\n\n true\n", "file_path": "erc20/lib.rs", "rank": 46, "score": 28170.053934218926 }, { "content": " assert_eq!(\n\n erc20.allowance(accounts.alice, accounts.bob),\n\n initial_allowance\n\n );\n\n // No more events must have been emitted\n\n let emitted_events_after =\n\n ink_env::test::recorded_events().collect::<Vec<_>>();\n\n assert_eq!(emitted_events_before.len(), emitted_events_after.len());\n\n }\n\n }\n\n\n\n #[cfg(test)]\n\n fn encoded_into_hash<T>(entity: &T) -> Hash\n\n where\n\n T: scale::Encode,\n\n {\n\n use ink_env::{\n\n hash::{\n\n Blake2x256,\n\n CryptoHash,\n", "file_path": "erc20/lib.rs", "rank": 47, "score": 28169.61483517576 }, { "content": "\n\n true\n\n }\n\n\n\n\n\n fn move_delegates(&mut self,src_rep:AccountId,dst_rep:AccountId,amount:u128) -> bool {\n\n if src_rep != dst_rep && amount > 0 {\n\n if src_rep != AccountId::default() {\n\n let src_rep_num = self.num_check_points.get(&src_rep).unwrap_or(&0).clone();\n\n let check_point:Checkpoint = self.check_points.get(&(src_rep,src_rep_num - 1)).unwrap().clone();\n\n let src_rep_old = if src_rep_num > 0 {check_point.votes} else { 0 } ;\n\n let src_rep_new = src_rep_old - amount;\n\n self.write_check_point(src_rep,src_rep_num,src_rep_old,src_rep_new);\n\n }\n\n if dst_rep != AccountId::default() {\n\n let dst_rep_num = self.num_check_points.get(&dst_rep).copied().unwrap_or(0);\n\n let check_point:Checkpoint = self.check_points.get(&(dst_rep,dst_rep_num - 1)).unwrap().clone();\n\n let dst_rep_old = if dst_rep_num > 0 {check_point.votes} else { 0 } ;\n\n let dsp_rep_new = dst_rep_old + amount;\n\n self.write_check_point(dst_rep,dst_rep_num,dst_rep_old,dsp_rep_new);\n", "file_path": "erc20/lib.rs", "rank": 48, "score": 28167.745436053265 }, { "content": " if n_checkpoints == 0 {\n\n return 0;\n\n }\n\n let check_point:Checkpoint = self.check_points.get(&(account,n_checkpoints - 1)).unwrap().clone();\n\n if check_point.from_block <= block_number {\n\n return check_point.votes;\n\n }\n\n // Next check implicit zero balance\n\n let check_point_zero:Checkpoint = self.check_points.get(&(account,0)).unwrap().clone();\n\n if check_point_zero.from_block > block_number {\n\n return 0;\n\n }\n\n let mut lower:u32 = 0;\n\n let mut upper:u32 = n_checkpoints - 1;\n\n while upper > lower {\n\n let center:u32 = upper - (upper - lower) / 2; // ceil, avoiding overflow\n\n let cp:Checkpoint = self.check_points.get(&(account,center)).unwrap().clone();\n\n if cp.from_block == block_number {\n\n return cp.votes;\n\n } else if cp.from_block < block_number {\n", "file_path": "erc20/lib.rs", "rank": 49, "score": 28167.445411391967 }, { "content": " HashOutput,\n\n },\n\n Clear,\n\n };\n\n let mut result = Hash::clear();\n\n let len_result = result.as_ref().len();\n\n let encoded = entity.encode();\n\n let len_encoded = encoded.len();\n\n if len_encoded <= len_result {\n\n result.as_mut()[..len_encoded].copy_from_slice(&encoded);\n\n return result\n\n }\n\n let mut hash_output = <<Blake2x256 as HashOutput>::Type as Default>::default();\n\n <Blake2x256 as CryptoHash>::hash(&encoded, &mut hash_output);\n\n let copy_len = core::cmp::min(hash_output.len(), len_result);\n\n result.as_mut()[0..copy_len].copy_from_slice(&hash_output[0..copy_len]);\n\n result\n\n }\n\n}\n", "file_path": "erc20/lib.rs", "rank": 50, "score": 28165.62355142937 }, { "content": " index:1,\n\n symbol:Default::default(),\n\n token:BTreeMap::new(),\n\n name:Default::default(),\n\n Infos:StorageHashMap::new(),\n\n }\n\n }\n\n #[ink(constructor)]\n\n pub fn default() -> Self{\n\n Self::new()\n\n } \n\n #[ink(message)]\n\n pub fn mint_erc20(&mut self,erc20_hash: Hash,version: u32,name:String,symbol:String ,initial_supply:u64,adr: AccountId,decimals:u8)->bool{\n\n\n\n let salt=version.to_le_bytes();\n\n let instance_params=Erc20::new(initial_supply.into(),name.clone(),symbol.clone(),decimals,adr)\n\n .endowment(RENT_VALUE)\n\n .code_hash(erc20_hash)\n\n .salt_bytes(salt)\n\n .params();\n", "file_path": "erc20_factory/lib.rs", "rank": 51, "score": 26606.964772621955 }, { "content": "\n\n const RENT_VALUE: u128 = 1000 * 1_000_000_000_000;\n\n\n\n\n\n\n\n #[ink (storage)]\n\n pub struct Erc20Factory{\n\n owner:AccountId,\n\n index:u64,\n\n symbol:String,\n\n name:String,\n\n token:BTreeMap<u64,AccountId>,\n\n Infos:StorageHashMap<u64,Info>,\n\n\n\n }\n\n impl Erc20Factory {\n\n #[ink(constructor)]\n\n pub fn new()->Self{\n\n Self{\n\n owner:Default::default(),\n", "file_path": "erc20_factory/lib.rs", "rank": 52, "score": 26604.897937430538 }, { "content": "\n\n#![cfg_attr(not(feature = \"std\"), no_std)]\n\nextern crate alloc;\n\nuse ink_lang as ink;\n\n\n\npub use self::erc20_factory::{\n\n Erc20Factory,\n\n};\n\n#[ink::contract]\n\nmod erc20_factory{\n\n use alloc::string::String;\n\n use erc20::Erc20;\n\n use ink_prelude::vec::Vec;\n\n use core::ptr::null;\n\n use ink_prelude::collections::BTreeMap;\n\n use ink_storage::{\n\n collections::{\n\n HashMap as StorageHashMap,\n\n },\n\n traits::{\n", "file_path": "erc20_factory/lib.rs", "rank": 53, "score": 26600.468219306953 }, { "content": " PackedLayout,\n\n SpreadLayout,\n\n },\n\n };\n\n #[derive(scale::Encode,scale::Decode, Clone, SpreadLayout,PackedLayout)]\n\n #[cfg_attr(\n\n feature = \"std\",\n\n derive(\n\n scale_info::TypeInfo,\n\n ink_storage::traits::StorageLayout\n\n )\n\n )]\n\n \n\n pub struct Info{\n\n owner:AccountId,\n\n index:u64,\n\n symbol:String,\n\n initial_supply:u64,\n\n \n\n }\n", "file_path": "erc20_factory/lib.rs", "rank": 54, "score": 26592.76815661827 }, { "content": "\n\n let instance_result=ink_env::instantiate_contract(&instance_params);\n\n let contract_addr=instance_result.expect(\"failed at instantiating the `ERC20` contract\");\n\n //self.symbol=symbol.clone();\n\n //self.name=name.clone();\n\n //self.token.insert(self.index,contract_addr);\n\n self.Infos.insert(self.index,\n\n Info{\n\n owner:adr,\n\n index:self.index,\n\n symbol,\n\n initial_supply,\n\n }\n\n );\n\n self.index+=1;\n\n true\n\n \n\n }\n\n\n\n #[ink(message)]\n", "file_path": "erc20_factory/lib.rs", "rank": 55, "score": 26587.324216845594 }, { "content": " pub fn get_Block(&self) -> Timestamp {\n\n self.env().block_timestamp()\n\n }\n\n\n\n #[ink(message)]\n\n pub fn get_transaction(&self,index:u64) -> Info {\n\n self.Infos.get(&index).unwrap().clone()\n\n }\n\n }\n\n}", "file_path": "erc20_factory/lib.rs", "rank": 56, "score": 26581.535114179926 }, { "content": "# RainbowDAO-Protocol-Ink-Test-Version-05", "file_path": "README.md", "rank": 57, "score": 15518.33748698528 }, { "content": " owner: AccountId,\n\n name: String,\n\n symbol: String,\n\n total_supply: u64,\n\n decimals: u8,\n\n }\n\n\n\n #[derive(\n\n Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode, SpreadLayout, PackedLayout, Default\n\n )]\n\n #[cfg_attr(\n\n feature = \"std\",\n\n derive(::scale_info::TypeInfo, ::ink_storage::traits::StorageLayout)\n\n )]\n\n pub struct DAOInitParams {\n\n base: BaseParam,\n\n erc20: ERC20Param,\n\n }\n\n\n\n\n", "file_path": "dao_manager/lib.rs", "rank": 60, "score": 32.56970754014776 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\nextern crate alloc;\n\nuse ink_lang as ink;\n\n\n\n#[ink::contract]\n\nmod dao_categeory{\n\n use alloc::string::String;\n\n use ink_prelude::vec::Vec;\n\n use ink_storage::{\n\n collections::HashMap as StorageHashMap,\n\n };\n\n\n\n #[ink(storage)]\n\n pub struct Daocategeory{\n\n owner:AccountId,\n\n index:u64,\n\n categeorys:StorageHashMap<u64,String>\n\n }\n\n impl Daocategeory{\n\n #[ink(constructor)]\n", "file_path": "dao_category/lib.rs", "rank": 62, "score": 31.30385857733161 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\nextern crate alloc;\n\nuse ink_lang as ink;\n\npub use self::dao_base::{\n\n DaoBase,\n\n};\n\n\n\n#[ink::contract]\n\nmod dao_base {\n\n\n\n use alloc::string::String;\n\n use ink_storage::{\n\n collections::HashMap as StorageHashMap,\n\n traits::{PackedLayout, SpreadLayout},\n\n };\n\n #[derive(scale::Encode, scale::Decode, Clone, SpreadLayout, PackedLayout)]\n\n #[cfg_attr(\n\n feature = \"std\", \n\n derive(scale_info::TypeInfo, ink_storage::traits::StorageLayout)\n\n )]\n", "file_path": "dao_base/lib.rs", "rank": 63, "score": 30.030224596710664 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\nextern crate alloc;\n\nuse ink_lang as ink;\n\npub use self::dao_vote::{\n\n DaoVote\n\n};\n\n\n\n#[ink::contract]\n\nmod dao_vote {\n\n use alloc::string::String;\n\n use ink_prelude::vec::Vec;\n\n use erc20::Erc20;\n\n use ink_storage::{\n\n collections::HashMap as StorageHashMap,\n\n traits::{\n\n PackedLayout,\n\n SpreadLayout,\n\n }\n\n };\n\n\n", "file_path": "dao_vote/lib.rs", "rank": 64, "score": 29.651539371431063 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\n\n\nuse ink_lang as ink;\n\n\n\nextern crate alloc;\n\npub use self::dao_govnance::{\n\n DaoGovnance,\n\n};\n\n\n\n#[ink::contract]\n\nmod dao_govnance {\n\n use route_manage::RouteManage;\n\n use erc20::Erc20;\n\n //use core::Core;\n\n use alloc::string::String;\n\n\n\n use ink_prelude::vec::Vec;\n\n use ink_prelude::collections::BTreeMap;\n\n\n\n use ink_storage::{\n", "file_path": "dao_govnance/lib.rs", "rank": 65, "score": 29.291022733697456 }, { "content": " #[cfg_attr(\n\n feature = \"std\",\n\n derive(::scale_info::TypeInfo, ::ink_storage::traits::StorageLayout)\n\n )]\n\n pub struct BaseParam {\n\n owner: AccountId,\n\n name: String,\n\n logo: String,\n\n desc: String,\n\n }\n\n\n\n /// DAO component instance addresses\n\n #[derive(\n\n Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode, SpreadLayout, PackedLayout, Default\n\n )]\n\n #[cfg_attr(\n\n feature = \"std\",\n\n derive(::scale_info::TypeInfo, ::ink_storage::traits::StorageLayout)\n\n )]\n\n pub struct ERC20Param {\n", "file_path": "dao_manager/lib.rs", "rank": 66, "score": 29.11291082039389 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\n\n\nuse ink_lang as ink;\n\n\n\n#[ink::contract]\n\nmod incomeProportion {\n\n\n\n /// Defines the storage of your contract.\n\n /// Add new fields to the below struct in order\n\n /// to add new static storage fields to your contract.\n\n #[ink(storage)]\n\n pub struct IncomeProportion {\n\n /// Stores a single `bool` value on the storage.\n\n value: bool,\n\n }\n\n\n\n impl IncomeProportion {\n\n /// Constructor that initializes the `bool` value to the given `init_value`.\n\n #[ink(constructor)]\n\n pub fn new(init_value: bool) -> Self {\n", "file_path": "incomeProportion/lib.rs", "rank": 67, "score": 28.98037555474567 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\nextern crate alloc;\n\npub use self::income_category::{\n\n IncomeCategory,\n\n};\n\n\n\nuse ink_lang as ink;\n\n\n\n#[ink::contract]\n\nmod income_category {\n\n //use ink_prelude::vec::Vec;\n\n use erc20::Erc20;\n\n use dao_vault::DaoVault;\n\n use alloc::string::String;\n\n use ink_prelude::vec::Vec;\n\n use ink_storage::{\n\n collections::HashMap as StorageHashMap,\n\n traits::{\n\n PackedLayout,\n\n SpreadLayout,\n", "file_path": "income_category/lib.rs", "rank": 70, "score": 28.246749987347627 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\nextern crate alloc;\n\n\n\nuse ink_lang as ink;\n\npub use self::core::{\n\n Core\n\n};\n\n#[ink::contract]\n\nmod core {\n\n use alloc::string::String;\n\n // use ink_storage::Lazy;\n\n use role_manage::RoleManage;\n\n use route_manage::RouteManage;\n\n use authority_management::AuthorityManagement;\n\n const DAO_INIT_BALANCE: u128 = 1_000_000_000_000;\n\n\n\n #[ink(storage)]\n\n pub struct Core {\n\n owner:AccountId,\n\n role_manage: Option<RoleManage>,\n", "file_path": "core/lib.rs", "rank": 72, "score": 27.991613702021876 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\nextern crate alloc;\n\nuse ink_lang as ink;\n\npub use self::route_manage::{\n\n RouteManage,\n\n};\n\n\n\n#[ink::contract]\n\nmod route_manage {\n\n use alloc::string::String;\n\n use ink_prelude::vec::Vec;\n\n use ink_prelude::collections::BTreeMap;\n\n use ink_storage::{collections::HashMap as StorageHashMap, };\n\n #[ink(storage)]\n\n pub struct RouteManage {\n\n owner:AccountId,\n\n route_map:StorageHashMap<String,AccountId>,\n\n }\n\n\n\n impl RouteManage {\n", "file_path": "route_manage/lib.rs", "rank": 73, "score": 27.3819463188357 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\nextern crate alloc;\n\nuse ink_lang as ink;\n\n\n\npub use self::authority_management::{\n\n AuthorityManagement,\n\n};\n\n#[ink::contract]\n\nmod authority_management{\n\n use alloc::string::String;\n\n use ink_prelude::vec::Vec;\n\n use ink_prelude::collections::BTreeMap;\n\n use ink_storage::{collections::HashMap as StorageHashMap};\n\n\n\n /// Defines the storage of your contract.\n\n /// Add new fields to the below struct in order\n\n /// to add new static storage fields to your contract.\n\n #[ink(storage)]\n\n pub struct AuthorityManagement {\n\n owner:AccountId,\n", "file_path": "authority_management/lib.rs", "rank": 74, "score": 27.286783189217893 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\nextern crate alloc;\n\npub use self::role_manage::{\n\n RoleManage,\n\n // RoleManageRef,\n\n};\n\nuse ink_lang as ink;\n\n\n\n#[ink::contract]\n\nmod role_manage {\n\n use alloc::string::String;\n\n use ink_prelude::vec::Vec;\n\n use ink_prelude::collections::BTreeMap;\n\n use ink_storage::{collections::HashMap as StorageHashMap, };\n\n\n\n\n\n\n\n /// Defines the storage of your contract.\n\n /// Add new fields to the below struct in order\n\n /// to add new static storage fields to your contract.\n", "file_path": "role_manage/lib.rs", "rank": 75, "score": 27.220504006392247 }, { "content": " use dao_manager::DAOManager;\n\n\n\n const TEMPLATE_INIT_BALANCE: u128 = 1000 * 1000 * 1_000_000_000_000;\n\n const DAO_INIT_BALANCE: u128 = 1000 * 1000 * 1_000_000_000_000;\n\n\n\n /// Indicates whether a transaction is already confirmed or needs further confirmations.\n\n #[derive(scale::Encode, scale::Decode, Clone, SpreadLayout, PackedLayout)]\n\n #[cfg_attr(\n\n feature = \"std\",\n\n derive(scale_info::TypeInfo, ink_storage::traits::StorageLayout)\n\n )]\n\n\n\n #[derive(Debug)]\n\n pub struct DAOInstance {\n\n id: u64,\n\n owner: AccountId,\n\n size: u64,\n\n name: String,\n\n logo: String,\n\n desc: String,\n", "file_path": "dao_factory/lib.rs", "rank": 76, "score": 27.060248577944165 }, { "content": " #[ink(constructor)]\n\n pub fn new() -> Self {\n\n Self {\n\n owner:Self::env().caller(),\n\n route_map : StorageHashMap::new(),\n\n }\n\n }\n\n fn only_core(&self,sender:AccountId) {\n\n assert_eq!(self.owner, sender);\n\n }\n\n\n\n #[ink(message)]\n\n pub fn add_route(&mut self, name: String,value:AccountId) -> bool {\n\n self.only_core(Self::env().caller());\n\n self.route_map.insert(name,value);\n\n true\n\n }\n\n\n\n #[ink(message)]\n\n pub fn query_route_by_name(&self, name: String) -> AccountId {\n", "file_path": "route_manage/lib.rs", "rank": 77, "score": 26.807492171543768 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\nextern crate alloc;\n\nuse ink_lang as ink;\n\n\n\npub use self::dao_manager::{\n\n DAOManager,\n\n};\n\n\n\n#[ink::contract]\n\nmod dao_manager {\n\n use alloc::string::String;\n\n use dao_base::DaoBase;\n\n use erc20::Erc20;\n\n use template_manager::DAOTemplate;\n\n use ink_prelude::vec::Vec;\n\n use ink_prelude::collections::BTreeMap;\n\n use dao_vault::DaoVault;\n\n use dao_vote::DaoVote;\n\n use ink_storage::{\n\n // collections::HashMap as StorageHashMap,\n", "file_path": "dao_manager/lib.rs", "rank": 78, "score": 26.702193592430277 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\nextern crate alloc;\n\nuse ink_lang as ink;\n\n\n\n#[ink::contract]\n\nmod rainbow_govnance {\n\n use route_manage::RouteManage;\n\n use erc20::Erc20;\n\n use core::Core;\n\n use alloc::string::String;\n\n\n\n use ink_prelude::vec::Vec;\n\n use ink_prelude::collections::BTreeMap;\n\n use ink_storage::{\n\n traits::{\n\n PackedLayout,\n\n SpreadLayout,\n\n },\n\n collections::HashMap as StorageHashMap,\n\n };\n", "file_path": "rainbow_govnance/lib.rs", "rank": 79, "score": 26.664816824549614 }, { "content": " owner:Self::env().caller(),\n\n name:String::default(),\n\n index:0,\n\n balance:StorageHashMap::new(),\n\n list_vote:list,\n\n weightVotes:StorageHashMap::new(),\n\n vote:0,\n\n erc20_instance: Default::default(),\n\n }\n\n }\n\n #[ink(constructor)]\n\n pub fn default() -> Self{\n\n Self::new()\n\n } \n\n #[ink(message)]\n\n pub fn set_weight_vote(&mut self) {\n\n // let total_balance = Self::env().balance();\n\n let total_balance=self.balance.get(&self.env().caller()).unwrap().clone();\n\n self.balance.insert(self.env().caller(),total_balance);\n\n if total_balance<100{\n", "file_path": "dao_vote/lib.rs", "rank": 80, "score": 26.548134994608308 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\n\n\nextern crate alloc;\n\nuse ink_lang as ink;\n\n\n\npub use self::template_manager::DAOTemplate;\n\npub use self::template_manager::{\n\n TemplateManager,\n\n};\n\n#[ink::contract]\n\nmod template_manager {\n\n use alloc::string::String;\n\n use ink_prelude::vec::Vec;\n\n use ink_prelude::collections::BTreeMap;\n\n use ink_storage::{\n\n traits::{\n\n PackedLayout,\n\n SpreadLayout,\n\n },\n\n collections::HashMap as StorageHashMap,\n", "file_path": "template_manager/lib.rs", "rank": 81, "score": 26.083002210397048 }, { "content": " index:u64,\n\n authority_map:StorageHashMap<u64,String>,\n\n\n\n }\n\n\n\n impl AuthorityManagement{\n\n /// Constructor that initializes the `bool` value to the given `init_value`.\n\n #[ink(constructor)]\n\n pub fn new() -> Self {\n\n Self {\n\n owner:Self::env().caller(),\n\n index: 0,\n\n authority_map : StorageHashMap::new(),\n\n }\n\n }\n\n #[ink(message)]\n\n pub fn only_core(&self,sender:AccountId) {\n\n assert_eq!(self.owner, sender);\n\n }\n\n\n", "file_path": "authority_management/lib.rs", "rank": 82, "score": 26.008895698058843 }, { "content": " dao_category:StorageHashMap<u64,String>,\n\n }\n\n\n\n impl IncomeCategory {\n\n /// Constructor that initializes the `bool` value to the given `init_value`.\n\n #[ink(constructor)]\n\n pub fn new(treasury_vault:u128,super_manager:AccountId) -> Self {\n\n let mut list=StorageHashMap::new();\n\n list.insert(1,String::from(\"SonDao\"));\n\n list.insert(2,String::from(\"independentDao\"));\n\n list.insert(3,String::from(\"allianceDao\"));\n\n \n\n Self { \n\n treasury_vault,\n\n super_manager,\n\n dao_member_number:0,\n\n erc20_instance: Default::default(),\n\n vault_instance:Default::default(),\n\n category:StorageHashMap::new(),\n\n dao_category:list,\n", "file_path": "income_category/lib.rs", "rank": 83, "score": 25.891724945206885 }, { "content": "\n\n fn only_core(&self,sender:AccountId) {\n\n assert_eq!(self.owner, sender);\n\n }\n\n\n\n #[ink(message)]\n\n pub fn add_role(&mut self, name: String) -> bool {\n\n self.only_core(Self::env().caller());\n\n self.role_map.insert(self.index, name);\n\n self.index += 1;\n\n true\n\n }\n\n\n\n #[ink(message)]\n\n pub fn list_roles(&self) -> Vec<String> {\n\n let mut role_vec = Vec::new();\n\n let mut iter = self.role_map.values();\n\n let mut role = iter.next();\n\n while role.is_some() {\n\n role_vec.push(role.unwrap().clone());\n", "file_path": "role_manage/lib.rs", "rank": 84, "score": 25.663440164102955 }, { "content": " synopsis:String::default(),\n\n symbol:String::default(),\n\n }\n\n }\n\n\n\n #[ink(constructor)]\n\n pub fn default() -> Self {\n\n Self::new()\n\n }\n\n\n\n #[ink(message)]\n\n pub fn init_base(&mut self, name: String, synopsis: String, symbol: String) {\n\n self.set_name(name);\n\n self.set_synopsis(synopsis);\n\n self.set_symbol(symbol);\n\n }\n\n\n\n #[ink(message)]\n\n pub fn set_name(&mut self, name: String) {\n\n self.name = name;\n", "file_path": "dao_base/lib.rs", "rank": 85, "score": 25.593457102941375 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\n\n\nuse ink_lang as ink;\n\nuse ink_env::Environment;\n\nextern crate alloc;\n\n#[ink::contract]\n\nmod dao_users {\n\n use alloc::string::String;\n\n use ink_prelude::vec::Vec;\n\n use ink_storage::{\n\n collections::HashMap as StorageHashMap,\n\n lazy::Lazy,\n\n traits::{\n\n PackedLayout,\n\n SpreadLayout,\n\n }\n\n };\n\n #[ink(storage)]\n\n pub struct DaoUsers {\n\n user_info:StorageHashMap<AccountId,User>,\n", "file_path": "dao_users/lib.rs", "rank": 86, "score": 25.1779872361099 }, { "content": " self.route_map.get(&name).unwrap().clone()\n\n }\n\n #[ink(message)]\n\n pub fn change_route(&mut self,name:String,value:AccountId) -> bool {\n\n self.only_core(Self::env().caller());\n\n self.route_map[&name] = value;\n\n true\n\n }\n\n }\n\n\n\n}\n", "file_path": "route_manage/lib.rs", "rank": 87, "score": 24.41578783190123 }, { "content": " pub fn select_vote_name(&self)->String{\n\n self.name.clone()\n\n }\n\n #[ink(message)]\n\n pub fn select_vote_info(&self)->VoteInfo{\n\n VoteInfo {\n\n name:self.name.clone(),\n\n number:self.index,\n\n vote:self.vote,\n\n } \n\n }\n\n //add test balance\n\n #[ink(message)]\n\n pub fn set_balance(&mut self,balance:u128){\n\n let owner=self.env().caller();\n\n self.balance.insert(owner,balance);\n\n\n\n }\n\n\n\n /// Simply returns the current value of our `bool`.\n", "file_path": "dao_vote/lib.rs", "rank": 88, "score": 24.357039852277587 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\nextern crate alloc;\n\nuse ink_lang as ink;\n\n\n\n#[ink::contract]\n\nmod multi_sign {\n\n use alloc::string::String;\n\n //Defining a mutable array\n\n use ink_prelude::vec::Vec;\n\n use ink_prelude::collections::BTreeMap;\n\n use ink_storage::{\n\n collections::{\n\n HashMap as StorageHashMap,\n\n Vec as StorageVec,\n\n },\n\n traits::{\n\n PackedLayout,\n\n SpreadLayout,\n\n },\n\n };\n", "file_path": "multi_sign/lib.rs", "rank": 89, "score": 24.19677953413327 }, { "content": " pub struct DaoInfo {\n\n owner: AccountId,\n\n name: String,\n\n synopsis: String,\n\n symbol: String,\n\n }\n\n #[ink(storage)]\n\n pub struct DaoBase {\n\n owner: AccountId,\n\n name: String,\n\n synopsis:String,\n\n symbol:String,\n\n }\n\n\n\n impl DaoBase {\n\n #[ink(constructor)]\n\n pub fn new() -> Self {\n\n Self {\n\n owner: Self::env().caller(),\n\n name:String::default(),\n", "file_path": "dao_base/lib.rs", "rank": 90, "score": 24.185296309086837 }, { "content": " #[ink(message)]\n\n pub fn add_authority(&mut self, name: String) -> bool {\n\n self.only_core(Self::env().caller());\n\n self.authority_map.insert(self.index, name);\n\n self.index += 1;\n\n true\n\n }\n\n\n\n #[ink(message)]\n\n pub fn list_authority(&self) -> Vec<String> {\n\n let mut authority_vec = Vec::new();\n\n let mut iter = self.authority_map.values();\n\n let mut authority = iter.next();\n\n while authority.is_some() {\n\n authority_vec.push(authority.unwrap().clone());\n\n authority = iter.next();\n\n }\n\n authority_vec\n\n }\n\n\n", "file_path": "authority_management/lib.rs", "rank": 91, "score": 24.062779671964194 }, { "content": " Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode, SpreadLayout, PackedLayout, Default\n\n )]\n\n #[cfg_attr(\n\n feature = \"std\",\n\n derive(::scale_info::TypeInfo, ::ink_storage::traits::StorageLayout)\n\n )]\n\n pub struct DAOComponentAddrs {\n\n // base module contract's address\n\n pub base_addr: Option<AccountId>,\n\n // erc20 module contract's address\n\n pub erc20_addr: Option<AccountId>,\n\n pub vault_addr: Option<AccountId>,\n\n // vote module contract's address\n\n pub vote_addr: Option<AccountId>,\n\n \n\n }\n\n\n\n #[derive(\n\n Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode, SpreadLayout, PackedLayout, Default\n\n )]\n", "file_path": "dao_manager/lib.rs", "rank": 92, "score": 23.96374026529316 }, { "content": " role = iter.next();\n\n }\n\n role_vec\n\n }\n\n\n\n #[ink(message)]\n\n pub fn get_role_by_index(&self, index: u64) -> String {\n\n self.role_map.get(&index).unwrap().clone()\n\n }\n\n\n\n\n\n #[ink(message)]\n\n pub fn add_insert_authority(&mut self ,name:String,authority:String) -> bool {\n\n self.only_core(Self::env().caller());\n\n let role_authority_list = self.role_authority.entry(name.clone()).or_insert(Vec::new());\n\n role_authority_list.push(authority);\n\n\n\n true\n\n }\n\n\n", "file_path": "role_manage/lib.rs", "rank": 93, "score": 23.844332841113154 }, { "content": " Defeated,\n\n Succeeded,\n\n Executed,\n\n Expired,\n\n Queued\n\n }\n\n\n\n #[derive(Debug)]\n\n pub struct Receipt {\n\n has_voted:bool,\n\n support: bool,\n\n votes:u128\n\n }\n\n\n\n impl DaoGovnance {\n\n /// Constructor that initializes the `bool` value to the given `init_value`.\n\n #[ink(constructor)]\n\n pub fn new(route_addr:AccountId,rbd_addr:AccountId) -> Self {\n\n Self{\n\n owner:Self.env().caller(),\n", "file_path": "dao_govnance/lib.rs", "rank": 94, "score": 23.79369950264634 }, { "content": " pub fn new()->Self{\n\n Self{\n\n owner:Self::env().caller(),\n\n index:0,\n\n categeorys:StorageHashMap::new(),\n\n }\n\n }\n\n #[ink(message)]\n\n pub fn add_categeorys(&mut self, categeorys:String)->bool{\n\n self.categeorys.insert(self.index,categeorys);\n\n self.index +=1;\n\n true\n\n }\n\n #[ink(message)]\n\n pub fn list_categeorys(&mut self )-> Vec<String>{\n\n let mut categeory_vec=Vec::new();\n\n let mut iter=self.categeorys.values();\n\n let mut categeory=iter.next();\n\n while categeory.is_some(){\n\n categeory_vec.push(categeory.unwrap().clone());\n", "file_path": "dao_category/lib.rs", "rank": 95, "score": 23.653822235535205 }, { "content": " list_vote:StorageHashMap<u64,String>,\n\n //weight grading (Tentative three grades)\n\n weightVotes:StorageHashMap<u128,u128>,\n\n vote:u128,\n\n erc20_instance:Erc20,\n\n\n\n\n\n }\n\n\n\n impl DaoVote {\n\n /// Constructor that initializes the `bool` value to the given `init_value`.\n\n #[ink(constructor)]\n\n pub fn new() -> Self {\n\n let mut list=StorageHashMap::new();\n\n list.insert(1,String::from(\"a_currency_one_vote\"));\n\n list.insert(2,String::from(\"one_man_one_vote\"));\n\n list.insert(3,String::from(\"weight_vote\"));\n\n list.insert(4,String::from(\"basic_quadratic_vote\"));\n\n list.insert(5,String::from(\"weight_quadratic_vote\"));\n\n Self { \n", "file_path": "dao_vote/lib.rs", "rank": 96, "score": 23.63791540776612 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\nextern crate alloc;\n\nuse ink_lang as ink;\n\n\n\n#[ink::contract]\n\nmod dao_factory {\n\n\n\n use alloc::string::String;\n\n use ink_prelude::vec::Vec;\n\n use ink_prelude::collections::BTreeMap;\n\n use ink_storage::{\n\n traits::{\n\n PackedLayout,\n\n SpreadLayout,\n\n },\n\n collections::HashMap as StorageHashMap,\n\n };\n\n //use dao_base::DaoBase;\n\n use template_manager::TemplateManager;\n\n use template_manager::DAOTemplate;\n", "file_path": "dao_factory/lib.rs", "rank": 97, "score": 23.35662353231127 }, { "content": " pub fn exec(&mut self,index:u64,target_name:String,exec_string:String) -> bool {\n\n let mut proposal:Proposal = self.proposals.get(&index).unwrap().clone();\n\n assert!(self.state(index) == ProposalState::Queued);\n\n let addr = self.get_contract_addr(target_name);\n\n proposal.executed = true;\n\n true\n\n\n\n }\n\n\n\n #[ink(message)]\n\n pub fn cast_vote(&mut self,proposal_id:u64,support:bool) ->bool {\n\n let caller = Self::env().caller();\n\n assert!(self.state(proposal_id) == ProposalState::Active);\n\n let mut proposal:Proposal = self.proposals.get(&proposal_id).unwrap().clone();\n\n let mut receipts = proposal.receipts.get(&caller).unwrap().clone();\n\n assert!(receipts.has_voted == false);\n\n let erc20_instance: Erc20 = ink_env::call::FromAccountId::from_account_id(self.rbd_addr);\n\n let votes = erc20_instance.get_prior_votes(caller,proposal.start_block);\n\n if support {\n\n proposal.support_vote += votes;\n", "file_path": "dao_govnance/lib.rs", "rank": 98, "score": 23.197978696488683 }, { "content": " }\n\n\n\n #[ink(message)]\n\n pub fn get_name(&self) -> String{\n\n self.name.clone()\n\n }\n\n\n\n #[ink(message)]\n\n pub fn set_synopsis(&mut self, synopsis: String) {\n\n self.synopsis = synopsis;\n\n }\n\n\n\n #[ink(message)]\n\n pub fn get_synopsis(&self) -> String{\n\n self.synopsis.clone()\n\n }\n\n\n\n #[ink(message)]\n\n pub fn set_symbol(&mut self, symbol: String) {\n\n self.symbol = symbol;\n", "file_path": "dao_base/lib.rs", "rank": 99, "score": 23.16615093856276 } ]
Rust
crates/tm4c129x/src/pwm0/sync.rs
m-labs/ti2svd
30145706b658136c35c90290701de3f02a4b8ef2
#[doc = "Reader of register SYNC"] pub type R = crate::R<u32, super::SYNC>; #[doc = "Writer for register SYNC"] pub type W = crate::W<u32, super::SYNC>; #[doc = "Register SYNC `reset()`'s with value 0"] impl crate::ResetValue for super::SYNC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `SYNC0`"] pub type SYNC0_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SYNC0`"] pub struct SYNC0_W<'a> { w: &'a mut W, } impl<'a> SYNC0_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 `SYNC1`"] pub type SYNC1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SYNC1`"] pub struct SYNC1_W<'a> { w: &'a mut W, } impl<'a> SYNC1_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 `SYNC2`"] pub type SYNC2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SYNC2`"] pub struct SYNC2_W<'a> { w: &'a mut W, } impl<'a> SYNC2_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 `SYNC3`"] pub type SYNC3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SYNC3`"] pub struct SYNC3_W<'a> { w: &'a mut W, } impl<'a> SYNC3_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 } } impl R { #[doc = "Bit 0 - Reset Generator 0 Counter"] #[inline(always)] pub fn sync0(&self) -> SYNC0_R { SYNC0_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Reset Generator 1 Counter"] #[inline(always)] pub fn sync1(&self) -> SYNC1_R { SYNC1_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Reset Generator 2 Counter"] #[inline(always)] pub fn sync2(&self) -> SYNC2_R { SYNC2_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - Reset Generator 3 Counter"] #[inline(always)] pub fn sync3(&self) -> SYNC3_R { SYNC3_R::new(((self.bits >> 3) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Reset Generator 0 Counter"] #[inline(always)] pub fn sync0(&mut self) -> SYNC0_W { SYNC0_W { w: self } } #[doc = "Bit 1 - Reset Generator 1 Counter"] #[inline(always)] pub fn sync1(&mut self) -> SYNC1_W { SYNC1_W { w: self } } #[doc = "Bit 2 - Reset Generator 2 Counter"] #[inline(always)] pub fn sync2(&mut self) -> SYNC2_W { SYNC2_W { w: self } } #[doc = "Bit 3 - Reset Generator 3 Counter"] #[inline(always)] pub fn sync3(&mut self) -> SYNC3_W { SYNC3_W { w: self } } }
#[doc = "Reader of register SYNC"] pub type R = crate::R<u32, super::SYNC>; #[doc = "Writer for register SYNC"] pub type W = crate::W<u32, super::SYNC>; #[doc = "Register SYNC `reset()`'s with value 0"] impl crate::ResetValue for super::SYNC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `SYNC0`"] pub type SYNC0_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SYNC0`"] pub struct SYNC0_W<'a> { w: &'a mut W, } impl<'a> SYNC0_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 `SYNC1`"] pub type SYNC1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SYNC1`"] pub struct SYNC1_W<'a> { w: &'a mut W, } impl<'a> SYNC1_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 `SYNC2`"] pub type SYNC2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SYNC2`"] pub struct SYNC2_W<'a> { w: &'a mut W, } impl<'a> SYNC2_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
)] pub fn sync1(&mut self) -> SYNC1_W { SYNC1_W { w: self } } #[doc = "Bit 2 - Reset Generator 2 Counter"] #[inline(always)] pub fn sync2(&mut self) -> SYNC2_W { SYNC2_W { w: self } } #[doc = "Bit 3 - Reset Generator 3 Counter"] #[inline(always)] pub fn sync3(&mut self) -> SYNC3_W { SYNC3_W { w: self } } }
as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `SYNC3`"] pub type SYNC3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SYNC3`"] pub struct SYNC3_W<'a> { w: &'a mut W, } impl<'a> SYNC3_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 } } impl R { #[doc = "Bit 0 - Reset Generator 0 Counter"] #[inline(always)] pub fn sync0(&self) -> SYNC0_R { SYNC0_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Reset Generator 1 Counter"] #[inline(always)] pub fn sync1(&self) -> SYNC1_R { SYNC1_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Reset Generator 2 Counter"] #[inline(always)] pub fn sync2(&self) -> SYNC2_R { SYNC2_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - Reset Generator 3 Counter"] #[inline(always)] pub fn sync3(&self) -> SYNC3_R { SYNC3_R::new(((self.bits >> 3) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Reset Generator 0 Counter"] #[inline(always)] pub fn sync0(&mut self) -> SYNC0_W { SYNC0_W { w: self } } #[doc = "Bit 1 - Reset Generator 1 Counter"] #[inline(always
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Reset value of the register\"]\n\n fn reset_value() -> Self::Type;\n\n}\n\n#[doc = \"This structure provides volatile access to register\"]\n\npub struct Reg<U, REG> {\n\n register: vcell::VolatileCell<U>,\n\n _marker: marker::PhantomData<REG>,\n\n}\n\nunsafe impl<U: Send, REG> Send for Reg<U, REG> {}\n\nimpl<U, REG> Reg<U, REG>\n\nwhere\n\n Self: Readable,\n\n U: Copy,\n\n{\n\n #[doc = \"Reads the contents of `Readable` register\"]\n\n #[doc = \"\"]\n\n #[doc = \"You can read the contents of a register in such way:\"]\n", "file_path": "crates/tm4c123x/src/generic.rs", "rank": 0, "score": 159295.56070954952 }, { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Reset value of the register\"]\n\n fn reset_value() -> Self::Type;\n\n}\n\n#[doc = \"This structure provides volatile access to register\"]\n\npub struct Reg<U, REG> {\n\n register: vcell::VolatileCell<U>,\n\n _marker: marker::PhantomData<REG>,\n\n}\n\nunsafe impl<U: Send, REG> Send for Reg<U, REG> {}\n\nimpl<U, REG> Reg<U, REG>\n\nwhere\n\n Self: Readable,\n\n U: Copy,\n\n{\n\n #[doc = \"Reads the contents of `Readable` register\"]\n\n #[doc = \"\"]\n\n #[doc = \"You can read the contents of a register in such way:\"]\n", "file_path": "crates/tm4c129x/src/generic.rs", "rank": 1, "score": 159295.56070954952 }, { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\")).unwrap().write_all(include_bytes!(\"device.x\")).unwrap();\n\n println!(\"cargo:rustc-link-search={}\", out.display());\n\n println!(\"cargo:rerun-if-changed=device.x\");\n\n }\n\n println!(\"cargo:rerun-if-changed=build.rs\");\n\n}\n", "file_path": "crates/tm4c123x/build.rs", "rank": 2, "score": 61987.665827901175 }, { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\")).unwrap().write_all(include_bytes!(\"device.x\")).unwrap();\n\n println!(\"cargo:rustc-link-search={}\", out.display());\n\n println!(\"cargo:rerun-if-changed=device.x\");\n\n }\n\n println!(\"cargo:rerun-if-changed=build.rs\");\n\n}\n", "file_path": "crates/tm4c129x/build.rs", "rank": 3, "score": 61987.665827901175 }, { "content": "#[doc = \"This trait shows that register has `write`, `write_with_zero` and `reset` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Readable` can be also `modify`'ed\"]\n\npub trait Writable {}\n", "file_path": "crates/tm4c129x/src/generic.rs", "rank": 4, "score": 56875.064836524 }, { "content": "#[doc = \"This trait shows that register has `write`, `write_with_zero` and `reset` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Readable` can be also `modify`'ed\"]\n\npub trait Writable {}\n", "file_path": "crates/tm4c123x/src/generic.rs", "rank": 5, "score": 56875.064836524 }, { "content": "#[doc = \"This trait shows that register has `read` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Writable` can be also `modify`'ed\"]\n\npub trait Readable {}\n", "file_path": "crates/tm4c129x/src/generic.rs", "rank": 6, "score": 56863.05328766474 }, { "content": "#[doc = \"This trait shows that register has `read` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Writable` can be also `modify`'ed\"]\n\npub trait Readable {}\n", "file_path": "crates/tm4c123x/src/generic.rs", "rank": 7, "score": 56863.05328766474 }, { "content": "#[doc = \"Reader of register BIT\"]\n\npub type R = crate::R<u32, super::BIT>;\n\n#[doc = \"Writer for register BIT\"]\n\npub type W = crate::W<u32, super::BIT>;\n\n#[doc = \"Register BIT `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::BIT {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `BRP`\"]\n\npub type BRP_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `BRP`\"]\n\npub struct BRP_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> BRP_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "crates/tm4c129x/src/can0/bit_.rs", "rank": 8, "score": 55627.83727210846 }, { "content": "#[doc = \"Reader of register BIT\"]\n\npub type R = crate::R<u32, super::BIT>;\n\n#[doc = \"Writer for register BIT\"]\n\npub type W = crate::W<u32, super::BIT>;\n\n#[doc = \"Register BIT `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::BIT {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `BRP`\"]\n\npub type BRP_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `BRP`\"]\n\npub struct BRP_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> BRP_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "crates/tm4c123x/src/can0/bit_.rs", "rank": 9, "score": 55627.83727210846 }, { "content": "#[doc = \"Reader of field `TSEG1`\"]\n\npub type TSEG1_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `TSEG1`\"]\n\npub struct TSEG1_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> TSEG1_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Reader of field `TSEG2`\"]\n\npub type TSEG2_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `TSEG2`\"]\n\npub struct TSEG2_W<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "crates/tm4c123x/src/can0/bit_.rs", "rank": 10, "score": 55606.724616690975 }, { "content": "#[doc = \"Reader of field `TSEG1`\"]\n\npub type TSEG1_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `TSEG1`\"]\n\npub struct TSEG1_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> TSEG1_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Reader of field `TSEG2`\"]\n\npub type TSEG2_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `TSEG2`\"]\n\npub struct TSEG2_W<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "crates/tm4c129x/src/can0/bit_.rs", "rank": 11, "score": 55606.724616690975 }, { "content": " #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !0x3f) | ((value as u32) & 0x3f);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Reader of field `SJW`\"]\n\npub type SJW_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `SJW`\"]\n\npub struct SJW_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SJW_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 6)) | (((value as u32) & 0x03) << 6);\n\n self.w\n\n }\n\n}\n", "file_path": "crates/tm4c123x/src/can0/bit_.rs", "rank": 12, "score": 55605.83505573895 }, { "content": " #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !0x3f) | ((value as u32) & 0x3f);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Reader of field `SJW`\"]\n\npub type SJW_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `SJW`\"]\n\npub struct SJW_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SJW_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 6)) | (((value as u32) & 0x03) << 6);\n\n self.w\n\n }\n\n}\n", "file_path": "crates/tm4c129x/src/can0/bit_.rs", "rank": 13, "score": 55605.83505573895 }, { "content": "impl<'a> TSEG2_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x07 << 12)) | (((value as u32) & 0x07) << 12);\n\n self.w\n\n }\n\n}\n\nimpl R {\n\n #[doc = \"Bits 0:5 - Baud Rate Prescaler\"]\n\n #[inline(always)]\n\n pub fn brp(&self) -> BRP_R {\n\n BRP_R::new((self.bits & 0x3f) as u8)\n\n }\n\n #[doc = \"Bits 6:7 - (Re)Synchronization Jump Width\"]\n\n #[inline(always)]\n\n pub fn sjw(&self) -> SJW_R {\n\n SJW_R::new(((self.bits >> 6) & 0x03) as u8)\n\n }\n\n #[doc = \"Bits 8:11 - Time Segment Before Sample Point\"]\n", "file_path": "crates/tm4c129x/src/can0/bit_.rs", "rank": 14, "score": 55591.61117287072 }, { "content": "impl<'a> TSEG2_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x07 << 12)) | (((value as u32) & 0x07) << 12);\n\n self.w\n\n }\n\n}\n\nimpl R {\n\n #[doc = \"Bits 0:5 - Baud Rate Prescaler\"]\n\n #[inline(always)]\n\n pub fn brp(&self) -> BRP_R {\n\n BRP_R::new((self.bits & 0x3f) as u8)\n\n }\n\n #[doc = \"Bits 6:7 - (Re)Synchronization Jump Width\"]\n\n #[inline(always)]\n\n pub fn sjw(&self) -> SJW_R {\n\n SJW_R::new(((self.bits >> 6) & 0x03) as u8)\n\n }\n\n #[doc = \"Bits 8:11 - Time Segment Before Sample Point\"]\n", "file_path": "crates/tm4c123x/src/can0/bit_.rs", "rank": 15, "score": 55591.61117287072 }, { "content": "#[doc = \"Reader of register VALUE\"]\n\npub type R = crate::R<u32, super::VALUE>;\n\nimpl R {}\n", "file_path": "crates/tm4c129x/src/watchdog0/value.rs", "rank": 16, "score": 55589.710525917406 }, { "content": "#[doc = \"Reader of register VALUE\"]\n\npub type R = crate::R<u32, super::VALUE>;\n\nimpl R {}\n", "file_path": "crates/tm4c123x/src/watchdog0/value.rs", "rank": 17, "score": 55589.710525917406 }, { "content": " #[inline(always)]\n\n pub fn tseg1(&self) -> TSEG1_R {\n\n TSEG1_R::new(((self.bits >> 8) & 0x0f) as u8)\n\n }\n\n #[doc = \"Bits 12:14 - Time Segment after Sample Point\"]\n\n #[inline(always)]\n\n pub fn tseg2(&self) -> TSEG2_R {\n\n TSEG2_R::new(((self.bits >> 12) & 0x07) as u8)\n\n }\n\n}\n\nimpl W {\n\n #[doc = \"Bits 0:5 - Baud Rate Prescaler\"]\n\n #[inline(always)]\n\n pub fn brp(&mut self) -> BRP_W {\n\n BRP_W { w: self }\n\n }\n\n #[doc = \"Bits 6:7 - (Re)Synchronization Jump Width\"]\n\n #[inline(always)]\n\n pub fn sjw(&mut self) -> SJW_W {\n\n SJW_W { w: self }\n", "file_path": "crates/tm4c129x/src/can0/bit_.rs", "rank": 18, "score": 55576.74840749567 }, { "content": " #[inline(always)]\n\n pub fn tseg1(&self) -> TSEG1_R {\n\n TSEG1_R::new(((self.bits >> 8) & 0x0f) as u8)\n\n }\n\n #[doc = \"Bits 12:14 - Time Segment after Sample Point\"]\n\n #[inline(always)]\n\n pub fn tseg2(&self) -> TSEG2_R {\n\n TSEG2_R::new(((self.bits >> 12) & 0x07) as u8)\n\n }\n\n}\n\nimpl W {\n\n #[doc = \"Bits 0:5 - Baud Rate Prescaler\"]\n\n #[inline(always)]\n\n pub fn brp(&mut self) -> BRP_W {\n\n BRP_W { w: self }\n\n }\n\n #[doc = \"Bits 6:7 - (Re)Synchronization Jump Width\"]\n\n #[inline(always)]\n\n pub fn sjw(&mut self) -> SJW_W {\n\n SJW_W { w: self }\n", "file_path": "crates/tm4c123x/src/can0/bit_.rs", "rank": 19, "score": 55576.74840749567 }, { "content": " }\n\n #[doc = \"Bits 8:11 - Time Segment Before Sample Point\"]\n\n #[inline(always)]\n\n pub fn tseg1(&mut self) -> TSEG1_W {\n\n TSEG1_W { w: self }\n\n }\n\n #[doc = \"Bits 12:14 - Time Segment after Sample Point\"]\n\n #[inline(always)]\n\n pub fn tseg2(&mut self) -> TSEG2_W {\n\n TSEG2_W { w: self }\n\n }\n\n}\n", "file_path": "crates/tm4c123x/src/can0/bit_.rs", "rank": 20, "score": 55567.4237793735 }, { "content": " }\n\n #[doc = \"Bits 8:11 - Time Segment Before Sample Point\"]\n\n #[inline(always)]\n\n pub fn tseg1(&mut self) -> TSEG1_W {\n\n TSEG1_W { w: self }\n\n }\n\n #[doc = \"Bits 12:14 - Time Segment after Sample Point\"]\n\n #[inline(always)]\n\n pub fn tseg2(&mut self) -> TSEG2_W {\n\n TSEG2_W { w: self }\n\n }\n\n}\n", "file_path": "crates/tm4c129x/src/can0/bit_.rs", "rank": 21, "score": 55567.4237793735 }, { "content": "#[doc = \"Reader of register SYNC\"]\n\npub type R = crate::R<u32, super::SYNC>;\n\n#[doc = \"Writer for register SYNC\"]\n\npub type W = crate::W<u32, super::SYNC>;\n\n#[doc = \"Register SYNC `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SYNC {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `SYNC0`\"]\n\npub type SYNC0_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `SYNC0`\"]\n\npub struct SYNC0_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNC0_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "crates/tm4c123x/src/pwm0/sync.rs", "rank": 23, "score": 55559.19868888943 }, { "content": " }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);\n\n self.w\n\n }\n\n}\n\nimpl R {\n\n #[doc = \"Bit 0 - Reset Generator 0 Counter\"]\n\n #[inline(always)]\n\n pub fn sync0(&self) -> SYNC0_R {\n\n SYNC0_R::new((self.bits & 0x01) != 0)\n\n }\n\n #[doc = \"Bit 1 - Reset Generator 1 Counter\"]\n\n #[inline(always)]\n\n pub fn sync1(&self) -> SYNC1_R {\n\n SYNC1_R::new(((self.bits >> 1) & 0x01) != 0)\n\n }\n\n #[doc = \"Bit 2 - Reset Generator 2 Counter\"]\n", "file_path": "crates/tm4c123x/src/pwm0/sync.rs", "rank": 24, "score": 55533.76142424189 }, { "content": " #[inline(always)]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\"Clears the field bit\"]\n\n #[inline(always)]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Reader of field `SYNC1`\"]\n\npub type SYNC1_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `SYNC1`\"]\n\npub struct SYNC1_W<'a> {\n", "file_path": "crates/tm4c123x/src/pwm0/sync.rs", "rank": 26, "score": 55532.101131353644 }, { "content": "#[doc = \"Reader of field `SYNC2`\"]\n\npub type SYNC2_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `SYNC2`\"]\n\npub struct SYNC2_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNC2_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n\n #[inline(always)]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\"Clears the field bit\"]\n\n #[inline(always)]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n", "file_path": "crates/tm4c123x/src/pwm0/sync.rs", "rank": 29, "score": 55531.02978324594 }, { "content": "#[doc = \"Reader of register SYNC\"]\n\npub type R = crate::R<u32, super::SYNC>;\n\n#[doc = \"Writer for register SYNC\"]\n\npub type W = crate::W<u32, super::SYNC>;\n\n#[doc = \"Register SYNC `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SYNC {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM Timer 0\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCT0_A {\n\n #[doc = \"0: GPTM0 is not affected\"]\n\n NONE = 0,\n\n #[doc = \"1: A timeout event for Timer A of GPTM0 is triggered\"]\n\n TA = 1,\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 30, "score": 55527.7401762446 }, { "content": "#[doc = \"Reader of register SYNC\"]\n\npub type R = crate::R<u32, super::SYNC>;\n\n#[doc = \"Writer for register SYNC\"]\n\npub type W = crate::W<u32, super::SYNC>;\n\n#[doc = \"Register SYNC `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SYNC {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM Timer 0\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCT0_A {\n\n #[doc = \"0: GPTM0 is not affected\"]\n\n NONE = 0,\n\n #[doc = \"1: A timeout event for Timer A of GPTM0 is triggered\"]\n\n TA = 1,\n", "file_path": "crates/tm4c129x/src/timer0/sync.rs", "rank": 31, "score": 55527.7401762446 }, { "content": "#[doc = \"Reader of register SYNC\"]\n\npub type R = crate::R<u32, super::SYNC>;\n\n#[doc = \"Writer for register SYNC\"]\n\npub type W = crate::W<u32, super::SYNC>;\n\n#[doc = \"Register SYNC `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SYNC {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM Timer 0\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCT0_A {\n\n #[doc = \"0: GPTM0 is not affected\"]\n\n NONE = 0,\n\n #[doc = \"1: A timeout event for Timer A of GPTM0 is triggered\"]\n\n TA = 1,\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 32, "score": 55527.7401762446 }, { "content": " #[inline(always)]\n\n pub fn sync2(&self) -> SYNC2_R {\n\n SYNC2_R::new(((self.bits >> 2) & 0x01) != 0)\n\n }\n\n #[doc = \"Bit 3 - Reset Generator 3 Counter\"]\n\n #[inline(always)]\n\n pub fn sync3(&self) -> SYNC3_R {\n\n SYNC3_R::new(((self.bits >> 3) & 0x01) != 0)\n\n }\n\n}\n\nimpl W {\n\n #[doc = \"Bit 0 - Reset Generator 0 Counter\"]\n\n #[inline(always)]\n\n pub fn sync0(&mut self) -> SYNC0_W {\n\n SYNC0_W { w: self }\n\n }\n\n #[doc = \"Bit 1 - Reset Generator 1 Counter\"]\n\n #[inline(always)]\n\n pub fn sync1(&mut self) -> SYNC1_W {\n\n SYNC1_W { w: self }\n", "file_path": "crates/tm4c123x/src/pwm0/sync.rs", "rank": 33, "score": 55523.02313046394 }, { "content": " self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Reader of field `SYNC3`\"]\n\npub type SYNC3_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `SYNC3`\"]\n\npub struct SYNC3_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNC3_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n\n #[inline(always)]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\"Clears the field bit\"]\n\n #[inline(always)]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n", "file_path": "crates/tm4c123x/src/pwm0/sync.rs", "rank": 36, "score": 55522.111291870024 }, { "content": " w: &'a mut W,\n\n}\n\nimpl<'a> SYNC1_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n\n #[inline(always)]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\"Clears the field bit\"]\n\n #[inline(always)]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);\n\n self.w\n\n }\n\n}\n", "file_path": "crates/tm4c123x/src/pwm0/sync.rs", "rank": 38, "score": 55518.95719805268 }, { "content": " #[inline(always)]\n\n pub fn tb(self) -> &'a mut W {\n\n self.variant(SYNCT7_A::TB)\n\n }\n\n #[doc = \"A timeout event for both Timer A and Timer B of GPTM7 is triggered\"]\n\n #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCT7_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 14)) | (((value as u32) & 0x03) << 14);\n\n self.w\n\n }\n\n}\n\nimpl R {\n\n #[doc = \"Bits 0:1 - Synchronize GPTM Timer 0\"]\n\n #[inline(always)]\n\n pub fn synct0(&self) -> SYNCT0_R {\n", "file_path": "crates/tm4c129x/src/timer0/sync.rs", "rank": 39, "score": 55512.000741873475 }, { "content": " }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 22)) | (((value as u32) & 0x03) << 22);\n\n self.w\n\n }\n\n}\n\nimpl R {\n\n #[doc = \"Bits 0:1 - Synchronize GPTM Timer 0\"]\n\n #[inline(always)]\n\n pub fn synct0(&self) -> SYNCT0_R {\n\n SYNCT0_R::new((self.bits & 0x03) as u8)\n\n }\n\n #[doc = \"Bits 2:3 - Synchronize GPTM Timer 1\"]\n\n #[inline(always)]\n\n pub fn synct1(&self) -> SYNCT1_R {\n\n SYNCT1_R::new(((self.bits >> 2) & 0x03) as u8)\n\n }\n\n #[doc = \"Bits 4:5 - Synchronize GPTM Timer 2\"]\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 40, "score": 55509.35716064093 }, { "content": " }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 22)) | (((value as u32) & 0x03) << 22);\n\n self.w\n\n }\n\n}\n\nimpl R {\n\n #[doc = \"Bits 0:1 - Synchronize GPTM Timer 0\"]\n\n #[inline(always)]\n\n pub fn synct0(&self) -> SYNCT0_R {\n\n SYNCT0_R::new((self.bits & 0x03) as u8)\n\n }\n\n #[doc = \"Bits 2:3 - Synchronize GPTM Timer 1\"]\n\n #[inline(always)]\n\n pub fn synct1(&self) -> SYNCT1_R {\n\n SYNCT1_R::new(((self.bits >> 2) & 0x03) as u8)\n\n }\n\n #[doc = \"Bits 4:5 - Synchronize GPTM Timer 2\"]\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 41, "score": 55509.35716064093 }, { "content": " pub fn is_tb(&self) -> bool {\n\n *self == SYNCWT5_A::TB\n\n }\n\n #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCWT5_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCWT5`\"]\n\npub struct SYNCWT5_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCWT5_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCWT5_A) -> &'a mut W {\n\n {\n\n self.bits(variant.into())\n\n }\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 42, "score": 55508.86425551277 }, { "content": " pub fn is_tb(&self) -> bool {\n\n *self == SYNCWT5_A::TB\n\n }\n\n #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCWT5_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCWT5`\"]\n\npub struct SYNCWT5_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCWT5_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCWT5_A) -> &'a mut W {\n\n {\n\n self.bits(variant.into())\n\n }\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 43, "score": 55508.86425551277 }, { "content": " #[inline(always)]\n\n pub fn is_tb(&self) -> bool {\n\n *self == SYNCWT2_A::TB\n\n }\n\n #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCWT2_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCWT2`\"]\n\npub struct SYNCWT2_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCWT2_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCWT2_A) -> &'a mut W {\n\n {\n\n self.bits(variant.into())\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 44, "score": 55508.32228430794 }, { "content": " #[inline(always)]\n\n pub fn is_tb(&self) -> bool {\n\n *self == SYNCWT2_A::TB\n\n }\n\n #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCWT2_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCWT2`\"]\n\npub struct SYNCWT2_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCWT2_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCWT2_A) -> &'a mut W {\n\n {\n\n self.bits(variant.into())\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 45, "score": 55508.32228430794 }, { "content": " #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCT0_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCT0`\"]\n\npub struct SYNCT0_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCT0_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCT0_A) -> &'a mut W {\n\n {\n\n self.bits(variant.into())\n\n }\n\n }\n\n #[doc = \"GPTM0 is not affected\"]\n\n #[inline(always)]\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 46, "score": 55507.44363786891 }, { "content": " #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCT0_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCT0`\"]\n\npub struct SYNCT0_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCT0_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCT0_A) -> &'a mut W {\n\n {\n\n self.bits(variant.into())\n\n }\n\n }\n\n #[doc = \"GPTM0 is not affected\"]\n\n #[inline(always)]\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 47, "score": 55507.44363786891 }, { "content": " #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCT0_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCT0`\"]\n\npub struct SYNCT0_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCT0_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCT0_A) -> &'a mut W {\n\n {\n\n self.bits(variant.into())\n\n }\n\n }\n\n #[doc = \"GPTM0 is not affected\"]\n\n #[inline(always)]\n", "file_path": "crates/tm4c129x/src/timer0/sync.rs", "rank": 48, "score": 55507.44363786891 }, { "content": " #[inline(always)]\n\n pub fn tb(self) -> &'a mut W {\n\n self.variant(SYNCWT1_A::TB)\n\n }\n\n #[doc = \"A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 1 is triggered\"]\n\n #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCWT1_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 14)) | (((value as u32) & 0x03) << 14);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM 32/64-Bit Timer 2\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCWT2_A {\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 49, "score": 55507.029525886814 }, { "content": " #[inline(always)]\n\n pub fn tb(self) -> &'a mut W {\n\n self.variant(SYNCWT1_A::TB)\n\n }\n\n #[doc = \"A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 1 is triggered\"]\n\n #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCWT1_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 14)) | (((value as u32) & 0x03) << 14);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM 32/64-Bit Timer 2\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCWT2_A {\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 50, "score": 55507.029525886814 }, { "content": " pub fn tb(self) -> &'a mut W {\n\n self.variant(SYNCWT4_A::TB)\n\n }\n\n #[doc = \"A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 4 is triggered\"]\n\n #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCWT4_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 20)) | (((value as u32) & 0x03) << 20);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM 32/64-Bit Timer 5\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCWT5_A {\n\n #[doc = \"0: GPTM 32/64-Bit Timer 5 is not affected\"]\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 51, "score": 55506.79928134305 }, { "content": " pub fn tb(self) -> &'a mut W {\n\n self.variant(SYNCWT4_A::TB)\n\n }\n\n #[doc = \"A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 4 is triggered\"]\n\n #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCWT4_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 20)) | (((value as u32) & 0x03) << 20);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM 32/64-Bit Timer 5\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCWT5_A {\n\n #[doc = \"0: GPTM 32/64-Bit Timer 5 is not affected\"]\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 52, "score": 55506.79928134305 }, { "content": " }\n\n #[doc = \"A timeout event for Timer B of GPTM1 is triggered\"]\n\n #[inline(always)]\n\n pub fn tb(self) -> &'a mut W {\n\n self.variant(SYNCT1_A::TB)\n\n }\n\n #[doc = \"A timeout event for both Timer A and Timer B of GPTM1 is triggered\"]\n\n #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCT1_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 2)) | (((value as u32) & 0x03) << 2);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM Timer 2\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 53, "score": 55506.44052709542 }, { "content": " }\n\n #[doc = \"A timeout event for Timer B of GPTM1 is triggered\"]\n\n #[inline(always)]\n\n pub fn tb(self) -> &'a mut W {\n\n self.variant(SYNCT1_A::TB)\n\n }\n\n #[doc = \"A timeout event for both Timer A and Timer B of GPTM1 is triggered\"]\n\n #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCT1_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 2)) | (((value as u32) & 0x03) << 2);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM Timer 2\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 54, "score": 55506.44052709542 }, { "content": " }\n\n #[doc = \"A timeout event for Timer B of GPTM1 is triggered\"]\n\n #[inline(always)]\n\n pub fn tb(self) -> &'a mut W {\n\n self.variant(SYNCT1_A::TB)\n\n }\n\n #[doc = \"A timeout event for both Timer A and Timer B of GPTM1 is triggered\"]\n\n #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCT1_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 2)) | (((value as u32) & 0x03) << 2);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM Timer 2\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n", "file_path": "crates/tm4c129x/src/timer0/sync.rs", "rank": 55, "score": 55506.44052709542 }, { "content": " #[doc = \"A timeout event for Timer B of GPTM4 is triggered\"]\n\n #[inline(always)]\n\n pub fn tb(self) -> &'a mut W {\n\n self.variant(SYNCT4_A::TB)\n\n }\n\n #[doc = \"A timeout event for both Timer A and Timer B of GPTM4 is triggered\"]\n\n #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCT4_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 8)) | (((value as u32) & 0x03) << 8);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM Timer 5\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n", "file_path": "crates/tm4c129x/src/timer0/sync.rs", "rank": 56, "score": 55506.0219953113 }, { "content": " #[doc = \"A timeout event for Timer B of GPTM4 is triggered\"]\n\n #[inline(always)]\n\n pub fn tb(self) -> &'a mut W {\n\n self.variant(SYNCT4_A::TB)\n\n }\n\n #[doc = \"A timeout event for both Timer A and Timer B of GPTM4 is triggered\"]\n\n #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCT4_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 8)) | (((value as u32) & 0x03) << 8);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM Timer 5\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 57, "score": 55506.0219953113 }, { "content": " #[doc = \"A timeout event for Timer B of GPTM4 is triggered\"]\n\n #[inline(always)]\n\n pub fn tb(self) -> &'a mut W {\n\n self.variant(SYNCT4_A::TB)\n\n }\n\n #[doc = \"A timeout event for both Timer A and Timer B of GPTM4 is triggered\"]\n\n #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCT4_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 8)) | (((value as u32) & 0x03) << 8);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM Timer 5\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 58, "score": 55506.0219953113 }, { "content": " pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCT5_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 10)) | (((value as u32) & 0x03) << 10);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM Timer 6\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCT6_A {\n\n #[doc = \"0: GPTM6 is not affected\"]\n\n NONE = 0,\n\n #[doc = \"1: A timeout event for Timer A of GPTM6 is triggered\"]\n\n TA = 1,\n\n #[doc = \"2: A timeout event for Timer B of GPTM6 is triggered\"]\n\n TB = 2,\n", "file_path": "crates/tm4c129x/src/timer0/sync.rs", "rank": 59, "score": 55505.82345784412 }, { "content": " #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCT2_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 4)) | (((value as u32) & 0x03) << 4);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM Timer 3\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCT3_A {\n\n #[doc = \"0: GPTM3 is not affected\"]\n\n NONE = 0,\n\n #[doc = \"1: A timeout event for Timer A of GPTM3 is triggered\"]\n\n TA = 1,\n\n #[doc = \"2: A timeout event for Timer B of GPTM3 is triggered\"]\n", "file_path": "crates/tm4c129x/src/timer0/sync.rs", "rank": 60, "score": 55505.59675970493 }, { "content": " #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCT2_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 4)) | (((value as u32) & 0x03) << 4);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM Timer 3\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCT3_A {\n\n #[doc = \"0: GPTM3 is not affected\"]\n\n NONE = 0,\n\n #[doc = \"1: A timeout event for Timer A of GPTM3 is triggered\"]\n\n TA = 1,\n\n #[doc = \"2: A timeout event for Timer B of GPTM3 is triggered\"]\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 61, "score": 55505.59675970493 }, { "content": " #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCT2_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 4)) | (((value as u32) & 0x03) << 4);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM Timer 3\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCT3_A {\n\n #[doc = \"0: GPTM3 is not affected\"]\n\n NONE = 0,\n\n #[doc = \"1: A timeout event for Timer A of GPTM3 is triggered\"]\n\n TA = 1,\n\n #[doc = \"2: A timeout event for Timer B of GPTM3 is triggered\"]\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 62, "score": 55505.59675970493 }, { "content": " #[doc = \"Checks if the value of the field is `TB`\"]\n\n #[inline(always)]\n\n pub fn is_tb(&self) -> bool {\n\n *self == SYNCT5_A::TB\n\n }\n\n #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCT5_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCT5`\"]\n\npub struct SYNCT5_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCT5_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCT5_A) -> &'a mut W {\n\n {\n", "file_path": "crates/tm4c129x/src/timer0/sync.rs", "rank": 63, "score": 55505.45830020573 }, { "content": " #[doc = \"Checks if the value of the field is `TB`\"]\n\n #[inline(always)]\n\n pub fn is_tb(&self) -> bool {\n\n *self == SYNCT5_A::TB\n\n }\n\n #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCT5_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCT5`\"]\n\npub struct SYNCT5_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCT5_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCT5_A) -> &'a mut W {\n\n {\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 64, "score": 55505.45830020573 }, { "content": " }\n\n #[doc = \"Checks if the value of the field is `TB`\"]\n\n #[inline(always)]\n\n pub fn is_tb(&self) -> bool {\n\n *self == SYNCT2_A::TB\n\n }\n\n #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCT2_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCT2`\"]\n\npub struct SYNCT2_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCT2_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCT2_A) -> &'a mut W {\n", "file_path": "crates/tm4c129x/src/timer0/sync.rs", "rank": 65, "score": 55505.45830020573 }, { "content": " }\n\n #[doc = \"Checks if the value of the field is `TB`\"]\n\n #[inline(always)]\n\n pub fn is_tb(&self) -> bool {\n\n *self == SYNCT2_A::TB\n\n }\n\n #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCT2_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCT2`\"]\n\npub struct SYNCT2_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCT2_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCT2_A) -> &'a mut W {\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 66, "score": 55505.45830020573 }, { "content": " }\n\n #[doc = \"Checks if the value of the field is `TB`\"]\n\n #[inline(always)]\n\n pub fn is_tb(&self) -> bool {\n\n *self == SYNCT2_A::TB\n\n }\n\n #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCT2_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCT2`\"]\n\npub struct SYNCT2_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCT2_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCT2_A) -> &'a mut W {\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 67, "score": 55505.45830020573 }, { "content": " #[doc = \"Checks if the value of the field is `TB`\"]\n\n #[inline(always)]\n\n pub fn is_tb(&self) -> bool {\n\n *self == SYNCT5_A::TB\n\n }\n\n #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCT5_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCT5`\"]\n\npub struct SYNCT5_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCT5_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCT5_A) -> &'a mut W {\n\n {\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 68, "score": 55505.45830020573 }, { "content": " pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCT5_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 10)) | (((value as u32) & 0x03) << 10);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM 32/64-Bit Timer 0\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCWT0_A {\n\n #[doc = \"0: GPTM 32/64-Bit Timer 0 is not affected\"]\n\n NONE = 0,\n\n #[doc = \"1: A timeout event for Timer A of GPTM 32/64-Bit Timer 0 is triggered\"]\n\n TA = 1,\n\n #[doc = \"2: A timeout event for Timer B of GPTM 32/64-Bit Timer 0 is triggered\"]\n\n TB = 2,\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 69, "score": 55505.140696379865 }, { "content": " pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCT5_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 10)) | (((value as u32) & 0x03) << 10);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM 32/64-Bit Timer 0\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCWT0_A {\n\n #[doc = \"0: GPTM 32/64-Bit Timer 0 is not affected\"]\n\n NONE = 0,\n\n #[doc = \"1: A timeout event for Timer A of GPTM 32/64-Bit Timer 0 is triggered\"]\n\n TA = 1,\n\n #[doc = \"2: A timeout event for Timer B of GPTM 32/64-Bit Timer 0 is triggered\"]\n\n TB = 2,\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 70, "score": 55505.140696379865 }, { "content": " pub fn is_tatb(&self) -> bool {\n\n *self == SYNCWT0_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCWT0`\"]\n\npub struct SYNCWT0_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCWT0_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCWT0_A) -> &'a mut W {\n\n {\n\n self.bits(variant.into())\n\n }\n\n }\n\n #[doc = \"GPTM 32/64-Bit Timer 0 is not affected\"]\n\n #[inline(always)]\n\n pub fn none(self) -> &'a mut W {\n\n self.variant(SYNCWT0_A::NONE)\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 71, "score": 55504.981350340946 }, { "content": " pub fn is_tatb(&self) -> bool {\n\n *self == SYNCWT0_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCWT0`\"]\n\npub struct SYNCWT0_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCWT0_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCWT0_A) -> &'a mut W {\n\n {\n\n self.bits(variant.into())\n\n }\n\n }\n\n #[doc = \"GPTM 32/64-Bit Timer 0 is not affected\"]\n\n #[inline(always)]\n\n pub fn none(self) -> &'a mut W {\n\n self.variant(SYNCWT0_A::NONE)\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 72, "score": 55504.981350340946 }, { "content": " #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCT3_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCT3`\"]\n\npub struct SYNCT3_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCT3_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCT3_A) -> &'a mut W {\n\n {\n\n self.bits(variant.into())\n\n }\n\n }\n\n #[doc = \"GPTM3 is not affected\"]\n\n #[inline(always)]\n\n pub fn none(self) -> &'a mut W {\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 73, "score": 55504.37987629084 }, { "content": " #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCT3_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCT3`\"]\n\npub struct SYNCT3_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCT3_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCT3_A) -> &'a mut W {\n\n {\n\n self.bits(variant.into())\n\n }\n\n }\n\n #[doc = \"GPTM3 is not affected\"]\n\n #[inline(always)]\n\n pub fn none(self) -> &'a mut W {\n", "file_path": "crates/tm4c129x/src/timer0/sync.rs", "rank": 74, "score": 55504.37987629084 }, { "content": " #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCT3_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCT3`\"]\n\npub struct SYNCT3_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCT3_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCT3_A) -> &'a mut W {\n\n {\n\n self.bits(variant.into())\n\n }\n\n }\n\n #[doc = \"GPTM3 is not affected\"]\n\n #[inline(always)]\n\n pub fn none(self) -> &'a mut W {\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 75, "score": 55504.37987629084 }, { "content": " pub fn is_tatb(&self) -> bool {\n\n *self == SYNCT6_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCT6`\"]\n\npub struct SYNCT6_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCT6_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCT6_A) -> &'a mut W {\n\n {\n\n self.bits(variant.into())\n\n }\n\n }\n\n #[doc = \"GPTM6 is not affected\"]\n\n #[inline(always)]\n\n pub fn none(self) -> &'a mut W {\n\n self.variant(SYNCT6_A::NONE)\n", "file_path": "crates/tm4c129x/src/timer0/sync.rs", "rank": 76, "score": 55504.14314659284 }, { "content": " }\n\n #[doc = \"A timeout event for Timer A of GPTM6 is triggered\"]\n\n #[inline(always)]\n\n pub fn ta(self) -> &'a mut W {\n\n self.variant(SYNCT6_A::TA)\n\n }\n\n #[doc = \"A timeout event for Timer B of GPTM6 is triggered\"]\n\n #[inline(always)]\n\n pub fn tb(self) -> &'a mut W {\n\n self.variant(SYNCT6_A::TB)\n\n }\n\n #[doc = \"A timeout event for both Timer A and Timer B of GPTM6 is triggered\"]\n\n #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCT6_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 12)) | (((value as u32) & 0x03) << 12);\n", "file_path": "crates/tm4c129x/src/timer0/sync.rs", "rank": 77, "score": 55502.39267810274 }, { "content": " #[doc = \"A timeout event for Timer A of GPTM 32/64-Bit Timer 3 is triggered\"]\n\n #[inline(always)]\n\n pub fn ta(self) -> &'a mut W {\n\n self.variant(SYNCWT3_A::TA)\n\n }\n\n #[doc = \"A timeout event for Timer B of GPTM 32/64-Bit Timer 3 is triggered\"]\n\n #[inline(always)]\n\n pub fn tb(self) -> &'a mut W {\n\n self.variant(SYNCWT3_A::TB)\n\n }\n\n #[doc = \"A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 3 is triggered\"]\n\n #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCWT3_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 18)) | (((value as u32) & 0x03) << 18);\n\n self.w\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 78, "score": 55502.128842720085 }, { "content": " #[doc = \"A timeout event for Timer A of GPTM 32/64-Bit Timer 3 is triggered\"]\n\n #[inline(always)]\n\n pub fn ta(self) -> &'a mut W {\n\n self.variant(SYNCWT3_A::TA)\n\n }\n\n #[doc = \"A timeout event for Timer B of GPTM 32/64-Bit Timer 3 is triggered\"]\n\n #[inline(always)]\n\n pub fn tb(self) -> &'a mut W {\n\n self.variant(SYNCWT3_A::TB)\n\n }\n\n #[doc = \"A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 3 is triggered\"]\n\n #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCWT3_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 18)) | (((value as u32) & 0x03) << 18);\n\n self.w\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 79, "score": 55502.128842720085 }, { "content": " }\n\n #[doc = \"A timeout event for Timer A of GPTM 32/64-Bit Timer 0 is triggered\"]\n\n #[inline(always)]\n\n pub fn ta(self) -> &'a mut W {\n\n self.variant(SYNCWT0_A::TA)\n\n }\n\n #[doc = \"A timeout event for Timer B of GPTM 32/64-Bit Timer 0 is triggered\"]\n\n #[inline(always)]\n\n pub fn tb(self) -> &'a mut W {\n\n self.variant(SYNCWT0_A::TB)\n\n }\n\n #[doc = \"A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 0 is triggered\"]\n\n #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCWT0_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 12)) | (((value as u32) & 0x03) << 12);\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 80, "score": 55502.128842720085 }, { "content": " }\n\n #[doc = \"A timeout event for Timer A of GPTM 32/64-Bit Timer 0 is triggered\"]\n\n #[inline(always)]\n\n pub fn ta(self) -> &'a mut W {\n\n self.variant(SYNCWT0_A::TA)\n\n }\n\n #[doc = \"A timeout event for Timer B of GPTM 32/64-Bit Timer 0 is triggered\"]\n\n #[inline(always)]\n\n pub fn tb(self) -> &'a mut W {\n\n self.variant(SYNCWT0_A::TB)\n\n }\n\n #[doc = \"A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 0 is triggered\"]\n\n #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCWT0_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 12)) | (((value as u32) & 0x03) << 12);\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 81, "score": 55502.128842720085 }, { "content": " }\n\n #[doc = \"Bit 2 - Reset Generator 2 Counter\"]\n\n #[inline(always)]\n\n pub fn sync2(&mut self) -> SYNC2_W {\n\n SYNC2_W { w: self }\n\n }\n\n #[doc = \"Bit 3 - Reset Generator 3 Counter\"]\n\n #[inline(always)]\n\n pub fn sync3(&mut self) -> SYNC3_W {\n\n SYNC3_W { w: self }\n\n }\n\n}\n", "file_path": "crates/tm4c123x/src/pwm0/sync.rs", "rank": 83, "score": 55501.0606420349 }, { "content": " self.variant(SYNCWT2_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 16)) | (((value as u32) & 0x03) << 16);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM 32/64-Bit Timer 3\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCWT3_A {\n\n #[doc = \"0: GPTM 32/64-Bit Timer 3 is not affected\"]\n\n NONE = 0,\n\n #[doc = \"1: A timeout event for Timer A of GPTM 32/64-Bit Timer 3 is triggered\"]\n\n TA = 1,\n\n #[doc = \"2: A timeout event for Timer B of GPTM 32/64-Bit Timer 3 is triggered\"]\n\n TB = 2,\n\n #[doc = \"3: A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 3 is triggered\"]\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 84, "score": 55501.02190793206 }, { "content": " self.variant(SYNCWT2_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x03 << 16)) | (((value as u32) & 0x03) << 16);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM 32/64-Bit Timer 3\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCWT3_A {\n\n #[doc = \"0: GPTM 32/64-Bit Timer 3 is not affected\"]\n\n NONE = 0,\n\n #[doc = \"1: A timeout event for Timer A of GPTM 32/64-Bit Timer 3 is triggered\"]\n\n TA = 1,\n\n #[doc = \"2: A timeout event for Timer B of GPTM 32/64-Bit Timer 3 is triggered\"]\n\n TB = 2,\n\n #[doc = \"3: A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 3 is triggered\"]\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 85, "score": 55501.02190793206 }, { "content": " *self == SYNCWT3_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCWT3`\"]\n\npub struct SYNCWT3_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCWT3_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCWT3_A) -> &'a mut W {\n\n {\n\n self.bits(variant.into())\n\n }\n\n }\n\n #[doc = \"GPTM 32/64-Bit Timer 3 is not affected\"]\n\n #[inline(always)]\n\n pub fn none(self) -> &'a mut W {\n\n self.variant(SYNCWT3_A::NONE)\n\n }\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 86, "score": 55500.98892818918 }, { "content": " *self == SYNCWT3_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCWT3`\"]\n\npub struct SYNCWT3_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SYNCWT3_W<'a> {\n\n #[doc = r\"Writes `variant` to the field\"]\n\n #[inline(always)]\n\n pub fn variant(self, variant: SYNCWT3_A) -> &'a mut W {\n\n {\n\n self.bits(variant.into())\n\n }\n\n }\n\n #[doc = \"GPTM 32/64-Bit Timer 3 is not affected\"]\n\n #[inline(always)]\n\n pub fn none(self) -> &'a mut W {\n\n self.variant(SYNCWT3_A::NONE)\n\n }\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 87, "score": 55500.98892818918 }, { "content": " }\n\n #[doc = \"Checks if the value of the field is `TA`\"]\n\n #[inline(always)]\n\n pub fn is_ta(&self) -> bool {\n\n *self == SYNCWT1_A::TA\n\n }\n\n #[doc = \"Checks if the value of the field is `TB`\"]\n\n #[inline(always)]\n\n pub fn is_tb(&self) -> bool {\n\n *self == SYNCWT1_A::TB\n\n }\n\n #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCWT1_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCWT1`\"]\n\npub struct SYNCWT1_W<'a> {\n\n w: &'a mut W,\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 88, "score": 55499.63351376302 }, { "content": " }\n\n #[doc = \"Checks if the value of the field is `TA`\"]\n\n #[inline(always)]\n\n pub fn is_ta(&self) -> bool {\n\n *self == SYNCT7_A::TA\n\n }\n\n #[doc = \"Checks if the value of the field is `TB`\"]\n\n #[inline(always)]\n\n pub fn is_tb(&self) -> bool {\n\n *self == SYNCT7_A::TB\n\n }\n\n #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCT7_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCT7`\"]\n\npub struct SYNCT7_W<'a> {\n\n w: &'a mut W,\n", "file_path": "crates/tm4c129x/src/timer0/sync.rs", "rank": 89, "score": 55499.63351376302 }, { "content": " #[doc = \"Checks if the value of the field is `TA`\"]\n\n #[inline(always)]\n\n pub fn is_ta(&self) -> bool {\n\n *self == SYNCWT4_A::TA\n\n }\n\n #[doc = \"Checks if the value of the field is `TB`\"]\n\n #[inline(always)]\n\n pub fn is_tb(&self) -> bool {\n\n *self == SYNCWT4_A::TB\n\n }\n\n #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCWT4_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCWT4`\"]\n\npub struct SYNCWT4_W<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 90, "score": 55499.63351376302 }, { "content": " }\n\n #[doc = \"Checks if the value of the field is `TA`\"]\n\n #[inline(always)]\n\n pub fn is_ta(&self) -> bool {\n\n *self == SYNCWT1_A::TA\n\n }\n\n #[doc = \"Checks if the value of the field is `TB`\"]\n\n #[inline(always)]\n\n pub fn is_tb(&self) -> bool {\n\n *self == SYNCWT1_A::TB\n\n }\n\n #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCWT1_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCWT1`\"]\n\npub struct SYNCWT1_W<'a> {\n\n w: &'a mut W,\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 91, "score": 55499.63351376302 }, { "content": " #[doc = \"Checks if the value of the field is `TA`\"]\n\n #[inline(always)]\n\n pub fn is_ta(&self) -> bool {\n\n *self == SYNCWT4_A::TA\n\n }\n\n #[doc = \"Checks if the value of the field is `TB`\"]\n\n #[inline(always)]\n\n pub fn is_tb(&self) -> bool {\n\n *self == SYNCWT4_A::TB\n\n }\n\n #[doc = \"Checks if the value of the field is `TATB`\"]\n\n #[inline(always)]\n\n pub fn is_tatb(&self) -> bool {\n\n *self == SYNCWT4_A::TATB\n\n }\n\n}\n\n#[doc = \"Write proxy for field `SYNCWT4`\"]\n\npub struct SYNCWT4_W<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 92, "score": 55499.63351376302 }, { "content": " pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !0x03) | ((value as u32) & 0x03);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM Timer 1\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCT1_A {\n\n #[doc = \"0: GPTM1 is not affected\"]\n\n NONE = 0,\n\n #[doc = \"1: A timeout event for Timer A of GPTM1 is triggered\"]\n\n TA = 1,\n\n #[doc = \"2: A timeout event for Timer B of GPTM1 is triggered\"]\n\n TB = 2,\n\n #[doc = \"3: A timeout event for both Timer A and Timer B of GPTM1 is triggered\"]\n\n TATB = 3,\n\n}\n\nimpl From<SYNCT1_A> for u8 {\n\n #[inline(always)]\n", "file_path": "crates/tm4c129x/src/timer0/sync.rs", "rank": 93, "score": 55498.05020128698 }, { "content": " pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !0x03) | ((value as u32) & 0x03);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM Timer 1\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCT1_A {\n\n #[doc = \"0: GPTM1 is not affected\"]\n\n NONE = 0,\n\n #[doc = \"1: A timeout event for Timer A of GPTM1 is triggered\"]\n\n TA = 1,\n\n #[doc = \"2: A timeout event for Timer B of GPTM1 is triggered\"]\n\n TB = 2,\n\n #[doc = \"3: A timeout event for both Timer A and Timer B of GPTM1 is triggered\"]\n\n TATB = 3,\n\n}\n\nimpl From<SYNCT1_A> for u8 {\n\n #[inline(always)]\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 94, "score": 55498.05020128698 }, { "content": " pub fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !0x03) | ((value as u32) & 0x03);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Synchronize GPTM Timer 1\\n\\nValue on reset: 0\"]\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\n#[repr(u8)]\n\npub enum SYNCT1_A {\n\n #[doc = \"0: GPTM1 is not affected\"]\n\n NONE = 0,\n\n #[doc = \"1: A timeout event for Timer A of GPTM1 is triggered\"]\n\n TA = 1,\n\n #[doc = \"2: A timeout event for Timer B of GPTM1 is triggered\"]\n\n TB = 2,\n\n #[doc = \"3: A timeout event for both Timer A and Timer B of GPTM1 is triggered\"]\n\n TATB = 3,\n\n}\n\nimpl From<SYNCT1_A> for u8 {\n\n #[inline(always)]\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 95, "score": 55498.05020128698 }, { "content": " variant as _\n\n }\n\n}\n\n#[doc = \"Reader of field `SYNCT4`\"]\n\npub type SYNCT4_R = crate::R<u8, SYNCT4_A>;\n\nimpl SYNCT4_R {\n\n #[doc = r\"Get enumerated values variant\"]\n\n #[inline(always)]\n\n pub fn variant(&self) -> SYNCT4_A {\n\n match self.bits {\n\n 0 => SYNCT4_A::NONE,\n\n 1 => SYNCT4_A::TA,\n\n 2 => SYNCT4_A::TB,\n\n 3 => SYNCT4_A::TATB,\n\n _ => unreachable!(),\n\n }\n\n }\n\n #[doc = \"Checks if the value of the field is `NONE`\"]\n\n #[inline(always)]\n\n pub fn is_none(&self) -> bool {\n", "file_path": "crates/tm4c129x/src/timer0/sync.rs", "rank": 96, "score": 55496.58998247804 }, { "content": " variant as _\n\n }\n\n}\n\n#[doc = \"Reader of field `SYNCT4`\"]\n\npub type SYNCT4_R = crate::R<u8, SYNCT4_A>;\n\nimpl SYNCT4_R {\n\n #[doc = r\"Get enumerated values variant\"]\n\n #[inline(always)]\n\n pub fn variant(&self) -> SYNCT4_A {\n\n match self.bits {\n\n 0 => SYNCT4_A::NONE,\n\n 1 => SYNCT4_A::TA,\n\n 2 => SYNCT4_A::TB,\n\n 3 => SYNCT4_A::TATB,\n\n _ => unreachable!(),\n\n }\n\n }\n\n #[doc = \"Checks if the value of the field is `NONE`\"]\n\n #[inline(always)]\n\n pub fn is_none(&self) -> bool {\n", "file_path": "crates/tm4c123x/src/wtimer0/sync.rs", "rank": 97, "score": 55496.58998247804 }, { "content": " variant as _\n\n }\n\n}\n\n#[doc = \"Reader of field `SYNCT4`\"]\n\npub type SYNCT4_R = crate::R<u8, SYNCT4_A>;\n\nimpl SYNCT4_R {\n\n #[doc = r\"Get enumerated values variant\"]\n\n #[inline(always)]\n\n pub fn variant(&self) -> SYNCT4_A {\n\n match self.bits {\n\n 0 => SYNCT4_A::NONE,\n\n 1 => SYNCT4_A::TA,\n\n 2 => SYNCT4_A::TB,\n\n 3 => SYNCT4_A::TATB,\n\n _ => unreachable!(),\n\n }\n\n }\n\n #[doc = \"Checks if the value of the field is `NONE`\"]\n\n #[inline(always)]\n\n pub fn is_none(&self) -> bool {\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 98, "score": 55496.58998247804 }, { "content": " self.variant(SYNCT3_A::NONE)\n\n }\n\n #[doc = \"A timeout event for Timer A of GPTM3 is triggered\"]\n\n #[inline(always)]\n\n pub fn ta(self) -> &'a mut W {\n\n self.variant(SYNCT3_A::TA)\n\n }\n\n #[doc = \"A timeout event for Timer B of GPTM3 is triggered\"]\n\n #[inline(always)]\n\n pub fn tb(self) -> &'a mut W {\n\n self.variant(SYNCT3_A::TB)\n\n }\n\n #[doc = \"A timeout event for both Timer A and Timer B of GPTM3 is triggered\"]\n\n #[inline(always)]\n\n pub fn tatb(self) -> &'a mut W {\n\n self.variant(SYNCT3_A::TATB)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bits(self, value: u8) -> &'a mut W {\n", "file_path": "crates/tm4c123x/src/timer0/sync.rs", "rank": 99, "score": 55496.50933049585 } ]
Rust
benches/xml.rs
sahwar/roxmltree
fb3315cee821a370c6f90f33f3e65072dc735848
#![allow(dead_code)] #[macro_use] extern crate bencher; extern crate roxmltree; extern crate xmlparser; extern crate xmltree; extern crate sxd_document; extern crate elementtree; extern crate treexml; extern crate xml; use std::fs; use std::env; use std::io::Read; use bencher::Bencher; fn load_string(path: &str) -> String { let path = env::current_dir().unwrap().join(path); let mut file = fs::File::open(&path).unwrap(); let mut text = String::new(); file.read_to_string(&mut text).unwrap(); text } fn load_data(path: &str) -> Vec<u8> { let path = env::current_dir().unwrap().join(path); let mut file = fs::File::open(&path).unwrap(); let mut buf = Vec::new(); file.read_to_end(&mut buf).unwrap(); buf } fn tiny_xmlparser(bencher: &mut Bencher) { let text = load_string("fonts.conf"); bencher.iter(|| { for t in xmlparser::Tokenizer::from(text.as_str()) { let _ = t.unwrap(); } }) } fn medium_xmlparser(bencher: &mut Bencher) { let text = load_string("medium.svg"); bencher.iter(|| { for t in xmlparser::Tokenizer::from(text.as_str()) { let _ = t.unwrap(); } }) } fn large_xmlparser(bencher: &mut Bencher) { let text = load_string("large.plist"); bencher.iter(|| { for t in xmlparser::Tokenizer::from(text.as_str()) { let _ = t.unwrap(); } }) } fn tiny_xmlrs(bencher: &mut Bencher) { let text = load_string("fonts.conf"); bencher.iter(|| { for event in xml::EventReader::new(text.as_bytes()) { let _ = event.unwrap(); } }) } fn medium_xmlrs(bencher: &mut Bencher) { let text = load_string("medium.svg"); bencher.iter(|| { for event in xml::EventReader::new(text.as_bytes()) { let _ = event.unwrap(); } }) } fn large_xmlrs(bencher: &mut Bencher) { let text = load_string("large.plist"); bencher.iter(|| { for event in xml::EventReader::new(text.as_bytes()) { let _ = event.unwrap(); } }) } fn tiny_roxmltree(bencher: &mut Bencher) { let text = load_string("fonts.conf"); bencher.iter(|| roxmltree::Document::parse(&text).unwrap()) } fn medium_roxmltree(bencher: &mut Bencher) { let text = load_string("medium.svg"); bencher.iter(|| roxmltree::Document::parse(&text).unwrap()) } fn large_roxmltree(bencher: &mut Bencher) { let text = load_string("large.plist"); bencher.iter(|| roxmltree::Document::parse(&text).unwrap()) } fn tiny_xmltree(bencher: &mut Bencher) { let text = load_string("fonts.conf"); bencher.iter(|| xmltree::Element::parse(text.as_bytes()).unwrap()) } fn medium_xmltree(bencher: &mut Bencher) { let text = load_string("medium.svg"); bencher.iter(|| xmltree::Element::parse(text.as_bytes()).unwrap()) } fn large_xmltree(bencher: &mut Bencher) { let text = load_string("large.plist"); bencher.iter(|| xmltree::Element::parse(text.as_bytes()).unwrap()) } fn tiny_sdx_document(bencher: &mut Bencher) { let text = load_string("fonts.conf"); bencher.iter(|| sxd_document::parser::parse(&text).unwrap()) } fn medium_sdx_document(bencher: &mut Bencher) { let text = load_string("medium.svg"); bencher.iter(|| sxd_document::parser::parse(&text).unwrap()) } fn large_sdx_document(bencher: &mut Bencher) { let text = load_string("large.plist"); bencher.iter(|| sxd_document::parser::parse(&text).unwrap()) } fn tiny_elementtree(bencher: &mut Bencher) { let data = load_data("fonts.conf"); bencher.iter(|| elementtree::Element::from_reader(&data[..]).unwrap()) } fn medium_elementtree(bencher: &mut Bencher) { let data = load_data("medium.svg"); bencher.iter(|| elementtree::Element::from_reader(&data[..]).unwrap()) } fn large_elementtree(bencher: &mut Bencher) { let data = load_data("large.plist"); bencher.iter(|| elementtree::Element::from_reader(&data[..]).unwrap()) } fn tiny_treexml(bencher: &mut Bencher) { let data = load_data("fonts.conf"); bencher.iter(|| treexml::Document::parse(&data[..]).unwrap()) } fn medium_treexml(bencher: &mut Bencher) { let data = load_data("medium.svg"); bencher.iter(|| treexml::Document::parse(&data[..]).unwrap()) } fn large_treexml(bencher: &mut Bencher) { let data = load_data("large.plist"); bencher.iter(|| treexml::Document::parse(&data[..]).unwrap()) } benchmark_group!(roxmltree, tiny_roxmltree, medium_roxmltree, large_roxmltree); benchmark_group!(xmltree, tiny_xmltree, medium_xmltree, large_xmltree); benchmark_group!(sdx, tiny_sdx_document, medium_sdx_document, large_sdx_document); benchmark_group!(elementtree, tiny_elementtree, medium_elementtree, large_elementtree); benchmark_group!(treexml, tiny_treexml, medium_treexml, large_treexml); benchmark_group!(xmlparser, tiny_xmlparser, medium_xmlparser, large_xmlparser); benchmark_group!(xmlrs, tiny_xmlrs, medium_xmlrs, large_xmlrs); benchmark_main!(roxmltree, xmltree, sdx, elementtree, treexml, xmlparser, xmlrs);
#![allow(dead_code)] #[macro_use] extern crate bencher; extern crate roxmltree; extern crate xmlparser; extern crate xmltree; extern crate sxd_document; extern crate elementtree; extern crate treexml; extern crate xml; use std::fs; use std::env; use std::io::Read; use bencher::Bencher; fn load_string(path: &str) -> String { let path = env::current_dir().unwrap().join(path); let mut file = fs::File::open(&path).unwrap(); let mut text = String::new(); file.read_to_string(&mut text).unwrap(); text } fn load_data(path: &str) -> Vec<u8> { let path = env::current_dir().unwrap().join(path); let mut file = fs::File::open(&path).unwrap(); let mut buf = Vec::new(); file.read_to_end(&mut buf).unwrap(); buf } fn tiny_xmlparser(bencher: &mut Bencher) { let text = load_string("fonts.conf"); bencher.iter(|| { for t in xmlparser::Tokenizer::from(text.as_str()) { let _ = t.unwrap(); } }) } fn medium_xmlparser(bencher: &mut Bencher) { let text = load_string("medium.svg"); bencher.iter(|| { for t in xmlparser::Tokenizer::from(text.as_str()) { let _ = t.unwrap(); } }) } fn large_xmlparser(bencher: &mut Bencher) { let text = load_string("large.plist"); bencher.iter(|| { for t in xmlparser::Tokenizer::from(text.as_str()) { let _ = t.unwrap(); } }) } fn tiny_xmlrs(bencher: &mut Bencher) { let text = load_string("fonts.conf"); bencher.iter(|| { for event in xml::EventReader::new(text.as_bytes()) { let _ = event.unwrap(); } }) } fn medium_xmlrs(bencher: &mut Bencher) { let text = load_string("medium.svg");
fn large_xmlrs(bencher: &mut Bencher) { let text = load_string("large.plist"); bencher.iter(|| { for event in xml::EventReader::new(text.as_bytes()) { let _ = event.unwrap(); } }) } fn tiny_roxmltree(bencher: &mut Bencher) { let text = load_string("fonts.conf"); bencher.iter(|| roxmltree::Document::parse(&text).unwrap()) } fn medium_roxmltree(bencher: &mut Bencher) { let text = load_string("medium.svg"); bencher.iter(|| roxmltree::Document::parse(&text).unwrap()) } fn large_roxmltree(bencher: &mut Bencher) { let text = load_string("large.plist"); bencher.iter(|| roxmltree::Document::parse(&text).unwrap()) } fn tiny_xmltree(bencher: &mut Bencher) { let text = load_string("fonts.conf"); bencher.iter(|| xmltree::Element::parse(text.as_bytes()).unwrap()) } fn medium_xmltree(bencher: &mut Bencher) { let text = load_string("medium.svg"); bencher.iter(|| xmltree::Element::parse(text.as_bytes()).unwrap()) } fn large_xmltree(bencher: &mut Bencher) { let text = load_string("large.plist"); bencher.iter(|| xmltree::Element::parse(text.as_bytes()).unwrap()) } fn tiny_sdx_document(bencher: &mut Bencher) { let text = load_string("fonts.conf"); bencher.iter(|| sxd_document::parser::parse(&text).unwrap()) } fn medium_sdx_document(bencher: &mut Bencher) { let text = load_string("medium.svg"); bencher.iter(|| sxd_document::parser::parse(&text).unwrap()) } fn large_sdx_document(bencher: &mut Bencher) { let text = load_string("large.plist"); bencher.iter(|| sxd_document::parser::parse(&text).unwrap()) } fn tiny_elementtree(bencher: &mut Bencher) { let data = load_data("fonts.conf"); bencher.iter(|| elementtree::Element::from_reader(&data[..]).unwrap()) } fn medium_elementtree(bencher: &mut Bencher) { let data = load_data("medium.svg"); bencher.iter(|| elementtree::Element::from_reader(&data[..]).unwrap()) } fn large_elementtree(bencher: &mut Bencher) { let data = load_data("large.plist"); bencher.iter(|| elementtree::Element::from_reader(&data[..]).unwrap()) } fn tiny_treexml(bencher: &mut Bencher) { let data = load_data("fonts.conf"); bencher.iter(|| treexml::Document::parse(&data[..]).unwrap()) } fn medium_treexml(bencher: &mut Bencher) { let data = load_data("medium.svg"); bencher.iter(|| treexml::Document::parse(&data[..]).unwrap()) } fn large_treexml(bencher: &mut Bencher) { let data = load_data("large.plist"); bencher.iter(|| treexml::Document::parse(&data[..]).unwrap()) } benchmark_group!(roxmltree, tiny_roxmltree, medium_roxmltree, large_roxmltree); benchmark_group!(xmltree, tiny_xmltree, medium_xmltree, large_xmltree); benchmark_group!(sdx, tiny_sdx_document, medium_sdx_document, large_sdx_document); benchmark_group!(elementtree, tiny_elementtree, medium_elementtree, large_elementtree); benchmark_group!(treexml, tiny_treexml, medium_treexml, large_treexml); benchmark_group!(xmlparser, tiny_xmlparser, medium_xmlparser, large_xmlparser); benchmark_group!(xmlrs, tiny_xmlrs, medium_xmlrs, large_xmlrs); benchmark_main!(roxmltree, xmltree, sdx, elementtree, treexml, xmlparser, xmlrs);
bencher.iter(|| { for event in xml::EventReader::new(text.as_bytes()) { let _ = event.unwrap(); } }) }
function_block-function_prefixed
[ { "content": "fn load_file(path: &str) -> String {\n\n let mut file = fs::File::open(&path).unwrap();\n\n let mut text = String::new();\n\n file.read_to_string(&mut text).unwrap();\n\n text\n\n}\n", "file_path": "examples/ast.rs", "rank": 1, "score": 190922.63934523566 }, { "content": "fn load_file(path: &str) -> String {\n\n let mut file = fs::File::open(&path).unwrap();\n\n let mut text = String::new();\n\n file.read_to_string(&mut text).unwrap();\n\n text\n\n}\n", "file_path": "examples/stats.rs", "rank": 2, "score": 190922.63934523563 }, { "content": "fn load_file(path: &str) -> String {\n\n let mut file = fs::File::open(&path).unwrap();\n\n let mut text = String::new();\n\n file.read_to_string(&mut text).unwrap();\n\n text\n\n}\n", "file_path": "examples/print_pos.rs", "rank": 3, "score": 185718.01225783827 }, { "content": "fn load_file(path: &path::Path) -> String {\n\n let mut file = fs::File::open(&path).unwrap();\n\n let mut text = String::new();\n\n file.read_to_string(&mut text).unwrap();\n\n text\n\n}\n\n\n", "file_path": "tests/ast.rs", "rank": 13, "score": 164736.15541319904 }, { "content": "fn gen_qname_string(prefix: &str, local: &str) -> String {\n\n if prefix.is_empty() {\n\n local.to_string()\n\n } else {\n\n format!(\"{}:{}\", prefix, local)\n\n }\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 27, "score": 132904.67501220954 }, { "content": "fn actual_test(path: path::PathBuf) {\n\n let expected = load_file(&path.with_extension(\"yaml\"));\n\n\n\n let input_xml = load_file(&path);\n\n let doc = match Document::parse(&input_xml) {\n\n Ok(v) => v,\n\n Err(e) => {\n\n assert_eq!(TStr(&format!(\"error: \\\"{}\\\"\", e)), TStr(expected.trim()));\n\n return;\n\n }\n\n };\n\n\n\n assert_eq!(TStr(&to_yaml(&doc)), TStr(&expected));\n\n}\n\n\n", "file_path": "tests/ast.rs", "rank": 28, "score": 121931.70972503148 }, { "content": "fn create_test(path: path::PathBuf) -> TestDescAndFn {\n\n let name = path.file_name().unwrap().to_str().unwrap().to_string();\n\n\n\n TestDescAndFn {\n\n desc: TestDesc::new(DynTestName(name)),\n\n testfn: DynTestFn(Box::new(move || actual_test(path.clone()))),\n\n }\n\n}\n\n\n", "file_path": "tests/ast.rs", "rank": 29, "score": 120126.95918333891 }, { "content": "fn parse(text: &str) -> Result<Document, Error> {\n\n let mut pd = ParserData {\n\n attrs_start_idx: 0,\n\n ns_start_idx: 1,\n\n tmp_attrs: Vec::with_capacity(16),\n\n entities: Vec::new(),\n\n buffer: TextBuffer::new(),\n\n after_text: false,\n\n };\n\n\n\n // Trying to guess rough nodes and attributes amount.\n\n let nodes_capacity = text.bytes().filter(|c| *c == b'<').count();\n\n let attributes_capacity = text.bytes().filter(|c| *c == b'=').count();\n\n\n\n // Init document.\n\n let mut doc = Document {\n\n text,\n\n nodes: Vec::with_capacity(nodes_capacity),\n\n attrs: Vec::with_capacity(attributes_capacity),\n\n namespaces: Namespaces(Vec::new()),\n", "file_path": "src/parse.rs", "rank": 30, "score": 112687.57849688482 }, { "content": "fn err_pos_from_span(text: StrSpan) -> TextPos {\n\n Stream::from(text).gen_text_pos()\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 31, "score": 103838.73456804908 }, { "content": "fn is_normalization_required(text: &StrSpan) -> bool {\n\n // We assume that `&` indicates an entity or a character reference.\n\n // But in rare cases it can be just an another character.\n\n\n\n fn check(c: u8) -> bool {\n\n match c {\n\n b'&'\n\n | b'\\t'\n\n | b'\\n'\n\n | b'\\r' => true,\n\n _ => false,\n\n }\n\n }\n\n\n\n text.to_str().bytes().any(check)\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 32, "score": 100193.92272893488 }, { "content": "fn _to_yaml(doc: &Document, s: &mut String) -> Result<(), fmt::Error> {\n\n if !doc.root().has_children() {\n\n return write!(s, \"Document:\");\n\n }\n\n\n\n macro_rules! writeln_indented {\n\n ($depth:expr, $f:expr, $fmt:expr) => {\n\n for _ in 0..$depth { write!($f, \" \")?; }\n\n writeln!($f, $fmt)?;\n\n };\n\n ($depth:expr, $f:expr, $fmt:expr, $($arg:tt)*) => {\n\n for _ in 0..$depth { write!($f, \" \")?; }\n\n writeln!($f, $fmt, $($arg)*)?;\n\n };\n\n }\n\n\n\n fn print_children(parent: Node, depth: usize, s: &mut String) -> Result<(), fmt::Error> {\n\n for child in parent.children() {\n\n match child.node_type() {\n\n NodeType::Element => {\n", "file_path": "tests/ast.rs", "rank": 33, "score": 98192.04939830421 }, { "content": "fn to_yaml(doc: &Document) -> String {\n\n let mut s = String::new();\n\n _to_yaml(doc, &mut s).unwrap();\n\n s\n\n}\n\n\n", "file_path": "tests/ast.rs", "rank": 34, "score": 81698.87849182828 }, { "content": "fn err_pos_from_qname(prefix: StrSpan, local: StrSpan) -> TextPos {\n\n let err_span = if prefix.is_empty() { local } else { prefix };\n\n err_pos_from_span(err_span)\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 35, "score": 74648.92273674463 }, { "content": "fn err_pos_for_close_tag(prefix: StrSpan, local: StrSpan) -> TextPos {\n\n let mut pos = err_pos_from_qname(prefix, local);\n\n pos.col -= 2; // jump before '</'\n\n pos\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 36, "score": 72677.89406355041 }, { "content": "#[test]\n\nfn get_text_01() {\n\n let data = \"\\\n\n<root>\n\n Text1\n\n <item>\n\n Text2\n\n </item>\n\n Text3\n\n</root>\n\n\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let root = doc.root_element();\n\n\n\n assert_eq!(root.text(), Some(\"\\n Text1\\n \"));\n\n assert_eq!(root.tail(), None);\n\n\n\n let item = root.children().nth(1).unwrap();\n\n\n\n assert_eq!(item.text(), Some(\"\\n Text2\\n \"));\n\n assert_eq!(item.tail(), Some(\"\\n Text3\\n\"));\n\n}\n\n\n", "file_path": "tests/api.rs", "rank": 37, "score": 71158.96749248347 }, { "content": "#[test]\n\nfn get_text_02() {\n\n let data = \"<root>&apos;</root>\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let root = doc.root_element();\n\n\n\n assert_eq!(root.text(), Some(\"'\"));\n\n}\n\n\n", "file_path": "tests/api.rs", "rank": 38, "score": 71158.96749248347 }, { "content": "#[test]\n\nfn text_pos_02() {\n\n let data = \"<n1:e xmlns:n1='http://www.w3.org' n1:a='b'/>\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let node = doc.root_element();\n\n\n\n assert_eq!(node.node_pos(), TextPos::new(1, 1));\n\n assert_eq!(node.attribute_pos((\"http://www.w3.org\", \"a\")).unwrap(), TextPos::new(1, 36));\n\n assert_eq!(node.attribute_value_pos((\"http://www.w3.org\", \"a\")).unwrap(), TextPos::new(1, 42));\n\n}\n\n\n", "file_path": "tests/api.rs", "rank": 39, "score": 71158.96749248347 }, { "content": "#[test]\n\nfn text_pos_03() {\n\n let data = \"\\\n\n<!-- comment -->\n\n<e/>\n\n\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let node = doc.root_element();\n\n\n\n assert_eq!(node.node_pos(), TextPos::new(2, 1));\n\n}\n\n\n", "file_path": "tests/api.rs", "rank": 40, "score": 71158.96749248347 }, { "content": "#[test]\n\nfn text_pos_01() {\n\n let data = \"\\\n\n<e a='b'>\n\n <!-- comment -->\n\n <p>Text</p>\n\n</e>\n\n\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let node = doc.root_element();\n\n\n\n assert_eq!(node.node_pos(), TextPos::new(1, 1));\n\n assert_eq!(node.attribute_pos(\"a\").unwrap(), TextPos::new(1, 4));\n\n assert_eq!(node.attribute_value_pos(\"a\").unwrap(), TextPos::new(1, 7));\n\n\n\n // first child is a text/whitespace, not a comment\n\n let comm = node.first_child().unwrap().next_sibling().unwrap();\n\n assert_eq!(comm.node_pos(), TextPos::new(2, 5));\n\n\n\n let p = comm.next_sibling().unwrap().next_sibling().unwrap();\n\n assert_eq!(p.node_pos(), TextPos::new(3, 5));\n\n\n\n let text = p.first_child().unwrap();\n\n assert_eq!(text.node_pos(), TextPos::new(3, 8));\n\n}\n\n\n", "file_path": "tests/api.rs", "rank": 41, "score": 71158.96749248347 }, { "content": "fn append_text<'d>(\n\n text: Cow<'d, str>,\n\n parent_id: NodeId,\n\n orig_pos: usize,\n\n after_text: bool,\n\n doc: &mut Document<'d>,\n\n) {\n\n if after_text {\n\n // Prepend to a previous text node.\n\n if let Some(node) = doc.nodes.iter_mut().last() {\n\n if let NodeKind::Text(ref mut prev_text) = node.kind {\n\n match *prev_text {\n\n Cow::Borrowed(..) => {\n\n *prev_text = Cow::Owned(prev_text.to_string() + text.borrow());\n\n }\n\n Cow::Owned(ref mut s) => {\n\n s.push_str(text.borrow());\n\n }\n\n }\n\n }\n\n }\n\n } else {\n\n doc.append(parent_id, NodeKind::Text(text), orig_pos);\n\n }\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 42, "score": 69349.71532696458 }, { "content": "fn process_text<'d>(\n\n text: StrSpan<'d>,\n\n parent_id: NodeId,\n\n entity_depth: u8,\n\n pd: &mut ParserData<'d>,\n\n doc: &mut Document<'d>,\n\n) -> Result<(), Error> {\n\n // Add text as is if it has only valid characters.\n\n if !text.to_str().bytes().any(|b| b == b'&' || b == b'\\r') {\n\n append_text(Cow::Borrowed(text.to_str()), parent_id, text.start(), pd.after_text, doc);\n\n pd.after_text = true;\n\n return Ok(());\n\n }\n\n\n\n fn _append_text(parent_id: NodeId, orig_pos: usize, pd: &mut ParserData, doc: &mut Document) {\n\n let cow_text = Cow::Owned(pd.buffer.to_str().to_owned());\n\n append_text(cow_text, parent_id, orig_pos, pd.after_text, doc);\n\n pd.after_text = true;\n\n pd.buffer.clear();\n\n }\n", "file_path": "src/parse.rs", "rank": 43, "score": 69349.71532696458 }, { "content": "#[derive(Clone, Copy, PartialEq)]\n\nstruct TStr<'a>(pub &'a str);\n\n\n\nimpl<'a> fmt::Debug for TStr<'a> {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{}\", self.0)\n\n }\n\n}\n\n\n\n\n", "file_path": "tests/ast.rs", "rank": 44, "score": 52401.62682626934 }, { "content": "struct Uri(Rc<String>);\n\n\n\nimpl Uri {\n\n fn new(text: String) -> Self {\n\n Uri(Rc::new(text))\n\n }\n\n\n\n fn as_str(&self) -> &str {\n\n self.0.as_str()\n\n }\n\n}\n\n\n\nimpl Clone for Uri {\n\n fn clone(&self) -> Self {\n\n Uri(Rc::clone(&self.0))\n\n }\n\n}\n\n\n\nimpl PartialEq for Uri {\n\n fn eq(&self, other: &Uri) -> bool {\n", "file_path": "src/lib.rs", "rank": 45, "score": 48079.07763292345 }, { "content": "#[test]\n\nfn lifetimes() {\n\n fn f<'a, 'd, F, R>(doc: &'a roxmltree::Document<'d>, fun: F) -> R \n\n where F: Fn(&'a roxmltree::Document<'d>) -> R\n\n {\n\n fun(doc)\n\n }\n\n\n\n let doc = roxmltree::Document::parse(\"<e xmlns='http://www.w3.org'/>\").unwrap();\n\n\n\n let _ = f(&doc, |d| d.root());\n\n let _ = f(&doc, |d| d.root().document());\n\n let _ = f(&doc, |d| d.root().tag_name());\n\n let _ = f(&doc, |d| d.root().tag_name().namespace());\n\n let _ = f(&doc, |d| d.root().tag_name().name());\n\n let _ = f(&doc, |d| d.root().default_namespace());\n\n let _ = f(&doc, |d| d.root().resolve_tag_name_prefix());\n\n let _ = f(&doc, |d| d.root().lookup_prefix(\"\"));\n\n let _ = f(&doc, |d| d.root().lookup_namespace_uri(None));\n\n let _ = f(&doc, |d| d.root().attribute(\"a\"));\n\n let _ = f(&doc, |d| d.root().attributes());\n\n let _ = f(&doc, |d| d.root().namespaces());\n\n let _ = f(&doc, |d| d.root().text());\n\n let _ = f(&doc, |d| d.root().tail());\n\n let _ = f(&doc, |d| d.root().pi());\n\n}\n", "file_path": "tests/api.rs", "rank": 46, "score": 45206.31966624264 }, { "content": "#[test]\n\nfn run() {\n\n let mut tests = Vec::new();\n\n\n\n for entry in fs::read_dir(\"tests/files\").unwrap() {\n\n let entry = entry.unwrap();\n\n\n\n if !entry.path().has_extension(\"xml\") {\n\n continue;\n\n }\n\n\n\n let file_name = entry.path().file_name().unwrap().to_str().unwrap().to_string();\n\n if !IGNORE.contains(&file_name.as_str()) {\n\n tests.push(create_test(entry.path()));\n\n }\n\n }\n\n\n\n let args: Vec<String> = env::args().collect();\n\n rustc_test::test_main(&args[..1], tests);\n\n}\n\n\n", "file_path": "tests/ast.rs", "rank": 47, "score": 45206.31966624264 }, { "content": "#[test]\n\nfn api_01() {\n\n let data = \"\\\n\n<e a:attr='a_ns' b:attr='b_ns' attr='no_ns' xmlns:b='http://www.ietf.org' \\\n\n xmlns:a='http://www.w3.org' xmlns='http://www.uvic.ca'/>\n\n\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let p = doc.root_element();\n\n\n\n assert_eq!(p.attribute(\"attr\"), Some(\"no_ns\"));\n\n assert_eq!(p.has_attribute(\"attr\"), true);\n\n\n\n assert_eq!(p.attribute((\"http://www.w3.org\", \"attr\")), Some(\"a_ns\"));\n\n assert_eq!(p.has_attribute((\"http://www.w3.org\", \"attr\")), true);\n\n\n\n assert_eq!(p.attribute(\"attr2\"), None);\n\n assert_eq!(p.has_attribute(\"attr2\"), false);\n\n\n\n assert_eq!(p.attribute((\"http://www.w2.org\", \"attr\")), None);\n\n assert_eq!(p.has_attribute((\"http://www.w2.org\", \"attr\")), false);\n\n\n\n assert_eq!(p.attribute(\"b\"), None);\n\n assert_eq!(p.has_attribute(\"b\"), false);\n\n\n\n assert_eq!(p.attribute(\"xmlns\"), None);\n\n assert_eq!(p.has_attribute(\"xmlns\"), false);\n\n}\n\n\n", "file_path": "tests/api.rs", "rank": 48, "score": 45206.31966624264 }, { "content": "fn main() {\n\n let args: Vec<_> = env::args().collect();\n\n\n\n if args.len() != 2 {\n\n println!(\"Usage:\\n\\tcargo run --example stats -- input.xml\");\n\n process::exit(1);\n\n }\n\n\n\n let text = load_file(&args[1]);\n\n let doc = match roxmltree::Document::parse(&text) {\n\n Ok(v) => v,\n\n Err(e) => {\n\n println!(\"Error: {}.\", e);\n\n process::exit(1);\n\n }\n\n };\n\n\n\n println!(\"Elements count: {}\",\n\n doc.root().descendants().filter(|n| n.is_element()).count());\n\n\n", "file_path": "examples/stats.rs", "rank": 49, "score": 45206.31966624264 }, { "content": "fn main() {\n\n let args: Vec<_> = env::args().collect();\n\n\n\n if args.len() != 2 {\n\n println!(\"Usage:\\n\\tcargo run --example ast -- input.xml\");\n\n process::exit(1);\n\n }\n\n\n\n let text = load_file(&args[1]);\n\n match roxmltree::Document::parse(&text) {\n\n Ok(doc) => print!(\"{:?}\", doc),\n\n Err(e) => println!(\"Error: {}.\", e),\n\n }\n\n}\n\n\n", "file_path": "examples/ast.rs", "rank": 50, "score": 45206.31966624264 }, { "content": "#[test]\n\nfn lookup_prefix_01() {\n\n let data = \"<e xmlns:n1='http://www.w3.org' n1:a='b1'/>\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let node = doc.root_element();\n\n assert_eq!(node.lookup_prefix(\"http://www.w3.org\"), Some(\"n1\"));\n\n assert_eq!(node.lookup_prefix(\"http://www.w4.org\"), None);\n\n}\n\n\n", "file_path": "tests/api.rs", "rank": 51, "score": 43742.76033785923 }, { "content": "#[test]\n\nfn children() {\n\n let data = \"\\\n\n<svg>\n\n <rect/>\n\n <!-- comment -->\n\n <rect/>\n\n <!-- comment -->\n\n <rect/>\n\n</svg>\n\n\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let svg_elem = doc.root_element();\n\n\n\n let count = svg_elem.children().filter(|n| n.is_element()).count();\n\n assert_eq!(count, 3);\n\n}\n\n\n\n// ParentNode.firstElementChild\n", "file_path": "tests/dom-api.rs", "rank": 52, "score": 43742.76033785923 }, { "content": "#[test]\n\nfn root_element_01() {\n\n let data = \"\\\n\n<!-- comment -->\n\n<e/>\n\n\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let node = doc.root_element();\n\n assert_eq!(node.tag_name().name(), \"e\");\n\n}\n\n\n", "file_path": "tests/api.rs", "rank": 53, "score": 43742.76033785923 }, { "content": "fn resolve_namespaces(\n\n start_idx: usize,\n\n parent_id: NodeId,\n\n doc: &mut Document,\n\n) -> Range<usize> {\n\n let mut tmp_parent_id = parent_id.0;\n\n while tmp_parent_id != 0 {\n\n let curr_id = tmp_parent_id;\n\n tmp_parent_id = match doc.nodes[tmp_parent_id].parent {\n\n Some(id) => id.0,\n\n None => 0,\n\n };\n\n\n\n let ns_range = match doc.nodes[curr_id].kind {\n\n NodeKind::Element { ref namespaces, .. } => namespaces.clone(),\n\n _ => continue,\n\n };\n\n\n\n for i in ns_range {\n\n if !doc.namespaces.exists(start_idx, doc.namespaces[i].name) {\n", "file_path": "src/parse.rs", "rank": 54, "score": 43742.76033785923 }, { "content": "#[test]\n\nfn lookup_prefix_02() {\n\n let data = \"<e xml:space='preserve'/>\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let node = doc.root_element();\n\n assert_eq!(node.lookup_prefix(NS_XML_URI), Some(\"xml\"));\n\n}\n\n\n", "file_path": "tests/api.rs", "rank": 55, "score": 43742.76033785923 }, { "content": "#[test]\n\nfn contains() {\n\n let data = \"\\\n\n<svg>\n\n <rect/>\n\n</svg>\n\n\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let svg = doc.root_element();\n\n let rect = svg.first_child().unwrap();\n\n\n\n assert!(svg.descendants().any(|n| n == rect));\n\n}\n", "file_path": "tests/dom-api.rs", "rank": 56, "score": 43742.76033785923 }, { "content": "fn _normalize_attribute(\n\n text: StrSpan,\n\n entities: &[Entity],\n\n entity_depth: u8,\n\n buffer: &mut TextBuffer,\n\n) -> Result<(), Error> {\n\n let mut entity_depth = entity_depth;\n\n\n\n let mut s = Stream::from(text);\n\n while !s.at_end() {\n\n // Safe, because we already checked that the stream is not at the end.\n\n let c = s.curr_byte_unchecked();\n\n\n\n if c != b'&' {\n\n s.advance(1);\n\n buffer.push_from_attr(c, s.get_curr_byte());\n\n continue;\n\n }\n\n\n\n // Check for character/entity references.\n", "file_path": "src/parse.rs", "rank": 57, "score": 43742.76033785923 }, { "content": "#[test]\n\nfn get_pi() {\n\n let data = \"\\\n\n<?target value?>\n\n<root/>\n\n\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let node = doc.root().first_child().unwrap();\n\n assert_eq!(node.pi(), Some(PI { target: \"target\", value: Some(\"value\") }));\n\n}\n\n\n", "file_path": "tests/api.rs", "rank": 58, "score": 43742.76033785923 }, { "content": "fn main() {\n\n let args: Vec<_> = env::args().collect();\n\n\n\n if args.len() != 2 {\n\n println!(\"Usage:\\n\\tcargo run --example print_pos -- input.xml\");\n\n process::exit(1);\n\n }\n\n\n\n let text = load_file(&args[1]);\n\n let doc = match roxmltree::Document::parse(&text) {\n\n Ok(doc) => doc,\n\n Err(e) => {\n\n println!(\"Error: {}.\", e);\n\n return;\n\n },\n\n };\n\n\n\n // TODO: finish\n\n for node in doc.descendants() {\n\n if node.is_element() {\n\n println!(\"{:?} at {}\", node.tag_name(), node.node_pos());\n\n }\n\n }\n\n}\n\n\n", "file_path": "examples/print_pos.rs", "rank": 59, "score": 43742.76033785923 }, { "content": "#[test]\n\nfn lookup_namespace_uri() {\n\n let data = \"<e xmlns:n1='http://www.w3.org' xmlns='http://www.w4.org'/>\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let node = doc.root_element();\n\n assert_eq!(node.lookup_namespace_uri(Some(\"n1\")), Some(\"http://www.w3.org\"));\n\n assert_eq!(node.lookup_namespace_uri(None), Some(\"http://www.w4.org\"));\n\n assert_eq!(node.lookup_namespace_uri(Some(\"n2\")), None);\n\n}\n\n\n", "file_path": "tests/api.rs", "rank": 60, "score": 42430.07107032529 }, { "content": "#[test]\n\nfn parent_element() {\n\n let data = \"\\\n\n<svg>\n\n <!-- comment -->\n\n <rect/>\n\n</svg>\n\n\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let rect = doc.descendants().filter(|n| n.has_tag_name(\"rect\")).nth(0).unwrap();\n\n assert!(rect.parent_element().unwrap().has_tag_name(\"svg\"));\n\n\n\n // or\n\n\n\n assert!(rect.ancestors().filter(|n| n.is_element()).nth(0).unwrap().has_tag_name(\"svg\"));\n\n}\n\n\n\n// Node.contains\n", "file_path": "tests/dom-api.rs", "rank": 61, "score": 42430.07107032529 }, { "content": "#[test]\n\nfn owner_document() {\n\n let doc = Document::parse(\"<svg/>\").unwrap();\n\n let _elem = doc.root_element();\n\n}\n\n\n\n// Node.parentElement\n", "file_path": "tests/dom-api.rs", "rank": 62, "score": 42430.07107032529 }, { "content": "// https://www.w3.org/TR/REC-xml/#AVNormalize\n\nfn normalize_attribute<'d>(\n\n entity_depth: u8,\n\n text: StrSpan<'d>,\n\n entities: &[Entity],\n\n buffer: &mut TextBuffer,\n\n) -> Result<Cow<'d, str>, Error> {\n\n if is_normalization_required(&text) {\n\n buffer.clear();\n\n _normalize_attribute(text, entities, entity_depth, buffer)?;\n\n Ok(Cow::Owned(buffer.to_str().to_owned()))\n\n } else {\n\n Ok(Cow::Borrowed(text.to_str()))\n\n }\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 63, "score": 41936.48424772415 }, { "content": "fn process_tokens<'d>(\n\n parser: xmlparser::Tokenizer<'d>,\n\n entity_depth: u8,\n\n mut parent_id: NodeId,\n\n tag_name: &mut TagNameSpan<'d>,\n\n pd: &mut ParserData<'d>,\n\n doc: &mut Document<'d>,\n\n) -> Result<(), Error> {\n\n for token in parser {\n\n let token = token?;\n\n match token {\n\n xmlparser::Token::ProcessingInstruction(target, content) => {\n\n let orig_pos = target.start() - 2; // jump before '<?'\n\n let pi = NodeKind::PI(PI {\n\n target: target.to_str(),\n\n value: content.map(|v| v.to_str()),\n\n });\n\n doc.append(parent_id, pi, orig_pos);\n\n }\n\n xmlparser::Token::Comment(text) => {\n", "file_path": "src/parse.rs", "rank": 64, "score": 41933.50817234034 }, { "content": "fn process_attribute<'d>(\n\n entity_depth: u8,\n\n prefix: StrSpan<'d>,\n\n local: StrSpan<'d>,\n\n value: StrSpan<'d>,\n\n pd: &mut ParserData<'d>,\n\n doc: &mut Document<'d>,\n\n) -> Result<(), Error> {\n\n let prefix_str = prefix.to_str();\n\n let local_str = local.to_str();\n\n let value_pos = value.start();\n\n let value = normalize_attribute(entity_depth, value, &pd.entities, &mut pd.buffer)?;\n\n\n\n if prefix_str == \"xmlns\" {\n\n // The xmlns namespace MUST NOT be declared as the default namespace.\n\n if value == NS_XMLNS_URI {\n\n let pos = err_pos_from_qname(prefix, local);\n\n return Err(Error::UnexpectedXmlnsUri(pos));\n\n }\n\n\n", "file_path": "src/parse.rs", "rank": 65, "score": 41933.50817234034 }, { "content": "fn resolve_attributes<'d>(\n\n start_idx: usize,\n\n namespaces: Range<usize>,\n\n tmp_attrs: &mut [AttributeData<'d>],\n\n doc: &mut Document<'d>,\n\n) -> Result<Range<usize>, Error> {\n\n if tmp_attrs.is_empty() {\n\n return Ok(0..0);\n\n }\n\n\n\n for attr in tmp_attrs {\n\n let ns = if attr.prefix == \"xml\" {\n\n // The prefix 'xml' is by definition bound to the namespace name\n\n // http://www.w3.org/XML/1998/namespace.\n\n Some(doc.namespaces.xml_uri())\n\n } else if attr.prefix.is_empty() {\n\n // 'The namespace name for an unprefixed attribute name\n\n // always has no value.'\n\n None\n\n } else {\n", "file_path": "src/parse.rs", "rank": 66, "score": 41933.50817234034 }, { "content": "fn process_element<'d>(\n\n tag_name: TagNameSpan<'d>,\n\n end_token: xmlparser::ElementEnd<'d>,\n\n parent_id: &mut NodeId,\n\n pd: &mut ParserData<'d>,\n\n doc: &mut Document<'d>,\n\n) -> Result<(), Error> {\n\n if tag_name.name.is_empty() {\n\n // May occur in XML like this:\n\n // <!DOCTYPE test [ <!ENTITY p '</p>'> ]>\n\n // <root>&p;</root>\n\n\n\n if let xmlparser::ElementEnd::Close(prefix, local) = end_token {\n\n return Err(Error::UnexpectedEntityCloseTag(err_pos_for_close_tag(prefix, local)));\n\n } else {\n\n unreachable!(\"should be already checked by the xmlparser\");\n\n }\n\n }\n\n\n\n let namespaces = resolve_namespaces(pd.ns_start_idx, *parent_id, doc);\n", "file_path": "src/parse.rs", "rank": 67, "score": 41933.50817234034 }, { "content": "#[test]\n\nfn get_element_by_id() {\n\n let data = \"\\\n\n<svg id='svg1'>\n\n <circle id='circle1'/>\n\n <g>\n\n <rect id='rect1'/>\n\n </g>\n\n</svg>\n\n\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let elem = doc.descendants().filter(|n| n.attribute(\"id\") == Some(\"rect1\")).nth(0).unwrap();\n\n assert!(elem.has_tag_name(\"rect\"));\n\n}\n\n\n\n// Node.ownerDocument\n", "file_path": "tests/dom-api.rs", "rank": 68, "score": 41246.06681618066 }, { "content": "#[test]\n\nfn last_element_child() {\n\n let data = \"\\\n\n<svg>\n\n <!-- comment -->\n\n <rect/>\n\n <!-- comment -->\n\n</svg>\n\n\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let svg_elem = doc.root_element();\n\n\n\n let elem = svg_elem.last_element_child().unwrap();\n\n assert!(elem.has_tag_name(\"rect\"));\n\n\n\n // or\n\n\n\n let elem = svg_elem.children().filter(|n| n.is_element()).last().unwrap();\n\n assert!(elem.has_tag_name(\"rect\"));\n\n}\n\n\n\n// Document.getElementById\n", "file_path": "tests/dom-api.rs", "rank": 69, "score": 41246.06681618066 }, { "content": "#[test]\n\nfn child_element_count() {\n\n let data = \"\\\n\n<svg>\n\n <rect/>\n\n <!-- comment -->\n\n <rect/>\n\n <!-- comment -->\n\n <rect/>\n\n</svg>\n\n\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let svg_elem = doc.root_element();\n\n\n\n let count = svg_elem.children().filter(|n| n.is_element()).count();\n\n assert_eq!(count, 3);\n\n}\n\n\n\n// ParentNode.children\n", "file_path": "tests/dom-api.rs", "rank": 70, "score": 41246.06681618066 }, { "content": "#[test]\n\nfn first_element_child() {\n\n let data = \"\\\n\n<svg>\n\n <!-- comment -->\n\n <rect/>\n\n</svg>\n\n\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n let svg_elem = doc.root_element();\n\n\n\n let elem = svg_elem.first_element_child().unwrap();\n\n assert!(elem.has_tag_name(\"rect\"));\n\n\n\n // or\n\n\n\n let elem = svg_elem.children().filter(|n| n.is_element()).nth(0).unwrap();\n\n assert!(elem.has_tag_name(\"rect\"));\n\n}\n\n\n\n// ParentNode.lastElementChild\n", "file_path": "tests/dom-api.rs", "rank": 71, "score": 41246.06681618066 }, { "content": "fn parse_next_chunk<'a>(\n\n s: &mut Stream<'a>,\n\n entities: &[Entity<'a>],\n\n) -> Result<NextChunk<'a>, Error> {\n\n debug_assert!(!s.at_end());\n\n\n\n // Safe, because we already checked that stream is not at the end.\n\n // But we have an additional `debug_assert` above just in case.\n\n let c = s.curr_byte_unchecked();\n\n\n\n // Check for character/entity references.\n\n if c == b'&' {\n\n match s.try_consume_reference() {\n\n Some(Reference::CharRef(ch)) => {\n\n Ok(NextChunk::Char(ch))\n\n }\n\n Some(Reference::EntityRef(name)) => {\n\n match entities.iter().find(|e| e.name == name) {\n\n Some(entity) => {\n\n Ok(NextChunk::Text(entity.value))\n", "file_path": "src/parse.rs", "rank": 72, "score": 40620.81890480641 }, { "content": "fn main() {\n\n fuzz(|data| {\n\n if let Ok(text) = str::from_utf8(data) {\n\n let _ = roxmltree::Document::parse(&text);\n\n }\n\n });\n\n}\n", "file_path": "testing-tools/afl-fuzz/src/main.rs", "rank": 73, "score": 40172.70895825514 }, { "content": "#[test]\n\nfn get_elements_by_tag_name() {\n\n let data = \"\\\n\n<!-- comment -->\n\n<svg>\n\n <rect/>\n\n <text>Text</text>\n\n <g>\n\n <!-- comment -->\n\n <rect/>\n\n </g>\n\n</svg>\n\n\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n\n\n let nodes: Vec<Node> = doc.descendants().filter(|n| n.has_tag_name(\"rect\")).collect();\n\n assert_eq!(nodes.len(), 2);\n\n}\n\n\n\n// Document.getElementsByTagNameNS()\n", "file_path": "tests/dom-api.rs", "rank": 74, "score": 40172.70895825514 }, { "content": "#[test]\n\nfn get_elements_by_tag_name_ns() {\n\n let data = \"\\\n\n<!-- comment -->\n\n<svg xmlns:q='http://www.w3.org/'>\n\n <rect/>\n\n <text>Text</text>\n\n <g>\n\n <!-- comment -->\n\n <q:rect/>\n\n </g>\n\n</svg>\n\n\";\n\n\n\n let doc = Document::parse(data).unwrap();\n\n\n\n let nodes: Vec<Node> = doc.descendants()\n\n .filter(|n| n.has_tag_name((\"http://www.w3.org/\", \"rect\"))).collect();\n\n assert_eq!(nodes.len(), 1);\n\n}\n\n\n\n// ParentNode.childElementCount\n", "file_path": "tests/dom-api.rs", "rank": 75, "score": 39195.1798327739 }, { "content": "fn orig_pos_from_tag_name(tag_name: &TagNameSpan) -> usize {\n\n let span = if tag_name.prefix.is_empty() { tag_name.name } else { tag_name.prefix };\n\n span.start() - 1 // jump before '<'\n\n}\n\n\n\n\n\nmod internals {\n\n /// Iterate over `char` by `u8`.\n\n pub struct CharToBytes {\n\n buf: [u8; 4],\n\n idx: u8,\n\n }\n\n\n\n impl CharToBytes {\n\n pub fn new(c: char) -> Self {\n\n let mut buf = [0xFF; 4];\n\n c.encode_utf8(&mut buf);\n\n\n\n CharToBytes {\n\n buf,\n", "file_path": "src/parse.rs", "rank": 76, "score": 31494.921155815846 }, { "content": "def escape_text(text):\n", "file_path": "testing-tools/lxml-ast.py", "rank": 78, "score": 21558.440584925636 }, { "content": "### Tests\n\n\n\n- attrs_001 - simple attribute\n\n- attrs_002 - attribute value with new lines\n\n- attrs_003 - attribute value with escaped text\n\n- attrs_004 - attribute value with escaped text\n\n- attrs_005 - attribute value with \\r\\n\n\n- attrs_err_001 - duplicated attributes\n\n- attrs_err_002 - duplicated attributes via namespaces\n\n- cdata_001 - simple case\n\n- cdata_002 - simple case\n\n- cdata_003 - empty\n\n- cdata_004 - simple case\n\n- cdata_005 - mixed text and cdata\n\n- cdata_006 - simple case\n\n- comments_001 - comment before and after the root element\n\n- elems_err_001 - invalid tree structure\n\n- elems_err_002 - invalid tree structure with namespace\n\n- entity_001 - entity reference to an element\n\n- entity_002 - entity reference to an attribute value\n\n- entity_003 - many entity references to an attribute value\n\n- entity_004 - entity reference to a text\n\n- entity_005 - unused entity reference\n\n- entity_006 - entity reference to an escaped text\n\n- entity_007 - indirect entity reference to an attribute value\n\n- entity_008 - entity reference to an element\n\n- entity_009 - entity reference to a mixed content\n\n- entity_010 - entity reference to an element with an entity reference\n\n- entity_011 - character and entity references in attributes\n\n- entity_012 - mixed entity references in text\n\n- entity_err_001 - unknown entity reference\n\n- entity_err_002 - recursive entity references\n\n- entity_err_003 - reference to a close tag\n\n- entity_err_004 - reference to a close tag\n\n- entity_err_005 - billion laughs\n\n- entity_err_006 - billion laughs\n\n- ns_001 - attributes with different namespaces\n\n- ns_002 - attribute is not affected by the default namespace\n\n- ns_003 - attributes with different namespaces\n\n- ns_004 - `href` with a custom prefix\n\n- ns_005 - `xml` namespace resolving\n\n- ns_006 - `xml` namespace overriding\n\n- ns_007 - many namespaces\n\n- ns_008 - namespace propagation\n\n- ns_009 - namespace overwriting\n\n- ns_010 - indirect namespace propagation\n\n- ns_011 - empty URI\n\n- ns_012 - namespace propagation\n\n- ns_013 - namespace from entity\n\n- ns_014 - no namespaces\n\n- ns_014 - duplicated namespaces with different prefixes\n\n- ns_err_001 - invalid `xml` URI\n\n- ns_err_002 - reserved URI\n\n- ns_err_003 - reserved URI\n\n- ns_err_004 - duplicated namespaces\n\n- ns_err_005 - escaped namespace\n\n- ns_err_006 - escaped namespace\n\n- ns_err_007 - reserved URI\n\n- ns_err_008 - reserved URI\n\n- ns_err_009 - unknown namespace\n\n- text_001 - single space text\n\n- text_002 - single escaped space text\n\n- text_003 - escaped text\n\n- text_004 - '>' text\n\n- text_005 - '\\n\\r\\r\\n' text\n\n- text_006 - '\\r\\r\\r' text\n\n- text_007 - '\\r\\n\\r\\n' text\n\n- text_008 - only whitespaces\n\n- text_009 - escaped text\n\n- text_010 - text around elements\n\n- text_011 - mixed character references in text\n\n- tree_001 - all node types\n\n- tree_002 - BOM\n\n- tree_003 - Windows-1251 encoding\n\n- tree_err_001 - no elements\n", "file_path": "tests/files/README.md", "rank": 79, "score": 17901.502926722424 }, { "content": "#![warn(missing_docs)]\n\n\n\nextern crate xmlparser;\n\n\n\nuse std::borrow::Cow;\n\nuse std::fmt;\n\nuse std::ops::{Deref, Range};\n\nuse std::rc::Rc;\n\n\n\npub use xmlparser::TextPos;\n\n\n\nmod parse;\n\npub use parse::*;\n\n\n\n\n\n/// The <http://www.w3.org/XML/1998/namespace> URI.\n\npub const NS_XML_URI: &str = \"http://www.w3.org/XML/1998/namespace\";\n\n\n\n/// The <http://www.w3.org/2000/xmlns/> URI.\n\npub const NS_XMLNS_URI: &str = \"http://www.w3.org/2000/xmlns/\";\n", "file_path": "src/lib.rs", "rank": 80, "score": 14.261971681947907 }, { "content": "## Performance\n\n\n\n```text\n\ntest large_roxmltree ... bench: 5,609,303 ns/iter (+/- 105,511)\n\ntest large_sdx_document ... bench: 10,299,996 ns/iter (+/- 315,027)\n\ntest large_xmltree ... bench: 32,797,800 ns/iter (+/- 134,016)\n\ntest large_treexml ... bench: 31,380,063 ns/iter (+/- 71,732)\n\ntest large_elementtree ... bench: 32,121,979 ns/iter (+/- 264,842)\n\n\n\ntest medium_roxmltree ... bench: 1,208,790 ns/iter (+/- 4,041)\n\ntest medium_sdx_document ... bench: 3,601,921 ns/iter (+/- 14,758)\n\ntest medium_treexml ... bench: 10,975,247 ns/iter (+/- 22,692)\n\ntest medium_xmltree ... bench: 11,601,320 ns/iter (+/- 46,216)\n\ntest medium_elementtree ... bench: 11,550,227 ns/iter (+/- 17,991)\n\n\n\ntest tiny_roxmltree ... bench: 8,002 ns/iter (+/- 73)\n\ntest tiny_sdx_document ... bench: 26,835 ns/iter (+/- 47)\n\ntest tiny_xmltree ... bench: 47,199 ns/iter (+/- 110)\n\ntest tiny_treexml ... bench: 50,399 ns/iter (+/- 55)\n\ntest tiny_elementtree ... bench: 51,569 ns/iter (+/- 165)\n\n```\n\n\n\n*roxmltree* uses [xmlparser] internally,\n\nwhile *sdx-document* uses its own implementation and *xmltree*, *elementtree*\n\nand *treexml* use the [xml-rs] crate.\n\nHere is a comparison between *xmlparser* and *xml-rs*:\n\n\n\n```text\n\ntest large_xmlparser ... bench: 2,149,545 ns/iter (+/- 2,689)\n\ntest large_xmlrs ... bench: 28,252,304 ns/iter (+/- 27,852)\n\n\n\ntest medium_xmlparser ... bench: 517,778 ns/iter (+/- 1,842)\n\ntest medium_xmlrs ... bench: 10,237,568 ns/iter (+/- 13,497)\n\n\n\ntest tiny_xmlparser ... bench: 4,283 ns/iter (+/- 29)\n\ntest tiny_xmlrs ... bench: 45,832 ns/iter (+/- 50)\n\n```\n\n\n\n*Note:* tree crates may use different *xml-rs* crate versions.\n\n\n\nYou can try it yourself by running `cargo bench` in the `benches` dir.\n\n\n\n[xml-rs]: https://crates.io/crates/xml-rs\n\n[xmlparser]: https://crates.io/crates/xmlparser\n\n\n", "file_path": "README.md", "rank": 81, "score": 13.849580550044008 }, { "content": "extern crate roxmltree;\n\nextern crate rustc_test;\n\n#[macro_use] extern crate pretty_assertions;\n\n\n\nuse roxmltree::*;\n\n\n\nuse rustc_test::{TestDesc, TestDescAndFn, DynTestName, DynTestFn};\n\n\n\nuse std::env;\n\nuse std::path;\n\nuse std::fs;\n\nuse std::io::Read;\n\nuse std::fmt::Write;\n\nuse std::fmt;\n\n\n\n#[derive(Clone, Copy, PartialEq)]\n", "file_path": "tests/ast.rs", "rank": 82, "score": 13.619232656055049 }, { "content": "extern crate afl;\n\nextern crate roxmltree;\n\n\n\nuse std::str;\n\n\n\nuse afl::fuzz;\n\n\n", "file_path": "testing-tools/afl-fuzz/src/main.rs", "rank": 83, "score": 13.554670071092334 }, { "content": " self.buf.is_empty()\n\n }\n\n\n\n pub fn to_str(&self) -> &str {\n\n use std::str;\n\n\n\n // `unwrap` is safe, because buffer must contain a valid UTF-8 string.\n\n str::from_utf8(&self.buf).unwrap()\n\n }\n\n }\n\n}\n\n\n\nuse self::internals::*;\n", "file_path": "src/parse.rs", "rank": 84, "score": 12.531858301589558 }, { "content": "use std::borrow::{Cow, Borrow};\n\nuse std::error;\n\nuse std::fmt;\n\nuse std::mem;\n\nuse std::ops::Range;\n\nuse std::str;\n\n\n\nuse xmlparser::{\n\n self,\n\n Reference,\n\n Stream,\n\n StrSpan,\n\n TextPos,\n\n};\n\n\n\nuse {\n\n NS_XML_URI,\n\n NS_XMLNS_URI,\n\n Attribute,\n\n Document,\n", "file_path": "src/parse.rs", "rank": 85, "score": 12.156344498775248 }, { "content": "extern crate roxmltree;\n\n#[macro_use] extern crate pretty_assertions;\n\n\n\nuse roxmltree::*;\n\n\n\n#[test]\n", "file_path": "tests/api.rs", "rank": 86, "score": 10.807693113500445 }, { "content": " _ => TextPos::new(1, 1)\n\n }\n\n }\n\n}\n\n\n\nimpl From<xmlparser::Error> for Error {\n\n fn from(e: xmlparser::Error) -> Self {\n\n Error::ParserError(e)\n\n }\n\n}\n\n\n\nimpl fmt::Display for Error {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match *self {\n\n Error::InvalidXmlPrefixUri(pos) => {\n\n write!(f, \"'xml' namespace prefix mapped to wrong URI at {}\", pos)\n\n }\n\n Error::UnexpectedXmlUri(pos) => {\n\n write!(f, \"the 'xml' namespace URI is used for not 'xml' prefix at {}\", pos)\n\n }\n", "file_path": "src/parse.rs", "rank": 87, "score": 10.505241911214473 }, { "content": "| License | MIT / Apache-2.0 | MIT | BSD-3-Clause | MIT | MIT |\n\n\n\nLegend:\n\n\n\n- ✔ - supported\n\n- ⚠ - parsing error\n\n- ~ - partial\n\n- *nothing* - not supported\n\n\n\nNotes:\n\n\n\n1. No default namespace propagation.\n\n2. *roxmltree* keeps all node and attribute positions in the original document,\n\n so you can easily retrieve it if you need it.\n\n See [examples/print_pos.rs](examples/print_pos.rs) for details.\n\n3. In the `string_cache` crate.\n\n4. Binary size overhead according to [cargo-bloat](https://github.com/RazrFalcon/cargo-bloat).\n\n\n\n[Entity references]: https://www.w3.org/TR/REC-xml/#dt-entref\n\n[Character references]: https://www.w3.org/TR/REC-xml/#NT-CharRef\n\n[Attribute-Value Normalization]: https://www.w3.org/TR/REC-xml/#AVNormalize\n\n\n\n[xmltree]: https://crates.io/crates/xmltree\n\n[elementtree]: https://crates.io/crates/elementtree\n\n[treexml]: https://crates.io/crates/treexml\n\n[sxd-document]: https://crates.io/crates/sxd-document\n\n\n", "file_path": "README.md", "rank": 88, "score": 9.696688040381835 }, { "content": " pub fn push_from_attr(&mut self, mut c: u8, c2: Option<u8>) {\n\n // \\r in \\r\\n should be ignored.\n\n if c == b'\\r' && c2 == Some(b'\\n') {\n\n return;\n\n }\n\n\n\n // \\n, \\r and \\t should be converted into spaces.\n\n c = match c {\n\n b'\\n' | b'\\r' | b'\\t' => b' ',\n\n _ => c,\n\n };\n\n\n\n self.buf.push(c);\n\n }\n\n\n\n // Translate \\r\\n and any \\r that is not followed by \\n into a single \\n character.\n\n //\n\n // https://www.w3.org/TR/xml/#sec-line-ends\n\n pub fn push_from_text(&mut self, c: u8, at_end: bool) {\n\n if self.buf.last() == Some(&b'\\r') {\n", "file_path": "src/parse.rs", "rank": 89, "score": 9.597559156352759 }, { "content": " };\n\n\n\n // Add a root node.\n\n doc.nodes.push(NodeData {\n\n parent: None,\n\n prev_sibling: None,\n\n next_sibling: None,\n\n children: None,\n\n kind: NodeKind::Root,\n\n orig_pos: 0,\n\n });\n\n\n\n doc.namespaces.push_ns(Some(\"xml\"), NS_XML_URI.to_string());\n\n\n\n let parser = xmlparser::Tokenizer::from(text);\n\n let parent_id = doc.root().id;\n\n let mut tag_name = TagNameSpan::new_null();\n\n process_tokens(parser, 0, parent_id, &mut tag_name, &mut pd, &mut doc)?;\n\n\n\n if !doc.root().children().any(|n| n.is_element()) {\n", "file_path": "src/parse.rs", "rank": 90, "score": 9.448403600726886 }, { "content": " let orig_pos = text.start() - 4; // jump before '<!--'\n\n doc.append(parent_id, NodeKind::Comment(text.to_str()), orig_pos);\n\n }\n\n xmlparser::Token::Text(text) |\n\n xmlparser::Token::Whitespaces(text) => {\n\n process_text(text, parent_id, entity_depth, pd, doc)?;\n\n }\n\n xmlparser::Token::Cdata(text) => {\n\n let cow_str = Cow::Borrowed(text.to_str());\n\n append_text(cow_str, parent_id, text.start(), pd.after_text, doc);\n\n pd.after_text = true;\n\n }\n\n xmlparser::Token::ElementStart(prefix, local) => {\n\n if prefix.to_str() == \"xmlns\" {\n\n let pos = err_pos_from_span(prefix);\n\n return Err(Error::InvalidElementNamePrefix(pos));\n\n }\n\n\n\n *tag_name = TagNameSpan::new(prefix, local);\n\n }\n", "file_path": "src/parse.rs", "rank": 91, "score": 9.34445492429579 }, { "content": "extern crate roxmltree;\n\n\n\nuse std::fs;\n\nuse std::env;\n\nuse std::io::Read;\n\nuse std::process;\n\n\n", "file_path": "examples/print_pos.rs", "rank": 92, "score": 9.309281577583471 }, { "content": "extern crate roxmltree;\n\n\n\nuse std::fs;\n\nuse std::env;\n\nuse std::io::Read;\n\nuse std::process;\n\n\n", "file_path": "examples/ast.rs", "rank": 93, "score": 9.309281577583471 }, { "content": " None\n\n }\n\n }\n\n\n\n\n\n pub struct TextBuffer {\n\n buf: Vec<u8>,\n\n }\n\n\n\n impl TextBuffer {\n\n pub fn new() -> Self {\n\n TextBuffer {\n\n buf: Vec::with_capacity(32),\n\n }\n\n }\n\n\n\n pub fn push_raw(&mut self, c: u8) {\n\n self.buf.push(c);\n\n }\n\n\n", "file_path": "src/parse.rs", "rank": 94, "score": 9.132718110624467 }, { "content": "extern crate roxmltree;\n\n\n\nuse std::collections::HashSet;\n\nuse std::fs;\n\nuse std::env;\n\nuse std::io::Read;\n\nuse std::process;\n\n\n", "file_path": "examples/stats.rs", "rank": 95, "score": 8.888544906313534 }, { "content": "extern crate roxmltree;\n\n\n\nuse roxmltree::*;\n\n\n\n// Document.getElementsByTagName()\n\n#[test]\n", "file_path": "tests/dom-api.rs", "rank": 96, "score": 8.741912429784836 }, { "content": "\n\n /// The <http://www.w3.org/2000/xmlns/> URI must not be declared.\n\n UnexpectedXmlnsUri(TextPos),\n\n\n\n /// `xmlns` can't be used as an element prefix.\n\n InvalidElementNamePrefix(TextPos),\n\n\n\n /// A namespace was already defined on this element.\n\n DuplicatedNamespace(String, TextPos),\n\n\n\n /// Incorrect tree structure.\n\n #[allow(missing_docs)]\n\n UnexpectedCloseTag { expected: String, actual: String, pos: TextPos },\n\n\n\n /// Entity value starts with a close tag.\n\n ///\n\n /// Example:\n\n /// ```xml\n\n /// <!DOCTYPE test [ <!ENTITY p '</p>'> ]>\n\n /// <root>&p;</root>\n", "file_path": "src/parse.rs", "rank": 97, "score": 8.48417565614852 }, { "content": " xmlparser::Token::Attribute((prefix, local), value) => {\n\n process_attribute(entity_depth, prefix, local, value, pd, doc)?;\n\n }\n\n xmlparser::Token::ElementEnd(end) => {\n\n process_element(*tag_name, end, &mut parent_id, pd, doc)?;\n\n }\n\n xmlparser::Token::EntityDeclaration(name, value) => {\n\n if let xmlparser::EntityDefinition::EntityValue(value) = value {\n\n pd.entities.push(Entity { name: name.to_str(), value });\n\n }\n\n }\n\n _ => {}\n\n }\n\n\n\n match token {\n\n xmlparser::Token::ProcessingInstruction(..) |\n\n xmlparser::Token::Comment(..) |\n\n xmlparser::Token::ElementStart(..) |\n\n xmlparser::Token::ElementEnd(..) => {\n\n pd.after_text = false;\n\n }\n\n _ => {}\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 98, "score": 7.5704867443776775 }, { "content": " let mut parser = xmlparser::Tokenizer::from(fragment);\n\n parser.enable_fragment_mode();\n\n\n\n let mut tag_name = TagNameSpan::new_null();\n\n entity_depth += 1; // TODO: explain\n\n process_tokens(parser, entity_depth, parent_id, &mut tag_name, pd, doc)?;\n\n pd.buffer.clear();\n\n }\n\n }\n\n }\n\n\n\n if !pd.buffer.is_empty() {\n\n _append_text(parent_id, text.start(), pd, doc);\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 99, "score": 7.037150166513375 } ]
Rust
amethyst_core/src/hide_system.rs
csh/amethyst
68aa4eaadd56c40de6f91d1148affbe3c2381128
use crate::{ ecs::prelude::{ BitSet, ComponentEvent, ReadExpect, ReadStorage, ReaderId, System, SystemData, World, WriteStorage, }, transform::components::{HierarchyEvent, Parent, ParentHierarchy}, SystemDesc, }; #[cfg(feature = "profiler")] use thread_profiler::profile_scope; use log::error; use crate::HiddenPropagate; #[derive(Default, Debug)] pub struct HideHierarchySystemDesc; impl<'a, 'b> SystemDesc<'a, 'b, HideHierarchySystem> for HideHierarchySystemDesc { fn build(self, world: &mut World) -> HideHierarchySystem { <HideHierarchySystem as System<'_>>::SystemData::setup(world); let parent_events_id = world.fetch_mut::<ParentHierarchy>().track(); let mut hidden = WriteStorage::<HiddenPropagate>::fetch(&world); let hidden_events_id = hidden.register_reader(); HideHierarchySystem::new(hidden_events_id, parent_events_id) } } #[derive(Debug)] pub struct HideHierarchySystem { marked_as_modified: BitSet, manually_hidden: BitSet, hidden_events_id: ReaderId<ComponentEvent>, parent_events_id: ReaderId<HierarchyEvent>, } impl HideHierarchySystem { pub fn new( hidden_events_id: ReaderId<ComponentEvent>, parent_events_id: ReaderId<HierarchyEvent>, ) -> Self { Self { marked_as_modified: BitSet::default(), manually_hidden: BitSet::default(), hidden_events_id, parent_events_id, } } } impl<'a> System<'a> for HideHierarchySystem { type SystemData = ( WriteStorage<'a, HiddenPropagate>, ReadStorage<'a, Parent>, ReadExpect<'a, ParentHierarchy>, ); fn run(&mut self, (mut hidden, parents, hierarchy): Self::SystemData) { #[cfg(feature = "profiler")] profile_scope!("hide_hierarchy_system"); self.marked_as_modified.clear(); self.manually_hidden.clear(); let self_hidden_events_id = &mut self.hidden_events_id; let self_marked_as_modified = &mut self.marked_as_modified; let self_manually_hidden = &mut self.manually_hidden; hidden .channel() .read(self_hidden_events_id) .for_each(|event| match event { ComponentEvent::Inserted(id) | ComponentEvent::Removed(id) => { self_marked_as_modified.add(*id); } ComponentEvent::Modified(_id) => {} }); for event in hierarchy.changed().read(&mut self.parent_events_id) { match *event { HierarchyEvent::Removed(entity) => { self_marked_as_modified.add(entity.id()); } HierarchyEvent::Modified(entity) => { self_marked_as_modified.add(entity.id()); } } } for entity in hierarchy.all() { { let self_hidden = hidden.get(*entity); let self_is_manually_hidden = self_hidden.as_ref().map_or(false, |p| !p.is_propagated); if self_is_manually_hidden { self_manually_hidden.add(entity.id()); } let parent_entity = parents .get(*entity) .expect( "Unreachable: All entities in `ParentHierarchy` should also be in \ `Parents`", ) .entity; let parent_dirty = self_marked_as_modified.contains(parent_entity.id()); let parent_hidden = hidden.get(parent_entity); let parent_is_manually_hidden = parent_hidden.as_ref().map_or(false, |p| !p.is_propagated); if parent_is_manually_hidden { self_manually_hidden.add(parent_entity.id()); self_manually_hidden.add(entity.id()); } if parent_dirty && !self_is_manually_hidden { if parent_hidden.is_some() { if let Err(e) = hidden.insert(*entity, HiddenPropagate::new_propagated()) { error!("Failed to automatically add `HiddenPropagate`: {:?}", e); } } else { hidden.remove(*entity); } } } hidden .channel() .read(self_hidden_events_id) .for_each(|event| match event { ComponentEvent::Inserted(id) | ComponentEvent::Removed(id) => { self_marked_as_modified.add(*id); } ComponentEvent::Modified(_id) => {} }); } } }
use crate::{ ecs::prelude::{ BitSet, ComponentEvent, ReadExpect, ReadStorage, ReaderId, System, SystemData, World, WriteStorage, }, transform::components::{HierarchyEvent, Parent, ParentHierarchy}, SystemDesc, }; #[cfg(feature = "profiler")] use thread_profiler::profile_scope; use log::error; use crate::HiddenPropagate; #[derive(Default, Debug)] pub struct HideHierarchySystemDesc; impl<'a, 'b> SystemDesc<'a, 'b, HideHierarchySystem> for HideHierarchySystemDesc { fn build(self, world: &mut World) -> HideHierarchySystem { <HideHierarchySystem as System<'_>>::SystemData::setup(world); let parent_events_id = world.fetch_mut::<ParentHierarchy>().track(); let mut hidden = WriteStorage::<HiddenPropagate>::fetch(&world); let hidden_events_id = hidden.register_reader(); HideHierarchySystem::new(hidden_events_id, parent_events_id) } } #[derive(Debug)] pub struct HideHierarchySystem { marked_as_modified: BitSet, manually_hidden: BitSet, hidden_events_id: ReaderId<ComponentEvent>, parent_events_id: ReaderId<HierarchyEvent>, } impl HideHierarchySystem { pub fn new( hidden_events_id: ReaderId<ComponentEvent>, parent_events_id: ReaderId<HierarchyEvent>, ) -> Self { Self { marked_as_modified: BitSet::default(), manually_hidden: BitSet::default(), hidden_events_id, parent_events_id, } } } impl<'a> System<'a> for HideHierarchySystem { type SystemData = ( WriteStorage<'a, HiddenPropagate>, ReadStorage<'a, Parent>, ReadExpect<'a, ParentHierarchy>, );
}
fn run(&mut self, (mut hidden, parents, hierarchy): Self::SystemData) { #[cfg(feature = "profiler")] profile_scope!("hide_hierarchy_system"); self.marked_as_modified.clear(); self.manually_hidden.clear(); let self_hidden_events_id = &mut self.hidden_events_id; let self_marked_as_modified = &mut self.marked_as_modified; let self_manually_hidden = &mut self.manually_hidden; hidden .channel() .read(self_hidden_events_id) .for_each(|event| match event { ComponentEvent::Inserted(id) | ComponentEvent::Removed(id) => { self_marked_as_modified.add(*id); } ComponentEvent::Modified(_id) => {} }); for event in hierarchy.changed().read(&mut self.parent_events_id) { match *event { HierarchyEvent::Removed(entity) => { self_marked_as_modified.add(entity.id()); } HierarchyEvent::Modified(entity) => { self_marked_as_modified.add(entity.id()); } } } for entity in hierarchy.all() { { let self_hidden = hidden.get(*entity); let self_is_manually_hidden = self_hidden.as_ref().map_or(false, |p| !p.is_propagated); if self_is_manually_hidden { self_manually_hidden.add(entity.id()); } let parent_entity = parents .get(*entity) .expect( "Unreachable: All entities in `ParentHierarchy` should also be in \ `Parents`", ) .entity; let parent_dirty = self_marked_as_modified.contains(parent_entity.id()); let parent_hidden = hidden.get(parent_entity); let parent_is_manually_hidden = parent_hidden.as_ref().map_or(false, |p| !p.is_propagated); if parent_is_manually_hidden { self_manually_hidden.add(parent_entity.id()); self_manually_hidden.add(entity.id()); } if parent_dirty && !self_is_manually_hidden { if parent_hidden.is_some() { if let Err(e) = hidden.insert(*entity, HiddenPropagate::new_propagated()) { error!("Failed to automatically add `HiddenPropagate`: {:?}", e); } } else { hidden.remove(*entity); } } } hidden .channel() .read(self_hidden_events_id) .for_each(|event| match event { ComponentEvent::Inserted(id) | ComponentEvent::Removed(id) => { self_marked_as_modified.add(*id); } ComponentEvent::Modified(_id) => {} }); } }
function_block-full_function
[ { "content": "fn create_default_mat<B: Backend>(world: &mut World) -> Material {\n\n use crate::mtl::TextureOffset;\n\n\n\n use amethyst_assets::Loader;\n\n\n\n let loader = world.fetch::<Loader>();\n\n\n\n let albedo = load_from_srgba(Srgba::new(0.5, 0.5, 0.5, 1.0));\n\n let emission = load_from_srgba(Srgba::new(0.0, 0.0, 0.0, 0.0));\n\n let normal = load_from_linear_rgba(LinSrgba::new(0.5, 0.5, 1.0, 1.0));\n\n let metallic_roughness = load_from_linear_rgba(LinSrgba::new(0.0, 0.5, 0.0, 0.0));\n\n let ambient_occlusion = load_from_linear_rgba(LinSrgba::new(1.0, 1.0, 1.0, 1.0));\n\n let cavity = load_from_linear_rgba(LinSrgba::new(1.0, 1.0, 1.0, 1.0));\n\n\n\n let tex_storage = world.fetch();\n\n\n\n let albedo = loader.load_from_data(albedo.into(), (), &tex_storage);\n\n let emission = loader.load_from_data(emission.into(), (), &tex_storage);\n\n let normal = loader.load_from_data(normal.into(), (), &tex_storage);\n\n let metallic_roughness = loader.load_from_data(metallic_roughness.into(), (), &tex_storage);\n", "file_path": "amethyst_rendy/src/system.rs", "rank": 0, "score": 364113.066909502 }, { "content": "/// Initialise audio in the world. This includes the background track and the\n\n/// sound effects.\n\npub fn initialise_audio(world: &mut World) {\n\n use crate::{AUDIO_BOUNCE, AUDIO_MUSIC, AUDIO_SCORE};\n\n\n\n let (sound_effects, music) = {\n\n let loader = world.read_resource::<Loader>();\n\n\n\n let mut sink = world.write_resource::<AudioSink>();\n\n sink.set_volume(0.25); // Music is a bit loud, reduce the volume.\n\n\n\n let music = AUDIO_MUSIC\n\n .iter()\n\n .map(|file| load_audio_track(&loader, &world, file))\n\n .collect::<Vec<_>>()\n\n .into_iter()\n\n .cycle();\n\n let music = Music { music };\n\n\n\n let sound = Sounds {\n\n bounce_sfx: load_audio_track(&loader, &world, AUDIO_BOUNCE),\n\n score_sfx: load_audio_track(&loader, &world, AUDIO_SCORE),\n", "file_path": "examples/pong_tutorial_06/audio.rs", "rank": 1, "score": 338619.7063876637 }, { "content": "/// Initialize default output\n\npub fn init_output(world: &mut World) {\n\n if let Some(o) = default_output() {\n\n world\n\n .entry::<AudioSink>()\n\n .or_insert_with(|| AudioSink::new(&o));\n\n world.entry::<Output>().or_insert_with(|| o);\n\n } else {\n\n error!(\"Failed finding a default audio output to hook AudioSink to, audio will not work!\")\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n #[cfg(target_os = \"linux\")]\n\n use {\n\n crate::{output::Output, source::Source, DecoderError},\n\n amethyst_utils::app_root_dir::application_root_dir,\n\n std::{fs::File, io::Read, vec::Vec},\n\n };\n\n\n", "file_path": "amethyst_audio/src/output.rs", "rank": 2, "score": 338613.98525919346 }, { "content": "fn initialise_camera(world: &mut World, parent: Entity) -> Entity {\n\n let (width, height) = {\n\n let dim = world.read_resource::<ScreenDimensions>();\n\n (dim.width(), dim.height())\n\n };\n\n\n\n let mut camera_transform = Transform::default();\n\n camera_transform.set_translation_z(5.0);\n\n\n\n world\n\n .create_entity()\n\n .with(camera_transform)\n\n .with(Parent { entity: parent })\n\n .with(Camera::standard_2d(width, height))\n\n .named(\"camera\")\n\n .build()\n\n}\n\n\n", "file_path": "examples/sprite_camera_follow/main.rs", "rank": 3, "score": 318444.5724521827 }, { "content": "fn create_tinted_crates(world: &mut World) {\n\n let crate_spritesheet = load_crate_spritesheet(world);\n\n\n\n let crate_sprite_render = SpriteRender {\n\n sprite_sheet: crate_spritesheet.clone(),\n\n sprite_number: 0,\n\n };\n\n\n\n let crate_scale = Vector3::new(0.01, 0.01, 1.0);\n\n\n\n let mut red_crate_transform = Transform::default();\n\n red_crate_transform.set_translation_xyz(4.44, 0.32, 0.5);\n\n red_crate_transform.set_scale(crate_scale);\n\n\n\n let mut green_crate_transform = Transform::default();\n\n green_crate_transform.set_translation_xyz(4.44, 0.0, 0.5);\n\n green_crate_transform.set_scale(crate_scale);\n\n\n\n let mut blue_crate_transform = Transform::default();\n\n blue_crate_transform.set_translation_xyz(4.44, -0.32, 0.5);\n", "file_path": "examples/rendy/main.rs", "rank": 4, "score": 317105.6614827623 }, { "content": "fn load_crate_spritesheet(world: &mut World) -> Handle<SpriteSheet> {\n\n let crate_texture_handle = {\n\n let loader = world.read_resource::<Loader>();\n\n let texture_storage = world.read_resource::<AssetStorage<Texture>>();\n\n loader.load(\n\n Path::new(\"texture\").join(\"crate.png\").to_string_lossy(),\n\n ImageFormat::default(),\n\n (),\n\n &texture_storage,\n\n )\n\n };\n\n\n\n let resource_loader = world.read_resource::<Loader>();\n\n let crate_spritesheet_store = world.read_resource::<AssetStorage<SpriteSheet>>();\n\n\n\n resource_loader.load(\n\n Path::new(\"texture\")\n\n .join(\"crate_spritesheet.ron\")\n\n .to_string_lossy(),\n\n SpriteSheetFormat(crate_texture_handle),\n\n (),\n\n &crate_spritesheet_store,\n\n )\n\n}\n\n\n", "file_path": "examples/rendy/main.rs", "rank": 5, "score": 297350.05708710174 }, { "content": "fn init_camera(world: &mut World, parent: Entity, transform: Transform, camera: Camera) -> Entity {\n\n world\n\n .create_entity()\n\n .with(transform)\n\n .with(Parent { entity: parent })\n\n .with(camera)\n\n .named(\"camera\")\n\n .build()\n\n}\n\n\n", "file_path": "examples/tiles/main.rs", "rank": 6, "score": 293909.6736548907 }, { "content": "// Hack: Ideally we want a `SendBoxFnOnce`. However implementing it got too crazy:\n\n//\n\n// * When taking in `ApplicationBuilder<StateLocal>` as a parameter, I couldn't get the type\n\n// parameters to be happy. `StateLocal` had to change depending on the first state, but it\n\n// couldn't be consolidated with `T`.\n\n// * When using `SendBoxFnOnce<'w, (&'w mut World,)>`, the lifetime parameter for the function and\n\n// the `World` could not agree &mdash; you can't coerce a `SendBoxFnOnce<'longer>` into a\n\n// `SendBoxFnOnce<'shorter>`, which was necessary to indicate the length of the borrow of `World`\n\n// for the function is not the `'w` needed to store the function in `AmethystApplication`.\n\n// In addition, it requires the `World` (and hence the `ApplicationBuilder`) to be instantiated\n\n// in a scope greater than the `AmethystApplication`'s lifetime, which detracts from the\n\n// ergonomics of this test harness.\n\ntype FnResourceAdd = Box<dyn FnMut(&mut World) + Send>;\n", "file_path": "amethyst_test/src/amethyst_application.rs", "rank": 7, "score": 289836.7859758023 }, { "content": "type FnSetup = Box<dyn FnOnce(&mut World) + Send>;\n", "file_path": "amethyst_test/src/amethyst_application.rs", "rank": 8, "score": 282729.7948830143 }, { "content": "/// Initialises a ui scoreboard\n\nfn initialise_scoreboard(world: &mut World) {\n\n let font = world.read_resource::<Loader>().load(\n\n \"font/square.ttf\",\n\n TtfFormat,\n\n (),\n\n &world.read_resource(),\n\n );\n\n\n\n let p1_transform = UiTransform::new(\n\n \"P1\".to_string(),\n\n Anchor::TopMiddle,\n\n Anchor::Middle,\n\n -50.,\n\n -50.,\n\n 1.,\n\n 200.,\n\n 50.,\n\n );\n\n let p2_transform = UiTransform::new(\n\n \"P2\".to_string(),\n", "file_path": "examples/pong_tutorial_05/pong.rs", "rank": 9, "score": 267047.00966929964 }, { "content": "/// Initialise the camera.\n\nfn initialise_camera(world: &mut World) {\n\n // Setup camera in a way that our screen covers whole arena and (0, 0) is in the bottom left.\n\n let mut transform = Transform::default();\n\n transform.set_translation_xyz(ARENA_WIDTH * 0.5, ARENA_HEIGHT * 0.5, 1.0);\n\n\n\n world\n\n .create_entity()\n\n .with(Camera::standard_2d(ARENA_WIDTH, ARENA_HEIGHT))\n\n .with(transform)\n\n .build();\n\n}\n\n\n", "file_path": "examples/pong_tutorial_05/pong.rs", "rank": 10, "score": 267047.0096692996 }, { "content": "fn initialise_camera(world: &mut World) {\n\n let (width, height) = {\n\n let dim = world.read_resource::<ScreenDimensions>();\n\n (dim.width(), dim.height())\n\n };\n\n\n\n let mut camera_transform = Transform::default();\n\n camera_transform.set_translation_z(1.0);\n\n\n\n world\n\n .create_entity()\n\n .with(camera_transform)\n\n .with(Camera::standard_2d(width, height))\n\n .build();\n\n}\n\n\n", "file_path": "examples/sprite_animation/main.rs", "rank": 11, "score": 267047.00966929964 }, { "content": "/// Initialise the camera.\n\nfn initialise_camera(world: &mut World) {\n\n // Setup camera in a way that our screen covers whole arena and (0, 0) is in the bottom left.\n\n let mut transform = Transform::default();\n\n transform.set_translation_xyz(ARENA_WIDTH * 0.5, ARENA_HEIGHT * 0.5, 1.0);\n\n\n\n world\n\n .create_entity()\n\n .with(Camera::standard_2d(ARENA_WIDTH, ARENA_HEIGHT))\n\n .with(transform)\n\n .build();\n\n}\n\n\n", "file_path": "examples/pong_tutorial_04/pong.rs", "rank": 12, "score": 267047.0096692996 }, { "content": "fn initialise_camera(world: &mut World) {\n\n let mut transform = Transform::default();\n\n transform.set_translation_xyz(0.0, -20.0, 10.0);\n\n transform.prepend_rotation_x_axis(1.325_752_1);\n\n\n\n world\n\n .create_entity()\n\n .with(Camera::perspective(1.0, std::f32::consts::FRAC_PI_3, 0.1))\n\n .with(transform)\n\n .build();\n\n}\n\n\n", "file_path": "examples/asset_loading/main.rs", "rank": 13, "score": 267047.0096692996 }, { "content": "fn initialise_score(world: &mut World) {\n\n let font = world.read_resource::<Loader>().load(\n\n \"font/square.ttf\",\n\n TtfFormat,\n\n (),\n\n &world.read_resource(),\n\n );\n\n let p1_transform = UiTransform::new(\n\n \"P1\".to_string(),\n\n Anchor::TopMiddle,\n\n Anchor::Middle,\n\n -50.,\n\n -50.,\n\n 1.,\n\n 200.,\n\n 50.,\n\n );\n\n\n\n let p2_transform = UiTransform::new(\n\n \"P2\".to_string(),\n", "file_path": "examples/pong_tutorial_06/pong.rs", "rank": 14, "score": 267047.00966929964 }, { "content": "/// Adds lights to the scene.\n\nfn initialise_lights(world: &mut World) {\n\n let light: Light = PointLight {\n\n intensity: 100.0,\n\n radius: 1.0,\n\n color: Srgb::new(1.0, 1.0, 1.0),\n\n ..Default::default()\n\n }\n\n .into();\n\n\n\n let mut transform = Transform::default();\n\n transform.set_translation_xyz(5.0, -20.0, 15.0);\n\n\n\n // Add point light.\n\n world.create_entity().with(light).with(transform).build();\n\n}\n", "file_path": "examples/asset_loading/main.rs", "rank": 15, "score": 267047.0096692996 }, { "content": "/// Initialise the camera.\n\nfn initialise_camera(world: &mut World) {\n\n // Setup camera in a way that our screen covers whole arena and (0, 0) is in the bottom left.\n\n let mut transform = Transform::default();\n\n transform.set_translation_xyz(ARENA_WIDTH * 0.5, ARENA_HEIGHT * 0.5, 1.0);\n\n\n\n world\n\n .create_entity()\n\n .with(Camera::standard_2d(ARENA_WIDTH, ARENA_HEIGHT))\n\n .with(transform)\n\n .build();\n\n}\n\n\n", "file_path": "examples/pong_tutorial_06/pong.rs", "rank": 16, "score": 267047.00966929964 }, { "content": "/// Initialise the camera.\n\nfn initialise_camera(world: &mut World) {\n\n // Setup camera in a way that our screen covers whole arena and (0, 0) is in the bottom left.\n\n let mut transform = Transform::default();\n\n transform.set_translation_xyz(ARENA_WIDTH * 0.5, ARENA_HEIGHT * 0.5, 1.0);\n\n\n\n world\n\n .create_entity()\n\n .with(Camera::standard_2d(ARENA_WIDTH, ARENA_HEIGHT))\n\n .with(transform)\n\n .build();\n\n}\n\n\n", "file_path": "examples/pong_tutorial_02/pong.rs", "rank": 17, "score": 267047.0096692996 }, { "content": "fn init_camera(world: &mut World) {\n\n let (width, height) = {\n\n let dim = world.read_resource::<ScreenDimensions>();\n\n (dim.width(), dim.height())\n\n };\n\n //println!(\"Init camera with dimensions: {}x{}\", width, height);\n\n\n\n let mut camera_transform = Transform::default();\n\n camera_transform.set_translation_z(1.0);\n\n\n\n world\n\n .create_entity()\n\n .with(camera_transform)\n\n .with(Camera::standard_2d(width, height))\n\n .build();\n\n}\n\n\n", "file_path": "examples/mouse_raycast/main.rs", "rank": 18, "score": 267047.00966929964 }, { "content": "/// Initialise the camera.\n\nfn initialise_camera(world: &mut World) {\n\n // Setup camera in a way that our screen covers whole arena and (0, 0) is in the bottom left.\n\n let mut transform = Transform::default();\n\n transform.set_translation_xyz(ARENA_WIDTH * 0.5, ARENA_HEIGHT * 0.5, 1.0);\n\n\n\n world\n\n .create_entity()\n\n .with(Camera::standard_2d(ARENA_WIDTH, ARENA_HEIGHT))\n\n .with(transform)\n\n .build();\n\n}\n\n\n", "file_path": "examples/pong_tutorial_03/pong.rs", "rank": 19, "score": 267047.00966929964 }, { "content": "pub fn transform_global_view_matrix_1000(b: &mut Criterion) {\n\n let transform = setup();\n\n\n\n b.bench_function(\"transform_global_view_matrix_1000\", move |b| {\n\n b.iter(|| {\n\n for _ in 0..1000 {\n\n let _: [[f32; 4]; 4] =\n\n convert::<_, Matrix4<f32>>(transform.global_view_matrix()).into();\n\n }\n\n });\n\n });\n\n}\n\n\n", "file_path": "amethyst_rendy/benches/camera.rs", "rank": 20, "score": 264557.96999029396 }, { "content": "pub fn manual_inverse_global_matrix_1000(b: &mut Criterion) {\n\n let transform = setup();\n\n\n\n b.bench_function(\"manual_inverse_global_matrix_1000\", move |b| {\n\n b.iter(|| {\n\n for _ in 0..1000 {\n\n let _: [[f32; 4]; 4] = convert::<_, Matrix4<f32>>(\n\n transform\n\n .global_matrix()\n\n .try_inverse()\n\n .expect(\"Unable to get inverse of camera transform\"),\n\n )\n\n .into();\n\n }\n\n });\n\n });\n\n}\n\n\n\ncriterion_group!(\n\n cameras,\n\n transform_global_view_matrix_1000,\n\n manual_inverse_global_matrix_1000,\n\n);\n\ncriterion_main!(cameras);\n", "file_path": "amethyst_rendy/benches/camera.rs", "rank": 21, "score": 264557.96999029396 }, { "content": "pub fn impl_system_desc(ast: &DeriveInput) -> TokenStream {\n\n let system_name = &ast.ident;\n\n let system_desc_name = system_desc_name(&ast);\n\n\n\n // Whether the `SystemDesc` implementation is on the `System` type itself.\n\n let is_self = system_desc_name.is_none();\n\n let system_desc_name = system_desc_name.unwrap_or_else(|| system_name.clone());\n\n\n\n let (system_desc_fields, is_default) = if is_self {\n\n (SystemDescFields::default(), false)\n\n } else {\n\n let system_desc_fields = system_desc_fields(&ast);\n\n\n\n // Don't have to worry about fields to compute -- those are computed in the `build`\n\n // function.\n\n let is_default = system_desc_fields\n\n .field_mappings\n\n .iter()\n\n .find(|&field_mapping| {\n\n if let FieldVariant::Passthrough { .. } = field_mapping.field_variant {\n", "file_path": "amethyst_derive/src/system_desc.rs", "rank": 22, "score": 252704.14870519433 }, { "content": "/// Loads and returns a handle to a sprite sheet.\n\n///\n\n/// The sprite sheet consists of two parts:\n\n///\n\n/// * texture: the pixel data\n\n/// * `SpriteSheet`: the layout information of the sprites on the image\n\nfn load_sprite_sheet(world: &mut World) -> LoadedSpriteSheet {\n\n let loader = world.read_resource::<Loader>();\n\n let texture_handle = {\n\n let texture_storage = world.read_resource::<AssetStorage<Texture>>();\n\n loader.load(\n\n \"texture/arrow_semi_transparent.png\",\n\n ImageFormat::default(),\n\n (),\n\n &texture_storage,\n\n )\n\n };\n\n let sprite_w = 32;\n\n let sprite_h = 32;\n\n let sprite_sheet_definition = SpriteSheetDefinition::new(sprite_w, sprite_h, 2, 6, false);\n\n\n\n let sprite_sheet = sprite_sheet_loader::load(texture_handle, &sprite_sheet_definition);\n\n let sprite_count = sprite_sheet.sprites.len() as u32;\n\n\n\n let sprite_sheet_handle = {\n\n let loader = world.read_resource::<Loader>();\n", "file_path": "examples/sprites_ordered/main.rs", "rank": 23, "score": 252373.31443207467 }, { "content": "fn load_sprite_sheet(world: &mut World) -> Handle<SpriteSheet> {\n\n // Load the sprite sheet necessary to render the graphics.\n\n // The texture is the pixel data\n\n // `sprite_sheet` is the layout of the sprites on the image\n\n // `texture_handle` is a cloneable reference to the texture\n\n\n\n let texture_handle = {\n\n let loader = world.read_resource::<Loader>();\n\n let texture_storage = world.read_resource::<AssetStorage<Texture>>();\n\n loader.load(\n\n \"texture/pong_spritesheet.png\",\n\n ImageFormat::default(),\n\n (),\n\n &texture_storage,\n\n )\n\n };\n\n\n\n let loader = world.read_resource::<Loader>();\n\n let sprite_sheet_store = world.read_resource::<AssetStorage<SpriteSheet>>();\n\n loader.load(\n\n \"texture/pong_spritesheet.ron\", // Here we load the associated ron file\n\n SpriteSheetFormat(texture_handle), // We pass it the texture we want it to use\n\n (),\n\n &sprite_sheet_store,\n\n )\n\n}\n\n\n", "file_path": "examples/pong_tutorial_04/pong.rs", "rank": 24, "score": 247638.44251993587 }, { "content": "fn load_sprite_sheet(world: &mut World) -> Handle<SpriteSheet> {\n\n let texture_handle = {\n\n let loader = world.read_resource::<Loader>();\n\n let texture_storage = world.read_resource::<AssetStorage<Texture>>();\n\n loader.load(\n\n \"texture/pong_spritesheet.png\",\n\n ImageFormat::default(),\n\n (),\n\n &texture_storage,\n\n )\n\n };\n\n\n\n let loader = world.read_resource::<Loader>();\n\n let sprite_sheet_store = world.read_resource::<AssetStorage<SpriteSheet>>();\n\n loader.load(\n\n \"texture/pong_spritesheet.ron\",\n\n SpriteSheetFormat(texture_handle),\n\n (),\n\n &sprite_sheet_store,\n\n )\n\n}\n\n\n", "file_path": "examples/pong_tutorial_03/pong.rs", "rank": 25, "score": 247638.44251993587 }, { "content": "fn load_sprite_sheet(world: &mut World) -> Handle<SpriteSheet> {\n\n // Load the sprite sheet necessary to render the graphics.\n\n // The texture is the pixel data\n\n // `sprite_sheet` is the layout of the sprites on the image\n\n // `texture_handle` is a cloneable reference to the texture\n\n\n\n let texture_handle = {\n\n let loader = world.read_resource::<Loader>();\n\n let texture_storage = world.read_resource::<AssetStorage<Texture>>();\n\n loader.load(\n\n \"texture/pong_spritesheet.png\",\n\n ImageFormat::default(),\n\n (),\n\n &texture_storage,\n\n )\n\n };\n\n\n\n let loader = world.read_resource::<Loader>();\n\n let sprite_sheet_store = world.read_resource::<AssetStorage<SpriteSheet>>();\n\n loader.load(\n\n \"texture/pong_spritesheet.ron\", // Here we load the associated ron file\n\n SpriteSheetFormat(texture_handle), // We pass it the texture we want it to use\n\n (),\n\n &sprite_sheet_store,\n\n )\n\n}\n\n\n", "file_path": "examples/pong_tutorial_06/pong.rs", "rank": 26, "score": 247638.44251993587 }, { "content": "fn load_sprite_sheet(world: &mut World) -> Handle<SpriteSheet> {\n\n let texture_handle = {\n\n let loader = world.read_resource::<Loader>();\n\n let texture_storage = world.read_resource::<AssetStorage<Texture>>();\n\n loader.load(\n\n \"texture/pong_spritesheet.png\",\n\n ImageFormat::default(),\n\n (),\n\n &texture_storage,\n\n )\n\n };\n\n let loader = world.read_resource::<Loader>();\n\n let sprite_sheet_store = world.read_resource::<AssetStorage<SpriteSheet>>();\n\n loader.load(\n\n \"texture/pong_spritesheet.ron\",\n\n SpriteSheetFormat(texture_handle),\n\n (),\n\n &sprite_sheet_store,\n\n )\n\n}\n\n\n", "file_path": "examples/pong_tutorial_02/pong.rs", "rank": 27, "score": 247638.44251993587 }, { "content": "fn load_sprite_sheet(world: &mut World) -> Handle<SpriteSheet> {\n\n // Load the sprite sheet necessary to render the graphics.\n\n // The texture is the pixel data\n\n // `sprite_sheet` is the layout of the sprites on the image\n\n // `texture_handle` is a cloneable reference to the texture\n\n\n\n let texture_handle = {\n\n let loader = world.read_resource::<Loader>();\n\n let texture_storage = world.read_resource::<AssetStorage<Texture>>();\n\n loader.load(\n\n \"texture/pong_spritesheet.png\",\n\n ImageFormat::default(),\n\n (),\n\n &texture_storage,\n\n )\n\n };\n\n\n\n let loader = world.read_resource::<Loader>();\n\n let sprite_sheet_store = world.read_resource::<AssetStorage<SpriteSheet>>();\n\n loader.load(\n\n \"texture/pong_spritesheet.ron\", // Here we load the associated ron file\n\n SpriteSheetFormat(texture_handle), // We pass it the texture we want it to use\n\n (),\n\n &sprite_sheet_store,\n\n )\n\n}\n\n\n", "file_path": "examples/pong_tutorial_05/pong.rs", "rank": 28, "score": 247638.44251993587 }, { "content": "/// This function is used extensively to ensure buffers are allocated and sized appropriately to\n\n/// their use. This function will either allocate a new buffer, resize the current buffer, or perform\n\n/// no action depending on the needs of the function call. This can be used for dynamic buffer\n\n/// allocation or single static buffer allocation.\n\npub fn ensure_buffer<B: Backend>(\n\n factory: &Factory<B>,\n\n buffer: &mut Option<Escape<rendy::resource::Buffer<B>>>,\n\n usage: Usage,\n\n memory_usage: impl MemoryUsage,\n\n min_size: u64,\n\n) -> Result<bool, failure::Error> {\n\n #[cfg(feature = \"profiler\")]\n\n profile_scope!(\"ensure_buffer\");\n\n\n\n if buffer.as_ref().map(|b| b.size()).unwrap_or(0) < min_size {\n\n let new_size = min_size.next_power_of_two();\n\n let new_buffer = factory.create_buffer(\n\n BufferInfo {\n\n size: new_size,\n\n usage,\n\n },\n\n memory_usage,\n\n )?;\n\n *buffer = Some(new_buffer);\n\n Ok(true)\n\n } else {\n\n Ok(false)\n\n }\n\n}\n\n\n", "file_path": "amethyst_rendy/src/util.rs", "rank": 29, "score": 244062.19772198738 }, { "content": "#[inline]\n\npub fn texture_desc<B: Backend>(\n\n texture: &Texture,\n\n layout: hal::image::Layout,\n\n) -> Option<pso::Descriptor<'_, B>> {\n\n B::unwrap_texture(texture).map(|inner| {\n\n pso::Descriptor::CombinedImageSampler(inner.view().raw(), layout, inner.sampler().raw())\n\n })\n\n}\n\n\n", "file_path": "amethyst_rendy/src/util.rs", "rank": 30, "score": 244050.75307265954 }, { "content": "fn init_player(world: &mut World, sprite_sheet: &SpriteSheetHandle) -> Entity {\n\n let mut transform = Transform::default();\n\n transform.set_translation_xyz(0.0, 0.0, 0.1);\n\n let sprite = SpriteRender {\n\n sprite_sheet: sprite_sheet.clone(),\n\n sprite_number: 1,\n\n };\n\n world\n\n .create_entity()\n\n .with(transform)\n\n .with(Player)\n\n .with(sprite)\n\n .with(Transparent)\n\n .named(\"player\")\n\n .build()\n\n}\n\n\n", "file_path": "examples/tiles/main.rs", "rank": 31, "score": 241162.9811099595 }, { "content": "// Initialize a sprite as a reference point at a fixed location\n\nfn init_reference_sprite(world: &mut World, sprite_sheet: &SpriteSheetHandle) -> Entity {\n\n let mut transform = Transform::default();\n\n transform.set_translation_xyz(0.0, 0.0, 0.1);\n\n let sprite = SpriteRender {\n\n sprite_sheet: sprite_sheet.clone(),\n\n sprite_number: 0,\n\n };\n\n world\n\n .create_entity()\n\n .with(transform)\n\n .with(sprite)\n\n .with(Transparent)\n\n .named(\"reference\")\n\n .build()\n\n}\n\n\n", "file_path": "examples/tiles/main.rs", "rank": 32, "score": 239047.3004497176 }, { "content": "/// Initialises one paddle on the left, and one paddle on the right.\n\nfn initialise_paddles(world: &mut World, sprite_sheet_handle: Handle<SpriteSheet>) {\n\n let mut left_transform = Transform::default();\n\n let mut right_transform = Transform::default();\n\n\n\n // Correctly position the paddles.\n\n let y = ARENA_HEIGHT / 2.0;\n\n left_transform.set_translation_xyz(PADDLE_WIDTH * 0.5, y, 0.0);\n\n right_transform.set_translation_xyz(ARENA_WIDTH - PADDLE_WIDTH * 0.5, y, 0.0);\n\n\n\n // Assign the sprites for the paddles\n\n let sprite_render = SpriteRender {\n\n sprite_sheet: sprite_sheet_handle,\n\n sprite_number: 0, // paddle is the first sprite in the sprite_sheet\n\n };\n\n\n\n // Create a left plank entity.\n\n world\n\n .create_entity()\n\n .with(sprite_render.clone())\n\n .with(Paddle::new(Side::Left))\n", "file_path": "examples/pong_tutorial_04/pong.rs", "rank": 33, "score": 239047.3004497176 }, { "content": "/// Initialises one paddle on the left, and one paddle on the right.\n\nfn initialise_paddles(world: &mut World, sprite_sheet_handle: Handle<SpriteSheet>) {\n\n let mut left_transform = Transform::default();\n\n let mut right_transform = Transform::default();\n\n\n\n // Correctly position the paddles.\n\n let y = ARENA_HEIGHT / 2.0;\n\n left_transform.set_translation_xyz(PADDLE_WIDTH * 0.5, y, 0.0);\n\n right_transform.set_translation_xyz(ARENA_WIDTH - PADDLE_WIDTH * 0.5, y, 0.0);\n\n\n\n // Assign the sprites for the paddles\n\n let sprite_render = SpriteRender {\n\n sprite_sheet: sprite_sheet_handle,\n\n sprite_number: 0, // paddle is the first sprite in the sprite_sheet\n\n };\n\n\n\n // Create a left plank entity.\n\n world\n\n .create_entity()\n\n .with(sprite_render.clone())\n\n .with(Paddle::new(Side::Left))\n", "file_path": "examples/pong_tutorial_02/pong.rs", "rank": 34, "score": 239047.3004497176 }, { "content": "/// Initialises one paddle on the left, and one paddle on the right.\n\nfn initialise_paddles(world: &mut World, sprite_sheet_handle: Handle<SpriteSheet>) {\n\n let mut left_transform = Transform::default();\n\n let mut right_transform = Transform::default();\n\n\n\n // Correctly position the paddles.\n\n let y = ARENA_HEIGHT / 2.0;\n\n left_transform.set_translation_xyz(PADDLE_WIDTH * 0.5, y, 0.0);\n\n right_transform.set_translation_xyz(ARENA_WIDTH - PADDLE_WIDTH * 0.5, y, 0.0);\n\n\n\n // Assign the sprites for the paddles\n\n let sprite_render = SpriteRender {\n\n sprite_sheet: sprite_sheet_handle,\n\n sprite_number: 0, // paddle is the first sprite in the sprite_sheet\n\n };\n\n\n\n // Create a left plank entity.\n\n world\n\n .create_entity()\n\n .with(sprite_render.clone())\n\n .with(Paddle::new(Side::Left))\n", "file_path": "examples/pong_tutorial_03/pong.rs", "rank": 35, "score": 239047.3004497176 }, { "content": "/// Initialises one paddle on the left, and one paddle on the right.\n\nfn initialise_paddles(world: &mut World, sprite_sheet_handle: Handle<SpriteSheet>) {\n\n let mut left_transform = Transform::default();\n\n let mut right_transform = Transform::default();\n\n\n\n // Correctly position the paddles.\n\n let y = ARENA_HEIGHT / 2.0;\n\n left_transform.set_translation_xyz(PADDLE_WIDTH * 0.5, y, 0.0);\n\n right_transform.set_translation_xyz(ARENA_WIDTH - PADDLE_WIDTH * 0.5, y, 0.0);\n\n\n\n // Assign the sprites for the paddles\n\n let sprite_render = SpriteRender {\n\n sprite_sheet: sprite_sheet_handle,\n\n sprite_number: 0, // paddle is the first sprite in the sprite_sheet\n\n };\n\n\n\n // Create a left plank entity.\n\n world\n\n .create_entity()\n\n .with(sprite_render.clone())\n\n .with(Paddle::new(Side::Left))\n", "file_path": "examples/pong_tutorial_05/pong.rs", "rank": 36, "score": 239047.3004497176 }, { "content": "/// Initialises one paddle on the left, and one paddle on the right.\n\nfn initialise_paddles(world: &mut World, sprite_sheet_handle: Handle<SpriteSheet>) {\n\n use crate::{PADDLE_HEIGHT, PADDLE_VELOCITY, PADDLE_WIDTH};\n\n\n\n let mut left_transform = Transform::default();\n\n let mut right_transform = Transform::default();\n\n\n\n // Correctly position the paddles.\n\n let y = ARENA_HEIGHT / 2.0;\n\n left_transform.set_translation_xyz(PADDLE_WIDTH * 0.5, y, 0.0);\n\n right_transform.set_translation_xyz(ARENA_WIDTH - PADDLE_WIDTH * 0.5, y, 0.0);\n\n\n\n // Assign the sprites for the paddles\n\n let sprite_render = SpriteRender {\n\n sprite_sheet: sprite_sheet_handle,\n\n sprite_number: 0, // paddle is the first sprite in the sprite_sheet\n\n };\n\n\n\n // Create a left plank entity.\n\n world\n\n .create_entity()\n", "file_path": "examples/pong_tutorial_06/pong.rs", "rank": 37, "score": 239047.3004497176 }, { "content": "/// Initialises one ball in the middle-ish of the arena.\n\nfn initialise_ball(world: &mut World, sprite_sheet_handle: Handle<SpriteSheet>) {\n\n // Create the translation.\n\n let mut local_transform = Transform::default();\n\n local_transform.set_translation_xyz(ARENA_WIDTH / 2.0, ARENA_HEIGHT / 2.0, 0.0);\n\n\n\n // Assign the sprite for the ball\n\n let sprite_render = SpriteRender {\n\n sprite_sheet: sprite_sheet_handle,\n\n sprite_number: 1, // ball is the second sprite on the sprite_sheet\n\n };\n\n\n\n world\n\n .create_entity()\n\n .with(sprite_render)\n\n .with(Ball {\n\n radius: BALL_RADIUS,\n\n velocity: [BALL_VELOCITY_X, BALL_VELOCITY_Y],\n\n })\n\n .with(local_transform)\n\n .build();\n\n}\n\n\n", "file_path": "examples/pong_tutorial_05/pong.rs", "rank": 38, "score": 239047.3004497176 }, { "content": "/// Initialises one ball in the middle-ish of the arena.\n\nfn initialise_ball(world: &mut World, sprite_sheet_handle: Handle<SpriteSheet>) {\n\n use crate::{BALL_RADIUS, BALL_VELOCITY_X, BALL_VELOCITY_Y};\n\n\n\n // Create the translation.\n\n let mut local_transform = Transform::default();\n\n local_transform.set_translation_xyz(ARENA_WIDTH / 2.0, ARENA_HEIGHT / 2.0, 0.0);\n\n\n\n // Assign the sprite for the ball\n\n let sprite_render = SpriteRender {\n\n sprite_sheet: sprite_sheet_handle,\n\n sprite_number: 1, // ball is the second sprite on the sprite_sheet\n\n };\n\n\n\n world\n\n .create_entity()\n\n .with(sprite_render)\n\n .with(Ball {\n\n radius: BALL_RADIUS,\n\n velocity: [BALL_VELOCITY_X, BALL_VELOCITY_Y],\n\n })\n\n .with(local_transform)\n\n .build();\n\n}\n\n\n", "file_path": "examples/pong_tutorial_06/pong.rs", "rank": 39, "score": 239047.3004497176 }, { "content": "/// Initialises one ball in the middle of the arena.\n\nfn initialise_ball(world: &mut World, sprite_sheet_handle: Handle<SpriteSheet>) {\n\n // Create the translation.\n\n let mut local_transform = Transform::default();\n\n local_transform.set_translation_xyz(\n\n (ARENA_WIDTH - BALL_RADIUS) * 0.5,\n\n (ARENA_HEIGHT - BALL_RADIUS) * 0.5,\n\n 0.0,\n\n );\n\n\n\n // Assign the sprite for the ball\n\n let sprite_render = SpriteRender {\n\n sprite_sheet: sprite_sheet_handle,\n\n sprite_number: 1, // ball is the second sprite on the sprite_sheet\n\n };\n\n\n\n world\n\n .create_entity()\n\n .with(sprite_render)\n\n .with(Ball {\n\n radius: BALL_RADIUS,\n\n velocity: [BALL_VELOCITY_X, BALL_VELOCITY_Y],\n\n })\n\n .with(local_transform)\n\n .build();\n\n}\n", "file_path": "examples/pong_tutorial_04/pong.rs", "rank": 40, "score": 239047.3004497176 }, { "content": "#[inline]\n\npub fn desc_write<'a, B: Backend>(\n\n set: &'a B::DescriptorSet,\n\n binding: u32,\n\n descriptor: pso::Descriptor<'a, B>,\n\n) -> pso::DescriptorSetWrite<'a, B, Option<pso::Descriptor<'a, B>>> {\n\n pso::DescriptorSetWrite {\n\n set,\n\n binding,\n\n array_offset: 0,\n\n descriptors: Some(descriptor),\n\n }\n\n}\n\n\n\n/// Helper function to create a `CombinedImageSampler` from a supplied `Texture` and `Layout`\n", "file_path": "amethyst_rendy/src/util.rs", "rank": 41, "score": 238600.34309826663 }, { "content": "// Initialize a sprite as a reference point\n\nfn init_screen_reference_sprite(world: &mut World, sprite_sheet: &SpriteSheetHandle) -> Entity {\n\n let mut transform = Transform::default();\n\n transform.set_translation_xyz(-250.0, -245.0, 0.1);\n\n let sprite = SpriteRender {\n\n sprite_sheet: sprite_sheet.clone(),\n\n sprite_number: 0,\n\n };\n\n world\n\n .create_entity()\n\n .with(transform)\n\n .with(sprite)\n\n .with(Transparent)\n\n .named(\"screen_reference\")\n\n .build()\n\n}\n\n\n", "file_path": "examples/tiles/main.rs", "rank": 42, "score": 236992.93098635483 }, { "content": "/// Helper function to create a `GraphicsShaderSet`\n\npub fn simple_shader_set<'a, B: Backend>(\n\n vertex: &'a B::ShaderModule,\n\n fragment: Option<&'a B::ShaderModule>,\n\n) -> pso::GraphicsShaderSet<'a, B> {\n\n simple_shader_set_ext(vertex, fragment, None, None, None)\n\n}\n\n\n", "file_path": "amethyst_rendy/src/util.rs", "rank": 43, "score": 235928.8897942808 }, { "content": "/// Helper function to create a `GraphicsShaderSet`\n\npub fn simple_shader_set_ext<'a, B: Backend>(\n\n vertex: &'a B::ShaderModule,\n\n fragment: Option<&'a B::ShaderModule>,\n\n hull: Option<&'a B::ShaderModule>,\n\n domain: Option<&'a B::ShaderModule>,\n\n geometry: Option<&'a B::ShaderModule>,\n\n) -> pso::GraphicsShaderSet<'a, B> {\n\n fn map_entry_point<B: Backend>(module: &B::ShaderModule) -> pso::EntryPoint<'_, B> {\n\n pso::EntryPoint {\n\n entry: \"main\",\n\n module,\n\n specialization: pso::Specialization::default(),\n\n }\n\n }\n\n\n\n pso::GraphicsShaderSet {\n\n vertex: map_entry_point(vertex),\n\n fragment: fragment.map(map_entry_point),\n\n hull: hull.map(map_entry_point),\n\n domain: domain.map(map_entry_point),\n\n geometry: geometry.map(map_entry_point),\n\n }\n\n}\n\n\n", "file_path": "amethyst_rendy/src/util.rs", "rank": 44, "score": 233351.3535922649 }, { "content": "fn init_player(world: &mut World, sprite_sheet: &Handle<SpriteSheet>) -> Entity {\n\n let mut transform = Transform::default();\n\n transform.set_translation_xyz(0.0, 0.0, -3.0);\n\n let sprite = SpriteRender {\n\n sprite_sheet: sprite_sheet.clone(),\n\n sprite_number: 1,\n\n };\n\n world\n\n .create_entity()\n\n .with(transform)\n\n .with(Player)\n\n .with(sprite)\n\n .with(Transparent)\n\n .named(\"player\")\n\n .build()\n\n}\n\n\n", "file_path": "examples/sprite_camera_follow/main.rs", "rank": 45, "score": 233076.799492331 }, { "content": "// Initialize a sprite as a reference point at a fixed location\n\nfn init_reference_sprite(world: &mut World, sprite_sheet: &Handle<SpriteSheet>) -> Entity {\n\n let mut transform = Transform::default();\n\n transform.set_translation_xyz(0.0, 0.0, 0.0);\n\n let sprite = SpriteRender {\n\n sprite_sheet: sprite_sheet.clone(),\n\n sprite_number: 0,\n\n };\n\n world\n\n .create_entity()\n\n .with(transform)\n\n .with(sprite)\n\n .with(Transparent)\n\n .named(\"reference\")\n\n .build()\n\n}\n\n\n", "file_path": "examples/sprite_camera_follow/main.rs", "rank": 46, "score": 231081.03212302836 }, { "content": "// Initialize a background\n\nfn init_background_sprite(world: &mut World, sprite_sheet: &Handle<SpriteSheet>) -> Entity {\n\n let mut transform = Transform::default();\n\n transform.set_translation_z(-10.0);\n\n let sprite = SpriteRender {\n\n sprite_sheet: sprite_sheet.clone(),\n\n sprite_number: 0,\n\n };\n\n world\n\n .create_entity()\n\n .with(transform)\n\n .with(sprite)\n\n .named(\"background\")\n\n .with(Transparent)\n\n .build()\n\n}\n\n\n", "file_path": "examples/sprite_camera_follow/main.rs", "rank": 47, "score": 231081.03212302836 }, { "content": "// Initialize a sprite as a reference point\n\nfn init_screen_reference_sprite(world: &mut World, sprite_sheet: &Handle<SpriteSheet>) -> Entity {\n\n let mut transform = Transform::default();\n\n transform.set_translation_xyz(-250.0, -245.0, -11.0);\n\n let sprite = SpriteRender {\n\n sprite_sheet: sprite_sheet.clone(),\n\n sprite_number: 0,\n\n };\n\n world\n\n .create_entity()\n\n .with(transform)\n\n .with(sprite)\n\n .with(Transparent)\n\n .named(\"screen_reference\")\n\n .build()\n\n}\n\n\n", "file_path": "examples/sprite_camera_follow/main.rs", "rank": 48, "score": 229141.3186631069 }, { "content": "/// Basic building block of rendering in [RenderingBundle].\n\n///\n\n/// Can be used to register rendering-related systems to the dispatcher,\n\n/// building render graph by registering render targets, adding [RenderableAction]s to them\n\n/// and signalling when the graph has to be rebuild.\n\npub trait RenderPlugin<B: Backend>: std::fmt::Debug {\n\n /// Hook for adding systems and bundles to the dispatcher.\n\n fn on_build<'a, 'b>(\n\n &mut self,\n\n _world: &mut World,\n\n _builder: &mut DispatcherBuilder<'a, 'b>,\n\n ) -> Result<(), Error> {\n\n Ok(())\n\n }\n\n\n\n /// Hook for providing triggers to rebuild the render graph.\n\n fn should_rebuild(&mut self, _world: &World) -> bool {\n\n false\n\n }\n\n\n\n /// Hook for extending the rendering plan.\n\n fn on_plan(\n\n &mut self,\n\n plan: &mut RenderPlan<B>,\n\n factory: &mut Factory<B>,\n", "file_path": "amethyst_rendy/src/bundle.rs", "rank": 49, "score": 225772.27184955432 }, { "content": "fn load_sprite_sheet(world: &mut World, png_path: &str, ron_path: &str) -> SpriteSheetHandle {\n\n let texture_handle = {\n\n let loader = world.read_resource::<Loader>();\n\n let texture_storage = world.read_resource::<AssetStorage<Texture>>();\n\n loader.load(png_path, ImageFormat::default(), (), &texture_storage)\n\n };\n\n let loader = world.read_resource::<Loader>();\n\n let sprite_sheet_store = world.read_resource::<AssetStorage<SpriteSheet>>();\n\n loader.load(\n\n ron_path,\n\n SpriteSheetFormat(texture_handle),\n\n (),\n\n &sprite_sheet_store,\n\n )\n\n}\n\n\n", "file_path": "examples/tiles/main.rs", "rank": 50, "score": 225555.39330180868 }, { "content": "fn load_sprite_sheet(world: &mut World, png_path: &str, ron_path: &str) -> Handle<SpriteSheet> {\n\n let texture_handle = {\n\n let loader = world.read_resource::<Loader>();\n\n let texture_storage = world.read_resource::<AssetStorage<Texture>>();\n\n loader.load(png_path, ImageFormat::default(), (), &texture_storage)\n\n };\n\n let loader = world.read_resource::<Loader>();\n\n let sprite_sheet_store = world.read_resource::<AssetStorage<SpriteSheet>>();\n\n loader.load(\n\n ron_path,\n\n SpriteSheetFormat(texture_handle),\n\n (),\n\n &sprite_sheet_store,\n\n )\n\n}\n\n\n", "file_path": "examples/sprite_camera_follow/main.rs", "rank": 51, "score": 218538.01294164313 }, { "content": "/// Graph trait implementation required by consumers. Builds a graph and manages signaling when\n\n/// the graph needs to be rebuilt.\n\npub trait GraphCreator<B: Backend> {\n\n /// Check if graph needs to be rebuilt.\n\n /// This function is evaluated every frame before running the graph.\n\n fn rebuild(&mut self, world: &World) -> bool;\n\n\n\n /// Retrieve configured complete graph builder.\n\n fn builder(&mut self, factory: &mut Factory<B>, world: &World) -> GraphBuilder<B, World>;\n\n}\n\n\n\n/// Amethyst rendering system\n\n#[allow(missing_debug_implementations)]\n\npub struct RenderingSystem<B, G>\n\nwhere\n\n B: Backend,\n\n G: GraphCreator<B>,\n\n{\n\n graph: Option<Graph<B, World>>,\n\n families: Option<Families<B>>,\n\n graph_creator: G,\n\n}\n", "file_path": "amethyst_rendy/src/system.rs", "rank": 52, "score": 214699.42186828898 }, { "content": "/// Copy the byte-data from an iterator into a slice\n\npub fn write_into_slice<I: IntoIterator>(dst_slice: &mut [u8], iter: I) {\n\n for (data, dst) in iter\n\n .into_iter()\n\n .zip(dst_slice.chunks_exact_mut(std::mem::size_of::<I::Item>()))\n\n {\n\n dst.copy_from_slice(slice_as_bytes(&[data]));\n\n }\n\n}\n\n\n\n/// Iterator counting adapter.\n\n#[must_use = \"iterator adaptors are lazy and do nothing unless consumed\"]\n\n#[allow(missing_debug_implementations)]\n\npub struct TapCountIterator<'a, T: PrimInt, I: Iterator> {\n\n inner: I,\n\n counter: &'a mut T,\n\n}\n\n\n", "file_path": "amethyst_rendy/src/util.rs", "rank": 53, "score": 211629.3801080579 }, { "content": "pub fn amethyst_core() -> TokenStream {\n\n if let Ok(name) =\n\n proc_macro_crate::crate_name(\"amethyst_core\").map(|x| Ident::new(&x, Span::call_site()))\n\n {\n\n quote!(::#name)\n\n } else if let Ok(name) =\n\n proc_macro_crate::crate_name(\"amethyst\").map(|x| Ident::new(&x, Span::call_site()))\n\n {\n\n quote!(::#name::core)\n\n } else {\n\n quote!(::amethyst::core)\n\n }\n\n}\n\n\n", "file_path": "amethyst_derive/src/system_desc.rs", "rank": 54, "score": 211505.64051267097 }, { "content": "fn build_lines_pipeline<B: Backend>(\n\n factory: &Factory<B>,\n\n subpass: hal::pass::Subpass<'_, B>,\n\n framebuffer_width: u32,\n\n framebuffer_height: u32,\n\n layouts: Vec<&B::DescriptorSetLayout>,\n\n) -> Result<(B::GraphicsPipeline, B::PipelineLayout), failure::Error> {\n\n let pipeline_layout = unsafe {\n\n factory\n\n .device()\n\n .create_pipeline_layout(layouts, None as Option<(_, _)>)\n\n }?;\n\n\n\n let shader_vertex = unsafe { super::DEBUG_LINES_VERTEX.module(factory).unwrap() };\n\n let shader_fragment = unsafe { super::DEBUG_LINES_FRAGMENT.module(factory).unwrap() };\n\n\n\n let pipes = PipelinesBuilder::new()\n\n .with_pipeline(\n\n PipelineDescBuilder::new()\n\n .with_vertex_desc(&[(DebugLine::vertex(), pso::VertexInputRate::Instance(1))])\n", "file_path": "amethyst_rendy/src/pass/debug_lines.rs", "rank": 55, "score": 210782.19276378278 }, { "content": "/// Adds a `Removal` component with the specified id to the specified entity.\n\n/// Usually used with prefabs, when you want to add a `Removal` component at the root of the loaded prefab.\n\npub fn add_removal_to_entity<T: PartialEq + Clone + Debug + Send + Sync + 'static>(\n\n entity: Entity,\n\n id: T,\n\n storage: &mut WriteStorage<'_, Removal<T>>,\n\n) {\n\n storage\n\n .insert(entity, Removal::new(id))\n\n .unwrap_or_else(|_| {\n\n panic!(\n\n \"Failed to insert `Removal` component id to entity {:?}.\",\n\n entity,\n\n )\n\n });\n\n}\n", "file_path": "amethyst_utils/src/removal.rs", "rank": 56, "score": 205221.03876397345 }, { "content": "/// Initializes a `System` with some interaction with the `World`.\n\npub trait SystemDesc<'a, 'b, S>\n\nwhere\n\n S: System<'a>,\n\n{\n\n /// Builds and returns a `System`.\n\n ///\n\n /// # Parameters\n\n ///\n\n /// * `world`: `World` that the system will run on.\n\n fn build(self, world: &mut World) -> S;\n\n}\n\n\n", "file_path": "amethyst_core/src/system_desc.rs", "rank": 57, "score": 204441.2296438096 }, { "content": "/// Define a set of types used for bindings configuration.\n\n/// Usually defaulted to `StringBindings`, which uses `String`s.\n\n///\n\n/// By defining your own set of types (usually enums),\n\n/// you will be able to have compile-time guarantees while handling events,\n\n/// and you can also add additional context, for example player index\n\n/// in local multiplayer game.\n\n///\n\n/// Example configuration for local multiplayer driving game might look like this:\n\n/// ```rust,edition2018,no_run,noplaypen\n\n/// # use serde::{Serialize, Deserialize};\n\n/// # use amethyst_input::{BindingTypes, Bindings};\n\n/// type PlayerId = u8;\n\n///\n\n/// #[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]\n\n/// enum AxisBinding {\n\n/// Throttle(PlayerId),\n\n/// Steering(PlayerId),\n\n/// }\n\n///\n\n/// #[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]\n\n/// enum ActionBinding {\n\n/// UsePowerup(PlayerId),\n\n/// }\n\n///\n\n/// #[derive(Debug)]\n\n/// struct DriverBindingTypes;\n\n/// impl BindingTypes for DriverBindingTypes {\n\n/// type Axis = AxisBinding;\n\n/// type Action = ActionBinding;\n\n/// }\n\n///\n\n/// type GameBindings = Bindings<DriverBindingTypes>;\n\n/// ```\n\n/// And the `bindings.ron`:\n\n/// ```ron\n\n/// (\n\n/// axes: {\n\n/// Throttle(0): Emulated(pos: Key(W), neg: Key(S)),\n\n/// Steering(0): Emulated(pos: Key(D), neg: Key(A)),\n\n/// Throttle(1): Emulated(pos: Key(Up), neg: Key(Down)),\n\n/// Steering(1): Emulated(pos: Key(Right), neg: Key(Left)),\n\n/// },\n\n/// actions: {\n\n/// UsePowerup(0): [[Key(E)]],\n\n/// UsePowerup(1): [[Key(P)]],\n\n/// },\n\n/// )\n\n/// ```\n\npub trait BindingTypes: Debug + Send + Sync + 'static {\n\n /// Type used for defining axis keys. Usually an enum or string.\n\n type Axis: Clone + Debug + Hash + Eq + Send + Sync + 'static;\n\n /// Type used for defining action keys. Usually an enum or string.\n\n type Action: Clone + Debug + Hash + Eq + Send + Sync + 'static;\n\n}\n\n\n\n/// The builtin `BindingTypes` implementation, set of types for binding configuration keys.\n\n/// Uses `String` for both axes and actions. Usage of this type is discouraged\n\n/// and it's meant mainly for prototypes. Check `BindingTypes` for examples.\n\n#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]\n\npub struct StringBindings;\n\n\n\nimpl BindingTypes for StringBindings {\n\n type Axis = String;\n\n type Action = String;\n\n}\n\n\n\n/// Used for saving and loading input settings.\n\n///\n", "file_path": "amethyst_input/src/bindings.rs", "rank": 58, "score": 203173.85686736938 }, { "content": "/// Gets the input axis value from the `InputHandler`.\n\n/// If the name is None, it will return the default value of the axis (0.0).\n\npub fn get_input_axis_simple<T: BindingTypes>(\n\n name: &Option<T::Axis>,\n\n input: &InputHandler<T>,\n\n) -> f32 {\n\n name.as_ref()\n\n .and_then(|ref n| input.axis_value(n))\n\n .unwrap_or(0.0)\n\n}\n\n\n", "file_path": "amethyst_input/src/util.rs", "rank": 59, "score": 203029.5562032263 }, { "content": "#[derive(Debug)]\n\nstruct ActionChangeStack<T: Debug + Clone + PartialEq> {\n\n initial_value: T,\n\n stack: Vec<T>,\n\n}\n\n\n\nimpl<T> ActionChangeStack<T>\n\nwhere\n\n T: Debug + Clone + PartialEq,\n\n{\n\n pub fn new(initial_value: T) -> Self {\n\n ActionChangeStack {\n\n initial_value,\n\n stack: Vec::new(),\n\n }\n\n }\n\n\n\n pub fn add(&mut self, change: T) {\n\n self.stack.push(change);\n\n }\n\n\n", "file_path": "amethyst_ui/src/button/system.rs", "rank": 60, "score": 201342.69242015248 }, { "content": "#[proc_macro_derive(SystemDesc, attributes(system_desc))]\n\npub fn system_desc_derive(input: TokenStream) -> TokenStream {\n\n let ast = parse_macro_input!(input as DeriveInput);\n\n let gen = system_desc::impl_system_desc(&ast);\n\n gen.into()\n\n}\n", "file_path": "amethyst_derive/src/lib.rs", "rank": 61, "score": 196539.93535055296 }, { "content": "/// Returns the default system font.\n\npub fn default_system_font() -> Result<Handle, SelectionError> {\n\n let source = SystemSource::new();\n\n let default_fonts = &[\n\n FamilyName::Title(\"arial\".to_string()),\n\n FamilyName::SansSerif,\n\n FamilyName::Monospace,\n\n FamilyName::Fantasy,\n\n ];\n\n source.select_best_match(default_fonts, Properties::new().style(Style::Normal))\n\n}\n", "file_path": "amethyst_ui/src/font/systemfont.rs", "rank": 62, "score": 196539.19453520846 }, { "content": "pub fn impl_event_reader(ast: &DeriveInput) -> TokenStream {\n\n let event_name = &ast.ident;\n\n\n\n let mut reader_name: Option<Ident> = None;\n\n for meta in ast\n\n .attrs\n\n .iter()\n\n .filter(|attr| attr.path.segments[0].ident == \"reader\")\n\n .map(|attr| {\n\n attr.parse_meta()\n\n .expect(\"reader attribute incorrectly defined\")\n\n })\n\n {\n\n if let Meta::List(l) = meta {\n\n for nested_meta in l.nested.iter() {\n\n match nested_meta {\n\n NestedMeta::Meta(Meta::Path(path)) => {\n\n if let Some(ident) = path.get_ident() {\n\n reader_name = Some(ident.clone());\n\n } else {\n", "file_path": "amethyst_derive/src/event_reader.rs", "rank": 63, "score": 194802.36372163368 }, { "content": "pub fn impl_prefab_data(ast: &DeriveInput) -> TokenStream {\n\n if is_component_prefab(&ast.attrs[..]) {\n\n impl_prefab_data_component(ast)\n\n } else {\n\n impl_prefab_data_aggregate(ast)\n\n }\n\n}\n\n\n", "file_path": "amethyst_derive/src/prefab_data.rs", "rank": 64, "score": 194802.36372163368 }, { "content": "pub fn impl_widget_id(ast: &DeriveInput) -> TokenStream {\n\n // For now, we can only derive this on enums\n\n let default_variant = match &ast.data {\n\n Data::Enum(ref data_enum) => {\n\n let maybe_marked_default = data_enum\n\n .variants\n\n .iter()\n\n .filter(|v| {\n\n v.attrs\n\n .iter()\n\n .any(|attr| attr.path.segments[0].ident == \"widget_id_default\")\n\n })\n\n .map(|v| v.ident.clone())\n\n .collect::<Vec<Ident>>();\n\n\n\n if maybe_marked_default.len() > 1 {\n\n panic!(\"Only 1 variant can be marked as default widget id\")\n\n }\n\n\n\n if !maybe_marked_default.is_empty() {\n", "file_path": "amethyst_derive/src/widget_id.rs", "rank": 65, "score": 194802.36372163368 }, { "content": "#[derive(SystemDesc)]\n\nstruct ExampleLinesSystem;\n\n\n\nimpl<'s> System<'s> for ExampleLinesSystem {\n\n type SystemData = (\n\n Write<'s, DebugLines>, // Request DebugLines resource\n\n Read<'s, Time>,\n\n );\n\n\n\n fn run(&mut self, (mut debug_lines_resource, time): Self::SystemData) {\n\n // Drawing debug lines as a resource\n\n let t = (time.absolute_time_seconds() as f32).cos();\n\n\n\n debug_lines_resource.draw_direction(\n\n Point3::new(t, 0.0, 0.5),\n\n Vector3::new(0.0, 0.3, 0.0),\n\n Srgba::new(0.5, 0.05, 0.65, 1.0),\n\n );\n\n\n\n debug_lines_resource.draw_line(\n\n Point3::new(t, 0.0, 0.5),\n\n Point3::new(0.0, 0.0, 0.2),\n\n Srgba::new(0.5, 0.05, 0.65, 1.0),\n\n );\n\n }\n\n}\n\n\n", "file_path": "examples/debug_lines/main.rs", "rank": 66, "score": 194593.2901378143 }, { "content": "#[derive(Debug)]\n\nstruct PerImageDynamicVertexData<B: Backend, V: VertexDataBufferType> {\n\n buffer: Option<Escape<Buffer<B>>>,\n\n marker: PhantomData<V>,\n\n}\n\n\n\nimpl<B: Backend, V: VertexDataBufferType> PerImageDynamicVertexData<B, V> {\n\n /// Creates a new 'PerImageDynamicVertexData'\n\n fn new() -> Self {\n\n Self {\n\n buffer: None,\n\n marker: PhantomData,\n\n }\n\n }\n\n\n\n /// Garuntees that at least max_size bytes of memory is allocated for this buffer\n\n /// Calls the utility function, [util::ensure_buffer] to dynamically grow the buffer if needed.\n\n fn ensure(&mut self, factory: &Factory<B>, max_size: u64) -> bool {\n\n util::ensure_buffer(\n\n &factory,\n\n &mut self.buffer,\n", "file_path": "amethyst_rendy/src/submodules/vertex.rs", "rank": 67, "score": 192752.34211046167 }, { "content": "#[derive(SystemDesc)]\n\nstruct ExampleLinesSystem;\n\n\n\nimpl ExampleLinesSystem {\n\n pub fn new() -> Self {\n\n Self\n\n }\n\n}\n\n\n\nimpl<'s> System<'s> for ExampleLinesSystem {\n\n type SystemData = (\n\n ReadExpect<'s, ScreenDimensions>,\n\n Write<'s, DebugLines>,\n\n Read<'s, Time>,\n\n );\n\n\n\n fn run(&mut self, (screen_dimensions, mut debug_lines_resource, time): Self::SystemData) {\n\n let t = (time.absolute_time_seconds() as f32).cos() / 2.0 + 0.5;\n\n\n\n let screen_w = screen_dimensions.width();\n\n let screen_h = screen_dimensions.height();\n\n let y = t * screen_h;\n\n\n\n debug_lines_resource.draw_line(\n\n [0.0, y, 1.0].into(),\n\n [screen_w, y + 2.0, 1.0].into(),\n\n Srgba::new(0.3, 0.3, 1.0, 1.0),\n\n );\n\n }\n\n}\n\n\n", "file_path": "examples/debug_lines_ortho/main.rs", "rank": 68, "score": 191720.32559010966 }, { "content": "/// Lists all installed font families on the system.\n\npub fn list_system_font_families() -> Result<Vec<String>, SelectionError> {\n\n let source = SystemSource::new();\n\n source.all_families()\n\n}\n\n\n", "file_path": "amethyst_ui/src/font/systemfont.rs", "rank": 69, "score": 188835.0576946588 }, { "content": "/// Get the (width, height) in pixels of the parent of this `UiTransform`.\n\npub fn get_parent_pixel_size<S: GenericReadStorage<Component = UiTransform>>(\n\n entity: Entity,\n\n hierarchy: &ParentHierarchy,\n\n ui_transforms: &S,\n\n screen_dimensions: &ScreenDimensions,\n\n) -> (f32, f32) {\n\n let mut parent_width = screen_dimensions.width();\n\n let mut parent_height = screen_dimensions.height();\n\n\n\n if let Some(parent) = hierarchy.parent(entity) {\n\n if let Some(ui_transform) = ui_transforms.get(parent) {\n\n parent_width = ui_transform.pixel_width();\n\n parent_height = ui_transform.pixel_height();\n\n }\n\n }\n\n\n\n (parent_width, parent_height)\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "amethyst_ui/src/transform.rs", "rank": 70, "score": 187252.9446466349 }, { "content": "fn system_desc_struct(context: &Context<'_>) -> TokenStream {\n\n let Context {\n\n ref system_name,\n\n ref system_desc_name,\n\n ref system_desc_fields,\n\n ref ty_generics,\n\n ref where_clause,\n\n ..\n\n } = context;\n\n\n\n let fields = &system_desc_fields.fields;\n\n let struct_declaration = match fields {\n\n Fields::Unit => quote!(struct #system_desc_name;),\n\n Fields::Unnamed(..) => quote! {\n\n struct #system_desc_name #ty_generics #fields #where_clause;\n\n },\n\n Fields::Named(..) => quote! {\n\n struct #system_desc_name #ty_generics #where_clause #fields\n\n },\n\n };\n\n\n\n let doc_string = format!(\"Builds a `{}`.\", system_name);\n\n quote! {\n\n #[doc = #doc_string]\n\n #[derive(Debug)]\n\n pub #struct_declaration\n\n }\n\n}\n\n\n", "file_path": "amethyst_derive/src/system_desc.rs", "rank": 71, "score": 180919.9513308095 }, { "content": "#[test]\n\nfn rename_struct() -> Result<(), Error> {\n\n #[derive(Debug, SystemDesc)]\n\n #[system_desc(name(SystemUnitDesc))]\n\n struct SystemUnit;\n\n\n\n impl<'s> System<'s> for SystemUnit {\n\n type SystemData = ();\n\n fn run(&mut self, _: Self::SystemData) {}\n\n }\n\n\n\n let mut world = World::new();\n\n\n\n SystemUnitDesc.build(&mut world);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "amethyst_derive/tests/system_desc.rs", "rank": 72, "score": 179883.06489498733 }, { "content": "#[test]\n\nfn struct_tuple_with_passthrough() -> Result<(), Error> {\n\n #[derive(Debug, Default, SystemDesc)]\n\n #[system_desc(name(SystemTuplePassthroughDesc))]\n\n struct SystemTuplePassthrough(u32);\n\n\n\n impl<'s> System<'s> for SystemTuplePassthrough {\n\n type SystemData = ();\n\n fn run(&mut self, _: Self::SystemData) {}\n\n }\n\n\n\n let mut world = World::new();\n\n\n\n SystemTuplePassthroughDesc::new(123).build(&mut world);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "amethyst_derive/tests/system_desc.rs", "rank": 73, "score": 177222.2750853111 }, { "content": "#[test]\n\nfn struct_tuple_complex() -> Result<(), Error> {\n", "file_path": "amethyst_derive/tests/system_desc.rs", "rank": 74, "score": 177222.2750853111 }, { "content": "#[test]\n\nfn struct_tuple_with_phantom() -> Result<(), Error> {\n\n // Expects `System` to `impl Default`\n\n #[derive(Debug, SystemDesc)]\n\n #[system_desc(name(SystemTuplePhantomDesc))]\n\n struct SystemTuplePhantom<T>(PhantomData<T>);\n\n impl<T> Default for SystemTuplePhantom<T> {\n\n fn default() -> Self {\n\n SystemTuplePhantom(PhantomData)\n\n }\n\n }\n\n\n\n impl<'s, T> System<'s> for SystemTuplePhantom<T> {\n\n type SystemData = ();\n\n fn run(&mut self, _: Self::SystemData) {}\n\n }\n\n\n\n let mut world = World::new();\n\n\n\n SystemTuplePhantomDesc::<()>::default().build(&mut world);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "amethyst_derive/tests/system_desc.rs", "rank": 75, "score": 177222.2750853111 }, { "content": "#[test]\n\nfn struct_tuple_with_skip() -> Result<(), Error> {\n\n // Expects `System` to `impl Default`\n\n #[derive(Debug, Default, SystemDesc)]\n\n #[system_desc(name(SystemTupleSkipDesc))]\n\n struct SystemTupleSkip(#[system_desc(skip)] u32);\n\n\n\n impl<'s> System<'s> for SystemTupleSkip {\n\n type SystemData = ();\n\n fn run(&mut self, _: Self::SystemData) {}\n\n }\n\n\n\n let mut world = World::new();\n\n\n\n SystemTupleSkipDesc::default().build(&mut world);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "amethyst_derive/tests/system_desc.rs", "rank": 76, "score": 177222.2750853111 }, { "content": "#[test]\n\nfn struct_named_complex() -> Result<(), Error> {\n", "file_path": "amethyst_derive/tests/system_desc.rs", "rank": 77, "score": 177222.2750853111 }, { "content": "#[test]\n\nfn struct_named_with_skip() -> Result<(), Error> {\n\n // Expects `System` to `impl Default`\n\n #[derive(Debug, Default, SystemDesc)]\n\n #[system_desc(name(SystemNamedSkipDesc))]\n\n struct SystemNamedSkip {\n\n #[system_desc(skip)]\n\n a: u32,\n\n }\n\n\n\n impl<'s> System<'s> for SystemNamedSkip {\n\n type SystemData = ();\n\n fn run(&mut self, _: Self::SystemData) {}\n\n }\n\n\n\n let mut world = World::new();\n\n\n\n SystemNamedSkipDesc::default().build(&mut world);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "amethyst_derive/tests/system_desc.rs", "rank": 78, "score": 177222.2750853111 }, { "content": "#[test]\n\nfn struct_named_with_passthrough() -> Result<(), Error> {\n\n #[derive(Debug, Default, SystemDesc)]\n\n #[system_desc(name(SystemNamedPassthroughDesc))]\n\n struct SystemNamedPassthrough {\n\n a: u32,\n\n }\n\n\n\n impl<'s> System<'s> for SystemNamedPassthrough {\n\n type SystemData = ();\n\n fn run(&mut self, _: Self::SystemData) {}\n\n }\n\n\n\n let mut world = World::new();\n\n\n\n SystemNamedPassthroughDesc::new(123).build(&mut world);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "amethyst_derive/tests/system_desc.rs", "rank": 79, "score": 177222.2750853111 }, { "content": "#[test]\n\nfn struct_named_with_phantom() -> Result<(), Error> {\n\n // Expects `System` to `impl Default`\n\n #[derive(Debug, SystemDesc)]\n\n #[system_desc(name(SystemNamedPhantomDesc))]\n\n struct SystemNamedPhantom<T> {\n\n marker: PhantomData<T>,\n\n }\n\n impl<T> Default for SystemNamedPhantom<T> {\n\n fn default() -> Self {\n\n SystemNamedPhantom {\n\n marker: PhantomData,\n\n }\n\n }\n\n }\n\n\n\n impl<'s, T> System<'s> for SystemNamedPhantom<T> {\n\n type SystemData = ();\n\n fn run(&mut self, _: Self::SystemData) {}\n\n }\n\n\n\n let mut world = World::new();\n\n\n\n SystemNamedPhantomDesc::<()>::default().build(&mut world);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "amethyst_derive/tests/system_desc.rs", "rank": 80, "score": 177222.2750853111 }, { "content": "struct AddBundle<B> {\n\n bundle: B,\n\n}\n\n\n\nimpl<'a, 'b, B> DispatcherOperation<'a, 'b> for AddBundle<B>\n\nwhere\n\n B: SystemBundle<'a, 'b>,\n\n{\n\n fn exec(\n\n self: Box<Self>,\n\n world: &mut World,\n\n dispatcher_builder: &mut DispatcherBuilder<'a, 'b>,\n\n ) -> Result<(), Error> {\n\n self.bundle.build(world, dispatcher_builder)?;\n\n Ok(())\n\n }\n\n}\n", "file_path": "examples/custom_game_data/game_data.rs", "rank": 81, "score": 174740.7965604501 }, { "content": "/// Helper function which takes an array of vertex format information and returns allocated\n\n/// `VertexBufferDesc` and `AttributeDesc` collections.\n\npub fn vertex_desc(\n\n formats: &[(VertexFormat, pso::VertexInputRate)],\n\n) -> (Vec<pso::VertexBufferDesc>, Vec<pso::AttributeDesc>) {\n\n let mut vertex_buffers = Vec::with_capacity(formats.len());\n\n let mut attributes = Vec::with_capacity(formats.len());\n\n\n\n let mut sorted: SmallVec<[_; 16]> = formats.iter().enumerate().collect();\n\n sorted.sort_unstable_by(|a, b| a.1.cmp(&b.1));\n\n\n\n let mut loc_offset = 0;\n\n for (loc_base, (format, rate)) in sorted {\n\n push_vertex_desc(\n\n format.gfx_vertex_input_desc(*rate),\n\n loc_base as pso::Location + loc_offset,\n\n &mut vertex_buffers,\n\n &mut attributes,\n\n );\n\n loc_offset += format.attributes.len() as pso::Location - 1;\n\n }\n\n (vertex_buffers, attributes)\n\n}\n\n\n", "file_path": "amethyst_rendy/src/util.rs", "rank": 82, "score": 173078.09018650654 }, { "content": "#[test]\n\nfn struct_named_with_event_channel_reader() -> Result<(), Error> {\n\n // Expects `System` to have a `new` constructor.\n\n #[derive(Debug, SystemDesc)]\n\n #[system_desc(name(SystemNamedEventChannelDesc))]\n\n struct SystemNamedEventChannel {\n\n #[system_desc(event_channel_reader)]\n\n u32_reader: ReaderId<u32>,\n\n }\n\n impl SystemNamedEventChannel {\n\n fn new(u32_reader: ReaderId<u32>) -> Self {\n\n Self { u32_reader }\n\n }\n\n }\n\n\n\n impl<'s> System<'s> for SystemNamedEventChannel {\n\n type SystemData = ();\n\n fn run(&mut self, _: Self::SystemData) {}\n\n }\n\n\n\n let mut world = World::new();\n\n world.insert(EventChannel::<u32>::new());\n\n\n\n SystemNamedEventChannelDesc::default().build(&mut world);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "amethyst_derive/tests/system_desc.rs", "rank": 83, "score": 172176.47450299343 }, { "content": "#[test]\n\nfn struct_tuple_with_event_channel_reader() -> Result<(), Error> {\n\n // Expects `System` to have a `new` constructor.\n\n #[derive(Debug, SystemDesc)]\n\n #[system_desc(name(SystemTupleEventChannelDesc))]\n\n struct SystemTupleEventChannel(#[system_desc(event_channel_reader)] ReaderId<u32>);\n\n impl SystemTupleEventChannel {\n\n fn new(reader_id: ReaderId<u32>) -> Self {\n\n Self(reader_id)\n\n }\n\n }\n\n\n\n impl<'s> System<'s> for SystemTupleEventChannel {\n\n type SystemData = ();\n\n fn run(&mut self, _: Self::SystemData) {}\n\n }\n\n\n\n let mut world = World::new();\n\n world.insert(EventChannel::<u32>::new());\n\n\n\n SystemTupleEventChannelDesc::default().build(&mut world);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "amethyst_derive/tests/system_desc.rs", "rank": 84, "score": 172176.47450299343 }, { "content": "#[derive(Debug)]\n\nstruct PlanContext<B: Backend> {\n\n targets: HashMap<Target, TargetPlan<B>>,\n\n target_metadata: HashMap<Target, TargetMetadata>,\n\n passes: HashMap<Target, EvaluationState>,\n\n outputs: HashMap<TargetImage, ImageId>,\n\n graph_builder: GraphBuilder<B, World>,\n\n}\n\n\n\nimpl<B: Backend> PlanContext<B> {\n\n pub fn mark_evaluating(&mut self, target: Target) -> Result<(), Error> {\n\n match self.passes.get(&target) {\n\n None => {},\n\n Some(EvaluationState::Evaluating) => return Err(format_err!(\"Trying to evaluate {:?} render plan that is already evaluating. Circular dependency detected.\", target)),\n\n // this case is not a soft runtime error, as this should never be allowed by the API.\n\n Some(EvaluationState::Built(_)) => panic!(\"Trying to reevaluate a render plan for {:?}.\", target),\n\n };\n\n self.passes.insert(target, EvaluationState::Evaluating);\n\n Ok(())\n\n }\n\n\n", "file_path": "amethyst_rendy/src/bundle.rs", "rank": 85, "score": 171730.91671974584 }, { "content": "#[derive(derivative::Derivative)]\n\n#[derivative(Debug(bound = \"\"))]\n\nstruct TargetPlan<B: Backend> {\n\n key: Target,\n\n #[derivative(Debug = \"ignore\")]\n\n extensions: Vec<Box<dyn FnOnce(&mut TargetPlanContext<'_, B>) -> Result<(), Error> + 'static>>,\n\n outputs: Option<TargetPlanOutputs<B>>,\n\n}\n\n\n\nimpl<B: Backend> TargetPlan<B> {\n\n fn new(key: Target) -> Self {\n\n Self {\n\n key,\n\n extensions: vec![],\n\n outputs: None,\n\n }\n\n }\n\n\n\n // safety:\n\n // * `physical_device` must be created from same `Instance` as the `Surface` present in output\n\n unsafe fn metadata(&self, physical_device: &B::PhysicalDevice) -> Option<TargetMetadata> {\n\n self.outputs\n", "file_path": "amethyst_rendy/src/bundle.rs", "rank": 86, "score": 171730.77977468498 }, { "content": "fn impl_constructor(context: &Context<'_>) -> TokenStream {\n\n let Context {\n\n ref system_desc_name,\n\n ref impl_generics,\n\n ref ty_generics,\n\n ref where_clause,\n\n ref is_default,\n\n ..\n\n } = context;\n\n\n\n let constructor_parameters = impl_constructor_parameters(context);\n\n let constructor_body = impl_constructor_body(context);\n\n\n\n if *is_default {\n\n quote! {\n\n impl #impl_generics ::std::default::Default for #system_desc_name #ty_generics\n\n #where_clause\n\n {\n\n fn default() -> Self {\n\n #constructor_body\n", "file_path": "amethyst_derive/src/system_desc.rs", "rank": 87, "score": 171254.16574481793 }, { "content": "/// Combines an iterator of descriptor information in tuple form into a `DescriptorSetLayoutBinding`\n\n/// # Limitations\n\n/// * All descriptors are created as single count and immutable_samplers is false.\n\npub fn set_layout_bindings(\n\n bindings: impl IntoIterator<Item = (u32, pso::DescriptorType, pso::ShaderStageFlags)>,\n\n) -> Vec<pso::DescriptorSetLayoutBinding> {\n\n bindings\n\n .into_iter()\n\n .flat_map(|(times, ty, stage_flags)| (0..times).map(move |_| (ty, stage_flags)))\n\n .enumerate()\n\n .map(\n\n |(binding, (ty, stage_flags))| pso::DescriptorSetLayoutBinding {\n\n binding: binding as u32,\n\n ty,\n\n count: 1,\n\n stage_flags,\n\n immutable_samplers: false,\n\n },\n\n )\n\n .collect()\n\n}\n\n\n\n/// Helper forward lookup struct using `FnvHashMap`\n", "file_path": "amethyst_rendy/src/util.rs", "rank": 88, "score": 171165.78091993422 }, { "content": "pub fn load_mesh(\n\n mesh: &gltf::Mesh<'_>,\n\n buffers: &Buffers,\n\n options: &GltfSceneOptions,\n\n) -> Result<Vec<(MeshBuilder<'static>, Option<usize>, Range<[f32; 3]>)>, Error> {\n\n trace!(\"Loading mesh\");\n\n let mut primitives = vec![];\n\n\n\n for primitive in mesh.primitives() {\n\n trace!(\"Loading mesh primitive\");\n\n let reader = primitive.reader(|buffer| buffers.buffer(&buffer));\n\n let mut builder = MeshBuilder::new();\n\n\n\n trace!(\"Loading indices\");\n\n use gltf::mesh::util::ReadIndices;\n\n let indices = match reader.read_indices() {\n\n Some(ReadIndices::U8(iter)) => Indices::U16(iter.map(u16::from).collect()),\n\n Some(ReadIndices::U16(iter)) => Indices::U16(iter.collect()),\n\n Some(ReadIndices::U32(iter)) => Indices::U32(iter.collect()),\n\n None => Indices::None,\n", "file_path": "amethyst_gltf/src/format/mesh.rs", "rank": 89, "score": 171165.78091993422 }, { "content": "pub fn load_skin(\n\n skin: &gltf::Skin<'_>,\n\n buffers: &Buffers,\n\n skin_entity: usize,\n\n node_map: &HashMap<usize, usize>,\n\n meshes: Vec<usize>,\n\n prefab: &mut Prefab<GltfPrefab>,\n\n) -> Result<(), Error> {\n\n let joints = skin\n\n .joints()\n\n .map(|j| {\n\n node_map.get(&j.index()).cloned().expect(\n\n \"Unreachable: `node_map` is initialized with the indexes from the `Gltf` object\",\n\n )\n\n })\n\n .collect::<Vec<_>>();\n\n\n\n let reader = skin.reader(|buffer| buffers.buffer(&buffer));\n\n\n\n let inverse_bind_matrices = reader\n", "file_path": "amethyst_gltf/src/format/skin.rs", "rank": 90, "score": 171165.78091993422 }, { "content": "pub fn load_animations(\n\n gltf: &gltf::Gltf,\n\n buffers: &Buffers,\n\n node_map: &HashMap<usize, usize>,\n\n) -> Result<AnimationSetPrefab<usize, Transform>, Error> {\n\n let mut prefab = AnimationSetPrefab::default();\n\n for animation in gltf.animations() {\n\n let anim = load_animation(&animation, buffers)?;\n\n if anim\n\n .samplers\n\n .iter()\n\n .any(|sampler| node_map.contains_key(&sampler.0))\n\n {\n\n prefab.animations.push((animation.index(), anim));\n\n }\n\n }\n\n Ok(prefab)\n\n}\n\n\n", "file_path": "amethyst_gltf/src/format/animation.rs", "rank": 91, "score": 171165.78091993422 }, { "content": "/// Helper function which takes an iterator of tuple-stored vertex buffer descriptions and writes\n\n/// into `VertexBufferDesc` and `AttributeDesc` collections.\n\npub fn push_vertex_desc(\n\n (elements, stride, rate): (\n\n impl IntoIterator<Item = pso::Element<format::Format>>,\n\n pso::ElemStride,\n\n pso::VertexInputRate,\n\n ),\n\n mut location: pso::Location,\n\n vertex_buffers: &mut Vec<pso::VertexBufferDesc>,\n\n attributes: &mut Vec<pso::AttributeDesc>,\n\n) {\n\n let index = vertex_buffers.len() as pso::BufferIndex;\n\n vertex_buffers.push(pso::VertexBufferDesc {\n\n binding: index,\n\n stride,\n\n rate,\n\n });\n\n\n\n for element in elements.into_iter() {\n\n attributes.push(pso::AttributeDesc {\n\n location,\n\n binding: index,\n\n element,\n\n });\n\n location += 1;\n\n }\n\n}\n\n\n\n/// Helper function to create a `DescriptorSetWrite` from arguments\n", "file_path": "amethyst_rendy/src/util.rs", "rank": 92, "score": 171165.78091993422 }, { "content": "// Load a single material, and transform into a format usable by the engine\n\npub fn load_material(\n\n material: &gltf::Material<'_>,\n\n buffers: &Buffers,\n\n source: Arc<dyn Source>,\n\n name: &str,\n\n) -> Result<MaterialPrefab, Error> {\n\n let mut prefab = MaterialPrefab::default();\n\n\n\n let pbr = material.pbr_metallic_roughness();\n\n\n\n prefab.albedo = Some(\n\n load_texture_with_factor(\n\n pbr.base_color_texture(),\n\n pbr.base_color_factor(),\n\n buffers,\n\n source.clone(),\n\n name,\n\n true,\n\n )\n\n .map(|(texture, _)| TexturePrefab::Data(texture.into()))?,\n", "file_path": "amethyst_gltf/src/format/material.rs", "rank": 93, "score": 171165.78091993422 }, { "content": "#[derive(Debug)]\n\nstruct SlottedBuffer<B: Backend> {\n\n buffer: Escape<Buffer<B>>,\n\n elem_size: u64,\n\n}\n\n\n\nimpl<B: Backend> SlottedBuffer<B> {\n\n fn new(\n\n factory: &Factory<B>,\n\n elem_size: u64,\n\n capacity: usize,\n\n usage: hal::buffer::Usage,\n\n ) -> Result<Self, failure::Error> {\n\n Ok(Self {\n\n buffer: factory.create_buffer(\n\n BufferInfo {\n\n size: elem_size * (capacity as u64),\n\n usage,\n\n },\n\n rendy::memory::Dynamic,\n\n )?,\n", "file_path": "amethyst_rendy/src/submodules/material.rs", "rank": 94, "score": 169878.11616433127 }, { "content": "pub fn get_image_data(\n\n image: &gltf::Image<'_>,\n\n buffers: &Buffers,\n\n source: Arc<dyn AssetSource>,\n\n base_path: &Path,\n\n) -> Result<(Vec<u8>, ImageFormat), Error> {\n\n use gltf::image::Source;\n\n match image.source() {\n\n Source::View { view, mime_type } => {\n\n let data = buffers\n\n .view(&view)\n\n .expect(\"`view` of image data points to a buffer which does not exist\");\n\n Ok((data.to_vec(), ImageFormat::from_mime_type(mime_type)))\n\n }\n\n\n\n Source::Uri { uri, mime_type } => {\n\n if uri.starts_with(\"data:\") {\n\n let data = parse_data_uri(uri)?;\n\n if let Some(ty) = mime_type {\n\n Ok((data, ImageFormat::from_mime_type(ty)))\n", "file_path": "amethyst_gltf/src/format/importer.rs", "rank": 95, "score": 169323.15003236826 }, { "content": "fn impl_constructor_body(context: &Context<'_>) -> TokenStream {\n\n let Context {\n\n ref system_desc_name,\n\n ref system_desc_fields,\n\n ..\n\n } = context;\n\n\n\n let fields = &system_desc_fields.fields;\n\n match fields {\n\n Fields::Unit => quote!(#system_desc_name),\n\n Fields::Unnamed(fields_unnamed) => {\n\n let field_initializers = fields_unnamed\n\n .unnamed\n\n .iter()\n\n .map(|field| {\n\n if field.is_phantom_data() {\n\n quote!(::std::marker::PhantomData)\n\n } else {\n\n let type_name_snake = snake_case(field);\n\n quote!(#type_name_snake)\n", "file_path": "amethyst_derive/src/system_desc.rs", "rank": 96, "score": 168772.40484467172 }, { "content": "fn impl_constructor_parameters(context: &Context<'_>) -> TokenStream {\n\n let Context {\n\n ref system_desc_fields,\n\n ..\n\n } = context;\n\n\n\n let fields = &system_desc_fields.fields;\n\n match fields {\n\n Fields::Unit => quote!(),\n\n Fields::Unnamed(fields_unnamed) => {\n\n let constructor_parameters = fields_unnamed\n\n .unnamed\n\n .iter()\n\n .filter(|field| !field.is_phantom_data())\n\n .map(|field| {\n\n let type_name_snake = snake_case(field);\n\n let field_type = &field.ty;\n\n quote!(#type_name_snake: #field_type)\n\n })\n\n .collect::<Vec<TokenStream>>();\n", "file_path": "amethyst_derive/src/system_desc.rs", "rank": 97, "score": 168772.40484467172 }, { "content": "/// A bundle of ECS components, resources and systems.\n\npub trait SystemBundle<'a, 'b> {\n\n /// Build and add ECS resources, register components, add systems etc to the Application.\n\n fn build(\n\n self,\n\n world: &mut World,\n\n dispatcher: &mut DispatcherBuilder<'a, 'b>,\n\n ) -> Result<(), Error>;\n\n}\n", "file_path": "amethyst_core/src/bundle.rs", "rank": 98, "score": 168449.2617790585 }, { "content": "struct PluggableRenderGraphCreator<B: Backend> {\n\n plugins: Vec<Box<dyn RenderPlugin<B>>>,\n\n}\n\n\n\nimpl<B: Backend> GraphCreator<B> for PluggableRenderGraphCreator<B> {\n\n fn rebuild(&mut self, world: &World) -> bool {\n\n let mut rebuild = false;\n\n for plugin in self.plugins.iter_mut() {\n\n rebuild = plugin.should_rebuild(world) || rebuild;\n\n }\n\n rebuild\n\n }\n\n\n\n fn builder(&mut self, factory: &mut Factory<B>, world: &World) -> GraphBuilder<B, World> {\n\n if self.plugins.is_empty() {\n\n log::warn!(\"RenderingBundle is configured to display nothing. Use `with_plugin` to add functionality.\");\n\n }\n\n\n\n let mut plan = RenderPlan::new();\n\n for plugin in self.plugins.iter_mut() {\n\n plugin.on_plan(&mut plan, factory, world).unwrap();\n\n }\n\n plan.build(factory).unwrap()\n\n }\n\n}\n\n\n", "file_path": "amethyst_rendy/src/bundle.rs", "rank": 99, "score": 168085.6588830818 } ]
Rust
src/connectivity/network/testing/netemul/runner/test/netstack_intermediary/src/main.rs
yanyushr/fuchsia
98e70672a81a206d235503e398f37b7b65581f79
#![feature(async_await, await_macro, futures_api)] use { ethernet, failure::{bail, format_err, Error, ResultExt}, fidl_fuchsia_hardware_ethernet::{DeviceMarker, DeviceProxy}, fidl_fuchsia_hardware_ethertap::{ TapControlMarker, TapDeviceEvent, TapDeviceMarker, TapDeviceProxy, }, fidl_fuchsia_netemul_network::{EndpointManagerMarker, NetworkContextMarker}, fidl_fuchsia_netstack::{InterfaceConfig, IpAddressConfig, NetstackMarker}, fuchsia_async as fasync, fuchsia_component::client, fuchsia_vfs_watcher::{WatchEvent, Watcher}, fuchsia_zircon as zx, futures::TryStreamExt, std::fs::File, std::path::Path, std::str, structopt::StructOpt, }; #[derive(StructOpt, Debug)] struct Opt { #[structopt(long = "mock_guest")] is_mock_guest: bool, #[structopt(long = "server")] is_server: bool, #[structopt(long)] endpoint_name: Option<String>, } const DEFAULT_METRIC: u32 = 100; const ETHERTAP_PATH: &'static str = "/dev/misc/tapctl"; const ETHERNET_DIR: &'static str = "/dev/class/ethernet"; const TAP_MAC: [u8; 6] = [12, 1, 2, 3, 4, 5]; async fn open_ethertap() -> Result<TapDeviceProxy, Error> { let (tapctl, tapctl_server) = fidl::endpoints::create_proxy::<TapControlMarker>()?; fdio::service_connect(ETHERTAP_PATH, tapctl_server.into_channel())?; let (tap, tap_server) = fidl::endpoints::create_proxy::<TapDeviceMarker>()?; let status = await!(tapctl.open_device( "benchmarks", &mut fidl_fuchsia_hardware_ethertap::Config { options: fidl_fuchsia_hardware_ethertap::OPT_ONLINE | fidl_fuchsia_hardware_ethertap::OPT_TRACE, features: 0, mtu: 1500, mac: fidl_fuchsia_hardware_ethernet::MacAddress { octets: TAP_MAC }, }, tap_server ))?; let status = zx::Status::from_raw(status); if status != zx::Status::OK { return Err(format_err!("Open device failed with {}", status)); } Ok(tap) } async fn open_ethernet() -> Result<(DeviceProxy, String), Error> { let root = Path::new(ETHERNET_DIR); let mut watcher = Watcher::new(&File::open(root)?)?; while let Some(fuchsia_vfs_watcher::WatchMessage { event, filename }) = await!(watcher.try_next()).context("watching ethernet dir")? { match event { WatchEvent::ADD_FILE | WatchEvent::EXISTING => { let (eth, eth_server) = fidl::endpoints::create_proxy::<DeviceMarker>()?; let eth_path = root.join(filename); let eth_path = eth_path.as_path().to_str().unwrap(); let () = fdio::service_connect(eth_path, eth_server.into_channel())?; let info = await!(eth.get_info())?; if info.mac.octets == TAP_MAC { return Ok((eth, eth_path.to_string())); } } _ => {} } } Err(format_err!("Directory watch ended unexpectedly")) } async fn run_mock_guest() -> Result<(), Error> { let tap = await!(open_ethertap())?; let (eth_device, device_path) = await!(open_ethernet())?; let eth_marker = fidl::endpoints::ClientEnd::new(eth_device.into_channel().unwrap().into_zx_channel()); let netstack = client::connect_to_service::<NetstackMarker>()?; let ip_addr_config = IpAddressConfig::Dhcp(true); let mut cfg = InterfaceConfig { name: "eth-test".to_string(), ip_address_config: ip_addr_config, metric: DEFAULT_METRIC, }; let _nicid = await!(netstack.add_ethernet_device(device_path.as_str(), &mut cfg, eth_marker))?; let echo_string = String::from("hello"); tap.set_online(true)?; tap.write_frame(&mut echo_string.clone().into_bytes().drain(0..))?; println!("To Server: {}", echo_string); let mut tap_events = tap.take_event_stream(); while let Some(event) = await!(tap_events.try_next())? { match event { TapDeviceEvent::OnFrame { data } => { let server_string = str::from_utf8(&data)?; assert!( echo_string == server_string, "Server reply ({}) did not match client message ({})", server_string, echo_string ); println!("From Server: {}", server_string); break; } _ => continue, } } Ok(()) } async fn run_echo_server(ep_name: String) -> Result<(), Error> { let netctx = client::connect_to_service::<NetworkContextMarker>()?; let (epm, epm_server_end) = fidl::endpoints::create_proxy::<EndpointManagerMarker>()?; netctx.get_endpoint_manager(epm_server_end)?; let ep = await!(epm.get_endpoint(&ep_name))?; let ep = match ep { Some(ep) => ep.into_proxy().unwrap(), None => bail!(format_err!("Can't find endpoint {}", &ep_name)), }; let vmo = zx::Vmo::create_with_opts( zx::VmoOptions::NON_RESIZABLE, 256 * ethernet::DEFAULT_BUFFER_SIZE as u64, )?; let eth_dev = await!(ep.get_ethernet_device())?; let eth_proxy = match eth_dev.into_proxy() { Ok(proxy) => proxy, _ => bail!("Could not get ethernet proxy"), }; let mut eth_client = await!(ethernet::Client::new(eth_proxy, vmo, ethernet::DEFAULT_BUFFER_SIZE, &ep_name))?; await!(eth_client.start())?; let mut eth_events = eth_client.get_stream(); let mut sent_response = false; while let Some(event) = await!(eth_events.try_next())? { match event { ethernet::Event::Receive(rx, _flags) => { if !sent_response { let mut data: [u8; 100] = [0; 100]; rx.read(&mut data); let user_message = str::from_utf8(&data[0..rx.len()]).unwrap(); println!("From client: {}", user_message); eth_client.send(&data[0..rx.len()]); sent_response = true; await!(eth_client.tx_listen_start())?; } else { break; } } _ => { continue; } } } Ok(()) } async fn do_run(opt: Opt) -> Result<(), Error> { if opt.is_mock_guest { await!(run_mock_guest())?; } else if opt.is_server { match opt.endpoint_name { Some(endpoint_name) => { await!(run_echo_server(endpoint_name))?; } None => { bail!("Must provide endpoint_name for server"); } } } Ok(()) } fn main() -> Result<(), Error> { let opt = Opt::from_args(); let mut executor = fasync::Executor::new().context("Error creating executor")?; executor.run_singlethreaded(do_run(opt))?; return Ok(()); }
#![feature(async_await, await_macro, futures_api)] use { ethernet, failure::{bail, format_err, Error, ResultExt}, fidl_fuchsia_hardware_ethernet::{DeviceMarker, DeviceProxy}, fidl_fuchsia_hardware_ethertap::{ TapControlMarker, TapDeviceEvent, TapDeviceMarker, TapDeviceProxy, }, fidl_fuchsia_netemul_network::{EndpointManagerMarker, NetworkContextMarker}, fidl_fuchsia_netstack::{InterfaceConfig, IpAddressConfig, NetstackMarker}, fuchsia_async as fasync, fuchsia_component::client, fuchsia_vfs_watcher::{WatchEvent, Watcher}, fuchsia_zircon as zx, futures::TryStreamExt, std::fs::File, std::path::Path, std::str, structopt::StructOpt, }; #[derive(StructOpt, Debug)] struct Opt { #[structopt(long = "mock_guest")] is_mock_guest: bool, #[structopt(long = "server")] is_server: bool, #[structopt(long)] endpoint_name: Option<String>, } const DEFAULT_METRIC: u32 = 100; const ETHERTAP_PATH: &'static str = "/dev/misc/tapctl"; const ETHERNET_DIR: &'static str = "/dev/class/ethernet"; const TAP_MAC: [u8; 6] = [12, 1, 2, 3, 4, 5]; async fn open_ethertap() -> Result<TapDeviceProxy, Error> { let (tapctl, tapctl_server) = fidl::endpoints::create_proxy::<TapControlMarker>()?; fdio::service_connect(ETHERTAP_PATH, tapctl_server.into_channel())?; let (tap, tap_server) = fidl::endpoints::create_proxy::<TapDeviceMarker>()?; let status = await!(tapctl.open_device( "benchmarks", &mut fidl_fuchsia_hardware_ethertap::Config { options: fidl_fuchsia_hardware_ethertap::OPT_ONLINE | fidl_fuchsia_hardware_ethertap::OPT_TRACE, features: 0, mtu: 1500, mac: fidl_fuchsia_hardware_ethernet::MacAddress { octets: TAP_MAC }, }, tap_server ))?; let status = zx::Status::from_raw(status); if status != zx::Status::OK { return Err(format_err!("Open device failed with {}", status)); } Ok(tap) } async fn open_ethernet() -> Result<(DeviceProxy, String), Error> { let root = Path::new(ETHERNET_DIR); let mut watcher = Watcher::new(&File::open(root)?)?; while let Some(fuchsia_vfs_watcher::WatchMessage { event, filename }) = await!(watcher.try_next()).context("watching ethernet dir")? { match event { WatchEvent::ADD_FILE | WatchEvent::EXISTING => { let (eth, eth_server) = fidl::endpoints::create_proxy::<DeviceMarker>()?; let eth_path = root.join(filename); let eth_path = eth_path.as_path().to_str().unwrap(); let () = fdio::service_connect(eth_path, eth_server.into_channel())?; let info = await!(eth.get_info())?; if info.mac.octets == TAP_MAC { return Ok((eth, eth_path.to_string())); } } _ => {} } } Err(format_err!("Directory watch ended unexpectedly")) } async fn run_mock_guest() -> Result<(), Error> { let tap = await!(open_ethertap())?; let (eth_device, device_path) = await!(open_ethernet())?;
o_string.clone().into_bytes().drain(0..))?; println!("To Server: {}", echo_string); let mut tap_events = tap.take_event_stream(); while let Some(event) = await!(tap_events.try_next())? { match event { TapDeviceEvent::OnFrame { data } => { let server_string = str::from_utf8(&data)?; assert!( echo_string == server_string, "Server reply ({}) did not match client message ({})", server_string, echo_string ); println!("From Server: {}", server_string); break; } _ => continue, } } Ok(()) } async fn run_echo_server(ep_name: String) -> Result<(), Error> { let netctx = client::connect_to_service::<NetworkContextMarker>()?; let (epm, epm_server_end) = fidl::endpoints::create_proxy::<EndpointManagerMarker>()?; netctx.get_endpoint_manager(epm_server_end)?; let ep = await!(epm.get_endpoint(&ep_name))?; let ep = match ep { Some(ep) => ep.into_proxy().unwrap(), None => bail!(format_err!("Can't find endpoint {}", &ep_name)), }; let vmo = zx::Vmo::create_with_opts( zx::VmoOptions::NON_RESIZABLE, 256 * ethernet::DEFAULT_BUFFER_SIZE as u64, )?; let eth_dev = await!(ep.get_ethernet_device())?; let eth_proxy = match eth_dev.into_proxy() { Ok(proxy) => proxy, _ => bail!("Could not get ethernet proxy"), }; let mut eth_client = await!(ethernet::Client::new(eth_proxy, vmo, ethernet::DEFAULT_BUFFER_SIZE, &ep_name))?; await!(eth_client.start())?; let mut eth_events = eth_client.get_stream(); let mut sent_response = false; while let Some(event) = await!(eth_events.try_next())? { match event { ethernet::Event::Receive(rx, _flags) => { if !sent_response { let mut data: [u8; 100] = [0; 100]; rx.read(&mut data); let user_message = str::from_utf8(&data[0..rx.len()]).unwrap(); println!("From client: {}", user_message); eth_client.send(&data[0..rx.len()]); sent_response = true; await!(eth_client.tx_listen_start())?; } else { break; } } _ => { continue; } } } Ok(()) } async fn do_run(opt: Opt) -> Result<(), Error> { if opt.is_mock_guest { await!(run_mock_guest())?; } else if opt.is_server { match opt.endpoint_name { Some(endpoint_name) => { await!(run_echo_server(endpoint_name))?; } None => { bail!("Must provide endpoint_name for server"); } } } Ok(()) } fn main() -> Result<(), Error> { let opt = Opt::from_args(); let mut executor = fasync::Executor::new().context("Error creating executor")?; executor.run_singlethreaded(do_run(opt))?; return Ok(()); }
let eth_marker = fidl::endpoints::ClientEnd::new(eth_device.into_channel().unwrap().into_zx_channel()); let netstack = client::connect_to_service::<NetstackMarker>()?; let ip_addr_config = IpAddressConfig::Dhcp(true); let mut cfg = InterfaceConfig { name: "eth-test".to_string(), ip_address_config: ip_addr_config, metric: DEFAULT_METRIC, }; let _nicid = await!(netstack.add_ethernet_device(device_path.as_str(), &mut cfg, eth_marker))?; let echo_string = String::from("hello"); tap.set_online(true)?; tap.write_frame(&mut ech
random
[]
Rust
crate2nix/src/prefetch.rs
alyssais/crate2nix
049897e466ff326945a17303ed4585868cc65b35
use std::io::Write; use std::process::Command; use crate::resolve::{CrateDerivation, CratesIoSource, GitSource, ResolvedSource}; use crate::GenerateConfig; use cargo_metadata::PackageId; use failure::bail; use failure::format_err; use failure::Error; use serde::Deserialize; use std::collections::{BTreeMap, HashMap}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum HashSource { Prefetched, CargoLock, } #[derive(Debug, Clone, PartialEq, Eq)] struct HashWithSource { sha256: String, source: HashSource, } #[derive(Debug)] struct SourcePrefetchBundle<'a> { source: &'a ResolvedSource, packages: &'a Vec<&'a CrateDerivation>, hash: Option<HashWithSource>, } pub fn prefetch( config: &GenerateConfig, from_lock_file: &HashMap<PackageId, String>, crate_derivations: &[CrateDerivation], ) -> Result<BTreeMap<PackageId, String>, Error> { let hashes_string: String = if config.read_crate_hashes { std::fs::read_to_string(&config.crate_hashes_json).unwrap_or_else(|_| "{}".to_string()) } else { "{}".to_string() }; let old_prefetched_hashes: BTreeMap<PackageId, String> = serde_json::from_str(&hashes_string)?; let mut hashes = BTreeMap::<PackageId, String>::new(); let packages_by_source: HashMap<ResolvedSource, Vec<&CrateDerivation>> = { let mut index = HashMap::new(); for package in crate_derivations { index .entry(package.source.without_sha256()) .or_insert_with(Vec::new) .push(package); } index }; let prefetchable_sources: Vec<SourcePrefetchBundle> = packages_by_source .iter() .filter(|(source, _)| source.needs_prefetch()) .map(|(source, packages)| { let hash = packages .iter() .filter_map(|p| { from_lock_file .get(&p.package_id) .map(|hash| HashWithSource { sha256: hash.clone(), source: HashSource::CargoLock, }) .or_else(|| { old_prefetched_hashes .get(&p.package_id) .map(|hash| HashWithSource { sha256: hash.clone(), source: HashSource::Prefetched, }) }) }) .next(); SourcePrefetchBundle { source, packages, hash, } }) .collect(); let without_hash_num = prefetchable_sources .iter() .filter(|SourcePrefetchBundle { hash, .. }| hash.is_none()) .count(); let mut idx = 1; for SourcePrefetchBundle { source, packages, hash, } in prefetchable_sources { let (sha256, hash_source) = if let Some(HashWithSource { sha256, source }) = hash { (sha256.trim().to_string(), source) } else { eprintln!( "Prefetching {:>4}/{}: {}", idx, without_hash_num, source.to_string() ); idx += 1; (source.prefetch()?, HashSource::Prefetched) }; for package in packages { if hash_source == HashSource::Prefetched { hashes.insert(package.package_id.clone(), sha256.clone()); } } } if hashes != old_prefetched_hashes { std::fs::write( &config.crate_hashes_json, serde_json::to_vec_pretty(&hashes)?, ) .map_err(|e| { format_err!( "while writing hashes to {}: {}", config.crate_hashes_json.to_str().unwrap_or("<unknown>"), e ) })?; eprintln!( "Wrote hashes to {}.", config.crate_hashes_json.to_string_lossy() ); } Ok(hashes) } fn get_command_output(cmd: &str, args: &[&str]) -> Result<String, Error> { let output = Command::new(cmd) .args(args) .output() .map_err(|e| format_err!("While spawning '{} {}': {}", cmd, args.join(" "), e))?; if !output.status.success() { std::io::stdout().write_all(&output.stdout)?; std::io::stderr().write_all(&output.stderr)?; bail!( "{}\n=> exited with: {}", cmd, output.status.code().unwrap_or(-1) ); } String::from_utf8(output.stdout) .map(|s| s.trim().to_string()) .map_err(|_e| format_err!("output of '{} {}' is not UTF8!", cmd, args.join(" "))) } trait PrefetchableSource: ToString { fn needs_prefetch(&self) -> bool; fn prefetch(&self) -> Result<String, Error>; } impl ResolvedSource { fn inner_prefetchable(&self) -> Option<&dyn PrefetchableSource> { match self { ResolvedSource::CratesIo(source) => Some(source), ResolvedSource::Git(source) => Some(source), _ => None, } } } impl PrefetchableSource for ResolvedSource { fn needs_prefetch(&self) -> bool { self.inner_prefetchable() .map(|s| s.needs_prefetch()) .unwrap_or(false) } fn prefetch(&self) -> Result<String, Error> { self.inner_prefetchable() .map(|s| s.prefetch()) .unwrap_or_else(|| Err(format_err!("source does not support prefetch: {:?}", self))) } } impl PrefetchableSource for CratesIoSource { fn needs_prefetch(&self) -> bool { self.sha256.is_none() } fn prefetch(&self) -> Result<String, Error> { let args = &[ &self.url(), "--name", &format!("{}-{}", self.name, self.version), ]; get_command_output("nix-prefetch-url", args) } } impl PrefetchableSource for GitSource { fn needs_prefetch(&self) -> bool { self.sha256.is_none() } fn prefetch(&self) -> Result<String, Error> { #[derive(Deserialize)] struct NixPrefetchGitInfo { sha256: String, } let mut args = vec![ "--url", self.url.as_str(), "--fetch-submodules", "--rev", &self.rev, ]; if let Some(r#ref) = self.r#ref.as_ref() { args.extend_from_slice(&["--branch-name", r#ref]); } let json = get_command_output("nix-prefetch-git", &args)?; let prefetch_info: NixPrefetchGitInfo = serde_json::from_str(&json)?; Ok(prefetch_info.sha256) } }
use std::io::Write; use std::process::Command; use crate::resolve::{CrateDerivation, CratesIoSource, GitSource, ResolvedSource}; use crate::GenerateConfig; use cargo_metadata::PackageId; use failure::bail; use failure::format_err; use failure::Error; use serde::Deserialize; use std::collections::{BTreeMap, HashMap}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum HashSource { Prefetched, CargoLock, } #[derive(Debug, Clone, PartialEq, Eq)] struct HashWithSource { sha256: String, source: HashSource, } #[derive(Debug)] struct SourcePrefetchBundle<'a> { source: &'a ResolvedSource, packages: &'a Vec<&'a CrateDerivation>, hash: Option<HashWithSource>, } pub fn prefetch( config: &GenerateConfig, from_lock_file: &HashMap<PackageId, String>, crate_derivations: &[CrateDerivation], ) -> Result<BTreeMap<PackageId, String>, Error> { let hashes_string: String = if config.read_crate_hashes { std::fs::read_to_string(&config.crate_hashes_json).unwrap_or_else(|_| "{}".to_string()) } else { "{}".to_string() }; let old_prefetched_hashes: BTreeMap<PackageId, String> = serde_json::from_str(&hashes_string)?; let mut hashes = BTreeMap::<PackageId, String>::new(); let packages_by_source: HashMap<ResolvedSource, Vec<&CrateDerivation>> = { let mut index = HashMap::new(); for package in crate_derivations { index .entry(package.source.without_sha256()) .or_insert_with(Vec::new) .push(package); } index }; let prefetchable_sources: Vec<SourcePrefetchBundle> = packages_by_source .iter() .filter(|(source, _)| source.needs_prefetch()) .map(|(source, packages)| { let hash = packages .iter() .filter_map(|p| { from_lock_file .get(&p.package_id) .map(|hash| HashWithSource { sha256: hash.clone(), source: HashSource::CargoLock, }) .or_else(|| { old_prefetched_hashes .get(&p.package_id) .map(|hash| HashWithSource { sha256: hash.clone(), source: HashSource::Prefetched, }) }) }) .next(); SourcePrefetchBundle { source, packages, hash, } }) .collect(); let without_hash_num = prefetchable_sources .iter() .filter(|SourcePrefetchBundle { hash, .. }| hash.is_none()) .count(); let mut idx = 1; for SourcePrefetchBundle { source, packages, hash, } in prefetchable_sources { let (sha256, hash_source) = if let Some(HashWithSource { sha256, source }) = hash { (sha256.trim().to_string(), source) } else { eprintln!( "Prefetching {:>4}/{}: {}", idx, without_hash_num, source.to_string() ); idx += 1; (source.prefetch()?, HashSource::Prefetched) }; for package in packages { if hash_source == HashSource::Prefetched { hashes.insert(package.package_id.clone(), sha256.clone()); } } } if hashes != old_prefetched_hashes { std::fs::write( &config.crate_hashes_json, serde_json::to_vec_pretty(&hashes)?, ) .map_err(|e| { format_err!( "while writing hashes to {}: {}", config.crate_hashes_json.to_str().unwrap_or("<unknown>"), e ) })?; eprintln!( "Wrote hashes to {}.", config.crate_hashes_json.to_string_lossy() ); } Ok(hashes) } fn get_command_output(cmd: &str, args: &[&str]) -> Result<String, Error> { let output = Command::new(cmd) .args(args) .output() .map_err(|e| format_err!("While spawning '{} {}': {}", cmd, args.join(" "), e))?; if !output.status.success() { std::io::stdout().write_all(&output.stdout)?; std::io::stderr().write_all(&output.stderr)?; bail!( "{}\n=> exited with: {}", cmd, output.status.code().unwrap_or(-1) ); } String::from_utf8(output.stdout) .map(|s| s.trim().to_string()) .map_err(|_e| format_err!("output of '{} {}' is not UTF8!", cmd, args.join(" "))) } trait PrefetchableSource: ToString { fn needs_prefetch(&self) -> bool; fn prefetch(&self) -> Result<String, Error>; } impl ResolvedSource { fn inner_prefetchable(&self) -> Option<&dyn PrefetchableSource> { match self { ResolvedSource::CratesIo(source) => Some(source), ResolvedSource::Git(source) => Some(source), _ => None, } } } impl PrefetchableSource for ResolvedSource { fn needs_prefetch(&self) -> bool { self.inner_prefetchable() .map(|s| s.needs_prefetch()) .unwrap_or(false) } fn prefetch(&self) -> Result<String, Error> { self.inner_prefetchable() .map(|s| s.prefetch()) .unwrap_or_else(|| Err(format_err!("source does not support prefetch: {:?}", self))) } } impl PrefetchableSource for CratesIoSource { fn needs_prefetch(&self) -> bool { self.sha256.is_none() } fn prefetch(&self) -> Result<String, Error> { let args = &[ &self.url(), "--name", &format!("{}-{}", self.name, self.version), ]; get_command_output("nix-prefetch-url", args) } } impl PrefetchableSource for GitSource { fn needs_prefetch(&self) -> bool { self.sha256.is_none() } fn prefetch(&self) -> Result<String, Error> { #[derive(Deserialize)] struct NixPrefetchGitInfo { sha256: String, }
if let Some(r#ref) = self.r#ref.as_ref() { args.extend_from_slice(&["--branch-name", r#ref]); } let json = get_command_output("nix-prefetch-git", &args)?; let prefetch_info: NixPrefetchGitInfo = serde_json::from_str(&json)?; Ok(prefetch_info.sha256) } }
let mut args = vec![ "--url", self.url.as_str(), "--fetch-submodules", "--rev", &self.rev, ];
assignment_statement
[ { "content": "/// Run the command at the given path without arguments and capture the output in the return value.\n\npub fn run_cmd(cmd_path: impl AsRef<Path>) -> Result<String, Error> {\n\n let cmd_path = cmd_path.as_ref().to_string_lossy().to_string();\n\n let output = Command::new(&cmd_path)\n\n .output()\n\n .map_err(|e| format_err!(\"while spawning {}: {}\", cmd_path, e))?;\n\n if !output.status.success() {\n\n std::io::stdout().write_all(&output.stdout)?;\n\n std::io::stderr().write_all(&output.stderr)?;\n\n bail!(\n\n \"{}\\n=> exited with: {}\",\n\n cmd_path,\n\n output.status.code().unwrap_or(-1)\n\n );\n\n }\n\n\n\n Ok(String::from_utf8(output.stdout)\n\n .map_err(|_e| format_err!(\"output of {} is not UTF8!\", cmd_path))?)\n\n}\n", "file_path": "crate2nix/src/nix_build.rs", "rank": 1, "score": 200482.50424176198 }, { "content": "pub fn write_to_file(path: impl AsRef<Path>, contents: &str) -> Result<(), Error> {\n\n let mut output_file = File::create(&path)?;\n\n output_file.write_all(contents.as_bytes())?;\n\n println!(\n\n \"Generated {} successfully.\",\n\n path.as_ref().to_string_lossy()\n\n );\n\n Ok(())\n\n}\n\n\n\nlazy_static! {\n\n static ref TERA: Tera = {\n\n let mut tera = Tera::default();\n\n tera.add_raw_templates(vec![\n\n (\n\n \"build.nix.tera\",\n\n include_str!(\"../templates/build.nix.tera\"),\n\n ),\n\n (\n\n \"nix/crate2nix/default.nix\",\n", "file_path": "crate2nix/src/render.rs", "rank": 2, "score": 191700.67913392524 }, { "content": "/// Escapes a string as a nix string.\n\n///\n\n/// ```\n\n/// use crate2nix::render::escape_nix_string;\n\n/// assert_eq!(\"\\\"abc\\\"\", escape_nix_string(\"abc\"));\n\n/// assert_eq!(\"\\\"a\\\\\\\"bc\\\"\", escape_nix_string(\"a\\\"bc\"));\n\n/// assert_eq!(\"\\\"a$bc\\\"\", escape_nix_string(\"a$bc\"));\n\n/// assert_eq!(\"\\\"a$\\\"\", escape_nix_string(\"a$\"));\n\n/// assert_eq!(\"\\\"a\\\\${bc\\\"\", escape_nix_string(\"a${bc\"));\n\n/// ```\n\npub fn escape_nix_string(raw_string: &str) -> String {\n\n let mut ret = String::with_capacity(raw_string.len() + 2);\n\n ret.push('\"');\n\n let mut peekable_chars = raw_string.chars().peekable();\n\n while let Some(c) = peekable_chars.next() {\n\n if c == '\\\\' || c == '\"' || (c == '$' && peekable_chars.peek() == Some(&'{')) {\n\n ret.push('\\\\');\n\n }\n\n ret.push(c);\n\n }\n\n ret.push('\"');\n\n ret\n\n}\n", "file_path": "crate2nix/src/render.rs", "rank": 3, "score": 173595.7885237696 }, { "content": "pub fn hello_world(name: &str) {\n\n println!(\"Hello, {}!\", name);\n\n}\n", "file_path": "sample_projects/lib/src/lib.rs", "rank": 4, "score": 168629.01617781716 }, { "content": "pub fn hello_world(name: &str) {\n\n println!(\"Hello, {}!\", name);\n\n}\n", "file_path": "sample_workspace/lib/src/lib.rs", "rank": 5, "score": 168629.01617781716 }, { "content": "pub fn run_instantiate() -> Result<String, Error> {\n\n let output = Command::new(\"nix-instantiate\")\n\n .args(&[\n\n \"--eval\",\n\n \"--strict\",\n\n \"--json\",\n\n \"--show-trace\",\n\n \"./templates/nix/crate2nix/tests/default.nix\",\n\n ])\n\n .output()\n\n .map_err(|e| format_err!(\"while spawning nix-instantiate: {}\", e))?;\n\n if !output.status.success() {\n\n std::io::stdout().write_all(&output.stdout)?;\n\n std::io::stderr().write_all(&output.stderr)?;\n\n bail!(\n\n \"nix-instantiate\\n=> exited with: {}\",\n\n output.status.code().unwrap_or(-1)\n\n );\n\n }\n\n\n\n Ok(String::from_utf8(output.stdout)\n\n .map_err(|_e| format_err!(\"output of nix-instantiate is not UTF8!\"))?)\n\n}\n\n\n", "file_path": "crate2nix/tests/run_nix_tests.rs", "rank": 6, "score": 159705.95385088437 }, { "content": "pub fn render_build_file(metadata: &BuildInfo) -> Result<String, Error> {\n\n Ok(TERA\n\n .render(\"build.nix.tera\", &Context::from_serialize(metadata)?)\n\n .map_err(|e| {\n\n format_err!(\n\n \"while rendering default.nix: {:?}\\nMetadata: {:?}\",\n\n e,\n\n metadata\n\n )\n\n })?)\n\n}\n\n\n", "file_path": "crate2nix/src/render.rs", "rank": 8, "score": 145879.67108829308 }, { "content": "/// Call `cargo metadata` and return result.\n\nfn cargo_metadata(config: &GenerateConfig) -> Result<Metadata, Error> {\n\n let mut cmd = cargo_metadata::MetadataCommand::new();\n\n let mut other_options = config.other_metadata_options.clone();\n\n other_options.push(\"--locked\".into());\n\n cmd.manifest_path(&config.cargo_toml)\n\n .other_options(&other_options);\n\n cmd.exec().map_err(|e| {\n\n format_err!(\n\n \"while retrieving metadata about {}: {}\",\n\n &config.cargo_toml.to_string_lossy(),\n\n e\n\n )\n\n })\n\n}\n\n\n", "file_path": "crate2nix/src/lib.rs", "rank": 12, "score": 141720.7976631354 }, { "content": "/// Dump the content of the specified file with line numbers to stdout.\n\npub fn dump_with_lines(file_path: impl AsRef<Path>) -> Result<(), Error> {\n\n let file_path = file_path.as_ref().to_string_lossy().to_string();\n\n let content = std::io::BufReader::new(std::fs::File::open(&file_path)?);\n\n let stdout = std::io::stdout();\n\n let mut handle = stdout.lock();\n\n for (idx, line) in content.lines().enumerate() {\n\n writeln!(handle, \"{:>5}: {}\", idx + 1, line?)?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "crate2nix/src/nix_build.rs", "rank": 13, "score": 140110.5150393598 }, { "content": "/// Return all occurrences of each item after the first.\n\n/// ```\n\n/// use crate2nix::util::find_duplicates;\n\n/// assert_eq!(find_duplicates(Vec::<&str>::new().iter()), Vec::<&&str>::new());\n\n/// assert_eq!(find_duplicates(vec![\"a\", \"b\"].iter()), Vec::<&&str>::new());\n\n/// assert_eq!(find_duplicates(vec![\"a\", \"b\", \"a\"].iter()), vec![&\"a\"]);\n\n/// assert_eq!(find_duplicates(vec![\"a\", \"b\", \"a\", \"b\", \"a\"].iter()), vec![&\"a\", &\"b\", &\"a\"]);\n\n/// ```\n\npub fn find_duplicates<'a, T: Ord>(source: impl Iterator<Item = &'a T>) -> Vec<&'a T> {\n\n let mut seen = BTreeSet::new();\n\n source.filter(|v| !seen.insert(*v)).collect()\n\n}\n", "file_path": "crate2nix/src/util.rs", "rank": 14, "score": 133476.89055428657 }, { "content": "fn get_test_configs() -> Result<Vec<TestConfig>, Error> {\n\n let output = Command::new(\"nix\")\n\n .args(&[\"eval\", \"--json\", \"-f\", \"../tests.nix\", \"buildTestConfigs\"])\n\n .output()\n\n .map_err(|e| format_err!(\"while spawning nix: {}\", e))?;\n\n if !output.status.success() {\n\n std::io::stdout().write_all(&output.stdout)?;\n\n std::io::stderr().write_all(&output.stderr)?;\n\n bail!(\n\n \"nix-instantiate\\n=> exited with: {}\",\n\n output.status.code().unwrap_or(-1)\n\n );\n\n }\n\n\n\n let json_string = String::from_utf8(output.stdout)\n\n .map_err(|_e| format_err!(\"output of nix-instantiate is not UTF8!\"))?;\n\n\n\n Ok(serde_json::from_str(&json_string)?)\n\n}\n", "file_path": "crate2nix/tests/self_build_up_to_date.rs", "rank": 15, "score": 126492.57449210926 }, { "content": "#[derive(Debug, Serialize, Deserialize)]\n\nstruct TestConfig {\n\n name: String,\n\n #[serde(rename = \"pregeneratedBuild\")]\n\n pregenerated_build: Option<String>,\n\n}\n\n\n", "file_path": "crate2nix/tests/self_build_up_to_date.rs", "rank": 17, "score": 107418.17659827843 }, { "content": "/// Prefetch hashes when necessary.\n\nfn prefetch_and_fill_crates_sha256(\n\n config: &GenerateConfig,\n\n default_nix: &mut BuildInfo,\n\n) -> Result<(), Error> {\n\n let mut from_lock_file: HashMap<PackageId, String> =\n\n extract_hashes_from_lockfile(&config, default_nix)?;\n\n for (_package_id, hash) in from_lock_file.iter_mut() {\n\n let bytes =\n\n hex::decode(&hash).map_err(|e| format_err!(\"while decoding '{}': {}\", hash, e))?;\n\n *hash = nix_base32::to_nix_base32(&bytes);\n\n }\n\n\n\n let prefetched = prefetch::prefetch(config, &from_lock_file, &default_nix.crates)\n\n .map_err(|e| format_err!(\"while prefetching crates for calculating sha256: {}\", e))?;\n\n\n\n for package in default_nix.crates.iter_mut() {\n\n if package.source.sha256().is_none() {\n\n if let Some(hash) = prefetched\n\n .get(&package.package_id)\n\n .or_else(|| from_lock_file.get(&package.package_id))\n\n {\n\n package.source = package.source.with_sha256(hash.clone());\n\n }\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "crate2nix/src/lib.rs", "rank": 18, "score": 95222.32367235239 }, { "content": "/// Call `nix build` in the given directory on the `default.nix` in that directory.\n\npub fn nix_build(\n\n project_dir: impl AsRef<Path>,\n\n nix_attr: &str,\n\n features: &[&str],\n\n) -> Result<(), Error> {\n\n let project_dir = project_dir.as_ref().to_string_lossy().to_string();\n\n println!(\"Building {}.\", project_dir);\n\n let status = Command::new(\"nix\")\n\n .current_dir(&project_dir)\n\n .args(&[\n\n \"--show-trace\",\n\n \"build\",\n\n \"-f\",\n\n \"default.nix\",\n\n nix_attr,\n\n \"--arg\",\n\n \"rootFeatures\",\n\n ])\n\n .arg(format!(\n\n \"[ {} ]\",\n", "file_path": "crate2nix/src/nix_build.rs", "rank": 19, "score": 89727.9242948477 }, { "content": "pub fn hello_world() {\n\n println!(\"Hello, lib_and_bin!\");\n\n}\n", "file_path": "sample_projects/lib_and_bin/src/lib.rs", "rank": 20, "score": 86234.30636498216 }, { "content": "pub fn hello_world() {\n\n println!(\"Hello, lib_and_bin!\");\n\n}\n", "file_path": "sample_workspace/lib_and_bin/src/lib.rs", "rank": 21, "score": 86234.30636498216 }, { "content": "fn run_integration_tests() -> Result<(), Error> {\n\n let status = Command::new(\"nix\")\n\n .args(&[\n\n \"build\",\n\n \"-f\",\n\n \"../tests.nix\",\n\n \"--show-trace\",\n\n \"-o\",\n\n \"target/nix-result\",\n\n \"--keep-going\",\n\n ])\n\n .stdin(Stdio::null())\n\n .stdout(Stdio::inherit())\n\n .stderr(Stdio::inherit())\n\n .status()\n\n .map_err(|e| format_err!(\"while spawning nix build: {}\", e))?;\n\n if !status.success() {\n\n bail!(\"nix build\\n=> exited with: {}\", status.code().unwrap_or(-1));\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "crate2nix/tests/run_nix_tests.rs", "rank": 22, "score": 81950.25604935124 }, { "content": "fn is_ident_start(ch: char) -> bool {\n\n ch == '_' || ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z')\n\n}\n\n\n", "file_path": "crate2nix/src/target_cfg.rs", "rank": 23, "score": 81526.69541979645 }, { "content": "fn is_ident_rest(ch: char) -> bool {\n\n is_ident_start(ch) || ('0' <= ch && ch <= '9')\n\n}\n\n\n\nimpl<'a> Token<'a> {\n\n fn classify(&self) -> &str {\n\n match *self {\n\n Token::LeftParen => \"`(`\",\n\n Token::RightParen => \"`)`\",\n\n Token::Ident(..) => \"an identifier\",\n\n Token::Comma => \"`,`\",\n\n Token::Equals => \"`=`\",\n\n Token::String(..) => \"a string\",\n\n }\n\n }\n\n}\n", "file_path": "crate2nix/src/target_cfg.rs", "rank": 24, "score": 81526.69541979645 }, { "content": "/// Renders a config expression to nix code.\n\nfn cfg_to_nix_expr(cfg: &CfgExpr) -> String {\n\n fn target(target_name: &str) -> String {\n\n escape_nix_string(if target_name.starts_with(\"target_\") {\n\n &target_name[7..]\n\n } else {\n\n target_name\n\n })\n\n }\n\n\n\n fn render(result: &mut String, cfg: &CfgExpr) {\n\n match cfg {\n\n CfgExpr::Value(Cfg::Name(name)) => {\n\n result.push_str(&format!(\"target.{}\", target(name)));\n\n }\n\n CfgExpr::Value(Cfg::KeyPair(key, value)) => {\n\n let escaped_value = escape_nix_string(value);\n\n result.push_str(&if key == \"feature\" {\n\n format!(\"(builtins.elem {} features)\", escaped_value)\n\n } else {\n\n format!(\"(target.{} == {})\", target(key), escaped_value)\n", "file_path": "crate2nix/src/render.rs", "rank": 25, "score": 79542.77281336326 }, { "content": "#[test]\n\nfn self_up_to_date() {\n\n let metadata = BuildInfo::for_config(\n\n &GenerateInfo {\n\n crate2nix_arguments: vec![\n\n \"generate\",\n\n \"-n\",\n\n \"../nixpkgs.nix\",\n\n \"-f\",\n\n \"./crate2nix/Cargo.toml\",\n\n \"-o\",\n\n \"./crate2nix/Cargo.nix\",\n\n ]\n\n .iter()\n\n .map(|s| s.to_string())\n\n .collect(),\n\n ..GenerateInfo::default()\n\n },\n\n &GenerateConfig {\n\n cargo_toml: PathBuf::from(\"./Cargo.toml\"),\n\n output: PathBuf::from(\"./Cargo.nix\"),\n", "file_path": "crate2nix/tests/self_build_up_to_date.rs", "rank": 26, "score": 76635.18922699793 }, { "content": "fn extract_hashes_from_lockfile(\n\n config: &GenerateConfig,\n\n default_nix: &mut BuildInfo,\n\n) -> Result<HashMap<PackageId, String>, Error> {\n\n if !config.use_cargo_lock_checksums {\n\n return Ok(HashMap::new());\n\n }\n\n\n\n let lock_file = crate::lock::EncodableResolve::load_lock_file(\n\n &config.cargo_toml.parent().unwrap().join(\"Cargo.lock\"),\n\n )?;\n\n let hashes = lock_file\n\n .get_hashes_by_package_id()\n\n .context(\"while parsing checksums from Lockfile\")?;\n\n\n\n let mut missing_hashes = Vec::new();\n\n for package in default_nix.crates.iter_mut().filter(|c| match &c.source {\n\n ResolvedSource::CratesIo { .. } => !hashes.contains_key(&c.package_id),\n\n _ => false,\n\n }) {\n", "file_path": "crate2nix/src/lib.rs", "rank": 27, "score": 70229.78243691156 }, { "content": "#[test]\n\nfn pregenerated_up_to_date() {\n\n let test_configs = get_test_configs().expect(\"while running instantiate\");\n\n // TODO: Regenerate build files and compare\n\n for test_config in test_configs {\n\n match test_config.pregenerated_build {\n\n Some(pregenerated_build) => {\n\n let cargo_nix = PathBuf::from_str(&pregenerated_build)\n\n .expect(\"pregeneratedBuild must be valid path\");\n\n assert_up_to_date(&cargo_nix.parent().expect(\"Cargo.nix must be in directory\"));\n\n }\n\n None => println!(\"Skipping not pregenerated {}\", test_config.name),\n\n }\n\n }\n\n}\n\n\n", "file_path": "crate2nix/tests/self_build_up_to_date.rs", "rank": 28, "score": 68104.93893811431 }, { "content": "// Assert that the pregenerated build files are up to date, i.e.\n\n// the current code would result in the same build file.\n\nfn assert_up_to_date(project_dir: &Path) {\n\n let cargo_toml = project_dir.join(\"Cargo.toml\");\n\n let output = project_dir.join(\"Cargo.nix\");\n\n println!(\"Checking pregenerated {}\", output.to_str().unwrap());\n\n let config = GenerateConfig {\n\n cargo_toml: PathBuf::from(\"../\").join(cargo_toml.clone()),\n\n output: PathBuf::from(\"../\").join(output.clone()),\n\n nixpkgs_path: \"<nixpkgs>\".to_string(),\n\n crate_hashes_json: PathBuf::from(\"../\")\n\n .join(project_dir)\n\n .join(\"./crate-hashes.json\"),\n\n other_metadata_options: vec![],\n\n use_cargo_lock_checksums: true,\n\n read_crate_hashes: true,\n\n };\n\n let metadata = BuildInfo::for_config(\n\n &GenerateInfo {\n\n crate2nix_arguments: vec![\n\n \"generate\",\n\n \"-f\",\n", "file_path": "crate2nix/tests/self_build_up_to_date.rs", "rank": 29, "score": 60390.363391652005 }, { "content": "#[derive(Serialize, Deserialize, Debug, Default)]\n\nstruct Patch {\n\n unused: Vec<EncodableDependency>,\n\n}\n\n\n\npub type Metadata = BTreeMap<String, String>;\n\n\n\n#[derive(Serialize, Deserialize, Debug, PartialOrd, Ord, PartialEq, Eq)]\n\npub struct EncodableDependency {\n\n name: String,\n\n version: String,\n\n source: Option<String>,\n\n checksum: Option<String>,\n\n dependencies: Option<Vec<EncodablePackageId>>,\n\n replace: Option<EncodablePackageId>,\n\n}\n\n\n\n#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Hash, Clone)]\n\npub struct EncodablePackageId {\n\n name: String,\n\n version: Option<String>,\n", "file_path": "crate2nix/src/lock.rs", "rank": 30, "score": 56347.5333607216 }, { "content": "#[derive(PartialEq)]\n\nenum Token<'a> {\n\n LeftParen,\n\n RightParen,\n\n Ident(&'a str),\n\n Comma,\n\n Equals,\n\n String(&'a str),\n\n}\n\n\n", "file_path": "crate2nix/src/target_cfg.rs", "rank": 31, "score": 53484.604976832066 }, { "content": "/// The resolved dependencies of one package/crate.\n\nstruct ResolvedDependencies<'a> {\n\n /// The corresponding packages for the dependencies.\n\n packages: Vec<&'a Package>,\n\n /// The dependencies of the package/crate.\n\n dependencies: Vec<&'a Dependency>,\n\n}\n\n\n\nimpl<'a> ResolvedDependencies<'a> {\n\n fn new(\n\n metadata: &'a IndexedMetadata,\n\n package: &'a Package,\n\n ) -> Result<ResolvedDependencies<'a>, Error> {\n\n let node: &Node = metadata.nodes_by_id.get(&package.id).ok_or_else(|| {\n\n format_err!(\n\n \"Could not find node for {}.\\n-- Package\\n{}\",\n\n &package.id,\n\n to_string_pretty(&package).unwrap_or_else(|_| \"ERROR\".to_string())\n\n )\n\n })?;\n\n\n", "file_path": "crate2nix/src/resolve.rs", "rank": 32, "score": 52814.98169442443 }, { "content": "struct Parser<'a> {\n\n t: iter::Peekable<Tokenizer<'a>>,\n\n}\n\n\n\nimpl FromStr for Cfg {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> Result<Cfg, Error> {\n\n let mut p = Parser::new(s);\n\n let e = p.cfg()?;\n\n if p.t.next().is_some() {\n\n bail!(\"malformed cfg value or key/value pair: `{}`\", s)\n\n }\n\n Ok(e)\n\n }\n\n}\n\n\n\nimpl fmt::Display for Cfg {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match *self {\n", "file_path": "crate2nix/src/target_cfg.rs", "rank": 33, "score": 52811.63792659418 }, { "content": "struct Tokenizer<'a> {\n\n s: iter::Peekable<str::CharIndices<'a>>,\n\n orig: &'a str,\n\n}\n\n\n", "file_path": "crate2nix/src/target_cfg.rs", "rank": 34, "score": 52811.63792659418 }, { "content": "struct CommaSep<'a, T: 'a>(&'a [T]);\n\n\n\nimpl<'a, T: fmt::Display> fmt::Display for CommaSep<'a, T> {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n for (i, v) in self.0.iter().enumerate() {\n\n if i > 0 {\n\n write!(f, \", \")?;\n\n }\n\n write!(f, \"{}\", v)?;\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl<'a> Parser<'a> {\n\n fn new(s: &'a str) -> Parser<'a> {\n\n Parser {\n\n t: Tokenizer {\n\n s: s.char_indices().peekable(),\n\n orig: s,\n", "file_path": "crate2nix/src/target_cfg.rs", "rank": 35, "score": 43480.51218442281 }, { "content": "#[test]\n\nfn test_no_legacy_checksums() {\n\n let config = r#\"\n\n[[package]]\n\nname = \"aho-corasick\"\n\nversion = \"0.7.6\"\n\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n\n dependencies = [\n\n \"memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)\",\n\n ]\n\n\"#;\n\n let resolve = EncodableResolve::load_lock_string(Path::new(\"dummy\"), config).unwrap();\n\n assert_eq!(resolve.get_hashes_by_package_id().unwrap(), HashMap::new());\n\n}\n\n\n", "file_path": "crate2nix/src/lock.rs", "rank": 36, "score": 41960.21393392091 }, { "content": "#[test]\n\nfn test_some_legacy_checksums() {\n\n let config = r#\"\n\n[[package]]\n\nname = \"aho-corasick\"\n\nversion = \"0.7.6\"\n\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n\ndependencies = [\n\n \"memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)\",\n\n]\n\n\n\n[metadata]\n\n\"checksum structopt 0.2.18 (registry+https://github.com/rust-lang/crates.io-index)\" = \"16c2cdbf9cc375f15d1b4141bc48aeef444806655cd0e904207edc8d68d86ed7\"\n\n\"checksum structopt-derive 0.2.18 (registry+https://github.com/rust-lang/crates.io-index)\" = \"53010261a84b37689f9ed7d395165029f9cc7abb9f56bbfe86bee2597ed25107\"\n\n\n\n\"#;\n\n let resolve = EncodableResolve::load_lock_string(Path::new(\"dummy\"), config).unwrap();\n\n assert_eq!(\n\n resolve.get_hashes_by_package_id().unwrap(),\n\n vec![\n\n (\n", "file_path": "crate2nix/src/lock.rs", "rank": 37, "score": 41960.21393392091 }, { "content": "#[test]\n\nfn test_some_inline_checksums() {\n\n let config = r#\"\n\n[[package]]\n\nname = \"aho-corasick\"\n\nversion = \"0.7.6\"\n\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n\ndependencies = [\n\n \"memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)\",\n\n]\n\nchecksum = \"16c2cdbf9cc375f15d1b4141bc48aeef444806655cd0e904207edc8d68d86ed7\"\n\n\"#;\n\n let resolve = EncodableResolve::load_lock_string(Path::new(\"dummy\"), config).unwrap();\n\n assert_eq!(\n\n resolve.get_hashes_by_package_id().unwrap(),\n\n vec![(\n\n PackageId {\n\n repr: \"aho-corasick 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)\"\n\n .to_string()\n\n },\n\n \"16c2cdbf9cc375f15d1b4141bc48aeef444806655cd0e904207edc8d68d86ed7\"\n", "file_path": "crate2nix/src/lock.rs", "rank": 38, "score": 41960.21393392091 }, { "content": "fn main() {\n\n println!(\"Hello from numtest, world!\");\n\n}\n", "file_path": "sample_projects/numtest/src/main.rs", "rank": 39, "score": 41960.21393392091 }, { "content": "fn main() {\n\n println!(\"Hello, with_tera!\");\n\n}\n", "file_path": "sample_workspace/with_tera/src/main.rs", "rank": 40, "score": 41960.21393392091 }, { "content": "fn main() {\n\n println!(\"Hello, simple_dep!\");\n\n}\n", "file_path": "sample_projects/simple_dep/src/main.rs", "rank": 41, "score": 41021.52566724722 }, { "content": "fn cfg_to_nix_expr_filter(\n\n value: &tera::Value,\n\n _args: &HashMap<String, tera::Value>,\n\n) -> tera::Result<tera::Value> {\n\n match value {\n\n tera::Value::String(key) => {\n\n if key.starts_with(\"cfg(\") && key.ends_with(')') {\n\n let cfg = &key[4..key.len() - 1];\n\n\n\n let expr = CfgExpr::from_str(&cfg).map_err(|e| {\n\n tera::Error::msg(format!(\n\n \"cfg_to_nix_expr_filter: Could not parse '{}': {}\",\n\n cfg, e\n\n ))\n\n })?;\n\n Ok(tera::Value::String(cfg_to_nix_expr(&expr)))\n\n } else {\n\n // It is hopefully a target \"triplet\".\n\n let condition =\n\n format!(\"(stdenv.hostPlatform.config == {})\", escape_nix_string(key));\n\n Ok(tera::Value::String(condition))\n\n }\n\n }\n\n _ => Err(tera::Error::msg(format!(\n\n \"cfg_to_nix_expr_filter: Expected string, got {:?}\",\n\n value\n\n ))),\n\n }\n\n}\n\n\n", "file_path": "crate2nix/src/render.rs", "rank": 42, "score": 41021.52566724722 }, { "content": "fn main() {\n\n hello_world();\n\n}\n", "file_path": "sample_workspace/lib_and_bin/src/main.rs", "rank": 43, "score": 41021.52566724722 }, { "content": "fn main() {\n\n println!(\"Hello, world! from bin2\");\n\n}\n", "file_path": "sample_projects/multiple_bin/src/bin2.rs", "rank": 44, "score": 41021.52566724722 }, { "content": "fn main() {}\n", "file_path": "sample_projects/renamed_build_deps/build.rs", "rank": 45, "score": 41021.52566724722 }, { "content": "fn main() {\n\n println!(\"Hello, world! from bin1\");\n\n}\n", "file_path": "sample_projects/multiple_bin/src/bin1.rs", "rank": 46, "score": 41021.52566724722 }, { "content": "fn main() {\n\n println!(\"Hello, world!\");\n\n}\n", "file_path": "sample_projects/multiple_bin/src/main.rs", "rank": 47, "score": 41021.52566724722 }, { "content": "fn main() {\n\n println!(\"Hello, dependency_issue_65!\");\n\n}\n", "file_path": "sample_projects/dependency_issue_65/src/main.rs", "rank": 48, "score": 41021.52566724722 }, { "content": "fn main() {\n\n println!(\"Hello, {}!\", CRATE_NAME);\n\n}\n", "file_path": "sample_projects/futures_compat/src/main.rs", "rank": 49, "score": 41021.52566724722 }, { "content": "fn main() {\n\n hello_world();\n\n}\n", "file_path": "sample_projects/lib_and_bin/src/main.rs", "rank": 50, "score": 41021.52566724722 }, { "content": "fn main() {\n\n let out_dir = env::var(\"OUT_DIR\").unwrap();\n\n let dest_path = Path::new(&out_dir).join(\"hello.rs\");\n\n let mut f = File::create(&dest_path).unwrap();\n\n\n\n f.write_all(\n\n b\"\n\n pub fn message() -> &'static str {\n\n \\\"Hello, World!\\\"\n\n }\n\n \",\n\n )\n\n .unwrap();\n\n}", "file_path": "sample_projects/still_unsupported/codegen/build.rs", "rank": 51, "score": 41021.52566724722 }, { "content": "fn main() {\n\n println!(\"Hello, with_problematic_crates!\");\n\n}\n", "file_path": "sample_projects/with_problematic_crates/src/main.rs", "rank": 52, "score": 41021.52566724722 }, { "content": "fn main() {\n\n println!(\"Hello, cfg-test!\");\n\n}\n", "file_path": "sample_projects/cfg-test/src/main.rs", "rank": 53, "score": 41021.52566724722 }, { "content": "fn main() -> CliResult {\n\n let opt = Opt::from_args();\n\n match opt {\n\n Opt::Generate {\n\n cargo_toml,\n\n output: opt_output,\n\n nixpkgs_path,\n\n crate_hashes,\n\n all_features,\n\n default_features,\n\n no_default_features,\n\n features,\n\n no_cargo_lock_checksums,\n\n dont_read_crate_hashes,\n\n } => {\n\n let crate_hashes_json = crate_hashes.unwrap_or_else(|| {\n\n cargo_toml\n\n .parent()\n\n .expect(\"Cargo.toml has parent\")\n\n .join(\"crate-hashes.json\")\n", "file_path": "crate2nix/src/main.rs", "rank": 54, "score": 40524.23748477379 }, { "content": "fn main() {\n\n println!(\"Banana is a veggie and tomato is a fruit\");\n\n}\n", "file_path": "sample_projects/test_flag_passing/src/main.rs", "rank": 55, "score": 40147.83276994286 }, { "content": "fn main() {\n\n hello_world_lib::hello_world(\"bin_with_lib_dep\");\n\n}\n", "file_path": "sample_workspace/bin_with_lib_dep/src/main.rs", "rank": 56, "score": 40147.83276994286 }, { "content": "#[test]\n\nfn nix_integration_tests() {\n\n run_integration_tests().unwrap();\n\n}\n\n\n", "file_path": "crate2nix/tests/run_nix_tests.rs", "rank": 57, "score": 40147.83276994286 }, { "content": "fn main() {\n\n println!(\"Hello, renamed_build_deps!\");\n\n}\n", "file_path": "sample_projects/renamed_build_deps/src/main.rs", "rank": 58, "score": 40147.83276994286 }, { "content": "#[cfg(test)]\n\n#[test]\n\nfn lib_test() {\n\n println!(\"lib test executed\");\n\n}\n", "file_path": "sample_projects/cfg-test/src/lib.rs", "rank": 59, "score": 40147.83276994286 }, { "content": "fn main() {\n\n #[cfg(feature = \"use_lib\")]\n\n hello_world_lib::hello_world(\"bin_with_default_features\");\n\n #[cfg(feature = \"do_not_activate\")]\n\n println!(\"COMPILED with do_not_activate\");\n\n}\n", "file_path": "sample_workspace/bin_with_default_features/src/main.rs", "rank": 60, "score": 40147.83276994286 }, { "content": "fn main() {\n\n renamed_hello_world_lib::hello_world(\"bin_with_lib_dep\");\n\n}\n", "file_path": "sample_projects/bin_with_lib_dep/src/main.rs", "rank": 61, "score": 40147.83276994286 }, { "content": "fn main() {\n\n println!(\"{}\", message());\n\n}", "file_path": "sample_projects/still_unsupported/codegen/src/main.rs", "rank": 62, "score": 40147.83276994286 }, { "content": "#[test]\n\nfn test_render_cfg_to_nix_expr() {\n\n fn name(value: &str) -> CfgExpr {\n\n CfgExpr::Value(Cfg::Name(value.to_string()))\n\n }\n\n\n\n fn kv(key: &str, value: &str) -> CfgExpr {\n\n use crate::target_cfg::Cfg::KeyPair;\n\n CfgExpr::Value(KeyPair(key.to_string(), value.to_string()))\n\n }\n\n\n\n assert_eq!(\"target.\\\"unix\\\"\", &cfg_to_nix_expr(&name(\"unix\")));\n\n assert_eq!(\n\n \"(target.\\\"os\\\" == \\\"linux\\\")\",\n\n &cfg_to_nix_expr(&kv(\"target_os\", \"linux\"))\n\n );\n\n assert_eq!(\n\n \"(!(target.\\\"os\\\" == \\\"linux\\\"))\",\n\n &cfg_to_nix_expr(&CfgExpr::Not(Box::new(kv(\"target_os\", \"linux\"))))\n\n );\n\n assert_eq!(\n\n \"(target.\\\"unix\\\" || (target.\\\"os\\\" == \\\"linux\\\"))\",\n\n &cfg_to_nix_expr(&CfgExpr::Any(vec![name(\"unix\"), kv(\"target_os\", \"linux\")]))\n\n );\n\n assert_eq!(\n\n \"(target.\\\"unix\\\" && (target.\\\"os\\\" == \\\"linux\\\"))\",\n\n &cfg_to_nix_expr(&CfgExpr::All(vec![name(\"unix\"), kv(\"target_os\", \"linux\")]))\n\n );\n\n}\n\n\n", "file_path": "crate2nix/src/render.rs", "rank": 63, "score": 40147.83276994286 }, { "content": "fn main() {\n\n #[cfg(feature = \"do_not_activate\")]\n\n let str = \", do_not_activate\";\n\n #[cfg(not(feature = \"do_not_activate\"))]\n\n let str = \"\";\n\n #[cfg(feature = \"use_lib\")]\n\n renamed_hello_world_lib::hello_world(\n\n &format!(\"bin_with_default_features{}\", str));\n\n}\n", "file_path": "sample_projects/bin_with_default_features/src/main.rs", "rank": 64, "score": 40147.83276994286 }, { "content": "#[test]\n\nfn nix_unit_tests() {\n\n let result = run_instantiate().expect(\"while running instantiate\");\n\n let json_value: Value = serde_json::from_str(&result).expect(\"while reading result as json\");\n\n let result = serde_json::to_string_pretty(&json_value).expect(\"while pretty printing\");\n\n if result != \"\\\"OK\\\"\" {\n\n panic!(\"Results with failures:\\n{}\", result);\n\n }\n\n}\n\n\n", "file_path": "crate2nix/tests/run_nix_tests.rs", "rank": 65, "score": 40147.83276994286 }, { "content": "#[test]\n\nfn this_must_run() {\n\n}\n", "file_path": "sample_projects/test_flag_passing/src/lib.rs", "rank": 66, "score": 39332.610644889945 }, { "content": "fn main() {\n\n new_name_hello_world_lib::hello_world(\"bin_with_rerenamed_lib_dep\");\n\n}\n", "file_path": "sample_projects/bin_with_rerenamed_lib_dep/src/main.rs", "rank": 67, "score": 39332.610644889945 }, { "content": "fn main() {\n\n println!(\"Hello from numtest, world!\");\n\n}\n", "file_path": "sample_projects/numtest_new_cargo_lock/src/main.rs", "rank": 68, "score": 39332.610644889945 }, { "content": "fn main() {\n\n println!(\"Hello world from with_git_submodule_dep!\");\n\n}\n", "file_path": "sample_projects/bin_with_git_submodule_dep/src/main.rs", "rank": 69, "score": 39332.610644889945 }, { "content": "#[test]\n\nfn this_must_be_skipped() {\n\n panic!(\"hello darkness, my old friend\");\n\n}\n\n\n", "file_path": "sample_projects/test_flag_passing/src/lib.rs", "rank": 70, "score": 39332.610644889945 }, { "content": "fn main() {\n\n nix_base32::to_nix_base32(&[1,2,3]);\n\n println!(\"Hello world from bin_with_lib_git_dep!\");\n\n}\n", "file_path": "sample_projects/bin_with_lib_git_dep/src/main.rs", "rank": 71, "score": 39332.610644889945 }, { "content": "fn main() {\n\n nix_base32::to_nix_base32(&[1,2,3]);\n\n println!(\"Hello world from bin_with_git_branch_dep!\");\n\n}\n", "file_path": "sample_projects/bin_with_git_branch_dep/src/main.rs", "rank": 72, "score": 39332.610644889945 }, { "content": "#[test]\n\nfn echo_foo_test() {\n\n println!(\"echo_foo_test\");\n\n}\n", "file_path": "sample_projects/cfg-test/tests/echo_foo_test.rs", "rank": 73, "score": 37855.57293302973 }, { "content": " cargo_toml.to_str().unwrap(),\n\n \"-o\",\n\n output.to_str().unwrap(),\n\n ]\n\n .iter()\n\n .map(|s| s.to_string())\n\n .collect(),\n\n ..GenerateInfo::default()\n\n },\n\n &config,\n\n )\n\n .unwrap();\n\n let rerendered_default_nix = render::render_build_file(&metadata).unwrap();\n\n let actual_default_nix = std::fs::read_to_string(&config.output).unwrap();\n\n\n\n assert_eq!(\n\n actual_default_nix,\n\n rerendered_default_nix,\n\n \"Pregenerated build files differ, please rerun ./regenerate_cargo_nix.sh.\\n{}\",\n\n PrettyDifference {\n", "file_path": "crate2nix/tests/self_build_up_to_date.rs", "rank": 83, "score": 29195.174642648115 }, { "content": "use colored_diff::PrettyDifference;\n\nuse crate2nix::{nix_build::dump_with_lines, render, BuildInfo, GenerateConfig, GenerateInfo};\n\nuse failure::{bail, format_err, Error};\n\nuse serde::Deserialize;\n\nuse serde::Serialize;\n\nuse std::io::Write;\n\nuse std::path::{Path, PathBuf};\n\nuse std::process::Command;\n\nuse std::str::FromStr;\n\n\n\n#[test]\n", "file_path": "crate2nix/tests/self_build_up_to_date.rs", "rank": 84, "score": 29191.426241381716 }, { "content": " nixpkgs_path: \"../nixpkgs.nix\".to_string(),\n\n crate_hashes_json: PathBuf::from(\"./crate-hashes.json\"),\n\n other_metadata_options: vec![],\n\n use_cargo_lock_checksums: true,\n\n read_crate_hashes: true,\n\n },\n\n )\n\n .unwrap();\n\n let rerendered_default_nix = render::render_build_file(&metadata).unwrap();\n\n let actual_default_nix = std::fs::read_to_string(\"./Cargo.nix\").unwrap();\n\n assert_eq!(actual_default_nix, rerendered_default_nix);\n\n\n\n if rerendered_default_nix.contains(\" /home/\") || rerendered_default_nix.contains(\".cargo\") {\n\n dump_with_lines(\"./Cargo.nix\").unwrap();\n\n panic!(\"Build file contains forbidden strings.\");\n\n }\n\n}\n\n\n", "file_path": "crate2nix/tests/self_build_up_to_date.rs", "rank": 85, "score": 29185.279017969257 }, { "content": " actual: &actual_default_nix,\n\n expected: &rerendered_default_nix\n\n }\n\n );\n\n\n\n if rerendered_default_nix.contains(\" /home/\") || rerendered_default_nix.contains(\".cargo\") {\n\n dump_with_lines(\"./Cargo.nix\").unwrap();\n\n panic!(\"Build file contains forbidden strings.\");\n\n }\n\n}\n\n\n", "file_path": "crate2nix/tests/self_build_up_to_date.rs", "rank": 86, "score": 29178.446909297774 }, { "content": " dependencies: package.dependencies.iter().collect(),\n\n })\n\n }\n\n\n\n fn filtered_dependencies(\n\n &self,\n\n filter: impl Fn(&Dependency) -> bool,\n\n ) -> Vec<ResolvedDependency> {\n\n /// Normalize a package name such as cargo does.\n\n fn normalize_package_name(package_name: &str) -> String {\n\n package_name.replace('-', \"_\")\n\n }\n\n\n\n // A map from the normalised name (used by features) to a vector of dependencies associated\n\n // with that name. There can be multiple dependencies because some might be behind\n\n // different targets (including no target at all).\n\n let mut names: HashMap<String, Vec<&Dependency>> = HashMap::new();\n\n for d in self.dependencies.iter().filter(|d| (filter(**d))) {\n\n let normalized = normalize_package_name(&d.name);\n\n names\n", "file_path": "crate2nix/src/resolve.rs", "rank": 87, "score": 30.67995559059532 }, { "content": "\n\nimpl ResolvedSource {\n\n pub fn new(\n\n config: &GenerateConfig,\n\n package: &Package,\n\n package_path: impl AsRef<Path>,\n\n ) -> Result<ResolvedSource, Error> {\n\n match package.source.as_ref() {\n\n Some(source) if source.is_crates_io() => {\n\n // Will sha256 will be filled later by prefetch_and_fill_crates_sha256.\n\n Ok(ResolvedSource::CratesIo(CratesIoSource {\n\n name: package.name.clone(),\n\n version: package.version.clone(),\n\n sha256: None,\n\n }))\n\n }\n\n Some(source) => {\n\n ResolvedSource::git_or_local_directory(config, package, &package_path, source)\n\n }\n\n None => Ok(ResolvedSource::LocalDirectory(LocalDirectorySource {\n", "file_path": "crate2nix/src/resolve.rs", "rank": 88, "score": 30.012836668430445 }, { "content": " let mut s = s.splitn(3, ' ');\n\n let name = s.next().unwrap();\n\n let version = s.next();\n\n let source_id = match s.next() {\n\n Some(s) => {\n\n if s.starts_with('(') && s.ends_with(')') {\n\n Some(String::from(&s[1..s.len() - 1]))\n\n } else {\n\n failure::bail!(\"invalid serialized PackageId\")\n\n }\n\n }\n\n None => None,\n\n };\n\n\n\n Ok(EncodablePackageId {\n\n name: name.to_string(),\n\n version: version.map(|v| v.to_string()),\n\n source: source_id,\n\n })\n\n }\n", "file_path": "crate2nix/src/lock.rs", "rank": 89, "score": 29.97189844707473 }, { "content": " let mut default_nix = BuildInfo::new(info, config, indexed_metadata)?;\n\n\n\n default_nix.prune_unneeded_crates();\n\n\n\n prefetch_and_fill_crates_sha256(config, &mut default_nix)?;\n\n\n\n Ok(default_nix)\n\n }\n\n\n\n fn prune_unneeded_crates(&mut self) {\n\n let mut queue: VecDeque<&PackageId> = self\n\n .root_package_id\n\n .iter()\n\n .chain(self.workspace_members.values())\n\n .collect();\n\n let mut reachable = HashSet::new();\n\n let indexed_crates: BTreeMap<_, _> =\n\n self.crates.iter().map(|c| (&c.package_id, c)).collect();\n\n while let Some(next_package_id) = queue.pop_back() {\n\n if !reachable.insert(next_package_id.clone()) {\n", "file_path": "crate2nix/src/lib.rs", "rank": 90, "score": 29.304910182019942 }, { "content": " .try_into()\n\n .map_err(|e| format_err!(\"unexpected format in {}: {}\", path.display(), e))?;\n\n Ok(v)\n\n }\n\n\n\n pub fn get_hashes_by_package_id(&self) -> Result<HashMap<PackageId, String>, Error> {\n\n let mut hashes = HashMap::new();\n\n\n\n for EncodableDependency {\n\n name,\n\n version,\n\n source,\n\n checksum,\n\n ..\n\n } in self.package.iter()\n\n {\n\n if let (Some(source), Some(checksum)) = (source, checksum) {\n\n let package_id = PackageId {\n\n repr: format!(\"{} {} ({})\", name, version, source),\n\n };\n", "file_path": "crate2nix/src/lock.rs", "rank": 91, "score": 27.698565455987914 }, { "content": "use cargo_metadata::PackageId;\n\nuse failure::{format_err, Error};\n\nuse serde::{de, ser, Deserialize, Serialize};\n\nuse std::collections::{BTreeMap, HashMap};\n\nuse std::fmt;\n\nuse std::path::Path;\n\nuse std::str::FromStr;\n\n\n\nimpl EncodableResolve {\n\n pub fn load_lock_file(path: &Path) -> Result<EncodableResolve, Error> {\n\n let config = &std::fs::read_to_string(path)\n\n .map_err(|e| format_err!(\"while reading lock file {}: {}\", path.display(), e))?;\n\n Self::load_lock_string(path, config)\n\n }\n\n\n\n pub fn load_lock_string(path: &Path, config: &str) -> Result<EncodableResolve, Error> {\n\n let resolve: toml::Value = toml::from_str(&config)\n\n .map_err(|e| format_err!(\"while parsing toml from {}: {}\", path.display(), e))?;\n\n\n\n let v: EncodableResolve = resolve\n", "file_path": "crate2nix/src/lock.rs", "rank": 92, "score": 27.497680168226974 }, { "content": " source: Option<String>,\n\n}\n\n\n\nimpl fmt::Display for EncodablePackageId {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"{}\", self.name)?;\n\n if let Some(s) = &self.version {\n\n write!(f, \" {}\", s)?;\n\n }\n\n if let Some(s) = &self.source {\n\n write!(f, \" ({})\", s)?;\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl FromStr for EncodablePackageId {\n\n type Err = failure::Error;\n\n\n\n fn from_str(s: &str) -> Result<EncodablePackageId, Error> {\n", "file_path": "crate2nix/src/lock.rs", "rank": 93, "score": 26.928880032331417 }, { "content": " match self {\n\n Self::CratesIo(source) => Self::CratesIo(CratesIoSource {\n\n sha256: None,\n\n ..source.clone()\n\n }),\n\n Self::Git(source) => Self::Git(GitSource {\n\n sha256: None,\n\n ..source.clone()\n\n }),\n\n _ => self.clone(),\n\n }\n\n }\n\n}\n\n\n\nimpl ToString for ResolvedSource {\n\n fn to_string(&self) -> String {\n\n match self {\n\n Self::CratesIo(source) => source.to_string(),\n\n Self::Git(source) => source.to_string(),\n\n Self::LocalDirectory(source) => source.to_string(),\n", "file_path": "crate2nix/src/resolve.rs", "rank": 94, "score": 26.378420065637638 }, { "content": " pub name: String,\n\n pub version: Version,\n\n pub sha256: Option<String>,\n\n}\n\n\n\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, Hash)]\n\npub struct GitSource {\n\n #[serde(with = \"url_serde\")]\n\n pub url: Url,\n\n pub rev: String,\n\n pub r#ref: Option<String>,\n\n pub sha256: Option<String>,\n\n}\n\n\n\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, Hash)]\n\npub struct LocalDirectorySource {\n\n path: PathBuf,\n\n}\n\n\n\nconst GIT_SOURCE_PREFIX: &str = \"git+\";\n", "file_path": "crate2nix/src/resolve.rs", "rank": 95, "score": 26.340548705756028 }, { "content": " }\n\n _ => None,\n\n }\n\n }\n\n\n\n pub fn with_sha256(&self, sha256: String) -> Self {\n\n match self {\n\n Self::CratesIo(source) => Self::CratesIo(CratesIoSource {\n\n sha256: Some(sha256),\n\n ..source.clone()\n\n }),\n\n Self::Git(source) => Self::Git(GitSource {\n\n sha256: Some(sha256),\n\n ..source.clone()\n\n }),\n\n _ => self.clone(),\n\n }\n\n }\n\n\n\n pub fn without_sha256(&self) -> Self {\n", "file_path": "crate2nix/src/resolve.rs", "rank": 96, "score": 26.196205028278598 }, { "content": " .source\n\n .as_ref()\n\n .map(std::string::ToString::to_string)\n\n .unwrap_or_else(|| \"N/A\".to_string()),\n\n &path.to_string_lossy()\n\n );\n\n Ok(ResolvedSource::LocalDirectory(LocalDirectorySource {\n\n path,\n\n }))\n\n }\n\n\n\n fn relative_directory(\n\n config: &GenerateConfig,\n\n package_path: impl AsRef<Path>,\n\n ) -> Result<PathBuf, Error> {\n\n // Use local directory. This is the local cargo crate directory in the worst case.\n\n\n\n let mut output_build_file_directory = config\n\n .output\n\n .parent()\n", "file_path": "crate2nix/src/resolve.rs", "rank": 97, "score": 25.157319522718527 }, { "content": "//TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n\n//PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n\n//SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n\n//CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n\n//OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\n\n//IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\n//DEALINGS IN THE SOFTWARE.\n\n\n\nuse failure::bail;\n\nuse failure::format_err;\n\nuse failure::Error;\n\nuse std::fmt;\n\nuse std::iter;\n\nuse std::str::{self, FromStr};\n\n\n\n#[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Clone, Debug)]\n\npub enum Cfg {\n\n Name(String),\n\n KeyPair(String, String),\n\n}\n", "file_path": "crate2nix/src/target_cfg.rs", "rank": 98, "score": 25.083564703228625 }, { "content": " Ok(ResolvedSource::Git(GitSource {\n\n url,\n\n rev,\n\n r#ref: branch,\n\n sha256: None,\n\n }))\n\n }\n\n\n\n fn fallback_to_local_directory(\n\n config: &GenerateConfig,\n\n package: &Package,\n\n package_path: impl AsRef<Path>,\n\n warning: &str,\n\n ) -> Result<ResolvedSource, Error> {\n\n let path = Self::relative_directory(config, package_path)?;\n\n eprintln!(\n\n \"WARNING: {} Falling back to local directory for crate {} with source {}: {}\",\n\n warning,\n\n package.id,\n\n package\n", "file_path": "crate2nix/src/resolve.rs", "rank": 99, "score": 24.63041739095437 } ]
Rust
sdk/src/permissions.rs
target/grid
e8efd7f0109dadc89f4b1ab5d57b09aa2d87eb26
use std::error::Error; use std::fmt; cfg_if! { if #[cfg(target_arch = "wasm32")] { use sabre_sdk::WasmSdkError as ContextError; use sabre_sdk::TransactionContext; } else { use sawtooth_sdk::processor::handler::ContextError; use sawtooth_sdk::processor::handler::TransactionContext; } } use crate::pike::addressing::compute_agent_address; use crate::protocol::pike::state::{Agent, AgentList}; use crate::protos::{FromBytes, ProtoConversionError}; #[derive(Debug)] pub enum PermissionCheckerError { Context(ContextError), InvalidPublicKey(String), ProtoConversion(ProtoConversionError), } impl fmt::Display for PermissionCheckerError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { PermissionCheckerError::Context(ref e) => e.fmt(f), PermissionCheckerError::InvalidPublicKey(ref msg) => { write!(f, "InvalidPublicKey: {}", msg) } PermissionCheckerError::ProtoConversion(ref e) => e.fmt(f), } } } impl Error for PermissionCheckerError { fn cause(&self) -> Option<&dyn Error> { match *self { PermissionCheckerError::Context(_) => None, PermissionCheckerError::InvalidPublicKey(_) => None, PermissionCheckerError::ProtoConversion(ref e) => Some(e), } } } impl From<ContextError> for PermissionCheckerError { fn from(err: ContextError) -> PermissionCheckerError { PermissionCheckerError::Context(err) } } impl From<ProtoConversionError> for PermissionCheckerError { fn from(err: ProtoConversionError) -> PermissionCheckerError { PermissionCheckerError::ProtoConversion(err) } } pub struct PermissionChecker<'a> { context: &'a dyn TransactionContext, } impl<'a> PermissionChecker<'a> { pub fn new(context: &'a dyn TransactionContext) -> PermissionChecker { PermissionChecker { context } } pub fn has_permission( &self, public_key: &str, permission: &str, record_owner: &str, ) -> Result<bool, PermissionCheckerError> { let agent = self.get_agent(public_key)?; match agent { Some(agent) => { if agent.org_id() != record_owner { return Ok(false); } Ok(agent.roles().iter().any(|r| r == permission)) } None => Err(PermissionCheckerError::InvalidPublicKey(format!( "The signer is not an Agent: {}", public_key ))), } } fn get_agent(&self, public_key: &str) -> Result<Option<Agent>, PermissionCheckerError> { let address = compute_agent_address(public_key); let d = self.context.get_state_entry(&address)?; match d { Some(packed) => { let agent_list = AgentList::from_bytes(packed.as_slice())?; for agent in agent_list.agents() { if agent.public_key() == public_key { return Ok(Some(agent.clone())); } } Ok(None) } None => Ok(None), } } } #[cfg(test)] mod tests { use super::*; use std::cell::RefCell; use std::collections::HashMap; use crate::protocol::pike::state::{AgentBuilder, AgentListBuilder}; use crate::protos::IntoBytes; const ROLE_A: &str = "Role A"; const ROLE_B: &str = "Role B"; const PUBLIC_KEY: &str = "test_public_key"; const ORG_ID: &str = "test_org"; const WRONG_ORG_ID: &str = "test_wrong_org"; #[derive(Default)] struct MockTransactionContext { state: RefCell<HashMap<String, Vec<u8>>>, } impl TransactionContext for MockTransactionContext { fn get_state_entries( &self, addresses: &[String], ) -> Result<Vec<(String, Vec<u8>)>, ContextError> { let mut results = Vec::new(); for addr in addresses { let data = match self.state.borrow().get(addr) { Some(data) => data.clone(), None => Vec::new(), }; results.push((addr.to_string(), data)); } Ok(results) } fn set_state_entries(&self, entries: Vec<(String, Vec<u8>)>) -> Result<(), ContextError> { for (addr, data) in entries { self.state.borrow_mut().insert(addr, data); } Ok(()) } fn delete_state_entries(&self, _addresses: &[String]) -> Result<Vec<String>, ContextError> { unimplemented!() } fn add_receipt_data(&self, _data: &[u8]) -> Result<(), ContextError> { unimplemented!() } fn add_event( &self, _event_type: String, _attributes: Vec<(String, String)>, _data: &[u8], ) -> Result<(), ContextError> { unimplemented!() } } #[test] fn test_has_permission_a_has_none() { let context = MockTransactionContext::default(); let pc = PermissionChecker::new(&context); let builder = AgentBuilder::new(); let agent = builder .with_org_id(ORG_ID.to_string()) .with_public_key(PUBLIC_KEY.to_string()) .with_active(true) .build() .unwrap(); let builder = AgentListBuilder::new(); let agent_list = builder.with_agents(vec![agent.clone()]).build().unwrap(); let agent_bytes = agent_list.into_bytes().unwrap(); let agent_address = compute_agent_address(PUBLIC_KEY); context.set_state_entry(agent_address, agent_bytes).unwrap(); let result = pc.has_permission(PUBLIC_KEY, ROLE_A, ORG_ID).unwrap(); assert!(!result); } #[test] fn test_has_permission_a_has_a() { let context = MockTransactionContext::default(); let pc = PermissionChecker::new(&context); let builder = AgentBuilder::new(); let agent = builder .with_org_id(ORG_ID.to_string()) .with_public_key(PUBLIC_KEY.to_string()) .with_active(true) .with_roles(vec![ROLE_A.to_string()]) .build() .unwrap(); let builder = AgentListBuilder::new(); let agent_list = builder.with_agents(vec![agent.clone()]).build().unwrap(); let agent_bytes = agent_list.into_bytes().unwrap(); let agent_address = compute_agent_address(PUBLIC_KEY); context.set_state_entry(agent_address, agent_bytes).unwrap(); let result = pc.has_permission(PUBLIC_KEY, ROLE_A, ORG_ID).unwrap(); assert!(result); } #[test] fn test_has_permission_b_has_a() { let context = MockTransactionContext::default(); let pc = PermissionChecker::new(&context); let builder = AgentBuilder::new(); let agent = builder .with_org_id(ORG_ID.to_string()) .with_public_key(PUBLIC_KEY.to_string()) .with_active(true) .with_roles(vec![ROLE_A.to_string()]) .build() .unwrap(); let builder = AgentListBuilder::new(); let agent_list = builder.with_agents(vec![agent.clone()]).build().unwrap(); let agent_bytes = agent_list.into_bytes().unwrap(); let agent_address = compute_agent_address(PUBLIC_KEY); context.set_state_entry(agent_address, agent_bytes).unwrap(); let result = pc.has_permission(PUBLIC_KEY, ROLE_B, ORG_ID).unwrap(); assert!(!result); } #[test] fn test_has_permission_a_has_ab() { let context = MockTransactionContext::default(); let pc = PermissionChecker::new(&context); let builder = AgentBuilder::new(); let agent = builder .with_org_id(ORG_ID.to_string()) .with_public_key(PUBLIC_KEY.to_string()) .with_active(true) .with_roles(vec![ROLE_A.to_string(), ROLE_B.to_string()]) .build() .unwrap(); let builder = AgentListBuilder::new(); let agent_list = builder.with_agents(vec![agent.clone()]).build().unwrap(); let agent_bytes = agent_list.into_bytes().unwrap(); let agent_address = compute_agent_address(PUBLIC_KEY); context.set_state_entry(agent_address, agent_bytes).unwrap(); let result = pc.has_permission(PUBLIC_KEY, ROLE_A, ORG_ID).unwrap(); assert!(result); } #[test] fn test_has_permission_b_has_ab() { let context = MockTransactionContext::default(); let pc = PermissionChecker::new(&context); let builder = AgentBuilder::new(); let agent = builder .with_org_id(ORG_ID.to_string()) .with_public_key(PUBLIC_KEY.to_string()) .with_active(true) .with_roles(vec![ROLE_A.to_string(), ROLE_B.to_string()]) .build() .unwrap(); let builder = AgentListBuilder::new(); let agent_list = builder.with_agents(vec![agent.clone()]).build().unwrap(); let agent_bytes = agent_list.into_bytes().unwrap(); let agent_address = compute_agent_address(PUBLIC_KEY); context.set_state_entry(agent_address, agent_bytes).unwrap(); let result = pc.has_permission(PUBLIC_KEY, ROLE_B, ORG_ID).unwrap(); assert!(result); } #[test] fn test_has_wrong_org() { let context = MockTransactionContext::default(); let pc = PermissionChecker::new(&context); let builder = AgentBuilder::new(); let agent = builder .with_org_id(ORG_ID.to_string()) .with_public_key(PUBLIC_KEY.to_string()) .with_active(true) .with_roles(vec![ROLE_A.to_string()]) .build() .unwrap(); let builder = AgentListBuilder::new(); let agent_list = builder.with_agents(vec![agent.clone()]).build().unwrap(); let agent_bytes = agent_list.into_bytes().unwrap(); let agent_address = compute_agent_address(PUBLIC_KEY); context.set_state_entry(agent_address, agent_bytes).unwrap(); let result = pc.has_permission(PUBLIC_KEY, ROLE_A, WRONG_ORG_ID).unwrap(); assert!(!result); } }
use std::error::Error; use std::fmt; cfg_if! { if #[cfg(target_arch = "wasm32")] { use sabre_sdk::WasmSdkError as ContextError; use sabre_sdk::TransactionContext; } else { use sawtooth_sdk::processor::handler::ContextError; use sawtooth_sdk::processor::handler::TransactionContext; } } use crate::pike::addressing::compute_agent_address; use cr
ntextError), InvalidPublicKey(String), ProtoConversion(ProtoConversionError), } impl fmt::Display for PermissionCheckerError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { PermissionCheckerError::Context(ref e) => e.fmt(f), PermissionCheckerError::InvalidPublicKey(ref msg) => { write!(f, "InvalidPublicKey: {}", msg) } PermissionCheckerError::ProtoConversion(ref e) => e.fmt(f), } } } impl Error for PermissionCheckerError { fn cause(&self) -> Option<&dyn Error> { match *self { PermissionCheckerError::Context(_) => None, PermissionCheckerError::InvalidPublicKey(_) => None, PermissionCheckerError::ProtoConversion(ref e) => Some(e), } } } impl From<ContextError> for PermissionCheckerError { fn from(err: ContextError) -> PermissionCheckerError { PermissionCheckerError::Context(err) } } impl From<ProtoConversionError> for PermissionCheckerError { fn from(err: ProtoConversionError) -> PermissionCheckerError { PermissionCheckerError::ProtoConversion(err) } } pub struct PermissionChecker<'a> { context: &'a dyn TransactionContext, } impl<'a> PermissionChecker<'a> { pub fn new(context: &'a dyn TransactionContext) -> PermissionChecker { PermissionChecker { context } } pub fn has_permission( &self, public_key: &str, permission: &str, record_owner: &str, ) -> Result<bool, PermissionCheckerError> { let agent = self.get_agent(public_key)?; match agent { Some(agent) => { if agent.org_id() != record_owner { return Ok(false); } Ok(agent.roles().iter().any(|r| r == permission)) } None => Err(PermissionCheckerError::InvalidPublicKey(format!( "The signer is not an Agent: {}", public_key ))), } } fn get_agent(&self, public_key: &str) -> Result<Option<Agent>, PermissionCheckerError> { let address = compute_agent_address(public_key); let d = self.context.get_state_entry(&address)?; match d { Some(packed) => { let agent_list = AgentList::from_bytes(packed.as_slice())?; for agent in agent_list.agents() { if agent.public_key() == public_key { return Ok(Some(agent.clone())); } } Ok(None) } None => Ok(None), } } } #[cfg(test)] mod tests { use super::*; use std::cell::RefCell; use std::collections::HashMap; use crate::protocol::pike::state::{AgentBuilder, AgentListBuilder}; use crate::protos::IntoBytes; const ROLE_A: &str = "Role A"; const ROLE_B: &str = "Role B"; const PUBLIC_KEY: &str = "test_public_key"; const ORG_ID: &str = "test_org"; const WRONG_ORG_ID: &str = "test_wrong_org"; #[derive(Default)] struct MockTransactionContext { state: RefCell<HashMap<String, Vec<u8>>>, } impl TransactionContext for MockTransactionContext { fn get_state_entries( &self, addresses: &[String], ) -> Result<Vec<(String, Vec<u8>)>, ContextError> { let mut results = Vec::new(); for addr in addresses { let data = match self.state.borrow().get(addr) { Some(data) => data.clone(), None => Vec::new(), }; results.push((addr.to_string(), data)); } Ok(results) } fn set_state_entries(&self, entries: Vec<(String, Vec<u8>)>) -> Result<(), ContextError> { for (addr, data) in entries { self.state.borrow_mut().insert(addr, data); } Ok(()) } fn delete_state_entries(&self, _addresses: &[String]) -> Result<Vec<String>, ContextError> { unimplemented!() } fn add_receipt_data(&self, _data: &[u8]) -> Result<(), ContextError> { unimplemented!() } fn add_event( &self, _event_type: String, _attributes: Vec<(String, String)>, _data: &[u8], ) -> Result<(), ContextError> { unimplemented!() } } #[test] fn test_has_permission_a_has_none() { let context = MockTransactionContext::default(); let pc = PermissionChecker::new(&context); let builder = AgentBuilder::new(); let agent = builder .with_org_id(ORG_ID.to_string()) .with_public_key(PUBLIC_KEY.to_string()) .with_active(true) .build() .unwrap(); let builder = AgentListBuilder::new(); let agent_list = builder.with_agents(vec![agent.clone()]).build().unwrap(); let agent_bytes = agent_list.into_bytes().unwrap(); let agent_address = compute_agent_address(PUBLIC_KEY); context.set_state_entry(agent_address, agent_bytes).unwrap(); let result = pc.has_permission(PUBLIC_KEY, ROLE_A, ORG_ID).unwrap(); assert!(!result); } #[test] fn test_has_permission_a_has_a() { let context = MockTransactionContext::default(); let pc = PermissionChecker::new(&context); let builder = AgentBuilder::new(); let agent = builder .with_org_id(ORG_ID.to_string()) .with_public_key(PUBLIC_KEY.to_string()) .with_active(true) .with_roles(vec![ROLE_A.to_string()]) .build() .unwrap(); let builder = AgentListBuilder::new(); let agent_list = builder.with_agents(vec![agent.clone()]).build().unwrap(); let agent_bytes = agent_list.into_bytes().unwrap(); let agent_address = compute_agent_address(PUBLIC_KEY); context.set_state_entry(agent_address, agent_bytes).unwrap(); let result = pc.has_permission(PUBLIC_KEY, ROLE_A, ORG_ID).unwrap(); assert!(result); } #[test] fn test_has_permission_b_has_a() { let context = MockTransactionContext::default(); let pc = PermissionChecker::new(&context); let builder = AgentBuilder::new(); let agent = builder .with_org_id(ORG_ID.to_string()) .with_public_key(PUBLIC_KEY.to_string()) .with_active(true) .with_roles(vec![ROLE_A.to_string()]) .build() .unwrap(); let builder = AgentListBuilder::new(); let agent_list = builder.with_agents(vec![agent.clone()]).build().unwrap(); let agent_bytes = agent_list.into_bytes().unwrap(); let agent_address = compute_agent_address(PUBLIC_KEY); context.set_state_entry(agent_address, agent_bytes).unwrap(); let result = pc.has_permission(PUBLIC_KEY, ROLE_B, ORG_ID).unwrap(); assert!(!result); } #[test] fn test_has_permission_a_has_ab() { let context = MockTransactionContext::default(); let pc = PermissionChecker::new(&context); let builder = AgentBuilder::new(); let agent = builder .with_org_id(ORG_ID.to_string()) .with_public_key(PUBLIC_KEY.to_string()) .with_active(true) .with_roles(vec![ROLE_A.to_string(), ROLE_B.to_string()]) .build() .unwrap(); let builder = AgentListBuilder::new(); let agent_list = builder.with_agents(vec![agent.clone()]).build().unwrap(); let agent_bytes = agent_list.into_bytes().unwrap(); let agent_address = compute_agent_address(PUBLIC_KEY); context.set_state_entry(agent_address, agent_bytes).unwrap(); let result = pc.has_permission(PUBLIC_KEY, ROLE_A, ORG_ID).unwrap(); assert!(result); } #[test] fn test_has_permission_b_has_ab() { let context = MockTransactionContext::default(); let pc = PermissionChecker::new(&context); let builder = AgentBuilder::new(); let agent = builder .with_org_id(ORG_ID.to_string()) .with_public_key(PUBLIC_KEY.to_string()) .with_active(true) .with_roles(vec![ROLE_A.to_string(), ROLE_B.to_string()]) .build() .unwrap(); let builder = AgentListBuilder::new(); let agent_list = builder.with_agents(vec![agent.clone()]).build().unwrap(); let agent_bytes = agent_list.into_bytes().unwrap(); let agent_address = compute_agent_address(PUBLIC_KEY); context.set_state_entry(agent_address, agent_bytes).unwrap(); let result = pc.has_permission(PUBLIC_KEY, ROLE_B, ORG_ID).unwrap(); assert!(result); } #[test] fn test_has_wrong_org() { let context = MockTransactionContext::default(); let pc = PermissionChecker::new(&context); let builder = AgentBuilder::new(); let agent = builder .with_org_id(ORG_ID.to_string()) .with_public_key(PUBLIC_KEY.to_string()) .with_active(true) .with_roles(vec![ROLE_A.to_string()]) .build() .unwrap(); let builder = AgentListBuilder::new(); let agent_list = builder.with_agents(vec![agent.clone()]).build().unwrap(); let agent_bytes = agent_list.into_bytes().unwrap(); let agent_address = compute_agent_address(PUBLIC_KEY); context.set_state_entry(agent_address, agent_bytes).unwrap(); let result = pc.has_permission(PUBLIC_KEY, ROLE_A, WRONG_ORG_ID).unwrap(); assert!(!result); } }
ate::protocol::pike::state::{Agent, AgentList}; use crate::protos::{FromBytes, ProtoConversionError}; #[derive(Debug)] pub enum PermissionCheckerError { Context(Co
random
[ { "content": "cfg_if! {\n\n if #[cfg(target_arch = \"wasm32\")] {\n\n #[macro_use]\n\n extern crate sabre_sdk;\n\n } else {\n\n #[macro_use]\n\n extern crate clap;\n\n #[macro_use]\n\n extern crate log;\n\n extern crate sawtooth_sdk;\n\n extern crate flexi_logger;\n\n\n\n mod error;\n\n\n\n use flexi_logger::{LogSpecBuilder, Logger};\n\n use sawtooth_sdk::processor::TransactionProcessor;\n\n use handler::PikeTransactionHandler;\n\n use error::CliError;\n\n }\n\n}\n\n\n\npub mod handler;\n\n\n\n//use sawtooth_sdk::processor::TransactionProcessor;\n\n//use handler::PikeTransactionHandler;\n\n\n\n#[cfg(not(target_arch = \"wasm32\"))]\n", "file_path": "contracts/pike/src/main.rs", "rank": 0, "score": 12.10864294185991 }, { "content": " #[macro_use]\n\n extern crate log;\n\n use std::process;\n\n use log::LogLevelFilter;\n\n use log4rs::append::console::ConsoleAppender;\n\n use log4rs::config::{Appender, Config, Root};\n\n use log4rs::encode::pattern::PatternEncoder;\n\n use sawtooth_sdk::processor::TransactionProcessor;\n\n use handler::GridSchemaTransactionHandler;\n\n } else {\n\n #[macro_use]\n\n extern crate sabre_sdk;\n\n }\n\n}\n\n\n\npub mod handler;\n\nmod payload;\n\nmod state;\n\n\n\n#[cfg(not(target_arch = \"wasm32\"))]\n", "file_path": "contracts/schema/src/main.rs", "rank": 1, "score": 11.086450777396816 }, { "content": " extern crate clap;\n\n #[macro_use]\n\n extern crate log;\n\n use std::process;\n\n use log::LogLevelFilter;\n\n use log4rs::append::console::ConsoleAppender;\n\n use log4rs::config::{Appender, Config, Root};\n\n use log4rs::encode::pattern::PatternEncoder;\n\n use sawtooth_sdk::processor::TransactionProcessor;\n\n use crate::handler::LocationTransactionHandler;\n\n } else {\n\n #[macro_use]\n\n extern crate sabre_sdk;\n\n }\n\n}\n\n\n\npub mod handler;\n\nmod state;\n\n\n\n#[cfg(not(target_arch = \"wasm32\"))]\n", "file_path": "contracts/location/src/main.rs", "rank": 2, "score": 11.056160172922649 }, { "content": " extern crate clap;\n\n #[macro_use]\n\n extern crate log;\n\n use std::process;\n\n use log::LogLevelFilter;\n\n use log4rs::append::console::ConsoleAppender;\n\n use log4rs::config::{Appender, Config, Root};\n\n use log4rs::encode::pattern::PatternEncoder;\n\n use sawtooth_sdk::processor::TransactionProcessor;\n\n use handler::TrackAndTraceTransactionHandler;\n\n } else {\n\n #[macro_use]\n\n extern crate sabre_sdk;\n\n }\n\n}\n\n\n\npub mod handler;\n\nmod payload;\n\nmod state;\n\n\n\n#[cfg(not(target_arch = \"wasm32\"))]\n", "file_path": "contracts/track_and_trace/src/main.rs", "rank": 3, "score": 10.996374167563108 }, { "content": " #[macro_use]\n\n extern crate clap;\n\n #[macro_use]\n\n extern crate log;\n\n use std::process;\n\n use log::LogLevelFilter;\n\n use log4rs::append::console::ConsoleAppender;\n\n use log4rs::config::{Appender, Config, Root};\n\n use log4rs::encode::pattern::PatternEncoder;\n\n use sawtooth_sdk::processor::TransactionProcessor;\n\n use crate::handler::ProductTransactionHandler;\n\n } else {\n\n #[macro_use]\n\n extern crate sabre_sdk;\n\n }\n\n}\n\n\n\npub mod handler;\n\nmod payload;\n\nmod state;\n\nmod validation;\n\n\n\n#[cfg(not(target_arch = \"wasm32\"))]\n", "file_path": "contracts/product/src/main.rs", "rank": 4, "score": 10.952149467817637 }, { "content": " protos::{FromBytes, IntoBytes},\n\n schemas::addressing::compute_schema_address,\n\n};\n\n\n\ncfg_if! {\n\n if #[cfg(target_arch = \"wasm32\")] {\n\n use sabre_sdk::ApplyError;\n\n use sabre_sdk::TransactionContext;\n\n } else {\n\n use sawtooth_sdk::processor::handler::ApplyError;\n\n use sawtooth_sdk::processor::handler::TransactionContext;\n\n }\n\n}\n\n\n\n/// GridSchemaState is in charge of handling getting and setting state.\n\npub struct GridSchemaState<'a> {\n\n context: &'a dyn TransactionContext,\n\n}\n\n\n\nimpl<'a> GridSchemaState<'a> {\n", "file_path": "contracts/schema/src/state.rs", "rank": 5, "score": 10.446746398804853 }, { "content": " error::{CommitEventError, CommitStoreError},\n\n ChainRecord, Commit, CommitEvent,\n\n};\n\nuse crate::commits::MAX_COMMIT_NUM;\n\nuse crate::error::InternalError;\n\n\n\n/// Implementation of CommitStore that stores Commits in memory. Useful for when persistence isn't\n\n/// necessary.\n\n#[derive(Clone, Default)]\n\npub struct MemoryCommitStore {\n\n inner_commit: Arc<Mutex<HashMap<String, Commit>>>,\n\n inner_cr: Arc<Mutex<HashMap<String, ChainRecord>>>,\n\n}\n\n\n\nimpl MemoryCommitStore {\n\n pub fn new() -> Self {\n\n MemoryCommitStore {\n\n inner_commit: Arc::new(Mutex::new(HashMap::new())),\n\n inner_cr: Arc::new(Mutex::new(HashMap::new())),\n\n }\n", "file_path": "sdk/src/commits/store/memory.rs", "rank": 6, "score": 10.446446653157306 }, { "content": " use sabre_sdk::{WasmPtr, execute_entrypoint};\n\n } else {\n\n use sawtooth_sdk::processor::handler::ApplyError;\n\n use sawtooth_sdk::processor::handler::TransactionContext;\n\n use sawtooth_sdk::processor::handler::TransactionHandler;\n\n use sawtooth_sdk::messages::processor::TpProcessRequest;\n\n }\n\n}\n\n\n\nuse grid_sdk::permissions::PermissionChecker;\n\nuse grid_sdk::protocol::schema::payload::{\n\n Action, SchemaCreateAction, SchemaPayload, SchemaUpdateAction,\n\n};\n\nuse grid_sdk::protocol::schema::state::SchemaBuilder;\n\nuse grid_sdk::protos::FromBytes;\n\nuse grid_sdk::schemas::addressing::GRID_NAMESPACE;\n\n\n\nuse crate::payload::validate_payload;\n\nuse crate::state::GridSchemaState;\n\n\n\n#[cfg(target_arch = \"wasm32\")]\n\n// Sabre apply must return a bool\n", "file_path": "contracts/schema/src/handler.rs", "rank": 7, "score": 10.36566504317948 }, { "content": " use sabre_sdk::{WasmPtr, execute_entrypoint};\n\n } else {\n\n use sawtooth_sdk::processor::handler::ApplyError;\n\n use sawtooth_sdk::processor::handler::TransactionContext;\n\n use sawtooth_sdk::processor::handler::TransactionHandler;\n\n use sawtooth_sdk::messages::processor::TpProcessRequest;\n\n }\n\n}\n\n\n\nuse grid_sdk::{\n\n locations::addressing::GRID_NAMESPACE,\n\n permissions::PermissionChecker,\n\n protocol::location::{\n\n payload::{\n\n Action, LocationCreateAction, LocationDeleteAction, LocationNamespace, LocationPayload,\n\n LocationUpdateAction,\n\n },\n\n state::{LocationBuilder, LocationNamespace as StateNamespace},\n\n },\n\n};\n\n\n\nuse grid_sdk::protos::FromBytes;\n\n\n\nuse crate::state::LocationState;\n\n\n\n#[cfg(target_arch = \"wasm32\")]\n", "file_path": "contracts/location/src/handler.rs", "rank": 8, "score": 10.325226416632372 }, { "content": " use sabre_sdk::{WasmPtr, execute_entrypoint};\n\n } else {\n\n use sawtooth_sdk::processor::handler::ApplyError;\n\n use sawtooth_sdk::processor::handler::TransactionContext;\n\n use sawtooth_sdk::processor::handler::TransactionHandler;\n\n use sawtooth_sdk::messages::processor::TpProcessRequest;\n\n }\n\n}\n\n\n\nuse grid_sdk::{\n\n permissions::PermissionChecker,\n\n products::addressing::GRID_NAMESPACE,\n\n protocol::product::{\n\n payload::{\n\n Action, ProductCreateAction, ProductDeleteAction, ProductPayload, ProductUpdateAction,\n\n },\n\n state::{ProductBuilder, ProductNamespace},\n\n },\n\n protos::FromBytes,\n\n};\n\n\n\nuse crate::payload::validate_payload;\n\nuse crate::state::ProductState;\n\nuse crate::validation::validate_gtin;\n\n\n\n#[cfg(target_arch = \"wasm32\")]\n\n// Sabre apply must return a bool\n", "file_path": "contracts/product/src/handler.rs", "rank": 9, "score": 10.255083397776968 }, { "content": "// Copyright 2018 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse protobuf;\n\n\n\ncfg_if! {\n\n if #[cfg(target_arch = \"wasm32\")] {\n\n use sabre_sdk::ApplyError;\n\n use sabre_sdk::TransactionContext;\n", "file_path": "contracts/pike/src/handler.rs", "rank": 10, "score": 10.087466473974285 }, { "content": "// Copyright 2020 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\ncfg_if! {\n\n if #[cfg(target_arch = \"wasm32\")] {\n\n use sabre_sdk::ApplyError;\n\n use sabre_sdk::TransactionContext;\n\n use sabre_sdk::TransactionHandler;\n\n use sabre_sdk::TpProcessRequest;\n", "file_path": "contracts/location/src/handler.rs", "rank": 11, "score": 10.067221804297464 }, { "content": "// Copyright 2019 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\ncfg_if! {\n\n if #[cfg(target_arch = \"wasm32\")] {\n\n use sabre_sdk::ApplyError;\n\n use sabre_sdk::TransactionContext;\n\n use sabre_sdk::TransactionHandler;\n\n use sabre_sdk::TpProcessRequest;\n", "file_path": "contracts/schema/src/handler.rs", "rank": 12, "score": 10.067221804297464 }, { "content": "// Copyright (c) 2019 Target Brands, Inc.\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\ncfg_if! {\n\n if #[cfg(target_arch = \"wasm32\")] {\n\n use sabre_sdk::ApplyError;\n\n use sabre_sdk::TransactionContext;\n\n use sabre_sdk::TransactionHandler;\n\n use sabre_sdk::TpProcessRequest;\n", "file_path": "contracts/product/src/handler.rs", "rank": 13, "score": 10.036912254337347 }, { "content": "// Copyright 2018 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse std::collections::HashMap;\n\n\n\ncfg_if! {\n\n if #[cfg(target_arch = \"wasm32\")] {\n\n use sabre_sdk::ApplyError;\n\n use sabre_sdk::TransactionContext;\n", "file_path": "contracts/track_and_trace/src/handler.rs", "rank": 14, "score": 9.98542049460262 }, { "content": "// Copyright 2020 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\ncfg_if! {\n\n if #[cfg(target_arch = \"wasm32\")] {\n\n use sabre_sdk::ApplyError;\n\n use sabre_sdk::TransactionContext;\n\n } else {\n\n use sawtooth_sdk::processor::handler::ApplyError;\n", "file_path": "contracts/location/src/state.rs", "rank": 16, "score": 9.918759301169967 }, { "content": "// Copyright 2019 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\ncfg_if! {\n\n if #[cfg(target_arch = \"wasm32\")] {\n\n use sabre_sdk::ApplyError;\n\n use sabre_sdk::TransactionContext;\n\n } else {\n\n use sawtooth_sdk::processor::handler::ApplyError;\n", "file_path": "contracts/track_and_trace/src/state.rs", "rank": 17, "score": 9.918759301169967 }, { "content": "// Copyright (c) 2019 Target Brands, Inc.\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\ncfg_if! {\n\n if #[cfg(target_arch = \"wasm32\")] {\n\n use sabre_sdk::ApplyError;\n\n use sabre_sdk::TransactionContext;\n\n } else {\n\n use sawtooth_sdk::processor::handler::ApplyError;\n", "file_path": "contracts/product/src/state.rs", "rank": 18, "score": 9.885828285351895 }, { "content": "// Copyright 2020 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n#[macro_use]\n\nextern crate cfg_if;\n\nextern crate grid_sdk;\n\ncfg_if! {\n\n if #[cfg(not(target_arch = \"wasm32\"))] {\n\n #[macro_use]\n", "file_path": "contracts/location/src/main.rs", "rank": 19, "score": 9.729939720417667 }, { "content": "// Copyright 2018 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n#[macro_use]\n\nextern crate cfg_if;\n\nextern crate grid_sdk;\n\ncfg_if! {\n\n if #[cfg(not(target_arch = \"wasm32\"))] {\n\n #[macro_use]\n", "file_path": "contracts/track_and_trace/src/main.rs", "rank": 20, "score": 9.729939720417667 }, { "content": "// Copyright (c) 2019 Target Brands, Inc.\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\ncfg_if! {\n\n if #[cfg(target_arch = \"wasm32\")] {\n\n use sabre_sdk::ApplyError;\n\n } else {\n\n use sawtooth_sdk::processor::handler::ApplyError;\n\n }\n\n}\n\n\n\nuse grid_sdk::protocol::product::payload::{Action, ProductCreateAction, ProductPayload};\n\n\n", "file_path": "contracts/product/src/payload.rs", "rank": 21, "score": 9.662441369980014 }, { "content": "// Copyright 2019 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\ncfg_if! {\n\n if #[cfg(target_arch = \"wasm32\")] {\n\n use sabre_sdk::ApplyError;\n\n } else {\n\n use sawtooth_sdk::processor::handler::ApplyError;\n\n }\n\n}\n\n\n\nuse grid_sdk::protocol::track_and_trace::payload::{\n\n Action, CreateRecordAction, TrackAndTracePayload,\n\n};\n\n\n", "file_path": "contracts/track_and_trace/src/payload.rs", "rank": 22, "score": 9.63150748448869 }, { "content": "// Copyright 2019 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n#[macro_use]\n\nextern crate cfg_if;\n\nextern crate grid_sdk;\n\ncfg_if! {\n\n if #[cfg(not(target_arch = \"wasm32\"))] {\n\n #[macro_use]\n\n extern crate clap;\n", "file_path": "contracts/schema/src/main.rs", "rank": 23, "score": 9.62034007072445 }, { "content": "// Copyright 2019 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\ncfg_if! {\n\n if #[cfg(target_arch = \"wasm32\")] {\n\n use sabre_sdk::ApplyError;\n\n } else {\n\n use sawtooth_sdk::processor::handler::ApplyError;\n\n }\n\n}\n\n\n\nuse grid_sdk::protocol::schema::payload::{\n\n Action, SchemaCreateAction, SchemaPayload, SchemaUpdateAction,\n\n};\n\n\n", "file_path": "contracts/schema/src/payload.rs", "rank": 24, "score": 9.60080868269868 }, { "content": "// Copyright 2019 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\n#[macro_use]\n\nextern crate cfg_if;\n\nextern crate grid_sdk;\n\n\n\ncfg_if! {\n\n if #[cfg(not(target_arch = \"wasm32\"))] {\n", "file_path": "contracts/product/src/main.rs", "rank": 25, "score": 9.158604262091567 }, { "content": "// Copyright (c) 2019 Target Brands, Inc.\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\ncfg_if! {\n\n if #[cfg(target_arch = \"wasm32\")] {\n\n use sabre_sdk::ApplyError;\n\n } else {\n\n use sawtooth_sdk::processor::handler::ApplyError;\n\n }\n\n}\n\n\n\n/* The purpose of this file is to programmatically express the equation used to validate a GTIN\n\nIt validates gtin format to avoid mistype errors similar to a credit card validation\n\nCheck digit validation: (https://www.gs1.org/services/how-calculate-check-digit-manually) */\n\n\n\n// Leaving this as an extensible function, so other validation rules can be implemented by GTIN format\n", "file_path": "contracts/product/src/validation.rs", "rank": 26, "score": 8.90174811208444 }, { "content": "use crypto::sha2::Sha512;\n\n\n\nuse protobuf::Message;\n\n\n\nuse sabre_sdk::protocol::payload::ExecuteContractActionBuilder;\n\nuse sabre_sdk::protos::IntoBytes;\n\nuse sawtooth_sdk::messages::batch::Batch;\n\nuse sawtooth_sdk::messages::batch::BatchHeader;\n\nuse sawtooth_sdk::messages::batch::BatchList;\n\nuse sawtooth_sdk::messages::transaction::Transaction;\n\nuse sawtooth_sdk::messages::transaction::TransactionHeader;\n\nuse sawtooth_sdk::signing;\n\n\n\nuse crate::key;\n\n\n\nuse crate::CliError;\n\n\n\nconst PIKE_FAMILY_NAME: &str = \"pike\";\n\nconst PIKE_FAMILY_VERSION: &str = \"1\";\n\n\n", "file_path": "cli/src/transaction.rs", "rank": 27, "score": 7.101659421389448 }, { "content": "use std::str::FromStr;\n\n\n\nuse clap::{App, Arg};\n\nuse diesel::r2d2::{ConnectionManager, Pool};\n\nuse flexi_logger::{DeferredNow, LogSpecBuilder, Logger};\n\nuse grid_sdk::{rest_api::actix_web_3, store::ConnectionUri};\n\nuse log::Record;\n\nuse users::get_current_username;\n\n\n\nuse error::Error;\n\n\n", "file_path": "griddle/src/main.rs", "rank": 28, "score": 7.0678454973763305 }, { "content": "#[cfg(feature = \"pike\")]\n\npub use agents::*;\n\npub use batches::*;\n\n#[cfg(feature = \"location\")]\n\npub use locations::*;\n\n#[cfg(feature = \"pike\")]\n\npub use organizations::*;\n\n#[cfg(feature = \"product\")]\n\npub use products::*;\n\n#[cfg(feature = \"track-and-trace\")]\n\npub use records::*;\n\n#[cfg(feature = \"schema\")]\n\npub use schemas::*;\n\n\n\nuse crate::database::ConnectionPool;\n\n\n\nuse actix::{Actor, SyncContext};\n\n\n\n#[derive(Clone)]\n\npub struct DbExecutor {\n", "file_path": "daemon/src/rest_api/routes/mod.rs", "rank": 29, "score": 7.05177322101529 }, { "content": "\n\n#[cfg(feature = \"integration\")]\n\nuse grid_sdk::rest_api::actix_web_3::State as IntegrationState;\n\nuse grid_sdk::store::ConnectionUri;\n\nuse splinter::events::Reactor;\n\n\n\nuse crate::config::GridConfig;\n\nuse crate::database::ConnectionPool;\n\nuse crate::error::DaemonError;\n\nuse crate::event::{db_handler::DatabaseEventHandler, EventHandler};\n\nuse crate::rest_api;\n\n\n\nuse super::{\n\n app_auth_handler, batch_submitter::SplinterBatchSubmitter,\n\n event::ScabbardEventConnectionFactory, key::load_scabbard_admin_key,\n\n};\n\n\n", "file_path": "daemon/src/splinter/run.rs", "rank": 30, "score": 6.922077290895228 }, { "content": "use std::os::unix::fs::OpenOptionsExt;\n\nuse std::path::{Path, PathBuf};\n\n\n\n#[cfg(target_os = \"linux\")]\n\nuse std::os::linux::fs::MetadataExt;\n\n#[cfg(not(target_os = \"linux\"))]\n\nuse std::os::unix::fs::MetadataExt;\n\n\n\nuse crate::error::CliError;\n\nuse cylinder::{secp256k1::Secp256k1Context, Context};\n\n\n\nuse super::chown;\n\n\n", "file_path": "cli/src/actions/keygen.rs", "rank": 31, "score": 6.9210202510153795 }, { "content": "\n\n#[cfg(feature = \"integration\")]\n\nuse grid_sdk::rest_api::actix_web_3::State as IntegrationState;\n\nuse grid_sdk::store::{create_store_factory, ConnectionUri};\n\n\n\nuse crate::config::GridConfig;\n\nuse crate::database::{ConnectionPool, DatabaseError};\n\nuse crate::error::DaemonError;\n\nuse crate::event::{db_handler::DatabaseEventHandler, EventProcessor};\n\nuse crate::rest_api;\n\n\n\nuse super::{batch_submitter::SawtoothBatchSubmitter, connection::SawtoothConnection};\n\n\n", "file_path": "daemon/src/sawtooth/run.rs", "rank": 32, "score": 6.904808028498756 }, { "content": "\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use grid_sdk::protocol::schema::payload::{Action, SchemaPayload};\n\n use grid_sdk::protocol::schema::state::{\n\n DataType, PropertyDefinition, PropertyDefinitionBuilder,\n\n };\n\n use std::env;\n\n use std::fs::{remove_file, File};\n\n use std::io::Write;\n\n use std::panic;\n\n use std::thread;\n\n\n\n static LIGHTBULB_YAML_EXAMPLE: &[u8; 800] = br##\"- name: \"Lightbulb\"\n\n description: \"Example Lightbulb schema\"\n\n properties:\n\n - name: \"size\"\n\n data_type: NUMBER\n\n description: \"Lightbulb radius, in millimeters\"\n", "file_path": "cli/src/actions/schemas.rs", "rank": 33, "score": 6.854873897482362 }, { "content": "use crate::config::Endpoint;\n\npub use crate::rest_api::error::RestApiServerError;\n\n\n\n#[cfg(feature = \"pike\")]\n\nuse crate::rest_api::routes::{fetch_agent, fetch_organization, list_agents, list_organizations};\n\n#[cfg(feature = \"schema\")]\n\nuse crate::rest_api::routes::{fetch_grid_schema, list_grid_schemas};\n\n#[cfg(feature = \"location\")]\n\nuse crate::rest_api::routes::{fetch_location, list_locations};\n\n#[cfg(feature = \"product\")]\n\nuse crate::rest_api::routes::{fetch_product, list_products};\n\n#[cfg(feature = \"track-and-trace\")]\n\nuse crate::rest_api::routes::{fetch_record, fetch_record_property, list_records};\n\n\n\nuse crate::rest_api::routes::{get_batch_statuses, submit_batches};\n\n\n\nuse crate::submitter::BatchSubmitter;\n\nuse actix::{Addr, SyncArbiter};\n\nuse actix_web::{\n\n dev,\n", "file_path": "daemon/src/rest_api/mod.rs", "rank": 34, "score": 6.838002326200162 }, { "content": " use crate::submitter::*;\n\n\n\n use actix_web::{\n\n http,\n\n test::{start, TestServer},\n\n web, App,\n\n };\n\n use diesel::Connection;\n\n #[cfg(feature = \"test-postgres\")]\n\n use diesel::PgConnection;\n\n #[cfg(not(feature = \"test-postgres\"))]\n\n use diesel::SqliteConnection;\n\n use futures::prelude::*;\n\n #[cfg(feature = \"test-postgres\")]\n\n use grid_sdk::migrations::{clear_postgres_database, run_postgres_migrations};\n\n #[cfg(not(feature = \"test-postgres\"))]\n\n use grid_sdk::migrations::{clear_sqlite_database, run_sqlite_migrations};\n\n #[cfg(feature = \"track-and-trace\")]\n\n use grid_sdk::track_and_trace::store::{\n\n diesel::DieselTrackAndTraceStore, AssociatedAgent, LatLongValue, Property, Proposal,\n", "file_path": "daemon/src/rest_api/routes/mod.rs", "rank": 35, "score": 6.826072405767404 }, { "content": "use grid_sdk::protocol::product::payload::{\n\n Action, ProductCreateAction, ProductCreateActionBuilder, ProductDeleteAction,\n\n ProductPayloadBuilder, ProductUpdateAction, ProductUpdateActionBuilder,\n\n};\n\nuse grid_sdk::protocol::product::state::ProductNamespace;\n\nuse grid_sdk::protocol::schema::state::{LatLongBuilder, PropertyValue, PropertyValueBuilder};\n\nuse grid_sdk::protos::IntoProto;\n\nuse grid_sdk::schemas::addressing::GRID_SCHEMA_NAMESPACE;\n\nuse reqwest::Client;\n\n\n\nuse crate::error::CliError;\n\nuse serde::Deserialize;\n\n\n\nuse std::{\n\n collections::HashMap,\n\n fs::File,\n\n io::prelude::*,\n\n time::{SystemTime, UNIX_EPOCH},\n\n};\n\n\n", "file_path": "cli/src/actions/products.rs", "rank": 36, "score": 6.811538286040184 }, { "content": "use std::cell::RefCell;\n\nuse std::thread;\n\n\n\n#[cfg(feature = \"pike\")]\n\nuse grid_sdk::pike::addressing::PIKE_NAMESPACE;\n\n\n\ncfg_if! {\n\n if #[cfg(feature = \"schema\")] {\n\n use grid_sdk::schemas::addressing::GRID_NAMESPACE;\n\n } else if #[cfg(feature = \"product\")] {\n\n use grid_sdk::products::addressing::GRID_NAMESPACE;\n\n } else if #[cfg(feature = \"location\")] {\n\n use grid_sdk::locations::addressing::GRID_NAMESPACE;\n\n }\n\n}\n\n\n\n#[cfg(feature = \"track-and-trace\")]\n\nuse grid_sdk::track_and_trace::addressing::TRACK_AND_TRACE_NAMESPACE;\n\n\n\nuse grid_sdk::commits::store::{CommitEvent as DbCommitEvent, StateChange as DbStateChange};\n", "file_path": "daemon/src/event/mod.rs", "rank": 37, "score": 6.789407790056323 }, { "content": "use super::{\n\n Agent, AgentList, Organization, OrganizationList, OrganizationMetadata, PikeStore,\n\n PikeStoreError, Role,\n\n};\n\nuse crate::error::ResourceTemporarilyUnavailableError;\n\nuse models::{make_org_metadata_models, make_role_models};\n\nuse operations::add_agent::PikeStoreAddAgentOperation as _;\n\nuse operations::add_organization::PikeStoreAddOrganizationOperation as _;\n\nuse operations::fetch_agent::PikeStoreFetchAgentOperation as _;\n\nuse operations::fetch_organization::PikeStoreFetchOrganizationOperation as _;\n\nuse operations::list_agents::PikeStoreListAgentsOperation as _;\n\nuse operations::list_organizations::PikeStoreListOrganizationsOperation as _;\n\nuse operations::update_agent::PikeStoreUpdateAgentOperation as _;\n\nuse operations::PikeStoreOperations;\n\n\n\n/// Manages creating agents in the database\n\n#[derive(Clone)]\n\npub struct DieselPikeStore<C: diesel::Connection + 'static> {\n\n connection_pool: Pool<ConnectionManager<C>>,\n\n}\n", "file_path": "sdk/src/pike/store/diesel/mod.rs", "rank": 38, "score": 6.77872755408314 }, { "content": "/*\n\n * Copyright 2019 Cargill Incorporated\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n * -----------------------------------------------------------------------------\n\n */\n\n\n\nuse crate::CliError;\n\nuse protobuf::Message;\n\nuse reqwest::Client;\n\nuse sawtooth_sdk::messages::batch::BatchList;\n\nuse serde::Deserialize;\n\nuse std::collections::HashMap;\n\nuse std::time::Instant;\n\n\n", "file_path": "cli/src/http.rs", "rank": 39, "score": 6.773236179390198 }, { "content": " }\n\n Ok(None)\n\n }\n\n None => Ok(None),\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n use std::cell::RefCell;\n\n use std::collections::HashMap;\n\n\n\n use grid_sdk::protocol::product::state::{ProductBuilder, ProductNamespace};\n\n use grid_sdk::protocol::schema::state::{DataType, PropertyValue, PropertyValueBuilder};\n\n\n\n use sawtooth_sdk::processor::handler::{ContextError, TransactionContext};\n\n\n", "file_path": "contracts/product/src/state.rs", "rank": 40, "score": 6.76653656961521 }, { "content": "use super::diesel::models::{\n\n LocationAttributeModel, LocationModel, NewLocationAttributeModel, NewLocationModel,\n\n};\n\nuse super::{\n\n LatLongValue, Location, LocationAttribute, LocationList, LocationStore, LocationStoreError,\n\n};\n\nuse crate::commits::MAX_COMMIT_NUM;\n\nuse crate::error::ResourceTemporarilyUnavailableError;\n\n\n\nuse operations::add_location::LocationStoreAddLocationOperation as _;\n\nuse operations::delete_location::LocationStoreDeleteLocationOperation as _;\n\nuse operations::fetch_location::LocationStoreFetchLocationOperation as _;\n\nuse operations::list_locations::LocationStoreListLocationsOperation as _;\n\nuse operations::update_location::LocationStoreUpdateLocationOperation as _;\n\nuse operations::LocationStoreOperations;\n\n\n\n/// Manages creating organizations in the database\n\n#[derive(Clone)]\n\npub struct DieselLocationStore<C: diesel::Connection + 'static> {\n\n connection_pool: Pool<ConnectionManager<C>>,\n", "file_path": "sdk/src/locations/store/diesel/mod.rs", "rank": 41, "score": 6.719608781060204 }, { "content": " use sabre_sdk::TransactionHandler;\n\n use sabre_sdk::TpProcessRequest;\n\n use sabre_sdk::{WasmPtr, execute_entrypoint};\n\n } else {\n\n use sawtooth_sdk::processor::handler::ApplyError;\n\n use sawtooth_sdk::processor::handler::TransactionContext;\n\n use sawtooth_sdk::processor::handler::TransactionHandler;\n\n use sawtooth_sdk::messages::processor::TpProcessRequest;\n\n }\n\n}\n\n\n\nuse grid_sdk::{\n\n pike::addressing::PIKE_NAMESPACE,\n\n protocol::{\n\n errors::BuilderError,\n\n schema::state::{PropertyDefinition, PropertyValue},\n\n track_and_trace::{\n\n payload::{\n\n Action, AnswerProposalAction, CreateProposalAction, CreateRecordAction,\n\n FinalizeRecordAction, Response, RevokeReporterAction, TrackAndTracePayload,\n", "file_path": "contracts/track_and_trace/src/handler.rs", "rank": 42, "score": 6.709312845555709 }, { "content": " parse_value_as_string, parse_value_as_vec_string,\n\n};\n\nuse grid_sdk::pike::addressing::PIKE_NAMESPACE;\n\nuse grid_sdk::protocol::schema::payload::{\n\n Action, SchemaCreateAction, SchemaCreateBuilder, SchemaPayload, SchemaPayloadBuilder,\n\n SchemaUpdateAction, SchemaUpdateBuilder,\n\n};\n\nuse grid_sdk::protocol::schema::state::{\n\n DataType as StateDataType, PropertyDefinition, PropertyDefinitionBuilder,\n\n};\n\nuse grid_sdk::protos::IntoProto;\n\nuse grid_sdk::schemas::addressing::GRID_SCHEMA_NAMESPACE;\n\nuse reqwest::Client;\n\n\n\nuse serde::Deserialize;\n\nuse serde_yaml::{Mapping, Value};\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct GridSchemaSlice {\n\n pub name: String,\n", "file_path": "cli/src/actions/schemas.rs", "rank": 43, "score": 6.701407165831927 }, { "content": "use cylinder::{load_key, secp256k1::Secp256k1Context, Context, PrivateKey};\n\nuse protobuf::Message;\n\nuse sabre_sdk::{\n\n protocol::payload::ExecuteContractActionBuilder, protos::IntoBytes as SabreIntoBytes,\n\n};\n\nuse sawtooth_sdk::messages::{batch, transaction};\n\n\n\nuse super::payloads::{Batch, SubmitBatchRequest, SubmitBatchResponse};\n\nuse crate::batches::{\n\n store::{Batch as DbBatch, BatchStoreError},\n\n BatchStore,\n\n};\n\nuse crate::protos::IntoBytes;\n\nuse crate::rest_api::resources::error::ErrorResponse;\n\n\n\nconst SABRE_FAMILY_NAME: &str = \"sabre\";\n\nconst SABRE_FAMILY_VERSION: &str = \"0.5\";\n\nconst SABRE_NAMESPACE_REGISTRY_PREFIX: &str = \"00ec00\";\n\nconst SABRE_CONTRACT_REGISTRY_PREFIX: &str = \"00ec01\";\n\nconst SABRE_CONTRACT_PREFIX: &str = \"00ec02\";\n", "file_path": "sdk/src/rest_api/resources/submit/v1/handler.rs", "rank": 44, "score": 6.669969880460968 }, { "content": " use sabre_sdk::TransactionHandler;\n\n use sabre_sdk::TpProcessRequest;\n\n use sabre_sdk::{WasmPtr, execute_entrypoint};\n\n } else {\n\n use sawtooth_sdk::processor::handler::ApplyError;\n\n use sawtooth_sdk::processor::handler::TransactionContext;\n\n use sawtooth_sdk::processor::handler::TransactionHandler;\n\n use sawtooth_sdk::messages::processor::TpProcessRequest;\n\n }\n\n}\n\n\n\nuse grid_sdk::{\n\n permissions::PermissionChecker,\n\n pike::addressing::{compute_agent_address, compute_organization_address, PIKE_NAMESPACE},\n\n protos::{\n\n pike_payload::{\n\n CreateAgentAction, CreateOrganizationAction, PikePayload, PikePayload_Action as Action,\n\n UpdateAgentAction, UpdateOrganizationAction,\n\n },\n\n pike_state::{Agent, AgentList, Organization, OrganizationList},\n", "file_path": "contracts/pike/src/handler.rs", "rank": 45, "score": 6.669969880460968 }, { "content": "use super::diesel::models::BatchModel;\n\nuse super::{Batch, BatchList, BatchStatus, BatchStore, BatchStoreError};\n\nuse crate::error::ResourceTemporarilyUnavailableError;\n\n\n\nuse operations::add_batch::AddBatchOperation as _;\n\nuse operations::fetch_batch::FetchBatchOperation as _;\n\nuse operations::list_batches::ListBatchesOperation as _;\n\nuse operations::list_batches_with_status::ListBatchesWithStatusOperation as _;\n\nuse operations::update_status::UpdateStatusOperation as _;\n\nuse operations::BatchStoreOperations;\n\n\n\n#[derive(Clone)]\n\npub struct DieselBatchStore<C: diesel::Connection + 'static> {\n\n connection_pool: Pool<ConnectionManager<C>>,\n\n}\n\n\n\nimpl<C: diesel::Connection> DieselBatchStore<C> {\n\n #[allow(dead_code)]\n\n pub fn new(connection_pool: Pool<ConnectionManager<C>>) -> Self {\n\n DieselBatchStore { connection_pool }\n", "file_path": "sdk/src/batches/store/diesel/mod.rs", "rank": 46, "score": 6.662585061719142 }, { "content": "\n\n#[cfg(feature = \"postgres\")]\n\nuse grid_sdk::migrations::run_postgres_migrations;\n\n\n\nuse crate::error::CliError;\n\n\n\n#[cfg(feature = \"sqlite\")]\n\nuse self::sqlite::sqlite_migrations;\n\n\n\n// Allow unused_variables here because database_url is not used if no database is configured\n\n#[allow(unused_variables)]\n", "file_path": "cli/src/actions/database/mod.rs", "rank": 47, "score": 6.658302839734737 }, { "content": "/*\n\n * Copyright 2017 Intel Corporation\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n * ------------------------------------------------------------------------------\n\n */\n\n\n\nextern crate glob;\n\nextern crate protoc_rust;\n\n\n\nuse std::env;\n\nuse std::fs;\n\nuse std::fs::File;\n\nuse std::io::Write;\n\nuse std::path::Path;\n\n\n\nuse protoc_rust::Customize;\n\n\n", "file_path": "sdk/build.rs", "rank": 48, "score": 6.652700165989958 }, { "content": "mod tests {\n\n use super::*;\n\n\n\n use std::cell::RefCell;\n\n use std::collections::HashMap;\n\n\n\n use grid_sdk::protocol::pike::state::{AgentBuilder, AgentListBuilder};\n\n use grid_sdk::protocol::schema::state::{DataType, PropertyDefinitionBuilder, SchemaBuilder};\n\n use sawtooth_sdk::processor::handler::{ContextError, TransactionContext};\n\n\n\n #[derive(Default)]\n\n /// A MockTransactionContext that can be used to test GridSchemaState\n\n struct MockTransactionContext {\n\n state: RefCell<HashMap<String, Vec<u8>>>,\n\n }\n\n\n\n impl TransactionContext for MockTransactionContext {\n\n fn get_state_entries(\n\n &self,\n\n addresses: &[String],\n", "file_path": "contracts/schema/src/state.rs", "rank": 49, "score": 6.643818328689553 }, { "content": "use std::os::unix::fs::OpenOptionsExt;\n\nuse std::path::PathBuf;\n\n\n\nuse sawtooth_sdk::signing;\n\n\n\nuse crate::error::CliError;\n\n\n\nconst DEFAULT_KEY_DIR: &str = \"/etc/grid/keys\";\n\n\n\npub enum ConflictStrategy {\n\n Force,\n\n Skip,\n\n Error,\n\n}\n\n\n", "file_path": "cli/src/actions/admin.rs", "rank": 50, "score": 6.627267734725892 }, { "content": "extern crate cfg_if;\n\n#[macro_use]\n\nextern crate clap;\n\nextern crate diesel;\n\nextern crate diesel_migrations;\n\n#[macro_use]\n\nextern crate log;\n\n#[cfg(feature = \"serde_json\")]\n\n#[macro_use]\n\nextern crate serde_json;\n\n#[cfg(feature = \"serde\")]\n\n#[macro_use]\n\nextern crate serde;\n\n\n\nmod config;\n\n#[cfg(feature = \"database\")]\n\nmod database;\n\nmod error;\n\n#[cfg(feature = \"event\")]\n\n#[macro_use]\n", "file_path": "daemon/src/main.rs", "rank": 51, "score": 6.610303284229328 }, { "content": "\n\nuse grid_sdk::{\n\n locations::addressing::GRID_LOCATION_NAMESPACE,\n\n pike::addressing::PIKE_NAMESPACE,\n\n protocol::{\n\n location::payload::{\n\n Action, LocationCreateAction, LocationCreateActionBuilder, LocationDeleteAction,\n\n LocationNamespace, LocationPayloadBuilder, LocationUpdateAction,\n\n LocationUpdateActionBuilder,\n\n },\n\n schema::state::{LatLongBuilder, PropertyValue, PropertyValueBuilder},\n\n },\n\n protos::IntoProto,\n\n};\n\nuse reqwest::Client;\n\nuse serde::Deserialize;\n\n\n\nuse crate::actions::Paging;\n\nuse crate::error::CliError;\n\nuse crate::http::submit_batches;\n\nuse crate::{\n\n actions::schemas::{self, get_schema, GridPropertyDefinitionSlice},\n\n transaction::location_batch_builder,\n\n};\n\n\n", "file_path": "cli/src/actions/locations.rs", "rank": 52, "score": 6.608526877664698 }, { "content": "// Copyright 2018-2020 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse super::PikeStoreOperations;\n\nuse crate::commits::MAX_COMMIT_NUM;\n\nuse crate::error::InternalError;\n\nuse crate::paging::Paging;\n\nuse crate::pike::store::diesel::models::{OrganizationMetadataModel, OrganizationModel};\n\nuse crate::pike::store::diesel::{\n", "file_path": "sdk/src/pike/store/diesel/operations/list_organizations.rs", "rank": 53, "score": 6.591021378817006 }, { "content": "use super::{Commit, CommitEvent, CommitEventError, CommitStore, CommitStoreError};\n\nuse crate::commits::store::diesel::models::{CommitModel, NewCommitModel};\n\nuse crate::error::{\n\n ConstraintViolationError, ConstraintViolationType, InternalError,\n\n ResourceTemporarilyUnavailableError,\n\n};\n\nuse operations::add_commit::CommitStoreAddCommitOperation as _;\n\nuse operations::create_db_commit_from_commit_event::CommitStoreCreateDbCommitFromCommitEventOperation as _;\n\nuse operations::get_commit_by_commit_num::CommitStoreGetCommitByCommitNumOperation as _;\n\nuse operations::get_current_commit_id::CommitStoreGetCurrentCommitIdOperation as _;\n\nuse operations::get_next_commit_num::CommitStoreGetNextCommitNumOperation as _;\n\nuse operations::resolve_fork::CommitStoreResolveForkOperation as _;\n\nuse operations::CommitStoreOperations;\n\n\n\n/// Manages creating commits in the database\n\n#[derive(Clone)]\n\npub struct DieselCommitStore<C: diesel::Connection + 'static> {\n\n connection_pool: Pool<ConnectionManager<C>>,\n\n}\n\n\n", "file_path": "sdk/src/commits/store/diesel/mod.rs", "rank": 54, "score": 6.582723288267848 }, { "content": "// Copyright 2018-2021 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse std::path::PathBuf;\n\nuse std::sync::Arc;\n\nuse std::time::Instant;\n\n\n\nuse crypto::digest::Digest;\n\nuse crypto::sha2::Sha512;\n", "file_path": "sdk/src/rest_api/resources/submit/v1/handler.rs", "rank": 55, "score": 6.578686216855525 }, { "content": "// Copyright 2018-2020 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse std::collections::HashMap;\n\nuse std::convert::TryInto;\n\nuse std::sync::{Arc, Mutex};\n\n\n\nuse super::CommitStore;\n\nuse crate::commits::store::{\n", "file_path": "sdk/src/commits/store/memory.rs", "rank": 57, "score": 6.568555435415536 }, { "content": "// Copyright 2018-2021 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse protobuf::Message;\n\nuse protobuf::RepeatedField;\n\n\n\nuse crate::protos;\n\nuse crate::protos::{location_payload, location_payload::LocationPayload_Action};\n\nuse crate::protos::{\n", "file_path": "sdk/src/rest_api/resources/submit/v1/payloads/location.rs", "rank": 58, "score": 6.558455807590107 }, { "content": "// Copyright 2018-2021 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse protobuf::Message;\n\nuse protobuf::RepeatedField;\n\n\n\nuse crate::protos;\n\nuse crate::protos::{product_payload, product_payload::ProductPayload_Action};\n\nuse crate::protos::{\n", "file_path": "sdk/src/rest_api/resources/submit/v1/payloads/product.rs", "rank": 59, "score": 6.558455807590107 }, { "content": " product_store,\n\n schema_store,\n\n tnt_store,\n\n }\n\n }\n\n}\n\n\n\n#[cfg(all(test, feature = \"stable\"))]\n\nmod test {\n\n use super::*;\n\n use crate::config::Endpoint;\n\n use crate::database;\n\n use crate::rest_api::{\n\n error::RestApiResponseError,\n\n routes::{AgentListSlice, AgentSlice, OrganizationListSlice, OrganizationSlice},\n\n AppState,\n\n };\n\n use crate::sawtooth::batch_submitter::{\n\n process_batch_status_response, process_validator_response, query_validator,\n\n };\n", "file_path": "daemon/src/rest_api/routes/mod.rs", "rank": 60, "score": 6.549404537306905 }, { "content": "// Copyright 2019 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse std::pin::Pin;\n\nuse std::time::Duration;\n\n\n\nuse futures::prelude::*;\n\nuse sawtooth_sdk::messages::batch::Batch;\n\nuse sawtooth_sdk::messages::client_batch_submit::{\n", "file_path": "daemon/src/sawtooth/batch_submitter.rs", "rank": 61, "score": 6.5483871898970625 }, { "content": "// Copyright (c) 2019 Target Brands, Inc.\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse crate::actions::schemas::{self, get_schema, GridPropertyDefinitionSlice};\n\nuse crate::actions::Paging;\n\nuse crate::http::submit_batches;\n\nuse crate::transaction::product_batch_builder;\n\nuse grid_sdk::pike::addressing::PIKE_NAMESPACE;\n\nuse grid_sdk::products::addressing::GRID_PRODUCT_NAMESPACE;\n", "file_path": "cli/src/actions/products.rs", "rank": 62, "score": 6.547660706659159 }, { "content": "// Copyright 2019 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse std::pin::Pin;\n\n\n\nuse futures::prelude::*;\n\nuse sawtooth_sdk::messages::batch::BatchList;\n\nuse sawtooth_sdk::messages::client_batch_submit::ClientBatchStatus;\n\nuse url::Url;\n\n\n\nuse crate::rest_api::error::RestApiResponseError;\n\n\n\npub const DEFAULT_TIME_OUT: u32 = 300; // Max timeout 300 seconds == 5 minutes\n\n\n", "file_path": "daemon/src/submitter.rs", "rank": 64, "score": 6.521917075265385 }, { "content": "#[cfg(feature = \"location\")]\n\nuse grid_sdk::locations::addressing::GRID_LOCATION_NAMESPACE;\n\n#[cfg(feature = \"pike\")]\n\nuse grid_sdk::pike::addressing::PIKE_NAMESPACE;\n\n#[cfg(feature = \"product\")]\n\nuse grid_sdk::products::addressing::GRID_PRODUCT_NAMESPACE;\n\n#[cfg(feature = \"schema\")]\n\nuse grid_sdk::schemas::addressing::GRID_SCHEMA_NAMESPACE;\n\n\n\nuse sabre_sdk::protocol::payload::{\n\n CreateContractActionBuilder, CreateContractRegistryActionBuilder,\n\n CreateNamespaceRegistryActionBuilder, CreateNamespaceRegistryPermissionActionBuilder,\n\n};\n\nuse sawtooth_sdk::signing::{\n\n create_context, secp256k1::Secp256k1PrivateKey, transact::TransactSigner,\n\n Signer as SawtoothSigner,\n\n};\n\nuse scabbard::client::{ScabbardClient, ServiceId};\n\n#[cfg(any(\n\n feature = \"location\",\n", "file_path": "daemon/src/splinter/app_auth_handler/sabre.rs", "rank": 65, "score": 6.521917075265385 }, { "content": "use futures::prelude::*;\n\nuse protobuf::Message;\n\nuse sawtooth_sdk::messages::batch::Batch;\n\n\n\nuse crate::rest_api::error::RestApiResponseError;\n\nuse crate::submitter::{\n\n BatchStatus, BatchStatusLink, BatchStatuses, BatchSubmitter, InvalidTransaction, SubmitBatches,\n\n};\n\n\n\nmacro_rules! try_fut {\n\n ($try_expr:expr) => {\n\n match $try_expr {\n\n Ok(res) => res,\n\n Err(err) => return futures::future::err(err).boxed(),\n\n }\n\n };\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct SplinterBatchSubmitter {\n", "file_path": "daemon/src/splinter/batch_submitter.rs", "rank": 66, "score": 6.513400928603957 }, { "content": " };\n\n self.context\n\n .set_state_entry(address, serialized)\n\n .map_err(|err| ApplyError::InternalError(format!(\"{}\", err)))?;\n\n Ok(())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n use std::cell::RefCell;\n\n use std::collections::HashMap;\n\n\n\n use grid_sdk::protocol::pike::state::{AgentBuilder, AgentListBuilder};\n\n use grid_sdk::protocol::schema::state::{\n\n DataType, PropertyDefinition, PropertyDefinitionBuilder, PropertyValue,\n\n PropertyValueBuilder,\n\n };\n", "file_path": "contracts/track_and_trace/src/state.rs", "rank": 67, "score": 6.501487529369916 }, { "content": "//!\n\n//! ```\n\n//! use std::error;\n\n//! use std::fmt;\n\n//! use std::fs;\n\n//!\n\n//! use grid_sdk::error::InternalError;\n\n//!\n\n//! #[derive(Debug)]\n\n//! enum MyError {\n\n//! InternalError(InternalError),\n\n//! MissingFilenameExtension,\n\n//! }\n\n//!\n\n//! impl error::Error for MyError {}\n\n//!\n\n//! impl fmt::Display for MyError {\n\n//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n//! match self {\n\n//! MyError::InternalError(e) => write!(f, \"{}\", e),\n", "file_path": "sdk/src/error/mod.rs", "rank": 68, "score": 6.491116497484413 }, { "content": "mod tests {\n\n use super::*;\n\n\n\n use std::cell::RefCell;\n\n use std::collections::HashMap;\n\n\n\n use grid_sdk::{\n\n pike::addressing::compute_agent_address,\n\n protocol::{\n\n pike::state::{AgentBuilder, AgentListBuilder},\n\n schema::{\n\n payload::{SchemaCreateBuilder, SchemaUpdateBuilder},\n\n state::{DataType, PropertyDefinitionBuilder, SchemaBuilder, SchemaListBuilder},\n\n },\n\n },\n\n protos::IntoBytes,\n\n schemas::addressing::compute_schema_address,\n\n };\n\n\n\n use sawtooth_sdk::processor::handler::ApplyError;\n", "file_path": "contracts/schema/src/handler.rs", "rank": 69, "score": 6.477790996287012 }, { "content": "\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n use sawtooth_sdk::messages::events::Event_Attribute;\n\n\n\n #[cfg(feature = \"schema\")]\n\n use grid_sdk::schemas::addressing::GRID_SCHEMA_NAMESPACE;\n\n\n\n #[cfg(feature = \"product\")]\n\n use grid_sdk::products::addressing::GRID_PRODUCT_NAMESPACE;\n\n\n\n #[cfg(feature = \"location\")]\n\n use grid_sdk::locations::addressing::GRID_LOCATION_NAMESPACE;\n\n\n\n /// Verify that a valid set of Sawtooth events can be converted to a `CommitEvent`.\n\n #[test]\n\n fn sawtooth_events_to_commit_event() {\n\n let block_id = \"abcdef\";\n", "file_path": "daemon/src/sawtooth/event.rs", "rank": 70, "score": 6.477790996287012 }, { "content": "/*\n\n * Copyright 2020 Cargill Incorporated\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n * -----------------------------------------------------------------------------\n\n */\n\nuse serde_json::Value;\n\nuse std::error::Error;\n\nuse std::fmt;\n\nuse std::thread;\n", "file_path": "daemon/src/splinter/app_auth_handler/node.rs", "rank": 71, "score": 6.4660073885123275 }, { "content": " } else {\n\n return false;\n\n };\n\n\n\n (check_digit + acc) % 10 == 0\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n use std::cell::RefCell;\n\n use std::collections::HashMap;\n\n\n\n use grid_sdk::{\n\n pike::addressing::{compute_agent_address, compute_organization_address},\n\n protocol::{\n\n location::payload::{\n\n LocationCreateActionBuilder, LocationDeleteActionBuilder,\n\n LocationUpdateActionBuilder,\n", "file_path": "contracts/location/src/handler.rs", "rank": 72, "score": 6.461616921768718 }, { "content": "// Copyright 2018-2021 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse super::BatchStoreOperations;\n\nuse crate::batches::store::diesel::models::BatchModel;\n\nuse crate::batches::store::{diesel::schema::batches, BatchStoreError};\n\nuse crate::error::InternalError;\n\n\n\nuse diesel::{dsl::insert_into, prelude::*};\n", "file_path": "sdk/src/batches/store/diesel/operations/add_batch.rs", "rank": 73, "score": 6.4591418422595375 }, { "content": "// Copyright 2018-2020 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse super::TrackAndTraceStoreOperations;\n\nuse crate::track_and_trace::store::diesel::{schema::record, TrackAndTraceStoreError};\n\n\n\nuse crate::commits::MAX_COMMIT_NUM;\n\nuse crate::error::InternalError;\n\nuse crate::paging::Paging;\n", "file_path": "sdk/src/track_and_trace/store/diesel/operations/list_records.rs", "rank": 74, "score": 6.4591418422595375 }, { "content": "// Copyright 2018-2021 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse super::BatchStoreOperations;\n\nuse crate::batches::store::{diesel::schema::batches, BatchStoreError};\n\n\n\nuse crate::batches::store::diesel::BatchModel;\n\nuse crate::error::InternalError;\n\nuse diesel::{prelude::*, result::Error::NotFound};\n", "file_path": "sdk/src/batches/store/diesel/operations/fetch_batch.rs", "rank": 75, "score": 6.4591418422595375 }, { "content": "};\n\n\n\nuse actix::{Handler, Message, SyncContext};\n\nuse actix_web::{web, HttpResponse};\n\nuse grid_sdk::pike::store::Agent;\n\nuse serde::{Deserialize, Serialize};\n\nuse serde_json::Value as JsonValue;\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct AgentSlice {\n\n pub public_key: String,\n\n pub org_id: String,\n\n pub active: bool,\n\n pub roles: Vec<String>,\n\n pub metadata: JsonValue,\n\n #[serde(default)]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub service_id: Option<String>,\n\n}\n\n\n", "file_path": "daemon/src/rest_api/routes/agents.rs", "rank": 76, "score": 6.454266573500085 }, { "content": " let mut inner_cr = self.inner_cr.lock().map_err(|_| {\n\n CommitStoreError::InternalError(InternalError::with_message(\n\n \"Cannot access chain_records: mutex lock poisoned\".to_string(),\n\n ))\n\n })?;\n\n\n\n inner_cr.retain(|_, v| v.start_commit_num.lt(&commit_num));\n\n\n\n for (_, v) in inner_cr.iter_mut() {\n\n if v.end_commit_num.ge(&commit_num) {\n\n v.end_commit_num = MAX_COMMIT_NUM;\n\n }\n\n }\n\n\n\n inner_commit.retain(|_, v| v.commit_num.lt(&commit_num));\n\n\n\n Ok(())\n\n }\n\n\n\n fn get_commit_by_commit_num(\n", "file_path": "sdk/src/commits/store/memory.rs", "rank": 77, "score": 6.452237247811089 }, { "content": "// Copyright 2019 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse protobuf::Message;\n\nuse protobuf::RepeatedField;\n\n\n\nuse std::default::Default;\n\n\n\nuse super::errors::BuilderError;\n", "file_path": "sdk/src/protocol/track_and_trace/payload.rs", "rank": 78, "score": 6.442568318566691 }, { "content": "// Copyright 2019 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse protobuf::Message;\n\nuse protobuf::RepeatedField;\n\n\n\nuse std::error::Error as StdError;\n\n\n\nuse crate::protos;\n", "file_path": "sdk/src/protocol/pike/state.rs", "rank": 79, "score": 6.442568318566691 }, { "content": "// Copyright 2018-2021 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse protobuf::Message;\n\nuse protobuf::RepeatedField;\n\n\n\nuse std::error::Error as StdError;\n\n\n\nuse crate::protos;\n", "file_path": "sdk/src/rest_api/resources/submit/v1/payloads/schema.rs", "rank": 80, "score": 6.442568318566691 }, { "content": "// Copyright 2020 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse protobuf::Message;\n\nuse protobuf::RepeatedField;\n\n\n\nuse std::error::Error as StdError;\n\n\n\nuse crate::protos;\n", "file_path": "sdk/src/protocol/location/state.rs", "rank": 81, "score": 6.442568318566691 }, { "content": "// Copyright 2019 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse protobuf::Message;\n\nuse protobuf::RepeatedField;\n\n\n\nuse std::error::Error as StdError;\n\n\n\nuse crate::protos;\n", "file_path": "sdk/src/protocol/schema/state.rs", "rank": 82, "score": 6.442568318566691 }, { "content": "use users::get_current_username;\n\n\n\nuse sawtooth_sdk::signing::secp256k1::Secp256k1PrivateKey;\n\n\n\nuse crate::error::CliError;\n\n\n\n/// Return a signing key loaded from the user's environment\n\n///\n\n/// This method attempts to load the user's key from a file. The filename\n\n/// is constructed by appending \".priv\" to the key's name. If the name argument\n\n/// is None, then the USER environment variable is used in its place.\n\n///\n\n/// The directory containing the keys is determined using the HOME\n\n/// environment variable:\n\n///\n\n/// $HOME/.grid/keys/\n\n///\n\n/// # Arguments\n\n///\n\n/// * `name` - The name of the signing key, which is used to construct the\n\n/// key's filename\n\n///\n\n/// # Errors\n\n///\n\n/// If a signing error occurs, a CliError::SigningError is returned.\n\n///\n\n/// If a HOME or USER environment variable is required but cannot be\n\n/// retrieved from the environment, a CliError::VarError is returned.\n", "file_path": "cli/src/key.rs", "rank": 83, "score": 6.4396388954450305 }, { "content": "// Copyright 2018-2020 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse std::error::Error;\n\nuse std::fmt;\n\n#[cfg(feature = \"batch-store\")]\n\nuse std::fmt::Write;\n\n\n\nuse serde::de;\n\nuse serde::Deserializer;\n\n\n\n/// Converts a byte array into a hex string\n\n///\n\n/// # Arguments\n\n///\n\n/// * `bytes`: the byte array to convert\n\n#[cfg(feature = \"batch-store\")]\n", "file_path": "sdk/src/hex.rs", "rank": 84, "score": 6.4396388954450305 }, { "content": "use super::diesel::models::{\n\n AssociatedAgentModel, NewAssociatedAgentModel, NewPropertyModel, NewProposalModel,\n\n NewRecordModel, NewReportedValueModel, NewReporterModel, PropertyModel, ProposalModel,\n\n RecordModel, ReportedValueReporterToAgentMetadataModel, ReporterModel,\n\n};\n\nuse super::{\n\n AssociatedAgent, LatLongValue, Property, Proposal, Record, RecordList, ReportedValue,\n\n ReportedValueReporterToAgentMetadata, Reporter, TrackAndTraceStore, TrackAndTraceStoreError,\n\n};\n\nuse crate::error::{\n\n ConstraintViolationError, ConstraintViolationType, InternalError,\n\n ResourceTemporarilyUnavailableError,\n\n};\n\nuse operations::add_associated_agents::TrackAndTraceStoreAddAssociatedAgentsOperation as _;\n\nuse operations::add_properties::TrackAndTraceStoreAddPropertiesOperation as _;\n\nuse operations::add_proposals::TrackAndTraceStoreAddProposalsOperation as _;\n\nuse operations::add_records::TrackAndTraceStoreAddRecordsOperation as _;\n\nuse operations::add_reported_values::TrackAndTraceStoreAddReportedValuesOperation as _;\n\nuse operations::add_reporters::TrackAndTraceStoreAddReportersOperation as _;\n\nuse operations::fetch_property_with_data_type::TrackAndTraceStoreFetchPropertyWithDataTypeOperation as _;\n", "file_path": "sdk/src/track_and_trace/store/diesel/mod.rs", "rank": 85, "score": 6.433788033957935 }, { "content": "/*\n\n * Copyright 2019 Cargill Incorporated\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n * -----------------------------------------------------------------------------\n\n */\n\n\n\nuse std::ffi::CString;\n\nuse std::path::Path;\n\n\n\nuse super::error::CliError;\n\n\n\nuse serde::Deserialize;\n\n\n", "file_path": "cli/src/actions/mod.rs", "rank": 86, "score": 6.430912392712442 }, { "content": "// Copyright (c) 2019 Target Brands, Inc.\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse protobuf::Message;\n\nuse protobuf::RepeatedField;\n\n\n\nuse std::error::Error as StdError;\n\n\n\nuse crate::protos;\n", "file_path": "sdk/src/protocol/product/state.rs", "rank": 87, "score": 6.430912392712442 }, { "content": "/*\n\n * Copyright 2020 Cargill Incorporated\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n * -----------------------------------------------------------------------------\n\n */\n\n\n\nuse std::error::Error;\n\nuse std::fmt;\n\nuse std::io::Read;\n\nuse std::{fs::File, path::Path};\n\n\n", "file_path": "daemon/src/splinter/key.rs", "rank": 88, "score": 6.430912392712442 }, { "content": "// Copyright 2019 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse crate::actions::Paging;\n\nuse crate::error::CliError;\n\nuse crate::http::submit_batches;\n\nuse crate::transaction::schema_batch_builder;\n\nuse crate::yaml_parser::{\n\n parse_value_as_boolean, parse_value_as_data_type, parse_value_as_i32, parse_value_as_sequence,\n", "file_path": "cli/src/actions/schemas.rs", "rank": 89, "score": 6.420253369772393 }, { "content": "// Copyright 2020 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse protobuf::Message;\n\nuse protobuf::RepeatedField;\n\n\n\nuse std::error::Error as StdError;\n\n\n\nuse super::errors::BuilderError;\n", "file_path": "sdk/src/protocol/location/payload.rs", "rank": 90, "score": 6.41929856660632 }, { "content": "// Copyright 2018-2020 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse super::TrackAndTraceStoreOperations;\n\nuse crate::track_and_trace::store::diesel::{schema::record, TrackAndTraceStoreError};\n\n\n\nuse crate::commits::MAX_COMMIT_NUM;\n\nuse crate::error::InternalError;\n\nuse crate::track_and_trace::store::diesel::models::RecordModel;\n", "file_path": "sdk/src/track_and_trace/store/diesel/operations/fetch_record.rs", "rank": 91, "score": 6.410604308976709 }, { "content": "// Copyright 2018-2020 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse super::PikeStoreOperations;\n\nuse crate::commits::MAX_COMMIT_NUM;\n\nuse crate::error::InternalError;\n\nuse crate::pike::store::diesel::models::{OrganizationMetadataModel, OrganizationModel};\n\nuse crate::pike::store::diesel::{\n\n schema::{pike_organization, pike_organization_metadata},\n", "file_path": "sdk/src/pike/store/diesel/operations/fetch_organization.rs", "rank": 92, "score": 6.410604308976709 }, { "content": "// Copyright 2018-2020 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse super::TrackAndTraceStoreOperations;\n\nuse crate::track_and_trace::store::diesel::{schema::proposal, TrackAndTraceStoreError};\n\n\n\nuse crate::commits::MAX_COMMIT_NUM;\n\nuse crate::error::InternalError;\n\nuse crate::track_and_trace::store::diesel::models::ProposalModel;\n", "file_path": "sdk/src/track_and_trace/store/diesel/operations/list_proposals.rs", "rank": 93, "score": 6.410604308976709 }, { "content": "// Copyright 2018-2020 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse super::TrackAndTraceStoreOperations;\n\nuse crate::track_and_trace::store::diesel::{schema::reporter, TrackAndTraceStoreError};\n\n\n\nuse crate::commits::MAX_COMMIT_NUM;\n\nuse crate::error::InternalError;\n\nuse crate::track_and_trace::store::diesel::models::ReporterModel;\n", "file_path": "sdk/src/track_and_trace/store/diesel/operations/list_reporters.rs", "rank": 94, "score": 6.410604308976709 }, { "content": "// Copyright 2019 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse grid_sdk::protos;\n\nuse sawtooth_sdk::signing;\n\nuse std::error::Error as StdError;\n\nuse std::io;\n\n\n\n#[derive(Debug)]\n", "file_path": "cli/src/error.rs", "rank": 95, "score": 6.407726612570947 }, { "content": "// Copyright (c) 2019 Target Brands, Inc.\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse protobuf::Message;\n\nuse protobuf::RepeatedField;\n\n\n\nuse std::error::Error as StdError;\n\n\n\nuse super::errors::BuilderError;\n", "file_path": "sdk/src/protocol/product/payload.rs", "rank": 96, "score": 6.407726612570947 }, { "content": "// Copyright 2018-2020 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse super::CommitStoreOperations;\n\nuse crate::commits::store::diesel::{schema::chain_record, schema::commits};\n\nuse crate::commits::store::CommitStoreError;\n\nuse crate::commits::MAX_COMMIT_NUM;\n\nuse crate::error::{ConstraintViolationError, ConstraintViolationType, InternalError};\n\n\n", "file_path": "sdk/src/commits/store/diesel/operations/resolve_fork.rs", "rank": 97, "score": 6.400984207990369 }, { "content": "// Copyright 2018-2020 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse super::CommitStoreOperations;\n\nuse crate::commits::store::diesel::models::{CommitModel, NewCommitModel};\n\nuse crate::commits::store::diesel::{schema::commits, CommitStoreError};\n\nuse crate::error::{ConstraintViolationError, ConstraintViolationType, InternalError};\n\n\n\nuse diesel::{\n", "file_path": "sdk/src/commits/store/diesel/operations/add_commit.rs", "rank": 98, "score": 6.400984207990369 }, { "content": "// Copyright 2019 Cargill Incorporated\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse protobuf::Message;\n\nuse protobuf::RepeatedField;\n\n\n\nuse std::error::Error as StdError;\n\n\n\nuse crate::protocol::schema::state::PropertyDefinition;\n", "file_path": "sdk/src/protocol/schema/payload.rs", "rank": 99, "score": 6.396196304567715 } ]
Rust
thavalon-server/src/database/games/db_game.rs
theadd336/ThavalonWeb
cf5e9f80270cdab3d4d2d25fa8bc35748aa18f92
use crate::database::get_database; use crate::utils; use std::collections::{HashMap, HashSet}; use chrono::Utc; use mongodb::{ bson::{self, doc, oid::ObjectId, Document}, Collection, }; use serde::{Deserialize, Serialize}; use thiserror::Error; const GAME_COLLECTION: &str = "thavalon_games"; const FRIEND_CODE_LENGTH: usize = 4; #[derive(PartialEq, Error, Debug)] pub enum DBGameError { #[error("The game could not be created.")] CreationError, #[error("An error occurred while updating the game in the database.")] UpdateError, #[error("Invalid state for the requested update.")] InvalidStateError, #[error("The display name is already in use.")] DuplicateDisplayName, } #[derive(PartialEq, Serialize, Deserialize, Debug, Clone)] pub enum DBGameStatus { Lobby, InProgress, Finished, } impl Drop for DatabaseGame { fn drop(&mut self) { if self.status == DBGameStatus::Lobby { log::info!("Deleting game {}.", self.friend_code); let friend_code = self.friend_code.clone(); let _id = self._id.clone(); tokio::spawn(async move { let collection = DatabaseGame::get_collection().await; let doc = doc! { "_id": bson::to_bson(&_id).unwrap(), }; if let Err(e) = collection.delete_one(doc, None).await { log::error!("Error while deleting game {}. {}.", friend_code, e); } }); } } } #[derive(Debug, Serialize, Deserialize)] pub struct DatabaseGame { _id: ObjectId, friend_code: String, players: HashSet<String>, display_names: HashSet<String>, players_to_display_names: HashMap<String, String>, status: DBGameStatus, created_time: i64, start_time: Option<i64>, end_time: Option<i64>, snapshot_id: Option<String>, } impl DatabaseGame { pub async fn new() -> Result<Self, DBGameError> { log::info!("Creating a new database game."); let collection = DatabaseGame::get_collection().await; let _id: ObjectId = match collection.insert_one(doc! {}, None).await { Ok(result) => { bson::from_bson(result.inserted_id).expect("Could not deserialize new game _id.") } Err(e) => { log::error!("ERROR: failed to create new game. {}.", e); return Err(DBGameError::CreationError); } }; let friend_code = utils::generate_letter_string(FRIEND_CODE_LENGTH); let game = DatabaseGame { friend_code, _id, players: HashSet::with_capacity(10), display_names: HashSet::with_capacity(10), players_to_display_names: HashMap::with_capacity(10), status: DBGameStatus::Lobby, created_time: Utc::now().timestamp(), start_time: None, end_time: None, snapshot_id: None, }; collection .replace_one( doc! {"_id": &game._id}, bson::to_document(&game).unwrap(), None, ) .await .unwrap(); log::info!("Successfully created DB entry for game {}.", game._id); Ok(game) } pub async fn start_game(&mut self) -> Result<(), DBGameError> { log::info!("Starting DB game {}.", self._id); self.start_time = Some(Utc::now().timestamp()); self.status = DBGameStatus::InProgress; let update_doc = doc! { "$set": { "start_time": bson::to_bson(&self.start_time).unwrap(), "status": bson::to_bson(&self.status).unwrap(), "snapshot_id": bson::to_bson(&self.snapshot_id).unwrap(), } }; self.update_db(update_doc).await } pub async fn end_game(&mut self) -> Result<(), DBGameError> { self.friend_code.clear(); self.end_time = Some(Utc::now().timestamp()); self.status = DBGameStatus::Finished; let update_doc = doc! { "$set": { "friend_code": bson::to_bson(&self.friend_code).unwrap(), "end_time": bson::to_bson(&self.end_time).unwrap(), "status": bson::to_bson(&self.status).unwrap() } }; self.update_db(update_doc).await } pub async fn add_player( &mut self, player_id: String, display_name: String, ) -> Result<(), DBGameError> { log::info!("Adding player {} to game {}.", player_id, self._id); if self.status != DBGameStatus::Lobby { log::error!( "Attempted to add player {} to game {} while in state {:?}. Players may only be added during the Lobby phase.", player_id, self._id, self.status ); return Err(DBGameError::InvalidStateError); } if self.display_names.contains(&display_name) { log::warn!( "Name {} is already in game {}. Display names must be unique.", display_name, self._id ); return Err(DBGameError::DuplicateDisplayName); } self.players.insert(player_id.clone()); self.display_names.insert(display_name.clone()); self.players_to_display_names .insert(player_id, display_name); let update_doc = doc! { "$set": { "players": bson::to_bson(&self.players).unwrap(), "display_names": bson::to_bson(&self.display_names).unwrap() } }; self.update_db(update_doc).await } pub async fn remove_player( &mut self, player_id: &String, ) -> Result<Option<String>, DBGameError> { log::info!("Removing player {} from game {}.", player_id, self._id); if self.status != DBGameStatus::Lobby { log::error!( "ERROR: attempted to remove player {} to game {} while in state {:?}. Players may only be removed during the Lobby phase.", player_id, self._id, self.status ); return Err(DBGameError::InvalidStateError); } self.players.remove(player_id); let display_name = match self.players_to_display_names.remove(player_id) { Some(name) => name, None => { log::warn!( "Tried to remove nonexistant player {} from game {}.", player_id, self._id ); return Ok(None); } }; self.display_names.remove(&display_name); self.players_to_display_names.remove(player_id); let update_doc = doc! { "$set": { "players": bson::to_bson(&self.players).unwrap(), "display_names": bson::to_bson(&self.display_names).unwrap() } }; self.update_db(update_doc).await?; Ok(Some(display_name)) } async fn get_collection() -> Collection { get_database().await.collection(GAME_COLLECTION) } async fn update_db(&self, update_doc: Document) -> Result<(), DBGameError> { let collection = DatabaseGame::get_collection().await; if let Err(e) = collection .update_one(doc! {"_id": &self._id}, update_doc, None) .await { log::error!("ERROR: failed to update database game. {}.", e); return Err(DBGameError::UpdateError); } log::info!("DB game {} updated successfully.", self._id); Ok(()) } pub fn get_friend_code(&self) -> &String { &self.friend_code } }
use crate::database::get_database; use crate::utils; use std::collections::{HashMap, HashSet}; use chrono::Utc; use mongodb::{ bson::{self, doc, oid::ObjectId, Document}, Collection, }; use serde::{Deserialize, Serialize}; use thiserror::Error; const GAME_COLLECTION: &str = "thavalon_games"; const FRIEND_CODE_LENGTH: usize = 4; #[derive(PartialEq, Error, Debug)] pub enum DBGameError { #[error("The game could not be created.")] CreationError, #[error("An error occurred while updating the game in the database.")] UpdateError, #[error("Invalid state for the requested update.")] InvalidStateError, #[error("The display name is already in use.")] DuplicateDisplayName, } #[derive(PartialEq, Serialize, Deserialize, Debug, Clone)] pub enum DBGameStatus { Lobby, InProgress, Finished, } impl Drop for DatabaseGame { fn drop(&mut self) { if self.status == DBGameStatus::Lobby { log::info!("Deleting game {}.", self.friend_code); let friend_code = self.friend_code.clone(); let _id = self._id.clone(); tokio::spawn(async move { let collection = DatabaseGame::get_collection().await; let doc = doc! { "_id": bson::to_bson(&_id).unwrap(), }; if let Err(e) = collection.delete_one(doc, None).await { log::error!("Error while deleting game {}. {}.", friend_code, e); } }); } } } #[derive(Debug, Serialize, Deserialize)] pub struct DatabaseGame { _id: ObjectId, friend_code: String, players: HashSet<String>, display_names: HashSet<String>, players_to_display_names: HashMap<String, String>, status: DBGameStatus, created_time: i64, start_time: Option<i64>, end_time: Option<i64>, snapshot_id: Option<String>, } impl DatabaseGame { pub async fn new() -> Result<Self, DBGameError> { log::info!("Creating a new database game."); let collection = DatabaseGame::get_collection().await; let _id: ObjectId = match collection.insert_one(doc! {}, None).await { Ok(result) => { bson::from_bson(result.inserted_id).expect("Could not deserialize new game _id.") } Err(e) => { log::error!("ERROR: failed to create new game. {}.", e); return Err(DBGameError::CreationError); } }; let friend_code = utils::generate_letter_string(FRIEND_CODE_LENGTH); let game = DatabaseGame { friend_code, _id, players: HashSet::with_capacity(10), display_names: HashSet::with_capacity(10), players_to_display_names: HashMap::with_capacity(10), status: DBGameStatus::Lobby, created_time: Utc::now().timestamp(), start_time: None, end_time: None, snapshot_id: None, }; collection .replace_one( doc! {"_id": &game._id}, bson::to_document(&game).unwrap(), None, ) .await .unwrap(); log::info!("Successfully created DB entry for game {}.", game._id); Ok(game) }
pub async fn end_game(&mut self) -> Result<(), DBGameError> { self.friend_code.clear(); self.end_time = Some(Utc::now().timestamp()); self.status = DBGameStatus::Finished; let update_doc = doc! { "$set": { "friend_code": bson::to_bson(&self.friend_code).unwrap(), "end_time": bson::to_bson(&self.end_time).unwrap(), "status": bson::to_bson(&self.status).unwrap() } }; self.update_db(update_doc).await } pub async fn add_player( &mut self, player_id: String, display_name: String, ) -> Result<(), DBGameError> { log::info!("Adding player {} to game {}.", player_id, self._id); if self.status != DBGameStatus::Lobby { log::error!( "Attempted to add player {} to game {} while in state {:?}. Players may only be added during the Lobby phase.", player_id, self._id, self.status ); return Err(DBGameError::InvalidStateError); } if self.display_names.contains(&display_name) { log::warn!( "Name {} is already in game {}. Display names must be unique.", display_name, self._id ); return Err(DBGameError::DuplicateDisplayName); } self.players.insert(player_id.clone()); self.display_names.insert(display_name.clone()); self.players_to_display_names .insert(player_id, display_name); let update_doc = doc! { "$set": { "players": bson::to_bson(&self.players).unwrap(), "display_names": bson::to_bson(&self.display_names).unwrap() } }; self.update_db(update_doc).await } pub async fn remove_player( &mut self, player_id: &String, ) -> Result<Option<String>, DBGameError> { log::info!("Removing player {} from game {}.", player_id, self._id); if self.status != DBGameStatus::Lobby { log::error!( "ERROR: attempted to remove player {} to game {} while in state {:?}. Players may only be removed during the Lobby phase.", player_id, self._id, self.status ); return Err(DBGameError::InvalidStateError); } self.players.remove(player_id); let display_name = match self.players_to_display_names.remove(player_id) { Some(name) => name, None => { log::warn!( "Tried to remove nonexistant player {} from game {}.", player_id, self._id ); return Ok(None); } }; self.display_names.remove(&display_name); self.players_to_display_names.remove(player_id); let update_doc = doc! { "$set": { "players": bson::to_bson(&self.players).unwrap(), "display_names": bson::to_bson(&self.display_names).unwrap() } }; self.update_db(update_doc).await?; Ok(Some(display_name)) } async fn get_collection() -> Collection { get_database().await.collection(GAME_COLLECTION) } async fn update_db(&self, update_doc: Document) -> Result<(), DBGameError> { let collection = DatabaseGame::get_collection().await; if let Err(e) = collection .update_one(doc! {"_id": &self._id}, update_doc, None) .await { log::error!("ERROR: failed to update database game. {}.", e); return Err(DBGameError::UpdateError); } log::info!("DB game {} updated successfully.", self._id); Ok(()) } pub fn get_friend_code(&self) -> &String { &self.friend_code } }
pub async fn start_game(&mut self) -> Result<(), DBGameError> { log::info!("Starting DB game {}.", self._id); self.start_time = Some(Utc::now().timestamp()); self.status = DBGameStatus::InProgress; let update_doc = doc! { "$set": { "start_time": bson::to_bson(&self.start_time).unwrap(), "status": bson::to_bson(&self.status).unwrap(), "snapshot_id": bson::to_bson(&self.snapshot_id).unwrap(), } }; self.update_db(update_doc).await }
function_block-full_function
[ { "content": "/// Generate an [`Effect`] that sends an error reply to the player.\n\nfn player_error<S: Into<String>>(message: S) -> Effect {\n\n Effect::Reply(Message::Error(message.into()))\n\n}\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 0, "score": 213652.85552980838 }, { "content": "/// Generates a random string of only capital alphabet characters of a certain length.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `length` - The length of the random string to generate\n\n///\n\n/// # Returns\n\n///\n\n/// * `String` - A random alphanumeric string\n\npub fn generate_letter_string(length: usize) -> String {\n\n let mut rng = rand::thread_rng();\n\n let random_string = iter::repeat(())\n\n .map(|()| rng.gen_range(b'A', b'Z') as char)\n\n .take(length)\n\n .collect::<String>();\n\n random_string\n\n}\n", "file_path": "thavalon-server/src/utils.rs", "rank": 1, "score": 178501.8657558828 }, { "content": "/// Generates a random alphanumeric string of a certain length.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `length` - The length of the random string to generate\n\n/// * `only_uppercase` - If true, returns only upper case letters. Otherwise, returns\n\n/// mixed-case strings.\n\n///\n\n/// # Returns\n\n///\n\n/// * `String` - A random alphanumeric string\n\npub fn generate_random_string(length: usize, only_uppercase: bool) -> String {\n\n let mut rng = rand::thread_rng();\n\n let random_string = iter::repeat(())\n\n .map(|()| rng.sample(Alphanumeric))\n\n .take(length)\n\n .collect::<String>();\n\n if only_uppercase {\n\n return random_string.to_uppercase();\n\n }\n\n random_string\n\n}\n\n\n", "file_path": "thavalon-server/src/utils.rs", "rank": 2, "score": 167469.04525530708 }, { "content": "#[allow(clippy::borrowed_box)] // We need &Box<T> instead of &T here to match what serde expects and to add the Send + 'static constraints\n\nfn serialize_internal_error<S: serde::Serializer>(\n\n error: &Box<dyn std::error::Error + Send + 'static>,\n\n ser: S,\n\n) -> Result<S::Ok, S::Error> {\n\n let error_message = error.to_string();\n\n ser.serialize_str(&error_message)\n\n}\n", "file_path": "thavalon-server/src/game/messages.rs", "rank": 3, "score": 153995.53389820165 }, { "content": "fn with_game_collection(\n\n game_collection: GameCollection,\n\n) -> impl Filter<Extract = (GameCollection,), Error = Infallible> + Clone {\n\n warp::any().map(move || game_collection.clone())\n\n}\n", "file_path": "thavalon-server/src/connections/mod.rs", "rank": 4, "score": 126709.28396173261 }, { "content": "/// A phase of the THavalon state machine\n\npub trait Phase: Sized {\n\n /// Lifts a game in this phase back into the [`GameStateWrapper`] enum. This is used by code\n\n /// that is generic over different game phases and needs a wrapped version of the game.\n\n fn wrap(game: GameState<Self>) -> GameStateWrapper;\n\n}\n\n\n\n// Boilerplate for wrapping game phases into an enum\n\nmacro_rules! impl_phase {\n\n ($phase:ident) => {\n\n impl $crate::game::state::Phase for $phase {\n\n fn wrap(game: GameState<Self>) -> GameStateWrapper {\n\n GameStateWrapper::$phase(game)\n\n }\n\n }\n\n };\n\n}\n\n\n\nimpl_phase!(Done);\n\n\n\n// For Rust scoping reasons I don't quite understand, these have to come after the macro definition\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 5, "score": 117537.21937554449 }, { "content": "/// Common logic for transitioning to the next phase after a mission ends. This is shared by the [`OnMission`] and\n\n/// [`WaitingForAgravaine`] phases. This assumes that `state.mission_results` is up-to-date (including Agravaine\n\n/// declarations).\n\n///\n\n/// # Arguments\n\n/// * `state` - the `GameState` to transition from (either `OnMission` or `WaitingForAgravaine`)\n\n/// * `effects` - additional side-effects to apply (this varies depending on whether or not Agravaine declared)\n\n/// * `proposal` - the proposal the mission was based on, used to figure out who is proposing next\n\nfn conclude_mission<P: Phase>(\n\n mut state: GameState<P>,\n\n mut effects: Vec<Effect>,\n\n proposal: usize,\n\n) -> ActionResult {\n\n let (mut successes, mut fails) = (0, 0);\n\n for mission in state.mission_results.iter() {\n\n if mission.passed {\n\n successes += 1\n\n } else {\n\n fails += 1\n\n }\n\n }\n\n\n\n if successes == 3 {\n\n log::debug!(\"3 missions have passed, moving to assassination\");\n\n effects.push(Effect::Broadcast(Message::BeginAssassination {\n\n assassin: state.game.assassin.to_string(),\n\n }));\n\n let next_state = GameStateWrapper::Assassination(state.with_phase(Assassination {}));\n", "file_path": "thavalon-server/src/game/state/on_mission.rs", "rank": 6, "score": 113101.22550743647 }, { "content": "/// Tests if a mission has failed\n\n/// Note: this is written the way it is because it's easier to express the rules for a mission failing. In general,\n\n/// it's clearer to keep track of whether or not it passed.\n\nfn is_failure<'a, I: IntoIterator<Item = &'a Card>>(\n\n spec: &GameSpec,\n\n mission: usize,\n\n cards: I,\n\n) -> bool {\n\n let (fails, reverses) = cards\n\n .into_iter()\n\n .fold((0, 0), |(fails, reverses), card| match card {\n\n Card::Fail => (fails + 1, reverses),\n\n Card::Reverse => (fails, reverses + 1),\n\n Card::Success => (fails, reverses),\n\n });\n\n\n\n // Two reverses cancel each other out\n\n let reversed = reverses % 2 == 1;\n\n\n\n if mission == 4 && spec.double_fail_mission_four {\n\n // Mission 4 can fail if there are 2+ fails or a reverse and a fail, in large enough games\n\n (fails >= 2 && !reversed) || (fails == 1 && reverses == 1)\n\n } else {\n", "file_path": "thavalon-server/src/game/state/on_mission.rs", "rank": 7, "score": 107880.13353522125 }, { "content": "#[derive(Serialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct ServerError {\n\n error_code: i32,\n\n error_message: String,\n\n}\n\n\n", "file_path": "thavalon-server/src/connections/errors.rs", "rank": 8, "score": 103356.22499467255 }, { "content": "#[derive(PartialEq)]\n\nenum ErrorCode {\n\n Unauthorized = 1,\n\n DuplicateAccount,\n\n PasswordInsecure,\n\n InvalidLogin,\n\n MissingHeader,\n\n InvalidAccountVerification,\n\n AccountNotVerified,\n\n NoActiveGame,\n\n Unknown = 255,\n\n}\n\n\n\n/// Recovers any custom rejections and returns a response to the client.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `err` - The rejection caused by an upstream failure.\n\npub async fn recover_errors(err: Rejection) -> Result<impl Reply, Infallible> {\n\n log::info!(\"Handling rejections: {:?}\", err);\n\n let mut http_response_code = StatusCode::INTERNAL_SERVER_ERROR;\n", "file_path": "thavalon-server/src/connections/errors.rs", "rank": 9, "score": 103351.97481181778 }, { "content": "export function updateDeclaredPlayers(\n\n player: string,\n\n role: Role,\n\n playersToRolesMap: Map<string, Role>,\n\n rolesToPlayersMap: Map<Role, string>,\n\n playersToRolesSetter: React.Dispatch<React.SetStateAction<Map<string, Role>>>,\n\n rolesToPlayersSetter: React.Dispatch<React.SetStateAction<Map<Role, string>>>,\n\n): void {\n\n const newPlayersToRoles = new Map(playersToRolesMap);\n\n const newRolesToPlayers = new Map(rolesToPlayersMap);\n\n newPlayersToRoles.set(player, role);\n\n newRolesToPlayers.set(role, player);\n\n rolesToPlayersSetter(newRolesToPlayers);\n\n playersToRolesSetter(newPlayersToRoles);\n", "file_path": "thavalon-webapp/src/components/gameComponents/gameUtils.ts", "rank": 10, "score": 99755.65590319972 }, { "content": "export function createSelectedPlayerTypesList(\n\n name: string,\n\n primarySelectedPlayers: Set<string>,\n\n secondarySelectedPlayers: Set<string>):\n\n SelectedPlayerType[] {\n\n const selectedTypes = new Array<SelectedPlayerType>();\n\n if (primarySelectedPlayers.has(name)) {\n\n selectedTypes.push(SelectedPlayerType.Primary);\n\n }\n\n if (secondarySelectedPlayers.has(name)) {\n\n selectedTypes.push(SelectedPlayerType.Secondary);\n\n }\n\n return selectedTypes;\n", "file_path": "thavalon-webapp/src/components/gameComponents/gameUtils.ts", "rank": 11, "score": 96595.63514781572 }, { "content": "/// Authorizes a request for downstream endpoints.\n\n/// This function returns a filter that passes along the user ID or a rejection.\n\nfn authorize_request(\n\n token_manager: &TokenManager,\n\n) -> impl Filter<Extract = (String,), Error = Rejection> + Clone {\n\n log::info!(\"Restricted API called. Validating auth header.\");\n\n warp::header::<String>(\"Authorization\")\n\n .and(with_token_manager(token_manager.clone()))\n\n .and_then(authorize_user)\n\n}\n\n\n\n/// Authorizes a user via JWT.\n\n/// Returns either the user ID or a rejection if the user isn't authorized.\n\nasync fn authorize_user(header: String, token_manager: TokenManager) -> Result<String, Rejection> {\n\n log::info!(\"Authorizing user for restricted API by JWT.\");\n\n let token_pieces: Vec<&str> = header.split(' ').collect();\n\n if token_pieces.len() < 2 {\n\n log::info!(\n\n \"Invalid header format received. Received {}. Expected \\\"Basic <token>\\\".\",\n\n header\n\n );\n\n return Err(reject::custom(InvalidTokenRejection));\n", "file_path": "thavalon-server/src/connections/mod.rs", "rank": 12, "score": 94471.93983170309 }, { "content": "#[derive(Deserialize)]\n\n#[serde(tag = \"messageType\", content = \"data\")]\n\nenum IncomingMessage {\n\n Ping,\n\n StartGame,\n\n GetLobbyState,\n\n GameCommand(Action),\n\n GetPlayerList,\n\n GetSnapshot,\n\n PlayerFocusChange(bool),\n\n}\n\n\n\n/// An outgoing message to the client.\n\n#[derive(Serialize)]\n\n#[serde(tag = \"messageType\", content = \"data\")]\n\npub enum OutgoingMessage {\n\n Pong(String),\n\n PlayerList(Vec<String>),\n\n LobbyState(LobbyState),\n\n GameMessage(Message),\n\n Snapshot(GameSnapshot),\n\n PlayerFocusChange {\n", "file_path": "thavalon-server/src/lobby/mod.rs", "rank": 13, "score": 93981.05855201281 }, { "content": "#[derive(Hash, PartialEq, Eq)]\n\nenum TaskType {\n\n FromGame,\n\n FromClient,\n\n ToClient,\n\n HeartBeat,\n\n}\n\n\n\n/// Message types that can be sent to the outbound messaging task.\n\n/// Most of the time, this will be ToClient, which will forward the message to the client.\n\n/// However, in the event of a new connection, the NewWebSocket can be used to update\n\n/// the outgoing WS connection without needing to recreate the task.\n", "file_path": "thavalon-server/src/lobby/client.rs", "rank": 14, "score": 93976.88319985985 }, { "content": "interface LobbyStateResponse {\n\n state: LobbyState\n", "file_path": "thavalon-webapp/src/components/gameContainer.tsx", "rank": 15, "score": 93191.39788769753 }, { "content": "#[derive(Serialize, Deserialize)]\n\nstruct InternalDBAccount {\n\n _id: ObjectId,\n\n email: String,\n\n hash: String,\n\n display_name: String,\n\n profile_picture: Option<Vec<u8>>,\n\n email_verified: bool,\n\n}\n\n\n\nimpl TryFrom<DatabaseAccount> for InternalDBAccount {\n\n type Error = String;\n\n\n\n fn try_from(public_account: DatabaseAccount) -> Result<Self, Self::Error> {\n\n let _id = match ObjectId::with_string(&public_account.id) {\n\n Ok(id) => id,\n\n Err(e) => {\n\n return Err(format!(\n\n \"Given ID {} is not valid hex. {}\",\n\n &public_account.id, e\n\n ));\n", "file_path": "thavalon-server/src/database/accounts/mod.rs", "rank": 16, "score": 91476.51505186554 }, { "content": "#[derive(Debug)]\n\nenum OutboundTaskMessageType {\n\n ToClient(String),\n\n NewWebSocket(SplitSink<WebSocket, ws::Message>),\n\n HeartBeat,\n\n}\n\n\n\n/// Manages the connection to the actual player.\n\n/// `PlayerClient` maintains all the connection tasks, updating and remaking them\n\n/// as needed. The struct also maintains connections to the lobby and to the game.\n\npub struct PlayerClient {\n\n tasks: HashMap<TaskType, AbortHandle>,\n\n client_id: String,\n\n to_lobby: LobbyChannel,\n\n to_game: Sender<Action>,\n\n to_outbound_task: Sender<OutboundTaskMessageType>,\n\n oubound_task_receiver: Option<Receiver<OutboundTaskMessageType>>,\n\n}\n\n\n\n// Implement drop to clean up all outstanding tasks.\n\nimpl Drop for PlayerClient {\n", "file_path": "thavalon-server/src/lobby/client.rs", "rank": 17, "score": 90928.71179301073 }, { "content": "#[async_trait]\n\npub trait Interactions {\n\n /// Send a message to a specific player\n\n async fn send_to(&mut self, player: &str, message: Message) -> Result<(), GameError>;\n\n\n\n /// Send a message to all players\n\n async fn send(&mut self, message: Message) -> Result<(), GameError>;\n\n\n\n /// Receive the next message from any player\n\n async fn receive(&mut self) -> Result<(String, Action), GameError>;\n\n}\n\n\n\n/// An Interactions that uses per-player MPSC channels\n\npub struct ChannelInteractions {\n\n inbox: StreamMap<String, mpsc::Receiver<Action>>,\n\n outbox: HashMap<String, mpsc::Sender<Message>>,\n\n}\n\n\n\nimpl ChannelInteractions {\n\n pub fn new() -> ChannelInteractions {\n\n ChannelInteractions {\n", "file_path": "thavalon-server/src/game/interactions.rs", "rank": 18, "score": 85946.05173331496 }, { "content": " DBGameError::DuplicateDisplayName => Err(LobbyError::DuplicateDisplayName),\n\n _ => {\n\n log::error!(\"An unknown error occurred in game {}.\", self.friend_code);\n\n Err(LobbyError::UnknownError)\n\n }\n\n };\n\n\n\n return LobbyResponse::Standard(return_err);\n\n }\n\n\n\n // Player added to the database game. Now add the player to the game instance.\n\n let (sender, receiver) = self\n\n .builder\n\n .as_mut()\n\n .unwrap()\n\n .add_player(display_name.clone());\n\n\n\n // Generate a unique client ID for the player and update all our dictionaries.\n\n let client_id = utils::generate_random_string(32, false);\n\n let client = PlayerClient::new(client_id.clone(), self.to_lobby.clone(), sender, receiver);\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 19, "score": 83751.81520249457 }, { "content": " self.friend_code\n\n );\n\n return LobbyResponse::Standard(Err(LobbyError::InvalidStateError));\n\n }\n\n\n\n // The checks passed. Try adding the player into the game.\n\n if let Err(e) = self\n\n .database_game\n\n .add_player(player_id.clone(), display_name.clone())\n\n .await\n\n {\n\n log::error!(\n\n \"Error while adding player {} to game {}. {}\",\n\n player_id,\n\n self.friend_code,\n\n e\n\n );\n\n let return_err = match e {\n\n DBGameError::UpdateError => Err(LobbyError::DatabaseError),\n\n DBGameError::InvalidStateError => Err(LobbyError::InvalidStateError),\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 20, "score": 83751.05841279948 }, { "content": " }\n\n\n\n let builder = self.builder.take().unwrap();\n\n let (abort_handle, abort_registration) = AbortHandle::new_pair();\n\n self.game_abort_handle = Some(abort_handle);\n\n match builder.start(self.to_lobby.clone(), abort_registration) {\n\n Ok((snapshots, _)) => {\n\n self.snapshots = Some(snapshots);\n\n // Tell the players the game is about to start to move to the game page.\n\n self.broadcast_message(&OutgoingMessage::LobbyState(LobbyState::Game))\n\n .await;\n\n self.status = LobbyState::Game;\n\n LobbyResponse::None\n\n }\n\n Err(err) => {\n\n // Starting the game can fail, for example if there are too many players in the lobby\n\n // Since that isn't necessarily a fatal error, don't close the lobby\n\n log::error!(\"Error creating game {}: {}\", self.friend_code, err);\n\n LobbyResponse::Standard(Err(LobbyError::InvalidStateError))\n\n }\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 21, "score": 83749.5832787483 }, { "content": " for client in self.clients.values_mut() {\n\n client.send_message(message.clone()).await;\n\n }\n\n }\n\n\n\n /// Begins a loop for the lobby to listen for incoming commands.\n\n /// This function should only return when the game ends or when a fatal\n\n /// error occurs.\n\n async fn listen(mut self, mut receiver: Receiver<(LobbyCommand, Option<ResponseChannel>)>) {\n\n while let Some(msg) = receiver.recv().await {\n\n if self.status == LobbyState::Finished {\n\n break;\n\n }\n\n let (msg_contents, result_channel) = msg;\n\n let results = match msg_contents {\n\n LobbyCommand::AddPlayer {\n\n player_id,\n\n display_name,\n\n } => self.add_player(player_id, display_name).await,\n\n\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 22, "score": 83744.23861608104 }, { "content": "impl Lobby {\n\n /// Creates a new lobby instance on a separate Tokio thread.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `end_game_channel` A channel this lobby should publish to when it's finished running.\n\n ///\n\n /// # Returns\n\n ///\n\n /// * `LobbyChannel` A channel for sending messages to this lobby.\n\n pub async fn new(game_over_channel: oneshot::Sender<bool>) -> LobbyChannel {\n\n let (tx, rx) = mpsc::channel(10);\n\n\n\n let to_lobby = tx.clone();\n\n task::spawn(async move {\n\n let database_game = DatabaseGame::new().await.unwrap();\n\n let friend_code = database_game.get_friend_code().clone();\n\n let lobby = Lobby {\n\n game_over_channel: Some(game_over_channel),\n\n database_game,\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 23, "score": 83742.47241125879 }, { "content": " player_id,\n\n display_name,\n\n existing_display_name);\n\n return LobbyResponse::Standard(Err(LobbyError::NameChangeOnReconnectError));\n\n }\n\n return LobbyResponse::JoinGame(Ok(client_id));\n\n }\n\n\n\n /// Removes a player from the lobby and game.\n\n async fn remove_player(&mut self, client_id: String) {\n\n log::info!(\n\n \"Removing client {} from game {}.\",\n\n client_id,\n\n self.friend_code\n\n );\n\n let player_id = match self.client_ids_to_player_info.remove(&client_id) {\n\n Some((player_id, _)) => player_id,\n\n None => {\n\n log::warn!(\"No player ID found matching client ID {}.\", client_id);\n\n return;\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 24, "score": 83741.00575827043 }, { "content": " );\n\n // Reconnecting can only happen for games in progress, as lobbies just kick disconnected players\n\n // and finished games are finished.\n\n if self.status != LobbyState::Game {\n\n log::warn!(\n\n \"Player {} attempted to join game not in progress {}.\",\n\n player_id,\n\n self.friend_code\n\n );\n\n return LobbyResponse::Standard(Err(LobbyError::InvalidStateError));\n\n }\n\n let client_id = self\n\n .player_ids_to_client_ids\n\n .get(player_id)\n\n .unwrap()\n\n .clone();\n\n let existing_display_name = &self.client_ids_to_player_info.get(&client_id).unwrap().1;\n\n if existing_display_name != &display_name {\n\n log::warn!(\n\n \"Player {} attempted to reconnect with display name {}, but previously had display name {}.\",\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 25, "score": 83740.69245585284 }, { "content": " }\n\n };\n\n\n\n client.update_websocket(ws).await;\n\n self.on_player_list_change().await;\n\n LobbyResponse::Standard(Ok(()))\n\n }\n\n\n\n /// Sends a pong back to the client that requested it.\n\n async fn send_pong(&mut self, client_id: String) -> LobbyResponse {\n\n let client = match self.clients.get_mut(&client_id) {\n\n Some(client) => client,\n\n None => {\n\n log::error!(\"Client {} does not exist. Cannot send Pong.\", client_id);\n\n return LobbyResponse::Standard(Err(LobbyError::InvalidClientID));\n\n }\n\n };\n\n let message = OutgoingMessage::Pong(\"Pong\".to_string());\n\n let message = serde_json::to_string(&message).unwrap();\n\n client.send_message(message).await;\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 26, "score": 83739.19833707114 }, { "content": "\n\n /// Gets all snapshots that have occurred for a given client ID.\n\n async fn get_snapshots(&mut self, client_id: String) -> LobbyResponse {\n\n let (_, display_name) = &self.client_ids_to_player_info[&client_id];\n\n let snapshot = self\n\n .snapshots\n\n .as_ref()\n\n .unwrap()\n\n .get(display_name)\n\n .unwrap()\n\n .lock()\n\n .unwrap()\n\n .clone();\n\n let mut client = self.clients.get_mut(&client_id).unwrap();\n\n let message = OutgoingMessage::Snapshot(snapshot);\n\n let message = serde_json::to_string(&message).unwrap();\n\n client.send_message(message).await;\n\n LobbyResponse::None\n\n }\n\n\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 27, "score": 83738.87615037963 }, { "content": "\n\n /// Adds a player to the lobby and all associated games.\n\n async fn add_player(&mut self, player_id: String, display_name: String) -> LobbyResponse {\n\n log::info!(\n\n \"Attempting to add player {} to lobby {}.\",\n\n player_id,\n\n self.friend_code\n\n );\n\n\n\n // First, check if this player is already in game. If so, this is a reconnect. Otherwise,\n\n // this is a new player.\n\n if self.player_ids_to_client_ids.contains_key(&player_id) {\n\n return self.reconnect_player(&player_id, &display_name);\n\n }\n\n\n\n // Unlike reconnecting, new players may only join when the game is in Lobby.\n\n if self.status != LobbyState::Lobby {\n\n log::warn!(\n\n \"Player {} attempted to join in-progress or finished game {}.\",\n\n player_id,\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 28, "score": 83738.58635414805 }, { "content": " /// Handles a player focus change event by telling all clients that a player's\n\n /// visibility has changed.\n\n async fn player_focus_changed(\n\n &mut self,\n\n client_id: String,\n\n is_tabbed_out: bool,\n\n ) -> LobbyResponse {\n\n let (_, display_name) = &self.client_ids_to_player_info[&client_id];\n\n let display_name = display_name.clone();\n\n let message = OutgoingMessage::PlayerFocusChange {\n\n displayName: display_name,\n\n isTabbedOut: is_tabbed_out,\n\n };\n\n self.broadcast_message(&message).await;\n\n LobbyResponse::None\n\n }\n\n\n\n /// Broadcasts a message to all clients in the lobby.\n\n async fn broadcast_message(&mut self, message: &OutgoingMessage) {\n\n let message = serde_json::to_string(&message).unwrap();\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 29, "score": 83738.02505494755 }, { "content": " }\n\n\n\n /// Updates a player's connections to and from the game and to and from the\n\n /// client.\n\n async fn update_player_connections(\n\n &mut self,\n\n client_id: String,\n\n ws: WebSocket,\n\n ) -> LobbyResponse {\n\n log::info!(\"Updating connections for client {}.\", client_id);\n\n let client = match self.clients.get_mut(&client_id) {\n\n Some(client) => client,\n\n None => {\n\n log::warn!(\n\n \"Client {} tried to connect to lobby {} but is not registered\",\n\n client_id,\n\n self.friend_code\n\n );\n\n let _ = ws.close().await;\n\n return LobbyResponse::Standard(Err(LobbyError::InvalidClientID));\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 30, "score": 83737.24866073845 }, { "content": " \"Client {} has disconnected from game {}.\",\n\n client_id,\n\n self.friend_code\n\n );\n\n\n\n // If we're in the lobby phase, a disconnect counts as leaving the game.\n\n if self.status == LobbyState::Lobby {\n\n self.remove_player(client_id).await;\n\n }\n\n\n\n LobbyResponse::Standard(Ok(()))\n\n }\n\n\n\n /// Starts the game and updates statuses\n\n async fn start_game(&mut self) -> LobbyResponse {\n\n // The only thing that can fail is updating the database. In this case,\n\n // the lobby is probably dead, so panic to blow up everything.\n\n if let Err(e) = self.database_game.start_game().await {\n\n log::error!(\"Error while starting game {}. {}\", self.friend_code, e);\n\n panic!();\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 31, "score": 83736.7056040828 }, { "content": " }\n\n\n\n /// Sends the current player list to the client.\n\n async fn send_player_list(&mut self, client_id: String) -> LobbyResponse {\n\n let mut client = self.clients.get_mut(&client_id).unwrap();\n\n let player_list = self.builder.as_ref().unwrap().get_player_list().to_vec();\n\n let player_list = OutgoingMessage::PlayerList(player_list);\n\n let player_list = serde_json::to_string(&player_list).unwrap();\n\n client.send_message(player_list).await;\n\n LobbyResponse::None\n\n }\n\n\n\n /// Sends the current state of the lobby to the client.\n\n async fn send_current_state(&mut self, client_id: String) -> LobbyResponse {\n\n let mut client = self.clients.get_mut(&client_id).unwrap();\n\n let state = OutgoingMessage::LobbyState(self.status.clone());\n\n let message = serde_json::to_string(&state).unwrap();\n\n client.send_message(message).await;\n\n LobbyResponse::None\n\n }\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 32, "score": 83736.49640038269 }, { "content": " }\n\n }\n\n\n\n // End the lobby, including ending the database game and aborting the game thread.\n\n async fn end_game(&mut self) -> LobbyResponse {\n\n self.status = LobbyState::Finished;\n\n self.database_game\n\n .end_game()\n\n .await\n\n .expect(\"Failed to end database game!\");\n\n // game_abort_handle is None if the game has not been started. In that case, do nothing to end it.\n\n if let Some(handle) = self.game_abort_handle.take() {\n\n handle.abort()\n\n }\n\n self.game_over_channel\n\n .take()\n\n .unwrap()\n\n .send(true)\n\n .expect(\"Failed to notify lobby manager!\");\n\n LobbyResponse::None\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 33, "score": 83734.73391544631 }, { "content": "const MAX_NUM_PLAYERS: usize = 10;\n\n\n\n/// A lobby for an individual game. The Lobby acts as an interface between the\n\n/// Thavalon game instance, the DatabaseGame which keeps the game state in sync\n\n/// with the database, and all players connected to the game.\n\npub struct Lobby {\n\n game_over_channel: Option<oneshot::Sender<bool>>,\n\n database_game: DatabaseGame,\n\n friend_code: String,\n\n player_ids_to_client_ids: HashMap<String, String>,\n\n // Map of client IDs to player ID and display name.\n\n client_ids_to_player_info: HashMap<String, (String, String)>,\n\n clients: HashMap<String, PlayerClient>,\n\n status: LobbyState,\n\n builder: Option<GameBuilder>,\n\n snapshots: Option<Snapshots>,\n\n game_abort_handle: Option<AbortHandle>,\n\n to_lobby: LobbyChannel,\n\n}\n\n\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 34, "score": 83734.11735581087 }, { "content": " log::info!(\n\n \"Successfully added player {} to game {} with unique client ID {}.\",\n\n player_id,\n\n self.friend_code,\n\n client_id\n\n );\n\n self.player_ids_to_client_ids\n\n .insert(player_id.clone(), client_id.clone());\n\n self.client_ids_to_player_info\n\n .insert(client_id.clone(), (player_id, display_name));\n\n self.clients.insert(client_id.clone(), client);\n\n LobbyResponse::JoinGame(Ok(client_id))\n\n }\n\n\n\n /// Reconnect a player to an existing game in progress. Helper for add_player.\n\n fn reconnect_player(&self, player_id: &str, display_name: &str) -> LobbyResponse {\n\n log::info!(\n\n \"Player {} is already in game {}, reconnecting.\",\n\n player_id,\n\n self.friend_code\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 35, "score": 83732.60526783767 }, { "content": "use super::client::PlayerClient;\n\nuse super::{IncomingMessage, LobbyState, OutgoingMessage};\n\nuse super::{LobbyChannel, LobbyCommand, LobbyError, LobbyResponse, ResponseChannel};\n\nuse crate::database::games::{DBGameError, DBGameStatus, DatabaseGame};\n\nuse crate::game::{\n\n builder::GameBuilder,\n\n snapshot::{GameSnapshot, Snapshots},\n\n};\n\nuse crate::utils;\n\n\n\nuse futures::future::AbortHandle;\n\nuse tokio::{\n\n sync::mpsc::{self, Receiver},\n\n sync::oneshot,\n\n task,\n\n};\n\nuse warp::filters::ws::WebSocket;\n\n\n\nuse std::collections::HashMap;\n\n\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 36, "score": 83731.6824859968 }, { "content": " }\n\n };\n\n\n\n log::info!(\n\n \"Found player {} for client {}. Removing player.\",\n\n player_id,\n\n client_id\n\n );\n\n\n\n let display_name = self.database_game.remove_player(&player_id).await.unwrap();\n\n if display_name == None {\n\n log::warn!(\"No player display name found for player {}.\", player_id);\n\n return;\n\n }\n\n let display_name = display_name.unwrap();\n\n self.builder.as_mut().unwrap().remove_player(&display_name);\n\n self.player_ids_to_client_ids.remove(&player_id);\n\n self.clients.remove(&client_id);\n\n self.on_player_list_change().await;\n\n log::info!(\"Successfully removed player {} from the game.\", player_id);\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 37, "score": 83731.39973451674 }, { "content": " LobbyResponse::Standard(Ok(()))\n\n }\n\n\n\n /// Handles a change to the player list, due to a player joining or leaving the game.\n\n async fn on_player_list_change(&mut self) {\n\n // Only broadcast to players if the game hasn't started yet.\n\n // TODO: Maybe a helpful message to players that someone has disconnected.\n\n // Would need to have a way to lookup name by the disconnected client ID.\n\n if self.status == LobbyState::Lobby {\n\n let current_players = self.builder.as_ref().unwrap().get_player_list();\n\n self.broadcast_message(&OutgoingMessage::PlayerList(current_players.to_vec()))\n\n .await;\n\n }\n\n }\n\n\n\n // Handles dealing with a disconnected player.\n\n // If the lobby isn't in progress or done, a disconnect should remove the player.\n\n // Otherwise, nothing happens.\n\n async fn on_player_disconnect(&mut self, client_id: String) -> LobbyResponse {\n\n log::info!(\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 38, "score": 83730.58292830881 }, { "content": " friend_code,\n\n player_ids_to_client_ids: HashMap::with_capacity(MAX_NUM_PLAYERS),\n\n client_ids_to_player_info: HashMap::with_capacity(MAX_NUM_PLAYERS),\n\n clients: HashMap::with_capacity(MAX_NUM_PLAYERS),\n\n status: LobbyState::Lobby,\n\n builder: Some(GameBuilder::new()),\n\n snapshots: None,\n\n game_abort_handle: None,\n\n to_lobby,\n\n };\n\n lobby.listen(rx).await\n\n });\n\n\n\n tx\n\n }\n\n\n\n /// Gets the friend code for the lobby in question.\n\n fn get_friend_code(&self) -> LobbyResponse {\n\n LobbyResponse::FriendCode(self.friend_code.clone())\n\n }\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 39, "score": 83729.9319908693 }, { "content": " LobbyCommand::GetFriendCode => self.get_friend_code(),\n\n LobbyCommand::IsClientRegistered { client_id } => {\n\n LobbyResponse::IsClientRegistered(self.clients.contains_key(&client_id))\n\n }\n\n LobbyCommand::ConnectClientChannels { client_id, ws } => {\n\n self.update_player_connections(client_id, ws).await\n\n }\n\n LobbyCommand::Ping { client_id } => self.send_pong(client_id).await,\n\n LobbyCommand::GetLobbyState { client_id } => {\n\n self.send_current_state(client_id).await\n\n }\n\n LobbyCommand::StartGame => self.start_game().await,\n\n LobbyCommand::EndGame => self.end_game().await,\n\n LobbyCommand::PlayerDisconnect { client_id } => {\n\n self.on_player_disconnect(client_id).await\n\n }\n\n LobbyCommand::GetPlayerList { client_id } => self.send_player_list(client_id).await,\n\n LobbyCommand::GetSnapshots { client_id } => self.get_snapshots(client_id).await,\n\n LobbyCommand::PlayerFocusChange {\n\n client_id,\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 40, "score": 83725.61387335024 }, { "content": " is_tabbed_out,\n\n } => self.player_focus_changed(client_id, is_tabbed_out).await,\n\n };\n\n\n\n if let Some(channel) = result_channel {\n\n channel\n\n .send(results)\n\n .expect(\"Could not send a result message back to caller.\");\n\n }\n\n }\n\n }\n\n}\n", "file_path": "thavalon-server/src/lobby/lobby_impl.rs", "rank": 41, "score": 83710.30598238709 }, { "content": "fn setup_logger() -> Result<(), fern::InitError> {\n\n let colors = ColoredLevelConfig::new()\n\n .info(Color::Green)\n\n .debug(Color::Cyan);\n\n fern::Dispatch::new()\n\n .format(move |out, message, record| {\n\n out.finish(format_args!(\n\n \"{} [{}] {}\",\n\n colors.color(record.level()),\n\n record.target(),\n\n message\n\n ))\n\n })\n\n .level(log::LevelFilter::Debug)\n\n .level_for(\"hyper\", log::LevelFilter::Info)\n\n .level_for(\"warp\", log::LevelFilter::Debug)\n\n .chain(std::io::stdout())\n\n .apply()?;\n\n\n\n Ok(())\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() {\n\n setup_logger().expect(\"Could not set up logging\");\n\n database::initialize_mongo_client().await;\n\n connections::serve_connections().await;\n\n}\n", "file_path": "thavalon-server/src/main.rs", "rank": 42, "score": 81820.47985447187 }, { "content": "//! Tracks game state related to individual roles, such as how many uses of an ability are left.\n\n\n\nuse super::prelude::*;\n\n\n\npub struct RoleState {\n\n pub maeve: MaeveState,\n\n pub arthur: ArthurState,\n\n}\n\n\n\npub struct MaeveState {\n\n obscures_remaining: usize,\n\n obscured_this_round: bool,\n\n}\n\n\n\npub struct ArthurState {\n\n has_declared: bool,\n\n}\n\n\n\nimpl RoleState {\n\n pub fn new(game: &Game) -> RoleState {\n", "file_path": "thavalon-server/src/game/state/role_state.rs", "rank": 43, "score": 77145.31619624195 }, { "content": " RoleState {\n\n maeve: MaeveState::new(game.spec),\n\n arthur: ArthurState::new(),\n\n }\n\n }\n\n\n\n /// Updates role state at the start of each round. This has an unusual signature (taking `&mut GameState` instead of `&mut self`) because\n\n /// some roles require the entire game state to update.\n\n pub fn on_round_start<P: Phase>(state: &mut GameState<P>, effects: &mut Vec<Effect>) {\n\n state.role_state.maeve.on_round_start();\n\n state.role_state.arthur.on_round_start(state, effects);\n\n }\n\n}\n\n\n\nimpl MaeveState {\n\n fn new(spec: &GameSpec) -> MaeveState {\n\n MaeveState {\n\n obscures_remaining: spec.max_maeve_obscures,\n\n obscured_this_round: false,\n\n }\n", "file_path": "thavalon-server/src/game/state/role_state.rs", "rank": 44, "score": 77140.06870529243 }, { "content": " // Arthur can declare if 2 missions have failed\n\n state.mission_results.iter().filter(|m| !m.passed).count() == 2\n\n }\n\n }\n\n\n\n fn on_round_start<P: Phase>(&self, state: &GameState<P>, effects: &mut Vec<Effect>) {\n\n if let Some(arthur) = state.game.players.by_role(Role::Arthur) {\n\n let message = if self.can_declare(state) {\n\n Message::ArthurCanDeclare\n\n } else {\n\n Message::ArthurCannotDeclare\n\n };\n\n effects.push(Effect::Send(arthur.name.clone(), message));\n\n }\n\n }\n\n}\n", "file_path": "thavalon-server/src/game/state/role_state.rs", "rank": 45, "score": 77138.21020175195 }, { "content": " }\n\n\n\n fn on_round_start(&mut self) {\n\n self.obscured_this_round = false;\n\n }\n\n\n\n /// Checks if Maeve is allowed to use her ability\n\n pub fn can_obscure(&self) -> bool {\n\n !self.obscured_this_round && self.obscures_remaining > 0\n\n }\n\n\n\n /// Records when Maeve uses her ability.\n\n pub fn mark_obscure(&mut self) {\n\n self.obscured_this_round = true;\n\n self.obscures_remaining -= 1;\n\n }\n\n}\n\n\n\nimpl ArthurState {\n\n fn new() -> ArthurState {\n", "file_path": "thavalon-server/src/game/state/role_state.rs", "rank": 46, "score": 77136.88409325546 }, { "content": " ArthurState {\n\n has_declared: false,\n\n }\n\n }\n\n\n\n pub fn declare(&mut self) {\n\n self.has_declared = true;\n\n }\n\n\n\n /// Checks if Arthur has already declared\n\n pub fn has_declared(&self) -> bool {\n\n self.has_declared\n\n }\n\n\n\n /// Checks if Arthur is allowed to declare\n\n pub fn can_declare<P: Phase>(&self, state: &GameState<P>) -> bool {\n\n if self.has_declared || state.mission() == 5 {\n\n // Arthur cannot declare on mission 5\n\n false\n\n } else {\n", "file_path": "thavalon-server/src/game/state/role_state.rs", "rank": 47, "score": 77133.74160559526 }, { "content": "\n\n /// Returns whether or not the game is over\n\n pub fn is_done(&self) -> bool {\n\n matches!(self, GameStateWrapper::Done(_))\n\n }\n\n\n\n fn game(&self) -> &Game {\n\n any_phase!(self, |inner| &inner.game)\n\n }\n\n}\n\n\n\nimpl Done {\n\n pub fn new(winning_team: Team) -> Done {\n\n Done { winning_team }\n\n }\n\n}\n\n\n\nimpl fmt::Display for Proposal {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n use itertools::Itertools;\n\n write!(\n\n f,\n\n \"{} (proposed by {})\",\n\n self.players.iter().format(\", \"),\n\n self.proposer\n\n )\n\n }\n\n}\n\n\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 64, "score": 71716.20194153476 }, { "content": " |state| => (state, vec![player_error(\"You can't move to assassination right now\")])\n\n ),\n\n\n\n (state, _) => (state, vec![player_error(\"You can't do that right now\")]),\n\n }\n\n }\n\n\n\n /// Handles a timeout set by [`Effect::SetTimeout`] expiring. This is used for player actions which must happen in a\n\n /// certain time window, like Agravaine declarations.\n\n pub fn handle_timeout(self) -> ActionResult {\n\n log::debug!(\"Action timeout expired\");\n\n match self {\n\n GameStateWrapper::WaitingForAgravaine(inner) => inner.handle_timeout(),\n\n _ => {\n\n // This might happen if we transition to a new phase (like assassination) while a timeout is active.\n\n log::warn!(\"Timeout expired when no timeout should have been set\");\n\n (self, vec![])\n\n }\n\n }\n\n }\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 65, "score": 71712.51038301598 }, { "content": " pub fn new(game: Game) -> ActionResult {\n\n let first_proposer = &game.proposal_order()[0];\n\n let phase = Proposing::new(first_proposer.clone());\n\n\n\n let mut effects = vec![Effect::Broadcast(Message::ProposalOrder(\n\n game.proposal_order.clone(),\n\n ))];\n\n\n\n for player in game.players.iter() {\n\n effects.push(Effect::Send(\n\n player.name.clone(),\n\n Message::RoleInformation {\n\n details: game.info[&player.name].clone(),\n\n },\n\n ));\n\n }\n\n\n\n // Send NextProposal last to move client to the proposal phase after\n\n // receiving role information.\n\n effects.push(Effect::Broadcast(Message::NextProposal {\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 66, "score": 71708.60612166348 }, { "content": "#![allow(dead_code)]\n\nuse std::collections::HashSet;\n\nuse std::fmt;\n\nuse std::time::Duration;\n\n\n\nuse super::messages::{Action, Message};\n\nuse super::role::{Role, Team};\n\nuse super::{Game, MissionNumber};\n\n\n\nuse self::assassination::Assassination;\n\nuse self::on_mission::{OnMission, WaitingForAgravaine};\n\nuse self::proposing::Proposing;\n\nuse self::role_state::RoleState;\n\nuse self::voting::Voting;\n\n\n\nmod role_state;\n\n\n\n/// Result of handling a player action. The [`GameStateWrapper`] is the new state of the game and the [`Effect`]\n\n/// [`Vec`] describes side-effects of the state transition.\n\npub type ActionResult = (GameStateWrapper, Vec<Effect>);\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 67, "score": 71706.8142493894 }, { "content": " pub fn handle_action(self, player: &str, action: Action) -> ActionResult {\n\n log::debug!(\"Responding to {:?} from {}\", action, player);\n\n match (self, action) {\n\n (GameStateWrapper::Proposing(inner), Action::Propose { players }) => {\n\n inner.handle_proposal(player, players)\n\n }\n\n (GameStateWrapper::Proposing(inner), Action::SelectPlayer { player: selected }) => {\n\n inner.handle_player_selected(player, selected)\n\n }\n\n (GameStateWrapper::Proposing(inner), Action::UnselectPlayer { player: unselected }) => {\n\n inner.handle_player_unselected(player, unselected)\n\n }\n\n (GameStateWrapper::Voting(inner), Action::Vote { upvote }) => {\n\n inner.handle_vote(player, upvote)\n\n }\n\n (GameStateWrapper::Voting(inner), Action::Obscure) => inner.handle_obscure(player),\n\n (GameStateWrapper::OnMission(inner), Action::Play { card }) => {\n\n inner.handle_card(player, card)\n\n }\n\n (GameStateWrapper::OnMission(inner), Action::QuestingBeast) => {\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 68, "score": 71705.35609791313 }, { "content": " roles: self.game.info.clone(),\n\n }));\n\n let next_state = self.with_phase(Done::new(winning_team));\n\n (GameStateWrapper::Done(next_state), effects)\n\n }\n\n}\n\n\n\n/// Macro for repeating identical code across phases, with a fallback for any other phases.\n\n///\n\n/// # Examples\n\n/// ```\n\n/// in_phases!(\n\n/// state,\n\n/// Phase1 | Phase2 => |inner_state| do_stuff(inner_state),\n\n/// |other_state| error_message(other_state)\n\n/// )\n\n/// ```\n\nmacro_rules! in_phases {\n\n // Arguments are divided into 3 parts:\n\n // - the expression to match on, of type GameStateWrapper\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 69, "score": 71703.96639133058 }, { "content": " players: HashSet<String>,\n\n}\n\n\n\n// Convenience methods shared across game phases\n\nimpl<P: Phase> GameState<P> {\n\n /// Generate an [`ActionResult`] that keeps the current state and returns an error reply to the player.\n\n fn player_error<S: Into<String>>(self, message: S) -> ActionResult {\n\n (P::wrap(self), vec![player_error(message)])\n\n }\n\n\n\n /// The current mission, indexed starting at 1\n\n fn mission(&self) -> MissionNumber {\n\n self.mission_results.len() as u8 + 1\n\n }\n\n\n\n /// Calculates the number of \"spent\" proposals, for the purposes of determining if force is active\n\n /// - The two proposals on mission 1 do not count\n\n /// - Proposals that are sent do not count. Equivalently, every time a mission is sent we get a proposal back\n\n ///\n\n /// *This will be off by 1 while going on a mission, since the spent proposal has not yet been returned*\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 70, "score": 71703.21038902023 }, { "content": " inner.handle_questing_beast(player)\n\n }\n\n (GameStateWrapper::WaitingForAgravaine(inner), Action::Declare) => {\n\n inner.handle_declaration(player)\n\n }\n\n (GameStateWrapper::Assassination(inner), Action::Assassinate { target, players }) => {\n\n inner.handle_assassination(player, target, players)\n\n }\n\n\n\n (state, Action::Declare) if state.game().players.is(player, Role::Arthur) => {\n\n let (state, effects) =\n\n any_phase!(state, |inner| inner.handle_arthur_declaration(player));\n\n match state {\n\n GameStateWrapper::Voting(inner) => inner.cancel_vote(effects),\n\n state => (state, effects),\n\n }\n\n }\n\n\n\n (state, Action::MoveToAssassination) => in_phases!(state,\n\n Proposing | Voting | OnMission | WaitingForAgravaine => |inner| inner.move_to_assassinate(player),\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 71, "score": 71702.85211532138 }, { "content": " // - included phases, separated by `|`, with a closure-like action\n\n // - a closure-like action for excluded phases\n\n ($wrapper:expr, $($phase:ident)|+ => |$inner:pat| $action:expr , |$other:pat| => $fallback:expr) => {\n\n match $wrapper {\n\n $(\n\n GameStateWrapper::$phase($inner) => $action,\n\n )+\n\n $other => $fallback\n\n }\n\n }\n\n}\n\n\n\nmacro_rules! any_phase {\n\n ($wrapper:expr, |$inner:pat| $action:expr) => {\n\n in_phases!($wrapper, Proposing | Voting | OnMission | WaitingForAgravaine | Assassination => |$inner| $action, |_| => panic!(\"Missing case in any_phase macro!\"))\n\n }\n\n}\n\n\n\nimpl GameStateWrapper {\n\n /// Creates the [`GameState`] wrapper for a new game.\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 72, "score": 71702.20581858413 }, { "content": " };\n\n}\n\n\n\n/// A side-effect of a state transition. In most cases, this will result in sending a message to some or all players.\n\n#[derive(Debug)]\n\npub enum Effect {\n\n Reply(Message),\n\n Broadcast(Message),\n\n Send(String, Message),\n\n StartTimeout(Duration),\n\n ClearTimeout,\n\n}\n\n\n\npub struct Proposal {\n\n proposer: String,\n\n players: HashSet<String>,\n\n}\n\n\n\npub struct MissionResults {\n\n passed: bool,\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 73, "score": 71702.07553169617 }, { "content": " severity: prelude::ToastSeverity::URGENT,\n\n message: format!(\"{} has declared as Arthur!\", player),\n\n }),\n\n ],\n\n )\n\n } else {\n\n self.player_error(\"You cannot declare as Arthur right now\")\n\n }\n\n }\n\n\n\n /// Transition this game state into a new phase. All non-phase-specific state is copied over.\n\n fn with_phase<Q: Phase>(self, next_phase: Q) -> GameState<Q> {\n\n GameState {\n\n phase: next_phase,\n\n game: self.game,\n\n role_state: self.role_state,\n\n proposals: self.proposals,\n\n mission_results: self.mission_results,\n\n }\n\n }\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 74, "score": 71701.79067905156 }, { "content": " proposer: first_proposer.clone(),\n\n mission: 1,\n\n proposals_made: 0,\n\n max_proposals: game.spec.max_proposals,\n\n mission_size: game.spec.mission_size(1),\n\n }));\n\n\n\n let mut state = GameState {\n\n phase,\n\n role_state: RoleState::new(&game),\n\n game,\n\n proposals: vec![],\n\n mission_results: vec![],\n\n };\n\n RoleState::on_round_start(&mut state, &mut effects);\n\n\n\n (GameStateWrapper::Proposing(state), effects)\n\n }\n\n\n\n /// Advance to the next game state given a player action\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 75, "score": 71701.16112717014 }, { "content": "mod assassination;\n\nmod on_mission;\n\nmod proposing;\n\nmod voting;\n\n\n\n/// A bundle of imports needed for most game phases\n\nmod prelude {\n\n pub use super::{\n\n ActionResult, Done, Effect, GameState, GameStateWrapper, MissionResults, Phase, Proposal,\n\n };\n\n\n\n pub use super::assassination::Assassination;\n\n pub use super::on_mission::OnMission;\n\n pub use super::proposing::Proposing;\n\n pub use super::voting::Voting;\n\n\n\n pub use super::super::{\n\n messages::{self, Action, Message, ToastSeverity},\n\n role::{PriorityTarget, Role, Team},\n\n Card, Game, GameSpec,\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 76, "score": 71700.53342913398 }, { "content": "\n\n /// Switch into the `Proposing` state with `proposer` as the next player to propose. In addition to effects\n\n /// related to the next proposal, the returned [`ActionResult`] will include `effects`.\n\n fn into_proposing(self, proposer: String, mut effects: Vec<Effect>) -> ActionResult {\n\n effects.push(Effect::Broadcast(Message::NextProposal {\n\n proposer: proposer.clone(),\n\n mission: self.mission(),\n\n proposals_made: self.spent_proposals(),\n\n max_proposals: self.game.spec.max_proposals,\n\n mission_size: self.game.spec.mission_size(self.mission()),\n\n }));\n\n let next_state = self.with_phase(Proposing::new(proposer));\n\n (GameStateWrapper::Proposing(next_state), effects)\n\n }\n\n\n\n /// Switch into the `Done` state with `winning_team` as the winners. The returned [`ActionResult`]\n\n /// will include `effects`.\n\n fn into_done(self, winning_team: Team, mut effects: Vec<Effect>) -> ActionResult {\n\n effects.push(Effect::Broadcast(Message::GameOver {\n\n winning_team,\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 77, "score": 71699.9095914373 }, { "content": "\n\n/// Wrapper over specific phases, so callers can hold a game in any phase.\n\npub enum GameStateWrapper {\n\n Proposing(GameState<Proposing>),\n\n Voting(GameState<Voting>),\n\n OnMission(GameState<OnMission>),\n\n WaitingForAgravaine(GameState<WaitingForAgravaine>),\n\n Assassination(GameState<Assassination>),\n\n Done(GameState<Done>),\n\n}\n\n\n\n/// State of an in-progress game. Game state is divided into two parts. Data needed in all phases of the game,\n\n/// such as player information, is stored in the `GameState` directly. Phase-specific data, such as how players\n\n/// voted on a specific mission proposal, is stored in a particular [`Phase`] implementation.\n\npub struct GameState<P: Phase> {\n\n /// State specific to the current game phase.\n\n phase: P,\n\n /// Game configuration\n\n game: Game,\n\n role_state: RoleState,\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 78, "score": 71699.60646450096 }, { "content": " fn spent_proposals(&self) -> usize {\n\n self.proposals\n\n .len()\n\n .saturating_sub(2) // Subtract 2 proposals for mission 1\n\n .saturating_sub(self.mission_results.len()) // Subtract 1 proposal for each sent mission\n\n }\n\n\n\n /// Handles an Arthur declaration by recording it and announcing to all players.\n\n fn handle_arthur_declaration(mut self, player: &str) -> ActionResult {\n\n if self.role_state.arthur.can_declare(&self) {\n\n log::debug!(\"{} declared as Arthur\", player);\n\n self.role_state.arthur.declare();\n\n (\n\n P::wrap(self),\n\n vec![\n\n Effect::Broadcast(Message::ArthurCannotDeclare),\n\n Effect::Broadcast(Message::ArthurDeclaration {\n\n player: player.into(),\n\n }),\n\n Effect::Broadcast(Message::Toast {\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 79, "score": 71699.21769377371 }, { "content": " /// All proposals made in the game\n\n proposals: Vec<Proposal>,\n\n /// Results of all completed missions\n\n mission_results: Vec<MissionResults>,\n\n}\n\n\n\n/// Phase used when the game is over.\n\npub struct Done {\n\n winning_team: Team,\n\n}\n\n\n\n/// A phase of the THavalon state machine\n", "file_path": "thavalon-server/src/game/state.rs", "rank": 80, "score": 71697.57818513461 }, { "content": "export function Lobby(props: LobbyProps): JSX.Element {\n\n // State for maintaining the player list.\n\n const [playerList, setPlayerList] = useState<string[]>([]);\n\n\n\n /**\n\n * Handles any lobby messages that come from the server. If the message type\n\n * is a PlayerList change, the playerList is updated accordingly.\n\n * @param message An incoming message from the server\n\n */\n\n function handleLobbyMessage(message: InboundMessage): void {\n\n if (message.messageType === InboundMessageType.PlayerList) {\n\n setPlayerList(message.data as string[]);\n\n }\n\n }\n\n\n\n // useEffect handles componentDidMount and componentWillUnmount steps.\n\n useEffect(() => {\n\n // On mount, get the connection instance and set up event handlers.\n\n // Then, get the player list.\n\n const connection = GameSocket.getInstance();\n\n connection?.onLobbyEvent.subscribe(handleLobbyMessage);\n\n connection?.sendMessage({ messageType: OutboundMessageType.GetPlayerList });\n\n\n\n // On unmount, unsubscribe our event handlers.\n\n return () => {\n\n const connection = GameSocket.getInstance();\n\n connection?.onLobbyEvent.unsubscribe(handleLobbyMessage);\n\n }\n\n }, []);\n\n\n\n const connection = GameSocket.getInstance();\n\n // Create the player ListGroup items with each player name.\n\n const players = playerList.map((player) =>\n\n <ListGroup.Item key={player}>{player}</ListGroup.Item>\n\n );\n\n\n\n return (\n\n <Container>\n\n <h1>Friend Code: {props.friendCode}</h1>\n\n <ListGroup variant=\"flush\">\n\n {players}\n\n </ListGroup>\n\n <Button\n\n variant=\"primary\"\n\n onClick={() => connection?.sendMessage({ messageType: OutboundMessageType.StartGame })}>\n\n Start Game\n\n </Button>\n\n </Container>\n\n );\n", "file_path": "thavalon-webapp/src/components/gameComponents/lobby.tsx", "rank": 81, "score": 71504.84881226261 }, { "content": "interface LobbyProps {\n\n friendCode: string\n", "file_path": "thavalon-webapp/src/components/gameComponents/lobby.tsx", "rank": 82, "score": 70421.5776000094 }, { "content": "export function PlayerBoard(): JSX.Element {\n\n // On mount, set up event handlers for the game socket and the DOM.\n\n // On unmount, clean up event handlers.\n\n useEffect(() => {\n\n const connection = GameSocket.getInstance();\n\n connection.onGameEvent.subscribe(handleMessage);\n\n connection.onLobbyEvent.subscribe(handleMessage);\n\n // TODO: fix the tabbed out indicator.\n\n // document.onvisibilitychange = () => sendPlayerVisibilityChange();\n\n return () => {\n\n connection.onGameEvent.unsubscribe(handleMessage);\n\n connection.onLobbyEvent.unsubscribe(handleMessage);\n\n // document.onvisibilitychange = null;\n\n }\n\n }, [handleMessage])\n\n\n\n // State for maintaining the player list.\n\n const [playerList, setPlayerList] = useState<string[]>([])\n\n // State maintaining selected players. These players are highlighted in green.\n\n const [primarySelectedPlayers, setPrimarySelectedPlayers] = useState(new Set<string>());\n\n // State maintaining the secondary selected players. These players are highlighted in red.\n\n const [secondarySelectedPlayers, setSecondarySelectedPlayers] = useState(new Set<string>());\n\n // State for maintaining players who are tabbed out. These players have a tab indicator.\n\n const [tabbedOutPlayers, setTabbedOutPlayers] = useState(new Set<string>());\n\n // State for maintaining the current game phase\n\n const [gamePhase, setGamePhase] = useState(GamePhase.Proposal);\n\n // State for maintaining the current mission number\n\n const [missionNumber, setMissionNumber] = useState(1);\n\n // State for tracking who this player is\n\n const [me, setMe] = useState(\"\");\n\n // State for maintaining the last major message, initialized to a default NextProposalMessage\n\n const [majorMessage, setMajorMessage] = useState<NextProposalMessage | MissionGoingMessage>(\n\n {\n\n proposer: \"\",\n\n mission: 1,\n\n mission_size: 2,\n\n max_proposals: 1,\n\n proposals_made: 0\n\n }\n\n );\n\n // State for maintaining the map of players to votes\n\n const [votes, setVotes] = useState<Map<string, Vote>>(new Map<string, Vote>());\n\n // State to show the mission modal or not.\n\n const [showMissionResults, setShowMissionResults] = useState(false);\n\n // State to maintain the mission results.\n\n const [missionResults, setMissionResults] = useState<MissionResultsMessage>();\n\n // State for maintaining the role of a player\n\n const [role, setRole] = useState<Role>(Role.Merlin);\n\n // State for tracking declared players keyed by role. \n\n const [declarationRolesToPlayers, setDeclarationRolesToPlayers] = useState<Map<Role, string>>(new Map());\n\n // State for tracking declared players keyed by player name. \n\n const [declarationPlayersToRoles, setDeclarationPlayersToRoles] = useState<Map<string, Role>>(new Map());\n\n\n\n /**\n\n * Generic message handler for all messages from the server\n\n * @param message The InboundMessage from the server.\n\n */\n\n function handleMessage(message: InboundMessage): void {\n\n switch (message.messageType) {\n\n case InboundMessageType.Snapshot:\n\n const connection = GameSocket.getInstance();\n\n const snapshot = message.data as Snapshot;\n\n setMe(snapshot.me);\n\n setRole(snapshot.roleInfo.role as Role);\n\n // Get proposal order, then get the most recent major message.\n\n // Finally, feed the last message in\n\n snapshot.log.map((message) => connection.sendGameMessage(message));\n\n break;\n\n case InboundMessageType.PlayerFocusChange:\n\n // TODO: Fix the tabbed out indicator\n\n // const { displayName, isTabbedOut } = message.data as PlayerFocusChangeMessage;\n\n // playerFocusChanged(displayName, isTabbedOut);\n\n break;\n\n case InboundMessageType.GameMessage:\n\n handleGameMessage(message.data as GameMessage);\n\n break;\n\n }\n\n }\n\n\n\n /**\n\n * GameMessage specific message handler. This is needed because the GameMessage\n\n * has internal types to parse.\n\n * @param message The GameMessage from the server\n\n */\n\n function handleGameMessage(message: GameMessage): void {\n\n // TODO: This has become a steaming pile of spaghetti and a large source of bugs.\n\n // This could be updated to check for major messages, instead of an \n\n // exclusion list.\n\n const newGamePhase = mapMessageToGamePhase(message.messageType);\n\n if (newGamePhase !== undefined) {\n\n setGamePhase(newGamePhase);\n\n }\n\n switch (message.messageType) {\n\n case GameMessageType.ProposalOrder:\n\n setPlayerList(message.data as string[]);\n\n break;\n\n case GameMessageType.NextProposal:\n\n const data = message.data as NextProposalMessage;\n\n if (data.mission > 1) {\n\n setPrimarySelectedPlayers(new Set());\n\n setSecondarySelectedPlayers(new Set());\n\n }\n\n setMissionNumber(data.mission);\n\n setMajorMessage(data);\n\n break;\n\n case GameMessageType.VotingResults:\n\n // If results are public, set them here. Otherwise, trigger toast for Maeve.\n\n const votingResults = message.data as VotingResultsMessage;\n\n if (votingResults.counts.voteType === \"Public\") {\n\n const { upvotes, downvotes } = votingResults.counts;\n\n if (typeof upvotes === \"number\" || typeof downvotes === \"number\") {\n\n throw new TypeError(\"Votes for public votes must be string arrays, not numbers.\");\n\n }\n\n const voteMap = new Map<string, Vote>();\n\n for (const player of upvotes) {\n\n voteMap.set(player, Vote.Upvote);\n\n }\n\n for (const player of downvotes) {\n\n voteMap.set(player, Vote.Downvote);\n\n }\n\n console.log(voteMap);\n\n setVotes(voteMap);\n\n } else {\n\n setVotes(new Map());\n\n }\n\n break;\n\n case GameMessageType.MissionGoing:\n\n setMajorMessage(message.data as MissionGoingMessage);\n\n break;\n\n case GameMessageType.MissionResults:\n\n setShowMissionResults(true);\n\n setMissionResults(message.data as MissionResultsMessage);\n\n break;\n\n case GameMessageType.AgravaineDeclaration:\n\n if (missionResults !== undefined) {\n\n const agravaineMessage = message.data as AgravaineDeclarationMessage;\n\n // Update the declaration map with the player\n\n updateDeclaredPlayers(\n\n agravaineMessage.player,\n\n Role.Agravaine,\n\n declarationPlayersToRoles,\n\n declarationRolesToPlayers,\n\n setDeclarationPlayersToRoles,\n\n setDeclarationRolesToPlayers\n\n );\n\n\n\n // Update Mission Results and show modal\n\n const newMissionResult = { ...missionResults };\n\n newMissionResult.passed = false;\n\n setShowMissionResults(true);\n\n setMissionResults(newMissionResult);\n\n }\n\n break;\n\n case GameMessageType.ArthurDeclaration:\n\n const arthurMessage = message.data as ArthurDeclarationMessage;\n\n updateDeclaredPlayers(\n\n arthurMessage.player,\n\n Role.Arthur,\n\n declarationPlayersToRoles,\n\n declarationRolesToPlayers,\n\n setDeclarationPlayersToRoles,\n\n setDeclarationRolesToPlayers\n\n );\n\n // If we're proposing, reset proposal to remove Arthur from\n\n // the proposal.\n\n if (gamePhase === GamePhase.Proposal) {\n\n setPrimarySelectedPlayers(new Set());\n\n setSecondarySelectedPlayers(new Set());\n\n }\n\n break;\n\n }\n\n }\n\n\n\n /**\n\n * Sends a message to the server that the player is tabbed in or out.\n\n */\n\n function sendPlayerVisibilityChange(): void {\n\n const connection = GameSocket.getInstance();\n\n const isTabbedOut = document.visibilityState === \"hidden\" ? true : false;\n\n const message = { messageType: OutboundMessageType.PlayerFocusChange, data: isTabbedOut };\n\n connection.sendMessage(message);\n\n }\n\n\n\n /**\n\n * Updates the tabbed out player list with a new player and visibility\n\n * @param player The player whose focus has changed\n\n * @param visibility The new visibility for that player\n\n */\n\n function playerFocusChanged(player: string, isTabbedOut: boolean): void {\n\n const tempSet = new Set(tabbedOutPlayers.values());\n\n if (isTabbedOut) {\n\n tempSet.add(player);\n\n } else {\n\n tempSet.delete(player);\n\n }\n\n setTabbedOutPlayers(tempSet);\n\n }\n\n\n\n return (\n\n <div className=\"player-board\">\n\n {\n\n gamePhase === GamePhase.Proposal &&\n\n <ProposalManager\n\n message={majorMessage as NextProposalMessage}\n\n me={me}\n\n role={role}\n\n playerList={playerList}\n\n tabbedOutPlayers={tabbedOutPlayers}\n\n primarySelectedPlayers={primarySelectedPlayers}\n\n setPrimarySelectedPlayers={setPrimarySelectedPlayers}\n\n secondarySelectedPlayers={secondarySelectedPlayers}\n\n setSecondarySelectedPlayers={setSecondarySelectedPlayers}\n\n votes={votes}\n\n declarationMap={declarationPlayersToRoles}\n\n mission={missionNumber}\n\n />\n\n }\n\n {\n\n gamePhase === GamePhase.Vote &&\n\n <VoteManager\n\n role={role}\n\n isMissionOne={missionNumber === 1}\n\n playerList={playerList}\n\n primarySelectedPlayers={primarySelectedPlayers}\n\n secondarySelectedPlayers={secondarySelectedPlayers}\n\n tabbedOutPlayers={tabbedOutPlayers}\n\n declarationMap={declarationPlayersToRoles}\n\n />\n\n }\n\n {\n\n gamePhase === GamePhase.Mission &&\n\n <MissionManager\n\n role={role}\n\n me={me}\n\n playerList={playerList}\n\n message={majorMessage as MissionGoingMessage}\n\n primarySelectedPlayers={primarySelectedPlayers}\n\n secondarySelectedPlayers={secondarySelectedPlayers}\n\n tabbedOutPlayers={tabbedOutPlayers}\n\n votes={votes}\n\n declarationMap={declarationPlayersToRoles}\n\n />\n\n }\n\n {\n\n showMissionResults &&\n\n <MissionResultModal\n\n setOpen={setShowMissionResults}\n\n message={missionResults}\n\n agravaine={declarationRolesToPlayers.get(Role.Agravaine)} />\n\n }\n\n </div>\n\n );\n", "file_path": "thavalon-webapp/src/components/gameComponents/playerBoard.tsx", "rank": 83, "score": 70199.75094984344 }, { "content": "export function PlayerCard(props: PlayerCardProps): JSX.Element {\n\n let disabled = false;\n\n if (props.enabled === false) {\n\n disabled = true;\n\n }\n\n\n\n let selectedClassNames = new Array<string>();\n\n if (props.selectedTypes !== undefined) {\n\n for (const selectedType of props.selectedTypes) {\n\n switch (selectedType) {\n\n case SelectedPlayerType.Primary:\n\n selectedClassNames.push(\"player-selected-primary\");\n\n break;\n\n case SelectedPlayerType.Secondary:\n\n selectedClassNames.push(\"player-selected-secondary\");\n\n break;\n\n }\n\n }\n\n if (selectedClassNames.length > 1) {\n\n selectedClassNames = [\"player-selected-all\"];\n\n }\n\n }\n\n\n\n let voteLetter: string = \"\";\n\n if (props.vote === Vote.Upvote) {\n\n voteLetter = \"Upvoted\";\n\n } else if (props.vote === Vote.Downvote) {\n\n voteLetter = \"Downvoted\";\n\n }\n\n\n\n const className = props.className === undefined ? \"\" : props.className;\n\n const baseClassName = className !== \"\" ? className : \"player-card-base\";\n\n return (\n\n <button\n\n disabled={disabled}\n\n className={`${ baseClassName } ${ selectedClassNames.join(\" \") }`}\n\n onClick={() => {\n\n if (props.toggleSelected !== undefined) {\n\n props.toggleSelected(props.name);\n\n }\n\n }}>\n\n <div>\n\n <div style={{\n\n position: \"relative\", float: \"left\"\n\n }}>\n\n {voteLetter}\n\n </div>\n\n {props.tabbedOut &&\n\n <Spinner\n\n className=\"tabbed-out-indicator\"\n\n size=\"sm\"\n\n variant=\"dark\"\n\n animation=\"border\" />}\n\n {props.name}\n\n {props.declaredAs !== undefined ? ` - ${ props.declaredAs }` : \"\"}\n\n <div style={{ position: \"relative\", float: \"right\" }}>\n\n {props.isProposing ? \"Proposing\" : \"\"}\n\n </div>\n\n </div>\n\n </button>\n\n );\n", "file_path": "thavalon-webapp/src/components/gameComponents/playerCard.tsx", "rank": 84, "score": 70192.10163166487 }, { "content": " proposal_index: usize,\n\n}\n\n\n\n/// How long to wait for an Agravaine declaration\n\nconst AGRAVAINE_TIMEOUT: Duration = Duration::from_secs(30);\n\n\n\nimpl GameState<OnMission> {\n\n pub fn handle_card(mut self, player: &str, card: Card) -> ActionResult {\n\n if self.includes_player(player) {\n\n if let Some(card) = self.phase.cards.get(player).cloned() {\n\n self.player_error(format!(\"You already played a {}\", card))\n\n } else if !self\n\n .game\n\n .players\n\n .by_name(player)\n\n .unwrap()\n\n .role\n\n .can_play(card)\n\n {\n\n self.player_error(format!(\"You can't play a {}\", card))\n", "file_path": "thavalon-server/src/game/state/on_mission.rs", "rank": 85, "score": 70144.25478544051 }, { "content": "use std::collections::{HashMap, HashSet};\n\n\n\nuse super::prelude::*;\n\n\n\n/// Phase for voting on a mission proposal\n\npub struct Voting {\n\n /// Map from players to whether they up- or down-voted the proposal.\n\n votes: HashMap<String, bool>,\n\n /// Whether or not the voting results are obscured\n\n obscured: bool,\n\n}\n\n\n\nimpl GameState<Voting> {\n\n pub fn handle_vote(mut self, player: &str, is_upvote: bool) -> ActionResult {\n\n if self.phase.votes.contains_key(player) {\n\n return self.player_error(\"You already voted\");\n\n }\n\n\n\n log::debug!(\n\n \"{} {}\",\n", "file_path": "thavalon-server/src/game/state/voting.rs", "rank": 86, "score": 70143.26420331918 }, { "content": "impl<P: Phase> GameState<P> {\n\n pub fn move_to_assassinate(self, player: &str) -> ActionResult {\n\n if player == self.game.assassin {\n\n log::debug!(\"{} moved to assassinate\", player);\n\n let effects = vec![Effect::Broadcast(Message::BeginAssassination {\n\n assassin: player.to_string(),\n\n })];\n\n let next_state = GameStateWrapper::Assassination(self.with_phase(Assassination {}));\n\n (next_state, effects)\n\n } else {\n\n self.player_error(\"You are not the assassin\")\n\n }\n\n }\n\n}\n\n\n\nimpl_phase!(Assassination);\n", "file_path": "thavalon-server/src/game/state/assassination.rs", "rank": 87, "score": 70142.69062662167 }, { "content": " second_proposal,\n\n mission\n\n );\n\n } else {\n\n let proposal = self.proposals.last().unwrap();\n\n log::debug!(\"Voting on {} for mission {}\", proposal, mission);\n\n }\n\n\n\n effects.push(Effect::Broadcast(Message::CommenceVoting));\n\n let next_state = self.with_phase(Voting::new());\n\n (GameStateWrapper::Voting(next_state), effects)\n\n }\n\n }\n\n\n\n /// Checks if `player` is allowed on this proposal, returning an error message if not.\n\n fn validate_player(&self, player_name: &str) -> Option<String> {\n\n match self.game.players.by_name(player_name) {\n\n Some(player) => {\n\n if player.role == Role::Arthur\n\n && self.role_state.arthur.has_declared()\n", "file_path": "thavalon-server/src/game/state/proposing.rs", "rank": 88, "score": 70142.63056284568 }, { "content": "use std::collections::HashSet;\n\n\n\nuse super::prelude::*;\n\n\n\n/// Phase for waiting for a player to make a mission proposal.\n\npub struct Proposing {\n\n /// The player whose turn it is to propose\n\n proposer: String,\n\n selected_players: HashSet<String>,\n\n}\n\n\n\nconst NOT_PROPOSER_ERROR: &str = \"It's not your proposal\";\n\n\n\nimpl GameState<Proposing> {\n\n /// Respond to the proposer adding a player to their proposal. If the player performing the action\n\n /// is not the proposer, this sends them an error message. It validates that the added player is\n\n /// in the game, but does not check if they are already on the proposal or if the proposal is the\n\n /// correct size, since final validation is done when the proposal is submitted.\n\n pub fn handle_player_selected(mut self, player: &str, added_player: String) -> ActionResult {\n\n if player != self.phase.proposer {\n", "file_path": "thavalon-server/src/game/state/proposing.rs", "rank": 89, "score": 70142.20124956944 }, { "content": " message: toast_message,\n\n },\n\n )\n\n }\n\n}\n\n\n\nimpl OnMission {\n\n /// Create a new `OnMission` phase given the proposal used for it\n\n pub fn new(proposal_index: usize) -> OnMission {\n\n OnMission {\n\n proposal_index,\n\n cards: HashMap::new(),\n\n questing_beasts: 0,\n\n }\n\n }\n\n}\n\n\n\nimpl GameState<WaitingForAgravaine> {\n\n pub fn handle_declaration(mut self, player: &str) -> ActionResult {\n\n // Subtract one since the mission Agravaine failing is the one prior to the current propposal.\n", "file_path": "thavalon-server/src/game/state/on_mission.rs", "rank": 90, "score": 70142.14578199726 }, { "content": " && self.mission() != 5\n\n {\n\n Some(format!(\"Arthur cannot go until mission 5\"))\n\n } else {\n\n None\n\n }\n\n }\n\n None => Some(format!(\"{} is not in the game\", player_name)),\n\n }\n\n }\n\n}\n\n\n\nimpl Proposing {\n\n /// Create a new `Proposing` phase given the player proposing.\n\n pub fn new(proposer: String) -> Proposing {\n\n Proposing {\n\n proposer,\n\n selected_players: HashSet::new(),\n\n }\n\n }\n\n}\n\n\n\nimpl_phase!(Proposing);\n", "file_path": "thavalon-server/src/game/state/proposing.rs", "rank": 91, "score": 70140.06477496849 }, { "content": " player: &str,\n\n removed_player: String,\n\n ) -> ActionResult {\n\n if player != self.phase.proposer {\n\n return self.player_error(NOT_PROPOSER_ERROR);\n\n }\n\n\n\n if self.game.players.by_name(&removed_player).is_none() {\n\n return self.player_error(format!(\"{} is not in the game!\", removed_player));\n\n }\n\n\n\n if self.phase.selected_players.remove(&removed_player) {\n\n let effects = vec![Effect::Broadcast(Message::ProposalUpdated {\n\n players: self.phase.selected_players.clone(),\n\n })];\n\n\n\n (GameStateWrapper::Proposing(self), effects)\n\n } else {\n\n self.player_error(format!(\"{} wasn't on the proposal!\", removed_player))\n\n }\n", "file_path": "thavalon-server/src/game/state/proposing.rs", "rank": 92, "score": 70139.94325408373 }, { "content": " }\n\n }\n\n } else {\n\n // If we don't have all the votes yet, there's no state change\n\n (GameStateWrapper::Voting(self), effects)\n\n }\n\n }\n\n\n\n pub fn handle_obscure(mut self, player: &str) -> ActionResult {\n\n if self.game.players.by_name(player).unwrap().role == Role::Maeve {\n\n if self.phase.obscured {\n\n self.player_error(\"You already obscured the votes for this proposal\")\n\n } else if self.role_state.maeve.can_obscure() {\n\n log::debug!(\"Maeve obscured the votes!\");\n\n self.role_state.maeve.mark_obscure();\n\n self.phase.obscured = true;\n\n (GameStateWrapper::Voting(self), vec![])\n\n } else {\n\n self.player_error(\"You can't obscure this round\")\n\n }\n", "file_path": "thavalon-server/src/game/state/voting.rs", "rank": 93, "score": 70139.88518840753 }, { "content": " players: proposal.players.clone(),\n\n }));\n\n let next_state = self.with_phase(OnMission::new(proposal_index));\n\n (GameStateWrapper::OnMission(next_state), effects)\n\n } else {\n\n let proposal = self.proposals.last().expect(\"Voted with no proposals!\");\n\n if sent {\n\n log::debug!(\"Voted to send {} on mission {}\", proposal, mission);\n\n effects.push(Effect::Broadcast(Message::MissionGoing {\n\n mission,\n\n players: proposal.players.clone(),\n\n }));\n\n let proposal_index = self.proposals.len() - 1;\n\n let next_state = self.with_phase(OnMission::new(proposal_index));\n\n (GameStateWrapper::OnMission(next_state), effects)\n\n } else {\n\n log::debug!(\"Voted not to send {}\", proposal);\n\n\n\n let next_proposer = self.game.next_proposer(&proposal.proposer).to_string();\n\n self.into_proposing(next_proposer, effects)\n", "file_path": "thavalon-server/src/game/state/voting.rs", "rank": 94, "score": 70132.00063143972 }, { "content": " self,\n\n player: &str,\n\n target: PriorityTarget,\n\n players: HashSet<String>,\n\n ) -> ActionResult {\n\n if player == self.game.assassin {\n\n log::debug!(\n\n \"{} assassinated {} as {:?}\",\n\n player,\n\n players.iter().format(\" and \"),\n\n target\n\n );\n\n\n\n // All priority assassinations (so far) take the form of \"X players are one of Y roles\", so we model that as\n\n // `expected_targets` and `matches` methods on `PriorityTarget` to cut down on duplication.\n\n // The `None` priority target is special, because it matches no players.\n\n\n\n if players.len() != target.expected_targets() {\n\n return self.player_error(format!(\n\n \"You must assassinate {} players as {:?}\",\n", "file_path": "thavalon-server/src/game/state/assassination.rs", "rank": 95, "score": 70131.90054144677 }, { "content": " (next_state, effects)\n\n } else if fails == 3 {\n\n log::debug!(\"3 missions have failed, the Evil team has won\");\n\n state.into_done(Team::Evil, effects)\n\n } else {\n\n let mission = state.mission();\n\n let next_proposer = if mission == 2 {\n\n // On mission 2, the third proposer goes first, because the first 2 proposers already proposed for mission 1\n\n // the mod is to account for 2-player testing games, for which we wrap back around to player 1\n\n // Note: the index of the 3rd proposer is 2\n\n let next_proposer_index = 2 % state.game.proposal_order.len();\n\n state.game.proposal_order[next_proposer_index].clone()\n\n } else {\n\n let mission_proposer = &state.proposals[proposal].proposer;\n\n state.game.next_proposer(mission_proposer).to_string()\n\n };\n\n\n\n RoleState::on_round_start(&mut state, &mut effects);\n\n state.into_proposing(next_proposer, effects)\n\n }\n\n}\n\n\n", "file_path": "thavalon-server/src/game/state/on_mission.rs", "rank": 96, "score": 70131.7228232035 }, { "content": "use std::collections::HashMap;\n\nuse std::time::Duration;\n\n\n\nuse super::prelude::*;\n\nuse super::RoleState;\n\n\n\n/// Phase for when the voted-on players are going on a mission\n\npub struct OnMission {\n\n /// The proposal this mission is based on. Used to check if players are on the mission or not\n\n proposal_index: usize,\n\n\n\n /// Cards played by each player on the mission.\n\n cards: HashMap<String, Card>,\n\n\n\n /// The number of questing beasts played\n\n questing_beasts: usize,\n\n}\n\n\n\n/// Placeholder phase used when waiting for Agravaine to declare\n\npub struct WaitingForAgravaine {\n", "file_path": "thavalon-server/src/game/state/on_mission.rs", "rank": 97, "score": 70131.5460387019 }, { "content": " return self.player_error(NOT_PROPOSER_ERROR);\n\n }\n\n\n\n if let Some(error) = self.validate_player(player) {\n\n return self.player_error(error);\n\n }\n\n\n\n self.phase.selected_players.insert(added_player);\n\n let effects = vec![Effect::Broadcast(Message::ProposalUpdated {\n\n players: self.phase.selected_players.clone(),\n\n })];\n\n\n\n (GameStateWrapper::Proposing(self), effects)\n\n }\n\n\n\n /// Respond to the proposer removing a player from their proposal. If the player performing the action is not\n\n /// the proposer, this sends them an error message. It also validates that the removed player is in the game\n\n /// and was on the proposal.\n\n pub fn handle_player_unselected(\n\n mut self,\n", "file_path": "thavalon-server/src/game/state/proposing.rs", "rank": 98, "score": 70131.16790279651 }, { "content": " target.expected_targets(),\n\n target\n\n ));\n\n }\n\n\n\n let mut is_correct = true;\n\n if target == PriorityTarget::None {\n\n // If there are no assassination targets in the game, we'll have checked for that at the beginning\n\n is_correct = self.game.priority_target == PriorityTarget::None\n\n } else {\n\n for name in players.iter() {\n\n if let Some(player) = self.game.players.by_name(name) {\n\n if !target.matches(player) {\n\n is_correct = false;\n\n }\n\n } else {\n\n return self.player_error(format!(\"{} is not in the game\", name));\n\n }\n\n }\n\n }\n", "file_path": "thavalon-server/src/game/state/assassination.rs", "rank": 99, "score": 70130.84896794973 } ]
Rust
src/mevdb.rs
sambacha/mev-inspect-rs
9d111bf50910f188c3ee66624d5b25b41757c0e1
use crate::types::Evaluation; use ethers::types::{TxHash, U256}; use rust_decimal::prelude::*; use thiserror::Error; use tokio_postgres::{config::Config, Client, NoTls}; pub struct MevDB<'a> { client: Client, table_name: &'a str, overwrite: String, } impl<'a> MevDB<'a> { pub async fn connect(cfg: Config, table_name: &'a str) -> Result<MevDB<'a>, DbError> { let (client, connection) = cfg.connect(NoTls).await?; tokio::spawn(async move { if let Err(e) = connection.await { eprintln!("connection error: {}", e); } }); let overwrite = "on conflict do nothing"; Ok(Self { client, table_name, overwrite: overwrite.to_owned(), }) } pub async fn create(&mut self) -> Result<(), DbError> { self.client .batch_execute(&format!( "CREATE TABLE IF NOT EXISTS {} ( hash text PRIMARY KEY, status text, block_number NUMERIC, gas_price NUMERIC, gas_used NUMERIC, revenue NUMERIC, protocols text[], actions text[], eoa text, contract text, proxy_impl text, inserted_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() )", self.table_name )) .await?; Ok(()) } pub async fn insert(&mut self, evaluation: &Evaluation) -> Result<(), DbError> { self.client .execute( format!( "INSERT INTO {} ( hash, status, block_number, gas_price, gas_used, revenue, protocols, actions, eoa, contract, proxy_impl ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) {}", self.table_name, self.overwrite, ) .as_str(), &[ &format!("{:?}", evaluation.inspection.hash), &format!("{:?}", evaluation.inspection.status), &Decimal::from(evaluation.inspection.block_number), &u256_decimal(evaluation.gas_price)?, &u256_decimal(evaluation.gas_used)?, &u256_decimal(evaluation.profit)?, &vec_str(&evaluation.inspection.protocols), &vec_str(&evaluation.actions), &format!("{:?}", evaluation.inspection.from), &format!("{:?}", evaluation.inspection.contract), &evaluation .inspection .proxy_impl .map(|x| format!("{:?}", x)) .unwrap_or_else(|| "".to_owned()), ], ) .await?; Ok(()) } pub async fn exists(&mut self, hash: TxHash) -> Result<bool, DbError> { let rows = self .client .query( format!("SELECT hash FROM {} WHERE hash = $1", self.table_name).as_str(), &[&format!("{:?}", hash)], ) .await?; if let Some(row) = rows.get(0) { let got: String = row.get(0); Ok(format!("{:?}", hash) == got) } else { Ok(false) } } pub async fn block_exists(&mut self, block: u64) -> Result<bool, DbError> { let rows = self .client .query( format!( "SELECT block_number FROM {} WHERE block_number = $1 LIMIT 1;", self.table_name ) .as_str(), &[&Decimal::from_u64(block).ok_or(DbError::InvalidDecimal)?], ) .await?; if rows.get(0).is_some() { Ok(true) } else { Ok(false) } } pub async fn clear(&mut self) -> Result<(), DbError> { self.client .batch_execute(&format!("DROP TABLE {}", self.table_name)) .await?; Ok(()) } } #[derive(Error, Debug)] pub enum DbError { #[error(transparent)] Decimal(#[from] rust_decimal::Error), #[error("could not convert u64 to decimal")] InvalidDecimal, #[error(transparent)] TokioPostGres(#[from] tokio_postgres::Error), } fn vec_str<T: std::fmt::Debug, I: IntoIterator<Item = T>>(t: I) -> Vec<String> { t.into_iter() .map(|i| format!("{:?}", i).to_lowercase()) .collect::<Vec<_>>() } fn u256_decimal(src: U256) -> Result<Decimal, rust_decimal::Error> { Decimal::from_str(&src.to_string()) } #[cfg(all(test, feature = "postgres-tests"))] mod tests { use super::*; use crate::types::evaluation::ActionType; use crate::types::Inspection; use ethers::types::{Address, TxHash}; use std::collections::HashSet; #[tokio::test] async fn insert_eval() { let mut client = MevDB::connect("localhost", "postgres", None, "test_table") .await .unwrap(); client.clear().await.unwrap(); client.create().await.unwrap(); let inspection = Inspection { status: crate::types::Status::Checked, actions: Vec::new(), protocols: Vec::new(), from: Address::zero(), contract: Address::zero(), proxy_impl: None, hash: TxHash::zero(), block_number: 9, }; let actions = [ActionType::Liquidation, ActionType::Arbitrage] .iter() .cloned() .collect::<HashSet<_>>(); let evaluation = Evaluation { inspection, gas_used: 21000.into(), gas_price: (100e9 as u64).into(), actions, profit: (1e18 as u64).into(), }; client.insert(&evaluation).await.unwrap(); assert!(client.exists(evaluation.as_ref().hash).await.unwrap()); client.insert(&evaluation).await.unwrap(); } }
use crate::types::Evaluation; use ethers::types::{TxHash, U256}; use rust_decimal::prelude::*; use thiserror::Error; use tokio_postgres::{config::Config, Client, NoTls}; pub struct MevDB<'a> { client: Client, table_name: &'a str, overwrite: String, } impl<'a> MevDB<'a> { pub async fn connect(cfg: Config, table_name: &'a str) -> Result<MevDB<'a>, DbError> { let (client, connection) = cfg.connect(NoTls).await?; tokio::spawn(async move { if let Err(e) = connection.await { eprintln!("connection error: {}", e); } }); let overwrite = "on conflict do nothing"; Ok(Self { client, table_name, overwrite: overwrite.to_owned(), }) } pub async fn create(&mut self) -> Result<(), DbError> { self.client .batch_execute(&format!( "CREATE TABLE IF NOT EXISTS {} ( hash text PRIMARY KEY, status text, block_number NUMERIC, gas_price NUMERIC, gas_used NUMERIC, revenue NUMERIC, protocols text[], actions text[], eoa text, contract text, proxy_impl text, inserted_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() )", self.table_name )) .await?; Ok(()) } pub async fn insert(&mut self, evaluation: &Evaluation) -> Result<(), DbError> { self.client .execute( format!( "INSERT INTO {} ( hash, status, block_number, gas_price, gas_used, revenue, protocols, actions, eoa,
pub async fn exists(&mut self, hash: TxHash) -> Result<bool, DbError> { let rows = self .client .query( format!("SELECT hash FROM {} WHERE hash = $1", self.table_name).as_str(), &[&format!("{:?}", hash)], ) .await?; if let Some(row) = rows.get(0) { let got: String = row.get(0); Ok(format!("{:?}", hash) == got) } else { Ok(false) } } pub async fn block_exists(&mut self, block: u64) -> Result<bool, DbError> { let rows = self .client .query( format!( "SELECT block_number FROM {} WHERE block_number = $1 LIMIT 1;", self.table_name ) .as_str(), &[&Decimal::from_u64(block).ok_or(DbError::InvalidDecimal)?], ) .await?; if rows.get(0).is_some() { Ok(true) } else { Ok(false) } } pub async fn clear(&mut self) -> Result<(), DbError> { self.client .batch_execute(&format!("DROP TABLE {}", self.table_name)) .await?; Ok(()) } } #[derive(Error, Debug)] pub enum DbError { #[error(transparent)] Decimal(#[from] rust_decimal::Error), #[error("could not convert u64 to decimal")] InvalidDecimal, #[error(transparent)] TokioPostGres(#[from] tokio_postgres::Error), } fn vec_str<T: std::fmt::Debug, I: IntoIterator<Item = T>>(t: I) -> Vec<String> { t.into_iter() .map(|i| format!("{:?}", i).to_lowercase()) .collect::<Vec<_>>() } fn u256_decimal(src: U256) -> Result<Decimal, rust_decimal::Error> { Decimal::from_str(&src.to_string()) } #[cfg(all(test, feature = "postgres-tests"))] mod tests { use super::*; use crate::types::evaluation::ActionType; use crate::types::Inspection; use ethers::types::{Address, TxHash}; use std::collections::HashSet; #[tokio::test] async fn insert_eval() { let mut client = MevDB::connect("localhost", "postgres", None, "test_table") .await .unwrap(); client.clear().await.unwrap(); client.create().await.unwrap(); let inspection = Inspection { status: crate::types::Status::Checked, actions: Vec::new(), protocols: Vec::new(), from: Address::zero(), contract: Address::zero(), proxy_impl: None, hash: TxHash::zero(), block_number: 9, }; let actions = [ActionType::Liquidation, ActionType::Arbitrage] .iter() .cloned() .collect::<HashSet<_>>(); let evaluation = Evaluation { inspection, gas_used: 21000.into(), gas_price: (100e9 as u64).into(), actions, profit: (1e18 as u64).into(), }; client.insert(&evaluation).await.unwrap(); assert!(client.exists(evaluation.as_ref().hash).await.unwrap()); client.insert(&evaluation).await.unwrap(); } }
contract, proxy_impl ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) {}", self.table_name, self.overwrite, ) .as_str(), &[ &format!("{:?}", evaluation.inspection.hash), &format!("{:?}", evaluation.inspection.status), &Decimal::from(evaluation.inspection.block_number), &u256_decimal(evaluation.gas_price)?, &u256_decimal(evaluation.gas_used)?, &u256_decimal(evaluation.profit)?, &vec_str(&evaluation.inspection.protocols), &vec_str(&evaluation.actions), &format!("{:?}", evaluation.inspection.from), &format!("{:?}", evaluation.inspection.contract), &evaluation .inspection .proxy_impl .map(|x| format!("{:?}", x)) .unwrap_or_else(|| "".to_owned()), ], ) .await?; Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn get_trace(hash: &str) -> Inspection {\n\n let hash = if hash.starts_with(\"0x\") {\n\n &hash[2..]\n\n } else {\n\n hash\n\n };\n\n\n\n TraceWrapper(\n\n TRACES\n\n .iter()\n\n .filter(|t| t.transaction_hash == Some(hash.parse::<TxHash>().unwrap()))\n\n .cloned()\n\n .collect::<Vec<_>>(),\n\n )\n\n .try_into()\n\n .unwrap()\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! set {\n", "file_path": "src/test_helpers/mod.rs", "rank": 0, "score": 167333.36382563927 }, { "content": "pub fn lookup(address: Address) -> String {\n\n ADDRESSBOOK\n\n .get(&address)\n\n .unwrap_or(&format!(\"{:?}\", &address))\n\n .clone()\n\n}\n\n\n", "file_path": "src/addresses.rs", "rank": 2, "score": 133168.728397316 }, { "content": "pub fn parse_address(addr: &str) -> Address {\n\n let addr = addr.strip_prefix(\"0x\").unwrap_or(addr);\n\n addr.parse().unwrap()\n\n}\n", "file_path": "src/addresses.rs", "rank": 3, "score": 129945.81235561219 }, { "content": "pub fn read_trace(path: &str) -> Inspection {\n\n let input = std::fs::read_to_string(format!(\"res/{}\", path)).unwrap();\n\n let traces: Vec<Trace> = serde_json::from_str(&input).unwrap();\n\n TraceWrapper(traces).try_into().unwrap()\n\n}\n\n\n", "file_path": "src/test_helpers/mod.rs", "rank": 4, "score": 124525.83131122586 }, { "content": "pub fn mk_inspection(actions: Vec<Classification>) -> Inspection {\n\n Inspection {\n\n status: Status::Success,\n\n actions,\n\n protocols: HashSet::new(),\n\n from: Address::zero(),\n\n contract: Address::zero(),\n\n proxy_impl: None,\n\n hash: TxHash::zero(),\n\n block_number: 0,\n\n }\n\n}\n\n\n", "file_path": "src/test_helpers/mod.rs", "rank": 5, "score": 103256.71830743023 }, { "content": "fn uniswappy(call: &TraceCall) -> Protocol {\n\n if let Some(protocol) = PROTOCOLS.get(&call.to) {\n\n *protocol\n\n } else if let Some(protocol) = PROTOCOLS.get(&call.from) {\n\n *protocol\n\n } else {\n\n Protocol::Uniswappy\n\n }\n\n}\n\n\n\nimpl Uniswap {\n\n /// Constructor\n\n pub fn new() -> Self {\n\n Self {\n\n router: BaseContract::from({\n\n serde_json::from_str::<Abi>(include_str!(\"../../abi/unirouterv2.json\"))\n\n .expect(\"could not parse uniswap abi\")\n\n }),\n\n pair: BaseContract::from({\n\n serde_json::from_str::<Abi>(include_str!(\"../../abi/unipair.json\"))\n", "file_path": "src/inspectors/uniswap.rs", "rank": 7, "score": 89196.00910671215 }, { "content": "pub fn addrs() -> Vec<Address> {\n\n use ethers::core::rand::thread_rng;\n\n (0..10)\n\n .into_iter()\n\n .map(|_| ethers::signers::LocalWallet::new(&mut thread_rng()).address())\n\n .collect()\n\n}\n\n\n", "file_path": "src/test_helpers/mod.rs", "rank": 8, "score": 87708.18674915982 }, { "content": "fn insert_many<T: Clone>(\n\n mut map: HashMap<Address, T>,\n\n addrs: &[&str],\n\n value: T,\n\n) -> HashMap<Address, T> {\n\n for addr in addrs {\n\n map.insert(parse_address(addr), value.clone());\n\n }\n\n map\n\n}\n\n\n", "file_path": "src/addresses.rs", "rank": 9, "score": 76168.73236044527 }, { "content": "type AddLiquidity = (Address, Address, U256, U256, U256, U256, Address, U256);\n\n\n\n#[derive(Debug, Clone)]\n\n/// An inspector for Uniswap\n\npub struct Uniswap {\n\n router: BaseContract,\n\n pair: BaseContract,\n\n}\n\n\n\nimpl Inspector for Uniswap {\n\n fn inspect(&self, inspection: &mut Inspection) {\n\n let num_protocols = inspection.protocols.len();\n\n let actions = inspection.actions.to_vec();\n\n\n\n let mut prune: Vec<usize> = Vec::new();\n\n let mut has_trade = false;\n\n for i in 0..inspection.actions.len() {\n\n let action = &mut inspection.actions[i];\n\n\n\n if let Some(calltrace) = action.as_call() {\n", "file_path": "src/inspectors/uniswap.rs", "rank": 10, "score": 66801.05990489518 }, { "content": "type Swap = (Address, U256, Address, U256, U256);\n\n\n\nimpl Inspector for Balancer {\n\n fn inspect(&self, inspection: &mut Inspection) {\n\n let actions = inspection.actions.to_vec();\n\n let mut prune = Vec::new();\n\n for i in 0..inspection.actions.len() {\n\n let action = &mut inspection.actions[i];\n\n\n\n if let Some(calltrace) = action.as_call() {\n\n let call = calltrace.as_ref();\n\n let (token_in, _, token_out, _, _) = if let Ok(inner) = self\n\n .bpool\n\n .decode::<Swap, _>(\"swapExactAmountIn\", &call.input)\n\n {\n\n inner\n\n } else if let Ok(inner) = self\n\n .bpool\n\n .decode::<Swap, _>(\"swapExactAmountOut\", &call.input)\n\n {\n", "file_path": "src/inspectors/balancer.rs", "rank": 11, "score": 62654.49131640601 }, { "content": "// Type aliases for Uniswap's `swap` return types\n\ntype SwapTokensFor = (U256, U256, Vec<Address>, Address, U256);\n", "file_path": "src/inspectors/uniswap.rs", "rank": 12, "score": 60663.29339153023 }, { "content": "// Type aliases for Curve\n\ntype Exchange = (u128, u128, U256, U256);\n\n\n\n#[derive(Debug, Clone)]\n\n/// An inspector for Curve\n\npub struct Curve {\n\n pool: BaseContract,\n\n pool4: BaseContract,\n\n pools: HashMap<Address, Vec<Address>>,\n\n}\n\n\n\nabigen!(\n\n CurveRegistry,\n\n \"abi/curveregistry.json\",\n\n methods {\n\n find_pool_for_coins(address,address,uint256) as find_pool_for_coins2;\n\n }\n\n);\n\n\n\nimpl Inspector for Curve {\n\n fn inspect(&self, inspection: &mut Inspection) {\n", "file_path": "src/inspectors/curve.rs", "rank": 13, "score": 56846.44929657213 }, { "content": "type PairSwap = (U256, U256, Address, Bytes);\n", "file_path": "src/inspectors/uniswap.rs", "rank": 14, "score": 56004.51640683861 }, { "content": "#[derive(Debug, Options, Clone)]\n\nstruct Opts {\n\n help: bool,\n\n\n\n #[options(help = \"clear and re-build the database\")]\n\n reset: bool,\n\n\n\n #[options(help = \"do not skip blocks which already exist\")]\n\n overwrite: bool,\n\n\n\n #[options(\n\n default = \"http://localhost:8545\",\n\n help = \"The tracing / archival node's URL\"\n\n )]\n\n url: String,\n\n\n\n #[options(help = \"Path to where traces will be cached\")]\n\n cache: Option<PathBuf>,\n\n\n\n #[options(help = \"Database config\")]\n\n db_cfg: tokio_postgres::Config,\n\n #[options(default = \"mev_inspections\", help = \"the table of the database\")]\n\n db_table: String,\n\n\n\n // Single tx or many blocks\n\n #[options(command)]\n\n cmd: Option<Command>,\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 15, "score": 55388.434022050074 }, { "content": "type SwapEthFor = (U256, Vec<Address>, Address, U256);\n", "file_path": "src/inspectors/uniswap.rs", "rank": 16, "score": 54417.87782592677 }, { "content": "#[derive(Debug, Options, Clone)]\n\nstruct TxOpts {\n\n help: bool,\n\n #[options(free, help = \"the transaction's hash\")]\n\n tx: TxHash,\n\n}\n", "file_path": "src/main.rs", "rank": 17, "score": 54013.23425893849 }, { "content": "#[derive(Debug, Options, Clone)]\n\nstruct BlockOpts {\n\n help: bool,\n\n #[options(help = \"the block to start tracing from\")]\n\n from: u64,\n\n #[options(help = \"the block to finish tracing at\")]\n\n to: u64,\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> anyhow::Result<()> {\n\n let opts = Opts::parse_args_default_or_exit();\n\n\n\n // Instantiate the provider and read from the cached files if needed\n\n if let Some(ref cache) = opts.cache {\n\n let provider = CachedProvider::new(Provider::try_from(opts.url.as_str())?, cache);\n\n run(provider, opts).await\n\n } else {\n\n let provider = Provider::try_from(opts.url.as_str())?;\n\n run(provider, opts).await\n\n }\n", "file_path": "src/main.rs", "rank": 18, "score": 54013.23425893849 }, { "content": "pub trait Reducer {\n\n /// By default the reducer is empty. A consumer may optionally\n\n /// implement this method to perform additional actions on the classified &\n\n /// filtered results.\n\n fn reduce(&self, _: &mut Inspection);\n\n}\n\n\n", "file_path": "src/traits.rs", "rank": 19, "score": 51181.915641750165 }, { "content": "/// Trait for defining an inspector for a specific DeFi protocol\n\npub trait Inspector: core::fmt::Debug {\n\n /// Classifies an inspection's actions\n\n fn inspect(&self, inspection: &mut Inspection);\n\n}\n", "file_path": "src/traits.rs", "rank": 20, "score": 44221.71977497585 }, { "content": "type LiquidateBorrow = (Address, U256, Address);\n", "file_path": "src/inspectors/compound.rs", "rank": 21, "score": 43485.7169814558 }, { "content": "type SeizeInternal = (Address, Address, Address, U256);\n\n\n\nabigen!(\n\n Comptroller,\n\n \"abi/comptroller.json\",\n\n methods {\n\n // TODO: Fix bug in ethers-rs so that we can rename them properly\n\n borrowGuardianPaused(address) as borrow_guardian_paused2;\n\n mintGuardianPaused(address) as mint_guardian_paused2;\n\n actionGuardianPaused(address) as action_paused2;\n\n },\n\n);\n\n\n\nabigen!(CToken, \"abi/ctoken.json\",);\n\n\n\n#[derive(Debug, Clone)]\n\n/// An inspector for Compound liquidations\n\npub struct Compound {\n\n ctoken: BaseContract,\n\n cether: BaseContract,\n", "file_path": "src/inspectors/compound.rs", "rank": 22, "score": 41586.72549460694 }, { "content": "// reads line-separated addresses from a file path and returns them as a vector\n\nfn read_addrs<P>(path: P) -> Vec<Address>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n let file = File::open(path).unwrap();\n\n let lines = io::BufReader::new(file).lines();\n\n lines.map(|line| parse_address(&line.unwrap())).collect()\n\n}\n\n\n\n// Protocol Addrs\n\npub static PROTOCOLS: Lazy<HashMap<Address, Protocol>> = Lazy::new(|| {\n\n let map = HashMap::new();\n\n let map = insert_many(\n\n map,\n\n &[\n\n \"0x9346c20186d1794101b8517177a1b15c49c9ff9b\",\n\n \"0x2b095969ae40BcE8BaAF515B16614A636C22a6Db\",\n\n \"0x2fdbadf3c4d5a8666bc06645b8358ab803996e28\",\n\n \"0x7a250d5630b4cf539739df2c5dacb4c659f2488d\",\n\n \"0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc\",\n", "file_path": "src/addresses.rs", "rank": 23, "score": 40728.11067430656 }, { "content": "type LiquidationCall = (Address, Address, Address, U256, bool);\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Aave {\n\n pub pool: BaseContract,\n\n}\n\n\n\nimpl Aave {\n\n pub fn new() -> Self {\n\n Aave {\n\n pool: BaseContract::from({\n\n serde_json::from_str::<Abi>(include_str!(\"../../abi/aavepool.json\"))\n\n .expect(\"could not parse aave abi\")\n\n }),\n\n }\n\n }\n\n}\n\n\n\nimpl Inspector for Aave {\n\n fn inspect(&self, inspection: &mut Inspection) {\n", "file_path": "src/inspectors/aave.rs", "rank": 24, "score": 39857.918986444085 }, { "content": "type BridgeTransfer = (Address, Address, Address, U256, Bytes);\n\n\n\nimpl ZeroEx {\n\n pub fn new() -> Self {\n\n let bridge = BaseContract::from(\n\n parse_abi(&[\n\n \"function bridgeTransferFrom(address tokenAddress, address from, address to, uint256 amount, bytes calldata bridgeData)\"\n\n ]).expect(\"could not parse bridge abi\"));\n\n\n\n Self { bridge }\n\n }\n\n}\n\n\n\nimpl Inspector for ZeroEx {\n\n fn inspect(&self, inspection: &mut Inspection) {\n\n let actions = inspection.actions.to_vec();\n\n let mut prune = Vec::new();\n\n for i in 0..inspection.actions.len() {\n\n let action = &mut inspection.actions[i];\n\n\n", "file_path": "src/inspectors/zeroex.rs", "rank": 25, "score": 39857.918986444085 }, { "content": "\n\nimpl Evaluation {\n\n /// Takes an inspection and reduces it to the data format which will be pushed\n\n /// to the database.\n\n pub async fn new<T: Middleware>(\n\n inspection: Inspection,\n\n prices: &HistoricalPrice<T>,\n\n gas_used: U256,\n\n gas_price: U256,\n\n ) -> Result<Self, EvalError<T>>\n\n where\n\n T: 'static,\n\n {\n\n // TODO: Figure out how to sum up liquidations & arbs while pruning\n\n // aggressively\n\n // TODO: If an Inspection is CHECKED and contains >1 trading protocol,\n\n // then probably this is an Arbitrage?\n\n let mut actions = HashSet::new();\n\n let mut profit = U256::zero();\n\n for action in &inspection.actions {\n", "file_path": "src/types/evaluation.rs", "rank": 26, "score": 33199.57905422859 }, { "content": "use crate::{\n\n types::{actions::SpecificAction, Classification, Inspection},\n\n HistoricalPrice,\n\n};\n\n\n\nuse ethers::{\n\n contract::ContractError,\n\n providers::Middleware,\n\n types::{TxHash, U256},\n\n};\n\nuse std::collections::HashSet;\n\n\n\nuse thiserror::Error;\n\n\n\n#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Hash)]\n\npub enum ActionType {\n\n Liquidation,\n\n Arbitrage,\n\n Trade,\n\n}\n", "file_path": "src/types/evaluation.rs", "rank": 27, "score": 33196.43376153094 }, { "content": "\n\n Ok(Evaluation {\n\n inspection,\n\n gas_used,\n\n gas_price,\n\n actions,\n\n profit,\n\n })\n\n }\n\n}\n\n\n\n// TODO: Can we do something about the generic static type bounds?\n\n#[derive(Debug, Error)]\n\npub enum EvalError<M: Middleware>\n\nwhere\n\n M: 'static,\n\n{\n\n #[error(transparent)]\n\n Provider(M::Error),\n\n #[error(\"Transaction was not found {0}\")]\n\n TxNotFound(TxHash),\n\n #[error(transparent)]\n\n Contract(ContractError<M>),\n\n}\n", "file_path": "src/types/evaluation.rs", "rank": 28, "score": 33195.61504763306 }, { "content": "\n\n#[derive(Clone, Debug)]\n\npub struct Evaluation {\n\n /// The internal inspection which produced this evaluation\n\n pub inspection: Inspection,\n\n /// The gas used in total by this transaction\n\n pub gas_used: U256,\n\n /// The gas price used in this transaction\n\n pub gas_price: U256,\n\n /// The actions involved\n\n pub actions: HashSet<ActionType>,\n\n /// The money made by this transfer\n\n pub profit: U256,\n\n}\n\n\n\nimpl AsRef<Inspection> for Evaluation {\n\n fn as_ref(&self) -> &Inspection {\n\n &self.inspection\n\n }\n\n}\n", "file_path": "src/types/evaluation.rs", "rank": 29, "score": 33193.80614711275 }, { "content": " actions.insert(ActionType::Liquidation);\n\n }\n\n SpecificAction::LiquidationCheck => {\n\n actions.insert(ActionType::Liquidation);\n\n }\n\n SpecificAction::ProfitableLiquidation(liq) => {\n\n actions.insert(ActionType::Liquidation);\n\n profit += prices\n\n .quote(liq.token, liq.profit, inspection.block_number)\n\n .await\n\n .map_err(EvalError::Contract)?;\n\n }\n\n SpecificAction::Trade(_) => {\n\n actions.insert(ActionType::Trade);\n\n }\n\n _ => (),\n\n },\n\n _ => (),\n\n };\n\n }\n", "file_path": "src/types/evaluation.rs", "rank": 30, "score": 33190.82531991474 }, { "content": " match action {\n\n Classification::Known(action) => match action.as_ref() {\n\n SpecificAction::Arbitrage(arb) => {\n\n if arb.profit > 0.into() {\n\n actions.insert(ActionType::Arbitrage);\n\n profit += prices\n\n .quote(arb.token, arb.profit, inspection.block_number)\n\n .await\n\n .map_err(EvalError::Contract)?;\n\n }\n\n }\n\n SpecificAction::Liquidation(liq) => {\n\n let res = futures::future::join(\n\n prices.quote(liq.sent_token, liq.sent_amount, inspection.block_number),\n\n prices.quote(\n\n liq.received_token,\n\n liq.received_amount,\n\n inspection.block_number,\n\n ),\n\n )\n", "file_path": "src/types/evaluation.rs", "rank": 31, "score": 33187.32471488495 }, { "content": " .await;\n\n\n\n match res {\n\n (Ok(amount_in), Ok(amount_out)) => {\n\n profit += amount_out.saturating_sub(amount_in);\n\n }\n\n _ => println!(\"Could not fetch prices from Uniswap\"),\n\n };\n\n\n\n if res.0.is_err() {\n\n println!(\"Sent: {} of token {:?}\", liq.sent_amount, liq.sent_token);\n\n }\n\n\n\n if res.1.is_err() {\n\n println!(\n\n \"Received: {} of token {:?}\",\n\n liq.received_amount, liq.received_token\n\n );\n\n }\n\n\n", "file_path": "src/types/evaluation.rs", "rank": 32, "score": 33182.02444220982 }, { "content": "pub struct Arbitrage {\n\n pub profit: U256,\n\n pub token: Address,\n\n pub to: Address,\n\n}\n\n\n\nimpl From<Arbitrage> for SpecificAction {\n\n fn from(src: Arbitrage) -> Self {\n\n SpecificAction::Arbitrage(src)\n\n }\n\n}\n\n\n\nimpl fmt::Debug for Arbitrage {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.debug_struct(\"Arbitrage\")\n\n .field(\"profit\", &self.profit)\n\n .field(\"to\", &lookup(self.to))\n\n .field(\"token\", &lookup(self.token))\n\n .finish()\n\n }\n", "file_path": "src/types/actions.rs", "rank": 33, "score": 32987.75543012247 }, { "content": "impl From<Deposit> for SpecificAction {\n\n fn from(src: Deposit) -> Self {\n\n SpecificAction::WethDeposit(src)\n\n }\n\n}\n\n\n\nimpl fmt::Debug for Deposit {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.debug_struct(\"Deposit\")\n\n .field(\"from\", &lookup(self.from))\n\n .field(\"amount\", &self.amount)\n\n .finish()\n\n }\n\n}\n\n\n\n#[derive(Clone, PartialOrd, PartialEq)]\n\npub struct Withdrawal {\n\n pub to: Address,\n\n pub amount: U256,\n\n}\n", "file_path": "src/types/actions.rs", "rank": 34, "score": 32987.499123298876 }, { "content": "}\n\n\n\n#[derive(Default, Clone, PartialOrd, PartialEq)]\n\npub struct Liquidation {\n\n pub sent_token: Address,\n\n pub sent_amount: U256,\n\n\n\n pub received_token: Address,\n\n pub received_amount: U256,\n\n\n\n pub from: Address,\n\n pub liquidated_user: Address,\n\n}\n\n\n\nimpl From<Liquidation> for SpecificAction {\n\n fn from(src: Liquidation) -> Self {\n\n SpecificAction::Liquidation(src)\n\n }\n\n}\n\n\n", "file_path": "src/types/actions.rs", "rank": 35, "score": 32986.55210368799 }, { "content": "\n\nimpl From<Withdrawal> for SpecificAction {\n\n fn from(src: Withdrawal) -> Self {\n\n SpecificAction::WethWithdrawal(src)\n\n }\n\n}\n\n\n\nimpl fmt::Debug for Withdrawal {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.debug_struct(\"Withdrawal\")\n\n .field(\"to\", &lookup(self.to))\n\n .field(\"amount\", &self.amount)\n\n .finish()\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, PartialOrd, PartialEq)]\n\npub struct Trade {\n\n pub t1: Transfer,\n\n pub t2: Transfer,\n", "file_path": "src/types/actions.rs", "rank": 36, "score": 32984.73461118313 }, { "content": " _ => None,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Clone, PartialOrd, PartialEq)]\n\n/// A token transfer\n\npub struct Transfer {\n\n pub from: Address,\n\n pub to: Address,\n\n pub amount: U256,\n\n pub token: Address,\n\n}\n\n\n\nimpl From<Transfer> for SpecificAction {\n\n fn from(src: Transfer) -> Self {\n\n SpecificAction::Transfer(src)\n\n }\n\n}\n\n\n", "file_path": "src/types/actions.rs", "rank": 37, "score": 32983.53864213105 }, { "content": "// Manually implemented Debug (and Display?) for datatypes so that we\n\n// can get their token names instead of using addresses. TODO: Could we\n\n// also normalize the decimals? What about tokens with non-18 decimals e.g. Tether?\n\nimpl fmt::Debug for Transfer {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.debug_struct(\"Transfer\")\n\n .field(\"from\", &lookup(self.from))\n\n .field(\"to\", &lookup(self.to))\n\n .field(\"amount\", &self.amount)\n\n .field(\"token\", &lookup(self.token))\n\n .finish()\n\n }\n\n}\n\n\n\n#[derive(Clone, PartialOrd, PartialEq)]\n\npub struct Deposit {\n\n pub from: Address,\n\n pub amount: U256,\n\n}\n\n\n", "file_path": "src/types/actions.rs", "rank": 38, "score": 32982.90347882532 }, { "content": " ProfitableLiquidation(ProfitableLiquidation),\n\n\n\n Unclassified(Bytes),\n\n\n\n LiquidationCheck,\n\n}\n\n\n\n#[derive(Debug, Clone, PartialOrd, PartialEq)]\n\npub struct AddLiquidity {\n\n pub tokens: Vec<Address>,\n\n pub amounts: Vec<U256>,\n\n}\n\n\n\nimpl From<AddLiquidity> for SpecificAction {\n\n fn from(src: AddLiquidity) -> Self {\n\n SpecificAction::AddLiquidity(src)\n\n }\n\n}\n\n\n\nimpl SpecificAction {\n", "file_path": "src/types/actions.rs", "rank": 39, "score": 32982.66919140279 }, { "content": "}\n\n\n\nimpl From<Trade> for SpecificAction {\n\n fn from(src: Trade) -> Self {\n\n SpecificAction::Trade(src)\n\n }\n\n}\n\n\n\nimpl Trade {\n\n /// Creates a new trade made up of 2 matching transfers\n\n pub fn new(t1: Transfer, t2: Transfer) -> Self {\n\n assert!(\n\n t1.from == t2.to && t2.from == t1.to,\n\n \"Found mismatched trade\"\n\n );\n\n Self { t1, t2 }\n\n }\n\n}\n\n\n\n#[derive(Clone, PartialOrd, PartialEq)]\n", "file_path": "src/types/actions.rs", "rank": 40, "score": 32982.406175837765 }, { "content": "use crate::addresses::lookup;\n\n\n\nuse ethers::types::{Address, Bytes, U256};\n\n\n\nuse std::fmt;\n\n\n\n// https://github.com/flashbots/mev-inspect/blob/master/src/types.ts#L65-L87\n\n#[derive(Debug, Clone, PartialOrd, PartialEq)]\n\n/// The types of actions\n\npub enum SpecificAction {\n\n WethDeposit(Deposit),\n\n WethWithdrawal(Withdrawal),\n\n\n\n Transfer(Transfer),\n\n Trade(Trade),\n\n Liquidation(Liquidation),\n\n\n\n AddLiquidity(AddLiquidity),\n\n\n\n Arbitrage(Arbitrage),\n", "file_path": "src/types/actions.rs", "rank": 41, "score": 32981.48298826579 }, { "content": "impl AsRef<Liquidation> for ProfitableLiquidation {\n\n fn as_ref(&self) -> &Liquidation {\n\n &self.liquidation\n\n }\n\n}\n\n\n\nimpl From<ProfitableLiquidation> for SpecificAction {\n\n fn from(src: ProfitableLiquidation) -> Self {\n\n SpecificAction::ProfitableLiquidation(src)\n\n }\n\n}\n\n\n\nimpl fmt::Debug for ProfitableLiquidation {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.debug_struct(\"ProfitableLiquidation\")\n\n .field(\"liquidation\", &self.liquidation)\n\n .field(\"profit\", &self.profit)\n\n .field(\"token\", &lookup(self.token))\n\n .finish()\n\n }\n\n}\n", "file_path": "src/types/actions.rs", "rank": 42, "score": 32980.826443311584 }, { "content": "impl fmt::Debug for Liquidation {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.debug_struct(\"Liquidation\")\n\n .field(\"sent_token\", &lookup(self.sent_token))\n\n .field(\"sent_amount\", &self.sent_amount)\n\n .field(\"received_token\", &lookup(self.received_token))\n\n .field(\"received_amount\", &self.received_amount)\n\n .field(\"liquidated_user\", &lookup(self.liquidated_user))\n\n .field(\"from\", &lookup(self.from))\n\n .finish()\n\n }\n\n}\n\n\n\n#[derive(Clone, PartialOrd, PartialEq)]\n\npub struct ProfitableLiquidation {\n\n pub liquidation: Liquidation,\n\n pub profit: U256,\n\n pub token: Address,\n\n}\n\n\n", "file_path": "src/types/actions.rs", "rank": 43, "score": 32980.664802974985 }, { "content": "\n\n pub fn trade(&self) -> Option<&Trade> {\n\n match self {\n\n SpecificAction::Trade(inner) => Some(inner),\n\n _ => None,\n\n }\n\n }\n\n\n\n pub fn arbitrage(&self) -> Option<&Arbitrage> {\n\n match self {\n\n SpecificAction::Arbitrage(inner) => Some(inner),\n\n _ => None,\n\n }\n\n }\n\n\n\n pub fn liquidation(&self) -> Option<&Liquidation> {\n\n match self {\n\n SpecificAction::Liquidation(inner) => Some(inner),\n\n _ => None,\n\n }\n", "file_path": "src/types/actions.rs", "rank": 44, "score": 32977.758399408514 }, { "content": " pub fn deposit(&self) -> Option<&Deposit> {\n\n match self {\n\n SpecificAction::WethDeposit(inner) => Some(inner),\n\n _ => None,\n\n }\n\n }\n\n\n\n pub fn withdrawal(&self) -> Option<&Withdrawal> {\n\n match self {\n\n SpecificAction::WethWithdrawal(inner) => Some(inner),\n\n _ => None,\n\n }\n\n }\n\n\n\n pub fn transfer(&self) -> Option<&Transfer> {\n\n match self {\n\n SpecificAction::Transfer(inner) => Some(inner),\n\n _ => None,\n\n }\n\n }\n", "file_path": "src/types/actions.rs", "rank": 45, "score": 32977.692499815676 }, { "content": " }\n\n\n\n // TODO: Can we convert these to AsRef / AsMut Options somehow?\n\n pub fn liquidation_mut(&mut self) -> Option<&mut Liquidation> {\n\n match self {\n\n SpecificAction::Liquidation(inner) => Some(inner),\n\n _ => None,\n\n }\n\n }\n\n\n\n pub fn profitable_liquidation(&self) -> Option<&ProfitableLiquidation> {\n\n match self {\n\n SpecificAction::ProfitableLiquidation(inner) => Some(inner),\n\n _ => None,\n\n }\n\n }\n\n\n\n pub fn add_liquidity(&self) -> Option<&AddLiquidity> {\n\n match self {\n\n SpecificAction::AddLiquidity(inner) => Some(inner),\n", "file_path": "src/types/actions.rs", "rank": 46, "score": 32977.289909090694 }, { "content": " }\n\n }\n\n\n\n /// Instantiates Compound with all live markets\n\n ///\n\n /// # Panics\n\n ///\n\n /// - If the `Ctoken.underlying` call fails\n\n pub async fn create<M: Middleware>(\n\n provider: std::sync::Arc<M>,\n\n ) -> Result<Self, ContractError<M>> {\n\n let comptroller = Comptroller::new(*COMPTROLLER, provider.clone());\n\n\n\n let markets = comptroller.get_all_markets().call().await?;\n\n let futs = markets\n\n .into_iter()\n\n .map(|market| {\n\n let provider = provider.clone();\n\n async move {\n\n if market != *CETH {\n", "file_path": "src/inspectors/compound.rs", "rank": 56, "score": 23.801311775402304 }, { "content": "\n\n Some(AddLiquidity {\n\n tokens: tokens.clone(),\n\n amounts,\n\n })\n\n }\n\n\n\n pub async fn create<M: Middleware>(\n\n provider: std::sync::Arc<M>,\n\n ) -> Result<Self, ContractError<M>> {\n\n let mut this = Self::new(vec![]);\n\n let registry = CurveRegistry::new(*CURVE_REGISTRY, provider);\n\n\n\n let pool_count = registry.pool_count().call().await?;\n\n // TODO: Cache these locally.\n\n for i in 0..pool_count.as_u64() {\n\n let pool = registry.pool_list(i.into()).call().await?;\n\n let tokens = registry.get_underlying_coins(pool).call().await?;\n\n this.pools.insert(pool, tokens.to_vec());\n\n }\n", "file_path": "src/inspectors/curve.rs", "rank": 57, "score": 22.6131483816769 }, { "content": "use crate::{\n\n actions_after,\n\n addresses::{CETH, COMPTROLLER, COMP_ORACLE, WETH},\n\n traits::Inspector,\n\n types::{\n\n actions::{Liquidation, SpecificAction},\n\n Classification, Inspection, Protocol, Status,\n\n },\n\n};\n\nuse ethers::{\n\n abi::{Abi, FunctionExt},\n\n contract::{abigen, BaseContract, ContractError},\n\n providers::Middleware,\n\n types::{Address, Call, CallType, U256},\n\n};\n\n\n\nuse std::collections::HashMap;\n\n\n", "file_path": "src/inspectors/compound.rs", "rank": 58, "score": 21.95619767955428 }, { "content": "use async_trait::async_trait;\n\nuse ethers::{\n\n providers::{FromErr, Middleware},\n\n types::{BlockNumber, Trace},\n\n};\n\nuse serde::{de::DeserializeOwned, Serialize};\n\nuse std::path::{Path, PathBuf};\n\n\n\n#[derive(Clone, Debug)]\n\npub struct CachedProvider<M> {\n\n inner: M,\n\n cache: PathBuf,\n\n}\n\n\n\nuse thiserror::Error;\n\n\n\nimpl<M: Middleware> CachedProvider<M> {\n\n /// Creates a new provider with the cache located at the provided path\n\n pub fn new<P: Into<PathBuf>>(inner: M, cache: P) -> Self {\n\n Self {\n", "file_path": "src/cached_provider.rs", "rank": 59, "score": 21.172042100956798 }, { "content": "#![allow(clippy::too_many_arguments)]\n\nuse crate::{\n\n addresses::CURVE_REGISTRY,\n\n traits::Inspector,\n\n types::{actions::AddLiquidity, Classification, Inspection, Protocol},\n\n};\n\n\n\nuse ethers::{\n\n abi::parse_abi,\n\n contract::decode_function_data,\n\n contract::{abigen, ContractError},\n\n providers::Middleware,\n\n types::{Address, Bytes, Call as TraceCall, U256},\n\n};\n\nuse ethers::{abi::Abi, contract::BaseContract};\n\nuse std::collections::HashMap;\n\n\n\n// Type aliases for Curve\n", "file_path": "src/inspectors/curve.rs", "rank": 60, "score": 20.20382094552393 }, { "content": " let traces = provider.trace_transaction(opts.tx).await?;\n\n if let Some(inspection) = processor.inspect_one(traces) {\n\n let gas_used = provider\n\n .get_transaction_receipt(inspection.hash)\n\n .await?\n\n .expect(\"tx not found\")\n\n .gas_used\n\n .unwrap_or_default();\n\n\n\n let gas_price = provider\n\n .get_transaction(inspection.hash)\n\n .await?\n\n .expect(\"tx not found\")\n\n .gas_price;\n\n\n\n let evaluation =\n\n Evaluation::new(inspection, &prices, gas_used, gas_price).await?;\n\n println!(\"Found: {:?}\", evaluation.as_ref().hash);\n\n println!(\"Revenue: {:?} WEI\", evaluation.profit);\n\n println!(\"Cost: {:?} WEI\", evaluation.gas_used * evaluation.gas_price);\n", "file_path": "src/main.rs", "rank": 61, "score": 19.998110259506024 }, { "content": " let writer = std::fs::File::create(path)?;\n\n Ok(serde_json::to_writer(writer, &data)?)\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<M: Middleware> Middleware for CachedProvider<M> {\n\n type Error = CachedProviderError<M>;\n\n type Provider = M::Provider;\n\n type Inner = M;\n\n\n\n fn inner(&self) -> &Self::Inner {\n\n &self.inner\n\n }\n\n\n\n async fn trace_block(&self, block: BlockNumber) -> Result<Vec<Trace>, Self::Error> {\n\n // check if it exists, else get from the provider\n\n let mut traces = None;\n\n if let BlockNumber::Number(block_number) = block {\n\n traces = self\n", "file_path": "src/cached_provider.rs", "rank": 62, "score": 19.579417830126694 }, { "content": "//! All the datatypes associated with MEV-Inspect\n\npub mod actions;\n\n\n\npub mod evaluation;\n\npub use evaluation::{EvalError, Evaluation};\n\n\n\npub(crate) mod classification;\n\npub use classification::Classification;\n\n\n\npub(crate) mod inspection;\n\npub use inspection::Inspection;\n\n\n\n#[derive(Debug, Clone, PartialOrd, PartialEq)]\n\npub enum Status {\n\n /// When a transaction reverts without touching any DeFi protocol\n\n Reverted,\n\n /// When a transaction reverts early but it had touched a DeFi protocol\n\n Checked,\n\n /// When a transaction suceeds\n\n Success,\n", "file_path": "src/types/mod.rs", "rank": 63, "score": 19.363147731627492 }, { "content": "use crate::{\n\n addresses::{DYDX, FILTER, ZEROX},\n\n types::{\n\n classification::{ActionTrace, CallTrace},\n\n Classification, Protocol, Status,\n\n },\n\n};\n\nuse ethers::types::{Action, Address, CallType, Trace, TxHash};\n\nuse std::{collections::HashSet, convert::TryFrom};\n\n\n\n#[derive(Debug, Clone)]\n\n/// The result of an inspection of a trace along with its inspected subtraces\n\npub struct Inspection {\n\n /// Success / failure\n\n pub status: Status,\n\n\n\n ////// What\n\n /// All the classified / unclassified actions that happened\n\n pub actions: Vec<Classification>,\n\n\n", "file_path": "src/types/inspection.rs", "rank": 64, "score": 19.230576265287475 }, { "content": "use crate::{\n\n addresses::PROTOCOLS,\n\n traits::Inspector,\n\n types::{actions::Transfer, Classification, Inspection, Protocol},\n\n};\n\n\n\nuse ethers::{\n\n abi::parse_abi,\n\n contract::BaseContract,\n\n types::{Address, Bytes, U256},\n\n};\n\n\n\n#[derive(Debug, Clone)]\n\n/// An inspector for ZeroEx Exchange Proxy transfers\n\npub struct ZeroEx {\n\n bridge: BaseContract,\n\n}\n\n\n", "file_path": "src/inspectors/zeroex.rs", "rank": 65, "score": 19.121907968758027 }, { "content": " receipt.transaction_hash,\n\n receipt.gas_used.unwrap_or_default(),\n\n )\n\n })\n\n .collect::<HashMap<TxHash, U256>>();\n\n\n\n let inspections = processor.inspect_many(traces);\n\n\n\n let t1 = std::time::Instant::now();\n\n\n\n let eval_futs = inspections.into_iter().map(|inspection| {\n\n let gas_used = gas_used_txs\n\n .get(&inspection.hash)\n\n .cloned()\n\n .unwrap_or_default();\n\n let gas_price = gas_price_txs\n\n .get(&inspection.hash)\n\n .cloned()\n\n .unwrap_or_default();\n\n Evaluation::new(inspection, &prices, gas_used, gas_price)\n", "file_path": "src/main.rs", "rank": 66, "score": 18.88341707982997 }, { "content": " });\n\n for evaluation in futures::future::join_all(eval_futs).await {\n\n if let Ok(evaluation) = evaluation {\n\n db.insert(&evaluation).await?;\n\n }\n\n }\n\n\n\n writeln!(\n\n lock,\n\n \"Processed {:?} in {:?}\",\n\n block_number,\n\n std::time::Instant::now().duration_since(t1)\n\n )?;\n\n Ok(())\n\n}\n", "file_path": "src/main.rs", "rank": 68, "score": 18.44014446038191 }, { "content": " println!(\"Actions: {:?}\", evaluation.actions);\n\n println!(\"Protocols: {:?}\", evaluation.inspection.protocols);\n\n println!(\"Status: {:?}\", evaluation.inspection.status);\n\n db.insert(&evaluation).await?;\n\n } else {\n\n eprintln!(\"No actions found for tx {:?}\", opts.tx);\n\n }\n\n }\n\n Command::Blocks(inner) => {\n\n let t1 = std::time::Instant::now();\n\n let stdout = std::io::stdout();\n\n let mut lock = stdout.lock();\n\n for block in inner.from..inner.to {\n\n // TODO: Can we do the block processing in parallel? Theoretically\n\n // it should be possible\n\n process_block(&mut lock, block, &provider, &processor, &mut db, &prices)\n\n .await?;\n\n }\n\n drop(lock);\n\n\n", "file_path": "src/main.rs", "rank": 69, "score": 18.349362695210505 }, { "content": "use crate::{\n\n addresses::BALANCER_PROXY,\n\n inspectors::find_matching,\n\n traits::Inspector,\n\n types::{actions::Trade, Classification, Inspection, Protocol},\n\n};\n\n\n\nuse ethers::{\n\n abi::Abi,\n\n contract::BaseContract,\n\n types::{Address, Call as TraceCall, U256},\n\n};\n\n\n\n#[derive(Debug, Clone)]\n\n/// An inspector for Uniswap\n\npub struct Balancer {\n\n bpool: BaseContract,\n\n bproxy: BaseContract,\n\n}\n\n\n", "file_path": "src/inspectors/balancer.rs", "rank": 70, "score": 18.152823211709272 }, { "content": " pub async fn quote<T: Into<BlockNumber>, A: Into<U256>>(\n\n &self,\n\n token: Address,\n\n amount: A,\n\n block: T,\n\n ) -> Result<U256, ContractError<M>> {\n\n let amount = amount.into();\n\n\n\n // assume price parity of WETH / ETH\n\n if token == *ETH || token == *WETH {\n\n return Ok(amount);\n\n }\n\n\n\n // get a marginal price for a 1 ETH buy order\n\n let one = DECIMALS\n\n .get(&token)\n\n .map(|decimals| U256::from(10u64.pow(*decimals as u32)))\n\n .unwrap_or(WEI_IN_ETHER);\n\n\n\n // ask uniswap how much we'd get from the TOKEN -> WETH path\n", "file_path": "src/prices.rs", "rank": 71, "score": 17.850500868954605 }, { "content": "use crate::{\n\n addresses::AAVE_LENDING_POOL,\n\n types::{actions::Liquidation, Classification, Inspection, Protocol},\n\n Inspector,\n\n};\n\nuse ethers::{\n\n abi::Abi,\n\n contract::BaseContract,\n\n types::{Address, U256},\n\n};\n\n\n", "file_path": "src/inspectors/aave.rs", "rank": 72, "score": 17.18025562231458 }, { "content": " ///// Where\n\n /// All the involved protocols\n\n pub protocols: HashSet<Protocol>,\n\n\n\n // Who\n\n /// The sender of the transaction\n\n pub from: Address,\n\n /// The first receiver of this tx, the contract being interacted with. In case\n\n /// of sophisticated bots, this will be the bot's contract logic.\n\n pub contract: Address,\n\n /// If this is set, then the `contract` was a proxy and the actual logic is\n\n /// in this address\n\n pub proxy_impl: Option<Address>,\n\n\n\n ////// When\n\n /// The trace's tx hash\n\n pub hash: TxHash,\n\n\n\n /// The block number of this tx\n\n pub block_number: u64,\n", "file_path": "src/types/inspection.rs", "rank": 73, "score": 16.275690875276844 }, { "content": " if let Some(calltrace) = action.as_call() {\n\n let call = calltrace.as_ref();\n\n\n\n if let Ok(transfer) = self\n\n .bridge\n\n .decode::<BridgeTransfer, _>(\"bridgeTransferFrom\", &call.input)\n\n {\n\n // we found a 0x transaction\n\n inspection.protocols.insert(Protocol::ZeroEx);\n\n\n\n // the bridge call will tell us which sub-protocol was used\n\n if let Some(protocol) = PROTOCOLS.get(&transfer.1) {\n\n inspection.protocols.insert(*protocol);\n\n }\n\n\n\n // change this to a transfer\n\n *action = Classification::new(\n\n Transfer {\n\n token: transfer.0,\n\n from: transfer.1,\n", "file_path": "src/inspectors/zeroex.rs", "rank": 74, "score": 16.031996438623164 }, { "content": "use crate::{\n\n addresses::{AAVE_LENDING_POOL_CORE, PROTOCOLS},\n\n inspectors::find_matching,\n\n traits::Inspector,\n\n types::{\n\n actions::{AddLiquidity as AddLiquidityAct, Trade},\n\n Classification, Inspection, Protocol, Status,\n\n },\n\n};\n\n\n\nuse ethers::{abi::Abi, contract::BaseContract};\n\nuse ethers::{\n\n contract::decode_function_data,\n\n types::{Address, Bytes, Call as TraceCall, CallType, U256},\n\n};\n\n\n\n// Type aliases for Uniswap's `swap` return types\n", "file_path": "src/inspectors/uniswap.rs", "rank": 75, "score": 15.765982880207044 }, { "content": "#![allow(clippy::clippy::too_many_arguments)]\n\nuse crate::addresses::{parse_address, ETH, WETH};\n\nuse ethers::{\n\n contract::{abigen, ContractError},\n\n providers::Middleware,\n\n types::{Address, BlockNumber, U256},\n\n utils::WEI_IN_ETHER,\n\n};\n\nuse once_cell::sync::Lazy;\n\nuse std::{collections::HashMap, sync::Arc};\n\n\n\n// Generate type-safe bindings to Uniswap's router\n\nabigen!(Uniswap, \"abi/unirouterv2.json\");\n\n\n\n/// Gets historical prices in ETH for any token via Uniswap.\n\n/// **Requires an archive node to work**\n\npub struct HistoricalPrice<M> {\n\n uniswap: Uniswap<M>,\n\n}\n\n\n", "file_path": "src/prices.rs", "rank": 76, "score": 15.706266367741927 }, { "content": "use crate::{\n\n addresses::{ETH, WETH},\n\n types::{\n\n actions::{Deposit, SpecificAction, Transfer, Withdrawal},\n\n Classification, Inspection,\n\n },\n\n Inspector,\n\n};\n\nuse ethers::{\n\n abi::parse_abi,\n\n contract::BaseContract,\n\n types::{Address, Call as TraceCall, CallType, U256},\n\n};\n\n\n\n#[derive(Debug, Clone)]\n\n/// Decodes ERC20 calls\n\npub struct ERC20(BaseContract);\n\n\n\nimpl Inspector for ERC20 {\n\n fn inspect(&self, inspection: &mut Inspection) {\n", "file_path": "src/inspectors/erc20.rs", "rank": 77, "score": 15.482770405210035 }, { "content": " actions: Vec::new(),\n\n // start off with empty protocols since everything is unclassified\n\n protocols: HashSet::new(),\n\n from: call.from,\n\n contract: call.to,\n\n proxy_impl: None,\n\n hash: trace.transaction_hash.unwrap_or_else(TxHash::zero),\n\n block_number: trace.block_number,\n\n };\n\n\n\n inspection.actions = traces\n\n .into_iter()\n\n .filter_map(|trace| {\n\n // Revert if all subtraces revert? There are counterexamples\n\n // e.g. when a low-level trace's revert is handled\n\n if trace.error.is_some() {\n\n inspection.status = Status::Reverted;\n\n }\n\n\n\n match trace.action {\n", "file_path": "src/types/inspection.rs", "rank": 78, "score": 15.409435333883671 }, { "content": " for action in inspection.actions.iter_mut() {\n\n match action {\n\n Classification::Unknown(ref mut calltrace) => {\n\n let call = calltrace.as_ref();\n\n if call.to == *AAVE_LENDING_POOL {\n\n inspection.protocols.insert(Protocol::Aave);\n\n\n\n // https://github.com/aave/aave-protocol/blob/master/contracts/lendingpool/LendingPool.sol#L805\n\n if let Ok((collateral, reserve, user, purchase_amount, _)) =\n\n self.pool\n\n .decode::<LiquidationCall, _>(\"liquidationCall\", &call.input)\n\n {\n\n // Set the amount to 0. We'll set it at the reducer\n\n *action = Classification::new(\n\n Liquidation {\n\n sent_token: reserve,\n\n sent_amount: purchase_amount,\n\n\n\n received_token: collateral,\n\n received_amount: U256::zero(),\n", "file_path": "src/inspectors/aave.rs", "rank": 79, "score": 15.337272234170527 }, { "content": " );\n\n\n\n // sushi router\n\n map.insert(\n\n \"d9e1cE17f2641f24aE83637ab66a2cca9C378B9F\".parse().unwrap(),\n\n Protocol::Sushiswap,\n\n );\n\n\n\n insert_many(\n\n map,\n\n &[\"0xfe01821Ca163844203220cd08E4f2B2FB43aE4E4\"], // 0x: BalancerBridge\n\n Protocol::Balancer,\n\n )\n\n});\n\n\n\n// Addresses which should be ignored when used as the target of a transaction\n\npub static FILTER: Lazy<HashSet<Address>> = Lazy::new(|| {\n\n let mut set = HashSet::new();\n\n // 1inch\n\n set.insert(parse_address(\"0x11111254369792b2ca5d084ab5eea397ca8fa48b\"));\n", "file_path": "src/addresses.rs", "rank": 80, "score": 15.153036585896935 }, { "content": "use crate::types::{inspection::TraceWrapper, Classification, Inspection, Status};\n\nuse ethers::types::{Address, Trace, TxHash};\n\nuse once_cell::sync::Lazy;\n\nuse std::{collections::HashSet, convert::TryInto};\n\n\n\npub const TRACE: &str = include_str!(\"../../res/11017338.trace.json\");\n\npub static TRACES: Lazy<Vec<Trace>> = Lazy::new(|| serde_json::from_str(TRACE).unwrap());\n\n\n", "file_path": "src/test_helpers/mod.rs", "rank": 81, "score": 14.781490449570178 }, { "content": "\n\n Ok(traces)\n\n }\n\n }\n\n}\n\n\n\n#[derive(Error, Debug)]\n\npub enum CachedProviderError<M: Middleware> {\n\n /// Thrown when the internal middleware errors\n\n #[error(\"{0}\")]\n\n MiddlewareError(M::Error),\n\n #[error(transparent)]\n\n IoError(#[from] std::io::Error),\n\n #[error(transparent)]\n\n DeserializationError(#[from] serde_json::Error),\n\n}\n\n\n\nimpl<M: Middleware> FromErr<M::Error> for CachedProviderError<M> {\n\n fn from(src: M::Error) -> Self {\n\n CachedProviderError::MiddlewareError(src)\n\n }\n\n}\n", "file_path": "src/cached_provider.rs", "rank": 82, "score": 14.605077286468017 }, { "content": " let traces = provider\n\n .trace_block(BlockNumber::Number(block_number))\n\n .await?;\n\n // get all the block txs\n\n let block = provider\n\n .get_block_with_txs(block_number)\n\n .await?\n\n .expect(\"block should exist\");\n\n let gas_price_txs = block\n\n .transactions\n\n .iter()\n\n .map(|tx| (tx.hash, tx.gas_price))\n\n .collect::<HashMap<TxHash, U256>>();\n\n\n\n // get all the receipts\n\n let receipts = provider.parity_block_receipts(block_number).await?;\n\n let gas_used_txs = receipts\n\n .into_iter()\n\n .map(|receipt| {\n\n (\n", "file_path": "src/main.rs", "rank": 83, "score": 14.324505463394473 }, { "content": " ];\n\n\n\n let reducers: Vec<Box<dyn Reducer>> = vec![\n\n Box::new(LiquidationReducer::new()),\n\n Box::new(TradeReducer::new()),\n\n Box::new(ArbitrageReducer::new()),\n\n ];\n\n let processor = BatchInspector::new(inspectors, reducers);\n\n\n\n // TODO: Pass overwrite parameter\n\n let mut db = MevDB::connect(opts.db_cfg, &opts.db_table).await?;\n\n db.create().await?;\n\n if opts.reset {\n\n db.clear().await?;\n\n db.create().await?;\n\n }\n\n\n\n if let Some(cmd) = opts.cmd {\n\n match cmd {\n\n Command::Tx(opts) => {\n", "file_path": "src/main.rs", "rank": 84, "score": 14.267275162770197 }, { "content": " pub fn unknown(&self) -> Vec<CallTrace> {\n\n self.actions\n\n .iter()\n\n .filter_map(|classification| match classification {\n\n Classification::Unknown(inner) => Some(inner),\n\n Classification::Known(_) | Classification::Prune => None,\n\n })\n\n .cloned()\n\n .collect()\n\n }\n\n}\n\n\n\n/// Helper type to bypass https://github.com/rust-lang/rust/issues/50133#issuecomment-646908391\n\npub(crate) struct TraceWrapper<T>(pub(crate) T);\n\nimpl<T: IntoIterator<Item = Trace>> TryFrom<TraceWrapper<T>> for Inspection {\n\n type Error = ();\n\n\n\n fn try_from(traces: TraceWrapper<T>) -> Result<Self, Self::Error> {\n\n let mut traces = traces.0.into_iter().peekable();\n\n\n", "file_path": "src/types/inspection.rs", "rank": 85, "score": 14.117969597450143 }, { "content": " inner,\n\n cache: cache.into(),\n\n }\n\n }\n\n\n\n fn read<T: DeserializeOwned, K: AsRef<Path>>(\n\n &self,\n\n fname: K,\n\n ) -> Result<T, CachedProviderError<M>> {\n\n let path = self.cache.join(fname);\n\n let json = std::fs::read_to_string(path)?;\n\n Ok(serde_json::from_str::<T>(&json)?)\n\n }\n\n\n\n fn write<T: Serialize, K: AsRef<Path>>(\n\n &self,\n\n fname: K,\n\n data: T,\n\n ) -> Result<(), CachedProviderError<M>> {\n\n let path = self.cache.join(fname);\n", "file_path": "src/cached_provider.rs", "rank": 86, "score": 14.108945809001543 }, { "content": "use crate::{\n\n inspectors::find_matching,\n\n types::{\n\n actions::{Arbitrage, SpecificAction},\n\n Classification, Inspection,\n\n },\n\n Reducer,\n\n};\n\n\n\n#[derive(Clone, Debug)]\n\npub struct ArbitrageReducer;\n\n\n\nimpl ArbitrageReducer {\n\n pub fn new() -> Self {\n\n Self\n\n }\n\n}\n\n\n\nimpl Reducer for ArbitrageReducer {\n\n fn reduce(&self, inspection: &mut Inspection) {\n", "file_path": "src/reducers/arbitrage.rs", "rank": 87, "score": 13.523337685902096 }, { "content": "use crate::{\n\n inspectors::find_matching,\n\n types::{actions::Trade, Classification, Inspection},\n\n Reducer,\n\n};\n\n\n\npub struct TradeReducer;\n\n\n\nimpl TradeReducer {\n\n /// Instantiates the reducer\n\n pub fn new() -> Self {\n\n Self\n\n }\n\n}\n\n\n\nimpl Reducer for TradeReducer {\n\n fn reduce(&self, inspection: &mut Inspection) {\n\n let actions = inspection.actions.to_vec();\n\n let mut prune = Vec::new();\n\n inspection\n", "file_path": "src/reducers/trade.rs", "rank": 88, "score": 13.420959940199168 }, { "content": " .decode::<(Address, U256), _>(\"mint\", &trace_call.input)\n\n {\n\n Some(SpecificAction::Transfer(Transfer {\n\n // Mints create from `0x0`\n\n from: Address::zero(),\n\n to,\n\n amount,\n\n token,\n\n }))\n\n } else if let Ok((to, amount)) = self\n\n .0\n\n .decode::<(Address, U256), _>(\"transfer\", &trace_call.input)\n\n {\n\n Some(SpecificAction::Transfer(Transfer {\n\n from: trace_call.from,\n\n to,\n\n amount,\n\n token,\n\n }))\n\n } else if let Ok(amount) = self.0.decode::<U256, _>(\"withdraw\", &trace_call.input) {\n", "file_path": "src/inspectors/erc20.rs", "rank": 89, "score": 13.367046739027561 }, { "content": " comptroller: BaseContract,\n\n ctoken_to_token: HashMap<Address, Address>,\n\n}\n\n\n\nimpl Inspector for Compound {\n\n fn inspect(&self, inspection: &mut Inspection) {\n\n let mut found = false;\n\n for i in 0..inspection.actions.len() {\n\n // split in two so that we can iterate mutably without cloning\n\n let (action, subtraces) = actions_after(&mut inspection.actions, i);\n\n\n\n // if the provided action is a liquidation, start parsing all the subtraces\n\n if let Some((mut liquidation, trace)) = self.try_as_liquidation(&action) {\n\n inspection.protocols.insert(Protocol::Compound);\n\n\n\n // omit the double-counted Dcall\n\n if let Some(ref call_type) = action.as_call().map(|call| &call.call.call_type) {\n\n if matches!(call_type, CallType::DelegateCall) {\n\n continue;\n\n }\n", "file_path": "src/inspectors/compound.rs", "rank": 90, "score": 13.326143499002436 }, { "content": " }\n\n}\n\n\n\nimpl Compound {\n\n /// Constructor\n\n pub fn new<T: IntoIterator<Item = (Address, Address)>>(ctoken_to_token: T) -> Self {\n\n Self {\n\n ctoken: BaseContract::from({\n\n serde_json::from_str::<Abi>(include_str!(\"../../abi/ctoken.json\"))\n\n .expect(\"could not parse ctoken abi\")\n\n }),\n\n cether: BaseContract::from({\n\n serde_json::from_str::<Abi>(include_str!(\"../../abi/cether.json\"))\n\n .expect(\"could not parse ctoken abi\")\n\n }),\n\n comptroller: BaseContract::from({\n\n serde_json::from_str::<Abi>(include_str!(\"../../abi/comptroller.json\"))\n\n .expect(\"could not parse ctoken abi\")\n\n }),\n\n ctoken_to_token: ctoken_to_token.into_iter().collect(),\n", "file_path": "src/inspectors/compound.rs", "rank": 91, "score": 13.053028596544603 }, { "content": " .read(format!(\"{}.trace.json\", block_number.as_u64()))\n\n .ok();\n\n };\n\n\n\n if let Some(traces) = traces {\n\n Ok(traces)\n\n } else {\n\n let traces: Vec<Trace> = self\n\n .inner()\n\n .trace_block(block)\n\n .await\n\n .map_err(CachedProviderError::MiddlewareError)?;\n\n\n\n let block_number = if let BlockNumber::Number(block_number) = block {\n\n block_number.as_u64()\n\n } else {\n\n self.get_block_number().await?.as_u64()\n\n };\n\n\n\n self.write(format!(\"{}.trace.json\", block_number), &traces)?;\n", "file_path": "src/cached_provider.rs", "rank": 92, "score": 12.763078891325964 }, { "content": "use crate::{\n\n addresses::{ETH, WETH},\n\n inspectors::find_matching,\n\n types::{\n\n actions::{ProfitableLiquidation, Transfer},\n\n Classification, Inspection,\n\n },\n\n Reducer,\n\n};\n\n\n\npub struct LiquidationReducer;\n\n\n\nimpl LiquidationReducer {\n\n pub fn new() -> Self {\n\n Self\n\n }\n\n}\n\n\n\nimpl Reducer for LiquidationReducer {\n\n fn reduce(&self, inspection: &mut Inspection) {\n", "file_path": "src/reducers/liquidation.rs", "rank": 93, "score": 12.734693178282793 }, { "content": " Action::Call(call) => {\n\n if inspection.proxy_impl.is_none()\n\n && call.call_type == CallType::DelegateCall\n\n && call.from == inspection.contract\n\n {\n\n inspection.proxy_impl = Some(call.to);\n\n }\n\n\n\n if call.to == *DYDX {\n\n inspection.protocols.insert(Protocol::DyDx);\n\n }\n\n\n\n if call.to == *ZEROX {\n\n inspection.protocols.insert(Protocol::ZeroEx);\n\n }\n\n\n\n Some(\n\n CallTrace {\n\n call,\n\n trace_address: trace.trace_address,\n", "file_path": "src/types/inspection.rs", "rank": 94, "score": 12.638775163416668 }, { "content": " pub fn reduce(&self, inspection: &mut Inspection) {\n\n for reducer in self.reducers.iter() {\n\n reducer.reduce(inspection);\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::{\n\n addresses::{ADDRESSBOOK, WETH},\n\n inspectors::*,\n\n reducers::*,\n\n set,\n\n test_helpers::*,\n\n types::{Protocol, Status},\n\n };\n\n use ethers::types::U256;\n\n\n", "file_path": "src/inspectors/batch.rs", "rank": 95, "score": 12.490347331778267 }, { "content": " ],\n\n );\n\n inspector.inspect(&mut inspection);\n\n inspector.reduce(&mut inspection);\n\n inspection.prune();\n\n\n\n let known = inspection.known();\n\n\n\n let arb = known\n\n .iter()\n\n .find_map(|action| action.as_ref().arbitrage())\n\n .unwrap();\n\n assert_eq!(arb.profit, U256::from_dec_str(\"14397525374450478\").unwrap());\n\n assert_eq!(arb.token, *WETH);\n\n assert_eq!(\n\n inspection.protocols,\n\n set![Protocol::Sushiswap, Protocol::Curve, Protocol::ZeroEx]\n\n );\n\n }\n\n\n", "file_path": "src/inspectors/batch.rs", "rank": 96, "score": 12.308380287074154 }, { "content": "# <h1 align=\"center\"> MEV Inspect </h1>\n\n\n\n**Ethereum MEV Inspector in Rust**\n\n\n\n## Inspectors\n\n\n\n- Curve\n\n- Balancer\n\n- Uniswap (& clones)\n\n- Aave\n\n- Compound\n\n\n\n## Installing\n\n\n\n`cargo build --release`\n\n\n\n## Running the CLI\n\n\n\n```\n\nUsage: ./target/release/mev-inspect [OPTIONS]\n\n\n\nOptional arguments:\n\n -h, --help\n\n -r, --reset clear and re-build the database\n\n -o, --overwrite do not skip blocks which already exist\n\n -u, --url URL The tracing / archival node's URL (default: http://localhost:8545)\n\n -c, --cache CACHE Path to where traces will be cached\n\n -d, --db-cfg DB-CFG Database config\n\n -D, --db-table DB-TABLE the table of the database (default: mev_inspections)\n\n\n\nAvailable commands:\n\n tx inspect a transaction\n\n blocks inspect a range of blocks\n\n```\n\n\n\n## Running the tests\n\n\n\n**Tests require `postgres` installed.**\n\n\n\n`cargo test`\n", "file_path": "README.md", "rank": 97, "score": 12.119002974251309 }, { "content": " }\n\n }\n\n\n\n prune\n\n .iter()\n\n .for_each(|p| inspection.actions[*p] = Classification::Prune);\n\n // TODO: Add checked calls\n\n }\n\n}\n\n\n\nimpl Balancer {\n\n fn check(&self, call: &TraceCall) -> bool {\n\n // TODO: Adjust for exchange proxy calls\n\n call.to == *BALANCER_PROXY\n\n }\n\n\n\n /// Constructor\n\n pub fn new() -> Self {\n\n Self {\n\n bpool: BaseContract::from({\n", "file_path": "src/inspectors/balancer.rs", "rank": 98, "score": 12.015007117583517 }, { "content": " }\n\n}\n\n\n\n#[cfg(test)]\n\npub mod tests {\n\n use super::*;\n\n use crate::test_helpers::*;\n\n use crate::{\n\n addresses::ADDRESSBOOK,\n\n reducers::{ArbitrageReducer, TradeReducer},\n\n types::{Protocol, Status},\n\n Reducer,\n\n };\n\n use crate::{inspectors::ERC20, types::Inspection, Inspector};\n\n use ethers::types::U256;\n\n\n\n // inspector that does all 3 transfer/trade/arb combos\n\n struct MyInspector {\n\n erc20: ERC20,\n\n uni: Uniswap,\n", "file_path": "src/inspectors/uniswap.rs", "rank": 99, "score": 11.975362872381602 } ]
Rust
src/impls/primitive.rs
JuanPotato/deku
09427b8eb5e39402c4dec49070e9ae0a5ecbe20d
use crate::{ctx::*, DekuError, DekuRead, DekuWrite}; use bitvec::prelude::*; use core::convert::TryInto; #[cfg(feature = "alloc")] use alloc::format; macro_rules! ImplDekuTraits { ($typ:ty) => { impl DekuRead<'_, (Endian, Size)> for $typ { fn read( input: &BitSlice<u8, Msb0>, (endian, size): (Endian, Size), ) -> Result<(&BitSlice<u8, Msb0>, Self), DekuError> { let max_type_bits: usize = Size::of::<$typ>().bit_size(); let bit_size: usize = size.bit_size(); let input_is_le = endian.is_le(); if bit_size > max_type_bits { return Err(DekuError::Parse(format!( "too much data: container of {} bits cannot hold {} bits", max_type_bits, bit_size ))); } if input.len() < bit_size { return Err(DekuError::Incomplete(crate::error::NeedSize::new(bit_size))); } let (bit_slice, rest) = input.split_at(bit_size); let pad = 8 * ((bit_slice.len() + 7) / 8) - bit_slice.len(); let value = if pad == 0 && bit_slice.len() == max_type_bits && bit_slice.domain().region().unwrap().1.len() * 8 == max_type_bits { let bytes: &[u8] = bit_slice.domain().region().unwrap().1; if input_is_le { <$typ>::from_le_bytes(bytes.try_into()?) } else { <$typ>::from_be_bytes(bytes.try_into()?) } } else { let bits: BitVec<u8, Msb0> = { let mut bits = BitVec::with_capacity(bit_slice.len() + pad); bits.extend_from_bitslice(bit_slice); bits.force_align(); let index = if input_is_le { bits.len() - (8 - pad) } else { 0 }; for _ in 0..pad { bits.insert(index, false); } for _ in 0..(max_type_bits - bits.len()) { if input_is_le { bits.push(false); } else { bits.insert(0, false); } } bits }; let bytes: &[u8] = bits.domain().region().unwrap().1; if input_is_le { <$typ>::from_le_bytes(bytes.try_into()?) } else { <$typ>::from_be_bytes(bytes.try_into()?) } }; Ok((rest, value)) } } impl DekuRead<'_, Endian> for $typ { fn read( input: &BitSlice<u8, Msb0>, endian: Endian, ) -> Result<(&BitSlice<u8, Msb0>, Self), DekuError> { let max_type_bits = Size::of::<$typ>(); <$typ>::read(input, (endian, max_type_bits)) } } impl DekuRead<'_, Size> for $typ { fn read( input: &BitSlice<u8, Msb0>, bit_size: Size, ) -> Result<(&BitSlice<u8, Msb0>, Self), DekuError> { let endian = Endian::default(); <$typ>::read(input, (endian, bit_size)) } } impl DekuRead<'_> for $typ { fn read( input: &BitSlice<u8, Msb0>, _: (), ) -> Result<(&BitSlice<u8, Msb0>, Self), DekuError> { <$typ>::read(input, Endian::default()) } } impl DekuWrite<(Endian, Size)> for $typ { fn write( &self, output: &mut BitVec<u8, Msb0>, (endian, size): (Endian, Size), ) -> Result<(), DekuError> { let input = match endian { Endian::Little => self.to_le_bytes(), Endian::Big => self.to_be_bytes(), }; let bit_size: usize = size.bit_size(); let input_bits = input.view_bits::<Msb0>(); if bit_size > input_bits.len() { return Err(DekuError::InvalidParam(format!( "bit size {} is larger then input {}", bit_size, input_bits.len() ))); } if matches!(endian, Endian::Little) { let mut remaining_bits = bit_size; for chunk in input_bits.chunks(8) { if chunk.len() > remaining_bits { output.extend_from_bitslice(&chunk[chunk.len() - remaining_bits..]); break; } else { output.extend_from_bitslice(chunk) } remaining_bits -= chunk.len(); } } else { output.extend_from_bitslice(&input_bits[input_bits.len() - bit_size..]); } Ok(()) } } impl DekuWrite<Endian> for $typ { fn write( &self, output: &mut BitVec<u8, Msb0>, endian: Endian, ) -> Result<(), DekuError> { let input = match endian { Endian::Little => self.to_le_bytes(), Endian::Big => self.to_be_bytes(), }; output.extend_from_bitslice(input.view_bits::<Msb0>()); Ok(()) } } impl DekuWrite<Size> for $typ { fn write( &self, output: &mut BitVec<u8, Msb0>, bit_size: Size, ) -> Result<(), DekuError> { <$typ>::write(self, output, (Endian::default(), bit_size)) } } impl DekuWrite for $typ { fn write(&self, output: &mut BitVec<u8, Msb0>, _: ()) -> Result<(), DekuError> { <$typ>::write(self, output, Endian::default()) } } }; } ImplDekuTraits!(u8); ImplDekuTraits!(u16); ImplDekuTraits!(u32); ImplDekuTraits!(u64); ImplDekuTraits!(u128); ImplDekuTraits!(usize); ImplDekuTraits!(i8); ImplDekuTraits!(i16); ImplDekuTraits!(i32); ImplDekuTraits!(i64); ImplDekuTraits!(i128); ImplDekuTraits!(isize); ImplDekuTraits!(f32); ImplDekuTraits!(f64); #[cfg(test)] mod tests { use super::*; use crate::native_endian; use rstest::rstest; static ENDIAN: Endian = Endian::new(); macro_rules! TestPrimitive { ($test_name:ident, $typ:ty, $input:expr, $expected:expr) => { #[test] fn $test_name() { let input = $input; let bit_slice = input.view_bits::<Msb0>(); let (_rest, res_read) = <$typ>::read(bit_slice, ENDIAN).unwrap(); assert_eq!($expected, res_read); let mut res_write = bitvec![u8, Msb0;]; res_read.write(&mut res_write, ENDIAN).unwrap(); assert_eq!(input, res_write.into_vec()); } }; } TestPrimitive!(test_u8, u8, vec![0xAAu8], 0xAAu8); TestPrimitive!( test_u16, u16, vec![0xABu8, 0xCD], native_endian!(0xCDAB_u16) ); TestPrimitive!( test_u32, u32, vec![0xABu8, 0xCD, 0xEF, 0xBE], native_endian!(0xBEEFCDAB_u32) ); TestPrimitive!( test_u64, u64, vec![0xABu8, 0xCD, 0xEF, 0xBE, 0xAB, 0xCD, 0xFE, 0xC0], native_endian!(0xC0FECDABBEEFCDAB_u64) ); TestPrimitive!( test_u128, u128, vec![ 0xABu8, 0xCD, 0xEF, 0xBE, 0xAB, 0xCD, 0xFE, 0xC0, 0xAB, 0xCD, 0xEF, 0xBE, 0xAB, 0xCD, 0xFE, 0xC0 ], native_endian!(0xC0FECDABBEEFCDABC0FECDABBEEFCDAB_u128) ); TestPrimitive!( test_usize, usize, vec![0xABu8, 0xCD, 0xEF, 0xBE, 0xAB, 0xCD, 0xFE, 0xC0], if core::mem::size_of::<usize>() == 8 { native_endian!(0xC0FECDABBEEFCDAB_usize) } else { native_endian!(0xBEEFCDAB_usize) } ); TestPrimitive!(test_i8, i8, vec![0xFBu8], -5); TestPrimitive!(test_i16, i16, vec![0xFDu8, 0xFE], native_endian!(-259_i16)); TestPrimitive!( test_i32, i32, vec![0x02u8, 0x3F, 0x01, 0xEF], native_endian!(-0x10FEC0FE_i32) ); TestPrimitive!( test_i64, i64, vec![0x02u8, 0x3F, 0x01, 0xEF, 0x01, 0x3F, 0x01, 0xEF], native_endian!(-0x10FEC0FE10FEC0FE_i64) ); TestPrimitive!( test_i128, i128, vec![ 0x02u8, 0x3F, 0x01, 0xEF, 0x01, 0x3F, 0x01, 0xEF, 0x01, 0x3F, 0x01, 0xEF, 0x01, 0x3F, 0x01, 0xEF ], native_endian!(-0x10FEC0FE10FEC0FE10FEC0FE10FEC0FE_i128) ); TestPrimitive!( test_isize, isize, vec![0x02u8, 0x3F, 0x01, 0xEF, 0x01, 0x3F, 0x01, 0xEF], if core::mem::size_of::<isize>() == 8 { native_endian!(-0x10FEC0FE10FEC0FE_isize) } else { native_endian!(-0x10FEC0FE_isize) } ); TestPrimitive!( test_f32, f32, vec![0xA6u8, 0x9B, 0xC4, 0xBB], native_endian!(-0.006_f32) ); TestPrimitive!( test_f64, f64, vec![0xFAu8, 0x7E, 0x6A, 0xBC, 0x74, 0x93, 0x78, 0xBF], native_endian!(-0.006_f64) ); #[rstest(input, endian, bit_size, expected, expected_rest, case::normal([0xDD, 0xCC, 0xBB, 0xAA].as_ref(), Endian::Little, Some(32), 0xAABB_CCDD, bits![u8, Msb0;]), case::normal_bits_12_le([0b1001_0110, 0b1110_0000, 0xCC, 0xDD ].as_ref(), Endian::Little, Some(12), 0b1110_1001_0110, bits![u8, Msb0; 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1]), case::normal_bits_12_be([0b1001_0110, 0b1110_0000, 0xCC, 0xDD ].as_ref(), Endian::Big, Some(12), 0b1001_0110_1110, bits![u8, Msb0; 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1]), case::normal_bit_6([0b1001_0110].as_ref(), Endian::Little, Some(6), 0b1001_01, bits![u8, Msb0; 1, 0,]), #[should_panic(expected = "Incomplete(NeedSize { bits: 32 })")] case::not_enough_data([].as_ref(), Endian::Little, Some(32), 0xFF, bits![u8, Msb0;]), #[should_panic(expected = "Incomplete(NeedSize { bits: 32 })")] case::not_enough_data([0xAA, 0xBB].as_ref(), Endian::Little, Some(32), 0xFF, bits![u8, Msb0;]), #[should_panic(expected = "Parse(\"too much data: container of 32 bits cannot hold 64 bits\")")] case::too_much_data([0xAA, 0xBB, 0xCC, 0xDD, 0xAA, 0xBB, 0xCC, 0xDD].as_ref(), Endian::Little, Some(64), 0xFF, bits![u8, Msb0;]), )] fn test_bit_read( input: &[u8], endian: Endian, bit_size: Option<usize>, expected: u32, expected_rest: &BitSlice<u8, Msb0>, ) { let bit_slice = input.view_bits::<Msb0>(); let (rest, res_read) = match bit_size { Some(bit_size) => u32::read(bit_slice, (endian, Size::Bits(bit_size))).unwrap(), None => u32::read(bit_slice, endian).unwrap(), }; assert_eq!(expected, res_read); assert_eq!(expected_rest, rest); } #[rstest(input, endian, bit_size, expected, case::normal_le(0xDDCC_BBAA, Endian::Little, None, vec![0xAA, 0xBB, 0xCC, 0xDD]), case::normal_be(0xDDCC_BBAA, Endian::Big, None, vec![0xDD, 0xCC, 0xBB, 0xAA]), case::bit_size_le_smaller(0x03AB, Endian::Little, Some(10), vec![0xAB, 0b11_000000]), case::bit_size_be_smaller(0x03AB, Endian::Big, Some(10), vec![0b11_1010_10, 0b11_000000]), #[should_panic(expected = "InvalidParam(\"bit size 100 is larger then input 32\")")] case::bit_size_le_bigger(0x03AB, Endian::Little, Some(100), vec![0xAB, 0b11_000000]), )] fn test_bit_write(input: u32, endian: Endian, bit_size: Option<usize>, expected: Vec<u8>) { let mut res_write = bitvec![u8, Msb0;]; match bit_size { Some(bit_size) => input .write(&mut res_write, (endian, Size::Bits(bit_size))) .unwrap(), None => input.write(&mut res_write, endian).unwrap(), }; assert_eq!(expected, res_write.into_vec()); } #[rstest(input, endian, bit_size, expected, expected_rest, expected_write, case::normal([0xDD, 0xCC, 0xBB, 0xAA].as_ref(), Endian::Little, Some(32), 0xAABB_CCDD, bits![u8, Msb0;], vec![0xDD, 0xCC, 0xBB, 0xAA]), )] fn test_bit_read_write( input: &[u8], endian: Endian, bit_size: Option<usize>, expected: u32, expected_rest: &BitSlice<u8, Msb0>, expected_write: Vec<u8>, ) { let bit_slice = input.view_bits::<Msb0>(); let (rest, res_read) = match bit_size { Some(bit_size) => u32::read(bit_slice, (endian, Size::Bits(bit_size))).unwrap(), None => u32::read(bit_slice, endian).unwrap(), }; assert_eq!(expected, res_read); assert_eq!(expected_rest, rest); let mut res_write = bitvec![u8, Msb0;]; match bit_size { Some(bit_size) => res_read .write(&mut res_write, (endian, Size::Bits(bit_size))) .unwrap(), None => res_read.write(&mut res_write, endian).unwrap(), }; assert_eq!(expected_write, res_write.into_vec()); } }
use crate::{ctx::*, DekuError, DekuRead, DekuWrite}; use bitvec::prelude::*; use core::convert::TryInto; #[cfg(feature = "alloc")] use alloc::format; macro_rules! ImplDekuTraits { ($typ:ty) => { impl DekuRead<'_, (Endian, Size)> for $typ { fn read( input: &BitSlice<u8, Msb0>, (endian, size): (Endian, Size), ) -> Result<(&BitSlice<u8, Msb0>, Self), DekuError> { let max_type_bits: usize = Size::of::<$typ>().bit_size(); let bit_size: usize = size.bit_size(); let input_is_le = endian.is_le(); if bit_size > max_type_bits { return Err(DekuError::Parse(format!( "too much data: container of {} bits cannot hold {} bits", max_type_bits, bit_size ))); } if input.len() < bit_size { return Err(DekuError::Incomplete(crate::error::NeedSize::new(bit_size))); } let (bit_slice, rest) = input.split_at(bit_size); let pad = 8 * ((bit_slice.len() + 7) / 8) - bit_slice.len(); let value = if pad == 0 && bit_sl
3F, 0x01, 0xEF], native_endian!(-0x10FEC0FE_i32) ); TestPrimitive!( test_i64, i64, vec![0x02u8, 0x3F, 0x01, 0xEF, 0x01, 0x3F, 0x01, 0xEF], native_endian!(-0x10FEC0FE10FEC0FE_i64) ); TestPrimitive!( test_i128, i128, vec![ 0x02u8, 0x3F, 0x01, 0xEF, 0x01, 0x3F, 0x01, 0xEF, 0x01, 0x3F, 0x01, 0xEF, 0x01, 0x3F, 0x01, 0xEF ], native_endian!(-0x10FEC0FE10FEC0FE10FEC0FE10FEC0FE_i128) ); TestPrimitive!( test_isize, isize, vec![0x02u8, 0x3F, 0x01, 0xEF, 0x01, 0x3F, 0x01, 0xEF], if core::mem::size_of::<isize>() == 8 { native_endian!(-0x10FEC0FE10FEC0FE_isize) } else { native_endian!(-0x10FEC0FE_isize) } ); TestPrimitive!( test_f32, f32, vec![0xA6u8, 0x9B, 0xC4, 0xBB], native_endian!(-0.006_f32) ); TestPrimitive!( test_f64, f64, vec![0xFAu8, 0x7E, 0x6A, 0xBC, 0x74, 0x93, 0x78, 0xBF], native_endian!(-0.006_f64) ); #[rstest(input, endian, bit_size, expected, expected_rest, case::normal([0xDD, 0xCC, 0xBB, 0xAA].as_ref(), Endian::Little, Some(32), 0xAABB_CCDD, bits![u8, Msb0;]), case::normal_bits_12_le([0b1001_0110, 0b1110_0000, 0xCC, 0xDD ].as_ref(), Endian::Little, Some(12), 0b1110_1001_0110, bits![u8, Msb0; 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1]), case::normal_bits_12_be([0b1001_0110, 0b1110_0000, 0xCC, 0xDD ].as_ref(), Endian::Big, Some(12), 0b1001_0110_1110, bits![u8, Msb0; 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1]), case::normal_bit_6([0b1001_0110].as_ref(), Endian::Little, Some(6), 0b1001_01, bits![u8, Msb0; 1, 0,]), #[should_panic(expected = "Incomplete(NeedSize { bits: 32 })")] case::not_enough_data([].as_ref(), Endian::Little, Some(32), 0xFF, bits![u8, Msb0;]), #[should_panic(expected = "Incomplete(NeedSize { bits: 32 })")] case::not_enough_data([0xAA, 0xBB].as_ref(), Endian::Little, Some(32), 0xFF, bits![u8, Msb0;]), #[should_panic(expected = "Parse(\"too much data: container of 32 bits cannot hold 64 bits\")")] case::too_much_data([0xAA, 0xBB, 0xCC, 0xDD, 0xAA, 0xBB, 0xCC, 0xDD].as_ref(), Endian::Little, Some(64), 0xFF, bits![u8, Msb0;]), )] fn test_bit_read( input: &[u8], endian: Endian, bit_size: Option<usize>, expected: u32, expected_rest: &BitSlice<u8, Msb0>, ) { let bit_slice = input.view_bits::<Msb0>(); let (rest, res_read) = match bit_size { Some(bit_size) => u32::read(bit_slice, (endian, Size::Bits(bit_size))).unwrap(), None => u32::read(bit_slice, endian).unwrap(), }; assert_eq!(expected, res_read); assert_eq!(expected_rest, rest); } #[rstest(input, endian, bit_size, expected, case::normal_le(0xDDCC_BBAA, Endian::Little, None, vec![0xAA, 0xBB, 0xCC, 0xDD]), case::normal_be(0xDDCC_BBAA, Endian::Big, None, vec![0xDD, 0xCC, 0xBB, 0xAA]), case::bit_size_le_smaller(0x03AB, Endian::Little, Some(10), vec![0xAB, 0b11_000000]), case::bit_size_be_smaller(0x03AB, Endian::Big, Some(10), vec![0b11_1010_10, 0b11_000000]), #[should_panic(expected = "InvalidParam(\"bit size 100 is larger then input 32\")")] case::bit_size_le_bigger(0x03AB, Endian::Little, Some(100), vec![0xAB, 0b11_000000]), )] fn test_bit_write(input: u32, endian: Endian, bit_size: Option<usize>, expected: Vec<u8>) { let mut res_write = bitvec![u8, Msb0;]; match bit_size { Some(bit_size) => input .write(&mut res_write, (endian, Size::Bits(bit_size))) .unwrap(), None => input.write(&mut res_write, endian).unwrap(), }; assert_eq!(expected, res_write.into_vec()); } #[rstest(input, endian, bit_size, expected, expected_rest, expected_write, case::normal([0xDD, 0xCC, 0xBB, 0xAA].as_ref(), Endian::Little, Some(32), 0xAABB_CCDD, bits![u8, Msb0;], vec![0xDD, 0xCC, 0xBB, 0xAA]), )] fn test_bit_read_write( input: &[u8], endian: Endian, bit_size: Option<usize>, expected: u32, expected_rest: &BitSlice<u8, Msb0>, expected_write: Vec<u8>, ) { let bit_slice = input.view_bits::<Msb0>(); let (rest, res_read) = match bit_size { Some(bit_size) => u32::read(bit_slice, (endian, Size::Bits(bit_size))).unwrap(), None => u32::read(bit_slice, endian).unwrap(), }; assert_eq!(expected, res_read); assert_eq!(expected_rest, rest); let mut res_write = bitvec![u8, Msb0;]; match bit_size { Some(bit_size) => res_read .write(&mut res_write, (endian, Size::Bits(bit_size))) .unwrap(), None => res_read.write(&mut res_write, endian).unwrap(), }; assert_eq!(expected_write, res_write.into_vec()); } }
ice.len() == max_type_bits && bit_slice.domain().region().unwrap().1.len() * 8 == max_type_bits { let bytes: &[u8] = bit_slice.domain().region().unwrap().1; if input_is_le { <$typ>::from_le_bytes(bytes.try_into()?) } else { <$typ>::from_be_bytes(bytes.try_into()?) } } else { let bits: BitVec<u8, Msb0> = { let mut bits = BitVec::with_capacity(bit_slice.len() + pad); bits.extend_from_bitslice(bit_slice); bits.force_align(); let index = if input_is_le { bits.len() - (8 - pad) } else { 0 }; for _ in 0..pad { bits.insert(index, false); } for _ in 0..(max_type_bits - bits.len()) { if input_is_le { bits.push(false); } else { bits.insert(0, false); } } bits }; let bytes: &[u8] = bits.domain().region().unwrap().1; if input_is_le { <$typ>::from_le_bytes(bytes.try_into()?) } else { <$typ>::from_be_bytes(bytes.try_into()?) } }; Ok((rest, value)) } } impl DekuRead<'_, Endian> for $typ { fn read( input: &BitSlice<u8, Msb0>, endian: Endian, ) -> Result<(&BitSlice<u8, Msb0>, Self), DekuError> { let max_type_bits = Size::of::<$typ>(); <$typ>::read(input, (endian, max_type_bits)) } } impl DekuRead<'_, Size> for $typ { fn read( input: &BitSlice<u8, Msb0>, bit_size: Size, ) -> Result<(&BitSlice<u8, Msb0>, Self), DekuError> { let endian = Endian::default(); <$typ>::read(input, (endian, bit_size)) } } impl DekuRead<'_> for $typ { fn read( input: &BitSlice<u8, Msb0>, _: (), ) -> Result<(&BitSlice<u8, Msb0>, Self), DekuError> { <$typ>::read(input, Endian::default()) } } impl DekuWrite<(Endian, Size)> for $typ { fn write( &self, output: &mut BitVec<u8, Msb0>, (endian, size): (Endian, Size), ) -> Result<(), DekuError> { let input = match endian { Endian::Little => self.to_le_bytes(), Endian::Big => self.to_be_bytes(), }; let bit_size: usize = size.bit_size(); let input_bits = input.view_bits::<Msb0>(); if bit_size > input_bits.len() { return Err(DekuError::InvalidParam(format!( "bit size {} is larger then input {}", bit_size, input_bits.len() ))); } if matches!(endian, Endian::Little) { let mut remaining_bits = bit_size; for chunk in input_bits.chunks(8) { if chunk.len() > remaining_bits { output.extend_from_bitslice(&chunk[chunk.len() - remaining_bits..]); break; } else { output.extend_from_bitslice(chunk) } remaining_bits -= chunk.len(); } } else { output.extend_from_bitslice(&input_bits[input_bits.len() - bit_size..]); } Ok(()) } } impl DekuWrite<Endian> for $typ { fn write( &self, output: &mut BitVec<u8, Msb0>, endian: Endian, ) -> Result<(), DekuError> { let input = match endian { Endian::Little => self.to_le_bytes(), Endian::Big => self.to_be_bytes(), }; output.extend_from_bitslice(input.view_bits::<Msb0>()); Ok(()) } } impl DekuWrite<Size> for $typ { fn write( &self, output: &mut BitVec<u8, Msb0>, bit_size: Size, ) -> Result<(), DekuError> { <$typ>::write(self, output, (Endian::default(), bit_size)) } } impl DekuWrite for $typ { fn write(&self, output: &mut BitVec<u8, Msb0>, _: ()) -> Result<(), DekuError> { <$typ>::write(self, output, Endian::default()) } } }; } ImplDekuTraits!(u8); ImplDekuTraits!(u16); ImplDekuTraits!(u32); ImplDekuTraits!(u64); ImplDekuTraits!(u128); ImplDekuTraits!(usize); ImplDekuTraits!(i8); ImplDekuTraits!(i16); ImplDekuTraits!(i32); ImplDekuTraits!(i64); ImplDekuTraits!(i128); ImplDekuTraits!(isize); ImplDekuTraits!(f32); ImplDekuTraits!(f64); #[cfg(test)] mod tests { use super::*; use crate::native_endian; use rstest::rstest; static ENDIAN: Endian = Endian::new(); macro_rules! TestPrimitive { ($test_name:ident, $typ:ty, $input:expr, $expected:expr) => { #[test] fn $test_name() { let input = $input; let bit_slice = input.view_bits::<Msb0>(); let (_rest, res_read) = <$typ>::read(bit_slice, ENDIAN).unwrap(); assert_eq!($expected, res_read); let mut res_write = bitvec![u8, Msb0;]; res_read.write(&mut res_write, ENDIAN).unwrap(); assert_eq!(input, res_write.into_vec()); } }; } TestPrimitive!(test_u8, u8, vec![0xAAu8], 0xAAu8); TestPrimitive!( test_u16, u16, vec![0xABu8, 0xCD], native_endian!(0xCDAB_u16) ); TestPrimitive!( test_u32, u32, vec![0xABu8, 0xCD, 0xEF, 0xBE], native_endian!(0xBEEFCDAB_u32) ); TestPrimitive!( test_u64, u64, vec![0xABu8, 0xCD, 0xEF, 0xBE, 0xAB, 0xCD, 0xFE, 0xC0], native_endian!(0xC0FECDABBEEFCDAB_u64) ); TestPrimitive!( test_u128, u128, vec![ 0xABu8, 0xCD, 0xEF, 0xBE, 0xAB, 0xCD, 0xFE, 0xC0, 0xAB, 0xCD, 0xEF, 0xBE, 0xAB, 0xCD, 0xFE, 0xC0 ], native_endian!(0xC0FECDABBEEFCDABC0FECDABBEEFCDAB_u128) ); TestPrimitive!( test_usize, usize, vec![0xABu8, 0xCD, 0xEF, 0xBE, 0xAB, 0xCD, 0xFE, 0xC0], if core::mem::size_of::<usize>() == 8 { native_endian!(0xC0FECDABBEEFCDAB_usize) } else { native_endian!(0xBEEFCDAB_usize) } ); TestPrimitive!(test_i8, i8, vec![0xFBu8], -5); TestPrimitive!(test_i16, i16, vec![0xFDu8, 0xFE], native_endian!(-259_i16)); TestPrimitive!( test_i32, i32, vec![0x02u8, 0x
random
[ { "content": "fn emit_magic_read(input: &DekuData) -> TokenStream {\n\n let crate_ = super::get_crate_name();\n\n if let Some(magic) = &input.magic {\n\n quote! {\n\n let __deku_magic = #magic;\n\n\n\n for __deku_byte in __deku_magic {\n\n let (__deku_new_rest, __deku_read_byte) = u8::read(__deku_rest, ())?;\n\n if *__deku_byte != __deku_read_byte {\n\n return Err(::#crate_::DekuError::Parse(format!(\"Missing magic value {:?}\", #magic)));\n\n }\n\n\n\n __deku_rest = __deku_new_rest;\n\n }\n\n }\n\n } else {\n\n quote! {}\n\n }\n\n}\n\n\n", "file_path": "deku-derive/src/macros/deku_read.rs", "rank": 0, "score": 176670.81260673385 }, { "content": "fn test_pad_bits_before_read_err() {\n\n #[derive(PartialEq, Debug, DekuRead)]\n\n struct TestStruct {\n\n #[deku(bits = 2)]\n\n field_a: u8,\n\n #[deku(pad_bits_before = \"-1\", bits = 4)]\n\n field_b: u8,\n\n }\n\n\n\n let data: Vec<u8> = vec![0b10_01_1001];\n\n\n\n let _ret_read = TestStruct::try_from(data.as_ref()).unwrap();\n\n}\n\n\n\n#[test]\n\n#[should_panic(\n\n expected = r#\"InvalidParam(\"Invalid padding param \\\"(- 1)\\\": cannot convert to usize\")\"#\n\n)]\n", "file_path": "tests/test_attributes/test_padding/test_pad_bits_before.rs", "rank": 1, "score": 176557.44079582253 }, { "content": "fn test_pad_bits_after_read_err() {\n\n #[derive(PartialEq, Debug, DekuRead)]\n\n struct TestStruct {\n\n #[deku(bits = 2)]\n\n field_a: u8,\n\n #[deku(pad_bits_after = \"-1\", bits = 4)]\n\n field_b: u8,\n\n }\n\n\n\n let data: Vec<u8> = vec![0b10_01_1001];\n\n\n\n let _ret_read = TestStruct::try_from(data.as_ref()).unwrap();\n\n}\n\n\n\n#[test]\n\n#[should_panic(\n\n expected = r#\"InvalidParam(\"Invalid padding param \\\"(- 1)\\\": cannot convert to usize\")\"#\n\n)]\n", "file_path": "tests/test_attributes/test_padding/test_pad_bits_after.rs", "rank": 2, "score": 176557.44079582253 }, { "content": "#[test]\n\n#[should_panic(expected = r#\"Parse(\"Too much data\")\"#)]\n\nfn test_read_too_much_data() {\n\n #[derive(DekuRead)]\n\n pub struct TestStruct {\n\n #[deku(bits = \"6\")]\n\n pub field_a: u8,\n\n }\n\n\n\n let test_data = [0u8; 100].as_ref();\n\n TestStruct::try_from(test_data).unwrap();\n\n}\n\n\n", "file_path": "tests/test_struct.rs", "rank": 3, "score": 171461.11951669352 }, { "content": "fn emit_padding(bit_size: &TokenStream) -> TokenStream {\n\n let crate_ = super::get_crate_name();\n\n quote! {\n\n {\n\n use core::convert::TryFrom;\n\n let __deku_pad = usize::try_from(#bit_size).map_err(|e|\n\n ::#crate_::DekuError::InvalidParam(format!(\n\n \"Invalid padding param \\\"({})\\\": cannot convert to usize\",\n\n stringify!(#bit_size)\n\n ))\n\n )?;\n\n\n\n if __deku_rest.len() >= __deku_pad {\n\n let (__deku_padded_bits, __deku_new_rest) = __deku_rest.split_at(__deku_pad);\n\n __deku_rest = __deku_new_rest;\n\n } else {\n\n return Err(::#crate_::DekuError::Incomplete(::#crate_::error::NeedSize::new(__deku_pad)));\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "deku-derive/src/macros/deku_read.rs", "rank": 4, "score": 169738.16263731496 }, { "content": "fn deku_read_byte(input: &[u8]) {\n\n let (_rest, _v) = DekuByte::from_bytes((input, 0)).unwrap();\n\n}\n\n\n", "file_path": "benches/deku.rs", "rank": 5, "score": 158506.17129318698 }, { "content": "fn deku_read_vec(input: &[u8]) {\n\n let (_rest, _v) = DekuVec::from_bytes((input, 0)).unwrap();\n\n}\n\n\n", "file_path": "benches/deku.rs", "rank": 6, "score": 158506.17129318698 }, { "content": "fn deku_read_enum(input: &[u8]) {\n\n let (_rest, _v) = DekuEnum::from_bytes((input, 0)).unwrap();\n\n}\n\n\n", "file_path": "benches/deku.rs", "rank": 7, "score": 158506.17129318698 }, { "content": "fn emit_struct(input: &DekuData) -> Result<TokenStream, syn::Error> {\n\n let crate_ = super::get_crate_name();\n\n let mut tokens = TokenStream::new();\n\n\n\n let lifetime = input\n\n .generics\n\n .lifetimes()\n\n .next()\n\n .map_or(quote!('_), |v| quote!(#v));\n\n\n\n let DekuDataStruct {\n\n imp,\n\n wher,\n\n ident,\n\n fields,\n\n } = DekuDataStruct::try_from(input)?;\n\n\n\n let magic_read = emit_magic_read(input);\n\n\n\n // check if the first field has an ident, if not, it's a unnamed struct\n", "file_path": "deku-derive/src/macros/deku_read.rs", "rank": 8, "score": 151434.5857855329 }, { "content": "fn emit_enum(input: &DekuData) -> Result<TokenStream, syn::Error> {\n\n let crate_ = super::get_crate_name();\n\n let mut tokens = TokenStream::new();\n\n\n\n let DekuDataEnum {\n\n imp,\n\n wher,\n\n variants,\n\n ident,\n\n id,\n\n id_type,\n\n id_args,\n\n } = DekuDataEnum::try_from(input)?;\n\n\n\n let lifetime = input\n\n .generics\n\n .lifetimes()\n\n .next()\n\n .map_or(quote!('_), |v| quote!(#v));\n\n\n", "file_path": "deku-derive/src/macros/deku_read.rs", "rank": 9, "score": 151434.5857855329 }, { "content": "#[test]\n\nfn test_pad_bits_after() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n struct TestStruct {\n\n #[deku(bits = 2)]\n\n field_a: u8,\n\n #[deku(bits = 4, pad_bits_after = \"2\")]\n\n field_b: u8,\n\n }\n\n\n\n let data: Vec<u8> = vec![0b10_0110_01];\n\n\n\n let ret_read = TestStruct::try_from(data.as_ref()).unwrap();\n\n\n\n assert_eq!(\n\n TestStruct {\n\n field_a: 0b10,\n\n field_b: 0b0110,\n\n },\n\n ret_read\n\n );\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(vec![0b10_0110_00], ret_write);\n\n}\n\n\n", "file_path": "tests/test_attributes/test_padding/test_pad_bits_after.rs", "rank": 10, "score": 150833.9681413785 }, { "content": "#[test]\n\nfn test_pad_bits_before() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n struct TestStruct {\n\n #[deku(bits = 2)]\n\n field_a: u8,\n\n #[deku(pad_bits_before = \"2\", bits = 4)]\n\n field_b: u8,\n\n }\n\n\n\n let data: Vec<u8> = vec![0b10_01_1001];\n\n\n\n let ret_read = TestStruct::try_from(data.as_ref()).unwrap();\n\n\n\n assert_eq!(\n\n TestStruct {\n\n field_a: 0b10,\n\n field_b: 0b1001,\n\n },\n\n ret_read\n\n );\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(vec![0b10_00_1001], ret_write);\n\n}\n\n\n", "file_path": "tests/test_attributes/test_padding/test_pad_bits_before.rs", "rank": 11, "score": 150833.9681413785 }, { "content": "#[test]\n\n#[should_panic(expected = \"Incomplete(NeedSize { bits: 6 })\")]\n\nfn test_pad_bits_before_not_enough() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n struct TestStruct {\n\n #[deku(bits = 4)]\n\n field_a: u8,\n\n #[deku(pad_bits_before = \"6\", bits = 2)]\n\n field_b: u8,\n\n }\n\n\n\n let data: Vec<u8> = vec![0b10_01_1001];\n\n\n\n let _ret_read = TestStruct::try_from(data.as_ref()).unwrap();\n\n}\n\n\n\n#[test]\n\n#[should_panic(\n\n expected = r#\"InvalidParam(\"Invalid padding param \\\"(- 1)\\\": cannot convert to usize\")\"#\n\n)]\n", "file_path": "tests/test_attributes/test_padding/test_pad_bits_before.rs", "rank": 12, "score": 148685.7269761894 }, { "content": "#[test]\n\n#[should_panic(expected = \"Incomplete(NeedSize { bits: 4 })\")]\n\nfn test_pad_bits_after_not_enough() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n struct TestStruct {\n\n #[deku(bits = 2)]\n\n field_a: u8,\n\n #[deku(bits = 4, pad_bits_after = \"4\")]\n\n field_b: u8,\n\n }\n\n\n\n let data: Vec<u8> = vec![0b10_0110_01];\n\n\n\n let _ret_read = TestStruct::try_from(data.as_ref()).unwrap();\n\n}\n\n\n\n#[test]\n\n#[should_panic(\n\n expected = r#\"InvalidParam(\"Invalid padding param \\\"(- 1)\\\": cannot convert to usize\")\"#\n\n)]\n", "file_path": "tests/test_attributes/test_padding/test_pad_bits_after.rs", "rank": 13, "score": 148685.7269761894 }, { "content": "fn test_pad_bits_after_write_err() {\n\n #[derive(PartialEq, Debug, DekuWrite)]\n\n struct TestStruct {\n\n #[deku(bits = 2)]\n\n field_a: u8,\n\n #[deku(pad_bits_after = \"-1\", bits = 4)]\n\n field_b: u8,\n\n }\n\n\n\n let data = TestStruct {\n\n field_a: 0b10,\n\n field_b: 0b1001,\n\n };\n\n\n\n let _ret_write: Vec<u8> = data.try_into().unwrap();\n\n}\n", "file_path": "tests/test_attributes/test_padding/test_pad_bits_after.rs", "rank": 14, "score": 146601.98842715402 }, { "content": "fn test_pad_bits_before_write_err() {\n\n #[derive(PartialEq, Debug, DekuWrite)]\n\n struct TestStruct {\n\n #[deku(bits = 2)]\n\n field_a: u8,\n\n #[deku(pad_bits_before = \"-1\", bits = 4)]\n\n field_b: u8,\n\n }\n\n\n\n let data = TestStruct {\n\n field_a: 0b10,\n\n field_b: 0b1001,\n\n };\n\n\n\n let _ret_write: Vec<u8> = data.try_into().unwrap();\n\n}\n", "file_path": "tests/test_attributes/test_padding/test_pad_bits_before.rs", "rank": 15, "score": 146601.98842715402 }, { "content": "/// Read `u8`s and returns a byte slice up until a given predicate returns true\n\n/// * `ctx` - The context required by `u8`. It will be passed to every `u8` when constructing.\n\n/// * `predicate` - the predicate that decides when to stop reading `u8`s\n\n/// The predicate takes two parameters: the number of bits that have been read so far,\n\n/// and a borrow of the latest value to have been read. It should return `true` if reading\n\n/// should now stop, and `false` otherwise\n\nfn read_slice_with_predicate<'a, Ctx: Copy, Predicate: FnMut(usize, &u8) -> bool>(\n\n input: &'a BitSlice<u8, Msb0>,\n\n ctx: Ctx,\n\n mut predicate: Predicate,\n\n) -> Result<(&'a BitSlice<u8, Msb0>, &[u8]), DekuError>\n\nwhere\n\n u8: DekuRead<'a, Ctx>,\n\n{\n\n let mut rest = input;\n\n let mut value;\n\n\n\n loop {\n\n let (new_rest, val) = u8::read(rest, ctx)?;\n\n rest = new_rest;\n\n\n\n let read_idx = unsafe { rest.as_bitptr().offset_from(input.as_bitptr()) } as usize;\n\n value = input[..read_idx].domain().region().unwrap().1;\n\n\n\n if predicate(read_idx, &val) {\n\n break;\n", "file_path": "src/impls/slice.rs", "rank": 16, "score": 143430.45591246244 }, { "content": "fn emit_padding(bit_size: &TokenStream) -> TokenStream {\n\n let crate_ = super::get_crate_name();\n\n quote! {\n\n {\n\n use core::convert::TryFrom;\n\n let __deku_pad = usize::try_from(#bit_size).map_err(|e|\n\n ::#crate_::DekuError::InvalidParam(format!(\n\n \"Invalid padding param \\\"({})\\\": cannot convert to usize\",\n\n stringify!(#bit_size)\n\n ))\n\n )?;\n\n let new_len = __deku_output.len() + __deku_pad;\n\n __deku_output.resize(new_len, false);\n\n }\n\n }\n\n}\n\n\n", "file_path": "deku-derive/src/macros/deku_write.rs", "rank": 17, "score": 140518.4457504114 }, { "content": "#[test]\n\nfn test_pad_bits_after_and_pad_bytes_after() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n struct TestStruct {\n\n #[deku(bits = 2, pad_bits_after = \"6\", pad_bytes_after = \"1\")]\n\n field_a: u8,\n\n field_b: u8,\n\n }\n\n\n\n let data: Vec<u8> = vec![0b10_000000, 0xAA, 0xBB];\n\n\n\n let ret_read = TestStruct::try_from(data.as_ref()).unwrap();\n\n\n\n assert_eq!(\n\n TestStruct {\n\n field_a: 0b10,\n\n field_b: 0xBB,\n\n },\n\n ret_read\n\n );\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(vec![0b10_000000, 0x00, 0xBB], ret_write);\n\n}\n", "file_path": "tests/test_attributes/test_padding/mod.rs", "rank": 18, "score": 140296.05443210187 }, { "content": "#[test]\n\nfn test_pad_bits_before_and_pad_bytes_before() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n struct TestStruct {\n\n #[deku(bits = 2)]\n\n field_a: u8,\n\n #[deku(pad_bits_before = \"5 + 1\", pad_bytes_before = \"0 + 1\")]\n\n field_b: u8,\n\n }\n\n\n\n let data: Vec<u8> = vec![0b10_000000, 0xAA, 0xBB];\n\n\n\n let ret_read = TestStruct::try_from(data.as_ref()).unwrap();\n\n\n\n assert_eq!(\n\n TestStruct {\n\n field_a: 0b10,\n\n field_b: 0xBB,\n\n },\n\n ret_read\n\n );\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(vec![0b10_000000, 0x00, 0xBB], ret_write);\n\n}\n\n\n", "file_path": "tests/test_attributes/test_padding/mod.rs", "rank": 19, "score": 140296.05443210187 }, { "content": "#[wasm_bindgen]\n\npub fn deku_read(input: &[u8]) -> DekuTest {\n\n let (_rest, val) = DekuTest::from_bytes((input, 0)).unwrap();\n\n\n\n val\n\n}\n\n\n", "file_path": "ensure_wasm/src/lib.rs", "rank": 20, "score": 139773.54408709038 }, { "content": "/// Read `T`s into a vec until a given predicate returns true\n\n/// * `capacity` - an optional capacity to pre-allocate the vector with\n\n/// * `ctx` - The context required by `T`. It will be passed to every `T` when constructing.\n\n/// * `predicate` - the predicate that decides when to stop reading `T`s\n\n/// The predicate takes two parameters: the number of bits that have been read so far,\n\n/// and a borrow of the latest value to have been read. It should return `true` if reading\n\n/// should now stop, and `false` otherwise\n\nfn read_vec_with_predicate<\n\n 'a,\n\n T: DekuRead<'a, Ctx>,\n\n Ctx: Copy,\n\n Predicate: FnMut(usize, &T) -> bool,\n\n>(\n\n input: &'a BitSlice<u8, Msb0>,\n\n capacity: Option<usize>,\n\n ctx: Ctx,\n\n mut predicate: Predicate,\n\n) -> Result<(&'a BitSlice<u8, Msb0>, Vec<T>), DekuError> {\n\n let mut res = capacity.map_or_else(Vec::new, Vec::with_capacity);\n\n\n\n let mut rest = input;\n\n\n\n loop {\n\n let (new_rest, val) = <T>::read(rest, ctx)?;\n\n res.push(val);\n\n rest = new_rest;\n\n\n", "file_path": "src/impls/vec.rs", "rank": 21, "score": 137534.61869676242 }, { "content": "#[allow(clippy::type_complexity)]\n\nfn read_hashset_with_predicate<\n\n 'a,\n\n T: DekuRead<'a, Ctx> + Eq + Hash,\n\n S: BuildHasher + Default,\n\n Ctx: Copy,\n\n Predicate: FnMut(usize, &T) -> bool,\n\n>(\n\n input: &'a BitSlice<u8, Msb0>,\n\n capacity: Option<usize>,\n\n ctx: Ctx,\n\n mut predicate: Predicate,\n\n) -> Result<(&'a BitSlice<u8, Msb0>, HashSet<T, S>), DekuError> {\n\n let mut res = HashSet::with_capacity_and_hasher(capacity.unwrap_or(0), S::default());\n\n\n\n let mut rest = input;\n\n let mut found_predicate = false;\n\n\n\n while !found_predicate {\n\n let (new_rest, val) = <T>::read(rest, ctx)?;\n\n found_predicate = predicate(unsafe { new_rest.as_bitptr().offset_from(input.as_bitptr()) } as usize, &val);\n", "file_path": "src/impls/hashset.rs", "rank": 22, "score": 137517.17408421665 }, { "content": "#[allow(clippy::type_complexity)]\n\nfn read_hashmap_with_predicate<\n\n 'a,\n\n K: DekuRead<'a, Ctx> + Eq + Hash,\n\n V: DekuRead<'a, Ctx>,\n\n S: BuildHasher + Default,\n\n Ctx: Copy,\n\n Predicate: FnMut(usize, &(K, V)) -> bool,\n\n>(\n\n input: &'a BitSlice<u8, Msb0>,\n\n capacity: Option<usize>,\n\n ctx: Ctx,\n\n mut predicate: Predicate,\n\n) -> Result<(&'a BitSlice<u8, Msb0>, HashMap<K, V, S>), DekuError> {\n\n let mut res = HashMap::with_capacity_and_hasher(capacity.unwrap_or(0), S::default());\n\n\n\n let mut rest = input;\n\n let mut found_predicate = false;\n\n\n\n while !found_predicate {\n\n let (new_rest, kv) = <(K, V)>::read(rest, ctx)?;\n", "file_path": "src/impls/hashmap.rs", "rank": 23, "score": 137517.17408421665 }, { "content": "fn emit_magic_write(input: &DekuData) -> TokenStream {\n\n if let Some(magic) = &input.magic {\n\n quote! {\n\n #magic.write(__deku_output, ())?;\n\n }\n\n } else {\n\n quote! {}\n\n }\n\n}\n\n\n", "file_path": "deku-derive/src/macros/deku_write.rs", "rank": 24, "score": 136833.21447581745 }, { "content": "fn pad_bits(\n\n bits: Option<&TokenStream>,\n\n bytes: Option<&TokenStream>,\n\n emit_padding: fn(&TokenStream) -> TokenStream,\n\n) -> TokenStream {\n\n match (bits, bytes) {\n\n (Some(pad_bits), Some(pad_bytes)) => {\n\n emit_padding(&quote! { (#pad_bits) + ((#pad_bytes) * 8) })\n\n }\n\n (Some(pad_bits), None) => emit_padding(pad_bits),\n\n (None, Some(pad_bytes)) => emit_padding(&quote! {((#pad_bytes) * 8)}),\n\n (None, None) => quote!(),\n\n }\n\n}\n", "file_path": "deku-derive/src/macros/mod.rs", "rank": 25, "score": 135736.05864649944 }, { "content": "fn test_pad_bytes_before_read_err() {\n\n #[derive(PartialEq, Debug, DekuRead)]\n\n struct TestStruct {\n\n field_a: u8,\n\n #[deku(pad_bytes_before = \"-2\")]\n\n field_b: u8,\n\n }\n\n\n\n let data: Vec<u8> = vec![0xAA, 0xBB, 0xCC, 0xDD];\n\n\n\n let _ret_read = TestStruct::try_from(data.as_ref()).unwrap();\n\n}\n\n\n\n#[test]\n\n#[should_panic(\n\n expected = r#\"InvalidParam(\"Invalid padding param \\\"(((- 2) * 8))\\\": cannot convert to usize\")\"#\n\n)]\n", "file_path": "tests/test_attributes/test_padding/test_pad_bytes_before.rs", "rank": 26, "score": 135505.99330034992 }, { "content": "fn test_pad_bytes_after_read_err() {\n\n #[derive(PartialEq, Debug, DekuRead)]\n\n struct TestStruct {\n\n #[deku(pad_bytes_after = \"-2\")]\n\n field_a: u8,\n\n field_b: u8,\n\n }\n\n\n\n let data: Vec<u8> = vec![0xAA, 0xBB, 0xCC, 0xDD];\n\n\n\n let _ret_read = TestStruct::try_from(data.as_ref()).unwrap();\n\n}\n\n\n\n#[test]\n\n#[should_panic(\n\n expected = r#\"InvalidParam(\"Invalid padding param \\\"(((- 2) * 8))\\\": cannot convert to usize\")\"#\n\n)]\n", "file_path": "tests/test_attributes/test_padding/test_pad_bytes_after.rs", "rank": 27, "score": 135505.99330034992 }, { "content": "fn bit_flipper_read(\n\n field_a: u8,\n\n rest: &BitSlice<u8, Msb0>,\n\n bit_size: Size,\n\n) -> Result<(&BitSlice<u8, Msb0>, u8), DekuError> {\n\n // Access to previously read fields\n\n println!(\"field_a = 0x{:X}\", field_a);\n\n\n\n // The current rest\n\n println!(\"rest = {:?}\", rest);\n\n\n\n // Size of the current field\n\n println!(\"bit_size: {:?}\", bit_size);\n\n\n\n // read field_b, calling original func\n\n let (rest, value) = u8::read(rest, bit_size)?;\n\n\n\n // flip the bits on value if field_a is 0x01\n\n let value = if field_a == 0x01 { !value } else { value };\n\n\n\n Ok((rest, value))\n\n}\n\n\n", "file_path": "examples/custom_reader_and_writer.rs", "rank": 28, "score": 135210.2954500619 }, { "content": "fn test_assert_read(input: &[u8], expected: TestStruct) {\n\n let ret_read = TestStruct::try_from(input).unwrap();\n\n assert_eq!(expected, ret_read);\n\n}\n\n\n\n#[rstest(input, expected,\n\n case(TestStruct {\n\n field_a: 0x01,\n\n field_b: 0x02,\n\n }, hex!(\"0102\").to_vec()),\n\n\n\n #[should_panic(expected = r#\"Assertion(\"TestStruct.field_b field failed assertion: * field_a + * field_b >= 3\")\"#)]\n\n case(TestStruct {\n\n field_a: 0x01,\n\n field_b: 0x01,\n\n }, hex!(\"\").to_vec()),\n\n)]\n", "file_path": "tests/test_attributes/test_assert.rs", "rank": 29, "score": 135018.63785147655 }, { "content": "fn test_assert_eq_read(input: &[u8], expected: TestStruct) {\n\n let ret_read = TestStruct::try_from(input).unwrap();\n\n assert_eq!(expected, ret_read);\n\n}\n\n\n\n#[rstest(input, expected,\n\n case(TestStruct {\n\n field_a: 0x01,\n\n field_b: 0x01,\n\n }, hex!(\"0101\").to_vec()),\n\n\n\n #[should_panic(expected = r#\"Assertion(\"TestStruct.field_b field failed assertion: field_b == * field_a\")\"#)]\n\n case(TestStruct {\n\n field_a: 0x01,\n\n field_b: 0x02,\n\n }, hex!(\"\").to_vec()),\n\n)]\n", "file_path": "tests/test_attributes/test_assert_eq.rs", "rank": 30, "score": 130719.67398564714 }, { "content": "fn emit_bit_byte_offsets(\n\n fields: &[&Option<TokenStream>],\n\n) -> (Option<TokenStream>, Option<TokenStream>) {\n\n // determine if we should include `bit_offset` and `byte_offset`\n\n let byte_offset = if fields\n\n .iter()\n\n .any(|v| token_contains_string(v, \"__deku_byte_offset\"))\n\n {\n\n Some(quote! {\n\n let __deku_byte_offset = __deku_bit_offset / 8;\n\n })\n\n } else {\n\n None\n\n };\n\n\n\n let bit_offset = if fields\n\n .iter()\n\n .any(|v| token_contains_string(v, \"__deku_bit_offset\"))\n\n || byte_offset.is_some()\n\n {\n\n Some(quote! {\n\n let __deku_bit_offset = usize::try_from(unsafe { __deku_rest.as_bitptr().offset_from(__deku_input_bits.as_bitptr()) } )?;\n\n })\n\n } else {\n\n None\n\n };\n\n\n\n (bit_offset, byte_offset)\n\n}\n\n\n", "file_path": "deku-derive/src/macros/deku_read.rs", "rank": 31, "score": 126584.6622210603 }, { "content": "fn emit_struct(input: &DekuData) -> Result<TokenStream, syn::Error> {\n\n let crate_ = super::get_crate_name();\n\n let mut tokens = TokenStream::new();\n\n\n\n let DekuDataStruct {\n\n imp,\n\n wher,\n\n ident,\n\n fields,\n\n } = DekuDataStruct::try_from(input)?;\n\n\n\n let magic_write = emit_magic_write(input);\n\n\n\n let field_writes = emit_field_writes(input, &fields, None, &ident)?;\n\n let field_updates = emit_field_updates(&fields, Some(quote! { self. }));\n\n\n\n let named = fields.style.is_struct();\n\n\n\n let field_idents = fields\n\n .iter()\n", "file_path": "deku-derive/src/macros/deku_write.rs", "rank": 32, "score": 123582.9940729313 }, { "content": "fn emit_enum(input: &DekuData) -> Result<TokenStream, syn::Error> {\n\n let crate_ = super::get_crate_name();\n\n let mut tokens = TokenStream::new();\n\n\n\n let DekuDataEnum {\n\n imp,\n\n wher,\n\n variants,\n\n ident,\n\n id,\n\n id_type,\n\n id_args,\n\n } = DekuDataEnum::try_from(input)?;\n\n\n\n let magic_write = emit_magic_write(input);\n\n\n\n let mut variant_writes = vec![];\n\n let mut variant_updates = vec![];\n\n\n\n let has_discriminant = variants.iter().any(|v| v.discriminant.is_some());\n", "file_path": "deku-derive/src/macros/deku_write.rs", "rank": 33, "score": 123582.9940729313 }, { "content": "fn test_magic_struct(input: &[u8]) {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n #[deku(magic = b\"deku\")]\n\n struct TestStruct {}\n\n\n\n let ret_read = TestStruct::try_from(input).unwrap();\n\n\n\n assert_eq!(TestStruct {}, ret_read);\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(ret_write, input)\n\n}\n\n\n\n#[rstest(input,\n\n case(&hex!(\"64656b7500\")),\n\n\n\n #[should_panic(expected = \"Parse(\\\"Missing magic value [100, 101, 107, 117]\\\")\")]\n\n case(&hex!(\"64656bde00\")),\n\n\n\n #[should_panic(expected = \"Parse(\\\"Missing magic value [100, 101, 107, 117]\\\")\")]\n", "file_path": "tests/test_magic.rs", "rank": 34, "score": 121193.66477563062 }, { "content": "fn deku_write_enum(input: &DekuEnum) {\n\n let _v = input.to_bytes().unwrap();\n\n}\n\n\n", "file_path": "benches/deku.rs", "rank": 35, "score": 121193.66477563062 }, { "content": "fn deku_write_vec(input: &DekuVec) {\n\n let _v = input.to_bytes().unwrap();\n\n}\n\n\n", "file_path": "benches/deku.rs", "rank": 36, "score": 121193.66477563062 }, { "content": "fn test_magic_enum(input: &[u8]) {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n #[deku(magic = b\"deku\", type = \"u8\")]\n\n enum TestEnum {\n\n #[deku(id = \"0\")]\n\n Variant,\n\n }\n\n\n\n let ret_read = TestEnum::try_from(input).unwrap();\n\n\n\n assert_eq!(TestEnum::Variant, ret_read);\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(ret_write, input)\n\n}\n", "file_path": "tests/test_magic.rs", "rank": 37, "score": 121193.66477563062 }, { "content": "fn deku_write_byte(input: &DekuByte) {\n\n let _v = input.to_bytes().unwrap();\n\n}\n\n\n", "file_path": "benches/deku.rs", "rank": 38, "score": 121193.66477563062 }, { "content": "#[proc_macro_derive(DekuRead, attributes(deku))]\n\npub fn proc_deku_read(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n\n let input = match syn::parse(input) {\n\n Ok(input) => input,\n\n Err(err) => return err.to_compile_error().into(),\n\n };\n\n\n\n let receiver = match DekuReceiver::from_derive_input(&input) {\n\n Ok(receiver) => receiver,\n\n Err(err) => return err.write_errors().into(),\n\n };\n\n\n\n let data = match DekuData::from_receiver(receiver) {\n\n Ok(data) => data,\n\n Err(err) => return err.into(),\n\n };\n\n\n\n data.emit_reader().into()\n\n}\n\n\n\n/// Entry function for `DekuWrite` proc-macro\n", "file_path": "deku-derive/src/lib.rs", "rank": 39, "score": 121164.79417485403 }, { "content": "fn test_enum(input: &[u8], expected: TestEnum) {\n\n let ret_read = TestEnum::try_from(input).unwrap();\n\n assert_eq!(expected, ret_read);\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(input.to_vec(), ret_write);\n\n}\n\n\n", "file_path": "tests/test_enum.rs", "rank": 40, "score": 109942.13200270449 }, { "content": "#[test]\n\nfn test_pad_bytes_after() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n struct TestStruct {\n\n #[deku(pad_bytes_after = \"2\")]\n\n field_a: u8,\n\n field_b: u8,\n\n }\n\n\n\n let data: Vec<u8> = vec![0xAA, 0xBB, 0xCC, 0xDD];\n\n\n\n let ret_read = TestStruct::try_from(data.as_ref()).unwrap();\n\n\n\n assert_eq!(\n\n TestStruct {\n\n field_a: 0xAA,\n\n field_b: 0xDD,\n\n },\n\n ret_read\n\n );\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(vec![0xAA, 0x00, 0x00, 0xDD], ret_write);\n\n}\n\n\n", "file_path": "tests/test_attributes/test_padding/test_pad_bytes_after.rs", "rank": 41, "score": 108335.1741468942 }, { "content": "#[test]\n\nfn test_pad_bytes_before() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n struct TestStruct {\n\n field_a: u8,\n\n #[deku(pad_bytes_before = \"2\")]\n\n field_b: u8,\n\n }\n\n\n\n let data: Vec<u8> = vec![0xAA, 0xBB, 0xCC, 0xDD];\n\n\n\n let ret_read = TestStruct::try_from(data.as_ref()).unwrap();\n\n\n\n assert_eq!(\n\n TestStruct {\n\n field_a: 0xAA,\n\n field_b: 0xDD,\n\n },\n\n ret_read\n\n );\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(vec![0xAA, 0x00, 0x00, 0xDD], ret_write);\n\n}\n\n\n", "file_path": "tests/test_attributes/test_padding/test_pad_bytes_before.rs", "rank": 42, "score": 108335.1741468942 }, { "content": "#[test]\n\n#[should_panic(expected = \"Incomplete(NeedSize { bits: 24 })\")]\n\nfn test_pad_bytes_after_not_enough() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n struct TestStruct {\n\n field_a: u8,\n\n #[deku(pad_bytes_after = \"2 + 1\")]\n\n field_b: u8,\n\n }\n\n\n\n let data: Vec<u8> = vec![0xAA, 0xBB, 0xCC, 0xDD];\n\n\n\n let _ret_read = TestStruct::try_from(data.as_ref()).unwrap();\n\n}\n\n\n\n#[test]\n\n#[should_panic(\n\n expected = r#\"InvalidParam(\"Invalid padding param \\\"(((- 2) * 8))\\\": cannot convert to usize\")\"#\n\n)]\n", "file_path": "tests/test_attributes/test_padding/test_pad_bytes_after.rs", "rank": 43, "score": 106923.14247198563 }, { "content": "#[test]\n\n#[should_panic(expected = \"Incomplete(NeedSize { bits: 16 })\")]\n\nfn test_pad_bytes_before_not_enough() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n struct TestStruct {\n\n field_a: u8,\n\n #[deku(pad_bytes_before = \"2\")]\n\n field_b: u8,\n\n }\n\n\n\n let data: Vec<u8> = vec![0xAA];\n\n\n\n let _ret_read = TestStruct::try_from(data.as_ref()).unwrap();\n\n}\n\n\n\n#[test]\n\n#[should_panic(\n\n expected = r#\"InvalidParam(\"Invalid padding param \\\"(((- 2) * 8))\\\": cannot convert to usize\")\"#\n\n)]\n", "file_path": "tests/test_attributes/test_padding/test_pad_bytes_before.rs", "rank": 44, "score": 106923.14247198563 }, { "content": "fn test_enum_discriminant(input: &[u8], expected: TestEnumDiscriminant) {\n\n let ret_read = TestEnumDiscriminant::try_from(input).unwrap();\n\n assert_eq!(expected, ret_read);\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(input.to_vec(), ret_write);\n\n}\n\n\n", "file_path": "tests/test_enum.rs", "rank": 45, "score": 106605.48618787475 }, { "content": "fn emit_field_reads(\n\n input: &DekuData,\n\n fields: &Fields<&FieldData>,\n\n ident: &TokenStream,\n\n) -> Result<(Vec<FieldIdent>, Vec<TokenStream>), syn::Error> {\n\n let mut field_reads = vec![];\n\n let mut field_idents = vec![];\n\n\n\n for (i, f) in fields.iter().enumerate() {\n\n let (field_ident, field_read) = emit_field_read(input, i, f, ident)?;\n\n field_idents.push(FieldIdent {\n\n field_ident,\n\n is_temp: f.temp,\n\n });\n\n field_reads.push(field_read);\n\n }\n\n\n\n Ok((field_idents, field_reads))\n\n}\n\n\n", "file_path": "deku-derive/src/macros/deku_read.rs", "rank": 46, "score": 105715.10886415251 }, { "content": "fn emit_field_read(\n\n input: &DekuData,\n\n i: usize,\n\n f: &FieldData,\n\n ident: &TokenStream,\n\n) -> Result<(TokenStream, TokenStream), syn::Error> {\n\n let crate_ = super::get_crate_name();\n\n let field_type = &f.ty;\n\n\n\n let field_endian = f.endian.as_ref().or_else(|| input.endian.as_ref());\n\n\n\n let field_reader = &f.reader;\n\n\n\n // fields to check usage of bit/byte offset\n\n let field_check_vars = [\n\n &f.count,\n\n &f.bits_read,\n\n &f.bytes_read,\n\n &f.until,\n\n &f.cond,\n", "file_path": "deku-derive/src/macros/deku_read.rs", "rank": 47, "score": 105715.10886415251 }, { "content": "fn test_pad_bytes_after_write_err() {\n\n #[derive(PartialEq, Debug, DekuWrite)]\n\n struct TestStruct {\n\n #[deku(pad_bytes_after = \"-2\")]\n\n field_a: u8,\n\n field_b: u8,\n\n }\n\n\n\n let data = TestStruct {\n\n field_a: 0xAA,\n\n field_b: 0xDD,\n\n };\n\n\n\n let _ret_write: Vec<u8> = data.try_into().unwrap();\n\n}\n", "file_path": "tests/test_attributes/test_padding/test_pad_bytes_after.rs", "rank": 48, "score": 105550.54093168145 }, { "content": "fn test_pad_bytes_before_write_err() {\n\n #[derive(PartialEq, Debug, DekuWrite)]\n\n struct TestStruct {\n\n #[deku(pad_bytes_before = \"-2\")]\n\n field_a: u8,\n\n field_b: u8,\n\n }\n\n\n\n let data = TestStruct {\n\n field_a: 0xAA,\n\n field_b: 0xDD,\n\n };\n\n\n\n let _ret_write: Vec<u8> = data.try_into().unwrap();\n\n}\n", "file_path": "tests/test_attributes/test_padding/test_pad_bytes_before.rs", "rank": 49, "score": 105550.54093168145 }, { "content": "/// \"Reader\" trait: implemented on DekuRead struct and enum containers. A `container` is a type which\n\n/// doesn't need any context information.\n\npub trait DekuContainerRead<'a>: DekuRead<'a, ()> {\n\n /// Read bytes and construct type\n\n /// * **input** - Input given as data and bit offset\n\n ///\n\n /// Returns the remaining bytes and bit offset after parsing in addition to Self.\n\n fn from_bytes(input: (&'a [u8], usize)) -> Result<((&'a [u8], usize), Self), DekuError>\n\n where\n\n Self: Sized;\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 50, "score": 103864.50407593997 }, { "content": "#[wasm_bindgen]\n\npub fn deku_write(input: &DekuTest) -> Vec<u8> {\n\n input.to_bytes().unwrap()\n\n}\n", "file_path": "ensure_wasm/src/lib.rs", "rank": 51, "score": 103591.04964434702 }, { "content": "#[wasm_bindgen_test]\n\nfn test_read() {\n\n assert_eq!(\n\n DekuTest {\n\n field_a: 0b10101,\n\n field_b: 0b101,\n\n field_c: 0xBE\n\n },\n\n deku_read([0b10101_101, 0xBE].as_ref())\n\n )\n\n}\n\n\n", "file_path": "ensure_wasm/tests/deku.rs", "rank": 52, "score": 101591.42536641176 }, { "content": "fn test_assert_write(input: TestStruct, expected: Vec<u8>) {\n\n let ret_write: Vec<u8> = input.try_into().unwrap();\n\n assert_eq!(expected, ret_write);\n\n}\n", "file_path": "tests/test_attributes/test_assert.rs", "rank": 53, "score": 100582.20908992058 }, { "content": "fn main() {}\n", "file_path": "tests/test_compile/cases/unknown_endian.rs", "rank": 54, "score": 100158.07539011422 }, { "content": "fn bit_flipper_write(\n\n field_a: u8,\n\n field_b: u8,\n\n output: &mut BitVec<u8, Msb0>,\n\n bit_size: Size,\n\n) -> Result<(), DekuError> {\n\n // Access to previously written fields\n\n println!(\"field_a = 0x{:X}\", field_a);\n\n\n\n // value of field_b\n\n println!(\"field_b = 0x{:X}\", field_b);\n\n\n\n // Size of the current field\n\n println!(\"bit_size: {:?}\", bit_size);\n\n\n\n // flip the bits on value if field_a is 0x01\n\n let value = if field_a == 0x01 { !field_b } else { field_b };\n\n\n\n value.write(output, bit_size)\n\n}\n\n\n", "file_path": "examples/custom_reader_and_writer.rs", "rank": 55, "score": 99923.89712324954 }, { "content": "fn main() {}\n", "file_path": "tests/test_compile/cases/bits_bytes_conflict.rs", "rank": 56, "score": 97899.4997218458 }, { "content": "fn test_assert_eq_write(input: TestStruct, expected: Vec<u8>) {\n\n let ret_write: Vec<u8> = input.try_into().unwrap();\n\n assert_eq!(expected, ret_write);\n\n}\n", "file_path": "tests/test_attributes/test_assert_eq.rs", "rank": 57, "score": 97855.12831598106 }, { "content": "fn main() {}\n", "file_path": "tests/test_compile/cases/count_read_conflict.rs", "rank": 58, "score": 97446.56088747442 }, { "content": "#[test]\n\nfn test_enum_endian_ctx() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n #[deku(type = \"u32\", endian = \"endian\", ctx = \"endian: deku::ctx::Endian\")]\n\n enum EnumTypeEndianCtx {\n\n #[deku(id = \"0xDEADBEEF\")]\n\n VarA(u8),\n\n }\n\n\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n struct EnumTypeEndian {\n\n #[deku(endian = \"big\")]\n\n t: EnumTypeEndianCtx,\n\n }\n\n\n\n let test_data = [0xdeu8, 0xad, 0xbe, 0xef, 0xff];\n\n let ret_read = EnumTypeEndian::try_from(test_data.as_ref()).unwrap();\n\n\n\n assert_eq!(\n\n EnumTypeEndian {\n\n t: EnumTypeEndianCtx::VarA(0xFF)\n\n },\n\n ret_read\n\n );\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(ret_write, test_data)\n\n}\n", "file_path": "tests/test_attributes/test_ctx.rs", "rank": 59, "score": 96209.5309216364 }, { "content": "fn emit_bit_byte_offsets(\n\n fields: &[&Option<TokenStream>],\n\n) -> (Option<TokenStream>, Option<TokenStream>) {\n\n // determine if we should include `bit_offset` and `byte_offset`\n\n let byte_offset = if fields\n\n .iter()\n\n .any(|v| token_contains_string(v, \"__deku_byte_offset\"))\n\n {\n\n Some(quote! {\n\n let __deku_byte_offset = __deku_bit_offset / 8;\n\n })\n\n } else {\n\n None\n\n };\n\n\n\n let bit_offset = if fields\n\n .iter()\n\n .any(|v| token_contains_string(v, \"__deku_bit_offset\"))\n\n || byte_offset.is_some()\n\n {\n\n Some(quote! {\n\n let __deku_bit_offset = __deku_output.len();\n\n })\n\n } else {\n\n None\n\n };\n\n\n\n (bit_offset, byte_offset)\n\n}\n\n\n", "file_path": "deku-derive/src/macros/deku_write.rs", "rank": 60, "score": 94181.53407332036 }, { "content": "#[proc_macro_derive(DekuWrite, attributes(deku))]\n\npub fn proc_deku_write(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n\n let input = match syn::parse(input) {\n\n Ok(input) => input,\n\n Err(err) => return err.to_compile_error().into(),\n\n };\n\n\n\n let receiver = match DekuReceiver::from_derive_input(&input) {\n\n Ok(receiver) => receiver,\n\n Err(err) => return err.write_errors().into(),\n\n };\n\n\n\n let data = match DekuData::from_receiver(receiver) {\n\n Ok(data) => data,\n\n Err(err) => return err.into(),\n\n };\n\n\n\n data.emit_writer().into()\n\n}\n\n\n", "file_path": "deku-derive/src/lib.rs", "rank": 61, "score": 93946.4673588481 }, { "content": "fn apply_replacements(input: &syn::LitStr) -> Result<syn::LitStr, ReplacementError> {\n\n if input.value().contains(\"__deku_\") {\n\n return Err(darling::Error::unsupported_format(\n\n \"attribute cannot contain `__deku_` these are internal variables. Please use the `deku::` instead.\"\n\n )) .map_err(|e| e.with_span(&input).write_errors());\n\n }\n\n\n\n let input_str = input\n\n .value()\n\n .replace(\"deku::input\", \"__deku_input\") // part of the public API `from_bytes`\n\n .replace(\"deku::input_bits\", \"__deku_input_bits\") // part of the public API `read`\n\n .replace(\"deku::output\", \"__deku_output\") // part of the public API `write`\n\n .replace(\"deku::rest\", \"__deku_rest\")\n\n .replace(\"deku::bit_offset\", \"__deku_bit_offset\")\n\n .replace(\"deku::byte_offset\", \"__deku_byte_offset\");\n\n\n\n Ok(syn::LitStr::new(&input_str, input.span()))\n\n}\n\n\n", "file_path": "deku-derive/src/lib.rs", "rank": 62, "score": 92887.34756990612 }, { "content": "/// emit `from_bytes()` for struct/enum\n\npub fn emit_from_bytes(\n\n imp: &syn::ImplGenerics,\n\n lifetime: &TokenStream,\n\n ident: &TokenStream,\n\n wher: Option<&syn::WhereClause>,\n\n body: TokenStream,\n\n) -> TokenStream {\n\n let crate_ = super::get_crate_name();\n\n quote! {\n\n impl #imp ::#crate_::DekuContainerRead<#lifetime> for #ident #wher {\n\n #[allow(non_snake_case)]\n\n fn from_bytes(__deku_input: (&#lifetime [u8], usize)) -> Result<((&#lifetime [u8], usize), Self), ::#crate_::DekuError> {\n\n #body\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "deku-derive/src/macros/deku_read.rs", "rank": 63, "score": 92864.07825930962 }, { "content": "/// emit `TryFrom` trait for struct/enum\n\npub fn emit_try_from(\n\n imp: &syn::ImplGenerics,\n\n lifetime: &TokenStream,\n\n ident: &TokenStream,\n\n wher: Option<&syn::WhereClause>,\n\n) -> TokenStream {\n\n let crate_ = super::get_crate_name();\n\n quote! {\n\n impl #imp core::convert::TryFrom<&#lifetime [u8]> for #ident #wher {\n\n type Error = ::#crate_::DekuError;\n\n\n\n fn try_from(input: &#lifetime [u8]) -> Result<Self, Self::Error> {\n\n let (rest, res) = Self::from_bytes((input, 0))?;\n\n if !rest.0.is_empty() {\n\n return Err(::#crate_::DekuError::Parse(format!(\"Too much data\")));\n\n }\n\n Ok(res)\n\n }\n\n }\n\n }\n\n}\n", "file_path": "deku-derive/src/macros/deku_read.rs", "rank": 64, "score": 92864.07825930962 }, { "content": "/// Calls apply replacements on Option<LitStr>\n\nfn map_option_litstr(input: Option<syn::LitStr>) -> Result<Option<syn::LitStr>, ReplacementError> {\n\n Ok(match input {\n\n Some(v) => Some(apply_replacements(&v)?),\n\n None => None,\n\n })\n\n}\n\n\n", "file_path": "deku-derive/src/lib.rs", "rank": 65, "score": 85319.71251425079 }, { "content": "#[derive(DekuRead)]\n\nstruct Test4(#[deku(bits = \"7\", bytes = \"8\")] u8);\n\n\n", "file_path": "tests/test_compile/cases/bits_bytes_conflict.rs", "rank": 66, "score": 84818.44688535566 }, { "content": "use deku::prelude::*;\n\nuse std::convert::{TryFrom, TryInto};\n\n\n\n#[test]\n", "file_path": "tests/test_attributes/test_padding/test_pad_bits_before.rs", "rank": 67, "score": 79674.0881958592 }, { "content": "use deku::prelude::*;\n\nuse std::convert::{TryFrom, TryInto};\n\n\n\n#[test]\n", "file_path": "tests/test_attributes/test_padding/test_pad_bits_after.rs", "rank": 68, "score": 79674.0881958592 }, { "content": "/// avoid outputing `use core::convert::TryInto` if update() function is generated with empty Vec\n\nfn check_update_use<T>(vec: &[T]) -> TokenStream {\n\n if !vec.is_empty() {\n\n quote! {use core::convert::TryInto;}\n\n } else {\n\n quote! {}\n\n }\n\n}\n", "file_path": "deku-derive/src/macros/deku_write.rs", "rank": 69, "score": 79653.17048680317 }, { "content": "/// Returns true if the literal substring `s` is in the token\n\nfn token_contains_string(tok: &Option<TokenStream>, s: &str) -> bool {\n\n tok.as_ref()\n\n .map(|v| {\n\n let v = v.to_string();\n\n v.contains(s)\n\n })\n\n .unwrap_or(false)\n\n}\n\n\n", "file_path": "deku-derive/src/macros/mod.rs", "rank": 70, "score": 76993.60021211785 }, { "content": "/// Generate endian tokens from string: `big` -> `Endian::Big`.\n\nfn gen_endian_from_str(s: &syn::LitStr) -> syn::Result<TokenStream> {\n\n let crate_ = get_crate_name();\n\n match s.value().as_str() {\n\n \"little\" => Ok(quote! {::#crate_::ctx::Endian::Little}),\n\n \"big\" => Ok(quote! {::#crate_::ctx::Endian::Big}),\n\n _ => {\n\n // treat as variable, possibly from `ctx`\n\n let v: TokenStream = s.value().parse()?;\n\n Ok(quote! {#v})\n\n }\n\n }\n\n}\n\n\n", "file_path": "deku-derive/src/macros/mod.rs", "rank": 71, "score": 75554.42651751175 }, { "content": " data: test_data.as_ref()\n\n },\n\n ret_read\n\n );\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(test_data, ret_write);\n\n }\n\n\n\n #[rstest(input_bits,\n\n #[should_panic(expected = \"Incomplete(NeedSize { bits: 8 })\")]\n\n case(15),\n\n\n\n case(16),\n\n\n\n #[should_panic(expected = \"Incomplete(NeedSize { bits: 8 })\")]\n\n case(17),\n\n )]\n\n fn test_bits_read_from_field(input_bits: u8) {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n", "file_path": "tests/test_attributes/test_limits/test_bits_read.rs", "rank": 72, "score": 69013.87355283786 }, { "content": " // thus resulting in a single u16 element\n\n data: vec![0xBBAA]\n\n },\n\n ret_read\n\n );\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(test_data, ret_write);\n\n }\n\n\n\n #[rstest(input_bits,\n\n #[should_panic(expected = \"Incomplete(NeedSize { bits: 16 })\")]\n\n case(15),\n\n\n\n case(16),\n\n\n\n #[should_panic(expected = \"Incomplete(NeedSize { bits: 16 })\")]\n\n case(17),\n\n )]\n\n fn test_bits_read_from_field(input_bits: u8) {\n", "file_path": "tests/test_attributes/test_limits/test_bits_read.rs", "rank": 73, "score": 69013.40490191353 }, { "content": " struct TestStruct<'a> {\n\n bits: u8,\n\n\n\n #[deku(bits_read = \"bits\")]\n\n data: &'a [u8],\n\n }\n\n\n\n let test_data: Vec<u8> = [input_bits, 0xAA, 0xBB].to_vec();\n\n\n\n let ret_read = TestStruct::try_from(test_data.as_ref()).unwrap();\n\n assert_eq!(\n\n TestStruct {\n\n bits: 16,\n\n data: &test_data[1..]\n\n },\n\n ret_read\n\n );\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(test_data, ret_write);\n", "file_path": "tests/test_attributes/test_limits/test_bits_read.rs", "rank": 74, "score": 69009.80426532686 }, { "content": "use deku::prelude::*;\n\nuse rstest::rstest;\n\nuse std::convert::{TryFrom, TryInto};\n\n\n\nmod test_slice {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_bits_read_static() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n struct TestStruct<'a> {\n\n #[deku(bits_read = \"16\")]\n\n data: &'a [u8],\n\n }\n\n\n\n let test_data: Vec<u8> = [0xAA, 0xBB].to_vec();\n\n\n\n let ret_read = TestStruct::try_from(test_data.as_ref()).unwrap();\n\n assert_eq!(\n\n TestStruct {\n", "file_path": "tests/test_attributes/test_limits/test_bits_read.rs", "rank": 75, "score": 69009.56307696438 }, { "content": " #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n struct TestStruct {\n\n bits: u8,\n\n\n\n #[deku(endian = \"little\", bits_read = \"bits\")]\n\n data: Vec<u16>,\n\n }\n\n\n\n let test_data: Vec<u8> = [input_bits, 0xAA, 0xBB].to_vec();\n\n\n\n let ret_read = TestStruct::try_from(test_data.as_ref()).unwrap();\n\n assert_eq!(\n\n TestStruct {\n\n bits: 16,\n\n\n\n // We should read 16 bits, not 16 elements,\n\n // thus resulting in a single u16 element\n\n data: vec![0xBBAA]\n\n },\n\n ret_read\n\n );\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(test_data, ret_write);\n\n }\n\n}\n", "file_path": "tests/test_attributes/test_limits/test_bits_read.rs", "rank": 76, "score": 69009.14341618835 }, { "content": " }\n\n}\n\n\n\nmod test_vec {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_bits_read_static() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n struct TestStruct {\n\n #[deku(endian = \"little\", bits_read = \"16\")]\n\n data: Vec<u16>,\n\n }\n\n\n\n let test_data: Vec<u8> = [0xAA, 0xBB].to_vec();\n\n\n\n let ret_read = TestStruct::try_from(test_data.as_ref()).unwrap();\n\n assert_eq!(\n\n TestStruct {\n\n // We should read 16 bits, not 16 elements,\n", "file_path": "tests/test_attributes/test_limits/test_bits_read.rs", "rank": 77, "score": 69008.75700342901 }, { "content": "fn main() {\n\n let test_data = hex!(\"4500004b0f490000801163a591fea0ed91fd02cb\").to_vec();\n\n\n\n let ip_header = Ipv4Header::try_from(test_data.as_ref()).unwrap();\n\n\n\n assert_eq!(\n\n Ipv4Header {\n\n version: 4,\n\n ihl: 5,\n\n ecn: 0,\n\n dscp: 0,\n\n length: 75,\n\n identification: 0x0f49,\n\n flags: 0,\n\n offset: 0,\n\n ttl: 128,\n\n protocol: 17,\n\n checksum: 0x63a5,\n\n src: Ipv4Addr::new(145, 254, 160, 237),\n\n dst: Ipv4Addr::new(145, 253, 2, 203),\n\n },\n\n ip_header\n\n );\n\n\n\n let ip_header_data: Vec<u8> = ip_header.try_into().unwrap();\n\n\n\n assert_eq!(test_data, ip_header_data);\n\n}\n", "file_path": "examples/ipv4.rs", "rank": 78, "score": 68818.49743528545 }, { "content": "fn main() {\n\n let test_data: &[u8] = [\n\n 0xAB,\n\n 0b1010010_1,\n\n 0xAB,\n\n 0xCD,\n\n 0b1100_0110,\n\n 0x02,\n\n 0xBE,\n\n 0xEF,\n\n 0xC0,\n\n 0xFE,\n\n ]\n\n .as_ref();\n\n\n\n let test_deku = DekuTest::try_from(test_data).unwrap();\n\n\n\n assert_eq!(\n\n DekuTest {\n\n field_a: 0xAB,\n", "file_path": "examples/example.rs", "rank": 79, "score": 68818.49743528545 }, { "content": "fn main() {\n\n let test_data = hex!(\"03020102\").to_vec();\n\n\n\n let deku_test = DekuTest::try_from(test_data.as_ref()).unwrap();\n\n\n\n assert_eq!(\n\n DekuTest::Var4 {\n\n field_a: 0x02,\n\n field_b: vec![0x01, 0x02]\n\n },\n\n deku_test\n\n );\n\n\n\n let ret_out: Vec<u8> = deku_test.to_bytes().unwrap();\n\n\n\n assert_eq!(test_data, ret_out);\n\n\n\n let id_first_byte = deku_test.deku_id();\n\n assert_eq!(Ok(test_data[0]), id_first_byte);\n\n}\n", "file_path": "examples/enums.rs", "rank": 80, "score": 68818.49743528545 }, { "content": "/// Generate field name which supports both un-named/named structs/enums\n\n/// `ident` is Some if the container has named fields\n\n/// `index` is the numerical index of the current field used in un-named containers\n\n/// `prefix` is true in the case of variable declarations and match arms,\n\n/// false when the raw field is required, for example a field access\n\nfn gen_field_ident<T: ToString>(ident: Option<T>, index: usize, prefix: bool) -> TokenStream {\n\n let field_name = match ident {\n\n Some(field_name) => field_name.to_string(),\n\n None => {\n\n let index = syn::Index::from(index);\n\n let prefix = if prefix { \"field_\" } else { \"\" };\n\n format!(\"{}{}\", prefix, quote! { #index })\n\n }\n\n };\n\n\n\n field_name.parse().unwrap()\n\n}\n\n\n\n/// Provided default when a attribute is not available\n", "file_path": "deku-derive/src/lib.rs", "rank": 81, "score": 68073.56577819452 }, { "content": "#[test]\n\nfn issue_224() {\n\n #[derive(Debug, PartialEq, DekuRead, DekuWrite)]\n\n pub struct Packet {\n\n pub data: Data,\n\n }\n\n\n\n #[derive(Debug, PartialEq, DekuRead, DekuWrite)]\n\n pub struct Data {\n\n pub one: One,\n\n pub two: Two,\n\n }\n\n\n\n #[derive(Debug, PartialEq, DekuRead, DekuWrite)]\n\n #[deku(type = \"u8\", bits = \"2\")]\n\n pub enum One {\n\n Start = 0,\n\n Go = 1,\n\n Stop = 2,\n\n }\n\n\n", "file_path": "tests/test_regression.rs", "rank": 82, "score": 67543.17469368767 }, { "content": "#[derive(DekuRead, DekuWrite)]\n\nstruct TestBitRead {\n\n field_a: u8,\n\n #[deku(bits_read = \"deku::bit_offset\")]\n\n field_b: Vec<u8>\n\n}\n\n\n", "file_path": "tests/test_compile/cases/internal_variables.rs", "rank": 83, "score": 67064.99505692905 }, { "content": "fn main() {\n\n let test_data: &[u8] = [0x01, 0b1001_0110].as_ref();\n\n\n\n let (_rest, ret_read) = DekuTest::from_bytes((test_data, 0)).unwrap();\n\n\n\n assert_eq!(\n\n ret_read,\n\n DekuTest {\n\n field_a: 0x01,\n\n field_b: 0b0110_1001\n\n }\n\n );\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(test_data.to_vec(), ret_write);\n\n}\n", "file_path": "examples/custom_reader_and_writer.rs", "rank": 84, "score": 66348.2759604709 }, { "content": "#[test]\n\nfn test_from_bytes_struct() {\n\n #[derive(Debug, PartialEq, DekuRead, DekuWrite)]\n\n struct TestDeku(#[deku(bits = 4)] u8);\n\n\n\n let test_data: Vec<u8> = [0b0110_0110u8, 0b0101_1010u8].to_vec();\n\n\n\n let ((rest, i), ret_read) = TestDeku::from_bytes((&test_data, 0)).unwrap();\n\n assert_eq!(TestDeku(0b0110), ret_read);\n\n assert_eq!(2, rest.len());\n\n assert_eq!(4, i);\n\n\n\n let ((rest, i), ret_read) = TestDeku::from_bytes((&rest, i)).unwrap();\n\n assert_eq!(TestDeku(0b0110), ret_read);\n\n assert_eq!(1, rest.len());\n\n assert_eq!(0, i);\n\n\n\n let ((rest, i), ret_read) = TestDeku::from_bytes((&rest, i)).unwrap();\n\n assert_eq!(TestDeku(0b0101), ret_read);\n\n assert_eq!(1, rest.len());\n\n assert_eq!(4, i);\n\n\n\n let ((rest, i), ret_read) = TestDeku::from_bytes((&rest, i)).unwrap();\n\n assert_eq!(TestDeku(0b1010), ret_read);\n\n assert_eq!(0, rest.len());\n\n assert_eq!(0, i);\n\n}\n\n\n", "file_path": "tests/test_from_bytes.rs", "rank": 85, "score": 65226.42626380936 }, { "content": "#[test]\n\nfn test_regular() {\n\n #[derive(Debug, DekuRead, DekuWrite)]\n\n #[deku(type = \"u8\")]\n\n enum Request1 {\n\n #[deku(id = \"0x01\")]\n\n Cats { toy: u8 },\n\n\n\n #[deku(id = \"0x10\")]\n\n Dogs { ball: u8 },\n\n }\n\n\n\n assert_eq!(Ok(0x01), Request1::Cats { toy: 0 }.deku_id());\n\n assert_eq!(Ok(0x10), Request1::Dogs { ball: 0 }.deku_id());\n\n}\n\n\n", "file_path": "tests/test_deku_id.rs", "rank": 86, "score": 65226.42626380936 }, { "content": "#[test]\n\nfn test_slice_struct() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n struct TestStruct<'a> {\n\n #[deku(count = \"2\")]\n\n field_a: &'a [u8],\n\n }\n\n\n\n let test_data: Vec<u8> = [0x01, 0x02].to_vec();\n\n\n\n let ret_read = TestStruct::try_from(test_data.as_ref()).unwrap();\n\n assert_eq!(\n\n TestStruct {\n\n field_a: test_data.as_ref()\n\n },\n\n ret_read\n\n );\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(test_data, ret_write);\n\n}\n", "file_path": "tests/test_generic.rs", "rank": 87, "score": 65226.42626380936 }, { "content": "#[test]\n\nfn test_ctx() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n #[deku(ctx = \"my_id: u8\", id = \"my_id\")]\n\n enum EnumId {\n\n #[deku(id = \"1\")]\n\n VarA(u8),\n\n #[deku(id = \"2\")]\n\n VarB,\n\n }\n\n\n\n assert_eq!(Ok(1), EnumId::VarA(0).deku_id());\n\n\n\n #[derive(Copy, Clone, PartialEq, Debug, DekuRead, DekuWrite)]\n\n #[deku(type = \"u8\")]\n\n enum Nice {\n\n True = 0x00,\n\n False = 0x01,\n\n }\n\n\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n", "file_path": "tests/test_deku_id.rs", "rank": 88, "score": 65226.42626380936 }, { "content": "#[test]\n\n#[cfg(not(tarpaulin))]\n\n#[cfg_attr(miri, ignore)]\n\nfn test_compile() {\n\n let t = trybuild::TestCases::new();\n\n t.compile_fail(\"tests/test_compile/cases/*.rs\");\n\n}\n", "file_path": "tests/test_compile/mod.rs", "rank": 89, "score": 65226.42626380936 }, { "content": "#[test]\n\nfn test_generic_enum() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n #[deku(type = \"u8\")]\n\n enum TestEnum<T>\n\n where\n\n T: deku::DekuWrite + for<'a> deku::DekuRead<'a>,\n\n {\n\n #[deku(id = \"1\")]\n\n VariantT(T),\n\n }\n\n\n\n let test_data: Vec<u8> = [0x01, 0x02].to_vec();\n\n\n\n let ret_read = TestEnum::<u8>::try_from(test_data.as_ref()).unwrap();\n\n assert_eq!(TestEnum::<u8>::VariantT(0x02), ret_read);\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(test_data, ret_write);\n\n}\n\n\n", "file_path": "tests/test_generic.rs", "rank": 90, "score": 65226.42626380936 }, { "content": "#[test]\n\n#[should_panic(expected = \"Parse(\\\"Could not match enum variant id = 2 on enum `TestEnum`\\\")\")]\n\nfn test_enum_error() {\n\n #[derive(DekuRead)]\n\n #[deku(type = \"u8\")]\n\n enum TestEnum {\n\n #[deku(id = \"1\")]\n\n VarA(u8),\n\n }\n\n\n\n let test_data: Vec<u8> = [0x02, 0x02].to_vec();\n\n let _ret_read = TestEnum::try_from(test_data.as_ref()).unwrap();\n\n}\n\n\n", "file_path": "tests/test_enum.rs", "rank": 91, "score": 65226.42626380936 }, { "content": "#[test]\n\nfn test_generic_struct() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n struct TestStruct<T>\n\n where\n\n T: deku::DekuWrite + for<'a> deku::DekuRead<'a>,\n\n {\n\n field_a: T,\n\n }\n\n\n\n let test_data: Vec<u8> = [0x01].to_vec();\n\n\n\n let ret_read = TestStruct::<u8>::try_from(test_data.as_ref()).unwrap();\n\n assert_eq!(TestStruct::<u8> { field_a: 0x01 }, ret_read);\n\n\n\n let ret_write: Vec<u8> = ret_read.try_into().unwrap();\n\n assert_eq!(test_data, ret_write);\n\n}\n\n\n", "file_path": "tests/test_generic.rs", "rank": 92, "score": 65226.42626380936 }, { "content": "#[test]\n\nfn test_unnamed_struct() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n pub struct TestUnamedStruct(\n\n pub u8,\n\n #[deku(bits = \"2\")] pub u8,\n\n #[deku(bits = \"6\")] pub u8,\n\n #[deku(bytes = \"2\")] pub u16,\n\n #[deku(endian = \"big\")] pub u16,\n\n pub NestedDeku,\n\n #[deku(update = \"self.7.len()\")] pub u8,\n\n #[deku(count = \"field_6\")] pub Vec<u8>,\n\n );\n\n\n\n let test_data: Vec<u8> = [\n\n 0xFF,\n\n 0b1001_0110,\n\n 0xAA,\n\n 0xBB,\n\n 0xCC,\n\n 0xDD,\n", "file_path": "tests/test_struct.rs", "rank": 93, "score": 65226.42626380936 }, { "content": "#[test]\n\nfn test_named_struct() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n pub struct TestStruct {\n\n pub field_a: u8,\n\n #[deku(bits = \"2\")]\n\n pub field_b: u8,\n\n #[deku(bits = \"6\")]\n\n pub field_c: u8,\n\n #[deku(bytes = \"2\")]\n\n pub field_d: u16,\n\n #[deku(update = \"1+self.field_d\")]\n\n #[deku(endian = \"big\")]\n\n pub field_e: u16,\n\n pub field_f: NestedDeku,\n\n pub vec_len: u8,\n\n #[deku(count = \"vec_len\")]\n\n pub vec_data: Vec<u8>,\n\n }\n\n\n\n let test_data: Vec<u8> = [\n", "file_path": "tests/test_struct.rs", "rank": 94, "score": 65226.42626380936 }, { "content": "#[wasm_bindgen_test]\n\nfn test_write() {\n\n assert_eq!(\n\n vec![0b10101_101, 0xBE],\n\n DekuTest {\n\n field_a: 0b10101,\n\n field_b: 0b101,\n\n field_c: 0xBE\n\n }\n\n .to_bytes()\n\n .unwrap()\n\n )\n\n}\n", "file_path": "ensure_wasm/tests/deku.rs", "rank": 95, "score": 65226.42626380936 }, { "content": "#[test]\n\nfn test_from_bytes_enum() {\n\n #[derive(Debug, PartialEq, DekuRead, DekuWrite)]\n\n #[deku(type = \"u8\", bits = \"4\")]\n\n enum TestDeku {\n\n #[deku(id = \"0b0110\")]\n\n VariantA(#[deku(bits = \"4\")] u8),\n\n #[deku(id = \"0b0101\")]\n\n VariantB(#[deku(bits = \"2\")] u8),\n\n }\n\n\n\n let test_data: Vec<u8> = [0b0110_0110u8, 0b0101_1010u8].to_vec();\n\n\n\n let ((rest, i), ret_read) = TestDeku::from_bytes((&test_data, 0)).unwrap();\n\n assert_eq!(TestDeku::VariantA(0b0110), ret_read);\n\n assert_eq!(1, rest.len());\n\n assert_eq!(0, i);\n\n\n\n let ((rest, i), ret_read) = TestDeku::from_bytes((&rest, i)).unwrap();\n\n assert_eq!(TestDeku::VariantB(0b10), ret_read);\n\n assert_eq!(1, rest.len());\n\n assert_eq!(6, i);\n\n assert_eq!(0b0101_1010u8, rest[0]);\n\n}\n", "file_path": "tests/test_from_bytes.rs", "rank": 96, "score": 65226.42626380936 }, { "content": "#[test]\n\nfn test_litbytestr() {\n\n #[derive(PartialEq, Debug, DekuRead, DekuWrite)]\n\n #[deku(type = \"[u8; 3]\")]\n\n enum TestEnumArray {\n\n #[deku(id = b\"123\")]\n\n VarA,\n\n #[deku(id = \"[1,1,1]\")]\n\n VarB,\n\n }\n\n\n\n assert_eq!(b\"123\", TestEnumArray::VarA.deku_id().unwrap().as_ref());\n\n}\n\n\n", "file_path": "tests/test_deku_id.rs", "rank": 97, "score": 65226.42626380936 }, { "content": "#[test]\n\n#[should_panic(expected = \"called `Result::unwrap()` on an `Err` value: IdVariantNotFound\")]\n\nfn test_no_id_discriminant() {\n\n #[derive(Debug, DekuRead, PartialEq, DekuWrite)]\n\n #[deku(type = \"u8\")]\n\n enum Discriminant {\n\n Cats = 0x01,\n\n Dogs,\n\n }\n\n Discriminant::Dogs.deku_id().unwrap();\n\n}\n", "file_path": "tests/test_deku_id.rs", "rank": 98, "score": 64175.27628129335 }, { "content": "/// Parse a TokenStream from an Option<LitStr>\n\n/// Also replaces any namespaced variables to internal variables found in `input`\n\nfn map_litstr_as_tokenstream(\n\n input: Option<syn::LitStr>,\n\n) -> Result<Option<TokenStream>, ReplacementError> {\n\n Ok(match input {\n\n Some(v) => {\n\n let v = apply_replacements(&v)?;\n\n Some(\n\n v.parse::<TokenStream>()\n\n .expect(\"could not parse token stream\"),\n\n )\n\n }\n\n None => None,\n\n })\n\n}\n\n\n", "file_path": "deku-derive/src/lib.rs", "rank": 99, "score": 64175.05183661128 } ]
Rust
src/main.rs
pmalmgren/pongbrickbreaker
708bee1059243ea43af39418dac04eeca8034275
use ncurses::CURSOR_VISIBILITY::CURSOR_INVISIBLE; use ncurses::*; use std::char; use std::process; use std::{thread, time}; use std::cmp; use std::time::{SystemTime, UNIX_EPOCH}; use std::convert::TryFrom; const PADDLE_WIDTH: i32 = 12; const NUM_ROWS: i32 = 4; const BRICKS_PER_ROW: i32 = 6; enum Direction { Left, Right, Down, Up, Still, } impl Direction { fn vel(&self) -> Point { match self { Direction::Left => Point { x: -1, y: 0 }, Direction::Right => Point { x: 1, y: 0 }, Direction::Up => Point { x: 0, y: -1 }, Direction::Down => Point { x: 0, y: 1 }, Direction::Still => Point { x: 0, y: 0 }, } } } struct Point { x: i32, y: i32, } impl Point { fn will_collide(&self, bounds: &Bounds, direction: &Direction) -> bool { let vel = direction.vel(); (self.y + vel.y) == bounds.max_y && (self.x + vel.x) <= bounds.max_x && (self.x + vel.x) >= bounds.min_x } fn will_collide_with_any(&self, bounds: &Vec<Bounds>, direction: &Direction) -> Option<usize> { for (idx, bound) in bounds.iter().enumerate() { if self.will_collide(bound, direction) { return Some(idx); } } None } fn move_dir(&mut self, direction: &Direction) { let vel = direction.vel(); self.x += vel.x; self.y += vel.y; } } #[allow(dead_code)] struct Bounds { min_x: i32, min_y: i32, max_x: i32, max_y: i32, } enum MoveResult { HitPaddleCenter, HitPaddleLeft, HitPaddleRight, HitWallLeftRight, HitWallBottom, HitWallTop, HitBrick(Direction, usize), } struct GameObject { pos: Point, vel: Point, disp_char: u32, width: i32, } impl GameObject { fn get_bounds(&self) -> Bounds { let left_edge = self.pos.x - (self.width / 2); let right_edge = self.pos.x + (self.width / 2); Bounds { min_x: left_edge, max_x: right_edge, min_y: self.pos.y, max_y: self.pos.y } } fn do_move1(&mut self, bricks: &Vec<Bounds>, dir: Direction) -> Option<MoveResult> { match self.pos.will_collide_with_any(bricks, &dir) { Some(idx) => Some(MoveResult::HitBrick(dir, idx)), None => { self.pos.move_dir(&dir); None } } } fn move1(&mut self, direction: Direction, bounds: &Bounds, paddle_bounds: &Bounds, bricks: &Vec<Bounds>) -> Option<MoveResult> { let left_edge = self.pos.x - (self.width / 2); let right_edge = self.pos.x + (self.width / 2); return match direction { Direction::Left => { if left_edge <= 1 { return Some(MoveResult::HitWallLeftRight); } self.do_move1(bricks, direction) }, Direction::Right => { if right_edge >= (bounds.max_x - 2) { return Some(MoveResult::HitWallLeftRight) } self.do_move1(bricks, direction) }, Direction::Up => { if self.pos.y <= 1 { return Some(MoveResult::HitWallTop); } self.do_move1(bricks, direction) }, Direction::Down => { if self.pos.y >= (bounds.max_y - 2) { return Some(MoveResult::HitWallBottom) } if self.pos.will_collide(paddle_bounds, &Direction::Down) { let third = PADDLE_WIDTH / 3; if self.pos.x < (paddle_bounds.min_x + third) { return Some(MoveResult::HitPaddleLeft); } if self.pos.x < (paddle_bounds.min_x + (2 * third)) { return Some(MoveResult::HitPaddleCenter); } return Some(MoveResult::HitPaddleRight); } self.do_move1(bricks, direction) }, Direction::Still => None, } } fn float(&mut self, screen_bounds: &Bounds, paddle_bounds: &Bounds, brick_bounds: &Vec<Bounds>) -> Result<Option<usize>, String> { let mut hit_brick: Option<usize> = None; let mut lost: bool = false; let x_collision: Option<MoveResult> = match self.vel.x { x if x < 0 => self.move1(Direction::Left, screen_bounds, paddle_bounds, brick_bounds), x if x > 0 => self.move1(Direction::Right, screen_bounds, paddle_bounds, brick_bounds), _ => None, }; let y_collision: Option<MoveResult> = match self.vel.y { y if y > 0 => self.move1(Direction::Down, screen_bounds, paddle_bounds, brick_bounds), y if y < 0 => self.move1(Direction::Up, screen_bounds, paddle_bounds, brick_bounds), _ => None, }; match y_collision { Some(MoveResult::HitPaddleCenter) => { self.vel.y = -self.vel.y; self.vel.x = 0; }, Some(MoveResult::HitPaddleLeft) => { self.vel.x = -1; self.vel.y = -self.vel.y; }, Some(MoveResult::HitPaddleRight) => { self.vel.x = 1; self.vel.y = -self.vel.y; }, Some(MoveResult::HitWallTop) => self.vel.y = -self.vel.y, Some(MoveResult::HitWallBottom) => { self.vel.x = 0; self.vel.y = 0; lost = true; }, Some(MoveResult::HitBrick(Direction::Down, brick_idx)) => { self.vel.y = -self.vel.y; hit_brick = Some(brick_idx); }, Some(MoveResult::HitBrick(Direction::Up, brick_idx)) => { self.vel.y = -self.vel.y; hit_brick = Some(brick_idx); }, _ => (), }; match x_collision { Some(MoveResult::HitBrick(Direction::Left, brick_idx)) => { if !hit_brick.is_some() { self.vel.x = -self.vel.x; hit_brick = Some(brick_idx); } }, Some(MoveResult::HitBrick(Direction::Right, brick_idx)) => { if !hit_brick.is_some() { self.vel.x = -self.vel.x; hit_brick = Some(brick_idx); } }, Some(MoveResult::HitWallLeftRight) => self.vel.x = -self.vel.x, Some(_collision) => self.vel.x = -self.vel.x, None => (), }; if lost { return Err("Player has lost.".to_string()); } Ok(hit_brick) } fn draw(&self) { let start = self.pos.x - self.width / 2; let end = self.pos.x + (self.width / 2); for x in start..cmp::max(end, start+1) { mvaddch(self.pos.y, x, self.disp_char); } } fn clear(&self) { let start = self.pos.x - self.width / 2; let end = self.pos.x + (self.width / 2); for x in start..cmp::max(end, start+1) { mvaddch(self.pos.y, x, ' ' as u32); } } } struct Game { bounds: Bounds, player: GameObject, ball: GameObject, bricks: Vec<GameObject>, window: WINDOW, last_ball_move: u128, } impl Game { fn draw_player(&mut self) { self.player.clear(); self.player.draw(); } fn draw_ball(&mut self) { self.ball.clear(); self.ball.draw(); } fn draw_bricks(&mut self) { for brick in &self.bricks { brick.draw() } } fn move_player(&mut self, direction: Direction) { self.player.clear(); self.player.move1(direction, &self.bounds, &self.bounds, &vec![]); self.draw_player(); } fn move_ball(&mut self) -> Result<Option<usize>, String> { let now = now_ms(); if now - self.last_ball_move > 70 { let brick_bounds = self.get_brick_bounds(); self.last_ball_move = now; self.ball.clear(); let result = self.ball.float(&self.bounds, &self.player.get_bounds(), &brick_bounds); self.draw_ball(); return result; } Ok(None) } fn get_brick_bounds(&self) -> Vec<Bounds> { let mut brick_bounds = Vec::with_capacity(self.bricks.len()); for brick in &self.bricks { let bounds = brick.get_bounds(); brick_bounds.push(bounds); } brick_bounds } fn rm_brick(&mut self, brick_idx: usize) { assert!(brick_idx <= self.bricks.len()); self.bricks[brick_idx].clear(); self.bricks.remove(brick_idx); } } enum Command { Move(Direction), Quit, } impl Command { fn from_char(c: char) -> Command { match c { 'a' => return Command::Move(Direction::Left), 'd' => return Command::Move(Direction::Right), 'q' => return Command::Quit, _ => return Command::Move(Direction::Still), }; } fn from_i32(i: i32) -> Command { match char::from_u32(i as u32) { Some(ch) => return Command::from_char(ch), None => return Command::Move(Direction::Still), }; } } fn init() -> Result<WINDOW, String> { let window = initscr(); cbreak(); noecho(); clear(); refresh(); keypad(window, true); nodelay(window, true); curs_set(CURSOR_INVISIBLE); if !has_colors() { endwin(); return Err(String::from("No colors were available.")); } start_color(); init_pair(1, COLOR_GREEN, COLOR_BLACK); wbkgdset(window, COLOR_PAIR(1)); attron(A_BOLD()); box_(window, 0, 0); attroff(A_BOLD()); return Ok(window); } fn run(game: &mut Game) -> String { let ten_millis = time::Duration::from_millis(10); game.draw_bricks(); game.draw_player(); game.draw_ball(); refresh(); loop { thread::sleep(ten_millis); match Command::from_i32(wgetch(game.window)) { Command::Move(direction) => { game.move_player(direction); }, Command::Quit => return "Bye!".to_string(), }; let result = game.move_ball(); match result { Ok(hit_brick) => { match hit_brick { Some(brick_idx) => game.rm_brick(brick_idx), None => (), } }, Err(_) => { return "You lost :(".to_string(); } } if game.bricks.len() == 0 { return "You won! :)".to_string(); } refresh(); } } fn now_ms() -> u128 { SystemTime::now() .duration_since(UNIX_EPOCH) .expect("Time went backwards") .as_millis() } fn main() { let window = match init() { Ok(window) => window, Err(error) => { println!("Error creating window: {}\n", error); process::exit(1); }, }; let mut max_x: i32 = 0; let mut max_y: i32 = 0; getmaxyx(window, &mut max_y, &mut max_x); let brick_width = max_x / BRICKS_PER_ROW; let capacity = usize::try_from((BRICKS_PER_ROW - 1) * NUM_ROWS).unwrap(); let mut bricks = Vec::with_capacity(capacity); for row in 1..NUM_ROWS+1 { let offset = match row % 2 { 0 => (brick_width / 2), _ => (brick_width / 2) - (brick_width / 4), }; for col in 0..(BRICKS_PER_ROW - 1) { bricks.push( GameObject { pos: Point { x: offset + (col * brick_width) + (brick_width / 2), y: row }, vel: Point { x: 0, y: 0 }, disp_char: '#' as u32, width: brick_width, } ); } } let mut game = Game { window: window, bounds: Bounds { max_x: max_x, max_y: max_y, min_x: 0, min_y: 0 }, player: GameObject { pos: Point { x: (max_x / 2), y: max_y - 4}, vel: Point { x: 0, y: 0 }, disp_char: '=' as u32, width: PADDLE_WIDTH, }, ball: GameObject { pos: Point { x: (max_x / 2), y: 7 }, vel: Point { x: 0, y: 1 }, disp_char: '0' as u32, width: 1, }, bricks: bricks, last_ball_move: now_ms() }; let msg = run(&mut game); endwin(); println!("{}", msg); }
use ncurses::CURSOR_VISIBILITY::CURSOR_INVISIBLE; use ncurses::*; use std::char; use std::process; use std::{thread, time}; use std::cmp; use std::time::{SystemTime, UNIX_EPOCH}; use std::convert::TryFrom; const PADDLE_WIDTH: i32 = 12; const NUM_ROWS: i32 = 4; const BRICKS_PER_ROW: i32 = 6; enum Direction { Left, Right, Down, Up, Still, } impl Direction { fn vel(&self) -> Point { match self { Direction::Left => Point { x: -1, y: 0 }, Direction::Right => Point { x: 1, y: 0 }, Direction::Up => Point { x: 0, y: -1 }, Direction::Down => Point { x: 0, y: 1 }, Direction::Still => Point { x: 0, y: 0 }, } } } struct Point { x: i32, y: i32, } impl Point { fn will_collide(&self, bounds: &Bounds, direction: &Direction) -> bool { let vel = direction.vel(); (self.y + vel.y) == bounds.max_y && (self.x + vel.x) <= bounds.max_x && (self.x + vel.x) >= bounds.min_x } fn will_collide_with_any(&self, bounds: &Vec<Bounds>, direction: &Direction) -> Option<usize> { for (idx, bound) in bounds.iter().enumerate() { if self.will_collide(bound, direction) { return Some(idx); } } None } fn move_dir(&mut self, direction: &Direction) { let vel = direction.vel(); self.x += vel.x; self.y += vel.y; } } #[allow(dead_code)] struct Bounds { min_x: i32, min_y: i32, max_x: i32, max_y: i32, } enum MoveResult { HitPaddleCenter, HitPaddleLeft, HitPaddleRight, HitWallLeftRight, HitWallBottom, HitWallTop, HitBrick(Direction, usize), } struct GameObject { pos: Point, vel: Point, disp_char: u32, width: i32, } impl GameObject { fn get_bounds(&self) -> Bounds { let left_edge = self.pos.x - (self.width / 2); let right_edge = self.pos.x + (self.width / 2); Bounds { min_x: left_edge, max_x: right_edge, min_y: self.pos.y, max_y: self.pos.y } } fn do_move1(&mut self, bricks: &Vec<Bounds>, dir: Direction) -> Option<MoveResult> { match self.pos.will_collide_with_any(bricks, &dir) { Some(idx) => Some(MoveResult::HitBrick(dir, idx)), None => { self.pos.move_dir(&dir); None } } } fn move1(&mut self, direction: Direction, bounds: &Bounds, paddle_bounds: &Bounds, bricks: &Vec<Bounds>) -> Option<MoveResult> { let left_edge = self.pos.x - (self.width / 2); let right_edge = self.pos.x + (self.width / 2); return match direction { Direction::Left => { if left_edge <= 1 { return Some(MoveResult::HitWallLeftRight); } self.do_move1(bricks, direction) }, Direction::Right => { if right_edge >= (bounds.max_x - 2) { return Some(MoveResult::HitWallLeftRight) } self.do_move1(bricks, direction) }, Direction::Up => { if self.pos.y <= 1 { return Some(MoveResult::HitWallTop); } self.do_move1(bricks, direction) }, Direction::Down => { if self.pos.y >= (bounds.max_y - 2) { return Some(MoveResult::HitWallBottom) } if self.pos.will_collide(paddle_bounds, &Direction::Down) { let third = PADDLE_WIDTH / 3; if self.pos.x < (paddle_bounds.min_x + third) { return Some(MoveResult::HitPaddleLeft); } if self.pos.x < (paddle_bounds.min_x + (2 * third)) { return Some(MoveResult::HitPaddleCenter); } return Some(MoveResult::HitPaddleRight); } self.do_move1(bricks, direction) }, Direction::Still => None, } } fn float(&mut self, screen_bounds: &Bounds, paddle_bounds: &Bounds, brick_bounds: &Vec<Bounds>) -> Result<Option<usize>, String> { let mut hit_brick: Option<usize> = None; let mut lost: bool = false; let x_collision: Option<MoveResult> = match self.vel.x { x if x < 0 => self.move1(Direction::Left, screen_bounds, paddle_bounds, brick_bounds), x if x > 0 => self.move1(Direction::Right, screen_bounds, paddle_bounds, brick_bounds), _ => None, }; let y_collision: Option<MoveResult> =
; match y_collision { Some(MoveResult::HitPaddleCenter) => { self.vel.y = -self.vel.y; self.vel.x = 0; }, Some(MoveResult::HitPaddleLeft) => { self.vel.x = -1; self.vel.y = -self.vel.y; }, Some(MoveResult::HitPaddleRight) => { self.vel.x = 1; self.vel.y = -self.vel.y; }, Some(MoveResult::HitWallTop) => self.vel.y = -self.vel.y, Some(MoveResult::HitWallBottom) => { self.vel.x = 0; self.vel.y = 0; lost = true; }, Some(MoveResult::HitBrick(Direction::Down, brick_idx)) => { self.vel.y = -self.vel.y; hit_brick = Some(brick_idx); }, Some(MoveResult::HitBrick(Direction::Up, brick_idx)) => { self.vel.y = -self.vel.y; hit_brick = Some(brick_idx); }, _ => (), }; match x_collision { Some(MoveResult::HitBrick(Direction::Left, brick_idx)) => { if !hit_brick.is_some() { self.vel.x = -self.vel.x; hit_brick = Some(brick_idx); } }, Some(MoveResult::HitBrick(Direction::Right, brick_idx)) => { if !hit_brick.is_some() { self.vel.x = -self.vel.x; hit_brick = Some(brick_idx); } }, Some(MoveResult::HitWallLeftRight) => self.vel.x = -self.vel.x, Some(_collision) => self.vel.x = -self.vel.x, None => (), }; if lost { return Err("Player has lost.".to_string()); } Ok(hit_brick) } fn draw(&self) { let start = self.pos.x - self.width / 2; let end = self.pos.x + (self.width / 2); for x in start..cmp::max(end, start+1) { mvaddch(self.pos.y, x, self.disp_char); } } fn clear(&self) { let start = self.pos.x - self.width / 2; let end = self.pos.x + (self.width / 2); for x in start..cmp::max(end, start+1) { mvaddch(self.pos.y, x, ' ' as u32); } } } struct Game { bounds: Bounds, player: GameObject, ball: GameObject, bricks: Vec<GameObject>, window: WINDOW, last_ball_move: u128, } impl Game { fn draw_player(&mut self) { self.player.clear(); self.player.draw(); } fn draw_ball(&mut self) { self.ball.clear(); self.ball.draw(); } fn draw_bricks(&mut self) { for brick in &self.bricks { brick.draw() } } fn move_player(&mut self, direction: Direction) { self.player.clear(); self.player.move1(direction, &self.bounds, &self.bounds, &vec![]); self.draw_player(); } fn move_ball(&mut self) -> Result<Option<usize>, String> { let now = now_ms(); if now - self.last_ball_move > 70 { let brick_bounds = self.get_brick_bounds(); self.last_ball_move = now; self.ball.clear(); let result = self.ball.float(&self.bounds, &self.player.get_bounds(), &brick_bounds); self.draw_ball(); return result; } Ok(None) } fn get_brick_bounds(&self) -> Vec<Bounds> { let mut brick_bounds = Vec::with_capacity(self.bricks.len()); for brick in &self.bricks { let bounds = brick.get_bounds(); brick_bounds.push(bounds); } brick_bounds } fn rm_brick(&mut self, brick_idx: usize) { assert!(brick_idx <= self.bricks.len()); self.bricks[brick_idx].clear(); self.bricks.remove(brick_idx); } } enum Command { Move(Direction), Quit, } impl Command { fn from_char(c: char) -> Command { match c { 'a' => return Command::Move(Direction::Left), 'd' => return Command::Move(Direction::Right), 'q' => return Command::Quit, _ => return Command::Move(Direction::Still), }; } fn from_i32(i: i32) -> Command { match char::from_u32(i as u32) { Some(ch) => return Command::from_char(ch), None => return Command::Move(Direction::Still), }; } } fn init() -> Result<WINDOW, String> { let window = initscr(); cbreak(); noecho(); clear(); refresh(); keypad(window, true); nodelay(window, true); curs_set(CURSOR_INVISIBLE); if !has_colors() { endwin(); return Err(String::from("No colors were available.")); } start_color(); init_pair(1, COLOR_GREEN, COLOR_BLACK); wbkgdset(window, COLOR_PAIR(1)); attron(A_BOLD()); box_(window, 0, 0); attroff(A_BOLD()); return Ok(window); } fn run(game: &mut Game) -> String { let ten_millis = time::Duration::from_millis(10); game.draw_bricks(); game.draw_player(); game.draw_ball(); refresh(); loop { thread::sleep(ten_millis); match Command::from_i32(wgetch(game.window)) { Command::Move(direction) => { game.move_player(direction); }, Command::Quit => return "Bye!".to_string(), }; let result = game.move_ball(); match result { Ok(hit_brick) => { match hit_brick { Some(brick_idx) => game.rm_brick(brick_idx), None => (), } }, Err(_) => { return "You lost :(".to_string(); } } if game.bricks.len() == 0 { return "You won! :)".to_string(); } refresh(); } } fn now_ms() -> u128 { SystemTime::now() .duration_since(UNIX_EPOCH) .expect("Time went backwards") .as_millis() } fn main() { let window = match init() { Ok(window) => window, Err(error) => { println!("Error creating window: {}\n", error); process::exit(1); }, }; let mut max_x: i32 = 0; let mut max_y: i32 = 0; getmaxyx(window, &mut max_y, &mut max_x); let brick_width = max_x / BRICKS_PER_ROW; let capacity = usize::try_from((BRICKS_PER_ROW - 1) * NUM_ROWS).unwrap(); let mut bricks = Vec::with_capacity(capacity); for row in 1..NUM_ROWS+1 { let offset = match row % 2 { 0 => (brick_width / 2), _ => (brick_width / 2) - (brick_width / 4), }; for col in 0..(BRICKS_PER_ROW - 1) { bricks.push( GameObject { pos: Point { x: offset + (col * brick_width) + (brick_width / 2), y: row }, vel: Point { x: 0, y: 0 }, disp_char: '#' as u32, width: brick_width, } ); } } let mut game = Game { window: window, bounds: Bounds { max_x: max_x, max_y: max_y, min_x: 0, min_y: 0 }, player: GameObject { pos: Point { x: (max_x / 2), y: max_y - 4}, vel: Point { x: 0, y: 0 }, disp_char: '=' as u32, width: PADDLE_WIDTH, }, ball: GameObject { pos: Point { x: (max_x / 2), y: 7 }, vel: Point { x: 0, y: 1 }, disp_char: '0' as u32, width: 1, }, bricks: bricks, last_ball_move: now_ms() }; let msg = run(&mut game); endwin(); println!("{}", msg); }
match self.vel.y { y if y > 0 => self.move1(Direction::Down, screen_bounds, paddle_bounds, brick_bounds), y if y < 0 => self.move1(Direction::Up, screen_bounds, paddle_bounds, brick_bounds), _ => None, }
if_condition
[ { "content": "# Pong Brick Breaker Game\n\n\n\nA console pong brick breaker game written with Rust and ncurses.\n\n\n\n`a` moves the paddle to the left, `d` moves the paddle to the right.\n\n\n\n## Requirements\n\n\n\nYou'll need [Rust](https://www.rust-lang.org/tools/install) and ncurses to play. Once you have those, clone this repo and use `cargo`:\n\n\n\n```\n\n$ git clone [email protected]:pmalmgren/pongbrickbreaker.git\n\n$ cd pongbrickbreaker\n\n$ cargo run\n\n```\n\n\n\n## ncurses\n\n\n\n### macOS\n\n\n\n`ncurses` can be installed on macOS with [Homebrew](https://brew.sh/): `brew install ncurses`\n\n\n\n### Debian/Ubuntu Linux\n\n\n\n`ncurses` can be installed on Debian/Ubuntu Linux with the command: `sudo apt-get install libncurses5-dev libncursesw5-dev`\n\n\n", "file_path": "README.md", "rank": 24, "score": 1.9484109924091915 } ]
Rust
host/src/route/chain.rs
manasrivastava/tinychain
e6082f587ac089307ca9264d90d20c3f0991da52
use log::debug; use safecast::TryCastFrom; use tc_error::*; use tc_transact::fs::File; use tc_transact::Transaction; use tc_value::Value; use tcgeneric::{Instance, PathSegment, TCPath}; use crate::chain::{Chain, ChainInstance, ChainType, Subject, SUBJECT}; use super::{DeleteHandler, GetHandler, Handler, PostHandler, Public, PutHandler, Route}; impl Route for ChainType { fn route<'a>(&'a self, _path: &'a [PathSegment]) -> Option<Box<dyn Handler<'a> + 'a>> { None } } impl Route for Subject { fn route<'a>(&'a self, path: &'a [PathSegment]) -> Option<Box<dyn Handler<'a> + 'a>> { debug!("Chain::route {}", TCPath::from(path)); Some(Box::new(SubjectHandler::new(self, path))) } } struct SubjectHandler<'a> { subject: &'a Subject, path: &'a [PathSegment], } impl<'a> SubjectHandler<'a> { fn new(subject: &'a Subject, path: &'a [PathSegment]) -> Self { debug!("SubjectHandler {}", TCPath::from(path)); Self { subject, path } } } impl<'a> Handler<'a> for SubjectHandler<'a> { fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>> where 'b: 'a, { Some(Box::new(|txn, key| { Box::pin(async move { debug!("Subject::get {} {}", TCPath::from(self.path), key); match self.subject { Subject::BTree(btree) => btree.get(&txn, self.path, key).await, Subject::Table(table) => Public::get(table, &txn, self.path, key).await, #[cfg(feature = "tensor")] Subject::Dense(tensor) => tensor.get(&txn, self.path, key).await, #[cfg(feature = "tensor")] Subject::Sparse(tensor) => tensor.get(&txn, self.path, key).await, Subject::Value(file) => { let value = file.read_block(*txn.id(), SUBJECT.into()).await?; if self.path.is_empty() { Ok(value.clone().into()) } else { value.get(&txn, self.path, key).await } } } }) })) } fn put<'b>(self: Box<Self>) -> Option<PutHandler<'a, 'b>> where 'b: 'a, { Some(Box::new(|txn, key, value| { Box::pin(async move { match self.subject { Subject::BTree(btree) => btree.put(&txn, self.path, key, value).await, Subject::Table(table) => table.put(&txn, self.path, key, value).await, #[cfg(feature = "tensor")] Subject::Dense(tensor) => tensor.put(&txn, self.path, key, value).await, #[cfg(feature = "tensor")] Subject::Sparse(tensor) => tensor.put(&txn, self.path, key, value).await, Subject::Value(file) if self.path.is_empty() => { let mut subject = file.write_block(*txn.id(), SUBJECT.into()).await?; let value = Value::try_cast_from(value, |s| { TCError::bad_request( format!("invalid Value {} for Chain subject, expected", s), subject.class(), ) })?; *subject = value; Ok(()) } Subject::Value(file) => { let subject = file.read_block(*txn.id(), SUBJECT.into()).await?; subject.put(&txn, self.path, key, value).await } } }) })) } fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b>> where 'b: 'a, { Some(Box::new(|txn, params| { Box::pin(async move { debug!("Subject::post {}", params); match self.subject { Subject::BTree(btree) => btree.post(&txn, self.path, params).await, Subject::Table(table) => table.post(&txn, self.path, params).await, #[cfg(feature = "tensor")] Subject::Dense(tensor) => tensor.post(&txn, self.path, params).await, #[cfg(feature = "tensor")] Subject::Sparse(tensor) => tensor.post(&txn, self.path, params).await, Subject::Value(file) => { let subject = file.read_block(*txn.id(), SUBJECT.into()).await?; subject.post(&txn, self.path, params).await } } }) })) } fn delete<'b>(self: Box<Self>) -> Option<DeleteHandler<'a, 'b>> where 'b: 'a, { Some(Box::new(|txn, key| { Box::pin(async move { match self.subject { Subject::BTree(btree) => btree.delete(&txn, self.path, key).await, Subject::Table(table) => Public::delete(table, &txn, self.path, key).await, #[cfg(feature = "tensor")] Subject::Dense(tensor) => tensor.delete(&txn, self.path, key).await, #[cfg(feature = "tensor")] Subject::Sparse(tensor) => tensor.delete(&txn, self.path, key).await, Subject::Value(file) if self.path.is_empty() => { let mut subject = file.write_block(*txn.id(), SUBJECT.into()).await?; *subject = Value::None; Ok(()) } Subject::Value(file) => { let subject = file.read_block(*txn.id(), SUBJECT.into()).await?; subject.delete(&txn, self.path, key).await } } }) })) } } impl Route for Chain { fn route<'a>(&'a self, path: &'a [PathSegment]) -> Option<Box<dyn Handler<'a> + 'a>> { debug!("Chain::route {}", TCPath::from(path)); if path.len() == 1 && path[0].as_str() == "chain" { Some(Box::new(ChainHandler::from(self))) } else { Some(Box::new(AppendHandler::new(self, path))) } } } struct AppendHandler<'a> { chain: &'a Chain, path: &'a [PathSegment], } impl<'a> AppendHandler<'a> { fn new(chain: &'a Chain, path: &'a [PathSegment]) -> Self { Self { chain, path } } } impl<'a> Handler<'a> for AppendHandler<'a> { fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>> where 'b: 'a, { match self.chain.subject().route(self.path) { Some(handler) => handler.get(), None => None, } } fn put<'b>(self: Box<Self>) -> Option<PutHandler<'a, 'b>> where 'b: 'a, { match self.chain.subject().route(self.path) { Some(handler) => match handler.put() { Some(put_handler) => Some(Box::new(|txn, key, value| { Box::pin(async move { debug!("Chain::put {} <- {}", key, value); let path = self.path.to_vec().into(); self.chain .append_put(txn, path, key.clone(), value.clone()) .await?; put_handler(txn, key, value).await }) })), None => None, }, None => None, } } fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b>> where 'b: 'a, { match self.chain.subject().route(self.path) { Some(handler) => handler.post(), None => None, } } fn delete<'b>(self: Box<Self>) -> Option<DeleteHandler<'a, 'b>> where 'b: 'a, { match self.chain.subject().route(self.path) { Some(handler) => match handler.delete() { Some(delete_handler) => Some(Box::new(|txn, key| { Box::pin(async move { debug!("Chain::delete {}", key); self.chain .append_delete(*txn.id(), self.path.to_vec().into(), key.clone()) .await?; delete_handler(txn, key).await }) })), None => None, }, None => None, } } } struct ChainHandler<'a> { chain: &'a Chain, } impl<'a> From<&'a Chain> for ChainHandler<'a> { fn from(chain: &'a Chain) -> Self { Self { chain } } } impl<'a> Handler<'a> for ChainHandler<'a> { fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>> where 'b: 'a, { Some(Box::new(|_txn, key| { Box::pin(async move { if key.is_none() { Ok(self.chain.clone().into()) } else { Err(TCError::bad_request("invalid key for Chain", key)) } }) })) } }
use log::debug; use safecast::TryCastFrom; use tc_error::*; use tc_transact::fs::File; use tc_transact::Transaction; use tc_value::Value; use tcgeneric::{Instance, PathSegment, TCPath}; use crate::chain::{Chain, ChainInstance, ChainType, Subject, SUBJECT}; use super::{DeleteHandler, GetHandler, Handler, PostHandler, Public, PutHandler, Route}; impl Route for ChainType { fn route<'a>(&'a self, _path: &'a [PathSegment]) -> Option<Box<dyn Handler<'a> + 'a>> { None } } impl Route for Subject { fn route<'a>(&'a self, path: &'a [PathSegment]) -> Option<Box<dyn Handler<'a> + 'a>> { debug!("Chain::route {}", TCPath::from(path)); Some(Box::new(SubjectHandler::new(self, path))) } } struct SubjectHandler<'a> { subject: &'a Subject, path: &'a [PathSegment], } impl<'a> SubjectHandler<'a> { fn new(subject: &'a Subject, path: &'a [PathSegment]) -> Self { debug!("SubjectHandler {}", TCPath::from(path)); Self { subject, path } } } impl<'a> Handler<'a> for SubjectHandler<'a> { fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>> where 'b: 'a, { Some(Box::new(|txn, key| { Box::pin(async move { debug!("Subject::get {} {}", TCPath::from(self.path), key); match self.subject { Subject::BTree(btree) => btree.get(&txn, self.path, key).await, Subject::Table(table) => Public::get(table, &txn, self.path, key).await, #[cfg(feature = "tensor")] Subject::Dense(tensor) => tensor.get(&txn, self.path, key).await, #[cfg(feature = "tensor")] Subject::Sparse(tensor) => tensor.get(&txn, self.path, key).await, Subject::Value(file) => { let value = file.read_block(*txn.id(), SUBJECT.into()).await?; if self.path.is_empty() { Ok(value.clone().into()) } else { value.get(&txn, self.path, key).await } } } }) })) } fn put<'b>(self: Box<Self>) -> Option<PutHandler<'a, 'b>> where 'b: 'a, { Some(Box::new(|txn, key, value| { Box::pin(async move { match self.subject { Subject::BTree(btree) => btree.put(&txn, self.path, key, value).await, Subject::Table(table) => table.put(&txn, self.path, key, value).await, #[cfg(feature = "tensor")] Subject::Dense(tensor) => tensor.put(&txn, self.path, key, value).await, #[cfg(feature = "tensor")] Subject::Sparse(tensor) => tensor.put(&txn, self.path, key, value).await, Subject::Value(file) if self.path.is_empty() => { let mut subject = file.write_block(*txn.id(), SUBJECT.into()).await?; let value = Value::try_cast_from(value, |s| { TCError::bad_request( format!("invalid Value {} for Chain subject, expected", s), subject.class(), ) })?; *subject = value; Ok(()) } Subject::Value(file) => { let subject = file.read_block(*txn.id(), SUBJECT.into()).await?; subject.put(&txn, self.path, key, value).await } } }) })) } fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b>> where 'b: 'a, { Some(Box::new(|txn, params| { Box::pin(async move { debug!("Subject::post {}", params); match self.subject { Subject::BTree(btree) => btree.post(&txn, self.path, params).await, Subject::Table(table) => table.post(&txn, self.path, params).await, #[cfg(feature = "tensor")] Subject::Dense(tensor) => tensor.post(&txn, self.path, params).await, #[cfg(feature = "tensor")] Subject::Sparse(tensor) => tensor.post(&txn, self.path, params).await, Subject::Value(file) => { let subject = file.read_block(*txn.id(), SUBJECT.into()).await?; subject.post(&txn, self.path, params).await } } }) })) } fn delete<'b>(self: Box<Self>) -> Option<DeleteHandler<'a, 'b>> where 'b: 'a, { Some(Box::new(|txn, key| { Box::pin(async move { match self.subject { Subject::BTree(btree) => btree.delete(&txn, self.path, key).await, Subject::Table(table) => Public::delete(table, &txn, self.path, key).await, #[cfg(feature = "tensor")] Subject::Dense(tensor) => tensor.delete(&txn, self.path, key).await, #[cfg(feature = "tensor")] Subject::Sparse(tensor) => tensor.delete(&txn, self.path, key).await, Subject::Value(file) if self.path.is_empty() => { let mut subject = file.write_block(*txn.id(), SUBJECT.into()).await?; *subject = Value::None; Ok(()) } Subject::Value(file) => { let subject = file.read_block(*txn.id(), SUBJECT.into()).await?; subject.delete(&txn, self.path, key).await } } }) })) } } impl Route for Chain { fn route<'a>(&'a self, path: &'a [PathSegment]) -> Option<Box<dyn Handler<'a> + 'a>> { debug!("Chain::route {}", TCPath::from(path)); if path.len() == 1 && path[0].as_str() == "chain" { Some(Box::new(ChainHandler::from(self))) } else { Some(Box::new(AppendHandler::new(self, path))) } } } struct AppendHandler<'a> { chain: &'a Chain, path: &'a [PathSegment], } impl<'a> AppendHandler<'a> { fn new(chain: &'a Chain, path: &'a [PathSegment]) -> Self { Self { chain, path } } } impl<'a> Handler<'a> for AppendHandler<'a> { fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>> where 'b: 'a, { match self.chain.subject().route(self.path) { Some(handler) => handler.get(), None => None, } } fn put<'b>(self: Box<Self>) -> Option<PutHandler<'a, 'b>> where 'b: 'a, { match self.chain.subject().route(self.path) { Some(handler) => match handler.put() { Some(put_handler) => Some(Box::new(|txn, key, value| { Box::pin(async move { debug!("Chain::put {} <- {}", key, value); let path = self.path.to_vec().into(); self.chain .append_put(txn, path, key.clone(), value.clone()) .await?; put_handler(txn, key, value).await }) })), None => None, }, None => None, } } fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b>> where 'b: 'a, { match self.chain.subject().route(self.path) { Some(handler) => handler.post(), None => None, } } fn delete<'b>(self: Box<Self>) -> Option<DeleteHandler<'a, 'b>> where 'b: 'a, { match self.chain.subject().route(self.path) { Some(handler) => match handler.delete() { Some(delete_handler) => Some(Box::new(|txn, key| { Box::pin(asy
> From<&'a Chain> for ChainHandler<'a> { fn from(chain: &'a Chain) -> Self { Self { chain } } } impl<'a> Handler<'a> for ChainHandler<'a> { fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>> where 'b: 'a, { Some(Box::new(|_txn, key| { Box::pin(async move { if key.is_none() { Ok(self.chain.clone().into()) } else { Err(TCError::bad_request("invalid key for Chain", key)) } }) })) } }
nc move { debug!("Chain::delete {}", key); self.chain .append_delete(*txn.id(), self.path.to_vec().into(), key.clone()) .await?; delete_handler(txn, key).await }) })), None => None, }, None => None, } } } struct ChainHandler<'a> { chain: &'a Chain, } impl<'a
random
[ { "content": "fn route<'a, T>(tensor: &'a T, path: &'a [PathSegment]) -> Option<Box<dyn Handler<'a> + 'a>>\n\nwhere\n\n T: TensorAccess\n\n + TensorIO<fs::Dir, Txn = Txn>\n\n + TensorCompare<Tensor, Compare = Tensor, Dense = Tensor>\n\n + TensorBoolean<Tensor, Combine = Tensor>\n\n + TensorDualIO<fs::Dir, Tensor, Txn = Txn>\n\n + TensorMath<fs::Dir, Tensor, Combine = Tensor>\n\n + TensorReduce<fs::Dir, Txn = Txn>\n\n + TensorTransform\n\n + TensorUnary<fs::Dir, Txn = Txn>\n\n + Clone\n\n + Send\n\n + Sync,\n\n Collection: From<T>,\n\n Tensor: From<T>,\n\n <T as TensorTransform>::Slice: TensorAccess + Send,\n\n Tensor: From<<T as TensorReduce<fs::Dir>>::Reduce>,\n\n Tensor: From<<T as TensorTransform>::Expand>,\n\n Tensor: From<<T as TensorTransform>::Slice>,\n", "file_path": "host/src/route/collection/tensor.rs", "rank": 0, "score": 269926.76938796585 }, { "content": "#[inline]\n\nfn expect_row(mut row: Vec<Value>) -> TCResult<(Coord, Number)> {\n\n if let Some(value) = row.pop() {\n\n let value = value.try_into()?;\n\n expect_coord(row).map(|coord| (coord, value))\n\n } else {\n\n Err(TCError::internal(ERR_CORRUPT))\n\n }\n\n}\n\n\n", "file_path": "host/tensor/src/sparse/table.rs", "rank": 3, "score": 223935.9859516838 }, { "content": "struct TensorHandler<T> {\n\n tensor: T,\n\n}\n\n\n\nimpl<'a, T: 'a> Handler<'a> for TensorHandler<T>\n\nwhere\n\n T: TensorAccess\n\n + TensorIO<fs::Dir, Txn = Txn>\n\n + TensorDualIO<fs::Dir, Tensor, Txn = Txn>\n\n + TensorTransform\n\n + Clone\n\n + Send\n\n + Sync,\n\n <T as TensorTransform>::Slice: TensorAccess + Send,\n\n Tensor: From<<T as TensorTransform>::Slice>,\n\n{\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n", "file_path": "host/src/route/collection/tensor.rs", "rank": 4, "score": 220228.45369034744 }, { "content": "struct DualHandler {\n\n tensor: Tensor,\n\n op: fn(Tensor, Tensor) -> TCResult<Tensor>,\n\n}\n\n\n\nimpl DualHandler {\n\n fn new<T>(tensor: T, op: fn(Tensor, Tensor) -> TCResult<Tensor>) -> Self\n\n where\n\n Tensor: From<T>,\n\n {\n\n Self {\n\n tensor: tensor.into(),\n\n op,\n\n }\n\n }\n\n}\n\n\n\nimpl<'a> Handler<'a> for DualHandler {\n\n fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b>>\n\n where\n", "file_path": "host/src/route/collection/tensor.rs", "rank": 6, "score": 217838.9497524447 }, { "content": "struct RangeHandler;\n\n\n\nimpl<'a> Handler<'a> for RangeHandler {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, key| {\n\n Box::pin(async move {\n\n if key.matches::<(Vec<u64>, Number, Number)>() {\n\n let (shape, start, stop): (Vec<u64>, Number, Number) =\n\n key.opt_cast_into().unwrap();\n\n\n\n let file = create_file(&txn).await?;\n\n\n\n DenseTensor::range(file, *txn.id(), shape, start, stop)\n\n .map_ok(Tensor::from)\n\n .map_ok(Collection::from)\n\n .map_ok(State::from)\n\n .await\n\n } else {\n\n Err(TCError::bad_request(\"invalid schema for range tensor\", key))\n\n }\n\n })\n\n }))\n\n }\n\n}\n\n\n", "file_path": "host/src/route/collection/tensor.rs", "rank": 7, "score": 217838.94975244463 }, { "content": "struct UnaryHandler {\n\n tensor: Tensor,\n\n op: fn(&Tensor) -> TCResult<Tensor>,\n\n}\n\n\n\nimpl UnaryHandler {\n\n fn new(tensor: Tensor, op: fn(&Tensor) -> TCResult<Tensor>) -> Self {\n\n Self { tensor, op }\n\n }\n\n}\n\n\n\nimpl<'a> Handler<'a> for UnaryHandler {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n let tensor = if key.is_none() {\n\n self.tensor\n", "file_path": "host/src/route/collection/tensor.rs", "rank": 8, "score": 217838.94975244463 }, { "content": "struct EinsumHandler;\n\n\n\nimpl<'a> Handler<'a> for EinsumHandler {\n\n fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, mut params| {\n\n Box::pin(async move {\n\n let format: String = params.require(&label(\"format\").into())?;\n\n let tensors: Vec<Tensor> = params.require(&label(\"tensors\").into())?;\n\n einsum(&format, tensors)\n\n .map(Collection::from)\n\n .map(State::from)\n\n })\n\n }))\n\n }\n\n}\n\n\n", "file_path": "host/src/route/collection/tensor.rs", "rank": 9, "score": 217838.9497524447 }, { "content": "struct CreateHandler {\n\n class: TensorType,\n\n}\n\n\n\nimpl<'a> Handler<'a> for CreateHandler {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, key| {\n\n Box::pin(async move {\n\n let schema: Schema =\n\n key.try_cast_into(|v| TCError::bad_request(\"invalid Tensor schema\", v))?;\n\n\n\n match self.class {\n\n TensorType::Dense => {\n\n constant(&txn, schema.shape, schema.dtype.zero())\n\n .map_ok(Tensor::from)\n\n .map_ok(Collection::Tensor)\n\n .map_ok(State::Collection)\n", "file_path": "host/src/route/collection/tensor.rs", "rank": 10, "score": 217838.94975244463 }, { "content": "struct ConstantHandler;\n\n\n\nimpl<'a> Handler<'a> for ConstantHandler {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, key| {\n\n Box::pin(async move {\n\n let (shape, value): (Vec<u64>, Number) =\n\n key.try_cast_into(|v| TCError::bad_request(\"invalid Tensor schema\", v))?;\n\n\n\n constant(&txn, shape.into(), value)\n\n .map_ok(Tensor::from)\n\n .map_ok(Collection::from)\n\n .map_ok(State::from)\n\n .await\n\n })\n\n }))\n\n }\n\n}\n\n\n", "file_path": "host/src/route/collection/tensor.rs", "rank": 11, "score": 217838.94975244463 }, { "content": "struct CopySparseHandler;\n\n\n\nimpl<'a> Handler<'a> for CopySparseHandler {\n\n fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, mut params| {\n\n Box::pin(async move {\n\n let schema: Value = params.require(&label(\"schema\").into())?;\n\n let schema: Schema =\n\n schema.try_cast_into(|v| TCError::bad_request(\"invalid Tensor schema\", v))?;\n\n\n\n let source: TCStream = params.require(&label(\"source\").into())?;\n\n params.expect_empty()?;\n\n\n\n let elements = source.into_stream(txn.clone()).await?;\n\n\n\n let txn_id = *txn.id();\n\n let dir = txn.context().create_dir_tmp(txn_id).await?;\n", "file_path": "host/src/route/collection/tensor.rs", "rank": 12, "score": 213223.62771353102 }, { "content": "struct CopyDenseHandler;\n\n\n\nimpl<'a> Handler<'a> for CopyDenseHandler {\n\n fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, mut params| {\n\n Box::pin(async move {\n\n let schema: Value = params.require(&label(\"schema\").into())?;\n\n let Schema { dtype, shape } =\n\n schema.try_cast_into(|v| TCError::bad_request(\"invalid Tensor schema\", v))?;\n\n\n\n let source: TCStream = params.require(&label(\"source\").into())?;\n\n params.expect_empty()?;\n\n\n\n let elements = source.into_stream(txn.clone()).await?;\n\n let elements = elements.map(|r| {\n\n r.and_then(|n| {\n\n Number::try_cast_from(n, |n| {\n", "file_path": "host/src/route/collection/tensor.rs", "rank": 13, "score": 213223.62771353102 }, { "content": "struct SelfHandler<'a, T> {\n\n subject: &'a T,\n\n}\n\n\n\nimpl<'a, T: Clone + Send + Sync> Handler<'a> for SelfHandler<'a, T>\n\nwhere\n\n State: From<T>,\n\n{\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n if key.is_none() {\n\n Ok(self.subject.clone().into())\n\n } else {\n\n Err(TCError::not_found(key))\n\n }\n\n })\n", "file_path": "host/src/route/mod.rs", "rank": 14, "score": 211174.2255533226 }, { "content": "struct UuidHandler<'a> {\n\n dtype: &'a str,\n\n}\n\n\n\nimpl<'a> Handler<'a> for UuidHandler<'a> {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n let uuid = if key.is_some() {\n\n Uuid::try_cast_from(key, |v| TCError::bad_request(\"invalid UUID\", v))?\n\n } else {\n\n return Err(TCError::bad_request(\n\n \"missing UUID to cast into\",\n\n self.dtype,\n\n ));\n\n };\n\n\n", "file_path": "host/src/route/scalar/value/mod.rs", "rank": 15, "score": 209682.65190126724 }, { "content": "struct TransposeHandler<T> {\n\n tensor: T,\n\n}\n\n\n\nimpl<'a, T> Handler<'a> for TransposeHandler<T>\n\nwhere\n\n T: TensorTransform + Send + 'a,\n\n Tensor: From<T::Transpose>,\n\n{\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n let transpose = if key.is_none() {\n\n self.tensor.transpose(None)\n\n } else {\n\n let permutation = key.try_cast_into(|v| {\n\n TCError::bad_request(\"invalid permutation for transpose\", v)\n", "file_path": "host/src/route/collection/tensor.rs", "rank": 16, "score": 208495.6954779866 }, { "content": "struct ExpandHandler<T> {\n\n tensor: T,\n\n}\n\n\n\nimpl<'a, T> Handler<'a> for ExpandHandler<T>\n\nwhere\n\n T: TensorTransform + Send + 'a,\n\n Tensor: From<T::Expand>,\n\n{\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n let axis = key.try_cast_into(|v| TCError::bad_request(\"invalid tensor axis\", v))?;\n\n\n\n self.tensor\n\n .expand_dims(axis)\n\n .map(Tensor::from)\n", "file_path": "host/src/route/collection/tensor.rs", "rank": 17, "score": 208495.6954779866 }, { "content": "struct KeyHandler<'a, T> {\n\n table: &'a T,\n\n}\n\n\n\nimpl<'a, T: TableInstance<fs::File<Node>, fs::Dir, Txn> + 'a> Handler<'a> for KeyHandler<'a, T> {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n key.expect_none()?;\n\n\n\n let key = self\n\n .table\n\n .key()\n\n .iter()\n\n .map(|col| &col.name)\n\n .cloned()\n\n .map(Value::Id)\n", "file_path": "host/src/route/collection/table.rs", "rank": 18, "score": 206505.06851377978 }, { "content": "struct EqHandler<F> {\n\n call: F,\n\n}\n\n\n\nimpl<'a, F: FnOnce(Value) -> bool + Send + 'a> Handler<'a> for EqHandler<F> {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move { Ok(Value::from((self.call)(key)).into()) })\n\n }))\n\n }\n\n}\n\n\n\nimpl<F> From<F> for EqHandler<F> {\n\n fn from(call: F) -> Self {\n\n Self { call }\n\n }\n\n}\n", "file_path": "host/src/route/scalar/value/mod.rs", "rank": 19, "score": 205265.71980121662 }, { "content": "struct BTreeHandler<'a, T> {\n\n btree: &'a T,\n\n}\n\n\n\nimpl<'a, T: BTreeInstance> Handler<'a> for BTreeHandler<'a, T>\n\nwhere\n\n BTree: From<T::Slice>,\n\n{\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, range| {\n\n Box::pin(async move {\n\n let range = cast_into_range(Scalar::Value(range))?;\n\n let slice = self.btree.clone().slice(range, false)?;\n\n Ok(Collection::BTree(slice.into()).into())\n\n })\n\n }))\n\n }\n", "file_path": "host/src/route/collection/btree.rs", "rank": 20, "score": 202064.1326056826 }, { "content": "#[inline]\n\nfn expect_u64(value: Value) -> TCResult<u64> {\n\n if let Value::Number(Number::UInt(UInt::U64(unwrapped))) = value {\n\n Ok(unwrapped)\n\n } else {\n\n Err(TCError::bad_request(\"expected u64 but found\", value))\n\n }\n\n}\n", "file_path": "host/tensor/src/sparse/table.rs", "rank": 21, "score": 196428.64989352235 }, { "content": "struct UnaryHandlerAsync<F: Send> {\n\n tensor: Tensor,\n\n op: fn(Tensor, Txn) -> F,\n\n}\n\n\n\nimpl<'a, F: Send> UnaryHandlerAsync<F> {\n\n fn new(tensor: Tensor, op: fn(Tensor, Txn) -> F) -> Self {\n\n Self { tensor, op }\n\n }\n\n}\n\n\n\nimpl<'a, F> Handler<'a> for UnaryHandlerAsync<F>\n\nwhere\n\n F: Future<Output = TCResult<bool>> + Send + 'a,\n\n{\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, key| {\n", "file_path": "host/src/route/collection/tensor.rs", "rank": 22, "score": 196319.8146051242 }, { "content": "fn url(link: &Link, txn_id: &TxnId, key: &Value) -> TCResult<Url> {\n\n let mut url =\n\n Url::parse(&link.to_string()).map_err(|e| TCError::bad_request(\"invalid URL\", e))?;\n\n\n\n url.query_pairs_mut()\n\n .append_pair(\"txn_id\", &txn_id.to_string());\n\n\n\n if key.is_some() {\n\n let key_json = serde_json::to_string(&key)\n\n .map_err(|_| TCError::bad_request(\"unable to encode key\", key))?;\n\n\n\n url.query_pairs_mut().append_pair(\"key\", &key_json);\n\n }\n\n\n\n Ok(url)\n\n}\n\n\n", "file_path": "host/src/http/client.rs", "rank": 23, "score": 194602.1443555509 }, { "content": "struct ReduceHandler<'a, T: TensorReduce<fs::Dir>> {\n\n tensor: &'a T,\n\n reduce: fn(T, usize) -> TCResult<<T as TensorReduce<fs::Dir>>::Reduce>,\n\n reduce_all: fn(&'a T, Txn) -> TCBoxTryFuture<'a, Number>,\n\n}\n\n\n\nimpl<'a, T: TensorReduce<fs::Dir>> ReduceHandler<'a, T> {\n\n fn new(\n\n tensor: &'a T,\n\n reduce: fn(T, usize) -> TCResult<<T as TensorReduce<fs::Dir>>::Reduce>,\n\n reduce_all: fn(&'a T, Txn) -> TCBoxTryFuture<'a, Number>,\n\n ) -> Self {\n\n Self {\n\n tensor,\n\n reduce,\n\n reduce_all,\n\n }\n\n }\n\n}\n\n\n", "file_path": "host/src/route/collection/tensor.rs", "rank": 24, "score": 193878.19772335654 }, { "content": "#[inline]\n\nfn primary_key<T: TableInstance<fs::File<Node>, fs::Dir, Txn>>(\n\n key: Value,\n\n table: &T,\n\n) -> TCResult<Bounds> {\n\n let key: Vec<Value> = key.try_cast_into(|v| TCError::bad_request(\"invalid Table key\", v))?;\n\n\n\n if key.len() == table.key().len() {\n\n let bounds = table\n\n .key()\n\n .iter()\n\n .map(|col| col.name.clone())\n\n .zip(key)\n\n .collect();\n\n\n\n Ok(bounds)\n\n } else {\n\n Err(TCError::bad_request(\n\n \"invalid primary key\",\n\n Tuple::from(key),\n\n ))\n\n }\n\n}\n", "file_path": "host/src/route/collection/table.rs", "rank": 25, "score": 181375.56606069466 }, { "content": "pub fn cast_bounds(shape: &Shape, value: Value) -> TCResult<Bounds> {\n\n debug!(\"tensor bounds from {} (shape is {})\", value, shape);\n\n\n\n match value {\n\n Value::None => Ok(Bounds::all(shape)),\n\n Value::Number(i) => {\n\n let bound = cast_bound(shape[0], i.into())?;\n\n Ok(Bounds::from(vec![bound]))\n\n }\n\n Value::Tuple(range) if range.matches::<(Bound, Bound)>() => {\n\n if shape.is_empty() {\n\n return Err(TCError::bad_request(\n\n \"empty Tensor has no valid bounds, but found\",\n\n range,\n\n ));\n\n }\n\n\n\n let range = range.opt_cast_into().unwrap();\n\n Ok(Bounds::from(vec![cast_range(shape[0], range)?]))\n\n }\n", "file_path": "host/src/route/collection/tensor.rs", "rank": 26, "score": 181055.8027649947 }, { "content": "#[inline]\n\nfn expect_coord(coord: Vec<Value>) -> TCResult<Coord> {\n\n coord.into_iter().map(|val| expect_u64(val)).collect()\n\n}\n\n\n", "file_path": "host/tensor/src/sparse/table.rs", "rank": 27, "score": 178150.58860158402 }, { "content": "struct EchoHandler;\n\n\n\nimpl<'a> Handler<'a> for EchoHandler {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move { Ok(key.into()) })\n\n }))\n\n }\n\n}\n\n\n", "file_path": "host/src/route/mod.rs", "rank": 28, "score": 176943.4396040985 }, { "content": "struct TupleHandler;\n\n\n\nimpl<'a> Handler<'a> for TupleHandler {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n let value: Tuple<Value> = key.try_into()?;\n\n Ok(State::Tuple(value.into_iter().map(State::from).collect()))\n\n })\n\n }))\n\n }\n\n}\n\n\n\nimpl Route for StateType {\n\n fn route<'a>(&'a self, path: &'a [PathSegment]) -> Option<Box<dyn Handler<'a> + 'a>> {\n\n let child_handler = match self {\n\n Self::Chain(ct) => ct.route(path),\n", "file_path": "host/src/route/state.rs", "rank": 29, "score": 176943.4396040985 }, { "content": "struct ClassHandler {\n\n class: StateType,\n\n}\n\n\n\nimpl<'a> Handler<'a> for ClassHandler {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, _key| {\n\n Box::pin(async move { Ok(Link::from(self.class.path()).into()) })\n\n }))\n\n }\n\n\n\n fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, params| {\n\n Box::pin(async move {\n", "file_path": "host/src/route/state.rs", "rank": 30, "score": 176943.4396040985 }, { "content": "struct MapHandler;\n\n\n\nimpl<'a> Handler<'a> for MapHandler {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n let value = Tuple::<(Id, Value)>::try_cast_from(key, |v| {\n\n TCError::bad_request(\"invalid Map\", v)\n\n })?;\n\n\n\n let map = value\n\n .into_iter()\n\n .map(|(id, value)| (id, State::from(value)))\n\n .collect();\n\n\n\n Ok(State::Map(map))\n\n })\n\n }))\n\n }\n\n}\n\n\n", "file_path": "host/src/route/state.rs", "rank": 31, "score": 176943.4396040985 }, { "content": "struct ClosureHandler {\n\n context: Map<State>,\n\n op_def: OpDef,\n\n}\n\n\n\nimpl<'a> Handler<'a> for ClosureHandler {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n let mut context = self.context;\n\n if let OpDef::Get((key_name, op_def)) = self.op_def {\n\n Some(Box::new(|txn, key| {\n\n Box::pin(async move {\n\n context.insert(key_name, key.into());\n\n OpDef::call(op_def, txn, context).await\n\n })\n\n }))\n\n } else {\n\n None\n", "file_path": "host/src/route/closure.rs", "rank": 32, "score": 176943.4396040985 }, { "content": "struct OpHandler {\n\n op_def: OpDef,\n\n}\n\n\n\nimpl<'a> Handler<'a> for OpHandler {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n if let OpDef::Get((key_name, op_def)) = self.op_def {\n\n Some(Box::new(|txn, key| {\n\n Box::pin(async move {\n\n let context = iter::once((key_name, State::from(key)));\n\n OpDef::call(op_def, txn, context).await\n\n })\n\n }))\n\n } else {\n\n None\n\n }\n\n }\n", "file_path": "host/src/route/scalar/op.rs", "rank": 33, "score": 173269.3639501339 }, { "content": "struct CreateHandler;\n\n\n\nimpl<'a> Handler<'a> for CreateHandler {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, value| {\n\n Box::pin(async move {\n\n let schema = tc_btree::RowSchema::try_cast_from(value, |v| {\n\n TCError::bad_request(\"invalid BTree schema\", v)\n\n })?;\n\n\n\n let file = txn\n\n .context()\n\n .create_file_tmp(*txn.id(), BTreeType::default())\n\n .await?;\n\n\n\n BTreeFile::create(file, schema, *txn.id())\n\n .map_ok(Collection::from)\n\n .map_ok(State::from)\n\n .await\n\n })\n\n }))\n\n }\n\n}\n\n\n", "file_path": "host/src/route/collection/btree.rs", "rank": 34, "score": 173269.36395013396 }, { "content": "struct CreateHandler;\n\n\n\nimpl<'a> Handler<'a> for CreateHandler {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, value| {\n\n Box::pin(async move {\n\n let schema = tc_table::TableSchema::try_cast_from(value, |v| {\n\n TCError::bad_request(\"invalid Table schema\", v)\n\n })?;\n\n\n\n let dir = txn.context().create_dir_tmp(*txn.id()).await?;\n\n TableIndex::create(&dir, schema, *txn.id())\n\n .map_ok(Collection::from)\n\n .map_ok(State::from)\n\n .await\n\n })\n\n }))\n", "file_path": "host/src/route/collection/table.rs", "rank": 35, "score": 173269.3639501339 }, { "content": "struct CopyHandler;\n\n\n\nimpl<'a> Handler<'a> for CopyHandler {\n\n fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, mut params| {\n\n Box::pin(async move {\n\n let schema: Value = params.require(&label(\"schema\").into())?;\n\n let schema = tc_table::TableSchema::try_cast_from(schema, |v| {\n\n TCError::bad_request(\"invalid Table schema\", v)\n\n })?;\n\n\n\n let source: TCStream = params.require(&label(\"source\").into())?;\n\n params.expect_empty()?;\n\n\n\n let txn_id = *txn.id();\n\n\n\n let dir = txn.context().create_dir_tmp(*txn.id()).await?;\n", "file_path": "host/src/route/collection/table.rs", "rank": 36, "score": 173269.3639501339 }, { "content": "struct CastHandler {\n\n class: ScalarType,\n\n}\n\n\n\nimpl<'a> Handler<'a> for CastHandler {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n let err = format!(\"cannot cast into {} from {}\", self.class, key);\n\n\n\n Scalar::Value(key)\n\n .into_type(self.class)\n\n .map(State::Scalar)\n\n .ok_or_else(|| TCError::unsupported(err))\n\n })\n\n }))\n\n }\n", "file_path": "host/src/route/scalar/mod.rs", "rank": 37, "score": 173269.3639501339 }, { "content": "struct CopyHandler;\n\n\n\nimpl<'a> Handler<'a> for CopyHandler {\n\n fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, mut params| {\n\n Box::pin(async move {\n\n let schema: Value = params.require(&label(\"schema\").into())?;\n\n let schema = tc_btree::RowSchema::try_cast_from(schema, |v| {\n\n TCError::bad_request(\"invalid BTree schema\", v)\n\n })?;\n\n\n\n let source: TCStream = params.require(&label(\"source\").into())?;\n\n params.expect_empty()?;\n\n\n\n let txn_id = *txn.id();\n\n\n\n let file = txn\n", "file_path": "host/src/route/collection/btree.rs", "rank": 38, "score": 173269.3639501339 }, { "content": "fn cast_bound(dim: u64, bound: Value) -> TCResult<u64> {\n\n let bound = i64::try_cast_from(bound, |v| TCError::bad_request(\"invalid bound\", v))?;\n\n if bound.abs() as u64 > dim {\n\n return Err(TCError::bad_request(\n\n format!(\"Index out of bounds for dimension {}\", dim),\n\n bound,\n\n ));\n\n }\n\n\n\n if bound < 0 {\n\n Ok(dim - bound.abs() as u64)\n\n } else {\n\n Ok(bound as u64)\n\n }\n\n}\n\n\n", "file_path": "host/src/route/collection/tensor.rs", "rank": 39, "score": 172702.21462658246 }, { "content": "struct ReplicaHandler<'a> {\n\n cluster: &'a Cluster,\n\n}\n\n\n\nimpl<'a> Handler<'a> for ReplicaHandler<'a> {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, key| {\n\n Box::pin(async move {\n\n key.expect_none()?;\n\n\n\n let replicas = self.cluster.replicas(txn.id()).await?;\n\n assert!(replicas.contains(&txn.link(self.cluster.link().path().clone())));\n\n Ok(Value::from_iter(replicas).into())\n\n })\n\n }))\n\n }\n\n\n", "file_path": "host/src/route/cluster.rs", "rank": 40, "score": 172215.50736855407 }, { "content": "struct AuthorizeHandler<'a> {\n\n cluster: &'a Cluster,\n\n}\n\n\n\nimpl<'a> Handler<'a> for AuthorizeHandler<'a> {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, scope| {\n\n Box::pin(async move {\n\n let scope = scope\n\n .try_cast_into(|v| TCError::bad_request(\"expected an auth scope, not\", v))?;\n\n\n\n self.cluster\n\n .authorize(&txn, &scope)\n\n .map_ok(State::from)\n\n .await\n\n })\n\n }))\n", "file_path": "host/src/route/cluster.rs", "rank": 41, "score": 172215.50736855407 }, { "content": "struct ErrorHandler<'a> {\n\n code: &'a Id,\n\n}\n\n\n\nimpl<'a> Handler<'a> for ErrorHandler<'a> {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n let message = String::try_cast_from(key, |v| {\n\n TCError::bad_request(\"cannot cast into error message string from\", v)\n\n })?;\n\n\n\n if let Some(err_type) = error_type(self.code) {\n\n Err(TCError::new(err_type, message))\n\n } else {\n\n Err(TCError::not_found(self.code))\n\n }\n\n })\n\n }))\n\n }\n\n}\n\n\n", "file_path": "host/src/route/mod.rs", "rank": 42, "score": 172215.50736855407 }, { "content": "struct InstallHandler<'a> {\n\n cluster: &'a Cluster,\n\n}\n\n\n\nimpl<'a> Handler<'a> for InstallHandler<'a> {\n\n fn put<'b>(self: Box<Self>) -> Option<PutHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, link, scopes| {\n\n Box::pin(async move {\n\n let link = link.try_cast_into(|v| {\n\n TCError::bad_request(\"install requires a Link to a Cluster, not\", v)\n\n })?;\n\n\n\n let scopes = Tuple::try_cast_from(scopes, |v| {\n\n TCError::bad_request(\"expected a list of authorization scopes, not\", v)\n\n })?;\n\n\n\n self.cluster\n", "file_path": "host/src/route/cluster.rs", "rank": 43, "score": 172215.50736855407 }, { "content": "struct GrantHandler<'a> {\n\n cluster: &'a Cluster,\n\n}\n\n\n\nimpl<'a> Handler<'a> for GrantHandler<'a> {\n\n fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, mut params| {\n\n Box::pin(async move {\n\n let scope = params.require(&label(\"scope\").into())?;\n\n let op = params.require(&label(\"op\").into())?;\n\n let context = params.or_default(&label(\"context\").into())?;\n\n params.expect_empty()?;\n\n\n\n self.cluster.grant(txn, scope, op, context).await\n\n })\n\n }))\n\n }\n\n}\n\n\n\nimpl<'a> From<&'a Cluster> for GrantHandler<'a> {\n\n fn from(cluster: &'a Cluster) -> Self {\n\n Self { cluster }\n\n }\n\n}\n\n\n", "file_path": "host/src/route/cluster.rs", "rank": 44, "score": 172215.50736855407 }, { "content": "#[inline]\n\nfn read_file(path: &PathBuf) -> impl Future<Output = TCResult<fs::File>> + '_ {\n\n fs::File::open(path).map_err(move |e| io_err(e, path))\n\n}\n\n\n\nasync fn write_file(path: &PathBuf) -> TCResult<fs::File> {\n\n fs::OpenOptions::new()\n\n .truncate(true)\n\n .write(true)\n\n .open(path)\n\n .map_err(move |e| io_err(e, path))\n\n .await\n\n}\n", "file_path": "host/src/fs/cache.rs", "rank": 45, "score": 170495.49850785494 }, { "content": "#[inline]\n\nfn create_file(path: &PathBuf) -> impl Future<Output = TCResult<fs::File>> + '_ {\n\n tokio::fs::File::create(path).map_err(move |e| io_err(e, path))\n\n}\n\n\n", "file_path": "host/src/fs/cache.rs", "rank": 46, "score": 170495.49850785494 }, { "content": "struct MapOpHandler<I> {\n\n len: usize,\n\n items: I,\n\n}\n\n\n\nimpl<'a, I> Handler<'a> for MapOpHandler<I>\n\nwhere\n\n I: IntoIterator + Send + 'a,\n\n I::IntoIter: Send + 'a,\n\n State: From<I::Item>,\n\n{\n\n fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, mut params| {\n\n Box::pin(async move {\n\n let op: Closure = params.require(&label(\"op\").into())?;\n\n\n\n let mut tuple = Vec::with_capacity(self.len);\n", "file_path": "host/src/route/generic.rs", "rank": 47, "score": 168541.43171458947 }, { "content": "struct ClassHandler<'a> {\n\n class: &'a InstanceClass,\n\n}\n\n\n\nimpl<'a> Handler<'a> for ClassHandler<'a> {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n let parent = State::from(key);\n\n Ok(State::Object(\n\n InstanceExt::new(parent, self.class.clone()).into(),\n\n ))\n\n })\n\n }))\n\n }\n\n}\n\n\n", "file_path": "host/src/route/object/mod.rs", "rank": 48, "score": 168541.43171458947 }, { "content": "#[inline]\n\nfn u64_into_value(u: u64) -> Value {\n\n Value::Number(Number::UInt(UInt::U64(u)))\n\n}\n\n\n", "file_path": "host/tensor/src/sparse/table.rs", "rank": 49, "score": 166291.41174411718 }, { "content": "#[inline]\n\nfn file_version(file_path: &PathBuf, txn_id: &TxnId) -> PathBuf {\n\n let mut path = file_path.clone();\n\n path.push(super::VERSION.to_string());\n\n path.push(txn_id.to_string());\n\n path\n\n}\n\n\n", "file_path": "host/src/fs/file.rs", "rank": 50, "score": 165561.73094429853 }, { "content": "struct ReverseHandler<T> {\n\n btree: T,\n\n}\n\n\n\nimpl<'a, T: BTreeInstance + 'a> Handler<'a> for ReverseHandler<T>\n\nwhere\n\n BTree: From<<T as BTreeInstance>::Slice>,\n\n{\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n if key.is_some() {\n\n return Err(TCError::bad_request(\n\n \"BTree::reverse does not accept a key\",\n\n key,\n\n ));\n\n }\n", "file_path": "host/src/route/collection/btree.rs", "rank": 51, "score": 165053.1742846832 }, { "content": "struct CountHandler<T> {\n\n table: T,\n\n}\n\n\n\nimpl<'a, T: TableInstance<fs::File<Node>, fs::Dir, Txn> + 'a> Handler<'a> for CountHandler<T> {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, key| {\n\n Box::pin(async move {\n\n if key.is_some() {\n\n return Err(TCError::bad_request(\n\n \"Table::count does not accept a key (call Table::slice first)\",\n\n key,\n\n ));\n\n }\n\n\n\n self.table.count(*txn.id()).map_ok(State::from).await\n\n })\n\n }))\n\n }\n\n}\n\n\n\nimpl<T> From<T> for CountHandler<T> {\n\n fn from(table: T) -> Self {\n\n Self { table }\n\n }\n\n}\n\n\n", "file_path": "host/src/route/collection/table.rs", "rank": 52, "score": 165053.1742846832 }, { "content": "struct StreamHandler<T> {\n\n btree: T,\n\n}\n\n\n", "file_path": "host/src/route/collection/btree.rs", "rank": 53, "score": 165053.1742846832 }, { "content": "struct ContainsHandler<T> {\n\n table: T,\n\n}\n\n\n\nimpl<'a, T: TableInstance<fs::File<Node>, fs::Dir, Txn> + 'a> Handler<'a> for ContainsHandler<T> {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, key| {\n\n Box::pin(async move {\n\n let key = primary_key(key, &self.table)?;\n\n let slice = self.table.slice(key)?;\n\n\n\n let mut rows = slice.rows(*txn.id()).await?;\n\n rows.try_next()\n\n .map_ok(|row| row.is_some())\n\n .map_ok(Value::from)\n\n .map_ok(State::from)\n\n .await\n", "file_path": "host/src/route/collection/table.rs", "rank": 54, "score": 165053.1742846832 }, { "content": "struct LimitHandler<T> {\n\n table: T,\n\n}\n\n\n\nimpl<'a, T: TableInstance<fs::File<Node>, fs::Dir, Txn> + 'a> Handler<'a> for LimitHandler<T> {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n let limit = key.try_cast_into(|v| {\n\n TCError::bad_request(\"limit must be a positive integer, not\", v)\n\n })?;\n\n\n\n Ok(Collection::Table(self.table.limit(limit).into()).into())\n\n })\n\n }))\n\n }\n\n}\n\n\n\nimpl<T> From<T> for LimitHandler<T> {\n\n fn from(table: T) -> Self {\n\n Self { table }\n\n }\n\n}\n\n\n", "file_path": "host/src/route/collection/table.rs", "rank": 55, "score": 165053.1742846832 }, { "content": "struct SelectHandler<T> {\n\n table: T,\n\n}\n\n\n\nimpl<'a, T: TableInstance<fs::File<Node>, fs::Dir, Txn> + 'a> Handler<'a> for SelectHandler<T> {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n let columns =\n\n key.try_cast_into(|v| TCError::bad_request(\"invalid column list\", v))?;\n\n\n\n Ok(Collection::Table(self.table.select(columns)?.into()).into())\n\n })\n\n }))\n\n }\n\n}\n\n\n", "file_path": "host/src/route/collection/table.rs", "rank": 56, "score": 165053.1742846832 }, { "content": "struct UpdateHandler<T> {\n\n table: T,\n\n}\n\n\n\nimpl<'a, T: TableInstance<fs::File<Node>, fs::Dir, Txn> + 'a> Handler<'a> for UpdateHandler<T> {\n\n fn put<'b>(self: Box<Self>) -> Option<PutHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, key, value| {\n\n Box::pin(async move {\n\n if key.is_some() {\n\n return Err(TCError::bad_request(\n\n \"table update does not accept a key\",\n\n key,\n\n ));\n\n }\n\n\n\n let values =\n\n value.try_cast_into(|s| TCError::bad_request(\"invalid Table update\", s))?;\n", "file_path": "host/src/route/collection/table.rs", "rank": 57, "score": 165053.1742846832 }, { "content": "struct OrderHandler<T> {\n\n table: T,\n\n}\n\n\n\nimpl<'a, T: TableInstance<fs::File<Node>, fs::Dir, Txn> + 'a> Handler<'a> for OrderHandler<T> {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n let ordered = if key.matches::<(Vec<Id>, bool)>() {\n\n let (order, reverse) = key.opt_cast_into().unwrap();\n\n self.table.order_by(order, reverse)?\n\n } else if key.matches::<Vec<Id>>() {\n\n let order = key.opt_cast_into().unwrap();\n\n self.table.order_by(order, false)?\n\n } else {\n\n return Err(TCError::bad_request(\"invalid column list to order by\", key));\n\n };\n", "file_path": "host/src/route/collection/table.rs", "rank": 58, "score": 165053.1742846832 }, { "content": "struct GroupHandler<T> {\n\n table: T,\n\n}\n\n\n\nimpl<'a, T: TableInstance<fs::File<Node>, fs::Dir, Txn> + 'a> Handler<'a> for GroupHandler<T> {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n let columns = key.try_cast_into(|v| {\n\n TCError::bad_request(\"invalid column list to group by\", v)\n\n })?;\n\n\n\n let grouped = self.table.group_by(columns)?;\n\n Ok(Collection::Table(grouped.into()).into())\n\n })\n\n }))\n\n }\n\n}\n\n\n\nimpl<T> From<T> for GroupHandler<T> {\n\n fn from(table: T) -> Self {\n\n Self { table }\n\n }\n\n}\n\n\n", "file_path": "host/src/route/collection/table.rs", "rank": 59, "score": 165053.1742846832 }, { "content": "#[inline]\n\nfn route<'a, T: BTreeInstance>(\n\n btree: &'a T,\n\n path: &'a [PathSegment],\n\n) -> Option<Box<dyn Handler<'a> + 'a>>\n\nwhere\n\n BTree: From<T>,\n\n BTree: From<T::Slice>,\n\n{\n\n if path.is_empty() {\n\n Some(Box::new(BTreeHandler::from(btree)))\n\n } else if path.len() == 1 {\n\n match path[0].as_str() {\n\n \"count\" => Some(Box::new(CountHandler::from(btree))),\n\n \"first\" => Some(Box::new(FirstHandler::from(btree))),\n\n \"reverse\" => Some(Box::new(ReverseHandler::from(btree.clone()))),\n\n _ => None,\n\n }\n\n } else {\n\n None\n\n }\n", "file_path": "host/src/route/collection/btree.rs", "rank": 60, "score": 164887.57347850822 }, { "content": "struct Unary<F> {\n\n name: &'static str,\n\n op: F,\n\n}\n\n\n\nimpl<F> Unary<F> {\n\n fn new(name: &'static str, op: F) -> Self {\n\n Self { name, op }\n\n }\n\n}\n\n\n\nimpl<'a, F> Handler<'a> for Unary<F>\n\nwhere\n\n F: Fn() -> Number + Send + 'a,\n\n{\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, value| {\n", "file_path": "host/src/route/scalar/value/number.rs", "rank": 61, "score": 164726.29002546327 }, { "content": "struct Dual<F> {\n\n op: F,\n\n}\n\n\n\nimpl<F> Dual<F> {\n\n fn new(op: F) -> Self {\n\n Self { op }\n\n }\n\n}\n\n\n\nimpl<'a, F> Handler<'a> for Dual<F>\n\nwhere\n\n F: Fn(Number) -> Number + Send + 'a,\n\n{\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, value| {\n\n Box::pin(async move {\n\n let value = value.try_cast_into(|v| TCError::bad_request(\"not a Number\", v))?;\n\n Ok(State::from(Value::from((self.op)(value))))\n\n })\n\n }))\n\n }\n\n}\n\n\n", "file_path": "host/src/route/scalar/value/number.rs", "rank": 62, "score": 164726.29002546327 }, { "content": "struct FirstHandler<'a, T> {\n\n btree: &'a T,\n\n}\n\n\n\nimpl<'a, T: BTreeInstance> Handler<'a> for FirstHandler<'a, T> {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, key| {\n\n Box::pin(async move {\n\n if key.is_some() {\n\n return Err(TCError::bad_request(\n\n \"BTree::first does not accept a key\",\n\n key,\n\n ));\n\n }\n\n\n\n let mut keys = self.btree.clone().keys(*txn.id()).await?;\n\n if let Some(values) = keys.try_next().await? {\n", "file_path": "host/src/route/collection/btree.rs", "rank": 63, "score": 161441.38216054105 }, { "content": "struct TableHandler<'a, T> {\n\n table: &'a T,\n\n}\n\n\n\nimpl<'a, T: TableInstance<fs::File<Node>, fs::Dir, Txn>> Handler<'a> for TableHandler<'a, T> {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, key| {\n\n Box::pin(async move {\n\n if key.is_some() {\n\n let bounds = primary_key(key.clone(), self.table)?;\n\n let slice = self.table.clone().slice(bounds)?;\n\n let mut rows = slice.rows(*txn.id()).await?;\n\n if let Some(row) = rows.try_next().await? {\n\n let schema = self.table.schema();\n\n let columns = schema.primary().column_names().cloned();\n\n\n\n Ok(State::Scalar(\n", "file_path": "host/src/route/collection/table.rs", "rank": 64, "score": 161441.38216054105 }, { "content": "struct CountHandler<'a, T> {\n\n btree: &'a T,\n\n}\n\n\n\nimpl<'a, T: BTreeInstance> Handler<'a> for CountHandler<'a, T> {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, key| {\n\n Box::pin(async move {\n\n if key.is_some() {\n\n return Err(TCError::bad_request(\n\n \"BTree::count does not accept a key (call BTree::slice first)\",\n\n key,\n\n ));\n\n }\n\n\n\n self.btree.count(*txn.id()).map_ok(State::from).await\n\n })\n\n }))\n\n }\n\n}\n\n\n\nimpl<'a, T> From<&'a T> for CountHandler<'a, T> {\n\n fn from(btree: &'a T) -> Self {\n\n Self { btree }\n\n }\n\n}\n\n\n", "file_path": "host/src/route/collection/btree.rs", "rank": 65, "score": 161441.38216054105 }, { "content": "struct TupleHandler<'a, T: Clone> {\n\n tuple: &'a Tuple<T>,\n\n}\n\n\n\nimpl<'a, T: Instance + Clone> Handler<'a> for TupleHandler<'a, T>\n\nwhere\n\n State: From<Tuple<T>>,\n\n State: From<T>,\n\n{\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n if key.is_none() {\n\n Ok(State::from(self.tuple.clone()))\n\n } else {\n\n let i = Number::try_cast_from(key, |v| {\n\n TCError::bad_request(\"invalid tuple index\", v)\n", "file_path": "host/src/route/generic.rs", "rank": 66, "score": 158592.22044056622 }, { "content": "struct MapHandler<'a, T: Clone> {\n\n map: &'a Map<T>,\n\n}\n\n\n\nimpl<'a, T: Instance + Clone> Handler<'a> for MapHandler<'a, T>\n\nwhere\n\n State: From<Map<T>>,\n\n State: From<T>,\n\n{\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|_txn, key| {\n\n Box::pin(async move {\n\n if key.is_none() {\n\n Ok(State::from(self.map.clone()))\n\n } else {\n\n let key = Id::try_cast_from(key, |v| TCError::bad_request(\"invalid Id\", v))?;\n\n self.map\n", "file_path": "host/src/route/generic.rs", "rank": 67, "score": 158592.22044056622 }, { "content": "fn contract<D, T>(mut op: T, dimensions: BTreeMap<char, u64>, f_output: Label) -> TCResult<T>\n\nwhere\n\n D: Dir,\n\n T: TensorAccess + TensorReduce<D, Reduce = T> + TensorTransform<Transpose = T>,\n\n{\n\n let mut f_input = dimensions.keys().cloned().collect::<Label>();\n\n let mut axis = 0;\n\n while op.ndim() > f_output.len() {\n\n assert_eq!(f_input.len(), op.ndim());\n\n\n\n if !f_output.contains(&f_input[axis]) {\n\n op = op.sum(axis)?;\n\n f_input.remove(axis);\n\n } else {\n\n axis += 1;\n\n }\n\n }\n\n\n\n if f_input == f_output {\n\n Ok(op)\n", "file_path": "host/tensor/src/einsum.rs", "rank": 68, "score": 158107.2486807374 }, { "content": "#[inline]\n\nfn route<'a, T: TableInstance<fs::File<Node>, fs::Dir, Txn>>(\n\n table: &'a T,\n\n path: &[PathSegment],\n\n) -> Option<Box<dyn Handler<'a> + 'a>> {\n\n if path.is_empty() {\n\n Some(Box::new(TableHandler::from(table)))\n\n } else if path.len() == 1 {\n\n if path == &[\"key\"] {\n\n return Some(Box::new(KeyHandler::from(table)));\n\n }\n\n\n\n let table = table.clone();\n\n\n\n match path[0].as_str() {\n\n \"contains\" => Some(Box::new(ContainsHandler::from(table))),\n\n \"count\" => Some(Box::new(CountHandler::from(table))),\n\n \"limit\" => Some(Box::new(LimitHandler::from(table))),\n\n \"group\" => Some(Box::new(GroupHandler::from(table))),\n\n \"order\" => Some(Box::new(OrderHandler::from(table))),\n\n \"select\" => Some(Box::new(SelectHandler::from(table))),\n", "file_path": "host/src/route/collection/table.rs", "rank": 69, "score": 157273.1396939236 }, { "content": "#[inline]\n\nfn validate_key(key: Key, schema: &RowSchema) -> TCResult<Key> {\n\n if key.len() != schema.len() {\n\n return Err(TCError::bad_request(\"invalid key length\", Tuple::from(key)));\n\n }\n\n\n\n key.into_iter()\n\n .zip(schema)\n\n .map(|(val, col)| {\n\n val.into_type(col.dtype)\n\n .ok_or_else(|| TCError::bad_request(\"invalid value for column\", &col.name))\n\n })\n\n .collect()\n\n}\n", "file_path": "host/btree/src/file.rs", "rank": 70, "score": 156207.396869048 }, { "content": "#[inline]\n\nfn block_version(file_path: &PathBuf, txn_id: &TxnId, block_id: &BlockId) -> PathBuf {\n\n let mut path = file_version(file_path, txn_id);\n\n path.push(block_id.to_string());\n\n path\n\n}\n", "file_path": "host/src/fs/file.rs", "rank": 71, "score": 154584.78079270516 }, { "content": "struct FileVisitor<B> {\n\n txn_id: TxnId,\n\n file: File<B>,\n\n}\n\n\n\n#[async_trait]\n\nimpl<'en, B: fs::BlockData + de::FromStream<Context = ()> + 'en> de::Visitor for FileVisitor<B>\n\nwhere\n\n B: en::IntoStream<'en>,\n\n CacheBlock: From<CacheLock<B>>,\n\n CacheLock<B>: TryFrom<CacheBlock, Error = TCError>,\n\n{\n\n type Value = File<B>;\n\n\n\n fn expecting() -> &'static str {\n\n \"a File\"\n\n }\n\n\n\n async fn visit_seq<A: de::SeqAccess>(self, mut seq: A) -> Result<Self::Value, A::Error> {\n\n let mut i = 0u64;\n", "file_path": "host/src/fs/file.rs", "rank": 72, "score": 153956.3056069202 }, { "content": "pub fn dereference_self(form: Vec<(Id, Scalar)>, path: &TCPathBuf) -> Vec<(Id, Scalar)> {\n\n form.into_iter()\n\n .map(|(id, scalar)| (id, scalar.dereference_self(path)))\n\n .collect()\n\n}\n\n\n", "file_path": "host/src/scalar/op/def.rs", "rank": 73, "score": 147138.59821753946 }, { "content": "pub fn reference_self(form: Vec<(Id, Scalar)>, path: &TCPathBuf) -> Vec<(Id, Scalar)> {\n\n form.into_iter()\n\n .map(|(id, scalar)| (id, scalar.reference_self(path)))\n\n .collect()\n\n}\n", "file_path": "host/src/scalar/op/def.rs", "rank": 74, "score": 147138.59821753946 }, { "content": "struct ValueTypeVisitor;\n\n\n\nimpl ValueTypeVisitor {\n\n fn visit_path<E: DestreamError>(self, path: TCPathBuf) -> Result<ValueType, E> {\n\n ValueType::from_path(&path)\n\n .ok_or_else(|| DestreamError::invalid_value(path, Self::expecting()))\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl DestreamVisitor for ValueTypeVisitor {\n\n type Value = ValueType;\n\n\n\n fn expecting() -> &'static str {\n\n \"a Value type\"\n\n }\n\n\n\n fn visit_string<E: DestreamError>(self, v: String) -> Result<Self::Value, E> {\n\n let path: TCPathBuf = v.parse().map_err(DestreamError::custom)?;\n\n self.visit_path(path)\n", "file_path": "host/value/src/value.rs", "rank": 75, "score": 144383.91362857533 }, { "content": "struct ChainVisitor {\n\n txn: Txn,\n\n}\n\n\n\n#[async_trait]\n\nimpl de::Visitor for ChainVisitor {\n\n type Value = BlockChain;\n\n\n\n fn expecting() -> &'static str {\n\n \"a BlockChain\"\n\n }\n\n\n\n async fn visit_seq<A: de::SeqAccess>(self, mut seq: A) -> Result<Self::Value, A::Error> {\n\n let schema = seq\n\n .next_element(())\n\n .await?\n\n .ok_or_else(|| de::Error::invalid_length(0, \"a BlockChain schema\"))?;\n\n\n\n let history = seq\n\n .next_element(self.txn.clone())\n", "file_path": "host/src/chain/block.rs", "rank": 76, "score": 141287.1180141261 }, { "content": "struct ChainVisitor {\n\n txn: Txn,\n\n}\n\n\n\n#[async_trait]\n\nimpl de::Visitor for ChainVisitor {\n\n type Value = SyncChain;\n\n\n\n fn expecting() -> &'static str {\n\n \"a SyncChain\"\n\n }\n\n\n\n async fn visit_seq<A: de::SeqAccess>(self, mut seq: A) -> Result<Self::Value, A::Error> {\n\n let history = History::create(*self.txn.id(), self.txn.context().clone(), ChainType::Sync)\n\n .map_err(de::Error::custom)\n\n .await?;\n\n\n\n let schema = seq\n\n .next_element(())\n\n .await?\n", "file_path": "host/src/chain/sync.rs", "rank": 77, "score": 141287.1180141261 }, { "content": "struct Inner<F, D, Txn> {\n\n schema: TableSchema,\n\n primary: Index<F, D, Txn>,\n\n auxiliary: Vec<(Id, Index<F, D, Txn>)>,\n\n}\n\n\n\n/// The base type of a [`Table`].\n\n#[derive(Clone)]\n\npub struct TableIndex<F, D, Txn> {\n\n inner: Arc<Inner<F, D, Txn>>,\n\n}\n\n\n\nimpl<F: File<Node>, D: Dir, Txn: Transaction<D>> TableIndex<F, D, Txn> {\n\n /// Create a new `TableIndex` with the given [`TableSchema`].\n\n pub async fn create(\n\n context: &D,\n\n schema: TableSchema,\n\n txn_id: TxnId,\n\n ) -> TCResult<TableIndex<F, D, Txn>>\n\n where\n", "file_path": "host/table/src/index.rs", "rank": 78, "score": 138530.16301203094 }, { "content": "#[derive(Clone)]\n\nstruct Phantom<F, D, Txn> {\n\n file: PhantomData<F>,\n\n dir: PhantomData<D>,\n\n txn: PhantomData<Txn>,\n\n}\n\n\n\nimpl<F: File<Node>, D: Dir, Txn: Transaction<D>> Default for Phantom<F, D, Txn> {\n\n fn default() -> Self {\n\n Self {\n\n file: PhantomData,\n\n dir: PhantomData,\n\n txn: PhantomData,\n\n }\n\n }\n\n}\n", "file_path": "host/table/src/view.rs", "rank": 79, "score": 138530.16301203094 }, { "content": "struct ForEach {\n\n source: TCStream,\n\n}\n\n\n\nimpl<'a> Handler<'a> for ForEach {\n\n fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n Some(Box::new(|txn, mut params| {\n\n Box::pin(async move {\n\n let op = params.require(&label(\"op\").into())?;\n\n params.expect_empty()?;\n\n\n\n self.source\n\n .for_each(txn.clone(), op)\n\n .map_ok(State::from)\n\n .await\n\n })\n\n }))\n", "file_path": "host/src/route/stream.rs", "rank": 80, "score": 134896.30038537085 }, { "content": "fn main() {\n\n pkg_config::Config::new()\n\n .atleast_version(\"3.8\")\n\n .probe(\"arrayfire\")\n\n .unwrap();\n\n}\n", "file_path": "host/tensor/build.rs", "rank": 81, "score": 133894.44676458836 }, { "content": "#[inline]\n\nfn file_ext(path: &'_ PathBuf) -> Option<&'_ str> {\n\n path.extension().and_then(|ext| ext.to_str())\n\n}\n\n\n", "file_path": "host/src/fs/mod.rs", "rank": 82, "score": 133451.42321971816 }, { "content": "struct Active {\n\n expires: NetworkTime,\n\n scope: Scope,\n\n}\n\n\n\nimpl Active {\n\n fn new(txn_id: &TxnId, expires: NetworkTime) -> Self {\n\n let scope = TCPathBuf::from(txn_id.to_id());\n\n Self { expires, scope }\n\n }\n\n\n\n fn expires(&self) -> &NetworkTime {\n\n &self.expires\n\n }\n\n\n\n fn scope(&self) -> &Scope {\n\n &self.scope\n\n }\n\n}\n\n\n", "file_path": "host/src/txn/mod.rs", "rank": 83, "score": 132564.69833712175 }, { "content": "fn cast_range(dim: u64, range: Range) -> TCResult<AxisBounds> {\n\n debug!(\"cast range from {} with dimension {}\", range, dim);\n\n\n\n let start = match range.start {\n\n Bound::Un => 0,\n\n Bound::In(start) => cast_bound(dim, start)?,\n\n Bound::Ex(start) => cast_bound(dim, start)? + 1,\n\n };\n\n\n\n let end = match range.end {\n\n Bound::Un => dim,\n\n Bound::In(end) => cast_bound(dim, end)? + 1,\n\n Bound::Ex(end) => cast_bound(dim, end)?,\n\n };\n\n\n\n if end > start {\n\n Ok(AxisBounds::In(start..end))\n\n } else {\n\n Err(TCError::bad_request(\n\n \"invalid range\",\n\n Tuple::from(vec![start, end]),\n\n ))\n\n }\n\n}\n\n\n", "file_path": "host/src/route/collection/tensor.rs", "rank": 84, "score": 131470.7189859629 }, { "content": "fn normalize<\n\n T: TensorAccess + TensorTransform<Broadcast = T, Expand = T, Transpose = T> + Clone,\n\n>(\n\n tensor: T,\n\n f_input: &[char],\n\n f_output: &[char],\n\n dimensions: &BTreeMap<char, u64>,\n\n) -> TCResult<T> {\n\n debug!(\n\n \"normalize tensor with shape {} from {:?} -> {:?}\",\n\n tensor.shape(),\n\n f_input,\n\n f_output\n\n );\n\n if f_input == f_output {\n\n return Ok(tensor);\n\n }\n\n\n\n let source: HashMap<char, usize> = f_input.iter().cloned().zip(0..f_input.len()).collect();\n\n let permutation: Vec<usize> = f_output\n", "file_path": "host/tensor/src/einsum.rs", "rank": 85, "score": 131203.7420018873 }, { "content": "#[derive(Clone, Eq, PartialEq)]\n\nstruct NodeKey {\n\n deleted: bool,\n\n value: Vec<Value>,\n\n}\n\n\n\nimpl NodeKey {\n\n fn new(value: Vec<Value>) -> Self {\n\n Self {\n\n deleted: false,\n\n value,\n\n }\n\n }\n\n}\n\n\n\nimpl AsRef<[Value]> for NodeKey {\n\n fn as_ref(&self) -> &[Value] {\n\n &self.value\n\n }\n\n}\n\n\n", "file_path": "host/btree/src/file.rs", "rank": 86, "score": 130041.91078531045 }, { "content": "struct LinkVisitor;\n\n\n\n#[async_trait]\n\nimpl de::Visitor for LinkVisitor {\n\n type Value = Link;\n\n\n\n fn expecting() -> &'static str {\n\n \"a Link\"\n\n }\n\n\n\n fn visit_string<E: de::Error>(self, s: String) -> Result<Self::Value, E> {\n\n s.parse().map_err(de::Error::custom)\n\n }\n\n\n\n async fn visit_map<A: de::MapAccess>(self, mut map: A) -> Result<Self::Value, A::Error> {\n\n let s = map\n\n .next_key(())\n\n .await?\n\n .ok_or_else(|| de::Error::invalid_length(0, Self::expecting()))?;\n\n\n", "file_path": "host/value/src/link.rs", "rank": 87, "score": 129584.57190475527 }, { "content": "struct MutationVisitor;\n\n\n\n#[async_trait]\n\nimpl de::Visitor for MutationVisitor {\n\n type Value = Mutation;\n\n\n\n fn expecting() -> &'static str {\n\n \"a mutation record\"\n\n }\n\n\n\n async fn visit_seq<A: de::SeqAccess>(self, mut seq: A) -> Result<Self::Value, A::Error> {\n\n let path = seq\n\n .next_element(())\n\n .await?\n\n .ok_or_else(|| de::Error::invalid_length(0, Self::expecting()))?;\n\n\n\n let key = seq\n\n .next_element(())\n\n .await?\n\n .ok_or_else(|| de::Error::invalid_length(0, Self::expecting()))?;\n", "file_path": "host/src/chain/data/block.rs", "rank": 88, "score": 127253.08347379965 }, { "content": "struct HistoryVisitor {\n\n txn: Txn,\n\n}\n\n\n\n#[async_trait]\n\nimpl de::Visitor for HistoryVisitor {\n\n type Value = History;\n\n\n\n fn expecting() -> &'static str {\n\n \"Chain history\"\n\n }\n\n\n\n async fn visit_seq<A: de::SeqAccess>(self, mut seq: A) -> Result<Self::Value, A::Error> {\n\n let txn_id = *self.txn.id();\n\n let dir = self.txn.context().clone();\n\n\n\n let file: fs::File<ChainBlock> = dir\n\n .create_file(txn_id, CHAIN.into(), ChainType::default())\n\n .map_err(de::Error::custom)\n\n .await?;\n", "file_path": "host/src/chain/data/history.rs", "rank": 89, "score": 127253.08347379965 }, { "content": "fn encodable_c64<'en>(blocks: TCBoxTryStream<'en, Array>) -> impl Stream<Item = Vec<f64>> + 'en {\n\n blocks\n\n .take_while(|r| future::ready(r.is_ok()))\n\n .map(|block| block.expect(\"tensor block\"))\n\n .map(|arr| {\n\n let source = arr.type_cast::<afarray::Complex<f64>>();\n\n let re = source.re();\n\n let im = source.im();\n\n\n\n let mut i = 0;\n\n let mut dest = vec![0.; source.len() * 2];\n\n for (re, im) in re.to_vec().into_iter().zip(im.to_vec()) {\n\n dest[i] = re;\n\n dest[i + 1] = im;\n\n i += 2;\n\n }\n\n\n\n dest\n\n })\n\n}\n", "file_path": "host/tensor/src/dense/mod.rs", "rank": 90, "score": 126916.70486733674 }, { "content": "fn encodable_c32<'en>(blocks: TCBoxTryStream<'en, Array>) -> impl Stream<Item = Vec<f32>> + 'en {\n\n blocks\n\n .take_while(|r| future::ready(r.is_ok()))\n\n .map(|block| block.expect(\"tensor block\"))\n\n .map(|arr| {\n\n let source = arr.type_cast::<afarray::Complex<f32>>();\n\n let re = source.re();\n\n let im = source.im();\n\n\n\n let mut i = 0;\n\n let mut dest = vec![0.; source.len() * 2];\n\n for (re, im) in re.to_vec().into_iter().zip(im.to_vec()) {\n\n dest[i] = re;\n\n dest[i + 1] = im;\n\n i += 2;\n\n }\n\n\n\n dest\n\n })\n\n}\n\n\n", "file_path": "host/tensor/src/dense/mod.rs", "rank": 91, "score": 126916.70486733674 }, { "content": "fn block_offsets(\n\n indices: &ArrayExt<u64>,\n\n offsets: &ArrayExt<u64>,\n\n start: usize,\n\n block_id: u64,\n\n) -> (ArrayExt<u64>, usize) {\n\n assert_eq!(indices.len(), offsets.len());\n\n\n\n let num_to_update = af::sum_all(&af::eq(\n\n indices.af(),\n\n &af::constant(block_id, af::Dim4::new(&[1, 1, 1, 1])),\n\n true,\n\n ))\n\n .0;\n\n\n\n if num_to_update == 0 {\n\n return (af::Array::new_empty(af::Dim4::default()).into(), start);\n\n }\n\n\n\n let end = start + num_to_update as usize;\n\n let block_offsets = offsets.slice(start, end);\n\n\n\n (block_offsets, end)\n\n}\n\n\n", "file_path": "host/tensor/src/dense/file.rs", "rank": 92, "score": 126241.17530991562 }, { "content": "#[async_trait]\n\npub trait Public {\n\n async fn get(&self, txn: &Txn, path: &[PathSegment], key: Value) -> TCResult<State>;\n\n\n\n async fn put(&self, txn: &Txn, path: &[PathSegment], key: Value, value: State) -> TCResult<()>;\n\n\n\n async fn post(&self, txn: &Txn, path: &[PathSegment], params: Map<State>) -> TCResult<State>;\n\n\n\n async fn delete(&self, txn: &Txn, path: &[PathSegment], key: Value) -> TCResult<()>;\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: Route + fmt::Display> Public for T {\n\n async fn get(&self, txn: &Txn, path: &[PathSegment], key: Value) -> TCResult<State> {\n\n let handler = self\n\n .route(path)\n\n .ok_or_else(|| TCError::not_found(TCPath::from(path)))?;\n\n\n\n if let Some(get_handler) = handler.get() {\n\n get_handler(txn, key).await\n\n } else {\n", "file_path": "host/src/route/mod.rs", "rank": 93, "score": 125632.28299980458 }, { "content": "fn validate_args<T: TensorAccess>(\n\n f_inputs: &[Label],\n\n tensors: &[T],\n\n) -> TCResult<BTreeMap<char, u64>> {\n\n if f_inputs.len() != tensors.len() {\n\n return Err(TCError::bad_request(\n\n \"number of Tensors passed to einsum does not match number of format strings\",\n\n format!(\"{} != {}\", tensors.len(), f_inputs.len()),\n\n ));\n\n } else if tensors.is_empty() {\n\n return Err(TCError::bad_request(\n\n \"no Tensor was provided to einsum\",\n\n \"[]\",\n\n ));\n\n }\n\n\n\n let mut dimensions = BTreeMap::new();\n\n\n\n for (f_input, tensor) in f_inputs.iter().zip(tensors.iter()) {\n\n if f_input.len() != tensor.ndim() {\n", "file_path": "host/tensor/src/einsum.rs", "rank": 94, "score": 125304.87985627621 }, { "content": "pub trait BlockWrite<B: BlockData, F: File<B>>: DerefMut<Target = B> + Send {\n\n fn downgrade(\n\n self,\n\n file: &F,\n\n ) -> TCBoxTryFuture<<<F as File<B>>::Block as Block<B, F>>::ReadLock>;\n\n}\n\n\n\n/// A transactional filesystem block.\n", "file_path": "host/transact/src/fs.rs", "rank": 95, "score": 122100.61637527902 }, { "content": "#[inline]\n\nfn fs_path(mount_point: &PathBuf, name: &PathSegment) -> PathBuf {\n\n let mut path = mount_point.clone();\n\n path.push(name.to_string());\n\n path\n\n}\n\n\n", "file_path": "host/src/fs/mod.rs", "rank": 96, "score": 120363.2017207955 }, { "content": "struct TensorVisitor<FD, FS, D, T> {\n\n txn: T,\n\n dir: PhantomData<D>,\n\n dense: PhantomData<FD>,\n\n sparse: PhantomData<FS>,\n\n}\n\n\n\nimpl<FD, FS, D, T> TensorVisitor<FD, FS, D, T> {\n\n fn new(txn: T) -> Self {\n\n Self {\n\n txn,\n\n dir: PhantomData,\n\n dense: PhantomData,\n\n sparse: PhantomData,\n\n }\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<FD, FS, D, T> de::Visitor for TensorVisitor<FD, FS, D, T>\n", "file_path": "host/tensor/src/lib.rs", "rank": 97, "score": 117992.75245096769 }, { "content": "struct BlockStreamView<'en> {\n\n dtype: NumberType,\n\n blocks: TCBoxTryStream<'en, Array>,\n\n}\n\n\n\nimpl<'en> en::IntoStream<'en> for BlockStreamView<'en> {\n\n fn into_stream<E: en::Encoder<'en>>(self, encoder: E) -> Result<E::Ok, E::Error> {\n\n use tc_value::{\n\n ComplexType as CT, FloatType as FT, IntType as IT, NumberType as NT, UIntType as UT,\n\n };\n\n\n\n fn encodable<'en, T: af::HasAfEnum + Clone + Default + 'en>(\n\n blocks: TCBoxTryStream<'en, Array>,\n\n ) -> impl Stream<Item = Vec<T>> + 'en {\n\n // an error can't be encoded within an array\n\n // so in case of a read error, let the receiver figure out that the tensor\n\n // doesn't have enough elements\n\n blocks\n\n .take_while(|r| future::ready(r.is_ok()))\n\n .map(|r| r.expect(\"tensor block\").type_cast().to_vec())\n", "file_path": "host/tensor/src/dense/mod.rs", "rank": 98, "score": 116724.62189381887 }, { "content": "#[async_trait]\n\npub trait Handler<'a>: Send {\n\n fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n None\n\n }\n\n\n\n fn put<'b>(self: Box<Self>) -> Option<PutHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n None\n\n }\n\n\n\n fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n None\n\n }\n\n\n\n fn delete<'b>(self: Box<Self>) -> Option<DeleteHandler<'a, 'b>>\n\n where\n\n 'b: 'a,\n\n {\n\n None\n\n }\n\n}\n\n\n", "file_path": "host/src/route/mod.rs", "rank": 99, "score": 116474.56908736716 } ]
Rust
src/block_ciphers.rs
dkull/cryptopals
8d6b723b2c7f7905755804631a2bdda4c6b2005e
use crate::xor_arrays; use aes::Aes128; use std::collections::VecDeque; #[derive(PartialEq, Clone, Copy, Debug)] pub enum AESBlockMode { ECB, CBC, CTR, } fn ctr_input(nonce: Option<[u8; 8]>, n: usize) -> [u8; 16] { let nonce = if let Some(n) = nonce { n } else { [0u8; 8] }; let counter = &(n as u64).to_le_bytes(); let mut adjusted = [0u8; 16]; adjusted[0..8].copy_from_slice(&nonce); adjusted[8..16].copy_from_slice(counter); adjusted } pub fn pkcs7_padding(data: &mut Vec<u8>, block_size: usize) { let missing_bytes = block_size - (data.len() % block_size); (0..missing_bytes).for_each(|_| data.push(missing_bytes as u8)); } #[test] fn pkcs7_padding_works() { let mut case1 = (vec![0x00, 0xff, 0x01], vec![0x00, 0xff], 3); pkcs7_padding(&mut case1.1, case1.2); assert_eq!(case1.0, case1.1); let mut case2 = ( vec![0x00, 0xff, 0x01, 0x00, 0xff, 0x01, 0x02, 0x02], vec![0x00, 0xff, 0x01, 0x00, 0xff, 0x01], 8, ); pkcs7_padding(&mut case2.1, case2.2); assert_eq!(case2.0, case2.1); let mut case3 = (vec![0x00, 0xff, 0x02, 0x02], vec![0x00, 0xff], 2); pkcs7_padding(&mut case3.1, case3.2); assert_eq!(case3.0, case3.1); let mut case4 = (vec![0x00, 0xff, 0x01, 0x01], vec![0x00, 0xff, 0x01], 2); pkcs7_padding(&mut case4.1, case4.2); assert_eq!(case4.0, case4.1); let mut case5 = ( vec![0x00, 0xff, 0x01, 0x01, 0x02, 0x02], vec![0x00, 0xff, 0x01, 0x01], 2, ); pkcs7_padding(&mut case5.1, case5.2); assert_eq!(case5.0, case5.1); } pub fn pkcs7_padding_strip(data: &mut Vec<u8>) -> bool { let padding = data[data.len() - 1]; if padding as usize > data.len() { return false; } if padding == 0 { return false; } let padding_start = data.len() - padding as usize; for p in padding_start..data.len() { if data[p] != padding { return false; } } for _ in 0..padding { data.pop(); } true } #[test] fn pkcs7_padding_strip_works() { let mut data1 = vec![0x00, 0xff, 0x01, 0x00, 0xff, 0x01, 0x02, 0x02]; assert_eq!(pkcs7_padding_strip(&mut data1), true); let mut data2 = vec![0x00, 0xff, 0x01, 0x00, 0xff, 0x01, 0x02, 0x02, 0x02]; assert_eq!(pkcs7_padding_strip(&mut data2), true); let mut data3 = vec![0x00, 0xff, 0x01, 0x00, 0xff, 0x01, 0x02]; assert_eq!(pkcs7_padding_strip(&mut data3), false); let mut data4 = vec![0x00, 0xff, 0x01, 0x00, 0xff, 0x01, 0x03]; assert_eq!(pkcs7_padding_strip(&mut data4), false); } pub fn aes_encrypt(data: &[u8], key: &[u8], iv: Option<[u8; 16]>, mode: AESBlockMode) -> Vec<u8> { use aes::block_cipher_trait::generic_array::GenericArray; use aes::block_cipher_trait::BlockCipher; let iv = match iv { Some(iv) => iv, None => [0u8; 16], }; let mut data = data.to_vec(); match mode { AESBlockMode::ECB | AESBlockMode::CBC => { pkcs7_padding(&mut data, 16); } _ => (), } let cipher = Aes128::new(GenericArray::from_slice(&key)); let blocks = data.chunks(16).collect::<VecDeque<_>>(); let mut output = vec![]; blocks.iter().enumerate().fold(iv, |prev, (i, block)| { let block = match mode { AESBlockMode::ECB => block.to_vec(), AESBlockMode::CBC => xor_arrays(&prev, &block), AESBlockMode::CTR => block.to_vec(), }; let buffer = match mode { AESBlockMode::CTR => { let adjusted = ctr_input(None, i); let mut buffer = GenericArray::clone_from_slice(&adjusted); cipher.encrypt_block(&mut buffer); xor_arrays(&buffer.to_vec(), &block).to_vec() } _ => { let mut buffer = GenericArray::clone_from_slice(&block); cipher.encrypt_block(&mut buffer); buffer.to_vec() } }; let mut ct = [0u8; 16]; ct.copy_from_slice(buffer.as_slice()); output.push(ct.clone()); ct }); output.concat()[0..data.len()].to_vec() } #[test] fn aes_encrypt_works() { let data = hex_to_bytes("6bc1bee22e409f96e93d7e117393172a"); let key = hex_to_bytes("2b7e151628aed2a6abf7158809cf4f3c"); let iv = hex_to_bytes("000102030405060708090a0b0c0d0e0f"); let test_vector_cbc = hex_to_bytes("7649abac8119b246cee98e9b12e9197d"); let test_vector_ecb = hex_to_bytes("3ad77bb40d7a3660a89ecaf32466ef97"); let mut iv_real = [0u8; 16]; iv_real.copy_from_slice(&iv); let ct = aes_encrypt(&data, &key, Some(iv_real), AESBlockMode::CBC); assert_eq!(ct[0..16].to_vec(), test_vector_cbc); let ct = aes_encrypt(&data, &key, Some(iv_real), AESBlockMode::ECB); assert_eq!(ct[0..16].to_vec(), test_vector_ecb); let data_ctr = base64_to_bytes("L77na/nrFsKvynd6HzOoG7GHTLXsTVu9qvY/2syLXzhPweyyMTJULu/6/kXX0KSvoOLSFQ=="); let ctr_answer = b"Yo, VIP Let's kick it Ice, Ice, baby Ice, Ice, baby ".to_vec(); let encrypted = aes_encrypt(&ctr_answer, b"YELLOW SUBMARINE", None, AESBlockMode::CTR); assert_eq!(encrypted, data_ctr); } pub fn aes_decrypt(data: &[u8], key: &[u8], iv: Option<[u8; 16]>, mode: AESBlockMode) -> Vec<u8> { use aes::block_cipher_trait::generic_array::GenericArray; use aes::block_cipher_trait::BlockCipher; let iv = match iv { Some(iv) => iv, None => [0u8; 16], }; let cipher = Aes128::new(GenericArray::from_slice(&key)); let blocks = data.chunks(16).collect::<VecDeque<_>>(); let mut output = vec![]; blocks.iter().enumerate().fold(iv, |prev, (i, block)| { let mut ct = [0u8; 16]; ct[0..block.len()].copy_from_slice(block); let buffer = match mode { AESBlockMode::CTR => { let nonce = [0u8; 8]; let counter = &(i as u64).to_le_bytes(); let mut adjusted = [0u8; 16]; adjusted[0..8].copy_from_slice(&nonce); adjusted[8..16].copy_from_slice(counter); let mut buffer = GenericArray::clone_from_slice(&adjusted); cipher.encrypt_block(&mut buffer); buffer.to_vec() } _ => { let mut buffer = GenericArray::clone_from_slice(&block); cipher.decrypt_block(&mut buffer); buffer.to_vec() } }; let pt = match mode { AESBlockMode::ECB => buffer.as_slice().to_vec(), AESBlockMode::CBC => xor_arrays(&prev, buffer.as_slice()), AESBlockMode::CTR => xor_arrays(&block, &buffer.as_slice()[0..block.len()]), }; output.push(pt); ct }); let mut output = output.concat(); match mode { AESBlockMode::ECB | AESBlockMode::CBC => { let good_padding = pkcs7_padding_strip(&mut output); if !good_padding { return vec![]; } () } _ => (), } output } #[test] fn aes_decrypt_works() { let data = hex_to_bytes("6bc1bee22e409f96e93d7e117393172a"); let key = hex_to_bytes("2b7e151628aed2a6abf7158809cf4f3c"); let iv = hex_to_bytes("000102030405060708090a0b0c0d0e0f"); let mut iv_real = [0u8; 16]; iv_real.copy_from_slice(&iv); let cbc_ct = aes_encrypt(&data, &key, Some(iv_real), AESBlockMode::CBC); let ecb_ct = aes_encrypt(&data, &key, Some(iv_real), AESBlockMode::ECB); let pt = aes_decrypt(&cbc_ct, &key, Some(iv_real), AESBlockMode::CBC); assert_eq!(pt, data); let pt = aes_decrypt(&ecb_ct, &key, Some(iv_real), AESBlockMode::ECB); assert_eq!(pt, data); let data_ctr = base64_to_bytes("L77na/nrFsKvynd6HzOoG7GHTLXsTVu9qvY/2syLXzhPweyyMTJULu/6/kXX0KSvoOLSFQ=="); let ctr_answer = b"Yo, VIP Let's kick it Ice, Ice, baby Ice, Ice, baby ".to_vec(); let pt = aes_decrypt(&data_ctr, b"YELLOW SUBMARINE", None, AESBlockMode::CTR); assert_eq!(pt.to_vec(), ctr_answer); }
use crate::xor_arrays; use aes::Aes128; use std::collections::VecDeque; #[derive(PartialEq, Clone, Copy, Debug)] pub enum AESBlockMode { ECB, CBC, CTR, } fn ctr_input(nonce: Option<[u8; 8]>, n: usize) -> [u8; 16] { let nonce = if let Some(n) = nonce { n } else { [0u8; 8] }; let counter = &(n as u64).to_le_bytes(); let mut adjusted = [0u8; 16]; adjusted[0..8].copy_from_slice(&nonce); adjusted[8..16].copy_from_slice(counter); adjusted } pub fn pkcs7_padding(data: &mut Vec<u8>, block_size: usize) { let missing_bytes = block_size - (data.len() % block_size); (0..missing_bytes).for_each(|_| data.push(missing_bytes as u8)); } #[test]
pub fn pkcs7_padding_strip(data: &mut Vec<u8>) -> bool { let padding = data[data.len() - 1]; if padding as usize > data.len() { return false; } if padding == 0 { return false; } let padding_start = data.len() - padding as usize; for p in padding_start..data.len() { if data[p] != padding { return false; } } for _ in 0..padding { data.pop(); } true } #[test] fn pkcs7_padding_strip_works() { let mut data1 = vec![0x00, 0xff, 0x01, 0x00, 0xff, 0x01, 0x02, 0x02]; assert_eq!(pkcs7_padding_strip(&mut data1), true); let mut data2 = vec![0x00, 0xff, 0x01, 0x00, 0xff, 0x01, 0x02, 0x02, 0x02]; assert_eq!(pkcs7_padding_strip(&mut data2), true); let mut data3 = vec![0x00, 0xff, 0x01, 0x00, 0xff, 0x01, 0x02]; assert_eq!(pkcs7_padding_strip(&mut data3), false); let mut data4 = vec![0x00, 0xff, 0x01, 0x00, 0xff, 0x01, 0x03]; assert_eq!(pkcs7_padding_strip(&mut data4), false); } pub fn aes_encrypt(data: &[u8], key: &[u8], iv: Option<[u8; 16]>, mode: AESBlockMode) -> Vec<u8> { use aes::block_cipher_trait::generic_array::GenericArray; use aes::block_cipher_trait::BlockCipher; let iv = match iv { Some(iv) => iv, None => [0u8; 16], }; let mut data = data.to_vec(); match mode { AESBlockMode::ECB | AESBlockMode::CBC => { pkcs7_padding(&mut data, 16); } _ => (), } let cipher = Aes128::new(GenericArray::from_slice(&key)); let blocks = data.chunks(16).collect::<VecDeque<_>>(); let mut output = vec![]; blocks.iter().enumerate().fold(iv, |prev, (i, block)| { let block = match mode { AESBlockMode::ECB => block.to_vec(), AESBlockMode::CBC => xor_arrays(&prev, &block), AESBlockMode::CTR => block.to_vec(), }; let buffer = match mode { AESBlockMode::CTR => { let adjusted = ctr_input(None, i); let mut buffer = GenericArray::clone_from_slice(&adjusted); cipher.encrypt_block(&mut buffer); xor_arrays(&buffer.to_vec(), &block).to_vec() } _ => { let mut buffer = GenericArray::clone_from_slice(&block); cipher.encrypt_block(&mut buffer); buffer.to_vec() } }; let mut ct = [0u8; 16]; ct.copy_from_slice(buffer.as_slice()); output.push(ct.clone()); ct }); output.concat()[0..data.len()].to_vec() } #[test] fn aes_encrypt_works() { let data = hex_to_bytes("6bc1bee22e409f96e93d7e117393172a"); let key = hex_to_bytes("2b7e151628aed2a6abf7158809cf4f3c"); let iv = hex_to_bytes("000102030405060708090a0b0c0d0e0f"); let test_vector_cbc = hex_to_bytes("7649abac8119b246cee98e9b12e9197d"); let test_vector_ecb = hex_to_bytes("3ad77bb40d7a3660a89ecaf32466ef97"); let mut iv_real = [0u8; 16]; iv_real.copy_from_slice(&iv); let ct = aes_encrypt(&data, &key, Some(iv_real), AESBlockMode::CBC); assert_eq!(ct[0..16].to_vec(), test_vector_cbc); let ct = aes_encrypt(&data, &key, Some(iv_real), AESBlockMode::ECB); assert_eq!(ct[0..16].to_vec(), test_vector_ecb); let data_ctr = base64_to_bytes("L77na/nrFsKvynd6HzOoG7GHTLXsTVu9qvY/2syLXzhPweyyMTJULu/6/kXX0KSvoOLSFQ=="); let ctr_answer = b"Yo, VIP Let's kick it Ice, Ice, baby Ice, Ice, baby ".to_vec(); let encrypted = aes_encrypt(&ctr_answer, b"YELLOW SUBMARINE", None, AESBlockMode::CTR); assert_eq!(encrypted, data_ctr); } pub fn aes_decrypt(data: &[u8], key: &[u8], iv: Option<[u8; 16]>, mode: AESBlockMode) -> Vec<u8> { use aes::block_cipher_trait::generic_array::GenericArray; use aes::block_cipher_trait::BlockCipher; let iv = match iv { Some(iv) => iv, None => [0u8; 16], }; let cipher = Aes128::new(GenericArray::from_slice(&key)); let blocks = data.chunks(16).collect::<VecDeque<_>>(); let mut output = vec![]; blocks.iter().enumerate().fold(iv, |prev, (i, block)| { let mut ct = [0u8; 16]; ct[0..block.len()].copy_from_slice(block); let buffer = match mode { AESBlockMode::CTR => { let nonce = [0u8; 8]; let counter = &(i as u64).to_le_bytes(); let mut adjusted = [0u8; 16]; adjusted[0..8].copy_from_slice(&nonce); adjusted[8..16].copy_from_slice(counter); let mut buffer = GenericArray::clone_from_slice(&adjusted); cipher.encrypt_block(&mut buffer); buffer.to_vec() } _ => { let mut buffer = GenericArray::clone_from_slice(&block); cipher.decrypt_block(&mut buffer); buffer.to_vec() } }; let pt = match mode { AESBlockMode::ECB => buffer.as_slice().to_vec(), AESBlockMode::CBC => xor_arrays(&prev, buffer.as_slice()), AESBlockMode::CTR => xor_arrays(&block, &buffer.as_slice()[0..block.len()]), }; output.push(pt); ct }); let mut output = output.concat(); match mode { AESBlockMode::ECB | AESBlockMode::CBC => { let good_padding = pkcs7_padding_strip(&mut output); if !good_padding { return vec![]; } () } _ => (), } output } #[test] fn aes_decrypt_works() { let data = hex_to_bytes("6bc1bee22e409f96e93d7e117393172a"); let key = hex_to_bytes("2b7e151628aed2a6abf7158809cf4f3c"); let iv = hex_to_bytes("000102030405060708090a0b0c0d0e0f"); let mut iv_real = [0u8; 16]; iv_real.copy_from_slice(&iv); let cbc_ct = aes_encrypt(&data, &key, Some(iv_real), AESBlockMode::CBC); let ecb_ct = aes_encrypt(&data, &key, Some(iv_real), AESBlockMode::ECB); let pt = aes_decrypt(&cbc_ct, &key, Some(iv_real), AESBlockMode::CBC); assert_eq!(pt, data); let pt = aes_decrypt(&ecb_ct, &key, Some(iv_real), AESBlockMode::ECB); assert_eq!(pt, data); let data_ctr = base64_to_bytes("L77na/nrFsKvynd6HzOoG7GHTLXsTVu9qvY/2syLXzhPweyyMTJULu/6/kXX0KSvoOLSFQ=="); let ctr_answer = b"Yo, VIP Let's kick it Ice, Ice, baby Ice, Ice, baby ".to_vec(); let pt = aes_decrypt(&data_ctr, b"YELLOW SUBMARINE", None, AESBlockMode::CTR); assert_eq!(pt.to_vec(), ctr_answer); }
fn pkcs7_padding_works() { let mut case1 = (vec![0x00, 0xff, 0x01], vec![0x00, 0xff], 3); pkcs7_padding(&mut case1.1, case1.2); assert_eq!(case1.0, case1.1); let mut case2 = ( vec![0x00, 0xff, 0x01, 0x00, 0xff, 0x01, 0x02, 0x02], vec![0x00, 0xff, 0x01, 0x00, 0xff, 0x01], 8, ); pkcs7_padding(&mut case2.1, case2.2); assert_eq!(case2.0, case2.1); let mut case3 = (vec![0x00, 0xff, 0x02, 0x02], vec![0x00, 0xff], 2); pkcs7_padding(&mut case3.1, case3.2); assert_eq!(case3.0, case3.1); let mut case4 = (vec![0x00, 0xff, 0x01, 0x01], vec![0x00, 0xff, 0x01], 2); pkcs7_padding(&mut case4.1, case4.2); assert_eq!(case4.0, case4.1); let mut case5 = ( vec![0x00, 0xff, 0x01, 0x01, 0x02, 0x02], vec![0x00, 0xff, 0x01, 0x01], 2, ); pkcs7_padding(&mut case5.1, case5.2); assert_eq!(case5.0, case5.1); }
function_block-full_function
[ { "content": "pub fn xor_arrays(a: &[u8], b: &[u8]) -> Vec<u8> {\n\n assert!(a.len() >= b.len(), format!(\"{} vs {}\", a.len(), b.len()));\n\n a.to_vec()\n\n .iter()\n\n .zip(b.to_vec().iter().cycle())\n\n .map(|(a, b)| a ^ b)\n\n .collect()\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 3, "score": 118047.6283603263 }, { "content": "pub fn search_xor_key(data: &[u8], key_len: usize) -> (isize, Vec<u8>, Vec<u8>) {\n\n use std::cmp::max;\n\n let mut best_guesses = vec![];\n\n let mut best_key = vec![];\n\n let mut longest = 0;\n\n let mut sum_of_scores = 0;\n\n\n\n for offset in 0..key_len {\n\n let nth_bytes = data\n\n .iter()\n\n .enumerate()\n\n .filter(|(i, _)| i % key_len == offset)\n\n .map(|(_, b)| *b)\n\n .collect::<Vec<_>>();\n\n\n\n let best_guess = find_xor_key_eng(&nth_bytes);\n\n longest = max(best_guess.2.len(), longest);\n\n best_guesses.push(best_guess.2.clone());\n\n best_key.push(best_guess.1);\n\n sum_of_scores += best_guess.0;\n", "file_path": "src/lib.rs", "rank": 4, "score": 115499.08801494258 }, { "content": "pub fn bytes_to_hexbytes(data: &[u8]) -> Vec<u8> {\n\n let mut output: Vec<u8> = vec![];\n\n output.reserve(data.len() * 2);\n\n\n\n data.to_vec().iter().for_each(|b| {\n\n output.push(format!(\"{:x}\", (b & 0xf0) >> 4).as_bytes()[0]);\n\n output.push(format!(\"{:x}\", (b & 0x0f)).as_bytes()[0]);\n\n });\n\n output\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 5, "score": 114235.44344142717 }, { "content": "pub fn hexbytes_to_bytes(data: &[u8]) -> Vec<u8> {\n\n let mut output = vec![];\n\n output.reserve(data.len()); // actually need 1/2 of this\n\n\n\n data.to_vec()\n\n .chunks(2)\n\n .collect::<Vec<_>>()\n\n .iter()\n\n .for_each(|x| {\n\n let hex = format!(\"{}{}\", x[0] as char, x[1] as char);\n\n output.push(u8::from_str_radix(&hex, 16).unwrap());\n\n });\n\n\n\n output\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 6, "score": 114235.44344142717 }, { "content": "pub fn find_xor_key_eng(data: &[u8]) -> (isize, u8, Vec<u8>) {\n\n let mut best = (-0xffff, 0x00, vec![]);\n\n for b in 1..=255u8 {\n\n let decrypted = xor_arrays(data, &[b]);\n\n let score = english_frequency_score(&decrypted);\n\n if score > best.0 {\n\n best = (score, b, decrypted);\n\n }\n\n }\n\n best\n\n}\n", "file_path": "src/lib.rs", "rank": 7, "score": 109465.82969825211 }, { "content": "pub fn random_key<T: Into<usize>>(length: T) -> Vec<u8> {\n\n let length = length.into() as usize;\n\n let mut output: Vec<u8> = Vec::with_capacity(length);\n\n\n\n let mut rng = rand::thread_rng();\n\n for i in 0..length {\n\n output.push(rng.gen());\n\n }\n\n output\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 10, "score": 108089.07142058073 }, { "content": "// Returns a 128-bit MD4 hash as an array of four 32-bit words.\n\n// Based on RFC 1186 from https://www.ietf.org/rfc/rfc1186.txt\n\npub fn md4<T: Into<Vec<u8>>>(\n\n input: T,\n\n existing_len: u64,\n\n inner_state: Option<&[u32; 4]>,\n\n) -> [u32; 4] {\n\n let mut bytes = input.into().to_vec();\n\n let orig_bytes_len = bytes.len();\n\n let initial_bit_len = ((existing_len << 3) + (bytes.len() << 3) as u64) as u64;\n\n\n\n // Step 1. Append padding bits\n\n // Append one '1' bit, then append 0 ≤ k < 512 bits '0', such that the resulting message\n\n // length in bis is congruent to 448 (mod 512).\n\n // Since our message is in bytes, we use one byte with a set high-order bit (0x80) plus\n\n // a variable number of zero bytes.\n\n\n\n // Append zeros\n\n // Number of padding bytes needed is 448 bits (56 bytes) modulo 512 bits (64 bytes)\n\n bytes.push(0x80_u8);\n\n while (bytes.len() % 64) != 56 {\n\n bytes.push(0_u8);\n", "file_path": "src/md4.rs", "rank": 11, "score": 105156.87630591044 }, { "content": "pub fn bytes_to_hex(data: &[u8]) -> String {\n\n data.to_vec()\n\n .iter()\n\n .map(|b| format!(\"{:02x}\", b))\n\n .collect::<Vec<_>>()\n\n .join(\"\")\n\n}\n", "file_path": "src/lib.rs", "rank": 12, "score": 104821.4368771918 }, { "content": "pub fn bytes_to_base64(data: &[u8]) -> String {\n\n use std::cmp::min;\n\n\n\n let uppers = (b'A'..=b'Z').collect::<Vec<u8>>();\n\n let lowers = (b'a'..=b'z').collect::<Vec<u8>>();\n\n let numbers = (b'0'..=b'9').collect::<Vec<u8>>();\n\n let extras = vec![b'+', b'/'];\n\n let lookup = vec![uppers, lowers, numbers, extras].concat();\n\n\n\n let mut current_byte = 0;\n\n let mut bit_offset = 0;\n\n\n\n let mut output = String::new();\n\n loop {\n\n let take_bits = min(6, 8 - bit_offset);\n\n let mut taken_bits = bits_from_byte(data[current_byte], bit_offset, take_bits);\n\n\n\n // if we are on byte border\n\n if take_bits < 6 {\n\n let take_from_next = 6 - take_bits;\n", "file_path": "src/lib.rs", "rank": 13, "score": 104821.4368771918 }, { "content": "pub fn english_frequency_score(data: &[u8]) -> isize {\n\n let reference = \"etaoinsETAOINS \";\n\n\n\n let mut score = 0;\n\n data.to_vec().windows(3).for_each(|triplet| {\n\n let a = triplet[0] as char;\n\n let b = triplet[1] as char;\n\n let c = triplet[2] as char;\n\n\n\n if a == b {\n\n score -= 1;\n\n }\n\n if (a == b) && (b == c) {\n\n score -= 2;\n\n }\n\n if a != b && b != c && b == ' ' {\n\n score += 2;\n\n }\n\n\n\n if (a == '.' || a == ',') && b == ' ' {\n", "file_path": "src/lib.rs", "rank": 14, "score": 102170.95737434115 }, { "content": "pub fn hex_to_bytes(data: &str) -> Vec<u8> {\n\n let numbers = (b'0'..=b'9').collect::<Vec<u8>>();\n\n let lowers = (b'a'..=b'f').collect::<Vec<u8>>();\n\n let lookup = vec![numbers, lowers].concat();\n\n data.to_string()\n\n .to_ascii_lowercase()\n\n .bytes()\n\n .collect::<Vec<u8>>()\n\n .chunks(2)\n\n .map(|d| {\n\n let val_a = lookup.iter().position(|l| l == &d[0]).expect(\"first byte\");\n\n let val_b = lookup\n\n .iter()\n\n .position(|l| l == &d[1])\n\n .expect(\"uneven characters?\");\n\n (val_a * 16 + val_b) as u8\n\n })\n\n .collect::<Vec<u8>>()\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 15, "score": 99612.06268665097 }, { "content": "pub fn base64_to_bytes(data: &str) -> Vec<u8> {\n\n use std::cmp::min;\n\n\n\n let uppers = (b'A'..=b'Z').collect::<Vec<u8>>();\n\n let lowers = (b'a'..=b'z').collect::<Vec<u8>>();\n\n let numbers = (b'0'..=b'9').collect::<Vec<u8>>();\n\n let extras = vec![b'+', b'/'];\n\n let lookup = vec![uppers, lowers, numbers, extras].concat();\n\n\n\n let mut output = vec![];\n\n\n\n let mut filled_bits = 0;\n\n let mut carry = 0;\n\n for x in data.bytes() {\n\n let bits = lookup.iter().position(|l| l == &x);\n\n // skip newlines and such\n\n let bits = match bits {\n\n Some(b) => b,\n\n None => continue,\n\n } as u8;\n", "file_path": "src/lib.rs", "rank": 16, "score": 99612.06268665097 }, { "content": "fn convert_byte_vec_to_u32(mut bytes: Vec<u8>) -> Vec<u32> {\n\n bytes.shrink_to_fit();\n\n let num_bytes = bytes.len();\n\n let num_words = num_bytes / 4;\n\n unsafe {\n\n let words = Vec::from_raw_parts(bytes.as_mut_ptr() as *mut u32, num_words, num_words);\n\n mem::forget(bytes);\n\n words\n\n }\n\n}\n\n\n", "file_path": "src/md4.rs", "rank": 17, "score": 92762.45792490905 }, { "content": "#[inline(always)]\n\nfn as_block(input: &[u8]) -> &[u8; 64] {\n\n unsafe {\n\n assert!(input.len() == 64);\n\n let arr: &[u8; 64] = mem::transmute(input.as_ptr());\n\n arr\n\n }\n\n}\n\n\n\nimpl Default for Sha1 {\n\n fn default() -> Sha1 {\n\n Sha1::new()\n\n }\n\n}\n\n\n\nimpl Sha1 {\n\n /// Creates an fresh sha1 hash object.\n\n ///\n\n /// This is equivalent to creating a hash with `Default::default`.\n\n pub fn new() -> Sha1 {\n\n Sha1 {\n", "file_path": "src/sha1.rs", "rank": 18, "score": 85312.87749896166 }, { "content": "fn bits_from_byte(d: u8, a: u32, b: u32) -> u8 {\n\n assert!(a + b <= 8);\n\n assert!(b <= 8);\n\n d.rotate_left(a) >> (8 - b)\n\n}\n", "file_path": "src/lib.rs", "rank": 19, "score": 77346.51720403964 }, { "content": "#[test]\n\npub fn base64_to_bytes_works() {\n\n let result = base64_to_bytes(\"QQABAgNC//8=\");\n\n let reference = [b'A', 0x00, 0x01, 0x02, 0x03, b'B', 0xff, 0xff];\n\n assert_eq!(result, reference);\n\n\n\n let result = base64_to_bytes(\"sAAFlG0CAncq3weaDw==\");\n\n let reference = [\n\n 0xb0, 0x00, 0x05, 0x94, 0x6d, 0x02, 0x02, 0x77, 0x2a, 0xdf, 0x07, 0x9a, 0x0f,\n\n ];\n\n assert_eq!(result, reference);\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 20, "score": 76780.05968468015 }, { "content": "#[test]\n\npub fn bytes_to_hex_works() {\n\n assert_eq!(bytes_to_hex(&[0x00, 0x01, 0x02, 0x03, 0xff]), \"00010203ff\");\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 21, "score": 76780.05968468015 }, { "content": "pub fn load_stdin() -> String {\n\n let mut buffer = String::new();\n\n eprintln!(\"reading input from stdin...\");\n\n io::stdin().lock().read_to_string(&mut buffer).unwrap();\n\n buffer\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 22, "score": 74445.8590384547 }, { "content": "pub fn get_timestamp() -> std::time::Duration {\n\n SystemTime::now()\n\n .duration_since(UNIX_EPOCH)\n\n .expect(\"timetamp is broken\")\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 23, "score": 66682.95430746948 }, { "content": "#[test]\n\nfn test_mt19937() {\n\n use std::collections::HashMap;\n\n // matches output from:\n\n // http://burtleburtle.net/bob/c/readable.c\n\n let verification_data: HashMap<usize, u32> = [\n\n (0, 3331822403),\n\n (1, 157471482),\n\n (2, 2805605540),\n\n (3, 3776487808),\n\n (4, 3041352379),\n\n (5, 1684094076),\n\n (6, 1865610459),\n\n (7, 4068209049),\n\n (8, 1179506908),\n\n (9, 2512518870),\n\n (10, 3068092408),\n\n (100, 1155969921),\n\n (1000, 885714877),\n\n (9000, 270018718),\n\n (10000, 725707472),\n", "file_path": "src/mt19937.rs", "rank": 24, "score": 62551.2771435818 }, { "content": "pub trait SimdExt {\n\n fn simd_eq(self, rhs: Self) -> Self;\n\n}\n\n\n\nimpl SimdExt for fake::u32x4 {\n\n fn simd_eq(self, rhs: Self) -> Self {\n\n if self == rhs {\n\n fake::u32x4(0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff)\n\n } else {\n\n fake::u32x4(0, 0, 0, 0)\n\n }\n\n }\n\n}\n\n\n\nmod fake {\n\n use core::ops::{Add, BitAnd, BitOr, BitXor, Shl, Shr, Sub};\n\n\n\n #[derive(Clone, Copy, PartialEq, Eq)]\n\n #[allow(non_camel_case_types)]\n\n pub struct u32x4(pub u32, pub u32, pub u32, pub u32);\n", "file_path": "src/sha1.rs", "rank": 25, "score": 45255.656363250324 }, { "content": "#[test]\n\nfn hexbytes_works() {\n\n let test = vec![0x00, 0x01, 0x02, 0xff];\n\n let test2 = bytes_to_hexbytes(&test);\n\n let test3 = hexbytes_to_bytes(&test2);\n\n assert_eq!(test, test3);\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 26, "score": 36001.20198956437 }, { "content": "#[test]\n\nfn hex_to_bytes_works() {\n\n assert_eq!(\n\n hex_to_bytes(\"49276d206b00010203\".into()),\n\n [73, 39, 109, 32, 107, 0, 1, 2, 3]\n\n );\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 27, "score": 34753.4876429585 }, { "content": "#[test]\n\nfn bytes_to_base64_works() {\n\n let bytes = hex_to_bytes(\"49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d\".into());\n\n assert_eq!(\n\n bytes_to_base64(&bytes),\n\n \"SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t\"\n\n );\n\n\n\n assert_eq!(\n\n bytes_to_base64(&\"any carnal pleasure.\".bytes().collect::<Vec<_>>()),\n\n \"YW55IGNhcm5hbCBwbGVhc3VyZS4=\"\n\n );\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 28, "score": 34753.4876429585 }, { "content": "#[test]\n\nfn xor_arrays_works() {\n\n let first = hex_to_bytes(\"1c0111001f010100061a024b53535009181c\");\n\n let second = hex_to_bytes(\"686974207468652062756c6c277320657965\");\n\n let result = xor_arrays(&first, &second);\n\n let in_hex = bytes_to_hex(&result);\n\n assert_eq!(in_hex, \"746865206b696420646f6e277420706c6179\");\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 29, "score": 34753.4876429585 }, { "content": "#[test]\n\nfn bits_from_byte_works() {\n\n assert_eq!(bits_from_byte(43, 0, 2), 0);\n\n assert_eq!(bits_from_byte(43, 0, 8), 43);\n\n assert_eq!(bits_from_byte(43, 4, 4), 11);\n\n assert_eq!(bits_from_byte(43, 5, 3), 3);\n\n assert_eq!(bits_from_byte(73, 6, 2), 1);\n\n assert_eq!(bits_from_byte(73, 6, 2), 1);\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 30, "score": 34753.4876429585 }, { "content": "#[test]\n\nfn search_xor_key_works() {\n\n let data = \"LAgaCA9BAQQMCU0EDxEZGBwZBAVSDwAYDEFJUAgIHAUEEwYOGRhPSE1SHwkJTQYOEwdBAwtBFRoOQQ8fGBEGCg8NARgSBksIH00VDlIMAAUDQQABSwwZDglBGwUHAx8MAAYCDgJNABJSGw4fHggDHg5BDQ8OFAZLFQQIQQ4AAgYFAwANXksUAggPAgASERgIBUEWChUNTUlDAgcABQMVBAofQ0VDQSgGSwgfTRQSFw0UAE0VDlIIDgIeCAUXGUEYGg5BExgRCQ4VElIEB0wMAgkbDhcFAwZBBgMIH0NBNRoOQQoEExIGSwgfTQMTFwoKBQMGQQYDBEweGBIGDgxMj+H1Uh8JDRlBCAFLBQUeAg4EDhMFAwZBGgQWTBkJBFIODw8EEQkXGQwJAxVBAhkODwgSElIcDh4GEk9SPwkJTRIEEQQPCE0IElIYDgAbCA8VSxUECEEKFxJBGAUAFVICEkwYDwgDHgRMCw4TUgpBHAwTFRsIFAAME0EXBQIeFBEVFw9BAQgSEhMMBEwCE0EVGQ4ZHUEOFEsMCR4SABUOEkJn\";\n\n let data = base64_to_bytes(&data);\n\n let best_result = search_xor_key(&data, 7);\n\n\n\n let result_readable = String::from_utf8(best_result.2.clone()).unwrap();\n\n\n\n assert_eq!(best_result.1, [b'k', b'a', b'l', b'm', b'a', b'a', b'r']);\n\n assert!(result_readable.starts_with(\"Given some encrypted data (\\\"ciphertext\"));\n\n}\n", "file_path": "src/lib.rs", "rank": 32, "score": 33626.1033810134 }, { "content": "#[test]\n\nfn english_frequency_score_works() {\n\n let text = \"snniiiooooaaaaatttttteeeeeee \";\n\n let frequency_delta = english_frequency_score(text.to_string().as_bytes());\n\n assert_eq!(frequency_delta, -24);\n\n\n\n let text = \"Man is distinguished, not only by his reason, but by this singular passion from other animals,\n\nwhich is a lust of the mind, that by a perseverance of delight in the continued and indefatigable \n\ngeneration of knowledge, exceeds the short vehemence of any carnal pleasure.\";\n\n let frequency_delta = english_frequency_score(text.to_string().as_bytes());\n\n assert_eq!(frequency_delta, 166);\n\n\n\n let text = \"esto ia\";\n\n let frequency_delta = english_frequency_score(text.to_string().as_bytes());\n\n assert_eq!(frequency_delta, 7);\n\n\n\n let text = \"estonia hhhhrrrfffmmmlll\";\n\n let frequency_delta = english_frequency_score(text.to_string().as_bytes());\n\n assert_eq!(frequency_delta, -26);\n\n\n\n let text = \"We have students from different countries and continents gathered here to learn our language with you. At Totally English, you will make international friends and live fantastic learning adventures in the United Kingdom. Together, you will become more proficient in all areas of our language. Being fluent in English has become indispensable in the business area, so take your chance now and improve your skills with Totally English! Be more competitive in your job and see doors open left and right for you. English is the key!We have students from different countries and continents gathered here to learn our language with you. At Totally English, you will make international friends and live fantastic learning adventures in the United Kingdom. Together, you will become more proficient in all areas of our language. Being fluent in English has become indispensable in the business area, so take your chance now and improve your skills with Totally English! Be more competitive in your job and see doors open left and right for you. English is the key!\";\n\n let frequency_delta = english_frequency_score(text.to_string().as_bytes());\n\n assert_eq!(frequency_delta, 659);\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 35, "score": 33626.1033810134 }, { "content": "#[test]\n\nfn find_xor_key_eng_works() {\n\n let text = \"1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736\";\n\n let as_bytes = hex_to_bytes(text);\n\n let (_score, key, output) = find_xor_key_eng(&as_bytes);\n\n let output = String::from_utf8(output).unwrap();\n\n assert_eq!(key, 88);\n\n assert_eq!(output, \"Cooking MC's like a pound of bacon\");\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 37, "score": 32602.442937053864 }, { "content": "fn digest_to_str(digest: &[u32]) -> String {\n\n let mut s = String::new();\n\n for &word in digest {\n\n write!(&mut s, \"{:08x}\", word).unwrap();\n\n }\n\n s\n\n}\n", "file_path": "src/md4.rs", "rank": 38, "score": 30226.153675594163 }, { "content": "#[inline]\n\nfn sha1_first(w0: u32x4) -> u32 {\n\n w0.0\n\n}\n\n\n\n/// Not an intrinsic, but adds a word to the first element of a vector.\n", "file_path": "src/sha1.rs", "rank": 39, "score": 30226.153675594163 }, { "content": "/// Emulates `llvm.x86.sha1msg2` intrinsic.\n\nfn sha1msg2(a: u32x4, b: u32x4) -> u32x4 {\n\n let u32x4(x0, x1, x2, x3) = a;\n\n let u32x4(_, w13, w14, w15) = b;\n\n\n\n let w16 = (x0 ^ w13).rotate_left(1);\n\n let w17 = (x1 ^ w14).rotate_left(1);\n\n let w18 = (x2 ^ w15).rotate_left(1);\n\n let w19 = (x3 ^ w16).rotate_left(1);\n\n\n\n u32x4(w16, w17, w18, w19)\n\n}\n\n\n\n/// Emulates `llvm.x86.sha1nexte` intrinsic.\n", "file_path": "src/sha1.rs", "rank": 40, "score": 30150.959999119677 }, { "content": "/// Emulates `llvm.x86.sha1msg1` intrinsic.\n\nfn sha1msg1(a: u32x4, b: u32x4) -> u32x4 {\n\n let u32x4(_, _, w2, w3) = a;\n\n let u32x4(w4, w5, _, _) = b;\n\n a ^ u32x4(w2, w3, w4, w5)\n\n}\n\n\n", "file_path": "src/sha1.rs", "rank": 41, "score": 30150.959999119677 }, { "content": "// f(X,Y,Z) = XY v not(X)Z\n\nfn f(x: u32, y: u32, z: u32) -> u32 {\n\n (x & y) | (!x & z)\n\n}\n\n\n", "file_path": "src/md4.rs", "rank": 42, "score": 29291.302356088836 }, { "content": "// h(X,Y,Z) = X xor Y xor Z\n\nfn h(x: u32, y: u32, z: u32) -> u32 {\n\n x ^ y ^ z\n\n}\n\n\n\n// Round 1 macro\n\n// Let [A B C D i s] denote the operation\n\n// A = (A + f(B,C,D) + X[i]) <<< s\n\nmacro_rules! md4round1 {\n\n ( $a:expr, $b:expr, $c:expr, $d:expr, $i:expr, $s:expr, $x:expr) => {{\n\n // Rust defaults to non-overflowing arithmetic, so we need to specify wrapping add.\n\n $a = ($a.wrapping_add(f($b, $c, $d)).wrapping_add($x[$i])).rotate_left($s);\n\n }};\n\n}\n\n\n\n// Round 2 macro\n\n// Let [A B C D i s] denote the operation\n\n// A = (A + g(B,C,D) + X[i] + 5A827999) <<< s .\n\nmacro_rules! md4round2 {\n\n ( $a:expr, $b:expr, $c:expr, $d:expr, $i:expr, $s:expr, $x:expr) => {{\n\n $a = ($a\n", "file_path": "src/md4.rs", "rank": 43, "score": 29291.302356088836 }, { "content": "// g(X,Y,Z) = XY v XZ v YZ\n\nfn g(x: u32, y: u32, z: u32) -> u32 {\n\n (x & y) | (x & z) | (y & z)\n\n}\n\n\n", "file_path": "src/md4.rs", "rank": 44, "score": 29291.302356088836 }, { "content": "/// Not an intrinsic, but helps emulate `llvm.x86.sha1rnds4` intrinsic.\n\nfn sha1rnds4p(abcd: u32x4, msg: u32x4) -> u32x4 {\n\n let u32x4(mut a, mut b, mut c, mut d) = abcd;\n\n let u32x4(t, u, v, w) = msg;\n\n let mut e = 0u32;\n\n\n\n macro_rules! bool3ary_150 {\n\n ($a:expr, $b:expr, $c:expr) => {\n\n ($a ^ $b ^ $c)\n\n };\n\n } // Parity, XOR, MD5H, SHA1P\n\n\n\n e = e\n\n .wrapping_add(a.rotate_left(5))\n\n .wrapping_add(bool3ary_150!(b, c, d))\n\n .wrapping_add(t);\n\n b = b.rotate_left(30);\n\n\n\n d = d\n\n .wrapping_add(e.rotate_left(5))\n\n .wrapping_add(bool3ary_150!(a, b, c))\n", "file_path": "src/sha1.rs", "rank": 45, "score": 28193.677961599264 }, { "content": "/// Not an intrinsic, but helps emulate `llvm.x86.sha1rnds4` intrinsic.\n\nfn sha1rnds4m(abcd: u32x4, msg: u32x4) -> u32x4 {\n\n let u32x4(mut a, mut b, mut c, mut d) = abcd;\n\n let u32x4(t, u, v, w) = msg;\n\n let mut e = 0u32;\n\n\n\n macro_rules! bool3ary_232 {\n\n ($a:expr, $b:expr, $c:expr) => {\n\n ($a & $b) ^ ($a & $c) ^ ($b & $c)\n\n };\n\n } // Majority, SHA1M\n\n\n\n e = e\n\n .wrapping_add(a.rotate_left(5))\n\n .wrapping_add(bool3ary_232!(b, c, d))\n\n .wrapping_add(t);\n\n b = b.rotate_left(30);\n\n\n\n d = d\n\n .wrapping_add(e.rotate_left(5))\n\n .wrapping_add(bool3ary_232!(a, b, c))\n", "file_path": "src/sha1.rs", "rank": 46, "score": 28193.677961599264 }, { "content": "/// Not an intrinsic, but helps emulate `llvm.x86.sha1rnds4` intrinsic.\n\nfn sha1rnds4c(abcd: u32x4, msg: u32x4) -> u32x4 {\n\n let u32x4(mut a, mut b, mut c, mut d) = abcd;\n\n let u32x4(t, u, v, w) = msg;\n\n let mut e = 0u32;\n\n\n\n macro_rules! bool3ary_202 {\n\n ($a:expr, $b:expr, $c:expr) => {\n\n ($c ^ ($a & ($b ^ $c)))\n\n };\n\n } // Choose, MD5F, SHA1C\n\n\n\n e = e\n\n .wrapping_add(a.rotate_left(5))\n\n .wrapping_add(bool3ary_202!(b, c, d))\n\n .wrapping_add(t);\n\n b = b.rotate_left(30);\n\n\n\n d = d\n\n .wrapping_add(e.rotate_left(5))\n\n .wrapping_add(bool3ary_202!(a, b, c))\n", "file_path": "src/sha1.rs", "rank": 47, "score": 28193.677961599264 }, { "content": "#[inline]\n\nfn sha1_first_add(e: u32, w0: u32x4) -> u32x4 {\n\n let u32x4(a, b, c, d) = w0;\n\n u32x4(e.wrapping_add(a), b, c, d)\n\n}\n\n\n", "file_path": "src/sha1.rs", "rank": 48, "score": 27338.71623374519 }, { "content": "#[inline]\n\nfn sha1_first_half(abcd: u32x4, msg: u32x4) -> u32x4 {\n\n sha1_first_add(sha1_first(abcd).rotate_left(30), msg)\n\n}\n\n\n", "file_path": "src/sha1.rs", "rank": 49, "score": 26552.875292355464 }, { "content": "/// Emulates `llvm.x86.sha1rnds4` intrinsic.\n\n/// Performs 4 rounds of the message block digest.\n\nfn sha1_digest_round_x4(abcd: u32x4, work: u32x4, i: i8) -> u32x4 {\n\n const K0V: u32x4 = u32x4(K0, K0, K0, K0);\n\n const K1V: u32x4 = u32x4(K1, K1, K1, K1);\n\n const K2V: u32x4 = u32x4(K2, K2, K2, K2);\n\n const K3V: u32x4 = u32x4(K3, K3, K3, K3);\n\n\n\n match i {\n\n 0 => sha1rnds4c(abcd, work + K0V),\n\n 1 => sha1rnds4p(abcd, work + K1V),\n\n 2 => sha1rnds4m(abcd, work + K2V),\n\n 3 => sha1rnds4p(abcd, work + K3V),\n\n _ => panic!(\"unknown icosaround index\"),\n\n }\n\n}\n\n\n", "file_path": "src/sha1.rs", "rank": 50, "score": 24297.876979791086 }, { "content": "//extern crate cryptopals;\n\nuse std::num::Wrapping;\n\n\n\nconst N: u32 = 624;\n\nconst F: Wrapping<u32> = Wrapping(1812433253);\n\n\n\npub struct Mt19937 {\n\n state: [Wrapping<u32>; N as usize],\n\n index: u32,\n\n}\n\nimpl Mt19937 {\n\n pub fn from_seed(seed: u32) -> Mt19937 {\n\n let mut state = [Wrapping(0); N as usize];\n\n state[0] = Wrapping(seed);\n\n for i in 1..N as usize {\n\n state[i] = F * (state[i - 1] ^ (state[i - 1] >> 30)) + Wrapping(i as u32);\n\n }\n\n Mt19937 {\n\n state,\n\n index: N as u32,\n", "file_path": "src/mt19937.rs", "rank": 54, "score": 11.459322334549121 }, { "content": " (bits >> 56) as u8,\n\n (bits >> 48) as u8,\n\n (bits >> 40) as u8,\n\n (bits >> 32) as u8,\n\n (bits >> 24) as u8,\n\n (bits >> 16) as u8,\n\n (bits >> 8) as u8,\n\n (bits >> 0) as u8,\n\n ];\n\n let mut last = [0; 128];\n\n let blocklen = self.blocks.len as usize;\n\n last[..blocklen].clone_from_slice(&self.blocks.block[..blocklen]);\n\n last[blocklen] = 0x80;\n\n\n\n if blocklen < 56 {\n\n last[56..64].clone_from_slice(&extra);\n\n let out = last[0..64].to_vec();\n\n //println!(\"INNER digest used as last block: {:?}\", out);\n\n state.process(as_block(&last[0..64]));\n\n } else {\n", "file_path": "src/sha1.rs", "rank": 55, "score": 10.639133830643427 }, { "content": " (self.data.state[4] >> 0) as u8,\n\n ]\n\n }\n\n}\n\n\n\nimpl Blocks {\n\n fn input<F>(&mut self, mut input: &[u8], mut f: F)\n\n where\n\n F: FnMut(&[u8; 64]),\n\n {\n\n if self.len > 0 {\n\n let len = self.len as usize;\n\n let amt = cmp::min(input.len(), self.block.len() - len);\n\n self.block[len..len + amt].clone_from_slice(&input[..amt]);\n\n if len + amt == self.block.len() {\n\n f(&self.block);\n\n self.len = 0;\n\n input = &input[amt..];\n\n } else {\n\n self.len += amt as u32;\n", "file_path": "src/sha1.rs", "rank": 56, "score": 10.44819216228327 }, { "content": " }\n\n }\n\n\n\n pub fn from_state(state: [Wrapping<u32>; N as usize], index: u32) -> Mt19937 {\n\n Mt19937 { state, index }\n\n }\n\n\n\n pub fn extract_number(&mut self) -> u32 {\n\n if self.index >= N {\n\n self.twist();\n\n }\n\n let mut y: u32 = self.state[self.index as usize].0;\n\n y = self.temper(y);\n\n self.index += 1;\n\n y\n\n }\n\n\n\n fn temper(&self, num: u32) -> u32 {\n\n let mut num = num ^ num >> 11;\n\n num ^= num << 7 & 0x9D2C_5680;\n", "file_path": "src/mt19937.rs", "rank": 57, "score": 10.388521795989655 }, { "content": " num ^= num >> 22;\n\n\n\n num\n\n }\n\n\n\n fn twist(&mut self) {\n\n let upper_mask: Wrapping<u32> = Wrapping(0x8000_0000);\n\n let lower_mask: Wrapping<u32> = Wrapping(0x7fff_ffff);\n\n for i in 0..N as usize {\n\n let x = (self.state[i] & upper_mask) + (self.state[(i + 1) % N as usize] & lower_mask);\n\n let mut x_a: Wrapping<u32> = x >> 1;\n\n if x % Wrapping(2) != Wrapping(0) {\n\n x_a ^= Wrapping(0x9908_B0DF);\n\n }\n\n self.state[i] = self.state[(i + 397) % N as usize] ^ x_a;\n\n }\n\n self.index = 0;\n\n }\n\n}\n\n\n\n#[test]\n", "file_path": "src/mt19937.rs", "rank": 58, "score": 9.928109140688598 }, { "content": "impl hash::Hash for Blocks {\n\n fn hash<H: hash::Hasher>(&self, state: &mut H) {\n\n self.len.hash(state);\n\n self.block.hash(state);\n\n }\n\n}\n\n\n\nimpl Clone for Blocks {\n\n fn clone(&self) -> Blocks {\n\n Blocks { ..*self }\n\n }\n\n}\n\n\n\n/// Indicates that a digest couldn't be parsed.\n\n#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Debug)]\n\npub struct DigestParseError(());\n\n\n\nimpl fmt::Display for DigestParseError {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"not a valid sha1 hash\")\n", "file_path": "src/sha1.rs", "rank": 60, "score": 8.914232258979624 }, { "content": " pub fn update(&mut self, data: &[u8]) {\n\n let len = &mut self.len;\n\n let state = &mut self.state;\n\n self.blocks.input(data, |block| {\n\n *len += block.len() as u64;\n\n state.process(block);\n\n })\n\n }\n\n\n\n pub fn digest_now(data: &[u8]) -> Vec<u8> {\n\n let mut sha1 = Sha1::new();\n\n sha1.update(data);\n\n sha1.digest().bytes().to_vec()\n\n }\n\n\n\n /// Retrieve digest result.\n\n pub fn digest(&self) -> Digest {\n\n let mut state = self.state;\n\n let bits = (self.len + (self.blocks.len as u64)) * 8;\n\n let extra = [\n", "file_path": "src/sha1.rs", "rank": 61, "score": 8.41682833381891 }, { "content": "use core::str;\n\n\n\n/// The length of a SHA1 digest in bytes\n\npub const DIGEST_LENGTH: usize = 20;\n\n\n\n/// Represents a Sha1 hash object in memory.\n\n#[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]\n\npub struct Sha1 {\n\n state: Sha1State,\n\n blocks: Blocks,\n\n len: u64,\n\n}\n\n\n", "file_path": "src/sha1.rs", "rank": 62, "score": 8.416309251139474 }, { "content": "\n\n use self::std::prelude::v1::*;\n\n\n\n use Sha1;\n\n\n\n #[test]\n\n fn test_simple() {\n\n let mut m = Sha1::new();\n\n\n\n let tests = [\n\n (\"The quick brown fox jumps over the lazy dog\",\n\n \"2fd4e1c67a2d28fced849ee1bb76e7391b93eb12\"),\n\n (\"The quick brown fox jumps over the lazy cog\",\n\n \"de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3\"),\n\n (\"\", \"da39a3ee5e6b4b0d3255bfef95601890afd80709\"),\n\n (\"testing\\n\", \"9801739daae44ec5293d4e1f53d3f4d2d426d91c\"),\n\n (\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\n\n \"025ecbd5d70f8fb3c5457cd96bab13fda305dc59\"),\n\n (\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\n\n \"4300320394f7ee239bcdce7d3b8bcee173a0cd5c\"),\n", "file_path": "src/sha1.rs", "rank": 63, "score": 7.945956169179095 }, { "content": "extern crate openssl;\n\n\n\nuse crate::sha1::Sha1;\n\nuse num_bigint::{BigInt, BigUint, RandBigInt, ToBigInt, ToBigUint};\n\n\n\npub struct DSA {\n\n pub p: BigInt,\n\n pub q: BigInt,\n\n pub g: BigInt,\n\n pub pubkey: BigInt,\n\n pub privkey: BigInt,\n\n}\n\n\n\nconst DEFAULT_P: &[u8] = b\"800000000000000089e1855218a0e7dac38136ffafa72eda7\\\n\n 859f2171e25e65eac698c1702578b07dc2a1076da241c76c6\\\n\n 2d374d8389ea5aeffd3226a0530cc565f3bf6b50929139ebe\\\n\n ac04f48c3c84afb796d61e5a4f9a8fda812ab59494232c7d2\\\n\n b4deb50aa18ee9e132bfa85ac4374d7f9091abc3d015efc87\\\n\n 1a584471bb1\";\n\nconst DEFAULT_Q: &[u8] = b\"f4f47f05794b256174bba6e9b396a7707e563c5b\";\n", "file_path": "src/dsa.rs", "rank": 64, "score": 7.9058328667625695 }, { "content": " }\n\n\n\n #[test]\n\n fn spray_and_pray() {\n\n use self::rand::Rng;\n\n\n\n let mut rng = rand::thread_rng();\n\n let mut m = Sha1::new();\n\n let mut bytes = [0; 512];\n\n\n\n for _ in 0..20 {\n\n let ty = openssl::hash::MessageDigest::sha1();\n\n let mut r = openssl::hash::Hasher::new(ty).unwrap();\n\n m.reset();\n\n for _ in 0..50 {\n\n let len = rng.gen::<usize>() % bytes.len();\n\n rng.fill_bytes(&mut bytes[..len]);\n\n m.update(&bytes[..len]);\n\n r.update(&bytes[..len]).unwrap();\n\n }\n", "file_path": "src/sha1.rs", "rank": 65, "score": 7.818020264360822 }, { "content": "# cryptopals\n\nSolving the Cryptopals.com challenges\n\n\n\ns1c1-s1c3\n\n---\n\nimplemented in lib.rs as functions (with tests)\n\n\n\ns1c4\n\n---\n\ncargo run --bin detect_singlechar_xor < res/s1c4.txt\n\n\n\ns1c5\n\n---\n\ncargo run --bin xor_encrypt ICE < res/s1c5.txt\n\n\n\ns1c6 (find xor key)\n\n---\n\ncargo run --release --bin find_xor_key 30 < res/s1c6.txt\n\n\n\ns1c7 (decrypt aes-ecb)\n\n---\n\ncargo run --release --bin decrypt_aes_ecb \"YELLOW SUBMARINE\" < res/s1c7.txt\n\n\n\ns1c8 (detect ecb mode from lines)\n\n---\n\ncargo run --release --bin detect_ecb_mode < res/s1c8.txt\n\n\n\ns2c9 (pkcs7 padding)\n\n---\n\ncreated into block_ciphers.rs\n\n\n\ns2c10 (decrypt aes-cbc)\n\n---\n\ncargo run --bin decrypt_aes_cbc \"YELLOW SUBMARINE\" < res/s2c10.txt\n\n\n\ns2c11 (cbs vs ecb oracle)\n\n---\n\ncargo run --bin oracle_cbc_ecb\n\n\n\ns2c12 (byte-a-time ecb decrypt simple)\n\n---\n\ncargo run --release --bin break_ecb_byte_simple < res/s2c12.txt\n\n\n\ns2c13 (ecb cut and paste cookie)\n\n---\n\ncargo run --bin ecb_cut_and_paste\n\n\n\ns2c14 (byte-a-time ecb decrypt harder)\n\n---\n\ncargo run --release --bin break_ecb_byte_harder < res/s2c12.txt\n\n\n\ns2c16 (cbc bitlipping attack)\n\n---\n\ncargo run --bin cbc_bitflipping\n\n\n\ns3c17 (cbc padding oracle)\n\n---\n\n# FIXME: I do not decrypt the first block, add a virtual empty block before the first one?\n\ncargo run --bin cbc_padding_oracle < res/s3c17.txt\n\n\n\ns3c18 (ctr mode)\n\n---\n\ncreated into block_ciphers.rs\n\n\n\ns3c19 (ctr break substitutions - dumb)\n\n---\n\ncargo run --bin break_ctr_dumb < res/s3c19.txt\n\n\n\ns3c20 (ctr break sattistic - smart) actually same as previous\n\n---\n\ncargo run --bin break_ctr_smart < res/s3c20.txt\n\n\n\ns3c21 (mt19937)\n\n---\n\nimplemented into lib under mt19937.rs\n\n\n\ns3c22 (mt19937 epoch seed crack)\n\n---\n\ncargo run --release --bin s3c22_mt19937_wait_crack\n\n\n\ns3c23 (mt19937 clone from output)\n\n---\n\ncargo run --release --bin s3c23_clone_mt19937\n\n\n\ns3c24 (mt19937 stream cipher + crack)\n\n---\n\n`cargo run --release --bin s3c24_mt19937_cipher`\n\n\n\ns4c25 (aes_ctr_random_rw_break)\n\n---\n\n`cargo run --release --bin s4c25_aes_ctr_random_rw_break < res/s4c25.txt`\n\n\n\ns4c26\n\n---\n\n`cargo run --release --bin s4c26_ctr_bitflipping`\n\n\n", "file_path": "README.md", "rank": 66, "score": 7.638759684788892 }, { "content": " extern crate std;\n\n extern crate serde_json;\n\n\n\n use self::std::prelude::v1::*;\n\n\n\n use {Sha1, Digest};\n\n\n\n #[test]\n\n fn test_to_json() {\n\n let mut s = Sha1::new();\n\n s.update(b\"Hello World!\");\n\n let x = s.digest();\n\n let y = serde_json::to_vec(&x).unwrap();\n\n assert_eq!(y, &b\"\\\"2ef7bde608ce5404e97d5f042f95f89f1c232871\\\"\"[..]);\n\n }\n\n\n\n #[test]\n\n fn test_from_json() {\n\n let y: Digest = serde_json::from_str(\"\\\"2ef7bde608ce5404e97d5f042f95f89f1c232871\\\"\").unwrap();\n\n assert_eq!(y.to_string(), \"2ef7bde608ce5404e97d5f042f95f89f1c232871\");\n", "file_path": "src/sha1.rs", "rank": 68, "score": 7.18444494223804 }, { "content": " if state == 1 && cur_byte == &0xff_u8 && next_byte == 0x00_u8 {\n\n // take the 64 bytes of digest\n\n let provided_digest: &[u8] = &padded_sig[i + 2..i + 2 + 32];\n\n let calced_digest: &[u8] = &Sha256::digest(&m.to_bytes_be());\n\n return provided_digest == calced_digest;\n\n }\n\n }\n\n false\n\n }\n\n\n\n pub fn encrypt(&self, m: &BigUint) -> BigUint {\n\n m.modpow(&self.e, &self.n)\n\n }\n\n\n\n pub fn decrypt(&self, c: &BigUint) -> BigUint {\n\n c.modpow(&self.d, &self.n)\n\n }\n\n\n\n pub fn gen_big_prime(bits: i32) -> BigUint {\n\n use openssl::bn::BigNum;\n", "file_path": "src/rsa.rs", "rank": 69, "score": 7.093468140826138 }, { "content": " self.0 >> rhs.0,\n\n self.1 >> rhs.1,\n\n self.2 >> rhs.2,\n\n self.3 >> rhs.3,\n\n )\n\n }\n\n }\n\n\n\n #[derive(Clone, Copy)]\n\n #[allow(non_camel_case_types)]\n\n pub struct u64x2(pub u64, pub u64);\n\n\n\n impl Add for u64x2 {\n\n type Output = u64x2;\n\n\n\n fn add(self, rhs: u64x2) -> u64x2 {\n\n u64x2(self.0.wrapping_add(rhs.0), self.1.wrapping_add(rhs.1))\n\n }\n\n }\n\n}\n", "file_path": "src/sha1.rs", "rank": 70, "score": 6.900308910071147 }, { "content": "\n\n#[cfg(feature = \"serde\")]\n\nimpl serde::ser::Serialize for Digest {\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: serde::ser::Serializer,\n\n {\n\n fn to_hex(num: u8) -> u8 {\n\n b\"0123456789abcdef\"[num as usize]\n\n }\n\n\n\n let mut hex_str = [0u8; 40];\n\n let mut c = 0;\n\n for state in self.data.state.iter() {\n\n for off in 0..4 {\n\n let byte = (state >> (8 * (3 - off))) as u8;\n\n hex_str[c] = to_hex(byte >> 4);\n\n hex_str[c + 1] = to_hex(byte & 0xf);\n\n c += 2;\n\n }\n", "file_path": "src/sha1.rs", "rank": 71, "score": 6.879778416183777 }, { "content": " pub fn pad_pkcs_1_5(&self, m: &[u8]) -> Vec<u8> {\n\n let m_b = m.len();\n\n let k = self.n.to_bytes_be().len();\n\n let ps_len = k - 3 - m_b;\n\n assert!(m_b <= k - 11);\n\n\n\n let mut random_bytes = vec![];\n\n let mut rng = rand::thread_rng();\n\n\n\n // correct way to get unbiased random bytes\n\n while random_bytes.len() < ps_len {\n\n let b: u8 = rng.gen();\n\n if b == 0x00 {\n\n continue;\n\n }\n\n random_bytes.push(b);\n\n }\n\n\n\n vec![\n\n [0x00, 0x02].to_vec(),\n", "file_path": "src/rsa.rs", "rank": 72, "score": 6.817432936350897 }, { "content": " let S = match attack {\n\n None => (B - (k * (g.modpow(&x, &N)))).modpow(&(dh.secret + (u * x)), &N),\n\n Some(_) => 0.to_biguint().unwrap(),\n\n };\n\n println!(\"client got S: {}\", S);\n\n\n\n let K: &[u8] = &Sha256::digest(&S.to_bytes_be());\n\n\n\n /*\n\n send our HMAC(K, salt) to server for verification\n\n */\n\n let hmac = Sha256::digest(&vec![K, &server_salt.to_bytes_be()].concat());\n\n stream.write_all(&bytes_to_hexbytes(&hmac)).unwrap();\n\n\n\n /*\n\n read final \"OK\" or \"FAIL\"\n\n */\n\n let mut buffer = [0_u8; 2048];\n\n let _ = stream.read(&mut buffer).unwrap();\n\n if buffer[0] == 'O' as u8 {\n\n true\n\n } else {\n\n false\n\n }\n\n }\n\n}\n", "file_path": "src/srp.rs", "rank": 73, "score": 6.631716056249456 }, { "content": "// reexport block_cipher stuff for cryptopals crate users\n\npub mod block_ciphers;\n\npub mod dh;\n\npub mod dsa;\n\npub mod md4;\n\npub mod mt19937;\n\npub mod rsa;\n\npub mod sha1;\n\npub mod srp;\n\npub mod weakened_srp;\n\n\n\nuse rand::Rng;\n\nuse std::io::{self, Read};\n\nuse std::time::{SystemTime, UNIX_EPOCH};\n\n\n", "file_path": "src/lib.rs", "rank": 74, "score": 6.590528491238993 }, { "content": "use num_bigint::{BigUint, RandBigInt};\n\n\n\npub struct DiffieHellmanState {\n\n pub secret: BigUint,\n\n p: BigUint,\n\n g: BigUint,\n\n pub pubkey: BigUint,\n\n}\n\n\n\nimpl DiffieHellmanState {\n\n pub fn new(g: &BigUint, p: &BigUint) -> DiffieHellmanState {\n\n let secret = rand::thread_rng().gen_biguint_below(&p);\n\n let pubkey = DiffieHellmanState::gen_pubkey(&p, &g, &secret);\n\n DiffieHellmanState {\n\n secret,\n\n p: p.clone(),\n\n g: g.clone(),\n\n pubkey,\n\n }\n\n }\n", "file_path": "src/dh.rs", "rank": 75, "score": 6.5252248376520745 }, { "content": " }\n\n\n\n fn handle_connection(&self, mut stream: TcpStream) {\n\n let dh = if !self.attack {\n\n DiffieHellmanState::new(&self.g, &self.N)\n\n } else {\n\n let secret = 2.to_biguint().unwrap();\n\n DiffieHellmanState::new_static(&self.g, &self.N, &secret)\n\n };\n\n\n\n /*\n\n read username+DH_pubkey\n\n */\n\n\n\n let mut buffer = [0; 1024];\n\n let read_bytes = stream.read(&mut buffer).unwrap();\n\n let data = buffer[..read_bytes].to_vec();\n\n let mut tokens = data.splitn(2, |x| x == &0x00_u8);\n\n\n\n let username = String::from_utf8(tokens.next().unwrap().to_vec()).unwrap();\n", "file_path": "src/weakened_srp.rs", "rank": 76, "score": 6.520560419501443 }, { "content": "\n\npub struct WeakenedSRPClient {}\n\n\n\nimpl WeakenedSRPClient {\n\n pub fn auth(\n\n connstring: String,\n\n N: BigUint,\n\n g: BigUint,\n\n k: BigUint,\n\n username: String,\n\n password: String,\n\n ) -> bool {\n\n let mut stream = TcpStream::connect(connstring).unwrap();\n\n\n\n /*\n\n send username and DH pubkey\n\n */\n\n\n\n let dh = DiffieHellmanState::new(&g, &N);\n\n let A = dh.pubkey;\n", "file_path": "src/weakened_srp.rs", "rank": 77, "score": 6.489687607040546 }, { "content": "\n\n UserSRP { v, salt }\n\n }\n\n}\n\n\n\npub struct SRPClient {}\n\n\n\nimpl SRPClient {\n\n pub fn auth(\n\n connstring: String,\n\n N: BigUint,\n\n g: BigUint,\n\n k: BigUint,\n\n username: String,\n\n password: String,\n\n attack: &Option<BigUint>,\n\n ) -> bool {\n\n let mut stream = TcpStream::connect(connstring).unwrap();\n\n\n\n /*\n", "file_path": "src/srp.rs", "rank": 78, "score": 6.169256388555466 }, { "content": "//\n\n// Copied from https://rosettacode.org/wiki/MD4#Rust\n\n//\n\n// MD4, based on RFC 1186 and RFC 1320.\n\n//\n\n// https://www.ietf.org/rfc/rfc1186.txt\n\n// https://tools.ietf.org/html/rfc1320\n\n//\n\n\n\nuse std::fmt::Write;\n\nuse std::mem;\n\n\n\n// Let not(X) denote the bit-wise complement of X.\n\n// Let X v Y denote the bit-wise OR of X and Y.\n\n// Let X xor Y denote the bit-wise XOR of X and Y.\n\n// Let XY denote the bit-wise AND of X and Y.\n\n\n\n// f(X,Y,Z) = XY v not(X)Z\n", "file_path": "src/md4.rs", "rank": 79, "score": 6.13046394766792 }, { "content": " }\n\n\n\n /// Shortcut to create a sha1 from some bytes.\n\n ///\n\n /// This also lets you create a hash from a utf-8 string. This is equivalent\n\n /// to making a new Sha1 object and calling `update` on it once.\n\n pub fn from<D: AsRef<[u8]>>(data: D) -> Sha1 {\n\n let mut rv = Sha1::new();\n\n rv.update(data.as_ref());\n\n rv\n\n }\n\n\n\n /// Resets the hash object to it's initial state.\n\n pub fn reset(&mut self) {\n\n self.state = DEFAULT_STATE;\n\n self.len = 0;\n\n self.blocks.len = 0;\n\n }\n\n\n\n /// Update hash with input data.\n", "file_path": "src/sha1.rs", "rank": 80, "score": 6.096185078747202 }, { "content": " stream.write_all(&bytes_to_hexbytes(hmac)).unwrap();\n\n\n\n /*\n\n read final \"OK\" or \"FAIL\"\n\n */\n\n\n\n let mut buffer = [0_u8; 2048];\n\n let _ = stream.read(&mut buffer).unwrap();\n\n buffer[0] == 'O' as u8\n\n }\n\n}\n", "file_path": "src/weakened_srp.rs", "rank": 81, "score": 6.023354056320512 }, { "content": "extern crate openssl;\n\n\n\nuse rand::prelude::*;\n\n\n\nuse num_bigint::{BigInt, BigUint, RandBigInt, ToBigInt, ToBigUint};\n\nuse sha2::{Digest, Sha256};\n\n\n\npub struct RSA {\n\n pub e: BigUint,\n\n pub n: BigUint,\n\n pub d: BigUint,\n\n pub pubkey: (BigUint, BigUint),\n\n privkey: (BigUint, BigUint),\n\n}\n\n\n\nimpl RSA {\n\n pub fn new(bits: i32) -> RSA {\n\n let big_1 = &1.to_biguint().unwrap();\n\n\n\n let e = &3.to_biguint().unwrap();\n", "file_path": "src/rsa.rs", "rank": 82, "score": 5.987354004681382 }, { "content": " (100000, 3292829284),\n\n ]\n\n .iter()\n\n .cloned()\n\n .collect();\n\n\n\n let largest_test = verification_data.keys().max().expect(\"need some tests\");\n\n\n\n let mut mt = Mt19937::from_seed(0x12345678u32);\n\n for i in 0..=*largest_test {\n\n let out_num = mt.extract_number();\n\n if let Some(verification_num) = verification_data.get(&i) {\n\n assert_eq!(out_num, *verification_num);\n\n }\n\n }\n\n\n\n // test tempering\n\n let tempered_1 = mt.temper(42);\n\n assert_eq!(42, mt.untemper(tempered_1));\n\n\n\n let tempered_2 = mt.temper(0xff112233);\n\n assert_eq!(0xff112233, mt.untemper(tempered_2));\n\n}\n", "file_path": "src/mt19937.rs", "rank": 83, "score": 5.8938094581970555 }, { "content": " let v = &self.g.modpow(x, &self.N);\n\n\n\n let S = (&A * v.modpow(&BigUint::from_bytes_be(fake_u), &self.N))\n\n .modpow(&dh.secret, &self.N);\n\n let K: &[u8] = &Sha256::digest(&S.to_bytes_be());\n\n let guessed_hmac: &[u8] = &Sha256::digest(&vec![K, fake_salt].concat());\n\n if guessed_hmac == client_hmac {\n\n println!(\"\\n!!!!cracked password: {}\\n\", &password);\n\n }\n\n }\n\n }\n\n\n\n /*\n\n proceed with our calculations\n\n */\n\n\n\n let S = (&A * user_v.modpow(&u, &self.N)).modpow(&dh.secret, &self.N);\n\n let K: &[u8] = &Sha256::digest(&S.to_bytes_be());\n\n\n\n let server_hmac = Sha256::digest(&vec![K, &user_salt.to_bytes_be()].concat());\n", "file_path": "src/weakened_srp.rs", "rank": 84, "score": 5.696340079737459 }, { "content": " last[120..128].clone_from_slice(&extra);\n\n state.process(as_block(&last[0..64]));\n\n state.process(as_block(&last[64..128]));\n\n }\n\n\n\n Digest { data: state }\n\n }\n\n\n\n /// Retrieve the digest result as hex string directly.\n\n ///\n\n /// (The function is only available if the `std` feature is enabled)\n\n #[cfg(feature = \"std\")]\n\n pub fn hexdigest(&self) -> std::string::String {\n\n self.digest().to_string()\n\n }\n\n}\n\n\n\nimpl Digest {\n\n /// Returns the 160 bit (20 byte) digest as a byte array.\n\n pub fn bytes(&self) -> [u8; DIGEST_LENGTH] {\n", "file_path": "src/sha1.rs", "rank": 85, "score": 5.369869696698622 }, { "content": " assert_eq!(r.finish().unwrap().as_ref(), &m.digest().bytes());\n\n }\n\n }\n\n\n\n #[test]\n\n #[cfg(feature=\"std\")]\n\n fn test_parse() {\n\n use Digest;\n\n use std::error::Error;\n\n let y: Digest = \"2ef7bde608ce5404e97d5f042f95f89f1c232871\".parse().unwrap();\n\n assert_eq!(y.to_string(), \"2ef7bde608ce5404e97d5f042f95f89f1c232871\");\n\n assert!(\"asdfasdf\".parse::<Digest>().is_err());\n\n assert_eq!(\"asdfasdf\".parse::<Digest>()\n\n .map_err(|x| x.description().to_string()).unwrap_err(), \"not a valid sha1 hash\");\n\n }\n\n}\n\n\n\n#[cfg_attr(rustfmt, rustfmt_skip)]\n\n#[cfg(all(test, feature=\"serde\"))]\n\nmod serde_tests {\n", "file_path": "src/sha1.rs", "rank": 86, "score": 5.0965902894631165 }, { "content": " let mut buffer = [0; 1024];\n\n let read_bytes = stream.read(&mut buffer).unwrap();\n\n let payload = &buffer[..read_bytes];\n\n\n\n if hexbytes_to_bytes(payload) == etalon.as_slice() {\n\n stream.write_all(b\"OK\").unwrap();\n\n } else {\n\n stream.write_all(b\"FAIL\").unwrap();\n\n }\n\n }\n\n\n\n fn calc_user_srp(g: &BigUint, N: &BigUint, password: &str) -> UserSRP {\n\n let salt = rand::thread_rng().gen_biguint_below(N);\n\n\n\n let mut hasher = Sha256::new();\n\n hasher.update(salt.to_bytes_be());\n\n hasher.update(password);\n\n\n\n let x = BigUint::from_bytes_be(&hasher.finalize());\n\n let v = g.modpow(&x, N);\n", "file_path": "src/srp.rs", "rank": 87, "score": 4.992266786172178 }, { "content": "\n\n pub fn new_static(g: &BigUint, p: &BigUint, secret: &BigUint) -> DiffieHellmanState {\n\n let pubkey = DiffieHellmanState::gen_pubkey(&p, &g, &secret);\n\n DiffieHellmanState {\n\n secret: secret.clone(),\n\n p: p.clone(),\n\n g: g.clone(),\n\n pubkey,\n\n }\n\n }\n\n\n\n pub fn gen_shared_key(self, other_pubkey: &BigUint) -> BigUint {\n\n other_pubkey.modpow(&self.secret, &self.p)\n\n }\n\n\n\n fn gen_pubkey(p: &BigUint, g: &BigUint, secret: &BigUint) -> BigUint {\n\n g.modpow(secret, p)\n\n }\n\n}\n", "file_path": "src/dh.rs", "rank": 88, "score": 4.908216851396576 }, { "content": " stream\n\n .write_all(\n\n &vec![\n\n username.as_bytes(),\n\n &[0x00],\n\n &bytes_to_hexbytes(&A.to_bytes_be()),\n\n ]\n\n .concat(),\n\n )\n\n .unwrap();\n\n\n\n /*\n\n read salt+B from server\n\n */\n\n\n\n let mut buffer = [0; 2048];\n\n let read_bytes = stream.read(&mut buffer).unwrap();\n\n let data = buffer[..read_bytes].to_vec();\n\n let mut tokens = data.splitn(3, |x| x == &0x00_u8);\n\n\n", "file_path": "src/weakened_srp.rs", "rank": 89, "score": 4.788144711476588 }, { "content": " let mut b = b.clone();\n\n\n\n while a != 0.to_bigint().unwrap() {\n\n let (q, _a) = (&b / &a, &b % &a);\n\n b = a;\n\n a = _a;\n\n let (_y0, _y1) = (&y1, &y0 - (&q * &y1));\n\n y0 = _y0.clone();\n\n y1 = _y1;\n\n let (_x0, _x1) = (&x1, &x0 - (&q * &x1));\n\n x0 = _x0.clone();\n\n x1 = _x1;\n\n }\n\n (b, x0, y0)\n\n }\n\n\n\n fn egcd(a: &BigInt, b: &BigInt) -> (BigInt, BigInt, BigInt) {\n\n if a == &0.to_bigint().unwrap() {\n\n return (b.clone(), 0.to_bigint().unwrap(), 1.to_bigint().unwrap());\n\n }\n", "file_path": "src/rsa.rs", "rank": 90, "score": 4.769502938484949 }, { "content": " let mut users_srp: HashMap<String, UserSRP> = HashMap::new();\n\n for (username, password) in users.iter() {\n\n let srp_params = SRPServer::calc_user_srp(&g, &N, password);\n\n users_srp.insert(username.to_string(), srp_params);\n\n }\n\n let server = SRPServer { N, g, k, users_srp };\n\n thread::spawn(move || {\n\n let listener = TcpListener::bind(connstring).unwrap();\n\n for stream in listener.incoming() {\n\n server.handle_connection(stream.unwrap());\n\n }\n\n });\n\n }\n\n\n\n fn handle_connection(&self, mut stream: TcpStream) {\n\n let dh = DiffieHellmanState::new(&self.g, &self.N);\n\n /*\n\n read username+DH_pubkey\n\n */\n\n let mut buffer = [0; 1024];\n", "file_path": "src/srp.rs", "rank": 91, "score": 4.715405743019177 }, { "content": " let mut big = BigNum::new().unwrap();\n\n\n\n big.generate_prime(bits, true, None, None).unwrap();\n\n let prime_bytes = big.to_vec();\n\n BigUint::from_bytes_be(&prime_bytes)\n\n }\n\n\n\n /*\n\n unusded\n\n alternative to egcd\n\n */\n\n fn _xgcd(a: &BigInt, b: &BigInt) -> (BigInt, BigInt, BigInt) {\n\n let (mut x0, mut x1, mut y0, mut y1) = (\n\n 0.to_bigint().unwrap(),\n\n 1.to_bigint().unwrap(),\n\n 1.to_bigint().unwrap(),\n\n 0.to_bigint().unwrap(),\n\n );\n\n\n\n let mut a = a.clone();\n", "file_path": "src/rsa.rs", "rank": 92, "score": 4.692957560191009 }, { "content": " random_bytes,\n\n [0x00].to_vec(),\n\n m.to_vec(),\n\n ]\n\n .concat()\n\n }\n\n\n\n /*\n\n this function is 100% fake and does just enough to do the task\n\n */\n\n pub fn verify(&self, m: &BigUint, sig: &BigUint) -> bool {\n\n let padded_sig = self.encrypt(sig).to_bytes_be();\n\n let mut state = 0;\n\n for (i, cur_byte) in padded_sig.iter().enumerate() {\n\n let next_byte = padded_sig[i + 1];\n\n if state == 0 {\n\n assert_eq!(&0x01_u8, cur_byte);\n\n state = 1;\n\n continue;\n\n }\n", "file_path": "src/rsa.rs", "rank": 93, "score": 4.678502489065998 }, { "content": "\n\n let h = \"2fd4e1c67a2d28fced849ee1bb76e7391b93eb12\";\n\n assert_eq!(hh.len(), h.len());\n\n assert_eq!(hh, &*h);\n\n }\n\n\n\n #[test]\n\n fn test_sha1_loop() {\n\n let mut m = Sha1::new();\n\n let s = \"The quick brown fox jumps over the lazy dog.\";\n\n let n = 1000u64;\n\n\n\n for _ in 0..3 {\n\n m.reset();\n\n for _ in 0..n {\n\n m.update(s.as_bytes());\n\n }\n\n assert_eq!(m.digest().to_string(),\n\n \"7ca27655f67fceaa78ed2e645a81c7f1d6e249d2\");\n\n }\n", "file_path": "src/sha1.rs", "rank": 94, "score": 4.666053344037788 }, { "content": " }\n\n}\n\n\n\n// Copyright (c) 2006-2009 Graydon Hoare\n\n// Copyright (c) 2009-2013 Mozilla Foundation\n\n\n\n// Permission is hereby granted, free of charge, to any\n\n// person obtaining a copy of this software and associated\n\n// documentation files (the \"Software\"), to deal in the\n\n// Software without restriction, including without\n\n// limitation the rights to use, copy, modify, merge,\n\n// publish, distribute, sublicense, and/or sell copies of\n\n// the Software, and to permit persons to whom the Software\n\n// is furnished to do so, subject to the following\n\n// conditions:\n\n\n\n// The above copyright notice and this permission notice\n\n// shall be included in all copies or substantial portions\n\n// of the Software.\n\n\n", "file_path": "src/sha1.rs", "rank": 95, "score": 4.565573982826924 }, { "content": " .map_err(|_| DigestParseError(()))?;\n\n }\n\n Ok(rv)\n\n }\n\n}\n\n\n\nimpl fmt::Display for Digest {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n for i in self.data.state.iter() {\n\n write!(f, \"{:08x}\", i)?;\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl fmt::Debug for Digest {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"Digest {{ \\\"{}\\\" }}\", self)\n\n }\n\n}\n", "file_path": "src/sha1.rs", "rank": 96, "score": 4.479059206514475 }, { "content": "// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\n\n// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n\n// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n\n// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n\n// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\n\n// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\n// DEALINGS IN THE SOFTWARE.\n\n\n\npub use self::fake::*;\n\n\n", "file_path": "src/sha1.rs", "rank": 97, "score": 4.3288222745563525 }, { "content": " }\n\n\n\n // Everything after this operates on 32-bit words, so reinterpret the buffer.\n\n let mut w = convert_byte_vec_to_u32(bytes.clone());\n\n\n\n // Step 2. Append length\n\n // A 64-bit representation of b (the length of the message before the padding bits were added)\n\n // is appended to the result of the previous step, low-order bytes first.\n\n w.push(initial_bit_len as u32); // Push low-order bytes first\n\n w.push((initial_bit_len >> 32) as u32);\n\n\n\n // Step 3. Initialize MD buffer\n\n let (mut a, mut b, mut c, mut d) = match inner_state {\n\n Some(is) => (is[0], is[1], is[2], is[3]),\n\n None => (\n\n 0x67452301_u32,\n\n 0xefcdab89_u32,\n\n 0x98badcfe_u32,\n\n 0x10325476_u32,\n\n ),\n", "file_path": "src/md4.rs", "rank": 98, "score": 4.205034574786506 }, { "content": " [\n\n (self.data.state[0] >> 24) as u8,\n\n (self.data.state[0] >> 16) as u8,\n\n (self.data.state[0] >> 8) as u8,\n\n (self.data.state[0] >> 0) as u8,\n\n (self.data.state[1] >> 24) as u8,\n\n (self.data.state[1] >> 16) as u8,\n\n (self.data.state[1] >> 8) as u8,\n\n (self.data.state[1] >> 0) as u8,\n\n (self.data.state[2] >> 24) as u8,\n\n (self.data.state[2] >> 16) as u8,\n\n (self.data.state[2] >> 8) as u8,\n\n (self.data.state[2] >> 0) as u8,\n\n (self.data.state[3] >> 24) as u8,\n\n (self.data.state[3] >> 16) as u8,\n\n (self.data.state[3] >> 8) as u8,\n\n (self.data.state[3] >> 0) as u8,\n\n (self.data.state[4] >> 24) as u8,\n\n (self.data.state[4] >> 16) as u8,\n\n (self.data.state[4] >> 8) as u8,\n", "file_path": "src/sha1.rs", "rank": 99, "score": 4.200619750245788 } ]
Rust
sigma-tree/src/sigma_protocol.rs
robkorn/sigma-rust
3aa25d62a2b6f6b071b5b89607d0688e5509a9a6
#![allow(dead_code)] #![allow(unused_variables)] #![allow(missing_docs)] pub mod dlog_group; pub mod dlog_protocol; pub mod prover; pub mod verifier; use k256::arithmetic::Scalar; use crate::{big_integer::BigInteger, serialization::op_code::OpCode}; use blake2::digest::{Update, VariableOutput}; use blake2::VarBlake2b; use dlog_group::EcPoint; use dlog_protocol::{FirstDlogProverMessage, SecondDlogProverMessage}; use std::convert::TryInto; pub struct DlogProverInput { pub w: Scalar, } impl DlogProverInput { pub fn random() -> DlogProverInput { DlogProverInput { w: dlog_group::random_scalar_in_group_range(), } } fn public_image(&self) -> ProveDlog { let g = dlog_group::generator(); ProveDlog::new(dlog_group::exponentiate(&g, &self.w)) } } pub enum PrivateInput { DlogProverInput(DlogProverInput), DiffieHellmanTupleProverInput, } #[derive(PartialEq, Eq, Debug, Clone)] pub struct ProveDlog { pub h: Box<EcPoint>, } impl ProveDlog { pub fn new(ecpoint: EcPoint) -> ProveDlog { ProveDlog { h: Box::new(ecpoint), } } } #[derive(PartialEq, Eq, Debug, Clone)] pub struct ProveDHTuple { gv: Box<EcPoint>, hv: Box<EcPoint>, uv: Box<EcPoint>, vv: Box<EcPoint>, } #[derive(PartialEq, Eq, Debug, Clone)] pub enum SigmaProofOfKnowledgeTree { ProveDHTuple(ProveDHTuple), ProveDlog(ProveDlog), } #[derive(PartialEq, Eq, Debug, Clone)] pub enum SigmaBoolean { TrivialProp(bool), ProofOfKnowledge(SigmaProofOfKnowledgeTree), CAND(Vec<SigmaBoolean>), } impl SigmaBoolean { pub fn op_code(&self) -> OpCode { match self { SigmaBoolean::ProofOfKnowledge(SigmaProofOfKnowledgeTree::ProveDlog(_)) => { OpCode::PROVE_DLOG } _ => todo!(), } } } #[derive(PartialEq, Eq, Debug, Clone)] pub struct SigmaProp(SigmaBoolean); impl SigmaProp { pub fn new(sbool: SigmaBoolean) -> Self { SigmaProp { 0: sbool } } pub fn value(&self) -> &SigmaBoolean { &self.0 } } pub enum ProofTree { UncheckedTree(UncheckedTree), UnprovenTree(UnprovenTree), } impl ProofTree { pub fn with_challenge(&self, challenge: Challenge) -> ProofTree { todo!() } } pub enum UnprovenTree { UnprovenSchnorr(UnprovenSchnorr), } impl UnprovenTree { pub fn real(&self) -> bool { match self { UnprovenTree::UnprovenSchnorr(us) => !us.simulated, } } } pub struct UnprovenSchnorr { proposition: ProveDlog, commitment_opt: Option<FirstDlogProverMessage>, randomness_opt: Option<BigInteger>, challenge_opt: Option<Challenge>, simulated: bool, } #[derive(PartialEq, Eq, Debug, Clone)] pub struct Challenge(FiatShamirHash); pub enum UncheckedSigmaTree { UncheckedLeaf(UncheckedLeaf), } pub enum UncheckedLeaf { UncheckedSchnorr(UncheckedSchnorr), } impl UncheckedLeaf { pub fn proposition(&self) -> SigmaBoolean { match self { UncheckedLeaf::UncheckedSchnorr(us) => SigmaBoolean::ProofOfKnowledge( SigmaProofOfKnowledgeTree::ProveDlog(us.proposition.clone()), ), } } } pub struct UncheckedSchnorr { proposition: ProveDlog, commitment_opt: Option<FirstDlogProverMessage>, challenge: Challenge, second_message: SecondDlogProverMessage, } impl UncheckedSigmaTree { } pub enum UncheckedTree { NoProof, UncheckedSigmaTree(UncheckedSigmaTree), } fn serialize_sig(tree: UncheckedTree) -> Vec<u8> { match tree { UncheckedTree::NoProof => vec![], UncheckedTree::UncheckedSigmaTree(_) => todo!(), } } fn fiat_shamir_tree_to_bytes(tree: &ProofTree) -> Vec<u8> { todo!() } /** Size of the binary representation of any group element (2 ^ groupSizeBits == <number of elements in a group>) */ pub const GROUP_SIZE_BITS: usize = 256; /** Number of bytes to represent any group element as byte array */ pub const GROUP_SIZE: usize = GROUP_SIZE_BITS / 8; /** A size of challenge in Sigma protocols, in bits. * If this anything but 192, threshold won't work, because we have polynomials over GF(2^192) and no others. * So DO NOT change the value without implementing polynomials over GF(2^soundnessBits) first * and changing code that calls on GF2_192 and GF2_192_Poly classes!!! * We get the challenge by reducing hash function output to proper value. */ pub const SOUNDNESS_BITS: usize = 192; pub const SOUNDNESS_BYTES: usize = SOUNDNESS_BITS / 8; #[derive(PartialEq, Eq, Debug, Clone)] pub struct FiatShamirHash(pub Box<[u8; SOUNDNESS_BYTES]>); pub fn fiat_shamir_hash_fn(input: &[u8]) -> FiatShamirHash { let mut hasher = VarBlake2b::new(SOUNDNESS_BYTES).unwrap(); hasher.update(input); let hash = hasher.finalize_boxed(); FiatShamirHash(hash.try_into().unwrap()) } #[cfg(test)] mod tests { use super::*; use proptest::prelude::*; impl Arbitrary for ProveDlog { type Parameters = (); type Strategy = BoxedStrategy<Self>; fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy { (any::<EcPoint>()).prop_map(ProveDlog::new).boxed() } } impl Arbitrary for SigmaBoolean { type Parameters = (); type Strategy = BoxedStrategy<Self>; fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy { (any::<ProveDlog>()) .prop_map(|p| { SigmaBoolean::ProofOfKnowledge(SigmaProofOfKnowledgeTree::ProveDlog(p)) }) .boxed() } } impl Arbitrary for SigmaProp { type Parameters = (); type Strategy = BoxedStrategy<Self>; fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy { (any::<SigmaBoolean>()).prop_map(SigmaProp).boxed() } } #[test] fn ensure_soundness_bits() { assert!(SOUNDNESS_BITS < GROUP_SIZE_BITS); assert!(SOUNDNESS_BYTES * 8 <= 512); assert!(SOUNDNESS_BYTES % 8 == 0); } }
#![allow(dead_code)] #![allow(unused_variables)] #![allow(missing_docs)] pub mod dlog_group; pub mod dlog_protocol; pub mod prover; pub mod verifier; use k256::arithmetic::Scalar; use crate::{big_integer::BigInteger, serialization::op_code::OpCode}; use blake2::digest::{Update, VariableOutput}; use blake2::VarBlake2b; use dlog_group::EcPoint; use dlog_protocol::{FirstDlogProverMessage, SecondDlogProverMessage}; use std::convert::TryInto; pub struct DlogProverInput { pub w: Scalar, } impl DlogProverInput { pub fn random() -> DlogProverInput { DlogProverInput { w: dlog_group::random_scalar_in_group_range(), } } fn public_image(&self) -> ProveDlog { let g = dlog_group::generator(); ProveDlog::new(dlog_group::exponentiate(&g, &self.w)) } } pub enum PrivateInput { DlogProverInput(DlogProverInput), DiffieHellmanTupleProverInput, } #[derive(PartialEq, Eq, Debug, Clone)] pub struct ProveDlog { pub h: Box<EcPoint>, } impl ProveDlog { pub fn new(ecpoint: EcPoint) -> ProveDlog { ProveDlog { h: Box::new(ecpoint), } } } #[derive(PartialEq, Eq, Debug, Clone)] pub struct ProveDHTuple { gv: Box<EcPoint>, hv: Box<EcPoint>, uv: Box<EcPoint>, vv: Box<EcPoint>, } #[derive(PartialEq, Eq, Debug, Clone)] pub enum SigmaProofOfKnowledgeTree { ProveDHTuple(ProveDHTuple), ProveDlog(ProveDlog), } #[derive(PartialEq, Eq, Debug, Clone)] pub enum SigmaBoolean { TrivialProp(bool), ProofOfKnowledge(SigmaProofOfKnowledgeTree), CAND(Vec<SigmaBoolean>), } impl SigmaBoolean { pub fn op_code(&self) -> OpCode { match self { SigmaBoolean::ProofOfKnowledge(SigmaProofOfKnowledgeTree::ProveDlog(_)) => { OpCode::PROVE_DLOG } _ => todo!(), } } } #[derive(PartialEq, Eq, Debug, Clone)] pub struct SigmaProp(SigmaBoolean); impl SigmaProp { pub fn new(sbool: SigmaBoolean) -> Self { SigmaProp { 0: sbool } } pub fn value(&self) -> &SigmaBoolean { &self.0 } } pub enum ProofTree { UncheckedTree(UncheckedTree), UnprovenTree(UnprovenTree), } impl ProofTree { pub fn with_challenge(&self, challenge: Challenge) -> ProofTree { todo!() } } pub enum UnprovenTree { UnprovenSchnorr(UnprovenSchnorr), } impl UnprovenTree { pub fn real(&self) -> bool { match self { UnprovenTree::UnprovenSchnorr(us) => !us.simulated, } } } pub struct UnprovenSchnorr { proposition: ProveDlog, commitment_opt: Option<FirstDlogProverMessage>, randomness_opt: Option<BigInteger>, challenge_opt: Option<Challenge>, simulated: bool, } #[derive(PartialEq, Eq, Debug, Clone)] pub struct Challenge(FiatShamirHash); pub enum UncheckedSigmaTree { UncheckedLeaf(UncheckedLeaf), } pub enum UncheckedLeaf { UncheckedSchnorr(UncheckedSchnorr), } impl UncheckedLeaf { pub fn proposition(&self) -> SigmaBoolean { match self { UncheckedLeaf::UncheckedSchnorr(us) => SigmaBoolean::ProofOfKnowledge( SigmaProofOfKnowledgeTree::ProveDlog(us.proposition.clone()), ), } } } pub struct UncheckedSchnorr { proposition: ProveDlog, commitment_opt: Option<FirstDlogProverMessage>, challenge: Challenge, second_message: SecondDlogProverMessage, } impl UncheckedSigmaTree { } pub enum UncheckedTree { NoProof, UncheckedSigmaTree(UncheckedSigmaTree), } fn serialize_sig(tree: UncheckedTree) -> Vec<u8> { match tree { UncheckedTree::NoProof => vec![], UncheckedTree::UncheckedSigmaTree(_) => todo!(), } } fn fiat_shamir_tree_to_bytes(tree: &ProofTree) -> Vec<u8> { todo!() } /** Size of the binary representation of any group element (2 ^ groupSizeBits == <number of elements in a group>) */ pub const GROUP_SIZE_BITS: usize = 256; /** Number of bytes to represent any group element as byte array */ pub const GROUP_SIZE: usize = GROUP_SIZE_BITS / 8; /** A size of challenge in Sigma protocols, in bits. * If this anything but 192, threshold won't work, because we have polynomials over GF(2^192) and no others. * So DO NOT change the value without implementing polynomials over GF(2^soundnessBits) first * and changing code that calls on GF2_192 and GF2_192_Poly classes!!! * We get the challenge by reducing hash function output to proper value. */ pub const SOUNDNESS_BITS: usize = 192; pub const SOUNDNESS_BYTES: usize = SOUNDNESS_BITS / 8; #[derive(PartialEq, Eq, Debug, Clone)] pub struct FiatShamirHash(pub Box<[u8; SOUNDNESS_BYTES]>); pub fn fiat_shamir_hash_fn(input: &[u8]) -> FiatShamirHash { let mut hasher = VarBlake2b::new(SOUNDNESS_BYTES).unwra
#[cfg(test)] mod tests { use super::*; use proptest::prelude::*; impl Arbitrary for ProveDlog { type Parameters = (); type Strategy = BoxedStrategy<Self>; fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy { (any::<EcPoint>()).prop_map(ProveDlog::new).boxed() } } impl Arbitrary for SigmaBoolean { type Parameters = (); type Strategy = BoxedStrategy<Self>; fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy { (any::<ProveDlog>()) .prop_map(|p| { SigmaBoolean::ProofOfKnowledge(SigmaProofOfKnowledgeTree::ProveDlog(p)) }) .boxed() } } impl Arbitrary for SigmaProp { type Parameters = (); type Strategy = BoxedStrategy<Self>; fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy { (any::<SigmaBoolean>()).prop_map(SigmaProp).boxed() } } #[test] fn ensure_soundness_bits() { assert!(SOUNDNESS_BITS < GROUP_SIZE_BITS); assert!(SOUNDNESS_BYTES * 8 <= 512); assert!(SOUNDNESS_BYTES % 8 == 0); } }
p(); hasher.update(input); let hash = hasher.finalize_boxed(); FiatShamirHash(hash.try_into().unwrap()) }
function_block-function_prefixed
[ { "content": "/// Creates a random scalar, a big-endian integer in the range [0, n), where n is group order\n\npub fn random_scalar_in_group_range() -> Scalar {\n\n loop {\n\n // Generate a new secret key using the operating system's\n\n // cryptographically secure random number generator\n\n let sk = k256::SecretKey::generate();\n\n let bytes: [u8; 32] = sk\n\n .secret_scalar()\n\n .as_ref()\n\n .as_slice()\n\n .try_into()\n\n .expect(\"expected 32 bytes\");\n\n // Returns None if the byte array does not contain\n\n // a big-endian integer in the range [0, n), where n is group order.\n\n let maybe_scalar = Scalar::from_bytes(bytes);\n\n if bool::from(maybe_scalar.is_some()) {\n\n break maybe_scalar.unwrap();\n\n }\n\n }\n\n}\n\n\n", "file_path": "sigma-tree/src/sigma_protocol/dlog_group.rs", "rank": 0, "score": 304795.5759556212 }, { "content": "/// Creates a random member of this Dlog group\n\npub fn random_element() -> EcPoint {\n\n let sk = DlogProverInput::random();\n\n let bytes = sk.w.to_bytes();\n\n let bi = BigInt::from_bytes_be(Sign::Plus, &bytes[..]);\n\n\n\n exponentiate(&generator(), &sk.w)\n\n}\n\n\n", "file_path": "sigma-tree/src/sigma_protocol/dlog_group.rs", "rank": 1, "score": 290281.25990754174 }, { "content": "pub fn is_identity(ge: &EcPoint) -> bool {\n\n *ge == identity()\n\n}\n\n\n", "file_path": "sigma-tree/src/sigma_protocol/dlog_group.rs", "rank": 4, "score": 261162.48115587642 }, { "content": "/// Blake2b256 hash (256 bit)\n\npub fn blake2b256_hash(bytes: &[u8]) -> Digest32 {\n\n // unwrap is safe 32 bytes is a valid hash size (<= 512 && 32 % 8 == 0)\n\n let mut hasher = VarBlake2b::new(Digest32::SIZE).unwrap();\n\n hasher.update(bytes);\n\n let hash = hasher.finalize_boxed();\n\n // unwrap is safe due to hash size is expected to be Digest32::SIZE\n\n Digest32(hash.try_into().unwrap())\n\n}\n\n\n\nimpl From<[u8; Digest32::SIZE]> for Digest32 {\n\n fn from(bytes: [u8; Digest32::SIZE]) -> Self {\n\n Digest32(Box::new(bytes))\n\n }\n\n}\n\n\n\nimpl Into<Base16EncodedBytes> for Digest32 {\n\n fn into(self) -> Base16EncodedBytes {\n\n Base16EncodedBytes::new(self.0.as_ref())\n\n }\n\n}\n", "file_path": "sigma-tree/src/chain/digest32.rs", "rank": 6, "score": 248194.5878895931 }, { "content": "/// Raises the base GroupElement to the exponent. The result is another GroupElement.\n\npub fn exponentiate(base: &EcPoint, exponent: &Scalar) -> EcPoint {\n\n if !is_identity(base) {\n\n // implement for negative exponent\n\n // see reference impl https://github.com/ScorexFoundation/sigmastate-interpreter/blob/ec71a6f988f7412bc36199f46e7ad8db643478c7/sigmastate/src/main/scala/sigmastate/basics/BcDlogGroup.scala#L201\n\n // see https://github.com/ergoplatform/sigma-rust/issues/36\n\n\n\n // we treat EC as a multiplicative group, therefore, exponentiate point is multiply.\n\n EcPoint(base.0 * exponent)\n\n } else {\n\n base.clone()\n\n }\n\n}\n\n\n", "file_path": "sigma-tree/src/sigma_protocol/dlog_group.rs", "rank": 7, "score": 246609.0916878886 }, { "content": "/// The generator g of the group is an element of the group such that, when written multiplicatively, every element\n\n/// of the group is a power of g.\n\npub fn generator() -> EcPoint {\n\n EcPoint(ProjectivePoint::generator())\n\n}\n\n\n\n/// the identity(infinity) element of this Dlog group\n\npub const fn identity() -> EcPoint {\n\n EcPoint(ProjectivePoint::identity())\n\n}\n\n\n", "file_path": "sigma-tree/src/sigma_protocol/dlog_group.rs", "rank": 8, "score": 233539.662568651 }, { "content": "pub trait Prover: Evaluator {\n\n fn secrets(&self) -> &[PrivateInput];\n\n\n\n fn prove(\n\n &self,\n\n tree: &ErgoTree,\n\n env: &Env,\n\n message: &[u8],\n\n ) -> Result<ProverResult, ProverError> {\n\n let expr = tree.proposition()?;\n\n let proof = self\n\n .reduce_to_crypto(expr.as_ref(), env)\n\n .map_err(ProverError::EvalError)\n\n .and_then(|v| match v.sigma_prop {\n\n SigmaBoolean::TrivialProp(true) => Ok(UncheckedTree::NoProof),\n\n SigmaBoolean::TrivialProp(false) => Err(ProverError::ReducedToFalse),\n\n sb => {\n\n let tree = self.convert_to_unproven(sb);\n\n let unchecked_tree = self.prove_to_unchecked(tree, message)?;\n\n Ok(UncheckedTree::UncheckedSigmaTree(unchecked_tree))\n", "file_path": "sigma-tree/src/sigma_protocol/prover.rs", "rank": 9, "score": 201430.14083236712 }, { "content": "fn get_embeddable_type(code: u8) -> Result<SType, SerializationError> {\n\n match TypeCode::new(code) {\n\n TypeCode::SBOOLEAN => Ok(SType::SBoolean),\n\n TypeCode::SBYTE => Ok(SType::SByte),\n\n TypeCode::SSHORT => Ok(SType::SShort),\n\n TypeCode::SINT => Ok(SType::SInt),\n\n TypeCode::SLONG => Ok(SType::SLong),\n\n TypeCode::SBIGINT => Ok(SType::SBigInt),\n\n TypeCode::SGROUP_ELEMENT => Ok(SType::SGroupElement),\n\n TypeCode::SSIGMAPROP => Ok(SType::SSigmaProp),\n\n _ => Err(SerializationError::InvalidOpCode),\n\n }\n\n}\n\n\n", "file_path": "sigma-tree/src/serialization/types.rs", "rank": 10, "score": 199649.98139593913 }, { "content": "pub trait Verifier: Evaluator {\n\n fn verify(\n\n &mut self,\n\n tree: &ErgoTree,\n\n env: &Env,\n\n proof: &[u8],\n\n message: &[u8],\n\n ) -> Result<VerificationResult, VerifierError> {\n\n let expr = tree.proposition()?;\n\n let cprop = self.reduce_to_crypto(expr.as_ref(), env)?.sigma_prop;\n\n let res: bool = match cprop {\n\n SigmaBoolean::TrivialProp(b) => b,\n\n sb => todo!(),\n\n };\n\n Ok(VerificationResult {\n\n result: res,\n\n cost: 0,\n\n })\n\n }\n\n}\n", "file_path": "sigma-tree/src/sigma_protocol/verifier.rs", "rank": 11, "score": 182454.27450487658 }, { "content": "/// Box serialization with token ids optionally saved in transaction\n\n/// (in this case only token index is saved)\n\npub fn serialize_box_with_indexed_digests<W: vlq_encode::WriteSigmaVlqExt>(\n\n box_value: &BoxValue,\n\n ergo_tree_bytes: Vec<u8>,\n\n tokens: &[TokenAmount],\n\n additional_registers: &NonMandatoryRegisters,\n\n creation_height: u32,\n\n token_ids_in_tx: Option<&IndexSet<TokenId>>,\n\n w: &mut W,\n\n) -> Result<(), io::Error> {\n\n // reference implementation - https://github.com/ScorexFoundation/sigmastate-interpreter/blob/9b20cb110effd1987ff76699d637174a4b2fb441/sigmastate/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala#L95-L95\n\n box_value.sigma_serialize(w)?;\n\n w.write_all(&ergo_tree_bytes[..])?;\n\n w.put_u32(creation_height)?;\n\n w.put_u8(u8::try_from(tokens.len()).unwrap())?;\n\n\n\n tokens.iter().try_for_each(|t| {\n\n match token_ids_in_tx {\n\n Some(token_ids) => w.put_u32(\n\n u32::try_from(\n\n token_ids\n", "file_path": "sigma-tree/src/serialization/ergo_box.rs", "rank": 12, "score": 173133.05255750826 }, { "content": "#[derive(PartialEq, Eq, Debug, Clone)]\n\nstruct ErgoTreeHeader(u8);\n\n\n\nimpl ErgoTreeHeader {\n\n const CONSTANT_SEGREGATION_FLAG: u8 = 0x10;\n\n\n\n pub fn is_constant_segregation(&self) -> bool {\n\n self.0 & ErgoTreeHeader::CONSTANT_SEGREGATION_FLAG != 0\n\n }\n\n}\n\n\n\n/// Whole ErgoTree parsing (deserialization) error\n\n#[derive(PartialEq, Eq, Debug, Clone)]\n\npub struct ErgoTreeConstantsParsingError {\n\n /// Ergo tree bytes (faild to deserialize)\n\n pub bytes: Vec<u8>,\n\n /// Deserialization error\n\n pub error: SerializationError,\n\n}\n\n\n\n/// ErgoTree root expr parsing (deserialization) error\n", "file_path": "sigma-tree/src/ergo_tree.rs", "rank": 13, "score": 171467.29386373737 }, { "content": "pub fn serialize_bytes<S, T>(bytes: T, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n T: AsRef<[u8]>,\n\n{\n\n serializer.serialize_str(&base16::encode_lower(bytes.as_ref()))\n\n}\n\n\n\npub mod ergo_tree {\n\n\n\n use super::*;\n\n use crate::ErgoTree;\n\n use serde::{Deserialize, Deserializer, Serializer};\n\n use sigma_ser::serializer::SigmaSerializable;\n\n\n\n pub fn serialize<S>(ergo_tree: &ErgoTree, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: Serializer,\n\n {\n\n let bytes = ergo_tree.sigma_serialise_bytes();\n", "file_path": "sigma-tree/src/chain/json.rs", "rank": 14, "score": 145282.7728311161 }, { "content": "fn is_stype_embeddable(tpe: &SType) -> bool {\n\n match tpe {\n\n SType::SBoolean => true,\n\n SType::SByte => true,\n\n SType::SShort => true,\n\n SType::SInt => true,\n\n SType::SLong => true,\n\n SType::SBigInt => true,\n\n SType::SGroupElement => true,\n\n SType::SSigmaProp => true,\n\n _ => false,\n\n }\n\n}\n\n\n\nimpl SigmaSerializable for SType {\n\n fn sigma_serialize<W: WriteSigmaVlqExt>(&self, w: &mut W) -> Result<(), io::Error> {\n\n // for reference see http://github.com/ScorexFoundation/sigmastate-interpreter/blob/25251c1313b0131835f92099f02cef8a5d932b5e/sigmastate/src/main/scala/sigmastate/serialization/TypeSerializer.scala#L25-L25\n\n match self {\n\n SType::SAny => self.type_code().sigma_serialize(w),\n\n\n", "file_path": "sigma-tree/src/serialization/types.rs", "rank": 15, "score": 144069.00610777322 }, { "content": "#[allow(unconditional_recursion)]\n\nfn eval(expr: &Expr, env: &Env, ca: &mut CostAccumulator) -> Result<Value, EvalError> {\n\n match expr {\n\n Expr::Const(Constant {\n\n tpe: SType::SBoolean,\n\n v: ConstantVal::Boolean(b),\n\n }) => Ok(Value::Boolean(*b)),\n\n Expr::Const(Constant {\n\n tpe: SType::SSigmaProp,\n\n v: ConstantVal::SigmaProp(sp),\n\n }) => Ok(Value::SigmaProp(Box::new((*sp.value()).clone()))),\n\n Expr::Coll { .. } => todo!(),\n\n Expr::Tup { .. } => todo!(),\n\n Expr::PredefFunc(_) => todo!(),\n\n Expr::CollM(_) => todo!(),\n\n Expr::BoxM(_) => todo!(),\n\n Expr::CtxM(_) => todo!(),\n\n Expr::MethodCall { .. } => todo!(),\n\n Expr::BinOp(bin_op, l, r) => {\n\n let v_l = eval(l, env, ca)?;\n\n let v_r = eval(r, env, ca)?;\n", "file_path": "sigma-tree/src/eval.rs", "rank": 16, "score": 143356.5365707662 }, { "content": "//! Verifier\n\n\n\n#![allow(dead_code)]\n\n#![allow(unused_variables)]\n\n#![allow(missing_docs)]\n\n\n\nuse super::SigmaBoolean;\n\nuse crate::{\n\n eval::{Env, EvalError, Evaluator},\n\n ErgoTree, ErgoTreeParsingError,\n\n};\n\n\n\npub enum VerifierError {\n\n ErgoTreeError(ErgoTreeParsingError),\n\n EvalError(EvalError),\n\n}\n\n\n\nimpl From<ErgoTreeParsingError> for VerifierError {\n\n fn from(err: ErgoTreeParsingError) -> Self {\n\n VerifierError::ErgoTreeError(err)\n", "file_path": "sigma-tree/src/sigma_protocol/verifier.rs", "rank": 17, "score": 132343.50952893982 }, { "content": " }\n\n}\n\n\n\nimpl From<EvalError> for VerifierError {\n\n fn from(err: EvalError) -> Self {\n\n VerifierError::EvalError(err)\n\n }\n\n}\n\n\n\npub struct VerificationResult {\n\n result: bool,\n\n cost: u64,\n\n}\n\n\n", "file_path": "sigma-tree/src/sigma_protocol/verifier.rs", "rank": 18, "score": 132336.48822234911 }, { "content": "\n\nimpl Evaluator for TestProver {}\n\nimpl Prover for TestProver {\n\n fn secrets(&self) -> &[PrivateInput] {\n\n self.secrets.as_ref()\n\n }\n\n}\n\n\n\n#[derive(PartialEq, Eq, Debug, Clone)]\n\npub enum ProverError {\n\n ErgoTreeError(ErgoTreeParsingError),\n\n EvalError(EvalError),\n\n ReducedToFalse,\n\n TreeRootIsNotReal,\n\n SimulatedLeafWithoutChallenge,\n\n RealUnprovenTreeWithoutChallenge,\n\n SecretNotFound,\n\n}\n\n\n\nimpl From<ErgoTreeParsingError> for ProverError {\n\n fn from(err: ErgoTreeParsingError) -> Self {\n\n ProverError::ErgoTreeError(err)\n\n }\n\n}\n\n\n", "file_path": "sigma-tree/src/sigma_protocol/prover.rs", "rank": 19, "score": 132090.0939276574 }, { "content": "//! Interpreter with enhanced functionality to prove statements.\n\n\n\n#![allow(dead_code)]\n\n#![allow(unused_variables)]\n\n#![allow(missing_docs)]\n\n\n\nuse super::{\n\n dlog_protocol, fiat_shamir_hash_fn, fiat_shamir_tree_to_bytes, serialize_sig, Challenge,\n\n PrivateInput, ProofTree, SigmaBoolean, SigmaProofOfKnowledgeTree, UncheckedLeaf,\n\n UncheckedSchnorr, UncheckedSigmaTree, UncheckedTree, UnprovenSchnorr, UnprovenTree,\n\n};\n\nuse crate::{\n\n chain::{ContextExtension, ProverResult},\n\n eval::{Env, EvalError, Evaluator},\n\n ErgoTree, ErgoTreeParsingError,\n\n};\n\n\n\npub struct TestProver {\n\n pub secrets: Vec<PrivateInput>,\n\n}\n", "file_path": "sigma-tree/src/sigma_protocol/prover.rs", "rank": 20, "score": 132086.3459287251 }, { "content": " // and the message being signed.\n\n s.append(&mut message.to_vec());\n\n let root_challenge = fiat_shamir_hash_fn(s.as_slice());\n\n let step8 = step6.with_challenge(Challenge(root_challenge));\n\n\n\n // Prover Step 9: complete the proof by computing challenges at real nodes and additionally responses at real leaves\n\n let step9 = self.proving(step8)?;\n\n\n\n // Prover Step 10: output the right information into the proof\n\n match step9 {\n\n ProofTree::UncheckedTree(UncheckedTree::UncheckedSigmaTree(tree)) => Ok(tree),\n\n _ => todo!(),\n\n }\n\n }\n\n\n\n /**\n\n Prover Step 1: This step will mark as \"real\" every node for which the prover can produce a real proof.\n\n This step may mark as \"real\" more nodes than necessary if the prover has more than the minimal\n\n necessary number of witnesses (for example, more than one child of an OR).\n\n This will be corrected in the next step.\n", "file_path": "sigma-tree/src/sigma_protocol/prover.rs", "rank": 21, "score": 132085.12741664032 }, { "content": " match tree {\n\n ProofTree::UncheckedTree(_) => Ok(tree),\n\n ProofTree::UnprovenTree(unproven_tree) => match unproven_tree {\n\n UnprovenTree::UnprovenSchnorr(us) if unproven_tree.real() => {\n\n if let Some(challenge) = us.challenge_opt.clone() {\n\n if let Some(priv_key) = self\n\n .secrets()\n\n .iter()\n\n .flat_map(|s| match s {\n\n PrivateInput::DlogProverInput(dl) => vec![dl],\n\n _ => vec![],\n\n })\n\n .find(|prover_input| prover_input.public_image() == us.proposition)\n\n {\n\n let z = dlog_protocol::interactive_prover::second_message(\n\n &priv_key,\n\n us.randomness_opt.unwrap(),\n\n &challenge,\n\n );\n\n Ok(ProofTree::UncheckedTree(UncheckedTree::UncheckedSigmaTree(\n", "file_path": "sigma-tree/src/sigma_protocol/prover.rs", "rank": 22, "score": 132083.74330649685 }, { "content": " In a top-down traversal of the tree, do the following for each node:\n\n */\n\n fn polish_simulated(&self, unproven_tree: UnprovenTree) -> UnprovenTree {\n\n todo!()\n\n }\n\n\n\n /**\n\n Prover Step 4: In a top-down traversal of the tree, compute the challenges e for simulated children of every node\n\n Prover Step 5: For every leaf marked \"simulated\", use the simulator of the Sigma-protocol for that leaf\n\n to compute the commitment $a$ and the response z, given the challenge e that is already stored in the leaf.\n\n Prover Step 6: For every leaf marked \"real\", use the first prover step of the Sigma-protocol for that leaf to\n\n compute the commitment a.\n\n */\n\n fn simulate_and_commit(&self, tree: UnprovenTree) -> Result<ProofTree, ProverError> {\n\n match tree {\n\n UnprovenTree::UnprovenSchnorr(us) => {\n\n if us.simulated {\n\n // Step 5 (simulated leaf -- complete the simulation)\n\n if let Some(challenge) = us.challenge_opt {\n\n let (fm, sm) = dlog_protocol::interactive_prover::simulate(\n", "file_path": "sigma-tree/src/sigma_protocol/prover.rs", "rank": 23, "score": 132083.60331504315 }, { "content": "}\n\n\n\n// #[cfg(test)]\n\n// mod tests {\n\n// use super::*;\n\n// use crate::{\n\n// ast::{Constant, ConstantVal, Expr},\n\n// sigma_protocol::{DlogProverInput, SigmaProp},\n\n// types::SType,\n\n// };\n\n// use std::rc::Rc;\n\n\n\n// #[test]\n\n// fn test_prove_true_prop() {\n\n// let bool_true_tree = ErgoTree::from(Rc::new(Expr::Const(Constant {\n\n// tpe: SType::SBoolean,\n\n// v: ConstantVal::Boolean(true),\n\n// })));\n\n// let message = vec![0u8; 100];\n\n\n", "file_path": "sigma-tree/src/sigma_protocol/prover.rs", "rank": 24, "score": 132082.14336036408 }, { "content": " if !step1.real() {\n\n return Err(ProverError::TreeRootIsNotReal);\n\n }\n\n\n\n // Prover Step 3: Change some \"real\" nodes to \"simulated\" to make sure each node\n\n // has the right number of simulated children.\n\n\n\n // skipped, since it leaves UnprovenSchnorr untouched\n\n // let step3 = self.polish_simulated(step1);\n\n\n\n // Prover Steps 4, 5, and 6 together: find challenges for simulated nodes; simulate simulated leaves;\n\n // compute commitments for real leaves\n\n let step6 = self.simulate_and_commit(step1)?;\n\n\n\n // Prover Steps 7: convert the relevant information in the tree (namely, tree structure, node types,\n\n // the statements being proven and commitments at the leaves)\n\n // to a string\n\n let mut s = fiat_shamir_tree_to_bytes(&step6);\n\n\n\n // Prover Step 8: compute the challenge for the root of the tree as the Fiat-Shamir hash of s\n", "file_path": "sigma-tree/src/sigma_protocol/prover.rs", "rank": 25, "score": 132080.5613411577 }, { "content": " &us.proposition,\n\n &challenge,\n\n );\n\n Ok(ProofTree::UncheckedTree(UncheckedTree::UncheckedSigmaTree(\n\n UncheckedSigmaTree::UncheckedLeaf(UncheckedLeaf::UncheckedSchnorr(\n\n UncheckedSchnorr {\n\n proposition: us.proposition,\n\n commitment_opt: Some(fm),\n\n challenge,\n\n second_message: sm,\n\n },\n\n )),\n\n )))\n\n } else {\n\n Err(ProverError::SimulatedLeafWithoutChallenge)\n\n }\n\n } else {\n\n // Step 6 (real leaf -- compute the commitment a)\n\n let (r, commitment) =\n\n dlog_protocol::interactive_prover::first_message(&us.proposition);\n", "file_path": "sigma-tree/src/sigma_protocol/prover.rs", "rank": 26, "score": 132080.44406417472 }, { "content": " }\n\n });\n\n proof.map(|v| ProverResult {\n\n proof: serialize_sig(v),\n\n extension: ContextExtension::empty(),\n\n })\n\n }\n\n\n\n fn convert_to_unproven(&self, sigma_tree: SigmaBoolean) -> UnprovenTree {\n\n match sigma_tree {\n\n SigmaBoolean::TrivialProp(_) => todo!(), // TODO: why it's even here\n\n SigmaBoolean::ProofOfKnowledge(pok) => match pok {\n\n SigmaProofOfKnowledgeTree::ProveDHTuple(_) => todo!(),\n\n SigmaProofOfKnowledgeTree::ProveDlog(prove_dlog) => {\n\n UnprovenTree::UnprovenSchnorr(UnprovenSchnorr {\n\n proposition: prove_dlog,\n\n commitment_opt: None,\n\n randomness_opt: None,\n\n challenge_opt: None,\n\n simulated: false,\n", "file_path": "sigma-tree/src/sigma_protocol/prover.rs", "rank": 27, "score": 132080.42293479643 }, { "content": "// let prover = TestProver { secrets: vec![] };\n\n// let res = prover.prove(&bool_true_tree, &Env::empty(), message.as_slice());\n\n// assert!(res.is_ok());\n\n// assert!(res.unwrap().proof.is_empty());\n\n// }\n\n\n\n// #[test]\n\n// fn test_prove_false_prop() {\n\n// let bool_false_tree = ErgoTree::from(Rc::new(Expr::Const(Constant {\n\n// tpe: SType::SBoolean,\n\n// v: ConstantVal::Boolean(false),\n\n// })));\n\n// let message = vec![0u8; 100];\n\n\n\n// let prover = TestProver { secrets: vec![] };\n\n// let res = prover.prove(&bool_false_tree, &Env::empty(), message.as_slice());\n\n// assert!(res.is_err());\n\n// assert_eq!(res.err().unwrap(), ProverError::ReducedToFalse);\n\n// }\n\n\n", "file_path": "sigma-tree/src/sigma_protocol/prover.rs", "rank": 28, "score": 132077.7923285461 }, { "content": " UncheckedSigmaTree::UncheckedLeaf(UncheckedLeaf::UncheckedSchnorr(\n\n UncheckedSchnorr {\n\n proposition: us.proposition,\n\n commitment_opt: None,\n\n challenge,\n\n second_message: z,\n\n },\n\n )),\n\n )))\n\n } else {\n\n Err(ProverError::SecretNotFound)\n\n }\n\n } else {\n\n Err(ProverError::RealUnprovenTreeWithoutChallenge)\n\n }\n\n }\n\n _ => todo!(),\n\n },\n\n }\n\n }\n", "file_path": "sigma-tree/src/sigma_protocol/prover.rs", "rank": 29, "score": 132077.4879540827 }, { "content": " In a bottom-up traversal of the tree, do the following for each node:\n\n */\n\n fn mark_real(&self, unproven_tree: UnprovenTree) -> UnprovenTree {\n\n match unproven_tree {\n\n UnprovenTree::UnprovenSchnorr(us) => {\n\n let secret_known = self.secrets().iter().any(|s| match s {\n\n PrivateInput::DlogProverInput(dl) => dl.public_image() == us.proposition,\n\n _ => false,\n\n });\n\n UnprovenTree::UnprovenSchnorr(UnprovenSchnorr {\n\n simulated: !secret_known,\n\n ..us\n\n })\n\n }\n\n }\n\n }\n\n\n\n /**\n\n Prover Step 3: This step will change some \"real\" nodes to \"simulated\" to make sure each node has\n\n the right number of simulated children.\n", "file_path": "sigma-tree/src/sigma_protocol/prover.rs", "rank": 30, "score": 132075.8234238417 }, { "content": " })\n\n }\n\n },\n\n SigmaBoolean::CAND(_) => todo!(),\n\n }\n\n }\n\n\n\n /// The comments in this section are taken from the algorithm for the\n\n /// Sigma-protocol prover as described in the white paper\n\n /// https://ergoplatform.org/docs/ErgoScript.pdf (Appendix A)\n\n fn prove_to_unchecked(\n\n &self,\n\n unproven_tree: UnprovenTree,\n\n message: &[u8],\n\n ) -> Result<UncheckedSigmaTree, ProverError> {\n\n // Prover Step 1: Mark as real everything the prover can prove\n\n let step1 = self.mark_real(unproven_tree);\n\n\n\n // Prover Step 2: If the root of the tree is marked \"simulated\" then the prover does not have enough witnesses\n\n // to perform the proof. Abort.\n", "file_path": "sigma-tree/src/sigma_protocol/prover.rs", "rank": 31, "score": 132075.221121568 }, { "content": "// #[test]\n\n// fn test_prove_pk_prop() {\n\n// let secret = DlogProverInput::random();\n\n// let pk = secret.public_image();\n\n// let tree = ErgoTree::from(Rc::new(Expr::Const(Constant {\n\n// tpe: SType::SSigmaProp,\n\n// v: ConstantVal::SigmaProp(Box::new(SigmaProp(SigmaBoolean::ProofOfKnowledge(\n\n// SigmaProofOfKnowledgeTree::ProveDlog(pk),\n\n// )))),\n\n// })));\n\n// let message = vec![0u8; 100];\n\n\n\n// let prover = TestProver {\n\n// secrets: vec![PrivateInput::DlogProverInput(secret)],\n\n// };\n\n// let res = prover.prove(&tree, &Env::empty(), message.as_slice());\n\n// // assert!(res.is_ok());\n\n// assert!(!res.unwrap().proof.is_empty());\n\n// }\n\n// }\n", "file_path": "sigma-tree/src/sigma_protocol/prover.rs", "rank": 32, "score": 132074.9440513409 }, { "content": " Ok(ProofTree::UnprovenTree(UnprovenTree::UnprovenSchnorr(\n\n UnprovenSchnorr {\n\n commitment_opt: Some(commitment),\n\n randomness_opt: Some(r),\n\n ..us\n\n },\n\n )))\n\n }\n\n }\n\n }\n\n }\n\n\n\n /**\n\n Prover Step 9: Perform a top-down traversal of only the portion of the tree marked \"real\" in order to compute\n\n the challenge e for every node marked \"real\" below the root and, additionally, the response z for every leaf\n\n marked \"real\"\n\n */\n\n fn proving(&self, tree: ProofTree) -> Result<ProofTree, ProverError> {\n\n // If the node is a leaf marked \"real\", compute its response according to the second prover step\n\n // of the Sigma-protocol given the commitment, challenge, and witness\n", "file_path": "sigma-tree/src/sigma_protocol/prover.rs", "rank": 33, "score": 132071.53000850373 }, { "content": "/// Box deserialization with token ids optionally parsed in transaction\n\npub fn parse_box_with_indexed_digests<R: vlq_encode::ReadSigmaVlqExt>(\n\n digests_in_tx: Option<&IndexSet<TokenId>>,\n\n r: &mut R,\n\n) -> Result<ErgoBoxCandidate, SerializationError> {\n\n // reference implementation -https://github.com/ScorexFoundation/sigmastate-interpreter/blob/9b20cb110effd1987ff76699d637174a4b2fb441/sigmastate/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala#L144-L144\n\n\n\n let value = BoxValue::sigma_parse(r)?;\n\n let ergo_tree = ErgoTree::sigma_parse(r)?;\n\n let creation_height = r.get_u32()?;\n\n let tokens_count = r.get_u8()?;\n\n let mut tokens = Vec::with_capacity(tokens_count as usize);\n\n for _ in 0..tokens_count {\n\n let token_id = match digests_in_tx {\n\n None => TokenId::sigma_parse(r)?,\n\n Some(digests) => {\n\n let digest_index = r.get_u32()?;\n\n match digests.get_index(digest_index as usize) {\n\n Some(i) => Ok((*i).clone()),\n\n None => Err(SerializationError::Misc(\n\n \"failed to find token id in tx digests\".to_string(),\n", "file_path": "sigma-tree/src/serialization/ergo_box.rs", "rank": 34, "score": 130755.87430331073 }, { "content": "use num_bigint::{BigInt, Sign};\n\nuse sigma_ser::{\n\n serializer::{SerializationError, SigmaSerializable},\n\n vlq_encode,\n\n};\n\nuse std::{convert::TryInto, io};\n\n\n\n#[derive(PartialEq, Debug, Clone)]\n\npub struct EcPoint(ProjectivePoint);\n\n\n\nimpl EcPoint {\n\n pub const GROUP_SIZE: usize = 33;\n\n}\n\n\n\nimpl Eq for EcPoint {}\n\n\n\n/// The generator g of the group is an element of the group such that, when written multiplicatively, every element\n\n/// of the group is a power of g.\n", "file_path": "sigma-tree/src/sigma_protocol/dlog_group.rs", "rank": 35, "score": 128997.84124939927 }, { "content": "impl SigmaSerializable for EcPoint {\n\n fn sigma_serialize<W: vlq_encode::WriteSigmaVlqExt>(&self, w: &mut W) -> Result<(), io::Error> {\n\n let caff = self.0.to_affine();\n\n if bool::from(caff.is_some()) {\n\n let pubkey = caff.unwrap().to_compressed_pubkey();\n\n w.write_all(pubkey.as_bytes())?;\n\n } else {\n\n // infinity point\n\n let zeroes = [0u8; EcPoint::GROUP_SIZE];\n\n w.write_all(&zeroes)?;\n\n }\n\n Ok(())\n\n }\n\n\n\n fn sigma_parse<R: vlq_encode::ReadSigmaVlqExt>(r: &mut R) -> Result<Self, SerializationError> {\n\n let mut buf = [0; EcPoint::GROUP_SIZE];\n\n r.read_exact(&mut buf[..])?;\n\n if buf[0] != 0 {\n\n let pubkey = PublicKey::from_bytes(&buf[..]).ok_or_else(|| {\n\n SerializationError::Misc(\"failed to parse PK from bytes\".to_string())\n", "file_path": "sigma-tree/src/sigma_protocol/dlog_group.rs", "rank": 36, "score": 128991.06248959851 }, { "content": "//! This is the general interface for the discrete logarithm prime-order group.\n\n//!\n\n//! The discrete logarithm problem is as follows: given a generator g of a finite\n\n//! group G and a random element h in G, find the (unique) integer x such that\n\n//! `g^x = h`.\n\n//!\n\n//! In cryptography, we are interested in groups for which the discrete logarithm problem\n\n//! (Dlog for short) is assumed to be hard. The most known groups of that kind are some Elliptic curve groups.\n\n//!\n\n//! Another issue pertaining elliptic curves is the need to find a suitable mapping that will convert an arbitrary\n\n//! message (that is some binary string) to an element of the group and vice-versa.\n\n//!\n\n//! Only a subset of the messages can be effectively mapped to a group element in such a way that there is a one-to-one\n\n//! injection that converts the string to a group element and vice-versa.\n\n//!\n\n//! On the other hand, any group element can be mapped to some string.\n\n\n\nuse super::DlogProverInput;\n\nuse k256::arithmetic::{ProjectivePoint, Scalar};\n\nuse k256::{arithmetic::AffinePoint, PublicKey};\n", "file_path": "sigma-tree/src/sigma_protocol/dlog_group.rs", "rank": 37, "score": 128984.70460948438 }, { "content": " use sigma_ser::test_helpers::*;\n\n\n\n impl Arbitrary for EcPoint {\n\n type Parameters = ();\n\n type Strategy = BoxedStrategy<Self>;\n\n\n\n fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {\n\n prop_oneof![Just(generator()), Just(identity()), Just(random_element()),].boxed()\n\n }\n\n }\n\n\n\n proptest! {\n\n\n\n #[test]\n\n fn ser_roundtrip(v in any::<EcPoint>()) {\n\n prop_assert_eq![sigma_serialize_roundtrip(&v), v];\n\n }\n\n }\n\n}\n", "file_path": "sigma-tree/src/sigma_protocol/dlog_group.rs", "rank": 38, "score": 128982.96969987261 }, { "content": " })?;\n\n let cp = AffinePoint::from_pubkey(&pubkey);\n\n if bool::from(cp.is_none()) {\n\n Err(SerializationError::Misc(\n\n \"failed to get affine point from PK\".to_string(),\n\n ))\n\n } else {\n\n Ok(EcPoint(ProjectivePoint::from(cp.unwrap())))\n\n }\n\n } else {\n\n // infinity point\n\n Ok(EcPoint(ProjectivePoint::identity()))\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use proptest::prelude::*;\n", "file_path": "sigma-tree/src/sigma_protocol/dlog_group.rs", "rank": 39, "score": 128973.18299612621 }, { "content": "#[derive(PartialEq, Eq, Debug, Clone)]\n\nstruct ParsedTree {\n\n constants: Vec<Constant>,\n\n root: Result<Rc<Expr>, ErgoTreeRootParsingError>,\n\n}\n\n\n\n/** The root of ErgoScript IR. Serialized instances of this class are self sufficient and can be passed around.\n\n */\n\n#[derive(PartialEq, Eq, Debug, Clone)]\n\npub struct ErgoTree {\n\n header: ErgoTreeHeader,\n\n tree: Result<ParsedTree, ErgoTreeConstantsParsingError>,\n\n}\n\n\n", "file_path": "sigma-tree/src/ergo_tree.rs", "rank": 40, "score": 124535.41137541014 }, { "content": "/// Consensus-critical serialization for Ergo\n\npub trait SigmaSerializable: Sized {\n\n /// Write `self` to the given `writer`.\n\n /// This function has a `sigma_` prefix to alert the reader that the\n\n /// serialization in use is consensus-critical serialization \n\n /// Notice that the error type is [`std::io::Error`]; this indicates that\n\n /// serialization MUST be infallible up to errors in the underlying writer.\n\n /// In other words, any type implementing `SigmaSerializable`\n\n /// must make illegal states unrepresentable.\n\n fn sigma_serialize<W: vlq_encode::WriteSigmaVlqExt>(&self, w: &mut W) -> Result<(), io::Error>;\n\n\n\n /// Try to read `self` from the given `reader`.\n\n /// `sigma-` prefix to alert the reader that the serialization in use\n\n /// is consensus-critical\n\n fn sigma_parse<R: vlq_encode::ReadSigmaVlqExt>(r: &mut R) -> Result<Self, SerializationError>;\n\n\n\n /// Serialize any SigmaSerializable value into bytes\n\n fn sigma_serialise_bytes(&self) -> Vec<u8> {\n\n let mut data = Vec::new();\n\n self.sigma_serialize(&mut data)\n\n // since serialization may fail only for underlying IO errors it's ok to force unwrap\n", "file_path": "sigma-ser/src/serializer.rs", "rank": 41, "score": 115946.81811420254 }, { "content": "/// Encode a 32-bit value with ZigZag. ZigZag encodes signed integers\n\n/// into values that can be efficiently encoded with VLQ. (Otherwise,\n\n/// negative values must be sign-extended to 64 bits to be varint encoded,\n\n/// thus always taking 10 bytes on the wire.)\n\n/// see https://developers.google.com/protocol-buffers/docs/encoding#types\n\npub fn encode_i32(v: i32) -> u32 {\n\n // Note: the right-shift must be arithmetic\n\n // source: http://github.com/google/protobuf/blob/a7252bf42df8f0841cf3a0c85fdbf1a5172adecb/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java#L934\n\n ((v << 1) ^ (v >> 31)) as u32\n\n}\n\n\n", "file_path": "sigma-ser/src/zig_zag_encode.rs", "rank": 42, "score": 113382.27196220358 }, { "content": "/// Encode a 64-bit value with ZigZag. ZigZag encodes signed integers\n\n/// into values that can be efficiently encoded with varint. (Otherwise,\n\n/// negative values must be sign-extended to 64 bits to be varint encoded,\n\n/// thus always taking 10 bytes on the wire.)\n\n/// see https://developers.google.com/protocol-buffers/docs/encoding#types\n\npub fn encode_i64(v: i64) -> u64 {\n\n // source: http://github.com/google/protobuf/blob/a7252bf42df8f0841cf3a0c85fdbf1a5172adecb/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java#L949\n\n ((v << 1) ^ (v >> 63)) as u64\n\n}\n\n\n", "file_path": "sigma-ser/src/zig_zag_encode.rs", "rank": 43, "score": 113382.27196220358 }, { "content": "/// Decode a signed value previously ZigZag-encoded with [`encode_i32`]\n\n/// see https://developers.google.com/protocol-buffers/docs/encoding#types\n\npub fn decode_u32(v: u32) -> i32 {\n\n // source: http://github.com/google/protobuf/blob/a7252bf42df8f0841cf3a0c85fdbf1a5172adecb/java/core/src/main/java/com/google/protobuf/CodedInputStream.java#L553\n\n ((v >> 1) ^ (-((v & 1) as i32)) as u32) as i32\n\n}\n\n\n", "file_path": "sigma-ser/src/zig_zag_encode.rs", "rank": 44, "score": 113375.03674928242 }, { "content": "/// Decode a signed value previously ZigZag-encoded with [`encode_i64`]\n\n/// see https://developers.google.com/protocol-buffers/docs/encoding#types\n\npub fn decode_u64(v: u64) -> i64 {\n\n // source: http://github.com/google/protobuf/blob/a7252bf42df8f0841cf3a0c85fdbf1a5172adecb/java/core/src/main/java/com/google/protobuf/CodedInputStream.java#L566\n\n ((v >> 1) ^ (-((v & 1) as i64)) as u64) as i64\n\n}\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[allow(overflowing_literals)]\n\n #[test]\n\n fn test_expected_values() {\n\n // source: http://github.com/google/protobuf/blob/a7252bf42df8f0841cf3a0c85fdbf1a5172adecb/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java#L281\n\n assert_eq!(0, encode_i32(0));\n\n assert_eq!(1, encode_i32(-1));\n\n assert_eq!(2, encode_i32(1));\n\n assert_eq!(3, encode_i32(-2));\n\n assert_eq!(0x7FFF_FFFE, encode_i32(0x3FFF_FFFF));\n\n assert_eq!(0x7FFF_FFFF, encode_i32(0xC000_0000));\n\n assert_eq!(0xFFFF_FFFE, encode_i32(0x7FFF_FFFF));\n\n assert_eq!(0xFFFF_FFFF, encode_i32(0x8000_0000));\n", "file_path": "sigma-ser/src/zig_zag_encode.rs", "rank": 45, "score": 113375.03674928242 }, { "content": "pub trait Evaluator {\n\n fn reduce_to_crypto(&self, expr: &Expr, env: &Env) -> Result<ReductionResult, EvalError> {\n\n let mut ca = CostAccumulator::new(0, None);\n\n eval(expr, env, &mut ca).and_then(|v| match v {\n\n Value::Boolean(b) => Ok(ReductionResult {\n\n sigma_prop: SigmaBoolean::TrivialProp(b),\n\n cost: 0,\n\n }),\n\n Value::SigmaProp(sb) => Ok(ReductionResult {\n\n sigma_prop: *sb,\n\n cost: 0,\n\n }),\n\n _ => Err(EvalError::InvalidResultType),\n\n })\n\n }\n\n}\n\n\n", "file_path": "sigma-tree/src/eval.rs", "rank": 46, "score": 110591.21666816529 }, { "content": "/// serialization roundtrip\n\npub fn sigma_serialize_roundtrip<T: crate::serializer::SigmaSerializable>(v: &T) -> T {\n\n let mut data = Vec::new();\n\n v.sigma_serialize(&mut data).expect(\"serialization failed\");\n\n let cursor = Cursor::new(&mut data[..]);\n\n let mut reader = PeekableReader::new(cursor);\n\n T::sigma_parse(&mut reader).expect(\"parse failed\")\n\n}\n", "file_path": "sigma-ser/src/test_helpers.rs", "rank": 47, "score": 107673.6881738675 }, { "content": "/// Conversion to SType\n\npub trait LiftIntoSType {\n\n /// get SType\n\n fn stype() -> SType;\n\n}\n\n\n\nimpl<T: LiftIntoSType> LiftIntoSType for Vec<T> {\n\n fn stype() -> SType {\n\n SType::SColl(Box::new(T::stype()))\n\n }\n\n}\n\n\n\nimpl LiftIntoSType for bool {\n\n fn stype() -> SType {\n\n SType::SBoolean\n\n }\n\n}\n\n\n\nimpl LiftIntoSType for i8 {\n\n fn stype() -> SType {\n\n SType::SByte\n", "file_path": "sigma-tree/src/types.rs", "rank": 48, "score": 105828.2680589123 }, { "content": "/// Marker trait to select types for which CollElems::NonPrimitive is used to store elements as Vec<ConstantVal>\n\npub trait StoredNonPrimitive {}\n\n\n\nimpl StoredNonPrimitive for bool {}\n\nimpl StoredNonPrimitive for i16 {}\n\nimpl StoredNonPrimitive for i32 {}\n\nimpl StoredNonPrimitive for i64 {}\n\n\n\nimpl<T: LiftIntoSType + StoredNonPrimitive + Into<ConstantVal>> Into<ConstantVal> for Vec<T> {\n\n fn into(self) -> ConstantVal {\n\n ConstantVal::Coll(ConstantColl::NonPrimitive {\n\n elem_tpe: T::stype(),\n\n v: self.into_iter().map(|i| i.into()).collect(),\n\n })\n\n }\n\n}\n\n\n\nimpl<T: LiftIntoSType + StoredNonPrimitive + Into<ConstantVal>> Into<Constant> for Vec<T> {\n\n fn into(self) -> Constant {\n\n Constant {\n\n tpe: Self::stype(),\n", "file_path": "sigma-tree/src/ast/constant.rs", "rank": 49, "score": 103640.71752145007 }, { "content": "use super::dlog_group::EcPoint;\n\nuse crate::big_integer::BigInteger;\n\n\n\npub struct FirstDlogProverMessage(EcPoint);\n\npub struct SecondDlogProverMessage(BigInteger);\n\n\n\npub mod interactive_prover {\n\n use super::{FirstDlogProverMessage, SecondDlogProverMessage};\n\n use crate::{\n\n big_integer::BigInteger,\n\n sigma_protocol::{dlog_group, Challenge, DlogProverInput, ProveDlog},\n\n };\n\n\n\n pub fn simulate(\n\n public_input: &ProveDlog,\n\n challenge: &Challenge,\n\n ) -> (FirstDlogProverMessage, SecondDlogProverMessage) {\n\n todo!()\n\n }\n\n\n", "file_path": "sigma-tree/src/sigma_protocol/dlog_protocol.rs", "rank": 50, "score": 103559.58389473011 }, { "content": " pub fn first_message(proposition: &ProveDlog) -> (BigInteger, FirstDlogProverMessage) {\n\n let scalar = dlog_group::random_scalar_in_group_range();\n\n let g = dlog_group::generator();\n\n let a = dlog_group::exponentiate(&g, &scalar);\n\n (scalar.into(), FirstDlogProverMessage(a))\n\n }\n\n\n\n pub fn second_message(\n\n private_input: &DlogProverInput,\n\n rnd: BigInteger,\n\n challenge: &Challenge,\n\n ) -> SecondDlogProverMessage {\n\n todo!()\n\n }\n\n}\n", "file_path": "sigma-tree/src/sigma_protocol/dlog_protocol.rs", "rank": 51, "score": 103556.93764173287 }, { "content": "#[allow(dead_code)]\n\npub fn set_panic_hook() {\n\n // When the `console_error_panic_hook` feature is enabled, we can call the\n\n // `set_panic_hook` function at least once during initialization, and then\n\n // we will get better error messages if our code ever panics.\n\n //\n\n // For more details see\n\n // https://github.com/rustwasm/console_error_panic_hook#readme\n\n #[cfg(feature = \"console_error_panic_hook\")]\n\n console_error_panic_hook::set_once();\n\n}\n", "file_path": "bindings/ergo-wallet-lib-wasm/src/utils.rs", "rank": 52, "score": 101352.21596770632 }, { "content": "use super::op_code::OpCode;\n\nuse crate::sigma_protocol::{\n\n dlog_group::EcPoint, ProveDlog, SigmaBoolean, SigmaProofOfKnowledgeTree,\n\n};\n\nuse sigma_ser::{\n\n serializer::{SerializationError, SigmaSerializable},\n\n vlq_encode,\n\n};\n\nuse std::io;\n\n\n\nimpl SigmaSerializable for SigmaBoolean {\n\n fn sigma_serialize<W: vlq_encode::WriteSigmaVlqExt>(&self, w: &mut W) -> Result<(), io::Error> {\n\n self.op_code().sigma_serialize(w)?;\n\n match self {\n\n SigmaBoolean::ProofOfKnowledge(proof) => match proof {\n\n SigmaProofOfKnowledgeTree::ProveDHTuple { .. } => todo!(),\n\n SigmaProofOfKnowledgeTree::ProveDlog(v) => v.sigma_serialize(w),\n\n },\n\n SigmaBoolean::CAND(_) => todo!(),\n\n SigmaBoolean::TrivialProp(_) => Ok(()), // besides opCode no additional bytes\n", "file_path": "sigma-tree/src/serialization/sigmaboolean.rs", "rank": 65, "score": 93760.16782276653 }, { "content": " }\n\n }\n\n\n\n fn sigma_parse<R: vlq_encode::ReadSigmaVlqExt>(r: &mut R) -> Result<Self, SerializationError> {\n\n let op_code = OpCode::sigma_parse(r)?;\n\n match op_code {\n\n OpCode::PROVE_DLOG => Ok(SigmaBoolean::ProofOfKnowledge(\n\n SigmaProofOfKnowledgeTree::ProveDlog(ProveDlog::sigma_parse(r)?),\n\n )),\n\n _ => todo!(),\n\n }\n\n }\n\n}\n\n\n\nimpl SigmaSerializable for ProveDlog {\n\n fn sigma_serialize<W: vlq_encode::WriteSigmaVlqExt>(&self, w: &mut W) -> Result<(), io::Error> {\n\n self.h.sigma_serialize(w)\n\n }\n\n\n\n fn sigma_parse<R: vlq_encode::ReadSigmaVlqExt>(r: &mut R) -> Result<Self, SerializationError> {\n\n let p = EcPoint::sigma_parse(r)?;\n\n Ok(ProveDlog::new(p))\n\n }\n\n}\n", "file_path": "sigma-tree/src/serialization/sigmaboolean.rs", "rank": 66, "score": 93751.81868783914 }, { "content": "use crate::{chain::ErgoBox, sigma_protocol::SigmaBoolean};\n\nuse std::ops::Add;\n\n\n\n#[allow(dead_code)]\n\npub enum Value {\n\n Boolean(bool),\n\n Byte(i8),\n\n Short(i16),\n\n Int(i32),\n\n Long(i64),\n\n BigInt,\n\n GroupElement,\n\n SigmaProp(Box<SigmaBoolean>),\n\n Box(Box<ErgoBox>),\n\n AvlTree,\n\n Coll(Vec<Value>),\n\n Tup(Vec<Value>),\n\n}\n\n\n\nimpl Value {\n", "file_path": "sigma-tree/src/eval/value.rs", "rank": 67, "score": 93679.11921324018 }, { "content": " #[inline]\n\n pub fn byte(value: i8) -> Self {\n\n Value::Byte(value)\n\n }\n\n}\n\n\n\nimpl Add for Value {\n\n type Output = Self;\n\n fn add(self, other: Self) -> Self {\n\n match (self, other) {\n\n (Value::Byte(s), Value::Byte(o)) => Self::byte(s + o),\n\n _ => todo!(),\n\n }\n\n }\n\n}\n", "file_path": "sigma-tree/src/eval/value.rs", "rank": 68, "score": 93670.11107088254 }, { "content": "use sigma_ser::{\n\n serializer::{SerializationError, SigmaSerializable},\n\n vlq_encode,\n\n};\n\nuse std::io;\n\nuse vlq_encode::WriteSigmaVlqExt;\n\n\n\n#[derive(PartialEq, Eq, Hash, Copy, Clone)]\n\npub struct OpCode(u8);\n\n\n\nimpl OpCode {\n\n pub const LAST_DATA_TYPE: OpCode = OpCode(111);\n\n pub const LAST_CONSTANT_CODE: OpCode = OpCode(Self::LAST_DATA_TYPE.value() + 1);\n\n\n\n pub const FOLD: OpCode = Self::new_op_code(64);\n\n pub const PROVE_DLOG: OpCode = Self::new_op_code(93);\n\n\n\n const fn new_op_code(shift: u8) -> OpCode {\n\n OpCode(Self::LAST_CONSTANT_CODE.value() + shift)\n\n }\n", "file_path": "sigma-tree/src/serialization/op_code.rs", "rank": 69, "score": 91145.22622905049 }, { "content": "\n\n pub fn parse(b: u8) -> OpCode {\n\n OpCode(b)\n\n }\n\n\n\n pub const fn value(self) -> u8 {\n\n self.0\n\n }\n\n}\n\n\n\nimpl SigmaSerializable for OpCode {\n\n fn sigma_serialize<W: WriteSigmaVlqExt>(&self, w: &mut W) -> Result<(), io::Error> {\n\n w.put_u8(self.0)?;\n\n Ok(())\n\n }\n\n fn sigma_parse<R: vlq_encode::ReadSigmaVlqExt>(r: &mut R) -> Result<Self, SerializationError> {\n\n let code = r.get_u8()?;\n\n Ok(OpCode::parse(code))\n\n }\n\n}\n", "file_path": "sigma-tree/src/serialization/op_code.rs", "rank": 70, "score": 91144.24305277137 }, { "content": "//! Transitioning type for Base16 encoded bytes in JSON serialization\n\n\n\n#[cfg(feature = \"with-serde\")]\n\nuse serde::{Deserialize, Serialize};\n\nuse std::convert::TryFrom;\n\n\n\n/// Transitioning type for Base16 encoded bytes\n\n#[cfg_attr(feature = \"with-serde\", derive(Serialize, Deserialize))]\n\n#[cfg_attr(feature = \"with-serde\", serde(into = \"String\"))]\n\n#[derive(PartialEq, Eq, Debug, Clone)]\n\npub struct Base16EncodedBytes(String);\n\n\n\nimpl Base16EncodedBytes {\n\n /// Create from byte array ref (&[u8])\n\n pub fn new<T: ?Sized + AsRef<[u8]>>(input: &T) -> Base16EncodedBytes {\n\n Base16EncodedBytes(base16::encode_lower(input))\n\n }\n\n}\n\n\n\nimpl Into<String> for Base16EncodedBytes {\n", "file_path": "sigma-tree/src/chain/base16_bytes.rs", "rank": 71, "score": 91105.97352877635 }, { "content": " fn into(self) -> String {\n\n self.0\n\n }\n\n}\n\n\n\n/// Transitioning type for Base16 decoded bytes\n\n#[cfg_attr(feature = \"with-serde\", derive(Serialize, Deserialize))]\n\n#[cfg_attr(feature = \"with-serde\", serde(try_from = \"String\"))]\n\n#[derive(PartialEq, Eq, Debug, Clone)]\n\npub struct Base16DecodedBytes(pub Vec<u8>);\n\n\n\nimpl TryFrom<String> for Base16DecodedBytes {\n\n type Error = base16::DecodeError;\n\n fn try_from(str: String) -> Result<Self, Self::Error> {\n\n Ok(Base16DecodedBytes(base16::decode(&str)?))\n\n }\n\n}\n", "file_path": "sigma-tree/src/chain/base16_bytes.rs", "rank": 72, "score": 91104.22240508255 }, { "content": "//! ProverResult\n\nuse sigma_ser::serializer::SerializationError;\n\nuse sigma_ser::serializer::SigmaSerializable;\n\nuse sigma_ser::vlq_encode;\n\nuse std::io;\n\n\n\nuse super::context_extension::ContextExtension;\n\n#[cfg(feature = \"with-serde\")]\n\nuse serde::{Deserialize, Serialize};\n\n\n\n/// Proof of correctness of tx spending\n\n#[derive(Debug, PartialEq, Eq, Clone)]\n\n#[cfg_attr(feature = \"with-serde\", derive(Serialize, Deserialize))]\n\npub struct ProverResult {\n\n /// proof that satisfies final sigma proposition\n\n #[cfg_attr(feature = \"with-serde\", serde(rename = \"proofBytes\"))]\n\n pub proof: Vec<u8>,\n\n /// user-defined variables to be put into context\n\n #[cfg_attr(feature = \"with-serde\", serde(rename = \"extension\"))]\n\n pub extension: ContextExtension,\n", "file_path": "sigma-tree/src/chain/prover_result.rs", "rank": 73, "score": 90873.78550028711 }, { "content": "}\n\n\n\nimpl SigmaSerializable for ProverResult {\n\n fn sigma_serialize<W: vlq_encode::WriteSigmaVlqExt>(&self, w: &mut W) -> Result<(), io::Error> {\n\n w.put_u16(self.proof.len() as u16)?;\n\n w.write_all(&self.proof)?;\n\n self.extension.sigma_serialize(w)?;\n\n Ok(())\n\n }\n\n fn sigma_parse<R: vlq_encode::ReadSigmaVlqExt>(r: &mut R) -> Result<Self, SerializationError> {\n\n let proof_len = r.get_u16()?;\n\n let mut proof = vec![0; proof_len as usize];\n\n r.read_exact(&mut proof)?;\n\n let extension = ContextExtension::sigma_parse(r)?;\n\n Ok(ProverResult { proof, extension })\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "sigma-tree/src/chain/prover_result.rs", "rank": 74, "score": 90872.3009561621 }, { "content": " use super::*;\n\n use proptest::{collection::vec, prelude::*};\n\n use sigma_ser::test_helpers::*;\n\n\n\n impl Arbitrary for ProverResult {\n\n type Parameters = ();\n\n\n\n fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {\n\n (vec(any::<u8>(), 0..100))\n\n .prop_map(|v| Self {\n\n proof: v,\n\n extension: ContextExtension::empty(),\n\n })\n\n .boxed()\n\n }\n\n\n\n type Strategy = BoxedStrategy<Self>;\n\n }\n\n proptest! {\n\n\n\n #[test]\n\n fn ser_roundtrip(v in any::<ProverResult>()) {\n\n prop_assert_eq![sigma_serialize_roundtrip(&v), v];\n\n }\n\n }\n\n}\n", "file_path": "sigma-tree/src/chain/prover_result.rs", "rank": 75, "score": 90870.22102646278 }, { "content": "pub fn address_delete(address: AddressPtr) {\n\n if !address.is_null() {\n\n let boxed = unsafe { Box::from_raw(address) };\n\n std::mem::drop(boxed);\n\n }\n\n}\n", "file_path": "bindings/ergo-wallet-lib-c-core/src/lib.rs", "rank": 76, "score": 90512.35178426781 }, { "content": "impl SigmaSerializable for BoxValue {\n\n fn sigma_serialize<W: vlq_encode::WriteSigmaVlqExt>(&self, w: &mut W) -> Result<(), io::Error> {\n\n w.put_u64(self.0)\n\n }\n\n fn sigma_parse<R: vlq_encode::ReadSigmaVlqExt>(r: &mut R) -> Result<Self, SerializationError> {\n\n let v = r.get_u64()?;\n\n Ok(BoxValue(v))\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use proptest::{arbitrary::Arbitrary, prelude::*};\n\n\n\n impl Arbitrary for BoxValue {\n\n type Parameters = ();\n\n type Strategy = BoxedStrategy<Self>;\n\n fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {\n\n (1..i64::MAX).prop_map(|v| BoxValue(v as u64)).boxed()\n\n }\n\n }\n\n}\n", "file_path": "sigma-tree/src/chain/ergo_box/box_value.rs", "rank": 77, "score": 86290.55009248243 }, { "content": "//! Box value newtype\n\n\n\n#[cfg(feature = \"with-serde\")]\n\nuse serde::{Deserialize, Serialize};\n\nuse sigma_ser::serializer::{SerializationError, SigmaSerializable};\n\nuse sigma_ser::vlq_encode;\n\nuse std::{convert::TryFrom, io};\n\n\n\n/// Box value\n\n#[derive(PartialEq, Eq, Hash, Debug, Clone)]\n\n#[cfg_attr(feature = \"with-serde\", derive(Serialize, Deserialize))]\n\npub struct BoxValue(u64);\n\n\n\nimpl BoxValue {\n\n const MIN_RAW: u64 = 1;\n\n const MAX_RAW: u64 = i64::MAX as u64;\n\n\n\n /// Minimal value\n\n pub const MIN: BoxValue = BoxValue(BoxValue::MIN_RAW);\n\n\n", "file_path": "sigma-tree/src/chain/ergo_box/box_value.rs", "rank": 78, "score": 86288.76558877125 }, { "content": " /// Create from u64 with bounds check\n\n pub fn new(v: u64) -> Result<BoxValue, BoxValueError> {\n\n BoxValue::try_from(v)\n\n }\n\n\n\n /// Check if a value is in bounds\n\n pub fn within_bounds(v: u64) -> bool {\n\n v >= BoxValue::MIN_RAW && v <= BoxValue::MAX_RAW\n\n }\n\n\n\n /// Get u64 value\n\n pub fn value(&self) -> u64 {\n\n self.0\n\n }\n\n}\n\n\n\n/// BoxValue errors\n\n#[derive(PartialEq, Eq, Debug, Clone)]\n\npub enum BoxValueError {\n\n /// Value is out of bounds\n", "file_path": "sigma-tree/src/chain/ergo_box/box_value.rs", "rank": 79, "score": 86284.22098746832 }, { "content": " OutOfBounds,\n\n}\n\n\n\nimpl TryFrom<u64> for BoxValue {\n\n type Error = BoxValueError;\n\n fn try_from(v: u64) -> Result<Self, Self::Error> {\n\n if BoxValue::within_bounds(v) {\n\n Ok(BoxValue(v))\n\n } else {\n\n Err(BoxValueError::OutOfBounds)\n\n }\n\n }\n\n}\n\n\n\nimpl Into<u64> for BoxValue {\n\n fn into(self) -> u64 {\n\n self.0\n\n }\n\n}\n\n\n", "file_path": "sigma-tree/src/chain/ergo_box/box_value.rs", "rank": 80, "score": 86273.21533300132 }, { "content": "class OutputBoxes {\n\n internal var pointer: OutputBoxesPtr\n\n\n\n init(box: ErgoBoxCandidate) throws {\n\n var ptr: OutputBoxesPtr?\n\n let error = ergo_wallet_output_boxes_new(box.pointer, &ptr)\n\n try checkError(error)\n\n self.pointer = ptr!\n\n }\n\n\n\n deinit {\n\n ergo_wallet_output_boxes_delete(self.pointer)\n\n }\n\n}\n\n\n", "file_path": "bindings/ergo-wallet-lib-ios/Sources/ErgoWallet/ErgoWallet.swift", "rank": 81, "score": 84905.9088467529 }, { "content": "// Tries to get meaningful description from panic-error.\n\npub fn any_to_string(any: &Box<dyn Any + Send>) -> String {\n\n if let Some(s) = any.downcast_ref::<&str>() {\n\n s.to_string()\n\n } else if let Some(s) = any.downcast_ref::<String>() {\n\n s.clone()\n\n } else if let Some(error) = any.downcast_ref::<Box<dyn std::error::Error + Send>>() {\n\n error.to_string()\n\n } else {\n\n \"Unknown error occurred\".to_string()\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::error::Error;\n\n use std::panic;\n\n\n\n #[test]\n\n fn str_any() {\n", "file_path": "bindings/ergo-wallet-lib-android/src/main/rust/exception.rs", "rank": 82, "score": 78793.44584052754 }, { "content": "/// A wrapper around any struct implementing the `Read` trait, additionally\n\n/// allowing for `peek` operations to be performed. Therefore, the\n\n/// `PeekableReader` struct also implements the `Read` trait.\n\n///\n\n/// The primary invariant of the `PeekableReader` is that after calling the\n\n/// `peek` method, the next `read_byte` call will return the same result as\n\n/// the `peek` does. When the result is a byte (read off the wrapped reader),\n\n/// any read-type method of the `Reader` trait will include the byte as the\n\n/// first one. On the other hand, if the result is an `io::Error`, the error\n\n/// will be returned regardless of which read-type method of the `Reader` is\n\n/// invoked. Consecutive `peek`s before any read-type operation is used\n\n/// always return the same `io::Result`.\n\n///\n\npub trait Peekable: Read {\n\n /// When using peek_u8 you will get a Result<u8, &Error>, while when you call\n\n /// any of the `Read` functions you will get an io::Result<u8>, thereby\n\n /// consuming the io::Error (if any.)\n\n fn peek_u8(&mut self) -> Result<u8, &Error>;\n\n}\n\n\n\nimpl<R: Read> Peekable for PeekableReader<R> {\n\n /// Returns the `io::Result` which the Reader will return on the next\n\n /// `get_byte` call.\n\n ///\n\n /// If the `io::Result` is indeed an `io::Error`, the error will be returned\n\n /// for any subsequent read operation invoked upon the `Read`er.\n\n fn peek_u8(&mut self) -> Result<u8, &Error> {\n\n // Return either the currently cached peeked byte or obtain a new one\n\n // from the underlying reader.\n\n match self.peeked_result {\n\n Some(Ok(x)) => Ok(x),\n\n Some(Err(ref e)) => Err(e),\n\n None => {\n", "file_path": "sigma-ser/src/peekable_reader.rs", "rank": 83, "score": 75564.83631597302 }, { "content": "/// Write encoded unsigned values using VLQ and signed values first with ZigZag, then using VLQ\n\n/// for VLQ see [[https://en.wikipedia.org/wiki/Variable-length_quantity]]\n\n/// for ZigZag see https://developers.google.com/protocol-buffers/docs/encoding#types\n\npub trait WriteSigmaVlqExt: io::Write {\n\n /// Write i8 without encoding\n\n fn put_i8(&mut self, v: i8) -> io::Result<()> {\n\n Self::put_u8(self, v as u8)\n\n }\n\n\n\n /// Write u8 without encoding\n\n fn put_u8(&mut self, v: u8) -> io::Result<()> {\n\n self.write_all(&[v])\n\n }\n\n\n\n /// Encode using ZigZag and then VLQ.\n\n fn put_i16(&mut self, v: i16) -> io::Result<()> {\n\n Self::put_u32(self, zig_zag_encode::encode_i32(v as i32))\n\n }\n\n\n\n /// Encode using VLQ.\n\n fn put_u16(&mut self, v: u16) -> io::Result<()> {\n\n Self::put_u64(self, v as u64)\n\n }\n", "file_path": "sigma-ser/src/vlq_encode.rs", "rank": 84, "score": 75482.89445492288 }, { "content": "/// Read and decode values using VLQ (+ ZigZag for signed values) encoded and written with [`WriteSigmaVlqExt`]\n\n/// for VLQ see [[https://en.wikipedia.org/wiki/Variable-length_quantity]]\n\n/// for ZigZag see https://developers.google.com/protocol-buffers/docs/encoding#types\n\npub trait ReadSigmaVlqExt: peekable_reader::Peekable {\n\n /// Read i8 without decoding\n\n fn get_i8(&mut self) -> Result<i8, io::Error> {\n\n Self::get_u8(self).map(|v| v as i8)\n\n }\n\n\n\n /// Read u8 without decoding\n\n fn get_u8(&mut self) -> std::result::Result<u8, io::Error> {\n\n let mut slice = [0u8; 1];\n\n self.read_exact(&mut slice)?;\n\n Ok(slice[0])\n\n }\n\n\n\n /// Read and decode using VLQ and ZigZag value written with [`WriteSigmaVlqExt::put_i16`]\n\n fn get_i16(&mut self) -> Result<i16, VlqEncodingError> {\n\n Self::get_u32(self).and_then(|v| {\n\n let vd = zig_zag_encode::decode_u32(v);\n\n i16::try_from(vd).map_err(VlqEncodingError::TryFrom)\n\n })\n\n }\n", "file_path": "sigma-ser/src/vlq_encode.rs", "rank": 85, "score": 74328.58198814924 }, { "content": "#[allow(dead_code)]\n\npub fn unwrap_exc_or_default<T: Default>(env: &JNIEnv, res: ExceptionResult<T>) -> T {\n\n unwrap_exc_or(env, res, T::default())\n\n}\n\n\n", "file_path": "bindings/ergo-wallet-lib-android/src/main/rust/exception.rs", "rank": 86, "score": 67504.29583301273 }, { "content": "// Returns value or \"throws\" exception. `error_val` is returned, because exception will be thrown\n\n// at the Java side. So this function should be used only for the `panic::catch_unwind` result.\n\npub fn unwrap_exc_or<T>(env: &JNIEnv, res: ExceptionResult<T>, error_val: T) -> T {\n\n match res {\n\n Ok(val) => {\n\n match val {\n\n Ok(val) => val,\n\n Err(jni_error) => {\n\n // Do nothing if there is a pending Java-exception that will be thrown\n\n // automatically by the JVM when the native method returns.\n\n if !env.exception_check().unwrap() {\n\n // Throw a Java exception manually in case of an internal error.\n\n throw(env, &jni_error.to_string())\n\n }\n\n error_val\n\n }\n\n }\n\n }\n\n Err(ref e) => {\n\n throw(env, &any_to_string(e));\n\n error_val\n\n }\n\n }\n\n}\n\n\n\n// Same as `unwrap_exc_or` but returns default value.\n", "file_path": "bindings/ergo-wallet-lib-android/src/main/rust/exception.rs", "rank": 87, "score": 65457.556864192375 }, { "content": " pub fn with_segregation(_: Rc<Expr>) -> ErgoTree {\n\n todo!()\n\n }\n\n}\n\n\n\nimpl From<Rc<Expr>> for ErgoTree {\n\n fn from(expr: Rc<Expr>) -> Self {\n\n match expr.as_ref() {\n\n Expr::Const(Constant { tpe, .. }) if *tpe == SType::SSigmaProp => {\n\n ErgoTree::without_segregation(expr)\n\n }\n\n _ => ErgoTree::with_segregation(expr),\n\n }\n\n }\n\n}\n\nimpl SigmaSerializable for ErgoTreeHeader {\n\n fn sigma_serialize<W: WriteSigmaVlqExt>(&self, w: &mut W) -> Result<(), io::Error> {\n\n w.put_u8(self.0)?;\n\n Ok(())\n\n }\n", "file_path": "sigma-tree/src/ergo_tree.rs", "rank": 88, "score": 64578.35108023852 }, { "content": " fn sigma_parse<R: ReadSigmaVlqExt>(r: &mut R) -> Result<Self, SerializationError> {\n\n let header = r.get_u8()?;\n\n Ok(ErgoTreeHeader(header))\n\n }\n\n}\n\n\n\nimpl SigmaSerializable for ErgoTree {\n\n fn sigma_serialize<W: WriteSigmaVlqExt>(&self, w: &mut W) -> Result<(), io::Error> {\n\n self.header.sigma_serialize(w)?;\n\n match &self.tree {\n\n Ok(ParsedTree { constants, root }) => {\n\n if self.header.is_constant_segregation() {\n\n w.put_usize_as_u32(constants.len())?;\n\n assert!(\n\n constants.is_empty(),\n\n \"separate constants serialization is not yet supported\"\n\n );\n\n }\n\n match root {\n\n Ok(expr) => expr.sigma_serialize(w)?,\n", "file_path": "sigma-tree/src/ergo_tree.rs", "rank": 89, "score": 64572.65151070547 }, { "content": "#[derive(PartialEq, Eq, Debug, Clone)]\n\npub struct ErgoTreeRootParsingError {\n\n /// Ergo tree root expr bytes (faild to deserialize)\n\n pub bytes: Vec<u8>,\n\n /// Deserialization error\n\n pub error: SerializationError,\n\n}\n\n\n\n/// ErgoTree parsing (deserialization) error\n\n#[derive(PartialEq, Eq, Debug, Clone)]\n\npub enum ErgoTreeParsingError {\n\n /// Whole ErgoTree parsing (deserialization) error\n\n TreeParsingError(ErgoTreeConstantsParsingError),\n\n /// ErgoTree root expr parsing (deserialization) error\n\n RootParsingError(ErgoTreeRootParsingError),\n\n}\n\n\n\nimpl ErgoTree {\n\n const DEFAULT_HEADER: ErgoTreeHeader = ErgoTreeHeader(0);\n\n\n", "file_path": "sigma-tree/src/ergo_tree.rs", "rank": 90, "score": 64570.58744980605 }, { "content": " Ok(ErgoTree {\n\n header,\n\n tree: Ok(ParsedTree {\n\n constants,\n\n root: Ok(Rc::new(root)),\n\n }),\n\n })\n\n }\n\n\n\n fn sigma_parse_bytes(mut bytes: Vec<u8>) -> Result<Self, SerializationError> {\n\n let cursor = Cursor::new(&mut bytes[..]);\n\n let mut r = PeekableReader::new(cursor);\n\n let header = ErgoTreeHeader::sigma_parse(&mut r)?;\n\n if header.is_constant_segregation() {\n\n let constants_len = r.get_u32()?;\n\n if constants_len != 0 {\n\n return Ok(ErgoTree {\n\n header,\n\n tree: Err(ErgoTreeConstantsParsingError {\n\n bytes: bytes[1..].to_vec(),\n", "file_path": "sigma-tree/src/ergo_tree.rs", "rank": 91, "score": 64569.438522524986 }, { "content": " error: SerializationError::NotImplementedYet(\n\n \"separate constants serialization is not yet supported\".to_string(),\n\n ),\n\n }),\n\n });\n\n }\n\n }\n\n let constants = Vec::new();\n\n let mut rest_of_the_bytes = Vec::new();\n\n let _ = r.read_to_end(&mut rest_of_the_bytes);\n\n let rest_of_the_bytes_copy = rest_of_the_bytes.clone();\n\n match Expr::sigma_parse_bytes(rest_of_the_bytes) {\n\n Ok(parsed) => Ok(ErgoTree {\n\n header,\n\n tree: Ok(ParsedTree {\n\n constants,\n\n root: Ok(Rc::new(parsed)),\n\n }),\n\n }),\n\n Err(err) => Ok(ErgoTree {\n", "file_path": "sigma-tree/src/ergo_tree.rs", "rank": 92, "score": 64568.31162559973 }, { "content": " Err(ErgoTreeRootParsingError { bytes, .. }) => w.write_all(&bytes[..])?,\n\n }\n\n }\n\n Err(ErgoTreeConstantsParsingError { bytes, .. }) => w.write_all(&bytes[..])?,\n\n }\n\n Ok(())\n\n }\n\n\n\n fn sigma_parse<R: ReadSigmaVlqExt>(r: &mut R) -> Result<Self, SerializationError> {\n\n let header = ErgoTreeHeader::sigma_parse(r)?;\n\n if header.is_constant_segregation() {\n\n let constants_len = r.get_u32()?;\n\n if constants_len != 0 {\n\n return Err(SerializationError::NotImplementedYet(\n\n \"separate constants serialization is not yet supported\".to_string(),\n\n ));\n\n }\n\n }\n\n let constants = Vec::new();\n\n let root = Expr::sigma_parse(r)?;\n", "file_path": "sigma-tree/src/ergo_tree.rs", "rank": 93, "score": 64566.57379992548 }, { "content": " /// get Expr out of ErgoTree\n\n pub fn proposition(&self) -> Result<Rc<Expr>, ErgoTreeParsingError> {\n\n self.tree\n\n .clone()\n\n .map_err(ErgoTreeParsingError::TreeParsingError)\n\n .and_then(|t| t.root.map_err(ErgoTreeParsingError::RootParsingError))\n\n }\n\n\n\n /// Build ErgoTree using expr as is, without constants segregated\n\n pub fn without_segregation(expr: Rc<Expr>) -> ErgoTree {\n\n ErgoTree {\n\n header: ErgoTree::DEFAULT_HEADER,\n\n tree: Ok(ParsedTree {\n\n constants: Vec::new(),\n\n root: Ok(expr),\n\n }),\n\n }\n\n }\n\n\n\n /// Build ErgoTree with constants segregated from expr\n", "file_path": "sigma-tree/src/ergo_tree.rs", "rank": 94, "score": 64565.3049188236 }, { "content": " prop_assert_eq![sigma_serialize_roundtrip(&(v)), v];\n\n }\n\n }\n\n\n\n #[test]\n\n fn deserialization_non_parseable_tree_ok() {\n\n // constants length is set\n\n assert!(ErgoTree::sigma_parse_bytes(vec![0, 1]).is_ok());\n\n }\n\n\n\n #[test]\n\n fn deserialization_non_parseable_root_ok() {\n\n // constants length is zero, but Expr is invalid\n\n assert!(ErgoTree::sigma_parse_bytes(vec![0, 0, 1]).is_ok());\n\n }\n\n\n\n #[test]\n\n fn test_constant_segregation_header_flag_support() {\n\n let encoder = chain::AddressEncoder::new(chain::NetworkPrefix::Mainnet);\n\n let address = encoder\n\n .parse_address_from_str(\"9hzP24a2q8KLPVCUk7gdMDXYc7vinmGuxmLp5KU7k9UwptgYBYV\")\n\n .unwrap();\n\n\n\n let contract = chain::Contract::pay_to_address(address).unwrap();\n\n let bytes = &contract.get_ergo_tree().sigma_serialise_bytes();\n\n assert_eq!(&bytes[..2], vec![0u8, 8u8].as_slice());\n\n }\n\n}\n", "file_path": "sigma-tree/src/ergo_tree.rs", "rank": 95, "score": 64565.16805310321 }, { "content": " header,\n\n tree: Ok(ParsedTree {\n\n constants,\n\n root: Err(ErgoTreeRootParsingError {\n\n bytes: rest_of_the_bytes_copy,\n\n error: err,\n\n }),\n\n }),\n\n }),\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::{ast::ConstantVal, chain, sigma_protocol::SigmaProp, types::SType};\n\n use proptest::prelude::*;\n\n use sigma_ser::test_helpers::*;\n\n\n", "file_path": "sigma-tree/src/ergo_tree.rs", "rank": 96, "score": 64564.009160363144 }, { "content": "//! ErgoTree\n\nuse crate::{\n\n ast::{Constant, Expr},\n\n types::SType,\n\n};\n\nuse io::{Cursor, Read};\n\nuse sigma_ser::serializer::SerializationError;\n\nuse sigma_ser::serializer::SigmaSerializable;\n\nuse sigma_ser::{peekable_reader::PeekableReader, vlq_encode};\n\nuse std::io;\n\nuse std::rc::Rc;\n\nuse vlq_encode::{ReadSigmaVlqExt, WriteSigmaVlqExt};\n\n\n\n#[derive(PartialEq, Eq, Debug, Clone)]\n", "file_path": "sigma-tree/src/ergo_tree.rs", "rank": 97, "score": 64562.33551290245 }, { "content": " impl Arbitrary for ErgoTree {\n\n type Parameters = ();\n\n type Strategy = BoxedStrategy<Self>;\n\n\n\n fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {\n\n (any::<SigmaProp>())\n\n .prop_map(|p| {\n\n ErgoTree::from(Rc::new(Expr::Const(Constant {\n\n tpe: SType::SSigmaProp,\n\n v: ConstantVal::SigmaProp(Box::new(p)),\n\n })))\n\n })\n\n .boxed()\n\n }\n\n }\n\n\n\n proptest! {\n\n\n\n #[test]\n\n fn ser_roundtrip(v in any::<ErgoTree>()) {\n", "file_path": "sigma-tree/src/ergo_tree.rs", "rank": 98, "score": 64559.99938191821 }, { "content": "//! AST for ErgoTree\n\nuse crate::{serialization::op_code::OpCode, types::*};\n\nuse core::fmt;\n\nuse Expr::*;\n\n\n\nmod constant;\n\npub mod ops;\n\n\n\npub use constant::*;\n\n\n\n#[derive(PartialEq, Eq, Debug)]\n\n/// newtype for box register id\n\npub struct RegisterId(u8);\n\n\n\n#[derive(PartialEq, Eq, Debug)]\n\n/// Expression in ErgoTree\n\npub enum Expr {\n\n /// Constant value\n\n Const(Constant),\n\n /// Collection of values (same type)\n", "file_path": "sigma-tree/src/ast.rs", "rank": 99, "score": 59012.81410275754 } ]
Rust
src/lib.rs
load1n9/neko
addb9c2b2e911e33f2926230677c2d90b3b43de0
extern crate minifb; use std::cell::RefCell; use std::collections::HashMap; use minifb::Key; use minifb::Window; use minifb::WindowOptions; use minifb::MouseMode; use minifb::MouseButton; pub static SUCCESS: u32 = 0; pub static ERR_WINDOW_NOT_FOUND: u32 = 2; pub static ERR_UPDATE_WITH_BUFFER_FAILED: u32 = 3; thread_local! { static WINDOWS: RefCell<HashMap<u32, Window>> = RefCell::new(HashMap::new()); } fn str_to_mousekey_code(key: &str) -> Option<MouseButton> { match key { "left" => Some(MouseButton::Left), "right" => Some(MouseButton::Right), "middle" => Some(MouseButton::Middle), _ => None, } } fn str_to_key_code(key: &str) -> Option<Key> { match key { "key0" => Some(Key::Key0), "key1" => Some(Key::Key1), "key2" => Some(Key::Key2), "key3" => Some(Key::Key3), "key4" => Some(Key::Key4), "key5" => Some(Key::Key5), "key6" => Some(Key::Key6), "key7" => Some(Key::Key7), "key8" => Some(Key::Key8), "key9" => Some(Key::Key9), "a" => Some(Key::A), "b" => Some(Key::B), "c" => Some(Key::C), "d" => Some(Key::D), "e" => Some(Key::E), "f" => Some(Key::F), "g" => Some(Key::G), "h" => Some(Key::H), "i" => Some(Key::I), "j" => Some(Key::J), "k" => Some(Key::K), "l" => Some(Key::L), "m" => Some(Key::M), "n" => Some(Key::N), "o" => Some(Key::O), "p" => Some(Key::P), "q" => Some(Key::Q), "r" => Some(Key::R), "s" => Some(Key::S), "t" => Some(Key::T), "u" => Some(Key::U), "v" => Some(Key::V), "w" => Some(Key::W), "x" => Some(Key::X), "y" => Some(Key::Y), "z" => Some(Key::Z), "f1" => Some(Key::F1), "f2" => Some(Key::F2), "f3" => Some(Key::F3), "f4" => Some(Key::F4), "f5" => Some(Key::F5), "f6" => Some(Key::F6), "f7" => Some(Key::F7), "f8" => Some(Key::F8), "f9" => Some(Key::F9), "f10" => Some(Key::F10), "f11" => Some(Key::F11), "f12" => Some(Key::F12), "f13" => Some(Key::F13), "f14" => Some(Key::F14), "f15" => Some(Key::F15), "down" => Some(Key::Down), "left" => Some(Key::Left), "right" => Some(Key::Right), "up" => Some(Key::Up), "apostrophe" => Some(Key::Apostrophe), "backquote" => Some(Key::Backquote), "backslash" => Some(Key::Backslash), "comma" => Some(Key::Comma), "equal" => Some(Key::Equal), "leftbracket" => Some(Key::LeftBracket), "minus" => Some(Key::Minus), "period" => Some(Key::Period), "rightbracket" => Some(Key::RightBracket), "semicolon" => Some(Key::Semicolon), "slash" => Some(Key::Slash), "backspace" => Some(Key::Backspace), "delete" => Some(Key::Delete), "end" => Some(Key::End), "enter" => Some(Key::Enter), "escape" => Some(Key::Escape), "home" => Some(Key::Home), "insert" => Some(Key::Insert), "menu" => Some(Key::Menu), "pagedown" => Some(Key::PageDown), "pageup" => Some(Key::PageUp), "pause" => Some(Key::Pause), "space" => Some(Key::Space), "tab" => Some(Key::Tab), "numlock" => Some(Key::NumLock), "capslock" => Some(Key::CapsLock), "scrolllock" => Some(Key::ScrollLock), "leftshift" => Some(Key::LeftShift), "rightshift" => Some(Key::RightShift), "leftctrl" => Some(Key::LeftCtrl), "rightctrl" => Some(Key::RightCtrl), "numpad0" => Some(Key::NumPad0), "numpad1" => Some(Key::NumPad1), "numpad2" => Some(Key::NumPad2), "numpad3" => Some(Key::NumPad3), "numpad4" => Some(Key::NumPad4), "numpad5" => Some(Key::NumPad5), "numpad6" => Some(Key::NumPad6), "numpad7" => Some(Key::NumPad7), "numpad8" => Some(Key::NumPad8), "numpad9" => Some(Key::NumPad9), "numpaddot" => Some(Key::NumPadDot), "numpadslash" => Some(Key::NumPadSlash), "numpadasterisk" => Some(Key::NumPadAsterisk), "numpadminus" => Some(Key::NumPadMinus), "numpadplus" => Some(Key::NumPadPlus), "numpadenter" => Some(Key::NumPadEnter), "leftalt" => Some(Key::LeftAlt), "rightalt" => Some(Key::RightAlt), "leftsuper" => Some(Key::LeftSuper), "rightsuper" => Some(Key::RightSuper), "unknown" => Some(Key::Unknown), _ => None, } } #[no_mangle] pub extern "C" fn window_is_key_down(id: u32, key: *const i8) -> u32 { let key = unsafe { std::ffi::CStr::from_ptr(key) }.to_str().unwrap(); let key = str_to_key_code(key); if let Some(key) = key { WINDOWS.with(|map| { let map = map.borrow(); if let Some(window) = map.get(&id) { if window.is_key_down(key) { 1 } else { 0 } } else { ERR_WINDOW_NOT_FOUND } }) } else { 0 } } #[no_mangle] pub extern "C" fn window_is_mouse_button_down(id: u32, key: *const i8) -> u32 { let key = unsafe { std::ffi::CStr::from_ptr(key) }.to_str().unwrap(); let key = str_to_mousekey_code(key); if let Some(key) = key { WINDOWS.with(|map| { let map = map.borrow(); if let Some(window) = map.get(&id) { if window.get_mouse_down(key) { 1 } else { 0 } } else { ERR_WINDOW_NOT_FOUND } }) } else { 0 } } #[no_mangle] pub extern "C" fn window_get_mouse_x(id: u32) -> f32 { WINDOWS.with(|map| { let map = map.borrow(); if let Some(window) = map.get(&id) { let mouse = window.get_mouse_pos(MouseMode::Pass); if mouse.is_some() { let mouse = mouse.unwrap(); return mouse.0; } } 0.0 }) } #[no_mangle] pub extern "C" fn window_get_mouse_y(id: u32) -> f32 { WINDOWS.with(|map| { let map = map.borrow(); if let Some(window) = map.get(&id) { let mouse = window.get_mouse_pos(MouseMode::Pass); if mouse.is_some() { let mouse = mouse.unwrap(); return mouse.1; } } 0.0 }) } #[no_mangle] pub extern "C" fn window_get_mouse_scroll(id: u32) -> f32 { WINDOWS.with(|map| { let map = map.borrow(); if let Some(window) = map.get(&id) { let mouse = window.get_scroll_wheel(); if mouse.is_some() { let mouse = mouse.unwrap(); return mouse.1; } } 0.0 }) } #[no_mangle] pub extern "C" fn window_new(title: *const i8, width: usize, height: usize) -> u32 { WINDOWS.with(|map| { let mut map = map.borrow_mut(); let mut id = 0u32; while map.contains_key(&id) { id += 1; } let title = unsafe { std::ffi::CStr::from_ptr(title) }; let window = Window::new( title.to_str().unwrap(), width, height, WindowOptions::default(), ) .unwrap(); map.insert(id, window); id }) } #[no_mangle] pub extern "C" fn window_close(id: u32) -> u32 { WINDOWS.with(|map| { let mut map = map.borrow_mut(); if map.contains_key(&id) { map.remove(&id); SUCCESS } else { ERR_WINDOW_NOT_FOUND } }) } #[no_mangle] pub extern "C" fn window_is_open(id: u32) -> u32 { WINDOWS.with(|map| { let map = map.borrow(); if let Some(window) = map.get(&id) { if window.is_open() { 1 } else { 0 } } else { ERR_WINDOW_NOT_FOUND } }) } #[no_mangle] pub extern "C" fn window_is_active(id: u32) -> u32 { WINDOWS.with(|map| { let mut map = map.borrow_mut(); if let Some(window) = map.get_mut(&id) { if window.is_active() { 1 } else { 0 } } else { ERR_WINDOW_NOT_FOUND } }) } #[no_mangle] pub extern "C" fn window_limit_update_rate(id: u32, ms: u64) -> u32 { WINDOWS.with(|map| { let mut map = map.borrow_mut(); if let Some(window) = map.get_mut(&id) { window.limit_update_rate(if ms == 0 { None } else { Some(std::time::Duration::from_micros(ms)) }); SUCCESS } else { ERR_WINDOW_NOT_FOUND } }) } #[no_mangle] pub extern "C" fn window_update_with_buffer( id: u32, buffer: *const u8, width: usize, height: usize, ) -> u32 { WINDOWS.with(|map| { let mut map = map.borrow_mut(); if let Some(window) = map.get_mut(&id) { let bufu8: &[u8] = unsafe { std::slice::from_raw_parts(buffer, width * height * 4) }; let mut buffer = vec![0u32; width * height]; let mut idx = 0; while idx < buffer.len() { let r = bufu8[idx * 4 + 0] as u32; let g = bufu8[idx * 4 + 1] as u32; let b = bufu8[idx * 4 + 2] as u32; buffer[idx] = (r << 16) | (g << 8) | b; idx += 1; } if let Ok(()) = window.update_with_buffer(&buffer, width, height) { SUCCESS } else { ERR_UPDATE_WITH_BUFFER_FAILED } } else { ERR_WINDOW_NOT_FOUND } }) } #[no_mangle] pub extern "C" fn window_update(id: u32) -> u32 { WINDOWS.with(|map| { let mut map = map.borrow_mut(); if let Some(window) = map.get_mut(&id) { window.update(); SUCCESS } else { ERR_WINDOW_NOT_FOUND } }) }
extern crate minifb; use std::cell::RefCell; use std::collections::HashMap; use minifb::Key; use minifb::Window; use minifb::WindowOptions; use minifb::MouseMode; use minifb::MouseButton; pub static SUCCESS: u32 = 0; pub static ERR_WINDOW_NOT_FOUND: u32 = 2; pub static ERR_UPDATE_WITH_BUFFER_FAILED: u32 = 3; thread_local! { static WINDOWS: RefCell<HashMap<u32, Window>> = RefCell::new(HashMap::new()); } fn str_to_mousekey_code(key: &str) -> Option<MouseButton> { match key { "left" => Some(MouseButton::Left), "right" => Some(MouseButton::Right), "middle" => Some(MouseButton::Middle), _ => None, } } fn str_to_key_code(key: &str) -> Option<Key> { match key { "key0" => Some(Key::Key0), "key1" => Some(Key::Key1), "key2" => Some(Key::Key2), "key3" => Some(Key::Key3), "key4" => Some(Key::Key4), "key5" => Some(Key::Key5), "key6" => Some(Key::Key6), "key7" => Some(Key::Key7), "key8" => Some(Key::Key8), "key9" => Some(Key::Key9), "a" => Some(Key::A), "b" => Some(Key::B), "c" => Some(Key::C), "d" => Some(Key::D), "e" => Some(Key::E), "f" => Some(Key::F), "g" => Some(Key::G), "h" => Some(Key::H), "i" => Some(Key::I), "j" => Some(Key::J), "k" => Some(Key::K), "l" => Some(Key::L), "m" => Some(Key::M), "n" => Some(Key::N), "o" => Some(Key::O), "p" => Some(Key::P), "q" => Some(Key::Q), "r" => Some(Key::R), "s" => Some(Key::S), "t" => Some(Key::T), "u" => Some(Key::U), "v" => Some(Key::V), "w" => Some(Key::W), "x" => Some(Key::X), "y" => Some(Key::Y), "z" => Some(Key::Z), "f1" => Some(Key::F1), "f2" => Some(Key::F2), "f3" => Some(Key::F3), "f4" => Some(Key::F4), "f5" => Some(Key::F5), "f6" => Some(Key::F6), "f7" => Some(Key::F7), "f8" => Some(Key::F8), "f9" => Some(Key::F9), "f10" => Some(Key::F10), "f11" => Some(Key::F11), "f12" => Some(Key::F12), "f13" => Some(Key::F13), "f14" => Some(Key::F14), "f15" => Some(Key::F15), "down" => Some(Key::Down), "left" => Some(Key::Left), "right" => Some(Key::Right), "up" => Some(Key::Up), "apostrophe" => Some(Key::Apostrophe), "backquote" => Some(Key::Backquote), "backslash" => Some(Key::Backslash), "comma" => Some(Key::Comma), "equal" => Some(Key::Equal), "leftbracket" => Some(Key::LeftBracket), "minus" => Some(Key::Minus), "period" => Some(Key::Period), "rightbracket" => Some(Key::RightBracket), "semicolon" => Some(Key::Semicolon), "slash" => Some(Key::Slash), "backspace" => Some(Key::Backspace), "delete" => Some(Key::Delete), "end" => Some(Key::End), "enter" => Some(Key::Enter), "escape" => Some(Key::Escape), "home" => Some(Key::Home), "insert" => Some(Key::Insert), "menu" => Some(Key::Menu), "pagedown" => Some(Key::PageDown), "pageup" => Some(Key::PageUp), "pause" => Some(Key::Pause), "space" => Some(Key::Space), "tab" => Some(Key::Tab), "numlock" => Some(Key::NumLock), "capslock" => Some(Key::CapsLock), "scrolllock" => Some(Key::ScrollLock), "leftshift" => Some(Key::LeftShift), "rightshift" => Some(Key::RightShift), "leftctrl" => Some(Key::LeftCtrl), "rightctrl" => Some(Key::RightCtrl), "numpad0" => Some(Key::NumPad0), "numpad1" => Some(Key::NumPad1), "numpad2" => Some(Key::NumPad2), "numpad3" => Some(Key::NumPad3), "numpad4" => Some(Key::NumPad4), "numpad5" => Some(Key::NumPad5), "numpad6" => Some(Key::NumPad6), "numpad7" => Some(Key::NumPad7), "numpad8" => Some(Key::NumPad8), "numpad9" => Some(Key::NumPad9), "numpaddot" => Some(Key::NumPadDot), "numpadslash" => Some(Key::NumPadSlash), "numpadasterisk" => Some(Key::NumPadAsterisk), "numpadminus" => Some(Key::NumPadMinus), "numpadplus" => Some(Key::NumPadPlus), "numpadenter" => Some(Key::NumPadEnter), "leftalt" => Some(Key::LeftAlt), "rightalt" => Some(Key::RightAlt), "leftsuper" => Some(Key::LeftSuper), "rightsuper" => Some(Key::RightSuper), "unknown" => Some(Key::Unknown), _ => None, } } #[no_mangle] pub extern "C" fn window_is_key_down(id: u32, key: *const i8) -> u32 { let key = unsafe { std::ffi::CStr::from_ptr(key) }.to_str().unwrap(); let key = str_to_key_code(key); if let Some(key) = key { WINDOWS.with(|map| { let map = map.borrow(); if let Some(window) = map.get(&id) { if window.is_key_down(key) { 1 } else { 0 } } else { ERR_WINDOW_NOT_FOUND } }) } else { 0 } } #[no_mangle] pub extern "C" fn window_is_mouse_button_down(id: u32, key: *const i8) -> u32 { let key = unsafe { std::ffi::CStr::from_ptr(key) }.to_str().unwrap(); let key = str_to_mousekey_code(key); if let Some(key) = key { WINDOWS.with(|map| { let map = map.borrow(); if let Some(window) = map.get(&id) { if window.get_mouse_down(key) { 1 } else { 0 } } else { ERR_WINDOW_NOT_FOUND } }) } else { 0 } } #[no_mangle] pub extern "C" fn window_get_mouse_x(id: u32) -> f32 { WINDOWS.with(|map| { let map = map.borrow(); if let Some(window) = map.get(&id) { let mouse = window.get_mouse_pos(MouseMode::Pass); if mouse.is_some() { let mouse = mouse.unwrap(); return mouse.0; } } 0.0 }) } #[no_mangle] pub extern "C" fn window_get_mouse_y(id: u32) -> f32 { WINDOWS.with(|map| { let map = map.borrow(); if let Some(window) = map.get(&id) { let mouse = window.get_mouse_pos(MouseMode::Pass); if mouse.is_some() { let mouse = mouse.unwrap(); return mouse.1; } } 0.0 }) } #[no_mangle] pub extern "C" fn window_get_mouse_scroll(id: u32) -> f32 { WINDOWS.with(|map| { let map = map.borrow(); if let Some(window) = map.get(&id) { let mouse = window.get_scroll_wheel(); if mouse.is_some() { let mouse = mouse.unwrap(); return mouse.1; } } 0.0 }) } #[no_mangle] pub extern "C" fn window_new(title: *const i8, width: usize, height: usize) -> u32 { WINDOWS.with(|map| { let mut map = map.borrow_mut(); let mut id = 0u32; while map.contains_key(&id) { id += 1; } let title = unsafe { std::ffi::CStr::from_ptr(title) }; let window = Window::new( title.to_str().unwrap(), width, height, WindowOptions::default(), ) .unwrap(); map.insert(id, window); id }) } #[no_mangle] pub extern "C" fn window_close(id: u32) -> u32 { WINDOWS.with(|map| { let mut map = map.borrow_mut(); if map.contains_key(&id) { map.remove(&id); SUCCESS } else { ERR_WINDOW_NOT_FOUND } }) } #[no_mangle]
#[no_mangle] pub extern "C" fn window_is_active(id: u32) -> u32 { WINDOWS.with(|map| { let mut map = map.borrow_mut(); if let Some(window) = map.get_mut(&id) { if window.is_active() { 1 } else { 0 } } else { ERR_WINDOW_NOT_FOUND } }) } #[no_mangle] pub extern "C" fn window_limit_update_rate(id: u32, ms: u64) -> u32 { WINDOWS.with(|map| { let mut map = map.borrow_mut(); if let Some(window) = map.get_mut(&id) { window.limit_update_rate(if ms == 0 { None } else { Some(std::time::Duration::from_micros(ms)) }); SUCCESS } else { ERR_WINDOW_NOT_FOUND } }) } #[no_mangle] pub extern "C" fn window_update_with_buffer( id: u32, buffer: *const u8, width: usize, height: usize, ) -> u32 { WINDOWS.with(|map| { let mut map = map.borrow_mut(); if let Some(window) = map.get_mut(&id) { let bufu8: &[u8] = unsafe { std::slice::from_raw_parts(buffer, width * height * 4) }; let mut buffer = vec![0u32; width * height]; let mut idx = 0; while idx < buffer.len() { let r = bufu8[idx * 4 + 0] as u32; let g = bufu8[idx * 4 + 1] as u32; let b = bufu8[idx * 4 + 2] as u32; buffer[idx] = (r << 16) | (g << 8) | b; idx += 1; } if let Ok(()) = window.update_with_buffer(&buffer, width, height) { SUCCESS } else { ERR_UPDATE_WITH_BUFFER_FAILED } } else { ERR_WINDOW_NOT_FOUND } }) } #[no_mangle] pub extern "C" fn window_update(id: u32) -> u32 { WINDOWS.with(|map| { let mut map = map.borrow_mut(); if let Some(window) = map.get_mut(&id) { window.update(); SUCCESS } else { ERR_WINDOW_NOT_FOUND } }) }
pub extern "C" fn window_is_open(id: u32) -> u32 { WINDOWS.with(|map| { let map = map.borrow(); if let Some(window) = map.get(&id) { if window.is_open() { 1 } else { 0 } } else { ERR_WINDOW_NOT_FOUND } }) }
function_block-full_function
[ { "content": "const width = 800;\n", "file_path": "examples/test.ts", "rank": 2, "score": 55611.0160243587 }, { "content": "const height = 600;\n", "file_path": "examples/test.ts", "rank": 3, "score": 55611.0160243587 }, { "content": "const H = 300;\n", "file_path": "canvas/examples/tetris.ts", "rank": 4, "score": 54832.42854458706 }, { "content": "const W = 300;\n", "file_path": "canvas/examples/tetris.ts", "rank": 5, "score": 54832.42854458706 }, { "content": "let P = MakePermutation();\n", "file_path": "canvas/examples/perlin.ts", "rank": 6, "score": 54803.60461176964 }, { "content": "const P = MakePermutation();\n", "file_path": "canvas/examples/terrain.ts", "rank": 7, "score": 54803.60461176964 }, { "content": "let width: any\n", "file_path": "canvas/examples/spiral.ts", "rank": 8, "score": 54691.095863010516 }, { "content": " get height(): number {\n\n return this.#height;\n", "file_path": "canvas/Ctx.ts", "rank": 9, "score": 54691.095863010516 }, { "content": "let height: any\n", "file_path": "canvas/examples/spiral.ts", "rank": 10, "score": 54691.095863010516 }, { "content": " get width(): number {\n\n return this.#width;\n", "file_path": "canvas/Ctx.ts", "rank": 11, "score": 54691.095863010516 }, { "content": "export function unwrapBoolean(result: number): boolean {\n\n if (result !== 0 && result !== 1) {\n\n unwrap(result);\n\n return false;\n\n } else {\n\n return result === 1;\n\n }\n", "file_path": "lib/utils.ts", "rank": 12, "score": 30007.036543887454 }, { "content": "const SPACING = 4;\n", "file_path": "canvas/examples/spiral.ts", "rank": 13, "score": 30007.036543887454 }, { "content": " isKeyDown(key: string): boolean {\n\n return unwrapBoolean(lib.symbols.window_is_key_down(this.#id, new Uint8Array([...encode(key), 0])));\n", "file_path": "lib/Neko.ts", "rank": 14, "score": 29947.28940163874 }, { "content": "let rightPressed = false; \n", "file_path": "canvas/examples/brickbreaker.ts", "rank": 15, "score": 29137.084644085677 }, { "content": "const thetaZ = theta * Math.PI / 180\n", "file_path": "canvas/examples/terrain.ts", "rank": 16, "score": 29107.145138897977 }, { "content": "let leftPressed = false;\n", "file_path": "canvas/examples/brickbreaker.ts", "rank": 17, "score": 29107.145138897977 }, { "content": "const BLOCK_H = H / ROWS;\n", "file_path": "canvas/examples/tetris.ts", "rank": 18, "score": 29107.145138897977 }, { "content": "let thetaZ = theta * Math.PI / 180\n", "file_path": "canvas/examples/cube.ts", "rank": 19, "score": 29107.145138897977 }, { "content": "const BLOCK_W = W / COLS;\n", "file_path": "canvas/examples/tetris.ts", "rank": 20, "score": 29107.145138897977 }, { "content": " isMouseButtonDown(key: string): boolean {\n\n return unwrapBoolean(lib.symbols.window_is_mouse_button_down(this.#id, new Uint8Array([...encode(key), 0])));\n", "file_path": "lib/Neko.ts", "rank": 21, "score": 29079.069666885345 }, { "content": "const brickHeight = 20;\n", "file_path": "canvas/examples/brickbreaker.ts", "rank": 22, "score": 29024.158902857176 }, { "content": "const paddleHeight = 10;\n", "file_path": "canvas/examples/brickbreaker.ts", "rank": 23, "score": 29024.158902857176 }, { "content": "const brickWidth = 80;\n", "file_path": "canvas/examples/brickbreaker.ts", "rank": 24, "score": 29024.158902857176 }, { "content": "let paddleWidth = 75;\n", "file_path": "canvas/examples/brickbreaker.ts", "rank": 25, "score": 29024.158902857176 }, { "content": "let lastX: any\n", "file_path": "canvas/examples/spiral.ts", "rank": 26, "score": 28996.8191676101 }, { "content": "let currentX: number | undefined;\n", "file_path": "canvas/examples/tetris.ts", "rank": 27, "score": 28996.8191676101 }, { "content": "const foodX: any[] = [];\n", "file_path": "canvas/examples/snake.ts", "rank": 28, "score": 28996.8191676101 }, { "content": "let thetaX = theta * Math.PI / 180\n", "file_path": "canvas/examples/cube.ts", "rank": 29, "score": 28996.8191676101 }, { "content": "const thetaX = theta * Math.PI / 180\n", "file_path": "canvas/examples/terrain.ts", "rank": 30, "score": 28996.8191676101 }, { "content": "let paddleX = (canvas.width - paddleWidth) / 2;\n", "file_path": "canvas/examples/brickbreaker.ts", "rank": 31, "score": 28996.8191676101 }, { "content": "const brickOffsetLeft = 40;\n", "file_path": "canvas/examples/brickbreaker.ts", "rank": 32, "score": 28287.058158667696 }, { "content": " getMousePosition(): [number, number] {\n\n return [lib.symbols.window_get_mouse_x(this.#id), lib.symbols.window_get_mouse_y(this.#id)];\n", "file_path": "lib/Neko.ts", "rank": 33, "score": 28259.77370648719 }, { "content": "<p align=\"center\">\n\n <img src=https://raw.githubusercontent.com/load1n9/neko/master/assets/neko.png width=\"100rem\" /> \n\n <br>\n\n <h1 align=\"center\" >Neko 🐈</h1>\n\n</p>\n\n\n\nneko's twin frame buffer deno module built on top of mini_fb with canvas api implementation\n\n<p align=\"center\">\n\n <a href=\"https://github.com/load1n9/neko/stargazers\">\n\n <img alt=\"neko stars\" src=\"https://img.shields.io/github/stars/load1n9/neko?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAYAAAEFCu8CAAAABGdBTUEAALGPC/xhBQAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAHKADAAQAAAABAAAAHAAAAABHddaYAAABxElEQVRIDe2Wv04CQRDGAQuoTKQ2ITyADZWVJZWV+gJYWBNqKh/C16CRBlprWxsTE2NJfABNOH9z7Gzm2Nv7A8TCOMnHzs1838ze3e4ejUbMkiRZS64lP1x8MjTFr2DQE6Gl2nI+7POARXAmdbas44ku8eLGhU9UckRliX6qxM9sQvz0vrcVaaKJKdsSNO7LOtK1kvcbaXVRu4LMz9kgKoYwBq/KLBi/yC2DQgSnBaLMQ88Tx7Q3AVkDKHpgBdoak5HrCSjuaAW/6zOz+u/Q3ZfcVrhliuaPYCAqsSJekIO/TlWbn2BveAH5JZBVUWayusZW2ClTuPzMi6xTIp5abuBHxHLcZSyzkxHF1uNJRrV9gXBhOl7h6wFW/FqcaGILEmsDWfg9G//3858Az0lWaHhm5dP3i9JoDtTm+1UrUdMl72OZv10itfx3zOYpLAv/FPQNLvFj35Bnco/gzeCD72H6b4JYaDTpgidwaJOa3bCji5BsgYcDdJUamSMi2lQTCEbgu0Zz4Y5UX3tE3K/RTKny3qNWdst3UWU8sYtmU40py2Go9o5zC460l/guJjm1leZrjaiH4B4cVxUK12mGVTV/j/cDqcFClUX01ZEAAAAASUVORK5CYII=\" />\n\n </a>\n\n <a href=\"https://github.com/load1n9/neko/releases/latest/\">\n\n <img alt=\"neko releases\" src=\"https://img.shields.io/github/v/release/load1n9/neko?logo=github\" />\n\n </a>\n\n <a href=\"https://github.com/load1n9/neko/blob/master/LICENSE\">\n\n <img alt=\"neko License\" src=\"https://img.shields.io/github/license/load1n9/neko?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAYAAAEFCu8CAAAABGdBTUEAALGPC/xhBQAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAHKADAAQAAAABAAAAHAAAAABHddaYAAAC5UlEQVRIDd2WPWtVQRCGby5pVASLiGghQSxyG8Ui2KWwCfkH9olY2JneQkiR0oCIxH/gB+qVFDYBIWBAbAIRSbCRpLXwIxLiPT7vnNm9e87ZxJtUwYH3zO47Mzv7Mbv3tlo5KYriGtgAJ81OY1ENdG/YI4boFEOI911BXgY/pdtwGuAtXpvmB1tAXHDnUolE5urkPOQo6MqA3pXWmJJL4Bb4rQ7yEYfxsjnIF29NJIoNC6e5fxOL/qN+9KCz7AaLpN8zI415N2i2EptpGrkRIjGeAuvR6IY1hSFLFUOug9Ms2M7ZxIUNytm1mnME186sdI2BOCwAyQMg54ugzSmKmwbPwSbolKH+hbAtQdsOoF+BsF3anUVwBdiOWRidFZDKTTrKEAJTm3GVrGkHzw/uPZbyx7DNNLfB7KGmRsCcr+/gjaiPSpAOTyX9qG4L/XBDdWXDDf1M+wtQ5fwCOtcb4Dto6VpLmzByB6gqdHbTItGSJdAGqibJQhmRfCF7IN4beSF2G9CqnGXQrxofXU+EykllNeoczRgYytDKMubDIRK0g5MF8rE69cGu0u9nlUcqaUZ41W0qK2nGcSzr4D2wV9U9wxp1rnpxn8agXAOHMQ9cy9kbHM7ngY4gFb03TxrO/yfBUifTtXt78jCrjY/jgEFnMn45LuNWUtknuu7NSm7D3QEn3HbatV1Q2jvgIRf1sfODKQaeymxZoMLlTqsq1LF+HvaTqQOzEzUCfni0/eNIA+DfuE3KEtbsegckGmMktTXacnBHPVe687ugkpT+axCkkhBSyRSjWI2xf1KMMVmYiQdWksK9BEFiQoiYLIlvJA3/zeTzCejP0RbB6YPbhZuB+0pR3KcdX0LaJtju0ZgBL8Bd+sbz2QIaU2OfBX3BaQLsgZysQtrk0M8Sh1A0w3DyyYnGnAiZ4gqZ/TvI2A8OGd1YIbF7+F3P+B6dYpYdsJNZgrjO0UdOIhmom0nwL0pnfnzkL1803jAoKhvyAAAAAElFTkSuQmCC\" />\n\n </a>\n\n </p>\n\n<hr/>\n\n\n", "file_path": "README.md", "rank": 34, "score": 25640.785658484252 }, { "content": "## [Canvas API using Neko](https://github.com/load1n9/neko/tree/master/canvas)\n\n\n\n<img src=\"https://raw.githubusercontent.com/load1n9/neko/master/assets/tetris.png\" width=\"1500rem\" />\n\n### Usage\n\n\n\n#### Using Methods\n\n\n\n```typescript\n\nimport { World, Neko } from \"https://deno.land/x/neko/mod.ts\";\n\n\n\nconst width = 800;\n\nconst height = 600;\n\n\n\nconst neko = new Neko({\n\n title: \"Neko\",\n\n width,\n\n height,\n\n});\n\nconst frame = new Uint8Array(width * height * 4).fill(0x000000);\n\nclass Instance extends World {\n\n update() {\n\n frame[Math.round(Math.random() * frame.length)] = Math.round(Math.random() * 0xffffff);\n\n neko.setFrameBuffer(frame);\n\n }\n\n}\n\n\n\nnew Instance().start(neko, 60);\n\n```\n\n#### Using Functions\n\n```typescript\n\nimport { World, Neko } from \"https://deno.land/x/neko/mod.ts\";\n\n\n\nconst width = 800;\n\nconst height = 600;\n\n\n\nconst neko = new Neko({\n\n title: \"Neko\",\n\n width,\n\n height,\n\n});\n\nconst frame = new Uint8Array(width * height * 4).fill(0x000000);\n\nnew World().start(neko, {\n\n fps: 60,\n\n update: () => {\n\n frame[Math.round(Math.random() * frame.length)] = Math.round(Math.random() * 0xffffff);\n\n neko.setFrameBuffer(frame);\n\n }\n\n});\n\n```\n\n### Maintainers\n\n- Loading ([@load1n9](https://github.com/load1n9))\n\n\n", "file_path": "README.md", "rank": 35, "score": 25639.780087096955 }, { "content": "export { Neko } from \"./lib/Neko.ts\";\n", "file_path": "mod.ts", "rank": 36, "score": 25630.810228469283 }, { "content": "# Neko Canvas 🐈\n\n\n\n### Usage\n\n\n\n#### Render a red square\n\n```typescript\n\nimport { Canvas } from \"https://deno.land/x/neko/canvas/mod.ts\";\n\n\n\nconst canvas = new Canvas({\n\n title: \"Neko\",\n\n width: 200,\n\n height: 200,\n\n fps: 60,\n\n});\n\n\n\nconst ctx = canvas.getContext(\"2d\");\n\n\n\nctx.fillStyle = \"red\";\n\nctx.fillRect(10, 10, 50, 50);\n\n```\n\n#### Render an Image\n\n```typescript\n\nimport { Canvas, loadImage } from \"https://deno.land/x/neko/canvas/mod.ts\";\n\n\n\nconst canvas = new Canvas({\n\n title: \"Neko\",\n\n width: 500,\n\n height: 500,\n\n});\n\n\n\nconst ctx = canvas.getContext(\"2d\");\n\n// image created by Hashrock (https://hashrock.studio.site)\n\nconst img = await loadImage(\"https://deno.land/images/artwork/hashrock_simple.png\");\n\nctx.drawImage(img, 0, 0);\n\n```\n", "file_path": "canvas/README.md", "rank": 37, "score": 24988.44384608725 }, { "content": "import { Plug } from \"https://deno.land/x/[email protected]/mod.ts\";\n\nimport { NekoOptions } from \"./types.ts\";\n\nimport { encode, unwrap, unwrapBoolean } from \"./utils.ts\";\n\n\n\nconst options: Plug.Options = {\n\n name: \"neko\",\n\n urls: {\n\n windows: `https://github.com/load1n9/neko/blob/master/dist/neko.dll?raw=true`,\n\n darwin: `https://github.com/load1n9/neko/blob/master/dist/libneko.dylib?raw=true`,\n\n linux: `https://github.com/load1n9/neko/blob/master/dist/libneko.so?raw=true` \n\n },\n\n};\n\n\n\nconst lib = await Plug.prepare(options, {\n\n window_new: {\n\n parameters: [\"pointer\", \"usize\", \"usize\"],\n\n result: \"u32\",\n\n },\n\n\n\n window_close: {\n\n parameters: [\"u32\"],\n\n result: \"u32\",\n\n },\n\n window_is_open: {\n\n parameters: [\"u32\"],\n\n result: \"u32\",\n\n },\n\n window_is_key_down: {\n\n parameters: [\"u32\", \"pointer\"],\n\n result: \"u32\",\n\n },\n\n\n\n window_is_mouse_button_down: {\n\n parameters: [\"u32\", \"pointer\"],\n\n result: \"u32\",\n\n },\n\n\n\n window_is_active: {\n\n parameters: [\"u32\"],\n\n result: \"u32\",\n\n },\n\n\n\n window_limit_update_rate: {\n\n parameters: [\"u32\", \"u64\"],\n\n result: \"u32\",\n\n },\n\n\n\n window_update_with_buffer: {\n\n parameters: [\"u32\", \"pointer\", \"usize\", \"usize\"],\n\n result: \"u32\",\n\n },\n\n\n\n window_update: {\n\n parameters: [\"u32\"],\n\n result: \"u32\",\n\n },\n\n\n\n window_get_mouse_x: {\n\n parameters: [\"u32\"],\n\n result: \"f32\",\n\n },\n\n\n\n window_get_mouse_y: {\n\n parameters: [\"u32\"],\n\n result: \"f32\",\n\n },\n\n\n\n window_get_mouse_scroll: {\n\n parameters: [\"u32\"],\n\n result: \"f32\",\n\n },\n\n});\n\n\n\n\n\nexport class Neko {\n\n #id;\n\n width: number;\n\n height: number;\n\n constructor(options: NekoOptions) {\n\n this.width = options.width;\n\n this.height = options.height;\n\n this.#id = lib.symbols.window_new(\n\n new Uint8Array([...encode(options.title), 0]),\n\n options.width,\n\n options.height,\n\n );\n\n }\n\n limitUpdateRate(micros: number) {\n\n unwrap(lib.symbols.window_limit_update_rate(this.#id, micros));\n\n }\n\n setFrameBuffer(buffer: Uint8Array, width?: number, height?: number) {\n\n unwrap(\n\n lib.symbols.window_update_with_buffer(\n\n this.#id,\n\n buffer,\n\n width ?? this.width,\n\n height ?? this.height,\n\n )\n\n );\n\n }\n\n\n\n update() {\n\n unwrap(lib.symbols.window_update(this.#id));\n\n }\n\n\n\n close() {\n\n unwrap(lib.symbols.window_close(this.#id));\n\n }\n\n\n\n isKeyDown(key: string): boolean {\n\n return unwrapBoolean(lib.symbols.window_is_key_down(this.#id, new Uint8Array([...encode(key), 0])));\n\n }\n\n\n\n isMouseButtonDown(key: string): boolean {\n\n return unwrapBoolean(lib.symbols.window_is_mouse_button_down(this.#id, new Uint8Array([...encode(key), 0])));\n\n }\n\n\n\n getScroll(): number {\n\n return lib.symbols.window_get_mouse_scroll(this.#id);\n\n }\n\n\n\n\n\n getMousePosition(): [number, number] {\n\n return [lib.symbols.window_get_mouse_x(this.#id), lib.symbols.window_get_mouse_y(this.#id)];\n\n }\n\n\n\n get open(): boolean {\n\n return unwrapBoolean(lib.symbols.window_is_open(this.#id));\n\n }\n\n\n\n get active(): boolean {\n\n return unwrapBoolean(lib.symbols.window_is_active(this.#id));\n\n }\n\n}\n", "file_path": "lib/Neko.ts", "rank": 38, "score": 24981.80989607868 }, { "content": "import { World, Neko } from \"../mod.ts\";\n\n\n\nconst width = 800;\n\nconst height = 600;\n\n\n\nconst neko = new Neko({\n\n title: \"Neko\",\n\n width,\n\n height,\n\n});\n\nconst frame = new Uint8Array(width * height * 4).fill(0x000000);\n\nclass Instance extends World {\n\n update() {\n\n frame[Math.round(Math.random() * frame.length)] = Math.round(Math.random() * 0xffffff);\n\n neko.setFrameBuffer(frame);\n\n }\n\n}\n\n\n", "file_path": "examples/test.ts", "rank": 39, "score": 24981.80989607868 }, { "content": "import { Neko } from \"./Neko.ts\";\n\nimport { WorldSettings } from \"./types.ts\";\n\n\n\nexport class World {\n\n start(renderer: Neko, settingsOrFps: number | WorldSettings = 60) {\n\n const settings = typeof settingsOrFps === \"number\" ? { fps: settingsOrFps } : settingsOrFps;\n\n const fps = typeof settingsOrFps === \"number\" ? settingsOrFps : settingsOrFps.fps;\n\n (settings.setup || this.setup)();\n\n setInterval(() => {\n\n if (renderer.open) {\n\n (settings.update || this.update)();\n\n } else {\n\n Deno.exit(0)\n\n }\n\n }, 1 / fps * 1000)\n\n }\n\n setup() {\n\n \n\n }\n\n update() {\n\n\n\n }\n", "file_path": "lib/World.ts", "rank": 40, "score": 24981.80989607868 }, { "content": "import { Neko, World } from \"../mod.ts\";\n\nimport { createCanvas } from \"https://deno.land/x/[email protected]/mod.ts\";\n\nimport type {\n\n CanvasRenderingContext2D,\n\n EmulatedCanvas2D,\n\n} from \"https://deno.land/x/[email protected]/mod.ts\";\n\ninterface Config {\n\n title?: string;\n\n width?: number;\n\n height?: number;\n\n fps?: number;\n\n}\n\nexport class Canvas {\n\n #title: string;\n\n #ctx: CanvasRenderingContext2D;\n\n #canvas: EmulatedCanvas2D;\n\n window: Neko;\n\n #world: World;\n\n #width: number;\n\n #height: number;\n\n #fps: number;\n\n constructor(config: Config) {\n\n this.#world = new World();\n\n this.#height = config.height || 200;\n\n this.#width = config.width || 200;\n\n this.#title = config.title || \"Neko\";\n\n this.#fps = config.fps || 60;\n\n this.#canvas = createCanvas(this.#width, this.#height);\n\n this.#ctx = this.#canvas.getContext(\"2d\");\n\n this.window = new Neko({\n\n title: this.#title,\n\n width: this.#width,\n\n height: this.#height,\n\n });\n\n this.#world.start(this.window, {\n\n fps: this.#fps,\n\n update: () => {\n\n this.window.setFrameBuffer(\n\n this.#canvas.getRawBuffer(0, 0, this.#width, this.#height),\n\n );\n\n },\n\n });\n\n }\n\n getContext(_type = \"2d\"): CanvasRenderingContext2D {\n\n return this.#ctx;\n\n }\n\n get canvas(): EmulatedCanvas2D {\n\n return this.#canvas;\n\n }\n\n get width(): number {\n\n return this.#width;\n\n }\n\n get height(): number {\n\n return this.#height;\n\n }\n\n}\n", "file_path": "canvas/Ctx.ts", "rank": 41, "score": 24981.80989607868 }, { "content": "export interface NekoOptions {\n\n title: string;\n\n width: number;\n\n height: number;\n\n}\n\nexport interface WorldSettings {\n\n fps: number;\n\n setup?: () => void;\n\n update?: () => void;\n", "file_path": "lib/types.ts", "rank": 42, "score": 24981.80989607868 }, { "content": "export const encode = (str: string): Uint8Array => new TextEncoder().encode(str);\n\n\n\nconst ERROR_CODES: {\n\n [code: number]: string | undefined;\n\n} = {\n\n 2: \"Window not found\",\n\n 3: \"Failed to updateWithBuffer\",\n\n};\n\n\n\nexport function unwrap(result: number) {\n\n let error;\n\n if ((error = ERROR_CODES[result])) {\n\n throw new Error(`Unwrap called on Error Value (${result}): ${error}`);\n\n }\n\n}\n\n\n\nexport function unwrapBoolean(result: number): boolean {\n\n if (result !== 0 && result !== 1) {\n\n unwrap(result);\n\n return false;\n\n } else {\n\n return result === 1;\n\n }\n\n}\n", "file_path": "lib/utils.ts", "rank": 43, "score": 24981.80989607868 }, { "content": "export * from \"./Ctx.ts\";\n", "file_path": "canvas/mod.ts", "rank": 44, "score": 24981.80989607868 }, { "content": "let x = canvas.width / 2;\n", "file_path": "canvas/examples/brickbreaker.ts", "rank": 45, "score": 24856.22541582151 }, { "content": "// deno-lint-ignore-file no-explicit-any\n\nimport { Canvas } from \"../mod.ts\";\n\n\n\nconst COLS = 20;\n\nconst ROWS = 20;\n\nconst board: any = [];\n\n// deno-lint-ignore no-unused-vars prefer-const\n\nlet score = 0;\n\nlet lose = false;\n\nlet interval: any;\n\nlet intervalRender: any;\n\nlet intervalRotate: any;\n\nlet current: any;\n\nlet currentX: number | undefined;\n\nlet currentY: number | undefined;\n\nlet freezed: boolean | undefined;\n\nconst shapes = [\n\n [1, 1, 1, 1],\n\n [1, 1, 1, 0, 1],\n\n [1, 1, 1, 0, 0, 0, 1],\n\n [1, 1, 0, 0, 1, 1],\n\n [1, 1, 0, 0, 0, 1, 1],\n\n [0, 1, 1, 0, 1, 1],\n\n [0, 1, 0, 0, 1, 1, 1],\n\n];\n\nconst colors = [\n\n \"cyan\",\n\n \"orange\",\n\n \"blue\",\n\n \"yellow\",\n\n \"red\",\n\n \"green\",\n\n \"purple\",\n\n];\n\nfunction newShape() {\n\n const id = Math.floor(Math.random() * shapes.length);\n\n const shape = shapes[id];\n\n current = [];\n\n for (let y = 0; y < 4; ++y) {\n\n current[y] = [];\n\n for (let x = 0; x < 4; ++x) {\n\n const i = 4 * y + x;\n\n if (typeof shape[i] != \"undefined\" && shape[i]) {\n\n current[y][x] = id + 1;\n\n } else {\n\n current[y][x] = 0;\n\n }\n\n }\n\n }\n\n freezed = false;\n\n currentX = 5;\n\n currentY = 0;\n\n}\n\n\n\nfunction init() {\n\n for (let y = 0; y < ROWS; ++y) {\n\n board[y] = [];\n\n for (let x = 0; x < COLS; ++x) {\n\n board[y][x] = 0;\n\n }\n\n }\n\n}\n\n\n\nfunction tick() {\n\n if (valid(0, 1)) {\n\n (currentY!)++;\n\n }\n\n else {\n\n freeze();\n\n valid(0, 1);\n\n clearLines();\n\n if (lose) {\n\n clearAllIntervals();\n\n return false;\n\n }\n\n newShape();\n\n }\n\n}\n\n\n\nfunction freeze() {\n\n for (let y = 0; y < 4; ++y) {\n\n for (let x = 0; x < 4; ++x) {\n\n if (current[y][x]) {\n\n board[y + currentY!][x + currentX!] = current[y][x];\n\n }\n\n }\n\n }\n\n freezed = true;\n\n}\n\n\n\nfunction rotate(current: any) {\n\n const newCurrent: any = [];\n\n for (let y = 0; y < 4; ++y) {\n\n newCurrent[y] = [];\n\n for (let x = 0; x < 4; ++x) {\n\n newCurrent[y][x] = current[3 - x][y];\n\n }\n\n }\n\n\n\n return newCurrent;\n\n}\n\n\n\nfunction clearLines() {\n\n for (let y = ROWS - 1; y >= 0; --y) {\n\n let rowFilled = true;\n\n for (let x = 0; x < COLS; ++x) {\n\n if (board[y][x] == 0) {\n\n rowFilled = false;\n\n break;\n\n }\n\n }\n\n if (rowFilled) {\n\n for (let yy = y; yy > 0; --yy) {\n\n for (let x = 0; x < COLS; ++x) {\n\n board[yy][x] = board[yy - 1][x];\n\n }\n\n }\n\n y++;\n\n }\n\n }\n\n}\n\n\n\nfunction keyPress(key: string) {\n\n switch (key) {\n\n case \"left\":\n\n if (valid(-1)) {\n\n (currentX!)--;\n\n }\n\n break;\n\n case \"right\":\n\n if (valid(1)) {\n\n (currentX!)++;\n\n }\n\n break;\n\n case \"down\":\n\n if (valid(0, 1)) {\n\n (currentY!)++;\n\n }\n\n break;\n\n // deno-lint-ignore no-case-declarations\n\n case \"rotate\":\n\n const rotated = rotate(current);\n\n if (valid(0, 0, rotated)) {\n\n current = rotated;\n\n }\n\n break;\n\n case \"drop\":\n\n while (valid(0, 1)) {\n\n (currentY!)++;\n\n }\n\n tick();\n\n break;\n\n }\n\n}\n\nfunction checkForKeyPress() {\n\n if(canvas.window.isKeyDown(\"up\")) {\n\n keyPress(\"rotate\");\n\n }\n\n}\n\nfunction valid(offsetX = 0, offsetY = 0, newCurrent?: any) {\n\n offsetX = currentX! + offsetX;\n\n offsetY = currentY! + offsetY;\n\n newCurrent = newCurrent || current;\n\n\n\n for (let y = 0; y < 4; y++) {\n\n for (let x = 0; x < 4; x++) {\n\n if (newCurrent[y][x]) {\n\n if (\n\n typeof board[y + offsetY] == \"undefined\" ||\n\n typeof board[y + offsetY][x + offsetX] == \"undefined\" ||\n\n board[y + offsetY][x + offsetX] ||\n\n x + offsetX < 0 ||\n\n y + offsetY >= ROWS ||\n\n x + offsetX >= COLS\n\n ) {\n\n if (offsetY == 1 && freezed) {\n\n lose = true;\n\n }\n\n return false;\n\n }\n\n }\n\n }\n\n }\n\n return true;\n\n}\n\n\n\nfunction playButtonClicked() {\n\n newGame();\n\n}\n\n\n\nfunction newGame() {\n\n clearAllIntervals();\n\n intervalRender = setInterval(render, 30);\n\n intervalRotate = setInterval(checkForKeyPress, 70);\n\n init();\n\n newShape();\n\n lose = false;\n\n interval = setInterval(tick, 400);\n\n}\n\n\n\nfunction clearAllIntervals() {\n\n clearInterval(interval);\n\n clearInterval(intervalRender);\n\n clearInterval(intervalRotate);\n\n}\n\n\n\nconst canvas = new Canvas({\n\n title: \"Tetris\",\n\n width: 300,\n\n height: 300,\n\n});\n\nconst ctx = canvas.getContext(\"2d\");\n\nconst W = 300;\n\nconst H = 300;\n\nconst BLOCK_W = W / COLS;\n\nconst BLOCK_H = H / ROWS;\n\n\n\nfunction drawBlock(x: number, y: number) {\n\n ctx.fillRect(BLOCK_W * x, BLOCK_H * y, BLOCK_W - 1, BLOCK_H - 1);\n\n ctx.strokeRect(BLOCK_W * x, BLOCK_H * y, BLOCK_W - 1, BLOCK_H - 1);\n\n}\n\n\n\nfunction render() {\n\n ctx.clearRect(0, 0, W, H);\n\n if(canvas.window.isKeyDown(\"space\")) {\n\n keyPress(\"drop\");\n\n }\n\n if(canvas.window.isKeyDown(\"left\")) {\n\n keyPress(\"left\");\n\n }\n\n if(canvas.window.isKeyDown(\"right\")) {\n\n keyPress(\"right\");\n\n }\n\n if(canvas.window.isKeyDown(\"down\")) {\n\n keyPress(\"down\");\n\n }\n\n ctx.strokeStyle = \"black\";\n\n for (let x = 0; x < COLS; ++x) {\n\n for (let y = 0; y < ROWS; ++y) {\n\n if (board[y][x]) {\n\n ctx.fillStyle = colors[board[y][x] - 1];\n\n drawBlock(x, y);\n\n }\n\n }\n\n }\n\n\n\n ctx.fillStyle = \"red\";\n\n ctx.strokeStyle = \"black\";\n\n for (let y = 0; y < 4; ++y) {\n\n for (let x = 0; x < 4; ++x) {\n\n if (current[y][x]) {\n\n ctx.fillStyle = colors[current[y][x] - 1];\n\n drawBlock(currentX! + x, currentY! + y);\n\n }\n\n }\n\n }\n\n}\n\nplayButtonClicked();\n", "file_path": "canvas/examples/tetris.ts", "rank": 46, "score": 24364.864698215602 }, { "content": "// ported from https://codepen.io/hakimel/pen/QdWpRv\n\nimport { Canvas } from \"../mod.ts\";\n\nconst canvas = new Canvas({\n\n title: \"spiral\",\n\n width: 1000,\n\n height: 1000,\n\n});\n\nconst context = canvas.getContext(\"2d\");\n\n\n\nlet time = 0;\n\nlet velocity = 0.1;\n\nconst velocityTarget = 0.1;\n\n// deno-lint-ignore no-explicit-any\n\nlet width: any\n\n// deno-lint-ignore no-explicit-any\n\nlet height: any\n\n// deno-lint-ignore no-explicit-any no-unused-vars\n\nlet lastX: any\n\n// deno-lint-ignore no-explicit-any no-unused-vars\n\nlet lastY: any\n\n\n\nconst MAX_OFFSET = 400;\n\nconst SPACING = 4;\n\nconst POINTS = MAX_OFFSET / SPACING;\n\nconst PEAK = MAX_OFFSET * 0.25;\n\nconst POINTS_PER_LAP = 6;\n\nconst SHADOW_STRENGTH = 6;\n\n\n\nsetup();\n\n\n\nfunction setup() {\n\n resize();\n\n step();\n\n}\n\n\n\nfunction resize() {\n\n width = canvas.width;\n\n height = canvas.height;\n\n}\n\n\n\nfunction step() {\n\n time += velocity;\n\n velocity += (velocityTarget - velocity) * 0.3;\n\n\n\n clear();\n\n render();\n\n}\n\n\n\nfunction clear() {\n\n context.clearRect(0, 0, width, height);\n\n}\n\n\n\nfunction render() {\n\n // deno-lint-ignore prefer-const\n\n let x, y, cx = width / 2, cy = height / 2;\n\n\n\n context.globalCompositeOperation = \"lighter\";\n\n context.strokeStyle = \"#fff\";\n\n context.shadowColor = \"#fff\";\n\n context.lineWidth = 2;\n\n context.beginPath();\n\n\n\n for (let i = POINTS; i > 0; i--) {\n\n const value = i * SPACING + (time % SPACING);\n\n\n\n const ax = Math.sin(value / POINTS_PER_LAP) * Math.PI;\n\n const ay = Math.cos(value / POINTS_PER_LAP) * Math.PI;\n\n\n\n x = ax * value, y = ay * value * 0.35;\n\n\n\n const o = 1 - (Math.min(value, PEAK) / PEAK);\n\n\n\n y -= Math.pow(o, 2) * 200;\n\n y += 200 * value / MAX_OFFSET;\n\n y += x / cx * width * 0.1;\n\n\n\n context.globalAlpha = 1 - (value / MAX_OFFSET);\n\n context.shadowBlur = SHADOW_STRENGTH * o;\n\n\n\n context.lineTo(cx + x, cy + y);\n\n context.stroke();\n\n\n\n context.beginPath();\n\n context.moveTo(cx + x, cy + y);\n\n }\n\n\n\n context.lineTo(cx, cy - 200);\n\n context.lineTo(cx, 0);\n\n context.stroke();\n\n}\n\n\n", "file_path": "canvas/examples/spiral.ts", "rank": 47, "score": 24364.864698215602 }, { "content": "import { Canvas } from \"../mod.ts\";\n\n\n\nconst canvas = new Canvas({\n\n title: \"Neko\",\n\n width: 200,\n\n height: 200,\n\n fps: 60,\n\n});\n\n\n\nconst ctx = canvas.getContext(\"2d\");\n\n\n\nctx.fillStyle = \"red\";\n", "file_path": "canvas/examples/rect.ts", "rank": 48, "score": 24364.864698215602 }, { "content": "// ported from https://github.com/AleikovStudio/Brick-breaker-game-JS-HTML-Canvas\n\nimport { Canvas } from \"../mod.ts\";\n\nconst canvas = new Canvas({\n\n title: \"Brick Breaker\",\n\n width: 500,\n\n height: 500,\n\n});\n\nconst ctx = canvas.getContext(\"2d\");\n\n\n\nlet x = canvas.width / 2;\n\nlet y = canvas.height - 80;\n\nconst paddleHeight = 10;\n\nlet paddleWidth = 75;\n\nlet paddleX = (canvas.width - paddleWidth) / 2;\n\nlet rightPressed = false; \n\nlet leftPressed = false;\n\nconst ballRadius = 10;\n\nconst brickRowCount = 7;\n\nconst brickColumnCount = 5;\n\n\n\nlet count = brickRowCount * brickColumnCount;\n\nlet rem = count;\n\n\n\nlet score = 0;\n\nlet lives = 3;\n\n\n\nconst brickWidth = 80;\n\nconst brickHeight = 20;\n\nconst brickPadding = 7;\n\nconst brickOffsetTop = 30;\n\nconst brickOffsetLeft = 40;\n\nlet speedup1 = 0;\n\nlet speedup2 = 0;\n\nlet speedup3 = 0;\n\nlet speedup4 = 0;\n\nlet speedup5 = 0;\n\nlet speedup6 = 0;\n\nconst _speedup7 = 0;\n\n\n\n// deno-lint-ignore no-explicit-any\n\nconst bricks: any = [];\n\nfor (let c = 0; c < brickColumnCount; ++c) {\n\n bricks[c] = [];\n\n for (let r = 0; r < brickRowCount; ++r) {\n\n bricks[c][r] = { x: 0, y: 0, status: 1 };\n\n }\n\n}\n\n\n\nlet dx = 3.5;\n\nlet dy = -3.5;\n\n\n\nfunction drawBall() {\n\n ctx.beginPath();\n\n ctx.arc(x, y, ballRadius, 0, Math.PI * 2);\n\n ctx.fillStyle = \"#fff\";\n\n ctx.fill();\n\n ctx.closePath();\n\n}\n\n\n\nfunction drawPaddle() {\n\n ctx.beginPath();\n\n ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight);\n\n ctx.fillStyle = \"#00ffff\";\n\n ctx.fill();\n\n ctx.closePath();\n\n}\n\n\n\nfunction drawBricks() {\n\n for (let c = 0; c < brickColumnCount; ++c) {\n\n for (let r = 0; r < brickRowCount; ++r) {\n\n if (bricks[c][r].status == 1) {\n\n const brickX = (c * (brickWidth + brickPadding)) + brickOffsetLeft;\n\n const brickY = (r * (brickHeight + brickPadding)) + brickOffsetTop;\n\n bricks[c][r].x = brickX;\n\n bricks[c][r].y = brickY;\n\n ctx.beginPath();\n\n ctx.rect(brickX, brickY, brickWidth, brickHeight);\n\n if (c % 2 != 0) {\n\n ctx.fillStyle = \"#fff\";\n\n } else {\n\n ctx.fillStyle = \"#C2AA83\";\n\n }\n\n ctx.fill();\n\n ctx.closePath();\n\n }\n\n }\n\n }\n\n}\n\nfunction collisionDetection() {\n\n for (let c = 0; c < brickColumnCount; ++c) {\n\n for (let r = 0; r < brickRowCount; ++r) {\n\n const b = bricks[c][r];\n\n\n\n if (b.status == 1) {\n\n if (\n\n x > b.x && x < b.x + brickWidth && y > b.y && y < b.y + brickHeight\n\n ) {\n\n dy = -dy;\n\n b.status = 0;\n\n score++;\n\n count--;\n\n ctx.beginPath();\n\n ctx.arc(x, y, ballRadius, 0, Math.PI * 2);\n\n ctx.fillStyle = \"#00ffff\";\n\n ctx.fill();\n\n ctx.closePath();\n\n if (count <= (rem - rem / 7) && speedup1 == 0) {\n\n if (dy < 0) {\n\n dy -= 0.5;\n\n } else {\n\n dy += 0.5;\n\n }\n\n if (dx < 0) {\n\n dx -= 0.5;\n\n } else {\n\n dx += 0.5;\n\n }\n\n paddleWidth += 2;\n\n speedup1 = 1;\n\n }\n\n if (count <= (rem - 2 * rem / 7) && speedup2 == 0) {\n\n if (dy < 0) {\n\n dy -= 1;\n\n } else {\n\n dy += 1;\n\n }\n\n if (dx < 0) {\n\n dx -= 1;\n\n } else {\n\n dx += 1;\n\n }\n\n\n\n paddleWidth += 3;\n\n speedup2 = 1;\n\n }\n\n if (count <= (rem - 3 * rem / 7) && speedup3 == 0) {\n\n if (dy < 0) {\n\n dy -= 1;\n\n } else {\n\n dy += 1;\n\n }\n\n if (dx < 0) {\n\n dx -= 1;\n\n } else {\n\n dx += 1;\n\n }\n\n\n\n paddleWidth += 4;\n\n speedup3 = 1;\n\n }\n\n\n\n if (count <= (rem - 4 * rem / 7) && speedup4 == 0) {\n\n if (dy < 0) {\n\n dy -= 1;\n\n } else {\n\n dy += 1;\n\n }\n\n if (dx < 0) {\n\n dx -= 1;\n\n } else {\n\n dx += 1;\n\n }\n\n paddleWidth += 5;\n\n speedup4 = 1;\n\n }\n\n\n\n if (count <= (rem - 5 * rem / 7) && speedup5 == 0) {\n\n if (dy < 0) {\n\n dy -= 1;\n\n } else {\n\n dy += 1;\n\n }\n\n if (dx < 0) {\n\n dx -= 1;\n\n } else {\n\n dx += 1;\n\n }\n\n paddleWidth += 6;\n\n speedup5 = 1;\n\n }\n\n\n\n if (count <= (rem - 6 * rem / 7) && speedup6 == 0) {\n\n if (dy < 0) {\n\n dy -= 1;\n\n } else {\n\n dy += 1;\n\n }\n\n if (dx < 0) {\n\n dx -= 1;\n\n } else {\n\n dx += 1;\n\n }\n\n paddleWidth += 7;\n\n speedup6 = 1;\n\n }\n\n\n\n if (count <= 0) {\n\n console.log(\"You Win!\");\n\n Deno.exit(0);\n\n }\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n\nfunction drawScore() {\n\n ctx.font = \"18px Arial\";\n\n ctx.fillStyle = \"#fff\";\n\n ctx.fillText(\"score: \" + score, 40, 20);\n\n}\n\n\n\nfunction drawLives() {\n\n ctx.font = \"18px Arial\";\n\n ctx.fillStyle = \"#fff\";\n\n ctx.fillText(\n\n \"lives: \" + lives,\n\n canvas.width - 310,\n\n 20,\n\n );\n\n}\n\n\n\nfunction draw() {\n\n keyHandler();\n\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n\n drawBricks();\n\n drawBall();\n\n drawPaddle();\n\n drawScore();\n\n drawLives();\n\n\n\n collisionDetection();\n\n\n\n if (y + dy < ballRadius) {\n\n dy = -dy;\n\n } else if (y + dy > canvas.height - ballRadius) {\n\n if (x >= paddleX && x <= paddleX + paddleWidth) {\n\n dy = -dy;\n\n } else {\n\n lives--;\n\n if (lives <= 0) {\n\n console.log(\"Sorry, you've lost...\\nTry again! :-)\");\n\n Deno.exit(0);\n\n } else {\n\n x = canvas.width / 2;\n\n y = canvas.height - 30;\n\n paddleWidth = 80;\n\n rem = count;\n\n paddleX = (canvas.width - paddleWidth) / 2;\n\n }\n\n }\n\n } else {\n\n y += dy;\n\n }\n\n\n\n if (x + dx < ballRadius || x + dx > canvas.width - ballRadius) {\n\n dx = -dx;\n\n } else {\n\n x += dx;\n\n }\n\n\n\n if (rightPressed && paddleX < canvas.width - paddleWidth) {\n\n paddleX += 7;\n\n } else if (leftPressed && paddleX > 0) {\n\n paddleX -= 7;\n\n }\n\n}\n\n\n\nfunction keyHandler() {\n\n if (canvas.window.isKeyDown(\"right\")) {\n\n rightPressed = true;\n\n } else {\n\n rightPressed = false;\n\n }\n\n if (canvas.window.isKeyDown(\"left\")) {\n\n leftPressed = true;\n\n } else {\n\n leftPressed = false;\n\n }\n\n}\n\n\n\nsetInterval(draw, 20);\n", "file_path": "canvas/examples/brickbreaker.ts", "rank": 49, "score": 24364.864698215602 }, { "content": "import { Canvas, loadImage } from \"../mod.ts\";\n\n\n\nconst canvas = new Canvas({\n\n title: \"Neko\",\n\n width: 500,\n\n height: 500,\n\n});\n\nconst ctx = canvas.getContext(\"2d\");\n\n// image created by Hashrock (https://hashrock.studio.site)\n\nconst img = await loadImage(\"https://deno.land/images/artwork/hashrock_simple.png\");\n", "file_path": "canvas/examples/image.ts", "rank": 50, "score": 24364.864698215602 }, { "content": "// ported from https://codepen.io/lukasvait/pen/OJexNE\n\nimport { Canvas } from \"../mod.ts\";\n\nconst canvas = new Canvas({\n\n title: \"Snake\",\n\n width: 500,\n\n height: 500,\n\n});\n\n// deno-lint-ignore no-explicit-any\n\nlet loop: any = undefined;\n\nconst ctx = canvas.getContext(\"2d\");\n\nlet direction = \"\";\n\nlet directionQueue = \"\";\n\nconst fps = 70;\n\n// deno-lint-ignore no-explicit-any\n\nlet snake: any[] = [];\n\nconst snakeLength = 5;\n\nconst cellSize = 20;\n\nconst snakeColor = \"#3498db\";\n\nconst foodColor = \"#ff3636\";\n\n// deno-lint-ignore no-explicit-any\n\nconst foodX: any[] = [];\n\n// deno-lint-ignore no-explicit-any\n\nconst foodY: any[] = [];\n\nconst food = {\n\n x: 0,\n\n y: 0,\n\n};\n\nlet score = 0;\n\n\n\nfor (let i = 0; i <= canvas.width - cellSize; i += cellSize) {\n\n foodX.push(i);\n\n foodY.push(i);\n\n}\n\nconst drawSquare = (x: number, y: number, color: string) => {\n\n ctx.fillStyle = color;\n\n ctx.fillRect(x, y, cellSize, cellSize);\n\n};\n\n\n\nconst createFood = () => {\n\n food.x = foodX[Math.floor(Math.random() * foodX.length)];\n\n food.y = foodY[Math.floor(Math.random() * foodY.length)];\n\n for (const i in snake) {\n\n if (checkCollision(food.x, food.y, snake[i].x, snake[i].y)) {\n\n createFood();\n\n }\n\n }\n\n};\n\nconst drawFood = () => {\n\n drawSquare(food.x, food.y, foodColor);\n\n};\n\n\n\nconst setBackground = (color1: string, color2: string) => {\n\n ctx.fillStyle = color1;\n\n ctx.strokeStyle = color2;\n\n\n\n ctx.fillRect(0, 0, canvas.height, canvas.width);\n\n\n\n for (let x = 0.5; x < canvas.width; x += cellSize) {\n\n ctx.moveTo(x, 0);\n\n ctx.lineTo(x, canvas.height);\n\n }\n\n for (let y = 0.5; y < canvas.height; y += cellSize) {\n\n ctx.moveTo(0, y);\n\n ctx.lineTo(canvas.width, y);\n\n }\n\n\n\n ctx.stroke();\n\n};\n\nconst createSnake = () => {\n\n snake = [];\n\n for (let i = snakeLength; i > 0; i--) {\n\n snake.push({ x: i * cellSize, y: 0 });\n\n }\n\n};\n\nconst drawSnake = () => {\n\n for (let i = 0; i < snake.length; i++) {\n\n drawSquare(snake[i].x, snake[i].y, snakeColor);\n\n }\n\n};\n\nconst changeDirection = (keycode: string) => {\n\n if (keycode === \"left\" && direction != \"right\") directionQueue = \"left\";\n\n else if (keycode === \"up\" && direction != \"down\") directionQueue = \"up\";\n\n else if (keycode === \"right\" && direction != \"left\") directionQueue = \"right\";\n\n else if (keycode === \"down\" && direction != \"top\") directionQueue = \"down\";\n\n};\n\nconst moveSnake = () => {\n\n let x = snake[0].x;\n\n let y = snake[0].y;\n\n\n\n direction = directionQueue;\n\n\n\n if (direction == \"right\") {\n\n x += cellSize;\n\n } else if (direction == \"left\") {\n\n x -= cellSize;\n\n } else if (direction == \"up\") {\n\n y -= cellSize;\n\n } else if (direction == \"down\") {\n\n y += cellSize;\n\n }\n\n const tail = snake.pop();\n\n tail.x = x;\n\n tail.y = y;\n\n snake.unshift(tail);\n\n};\n\n\n\nconst checkCollision = (\n\n x1: number,\n\n y1: number,\n\n x2: number,\n\n y2: number,\n\n) => (x1 === x2 && y1 === y2);\n\nconst game = () => {\n\n const head = snake[0];\n\n if (\n\n head.x < 0 || head.x > canvas.width - cellSize || head.y < 0 ||\n\n head.y > canvas.height - cellSize\n\n ) {\n\n setBackground(\"#ff3636\", \"#ff3636\");\n\n createSnake();\n\n drawSnake();\n\n createFood();\n\n drawFood();\n\n directionQueue = \"right\";\n\n score = 0;\n\n }\n\n for (let i = 1; i < snake.length; i++) {\n\n if (head.x == snake[i].x && head.y == snake[i].y) {\n\n setBackground(\"#ff3636\", \"#ff3636\");\n\n createSnake();\n\n drawSnake();\n\n createFood();\n\n drawFood();\n\n directionQueue = \"right\";\n\n score = 0;\n\n }\n\n }\n\n if (checkCollision(head.x, head.y, food.x, food.y)) {\n\n snake[snake.length] = { x: head.x, y: head.y };\n\n createFood();\n\n drawFood();\n\n score += 10;\n\n }\n\n\n\n if (canvas.window.isKeyDown(\"left\")) {\n\n changeDirection(\"left\");\n\n } else if (canvas.window.isKeyDown(\"right\")) {\n\n changeDirection(\"right\");\n\n } else if (canvas.window.isKeyDown(\"up\")) {\n\n changeDirection(\"up\");\n\n } else if (canvas.window.isKeyDown(\"down\")) {\n\n changeDirection(\"down\");\n\n }\n\n\n\n ctx.beginPath();\n\n setBackground(\"#fff\", \"#eee\");\n\n drawSnake();\n\n drawFood();\n\n moveSnake();\n\n};\n\nfunction newGame() {\n\n direction = \"right\";\n\n directionQueue = \"right\";\n\n ctx.beginPath();\n\n createSnake();\n\n createFood();\n\n\n\n if (typeof loop != \"undefined\") {\n\n clearInterval(loop);\n\n } else {\n\n loop = setInterval(game, fps);\n\n }\n\n}\n\nnewGame();\n", "file_path": "canvas/examples/snake.ts", "rank": 51, "score": 24364.864698215602 }, { "content": "import { Canvas } from \"../mod.ts\";\n\n\n\ntype Vector = {\n\n x: number,\n\n y: number\n\n}\n\n\n\nconst canvas = new Canvas({\n\n title: \"Perlin\",\n\n width: 800,\n\n height: 800,\n\n});\n\nconst ctx = canvas.getContext(\"2d\")\n\n\n\nconst BATCH = 5\n\nconst WRAP = 100\n\nconst SIZE = 1\n\nconst TOTAL = WRAP * BATCH\n\n\n\nfunction Shuffle(tab: number[]) {\n\n for (let e = tab.length - 1; e > 0; e--) {\n\n let index = Math.round(Math.random() * (e - 1)),\n\n temp = tab[e];\n\n\n\n tab[e] = tab[index];\n\n tab[index] = temp;\n\n }\n\n}\n\n\n\nfunction MakePermutation() {\n\n let P = [];\n\n for (let i = 0; i < 256; i++) {\n\n P.push(i);\n\n }\n\n Shuffle(P);\n\n for (let i = 0; i < 256; i++) {\n\n P.push(P[i]);\n\n }\n\n\n\n return P;\n\n}\n\nlet P = MakePermutation();\n\n\n\nfunction ConstantVector(v: number) {\n\n return [\n\n { x: 1, y: 1 },\n\n { x: -1, y: 1 },\n\n { x: -1, y: -1 },\n\n { x: 1, y: -1 }\n\n ][v & 3]\n\n}\n\n\n\nconst matrix: number[][] = []\n\nfor (let i = 0; i < TOTAL; i++) {\n\n const col = []\n\n for (let j = 0; j < TOTAL; j++) {\n\n col.push(0);\n\n }\n\n matrix.push(col)\n\n}\n\n\n\nfunction Calculate() {\n\n for (let i = 0; i < BATCH; i++) {\n\n for (let j = 0; j < BATCH; j++) {\n\n PerlinBatch(i, j)\n\n }\n\n }\n\n}\n\n\n\nfunction Draw() {\n\n ctx.fillStyle = `rgb(0, 0, 0)`\n\n ctx.fillRect(0, 0, 800, 800)\n\n for (let i = 0; i < TOTAL; i++) {\n\n for (let j = 0; j < TOTAL; j++) {\n\n ctx.fillStyle = `rgba(255, 255, 255, ${matrix[i][j] + 0.5})`\n\n ctx.fillRect(i * SIZE, j * SIZE, SIZE, SIZE)\n\n }\n\n }\n\n}\n\n\n\nfunction PerlinBatch(batchX: number, batchY: number,) {\n\n const trv = ConstantVector(P[P[batchX + 1] + batchY + 1]);\n\n const tlv = ConstantVector(P[P[batchX] + batchY + 1]);\n\n const brv = ConstantVector(P[P[batchX + 1] + batchY]);\n\n const blv = ConstantVector(P[P[batchX] + batchY]);\n\n\n\n for (let x = 0; x < WRAP; x++) {\n\n for (let y = 0; y < WRAP; y++) {\n\n const currentX = x + batchX * WRAP;\n\n const currentY = y + batchY * WRAP;\n\n matrix[currentX][currentY] = Perlin(x / WRAP, y / WRAP, trv, tlv, brv, blv)\n\n }\n\n }\n\n};\n\n\n\nfunction Perlin(x: number, y: number, trv: Vector, tlv: Vector, brv: Vector, blv: Vector) {\n\n const tr = { x: x - 1, y: y - 1 }\n\n const tl = { x: x, y: y - 1 }\n\n const br = { x: x - 1, y: y }\n\n const bl = { x: x, y: y }\n\n\n\n const trd = Dot(trv, tr)\n\n const tld = Dot(tlv, tl)\n\n const brd = Dot(brv, br)\n\n const bld = Dot(blv, bl)\n\n\n\n const u = Fade(x);\n\n const v = Fade(y);\n\n\n\n const left = Lerp(bld, tld, v)\n\n const right = Lerp(brd, trd, v)\n\n return Lerp(left, right, u)\n\n};\n\n\n\nfunction Dot(a: Vector, b: Vector) {\n\n return a.x * b.x + a.y * b.y\n\n}\n\n\n\nfunction Lerp(a: number, b: number, x: number) {\n\n return a + (b - a) * x\n\n}\n\n\n\nfunction Fade(t: number) {\n\n return ((6 * t - 15) * t + 10) * t * t * t;\n\n}\n\n\n\nCalculate()\n", "file_path": "canvas/examples/perlin.ts", "rank": 52, "score": 24364.864698215602 }, { "content": "import { Canvas } from \"../mod.ts\";\n\n\n\nconst canvas = new Canvas({\n\n title: \"Cube\",\n\n width: 800,\n\n height: 800,\n\n \n\n});\n\nconst ctx = canvas.getContext(\"2d\")\n\nctx.fillStyle = \"#fff\";\n\nctx.strokeStyle = \"#fff\";\n\n\n\nlet theta = 0\n\nlet thetaZ = theta * Math.PI / 180\n\nlet thetaY = theta * Math.PI / 180\n\nlet thetaX = theta * Math.PI / 180\n\nconst d = 300\n\nconst step = 200\n\nconst steps = 1\n\nconst matrix: [number, number, number][][][] = []\n\n\n\nfor (let i = -step * steps / 2; i < step * steps; i += step) {\n\n const column: [number, number, number][][] = []\n\n for (let j = -step * steps / 2; j < step * steps; j += step) {\n\n const row: [number, number, number][] = []\n\n for (let k = -step * steps / 2; k < step * steps; k += step) {\n\n row.push([i, j, k])\n\n }\n\n column.push(row)\n\n }\n\n matrix.push(column)\n\n}\n\n\n\nfunction Render() {\n\n const matrix2 = []\n\n for (const column of matrix) {\n\n const column2 = []\n\n for (const row of column) {\n\n const row2 = []\n\n for (const point of row) {\n\n let x = point[0]\n\n let y = point[1]\n\n let z = point[2]\n\n x = x * Math.cos(thetaX) - z * Math.sin(thetaX)\n\n z = point[0] * Math.sin(thetaX) + z * Math.cos(thetaX)\n\n y = y * Math.cos(thetaY) - z * Math.sin(thetaY)\n\n z = point[1] * Math.sin(thetaY) + z * Math.cos(thetaY)\n\n const x2 = x\n\n x = x * Math.cos(thetaZ) - y * Math.sin(thetaZ)\n\n y = x2 * Math.sin(thetaZ) + y * Math.cos(thetaZ)\n\n\n\n ctx.beginPath();\n\n ctx.arc(x + d, y + d, 5, 0, 2 * Math.PI);\n\n ctx.fill();\n\n row2.push([x + d, y + d])\n\n }\n\n column2.push(row2)\n\n }\n\n matrix2.push(column2)\n\n }\n\n\n\n for (let i = 0; i < matrix2.length; i++) {\n\n for (let j = 0; j < matrix2[i].length; j++) {\n\n for (let k = 0; k < matrix2[i][j].length; k++) {\n\n const point = matrix2[i][j][k]\n\n const point2 = matrix2[i][j][k + 1]\n\n if (point2) {\n\n ctx.beginPath();\n\n ctx.moveTo(point[0], point[1]);\n\n ctx.lineTo(point2[0], point2[1]);\n\n ctx.stroke();\n\n }\n\n }\n\n const point = matrix2[i][j]\n\n const point2 = matrix2[i][j + 1]\n\n if (point2) {\n\n for (let k = 0; k < matrix2[i][j].length; k++) {\n\n ctx.beginPath();\n\n ctx.moveTo(point[k][0], point[k][1]);\n\n ctx.lineTo(point2[k][0], point2[k][1]);\n\n ctx.stroke();\n\n }\n\n }\n\n }\n\n const point = matrix2[i]\n\n const point2 = matrix2[i + 1]\n\n if (point2) {\n\n for (let j = 0; j < matrix2[i].length; j++) {\n\n for (let k = 0; k < matrix2[i][j].length; k++) {\n\n ctx.beginPath();\n\n ctx.moveTo(point[j][k][0], point[j][k][1]);\n\n ctx.lineTo(point2[j][k][0], point2[j][k][1]);\n\n ctx.stroke();\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n\nctx.clearRect(0, 0, canvas.width, canvas.height)\n\n\n\nsetInterval(() => {\n\n ctx.clearRect(0, 0, canvas.width, canvas.height)\n\n theta += 3\n\n if (theta > 360) {\n\n theta = 0\n\n }\n\n thetaY = theta * Math.PI / 180\n\n thetaZ = theta * Math.PI / 180\n\n thetaX = theta * Math.PI / 180\n\n Render()\n", "file_path": "canvas/examples/cube.ts", "rank": 53, "score": 24364.864698215602 }, { "content": "import { Canvas } from \"../mod.ts\";\n\n\n\ntype Vector = {\n\n x: number,\n\n y: number\n\n}\n\n\n\nconst canvas = new Canvas({\n\n title: \"Terrain\",\n\n width: 800,\n\n height: 800,\n\n});\n\nconst ctx = canvas.getContext(\"2d\")\n\nctx.fillStyle = \"#fff\";\n\nctx.strokeStyle = \"#fff\";\n\n\n\nconst BATCH = 5\n\nconst WRAP = 4\n\nconst TOTAL = WRAP * BATCH\n\nconst theta = 40\n\nconst thetaZ = theta * Math.PI / 180\n\nconst thetaY = theta * Math.PI / 180\n\nconst thetaX = theta * Math.PI / 180\n\nconst sx = 200\n\nconst sy = 40\n\nconst step = 20\n\nconst steps = 20\n\nconst radius = 2\n\n\n\nconst matrix: [number, number, number][][][] = []\n\nconst matrix2: number[][] = []\n\nfor (let i = 0; i < TOTAL; i++) {\n\n const col: number[] = []\n\n for (let j = 0; j < TOTAL; j++) {\n\n col.push(0);\n\n }\n\n matrix2.push(col)\n\n}\n\n\n\n\n\nfunction Shuffle(tab: number[]) {\n\n for (let e = tab.length - 1; e > 0; e--) {\n\n const index = Math.round(Math.random() * (e - 1)),\n\n temp = tab[e];\n\n\n\n tab[e] = tab[index];\n\n tab[index] = temp;\n\n }\n\n}\n\n\n\nfunction MakePermutation() {\n\n const P = [];\n\n for (let i = 0; i < 256; i++) {\n\n P.push(i);\n\n }\n\n Shuffle(P);\n\n for (let i = 0; i < 256; i++) {\n\n P.push(P[i]);\n\n }\n\n\n\n return P;\n\n}\n\nconst P = MakePermutation();\n\n\n\nfunction ConstantVector(v: number) {\n\n return [\n\n { x: 1, y: 1 },\n\n { x: -1, y: 1 },\n\n { x: -1, y: -1 },\n\n { x: 1, y: -1 }\n\n ][v & 3]\n\n}\n\n\n\nfunction Calculate() {\n\n for (let i = 0; i < TOTAL; i++) {\n\n for (let j = 0; j < TOTAL; j++) {\n\n matrix2[i][j] = PerlinBatch(i, j)\n\n }\n\n }\n\n}\n\n\n\nfunction PerlinBatch(posX: number, posY: number) {\n\n const batchX = Math.floor(posX / WRAP)\n\n const batchY = Math.floor(posY / WRAP)\n\n const trv = ConstantVector(P[P[batchX + 1] + batchY + 1]);\n\n const tlv = ConstantVector(P[P[batchX] + batchY + 1]);\n\n const brv = ConstantVector(P[P[batchX + 1] + batchY]);\n\n const blv = ConstantVector(P[P[batchX] + batchY]);\n\n\n\n const currentX = posX / WRAP - batchX;\n\n const currentY = posY / WRAP - batchY;\n\n return Perlin(currentX, currentY, trv, tlv, brv, blv)\n\n};\n\n\n\nfunction Perlin(x: number, y: number, trv: Vector, tlv: Vector, brv: Vector, blv: Vector) {\n\n const tr = { x: x - 1, y: y - 1 }\n\n const tl = { x: x, y: y - 1 }\n\n const br = { x: x - 1, y: y }\n\n const bl = { x: x, y: y }\n\n\n\n const trd = Dot(trv, tr)\n\n const tld = Dot(tlv, tl)\n\n const brd = Dot(brv, br)\n\n const bld = Dot(blv, bl)\n\n\n\n const u = Fade(x);\n\n const v = Fade(y);\n\n\n\n const left = Lerp(bld, tld, v)\n\n const right = Lerp(brd, trd, v)\n\n return Lerp(left, right, u)\n\n};\n\n\n\nfunction Dot(a: Vector, b: Vector) {\n\n return a.x * b.x + a.y * b.y\n\n}\n\n\n\nfunction Lerp(a: number, b: number, x: number) {\n\n return a + (b - a) * x\n\n}\n\n\n\nfunction Fade(t: number) {\n\n return ((6 * t - 15) * t + 10) * t * t * t;\n\n}\n\n\n\nfor (let i = 0; i < steps; i += 1) {\n\n const column: [number, number, number][][] = []\n\n for (let j = 0; j < steps; j += 1) {\n\n const row: [number, number, number][] = []\n\n const x = i * step;\n\n const y = j * step;\n\n row.push([x, y, -PerlinBatch(i, j) * 40])\n\n column.push(row)\n\n }\n\n matrix.push(column)\n\n}\n\n\n\nfunction Render() {\n\n const matrix2 = []\n\n for (const column of matrix) {\n\n const column2 = []\n\n for (const row of column) {\n\n const row2 = []\n\n for (const point of row) {\n\n let x = point[0]\n\n let y = point[1]\n\n let z = point[2]\n\n x = x * Math.cos(thetaX) - z * Math.sin(thetaX)\n\n z = point[0] * Math.sin(thetaX) + z * Math.cos(thetaX)\n\n y = y * Math.cos(thetaY) - z * Math.sin(thetaY)\n\n z = point[1] * Math.sin(thetaY) + z * Math.cos(thetaY)\n\n const x2 = x\n\n x = x * Math.cos(thetaZ) - y * Math.sin(thetaZ)\n\n y = x2 * Math.sin(thetaZ) + y * Math.cos(thetaZ)\n\n\n\n ctx.beginPath();\n\n ctx.arc(x + sx, y + sy, radius, 0, 2 * Math.PI);\n\n ctx.fill();\n\n row2.push([x + sx, y + sy])\n\n }\n\n column2.push(row2)\n\n }\n\n matrix2.push(column2)\n\n }\n\n\n\n for (let i = 0; i < matrix2.length; i++) {\n\n for (let j = 0; j < matrix2[i].length; j++) {\n\n for (let k = 0; k < matrix2[i][j].length; k++) {\n\n const point = matrix2[i][j][k]\n\n const point2 = matrix2[i][j][k + 1]\n\n if (point2) {\n\n ctx.beginPath();\n\n ctx.moveTo(point[0], point[1]);\n\n ctx.lineTo(point2[0], point2[1]);\n\n ctx.stroke();\n\n }\n\n }\n\n const point = matrix2[i][j]\n\n const point2 = matrix2[i][j + 1]\n\n if (point2) {\n\n for (let k = 0; k < matrix2[i][j].length; k++) {\n\n ctx.beginPath();\n\n ctx.moveTo(point[k][0], point[k][1]);\n\n ctx.lineTo(point2[k][0], point2[k][1]);\n\n ctx.stroke();\n\n }\n\n }\n\n }\n\n const point = matrix2[i]\n\n const point2 = matrix2[i + 1]\n\n if (point2) {\n\n for (let j = 0; j < matrix2[i].length; j++) {\n\n for (let k = 0; k < matrix2[i][j].length; k++) {\n\n ctx.beginPath();\n\n ctx.moveTo(point[j][k][0], point[j][k][1]);\n\n ctx.lineTo(point2[j][k][0], point2[j][k][1]);\n\n ctx.stroke();\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n\nCalculate()\n", "file_path": "canvas/examples/terrain.ts", "rank": 54, "score": 24364.864698215602 }, { "content": "export class Neko {\n\n #id;\n\n width: number;\n\n height: number;\n\n constructor(options: NekoOptions) {\n\n this.width = options.width;\n\n this.height = options.height;\n\n this.#id = lib.symbols.window_new(\n\n new Uint8Array([...encode(options.title), 0]),\n\n options.width,\n\n options.height,\n\n );\n\n }\n\n limitUpdateRate(micros: number) {\n\n unwrap(lib.symbols.window_limit_update_rate(this.#id, micros));\n\n }\n\n setFrameBuffer(buffer: Uint8Array, width?: number, height?: number) {\n\n unwrap(\n\n lib.symbols.window_update_with_buffer(\n\n this.#id,\n\n buffer,\n\n width ?? this.width,\n\n height ?? this.height,\n\n )\n\n );\n\n }\n\n\n\n update() {\n\n unwrap(lib.symbols.window_update(this.#id));\n\n }\n\n\n\n close() {\n\n unwrap(lib.symbols.window_close(this.#id));\n\n }\n\n\n\n isKeyDown(key: string): boolean {\n\n return unwrapBoolean(lib.symbols.window_is_key_down(this.#id, new Uint8Array([...encode(key), 0])));\n\n }\n\n\n\n isMouseButtonDown(key: string): boolean {\n\n return unwrapBoolean(lib.symbols.window_is_mouse_button_down(this.#id, new Uint8Array([...encode(key), 0])));\n\n }\n\n\n\n getScroll(): number {\n\n return lib.symbols.window_get_mouse_scroll(this.#id);\n\n }\n\n\n\n\n\n getMousePosition(): [number, number] {\n\n return [lib.symbols.window_get_mouse_x(this.#id), lib.symbols.window_get_mouse_y(this.#id)];\n\n }\n\n\n\n get open(): boolean {\n\n return unwrapBoolean(lib.symbols.window_is_open(this.#id));\n\n }\n\n\n\n get active(): boolean {\n\n return unwrapBoolean(lib.symbols.window_is_active(this.#id));\n\n }\n", "file_path": "lib/Neko.ts", "rank": 72, "score": 5.2839719015223805 }, { "content": "export class Canvas {\n\n #title: string;\n\n #ctx: CanvasRenderingContext2D;\n\n #canvas: EmulatedCanvas2D;\n\n window: Neko;\n\n #world: World;\n\n #width: number;\n\n #height: number;\n\n #fps: number;\n\n constructor(config: Config) {\n\n this.#world = new World();\n\n this.#height = config.height || 200;\n\n this.#width = config.width || 200;\n\n this.#title = config.title || \"Neko\";\n\n this.#fps = config.fps || 60;\n\n this.#canvas = createCanvas(this.#width, this.#height);\n\n this.#ctx = this.#canvas.getContext(\"2d\");\n\n this.window = new Neko({\n\n title: this.#title,\n\n width: this.#width,\n\n height: this.#height,\n\n });\n\n this.#world.start(this.window, {\n\n fps: this.#fps,\n\n update: () => {\n\n this.window.setFrameBuffer(\n\n this.#canvas.getRawBuffer(0, 0, this.#width, this.#height),\n\n );\n\n },\n\n });\n\n }\n\n getContext(_type = \"2d\"): CanvasRenderingContext2D {\n\n return this.#ctx;\n\n }\n\n get canvas(): EmulatedCanvas2D {\n\n return this.#canvas;\n\n }\n\n get width(): number {\n\n return this.#width;\n\n }\n\n get height(): number {\n\n return this.#height;\n\n }\n", "file_path": "canvas/Ctx.ts", "rank": 73, "score": 2.8236485947224073 }, { "content": "let score = 0;\n", "file_path": "canvas/examples/tetris.ts", "rank": 74, "score": 2.3680541116852547 } ]
Rust
applications/swap/src/lib.rs
jacob-earle/Theseus
d53038328d1a39c69ffff6e32226394e8c957e33
#![no_std] #![feature(slice_concat_ext)] #[macro_use] extern crate alloc; #[macro_use] extern crate terminal_print; extern crate itertools; extern crate getopts; extern crate memory; extern crate mod_mgmt; extern crate crate_swap; extern crate hpet; extern crate task; extern crate path; extern crate fs_node; use alloc::{ string::{String, ToString}, vec::Vec, sync::Arc, }; use getopts::{Options, Matches}; use mod_mgmt::{NamespaceDir, IntoCrateObjectFile}; use crate_swap::SwapRequest; use hpet::get_hpet; use path::Path; use fs_node::{FileOrDir, DirRef}; pub fn main(args: Vec<String>) -> isize { #[cfg(not(loadable))] { println!("****************\nWARNING: Theseus was not built in 'loadable' mode, so crate swapping may not work.\n****************"); } let mut opts = Options::new(); opts.optflag("h", "help", "print this help menu"); opts.optflag("v", "verbose", "enable verbose logging of crate swapping actions"); opts.optflag("c", "cache", "enable caching of the old crate(s) removed by the swapping action"); opts.optopt("d", "directory-crates", "the absolute path of the base directory where new crates will be loaded from", "PATH"); opts.optmulti("t", "state-transfer", "the fully-qualified symbol names of state transfer functions, to be run in the order given", "SYMBOL"); let matches = match opts.parse(&args) { Ok(m) => m, Err(_f) => { println!("{}", _f); print_usage(opts); return -1; } }; if matches.opt_present("h") { print_usage(opts); return 0; } match rmain(matches) { Ok(_) => 0, Err(e) => { println!("Error: {}", e); -1 } } } fn rmain(matches: Matches) -> Result<(), String> { let taskref = task::get_my_current_task() .ok_or_else(|| format!("failed to get current task"))?; let curr_dir = Arc::clone(&taskref.get_env().lock().working_dir); let override_namespace_crate_dir = if let Some(path) = matches.opt_str("d") { let path = Path::new(path); let dir = match path.get(&curr_dir) { Some(FileOrDir::Dir(dir)) => dir, _ => return Err(format!("Error: could not find specified namespace crate directory: {}.", path)), }; Some(NamespaceDir::new(dir)) } else { None }; let verbose = matches.opt_present("v"); let cache_old_crates = matches.opt_present("c"); let state_transfer_functions = matches.opt_strs("t"); let free_args = matches.free.join(" "); println!("arguments: {}", free_args); let tuples = parse_input_tuples(&free_args)?; println!("tuples: {:?}", tuples); do_swap( tuples, &curr_dir, override_namespace_crate_dir, state_transfer_functions, verbose, cache_old_crates ) } fn parse_input_tuples<'a>(args: &'a str) -> Result<Vec<(&'a str, &'a str, bool)>, String> { let mut v: Vec<(&str, &str, bool)> = Vec::new(); let mut open_paren_iter = args.match_indices('('); while let Some((paren_start, _)) = open_paren_iter.next() { let the_rest = args.get((paren_start + 1) ..).ok_or_else(|| "unmatched open parenthesis.".to_string())?; let parsed = the_rest.find(')') .and_then(|end_index| the_rest.get(.. end_index)) .and_then(|inside_paren| { let mut token_iter = inside_paren.split(',').map(str::trim); token_iter.next().and_then(|first| { token_iter.next().map(|second| { (first, second, token_iter.next()) }) }) }); match parsed { Some((o, n, reexport)) => { println!("found triple: {:?}, {:?}, {:?}", o, n, reexport); let reexport_bool = match reexport { Some("true") => true, Some("yes") => true, Some("y") => true, _ => false, }; v.push((o, n, reexport_bool)); } _ => return Err("list of crate tuples is formatted incorrectly.".to_string()), } } if v.is_empty() { Err("no crate tuples specified.".to_string()) } else { Ok(v) } } fn do_swap( tuples: Vec<(&str, &str, bool)>, curr_dir: &DirRef, override_namespace_crate_dir: Option<NamespaceDir>, state_transfer_functions: Vec<String>, verbose_log: bool, cache_old_crates: bool ) -> Result<(), String> { let kernel_mmi_ref = memory::get_kernel_mmi_ref().ok_or_else(|| "couldn't get kernel_mmi_ref".to_string())?; let namespace = task::get_my_current_task().ok_or("Couldn't get current task")?.get_namespace(); let swap_requests = { let mut requests: Vec<SwapRequest> = Vec::with_capacity(tuples.len()); for (old_crate_name, new_crate_str, reexport) in tuples { let (into_new_crate_file, new_namespace) = { if let Some(f) = override_namespace_crate_dir.as_ref().and_then(|ns_dir| ns_dir.get_file_starting_with(new_crate_str)) { (IntoCrateObjectFile::File(f), None) } else if let Some(FileOrDir::File(f)) = Path::new(String::from(new_crate_str)).get(curr_dir) { (IntoCrateObjectFile::File(f), None) } else { (IntoCrateObjectFile::Prefix(String::from(new_crate_str)), None) } }; let swap_req = SwapRequest::new( Some(old_crate_name), Arc::clone(&namespace), into_new_crate_file, new_namespace, reexport ).map_err(|invalid_req| format!("{:#?}", invalid_req))?; requests.push(swap_req); } requests }; let start = get_hpet().as_ref().ok_or("couldn't get HPET timer")?.get_counter(); let swap_result = crate_swap::swap_crates( &namespace, swap_requests, override_namespace_crate_dir, state_transfer_functions, &kernel_mmi_ref, verbose_log, cache_old_crates, ); let end = get_hpet().as_ref().ok_or("couldn't get HPET timer")?.get_counter(); let hpet_period = get_hpet().as_ref().ok_or("couldn't get HPET timer")?.counter_period_femtoseconds(); let elapsed_ticks = end - start; match swap_result { Ok(()) => { println!("Swap operation complete. Elapsed HPET ticks: {}, (HPET Period: {} femtoseconds)", elapsed_ticks, hpet_period); Ok(()) } Err(e) => Err(e.to_string()) } } fn print_usage(opts: Options) { println!("{}", opts.usage(USAGE)); } const USAGE: &'static str = "Usage: swap (OLD1, NEW1 [, true | false]) [(OLD2, NEW2 [, true | false])]... Swaps the given list of crate tuples, with NEW# replacing OLD# in each tuple. The OLD and NEW values are crate names, such as \"my_crate-<hash>\". Both the old crate name and the new crate name can be prefixes, e.g., \"my_cra\" will find \"my_crate-<hash>\", but *only* if there is a single matching crate or object file. A third element of each tuple is the optional 'reexport_new_symbols_as_old' boolean, which if true, will reexport new symbols under their old names, if those symbols match (excluding hashes).";
#![no_std] #![feature(slice_concat_ext)] #[macro_use] extern crate alloc; #[macro_use] extern crate terminal_print; extern crate itertools; extern crate getopts; extern crate memory; extern crate mod_mgmt; extern crate crate_swap; extern crate hpet; extern crate task; extern crate path; extern crate fs_node; use alloc::{ string::{String, ToString}, vec::Vec, sync::Arc, }; use getopts::{Options, Matches}; use mod_mgmt::{NamespaceDir, IntoCrateObjectFile}; use crate_swap::SwapRequest; use hpet::get_hpet; use path::Path; use fs_node::{FileOrDir, DirRef}; pub fn main(args: Vec<String>) -> isize { #[cfg(not(loadable))] { println!("****************\nWARNING: Theseus was not built in 'loadable' mode, so crate swapping may not work.\n****************"); } let mut opts = Options::new(); opts.optflag("h", "help", "print this help menu"); opts.optflag("v", "verbose", "enable verbose logging of crate swapping actions"); opts.optflag("c", "cache", "enable caching of the old crate(s) removed by the swapping action"); opts.optopt("d", "directory-crates", "the absolute path of the base directory where new crates will be loaded from", "PATH"); opts.optmulti("t", "state-transfer", "the fully-qualified symbol names of state transfer functions, to be run in the order given", "SYMBOL"); let matches = match opts.parse(&args) { Ok(m) => m, Err(_f) => { println!("{}", _f); print_usage(opts); return -1; } }; if matches.opt_present("h") { print_usage(opts); return 0; } match rmain(matches) { Ok(_) => 0, Err(e) => { println!("Error: {}", e); -1 } } } fn rmain(matches: Matches) -> Result<(), String> { let taskref = task::get_my_current_task() .ok_or_else(|| format!("failed to get current task"))?; let curr_dir = Arc::clone(&taskref.get_env().lock().working_dir); let override_namespace_crate_dir = if let Some(path) = matches.opt_str("d") { let path = Path::new(path); let dir = match path.get(&curr_dir) { Some(FileOrDir::Dir(dir)) => dir, _ => return Err(format!("Error: could not find specified namespace crate directory: {}.", path)), }; Some(NamespaceDir::new(dir)) } else { None }; let verbose = matches.opt_present("v"); let cache_old_crates = matches.opt_present("c"); let state_transfer_functions = matches.opt_strs("t"); let free_args = matches.free.join(" "); println!("arguments: {}", free_args); let tuples = parse_input_tuples(&free_args)?; println!("tuples: {:?}", tuples); do_swap( tuples, &curr_dir, override_namespace_crate_dir, state_transfer_functions, verbose, cache_old_crates ) } fn parse_input_tuples<'a>(args: &'a str) -> Result<Vec<(&'a str, &'a str, bool)>, String> { let mut v: Vec<(&str, &str, bool)> = Vec::new(); let mut open_paren_iter = args.match_indices('('); while let Some((paren_start, _)) = open_paren_iter.next() { let the_rest = args.get((paren_start + 1) ..).ok_or_else(|| "unmatched open parenthesis.".to_string())?; let parsed = the_rest.find(')') .and_then(|end_index| the_rest.get(.. end_index)) .and_then(|inside_paren| { let mut token_iter = inside_paren.split(',').map(str::trim); token_iter.next().and_then(|first| { token_iter.next().map(|second| { (first, second, token_iter.next()) }) }) }); match parsed { Some((o, n, reexport)) => { println!("found triple: {:?}, {:?}, {:?}", o, n, reexport); let reexport_bool = match reexport { Some("true") => true, Some("yes") => true, Some("y") => true, _ => false, };
ace = task::get_my_current_task().ok_or("Couldn't get current task")?.get_namespace(); let swap_requests = { let mut requests: Vec<SwapRequest> = Vec::with_capacity(tuples.len()); for (old_crate_name, new_crate_str, reexport) in tuples { let (into_new_crate_file, new_namespace) = { if let Some(f) = override_namespace_crate_dir.as_ref().and_then(|ns_dir| ns_dir.get_file_starting_with(new_crate_str)) { (IntoCrateObjectFile::File(f), None) } else if let Some(FileOrDir::File(f)) = Path::new(String::from(new_crate_str)).get(curr_dir) { (IntoCrateObjectFile::File(f), None) } else { (IntoCrateObjectFile::Prefix(String::from(new_crate_str)), None) } }; let swap_req = SwapRequest::new( Some(old_crate_name), Arc::clone(&namespace), into_new_crate_file, new_namespace, reexport ).map_err(|invalid_req| format!("{:#?}", invalid_req))?; requests.push(swap_req); } requests }; let start = get_hpet().as_ref().ok_or("couldn't get HPET timer")?.get_counter(); let swap_result = crate_swap::swap_crates( &namespace, swap_requests, override_namespace_crate_dir, state_transfer_functions, &kernel_mmi_ref, verbose_log, cache_old_crates, ); let end = get_hpet().as_ref().ok_or("couldn't get HPET timer")?.get_counter(); let hpet_period = get_hpet().as_ref().ok_or("couldn't get HPET timer")?.counter_period_femtoseconds(); let elapsed_ticks = end - start; match swap_result { Ok(()) => { println!("Swap operation complete. Elapsed HPET ticks: {}, (HPET Period: {} femtoseconds)", elapsed_ticks, hpet_period); Ok(()) } Err(e) => Err(e.to_string()) } } fn print_usage(opts: Options) { println!("{}", opts.usage(USAGE)); } const USAGE: &'static str = "Usage: swap (OLD1, NEW1 [, true | false]) [(OLD2, NEW2 [, true | false])]... Swaps the given list of crate tuples, with NEW# replacing OLD# in each tuple. The OLD and NEW values are crate names, such as \"my_crate-<hash>\". Both the old crate name and the new crate name can be prefixes, e.g., \"my_cra\" will find \"my_crate-<hash>\", but *only* if there is a single matching crate or object file. A third element of each tuple is the optional 'reexport_new_symbols_as_old' boolean, which if true, will reexport new symbols under their old names, if those symbols match (excluding hashes).";
v.push((o, n, reexport_bool)); } _ => return Err("list of crate tuples is formatted incorrectly.".to_string()), } } if v.is_empty() { Err("no crate tuples specified.".to_string()) } else { Ok(v) } } fn do_swap( tuples: Vec<(&str, &str, bool)>, curr_dir: &DirRef, override_namespace_crate_dir: Option<NamespaceDir>, state_transfer_functions: Vec<String>, verbose_log: bool, cache_old_crates: bool ) -> Result<(), String> { let kernel_mmi_ref = memory::get_kernel_mmi_ref().ok_or_else(|| "couldn't get kernel_mmi_ref".to_string())?; let namesp
random
[ { "content": "/// Spawns a new userspace task based on the provided `path`, which must point to an ELF executable file with a defined entry point.\n\n/// Optionally, provide a `name` for the new Task. If none is provided, the name is based on the given `Path`.\n\npub fn spawn_userspace(path: Path, name: Option<String>) -> Result<TaskRef, &'static str> {\n\n return Err(\"this function has not yet been adapted to use the fs-based crate namespace system\");\n\n\n\n debug!(\"spawn_userspace [0]: Interrupts enabled: {}\", irq_safety::interrupts_enabled());\n\n \n\n let mut new_task = Task::new();\n\n new_task.name = String::from(name.unwrap_or(String::from(path.as_ref())));\n\n\n\n let mut ustack: Option<Stack> = None;\n\n\n\n // create a new MemoryManagementInfo instance to represent the new process's address space. \n\n let new_userspace_mmi = {\n\n let kernel_mmi_ref = get_kernel_mmi_ref().expect(\"spawn_userspace(): KERNEL_MMI was not yet initialized!\");\n\n let mut kernel_mmi_locked = kernel_mmi_ref.lock();\n\n \n\n // create a new kernel stack for this userspace task\n\n let mut kstack: Stack = kernel_mmi_locked.alloc_stack(KERNEL_STACK_SIZE_IN_PAGES).expect(\"spawn_userspace: couldn't alloc_stack for new kernel stack!\");\n\n\n\n setup_context_trampoline(&mut kstack, &mut new_task, userspace_wrapper);\n\n \n", "file_path": "old_crates/spawn_userspace/src/lib.rs", "rank": 0, "score": 599883.9079822414 }, { "content": "/// This function is used for live evolution from a round robin scheduler to a priority scheduler. \n\n/// It first extracts the taskrefs from the round robin Runqueue,\n\n/// then converts them into priority taskrefs and places them on the priority Runqueue.\n\npub fn prio_sched(_old_namespace: &Arc<CrateNamespace>, _new_namespace: &CrateNamespace) -> Result<(), &'static str> {\n\n\n\n // just debugging info\n\n #[cfg(not(loscd_eval))]\n\n {\n\n warn!(\"prio_sched(): at the top.\");\n\n let rq_rr_crate = CrateNamespace::get_crate_starting_with(_old_namespace, \"runqueue_round_robin\")\n\n .map(|(_crate_name, crate_ref, _ns)| crate_ref)\n\n .ok_or(\"Couldn't get runqueue_round_robin crate from old namespace\")?;\n\n let krate = rq_rr_crate.lock_as_ref();\n\n for sec in krate.sections.values() {\n\n if sec.name.contains(\"RUNQUEUES\") {\n\n debug!(\"Section {}\\n\\ttype: {:?}\\n\\tvaddr: {:#X}\\n\\tsize: {}\\n\", sec.name, sec.typ, sec.start_address(), sec.size());\n\n }\n\n }\n\n warn!(\"REPLACING LAZY_STATIC RUNQUEUES...\");\n\n }\n\n\n\n #[cfg(loscd_eval)]\n\n let hpet = hpet::get_hpet().ok_or(\"couldn't get HPET timer\")?;\n", "file_path": "kernel/state_transfer/src/lib.rs", "rank": 1, "score": 498659.451111004 }, { "content": "/// Parses the given `path` to obtain the part of the filename before the crate name delimiter '-'. \n\nfn get_plain_crate_name_from_path<'p>(path: &'p Path) -> Result<&'p str, String> {\n\n path.file_stem()\n\n .and_then(|os_str| os_str.to_str())\n\n .ok_or_else(|| format!(\"Couldn't get file name of file in out_dir: {}\", path.display()))?\n\n .split('-').next()\n\n .ok_or_else(|| format!(\"File in out_dir missing delimiter '-' between crate name and hash. {}\", path.display()))\n\n}\n\n\n\n\n", "file_path": "tools/theseus_cargo/src/main.rs", "rank": 2, "score": 489312.4673317265 }, { "content": "/// This function calls the crate swapping routine for a corrupted crate (referred to as self swap)\n\n/// Swapping a crate with a new copy of object file includes following steps in high level\n\n/// 1) Call generic crate swapping routine with self_swap = true\n\n/// 2) Change the calues in the stack to the reloaded crate\n\n/// 3) Change any other references in the heap to the reloaded crate\n\n/// This function handles 1 and 2 operations and 3 is handled in the call site depending on necessity\n\npub fn self_swap_handler(crate_name: &str) -> Result<SwapRanges, String> {\n\n\n\n let taskref = task::get_my_current_task()\n\n .ok_or_else(|| format!(\"failed to get current task\"))?;\n\n\n\n #[cfg(not(downtime_eval))]\n\n debug!(\"The taskref is {:?}\",taskref);\n\n\n\n let curr_dir = Arc::clone(&taskref.get_env().lock().working_dir);\n\n\n\n let override_namespace_crate_dir = Option::<NamespaceDir>::None;\n\n\n\n let verbose = false;\n\n let state_transfer_functions: Vec<String> = Vec::new();\n\n\n\n let mut tuples: Vec<(&str, &str, bool)> = Vec::new();\n\n\n\n tuples.push((crate_name, crate_name , false));\n\n\n\n #[cfg(not(downtime_eval))]\n", "file_path": "kernel/fault_crate_swap/src/lib.rs", "rank": 3, "score": 488256.98800288304 }, { "content": "/// Replaces the `old_crate_name` substring in the given `demangled_full_symbol` with the given `new_crate_name`, \n\n/// if it can be found, and if the parent crate name matches the `old_crate_name`. \n\n/// If the parent crate name can be found but does not match the expected `old_crate_name`,\n\n/// then None is returned.\n\n/// \n\n/// This creates an entirely new String rather than performing an in-place replacement, \n\n/// because the `new_crate_name` might be a different length than the original crate name.\n\n/// \n\n/// We cannot simply use `str::replace()` because it would replace *all* instances of the `old_crate_name`, \n\n/// including components of function/symbol names. \n\n/// \n\n/// # Examples\n\n/// * `replace_containing_crate_name(\"keyboard::init\", \"keyboard\", \"keyboard_new\") -> Some(\"keyboard_new::init\")`\n\n/// * `replace_containing_crate_name(\"<framebuffer::VirtualFramebuffer as display::Display>::fill_rectangle\", \"display\", \"display3\")\n\n/// -> Some(\"<framebuffer::VirtualFramebuffer as display3::Display>::fill_rectangle\")`\n\npub fn replace_containing_crate_name(demangled_full_symbol: &str, old_crate_name: &str, new_crate_name: &str) -> Option<String> {\n\n let mut new_symbol = String::from(demangled_full_symbol);\n\n let mut addend: isize = 0; // index compensation for the difference in old vs. new crate name length\n\n let mut replaced = false;\n\n for range in get_containing_crate_name_ranges(demangled_full_symbol) {\n\n if demangled_full_symbol.get(range.clone()) == Some(old_crate_name) {\n\n new_symbol = format!(\"{}{}{}\", \n\n &new_symbol[.. ((range.start as isize + addend) as usize)],\n\n new_crate_name,\n\n &demangled_full_symbol[range.end ..]\n\n );\n\n replaced = true;\n\n addend += (new_crate_name.len() as isize) - (old_crate_name.len() as isize);\n\n }\n\n }\n\n if replaced { Some(new_symbol) } else { None }\n\n}\n", "file_path": "kernel/crate_name_utils/src/lib.rs", "rank": 4, "score": 488128.19302356354 }, { "content": "/// Outputs the list of sections in the given crate.\n\n/// \n\n/// # Arguments\n\n/// * `all_sections`: If `true`, then all sections will be printed. \n\n/// If `false`, then only public (global) sections will be printed.\n\n/// \n\n/// If there are multiple matches, this returns an Error containing \n\n/// all of the matching section names separated by the newline character `'\\n'`.\n\nfn sections_in_crate(crate_name: &str, all_sections: bool) -> Result<(), String> {\n\n let (crate_name, crate_ref) = find_crate(crate_name)?;\n\n\n\n let mut containing_crates = BTreeSet::new();\n\n if all_sections {\n\n println_log!(\"Sections (all) in crate {}:\", crate_name);\n\n for sec in crate_ref.lock_as_ref().sections.values() {\n\n println_log!(\" {}\", sec.name);\n\n for n in get_containing_crate_name(&sec.name) {\n\n containing_crates.insert(String::from(n));\n\n }\n\n }\n\n } else {\n\n println_log!(\"Sections (public-only) in crate {}:\", crate_name);\n\n for sec in crate_ref.lock_as_ref().global_sections_iter() {\n\n println_log!(\" {}\", sec.name);\n\n for n in get_containing_crate_name(&sec.name) {\n\n containing_crates.insert(String::from(n));\n\n }\n\n }\n\n }\n\n\n\n let crates_list = containing_crates.into_iter().collect::<Vec<String>>().join(\"\\n\");\n\n println_log!(\"Constituent (or related) crates:\\n{}\", &crates_list);\n\n Ok(())\n\n}\n\n\n\n\n", "file_path": "applications/deps/src/lib.rs", "rank": 5, "score": 456637.2499454488 }, { "content": "/// Removes a `TaskRef` from all `RunQueue`s that exist on the entire system.\n\npub fn remove_task_from_all(task: &TaskRef) -> Result<(), &'static str>{\n\n RunQueue::remove_task_from_all(task)\n\n}\n\n\n\n\n\n\n", "file_path": "kernel/runqueue/src/lib.rs", "rank": 6, "score": 453697.7047795294 }, { "content": "/// Returns the crate matching the given `crate_name` if there is a single match.\n\n/// \n\n/// If there are multiple matches, this returns an Error containing \n\n/// all of the matching section names separated by the newline character `'\\n'`.\n\nfn find_crate(crate_name: &str) -> Result<(String, StrongCrateRef), String> {\n\n let namespace = get_my_current_namespace();\n\n let mut matching_crates = CrateNamespace::get_crates_starting_with(&namespace, crate_name);\n\n match matching_crates.len() {\n\n 0 => Err(format!(\"couldn't find crate matching {:?}\", crate_name)),\n\n 1 => {\n\n let mc = matching_crates.swap_remove(0);\n\n Ok((mc.0, mc.1)) \n\n }\n\n _ => Err(matching_crates.into_iter().map(|(crate_name, _crate_ref, _ns)| crate_name).collect::<Vec<String>>().join(\"\\n\")),\n\n }\n\n}\n\n\n\n\n", "file_path": "applications/deps/src/lib.rs", "rank": 7, "score": 442980.47538265924 }, { "content": "fn print_crates(output: &mut String, indent: usize, namespace: &CrateNamespace, recursive: bool) -> core::fmt::Result {\n\n writeln!(output, \"\\n{:indent$}{} CrateNamespace has loaded crates:\", \"\", namespace.name(), indent = indent)?;\n\n let mut crates: Vec<String> = Vec::new();\n\n // We do recursion manually here so we can separately print each recursive namespace.\n\n namespace.for_each_crate(false, |crate_name, crate_ref| {\n\n crates.push(format!(\"{:indent$}{} {:?}\", \"\", crate_name, crate_ref.lock_as_ref().object_file.lock().get_absolute_path(), indent = (indent + 4)));\n\n true\n\n });\n\n crates.sort();\n\n for c in crates {\n\n writeln!(output, \"{}\", c)?;\n\n }\n\n\n\n if recursive {\n\n if let Some(r_ns) = namespace.recursive_namespace() {\n\n print_crates(output, indent + 2, r_ns.deref(), recursive)?;\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\n\n", "file_path": "applications/ns/src/lib.rs", "rank": 8, "score": 439216.26627476927 }, { "content": "/// This function sets up the given new `Task`'s kernel stack pointer to properly jump\n\n/// to the given entry point function when the new `Task` is first scheduled in. \n\n/// \n\n/// When a new task is first scheduled in, a `Context` struct will be popped off the stack,\n\n/// and at the end of that struct is the address of the next instruction that will be popped off as part of the \"ret\" instruction, \n\n/// i.e., the entry point into the new task. \n\n/// \n\n/// So, this function allocates space for the saved context registers to be popped off when this task is first switched to.\n\n/// It also sets the given `new_task`'s `saved_sp` (its saved stack pointer, which holds the Context for task switching).\n\n/// \n\nfn setup_context_trampoline(new_task: &mut Task, entry_point_function: fn() -> !) -> Result<(), &'static str> {\n\n \n\n /// A private macro that actually creates the Context and sets it up in the `new_task`.\n\n /// We use a macro here so we can pass in the proper `ContextType` at runtime, \n\n /// which is useful for both the simd_personality config and regular/SSE configs.\n\n macro_rules! set_context {\n\n ($ContextType:ty) => (\n\n // We write the new Context struct at the top of the stack, which is at the end of the stack's MappedPages. \n\n // We subtract \"size of usize\" (8) bytes to ensure the new Context struct doesn't spill over past the top of the stack.\n\n let mp_offset = new_task.inner_mut().kstack.size_in_bytes() - mem::size_of::<usize>() - mem::size_of::<$ContextType>();\n\n let new_context_destination: &mut $ContextType = new_task.inner_mut().kstack.as_type_mut(mp_offset)?;\n\n *new_context_destination = <$ContextType>::new(entry_point_function as usize);\n\n new_task.inner_mut().saved_sp = new_context_destination as *const _ as usize;\n\n );\n\n }\n\n\n\n // If `simd_personality` is enabled, all of the `context_switch*` implementation crates are simultaneously enabled,\n\n // in order to allow choosing one of them based on the configuration options of each Task (SIMD, regular, etc).\n\n #[cfg(simd_personality)] {\n\n match new_task.simd {\n", "file_path": "kernel/spawn/src/lib.rs", "rank": 9, "score": 437286.9768535586 }, { "content": "pub fn sysrecv(name:&CStr) -> String{\n\n let sname = name.to_string_lossy().into_owned();;;\n\n trace!(\"Get the connection {}\", &sname);\n\n let mut table = get_connection_table().write();\n\n let mut connection = table.get_connection(sname)\n\n .expect(\"Fail to create the bus connection\").write();\n\n\n\n let obj = connection.receive();\n\n if obj.is_some() {\n\n trace!(\"Get the result!\");\n\n return obj.unwrap().data;\n\n } else {\n\n trace!(\"No message!\");\n\n return String::from(\"\");\n\n }\n\n}\n", "file_path": "old_crates/dbus/src/lib.rs", "rank": 10, "score": 435715.33054222027 }, { "content": "fn print_files(output: &mut String, indent: usize, namespace: &CrateNamespace, recursive: bool) -> core::fmt::Result {\n\n writeln!(output, \"\\n{:indent$}{} CrateNamespace has crate object files:\", \"\", namespace.name(), indent = indent)?;\n\n let mut files = namespace.dir().lock().list();\n\n files.sort();\n\n for f in files {\n\n writeln!(output, \"{:indent$}{}\", \"\", f, indent = (indent + 4))?;\n\n }\n\n\n\n if recursive {\n\n if let Some(r_ns) = namespace.recursive_namespace() {\n\n print_files(output, indent + 2, r_ns.deref(), recursive)?;\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\n\n", "file_path": "applications/ns/src/lib.rs", "rank": 12, "score": 425113.5945333614 }, { "content": "/// Creates a new directory with a unique name in the given `parent_dir`. \n\n/// For example, given a base_name of \"my_dir\", \n\n/// it will create a directory \"my_dir.2\" if \"my_dir\" and \"my_dir.1\" already exist.\n\nfn make_unique_directory(base_name: &str, parent_dir: &DirRef) -> Result<DirRef, &'static str> {\n\n if parent_dir.lock().get(base_name).is_none() {\n\n return VFSDirectory::new(base_name.to_string(), parent_dir);\n\n }\n\n for i in 1.. {\n\n let new_base_name = format!(\"{}.{}\", base_name, i);\n\n if parent_dir.lock().get(&new_base_name).is_none() {\n\n return VFSDirectory::new(new_base_name, parent_dir);\n\n } \n\n }\n\n\n\n Err(\"unable to create new unique directory\")\n\n}\n\n\n\n\n", "file_path": "applications/upd/src/lib.rs", "rank": 13, "score": 423567.98013474175 }, { "content": "fn load_crate(output: &mut String, crate_file_ref: FileRef, namespace: &Arc<CrateNamespace>) -> Result<(), String> {\n\n let kernel_mmi_ref = memory::get_kernel_mmi_ref().ok_or_else(|| format!(\"Cannot get kernel_mmi_ref\"))?;\n\n let (_new_crate_ref, _new_syms) = namespace.load_crate(\n\n &crate_file_ref,\n\n None,\n\n &kernel_mmi_ref,\n\n false\n\n ).map_err(|e| String::from(e))?;\n\n writeln!(output, \"Loaded crate with {} new symbols from {}\", _new_syms, crate_file_ref.lock().get_absolute_path()).unwrap();\n\n Ok(())\n\n}\n\n\n\n\n", "file_path": "applications/ns/src/lib.rs", "rank": 14, "score": 412844.7681497364 }, { "content": "/// Applies an already-downloaded update according the \"diff.txt\" file\n\n/// that must be in the given base directory.\n\nfn apply(base_dir_path: &Path) -> Result<(), String> {\n\n if cfg!(not(loadable)) {\n\n return Err(format!(\"Evolutionary updates can only be applied when Theseus is built in loadable mode.\"));\n\n }\n\n\n\n let kernel_mmi_ref = memory::get_kernel_mmi_ref().ok_or_else(|| format!(\"couldn't get kernel MMI\"))?;\n\n let curr_dir = task::get_my_current_task().map(|t| t.get_env().lock().working_dir.clone()).ok_or_else(|| format!(\"couldn't get my current working directory\"))?;\n\n let new_namespace_dir = match base_dir_path.get(&curr_dir) {\n\n Some(FileOrDir::Dir(d)) => NamespaceDir::new(d),\n\n _ => return Err(format!(\"cannot find an update base directory at path {}\", base_dir_path)),\n\n };\n\n let diff_file = match new_namespace_dir.lock().get(DIFF_FILE_NAME) { \n\n Some(FileOrDir::File(f)) => f,\n\n _ => return Err(format!(\"cannot find diff file expected at {}/{}\", base_dir_path, DIFF_FILE_NAME)),\n\n };\n\n let mut diff_content: Vec<u8> = alloc::vec::from_elem(0, diff_file.lock().size()); \n\n let _bytes_read = diff_file.lock().read(&mut diff_content, 0)?;\n\n let diffs = ota_update_client::as_lines(&diff_content).map_err(|e| e.to_string())\n\n .and_then(|diff_lines| ota_update_client::parse_diff_lines(&diff_lines).map_err(|e| e.to_string()))?;\n\n\n", "file_path": "applications/upd/src/lib.rs", "rank": 15, "score": 408477.0494424983 }, { "content": "/// Chooses the \"least busy\" core's runqueue\n\n/// and adds the given `Task` reference to that core's runqueue.\n\npub fn add_task_to_any_runqueue(task: TaskRef) -> Result<(), &'static str>{\n\n RunQueue::add_task_to_any_runqueue(task)\n\n}\n\n\n", "file_path": "kernel/runqueue/src/lib.rs", "rank": 16, "score": 408019.60812394647 }, { "content": "/// Parse the given verbose rustc command string and return the value of the \"--out-dir\" argument.\n\nfn get_out_dir_arg(cmd_str: &str) -> Result<String, String> {\n\n let out_dir_str_start = cmd_str.find(\" --out-dir\")\n\n .map(|idx| &cmd_str[idx..])\n\n .ok_or_else(|| format!(\"Captured rustc command did not have an --out-dir argument\"))?;\n\n let out_dir_parse = rustc_clap_options(\"\")\n\n .setting(clap::AppSettings::DisableHelpFlags)\n\n .setting(clap::AppSettings::DisableHelpSubcommand)\n\n .setting(clap::AppSettings::AllowExternalSubcommands)\n\n .setting(clap::AppSettings::NoBinaryName)\n\n .setting(clap::AppSettings::ColorNever)\n\n .get_matches_from_safe(out_dir_str_start.split_whitespace());\n\n let matches = out_dir_parse.map_err(|e| \n\n format!(\"Could not parse --out-dir argument in captured rustc command.\\nError {}\", e)\n\n )?;\n\n matches.value_of(\"--out-dir\")\n\n .map(String::from)\n\n .ok_or_else(|| format!(\"--out-dir argument did not have a value\"))\n\n}\n\n\n\n\n", "file_path": "tools/theseus_cargo/src/main.rs", "rank": 17, "score": 407685.89983285917 }, { "content": "/// Outputs the given crate's weak dependents, i.e.,\n\n/// the crates that depend on the given crate.\n\n/// \n\n/// If there are multiple matches, this returns an Error containing \n\n/// all of the matching crate names separated by the newline character `'\\n'`.\n\nfn crates_dependent_on_me(_crate_name: &str) -> Result<(), String> {\n\n Err(format!(\"unimplemented\"))\n\n}\n\n\n\n\n", "file_path": "applications/deps/src/lib.rs", "rank": 18, "score": 406320.82831300865 }, { "content": "/// Outputs the given crate's strong dependencies, i.e.,\n\n/// the crates that the given crate depends on.\n\n/// \n\n/// If there are multiple matches, this returns an Error containing \n\n/// all of the matching crate names separated by the newline character `'\\n'`.\n\nfn crates_i_depend_on(_crate_name: &str) -> Result<(), String> {\n\n Err(format!(\"unimplemented\"))\n\n}\n\n\n\n\n\n\n", "file_path": "applications/deps/src/lib.rs", "rank": 19, "score": 406320.82831300865 }, { "content": "/// Finds the corresponding function for each instruction pointer and calculates the percentage amount each function occured in the samples\n\npub fn find_function_names_from_samples(sample_results: &SampleResults) -> Result<(), &'static str> {\n\n let taskref = task::get_my_current_task().ok_or(\"pmu_x86::get_function_names_from_samples: Could not get reference to current task\")?;\n\n let namespace = taskref.get_namespace();\n\n debug!(\"Analyze Samples:\");\n\n\n\n let mut sections: BTreeMap<String, usize> = BTreeMap::new();\n\n let total_samples = sample_results.instruction_pointers.len();\n\n\n\n for ip in sample_results.instruction_pointers.iter() {\n\n let (section_ref, _offset) = namespace.get_section_containing_address(\n\n memory::VirtualAddress::new(ip.0).ok_or(\"sampled instruction pointer was an invalid virtual address\")?,\n\n true\n\n ).ok_or(\"Can't find section containing sampled instruction pointer\")?;\n\n let section_name = section_ref.name_without_hash().to_string();\n\n\n\n sections.entry(section_name).and_modify(|e| {*e += 1}).or_insert(1);\n\n }\n\n\n\n for (section, occurrences) in sections.iter() {\n\n let percentage = *occurrences as f32 / total_samples as f32 * 100.0;\n\n debug!(\"{:?} {}% \\n\", section, percentage);\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "kernel/pmu_x86/src/lib.rs", "rank": 20, "score": 403932.27209229174 }, { "content": "fn num_deps_crate(crate_name: &str) -> Result<(), String> {\n\n let (_cn, crate_ref) = find_crate(crate_name)?;\n\n let (s, w, i) = crate_dependency_count(&crate_ref);\n\n println!(\"Crate {}'s Dependency Count:\\nStrong: {}\\nWeak: {}\\nIntrnl: {}\", crate_name, s, w, i);\n\n Ok(())\n\n}\n\n\n", "file_path": "applications/deps/src/lib.rs", "rank": 21, "score": 400201.7806153407 }, { "content": "/// Returns the crate name that is derived from a crate object file path.\n\n/// \n\n/// # Examples of acceptable paths\n\n/// Legal paths can:\n\n/// * be absolute or relative,\n\n/// * optionally end with an extension, e.g., `\".o\"`, optionally start \n\n/// * optionally start with a module file prefix, e.g., `\"k#my_crate-<hash>.o\"`.\n\npub fn crate_name_from_path<'p>(object_file_path: &'p Path) -> &'p str {\n\n let stem = object_file_path.file_stem();\n\n if let Ok((_crate_type, _prefix, name)) = CrateType::from_module_name(stem) {\n\n name\n\n } else {\n\n stem\n\n }\n\n}\n\n\n", "file_path": "kernel/crate_name_utils/src/lib.rs", "rank": 22, "score": 400198.30873816303 }, { "content": "/// Parses the given symbol string to try to find the name of the parent crate\n\n/// that contains the symbol. \n\n/// Depending on the symbol, there may be multiple potential parent crates;\n\n/// if so, they are returned in order of likeliness: \n\n/// the first crate name in the symbol is most likely to contain it.\n\n/// If the parent crate cannot be determined (e.g., a `no_mangle` symbol),\n\n/// then an empty `Vec` is returned.\n\n/// \n\n/// # Examples\n\n/// * `<*const T as core::fmt::Debug>::fmt` -> `[\"core\"]`\n\n/// * `<alloc::boxed::Box<T>>::into_unique` -> `[\"alloc\"]`\n\n/// * `<framebuffer::VirtualFramebuffer as display::Display>::fill_rectangle` -> `[\"framebuffer\", \"display\"]`\n\n/// * `keyboard::init` -> `[\"keyboard\"]`\n\npub fn get_containing_crate_name<'a>(demangled_full_symbol: &'a str) -> Vec<&'a str> {\n\n get_containing_crate_name_ranges(demangled_full_symbol)\n\n .into_iter()\n\n .filter_map(|range| demangled_full_symbol.get(range))\n\n .dedup()\n\n .collect()\n\n}\n\n\n\n\n", "file_path": "kernel/crate_name_utils/src/lib.rs", "rank": 23, "score": 396355.2217847112 }, { "content": "/// Removes the (child application's task ID, parent terminal print_producer) key-val pair from the map\n\n/// Called right after an application exits\n\npub fn remove_child(child_task_id: usize) -> Result<(), &'static str> {\n\n TERMINAL_PRINT_PRODUCERS.lock().remove(&child_task_id);\n\n Ok(()) \n\n}\n\n\n\n\n\n\n\nuse core::fmt;\n", "file_path": "kernel/terminal_print/src/lib.rs", "rank": 24, "score": 394094.2936114032 }, { "content": "/// Goes through the contents of each directory to compare each file. \n\n/// \n\n/// Returns a mapping of old crate to new crate, meaning that the old crate should be replaced with the new crate. \n\n/// If the old crate is `None` and the new crate is `Some`, then the new crate is a new addition that does not replace any old crate.\n\n/// If the old crate is `Some` and the new crate is `None`, then the old crate is merely being removed without being replaced.\n\n/// If both the old crate and new crate are `Some`, then the new crate is replacing the old crate.\n\nfn compare_dirs(old_dir_contents: Trie<BString, PathBuf>, new_dir_contents: Trie<BString, PathBuf>) -> Result<MultiMap<String, String>, String> {\n\n let mut replacements: MultiMap<String, String> = MultiMap::new();\n\n\n\n // First, we go through the new directory and see which files have changed since the old directory\n\n for (new_filename, new_path) in new_dir_contents.iter() {\n\n\n\n // if the old dir contains an identical file as the new dir, then we diff their actual contents\n\n if let Some(old_path) = old_dir_contents.get(new_filename) {\n\n let old_file = fs::read(old_path).map_err(|e| e.to_string())?;\n\n let new_file = fs::read(new_path).map_err(|e| e.to_string())?;\n\n if old_file != new_file {\n\n println!(\"{0} -> {0}\", new_filename.as_str());\n\n replacements.insert(new_filename.clone().into(), new_filename.clone().into());\n\n }\n\n }\n\n // otherwise we try to search the old dir to see if there's a single matching crate that has a different hash\n\n else {\n\n // initially, we search just the crate name itself (e.g., \"terminal\", \"apic\") without the trailing hash to allow for matching applications.\n\n let crate_name_search_str = format!(\"{}\", crate_name_without_hash(new_filename.as_str()));\n\n let matching_old_crates: Vec<(BString, PathBuf)> = old_dir_contents.iter_prefix_str(&crate_name_search_str).map(|(k, v)| (k.clone(), v.clone())).collect();\n", "file_path": "tools/diff_crates/src/main.rs", "rank": 25, "score": 392359.44195370865 }, { "content": "/// This function is designed to be invoked from an interrupt handler \n\n/// when a sampling interrupt has (or may have) occurred. \n\n///\n\n/// It takes a sample by logging the the instruction pointer and task ID at the point\n\n/// at which the sampling interrupt occurred. \n\n/// The counter is then either reset to its starting value \n\n/// (if there are more samples that need to be taken)\n\n/// or disabled entirely if the final sample has been taken. \n\n///\n\n/// # Argument\n\n/// * `stack_frame`: the stack frame that was pushed onto the stack automatically \n\n/// by the CPU and passed into the interrupt/exception handler. \n\n/// This is used to determine during which instruction the sampling interrupt occurred.\n\n///\n\n/// # Return\n\n/// * Returns `Ok(true)` if a PMU sample occurred and was handled. \n\n/// * Returns `Ok(false)` if PMU isn't supported, or if PMU wasn't yet initialized, \n\n/// or if there was not a pending sampling interrupt. \n\n/// * Returns an `Err` if PMU is supported and initialized and a sample was pending, \n\n/// but an error occurred while logging the sample.\n\n///\n\npub fn handle_sample(stack_frame: &mut ExceptionStackFrame) -> Result<bool, &'static str> {\n\n // Check that PMU hardware exists and is supported on this machine.\n\n if *PMU_VERSION < MIN_PMU_VERSION {\n\n return Ok(false);\n\n }\n\n // Check that a PMU sampling event is currently pending.\n\n if rdmsr(IA32_PERF_GLOBAL_STAUS) == 0 {\n\n return Ok(false);\n\n }\n\n\n\n unsafe { wrmsr(IA32_PERF_GLOBAL_OVF_CTRL, CLEAR_PERF_STATUS_MSR); }\n\n\n\n let my_core_id = apic::get_my_apic_id();\n\n let event_mask = rdmsr(IA32_PERFEVTSEL0);\n\n\n\n let mut sampling_info = SAMPLING_INFO.lock();\n\n let mut samples = sampling_info.get_mut(&my_core_id)\n\n .ok_or(\"pmu_x86::handle_sample: Could not retrieve sampling information for this core\")?;\n\n\n\n let current_count = samples.sample_count;\n", "file_path": "kernel/pmu_x86/src/lib.rs", "rank": 26, "score": 391348.2914188261 }, { "content": "/// This function returns the name of the crate to replace if required. \n\n/// Returns none if no crate is needed to be replaced. \n\npub fn get_crate_to_swap() -> Option<String> {\n\n\n\n #[cfg(not(use_crate_replacement))]\n\n {\n\n return null_swap_policy();\n\n }\n\n\n\n\n\n #[cfg(use_crate_replacement)]\n\n {\n\n #[cfg(not(use_iterative_replacement))]\n\n return simple_swap_policy();\n\n\n\n #[cfg(use_iterative_replacement)]\n\n return iterative_swap_policy() ;\n\n }\n\n}\n", "file_path": "kernel/fault_crate_swap/src/lib.rs", "rank": 27, "score": 382009.2490633057 }, { "content": "/// Adds the given `Task` reference to given core's runqueue.\n\npub fn add_task_to_specific_runqueue(which_core: u8, task: TaskRef) -> Result<(), &'static str>{\n\n RunQueue::add_task_to_specific_runqueue(which_core, task)\n\n}\n\n\n", "file_path": "kernel/runqueue/src/lib.rs", "rank": 28, "score": 379951.3577393348 }, { "content": "/// Changes the priority of the given task with the given priority level.\n\n/// Priority values must be between 40 (maximum priority) and 0 (minimum prriority).\n\npub fn set_priority(task: &TaskRef, priority: u8) -> Result<(), &'static str> {\n\n let priority = core::cmp::min(priority, MAX_PRIORITY);\n\n RunQueue::set_priority(task, priority)\n\n}\n\n\n", "file_path": "kernel/scheduler_priority/src/lib.rs", "rank": 29, "score": 376628.47468942497 }, { "content": "/// Shell call this function to check whether a task is requesting instant stdin flush.\n\n/// \n\n/// Error can occur when there is no IoControlFlags structure for that task.\n\npub fn is_requesting_instant_flush(task_id: &usize) -> Result<bool, &'static str> {\n\n let locked_flags = shared_maps::lock_flag_map();\n\n match locked_flags.get(task_id) {\n\n Some(flags) => {\n\n Ok(flags.stdin_instant_flush)\n\n },\n\n None => Err(\"no io control flags for this task\")\n\n }\n\n}\n\n\n\n/// Calls `print!()` with an extra newline ('\\n') appended to the end. \n\n#[macro_export]\n\nmacro_rules! println {\n\n ($fmt:expr) => (print!(concat!($fmt, \"\\n\")));\n\n ($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, \"\\n\"), $($arg)*));\n\n\n\n}\n\n\n\n/// The main printing macro, which simply writes to the current task's stdout stream.\n\n#[macro_export]\n\nmacro_rules! print {\n\n ($($arg:tt)*) => ({\n\n $crate::print_to_stdout_args(format_args!($($arg)*));\n\n });\n\n}\n\n\n\nuse core::fmt;\n\nuse bare_io::Write;\n", "file_path": "applications/app_io/src/lib.rs", "rank": 30, "score": 376293.3365553078 }, { "content": "/// enable or disable the packet streaming\n\n/// also return the vec of data previously in the buffer which may be useful\n\npub fn mouse_packet_streaming(enable: bool) -> Result<Vec<u8>, &'static str> {\n\n if enable {\n\n if let Err(_e) = command_to_mouse(0xf4) {\n\n warn!(\"enable streaming failed\");\n\n Err(\"enable mouse streaming failed\")\n\n } else {\n\n // info!(\"enable streaming succeeded!!\");\n\n Ok(Vec::new())\n\n }\n\n }\n\n else {\n\n let mut buffer_data = Vec::new();\n\n if data_to_port2(0xf5) != 0xfa {\n\n for x in 0..15 {\n\n if x == 14 {\n\n warn!(\"disable mouse streaming failed\");\n\n return Err(\"disable mouse streaming failed\");\n\n }\n\n let response = ps2_read_data();\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 31, "score": 375503.69543570344 }, { "content": "/// Performs early-stage initialization for simple devices needed during early boot.\n\n///\n\n/// This includes:\n\n/// * local APICs ([`apic`]),\n\n/// * [`acpi`] tables for system configuration info, including the IOAPIC.\n\npub fn early_init(kernel_mmi: &mut MemoryManagementInfo) -> Result<(), &'static str> {\n\n // First, initialize the local apic info.\n\n apic::init(&mut kernel_mmi.page_table)?;\n\n \n\n // Then, parse the ACPI tables to acquire system configuration info.\n\n acpi::init(&mut kernel_mmi.page_table)?;\n\n\n\n Ok(())\n\n}\n\n\n\n\n", "file_path": "kernel/device_manager/src/lib.rs", "rank": 32, "score": 371455.4948536592 }, { "content": "/// Returns the section matching the given `section_name` if there is a single match.\n\n/// \n\n/// If there are multiple matches, this returns an Error containing \n\n/// all of the matching section names separated by the newline character `'\\n'`.\n\nfn find_section(section_name: &str) -> Result<StrongSectionRef, String> {\n\n let namespace = get_my_current_namespace();\n\n let matching_symbols = namespace.find_symbols_starting_with(section_name);\n\n if matching_symbols.len() == 1 {\n\n return matching_symbols[0].1.upgrade()\n\n .ok_or_else(|| format!(\"Found matching symbol name but couldn't get reference to section\"));\n\n } else if matching_symbols.len() > 1 {\n\n return Err(matching_symbols.into_iter().map(|(k, _v)| k).collect::<Vec<String>>().join(\"\\n\"));\n\n } else {\n\n // continue on\n\n }\n\n\n\n // If it wasn't a global section in the symbol map, then we need to find its containing crate\n\n // and search that crate's symbols manually.\n\n let containing_crate_ref = get_containing_crate_name(section_name).get(0)\n\n .and_then(|cname| CrateNamespace::get_crate_starting_with(&namespace, &format!(\"{}-\", cname)))\n\n .or_else(|| get_containing_crate_name(section_name).get(1)\n\n .and_then(|cname| CrateNamespace::get_crate_starting_with(&namespace, &format!(\"{}-\", cname)))\n\n )\n\n .map(|(_cname, crate_ref, _ns)| crate_ref)\n", "file_path": "applications/deps/src/lib.rs", "rank": 33, "score": 368825.29379083513 }, { "content": "/// Same as [`get_containing_crate_name()`](#get_containing_crate_name),\n\n/// but returns the substring `Range`s of where the parent crate names \n\n/// are located in the given `demangled_full_symbol` string.\n\n/// \n\n/// # Examples\n\n/// * `<*const T as core::fmt::Debug>::fmt` -> `[12..16]`\n\n/// * `<alloc::boxed::Box<T>>::into_unique` -> `[1..6]`\n\n/// * `<framebuffer::VirtualFramebuffer as display::Display>::fill_rectangle` -> `[1..13, 37..44]`\n\n/// * `keyboard::init` -> `[0..8]`\n\npub fn get_containing_crate_name_ranges(demangled_full_symbol: &str) -> Vec<Range<usize>> {\n\n let mut ranges: Vec<Range<usize>> = Vec::new();\n\n // the separator between independent parts of the symbol string\n\n const AS: &'static str = \" as \";\n\n // the index at which we are starting our search for a crate name\n\n let mut beginning_bound = Some(0);\n\n\n\n while let Some(beg) = beginning_bound {\n\n // Find the first occurrence of \"::\"; the crate name will be right before that.\n\n let end = demangled_full_symbol.get(beg..)\n\n .and_then(|s| s.find(\"::\"))\n\n .map(|end_idx| beg + end_idx);\n\n\n\n if let Some(end) = end {\n\n // If the above search for \"::\" passed an \" as \" substring, \n\n // we skip it and let the next iteration of the loop handle it to avoid doubly counting it.\n\n if demangled_full_symbol.get(beg..end).map(|s| s.contains(AS)) != Some(true) {\n\n // Find the beginning of the crate name, searching backwards from the \"end\"\n\n let start = demangled_full_symbol.get(beg..end)\n\n .and_then(|s| s.rfind(|c| !is_valid_crate_name_char(c))) // find the first char before the crate name that isn't part of the crate name\n", "file_path": "kernel/crate_name_utils/src/lib.rs", "rank": 34, "score": 367750.6082950745 }, { "content": "/// Provides the most recent entry in the log for given crate\n\n/// Utility function for iterative crate replacement\n\npub fn get_the_most_recent_match(error_crate : &str) -> Option<FaultEntry> {\n\n\n\n #[cfg(not(downtime_eval))]\n\n debug!(\"getting the most recent match\");\n\n\n\n let mut fe :Option<FaultEntry> = None;\n\n for fault_entry in FAULT_LIST.lock().iter() {\n\n if let Some(crate_error_occured) = &fault_entry.crate_error_occured {\n\n let error_crate_name = crate_error_occured.clone();\n\n let error_crate_name_simple = error_crate_name.split(\"-\").next().unwrap_or_else(|| &error_crate_name);\n\n if error_crate_name_simple == error_crate {\n\n let item = fault_entry.clone();\n\n fe = Some(item);\n\n }\n\n }\n\n }\n\n\n\n if fe.is_none(){\n\n\n\n #[cfg(not(downtime_eval))]\n\n debug!(\"No recent entries for the given crate {}\", error_crate);\n\n }\n\n fe\n\n}", "file_path": "kernel/fault_log/src/lib.rs", "rank": 35, "score": 366278.20432617544 }, { "content": "/// Starts a new task that detects new console connections\n\n/// by waiting for new data to be received on serial ports.\n\n///\n\n/// Returns the newly-spawned detection task.\n\npub fn start_connection_detection() -> Result<TaskRef, &'static str> {\n\n\tlet (sender, receiver) = async_channel::new_channel(4);\n\n\tserial_port::set_connection_listener(sender);\n\n\n\n\tspawn::new_task_builder(console_connection_detector, receiver)\n\n\t\t.name(\"console_connection_detector\".into())\n\n\t\t.spawn()\n\n}\n\n\n\npub struct Console<I, O, Backend> \n\n\twhere I: bare_io::Read,\n\n\t O: bare_io::Write,\n\n\t\t Backend: TerminalBackend,\n\n{\n\n\tname: String,\n\n\t_input: I,\n\n\tterminal: TextTerminal<Backend>,\n\n\t_output: PhantomData<O>,\n\n}\n\n\n", "file_path": "kernel/console/src/lib.rs", "rank": 36, "score": 365571.09612527635 }, { "content": "pub fn rmain(matches: &Matches, opts: &Options) -> Result<(), &'static str> {\n\n\n\n let mut did_work = false;\n\n\n\n if let Some(i) = matches.opt_str(\"w\") {\n\n let num_tasks = i.parse::<usize>().map_err(|_e| \"couldn't parse number of num_tasks\")?;\n\n run_whole(num_tasks)?;\n\n did_work = true;\n\n }\n\n\n\n if let Some(i) = matches.opt_str(\"s\") {\n\n let iterations = i.parse::<usize>().map_err(|_e| \"couldn't parse number of num_tasks\")?;\n\n run_single(iterations)?;\n\n did_work = true;\n\n } \n\n\n\n if did_work {\n\n Ok(())\n\n }\n\n else {\n\n println!(\"Nothing was done. Please specify a type of evaluation task to run.\");\n\n print_usage(opts);\n\n Ok(())\n\n }\n\n}\n\n\n\n\n", "file_path": "applications/rq_eval/src/lib.rs", "rank": 37, "score": 364208.5968591212 }, { "content": "pub fn rmain(matches: &Matches, _opts: &Options) -> Result<(), &'static str> {\n\n const TRIES: usize = 10;\n\n let mut mapper_normal = mapper_from_current();\n\n let mut mapper_spillful = MapperSpillful::new();\n\n\n\n let num_mappings = matches.opt_str(\"n\")\n\n .and_then(|i| i.parse::<usize>().ok())\n\n .unwrap_or(100);\n\n\n\n let size_in_pages = matches.opt_str(\"s\")\n\n .and_then(|i| i.parse::<usize>().ok())\n\n .unwrap_or(2);\n\n\n\n let use_spillful = matches.opt_present(\"p\");\n\n let verbose = matches.opt_present(\"v\");\n\n\n\n if num_mappings < 1 { \n\n return Err(\"invalid number of mappings specified.\")\n\n }\n\n\n", "file_path": "applications/mm_eval/src/lib.rs", "rank": 38, "score": 364208.5968591211 }, { "content": "/// Iterates over the contents of the given directory to find crates within it. \n\n/// \n\n/// This directory should contain one .rmeta and .rlib file per crate, \n\n/// and those files are named as such:\n\n/// `\"lib<crate_name>-<hash>.[rmeta]\"`\n\n/// \n\n/// This function only looks at the `.rmeta` files in the given directory \n\n/// and extracts from that file name the name of the crate name as a String.\n\n/// \n\n/// Returns the set of discovered crates as a map, in which the key is the simple crate name \n\n/// (\"my_crate\") and the value is the full crate name with the hash included (\"my_crate-43462c60d48a531a\").\n\n/// The value can be used to define the path to crate's actual .rmeta/.rlib file.\n\nfn populate_crates_from_dir<P: AsRef<Path>>(dir_path: P) -> Result<HashMap<String, String>, io::Error> {\n\n let mut crates: HashMap<String, String> = HashMap::new();\n\n \n\n let dir_iter = WalkDir::new(dir_path)\n\n .into_iter()\n\n .filter_map(|res| res.ok());\n\n\n\n for dir_entry in dir_iter {\n\n if !dir_entry.file_type().is_file() { continue; }\n\n let path = dir_entry.path();\n\n if path.extension().and_then(|p| p.to_str()) == Some(RMETA_FILE_EXTENSION) {\n\n let filestem = path.file_stem().expect(\"no valid file stem\").to_string_lossy();\n\n if filestem.starts_with(\"lib\") {\n\n let crate_name_with_hash = &filestem[PREFIX_END ..];\n\n let crate_name_without_hash = crate_name_with_hash.split('-').next().unwrap();\n\n crates.insert(crate_name_without_hash.to_string(), crate_name_with_hash.to_string());\n\n } else {\n\n return Err(io::Error::new(\n\n io::ErrorKind::Other,\n\n format!(\"File {:?} is an .rmeta file that does not begin with 'lib' as expected.\", path),\n", "file_path": "tools/theseus_cargo/src/main.rs", "rank": 39, "score": 362042.4131036053 }, { "content": "/// Returns the top-level directory that contains all of the namespaces. \n\npub fn get_namespaces_directory() -> Option<DirRef> {\n\n root::get_root().lock().get_dir(NAMESPACES_DIRECTORY_NAME)\n\n}\n\n\n\nlazy_static! {\n\n /// The thread-local storage (TLS) area \"image\" that is used as the initial data for each `Task`.\n\n /// When spawning a new task, the new task will create its own local TLS area\n\n /// with this `TlsInitializer` as the initial data values.\n\n /// \n\n /// # Implementation Notes/Shortcomings\n\n /// Currently, a single system-wide `TlsInitializer` instance is shared across all namespaces.\n\n /// In the future, each namespace should hold its own TLS sections in its TlsInitializer area.\n\n /// \n\n /// However, this is quite complex because each namespace must be aware of the TLS sections\n\n /// in BOTH its underlying recursive namespace AND its (multiple) \"parent\" namespace(s)\n\n /// that recursively depend on it, since no two TLS sections can conflict (have the same offset).\n\n /// \n\n /// Thus, we stick with a singleton `TlsInitializer` instance, which makes sense \n\n /// because it behaves much like an allocator, in that it reserves space (index ranges) in the TLS area.\n\n static ref TLS_INITIALIZER: Mutex<TlsInitializer> = Mutex::new(TlsInitializer::empty());\n\n}\n\n\n\n\n", "file_path": "kernel/mod_mgmt/src/lib.rs", "rank": 40, "score": 355910.05587729823 }, { "content": "pub fn remove_node(args: Vec<String>) -> Result<(), String> {\n\n let mut opts = Options::new();\n\n opts.optflag(\"h\", \"help\", \"print this help menu\");\n\n opts.optflag(\"r\", \"recursive\", \"recursively remove directories and their contents\");\n\n \n\n let matches = match opts.parse(&args) {\n\n Ok(m) => m,\n\n Err(e) => {\n\n print_usage(opts);\n\n return Err(e.to_string());\n\n }\n\n };\n\n\n\n if matches.opt_present(\"h\") {\n\n print_usage(opts);\n\n return Ok(());\n\n }\n\n\n\n\n\n let taskref = match task::get_my_current_task() {\n", "file_path": "applications/rm/src/lib.rs", "rank": 41, "score": 355705.60782637005 }, { "content": "/// Starts the first applications that run in Theseus \n\n/// by creating a new \"default\" application namespace\n\n/// and spawning the first application `Task`(s). \n\n/// \n\n/// Currently this only spawns a shell (terminal),\n\n/// but in the future it could spawn a fuller desktop environment. \n\n/// \n\n/// Kernel initialization routines should be complete before invoking this. \n\npub fn start() -> Result<(), &'static str> {\n\n let new_app_ns = mod_mgmt::create_application_namespace(None)?;\n\n let (shell_file, _ns) = CrateNamespace::get_crate_object_file_starting_with(&new_app_ns, \"shell-\")\n\n .ok_or(\"Couldn't find shell application in default app namespace\")?;\n\n\n\n let path = Path::new(shell_file.lock().get_absolute_path());\n\n info!(\"Starting first application: crate at {:?}\", path);\n\n // Spawn the default shell\n\n spawn::new_application_task_builder(path, Some(new_app_ns))?\n\n .name(\"default_shell\".to_string())\n\n .spawn()?;\n\n\n\n Ok(())\n\n}\n", "file_path": "kernel/first_application/src/lib.rs", "rank": 42, "score": 352575.5810519779 }, { "content": "/// Initializes the tasks virtual filesystem directory within the root directory.\n\npub fn init() -> Result<(), &'static str> {\n\n TaskFs::new()?;\n\n Ok(())\n\n}\n\n\n\n\n\n/// The top level directory that includes a dynamically-generated list of all `Task`s,\n\n/// each comprising a `TaskDir`.\n\n/// This directory exists in the root directory.\n\npub struct TaskFs { }\n\n\n\nimpl TaskFs {\n\n fn new() -> Result<DirRef, &'static str> {\n\n let root = root::get_root();\n\n let dir_ref = Arc::new(Mutex::new(TaskFs { })) as DirRef;\n\n root.lock().insert(FileOrDir::Dir(dir_ref.clone()))?;\n\n Ok(dir_ref)\n\n }\n\n\n\n fn get_self_pointer(&self) -> Option<DirRef> {\n", "file_path": "kernel/task_fs/src/lib.rs", "rank": 43, "score": 352315.04485890386 }, { "content": "/// Iterates over the contents of the given directory to find crates within it. \n\n/// \n\n/// Crates are discovered by looking for a directory that contains a `Cargo.toml` file. \n\n/// \n\n/// Returns the set of unique crate names. \n\nfn populate_crates_from_dir<P: AsRef<Path>>(dir_path: P) -> Result<HashSet<String>, io::Error> {\n\n let mut crates: HashSet<String> = HashSet::new();\n\n \n\n let dir_iter = WalkDir::new(dir_path)\n\n .into_iter()\n\n .filter_map(|res| res.ok());\n\n // .filter(|entry| entry.path().is_file() && entry.path().extension() == Some(object_file_extension))\n\n // .filter_map(|entry| entry.path().file_name()\n\n // .map(|fname| {\n\n // (\n\n // fname.to_string_lossy().to_string().into(), \n\n // entry.path().to_path_buf()\n\n // )\n\n // })\n\n // );\n\n\n\n for dir_entry in dir_iter {\n\n if dir_entry.file_type().is_file() && dir_entry.file_name() == \"Cargo.toml\" {\n\n // the parent of this dir_entry is a crate directory\n\n let parent_crate_dir = dir_entry.path().parent().ok_or_else(|| {\n", "file_path": "tools/copy_latest_crate_objects/src/main.rs", "rank": 44, "score": 350284.11635661166 }, { "content": "/// Changes the priority of the given task with the given priority level.\n\n/// Priority values must be between 40 (maximum priority) and 0 (minimum prriority).\n\n/// This function returns an error when a scheduler without priority is loaded. \n\npub fn set_priority(_task: &TaskRef, _priority: u8) -> Result<(), &'static str> {\n\n #[cfg(priority_scheduler)] {\n\n scheduler_priority::set_priority(_task, _priority)\n\n }\n\n #[cfg(not(priority_scheduler))] {\n\n Err(\"no scheduler that uses task priority is currently loaded\")\n\n }\n\n}\n\n\n", "file_path": "kernel/scheduler/src/lib.rs", "rank": 45, "score": 350062.594677154 }, { "content": "/// Outputs the given section's weak dependents, i.e.,\n\n/// the sections that depend on the given section.\n\n/// \n\n/// If there are multiple matches, this returns an Error containing \n\n/// all of the matching section names separated by the newline character `'\\n'`.\n\nfn sections_dependent_on_me(section_name: &str) -> Result<(), String> {\n\n let sec = find_section(section_name)?;\n\n println!(\"Sections that depend on {} (weak dependents):\", sec.name);\n\n for dependent_sec in sec.inner.read().sections_dependent_on_me.iter().filter_map(|weak_dep| weak_dep.section.upgrade()) {\n\n if verbose!() { \n\n println!(\" {} in {:?}\", dependent_sec.name, dependent_sec.parent_crate.upgrade());\n\n } else {\n\n println!(\" {}\", dependent_sec.name);\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n\n\n", "file_path": "applications/deps/src/lib.rs", "rank": 46, "score": 349886.6792293177 }, { "content": "/// Outputs the given section's strong dependencies, i.e.,\n\n/// the sections that the given section depends on.\n\n/// \n\n/// If there are multiple matches, this returns an Error containing \n\n/// all of the matching section names separated by the newline character `'\\n'`.\n\nfn sections_i_depend_on(section_name: &str) -> Result<(), String> {\n\n let sec = find_section(section_name)?;\n\n println!(\"Sections that {} depends on (strong dependencies):\", sec.name);\n\n for dependency_sec in sec.inner.read().sections_i_depend_on.iter().map(|dep| &dep.section) {\n\n if verbose!() { \n\n println!(\" {} in {:?}\", dependency_sec.name, dependency_sec.parent_crate.upgrade());\n\n } else {\n\n println!(\" {}\", dependency_sec.name);\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n\n\n", "file_path": "applications/deps/src/lib.rs", "rank": 47, "score": 349886.6792293177 }, { "content": "/// Create a new application `CrateNamespace` that uses the default application directory \n\n/// and is structured atop the given `recursive_namespace`. \n\n/// If no `recursive_namespace` is provided, the default initial kernel namespace will be used. \n\n/// \n\n/// # Return\n\n/// The returned `CrateNamespace` will itself be empty, having no crates and no symbols in its map.\n\n/// \n\npub fn create_application_namespace(recursive_namespace: Option<Arc<CrateNamespace>>) -> Result<Arc<CrateNamespace>, &'static str> {\n\n // (1) use the initial kernel CrateNamespace as the new app namespace's recursive namespace if none was provided.\n\n let recursive_namespace = recursive_namespace\n\n .or_else(|| get_initial_kernel_namespace().cloned())\n\n .ok_or(\"initial kernel CrateNamespace not yet initialized\")?;\n\n // (2) get the directory where the default app namespace should have been populated when mod_mgmt was inited.\n\n let default_app_namespace_name = CrateType::Application.default_namespace_name().to_string(); // this will be \"_applications\"\n\n let default_app_namespace_dir = get_namespaces_directory()\n\n .and_then(|ns_dir| ns_dir.lock().get_dir(&default_app_namespace_name))\n\n .ok_or(\"Couldn't find the directory for the default application CrateNamespace\")?;\n\n // (3) create the actual new application CrateNamespace.\n\n let new_app_namespace = Arc::new(CrateNamespace::new(\n\n default_app_namespace_name,\n\n NamespaceDir::new(default_app_namespace_dir),\n\n Some(recursive_namespace),\n\n ));\n\n\n\n Ok(new_app_namespace)\n\n}\n\n\n\n\n", "file_path": "kernel/mod_mgmt/src/lib.rs", "rank": 48, "score": 349229.9302905223 }, { "content": "/// Helper function to allocate memory at required address\n\n/// \n\n/// # Arguments\n\n/// * `mem_base`: starting physical address of the region that need to be allocated\n\n/// * `mem_size_in_bytes`: size of the region that needs to be allocated \n\npub fn allocate_memory(mem_base: PhysicalAddress, mem_size_in_bytes: usize) -> Result<MappedPages, &'static str> {\n\n // set up virtual pages and physical frames to be mapped\n\n let pages_nic = allocate_pages_by_bytes(mem_size_in_bytes)\n\n .ok_or(\"NicInit::mem_map(): couldn't allocate virtual page!\")?;\n\n let frames_nic = allocate_frames_by_bytes_at(mem_base, mem_size_in_bytes)\n\n .map_err(|_e| \"NicInit::mem_map(): couldn't allocate physical frames!\")?;\n\n\n\n // debug!(\"NicInit: memory base: {:#X}, memory size: {}\", mem_base, mem_size_in_bytes);\n\n\n\n let kernel_mmi_ref = get_kernel_mmi_ref().ok_or(\"NicInit::mem_map(): KERNEL_MMI was not yet initialized!\")?;\n\n let mut kernel_mmi = kernel_mmi_ref.lock();\n\n let nic_mapped_page = kernel_mmi.page_table.map_allocated_pages_to(pages_nic, frames_nic, NIC_MAPPING_FLAGS)?;\n\n\n\n Ok(nic_mapped_page)\n\n}\n\n\n", "file_path": "kernel/nic_initialization/src/lib.rs", "rank": 49, "score": 346913.2801913284 }, { "content": "/// Initially maps the base APIC MMIO register frames so that we can know which LAPIC (core) we are.\n\n/// This only does something for apic/xapic systems, it does nothing for x2apic systems, as required.\n\npub fn init(_page_table: &mut PageTable) -> Result<(), &'static str> {\n\n let x2 = has_x2apic();\n\n debug!(\"is x2apic? {}. IA32_APIC_BASE (phys addr): {:X?}\", \n\n x2, PhysicalAddress::new(rdmsr(IA32_APIC_BASE) as usize)\n\n );\n\n\n\n if !x2 {\n\n // Ensure the local apic is enabled in xapic mode, otherwise we'll get a General Protection fault\n\n unsafe { wrmsr(IA32_APIC_BASE, rdmsr(IA32_APIC_BASE) | IA32_APIC_XAPIC_ENABLE); }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\n\n", "file_path": "kernel/apic/src/lib.rs", "rank": 50, "score": 346884.4432456855 }, { "content": "/// Parses the system's ACPI tables \n\npub fn init(page_table: &mut PageTable) -> Result<(), &'static str> {\n\n // The first step is to search for the RSDP (Root System Descriptor Pointer),\n\n // which contains the physical address of the RSDT/XSDG (Root/Extended System Descriptor Table).\n\n let rsdp = Rsdp::get_rsdp(page_table)?;\n\n let rsdt_phys_addr = rsdp.sdt_address();\n\n debug!(\"RXSDT is located in Frame {:#X}\", rsdt_phys_addr);\n\n\n\n // Now, we get the actual RSDT/XSDT\n\n {\n\n let mut acpi_tables = ACPI_TABLES.lock();\n\n let (sdt_signature, sdt_total_length) = acpi_tables.map_new_table(rsdt_phys_addr, page_table)?;\n\n acpi_table_handler(&mut acpi_tables, sdt_signature, sdt_total_length, rsdt_phys_addr)?;\n\n }\n\n let sdt_addresses: Vec<PhysicalAddress> = {\n\n let acpi_tables = ACPI_TABLES.lock();\n\n let rxsdt = rsdt::RsdtXsdt::get(&acpi_tables).ok_or(\"couldn't get RSDT or XSDT from ACPI tables\")?;\n\n rxsdt.addresses().collect()\n\n };\n\n\n\n // The RSDT/XSDT tells us where all of the rest of the ACPI tables exist.\n", "file_path": "kernel/acpi/src/lib.rs", "rank": 51, "score": 346879.1935156811 }, { "content": "/// Spawns an idle task on the given `core` if specified, otherwise on the current core. \n\n/// Then, it adds adds the new idle task to that core's runqueue.\n\npub fn create_idle_task(core: Option<u8>) -> Result<TaskRef, &'static str> {\n\n let apic_id = core.unwrap_or_else(|| get_my_apic_id());\n\n debug!(\"Spawning a new idle task on core {}\", apic_id);\n\n\n\n new_task_builder(dummy_idle_task, apic_id)\n\n .name(format!(\"idle_task_core_{}\", apic_id))\n\n .idle(apic_id)\n\n .spawn_restartable()\n\n}\n\n\n\n/// Dummy `idle_task` to be used if original `idle_task` crashes.\n\n/// \n\n/// Note: the current spawn API does not support spawning a task with the return type `!`,\n\n/// so we use `()` here instead. \n", "file_path": "kernel/spawn/src/lib.rs", "rank": 52, "score": 345838.73017929215 }, { "content": "/// A convenience function to poll the given network interface (i.e., flush tx/rx).\n\n/// Returns true if any packets were sent or received through that interface on the given `sockets`.\n\npub fn poll_iface(iface: &NetworkInterfaceRef, sockets: &mut SocketSet, startup_time: u64) -> Result<bool, &'static str> {\n\n let timestamp: i64 = millis_since(startup_time)?\n\n .try_into()\n\n .map_err(|_e| \"millis_since() u64 timestamp was larger than i64\")?;\n\n // debug!(\"calling iface.poll() with timestamp: {:?}\", timestamp);\n\n let packets_were_sent_or_received = match iface.lock().poll(sockets, Instant::from_millis(timestamp)) {\n\n Ok(b) => b,\n\n Err(err) => {\n\n warn!(\"smoltcp_helper: poll error: {}\", err);\n\n false\n\n }\n\n };\n\n Ok(packets_were_sent_or_received)\n\n}\n", "file_path": "kernel/smoltcp_helper/src/lib.rs", "rank": 53, "score": 345757.92634408025 }, { "content": "/// Convenience function that removes the given `file` from its parent directory \n\n/// and inserts it into the given destination directory. \n\n/// \n\n/// # Return\n\n/// If the file ends up replacing a file/dir node in the `dest_dir`, this returns a tuple of:\n\n/// 1. The node that was in the `dest_dir` that got replaced by the given `file`,\n\n/// 2. The parent directory that originally contained the given `file`. This is useful for realizing a file \"swap\" operation.\n\n/// \n\n/// # Locking / Deadlock\n\n/// This function obtains the lock on both `file`, the `file`'s parent directory, and the `dest_dir`. \n\nfn move_file(file: &FileRef, dest_dir: &DirRef) -> Result<Option<(FileOrDir, DirRef)>, &'static str> {\n\n let parent = file.lock().get_parent_dir().ok_or(\"couldn't get file's parent directory\")?;\n\n // This section is redundent as it is checked before calling the function\n\n // if Arc::ptr_eq(&parent, dest_dir) {\n\n // #[cfg(not(downtime_eval))]\n\n // trace!(\"swap_crates::move_file(): skipping move between same directory {:?} for file {:?}\", \n\n // dest_dir.try_lock().map(|f| f.get_absolute_path()), file.try_lock().map(|f| f.get_absolute_path())\n\n // );\n\n // return Ok(None);\n\n // }\n\n\n\n // Perform the actual move operation.\n\n let mut removed_file = parent.lock().remove(&FileOrDir::File(Arc::clone(file))).ok_or(\"Couldn't remove file from its parent directory\")?;\n\n removed_file.set_parent_dir(Arc::downgrade(dest_dir));\n\n let res = dest_dir.lock().insert(removed_file.clone());\n\n \n\n // Log success or failure\n\n match res {\n\n Ok(replaced_file) => {\n\n #[cfg(not(any(loscd_eval, downtime_eval)))]\n", "file_path": "kernel/crate_swap/src/lib.rs", "rank": 54, "score": 345718.62232842157 }, { "content": "pub fn rmain(matches: &Matches, _opts: Options, address: IpAddress) -> Result<(), &'static str> {\n\n\n\n \n\n let mut count = 4;\n\n let mut interval = 1000;\n\n let mut timeout = 5000;\n\n let mut buffer_size = 40;\n\n let mut verbose = false;\n\n let did_work = true;\n\n\n\n\n\n if let Some(i) = matches.opt_default(\"c\", \"4\") {\n\n count = i.parse::<usize>().map_err(|_e| \"couldn't parse number of packets\")?;\n\n }\n\n if let Some(i) = matches.opt_default(\"i\", \"1000\") {\n\n interval = i.parse::<u64>().map_err(|_e| \"couldn't parse interval\")?;\n\n }\n\n if let Some(i) = matches.opt_default(\"t\", \"5000\") {\n\n timeout = i.parse::<u64>().map_err(|_e| \"couldn't parse timeout length\")?;\n\n }\n", "file_path": "applications/ping/src/lib.rs", "rank": 55, "score": 345240.7451861227 }, { "content": "pub fn main(_args: Vec<String>) -> isize {\n\n print_fault_log();\n\n 0\n\n}\n", "file_path": "applications/print_fault_log/src/lib.rs", "rank": 56, "score": 345088.5538016539 }, { "content": "fn num_deps_section(section_name: &str) -> Result<(), String> {\n\n let section = find_section(section_name)?;\n\n let (s, w, i) = section_dependency_count(&section);\n\n println!(\"Section {}'s Dependency Count:\\nStrong: {}\\nWeak: {}\\nIntrnl: {}\", section_name, s, w, i);\n\n Ok(())\n\n}\n\n\n", "file_path": "applications/deps/src/lib.rs", "rank": 57, "score": 344679.71595668735 }, { "content": "/// Wrapper function used to measure file read and file read with open. \n\n/// Accepts a bool argument. If true includes the latency to open a file\n\n/// If false only measure the time to read from file.\n\n/// Actual measuring is deferred to `do_fs_read_with_size` function\n\nfn do_fs_read(with_open: bool) -> Result<(), &'static str>{\n\n\tlet fsize_kb = 1024;\n\n\tprintlninfo!(\"File size : {} KB\", fsize_kb);\n\n\tprintlninfo!(\"Read buf size : {} KB\", READ_BUF_SIZE / 1024);\n\n\tprintlninfo!(\"========================================\");\n\n\n\n\tlet overhead_ct = hpet_timing_overhead()?;\n\n\n\n\tdo_fs_read_with_size(overhead_ct, fsize_kb, with_open)?;\n\n\tif with_open {\n\n\t\tprintlninfo!(\"This test is equivalent to `bw_file_rd open2close` in LMBench\");\n\n\t} else {\n\n\t\tprintlninfo!(\"This test is equivalent to `bw_file_rd io_only` in LMBench\");\n\n\t}\n\n\tOk(())\n\n}\n\n\n", "file_path": "applications/bm/src/lib.rs", "rank": 58, "score": 343959.0617462259 }, { "content": "fn kill_task(task_id: usize, reap: bool) -> Result<(), String> {\n\n if let Some(task_ref) = task::get_task(task_id) {\n\n if task_ref.kill(task::KillReason::Requested)\n\n .and_then(|_| runqueue::remove_task_from_all(&task_ref))\n\n .is_ok() \n\n {\n\n println!(\"Killed task {}\", &*task_ref);\n\n if reap {\n\n match task_ref.take_exit_value() {\n\n Some(exit_val) => { \n\n println!(\"Reaped task {}, got exit value {}\", task_id, debugit!(exit_val));\n\n Ok(())\n\n }\n\n _ => {\n\n Err(format!(\"Failed to reap task {}\", task_id))\n\n }\n\n }\n\n } \n\n else {\n\n // killed the task successfully, no reap request, so return success.\n", "file_path": "applications/kill/src/lib.rs", "rank": 59, "score": 342342.30175521155 }, { "content": "/// Allocates memory for the NIC registers\n\n/// \n\n/// # Arguments \n\n/// * `dev`: reference to pci device \n\n/// * `mem_base`: starting physical address of the device's memory mapped registers\n\npub fn allocate_device_register_memory(dev: &PciDevice, mem_base: PhysicalAddress) -> Result<MappedPages, &'static str> {\n\n //find out amount of space needed\n\n let mem_size_in_bytes = dev.determine_mem_size(0) as usize;\n\n\n\n allocate_memory(mem_base, mem_size_in_bytes)\n\n}\n\n\n", "file_path": "kernel/nic_initialization/src/lib.rs", "rank": 60, "score": 342225.3246529746 }, { "content": "fn run(filename: String) -> Result<(), String> {\n\n\n\n // Acquire key event queue.\n\n let key_event_queue = app_io::take_key_event_queue()?;\n\n let key_event_queue = (*key_event_queue).as_ref()\n\n .ok_or(\"failed to take key event reader\")?;\n\n\n\n // Read the whole file to a String.\n\n let content = get_content_string(filename)?;\n\n\n\n // Get it run.\n\n let map = parse_content(&content)?;\n\n\n\n Ok(event_handler_loop(&content, &map, key_event_queue)?)\n\n}\n\n\n", "file_path": "applications/less/src/lib.rs", "rank": 61, "score": 341494.9911143106 }, { "content": "/// Read the whole file to a String.\n\nfn get_content_string(file_path: String) -> Result<String, String> {\n\n let taskref = match task::get_my_current_task() {\n\n Some(t) => t,\n\n None => {\n\n return Err(\"failed to get current task\".to_string());\n\n }\n\n };\n\n\n\n // grabs the current working directory pointer; this is scoped so that we drop the lock on the task as soon as we get the working directory pointer\n\n let curr_wr = Arc::clone(&taskref.get_env().lock().working_dir);\n\n let path = Path::new(file_path);\n\n \n\n // navigate to the filepath specified by first argument\n\n match path.get(&curr_wr) {\n\n Some(file_dir_enum) => { \n\n match file_dir_enum {\n\n FileOrDir::Dir(directory) => {\n\n Err(format!(\"{:?} is a directory, cannot 'less' non-files.\", directory.lock().get_name()))\n\n }\n\n FileOrDir::File(file) => {\n", "file_path": "applications/less/src/lib.rs", "rank": 62, "score": 341229.3003963408 }, { "content": "/// Convenience function for converting a byte stream\n\n/// that is delimited by newlines into a list of Strings.\n\npub fn as_lines(bytes: &[u8]) -> Result<Vec<String>, &'static str> {\n\n str::from_utf8(bytes)\n\n .map_err(|_e| \"couldn't convert file into a UTF8 string\")\n\n .map(|files| files.lines().map(|s| String::from(s)).collect())\n\n}\n\n\n\n\n\n/// A representation of an diff file used to define an evolutionary crate swapping update.\n\npub struct Diff {\n\n /// A list of tuples in which the first element is the old crate and the second element is the new crate.\n\n /// If the first element is the empty string, the second element is a new addition (replacing nothing),\n\n /// and if the second element is the empty string, the first element is to be removed without replacement.\n\n pub pairs: Vec<(String, String)>,\n\n /// The list of state transfer functions which should be applied at the end of a crate swapping operation.\n\n pub state_transfer_functions: Vec<String>,\n\n}\n\n\n\n\n", "file_path": "kernel/ota_update_client/src/lib.rs", "rank": 64, "score": 335697.1878498163 }, { "content": "/// Measures the overhead of using the hpet timer. \n\n/// Calls `timing_overhead_inner` multiple times and averages the value. \n\n/// Overhead is a count value. It is not time. \n\npub fn hpet_timing_overhead() -> Result<u64, &'static str> {\n\n\tconst TRIES: u64 = 10;\n\n\tlet mut tries: u64 = 0;\n\n\tlet mut max: u64 = core::u64::MIN;\n\n\tlet mut min: u64 = core::u64::MAX;\n\n\n\n\tfor _ in 0..TRIES {\n\n\t\tlet overhead = hpet_timing_overhead_inner()?;\n\n\t\ttries += overhead;\n\n\t\tif overhead > max {max = overhead;}\n\n\t\tif overhead < min {min = overhead;}\n\n\t}\n\n\n\n\tlet overhead = tries / TRIES as u64;\n\n\tlet err = (overhead * 10 + overhead * THRESHOLD_ERROR_RATIO) / 10;\n\n\tif \tmax - overhead > err || overhead - min > err {\n\n\t\twarn!(\"hpet_timing_overhead diff is too big: {} ({} - {}) ctr\", max-min, max, min);\n\n\t}\n\n\tinfo!(\"HPET timing overhead is {} ticks\", overhead);\n\n\tOk(overhead)\n\n}\n\n\n", "file_path": "kernel/libtest/src/lib.rs", "rank": 65, "score": 335566.3317660459 }, { "content": "/// Returns the frequency of the TSC for the system, \n\n/// currently measured using the PIT clock for calibration.\n\npub fn get_tsc_frequency() -> Result<u128, &'static str> {\n\n // this is a soft state, so it's not a form of state spill\n\n static TSC_FREQUENCY: AtomicUsize = AtomicUsize::new(0);\n\n\n\n let freq = TSC_FREQUENCY.load(Ordering::SeqCst) as u128;\n\n \n\n if freq != 0 {\n\n Ok(freq)\n\n }\n\n else {\n\n // a freq of zero means it hasn't yet been initialized.\n\n let start = tsc_ticks();\n\n // wait 10000 us (10 ms)\n\n pit_clock::pit_wait(10000)?;\n\n let end = tsc_ticks(); \n\n\n\n let diff = end.sub(&start).ok_or(\"couldn't subtract end-start TSC tick values\")?;\n\n let tsc_freq = diff.into() * 100; // multiplied by 100 because we measured a 10ms interval\n\n info!(\"TSC frequency calculated by PIT is: {}\", tsc_freq);\n\n TSC_FREQUENCY.store(tsc_freq as usize, Ordering::Release);\n\n Ok(tsc_freq)\n\n }\n\n}\n", "file_path": "kernel/tsc/src/lib.rs", "rank": 66, "score": 335512.40827376756 }, { "content": "/// returns Ok(()) if everything was handled properly.\n\n/// Otherwise, returns an error string.\n\npub fn handle_keyboard_input(scan_code: u8, extended: bool) -> Result<(), &'static str> {\n\n // SAFE: no real race conditions with keyboard presses\n\n let modifiers = unsafe { &mut KBD_MODIFIERS };\n\n // debug!(\"KBD_MODIFIERS before {}: {:?}\", scan_code, modifiers);\n\n\n\n // first, update the modifier keys\n\n match scan_code {\n\n x if x == Keycode::Control as u8 => { \n\n modifiers.insert(if extended { KeyboardModifiers::CONTROL_RIGHT } else { KeyboardModifiers::CONTROL_LEFT});\n\n }\n\n x if x == Keycode::Alt as u8 => { modifiers.insert(KeyboardModifiers::ALT); }\n\n x if x == Keycode::LeftShift as u8 => { modifiers.insert(KeyboardModifiers::SHIFT_LEFT); }\n\n x if x == Keycode::RightShift as u8 => { modifiers.insert(KeyboardModifiers::SHIFT_RIGHT); }\n\n x if x == Keycode::SuperKeyLeft as u8 => { modifiers.insert(KeyboardModifiers::SUPER_KEY_LEFT); }\n\n x if x == Keycode::SuperKeyRight as u8 => { modifiers.insert(KeyboardModifiers::SUPER_KEY_RIGHT); }\n\n\n\n x if x == Keycode::Control as u8 + KEY_RELEASED_OFFSET => {\n\n modifiers.remove(if extended { KeyboardModifiers::CONTROL_RIGHT } else { KeyboardModifiers::CONTROL_LEFT});\n\n }\n\n x if x == Keycode::Alt as u8 + KEY_RELEASED_OFFSET => { modifiers.remove(KeyboardModifiers::ALT); }\n", "file_path": "kernel/keyboard/src/lib.rs", "rank": 67, "score": 331859.0676609294 }, { "content": "/// Crate names must be only alphanumeric characters, an underscore, or a dash.\n\n/// \n\n/// See: <https://www.reddit.com/r/rust/comments/4rlom7/what_characters_are_allowed_in_a_crate_name/>\n\npub fn is_valid_crate_name_char(c: char) -> bool {\n\n char::is_alphanumeric(c) || \n\n c == '_' || \n\n c == '-'\n\n}\n\n\n", "file_path": "kernel/crate_name_utils/src/lib.rs", "rank": 68, "score": 330602.76959084754 }, { "content": "/// Returns a reference to the current task.\n\npub fn get_my_current_task() -> Option<&'static TaskRef> {\n\n get_task_local_data().map(|tld| &tld.current_taskref)\n\n}\n\n\n", "file_path": "kernel/task/src/lib.rs", "rank": 69, "score": 328585.5125592143 }, { "content": "/// Parses a series of diff lines into a representation of an update diff.\n\n/// \n\n/// # Arguments\n\n/// * `diffs`: a list of lines, in which each line is a diff entry.\n\n/// \n\n/// # Example diff entry formats\n\n/// ```\n\n/// a#ps.o -> a#ps.o\n\n/// k#runqueue-d04869f0baadb1bd.o -> k#runqueue-d04869f0baadb1bd.o\n\n/// - k#scheduler-7f6134ffbb934a27.o\n\n/// + k#spawn-f1c87a8fc4e03893.o\n\n/// ```\n\npub fn parse_diff_lines(diffs: &Vec<String>) -> Result<Diff, &'static str> {\n\n let mut pairs: Vec<(String, String)> = Vec::with_capacity(diffs.len());\n\n let mut state_transfer_functions: Vec<String> = Vec::new();\n\n for diff in diffs {\n\n // addition of new crate\n\n if diff.starts_with(\"+\") {\n\n pairs.push((\n\n String::new(), \n\n diff.get(1..).ok_or(\"error parsing (+) diff line\")?.trim().to_string(),\n\n ));\n\n } \n\n // removal of old crate\n\n else if diff.starts_with(\"-\") {\n\n pairs.push((\n\n diff.get(1..).ok_or(\"error parsing (-) diff line\")?.trim().to_string(), \n\n String::new()\n\n ));\n\n }\n\n // replacement of old crate with new crate\n\n else if let Some((old, new)) = diff.split(\"->\").collect_tuple() {\n", "file_path": "kernel/ota_update_client/src/lib.rs", "rank": 70, "score": 327292.949210211 }, { "content": "/// Adds the (child application's task ID, parent terminal print_producer) key-val pair to the map \n\n/// Simulates connecting an output stream to the application\n\npub fn add_child(child_task_id: usize, print_producer: DFQueueProducer<Event>) -> Result<(), &'static str> {\n\n TERMINAL_PRINT_PRODUCERS.lock().insert(child_task_id, print_producer);\n\n Ok(())\n\n}\n\n\n", "file_path": "kernel/terminal_print/src/lib.rs", "rank": 71, "score": 326550.2272909797 }, { "content": "fn run() -> Result<(), &'static str> {\n\n let stdout = app_io::stdout()?;\n\n let mut stdout_locked = stdout.lock();\n\n let queue = app_io::take_key_event_queue()?;\n\n let queue = (*queue).as_ref().ok_or(\"failed to get key event reader\")?;\n\n let ack = \"event received\\n\".as_bytes();\n\n\n\n stdout_locked.write_all(\n\n format!(\"{}\\n{}\\n{}\\n\\n\",\n\n \"Acknowledge upon receiving a keyboard event.\",\n\n \"Note that one keyboard strike contains at least one pressing event and one releasing event.\",\n\n \"Press `q` to exit.\"\n\n ).as_bytes()\n\n )\n\n .or(Err(\"failed to perform write_all\"))?;\n\n\n\n // Print an acknowledge message to the screen.\n\n // Note that one keyboard strike contains at least two events:\n\n // one pressing event and one releasing event.\n\n loop {\n\n if let Some(key_event) = queue.read_one() {\n\n stdout_locked.write_all(&ack).or(Err(\"failed to perform write_all\"))?;\n\n if key_event.keycode == Keycode::Q { break; }\n\n }\n\n scheduler::schedule();\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "applications/keyboard_echo/src/lib.rs", "rank": 72, "score": 323573.5601910429 }, { "content": "fn run() -> Result<(), &'static str> {\n\n let mut stdin = app_io::stdin()?;\n\n let stdout = app_io::stdout()?;\n\n let mut stdout_locked = stdout.lock();\n\n\n\n stdout_locked.write_all(\n\n format!(\"{}\\n{}\\n\\n\",\n\n \"Echo upon receiving a new input line.\",\n\n \"Press `ctrl-D` to exit cleanly.\"\n\n ).as_bytes()\n\n )\n\n .or(Err(\"failed to perform write_all\"))?;\n\n\n\n let mut buf = String::new();\n\n\n\n // Read a line and print it back.\n\n loop {\n\n let cnt = stdin.read_line(&mut buf).or(Err(\"failed to perform read_line\"))?;\n\n if cnt == 0 { break; }\n\n stdout_locked.write_all(buf.as_bytes())\n\n .or(Err(\"faileld to perform write_all\"))?;\n\n buf.clear();\n\n }\n\n Ok(())\n\n}\n", "file_path": "applications/input_echo/src/lib.rs", "rank": 73, "score": 323573.56019104295 }, { "content": "/// Returns the first network interface available in the system.\n\npub fn get_default_iface() -> Result<NetworkInterfaceRef, &'static str> {\n\n NETWORK_INTERFACES.lock()\n\n .iter()\n\n .next()\n\n .cloned()\n\n .ok_or_else(|| \"no network interfaces available\")\n\n}\n\n\n", "file_path": "kernel/smoltcp_helper/src/lib.rs", "rank": 74, "score": 321388.0530333385 }, { "content": "/// Finds the addresses in memory of the main kernel sections, as specified by the given boot information. \n\n/// \n\n/// Returns the following tuple, if successful:\n\n/// * The combined size and address bounds of key sections, e.g., .text, .rodata, .data.\n\n/// Each of the these section bounds is aggregated to cover the bounds and sizes of *all* sections \n\n/// that share the same page table mapping flags and can thus be logically combined.\n\n/// * The list of all individual sections found. \n\npub fn find_section_memory_bounds(boot_info: &BootInformation) -> Result<(AggregatedSectionMemoryBounds, [Option<SectionMemoryBounds>; 32]), &'static str> {\n\n let elf_sections_tag = boot_info.elf_sections_tag().ok_or(\"no Elf sections tag present!\")?;\n\n\n\n let mut index = 0;\n\n let mut text_start: Option<(VirtualAddress, PhysicalAddress)> = None;\n\n let mut text_end: Option<(VirtualAddress, PhysicalAddress)> = None;\n\n let mut rodata_start: Option<(VirtualAddress, PhysicalAddress)> = None;\n\n let mut rodata_end: Option<(VirtualAddress, PhysicalAddress)> = None;\n\n let mut data_start: Option<(VirtualAddress, PhysicalAddress)> = None;\n\n let mut data_end: Option<(VirtualAddress, PhysicalAddress)> = None;\n\n let mut stack_start: Option<(VirtualAddress, PhysicalAddress)> = None;\n\n let mut stack_end: Option<(VirtualAddress, PhysicalAddress)> = None;\n\n let mut page_table_start: Option<(VirtualAddress, PhysicalAddress)> = None;\n\n let mut page_table_end: Option<(VirtualAddress, PhysicalAddress)> = None;\n\n\n\n let mut text_flags: Option<EntryFlags> = None;\n\n let mut rodata_flags: Option<EntryFlags> = None;\n\n let mut data_flags: Option<EntryFlags> = None;\n\n\n\n let mut sections_memory_bounds: [Option<SectionMemoryBounds>; 32] = Default::default();\n", "file_path": "kernel/memory_x86_64/src/lib.rs", "rank": 75, "score": 320351.9671537116 }, { "content": "/// Sets the kill handler function for the current `Task`\n\npub fn set_my_kill_handler(handler: KillHandler) -> Result<(), &'static str> {\n\n get_my_current_task()\n\n .ok_or(\"couldn't get_my_current_task\")\n\n .map(|taskref| taskref.set_kill_handler(handler))\n\n}\n\n\n\n\n\n/// The list of possible reasons that a given `Task` was killed prematurely.\n\n#[derive(Debug)]\n\npub enum KillReason {\n\n /// The user or another task requested that this `Task` be killed. \n\n /// For example, the user pressed `Ctrl + C` on the shell window that started a `Task`.\n\n Requested,\n\n /// A Rust-level panic occurred while running this `Task`.\n\n Panic(PanicInfoOwned),\n\n /// A non-language-level problem, such as a Page Fault or some other machine exception.\n\n /// The number of the exception is included, e.g., 15 (0xE) for a Page Fault.\n\n Exception(u8),\n\n}\n\nimpl fmt::Display for KillReason {\n", "file_path": "kernel/task/src/lib.rs", "rank": 76, "score": 319958.4331707658 }, { "content": "/// This function saves the current CPU register values onto the stack (to preserve them)\n\n/// and then invokes the given closure with those registers as the argument.\n\n/// \n\n/// In general, this is useful for jumpstarting the unwinding procedure,\n\n/// since we have to start from the current call frame and work backwards up the call stack \n\n/// while applying the rules for register value changes in each call frame\n\n/// in order to arrive at the proper register values for a prior call frame.\n\npub fn invoke_with_current_registers<F>(f: F) -> Result<(), &'static str> \n\n where F: FuncWithRegisters \n\n{\n\n let f: RefFuncWithRegisters = &f;\n\n let result = unsafe { \n\n let res_ptr = unwind_trampoline(&f);\n\n let res_boxed = Box::from_raw(res_ptr);\n\n *res_boxed\n\n };\n\n return result;\n\n // this is the end of the code in this function, the following is just inner functions.\n\n\n\n\n\n /// This is an internal assembly function used by `invoke_with_current_registers()` \n\n /// that saves the current register values by pushing them onto the stack\n\n /// before invoking the function \"unwind_recorder\" with those register values as the only argument.\n\n /// This is needed because the unwind info tables describe register values as operations (offsets/addends)\n\n /// that are relative to the current register values, so we must have those current values as a starting point.\n\n /// \n\n /// The argument is a pointer to a function reference, so effectively a pointer to a pointer. \n", "file_path": "kernel/unwind/src/lib.rs", "rank": 77, "score": 319590.59352102946 }, { "content": "fn run() -> Result<(), &'static str> {\n\n app_io::request_stdin_instant_flush()?;\n\n let stdin = app_io::stdin()?;\n\n let stdout = app_io::stdout()?;\n\n let mut buf = [0u8];\n\n\n\n // Can lock them at the same time. Won't run into deadlock.\n\n let mut stdin_locked = stdin.lock();\n\n let mut stdout_locked = stdout.lock();\n\n\n\n stdout_locked.write_all(\n\n format!(\"{}\\n{}\\n\\n\",\n\n \"Echo upon receiving a character input.\",\n\n \"Press `ctrl-D` to exit cleanly.\"\n\n ).as_bytes()\n\n )\n\n .or(Err(\"failed to perform write_all\"))?;\n\n\n\n loop {\n\n let byte_num = stdin_locked.read(&mut buf).or(Err(\"failed to invoke read\"))?;\n\n if byte_num == 0 { break; }\n\n stdout_locked.write_all(&buf).or(Err(\"failed to invoke write_all\"))?;\n\n }\n\n stdout_locked.write_all(&['\\n' as u8]).or(Err(\"failed to invoke write_all\"))?;\n\n Ok(())\n\n}\n", "file_path": "applications/immediate_input_echo/src/lib.rs", "rank": 78, "score": 318993.6638906435 }, { "content": "/// Downloads all of the new or changed crates from the `diff` file of the \n\nfn download(remote_endpoint: IpEndpoint, update_build: &str, crate_list: Option<&[String]>) -> Result<(), String> {\n\n let iface = get_default_iface()?;\n\n println!(\"Downloading crates...\");\n\n let crate_list = if crate_list == Some(&[]) { None } else { crate_list };\n\n\n\n let mut diff_file_lines: Option<Vec<String>> = None;\n\n\n\n let crates = if let Some(crate_list) = crate_list {\n\n let crate_set = crate_list.iter().cloned().collect::<BTreeSet<String>>();\n\n ota_update_client::download_crates(&iface, remote_endpoint, update_build, crate_set).map_err(|e| e.to_string())?\n\n } else {\n\n let diff_lines = ota_update_client::download_diff(&iface, remote_endpoint, update_build)\n\n .map_err(|e| format!(\"failed to download diff file for {}, error: {}\", update_build, e))?;\n\n let diff = ota_update_client::parse_diff_lines(&diff_lines).map_err(|e| e.to_string())?;\n\n\n\n // download all of the new crates\n\n let new_crates_to_download: BTreeSet<String> = diff.pairs.iter().map(|(_old, new)| new.clone()).collect();\n\n let crates = ota_update_client::download_crates(&iface, remote_endpoint, update_build, new_crates_to_download).map_err(|e| e.to_string())?;\n\n diff_file_lines = Some(diff_lines);\n\n crates\n", "file_path": "applications/upd/src/lib.rs", "rank": 79, "score": 316468.89862397197 }, { "content": "/// Convenience function for writing a simple string to the logger.\n\n///\n\n/// If the logger has not yet been initialized, no log messages will be emitted.\n\n/// and an `Error` will be returned.\n\npub fn write_str(s: &str) -> fmt::Result {\n\n crate::write_fmt(format_args!(\"{}\", s))\n\n}\n\n\n\n\n\n/// ANSI style codes for basic colors.\n", "file_path": "kernel/logger/src/lib.rs", "rank": 80, "score": 315215.8892302605 }, { "content": "fn crate_name_without_hash<'s>(name: &'s str) -> &'s str {\n\n name.split(\"-\")\n\n .next()\n\n .unwrap_or_else(|| name)\n\n}\n\n\n\n\n", "file_path": "tools/diff_crates/src/main.rs", "rank": 82, "score": 310764.67697308 }, { "content": "/// Initialization function that enables the PMU if one is available.\n\n/// We initialize the 3 fixed PMCs and general purpose PMCs. Calling this initialization function again\n\n/// on a core that has already been initialized will do nothing.\n\n/// \n\n/// Currently we support a maximum core ID of 255, and up to 8 general purpose counters per core. \n\n/// A core ID greater than 255 is not supported in Theseus in general since the ID has to fit within a u8.\n\n/// \n\n/// If the core ID limit is changed and we need to update the PMU data structures to support more cores then: \n\n/// - Increase WORDS_IN_BITMAP and CORES_SUPPORTED_BY_PMU as required. For example, the cores supported is 256 so there are 4 64-bit words in the bitmap, one bit per core. \n\n/// - Add additional AtomicU64 variables to the initialization of the CORES_SAMPLING and RESULTS_READY bitmaps. \n\n/// \n\n/// If the general purpose PMC limit is reached then: \n\n/// - Update PMCS_SUPPORTED_BY_PMU to the new PMC limit.\n\n/// - Change the element type in the PMCS_AVAILABLE vector to be larger than AtomicU8 so that there is one bit per counter.\n\n/// - Update INIT_PMCS_AVAILABLE to the new maximum value for the per core bitmap.\n\n/// \n\n/// # Warning\n\n/// This function should only be called after all the cores have been booted up.\n\npub fn init() -> Result<(), &'static str> {\n\n let mut cores_initialized = CORES_INITIALIZED.lock();\n\n let core_id = apic::get_my_apic_id();\n\n\n\n if cores_initialized.contains(&core_id) {\n\n warn!(\"PMU has already been intitialized on core {}\", core_id);\n\n return Ok(());\n\n } \n\n else {\n\n\n\n if *PMU_VERSION >= MIN_PMU_VERSION {\n\n \n\n if greater_core_id_than_expected()? {\n\n return Err(\"pmu_x86: There are larger core ids in this machine than can be handled by the existing structures which store information about the PMU\");\n\n }\n\n\n\n if more_pmcs_than_expected(*NUM_PMC)? {\n\n return Err(\"pmu_x86: There are more general purpose PMCs in this machine than can be handled by the existing structures which store information about the PMU\");\n\n }\n\n\n", "file_path": "kernel/pmu_x86/src/lib.rs", "rank": 83, "score": 308215.64918284403 }, { "content": "/// reset the mouse\n\npub fn reset_mouse() -> Result<(), &'static str> {\n\n if let Err(_e) = command_to_mouse(0xFF) {\n\n Err(\"reset mouse failled please try again\")\n\n } else {\n\n for _x in 0..14 {\n\n let more_bytes = ps2_read_data();\n\n if more_bytes == 0xAA {\n\n // command reset mouse succeeded\n\n return Ok(());\n\n }\n\n }\n\n warn!(\"disable streaming failed\");\n\n Err(\"fail to command reset mouse fail!!!\")\n\n }\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 84, "score": 308198.372075957 }, { "content": "pub fn do_threadtest() -> Result<(), &'static str> {\n\n\n\n let nthreads = NTHREADS.load(Ordering::SeqCst);\n\n let mut tries = Vec::with_capacity(TRIES as usize);\n\n\n\n let hpet_overhead = hpet_timing_overhead()?;\n\n let hpet = get_hpet().ok_or(\"couldn't get HPET timer\")?;\n\n\n\n println!(\"Running threadtest for {} threads, {} iterations, {} total objects allocated every iteration by all threads, {} obj size ...\", \n\n nthreads, NITERATIONS.load(Ordering::SeqCst), NOBJECTS.load(Ordering::SeqCst), OBJSIZE.load(Ordering::SeqCst));\n\n\n\n #[cfg(direct_access_to_multiple_heaps)]\n\n {\n\n let overhead = overhead_of_accessing_multiple_heaps()?;\n\n println!(\"Overhead of accessing multiple heaps is: {} ticks, {} ns\", overhead, hpet_2_us(overhead));\n\n }\n\n\n\n for try in 0..TRIES {\n\n let mut threads = Vec::with_capacity(nthreads);\n\n\n", "file_path": "applications/heap_eval/src/threadtest.rs", "rank": 85, "score": 308198.372075957 }, { "content": "/// resend the most recent packet again\n\npub fn mouse_resend() -> Result<(), &'static str> {\n\n if let Err(_e) = command_to_mouse(0xFE) {\n\n Err(\"mouse resend request failled, please request again\")\n\n } else {\n\n // mouse resend request succeeded\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "kernel/ps2/src/lib.rs", "rank": 86, "score": 308198.372075957 }, { "content": "pub fn do_shbench() -> Result<(), &'static str> {\n\n\n\n let nthreads = NTHREADS.load(Ordering::SeqCst);\n\n let niterations = NITERATIONS.load(Ordering::SeqCst);\n\n let mut tries = Vec::with_capacity(TRIES as usize);\n\n\n\n let hpet_overhead = hpet_timing_overhead()?;\n\n let hpet = get_hpet().ok_or(\"couldn't get HPET timer\")?;\n\n\n\n println!(\"Running shbench for {} threads, {} total iterations, {} iterations per thread, {} total objects allocated by all threads, {} max block size, {} min block size ...\", \n\n nthreads, niterations, niterations/nthreads, ALLOCATIONS_PER_ITER * niterations, MAX_BLOCK_SIZE.load(Ordering::SeqCst), MIN_BLOCK_SIZE.load(Ordering::SeqCst));\n\n \n\n #[cfg(direct_access_to_multiple_heaps)]\n\n {\n\n let overhead = overhead_of_accessing_multiple_heaps()?;\n\n println!(\"Overhead of accessing multiple heaps is: {} ticks, {} ns\", overhead, hpet_2_us(overhead));\n\n }\n\n\n\n for try in 0..TRIES {\n\n\n", "file_path": "applications/heap_eval/src/shbench.rs", "rank": 87, "score": 308198.372075957 }, { "content": "/// Sets the current core's TSS privilege stack 0 (RSP0) entry, which points to the stack that \n\n/// the x86_64 hardware automatically switches to when transitioning from Ring 3 -> Ring 0.\n\n/// Should be set to an address within the current userspace task's kernel stack.\n\n/// WARNING: If set incorrectly, the OS will crash upon an interrupt from userspace into kernel space!!\n\npub fn tss_set_rsp0(new_privilege_stack_top: VirtualAddress) -> Result<(), &'static str> {\n\n let my_apic_id = apic::get_my_apic_id();\n\n let mut tss_entry = TSS.get(&my_apic_id).ok_or_else(|| {\n\n error!(\"tss_set_rsp0(): couldn't find TSS for apic {}\", my_apic_id);\n\n \"No TSS for the current core's apid id\" \n\n })?.lock();\n\n tss_entry.privilege_stack_table[0] = x86_64::VirtualAddress(new_privilege_stack_top.value());\n\n // trace!(\"tss_set_rsp0: new TSS {:?}\", tss_entry);\n\n Ok(())\n\n}\n\n\n\n\n", "file_path": "kernel/tss/src/lib.rs", "rank": 88, "score": 307269.11542648793 }, { "content": "/// Initialize the page allocator.\n\n///\n\n/// # Arguments\n\n/// * `end_vaddr_of_low_designated_region`: the `VirtualAddress` that marks the end of the \n\n/// lower designated region, which should be the ending address of the initial kernel image\n\n/// (a lower-half identity address).\n\n/// \n\n/// The page allocator will only allocate addresses lower than `end_vaddr_of_low_designated_region`\n\n/// if specifically requested.\n\n/// General allocation requests for any virtual address will not use any address lower than that,\n\n/// unless the rest of the entire virtual address space is already in use.\n\n///\n\npub fn init(end_vaddr_of_low_designated_region: VirtualAddress) -> Result<(), &'static str> {\n\n\tassert!(end_vaddr_of_low_designated_region < DESIGNATED_PAGES_HIGH_START.start_address());\n\n\tlet designated_low_end = DESIGNATED_PAGES_LOW_END.call_once(|| Page::containing_address(end_vaddr_of_low_designated_region));\n\n\tlet designated_low_end = *designated_low_end;\n\n\n\n\tlet initial_free_chunks = [\n\n\t\t// The first region contains all pages *below* the beginning of the 510th entry of P4. \n\n\t\t// We split it up into three chunks just for ease, since it overlaps the designated regions.\n\n\t\tSome(Chunk { \n\n\t\t\tpages: PageRange::new(\n\n\t\t\t\tPage::containing_address(VirtualAddress::zero()),\n\n\t\t\t\tdesignated_low_end,\n\n\t\t\t)\n\n\t\t}),\n\n\t\tSome(Chunk { \n\n\t\t\tpages: PageRange::new(\n\n\t\t\t\tdesignated_low_end + 1,\n\n\t\t\t\tDESIGNATED_PAGES_HIGH_START - 1,\n\n\t\t\t)\n\n\t\t}),\n", "file_path": "kernel/page_allocator/src/lib.rs", "rank": 89, "score": 307106.3441707317 }, { "content": "/// Measures the round trip time to send a 1-byte message on a rendezvous channel. \n\n/// Calls `do_ipc_rendezvous_inner` multiple times to perform the actual operation\n\nfn do_ipc_rendezvous(pinned: bool, cycles: bool) -> Result<(), &'static str> {\n\n\tlet child_core = if pinned {\n\n\t\tSome(CPU_ID!())\n\n\t} else {\n\n\t\tNone\n\n\t};\n\n\n\n\tlet mut tries: u64 = 0;\n\n\tlet mut max: u64 = core::u64::MIN;\n\n\tlet mut min: u64 = core::u64::MAX;\n\n\tlet mut vec = Vec::with_capacity(TRIES);\n\n\n\n\tprint_header(TRIES, ITERATIONS);\n\n\n\n\tfor i in 0..TRIES {\n\n\t\tlet lat = if cycles {\n\n\t\t\tdo_ipc_rendezvous_inner_cycles(i+1, TRIES, child_core)?\t\n\n\t\t} else {\n\n\t\t\tdo_ipc_rendezvous_inner(i+1, TRIES, child_core)?\t\n\n\t\t};\n", "file_path": "applications/bm/src/lib.rs", "rank": 90, "score": 306746.7623434306 }, { "content": "/// Measures the round trip time to send a 1-byte message on a simple channel. \n\n/// Calls `do_ipc_simple_inner` multiple times to perform the actual operation\n\nfn do_ipc_simple(pinned: bool, cycles: bool) -> Result<(), &'static str> {\n\n\tlet child_core = if pinned {\n\n\t\tSome(CPU_ID!())\n\n\t} else {\n\n\t\tNone\n\n\t};\n\n\n\n\tlet mut tries: u64 = 0;\n\n\tlet mut max: u64 = core::u64::MIN;\n\n\tlet mut min: u64 = core::u64::MAX;\n\n\tlet mut vec = Vec::with_capacity(TRIES);\n\n\t\n\n\tprint_header(TRIES, ITERATIONS);\n\n\n\n\tfor i in 0..TRIES {\n\n\t\tlet lat = if cycles {\n\n\t\t\tdo_ipc_simple_inner_cycles(i+1, TRIES, child_core)?\n\n\t\t} else {\n\n\t\t\tdo_ipc_simple_inner(i+1, TRIES, child_core)?\n\n\t\t};\n", "file_path": "applications/bm/src/lib.rs", "rank": 91, "score": 306746.7623434306 }, { "content": "/// Allocates the given number of frames starting at (inclusive of) the frame containing the given `PhysicalAddress`.\n\n/// \n\n/// See [`allocate_frames_deferred()`](fn.allocate_frames_deferred.html) for more details. \n\npub fn allocate_frames_at(paddr: PhysicalAddress, num_frames: usize) -> Result<AllocatedFrames, &'static str> {\n\n allocate_frames_deferred(Some(paddr), num_frames)\n\n .map(|(af, _action)| af)\n\n}\n\n\n\n\n\n/// Converts the frame allocator from using static memory (a primitive array) to dynamically-allocated memory.\n\n/// \n\n/// Call this function once heap allocation is available. \n\n/// Calling this multiple times is unnecessary but harmless, as it will do nothing after the first invocation.\n", "file_path": "kernel/frame_allocator/src/lib.rs", "rank": 92, "score": 306565.7796150503 }, { "content": "/// Allocates the given number of pages starting at (inclusive of) the page containing the given `VirtualAddress`.\n\n/// \n\n/// See [`allocate_pages_deferred()`](fn.allocate_pages_deferred.html) for more details. \n\npub fn allocate_pages_at(vaddr: VirtualAddress, num_pages: usize) -> Result<AllocatedPages, &'static str> {\n\n\tallocate_pages_deferred(Some(vaddr), num_pages)\n\n\t\t.map(|(ap, _action)| ap)\n\n}\n\n\n\n\n\n/// Converts the page allocator from using static memory (a primitive array) to dynamically-allocated memory.\n\n/// \n\n/// Call this function once heap allocation is available. \n\n/// Calling this multiple times is unnecessary but harmless, as it will do nothing after the first invocation.\n", "file_path": "kernel/page_allocator/src/lib.rs", "rank": 93, "score": 306565.7796150503 }, { "content": "/// Returns the priority of the given task.\n\npub fn get_priority(task: &TaskRef) -> Option<u8> {\n\n RunQueue::get_priority(task)\n\n}\n\n\n", "file_path": "kernel/scheduler_priority/src/lib.rs", "rank": 94, "score": 306287.72402710957 }, { "content": "/// Clears the cache of unloaded (swapped-out) crates saved from previous crate swapping operations. \n\npub fn clear_unloaded_crate_cache() {\n\n UNLOADED_CRATE_CACHE.lock().clear();\n\n}\n\n\n\n\n\n/// A state transfer function is an arbitrary function called when swapping crates. \n\n/// \n\n/// See the `swap_crates()` function for more details. \n\npub type StateTransferFunction = fn(&Arc<CrateNamespace>, &CrateNamespace) -> Result<(), &'static str>;\n\n\n\n\n", "file_path": "kernel/crate_swap/src/lib.rs", "rank": 95, "score": 305953.26402118965 }, { "content": "/// Frees all counters and make them available to be used.\n\n/// Essentially sets the PMU to its initial state.\n\npub fn reset_pmu() -> Result<(), &'static str> {\n\n for pmc in get_pmcs_available()?.iter() {\n\n pmc.store(INIT_VAL_PMCS_AVAILABLE, Ordering::SeqCst);\n\n }\n\n for core in CORES_SAMPLING.iter() {\n\n core.store(0, Ordering::SeqCst);\n\n }\n\n for result in RESULTS_READY.iter() {\n\n result.store(0, Ordering::SeqCst);\n\n }\n\n SAMPLING_INFO.lock().clear();\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "kernel/pmu_x86/src/lib.rs", "rank": 96, "score": 303870.8776198717 }, { "content": "/// Measures the round trip time to send a 1-byte message on an async channel. \n\n/// Calls `do_ipc_async_inner` multiple times to perform the actual operation\n\nfn do_ipc_async(pinned: bool, blocking: bool, cycles: bool) -> Result<(), &'static str> {\n\n\tlet child_core = if pinned {\n\n\t\tSome(CPU_ID!())\n\n\t} else {\n\n\t\tNone\n\n\t};\n\n\n\n\tlet mut tries: u64 = 0;\n\n\tlet mut max: u64 = core::u64::MIN;\n\n\tlet mut min: u64 = core::u64::MAX;\n\n\tlet mut vec = Vec::with_capacity(TRIES);\n\n\n\n\tprint_header(TRIES, ITERATIONS);\n\n\n\n\tfor i in 0..TRIES {\n\n\t\tlet lat = if cycles {\n\n\t\t\tdo_ipc_async_inner_cycles(i+1, TRIES, child_core, blocking)?\t\n\n\t\t} else {\n\n\t\t\tdo_ipc_async_inner(i+1, TRIES, child_core, blocking)?\n\n\t\t};\n", "file_path": "applications/bm/src/lib.rs", "rank": 97, "score": 303696.57440139557 }, { "content": "/// Returns the samples that were stored during sampling in the form of a SampleResults object. \n\n/// If samples are not yet finished, forces them to stop. \n\npub fn retrieve_samples() -> Result<SampleResults, &'static str> {\n\n let my_core_id = apic::get_my_apic_id();\n\n\n\n let mut sampling_info = SAMPLING_INFO.lock();\n\n let mut samples = sampling_info.get_mut(&my_core_id).ok_or(\"pmu_x86::retrieve_samples: could not retrieve sampling information for this core\")?;\n\n\n\n // the interrupt handler might have stopped samples already so thsi check is required\n\n if core_is_currently_sampling(my_core_id) {\n\n stop_samples(my_core_id, &mut samples)?;\n\n }\n\n \n\n sampling_results_have_been_retrieved(my_core_id)?;\n\n\n\n Ok(SampleResults{instruction_pointers: samples.ip_list.clone(), task_ids: samples.task_id_list.clone()}) \n\n}\n\n\n", "file_path": "kernel/pmu_x86/src/lib.rs", "rank": 98, "score": 303202.7709236565 }, { "content": "/// Allocates pages starting at the given `VirtualAddress` with a size given in number of bytes. \n\n/// \n\n/// This function still allocates whole pages by rounding up the number of bytes. \n\n/// See [`allocate_pages_deferred()`](fn.allocate_pages_deferred.html) for more details. \n\npub fn allocate_pages_by_bytes_at(vaddr: VirtualAddress, num_bytes: usize) -> Result<AllocatedPages, &'static str> {\n\n\tallocate_pages_by_bytes_deferred(Some(vaddr), num_bytes)\n\n\t\t.map(|(ap, _action)| ap)\n\n}\n\n\n\n\n", "file_path": "kernel/page_allocator/src/lib.rs", "rank": 99, "score": 303053.0685333697 } ]
Rust
src/de/value.rs
Mingun/serde-gff
2bfacbb0b6b361da749082f99edaec474ccc6c7c
use std::collections::HashMap; use std::fmt; use std::marker::PhantomData; use indexmap::IndexMap; use serde::forward_to_deserialize_any; use serde::de::{Deserialize, Deserializer, Error, IntoDeserializer, SeqAccess, MapAccess, Visitor}; use crate::Label; use crate::string::{GffString, StringKey}; use crate::value::Value; macro_rules! string_key { ($method:ident, $type:ty) => ( #[inline] fn $method<E>(self, value: $type) -> Result<Key, E> where E: Error, { Ok(Key::String(StringKey(value as u32))) } ); } enum Key { Label(Label), String(StringKey), } struct KeyVisitor; impl<'de> Visitor<'de> for KeyVisitor { type Value = Key; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a string with length in UTF-8 <=16, byte buffer with length <=16, char or integer") } string_key!(visit_u8, u8); string_key!(visit_i8, i8); string_key!(visit_u16, u16); string_key!(visit_i16, i16); string_key!(visit_u32, u32); string_key!(visit_i32, i32); string_key!(visit_u64, u64); string_key!(visit_i64, i64); string_key!(visit_u128, u128); string_key!(visit_i128, i128); #[inline] fn visit_char<E>(self, value: char) -> Result<Key, E> where E: Error, { self.visit_string(value.to_string()) } #[inline] fn visit_str<E>(self, value: &str) -> Result<Key, E> where E: Error, { self.visit_bytes(value.as_bytes()) } #[inline] fn visit_bytes<E>(self, value: &[u8]) -> Result<Key, E> where E: Error, { use crate::error::Error::TooLongLabel; match Label::from_bytes(value) { Ok(label) => Ok(Key::Label(label)), Err(TooLongLabel(len)) => Err(E::invalid_length(len, &self)), Err(err) => Err(E::custom(err)), } } } impl<'de> Deserialize<'de> for Key { #[inline] fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(KeyVisitor) } } struct LabelVisitor; impl<'de> Visitor<'de> for LabelVisitor { type Value = Label; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a string with length in UTF-8 <=16, byte buffer with length <=16, or char") } #[inline] fn visit_char<E>(self, value: char) -> Result<Label, E> where E: Error, { self.visit_string(value.to_string()) } #[inline] fn visit_str<E>(self, value: &str) -> Result<Label, E> where E: Error, { self.visit_bytes(value.as_bytes()) } #[inline] fn visit_bytes<E>(self, value: &[u8]) -> Result<Label, E> where E: Error, { use crate::error::Error::TooLongLabel; match Label::from_bytes(value) { Ok(label) => Ok(label), Err(TooLongLabel(len)) => Err(E::invalid_length(len, &self)), Err(err) => Err(E::custom(err)), } } } impl<'de> Deserialize<'de> for Label { #[inline] fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(LabelVisitor) } } #[derive(Debug)] pub struct LabelDeserializer<E> { value: Label, marker: PhantomData<E>, } impl<'de, E> IntoDeserializer<'de, E> for Label where E: Error, { type Deserializer = LabelDeserializer<E>; #[inline] fn into_deserializer(self) -> Self::Deserializer { LabelDeserializer { value: self, marker: PhantomData } } } impl<'de, E> Deserializer<'de> for LabelDeserializer<E> where E: Error, { type Error = E; fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { if let Ok(str) = self.value.as_str() { return visitor.visit_str(str); } visitor.visit_bytes(self.value.as_ref()) } forward_to_deserialize_any!( bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum identifier ignored_any ); } macro_rules! value_from_primitive { ($name:ident, $type:ty => $variant:ident) => ( #[inline] fn $name<E>(self, value: $type) -> Result<Value, E> { Ok(Value::$variant(value.into())) } ); } struct ValueVisitor; impl<'de> Visitor<'de> for ValueVisitor { type Value = Value; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("any valid GFF value") } #[inline] fn visit_bool<E>(self, value: bool) -> Result<Value, E> { Ok(Value::Byte(if value { 1 } else { 0 })) } value_from_primitive!(visit_i8 , i8 => Char); value_from_primitive!(visit_i16, i16 => Short); value_from_primitive!(visit_i32, i32 => Int); value_from_primitive!(visit_i64, i64 => Int64); value_from_primitive!(visit_u8 , u8 => Byte); value_from_primitive!(visit_u16, u16 => Word); value_from_primitive!(visit_u32, u32 => Dword); value_from_primitive!(visit_u64, u64 => Dword64); value_from_primitive!(visit_f32, f32 => Float); value_from_primitive!(visit_f64, f64 => Double); value_from_primitive!(visit_str, &str => String); value_from_primitive!(visit_string, String => String); value_from_primitive!(visit_bytes, &[u8] => Void); value_from_primitive!(visit_byte_buf, Vec<u8> => Void); #[inline] fn visit_some<D>(self, deserializer: D) -> Result<Value, D::Error> where D: Deserializer<'de>, { Deserialize::deserialize(deserializer) } #[inline] fn visit_unit<E>(self) -> Result<Value, E> { Ok(Value::Struct(IndexMap::with_capacity(0))) } #[inline] fn visit_seq<V>(self, mut seq: V) -> Result<Value, V::Error> where V: SeqAccess<'de>, { let mut vec = Vec::with_capacity(seq.size_hint().unwrap_or(0)); while let Some(elem) = seq.next_element()? { vec.push(elem); } Ok(Value::List(vec)) } fn visit_map<V>(self, mut map: V) -> Result<Value, V::Error> where V: MapAccess<'de>, { let size = map.size_hint().unwrap_or(0); if let Some(key) = map.next_key()? { match key { Key::Label(label) => { let mut values = IndexMap::with_capacity(size); values.insert(label, map.next_value()?); while let Some((key, value)) = map.next_entry()? { values.insert(key, value); } Ok(Value::Struct(values)) }, Key::String(key) => { let mut values = HashMap::with_capacity(size); values.insert(key, map.next_value()?); while let Some((key, value)) = map.next_entry()? { values.insert(StringKey(key), value); } Ok(Value::LocString(GffString::Internal(values).into())) }, } } else { Ok(Value::Struct(IndexMap::with_capacity(0))) } } } impl<'de> Deserialize<'de> for Value { #[inline] fn deserialize<D>(deserializer: D) -> Result<Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(ValueVisitor) } } #[derive(Debug)] pub struct ValueDeserializer<E> { value: Value, marker: PhantomData<E>, } impl<'de, E> IntoDeserializer<'de, E> for Value where E: Error, { type Deserializer = ValueDeserializer<E>; #[inline] fn into_deserializer(self) -> Self::Deserializer { ValueDeserializer { value: self, marker: PhantomData } } } impl<'de, E> Deserializer<'de> for ValueDeserializer<E> where E: Error, { type Error = E; #[inline] fn is_human_readable(&self) -> bool { false } fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { use self::Value::*; match self.value { Byte(val) => visitor.visit_u8(val), Char(val) => visitor.visit_i8(val), Word(val) => visitor.visit_u16(val), Short(val) => visitor.visit_i16(val), Dword(val) => visitor.visit_u32(val), Int(val) => visitor.visit_i32(val), Dword64(val) => visitor.visit_u64(val), Int64(val) => visitor.visit_i64(val), Float(val) => visitor.visit_f32(val), Double(val) => visitor.visit_f64(val), String(val) => visitor.visit_string(val), ResRef(val) => { if let Ok(str) = val.as_str() { return visitor.visit_str(str); } visitor.visit_byte_buf(val.0) }, LocString(val) => { let value: GffString = val.into(); value.into_deserializer().deserialize_any(visitor) }, Void(val) => visitor.visit_byte_buf(val), Struct(val) => { use serde::de::value::MapDeserializer; MapDeserializer::new(val.into_iter()).deserialize_any(visitor) }, List(val) => val.into_deserializer().deserialize_any(visitor), } } forward_to_deserialize_any!( bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum identifier ignored_any ); }
use std::collections::HashMap; use std::fmt; use std::marker::PhantomData; use indexmap::IndexMap; use serde::forward_to_deserialize_any; use serde::de::{Deserialize, Deserializer, Error, IntoDeserializer, SeqAccess, MapAccess, Visitor}; use crate::Label; use crate::string::{GffString, StringKey}; use crate::value::Value; macro_rules! string_key { ($method:ident, $type:ty) => ( #[inline] fn $method<E>(self, value: $type) -> Result<Key, E> where E: Error, { Ok(Key::String(StringKey(value as u32))) } ); } enum Key { Label(Label), String(StringKey), } struct KeyVisitor; impl<'de> Visitor<'de> for KeyVisitor { type Value = Key; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a string with length in UTF-8 <=16, byte buffer with length <=16, char or integer") } string_key!(visit_u8, u8); string_key!(visit_i8, i8); string_key!(visit_u16, u16); string_key!(visit_i16, i16); string_key!(visit_u32, u32); string_key!(visit_i32, i32); string_key!(visit_u64, u64); string_key!(visit_i64, i64); string_key!(visit_u128, u128); string_key!(visit_i128, i128); #[inline] fn visit_char<E>(self, value: char) -> Result<Key, E> where E: Error, { self.visit_string(value.to_string()) } #[inline] fn visit_str<E>(self, value: &str) -> Result<Key, E> where E: Error, { self.visit_bytes(value.as_bytes()) } #[inline] fn visit_bytes<E>(self, value: &[u8]) -> Result<Key, E> where E: Error, { use crate::error::Error::TooLongLabel; match Label::from_bytes(value) { Ok(label) => Ok(Key::Label(label)), Err(TooLongLabel(len)) => Err(E::invalid_length(len, &self)), Err(err) => Err(E::custom(err)), } } } impl<'de> Deserialize<'de> for Key { #[inline] fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(KeyVisitor) } } struct LabelVisitor; impl<'de> Visitor<'de> for LabelVisitor { type Value = Label; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a string with length in UTF-8 <=16, byte buffer with length <=16, or char") } #[inline] fn visit_char<E>(self, value: char) -> Result<Label, E> where E: Error, { self.visit_string(value.to_string()) } #[inline] fn visit_str<E>(self, value: &str) -> Result<Label, E> where E: Error, { self.visit_bytes(value.as_bytes()) } #[inline] fn visit_bytes<E>(self, value: &[u
} impl<'de> Deserialize<'de> for Label { #[inline] fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(LabelVisitor) } } #[derive(Debug)] pub struct LabelDeserializer<E> { value: Label, marker: PhantomData<E>, } impl<'de, E> IntoDeserializer<'de, E> for Label where E: Error, { type Deserializer = LabelDeserializer<E>; #[inline] fn into_deserializer(self) -> Self::Deserializer { LabelDeserializer { value: self, marker: PhantomData } } } impl<'de, E> Deserializer<'de> for LabelDeserializer<E> where E: Error, { type Error = E; fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { if let Ok(str) = self.value.as_str() { return visitor.visit_str(str); } visitor.visit_bytes(self.value.as_ref()) } forward_to_deserialize_any!( bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum identifier ignored_any ); } macro_rules! value_from_primitive { ($name:ident, $type:ty => $variant:ident) => ( #[inline] fn $name<E>(self, value: $type) -> Result<Value, E> { Ok(Value::$variant(value.into())) } ); } struct ValueVisitor; impl<'de> Visitor<'de> for ValueVisitor { type Value = Value; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("any valid GFF value") } #[inline] fn visit_bool<E>(self, value: bool) -> Result<Value, E> { Ok(Value::Byte(if value { 1 } else { 0 })) } value_from_primitive!(visit_i8 , i8 => Char); value_from_primitive!(visit_i16, i16 => Short); value_from_primitive!(visit_i32, i32 => Int); value_from_primitive!(visit_i64, i64 => Int64); value_from_primitive!(visit_u8 , u8 => Byte); value_from_primitive!(visit_u16, u16 => Word); value_from_primitive!(visit_u32, u32 => Dword); value_from_primitive!(visit_u64, u64 => Dword64); value_from_primitive!(visit_f32, f32 => Float); value_from_primitive!(visit_f64, f64 => Double); value_from_primitive!(visit_str, &str => String); value_from_primitive!(visit_string, String => String); value_from_primitive!(visit_bytes, &[u8] => Void); value_from_primitive!(visit_byte_buf, Vec<u8> => Void); #[inline] fn visit_some<D>(self, deserializer: D) -> Result<Value, D::Error> where D: Deserializer<'de>, { Deserialize::deserialize(deserializer) } #[inline] fn visit_unit<E>(self) -> Result<Value, E> { Ok(Value::Struct(IndexMap::with_capacity(0))) } #[inline] fn visit_seq<V>(self, mut seq: V) -> Result<Value, V::Error> where V: SeqAccess<'de>, { let mut vec = Vec::with_capacity(seq.size_hint().unwrap_or(0)); while let Some(elem) = seq.next_element()? { vec.push(elem); } Ok(Value::List(vec)) } fn visit_map<V>(self, mut map: V) -> Result<Value, V::Error> where V: MapAccess<'de>, { let size = map.size_hint().unwrap_or(0); if let Some(key) = map.next_key()? { match key { Key::Label(label) => { let mut values = IndexMap::with_capacity(size); values.insert(label, map.next_value()?); while let Some((key, value)) = map.next_entry()? { values.insert(key, value); } Ok(Value::Struct(values)) }, Key::String(key) => { let mut values = HashMap::with_capacity(size); values.insert(key, map.next_value()?); while let Some((key, value)) = map.next_entry()? { values.insert(StringKey(key), value); } Ok(Value::LocString(GffString::Internal(values).into())) }, } } else { Ok(Value::Struct(IndexMap::with_capacity(0))) } } } impl<'de> Deserialize<'de> for Value { #[inline] fn deserialize<D>(deserializer: D) -> Result<Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(ValueVisitor) } } #[derive(Debug)] pub struct ValueDeserializer<E> { value: Value, marker: PhantomData<E>, } impl<'de, E> IntoDeserializer<'de, E> for Value where E: Error, { type Deserializer = ValueDeserializer<E>; #[inline] fn into_deserializer(self) -> Self::Deserializer { ValueDeserializer { value: self, marker: PhantomData } } } impl<'de, E> Deserializer<'de> for ValueDeserializer<E> where E: Error, { type Error = E; #[inline] fn is_human_readable(&self) -> bool { false } fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { use self::Value::*; match self.value { Byte(val) => visitor.visit_u8(val), Char(val) => visitor.visit_i8(val), Word(val) => visitor.visit_u16(val), Short(val) => visitor.visit_i16(val), Dword(val) => visitor.visit_u32(val), Int(val) => visitor.visit_i32(val), Dword64(val) => visitor.visit_u64(val), Int64(val) => visitor.visit_i64(val), Float(val) => visitor.visit_f32(val), Double(val) => visitor.visit_f64(val), String(val) => visitor.visit_string(val), ResRef(val) => { if let Ok(str) = val.as_str() { return visitor.visit_str(str); } visitor.visit_byte_buf(val.0) }, LocString(val) => { let value: GffString = val.into(); value.into_deserializer().deserialize_any(visitor) }, Void(val) => visitor.visit_byte_buf(val), Struct(val) => { use serde::de::value::MapDeserializer; MapDeserializer::new(val.into_iter()).deserialize_any(visitor) }, List(val) => val.into_deserializer().deserialize_any(visitor), } } forward_to_deserialize_any!( bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum identifier ignored_any ); }
8]) -> Result<Label, E> where E: Error, { use crate::error::Error::TooLongLabel; match Label::from_bytes(value) { Ok(label) => Ok(label), Err(TooLongLabel(len)) => Err(E::invalid_length(len, &self)), Err(err) => Err(E::custom(err)), } }
function_block-function_prefixed
[ { "content": "/// Десериализатор для чтения идентификаторов полей\n\nstruct Field<'a, R: 'a + Read + Seek>(&'a mut Deserializer<R>);\n\n\n\nimpl<'de, 'a, R: 'a + Read + Seek> de::Deserializer<'de> for Field<'a, R> {\n\n type Error = Error;\n\n\n\n #[inline]\n\n fn is_human_readable(&self) -> bool { false }\n\n\n\n fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value>\n\n where V: Visitor<'de>,\n\n {\n\n let token = self.0.next_token()?;\n\n if let Token::Label(index) = token {\n\n let label = self.0.parser.read_label(index)?;\n\n return visitor.visit_str(label.as_str()?);\n\n }\n\n return Err(Error::Unexpected(\"Label\", token));\n\n }\n\n\n\n delegate!(deserialize_i8);\n", "file_path": "src/de/mod.rs", "rank": 4, "score": 84696.97356030186 }, { "content": "#[derive(Debug)]\n\nenum Struct {\n\n /// Структура без полей\n\n NoFields,\n\n /// Структура, состоящая только из одного поля, содержит индекс этого поля\n\n OneField(usize),\n\n /// Структура, состоящая из двух и более полей. Содержит индекс списка и количество полей\n\n MultiField { list: FieldListIndex, fields: u32 }\n\n}\n\nimpl Struct {\n\n /// Преобразует промежуточное представление в окончательное, которое может быть записано в файл\n\n #[inline]\n\n fn into_raw(&self, offsets: &[u32]) -> raw::Struct {\n\n use self::Struct::*;\n\n\n\n match *self {\n\n NoFields => raw::Struct { tag: 0, offset: 0, fields: 0 },\n\n OneField(index) => raw::Struct { tag: 0, offset: index as u32, fields: 1 },\n\n MultiField { list, fields } => raw::Struct { tag: 0, offset: offsets[list.0], fields },\n\n }\n\n }\n\n}\n\n\n\n/// Промежуточное представление сериализуемого поля структуры. Содержит данные, которые после\n\n/// небольшого преобразования, возможного только после окончания сериализации, могут\n\n/// быть записаны в файл\n", "file_path": "src/ser/mod.rs", "rank": 5, "score": 78386.64666751807 }, { "content": "/// Список индексов для одной структуры, хранимые в поле [`Gff::field_indices`]\n\n///\n\n/// [`Gff::field_indices`]: ../struct.Gff.html#field.field_indices\n\nstruct FieldIndex<'a>(&'a [u32]);\n\nimpl<'a> fmt::Debug for FieldIndex<'a> {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{:?}\", self.0)\n\n }\n\n}\n\n/// Представление списка индексов полей структур для отладочного вывода\n", "file_path": "src/raw.rs", "rank": 6, "score": 63018.69864732902 }, { "content": "/// Данные для одного поля, хранимые в поле [`Gff::field_data`]. Используется для улучшения отладочного вывода\n\n///\n\n/// [`Gff::field_data`]: ../struct.Gff.html#field.field_data\n\nstruct FieldData<'a>(&'a [u8]);\n\nimpl<'a> fmt::Debug for FieldData<'a> {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{:?}\", self.0)\n\n }\n\n}\n\n/// Представление данных комплексных полей для отладочного вывода\n", "file_path": "src/raw.rs", "rank": 7, "score": 63018.69864732902 }, { "content": "/// Список индексов для одного списка, хранимый в поле [`Gff::list_indices`]\n\n///\n\n/// [`Gff::list_indices`]: ../struct.Gff.html#field.list_indices\n\nstruct ListIndex<'a>(&'a [u32]);\n\nimpl<'a> fmt::Debug for ListIndex<'a> {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{:?}\", self.0)\n\n }\n\n}\n\n/// Представление списка индексов полей структур для отладочного вывода\n", "file_path": "src/raw.rs", "rank": 8, "score": 63018.69864732902 }, { "content": "#[inline]\n\npub fn to_vec<T>(signature: Signature, value: &T) -> Result<Vec<u8>>\n\n where T: Serialize + ?Sized,\n\n{\n\n let mut vec = Vec::new();\n\n to_writer(&mut vec, signature, value)?;\n\n Ok(vec)\n\n}\n\n\n\n/// Реализует метод, возвращающий ошибку при попытке сериализовать значение, с описанием\n\n/// причины, что GFF не поддерживает данный тип на верхнем уровне и требуется обернуть его\n\n/// в структуру\n\nmacro_rules! unsupported {\n\n ($ser_method:ident ( $($type:ty),* ) ) => (\n\n unsupported!($ser_method($($type),*) -> Self::Ok);\n\n );\n\n ($ser_method:ident ( $($type:ty),* ) -> $result:ty) => (\n\n fn $ser_method(self, $(_: $type),*) -> Result<$result> {\n\n Err(Error::Serialize(concat!(\n\n \"`\", stringify!($ser_method), \"` can't be implemented in GFF format. Wrap value to the struct and serialize struct\"\n\n ).into()))\n", "file_path": "src/ser/mod.rs", "rank": 9, "score": 57658.16761985123 }, { "content": "#[inline]\n\npub fn to_writer<W, T>(writer: &mut W, signature: Signature, value: &T) -> Result<()>\n\n where W: Write,\n\n T: Serialize + ?Sized,\n\n{\n\n let mut s = Serializer::default();\n\n value.serialize(&mut s)?;\n\n s.write(writer, signature, Version::V3_2)\n\n}\n\n/// Сериализует значение в массив. Значение должно являться Rust структурой или перечислением\n", "file_path": "src/ser/mod.rs", "rank": 10, "score": 52929.837909316484 }, { "content": "#[derive(Debug, Copy, Clone)]\n\nstruct StructIndex(usize);\n\n\n\n/// Вспомогательная структура, описывающая индекс списка полей структуры, для типобезопасности.\n\n/// Любая GFF структура, имеющая более двух полей, ссылается по такому индексу на список с\n\n/// перечислением имеющихся у нее полей\n", "file_path": "src/ser/mod.rs", "rank": 11, "score": 42628.416642876524 }, { "content": "#[derive(Debug)]\n\nenum Field {\n\n /// Поле, представленное значением без внутренней структуры. Содержит метку поля и его значение\n\n Simple { label: LabelIndex, value: SimpleValueRef },\n\n /// Поле, представленное значением с внутренней структурой. Содержит метку поля и индекс\n\n /// промежуточного представления структуры в массиве [`structs`](struct.Serializer.html#field.structs)\n\n Struct { label: LabelIndex, struct_: StructIndex },\n\n /// Поле, представленное списком значений. Содержит метку поля и индекс списка в массиве\n\n /// [`list_indices`](struct.Serializer.html#field.list_indices)\n\n List { label: LabelIndex, list: ListIndex },\n\n}\n\nimpl Field {\n\n /// Преобразует промежуточное представление в окончательное, которое может быть записано в файл\n\n #[inline]\n\n fn into_raw(&self, offsets: &[u32]) -> Result<raw::Field> {\n\n use self::Field::*;\n\n\n\n Ok(match self {\n\n Simple { label, value } => value.into_raw(label.0)?,\n\n Struct { label, struct_ } => {\n\n let mut data = [0u8; 4];\n", "file_path": "src/ser/mod.rs", "rank": 12, "score": 39430.20043977518 }, { "content": "#[derive(Debug, Clone)]\n\nstruct ReadList {\n\n /// Индекс в таблице индексов, содержащий структуру-элемент для чтения\n\n index: ListIndicesIndex,\n\n /// Состояние, в которое нужно перейти после завершения чтения списка\n\n state: Box<State>,\n\n}\n\nimpl ReadList {\n\n /// # Возвращаемое значение\n\n /// Возвращает генерируемый в процессе разбора токен и новое состояние парсера\n\n fn next<R: Read + Seek>(self, parser: &mut Parser<R>) -> Result<(Token, State)> {\n\n // Переходим к списку индексов структур-элементов списка и читаем его размер\n\n parser.seek(self.index)?;\n\n let count = parser.read_u32()?;\n\n\n\n // Сообщаем о начале списка и переходим в состояние чтения первого элемента\n\n let token = Token::ListBegin(count);\n\n let state = ReadItems {\n\n index: self.index + 1,\n\n count: count,\n\n state: self.state,\n", "file_path": "src/parser/states.rs", "rank": 13, "score": 37342.98237045143 }, { "content": "/// Сериализатор, записывающий значение поля\n\nstruct FieldSerializer<'a> {\n\n /// Хранилище записываемых данных\n\n ser: &'a mut Serializer,\n\n /// Номер метки, ассоциированной с сериализуемым полем\n\n label: LabelIndex,\n\n}\n\nimpl<'a> FieldSerializer<'a> {\n\n /// Добавляет в список структур новую структуру с указанным количеством полей, а\n\n /// в список полей -- новое поле типа \"структура\".\n\n ///\n\n /// Корректная ссылка на данные еще не заполнена, ее нужно будет скорректировать\n\n /// после того, как содержимое структуры будет записано\n\n ///\n\n /// Возвращает пару индексов: добавленной структуры и списка с полями структуры,\n\n /// если полей несколько\n\n fn add_struct(&mut self, fields: usize) -> Result<(StructIndex, FieldListIndex)> {\n\n // Добавляем запись о структуре\n\n let (struct_index, fields_index) = self.ser.add_struct(fields);\n\n\n\n self.ser.fields.push(Field::Struct {\n", "file_path": "src/ser/mod.rs", "rank": 14, "score": 34328.402072405515 }, { "content": "#[derive(Debug)]\n\nstruct DebugListIndex<'a> {\n\n /// Данные, разбитые по принадлежности к отдельным спискам и без длины, для удобства отладочного вывода\n\n by_list: Vec<ListIndex<'a>>,\n\n /// Данные в том виде, в каком они хранятся в файле\n\n raw: &'a [u32],\n\n}\n\n\n\n/// Описание всей структуры GFF файла, как она хранится в GFF файле\n\npub struct Gff {\n\n /// Заголовок файла, содержащий метаинформацию о нем: тип содержимого, версию структуры,\n\n /// количество и местоположение структур в файле\n\n pub header: Header,\n\n /// Список структур внутри GFF файла. Структура -- группирующий элемент, состоящий\n\n /// из [полей], помеченных [метками]\n\n ///\n\n /// [полей]: struct.Field.html\n\n /// [метками]: ../struct.Label.html\n\n pub structs: Vec<Struct>,\n\n /// Список полей из всех структур GFF файла. Каждое поле ссылается на [метку] и данные,\n\n /// а также имеет некоторый тип\n", "file_path": "src/raw.rs", "rank": 15, "score": 34328.402072405515 }, { "content": "#[derive(Debug)]\n\nstruct DebugFieldIndex<'a> {\n\n /// Данные, разбитые по принадлежности к отдельным структурам, для удобства отладочного вывода\n\n by_struct: Vec<FieldIndex<'a>>,\n\n /// Данные в том виде, в каком они хранятся в файле\n\n raw: &'a [u32],\n\n}\n\n\n", "file_path": "src/raw.rs", "rank": 16, "score": 34328.402072405515 }, { "content": "#[derive(Debug)]\n\nstruct DebugFieldData<'a> {\n\n /// Данные, разбитые по принадлежности к отдельным полям, для удобства отладочного вывода\n\n by_field: Vec<FieldData<'a>>,\n\n /// Данные в том виде, в каком они хранятся в файле\n\n raw: &'a [u8],\n\n}\n\n\n", "file_path": "src/raw.rs", "rank": 17, "score": 34328.402072405515 }, { "content": "#[derive(Debug, Copy, Clone)]\n\nstruct ListIndex(usize);\n\n\n\n/// Промежуточное представление сериализуемых структур. Содержит данные, которые после\n\n/// небольшого преобразования, возможного только после окончания сериализации, могут\n\n/// быть записаны в файл\n", "file_path": "src/ser/mod.rs", "rank": 18, "score": 32896.906332685656 }, { "content": "#[derive(Debug, Copy, Clone)]\n\nstruct FieldListIndex(usize);\n\n\n\n/// Вспомогательная структура, описывающая индекс списка элементов GFF списка, для типобезопасности\n", "file_path": "src/ser/mod.rs", "rank": 19, "score": 31618.23813472376 }, { "content": "impl From<FromUtf8Error> for Error {\n\n fn from(value: FromUtf8Error) -> Self { Encoding(value.to_string().into()) }\n\n}\n\n\n\nimpl de::Error for Error {\n\n fn custom<T: fmt::Display>(msg: T) -> Self {\n\n Deserialize(msg.to_string())\n\n }\n\n}\n\nimpl ser::Error for Error {\n\n fn custom<T: fmt::Display>(msg: T) -> Self {\n\n Error::Serialize(msg.to_string())\n\n }\n\n}\n", "file_path": "src/error.rs", "rank": 20, "score": 31157.648306416206 }, { "content": "\n\nimpl error::Error for Error {\n\n fn source(&self) -> Option<&(dyn error::Error + 'static)> {\n\n match *self {\n\n Io(ref err) => Some(err),\n\n _ => None,\n\n }\n\n }\n\n}\n\n\n\nimpl From<io::Error> for Error {\n\n fn from(value: io::Error) -> Self { Io(value) }\n\n}\n\n/// Реализация для конвертации из ошибок кодирования библиотеки `encodings`\n\nimpl From<Cow<'static, str>> for Error {\n\n fn from(value: Cow<'static, str>) -> Self { Encoding(value) }\n\n}\n\nimpl From<Utf8Error> for Error {\n\n fn from(value: Utf8Error) -> Self { Encoding(value.to_string().into()) }\n\n}\n", "file_path": "src/error.rs", "rank": 21, "score": 31157.074837021893 }, { "content": " /// Произошла ошибка кодирования или декодирования строки, например, из-за использования\n\n /// символа, не поддерживаемого кодировкой\n\n Encoding(Cow<'static, str>),\n\n /// В файле встретилось значение неизвестного типа, хранящее указанное значение\n\n UnknownValue {\n\n /// Идентификатор типа значения\n\n tag: u32,\n\n /// Значение, которое было записано в файле для данного тега\n\n value: u32\n\n },\n\n /// Разбор уже завершен\n\n ParsingFinished,\n\n /// Некорректное значение для метки. Метка не должна превышать по длине 16 байт в UTF-8,\n\n /// но указанное значение больше. Ошибка содержит длину текста, который пытаются преобразовать\n\n TooLongLabel(usize),\n\n /// При десериализации был обнаружен указанный токен, хотя ожидался не он.\n\n /// Ожидаемые значения описаны в первом параметре\n\n Unexpected(&'static str, Token),\n\n /// Ошибка, возникшая при десериализации\n\n Deserialize(String),\n", "file_path": "src/error.rs", "rank": 22, "score": 31156.977287721165 }, { "content": " /// Ошибка, возникшая при сериализации\n\n Serialize(String),\n\n}\n\n/// Тип результата, используемый в методах данной библиотеки\n\npub type Result<T> = result::Result<T, Error>;\n\n\n\nimpl fmt::Display for Error {\n\n fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {\n\n match *self {\n\n Io(ref err) => err.fmt(fmt),\n\n Encoding(ref msg) => msg.fmt(fmt),\n\n UnknownValue { tag, value } => write!(fmt, \"Unknown field value (tag: {}, value: {})\", tag, value),\n\n ParsingFinished => write!(fmt, \"Parsing finished\"),\n\n TooLongLabel(len) => write!(fmt, \"Too long label: label can contain up to 16 bytes, but string contains {} bytes in UTF-8\", len),\n\n Unexpected(ref expected, ref actual) => write!(fmt, \"Expected {}, but {:?} found\", expected, actual),\n\n Deserialize(ref msg) => msg.fmt(fmt),\n\n Serialize(ref msg) => msg.fmt(fmt),\n\n }\n\n }\n\n}\n", "file_path": "src/error.rs", "rank": 23, "score": 31155.115355074882 }, { "content": "//! Реализация структуры, описывающей ошибки кодирования или декодирования GFF\n\n\n\nuse std::borrow::Cow;\n\nuse std::fmt;\n\nuse std::error;\n\nuse std::io;\n\nuse std::result;\n\nuse std::str::Utf8Error;\n\nuse std::string::FromUtf8Error;\n\nuse serde::de;\n\nuse serde::ser;\n\n\n\nuse crate::parser::Token;\n\nuse self::Error::*;\n\n\n\n/// Виды ошибок, который могут возникнуть при чтении и интерпретации GFF-файла\n\n#[derive(Debug)]\n\npub enum Error {\n\n /// Произошла ошибка чтения или записи из/в нижележащего буфера\n\n Io(io::Error),\n", "file_path": "src/error.rs", "rank": 24, "score": 31150.980686689294 }, { "content": "\n\nimpl From<[u8; 16]> for Label {\n\n fn from(arr: [u8; 16]) -> Self { Label(arr) }\n\n}\n\n\n\nimpl AsRef<[u8]> for Label {\n\n fn as_ref(&self) -> &[u8] { &self.0 }\n\n}\n\n\n\nimpl FromStr for Label {\n\n type Err = Error;\n\n\n\n #[inline]\n\n fn from_str(value: &str) -> Result<Self, Error> {\n\n Self::from_bytes(value.as_bytes())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "src/label.rs", "rank": 25, "score": 31144.708684693032 }, { "content": " return from_utf8(&self.0[0..i])\n\n }\n\n }\n\n return from_utf8(&self.0);\n\n }\n\n\n\n /// Пытается создать метку из указанного массива байт.\n\n ///\n\n /// # Ошибки\n\n /// В случае, если длина среза равна или превышает 16 байт, возвращается ошибка\n\n /// [`Error::TooLongLabel`](./error/enum.Error.html#variant.TooLongLabel)\n\n pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {\n\n if bytes.len() > 16 {\n\n return Err(Error::TooLongLabel(bytes.len()));\n\n }\n\n\n\n let mut storage: [u8; 16] = Default::default();\n\n let range = 0..bytes.len();\n\n storage[range.clone()].copy_from_slice(&bytes[range]);\n\n Ok(storage.into())\n", "file_path": "src/label.rs", "rank": 26, "score": 31139.326154841918 }, { "content": "//! Содержит реализацию структуры, описывающей название поля в GFF файле и реализацию типажей для\n\n//! конвертации других типов данных в метку и обратно\n\n\n\nuse std::fmt;\n\nuse std::result::Result;\n\nuse std::str::{from_utf8, FromStr, Utf8Error};\n\nuse crate::error::Error;\n\n\n\n/// Описание названия поля структуры GFF файла. GFF файл состоит из дерева структур, а каждая\n\n/// структура -- из полей с именем и значением. Имена полей представлены данной структурой\n\n#[derive(Clone, Copy, PartialEq, Eq, Hash)]\n\npub struct Label([u8; 16]);\n\n\n\nimpl Label {\n\n /// Возвращает представление данной метки как текста, если он представлен в виде `UTF-8` строки\n\n pub fn as_str(&self) -> Result<&str, Utf8Error> {\n\n for i in 0..self.0.len() {\n\n // Во внутреннем представлении данные метки продолжаются до первого нулевого символа,\n\n // однако сам нулевой символ не храниться -- это просто заполнитель\n\n if self.0[i] == 0 {\n", "file_path": "src/label.rs", "rank": 27, "score": 31137.62733871038 }, { "content": " }\n\n}\n\n\n\nimpl fmt::Debug for Label {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n if let Ok(value) = self.as_str() {\n\n return write!(f, \"Label({})\", value);\n\n }\n\n write!(f, \"Label(\")?;\n\n self.0.fmt(f)?;\n\n return write!(f, \")\");\n\n }\n\n}\n\n\n\nimpl fmt::Display for Label {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n let value = self.as_str().map_err(|_| fmt::Error)?;\n\n write!(f, \"{}\", value)\n\n }\n\n}\n", "file_path": "src/label.rs", "rank": 28, "score": 31136.28605459529 }, { "content": " use super::Label;\n\n\n\n #[test]\n\n fn label_constructs_from_str() {\n\n assert_eq!(Label::from(*b\"short\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"), \"short\".parse().unwrap());\n\n assert_eq!(Label::from(*b\"exact_16_chars_\\0\"), \"exact_16_chars_\".parse().unwrap());\n\n assert!(\"more_then_16_char\".parse::<Label>().is_err());\n\n }\n\n}\n", "file_path": "src/label.rs", "rank": 29, "score": 31129.95299440092 }, { "content": " /// Преобразует вариант строки, наиболее приближенный к хранимому в файле варианту (и, таким\n\n /// образом, хранящий без потерь все содержимое файла) в вариант строки, в котором компилятор\n\n /// Rust гарантирует корректность данных -- либо ссылка на внешнюю строку, либо список строк\n\n /// для каждого языка и пола, причем для каждой пары существует лишь один вариант строки --\n\n /// последний из `LocString.strings`, если их там окажется несколько.\n\n ///\n\n /// Метод возвращает внутреннее представление, если `LocString.str_ref == StrRef(0xFFFFFFFF)`,\n\n /// в противном случае возвращается внешнее представление. Все строки из массива `LocString.strings`\n\n /// в этом случае игнорируются.\n\n fn from(value: LocString) -> Self {\n\n use self::GffString::*;\n\n\n\n match value.str_ref {\n\n StrRef(0xFFFFFFFF) => Internal(value.strings.into_iter().map(Into::into).collect()),\n\n _ => External(value.str_ref),\n\n }\n\n }\n\n}\n\nimpl From<GffString> for LocString {\n\n /// Преобразует представление локализованной строки, корректность данных в котором гарантируется\n", "file_path": "src/string.rs", "rank": 30, "score": 30987.8971985248 }, { "content": " /// компилятором Rust в представление, приближенное к хранимому в GFF файле.\n\n ///\n\n /// При преобразовании внешнего представления строки в `LocString.strings` записывается пустой массив.\n\n /// При преобразовании внутреннего представления в `LocString.str_ref` записывается `StrRef(0xFFFFFFFF)`.\n\n fn from(value: GffString) -> Self {\n\n use self::GffString::*;\n\n\n\n match value {\n\n External(str_ref) => LocString { str_ref, strings: vec![] },\n\n Internal(strings) => {\n\n let strings = strings.into_iter().map(Into::into).collect();\n\n LocString { str_ref: StrRef(0xFFFFFFFF), strings }\n\n },\n\n }\n\n }\n\n}\n", "file_path": "src/string.rs", "rank": 31, "score": 30987.151542149175 }, { "content": "}\n\nimpl From<(StringKey, String)> for SubString {\n\n #[inline]\n\n fn from(value: (StringKey, String)) -> Self {\n\n SubString { key: value.0, string: value.1 }\n\n }\n\n}\n\nimpl Into<(StringKey, String)> for SubString {\n\n #[inline]\n\n fn into(self) -> (StringKey, String) {\n\n (self.key, self.string)\n\n }\n\n}\n\n\n\n/// Локализуемая строка, содержащая в себе все данные, которые могут храниться в GFF файле.\n\n/// Может содержать логически некорректные данные, поэтому, если не требуется анализировать\n\n/// непосредственное содержимое GFF файла без потерь, лучше сразу преобразовать ее в\n\n/// [`GffString`], используя `into()`, и работать с ней.\n\n///\n\n/// [`GffString`]: enum.GffString.html\n", "file_path": "src/string.rs", "rank": 32, "score": 30986.995264880225 }, { "content": " StringKey(((value.0 as u32) << 1) | value.1 as u32)\n\n }\n\n}\n\n/// Преобразует ключ в число, в котором он храниться в GFF файле по формуле:\n\n/// ```rust,ignore\n\n/// ((self.language() as u32) << 1) | self.gender() as u32\n\n/// ```\n\nimpl Into<u32> for StringKey {\n\n #[inline]\n\n fn into(self) -> u32 { self.0 }\n\n}\n\n\n\n/// Часть локализованной строки, хранящая информацию для одного языка и пола\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash)]\n\npub struct SubString {\n\n /// Язык, на котором записан текст этой части многоязыковой строки, и пол\n\n /// персонажа, для которого он написан\n\n pub key: StringKey,\n\n /// Текст многоязыковой строки для указанного пола и языка\n\n pub string: String,\n", "file_path": "src/string.rs", "rank": 33, "score": 30986.93637505392 }, { "content": " /// Строка предназначена для персонажа мужского или неопределенного пола\n\n Male = 0,\n\n /// Строка предназначена для персонажа женского пола\n\n Female = 1,\n\n}\n\n\n\n/// Ключ, используемый для индексации локализуемых строк во внутреннем представлении\n\n/// строк (когда строки внедрены в GFF файл, а не используются ссылки на строки в TLK\n\n/// файле).\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash)]\n\npub struct StringKey(pub(crate) u32);\n\nimpl StringKey {\n\n /// Язык, на котором записан текст этой части многоязыковой строки\n\n pub fn language(&self) -> Language { unsafe { transmute(self.0 >> 1) } }\n\n /// Пол персонажа, для которого написан текст этой части многоязыковой строки\n\n pub fn gender(&self) -> Gender { unsafe { transmute(self.0 % 2) } }\n\n}\n\nimpl From<(Language, Gender)> for StringKey {\n\n #[inline]\n\n fn from(value: (Language, Gender)) -> Self {\n", "file_path": "src/string.rs", "rank": 34, "score": 30984.9720129579 }, { "content": " #[inline]\n\n pub fn code(&self) -> u32 { self.0 & !USER_TLK_MASK }\n\n}\n\n\n\nimpl fmt::Debug for StrRef {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"code: {}, user: {}\", self.code(), self.is_user())\n\n }\n\n}\n\n\n\n/// Виды языков, на которых могут храниться локализованные строки в объекте `LocString`\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\n#[repr(u32)]\n\npub enum Language {\n\n /// Английский язык\n\n English = 0,\n\n /// Французский язык\n\n French = 1,\n\n /// Немецкий язык\n\n German = 2,\n", "file_path": "src/string.rs", "rank": 35, "score": 30983.126135282753 }, { "content": "//! Содержит реализации структур, описывающих строки, хранящиеся в GFF файле\n\nuse std::fmt;\n\nuse std::mem::transmute;\n\nuse std::collections::HashMap;\n\n\n\n/// Маска, определяющая идентификатор строки\n\nconst USER_TLK_MASK: u32 = 0x8000_0000;\n\n\n\n/// Индекс в файле `dialog.tlk`, содержащий локализованный текст\n\n#[derive(Clone, Copy, PartialEq, Eq, Hash)]\n\npub struct StrRef(pub(crate) u32);\n\n\n\nimpl StrRef {\n\n /// Определяет, является ли строка индексом не из основного TLK файла игры, а из TLK\n\n /// файла модуля. Строка является строкой из TLK файла модуля, если старший бит в ее\n\n /// идентификаторе взведен\n\n #[inline]\n\n pub fn is_user(&self) -> bool { self.0 & USER_TLK_MASK != 0 }\n\n\n\n /// Определяет индекс строки в TLK файле\n", "file_path": "src/string.rs", "rank": 36, "score": 30980.13710120473 }, { "content": "#[derive(Debug, Clone, PartialEq, Eq, Hash)]\n\npub struct LocString {\n\n /// Индекс в TLK файле, содержащий локализованный текст\n\n pub str_ref: StrRef,\n\n /// Список локализованных строк для каждого языка и пола\n\n pub strings: Vec<SubString>,\n\n}\n\n\n\n/// Локализуемая строка, представленная в виде, в котором некорректные значения\n\n/// непредставимы.\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\npub enum GffString {\n\n /// Внешнее представление строки в виде индекса в TLK файле, содержащем локализованный\n\n /// текст. В зависимости от локализации текст будет разным\n\n External(StrRef),\n\n /// Внутреннее представление строки, хранимое внутри самого файла -- по строке для каждого\n\n /// языка и пола персонажа\n\n Internal(HashMap<StringKey, String>),\n\n}\n\nimpl From<LocString> for GffString {\n", "file_path": "src/string.rs", "rank": 37, "score": 30978.754982429386 }, { "content": " /// Итальянский язык\n\n Italian = 3,\n\n /// Испанский язык\n\n Spanish = 4,\n\n /// Польский язык\n\n Polish = 5,\n\n /// Корейский язык\n\n Korean = 128,\n\n /// Традиционный китайский\n\n ChineseTraditional = 129,\n\n /// Упрощенный китайский\n\n ChineseSimplified = 130,\n\n /// Японский\n\n Japanese= 131,\n\n}\n\n\n\n/// Виды пола персонажа, на которых могут храниться локализованные строки в объекте `LocString`\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\n#[repr(u32)]\n\npub enum Gender {\n", "file_path": "src/string.rs", "rank": 38, "score": 30973.803320334773 }, { "content": " ///\n\n /// Тег, ассоциированный с типом, равен `0`.\n\n Byte(u8),\n\n /// Символ текста в диапазоне `0x00-0xFF`, занимающий один байт.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `1`.\n\n Char(i8),\n\n /// Беззнаковое целое (от 0 до 65535), занимающее 2 байта.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `2`.\n\n Word(u16),\n\n /// Знаковое целое (от -32768 до 32767), занимающее 2 байта.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `3`.\n\n Short(i16),\n\n /// Беззнаковое целое (от 0 до 4294967296), занимающее 4 байта.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `4`.\n\n Dword(u32),\n\n /// Знаковое целое (от -2147483648 до 2147483647), занимающее 4 байта.\n", "file_path": "src/value.rs", "rank": 39, "score": 30546.175296797446 }, { "content": " ///\n\n /// Тег, ассоциированный с типом, равен `13`.\n\n Void(Vec<u8>),\n\n /// Вложенная структура. Порядок полей в структуре постоянный и определяется порядком их добавления\n\n ///\n\n /// Тег, ассоциированный с типом, равен `14`.\n\n Struct(IndexMap<Label, Value>),\n\n /// Список значений любой длины.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `15`.\n\n List(Vec<Value>),\n\n}\n\n\n\nimpl From<SimpleValue> for Value {\n\n #[inline]\n\n fn from(value: SimpleValue) -> Value {\n\n use self::SimpleValue::*;\n\n\n\n match value {\n\n Byte(val) => Value::Byte(val),\n", "file_path": "src/value.rs", "rank": 40, "score": 30546.06659401941 }, { "content": " Char(i8),\n\n /// Беззнаковое целое (от 0 до 65535), занимающее 2 байта.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `2`.\n\n Word(u16),\n\n /// Знаковое целое (от -32768 до 32767), занимающее 2 байта.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `3`.\n\n Short(i16),\n\n /// Беззнаковое целое (от 0 до 4294967296), занимающее 4 байта.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `4`.\n\n Dword(u32),\n\n /// Знаковое целое (от -2147483648 до 2147483647), занимающее 4 байта.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `5`.\n\n Int(i32),\n\n /// Беззнаковое целое (от 0 до примерно 18e+18), занимающее 8 байт.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `6`.\n", "file_path": "src/value.rs", "rank": 41, "score": 30543.52106744416 }, { "content": "//! Содержит описания значений, которые может хранить GFF файл\n\n\n\nuse indexmap::IndexMap;\n\n\n\nuse crate::{Label, LocString, ResRef};\n\nuse crate::index::{U64Index, I64Index, F64Index, StringIndex, ResRefIndex, LocStringIndex, BinaryIndex};\n\n\n\n/// Перечисление, представляющее все примитивные типы данных, который может хранить GFF файл.\n\n///\n\n/// Кроме примитивных типов данных GFF файл также может хранить рекурсивные структуры из\n\n/// данных типов и их списки.\n\n#[derive(Debug, Clone, PartialEq)]\n\npub enum SimpleValueRef {\n\n /// Беззнаковое байтовое значение (от 0 до 255), занимающее один байт.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `0`.\n\n Byte(u8),\n\n /// Символ текста в диапазоне `0x00-0xFF`, занимающий один байт.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `1`.\n", "file_path": "src/value.rs", "rank": 42, "score": 30542.653857835507 }, { "content": " Word(u16),\n\n /// Знаковое целое (от -32768 до 32767), занимающее 2 байта.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `3`.\n\n Short(i16),\n\n /// Беззнаковое целое (от 0 до 4294967296), занимающее 4 байта.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `4`.\n\n Dword(u32),\n\n /// Знаковое целое (от -2147483648 до 2147483647), занимающее 4 байта.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `5`.\n\n Int(i32),\n\n /// Беззнаковое целое (от 0 до примерно 18e+18), занимающее 8 байт.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `6`.\n\n Dword64(u64),\n\n /// Знаковое целое (примерно от -9e+18 до +9e+18), занимающее 8 байт.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `7`.\n", "file_path": "src/value.rs", "rank": 43, "score": 30539.87136796028 }, { "content": "/// В отличие от [`SimpleValueRef`] содержит полностью прочитанные данные из файла, а не только\n\n/// ссылки на них\n\n///\n\n/// Кроме примитивных типов данных GFF файл также может хранить рекурсивные структуры из\n\n/// данных типов и их списки.\n\n///\n\n/// [`SimpleValueRef`]: enum.SimpleValueRef.html\n\n#[derive(Debug, Clone, PartialEq)]\n\npub enum SimpleValue {\n\n /// Беззнаковое байтовое значение (от 0 до 255), занимающее один байт.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `0`.\n\n Byte(u8),\n\n /// Символ текста в диапазоне `0x00-0xFF`, занимающий один байт.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `1`.\n\n Char(i8),\n\n /// Беззнаковое целое (от 0 до 65535), занимающее 2 байта.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `2`.\n", "file_path": "src/value.rs", "rank": 44, "score": 30537.620475558047 }, { "content": " ///\n\n /// Тег, ассоциированный с типом, равен `5`.\n\n Int(i32),\n\n /// Беззнаковое целое (от 0 до примерно 18e+18), занимающее 8 байт.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `6`.\n\n Dword64(u64),\n\n /// Знаковое целое (примерно от -9e+18 до +9e+18), занимающее 8 байт.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `7`.\n\n Int64(i64),\n\n /// Число с плавающей запятой одинарной точности, занимающее 4 байта.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `8`.\n\n Float(f32),\n\n /// Число с плавающей запятой двойной точности, занимающее 8 байт.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `9`.\n\n Double(f64),\n\n /// Нелокализуемая строка.\n", "file_path": "src/value.rs", "rank": 45, "score": 30532.849342583555 }, { "content": " Char(val) => Value::Char(val),\n\n Word(val) => Value::Word(val),\n\n Short(val) => Value::Short(val),\n\n Dword(val) => Value::Dword(val),\n\n Int(val) => Value::Int(val),\n\n Dword64(val) => Value::Dword64(val),\n\n Int64(val) => Value::Int64(val),\n\n Float(val) => Value::Float(val),\n\n Double(val) => Value::Double(val),\n\n String(val) => Value::String(val),\n\n ResRef(val) => Value::ResRef(val),\n\n LocString(val) => Value::LocString(val),\n\n Void(val) => Value::Void(val),\n\n }\n\n }\n\n}\n", "file_path": "src/value.rs", "rank": 46, "score": 30532.788314587626 }, { "content": " String(String),\n\n /// Имя файла ресурса, до 16 символов.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `11`.\n\n ResRef(ResRef),\n\n /// Локализуемая строка. Содержит `StringRef` и несколько `CExoString`, каждую со своим номером языка.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `12`.\n\n LocString(LocString),\n\n /// Произвольные данные любой длины.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `13`.\n\n Void(Vec<u8>),\n\n}\n\n\n\n/// Перечисление, представляющее все возможные типы данных, которых способен хранить GFF файл,\n\n/// в обобщенном виде. Аналог `serde_json::Value`\n\n#[derive(Debug, Clone, PartialEq)]\n\npub enum Value {\n\n /// Беззнаковое байтовое значение (от 0 до 255), занимающее один байт.\n", "file_path": "src/value.rs", "rank": 47, "score": 30532.700719398974 }, { "content": " Dword64(U64Index),\n\n /// Знаковое целое (примерно от -9e+18 до +9e+18), занимающее 8 байт.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `7`.\n\n Int64(I64Index),\n\n /// Число с плавающей запятой одинарной точности, занимающее 4 байта.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `8`.\n\n Float(f32),\n\n /// Число с плавающей запятой двойной точности, занимающее 8 байт.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `9`.\n\n Double(F64Index),\n\n /// Нелокализуемая строка.\n\n ///\n\n /// Предпочитаемый максимальный размер - 1024 символа. Это ограничение установлено в первую\n\n /// очередь для того, чтобы сохранить пропускную способность сети в том случае, если строку\n\n /// необходимо передавать с сервера на клиент.\n\n ///\n\n /// Данный вид строк не должен использоваться для текста, который может увидеть игрок, так как\n", "file_path": "src/value.rs", "rank": 48, "score": 30529.12186974538 }, { "content": " ///\n\n /// Предпочитаемый максимальный размер - 1024 символа. Это ограничение установлено в первую\n\n /// очередь для того, чтобы сохранить пропускную способность сети в том случае, если строку\n\n /// необходимо передавать с сервера на клиент.\n\n ///\n\n /// Данный вид строк не должен использоваться для текста, который может увидеть игрок, так как\n\n /// он будет одинаковым независимо от языка клиента игры. Область применения данного типа -\n\n /// текст для разработчиков/дизайнеров уровней, например, тегов объектов, используемых в скриптах.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `10`.\n\n String(String),\n\n /// Имя файла ресурса, до 16 символов.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `11`.\n\n ResRef(ResRef),\n\n /// Локализуемая строка. Содержит `StringRef` и несколько `CExoString`, каждую со своим номером языка.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `12`.\n\n LocString(LocString),\n\n /// Произвольные данные любой длины.\n", "file_path": "src/value.rs", "rank": 49, "score": 30526.940391457494 }, { "content": " /// он будет одинаковым независимо от языка клиента игры. Область применения данного типа -\n\n /// текст для разработчиков/дизайнеров уровней, например, тегов объектов, используемых в скриптах.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `10`.\n\n String(StringIndex),\n\n /// Имя файла ресурса, до 16 символов.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `11`.\n\n ResRef(ResRefIndex),\n\n /// Локализуемая строка. Содержит `StringRef` и несколько `CExoString`, каждую со своим номером языка.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `12`.\n\n LocString(LocStringIndex),\n\n /// Произвольные данные любой длины.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `13`.\n\n Void(BinaryIndex),\n\n}\n\n\n\n/// Перечисление, представляющее все примитивные типы данных, который может хранить GFF файл.\n", "file_path": "src/value.rs", "rank": 50, "score": 30526.8134241638 }, { "content": " Int64(i64),\n\n /// Число с плавающей запятой одинарной точности, занимающее 4 байта.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `8`.\n\n Float(f32),\n\n /// Число с плавающей запятой двойной точности, занимающее 8 байт.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `9`.\n\n Double(f64),\n\n /// Нелокализуемая строка.\n\n ///\n\n /// Предпочитаемый максимальный размер - 1024 символа. Это ограничение установлено в первую\n\n /// очередь для того, чтобы сохранить пропускную способность сети в том случае, если строку\n\n /// необходимо передавать с сервера на клиент.\n\n ///\n\n /// Данный вид строк не должен использоваться для текста, который может увидеть игрок, так как\n\n /// он будет одинаковым независимо от языка клиента игры. Область применения данного типа -\n\n /// текст для разработчиков/дизайнеров уровней, например, тегов объектов, используемых в скриптах.\n\n ///\n\n /// Тег, ассоциированный с типом, равен `10`.\n", "file_path": "src/value.rs", "rank": 51, "score": 30525.90206614384 }, { "content": " /// Фиктивный элемент, для связывания типа ошибки `E`\n\n marker: PhantomData<E>,\n\n}\n\nimpl<'de, E> Deserializer<'de> for GffStringDeserializer<E>\n\n where E: Error,\n\n{\n\n type Error = E;\n\n\n\n fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>\n\n where V: Visitor<'de>,\n\n {\n\n use self::GffString::*;\n\n\n\n match self.value {\n\n External(str_ref) => visitor.visit_u32(str_ref.0),\n\n Internal(strings) => visitor.visit_map(strings.into_deserializer()),\n\n }\n\n }\n\n\n\n forward_to_deserialize_any!(\n\n bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str\n\n string bytes byte_buf option unit unit_struct newtype_struct seq\n\n tuple tuple_struct map struct enum identifier ignored_any\n\n );\n\n}\n", "file_path": "src/de/string.rs", "rank": 52, "score": 28922.169946553317 }, { "content": "{\n\n type Error = E;\n\n\n\n fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>\n\n where V: Visitor<'de>,\n\n {\n\n visitor.visit_u32(self.value.into())\n\n }\n\n\n\n forward_to_deserialize_any!(\n\n bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str\n\n string bytes byte_buf option unit unit_struct newtype_struct seq\n\n tuple tuple_struct map struct enum identifier ignored_any\n\n );\n\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\nimpl<'de, E> IntoDeserializer<'de, E> for GffString\n\n where E: Error,\n", "file_path": "src/de/string.rs", "rank": 53, "score": 28921.305944119318 }, { "content": "//! Содержит реализацию конвертирования типа GFF строки в десериализатор\n\n//! с помощью которого из него могут быть прочитаны другие совместимые типы.\n\n\n\nuse std::marker::PhantomData;\n\n\n\nuse serde::forward_to_deserialize_any;\n\nuse serde::de::{Deserializer, Error, IntoDeserializer, Visitor};\n\n\n\nuse crate::string::{GffString, StringKey};\n\n\n\nimpl<'de, E> IntoDeserializer<'de, E> for StringKey\n\n where E: Error,\n\n{\n\n type Deserializer = StringKeyDeserializer<E>;\n\n\n\n #[inline]\n\n fn into_deserializer(self) -> Self::Deserializer {\n\n StringKeyDeserializer { value: self, marker: PhantomData }\n\n }\n\n}\n", "file_path": "src/de/string.rs", "rank": 54, "score": 28903.540760330176 }, { "content": "{\n\n type Deserializer = GffStringDeserializer<E>;\n\n\n\n #[inline]\n\n fn into_deserializer(self) -> Self::Deserializer {\n\n GffStringDeserializer { value: self, marker: PhantomData }\n\n }\n\n}\n\n\n\n/// Десериализатор, использующий в качестве источника данных тип [`GffString`].\n\n///\n\n/// В зависимости от типа хранимой строки позволяет прочитать из значения либо `u32`,\n\n/// являющемся StrRef индексом, либо отображение из `u32` (содержащего комбинированное\n\n/// значение языка и пола строки) на `String` с текстом строки для данного языка и пола.\n\n///\n\n/// [`GffString`]: ../../enum.GffString.html\n\n#[derive(Debug)]\n\npub struct GffStringDeserializer<E> {\n\n /// Источник данных, из которого достаются данные для десериализации других структур\n\n value: GffString,\n", "file_path": "src/de/string.rs", "rank": 55, "score": 28897.100960122872 }, { "content": "\n\n/// Десериализатор, использующий в качестве источника данных тип [`StringKey`].\n\n///\n\n/// Позволяет прочитать из ключа число, сформированное по формуле:\n\n/// ```rust,ignore\n\n/// ((language as u32) << 1) | gender as u32\n\n/// ```\n\n/// Именно в таком формате оно храниться в GFF файле.\n\n///\n\n/// [`StringKey`]: ../../enum.StringKey.html\n\n#[derive(Debug)]\n\npub struct StringKeyDeserializer<E> {\n\n /// Источник данных, из которого достаются данные для десериализации других структур\n\n value: StringKey,\n\n /// Фиктивный элемент, для связывания типа ошибки `E`\n\n marker: PhantomData<E>,\n\n}\n\n\n\nimpl<'de, E> Deserializer<'de> for StringKeyDeserializer<E>\n\n where E: Error,\n", "file_path": "src/de/string.rs", "rank": 56, "score": 28895.398146382126 }, { "content": " {\n\n use self::Value::*;\n\n\n\n match *self {\n\n Byte(val) => serializer.serialize_u8(val),\n\n Char(val) => serializer.serialize_i8(val),\n\n Word(val) => serializer.serialize_u16(val),\n\n Short(val) => serializer.serialize_i16(val),\n\n Dword(val) => serializer.serialize_u32(val),\n\n Int(val) => serializer.serialize_i32(val),\n\n Dword64(val) => serializer.serialize_u64(val),\n\n Int64(val) => serializer.serialize_i64(val),\n\n Float(val) => serializer.serialize_f32(val),\n\n Double(val) => serializer.serialize_f64(val),\n\n String(ref val) => serializer.serialize_str(&val),\n\n ResRef(ref val) => serializer.serialize_bytes(&val.0),\n\n //TODO: реализовать сериализацию LocString\n\n LocString(ref _val) => unimplemented!(\"serialization of LocString not yet implemented\"),\n\n Void(ref val) => serializer.serialize_bytes(&val),\n\n Struct(ref val) => {\n", "file_path": "src/ser/value.rs", "rank": 69, "score": 28476.337407948547 }, { "content": "//! Содержит реализацию типажа `Serialize` для сериализации типа `Value`\n\n\n\nuse serde::ser::{Serialize, SerializeMap, Serializer};\n\n\n\nuse crate::Label;\n\nuse crate::value::Value;\n\n\n\nimpl Serialize for Label {\n\n #[inline]\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where S: Serializer,\n\n {\n\n serializer.serialize_bytes(self.as_ref())\n\n }\n\n}\n\n\n\nimpl Serialize for Value {\n\n #[inline]\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where S: Serializer,\n", "file_path": "src/ser/value.rs", "rank": 73, "score": 28468.982693317765 }, { "content": " let mut map = serializer.serialize_map(Some(val.len()))?;\n\n for (k, v) in val {\n\n map.serialize_key(k)?;\n\n map.serialize_value(v)?;\n\n }\n\n map.end()\n\n },\n\n List(ref val) => val.serialize(serializer),\n\n }\n\n }\n\n}\n", "file_path": "src/ser/value.rs", "rank": 74, "score": 28459.222286063865 }, { "content": "}\n\n\n\nfn main() {\n\n let data = Test {\n\n u16: 1, i16: 2,\n\n u32: 3, i32: 4,\n\n u64: 5, i64: 6,\n\n\n\n string: \"String\".into(),\n\n\n\n Struct: Struct { f32: PI, f64: E, bytes: b\"Vec<u8>\".to_vec() },\n\n list: vec![\n\n Item { u8: 7, i8: -8 },\n\n Item { u8: 9, i8: -10 },\n\n ],\n\n };\n\n\n\n let mut vec = to_vec((*b\"GFF \").into(), &data).expect(\"can't write data\");\n\n // Важный нюанс - не забыть, что создание десериализатора читает заголовок и возвращает\n\n // Result, а не сам десериализатор, поэтому требуется распаковка результата\n\n let mut de = Deserializer::new(Cursor::new(vec)).expect(\"can't read GFF header\");\n\n let val = Value::deserialize(&mut de).expect(\"can't deserialize data\");\n\n\n\n println!(\"{:#?}\", val);\n\n}\n", "file_path": "readme.md", "rank": 75, "score": 39.74302806539192 }, { "content": "//! struct Item { u8: u8, i8: i8 }\n\n//!\n\n//! #[derive(Debug, Serialize, Deserialize)]\n\n//! struct Struct {\n\n//! f32: f32,\n\n//! f64: f64,\n\n//!\n\n//! #[serde(with = \"serde_bytes\")]\n\n//! bytes: Vec<u8>,\n\n//! }\n\n//!\n\n//! #[derive(Debug, Serialize, Deserialize)]\n\n//! #[allow(non_snake_case)]\n\n//! struct Test {\n\n//! u16: u16,\n\n//! i16: i16,\n\n//! u32: u32,\n\n//! i32: i32,\n\n//! u64: u64,\n\n//! i64: i64,\n", "file_path": "src/lib.rs", "rank": 76, "score": 39.28025437604654 }, { "content": " }\n\n }\n\n );\n\n}\n\nimpl<'de, 'a, R: Read + Seek> de::Deserializer<'de> for &'a mut Deserializer<R> {\n\n type Error = Error;\n\n\n\n #[inline]\n\n fn is_human_readable(&self) -> bool { false }\n\n\n\n primitive!(deserialize_i8 , visit_i8 , Char);\n\n primitive!(deserialize_u8 , visit_u8 , Byte);\n\n primitive!(deserialize_i16, visit_i16, Short);\n\n primitive!(deserialize_u16, visit_u16, Word);\n\n primitive!(deserialize_i32, visit_i32, Int);\n\n primitive!(deserialize_u32, visit_u32, Dword);\n\n primitive!(deserialize_i64, visit_i64, Int64, read_i64);\n\n primitive!(deserialize_u64, visit_u64, Dword64, read_u64);\n\n primitive!(deserialize_f32, visit_f32, Float);\n\n primitive!(deserialize_f64, visit_f64, Double, read_f64);\n", "file_path": "src/de/mod.rs", "rank": 77, "score": 39.25136861130052 }, { "content": " unsupported!(serialize_i16(i16));\n\n unsupported!(serialize_u16(u16));\n\n unsupported!(serialize_i32(i32));\n\n unsupported!(serialize_u32(u32));\n\n unsupported!(serialize_i64(i64));\n\n unsupported!(serialize_u64(u64));\n\n\n\n unsupported!(serialize_f32(f32));\n\n unsupported!(serialize_f64(f64));\n\n\n\n unsupported!(serialize_bool(bool));\n\n unsupported!(serialize_char(char));\n\n\n\n #[inline]\n\n fn serialize_str(self, value: &str) -> Result<Self::Ok> {\n\n // Добавляем запись о метке\n\n self.ser.ser.add_label(value)\n\n }\n\n unsupported!(serialize_bytes(&[u8]));\n\n\n", "file_path": "src/ser/mod.rs", "rank": 78, "score": 36.321910865387025 }, { "content": "//!\n\n//! string: String,\n\n//!\n\n//! Struct: Struct,\n\n//! list: Vec<Item>,\n\n//! }\n\n//!\n\n//! fn main() {\n\n//! let data = Test {\n\n//! u16: 1, i16: 2,\n\n//! u32: 3, i32: 4,\n\n//! u64: 5, i64: 6,\n\n//!\n\n//! string: \"String\".into(),\n\n//!\n\n//! Struct: Struct { f32: PI, f64: E, bytes: b\"Vec<u8>\".to_vec() },\n\n//! list: vec![\n\n//! Item { u8: 7, i8: -8 },\n\n//! Item { u8: 9, i8: -10 },\n\n//! ],\n", "file_path": "src/lib.rs", "rank": 79, "score": 35.672519039071155 }, { "content": "serde-gff\n\n=========\n\n[![Crates.io](https://img.shields.io/crates/v/serde_gff.svg)](https://crates.io/crates/serde_gff)\n\n[![Документация](https://docs.rs/serde-gff/badge.svg)](https://docs.rs/serde-gff)\n\n[![Лицензия MIT](https://img.shields.io/crates/l/serde_gff.svg)](https://github.com/Mingun/serde-gff/blob/master/LICENSE)\n\n\n\nGeneric File Format (GFF) -- формат файлов, используемый играми на движке Bioware Aurora:\n\nNewerwinter Nights, The Witcher и Newerwinter Nights 2.\n\n\n\nФормат имеет некоторые ограничения:\n\n- элементами верхнего уровня могут быть только структуры или перечисления Rust в unit или struct варианте\n\n- имена полей структур не должны быть длиннее 16 байт в UTF-8. При нарушении при сериализации будет ошибка\n\n- то же самое касается ключей карт. Кроме того, ключами могут быть только строки (`&str` или `String`)\n\n\n\nУстановка\n\n---------\n\nВыполните в корне проекта\n\n```sh\n\ncargo add serde_gff\n\n```\n\nили добавьте следующую строку в `Cargo.toml`:\n\n```toml\n\n[dependencies]\n\nserde_gff = \"0.2\"\n\n```\n\n\n\nПример\n\n------\n\n```rust\n\nuse std::f32::consts::PI;\n\nuse std::f64::consts::E;\n\nuse std::io::Cursor;\n\nuse serde::{Serialize, Deserialize};\n\n\n\nuse serde_gff::de::Deserializer;\n\nuse serde_gff::ser::to_vec;\n\nuse serde_gff::value::Value;\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\nstruct Item { u8: u8, i8: i8 }\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\nstruct Struct {\n\n f32: f32,\n\n f64: f64,\n\n\n\n #[serde(with = \"serde_bytes\")]\n\n bytes: Vec<u8>,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\n#[allow(non_snake_case)]\n\nstruct Test {\n\n u16: u16,\n\n i16: i16,\n\n u32: u32,\n\n i32: i32,\n\n u64: u64,\n\n i64: i64,\n\n\n\n string: String,\n\n\n\n Struct: Struct,\n\n list: Vec<Item>,\n", "file_path": "readme.md", "rank": 80, "score": 34.09530801930947 }, { "content": " delegate!(deserialize_u8);\n\n delegate!(deserialize_i16);\n\n delegate!(deserialize_u16);\n\n delegate!(deserialize_i32);\n\n delegate!(deserialize_u32);\n\n delegate!(deserialize_i64);\n\n delegate!(deserialize_u64);\n\n delegate!(deserialize_f32);\n\n delegate!(deserialize_f64);\n\n\n\n delegate!(deserialize_bool);\n\n delegate!(deserialize_char);\n\n delegate!(deserialize_str);\n\n delegate!(deserialize_string);\n\n delegate!(deserialize_bytes);\n\n delegate!(deserialize_byte_buf);\n\n delegate!(deserialize_option);\n\n delegate!(deserialize_unit);\n\n delegate!(deserialize_map);\n\n delegate!(deserialize_seq);\n", "file_path": "src/de/mod.rs", "rank": 81, "score": 33.046993488137666 }, { "content": " type SerializeTupleVariant = Self::SerializeSeq;\n\n type SerializeMap = MapSerializer<'a>;\n\n type SerializeStruct = StructSerializer<'a>;\n\n type SerializeStructVariant = Self::SerializeStruct;\n\n\n\n primitive!(serialize_u8 , u8 , Byte);\n\n primitive!(serialize_i8 , i8 , Char);\n\n primitive!(serialize_u16, u16, Word);\n\n primitive!(serialize_i16, i16, Short);\n\n primitive!(serialize_u32, u32, Dword);\n\n primitive!(serialize_i32, i32, Int);\n\n complex! (serialize_u64, u64, Dword64, write_u64);\n\n complex! (serialize_i64, i64, Int64, write_i64);\n\n\n\n primitive!(serialize_f32, f32, Float);\n\n complex! (serialize_f64, f64, Double, write_f64);\n\n\n\n /// Формат не поддерживает сериализацию булевых значений, поэтому значение сериализуется,\n\n /// как `u8`: `true` представляется в виде `1`, а `false` -- в виде `0`.\n\n #[inline]\n", "file_path": "src/ser/mod.rs", "rank": 82, "score": 32.984519516947536 }, { "content": " /// # Параметры\n\n /// - `tag`: Вид данных, которые требуется прочитать. Известные данные расположены в\n\n /// диапазоне `[0; 13]`, для остальных значений возвращается ошибка [`Error::UnknownValue`]\n\n ///\n\n /// # Возвращаемое значение\n\n /// Возвращает лениво читаемое значение. Если данные хранятся непосредственно за тегом, то\n\n /// они будут уже прочитаны, в противном случае читается только адрес их местонахождения в файле.\n\n /// Таким образом, если данные не нужны, лишних чтений не будет\n\n ///\n\n /// [`Error::UnknownValue`]: ../../error/enum.Error.html#variant.UnknownValue\n\n fn read_value_ref(&mut self, tag: u32) -> Result<SimpleValueRef> {\n\n use self::SimpleValueRef::*;\n\n\n\n let value = match tag {\n\n 0 => Byte (self.reader.read_u8()?),\n\n 1 => Char (self.reader.read_i8()?),\n\n 2 => Word (self.reader.read_u16::<LE>()?),\n\n 3 => Short(self.reader.read_i16::<LE>()?),\n\n 4 => Dword(self.reader.read_u32::<LE>()?),\n\n 5 => Int (self.reader.read_i32::<LE>()?),\n", "file_path": "src/parser/mod.rs", "rank": 83, "score": 30.68165213864182 }, { "content": " return Err(Error::Unexpected(\"Byte, Char\", token));\n\n }\n\n\n\n #[inline]\n\n fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>\n\n where V: Visitor<'de>,\n\n {\n\n self.deserialize_string(visitor)\n\n }\n\n fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>\n\n where V: Visitor<'de>,\n\n {\n\n let token = self.next_token()?;\n\n match token {\n\n Token::Value(SimpleValueRef::String(value)) => {\n\n visitor.visit_string(self.parser.read_string(value)?)\n\n },\n\n Token::Value(SimpleValueRef::ResRef(value)) => {\n\n visitor.visit_string(self.parser.read_resref(value)?.as_string()?)\n\n },\n", "file_path": "src/de/mod.rs", "rank": 84, "score": 30.511566422187407 }, { "content": "\n\n #[inline]\n\n fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<Self::Ok>\n\n where T: ?Sized + Serialize,\n\n {\n\n // Добавляем запись о метке\n\n let label = self.ser.add_label(key)?;\n\n self.serialize_value(label, value)\n\n }\n\n\n\n #[inline]\n\n fn end(self) -> Result<Self::Ok> { Ok(()) }\n\n}\n\nimpl<'a> SerializeStructVariant for StructSerializer<'a> {\n\n type Ok = ();\n\n type Error = Error;\n\n\n\n #[inline]\n\n fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<Self::Ok>\n\n where T: ?Sized + Serialize,\n", "file_path": "src/ser/mod.rs", "rank": 85, "score": 29.293138120035366 }, { "content": " }\n\n\n\n newtype_test!(u8 = 42u8);\n\n newtype_test!(u16 = 42u16);\n\n newtype_test!(u32 = 42u32);\n\n newtype_test!(u64 = 42u64);\n\n\n\n newtype_test!(i8 = -42i8);\n\n newtype_test!(i16 = -42i16);\n\n newtype_test!(i32 = -42i32);\n\n newtype_test!(i64 = -42i64);\n\n\n\n newtype_test!(f32 = 42f32);\n\n newtype_test!(f64 = 42f64);\n\n\n\n newtype_test!(bool = true);\n\n newtype_test!(bool = false);\n\n\n\n newtype_test!(String = String::from(\"some string\"));\n\n newtype_test!(ByteBuf = ByteBuf::from(b\"some vector\".to_vec()));\n", "file_path": "src/ser/mod.rs", "rank": 86, "score": 29.289398726253392 }, { "content": " fn serialize_bool(self, v: bool) -> Result<Self::Ok> {\n\n self.serialize_u8(if v { 1 } else { 0 })\n\n }\n\n /// Формат не поддерживает сериализацию произвольных символов как отдельную сущность, поэтому\n\n /// они сериализуются, как строка из одного символа\n\n #[inline]\n\n fn serialize_char(self, v: char) -> Result<Self::Ok> {\n\n let mut data = [0u8; 4];\n\n self.serialize_str(v.encode_utf8(&mut data))\n\n }\n\n\n\n complex!(serialize_str , &str , String);\n\n complex!(serialize_bytes, &[u8], Void);\n\n\n\n #[inline]\n\n fn serialize_none(self) -> Result<Self::Ok> {\n\n self.serialize_unit()\n\n }\n\n #[inline]\n\n fn serialize_some<T>(self, value: &T) -> Result<Self::Ok>\n", "file_path": "src/ser/mod.rs", "rank": 87, "score": 29.27307416122513 }, { "content": " unsupported!(serialize_i32(i32));\n\n unsupported!(serialize_u32(u32));\n\n unsupported!(serialize_i64(i64));\n\n unsupported!(serialize_u64(u64));\n\n\n\n unsupported!(serialize_f32(f32));\n\n unsupported!(serialize_f64(f64));\n\n\n\n unsupported!(serialize_bool(bool));\n\n unsupported!(serialize_char(char));\n\n\n\n unsupported!(serialize_str(&str));\n\n unsupported!(serialize_bytes(&[u8]));\n\n\n\n #[inline]\n\n fn serialize_none(self) -> Result<Self::Ok> {\n\n self.serialize_unit()\n\n }\n\n fn serialize_some<T>(self, value: &T) -> Result<Self::Ok>\n\n where T: ?Sized + Serialize,\n", "file_path": "src/ser/mod.rs", "rank": 88, "score": 28.207364269203115 }, { "content": " let token = self.next_token()?;\n\n unimplemented!(\"`deserialize_tuple_struct(name: {}, len: {})` not yet supported. Token: {:?}\", name, len, token)\n\n }\n\n fn deserialize_struct<V>(self, _name: &'static str, _fields: &'static [&'static str], visitor: V) -> Result<V::Value>\n\n where V: Visitor<'de>,\n\n {\n\n self.deserialize_map(visitor)\n\n }\n\n fn deserialize_enum<V>(self, name: &'static str, variants: &'static [&'static str], _visitor: V) -> Result<V::Value>\n\n where V: Visitor<'de>,\n\n {\n\n let token = self.next_token()?;\n\n unimplemented!(\"`deserialize_enum(name: {}, variants: {})` not yet supported. Token: {:?}\", name, variants.len(), token)\n\n }\n\n}\n\n\n\nimpl<'de, 'a, R: Read + Seek> de::MapAccess<'de> for &'a mut Deserializer<R> {\n\n type Error = Error;\n\n\n\n fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>\n", "file_path": "src/de/mod.rs", "rank": 89, "score": 28.157945108383448 }, { "content": " fn into_raw(&self, label: u32) -> Result<raw::Field> {\n\n use self::SimpleValueRef::*;\n\n\n\n let mut data = [0u8; 4];\n\n let type_ = {\n\n let mut storage = &mut data[..];\n\n match *self {\n\n Byte(val) => { storage.write_u8 (val )?; FieldType::Byte },\n\n Char(val) => { storage.write_i8 (val )?; FieldType::Char },\n\n Word(val) => { storage.write_u16::<LE>(val )?; FieldType::Word },\n\n Short(val) => { storage.write_i16::<LE>(val )?; FieldType::Short },\n\n Dword(val) => { storage.write_u32::<LE>(val )?; FieldType::Dword },\n\n Int(val) => { storage.write_i32::<LE>(val )?; FieldType::Int },\n\n Dword64(val) => { storage.write_u32::<LE>(val.0)?; FieldType::Dword64 },\n\n Int64(val) => { storage.write_u32::<LE>(val.0)?; FieldType::Int64 },\n\n Float(val) => { storage.write_f32::<LE>(val )?; FieldType::Float },\n\n Double(val) => { storage.write_u32::<LE>(val.0)?; FieldType::Double },\n\n String(val) => { storage.write_u32::<LE>(val.0)?; FieldType::String },\n\n ResRef(val) => { storage.write_u32::<LE>(val.0)?; FieldType::ResRef },\n\n LocString(val) => { storage.write_u32::<LE>(val.0)?; FieldType::LocString },\n", "file_path": "src/ser/mod.rs", "rank": 90, "score": 26.831443170936854 }, { "content": "\n\n delegate!(deserialize_any);\n\n delegate!(deserialize_ignored_any);\n\n\n\n delegate!(deserialize_unit_struct, name);\n\n delegate!(deserialize_newtype_struct, name);\n\n delegate!(deserialize_struct, names);\n\n delegate!(deserialize_enum, names);\n\n\n\n #[inline]\n\n fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value>\n\n where V: Visitor<'de>,\n\n {\n\n self.0.deserialize_tuple(len, visitor)\n\n }\n\n #[inline]\n\n fn deserialize_tuple_struct<V>(self, name: &'static str, len: usize, visitor: V) -> Result<V::Value>\n\n where V: Visitor<'de>,\n\n {\n\n self.0.deserialize_tuple_struct(name, len, visitor)\n", "file_path": "src/de/mod.rs", "rank": 91, "score": 26.41915103701061 }, { "content": " _ => Err(Error::Unexpected(\"String, ResRef\", token)),\n\n }\n\n }\n\n #[inline]\n\n fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>\n\n where V: Visitor<'de>,\n\n {\n\n self.deserialize_byte_buf(visitor)\n\n }\n\n fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>\n\n where V: Visitor<'de>,\n\n {\n\n let token = self.next_token()?;\n\n match token {\n\n Token::Value(SimpleValueRef::Void(value)) => {\n\n visitor.visit_byte_buf(self.parser.read_byte_buf(value)?)\n\n },\n\n Token::Value(SimpleValueRef::ResRef(value)) => {\n\n visitor.visit_byte_buf(self.parser.read_resref(value)?.0)\n\n },\n", "file_path": "src/de/mod.rs", "rank": 92, "score": 26.04842989291718 }, { "content": " where K: DeserializeSeed<'de>,\n\n {\n\n let token = self.peek_token()?.clone();\n\n match token {\n\n Token::RootEnd | Token::ItemEnd | Token::StructEnd => Ok(None),\n\n Token::Label(..) => seed.deserialize(Field(&mut **self)).map(Some),\n\n token => Err(Error::Unexpected(\"Label\", token)),\n\n }\n\n }\n\n\n\n #[inline]\n\n fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>\n\n where V: DeserializeSeed<'de>,\n\n {\n\n seed.deserialize(&mut **self)\n\n }\n\n}\n\n\n\nimpl<'de, 'a, R: Read + Seek> de::SeqAccess<'de> for &'a mut Deserializer<R> {\n\n type Error = Error;\n", "file_path": "src/de/mod.rs", "rank": 93, "score": 25.637917980794793 }, { "content": "//! Содержит реализацию структуры, описывающей ссылку на ресурс и реализацию типажей для\n\n//! конвертации других типов данных в ссылку и обратно\n\n\n\nuse std::fmt;\n\nuse std::str::{self, FromStr, Utf8Error};\n\nuse std::string::FromUtf8Error;\n\n\n\n/// Представляет ссылку на игровой ресурс, которым может быть шаблон объекта\n\n#[derive(Clone, PartialEq, Eq, Hash)]\n\npub struct ResRef(pub(crate) Vec<u8>);\n\n\n\nimpl ResRef {\n\n /// Возвращает представление данной ссылки на ресурс как строки, если она представлена в виде `UTF-8` строки\n\n #[inline]\n\n pub fn as_str(&self) -> Result<&str, Utf8Error> {\n\n str::from_utf8(&self.0)\n\n }\n\n /// Возвращает представление данной ссылки на ресурс как строки, если она представлена в виде `UTF-8` строки\n\n #[inline]\n\n pub fn as_string(self) -> Result<String, FromUtf8Error> {\n", "file_path": "src/resref.rs", "rank": 94, "score": 25.07538584320534 }, { "content": " }\n\n );\n\n}\n\n\n\nimpl<'a> ser::Serializer for &'a mut Serializer {\n\n type Ok = ();\n\n type Error = Error;\n\n\n\n type SerializeSeq = ListSerializer<'a>;\n\n type SerializeTuple = Impossible<Self::Ok, Self::Error>;\n\n type SerializeTupleStruct = Impossible<Self::Ok, Self::Error>;\n\n type SerializeTupleVariant = Self::SerializeSeq;\n\n type SerializeMap = MapSerializer<'a>;\n\n type SerializeStruct = StructSerializer<'a>;\n\n type SerializeStructVariant = Self::SerializeStruct;\n\n\n\n unsupported!(serialize_i8(i8));\n\n unsupported!(serialize_u8(u8));\n\n unsupported!(serialize_i16(i16));\n\n unsupported!(serialize_u16(u16));\n", "file_path": "src/ser/mod.rs", "rank": 95, "score": 25.018520171408536 }, { "content": "\n\n fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>\n\n where V: Visitor<'de>,\n\n {\n\n let token = self.next_token()?;\n\n if let Token::Value(SimpleValueRef::Byte(value)) = token {\n\n return visitor.visit_bool(value != 0);\n\n }\n\n return Err(Error::Unexpected(\"Byte\", token));\n\n }\n\n fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>\n\n where V: Visitor<'de>,\n\n {\n\n let token = self.next_token()?;\n\n if let Token::Value(SimpleValueRef::Byte(value)) = token {\n\n return visitor.visit_char(value as char);\n\n }\n\n if let Token::Value(SimpleValueRef::Char(value)) = token {\n\n return visitor.visit_char(value as u8 as char);\n\n }\n", "file_path": "src/de/mod.rs", "rank": 96, "score": 24.95690371453668 }, { "content": " String::from_utf8(self.0)\n\n }\n\n}\n\n\n\nimpl fmt::Debug for ResRef {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n if let Ok(value) = str::from_utf8(&self.0) {\n\n return write!(f, \"{}\", value);\n\n }\n\n self.0.fmt(f)\n\n }\n\n}\n\n\n\nimpl fmt::Display for ResRef {\n\n #[inline]\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n let value = self.as_str().map_err(|_| fmt::Error)?;\n\n write!(f, \"{}\", value)\n\n }\n\n}\n", "file_path": "src/resref.rs", "rank": 97, "score": 24.280137291571616 }, { "content": " let token = self.next_token()?;\n\n match token {\n\n //TODO: После решения https://github.com/serde-rs/serde/issues/745 можно будет передавать числа\n\n Token::Value(Byte(val)) => visitor.visit_string(val.to_string()),\n\n Token::Value(Char(val)) => visitor.visit_string(val.to_string()),\n\n Token::Value(Word(val)) => visitor.visit_string(val.to_string()),\n\n Token::Value(Short(val)) => visitor.visit_string(val.to_string()),\n\n Token::Value(Dword(val)) => visitor.visit_string(val.to_string()),\n\n Token::Value(Int(val)) => visitor.visit_string(val.to_string()),\n\n Token::Value(Dword64(val)) => visitor.visit_string(self.parser.read_u64(val)?.to_string()),\n\n Token::Value(Int64(val)) => visitor.visit_string(self.parser.read_i64(val)?.to_string()),\n\n Token::Value(String(val)) => visitor.visit_string(self.parser.read_string(val)?),\n\n _ => Err(Error::Unexpected(\"Byte, Char, Word, Short, Dword, Int, Int64, String\", token)),\n\n }\n\n }\n\n\n\n fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>\n\n where V: Visitor<'de>,\n\n {\n\n let token = self.next_token()?;\n", "file_path": "src/de/mod.rs", "rank": 98, "score": 23.95045613106896 }, { "content": " Token::Label(index) => {\n\n let label = self.parser.read_label(index)?;\n\n visitor.visit_str(label.as_str()?)\n\n },\n\n _ => unimplemented!(\"`deserialize_any`, token: {:?}\", token)\n\n }\n\n }\n\n fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value>\n\n where V: Visitor<'de>,\n\n {\n\n let token = self.next_token()?;\n\n self.parser.skip_next(token);\n\n visitor.visit_none()\n\n }\n\n /// Данный метод вызывается при необходимости десериализовать идентификатор перечисления\n\n fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value>\n\n where V: Visitor<'de>,\n\n {\n\n use self::SimpleValueRef::*;\n\n\n", "file_path": "src/de/mod.rs", "rank": 99, "score": 23.831870013881463 } ]
Rust
src/intrinsics_orthographic.rs
strawlab/cam-geom
0d160e2510d4f0df7af1123d51cf1518c7a58070
use nalgebra::{ allocator::Allocator, base::storage::{Owned, Storage}, convert, DefaultAllocator, Dim, OMatrix, RealField, U2, U3, }; #[cfg(feature = "serde-serialize")] use serde::{Deserialize, Serialize}; use crate::{ coordinate_system::CameraFrame, Bundle, IntrinsicParameters, Pixels, Points, RayBundle, }; use crate::ray_bundle_types::SharedDirectionRayBundle; #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))] pub struct OrthographicParams<R: RealField> { pub sx: R, pub sy: R, pub cx: R, pub cy: R, } impl<R: RealField> From<OrthographicParams<R>> for IntrinsicParametersOrthographic<R> { #[inline] fn from(params: OrthographicParams<R>) -> Self { Self { params } } } #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))] pub struct IntrinsicParametersOrthographic<R: RealField> { params: OrthographicParams<R>, } impl<R> IntrinsicParameters<R> for IntrinsicParametersOrthographic<R> where R: RealField, { type BundleType = SharedDirectionRayBundle<R>; fn pixel_to_camera<IN, NPTS>( &self, pixels: &Pixels<R, NPTS, IN>, ) -> RayBundle<CameraFrame, Self::BundleType, R, NPTS, Owned<R, NPTS, U3>> where Self::BundleType: Bundle<R>, IN: Storage<R, NPTS, U2>, NPTS: Dim, DefaultAllocator: Allocator<R, NPTS, U3>, { let zero: R = convert(0.0); let mut result = RayBundle::new_shared_plusz_direction(OMatrix::zeros_generic( NPTS::from_usize(pixels.data.nrows()), U3::from_usize(3), )); let origin = &mut result.data; for i in 0..pixels.data.nrows() { let u = pixels.data[(i, 0)].clone(); let v = pixels.data[(i, 1)].clone(); let x: R = (u - self.params.cx.clone()) / self.params.sx.clone(); let y: R = (v - self.params.cy.clone()) / self.params.sy.clone(); origin[(i, 0)] = x; origin[(i, 1)] = y; origin[(i, 2)] = zero.clone(); } result } fn camera_to_pixel<IN, NPTS>( &self, camera: &Points<CameraFrame, R, NPTS, IN>, ) -> Pixels<R, NPTS, Owned<R, NPTS, U2>> where IN: Storage<R, NPTS, U3>, NPTS: Dim, DefaultAllocator: Allocator<R, NPTS, U2>, { let mut result = Pixels::new(OMatrix::zeros_generic( NPTS::from_usize(camera.data.nrows()), U2::from_usize(2), )); for i in 0..camera.data.nrows() { result.data[(i, 0)] = camera.data[(i, 0)].clone() * self.params.sx.clone() + self.params.cx.clone(); result.data[(i, 1)] = camera.data[(i, 1)].clone() * self.params.sy.clone() + self.params.cy.clone(); } result } } #[cfg(test)] mod tests { use nalgebra::Vector3; use super::{IntrinsicParametersOrthographic, OrthographicParams}; use crate::camera::{roundtrip_camera, Camera}; use crate::extrinsics::ExtrinsicParameters; use crate::intrinsic_test_utils::roundtrip_intrinsics; #[test] fn roundtrip() { let params = OrthographicParams { sx: 100.0, sy: 102.0, cx: 321.0, cy: 239.9, }; let cam: IntrinsicParametersOrthographic<_> = params.into(); roundtrip_intrinsics(&cam, 640, 480, 5, 0, nalgebra::convert(1e-10)); let extrinsics = ExtrinsicParameters::from_view( &Vector3::new(1.2, 3.4, 5.6), &Vector3::new(2.2, 3.4, 5.6), &nalgebra::Unit::new_normalize(Vector3::new(0.0, 0.0, 1.0)), ); let full_cam = Camera::new(cam, extrinsics); roundtrip_camera(full_cam, 640, 480, 5, 0, nalgebra::convert(1e-10)); } #[test] #[cfg(feature = "serde-serialize")] fn test_serde() { let params = OrthographicParams { sx: 100.0, sy: 102.0, cx: 321.0, cy: 239.9, }; let expected: IntrinsicParametersOrthographic<_> = params.into(); let buf = serde_json::to_string(&expected).unwrap(); let actual: IntrinsicParametersOrthographic<f64> = serde_json::from_str(&buf).unwrap(); assert!(expected == actual); } }
use nalgebra::{ allocator::Allocator, base::storage::{Owned, Storage}, convert, DefaultAllocator, Dim, OMatrix, RealField, U2, U3, }; #[cfg(feature = "serde-serialize")] use serde::{Deserialize, Serialize}; use crate::{ coordinate_system::CameraFrame, Bundle, IntrinsicParameters, Pixels, Points, RayBundle, }; use crate::ray_bundle_types::SharedDirectionRayBundle; #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))] pub struct OrthographicParams<R: RealField> { pub sx: R, pub sy: R, pub cx: R, pub cy: R, } impl<R: RealField> From<OrthographicParams<R>> for IntrinsicParametersOrthographic<R> { #[inline] fn from(params: OrthographicParams<R>) -> Self { Self { params } } } #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))] pub struct IntrinsicParametersOrthographic<R: RealField> { params: OrthographicParams<R>, } impl<R> IntrinsicParameters<R> for IntrinsicParametersOrthographic<R> where R: RealField, { type BundleType = SharedDirectionRayBundle<R>; fn pixel_to_camera<IN, NPTS>( &self, pixels: &Pixels<R, NPTS, IN>, ) -> RayBundle<CameraFrame, Self::BundleType, R, NPTS, Owned<R, NPTS, U3>> where Self::BundleType: Bundle<R>, IN: Storage<R, NPTS, U2>, NPTS: Dim, DefaultAllocator: Allocator<R, NPTS, U3>, { let zero: R = convert(0.0); let mut result = RayBundle::new_shared_plusz_direction(OMatrix::zeros_generic( NPTS::from_usize(pixels.data.nrows()), U3::from_usize(3), )); let origin = &mut result.data; for i in 0..pixels.data.nrows() { let u = pixels.data[(i, 0)].clone(); let v = pixels.data[(i, 1)].clone(); let x: R = (u - self.params.cx.clone()) / self.params.sx.clone(); let y: R = (v - self.params.cy.clone()) / self.params.sy.clone(); origin[(i, 0)] = x; origin[(i, 1)] = y; origin[(i, 2)] = zero.clone(); } result } fn camera_to_pixel<IN, NPTS>( &self, camera: &Points<CameraFrame, R, NPTS, IN>, ) -> Pixels<R, NPTS, Owned<R, NPTS, U2>> where IN: Storage<R, NPTS, U3>, NPTS: Dim, DefaultAllocator: Allocator<R, NPTS, U2>, { let mut result = Pixels::new(OMatrix::zeros_generic( NPTS::from_usize(camera.data.nrows()), U2::from_usize(2), )); for i in 0..camera.data.nrows() { result.data[(i, 0)] = camera.data[(i, 0)].clone() * self.params.sx.clone() + self.params.cx.clone(); result.data[(i, 1)] = camera.data[(i, 1)].clone() * self.params.sy.clone() + self.params.cy.clone(); } result } } #[cfg(test)] mod tests { use nalgebra::Vector3; use super::{IntrinsicParametersOrthographic, OrthographicParams}; use crate::camera::{roundtrip_camera, Camera}; use crate::extrinsics::ExtrinsicParameters; use crate::intrinsic_test_utils::roundtrip_intrinsics; #[test]
#[test] #[cfg(feature = "serde-serialize")] fn test_serde() { let params = OrthographicParams { sx: 100.0, sy: 102.0, cx: 321.0, cy: 239.9, }; let expected: IntrinsicParametersOrthographic<_> = params.into(); let buf = serde_json::to_string(&expected).unwrap(); let actual: IntrinsicParametersOrthographic<f64> = serde_json::from_str(&buf).unwrap(); assert!(expected == actual); } }
fn roundtrip() { let params = OrthographicParams { sx: 100.0, sy: 102.0, cx: 321.0, cy: 239.9, }; let cam: IntrinsicParametersOrthographic<_> = params.into(); roundtrip_intrinsics(&cam, 640, 480, 5, 0, nalgebra::convert(1e-10)); let extrinsics = ExtrinsicParameters::from_view( &Vector3::new(1.2, 3.4, 5.6), &Vector3::new(2.2, 3.4, 5.6), &nalgebra::Unit::new_normalize(Vector3::new(0.0, 0.0, 1.0)), ); let full_cam = Camera::new(cam, extrinsics); roundtrip_camera(full_cam, 640, 480, 5, 0, nalgebra::convert(1e-10)); }
function_block-full_function
[ { "content": "#[cfg(test)]\n\npub fn roundtrip_camera<R, I>(\n\n cam: Camera<R, I>,\n\n width: usize,\n\n height: usize,\n\n step: usize,\n\n border: usize,\n\n eps: R,\n\n) where\n\n R: RealField,\n\n I: IntrinsicParameters<R>,\n\n I::BundleType: Bundle<R>,\n\n{\n\n let pixels = crate::intrinsic_test_utils::generate_uv_raw(width, height, step, border);\n\n\n\n let world_coords = cam.pixel_to_world(&pixels);\n\n let world_coords_points = world_coords.point_on_ray();\n\n\n\n // project back to pixel coordinates\n\n let pixel_actual = cam.world_to_pixel(&world_coords_points);\n\n approx::assert_abs_diff_eq!(pixels.data, pixel_actual.data, epsilon = convert(eps));\n\n}\n\n\n", "file_path": "src/camera.rs", "rank": 0, "score": 136172.98602122226 }, { "content": "// Calculate angle of quaternion\n\n///\n\n/// This is the implementation from prior to\n\n/// https://github.com/rustsim/nalgebra/commit/74aefd9c23dadd12ee654c7d0206b0a96d22040c\n\nfn my_quat_angle<R: RealField>(quat: &nalgebra::UnitQuaternion<R>) -> R {\n\n let w = quat.quaternion().scalar().abs();\n\n\n\n // Handle inaccuracies that make break `.acos`.\n\n if w >= R::one() {\n\n R::zero()\n\n } else {\n\n w.acos() * convert(2.0f64)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n #[test]\n\n #[cfg(feature = \"serde-serialize\")]\n\n fn test_serde() {\n\n use nalgebra::{Unit, Vector3};\n\n\n\n use super::PerspectiveParams;\n\n use crate::{Camera, ExtrinsicParameters, IntrinsicParametersPerspective};\n", "file_path": "src/camera.rs", "rank": 1, "score": 122426.87178791224 }, { "content": "/// Test roundtrip projection from pixels to camera rays for an intrinsic camera model.\n\n///\n\n/// Generate pixel coordinates, project them to rays, convert to points on the\n\n/// rays, convert the points back to pixels, and then compare with the original\n\n/// pixel coordinates.\n\npub fn roundtrip_intrinsics<R, CAM>(\n\n cam: &CAM,\n\n width: usize,\n\n height: usize,\n\n step: usize,\n\n border: usize,\n\n eps: R,\n\n) where\n\n R: RealField,\n\n CAM: IntrinsicParameters<R>,\n\n CAM::BundleType: Bundle<R>,\n\n{\n\n let pixels = generate_uv_raw(width, height, step, border);\n\n\n\n let camcoords = cam.pixel_to_camera(&pixels);\n\n let camera_coords_points = camcoords.point_on_ray();\n\n\n\n // project back to pixel coordinates\n\n let pixel_actual = cam.camera_to_pixel(&camera_coords_points);\n\n approx::assert_abs_diff_eq!(pixels.data, pixel_actual.data, epsilon = convert(eps));\n\n}\n", "file_path": "src/intrinsic_test_utils.rs", "rank": 2, "score": 115458.93551733317 }, { "content": "#[allow(clippy::many_single_char_names)]\n\nfn pmat2cam_center<R, S>(p: &Matrix<R, U3, U4, S>) -> Point3<R>\n\nwhere\n\n R: RealField,\n\n S: Storage<R, U3, U4> + Clone,\n\n{\n\n let x = p.clone().remove_column(0).determinant();\n\n let y = -p.clone().remove_column(1).determinant();\n\n let z = p.clone().remove_column(2).determinant();\n\n let w = -p.clone().remove_column(3).determinant();\n\n Point3::from(Vector3::new(x / w.clone(), y / w.clone(), z / w))\n\n}\n\n\n", "file_path": "src/camera.rs", "rank": 3, "score": 108975.94157834267 }, { "content": "/// perform RQ decomposition and return results as right-handed quaternion and intrinsics matrix\n\nfn rq_decomposition<R: RealField>(\n\n orig: Matrix3<R>,\n\n) -> Result<(UnitQuaternion<R>, Matrix3<R>), Error> {\n\n let (mut intrin, mut q) = rq(orig);\n\n let zero: R = convert(0.0);\n\n for i in 0..3 {\n\n if intrin[(i, i)] < zero {\n\n for j in 0..3 {\n\n intrin[(j, i)] = -intrin[(j, i)].clone();\n\n q[(i, j)] = -q[(i, j)].clone();\n\n }\n\n }\n\n }\n\n\n\n match right_handed_rotation_quat_new(&q) {\n\n Ok(rquat) => Ok((rquat, intrin)),\n\n Err(error) => {\n\n match error {\n\n Error::InvalidRotationMatrix => {\n\n // convert left-handed rotation to right-handed rotation\n", "file_path": "src/camera.rs", "rank": 4, "score": 105463.62763693056 }, { "content": "#[allow(non_snake_case)]\n\nfn rq<R: RealField>(A: Matrix3<R>) -> (Matrix3<R>, Matrix3<R>) {\n\n let zero: R = convert(0.0);\n\n let one: R = convert(1.0);\n\n\n\n // see https://math.stackexchange.com/a/1640762\n\n #[rustfmt::skip]\n\n let P = Matrix3::<R>::new(\n\n zero.clone(), zero.clone(), one.clone(), // row 1\n\n zero.clone(), one.clone(), zero.clone(), // row 2\n\n one, zero.clone(), zero, // row 3\n\n );\n\n let Atilde = P.clone() * A;\n\n\n\n let (Qtilde, Rtilde) = {\n\n let qrm = nalgebra::linalg::QR::new(Atilde.transpose());\n\n (qrm.q(), qrm.r())\n\n };\n\n let Q = P.clone() * Qtilde.transpose();\n\n let R = P.clone() * Rtilde.transpose() * P;\n\n (R, Q)\n\n}\n\n\n", "file_path": "src/camera.rs", "rank": 5, "score": 101123.39700944631 }, { "content": "/// Specifies operations which any RayBundle must implement.\n\npub trait Bundle<R>\n\nwhere\n\n R: RealField,\n\n{\n\n /// Return a single ray from a `RayBundle` with exactly one ray.\n\n fn to_single_ray<Coords>(&self, self_data: &SMatrix<R, 1, 3>) -> Ray<Coords, R>\n\n where\n\n Coords: CoordinateSystem;\n\n\n\n /// Get directions of each ray in bundle.\n\n ///\n\n /// This can be inefficient, because when not every ray has a different\n\n /// direction (which is the case for the `SharedDirectionRayBundle` type),\n\n /// this will nevertheless copy the single direction `NPTS` times.\n\n fn directions<NPTS, StorageIn>(\n\n &self,\n\n self_data: &Matrix<R, NPTS, U3, StorageIn>,\n\n ) -> Matrix<R, NPTS, U3, Owned<R, NPTS, U3>>\n\n where\n\n NPTS: DimName,\n", "file_path": "src/lib.rs", "rank": 6, "score": 100532.62165853298 }, { "content": "/// convert a 3x3 matrix into a valid right-handed rotation\n\nfn right_handed_rotation_quat_new<R: RealField>(\n\n orig: &Matrix3<R>,\n\n) -> Result<UnitQuaternion<R>, Error> {\n\n let r1 = orig.clone();\n\n let rotmat = Rotation3::from_matrix_unchecked(r1);\n\n let rquat = UnitQuaternion::from_rotation_matrix(&rotmat);\n\n if !is_right_handed_rotation_quat(&rquat) {\n\n return Err(Error::InvalidRotationMatrix);\n\n }\n\n Ok(rquat)\n\n}\n\n\n\n/// Check for valid right-handed rotation.\n\n///\n\n/// Converts quaternion to rotation matrix and back again to quat then comparing\n\n/// quats. Probably there is a much faster and better way.\n\npub(crate) fn is_right_handed_rotation_quat<R: RealField>(rquat: &UnitQuaternion<R>) -> bool {\n\n let rotmat2 = rquat.clone().to_rotation_matrix();\n\n let rquat2 = UnitQuaternion::from_rotation_matrix(&rotmat2);\n\n let delta = rquat.rotation_to(&rquat2);\n\n let angle = my_quat_angle(&delta);\n\n let epsilon = R::default_epsilon() * convert(1e5);\n\n angle.abs() <= epsilon\n\n}\n\n\n\n/// get the camera center from a 3x4 camera projection matrix\n", "file_path": "src/camera.rs", "rank": 7, "score": 97042.40713319693 }, { "content": "#[allow(non_snake_case)]\n\npub fn best_intersection_of_rays<Coords, R>(\n\n rays: &[Ray<Coords, R>],\n\n) -> Result<SinglePoint<Coords, R>, Error>\n\nwhere\n\n Coords: CoordinateSystem,\n\n R: RealField,\n\n DefaultAllocator: Allocator<R, Dynamic, U3>,\n\n DefaultAllocator: Allocator<R, U1, Dynamic>,\n\n DefaultAllocator: Allocator<R, U1, U3>,\n\n{\n\n if rays.len() < 2 {\n\n return Err(Error::MinimumTwoRaysNeeded);\n\n }\n\n\n\n let npts = Dynamic::new(rays.len());\n\n let u1 = U1::from_usize(1);\n\n let u3 = U3::from_usize(3);\n\n\n\n let mut line_dirs = OMatrix::<R, Dynamic, U3>::zeros_generic(npts, u3);\n\n let mut line_points = OMatrix::<R, Dynamic, U3>::zeros_generic(npts, u3);\n", "file_path": "src/ray_intersection.rs", "rank": 8, "score": 95032.78494146772 }, { "content": "#[cfg(feature = \"serde-serialize\")]\n\nfn _test_extrinsics_is_serialize() {\n\n // Compile-time test to ensure ExtrinsicParameters implements Serialize trait.\n\n fn implements<T: serde::Serialize>() {}\n\n implements::<ExtrinsicParameters<f64>>();\n\n}\n\n\n", "file_path": "src/extrinsics.rs", "rank": 9, "score": 91536.7480978276 }, { "content": "#[cfg(feature = \"serde-serialize\")]\n\nfn _test_is_deserialize() {\n\n // Compile-time test to ensure IntrinsicParametersPerspective implements Deserialize trait.\n\n fn implements<'de, T: serde::Deserialize<'de>>() {}\n\n implements::<IntrinsicParametersPerspective<f64>>();\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use nalgebra::{SMatrix, Vector3};\n\n\n\n use super::{IntrinsicParametersPerspective, PerspectiveParams};\n\n use crate::camera::{roundtrip_camera, Camera};\n\n use crate::extrinsics::ExtrinsicParameters;\n\n use crate::intrinsic_test_utils::roundtrip_intrinsics;\n\n use crate::Points;\n\n\n\n #[test]\n\n fn roundtrip() {\n\n let params = PerspectiveParams {\n\n fx: 100.0,\n", "file_path": "src/intrinsics_perspective.rs", "rank": 10, "score": 91536.7480978276 }, { "content": "#[cfg(feature = \"serde-serialize\")]\n\nfn _test_extrinsics_is_deserialize() {\n\n // Compile-time test to ensure ExtrinsicParameters implements Deserialize trait.\n\n fn implements<'de, T: serde::Deserialize<'de>>() {}\n\n implements::<ExtrinsicParameters<f64>>();\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use nalgebra::convert as c;\n\n\n\n #[test]\n\n fn roundtrip_f64() {\n\n roundtrip_generic::<f64>(1e-10)\n\n }\n\n\n\n #[test]\n\n fn roundtrip_f32() {\n\n roundtrip_generic::<f32>(1e-5)\n\n }\n", "file_path": "src/extrinsics.rs", "rank": 11, "score": 91536.7480978276 }, { "content": "#[cfg(feature = \"serde-serialize\")]\n\nfn _test_is_serialize() {\n\n // Compile-time test to ensure IntrinsicParametersPerspective implements Serialize trait.\n\n fn implements<T: serde::Serialize>() {}\n\n implements::<IntrinsicParametersPerspective<f64>>();\n\n}\n\n\n", "file_path": "src/intrinsics_perspective.rs", "rank": 12, "score": 91536.7480978276 }, { "content": "fn my_pinv<R: RealField>(m: &SMatrix<R, 3, 3>) -> Result<SMatrix<R, 3, 3>, Error> {\n\n Ok(\n\n na::linalg::SVD::try_new(m.clone(), true, true, na::convert(1e-7), 100)\n\n .ok_or(Error::SvdFailed)?\n\n .pseudo_inverse(na::convert(1.0e-7))\n\n .unwrap(),\n\n )\n\n // The unwrap() above is safe because, as of nalgebra 0.19, this could only error if the SVD has not been computed.\n\n // But this is not possible here, so the unwrap() should never result in a panic.\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use nalgebra::Vector3;\n\n\n\n use crate::{Camera, ExtrinsicParameters, IntrinsicParametersPerspective, PerspectiveParams};\n\n\n\n use super::*;\n\n\n\n #[test]\n", "file_path": "src/ray_intersection.rs", "rank": 13, "score": 89463.55211542993 }, { "content": "/// A geometric model of camera coordinates to pixels (and vice versa).\n\npub trait IntrinsicParameters<R>: std::fmt::Debug + Clone\n\nwhere\n\n R: RealField,\n\n{\n\n /// What type of ray bundle is returned when projecting pixels to rays.\n\n type BundleType;\n\n\n\n /// project pixels to camera coords\n\n fn pixel_to_camera<IN, NPTS>(\n\n &self,\n\n pixels: &Pixels<R, NPTS, IN>,\n\n ) -> RayBundle<coordinate_system::CameraFrame, Self::BundleType, R, NPTS, Owned<R, NPTS, U3>>\n\n where\n\n Self::BundleType: Bundle<R>,\n\n IN: Storage<R, NPTS, U2>,\n\n NPTS: Dim,\n\n DefaultAllocator: Allocator<R, U1, U2>, // needed to make life easy for implementors\n\n DefaultAllocator: Allocator<R, NPTS, U2>, // needed to make life easy for implementors\n\n DefaultAllocator: Allocator<R, NPTS, U3>;\n\n\n", "file_path": "src/lib.rs", "rank": 14, "score": 84438.46753649716 }, { "content": "#[test]\n\nfn test_jacobian_perspective() {\n\n use nalgebra::{OMatrix, RowVector2, RowVector3, Unit, Vector3};\n\n\n\n use super::*;\n\n use crate::{Camera, ExtrinsicParameters, IntrinsicParametersPerspective};\n\n\n\n // create a perspective camera\n\n let params = PerspectiveParams {\n\n fx: 100.0,\n\n fy: 102.0,\n\n skew: 0.1,\n\n cx: 321.0,\n\n cy: 239.9,\n\n };\n\n\n\n let intrinsics: IntrinsicParametersPerspective<_> = params.into();\n\n\n\n let camcenter = Vector3::new(10.0, 0.0, 10.0);\n\n let lookat = Vector3::new(0.0, 0.0, 0.0);\n\n let up = Unit::new_normalize(Vector3::new(0.0, 0.0, 1.0));\n", "file_path": "src/linearize.rs", "rank": 15, "score": 66591.21310308106 }, { "content": "fn main() -> Result<(), std::io::Error> {\n\n // Create cube vertices in the world coordinate frame.\n\n let world_coords = Points::<WorldFrame, _, _, _>::new(SMatrix::<f64, 8, 3>::from_row_slice(&[\n\n -1.0, -1.0, -1.0, // v1\n\n 1.0, -1.0, -1.0, // v2\n\n 1.0, 1.0, -1.0, // v3\n\n -1.0, 1.0, -1.0, // v4\n\n -1.0, -1.0, 1.0, // v5\n\n 1.0, -1.0, 1.0, // v6\n\n 1.0, 1.0, 1.0, // v7\n\n -1.0, 1.0, 1.0, // v8\n\n ]));\n\n let edges = [\n\n (0, 1),\n\n (1, 2),\n\n (2, 3),\n\n (3, 0),\n\n (4, 5),\n\n (5, 6),\n\n (6, 7),\n", "file_path": "examples/render-cube.rs", "rank": 16, "score": 62875.40159167157 }, { "content": "/// Create an orthographic camera.\n\nfn get_ortho_cam() -> Camera<f64, IntrinsicParametersOrthographic<f64>> {\n\n let intrinsics = OrthographicParams {\n\n sx: 100.0,\n\n sy: 102.0,\n\n cx: 321.0,\n\n cy: 239.9,\n\n };\n\n\n\n // Set extrinsic parameters.\n\n let camcenter = Vector3::new(10.0, 3.0, 5.0);\n\n let lookat = Vector3::new(0.0, 0.0, 0.0);\n\n let up = Unit::new_normalize(Vector3::new(0.0, 0.0, 1.0));\n\n let pose = ExtrinsicParameters::from_view(&camcenter, &lookat, &up);\n\n\n\n // Create camera with both intrinsic and extrinsic parameters.\n\n Camera::new(intrinsics.into(), pose)\n\n}\n\n\n", "file_path": "examples/render-cube.rs", "rank": 17, "score": 55875.500102336795 }, { "content": "/// Create a perspective camera.\n\nfn get_perspective_cam() -> Camera<f64, IntrinsicParametersPerspective<f64>> {\n\n // Set intrinsic parameters\n\n let intrinsics = PerspectiveParams {\n\n fx: 100.0,\n\n fy: 100.0,\n\n skew: 0.0,\n\n cx: 640.0,\n\n cy: 480.0,\n\n };\n\n\n\n // Set extrinsic parameters.\n\n let camcenter = Vector3::new(10.0, 3.0, 5.0);\n\n let lookat = Vector3::new(0.0, 0.0, 0.0);\n\n let up = Unit::new_normalize(Vector3::new(0.0, 0.0, 1.0));\n\n let pose = ExtrinsicParameters::from_view(&camcenter, &lookat, &up);\n\n\n\n // Create camera with both intrinsic and extrinsic parameters.\n\n Camera::new(intrinsics.into(), pose)\n\n}\n\n\n", "file_path": "examples/render-cube.rs", "rank": 18, "score": 55875.500102336795 }, { "content": " result.data[(i, j)] =\n\n center[j].clone() + scale.clone() * directions[(i, j)].clone();\n\n }\n\n }\n\n result\n\n }\n\n\n\n fn to_pose<NPTS, StorageIn, OutFrame>(\n\n &self,\n\n pose: Isometry3<R>,\n\n self_data: &Matrix<R, NPTS, U3, StorageIn>,\n\n ) -> RayBundle<OutFrame, Self, R, NPTS, Owned<R, NPTS, U3>>\n\n where\n\n NPTS: Dim,\n\n StorageIn: Storage<R, NPTS, U3>,\n\n OutFrame: CoordinateSystem,\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n\n {\n\n let bundle_type = Self::new_shared_zero_origin();\n\n let mut reposed = RayBundle::new(\n", "file_path": "src/ray_bundle_types.rs", "rank": 19, "score": 51819.391084191746 }, { "content": "use nalgebra::{OMatrix, SMatrix};\n\n\n\nuse crate::*;\n\n\n\n#[cfg(feature = \"serde-serialize\")]\n\nuse serde::{Deserialize, Serialize};\n\n\n\n/// A bundle of rays with the same arbitrary origin\n\n#[derive(Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serde-serialize\", derive(Serialize, Deserialize))]\n\npub struct SharedOriginRayBundle<R: RealField> {\n\n center: Point3<R>,\n\n}\n\n\n\nimpl<R> SharedOriginRayBundle<R>\n\nwhere\n\n R: RealField,\n\n{\n\n /// Create a new SharedOriginRayBundle with origin (center) at zero.\n\n #[inline]\n", "file_path": "src/ray_bundle_types.rs", "rank": 20, "score": 51818.4778008362 }, { "content": " pub fn new_shared_zero_origin() -> Self {\n\n // center is at (0,0,0)\n\n let zero: R = nalgebra::convert(0.0);\n\n Self {\n\n center: Point3::new(zero.clone(), zero.clone(), zero),\n\n }\n\n }\n\n}\n\n\n\nimpl<R> Bundle<R> for SharedOriginRayBundle<R>\n\nwhere\n\n R: RealField,\n\n{\n\n #[inline]\n\n fn to_single_ray<Coords>(&self, self_data: &SMatrix<R, 1, 3>) -> Ray<Coords, R>\n\n where\n\n Coords: CoordinateSystem,\n\n {\n\n Ray {\n\n direction: self_data.clone(),\n", "file_path": "src/ray_bundle_types.rs", "rank": 21, "score": 51815.05730868795 }, { "content": " for j in 0..3 {\n\n result[(i, j)] = self_data[(i, j)].clone();\n\n }\n\n }\n\n result\n\n }\n\n\n\n fn point_on_ray<NPTS, StorageIn, OutFrame>(\n\n &self,\n\n centers: &Matrix<R, NPTS, U3, StorageIn>,\n\n ) -> Points<OutFrame, R, NPTS, Owned<R, NPTS, U3>>\n\n where\n\n Self: Sized,\n\n NPTS: Dim,\n\n StorageIn: Storage<R, NPTS, U3>,\n\n OutFrame: CoordinateSystem,\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n\n {\n\n let mut result = Points::new(OMatrix::zeros_generic(\n\n NPTS::from_usize(centers.nrows()),\n", "file_path": "src/ray_bundle_types.rs", "rank": 22, "score": 51814.27521371419 }, { "content": " result\n\n }\n\n\n\n fn point_on_ray<NPTS, StorageIn, OutFrame>(\n\n &self,\n\n directions: &Matrix<R, NPTS, U3, StorageIn>,\n\n ) -> Points<OutFrame, R, NPTS, Owned<R, NPTS, U3>>\n\n where\n\n Self: Sized,\n\n NPTS: Dim,\n\n StorageIn: Storage<R, NPTS, U3>,\n\n OutFrame: CoordinateSystem,\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n\n {\n\n let mut result = Points::new(OMatrix::zeros_generic(\n\n NPTS::from_usize(directions.nrows()),\n\n U3::from_usize(3),\n\n ));\n\n let center = [\n\n self.center[0].clone(),\n", "file_path": "src/ray_bundle_types.rs", "rank": 23, "score": 51813.71449631355 }, { "content": " }\n\n result\n\n }\n\n\n\n fn centers<NPTS, StorageIn>(\n\n &self,\n\n self_data: &Matrix<R, NPTS, U3, StorageIn>,\n\n ) -> Matrix<R, NPTS, U3, Owned<R, NPTS, U3>>\n\n where\n\n NPTS: nalgebra::DimName,\n\n StorageIn: Storage<R, NPTS, U3>,\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n\n {\n\n // TODO: do this more smartly/efficiently\n\n let mut result = nalgebra::OMatrix::<R, NPTS, U3>::zeros();\n\n for i in 0..self_data.nrows() {\n\n for j in 0..3 {\n\n result[(i, j)] = self.center[j].clone();\n\n }\n\n }\n", "file_path": "src/ray_bundle_types.rs", "rank": 24, "score": 51812.460173182175 }, { "content": " for i in 0..self_data.nrows() {\n\n for j in 0..3 {\n\n result[(i, j)] = self.direction[j].clone();\n\n }\n\n }\n\n result\n\n }\n\n\n\n fn centers<NPTS, StorageIn>(\n\n &self,\n\n self_data: &Matrix<R, NPTS, U3, StorageIn>,\n\n ) -> Matrix<R, NPTS, U3, Owned<R, NPTS, U3>>\n\n where\n\n NPTS: nalgebra::DimName,\n\n StorageIn: Storage<R, NPTS, U3>,\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n\n {\n\n // TODO: do this more smartly/efficiently\n\n let mut result = nalgebra::OMatrix::<R, NPTS, U3>::zeros();\n\n for i in 0..self_data.nrows() {\n", "file_path": "src/ray_bundle_types.rs", "rank": 25, "score": 51812.18931822467 }, { "content": " self.center[1].clone(),\n\n self.center[2].clone(),\n\n ];\n\n for i in 0..directions.nrows() {\n\n for j in 0..3 {\n\n result.data[(i, j)] = center[j].clone() + directions[(i, j)].clone();\n\n }\n\n }\n\n result\n\n }\n\n\n\n fn point_on_ray_at_distance<NPTS, StorageIn, OutFrame>(\n\n &self,\n\n directions: &Matrix<R, NPTS, U3, StorageIn>,\n\n distance: R,\n\n ) -> Points<OutFrame, R, NPTS, Owned<R, NPTS, U3>>\n\n where\n\n Self: Sized,\n\n NPTS: Dim,\n\n StorageIn: Storage<R, NPTS, U3>,\n", "file_path": "src/ray_bundle_types.rs", "rank": 26, "score": 51811.314010433554 }, { "content": " center: self.center.coords.transpose(),\n\n c: std::marker::PhantomData,\n\n }\n\n }\n\n\n\n fn directions<NPTS, StorageIn>(\n\n &self,\n\n self_data: &Matrix<R, NPTS, U3, StorageIn>,\n\n ) -> Matrix<R, NPTS, U3, Owned<R, NPTS, U3>>\n\n where\n\n NPTS: nalgebra::DimName,\n\n StorageIn: Storage<R, NPTS, U3>,\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n\n {\n\n // TODO: do this more smartly/efficiently\n\n let mut result = nalgebra::OMatrix::<R, NPTS, U3>::zeros();\n\n for i in 0..self_data.nrows() {\n\n for j in 0..3 {\n\n result[(i, j)] = self_data[(i, j)].clone();\n\n }\n", "file_path": "src/ray_bundle_types.rs", "rank": 27, "score": 51811.087994732385 }, { "content": " Coords: CoordinateSystem,\n\n {\n\n Ray {\n\n direction: self.direction.transpose(),\n\n center: self_data.clone(),\n\n c: std::marker::PhantomData,\n\n }\n\n }\n\n\n\n fn directions<NPTS, StorageIn>(\n\n &self,\n\n self_data: &Matrix<R, NPTS, U3, StorageIn>,\n\n ) -> Matrix<R, NPTS, U3, Owned<R, NPTS, U3>>\n\n where\n\n NPTS: nalgebra::DimName,\n\n StorageIn: Storage<R, NPTS, U3>,\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n\n {\n\n // TODO: do this more smartly/efficiently\n\n let mut result = nalgebra::OMatrix::<R, NPTS, U3>::zeros();\n", "file_path": "src/ray_bundle_types.rs", "rank": 28, "score": 51810.1186098261 }, { "content": " where\n\n Self: Sized,\n\n NPTS: Dim,\n\n StorageIn: Storage<R, NPTS, U3>,\n\n OutFrame: CoordinateSystem,\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n\n {\n\n let mut result = Points::new(OMatrix::zeros_generic(\n\n NPTS::from_usize(centers.nrows()),\n\n U3::from_usize(3),\n\n ));\n\n\n\n let d = &self.direction;\n\n let dx = d[0].clone();\n\n let dy = d[1].clone();\n\n let dz = d[2].clone();\n\n let mag2 = dx.clone() * dx.clone() + dy.clone() * dy.clone() + dz.clone() * dz.clone();\n\n let mag = mag2.sqrt();\n\n let scale = distance / mag;\n\n let dist_dir = Vector3::new(scale.clone() * dx, scale.clone() * dy, scale * dz);\n", "file_path": "src/ray_bundle_types.rs", "rank": 29, "score": 51809.65576233619 }, { "content": "\n\n for i in 0..centers.nrows() {\n\n for j in 0..3 {\n\n result.data[(i, j)] = dist_dir[j].clone() + centers[(i, j)].clone();\n\n }\n\n }\n\n result\n\n }\n\n\n\n fn to_pose<NPTS, StorageIn, OutFrame>(\n\n &self,\n\n pose: Isometry3<R>,\n\n self_data: &Matrix<R, NPTS, U3, StorageIn>,\n\n ) -> RayBundle<OutFrame, Self, R, NPTS, Owned<R, NPTS, U3>>\n\n where\n\n NPTS: Dim,\n\n StorageIn: Storage<R, NPTS, U3>,\n\n OutFrame: CoordinateSystem,\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n\n {\n", "file_path": "src/ray_bundle_types.rs", "rank": 30, "score": 51809.64665817562 }, { "content": " let bundle_type = Self::new_plusz_shared_direction();\n\n\n\n let mut reposed = RayBundle::new(\n\n bundle_type,\n\n OMatrix::zeros_generic(NPTS::from_usize(self_data.nrows()), U3::from_usize(3)),\n\n );\n\n\n\n // transform single bundle direction\n\n let new_direction = pose.transform_vector(&self.direction);\n\n\n\n // transform multiple bundle origins\n\n for i in 0..self_data.nrows() {\n\n let orig_point = Point3 {\n\n coords: self_data.row(i).transpose(),\n\n };\n\n let new_point = pose.transform_point(&orig_point);\n\n for j in 0..3 {\n\n reposed.data[(i, j)] = new_point[j].clone();\n\n }\n\n }\n\n\n\n reposed.bundle_type = SharedDirectionRayBundle {\n\n direction: new_direction,\n\n };\n\n reposed\n\n }\n\n}\n", "file_path": "src/ray_bundle_types.rs", "rank": 31, "score": 51808.01957949661 }, { "content": "/// A bundle of rays with the same arbitrary direction\n\n#[derive(Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serde-serialize\", derive(Serialize, Deserialize))]\n\npub struct SharedDirectionRayBundle<R: RealField> {\n\n direction: Vector3<R>,\n\n}\n\n\n\nimpl<R: RealField> SharedDirectionRayBundle<R> {\n\n /// Create a new SharedDirectionRayBundle with direction +z.\n\n pub fn new_plusz_shared_direction() -> Self {\n\n // in +z direction\n\n Self {\n\n direction: Vector3::new(R::zero(), R::zero(), R::one()),\n\n }\n\n }\n\n}\n\n\n\nimpl<R: RealField> Bundle<R> for SharedDirectionRayBundle<R> {\n\n fn to_single_ray<Coords>(&self, self_data: &SMatrix<R, 1, 3>) -> Ray<Coords, R>\n\n where\n", "file_path": "src/ray_bundle_types.rs", "rank": 32, "score": 51807.299392168774 }, { "content": " U3::from_usize(3),\n\n ));\n\n let direction = [\n\n self.direction[0].clone(),\n\n self.direction[1].clone(),\n\n self.direction[2].clone(),\n\n ];\n\n for i in 0..centers.nrows() {\n\n for j in 0..3 {\n\n result.data[(i, j)] = direction[j].clone() + centers[(i, j)].clone();\n\n }\n\n }\n\n result\n\n }\n\n\n\n fn point_on_ray_at_distance<NPTS, StorageIn, OutFrame>(\n\n &self,\n\n centers: &Matrix<R, NPTS, U3, StorageIn>,\n\n distance: R,\n\n ) -> Points<OutFrame, R, NPTS, Owned<R, NPTS, U3>>\n", "file_path": "src/ray_bundle_types.rs", "rank": 33, "score": 51806.27216805993 }, { "content": " bundle_type,\n\n OMatrix::zeros_generic(NPTS::from_usize(self_data.nrows()), U3::from_usize(3)),\n\n );\n\n // transform single bundle center point\n\n let new_center = pose.transform_point(&self.center);\n\n\n\n // transform multiple bundle directions\n\n for i in 0..self_data.nrows() {\n\n let orig_vec = self_data.row(i).transpose();\n\n let new_vec = pose.transform_vector(&orig_vec);\n\n for j in 0..3 {\n\n reposed.data[(i, j)] = new_vec[j].clone();\n\n }\n\n }\n\n\n\n reposed.bundle_type = SharedOriginRayBundle { center: new_center };\n\n reposed\n\n }\n\n}\n\n\n", "file_path": "src/ray_bundle_types.rs", "rank": 34, "score": 51803.69948324986 }, { "content": " OutFrame: CoordinateSystem,\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n\n {\n\n let mut result = Points::new(OMatrix::zeros_generic(\n\n NPTS::from_usize(directions.nrows()),\n\n U3::from_usize(3),\n\n ));\n\n let center = [\n\n self.center[0].clone(),\n\n self.center[1].clone(),\n\n self.center[2].clone(),\n\n ];\n\n for i in 0..directions.nrows() {\n\n let dx = directions[(i, 0)].clone();\n\n let dy = directions[(i, 1)].clone();\n\n let dz = directions[(i, 2)].clone();\n\n let mag2 = dx.clone() * dx + dy.clone() * dy + dz.clone() * dz;\n\n let mag = mag2.sqrt();\n\n let scale = distance.clone() / mag;\n\n for j in 0..3 {\n", "file_path": "src/ray_bundle_types.rs", "rank": 35, "score": 51802.844693236715 }, { "content": "fn main() {\n\n use cam_geom::*;\n\n use nalgebra::{Matrix2x3, Unit, Vector3};\n\n\n\n // Create two points in the world coordinate frame.\n\n let world_coords = Points::new(Matrix2x3::new(\n\n 1.0, 0.0, 0.0, // point 1\n\n 0.0, 1.0, 0.0, // point 2\n\n ));\n\n\n\n // perepective parameters - focal length of 100, no skew, pixel center at (640,480)\n\n let intrinsics = IntrinsicParametersPerspective::from(PerspectiveParams {\n\n fx: 100.0,\n\n fy: 100.0,\n\n skew: 0.0,\n\n cx: 640.0,\n\n cy: 480.0,\n\n });\n\n\n\n // Set extrinsic parameters - camera at (10,0,0), looing at (0,0,0), up (0,0,1)\n", "file_path": "examples/3d-to-2d.rs", "rank": 36, "score": 46487.34670254089 }, { "content": "/// A simple SVG file writer\n\nstruct SvgWriter {\n\n segs: Vec<((f64, f64), (f64, f64))>,\n\n xmin: f64,\n\n xmax: f64,\n\n ymin: f64,\n\n ymax: f64,\n\n}\n\n\n\nimpl SvgWriter {\n\n fn new() -> Self {\n\n Self {\n\n xmin: std::f64::INFINITY,\n\n xmax: -std::f64::INFINITY,\n\n ymin: std::f64::INFINITY,\n\n ymax: -std::f64::INFINITY,\n\n segs: Vec::new(),\n\n }\n\n }\n\n fn add_edge<S>(&mut self, pt0: &Matrix<f64, U1, U2, S>, pt1: &Matrix<f64, U1, U2, S>)\n\n where\n", "file_path": "examples/render-cube.rs", "rank": 37, "score": 44111.36614513887 }, { "content": "fn main() {\n\n use cam_geom::*;\n\n use nalgebra::RowVector3;\n\n\n\n // Create the first ray.\n\n let ray1 = Ray::<WorldFrame, _>::new(\n\n RowVector3::new(1.0, 0.0, 0.0), // origin\n\n RowVector3::new(0.0, 1.0, 0.0), // direction\n\n );\n\n\n\n // Create the second ray.\n\n let ray2 = Ray::<WorldFrame, _>::new(\n\n RowVector3::new(0.0, 1.0, 0.0), // origin\n\n RowVector3::new(1.0, 0.0, 0.0), // direction\n\n );\n\n\n\n // Compute the best intersection.\n\n let result = best_intersection_of_rays(&[ray1, ray2]).unwrap();\n\n\n\n // Print the result.\n\n println!(\"result: {}\", result.data);\n\n}\n", "file_path": "examples/ray-intersect.rs", "rank": 38, "score": 43192.15790611204 }, { "content": "/// A coordinate system in which points and rays can be defined.\n\npub trait CoordinateSystem {}\n\n\n\n/// Implementations of [`CoordinateSystem`](trait.CoordinateSystem.html).\n\npub mod coordinate_system {\n\n\n\n #[cfg(feature = \"serde-serialize\")]\n\n use serde::{Deserialize, Serialize};\n\n\n\n /// Coordinates in the camera coordinate system.\n\n ///\n\n /// The camera center is at (0,0,0) at looking at (0,0,1) with up as\n\n /// (0,-1,0) in this coordinate frame.\n\n #[derive(Debug, Clone, PartialEq)]\n\n #[cfg_attr(feature = \"serde-serialize\", derive(Serialize, Deserialize))]\n\n pub struct CameraFrame {}\n\n impl crate::CoordinateSystem for CameraFrame {}\n\n\n\n /// Coordinates in the world coordinate system.\n\n ///\n\n /// The camera center is may be located at an arbitrary position and pointed\n", "file_path": "src/lib.rs", "rank": 39, "score": 40464.393337334455 }, { "content": "// Save a wireframe rendering of the vertices and edges to an SVG file.\n\nfn render_wireframe<NPTS, I, S>(\n\n verts: &Points<WorldFrame, f64, NPTS, S>,\n\n edges: &[(usize, usize)],\n\n cam: &Camera<f64, I>,\n\n fname: &str,\n\n) -> Result<(), std::io::Error>\n\nwhere\n\n NPTS: Dim,\n\n I: IntrinsicParameters<f64>,\n\n S: Storage<f64, NPTS, U3>,\n\n DefaultAllocator: Allocator<f64, NPTS, U3>,\n\n DefaultAllocator: Allocator<f64, NPTS, U2>,\n\n{\n\n // Project the original 3D coordinates to 2D pixel coordinates.\n\n let pixel_coords = cam.world_to_pixel(&verts);\n\n\n\n let mut wtr = SvgWriter::new();\n\n\n\n for edge in edges {\n\n let (i0, i1) = edge;\n\n let pt0 = pixel_coords.data.row(*i0);\n\n let pt1 = pixel_coords.data.row(*i1);\n\n wtr.add_edge(&pt0, &pt1);\n\n }\n\n wtr.save(fname)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "examples/render-cube.rs", "rank": 40, "score": 32972.6694241497 }, { "content": "use nalgebra::{\n\n allocator::Allocator,\n\n base::storage::{Owned, Storage},\n\n convert,\n\n geometry::{Point3, Rotation3, UnitQuaternion},\n\n DefaultAllocator, Dim, Matrix, Matrix3, RealField, SMatrix, Vector3, U1, U2, U3, U4,\n\n};\n\n\n\n#[cfg(feature = \"serde-serialize\")]\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::{\n\n coordinate_system::WorldFrame,\n\n intrinsics_perspective::{IntrinsicParametersPerspective, PerspectiveParams},\n\n Bundle, Error, ExtrinsicParameters, IntrinsicParameters, Pixels, Points, RayBundle,\n\n};\n\n\n\n/// A camera model that can convert world coordinates into pixel coordinates.\n\n///\n\n/// # Examples\n", "file_path": "src/camera.rs", "rank": 41, "score": 29144.473563773092 }, { "content": " I::BundleType: Bundle<R>,\n\n DefaultAllocator: Allocator<R, U1, U2>,\n\n DefaultAllocator: Allocator<R, NPTS, U2>,\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n\n {\n\n // get camera frame rays\n\n let camera = self.intrinsics.pixel_to_camera(&pixels);\n\n\n\n // get world frame rays\n\n self.extrinsics.ray_camera_to_world(&camera)\n\n }\n\n}\n\n\n\nimpl<R: RealField> Camera<R, IntrinsicParametersPerspective<R>> {\n\n /// Create a `Camera` from a 3x4 perspective projection matrix.\n\n pub fn from_perspective_matrix<S>(pmat: &Matrix<R, U3, U4, S>) -> Result<Self, Error>\n\n where\n\n S: Storage<R, U3, U4> + Clone,\n\n {\n\n let m = pmat.clone().remove_column(3);\n", "file_path": "src/camera.rs", "rank": 42, "score": 29139.99310188842 }, { "content": " &self.extrinsics\n\n }\n\n\n\n /// Return a reference to the intrinsic parameters.\n\n #[inline]\n\n pub fn intrinsics(&self) -> &I {\n\n &self.intrinsics\n\n }\n\n\n\n /// take 3D coordinates in world frame and convert to pixel coordinates\n\n pub fn world_to_pixel<NPTS, InStorage>(\n\n &self,\n\n world: &Points<WorldFrame, R, NPTS, InStorage>,\n\n ) -> Pixels<R, NPTS, Owned<R, NPTS, U2>>\n\n where\n\n NPTS: Dim,\n\n InStorage: Storage<R, NPTS, U3>,\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n\n DefaultAllocator: Allocator<R, NPTS, U2>,\n\n {\n", "file_path": "src/camera.rs", "rank": 43, "score": 29138.151316190673 }, { "content": " let camera_frame = self.extrinsics.world_to_camera(&world);\n\n self.intrinsics.camera_to_pixel(&camera_frame)\n\n }\n\n\n\n /// take pixel coordinates and project to 3D in world frame\n\n ///\n\n /// output arguments:\n\n /// `camera` - camera frame coordinate rays\n\n /// `world` - world frame coordinate rays\n\n ///\n\n /// Note that the camera frame coordinates are returned as they must\n\n /// be computed anyway, so this additional data is \"free\".\n\n pub fn pixel_to_world<IN, NPTS>(\n\n &self,\n\n pixels: &Pixels<R, NPTS, IN>,\n\n ) -> RayBundle<WorldFrame, I::BundleType, R, NPTS, Owned<R, NPTS, U3>>\n\n where\n\n I::BundleType: Bundle<R>,\n\n IN: Storage<R, NPTS, U2>,\n\n NPTS: Dim,\n", "file_path": "src/camera.rs", "rank": 44, "score": 29136.625153810426 }, { "content": "/// let pose = ExtrinsicParameters::from_view(&camcenter, &lookat, &up);\n\n///\n\n/// // Create camera with both intrinsic and extrinsic parameters.\n\n/// let cam = Camera::new(intrinsics, pose);\n\n/// ```\n\n///\n\n/// Creates a new orthographic camera:\n\n///\n\n/// ```\n\n/// use cam_geom::*;\n\n/// use nalgebra::*;\n\n///\n\n/// // orthographic parameters - scale of 100, pixel center at (640,480)\n\n/// let intrinsics = IntrinsicParametersOrthographic::from(OrthographicParams {\n\n/// sx: 100.0,\n\n/// sy: 100.0,\n\n/// cx: 640.0,\n\n/// cy: 480.0,\n\n/// });\n\n///\n", "file_path": "src/camera.rs", "rank": 45, "score": 29133.723403484277 }, { "content": " let (rquat, k) = rq_decomposition(m)?;\n\n\n\n let k22: R = k[(2, 2)].clone();\n\n\n\n let one: R = convert(1.0);\n\n\n\n let k = k * (one / k22); // normalize\n\n\n\n let params = PerspectiveParams {\n\n fx: k[(0, 0)].clone(),\n\n fy: k[(1, 1)].clone(),\n\n skew: k[(0, 1)].clone(),\n\n cx: k[(0, 2)].clone(),\n\n cy: k[(1, 2)].clone(),\n\n };\n\n\n\n let camcenter = pmat2cam_center(pmat);\n\n let extrinsics = ExtrinsicParameters::from_rotation_and_camcenter(rquat, camcenter);\n\n\n\n Ok(Self::new(params.into(), extrinsics))\n", "file_path": "src/camera.rs", "rank": 46, "score": 29130.104435495323 }, { "content": " }\n\n\n\n /// Create a 3x4 perspective projection matrix modeling this camera.\n\n pub fn as_camera_matrix(&self) -> SMatrix<R, 3, 4> {\n\n let m = {\n\n let p33 = self.intrinsics().as_intrinsics_matrix();\n\n p33 * self.extrinsics().cache.qt.clone()\n\n };\n\n\n\n // flip sign if focal length < 0\n\n let m = if m[(0, 0)] < nalgebra::convert(0.0) {\n\n -m\n\n } else {\n\n m\n\n };\n\n\n\n m.clone() / m[(2, 3)].clone() // normalize\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/camera.rs", "rank": 47, "score": 29129.253944656783 }, { "content": "///\n\n/// Creates a new perspective camera:\n\n///\n\n/// ```\n\n/// use cam_geom::*;\n\n/// use nalgebra::*;\n\n///\n\n/// // perepective parameters - focal length of 100, no skew, pixel center at (640,480)\n\n/// let intrinsics = IntrinsicParametersPerspective::from(PerspectiveParams {\n\n/// fx: 100.0,\n\n/// fy: 100.0,\n\n/// skew: 0.0,\n\n/// cx: 640.0,\n\n/// cy: 480.0,\n\n/// });\n\n///\n\n/// // Set extrinsic parameters - camera at (10,0,10), looing at (0,0,0), up (0,0,1)\n\n/// let camcenter = Vector3::new(10.0, 0.0, 10.0);\n\n/// let lookat = Vector3::new(0.0, 0.0, 0.0);\n\n/// let up = Unit::new_normalize(Vector3::new(0.0, 0.0, 1.0));\n", "file_path": "src/camera.rs", "rank": 48, "score": 29127.79443317597 }, { "content": "impl<R, I> Camera<R, I>\n\nwhere\n\n I: IntrinsicParameters<R>,\n\n R: RealField,\n\n{\n\n /// Create a new camera from intrinsic and extrinsic parameters.\n\n ///\n\n /// # Arguments\n\n /// Intrinsic parameters and extrinsic parameters\n\n #[inline]\n\n pub fn new(intrinsics: I, extrinsics: ExtrinsicParameters<R>) -> Self {\n\n Self {\n\n intrinsics,\n\n extrinsics,\n\n }\n\n }\n\n\n\n /// Return a reference to the extrinsic parameters.\n\n #[inline]\n\n pub fn extrinsics(&self) -> &ExtrinsicParameters<R> {\n", "file_path": "src/camera.rs", "rank": 49, "score": 29126.222083095578 }, { "content": "/// // Set extrinsic parameters - camera at (10,0,10), looing at (0,0,0), up (0,0,1)\n\n/// let camcenter = Vector3::new(10.0, 0.0, 10.0);\n\n/// let lookat = Vector3::new(0.0, 0.0, 0.0);\n\n/// let up = Unit::new_normalize(Vector3::new(0.0, 0.0, 1.0));\n\n/// let pose = ExtrinsicParameters::from_view(&camcenter, &lookat, &up);\n\n///\n\n/// // Create camera with both intrinsic and extrinsic parameters.\n\n/// let cam = Camera::new(intrinsics, pose);\n\n/// ```\n\n#[derive(Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serde-serialize\", derive(Serialize, Deserialize))]\n\npub struct Camera<R, I>\n\nwhere\n\n I: IntrinsicParameters<R>,\n\n R: RealField,\n\n{\n\n intrinsics: I,\n\n extrinsics: ExtrinsicParameters<R>,\n\n}\n\n\n", "file_path": "src/camera.rs", "rank": 50, "score": 29125.671528990628 }, { "content": "\n\n let params = PerspectiveParams {\n\n fx: 100.0,\n\n fy: 102.0,\n\n skew: 0.1,\n\n cx: 321.0,\n\n cy: 239.9,\n\n };\n\n\n\n let intrinsics: IntrinsicParametersPerspective<_> = params.into();\n\n\n\n let camcenter = Vector3::new(10.0, 0.0, 10.0);\n\n let lookat = Vector3::new(0.0, 0.0, 0.0);\n\n let up = Unit::new_normalize(Vector3::new(0.0, 0.0, 1.0));\n\n let pose = ExtrinsicParameters::from_view(&camcenter, &lookat, &up);\n\n\n\n let expected = Camera::new(intrinsics, pose);\n\n\n\n let buf = serde_json::to_string(&expected).unwrap();\n\n let actual: Camera<_, _> = serde_json::from_str(&buf).unwrap();\n\n assert!(expected == actual);\n\n }\n\n}\n", "file_path": "src/camera.rs", "rank": 51, "score": 29120.539110261896 }, { "content": " let q = -q;\n\n let intrin = -intrin;\n\n let rquat = right_handed_rotation_quat_new(&q)?;\n\n Ok((rquat, intrin))\n\n }\n\n e => Err(e),\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/camera.rs", "rank": 52, "score": 29109.535102279733 }, { "content": " let mut data = nalgebra::OMatrix::<R, Dynamic, U2>::from_element(uv_raws.len(), convert(0.0));\n\n for i in 0..uv_raws.len() {\n\n for j in 0..2 {\n\n data[(i, j)] = uv_raws[i][j].clone();\n\n }\n\n }\n\n Pixels { data }\n\n}\n\n\n\n/// Test roundtrip projection from pixels to camera rays for an intrinsic camera model.\n\n///\n\n/// Generate pixel coordinates, project them to rays, convert to points on the\n\n/// rays, convert the points back to pixels, and then compare with the original\n\n/// pixel coordinates.\n", "file_path": "src/intrinsic_test_utils.rs", "rank": 53, "score": 26210.138653684768 }, { "content": "//! Utilities for testing `cam_geom` implementations.\n\nuse super::*;\n\nuse nalgebra::{\n\n base::{dimension::Dynamic, VecStorage},\n\n convert,\n\n};\n\n\n\npub(crate) fn generate_uv_raw<R: RealField>(\n\n width: usize,\n\n height: usize,\n\n step: usize,\n\n border: usize,\n\n) -> Pixels<R, Dynamic, VecStorage<R, Dynamic, U2>> {\n\n let mut uv_raws: Vec<[R; 2]> = Vec::new();\n\n for row in num_iter::range_step(border, height - border, step) {\n\n for col in num_iter::range_step(border, width - border, step) {\n\n uv_raws.push([convert(col as f64), convert(row as f64)]);\n\n }\n\n }\n\n\n", "file_path": "src/intrinsic_test_utils.rs", "rank": 54, "score": 26205.75022012014 }, { "content": " type BundleType = SharedOriginRayBundle<R>;\n\n\n\n fn pixel_to_camera<IN, NPTS>(\n\n &self,\n\n pixels: &Pixels<R, NPTS, IN>,\n\n ) -> RayBundle<CameraFrame, Self::BundleType, R, NPTS, Owned<R, NPTS, U3>>\n\n where\n\n Self::BundleType: Bundle<R>,\n\n IN: Storage<R, NPTS, U2>,\n\n NPTS: Dim,\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n\n {\n\n let one: R = convert(1.0);\n\n\n\n // allocate zeros, fill later\n\n let mut result = RayBundle::new_shared_zero_origin(OMatrix::zeros_generic(\n\n NPTS::from_usize(pixels.data.nrows()),\n\n U3::from_usize(3),\n\n ));\n\n\n", "file_path": "src/intrinsics_perspective.rs", "rank": 57, "score": 41.213358780101956 }, { "content": "use nalgebra::{\n\n allocator::Allocator,\n\n convert,\n\n storage::{Owned, Storage},\n\n DefaultAllocator, Dim, Matrix, OMatrix, RealField, SMatrix, SliceStorage, U1, U2, U3,\n\n};\n\n\n\n#[cfg(feature = \"serde-serialize\")]\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::{\n\n coordinate_system::CameraFrame, Bundle, Error, IntrinsicParameters, Pixels, Points, RayBundle,\n\n};\n\n\n\nuse crate::ray_bundle_types::SharedOriginRayBundle;\n\n\n\n/// Parameters defining a pinhole perspective camera model.\n\n///\n\n/// These will be used to make the 3x4 intrinsic parameter matrix\n\n/// ```text\n", "file_path": "src/intrinsics_perspective.rs", "rank": 59, "score": 38.88697905728456 }, { "content": " /// project camera coords to pixel coordinates\n\n fn camera_to_pixel<IN, NPTS>(\n\n &self,\n\n camera: &Points<coordinate_system::CameraFrame, R, NPTS, IN>,\n\n ) -> Pixels<R, NPTS, Owned<R, NPTS, U2>>\n\n where\n\n IN: Storage<R, NPTS, U3>,\n\n NPTS: Dim,\n\n DefaultAllocator: Allocator<R, NPTS, U2>;\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use nalgebra::convert;\n\n\n\n #[cfg(not(feature = \"std\"))]\n\n compile_error!(\"tests require std\");\n\n\n\n #[test]\n", "file_path": "src/lib.rs", "rank": 62, "score": 36.05262309990812 }, { "content": "use nalgebra::geometry::{Isometry3, Point3, Rotation3, Translation, UnitQuaternion};\n\nuse nalgebra::{\n\n allocator::Allocator,\n\n storage::{Owned, Storage},\n\n DefaultAllocator, RealField,\n\n};\n\nuse nalgebra::{convert, Dim, OMatrix, SMatrix, Unit, Vector3, U3};\n\n\n\n#[cfg(feature = \"serde-serialize\")]\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::{\n\n coordinate_system::{CameraFrame, WorldFrame},\n\n Bundle, Points, RayBundle,\n\n};\n\n\n\n/// Defines the pose of a camera in the world coordinate system.\n\n#[derive(Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serde-serialize\", derive(Serialize))]\n\npub struct ExtrinsicParameters<R: RealField> {\n", "file_path": "src/extrinsics.rs", "rank": 63, "score": 35.1196506573625 }, { "content": " /// `Coords` type.\n\n pub fn new_shared_zero_origin(data: Matrix<R, NPTS, U3, StorageMultiple>) -> Self {\n\n let bundle_type = crate::ray_bundle_types::SharedOriginRayBundle::new_shared_zero_origin();\n\n Self::new(bundle_type, data)\n\n }\n\n}\n\n\n\nimpl<Coords, R, NPTS, StorageMultiple>\n\n RayBundle<\n\n Coords,\n\n crate::ray_bundle_types::SharedDirectionRayBundle<R>,\n\n R,\n\n NPTS,\n\n StorageMultiple,\n\n >\n\nwhere\n\n Coords: CoordinateSystem,\n\n R: RealField,\n\n NPTS: Dim,\n\n StorageMultiple: Storage<R, NPTS, U3>,\n", "file_path": "src/lib.rs", "rank": 64, "score": 33.515373384915016 }, { "content": " R: RealField,\n\n NPTS: Dim,\n\n{\n\n /// Create a new Points instance from the underlying storage.\n\n #[inline]\n\n pub fn new(data: nalgebra::Matrix<R, NPTS, U3, STORAGE>) -> Self {\n\n Self {\n\n coords: std::marker::PhantomData,\n\n data,\n\n }\n\n }\n\n}\n\n\n\n/// 3D rays. Can be in any [`CoordinateSystem`](trait.CoordinateSystem.html).\n\n///\n\n/// Any given `RayBundle` will have a particular bundle type, which implements\n\n/// the [`Bundle`](trait.Bundle.html) trait.\n\n#[derive(Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serde-serialize\", derive(Serialize, Deserialize))]\n\npub struct RayBundle<Coords, BType, R, NPTS, StorageMultiple>\n", "file_path": "src/lib.rs", "rank": 65, "score": 33.248173804708394 }, { "content": " std::fmt::Debug::fmt(self, f)\n\n }\n\n}\n\n\n\n/// 2D pixel locations on the image sensor.\n\n///\n\n/// These pixels are \"distorted\" - with barrel and pincushion distortion - if\n\n/// the camera model incorporates such. (Undistorted pixels are handled\n\n/// internally within the camera model.)\n\n///\n\n/// This is a newtype wrapping an `nalgebra::Matrix`.\n\n#[derive(Clone)]\n\npub struct Pixels<R: RealField, NPTS: Dim, STORAGE> {\n\n /// The matrix storing pixel locations.\n\n pub data: nalgebra::Matrix<R, NPTS, U2, STORAGE>,\n\n}\n\n\n\nimpl<R: RealField, NPTS: Dim, STORAGE> Pixels<R, NPTS, STORAGE> {\n\n /// Create a new Pixels instance\n\n #[inline]\n\n pub fn new(data: nalgebra::Matrix<R, NPTS, U2, STORAGE>) -> Self {\n\n Self { data }\n\n }\n\n}\n\n\n\n/// A coordinate system in which points and rays can be defined.\n", "file_path": "src/lib.rs", "rank": 66, "score": 32.531246057600065 }, { "content": " in_mult[(i, 2)].clone(),\n\n ));\n\n for j in 0..3 {\n\n out_mult[(i, j)] = tmp[j].clone();\n\n }\n\n }\n\n world\n\n }\n\n\n\n /// Convert rays in camera coordinates to world coordinates.\n\n #[inline]\n\n pub fn ray_camera_to_world<BType, NPTS, StorageCamera>(\n\n &self,\n\n camera: &RayBundle<CameraFrame, BType, R, NPTS, StorageCamera>,\n\n ) -> RayBundle<WorldFrame, BType, R, NPTS, Owned<R, NPTS, U3>>\n\n where\n\n BType: Bundle<R>,\n\n NPTS: Dim,\n\n StorageCamera: Storage<R, NPTS, U3>,\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n", "file_path": "src/extrinsics.rs", "rank": 67, "score": 32.50944476226419 }, { "content": " /// Vertical component of the principal point.\n\n pub cy: R,\n\n}\n\n\n\nimpl<R: RealField> From<PerspectiveParams<R>> for IntrinsicParametersPerspective<R> {\n\n fn from(params: PerspectiveParams<R>) -> Self {\n\n use nalgebra::convert as c;\n\n #[rustfmt::skip]\n\n let cache_p = nalgebra::SMatrix::<R,3,4>::new(\n\n params.fx.clone(), params.skew.clone(), params.cx.clone(), c(0.0),\n\n c(0.0), params.fy.clone(), params.cy.clone(), c(0.0),\n\n c(0.0), c(0.0), c(1.0), c(0.0),\n\n );\n\n Self { params, cache_p }\n\n }\n\n}\n\n\n\n/// A pinhole perspective camera model. Implements [`IntrinsicParameters`](trait.IntrinsicParameters.html).\n\n///\n\n/// Create an `IntrinsicParametersPerspective` as described for\n", "file_path": "src/intrinsics_perspective.rs", "rank": 68, "score": 31.60075913388543 }, { "content": "{\n\n /// Create a new RayBundle instance from the underlying storage.\n\n ///\n\n /// The coordinate system is given by the `Coords` type and the bundle type\n\n /// (e.g. shared origin or shared direction) is given by the `BType`.\n\n #[inline]\n\n fn new(bundle_type: BType, data: nalgebra::Matrix<R, NPTS, U3, StorageMultiple>) -> Self {\n\n Self {\n\n coords: std::marker::PhantomData,\n\n data,\n\n bundle_type,\n\n }\n\n }\n\n\n\n /// get a 3D point on the ray, obtained by adding the direction(s) to the origin(s)\n\n ///\n\n /// The distance of the point from the ray bundle center is not definted and\n\n /// can be arbitrary.\n\n #[inline]\n\n pub fn point_on_ray(&self) -> Points<Coords, R, NPTS, Owned<R, NPTS, U3>>\n", "file_path": "src/lib.rs", "rank": 69, "score": 31.515474382620422 }, { "content": " fn camera_to_pixel<IN, NPTS>(\n\n &self,\n\n camera: &Points<CameraFrame, R, NPTS, IN>,\n\n ) -> Pixels<R, NPTS, Owned<R, NPTS, U2>>\n\n where\n\n IN: Storage<R, NPTS, U3>,\n\n NPTS: Dim,\n\n DefaultAllocator: Allocator<R, NPTS, U2>,\n\n {\n\n let mut result = Pixels::new(OMatrix::zeros_generic(\n\n NPTS::from_usize(camera.data.nrows()),\n\n U2::from_usize(2),\n\n ));\n\n\n\n // It seems broadcasting is not (yet) supported in nalgebra, so we loop\n\n // through the data. See\n\n // https://discourse.nphysics.org/t/array-broadcasting-support/375/3 .\n\n\n\n for i in 0..camera.data.nrows() {\n\n let x = nalgebra::Point3::new(\n", "file_path": "src/intrinsics_perspective.rs", "rank": 71, "score": 30.810816112752722 }, { "content": " let C = Vector3::new(CX, CY, CZ);\n\n\n\n let s_f64_pinv = my_pinv(&S)?;\n\n let s_pinv = despecialize!(s_f64_pinv, R, 3, 3);\n\n let r: Vector3<R> = s_pinv * C;\n\n\n\n let mut result = crate::Points::new(nalgebra::OMatrix::<R, U1, U3>::zeros_generic(u1, u3));\n\n for j in 0..3 {\n\n result.data[(0, j)] = r[j].clone();\n\n }\n\n Ok(result)\n\n}\n\n\n", "file_path": "src/ray_intersection.rs", "rank": 72, "score": 30.032406695442504 }, { "content": " /// in an arbitrary direction in this coordinate frame.\n\n #[derive(Debug, Clone, PartialEq)]\n\n #[cfg_attr(feature = \"serde-serialize\", derive(Serialize, Deserialize))]\n\n pub struct WorldFrame {}\n\n impl crate::CoordinateSystem for WorldFrame {}\n\n}\n\npub use coordinate_system::{CameraFrame, WorldFrame};\n\n\n\n/// 3D points. Can be in any [`CoordinateSystem`](trait.CoordinateSystem.html).\n\n///\n\n/// This is a newtype wrapping an `nalgebra::Matrix`.\n\npub struct Points<Coords: CoordinateSystem, R: RealField, NPTS: Dim, STORAGE> {\n\n coords: std::marker::PhantomData<Coords>,\n\n /// The matrix storing point locations.\n\n pub data: nalgebra::Matrix<R, NPTS, U3, STORAGE>,\n\n}\n\n\n\nimpl<Coords, R, NPTS, STORAGE> Points<Coords, R, NPTS, STORAGE>\n\nwhere\n\n Coords: CoordinateSystem,\n", "file_path": "src/lib.rs", "rank": 73, "score": 29.865324876072883 }, { "content": " {\n\n camera.to_pose(self.cache.pose_inv.clone())\n\n }\n\n\n\n /// Convert points in world coordinates to camera coordinates.\n\n pub fn world_to_camera<NPTS, InStorage>(\n\n &self,\n\n world: &Points<WorldFrame, R, NPTS, InStorage>,\n\n ) -> Points<CameraFrame, R, NPTS, Owned<R, NPTS, U3>>\n\n where\n\n NPTS: Dim,\n\n InStorage: Storage<R, NPTS, U3>,\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n\n {\n\n let mut cam_coords = Points::new(OMatrix::zeros_generic(\n\n NPTS::from_usize(world.data.nrows()),\n\n U3::from_usize(3),\n\n ));\n\n\n\n // Potential optimization: remove for loops\n", "file_path": "src/extrinsics.rs", "rank": 74, "score": 29.442911666684736 }, { "content": "{\n\n /// Return the single ray from the RayBundle with exactly one ray.\n\n #[inline]\n\n pub fn to_single_ray(&self) -> Ray<Coords, R> {\n\n self.bundle_type.to_single_ray(&self.data)\n\n }\n\n}\n\n\n\nimpl<Coords, R, NPTS, StorageMultiple>\n\n RayBundle<Coords, crate::ray_bundle_types::SharedOriginRayBundle<R>, R, NPTS, StorageMultiple>\n\nwhere\n\n Coords: CoordinateSystem,\n\n R: RealField,\n\n NPTS: Dim,\n\n StorageMultiple: Storage<R, NPTS, U3>,\n\n{\n\n /// Create a new RayBundle instance in which all rays share origin at zero.\n\n ///\n\n /// The number of points allocated is given by the `npts` parameter, which\n\n /// should agree with the `NPTS` type. The coordinate system is given by the\n", "file_path": "src/lib.rs", "rank": 75, "score": 29.417751505426086 }, { "content": "\n\n#![deny(rust_2018_idioms, unsafe_code, missing_docs)]\n\n#![cfg_attr(not(feature = \"std\"), no_std)]\n\n\n\n#[cfg(not(feature = \"std\"))]\n\nextern crate core as std;\n\n\n\n#[cfg(feature = \"serde-serialize\")]\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse nalgebra::{\n\n allocator::Allocator,\n\n storage::{Owned, Storage},\n\n DefaultAllocator, Dim, DimName, Isometry3, Matrix, Point3, RealField, SMatrix, Vector3, U1, U2,\n\n U3,\n\n};\n\n\n\n#[cfg(feature = \"std\")]\n\npub mod intrinsic_test_utils;\n\n\n", "file_path": "src/lib.rs", "rank": 76, "score": 28.891117554823875 }, { "content": " #[inline]\n\n pub fn fy(&self) -> R {\n\n self.params.fy.clone()\n\n }\n\n\n\n /// Get skew\n\n #[inline]\n\n pub fn skew(&self) -> R {\n\n self.params.skew.clone()\n\n }\n\n\n\n /// Get X center\n\n #[inline]\n\n pub fn cx(&self) -> R {\n\n self.params.cx.clone()\n\n }\n\n\n\n /// Get Y center\n\n #[inline]\n\n pub fn cy(&self) -> R {\n", "file_path": "src/intrinsics_perspective.rs", "rank": 77, "score": 28.228063216177762 }, { "content": " // flip sign if focal length < 0\n\n let m = if m[(0, 0)] < nalgebra::zero() { -m } else { m };\n\n\n\n let m = m.clone() / m[(2, 3)].clone(); // normalize\n\n\n\n Self { m }\n\n }\n\n\n\n /// Linearize camera model by evaluating around input point `p`.\n\n ///\n\n /// Returns Jacobian matrix `A` (shape 2x3) such that `Ao = (u,v)` where `o`\n\n /// is 3D world coords offset from `p` and `(u,v)` are the shift in pixel\n\n /// coords from the projected location of `p`. In other words, for a camera\n\n /// model `F(x)`, if `F(p) = (a,b)` and `F(p+o) = (a,b)\n\n /// + Ao = (a,b) + (u,v) = (a+u,b+v)`, this function returns `A`.\n\n pub fn linearize_at<STORAGE>(&self, p: &Points<WorldFrame, R, U1, STORAGE>) -> SMatrix<R, 2, 3>\n\n where\n\n STORAGE: Storage<R, U1, U3>,\n\n {\n\n let pt3d = &p.data;\n", "file_path": "src/linearize.rs", "rank": 78, "score": 27.80528684431472 }, { "content": "/// [`PerspectiveParams`](struct.PerspectiveParams.html) by using `.into()`.\n\n#[derive(Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serde-serialize\", derive(Serialize))]\n\npub struct IntrinsicParametersPerspective<R: RealField> {\n\n params: PerspectiveParams<R>,\n\n #[cfg_attr(feature = \"serde-serialize\", serde(skip))]\n\n pub(crate) cache_p: SMatrix<R, 3, 4>,\n\n}\n\n\n\nimpl<R: RealField> IntrinsicParametersPerspective<R> {\n\n /// Create a new instance given an intrinsic parameter matrix.\n\n ///\n\n /// Returns an error if the intrinsic parameter matrix is not normalized or\n\n /// otherwise does not represent a perspective camera model.\n\n pub fn from_normalized_3x4_matrix(p: SMatrix<R, 3, 4>) -> std::result::Result<Self, Error> {\n\n let params: PerspectiveParams<R> = PerspectiveParams {\n\n fx: p[(0, 0)].clone(),\n\n fy: p[(1, 1)].clone(),\n\n skew: p[(0, 1)].clone(),\n\n cx: p[(0, 2)].clone(),\n", "file_path": "src/intrinsics_perspective.rs", "rank": 80, "score": 27.532207090466635 }, { "content": "{\n\n /// Create a new RayBundle instance in which all rays share +z direction.\n\n ///\n\n /// The number of points allocated is given by the `npts` parameter, which\n\n /// should agree with the `NPTS` type. The coordinate system is given by the\n\n /// `Coords` type.\n\n pub fn new_shared_plusz_direction(data: Matrix<R, NPTS, U3, StorageMultiple>) -> Self {\n\n let bundle_type =\n\n crate::ray_bundle_types::SharedDirectionRayBundle::new_plusz_shared_direction();\n\n Self::new(bundle_type, data)\n\n }\n\n}\n\n\n\nimpl<Coords, BType, R, NPTS, StorageMultiple> RayBundle<Coords, BType, R, NPTS, StorageMultiple>\n\nwhere\n\n Coords: CoordinateSystem,\n\n BType: Bundle<R>,\n\n R: RealField,\n\n NPTS: Dim,\n\n StorageMultiple: Storage<R, NPTS, U3>,\n", "file_path": "src/lib.rs", "rank": 81, "score": 26.810483928153676 }, { "content": "## Testing\n\n\n\n### Unit tests\n\n\n\nTo run the basic unit tests:\n\n\n\n```\n\ncargo test\n\n```\n\n\n\nTo run all unit tests:\n\n\n\n```\n\ncargo test --features serde-serialize\n\n```\n\n\n\n### Test for `no_std`\n\n\n\nSince the `thumbv7em-none-eabihf` target does not have `std` available, we\n\ncan build for it to check that our crate does not inadvertently pull in\n\nstd. The unit tests require std, so cannot be run on a `no_std` platform.\n\nThe following will fail if a std dependency is present:\n\n\n\n```\n\n# install target with: \"rustup target add thumbv7em-none-eabihf\"\n\ncargo build --no-default-features --target thumbv7em-none-eabihf\n\n```\n\n\n\n## Examples\n\n\n\n### Example - projecting 3D world coordinates to 2D pixel coordinates.\n\n\n\n```rust\n\nuse cam_geom::*;\n\nuse nalgebra::{Matrix2x3, Unit, Vector3};\n\n\n\n// Create two points in the world coordinate frame.\n\nlet world_coords = Points::new(Matrix2x3::new(\n\n 1.0, 0.0, 0.0, // point 1\n\n 0.0, 1.0, 0.0, // point 2\n\n));\n\n\n\n// perepective parameters - focal length of 100, no skew, pixel center at (640,480)\n\nlet intrinsics = IntrinsicParametersPerspective::from(PerspectiveParams {\n\n fx: 100.0,\n\n fy: 100.0,\n\n skew: 0.0,\n\n cx: 640.0,\n\n cy: 480.0,\n\n});\n\n\n\n// Set extrinsic parameters - camera at (10,0,0), looing at (0,0,0), up (0,0,1)\n\nlet camcenter = Vector3::new(10.0, 0.0, 0.0);\n\nlet lookat = Vector3::new(0.0, 0.0, 0.0);\n\nlet up = Unit::new_normalize(Vector3::new(0.0, 0.0, 1.0));\n\nlet pose = ExtrinsicParameters::from_view(&camcenter, &lookat, &up);\n\n\n\n// Create a `Camera` with both intrinsic and extrinsic parameters.\n\nlet camera = Camera::new(intrinsics, pose);\n\n\n\n// Project the original 3D coordinates to 2D pixel coordinates.\n\nlet pixel_coords = camera.world_to_pixel(&world_coords);\n\n\n\n// Print the results.\n\nfor i in 0..world_coords.data.nrows() {\n\n let wc = world_coords.data.row(i);\n\n let pix = pixel_coords.data.row(i);\n\n println!(\"{} -> {}\", wc, pix);\n\n}\n\n```\n\n\n\nThis will print:\n\n\n\n```\n\n ┌ ┐\n\n │ 1 0 0 │\n\n └ ┘\n\n\n\n ->\n\n ┌ ┐\n\n │ 640 480 │\n\n └ ┘\n\n\n\n\n\n\n\n ┌ ┐\n\n │ 0 1 0 │\n\n └ ┘\n\n\n\n ->\n\n ┌ ┐\n\n │ 650 480 │\n\n └ ┘\n\n```\n\n\n\n\n", "file_path": "README.md", "rank": 82, "score": 25.755761032683992 }, { "content": "/// let params = PerspectiveParams {\n\n/// fx: 100.0,\n\n/// fy: 100.0,\n\n/// skew: 0.0,\n\n/// cx: 640.0,\n\n/// cy: 480.0,\n\n/// };\n\n/// let intrinsics: IntrinsicParametersPerspective<_> = params.into();\n\n/// ```\n\n#[derive(Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"serde-serialize\", derive(Serialize, Deserialize))]\n\npub struct PerspectiveParams<R: RealField> {\n\n /// Horizontal focal length.\n\n pub fx: R,\n\n /// Vertical focal length.\n\n pub fy: R,\n\n /// Skew between horizontal and vertical axes.\n\n pub skew: R,\n\n /// Horizontal component of the principal point.\n\n pub cx: R,\n", "file_path": "src/intrinsics_perspective.rs", "rank": 83, "score": 25.57735879071031 }, { "content": " where\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n\n {\n\n self.bundle_type.point_on_ray(&self.data)\n\n }\n\n\n\n /// get a 3D point on the ray at a defined distance from the origin(s)\n\n #[inline]\n\n pub fn point_on_ray_at_distance(\n\n &self,\n\n distance: R,\n\n ) -> Points<Coords, R, NPTS, Owned<R, NPTS, U3>>\n\n where\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n\n {\n\n self.bundle_type\n\n .point_on_ray_at_distance(&self.data, distance)\n\n }\n\n\n\n #[inline]\n", "file_path": "src/lib.rs", "rank": 84, "score": 25.380549224719346 }, { "content": " self.params.cy.clone()\n\n }\n\n\n\n /// Create a 3x3 projection matrix.\n\n #[inline]\n\n pub(crate) fn as_intrinsics_matrix(\n\n &self,\n\n ) -> Matrix<R, U3, U3, SliceStorage<'_, R, U3, U3, U1, U3>> {\n\n // TODO: implement similar functionality for orthographic camera and\n\n // make a new trait which exposes this functionality. Note that not all\n\n // intrinsic parameter implementations will be able to implement this\n\n // hypothetical new trait, because not all cameras are linear.\n\n self.cache_p.fixed_slice::<3, 3>(0, 0)\n\n }\n\n}\n\n\n\nimpl<R> IntrinsicParameters<R> for IntrinsicParametersPerspective<R>\n\nwhere\n\n R: RealField,\n\n{\n", "file_path": "src/intrinsics_perspective.rs", "rank": 85, "score": 24.883178561565146 }, { "content": " let cam_dir = &mut result.data;\n\n\n\n // It seems broadcasting is not (yet) supported in nalgebra, so we loop\n\n // through the data. See\n\n // https://discourse.nphysics.org/t/array-broadcasting-support/375/3 .\n\n\n\n for i in 0..pixels.data.nrows() {\n\n let u = pixels.data[(i, 0)].clone();\n\n let v = pixels.data[(i, 1)].clone();\n\n\n\n // point in camcoords at distance 1.0 from image plane\n\n let y = (v - self.params.cy.clone()) / self.params.fy.clone();\n\n cam_dir[(i, 0)] = (u - self.params.skew.clone() * y.clone() - self.params.cx.clone())\n\n / self.params.fx.clone(); // x\n\n cam_dir[(i, 1)] = y;\n\n cam_dir[(i, 2)] = one.clone(); // z\n\n }\n\n result\n\n }\n\n\n", "file_path": "src/intrinsics_perspective.rs", "rank": 86, "score": 24.82773694544442 }, { "content": " cam_coords: &Points<CameraFrame, R, NPTS, InStorage>,\n\n ) -> Points<WorldFrame, R, NPTS, Owned<R, NPTS, U3>>\n\n where\n\n NPTS: Dim,\n\n InStorage: Storage<R, NPTS, U3>,\n\n DefaultAllocator: Allocator<R, NPTS, U3>,\n\n {\n\n let mut world = Points::new(OMatrix::zeros_generic(\n\n NPTS::from_usize(cam_coords.data.nrows()),\n\n U3::from_usize(3),\n\n ));\n\n\n\n // Potential optimization: remove for loops\n\n let in_mult = &cam_coords.data;\n\n let out_mult = &mut world.data;\n\n\n\n for i in 0..in_mult.nrows() {\n\n let tmp = self.cache.pose_inv.transform_point(&Point3::new(\n\n in_mult[(i, 0)].clone(),\n\n in_mult[(i, 1)].clone(),\n", "file_path": "src/extrinsics.rs", "rank": 87, "score": 24.63546639919511 }, { "content": " }\n\n\n\n if approx::relative_ne!(p[(2, 2)], nalgebra::convert(1.0)) {\n\n return Err(Error::InvalidInput); // camera matrix must be normalized\n\n }\n\n\n\n if approx::relative_ne!(p[(2, 3)], nalgebra::convert(0.0)) {\n\n return Err(Error::InvalidInput);\n\n }\n\n\n\n Ok(params.into())\n\n }\n\n\n\n /// Get X focal length\n\n #[inline]\n\n pub fn fx(&self) -> R {\n\n self.params.fx.clone()\n\n }\n\n\n\n /// Get Y focal length\n", "file_path": "src/intrinsics_perspective.rs", "rank": 88, "score": 24.402419456233815 }, { "content": "mod intrinsics_perspective;\n\npub use intrinsics_perspective::{IntrinsicParametersPerspective, PerspectiveParams};\n\n\n\nmod intrinsics_orthographic;\n\npub use intrinsics_orthographic::{IntrinsicParametersOrthographic, OrthographicParams};\n\n\n\nmod extrinsics;\n\npub use extrinsics::ExtrinsicParameters;\n\n\n\nmod camera;\n\npub use camera::Camera;\n\n\n\n/// Defines the different possible types of ray bundles.\n\npub mod ray_bundle_types;\n\n\n\nmod ray_intersection;\n\npub use ray_intersection::best_intersection_of_rays;\n\n\n\npub mod linearize;\n\n\n", "file_path": "src/lib.rs", "rank": 90, "score": 23.53548608496405 }, { "content": " );\n\n\n\n let from_params = Camera::new(cam, extrinsics);\n\n result.push((\"from-params\".into(), from_params));\n\n\n\n // in the future - more cameras\n\n\n\n result\n\n }\n\n\n\n #[test]\n\n #[cfg(feature = \"serde-serialize\")]\n\n fn test_serde() {\n\n let params = PerspectiveParams {\n\n fx: 100.0,\n\n fy: 102.0,\n\n skew: 0.1,\n\n cx: 321.0,\n\n cy: 239.9,\n\n };\n", "file_path": "src/intrinsics_perspective.rs", "rank": 91, "score": 23.250285383354317 }, { "content": "#![deny(unsafe_code, missing_docs)]\n\n\n\nuse nalgebra as na;\n\n\n\nuse na::{\n\n allocator::Allocator, base::storage::Owned, DefaultAllocator, Dim, Dynamic, Matrix3, OMatrix,\n\n RealField, SMatrix, Vector3, U1, U3,\n\n};\n\n\n\nuse itertools::izip;\n\n\n\nuse crate::{CoordinateSystem, Error, Points, Ray};\n\n\n\n/// Iter::Sum is not implemented for R.\n\nmacro_rules! sum_as_f64 {\n\n ($iter:expr,$R:ty) => {{\n\n $iter\n\n .map(|x| na::try_convert::<$R, f64>(x.clone()).unwrap())\n\n .sum()\n\n }};\n", "file_path": "src/ray_intersection.rs", "rank": 92, "score": 23.23541401194915 }, { "content": "\n\n fn get_test_cameras() -> Vec<(String, Camera<f64, IntrinsicParametersPerspective<f64>>)> {\n\n let mut result = Vec::new();\n\n\n\n // camera 1 - from perspective parameters\n\n let params = PerspectiveParams {\n\n fx: 100.0,\n\n fy: 102.0,\n\n skew: 0.1,\n\n cx: 321.0,\n\n cy: 239.9,\n\n };\n\n\n\n let cam: IntrinsicParametersPerspective<_> = params.into();\n\n roundtrip_intrinsics(&cam, 640, 480, 5, 0, nalgebra::convert(1e-10));\n\n\n\n let extrinsics = ExtrinsicParameters::from_view(\n\n &Vector3::new(1.2, 3.4, 5.6), // camcenter\n\n &Vector3::new(2.2, 3.4, 5.6), // lookat\n\n &nalgebra::Unit::new_normalize(Vector3::new(0.0, 0.0, 1.0)), // up\n", "file_path": "src/intrinsics_perspective.rs", "rank": 93, "score": 23.22266495132496 }, { "content": "//! Linearize camera models by computing the Jacobian matrix.\n\n\n\nuse crate::{Camera, IntrinsicParametersPerspective, Points, WorldFrame};\n\nuse nalgebra::{storage::Storage, RealField, SMatrix, U1, U3};\n\n\n\n/// Required data required for finding Jacobian of perspective camera models.\n\n///\n\n/// Create this with the [`new()`](struct.JacobianPerspectiveCache.html#method.new) method.\n\npub struct JacobianPerspectiveCache<R: RealField> {\n\n m: SMatrix<R, 3, 4>,\n\n}\n\n\n\nimpl<R: RealField> JacobianPerspectiveCache<R> {\n\n /// Create a new `JacobianPerspectiveCache` from a `Camera` with a perspective model.\n\n pub fn new(cam: &Camera<R, IntrinsicParametersPerspective<R>>) -> Self {\n\n let m = {\n\n let p33 = cam.intrinsics().as_intrinsics_matrix();\n\n p33 * cam.extrinsics().matrix()\n\n };\n\n\n", "file_path": "src/linearize.rs", "rank": 94, "score": 23.11128427585163 }, { "content": " DefaultAllocator: Allocator<R, NPTS, U3>,\n\n{\n\n /// get directions of each ray in bundle\n\n #[inline]\n\n pub fn directions(&self) -> Matrix<R, NPTS, U3, Owned<R, NPTS, U3>> {\n\n self.bundle_type.directions(&self.data)\n\n }\n\n\n\n /// get centers (origins) of each ray in bundle\n\n #[inline]\n\n pub fn centers(&self) -> Matrix<R, NPTS, U3, Owned<R, NPTS, U3>> {\n\n self.bundle_type.centers(&self.data)\n\n }\n\n}\n\n\n\nimpl<Coords, BType, R> RayBundle<Coords, BType, R, U1, Owned<R, U1, U3>>\n\nwhere\n\n Coords: CoordinateSystem,\n\n BType: Bundle<R>,\n\n R: RealField,\n", "file_path": "src/lib.rs", "rank": 95, "score": 23.1032511135329 }, { "content": "where\n\n Coords: CoordinateSystem,\n\n BType: Bundle<R>,\n\n R: RealField,\n\n NPTS: Dim,\n\n StorageMultiple: Storage<R, NPTS, U3>,\n\n{\n\n coords: std::marker::PhantomData<Coords>,\n\n /// The matrix storing the ray data.\n\n pub data: Matrix<R, NPTS, U3, StorageMultiple>,\n\n bundle_type: BType,\n\n}\n\n\n\nimpl<Coords, BType, R, NPTS, StorageMultiple> RayBundle<Coords, BType, R, NPTS, StorageMultiple>\n\nwhere\n\n Coords: CoordinateSystem,\n\n BType: Bundle<R>,\n\n R: RealField,\n\n NPTS: DimName,\n\n StorageMultiple: Storage<R, NPTS, U3>,\n", "file_path": "src/lib.rs", "rank": 96, "score": 22.929327902789414 }, { "content": "\n\n fn roundtrip_generic<R: RealField>(epsilon: R) {\n\n let zero: R = convert(0.0);\n\n let one: R = convert(1.0);\n\n\n\n let e1 = ExtrinsicParameters::<R>::from_view(\n\n &Vector3::new(c(1.2), c(3.4), c(5.6)), // camcenter\n\n &Vector3::new(c(2.2), c(3.4), c(5.6)), // lookat\n\n &nalgebra::Unit::new_normalize(Vector3::new(zero.clone(), zero.clone(), one.clone())), // up\n\n );\n\n\n\n #[rustfmt::skip]\n\n let cam_coords = Points {\n\n coords: std::marker::PhantomData,\n\n data: SMatrix::<R, 4, 3>::new(\n\n zero.clone(), zero.clone(), zero.clone(), // at camera center\n\n zero.clone(), zero.clone(), one.clone(), // one unit in +Z - exactly in camera direction\n\n one.clone(), zero.clone(), zero.clone(), // one unit in +X - right of camera axis\n\n zero.clone(), one.clone(), zero.clone(), // one unit in +Y - down from camera axis\n\n ),\n", "file_path": "src/extrinsics.rs", "rank": 97, "score": 22.421653754135733 }, { "content": " }\n\n\n\n /// Return a unit vector aligned along our right (+X) direction.\n\n pub fn right(&self) -> Unit<Vector3<R>> {\n\n let pt_cam = Point3::new(R::one(), R::zero(), R::zero());\n\n self.lookdir(&pt_cam)\n\n }\n\n\n\n /// Return a world coords unit vector aligned along the given direction\n\n ///\n\n /// `pt_cam` is specified in camera coords.\n\n fn lookdir(&self, pt_cam: &Point3<R>) -> Unit<Vector3<R>> {\n\n let cc = self.camcenter();\n\n let pt = self.cache.pose_inv.transform_point(&pt_cam) - cc;\n\n nalgebra::Unit::new_normalize(pt)\n\n }\n\n\n\n /// Convert points in camera coordinates to world coordinates.\n\n pub fn camera_to_world<NPTS, InStorage>(\n\n &self,\n", "file_path": "src/extrinsics.rs", "rank": 98, "score": 22.183906081320956 }, { "content": " /// can be arbitrary.\n\n fn point_on_ray<NPTS, StorageIn, OutFrame>(\n\n &self,\n\n self_data: &Matrix<R, NPTS, U3, StorageIn>,\n\n ) -> Points<OutFrame, R, NPTS, Owned<R, NPTS, U3>>\n\n where\n\n Self: Sized,\n\n NPTS: Dim,\n\n StorageIn: Storage<R, NPTS, U3>,\n\n OutFrame: CoordinateSystem,\n\n DefaultAllocator: Allocator<R, NPTS, U3>;\n\n\n\n /// Return points on on the input rays at a defined distance from the origin(s).\n\n fn point_on_ray_at_distance<NPTS, StorageIn, OutFrame>(\n\n &self,\n\n self_data: &Matrix<R, NPTS, U3, StorageIn>,\n\n distance: R,\n\n ) -> Points<OutFrame, R, NPTS, Owned<R, NPTS, U3>>\n\n where\n\n Self: Sized,\n", "file_path": "src/lib.rs", "rank": 99, "score": 21.99919840424277 } ]
Rust
src/handler/description.rs
p0lunin/dptree
cf41f052a864e145ef600faf79a1dff186b5a905
use core::mem; use std::{ collections::{hash_map::RandomState, HashSet}, hash::{BuildHasher, Hash}, }; pub trait HandlerDescription: Sized + Send + Sync + 'static { fn entry() -> Self; fn user_defined() -> Self; fn merge_chain(&self, other: &Self) -> Self; fn merge_branch(&self, other: &Self) -> Self; #[track_caller] fn map() -> Self { Self::user_defined() } #[track_caller] fn map_async() -> Self { Self::user_defined() } #[track_caller] fn filter() -> Self { Self::user_defined() } #[track_caller] fn filter_async() -> Self { Self::user_defined() } #[track_caller] fn filter_map() -> Self { Self::user_defined() } #[track_caller] fn filter_map_async() -> Self { Self::user_defined() } #[track_caller] fn endpoint() -> Self { Self::user_defined() } } #[derive(Debug, PartialEq, Eq)] pub struct Unspecified(()); #[derive(Debug, Clone)] pub enum EventKind<K, S = RandomState> { InterestList(HashSet<K, S>), UserDefined, Entry, } impl<T, S> HandlerDescription for EventKind<T, S> where T: Eq + Hash + Clone, S: BuildHasher + Clone, T: Send + Sync + 'static, S: Send + Sync + 'static, { fn entry() -> Self { EventKind::Entry } fn user_defined() -> Self { EventKind::UserDefined } fn merge_chain(&self, other: &Self) -> Self { use EventKind::*; match (self, other) { (Entry, other) | (other, Entry) => other.clone(), (InterestList(l), InterestList(r)) => { let hasher = l.hasher().clone(); let mut res = HashSet::with_hasher(hasher); res.extend(l.intersection(r).cloned()); InterestList(res) } (InterestList(known), UserDefined) => InterestList(known.clone()), (UserDefined, _) => UserDefined, } } fn merge_branch(&self, other: &Self) -> Self { use EventKind::*; match (self, other) { (Entry, other) | (other, Entry) => other.clone(), (InterestList(l), InterestList(r)) => { let hasher = l.hasher().clone(); let mut res = HashSet::with_hasher(hasher); res.extend(l.union(r).cloned()); InterestList(res) } (UserDefined, _) | (_, UserDefined) => UserDefined, } } } impl<K: Hash + Eq, S: BuildHasher> Eq for EventKind<K, S> {} impl<K: Hash + Eq, S: BuildHasher> PartialEq for EventKind<K, S> { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::InterestList(l), Self::InterestList(r)) => l == r, _ => mem::discriminant(self) == mem::discriminant(other), } } } impl HandlerDescription for Unspecified { fn entry() -> Self { Self(()) } fn user_defined() -> Self { Self(()) } fn merge_chain(&self, _other: &Self) -> Self { Self(()) } fn merge_branch(&self, _other: &Self) -> Self { Self(()) } }
use core::mem; use std::{ collections::{hash_map::RandomState, HashSet}, hash::{BuildHasher, Hash}, }; pub trait HandlerDescription: Sized + Send + Sync + 'static { fn entry() -> Self; fn user_defined() -> Self; fn merge_chain(&self, other: &Self) -> Self; fn merge_branch(&self, other: &Self) -> Self; #[track_caller] fn map() -> Self { Self::user_defined() } #[track_caller] fn map_async() -> Self { Self::user_defined() } #[track_caller] fn filter() -> Self { Self::user_defined() } #[track_caller] fn filter_async() -> Self { Self::user_defined() } #[track_caller] fn filter_map() -> Self { Self::user_defined() } #[track_caller] fn filter_map_async() -> Self { Self::user_defined() } #[track_caller] fn endpoint() -> Self { Self::user_defined() } } #[derive(Debug, PartialEq, Eq)] pub struct Unspecified(()); #[derive(Debug, Clone)] pub enum EventKind<K, S = RandomState> { InterestList(HashSet<K, S>), UserDefined, Entry, } impl<T, S> HandlerDescription for EventKind<T, S> where T: Eq + Hash + Clone, S: BuildHasher + Clone, T: Send + Sync + 'static, S: Send + Sync + 'static, { fn entry() -> Self { EventKind::Entry } fn user_defined() -> Self { EventKind::UserDefined } fn merge_chain(&self, other: &Self) -> Self { use EventKin
fn merge_branch(&self, other: &Self) -> Self { use EventKind::*; match (self, other) { (Entry, other) | (other, Entry) => other.clone(), (InterestList(l), InterestList(r)) => { let hasher = l.hasher().clone(); let mut res = HashSet::with_hasher(hasher); res.extend(l.union(r).cloned()); InterestList(res) } (UserDefined, _) | (_, UserDefined) => UserDefined, } } } impl<K: Hash + Eq, S: BuildHasher> Eq for EventKind<K, S> {} impl<K: Hash + Eq, S: BuildHasher> PartialEq for EventKind<K, S> { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::InterestList(l), Self::InterestList(r)) => l == r, _ => mem::discriminant(self) == mem::discriminant(other), } } } impl HandlerDescription for Unspecified { fn entry() -> Self { Self(()) } fn user_defined() -> Self { Self(()) } fn merge_chain(&self, _other: &Self) -> Self { Self(()) } fn merge_branch(&self, _other: &Self) -> Self { Self(()) } }
d::*; match (self, other) { (Entry, other) | (other, Entry) => other.clone(), (InterestList(l), InterestList(r)) => { let hasher = l.hasher().clone(); let mut res = HashSet::with_hasher(hasher); res.extend(l.intersection(r).cloned()); InterestList(res) } (InterestList(known), UserDefined) => InterestList(known.clone()), (UserDefined, _) => UserDefined, } }
function_block-function_prefixed
[ { "content": "#[must_use]\n\n#[track_caller]\n\npub fn filter_map<'a, Projection, Input, Output, NewType, Args, Descr>(\n\n proj: Projection,\n\n) -> Handler<'a, Input, Output, Descr>\n\nwhere\n\n Input: Clone,\n\n Asyncify<Projection>: Injectable<Input, Option<NewType>, Args> + Send + Sync + 'a,\n\n Input: Insert<NewType> + Send + Sync + 'a,\n\n Output: Send + Sync + 'a,\n\n Descr: HandlerDescription,\n\n NewType: Send,\n\n{\n\n filter_map_with_description(Descr::filter_map(), proj)\n\n}\n\n\n\n/// The asynchronous version of [`filter_map`].\n", "file_path": "src/handler/filter_map.rs", "rank": 1, "score": 134620.9475768156 }, { "content": "#[must_use]\n\n#[track_caller]\n\npub fn filter_map_async<'a, Projection, Input, Output, NewType, Args, Descr>(\n\n proj: Projection,\n\n) -> Handler<'a, Input, Output, Descr>\n\nwhere\n\n Input: Clone,\n\n Projection: Injectable<Input, Option<NewType>, Args> + Send + Sync + 'a,\n\n Input: Insert<NewType> + Send + Sync + 'a,\n\n Output: Send + Sync + 'a,\n\n Descr: HandlerDescription,\n\n NewType: Send,\n\n{\n\n filter_map_async_with_description(Descr::filter_map_async(), proj)\n\n}\n\n\n\n/// [`filter_map`] with a custom description.\n", "file_path": "src/handler/filter_map.rs", "rank": 2, "score": 132341.3470980578 }, { "content": "#[must_use]\n\n#[track_caller]\n\npub fn filter<'a, Pred, Input, Output, FnArgs, Descr>(\n\n pred: Pred,\n\n) -> Handler<'a, Input, Output, Descr>\n\nwhere\n\n Asyncify<Pred>: Injectable<Input, bool, FnArgs> + Send + Sync + 'a,\n\n Input: Send + Sync + 'a,\n\n Output: Send + Sync + 'a,\n\n Descr: HandlerDescription,\n\n{\n\n filter_with_description(Descr::filter(), pred)\n\n}\n\n\n\n/// The asynchronous version of [`filter`].\n", "file_path": "src/handler/filter.rs", "rank": 3, "score": 123583.6605678803 }, { "content": "#[must_use]\n\n#[track_caller]\n\npub fn filter_async<'a, Pred, Input, Output, FnArgs, Descr>(\n\n pred: Pred,\n\n) -> Handler<'a, Input, Output, Descr>\n\nwhere\n\n Pred: Injectable<Input, bool, FnArgs> + Send + Sync + 'a,\n\n Input: Send + Sync + 'a,\n\n Output: Send + Sync + 'a,\n\n Descr: HandlerDescription,\n\n{\n\n filter_async_with_description(Descr::filter_async(), pred)\n\n}\n\n\n\n/// [`filter`] with a custom description.\n", "file_path": "src/handler/filter.rs", "rank": 4, "score": 121573.83767211685 }, { "content": "#[must_use]\n\npub fn filter_map_with_description<'a, Projection, Input, Output, NewType, Args, Descr>(\n\n description: Descr,\n\n proj: Projection,\n\n) -> Handler<'a, Input, Output, Descr>\n\nwhere\n\n Input: Clone,\n\n Asyncify<Projection>: Injectable<Input, Option<NewType>, Args> + Send + Sync + 'a,\n\n Input: Insert<NewType> + Send + Sync + 'a,\n\n Output: Send + Sync + 'a,\n\n NewType: Send,\n\n{\n\n filter_map_async_with_description(description, Asyncify(proj))\n\n}\n\n\n\n/// [`filter_map_async`] with a custom description.\n", "file_path": "src/handler/filter_map.rs", "rank": 5, "score": 115372.80738819794 }, { "content": "#[must_use]\n\n#[track_caller]\n\npub fn endpoint<'a, F, Input, Output, FnArgs, Descr>(f: F) -> Endpoint<'a, Input, Output, Descr>\n\nwhere\n\n Input: Send + Sync + 'a,\n\n Output: Send + Sync + 'a,\n\n Descr: HandlerDescription,\n\n F: Injectable<Input, Output, FnArgs> + Send + Sync + 'a,\n\n{\n\n let f = Arc::new(f);\n\n\n\n from_fn_with_description(Descr::endpoint(), move |x, _cont| {\n\n let f = Arc::clone(&f);\n\n async move {\n\n let f = f.inject(&x);\n\n f().map(ControlFlow::Break).await\n\n }\n\n })\n\n}\n\n\n\n/// A handler with no further handlers in a chain.\n\npub type Endpoint<'a, Input, Output, Descr = description::Unspecified> =\n", "file_path": "src/handler/endpoint.rs", "rank": 6, "score": 114802.3962339515 }, { "content": "#[must_use]\n\npub fn filter_map_async_with_description<'a, Projection, Input, Output, NewType, Args, Descr>(\n\n description: Descr,\n\n proj: Projection,\n\n) -> Handler<'a, Input, Output, Descr>\n\nwhere\n\n Input: Clone,\n\n Projection: Injectable<Input, Option<NewType>, Args> + Send + Sync + 'a,\n\n Input: Insert<NewType> + Send + Sync + 'a,\n\n Output: Send + Sync + 'a,\n\n NewType: Send,\n\n{\n\n let proj = Arc::new(proj);\n\n\n\n from_fn_with_description(description, move |container: Input, cont| {\n\n let proj = Arc::clone(&proj);\n\n\n\n async move {\n\n let proj = proj.inject(&container);\n\n let res = proj().await;\n\n std::mem::drop(proj);\n", "file_path": "src/handler/filter_map.rs", "rank": 7, "score": 113208.22495815501 }, { "content": "#[must_use]\n\n#[track_caller]\n\npub fn map<'a, Projection, Input, Output, NewType, Args, Descr>(\n\n proj: Projection,\n\n) -> Handler<'a, Input, Output, Descr>\n\nwhere\n\n Input: Clone,\n\n Asyncify<Projection>: Injectable<Input, NewType, Args> + Send + Sync + 'a,\n\n Input: Insert<NewType> + Send + Sync + 'a,\n\n Output: Send + Sync + 'a,\n\n Descr: HandlerDescription,\n\n NewType: Send,\n\n{\n\n map_with_description(Descr::map(), proj)\n\n}\n\n\n\n/// The asynchronous version of [`map`].\n", "file_path": "src/handler/map.rs", "rank": 8, "score": 111413.53768491725 }, { "content": "#[must_use]\n\n#[track_caller]\n\npub fn map_async<'a, Projection, Input, Output, NewType, Args, Descr>(\n\n proj: Projection,\n\n) -> Handler<'a, Input, Output, Descr>\n\nwhere\n\n Input: Clone,\n\n Projection: Injectable<Input, NewType, Args> + Send + Sync + 'a,\n\n Input: Insert<NewType> + Send + Sync + 'a,\n\n Output: Send + Sync + 'a,\n\n Descr: HandlerDescription,\n\n NewType: Send,\n\n{\n\n map_async_with_description(Descr::map_async(), proj)\n\n}\n\n\n\n/// [`map`] with a custom description.\n", "file_path": "src/handler/map.rs", "rank": 9, "score": 109518.94596720312 }, { "content": "/// Converts functions into [`CompiledFn`].\n\n///\n\n/// The function must follow some rules, to be usable with DI:\n\n///\n\n/// 1. For each function parameter of type `T`, `Input` must satisfy\n\n/// `DependencySupplier<T>`.\n\n/// 2. The function must be of 0-9 arguments.\n\n/// 3. The function must return [`Future`].\n\npub trait Injectable<Input, Output, FnArgs> {\n\n fn inject<'a>(&'a self, container: &'a Input) -> CompiledFn<'a, Output>;\n\n}\n\n\n\n/// A function with all dependencies satisfied.\n\npub type CompiledFn<'a, Output> = Arc<dyn Fn() -> BoxFuture<'a, Output> + Send + Sync + 'a>;\n\n\n\n/// Turns a synchronous function into a type that implements [`Injectable`].\n\npub struct Asyncify<F>(pub F);\n\n\n\nmacro_rules! impl_into_di {\n\n ($($generic:ident),*) => {\n\n impl<Func, Input, Output, Fut, $($generic),*> Injectable<Input, Output, ($($generic,)*)> for Func\n\n where\n\n Input: $(DependencySupplier<$generic> +)*,\n\n Input: Send + Sync,\n\n Func: Fn($($generic),*) -> Fut + Send + Sync + 'static,\n\n Fut: Future<Output = Output> + Send + 'static,\n\n $($generic: Clone + Send + Sync),*\n\n {\n", "file_path": "src/di.rs", "rank": 10, "score": 105983.6501492435 }, { "content": "type WebHandler = Endpoint<'static, DependencyMap, String>;\n\n\n\n#[rustfmt::skip]\n\n#[tokio::main]\n\nasync fn main() {\n\n let web_server = dptree::entry()\n\n .branch(smiles_handler())\n\n .branch(sqrt_handler())\n\n .branch(not_found_handler());\n\n\n\n assert_eq!(\n\n web_server.dispatch(dptree::deps![\"/smile\"]).await,\n\n ControlFlow::Break(\"🙃\".to_owned())\n\n );\n\n assert_eq!(\n\n web_server.dispatch(dptree::deps![\"/sqrt 16\"]).await,\n\n ControlFlow::Break(\"4\".to_owned())\n\n );\n\n assert_eq!(\n\n web_server.dispatch(dptree::deps![\"/lol\"]).await,\n\n ControlFlow::Break(\"404 Not Found\".to_owned())\n\n );\n\n}\n\n\n", "file_path": "examples/web_server.rs", "rank": 11, "score": 104249.69858306258 }, { "content": "type CommandHandler = Endpoint<'static, DependencyMap, String>;\n\n\n", "file_path": "examples/simple_dispatcher.rs", "rank": 12, "score": 104249.69858306258 }, { "content": "#[must_use]\n\npub fn filter_with_description<'a, Pred, Input, Output, FnArgs, Descr>(\n\n description: Descr,\n\n pred: Pred,\n\n) -> Handler<'a, Input, Output, Descr>\n\nwhere\n\n Asyncify<Pred>: Injectable<Input, bool, FnArgs> + Send + Sync + 'a,\n\n Input: Send + Sync + 'a,\n\n Output: Send + Sync + 'a,\n\n{\n\n filter_async_with_description(description, Asyncify(pred))\n\n}\n\n\n\n/// [`filter_async`] with a custom description.\n", "file_path": "src/handler/filter.rs", "rank": 13, "score": 103852.26714478101 }, { "content": "#[must_use]\n\npub fn filter_async_with_description<'a, Pred, Input, Output, FnArgs, Descr>(\n\n description: Descr,\n\n pred: Pred,\n\n) -> Handler<'a, Input, Output, Descr>\n\nwhere\n\n Pred: Injectable<Input, bool, FnArgs> + Send + Sync + 'a,\n\n Input: Send + Sync + 'a,\n\n Output: Send + Sync + 'a,\n\n{\n\n let pred = Arc::new(pred);\n\n\n\n from_fn_with_description(description, move |event, cont| {\n\n let pred = Arc::clone(&pred);\n\n\n\n async move {\n\n let pred = pred.inject(&event);\n\n let cond = pred().await;\n\n drop(pred);\n\n\n\n if cond {\n", "file_path": "src/handler/filter.rs", "rank": 14, "score": 101946.93555320262 }, { "content": "/// Insert some value to a container.\n\npub trait Insert<Value> {\n\n /// Inserts `value` into itself, returning the previous value, if exists.\n\n fn insert(&mut self, value: Value) -> Option<Arc<Value>>;\n\n}\n\n\n\nimpl<T: Send + Sync + 'static> Insert<T> for DependencyMap {\n\n fn insert(&mut self, value: T) -> Option<Arc<T>> {\n\n DependencyMap::insert(self, value)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn get() {\n\n let mut map = DependencyMap::new();\n\n map.insert(42i32);\n\n map.insert(\"hello world\");\n\n map.insert_container(deps![true]);\n\n\n\n assert_eq!(map.get(), Arc::new(42i32));\n\n assert_eq!(map.get(), Arc::new(\"hello world\"));\n\n assert_eq!(map.get(), Arc::new(true));\n\n }\n\n}\n", "file_path": "src/di.rs", "rank": 15, "score": 93927.88749866367 }, { "content": "#[must_use]\n\npub fn map_with_description<'a, Projection, Input, Output, NewType, Args, Descr>(\n\n description: Descr,\n\n proj: Projection,\n\n) -> Handler<'a, Input, Output, Descr>\n\nwhere\n\n Input: Clone,\n\n Asyncify<Projection>: Injectable<Input, NewType, Args> + Send + Sync + 'a,\n\n Input: Insert<NewType> + Send + Sync + 'a,\n\n Output: Send + Sync + 'a,\n\n Descr: HandlerDescription,\n\n NewType: Send,\n\n{\n\n map_async_with_description(description, Asyncify(proj))\n\n}\n\n\n\n/// [`map_async`] with a custom description.\n", "file_path": "src/handler/map.rs", "rank": 16, "score": 92550.40625734326 }, { "content": "/// A DI container from which we can extract a value of a given type.\n\n///\n\n/// There are two possible ways to handle the situation when your container\n\n/// cannot return a value of specified type:\n\n///\n\n/// 1. Do not implement [`DependencySupplier`] for the type. It often requires\n\n/// some type-level manipulations.\n\n/// 2. Runtime panic. Be careful in this case: check whether you add your type\n\n/// to the container.\n\n///\n\n/// A concrete solution is left to a particular implementation.\n\npub trait DependencySupplier<Value> {\n\n /// Get the value.\n\n ///\n\n /// We assume that all values are stored in `Arc<_>`.\n\n fn get(&self) -> Arc<Value>;\n\n}\n\n\n\n/// A DI container with multiple dependencies.\n\n///\n\n/// This DI container stores types by their corresponding type identifiers. It\n\n/// cannot prove at compile-time that a type of a requested value exists within\n\n/// the container, so if you do not provide necessary types but they were\n\n/// requested, it will panic.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// # use std::sync::Arc;\n\n/// use dptree::di::{DependencyMap, DependencySupplier};\n\n///\n", "file_path": "src/di.rs", "rank": 17, "score": 91777.26195894007 }, { "content": "#[must_use]\n\npub fn map_async_with_description<'a, Projection, Input, Output, NewType, Args, Descr>(\n\n description: Descr,\n\n proj: Projection,\n\n) -> Handler<'a, Input, Output, Descr>\n\nwhere\n\n Input: Clone,\n\n Projection: Injectable<Input, NewType, Args> + Send + Sync + 'a,\n\n Input: Insert<NewType> + Send + Sync + 'a,\n\n Output: Send + Sync + 'a,\n\n Descr: HandlerDescription,\n\n NewType: Send,\n\n{\n\n let proj = Arc::new(proj);\n\n\n\n from_fn_with_description(description, move |container: Input, cont| {\n\n let proj = Arc::clone(&proj);\n\n\n\n async move {\n\n let proj = proj.inject(&container);\n\n let res = proj().await;\n", "file_path": "src/handler/map.rs", "rank": 18, "score": 90762.42975638456 }, { "content": "type Transition = Endpoint<'static, Store, TransitionOut>;\n", "file_path": "examples/state_machine.rs", "rank": 19, "score": 86366.62315577304 }, { "content": "#[must_use]\n\n#[track_caller]\n\npub fn entry<'a, Input, Output, Descr>() -> Handler<'a, Input, Output, Descr>\n\nwhere\n\n Input: Send + Sync + 'a,\n\n Output: Send + Sync + 'a,\n\n Descr: HandlerDescription,\n\n{\n\n from_fn_with_description(Descr::entry(), |event, cont| cont(event))\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) fn help_inference<I, O>(h: Handler<I, O>) -> Handler<I, O> {\n\n h\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use maplit::hashset;\n\n\n\n use crate::{\n\n deps, description, filter_map, filter_map_with_description,\n", "file_path": "src/handler/core.rs", "rank": 20, "score": 84623.40106453602 }, { "content": "#[track_caller]\n\nfn collector(name: &'static str) -> CollectLocations {\n\n CollectLocations { locations: vec![(name, Location::caller())] }\n\n}\n\n\n\nimpl HandlerDescription for CollectLocations {\n\n #[track_caller]\n\n fn entry() -> Self {\n\n collector(\"entry\")\n\n }\n\n\n\n #[track_caller]\n\n fn user_defined() -> Self {\n\n collector(\"user_defined\")\n\n }\n\n\n\n #[track_caller]\n\n fn merge_chain(&self, other: &Self) -> Self {\n\n let locations = self\n\n .locations\n\n .iter()\n", "file_path": "examples/descr_locations.rs", "rank": 21, "score": 79092.6021451737 }, { "content": "#[must_use]\n\npub fn from_fn_with_description<'a, F, Fut, Input, Output, Descr>(\n\n description: Descr,\n\n f: F,\n\n) -> Handler<'a, Input, Output, Descr>\n\nwhere\n\n F: Fn(Input, Cont<'a, Input, Output>) -> Fut,\n\n F: Send + Sync + 'a,\n\n Fut: Future<Output = ControlFlow<Output, Input>> + Send + 'a,\n\n{\n\n Handler {\n\n data: Arc::new(HandlerData {\n\n f: move |event, cont| Box::pin(f(event, cont)) as HandlerResult<_, _>,\n\n description,\n\n }),\n\n }\n\n}\n\n\n\n/// Constructs an entry point handler.\n\n///\n\n/// This function is only used to specify other handlers upon it (see the root\n\n/// examples).\n", "file_path": "src/handler/core.rs", "rank": 22, "score": 77034.3110163111 }, { "content": "struct HandlerData<Descr, F: ?Sized> {\n\n description: Descr,\n\n f: F,\n\n}\n\n\n", "file_path": "src/handler/core.rs", "rank": 23, "score": 68033.50362159465 }, { "content": "#[must_use]\n\npub fn from_fn<'a, F, Fut, Input, Output, Descr>(f: F) -> Handler<'a, Input, Output, Descr>\n\nwhere\n\n F: Fn(Input, Cont<'a, Input, Output>) -> Fut + Send + Sync + 'a,\n\n Fut: Future<Output = ControlFlow<Output, Input>> + Send + 'a,\n\n Descr: HandlerDescription,\n\n{\n\n from_fn_with_description(Descr::user_defined(), f)\n\n}\n\n\n\n/// [`from_fn`] with a custom description.\n", "file_path": "src/handler/core.rs", "rank": 24, "score": 65341.30427542399 }, { "content": "#[derive(Clone)]\n\nstruct Dependency {\n\n type_name: &'static str,\n\n inner: Arc<dyn Any + Send + Sync>,\n\n}\n\n\n\nimpl PartialEq for DependencyMap {\n\n fn eq(&self, other: &Self) -> bool {\n\n let keys1 = self.map.keys();\n\n let keys2 = other.map.keys();\n\n keys1.zip(keys2).map(|(k1, k2)| k1 == k2).all(|x| x)\n\n }\n\n}\n\n\n\nimpl DependencyMap {\n\n pub fn new() -> Self {\n\n Self::default()\n\n }\n\n\n\n /// Inserts a value into the container.\n\n ///\n", "file_path": "src/di.rs", "rank": 25, "score": 54261.94131157676 }, { "content": "use crate::{\n\n di::{Asyncify, Injectable, Insert},\n\n from_fn_with_description, Handler, HandlerDescription,\n\n};\n\nuse std::{ops::ControlFlow, sync::Arc};\n\n\n\n/// Constructs a handler that optionally passes a value of a new type further.\n\n///\n\n/// If the `proj` function returns `Some(v)` then `v` will be added to the\n\n/// container and passed further in a handler chain. If the function returns\n\n/// `None`, then the handler will return [`ControlFlow::Continue`] with the old\n\n/// container.\n\n#[must_use]\n\n#[track_caller]\n", "file_path": "src/handler/filter_map.rs", "rank": 26, "score": 53972.53157666978 }, { "content": "\n\n match res {\n\n Some(new_type) => {\n\n let mut intermediate = container.clone();\n\n intermediate.insert(new_type);\n\n match cont(intermediate).await {\n\n ControlFlow::Continue(_) => ControlFlow::Continue(container),\n\n ControlFlow::Break(result) => ControlFlow::Break(result),\n\n }\n\n }\n\n None => ControlFlow::Continue(container),\n\n }\n\n }\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::{deps, help_inference};\n", "file_path": "src/handler/filter_map.rs", "rank": 27, "score": 53968.43611763874 }, { "content": "\n\n #[tokio::test]\n\n async fn test_some() {\n\n let value = 123;\n\n\n\n let result = help_inference(filter_map(move || Some(value)))\n\n .endpoint(move |event: i32| async move {\n\n assert_eq!(event, value);\n\n value\n\n })\n\n .dispatch(deps![])\n\n .await;\n\n\n\n assert!(result == ControlFlow::Break(value));\n\n }\n\n\n\n #[tokio::test]\n\n async fn test_none() {\n\n let result = help_inference(filter_map(|| None::<i32>))\n\n .endpoint(|| async move { unreachable!() })\n\n .dispatch(deps![])\n\n .await;\n\n\n\n assert!(result == ControlFlow::Continue(crate::deps![]));\n\n }\n\n}\n", "file_path": "src/handler/filter_map.rs", "rank": 28, "score": 53968.172500595574 }, { "content": "#[derive(Copy, Clone, Debug)]\n\nenum Event {\n\n Ping,\n\n SetValue(i32),\n\n PrintValue,\n\n}\n\n\n\nimpl Event {\n\n fn parse(input: &[&str]) -> Option<Self> {\n\n match input {\n\n [\"ping\"] => Some(Event::Ping),\n\n [\"set_value\", value] => Some(Event::SetValue(value.parse().ok()?)),\n\n [\"print\"] => Some(Event::PrintValue),\n\n _ => None,\n\n }\n\n }\n\n}\n\n\n", "file_path": "examples/simple_dispatcher.rs", "rank": 29, "score": 53374.19869119703 }, { "content": "struct CollectLocations {\n\n locations: Vec<(&'static str, &'static Location<'static>)>,\n\n}\n\n\n", "file_path": "examples/descr_locations.rs", "rank": 30, "score": 51767.401535891724 }, { "content": "fn main() {\n\n #[rustfmt::skip]\n\n let some_tree: Handler<DependencyMap, _, _> = dptree::entry()\n\n .branch(\n\n dptree::filter(|| true)\n\n .endpoint(|| async {})\n\n )\n\n .branch(\n\n dptree::filter_async(|| async { true })\n\n .chain(dptree::filter_map(|| Some(1) ))\n\n .endpoint(|| async {})\n\n );\n\n\n\n get_locations(&some_tree).iter().for_each(|(name, loc)| println!(\"{name: <12} @ {loc}\"));\n\n}\n", "file_path": "examples/descr_locations.rs", "rank": 31, "score": 45704.20982797119 }, { "content": "fn get_locations<'a, 'b>(\n\n handler: &'a Handler<'b, impl Send + Sync + 'b, impl Send + Sync + 'b, CollectLocations>,\n\n) -> &'a [(&'static str, &'static Location<'static>)] {\n\n &handler.description().locations\n\n}\n\n\n", "file_path": "examples/descr_locations.rs", "rank": 32, "score": 42358.266987880525 }, { "content": "type FsmHandler = Handler<'static, Store, TransitionOut>;\n\n\n", "file_path": "examples/state_machine.rs", "rank": 33, "score": 42199.059048529074 }, { "content": "fn sqrt_handler() -> WebHandler {\n\n dptree::filter_map(|req: &'static str| {\n\n if req.starts_with(\"/sqrt\") {\n\n let (_, n) = req.split_once(' ')?;\n\n n.parse::<f64>().ok()\n\n } else {\n\n None\n\n }\n\n })\n\n .endpoint(|n: f64| async move { format!(\"{}\", n.sqrt()) })\n\n}\n\n\n", "file_path": "examples/web_server.rs", "rank": 34, "score": 41395.830893277525 }, { "content": "fn ping_handler() -> CommandHandler {\n\n dptree::filter_async(|event: Event| async move { matches!(event, Event::Ping) })\n\n .endpoint(|| async { \"Pong\".to_string() })\n\n}\n\n\n", "file_path": "examples/simple_dispatcher.rs", "rank": 35, "score": 41395.830893277525 }, { "content": "fn paused_handler() -> FsmHandler {\n\n dptree::case![CommandState::Paused].branch(transitions::resume()).branch(transitions::end())\n\n}\n\n\n", "file_path": "examples/state_machine.rs", "rank": 36, "score": 41395.830893277525 }, { "content": "fn smiles_handler() -> WebHandler {\n\n dptree::filter(|req: &'static str| req.starts_with(\"/smile\"))\n\n .endpoint(|| async { \"🙃\".to_owned() })\n\n}\n\n\n", "file_path": "examples/web_server.rs", "rank": 37, "score": 41395.830893277525 }, { "content": "fn exit_handler() -> FsmHandler {\n\n dptree::case![CommandState::Exit].branch(transitions::exit())\n\n}\n", "file_path": "examples/state_machine.rs", "rank": 38, "score": 41395.830893277525 }, { "content": "fn active_handler() -> FsmHandler {\n\n dptree::case![CommandState::Active].branch(transitions::pause()).branch(transitions::end())\n\n}\n\n\n", "file_path": "examples/state_machine.rs", "rank": 39, "score": 41395.830893277525 }, { "content": "fn inactive_handler() -> FsmHandler {\n\n dptree::case![CommandState::Inactive].branch(transitions::begin()).branch(transitions::exit())\n\n}\n\n\n", "file_path": "examples/state_machine.rs", "rank": 40, "score": 41395.830893277525 }, { "content": "fn not_found_handler() -> WebHandler {\n\n dptree::endpoint(|| async { \"404 Not Found\".to_owned() })\n\n}\n", "file_path": "examples/web_server.rs", "rank": 41, "score": 41395.830893277525 }, { "content": "fn set_value_handler() -> CommandHandler {\n\n dptree::filter_map_async(|event: Event| async move {\n\n match event {\n\n Event::SetValue(value) => Some(value),\n\n _ => None,\n\n }\n\n })\n\n .endpoint(move |value: i32, store: Arc<AtomicI32>| async move {\n\n store.store(value, Ordering::SeqCst);\n\n format!(\"{} stored\", value)\n\n })\n\n}\n\n\n", "file_path": "examples/simple_dispatcher.rs", "rank": 42, "score": 40510.088125972594 }, { "content": "fn print_value_handler() -> CommandHandler {\n\n dptree::filter_async(|event: Event| async move { matches!(event, Event::PrintValue) }).endpoint(\n\n move |store: Arc<AtomicI32>| async move {\n\n let value = store.load(Ordering::SeqCst);\n\n format!(\"{}\", value)\n\n },\n\n )\n\n}\n", "file_path": "examples/simple_dispatcher.rs", "rank": 43, "score": 40510.088125972594 }, { "content": "use crate::{description, di::Injectable, from_fn_with_description, Handler, HandlerDescription};\n\nuse futures::FutureExt;\n\nuse std::{ops::ControlFlow, sync::Arc};\n\n\n\nimpl<'a, Input, Output, Descr> Handler<'a, Input, Output, Descr>\n\nwhere\n\n Input: Send + Sync + 'a,\n\n Output: Send + Sync + 'a,\n\n Descr: HandlerDescription,\n\n{\n\n /// Chain this handler with the endpoint handler `f`.\n\n #[must_use]\n\n #[track_caller]\n\n pub fn endpoint<F, FnArgs>(self, f: F) -> Endpoint<'a, Input, Output, Descr>\n\n where\n\n F: Injectable<Input, Output, FnArgs> + Send + Sync + 'a,\n\n {\n\n self.chain(endpoint(f))\n\n }\n\n}\n\n\n\n/// Constructs a handler that has no further handlers in a chain.\n\n///\n\n/// An endpoint is a handler that _always_ breaks handler execution after its\n\n/// completion. So, you can use it when your chain of responsibility must end\n\n/// up, and handle an incoming event.\n\n#[must_use]\n\n#[track_caller]\n", "file_path": "src/handler/endpoint.rs", "rank": 44, "score": 28755.788048130416 }, { "content": " Handler<'a, Input, Output, Descr>;\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::{deps, help_inference};\n\n\n\n #[tokio::test]\n\n async fn test_endpoint() {\n\n let input = 123;\n\n let output = 7;\n\n\n\n let result = help_inference(endpoint(move |num: i32| async move {\n\n assert_eq!(num, input);\n\n output\n\n }))\n\n .dispatch(deps![input])\n\n .await;\n\n\n\n let result = match result {\n\n ControlFlow::Break(b) => b,\n\n _ => panic!(\"Unexpected: handler return ControlFlow::Break\"),\n\n };\n\n assert_eq!(result, output);\n\n }\n\n}\n", "file_path": "src/handler/endpoint.rs", "rank": 45, "score": 28747.834077232237 }, { "content": "use crate::{\n\n di::{Asyncify, Injectable},\n\n from_fn_with_description,\n\n handler::core::Handler,\n\n HandlerDescription,\n\n};\n\nuse std::{ops::ControlFlow, sync::Arc};\n\n\n\n/// Constructs a handler that filters input with the predicate `pred`.\n\n///\n\n/// `pred` has an access to all values that are stored in the input container.\n\n/// If it returns `true`, a continuation of the handler will be called,\n\n/// otherwise the handler returns [`ControlFlow::Continue`].\n\n#[must_use]\n\n#[track_caller]\n", "file_path": "src/handler/filter.rs", "rank": 46, "score": 28336.225145953722 }, { "content": " assert_eq!(event, input_value);\n\n true\n\n }))\n\n .endpoint(move |event: i32| async move {\n\n assert_eq!(event, input_value);\n\n output\n\n })\n\n .dispatch(input)\n\n .await;\n\n\n\n assert!(result == ControlFlow::Break(output));\n\n }\n\n\n\n #[tokio::test]\n\n async fn test_and_then_filter() {\n\n let input = 123;\n\n let output = 7;\n\n\n\n let result = help_inference(filter(move |event: i32| {\n\n assert_eq!(event, input);\n", "file_path": "src/handler/filter.rs", "rank": 47, "score": 28332.87634485482 }, { "content": " cont(event).await\n\n } else {\n\n ControlFlow::Continue(event)\n\n }\n\n }\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::{deps, help_inference};\n\n\n\n #[tokio::test]\n\n async fn test_filter() {\n\n let input_value = 123;\n\n let input = deps![input_value];\n\n let output = 7;\n\n\n\n let result = help_inference(filter_async(move |event: i32| async move {\n", "file_path": "src/handler/filter.rs", "rank": 48, "score": 28332.46251647711 }, { "content": " true\n\n }))\n\n .chain(\n\n filter_async(move |event: i32| async move {\n\n assert_eq!(event, input);\n\n true\n\n })\n\n .endpoint(move |event: i32| async move {\n\n assert_eq!(event, input);\n\n output\n\n }),\n\n )\n\n .dispatch(deps![input])\n\n .await;\n\n\n\n assert!(result == ControlFlow::Break(output));\n\n }\n\n}\n", "file_path": "src/handler/filter.rs", "rank": 49, "score": 28330.825804268537 }, { "content": "use crate::{\n\n di::{Asyncify, Injectable, Insert},\n\n from_fn_with_description, Handler, HandlerDescription,\n\n};\n\nuse std::{ops::ControlFlow, sync::Arc};\n\n\n\n/// Constructs a handler that passes a value of a new type further.\n\n///\n\n/// The result of invoking `proj` will be added to the container and passed\n\n/// further in a handler chain.\n\n///\n\n/// See also: [`crate::filter_map`].\n\n#[must_use]\n\n#[track_caller]\n", "file_path": "src/handler/map.rs", "rank": 50, "score": 28194.18758197884 }, { "content": " std::mem::drop(proj);\n\n\n\n let mut intermediate = container.clone();\n\n intermediate.insert(res);\n\n match cont(intermediate).await {\n\n ControlFlow::Continue(_) => ControlFlow::Continue(container),\n\n ControlFlow::Break(result) => ControlFlow::Break(result),\n\n }\n\n }\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::{deps, help_inference};\n\n\n\n #[tokio::test]\n\n async fn test_map() {\n\n let value = 123;\n", "file_path": "src/handler/map.rs", "rank": 51, "score": 28191.41688061015 }, { "content": "\n\n let result = help_inference(map(move || value))\n\n .endpoint(move |event: i32| async move {\n\n assert_eq!(event, value);\n\n value\n\n })\n\n .dispatch(deps![])\n\n .await;\n\n\n\n assert!(result == ControlFlow::Break(value));\n\n }\n\n}\n", "file_path": "src/handler/map.rs", "rank": 52, "score": 28188.32332798353 }, { "content": "type Store = Arc<DependencyMap>;\n\n\n\n#[tokio::main]\n\nasync fn main() {\n\n fn assert_num_string_handler(\n\n expected_num: u32,\n\n expected_string: &'static str,\n\n ) -> Endpoint<'static, Store, ()> {\n\n // The handler requires `u32` and `String` types from the input storage.\n\n dptree::endpoint(move |num: u32, string: String| async move {\n\n assert_eq!(num, expected_num);\n\n assert_eq!(string, expected_string);\n\n })\n\n }\n\n\n\n // Init storage with string and num\n\n let store = Arc::new(dptree::deps![10u32, \"Hello\".to_owned()]);\n\n\n\n let str_num_handler = assert_num_string_handler(10u32, \"Hello\");\n\n\n", "file_path": "examples/storage.rs", "rank": 53, "score": 24687.47907524598 }, { "content": "type Store = dptree::di::DependencyMap;\n", "file_path": "examples/state_machine.rs", "rank": 54, "score": 22801.64052358502 }, { "content": "//! Commonly used items.\n\n\n\npub use crate::{di::DependencyMap, Endpoint, Handler};\n\npub use std::ops::ControlFlow;\n", "file_path": "src/prelude.rs", "rank": 56, "score": 14.292753718292591 }, { "content": " #[allow(non_snake_case)]\n\n #[allow(unused_variables)]\n\n fn inject<'a>(&'a self, container: &'a Input) -> CompiledFn<'a, Output> {\n\n Arc::new(move || {\n\n $(let $generic = std::borrow::Borrow::<$generic>::borrow(&container.get()).clone();)*\n\n let fut = self( $( $generic ),* );\n\n Box::pin(fut)\n\n })\n\n }\n\n }\n\n\n\n impl<Func, Input, Output, $($generic),*> Injectable<Input, Output, ($($generic,)*)> for Asyncify<Func>\n\n where\n\n Input: $(DependencySupplier<$generic> +)*,\n\n Input: Send + Sync,\n\n Func: Fn($($generic),*) -> Output + Send + Sync + 'static,\n\n Output: Send + 'static,\n\n $($generic: Clone + Send + Sync),*\n\n {\n\n #[allow(non_snake_case)]\n", "file_path": "src/di.rs", "rank": 57, "score": 13.830068315785352 }, { "content": " where\n\n Out: Send + Sync + 'static,\n\n {\n\n filter_map_with_description(\n\n InterestList(hashset! { UpdateKind::B }),\n\n |update: Update| match update {\n\n Update::B(x) => Some(x),\n\n _ => None,\n\n },\n\n )\n\n }\n\n\n\n fn filter_c<Out>(\n\n ) -> Handler<'static, DependencyMap, Out, description::EventKind<UpdateKind>>\n\n where\n\n Out: Send + Sync + 'static,\n\n {\n\n filter_map_with_description(\n\n InterestList(hashset! { UpdateKind::C }),\n\n |update: Update| match update {\n", "file_path": "src/handler/core.rs", "rank": 58, "score": 13.779291915205254 }, { "content": " }\n\n}\n\n\n\nimpl<V> DependencySupplier<V> for DependencyMap\n\nwhere\n\n V: Send + Sync + 'static,\n\n{\n\n fn get(&self) -> Arc<V> {\n\n self.map\n\n .get(&TypeId::of::<V>())\n\n .unwrap_or_else(|| {\n\n panic!(\n\n \"{} was requested, but not provided. Available types:\\n{}\",\n\n std::any::type_name::<V>(),\n\n self.available_types()\n\n )\n\n })\n\n .clone()\n\n .inner\n\n .downcast::<V>()\n", "file_path": "src/di.rs", "rank": 59, "score": 12.905650533098525 }, { "content": " pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<Arc<T>> {\n\n self.map\n\n .remove(&TypeId::of::<T>())\n\n .map(|dep| dep.inner.downcast().expect(\"Values are stored by TypeId\"))\n\n }\n\n\n\n fn available_types(&self) -> String {\n\n let mut list = String::new();\n\n\n\n for dep in self.map.values() {\n\n writeln!(list, \" {}\", dep.type_name).unwrap();\n\n }\n\n\n\n list\n\n }\n\n}\n\n\n\nimpl Debug for DependencyMap {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {\n\n f.debug_struct(\"DependencyMap\").finish()\n", "file_path": "src/di.rs", "rank": 60, "score": 12.807727000511091 }, { "content": " /// If the container do not has this type present, `None` is returned.\n\n /// Otherwise, the value is updated, and the old value is returned.\n\n pub fn insert<T: Send + Sync + 'static>(&mut self, item: T) -> Option<Arc<T>> {\n\n self.map\n\n .insert(\n\n TypeId::of::<T>(),\n\n Dependency { type_name: std::any::type_name::<T>(), inner: Arc::new(item) },\n\n )\n\n .map(|dep| dep.inner.downcast().expect(\"Values are stored by TypeId\"))\n\n }\n\n\n\n /// Inserts all dependencies from another container into itself.\n\n pub fn insert_container(&mut self, container: Self) {\n\n self.map.extend(container.map);\n\n }\n\n\n\n /// Removes a value from the container.\n\n ///\n\n /// If the container do not has this type present, `None` is returned.\n\n /// Otherwise, the value is removed and returned.\n", "file_path": "src/di.rs", "rank": 62, "score": 11.9947725541206 }, { "content": " B(u8),\n\n C(u64),\n\n }\n\n\n\n fn filter_a<Out>(\n\n ) -> Handler<'static, DependencyMap, Out, description::EventKind<UpdateKind>>\n\n where\n\n Out: Send + Sync + 'static,\n\n {\n\n filter_map_with_description(\n\n InterestList(hashset! { UpdateKind::A }),\n\n |update: Update| match update {\n\n Update::A(x) => Some(x),\n\n _ => None,\n\n },\n\n )\n\n }\n\n\n\n fn filter_b<Out>(\n\n ) -> Handler<'static, DependencyMap, Out, description::EventKind<UpdateKind>>\n", "file_path": "src/handler/core.rs", "rank": 63, "score": 11.781195466309825 }, { "content": " Update::B(x) => Some(x),\n\n _ => None,\n\n },\n\n )\n\n }\n\n\n\n // User-defined filter that doesn't provide allowed updates\n\n fn user_defined_filter<Out>(\n\n ) -> Handler<'static, DependencyMap, Out, description::EventKind<UpdateKind>>\n\n where\n\n Out: Send + Sync + 'static,\n\n {\n\n filter_map(|update: Update| match update {\n\n Update::B(x) => Some(x),\n\n _ => None,\n\n })\n\n }\n\n\n\n #[track_caller]\n\n fn assert(\n", "file_path": "src/handler/core.rs", "rank": 65, "score": 11.361693460926134 }, { "content": "# dptree\n\n[![Rust](https://github.com/p0lunin/dptree/actions/workflows/rust.yml/badge.svg)](https://github.com/p0lunin/dptree/actions/workflows/rust.yml)\n\n[![Crates.io](https://img.shields.io/crates/v/dptree.svg)](https://crates.io/crates/dptree)\n\n[![Docs.rs](https://docs.rs/dptree/badge.svg)](https://docs.rs/dptree)\n\n\n\nAn implementation of the [chain (tree) of responsibility] pattern.\n\n\n\n[[`examples/web_server.rs`](examples/web_server.rs)]\n\n```rust\n\nuse dptree::prelude::*;\n\n\n\ntype WebHandler = Endpoint<'static, DependencyMap, String>;\n\n\n\n#[rustfmt::skip]\n\n#[tokio::main]\n\nasync fn main() {\n\n let web_server = dptree::entry()\n\n .branch(smiles_handler())\n\n .branch(sqrt_handler())\n\n .branch(not_found_handler());\n\n\n\n assert_eq!(\n\n web_server.dispatch(dptree::deps![\"/smile\"]).await,\n\n ControlFlow::Break(\"🙃\".to_owned())\n\n );\n\n assert_eq!(\n\n web_server.dispatch(dptree::deps![\"/sqrt 16\"]).await,\n\n ControlFlow::Break(\"4\".to_owned())\n\n );\n\n assert_eq!(\n\n web_server.dispatch(dptree::deps![\"/lol\"]).await,\n\n ControlFlow::Break(\"404 Not Found\".to_owned())\n\n );\n\n}\n\n\n\nfn smiles_handler() -> WebHandler {\n\n dptree::filter(|req: &'static str| req.starts_with(\"/smile\"))\n\n .endpoint(|| async { \"🙃\".to_owned() })\n\n}\n\n\n\nfn sqrt_handler() -> WebHandler {\n\n dptree::filter_map(|req: &'static str| {\n\n if req.starts_with(\"/sqrt\") {\n\n let (_, n) = req.split_once(' ')?;\n\n n.parse::<f64>().ok()\n\n } else {\n\n None\n\n }\n\n })\n\n .endpoint(|n: f64| async move { format!(\"{}\", n.sqrt()) })\n\n}\n\n\n\nfn not_found_handler() -> WebHandler {\n\n dptree::endpoint(|| async { \"404 Not Found\".to_owned() })\n\n}\n\n```\n\n\n", "file_path": "README.md", "rank": 67, "score": 10.859506997964981 }, { "content": "//! An implementation of the [chain (tree) of responsibility] pattern.\n\n//!\n\n//! ```\n\n//! use dptree::prelude::*;\n\n//!\n\n//! type WebHandler = Endpoint<'static, DependencyMap, String>;\n\n//!\n\n//! #[rustfmt::skip]\n\n//! #[tokio::main]\n\n//! async fn main() {\n\n//! let web_server = dptree::entry()\n\n//! .branch(smiles_handler())\n\n//! .branch(sqrt_handler())\n\n//! .branch(not_found_handler());\n\n//! \n\n//! assert_eq!(\n\n//! web_server.dispatch(dptree::deps![\"/smile\"]).await,\n\n//! ControlFlow::Break(\"🙃\".to_owned())\n\n//! );\n\n//! assert_eq!(\n", "file_path": "src/lib.rs", "rank": 68, "score": 10.85007183113916 }, { "content": "mod core;\n\npub mod description;\n\nmod endpoint;\n\nmod filter;\n\nmod filter_map;\n\nmod map;\n\n\n\npub use self::core::*;\n\npub use description::HandlerDescription;\n\npub use endpoint::*;\n\npub use filter::*;\n\npub use filter_map::*;\n\npub use map::*;\n", "file_path": "src/handler.rs", "rank": 69, "score": 10.60624801538126 }, { "content": " /// assert_eq!(\n\n /// handler.dispatch(dptree::deps![-10]).await,\n\n /// ControlFlow::Continue(dptree::deps![-10])\n\n /// );\n\n ///\n\n /// # }\n\n /// ```\n\n ///\n\n /// [chain of responsibility]: https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern\n\n #[must_use]\n\n #[track_caller]\n\n pub fn chain(self, next: Self) -> Self {\n\n let required_update_kinds_set = self.description().merge_chain(next.description());\n\n\n\n from_fn_with_description(required_update_kinds_set, move |event, cont| {\n\n let this = self.clone();\n\n let next = next.clone();\n\n let cont = Arc::new(cont);\n\n\n\n this.execute(event, move |event| {\n", "file_path": "src/handler/core.rs", "rank": 70, "score": 10.537806057419724 }, { "content": " /// );\n\n /// # }\n\n /// ```\n\n #[must_use]\n\n #[track_caller]\n\n pub fn branch(self, next: Self) -> Self {\n\n let required_update_kinds_set = self.description().merge_branch(next.description());\n\n\n\n from_fn_with_description(required_update_kinds_set, move |event, cont| {\n\n let this = self.clone();\n\n let next = next.clone();\n\n let cont = Arc::new(cont);\n\n\n\n this.execute(event, move |event| {\n\n let next = next.clone();\n\n let cont = cont.clone();\n\n\n\n async move {\n\n match next.dispatch(event).await {\n\n ControlFlow::Continue(event) => cont(event).await,\n", "file_path": "src/handler/core.rs", "rank": 72, "score": 9.942065341190846 }, { "content": "/// let mut container = DependencyMap::new();\n\n/// container.insert(5_i32);\n\n/// container.insert(\"abc\");\n\n///\n\n/// assert_eq!(container.get(), Arc::new(5_i32));\n\n/// assert_eq!(container.get(), Arc::new(\"abc\"));\n\n///\n\n/// // If a type of a value already exists within the container, it will be replaced.\n\n/// let old_value = container.insert(10_i32).unwrap();\n\n///\n\n/// assert_eq!(old_value, Arc::new(5_i32));\n\n/// assert_eq!(container.get(), Arc::new(10_i32));\n\n/// ```\n\n///\n\n/// When a value is not found within the container, it will panic:\n\n///\n\n/// ```should_panic\n\n/// # use std::sync::Arc;\n\n/// use dptree::di::{DependencyMap, DependencySupplier};\n\n/// let mut container = DependencyMap::new();\n", "file_path": "src/di.rs", "rank": 73, "score": 9.8166885386589 }, { "content": "use std::{future::Future, ops::ControlFlow, sync::Arc};\n\n\n\nuse futures::future::BoxFuture;\n\n\n\nuse crate::{description, HandlerDescription};\n\n\n\n/// An instance that receives an input and decides whether to break a chain or\n\n/// pass the value further.\n\n///\n\n/// In order to create this structure, you can use the predefined functions from\n\n/// [`crate`].\n\npub struct Handler<'a, Input, Output, Descr = description::Unspecified> {\n\n data: Arc<HandlerData<Descr, DynF<'a, Input, Output>>>,\n\n}\n\n\n", "file_path": "src/handler/core.rs", "rank": 74, "score": 9.630295976660939 }, { "content": " handler: Handler<'static, DependencyMap, (), description::EventKind<UpdateKind>>,\n\n allowed: description::EventKind<UpdateKind>,\n\n ) {\n\n assert_eq!(handler.description(), &allowed)\n\n }\n\n\n\n assert(filter_a().chain(filter_b()), InterestList(hashset! {}));\n\n assert(entry().chain(filter_b()), InterestList(hashset! { UpdateKind::B }));\n\n\n\n assert(\n\n filter_a().branch(filter_b()),\n\n InterestList(hashset! { UpdateKind::A, UpdateKind::B }),\n\n );\n\n assert(\n\n filter_a().branch(filter_b()).branch(filter_c().chain(filter_c())),\n\n InterestList(hashset! { UpdateKind::A, UpdateKind::B, UpdateKind::C }),\n\n );\n\n assert(filter_a().chain(filter(|| true)), InterestList(hashset! { UpdateKind::A }));\n\n assert(user_defined_filter().chain(filter_a()), UserDefined);\n\n assert(filter_a().chain(user_defined_filter()), InterestList(hashset! { UpdateKind::A }));\n", "file_path": "src/handler/core.rs", "rank": 75, "score": 9.50151033076001 }, { "content": " handler::{endpoint, filter, filter_async},\n\n prelude::DependencyMap,\n\n };\n\n\n\n use super::*;\n\n\n\n #[tokio::test]\n\n async fn test_from_fn_break() {\n\n let input = 123;\n\n let output = \"ABC\";\n\n\n\n let result = help_inference(from_fn(|event, _cont: Cont<i32, &'static str>| async move {\n\n assert_eq!(event, input);\n\n ControlFlow::Break(output)\n\n }))\n\n .dispatch(input)\n\n .await;\n\n\n\n assert!(result == ControlFlow::Break(output));\n\n }\n", "file_path": "src/handler/core.rs", "rank": 76, "score": 9.193878282214413 }, { "content": "/// container.insert(10i32);\n\n/// container.insert(true);\n\n/// container.insert(\"static str\");\n\n///\n\n/// // thread 'main' panicked at 'alloc::string::String was requested, but not provided. Available types:\n\n/// // &str\n\n/// // bool\n\n/// // i32\n\n/// // ', /media/hirrolot/772CF8924BEBB279/Documents/Rust/dptree/src/di.rs:150:17\n\n/// // note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n\n/// let string: Arc<String> = container.get();\n\n/// ```\n\n#[derive(Default, Clone)]\n\npub struct DependencyMap {\n\n map: HashMap<TypeId, Dependency>,\n\n}\n\n\n", "file_path": "src/di.rs", "rank": 78, "score": 9.15879141989109 }, { "content": "use dptree::prelude::*;\n\nuse std::{net::Ipv4Addr, sync::Arc};\n\n\n", "file_path": "examples/storage.rs", "rank": 79, "score": 8.987142421982181 }, { "content": "\n\n // Entry is invisible\n\n assert(entry().branch(filter_a()), InterestList(hashset! { UpdateKind::A }));\n\n assert(entry(), Entry);\n\n\n\n assert(user_defined_filter(), UserDefined);\n\n assert(user_defined_filter().branch(filter_a()), UserDefined);\n\n }\n\n}\n", "file_path": "src/handler/core.rs", "rank": 80, "score": 8.937056484507611 }, { "content": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\n\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\n\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n\n\n## unreleased\n\n\n\n## 0.2.1 - 2022-04-27\n\n\n\n### Added\n\n\n\n - The `dptree::case!` macro for enumeration destructuring.\n\n\n\n## 0.2.0 - 2022-04-18\n\n\n\n### Added\n\n\n\n - Introspection facilities:\n\n - The `HandlerDescription` trait.\n\n - Build-in description types: `crate::description::{Unspecified, EventKind}`.\n\n - Functions constructing handlers with descriptions: `filter_async_with_description`, `filter_map_async_with_description`, `filter_map_with_description`, `filter_with_description`, `from_fn_with_description`, `map_async_with_description`, `map_with_description`.\n\n\n\n## 0.1.2 - 2022-04-04\n\n\n\n### Added\n\n\n\n - `DependencyMap::insert_container` ([PR #7](https://github.com/p0lunin/dptree/pull/7)).\n\n - `map` and `map_async` ([PR #8](https://github.com/p0lunin/dptree/pull/8)).\n\n\n\n## 0.1.1 - 2022-03-21\n\n\n\n### Fixed\n\n\n\n - Emit a full list of available types on `DependencyMap::get` panic ([PR #6](https://github.com/p0lunin/dptree/pull/6)).\n\n\n\n## 0.1.0 - 2022-02-05\n\n\n\n### Added\n\n\n\n - This badass library.\n", "file_path": "CHANGELOG.md", "rank": 81, "score": 8.821104245429446 }, { "content": "use std::panic::Location;\n\n\n\nuse dptree::{di::DependencyMap, Handler, HandlerDescription};\n\n\n", "file_path": "examples/descr_locations.rs", "rank": 83, "score": 8.576579813998146 }, { "content": "\n\n #[tokio::test]\n\n async fn test_from_fn_continue() {\n\n let input = 123;\n\n type Output = &'static str;\n\n\n\n let result =\n\n help_inference(from_fn(|event: i32, _cont: Cont<i32, &'static str>| async move {\n\n assert_eq!(event, input);\n\n ControlFlow::<Output, _>::Continue(event)\n\n }))\n\n .dispatch(input)\n\n .await;\n\n\n\n assert!(result == ControlFlow::Continue(input));\n\n }\n\n\n\n #[tokio::test]\n\n async fn test_entry() {\n\n let input = 123;\n", "file_path": "src/handler/core.rs", "rank": 84, "score": 8.570999837848829 }, { "content": " assert_eq!(dispatcher.dispatch(deps![0]).await, ControlFlow::Break(Output::Zero));\n\n assert_eq!(dispatcher.dispatch(deps![-1]).await, ControlFlow::Break(Output::MinusOne));\n\n assert_eq!(dispatcher.dispatch(deps![-2]).await, ControlFlow::Break(Output::LT));\n\n }\n\n\n\n #[tokio::test]\n\n async fn allowed_updates() {\n\n use crate::description::EventKind::*;\n\n\n\n #[derive(Debug, Clone, PartialEq, Eq, Hash)]\n\n enum UpdateKind {\n\n A,\n\n B,\n\n C,\n\n }\n\n\n\n #[derive(Clone)]\n\n #[allow(dead_code)]\n\n enum Update {\n\n A(i32),\n", "file_path": "src/handler/core.rs", "rank": 85, "score": 8.351584995629743 }, { "content": " /// let handler: Handler<_, _> = dptree::filter(|x: i32| x > 0);\n\n ///\n\n /// let output = handler.execute(dptree::deps![10], |_| async { ControlFlow::Break(\"done\") }).await;\n\n /// assert_eq!(output, ControlFlow::Break(\"done\"));\n\n ///\n\n /// # }\n\n /// ```\n\n pub async fn execute<Cont, ContFut>(\n\n self,\n\n container: Input,\n\n cont: Cont,\n\n ) -> ControlFlow<Output, Input>\n\n where\n\n Cont: Fn(Input) -> ContFut,\n\n Cont: Send + Sync + 'a,\n\n ContFut: Future<Output = ControlFlow<Output, Input>> + Send + 'a,\n\n {\n\n (self.data.f)(container, Box::new(move |event| Box::pin(cont(event)))).await\n\n }\n\n\n", "file_path": "src/handler/core.rs", "rank": 86, "score": 8.18308766791963 }, { "content": " Input: Send + Sync + 'a,\n\n Output: Send + Sync + 'a,\n\n Descr: HandlerDescription,\n\n{\n\n /// Chain two handlers to form a [chain of responsibility].\n\n ///\n\n /// First, `self` will be executed, and then, if `self` decides to continue\n\n /// execution, `next` will be executed.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// # #[tokio::main]\n\n /// # async fn main() {\n\n /// use dptree::prelude::*;\n\n ///\n\n /// let handler: Handler<_, _> =\n\n /// dptree::filter(|x: i32| x > 0).chain(dptree::endpoint(|| async { \"done\" }));\n\n ///\n\n /// assert_eq!(handler.dispatch(dptree::deps![10]).await, ControlFlow::Break(\"done\"));\n", "file_path": "src/handler/core.rs", "rank": 87, "score": 8.087561205288324 }, { "content": "pub use handler::*;\n\n\n\n/// Filters an enumeration, passing its payload forwards.\n\n///\n\n/// This macro expands to a [`crate::Handler`] that acts on your enumeration\n\n/// type: if the enumeration is of a certain variant, the execution continues;\n\n/// otherwise, `dptree` will try the next branch. This is very useful for\n\n/// dialogue FSM transitions and incoming command filtering; for a real-world\n\n/// example, please see teloxide's [`examples/purchase.rs`].\n\n///\n\n/// Variants can take the following forms:\n\n///\n\n/// - `Enum::MyVariant` for empty variants;\n\n/// - `Enum::MyVariant(param1, ..., paramN)` for function-like variants;\n\n/// - `Enum::MyVariant { param1, ..., paramN }` for `struct`-like variants.\n\n///\n\n/// In the first case, this macro results in a simple [`crate::filter`]; in the\n\n/// second and third cases, this macro results in [`crate::filter_map`] that\n\n/// passes the payload of `MyVariant` to the next handler if the match occurs.\n\n/// (This next handler can be an endpoint or a more complex one.) The payload\n", "file_path": "src/lib.rs", "rank": 88, "score": 7.649273365886637 }, { "content": " continue;\n\n }\n\n },\n\n _ => {\n\n println!(\"Unknown event\");\n\n continue;\n\n }\n\n };\n\n\n\n if new_state == CommandState::Exit {\n\n return;\n\n }\n\n\n\n state = new_state;\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq)]\n\npub enum CommandState {\n\n Active,\n", "file_path": "examples/state_machine.rs", "rank": 89, "score": 7.119803249869147 }, { "content": "\n\n #[track_caller]\n\n fn map() -> Self {\n\n collector(\"map\")\n\n }\n\n\n\n #[track_caller]\n\n fn map_async() -> Self {\n\n collector(\"map_async\")\n\n }\n\n\n\n #[track_caller]\n\n fn filter() -> Self {\n\n collector(\"filter\")\n\n }\n\n\n\n #[track_caller]\n\n fn filter_async() -> Self {\n\n collector(\"filter_async\")\n\n }\n", "file_path": "examples/descr_locations.rs", "rank": 90, "score": 7.051233225197138 }, { "content": "\n\n #[track_caller]\n\n fn filter_map() -> Self {\n\n collector(\"filter_map\")\n\n }\n\n\n\n #[track_caller]\n\n fn filter_map_async() -> Self {\n\n collector(\"filter_map_async\")\n\n }\n\n\n\n #[track_caller]\n\n fn endpoint() -> Self {\n\n collector(\"endpoint\")\n\n }\n\n}\n\n\n", "file_path": "examples/descr_locations.rs", "rank": 92, "score": 6.983076237904248 }, { "content": " assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));\n\n }\n\n\n\n #[tokio::test]\n\n async fn handler_fn_variant() {\n\n let input = State::C(42, \"abc\");\n\n let h: crate::Handler<_, _> =\n\n case![State::C(x, y)].endpoint(|(x, str): (i32, &'static str)| async move {\n\n assert_eq!(x, 42);\n\n assert_eq!(str, \"abc\");\n\n 123\n\n });\n\n\n\n assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));\n\n assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));\n\n }\n\n\n\n #[tokio::test]\n\n async fn handler_single_struct_variant() {\n\n let input = State::D { foo: 42 };\n", "file_path": "src/lib.rs", "rank": 93, "score": 6.896835682971065 }, { "content": "\n\nasync fn repl(dispatcher: Handler<'static, DependencyMap, String>, store: Arc<AtomicI32>) -> ! {\n\n loop {\n\n print!(\">> \");\n\n std::io::stdout().flush().unwrap();\n\n\n\n let mut cmd = String::new();\n\n std::io::stdin().read_line(&mut cmd).unwrap();\n\n\n\n let strs = cmd.trim().split(' ').collect::<Vec<_>>();\n\n let event = Event::parse(strs.as_slice());\n\n\n\n let out = match event {\n\n Some(event) => match dispatcher.dispatch(dptree::deps![event, store.clone()]).await {\n\n ControlFlow::Continue(event) => panic!(\"Unhandled event {:?}\", event),\n\n ControlFlow::Break(result) => result,\n\n },\n\n _ => \"Unknown command\".to_string(),\n\n };\n\n\n\n println!(\"{}\", out);\n\n }\n\n}\n\n\n\n#[derive(Copy, Clone, Debug)]\n", "file_path": "examples/simple_dispatcher.rs", "rank": 94, "score": 6.792299227993009 }, { "content": "## Features\n\n\n\n - ✔️ Declarative handlers: `dptree::{endpoint, filter, filter_map, ...}`.\n\n - ✔️ A lightweight functional design using a form of [continuation-passing style (CPS)] internally.\n\n - ✔️ [Dependency injection (DI)] out-of-the-box.\n\n - ✔️ Supports both handler _chaining_ and _branching_ operations.\n\n - ✔️ Handler introspection facilities.\n\n - ✔️ Battle-tested: dptree is used in [teloxide] as a framework for Telegram update dispatching.\n\n - ✔️ Runtime-agnostic: uses only the [futures] crate.\n\n\n\n[continuation-passing style (CPS)]: https://en.wikipedia.org/wiki/Continuation-passing_style\n\n[Dependency injection (DI)]: https://en.wikipedia.org/wiki/Dependency_injection\n\n[teloxide]: https://github.com/teloxide/teloxide\n\n[futures]: https://github.com/rust-lang/futures-rs\n\n\n\n## Explanation\n\n\n\nThe above code is a simple web server dispatching tree. In pseudocode, it would look like this:\n\n\n\n - `dptree::entry()`: dispatch an update to the following branch handlers:\n\n - `.branch(smiles_handler())`: if the update satisfies the condition (`dptree::filter`), return a smile (`.endpoint`). Otherwise, pass the update forwards.\n\n - `.branch(sqrt_handler())`: if the update is a number (`dptree::filter_map`), return the square of it. Otherwise, pass the update forwards.\n\n - `.branch(not_found_handler())`: return `404 Not Found` immediately.\n\n\n", "file_path": "README.md", "rank": 95, "score": 6.734516095822276 }, { "content": "//! An implementation of [dependency injection].\n\n//!\n\n//! If you do not know what is dependency injection (DI), please read [this\n\n//! discussion on StackOverflow], then come back. The only difference is that in\n\n//! `dptree`, we inject objects into function-handlers, not into objects.\n\n//!\n\n//! Currently, the only container is [`DependencyMap`]. It implements the DI\n\n//! pattern completely, but be careful: it can panic when you do not provide\n\n//! necessary types. See more in its documentation.\n\n//!\n\n//! [dependency injection]: https://en.wikipedia.org/wiki/Dependency_injection\n\n//! [this discussion on StackOverflow]: https://stackoverflow.com/questions/130794/what-is-dependency-injection\n\nuse futures::future::{ready, BoxFuture};\n\n\n\nuse std::{\n\n any::{Any, TypeId},\n\n collections::HashMap,\n\n fmt::{Debug, Formatter, Write},\n\n future::Future,\n\n ops::Deref,\n", "file_path": "src/di.rs", "rank": 97, "score": 6.71576266591552 }, { "content": " })\n\n };\n\n ($($variant:ident)::+ {$param:ident}) => {\n\n $crate::filter_map(|x| match x {\n\n $($variant)::+{$param} => Some($param),\n\n _ => None,\n\n })\n\n };\n\n ($($variant:ident)::+ {$($param:ident),+ $(,)?}) => {\n\n $crate::filter_map(|x| match x {\n\n $($variant)::+ { $($param),+ } => Some(($($param),+ ,)),\n\n _ => None,\n\n })\n\n };\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::ops::ControlFlow;\n\n\n", "file_path": "src/lib.rs", "rank": 98, "score": 6.625783853079696 }, { "content": " /// Executes this handler.\n\n ///\n\n /// Returns [`ControlFlow::Break`] when executed successfully,\n\n /// [`ControlFlow::Continue`] otherwise.\n\n pub async fn dispatch(&self, container: Input) -> ControlFlow<Output, Input> {\n\n self.clone().execute(container, |event| async move { ControlFlow::Continue(event) }).await\n\n }\n\n\n\n /// Returns the set of updates that can be processed by this handler.\n\n pub fn description(&self) -> &Descr {\n\n &self.data.description\n\n }\n\n}\n\n\n\n/// Constructs a handler from a function.\n\n///\n\n/// Most of the time, you do not want to use this function. Take a look at more\n\n/// specialised functions: [`crate::endpoint`], [`crate::filter`],\n\n/// [`crate::filter_map`], etc.\n", "file_path": "src/handler/core.rs", "rank": 99, "score": 6.61480660486019 } ]
Rust
src/init/init_game_data.rs
Noah2610/LD48
433d248beef1b7a4dd99116d48348bef66bdd301
use crate::resource; use crate::resources::prelude::*; use crate::settings::Settings; use crate::states::aliases::{CustomData, GameDataBuilder}; use amethyst::prelude::Config; use amethyst::window::DisplayConfig; use deathframe::amethyst; pub(super) fn build_game_data<'a, 'b>( settings: &Settings, ) -> amethyst::Result<GameDataBuilder<'a, 'b>> { use crate::input::prelude::*; use crate::systems::prelude::*; use amethyst::core::transform::TransformBundle; use amethyst::renderer::types::DefaultBackend; use amethyst::renderer::{RenderFlat2D, RenderToWindow, RenderingBundle}; use amethyst::ui::{RenderUi, UiBundle}; use amethyst::utils::fps_counter::FpsCounterBundle; use amethyst::utils::ortho_camera::CameraOrthoSystem; use deathframe::bundles::*; let transform_bundle = TransformBundle::new(); let display_config = get_display_config()?; let rendering_bundle = RenderingBundle::<DefaultBackend>::new() .with_plugin( RenderToWindow::from_config(display_config) .with_clear([0.0, 0.0, 0.0, 1.0]), ) .with_plugin(RenderUi::default()) .with_plugin(RenderFlat2D::default()); let audio_bundle = AudioBundle::<SoundKey, SongKey>::default() .with_sounds_default_volume(settings.audio.volume); let menu_input_bundle = MenuBindings::bundle()?; let ingame_input_bundle = IngameBindings::bundle()?; let physics_bundle = PhysicsBundle::<CollisionTag, SolidTag>::new().with_deps(&[]); let animation_bundle = AnimationBundle::<AnimationKey>::new(); let custom_game_data = GameDataBuilder::default() .custom(CustomData::default()) .dispatcher(DispatcherId::MainMenu)? .dispatcher(DispatcherId::Ingame)? .dispatcher(DispatcherId::Paused)? .dispatcher(DispatcherId::ZoneTransition)? .dispatcher(DispatcherId::GameOver)? .dispatcher(DispatcherId::ZoneSelect)? .with_core_bundle(FpsCounterBundle)? .with_core_bundle(transform_bundle)? .with_core_bundle(rendering_bundle)? .with_core_bundle(audio_bundle)? .with_core_bundle(menu_input_bundle)? .with_core_bundle(UiBundle::<MenuBindings>::new())? .with_core_bundle(animation_bundle)? .with_core(PrintFpsSystem::default(), "print_fps_system", &[])? .with_core(CameraOrthoSystem::default(), "camera_ortho_system", &[])? .with_core(ScaleSpritesSystem::default(), "scale_sprites_system", &[])? .with_core( InputManagerSystem::<MenuBindings>::default(), "menu_input_manager_system", &[], )? .with_bundle(DispatcherId::Ingame, ingame_input_bundle)? .with_bundle(DispatcherId::Ingame, physics_bundle)? .with( DispatcherId::Ingame, InputManagerSystem::<IngameBindings>::default(), "ingame_input_manager_system", &[], )? .with( DispatcherId::Paused, InputManagerSystem::<MenuBindings>::default(), "paused_input_manager_system", &[], )? .with( DispatcherId::Ingame, FollowSystem::default(), "follow_system", &[], )? .with( DispatcherId::Ingame, ConfineEntitiesSystem::default(), "confine_entities_system", &["move_entities_system"], )? .with( DispatcherId::Ingame, EntityLoaderSystem::default(), "entity_loader_system", &[ "move_entities_system", "follow_system", "confine_entities_system", ], )? .with( DispatcherId::Ingame, UpdateHealthSystem::default(), "update_health_system", &[], )? .with( DispatcherId::Ingame, UpdateLifecycleSystem::default(), "update_lifecycle_system", &[], )? .with( DispatcherId::Ingame, ControlPlayer::default(), "control_player_system", &[], )? .with( DispatcherId::Ingame, UpdateOnLane::default(), "update_on_lane_system", &["control_player_system", "move_entities_system"], )? .with( DispatcherId::Ingame, HandleSegmentLoading::default(), "handle_segment_loading_system", &[], )? .with( DispatcherId::Ingame, ConfineCameraToFirstAndFinalSegment::default(), "confine_camera_to_first_and_final_segment", &[], )? .with( DispatcherId::Ingame, HandleZoneSwitch::default(), "handle_zone_switch_system", &["update_collisions_system"], )? .with( DispatcherId::Ingame, HandleParentDelete::default(), "handle_parent_delete_system", &[], )? .with( DispatcherId::Ingame, HandleObstacle::default(), "handle_obstacle_system", &[], )? .with( DispatcherId::Ingame, HandleCoinCollection::default(), "handle_coin_collection_system", &[], )? .with( DispatcherId::Ingame, UpdateScoreUi::default(), "update_score_ui_system", &[], )? .with( DispatcherId::Ingame, UpdateHighscoreUi::default(), "update_highscore_ui_system", &[], )? .with( DispatcherId::Ingame, HandleTurret::default(), "handle_turret_system", &[], )? .with( DispatcherId::Ingame, HandleDeleteDelay::default(), "handle_delete_delay_system", &[], )? .with( DispatcherId::Ingame, UpdateRotate::default(), "update_rotate_system", &[], )? .with( DispatcherId::MainMenu, UpdateHighscoreUi::default(), "main_menu_update_highscore_ui_system", &[], )? .with( DispatcherId::GameOver, UpdateScoreUi::default(), "game_over_update_score_ui_system", &[], )? .with( DispatcherId::GameOver, UpdateHighscoreUi::default(), "game_over_update_highscore_ui_system", &[], )? .with( DispatcherId::ZoneSelect, UpdateHighscoreUi::default(), "zone_select_update_highscore_ui_system", &[], )? .with( DispatcherId::GameOver, UpdateRotate::default(), "game_over_update_rotate_system", &[], )? .with( DispatcherId::ZoneSelect, HandleZoneSelect::default(), "handle_zone_select_system", &[], )? .with( DispatcherId::ZoneSelect, UpdateSelectedZoneUi::default(), "update_selected_zone_ui_system", &[], )?; Ok(custom_game_data) } fn get_display_config() -> amethyst::Result<DisplayConfig> { #[cfg(not(feature = "dev"))] let display_config = DisplayConfig::load(resource("config/display.ron"))?; #[cfg(feature = "dev")] let display_config = { let mut config = DisplayConfig::load(resource("config/display.ron"))?; config.min_dimensions = config.dimensions.clone(); config.max_dimensions = config.dimensions.clone(); config }; Ok(display_config) }
use crate::resource; use crate::resources::prelude::*; use crate::settings::Settings; use crate::states::aliases::{CustomData, GameDataBuilder}; use amethyst::prelude::Config; use amethyst::window::DisplayConfig; use deathframe::amethyst; pub(super) fn build_game_data<'a, 'b>( settings: &Settings, ) -> amethyst::Result<GameDataBuilder<'a, 'b>> { use crate::input::prelude::*; use crate::systems::prelude::*; use amethyst::core::transform::TransformBundle; use amethyst::renderer::types::DefaultBackend; use amethyst::renderer::{RenderFlat2D, RenderToWindow, RenderingBundle}; use amethyst::ui::{RenderUi, UiBundle}; use amethyst::utils::fps_counter::FpsCounterBundle; use amethyst::utils::ortho_camera::CameraOrthoSystem; use deathframe::bundles::*; let transform_bundle = TransformBundle::new(); let display_config = get_display_config()?; let rendering_bundle = RenderingBundle::<DefaultBackend>::new() .with_plugin( RenderToWindow::from_config(display_config) .with_clear([0.0, 0.0, 0.0, 1.0]), ) .with_plugin(RenderUi::default()) .with_plugin(RenderFlat2D::default()); let audio_bundle = AudioBundle::<SoundKey, SongKey>::default() .with_sounds_default_volume(settings.audio.volume); let menu_input_bundle = MenuBindings::bundle()?; let ingame_input_bundle = IngameBindings::bundle()?; let physics_bundle = PhysicsBundle::<CollisionTag, SolidTag>::new().with_deps(&[]); let animation_bundle = AnimationBundle::<AnimationKey>::new(); let custom_game_data = GameDataBuilder::default() .custom(CustomData::default()) .dispatcher(DispatcherId::MainMenu)? .dispatcher(DispatcherId::Ingame)? .dispatcher(DispatcherId::Paused)? .dispatcher(DispatcherId::ZoneTransition)? .dispatcher(DispatcherId::GameOver)? .dispatcher(DispatcherId::ZoneSelect)? .with_core_bundle(FpsCounterBundle)? .with_core_bundle(transform_bundle)? .with_core_bundle(rendering_bundle)? .with_core_bundle(audio_bundle)? .with_core_bundle(menu_input_bundle)? .with_core_bundle(UiBundle::<MenuBindings>::new())? .with_core_bundle(animation_bundle)? .with_core(PrintFpsSystem::default(), "print_fps_system", &[])? .with_core(CameraOrthoSystem::default(), "camera_ortho_system", &[])? .with_core(ScaleSpritesSystem::default(), "scale_sprites_system", &[])? .with_core( InputManagerSystem::<MenuBindings>::default(), "menu_input_manager_system", &[], )? .with_bundle(DispatcherId::Ingame, ingame_input_bundle)? .with_bundle(DispatcherId::Ingame, physics_bundle)? .with( DispatcherId::Ingame, InputManagerSystem::<IngameBindings>::default(), "ingame_input_manager_system", &[], )? .with( DispatcherId::Paused, InputManagerSystem::<MenuBindings>::default(), "paused_input_manager_system", &[], )? .with( DispatcherId::Ingame, FollowSystem::default(), "follow_system", &[], )? .with( DispatcherId::Ingame, ConfineEntitiesSystem::default(), "confine_entities_system", &["move_entities_system"], )? .with( DispatcherId::Ingame, EntityLoaderSystem::default(), "entity_loader_system", &[ "move_entities_system", "follow_system", "confine_entities_system", ], )? .with( DispatcherId::Ingame, UpdateHealthSystem::default(), "update_health_system", &[], )? .with( DispatcherId::Ingame, UpdateLifecycleSystem::default(), "update_lifecycle_system", &[], )? .with( DispatcherId::Ingame, ControlPlayer::default(), "control_player_system", &[], )? .with( DispatcherId::Ingame, UpdateOnLane::default(), "update_on_lane_system", &["control_player_system", "move_entities_system"], )? .with( DispatcherId::Ingame, HandleSegmentLoading::default(), "handle_segment_loading_system", &[], )? .with( DispatcherId::Ingame, ConfineCameraToFirstAndFinalSegment::default(), "confine_camera_to_first_and_final_segment", &[], )? .with( DispatcherId::Ingame, HandleZoneSwitch::default(), "handle_zone_switch_system", &["update_collisions_system"], )? .with( DispatcherId::Ingame, HandleParentDelete::default(), "handle_parent_delete_system", &[], )? .with( DispatcherId::Ingame, HandleObstacle::default(), "handle_obstacle_system", &[], )? .with( DispatcherId::Ingame, HandleCoinCollection::default(), "handle_coin_collection_system", &[], )? .with( DispatcherId::Ingame, UpdateScoreUi::default(), "update_score_ui_system", &[], )? .with( DispatcherId::Ingame, UpdateHighscoreUi::default(), "update_highscore_ui_system", &[], )? .with( DispatcherId::Ingame, HandleTurret::default(), "handle_turret_system", &[], )? .with( DispatcherId::Ingame, HandleDeleteDelay::default(), "handle_delete_delay_system", &[], )? .with( DispatcherId::Ingame, UpdateRotate::default(), "update_rotate_system", &[], )? .with( DispatcherId::MainMenu, UpdateHighscoreUi::default(), "main_menu_update_highscore_ui_system", &[], )? .with( DispatcherId::GameOver, UpdateScoreUi::default(), "game_over_update_score_ui_system", &[], )? .with( DispatcherId::GameOver, UpdateHighscoreUi::default(), "game_over_update_highscore_ui_system", &[], )? .
fn get_display_config() -> amethyst::Result<DisplayConfig> { #[cfg(not(feature = "dev"))] let display_config = DisplayConfig::load(resource("config/display.ron"))?; #[cfg(feature = "dev")] let display_config = { let mut config = DisplayConfig::load(resource("config/display.ron"))?; config.min_dimensions = config.dimensions.clone(); config.max_dimensions = config.dimensions.clone(); config }; Ok(display_config) }
with( DispatcherId::ZoneSelect, UpdateHighscoreUi::default(), "zone_select_update_highscore_ui_system", &[], )? .with( DispatcherId::GameOver, UpdateRotate::default(), "game_over_update_rotate_system", &[], )? .with( DispatcherId::ZoneSelect, HandleZoneSelect::default(), "handle_zone_select_system", &[], )? .with( DispatcherId::ZoneSelect, UpdateSelectedZoneUi::default(), "update_selected_zone_ui_system", &[], )?; Ok(custom_game_data) }
function_block-function_prefix_line
[ { "content": "/// Merge `Vec` of settings `T` together.\n\n/// Returns `None` if given `Vec` is empty.\n\nfn merge_settings<T>(all_settings: Vec<T>) -> Option<T>\n\nwhere\n\n T: Merge,\n\n{\n\n let mut merged_settings: Option<T> = None;\n\n for settings in all_settings {\n\n if let Some(merged) = merged_settings.as_mut() {\n\n merged.merge(settings);\n\n } else {\n\n merged_settings = Some(settings);\n\n }\n\n }\n\n merged_settings\n\n}\n", "file_path": "src/settings/mod.rs", "rank": 0, "score": 79516.49247778016 }, { "content": "pub fn add_components_to_entity(\n\n entity_builder: EntityBuilder,\n\n components: Vec<EntityComponent>,\n\n mut size_opt: Option<Size>,\n\n) -> EntityBuilder {\n\n use self::EntityComponent as Comp;\n\n\n\n components\n\n .into_iter()\n\n .fold(entity_builder, |builder, component| match component {\n\n Comp::Velocity(velocity) => builder.with(velocity),\n\n Comp::Size(size) => {\n\n size_opt = Some(size.clone());\n\n builder.with(size)\n\n }\n\n Comp::Gravity(gravity) => builder.with(gravity),\n\n Comp::Animation(mut animation) => {\n\n animation.play_cycle();\n\n builder.with(animation)\n\n }\n", "file_path": "src/settings/entity_components.rs", "rank": 1, "score": 75051.07953049059 }, { "content": "fn load_settings<S, P>(path: P) -> amethyst::Result<S>\n\nwhere\n\n for<'de> S: serde::Deserialize<'de>,\n\n P: fmt::Display,\n\n{\n\n let file = File::open(resource(path.to_string()))?;\n\n Ok(ron::de::from_reader(file).map_err(|e| {\n\n amethyst::Error::from_string(format!(\n\n \"Failed parsing RON settings file: {}\\n{:#?}\",\n\n path, e\n\n ))\n\n })?)\n\n}\n\n\n\n// Functions below copied from deathfloor project.\n\n\n", "file_path": "src/settings/mod.rs", "rank": 2, "score": 73401.48343388524 }, { "content": "fn load_settings_dir<T, S>(dirname: S) -> amethyst::Result<T>\n\nwhere\n\n for<'de> T: serde::Deserialize<'de> + Merge + Default,\n\n S: std::fmt::Display,\n\n{\n\n let path = resource(dirname.to_string());\n\n let errmsg = format!(\"No settings files found in {:?}\", &path);\n\n let all_settings = load_configs_recursively_from(path)?;\n\n let merged_settings = merge_settings(all_settings).unwrap_or_else(|| {\n\n eprintln!(\n\n \"[WARNING]\\n {}\\n Using default (probably empty settings)\",\n\n errmsg\n\n );\n\n T::default()\n\n });\n\n Ok(merged_settings)\n\n}\n\n\n", "file_path": "src/settings/mod.rs", "rank": 3, "score": 72189.41444008576 }, { "content": "fn load_configs_recursively_from<T>(path: PathBuf) -> amethyst::Result<Vec<T>>\n\nwhere\n\n for<'de> T: serde::Deserialize<'de> + Merge,\n\n{\n\n let mut settings = Vec::new();\n\n\n\n for entry in path.read_dir()? {\n\n let entry_path = entry?.path();\n\n if entry_path.is_file() {\n\n if let Some(\"ron\") = entry_path.extension().and_then(|e| e.to_str())\n\n {\n\n let file = File::open(&entry_path)?;\n\n settings.push(ron::de::from_reader(file).map_err(|e| {\n\n amethyst::Error::from_string(format!(\n\n \"Failed parsing RON settings file: {:?}\\n{:#?}\",\n\n entry_path, e\n\n ))\n\n })?);\n\n }\n\n } else if entry_path.is_dir() {\n\n settings.append(&mut load_configs_recursively_from(entry_path)?);\n\n }\n\n }\n\n\n\n Ok(settings)\n\n}\n\n\n", "file_path": "src/settings/mod.rs", "rank": 4, "score": 61939.66377277224 }, { "content": "fn main() {\n\n if let Err(e) = init::run() {\n\n eprintln!(\"An error occured: {}\", e);\n\n std::process::exit(1);\n\n }\n\n}\n", "file_path": "src/main.rs", "rank": 6, "score": 50236.19162970742 }, { "content": "fn start_logger() {\n\n use amethyst::{LogLevelFilter, LoggerConfig};\n\n amethyst::start_logger(LoggerConfig {\n\n level_filter: LogLevelFilter::Error,\n\n ..Default::default()\n\n });\n\n}\n\n\n", "file_path": "src/init/mod.rs", "rank": 7, "score": 48223.250913462456 }, { "content": "pub fn build_tiles(\n\n world: &mut World,\n\n tiles: Vec<DataTile>,\n\n tile_size: Size,\n\n segment: Option<(SegmentId, Entity)>,\n\n offset_y: f32,\n\n) -> amethyst::Result<()> {\n\n for tile in tiles {\n\n let transform = {\n\n let mut transform = Transform::default();\n\n transform.set_translation_x(tile.pos.x);\n\n transform.set_translation_y(-offset_y + tile.pos.y);\n\n if let Some(z) = tile.props.get(\"z\").and_then(|val| val.as_f64()) {\n\n transform.set_translation_z(z as f32);\n\n }\n\n transform\n\n };\n\n\n\n let sprite_render = {\n\n let sprite_sheet = world\n", "file_path": "src/level_loader/tiles.rs", "rank": 8, "score": 45071.173332134225 }, { "content": "pub fn build_level(\n\n world: &mut World,\n\n level_data: DataLevel,\n\n) -> amethyst::Result<()> {\n\n let tile_size =\n\n Size::new(level_data.level.tile_size.w, level_data.level.tile_size.h);\n\n\n\n tiles::build_tiles(world, level_data.tiles, tile_size, None, 0.0)?;\n\n objects::build_objects(world, level_data.objects, None, 0.0)?;\n\n\n\n world.maintain();\n\n\n\n Ok(())\n\n}\n", "file_path": "src/level_loader/mod.rs", "rank": 9, "score": 45071.173332134225 }, { "content": "pub fn build_objects(\n\n world: &mut World,\n\n objects: Vec<DataObject>,\n\n segment: Option<(SegmentId, Entity)>,\n\n offset_y: f32,\n\n) -> amethyst::Result<()> {\n\n for object in objects {\n\n let transform = {\n\n let mut transform = Transform::default();\n\n transform.set_translation_x(object.pos.x);\n\n transform.set_translation_y(-offset_y + object.pos.y);\n\n if let Some(z) = object.props.get(\"z\").and_then(|val| val.as_f64())\n\n {\n\n transform.set_translation_z(z as f32);\n\n }\n\n transform\n\n };\n\n let size = Size::new(object.size.w, object.size.h);\n\n\n\n match &object.object_type {\n", "file_path": "src/level_loader/objects.rs", "rank": 10, "score": 45071.173332134225 }, { "content": "pub fn build_camera(\n\n world: &mut World,\n\n player: Option<Entity>,\n\n level_size: Size,\n\n camera_size: Option<Size>,\n\n) -> amethyst::Result<()> {\n\n use amethyst::renderer::Camera as AmethystCamera;\n\n use amethyst::utils::ortho_camera::{\n\n CameraNormalizeMode,\n\n CameraOrtho,\n\n CameraOrthoWorldCoordinates,\n\n };\n\n\n\n const LOADING_DISTANCE_PADDING: (f32, f32) = (0.0, 16.0);\n\n\n\n let settings = (*world.read_resource::<CameraSettings>()).clone();\n\n\n\n let size = camera_size.unwrap_or(settings.size);\n\n\n\n let camera = AmethystCamera::standard_2d(size.w, size.h);\n", "file_path": "src/level_loader/objects.rs", "rank": 11, "score": 45071.173332134225 }, { "content": "pub fn build_segment(\n\n world: &mut World,\n\n level_data: DataLevel,\n\n segment_id: SegmentId,\n\n) -> amethyst::Result<()> {\n\n let is_first_is_final_segment = {\n\n let zones_manager = world.read_resource::<ZonesManager>();\n\n let zones_settings = world.read_resource::<ZonesSettings>();\n\n if let Some(current_zone) = zones_manager.current_zone() {\n\n zones_settings\n\n .zones\n\n .get(current_zone)\n\n .map(|zone_settings| {\n\n (\n\n zone_settings.first_segment.contains(&segment_id),\n\n zone_settings.final_segment.contains(&segment_id),\n\n )\n\n })\n\n .unwrap_or((false, false))\n\n } else {\n", "file_path": "src/level_loader/mod.rs", "rank": 12, "score": 45071.173332134225 }, { "content": "pub fn build_player(\n\n world: &mut World,\n\n mut transform: Transform,\n\n size: Size,\n\n player_speed: f32,\n\n) -> Entity {\n\n let sprite_render = {\n\n let sprite_sheet = world\n\n .write_resource::<SpriteSheetHandles<PathBuf>>()\n\n .get_or_load(resource(\"spritesheets/player.png\"), world);\n\n SpriteRender {\n\n sprite_sheet,\n\n sprite_number: 0,\n\n }\n\n };\n\n\n\n let settings = (*world.read_resource::<PlayerSettings>()).clone();\n\n\n\n transform.set_translation_z(settings.z);\n\n\n", "file_path": "src/level_loader/objects.rs", "rank": 13, "score": 45071.173332134225 }, { "content": "pub fn build_segment_collision(\n\n world: &mut World,\n\n size: Size,\n\n segment_id: SegmentId,\n\n (is_first_segment, is_final_segment): (bool, bool),\n\n offset_y: f32,\n\n) -> Entity {\n\n let mut transform = Transform::default();\n\n transform.set_translation_xyz(size.w * 0.5, -offset_y + size.h * 0.5, 0.0);\n\n world\n\n .create_entity()\n\n .with(Segment {\n\n id: segment_id,\n\n is_first_segment,\n\n is_final_segment,\n\n })\n\n .with(transform)\n\n .with(size)\n\n .build()\n\n}\n", "file_path": "src/level_loader/objects.rs", "rank": 14, "score": 44243.0495882738 }, { "content": "pub fn build_object<'a>(\n\n world: &'a mut World,\n\n object_type: ObjectType,\n\n transform: Transform,\n\n size_opt: Option<Size>,\n\n) -> Option<EntityBuilder<'a>> {\n\n match &object_type {\n\n ObjectType::Player => {\n\n eprintln!(\n\n \"[WARNING]\\n A `Player` object is placed in the \\\n\n level!\\n The player is loaded automatically by the \\\n\n game, don't place them in the levels.\\n The placed \\\n\n player object will not be loaded.\"\n\n );\n\n // let player_entity = build_player(world, transform, size);\n\n // let _ = build_camera(world, player_entity);\n\n None\n\n }\n\n\n\n object_type => {\n", "file_path": "src/level_loader/objects.rs", "rank": 15, "score": 43944.64625182798 }, { "content": "type ObjectsSettingsMap = HashMap<ObjectType, ObjectSettings>;\n\n\n\n#[derive(Deserialize, Clone, Default)]\n\n#[serde(deny_unknown_fields, from = \"ObjectsSettingsMap\")]\n\npub struct ObjectsSettings {\n\n pub objects: ObjectsSettingsMap,\n\n}\n\n\n\n#[derive(Deserialize, Clone)]\n\n#[serde(deny_unknown_fields)]\n\npub struct ObjectSettings {\n\n pub components: EntityComponents,\n\n #[serde(default)]\n\n pub spritesheet: Option<String>,\n\n}\n\n\n\nimpl From<ObjectsSettingsMap> for ObjectsSettings {\n\n fn from(objects: ObjectsSettingsMap) -> Self {\n\n Self { objects }\n\n }\n\n}\n\n\n\nimpl Merge for ObjectsSettings {\n\n fn merge(&mut self, other: Self) {\n\n self.objects.extend(&mut other.objects.into_iter())\n\n }\n\n}\n", "file_path": "src/settings/objects_settings.rs", "rank": 16, "score": 43458.602569909905 }, { "content": "fn setup(world: &mut World) {\n\n use crate::components::prelude::{\n\n BelongsToSegment,\n\n Coin,\n\n Cutscene,\n\n Object,\n\n Obstacle,\n\n Portal,\n\n Segment,\n\n Tile,\n\n Turret,\n\n };\n\n\n\n world.register::<Tile>();\n\n world.register::<Object>();\n\n world.register::<BelongsToSegment>();\n\n world.register::<Segment>();\n\n world.register::<Portal>();\n\n world.register::<Obstacle>();\n\n world.register::<Coin>();\n", "file_path": "src/states/startup.rs", "rank": 17, "score": 42993.3249080268 }, { "content": "pub fn run() -> amethyst::Result<()> {\n\n start_logger();\n\n\n\n let settings = Settings::load()?;\n\n let game_data = init_game_data::build_game_data(&settings)?;\n\n\n\n let Settings {\n\n camera: camera_settings,\n\n player: player_settings,\n\n objects: objects_settings,\n\n lanes: lanes_settings,\n\n zones: zones_settings,\n\n audio: audio_settings,\n\n savefile: savefile_settings,\n\n } = settings;\n\n\n\n let mut game: amethyst::CoreApplication<GameData> =\n\n ApplicationBuilder::new(application_root_dir()?, Startup::default())?\n\n .with_frame_limit_config(frame_rate_limit_config()?)\n\n .with_resource(camera_settings)\n", "file_path": "src/init/mod.rs", "rank": 18, "score": 42993.3249080268 }, { "content": "fn load_savefile(world: &World) -> Savefile {\n\n let savefile =\n\n match world.read_resource::<SavefileSettings>().savefile_path() {\n\n Ok(savefile_path) => match Savefile::load(savefile_path) {\n\n Ok(savefile) => Some(savefile),\n\n Err(e) => {\n\n eprintln!(\"[WARNING]\\n {}\", e);\n\n None\n\n }\n\n },\n\n Err(e) => {\n\n eprintln!(\"[WARNING]\\n {}\", e);\n\n None\n\n }\n\n };\n\n savefile.unwrap_or_default()\n\n}\n", "file_path": "src/states/startup.rs", "rank": 19, "score": 42165.201164166385 }, { "content": "// resources/settings/zones\n\n\n\nuse crate::resources::prelude::SongKey;\n\nuse deathframe::core::components::prelude::Merge;\n\nuse replace_with::replace_with_or_abort;\n\nuse std::collections::HashMap;\n\n\n\npub type ZoneId = String;\n\npub type SegmentId = String;\n\n\n\n#[derive(Deserialize, Default, Debug)]\n\n#[serde(deny_unknown_fields)]\n\npub struct ZonesSettings {\n\n #[serde(default)]\n\n pub config: ZonesConfig,\n\n #[serde(default)]\n\n pub zones: HashMap<ZoneId, ZoneSettings>,\n\n}\n\n\n\n#[derive(Deserialize, Default, Debug)]\n", "file_path": "src/settings/zones_settings.rs", "rank": 20, "score": 42098.00842541583 }, { "content": "// resources/settings/objects.ron\n\n\n\nuse super::entity_components::EntityComponents;\n\nuse crate::level_loader::ObjectType;\n\nuse deathframe::components::prelude::Merge;\n\nuse std::collections::HashMap;\n\n\n", "file_path": "src/settings/objects_settings.rs", "rank": 21, "score": 42097.90811652406 }, { "content": "// resources/settings/savefile.ron\n\n\n\nuse deathframe::amethyst;\n\nuse std::fs::create_dir_all;\n\nuse std::path::PathBuf;\n\n\n\n#[derive(Deserialize, Clone)]\n\n#[serde(deny_unknown_fields)]\n\npub struct SavefileSettings {\n\n pub savefile_name: String,\n\n}\n\n\n\nimpl SavefileSettings {\n\n pub fn savefile_path(&self) -> amethyst::Result<PathBuf> {\n\n const APP_NAME: &str = env!(\"CARGO_PKG_NAME\");\n\n\n\n if let Some(mut path) = dirs::data_local_dir() {\n\n path.push(APP_NAME);\n\n if !path.exists() {\n\n if let Err(e) = create_dir_all(&path) {\n", "file_path": "src/settings/savefile_settings.rs", "rank": 22, "score": 42097.706859172 }, { "content": "use crate::resources::prelude::{SongKey, SoundKey};\n\nuse std::collections::HashMap;\n\n\n\n#[derive(Deserialize, Clone)]\n\n#[serde(deny_unknown_fields)]\n\npub struct AudioSettings {\n\n pub volume: f32,\n\n pub bgm: HashMap<SongKey, AudioBgmSettings>,\n\n pub sfx: HashMap<SoundKey, AudioSfxSettings>,\n\n}\n\n\n\n#[derive(Deserialize, Clone)]\n\n#[serde(deny_unknown_fields)]\n\npub struct AudioBgmSettings {\n\n pub file: String,\n\n}\n\n\n\n#[derive(Deserialize, Clone)]\n\n#[serde(deny_unknown_fields)]\n\npub struct AudioSfxSettings {\n\n pub file: String,\n\n}\n", "file_path": "src/settings/audio_settings.rs", "rank": 23, "score": 42097.55007595937 }, { "content": "// resources/settings/player.ron\n\n\n\nuse super::entity_components::EntityComponents;\n\n\n\n#[derive(Deserialize, Clone)]\n\n#[serde(deny_unknown_fields)]\n\npub struct PlayerSettings {\n\n pub z: f32,\n\n pub components: EntityComponents,\n\n}\n", "file_path": "src/settings/player_settings.rs", "rank": 24, "score": 42097.34038637072 }, { "content": "// resources/settings/camera.ron\n\n\n\nuse crate::components::prelude::Size;\n\n\n\n#[derive(Deserialize, Clone)]\n\n#[serde(deny_unknown_fields)]\n\npub struct CameraSettings {\n\n pub z: f32,\n\n pub size: Size,\n\n pub follow_offset: (f32, f32),\n\n}\n", "file_path": "src/settings/camera_settings.rs", "rank": 25, "score": 42097.203257852736 }, { "content": " fn merge(&mut self, other: Self) {\n\n let ZonesSettings {\n\n config: other_config,\n\n zones: mut other_zones,\n\n } = other;\n\n replace_with_or_abort(self, |self_| {\n\n let mut zones = self_\n\n .zones\n\n .into_iter()\n\n .map(|(zone_id, zone_settings)| {\n\n let merged_zone_settings = if let Some(other_zone) =\n\n other_zones.remove(&zone_id)\n\n {\n\n zone_settings.merged(other_zone)\n\n } else {\n\n zone_settings\n\n };\n\n (zone_id, merged_zone_settings)\n\n })\n\n .collect::<HashMap<_, _>>();\n", "file_path": "src/settings/zones_settings.rs", "rank": 26, "score": 42094.99361274259 }, { "content": "// resources/settings/lanes.ron\n\n\n\n#[derive(Deserialize, Clone)]\n\npub struct LanesSettings {\n\n pub count: usize,\n\n pub spacing: f32,\n\n}\n", "file_path": "src/settings/lanes_settings.rs", "rank": 27, "score": 42094.60524213148 }, { "content": " arrays configured in multiple zone configs.\\n This \\\n\n will merge multiple `config.zone_order` arrays \\\n\n together.\\n This is probably not intended.\"\n\n );\n\n self.zone_order.append(&mut other_zone_order);\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl Merge for ZoneSettings {\n\n fn merge(&mut self, other: Self) {\n\n let ZoneSettings {\n\n song: _,\n\n player_speed: _,\n\n is_skippable: _,\n\n total_segments: _,\n\n first_segment: _,\n\n final_segment: _,\n\n segments: _,\n", "file_path": "src/settings/zones_settings.rs", "rank": 28, "score": 42094.097196544804 }, { "content": "#[serde(deny_unknown_fields)]\n\npub struct ZonesConfig {\n\n pub zone_order: Vec<ZoneId>,\n\n}\n\n\n\n#[derive(Deserialize, Debug)]\n\n#[serde(deny_unknown_fields)]\n\npub struct ZoneSettings {\n\n #[serde(default)]\n\n pub song: Option<SongKey>,\n\n pub player_speed: f32,\n\n #[serde(default)]\n\n pub is_skippable: bool,\n\n pub total_segments: Option<usize>,\n\n pub first_segment: Vec<SegmentId>,\n\n pub final_segment: Vec<SegmentId>,\n\n pub segments: HashMap<SegmentId, Vec<SegmentId>>,\n\n}\n\n\n\nimpl Merge for ZonesSettings {\n", "file_path": "src/settings/zones_settings.rs", "rank": 29, "score": 42093.66240690515 }, { "content": " zones.extend(other_zones.into_iter());\n\n ZonesSettings {\n\n config: self_.config.merged(other_config),\n\n zones,\n\n }\n\n });\n\n }\n\n}\n\n\n\nimpl Merge for ZonesConfig {\n\n fn merge(&mut self, other: Self) {\n\n let ZonesConfig {\n\n zone_order: mut other_zone_order,\n\n } = other;\n\n if self.zone_order.is_empty() {\n\n self.zone_order = other_zone_order;\n\n } else {\n\n if !other_zone_order.is_empty() {\n\n eprintln!(\n\n \"[WARNING]\\n Careful, you have `config.zone_order` \\\n", "file_path": "src/settings/zones_settings.rs", "rank": 30, "score": 42093.268113592494 }, { "content": " return Err(amethyst::Error::from_string(format!(\n\n \"Couldn't create data directory for \\\n\n savefile:\\n{:?}\\n{:?}\",\n\n &path, e\n\n )));\n\n }\n\n }\n\n path.push(&self.savefile_name);\n\n Ok(path)\n\n } else {\n\n Err(amethyst::Error::from_string(\n\n \"Couldn't find data directory for savefile\",\n\n ))\n\n }\n\n }\n\n}\n", "file_path": "src/settings/savefile_settings.rs", "rank": 31, "score": 42090.608237189204 }, { "content": " } = other;\n\n eprintln!(\n\n \"[WARNING]\\n Careful, you have the same `zones.<ZONE-ID>` \\\n\n configured in multiple zone configs.\\n This will NOT merge \\\n\n them together.\\n You should probably find and fix the \\\n\n duplicate configurations.\"\n\n );\n\n }\n\n}\n", "file_path": "src/settings/zones_settings.rs", "rank": 32, "score": 42090.608237189204 }, { "content": "pub fn enter_fullscreen(window: &Window) {\n\n let monitor_id = window.get_current_monitor();\n\n window.set_fullscreen(Some(monitor_id));\n\n window.hide_cursor(true);\n\n}\n\n\n", "file_path": "src/states/state_helpers.rs", "rank": 33, "score": 41379.22887798081 }, { "content": "pub fn toggle_fullscreen(window: &Window) {\n\n let is_fullscreen = window.get_fullscreen().is_some();\n\n if is_fullscreen {\n\n leave_fullscreen(window);\n\n } else {\n\n enter_fullscreen(window);\n\n }\n\n}\n", "file_path": "src/states/state_helpers.rs", "rank": 34, "score": 41379.22887798081 }, { "content": "pub fn leave_fullscreen(window: &Window) {\n\n window.set_fullscreen(None);\n\n window.hide_cursor(false);\n\n}\n\n\n", "file_path": "src/states/state_helpers.rs", "rank": 35, "score": 41379.22887798081 }, { "content": "fn frame_rate_limit_config() -> amethyst::Result<FrameRateLimitConfig> {\n\n use std::fs::File;\n\n Ok(ron::de::from_reader(File::open(resource(\n\n \"config/frame_limiter.ron\",\n\n ))?)?)\n\n}\n", "file_path": "src/init/mod.rs", "rank": 36, "score": 38598.43606783517 }, { "content": "pub fn load_level(filepath: PathBuf) -> amethyst::Result<DataLevel> {\n\n let level_file = File::open(filepath)?;\n\n let level_data = serde_json::de::from_reader::<_, DataLevel>(level_file)?;\n\n Ok(level_data)\n\n}\n\n\n", "file_path": "src/level_loader/mod.rs", "rank": 37, "score": 35847.56434609405 }, { "content": "pub mod prelude {\n\n pub use super::audio_settings::AudioSettings;\n\n pub use super::camera_settings::CameraSettings;\n\n pub use super::lanes_settings::LanesSettings;\n\n pub use super::objects_settings::{ObjectSettings, ObjectsSettings};\n\n pub use super::player_settings::PlayerSettings;\n\n pub use super::savefile_settings::SavefileSettings;\n\n pub use super::zones_settings::{ZoneId, ZoneSettings, ZonesSettings};\n\n pub use super::Settings;\n\n}\n\n\n\npub mod audio_settings;\n\npub mod camera_settings;\n\npub mod entity_components;\n\npub mod hitbox_config;\n\npub mod lanes_settings;\n\npub mod objects_settings;\n\npub mod player_settings;\n\npub mod savefile_settings;\n\npub mod zones_settings;\n", "file_path": "src/settings/mod.rs", "rank": 38, "score": 35443.692116441205 }, { "content": "\n\nuse crate::resource;\n\nuse deathframe::amethyst;\n\nuse deathframe::components::prelude::Merge;\n\nuse prelude::*;\n\nuse std::fmt;\n\nuse std::fs::File;\n\nuse std::path::PathBuf;\n\n\n\npub struct Settings {\n\n pub camera: CameraSettings,\n\n pub player: PlayerSettings,\n\n pub objects: ObjectsSettings,\n\n pub lanes: LanesSettings,\n\n pub zones: ZonesSettings,\n\n pub audio: AudioSettings,\n\n pub savefile: SavefileSettings,\n\n}\n\n\n\nimpl Settings {\n", "file_path": "src/settings/mod.rs", "rank": 39, "score": 35443.656144378365 }, { "content": " pub fn load() -> deathframe::amethyst::Result<Self> {\n\n Ok(Self {\n\n lanes: load_settings(\"settings/lanes.ron\")?,\n\n camera: load_settings(\"settings/camera.ron\")?,\n\n player: load_settings(\"settings/player.ron\")?,\n\n objects: load_settings_dir(\"settings/objects\")?,\n\n zones: load_settings_dir(\"settings/zones\")?,\n\n audio: load_settings(\"settings/audio.ron\")?,\n\n savefile: load_settings(\"settings/savefile.ron\")?,\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/settings/mod.rs", "rank": 40, "score": 35439.59311810336 }, { "content": "use crate::components::prelude::{Hitbox, Size};\n\nuse amethyst::ecs::{Builder, EntityBuilder};\n\nuse deathframe::amethyst;\n\nuse deathframe::core::geo::prelude::Rect;\n\n\n\n#[derive(Deserialize, Clone)]\n\npub enum HitboxConfig {\n\n Size,\n\n Custom(Hitbox),\n\n SizeOffset(Rect),\n\n}\n\n\n\nimpl HitboxConfig {\n\n pub fn add_hitbox_to_entity<'a>(\n\n &self,\n\n entity_builder: EntityBuilder<'a>,\n\n size_opt: Option<&Size>,\n\n ) -> EntityBuilder<'a> {\n\n match self {\n\n HitboxConfig::Size => {\n", "file_path": "src/settings/hitbox_config.rs", "rank": 41, "score": 34405.46575881045 }, { "content": "use super::hitbox_config::HitboxConfig;\n\nuse crate::components::prelude::*;\n\nuse crate::resources::prelude::{AnimationKey, CollisionTag, SolidTag};\n\nuse amethyst::ecs::{Builder, EntityBuilder};\n\nuse deathframe::amethyst;\n\n\n\npub type EntityComponents = Vec<EntityComponent>;\n\n\n\n#[derive(Deserialize, Clone)]\n\npub enum EntityComponent {\n\n Velocity(Velocity),\n\n Size(Size),\n\n Gravity(Gravity),\n\n Animation(Animation),\n\n Animations(AnimationsContainer<AnimationKey>),\n\n BaseFriction(BaseFriction),\n\n Hitbox(HitboxConfig),\n\n Collider(Collider<CollisionTag>),\n\n Collidable(Collidable<CollisionTag>),\n\n Solid(Solid<SolidTag>),\n", "file_path": "src/settings/entity_components.rs", "rank": 42, "score": 34405.46193016587 }, { "content": " if let Some(size) = size_opt {\n\n entity_builder.with(Hitbox::from(size))\n\n } else {\n\n panic!(\"HitboxConfig::Size entity doesn't have a Size\");\n\n }\n\n }\n\n HitboxConfig::Custom(hitbox) => entity_builder.with(hitbox.clone()),\n\n HitboxConfig::SizeOffset(padding) => {\n\n if let Some(size) = size_opt {\n\n let mut rect = Rect::from(size);\n\n rect.top += padding.top;\n\n rect.bottom += padding.bottom;\n\n rect.left += padding.left;\n\n rect.right += padding.right;\n\n entity_builder.with(Hitbox::from(rect))\n\n } else {\n\n panic!(\n\n \"HitboxConfig::SizePadding entity doesn't have a Size\"\n\n );\n\n }\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/settings/hitbox_config.rs", "rank": 43, "score": 34401.56069252267 }, { "content": " Comp::Animations(mut animations) => {\n\n let _ = animations.play(AnimationKey::Idle);\n\n builder.with(animations)\n\n }\n\n Comp::BaseFriction(base_friction) => builder.with(base_friction),\n\n Comp::Hitbox(hitbox) => {\n\n hitbox.add_hitbox_to_entity(builder, size_opt.as_ref())\n\n }\n\n Comp::Collider(collider) => builder.with(collider),\n\n Comp::Collidable(collidable) => builder.with(collidable),\n\n Comp::Solid(solid) => builder.with(solid),\n\n Comp::SolidPusher(solid_pusher) => builder.with(solid_pusher),\n\n Comp::SolidPushable(solid_pushable) => builder.with(solid_pushable),\n\n Comp::ScaleOnce(scale_once) => builder.with(scale_once),\n\n Comp::OnLane(on_lane) => builder.with(on_lane),\n\n Comp::Portal(portal) => builder.with(portal),\n\n Comp::Obstacle(obstacle) => builder.with(obstacle),\n\n Comp::Coin(coin) => builder.with(coin),\n\n Comp::Turret(turret) => builder.with(turret),\n\n Comp::Loadable(loadable) => {\n\n builder.with(loadable).with(Unloaded::default())\n\n }\n\n Comp::DeleteDelay(delete_delay) => builder.with(delete_delay),\n\n Comp::Rotate(rotate) => builder.with(rotate),\n\n Comp::Cutscene(cutscene) => builder.with(cutscene),\n\n })\n\n}\n", "file_path": "src/settings/entity_components.rs", "rank": 44, "score": 34401.56069252267 }, { "content": " SolidPusher(SolidPusher),\n\n SolidPushable(SolidPushable),\n\n ScaleOnce(ScaleOnce),\n\n OnLane(OnLane),\n\n Portal(Portal),\n\n Obstacle(Obstacle),\n\n Coin(Coin),\n\n Turret(Turret),\n\n Loadable(Loadable),\n\n DeleteDelay(DeleteDelay),\n\n Rotate(Rotate),\n\n Cutscene(Cutscene),\n\n}\n\n\n", "file_path": "src/settings/entity_components.rs", "rank": 45, "score": 34401.56069252267 }, { "content": "use super::data::*;\n\nuse super::ObjectType;\n\nuse crate::components::prelude::*;\n\nuse crate::resource;\n\nuse crate::settings::entity_components::add_components_to_entity;\n\nuse crate::settings::prelude::*;\n\nuse crate::settings::zones_settings::SegmentId;\n\nuse amethyst::ecs::{Builder, Entity, EntityBuilder, World, WorldExt};\n\nuse deathframe::amethyst;\n\nuse deathframe::core::geo::prelude::Axis;\n\nuse deathframe::resources::SpriteSheetHandles;\n\nuse std::path::PathBuf;\n\n\n", "file_path": "src/level_loader/objects.rs", "rank": 46, "score": 8.390125220967215 }, { "content": "use crate::settings::prelude::SavefileSettings;\n\nuse crate::settings::prelude::ZoneId;\n\nuse deathframe::amethyst;\n\nuse std::collections::{HashMap, HashSet};\n\nuse std::fs::File;\n\nuse std::path::PathBuf;\n\n\n\n#[derive(Default, Serialize, Deserialize)]\n\npub struct Savefile {\n\n pub highscores: Highscores,\n\n pub unlocked: HashSet<ZoneId>,\n\n\n\n #[serde(skip)]\n\n should_save: bool,\n\n}\n\n\n\n#[derive(Default, Serialize, Deserialize)]\n\npub struct Highscores {\n\n pub progression: Option<Highscore>,\n\n pub infinite: HashMap<ZoneId, Highscore>,\n", "file_path": "src/resources/savefile/mod.rs", "rank": 47, "score": 8.125703759704038 }, { "content": "use super::data::*;\n\nuse crate::components::prelude::*;\n\nuse crate::resource;\n\nuse crate::settings::zones_settings::SegmentId;\n\nuse amethyst::ecs::{Builder, Entity, World, WorldExt};\n\nuse deathframe::amethyst;\n\nuse deathframe::resources::SpriteSheetHandles;\n\nuse std::path::PathBuf;\n\n\n", "file_path": "src/level_loader/tiles.rs", "rank": 48, "score": 8.010321571180222 }, { "content": "use crate::resource;\n\nuse crate::settings::Settings;\n\nuse crate::states::aliases::GameData;\n\nuse crate::states::prelude::Startup;\n\nuse amethyst::core::frame_limiter::FrameRateLimitConfig;\n\nuse amethyst::utils::app_root_dir::application_root_dir;\n\nuse amethyst::ApplicationBuilder;\n\nuse deathframe::amethyst;\n\n\n\nmod init_game_data;\n\n\n", "file_path": "src/init/mod.rs", "rank": 50, "score": 7.8122570897575265 }, { "content": "use super::component_prelude::*;\n\nuse crate::settings::zones_settings::SegmentId;\n\n\n\n#[derive(Component)]\n\n#[storage(VecStorage)]\n\npub struct BelongsToSegment(pub SegmentId);\n", "file_path": "src/components/belongs_to_segment.rs", "rank": 51, "score": 7.653843852046629 }, { "content": "pub mod data;\n\npub mod objects;\n\npub mod tiles;\n\n\n\nuse crate::components::prelude::Size;\n\nuse crate::resources::prelude::{ZoneSize, ZonesManager};\n\nuse crate::settings::zones_settings::{SegmentId, ZoneId, ZonesSettings};\n\nuse amethyst::ecs::{World, WorldExt};\n\nuse data::*;\n\nuse deathframe::amethyst;\n\nuse std::fs::File;\n\nuse std::path::PathBuf;\n\n\n\n#[derive(Deserialize, Clone)]\n\npub enum TileType {\n\n #[serde(rename = \"\")]\n\n Empty,\n\n}\n\n\n\n#[derive(Deserialize, PartialEq, Eq, Hash, Clone, Debug)]\n\npub enum ObjectType {\n\n Player,\n\n Solid,\n\n Portal,\n\n Obstacle,\n\n Coin(ZoneId),\n\n Custom(String),\n\n}\n\n\n", "file_path": "src/level_loader/mod.rs", "rank": 52, "score": 7.574271604248039 }, { "content": "use crate::level_loader::data::DataLevel;\n\nuse crate::level_loader::load_level;\n\nuse crate::resource;\n\nuse crate::resources::prelude::SongKey;\n\nuse crate::settings::zones_settings::{SegmentId, ZoneId, ZonesSettings};\n\nuse rand::prelude::SliceRandom;\n\nuse replace_with::replace_with_or_abort;\n\nuse std::collections::HashMap;\n\n\n\nconst KEEP_COUNT_SEGMENTS_LOADED: usize = 2;\n\n\n\n#[derive(Default)]\n\npub struct ZonesManager {\n\n current_zone: Option<ZoneState>,\n\n initial_zone_idx: Option<usize>,\n\n is_infinite_zone: bool,\n\n last_staged_segment: Option<SegmentId>,\n\n staged_segments: Vec<SegmentId>,\n\n levels: HashMap<SegmentId, DataLevel>,\n\n segment_loading_locked: bool,\n\n}\n\n\n\n#[derive(Debug)]\n", "file_path": "src/resources/zones_manager.rs", "rank": 53, "score": 7.352643855591024 }, { "content": "use super::component_prelude::*;\n\nuse crate::settings::zones_settings::SegmentId;\n\n\n\n#[derive(Component)]\n\n#[storage(VecStorage)]\n\npub struct Segment {\n\n pub id: SegmentId,\n\n pub is_first_segment: bool,\n\n pub is_final_segment: bool,\n\n}\n", "file_path": "src/components/segment.rs", "rank": 54, "score": 7.324088429099131 }, { "content": "use crate::settings::prelude::LanesSettings;\n\n\n\npub struct Lanes {\n\n pub lanes: Vec<Lane>,\n\n}\n\n\n\npub struct Lane {\n\n pub x: f32,\n\n}\n\n\n\nimpl From<(&LanesSettings, f32)> for Lanes {\n\n fn from((settings, level_width): (&LanesSettings, f32)) -> Self {\n\n let center_x = level_width * 0.5;\n\n let total_lanes_width = settings.spacing * settings.count as f32;\n\n let half_lanes_width = total_lanes_width * 0.5;\n\n let half_lane_width = settings.spacing * 0.5;\n\n\n\n let lanes = (0 .. settings.count)\n\n .into_iter()\n\n .map(|i| Lane {\n\n x: center_x + (i as f32 * settings.spacing) - half_lanes_width\n\n + half_lane_width,\n\n })\n\n .collect();\n\n\n\n Self { lanes }\n\n }\n\n}\n", "file_path": "src/resources/lanes.rs", "rank": 55, "score": 6.6238731607347 }, { "content": "use crate::settings::prelude::ZoneId;\n\n\n\n#[derive(Default)]\n\npub struct SelectedZone(pub Option<(usize, ZoneId)>);\n", "file_path": "src/resources/selected_zone.rs", "rank": 56, "score": 6.538593033205714 }, { "content": " fn load_zone(&mut self, world: &mut World) {\n\n let mut player_speed_opt = None;\n\n\n\n {\n\n use deathframe::amethyst::ecs::{ReadExpect, WriteExpect};\n\n\n\n world.exec(\n\n |(\n\n mut zones_manager,\n\n settings,\n\n mut songs,\n\n savefile_settings,\n\n mut savefile,\n\n ): (\n\n WriteExpect<ZonesManager>,\n\n ReadExpect<ZonesSettings>,\n\n WriteExpect<Songs<SongKey>>,\n\n ReadExpect<SavefileSettings>,\n\n WriteExpect<Savefile>,\n\n )| {\n", "file_path": "src/states/ingame.rs", "rank": 57, "score": 6.4358998292679725 }, { "content": "\n\npub mod aliases {\n\n use crate::resources::prelude::DispatcherId;\n\n use deathframe::core::custom_game_data::prelude::*;\n\n\n\n pub type CustomData = ();\n\n\n\n pub type GameData<'a, 'b> =\n\n CustomGameData<'a, 'b, DispatcherId, CustomData>;\n\n\n\n pub type GameDataBuilder<'a, 'b> =\n\n CustomGameDataBuilder<'a, 'b, DispatcherId, CustomData>;\n\n}\n\n\n\nmod state_prelude {\n\n pub use super::aliases::*;\n\n pub use super::prelude::*;\n\n pub use super::state_helpers::*;\n\n pub use crate::resource;\n\n pub use crate::resources::prelude::*;\n\n pub use crate::settings::prelude::*;\n\n pub use deathframe::states::state_prelude::*;\n\n}\n\n\n\nmod menu_prelude {\n\n pub use deathframe::amethyst::ui::{UiEvent, UiEventType};\n\n pub use deathframe::core::menu::prelude::*;\n\n}\n", "file_path": "src/states/mod.rs", "rank": 58, "score": 6.169196797988084 }, { "content": "use super::system_prelude::*;\n\n\n\n#[derive(Default)]\n\npub struct HandleZoneSelect;\n\n\n\nimpl<'a> System<'a> for HandleZoneSelect {\n\n type SystemData = (\n\n ReadExpect<'a, InputManager<MenuBindings>>,\n\n ReadExpect<'a, ZonesSettings>,\n\n Write<'a, SelectedZone>,\n\n ReadExpect<'a, Savefile>,\n\n );\n\n\n\n fn run(\n\n &mut self,\n\n (\n\n input_manager,\n\n settings,\n\n mut selected_zone,\n\n savefile,\n", "file_path": "src/systems/handle_zone_select.rs", "rank": 59, "score": 6.0627299657871845 }, { "content": "\n\nimpl<'a, 'b> State<GameData<'a, 'b>, StateEvent> for ZoneTransition {\n\n fn on_start(&mut self, mut data: StateData<GameData<'a, 'b>>) {\n\n self.start(&mut data);\n\n\n\n {\n\n use deathframe::amethyst::ecs::{ReadExpect, WriteExpect};\n\n\n\n data.world.exec(\n\n |(mut zones_manager, zones_settings): (\n\n WriteExpect<ZonesManager>,\n\n ReadExpect<ZonesSettings>,\n\n )| {\n\n zones_manager.stage_next_zone(&zones_settings);\n\n },\n\n )\n\n }\n\n }\n\n\n\n fn on_resume(&mut self, mut data: StateData<GameData<'a, 'b>>) {\n", "file_path": "src/states/zone_transition.rs", "rank": 60, "score": 5.965678061123347 }, { "content": " pub use super::handle_delete_delay::HandleDeleteDelay;\n\n pub use super::handle_obstacle::HandleObstacle;\n\n pub use super::handle_parent_delete::HandleParentDelete;\n\n pub use super::handle_segment_loading::HandleSegmentLoading;\n\n pub use super::handle_turret::HandleTurret;\n\n pub use super::handle_zone_select::HandleZoneSelect;\n\n pub use super::handle_zone_switch::HandleZoneSwitch;\n\n pub use super::update_highscore_ui::UpdateHighscoreUi;\n\n pub use super::update_on_lane::UpdateOnLane;\n\n pub use super::update_rotate::UpdateRotate;\n\n pub use super::update_score_ui::UpdateScoreUi;\n\n pub use super::update_selected_zone_ui::UpdateSelectedZoneUi;\n\n pub use deathframe::systems::prelude::*;\n\n}\n\n\n\nmod system_prelude {\n\n pub use crate::components::prelude::*;\n\n pub use crate::input::prelude::*;\n\n pub use crate::resources::prelude::*;\n\n pub use crate::settings::prelude::*;\n\n pub use deathframe::core::geo::prelude::*;\n\n pub use deathframe::systems::system_prelude::*;\n\n}\n", "file_path": "src/systems/mod.rs", "rank": 61, "score": 5.91090618982883 }, { "content": " data.world.insert(ZoneSize::default());\n\n data.world.insert(ShouldLoadNextZone::default());\n\n data.world.insert(GameOver::default());\n\n data.world.insert(Score::default());\n\n\n\n {\n\n let lanes = Lanes::from((\n\n &*data.world.read_resource::<LanesSettings>(),\n\n SEGMENT_WIDTH,\n\n ));\n\n data.world.insert(lanes);\n\n }\n\n\n\n {\n\n use deathframe::amethyst::ecs::{ReadExpect, WriteExpect};\n\n\n\n data.world.exec(\n\n |(mut zones_manager, settings): (\n\n WriteExpect<ZonesManager>,\n\n ReadExpect<ZonesSettings>,\n", "file_path": "src/states/ingame.rs", "rank": 62, "score": 5.908676641088537 }, { "content": "extern crate climer;\n\nextern crate deathframe;\n\nextern crate dirs;\n\nextern crate rand;\n\nextern crate replace_with;\n\nextern crate ron;\n\n#[macro_use]\n\nextern crate serde;\n\nextern crate serde_json;\n\n\n\nmod components;\n\nmod init;\n\nmod input;\n\nmod level_loader;\n\nmod resources;\n\nmod settings;\n\nmod states;\n\nmod systems;\n\n\n\npub use deathframe::core::resource_helper::resource;\n\n\n", "file_path": "src/main.rs", "rank": 63, "score": 5.7282927833961566 }, { "content": "use super::system_prelude::*;\n\n\n\n#[derive(Default)]\n\npub struct HandleSegmentLoading;\n\n\n\nimpl<'a> System<'a> for HandleSegmentLoading {\n\n type SystemData = (\n\n Entities<'a>,\n\n WriteExpect<'a, ZonesManager>,\n\n ReadExpect<'a, ZonesSettings>,\n\n ReadStorage<'a, Camera>,\n\n ReadStorage<'a, Segment>,\n\n ReadStorage<'a, Transform>,\n\n ReadStorage<'a, Size>,\n\n );\n\n\n\n fn run(\n\n &mut self,\n\n (\n\n entities,\n", "file_path": "src/systems/handle_segment_loading.rs", "rank": 64, "score": 5.271385204277562 }, { "content": " .with_resource(player_settings)\n\n .with_resource(objects_settings)\n\n .with_resource(lanes_settings)\n\n .with_resource(zones_settings)\n\n .with_resource(audio_settings)\n\n .with_resource(savefile_settings)\n\n .build(game_data)?;\n\n\n\n game.run();\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/init/mod.rs", "rank": 65, "score": 4.580522909023876 }, { "content": " .map(|zone_settings| zone_settings.player_speed)\n\n }\n\n\n\n pub fn is_current_zone_skippable(\n\n &self,\n\n settings: &ZonesSettings,\n\n ) -> Option<bool> {\n\n if self.is_infinite_zone {\n\n Some(false)\n\n } else {\n\n self.current_zone\n\n .as_ref()\n\n .and_then(|current_zone| settings.zones.get(&current_zone.id))\n\n .map(|zone_settings| zone_settings.is_skippable)\n\n }\n\n }\n\n}\n", "file_path": "src/resources/zones_manager.rs", "rank": 66, "score": 4.530562666553377 }, { "content": " pub use super::cutscene::Cutscene;\n\n pub use super::delete_delay::DeleteDelay;\n\n pub use super::object::Object;\n\n pub use super::obstacle::Obstacle;\n\n pub use super::on_lane::OnLane;\n\n pub use super::parent_delete::ParentDelete;\n\n pub use super::player::Player;\n\n pub use super::portal::Portal;\n\n pub use super::rotate::Rotate;\n\n pub use super::segment::Segment;\n\n pub use super::tile::Tile;\n\n pub use super::turret::Turret;\n\n pub use deathframe::amethyst::core::transform::Parent;\n\n pub use deathframe::components::prelude::*;\n\n}\n\n\n\nmod component_prelude {\n\n pub use super::prelude::*;\n\n pub use deathframe::components::component_prelude::*;\n\n}\n", "file_path": "src/components/mod.rs", "rank": 67, "score": 4.524326462039251 }, { "content": " })\n\n }\n\n\n\n pub fn get_current_song<'a>(\n\n &self,\n\n settings: &'a ZonesSettings,\n\n ) -> Option<&'a SongKey> {\n\n self.current_zone\n\n .as_ref()\n\n .and_then(|current_zone| settings.zones.get(&current_zone.id))\n\n .and_then(|zone_settings| zone_settings.song.as_ref())\n\n }\n\n\n\n pub fn get_current_player_speed(\n\n &self,\n\n settings: &ZonesSettings,\n\n ) -> Option<f32> {\n\n self.current_zone\n\n .as_ref()\n\n .and_then(|current_zone| settings.zones.get(&current_zone.id))\n", "file_path": "src/resources/zones_manager.rs", "rank": 68, "score": 4.501170941338993 }, { "content": " );\n\n }\n\n }\n\n\n\n fn get_next_segment(&self, settings: &ZonesSettings) -> Option<SegmentId> {\n\n if self.segment_loading_locked {\n\n return None;\n\n }\n\n\n\n let mut rng = rand::thread_rng();\n\n self.current_zone\n\n .as_ref()\n\n .and_then(|current_zone| {\n\n settings\n\n .zones\n\n .get(&current_zone.id)\n\n .map(|settings| (current_zone, settings))\n\n })\n\n .map(|(current_zone, zone_settings)| {\n\n let should_load_next_zone = zone_settings\n", "file_path": "src/resources/zones_manager.rs", "rank": 69, "score": 4.4632102000735525 }, { "content": " let object_settings = {\n\n let settings = world.read_resource::<ObjectsSettings>();\n\n settings.objects.get(object_type).map(|s| s.clone())\n\n };\n\n\n\n if let Some(object_settings) = object_settings {\n\n let sprite_render_opt = if let Some(spritesheet) =\n\n object_settings.spritesheet.as_ref()\n\n {\n\n let sprite_sheet = world\n\n .write_resource::<SpriteSheetHandles<PathBuf>>()\n\n .get_or_load(\n\n resource(format!(\"spritesheets/{}\", spritesheet)),\n\n world,\n\n );\n\n Some({\n\n SpriteRender {\n\n sprite_sheet,\n\n sprite_number: 0,\n\n }\n", "file_path": "src/level_loader/objects.rs", "rank": 70, "score": 4.4632102000735525 }, { "content": "pub mod prelude {\n\n pub use super::animation_key::AnimationKey;\n\n pub use super::collision_tag::{CollisionTag, SolidTag};\n\n pub use super::dispatcher_id::DispatcherId;\n\n pub use super::game_over::GameOver;\n\n pub use super::lanes::{Lane, Lanes};\n\n pub use super::object_spawner::{ObjectSpawner, ObjectToSpawn};\n\n pub use super::savefile::{Highscore, Highscores, Savefile};\n\n pub use super::score::Score;\n\n pub use super::selected_zone::SelectedZone;\n\n pub use super::should_load_next_zone::ShouldLoadNextZone;\n\n pub use super::song_key::SongKey;\n\n pub use super::sound_key::SoundKey;\n\n pub use super::zone_progression_mode::ZoneProgressionMode;\n\n pub use super::zone_size::ZoneSize;\n\n pub use super::zones_manager::ZonesManager;\n\n pub use deathframe::resources::prelude::*;\n\n}\n\n\n\nmod animation_key;\n", "file_path": "src/resources/mod.rs", "rank": 71, "score": 4.413194167842804 }, { "content": "mod cutscene;\n\nmod game_over_state;\n\nmod ingame;\n\nmod main_menu;\n\nmod pause;\n\nmod startup;\n\nmod state_helpers;\n\nmod zone_select;\n\nmod zone_transition;\n\n\n\npub mod prelude {\n\n pub use super::cutscene::Cutscene;\n\n pub use super::game_over_state::GameOverState;\n\n pub use super::ingame::Ingame;\n\n pub use super::main_menu::MainMenu;\n\n pub use super::pause::Pause;\n\n pub use super::startup::Startup;\n\n pub use super::zone_select::ZoneSelect;\n\n pub use super::zone_transition::ZoneTransition;\n\n}\n", "file_path": "src/states/mod.rs", "rank": 72, "score": 4.2386060417002085 }, { "content": " Err(e) => {\n\n eprintln!(\n\n \"[WARNING]\\n Couldn't load segment {}!\\n{}\",\n\n &segment, e\n\n )\n\n }\n\n }\n\n }\n\n }\n\n\n\n pub fn stage_next_zone(&mut self, settings: &ZonesSettings) {\n\n if let Some((next_zone, next_order_idx)) = self.get_next_zone(settings)\n\n {\n\n self.reset();\n\n self.current_zone = Some(ZoneState::new(next_zone, next_order_idx));\n\n self.load_all_segments(settings);\n\n } else {\n\n eprintln!(\"[WARNING]\\n There is no next zone to load!\");\n\n }\n\n }\n", "file_path": "src/resources/zones_manager.rs", "rank": 73, "score": 4.108358676657278 }, { "content": " object_settings.components.clone(),\n\n size_opt,\n\n );\n\n\n\n Some(entity_builder)\n\n } else {\n\n eprintln!(\n\n \"[WARNING]\\n No settings for object: {:?}\",\n\n object_type\n\n );\n\n None\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/level_loader/objects.rs", "rank": 74, "score": 4.092350301061282 }, { "content": "use amethyst::renderer::rendy::wsi::winit::Window;\n\nuse deathframe::amethyst;\n\n\n", "file_path": "src/states/state_helpers.rs", "rank": 75, "score": 4.066435153209763 }, { "content": " {\n\n zones_manager.stage_initial_segments(&settings);\n\n player_speed_opt =\n\n zones_manager.get_current_player_speed(&settings);\n\n if let Some(is_skippable) =\n\n zones_manager.is_current_zone_skippable(&settings)\n\n {\n\n self.is_zone_skippable = is_skippable;\n\n }\n\n songs.stop_all();\n\n if let Some(song_key) =\n\n zones_manager.get_current_song(&settings)\n\n {\n\n songs.play(song_key);\n\n }\n\n }\n\n\n\n {\n\n if let Some(zone) = zones_manager.current_zone() {\n\n savefile.unlock(zone.clone());\n", "file_path": "src/states/ingame.rs", "rank": 76, "score": 4.035871855552555 }, { "content": "use super::menu_prelude::*;\n\nuse super::state_prelude::*;\n\nuse crate::components::prelude::Size;\n\nuse crate::input::prelude::{MenuAction, MenuBindings};\n\nuse crate::level_loader::objects::build_camera;\n\nuse crate::level_loader::{build_level, load_level};\n\n\n\n#[derive(Default)]\n\npub struct Cutscene {\n\n ui_data: UiData,\n\n did_load_level: bool,\n\n did_load_cutscene: bool,\n\n}\n\n\n\nimpl Cutscene {\n\n fn start<'a, 'b>(&mut self, data: &mut StateData<GameData<'a, 'b>>) {\n\n self.create_ui(data, resource(\"ui/cutscene.ron\").to_str().unwrap());\n\n }\n\n\n\n fn stop<'a, 'b>(&mut self, data: &mut StateData<GameData<'a, 'b>>) {\n", "file_path": "src/states/cutscene.rs", "rank": 77, "score": 4.022840966759144 }, { "content": "use super::menu_prelude::*;\n\nuse super::state_prelude::*;\n\nuse crate::components::prelude::{Size, Transform};\n\nuse crate::input::prelude::{MenuAction, MenuBindings};\n\nuse crate::level_loader::build_segment;\n\nuse crate::level_loader::objects::{build_camera, build_object, build_player};\n\n\n\nconst SEGMENT_WIDTH: f32 = 128.0;\n\nconst UI_SKIP_TEXT_ID: &str = \"skip_zone_text\";\n\nconst UI_SCORE_ID: &str = \"score\";\n\n\n\npub struct Ingame {\n\n initial_zone_idx: Option<usize>,\n\n is_infinite_zone: bool,\n\n load_new_zone_on_resume: bool,\n\n ui_data: UiData,\n\n is_zone_skippable: bool,\n\n}\n\n\n\nimpl Default for Ingame {\n", "file_path": "src/states/ingame.rs", "rank": 78, "score": 3.9989638226160755 }, { "content": "\n\n fn get_next_zone(\n\n &self,\n\n settings: &ZonesSettings,\n\n ) -> Option<(ZoneId, usize)> {\n\n if let Some(current_zone) = self.current_zone.as_ref() {\n\n let order_idx = current_zone.order_idx + 1;\n\n settings\n\n .config\n\n .zone_order\n\n .get(order_idx)\n\n .map(|next| (next, order_idx))\n\n } else {\n\n if let Some(&initial_zone_idx) = self.initial_zone_idx.as_ref() {\n\n settings\n\n .config\n\n .zone_order\n\n .get(initial_zone_idx)\n\n .map(|initial_zone| (initial_zone, initial_zone_idx))\n\n } else {\n", "file_path": "src/resources/zones_manager.rs", "rank": 79, "score": 3.9544715661755125 }, { "content": " }\n\n\n\n pub fn handle_save(&mut self, settings: &SavefileSettings) {\n\n if self.should_save() {\n\n match settings.savefile_path() {\n\n Ok(savefile_path) => {\n\n if let Err(e) = self.save(savefile_path) {\n\n eprintln!(\"[WARNING]\\n {}\", e);\n\n }\n\n }\n\n Err(e) => eprintln!(\"[WARNING]\\n {}\", e),\n\n }\n\n }\n\n }\n\n\n\n pub fn unlock(&mut self, zone: ZoneId) -> bool {\n\n let did_update = self.unlocked.insert(zone);\n\n if did_update {\n\n self.should_save = true;\n\n }\n", "file_path": "src/resources/savefile/mod.rs", "rank": 80, "score": 3.93818167472737 }, { "content": " use deathframe::amethyst::assets::AssetStorage;\n\n use deathframe::amethyst::ecs::{\n\n Join,\n\n Read,\n\n ReadStorage,\n\n WriteStorage,\n\n };\n\n use deathframe::amethyst::renderer::sprite::SpriteSheet;\n\n use deathframe::amethyst::renderer::Texture;\n\n\n\n if self.did_load_level && !self.did_load_cutscene {\n\n data.world.exec(\n\n |(\n\n spritesheet_assets,\n\n texture_assets,\n\n cutscene_store,\n\n mut animations_store,\n\n sprite_render_store,\n\n ): (\n\n Read<AssetStorage<SpriteSheet>>,\n", "file_path": "src/states/cutscene.rs", "rank": 81, "score": 3.927832111495411 }, { "content": " object.object_type,\n\n transform,\n\n object.size.map(Into::into),\n\n ) {\n\n entity_builder.build();\n\n }\n\n }\n\n }\n\n }\n\n\n\n fn handle_skippable_zone(&self, world: &mut World) {\n\n use deathframe::amethyst::core::HiddenPropagate;\n\n use deathframe::amethyst::ecs::{\n\n Entities,\n\n Join,\n\n ReadStorage,\n\n WriteStorage,\n\n };\n\n use deathframe::amethyst::ui::UiTransform;\n\n\n", "file_path": "src/states/ingame.rs", "rank": 82, "score": 3.911464089018892 }, { "content": " self.stage_next_segment(settings);\n\n }\n\n }\n\n\n\n pub fn stage_next_segment(&mut self, settings: &ZonesSettings) {\n\n if let Some(next_segment) = self.get_next_segment(settings) {\n\n self.current_zone\n\n .as_mut()\n\n .expect(\n\n \"Should have current zone, if next segment could be found\",\n\n )\n\n .total_segments_loaded += 1;\n\n self.last_staged_segment = Some(next_segment.clone());\n\n self.staged_segments.push(next_segment);\n\n } else {\n\n self.last_staged_segment = None;\n\n eprintln!(\n\n \"[WARNING]\\n ZonesManager couldn't find possible next \\\n\n segment, for zone and segment: {:?} {:?}\",\n\n &self.current_zone, &self.last_staged_segment\n", "file_path": "src/resources/zones_manager.rs", "rank": 83, "score": 3.8983102924001285 }, { "content": "pub mod prelude {\n\n pub use super::ingame_bindings::*;\n\n pub use super::menu_bindings::*;\n\n}\n\n\n\nmod ingame_bindings;\n\nmod menu_bindings;\n", "file_path": "src/input/mod.rs", "rank": 84, "score": 3.856927506606352 }, { "content": " );\n\n None\n\n }\n\n },\n\n )\n\n }\n\n\n\n fn load_all_segments(&mut self, settings: &ZonesSettings) {\n\n if let Some(segments) = self\n\n .current_zone\n\n .as_ref()\n\n .and_then(|zone| settings.zones.get(&zone.id))\n\n .map(|zone| {\n\n let mut segments = zone\n\n .segments\n\n .keys()\n\n .map(Clone::clone)\n\n .collect::<Vec<SegmentId>>();\n\n segments.append(&mut zone.first_segment.clone());\n\n segments.append(&mut zone.final_segment.clone());\n", "file_path": "src/resources/zones_manager.rs", "rank": 85, "score": 3.835462309663696 }, { "content": "use super::menu_prelude::*;\n\nuse super::state_prelude::*;\n\nuse crate::input::prelude::{MenuAction, MenuBindings};\n\n\n\n#[derive(Default)]\n\npub struct GameOverState {\n\n ui_data: UiData,\n\n}\n\n\n\nimpl GameOverState {\n\n fn start<'a, 'b>(&mut self, data: &mut StateData<GameData<'a, 'b>>) {\n\n self.create_ui(data, resource(\"ui/game_over.ron\").to_str().unwrap());\n\n self.update_highscore(data.world);\n\n }\n\n\n\n fn update_highscore(&self, world: &mut World) {\n\n use deathframe::amethyst::ecs::{Read, ReadExpect, WriteExpect};\n\n\n\n world.exec(\n\n |(\n", "file_path": "src/states/game_over_state.rs", "rank": 86, "score": 3.784425786064457 }, { "content": " .total_segments\n\n .map(|total_segments| {\n\n self.is_infinite_zone\n\n || current_zone.total_segments_loaded\n\n < total_segments\n\n })\n\n .unwrap_or(true);\n\n if should_load_next_zone {\n\n self.last_staged_segment\n\n .as_ref()\n\n .and_then(|current_segment| {\n\n zone_settings.segments.get(current_segment)\n\n })\n\n .unwrap_or(&zone_settings.first_segment)\n\n } else {\n\n &zone_settings.final_segment\n\n }\n\n })\n\n .and_then(|possible_segments| {\n\n possible_segments.choose(&mut rng).map(ToString::to_string)\n", "file_path": "src/resources/zones_manager.rs", "rank": 87, "score": 3.7653120127640265 }, { "content": "use super::component_prelude::*;\n\nuse crate::level_loader::ObjectType;\n\nuse climer::Timer;\n\nuse std::time::Duration;\n\n\n\n#[derive(Component, Clone, Deserialize)]\n\n#[storage(DenseVecStorage)]\n\npub struct Turret {\n\n pub shot_object_type: ObjectType,\n\n pub shot_interval_ms: u64,\n\n #[serde(default)]\n\n pub shot_initial_delay_ms: u64,\n\n #[serde(default)]\n\n pub shot_offset: (f32, f32),\n\n #[serde(skip)]\n\n shot_timer: Option<Timer>,\n\n}\n\n\n\nimpl Turret {\n\n pub fn get_timer(&mut self) -> &mut Timer {\n", "file_path": "src/components/turret.rs", "rank": 88, "score": 3.7632875163662955 }, { "content": "# DRIFTDOWN EZ MODE\n\nAlternate settings files to make the game easier. \n\nIntended for people who find the default settings too difficult, \n\nbut still want to experience the full game. \n\n\n\n## `EZ_ZONES`\n\n[`./ez_zones.ron`](./ez_zones.ron) \n\n\n\nOverwrite `resources/settings/zones/zones.ron` with the `ez_zones.ron` file.\n\n\n\n- Makes every zone skippable.\n\n- Decreases the total level segments in each zone.\n\n- Decreases the player speed in each zone.\n", "file_path": "ez_mode/README.md", "rank": 89, "score": 3.7515887614730565 }, { "content": " if let Some(song) = songs.get_mut(song_key) {\n\n song.set_volume(audio_settings.volume);\n\n }\n\n }\n\n Err(e) => eprintln!(\n\n \"[WARNING]\\n Error loading song {}, skipping.\\n{:#?}\",\n\n &song.file, e\n\n ),\n\n }\n\n }\n\n\n\n let mut sounds = Sounds::<SoundKey>::default();\n\n for (sound_key, sound) in audio_settings.sfx.iter() {\n\n if let Err(e) = sounds.load_audio(\n\n sound_key.clone(),\n\n resource(format!(\"audio/sfx/{}\", sound.file)),\n\n world,\n\n ) {\n\n eprintln!(\n\n \"[WARNING]\\n Error loading sound {}, skipping.\\n{:#?}\",\n", "file_path": "src/states/startup.rs", "rank": 90, "score": 3.711012713717892 }, { "content": "use super::system_prelude::*;\n\nuse deathframe::physics::query;\n\nuse query::prelude::{FilterQuery, Query};\n\n\n\n#[derive(Default)]\n\npub struct HandleCoinCollection;\n\n\n\nimpl<'a> System<'a> for HandleCoinCollection {\n\n type SystemData = (\n\n Entities<'a>,\n\n WriteExpect<'a, Score>,\n\n WriteExpect<'a, SoundPlayer<SoundKey>>,\n\n ReadStorage<'a, Player>,\n\n ReadStorage<'a, Coin>,\n\n ReadStorage<'a, Collider<CollisionTag>>,\n\n );\n\n\n\n fn run(\n\n &mut self,\n\n (\n", "file_path": "src/systems/handle_coin_collection.rs", "rank": 91, "score": 3.6968429990404617 }, { "content": "use super::system_prelude::*;\n\nuse deathframe::physics::query;\n\nuse query::prelude::{FindQuery, Query};\n\n\n\n#[derive(Default)]\n\npub struct HandleZoneSwitch;\n\n\n\nimpl<'a> System<'a> for HandleZoneSwitch {\n\n type SystemData = (\n\n WriteExpect<'a, ShouldLoadNextZone>,\n\n ReadStorage<'a, Player>,\n\n ReadStorage<'a, Collider<CollisionTag>>,\n\n );\n\n\n\n fn run(\n\n &mut self,\n\n (\n\n mut should_load_next_zone,\n\n player_store,\n\n collider_store,\n", "file_path": "src/systems/handle_zone_switch.rs", "rank": 92, "score": 3.6968429990404617 }, { "content": "use super::system_prelude::*;\n\nuse deathframe::physics::query;\n\nuse query::prelude::{FindQuery, Query};\n\n\n\n#[derive(Default)]\n\npub struct HandleObstacle;\n\n\n\nimpl<'a> System<'a> for HandleObstacle {\n\n type SystemData = (\n\n Entities<'a>,\n\n WriteExpect<'a, GameOver>,\n\n WriteExpect<'a, SoundPlayer<SoundKey>>,\n\n ReadStorage<'a, Player>,\n\n ReadStorage<'a, Obstacle>,\n\n ReadStorage<'a, Collider<CollisionTag>>,\n\n WriteStorage<'a, AnimationsContainer<AnimationKey>>,\n\n WriteStorage<'a, Velocity>,\n\n );\n\n\n\n fn run(\n", "file_path": "src/systems/handle_obstacle.rs", "rank": 93, "score": 3.6174476083654574 }, { "content": "use super::component_prelude::*;\n\nuse crate::level_loader::ObjectType;\n\n\n\n#[derive(Component)]\n\n#[storage(VecStorage)]\n\npub struct Object {\n\n pub object_type: ObjectType,\n\n}\n\n\n\nimpl From<ObjectType> for Object {\n\n fn from(object_type: ObjectType) -> Self {\n\n Self { object_type }\n\n }\n\n}\n", "file_path": "src/components/object.rs", "rank": 94, "score": 3.609006979843734 }, { "content": "use super::menu_prelude::*;\n\nuse super::state_prelude::*;\n\nuse crate::input::prelude::{MenuAction, MenuBindings};\n\n\n\n#[derive(Default)]\n\npub struct Pause {\n\n ui_data: UiData,\n\n}\n\n\n\nimpl Pause {\n\n fn start<'a, 'b>(&mut self, data: &mut StateData<GameData<'a, 'b>>) {\n\n self.create_ui(data, resource(\"ui/pause.ron\").to_str().unwrap());\n\n }\n\n\n\n fn stop<'a, 'b>(&mut self, data: &mut StateData<GameData<'a, 'b>>) {\n\n self.delete_ui(data);\n\n }\n\n\n\n fn handle_input<'a, 'b>(\n\n &mut self,\n", "file_path": "src/states/pause.rs", "rank": 95, "score": 3.6045454153532015 }, { "content": "use super::component_prelude::*;\n\nuse climer::Timer;\n\nuse std::time::Duration;\n\n\n\n#[derive(Component, Clone, Deserialize)]\n\n#[storage(DenseVecStorage)]\n\npub struct DeleteDelay {\n\n pub delete_after_ms: u64,\n\n #[serde(skip)]\n\n timer: Option<Timer>,\n\n}\n\n\n\nimpl DeleteDelay {\n\n pub fn get_timer(&mut self) -> &mut Timer {\n\n let ms = self.delete_after_ms;\n\n self.timer.get_or_insert_with(|| {\n\n let mut timer =\n\n Timer::new(Some(Duration::from_millis(ms).into()), None);\n\n let _ = timer.start();\n\n timer\n\n })\n\n }\n\n}\n", "file_path": "src/components/delete_delay.rs", "rank": 96, "score": 3.6045454153532015 }, { "content": " world.register::<Turret>();\n\n world.register::<Cutscene>();\n\n\n\n let sprite_sheet_handles = SpriteSheetHandles::<PathBuf>::default();\n\n world.insert(sprite_sheet_handles);\n\n\n\n world.insert(load_savefile(&world));\n\n\n\n let (songs, sounds) = {\n\n let audio_settings = world.read_resource::<AudioSettings>();\n\n\n\n let mut songs = Songs::<SongKey>::default();\n\n for (song_key, song) in audio_settings.bgm.iter() {\n\n match songs.load_audio(\n\n song_key.clone(),\n\n resource(format!(\"audio/bgm/{}\", song.file)),\n\n true,\n\n world,\n\n ) {\n\n Ok(_) => {\n", "file_path": "src/states/startup.rs", "rank": 97, "score": 3.5943853634685814 }, { "content": " settings.config.zone_order.first().map(|first| (first, 0))\n\n }\n\n }\n\n .map(|(next, order_idx)| (next.clone(), order_idx))\n\n }\n\n\n\n fn reset(&mut self) {\n\n replace_with_or_abort(self, |self_| ZonesManager {\n\n current_zone: None,\n\n initial_zone_idx: self_.initial_zone_idx,\n\n is_infinite_zone: self_.is_infinite_zone,\n\n last_staged_segment: None,\n\n staged_segments: Vec::new(),\n\n levels: HashMap::new(),\n\n segment_loading_locked: false,\n\n });\n\n }\n\n\n\n pub fn stage_initial_segments(&mut self, settings: &ZonesSettings) {\n\n for _ in 0 .. KEEP_COUNT_SEGMENTS_LOADED {\n", "file_path": "src/resources/zones_manager.rs", "rank": 98, "score": 3.5943853634685814 }, { "content": "pub mod belongs_to_segment;\n\npub mod camera;\n\npub mod coin;\n\npub mod cutscene;\n\npub mod delete_delay;\n\npub mod object;\n\npub mod obstacle;\n\npub mod on_lane;\n\npub mod parent_delete;\n\npub mod player;\n\npub mod portal;\n\npub mod rotate;\n\npub mod segment;\n\npub mod tile;\n\npub mod turret;\n\n\n\npub mod prelude {\n\n pub use super::belongs_to_segment::BelongsToSegment;\n\n pub use super::camera::Camera;\n\n pub use super::coin::Coin;\n", "file_path": "src/components/mod.rs", "rank": 99, "score": 3.4804111065257555 } ]
Rust
src/fixes.rs
utter-step/dotenv-linter
6005dbcb2ea3de0f233f218bf91d8373813b589e
use crate::common::*; mod ending_blank_line; mod key_without_value; mod lowercase_key; mod quote_character; mod space_character; mod trailing_whitespace; trait Fix { fn name(&self) -> &str; fn fix_warnings( &self, warnings: Vec<&mut Warning>, lines: &mut Vec<LineEntry>, ) -> Option<usize> { let mut count: usize = 0; for warning in warnings { let line = lines.get_mut(warning.line_number() - 1)?; if self.fix_line(line).is_some() { warning.mark_as_fixed(); count += 1; } } Some(count) } fn fix_line(&self, _line: &mut LineEntry) -> Option<()> { None } } fn fixlist() -> Vec<Box<dyn Fix>> { vec![ Box::new(key_without_value::KeyWithoutValueFixer::default()), Box::new(lowercase_key::LowercaseKeyFixer::default()), Box::new(space_character::SpaceCharacterFixer::default()), Box::new(trailing_whitespace::TrailingWhitespaceFixer::default()), Box::new(quote_character::QuoteCharacterFixer::default()), Box::new(ending_blank_line::EndingBlankLineFixer::default()), ] } pub fn run(warnings: &mut [Warning], lines: &mut Vec<LineEntry>) -> usize { if warnings.is_empty() { return 0; } let mut count = 0; for fixer in fixlist() { let fixer_warnings: Vec<&mut Warning> = warnings .iter_mut() .filter(|w| w.check_name == fixer.name()) .collect(); if !fixer_warnings.is_empty() { match fixer.fix_warnings(fixer_warnings, lines) { Some(fixer_count) => count += fixer_count, None => { for warning in warnings { warning.mark_as_unfixed(); } return 0; } } } } count } #[cfg(test)] mod tests { use super::*; use std::path::PathBuf; fn line_entry(number: usize, total_lines: usize, str: &str) -> LineEntry { LineEntry { number, file: FileEntry { path: PathBuf::from(".env"), file_name: ".env".to_string(), total_lines, }, raw_string: String::from(str), } } fn blank_line_entry(number: usize, total_lines: usize) -> LineEntry { LineEntry { number, file: FileEntry { path: PathBuf::from(".env"), file_name: ".env".to_string(), total_lines, }, raw_string: String::from("\n"), } } #[test] fn run_with_empty_warnings_test() { let mut lines = vec![line_entry(1, 2, "A=B"), blank_line_entry(2, 2)]; let mut warnings: Vec<Warning> = Vec::new(); assert_eq!(0, run(&mut warnings, &mut lines)); } #[test] fn run_with_fixable_warning_test() { let mut lines = vec![ line_entry(1, 3, "A=B"), line_entry(2, 3, "c=d"), blank_line_entry(3, 3), ]; let mut warnings = vec![Warning::new( lines[1].clone(), "LowercaseKey", String::from("The c key should be in uppercase"), )]; assert_eq!(1, run(&mut warnings, &mut lines)); assert_eq!("C=d", lines[1].raw_string); assert!(warnings[0].is_fixed); } #[test] fn run_with_unfixable_warning_test() { let mut lines = vec![ line_entry(1, 3, "A=B"), line_entry(2, 3, "UNFIXABLE-"), blank_line_entry(3, 3), ]; let mut warnings = vec![Warning::new( lines[1].clone(), "Unfixable", String::from("The UNFIXABLE- key is not fixable"), )]; assert_eq!(0, run(&mut warnings, &mut lines)); assert!(!warnings[0].is_fixed); } #[test] fn run_when_lines_do_not_fit_numbers_test() { let mut lines = vec![ line_entry(1, 3, "a=B"), line_entry(4, 3, "c=D"), blank_line_entry(3, 3), ]; let mut warnings = vec![ Warning::new( lines[0].clone(), "LowercaseKey", String::from("The a key should be in uppercase"), ), Warning::new( lines[1].clone(), "LowercaseKey", String::from("The c key should be in uppercase"), ), ]; assert_eq!(0, run(&mut warnings, &mut lines)); assert!(!warnings[0].is_fixed); } struct TestFixer<'a> { name: &'a str, } impl Fix for TestFixer<'_> { fn name(&self) -> &str { self.name } fn fix_line(&self, line: &mut LineEntry) -> Option<()> { if line.raw_string.chars().count() > 5 { Some(()) } else { None } } } #[test] fn warnings_are_marked_as_fixed_if_fix_returns_some() { let mut lines = vec![line_entry(1, 2, "foo=bar"), blank_line_entry(2, 2)]; let mut warning = Warning::new(lines[0].clone(), "", String::from("")); let fixer = TestFixer { name: "fixer" }; fixer.fix_warnings(vec![&mut warning], &mut lines); assert!(warning.is_fixed) } #[test] fn warnings_are_not_marked_as_fixed_if_fix_returns_none() { let mut lines = vec![line_entry(1, 2, "a=b"), blank_line_entry(2, 2)]; let mut warning = Warning::new(lines[0].clone(), "", String::from("")); let fixer = TestFixer { name: "fixer" }; fixer.fix_warnings(vec![&mut warning], &mut lines); assert!(!warning.is_fixed) } }
use crate::common::*; mod ending_blank_line; mod key_without_value; mod lowercase_key; mod quote_character; mod space_character; mod trailing_whitespace; trait Fix { fn name(&self) -> &str; fn fix_warnings( &self, warnings: Vec<&mut Warning>, lines: &mut Vec<LineEntry>, ) -> Option<usize> { let mut count: usize = 0; for warning in warnings { let line = lines.get_mut(warning.line_number() - 1)?; if self.fix_line(line).is_some() { warning.mark_as_fixed(); count += 1; } } Some(count) } fn fix_line(&self, _line: &mut LineEntry) -> Option<()> { None } } fn fixlist() -> Vec<Box<dyn Fix>> { vec![ Box::new(key_without_value::KeyWithoutValueFixer::default()), Box::new(lowercase_key::LowercaseKeyFixer::default()), Box::new(space_character::SpaceCharacterFixer::default()), Box::new(trailing_whitespace::TrailingWhitespaceFixer::default()), Box::new(quote_character::QuoteCharacterFixer::default()), Box::new(ending_blank_line::EndingBlankLineFixer::default()), ] } pub fn run(warnings: &mut [Warning], lines: &mut Vec<LineEntry>) -> usize { if warnings.is_empty() { return 0; } let mut count = 0; for fixer in fixlist() { let fixer_warnings: Vec<&mut Warning> = warnings .iter_mut() .filter(|w| w.check_name == fixer.name()) .collect(); if !fixer_warnings.is_empty() { match fixer.fix_warnings(fixer_warnings, lines) { Some(fixer_count) => count += fixer_count, None => { for warning in warnings { warning.mark_as_unfixed(); } return 0; } } } } count } #[cfg(test)] mod tests { use super::*; use std::path::PathBuf; fn line_entry(number: usize, total_lines: usize, str: &str) -> LineEntry { LineEntry { number, file: FileEntry { path: PathBuf::from(".env"), file_name: ".env".to_string(), total_lines, }, raw_string: String::from(str), } } fn blank_line_entry(number: usize, total_lines: usize) -> LineEntry { LineEntry { number, file: FileEntry { path: PathBuf::from(".env"), file_name: ".env".to_string(), total_lines, }, raw_string: String::from("\n"), } } #[test] fn run_with_empty_warnings_test() { let mut lines = vec![line_entry(1, 2, "A=B"), blank_line_entry(2, 2)]; let mut warnings: Vec<Warning> = Vec::new(); assert_eq!(0, run(&mut warnings, &mut lines)); } #[test] fn run_with_fixable_warning_test() { let mut lines = vec![ line_entry(1, 3, "A=B"), line_entry(2, 3, "c=d"), blank_line_entry(3, 3), ]; let mut warnings = vec![Warning::new( lines[1].clone(), "LowercaseKey", String::from("The c key should be in uppercase"), )]; assert_eq!(1, run(&mut warnings, &mut lines)); assert_eq!("C=d", lines[1].raw_string); assert!(warnings[0].is_fixed); } #[test] fn run_with_unfixable_warning_test() { let mut lines = vec![ line_entry(1, 3, "A=B"), line_entry(2, 3, "UNFIXABLE-"), blank_line_entry(3, 3), ]; let mut warnings = vec![Warning::new( lines[1].clone(), "Unfixable", String::from("The UNFIXABLE- key is not fixable"), )]; assert_eq!(0, run(&mut warnings, &mut lines)); assert!(!warnings[0].is_fixed); } #[test] fn run_when_lines_do_not_fit_numbers_test() { let mut lines = vec![ line_entry(1, 3, "a=B"), line_entry(4, 3, "c=D"), blank_line_entry(3, 3), ]; let mut warnings = vec![ Warning::new( lines[0].clone(), "LowercaseKey", String::from("The a key should be in uppercase"), ), Warning::new( lines[1].clone(), "LowercaseKey", String::from("The c key should be in uppercase"), ), ]; assert_eq!(0, run(&mut warnings, &mut lines)); assert!(!warnings[0].is_fixed); } struct TestFixer<'a> { name: &'a str, } impl Fix for TestFixer<'_> { fn name(&self) -> &str { self.name } fn fix_line(&self, line: &mut LineEntry) -> Option<()> { if line.raw_string.chars().count() > 5 { Some(()) } else { None } } } #[test] fn warnings_are_marked_as_fixed_if_fix_returns_some() { let mut lines = vec![line_entry(1, 2, "foo=bar"), blank_line_entry(2, 2)]; let mut warning = Warning::new(lines[0].clone(), "", String::from("")); let fixer = TestFixer { name: "fixer" }; fixer.fix_warnings(vec![&mut warning], &mut lines); assert!(warning.is_fixed) } #[test] fn warnings_are_not_marked_as_fixed_if_fix_returns_none() { let mut lines = vec![line_entry(1, 2, "a=b"), blank_line_entry(2, 2)]; let mut warning = Warning::new(lines[0].clone(), "", String::from(""));
}
let fixer = TestFixer { name: "fixer" }; fixer.fix_warnings(vec![&mut warning], &mut lines); assert!(!warning.is_fixed) }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn unfixed_warnings() {\n\n let testdir = TestDir::new();\n\n let testfile = testdir.create_testfile(\".env\", \"A=DEF\\nB=BAR \\nf=BAR\\n\\n\");\n\n\n\n let expected_output = String::from(\n\n \"Fixed warnings:\\n\\\n\n .env:2 TrailingWhitespace: Trailing whitespace detected\\n\\\n\n .env:3 LowercaseKey: The f key should be in uppercase\\n\\\n\n \\n\\\n\n Unfixed warnings:\\n\\\n\n .env:5 ExtraBlankLine: Extra blank line detected\\n\",\n\n );\n\n testdir.test_command_fix_fail(expected_output);\n\n\n\n assert_eq!(testfile.contents().as_str(), \"A=DEF\\nB=BAR\\nF=BAR\\n\\n\");\n\n\n\n testdir.close();\n\n}\n\n\n", "file_path": "tests/fixes/mod.rs", "rank": 1, "score": 207464.3160682502 }, { "content": "pub fn run(lines: &[LineEntry], skip_checks: &[&str]) -> Vec<Warning> {\n\n let mut checks = checklist();\n\n checks.retain(|c| !skip_checks.contains(&c.name()));\n\n\n\n let mut warnings: Vec<Warning> = Vec::new();\n\n\n\n for line in lines {\n\n let is_comment = line.is_comment();\n\n for ch in &mut checks {\n\n if is_comment && ch.skip_comments() {\n\n continue;\n\n }\n\n if let Some(warning) = ch.run(line) {\n\n warnings.push(warning);\n\n }\n\n }\n\n }\n\n\n\n warnings\n\n}\n", "file_path": "src/checks.rs", "rank": 2, "score": 202541.9256181306 }, { "content": "/// In the future versions we should create a backup copy, or at least notify the user about it\n\npub fn write_file(path: &PathBuf, lines: Vec<LineEntry>) -> io::Result<()> {\n\n let mut file = File::create(path)?;\n\n\n\n // We don't write the last line, because it contains only LF (common::FileEntry::from)\n\n // and writeln! already adds LF.\n\n for line in lines[..lines.len() - 1].iter() {\n\n writeln!(file, \"{}\", line.raw_string)?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::common::FileEntry;\n\n use std::fs::{self, File};\n\n\n\n fn run_relative_path_asserts(assertions: Vec<(&str, &str, &str)>) {\n\n for (target, base, relative) in assertions {\n", "file_path": "src/fs_utils.rs", "rank": 3, "score": 196915.51502914648 }, { "content": "#[test]\n\nfn lowercase_key() {\n\n let testdir = TestDir::new();\n\n let testfile = testdir.create_testfile(\".env\", \"abc=DEF\\n\\nfOO=BAR\\n\");\n\n let expected_output = String::from(\n\n \"Fixed warnings:\\n\\\n\n .env:1 LowercaseKey: The abc key should be in uppercase\\n\\\n\n .env:3 LowercaseKey: The fOO key should be in uppercase\\n\",\n\n );\n\n testdir.test_command_fix_success(expected_output);\n\n\n\n assert_eq!(testfile.contents().as_str(), \"ABC=DEF\\n\\nFOO=BAR\\n\");\n\n\n\n testdir.close();\n\n}\n\n\n", "file_path": "tests/fixes/mod.rs", "rank": 4, "score": 196172.34993274446 }, { "content": "#[test]\n\nfn correct_file() {\n\n let testdir = TestDir::new();\n\n let testfile = testdir.create_testfile(\".env\", \"ABC=DEF\\nD=BAR\\n\\nFOO=BAR\\n\");\n\n\n\n testdir.test_command_fix_success(String::new());\n\n\n\n assert_eq!(testfile.contents().as_str(), \"ABC=DEF\\nD=BAR\\n\\nFOO=BAR\\n\");\n\n\n\n testdir.close();\n\n}\n\n\n", "file_path": "tests/fixes/mod.rs", "rank": 6, "score": 174608.8767300266 }, { "content": "#[test]\n\nfn multiple_files() {\n\n let testdir = TestDir::new();\n\n\n\n let testfile1 = testdir.create_testfile(\"1.env\", \"AB=DEF\\nD=BAR\\n\\nF=BAR\\n\");\n\n let testfile2 = testdir.create_testfile(\"2.env\", \"abc=DEF\\n\\nF=BAR\\n\");\n\n let testfile3 = testdir.create_testfile(\"3.env\", \"A=b \\nab=DEF\\n\\n\");\n\n\n\n let expected_output = String::from(\n\n \"Fixed warnings:\\n\\\n\n 2.env:1 LowercaseKey: The abc key should be in uppercase\\n\\\n\n 3.env:1 TrailingWhitespace: Trailing whitespace detected\\n\\\n\n 3.env:2 LowercaseKey: The ab key should be in uppercase\\n\\\n\n \\n\\\n\n Unfixed warnings:\\n\\\n\n 3.env:4 ExtraBlankLine: Extra blank line detected\\n\",\n\n );\n\n testdir.test_command_fix_fail(expected_output);\n\n\n\n assert_eq!(testfile1.contents().as_str(), \"AB=DEF\\nD=BAR\\n\\nF=BAR\\n\");\n\n assert_eq!(testfile2.contents().as_str(), \"ABC=DEF\\n\\nF=BAR\\n\");\n\n assert_eq!(testfile3.contents().as_str(), \"A=b\\nAB=DEF\\n\\n\");\n\n\n\n testdir.close();\n\n}\n", "file_path": "tests/fixes/mod.rs", "rank": 7, "score": 174608.87673002656 }, { "content": "#[test]\n\nfn key_without_value() {\n\n let testdir = TestDir::new();\n\n let testfile = testdir.create_testfile(\".env\", \"FOO\\n\\nBAR=\\n\\nBAZ=QUX\\n\");\n\n let expected_output = String::from(\n\n \"Fixed warnings:\\n\\\n\n .env:1 KeyWithoutValue: The FOO key should be with a value or have an equal sign\\n\",\n\n );\n\n testdir.test_command_fix_success(expected_output);\n\n\n\n assert_eq!(testfile.contents().as_str(), \"FOO=\\n\\nBAR=\\n\\nBAZ=QUX\\n\");\n\n\n\n testdir.close();\n\n}\n\n\n", "file_path": "tests/fixes/mod.rs", "rank": 8, "score": 168043.80988036483 }, { "content": "pub fn available_check_names() -> Vec<String> {\n\n checklist()\n\n .iter()\n\n .map(|check| check.name().to_string())\n\n .collect()\n\n}\n\n\n", "file_path": "src/checks.rs", "rank": 9, "score": 157085.33004449407 }, { "content": "#[allow(clippy::redundant_closure)]\n\npub fn run(args: &clap::ArgMatches, current_dir: &PathBuf) -> Result<Vec<Warning>, Box<dyn Error>> {\n\n let mut file_paths: Vec<PathBuf> = Vec::new();\n\n let mut skip_checks: Vec<&str> = Vec::new();\n\n let mut excluded_paths: Vec<PathBuf> = Vec::new();\n\n\n\n let is_recursive = args.is_present(\"recursive\");\n\n\n\n if let Some(skip) = args.values_of(\"skip\") {\n\n skip_checks = skip.collect();\n\n }\n\n\n\n if let Some(excluded) = args.values_of(\"exclude\") {\n\n excluded_paths = excluded\n\n .filter_map(|f| fs_utils::canonicalize(f).ok())\n\n .collect();\n\n }\n\n\n\n if let Some(inputs) = args.values_of(\"input\") {\n\n let input_paths = inputs\n\n .filter_map(|s| fs_utils::canonicalize(s).ok())\n", "file_path": "src/lib.rs", "rank": 10, "score": 151794.52968669118 }, { "content": "fn get_line_entries(fe: &FileEntry, lines: Vec<String>) -> Vec<LineEntry> {\n\n let mut entries: Vec<LineEntry> = Vec::with_capacity(fe.total_lines);\n\n\n\n for (index, line) in lines.into_iter().enumerate() {\n\n entries.push(LineEntry {\n\n number: index + 1,\n\n file: fe.clone(),\n\n raw_string: line,\n\n })\n\n }\n\n\n\n entries\n\n}\n", "file_path": "src/lib.rs", "rank": 11, "score": 144748.96244230264 }, { "content": "/// Returns the relative path for `target_path` relative to `base_path`\n\npub fn get_relative_path(target_path: &PathBuf, base_path: &PathBuf) -> Option<PathBuf> {\n\n let comp_target: Vec<_> = target_path.components().collect();\n\n let comp_base: Vec<_> = base_path.components().collect();\n\n\n\n let mut i = 0;\n\n for (b, t) in comp_base.iter().zip(comp_target.iter()) {\n\n if b != t {\n\n break;\n\n }\n\n i += 1;\n\n }\n\n\n\n let mut relative_path = PathBuf::new();\n\n\n\n for _ in 0..(comp_base.len() - i) {\n\n relative_path.push(\"..\");\n\n }\n\n relative_path.extend(comp_target.get(i..)?);\n\n\n\n Some(relative_path)\n\n}\n\n\n", "file_path": "src/fs_utils.rs", "rank": 12, "score": 139261.1966945178 }, { "content": "#[test]\n\nfn exclude_two_files() {\n\n let test_dir = TestDir::new();\n\n let testfile_1 = test_dir.create_testfile(\".env\", \" FOO=\\n\");\n\n let testfile_2 = test_dir.create_testfile(\".loacl.env\", \" BAR=\\n\");\n\n\n\n test_dir.test_command_success_with_args(&[\n\n \"-e\",\n\n testfile_1.as_str(),\n\n \"-e\",\n\n testfile_2.as_str(),\n\n ]);\n\n}\n\n\n", "file_path": "tests/options/exclude.rs", "rank": 13, "score": 138800.32975634045 }, { "content": "#[test]\n\nfn exclude_one_file() {\n\n let test_dir = TestDir::new();\n\n let testfile = test_dir.create_testfile(\".env\", \" FOO=\\n\");\n\n test_dir.test_command_success_with_args(&[\"--exclude\", testfile.as_str()]);\n\n}\n\n\n", "file_path": "tests/options/exclude.rs", "rank": 14, "score": 138800.32975634045 }, { "content": "#[test]\n\nfn ending_blank_line() {\n\n let testdir = TestDir::new();\n\n let testfile = testdir.create_testfile(\".env\", \"ABC=DEF\\nFOO=BAR\");\n\n let expected_output = String::from(\n\n \"Fixed warnings:\\n\\\n\n .env:2 EndingBlankLine: No blank line at the end of the file\\n\",\n\n );\n\n testdir.test_command_fix_success(expected_output);\n\n\n\n assert_eq!(testfile.contents().as_str(), \"ABC=DEF\\nFOO=BAR\\n\");\n\n\n\n testdir.close();\n\n}\n", "file_path": "tests/fixes/ending_blank_line.rs", "rank": 15, "score": 138282.65747538724 }, { "content": "#[test]\n\nfn exclude_one_file_check_one_file() {\n\n let test_dir = TestDir::new();\n\n let testfile_to_check = test_dir.create_testfile(\".env\", \" FOO=\\n\");\n\n let testfile_to_exclude = test_dir.create_testfile(\".exclude-me.env\", \" BAR=\\n\");\n\n\n\n let args = &[\"--exclude\", testfile_to_exclude.as_str()];\n\n let expected_output = format!(\n\n \"{}:1 LeadingCharacter: Invalid leading character detected\\n\\nFound 1 problem\\n\",\n\n testfile_to_check.shortname_as_str()\n\n );\n\n\n\n test_dir.test_command_fail_with_args(args, expected_output);\n\n}\n", "file_path": "tests/options/exclude.rs", "rank": 16, "score": 136265.62854983204 }, { "content": "#[test]\n\nfn correct_files() {\n\n let contents = vec![\n\n \"A=B\\nF=BAR\\n\\nFOO=BAR\\n\",\n\n \"A=B\\r\\nF=BAR\\r\\n\\r\\nFOO=BAR\\r\\n\",\n\n \"\\n# comment\\n\\nABC=DEF\\n\",\n\n ];\n\n\n\n for content in contents {\n\n let testdir = TestDir::new();\n\n let testfile = testdir.create_testfile(\".env\", content);\n\n let args = &[testfile.as_str()];\n\n\n\n testdir.test_command_success_with_args(args);\n\n }\n\n}\n\n\n", "file_path": "tests/checks/extra_blank_line.rs", "rank": 17, "score": 133713.34845925934 }, { "content": "#[test]\n\nfn incorrect_files() {\n\n let contents = vec![\n\n \"ABC=DEF\\nD=BAR\\nFOO=BAR\",\n\n \"C=D\\r\\nK=L\\r\\nX=Y\",\n\n \"A=B\",\n\n \"# Comment 1\\n# Comment 2\\n# Comment 3\",\n\n ];\n\n let expected_line_numbers = vec![3, 3, 1, 3];\n\n\n\n for (i, content) in contents.iter().enumerate() {\n\n let testdir = TestDir::new();\n\n let testfile = testdir.create_testfile(\".env\", content);\n\n let args = &[testfile.as_str()];\n\n let expected_output = format!(\n\n \"{}:{} EndingBlankLine: No blank line at the end of the file\\n\\nFound 1 problem\\n\",\n\n testfile.shortname_as_str(),\n\n expected_line_numbers[i]\n\n );\n\n\n\n testdir.test_command_fail_with_args(args, expected_output);\n\n }\n\n}\n", "file_path": "tests/checks/ending_blank_line.rs", "rank": 18, "score": 133713.34845925937 }, { "content": "#[test]\n\nfn correct_files() {\n\n let contents = vec![\n\n \"A=B\\nF=BAR\\nFOO=BAR\\n\",\n\n \"A=B\\r\\nF=BAR\\r\\nFOO=BAR\\r\\n\",\n\n \"# comment\\nABC=DEF\\n\",\n\n ];\n\n\n\n for content in contents {\n\n let testdir = TestDir::new();\n\n let testfile = testdir.create_testfile(\".env\", content);\n\n let args = &[testfile.as_str()];\n\n\n\n testdir.test_command_success_with_args(args);\n\n }\n\n}\n\n\n", "file_path": "tests/checks/ending_blank_line.rs", "rank": 19, "score": 133713.34845925937 }, { "content": "#[test]\n\nfn checks_one_specific_file_and_one_path() {\n\n let testdir = TestDir::new();\n\n testdir.create_testfile(\".env\", \"foo=\");\n\n let testfile_2 = testdir.create_testfile(\"test-env-file\", \"FOO=BAR\\nBAR=FOO\\n\");\n\n\n\n let subdir = testdir.subdir();\n\n let testfile_3 = subdir.create_testfile(\"test.env\", \"FOO=BAR\\nFOO=BAR\\n\");\n\n\n\n let args = &[testfile_2.as_str(), subdir.as_str()];\n\n let expected_output = format!(\n\n \"{}:2 UnorderedKey: The BAR key should go before the FOO key\\n{}:2 DuplicatedKey: The FOO key is duplicated\\n\\nFound 2 problems\\n\",\n\n testfile_2.shortname_as_str(),\n\n Path::new(&testdir.relative_path(&subdir))\n\n .join(testfile_3.shortname_as_str())\n\n .to_str().expect(\"multi-platform path to test .env file\"),\n\n );\n\n\n\n testdir.test_command_fail_with_args(args, expected_output);\n\n}\n\n\n", "file_path": "tests/args/specific_path.rs", "rank": 20, "score": 132830.57445029358 }, { "content": "#[test]\n\nfn checks_one_specific_file() {\n\n let test_dir = TestDir::new();\n\n test_dir.create_testfile(\".env\", \"foo=\\n\");\n\n let testfile_2 = test_dir.create_testfile(\"test-env-file\", \"FOO =\\n\");\n\n\n\n let args = &[testfile_2.as_str()];\n\n let expected_output = format!(\n\n \"{}:1 SpaceCharacter: The line has spaces around equal sign\\n\\nFound 1 problem\\n\",\n\n testfile_2.shortname_as_str()\n\n );\n\n\n\n test_dir.test_command_fail_with_args(args, expected_output);\n\n}\n\n\n", "file_path": "tests/args/specific_path.rs", "rank": 21, "score": 130432.50197138556 }, { "content": "#[test]\n\nfn checks_two_specific_files() {\n\n let testdir = TestDir::new();\n\n testdir.create_testfile(\".env\", \"foo=\");\n\n let testfile_2 = testdir.create_testfile(\"test-env-file\", \"FOO =\\n\");\n\n\n\n let subdir = testdir.subdir();\n\n let testfile_3 = subdir.create_testfile(\"another_test_file\", \"FOO=BAR\\nFOO=BAR\\n\");\n\n\n\n let args = &[testfile_2.as_str(), testfile_3.as_str()];\n\n let expected_output = format!(\n\n \"{}:2 DuplicatedKey: The FOO key is duplicated\\n{}:1 SpaceCharacter: The line has spaces around equal sign\\n\\nFound 2 problems\\n\",\n\n Path::new(&testdir.relative_path(&subdir))\n\n .join(testfile_3.shortname_as_str())\n\n .to_str().expect(\"multi-platform path to test .env file\"),\n\n testfile_2.shortname_as_str(),\n\n );\n\n\n\n testdir.test_command_fail_with_args(args, expected_output);\n\n}\n\n\n", "file_path": "tests/args/specific_path.rs", "rank": 22, "score": 130432.50197138556 }, { "content": "#[test]\n\nfn checks_one_specific_file_twice() {\n\n let test_dir = TestDir::new();\n\n test_dir.create_testfile(\".env\", \"foo=\");\n\n let testfile_2 = test_dir.create_testfile(\"test-env-file\", \"1FOO=\\n\");\n\n\n\n let args = &[testfile_2.as_str(), testfile_2.as_str()];\n\n let expected_output = format!(\n\n \"{}:1 LeadingCharacter: Invalid leading character detected\\n\\nFound 1 problem\\n\",\n\n testfile_2.shortname_as_str()\n\n );\n\n\n\n test_dir.test_command_fail_with_args(args, expected_output);\n\n}\n", "file_path": "tests/args/specific_path.rs", "rank": 23, "score": 126697.69742909273 }, { "content": "pub fn remove_invalid_leading_chars(string: &str) -> String {\n\n string\n\n .chars()\n\n .skip_while(|&c| !(c.is_alphabetic() || c == '_'))\n\n .collect()\n\n}\n\n\n", "file_path": "src/common.rs", "rank": 25, "score": 118888.04419122054 }, { "content": "fn get_file_paths(\n\n dir_entries: Vec<PathBuf>,\n\n excludes: &[PathBuf],\n\n is_recursive: bool,\n\n) -> Vec<PathBuf> {\n\n let nested_paths: Vec<PathBuf> = dir_entries\n\n .iter()\n\n .filter(|entry| entry.is_dir())\n\n .filter(|entry| !excludes.contains(entry))\n\n .filter_map(|dir| dir.read_dir().ok())\n\n .map(|read_dir| {\n\n read_dir\n\n .filter_map(|e| e.ok())\n\n .map(|e| e.path())\n\n .filter(|path| FileEntry::is_env_file(path) || (is_recursive && path.is_dir()))\n\n .collect()\n\n })\n\n .flat_map(|dir_entries| get_file_paths(dir_entries, excludes, is_recursive))\n\n .collect();\n\n\n", "file_path": "src/lib.rs", "rank": 26, "score": 111880.81367185828 }, { "content": "#[test]\n\nfn checks_two_specific_paths() {\n\n let testdir = TestDir::new();\n\n testdir.create_testfile(\".env\", \"foo=\\n\");\n\n\n\n let subdir_1 = testdir.subdir();\n\n let testfile_2 = subdir_1.create_testfile(\".env\", \" FOO=\\n\");\n\n\n\n let subdir_2 = subdir_1.subdir();\n\n let testfile_3 = subdir_2.create_testfile(\".env\", \" FOO=\\n\");\n\n\n\n let args = &[subdir_1.as_str(), subdir_2.as_str()];\n\n let expected_output = format!(\n\n \"{}:1 LeadingCharacter: Invalid leading character detected\\n{}:1 LeadingCharacter: Invalid leading character detected\\n\\nFound 2 problems\\n\",\n\n Path::new(&testdir.relative_path(&subdir_1))\n\n .join(testfile_2.shortname_as_str())\n\n .to_str().expect(\"multi-platform path to test .env file\"),\n\n Path::new(&testdir.relative_path(&subdir_2))\n\n .join(testfile_3.shortname_as_str())\n\n .to_str().expect(\"multi-platform path to test .env file\"),\n\n );\n\n\n\n testdir.test_command_fail_with_args(args, expected_output);\n\n}\n\n\n", "file_path": "tests/args/specific_path.rs", "rank": 27, "score": 110916.87040246681 }, { "content": "#[test]\n\nfn checks_one_specific_path() {\n\n let testdir = TestDir::new();\n\n testdir.create_testfile(\".env\", \"foo=\\n\");\n\n\n\n let subdir = testdir.subdir();\n\n let testfile_2 = subdir.create_testfile(\".env.test\", \"1FOO=\\n\");\n\n\n\n let args = &[subdir.as_str()];\n\n let expected_output = format!(\n\n \"{}:1 LeadingCharacter: Invalid leading character detected\\n\\nFound 1 problem\\n\",\n\n Path::new(&testdir.relative_path(&subdir))\n\n .join(testfile_2.shortname_as_str())\n\n .to_str()\n\n .expect(\"multi-platform path to test .env file\")\n\n );\n\n\n\n testdir.test_command_fail_with_args(args, expected_output);\n\n}\n\n\n", "file_path": "tests/args/specific_path.rs", "rank": 28, "score": 110916.87040246681 }, { "content": "#[test]\n\nfn exits_with_0_on_no_warnings() {\n\n let test_dir = TestDir::new();\n\n test_dir.create_testfile(\".env\", \"FOO=bar\\n\");\n\n test_dir.test_command_success();\n\n}\n\n\n", "file_path": "tests/args/current_dir.rs", "rank": 29, "score": 107703.19972802594 }, { "content": "#[test]\n\nfn two_blank_lines_in_the_middle() {\n\n let content = \"ABC=DEF\\nD=BAR\\n\\n\\nFOO=BAR\\n\";\n\n\n\n let testdir = TestDir::new();\n\n let testfile = testdir.create_testfile(\".env\", content);\n\n let args = &[testfile.as_str()];\n\n let expected_output = format!(\n\n \"{}:{} ExtraBlankLine: Extra blank line detected\\n\\nFound 1 problem\\n\",\n\n testfile.shortname_as_str(),\n\n 4\n\n );\n\n\n\n testdir.test_command_fail_with_args(args, expected_output);\n\n}\n\n\n", "file_path": "tests/checks/extra_blank_line.rs", "rank": 30, "score": 107338.30223778376 }, { "content": "#[test]\n\nfn two_blank_lines_at_the_beginning() {\n\n let content = \"\\n\\nABC=DEF\\nD=BAR\\nFOO=BAR\\n\";\n\n\n\n let testdir = TestDir::new();\n\n let testfile = testdir.create_testfile(\".env\", content);\n\n let args = &[testfile.as_str()];\n\n let expected_output = format!(\n\n \"{}:{} ExtraBlankLine: Extra blank line detected\\n\\nFound 1 problem\\n\",\n\n testfile.shortname_as_str(),\n\n 2\n\n );\n\n\n\n testdir.test_command_fail_with_args(args, expected_output);\n\n}\n\n\n", "file_path": "tests/checks/extra_blank_line.rs", "rank": 31, "score": 107338.30223778376 }, { "content": "#[test]\n\nfn two_blank_lines_at_the_end() {\n\n let content = \"ABC=DEF\\nD=BAR\\nFOO=BAR\\n\\n\";\n\n\n\n let testdir = TestDir::new();\n\n let testfile = testdir.create_testfile(\".env\", content);\n\n let args = &[testfile.as_str()];\n\n let expected_output = format!(\n\n \"{}:{} ExtraBlankLine: Extra blank line detected\\n\\nFound 1 problem\\n\",\n\n testfile.shortname_as_str(),\n\n 5\n\n );\n\n\n\n testdir.test_command_fail_with_args(args, expected_output);\n\n}\n", "file_path": "tests/checks/extra_blank_line.rs", "rank": 32, "score": 107338.30223778376 }, { "content": "#[test]\n\nfn trailing_whitespace() {\n\n let testdir = TestDir::new();\n\n let testfile = testdir.create_testfile(\".env\", \"ABC=DEF \\n\\nFOO=BAR \\n\");\n\n let expected_output = String::from(\n\n \"Fixed warnings:\\n\\\n\n .env:1 TrailingWhitespace: Trailing whitespace detected\\n\\\n\n .env:3 TrailingWhitespace: Trailing whitespace detected\\n\",\n\n );\n\n testdir.test_command_fix_success(expected_output);\n\n\n\n assert_eq!(testfile.contents().as_str(), \"ABC=DEF\\n\\nFOO=BAR\\n\");\n\n\n\n testdir.close();\n\n}\n", "file_path": "tests/fixes/trailing_whitespace.rs", "rank": 33, "score": 106736.65892221834 }, { "content": "#[test]\n\nfn quote_character() {\n\n let testdir = TestDir::new();\n\n let testfile = testdir.create_testfile(\".env\", \"ABC=\\\"DEF\\\"\\n\\nFOO=\\'B\\\"AR\\'\\n\");\n\n let expected_output = String::from(\n\n \"Fixed warnings:\\n\\\n\n .env:1 QuoteCharacter: The value has quote characters (\\', \\\")\\n\\\n\n .env:3 QuoteCharacter: The value has quote characters (\\', \\\")\\n\",\n\n );\n\n testdir.test_command_fix_success(expected_output);\n\n\n\n assert_eq!(testfile.contents().as_str(), \"ABC=DEF\\n\\nFOO=BAR\\n\");\n\n\n\n testdir.close();\n\n}\n", "file_path": "tests/fixes/quote_character.rs", "rank": 34, "score": 106736.65892221834 }, { "content": "#[test]\n\nfn space_character() {\n\n let testdir = TestDir::new();\n\n let testfile = testdir.create_testfile(\".env\", \"ABC = DEF\\n\\nFOO= BAR\\n\");\n\n let expected_output = String::from(\n\n \"Fixed warnings:\\n\\\n\n .env:1 SpaceCharacter: The line has spaces around equal sign\\n\\\n\n .env:3 SpaceCharacter: The line has spaces around equal sign\\n\",\n\n );\n\n testdir.test_command_fix_success(expected_output);\n\n\n\n assert_eq!(testfile.contents().as_str(), \"ABC=DEF\\n\\nFOO=BAR\\n\");\n\n\n\n testdir.close();\n\n}\n", "file_path": "tests/fixes/space_character.rs", "rank": 35, "score": 106736.65892221834 }, { "content": "#[test]\n\nfn checks_files_in_deep_subdirs() {\n\n let test_dir = TestDir::new();\n\n test_dir.create_testfile(\"correct.env\", \"FOO=BAR\\n\");\n\n\n\n let test_subdir_2 = test_dir.subdir();\n\n let testfile_2 = test_subdir_2.create_testfile(\"incorrect.sub_1.env\", \"FOO=BAR\\nBAR=FOO\\n\");\n\n\n\n let test_subdir_3 = test_subdir_2.subdir();\n\n let testfile_3 = test_subdir_3.create_testfile(\".incorrect.env\", \"FOO=\");\n\n\n\n let args = &[\"--recursive\"];\n\n let expected_output = format!(\n\n \"{}:2 UnorderedKey: The BAR key should go before the FOO key\\n{}:1 EndingBlankLine: No blank line at the end of the file\\n\\nFound 2 problems\\n\",\n\n Path::new(&test_dir.relative_path(&test_subdir_2))\n\n .join(testfile_2.shortname_as_str())\n\n .to_str()\n\n .expect(\"multi-platform path to test .env file\"),\n\n Path::new(&test_dir.relative_path(&test_subdir_3))\n\n .join(testfile_3.shortname_as_str())\n\n .to_str()\n\n .expect(\"multi-platform path to test .env file\")\n\n );\n\n\n\n test_dir.test_command_fail_with_args(args, expected_output);\n\n}\n\n\n", "file_path": "tests/flags/recursive.rs", "rank": 36, "score": 104266.85934371926 }, { "content": "mod exclude;\n", "file_path": "tests/options/mod.rs", "rank": 37, "score": 103975.18667743792 }, { "content": "mod quote_character;\n\n\n\nuse crate::common::TestDir;\n\n\n\nmod ending_blank_line;\n\nmod space_character;\n\nmod trailing_whitespace;\n\n\n\n#[test]\n", "file_path": "tests/fixes/mod.rs", "rank": 38, "score": 102841.11388378526 }, { "content": "use crate::common::TestDir;\n\n\n\n#[test]\n", "file_path": "tests/fixes/ending_blank_line.rs", "rank": 39, "score": 94533.4285137353 }, { "content": "fn get_args(current_dir: &OsStr) -> clap::ArgMatches {\n\n clap::App::new(env!(\"CARGO_PKG_NAME\"))\n\n .about(env!(\"CARGO_PKG_DESCRIPTION\"))\n\n .author(env!(\"CARGO_PKG_AUTHORS\"))\n\n .version(env!(\"CARGO_PKG_VERSION\"))\n\n .version_short(\"v\")\n\n .arg(\n\n Arg::with_name(\"input\")\n\n .help(\"files or paths\")\n\n .index(1)\n\n .default_value_os(current_dir)\n\n .required(true)\n\n .multiple(true),\n\n )\n\n .arg(\n\n Arg::with_name(\"exclude\")\n\n .short(\"e\")\n\n .long(\"exclude\")\n\n .value_name(\"FILE_NAME\")\n\n .help(\"Excludes files from check\")\n", "file_path": "src/main.rs", "rank": 40, "score": 88836.69772615742 }, { "content": "// Checklist for checks which needs to know of only a single line\n\nfn checklist() -> Vec<Box<dyn Check>> {\n\n vec![\n\n Box::new(duplicated_key::DuplicatedKeyChecker::default()),\n\n Box::new(ending_blank_line::EndingBlankLineChecker::default()),\n\n Box::new(extra_blank_line::ExtraBlankLineChecker::default()),\n\n Box::new(incorrect_delimiter::IncorrectDelimiterChecker::default()),\n\n Box::new(leading_character::LeadingCharacterChecker::default()),\n\n Box::new(key_without_value::KeyWithoutValueChecker::default()),\n\n Box::new(lowercase_key::LowercaseKeyChecker::default()),\n\n Box::new(quote_character::QuoteCharacterChecker::default()),\n\n Box::new(space_character::SpaceCharacterChecker::default()),\n\n Box::new(trailing_whitespace::TrailingWhitespaceChecker::default()),\n\n Box::new(unordered_key::UnorderedKeyChecker::default()),\n\n ]\n\n}\n\n\n", "file_path": "src/checks.rs", "rank": 41, "score": 83056.47165956532 }, { "content": "#[test]\n\nfn output_without_total() {\n\n let test_dir = TestDir::new();\n\n let testfile_to_check = test_dir.create_testfile(\".env\", \" BAR='Baz'\\n\");\n\n\n\n let args = &[\"--quiet\"];\n\n let expected_output = format!(\n\n \"{a}:1 LeadingCharacter: Invalid leading character detected\\n{a}:1 QuoteCharacter: The value has quote characters (\\', \\\")\\n\",\n\n a=testfile_to_check.shortname_as_str()\n\n );\n\n\n\n test_dir.test_command_fail_with_args(args, expected_output);\n\n}\n", "file_path": "tests/flags/quiet.rs", "rank": 42, "score": 76419.81729152259 }, { "content": "#[test]\n\nfn checks_one_in_subdir() {\n\n let test_dir = TestDir::new();\n\n test_dir.create_testfile(\"correct.env\", \"FOO=BAR\\n\");\n\n let test_subdir = test_dir.subdir();\n\n let testfile_2 = test_subdir.create_testfile(\".incorrect.env\", \"1BAR=\\n\");\n\n\n\n let args = &[\"-r\"];\n\n let expected_output = format!(\n\n \"{}:1 LeadingCharacter: Invalid leading character detected\\n\\nFound 1 problem\\n\",\n\n Path::new(&test_dir.relative_path(&test_subdir))\n\n .join(testfile_2.shortname_as_str())\n\n .to_str()\n\n .expect(\"multi-platform path to test .env file\")\n\n );\n\n\n\n test_dir.test_command_fail_with_args(args, expected_output);\n\n}\n\n\n", "file_path": "tests/flags/recursive.rs", "rank": 43, "score": 76419.81729152259 }, { "content": "#[test]\n\nfn checks_current_dir() {\n\n let testdir = TestDir::new();\n\n let testfile = testdir.create_testfile(\".env\", \"FOO\\n\");\n\n\n\n testdir.test_command_fail(\n\n format!(\n\n \"{}:1 KeyWithoutValue: The FOO key should be with a value or have an equal sign\\n\\nFound 1 problem\\n\",\n\n testfile.shortname_as_str()\n\n )\n\n );\n\n}\n\n\n", "file_path": "tests/args/current_dir.rs", "rank": 44, "score": 74303.72632516392 }, { "content": "#[test]\n\nfn checks_recursive_with_exclude_subdir() {\n\n let test_dir = TestDir::new();\n\n test_dir.create_testfile(\"correct.env\", \"FOO=BAR\\n\");\n\n\n\n let test_subdir_2 = test_dir.subdir();\n\n let testfile_2 = test_subdir_2.create_testfile(\"incorrect.sub_1.env\", \"FOO=BAR\\nBAR=FOO\\n\");\n\n\n\n let test_subdir_3 = test_subdir_2.subdir();\n\n let testfile_to_exclude = test_subdir_3.create_testfile(\".incorrect.env\", \"FOO=\");\n\n\n\n let args = &[\"--exclude\", testfile_to_exclude.as_str(), \"--recursive\"];\n\n let expected_output = format!(\n\n \"{}:2 UnorderedKey: The BAR key should go before the FOO key\\n\\nFound 1 problem\\n\",\n\n Path::new(&test_dir.relative_path(&test_subdir_2))\n\n .join(testfile_2.shortname_as_str())\n\n .to_str()\n\n .expect(\"multi-platform path to test .env file\"),\n\n );\n\n\n\n test_dir.test_command_fail_with_args(args, expected_output);\n\n}\n", "file_path": "tests/flags/recursive.rs", "rank": 45, "score": 74303.72632516392 }, { "content": "#[test]\n\nfn checks_without_recursive_flag() {\n\n let test_dir = TestDir::new();\n\n test_dir.create_testfile(\"correct.env\", \"FOO=BAR\\n\");\n\n let test_subdir = test_dir.subdir();\n\n test_subdir.create_testfile(\".incorrect.env\", \"1BAR=\\n\");\n\n\n\n // incorrect file located in a subdirectory should not be checked\n\n test_dir.test_command_success();\n\n}\n\n\n", "file_path": "tests/flags/recursive.rs", "rank": 46, "score": 74303.72632516392 }, { "content": "#[test]\n\nfn remove_invalid_leading_chars_test() {\n\n let string = String::from(\"-1&*FOO\");\n\n assert_eq!(\"FOO\", remove_invalid_leading_chars(&string));\n\n\n\n let string = String::from(\"***FOO-BAR\");\n\n assert_eq!(\"FOO-BAR\", remove_invalid_leading_chars(&string));\n\n}\n", "file_path": "src/common.rs", "rank": 47, "score": 74303.72632516392 }, { "content": "fn print_total(total: usize) {\n\n let mut problems = String::from(\"problem\");\n\n\n\n if total > 1 {\n\n problems += \"s\";\n\n }\n\n\n\n println!(\"\\n{}\", format!(\"Found {} {}\", total, problems));\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 48, "score": 73940.5364243457 }, { "content": "#[test]\n\nfn checks_current_dir_with_dot_arg() {\n\n let testdir = TestDir::new();\n\n let testfile = testdir.create_testfile(\"test.env\", \"foo=\\n\");\n\n\n\n let args = &[\".\"];\n\n let expected_output = format!(\n\n \"{}:1 LowercaseKey: The foo key should be in uppercase\\n\\nFound 1 problem\\n\",\n\n testfile.shortname_as_str(),\n\n );\n\n\n\n testdir.test_command_fail_with_args(args, expected_output);\n\n}\n", "file_path": "tests/args/current_dir.rs", "rank": 49, "score": 70484.39821908093 }, { "content": "use crate::common::TestDir;\n\n\n\n#[test]\n", "file_path": "tests/options/exclude.rs", "rank": 50, "score": 69110.61139044068 }, { "content": "\n\n fn init_cmd() -> Command {\n\n Command::cargo_bin(env!(\"CARGO_PKG_NAME\")).expect(\"command from binary name\")\n\n }\n\n}\n\n\n\n/// Use as a temporary file to act on in a TestDir\n\npub struct TestFile {\n\n file_path: PathBuf,\n\n}\n\n\n\nimpl TestFile {\n\n /// Create a new file and write its contents\n\n pub fn new(test_dir: &TempDir, name: &str, contents: &str) -> Self {\n\n let file_path = test_dir.path().join(name);\n\n let mut file = File::create(&file_path).expect(\"create testfile\");\n\n file.write_all(contents.as_bytes()).expect(\"write to file\");\n\n\n\n Self { file_path }\n\n }\n", "file_path": "tests/common/mod.rs", "rank": 51, "score": 68865.91943028726 }, { "content": " subdir\n\n .current_dir\n\n .path()\n\n .strip_prefix(self.current_dir.path())\n\n .expect(\"strip dir from subdir path\")\n\n .to_string_lossy()\n\n .to_string()\n\n }\n\n\n\n /// Create a TestFile within the TestDir\n\n pub fn create_testfile(&self, name: &str, contents: &str) -> TestFile {\n\n TestFile::new(&self.current_dir, name, contents)\n\n }\n\n\n\n /// Get full path of TestDir as a &str\n\n pub fn as_str(&self) -> &str {\n\n self.current_dir\n\n .path()\n\n .to_str()\n\n .expect(\"convert directory to &str\")\n", "file_path": "tests/common/mod.rs", "rank": 52, "score": 68857.85355527402 }, { "content": "use assert_cmd::Command;\n\nuse std::ffi::OsStr;\n\nuse std::fs::{self, File};\n\nuse std::io::Write;\n\nuse std::path::PathBuf;\n\nuse tempfile::{tempdir, tempdir_in, TempDir};\n\n\n\n#[cfg(windows)]\n\nuse dunce::canonicalize;\n\n\n\n#[cfg(not(windows))]\n\nuse std::fs::canonicalize;\n\n\n\n/// Use to test commands in temporary directories\n\npub struct TestDir {\n\n current_dir: TempDir,\n\n}\n\n\n\nimpl TestDir {\n\n /// Generate a new TestDir\n", "file_path": "tests/common/mod.rs", "rank": 53, "score": 68856.23641018898 }, { "content": "\n\n /// Get full path of TestFile on filesystem as &str\n\n pub fn as_str(&self) -> &str {\n\n self.file_path.to_str().expect(\"convert testfile to &str\")\n\n }\n\n\n\n /// Get the filename (short path) as &str\n\n pub fn shortname_as_str(&self) -> &str {\n\n self.file_path\n\n .file_name()\n\n .expect(\"get shortname\")\n\n .to_str()\n\n .expect(\"convert shortname to &str\")\n\n }\n\n\n\n /// Get file contents\n\n pub fn contents(&self) -> String {\n\n String::from_utf8_lossy(&fs::read(self.as_str()).expect(\"read file\")).into_owned()\n\n }\n\n}\n", "file_path": "tests/common/mod.rs", "rank": 54, "score": 68854.7307150357 }, { "content": " /// This method removes the TestDir when command has finished.\n\n pub fn test_command_fail_with_args<I, S>(self, args: I, expected_output: String)\n\n where\n\n I: IntoIterator<Item = S>,\n\n S: AsRef<OsStr>,\n\n {\n\n let mut cmd = Self::init_cmd();\n\n let canonical_current_dir = canonicalize(&self.current_dir).expect(\"canonical current dir\");\n\n cmd.current_dir(&canonical_current_dir)\n\n .args(args)\n\n .assert()\n\n .failure()\n\n .code(1)\n\n .stdout(expected_output);\n\n\n\n self.close();\n\n }\n\n\n\n /// Run the default CLI binary, with \"-f\", in this TestDir and check it succeeds.\n\n pub fn test_command_fix_success(&self, expected_output: String) {\n", "file_path": "tests/common/mod.rs", "rank": 55, "score": 68850.9845774771 }, { "content": " pub fn new() -> Self {\n\n Self {\n\n current_dir: tempdir().expect(\"create testdir\"),\n\n }\n\n }\n\n\n\n /// Create a new TestDir within an existing one\n\n pub fn subdir(&self) -> Self {\n\n Self {\n\n current_dir: tempdir_in(&self.current_dir).expect(\"create subdir\"),\n\n }\n\n }\n\n\n\n /// Explicitly panic if unable to remove TestDir from filesystem\n\n pub fn close(self) {\n\n self.current_dir.close().expect(\"remove testdir\");\n\n }\n\n\n\n /// Get relative path between TestDir and a subdirectory TestDir\n\n pub fn relative_path(&self, subdir: &Self) -> String {\n", "file_path": "tests/common/mod.rs", "rank": 56, "score": 68850.68979912002 }, { "content": " ///\n\n /// This method removes the TestDir when command has finished.\n\n pub fn test_command_success_with_args<I, S>(self, args: I)\n\n where\n\n I: IntoIterator<Item = S>,\n\n S: AsRef<OsStr>,\n\n {\n\n let mut cmd = Self::init_cmd();\n\n let canonical_current_dir = canonicalize(&self.current_dir).expect(\"canonical current dir\");\n\n cmd.current_dir(&canonical_current_dir)\n\n .args(args)\n\n .assert()\n\n .success();\n\n\n\n self.close();\n\n }\n\n\n\n /// Run the default CLI binary, with command line arguments,\n\n /// in this TestDir and check it fails.\n\n ///\n", "file_path": "tests/common/mod.rs", "rank": 57, "score": 68850.47578159542 }, { "content": " let mut cmd = Self::init_cmd();\n\n let canonical_current_dir = canonicalize(&self.current_dir).expect(\"canonical current dir\");\n\n cmd.current_dir(&canonical_current_dir)\n\n .args(&[\"-f\"])\n\n .assert()\n\n .success()\n\n .stdout(expected_output);\n\n }\n\n\n\n /// Run the default CLI binary, with \"-f\", in this TestDir and check it fails.\n\n pub fn test_command_fix_fail(&self, expected_output: String) {\n\n let mut cmd = Self::init_cmd();\n\n let canonical_current_dir = canonicalize(&self.current_dir).expect(\"canonical current dir\");\n\n cmd.current_dir(&canonical_current_dir)\n\n .args(&[\"-f\"])\n\n .assert()\n\n .failure()\n\n .code(1)\n\n .stdout(expected_output);\n\n }\n", "file_path": "tests/common/mod.rs", "rank": 58, "score": 68848.7733157412 }, { "content": " }\n\n\n\n /// Run the default CLI binary in this TestDir and check it succeeds.\n\n ///\n\n /// This method removes the TestDir when command has finished.\n\n pub fn test_command_success(self) {\n\n let args: &[&str; 0] = &[];\n\n self.test_command_success_with_args(args);\n\n }\n\n\n\n /// Run the default CLI binary in this TestDir and check it fails.\n\n ///\n\n /// This method removes the TestDir when command has finished.\n\n pub fn test_command_fail(self, expected_output: String) {\n\n let args: &[&str; 0] = &[];\n\n self.test_command_fail_with_args(args, expected_output);\n\n }\n\n\n\n /// Run the default CLI binary, with command line arguments,\n\n /// in this TestDir and check it succeeds.\n", "file_path": "tests/common/mod.rs", "rank": 59, "score": 68847.85352234484 }, { "content": "mod ending_blank_line;\n\nmod extra_blank_line;\n", "file_path": "tests/checks/mod.rs", "rank": 60, "score": 68843.62665994112 }, { "content": "mod current_dir;\n\nmod specific_path;\n", "file_path": "tests/args/mod.rs", "rank": 61, "score": 68843.46307982004 }, { "content": "mod quiet;\n\nmod recursive;\n", "file_path": "tests/flags/mod.rs", "rank": 62, "score": 68839.93315402482 }, { "content": "use crate::common::TestDir;\n\nuse std::path::Path;\n\n\n\n#[test]\n", "file_path": "tests/args/specific_path.rs", "rank": 63, "score": 66333.99415956465 }, { "content": "use crate::common::TestDir;\n\n\n\n#[test]\n", "file_path": "tests/fixes/quote_character.rs", "rank": 64, "score": 65327.1456570207 }, { "content": "use crate::common::TestDir;\n\n\n\n#[test]\n", "file_path": "tests/fixes/space_character.rs", "rank": 65, "score": 65327.1456570207 }, { "content": "use crate::common::TestDir;\n\n\n\n#[test]\n", "file_path": "tests/fixes/trailing_whitespace.rs", "rank": 66, "score": 65327.1456570207 }, { "content": "use super::Fix;\n\nuse crate::common::*;\n\n\n\npub(crate) struct LowercaseKeyFixer<'a> {\n\n name: &'a str,\n\n}\n\n\n\nimpl Default for LowercaseKeyFixer<'_> {\n\n fn default() -> Self {\n\n Self {\n\n name: \"LowercaseKey\",\n\n }\n\n }\n\n}\n\n\n\nimpl Fix for LowercaseKeyFixer<'_> {\n\n fn name(&self) -> &str {\n\n self.name\n\n }\n\n\n", "file_path": "src/fixes/lowercase_key.rs", "rank": 67, "score": 65263.7006580456 }, { "content": " fn fix_line(&self, line: &mut LineEntry) -> Option<()> {\n\n let key = line.get_key()?;\n\n let key = key.to_uppercase();\n\n line.raw_string = format!(\"{}={}\", key, line.get_value()?);\n\n\n\n Some(())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::path::PathBuf;\n\n\n\n #[test]\n\n fn fix_line_test() {\n\n let fixer = LowercaseKeyFixer::default();\n\n let mut line = LineEntry {\n\n number: 1,\n\n file: FileEntry {\n", "file_path": "src/fixes/lowercase_key.rs", "rank": 68, "score": 65263.3150650013 }, { "content": " path: PathBuf::from(\".env\"),\n\n file_name: \".env\".to_string(),\n\n total_lines: 1,\n\n },\n\n raw_string: String::from(\"foO=BAR\"),\n\n };\n\n assert_eq!(Some(()), fixer.fix_line(&mut line));\n\n assert_eq!(\"FOO=BAR\", line.raw_string);\n\n }\n\n\n\n #[test]\n\n fn fix_warnings_test() {\n\n let fixer = LowercaseKeyFixer::default();\n\n let mut lines = vec![\n\n LineEntry {\n\n number: 1,\n\n file: FileEntry {\n\n path: PathBuf::from(\".env\"),\n\n file_name: \".env\".to_string(),\n\n total_lines: 3,\n", "file_path": "src/fixes/lowercase_key.rs", "rank": 69, "score": 65256.639992448974 }, { "content": " },\n\n ];\n\n let mut warning = Warning::new(\n\n lines[0].clone(),\n\n \"LowercaseKey\",\n\n String::from(\"The FOO key should be in uppercase\"),\n\n );\n\n\n\n assert_eq!(Some(1), fixer.fix_warnings(vec![&mut warning], &mut lines));\n\n assert_eq!(\"FOO=BAR\", lines[0].raw_string);\n\n assert!(warning.is_fixed);\n\n }\n\n}\n", "file_path": "src/fixes/lowercase_key.rs", "rank": 70, "score": 65247.52285483658 }, { "content": " },\n\n raw_string: String::from(\"foO=BAR\"),\n\n },\n\n LineEntry {\n\n number: 2,\n\n file: FileEntry {\n\n path: PathBuf::from(\".env\"),\n\n file_name: \".env\".to_string(),\n\n total_lines: 3,\n\n },\n\n raw_string: String::from(\"Z=Y\"),\n\n },\n\n LineEntry {\n\n number: 3,\n\n file: FileEntry {\n\n path: PathBuf::from(\".env\"),\n\n file_name: \".env\".to_string(),\n\n total_lines: 3,\n\n },\n\n raw_string: String::from(\"\\n\"),\n", "file_path": "src/fixes/lowercase_key.rs", "rank": 71, "score": 65242.70845843175 }, { "content": " }\n\n\n\n Some(0)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::path::PathBuf;\n\n\n\n #[test]\n\n fn fix_warnings_test() {\n\n let fixer = EndingBlankLineFixer::default();\n\n let mut lines = vec![\n\n LineEntry {\n\n number: 1,\n\n file: FileEntry {\n\n path: PathBuf::from(\".env\"),\n\n file_name: \".env\".to_string(),\n", "file_path": "src/fixes/ending_blank_line.rs", "rank": 72, "score": 63138.23525149328 }, { "content": "use super::Fix;\n\nuse crate::common::*;\n\n\n\npub(crate) struct EndingBlankLineFixer<'a> {\n\n name: &'a str,\n\n}\n\n\n\nimpl Default for EndingBlankLineFixer<'_> {\n\n fn default() -> Self {\n\n Self {\n\n name: \"EndingBlankLine\",\n\n }\n\n }\n\n}\n\n\n\nimpl Fix for EndingBlankLineFixer<'_> {\n\n fn name(&self) -> &str {\n\n self.name\n\n }\n\n\n", "file_path": "src/fixes/ending_blank_line.rs", "rank": 73, "score": 63134.97172306282 }, { "content": " assert_eq!(Some(1), fixer.fix_warnings(vec![&mut warning], &mut lines));\n\n assert_eq!(\"\\n\", lines[2].raw_string);\n\n assert!(warning.is_fixed);\n\n }\n\n\n\n #[test]\n\n fn ending_blank_line_exist_test() {\n\n let fixer = EndingBlankLineFixer::default();\n\n let mut lines = vec![\n\n LineEntry {\n\n number: 1,\n\n file: FileEntry {\n\n path: PathBuf::from(\".env\"),\n\n file_name: \".env\".to_string(),\n\n total_lines: 2,\n\n },\n\n raw_string: String::from(\"FOO=BAR\"),\n\n },\n\n LineEntry {\n\n number: 2,\n", "file_path": "src/fixes/ending_blank_line.rs", "rank": 74, "score": 63131.64085536878 }, { "content": " fn fix_warnings(\n\n &self,\n\n warnings: Vec<&mut Warning>,\n\n lines: &mut Vec<LineEntry>,\n\n ) -> Option<usize> {\n\n let file = lines.first()?.file.clone();\n\n let last_line = lines.last()?;\n\n\n\n if !last_line.raw_string.ends_with(LF) {\n\n lines.push(LineEntry {\n\n number: lines.len() + 1,\n\n file,\n\n raw_string: LF.to_string(),\n\n });\n\n\n\n for warning in warnings {\n\n warning.mark_as_fixed()\n\n }\n\n\n\n return Some(1);\n", "file_path": "src/fixes/ending_blank_line.rs", "rank": 75, "score": 63124.73281450901 }, { "content": " file: FileEntry {\n\n path: PathBuf::from(\".env\"),\n\n file_name: \".env\".to_string(),\n\n total_lines: 2,\n\n },\n\n raw_string: String::from(LF),\n\n },\n\n ];\n\n\n\n assert_eq!(Some(0), fixer.fix_warnings(vec![], &mut lines));\n\n assert_eq!(lines.len(), 2);\n\n }\n\n}\n", "file_path": "src/fixes/ending_blank_line.rs", "rank": 76, "score": 63119.98869479191 }, { "content": " total_lines: 2,\n\n },\n\n raw_string: String::from(\"FOO=BAR\"),\n\n },\n\n LineEntry {\n\n number: 2,\n\n file: FileEntry {\n\n path: PathBuf::from(\".env\"),\n\n file_name: \".env\".to_string(),\n\n total_lines: 2,\n\n },\n\n raw_string: String::from(\"Z=Y\"),\n\n },\n\n ];\n\n let mut warning = Warning::new(\n\n lines[1].clone(),\n\n \"EndingBlankLine\",\n\n String::from(\"No blank line at the end of the file\"),\n\n );\n\n\n", "file_path": "src/fixes/ending_blank_line.rs", "rank": 77, "score": 63119.12886195012 }, { "content": "use crate::common::TestDir;\n\n\n\n#[test]\n", "file_path": "tests/checks/ending_blank_line.rs", "rank": 78, "score": 63083.3794403388 }, { "content": "use crate::common::TestDir;\n\n\n\n#[test]\n", "file_path": "tests/checks/extra_blank_line.rs", "rank": 79, "score": 63083.3794403388 }, { "content": " fn fix_line(&self, line: &mut LineEntry) -> Option<()> {\n\n line.raw_string.push('=');\n\n\n\n Some(())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::path::PathBuf;\n\n\n\n #[test]\n\n fn fix_line_test() {\n\n let fixer = KeyWithoutValueFixer::default();\n\n let mut line = LineEntry {\n\n number: 1,\n\n file: FileEntry {\n\n path: PathBuf::from(\".env\"),\n\n file_name: \".env\".to_string(),\n", "file_path": "src/fixes/key_without_value.rs", "rank": 80, "score": 62826.69915816811 }, { "content": "use super::Fix;\n\nuse crate::common::*;\n\n\n\npub(crate) struct KeyWithoutValueFixer<'a> {\n\n name: &'a str,\n\n}\n\n\n\nimpl Default for KeyWithoutValueFixer<'_> {\n\n fn default() -> Self {\n\n Self {\n\n name: \"KeyWithoutValue\",\n\n }\n\n }\n\n}\n\n\n\nimpl Fix for KeyWithoutValueFixer<'_> {\n\n fn name(&self) -> &str {\n\n self.name\n\n }\n\n\n", "file_path": "src/fixes/key_without_value.rs", "rank": 81, "score": 62824.802103920905 }, { "content": " total_lines: 1,\n\n },\n\n raw_string: String::from(\"FOO\"),\n\n };\n\n assert_eq!(Some(()), fixer.fix_line(&mut line));\n\n assert_eq!(\"FOO=\", line.raw_string);\n\n }\n\n\n\n #[test]\n\n fn fix_warnings_test() {\n\n let fixer = KeyWithoutValueFixer::default();\n\n let mut lines = vec![\n\n LineEntry {\n\n number: 1,\n\n file: FileEntry {\n\n path: PathBuf::from(\".env\"),\n\n file_name: \".env\".to_string(),\n\n total_lines: 3,\n\n },\n\n raw_string: String::from(\"FOO\"),\n", "file_path": "src/fixes/key_without_value.rs", "rank": 82, "score": 62818.14771497109 }, { "content": " let mut warning = Warning::new(\n\n lines[0].clone(),\n\n \"KeyWithoutValue\",\n\n String::from(\"The FOO key should be with a value or have an equal sign\"),\n\n );\n\n\n\n assert_eq!(Some(1), fixer.fix_warnings(vec![&mut warning], &mut lines));\n\n assert_eq!(\"FOO=\", lines[0].raw_string);\n\n assert!(warning.is_fixed);\n\n }\n\n}\n", "file_path": "src/fixes/key_without_value.rs", "rank": 83, "score": 62809.232513360665 }, { "content": " },\n\n LineEntry {\n\n number: 2,\n\n file: FileEntry {\n\n path: PathBuf::from(\".env\"),\n\n file_name: \".env\".to_string(),\n\n total_lines: 3,\n\n },\n\n raw_string: String::from(\"Z=Y\"),\n\n },\n\n LineEntry {\n\n number: 3,\n\n file: FileEntry {\n\n path: PathBuf::from(\".env\"),\n\n file_name: \".env\".to_string(),\n\n total_lines: 3,\n\n },\n\n raw_string: String::from(\"\\n\"),\n\n },\n\n ];\n", "file_path": "src/fixes/key_without_value.rs", "rank": 84, "score": 62805.15692392663 }, { "content": "// This trait is used for checks which needs to know of only a single line\n\ntrait Check {\n\n fn run(&mut self, line: &LineEntry) -> Option<Warning>;\n\n fn name(&self) -> &str;\n\n fn skip_comments(&self) -> bool {\n\n true\n\n }\n\n}\n\n\n", "file_path": "src/checks.rs", "rank": 85, "score": 57562.75489655691 }, { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n let current_dir = env::current_dir()?;\n\n let args = get_args(current_dir.as_os_str());\n\n\n\n if args.is_present(\"show-checks\") {\n\n dotenv_linter::available_check_names()\n\n .iter()\n\n .for_each(|name| println!(\"{}\", name));\n\n process::exit(0);\n\n }\n\n\n\n let is_fix = args.is_present(\"fix\");\n\n\n\n let warnings = dotenv_linter::run(&args, &current_dir)?;\n\n\n\n if warnings.is_empty() {\n\n process::exit(0);\n\n }\n\n\n\n if is_fix {\n", "file_path": "src/main.rs", "rank": 86, "score": 39221.815706512425 }, { "content": "mod args;\n\nmod checks;\n\nmod common;\n\nmod fixes;\n\nmod flags;\n\nmod options;\n", "file_path": "tests/cli.rs", "rank": 96, "score": 35405.814445055395 }, { "content": " \"{}:{} {}: {}\",\n\n self.line.file, self.line.number, self.check_name, self.message\n\n )\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::path::PathBuf;\n\n\n\n #[test]\n\n fn warning_fmt_test() {\n\n let line = LineEntry {\n\n number: 1,\n\n file: FileEntry {\n\n path: PathBuf::from(\".env\"),\n\n file_name: \".env\".to_string(),\n\n total_lines: 1,\n\n },\n", "file_path": "src/common/warning.rs", "rank": 97, "score": 35108.23715626925 }, { "content": " }\n\n }\n\n\n\n pub fn line_number(&self) -> usize {\n\n self.line.number\n\n }\n\n\n\n pub fn mark_as_fixed(&mut self) {\n\n self.is_fixed = true;\n\n }\n\n\n\n pub fn mark_as_unfixed(&mut self) {\n\n self.is_fixed = false;\n\n }\n\n}\n\n\n\nimpl fmt::Display for Warning {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(\n\n f,\n", "file_path": "src/common/warning.rs", "rank": 98, "score": 35107.47037716739 }, { "content": "use std::fmt;\n\n\n\nuse crate::common::*;\n\n\n\n#[derive(Clone, Debug, PartialEq)]\n\npub struct Warning {\n\n pub check_name: String,\n\n line: LineEntry,\n\n message: String,\n\n pub is_fixed: bool,\n\n}\n\n\n\nimpl Warning {\n\n pub fn new(line: LineEntry, check_name: &str, message: String) -> Self {\n\n let check_name = String::from(check_name);\n\n Self {\n\n line,\n\n check_name,\n\n message,\n\n is_fixed: false,\n", "file_path": "src/common/warning.rs", "rank": 99, "score": 35106.136038697165 } ]
Rust
core/src/util.rs
kruton/SEGIMAP
7e9e68fecd5e2ad22862ec02c5f1a2be9f35269b
use regex::Regex; use std::env::current_dir; use std::fs; use std::path::Path; use std::path::PathBuf; use walkdir::WalkDir; use crate::folder::Folder; #[macro_export] macro_rules! path_filename_to_str( ($p:ident) => ({ use std::ffi::OsStr; $p.file_name().unwrap_or_else(|| OsStr::new("")).to_str().unwrap_or_else(|| "") }); ); fn make_absolute(dir: &Path) -> String { match current_dir() { Err(_) => dir.display().to_string(), Ok(absp) => { let mut abs_path = absp.clone(); abs_path.push(dir); abs_path.display().to_string() } } } pub fn perform_select( maildir: &str, select_args: &[&str], examine: bool, tag: &str, ) -> (Option<Folder>, String) { let err_res = (None, "".to_string()); if select_args.len() < 1 { return err_res; } let mbox_name = select_args[0].trim_matches('"').replace("INBOX", "."); let mut maildir_path = PathBuf::new(); maildir_path.push(maildir); maildir_path.push(mbox_name); let folder = match Folder::new(maildir_path, examine) { None => { return err_res; } Some(folder) => folder.clone(), }; let ok_res = folder.select_response(tag); (Some(folder), ok_res) } fn list_dir(dir: &Path, regex: &Regex, maildir_path: &Path) -> Option<String> { let dir_string = dir.display().to_string(); let dir_name = path_filename_to_str!(dir); if dir_name == "cur" || dir_name == "new" || dir_name == "tmp" { return None; } let abs_dir = make_absolute(dir); let mut flags = match fs::read_dir(&dir.join("cur")) { Err(_) => "\\Noselect".to_string(), _ => { match fs::read_dir(&dir.join("new")) { Err(_) => "\\Noselect".to_string(), Ok(newlisting) => { if newlisting.count() == 0 { "\\Unmarked".to_string() } else { "\\Marked".to_string() } } } } }; match fs::read_dir(&dir) { Err(_) => { return None; } Ok(dir_listing) => { let mut children = false; for subdir_entry in dir_listing { if let Ok(subdir) = subdir_entry { if *dir == *maildir_path { break; } let subdir_path = subdir.path(); let subdir_str = path_filename_to_str!(subdir_path); if subdir_str != "cur" && subdir_str != "new" && subdir_str != "tmp" { if fs::read_dir(&subdir.path().join("cur")).is_err() { continue; } if fs::read_dir(&subdir.path().join("new")).is_err() { continue; } children = true; break; } } } if children { flags.push_str(" \\HasChildren"); } else { flags.push_str(" \\HasNoChildren"); } } } let re_path = make_absolute(maildir_path); match fs::metadata(dir) { Err(_) => return None, Ok(md) => { if !md.is_dir() { return None; } } }; if !regex.is_match(&dir_string[..]) { return None; } let mut list_str = "* LIST (".to_string(); list_str.push_str(&flags[..]); list_str.push_str(") \"/\" "); let list_dir_string = if abs_dir.starts_with(&re_path[..]) { abs_dir.replacen(&re_path[..], "", 1) } else { abs_dir }; list_str.push_str(&(list_dir_string.replace("INBOX", ""))[..]); Some(list_str) } pub fn list(maildir: &str, regex: &Regex) -> Vec<String> { let maildir_path = Path::new(maildir); let mut responses = Vec::new(); if let Some(list_response) = list_dir(maildir_path, regex, maildir_path) { responses.push(list_response); } for dir_res in WalkDir::new(&maildir_path) { if let Ok(dir) = dir_res { if let Some(list_response) = list_dir(dir.path(), regex, maildir_path) { responses.push(list_response); } } } responses }
use regex::Regex; use std::env::current_dir; use std::fs; use std::path::Path; use std::path::PathBuf; use walkdir::WalkDir; use crate::folder::Folder; #[macro_export] macro_rules! path_filename_to_str( ($p:ident) => ({ use std::ffi::OsStr; $p.file_name().unwrap_or_else(|| OsStr::new("")).to_str().unwrap_or_else(|| "") }); ); fn make_absolute(dir: &Path) -> String { match current_dir() { Err(_) => dir.display().to_string(), Ok(absp) => { let mut abs_path = absp.clone(); abs_path.push(dir); abs_path.display().to_string() } } } pub fn perform_select( maildir: &str,
r); let mut flags = match fs::read_dir(&dir.join("cur")) { Err(_) => "\\Noselect".to_string(), _ => { match fs::read_dir(&dir.join("new")) { Err(_) => "\\Noselect".to_string(), Ok(newlisting) => { if newlisting.count() == 0 { "\\Unmarked".to_string() } else { "\\Marked".to_string() } } } } }; match fs::read_dir(&dir) { Err(_) => { return None; } Ok(dir_listing) => { let mut children = false; for subdir_entry in dir_listing { if let Ok(subdir) = subdir_entry { if *dir == *maildir_path { break; } let subdir_path = subdir.path(); let subdir_str = path_filename_to_str!(subdir_path); if subdir_str != "cur" && subdir_str != "new" && subdir_str != "tmp" { if fs::read_dir(&subdir.path().join("cur")).is_err() { continue; } if fs::read_dir(&subdir.path().join("new")).is_err() { continue; } children = true; break; } } } if children { flags.push_str(" \\HasChildren"); } else { flags.push_str(" \\HasNoChildren"); } } } let re_path = make_absolute(maildir_path); match fs::metadata(dir) { Err(_) => return None, Ok(md) => { if !md.is_dir() { return None; } } }; if !regex.is_match(&dir_string[..]) { return None; } let mut list_str = "* LIST (".to_string(); list_str.push_str(&flags[..]); list_str.push_str(") \"/\" "); let list_dir_string = if abs_dir.starts_with(&re_path[..]) { abs_dir.replacen(&re_path[..], "", 1) } else { abs_dir }; list_str.push_str(&(list_dir_string.replace("INBOX", ""))[..]); Some(list_str) } pub fn list(maildir: &str, regex: &Regex) -> Vec<String> { let maildir_path = Path::new(maildir); let mut responses = Vec::new(); if let Some(list_response) = list_dir(maildir_path, regex, maildir_path) { responses.push(list_response); } for dir_res in WalkDir::new(&maildir_path) { if let Ok(dir) = dir_res { if let Some(list_response) = list_dir(dir.path(), regex, maildir_path) { responses.push(list_response); } } } responses }
select_args: &[&str], examine: bool, tag: &str, ) -> (Option<Folder>, String) { let err_res = (None, "".to_string()); if select_args.len() < 1 { return err_res; } let mbox_name = select_args[0].trim_matches('"').replace("INBOX", "."); let mut maildir_path = PathBuf::new(); maildir_path.push(maildir); maildir_path.push(mbox_name); let folder = match Folder::new(maildir_path, examine) { None => { return err_res; } Some(folder) => folder.clone(), }; let ok_res = folder.select_response(tag); (Some(folder), ok_res) } fn list_dir(dir: &Path, regex: &Regex, maildir_path: &Path) -> Option<String> { let dir_string = dir.display().to_string(); let dir_name = path_filename_to_str!(dir); if dir_name == "cur" || dir_name == "new" || dir_name == "tmp" { return None; } let abs_dir = make_absolute(di
random
[ { "content": "/// Parse and perform the store operation specified by `store_args`. Returns the\n\n/// response to the client or None if a BAD response should be sent back to\n\n/// the client\n\npub fn store(folder: &mut Folder, store_args: &[&str], seq_uid: bool, tag: &str) -> Option<String> {\n\n if store_args.len() < 3 {\n\n return None;\n\n }\n\n\n\n // Parse the sequence set argument\n\n let sequence_set_opt = sequence_set::parse(store_args[0].trim_matches('\"'));\n\n // Grab how to handle the flags. It should be case insensitive.\n\n let data_name = store_args[1].trim_matches('\"').to_ascii_lowercase();\n\n\n\n // Split into \"flag\" part and \"silent\" part.\n\n let mut data_name_parts = (&data_name[..]).split('.');\n\n let flag_part = data_name_parts.next();\n\n let silent_part = data_name_parts.next();\n\n\n\n // There shouldn't be any more parts to the data name argument\n\n if data_name_parts.next().is_some() {\n\n return None;\n\n }\n\n\n", "file_path": "core/src/command/store.rs", "rank": 1, "score": 172655.79344536812 }, { "content": "/// Reads a JSON file and turns it into a `HashMap` of emails to users.\n\n/// May throw an `std::io::Error`, hence the `Result<>` type.\n\npub fn load_users(path_str: &str) -> ImapResult<HashMap<Email, User>> {\n\n let path = Path::new(&path_str[..]);\n\n\n\n let users = match File::open(&path) {\n\n Ok(mut file) => {\n\n let mut file_buf: String = String::new();\n\n file.read_to_string(&mut file_buf)?;\n\n serde_json::from_str(&file_buf)?\n\n }\n\n Err(e) => {\n\n warn!(\"Failed to open users file, creating default: {}\", e);\n\n create_default_users(&path)?\n\n }\n\n };\n\n\n\n let mut map = HashMap::<Email, User>::new();\n\n for user in users {\n\n map.insert(user.email.clone(), user);\n\n }\n\n\n\n Ok(map)\n\n}\n\n\n", "file_path": "core/src/server/user/mod.rs", "rank": 3, "score": 131725.49913843535 }, { "content": "/// Given a string as passed in from the client, create a list of sequence items\n\n/// If the string does not represent a valid list, return None\n\npub fn parse(sequence_string: &str) -> Option<Vec<SequenceItem>> {\n\n let sequences = sequence_string.split(',');\n\n let mut sequence_set = Vec::new();\n\n for sequence in sequences {\n\n let mut range = sequence.split(':');\n\n let start = match range.next() {\n\n None => return None,\n\n Some(seq) => match parse_item(seq) {\n\n None => return None,\n\n Some(item) => item,\n\n },\n\n };\n\n let stop = match range.next() {\n\n None => {\n\n // Nothing after ':'\n\n // Add the number or wildcard and bail out\n\n sequence_set.push(start);\n\n continue;\n\n }\n\n Some(seq) => match parse_item(seq) {\n", "file_path": "core/src/command/sequence_set.rs", "rank": 4, "score": 131504.31379202352 }, { "content": "/// Writes a list of users to a new file on the disk.\n\npub fn save_users(path: &Path, users: &[User]) -> ImapResult<()> {\n\n let encoded = serde_json::to_string(&users)?;\n\n\n\n let mut file = File::create(&path)?;\n\n file.write(encoded.as_bytes())?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "core/src/server/user/mod.rs", "rank": 6, "score": 124367.14001897915 }, { "content": "/// Takes a flag argument and returns the corresponding enum.\n\npub fn parse_flag(flag: &str) -> Option<Flag> {\n\n match flag {\n\n \"\\\\Deleted\" => Some(Flag::Deleted),\n\n \"\\\\Seen\" => Some(Flag::Seen),\n\n \"\\\\Draft\" => Some(Flag::Draft),\n\n \"\\\\Answered\" => Some(Flag::Answered),\n\n \"\\\\Flagged\" => Some(Flag::Flagged),\n\n _ => None,\n\n }\n\n}\n\n\n\n/// Representation of a Message\n\n#[derive(Debug, Clone)]\n\npub struct Message {\n\n // a unique id (timestamp) for the message\n\n uid: usize,\n\n\n\n // filename\n\n path: PathBuf,\n\n\n", "file_path": "core/src/message.rs", "rank": 7, "score": 118807.34395038549 }, { "content": "/// Take the rest of the arguments provided by the client and parse them into a\n\n/// `FetchCommand` object with `parser::fetch`.\n\npub fn fetch(args: Vec<&str>) -> ParserResult<FetchCommand> {\n\n let mut cmd = \"FETCH\".to_string();\n\n for arg in args {\n\n cmd.push(' ');\n\n cmd.push_str(arg);\n\n }\n\n\n\n parser::fetch(cmd.as_bytes())\n\n}\n\n\n", "file_path": "core/src/command/fetch.rs", "rank": 9, "score": 110073.9421727498 }, { "content": "pub fn serve(serv: Arc<Server>, mut stream: BufStream<TcpStream>) {\n\n let mut l = Lmtp {\n\n rev_path: None,\n\n to_path: Vec::new(),\n\n data: String::new(),\n\n quit: false,\n\n };\n\n return_on_err!(stream.write(format!(\"220 {} LMTP server ready\\r\\n\", *serv.host()).as_bytes()));\n\n return_on_err!(stream.flush());\n\n loop {\n\n let mut command = String::new();\n\n match stream.read_line(&mut command) {\n\n Ok(_) => {\n\n if command.is_empty() {\n\n return;\n\n }\n\n let trimmed_command = (&command[..]).trim();\n\n let mut args = trimmed_command.split(' ');\n\n let invalid = \"500 Invalid command\\r\\n\".to_string();\n\n let data_res = b\"354 Start mail input; end with <CRLF>.<CRLF>\\r\\n\";\n", "file_path": "core/src/server/lmtp.rs", "rank": 10, "score": 103302.48012242152 }, { "content": "/// Perform the fetch operation on each sequence number indicated and return\n\n/// the response to be sent back to the client.\n\npub fn fetch_loop(\n\n parsed_cmd: &FetchCommand,\n\n folder: &mut Folder,\n\n sequence_iter: &[usize],\n\n tag: &str,\n\n uid: bool,\n\n) -> String {\n\n for attr in &parsed_cmd.attributes {\n\n if let BodySection(_, _) = *attr {\n\n let mut seen_flag_set = HashSet::new();\n\n seen_flag_set.insert(Seen);\n\n folder.store(\n\n sequence_iter.to_vec(),\n\n &Add,\n\n true,\n\n seen_flag_set,\n\n false,\n\n tag,\n\n );\n\n break;\n", "file_path": "core/src/command/fetch.rs", "rank": 11, "score": 87552.26192698072 }, { "content": "/// Function to create an example users JSON file at the specified path.\n\n///\n\n/// Returns the list of example users.\n\nfn create_default_users(path: &Path) -> ImapResult<Vec<User>> {\n\n let users = vec![\n\n User::new(\n\n Email::new(\"will\".to_string(), \"xqz.ca\".to_string()),\n\n \"54321\".to_string(),\n\n \"./maildir\".to_string(),\n\n ),\n\n User::new(\n\n Email::new(\"nikitapekin\".to_string(), \"gmail.com\".to_string()),\n\n \"12345\".to_string(),\n\n \"./maildir\".to_string(),\n\n ),\n\n ];\n\n\n\n save_users(path, &users)?;\n\n\n\n Ok(users)\n\n}\n", "file_path": "core/src/server/user/mod.rs", "rank": 12, "score": 86813.52789540804 }, { "content": "/// This moves a list of messages from folder/new/ to folder/cur/ and returns a\n\n/// new list of messages\n\nfn move_new(messages: &[Message], path: &Path, start_index: usize) -> Vec<Message> {\n\n let mut new_messages = Vec::new();\n\n\n\n // Go over the messages by index\n\n for (i, msg) in messages.iter().enumerate() {\n\n // messages before start_index are already in folder/cur/\n\n if i + 1 < start_index {\n\n new_messages.push(msg.clone());\n\n continue;\n\n }\n\n let curpath = path.join(\"cur\").join(msg.get_uid().to_string());\n\n rename_message!(msg, curpath, new_messages);\n\n }\n\n\n\n // Return the new list of messages\n\n new_messages\n\n}\n", "file_path": "core/src/folder.rs", "rank": 13, "score": 83223.04383241442 }, { "content": "fn parse_item(item: &str) -> Option<SequenceItem> {\n\n if let Ok(intseq) = item.parse() {\n\n Some(Number(intseq))\n\n } else if item == \"*\" {\n\n // item is not a valid number\n\n // If it is the wildcard value return that\n\n // Otherwise, return no sequence item\n\n Some(Wildcard)\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "core/src/command/sequence_set.rs", "rank": 14, "score": 74735.59798608409 }, { "content": "fn grab_email(arg: Option<&str>) -> Option<Email> {\n\n let from_path_split = match arg {\n\n Some(full_from_path) => {\n\n let mut split_arg = full_from_path.split(':');\n\n match split_arg.next() {\n\n Some(from_str) => match &from_str.to_ascii_lowercase()[..] {\n\n \"from\" | \"to\" => {\n\n grab_email_token!(split_arg.next())\n\n }\n\n _ => {\n\n return None;\n\n }\n\n },\n\n _ => {\n\n return None;\n\n }\n\n }\n\n }\n\n _ => {\n\n return None;\n", "file_path": "core/src/server/lmtp.rs", "rank": 15, "score": 74696.64143306736 }, { "content": "/// Takes the argument specifying what to do with the provided flags in a store\n\n/// operation and returns the corresponding enum.\n\nfn parse_storename(storename: Option<&str>) -> Option<StoreName> {\n\n match storename {\n\n Some(\"flags\") => Some(Replace),\n\n Some(\"+flags\") => Some(Add),\n\n Some(\"-flags\") => Some(Sub),\n\n _ => None,\n\n }\n\n}\n", "file_path": "core/src/command/store.rs", "rank": 16, "score": 73254.45650290004 }, { "content": "pub fn fetch(input: &[u8]) -> ParserResult<FetchCommand> {\n\n use nom::IResult::{Done, Error, Incomplete};\n\n\n\n match self::grammar::fetch(input) {\n\n Done(_, v) => Ok(v),\n\n Incomplete(_) => Err(ParserError::Incomplete),\n\n Error(err) => Err(err).map_err(ParserError::from),\n\n }\n\n}\n", "file_path": "core/src/parser/mod.rs", "rank": 17, "score": 72386.61040590914 }, { "content": "pub fn uid_iterator(sequence_set: &[SequenceItem]) -> Vec<usize> {\n\n let mut items = Vec::new();\n\n for item in sequence_set.iter() {\n\n match *item {\n\n Number(num) => items.push(num),\n\n Range(ref a, ref b) => {\n\n let a = match **a {\n\n Number(num) => num,\n\n Wildcard => return Vec::new(),\n\n Range(_, _) => {\n\n error!(\"A range of ranges is invalid.\");\n\n continue;\n\n }\n\n };\n\n let b = match **b {\n\n Number(num) => num,\n\n Wildcard => return Vec::new(),\n\n Range(_, _) => {\n\n error!(\"A range of ranges is invalid.\");\n\n continue;\n", "file_path": "core/src/command/sequence_set.rs", "rank": 18, "score": 69745.82299310195 }, { "content": "pub fn imap_serve(serv: Arc<Server>, stream: TcpStream) {\n\n let mut session = ImapSession::new(serv);\n\n session.handle(stream);\n\n}\n", "file_path": "core/src/server/mod.rs", "rank": 19, "score": 69745.27040243053 }, { "content": "pub fn lmtp_serve(serv: Arc<Server>, stream: TcpStream) {\n\n lmtp::serve(serv, BufStream::new(stream))\n\n}\n\n\n", "file_path": "core/src/server/mod.rs", "rank": 20, "score": 69745.27040243053 }, { "content": "/// Create the list of unsigned integers representing valid ids from a list of\n\n/// sequence items. Ideally this would handle wildcards in O(1) rather than O(n)\n\npub fn iterator(sequence_set: &[SequenceItem], max_id: usize) -> Vec<usize> {\n\n // If the number of possible messages is 0, we return an empty vec.\n\n if max_id == 0 {\n\n return Vec::new();\n\n }\n\n\n\n let stop = max_id + 1;\n\n\n\n let mut items = Vec::new();\n\n for item in sequence_set.iter() {\n\n match *item {\n\n // For a number we just need the value\n\n Number(num) => items.push(num),\n\n // For a range we need all the values inside it\n\n Range(ref a, ref b) => {\n\n // Grab the start of the range\n\n let a = match **a {\n\n Number(num) => num,\n\n Wildcard => max_id,\n\n Range(_, _) => {\n", "file_path": "core/src/command/sequence_set.rs", "rank": 21, "score": 64941.092282152254 }, { "content": "fn main() {\n\n env_logger::init();\n\n info!(\"Application started\");\n\n\n\n // Create the server. We wrap it so that it is atomically reference\n\n // counted. This allows us to safely share it across threads\n\n\n\n let serv = match Server::new() {\n\n Err(e) => {\n\n error!(\"Error starting server: {}\", e);\n\n return;\n\n }\n\n Ok(s) => Arc::new(s),\n\n };\n\n\n\n // Spawn a separate thread for listening for LMTP connections\n\n let lmtp_h = if let Some(lmtp_listener) = serv.lmtp_listener() {\n\n match lmtp_listener {\n\n Err(e) => {\n\n error!(\"Error listening on LMTP port: {}\", e);\n", "file_path": "core/src/main.rs", "rank": 22, "score": 41416.64409152838 }, { "content": "fn listen_generic(\n\n v: TcpListener,\n\n serv: Arc<Server>,\n\n prot: &str,\n\n serve_func: fn(Arc<Server>, TcpStream),\n\n) {\n\n for stream in v.incoming() {\n\n match stream {\n\n Err(e) => {\n\n error!(\"Error accepting incoming {} connection: {}\", prot, e);\n\n }\n\n Ok(stream) => {\n\n let session_serv = serv.clone();\n\n spawn(move || serve_func(session_serv, stream));\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "core/src/main.rs", "rank": 23, "score": 40294.06572405435 }, { "content": "#[test]\n\nfn test_sequence_num() {\n\n assert_eq!(iterator(&[Number(4324)], 5000), vec![4324]);\n\n assert_eq!(iterator(&[Number(23), Number(44)], 5000), vec![23, 44]);\n\n assert_eq!(\n\n iterator(&[Number(6), Number(6), Number(2)], 5000),\n\n vec![2, 6]\n\n );\n\n}\n\n\n", "file_path": "core/src/command/sequence_set.rs", "rank": 24, "score": 37366.820453850625 }, { "content": "#[test]\n\nfn test_sequence_range() {\n\n assert_eq!(\n\n iterator(&[Range(Box::new(Number(6)), Box::new(Wildcard))], 10),\n\n vec![6, 7, 8, 9, 10]\n\n );\n\n assert_eq!(\n\n iterator(&[Range(Box::new(Number(1)), Box::new(Number(10)))], 4),\n\n vec![1, 2, 3, 4]\n\n );\n\n assert_eq!(\n\n iterator(\n\n &[\n\n Range(Box::new(Wildcard), Box::new(Number(8))),\n\n Number(9),\n\n Number(2),\n\n Number(2)\n\n ],\n\n 12\n\n ),\n\n vec![2, 8, 9, 10, 11, 12]\n\n );\n\n}\n\n\n", "file_path": "core/src/command/sequence_set.rs", "rank": 25, "score": 37366.820453850625 }, { "content": "#[test]\n\nfn test_sequence_wildcard() {\n\n assert_eq!(\n\n iterator(\n\n &[Range(Box::new(Number(10)), Box::new(Wildcard)), Wildcard],\n\n 6\n\n ),\n\n vec![1, 2, 3, 4, 5, 6]\n\n );\n\n assert_eq!(iterator(&[Wildcard, Number(8)], 3), vec![1, 2, 3]);\n\n}\n\n\n", "file_path": "core/src/command/sequence_set.rs", "rank": 26, "score": 37366.820453850625 }, { "content": "#[test]\n\nfn test_sequence_complex() {\n\n assert_eq!(\n\n iterator(\n\n &[\n\n Number(1),\n\n Number(3),\n\n Range(Box::new(Number(5)), Box::new(Number(7))),\n\n Number(9),\n\n Number(12),\n\n Range(Box::new(Number(15)), Box::new(Wildcard))\n\n ],\n\n 13\n\n ),\n\n vec![1, 3, 5, 6, 7, 9, 12, 13]\n\n );\n\n}\n", "file_path": "core/src/command/sequence_set.rs", "rank": 27, "score": 37366.820453850625 }, { "content": "#[test]\n\nfn test_sequence_past_end() {\n\n // Needed to help rust infer the type for the empty vec.\n\n let empty_vec: Vec<usize> = Vec::new();\n\n\n\n assert_eq!(iterator(&[Number(4324)], 100), empty_vec);\n\n assert_eq!(iterator(&[Number(23), Number(44)], 30), vec![23]);\n\n assert_eq!(iterator(&[Number(6), Number(6), Number(2)], 4), vec![2]);\n\n}\n\n\n", "file_path": "core/src/command/sequence_set.rs", "rank": 28, "score": 36514.655947224994 }, { "content": "/// Generate a random salt using the cryptographically secure PRNG provided by\n\n/// the OS, for use with bcrypt hashing.\n\nfn gen_salt() -> Vec<u8> {\n\n let mut buf = [0u8; 16];\n\n match getrandom(&mut buf) {\n\n Ok(()) => (),\n\n Err(why) => panic!(\"{:?}\", why),\n\n };\n\n buf.to_vec()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::server::user::auth;\n\n\n\n #[test]\n\n fn test_valid_auth_data() {\n\n let auth_data = auth::AuthData::new(\"12345\".to_string());\n\n assert!(auth_data.verify_auth(\"12345\".to_string()));\n\n }\n\n\n\n #[test]\n\n fn test_invalid_auth_data() {\n\n let auth_data = auth::AuthData::new(\"12345\".to_string());\n\n assert!(!auth_data.verify_auth(\"54321\".to_string()));\n\n }\n\n}\n", "file_path": "core/src/server/user/auth.rs", "rank": 29, "score": 35102.035450796844 }, { "content": "fn is_ctl(chr: u8) -> bool {\n\n chr <= b'\\x1F' || chr == b'\\x7F'\n\n}\n\n\n", "file_path": "core/src/parser/grammar/mod.rs", "rank": 30, "score": 34524.636951322675 }, { "content": "fn is_dquote(chr: u8) -> bool {\n\n chr == b'\"'\n\n}\n\n\n", "file_path": "core/src/parser/grammar/mod.rs", "rank": 31, "score": 34524.636951322675 }, { "content": "// an ASCII digit (%x30-%x39)\n\nfn is_digit(chr: u8) -> bool {\n\n chr >= b'0' && chr <= b'9'\n\n}\n\n\n", "file_path": "core/src/parser/grammar/mod.rs", "rank": 32, "score": 34524.636951322675 }, { "content": "fn is_sp(chr: u8) -> bool {\n\n chr == b' '\n\n}\n\n\n", "file_path": "core/src/parser/grammar/mod.rs", "rank": 33, "score": 34524.636951322675 }, { "content": "fn is_list_wildcards(chr: u8) -> bool {\n\n chr == b'%' || chr == b'*'\n\n}\n\n\n", "file_path": "core/src/parser/grammar/mod.rs", "rank": 34, "score": 33724.781794053386 }, { "content": "// a CR or LF CHAR\n\nfn is_eol_char(chr: u8) -> bool {\n\n chr == b'\\r' || chr == b'\\n'\n\n}\n\n\n\n/* String parsing */\n\n\n\nnamed!(astring<&[u8], &[u8]>, alt!(take_while1!(is_astring_char) | string));\n\n\n\nnamed!(string<&[u8], &[u8]>, alt!(quoted | literal));\n\n\n\nnamed!(quoted<&[u8], &[u8]>,\n\n delimited!(\n\n tag!(\"\\\"\"),\n\n recognize!(\n\n many0!(\n\n alt!(\n\n take_while1!(is_quoted_char) |\n\n preceded!(tag!(\"\\\\\"), alt!(tag!(\"\\\"\") | tag!(\"\\\\\")))\n\n )\n\n )\n", "file_path": "core/src/parser/grammar/mod.rs", "rank": 35, "score": 33724.781794053386 }, { "content": "fn is_astring_char(chr: u8) -> bool {\n\n is_atom_char(chr) || is_resp_specials(chr)\n\n}\n\n\n", "file_path": "core/src/parser/grammar/mod.rs", "rank": 36, "score": 33724.781794053386 }, { "content": "fn is_resp_specials(chr: u8) -> bool {\n\n chr == b']'\n\n}\n\n\n", "file_path": "core/src/parser/grammar/mod.rs", "rank": 37, "score": 33724.781794053386 }, { "content": "// any CHAR except CR and LF\n\nfn is_text_char(chr: u8) -> bool {\n\n !is_eol_char(chr)\n\n}\n\n\n", "file_path": "core/src/parser/grammar/mod.rs", "rank": 38, "score": 33724.781794053386 }, { "content": "fn is_quoted_specials(chr: u8) -> bool {\n\n is_dquote(chr) || chr == b'\\\\'\n\n}\n\n\n", "file_path": "core/src/parser/grammar/mod.rs", "rank": 39, "score": 33724.781794053386 }, { "content": "fn is_atom_specials(chr: u8) -> bool {\n\n chr == b'('\n\n || chr == b')'\n\n || chr == b'{'\n\n || is_sp(chr)\n\n || is_ctl(chr)\n\n || is_list_wildcards(chr)\n\n || is_quoted_specials(chr)\n\n || is_resp_specials(chr)\n\n}\n\n\n", "file_path": "core/src/parser/grammar/mod.rs", "rank": 40, "score": 33724.781794053386 }, { "content": "// any CHAR except atom-specials\n\nfn is_atom_char(chr: u8) -> bool {\n\n !is_atom_specials(chr)\n\n}\n\n\n", "file_path": "core/src/parser/grammar/mod.rs", "rank": 41, "score": 33724.781794053386 }, { "content": "// any TEXT_CHAR except quoted_specials\n\nfn is_quoted_char(chr: u8) -> bool {\n\n !is_quoted_specials(chr) && is_text_char(chr)\n\n}\n\n\n", "file_path": "core/src/parser/grammar/mod.rs", "rank": 42, "score": 33724.781794053386 }, { "content": "fn listen_lmtp(v: TcpListener, serv: Arc<Server>) {\n\n listen_generic(v, serv, \"LMTP\", lmtp_serve);\n\n}\n\n\n", "file_path": "core/src/main.rs", "rank": 43, "score": 32771.61215752442 }, { "content": "fn listen_imap(v: TcpListener, serv: Arc<Server>) {\n\n listen_generic(v, serv, \"IMAP\", imap_serve);\n\n}\n\n\n", "file_path": "core/src/main.rs", "rank": 44, "score": 32771.61215752442 }, { "content": "\n\n let config = match File::open(&path) {\n\n Ok(mut file) => {\n\n let mut encoded: String = String::new();\n\n match file.read_to_string(&mut encoded) {\n\n Ok(_) => match toml::from_str(&encoded) {\n\n Ok(v) => v,\n\n Err(e) => {\n\n // Use default values if parsing failed.\n\n warn!(\"Failed to parse config.toml.\\nUsing default values: {}\", e);\n\n Config::default(&config_dir)\n\n }\n\n },\n\n Err(e) => {\n\n // Use default values if reading failed.\n\n warn!(\"Failed to read config.toml.\\nUsing default values: {}\", e);\n\n Config::default(&config_dir)\n\n }\n\n }\n\n }\n", "file_path": "core/src/server/config.rs", "rank": 45, "score": 16.762673917986874 }, { "content": " return bad_res;\n\n }\n\n let email = login_args[0].trim_matches('\"');\n\n let password = login_args[1].trim_matches('\"');\n\n let mut no_res = tag.to_string();\n\n no_res.push_str(\" NO invalid username or password\\r\\n\");\n\n if let Some(user) = self.serv.login(email.to_string(), password.to_string()) {\n\n self.maildir = Some(user.maildir.clone());\n\n } else {\n\n return no_res;\n\n }\n\n match self.maildir {\n\n Some(_) => {\n\n let mut res = tag.to_string();\n\n res.push_str(\" OK logged in successfully as \");\n\n res.push_str(email);\n\n res.push_str(\"\\r\\n\");\n\n res\n\n }\n\n None => no_res,\n", "file_path": "core/src/server/imap.rs", "rank": 46, "score": 16.492849984162515 }, { "content": " let (folder, res) =\n\n util::perform_select(&maildir[..], &args.collect::<Vec<&str>>(), true, tag);\n\n self.folder = folder;\n\n match self.folder {\n\n None => bad_res,\n\n _ => res,\n\n }\n\n }\n\n \"create\" => {\n\n let create_args: Vec<&str> = args.collect();\n\n if create_args.len() < 1 {\n\n return bad_res;\n\n }\n\n let mbox_name = create_args[0].trim_matches('\"').replace(\"INBOX\", \"\");\n\n match self.maildir {\n\n None => bad_res,\n\n Some(ref maildir) => {\n\n let mut no_res = tag.to_string();\n\n no_res.push_str(\" NO Could not create folder.\\r\\n\");\n\n let maildir_path = Path::new(&maildir[..]).join(mbox_name);\n", "file_path": "core/src/server/imap.rs", "rank": 47, "score": 16.38617651849306 }, { "content": " }\n\n // Get the compiler to STFU with empty match block\n\n match fs::remove_file(&self.path.join(\".lock\")) {\n\n _ => {}\n\n }\n\n }\n\n result\n\n }\n\n\n\n pub fn message_count(&self) -> usize {\n\n self.messages.len()\n\n }\n\n\n\n /// Perform a fetch of the specified attributes on self.messsages[index]\n\n /// Return the FETCH response string to be sent back to the client\n\n pub fn fetch(&self, index: usize, attributes: &[Attribute]) -> String {\n\n let mut res = \"* \".to_string();\n\n res.push_str(&(index + 1).to_string()[..]);\n\n res.push_str(\" FETCH (\");\n\n res.push_str(&self.messages[index].fetch(attributes)[..]);\n", "file_path": "core/src/folder.rs", "rank": 48, "score": 15.931606873940863 }, { "content": " break;\n\n }\n\n };\n\n let maildir = rcpt.maildir.clone();\n\n let newdir_path = Path::new(&maildir[..]).join(\"new\");\n\n loop {\n\n let file_path = &newdir_path.join(timestamp.to_string());\n\n match File::create(&file_path) {\n\n Err(e) => {\n\n if e.kind() == AlreadyExists {\n\n timestamp += 1;\n\n } else {\n\n warn!(\"Error creating file '{}': {}\", file_path.to_str().unwrap_or_default(), e);\n\n delivery_ioerror!(res);\n\n }\n\n }\n\n Ok(mut file) => {\n\n if file.write(self.data.as_bytes()).is_err() {\n\n warn!(\"Error creating file '{}': cannot write file\", file_path.to_str().unwrap_or_default());\n\n delivery_ioerror!(res);\n", "file_path": "core/src/server/lmtp.rs", "rank": 49, "score": 15.372018042352423 }, { "content": " return no_res;\n\n }\n\n\n\n let mut ok_res = tag.to_string();\n\n ok_res.push_str(\" OK CREATE successful.\\r\\n\");\n\n ok_res\n\n }\n\n }\n\n }\n\n \"delete\" => {\n\n let delete_args: Vec<&str> = args.collect();\n\n if delete_args.len() < 1 {\n\n return bad_res;\n\n }\n\n let mbox_name = delete_args[0].trim_matches('\"').replace(\"INBOX\", \"\");\n\n match self.maildir {\n\n None => bad_res,\n\n Some(ref maildir) => {\n\n let mut no_res = tag.to_string();\n\n no_res.push_str(\" NO Invalid folder.\\r\\n\");\n", "file_path": "core/src/server/imap.rs", "rank": 51, "score": 14.889799173714405 }, { "content": " mime_message: MIME_Message,\n\n\n\n // contains the message's flags\n\n flags: HashSet<Flag>,\n\n\n\n // marks the message for deletion\n\n deleted: bool,\n\n}\n\n\n\nimpl Message {\n\n pub fn new(arg_path: &Path) -> ImapResult<Message> {\n\n let mime_message = MIME_Message::new(arg_path)?;\n\n\n\n // Grab the string in the filename representing the flags\n\n let mut path = path_filename_to_str!(arg_path).splitn(2, ':');\n\n let filename = match path.next() {\n\n Some(fname) => fname,\n\n None => {\n\n return Err(Error::MessageBadFilename);\n\n }\n", "file_path": "core/src/message.rs", "rank": 52, "score": 13.589146242655751 }, { "content": " }\n\n\n\n /**\n\n * RFC3501 - 7.4.2 - P.76\n\n *\n\n * The RFC requests that the data be returned as a parenthesized list, but\n\n * the current format is also acceptible by most mail clients.\n\n */\n\n pub fn get_parenthesized_addresses(&self, key: &str) -> &str {\n\n match self.headers.get(&key.to_string()) {\n\n Some(v) => &v[..],\n\n None => \"NIL\",\n\n }\n\n }\n\n\n\n pub fn get_size(&self) -> String {\n\n self.size.to_string()\n\n }\n\n\n\n pub fn get_header_boundary(&self) -> String {\n\n self.header_boundary.to_string()\n\n }\n\n\n\n pub fn get_header(&self) -> &str {\n\n &self.raw_contents[..self.header_boundary]\n\n }\n\n}\n", "file_path": "mime/src/lib.rs", "rank": 53, "score": 12.851552026303189 }, { "content": " }\n\n }\n\n \"logout\" => {\n\n // Close the connection after sending the response\n\n self.logout = true;\n\n\n\n // Write out current state of selected folder (if any)\n\n // to disk\n\n if let Some(ref folder) = self.folder {\n\n folder.expunge();\n\n }\n\n\n\n let mut res = \"* BYE Server logging out\\r\\n\".to_string();\n\n res.push_str(tag);\n\n res.push_str(\" OK Server logged out\\r\\n\");\n\n res\n\n }\n\n // Examine and Select should be nearly identical...\n\n \"select\" => {\n\n let maildir = match self.maildir {\n", "file_path": "core/src/server/imap.rs", "rank": 54, "score": 12.692861497042127 }, { "content": " // leave the other files, and the\n\n // folder itself, in tact.\n\n let mut ok_res = tag.to_string();\n\n ok_res.push_str(\" OK DELETE successsful.\\r\\n\");\n\n ok_res\n\n })\n\n )\n\n }\n\n }\n\n }\n\n // List folders which match the specified regular expression.\n\n \"list\" => {\n\n let list_args: Vec<&str> = args.collect();\n\n if list_args.len() < 2 {\n\n return bad_res;\n\n }\n\n let reference = list_args[0].trim_matches('\"');\n\n let mailbox_name = list_args[1].trim_matches('\"');\n\n match self.maildir {\n\n None => bad_res,\n", "file_path": "core/src/server/imap.rs", "rank": 55, "score": 12.50646153934058 }, { "content": " }\n\n\n\n let mut args = command.trim().split(' ');\n\n let inv_str = \" BAD Invalid command\\r\\n\";\n\n\n\n // The client will need the tag in the response in order to match up\n\n // the response to the command it issued because the client does not\n\n // have to wait on our response in order to issue new commands.\n\n let mut starttls = false;\n\n let res = match args.next() {\n\n None => inv_str.to_string(),\n\n Some(tag) => {\n\n let mut bad_res = tag.to_string();\n\n bad_res.push_str(inv_str);\n\n\n\n // Interpret the command and generate a response\n\n match args.next() {\n\n None => bad_res,\n\n Some(c) => {\n\n warn!(\"Cmd: {}\", command.trim());\n", "file_path": "core/src/server/imap.rs", "rank": 57, "score": 12.229046549141367 }, { "content": "use self::auth::AuthData;\n\nuse crate::error::ImapResult;\n\nuse serde_json;\n\nuse std::collections::HashMap;\n\nuse std::fs::File;\n\nuse std::io::{Read, Write};\n\nuse std::path::Path;\n\nuse std::str;\n\n\n\npub use self::email::Email;\n\npub use self::login::LoginData;\n\n\n\nmod auth;\n\nmod email;\n\nmod login;\n\n\n\n/// Representation of a User.\n\n#[derive(Debug, Deserialize, Serialize)]\n\npub struct User {\n\n /// The email address through which the user logs in.\n", "file_path": "core/src/server/user/mod.rs", "rank": 58, "score": 12.22257448113022 }, { "content": " }\n\n\n\n /// Goes through the list of attributes, constructing a FETCH response for\n\n /// this message containing the values of the requested attributes\n\n pub fn fetch(&self, attributes: &[Attribute]) -> String {\n\n let mut res = String::new();\n\n let mut first = true;\n\n for attr in attributes.iter() {\n\n // We need to space separate the attribute values\n\n if first {\n\n first = false;\n\n } else {\n\n res.push(' ');\n\n }\n\n\n\n // Provide the attribute name followed by the attribute value\n\n match *attr {\n\n Envelope => {\n\n res.push_str(\"ENVELOPE \");\n\n res.push_str(&self.mime_message.get_envelope()[..]);\n", "file_path": "core/src/message.rs", "rank": 59, "score": 12.146172666013968 }, { "content": "\n\nimpl AuthData {\n\n /// Generates a hash and salt for secure storage of a password\n\n pub fn new(password: String) -> AuthData {\n\n let salt = gen_salt();\n\n let password = password.into_bytes();\n\n // Perform the bcrypt hashing, storing it to an output vector.\n\n let out = &mut [0u8; 32];\n\n bcrypt_pbkdf(&password[..], &salt[..], ROUNDS, out);\n\n\n\n AuthData {\n\n salt: salt,\n\n out: out.to_vec(),\n\n }\n\n }\n\n\n\n /// Verify a password string against the stored auth data to see if it\n\n /// matches.\n\n pub fn verify_auth(&self, password: String) -> bool {\n\n let out = &mut [0u8; 32];\n\n bcrypt_pbkdf(&password.into_bytes()[..], &self.salt[..], ROUNDS, out);\n\n self.out == out.to_vec()\n\n }\n\n}\n\n\n\n/// Generate a random salt using the cryptographically secure PRNG provided by\n\n/// the OS, for use with bcrypt hashing.\n", "file_path": "core/src/server/user/auth.rs", "rank": 60, "score": 12.136464338060613 }, { "content": " Some(ref maildir) => {\n\n if mailbox_name.is_empty() {\n\n return format!(\n\n \"* LIST (\\\\Noselect) \\\"/\\\" \\\"{}\\\"\\r\\n{} OK List successful\\r\\n\",\n\n reference, tag\n\n );\n\n }\n\n let mailbox_name = mailbox_name.replace(\"*\", \".*\").replace(\"%\", \"[^/]*\");\n\n let maildir_path = Path::new(&maildir[..]);\n\n let re_opt = Regex::new(\n\n &format!(\n\n \"{}{}?{}{}?{}$\",\n\n path_filename_to_str!(maildir_path),\n\n MAIN_SEPARATOR,\n\n reference,\n\n MAIN_SEPARATOR,\n\n mailbox_name.replace(\"INBOX\", \"\")\n\n )[..],\n\n );\n\n match re_opt {\n", "file_path": "core/src/server/imap.rs", "rank": 61, "score": 11.935121872677625 }, { "content": "use std::collections::HashMap;\n\nuse std::fs::File;\n\nuse std::io::Read;\n\nuse std::path::Path;\n\nuse std::str;\n\n\n\npub use self::command::BodySectionType;\n\nuse self::command::BodySectionType::{AllSection, MsgtextSection, PartSection};\n\n\n\npub use self::command::Msgtext;\n\nuse self::command::Msgtext::{\n\n HeaderFieldsMsgtext, HeaderFieldsNotMsgtext, HeaderMsgtext, MimeMsgtext, TextMsgtext,\n\n};\n\n\n\npub use self::error::Error;\n\nuse self::error::Result as MimeResult;\n\n\n\nmod command;\n\nmod error;\n\n\n", "file_path": "mime/src/lib.rs", "rank": 62, "score": 11.845019632620046 }, { "content": " pub email: Email,\n\n /// The authentication data the used to verify the user's identity.\n\n pub auth_data: AuthData,\n\n /// The root directory in which the user's mail is stored.\n\n pub maildir: String,\n\n}\n\n\n\nimpl User {\n\n /// Creates a new user from a provided email, plaintext password, and root\n\n /// mail directory.\n\n pub fn new(email: Email, password: String, maildir: String) -> User {\n\n User {\n\n email: email,\n\n auth_data: AuthData::new(password),\n\n maildir: maildir,\n\n }\n\n }\n\n}\n\n\n\n/// Reads a JSON file and turns it into a `HashMap` of emails to users.\n\n/// May throw an `std::io::Error`, hence the `Result<>` type.\n", "file_path": "core/src/server/user/mod.rs", "rank": 63, "score": 11.790881924155237 }, { "content": " }\n\n };\n\n let mut from_parts = from_path_split.split('@');\n\n let local_part = match from_parts.next() {\n\n Some(part) => part.to_string(),\n\n _ => {\n\n return None;\n\n }\n\n };\n\n let domain_part = match from_parts.next() {\n\n Some(part) => part.to_string(),\n\n _ => {\n\n return None;\n\n }\n\n };\n\n Some(Email::new(local_part, domain_part))\n\n}\n\n\n", "file_path": "core/src/server/lmtp.rs", "rank": 64, "score": 11.756314561971612 }, { "content": " pub lmtp_ssl_port: Option<u16>,\n\n // SSL port on which to listen for IMAP\n\n pub imap_ssl_port: Option<u16>,\n\n // file in which user data is stored\n\n pub users: String,\n\n // Filename of PKCS #12 archive\n\n pub pkcs_file: String,\n\n // Password for PKCS #12 archive\n\n pub pkcs_pass: String,\n\n}\n\n\n\nimpl Config {\n\n pub fn new() -> ImapResult<Config> {\n\n let config_dir = match env::var(\"SEGIMAP_CONFIG_DIR\") {\n\n Ok(val) => val,\n\n Err(_e) => \".\".to_string(),\n\n };\n\n\n\n let config_file = format!(\"{}/config.toml\", config_dir);\n\n let path = Path::new(&config_file);\n", "file_path": "core/src/server/config.rs", "rank": 66, "score": 11.544548035186063 }, { "content": " }\n\n }\n\n\n\n pub fn remove_if_deleted(&self) -> bool {\n\n if self.deleted {\n\n // Get the compiler to STFU with empty match block\n\n match fs::remove_file(self.path.as_path()) {\n\n _ => {}\n\n }\n\n }\n\n self.deleted\n\n }\n\n\n\n pub fn get_path(&self) -> &Path {\n\n self.path.as_path()\n\n }\n\n\n\n pub fn get_uid(&self) -> usize {\n\n self.uid\n\n }\n", "file_path": "core/src/message.rs", "rank": 67, "score": 11.520464843241614 }, { "content": " Err(_) => bad_res,\n\n Ok(re) => {\n\n let list_responses = util::list(&maildir[..], &re);\n\n let mut ok_res = String::new();\n\n for list_response in &list_responses {\n\n ok_res.push_str(&list_response[..]);\n\n ok_res.push_str(\"\\r\\n\");\n\n }\n\n ok_res.push_str(tag);\n\n ok_res.push_str(\" OK list successful\\r\\n\");\n\n ok_res\n\n }\n\n }\n\n }\n\n }\n\n }\n\n // Resolve state of folder in memory with state of mail on\n\n // disk\n\n \"check\" => {\n\n match self.expunge() {\n", "file_path": "core/src/server/imap.rs", "rank": 68, "score": 11.496905734815986 }, { "content": "impl Folder {\n\n pub fn new(path: PathBuf, examine: bool) -> Option<Folder> {\n\n // the EXAMINE command is always read-only or we test SELECT for read-only status\n\n // We use a lock file to determine write access on a folder\n\n let readonly = if examine || fs::File::open(&path.join(\".lock\")).is_ok() {\n\n true\n\n } else {\n\n if let Ok(mut file) = fs::File::create(&path.join(\".lock\")) {\n\n // Get the compiler to STFU with this match\n\n let _ = file.write(b\"selected\");\n\n false\n\n } else {\n\n true\n\n }\n\n };\n\n\n\n if let Ok(cur) = fs::read_dir(&(path.join(\"cur\"))) {\n\n if let Ok(new) = fs::read_dir(&(path.join(\"new\"))) {\n\n let mut messages = Vec::new();\n\n let mut uid_to_seqnum: HashMap<usize, usize> = HashMap::new();\n", "file_path": "core/src/folder.rs", "rank": 69, "score": 11.259588345890243 }, { "content": " messages: messages,\n\n readonly: readonly,\n\n uid_to_seqnum: uid_to_seqnum,\n\n });\n\n }\n\n }\n\n None\n\n }\n\n\n\n /// Generate the SELECT/EXAMINE response based on data in the folder\n\n pub fn select_response(&self, tag: &str) -> String {\n\n let unseen_res = if self.unseen <= self.exists {\n\n let unseen_str = self.unseen.to_string();\n\n let mut res = \"* OK [UNSEEN \".to_string();\n\n res.push_str(&unseen_str[..]);\n\n res.push_str(\"] Message \");\n\n res.push_str(&unseen_str[..]);\n\n res.push_str(\"th is the first unseen\\r\\n\");\n\n res\n\n } else {\n", "file_path": "core/src/folder.rs", "rank": 70, "score": 11.229329420181921 }, { "content": "use std::fmt;\n\n\n\n/// Representation of an email\n\n/// This helps ensure the email at least has an '@' in it...\n\n#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]\n\npub struct Email {\n\n pub local_part: String,\n\n pub domain_part: String,\n\n}\n\n\n\nimpl fmt::Display for Email {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{}\", self.to_string())\n\n }\n\n}\n\n\n\nimpl Email {\n\n pub fn new(local_part: String, domain_part: String) -> Email {\n\n Email {\n\n local_part: local_part,\n", "file_path": "core/src/server/user/email.rs", "rank": 71, "score": 11.20183562969351 }, { "content": " /// single character per flag representation of the current set of flags.\n\n pub fn get_new_filename(&self) -> String {\n\n let mut res = self.uid.to_string();\n\n\n\n // it is just the UID if no flags are set.\n\n if self.flags.is_empty() {\n\n return res;\n\n }\n\n\n\n // Add the prelud which separates the flags\n\n res.push_str(\":2,\");\n\n\n\n // As per the Maildir standard, the flags are to be written in\n\n // alphabetical order\n\n if self.flags.contains(&Flag::Draft) {\n\n res.push('D');\n\n }\n\n if self.flags.contains(&Flag::Flagged) {\n\n res.push('F');\n\n }\n", "file_path": "core/src/message.rs", "rank": 73, "score": 10.917510122787943 }, { "content": "SEGIMAP\n\n=======\n\n\n\nThis is a continuation of the upstream SEGIMAP server. Unfortunately it seems upstream might be abandoned, so this repo is trying to modernize it enough to run in a Docker container.\n\n\n\n[![Docker image build](https://github.com/kruton/segimap/actions/workflows/docker.yml/badge.svg)](https://github.com/kruton/segimap/actions/workflows/docker.yml)\n\n\n\nOriginal description\n\n--------------------\n\nThis is an IMAP server implementation written in Rust. It originally started out as a class project in Fall 2014.\n\nThere is also an LMTP server attached so that SMTP servers may deliver mail without modifying the maildir themselves.\n\n\n\nSome notes about Rust\n\n---------------------\n\n\n\nThe most confusing thing for those reading the code who are unfamiliar with rust will likely be &str and String. &str is an actual string while String is actually a StringBuffer. `&x[..]` is used to get a &str out of a String called `x` and `y.to_string()` is used to get a String out of a &str called `y`. Sometimes we need something which is neither of these to be a string so we use `.to_str()` or `.to_string()` as appropriate. Sometimes we need a String but the thing we have can only be converted to &str so we have to chain the calls like so: `.to_str().to_string()`. It sometimes also occurs the other way around in which case we wind up with something like `&z.to_string()[..]`.\n\n\n\n& denotes a pointer (ie: pass-by-reference semantics). When you see &mut it means that the pointer is mutable. Rust only allows one mutable pointer at a time and enforces this at compile time. However, multiple immutable pointers may be created. * is used to dereference a pointer. In most cases, method calls will automatically dereference when needed.\n\n\n\nThe statement `return thing;` is equivalent to `thing` (note the absence of a semi-colon).\n\n\n\nThat should be everything someone who doesn't know rust needs to understand this code and why we do things certain ways.\n\n\n", "file_path": "README.md", "rank": 74, "score": 10.900299599168147 }, { "content": "use nom::crlf;\n\nuse std::str;\n\n\n\npub use self::fetch::fetch;\n\n\n\nmod fetch;\n\nmod sequence;\n\n\n\nconst DIGITS: &'static str = \"0123456789\";\n\nconst NZ_DIGITS: &'static str = \"123456789\";\n\n\n", "file_path": "core/src/parser/grammar/mod.rs", "rank": 75, "score": 10.79886151956141 }, { "content": " return;\n\n }\n\n }\n\n\n\n // If there is an error on the stream, exit.\n\n Err(_) => {\n\n return;\n\n }\n\n }\n\n }\n\n }\n\n\n\n /// Interprets a client command and generates a String response\n\n fn interpret(\n\n &mut self,\n\n cmd: &str,\n\n args: &mut Split<char>,\n\n tag: &str,\n\n bad_res: String,\n\n ) -> String {\n", "file_path": "core/src/server/imap.rs", "rank": 76, "score": 10.790367482061743 }, { "content": "use super::email::Email;\n\n\n\n/// Representation of an email and password login attempt.\n\npub struct LoginData {\n\n pub email: Email,\n\n pub password: String,\n\n}\n\n\n\nimpl LoginData {\n\n pub fn new(email: String, password: String) -> Option<LoginData> {\n\n let mut parts = (&email[..]).split('@');\n\n if let Some(local_part) = parts.next() {\n\n if let Some(domain_part) = parts.next() {\n\n let login_data = LoginData {\n\n email: Email {\n\n local_part: local_part.to_string(),\n\n domain_part: domain_part.to_string(),\n\n },\n\n password: password,\n\n };\n\n return Some(login_data);\n\n }\n\n }\n\n\n\n None\n\n }\n\n}\n", "file_path": "core/src/server/user/login.rs", "rank": 77, "score": 10.786754806448997 }, { "content": " _ => {}\n\n }\n\n match self.folder {\n\n None => bad_res,\n\n Some(ref mut folder) => {\n\n folder.check();\n\n let mut ok_res = tag.to_string();\n\n ok_res.push_str(\" OK Check completed\\r\\n\");\n\n ok_res\n\n }\n\n }\n\n }\n\n // Close the currently selected folder. Perform all\n\n // required cleanup.\n\n \"close\" => match self.expunge() {\n\n Err(_) => bad_res,\n\n Ok(_) => {\n\n if let Some(ref mut folder) = self.folder {\n\n folder.check();\n\n }\n", "file_path": "core/src/server/imap.rs", "rank": 78, "score": 10.724549191024547 }, { "content": " // The argument after the tag specified the command issued.\n\n // Additional arguments are arguments for that specific command.\n\n match cmd {\n\n \"noop\" => {\n\n let mut res = tag.to_string();\n\n res += \" OK NOOP\\r\\n\";\n\n res\n\n }\n\n\n\n // Inform the client of the supported IMAP version and\n\n // extension(s)\n\n \"capability\" => {\n\n let mut res = \"* CAPABILITY IMAP4rev1 CHILDREN\\r\\n\".to_string();\n\n res.push_str(tag);\n\n res.push_str(\" OK Capability successful\\r\\n\");\n\n res\n\n }\n\n \"login\" => {\n\n let login_args: Vec<&str> = args.collect();\n\n if login_args.len() < 2 {\n", "file_path": "core/src/server/imap.rs", "rank": 79, "score": 10.68003849757391 }, { "content": " self.folder = None;\n\n format!(\"{} OK close completed\\r\\n\", tag)\n\n }\n\n },\n\n // Delete the messages currently marked for deletion.\n\n \"expunge\" => match self.expunge() {\n\n Err(_) => bad_res,\n\n Ok(v) => {\n\n let mut ok_res = String::new();\n\n for i in &v {\n\n ok_res.push_str(\"* \");\n\n ok_res.push_str(&i.to_string()[..]);\n\n ok_res.push_str(\" EXPUNGE\\r\\n\");\n\n }\n\n ok_res.push_str(tag);\n\n ok_res.push_str(\" OK expunge completed\\r\\n\");\n\n ok_res\n\n }\n\n },\n\n \"fetch\" => {\n", "file_path": "core/src/server/imap.rs", "rank": 80, "score": 10.54853401654476 }, { "content": "use crate::error::ImapResult;\n\nuse openssl::error::ErrorStack;\n\nuse openssl::pkcs12::Pkcs12;\n\nuse openssl::ssl::{SslAcceptor, SslMethod};\n\nuse openssl::x509::X509;\n\nuse std::env;\n\nuse std::fs::File;\n\nuse std::io::{Error as IoError, Read, Write};\n\nuse std::path::Path;\n\nuse std::str;\n\nuse toml;\n\n\n\npub enum PkcsError {\n\n Io(IoError),\n\n Ssl(ErrorStack),\n\n PortsDisabled,\n\n}\n\n\n\nimpl From<IoError> for PkcsError {\n\n fn from(e: IoError) -> Self {\n", "file_path": "core/src/server/config.rs", "rank": 81, "score": 10.503736023253923 }, { "content": " _ => { },\n\n }\n\n },\n\n */\n\n UID => {\n\n res.push_str(\"UID \");\n\n res.push_str(&self.uid.to_string()[..])\n\n }\n\n }\n\n }\n\n res\n\n }\n\n\n\n // Creates a string of the current set of flags based on what is in\n\n // self.flags.\n\n fn print_flags(&self) -> String {\n\n let mut res = \"(\".to_string();\n\n let mut first = true;\n\n for flag in &self.flags {\n\n // The flags should be space separated.\n", "file_path": "core/src/message.rs", "rank": 82, "score": 10.445533997237021 }, { "content": " },\n\n },\n\n \"data\" => {\n\n return_on_err!(stream.write(data_res));\n\n return_on_err!(stream.flush());\n\n let mut loop_res = invalid;\n\n loop {\n\n let mut data_command = String::new();\n\n match stream.read_line(&mut data_command) {\n\n Ok(_) => {\n\n if data_command.is_empty() {\n\n break;\n\n }\n\n let data_cmd = (&data_command[..]).trim();\n\n if data_cmd == \".\" {\n\n loop_res = l.deliver();\n\n l.data = String::new();\n\n break;\n\n }\n\n l.data.push_str(data_cmd);\n", "file_path": "core/src/server/lmtp.rs", "rank": 83, "score": 10.251935949740748 }, { "content": "use chrono::{Datelike, NaiveDateTime, Timelike};\n\nuse std::collections::HashSet;\n\nuse std::fs;\n\nuse std::path::Path;\n\nuse std::path::PathBuf;\n\nuse std::str;\n\n\n\nuse crate::command::store::StoreName;\n\nuse crate::command::Attribute;\n\nuse crate::command::Attribute::{\n\n Body, BodyPeek, BodySection, BodyStructure, Envelope, Flags, InternalDate, RFC822, UID,\n\n};\n\nuse crate::command::RFC822Attribute::{AllRFC822, HeaderRFC822, SizeRFC822, TextRFC822};\n\n\n\nuse crate::error::{Error, ImapResult};\n\n\n\nuse mime::Message as MIME_Message;\n\n\n\n/// Representation of a message flag\n\n#[derive(Eq, PartialEq, Hash, Debug, Clone)]\n\npub enum Flag {\n\n Answered,\n\n Draft,\n\n Flagged,\n\n Seen,\n\n Deleted,\n\n}\n\n\n\n/// Takes a flag argument and returns the corresponding enum.\n", "file_path": "core/src/message.rs", "rank": 84, "score": 10.144893395645937 }, { "content": " let maildir_path = Path::new(&maildir[..]).join(mbox_name);\n\n let newmaildir_path = maildir_path.join(\"new\");\n\n let curmaildir_path = maildir_path.join(\"cur\");\n\n opendirlisting!(\n\n &newmaildir_path,\n\n newlist,\n\n no_res,\n\n opendirlisting!(&curmaildir_path, curlist, no_res, {\n\n // Delete the mail in the folder\n\n for file_entry in newlist {\n\n match file_entry {\n\n Ok(file) => {\n\n if fs::remove_file(file.path()).is_err() {\n\n return no_res;\n\n }\n\n }\n\n Err(_) => return no_res,\n\n }\n\n }\n\n for file_entry in curlist {\n", "file_path": "core/src/server/imap.rs", "rank": 85, "score": 10.123604945875744 }, { "content": " let start = match folder.get_index_from_uid(&n) {\n\n Some(start) => *start,\n\n None => {\n\n if n == 1 {\n\n 0usize\n\n } else {\n\n return bad_res;\n\n }\n\n }\n\n };\n\n let mut res = String::new();\n\n for index in start..folder.message_count() {\n\n res.push_str(&folder.fetch(index+1, &parsed_cmd.attributes)[..]);\n\n }\n\n res.push_str(tag);\n\n res.push_str(\" OK UID FETCH completed\\r\\n\");\n\n return res;\n\n }\n\n }\n\n };\n", "file_path": "core/src/server/imap.rs", "rank": 86, "score": 10.050227104959653 }, { "content": " match &c.to_ascii_lowercase()[..] {\n\n // STARTTLS is handled here because it modifies the stream\n\n \"starttls\" => match stream.get_ref() {\n\n &Stream::Tcp(_) => {\n\n if self.serv.can_starttls() {\n\n starttls = true;\n\n let mut ok_res = tag.to_string();\n\n ok_res.push_str(\n\n \" OK Begin TLS negotiation now\\r\\n\",\n\n );\n\n ok_res\n\n } else {\n\n bad_res\n\n }\n\n }\n\n _ => bad_res,\n\n },\n\n cmd => self.interpret(cmd, &mut args, tag, bad_res),\n\n }\n\n }\n", "file_path": "core/src/server/imap.rs", "rank": 87, "score": 10.024202457512857 }, { "content": " None => {\n\n return bad_res;\n\n }\n\n Some(ref maildir) => maildir,\n\n };\n\n let (folder, res) =\n\n util::perform_select(&maildir[..], &args.collect::<Vec<&str>>(), false, tag);\n\n self.folder = folder;\n\n match self.folder {\n\n None => bad_res,\n\n _ => res,\n\n }\n\n }\n\n \"examine\" => {\n\n let maildir = match self.maildir {\n\n None => {\n\n return bad_res;\n\n }\n\n Some(ref maildir) => maildir,\n\n };\n", "file_path": "core/src/server/imap.rs", "rank": 88, "score": 9.99704001070352 }, { "content": " }\n\n }\n\n);\n\n\n\nmacro_rules! delivery_ioerror(\n\n ($res:ident) => ({\n\n $res.push_str(\"451 Error in processing.\\r\\n\");\n\n break;\n\n })\n\n);\n\n\n\nmacro_rules! grab_email_token(\n\n ($arg:expr) => {\n\n match $arg {\n\n Some(from_path) => from_path.trim_start_matches('<').trim_end_matches('>'),\n\n _ => { return None; }\n\n }\n\n }\n\n);\n\n\n", "file_path": "core/src/server/lmtp.rs", "rank": 89, "score": 9.637673870499036 }, { "content": "use std::collections::{HashMap, HashSet};\n\nuse std::fs;\n\nuse std::io::Write;\n\nuse std::path::Path;\n\nuse std::path::PathBuf;\n\n\n\nuse crate::command::Attribute;\n\nuse crate::message::Flag;\n\nuse crate::message::Message;\n\n\n\nuse crate::command::store::StoreName;\n\n\n\n/// Representation of a Folder\n\n#[derive(Clone, Debug)]\n\npub struct Folder {\n\n // How many messages are in folder/new/\n\n recent: usize,\n\n // How many messages are in the folder total\n\n exists: usize,\n\n // How many messages are not marked with the Seen flag\n", "file_path": "core/src/folder.rs", "rank": 90, "score": 9.572147903086625 }, { "content": " domain_part: domain_part,\n\n }\n\n }\n\n\n\n fn to_string(&self) -> String {\n\n let mut res = self.local_part.clone();\n\n res.push('@');\n\n res.push_str(&self.domain_part[..]);\n\n res\n\n }\n\n}\n", "file_path": "core/src/server/user/email.rs", "rank": 91, "score": 9.308165254230122 }, { "content": " res.push_str(\")\\r\\n\");\n\n res\n\n }\n\n\n\n /// Turn a UID into a sequence number\n\n pub fn get_index_from_uid(&self, uid: &usize) -> Option<&usize> {\n\n self.uid_to_seqnum.get(uid)\n\n }\n\n\n\n /// Perform a STORE on the specified set of sequence numbers\n\n /// This modifies the flags of the specified messages\n\n /// Returns the String response to be sent back to the client.\n\n pub fn store(\n\n &mut self,\n\n sequence_set: Vec<usize>,\n\n flag_name: &StoreName,\n\n silent: bool,\n\n flags: HashSet<Flag>,\n\n seq_uid: bool,\n\n tag: &str,\n", "file_path": "core/src/folder.rs", "rank": 92, "score": 9.272117608844594 }, { "content": " (&self.raw_contents[..]).len(),\n\n self.raw_contents\n\n )\n\n }\n\n MsgtextSection(ref msgtext) => match *msgtext {\n\n HeaderMsgtext | HeaderFieldsNotMsgtext(_) | TextMsgtext | MimeMsgtext => {\n\n empty_string\n\n }\n\n HeaderFieldsMsgtext(ref fields) => {\n\n let mut field_keys = String::new();\n\n let mut field_values = String::new();\n\n let mut first = true;\n\n for field in fields.iter() {\n\n match self.headers.get(field) {\n\n Some(v) => {\n\n let field_slice = &field[..];\n\n if first {\n\n first = false;\n\n } else {\n\n field_keys.push(' ');\n", "file_path": "mime/src/lib.rs", "rank": 93, "score": 9.206912028322192 }, { "content": " .to_string();\n\n\n\n // Add a space between the merged lines.\n\n trimmed_next.push(' ');\n\n trimmed_next.push_str(line.trim_start_matches(' ').trim_start_matches('\\t'));\n\n if !next.starts_with(' ') && !next.starts_with('\\t') {\n\n let split: Vec<&str> = (&trimmed_next[..]).splitn(2, ':').collect();\n\n headers.insert(split[0].to_ascii_uppercase(), split[1][1..].to_string());\n\n break;\n\n }\n\n }\n\n } else {\n\n let split: Vec<&str> = line.splitn(2, ':').collect();\n\n headers.insert(split[0].to_ascii_uppercase(), split[1][1..].to_string());\n\n }\n\n }\n\n\n\n // Remove the \"Received\" key from the HashMap.\n\n let received_key = &RECEIVED.to_string();\n\n if headers.get(received_key).is_some() {\n", "file_path": "mime/src/lib.rs", "rank": 94, "score": 9.143419354657816 }, { "content": "pub enum Stream {\n\n Ssl(SslStream<TcpStream>),\n\n Tcp(TcpStream),\n\n}\n\n\n\nimpl Write for Stream {\n\n fn write(&mut self, buf: &[u8]) -> Result<usize> {\n\n match *self {\n\n Stream::Ssl(ref mut s) => s.write(buf),\n\n Stream::Tcp(ref mut s) => s.write(buf),\n\n }\n\n }\n\n\n\n fn flush(&mut self) -> Result<()> {\n\n match *self {\n\n Stream::Ssl(ref mut s) => s.flush(),\n\n Stream::Tcp(ref mut s) => s.flush(),\n\n }\n\n }\n\n}\n", "file_path": "core/src/server/mod.rs", "rank": 95, "score": 9.131637265736746 }, { "content": " }\n\n }\n\n\n\n /// Handles client commands as they come in on the stream and writes\n\n /// responeses back to the stream.\n\n pub fn handle(&mut self, orig_stream: TcpStream) {\n\n let mut stream = BufStream::new(self.serv.imap_ssl(orig_stream));\n\n // Provide the client with an IMAP greeting.\n\n return_on_err!(stream.write(GREET));\n\n return_on_err!(stream.flush());\n\n\n\n let mut command = String::new();\n\n loop {\n\n command.truncate(0);\n\n match stream.read_line(&mut command) {\n\n Ok(_) => {\n\n // If the command is empty, exit.\n\n // Exitting will close the stream for us.\n\n if command.is_empty() {\n\n return;\n", "file_path": "core/src/server/imap.rs", "rank": 96, "score": 8.999105109555664 }, { "content": "use bufstream::BufStream;\n\nuse regex::Regex;\n\nuse std::fs;\n\nuse std::io::{BufRead, Write};\n\nuse std::net::TcpStream;\n\nuse std::os::unix::fs::PermissionsExt;\n\nuse std::path::Path;\n\nuse std::path::MAIN_SEPARATOR;\n\nuse std::str::Split;\n\nuse std::sync::Arc;\n\n\n\nuse crate::folder::Folder;\n\nuse crate::server::Server;\n\nuse crate::server::Stream;\n\n\n\nuse crate::command::fetch;\n\nuse crate::command::sequence_set;\n\nuse crate::command::sequence_set::SequenceItem::{Number, Range, Wildcard};\n\nuse crate::command::store;\n\nuse crate::command::Attribute::UID;\n", "file_path": "core/src/server/imap.rs", "rank": 97, "score": 8.977644924311676 }, { "content": " if let Some(message) = self.messages.get_mut(i - 1) {\n\n responses.push_str(\"* \");\n\n responses.push_str(&i.to_string()[..]);\n\n responses.push_str(\" FETCH (FLAGS \");\n\n responses.push_str(&message.store(flag_name, flags.clone())[..]);\n\n\n\n // UID STORE needs to respond with the UID for each FETCH response\n\n if seq_uid {\n\n let uid_res = format!(\" UID {}\", uid);\n\n responses.push_str(&uid_res[..]);\n\n }\n\n responses.push_str(\" )\\r\\n\");\n\n }\n\n }\n\n\n\n // Return an empty string if the client wanted the STORE to be SILENT\n\n if silent {\n\n responses = String::new();\n\n }\n\n responses.push_str(tag);\n", "file_path": "core/src/folder.rs", "rank": 98, "score": 8.934740082385032 }, { "content": " use super::fetch;\n\n use command::sequence_set::SequenceItem::{Number, Range, Wildcard};\n\n use command::Attribute::{BodyPeek, Flags, RFC822};\n\n use command::FetchCommand;\n\n use command::RFC822Attribute::AllRFC822;\n\n use mime::BodySectionType::PartSection;\n\n use mime::Msgtext::HeaderFieldsNotMsgtext;\n\n use nom::IResult::Done;\n\n\n\n #[bench]\n\n fn bench_fetch(b: &mut Bencher) {\n\n const FETCH_STR: &'static str =\n\n \"FETCH 4,5:3,* (FLAGS RFC822 BODY.PEEK[43.65.HEADER.FIELDS.NOT (a \\\"abc\\\")]<4.2>)\";\n\n\n\n b.iter(|| {\n\n assert_eq!(\n\n fetch(FETCH_STR.as_bytes()),\n\n Done(\n\n &b\"\"[..],\n\n FetchCommand::new(\n", "file_path": "core/src/parser/grammar/fetch.rs", "rank": 99, "score": 8.76112179392614 } ]
Rust
dbcrossbarlib/src/config.rs
drusellers/dbcrossbar
c16ed98771a7d18dbef861f88cc8403839c96936
use failure::Fail; use std::{ env, fmt, fs::{create_dir_all, File}, io::{self, Read}, path::{Path, PathBuf}, }; use toml_edit::{Array, Document, Item, Value}; use crate::common::*; #[cfg(not(target_os = "macos"))] fn system_config_dir() -> Option<PathBuf> { dirs::config_dir() } #[cfg(target_os = "macos")] fn system_config_dir() -> Option<PathBuf> { if let Some(preference_dir) = dirs::preference_dir() { let old_config_dir = preference_dir.join("dbcrossbar"); if old_config_dir.is_dir() { use std::sync::Once; static ONCE: Once = Once::new(); ONCE.call_once(|| { if let Some(system_config_dir) = dirs::config_dir() { let new_config_dir = system_config_dir.join("dbcrossbar"); eprintln!( "DEPRECATION WARNING: Please move `{}` to `{}`", old_config_dir.display(), new_config_dir.display(), ); } }); return Some(preference_dir); } } dirs::config_dir() } pub(crate) fn config_dir() -> Result<PathBuf> { match env::var_os("DBCROSSBAR_CONFIG_DIR") { Some(dir) => Ok(PathBuf::from(dir)), None => Ok(system_config_dir() .ok_or_else(|| format_err!("could not find user config dir"))? .join("dbcrossbar")), } } pub(crate) fn config_file() -> Result<PathBuf> { Ok(config_dir()?.join("dbcrossbar.toml")) } #[derive(Debug)] pub struct Key<'a> { key: &'a str, } impl Key<'_> { pub fn temporary() -> Key<'static> { Self::global("temporary") } pub(crate) fn global(key: &str) -> Key<'_> { Key { key } } } impl<'a> fmt::Display for Key<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.key.fmt(f) } } #[derive(Debug)] pub struct Configuration { path: PathBuf, doc: Document, } impl Configuration { pub fn try_default() -> Result<Self> { Self::from_path(&config_file()?) } pub(crate) fn from_path(path: &Path) -> Result<Self> { match File::open(&path) { Ok(rdr) => { Ok(Self::from_reader(path.to_owned(), rdr).with_context(|_| { format!("could not read file {}", path.display()) })?) } Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(Self { path: path.to_owned(), doc: Document::default(), }), Err(err) => Err(err .context(format!("could not open file {}", path.display())) .into()), } } fn from_reader<R>(path: PathBuf, mut rdr: R) -> Result<Self> where R: Read + 'static, { let mut buf = String::new(); rdr.read_to_string(&mut buf)?; let doc = buf.parse::<Document>()?; Ok(Self { path, doc }) } pub fn write(&self) -> Result<()> { let parent = self.path.parent().ok_or_else(|| { format_err!("cannot find parent directory of {}", self.path.display()) })?; create_dir_all(&parent) .with_context(|_| format!("cannot create {}", parent.display()))?; let data = self.doc.to_string_in_original_order(); let mut f = File::create(&self.path) .with_context(|_| format!("cannot create {}", self.path.display()))?; f.write_all(data.as_bytes()) .with_context(|_| format!("error writing to {}", self.path.display()))?; f.flush() .with_context(|_| format!("error writing to {}", self.path.display()))?; Ok(()) } pub fn temporaries(&self) -> Result<Vec<String>> { self.string_array(&Key::global("temporary")) } fn string_array(&self, key: &Key<'_>) -> Result<Vec<String>> { let mut temps = vec![]; if let Some(raw_value) = self.doc.as_table().get(key.key) { if let Some(raw_array) = raw_value.as_array() { for raw_item in raw_array.iter() { if let Some(temp) = raw_item.as_str() { temps.push(temp.to_owned()); } else { return Err(format_err!( "expected string, found {:?} in {}", raw_item, self.path.display(), )); } } } else { return Err(format_err!( "expected array, found {:?} in {}", raw_value, self.path.display(), )); } } Ok(temps) } fn raw_string_array_mut<'a, 'b>( &mut self, key: &'a Key<'b>, ) -> Result<&mut Array> { let array_value = self .doc .as_table_mut() .entry(key.key) .or_insert(Item::Value(Value::Array(Array::default()))); match array_value.as_array_mut() { Some(array) => Ok(array), None => Err(format_err!( "expected array for {} in {}", key, self.path.display(), )), } } pub fn add_to_string_array(&mut self, key: &Key<'_>, value: &str) -> Result<()> { let raw_array = self.raw_string_array_mut(key)?; for raw_item in raw_array.iter() { if raw_item.as_str() == Some(value) { return Ok(()); } } raw_array.push(value).map_err(|_| { format_err!("cannot append to {} because value types don't match", key) })?; raw_array.fmt(); Ok(()) } pub fn remove_from_string_array( &mut self, key: &Key<'_>, value: &str, ) -> Result<()> { let raw_array = self.raw_string_array_mut(key)?; let mut indices = vec![]; for (idx, raw_item) in raw_array.iter().enumerate() { if raw_item.as_str() == Some(value) { indices.push(idx); } } for idx in indices.iter().rev().cloned() { raw_array.remove(idx); } raw_array.fmt(); Ok(()) } } #[test] fn temporaries_can_be_added_and_removed() { let temp = tempfile::Builder::new() .prefix("dbcrossbar") .suffix(".toml") .tempfile() .unwrap(); let path = temp.path(); let mut config = Configuration::from_path(&path).unwrap(); let key = Key::global("temporary"); assert_eq!(config.temporaries().unwrap(), Vec::<String>::new()); config.add_to_string_array(&key, "s3://example/").unwrap(); assert_eq!(config.temporaries().unwrap(), &["s3://example/".to_owned()]); config.write().unwrap(); config = Configuration::from_path(&path).unwrap(); assert_eq!(config.temporaries().unwrap(), &["s3://example/".to_owned()]); config .remove_from_string_array(&key, "s3://example/") .unwrap(); assert_eq!(config.temporaries().unwrap(), Vec::<String>::new()); }
use failure::Fail; use std::{ env, fmt, fs::{create_dir_all, File}, io::{self, Read}, path::{Path, PathBuf}, }; use toml_edit::{Array, Document, Item, Value}; use crate::common::*; #[cfg(not(target_os = "macos"))] fn system_config_dir() -> Option<PathBuf> { dirs::config_dir() } #[cfg(target_os = "macos")] fn system_config_dir() -> Option<PathBuf> { if let Some(preference_dir) = dirs::preference_dir() { let old_config_dir = preference_dir.join("dbcrossbar"); if old_config_dir.is_dir() { use std::sync::Once; static ONCE: Once = Once::new(); ONCE.call_once(|| { if let Some(system_config_dir) = dirs::config_dir() { let new_config_dir = system_config_dir.join("dbcrossbar"); eprintln!( "DEPRECATION WARNING: Please move `{}` to `{}`", old_config_dir.display(), new_config_dir.display(), ); } }); return Some(preference_dir); } } dirs::config_dir() } pub(crate) fn config_dir() -> Result<PathBuf> { match env::var_os("DBCROSSBAR_CONFIG_DIR") { Some(dir) => Ok(PathBuf::from(dir)), None => Ok(system_config_dir() .ok_or_else(|| format_err!("could not find user config dir"))? .join("dbcrossbar")), } } pub(crate) fn config_file() -> Result<PathBuf> { Ok(config_dir()?.join("dbcrossbar.toml")) } #[derive(Debug)] pub struct Key<'a> { key: &'a str, } impl Key<'_> { pub fn temporary() -> Key<'static> { Self::global("temporary") } pub(crate) fn global(key: &str) -> Key<'_> { Key { key } } } impl<'a> fmt::Display for Key<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.key.fmt(f) } } #[derive(Debug)] pub struct Configuration { path: PathBuf, doc: Document, } impl Configuration { pub fn try_default() -> Result<Self> { Self::from_path(&config_file()?) } pub(crate) fn from_path(path: &Path) -> Result<Self> { match File::open(&path) { Ok(rdr) => { Ok(Self::from_reader(path.to_owned(), rdr).with_context(|_| { format!("could not read file {}", path.display()) })?) } Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(Self { path: path.to_owned(), doc: Document::default(), }), Err(err) => Err(err .context(format!("could not open file {}", path.display())) .into()), } } fn from_reader<R>(path: PathBuf, mut rdr: R) -> Result<Self> where R: Read + 'static, { let mut buf = String::new(); rdr.read_to_string(&mut buf)?; let doc = buf.parse::<Document>()?; Ok(Self { path, doc }) } pub fn write(&self) -> Result<()> { let parent = self.path.parent().ok_or_else(|| { format_err!("cannot find parent directory of {}", self.path.display()) })?; create_dir_all(&parent) .with_context(|_| format!("cannot create {}", parent.display()))?; let data = self.doc.to_string_in_original_order(); let mut f = File::create(&self.path) .with_context(|_| format!("cannot create {}", self.path.display()))?; f.write_all(data.as_bytes()) .with_context(|_| format!("error writing to {}", self.path.display()))?; f.flush() .with_context(|_| format!("error writing to {}", self.path.display()))?; Ok(()) } pub fn temporaries(&self) -> Result<Vec<String>> { self.string_array(&Key::global("temporary")) } fn string_array(&self, key: &Key<'_>) -> Result<Vec<String>> { let mut temps = vec![]; if let Some(raw_value) = self.doc.as_table().get(key.key) { if let Some(raw_array) = raw_value.as_array() { for raw_item in raw_array.iter() { if let Some(temp) = raw_item.as_str() { temps.push(temp.to_owned()); } else { return Err(format_err!( "expected string, found {:?} in {}", raw_item, self.path.display(), )); } } } else { return Err(format_err!( "expected array, found {:?} in {}", raw_value, self.path.display(), )); } } Ok(temps) } fn raw_string_array_mut<'a, 'b>( &mut self, key: &'a Key<'b>, ) -> Result<&mut Array> { let array_value = self .doc .as_table_mut() .entry(key.key) .or_insert(Item::Value(Value::Array(Array::default()))); match array_value.as_array_mut() { Some(array) => Ok(array), None => Err(format_err!( "expected array for {} in {}", key, self.path.display(), )), } } pub fn add_to_string_array(&mut self, key: &Key<'_>, value: &str) -> Result<()> { let raw_array = self.raw_string_array_mut(key)?; for raw_item in raw_array.iter() {
e value types don't match", key) })?; raw_array.fmt(); Ok(()) } pub fn remove_from_string_array( &mut self, key: &Key<'_>, value: &str, ) -> Result<()> { let raw_array = self.raw_string_array_mut(key)?; let mut indices = vec![]; for (idx, raw_item) in raw_array.iter().enumerate() { if raw_item.as_str() == Some(value) { indices.push(idx); } } for idx in indices.iter().rev().cloned() { raw_array.remove(idx); } raw_array.fmt(); Ok(()) } } #[test] fn temporaries_can_be_added_and_removed() { let temp = tempfile::Builder::new() .prefix("dbcrossbar") .suffix(".toml") .tempfile() .unwrap(); let path = temp.path(); let mut config = Configuration::from_path(&path).unwrap(); let key = Key::global("temporary"); assert_eq!(config.temporaries().unwrap(), Vec::<String>::new()); config.add_to_string_array(&key, "s3://example/").unwrap(); assert_eq!(config.temporaries().unwrap(), &["s3://example/".to_owned()]); config.write().unwrap(); config = Configuration::from_path(&path).unwrap(); assert_eq!(config.temporaries().unwrap(), &["s3://example/".to_owned()]); config .remove_from_string_array(&key, "s3://example/") .unwrap(); assert_eq!(config.temporaries().unwrap(), Vec::<String>::new()); }
if raw_item.as_str() == Some(value) { return Ok(()); } } raw_array.push(value).map_err(|_| { format_err!("cannot append to {} becaus
function_block-random_span
[ { "content": "/// Generate the `COPY ... FROM ...` SQL we'll pass to `copy_in`. `data_format`\n\n/// should be something like `\"CSV HRADER\"` or `\"BINARY\"`.\n\n///\n\n/// We have a separate function for generating this because we'll use it for\n\n/// multiple `COPY` statements.\n\nfn copy_from_sql(table: &PgCreateTable, data_format: &str) -> Result<String> {\n\n let mut copy_sql_buff = vec![];\n\n writeln!(&mut copy_sql_buff, \"COPY {} (\", table.name.quoted())?;\n\n for (idx, col) in table.columns.iter().enumerate() {\n\n if idx + 1 == table.columns.len() {\n\n writeln!(&mut copy_sql_buff, \" {}\", Ident(&col.name))?;\n\n } else {\n\n writeln!(&mut copy_sql_buff, \" {},\", Ident(&col.name))?;\n\n }\n\n }\n\n writeln!(&mut copy_sql_buff, \") FROM STDIN WITH {}\", data_format)?;\n\n let copy_sql = str::from_utf8(&copy_sql_buff)\n\n .expect(\"generated SQL should always be UTF-8\")\n\n .to_owned();\n\n Ok(copy_sql)\n\n}\n\n\n\n/// Given `stream` containing CSV data, plus a the URL and table_name for a\n\n/// destination, as well as `\"COPY FROM\"` SQL, copy the data into the specified\n\n/// destination.\n", "file_path": "dbcrossbarlib/src/drivers/postgres/write_local_data.rs", "rank": 0, "score": 369015.41563082224 }, { "content": "/// Given a line of `aws s3 ls` output, extract the path.\n\nfn path_from_line(line: &str) -> Result<String> {\n\n lazy_static! {\n\n static ref RE: Regex = Regex::new(r#\"^[-0-9]+ [:0-9]+ +[0-9]+ ([^\\r\\n]+)\"#)\n\n .expect(\"invalid regex in source\");\n\n }\n\n let cap = RE\n\n .captures(line)\n\n .ok_or_else(|| format_err!(\"cannot parse S3 ls output: {:?}\", line))?;\n\n Ok(cap[1].to_owned())\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/clouds/aws/s3/ls.rs", "rank": 2, "score": 310524.6688510113 }, { "content": "#[derive(Deserialize)]\n\n#[serde(transparent)]\n\nstruct RowsJson(HashMap<String, Vec<Value>>);\n\n\n\nimpl RowsJson {\n\n /// If we only have a single key in our `HashMap`, return the corresponding value.\n\n fn into_rows(self) -> Result<Vec<Value>> {\n\n if self.0.len() == 1 {\n\n Ok(self\n\n .0\n\n .into_iter()\n\n .next()\n\n .expect(\"checked for exactly one value, didn't find it\")\n\n .1)\n\n } else {\n\n Err(format_err!(\n\n \"found multiple keys in Shopify response: {}\",\n\n self.0.keys().join(\",\")\n\n ))\n\n }\n\n }\n\n}\n", "file_path": "dbcrossbarlib/src/drivers/shopify/local_data.rs", "rank": 3, "score": 285221.9327160282 }, { "content": "/// Look up an environment variable by name, returning an error if it does not exist.\n\nfn var(name: &str) -> Result<String> {\n\n match try_var(name)? {\n\n Some(value) => Ok(value),\n\n None => Err(format_err!(\n\n \"expected environment variable {} to be set\",\n\n name,\n\n )),\n\n }\n\n}\n\n\n\n/// Load credentials stored in a file.\n", "file_path": "dbcrossbarlib/src/credentials.rs", "rank": 4, "score": 279074.77776419785 }, { "content": "/// Look up an environment variable by name, returning `Ok(None)` if it does not\n\n/// exist.\n\nfn try_var(name: &str) -> Result<Option<String>> {\n\n match env::var(name) {\n\n Ok(value) => Ok(Some(value)),\n\n Err(env::VarError::NotPresent) => Ok(None),\n\n Err(env::VarError::NotUnicode(..)) => Err(format_err!(\n\n \"environment variable {} cannot be converted to UTF-8\",\n\n name,\n\n )),\n\n }\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/credentials.rs", "rank": 5, "score": 267530.22396886325 }, { "content": "/// Make sure a table name is legal for PostgreSQL.\n\n///\n\n/// This will use an valid-looking table name if it can find one somewhere in\n\n/// the string, or it will return a default value.\n\nfn sanitize_table_name(table_name: &str) -> Result<String> {\n\n lazy_static! {\n\n static ref RE: Regex = Regex::new(\n\n r\"(?x)\n\n ([_a-zA-Z][_a-zA-Z0-9]*\\.)?\n\n ([_a-zA-Z][_a-zA-Z0-9]*)\n\n $\"\n\n )\n\n .expect(\"could not compile regex in source\");\n\n }\n\n if let Some(cap) = RE.captures(table_name) {\n\n Ok(cap[0].to_owned())\n\n } else {\n\n // Just use a generic table name.\n\n Ok(\"data\".to_owned())\n\n }\n\n}\n", "file_path": "dbcrossbarlib/src/drivers/postgres_sql/mod.rs", "rank": 6, "score": 263174.85666585446 }, { "content": "/// Parse a JSON value and write it out as a PostgreSQL binary value. This works\n\n/// for any type implementing `FromJsonValue` and `WriteBinary`. More\n\n/// complicated cases will need to do this manually.\n\nfn write_json_as_binary<T, W>(wtr: &mut W, json: &Value) -> Result<()>\n\nwhere\n\n T: FromJsonValue + WriteBinary,\n\n W: Write,\n\n{\n\n let value = T::from_json_value(json)?;\n\n value.write_binary(wtr)\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/drivers/postgres/csv_to_binary/mod.rs", "rank": 7, "score": 252037.10806113842 }, { "content": "/// Remove the \"dataset/\" prefix from `id`.\n\nfn strip_id_prefix<R: Resource>(id: &Id<R>) -> &str {\n\n // For any given `Resource` type `R`, we know the actual ID prefix, so we\n\n // can strip it like this.\n\n &id.as_str()[R::id_prefix().len()..]\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/drivers/bigml/local_data.rs", "rank": 8, "score": 246522.83703041537 }, { "content": "/// Convert a cell to PostgreSQL `BINARY` format.\n\nfn cell_to_binary(wtr: &mut BufferedWriter, col: &PgColumn, cell: &str) -> Result<()> {\n\n if cell.is_empty() && col.is_nullable {\n\n // We found an empty string in the CSV and this column is\n\n // nullable, so represent it as an SQL `NULL`. If the column\n\n // isn't nullable, then somebody else will have to figure out\n\n // if they can do anything with the empty string.\n\n wtr.write_i32::<NE>(-1)?;\n\n } else {\n\n match &col.data_type {\n\n PgDataType::Array {\n\n dimension_count,\n\n ty,\n\n } => {\n\n array_to_binary(wtr, *dimension_count, ty, cell)?;\n\n }\n\n PgDataType::Scalar(ty) => {\n\n scalar_to_binary(wtr, ty, cell)?;\n\n }\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/drivers/postgres/csv_to_binary/mod.rs", "rank": 9, "score": 232064.2902679389 }, { "content": "/// Convert `s` into a hexadecimal digest using a hash function.\n\n///\n\n/// The details of this hash function don't matter. We only care that it returns\n\n/// something that's safe to include in a file name, and that has an extremely\n\n/// low probability of colliding.\n\nfn string_to_hex_digest(s: &str) -> String {\n\n let mut hasher = Sha256::new();\n\n hasher.update(s);\n\n let bytes = hasher.finalize();\n\n let mut out = String::with_capacity(2 * bytes.len());\n\n for b in bytes {\n\n write!(&mut out, \"{:02x}\", b).expect(\"write should never fail\");\n\n }\n\n out\n\n}\n\n\n\n/// The path to the file where we store our OAuth2 tokens.\n\n///\n\n/// This should be unique per `token_id` (at least with extremely high probability).\n\nasync fn token_file_path(token_id: &str) -> Result<PathBuf> {\n\n let data_local_dir = dirs::data_local_dir().ok_or_else(|| {\n\n format_err!(\"cannot find directory to store authentication keys\")\n\n })?;\n\n // `yup_oauth2` will fail with a cryptic error if the containing directory\n\n // doesn't exist.\n", "file_path": "dbcrossbarlib/src/clouds/gcloud/auth.rs", "rank": 10, "score": 219194.3089187142 }, { "content": "/// Specify the the location of data or a schema.\n\npub trait Locator: fmt::Debug + fmt::Display + Send + Sync + 'static {\n\n /// Provide a mechanism for casting a `dyn Locator` back to the underlying,\n\n /// concrete locator type using Rust's `Any` type.\n\n ///\n\n /// See [this StackOverflow question][so] for a discussion of the technical\n\n /// details, and why we need a `Locator::as_any` method to use `Any`.\n\n ///\n\n /// This is a bit of a sketchy feature to provide, but we provide it for use\n\n /// with `supports_write_remote_data` and `write_remote_data`, which are\n\n /// used for certain locator pairs (i.e., Google Cloud Storage and BigQuery)\n\n /// to bypass our normal `local_data` and `write_local_data` transfers and\n\n /// use an external, optimized transfer method (such as direct loads from\n\n /// Google Cloud Storage into BigQuery).\n\n ///\n\n /// This should always be implemented as follows:\n\n ///\n\n /// ```no_compile\n\n /// impl Locator for MyLocator {\n\n /// fn as_any(&self) -> &dyn Any {\n\n /// self\n", "file_path": "dbcrossbarlib/src/locator.rs", "rank": 11, "score": 208991.2421188793 }, { "content": "/// All known drivers.\n\npub fn all_drivers() -> &'static [Box<dyn LocatorDriver>] {\n\n &KNOWN_DRIVERS[..]\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/drivers/mod.rs", "rank": 12, "score": 197886.37594838574 }, { "content": "/// Given a slice of bytes, determine if it contains a complete set of CSV\n\n/// headers, and if so, return their length.\n\nfn csv_header_length(data: &[u8]) -> Result<Option<usize>> {\n\n // We could try to use the `csv` crate for this, but the `csv` crate will\n\n // go to great lengths to recover from malformed CSV files, so it's not\n\n // very useful for detecting whether we have a complete header line.\n\n if let Some(pos) = data.iter().position(|b| *b == b'\\n') {\n\n if data[..pos].iter().any(|b| *b == b'\"') {\n\n Err(format_err!(\n\n \"cannot yet concatenate CSV streams with quoted headers\"\n\n ))\n\n } else {\n\n Ok(Some(pos + 1))\n\n }\n\n } else {\n\n Ok(None)\n\n }\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/concat.rs", "rank": 13, "score": 196898.67593449482 }, { "content": "/// Look up a specifc driver by `Locator` scheme.\n\npub fn find_driver(\n\n scheme: &str,\n\n enable_unstable: bool,\n\n) -> Result<&'static dyn LocatorDriver> {\n\n KNOWN_DRIVERS_BY_SCHEME\n\n .get(scheme)\n\n .copied()\n\n .filter(|&d| !d.is_unstable() || enable_unstable)\n\n .ok_or_else(|| format_err!(\"unknown locator scheme {:?}\", scheme))\n\n}\n", "file_path": "dbcrossbarlib/src/drivers/mod.rs", "rank": 14, "score": 196109.70468879747 }, { "content": "/// Write the specified value.\n\nfn write_json_value<W: Write>(\n\n wtr: &mut W,\n\n data_type: &DataType,\n\n value: &Value,\n\n) -> Result<()> {\n\n if data_type.serializes_as_json_for_csv() && !value.is_null() {\n\n serde_json::to_writer(wtr, value)?;\n\n } else {\n\n match value {\n\n // Write `null` as an empty CSV field.\n\n Value::Null => {}\n\n\n\n // Write booleans using our standard convention.\n\n Value::Bool(true) => write!(wtr, \"t\")?,\n\n Value::Bool(false) => write!(wtr, \"f\")?,\n\n\n\n // Numbers and strings can be written as-is.\n\n Value::Number(n) => write!(wtr, \"{}\", n)?,\n\n Value::String(s) => write!(wtr, \"{}\", s)?,\n\n\n", "file_path": "dbcrossbarlib/src/drivers/shopify/json_to_csv.rs", "rank": 15, "score": 193171.9229513635 }, { "content": "fn parse_locator(s: &str, enable_unstable: bool) -> Result<BoxLocator> {\n\n // Parse our locator into a URL-style scheme and the rest.\n\n lazy_static! {\n\n static ref SCHEME_RE: Regex =\n\n Regex::new(\"^[A-Za-z][-A-Za-z0-9+.]*:\").expect(\"invalid regex in source\");\n\n }\n\n let cap = SCHEME_RE\n\n .captures(s)\n\n .ok_or_else(|| format_err!(\"cannot parse locator: {:?}\", s))?;\n\n let scheme = &cap[0];\n\n\n\n // Select an appropriate locator type.\n\n let driver = find_driver(scheme, enable_unstable)?;\n\n driver.parse(s)\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/locator.rs", "rank": 16, "score": 191742.2035574998 }, { "content": "CREATE TEMP FUNCTION ImportJson_{idx}(input STRING)\n\nRETURNS ARRAY<{bq_type}>\n\nAS ((\n\n SELECT ARRAY_AGG(\n\n COALESCE(\n\n SAFE.PARSE_DATETIME('%Y-%m-%d %H:%M:%E*S', e),\n\n PARSE_DATETIME('%Y-%m-%dT%H:%M:%E*S', e)\n\n )\n\n )\n\n FROM UNNEST(ImportJsonHelper_{idx}(input)) AS e\n\n));\n\n\"#,\n\n idx = idx,\n\n bq_type = elem_ty,\n\n )?;\n\n }\n\n\n\n BqDataType::Array(_)\n\n | BqDataType::NonArray(BqNonArrayDataType::Struct(_)) => {\n\n generate_import_udf(self, idx, f)?;\n", "file_path": "dbcrossbarlib/src/drivers/bigquery_shared/column.rs", "rank": 17, "score": 173858.96758535085 }, { "content": "#[test]\n\nfn parses_typescript_and_converts_to_data_type() -> Result<(), main_error::MainError> {\n\n let input = r#\"\n", "file_path": "dbcrossbarlib/src/drivers/dbcrossbar_ts/ast.rs", "rank": 18, "score": 169357.23654057688 }, { "content": "#[test]\n\nfn find_schema() {\n\n let storage = TemporaryStorage::new(vec![\n\n \"s3://example/\".to_string(),\n\n \"gs://example/1/\".to_string(),\n\n \"gs://example/2/\".to_string(),\n\n ]);\n\n assert_eq!(storage.find_scheme(\"s3:\"), Some(\"s3://example/\"));\n\n assert_eq!(storage.find_scheme(\"gs:\"), Some(\"gs://example/1/\"));\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/temporary_storage.rs", "rank": 19, "score": 168827.2625854212 }, { "content": "#[test]\n\nfn path_from_line_returns_entire_path() {\n\n let examples = &[\n\n (\"2013-09-02 21:37:53 10 a.txt\", \"a.txt\"),\n\n (\"2013-09-02 21:37:53 2863288 foo.zip\", \"foo.zip\"),\n\n (\n\n \"2013-09-02 21:32:57 23 foo/bar/.baz/a\",\n\n \"foo/bar/.baz/a\",\n\n ),\n\n ];\n\n for &(line, rel_path) in examples {\n\n assert_eq!(path_from_line(line).unwrap(), rel_path);\n\n }\n\n}\n", "file_path": "dbcrossbarlib/src/clouds/aws/s3/ls.rs", "rank": 20, "score": 168325.28763072708 }, { "content": "#[test]\n\nfn locator_from_str_to_string_roundtrip() {\n\n let locators = vec![\n\n \"bigquery:my_project:my_dataset.my_table\",\n\n \"bigquery-schema:dir/my_table.json\",\n\n \"bigml:dataset\",\n\n \"bigml:datasets\",\n\n \"bigml:dataset/abc123\",\n\n \"bigml:source\",\n\n \"bigml:sources\",\n\n \"csv:file.csv\",\n\n \"csv:dir/\",\n\n \"dbcrossbar-schema:file.json\",\n\n \"dbcrossbar-ts:file %231 20%25.ts#Type\",\n\n \"gs://example-bucket/tmp/\",\n\n \"postgres://localhost:5432/db#my_table\",\n\n \"postgres-sql:dir/my_table.sql\",\n\n \"s3://example/my-dir/\",\n\n \"shopify://example.myshopify.com/admin/api/2020-04/orders.json\",\n\n ];\n\n for locator in locators.into_iter() {\n", "file_path": "dbcrossbarlib/src/locator.rs", "rank": 21, "score": 166432.3710849884 }, { "content": "/// Get a typed header, and return an error if it isn't present.\n\nfn get_header<H>(response: &reqwest::Response) -> Result<H>\n\nwhere\n\n H: Header,\n\n{\n\n response\n\n .headers()\n\n .typed_try_get::<H>()\n\n .with_context(|_| format!(\"error parsing {}\", H::name()))?\n\n .ok_or_else(|| format_err!(\"expected {} header\", H::name()))\n\n}\n\n\n\n/// An iterator which returns ranges for each chunk in a file.\n", "file_path": "dbcrossbarlib/src/clouds/gcloud/storage/download_file.rs", "rank": 23, "score": 163242.87343301298 }, { "content": "#[derive(Clone, Debug, Deserialize)]\n\n#[serde(deny_unknown_fields)]\n\nstruct BigMlDestinationArguments {\n\n /// The name of the source or dataset to create.\n\n name: Option<String>,\n\n\n\n /// The default optype to use for text fields.\n\n optype_for_text: Option<Optype>,\n\n\n\n /// Tags to apply to the resources we create.\n\n #[serde(default)]\n\n tags: Vec<String>,\n\n}\n\n\n\n/// Implementation of `write_local_data`, but as a real `async` function.\n\npub(crate) async fn write_local_data_helper(\n\n ctx: Context,\n\n dest: BigMlLocator,\n\n mut data: BoxStream<CsvStream>,\n\n shared_args: SharedArguments<Unverified>,\n\n dest_args: DestinationArguments<Unverified>,\n\n) -> Result<BoxStream<BoxFuture<BoxLocator>>> {\n", "file_path": "dbcrossbarlib/src/drivers/bigml/write_local_data.rs", "rank": 24, "score": 162009.89775555374 }, { "content": "/// Generate SQL to perform an UPSERT from `src_table_name` into `dest_table`\n\n/// using `upsert_keys`.\n\nfn upsert_sql(\n\n src_table: &PgCreateTable,\n\n dest_table: &PgCreateTable,\n\n upsert_keys: &[String],\n\n) -> Result<String> {\n\n // Figure out which of our columns are \"value\" (non-key) columns.\n\n let value_keys = columns_to_update_for_upsert(dest_table, upsert_keys)?;\n\n\n\n // TODO: Do we need to check for NULLable key columns which might\n\n // produce duplicate rows on upsert, like we do for BigQuery?\n\n\n\n Ok(format!(\n\n r#\"\n\nINSERT INTO {dest_table} ({all_columns}) (\n\n SELECT {all_columns} FROM {src_table}\n\n)\n\nON CONFLICT ({key_columns})\n\nDO UPDATE SET\n\n {value_updates}\n\n\"#,\n", "file_path": "dbcrossbarlib/src/drivers/postgres/write_local_data.rs", "rank": 25, "score": 160779.70188707754 }, { "content": "/// Generate the SQL needed to perform an upsert.\n\n///\n\n/// This will destructively modify and then delete `temp_table`.\n\nfn upsert_sql(\n\n temp_table: &PgCreateTable,\n\n dest_table: &PgCreateTable,\n\n upsert_keys: &[String],\n\n) -> Result<Vec<String>> {\n\n let value_cols = columns_to_update_for_upsert(dest_table, upsert_keys)?;\n\n let dest_table_name = dest_table.name.quoted();\n\n let temp_table_name = temp_table.name.quoted();\n\n let keys_match = upsert_keys\n\n .iter()\n\n .map(|k| {\n\n format!(\n\n \"{dest_table}.{name} = {temp_table}.{name}\",\n\n name = Ident(&k),\n\n dest_table = dest_table_name,\n\n temp_table = temp_table_name,\n\n )\n\n })\n\n .join(\" AND\\n \");\n\n Ok(vec![\n", "file_path": "dbcrossbarlib/src/drivers/redshift/write_remote_data.rs", "rank": 26, "score": 160774.97231162226 }, { "content": "#[test]\n\nfn nested_array_conversions() {\n\n let original_ty =\n\n DataType::Array(Box::new(DataType::Array(Box::new(DataType::Int32))));\n\n let pg_ty = PgDataType::from_data_type(&original_ty).unwrap();\n\n assert_eq!(\n\n pg_ty,\n\n PgDataType::Array {\n\n dimension_count: 2,\n\n ty: PgScalarDataType::Int,\n\n },\n\n );\n\n let portable_ty = pg_ty.to_data_type().unwrap();\n\n assert_eq!(portable_ty, original_ty);\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/drivers/postgres_shared/data_type.rs", "rank": 27, "score": 159170.63954712803 }, { "content": "#[test]\n\nfn nested_arrays() {\n\n let input = DataType::Array(Box::new(DataType::Array(Box::new(DataType::Array(\n\n Box::new(DataType::Int32),\n\n )))));\n\n\n\n // What we expect when loading from a CSV file.\n\n let bq = BqDataType::for_data_type(&input, Usage::CsvLoad).unwrap();\n\n assert_eq!(format!(\"{}\", bq), \"STRING\");\n\n\n\n // What we expect in the final BigQuery table.\n\n let bq = BqDataType::for_data_type(&input, Usage::FinalTable).unwrap();\n\n assert_eq!(\n\n format!(\"{}\", bq),\n\n \"ARRAY<STRUCT<ARRAY<STRUCT<ARRAY<INT64>>>>>\"\n\n );\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/drivers/bigquery_shared/data_type/mod.rs", "rank": 28, "score": 159170.63954712803 }, { "content": "#[test]\n\nfn chunk_ranges_returns_sequential_ranges() {\n\n let ranges = chunk_ranges(10, 25).collect::<Vec<_>>();\n\n assert_eq!(ranges, &[0..10, 10..20, 20..25]);\n\n}\n", "file_path": "dbcrossbarlib/src/clouds/gcloud/storage/download_file.rs", "rank": 29, "score": 156041.17067386303 }, { "content": "/// Write a JavaScript expression that will transform `input_expr` of\n\n/// `intput_type` into a `STRING` containing serialized JSON data. Only applies\n\n/// to non-array types.\n\nfn write_non_array_transform_expr(\n\n input_expr: &str,\n\n input_type: &BqNonArrayDataType,\n\n indent: IndentLevel,\n\n f: &mut dyn Write,\n\n) -> Result<()> {\n\n match input_type {\n\n BqNonArrayDataType::Bool\n\n | BqNonArrayDataType::Float64\n\n | BqNonArrayDataType::Int64\n\n | BqNonArrayDataType::Numeric\n\n | BqNonArrayDataType::String\n\n | BqNonArrayDataType::Timestamp => {\n\n write!(f, \"{}\", input_expr)?;\n\n }\n\n\n\n // BigQuery represents DATE (which has no time or timezone) as a\n\n // JavaScript `Date` with a timezone of `Z`. So we need to fix it.\n\n BqNonArrayDataType::Date => {\n\n write!(f, \"{}.toISOString().split('T')[0]\", input_expr)?;\n", "file_path": "dbcrossbarlib/src/drivers/bigquery_shared/export_udf.rs", "rank": 30, "score": 155675.60464833028 }, { "content": "/// Write a JavaScript expression that will transform `input_expr` into a value\n\n/// of type `output_type`. Only applies to non-array types.\n\nfn write_non_array_transform_expr(\n\n input_expr: &str,\n\n output_type: &BqNonArrayDataType,\n\n indent: IndentLevel,\n\n f: &mut dyn Write,\n\n) -> Result<()> {\n\n match output_type {\n\n // These types can be directly converted to JSON.\n\n //\n\n // TODO: Check min and max `INT64` values, because need to be\n\n // represented as JSON strings, not JSON numbers.\n\n BqNonArrayDataType::Bool\n\n | BqNonArrayDataType::Float64\n\n | BqNonArrayDataType::Int64\n\n | BqNonArrayDataType::Numeric\n\n | BqNonArrayDataType::String => {\n\n write!(f, \"{}\", input_expr)?;\n\n }\n\n\n\n // These types all need to go through `Date`, even when they\n", "file_path": "dbcrossbarlib/src/drivers/bigquery_shared/import_udf.rs", "rank": 31, "score": 155671.36254987077 }, { "content": "fn run() -> Result<()> {\n\n // Set up standard Rust logging for third-party crates.\n\n env_logger::init();\n\n\n\n // Find our system SSL configuration, even if we're statically linked.\n\n openssl_probe::init_ssl_cert_env_vars();\n\n\n\n // Parse our command-line arguments.\n\n let opt = cmd::Opt::from_args();\n\n\n\n // Set up `slog`-based structured logging for our async code, because we\n\n // need to be able to untangle very complicated logs from many parallel\n\n // async tasks.\n\n let base_drain = opt.log_format.create_drain();\n\n let filtered = slog_envlogger::new(base_drain);\n\n let drain = slog_async::Async::new(filtered)\n\n .chan_size(64)\n\n // This may slow down application performance, even when `RUST_LOG` is\n\n // not set. But we've been seeing a lot of dropped messages lately, so\n\n // let's try it.\n", "file_path": "dbcrossbar/src/main.rs", "rank": 32, "score": 153009.39190820363 }, { "content": "/// Given a stream of streams CSV data, return another stream of CSV streams\n\n/// where the CSV data is approximately `chunk_size` long whenever possible.\n\npub fn rechunk_csvs(\n\n ctx: Context,\n\n chunk_size: usize,\n\n streams: BoxStream<CsvStream>,\n\n) -> Result<BoxStream<CsvStream>> {\n\n // Convert out input `BoxStream<CsvStream>` into a single, concatenated\n\n // synchronous `Read` object.\n\n let ctx = ctx.child(o!(\"streams_transform\" => \"rechunk_csvs\"));\n\n let input_csv_stream = concatenate_csv_streams(ctx.clone(), streams)?;\n\n let csv_rdr = SyncStreamReader::new(ctx.clone(), input_csv_stream.data);\n\n\n\n // Create a channel to which we can write `CsvStream` values once we've\n\n // created them.\n\n let (mut csv_stream_sender, csv_stream_receiver) =\n\n mpsc::channel::<Result<CsvStream>>(1);\n\n\n\n // Run a synchronous background worker thread that parsers our sync CSV\n\n // `Read`er into a stream of `CsvStream`s.\n\n let worker_ctx = ctx.clone();\n\n let worker_fut = spawn_blocking(move || -> Result<()> {\n", "file_path": "dbcrossbarlib/src/rechunk.rs", "rank": 33, "score": 151720.23971467206 }, { "content": "/// Write a JSON row to a CSV document.\n\nfn write_row<W: Write>(\n\n wtr: &mut csv::Writer<W>,\n\n schema: &Table,\n\n row: Value,\n\n buffer: &mut Vec<u8>,\n\n) -> Result<()> {\n\n // Convert our row to a JSON object.\n\n let obj = match row {\n\n Value::Object(obj) => obj,\n\n value => return Err(format_err!(\"expected JSON object, found {:?}\", value)),\n\n };\n\n\n\n // Look up each column and output it.\n\n for col in &schema.columns {\n\n let value = obj.get(&col.name).unwrap_or(&Value::Null);\n\n buffer.clear();\n\n write_json_value(buffer, &col.data_type, &value)?;\n\n if !col.is_nullable && buffer.is_empty() {\n\n return Err(format_err!(\n\n \"unexpected NULL value in column {:?}\",\n", "file_path": "dbcrossbarlib/src/drivers/shopify/json_to_csv.rs", "rank": 34, "score": 151311.76802570833 }, { "content": "/// A `Write` implementation that keeps track of how much data has been written\n\n/// so far. Note that if you wrap this in a buffered type like `csv::Writer`, it\n\n/// won't keep track of the data in `csv::Writer`'s buffer, only the data that\n\n/// has been flushed.\n\nstruct CountingWriter<W: Write> {\n\n /// Our writer.\n\n inner: W,\n\n /// The total data that we've written. This is wrapped in `Rc<Cell<_>>` so\n\n /// that is can be easily accessed from anywhere in the same thread even if\n\n /// the `CountingWriter` is completely owned by another type such as\n\n /// `csv::Writer`.\n\n total_written: Rc<Cell<usize>>,\n\n}\n\n\n\nimpl<W: Write> CountingWriter<W> {\n\n /// Create a new `CountingWriter` that wraps `inner`.\n\n fn new(inner: W) -> Self {\n\n Self {\n\n inner,\n\n total_written: Rc::new(Cell::new(0)),\n\n }\n\n }\n\n\n\n /// How much data has been written? This returns an `Rc<Cell<_>>` that will\n", "file_path": "dbcrossbarlib/src/rechunk.rs", "rank": 35, "score": 150228.18827178952 }, { "content": "/// Extra `Locator` methods that can only be called statically. These cannot\n\n/// accessed via a `Box<Locator>`.\n\npub trait LocatorStatic: Locator + Clone + FromStr<Err = Error> + Sized {\n\n /// Convert this locator into a polymorphic `BoxLocator` on the heap.\n\n fn boxed(self) -> BoxLocator {\n\n Box::new(self)\n\n }\n\n\n\n /// Return the \"scheme\" used to format this locator, e.g., `\"postgres:\"`.\n\n fn scheme() -> &'static str;\n\n\n\n /// Return a mask of `LocatorFeatures` supported by this `Locator` type.\n\n fn features() -> Features;\n\n\n\n /// Is this driver unstable?\n\n fn is_unstable() -> bool {\n\n false\n\n }\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/locator.rs", "rank": 36, "score": 148884.95305569714 }, { "content": "/// Create a new `tokio` runtime and use it to run `cmd_future` (which carries\n\n/// out whatever task we want to perform), and `worker_future` (which should\n\n/// have been created by `Context::create` or `Context::create_for_test`).\n\n///\n\n/// Return when at least one future has failed, or both futures have completed\n\n/// successfully.\n\n///\n\n/// This can be safely used from within a test, but it may only be called from a\n\n/// synchronous context.\n\n///\n\n/// If this hangs, make sure all `Context` values are getting dropped once the\n\n/// work is done.\n\npub fn run_futures_with_runtime(\n\n cmd_future: BoxFuture<()>,\n\n worker_future: BoxFuture<()>,\n\n) -> Result<()> {\n\n // Wait for both `cmd_fut` and `copy_fut` to finish, but bail out as soon\n\n // as either returns an error. This involves some pretty deep `tokio` magic:\n\n // If a background worker fails, then `copy_fut` will be automatically\n\n // dropped, or vice vera.\n\n let combined_fut = async move {\n\n try_join!(cmd_future, worker_future)?;\n\n let result: Result<()> = Ok(());\n\n result\n\n };\n\n\n\n // Pass `combined_fut` to our `tokio` runtime, and wait for it to finish.\n\n let mut runtime =\n\n tokio::runtime::Runtime::new().expect(\"Unable to create a runtime\");\n\n runtime.block_on(combined_fut.boxed())?;\n\n Ok(())\n\n}\n", "file_path": "dbcrossbarlib/src/tokio_glue.rs", "rank": 37, "score": 148731.7608172574 }, { "content": "#[async_trait]\n\ntrait CredentialsSource: fmt::Debug + fmt::Display + Send + Sync + 'static {\n\n /// Look up an appropriate set of credentials.\n\n async fn get_credentials(&self) -> Result<Option<Credentials>>;\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/credentials.rs", "rank": 38, "score": 148213.27407872424 }, { "content": "/// Interface to a locator driver. This exists because we Rust can't treat\n\n/// classes as objects, the way Ruby can. Instead, what we do is take classes\n\n/// that implement [`LocatorStatic`] and wrap them up in objects that implement\n\n/// the `LocatorDriver` interface.\n\npub trait LocatorDriver: Send + Sync + 'static {\n\n /// Return the \"scheme\" used to format this locator, e.g., `\"postgres:\"`.\n\n fn scheme(&self) -> &str;\n\n\n\n /// The name of this driver. The same as [`LocatorDriver::schema`], but\n\n /// without the trailing `:`.\n\n fn name(&self) -> &str {\n\n let scheme = self.scheme();\n\n assert!(scheme.ends_with(':'));\n\n &scheme[..scheme.len() - 1]\n\n }\n\n\n\n /// The features supported by this driver.\n\n fn features(&self) -> Features;\n\n\n\n /// Is this driver unstable?\n\n fn is_unstable(&self) -> bool;\n\n\n\n /// Parse a locator string and return a [`BoxLocator`].\n\n fn parse(&self, s: &str) -> Result<BoxLocator>;\n", "file_path": "dbcrossbarlib/src/locator.rs", "rank": 39, "score": 140596.53763556026 }, { "content": "/// Interpret a JSON value as `data_type` and write it out as a `BINARY` value.\n\nfn json_to_binary<W: Write>(\n\n wtr: &mut W,\n\n data_type: &PgScalarDataType,\n\n json: &Value,\n\n) -> Result<()> {\n\n match data_type {\n\n PgScalarDataType::Boolean => write_json_as_binary::<bool, W>(wtr, json),\n\n PgScalarDataType::Date => write_json_as_binary::<NaiveDate, W>(wtr, json),\n\n PgScalarDataType::Numeric => Err(format_err!(\n\n \"cannot use `numeric` arrays with PostgreSQL yet\",\n\n )),\n\n PgScalarDataType::Real => write_json_as_binary::<f32, W>(wtr, json),\n\n PgScalarDataType::DoublePrecision => write_json_as_binary::<f64, W>(wtr, json),\n\n PgScalarDataType::Geometry(srid) => {\n\n let geometry = Geometry::<f64>::from_json_value(json)?;\n\n let value = GeometryWithSrid {\n\n geometry: &geometry,\n\n srid: *srid,\n\n };\n\n value.write_binary(wtr)\n", "file_path": "dbcrossbarlib/src/drivers/postgres/csv_to_binary/mod.rs", "rank": 40, "score": 139976.69362027606 }, { "content": "#[test]\n\nfn handles_magic_types() -> Result<(), main_error::MainError> {\n\n let input = r#\"\n", "file_path": "dbcrossbarlib/src/drivers/dbcrossbar_ts/ast.rs", "rank": 41, "score": 132544.79441469087 }, { "content": "#[test]\n\nfn parses_shopify_schema() -> Result<(), main_error::MainError> {\n\n let file_string = include_str!(\"../../../../dbcrossbar/fixtures/shopify.ts\");\n\n let source_file =\n\n SourceFile::parse(\"shopify.ts\".to_owned(), file_string.to_owned())?;\n\n for def in &[\"Order\"] {\n\n source_file.definition_to_table(def)?;\n\n }\n\n Ok(())\n\n}\n", "file_path": "dbcrossbarlib/src/drivers/dbcrossbar_ts/ast.rs", "rank": 42, "score": 132544.79441469087 }, { "content": "DELETE FROM {temp_table}\n\nUSING {dest_table}\n\nWHERE {keys_match}\",\n\n dest_table = dest_table_name,\n\n temp_table = temp_table_name,\n\n keys_match = keys_match,\n\n ),\n\n format!(\n\n r\"-- Insert new rows into dest table.\n\nINSERT INTO {dest_table} ({all_columns}) (\n\n SELECT {all_columns}\n\n FROM {temp_table}\n\n)\",\n\n dest_table = dest_table_name,\n\n temp_table = temp_table_name,\n\n all_columns = dest_table.columns.iter().map(|c| Ident(&c.name)).join(\", \"),\n\n ),\n\n format!(r\"DROP TABLE {temp_table}\", temp_table = temp_table_name),\n\n ])\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/drivers/redshift/write_remote_data.rs", "rank": 43, "score": 131947.88989853775 }, { "content": "/// Given an S3 URL, get the URL for just the bucket itself.\n\nfn bucket_url(url: &Url) -> Result<Url> {\n\n let bucket = url\n\n .host()\n\n .ok_or_else(|| format_err!(\"could not find bucket name in {}\", url))?;\n\n let bucket_url = format!(\"s3://{}/\", bucket)\n\n .parse::<Url>()\n\n .context(\"could not parse S3 URL\")?;\n\n Ok(bucket_url)\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/clouds/aws/s3/ls.rs", "rank": 44, "score": 131797.22688635628 }, { "content": "#[derive(Debug)]\n\nstruct EnvMapping {\n\n key: &'static str,\n\n var: &'static str,\n\n optional: bool,\n\n}\n\n\n\nimpl EnvMapping {\n\n /// Fetch the value of `key` from `var`.\n\n fn required(key: &'static str, var: &'static str) -> Self {\n\n Self {\n\n key,\n\n var,\n\n optional: false,\n\n }\n\n }\n\n\n\n /// Fetch the value of `key` from `var`, if present.\n\n fn optional(key: &'static str, var: &'static str) -> Self {\n\n Self {\n\n key,\n", "file_path": "dbcrossbarlib/src/credentials.rs", "rank": 45, "score": 129101.31453822306 }, { "content": "#[derive(Debug)]\n\nstruct EnvCredentialsSource {\n\n mapping: Vec<EnvMapping>,\n\n}\n\n\n\nimpl EnvCredentialsSource {\n\n /// Create a new `EnvCredentialsSource`.\n\n ///\n\n /// `mapping` should contain at least one element. The first element must\n\n /// not be `optional`.\n\n fn new(mapping: Vec<EnvMapping>) -> Self {\n\n // Check our preconditions with assertions, since all callers will be\n\n // hard-coded in the source.\n\n assert!(!mapping.is_empty());\n\n assert!(!mapping[0].optional);\n\n Self { mapping }\n\n }\n\n}\n\n\n\nimpl fmt::Display for EnvCredentialsSource {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n", "file_path": "dbcrossbarlib/src/credentials.rs", "rank": 46, "score": 127513.31167994003 }, { "content": "#[derive(Debug)]\n\nstruct FileCredentialsSource {\n\n key: &'static str,\n\n path: PathBuf,\n\n}\n\n\n\nimpl FileCredentialsSource {\n\n /// Specify how to find credentials in a file. The contents of the file will\n\n /// be mapped to `key` in the credential.\n\n fn new(key: &'static str, path: PathBuf) -> Self {\n\n Self { key, path }\n\n }\n\n}\n\n\n\nimpl fmt::Display for FileCredentialsSource {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n writeln!(f, \"- The file {}\", self.path.display())\n\n }\n\n}\n\n\n\n#[async_trait]\n", "file_path": "dbcrossbarlib/src/credentials.rs", "rank": 47, "score": 127396.80840640047 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct Value {\n\n /// The actual value. This is normally represented as a string.\n\n ///\n\n /// This might also be a nested `Row` object, but we don't handle that yet.\n\n #[serde(rename = \"v\")]\n\n value: serde_json::Value,\n\n}\n\n\n\nimpl Value {\n\n /// Convert this value into a JSON value.\n\n fn to_json_value(&self, _ctx: &Context) -> Result<serde_json::Value> {\n\n Ok(self.value.clone())\n\n }\n\n}\n\n\n\n/// Run a query that should return a small number of records, and return them as\n\n/// a JSON string.\n\nasync fn query_all_json(\n\n ctx: &Context,\n\n project: &str,\n", "file_path": "dbcrossbarlib/src/clouds/gcloud/bigquery/queries.rs", "rank": 48, "score": 125923.14504642788 }, { "content": "/// A polymorphic log drain (which means we need to use `Box<dyn ...>`,\n\n/// because that's how Rust does runtime polymorphism).\n\ntype BoxDrain = Box<dyn Drain<Ok = (), Err = Never> + Send + 'static>;\n\n\n\n/// What log format we should use.\n\n#[derive(Debug, Copy, Clone, Eq, PartialEq)]\n\npub(crate) enum LogFormat {\n\n /// Pretty, indented logs.\n\n Indented,\n\n /// Single-line log entries with all keys on each line.\n\n Flat,\n\n /// JSON records.\n\n Json,\n\n}\n\n\n\nimpl LogFormat {\n\n /// Create an appropriate `Drain` for this log format.\n\n pub(crate) fn create_drain(self) -> BoxDrain {\n\n match self {\n\n Self::Indented => {\n\n let decorator = slog_term::TermDecorator::new().stderr().build();\n\n Box::new(slog_term::CompactFormat::new(decorator).build().fuse())\n", "file_path": "dbcrossbar/src/logging.rs", "rank": 49, "score": 124999.40760604112 }, { "content": "#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct QueryResults {\n\n /// The schema of our query results.\n\n schema: TableSchema,\n\n\n\n /// Rows returned from the query.\n\n rows: Vec<Row>,\n\n\n\n /// Has this query completed?\n\n job_complete: bool,\n\n}\n\n\n\nimpl QueryResults {\n\n fn to_json_objects(&self, ctx: &Context) -> Result<Vec<serde_json::Value>> {\n\n let objects = self\n\n .rows\n\n .iter()\n\n .map(|row| row.to_json_object(ctx, &self.schema.fields))\n\n .collect::<Result<Vec<serde_json::Value>>>()?;\n\n trace!(\n\n ctx.log(),\n\n \"rows as objects: {}\",\n\n serde_json::to_string(&objects).expect(\"should be able to serialize rows\"),\n\n );\n\n Ok(objects)\n\n }\n\n}\n\n\n\n/// A row returned in `QueryResults`.\n", "file_path": "dbcrossbarlib/src/clouds/gcloud/bigquery/queries.rs", "rank": 50, "score": 124390.79418305974 }, { "content": "#[derive(Clone, Copy, Debug, Eq, PartialEq)]\n\nstruct CallLimit {\n\n /// How much of our call limit have we used?\n\n used: u32,\n\n /// How much is remaining?\n\n limit: u32,\n\n}\n\n\n\nimpl CallLimit {\n\n /// Are we close enough to our call limit that we should chill out a bit?\n\n fn should_wait(self) -> bool {\n\n self.used.saturating_mul(2) >= self.limit\n\n }\n\n}\n\n\n\nimpl FromStr for CallLimit {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n if let Some(split_pos) = s.find('/') {\n\n let used = s[..split_pos]\n", "file_path": "dbcrossbarlib/src/drivers/shopify/local_data.rs", "rank": 51, "score": 123537.5059197968 }, { "content": "#[derive(Debug)]\n\nstruct ShopifyResponse {\n\n /// How much of our API have we used?\n\n call_limit: CallLimit,\n\n\n\n /// The URL of the next page of data.\n\n next_page_url: Option<Url>,\n\n\n\n /// Individual data rows.\n\n rows: Vec<Value>,\n\n}\n\n\n\n/// A Shopify \"call limit\", specifying how much of our API quota we've used.\n", "file_path": "dbcrossbarlib/src/drivers/shopify/local_data.rs", "rank": 52, "score": 123537.5059197968 }, { "content": "#[derive(Debug, Serialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct QueryResultsQuery {\n\n /// Geographic location. Mandatory outside of US and Europe.\n\n location: String,\n\n}\n\n\n\n/// Results of a query.\n", "file_path": "dbcrossbarlib/src/clouds/gcloud/bigquery/queries.rs", "rank": 53, "score": 122953.8313537859 }, { "content": "#[derive(Debug)]\n\nstruct ChunkRanges {\n\n /// The size of chunk we want to return.\n\n chunk_size: u64,\n\n /// The total length of our file.\n\n len: u64,\n\n /// The place to start our next range.\n\n next_start: u64,\n\n}\n\n\n\nimpl Iterator for ChunkRanges {\n\n type Item = ops::Range<u64>;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n if self.next_start < self.len {\n\n let end = min(self.next_start + self.chunk_size, self.len);\n\n let range = self.next_start..end;\n\n self.next_start = end;\n\n Some(range)\n\n } else {\n\n None\n\n }\n\n }\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/clouds/gcloud/storage/download_file.rs", "rank": 54, "score": 122942.15705326418 }, { "content": "#[derive(Debug, Serialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct UploadQuery {\n\n /// The type of the upload we're performing.\n\n upload_type: &'static str,\n\n\n\n /// Only accept the upload if the existing object has the specified\n\n /// generation number. Use 0 to specify a non-existant object.\n\n if_generation_match: i64,\n\n\n\n /// The name of the object we're creating.\n\n name: String,\n\n}\n\n\n\n/// Upload `data` as a file at `url`.\n\n///\n\n/// Docs: https://cloud.google.com/storage/docs/json_api/v1/objects/insert\n\n///\n\n/// TODO: Support https://cloud.google.com/storage/docs/performing-resumable-uploads.\n\npub(crate) async fn upload_file<'a>(\n\n ctx: &'a Context,\n\n data: BoxStream<BytesMut>,\n", "file_path": "dbcrossbarlib/src/clouds/gcloud/storage/upload_file.rs", "rank": 55, "score": 122942.15705326418 }, { "content": "#[derive(Debug, Serialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct DownloadQuery {\n\n /// What format should we return?\n\n alt: Alt,\n\n\n\n /// What object generation do we expect to download?\n\n if_generation_match: i64,\n\n}\n\n\n\n/// Download the file at the specified URL as a stream.\n\npub(crate) async fn download_file(\n\n ctx: &Context,\n\n item: &StorageObject,\n\n) -> Result<BoxStream<BytesMut>> {\n\n let file_url = item.to_url_string().parse::<Url>()?;\n\n debug!(ctx.log(), \"streaming from {}\", file_url);\n\n let (bucket, object) = parse_gs_url(&file_url)?;\n\n\n\n // Build our URL & common headers.\n\n let url = format!(\n\n \"https://storage.googleapis.com/storage/v1/b/{}/o/{}\",\n", "file_path": "dbcrossbarlib/src/clouds/gcloud/storage/download_file.rs", "rank": 56, "score": 122942.15705326418 }, { "content": "#[test]\n\nfn must_have_upsert_keys() {\n\n assert!(\"upsert-on:\".parse::<IfExists>().is_err());\n\n}\n", "file_path": "dbcrossbarlib/src/if_exists.rs", "rank": 57, "score": 122166.34010023126 }, { "content": "#[test]\n\nfn random_tag() {\n\n assert_eq!(TemporaryStorage::random_tag().len(), 10);\n\n}\n", "file_path": "dbcrossbarlib/src/temporary_storage.rs", "rank": 58, "score": 122135.35303314697 }, { "content": "#[test]\n\nfn data_type_roundtrip() {\n\n let data_types = vec![\n\n DataType::Array(Box::new(DataType::Text)),\n\n DataType::Bool,\n\n DataType::Date,\n\n DataType::Decimal,\n\n DataType::Float32,\n\n DataType::Float64,\n\n DataType::Int16,\n\n DataType::Int32,\n\n DataType::Int64,\n\n DataType::Json,\n\n DataType::Struct(vec![StructField {\n\n name: \"x\".to_owned(),\n\n is_nullable: false,\n\n data_type: DataType::Float32,\n\n }]),\n\n DataType::Text,\n\n DataType::TimestampWithoutTimeZone,\n\n DataType::TimestampWithTimeZone,\n", "file_path": "dbcrossbarlib/src/schema.rs", "rank": 59, "score": 121180.23704572642 }, { "content": "#[test]\n\nfn data_type_serialization_examples() {\n\n // Our serialization format is an external format, so let's write some tests\n\n // to make sure we don't change it accidentally.\n\n let examples = &[\n\n (\n\n DataType::Array(Box::new(DataType::Text)),\n\n json!({\"array\":\"text\"}),\n\n ),\n\n (DataType::Bool, json!(\"bool\")),\n\n (DataType::Date, json!(\"date\")),\n\n (DataType::Decimal, json!(\"decimal\")),\n\n (DataType::Float32, json!(\"float32\")),\n\n (DataType::Float64, json!(\"float64\")),\n\n (DataType::Int16, json!(\"int16\")),\n\n (DataType::Int32, json!(\"int32\")),\n\n (DataType::Int64, json!(\"int64\")),\n\n (DataType::Json, json!(\"json\")),\n\n (\n\n DataType::Struct(vec![StructField {\n\n name: \"x\".to_owned(),\n", "file_path": "dbcrossbarlib/src/schema.rs", "rank": 60, "score": 119672.37532169785 }, { "content": "#[test]\n\nfn to_json_handles_nested_keys() {\n\n use serde_json::json;\n\n let raw_args = &[\"a=b\", \"c.d=x\", \"c.e[]=y\", \"c[e][]=z\"];\n\n let args = DriverArguments::from_cli_args(raw_args).unwrap();\n\n assert_eq!(\n\n args.to_json().unwrap(),\n\n json!({\"a\": \"b\", \"c\": { \"d\": \"x\", \"e\": [\"y\", \"z\"] } }),\n\n );\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/driver_args.rs", "rank": 61, "score": 119167.52157809134 }, { "content": "#[test]\n\nfn from_str_parses_schemas() {\n\n let examples = &[\n\n (\"postgres://user:pass@host/db#table\", \"table\"),\n\n (\"postgres://user:pass@host/db#public.table\", \"public.table\"),\n\n (\n\n \"postgres://user:pass@host/db#testme1.table\",\n\n \"testme1.table\",\n\n ),\n\n ];\n\n for &(url, table_name) in examples {\n\n assert_eq!(\n\n PostgresLocator::from_str(url).unwrap().table_name,\n\n table_name.parse::<TableName>().unwrap(),\n\n );\n\n }\n\n}\n\n\n\nimpl Locator for PostgresLocator {\n\n fn as_any(&self) -> &dyn Any {\n\n self\n", "file_path": "dbcrossbarlib/src/drivers/postgres/mod.rs", "rank": 62, "score": 119108.04265761728 }, { "content": "#[test]\n\n#[ignore]\n\nfn bigquery_roundtrips_structs() {\n\n let _ = env_logger::try_init();\n\n let testdir = TestDir::new(\"dbcrossbar\", \"bigquery_roundtrips_structs\");\n\n let raw_src_path = testdir.src_path(\"fixtures/structs/struct.json\");\n\n let src = testdir.path(\"structs.csv\");\n\n let raw_data_type_path =\n\n testdir.src_path(\"fixtures/structs/struct-data-type.json\");\n\n let schema = testdir.path(\"structs-schema.json\");\n\n let bq_temp_ds = bq_temp_dataset();\n\n let gs_temp_dir = gs_test_dir_url(\"bigquery_roundtrips_structs\");\n\n let bq_table = bq_test_table(\"bigquery_roundtrips_structs\");\n\n\n\n // Use our example JSON to create a CSV file with two columns: One\n\n // containing our struct, and the other containing a single-element array\n\n // containing our struct.\n\n let raw_src = fs::read_to_string(&raw_src_path).unwrap();\n\n let src_data = format!(\n\n r#\"struct,structs\n\n\"{escaped}\",\"[{escaped}]\"\n\n\"#,\n", "file_path": "dbcrossbar/tests/cli/cp/bigquery.rs", "rank": 63, "score": 119048.85403284949 }, { "content": "/// Construct a URL from something we can convert to URL, and something that we\n\n/// can serialize as a query string.\n\nfn build_url<U, Query>(url: U, query: Query) -> Result<Url>\n\nwhere\n\n U: IntoUrl,\n\n Query: fmt::Debug + Serialize,\n\n{\n\n let mut url = url.into_url().context(\"could not parse URL\")?;\n\n let query_str = serde_urlencoded::to_string(&query)?;\n\n if !query_str.is_empty() {\n\n url.set_query(Some(&query_str));\n\n }\n\n Ok(url)\n\n}\n\n\n\n/// A Google Cloud error response.\n", "file_path": "dbcrossbarlib/src/clouds/gcloud/client.rs", "rank": 64, "score": 118482.07542254198 }, { "content": "#[test]\n\nfn crc32c_matches_gcloud() {\n\n // Check that `data` hashes to `expected`.\n\n let check = |data: &[u8], expected: u32| {\n\n let mut hasher = Hasher::new();\n\n hasher.update(data);\n\n assert_eq!(hasher.finish(), expected);\n\n };\n\n\n\n // These test cases are from https://tools.ietf.org/html/rfc3720#page-217\n\n // and https://github.com/google/crc32c/blob/master/src/crc32c_unittest.cc\n\n check(&[0u8; 32], 0x8a91_36aa);\n\n check(&[0xff; 32], 0x62a8_ab43);\n\n let mut buf = [0u8; 32];\n\n for i in 0u8..=31 {\n\n buf[usize::from(i)] = i;\n\n }\n\n check(&buf, 0x46dd_794e);\n\n for i in 0u8..=31 {\n\n buf[usize::from(i)] = 31 - i;\n\n }\n", "file_path": "dbcrossbarlib/src/clouds/gcloud/crc32c_stream.rs", "rank": 65, "score": 117746.31734392996 }, { "content": "/// Convert a JSON-syntax array (possibly nested) into a `BINARY` array.\n\nfn array_to_binary(\n\n wtr: &mut BufferedWriter,\n\n dimension_count: i32,\n\n data_type: &PgScalarDataType,\n\n cell: &str,\n\n) -> Result<()> {\n\n // TODO: For now, we can only handle single-dimensional arrays like\n\n // `[1,2,3]`. Multidimensional arrays would require us to figure out things\n\n // like `[[1,2], [3]]` and what order to serialize nested elements in.\n\n if dimension_count != 1 {\n\n return Err(format_err!(\n\n \"arrays with {} dimensions cannot yet be written to PostgreSQL\",\n\n dimension_count,\n\n ));\n\n }\n\n\n\n // Parse our cell into a JSON value.\n\n let json = serde_json::from_str(cell).context(\"cannot parse JSON\")?;\n\n let json_array = match json {\n\n Value::Array(json_array) => json_array,\n", "file_path": "dbcrossbarlib/src/drivers/postgres/csv_to_binary/mod.rs", "rank": 66, "score": 117721.94354576748 }, { "content": "/// Choose an appropriate `DataType`.\n\nfn pg_data_type(\n\n data_type: &str,\n\n _udt_schema: &str,\n\n udt_name: &str,\n\n) -> Result<PgDataType> {\n\n if data_type == \"ARRAY\" {\n\n // Array element types have their own naming convention, which appears\n\n // to be \"_\" followed by the internal udt_name version of PostgreSQL's\n\n // base types.\n\n let element_type = match udt_name {\n\n \"_bool\" => PgScalarDataType::Boolean,\n\n \"_date\" => PgScalarDataType::Date,\n\n \"_float4\" => PgScalarDataType::Real,\n\n \"_float8\" => PgScalarDataType::DoublePrecision,\n\n \"_int2\" => PgScalarDataType::Smallint,\n\n \"_int4\" => PgScalarDataType::Int,\n\n \"_int8\" => PgScalarDataType::Bigint,\n\n \"_text\" => PgScalarDataType::Text,\n\n \"_timestamp\" => PgScalarDataType::TimestampWithoutTimeZone,\n\n \"_timestamptz\" => PgScalarDataType::TimestampWithTimeZone,\n", "file_path": "dbcrossbarlib/src/drivers/postgres_shared/catalog.rs", "rank": 67, "score": 116805.78950949595 }, { "content": "#[test]\n\nfn scalar_conversions() {\n\n let original_ty = DataType::Int32;\n\n let pg_ty = PgDataType::from_data_type(&original_ty).unwrap();\n\n assert_eq!(pg_ty, PgDataType::Scalar(PgScalarDataType::Int));\n\n let portable_ty = pg_ty.to_data_type().unwrap();\n\n assert_eq!(portable_ty, original_ty);\n\n}\n\n\n\nimpl fmt::Display for PgDataType {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match self {\n\n PgDataType::Array {\n\n dimension_count,\n\n ty,\n\n } => {\n\n ty.fmt(f)?;\n\n for _ in 0..*dimension_count {\n\n write!(f, \"[]\")?;\n\n }\n\n Ok(())\n", "file_path": "dbcrossbarlib/src/drivers/postgres_shared/data_type.rs", "rank": 68, "score": 116800.87908338688 }, { "content": "#[test]\n\nfn strips_id_prefix() {\n\n use bigml::resource::Dataset;\n\n let id = \"dataset/abc123\".parse::<Id<Dataset>>().unwrap();\n\n assert_eq!(strip_id_prefix(&id), \"abc123\");\n\n}\n", "file_path": "dbcrossbarlib/src/drivers/bigml/local_data.rs", "rank": 69, "score": 116800.87908338688 }, { "content": "#[test]\n\nfn parsing() {\n\n use std::convert::TryFrom;\n\n use BqDataType as DT;\n\n use BqNonArrayDataType as NADT;\n\n let examples = [\n\n (\"BOOL\", DT::NonArray(NADT::Bool)),\n\n // Not documented, but it exists.\n\n (\"BOOLEAN\", DT::NonArray(NADT::Bool)),\n\n (\"BYTES\", DT::NonArray(NADT::Bytes)),\n\n (\"DATE\", DT::NonArray(NADT::Date)),\n\n (\"DATETIME\", DT::NonArray(NADT::Datetime)),\n\n (\"FLOAT64\", DT::NonArray(NADT::Float64)),\n\n (\"GEOGRAPHY\", DT::NonArray(NADT::Geography)),\n\n (\"INT64\", DT::NonArray(NADT::Int64)),\n\n (\"NUMERIC\", DT::NonArray(NADT::Numeric)),\n\n (\"STRING\", DT::NonArray(NADT::String)),\n\n (\"TIME\", DT::NonArray(NADT::Time)),\n\n (\"TIMESTAMP\", DT::NonArray(NADT::Timestamp)),\n\n (\"ARRAY<STRING>\", DT::Array(NADT::String)),\n\n (\n", "file_path": "dbcrossbarlib/src/drivers/bigquery_shared/data_type/mod.rs", "rank": 70, "score": 116800.87908338688 }, { "content": "#[test]\n\nfn parse_call_limit() {\n\n let cl = CallLimit::from_str(\"2/10\").unwrap();\n\n assert_eq!(cl, CallLimit { used: 2, limit: 10 });\n\n}\n\n\n\n/// Shopify wraps all responses in single-item objects, but we don't know the\n\n/// field name. So we need a smart deserialization wrapper.\n", "file_path": "dbcrossbarlib/src/drivers/shopify/local_data.rs", "rank": 71, "score": 116800.87908338688 }, { "content": "#[test]\n\nfn csv_stream_name_handles_directory_inputs() {\n\n let expected = &[\n\n (\"dir/\", \"dir/file1.csv\", \"file1\"),\n\n (\"dir\", \"dir/file1.csv\", \"file1\"),\n\n (\"dir/\", \"dir/subdir/file2.csv\", \"subdir/file2\"),\n\n (\n\n \"s3://bucket/dir/\",\n\n \"s3://bucket/dir/subdir/file3.csv\",\n\n \"subdir/file3\",\n\n ),\n\n ];\n\n for &(base_path, file_path, stream_name) in expected {\n\n assert_eq!(csv_stream_name(base_path, file_path).unwrap(), stream_name);\n\n }\n\n}\n", "file_path": "dbcrossbarlib/src/csv_stream.rs", "rank": 72, "score": 116363.32114962838 }, { "content": "#[test]\n\nfn temporary_table_name() {\n\n let table_name = \"project:dataset.table\".parse::<TableName>().unwrap();\n\n\n\n // Construct a temporary table name without a `--temporary` argument.\n\n let default_temp_name = table_name\n\n .temporary_table_name(&TemporaryStorage::new(vec![]))\n\n .unwrap()\n\n .to_string();\n\n assert!(default_temp_name.starts_with(\"project:dataset.temp_table_\"));\n\n\n\n // Now try it with a `--temporary` argument.\n\n let temporary_storage =\n\n TemporaryStorage::new(vec![\"bigquery:project2:temp\".to_owned()]);\n\n let temp_name = table_name\n\n .temporary_table_name(&temporary_storage)\n\n .unwrap()\n\n .to_string();\n\n assert!(temp_name.starts_with(\"project2:temp.temp_table_\"));\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/drivers/bigquery_shared/table_name.rs", "rank": 73, "score": 116327.88528734157 }, { "content": "#[test]\n\nfn csv_stream_name_handles_file_inputs() {\n\n let expected = &[\n\n (\"/path/to/file1.csv\", \"file1\"),\n\n (\"file2.csv\", \"file2\"),\n\n (\"s3://bucket/dir/file3.csv\", \"file3\"),\n\n (\"gs://bucket/dir/file4.csv\", \"file4\"),\n\n ];\n\n for &(file_path, stream_name) in expected {\n\n assert_eq!(csv_stream_name(file_path, file_path).unwrap(), stream_name);\n\n }\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/csv_stream.rs", "rank": 74, "score": 116247.73660580194 }, { "content": "/// Write a JavaScript expression that will transform `input_expr` of\n\n/// `intput_type` into a `STRING` containing serialized JSON data.\n\nfn write_transform_expr(\n\n input_expr: &str,\n\n input_type: &BqDataType,\n\n indent: IndentLevel,\n\n f: &mut dyn Write,\n\n) -> Result<()> {\n\n // Check to see if anything below this level needs custom handling. This\n\n // check potentially requires O((depth of type)^2) to compute, but it\n\n // potentially saves us lots of unnecessary work on 300-3000 BigQuery CPUs.\n\n if needs_custom_json_export(input_type)?.in_js_code() {\n\n // Yup, we need to do this the hard way.\n\n match input_type {\n\n BqDataType::Array(ty) => {\n\n writeln!(\n\n f,\n\n \"({ie}) == null ? null : {ie}.map(function (e) {{\",\n\n ie = input_expr,\n\n )?;\n\n write!(f, \"{}return \", indent.incr())?;\n\n write_non_array_transform_expr(\"e\", ty, indent.incr(), f)?;\n", "file_path": "dbcrossbarlib/src/drivers/bigquery_shared/export_udf.rs", "rank": 75, "score": 115888.98459092289 }, { "content": "/// Write a JavaScript expression that will transform `input_expr` into a value\n\n/// of type `output_type`.\n\nfn write_transform_expr(\n\n input_expr: &str,\n\n output_type: &BqDataType,\n\n indent: IndentLevel,\n\n f: &mut dyn Write,\n\n) -> Result<()> {\n\n match output_type {\n\n BqDataType::Array(ty) => {\n\n writeln!(\n\n f,\n\n \"({ie} == null) ? null : {ie}.map(function (e) {{\",\n\n ie = input_expr,\n\n )?;\n\n write!(f, \"{}return \", indent.incr())?;\n\n write_non_array_transform_expr(\"e\", ty, indent.incr(), f)?;\n\n writeln!(f, \";\")?;\n\n write!(f, \"{}}})\", indent)?;\n\n }\n\n BqDataType::NonArray(ty) => {\n\n write_non_array_transform_expr(input_expr, ty, indent, f)?;\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/drivers/bigquery_shared/import_udf.rs", "rank": 76, "score": 115884.57593526386 }, { "content": "#[test]\n\nfn parsing_pg_data_type() {\n\n let array = |ty| PgDataType::Array {\n\n dimension_count: 1,\n\n ty,\n\n };\n\n let examples = &[\n\n // Basic types.\n\n (\n\n (\"bigint\", \"pg_catalog\", \"int8\"),\n\n PgDataType::Scalar(PgScalarDataType::Bigint),\n\n ),\n\n (\n\n (\"boolean\", \"pg_catalog\", \"bool\"),\n\n PgDataType::Scalar(PgScalarDataType::Boolean),\n\n ),\n\n (\n\n (\"character varying\", \"pg_catalog\", \"varchar\"),\n\n PgDataType::Scalar(PgScalarDataType::Text),\n\n ),\n\n (\n", "file_path": "dbcrossbarlib/src/drivers/postgres_shared/catalog.rs", "rank": 77, "score": 115432.71827418375 }, { "content": "/// A helper function which can deserialize integers represented as either\n\n/// numbers or strings.\n\nfn deserialize_int<'de, T, D>(deserializer: D) -> Result<T, D::Error>\n\nwhere\n\n T: FromStr,\n\n <T as FromStr>::Err: fmt::Display,\n\n D: Deserializer<'de>,\n\n{\n\n // We deserialize this using a visitor as described at\n\n // https://serde.rs/impl-deserialize.html because we may want to add support\n\n // for transparently handling a mix of strings and floats, if we ever get\n\n // that back from any API.\n\n struct IntVisitor<T>(PhantomData<T>);\n\n\n\n impl<'de, T> Visitor<'de> for IntVisitor<T>\n\n where\n\n T: FromStr,\n\n <T as FromStr>::Err: fmt::Display,\n\n {\n\n type Value = T;\n\n\n\n fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {\n", "file_path": "dbcrossbarlib/src/clouds/gcloud/storage/mod.rs", "rank": 78, "score": 114377.03939999503 }, { "content": "/// Parse a CSV cell and write it out as a PostgreSQL binary value. This works\n\n/// for any type implementing `FromCsvCell` and `WriteBinary`. More complicated\n\n/// cases will need to do this manually.\n\nfn write_cell_as_binary<T: FromCsvCell + WriteBinary>(\n\n wtr: &mut BufferedWriter,\n\n cell: &str,\n\n) -> Result<()> {\n\n let value = T::from_csv_cell(cell)?;\n\n value.write_binary(wtr)\n\n}\n\n\n\n/// Useful extensions to `Write`.\n\npub(crate) trait WriteExt {\n\n /// Write the length of a PostgreSQL value.\n\n fn write_len(&mut self, len: usize) -> Result<()>;\n\n\n\n /// Given a scratch `buffer` (which must be empty) and a function\n\n /// that writes output, run the function, collect the output, and write\n\n /// the output length and the output to this writer.\n\n ///\n\n /// We use an external `buffer` because this is an inner loop that will run\n\n /// over terabytes of data.\n\n fn write_value<F>(&mut self, buffer: &mut Vec<u8>, f: F) -> Result<()>\n", "file_path": "dbcrossbarlib/src/drivers/postgres/csv_to_binary/mod.rs", "rank": 79, "score": 114308.73889893357 }, { "content": "/// Similar to `needs_custom_json_export`, but for `BqNonArrayDataType`.\n\nfn non_array_needs_custom_json_export(\n\n ty: &BqNonArrayDataType,\n\n) -> Result<NeedsCustomJsonExport> {\n\n match ty {\n\n // These types should all export to JSON correctly by default, I hope.\n\n //\n\n // TODO: Check min and max `INT64`.\n\n BqNonArrayDataType::Bool\n\n | BqNonArrayDataType::Float64\n\n | BqNonArrayDataType::Int64\n\n | BqNonArrayDataType::Numeric\n\n | BqNonArrayDataType::String\n\n | BqNonArrayDataType::Timestamp => Ok(NeedsCustomJsonExport::Never),\n\n\n\n // The SQL function `TO_JSON_STRING` handles `DATE` correctly, but it\n\n // gets converted to a full `Date` when passed to JavaScript. And that\n\n // won't automatically convert to the right thing.\n\n BqNonArrayDataType::Date => Ok(NeedsCustomJsonExport::OnlyInsideUdf),\n\n\n\n // This will also export directly.\n", "file_path": "dbcrossbarlib/src/drivers/bigquery_shared/export_udf.rs", "rank": 80, "score": 112444.39631055872 }, { "content": "/// A helper which builds a `Box<dyn LocatorDriver>` for a type implementating\n\n/// `LocatorStatic`.\n\nfn driver<L: LocatorStatic>() -> Box<dyn LocatorDriver> {\n\n Box::new(LocatorDriverWrapper::<L>::new())\n\n}\n\n\n\nlazy_static! {\n\n /// A list of known drivers, computed the first time we use it and cached.\n\n static ref KNOWN_DRIVERS: Vec<Box<dyn LocatorDriver>> = vec![\n\n driver::<bigml::BigMlLocator>(),\n\n driver::<bigquery::BigQueryLocator>(),\n\n driver::<bigquery_schema::BigQuerySchemaLocator>(),\n\n driver::<csv::CsvLocator>(),\n\n driver::<dbcrossbar_schema::DbcrossbarSchemaLocator>(),\n\n driver::<dbcrossbar_ts::DbcrossbarTsLocator>(),\n\n driver::<gs::GsLocator>(),\n\n driver::<postgres::PostgresLocator>(),\n\n driver::<postgres_sql::PostgresSqlLocator>(),\n\n driver::<redshift::RedshiftLocator>(),\n\n driver::<s3::S3Locator>(),\n\n driver::<shopify::ShopifyLocator>(),\n\n ];\n", "file_path": "dbcrossbarlib/src/drivers/mod.rs", "rank": 81, "score": 104876.82696671684 }, { "content": "/// Return an iterator over successive subranges of a file, each containing\n\n/// `chunk_size` bytes except the last.\n\nfn chunk_ranges(chunk_size: u64, len: u64) -> ChunkRanges {\n\n assert!(chunk_size > 0);\n\n ChunkRanges {\n\n chunk_size,\n\n len,\n\n next_start: 0,\n\n }\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/clouds/gcloud/storage/download_file.rs", "rank": 82, "score": 99990.86383395335 }, { "content": "\n\n/// Given a table and list of upsert columns, return a list\n\npub(crate) fn columns_to_update_for_upsert<'a>(\n\n dest_table: &'a PgCreateTable,\n\n upsert_keys: &[String],\n\n) -> Result<Vec<&'a str>> {\n\n // Build a set of our upsert keys. We could probably implement this linear\n\n // search with no significant loss of performance.\n\n let upsert_keys_set: HashSet<&str> =\n\n HashSet::from_iter(upsert_keys.iter().map(|k| &k[..]));\n\n\n\n // Build our list of columns to update.\n\n let mut update_cols = vec![];\n\n for c in &dest_table.columns {\n\n if upsert_keys_set.contains(&c.name[..]) {\n\n // Verify that it's actually safe to use this as an upsert key.\n\n if c.is_nullable {\n\n return Err(format_err!(\n\n \"cannot upsert on column {} because it isn't declared NOT NULL\",\n\n Ident(&c.name),\n\n ));\n\n }\n\n } else {\n\n update_cols.push(&c.name[..]);\n\n }\n\n }\n\n Ok(update_cols)\n\n}\n\n\n", "file_path": "dbcrossbarlib/src/drivers/postgres/write_local_data.rs", "rank": 83, "score": 90409.37732950905 }, { "content": " let mut real_source_table =\n\n BqTable::read_from_table(&ctx, &source_table_name).await?;\n\n real_source_table = real_source_table.aligned_with(&source_table)?;\n\n\n\n // We need to build a temporary export table.\n\n let temp_table_name = source_table\n\n .name()\n\n .temporary_table_name(&temporary_storage)?;\n\n let mut export_sql_data = vec![];\n\n real_source_table.write_export_sql(&source_args, &mut export_sql_data)?;\n\n let export_sql =\n\n String::from_utf8(export_sql_data).expect(\"should always be UTF-8\");\n\n debug!(ctx.log(), \"export SQL: {}\", export_sql);\n\n\n\n // Run our query.\n\n bigquery::query_to_table(\n\n &ctx,\n\n source.project(),\n\n &export_sql,\n\n &temp_table_name,\n", "file_path": "dbcrossbarlib/src/drivers/gs/write_remote_data.rs", "rank": 84, "score": 90408.7186246099 }, { "content": "//! Implementation of `write_local_data` for Redshift.\n\n\n\nuse super::RedshiftLocator;\n\nuse crate::common::*;\n\nuse crate::drivers::s3::find_s3_temp_dir;\n\nuse crate::tokio_glue::ConsumeWithParallelism;\n\n\n\n/// Implementation of `write_local_data`, but as a real `async` function.\n\npub(crate) async fn write_local_data_helper(\n\n ctx: Context,\n\n dest: RedshiftLocator,\n\n data: BoxStream<CsvStream>,\n\n shared_args: SharedArguments<Unverified>,\n\n dest_args: DestinationArguments<Unverified>,\n\n) -> Result<BoxStream<BoxFuture<BoxLocator>>> {\n\n // Build a temporary location.\n\n let shared_args_v = shared_args.clone().verify(RedshiftLocator::features())?;\n\n let s3_temp = find_s3_temp_dir(shared_args_v.temporary_storage())?;\n\n let s3_dest_args = DestinationArguments::for_temporary();\n\n let s3_source_args = SourceArguments::for_temporary();\n", "file_path": "dbcrossbarlib/src/drivers/redshift/write_local_data.rs", "rank": 85, "score": 90407.0376541936 }, { "content": " let create_stmt = client.prepare(&create_sql).await?;\n\n client\n\n .execute(&create_stmt, &[])\n\n .await\n\n .with_context(|_| format!(\"error creating {}\", &table.name.quoted()))?;\n\n Ok(())\n\n}\n\n\n\n/// Create a temporary table based on `table`, but using a different name. This\n\n/// table will only live as long as the `client`.\n\npub(crate) async fn create_temp_table_for(\n\n ctx: &Context,\n\n client: &mut Client,\n\n table: &PgCreateTable,\n\n) -> Result<PgCreateTable> {\n\n let mut temp_table = table.to_owned();\n\n let temp_name = table.name.temporary_table_name()?;\n\n temp_table.name = temp_name;\n\n temp_table.if_not_exists = false;\n\n temp_table.temporary = true;\n", "file_path": "dbcrossbarlib/src/drivers/postgres/write_local_data.rs", "rank": 86, "score": 90406.55868184583 }, { "content": "//! Implementation of `write_local_data` for BigQuery.\n\n\n\nuse crate::common::*;\n\nuse crate::drivers::{bigquery::BigQueryLocator, gs::find_gs_temp_dir};\n\nuse crate::tokio_glue::ConsumeWithParallelism;\n\n\n\n/// Implementation of `write_local_data`, but as a real `async` function.\n\npub(crate) async fn write_local_data_helper(\n\n ctx: Context,\n\n dest: BigQueryLocator,\n\n data: BoxStream<CsvStream>,\n\n shared_args: SharedArguments<Unverified>,\n\n dest_args: DestinationArguments<Unverified>,\n\n) -> Result<BoxStream<BoxFuture<BoxLocator>>> {\n\n // Build a temporary location.\n\n let shared_args_v = shared_args.clone().verify(BigQueryLocator::features())?;\n\n let gs_temp = find_gs_temp_dir(shared_args_v.temporary_storage())?;\n\n let gs_dest_args = DestinationArguments::for_temporary();\n\n let gs_source_args = SourceArguments::for_temporary();\n\n\n", "file_path": "dbcrossbarlib/src/drivers/bigquery/write_local_data.rs", "rank": 87, "score": 90406.4598166158 }, { "content": " create_table(ctx, client, &temp_table).await?;\n\n Ok(temp_table)\n\n}\n\n\n\n/// Run `DROP TABLE` and/or `CREATE TABLE` as needed to prepare `table` for\n\n/// copying in data.\n\n///\n\n/// We take ownership of `pg_create_table` because we want to edit it before\n\n/// running it.\n\npub(crate) async fn prepare_table(\n\n ctx: &Context,\n\n client: &mut Client,\n\n mut table: PgCreateTable,\n\n if_exists: &IfExists,\n\n) -> Result<()> {\n\n match if_exists {\n\n IfExists::Overwrite => {\n\n drop_table_if_exists(ctx, client, &table).await?;\n\n table.if_not_exists = false;\n\n }\n", "file_path": "dbcrossbarlib/src/drivers/postgres/write_local_data.rs", "rank": 88, "score": 90404.80759849021 }, { "content": "//! Support for writing local data to Postgres.\n\n\n\nuse futures::pin_mut;\n\nuse itertools::Itertools;\n\nuse std::{collections::HashSet, io::prelude::*, iter::FromIterator, str};\n\n\n\nuse super::{csv_to_binary::copy_csv_to_pg_binary, Client, PostgresLocator};\n\nuse crate::common::*;\n\nuse crate::drivers::postgres_shared::{connect, CheckCatalog, Ident, PgCreateTable};\n\nuse crate::tokio_glue::try_forward;\n\nuse crate::transform::spawn_sync_transform;\n\n\n\n/// If `table_name` exists, `DROP` it.\n\nasync fn drop_table_if_exists(\n\n ctx: &Context,\n\n client: &mut Client,\n\n table: &PgCreateTable,\n\n) -> Result<()> {\n\n debug!(\n\n ctx.log(),\n", "file_path": "dbcrossbarlib/src/drivers/postgres/write_local_data.rs", "rank": 89, "score": 90403.11974345782 }, { "content": " // Concatenate all our CSV data into a single stream if requested.\n\n if concat_csv_streams {\n\n data = box_stream_once(Ok(concatenate_csv_streams(ctx.clone(), data)?));\n\n }\n\n\n\n // See if we have an S3 temporary directory, and transform `data` into a\n\n // list of BigML source IDs.\n\n let s3_temp = find_s3_temp_dir(shared_args_v.temporary_storage()).ok();\n\n let sources: BoxStream<BoxFuture<(Context, Source)>> =\n\n if let Some(s3_temp) = s3_temp {\n\n // We have S3 temporary storage, so let's copy everything there.\n\n\n\n // Pass our `data` streams to `S3Locator::write_local_data`, which will\n\n // write them to S3 and return a `BoxStream<BoxFuture<BoxLocator>>>`,\n\n // that is, a stream a futures yielding the S3 locators where we put\n\n // our data on S3.\n\n let s3_dest_args = DestinationArguments::for_temporary();\n\n let s3_locator_stream: BoxStream<BoxFuture<BoxLocator>> = s3_temp\n\n .write_local_data(ctx.clone(), data, shared_args, s3_dest_args)\n\n .await?;\n", "file_path": "dbcrossbarlib/src/drivers/bigml/write_local_data.rs", "rank": 90, "score": 90402.59353784253 }, { "content": " \"transforming data into final table {}\",\n\n dest_table.name(),\n\n );\n\n\n\n // Generate and run our import SQL.\n\n let mut query = Vec::new();\n\n dest_table.write_import_sql(initial_table.name(), if_exists, &mut query)?;\n\n let query =\n\n String::from_utf8(query).expect(\"generated SQL should always be UTF-8\");\n\n debug!(ctx.log(), \"import sql: {}\", query);\n\n bigquery::execute_sql(&ctx, dest.project(), &query, &job_labels).await?;\n\n\n\n // Delete temp table.\n\n bigquery::drop_table(&ctx, initial_table.name(), &job_labels).await?;\n\n }\n\n\n\n Ok(vec![dest.boxed()])\n\n}\n", "file_path": "dbcrossbarlib/src/drivers/bigquery/write_remote_data.rs", "rank": 91, "score": 90402.16074183013 }, { "content": " // Connect to Redshift and prepare our table.\n\n let mut client = connect(&ctx, dest.url()).await?;\n\n prepare_table(&ctx, &mut client, pg_create_table.clone(), &if_exists).await?;\n\n if let IfExists::Upsert(upsert_keys) = &if_exists {\n\n // Create a temporary table to hold our imported data.\n\n let temp_table =\n\n create_temp_table_for(&ctx, &mut client, &pg_create_table).await?;\n\n\n\n // Copy data into our temporary table.\n\n copy_in(&ctx, &client, &source_url, &temp_table.name, to_args).await?;\n\n\n\n // Build our upsert SQL.\n\n upsert_from_temp_table(\n\n &ctx,\n\n &mut client,\n\n &temp_table,\n\n &pg_create_table,\n\n upsert_keys,\n\n )\n\n .await?;\n", "file_path": "dbcrossbarlib/src/drivers/redshift/write_remote_data.rs", "rank": 92, "score": 90401.65438439896 }, { "content": " let fut = async move {\n\n while let Some(result) = data.next().await {\n\n match result {\n\n Err(err) => {\n\n debug!(ctx.log(), \"error reading stream of streams: {}\", err);\n\n return Err(err);\n\n }\n\n Ok(csv_stream) => {\n\n let ctx = ctx.child(o!(\"stream\" => csv_stream.name.clone()));\n\n\n\n // Convert our CSV stream into a PostgreSQL `BINARY` stream.\n\n let transform_table = dest_table.clone();\n\n let binary_stream = spawn_sync_transform(\n\n ctx.clone(),\n\n \"copy_csv_to_pg_binary\".to_owned(),\n\n csv_stream.data,\n\n move |_ctx, rdr, wtr| {\n\n copy_csv_to_pg_binary(&transform_table, rdr, wtr)\n\n },\n\n )?;\n", "file_path": "dbcrossbarlib/src/drivers/postgres/write_local_data.rs", "rank": 93, "score": 90400.35178357948 }, { "content": " dest_table = dest_table.name.quoted(),\n\n src_table = src_table.name.quoted(),\n\n all_columns = dest_table.columns.iter().map(|c| Ident(&c.name)).join(\", \"),\n\n key_columns = upsert_keys.iter().map(|k| Ident(k)).join(\", \"),\n\n value_updates = value_keys\n\n .iter()\n\n .map(|vk| format!(\"{name} = EXCLUDED.{name}\", name = Ident(&vk)))\n\n .join(\",\\n \"),\n\n ))\n\n}\n\n\n\n/// Upsert all rows from `src` into `dest`.\n\npub(crate) async fn upsert_from(\n\n ctx: &Context,\n\n client: &mut Client,\n\n src_table: &PgCreateTable,\n\n dest_table: &PgCreateTable,\n\n upsert_keys: &[String],\n\n) -> Result<()> {\n\n let sql = upsert_sql(src_table, dest_table, upsert_keys)?;\n", "file_path": "dbcrossbarlib/src/drivers/postgres/write_local_data.rs", "rank": 94, "score": 90399.50070595785 }, { "content": "\n\n // Copy to a temporary s3:// location.\n\n let to_temp_ctx = ctx.child(o!(\"to_temp\" => s3_temp.to_string()));\n\n let result_stream = s3_temp\n\n .write_local_data(to_temp_ctx, data, shared_args.clone(), s3_dest_args)\n\n .await?;\n\n\n\n // Wait for all s3:// uploads to finish with controllable parallelism.\n\n //\n\n // TODO: This duplicates our top-level `cp` code and we need to implement\n\n // the same rules for picking a good argument to `consume_with_parallelism`\n\n // and not just hard code our parallelism.\n\n result_stream\n\n .consume_with_parallelism(shared_args_v.max_streams())\n\n .await?;\n\n\n\n // Load from s3:// to Redshift.\n\n let from_temp_ctx = ctx.child(o!(\"from_temp\" => s3_temp.to_string()));\n\n dest.write_remote_data(\n\n from_temp_ctx,\n", "file_path": "dbcrossbarlib/src/drivers/redshift/write_local_data.rs", "rank": 95, "score": 90399.04756758394 }, { "content": " // Copy to a temporary gs:// location.\n\n let to_temp_ctx = ctx.child(o!(\"to_temp\" => gs_temp.to_string()));\n\n let result_stream = gs_temp\n\n .write_local_data(to_temp_ctx, data, shared_args.clone(), gs_dest_args)\n\n .await?;\n\n\n\n // Wait for all gs:// uploads to finish with controllable parallelism.\n\n //\n\n // TODO: This duplicates our top-level `cp` code and we need to implement\n\n // the same rules for picking a good argument to `consume_with_parallelism`\n\n // and not just hard code our parallelism.\n\n result_stream\n\n .consume_with_parallelism(shared_args_v.max_streams())\n\n .await?;\n\n\n\n // Load from gs:// to BigQuery.\n\n let from_temp_ctx = ctx.child(o!(\"from_temp\" => gs_temp.to_string()));\n\n dest.write_remote_data(\n\n from_temp_ctx,\n\n Box::new(gs_temp),\n", "file_path": "dbcrossbarlib/src/drivers/bigquery/write_local_data.rs", "rank": 96, "score": 90398.78404343598 }, { "content": "//! Implementation of `write_local_data`.\n\n\n\nuse bigml::{\n\n self,\n\n resource::{dataset, source, source::Optype, Resource, Source},\n\n};\n\nuse chrono::{Duration, Utc};\n\nuse serde::Deserialize;\n\n\n\nuse super::{source::SourceExt, BigMlLocator, CreateOptions};\n\nuse crate::clouds::aws::{sign_s3_url, AwsCredentials};\n\nuse crate::common::*;\n\nuse crate::concat::concatenate_csv_streams;\n\nuse crate::drivers::s3::find_s3_temp_dir;\n\n\n\n/// Parsed version of `--to-arg` values.\n\n#[derive(Clone, Debug, Deserialize)]\n\n#[serde(deny_unknown_fields)]\n", "file_path": "dbcrossbarlib/src/drivers/bigml/write_local_data.rs", "rank": 97, "score": 90398.71308136743 }, { "content": " }\n\n}\n\n\n\nimpl VerifyRedshiftCanImportFromCsv for DataType {\n\n fn verify_redshift_can_import_from_csv(&self) -> Result<()> {\n\n match self {\n\n DataType::Bool\n\n | DataType::Date\n\n | DataType::Float32\n\n | DataType::Float64\n\n | DataType::Int16\n\n | DataType::Int32\n\n | DataType::Int64\n\n | DataType::Text\n\n | DataType::TimestampWithoutTimeZone\n\n | DataType::TimestampWithTimeZone => Ok(()),\n\n DataType::Array(_)\n\n | DataType::Decimal\n\n | DataType::GeoJson(_)\n\n | DataType::Json\n\n | DataType::Struct(_)\n\n | DataType::Uuid => Err(format_err!(\n\n \"Redshift driver does not support data type {:?}\",\n\n self\n\n )),\n\n }\n\n }\n\n}\n", "file_path": "dbcrossbarlib/src/drivers/redshift/write_remote_data.rs", "rank": 98, "score": 90397.93899493864 } ]
Rust
src/prns.rs
Chris--B/comms-rs
8b9278e698c4c817a77449f74fa5ffed3f5c5425
use crate::prelude::*; extern crate num; use num::PrimInt; use std::mem::size_of; pub struct PrnGen<T> { poly_mask: T, state: T, } impl<T: PrimInt> PrnGen<T> { pub fn new(poly_mask: T, state: T) -> PrnGen<T> { PrnGen { poly_mask, state } } pub fn next_byte(&mut self) -> u8 { let fb_bit = T::from((self.state & self.poly_mask).count_ones() % 2).unwrap(); let output = self.state >> (size_of::<T>() * 8 - 1); self.state = self.state << 1; self.state = self.state | fb_bit; output.to_u8().unwrap() } } #[derive(Node)] pub struct PrnsNode<T> where T: PrimInt + Send, { prngen: PrnGen<T>, pub output: NodeSender<u8>, } impl<T> PrnsNode<T> where T: PrimInt + Send, { pub fn new(poly_mask: T, state: T) -> Self { PrnsNode { prngen: PrnGen::new(poly_mask, state), output: Default::default(), } } pub fn run(&mut self) -> Result<u8, NodeError> { Ok(self.prngen.next_byte()) } } #[cfg(test)] mod test { use crate::prelude::*; use crate::prns::*; use num::PrimInt; use std::collections::HashMap; use std::hash::Hash; use std::mem::size_of; use std::thread; use std::time::Instant; #[test] fn test_prns8_correctness() { struct TestPrnsGenerator<T: PrimInt + Hash> { poly_mask: T, state: T, statemap: HashMap<T, u8>, } impl<T: PrimInt + Hash> TestPrnsGenerator<T> { #[allow(clippy::map_entry)] fn run(&mut self) -> Option<u8> { if self.statemap.contains_key(&self.state) { println!("\nSize of <T>: {}", size_of::<T>()); println!("\n\nWrapped, size = {}!", self.statemap.len()); assert_eq!(self.statemap.len(), 255); return None; } else { self.statemap.insert(self.state, 1 as u8); } let fb_bit = T::from((self.state & self.poly_mask).count_ones() % 2) .unwrap(); let output = self.state >> (size_of::<T>() * 8 - 1); self.state = self.state << 1; self.state = self.state | fb_bit; output.to_u8() } } let mut prngen = TestPrnsGenerator { poly_mask: 0xB8 as u8, state: 0x01, statemap: HashMap::new(), }; while let Some(x) = prngen.run() { print!("{:x}", x); } } #[test] fn test_prns_node() { let mut mynode = PrnsNode::new(0xC0 as u8, 0x01); #[derive(Node)] struct CheckNode { input: NodeReceiver<u8>, state: Vec<u8>, } impl CheckNode { pub fn new() -> Self { CheckNode { state: vec![], input: Default::default(), } } pub fn run(&mut self, x: u8) -> Result<(), NodeError> { if self.state.len() == 128 { assert_eq!( self.state, vec![ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0 ] ); } else { self.state.push(x); } Ok(()) } } let mut check_node = CheckNode::new(); connect_nodes!(mynode, output, check_node, input); start_nodes!(mynode); let check = thread::spawn(move || { let now = Instant::now(); loop { check_node.call().unwrap(); if now.elapsed().as_secs() > 1 { break; } } }); assert!(check.join().is_ok()); } }
use crate::prelude::*; extern crate num; use num::PrimInt; use std::mem::size_of; pub struct PrnGen<T> { poly_mask: T, state: T, } impl<T: PrimInt> PrnGen<T> { pub fn new(poly_mask: T, state: T) -> PrnGen<T> { PrnGen { poly_mask, state } } pub fn next_byte(&mut self) -> u8 { let fb_bit = T::from((self.state & self.poly_mask).count_ones() % 2).unwrap(); let output = self.state >> (size_of::<T>() * 8 - 1); self.state = self.state << 1; self.state = self.state | fb_bit; output.to_u8().unwrap() } } #[derive(Node)] pub struct PrnsNode<T> where T: PrimInt + Send, { prngen: PrnGen<T>, pub output: NodeSender<u8>, } impl<T> PrnsNode<T> where T: PrimInt + Send, { pub fn new(poly_mask: T, state: T) -> Self { PrnsNode { prngen: PrnGen::new(poly_mask, state), output: Default::default(), } } pub fn run(&mut self) -> Result<u8, NodeError> { Ok(self.prngen.next_byte()) } } #[cfg(test)] mod test { use crate::prelude::*; use crate::prns::*; use num::PrimInt; use std::collections::HashMap; use std::hash::Hash; use std::mem::size_of; use std::thread; use std::time::Instant; #[test] fn test_prns8_correctness() { struct TestPrnsGenerator<T: PrimInt + Hash> { poly_mask: T, state: T, statemap: HashMap<T, u8>, } impl<T: PrimInt + Hash> TestPrnsGenerator<T> { #[allow(clippy::map_entry)] fn run(&mut self) -> Option<u8> {
let fb_bit = T::from((self.state & self.poly_mask).count_ones() % 2) .unwrap(); let output = self.state >> (size_of::<T>() * 8 - 1); self.state = self.state << 1; self.state = self.state | fb_bit; output.to_u8() } } let mut prngen = TestPrnsGenerator { poly_mask: 0xB8 as u8, state: 0x01, statemap: HashMap::new(), }; while let Some(x) = prngen.run() { print!("{:x}", x); } } #[test] fn test_prns_node() { let mut mynode = PrnsNode::new(0xC0 as u8, 0x01); #[derive(Node)] struct CheckNode { input: NodeReceiver<u8>, state: Vec<u8>, } impl CheckNode { pub fn new() -> Self { CheckNode { state: vec![], input: Default::default(), } } pub fn run(&mut self, x: u8) -> Result<(), NodeError> { if self.state.len() == 128 { assert_eq!( self.state, vec![ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0 ] ); } else { self.state.push(x); } Ok(()) } } let mut check_node = CheckNode::new(); connect_nodes!(mynode, output, check_node, input); start_nodes!(mynode); let check = thread::spawn(move || { let now = Instant::now(); loop { check_node.call().unwrap(); if now.elapsed().as_secs() > 1 { break; } } }); assert!(check.join().is_ok()); } }
if self.statemap.contains_key(&self.state) { println!("\nSize of <T>: {}", size_of::<T>()); println!("\n\nWrapped, size = {}!", self.statemap.len()); assert_eq!(self.statemap.len(), 255); return None; } else { self.statemap.insert(self.state, 1 as u8); }
if_condition
[ { "content": "/// Modulates a byte via BPSK into 8 int16 samples\n\npub fn bpsk_byte_mod(byte: u8) -> Vec<Complex<i16>> {\n\n (0..8)\n\n .map(|i| bpsk_bit_mod(((1_u8 << i) & byte).rotate_right(i)).unwrap())\n\n .collect()\n\n}\n\n\n", "file_path": "src/modulation/digital.rs", "rank": 0, "score": 114674.74686400298 }, { "content": "/// Modulates a bit to a complex int16 impulse via BPSK\n\npub fn bpsk_bit_mod(bit: u8) -> Option<Complex<i16>> {\n\n if bit == 0 {\n\n Some(Complex::new(1, 0))\n\n } else if bit == 1 {\n\n Some(Complex::new(-1, 0))\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "src/modulation/digital.rs", "rank": 1, "score": 114674.74686400298 }, { "content": "/// Modulates a byte via QPSK into 4 int16 samples\n\npub fn qpsk_byte_mod(byte: u8) -> Vec<Complex<i16>> {\n\n (0..8)\n\n .step_by(2)\n\n .map(|i| qpsk_bit_mod(((3_u8 << i) & byte).rotate_right(i)).unwrap())\n\n .collect()\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use num::Complex;\n\n\n\n #[test]\n\n fn test_bpsk_bit() {\n\n assert_eq!(bpsk_bit_mod(0_u8).unwrap(), Complex::new(1, 0));\n\n assert_eq!(bpsk_bit_mod(1_u8).unwrap(), Complex::new(-1, 0));\n\n }\n\n\n\n #[test]\n\n fn test_qpsk_bit() {\n", "file_path": "src/modulation/digital.rs", "rank": 2, "score": 114674.74686400298 }, { "content": "/// Modulates a pair of bits to a complex int16 impulse via QPSK\n\npub fn qpsk_bit_mod(bits: u8) -> Option<Complex<i16>> {\n\n if bits == 0 {\n\n Some(Complex::new(1, 1))\n\n } else if bits == 1 {\n\n Some(Complex::new(-1, 1))\n\n } else if bits == 2 {\n\n Some(Complex::new(1, -1))\n\n } else if bits == 3 {\n\n Some(Complex::new(-1, -1))\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "src/modulation/digital.rs", "rank": 3, "score": 114674.74686400298 }, { "content": "/// The trait that all nodes in the library implement.\n\npub trait Node: Send {\n\n fn start(&mut self);\n\n fn call(&mut self) -> Result<(), NodeError>;\n\n fn is_connected(&self) -> bool;\n\n}\n\n\n\n/// Connects two nodes together with crossbeam channels.\n\n///\n\n/// ```\n\n/// # #[macro_use] extern crate comms_rs;\n\n/// # use comms_rs::prelude::*;\n\n/// # fn main() {\n\n/// # #[derive(Node)]\n\n/// # struct Node1 {\n\n/// # output: NodeSender<u32>,\n\n/// # }\n\n/// #\n\n/// # impl Node1 {\n\n/// # pub fn new() -> Self {\n\n/// # Node1 {\n", "file_path": "src/node/mod.rs", "rank": 4, "score": 112282.60057911389 }, { "content": "/// Builds a closure for generating 0 or 1 with a Uniform distrubition.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use comms_rs::util::rand_node::random_bit;\n\n///\n\n/// let node = random_bit();\n\n/// ```\n\npub fn random_bit() -> UniformNode<u8> {\n\n UniformNode::new(0u8, 2u8)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::util::rand_node;\n\n use std::thread;\n\n use std::time::Instant;\n\n\n\n use crate::prelude::*;\n\n\n\n #[test]\n\n // A basic test that just makes sure the node doesn't crash.\n\n fn test_normal() {\n\n let mut norm_node = rand_node::NormalNode::new(0.0, 1.0);\n\n let check = thread::spawn(move || {\n\n let now = Instant::now();\n\n loop {\n\n norm_node.call().unwrap();\n", "file_path": "src/util/rand_node.rs", "rank": 5, "score": 107691.82470161495 }, { "content": "#[test]\n\nfn test_macro() {\n\n let mut node1 = Node1::new();\n\n\n\n let mut node2 = Node2::new(5);\n\n\n\n let mut node3 = Node3::new();\n\n\n\n connect_nodes!(node1, output, node2, recv_input);\n\n connect_nodes!(node2, output, node3, recv_input);\n\n\n\n thread::spawn(move || {\n\n node1.call().unwrap();\n\n });\n\n\n\n thread::spawn(move || {\n\n node2.call().unwrap();\n\n });\n\n\n\n node3.call().unwrap();\n\n}\n", "file_path": "tests/macro_tests.rs", "rank": 6, "score": 92349.61495203678 }, { "content": "#[test]\n\nfn simple_nodes() {\n\n #[derive(Node)]\n\n struct SourceNode {\n\n pub output: NodeSender<u32>,\n\n }\n\n\n\n impl SourceNode {\n\n pub fn new() -> Self {\n\n SourceNode {\n\n output: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(&mut self) -> Result<u32, NodeError> {\n\n Ok(1)\n\n }\n\n }\n\n\n\n #[derive(Node)]\n\n struct SinkNode {\n", "file_path": "tests/node_test.rs", "rank": 7, "score": 87663.93546720617 }, { "content": "/// Implementation of the Mengali qfilter tap calculator.\n\n///\n\n/// This is specifically to support Mengali's feedforward non data aided\n\n/// maximum likelihood estimator described in chp. 8.4 of his book as q(t).\n\n///\n\n/// # Arguments\n\n///\n\n/// * `n_taps` - Number of desired output taps. Only takes odd numbers. Even\n\n/// numbers will be incremented by one and that shall be used\n\n/// intead.\n\n/// * `alpha` - Shaping parameter of the function. Must be on the interval\n\n/// [0.0, 1.0].\n\n/// * `sam_per_sym` - Samples per symbol\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use comms_rs::util::math::qfilt_taps;\n\n/// use num::Complex;\n\n///\n\n/// let n_taps = 21;\n\n/// let alpha = 0.25;\n\n/// let sams_per_sym = 2;\n\n/// let taps: Vec<f64> = qfilt_taps(n_taps, alpha, sams_per_sym).unwrap();\n\n/// ```\n\npub fn qfilt_taps(\n\n n_taps: u32,\n\n alpha: f64,\n\n sam_per_sym: u32,\n\n) -> Result<Vec<f64>, MathError> {\n\n if alpha < 0.0 || alpha > 1.0 {\n\n return Err(MathError::InvalidRolloffError);\n\n };\n\n\n\n // We want an odd number of taps\n\n let mut real_n_taps = n_taps;\n\n if n_taps % 2 == 0 {\n\n real_n_taps += 1;\n\n }\n\n\n\n let d = ((real_n_taps as f64) / 2.0).floor() as i32;\n\n let ttarr: Vec<f64> = (0..real_n_taps)\n\n .map(|x| (x as i32 - d) as f64 / (sam_per_sym as f64))\n\n .collect();\n\n\n", "file_path": "src/util/math.rs", "rank": 8, "score": 87569.41548045655 }, { "content": "/// Implementation of run for the FirNode.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `input` - Input sample to be filtered.\n\n/// * `taps` - FIR filter taps.\n\n/// * `state` - FIR filter initial internal state.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use comms_rs::filter::fir::*;\n\n/// use num::Complex;\n\n///\n\n/// let input = Complex::new(1.2_f64, -0.747_f64);\n\n/// let taps = vec![\n\n/// Complex::new(0.2, 0.0),\n\n/// Complex::new(0.6, 0.0),\n\n/// Complex::new(0.6, 0.0),\n\n/// Complex::new(0.2, 0.0),\n\n/// ];\n\n///\n\n/// let mut state = vec![\n\n/// Complex::new(1.0, 0.0),\n\n/// Complex::new(0.5, 0.0),\n\n/// Complex::new(0.25, 0.0),\n\n/// Complex::new(0.125, 0.0),\n\n/// ];\n\n///\n\n/// let output = fir(&input, &taps, &mut state);\n\n/// ```\n\npub fn fir<T>(\n\n input: &Complex<T>,\n\n taps: &[Complex<T>],\n\n state: &mut Vec<Complex<T>>,\n\n) -> Complex<T>\n\nwhere\n\n T: Num + Copy,\n\n{\n\n state.rotate_right(1);\n\n state[0] = *input;\n\n taps.iter().zip(state.iter()).map(|(x, y)| *x * *y).sum()\n\n}\n\n\n", "file_path": "src/filter/fir.rs", "rank": 9, "score": 83078.53822239142 }, { "content": "/// Implementation of run for the BatchFirNode.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `input` - Input batch of samples to be filtered.\n\n/// * `taps` - FIR filter taps.\n\n/// * `state` - FIR filter initial internal state.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use comms_rs::filter::fir::*;\n\n/// use num::Complex;\n\n///\n\n/// let input: Vec<Complex<f64>> = (0..100).map(|x| Complex::new((x as f64).cos(), 0.0)).collect();\n\n/// let taps = vec![\n\n/// Complex::new(0.2, 0.0),\n\n/// Complex::new(0.6, 0.0),\n\n/// Complex::new(0.6, 0.0),\n\n/// Complex::new(0.2, 0.0),\n\n/// ];\n\n///\n\n/// let mut state = vec![\n\n/// Complex::new(1.0, 0.0),\n\n/// Complex::new(0.5, 0.0),\n\n/// Complex::new(0.25, 0.0),\n\n/// Complex::new(0.125, 0.0),\n\n/// ];\n\n///\n\n/// let output = batch_fir(&input, &taps, &mut state);\n\n/// ```\n\npub fn batch_fir<T>(\n\n input: &[Complex<T>],\n\n taps: &[Complex<T>],\n\n state: &mut Vec<Complex<T>>,\n\n) -> Vec<Complex<T>>\n\nwhere\n\n T: Num + Copy,\n\n{\n\n let mut output = Vec::new();\n\n for sample in input {\n\n state.rotate_right(1);\n\n state[0] = *sample;\n\n output.push(taps.iter().zip(state.iter()).map(|(x, y)| *x * *y).sum());\n\n }\n\n output\n\n}\n", "file_path": "src/filter/fir.rs", "rank": 10, "score": 80650.28385629607 }, { "content": "/// Gaussian filter impulse response.\n\n///\n\n/// Use this to create the taps for an FIR filter node and use that for a pulse\n\n/// shaping node.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `n_taps` - Number of desired output taps\n\n/// * `sam_per_sym` - Samples per symbol\n\n/// * `alpha` - Shaping parameter of the function\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use comms_rs::util::math::gaussian_taps;\n\n/// use num::Complex;\n\n///\n\n/// let n_taps = 28_u32;\n\n/// let sams_per_sym = 4.0_f64;\n\n/// let alpha = 0.25_f64;\n\n/// let taps: Vec<Complex<f64>> = gaussian_taps(n_taps, sams_per_sym, alpha).unwrap();\n\n/// ```\n\npub fn gaussian_taps<T>(\n\n n_taps: u32,\n\n sam_per_sym: f64,\n\n alpha: f64,\n\n) -> Option<Vec<Complex<T>>>\n\nwhere\n\n T: Copy + Num + num_traits::NumCast,\n\n{\n\n let tsym = 1.0_f64;\n\n let fs = sam_per_sym / tsym;\n\n\n\n let f =\n\n |t: f64| -> f64 { (alpha / PI).sqrt() * (-alpha * t.powi(2)).exp() };\n\n\n\n let mut taps = Vec::new();\n\n for i in 0..n_taps {\n\n let t = (f64::from(i) - f64::from(n_taps - 1) / 2.0) / fs;\n\n let value = T::from(f(t))?;\n\n let im = T::from(0)?;\n\n taps.push(Complex::new(value, im));\n\n }\n\n\n\n Some(taps)\n\n}\n\n\n", "file_path": "src/util/math.rs", "rank": 11, "score": 80647.61547523568 }, { "content": "/// Raise Cosine (RC) filter tap calculator.\n\n///\n\n/// Use this to create the taps for a FIR filter node and use that as your\n\n/// pulse shaping.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `n_taps` - Number of desired output taps\n\n/// * `sam_per_sym` - Samples per symbol\n\n/// * `beta` - Shaping parameter of the RC function. Must be on the interval\n\n/// [0, 1].\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use comms_rs::util::math::rc_taps;\n\n/// use num::Complex;\n\n///\n\n/// let n_taps = 28u32;\n\n/// let sams_per_sym = 4.0_f64;\n\n/// let beta = 0.25_f64;\n\n/// let taps: Vec<Complex<f64>> = rc_taps(n_taps, sams_per_sym, beta).unwrap();\n\n/// ```\n\npub fn rc_taps<T>(\n\n n_taps: u32,\n\n sam_per_sym: f64,\n\n beta: f64,\n\n) -> Result<Vec<Complex<T>>, MathError>\n\nwhere\n\n T: Copy + Num + num_traits::NumCast,\n\n{\n\n if beta < 0.0 || beta > 1.0 {\n\n return Err(MathError::InvalidRolloffError);\n\n };\n\n\n\n let tsym = 1.0_f64;\n\n let fs = sam_per_sym / tsym;\n\n\n\n let fint = || -> f64 { (PI / (4.0 * tsym)) * sinc(1.0 / (2.0 * beta)) };\n\n\n\n let f = |t: f64| -> f64 {\n\n (1.0 / tsym) * sinc(t / tsym) * ((PI * beta * t) / tsym).cos()\n\n / (1.0 - ((2.0 * beta * t) / tsym).powi(2))\n", "file_path": "src/util/math.rs", "rank": 12, "score": 80647.38128276012 }, { "content": "/// Root Raised Cosine (RRC) filter tap calculator.\n\n///\n\n/// Use this to create the taps for an FIR filter node and use that as your\n\n/// pulse shaping.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `n_taps` - Number of desired output taps\n\n/// * `sam_per_sym` - Samples per symbol\n\n/// * `beta` - Shaping parameter of the RRC function. Must be on the interval\n\n/// [0.0, 1.0].\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use comms_rs::util::math::rrc_taps;\n\n/// use num::Complex;\n\n///\n\n/// let n_taps = 28u32;\n\n/// let sams_per_sym = 4.0_f64;\n\n/// let beta = 0.25_f64;\n\n/// let taps: Vec<Complex<f64>> = rrc_taps(n_taps, sams_per_sym, beta).unwrap();\n\n/// ```\n\npub fn rrc_taps<T>(\n\n n_taps: u32,\n\n sam_per_sym: f64,\n\n beta: f64,\n\n) -> Result<Vec<Complex<T>>, MathError>\n\nwhere\n\n T: Copy + Num + num_traits::NumCast,\n\n{\n\n if beta < 0.0 || beta > 1.0 {\n\n return Err(MathError::InvalidRolloffError);\n\n };\n\n\n\n let tsym = 1.0_f64;\n\n let fs = sam_per_sym / tsym;\n\n\n\n let fzero = || -> f64 { (1.0 / tsym) * (1.0 + beta * (4.0 / PI - 1.0)) };\n\n\n\n let fint = || -> f64 {\n\n (beta / (tsym * 2.0_f64.sqrt()))\n\n * ((1.0 + 2.0 / PI) * (PI / (4.0 * beta)).sin()\n", "file_path": "src/util/math.rs", "rank": 13, "score": 80647.32434005407 }, { "content": "/// An example that will generate random numbers, pass them through a BPSK\n\n/// modulation and a pulse shaper, then broadcast them out to a file and\n\n/// via ZeroMQ for visualization.\n\nfn main() {\n\n // A simple node to perform BPSK modulation. Only broadcasts a message\n\n // once `num_samples` samples have been received and modulated.\n\n #[derive(Node, Default)]\n\n #[aggregate]\n\n struct BpskMod {\n\n input: NodeReceiver<u8>,\n\n num_samples: usize,\n\n state: Vec<Complex<f32>>,\n\n output: NodeSender<Vec<Complex<f32>>>,\n\n }\n\n\n\n impl BpskMod {\n\n pub fn new(num_samples: usize) -> Self {\n\n BpskMod {\n\n num_samples,\n\n state: vec![],\n\n ..Default::default()\n\n }\n\n }\n", "file_path": "examples/bpsk_mod.rs", "rank": 14, "score": 79709.09742135054 }, { "content": "/// Normalized sinc function implementation.\n\n///\n\n/// `sinc(0) = 1`\n\n///\n\n/// `sinc(x) = sin(pi * x) / (pi * x), x != 0`\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use comms_rs::util::math::sinc;\n\n///\n\n/// assert!((sinc(0.0) - 1.0).abs() < std::f64::EPSILON);\n\n/// assert!(sinc(1.0).abs() < std::f64::EPSILON);\n\n/// assert!(sinc(2.0).abs() < std::f64::EPSILON);\n\n/// assert!(sinc(3.0).abs() < std::f64::EPSILON);\n\n/// ```\n\npub fn sinc(x: f64) -> f64 {\n\n if x != 0.0 {\n\n (PI * x).sin() / (PI * x)\n\n } else {\n\n 1.0\n\n }\n\n}\n\n\n", "file_path": "src/util/math.rs", "rank": 15, "score": 74717.04588082223 }, { "content": "/// Calculates a phase estimate from the input QAM symbol vector.\n\n///\n\n/// Result is in radians, and the estimator assumes the input symbol vector is\n\n/// the output from a matched filter. It additionally assumes the vector has\n\n/// already gone through accurate timing recovery.\n\n///\n\n/// Reference Chp. 5.7.5 in Mengali.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `symbols` - Input vector of symbols to calculate the phase estimate from.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use comms_rs::demodulation::phase_estimator::*;\n\n/// use num::Complex;\n\n///\n\n/// let m = 4;\n\n/// let data: Vec<_> = (0..100).map(|x| Complex::new(0.0, x as f64).exp()).collect();\n\n///\n\n/// let estimate = qam_phase_estimate(&data);\n\n/// ```\n\npub fn qam_phase_estimate(symbols: &[Complex<f64>]) -> f64 {\n\n symbols\n\n .iter()\n\n .map(|x| -1.0 * x.powi(4))\n\n .sum::<Complex<f64>>()\n\n .arg()\n\n / 4.0\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::demodulation::phase_estimator::*;\n\n use num::Complex;\n\n use rand::distributions::Uniform;\n\n use rand::prelude::*;\n\n use rand::rngs::SmallRng;\n\n use std::f64::consts::PI;\n\n\n\n #[test]\n\n fn test_psk_phase_estimator() {\n", "file_path": "src/demodulation/phase_estimator.rs", "rank": 16, "score": 63089.80981543998 }, { "content": "/// Constructs a node containing an open but uninitialized connection to an\n\n/// RTLSDR at the given index. Use RTLSDRNode::init_radio to set up the radio\n\n/// prior to running the node.\n\npub fn rtlsdr(index: i32) -> Result<RTLSDR, RTLSDRError> {\n\n let rtlsdr = rtlsdr::open(index)?;\n\n Ok(RTLSDR { rtlsdr })\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::hardware::{radio, rtlsdr_radio};\n\n use std::time::Instant;\n\n\n\n use crate::prelude::*;\n\n use std::thread;\n\n\n\n #[test]\n\n #[cfg_attr(not(feature = \"rtlsdr_node\"), ignore)]\n\n // A quick test to check if we can read samples off the RTLSDR.\n\n fn test_get_samples() {\n\n let num_samples = 262144;\n\n let mut sdr = rtlsdr_radio::rtlsdr(0).unwrap();\n\n sdr.init_radio(88.7e6 as u32, 2.4e6 as u32, 0).unwrap();\n", "file_path": "src/hardware/rtlsdr_radio.rs", "rank": 17, "score": 61409.48216759188 }, { "content": "/// Calculates a phase estimate from the input PSK symbol vector.\n\n///\n\n/// Result is in radians, and the estimator assumes the input symbol vector is\n\n/// the output from a matched filter. It additionally assumes the vector has\n\n/// already gone through accurate timing recovery.\n\n///\n\n/// Reference Chp. 5.7.4 in Mengali.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `symbols` - Input vector of symbols to calculate the phase estimate from.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use comms_rs::demodulation::phase_estimator::*;\n\n/// use num::Complex;\n\n///\n\n/// let m = 4;\n\n/// let data: Vec<_> = (0..100).map(|x| Complex::new(0.0, x as f64).exp()).collect();\n\n///\n\n/// let estimate = psk_phase_estimate(&data, m);\n\n/// ```\n\npub fn psk_phase_estimate(symbols: &[Complex<f64>], m: u32) -> f64 {\n\n symbols\n\n .iter()\n\n .map(|x| x.powi(m as i32))\n\n .sum::<Complex<f64>>()\n\n .arg()\n\n / (m as f64)\n\n}\n\n\n", "file_path": "src/demodulation/phase_estimator.rs", "rank": 18, "score": 58502.1129323637 }, { "content": "/// Rectangle pulse shaping tap calculator.\n\n///\n\n/// Use this to create the taps for an FIR filter node and use that for the\n\n/// pulse shaping node.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `n_taps` - Number of desired output taps\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use comms_rs::util::math::rect_taps;\n\n/// use num::Complex;\n\n///\n\n/// let n_taps = 12_usize;\n\n/// let taps: Vec<Complex<f64>> = rect_taps(n_taps).unwrap();\n\n/// ```\n\npub fn rect_taps<T>(n_taps: usize) -> Option<Vec<Complex<T>>>\n\nwhere\n\n T: Copy + Num + num_traits::NumCast,\n\n{\n\n let re = T::from(1)?;\n\n let im = T::from(0)?;\n\n Some(vec![Complex::new(re, im); n_taps as usize])\n\n}\n\n\n", "file_path": "src/util/math.rs", "rank": 19, "score": 57332.33120896624 }, { "content": "/// Creates a node derived from an input structure with a constructor and\n\n/// implements the Node trait.\n\n///\n\n/// Takes a given structure and from it derives a node-based structure\n\n/// with the sending and receiving out of the node hidden from the user so\n\n/// the user can just focus on the implementation. This function does some\n\n/// transformations on the input data structure's types depending on the name\n\n/// of the fields in the structure.\n\n///\n\n/// The implementation of the Node trait depends on whether #[aggregate] is\n\n/// specified on the structure or not. If it is, the Node will only send out\n\n/// data when it gets a Some(T) from the run() function, otherwise it will\n\n/// continue to the next iteration.\n\n///\n\n/// This macro currently assumes that the structure in question implements a\n\n/// function called `run()` which is exercised in the `call()` function from\n\n/// the Node trait. The return type of the run() depends on whether the\n\n/// #[aggregate] flag is specified on the input structure. If #[aggregate] is\n\n/// present on the structure, the return type must be an Option. Otherwise, it\n\n/// can be anything.\n\n///\n\n/// Fields that are receivers must be of type NodeReceiver<T>. Fields that are\n\n/// senders must be of type NodeSender<T>.\n\n///\n\n/// Example:\n\n/// ```no_run\n\n/// #[derive(Node)]\n\n/// pub struct Node1<T> where T: Into<u32> {\n\n/// input: NodeReceiver<T>,\n\n/// internal_state: u32,\n\n/// output: NodeSender<T>,\n\n/// }\n\n/// ```\n\n/// \n\npub fn node_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n let name = &input.ident;\n\n let generics = &input.generics;\n\n let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();\n\n let attributes = &input.attrs;\n\n let mut aggregate = false;\n\n let mut pass_by_ref = false;\n\n for attr in attributes {\n\n match attr.parse_meta() {\n\n Ok(syn::Meta::Word(ref id)) if *id == \"aggregate\" => {\n\n aggregate = true\n\n }\n\n Ok(syn::Meta::Word(ref id)) if *id == \"pass_by_ref\" => {\n\n pass_by_ref = true\n\n }\n\n Ok(_) => continue,\n\n Err(_) => {\n\n let err = quote! {\n\n compile_error!(\"unrecognized attribute\");\n", "file_path": "node_derive/src/lib.rs", "rank": 20, "score": 55871.05244650427 }, { "content": "/// Casts a `Complex<T>` to a `Complex<U>`.\n\n///\n\n/// All of the normal caveats with using the `as` keyword apply here for the\n\n/// conversion.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use comms_rs::util::math::cast_complex;\n\n/// use num::Complex;\n\n///\n\n/// let a_num = Complex::new(12_i16, -4_i16);\n\n/// let a_new_num: Complex<f64> = cast_complex(&a_num).unwrap();\n\n/// ```\n\npub fn cast_complex<T, U>(input: &Complex<T>) -> Option<Complex<U>>\n\nwhere\n\n T: Copy + Num + num_traits::NumCast,\n\n U: Copy + Num + num_traits::NumCast,\n\n{\n\n let re = U::from(input.re)?;\n\n let im = U::from(input.im)?;\n\n Some(Complex::new(re, im))\n\n}\n\n\n", "file_path": "src/util/math.rs", "rank": 21, "score": 54903.68098313138 }, { "content": "fn main() {\n\n let mut audio: AudioNode<f32> = AudioNode::new(1, 48000, 0.5);\n\n\n\n #[derive(Node)]\n\n struct SineNode {\n\n source: Box<dyn Source<Item = f32> + Send>,\n\n pub output: NodeSender<Vec<f32>>,\n\n }\n\n\n\n impl SineNode {\n\n pub fn new(source: Box<dyn Source<Item = f32> + Send>) -> Self {\n\n SineNode {\n\n source,\n\n output: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(&mut self) -> Result<Vec<f32>, NodeError> {\n\n let source = &mut self.source;\n\n let samp: Vec<f32> = source.take(48000).collect();\n", "file_path": "examples/play_audio.rs", "rank": 22, "score": 49433.06424986267 }, { "content": "fn main() {\n\n // Get the radio frequency (assumed to be MHz as an input) and convert to\n\n // Hz. If no input is specified, default to 88.7 MHz.\n\n let radio_mhz = std::env::args()\n\n .nth(1)\n\n .and_then(|s| str::parse::<f32>(&s).ok());\n\n let radio_freq = match radio_mhz {\n\n Some(f) => (f * 1e6) as u32,\n\n None => {\n\n println!(\"No frequency specified, defaulting to 88.7.\");\n\n 88.7e6 as u32\n\n }\n\n };\n\n\n\n // The taps for the first low pass filter before FM demodulation.\n\n #[cfg_attr(rustfmt, rustfmt_skip)]\n\n let taps = [\n\n -0.01801270027742274, -0.004656920885448867, -0.002648852132912597,\n\n 0.0008677368918448623, 0.005009212152225975, 0.008526175375849215,\n\n 0.010172968340398776, 0.00912437509989248, 0.005334905990231011,\n", "file_path": "examples/fm_radio.rs", "rank": 23, "score": 49433.06424986267 }, { "content": "/// An example that will generate random numbers, pass them through a QPSK\n\n/// modulation and a pulse shaper, then broadcast them out to a file and\n\n/// via ZeroMQ for visualization.\n\nfn main() {\n\n let now = Instant::now();\n\n\n\n #[derive(Node)]\n\n struct QpskMod {\n\n pub output: NodeSender<Vec<Complex<f32>>>,\n\n }\n\n impl QpskMod {\n\n pub fn new() -> Self {\n\n QpskMod {\n\n output: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(&mut self) -> Result<Vec<Complex<f32>>, NodeError> {\n\n let dist = Uniform::new(0u8, 2u8);\n\n let mut rng = rand::thread_rng();\n\n let mut bits: Vec<u8> = Vec::new();\n\n for _ in 0..4096 {\n\n bits.push(rng.sample(&dist));\n", "file_path": "examples/qpsk_zmq.rs", "rank": 24, "score": 49433.06424986267 }, { "content": "/// An example that will generate random numbers, pass them through a QPSK\n\n/// modulation and a pulse shaper, then broadcast them out to a file and\n\n/// via ZeroMQ for visualization.\n\nfn main() {\n\n let mut rng = rand::thread_rng();\n\n let sam_per_sym = 4.0;\n\n let taps: Vec<Complex<f32>> =\n\n math::rrc_taps(32, sam_per_sym, 0.25).unwrap();\n\n let mut state: Vec<Complex<f32>> = vec![Complex::zero(); 32];\n\n let mut writer = BufWriter::new(File::create(\"./qpsk_out.bin\").unwrap());\n\n let now = Instant::now();\n\n let dist = Uniform::new(0u8, 2u8);\n\n\n\n loop {\n\n let mut bits: Vec<u8> = Vec::new();\n\n for _ in 0..4096 {\n\n bits.push(rng.sample(&dist));\n\n }\n\n let qpsk_mod: Vec<Complex<f32>> = bits\n\n .iter()\n\n .step_by(2)\n\n .zip(bits.iter().skip(1).step_by(2))\n\n .map(|(x, y)| {\n", "file_path": "examples/single_thread_qpsk.rs", "rank": 25, "score": 47979.68983001612 }, { "content": "/// An example that will generate random numbers, pass them through a BPSK\n\n/// modulation and a pulse shaper, then broadcast them out to a file and\n\n/// via ZeroMQ for visualization.\n\nfn main() {\n\n let mut rng = rand::thread_rng();\n\n let sam_per_sym = 4.0;\n\n let taps: Vec<Complex<f32>> =\n\n math::rrc_taps(32, sam_per_sym, 0.25).unwrap();\n\n let mut state: Vec<Complex<f32>> = vec![Complex::zero(); 32];\n\n let mut writer = BufWriter::new(File::create(\"./bpsk_out.bin\").unwrap());\n\n let now = Instant::now();\n\n let dist = Uniform::new(0u8, 2u8);\n\n\n\n loop {\n\n let mut bits: Vec<u8> = Vec::new();\n\n for _ in 0..4096 {\n\n bits.push(rng.sample(&dist));\n\n }\n\n let bpsk_mod: Vec<Complex<f32>> = bits\n\n .iter()\n\n .map(|x| Complex::new(f32::from(*x) * 2.0 - 1.0, 0.0))\n\n .collect();\n\n let mut upsample = vec![Complex::zero(); 4096 * 4];\n", "file_path": "examples/single_thread_bpsk.rs", "rank": 26, "score": 47979.68983001612 }, { "content": "struct ParsedFields<'a> {\n\n recv_fields: Vec<&'a syn::Field>,\n\n send_fields: Vec<&'a syn::Field>,\n\n}\n\n\n\n#[proc_macro_derive(Node, attributes(aggregate, pass_by_ref))]\n", "file_path": "node_derive/src/lib.rs", "rank": 27, "score": 45358.26200748177 }, { "content": "extern crate node_derive;\n\n#[macro_use]\n\nextern crate comms_rs;\n\n\n\nuse comms_rs::prelude::*;\n\nuse std::thread;\n\n\n\n#[derive(Node)]\n\npub struct Node1 {\n\n output: NodeSender<u32>,\n\n}\n\n\n\nimpl Node1 {\n\n fn new() -> Self {\n\n Node1 {\n\n output: Default::default(),\n\n }\n\n }\n\n\n\n fn run(&mut self) -> Result<u32, NodeError> {\n", "file_path": "tests/macro_tests.rs", "rank": 28, "score": 42288.81262493639 }, { "content": "#[macro_use]\n\nextern crate comms_rs;\n\n\n\nuse comms_rs::prelude::*;\n\nuse std::thread;\n\nuse std::time::Duration;\n\n\n\n#[test]\n", "file_path": "tests/node_test.rs", "rank": 29, "score": 42283.84567701762 }, { "content": " Ok(1)\n\n }\n\n}\n\n\n\n#[derive(Node)]\n\npub struct Node2 {\n\n recv_input: NodeReceiver<u32>,\n\n stuff: u32,\n\n output: NodeSender<u32>,\n\n}\n\n\n\nimpl Node2 {\n\n fn new(stuff: u32) -> Self {\n\n Node2 {\n\n stuff,\n\n recv_input: Default::default(),\n\n output: Default::default(),\n\n }\n\n }\n\n\n", "file_path": "tests/macro_tests.rs", "rank": 30, "score": 42277.995459399644 }, { "content": " pub input: NodeReceiver<u32>,\n\n }\n\n\n\n impl SinkNode {\n\n pub fn new() -> Self {\n\n SinkNode {\n\n input: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(&mut self, input: u32) -> Result<(), NodeError> {\n\n assert_eq!(input, 1);\n\n Ok(())\n\n }\n\n }\n\n\n\n let mut node = SourceNode::new();\n\n let mut node2 = SinkNode::new();\n\n connect_nodes!(node, output, node2, input);\n\n start_nodes!(node, node2);\n\n thread::sleep(Duration::from_secs(1));\n\n}\n", "file_path": "tests/node_test.rs", "rank": 31, "score": 42277.0053293621 }, { "content": " fn run(&mut self, x: u32) -> Result<u32, NodeError> {\n\n assert_eq!(x, 1);\n\n Ok(x + self.stuff)\n\n }\n\n}\n\n\n\n#[derive(Node)]\n\npub struct Node3 {\n\n recv_input: NodeReceiver<u32>,\n\n}\n\n\n\nimpl Node3 {\n\n fn new() -> Self {\n\n Node3 {\n\n recv_input: Default::default(),\n\n }\n\n }\n\n\n\n fn run(&mut self, x: u32) -> Result<(), NodeError> {\n\n assert_eq!(x, 6);\n\n Ok(())\n\n }\n\n}\n\n\n\n#[test]\n", "file_path": "tests/macro_tests.rs", "rank": 32, "score": 42276.73973636939 }, { "content": "/// A trait to capture the ability to send samples out of the hardware\n\n/// platform on a particular output.\n\npub trait RadioTx<T> {\n\n fn send_samples(&mut self, samples: &[T], output_idx: usize);\n\n}\n\n\n", "file_path": "src/hardware/radio.rs", "rank": 33, "score": 40557.73460283367 }, { "content": "/// A trait to capture the ability to receive samples from the hardware\n\n/// platform on a particular input.\n\npub trait RadioRx<T> {\n\n fn recv_samples(&mut self, num_samples: usize, input_idx: usize) -> Vec<T>;\n\n}\n\n\n\n/// A node that takes a generic hardware platform that supports transmitting\n\n/// samples.\n\n#[derive(Node)]\n\n#[pass_by_ref]\n\npub struct RadioTxNode<T, U>\n\nwhere\n\n T: RadioTx<U> + Send,\n\n U: Clone + Send,\n\n{\n\n pub input: NodeReceiver<Vec<U>>,\n\n radio: T,\n\n output_idx: usize,\n\n}\n\n\n\nimpl<T, U> RadioTxNode<T, U>\n\nwhere\n", "file_path": "src/hardware/radio.rs", "rank": 34, "score": 40550.44584628129 }, { "content": "fn parse_type(field: &syn::Field) -> FieldType {\n\n let ty = &field.ty;\n\n let type_str = quote! {#ty}.to_string();\n\n if type_str.starts_with(\"NodeReceiver\") {\n\n FieldType::Input\n\n } else if type_str.starts_with(\"NodeSender\") {\n\n FieldType::Output\n\n } else {\n\n FieldType::State\n\n }\n\n}\n", "file_path": "node_derive/src/lib.rs", "rank": 35, "score": 33200.607251486785 }, { "content": "fn parse_fields(fields: &syn::FieldsNamed) -> ParsedFields {\n\n let mut recv_fields = vec![];\n\n let mut send_fields = vec![];\n\n for field in &fields.named {\n\n match parse_type(&field) {\n\n FieldType::Input => recv_fields.push(field),\n\n FieldType::Output => send_fields.push(field),\n\n _ => continue,\n\n }\n\n }\n\n ParsedFields {\n\n recv_fields,\n\n send_fields,\n\n }\n\n}\n\n\n", "file_path": "node_derive/src/lib.rs", "rank": 36, "score": 32383.290157025967 }, { "content": " use rand::{thread_rng, Rng};\n\n use std::sync::{Arc, Mutex};\n\n use std::thread;\n\n use std::time::{Duration, Instant};\n\n\n\n use crate::node::graph::Graph;\n\n use crate::prelude::*;\n\n use rayon;\n\n\n\n #[test]\n\n /// Constructs a simple network with two nodes: one source and one sink.\n\n fn test_simple_nodes() {\n\n #[derive(Node)]\n\n struct Node1 {\n\n pub output: NodeSender<u32>,\n\n }\n\n\n\n impl Node1 {\n\n pub fn new() -> Self {\n\n Node1 {\n", "file_path": "src/node/mod.rs", "rank": 37, "score": 31847.311145337255 }, { "content": "//! Nodes for general input/output support, such as file IO, audio, and ZeroMQ.\n\n\n\n#[cfg(feature = \"zmq_node\")]\n\nextern crate zmq;\n\n\n\n#[cfg(feature = \"audio_node\")]\n\nextern crate rodio;\n\n\n\n#[cfg(feature = \"audio_node\")]\n\npub mod audio;\n\n\n\n#[cfg(feature = \"zmq_node\")]\n\npub mod zmq_node;\n\n\n\npub mod raw_iq;\n", "file_path": "src/io/mod.rs", "rank": 38, "score": 31846.103205669468 }, { "content": " ($n1:ident, $send:ident, $n2:ident, $recv:ident, $default:tt) => {{\n\n let (send, recv) = channel::unbounded();\n\n $n1.$send.push((send, Some($default)));\n\n $n2.$recv = Some(recv);\n\n }};\n\n}\n\n\n\n/// Spawns a thread for each node in order and starts nodes to run\n\n/// indefinitely.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// # #[macro_use] extern crate comms_rs;\n\n/// # use comms_rs::prelude::*;\n\n/// # use std::thread;\n\n/// # fn main() {\n\n/// # #[derive(Node)]\n\n/// # struct Node1 {\n\n/// # pub output: NodeSender<u32>,\n", "file_path": "src/node/mod.rs", "rank": 39, "score": 31845.807651698888 }, { "content": " thread::sleep(Duration::from_secs(1));\n\n assert!(check.join().is_ok());\n\n }\n\n\n\n #[test]\n\n /// A test to ensure that persistent state works within the nodes. Makes\n\n /// two nodes: one to send 1 to 10 and the other to add the number to a\n\n /// counter within the node.\n\n fn test_counter() {\n\n #[derive(Node)]\n\n struct OneNode {\n\n count: i32,\n\n output: NodeSender<i32>,\n\n }\n\n\n\n impl OneNode {\n\n pub fn new() -> Self {\n\n OneNode {\n\n count: 0,\n\n output: Default::default(),\n", "file_path": "src/node/mod.rs", "rank": 40, "score": 31845.308918603325 }, { "content": " $n2.$recv = Some(recv);\n\n }};\n\n}\n\n\n\n/// Connects two nodes together in a feedback configuration using channels.\n\n/// When the nodes are connected in feedback, a specified value is sent\n\n/// through the channel immediately so that the nodes don't deadlock on\n\n/// the first iteration.\n\n///\n\n/// ```\n\n/// # #[macro_use] extern crate comms_rs;\n\n/// # use comms_rs::prelude::*;\n\n/// # fn main() {\n\n/// # #[derive(Node)]\n\n/// # struct Node1 {\n\n/// # output: NodeSender<u32>,\n\n/// # }\n\n/// #\n\n/// # impl Node1 {\n\n/// # pub fn new() -> Self {\n", "file_path": "src/node/mod.rs", "rank": 41, "score": 31844.829633301546 }, { "content": " output: NodeSender<Vec<Complex<U>>>,\n\n }\n\n\n\n impl<T, U> ConvertNode<T, U>\n\n where\n\n T: Copy + Num + NumCast + Send,\n\n U: Copy + Num + NumCast + Send,\n\n {\n\n pub fn new() -> Self {\n\n ConvertNode {\n\n input: Default::default(),\n\n output: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(\n\n &mut self,\n\n input: Vec<Complex<T>>,\n\n ) -> Result<Vec<Complex<U>>, NodeError> {\n\n let out: Vec<Complex<U>> = input\n", "file_path": "examples/bpsk_mod.rs", "rank": 42, "score": 31844.649928353523 }, { "content": "//! Provides an infrastructure to create processing nodes, connect nodes\n\n//! together via crossbeam channels, and start nodes running in their own\n\n//! independent threads.\n\n//!\n\n//! # Example\n\n//!\n\n//! ```\n\n//! #[macro_use] extern crate comms_rs;\n\n//! use comms_rs::prelude::*;\n\n//! use std::thread;\n\n//!\n\n//! // Creates two nodes: a source and a sink node. For nodes that receive\n\n//! // inputs, the receivers must explicitly be named.\n\n//! #[derive(Node)]\n\n//! struct Node1 {\n\n//! pub output: NodeSender<u32>,\n\n//! }\n\n//!\n\n//! impl Node1 {\n\n//! pub fn new() -> Self {\n", "file_path": "src/node/mod.rs", "rank": 43, "score": 31844.510973531575 }, { "content": "//! Provides interfaces to hardware platforms and generic traits to encapsulate\n\n//! radio functionality.\n\n//!\n\n\n\n#[cfg(feature = \"rtlsdr_node\")]\n\nextern crate rtlsdr;\n\n\n\n#[cfg(feature = \"rtlsdr_node\")]\n\npub mod rtlsdr_radio;\n\n\n\npub mod radio;\n", "file_path": "src/hardware/mod.rs", "rank": 44, "score": 31842.592233065352 }, { "content": "/// # use comms_rs::prelude::*;\n\n/// # use std::thread;\n\n///\n\n/// # fn main() {\n\n/// # #[derive(Node)]\n\n/// # struct Node1 {\n\n/// # pub output: NodeSender<u32>,\n\n/// # }\n\n///\n\n/// # impl Node1 {\n\n/// # pub fn new() -> Self {\n\n/// # Node1 {\n\n/// # output: Default::default(),\n\n/// # }\n\n/// # }\n\n/// #\n\n/// # pub fn run(&mut self) -> Result<u32, NodeError> {\n\n/// # Ok(1)\n\n/// # }\n\n/// # }\n", "file_path": "src/node/mod.rs", "rank": 45, "score": 31842.470181540677 }, { "content": " });\n\n assert!(check.join().is_ok());\n\n }\n\n\n\n #[test]\n\n /// Constructs a simple network with two nodes: one source and one sink.\n\n fn test_simple_graph() {\n\n #[derive(Node)]\n\n struct Node1 {\n\n pub output: NodeSender<u32>,\n\n }\n\n\n\n impl Node1 {\n\n pub fn new() -> Self {\n\n Node1 {\n\n output: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(&mut self) -> Result<u32, NodeError> {\n", "file_path": "src/node/mod.rs", "rank": 46, "score": 31841.911748784038 }, { "content": "//! Nodes for performing FFTs and IFFTs.\n\n\n\npub mod fft_node;\n\n\n\nuse num::Complex;\n\nuse num::NumCast;\n\nuse rustfft::num_complex::Complex as FFTComplex;\n\nuse rustfft::num_traits::Num;\n\nuse rustfft::num_traits::Zero;\n\nuse rustfft::FFT;\n\nuse std::sync::Arc;\n\n\n\n/// Batch based wrapper of FFT implementation provided by\n\n/// [RustFFT](https://github.com/awelkie/RustFFT).\n\n///\n\n/// This implementation acts on a batch of samples at a time. The underlying\n\n/// library only provides an FFT for type `f64`, so this wrapper will\n\n/// automatically cast any provided input appropriately, although it does\n\n/// expect the general form of `Complex<T>`.\n\npub struct BatchFFT {\n", "file_path": "src/fft/mod.rs", "rank": 47, "score": 31841.855888134636 }, { "content": "\n\n pub fn run(\n\n &mut self,\n\n input: u8,\n\n ) -> Result<Option<Vec<Complex<f32>>>, NodeError> {\n\n let samp: f32 = num::cast(input).unwrap();\n\n self.state.push(Complex::new(samp * 2.0 - 1.0, 0.0));\n\n if self.state.len() == self.num_samples {\n\n let state_cl = self.state.clone();\n\n self.state = vec![];\n\n Ok(Some(state_cl))\n\n } else {\n\n Ok(None)\n\n }\n\n }\n\n }\n\n\n\n // A simple node to perform upsampling of data. Zeros are injected here;\n\n // filtering takes place elsewhere.\n\n #[derive(Node)]\n", "file_path": "examples/bpsk_mod.rs", "rank": 48, "score": 31841.40247385945 }, { "content": " #[test]\n\n /// Performs a _very_ simplistic throughput analysis. We generate\n\n /// 10000 random i16 values at a time and pass it through the pipeline\n\n /// to see if channels will handle the throughput we hope it will.\n\n /// Make sure to run this test with --release.\n\n fn test_threadpool_throughput() {\n\n #[derive(Node)]\n\n struct Node1 {\n\n pub output: NodeSender<Arc<Vec<i16>>>,\n\n }\n\n\n\n impl Node1 {\n\n pub fn new() -> Self {\n\n Node1 {\n\n output: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(&mut self) -> Result<Arc<Vec<i16>>, NodeError> {\n\n let mut random = vec![0i16; 10000];\n", "file_path": "src/node/mod.rs", "rank": 49, "score": 31841.070241606776 }, { "content": "\n\n let mut node1 = Node1::new();\n\n let mut node2 = Node2::new();\n\n let mut node3 = Node3::new();\n\n\n\n connect_nodes!(node1, output, node2, input);\n\n connect_nodes!(node2, output, node3, input);\n\n start_nodes!(node1, node3);\n\n start_nodes_threadpool!(node2,);\n\n thread::sleep(Duration::from_secs(1));\n\n }\n\n\n\n #[test]\n\n /// Constructs a network where a node receives from two different nodes.\n\n /// This serves to make sure that fan-in operation works as we expect\n\n /// it to.\n\n fn test_fan_in() {\n\n use crate::prelude::*;\n\n use std::thread;\n\n use std::time::Duration;\n", "file_path": "src/node/mod.rs", "rank": 50, "score": 31840.653667132454 }, { "content": " struct UpsampleNode<T>\n\n where\n\n T: Zero + Copy + Send,\n\n {\n\n input: NodeReceiver<Vec<T>>,\n\n upsample_factor: usize,\n\n output: NodeSender<Vec<T>>,\n\n }\n\n\n\n impl<T> UpsampleNode<T>\n\n where\n\n T: Zero + Copy + Send,\n\n {\n\n pub fn new(upsample_factor: usize) -> Self {\n\n UpsampleNode {\n\n upsample_factor,\n\n input: Default::default(),\n\n output: Default::default(),\n\n }\n\n }\n", "file_path": "examples/bpsk_mod.rs", "rank": 51, "score": 31840.253977236705 }, { "content": " write!(f, \"Math error: {}\", desc)\n\n }\n\n}\n\n\n\nimpl error::Error for MathError {}\n\n\n\n/// Some basic math functions used elsewhere in the project\n\npub mod math;\n\n/// Some nodes to aid in the generation of random numbers\n\npub mod rand_node;\n\n/// Some nodes to aid in resampling signals\n\npub mod resample_node;\n", "file_path": "src/util/mod.rs", "rank": 52, "score": 31839.50812913321 }, { "content": "/// # connect_nodes!(node1, output, node2, input);\n\n/// // Connect two nodes named node1 and node2. node1 will now send its\n\n/// // messages to node2. node2 will receive the\n\n/// // message on its receiver named `input`.\n\n/// start_nodes_threadpool!(node1, node2);\n\n/// # }\n\n/// ```\n\n#[macro_export]\n\nmacro_rules! start_nodes_threadpool {\n\n ($($node:ident),+ $(,)?) => {\n\n $(\n\n rayon::spawn(move || {\n\n $node.start();\n\n });\n\n )*\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n", "file_path": "src/node/mod.rs", "rank": 53, "score": 31839.505913402907 }, { "content": "/// ```\n\n#[macro_export]\n\nmacro_rules! start_nodes {\n\n ($($node:ident),+ $(,)?) => {\n\n $(\n\n thread::spawn(move || {\n\n $node.start();\n\n });\n\n )*\n\n }\n\n}\n\n\n\n/// Spawns a thread from a Rayon threadpool for each node in order and starts\n\n/// nodes to run indefinitely.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// # #[macro_use] extern crate comms_rs;\n\n/// # extern crate rayon;\n", "file_path": "src/node/mod.rs", "rank": 54, "score": 31839.16856665775 }, { "content": "/// # pub fn new() -> Self {\n\n/// # Node2 {\n\n/// # input: Default::default(),\n\n/// # }\n\n/// # }\n\n/// #\n\n/// # pub fn run(&mut self, x: u32) -> Result<(), NodeError> {\n\n/// # assert_eq!(x, 1);\n\n/// # Ok(())\n\n/// # }\n\n/// # }\n\n/// # let mut node1 = Node1::new();\n\n/// # let mut node2 = Node2::new();\n\n/// # connect_nodes!(node1, output, node2, input);\n\n///\n\n/// // Connect two nodes named node1 and node2. node1 will now send its\n\n/// // messages to node2. node2 will receive the\n\n/// // message on its receiver named `input`.\n\n/// start_nodes!(node1, node2);\n\n/// # }\n", "file_path": "src/node/mod.rs", "rank": 55, "score": 31838.55187829938 }, { "content": " {\n\n let check = check.lock().unwrap();\n\n assert!(*check);\n\n }\n\n }\n\n\n\n #[test]\n\n /// Constructs a network with three nodes: two aggregating data and one\n\n /// simple node. Node1 is actually doing aggregation whereas Node2\n\n /// operates as a simple node but exists to ensure that there are no\n\n /// errors in the macro. This test also demonstrates how Arc can be\n\n /// used to pass around references through the channels much easier,\n\n /// saving on potential expensive copies.\n\n fn test_aggregate_nodes() {\n\n #[derive(Node)]\n\n #[aggregate]\n\n struct Node1 {\n\n agg: Vec<u32>,\n\n pub output: NodeSender<Arc<Vec<u32>>>,\n\n }\n", "file_path": "src/node/mod.rs", "rank": 56, "score": 31838.541631148582 }, { "content": "use comms_rs::filter::fir_node::BatchFirNode;\n\nuse comms_rs::io::raw_iq::IQBatchOutput;\n\nuse comms_rs::node::graph::Graph;\n\nuse comms_rs::prelude::*;\n\nuse comms_rs::util::math;\n\nuse comms_rs::util::rand_node;\n\nuse num::{Complex, Num, NumCast, Zero};\n\nuse std::fs::File;\n\nuse std::io::BufWriter;\n\nuse std::sync::{Arc, Mutex};\n\nuse std::thread;\n\nuse std::time::Duration;\n\n\n\n/// An example that will generate random numbers, pass them through a BPSK\n\n/// modulation and a pulse shaper, then broadcast them out to a file and\n\n/// via ZeroMQ for visualization.\n", "file_path": "examples/bpsk_mod.rs", "rank": 57, "score": 31838.50904264467 }, { "content": "/// # }\n\n///\n\n/// # impl Node1 {\n\n/// # pub fn new() -> Self {\n\n/// # Node1 {\n\n/// # output: Default::default(),\n\n/// # }\n\n/// # }\n\n/// #\n\n/// # pub fn run(&mut self) -> Result<u32, NodeError> {\n\n/// # Ok(1)\n\n/// # }\n\n/// # }\n\n///\n\n/// # #[derive(Node)]\n\n/// # struct Node2 {\n\n/// # pub input: NodeReceiver<u32>,\n\n/// # }\n\n///\n\n/// # impl Node2 {\n", "file_path": "src/node/mod.rs", "rank": 58, "score": 31838.42802230971 }, { "content": "\n\n #[derive(Node)]\n\n #[pass_by_ref]\n\n struct Node2 {\n\n pub input: NodeReceiver<Arc<Vec<u32>>>,\n\n pub output: NodeSender<Arc<Vec<u32>>>,\n\n }\n\n\n\n impl Node2 {\n\n pub fn new() -> Self {\n\n Node2 {\n\n input: Default::default(),\n\n output: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(\n\n &mut self,\n\n input: &Arc<Vec<u32>>,\n\n ) -> Result<Arc<Vec<u32>>, NodeError> {\n", "file_path": "src/node/mod.rs", "rank": 59, "score": 31838.367359692584 }, { "content": " output: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(&mut self) -> Result<u32, NodeError> {\n\n Ok(1)\n\n }\n\n }\n\n\n\n #[derive(Node)]\n\n struct Node2 {\n\n pub input: NodeReceiver<u32>,\n\n }\n\n\n\n impl Node2 {\n\n pub fn new() -> Self {\n\n Node2 {\n\n input: Default::default(),\n\n }\n\n }\n", "file_path": "src/node/mod.rs", "rank": 60, "score": 31838.34639488312 }, { "content": "\n\n // Creates a node that takes no inputs and returns a value.\n\n #[derive(Node)]\n\n struct NoInputNode {\n\n output: NodeSender<u32>,\n\n }\n\n\n\n impl NoInputNode {\n\n pub fn new() -> Self {\n\n NoInputNode {\n\n output: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(&mut self) -> Result<u32, NodeError> {\n\n Ok(1)\n\n }\n\n }\n\n\n\n #[derive(Node)]\n", "file_path": "src/node/mod.rs", "rank": 61, "score": 31838.335173809664 }, { "content": " thread_rng().fill(random.as_mut_slice());\n\n Ok(Arc::new(random))\n\n }\n\n }\n\n\n\n #[derive(Node)]\n\n #[pass_by_ref]\n\n struct Node2 {\n\n pub input: NodeReceiver<Arc<Vec<i16>>>,\n\n pub output: NodeSender<Arc<Vec<i16>>>,\n\n }\n\n\n\n impl Node2 {\n\n pub fn new() -> Self {\n\n Node2 {\n\n input: Default::default(),\n\n output: Default::default(),\n\n }\n\n }\n\n\n", "file_path": "src/node/mod.rs", "rank": 62, "score": 31838.2823216712 }, { "content": "//! Node1 {\n\n//! output: Default::default(),\n\n//! }\n\n//! }\n\n//!\n\n//! pub fn run(&mut self) -> Result<u32, NodeError> {\n\n//! Ok(1)\n\n//! }\n\n//! }\n\n//!\n\n//! #[derive(Node)]\n\n//! struct Node2 {\n\n//! pub input: NodeReceiver<u32>,\n\n//! }\n\n//!\n\n//! impl Node2 {\n\n//! pub fn new() -> Self {\n\n//! Node2 {\n\n//! input: Default::default(),\n\n//! }\n", "file_path": "src/node/mod.rs", "rank": 63, "score": 31838.266258964697 }, { "content": "/// # output: Default::default(),\n\n/// # }\n\n/// # }\n\n/// #\n\n/// # pub fn run(&mut self) -> Result<u32, NodeError> {\n\n/// # Ok(1)\n\n/// # }\n\n/// # }\n\n/// #\n\n/// # #[derive(Node)]\n\n/// # struct Node2 {\n\n/// # input: NodeReceiver<u32>,\n\n/// # }\n\n/// #\n\n/// # impl Node2 {\n\n/// # pub fn new() -> Self {\n\n/// # Node2 {\n\n/// # input: Default::default(),\n\n/// # }\n\n/// # }\n", "file_path": "src/node/mod.rs", "rank": 64, "score": 31838.046719069287 }, { "content": " pub fn new() -> Self {\n\n Node3 {\n\n count: 0,\n\n input: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(\n\n &mut self,\n\n _val: &Arc<Vec<i16>>,\n\n ) -> Result<(), NodeError> {\n\n self.count += 1;\n\n if self.count == 40000 {\n\n println!(\n\n \"test_threadpool_throughput: Hit goal of 400 million i16 sent.\"\n\n );\n\n }\n\n Ok(())\n\n }\n\n }\n", "file_path": "src/node/mod.rs", "rank": 65, "score": 31838.028228007508 }, { "content": "\n\n pub fn run(&mut self, input: Vec<T>) -> Result<Vec<T>, NodeError> {\n\n let mut out = vec![T::zero(); input.len() * self.upsample_factor];\n\n let mut ix = 0;\n\n for val in input {\n\n out[ix] = val;\n\n ix += self.upsample_factor;\n\n }\n\n Ok(out)\n\n }\n\n }\n\n\n\n // A generic node to convert from one complex type to another.\n\n #[derive(Node)]\n\n struct ConvertNode<T, U>\n\n where\n\n T: Copy + Num + NumCast + Send,\n\n U: Copy + Num + NumCast + Send,\n\n {\n\n input: NodeReceiver<Vec<Complex<T>>>,\n", "file_path": "examples/bpsk_mod.rs", "rank": 66, "score": 31838.020197686776 }, { "content": " impl Node1 {\n\n pub fn new() -> Self {\n\n Node1 {\n\n output: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(&mut self) -> Result<Arc<Vec<i16>>, NodeError> {\n\n let mut random = vec![0i16; 10000];\n\n thread_rng().fill(random.as_mut_slice());\n\n Ok(Arc::new(random))\n\n }\n\n }\n\n\n\n #[derive(Node)]\n\n #[pass_by_ref]\n\n struct Node2 {\n\n pub input: NodeReceiver<Arc<Vec<i16>>>,\n\n pub output: NodeSender<Arc<Vec<i16>>>,\n\n }\n", "file_path": "src/node/mod.rs", "rank": 67, "score": 31837.979913595045 }, { "content": "/// # Node1 {\n\n/// # output: Default::default(),\n\n/// # }\n\n/// # }\n\n/// #\n\n/// # pub fn run(&mut self) -> Result<u32, NodeError> {\n\n/// # Ok(1)\n\n/// # }\n\n/// # }\n\n/// #\n\n/// # #[derive(Node)]\n\n/// # struct Node2 {\n\n/// # input: NodeReceiver<u32>,\n\n/// # }\n\n/// #\n\n/// # impl Node2 {\n\n/// # pub fn new() -> Self {\n\n/// # Node2 {\n\n/// # input: Default::default(),\n\n/// # }\n", "file_path": "src/node/mod.rs", "rank": 68, "score": 31837.960734664728 }, { "content": " struct AnotherNode {\n\n output: NodeSender<f64>,\n\n }\n\n\n\n impl AnotherNode {\n\n pub fn new() -> Self {\n\n AnotherNode {\n\n output: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(&mut self) -> Result<f64, NodeError> {\n\n Ok(2.0)\n\n }\n\n }\n\n\n\n // Creates a node that takes a u32 and a f64, returns a f32, and names\n\n // the receivers recv_u and recv_f.\n\n #[derive(Node)]\n\n struct DoubleInputNode {\n", "file_path": "src/node/mod.rs", "rank": 69, "score": 31837.916673462456 }, { "content": " pub fft: Arc<dyn FFT<f64>>,\n\n pub fft_size: usize,\n\n}\n\n\n\nimpl BatchFFT {\n\n /// Creates a new `BatchFFT`.\n\n ///\n\n /// Requires an FFT plan from the RustFFT crate.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `fft` - FFT plan to be executed in this implementation.\n\n /// * `fft_size` - Size of the FFT to be performed.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use comms_rs::fft::*;\n\n /// use rustfft::FFTplanner;\n\n ///\n", "file_path": "src/fft/mod.rs", "rank": 70, "score": 31837.912983584156 }, { "content": "///\n\n/// This implementation acts on a sample at a time. The underlying library\n\n/// only provides an FFT for type `f64`, so this wrapper will automatically\n\n/// cast any provided input appropriately, although it does expect the general\n\n/// form of `Complex<T>`.\n\npub struct SampleFFT<T> {\n\n pub fft: Arc<dyn FFT<f64>>,\n\n pub fft_size: usize,\n\n pub samples: Vec<Complex<T>>,\n\n}\n\n\n\nimpl<T> SampleFFT<T>\n\nwhere\n\n T: NumCast + Copy + Num,\n\n{\n\n /// Creates a new `SampleFFT`.\n\n ///\n\n /// Requires an FFT plan from the RustFFT crate.\n\n ///\n\n /// # Arguments\n", "file_path": "src/fft/mod.rs", "rank": 71, "score": 31837.71416746113 }, { "content": " output: NodeSender<i32>,\n\n }\n\n\n\n impl PrintNode {\n\n pub fn new() -> Self {\n\n PrintNode {\n\n count: 0,\n\n input: Default::default(),\n\n output: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(&mut self, val: i32) -> Result<i32, NodeError> {\n\n self.count = val;\n\n Ok(val)\n\n }\n\n }\n\n\n\n let mut add_node = AddNode::new();\n\n let mut print_node = PrintNode::new();\n", "file_path": "src/node/mod.rs", "rank": 72, "score": 31837.65790372658 }, { "content": "//! Nodes for demodulating signals.\n\npub mod nco;\n\npub mod phase_estimator;\n\npub mod timing_estimator;\n", "file_path": "src/demodulation/mod.rs", "rank": 73, "score": 31837.65122100358 }, { "content": "//! Nodes for modulating and demodulating signals.\n\n\n\npub mod analog;\n\npub mod analog_node;\n\npub mod digital;\n", "file_path": "src/modulation/mod.rs", "rank": 74, "score": 31837.65122100358 }, { "content": " input1: NodeReceiver<u32>,\n\n input2: NodeReceiver<f64>,\n\n output: NodeSender<f32>,\n\n }\n\n\n\n impl DoubleInputNode {\n\n pub fn new() -> Self {\n\n DoubleInputNode {\n\n input1: Default::default(),\n\n input2: Default::default(),\n\n output: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(&mut self, x: u32, y: f64) -> Result<f32, NodeError> {\n\n Ok((f64::from(x) + y) as f32)\n\n }\n\n }\n\n\n\n #[derive(Node)]\n", "file_path": "src/node/mod.rs", "rank": 75, "score": 31837.595532643212 }, { "content": " }\n\n }\n\n\n\n pub fn run(&mut self) -> Result<i32, NodeError> {\n\n self.count += 1;\n\n Ok(self.count)\n\n }\n\n }\n\n\n\n #[derive(Node)]\n\n struct CounterNode {\n\n input: NodeReceiver<i32>,\n\n count: i32,\n\n output: NodeSender<i32>,\n\n }\n\n\n\n impl CounterNode {\n\n pub fn new() -> Self {\n\n CounterNode {\n\n count: 0,\n", "file_path": "src/node/mod.rs", "rank": 76, "score": 31837.55421345403 }, { "content": "\n\n impl Node2 {\n\n pub fn new() -> Self {\n\n Node2 {\n\n input: Default::default(),\n\n output: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(\n\n &mut self,\n\n x: &Arc<Vec<i16>>,\n\n ) -> Result<Arc<Vec<i16>>, NodeError> {\n\n let mut y = Arc::clone(&x);\n\n for z in Arc::make_mut(&mut y).iter_mut() {\n\n *z = z.saturating_add(1);\n\n }\n\n Ok(y)\n\n }\n\n }\n", "file_path": "src/node/mod.rs", "rank": 77, "score": 31837.401725449658 }, { "content": "\n\n impl Node1 {\n\n pub fn new() -> Self {\n\n Node1 {\n\n agg: vec![],\n\n output: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(&mut self) -> Result<Option<Arc<Vec<u32>>>, NodeError> {\n\n if self.agg.len() < 2 {\n\n self.agg.push(1);\n\n Ok(None)\n\n } else {\n\n let val = self.agg.clone();\n\n self.agg = vec![];\n\n Ok(Some(Arc::new(val)))\n\n }\n\n }\n\n }\n", "file_path": "src/node/mod.rs", "rank": 78, "score": 31837.32749300274 }, { "content": " node3.call().unwrap();\n\n if now.elapsed().as_secs() >= 1 {\n\n break;\n\n }\n\n }\n\n });\n\n assert!(check.join().is_ok());\n\n }\n\n\n\n #[test]\n\n /// Performs a _very_ simplistic throughput analysis. We generate\n\n /// 10000 random i16 values at a time and pass it through the pipeline\n\n /// to see if channels will handle the throughput we hope it will.\n\n /// Make sure to run this test with --release.\n\n fn test_throughput() {\n\n #[derive(Node)]\n\n struct Node1 {\n\n pub output: NodeSender<Arc<Vec<i16>>>,\n\n }\n\n\n", "file_path": "src/node/mod.rs", "rank": 79, "score": 31837.25534498059 }, { "content": " /// ```\n\n /// use comms_rs::fft::*;\n\n /// use num::{Complex, Zero};\n\n /// use rustfft::FFTplanner;\n\n ///\n\n /// let fft_size = 1024;\n\n /// let mut planner = FFTplanner::new(false);\n\n /// let fft = planner.plan_fft(fft_size);\n\n /// let mut batch_fft = BatchFFT::new(fft, fft_size);\n\n ///\n\n /// let result: Vec<Complex<f64>> = batch_fft.run_fft(&vec![Complex::zero(); fft_size][..]);\n\n /// ```\n\n pub fn run_fft<T>(&mut self, data: &[Complex<T>]) -> Vec<Complex<T>>\n\n where\n\n T: NumCast + Copy + Num,\n\n {\n\n // Convert the input type from interleaved values to Complex<f32>.\n\n let mut input: Vec<FFTComplex<f64>> = data\n\n .iter()\n\n .map(|x| {\n", "file_path": "src/fft/mod.rs", "rank": 80, "score": 31837.20939287407 }, { "content": "\n\n impl AddNode {\n\n pub fn new() -> Self {\n\n AddNode {\n\n count: 1,\n\n input: Default::default(),\n\n output: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(&mut self, val: i32) -> Result<i32, NodeError> {\n\n self.count += val;\n\n Ok(self.count)\n\n }\n\n }\n\n\n\n #[derive(Node)]\n\n struct PrintNode {\n\n input: NodeReceiver<i32>,\n\n count: i32,\n", "file_path": "src/node/mod.rs", "rank": 81, "score": 31837.182872650556 }, { "content": "\n\npub mod graph;\n\n\n\nuse std::error;\n\nuse std::fmt;\n\n\n\n#[derive(Clone, Debug)]\n\npub enum NodeError {\n\n DataError,\n\n PermanentError,\n\n DataEnd,\n\n CommError,\n\n}\n\n\n\nimpl fmt::Display for NodeError {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n let desc = match *self {\n\n NodeError::DataError => \"unable to access data\",\n\n NodeError::PermanentError => \"unable to continue executing node\",\n\n NodeError::DataEnd => \"end of data source\",\n", "file_path": "src/node/mod.rs", "rank": 82, "score": 31837.113737814696 }, { "content": "/// #\n\n/// # pub fn run(&mut self, x: u32) -> Result<(), NodeError> {\n\n/// # assert_eq!(x, 1);\n\n/// # Ok(())\n\n/// # }\n\n/// # }\n\n/// let mut node1 = Node1::new();\n\n/// let mut node2 = Node2::new();\n\n///\n\n/// // node1 will now send its messages to node2. node2 will receive the\n\n/// // message on its receiver named `input`.\n\n/// connect_nodes!(node1, output, node2, input);\n\n/// # }\n\n/// ```\n\n///\n\n#[macro_export]\n\nmacro_rules! connect_nodes {\n\n ($n1:ident, $send:ident, $n2:ident, $recv:ident) => {{\n\n let (send, recv) = channel::unbounded();\n\n $n1.$send.push((send, None));\n", "file_path": "src/node/mod.rs", "rank": 83, "score": 31837.089027107246 }, { "content": " }\n\n }\n\n\n\n /// Runs the `SampleFFT`.\n\n ///\n\n /// Takes input `Complex<T>` and performs the FFT specified in\n\n /// construction, and returns the resulting output.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use comms_rs::fft::*;\n\n /// use num::{Complex, Zero};\n\n /// use rustfft::FFTplanner;\n\n ///\n\n /// let fft_size = 1024;\n\n /// let mut planner = FFTplanner::new(false);\n\n /// let fft = planner.plan_fft(fft_size);\n\n /// let mut sample_fft: SampleFFT<f64> = SampleFFT::new(fft, fft_size);\n\n /// sample_fft.samples = vec![Complex::zero(); fft_size];\n", "file_path": "src/fft/mod.rs", "rank": 84, "score": 31836.629185887916 }, { "content": "/// # }\n\n/// #\n\n/// # pub fn run(&mut self, x: u32) -> Result<(), NodeError> {\n\n/// # assert_eq!(x, 1);\n\n/// # Ok(())\n\n/// # }\n\n/// # }\n\n/// let mut node1 = Node1::new();\n\n/// let mut node2 = Node2::new();\n\n///\n\n/// // node1 will now send its messages to node2. node2 will receive the\n\n/// // message on its receiver named `input`. When node1 starts, it will send\n\n/// // a 0 to node2 the first time it's run by start_nodes! and run a normal\n\n/// // loop afterwards.\n\n/// connect_nodes_feedback!(node1, output, node2, input, 0);\n\n/// # }\n\n/// ```\n\n///\n\n#[macro_export]\n\nmacro_rules! connect_nodes_feedback {\n", "file_path": "src/node/mod.rs", "rank": 85, "score": 31836.045546835623 }, { "content": "\n\n let check = thread::spawn(move || {\n\n for _ in 0..10 {\n\n count_node.call().unwrap();\n\n }\n\n assert_eq!(count_node.count, 55);\n\n });\n\n\n\n assert!(check.join().is_ok());\n\n }\n\n\n\n #[test]\n\n /// A test to verify that feedback will work.\n\n fn test_feedback() {\n\n #[derive(Node)]\n\n struct AddNode {\n\n input: NodeReceiver<i32>,\n\n count: i32,\n\n output: NodeSender<i32>,\n\n }\n", "file_path": "src/node/mod.rs", "rank": 86, "score": 31835.334093573478 }, { "content": "\n\n #[derive(Node)]\n\n #[pass_by_ref]\n\n struct Node3 {\n\n pub input: NodeReceiver<Arc<Vec<i16>>>,\n\n count: u32,\n\n }\n\n\n\n impl Node3 {\n\n pub fn new() -> Self {\n\n Node3 {\n\n count: 0,\n\n input: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(\n\n &mut self,\n\n _val: &Arc<Vec<i16>>,\n\n ) -> Result<(), NodeError> {\n", "file_path": "src/node/mod.rs", "rank": 87, "score": 31835.24636338699 }, { "content": " Ok(1)\n\n }\n\n }\n\n\n\n #[derive(Node)]\n\n struct Node2 {\n\n pub input: NodeReceiver<u32>,\n\n pub check: Arc<Mutex<bool>>,\n\n }\n\n\n\n impl Node2 {\n\n pub fn new(check: Arc<Mutex<bool>>) -> Self {\n\n Node2 {\n\n input: Default::default(),\n\n check,\n\n }\n\n }\n\n\n\n pub fn run(&mut self, x: u32) -> Result<(), NodeError> {\n\n let mut check = self.check.lock().unwrap();\n", "file_path": "src/node/mod.rs", "rank": 88, "score": 31835.24032054455 }, { "content": "///\n\n/// # #[derive(Node)]\n\n/// # struct Node2 {\n\n/// # pub input: NodeReceiver<u32>,\n\n/// # }\n\n///\n\n/// # impl Node2 {\n\n/// # pub fn new() -> Self {\n\n/// # Node2 {\n\n/// # input: Default::default(),\n\n/// # }\n\n/// # }\n\n/// #\n\n/// # pub fn run(&mut self, x: u32) -> Result<(), NodeError> {\n\n/// # assert_eq!(x, 1);\n\n/// # Ok(())\n\n/// # }\n\n/// # }\n\n/// # let mut node1 = Node1::new();\n\n/// # let mut node2 = Node2::new();\n", "file_path": "src/node/mod.rs", "rank": 89, "score": 31835.200289404926 }, { "content": "//! }\n\n//!\n\n//! pub fn run(&mut self, x: u32) -> Result<(), NodeError> {\n\n//! assert_eq!(x, 1);\n\n//! Ok(())\n\n//! }\n\n//! }\n\n//!\n\n//! // Now that the structures are created, the user can now instantiate their\n\n//! // nodes and pass in closures for the nodes to execute.\n\n//! let mut node1 = Node1::new();\n\n//! let mut node2 = Node2::new();\n\n//!\n\n//! // Create a connection between two nodes: node1 sending messages and node2\n\n//! // receiving on the `input` receiver in the Node2 structure.\n\n//! connect_nodes!(node1, output, node2, input);\n\n//!\n\n//! // Spawn threads for node1 and node2 and have them executing indefinitely.\n\n//! start_nodes!(node1, node2);\n\n//! ```\n", "file_path": "src/node/mod.rs", "rank": 90, "score": 31835.08965641627 }, { "content": " let mut y = Arc::clone(&input);\n\n for z in Arc::make_mut(&mut y).iter_mut() {\n\n *z += 1;\n\n }\n\n Ok(y)\n\n }\n\n }\n\n\n\n #[derive(Node)]\n\n #[pass_by_ref]\n\n struct Node3 {\n\n pub input: NodeReceiver<Arc<Vec<u32>>>,\n\n }\n\n\n\n impl Node3 {\n\n pub fn new() -> Self {\n\n Node3 {\n\n input: Default::default(),\n\n }\n\n }\n", "file_path": "src/node/mod.rs", "rank": 91, "score": 31834.991109823564 }, { "content": " connect_nodes!(add_node, output, print_node, input);\n\n connect_nodes_feedback!(print_node, output, add_node, input, 0);\n\n start_nodes!(add_node);\n\n let check = thread::spawn(move || {\n\n for (print, val) in &print_node.output {\n\n match val {\n\n Some(v) => print.send(*v).unwrap(),\n\n None => continue,\n\n }\n\n }\n\n for _ in 0..10 {\n\n print_node.call().unwrap();\n\n }\n\n assert_eq!(print_node.count, 512);\n\n });\n\n assert!(check.join().is_ok());\n\n }\n\n}\n", "file_path": "src/node/mod.rs", "rank": 92, "score": 31834.749816776806 }, { "content": " self.count += 1;\n\n if self.count == 40000 {\n\n println!(\n\n \"test_throughput: Hit goal of 400 million i16 sent.\"\n\n );\n\n }\n\n Ok(())\n\n }\n\n }\n\n\n\n let mut node1 = Node1::new();\n\n let mut node2 = Node2::new();\n\n let mut node3 = Node3::new();\n\n\n\n connect_nodes!(node1, output, node2, input);\n\n connect_nodes!(node2, output, node3, input);\n\n start_nodes!(node1, node2, node3);\n\n thread::sleep(Duration::from_secs(1));\n\n }\n\n\n", "file_path": "src/node/mod.rs", "rank": 93, "score": 31834.552014440473 }, { "content": " struct CheckNode {\n\n input: NodeReceiver<f32>,\n\n }\n\n\n\n impl CheckNode {\n\n pub fn new() -> Self {\n\n CheckNode {\n\n input: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(&mut self, x: f32) -> Result<(), NodeError> {\n\n assert!(x - 3.0f32 < std::f32::EPSILON, \"Fan-out failed.\");\n\n Ok(())\n\n }\n\n }\n\n\n\n // Now, you can instantiate your nodes as usual.\n\n let mut node1 = NoInputNode::new();\n\n let mut node2 = AnotherNode::new();\n", "file_path": "src/node/mod.rs", "rank": 94, "score": 31834.251006164803 }, { "content": " input: Default::default(),\n\n output: Default::default(),\n\n }\n\n }\n\n\n\n pub fn run(&mut self, val: i32) -> Result<i32, NodeError> {\n\n self.count += val;\n\n Ok(self.count)\n\n }\n\n }\n\n\n\n let mut one_node = OneNode::new();\n\n let mut count_node = CounterNode::new();\n\n connect_nodes!(one_node, output, count_node, input);\n\n\n\n thread::spawn(move || {\n\n for _ in 0..10 {\n\n one_node.call().unwrap();\n\n }\n\n });\n", "file_path": "src/node/mod.rs", "rank": 95, "score": 31834.177284708723 }, { "content": "\n\n pub fn run(\n\n &mut self,\n\n input: &Arc<Vec<u32>>,\n\n ) -> Result<(), NodeError> {\n\n assert_eq!(**input, vec![2, 2]);\n\n Ok(())\n\n }\n\n }\n\n\n\n let mut node1 = Node1::new();\n\n let mut node2 = Node2::new();\n\n let mut node3 = Node3::new();\n\n\n\n connect_nodes!(node1, output, node2, input);\n\n connect_nodes!(node2, output, node3, input);\n\n start_nodes!(node1, node2);\n\n let check = thread::spawn(move || {\n\n let now = Instant::now();\n\n loop {\n", "file_path": "src/node/mod.rs", "rank": 96, "score": 31833.984851357603 }, { "content": "//! Utility nodes that don't fit into any specific category and helper\n\n//! functions for developing your own nodes.\n\n\n\nuse std::error;\n\nuse std::fmt;\n\n\n\n#[derive(Clone, Debug)]\n\npub enum MathError {\n\n ConvertError,\n\n InvalidRolloffError,\n\n}\n\n\n\nimpl fmt::Display for MathError {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n let desc = match *self {\n\n MathError::ConvertError => \"Type conversion from generic failed\",\n\n MathError::InvalidRolloffError => {\n\n \"Invalid rolloff parameter, must be on interval [0.0, 1.0]\"\n\n }\n\n };\n", "file_path": "src/util/mod.rs", "rank": 97, "score": 31833.922627013046 }, { "content": " ///\n\n /// let result: Vec<Complex<f64>> = sample_fft.run_fft();\n\n /// ```\n\n pub fn run_fft(&mut self) -> Vec<Complex<T>> {\n\n let mut input: Vec<FFTComplex<f64>> = self\n\n .samples\n\n .iter()\n\n .map(|x| {\n\n FFTComplex::new(x.re.to_f64().unwrap(), x.im.to_f64().unwrap())\n\n })\n\n .collect();\n\n let mut output: Vec<FFTComplex<f64>> =\n\n vec![FFTComplex::zero(); self.fft_size];\n\n self.fft.process(&mut input[..], &mut output[..]);\n\n\n\n // After the FFT, convert back to interleaved values.\n\n let res: Vec<Complex<T>> = output\n\n .iter()\n\n .map(|x| {\n\n Complex::new(T::from(x.re).unwrap(), T::from(x.im).unwrap())\n\n })\n\n .collect();\n\n res\n\n }\n\n}\n", "file_path": "src/fft/mod.rs", "rank": 98, "score": 31833.761075749688 }, { "content": " ///\n\n /// * `fft` - FFT plan to be executed in this implementation.\n\n /// * `fft_size` - Size of the FFT to be performed.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use comms_rs::fft::*;\n\n /// use rustfft::FFTplanner;\n\n ///\n\n /// let fft_size = 1024;\n\n /// let mut planner = FFTplanner::new(false);\n\n /// let fft = planner.plan_fft(fft_size);\n\n /// let sample_fft: SampleFFT<f64> = SampleFFT::new(fft, fft_size);\n\n /// ```\n\n pub fn new(fft: Arc<dyn FFT<f64>>, fft_size: usize) -> SampleFFT<T> {\n\n SampleFFT {\n\n fft,\n\n fft_size,\n\n samples: Vec::new(),\n", "file_path": "src/fft/mod.rs", "rank": 99, "score": 31833.62399485333 } ]
Rust
buildkit-llb/src/ops/fs/copy.rs
student-coin/dockerfile-plus
559196e0838404d32fa2f1b81151124573a64898
use std::collections::HashMap; use std::fmt::Debug; use std::path::{Path, PathBuf}; use buildkit_proto::pb; use super::path::{LayerPath, UnsetPath}; use super::FileOperation; use crate::serialization::{Context, Result}; use crate::utils::OutputIdx; #[derive(Debug)] pub struct CopyOperation<From: Debug, To: Debug> { source: From, destination: To, follow_symlinks: bool, recursive: bool, create_path: bool, wildcard: bool, description: HashMap<String, String>, caps: HashMap<String, bool>, } type OpWithoutSource = CopyOperation<UnsetPath, UnsetPath>; type OpWithSource<'a> = CopyOperation<LayerPath<'a, PathBuf>, UnsetPath>; type OpWithDestination<'a> = CopyOperation<LayerPath<'a, PathBuf>, (OutputIdx, LayerPath<'a, PathBuf>)>; impl OpWithoutSource { pub(crate) fn new() -> OpWithoutSource { let mut caps = HashMap::<String, bool>::new(); caps.insert("file.base".into(), true); CopyOperation { source: UnsetPath, destination: UnsetPath, follow_symlinks: false, recursive: false, create_path: false, wildcard: false, caps, description: Default::default(), } } pub fn from<P>(self, source: LayerPath<'_, P>) -> OpWithSource where P: AsRef<Path>, { CopyOperation { source: source.into_owned(), destination: UnsetPath, follow_symlinks: self.follow_symlinks, recursive: self.recursive, create_path: self.create_path, wildcard: self.wildcard, description: self.description, caps: self.caps, } } } impl<'a> OpWithSource<'a> { pub fn to<P>(self, output: OutputIdx, destination: LayerPath<'a, P>) -> OpWithDestination<'a> where P: AsRef<Path>, { CopyOperation { source: self.source, destination: (output, destination.into_owned()), follow_symlinks: self.follow_symlinks, recursive: self.recursive, create_path: self.create_path, wildcard: self.wildcard, description: self.description, caps: self.caps, } } } impl<'a> OpWithDestination<'a> { pub fn into_operation(self) -> super::sequence::SequenceOperation<'a> { super::sequence::SequenceOperation::new().append(self) } } impl<From, To> CopyOperation<From, To> where From: Debug, To: Debug, { pub fn follow_symlinks(mut self, value: bool) -> Self { self.follow_symlinks = value; self } pub fn recursive(mut self, value: bool) -> Self { self.recursive = value; self } pub fn create_path(mut self, value: bool) -> Self { self.create_path = value; self } pub fn wildcard(mut self, value: bool) -> Self { self.wildcard = value; self } } impl<'a> FileOperation for OpWithDestination<'a> { fn output(&self) -> i32 { self.destination.0.into() } fn serialize_inputs(&self, cx: &mut Context) -> Result<Vec<pb::Input>> { let mut inputs = if let LayerPath::Other(ref op, ..) = self.source { let serialized_from_head = cx.register(op.operation())?; vec![pb::Input { digest: serialized_from_head.digest.clone(), index: op.output().into(), }] } else { vec![] }; if let LayerPath::Other(ref op, ..) = self.destination.1 { let serialized_to_head = cx.register(op.operation())?; inputs.push(pb::Input { digest: serialized_to_head.digest.clone(), index: op.output().into(), }); } Ok(inputs) } fn serialize_action( &self, inputs_count: usize, inputs_offset: usize, ) -> Result<pb::FileAction> { let (src_idx, src_offset, src) = match self.source { LayerPath::Scratch(ref path) => (-1, 0, path.to_string_lossy().into()), LayerPath::Other(_, ref path) => { (inputs_offset as i64, 1, path.to_string_lossy().into()) } LayerPath::Own(ref output, ref path) => { let output: i64 = output.into(); ( inputs_count as i64 + output, 0, path.to_string_lossy().into(), ) } }; let (dest_idx, dest) = match self.destination.1 { LayerPath::Scratch(ref path) => (-1, path.to_string_lossy().into()), LayerPath::Other(_, ref path) => ( inputs_offset as i32 + src_offset, path.to_string_lossy().into(), ), LayerPath::Own(ref output, ref path) => { let output: i32 = output.into(); (inputs_count as i32 + output, path.to_string_lossy().into()) } }; Ok(pb::FileAction { input: i64::from(dest_idx), secondary_input: src_idx, output: i64::from(self.output()), action: Some(pb::file_action::Action::Copy(pb::FileActionCopy { src, dest, follow_symlink: self.follow_symlinks, dir_copy_contents: self.recursive, create_dest_path: self.create_path, allow_wildcard: self.wildcard, mode: -1, timestamp: -1, ..Default::default() })), }) } }
use std::collections::HashMap; use std::fmt::Debug; use std::path::{Path, PathBuf}; use buildkit_proto::pb; use super::path::{LayerPath, UnsetPath}; use super::FileOperation; use crate::serialization::{Context, Result}; use crate::utils::OutputIdx; #[derive(Debug)] pub struct CopyOperation<From: Debug, To: Debug> { source: From, destination: To, follow_symlinks: bool, recursive: bool, create_path: bool, wildcard: bool, description: HashMap<String, String>, caps: HashMap<String, bool>, } type OpWithoutSource = CopyOperation<UnsetPath, UnsetPath>; type OpWithSource<'a> = CopyOperation<LayerPath<'a, PathBuf>, UnsetPath>; type OpWithDestination<'a> = CopyOperation<LayerPath<'a, PathBuf>, (OutputIdx, LayerPath<'a, PathBuf>)>; impl OpWithoutSource { pub(crate) fn new() -> OpWithoutSource { let mut caps = HashMap::<String, bool>::new(); caps.insert("file.base".into(), true); CopyOperation { source: UnsetPath, destination: UnsetPath, follow_symlinks: false, recursive: false, create_path: false, wildcard: false, caps, description: Default::default(), } } pub fn from<P>(self, source: LayerPath<'_, P>) -> OpWithSource where P: AsRef<Path>, { CopyOperation { source: source.into_owned(), destination: Unse
ion: self.description, caps: self.caps, } } } impl<'a> OpWithSource<'a> { pub fn to<P>(self, output: OutputIdx, destination: LayerPath<'a, P>) -> OpWithDestination<'a> where P: AsRef<Path>, { CopyOperation { source: self.source, destination: (output, destination.into_owned()), follow_symlinks: self.follow_symlinks, recursive: self.recursive, create_path: self.create_path, wildcard: self.wildcard, description: self.description, caps: self.caps, } } } impl<'a> OpWithDestination<'a> { pub fn into_operation(self) -> super::sequence::SequenceOperation<'a> { super::sequence::SequenceOperation::new().append(self) } } impl<From, To> CopyOperation<From, To> where From: Debug, To: Debug, { pub fn follow_symlinks(mut self, value: bool) -> Self { self.follow_symlinks = value; self } pub fn recursive(mut self, value: bool) -> Self { self.recursive = value; self } pub fn create_path(mut self, value: bool) -> Self { self.create_path = value; self } pub fn wildcard(mut self, value: bool) -> Self { self.wildcard = value; self } } impl<'a> FileOperation for OpWithDestination<'a> { fn output(&self) -> i32 { self.destination.0.into() } fn serialize_inputs(&self, cx: &mut Context) -> Result<Vec<pb::Input>> { let mut inputs = if let LayerPath::Other(ref op, ..) = self.source { let serialized_from_head = cx.register(op.operation())?; vec![pb::Input { digest: serialized_from_head.digest.clone(), index: op.output().into(), }] } else { vec![] }; if let LayerPath::Other(ref op, ..) = self.destination.1 { let serialized_to_head = cx.register(op.operation())?; inputs.push(pb::Input { digest: serialized_to_head.digest.clone(), index: op.output().into(), }); } Ok(inputs) } fn serialize_action( &self, inputs_count: usize, inputs_offset: usize, ) -> Result<pb::FileAction> { let (src_idx, src_offset, src) = match self.source { LayerPath::Scratch(ref path) => (-1, 0, path.to_string_lossy().into()), LayerPath::Other(_, ref path) => { (inputs_offset as i64, 1, path.to_string_lossy().into()) } LayerPath::Own(ref output, ref path) => { let output: i64 = output.into(); ( inputs_count as i64 + output, 0, path.to_string_lossy().into(), ) } }; let (dest_idx, dest) = match self.destination.1 { LayerPath::Scratch(ref path) => (-1, path.to_string_lossy().into()), LayerPath::Other(_, ref path) => ( inputs_offset as i32 + src_offset, path.to_string_lossy().into(), ), LayerPath::Own(ref output, ref path) => { let output: i32 = output.into(); (inputs_count as i32 + output, path.to_string_lossy().into()) } }; Ok(pb::FileAction { input: i64::from(dest_idx), secondary_input: src_idx, output: i64::from(self.output()), action: Some(pb::file_action::Action::Copy(pb::FileActionCopy { src, dest, follow_symlink: self.follow_symlinks, dir_copy_contents: self.recursive, create_dest_path: self.create_path, allow_wildcard: self.wildcard, mode: -1, timestamp: -1, ..Default::default() })), }) } }
tPath, follow_symlinks: self.follow_symlinks, recursive: self.recursive, create_path: self.create_path, wildcard: self.wildcard, descript
function_block-random_span
[ { "content": "pub fn from_env<T, I>(pairs: I) -> Result<T>\n\nwhere\n\n T: DeserializeOwned,\n\n I: IntoIterator<Item = (String, String)>,\n\n{\n\n let owned_pairs = pairs.into_iter().collect::<Vec<_>>();\n\n let pairs = {\n\n owned_pairs.iter().filter_map(|(name, value)| {\n\n if name.starts_with(\"BUILDKIT_FRONTEND_OPT_\") {\n\n Some(value)\n\n } else {\n\n None\n\n }\n\n })\n\n };\n\n\n\n let deserializer = EnvDeserializer {\n\n vals: pairs.map(|value| extract_name_and_value(&value)),\n\n };\n\n\n\n Ok(T::deserialize(deserializer)?)\n\n}\n\n\n", "file_path": "dockerfile-plus/src/options.rs", "rank": 0, "score": 119353.22785735317 }, { "content": "#[derive(Debug)]\n\nstruct EnvDeserializer<P> {\n\n vals: P,\n\n}\n\n\n", "file_path": "dockerfile-plus/src/options.rs", "rank": 1, "score": 103249.88702063338 }, { "content": "pub trait FileOperation: Debug + Send + Sync {\n\n fn output(&self) -> i32;\n\n\n\n fn serialize_inputs(&self, cx: &mut Context) -> Result<Vec<pb::Input>>;\n\n fn serialize_action(&self, inputs_count: usize, inputs_offset: usize)\n\n -> Result<pb::FileAction>;\n\n}\n\n\n", "file_path": "buildkit-llb/src/ops/fs/mod.rs", "rank": 4, "score": 84330.13439009895 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n tonic_build::configure()\n\n .build_client(true)\n\n .build_server(true)\n\n .compile(DEFS, PATHS)?;\n\n\n\n Ok(())\n\n}\n", "file_path": "buildkit-proto/build.rs", "rank": 6, "score": 80684.48803103683 }, { "content": "#[test]\n\nfn prefixes() {\n\n crate::check_op!(\n\n GitSource::new(\"http://any.url\"),\n\n |digest| { \"sha256:ecde982e19ace932e5474e57b0ca71ba690ed7d28abff2a033e8f969e22bf2d8\" },\n\n |description| { vec![] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"git://any.url\".into(),\n\n attrs: Default::default(),\n\n })\n\n },\n\n );\n\n\n\n crate::check_op!(\n\n GitSource::new(\"https://any.url\"),\n\n |digest| { \"sha256:ecde982e19ace932e5474e57b0ca71ba690ed7d28abff2a033e8f969e22bf2d8\" },\n\n |description| { vec![] },\n", "file_path": "buildkit-llb/src/ops/source/git.rs", "rank": 7, "score": 80201.89027429 }, { "content": "#[test]\n\nfn with_reference() {\n\n crate::check_op!(\n\n GitSource::new(\"any.url\").with_reference(\"abcdef\"),\n\n |digest| { \"sha256:f59aa7f8db62e0b5c2a1da396752ba8a2bb0b5d28ddcfdd1d4f822d26ebfe3cf\" },\n\n |description| { vec![] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"git://any.url#abcdef\".into(),\n\n attrs: Default::default(),\n\n })\n\n },\n\n );\n\n}\n", "file_path": "buildkit-llb/src/ops/source/git.rs", "rank": 8, "score": 80201.89027429 }, { "content": "#[test]\n\nfn serialization() {\n\n crate::check_op!(\n\n GitSource::new(\"any.url\"),\n\n |digest| { \"sha256:ecde982e19ace932e5474e57b0ca71ba690ed7d28abff2a033e8f969e22bf2d8\" },\n\n |description| { vec![] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"git://any.url\".into(),\n\n attrs: Default::default(),\n\n })\n\n },\n\n );\n\n\n\n crate::check_op!(\n\n GitSource::new(\"any.url\").custom_name(\"git custom name\"),\n\n |digest| { \"sha256:ecde982e19ace932e5474e57b0ca71ba690ed7d28abff2a033e8f969e22bf2d8\" },\n\n |description| { vec![(\"llb.customname\", \"git custom name\")] },\n", "file_path": "buildkit-llb/src/ops/source/git.rs", "rank": 9, "score": 80201.89027429 }, { "content": "#[test]\n\nfn serialization() {\n\n crate::check_op!(\n\n LocalSource::new(\"context\"),\n\n |digest| { \"sha256:a60212791641cbeaa3a49de4f7dff9e40ae50ec19d1be9607232037c1db16702\" },\n\n |description| { vec![] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"local://context\".into(),\n\n attrs: Default::default(),\n\n })\n\n },\n\n );\n\n\n\n crate::check_op!(\n\n LocalSource::new(\"context\").custom_name(\"context custom name\"),\n\n |digest| { \"sha256:a60212791641cbeaa3a49de4f7dff9e40ae50ec19d1be9607232037c1db16702\" },\n\n |description| { vec![(\"llb.customname\", \"context custom name\")] },\n", "file_path": "buildkit-llb/src/ops/source/local.rs", "rank": 10, "score": 80201.89027429 }, { "content": "#[test]\n\nfn serialization() {\n\n crate::check_op!(\n\n HttpSource::new(\"http://any.url/with/path\"),\n\n |digest| { \"sha256:22ec64461f39dd3b54680fc240b459248b1ced597f113b5d692abe9695860d12\" },\n\n |description| { vec![] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"http://any.url/with/path\".into(),\n\n attrs: Default::default(),\n\n })\n\n },\n\n );\n\n\n\n crate::check_op!(\n\n HttpSource::new(\"http://any.url/with/path\").custom_name(\"git custom name\"),\n\n |digest| { \"sha256:22ec64461f39dd3b54680fc240b459248b1ced597f113b5d692abe9695860d12\" },\n\n |description| { vec![(\"llb.customname\", \"git custom name\")] },\n", "file_path": "buildkit-llb/src/ops/source/http.rs", "rank": 11, "score": 80201.89027429 }, { "content": "#[test]\n\nfn serialization() {\n\n crate::check_op!(\n\n ImageSource::new(\"rustlang/rust:nightly\"),\n\n |digest| { \"sha256:dee2a3d7dd482dd8098ba543ff1dcb01efd29fcd16fdb0979ef556f38564543a\" },\n\n |description| { vec![] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://docker.io/rustlang/rust:nightly\".into(),\n\n attrs: Default::default(),\n\n })\n\n },\n\n );\n\n\n\n crate::check_op!(\n\n ImageSource::new(\"library/alpine:latest\"),\n\n |digest| { \"sha256:0e6b31ceed3e6dc542018f35a53a0e857e6a188453d32a2a5bbe7aa2971c1220\" },\n\n |description| { vec![] },\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 12, "score": 80201.89027429 }, { "content": "#[test]\n\nfn image_name() {\n\n crate::check_op!(ImageSource::new(\"rustlang/rust\"), |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://docker.io/rustlang/rust:latest\".into(),\n\n attrs: Default::default(),\n\n })\n\n });\n\n\n\n crate::check_op!(ImageSource::new(\"rust:nightly\"), |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://docker.io/library/rust:nightly\".into(),\n\n attrs: Default::default(),\n\n })\n\n });\n\n\n\n crate::check_op!(ImageSource::new(\"rust\"), |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://docker.io/library/rust:latest\".into(),\n\n attrs: Default::default(),\n\n })\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 13, "score": 78500.34372088609 }, { "content": "#[test]\n\nfn resolve_mode() {\n\n crate::check_op!(\n\n ImageSource::new(\"rustlang/rust:nightly\").with_resolve_mode(ResolveMode::Default),\n\n |digest| { \"sha256:792e246751e84b9a5e40c28900d70771a07e8cc920c1039cdddfc6bf69256dfe\" },\n\n |description| { vec![] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://docker.io/rustlang/rust:nightly\".into(),\n\n attrs: crate::utils::test::to_map(vec![(\"image.resolvemode\", \"default\")]),\n\n })\n\n },\n\n );\n\n\n\n crate::check_op!(\n\n ImageSource::new(\"rustlang/rust:nightly\").with_resolve_mode(ResolveMode::ForcePull),\n\n |digest| { \"sha256:0bd920010eab701bdce44c61d220e6943d56d3fb9a9fa4e773fc060c0d746122\" },\n\n |description| { vec![] },\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 14, "score": 78500.34372088609 }, { "content": "fn extract_name_and_value(mut raw_value: &str) -> (&str, EnvValue) {\n\n if raw_value.starts_with(\"build-arg:\") {\n\n raw_value = raw_value.trim_start_matches(\"build-arg:\");\n\n }\n\n\n\n let mut parts = raw_value.splitn(2, '=');\n\n let name = parts.next().unwrap();\n\n\n\n match parts.next() {\n\n None => (name, EnvValue::Flag),\n\n Some(text) if text.is_empty() => (name, EnvValue::Flag),\n\n Some(text) if &text[0..1] == \"[\" || &text[0..1] == \"{\" => (name, EnvValue::Json(text)),\n\n Some(text) => (name, EnvValue::Text(text)),\n\n }\n\n}\n\n\n\nimpl<'de> IntoDeserializer<'de, serde::de::value::Error> for EnvValue<'de> {\n\n type Deserializer = Self;\n\n\n\n fn into_deserializer(self) -> Self::Deserializer {\n", "file_path": "dockerfile-plus/src/options.rs", "rank": 15, "score": 77141.80320970429 }, { "content": "fn build_init_commands(image: &ImageSource) -> Vec<OperationOutput> {\n\n (0..100)\n\n .map(|idx| {\n\n let base_dir = format!(\"/file/{}\", idx);\n\n let shell = format!(\"echo 'test {}' > /out{}/file.out\", idx, base_dir);\n\n\n\n let output_mount = FileSystem::mkdir(OutputIdx(0), LayerPath::Scratch(&base_dir))\n\n .make_parents(true)\n\n .into_operation()\n\n .ignore_cache(true)\n\n .ref_counted();\n\n\n\n Command::run(\"/bin/sh\")\n\n .args(&[\"-c\", &shell])\n\n .mount(Mount::ReadOnlyLayer(image.output(), \"/\"))\n\n .mount(Mount::Layer(OutputIdx(0), output_mount.output(0), \"/out\"))\n\n .ignore_cache(true)\n\n .ref_counted()\n\n .output(0)\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "buildkit-llb/examples/highly-parallel.rs", "rank": 16, "score": 63292.32039069585 }, { "content": "#[derive(Debug, Deserialize)]\n\nstruct DockerfileOptions {\n\n filename: Option<PathBuf>,\n\n}\n\n\n\nconst INCLUDE_COMMAND: &str = \"INCLUDE+\";\n\n\n\nasync fn dockerfile_trap(\n\n mut client: LlbBridgeClient<Channel>,\n\n dockerfile_frontend: DockerfileFrontend,\n\n dockerfile_contents: String,\n\n) -> Result<ReturnRequest> {\n\n let mut result: Vec<String> = vec![];\n\n let context_source = Source::local(\"context\");\n\n let context_layer = solve(&mut client, Terminal::with(context_source.output())).await?;\n\n\n\n fn replace(\n\n l : & String,\n\n r : &mut Vec<String>,\n\n c : &mut LlbBridgeClient<Channel>,\n\n ctx : & String\n", "file_path": "dockerfile-plus/src/main.rs", "rank": 17, "score": 55076.55444373955 }, { "content": "struct ProxyLlbServer {\n\n client: Arc<RwLock<LlbBridgeClient<Channel>>>,\n\n result_sender: Sender<frontend::ReturnRequest>,\n\n\n\n dockerfile_name: String,\n\n dockerfile_contents: Vec<u8>,\n\n}\n\n\n\nimpl ProxyLlbServer {\n\n fn new(\n\n client: LlbBridgeClient<Channel>,\n\n result_sender: Sender<frontend::ReturnRequest>,\n\n dockerfile_name: String,\n\n dockerfile_contents: Vec<u8>,\n\n ) -> Self {\n\n ProxyLlbServer {\n\n client: Arc::new(RwLock::new(client)),\n\n result_sender,\n\n dockerfile_name,\n\n dockerfile_contents,\n", "file_path": "dockerfile-plus/src/dockerfile_frontend.rs", "rank": 18, "score": 53264.10700414187 }, { "content": "fn main() {\n\n let builder_image =\n\n Source::image(\"library/alpine:latest\").custom_name(\"Using alpine:latest as a builder\");\n\n\n\n let command = {\n\n Command::run(\"/bin/sh\")\n\n .args(&[\"-c\", \"echo 'test string 5' > /out/file0\"])\n\n .custom_name(\"create a dummy file\")\n\n .mount(Mount::ReadOnlyLayer(builder_image.output(), \"/\"))\n\n .mount(Mount::Scratch(OutputIdx(0), \"/out\"))\n\n };\n\n\n\n let fs = {\n\n FileSystem::sequence()\n\n .custom_name(\"do multiple file system manipulations\")\n\n .append(\n\n FileSystem::copy()\n\n .from(LayerPath::Other(command.output(0), \"/file0\"))\n\n .to(OutputIdx(0), LayerPath::Other(command.output(0), \"/file1\")),\n\n )\n", "file_path": "buildkit-llb/examples/scratch.rs", "rank": 19, "score": 51885.602638147 }, { "content": "fn main() {\n\n let bitflags_archive = Source::http(\"https://crates.io/api/v1/crates/bitflags/1.0.4/download\")\n\n .with_file_name(\"bitflags.tar\");\n\n\n\n let alpine = Source::image(\"library/alpine:latest\");\n\n let bitflags_unpacked = {\n\n Command::run(\"/bin/tar\")\n\n .args(&[\n\n \"-xvzC\",\n\n \"/out\",\n\n \"--strip-components=1\",\n\n \"-f\",\n\n \"/in/bitflags.tar\",\n\n ])\n\n .mount(Mount::ReadOnlyLayer(alpine.output(), \"/\"))\n\n .mount(Mount::ReadOnlyLayer(bitflags_archive.output(), \"/in\"))\n\n .mount(Mount::Scratch(OutputIdx(0), \"/out\"))\n\n };\n\n\n\n let env_logger_repo = Source::git(\"https://github.com/sebasmagri/env_logger.git\")\n", "file_path": "buildkit-llb/examples/network.rs", "rank": 20, "score": 51885.602638147 }, { "content": "fn main() {\n\n let image = Source::image(\"library/alpine:latest\");\n\n let commands = build_init_commands(&image);\n\n let commands = build_modify_commands(&image, commands);\n\n\n\n let base_fs = FileSystem::sequence()\n\n .custom_name(\"assemble outputs\")\n\n .append(FileSystem::mkdir(\n\n OutputIdx(0),\n\n LayerPath::Scratch(\"/files\"),\n\n ));\n\n\n\n let (final_fs, final_output) =\n\n commands\n\n .into_iter()\n\n .zip(0..)\n\n .fold((base_fs, 0), |(fs, last_output), (output, idx)| {\n\n let layer = fs.append(\n\n FileSystem::copy()\n\n .from(LayerPath::Other(output, format!(\"/file-{}.out\", idx)))\n", "file_path": "buildkit-llb/examples/highly-parallel.rs", "rank": 21, "score": 50918.51692782246 }, { "content": "#[test]\n\nfn serialization() {\n\n use crate::prelude::*;\n\n\n\n let context = Source::local(\"context\");\n\n let builder_image = Source::image(\"rustlang/rust:nightly\");\n\n let final_image = Source::image(\"library/alpine:latest\");\n\n\n\n let first_command = Command::run(\"rustc\")\n\n .args(&[\"--crate-name\", \"crate-1\"])\n\n .mount(Mount::ReadOnlyLayer(builder_image.output(), \"/\"))\n\n .mount(Mount::ReadOnlyLayer(context.output(), \"/context\"))\n\n .mount(Mount::Scratch(OutputIdx(0), \"/target\"));\n\n\n\n let second_command = Command::run(\"rustc\")\n\n .args(&[\"--crate-name\", \"crate-2\"])\n\n .mount(Mount::ReadOnlyLayer(builder_image.output(), \"/\"))\n\n .mount(Mount::ReadOnlyLayer(context.output(), \"/context\"))\n\n .mount(Mount::Scratch(OutputIdx(0), \"/target\"));\n\n\n\n let assembly_op = FileSystem::sequence()\n", "file_path": "buildkit-llb/src/ops/terminal.rs", "rank": 22, "score": 50918.51692782246 }, { "content": "fn main() {\n\n Terminal::with(build_graph())\n\n .write_definition(stdout())\n\n .unwrap()\n\n}\n\n\n", "file_path": "buildkit-llb/examples/scratch-owned.rs", "rank": 23, "score": 50918.51692782246 }, { "content": "#[test]\n\nfn serialization() {\n\n use crate::prelude::*;\n\n use buildkit_proto::pb::{op::Op, ExecOp, Meta, NetMode, SecurityMode};\n\n\n\n crate::check_op!(\n\n {\n\n Command::run(\"/bin/sh\")\n\n .args(&[\"-c\", \"echo 'test string' > /out/file0\"])\n\n .env(\"HOME\", \"/root\")\n\n .custom_name(\"exec custom name\")\n\n },\n\n |digest| { \"sha256:dc9a5a3cd84bb1c7b633f1750fdfccd9d0a69d060f8e3babb297bc190e2d7484\" },\n\n |description| { vec![(\"llb.customname\", \"exec custom name\")] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Exec(ExecOp {\n\n mounts: vec![],\n\n network: NetMode::Unset.into(),\n", "file_path": "buildkit-llb/src/ops/exec/mod.rs", "rank": 24, "score": 50006.81925011307 }, { "content": "#[test]\n\nfn copy_serialization() {\n\n use crate::prelude::*;\n\n use buildkit_proto::pb::{file_action::Action, op::Op, FileAction, FileActionCopy, FileOp};\n\n\n\n let context = Source::local(\"context\");\n\n let builder_image = Source::image(\"rustlang/rust:nightly\");\n\n\n\n let operation = FileSystem::sequence()\n\n .append(\n\n FileSystem::copy()\n\n .from(LayerPath::Other(context.output(), \"Cargo.toml\"))\n\n .to(OutputIdx(0), LayerPath::Scratch(\"Cargo.toml\")),\n\n )\n\n .append(\n\n FileSystem::copy()\n\n .from(LayerPath::Other(builder_image.output(), \"/bin/sh\"))\n\n .to(OutputIdx(1), LayerPath::Own(OwnOutputIdx(0), \"/bin/sh\")),\n\n )\n\n .append(\n\n FileSystem::copy()\n", "file_path": "buildkit-llb/src/ops/fs/mod.rs", "rank": 25, "score": 49145.8837053224 }, { "content": "#[test]\n\nfn mkfile_serialization() {\n\n use crate::prelude::*;\n\n use buildkit_proto::pb::{file_action::Action, op::Op, FileAction, FileActionMkFile, FileOp};\n\n\n\n let context = Source::local(\"context\");\n\n\n\n let operation = FileSystem::sequence()\n\n .append(\n\n FileSystem::mkfile(\n\n OutputIdx(0),\n\n LayerPath::Other(context.output(), \"/build-plan.json\"),\n\n )\n\n .data(b\"any bytes\".to_vec()),\n\n )\n\n .append(FileSystem::mkfile(\n\n OutputIdx(1),\n\n LayerPath::Scratch(\"/build-graph.json\"),\n\n ))\n\n .append(FileSystem::mkfile(\n\n OutputIdx(2),\n", "file_path": "buildkit-llb/src/ops/fs/mod.rs", "rank": 26, "score": 49145.8837053224 }, { "content": "#[test]\n\nfn serialization_with_user() {\n\n use crate::prelude::*;\n\n use buildkit_proto::pb::{op::Op, ExecOp, Meta, NetMode, SecurityMode};\n\n\n\n crate::check_op!(\n\n Command::run(\"cargo\").args(&[\"build\"]).user(\"builder\"),\n\n |digest| { \"sha256:7631ea645e2126e9dbc5d9ae789e34301d9d5c80ce89bfa72bc9b82aa43b57c0\" },\n\n |description| { vec![] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Exec(ExecOp {\n\n mounts: vec![],\n\n network: NetMode::Unset.into(),\n\n security: SecurityMode::Sandbox.into(),\n\n meta: Some(Meta {\n\n args: crate::utils::test::to_vec(vec![\"cargo\", \"build\"]),\n\n env: vec![],\n\n cwd: \"/\".into(),\n\n user: \"builder\".into(),\n\n\n\n extra_hosts: vec![],\n\n proxy_env: None,\n\n }),\n\n })\n\n },\n\n );\n\n}\n\n\n", "file_path": "buildkit-llb/src/ops/exec/mod.rs", "rank": 27, "score": 49145.8837053224 }, { "content": "#[test]\n\nfn mkdir_serialization() {\n\n use crate::prelude::*;\n\n use buildkit_proto::pb::{file_action::Action, op::Op, FileAction, FileActionMkDir, FileOp};\n\n\n\n let context = Source::local(\"context\");\n\n\n\n let operation = FileSystem::sequence()\n\n .append(\n\n FileSystem::mkdir(\n\n OutputIdx(0),\n\n LayerPath::Other(context.output(), \"/new-crate\"),\n\n )\n\n .make_parents(true),\n\n )\n\n .append(FileSystem::mkdir(\n\n OutputIdx(1),\n\n LayerPath::Scratch(\"/new-crate\"),\n\n ))\n\n .append(FileSystem::mkdir(\n\n OutputIdx(2),\n", "file_path": "buildkit-llb/src/ops/fs/mod.rs", "rank": 28, "score": 49145.8837053224 }, { "content": "#[test]\n\nfn serialization_with_cwd() {\n\n use crate::prelude::*;\n\n use buildkit_proto::pb::{op::Op, ExecOp, Meta, NetMode, SecurityMode};\n\n\n\n crate::check_op!(\n\n Command::run(\"cargo\").args(&[\"build\"]).cwd(\"/rust-src\"),\n\n |digest| { \"sha256:b8120a0e1d1f7fcaa3d6c95db292d064524dc92c6cae8b97672d4e1eafcd03fa\" },\n\n |description| { vec![] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Exec(ExecOp {\n\n mounts: vec![],\n\n network: NetMode::Unset.into(),\n\n security: SecurityMode::Sandbox.into(),\n\n meta: Some(Meta {\n\n args: crate::utils::test::to_vec(vec![\"cargo\", \"build\"]),\n\n env: vec![],\n\n cwd: \"/rust-src\".into(),\n\n user: \"root\".into(),\n\n\n\n extra_hosts: vec![],\n\n proxy_env: None,\n\n }),\n\n })\n\n },\n\n );\n\n}\n\n\n", "file_path": "buildkit-llb/src/ops/exec/mod.rs", "rank": 29, "score": 49145.8837053224 }, { "content": "#[test]\n\nfn serialization_with_mounts() {\n\n use crate::prelude::*;\n\n use buildkit_proto::pb::{\n\n op::Op, CacheOpt, CacheSharingOpt, ExecOp, Meta, MountType, NetMode, SecurityMode,\n\n };\n\n\n\n let context = Source::local(\"context\");\n\n let builder_image = Source::image(\"rustlang/rust:nightly\");\n\n let final_image = Source::image(\"library/alpine:latest\");\n\n\n\n let command = Command::run(\"cargo\")\n\n .args(&[\"build\"])\n\n .mount(Mount::ReadOnlyLayer(builder_image.output(), \"/\"))\n\n .mount(Mount::Scratch(OutputIdx(1), \"/tmp\"))\n\n .mount(Mount::ReadOnlySelector(\n\n context.output(),\n\n \"/buildkit-frontend\",\n\n \"/frontend-sources\",\n\n ))\n\n .mount(Mount::Layer(OutputIdx(0), final_image.output(), \"/output\"))\n", "file_path": "buildkit-llb/src/ops/exec/mod.rs", "rank": 30, "score": 49145.8837053224 }, { "content": "#[test]\n\nfn serialization_with_ssh_mounts() {\n\n use crate::prelude::*;\n\n use buildkit_proto::pb::{op::Op, ExecOp, Meta, MountType, NetMode, SecurityMode, SshOpt};\n\n\n\n let builder_image = Source::image(\"rustlang/rust:nightly\");\n\n let command = Command::run(\"cargo\")\n\n .args(&[\"build\"])\n\n .mount(Mount::ReadOnlyLayer(builder_image.output(), \"/\"))\n\n .mount(Mount::OptionalSshAgent(\"/run/buildkit/ssh_agent.0\"));\n\n\n\n crate::check_op!(\n\n command,\n\n |digest| { \"sha256:1ac1438c67a153878f21fe8067383fd7544901261374eb53ba8bf26e9a5821a5\" },\n\n |description| { vec![] },\n\n |caps| { vec![\"exec.mount.bind\", \"exec.mount.ssh\"] },\n\n |cached_tail| {\n\n vec![\"sha256:dee2a3d7dd482dd8098ba543ff1dcb01efd29fcd16fdb0979ef556f38564543a\"]\n\n },\n\n |inputs| {\n\n vec![(\n", "file_path": "buildkit-llb/src/ops/exec/mod.rs", "rank": 31, "score": 48331.58556942726 }, { "content": "#[test]\n\nfn serialization_with_env_iter() {\n\n use crate::prelude::*;\n\n use buildkit_proto::pb::{op::Op, ExecOp, Meta, NetMode, SecurityMode};\n\n\n\n crate::check_op!(\n\n {\n\n Command::run(\"cargo\").args(&[\"build\"]).env_iter(vec![\n\n (\"HOME\", \"/root\"),\n\n (\"PATH\", \"/bin\"),\n\n (\"CARGO_HOME\", \"/root/.cargo\"),\n\n ])\n\n },\n\n |digest| { \"sha256:7675be0b02acb379d57bafee5dc749fca7e795fb1e0a92748ccc59a7bc3b491e\" },\n\n |description| { vec![] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Exec(ExecOp {\n\n mounts: vec![],\n", "file_path": "buildkit-llb/src/ops/exec/mod.rs", "rank": 32, "score": 48331.58556942726 }, { "content": "#[test]\n\nfn copy_with_params_serialization() {\n\n use crate::prelude::*;\n\n use buildkit_proto::pb::{file_action::Action, op::Op, FileAction, FileActionCopy, FileOp};\n\n\n\n let context = Source::local(\"context\");\n\n\n\n let operation = FileSystem::sequence()\n\n .append(\n\n FileSystem::copy()\n\n .from(LayerPath::Other(context.output(), \"Cargo.toml\"))\n\n .to(OutputIdx(0), LayerPath::Scratch(\"Cargo.toml\"))\n\n .follow_symlinks(true),\n\n )\n\n .append(\n\n FileSystem::copy()\n\n .from(LayerPath::Other(context.output(), \"Cargo.toml\"))\n\n .to(OutputIdx(1), LayerPath::Scratch(\"Cargo.toml\"))\n\n .recursive(true),\n\n )\n\n .append(\n", "file_path": "buildkit-llb/src/ops/fs/mod.rs", "rank": 33, "score": 48331.58556942726 }, { "content": "/// Common operation methods.\n\npub trait OperationBuilder<'a> {\n\n /// Sets an operation display name.\n\n fn custom_name<S>(self, name: S) -> Self\n\n where\n\n S: Into<String>;\n\n\n\n /// Sets caching behavior.\n\n fn ignore_cache(self, ignore: bool) -> Self;\n\n\n\n /// Convert the operation into `Arc` so it can be shared when efficient borrowing is not possible.\n\n fn ref_counted(self) -> Arc<Self>\n\n where\n\n Self: Sized + 'a,\n\n {\n\n Arc::new(self)\n\n }\n\n}\n", "file_path": "buildkit-llb/src/ops/mod.rs", "rank": 34, "score": 47920.413221495895 }, { "content": "#[test]\n\nfn serialization_with_several_root_mounts() {\n\n use crate::prelude::*;\n\n use buildkit_proto::pb::{op::Op, ExecOp, Meta, MountType, NetMode, SecurityMode};\n\n\n\n let builder_image = Source::image(\"rustlang/rust:nightly\");\n\n let final_image = Source::image(\"library/alpine:latest\");\n\n\n\n let command = Command::run(\"cargo\")\n\n .args(&[\"build\"])\n\n .mount(Mount::Scratch(OutputIdx(0), \"/tmp\"))\n\n .mount(Mount::ReadOnlyLayer(builder_image.output(), \"/\"))\n\n .mount(Mount::Scratch(OutputIdx(1), \"/var\"))\n\n .mount(Mount::ReadOnlyLayer(final_image.output(), \"/\"));\n\n\n\n crate::check_op!(\n\n command,\n\n |digest| { \"sha256:baa1bf591d2c47058b7361a0284fa8a3f1bd0fac8a93c87affa77ddc0a5026fd\" },\n\n |description| { vec![] },\n\n |caps| { vec![\"exec.mount.bind\"] },\n\n |cached_tail| {\n", "file_path": "buildkit-llb/src/ops/exec/mod.rs", "rank": 35, "score": 47560.23521145835 }, { "content": "pub trait MultiBorrowedOutput<'a> {\n\n fn output(&'a self, number: u32) -> OperationOutput<'a>;\n\n}\n\n\n", "file_path": "buildkit-llb/src/ops/mod.rs", "rank": 36, "score": 47092.67836283872 }, { "content": "pub trait MultiOwnedOutput<'a> {\n\n fn output(&self, number: u32) -> OperationOutput<'a>;\n\n}\n\n\n", "file_path": "buildkit-llb/src/ops/mod.rs", "rank": 37, "score": 47092.67836283872 }, { "content": "pub trait SingleOwnedOutput<'a> {\n\n fn output(&self) -> OperationOutput<'a>;\n\n}\n\n\n", "file_path": "buildkit-llb/src/ops/mod.rs", "rank": 38, "score": 47092.67836283872 }, { "content": "pub trait SingleBorrowedOutput<'a> {\n\n fn output(&'a self) -> OperationOutput<'a>;\n\n}\n\n\n", "file_path": "buildkit-llb/src/ops/mod.rs", "rank": 39, "score": 47092.67836283872 }, { "content": "fn build_modify_commands<'a>(\n\n image: &'a ImageSource,\n\n layers: Vec<OperationOutput<'a>>,\n\n) -> Vec<OperationOutput<'a>> {\n\n layers\n\n .into_iter()\n\n .zip(0..)\n\n .map(|(output, idx)| {\n\n let shell = format!(\n\n \"sed s/test/modified/ < /in/file/{}/file.in > /out/file-{}.out\",\n\n idx, idx\n\n );\n\n\n\n Command::run(\"/bin/sh\")\n\n .args(&[\"-c\", &shell])\n\n .mount(Mount::ReadOnlyLayer(image.output(), \"/\"))\n\n .mount(Mount::Scratch(OutputIdx(0), \"/out\"))\n\n .mount(Mount::ReadOnlySelector(\n\n output,\n\n format!(\"/in/file/{}/file.in\", idx),\n\n format!(\"file/{}/file.out\", idx),\n\n ))\n\n .ignore_cache(true)\n\n .ref_counted()\n\n .output(0)\n\n })\n\n .collect()\n\n}\n", "file_path": "buildkit-llb/examples/highly-parallel.rs", "rank": 40, "score": 46870.47977400101 }, { "content": "pub trait MultiOwnedLastOutput<'a> {\n\n fn last_output(&self) -> Option<OperationOutput<'a>>;\n\n}\n\n\n", "file_path": "buildkit-llb/src/ops/mod.rs", "rank": 41, "score": 46308.599962822846 }, { "content": "pub trait MultiBorrowedLastOutput<'a> {\n\n fn last_output(&'a self) -> Option<OperationOutput<'a>>;\n\n}\n\n\n", "file_path": "buildkit-llb/src/ops/mod.rs", "rank": 42, "score": 46308.599962822846 }, { "content": "#[derive(Debug)]\n\nstruct EnvItem<'de>(&'de str);\n\n\n", "file_path": "dockerfile-plus/src/options.rs", "rank": 43, "score": 45911.94391352548 }, { "content": "fn build_graph() -> OperationOutput<'static> {\n\n let builder_image = Source::image(\"library/alpine:latest\")\n\n .custom_name(\"Using alpine:latest as a builder\")\n\n .ref_counted();\n\n\n\n let command = {\n\n Command::run(\"/bin/sh\")\n\n .args(&[\"-c\", \"echo 'test string 5' > /out/file0\"])\n\n .custom_name(\"create a dummy file\")\n\n .mount(Mount::ReadOnlyLayer(builder_image.output(), \"/\"))\n\n .mount(Mount::Scratch(OutputIdx(0), \"/out\"))\n\n .ref_counted()\n\n };\n\n\n\n let fs = {\n\n FileSystem::sequence()\n\n .custom_name(\"do multiple file system manipulations\")\n\n .append(\n\n FileSystem::copy()\n\n .from(LayerPath::Other(command.output(0), \"/file0\"))\n", "file_path": "buildkit-llb/examples/scratch-owned.rs", "rank": 44, "score": 43494.27465520869 }, { "content": "use std::collections::HashMap;\n\nuse std::sync::Arc;\n\n\n\nuse buildkit_proto::pb::{self, op::Op, OpMetadata, SourceOp};\n\n\n\nuse crate::ops::{OperationBuilder, SingleBorrowedOutput, SingleOwnedOutput};\n\nuse crate::serialization::{Context, Node, Operation, OperationId, Result};\n\nuse crate::utils::{OperationOutput, OutputIdx};\n\n\n\n#[derive(Default, Debug)]\n\npub struct GitSource {\n\n id: OperationId,\n\n remote: String,\n\n reference: Option<String>,\n\n description: HashMap<String, String>,\n\n ignore_cache: bool,\n\n}\n\n\n\nimpl GitSource {\n\n pub(crate) fn new<S>(url: S) -> Self\n", "file_path": "buildkit-llb/src/ops/source/git.rs", "rank": 45, "score": 31108.52729114938 }, { "content": "use std::collections::HashMap;\n\nuse std::sync::Arc;\n\n\n\nuse buildkit_proto::pb::{self, op::Op, OpMetadata, SourceOp};\n\n\n\nuse crate::ops::{OperationBuilder, SingleBorrowedOutput, SingleOwnedOutput};\n\nuse crate::serialization::{Context, Node, Operation, OperationId, Result};\n\nuse crate::utils::{OperationOutput, OutputIdx};\n\n\n\n#[derive(Default, Debug)]\n\npub struct HttpSource {\n\n id: OperationId,\n\n url: String,\n\n file_name: Option<String>,\n\n description: HashMap<String, String>,\n\n ignore_cache: bool,\n\n}\n\n\n\nimpl HttpSource {\n\n pub(crate) fn new<S>(url: S) -> Self\n", "file_path": "buildkit-llb/src/ops/source/http.rs", "rank": 46, "score": 31108.40075673507 }, { "content": "mod git;\n\nmod http;\n\nmod image;\n\nmod local;\n\n\n\npub use self::git::GitSource;\n\npub use self::http::HttpSource;\n\npub use self::image::{ImageSource, ResolveMode};\n\npub use self::local::LocalSource;\n\n\n\n/// Provide an input for other operations. For example: `FROM` directive in Dockerfile.\n\n#[derive(Debug)]\n\npub struct Source;\n\n\n\nimpl Source {\n\n pub fn image<S>(name: S) -> ImageSource\n\n where\n\n S: Into<String>,\n\n {\n\n ImageSource::new(name)\n", "file_path": "buildkit-llb/src/ops/source/mod.rs", "rank": 47, "score": 31105.747022982516 }, { "content": "use std::collections::HashMap;\n\nuse std::sync::Arc;\n\n\n\nuse buildkit_proto::pb::{self, op::Op, OpMetadata, SourceOp};\n\n\n\nuse crate::ops::{OperationBuilder, SingleBorrowedOutput, SingleOwnedOutput};\n\nuse crate::serialization::{Context, Node, Operation, OperationId, Result};\n\nuse crate::utils::{OperationOutput, OutputIdx};\n\n\n\n#[derive(Default, Debug)]\n\npub struct LocalSource {\n\n id: OperationId,\n\n name: String,\n\n description: HashMap<String, String>,\n\n ignore_cache: bool,\n\n\n\n exclude: Vec<String>,\n\n include: Vec<String>,\n\n}\n\n\n", "file_path": "buildkit-llb/src/ops/source/local.rs", "rank": 48, "score": 31104.733996424904 }, { "content": "\n\n description: HashMap<String, String>,\n\n ignore_cache: bool,\n\n resolve_mode: Option<ResolveMode>,\n\n}\n\n\n\n#[derive(Debug, Clone, Copy)]\n\npub enum ResolveMode {\n\n Default,\n\n ForcePull,\n\n PreferLocal,\n\n}\n\n\n\nimpl fmt::Display for ResolveMode {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match self {\n\n ResolveMode::Default => write!(f, \"default\"),\n\n ResolveMode::ForcePull => write!(f, \"pull\"),\n\n ResolveMode::PreferLocal => write!(f, \"local\"),\n\n }\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 49, "score": 31102.783418765062 }, { "content": " description: Default::default(),\n\n ignore_cache: false,\n\n }\n\n }\n\n}\n\n\n\nimpl GitSource {\n\n pub fn with_reference<S>(mut self, reference: S) -> Self\n\n where\n\n S: Into<String>,\n\n {\n\n self.reference = Some(reference.into());\n\n self\n\n }\n\n}\n\n\n\nimpl<'a> SingleBorrowedOutput<'a> for GitSource {\n\n fn output(&'a self) -> OperationOutput<'a> {\n\n OperationOutput::borrowed(self, OutputIdx(0))\n\n }\n", "file_path": "buildkit-llb/src/ops/source/git.rs", "rank": 50, "score": 31102.11265673415 }, { "content": " self.description\n\n .insert(\"llb.customname\".into(), name.into());\n\n\n\n self\n\n }\n\n\n\n fn ignore_cache(mut self, ignore: bool) -> Self {\n\n self.ignore_cache = ignore;\n\n self\n\n }\n\n}\n\n\n\nimpl Operation for HttpSource {\n\n fn id(&self) -> &OperationId {\n\n &self.id\n\n }\n\n\n\n fn serialize(&self, _: &mut Context) -> Result<Node> {\n\n let mut attrs = HashMap::default();\n\n\n", "file_path": "buildkit-llb/src/ops/source/http.rs", "rank": 51, "score": 31102.10819247008 }, { "content": " fn custom_name<S>(mut self, name: S) -> Self\n\n where\n\n S: Into<String>,\n\n {\n\n self.description\n\n .insert(\"llb.customname\".into(), name.into());\n\n\n\n self\n\n }\n\n\n\n fn ignore_cache(mut self, ignore: bool) -> Self {\n\n self.ignore_cache = ignore;\n\n self\n\n }\n\n}\n\n\n\nimpl Operation for ImageSource {\n\n fn id(&self) -> &OperationId {\n\n &self.id\n\n }\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 52, "score": 31101.838769448586 }, { "content": "}\n\n\n\nimpl<'a> SingleOwnedOutput<'static> for Arc<GitSource> {\n\n fn output(&self) -> OperationOutput<'static> {\n\n OperationOutput::owned(self.clone(), OutputIdx(0))\n\n }\n\n}\n\n\n\nimpl OperationBuilder<'static> for GitSource {\n\n fn custom_name<S>(mut self, name: S) -> Self\n\n where\n\n S: Into<String>,\n\n {\n\n self.description\n\n .insert(\"llb.customname\".into(), name.into());\n\n\n\n self\n\n }\n\n\n\n fn ignore_cache(mut self, ignore: bool) -> Self {\n", "file_path": "buildkit-llb/src/ops/source/git.rs", "rank": 53, "score": 31101.637045006886 }, { "content": "impl LocalSource {\n\n pub(crate) fn new<S>(name: S) -> Self\n\n where\n\n S: Into<String>,\n\n {\n\n Self {\n\n id: OperationId::default(),\n\n name: name.into(),\n\n ignore_cache: false,\n\n\n\n ..Default::default()\n\n }\n\n }\n\n\n\n pub fn add_include_pattern<S>(mut self, include: S) -> Self\n\n where\n\n S: Into<String>,\n\n {\n\n // TODO: add `source.local.includepatterns` capability\n\n self.include.push(include.into());\n", "file_path": "buildkit-llb/src/ops/source/local.rs", "rank": 54, "score": 31101.507837047953 }, { "content": " where\n\n S: Into<String>,\n\n {\n\n Self {\n\n id: OperationId::default(),\n\n url: url.into(),\n\n file_name: None,\n\n description: Default::default(),\n\n ignore_cache: false,\n\n }\n\n }\n\n}\n\n\n\nimpl HttpSource {\n\n pub fn with_file_name<S>(mut self, name: S) -> Self\n\n where\n\n S: Into<String>,\n\n {\n\n self.file_name = Some(name.into());\n\n self\n", "file_path": "buildkit-llb/src/ops/source/http.rs", "rank": 55, "score": 31101.233482464002 }, { "content": "use std::collections::HashMap;\n\nuse std::fmt;\n\nuse std::sync::Arc;\n\n\n\nuse buildkit_proto::pb::{self, op::Op, OpMetadata, SourceOp};\n\nuse lazy_static::*;\n\nuse regex::Regex;\n\n\n\nuse crate::ops::{OperationBuilder, SingleBorrowedOutput, SingleOwnedOutput};\n\nuse crate::serialization::{Context, Node, Operation, OperationId, Result};\n\nuse crate::utils::{OperationOutput, OutputIdx};\n\n\n\n#[derive(Debug)]\n\npub struct ImageSource {\n\n id: OperationId,\n\n\n\n domain: Option<String>,\n\n name: String,\n\n tag: Option<String>,\n\n digest: Option<String>,\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 56, "score": 31100.940612884264 }, { "content": " }\n\n\n\n pub fn git<S>(url: S) -> GitSource\n\n where\n\n S: Into<String>,\n\n {\n\n GitSource::new(url)\n\n }\n\n\n\n pub fn local<S>(name: S) -> LocalSource\n\n where\n\n S: Into<String>,\n\n {\n\n LocalSource::new(name)\n\n }\n\n\n\n pub fn http<S>(name: S) -> HttpSource\n\n where\n\n S: Into<String>,\n\n {\n\n HttpSource::new(name)\n\n }\n\n}\n", "file_path": "buildkit-llb/src/ops/source/mod.rs", "rank": 57, "score": 31100.74453258572 }, { "content": " fn output(&self) -> OperationOutput<'static> {\n\n OperationOutput::owned(self.clone(), OutputIdx(0))\n\n }\n\n}\n\n\n\nimpl OperationBuilder<'static> for LocalSource {\n\n fn custom_name<S>(mut self, name: S) -> Self\n\n where\n\n S: Into<String>,\n\n {\n\n self.description\n\n .insert(\"llb.customname\".into(), name.into());\n\n\n\n self\n\n }\n\n\n\n fn ignore_cache(mut self, ignore: bool) -> Self {\n\n self.ignore_cache = ignore;\n\n self\n\n }\n", "file_path": "buildkit-llb/src/ops/source/local.rs", "rank": 58, "score": 31100.56007544263 }, { "content": "\n\n fn serialize(&self, _: &mut Context) -> Result<Node> {\n\n let mut attrs = HashMap::default();\n\n\n\n if let Some(ref mode) = self.resolve_mode {\n\n attrs.insert(\"image.resolvemode\".into(), mode.to_string());\n\n }\n\n\n\n let head = pb::Op {\n\n op: Some(Op::Source(SourceOp {\n\n identifier: format!(\"docker-image://{}\", self.canonical_name()),\n\n attrs,\n\n })),\n\n\n\n ..Default::default()\n\n };\n\n\n\n let metadata = OpMetadata {\n\n description: self.description.clone(),\n\n ignore_cache: self.ignore_cache,\n\n\n\n ..Default::default()\n\n };\n\n\n\n Ok(Node::new(head, metadata))\n\n }\n\n}\n\n\n\n#[test]\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 59, "score": 31100.250740322277 }, { "content": " self\n\n }\n\n\n\n pub fn add_exclude_pattern<S>(mut self, exclude: S) -> Self\n\n where\n\n S: Into<String>,\n\n {\n\n // TODO: add `source.local.excludepatterns` capability\n\n self.exclude.push(exclude.into());\n\n self\n\n }\n\n}\n\n\n\nimpl<'a> SingleBorrowedOutput<'a> for LocalSource {\n\n fn output(&'a self) -> OperationOutput<'a> {\n\n OperationOutput::borrowed(self, OutputIdx(0))\n\n }\n\n}\n\n\n\nimpl<'a> SingleOwnedOutput<'static> for Arc<LocalSource> {\n", "file_path": "buildkit-llb/src/ops/source/local.rs", "rank": 60, "score": 31099.056347008427 }, { "content": " |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"http://any.url/with/path\".into(),\n\n attrs: Default::default(),\n\n })\n\n },\n\n );\n\n\n\n crate::check_op!(\n\n HttpSource::new(\"http://any.url/with/path\").with_file_name(\"file.name\"),\n\n |digest| { \"sha256:e1fe6584287dfa2b065ed29fcf4f77bcf86fb54781832d2f45074fa1671df692\" },\n\n |description| { vec![] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"http://any.url/with/path\".into(),\n\n attrs: vec![(\"http.filename\".to_string(), \"file.name\".to_string())]\n\n .into_iter()\n\n .collect(),\n\n })\n\n },\n\n );\n\n}\n", "file_path": "buildkit-llb/src/ops/source/http.rs", "rank": 61, "score": 31098.62570449154 }, { "content": "}\n\n\n\nimpl Operation for LocalSource {\n\n fn id(&self) -> &OperationId {\n\n &self.id\n\n }\n\n\n\n fn serialize(&self, _: &mut Context) -> Result<Node> {\n\n let mut attrs = HashMap::default();\n\n\n\n if !self.exclude.is_empty() {\n\n attrs.insert(\n\n \"local.excludepatterns\".into(),\n\n serde_json::to_string(&self.exclude).unwrap(),\n\n );\n\n }\n\n\n\n if !self.include.is_empty() {\n\n attrs.insert(\n\n \"local.includepattern\".into(),\n", "file_path": "buildkit-llb/src/ops/source/local.rs", "rank": 62, "score": 31098.56953664328 }, { "content": " }\n\n}\n\n\n\nimpl Default for ResolveMode {\n\n fn default() -> Self {\n\n ResolveMode::Default\n\n }\n\n}\n\n\n\nlazy_static! {\n\n static ref TAG_EXPR: Regex = Regex::new(r\":[\\w][\\w.-]+$\").unwrap();\n\n}\n\n\n\nimpl ImageSource {\n\n // The implementation is based on:\n\n // https://github.com/containerd/containerd/blob/614c0858f2a8db9ee0c788a9164870069f3e53ed/reference/docker/reference.go\n\n pub(crate) fn new<S>(name: S) -> Self\n\n where\n\n S: Into<String>,\n\n {\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 63, "score": 31098.339351276747 }, { "content": " |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"git://any.url\".into(),\n\n attrs: Default::default(),\n\n })\n\n },\n\n );\n\n\n\n crate::check_op!(\n\n GitSource::new(\"git://any.url\"),\n\n |digest| { \"sha256:ecde982e19ace932e5474e57b0ca71ba690ed7d28abff2a033e8f969e22bf2d8\" },\n\n |description| { vec![] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n", "file_path": "buildkit-llb/src/ops/source/git.rs", "rank": 64, "score": 31097.27849911052 }, { "content": " }\n\n}\n\n\n\nimpl<'a> SingleBorrowedOutput<'a> for HttpSource {\n\n fn output(&'a self) -> OperationOutput<'a> {\n\n OperationOutput::borrowed(self, OutputIdx(0))\n\n }\n\n}\n\n\n\nimpl<'a> SingleOwnedOutput<'static> for Arc<HttpSource> {\n\n fn output(&self) -> OperationOutput<'static> {\n\n OperationOutput::owned(self.clone(), OutputIdx(0))\n\n }\n\n}\n\n\n\nimpl OperationBuilder<'static> for HttpSource {\n\n fn custom_name<S>(mut self, name: S) -> Self\n\n where\n\n S: Into<String>,\n\n {\n", "file_path": "buildkit-llb/src/ops/source/http.rs", "rank": 65, "score": 31096.815633598428 }, { "content": " serde_json::to_string(&self.include).unwrap(),\n\n );\n\n }\n\n\n\n let head = pb::Op {\n\n op: Some(Op::Source(SourceOp {\n\n identifier: format!(\"local://{}\", self.name),\n\n attrs,\n\n })),\n\n\n\n ..Default::default()\n\n };\n\n\n\n let metadata = OpMetadata {\n\n description: self.description.clone(),\n\n ignore_cache: self.ignore_cache,\n\n\n\n ..Default::default()\n\n };\n\n\n\n Ok(Node::new(head, metadata))\n\n }\n\n}\n\n\n\n#[test]\n", "file_path": "buildkit-llb/src/ops/source/local.rs", "rank": 66, "score": 31096.696348673468 }, { "content": " self.ignore_cache = ignore;\n\n self\n\n }\n\n}\n\n\n\nimpl Operation for GitSource {\n\n fn id(&self) -> &OperationId {\n\n &self.id\n\n }\n\n\n\n fn serialize(&self, _: &mut Context) -> Result<Node> {\n\n let identifier = if let Some(ref reference) = self.reference {\n\n format!(\"git://{}#{}\", self.remote, reference)\n\n } else {\n\n format!(\"git://{}\", self.remote)\n\n };\n\n\n\n let head = pb::Op {\n\n op: Some(Op::Source(SourceOp {\n\n identifier,\n", "file_path": "buildkit-llb/src/ops/source/git.rs", "rank": 67, "score": 31096.440419290946 }, { "content": " identifier: \"git://any.url\".into(),\n\n attrs: Default::default(),\n\n })\n\n },\n\n );\n\n\n\n crate::check_op!(\n\n GitSource::new(\"[email protected]\"),\n\n |digest| { \"sha256:ecde982e19ace932e5474e57b0ca71ba690ed7d28abff2a033e8f969e22bf2d8\" },\n\n |description| { vec![] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"git://any.url\".into(),\n\n attrs: Default::default(),\n\n })\n\n },\n\n );\n\n}\n\n\n", "file_path": "buildkit-llb/src/ops/source/git.rs", "rank": 68, "score": 31096.433639419873 }, { "content": " |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://docker.io/library/alpine:latest\".into(),\n\n attrs: Default::default(),\n\n })\n\n },\n\n );\n\n\n\n crate::check_op!(\n\n ImageSource::new(\"rustlang/rust:nightly\").custom_name(\"image custom name\"),\n\n |digest| { \"sha256:dee2a3d7dd482dd8098ba543ff1dcb01efd29fcd16fdb0979ef556f38564543a\" },\n\n |description| { vec![(\"llb.customname\", \"image custom name\")] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 69, "score": 31096.099225557817 }, { "content": " |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"local://context\".into(),\n\n attrs: Default::default(),\n\n })\n\n },\n\n );\n\n\n\n crate::check_op!(\n\n {\n\n LocalSource::new(\"context\")\n\n .custom_name(\"context custom name\")\n\n .add_exclude_pattern(\"**/target\")\n\n .add_exclude_pattern(\"Dockerfile\")\n\n },\n\n |digest| { \"sha256:f6962b8bb1659c63a2c2c3e2a7ccf0326c87530dd70c514343f127e4c20460c4\" },\n\n |description| { vec![(\"llb.customname\", \"context custom name\")] },\n", "file_path": "buildkit-llb/src/ops/source/local.rs", "rank": 70, "score": 31095.45173883769 }, { "content": " identifier: \"docker-image://docker.io/rustlang/rust:nightly\".into(),\n\n attrs: Default::default(),\n\n })\n\n },\n\n );\n\n\n\n crate::check_op!(\n\n ImageSource::new(\"rustlang/rust:nightly\").with_digest(\"sha256:123456\"),\n\n |digest| { \"sha256:a9837e26998d165e7b6433f8d40b36d259905295860fcbbc62bbce75a6c991c6\" },\n\n |description| { vec![] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://docker.io/rustlang/rust:nightly@sha256:123456\".into(),\n\n attrs: Default::default(),\n\n })\n\n },\n\n );\n\n}\n\n\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 71, "score": 31095.21499200355 }, { "content": " resolve_mode: None,\n\n }\n\n }\n\n\n\n pub fn with_resolve_mode(mut self, mode: ResolveMode) -> Self {\n\n self.resolve_mode = Some(mode);\n\n self\n\n }\n\n\n\n pub fn resolve_mode(&self) -> Option<ResolveMode> {\n\n self.resolve_mode\n\n }\n\n\n\n pub fn with_digest<S>(mut self, digest: S) -> Self\n\n where\n\n S: Into<String>,\n\n {\n\n self.digest = Some(digest.into());\n\n self\n\n }\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 72, "score": 31095.03755509101 }, { "content": " |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://docker.io/rustlang/rust:nightly\".into(),\n\n attrs: crate::utils::test::to_map(vec![(\"image.resolvemode\", \"pull\")]),\n\n })\n\n },\n\n );\n\n\n\n crate::check_op!(\n\n ImageSource::new(\"rustlang/rust:nightly\").with_resolve_mode(ResolveMode::PreferLocal),\n\n |digest| { \"sha256:bd6797c8644d2663b29c36a8b3b63931e539be44ede5e56aca2da4f35f241f18\" },\n\n |description| { vec![] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://docker.io/rustlang/rust:nightly\".into(),\n\n attrs: crate::utils::test::to_map(vec![(\"image.resolvemode\", \"local\")]),\n\n })\n\n },\n\n );\n\n}\n\n\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 73, "score": 31094.995866699697 }, { "content": "\n\n pub fn with_tag<S>(mut self, tag: S) -> Self\n\n where\n\n S: Into<String>,\n\n {\n\n self.tag = Some(tag.into());\n\n self\n\n }\n\n\n\n pub fn canonical_name(&self) -> String {\n\n let domain = match self.domain {\n\n Some(ref domain) => domain,\n\n None => \"docker.io\",\n\n };\n\n\n\n let tag = match self.tag {\n\n Some(ref tag) => tag,\n\n None => \"latest\",\n\n };\n\n\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 74, "score": 31094.670694195986 }, { "content": " if let Some(ref file_name) = self.file_name {\n\n attrs.insert(\"http.filename\".into(), file_name.into());\n\n }\n\n\n\n let head = pb::Op {\n\n op: Some(Op::Source(SourceOp {\n\n identifier: self.url.clone(),\n\n attrs,\n\n })),\n\n\n\n ..Default::default()\n\n };\n\n\n\n let metadata = OpMetadata {\n\n description: self.description.clone(),\n\n ignore_cache: self.ignore_cache,\n\n\n\n ..Default::default()\n\n };\n\n\n\n Ok(Node::new(head, metadata))\n\n }\n\n}\n\n\n\n#[test]\n", "file_path": "buildkit-llb/src/ops/source/http.rs", "rank": 75, "score": 31093.949422365033 }, { "content": " },\n\n |digest| { \"sha256:a7e628333262b810572f83193bbf8554e688abfb51d44ac30bdad7fa425f3839\" },\n\n |description| { vec![(\"llb.customname\", \"context custom name\")] },\n\n |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"local://context\".into(),\n\n attrs: crate::utils::test::to_map(vec![(\n\n \"local.includepattern\",\n\n r#\"[\"Cargo.toml\",\"inner/Cargo.toml\"]\"#,\n\n )]),\n\n })\n\n },\n\n );\n\n}\n", "file_path": "buildkit-llb/src/ops/source/local.rs", "rank": 76, "score": 31093.4696182506 }, { "content": " |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"local://context\".into(),\n\n attrs: crate::utils::test::to_map(vec![(\n\n \"local.excludepatterns\",\n\n r#\"[\"**/target\",\"Dockerfile\"]\"#,\n\n )]),\n\n })\n\n },\n\n );\n\n\n\n crate::check_op!(\n\n {\n\n LocalSource::new(\"context\")\n\n .custom_name(\"context custom name\")\n\n .add_include_pattern(\"Cargo.toml\")\n\n .add_include_pattern(\"inner/Cargo.toml\")\n", "file_path": "buildkit-llb/src/ops/source/local.rs", "rank": 77, "score": 31093.23980777434 }, { "content": " });\n\n\n\n crate::check_op!(ImageSource::new(\"127.0.0.1:5000/rust:obj\"), |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://127.0.0.1:5000/rust:obj\".into(),\n\n attrs: Default::default(),\n\n })\n\n });\n\n\n\n crate::check_op!(ImageSource::new(\"localhost:5000/rust\"), |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://localhost:5000/rust:latest\".into(),\n\n attrs: Default::default(),\n\n })\n\n });\n\n\n\n crate::check_op!(ImageSource::new(\"127.0.0.1:5000/rust\"), |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://127.0.0.1:5000/rust:latest\".into(),\n\n attrs: Default::default(),\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 78, "score": 31092.924854663026 }, { "content": "\n\n crate::check_op!(ImageSource::new(\"localhost/rust:obj\"), |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://localhost/rust:obj\".into(),\n\n attrs: Default::default(),\n\n })\n\n });\n\n\n\n crate::check_op!(ImageSource::new(\"127.0.0.1/rust:obj\"), |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://127.0.0.1/rust:obj\".into(),\n\n attrs: Default::default(),\n\n })\n\n });\n\n\n\n crate::check_op!(ImageSource::new(\"localhost:5000/rust:obj\"), |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://localhost:5000/rust:obj\".into(),\n\n attrs: Default::default(),\n\n })\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 79, "score": 31092.826840361584 }, { "content": " });\n\n\n\n crate::check_op!(ImageSource::new(\"library/rust\"), |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://docker.io/library/rust:latest\".into(),\n\n attrs: Default::default(),\n\n })\n\n });\n\n\n\n crate::check_op!(ImageSource::new(\"rust:obj@sha256:abcdef\"), |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://docker.io/library/rust:obj@sha256:abcdef\".into(),\n\n attrs: Default::default(),\n\n })\n\n });\n\n\n\n crate::check_op!(ImageSource::new(\"rust@sha256:abcdef\"), |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://docker.io/library/rust:latest@sha256:abcdef\".into(),\n\n attrs: Default::default(),\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 80, "score": 31092.549419730243 }, { "content": " })\n\n });\n\n\n\n crate::check_op!(ImageSource::new(\"docker.io/rust\"), |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://docker.io/library/rust:latest\".into(),\n\n attrs: Default::default(),\n\n })\n\n });\n\n\n\n crate::check_op!(ImageSource::new(\"docker.io/library/rust\"), |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://docker.io/library/rust:latest\".into(),\n\n attrs: Default::default(),\n\n })\n\n });\n\n}\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 81, "score": 31092.45806057572 }, { "content": " |caps| { vec![] },\n\n |cached_tail| { vec![] },\n\n |inputs| { vec![] },\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"git://any.url\".into(),\n\n attrs: Default::default(),\n\n })\n\n },\n\n );\n\n}\n\n\n", "file_path": "buildkit-llb/src/ops/source/git.rs", "rank": 82, "score": 31092.227437001773 }, { "content": " match self.digest {\n\n Some(ref digest) => format!(\"{}/{}:{}@{}\", domain, self.name, tag, digest),\n\n None => format!(\"{}/{}:{}\", domain, self.name, tag),\n\n }\n\n }\n\n}\n\n\n\nimpl<'a> SingleBorrowedOutput<'a> for ImageSource {\n\n fn output(&'a self) -> OperationOutput<'a> {\n\n OperationOutput::borrowed(self, OutputIdx(0))\n\n }\n\n}\n\n\n\nimpl<'a> SingleOwnedOutput<'static> for Arc<ImageSource> {\n\n fn output(&self) -> OperationOutput<'static> {\n\n OperationOutput::owned(self.clone(), OutputIdx(0))\n\n }\n\n}\n\n\n\nimpl OperationBuilder<'static> for ImageSource {\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 83, "score": 31092.224980181934 }, { "content": " })\n\n });\n\n\n\n crate::check_op!(ImageSource::new(\"rust:obj@abcdef\"), |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://docker.io/library/rust:obj@abcdef\".into(),\n\n attrs: Default::default(),\n\n })\n\n });\n\n\n\n crate::check_op!(\n\n ImageSource::new(\"b.gcr.io/test.example.com/my-app:test.example.com\"),\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://b.gcr.io/test.example.com/my-app:test.example.com\"\n\n .into(),\n\n attrs: Default::default(),\n\n })\n\n }\n\n );\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 84, "score": 31092.151068695013 }, { "content": "\n\n crate::check_op!(\n\n ImageSource::new(\"sub-dom1.foo.com/bar/baz/quux:some-long-tag\"),\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://sub-dom1.foo.com/bar/baz/quux:some-long-tag\".into(),\n\n attrs: Default::default(),\n\n })\n\n }\n\n );\n\n\n\n crate::check_op!(\n\n ImageSource::new(\"sub-dom1.foo.com/quux:some-long-tag\"),\n\n |op| {\n\n Op::Source(SourceOp {\n\n identifier: \"docker-image://sub-dom1.foo.com/quux:some-long-tag\".into(),\n\n attrs: Default::default(),\n\n })\n\n }\n\n );\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 85, "score": 31092.0084221641 }, { "content": " attrs: Default::default(),\n\n })),\n\n\n\n ..Default::default()\n\n };\n\n\n\n let metadata = OpMetadata {\n\n description: self.description.clone(),\n\n ignore_cache: self.ignore_cache,\n\n\n\n ..Default::default()\n\n };\n\n\n\n Ok(Node::new(head, metadata))\n\n }\n\n}\n\n\n\n#[test]\n", "file_path": "buildkit-llb/src/ops/source/git.rs", "rank": 86, "score": 31091.83323664578 }, { "content": " where\n\n S: Into<String>,\n\n {\n\n let mut raw_url = url.into();\n\n let remote = if raw_url.starts_with(\"http://\") {\n\n raw_url.split_off(7)\n\n } else if raw_url.starts_with(\"https://\") {\n\n raw_url.split_off(8)\n\n } else if raw_url.starts_with(\"git://\") {\n\n raw_url.split_off(6)\n\n } else if raw_url.starts_with(\"git@\") {\n\n raw_url.split_off(4)\n\n } else {\n\n raw_url\n\n };\n\n\n\n Self {\n\n id: OperationId::default(),\n\n remote,\n\n reference: None,\n", "file_path": "buildkit-llb/src/ops/source/git.rs", "rank": 87, "score": 31089.74235230637 }, { "content": " let mut name = name.into();\n\n\n\n let (digest, digest_separator) = match name.find('@') {\n\n Some(pos) => (Some(name[pos + 1..].into()), pos),\n\n None => (None, name.len()),\n\n };\n\n\n\n name.truncate(digest_separator);\n\n\n\n let (tag, tag_separator) = match TAG_EXPR.find(&name) {\n\n Some(found) => (Some(name[found.start() + 1..].into()), found.start()),\n\n None => (None, name.len()),\n\n };\n\n\n\n name.truncate(tag_separator);\n\n\n\n let (domain, mut name) = match name.find('/') {\n\n // The input has canonical-like format.\n\n Some(separator_pos) if &name[..separator_pos] == \"docker.io\" => {\n\n (None, name[separator_pos + 1..].into())\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 88, "score": 31088.040542765462 }, { "content": " Some(_) => (None, name),\n\n\n\n // Fallback if only single url component present.\n\n None => (None, name),\n\n };\n\n\n\n if domain.is_none() && name.find('/').is_none() {\n\n name = format!(\"library/{}\", name);\n\n }\n\n\n\n Self {\n\n id: OperationId::default(),\n\n\n\n domain,\n\n name,\n\n tag,\n\n digest,\n\n\n\n description: Default::default(),\n\n ignore_cache: false,\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 89, "score": 31087.794533887314 }, { "content": " }\n\n\n\n // Special case when domain is \"localhost\".\n\n Some(separator_pos) if &name[..separator_pos] == \"localhost\" => {\n\n (Some(\"localhost\".into()), name[separator_pos + 1..].into())\n\n }\n\n\n\n // General case for a common domain.\n\n Some(separator_pos) if name[..separator_pos].find('.').is_some() => (\n\n Some(name[..separator_pos].into()),\n\n name[separator_pos + 1..].into(),\n\n ),\n\n\n\n // General case for a domain with port number.\n\n Some(separator_pos) if name[..separator_pos].find(':').is_some() => (\n\n Some(name[..separator_pos].into()),\n\n name[separator_pos + 1..].into(),\n\n ),\n\n\n\n // Fallback if the first component is not a domain name.\n", "file_path": "buildkit-llb/src/ops/source/image.rs", "rank": 90, "score": 31085.245798638105 }, { "content": "}\n\n\n\nimpl<'a> MakeDirOperation<'a> {\n\n pub(crate) fn new<P>(output: OutputIdx, path: LayerPath<'a, P>) -> Self\n\n where\n\n P: AsRef<Path>,\n\n {\n\n let mut caps = HashMap::<String, bool>::new();\n\n caps.insert(\"file.base\".into(), true);\n\n\n\n MakeDirOperation {\n\n path: path.into_owned(),\n\n output,\n\n\n\n make_parents: false,\n\n\n\n caps,\n\n description: Default::default(),\n\n }\n\n }\n", "file_path": "buildkit-llb/src/ops/fs/mkdir.rs", "rank": 92, "score": 26.701251335082656 }, { "content": "}\n\n\n\nimpl<'a> MakeFileOperation<'a> {\n\n pub(crate) fn new<P>(output: OutputIdx, path: LayerPath<'a, P>) -> Self\n\n where\n\n P: AsRef<Path>,\n\n {\n\n let mut caps = HashMap::<String, bool>::new();\n\n caps.insert(\"file.base\".into(), true);\n\n\n\n MakeFileOperation {\n\n path: path.into_owned(),\n\n output,\n\n\n\n data: None,\n\n\n\n caps,\n\n description: Default::default(),\n\n }\n\n }\n", "file_path": "buildkit-llb/src/ops/fs/mkfile.rs", "rank": 93, "score": 26.70125133508266 }, { "content": "\n\nimpl<'a> SequenceOperation<'a> {\n\n pub(crate) fn new() -> Self {\n\n let mut caps = HashMap::<String, bool>::new();\n\n caps.insert(\"file.base\".into(), true);\n\n\n\n Self {\n\n id: OperationId::default(),\n\n inner: vec![],\n\n\n\n caps,\n\n description: Default::default(),\n\n ignore_cache: false,\n\n }\n\n }\n\n\n\n pub fn append<T>(mut self, op: T) -> Self\n\n where\n\n T: FileOperation + 'a,\n\n {\n", "file_path": "buildkit-llb/src/ops/fs/sequence.rs", "rank": 95, "score": 24.8920289559464 }, { "content": "use std::collections::HashMap;\n\nuse std::path::{Path, PathBuf};\n\n\n\nuse buildkit_proto::pb;\n\n\n\nuse super::path::LayerPath;\n\nuse super::FileOperation;\n\n\n\nuse crate::serialization::{Context, Result};\n\nuse crate::utils::OutputIdx;\n\n\n\n#[derive(Debug)]\n\npub struct MakeDirOperation<'a> {\n\n path: LayerPath<'a, PathBuf>,\n\n output: OutputIdx,\n\n\n\n make_parents: bool,\n\n\n\n description: HashMap<String, String>,\n\n caps: HashMap<String, bool>,\n", "file_path": "buildkit-llb/src/ops/fs/mkdir.rs", "rank": 99, "score": 20.426360818843786 } ]
Rust
src/shared/binary_rate_limiter.rs
rnestler/cobalt-rs
cf8a23791d4c253c75635a6206e8eeeb3f3e1969
use std::cmp; use std::time::{Duration, Instant}; use ::{Config, RateLimiter}; const MIN_GOOD_MODE_TIME_DELAY: u64 = 1000; const MAX_GOOD_MODE_TIME_DELAY: u64 = 60000; #[derive(Debug, PartialEq)] enum Mode { Good, Bad } #[derive(Debug)] pub struct BinaryRateLimiter { tick: u32, max_tick: u32, mode: Mode, rtt_threshold: u32, last_bad_time: Instant, last_good_time: Instant, good_time_duration: u64, delay_until_good_mode: u64 } impl RateLimiter for BinaryRateLimiter { fn new(config: Config) -> BinaryRateLimiter { let rate = config.send_rate as f32; BinaryRateLimiter { tick: 0, max_tick: (rate / (33.0 / (100.0 / rate))) as u32, mode: Mode::Good, rtt_threshold: 250, last_bad_time: Instant::now(), last_good_time: Instant::now(), good_time_duration: 0, delay_until_good_mode: MIN_GOOD_MODE_TIME_DELAY } } fn update(&mut self, rtt: u32, _: f32) { let conditions = if rtt <= self.rtt_threshold { self.good_time_duration += time_since(&self.last_good_time); self.last_good_time = Instant::now(); Mode::Good } else { self.last_bad_time = Instant::now(); self.good_time_duration = 0; Mode::Bad }; match self.mode { Mode::Good => match conditions { Mode::Bad => { self.mode = Mode::Bad; if time_since(&self.last_bad_time) < 10000 { self.delay_until_good_mode *= 2; self.delay_until_good_mode = cmp::min( self.delay_until_good_mode, MAX_GOOD_MODE_TIME_DELAY ); } }, Mode::Good => { if self.good_time_duration >= 10000 { self.good_time_duration -= 10000; self.delay_until_good_mode = cmp::max( self.delay_until_good_mode, MIN_GOOD_MODE_TIME_DELAY ); } } }, Mode::Bad => { if time_since(&self.last_bad_time) > self.delay_until_good_mode { self.mode = Mode::Good; } } } self.tick += 1; if self.tick == self.max_tick { self.tick = 0; } } fn congested(&self) -> bool { self.mode == Mode::Bad } fn should_send(&self ) -> bool { !self.congested() || self.tick == 0 } fn reset(&mut self) { self.tick = 0; self.mode = Mode::Good; self.last_bad_time = Instant::now();; self.last_good_time = Instant::now(); self.good_time_duration = 0; self.delay_until_good_mode = MIN_GOOD_MODE_TIME_DELAY; } } fn time_since(i: &Instant) -> u64 { millis_from_duration(i.elapsed()) } fn millis_from_duration(d: Duration) -> u64 { d.as_secs() * 1000 + (d.subsec_nanos() as u64 / 1000000) } #[cfg(test)] mod test { use std::thread; use std::time::Duration; use ::{Config, RateLimiter}; use super::BinaryRateLimiter; #[test] fn test_modes() { let mut rl = BinaryRateLimiter::new(Config::default()); assert_eq!(rl.congested(), false); assert_eq!(rl.should_send(), true); rl.update(51, 0.0); assert_eq!(rl.congested(), false); assert_eq!(rl.should_send(), true); rl.update(151, 0.0); assert_eq!(rl.congested(), false); assert_eq!(rl.should_send(), true); rl.update(250, 0.0); assert_eq!(rl.congested(), false); assert_eq!(rl.should_send(), true); rl.update(251, 0.0); assert_eq!(rl.congested(), true); assert_eq!(rl.should_send(), false); rl.update(251, 0.0); assert_eq!(rl.should_send(), false); rl.update(251, 0.0); assert_eq!(rl.should_send(), true); thread::sleep(Duration::from_millis(2100)); rl.update(12, 0.0); assert_eq!(rl.congested(), false); assert_eq!(rl.should_send(), true); } #[test] fn test_reset() { let mut rl = BinaryRateLimiter::new(Config::default()); assert_eq!(rl.congested(), false); assert_eq!(rl.should_send(), true); rl.update(251, 0.0); assert_eq!(rl.congested(), true); assert_eq!(rl.should_send(), false); rl.reset(); assert_eq!(rl.congested(), false); assert_eq!(rl.should_send(), true); } }
use std::cmp; use std::time::{Duration, Instant}; use ::{Config, RateLimiter}; const MIN_GOOD_MODE_TIME_DELAY: u64 = 1000; const MAX_GOOD_MODE_TIME_DELAY: u64 = 60000; #[derive(Debug, PartialEq)] enum Mode { Good, Bad } #[derive(Debug)] pub struct BinaryRateLimiter { tick: u32, max_tick: u32, mode: Mode, rtt_threshold: u32, last_bad_time: Instant, last_good_time: Instant, good_time_duration: u64, delay_until_good_mode: u64 } impl RateLimiter for BinaryRateLimiter { fn new(config: Config) -> BinaryRateLimiter { let rate = config.send_rate as f32; BinaryRateLimiter { tick: 0, max_tick: (rate / (33.0 / (100.0 / rate))) as u32, mode: Mode::Good, rtt_threshold: 250, last_bad_time: Instant::now(), last_good_time: Instant::now(), good_time_duration: 0, delay_until_good_mode: MIN_GOOD_MODE_TIME_DELAY } } fn update(&mut self, rtt: u32, _: f32) { let conditions = if rtt <= self.rtt_threshold { self.good_time_duration += time_since(&self.last_good_time); self.last_good_time = Instant::now(); Mode::Good } else { self.last_bad_time = Instant::now(); self.good_time_duration = 0; Mode::Bad }; match self.mode { Mode::Good => match conditions { Mode::Bad => { self.mode = Mode::Bad; if time_since(&self.last_bad_time) < 10000 { self.delay_until_good_mode *= 2; self.delay_until_good_mode = cmp::min( self.delay_until_good_mode, MAX_GOOD_MODE_TIME_DELAY ); } },
MIN_GOOD_MODE_TIME_DELAY ); } } }, Mode::Bad => { if time_since(&self.last_bad_time) > self.delay_until_good_mode { self.mode = Mode::Good; } } } self.tick += 1; if self.tick == self.max_tick { self.tick = 0; } } fn congested(&self) -> bool { self.mode == Mode::Bad } fn should_send(&self ) -> bool { !self.congested() || self.tick == 0 } fn reset(&mut self) { self.tick = 0; self.mode = Mode::Good; self.last_bad_time = Instant::now();; self.last_good_time = Instant::now(); self.good_time_duration = 0; self.delay_until_good_mode = MIN_GOOD_MODE_TIME_DELAY; } } fn time_since(i: &Instant) -> u64 { millis_from_duration(i.elapsed()) } fn millis_from_duration(d: Duration) -> u64 { d.as_secs() * 1000 + (d.subsec_nanos() as u64 / 1000000) } #[cfg(test)] mod test { use std::thread; use std::time::Duration; use ::{Config, RateLimiter}; use super::BinaryRateLimiter; #[test] fn test_modes() { let mut rl = BinaryRateLimiter::new(Config::default()); assert_eq!(rl.congested(), false); assert_eq!(rl.should_send(), true); rl.update(51, 0.0); assert_eq!(rl.congested(), false); assert_eq!(rl.should_send(), true); rl.update(151, 0.0); assert_eq!(rl.congested(), false); assert_eq!(rl.should_send(), true); rl.update(250, 0.0); assert_eq!(rl.congested(), false); assert_eq!(rl.should_send(), true); rl.update(251, 0.0); assert_eq!(rl.congested(), true); assert_eq!(rl.should_send(), false); rl.update(251, 0.0); assert_eq!(rl.should_send(), false); rl.update(251, 0.0); assert_eq!(rl.should_send(), true); thread::sleep(Duration::from_millis(2100)); rl.update(12, 0.0); assert_eq!(rl.congested(), false); assert_eq!(rl.should_send(), true); } #[test] fn test_reset() { let mut rl = BinaryRateLimiter::new(Config::default()); assert_eq!(rl.congested(), false); assert_eq!(rl.should_send(), true); rl.update(251, 0.0); assert_eq!(rl.congested(), true); assert_eq!(rl.should_send(), false); rl.reset(); assert_eq!(rl.congested(), false); assert_eq!(rl.should_send(), true); } }
Mode::Good => { if self.good_time_duration >= 10000 { self.good_time_duration -= 10000; self.delay_until_good_mode = cmp::max( self.delay_until_good_mode,
function_block-random_span
[ { "content": "fn create_connection(config: Option<Config>) -> Connection<BinaryRateLimiter, NoopPacketModifier> {\n\n create_connection_with_modifier::<NoopPacketModifier>(config)\n\n}\n\n\n", "file_path": "src/test/connection.rs", "rank": 3, "score": 102625.29645147541 }, { "content": "// Helpers --------------------------------------------------------------------\n\nfn client_init(config: Config) -> Client<MockSocket, BinaryRateLimiter, NoopPacketModifier> {\n\n\n\n let mut client = Client::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(config);\n\n client.connect(\"255.1.1.1:5678\").ok();\n\n\n\n // Verify initial connection packet\n\n let id = client.connection().unwrap().id().0;\n\n client.send(false).ok();\n\n client.socket().unwrap().assert_sent(vec![\n\n (\"255.1.1.1:5678\", [\n\n 1, 2, 3, 4,\n\n (id >> 24) as u8,\n\n (id >> 16) as u8,\n\n (id >> 8) as u8,\n\n id as u8,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0\n\n\n\n ].to_vec())\n\n ]);\n\n\n\n client\n\n\n\n}\n\n\n", "file_path": "src/test/client.rs", "rank": 4, "score": 100712.6361914995 }, { "content": "fn seq_bit_index(seq: u32, ack: u32) -> u32 {\n\n if seq > ack {\n\n ack + (MAX_SEQ_NUMBER - 1 - seq)\n\n\n\n } else {\n\n ack - 1 - seq\n\n }\n\n}\n\n\n", "file_path": "src/shared/connection.rs", "rank": 5, "score": 98706.87740606512 }, { "content": "#[test]\n\nfn test_rtt_tick_correction() {\n\n\n\n let mut conn = create_connection(None);\n\n let mut socket = MockSocket::new(conn.local_addr(), 0).unwrap();\n\n let address = conn.peer_addr();\n\n\n\n assert_eq!(conn.rtt(), 0);\n\n\n\n // First packet\n\n conn.send_packet(&mut socket, &address);\n\n socket.assert_sent(vec![\n\n (\"255.1.1.2:5678\", [\n\n 1, 2, 3, 4,\n\n (conn.id().0 >> 24) as u8,\n\n (conn.id().0 >> 16) as u8,\n\n (conn.id().0 >> 8) as u8,\n\n conn.id().0 as u8,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0\n", "file_path": "src/test/connection.rs", "rank": 6, "score": 97307.07521407463 }, { "content": "// Helpers --------------------------------------------------------------------\n\nfn create_connection_with_modifier<T: PacketModifier>(config: Option<Config>) -> Connection<BinaryRateLimiter, T> {\n\n let config = config.unwrap_or_else(Config::default);\n\n let local_address: SocketAddr = \"127.0.0.1:1234\".parse().unwrap();\n\n let peer_address: SocketAddr = \"255.1.1.2:5678\".parse().unwrap();\n\n let limiter = BinaryRateLimiter::new(config);\n\n let modifier = T::new(config);\n\n Connection::new(config, local_address, peer_address, limiter, modifier)\n\n}\n\n\n", "file_path": "src/test/connection.rs", "rank": 7, "score": 95820.29030890358 }, { "content": "// Static Helpers -------------------------------------------------------------\n\nfn moving_average(a: f32, b: Duration) -> f32 {\n\n let b = (b.as_secs() as f32) * 1000.0 + (b.subsec_nanos() / 1000000) as f32;\n\n (a - (a - b) * 0.10).max(0.0)\n\n}\n\n\n", "file_path": "src/shared/connection.rs", "rank": 8, "score": 94380.18914139559 }, { "content": "fn seq_is_more_recent(a: u32, b: u32) -> bool {\n\n (a > b) && (a - b <= MAX_SEQ_NUMBER / 2) ||\n\n (b > a) && (b - a > MAX_SEQ_NUMBER / 2)\n\n}\n\n\n", "file_path": "src/shared/connection.rs", "rank": 9, "score": 94218.3853669351 }, { "content": "fn seq_was_acked(seq: u32, ack: u32, bitfield: u32) -> bool {\n\n if seq == ack {\n\n true\n\n\n\n } else {\n\n let bit = seq_bit_index(seq, ack);\n\n bit < MAX_ACK_BITS && (bitfield & (1 << bit)) != 0\n\n }\n\n}\n\n\n", "file_path": "src/shared/connection.rs", "rank": 10, "score": 93795.16225558077 }, { "content": "/// Trait describing a network congestion avoidance algorithm.\n\npub trait RateLimiter {\n\n\n\n /// Method that constructs a new rate limiter using the provided configuration.\n\n fn new(Config) -> Self where Self: Sized;\n\n\n\n /// Method implementing a congestion avoidance algorithm based on round\n\n /// trip time and packet loss.\n\n fn update(&mut self, rtt: u32, packet_loss: f32);\n\n\n\n /// Method that should return `true` in case the connection is currently\n\n /// considered congested and should reduce the number of packets it sends\n\n /// per second.\n\n fn congested(&self) -> bool;\n\n\n\n /// Method that returns whether a connection should be currently sending\n\n /// packets or not.\n\n fn should_send(&self) -> bool;\n\n\n\n /// Method that resets any internal state of the rate limiter.\n\n fn reset(&mut self);\n\n\n\n}\n\n\n\nimpl fmt::Debug for RateLimiter {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"RateLimiter\")\n\n }\n\n}\n\n\n", "file_path": "src/traits/rate_limiter.rs", "rank": 11, "score": 89438.56064684934 }, { "content": "// Helpers ---------------------------------------------------------------------\n\nfn nanos_from_duration(d: Duration) -> u64 {\n\n d.as_secs() * 1000 * 1000000 + d.subsec_nanos() as u64\n\n}\n\n\n", "file_path": "src/shared/ticker.rs", "rank": 12, "score": 83301.06662775556 }, { "content": "#[test]\n\nfn test_rtt() {\n\n\n\n let mut conn = create_connection(None);\n\n let mut socket = MockSocket::new(conn.local_addr(), 0).unwrap();\n\n let address = conn.peer_addr();\n\n\n\n assert_eq!(conn.rtt(), 0);\n\n\n\n // First packet\n\n conn.send_packet(&mut socket, &address);\n\n socket.assert_sent(vec![\n\n (\"255.1.1.2:5678\", [\n\n 1, 2, 3, 4,\n\n (conn.id().0 >> 24) as u8,\n\n (conn.id().0 >> 16) as u8,\n\n (conn.id().0 >> 8) as u8,\n\n conn.id().0 as u8,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0\n", "file_path": "src/test/connection.rs", "rank": 13, "score": 73346.28597060584 }, { "content": "#[test]\n\nfn test_set_config() {\n\n // TODO how to check that the config was actually modified?\n\n let mut conn = create_connection(None);\n\n conn.set_config(Config {\n\n send_rate: 10,\n\n .. Config::default()\n\n });\n\n}\n\n\n", "file_path": "src/test/connection.rs", "rank": 14, "score": 70708.34476124767 }, { "content": "#[derive(Debug, PartialEq)]\n\nenum PacketState {\n\n Unknown,\n\n Acked,\n\n Lost\n\n}\n\n\n\n/// Structure used for packet acknowledgment of sent packets.\n", "file_path": "src/shared/connection.rs", "rank": 15, "score": 56896.23789175875 }, { "content": "#[derive(Debug, Eq, PartialEq)]\n\nstruct Message {\n\n kind: MessageKind,\n\n order: u16,\n\n size: u16,\n\n data: Vec<u8>\n\n}\n\n\n\nimpl Ord for Message {\n\n // Explicitly implement the trait so the queue becomes a min-heap\n\n // instead of a max-heap.\n\n fn cmp(&self, other: &Self) -> cmp::Ordering {\n\n other.order.cmp(&self.order)\n\n }\n\n}\n\n\n\nimpl PartialOrd for Message {\n\n fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {\n\n Some(self.cmp(other))\n\n }\n\n}\n", "file_path": "src/shared/message_queue.rs", "rank": 16, "score": 56896.23789175875 }, { "content": "// Helpers --------------------------------------------------------------------\n\nfn map_connection_events<R: RateLimiter, M: PacketModifier>(\n\n server_events: &mut VecDeque<ServerEvent>,\n\n connection: &mut Connection<R, M>\n\n) {\n\n let id = connection.id();\n\n for event in connection.events() {\n\n server_events.push_back(match event {\n\n ConnectionEvent::Connected => ServerEvent::Connection(id),\n\n ConnectionEvent::Lost(by_remote) => ServerEvent::ConnectionLost(id, by_remote),\n\n ConnectionEvent::FailedToConnect => unreachable!(),\n\n ConnectionEvent::Closed(by_remote) => ServerEvent::ConnectionClosed(id, by_remote),\n\n ConnectionEvent::Message(payload) => ServerEvent::Message(id, payload),\n\n ConnectionEvent::CongestionStateChanged(c) => ServerEvent::ConnectionCongestionStateChanged(id, c),\n\n ConnectionEvent::PacketLost(payload) => ServerEvent::PacketLost(id, payload)\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/server.rs", "rank": 17, "score": 56302.8420664489 }, { "content": "#[derive(Debug)]\n\nstruct SentPacketAck {\n\n seq: u32,\n\n time: Instant,\n\n state: PacketState,\n\n packet: Option<Vec<u8>>\n\n}\n\n\n\n/// Enum indicating the state of a connection.\n\n#[derive(Debug, Copy, Clone, PartialEq)]\n\npub enum ConnectionState {\n\n\n\n /// The connection has been opened but has yet to receive the first\n\n /// incoming packet.\n\n Connecting,\n\n\n\n /// The remote has responded and at least one incoming packet has been\n\n /// received.\n\n Connected,\n\n\n\n /// The remote did not respond with the first packet within the maximum\n", "file_path": "src/shared/connection.rs", "rank": 18, "score": 55608.853697523904 }, { "content": "/// Trait describing optional per-packet payload modification logic.\n\npub trait PacketModifier {\n\n\n\n /// Method that constructs a new packet modifier using the provided configuration.\n\n fn new(Config) -> Self where Self: Sized;\n\n\n\n /// Method that is called for payload modification before a packet is send\n\n /// over a connection's underlying socket.\n\n ///\n\n /// The default implementation does not actually perform any kind of\n\n /// modification and leaves the payload to be send untouched.\n\n fn outgoing(&mut self, _: &[u8]) -> Option<Vec<u8>> {\n\n None\n\n }\n\n\n\n /// Method that is called for payload modification purposes after a packet\n\n /// is received over a connection's underlying socket.\n\n ///\n\n /// The default implementation does not actually perform any kind of\n\n /// modification and returns leaves received payload untouched.\n\n fn incoming(&mut self, _: &[u8]) -> Option<Vec<u8>> {\n", "file_path": "src/traits/packet_modifier.rs", "rank": 19, "score": 51354.170321264835 }, { "content": "/// Trait describing a non-blocking low latency socket.\n\npub trait Socket: fmt::Debug {\n\n\n\n /// Method that tries to bind a new socket at the specified address.\n\n fn new<T: net::ToSocketAddrs>(T, usize) -> Result<Self, Error> where Self: Sized;\n\n\n\n /// Method that attempts to return a incoming packet on this socket without\n\n /// blocking.\n\n fn try_recv(&mut self) -> Result<(net::SocketAddr, Vec<u8>), TryRecvError>;\n\n\n\n /// Method sending data on the socket to the given address. On success,\n\n /// returns the number of bytes written.\n\n fn send_to(\n\n &mut self, data: &[u8], addr: net::SocketAddr)\n\n\n\n -> Result<usize, Error>;\n\n\n\n /// Method returning the address of the actual, underlying socket.\n\n fn local_addr(&self) -> Result<net::SocketAddr, Error>;\n\n\n\n}\n\n\n", "file_path": "src/traits/socket.rs", "rank": 20, "score": 47074.14265211287 }, { "content": "fn main() {\n\n\n\n // Create a new server that communicates over a udp socket\n\n let mut server = Server::<\n\n UdpSocket,\n\n BinaryRateLimiter,\n\n NoopPacketModifier\n\n\n\n >::new(Config::default());\n\n\n\n // Make the server listen on port `1234` on all interfaces.\n\n println!(\"[Server] Listening...\");\n\n server.listen(\"0.0.0.0:1234\").expect(\"Failed to bind to socket.\");\n\n\n\n 'main: loop {\n\n\n\n // Accept incoming connections and fetch their events\n\n while let Ok(event) = server.accept_receive() {\n\n // Handle events (e.g. Connection, Messages, etc.)\n\n match event {\n", "file_path": "examples/server.rs", "rank": 21, "score": 44898.4193240092 }, { "content": "fn main() {\n\n\n\n // Create a new client that communicates over a udp socket\n\n let mut client = Client::<\n\n UdpSocket,\n\n BinaryRateLimiter,\n\n NoopPacketModifier\n\n\n\n >::new(Config::default());\n\n\n\n // Make the client connect to port `1234` on `localhost`\n\n println!(\"[Client] Connecting...\");\n\n client.connect(\"127.0.0.1:1234\").expect(\"Failed to bind to socket.\");\n\n\n\n 'main: loop {\n\n\n\n // Accept incoming connections and fetch their events\n\n while let Ok(event) = client.receive() {\n\n // Handle events (e.g. Connection, Messages, etc.)\n\n match event {\n", "file_path": "examples/client.rs", "rank": 22, "score": 44898.4193240092 }, { "content": "fn client_events(client: &mut Client<MockSocket, BinaryRateLimiter, NoopPacketModifier>) -> Vec<ClientEvent> {\n\n client.send(false).ok();\n\n let mut events = Vec::new();\n\n while let Ok(event) = client.receive() {\n\n events.push(event);\n\n }\n\n events\n\n}\n\n\n", "file_path": "src/test/client.rs", "rank": 23, "score": 43871.428356658726 }, { "content": "// Helpers --------------------------------------------------------------------\n\nfn server_events(server: &mut Server<MockSocket, BinaryRateLimiter, NoopPacketModifier>) -> Vec<ServerEvent> {\n\n server.send(false).ok();\n\n let mut events = Vec::new();\n\n while let Ok(event) = server.accept_receive() {\n\n events.push(event);\n\n }\n\n events\n\n}\n\n\n", "file_path": "src/test/server.rs", "rank": 24, "score": 43871.428356658726 }, { "content": "#[test]\n\nfn test_create() {\n\n\n\n let mut conn = create_connection(None);\n\n assert_eq!(conn.open(), true);\n\n assert_eq!(conn.congested(), false);\n\n assert!(conn.state() == ConnectionState::Connecting);\n\n assert_eq!(conn.rtt(), 0);\n\n assert_f32_eq!(conn.packet_loss(), 0.0);\n\n\n\n let local_address: SocketAddr = \"127.0.0.1:1234\".parse().unwrap();\n\n let peer_address: SocketAddr = \"255.1.1.2:5678\".parse().unwrap();\n\n\n\n assert_eq!(conn.local_addr(), local_address);\n\n assert_eq!(conn.peer_addr(), peer_address);\n\n assert_eq!(conn.events().len(), 0);\n\n\n\n}\n\n\n", "file_path": "src/test/connection.rs", "rank": 25, "score": 42107.73290617343 }, { "content": "#[test]\n\nfn test_reset() {\n\n let mut conn = create_connection(None);\n\n conn.close();\n\n assert!(conn.state() == ConnectionState::Closing);\n\n\n\n conn.reset();\n\n assert_eq!(conn.open(), true);\n\n assert!(conn.state() == ConnectionState::Connecting);\n\n}\n\n\n", "file_path": "src/test/connection.rs", "rank": 26, "score": 42107.73290617343 }, { "content": "#[test]\n\nfn test_send_failure() {\n\n\n\n let mut conn = create_connection(None);\n\n let mut socket = MockSocket::new(conn.local_addr(), 0).unwrap();\n\n let address = conn.peer_addr();\n\n\n\n conn.send_packet(&mut socket, &address);\n\n socket.assert_sent(vec![\n\n (\"255.1.1.2:5678\", [\n\n 1, 2, 3, 4,\n\n (conn.id().0 >> 24) as u8,\n\n (conn.id().0 >> 16) as u8,\n\n (conn.id().0 >> 8) as u8,\n\n conn.id().0 as u8,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0\n\n ].to_vec())\n\n ]);\n\n\n", "file_path": "src/test/connection.rs", "rank": 27, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_receive_packet() {\n\n\n\n let mut conn = create_connection(None);\n\n\n\n assert_eq!(conn.receive_packet([\n\n 1, 2, 3, 4,\n\n 0, 0, 0, 0, // ConnectionID is ignored by receive_packet)\n\n 0, // local sequence number\n\n 0, // remote sequence number we confirm\n\n 0, 0, 0, 0\n\n\n\n ].to_vec()), true);\n\n\n\n // Ignore message with same sequence number\n\n assert_eq!(conn.receive_packet([\n\n 1, 2, 3, 4,\n\n 0, 0, 0, 0, // ConnectionID is ignored by receive_packet)\n\n 0, // local sequence number\n\n 0, // remote sequence number we confirm\n\n 0, 0, 0, 0\n", "file_path": "src/test/connection.rs", "rank": 28, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_debug_fmt() {\n\n let mut conn = create_connection(None);\n\n let mut socket = MockSocket::new(conn.local_addr(), 0).unwrap();\n\n let address = conn.peer_addr();\n\n conn.send_packet(&mut socket, &address);\n\n assert_ne!(format!(\"{:?}\", conn), \"\");\n\n}\n\n\n\n\n", "file_path": "src/test/connection.rs", "rank": 29, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_client_internals() {\n\n\n\n let mut client = Client::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config {\n\n send_rate: 30,\n\n .. Config::default()\n\n });\n\n\n\n assert_eq!(client.socket().unwrap_err().kind(), ErrorKind::NotConnected);\n\n\n\n}\n\n\n", "file_path": "src/test/client.rs", "rank": 30, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_server_internals() {\n\n\n\n let mut server = Server::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config {\n\n send_rate: 30,\n\n .. Config::default()\n\n });\n\n\n\n assert_eq!(server.socket().unwrap_err().kind(), ErrorKind::NotConnected);\n\n\n\n}\n\n\n", "file_path": "src/test/server.rs", "rank": 31, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_client_configuration() {\n\n\n\n let config = Config {\n\n send_rate: 30,\n\n .. Config::default()\n\n };\n\n\n\n let mut client = Client::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(config);\n\n assert_eq!(client.config(), config);\n\n\n\n let config = Config {\n\n send_rate: 60,\n\n .. Config::default()\n\n };\n\n\n\n client.set_config(config);\n\n assert_eq!(client.config(), config);\n\n\n\n}\n\n\n", "file_path": "src/test/client.rs", "rank": 32, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_close_remote() {\n\n\n\n let mut conn = create_connection(None);\n\n assert!(conn.state() == ConnectionState::Connecting);\n\n\n\n // Receive initial packet\n\n conn.receive_packet([\n\n 1, 2, 3, 4,\n\n 0, 0, 0, 0, // ConnectionID is ignored by receive_packet)\n\n 0, // local sequence number\n\n 0, // remote sequence number we confirm\n\n 0, 0, 0, 0 // bitfield\n\n\n\n ].to_vec());\n\n\n\n assert!(conn.state() == ConnectionState::Connected);\n\n\n\n let events: Vec<ConnectionEvent> = conn.events().collect();\n\n assert_eq!(events, vec![ConnectionEvent::Connected]);\n\n\n", "file_path": "src/test/connection.rs", "rank": 33, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_close_local() {\n\n\n\n let mut conn = create_connection(None);\n\n let mut socket = MockSocket::new(conn.local_addr(), 0).unwrap();\n\n let address = conn.peer_addr();\n\n\n\n // Initiate closure\n\n conn.close();\n\n assert_eq!(conn.open(), true);\n\n assert!(conn.state() == ConnectionState::Closing);\n\n\n\n // Receival of packets should have no effect on the connection state\n\n conn.receive_packet([\n\n 1, 2, 3, 4,\n\n 0, 0, 0, 0, // ConnectionID is ignored by receive_packet)\n\n 0, // local sequence number\n\n 0, // remote sequence number we confirm\n\n 0, 0, 0, 0 // bitfield\n\n\n\n ].to_vec());\n", "file_path": "src/test/connection.rs", "rank": 34, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_server_disconnected() {\n\n\n\n let conn_id = ConnectionID(0);\n\n\n\n let mut server = Server::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config {\n\n send_rate: 30,\n\n .. Config::default()\n\n });\n\n\n\n assert_eq!(server.bytes_sent(), 0);\n\n assert_eq!(server.bytes_received(), 0);\n\n\n\n assert_eq!(server.local_addr().unwrap_err().kind(), ErrorKind::AddrNotAvailable);\n\n assert_eq!(server.connection(&conn_id).unwrap_err().kind(), ErrorKind::NotConnected);\n\n assert_eq!(server.connections().len(), 0);\n\n\n\n assert_eq!(server.accept_receive(), Err(TryRecvError::Disconnected));\n\n assert_eq!(server.send(false).unwrap_err().kind(), ErrorKind::NotConnected);\n\n assert_eq!(server.shutdown().unwrap_err().kind(), ErrorKind::NotConnected);\n\n\n\n}\n\n\n", "file_path": "src/test/server.rs", "rank": 35, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_client_disconnected() {\n\n\n\n let mut client = Client::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config {\n\n send_rate: 30,\n\n .. Config::default()\n\n });\n\n\n\n assert_eq!(client.bytes_sent(), 0);\n\n assert_eq!(client.bytes_received(), 0);\n\n\n\n assert_eq!(client.peer_addr().unwrap_err().kind(), ErrorKind::AddrNotAvailable);\n\n assert_eq!(client.local_addr().unwrap_err().kind(), ErrorKind::AddrNotAvailable);\n\n assert_eq!(client.connection().unwrap_err().kind(), ErrorKind::NotConnected);\n\n\n\n assert_eq!(client.receive(), Err(TryRecvError::Disconnected));\n\n assert_eq!(client.send(false).unwrap_err().kind(), ErrorKind::NotConnected);\n\n assert_eq!(client.reset().unwrap_err().kind(), ErrorKind::NotConnected);\n\n assert_eq!(client.disconnect().unwrap_err().kind(), ErrorKind::NotConnected);\n\n\n\n}\n\n\n", "file_path": "src/test/client.rs", "rank": 36, "score": 40884.90179687059 }, { "content": "fn write_messages(\n\n queue: &mut VecDeque<Message>,\n\n packet: &mut Vec<u8>,\n\n available: usize,\n\n written: &mut usize\n\n) {\n\n let mut used = 0;\n\n while write_message(queue, packet, available, &mut used) {}\n\n *written += used;\n\n}\n\n\n", "file_path": "src/shared/message_queue.rs", "rank": 37, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_server_receive() {\n\n\n\n let mut server = Server::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config::default());\n\n server.listen(\"127.0.0.1:1234\").ok();\n\n\n\n // Accept incoming connections\n\n server.socket().unwrap().mock_receive(vec![\n\n (\"255.1.1.1:1000\", vec![\n\n 1, 2, 3, 4,\n\n 9, 8, 7, 6,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0,\n\n 0, 0, 0, 3, 66, 97, 122\n\n ]),\n\n (\"255.1.1.2:2000\", vec![\n\n 1, 2, 3, 4,\n\n 5, 5, 1, 1,\n\n 0,\n\n 0,\n", "file_path": "src/test/server.rs", "rank": 38, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_id_from_packet() {\n\n\n\n let config = Config {\n\n protocol_header: [1, 3, 3, 7],\n\n .. Config::default()\n\n };\n\n\n\n // Extract ID from matching protocol header\n\n assert_eq!(Connection::<BinaryRateLimiter, NoopPacketModifier>::id_from_packet(\n\n &config,\n\n &[1, 3, 3, 7, 1, 2, 3, 4]\n\n\n\n ), Some(ConnectionID(16909060)));\n\n\n\n // Ignore ID from non-matching protocol header\n\n assert_eq!(Connection::<BinaryRateLimiter, NoopPacketModifier>::id_from_packet(\n\n &config,\n\n &[9, 0, 0, 0, 1, 2, 3, 4]\n\n\n\n ), None);\n", "file_path": "src/test/connection.rs", "rank": 39, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_server_configuration() {\n\n\n\n let config = Config {\n\n send_rate: 30,\n\n .. Config::default()\n\n };\n\n\n\n let mut server = Server::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(config);\n\n assert_eq!(server.config(), config);\n\n\n\n let config = Config {\n\n send_rate: 60,\n\n .. Config::default()\n\n };\n\n\n\n server.set_config(config);\n\n assert_eq!(server.config(), config);\n\n\n\n}\n\n\n", "file_path": "src/test/server.rs", "rank": 40, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_packet_loss() {\n\n\n\n let config = Config {\n\n // set a low threshold for packet loss\n\n packet_drop_threshold: Duration::from_millis(10),\n\n .. Config::default()\n\n };\n\n\n\n let mut conn = create_connection(Some(config));\n\n let mut socket = MockSocket::new(conn.local_addr(), 0).unwrap();\n\n let address = conn.peer_addr();\n\n\n\n conn.send(MessageKind::Instant, b\"Packet Instant\".to_vec());\n\n conn.send(MessageKind::Reliable, b\"Packet Reliable\".to_vec());\n\n conn.send(MessageKind::Ordered, b\"Packet Ordered\".to_vec());\n\n\n\n conn.send_packet(&mut socket, &address);\n\n socket.assert_sent(vec![\n\n (\"255.1.1.2:5678\", [\n\n 1, 2, 3, 4,\n", "file_path": "src/test/connection.rs", "rank": 41, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_client_send() {\n\n\n\n let mut client = client_init(Config {\n\n connection_drop_threshold: Duration::from_millis(100),\n\n .. Config::default()\n\n });\n\n\n\n assert_eq!(client.bytes_sent(), 14);\n\n\n\n // Mock the receival of the first server packet which acknowledges the client\n\n let id = client.connection().unwrap().id().0;\n\n client.socket().unwrap().mock_receive(vec![\n\n (\"255.1.1.1:5678\", vec![\n\n 1, 2, 3, 4,\n\n (id >> 24) as u8,\n\n (id >> 16) as u8,\n\n (id >> 8) as u8,\n\n id as u8,\n\n 0,\n\n 0,\n", "file_path": "src/test/client.rs", "rank": 42, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_server_send() {\n\n\n\n let mut server = Server::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config::default());\n\n server.listen(\"127.0.0.1:1234\").ok();\n\n\n\n // Accept a incoming connection\n\n server.socket().unwrap().mock_receive(vec![\n\n (\"255.1.1.1:1000\", vec![\n\n 1, 2, 3, 4,\n\n 9, 8, 7, 6,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0\n\n ])\n\n ]);\n\n\n\n assert_eq!(server_events(&mut server), vec![\n\n ServerEvent::Connection(ConnectionID(151521030))\n\n ]);\n\n\n", "file_path": "src/test/server.rs", "rank": 43, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_reset() {\n\n\n\n let mut q = MessageQueue::new(Config::default());\n\n q.send(MessageKind::Instant, b\"Hello World\".to_vec());\n\n q.send(MessageKind::Instant, b\"Hello World\".to_vec());\n\n q.send(MessageKind::Reliable, b\"Hello World\".to_vec());\n\n q.send(MessageKind::Ordered, b\"Hello World\".to_vec());\n\n q.send(MessageKind::Ordered, b\"Hello World\".to_vec());\n\n\n\n // Reset all queues and order ids\n\n q.reset();\n\n\n\n // Check that nothing gets serialized\n\n let mut buffer = Vec::new();\n\n q.send_packet(&mut buffer, 64);\n\n assert_eq!(buffer, [].to_vec());\n\n\n\n // Check that local_order_id has been reset\n\n q.send(MessageKind::Ordered, b\"\".to_vec());\n\n q.send_packet(&mut buffer, 64);\n\n assert_eq!(buffer, [2, 0, 0, 0].to_vec());\n\n}\n\n\n", "file_path": "src/test/message_queue.rs", "rank": 44, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_connecting_failed() {\n\n\n\n let mut conn = create_connection(None);\n\n let mut socket = MockSocket::new(conn.local_addr(), 0).unwrap();\n\n let address = conn.peer_addr();\n\n\n\n thread::sleep(Duration::from_millis(500));\n\n conn.send_packet(&mut socket, &address);\n\n\n\n let events: Vec<ConnectionEvent> = conn.events().collect();\n\n assert_eq!(events, vec![ConnectionEvent::FailedToConnect]);\n\n\n\n // Ignore any further packets\n\n conn.receive_packet([\n\n 1, 2, 3, 4,\n\n 0, 0, 0, 0,\n\n 0, 128, 85, 85, 85, 85 // closure packet data\n\n\n\n ].to_vec());\n\n\n\n let events: Vec<ConnectionEvent> = conn.events().collect();\n\n assert_eq!(events, vec![]);\n\n\n\n}\n\n\n", "file_path": "src/test/connection.rs", "rank": 45, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_client_receive() {\n\n\n\n let mut client = client_init(Config {\n\n connection_drop_threshold: Duration::from_millis(100),\n\n .. Config::default()\n\n });\n\n\n\n let id = client.connection().unwrap().id().0;\n\n client.socket().unwrap().mock_receive(vec![\n\n (\"255.1.1.1:5678\", vec![\n\n 1, 2, 3, 4,\n\n (id >> 24) as u8,\n\n (id >> 16) as u8,\n\n (id >> 8) as u8,\n\n id as u8,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0,\n\n 1, 0, 0, 3, 70, 111, 111,\n\n 0, 0, 0, 3, 66, 97, 114\n", "file_path": "src/test/client.rs", "rank": 46, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_server_connection() {\n\n\n\n let mut server = Server::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config::default());\n\n server.listen(\"127.0.0.1:1234\").ok();\n\n\n\n // Accept a incoming connection\n\n server.socket().unwrap().mock_receive(vec![\n\n (\"255.1.1.1:1000\", vec![\n\n 1, 2, 3, 4,\n\n 9, 8, 7, 6,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0\n\n ])\n\n ]);\n\n\n\n assert_eq!(server_events(&mut server), vec![\n\n ServerEvent::Connection(ConnectionID(151521030))\n\n ]);\n\n\n", "file_path": "src/test/server.rs", "rank": 47, "score": 40884.90179687059 }, { "content": "fn write_message(\n\n queue: &mut VecDeque<Message>,\n\n packet: &mut Vec<u8>,\n\n available: usize,\n\n written: &mut usize\n\n\n\n) -> bool {\n\n\n\n if queue.is_empty() {\n\n false\n\n\n\n } else {\n\n\n\n let required = {\n\n (queue.front().unwrap().size as usize) + MESSAGE_HEADER_BYTES\n\n };\n\n\n\n // If adding this message would exceed the available bytes, exit\n\n if required > available - *written {\n\n false\n", "file_path": "src/shared/message_queue.rs", "rank": 48, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_packet_modification() {\n\n\n\n #[derive(Debug, Copy, Clone)]\n\n struct TestPacketModifier;\n\n\n\n impl PacketModifier for TestPacketModifier {\n\n\n\n fn new(_: Config) -> TestPacketModifier {\n\n TestPacketModifier\n\n }\n\n\n\n fn outgoing(&mut self, data: &[u8]) -> Option<Vec<u8>> {\n\n\n\n assert_eq!([\n\n 0, 0, 0, 3, 70, 111, 111, // Foo\n\n 0, 0, 0, 3, 66, 97, 114 // Bar\n\n ].to_vec(), data);\n\n\n\n // Remove messages\n\n Some(Vec::new())\n", "file_path": "src/test/connection.rs", "rank": 49, "score": 40884.90179687059 }, { "content": "#[test]\n\nfn test_client_reset_events() {\n\n\n\n let mut client = client_init(Config {\n\n .. Config::default()\n\n });\n\n\n\n let id = client.connection().unwrap().id().0;\n\n client.socket().unwrap().mock_receive(vec![\n\n (\"255.1.1.1:5678\", vec![\n\n 1, 2, 3, 4,\n\n (id >> 24) as u8,\n\n (id >> 16) as u8,\n\n (id >> 8) as u8,\n\n id as u8,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0\n\n ])\n\n ]);\n\n\n", "file_path": "src/test/client.rs", "rank": 50, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_receive_empty() {\n\n\n\n let mut q = MessageQueue::new(Config::default());\n\n\n\n // Receive 2 empty messages\n\n q.receive_packet(&[\n\n 0, 0, 0, 0,\n\n 0, 0, 0, 0\n\n ]);\n\n\n\n assert_eq!(messages(&mut q), [b\"\", b\"\"]);\n\n\n\n}\n\n\n", "file_path": "src/test/message_queue.rs", "rank": 51, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_send_and_receive_messages() {\n\n\n\n let mut conn = create_connection(None);\n\n let mut socket = MockSocket::new(conn.local_addr(), 0).unwrap();\n\n let address = conn.peer_addr();\n\n\n\n // Test Message Sending\n\n conn.send(MessageKind::Instant, b\"Foo\".to_vec());\n\n conn.send(MessageKind::Instant, b\"Bar\".to_vec());\n\n conn.send(MessageKind::Reliable, b\"Test\".to_vec());\n\n conn.send(MessageKind::Ordered, b\"Hello\".to_vec());\n\n conn.send(MessageKind::Ordered, b\"World\".to_vec());\n\n\n\n conn.send_packet(&mut socket, &address);\n\n socket.assert_sent(vec![\n\n (\"255.1.1.2:5678\", [\n\n 1, 2, 3, 4,\n\n (conn.id().0 >> 24) as u8,\n\n (conn.id().0 >> 16) as u8,\n\n (conn.id().0 >> 8) as u8,\n", "file_path": "src/test/connection.rs", "rank": 52, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_client_close_by_local() {\n\n\n\n let mut client = client_init(Config::default());\n\n let id = client.connection().unwrap().id().0;\n\n client.socket().unwrap().mock_receive(vec![\n\n (\"255.1.1.1:5678\", vec![\n\n 1, 2, 3, 4,\n\n (id >> 24) as u8,\n\n (id >> 16) as u8,\n\n (id >> 8) as u8,\n\n id as u8,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0\n\n ])\n\n ]);\n\n\n\n assert_eq!(client_events(&mut client), vec![\n\n ClientEvent::Connection\n\n ]);\n", "file_path": "src/test/client.rs", "rank": 53, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_client_without_connection() {\n\n\n\n let mut client = Client::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config::default());\n\n\n\n assert!(client.connect(\"255.1.1.1:5678\").is_ok());\n\n\n\n assert_eq!(client.receive(), Err(TryRecvError::Empty));\n\n\n\n assert!(client.send(false).is_ok());\n\n\n\n assert!(client.disconnect().is_ok());\n\n\n\n}\n\n\n", "file_path": "src/test/client.rs", "rank": 54, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_client_close_by_remote() {\n\n\n\n let mut client = client_init(Config::default());\n\n let id = client.connection().unwrap().id().0;\n\n client.socket().unwrap().mock_receive(vec![\n\n (\"255.1.1.1:5678\", vec![\n\n 1, 2, 3, 4,\n\n (id >> 24) as u8,\n\n (id >> 16) as u8,\n\n (id >> 8) as u8,\n\n id as u8,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0\n\n ])\n\n ]);\n\n\n\n assert_eq!(client_events(&mut client), vec![\n\n ClientEvent::Connection\n\n ]);\n", "file_path": "src/test/client.rs", "rank": 55, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_out_of_order_duplicates() {\n\n\n\n let mut q = MessageQueue::new(Config::default());\n\n\n\n q.receive_packet(&[\n\n 2, 0, 0, 1, 53, // Expected #1\n\n 2, 2, 0, 1, 54, // Expected #3\n\n 2, 2, 0, 1, 55,\n\n 2, 2, 0, 1, 56,\n\n 2, 1, 0, 1, 57, // Expected #2\n\n 2, 4, 0, 1, 58, // Expected #5\n\n 2, 3, 0, 1, 59 // Expected #4\n\n ]);\n\n\n\n assert_eq!(messages(&mut q), [[53], [57], [54], [59], [58]]);\n\n\n\n}\n\n\n", "file_path": "src/test/message_queue.rs", "rank": 56, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_send_and_receive_packet() {\n\n\n\n let mut conn = create_connection(None);\n\n let mut socket = MockSocket::new(conn.local_addr(), 0).unwrap();\n\n let address = conn.peer_addr();\n\n\n\n // Test Initial Packet\n\n conn.send_packet(&mut socket, &address);\n\n socket.assert_sent(vec![(\"255.1.1.2:5678\", [\n\n // protocol id\n\n 1, 2, 3, 4,\n\n\n\n // connection id\n\n (conn.id().0 >> 24) as u8,\n\n (conn.id().0 >> 16) as u8,\n\n (conn.id().0 >> 8) as u8,\n\n conn.id().0 as u8,\n\n\n\n 0, // local sequence number\n\n 0, // remote sequence number\n", "file_path": "src/test/connection.rs", "rank": 57, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_server_reset_events() {\n\n\n\n let mut server = Server::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config::default());\n\n server.listen(\"127.0.0.1:1234\").ok();\n\n\n\n // Accept a incoming connection\n\n server.socket().unwrap().mock_receive(vec![\n\n (\"255.1.1.1:1000\", vec![\n\n 1, 2, 3, 4,\n\n 9, 8, 7, 6,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0\n\n ])\n\n ]);\n\n\n\n // Fetch events from the connections\n\n server.accept_receive().ok();\n\n server.send(false).ok();\n\n\n\n // Shutdown should clear events\n\n server.shutdown().ok();\n\n\n\n // Re-bind and make events accesible again\n\n server.listen(\"127.0.0.1:1234\").ok();\n\n assert!(server_events(&mut server).is_empty());\n\n\n\n}\n\n\n", "file_path": "src/test/server.rs", "rank": 58, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_receive_invalid() {\n\n\n\n let mut q = MessageQueue::new(Config::default());\n\n\n\n // Receive a message with a invalid kind\n\n q.receive_packet(&[\n\n 255, 0, 0, 0\n\n ]);\n\n\n\n assert!(messages(&mut q).is_empty());\n\n\n\n // Receive a message with incomplete header\n\n q.receive_packet(&[\n\n 0, 0\n\n ]);\n\n\n\n q.receive_packet(&[\n\n 0, 0, 0\n\n ]);\n\n\n\n // Receive a message with incomplete data\n\n q.receive_packet(&[\n\n 0, 0, 0, 15, 72, 101, 108, 108, 111 // 15 bytes but only 5 in buffer\n\n ]);\n\n\n\n assert_eq!(messages(&mut q), [b\"Hello\"]);\n\n\n\n}\n\n\n", "file_path": "src/test/message_queue.rs", "rank": 59, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_receive_read() {\n\n\n\n let mut q = MessageQueue::new(Config::default());\n\n let packet = [\n\n // Hello World\n\n 0, 0, 0, 11, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100,\n\n // Hello World\n\n 0, 0, 0, 11, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100,\n\n // Foo\n\n 1, 0, 0, 3, 70, 111, 111,\n\n // Bar\n\n 2, 0, 0, 3, 66, 97, 114,\n\n // Hello World\n\n 0, 0, 0, 11, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100\n\n ].to_vec();\n\n\n\n q.receive_packet(&packet[..]);\n\n\n\n assert_eq!(messages(&mut q), [\n\n b\"Hello World\".to_vec(),\n\n b\"Hello World\".to_vec(),\n\n b\"Foo\".to_vec(),\n\n b\"Bar\".to_vec(),\n\n b\"Hello World\".to_vec()\n\n ]);\n\n\n\n}\n\n\n", "file_path": "src/test/message_queue.rs", "rank": 60, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_receive_invalid_packets() {\n\n\n\n let mut conn = create_connection(None);\n\n\n\n // Empty packet\n\n conn.receive_packet([].to_vec());\n\n\n\n // Garbage packet\n\n conn.receive_packet([\n\n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14\n\n\n\n ].to_vec());\n\n\n\n}\n\n\n", "file_path": "src/test/connection.rs", "rank": 61, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_server_connection_loss() {\n\n\n\n let mut server = Server::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config {\n\n connection_drop_threshold: Duration::from_millis(100),\n\n .. Config::default()\n\n });\n\n server.listen(\"127.0.0.1:1234\").ok();\n\n\n\n // Accept a incoming connection\n\n server.socket().unwrap().mock_receive(vec![\n\n (\"255.1.1.1:1000\", vec![\n\n 1, 2, 3, 4,\n\n 9, 8, 7, 6,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0\n\n ])\n\n ]);\n\n\n\n assert_eq!(server_events(&mut server), vec![\n", "file_path": "src/test/server.rs", "rank": 62, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_client_connection_failure() {\n\n\n\n let mut client = client_init(Config {\n\n connection_init_threshold: Duration::from_millis(100),\n\n .. Config::default()\n\n });\n\n\n\n // Let the connection attempt time out\n\n thread::sleep(Duration::from_millis(200));\n\n\n\n let events = client_events(&mut client);\n\n assert_eq!(events, vec![ClientEvent::ConnectionFailed]);\n\n\n\n client.send(false).ok();\n\n client.send(false).ok();\n\n\n\n // We expect no additional packets to be send once the connection failed\n\n client.socket().unwrap().assert_sent_none();\n\n\n\n}\n\n\n", "file_path": "src/test/client.rs", "rank": 63, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_debug_fmt() {\n\n\n\n let mut q = MessageQueue::new(Config::default());\n\n q.send(MessageKind::Instant, b\"Hello World\".to_vec());\n\n\n\n // Check debug fmt support\n\n assert_ne!(format!(\"{:?}\", q), \"\");\n\n\n\n}\n\n\n", "file_path": "src/test/message_queue.rs", "rank": 64, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_in_order_duplicates() {\n\n\n\n let mut q = MessageQueue::new(Config::default());\n\n\n\n q.receive_packet(&[\n\n 2, 0, 0, 1, 53, // Expected #1\n\n 2, 1, 0, 1, 54, // Expected #2\n\n 2, 1, 0, 1, 55,\n\n 2, 1, 0, 1, 56,\n\n 2, 2, 0, 1, 57, // Expected #3\n\n 2, 2, 0, 1, 58,\n\n 2, 3, 0, 1, 59 // Expected #4\n\n ]);\n\n\n\n assert_eq!(messages(&mut q), [[53], [54], [57], [59]]);\n\n\n\n}\n\n\n", "file_path": "src/test/message_queue.rs", "rank": 65, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_server_connection_close() {\n\n\n\n let mut server = Server::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config::default());\n\n server.listen(\"127.0.0.1:1234\").ok();\n\n\n\n // Accept incoming connections\n\n server.socket().unwrap().mock_receive(vec![\n\n (\"255.1.1.1:1000\", vec![\n\n 1, 2, 3, 4,\n\n 9, 8, 7, 6,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0\n\n ]),\n\n (\"255.1.1.2:2000\", vec![\n\n 1, 2, 3, 4,\n\n 5, 5, 1, 1,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0\n", "file_path": "src/test/server.rs", "rank": 66, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_server_listen_shutdown() {\n\n\n\n let mut server = Server::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config::default());\n\n\n\n assert!(server.listen(\"127.0.0.1:1234\").is_ok());\n\n\n\n assert_eq!(server.listen(\"127.0.0.1:1234\").unwrap_err().kind(), ErrorKind::AlreadyExists);\n\n assert!(server.socket().is_ok());\n\n\n\n assert!(server.shutdown().is_ok());\n\n assert_eq!(server.socket().unwrap_err().kind(), ErrorKind::NotConnected);\n\n\n\n assert_eq!(server.shutdown().unwrap_err().kind(), ErrorKind::NotConnected);\n\n\n\n}\n\n\n", "file_path": "src/test/server.rs", "rank": 67, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_send_write() {\n\n\n\n let mut q = MessageQueue::new(Config::default());\n\n\n\n // Filled from quota\n\n q.send(MessageKind::Instant, b\"Hello World\".to_vec());\n\n q.send(MessageKind::Instant, b\"Hello World\".to_vec());\n\n\n\n // Added by filling buffer\n\n q.send(MessageKind::Instant, b\"Hello World\".to_vec());\n\n\n\n // Put into packet 2\n\n q.send(MessageKind::Instant, b\"Hello World2\".to_vec());\n\n q.send(MessageKind::Instant, b\"Hello World2\".to_vec());\n\n\n\n // Filled from quota\n\n q.send(MessageKind::Reliable, b\"Foo\".to_vec());\n\n\n\n // Put into packet 2 by quota\n\n q.send(MessageKind::Reliable, b\"Foo2\".to_vec());\n", "file_path": "src/test/message_queue.rs", "rank": 68, "score": 39758.8705694476 }, { "content": "#[test]\n\nfn test_client_connection_success() {\n\n\n\n let mut client = client_init(Config {\n\n .. Config::default()\n\n });\n\n\n\n // Mock the receival of the first server packet which acknowledges the client\n\n let id = client.connection().unwrap().id().0;\n\n client.socket().unwrap().mock_receive(vec![\n\n (\"255.1.1.1:5678\", vec![\n\n 1, 2, 3, 4,\n\n (id >> 24) as u8,\n\n (id >> 16) as u8,\n\n (id >> 8) as u8,\n\n id as u8,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0\n\n ])\n\n ]);\n", "file_path": "src/test/client.rs", "rank": 69, "score": 39758.8705694476 }, { "content": "#[test]\n\n#[cfg(target_os = \"linux\")]\n\nfn test_server_flush_auto_delay() {\n\n\n\n let mut server = Server::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config::default());\n\n server.listen(\"127.0.0.1:1234\").ok();\n\n\n\n let start = Instant::now();\n\n for _ in 0..5 {\n\n server.accept_receive().ok();\n\n server.send(true).ok();\n\n }\n\n assert_millis_since!(start, 167, 33);\n\n\n\n}\n\n\n", "file_path": "src/test/server.rs", "rank": 70, "score": 38718.58275569182 }, { "content": "#[test]\n\nfn test_client_connect_reset_close() {\n\n\n\n let mut client = Client::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config::default());\n\n\n\n assert!(client.connect(\"255.1.1.1:5678\").is_ok());\n\n\n\n assert_eq!(client.connect(\"255.1.1.1:5678\").unwrap_err().kind(), ErrorKind::AlreadyExists);\n\n assert!(client.socket().is_ok());\n\n\n\n assert!(client.reset().is_ok());\n\n assert!(client.socket().is_ok());\n\n\n\n assert!(client.disconnect().is_ok());\n\n assert_eq!(client.socket().unwrap_err().kind(), ErrorKind::NotConnected);\n\n\n\n assert_eq!(client.disconnect().unwrap_err().kind(), ErrorKind::NotConnected);\n\n assert_eq!(client.reset().unwrap_err().kind(), ErrorKind::NotConnected);\n\n\n\n}\n\n\n", "file_path": "src/test/client.rs", "rank": 71, "score": 38718.58275569182 }, { "content": "#[test]\n\nfn test_receive_read_long() {\n\n\n\n let mut q = MessageQueue::new(Config::default());\n\n let packet = [\n\n 0, 0, 1, 188, 76, 111, 114, 101, 109, 32, 105, 112, 115, 117, 109,\n\n 32, 100, 111, 108, 111, 114, 32, 115, 105, 116, 32, 97, 109, 101,\n\n 116, 44, 32, 99, 111, 110, 115, 101, 99, 116, 101, 116, 117, 114,\n\n 32, 97, 100, 105, 112, 105, 115, 99, 105, 110, 103, 32, 101, 108,\n\n 105, 116, 44, 32, 115, 101, 100, 32, 100, 111, 32, 101, 105, 117,\n\n 115, 109, 111, 100, 32, 116, 101, 109, 112, 111, 114, 32, 105, 110,\n\n 99, 105, 100, 105, 100, 117, 110, 116, 32, 117, 116, 32, 108, 97,\n\n 98, 111, 114, 101, 32, 101, 116, 32, 100, 111, 108, 111, 114, 101,\n\n 32, 109, 97, 103, 110, 97, 32, 97, 108, 105, 113, 117, 97, 46, 32,\n\n 85, 116, 32, 101, 110, 105, 109, 32, 97, 100, 32, 109, 105, 110,\n\n 105, 109, 32, 118, 101, 110, 105, 97, 109, 44, 32, 113, 117, 105,\n\n 115, 32, 110, 111, 115, 116, 114, 117, 100, 32, 101, 120, 101, 114,\n\n 99, 105, 116, 97, 116, 105, 111, 110, 32, 117, 108, 108, 97, 109,\n\n 99, 111, 32, 108, 97, 98, 111, 114, 105, 115, 32, 110, 105, 115,\n\n 105, 32, 117, 116, 32, 97, 108, 105, 113, 117, 105, 112, 32, 101,\n\n 120, 32, 101, 97, 32, 99, 111, 109, 109, 111, 100, 111, 32, 99,\n", "file_path": "src/test/message_queue.rs", "rank": 72, "score": 38718.58275569182 }, { "content": "#[test]\n\nfn test_packet_lost_write() {\n\n\n\n let mut q = MessageQueue::new(Config::default());\n\n\n\n q.lost_packet(&[\n\n // Hello World2\n\n 0, 0, 0, 12, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 50,\n\n // Hello World2\n\n 0, 0, 0, 12, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 50,\n\n // Foo2\n\n 1, 0, 0, 4, 70, 111, 111, 50,\n\n // Bar2\n\n 2, 1, 0, 4, 66, 97, 114, 50,\n\n // Foo More\n\n 1, 0, 0, 8, 70, 111, 111, 32, 77, 111, 114, 101\n\n ]);\n\n\n\n // Send some more messages\n\n q.send(MessageKind::Instant, b\"Hello World\".to_vec());\n\n q.send(MessageKind::Reliable, b\"Foo5\".to_vec());\n", "file_path": "src/test/message_queue.rs", "rank": 73, "score": 38718.58275569182 }, { "content": "#[test]\n\nfn test_receive_packet_ack_overflow() {\n\n\n\n let mut conn = create_connection(None);\n\n\n\n // Receive more packets than the ack queue can hold\n\n for i in 0..33 {\n\n conn.receive_packet([\n\n 1, 2, 3, 4,\n\n 0, 0, 0, 0,\n\n i,\n\n 0,\n\n 0, 0, 0, 0\n\n\n\n ].to_vec());\n\n }\n\n\n\n // Verify ack bit field\n\n let mut socket = MockSocket::new(conn.local_addr(), 0).unwrap();\n\n let address = conn.peer_addr();\n\n\n", "file_path": "src/test/connection.rs", "rank": 74, "score": 38718.58275569182 }, { "content": "#[test]\n\nfn test_send_sequence_wrap_around() {\n\n\n\n let mut conn = create_connection(None);\n\n let mut socket = MockSocket::new(conn.local_addr(), 0).unwrap();\n\n let address = conn.peer_addr();\n\n\n\n for i in 0..256 {\n\n\n\n conn.send_packet(&mut socket, &address);\n\n\n\n socket.assert_sent(vec![(\"255.1.1.2:5678\", [\n\n // protocol id\n\n 1, 2, 3, 4,\n\n\n\n // connection id\n\n (conn.id().0 >> 24) as u8,\n\n (conn.id().0 >> 16) as u8,\n\n (conn.id().0 >> 8) as u8,\n\n conn.id().0 as u8,\n\n\n", "file_path": "src/test/connection.rs", "rank": 75, "score": 38718.58275569182 }, { "content": "#[test]\n\n#[cfg(target_os = \"linux\")]\n\nfn test_server_auto_delay_with_load() {\n\n\n\n let mut server = Server::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config::default());\n\n server.listen(\"127.0.0.1:1234\").ok();\n\n\n\n // Without load\n\n let start = Instant::now();\n\n for _ in 0..10 {\n\n server.accept_receive().ok();\n\n server.send(true).ok();\n\n }\n\n\n\n assert_millis_since!(start, 330, 16);\n\n\n\n // With load\n\n let start = Instant::now();\n\n for _ in 0..10 {\n\n server.accept_receive().ok();\n\n thread::sleep(Duration::from_millis(10));\n\n server.send(true).ok();\n", "file_path": "src/test/server.rs", "rank": 76, "score": 38718.58275569182 }, { "content": "#[test]\n\n#[cfg(target_os = \"linux\")]\n\nfn test_client_flush_auto_delay() {\n\n\n\n let mut client = Client::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config::default());\n\n client.connect(\"255.1.1.1:5678\").ok();\n\n\n\n let start = Instant::now();\n\n for _ in 0..5 {\n\n client.receive().ok();\n\n client.send(true).ok();\n\n }\n\n assert_millis_since!(start, 167, 33);\n\n\n\n}\n\n\n", "file_path": "src/test/client.rs", "rank": 77, "score": 38718.58275569182 }, { "content": "#[test]\n\nfn test_client_flush_without_delay() {\n\n\n\n let mut client = Client::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config::default());\n\n client.connect(\"255.1.1.1:5678\").ok();\n\n\n\n let start = Instant::now();\n\n for _ in 0..5 {\n\n client.receive().ok();\n\n client.send(false).ok();\n\n }\n\n assert_millis_since!(start, 0, 16);\n\n\n\n}\n\n\n", "file_path": "src/test/client.rs", "rank": 78, "score": 38718.58275569182 }, { "content": "#[test]\n\nfn test_server_flow_without_connections() {\n\n\n\n let mut server = Server::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config::default());\n\n\n\n assert!(server.listen(\"127.0.0.1:1234\").is_ok());\n\n\n\n assert_eq!(server.accept_receive(), Err(TryRecvError::Empty));\n\n\n\n assert!(server.send(false).is_ok());\n\n\n\n assert!(server.shutdown().is_ok());\n\n\n\n}\n\n\n", "file_path": "src/test/server.rs", "rank": 79, "score": 38718.58275569182 }, { "content": "#[test]\n\nfn test_client_connection_loss_and_reconnect() {\n\n\n\n let mut client = client_init(Config {\n\n connection_drop_threshold: Duration::from_millis(100),\n\n .. Config::default()\n\n });\n\n\n\n // Mock the receival of the first server packet which acknowledges the client\n\n let id = client.connection().unwrap().id().0;\n\n client.socket().unwrap().mock_receive(vec![\n\n (\"255.1.1.1:5678\", vec![\n\n 1, 2, 3, 4,\n\n (id >> 24) as u8,\n\n (id >> 16) as u8,\n\n (id >> 8) as u8,\n\n id as u8,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0\n\n ])\n", "file_path": "src/test/client.rs", "rank": 80, "score": 38718.58275569182 }, { "content": "#[test]\n\n#[cfg(target_os = \"linux\")]\n\nfn test_client_auto_delay_with_load() {\n\n\n\n let mut client = Client::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config::default());\n\n client.connect(\"255.1.1.1:5678\").ok();\n\n\n\n // Without load\n\n let start = Instant::now();\n\n for _ in 0..10 {\n\n client.receive().ok();\n\n client.send(true).ok();\n\n }\n\n\n\n assert_millis_since!(start, 330, 16);\n\n\n\n // With load\n\n let start = Instant::now();\n\n for _ in 0..10 {\n\n client.receive().ok();\n\n thread::sleep(Duration::from_millis(10));\n\n client.send(true).ok();\n", "file_path": "src/test/client.rs", "rank": 81, "score": 38718.58275569182 }, { "content": "#[test]\n\nfn test_receive_read_out_of_order() {\n\n\n\n let mut q = MessageQueue::new(Config::default());\n\n\n\n // Receive one out of order(#1) \"World\" message\n\n q.receive_packet(&[\n\n 2, 1, 0, 5, 87, 111, 114, 108, 100\n\n ]);\n\n\n\n // We expect no message yet\n\n assert!(messages(&mut q).is_empty());\n\n\n\n // Receive one out of order(#3) \"order!\" message\n\n q.receive_packet(&[\n\n 2, 3, 0, 6, 111, 114, 100, 101, 114, 33\n\n ]);\n\n\n\n // We still expect no message yet\n\n assert!(messages(&mut q).is_empty());\n\n\n", "file_path": "src/test/message_queue.rs", "rank": 82, "score": 38718.58275569182 }, { "content": "#[test]\n\nfn test_send_write_long() {\n\n\n\n let msg = b\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do \\\n\n eiusmod tempor incididunt ut labore et dolore magna aliqua. \\\n\n Ut enim ad minim veniam, quis nostrud exercitation ullamco \\\n\n laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure \\\n\n dolor in reprehenderit in voluptate velit esse cillum dolore eu \\\n\n fugiat nulla pariatur. Excepteur sint occaecat cupidatat non \\\n\n proident, sunt in culpa qui officia deserunt mollit anim id est \\\n\n laborum\";\n\n\n\n let mut q = MessageQueue::new(Config::default());\n\n q.send(MessageKind::Instant, msg.to_vec());\n\n\n\n let mut buffer = Vec::new();\n\n q.send_packet(&mut buffer, 1400);\n\n\n\n assert_eq!(buffer, [\n\n 0, 0, 1, 188, 76, 111, 114, 101, 109, 32, 105, 112, 115, 117, 109,\n\n 32, 100, 111, 108, 111, 114, 32, 115, 105, 116, 32, 97, 109, 101,\n", "file_path": "src/test/message_queue.rs", "rank": 83, "score": 38718.58275569182 }, { "content": "#[test]\n\nfn test_server_connection_address_remap() {\n\n\n\n let mut server = Server::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config::default());\n\n server.listen(\"127.0.0.1:1234\").ok();\n\n\n\n // Accept a incoming connection\n\n server.socket().unwrap().mock_receive(vec![\n\n (\"255.1.1.1:1000\", vec![\n\n 1, 2, 3, 4,\n\n 9, 8, 7, 6,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0\n\n ])\n\n ]);\n\n\n\n assert_eq!(server_events(&mut server), vec![\n\n ServerEvent::Connection(ConnectionID(151521030))\n\n ]);\n\n\n", "file_path": "src/test/server.rs", "rank": 84, "score": 38718.58275569182 }, { "content": "#[test]\n\nfn test_server_flush_without_delay() {\n\n\n\n let mut server = Server::<MockSocket, BinaryRateLimiter, NoopPacketModifier>::new(Config::default());\n\n server.listen(\"127.0.0.1:1234\").ok();\n\n\n\n let start = Instant::now();\n\n for _ in 0..5 {\n\n server.accept_receive().ok();\n\n server.send(false).ok();\n\n }\n\n assert_millis_since!(start, 0, 16);\n\n\n\n}\n\n\n", "file_path": "src/test/server.rs", "rank": 85, "score": 38718.58275569182 }, { "content": "#[test]\n\nfn test_client_connection_ignore_non_peer() {\n\n\n\n let mut client = client_init(Config {\n\n connection_init_threshold: Duration::from_millis(100),\n\n .. Config::default()\n\n });\n\n\n\n // We expect the client to ignore any packets from peers other than the\n\n // server it is connected to\n\n let id = client.connection().unwrap().id().0;\n\n client.socket().unwrap().mock_receive(vec![\n\n (\"255.1.1.1:5679\", vec![\n\n 1, 2, 3, 4,\n\n (id >> 24) as u8,\n\n (id >> 16) as u8,\n\n (id >> 8) as u8,\n\n id as u8,\n\n 0,\n\n 0,\n\n 0, 0, 0, 0\n\n ])\n\n ]);\n\n\n\n assert_eq!(client_events(&mut client), vec![]);\n\n\n\n}\n\n\n", "file_path": "src/test/client.rs", "rank": 86, "score": 37754.60395420192 }, { "content": "#[test]\n\nfn test_receive_ordered_decoding_wrap_around() {\n\n\n\n let mut q = MessageQueue::new(Config::default());\n\n for i in 0..4096 {\n\n\n\n q.receive_packet(&[\n\n 2 | ((i & 0x0F00) >> 4) as u8, (i as u8), 0, 2, (i >> 8) as u8, i as u8\n\n ]);\n\n\n\n assert_eq!(messages(&mut q), [[(i >> 8) as u8, i as u8]]);\n\n\n\n }\n\n\n\n // Should now expect order=0 again\n\n q.receive_packet(&[\n\n 2, 0, 0, 2, 0, 0\n\n ]);\n\n assert_eq!(messages(&mut q), [[0, 0]]);\n\n\n\n}\n\n\n", "file_path": "src/test/message_queue.rs", "rank": 87, "score": 36858.83489265856 }, { "content": "#[test]\n\nfn test_receive_ordered_encoding_wrap_around() {\n\n\n\n let mut q = MessageQueue::new(Config::default());\n\n for i in 0..4096 {\n\n\n\n q.send(MessageKind::Ordered, [(i >> 8) as u8, i as u8].to_vec());\n\n\n\n let mut buffer = Vec::new();\n\n q.send_packet(&mut buffer, 64);\n\n assert_eq!(buffer, [\n\n 2 | ((i & 0x0F00) >> 4) as u8, (i as u8), 0, 2, (i >> 8) as u8, i as u8].to_vec()\n\n );\n\n\n\n }\n\n\n\n // Should now write order=0 again\n\n q.send(MessageKind::Ordered, [0, 0].to_vec());\n\n\n\n let mut buffer = Vec::new();\n\n q.send_packet(&mut buffer, 64);\n\n assert_eq!(buffer, [2, 0, 0, 2, 0, 0].to_vec());\n\n\n\n}\n\n\n", "file_path": "src/test/message_queue.rs", "rank": 88, "score": 36858.83489265856 }, { "content": " /// Values must be in the range of `0.0` to `1.0` where `0.25` would be a\n\n /// quarter of the tick's sleep time.\n\n ///\n\n /// Example: For a `send_rate` of `30` with a maximum sleep time of `33.33`\n\n /// milliseconds, a `tick_overflow_recovery_rate` value of `0.5` would\n\n /// allow up to `16.66` milliseconds of sleep to be skipped.\n\n ///\n\n /// Values smaller than `0.0` or bigger than `1.0` will have no effect.\n\n ///\n\n /// Default is `1.0`.\n\n pub tick_overflow_recovery_rate: f32\n\n\n\n}\n\n\n\nimpl Default for Config {\n\n\n\n fn default() -> Config {\n\n Config {\n\n send_rate: 30,\n\n protocol_header: [1, 2, 3, 4],\n", "file_path": "src/shared/config.rs", "rank": 89, "score": 34049.100006275665 }, { "content": " /// Maximum time in milliseconds to wait for remote confirmation after\n\n /// programmatically closing a connection. Default is `150`.\n\n pub connection_closing_threshold: Duration,\n\n\n\n /// The percent of available packet bytes to use when serializing\n\n /// `MessageKind::Instant` into a packet via a `MessageQueue`.\n\n pub message_quota_instant: f32,\n\n\n\n /// The percent of available packet bytes to use when serializing\n\n /// `MessageKind::Reliable` into a packet via a `MessageQueue`.\n\n pub message_quota_reliable: f32,\n\n\n\n /// The percent of available packet bytes to use when serializing\n\n /// `MessageKind::Ordered` into a packet via a `MessageQueue`.\n\n pub message_quota_ordered: f32,\n\n\n\n /// Whether to keep track of ticks which exceed their maximum running time\n\n /// and speed up successive ticks in order to keep the desired target\n\n /// `send_rate` stable.\n\n ///\n", "file_path": "src/shared/config.rs", "rank": 90, "score": 34046.59921402105 }, { "content": " /// Each tick has a limit of the number of milliseconds in can take before\n\n /// the `send_rate` drops below the specified ticks per second\n\n /// target (`1000 / send_rate` milliseconds). Ticks which fall below this\n\n /// threshold will normally sleep for the remaining amount of time.\n\n ///\n\n /// Ticks which exceed this threshold will normally cause the `send_rate`\n\n /// to drop below the target; however, with `tick_overflow_recovery`\n\n /// enabled any tick which falls below the threshold will give up some of\n\n /// its remaining sleep time in order to allow the `send_rate` to catch up\n\n /// again.\n\n ///\n\n /// How much of each tick's sleep time is used for speedup purposes is\n\n /// determined by the value of `tick_overflow_recovery`.\n\n ///\n\n /// Default is `true`.\n\n pub tick_overflow_recovery: bool,\n\n\n\n /// Determines how much of each tick's sleep time may be used to reduce the\n\n /// current tick overflow time in order to smooth out the `send_rate`.\n\n ///\n", "file_path": "src/shared/config.rs", "rank": 91, "score": 34042.94708190082 }, { "content": "// Copyright (c) 2015-2017 Ivo Wetzel\n\n\n\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n\n// option. This file may not be copied, modified, or distributed\n\n// except according to those terms.\n\n\n\n\n\n// STD Dependencies -----------------------------------------------------------\n\nuse std::time::Duration;\n\n\n\n\n\n/// Structure defining connection and message configuration options.\n\n#[derive(Copy, Clone, Debug, PartialEq)]\n\npub struct Config {\n\n\n\n /// Number of packets send per second. Default is `30`.\n\n pub send_rate: u64,\n\n\n", "file_path": "src/shared/config.rs", "rank": 92, "score": 34041.098278179554 }, { "content": " packet_max_size: 1400,\n\n packet_drop_threshold: Duration::from_millis(1000),\n\n connection_init_threshold: Duration::from_millis(100),\n\n connection_drop_threshold: Duration::from_millis(1000),\n\n connection_closing_threshold: Duration::from_millis(150),\n\n message_quota_instant: 60.0,\n\n message_quota_reliable: 20.0,\n\n message_quota_ordered: 20.0,\n\n tick_overflow_recovery: true,\n\n tick_overflow_recovery_rate: 1.0\n\n }\n\n }\n\n\n\n}\n\n\n", "file_path": "src/shared/config.rs", "rank": 93, "score": 34038.90829515442 }, { "content": " /// Maximum bytes that can be received / send in one packet. Default\n\n /// `1400`.\n\n pub packet_max_size: usize,\n\n\n\n /// 32-Bit Protocol ID used to identify UDP related packets. Default is\n\n /// `[1, 2, 3, 4]`.\n\n pub protocol_header: [u8; 4],\n\n\n\n /// Maximum roundtrip-time in milliseconds before a packet is considered\n\n /// lost. Default is `1000`.\n\n pub packet_drop_threshold: Duration,\n\n\n\n /// Maximum time in milliseconds until the first packet must be received\n\n /// before a connection attempt fails. Default is `100`.\n\n pub connection_init_threshold: Duration,\n\n\n\n /// Maximum time in milliseconds between any two packets before the\n\n /// connection gets dropped. Default is `1000`.\n\n pub connection_drop_threshold: Duration,\n\n\n", "file_path": "src/shared/config.rs", "rank": 94, "score": 34036.4653740223 }, { "content": "// Static Helpers -------------------------------------------------------------\n\nfn order_is_more_recent(a: u16, b: u16) -> bool {\n\n (a > b) && (a - b <= MAX_ORDER_ID / 2)\n\n || (b > a) && (b - a > MAX_ORDER_ID / 2)\n\n}\n\n\n", "file_path": "src/shared/message_queue.rs", "rank": 95, "score": 32805.181867537656 }, { "content": "fn messages_from_packet(packet: &[u8]) -> Vec<Message> {\n\n\n\n let available = packet.len();\n\n let mut index = 0;\n\n let mut messages = Vec::new();\n\n\n\n // Consume as long as message headers can be present\n\n while index < available && available - index >= MESSAGE_HEADER_BYTES {\n\n\n\n // Upper 4 bits of kind are bits 9..11 of order\n\n let order_high = ((packet[index] & 0xF0) as u16) << 4;\n\n let order_low = packet[index + 1] as u16;\n\n\n\n // Byte 2 is the size\n\n let size_high = (packet[index + 2] as u16) << 8;\n\n let size = size_high | packet[index + 3] as u16;\n\n\n\n // Lower 4 bits of byte 0 are the MessageKind\n\n let kind = match packet[index] & 0x0F {\n\n 0 => Some(MessageKind::Instant),\n", "file_path": "src/shared/message_queue.rs", "rank": 96, "score": 32556.855098173364 }, { "content": "// Copyright (c) 2015-2017 Ivo Wetzel\n\n\n\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n\n// option. This file may not be copied, modified, or distributed\n\n// except according to those terms.\n\n\n\n// STD Dependencies -----------------------------------------------------------\n\nuse std::fmt;\n\n\n\n\n\n// Internal Dependencies ------------------------------------------------------\n\nuse super::super::Config;\n\n\n\n\n\n/// Trait describing a network congestion avoidance algorithm.\n", "file_path": "src/traits/rate_limiter.rs", "rank": 97, "score": 32313.664604644215 } ]
Rust
pkmnapi-db/src/pic/mod.rs
kevinselwyn/pkmnapi
170e6b6c9a74e85c377137bc086793898c415125
mod bitplane; mod bitstream; mod encoding_method; pub use encoding_method::EncodingMethod as PicEncodingMethod; use crate::error::{self, Result}; use bitplane::*; use bitstream::*; use image::{self, DynamicImage, ImageBuffer, ImageFormat, Luma}; #[derive(Clone, Debug, PartialEq)] pub struct Pic { pub width: u8, pub height: u8, pub pixels: Vec<u8>, pub bytes: usize, pub encoding_method: PicEncodingMethod, } impl Pic { pub fn new(data: &[u8]) -> Result<Self> { let mut bitstream = Bitstream::from(data); let width = bitstream.get(4) as u8; let height = bitstream.get(4) as u8; let primary_buffer = bitstream.get(1) as u8; let mut bitplane_1 = Pic::decode_bitplane(width, height, &mut bitstream); let encoding_method = PicEncodingMethod::from( { if bitstream.get(1) == 0x00 { 0x01 } else { if bitstream.get(1) == 0x00 { 0x02 } else { 0x03 } } }, primary_buffer, ); let mut bitplane_0 = Pic::decode_bitplane(width, height, &mut bitstream); match encoding_method { PicEncodingMethod::ONE(_) => { bitplane_1 = bitplane_1.delta_decode(width as usize * 8); bitplane_0 = bitplane_0.delta_decode(width as usize * 8); } PicEncodingMethod::TWO(_) => { bitplane_1 = bitplane_1.delta_decode(width as usize * 8); bitplane_0 = bitplane_0.clone() ^ bitplane_1.clone(); } PicEncodingMethod::THREE(_) => { bitplane_1 = bitplane_1.delta_decode(width as usize * 8); bitplane_0 = bitplane_0.delta_decode(width as usize * 8); bitplane_0 = bitplane_0.clone() ^ bitplane_1.clone(); } }; let pixels = { if encoding_method.value() == 0x00 { (bitplane_0 << 0x01) | bitplane_1 } else { (bitplane_1 << 0x01) | bitplane_0 } }; let bytes = ((bitstream.bits as f32) / 8.0).ceil() as usize; Ok(Pic { width, height, pixels: pixels.data, bytes, encoding_method, }) } pub fn encode(&self, encoding_method: PicEncodingMethod) -> Vec<u8> { let width = self.width; let height = self.height; let (mut bitplane_0b, mut bitplane_1b) = if encoding_method.value() == 0x00 { let pixel_bitplane = Bitplane::from(self.pixels.to_vec()); ( (pixel_bitplane.clone() & 0x02) >> 0x01, pixel_bitplane.clone() & 0x01, ) } else { let pixel_bitplane = Bitplane::from(self.pixels.to_vec()); ( pixel_bitplane.clone() & 0x01, (pixel_bitplane.clone() & 0x02) >> 0x01, ) }; let (bitplane_0a, bitplane_1a) = match encoding_method { PicEncodingMethod::ONE(_) => { let bitplane_1a = bitplane_1b.delta_encode(width as usize * 8); let bitplane_0a = bitplane_0b.delta_encode(width as usize * 8); (bitplane_0a, bitplane_1a) } PicEncodingMethod::TWO(_) => { let bitplane_1a = bitplane_1b.delta_encode(width as usize * 8); let bitplane_0a = bitplane_0b.clone() ^ bitplane_1b.clone(); (bitplane_0a, bitplane_1a) } PicEncodingMethod::THREE(_) => { let bitplane_1a = bitplane_1b.delta_encode(width as usize * 8); let bitplane_0a = bitplane_0b.delta_encode(width as usize * 8); let bitplane_0a = bitplane_0a.clone() ^ bitplane_1a.clone(); (bitplane_0a, bitplane_1a) } }; let bitplane_0a_raw = Pic::encode_bitplane(width, height, bitplane_0a); let bitplane_1a_raw = Pic::encode_bitplane(width, height, bitplane_1a); let data_bits: Vec<u8> = [ (0..=3) .map(|i| (width & (i << (3 - i))) >> (3 - i)) .collect(), (0..=3) .map(|i| (height & (i << (3 - i))) >> (3 - i)) .collect(), vec![encoding_method.value()], bitplane_1a_raw, encoding_method.to_vec(), bitplane_0a_raw, ] .concat(); let data_bytes = ((data_bits.len() as f32) / 8.0).ceil() as usize; let extra_bits = (data_bytes * 8) - data_bits.len(); let data_bits = [data_bits, vec![0x00; extra_bits]].concat(); let data: Vec<u8> = (0..data_bytes) .map(|i| { let index = i * 8; data_bits[index..(index + 8)] .iter() .enumerate() .map(|(i, bit)| bit << (7 - i)) .fold(0, |acc, val| acc | val) }) .collect(); data } fn from(data: Vec<u8>, format: ImageFormat) -> Result<Self> { let raw = match image::load_from_memory_with_format(&data, format) { Ok(img) => img, Err(_) => return Err(error::Error::PicCouldNotRead), }; let img = match raw.as_luma8() { Some(img) => img, None => return Err(error::Error::PicCouldNotRead), }; if img.width() % 8 != 0 || img.height() % 8 != 0 { return Err(error::Error::PicWrongSize); } let width = ((img.width() as f32) / 8.0) as u8; let height = ((img.height() as f32) / 8.0) as u8; let pixels: Vec<u8> = img .enumerate_pixels() .map(|(_, _, pixel)| { let pixel = 3 - (((pixel.0[0] as f32) / 85.0) as u8); pixel }) .collect(); let encoding_method = PicEncodingMethod::from(0x01, 0x00); Ok(Pic { width, height, pixels, bytes: 0, encoding_method, }) } pub fn from_png(data: Vec<u8>) -> Result<Self> { Pic::from(data, ImageFormat::Png) } pub fn from_jpeg(data: Vec<u8>) -> Result<Self> { Pic::from(data, ImageFormat::Jpeg) } pub fn decode_bitplane(width: u8, height: u8, bitstream: &mut Bitstream) -> Bitplane { let mut pairs: Vec<u8> = vec![]; let mut packet_type = bitstream.get(1); loop { if pairs.len() >= (width as u32 * height as u32 * 32) as usize { break; } if packet_type == 0x00 { let (length, bits) = bitstream.get_until_zero(); let value = bitstream.get(bits); let run = length + value + 1; for _ in 0..run { pairs.push(0x00); } packet_type = 0x01; } else { loop { if pairs.len() >= (width as u32 * height as u32 * 32) as usize { break; } let pair = bitstream.get(2); if pair == 0x00 { break; } pairs.push(pair as u8); } packet_type = 0x00; } } let mut bitplane = vec![0x00; pairs.len() * 2]; pairs.iter().enumerate().for_each(|(i, pair)| { let x = (i / (height as usize * 8)) * 2; let y = i % (height as usize * 8); let new_i = (y * (height as usize * 8)) + x; bitplane[new_i] = (pair & 0x02) >> 0x01; bitplane[new_i + 1] = pair & 0x01; }); Bitplane::from(bitplane) } pub fn encode_bitplane(width: u8, height: u8, bitplane: Bitplane) -> Vec<u8> { let mut output = vec![]; let pixels: Vec<usize> = (0..(width * 8)) .step_by(2) .map(|x| { (0..((height as usize) * 8)) .map(move |y| (y * ((height as usize) * 8)) + (x as usize)) }) .flatten() .collect(); let mut pairs = pixels .into_iter() .map(|i| (bitplane.data[i] << 0x01) | bitplane.data[i + 1]) .peekable(); let mut packet_type = match pairs.peek() { Some(&chunk) if chunk == 0x00 => 0x00, _ => 0x01, }; output.push(packet_type); loop { if pairs.peek() == None { break; } if packet_type == 0x00 { let mut output_data = vec![]; let run = { let mut run = 0; while pairs.peek() == Some(&0x00) { pairs.next(); run += 1; } run as i32 }; let bits = if run == 0x01 { 1 } else { (run as f32 + 1.0).log2().floor() as u32 }; let value = (run + 1) & !(1 << bits); let length = run - value - 1; (0..bits).for_each(|i| { let bit = ((length & (0x01 << (bits - i - 1))) >> (bits - i - 1)) as u8; output_data.push(bit); }); (0..bits).for_each(|i| { let bit = ((value & (0x01 << (bits - i - 1))) >> (bits - i - 1)) as u8; output_data.push(bit); }); output.append(&mut output_data); packet_type = 0x01; } else { let mut output_data = vec![]; while pairs.peek() != Some(&0x00) { let pair = pairs.next().unwrap(); output_data.push((pair & 0x02) >> 0x01); output_data.push(pair & 0x01); if pairs.peek() == None { break; } } output_data.push(0x00); output_data.push(0x00); output.append(&mut output_data); packet_type = 0x00; } } output } fn to_img(&self, format: ImageFormat, mirror: bool) -> Result<Vec<u8>> { let width = self.width as u32 * 8; let height = self.height as u32 * 8; let img = ImageBuffer::from_fn(width, height, |x, y| { let i = (y * width) + { if mirror { width - x - 1 } else { x } }; let pixel = (3 - self.pixels[i as usize]) * 0x55; Luma([pixel]) }); let img = DynamicImage::ImageLuma8(img); let mut buf = Vec::new(); match img.write_to(&mut buf, format) { Ok(_) => {} Err(_) => return Err(error::Error::PicCouldNotWrite), } Ok(buf) } pub fn to_png(&self, mirror: bool) -> Result<Vec<u8>> { self.to_img(ImageFormat::Png, mirror) } pub fn to_jpeg(&self, mirror: bool) -> Result<Vec<u8>> { self.to_img(ImageFormat::Jpeg, mirror) } }
mod bitplane; mod bitstream; mod encoding_method; pub use encoding_method::EncodingMethod as PicEncodingMethod; use crate::error::{self, Result}; use bitplane::*; use bitstream::*; use image::{self, DynamicImage, ImageBuffer, ImageFormat, Luma}; #[derive(Clone, Debug, PartialEq)] pub struct Pic { pub width: u8, pub height: u8, pub pixels: Vec<u8>, pub bytes: usize, pub encoding_method: PicEncodingMethod, } impl Pic { pub fn new(data: &[u8]) -> Result<Self> { let mut bitstream = Bitstream::from(data); let width = bitstream.get(4) as u8; let height = bitstream.get(4) as u8; let primary_buffer = bitstream.get(1) as u8; let mut bitplane_1 = Pic::decode_bitplane(width, height, &mut bitstream); let encoding_method = PicEncodingMethod::from( { if bitstream.get(1) == 0x00 { 0x01 } else { if bitstream.get(1) == 0x00 { 0x02 } else { 0x03 } } }, primary_buffer, ); let mut bitplane_0 = Pic::decode_bitplane(width, height, &mut bitstream); match encoding_method { PicEncodingMethod::ONE(_) => { bitplane_1 = bitplane_1.delta_decode(width as usize * 8); bitplane_0 = bitplane_0.delta_decode(width as usize * 8); } PicEncodingMethod::TWO(_) => { bitplane_1 = bitplane_1.delta_decode(width as usize * 8); bitplane_0 = bitplane_0.clone() ^ bitplane_1.clone(); } PicEncodingMethod::THREE(_) => { bitplane_1 = bitplane_1.delta_decode(width as usize * 8); bitplane_0 = bitplane_0.delta_decode(width as usize * 8); bitplane_0 = bitplane_0.clone() ^ bitplane_1.clone(); } }; let pixels = { if encoding_method.value() == 0x00 { (bitplane_0 << 0x01) | bitplane_1 } else { (bitplane_1 << 0x01) | bitplane_0 } }; let bytes = ((bitstream.bits as f32) / 8.0).ceil() as usize; Ok(Pic { width, height, pixels: pixels.data, bytes, encoding_method, }) } pub fn encode(&self, encoding_method: PicEncodingMethod) -> Vec<u8> { let width = self.width; let height = self.height; let (mut bitplane_0b, mut bitplane_1b) = if encoding_method.value() == 0x00 { let pixel_bitplane = Bitplane::from(self.pixels.to_vec()); ( (pixel_bitplane.clone() & 0x02) >> 0x01, pixel_bitplane.clone() & 0x01, ) } else { let pixel_bitplane = Bitplane::from(self.pixels.to_vec()); ( pixel_bitplane.clone() & 0x01, (pixel_bitplane.clone() & 0x02) >> 0x01, ) }; let (bitplane_0a, bitplane_1a) = match encoding_method { PicEncodingMethod::ONE(_) => { let bitplane_1a = bitplane_1b.delta_encode(width as usize * 8); let bitplane_0a = bitplane_0b.delta_encode(width as usize * 8); (bitplane_0a, bitplane_1a) } PicEncodingMethod::TWO(_) => { let bitplane_1a = bitplane_1b.delta_encode(width as usize * 8); let bitplane_0a = bitplane_0b.clone() ^ bitplane_1b.clone(); (bitplane_0a, bitplane_1a) } PicEncodingMethod::THREE(_) => { let bitplane_1a = bitplane_1b.delta_encode(width as usize * 8); let bitplane_0a = bitplane_0b.delta_encode(width as usize * 8); let bitplane_0a = bitplane_0a.clone() ^ bitplane_1a.clone(); (bitplane_0a, bitplane_1a) } }; let bitplane_0a_raw = Pic::encode_bitplane(width, height, bitplane_0a); let bitplane_1a_raw = Pic::encode_bitplane(width, height, bitplane_1a); let data_bits: Vec<u8> = [ (0..=3) .map(|i| (width & (i << (3 - i))) >> (3 - i)) .collect(), (0..=3) .map(|i| (height & (i << (3 - i))) >> (3 - i)) .collect(), vec![encoding_method.value()], bitplane_1a_raw, encoding_method.to_vec(), bitplane_0a_raw, ] .concat(); let data_bytes = ((data_bits.len() as f32) / 8.0).ceil() as usize; let extra_bits = (data_bytes * 8) - data_bits.len(); let data_bits = [data_bits, vec![0x00; extra_bits]].concat(); let data: Vec<u8> = (0..data_bytes) .map(|i| { let index = i * 8; data_bits[index..(index + 8)] .iter() .enumerate() .map(|(i, bit)| bit << (7 - i)) .fold(0, |acc, val| acc | val) }) .collect(); data } fn from(data: Vec<u8>, format: ImageFormat) -> Result<Self> { let raw = match image::load_from_memory_with_format(&data, format) { Ok(img) => img, Err(_) => return Err(error::Error::PicCouldNotRead), }; let img = match raw.as_luma8() { Some(img) => img, None => return Err(error::Error::PicCouldNotRead), }; if img.width() % 8 != 0 || img.height() % 8 != 0 { return Err(error::Error::PicWrongSize); } let width = ((img.width() as f32) / 8.0) as u8; let height = ((img.height() as f32) / 8.0) as u8; let pixels: Vec<u8> = img .enumerate_pixels() .map(|(_, _, pixel)| { let pixel = 3 - (((pixel.0[0] as f32) / 85.0) as u8); pixel }) .collect(); let encoding_method = PicEncodingMethod::from(0x01, 0x00);
} pub fn from_png(data: Vec<u8>) -> Result<Self> { Pic::from(data, ImageFormat::Png) } pub fn from_jpeg(data: Vec<u8>) -> Result<Self> { Pic::from(data, ImageFormat::Jpeg) } pub fn decode_bitplane(width: u8, height: u8, bitstream: &mut Bitstream) -> Bitplane { let mut pairs: Vec<u8> = vec![]; let mut packet_type = bitstream.get(1); loop { if pairs.len() >= (width as u32 * height as u32 * 32) as usize { break; } if packet_type == 0x00 { let (length, bits) = bitstream.get_until_zero(); let value = bitstream.get(bits); let run = length + value + 1; for _ in 0..run { pairs.push(0x00); } packet_type = 0x01; } else { loop { if pairs.len() >= (width as u32 * height as u32 * 32) as usize { break; } let pair = bitstream.get(2); if pair == 0x00 { break; } pairs.push(pair as u8); } packet_type = 0x00; } } let mut bitplane = vec![0x00; pairs.len() * 2]; pairs.iter().enumerate().for_each(|(i, pair)| { let x = (i / (height as usize * 8)) * 2; let y = i % (height as usize * 8); let new_i = (y * (height as usize * 8)) + x; bitplane[new_i] = (pair & 0x02) >> 0x01; bitplane[new_i + 1] = pair & 0x01; }); Bitplane::from(bitplane) } pub fn encode_bitplane(width: u8, height: u8, bitplane: Bitplane) -> Vec<u8> { let mut output = vec![]; let pixels: Vec<usize> = (0..(width * 8)) .step_by(2) .map(|x| { (0..((height as usize) * 8)) .map(move |y| (y * ((height as usize) * 8)) + (x as usize)) }) .flatten() .collect(); let mut pairs = pixels .into_iter() .map(|i| (bitplane.data[i] << 0x01) | bitplane.data[i + 1]) .peekable(); let mut packet_type = match pairs.peek() { Some(&chunk) if chunk == 0x00 => 0x00, _ => 0x01, }; output.push(packet_type); loop { if pairs.peek() == None { break; } if packet_type == 0x00 { let mut output_data = vec![]; let run = { let mut run = 0; while pairs.peek() == Some(&0x00) { pairs.next(); run += 1; } run as i32 }; let bits = if run == 0x01 { 1 } else { (run as f32 + 1.0).log2().floor() as u32 }; let value = (run + 1) & !(1 << bits); let length = run - value - 1; (0..bits).for_each(|i| { let bit = ((length & (0x01 << (bits - i - 1))) >> (bits - i - 1)) as u8; output_data.push(bit); }); (0..bits).for_each(|i| { let bit = ((value & (0x01 << (bits - i - 1))) >> (bits - i - 1)) as u8; output_data.push(bit); }); output.append(&mut output_data); packet_type = 0x01; } else { let mut output_data = vec![]; while pairs.peek() != Some(&0x00) { let pair = pairs.next().unwrap(); output_data.push((pair & 0x02) >> 0x01); output_data.push(pair & 0x01); if pairs.peek() == None { break; } } output_data.push(0x00); output_data.push(0x00); output.append(&mut output_data); packet_type = 0x00; } } output } fn to_img(&self, format: ImageFormat, mirror: bool) -> Result<Vec<u8>> { let width = self.width as u32 * 8; let height = self.height as u32 * 8; let img = ImageBuffer::from_fn(width, height, |x, y| { let i = (y * width) + { if mirror { width - x - 1 } else { x } }; let pixel = (3 - self.pixels[i as usize]) * 0x55; Luma([pixel]) }); let img = DynamicImage::ImageLuma8(img); let mut buf = Vec::new(); match img.write_to(&mut buf, format) { Ok(_) => {} Err(_) => return Err(error::Error::PicCouldNotWrite), } Ok(buf) } pub fn to_png(&self, mirror: bool) -> Result<Vec<u8>> { self.to_img(ImageFormat::Png, mirror) } pub fn to_jpeg(&self, mirror: bool) -> Result<Vec<u8>> { self.to_img(ImageFormat::Jpeg, mirror) } }
Ok(Pic { width, height, pixels, bytes: 0, encoding_method, })
call_expression
[ { "content": "pub fn get_data_raw(data: Data) -> Vec<u8> {\n\n let mut raw = Vec::new();\n\n\n\n data.stream_to(&mut raw).unwrap();\n\n\n\n raw\n\n}\n\n\n", "file_path": "pkmnapi-api/src/utils.rs", "rank": 0, "score": 323389.12652447517 }, { "content": "pub fn get_etag(if_match: Result<IfMatch, IfMatchError>) -> Result<String, ResponseError> {\n\n match if_match {\n\n Ok(if_match) => Ok(if_match.into_inner()),\n\n Err(_) => Err(ETagErrorMissing::new()),\n\n }\n\n}\n\n\n", "file_path": "pkmnapi-api/src/utils.rs", "rank": 1, "score": 249555.0115318573 }, { "content": "#[allow(dead_code)]\n\npub fn assert_unauthorized(response: &mut Response) -> Result<(), String> {\n\n let response_body = response.body_string().unwrap();\n\n let headers = response.headers();\n\n\n\n let body = json!({\n\n \"data\": {\n\n \"id\": \"error_access_tokens_unauthorized\",\n\n \"type\": \"errors\",\n\n \"attributes\": {\n\n \"message\": \"Authorization header must be set\"\n\n }\n\n }\n\n });\n\n\n\n assert_eq!(response_body, body.to_string());\n\n assert_eq!(response.status(), Status::Unauthorized);\n\n\n\n assert_headers(\n\n headers,\n\n vec![\n\n (\"Content-Type\", \"application/json\"),\n\n (\"Server\", \"pkmnapi/0.1.0\"),\n\n ],\n\n )\n\n}\n\n\n", "file_path": "pkmnapi-api/tests/common.rs", "rank": 2, "score": 243935.38348613508 }, { "content": "#[allow(dead_code)]\n\n#[allow(non_snake_case)]\n\npub fn load_rom() -> Vec<u8> {\n\n let PKMN_ROM = env::var(\"PKMN_ROM\")\n\n .expect(\"Set the PKMN_ROM environment variable to point to the ROM location\");\n\n\n\n fs::read(PKMN_ROM).unwrap()\n\n}\n\n\n", "file_path": "pkmnapi-api/tests/common.rs", "rank": 3, "score": 203748.85819862864 }, { "content": "#[allow(dead_code)]\n\n#[allow(non_snake_case)]\n\npub fn load_sav() -> Vec<u8> {\n\n let PKMN_SAV = env::var(\"PKMN_SAV\")\n\n .expect(\"Set the PKMN_SAV environment variable to point to the SAV location\");\n\n\n\n fs::read(PKMN_SAV).unwrap()\n\n}\n\n\n", "file_path": "pkmnapi-api/tests/common.rs", "rank": 4, "score": 203748.85819862864 }, { "content": "/// Generate eTag\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use pkmnapi_sql::utils;\n\n///\n\n/// let etag = utils::etag(&\"bar\".to_owned().into_bytes());\n\n///\n\n/// assert_eq!(etag, \"w/\\\"37b51d194a7513e45b56f6524f2d51f2\\\"\");\n\n/// ```\n\npub fn etag(body: &Vec<u8>) -> String {\n\n let content = hash(body);\n\n\n\n format!(\"w/\\\"{}\\\"\", content)\n\n}\n", "file_path": "pkmnapi-sql/src/utils.rs", "rank": 5, "score": 191117.4623637281 }, { "content": "/// Generate hash string\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use pkmnapi_sql::utils;\n\n///\n\n/// let hash = utils::hash(&\"bar\".to_owned().into_bytes());\n\n///\n\n/// assert_eq!(hash, \"37b51d194a7513e45b56f6524f2d51f2\");\n\n/// ```\n\npub fn hash(value: &Vec<u8>) -> String {\n\n format!(\"{:02x}\", md5::compute(value))\n\n}\n\n\n", "file_path": "pkmnapi-sql/src/utils.rs", "rank": 6, "score": 191117.28942506498 }, { "content": "#[get(\"/maps/pics/<map_id>\", format = \"image/jpeg\", rank = 2)]\n\npub fn get_map_pic_jpeg<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n map_id: u8,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let map = db.get_map_pic(&map_id)?;\n\n let img = map.to_jpeg()?;\n\n\n\n let response = Response::build()\n\n .header(ContentType::JPEG)\n\n .header(Header::new(\n\n \"Content-Disposition\",\n\n format!(r#\"attachment; filename=\"map-{}.jpg\"\"#, map_id),\n\n ))\n\n .sized_body(Cursor::new(img))\n\n .finalize();\n\n\n\n Ok(response)\n\n}\n", "file_path": "pkmnapi-api/src/routes/map_pics.rs", "rank": 7, "score": 190423.58549159678 }, { "content": "#[get(\"/maps/pics/<map_id>\", format = \"image/png\", rank = 1)]\n\npub fn get_map_pic_png<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n map_id: u8,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let map = db.get_map_pic(&map_id)?;\n\n let img = map.to_png()?;\n\n\n\n let response = Response::build()\n\n .header(ContentType::PNG)\n\n .header(Header::new(\n\n \"Content-Disposition\",\n\n format!(r#\"attachment; filename=\"map-{}.png\"\"#, map_id),\n\n ))\n\n .sized_body(Cursor::new(img))\n\n .finalize();\n\n\n\n Ok(response)\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/map_pics.rs", "rank": 8, "score": 190423.58549159678 }, { "content": "#[get(\"/trainers/pics/<trainer_id>?<mirror>\", format = \"image/png\", rank = 1)]\n\npub fn get_trainer_pic_png<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n trainer_id: u8,\n\n mirror: Option<bool>,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let pic = db.get_trainer_pic(&trainer_id)?;\n\n let trainer_name = db.get_trainer_name(&trainer_id)?;\n\n let img = pic.to_png(mirror.is_some())?;\n\n\n\n let response = Response::build()\n\n .header(ContentType::PNG)\n\n .header(Header::new(\n\n \"Content-Disposition\",\n\n format!(r#\"attachment; filename=\"{}.png\"\"#, trainer_name.name),\n\n ))\n", "file_path": "pkmnapi-api/src/routes/trainer_pics.rs", "rank": 9, "score": 190423.4429910677 }, { "content": "pub fn get_pokemon_pic_png<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n pokedex_id: u8,\n\n face: Option<String>,\n\n mirror: Option<bool>,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let pic = db.get_pokemon_pic(&pokedex_id, &PokemonPicFace::from(face))?;\n\n let pokemon_name = db.get_pokemon_name(&pokedex_id)?;\n\n let img = pic.to_png(mirror.is_some())?;\n\n\n\n let response = Response::build()\n\n .header(ContentType::PNG)\n\n .header(Header::new(\n\n \"Content-Disposition\",\n\n format!(r#\"attachment; filename=\"{}.png\"\"#, pokemon_name.name),\n", "file_path": "pkmnapi-api/src/routes/pokemon_pics.rs", "rank": 10, "score": 190412.1779769486 }, { "content": "pub fn get_pokemon_pic_jpeg<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n pokedex_id: u8,\n\n face: Option<String>,\n\n mirror: Option<bool>,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let pic = db.get_pokemon_pic(&pokedex_id, &PokemonPicFace::from(face))?;\n\n let pokemon_name = db.get_pokemon_name(&pokedex_id)?;\n\n let img = pic.to_jpeg(mirror.is_some())?;\n\n\n\n let response = Response::build()\n\n .header(ContentType::JPEG)\n\n .header(Header::new(\n\n \"Content-Disposition\",\n\n format!(r#\"attachment; filename=\"{}.jpg\"\"#, pokemon_name.name),\n", "file_path": "pkmnapi-api/src/routes/pokemon_pics.rs", "rank": 11, "score": 190412.1779769486 }, { "content": "pub fn post_pokemon_pic_jpeg<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n data: Data,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n pokedex_id: u8,\n\n face: Option<String>,\n\n method: Option<u8>,\n\n primary: Option<u8>,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n let raw_data = utils::get_data_raw(data);\n\n\n\n let pic = Pic::from_jpeg(raw_data)?;\n\n let encoding_method = PicEncodingMethod::from(method.unwrap_or(0x01), primary.unwrap_or(0x00));\n\n let patch = db.set_pokemon_pic(\n\n &pokedex_id,\n\n &PokemonPicFace::from(face),\n", "file_path": "pkmnapi-api/src/routes/pokemon_pics.rs", "rank": 12, "score": 190412.1779769486 }, { "content": "pub fn post_pokemon_pic_png<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n data: Data,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n pokedex_id: u8,\n\n face: Option<String>,\n\n method: Option<u8>,\n\n primary: Option<u8>,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n let raw_data = utils::get_data_raw(data);\n\n\n\n let pic = Pic::from_png(raw_data)?;\n\n let encoding_method = PicEncodingMethod::from(method.unwrap_or(0x01), primary.unwrap_or(0x00));\n\n let patch = db.set_pokemon_pic(\n\n &pokedex_id,\n\n &PokemonPicFace::from(face),\n", "file_path": "pkmnapi-api/src/routes/pokemon_pics.rs", "rank": 13, "score": 190412.1779769486 }, { "content": "pub fn post_trainer_pic_png<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n data: Data,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n trainer_id: u8,\n\n method: Option<u8>,\n\n primary: Option<u8>,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n let raw_data = utils::get_data_raw(data);\n\n\n\n let pic = Pic::from_png(raw_data)?;\n\n let encoding_method = PicEncodingMethod::from(method.unwrap_or(0x01), primary.unwrap_or(0x00));\n\n let patch = db.set_trainer_pic(&trainer_id, &pic, encoding_method)?;\n\n\n\n utils::insert_rom_patch(\n\n sql,\n", "file_path": "pkmnapi-api/src/routes/trainer_pics.rs", "rank": 14, "score": 190412.1779769486 }, { "content": "pub fn post_trainer_pic_jpeg<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n data: Data,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n trainer_id: u8,\n\n method: Option<u8>,\n\n primary: Option<u8>,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n let raw_data = utils::get_data_raw(data);\n\n\n\n let pic = Pic::from_jpeg(raw_data)?;\n\n let encoding_method = PicEncodingMethod::from(method.unwrap_or(0x01), primary.unwrap_or(0x00));\n\n let patch = db.set_trainer_pic(&trainer_id, &pic, encoding_method)?;\n\n\n\n utils::insert_rom_patch(\n\n sql,\n\n connection,\n\n access_token,\n\n patch,\n\n patch_description,\n\n BaseErrorResponseId::error_trainer_pics,\n\n )?;\n\n\n\n Ok(status::Accepted(Some(json!({}))))\n\n}\n", "file_path": "pkmnapi-api/src/routes/trainer_pics.rs", "rank": 15, "score": 190412.1779769486 }, { "content": "pub fn get_trainer_pic_jpeg<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n trainer_id: u8,\n\n mirror: Option<bool>,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let pic = db.get_trainer_pic(&trainer_id)?;\n\n let trainer_name = db.get_trainer_name(&trainer_id)?;\n\n let img = pic.to_jpeg(mirror.is_some())?;\n\n\n\n let response = Response::build()\n\n .header(ContentType::JPEG)\n\n .header(Header::new(\n\n \"Content-Disposition\",\n\n format!(r#\"attachment; filename=\"{}.jpg\"\"#, trainer_name.name),\n\n ))\n", "file_path": "pkmnapi-api/src/routes/trainer_pics.rs", "rank": 16, "score": 190412.1779769486 }, { "content": "pub fn get_data<T>(\n\n data: Result<Json<T>, JsonError>,\n\n error_id: BaseErrorResponseId,\n\n) -> Result<T, ResponseError> {\n\n match data {\n\n Ok(data) => Ok(data.into_inner()),\n\n Err(JsonError::Parse(_, e)) => {\n\n return Err(BadRequestError::new(error_id, Some(e.to_string())));\n\n }\n\n _ => {\n\n return Err(BadRequestError::new(\n\n error_id,\n\n Some(\"An unknown error occurred\".to_owned()),\n\n ));\n\n }\n\n }\n\n}\n\n\n", "file_path": "pkmnapi-api/src/utils.rs", "rank": 17, "score": 187959.07458001777 }, { "content": "#[post(\"/imgs/pokemon_logo\", format = \"image/png\", data = \"<data>\", rank = 1)]\n\npub fn post_pokemon_logo_png<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n data: Data,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n let raw_data = utils::get_data_raw(data);\n\n\n\n let img = Img::from_png(raw_data)?;\n\n let patch = db.set_pokemon_logo_img(&img)?;\n\n\n\n utils::insert_rom_patch(\n\n sql,\n\n connection,\n\n access_token,\n\n patch,\n\n patch_description,\n\n BaseErrorResponseId::error_pokemon_logo_imgs,\n\n )?;\n\n\n\n Ok(status::Accepted(Some(json!({}))))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/imgs.rs", "rank": 18, "score": 181059.44703563934 }, { "content": "#[post(\"/imgs/pokemon_logo\", format = \"image/jpeg\", data = \"<data>\", rank = 2)]\n\npub fn post_pokemon_logo_jpeg<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n data: Data,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n let raw_data = utils::get_data_raw(data);\n\n\n\n let img = Img::from_jpeg(raw_data)?;\n\n let patch = db.set_pokemon_logo_img(&img)?;\n\n\n\n utils::insert_rom_patch(\n\n sql,\n\n connection,\n\n access_token,\n\n patch,\n\n patch_description,\n\n BaseErrorResponseId::error_pokemon_logo_imgs,\n\n )?;\n\n\n\n Ok(status::Accepted(Some(json!({}))))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/imgs.rs", "rank": 19, "score": 181059.44703563934 }, { "content": "#[get(\"/imgs/pokemon_logo\", format = \"image/jpeg\", rank = 2)]\n\npub fn get_pokemon_logo_jpeg<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let pokemon_logo = db.get_pokemon_logo_img()?;\n\n let img = pokemon_logo.to_jpeg()?;\n\n\n\n let response = Response::build()\n\n .header(ContentType::JPEG)\n\n .header(Header::new(\n\n \"Content-Disposition\",\n\n r#\"attachment; filename=\"pokemon_logo.jpg\"\"#,\n\n ))\n\n .sized_body(Cursor::new(img))\n\n .finalize();\n\n\n\n Ok(response)\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/imgs.rs", "rank": 20, "score": 181053.21488653042 }, { "content": "#[get(\"/imgs/town_map\", format = \"image/png\", rank = 1)]\n\npub fn get_town_map_png<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let town_map = db.get_town_map_img()?;\n\n let img = town_map.to_png()?;\n\n\n\n let response = Response::build()\n\n .header(ContentType::PNG)\n\n .header(Header::new(\n\n \"Content-Disposition\",\n\n r#\"attachment; filename=\"town_map.png\"\"#,\n\n ))\n\n .sized_body(Cursor::new(img))\n\n .finalize();\n\n\n\n Ok(response)\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/imgs.rs", "rank": 21, "score": 181053.21488653042 }, { "content": "#[get(\"/imgs/game_boy\", format = \"image/jpeg\", rank = 2)]\n\npub fn get_game_boy_jpeg<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let game_boy = db.get_game_boy_img()?;\n\n let img = game_boy.to_jpeg()?;\n\n\n\n let response = Response::build()\n\n .header(ContentType::JPEG)\n\n .header(Header::new(\n\n \"Content-Disposition\",\n\n r#\"attachment; filename=\"game_boy.jpg\"\"#,\n\n ))\n\n .sized_body(Cursor::new(img))\n\n .finalize();\n\n\n\n Ok(response)\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/imgs.rs", "rank": 22, "score": 181053.21488653042 }, { "content": "#[get(\"/imgs/game_boy\", format = \"image/png\", rank = 1)]\n\npub fn get_game_boy_png<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let game_boy = db.get_game_boy_img()?;\n\n let img = game_boy.to_png()?;\n\n\n\n let response = Response::build()\n\n .header(ContentType::PNG)\n\n .header(Header::new(\n\n \"Content-Disposition\",\n\n r#\"attachment; filename=\"game_boy.png\"\"#,\n\n ))\n\n .sized_body(Cursor::new(img))\n\n .finalize();\n\n\n\n Ok(response)\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/imgs.rs", "rank": 23, "score": 181053.21488653042 }, { "content": "#[get(\"/imgs/town_map\", format = \"image/jpeg\", rank = 2)]\n\npub fn get_town_map_jpeg<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let town_map = db.get_town_map_img()?;\n\n let img = town_map.to_jpeg()?;\n\n\n\n let response = Response::build()\n\n .header(ContentType::JPEG)\n\n .header(Header::new(\n\n \"Content-Disposition\",\n\n r#\"attachment; filename=\"town_map.jpg\"\"#,\n\n ))\n\n .sized_body(Cursor::new(img))\n\n .finalize();\n\n\n\n Ok(response)\n\n}\n", "file_path": "pkmnapi-api/src/routes/imgs.rs", "rank": 24, "score": 181053.21488653042 }, { "content": "#[get(\"/imgs/pokemon_logo\", format = \"image/png\", rank = 1)]\n\npub fn get_pokemon_logo_png<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let pokemon_logo = db.get_pokemon_logo_img()?;\n\n let img = pokemon_logo.to_png()?;\n\n\n\n let response = Response::build()\n\n .header(ContentType::PNG)\n\n .header(Header::new(\n\n \"Content-Disposition\",\n\n r#\"attachment; filename=\"pokemon_logo.png\"\"#,\n\n ))\n\n .sized_body(Cursor::new(img))\n\n .finalize();\n\n\n\n Ok(response)\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/imgs.rs", "rank": 25, "score": 181053.21488653042 }, { "content": "#[get(\"/roms/patches?<checksum>\", format = \"application/patch\", rank = 2)]\n\npub fn get_rom_patches_raw<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n checksum: Option<bool>,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, connection) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let patches = match sql.select_rom_patches_by_access_token(&connection, &access_token) {\n\n Ok(patches) => patches,\n\n Err(_) => return Err(RomErrorNoRom::new()),\n\n };\n\n\n\n let header = \"PATCH\".chars().map(|c| c as u8).collect::<Vec<u8>>();\n\n let footer = \"EOF\".chars().map(|c| c as u8).collect::<Vec<u8>>();\n\n let mut body: Vec<u8> = patches\n\n .iter()\n\n .map(|patch| patch.data.to_vec())\n\n .flatten()\n", "file_path": "pkmnapi-api/src/routes/rom_patches.rs", "rank": 26, "score": 177905.3978717887 }, { "content": "#[catch(404)]\n\npub fn not_found(_req: &Request) -> Result<ResponseError, ResponseError> {\n\n Ok(NotFoundError::new(\n\n BaseErrorResponseId::error_not_found,\n\n None,\n\n ))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/errors.rs", "rank": 27, "score": 175409.46576456228 }, { "content": "/// Generate random ID of size length\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use pkmnapi_sql::utils::*;\n\n///\n\n/// let id = random_id(32);\n\n///\n\n/// assert_eq!(id.len(), 32);\n\n///\n\n/// let id = random_id(64);\n\n///\n\n/// assert_eq!(id.len(), 64);\n\n/// ```\n\npub fn random_id(length: usize) -> String {\n\n let mut rng = thread_rng();\n\n\n\n iter::repeat(())\n\n .map(|()| rng.sample(Alphanumeric))\n\n .take(length)\n\n .collect()\n\n}\n\n\n", "file_path": "pkmnapi-sql/src/utils.rs", "rank": 28, "score": 174260.8970826909 }, { "content": "#[allow(dead_code)]\n\npub fn test_raw<T>(test: T) -> ()\n\nwhere\n\n T: FnOnce() -> Result<(), String> + panic::UnwindSafe,\n\n{\n\n let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {\n\n test().unwrap();\n\n }));\n\n\n\n assert!(result.is_ok())\n\n}\n\n\n", "file_path": "pkmnapi-api/tests/common.rs", "rank": 29, "score": 174247.5950707791 }, { "content": "#[allow(dead_code)]\n\npub fn assert_headers(headers: &HeaderMap<'_>, expected: Vec<(&str, &str)>) -> Result<(), String> {\n\n let mut headers = headers.clone();\n\n\n\n for (key, val) in &expected {\n\n let header = match headers.get_one(key) {\n\n Some(header) => header,\n\n None => return Err(format!(\"Could not find header: {}\", key)),\n\n };\n\n\n\n if val.len() != 0 {\n\n assert_eq!(header, *val);\n\n }\n\n\n\n headers.remove(key);\n\n }\n\n\n\n for header in headers.iter() {\n\n panic!(\"Extra header found: {}\", header);\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "pkmnapi-api/tests/common.rs", "rank": 30, "score": 173741.5681792749 }, { "content": "#[catch(429)]\n\npub fn too_many_requests<'a>(req: &Request) -> Result<Response<'a>, ResponseError> {\n\n let wait_time = match req.guard::<RateLimit>() {\n\n Outcome::Failure((_, RateLimitError::TooManyRequests(wait_time))) => wait_time,\n\n _ => 0,\n\n };\n\n\n\n let response = TooManyRequestsError::new(wait_time);\n\n let body = serde_json::to_string(&response).unwrap();\n\n\n\n let response = Response::build()\n\n .status(Status::TooManyRequests)\n\n .header(ContentType::JSON)\n\n .sized_body(Cursor::new(body))\n\n .finalize();\n\n\n\n Ok(response)\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/errors.rs", "rank": 31, "score": 169475.90695515898 }, { "content": "#[catch(500)]\n\npub fn internal_server_error<'a>(_req: &Request) -> Result<Response<'a>, ResponseError> {\n\n let response = InternalServerError::new();\n\n let body = serde_json::to_string(&response).unwrap();\n\n\n\n let response = Response::build()\n\n .status(Status::InternalServerError)\n\n .header(ContentType::JSON)\n\n .sized_body(Cursor::new(body))\n\n .finalize();\n\n\n\n Ok(response)\n\n}\n", "file_path": "pkmnapi-api/src/routes/errors.rs", "rank": 32, "score": 166792.19339796045 }, { "content": "pub fn from_numeric_str<'de, T, D>(deserializer: D) -> Result<T, D::Error>\n\nwhere\n\n T: FromStr,\n\n T::Err: Display,\n\n D: Deserializer<'de>,\n\n{\n\n let s = String::deserialize(deserializer)?;\n\n\n\n T::from_str(&s).map_err(de::Error::custom)\n\n}\n", "file_path": "pkmnapi-api/src/utils.rs", "rank": 33, "score": 159600.41422436095 }, { "content": "pub fn get_db(\n\n sql: &State<PkmnapiSQL>,\n\n access_token: &String,\n\n) -> Result<(PkmnapiDB, PgPooledConnection), ResponseError> {\n\n let connection = sql.get_connection().unwrap();\n\n let rom_data = match sql.select_user_rom_data_by_access_token(&connection, &access_token) {\n\n Ok(Some(rom_data)) => rom_data,\n\n Ok(None) => return Err(RomErrorNoRom::new()),\n\n _ => {\n\n return Err(AccessTokenErrorInvalid::new(\n\n &\"Invalid access token\".to_owned(),\n\n ))\n\n }\n\n };\n\n\n\n let mut db = PkmnapiDB::new(&rom_data.data);\n\n\n\n match sql.select_user_sav_by_access_token(&connection, &access_token) {\n\n Ok(Some(sav)) => {\n\n db.sav(sav.data);\n", "file_path": "pkmnapi-api/src/utils.rs", "rank": 34, "score": 145996.01461366832 }, { "content": "#[openapi]\n\n#[post(\"/trades/<trade_id>\", format = \"application/json\", data = \"<data>\")]\n\npub fn post_trade(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<TradeRequest>, JsonError>,\n\n trade_id: u8,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_trades_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let trade = Trade::new(\n\n data.get_give_pokedex_id(),\n\n data.get_get_pokedex_id(),\n\n data.get_nickname(),\n\n );\n\n\n\n let patch = db.set_trade(&trade_id, &trade)?;\n\n\n", "file_path": "pkmnapi-api/src/routes/trades.rs", "rank": 35, "score": 143543.29184331253 }, { "content": "#[openapi]\n\n#[delete(\"/roms\")]\n\npub fn delete_rom(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n if_match: Result<IfMatch, IfMatchError>,\n\n) -> Result<status::NoContent, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let etag = utils::get_etag(if_match)?;\n\n let connection = sql.get_connection().unwrap();\n\n\n\n match sql.delete_user_rom_by_access_token(&connection, &access_token, &etag) {\n\n Ok(_) => {}\n\n Err(pkmnapi_sql::error::Error::ETagError) => return Err(ETagErrorMismatch::new()),\n\n Err(_) => return Err(RomErrorNoRom::new()),\n\n }\n\n\n\n Ok(status::NoContent)\n\n}\n", "file_path": "pkmnapi-api/src/routes/roms.rs", "rank": 36, "score": 143531.09523317707 }, { "content": "pub fn get_access_token(\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<String, ResponseError> {\n\n match access_token {\n\n Ok(access_token) => Ok(access_token.into_inner()),\n\n Err(_) => Err(AccessTokenErrorUnauthorized::new()),\n\n }\n\n}\n\n\n", "file_path": "pkmnapi-api/src/utils.rs", "rank": 37, "score": 143531.09523317707 }, { "content": "#[openapi]\n\n#[get(\"/trades/<trade_id>\")]\n\npub fn get_trade(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n trade_id: u8,\n\n) -> Result<Json<TradeResponse>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let trade = db.get_trade(&trade_id)?;\n\n let pokedex_ids = vec![trade.give_pokedex_id, trade.get_pokedex_id];\n\n let pokemon_names = db.get_pokemon_name_all(&pokedex_ids)?;\n\n\n\n let response = TradeResponse::new(&trade_id, &trade, &pokemon_names);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/trades.rs", "rank": 38, "score": 143531.09523317707 }, { "content": "pub fn insert_rom_patch(\n\n sql: State<PkmnapiSQL>,\n\n connection: PgPooledConnection,\n\n access_token: String,\n\n patch: Patch,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n error_id: BaseErrorResponseId,\n\n) -> Result<(), ResponseError> {\n\n let patch_description = get_patch_description(patch_description);\n\n\n\n match sql.insert_rom_patch(\n\n &connection,\n\n &access_token,\n\n &patch.to_raw(),\n\n patch_description,\n\n ) {\n\n Ok(_) => Ok(()),\n\n Err(e) => return Err(NotFoundError::new(error_id, Some(e.to_string()))),\n\n }\n\n}\n\n\n", "file_path": "pkmnapi-api/src/utils.rs", "rank": 39, "score": 143531.09523317707 }, { "content": "#[openapi]\n\n#[get(\"/trades\")]\n\npub fn get_trade_all(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<TradeResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let (min_trade_id, max_trade_id) = db.trade_id_bounds();\n\n let trade_ids: Vec<u8> = (min_trade_id..=max_trade_id)\n\n .map(|trade_id| trade_id as u8)\n\n .collect();\n\n let trades = db.get_trade_all(&trade_ids)?;\n\n let pokedex_ids = trades\n\n .iter()\n\n .map(|(_, trade)| vec![trade.give_pokedex_id, trade.get_pokedex_id])\n\n .flatten()\n\n .collect();\n\n let pokemon_names = db.get_pokemon_name_all(&pokedex_ids)?;\n\n\n\n let response = TradeResponseAll::new(&trade_ids, &trades, &pokemon_names);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/trades.rs", "rank": 40, "score": 143531.09523317707 }, { "content": "#[openapi]\n\n#[delete(\"/savs\")]\n\npub fn delete_sav(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n if_match: Result<IfMatch, IfMatchError>,\n\n) -> Result<status::NoContent, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let etag = utils::get_etag(if_match)?;\n\n let connection = sql.get_connection().unwrap();\n\n\n\n match sql.delete_user_sav_by_access_token(&connection, &access_token, &etag) {\n\n Ok(_) => {}\n\n Err(pkmnapi_sql::error::Error::ETagError) => return Err(ETagErrorMismatch::new()),\n\n Err(_) => return Err(SavErrorNoSav::new()),\n\n }\n\n\n\n Ok(status::NoContent)\n\n}\n", "file_path": "pkmnapi-api/src/routes/savs.rs", "rank": 41, "score": 143531.09523317707 }, { "content": "pub fn get_patch_description(\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n) -> Option<String> {\n\n match patch_description {\n\n Ok(patch_description) => patch_description.into_inner(),\n\n Err(_) => None,\n\n }\n\n}\n\n\n", "file_path": "pkmnapi-api/src/utils.rs", "rank": 42, "score": 143531.09523317707 }, { "content": "pub fn setup() -> Client {\n\n let api = Pkmnapi::init();\n\n let client = Client::new(api).unwrap();\n\n\n\n client\n\n}\n\n\n", "file_path": "pkmnapi-api/tests/common.rs", "rank": 43, "score": 141430.748405605 }, { "content": "pub fn get_db_with_applied_patches(\n\n sql: &State<PkmnapiSQL>,\n\n access_token: &String,\n\n) -> Result<(PkmnapiDB, PgPooledConnection), ResponseError> {\n\n let (mut db, connection) = get_db(sql, access_token)?;\n\n\n\n let rom_patches = match sql.select_rom_patches_by_access_token(&connection, &access_token) {\n\n Ok(patches) => patches,\n\n Err(_) => vec![],\n\n };\n\n\n\n let sav_patches = match sql.select_sav_patches_by_access_token(&connection, &access_token) {\n\n Ok(patches) => patches,\n\n Err(_) => vec![],\n\n };\n\n\n\n for patch in rom_patches {\n\n db.apply_patch(patch.data);\n\n }\n\n\n\n if let Some(ref mut sav) = db.sav {\n\n for patch in sav_patches {\n\n sav.apply_patch(patch.data);\n\n }\n\n }\n\n\n\n Ok((db, connection))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/utils.rs", "rank": 44, "score": 141184.622873297 }, { "content": "#[post(\"/savs\", data = \"<data>\")]\n\npub fn post_sav<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n data: Data,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let sav = utils::get_data_raw(data);\n\n\n\n if let Err(_) = Sav::new(&sav) {\n\n return Err(SavErrorInvalidSav::new());\n\n }\n\n\n\n let connection = sql.get_connection().unwrap();\n\n let sav = match sql.update_user_sav_by_access_token(&connection, &access_token, &sav) {\n\n Ok(sav) => sav,\n\n Err(_) => return Err(SavErrorSavExists::new()),\n\n };\n\n\n\n let response = SavResponse::new(&sav);\n", "file_path": "pkmnapi-api/src/routes/savs.rs", "rank": 45, "score": 138972.65777739196 }, { "content": "#[post(\"/roms\", data = \"<data>\")]\n\npub fn post_rom<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n data: Data,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let rom_data = utils::get_data_raw(data);\n\n\n\n let db = match PkmnapiDB::new(&rom_data).build() {\n\n Ok(db) => db,\n\n Err(_) => return Err(RomErrorInvalidRom::new()),\n\n };\n\n\n\n let connection = sql.get_connection().unwrap();\n\n let rom = match sql.update_user_rom_by_access_token(\n\n &connection,\n\n &access_token,\n\n &db.header.title,\n\n &rom_data,\n", "file_path": "pkmnapi-api/src/routes/roms.rs", "rank": 46, "score": 138972.65777739196 }, { "content": "#[get(\"/icons/<icon_id>\", format = \"image/gif\")]\n\npub fn get_icon<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n icon_id: u8,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let icon = db.get_icon(&icon_id)?;\n\n let gif = icon.to_gif(26)?;\n\n\n\n let response = Response::build()\n\n .header(ContentType::GIF)\n\n .header(Header::new(\n\n \"Content-Disposition\",\n\n format!(r#\"attachment; filename=\"icon-{}.gif\"\"#, icon_id),\n\n ))\n\n .sized_body(Cursor::new(gif))\n\n .finalize();\n\n\n\n Ok(response)\n\n}\n", "file_path": "pkmnapi-api/src/routes/icons.rs", "rank": 47, "score": 138971.72369265676 }, { "content": "#[get(\"/savs\")]\n\npub fn get_sav<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n\n\n let connection = sql.get_connection().unwrap();\n\n let sav = match sql.select_user_sav_by_access_token(&connection, &access_token) {\n\n Ok(Some(sav)) => sav,\n\n _ => return Err(SavErrorNoSav::new()),\n\n };\n\n\n\n let response = SavResponse::new(&sav);\n\n let body = serde_json::to_string(&response).unwrap();\n\n\n\n let response = Response::build()\n\n .header(ContentType::JSON)\n\n .header(Header::new(\"ETag\", sav.etag))\n\n .sized_body(Cursor::new(body))\n\n .finalize();\n\n\n\n Ok(response)\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/savs.rs", "rank": 48, "score": 138965.82902511375 }, { "content": "#[get(\"/roms\")]\n\npub fn get_rom<'a>(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Response<'a>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n\n\n let connection = sql.get_connection().unwrap();\n\n let rom_sql = match sql.select_user_rom_by_access_token(&connection, &access_token) {\n\n Ok(Some(rom_sql)) => rom_sql,\n\n _ => return Err(RomErrorNoRom::new()),\n\n };\n\n\n\n let response = RomResponse::new(&rom_sql);\n\n let body = serde_json::to_string(&response).unwrap();\n\n\n\n let response = Response::build()\n\n .header(ContentType::JSON)\n\n .header(Header::new(\"ETag\", rom_sql.etag))\n\n .sized_body(Cursor::new(body))\n\n .finalize();\n\n\n\n Ok(response)\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/roms.rs", "rank": 49, "score": 138965.82902511375 }, { "content": "#[openapi]\n\n#[delete(\"/access_tokens\", format = \"application/json\", data = \"<data>\")]\n\npub fn delete_access_token(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n data: Result<Json<AccessTokenDeleteRequest>, JsonError>,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<status::NoContent, ResponseError> {\n\n if access_token.is_ok() {\n\n return Err(AccessTokenErrorForbidden::new());\n\n }\n\n\n\n let data = match data {\n\n Ok(data) => data.into_inner(),\n\n Err(JsonError::Parse(_, e)) => {\n\n return Err(AccessTokenErrorInvalid::new(&e.to_string()));\n\n }\n\n _ => {\n\n return Err(AccessTokenErrorInvalid::new(\n\n &\"An unknown error occurred\".to_owned(),\n\n ));\n\n }\n", "file_path": "pkmnapi-api/src/routes/access_tokens.rs", "rank": 50, "score": 138960.57767942655 }, { "content": "#[openapi]\n\n#[post(\"/player_names\", format = \"application/json\", data = \"<data>\")]\n\npub fn post_player_names(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<PlayerNamesRequest>, JsonError>,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_player_names_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let player_names = PlayerNames {\n\n player: data\n\n .get_player_names()\n\n .iter()\n\n .map(|name| ROMString::from(name))\n\n .collect(),\n\n rival: data\n\n .get_rival_names()\n\n .iter()\n", "file_path": "pkmnapi-api/src/routes/player_names.rs", "rank": 51, "score": 138960.57767942655 }, { "content": "#[openapi]\n\n#[post(\"/access_tokens\", format = \"application/json\", data = \"<data>\")]\n\npub fn post_access_token(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n data: Result<Json<AccessTokenRequest>, JsonError>,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<status::Created<JsonValue>, ResponseError> {\n\n if access_token.is_ok() {\n\n return Err(AccessTokenErrorForbidden::new());\n\n }\n\n\n\n let data = match data {\n\n Ok(data) => data.into_inner(),\n\n Err(JsonError::Parse(_, e)) => {\n\n return Err(AccessTokenErrorInvalid::new(&e.to_string()));\n\n }\n\n _ => {\n\n return Err(AccessTokenErrorInvalid::new(\n\n &\"An unknown error occurred\".to_owned(),\n\n ));\n\n }\n", "file_path": "pkmnapi-api/src/routes/access_tokens.rs", "rank": 52, "score": 138960.57767942655 }, { "content": "#[openapi]\n\n#[post(\"/items/names/<item_id>\", format = \"application/json\", data = \"<data>\")]\n\npub fn post_item_name(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<ItemNameRequest>, JsonError>,\n\n item_id: u8,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_item_names_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let item_name = ItemName {\n\n name: ROMString::from(data.get_name()),\n\n };\n\n\n\n let patch = db.set_item_name(&item_id, &item_name)?;\n\n\n\n utils::insert_rom_patch(\n\n sql,\n\n connection,\n\n access_token,\n\n patch,\n\n patch_description,\n\n BaseErrorResponseId::error_item_names,\n\n )?;\n\n\n\n Ok(status::Accepted(Some(json!({}))))\n\n}\n", "file_path": "pkmnapi-api/src/routes/item_names.rs", "rank": 53, "score": 138960.33850039946 }, { "content": "#[openapi]\n\n#[post(\"/moves/names/<move_id>\", format = \"application/json\", data = \"<data>\")]\n\npub fn post_move_name(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<MoveNameRequest>, JsonError>,\n\n move_id: u8,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_move_names_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let move_name = MoveName {\n\n name: ROMString::from(data.get_name()),\n\n };\n\n\n\n let patch = db.set_move_name(&move_id, &move_name)?;\n\n\n\n utils::insert_rom_patch(\n\n sql,\n\n connection,\n\n access_token,\n\n patch,\n\n patch_description,\n\n BaseErrorResponseId::error_move_names,\n\n )?;\n\n\n\n Ok(status::Accepted(Some(json!({}))))\n\n}\n", "file_path": "pkmnapi-api/src/routes/move_names.rs", "rank": 54, "score": 138960.33850039946 }, { "content": "#[openapi]\n\n#[post(\"/hms/moves/<hm_id>\", format = \"application/json\", data = \"<data>\")]\n\npub fn post_hm_move(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<HMMoveRequest>, JsonError>,\n\n hm_id: u8,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_hms_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let hm_move = HMMove {\n\n move_id: data.get_move_id(),\n\n };\n\n\n\n let patch = db.set_hm_move(&hm_id, &hm_move)?;\n\n\n\n utils::insert_rom_patch(\n\n sql,\n\n connection,\n\n access_token,\n\n patch,\n\n patch_description,\n\n BaseErrorResponseId::error_hms,\n\n )?;\n\n\n\n Ok(status::Accepted(Some(json!({}))))\n\n}\n", "file_path": "pkmnapi-api/src/routes/hm_moves.rs", "rank": 55, "score": 138960.33850039946 }, { "content": "#[openapi]\n\n#[post(\"/moves/stats/<move_id>\", format = \"application/json\", data = \"<data>\")]\n\npub fn post_move_stats(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<MoveStatsRequest>, JsonError>,\n\n move_id: u8,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_move_stats_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let move_stats = MoveStats {\n\n move_id: move_id,\n\n effect: data.get_effect(),\n\n power: data.get_power(),\n\n type_id: data.get_type_id(),\n\n accuracy: data.get_accuracy(),\n\n pp: data.get_pp(),\n\n };\n", "file_path": "pkmnapi-api/src/routes/move_stats.rs", "rank": 56, "score": 138960.33850039946 }, { "content": "#[openapi]\n\n#[post(\"/marts/items/<mart_id>\", format = \"application/json\", data = \"<data>\")]\n\npub fn post_mart_items(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<MartItemsRequest>, JsonError>,\n\n mart_id: u8,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_mart_items_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let mart_items = data.get_mart_items();\n\n\n\n let patch = db.set_mart_items(&mart_id, &mart_items)?;\n\n\n\n utils::insert_rom_patch(\n\n sql,\n\n connection,\n\n access_token,\n\n patch,\n\n patch_description,\n\n BaseErrorResponseId::error_mart_items,\n\n )?;\n\n\n\n Ok(status::Accepted(Some(json!({}))))\n\n}\n", "file_path": "pkmnapi-api/src/routes/mart_items.rs", "rank": 57, "score": 138960.33850039946 }, { "content": "#[openapi]\n\n#[post(\"/tms/moves/<tm_id>\", format = \"application/json\", data = \"<data>\")]\n\npub fn post_tm_move(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<TMMoveRequest>, JsonError>,\n\n tm_id: u8,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_tm_moves_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let tm_move = TMMove {\n\n move_id: data.get_move_id(),\n\n };\n\n\n\n let patch = db.set_tm_move(&tm_id, &tm_move)?;\n\n\n\n utils::insert_rom_patch(\n\n sql,\n\n connection,\n\n access_token,\n\n patch,\n\n patch_description,\n\n BaseErrorResponseId::error_tm_moves,\n\n )?;\n\n\n\n Ok(status::Accepted(Some(json!({}))))\n\n}\n", "file_path": "pkmnapi-api/src/routes/tm_moves.rs", "rank": 58, "score": 138960.33850039946 }, { "content": "#[openapi]\n\n#[post(\"/maps/pokemon/<map_id>\", format = \"application/json\", data = \"<data>\")]\n\npub fn post_map_pokemon(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<MapPokemonRequest>, JsonError>,\n\n map_id: u8,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_map_pokemon_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let map_pokemon = MapPokemon {\n\n grass: data.get_grass(),\n\n water: data.get_water(),\n\n };\n\n\n\n let patch = db.set_map_pokemon(&map_id, &map_pokemon)?;\n\n\n\n utils::insert_rom_patch(\n", "file_path": "pkmnapi-api/src/routes/map_pokemon.rs", "rank": 59, "score": 138960.33850039946 }, { "content": "#[openapi]\n\n#[post(\"/types/names/<type_id>\", format = \"application/json\", data = \"<data>\")]\n\npub fn post_type_name(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<TypeNameRequest>, JsonError>,\n\n type_id: u8,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_type_names_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let type_name = TypeName {\n\n name: ROMString::from(data.get_name()),\n\n };\n\n\n\n let patch = db.set_type_name(&type_id, &type_name)?;\n\n\n\n utils::insert_rom_patch(\n\n sql,\n\n connection,\n\n access_token,\n\n patch,\n\n patch_description,\n\n BaseErrorResponseId::error_type_names,\n\n )?;\n\n\n\n Ok(status::Accepted(Some(json!({}))))\n\n}\n", "file_path": "pkmnapi-api/src/routes/type_names.rs", "rank": 60, "score": 138960.33850039946 }, { "content": "#[openapi]\n\n#[post(\"/tms/prices/<tm_id>\", format = \"application/json\", data = \"<data>\")]\n\npub fn post_tm_price(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<TMPriceRequest>, JsonError>,\n\n tm_id: u8,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_tm_prices_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let tm_price = TMPrice {\n\n value: data.get_price(),\n\n };\n\n\n\n let patch = db.set_tm_price(&tm_id, &tm_price)?;\n\n\n\n utils::insert_rom_patch(\n\n sql,\n\n connection,\n\n access_token,\n\n patch,\n\n patch_description,\n\n BaseErrorResponseId::error_tm_prices,\n\n )?;\n\n\n\n Ok(status::Accepted(Some(json!({}))))\n\n}\n", "file_path": "pkmnapi-api/src/routes/tm_prices.rs", "rank": 61, "score": 138960.33850039946 }, { "content": "#[openapi]\n\n#[get(\"/pokemon/cries\", format = \"application/json\")]\n\npub fn get_pokemon_cry_all(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<PokemonCryResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let (min_pokedex_id, max_pokedex_id) = db.pokedex_id_bounds();\n\n let pokedex_ids: Vec<u8> = (min_pokedex_id..=max_pokedex_id)\n\n .map(|pokedex_id| pokedex_id as u8)\n\n .collect();\n\n let pokemon_cries = db.get_pokemon_cry_all(&pokedex_ids)?;\n\n\n\n let response = PokemonCryResponseAll::new(&pokedex_ids, &pokemon_cries);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/pokemon_cries.rs", "rank": 62, "score": 138954.154898198 }, { "content": "#[openapi]\n\n#[get(\"/roms/patches\", format = \"application/json\", rank = 1)]\n\npub fn get_rom_patches(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<RomPatchResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n\n\n let connection = sql.get_connection().unwrap();\n\n let patches = match sql.select_rom_patches_by_access_token(&connection, &access_token) {\n\n Ok(patches) => patches,\n\n Err(_) => return Err(RomErrorNoRom::new()),\n\n };\n\n\n\n let response = RomPatchResponseAll::new(&patches);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/rom_patches.rs", "rank": 63, "score": 138954.0793763084 }, { "content": "pub fn post_pokemon_moveset(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<PokemonMovesetRequest>, JsonError>,\n\n pokedex_id: u8,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_pokemon_movesets_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let pokemon_moveset = data.get_moveset();\n\n\n\n let patch = db.set_pokemon_moveset(&pokedex_id, &pokemon_moveset)?;\n\n\n\n utils::insert_rom_patch(\n\n sql,\n\n connection,\n\n access_token,\n\n patch,\n\n patch_description,\n\n BaseErrorResponseId::error_pokemon_movesets,\n\n )?;\n\n\n\n Ok(status::Accepted(Some(json!({}))))\n\n}\n", "file_path": "pkmnapi-api/src/routes/pokemon_movesets.rs", "rank": 64, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/hms/moves/<hm_id>\")]\n\npub fn get_hm_move(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n hm_id: u8,\n\n) -> Result<Json<HMMoveResponse>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let hm_move = db.get_hm_move(&hm_id)?;\n\n let move_name = db.get_move_name(&hm_move.move_id)?;\n\n\n\n let response = HMMoveResponse::new(&hm_id, &hm_move, &move_name);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/hm_moves.rs", "rank": 65, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/maps/pokemon/<map_id>\")]\n\npub fn get_map_pokemon(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n map_id: u8,\n\n) -> Result<Json<MapPokemonResponse>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let map_pokemon = db.get_map_pokemon(&map_id)?;\n\n let pokedex_ids = vec![\n\n map_pokemon\n\n .grass\n\n .pokemon\n\n .iter()\n\n .map(|pokemon| pokemon.pokedex_id)\n\n .collect::<Vec<u8>>(),\n\n map_pokemon\n\n .water\n\n .pokemon\n", "file_path": "pkmnapi-api/src/routes/map_pokemon.rs", "rank": 66, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/pokemon/icons/<pokedex_id>\")]\n\npub fn get_pokemon_icon(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n pokedex_id: u8,\n\n) -> Result<Json<PokemonIconResponse>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let pokemon_icon = db.get_pokemon_icon(&pokedex_id)?;\n\n\n\n let response = PokemonIconResponse::new(&pokedex_id, &pokemon_icon);\n\n\n\n Ok(Json(response))\n\n}\n\n\n\n#[openapi]\n\n#[post(\n\n \"/pokemon/icons/<pokedex_id>\",\n\n format = \"application/json\",\n\n data = \"<data>\"\n\n)]\n", "file_path": "pkmnapi-api/src/routes/pokemon_icons.rs", "rank": 67, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/pokemon/movesets\")]\n\npub fn get_pokemon_moveset_all(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<PokemonMovesetResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let (min_pokedex_id, max_pokedex_id) = db.pokedex_id_bounds();\n\n let pokedex_ids: Vec<u8> = (min_pokedex_id..=max_pokedex_id)\n\n .map(|pokedex_id| pokedex_id as u8)\n\n .collect();\n\n let pokemon_movesets = db.get_pokemon_moveset_all(&pokedex_ids)?;\n\n let move_ids = pokemon_movesets\n\n .iter()\n\n .map(|(_, pokemon_moveset)| pokemon_moveset.to_vec())\n\n .flatten()\n\n .collect();\n\n let move_names = db.get_move_name_all(&move_ids)?;\n\n\n\n let response = PokemonMovesetResponseAll::new(&pokedex_ids, &pokemon_movesets, &move_names);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/pokemon_movesets.rs", "rank": 68, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/hms/moves\")]\n\npub fn get_hm_move_all(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<HMMoveResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let (min_hm_id, max_hm_id) = db.hm_id_bounds();\n\n let hm_ids: Vec<u8> = (min_hm_id..=max_hm_id).map(|hm_id| hm_id as u8).collect();\n\n let hm_moves = db.get_hm_move_all(&hm_ids)?;\n\n let move_ids: Vec<u8> = hm_moves.iter().map(|(_, hm)| hm.move_id).collect();\n\n let move_names = db.get_move_name_all(&move_ids)?;\n\n\n\n let response = HMMoveResponseAll::new(&hm_ids, &hm_moves, &move_names);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/hm_moves.rs", "rank": 69, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/pokemon/machines/<pokedex_id>\")]\n\npub fn get_pokemon_machines(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n pokedex_id: u8,\n\n) -> Result<Json<PokemonMachinesResponse>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let pokemon_machines = db.get_pokemon_machines(&pokedex_id)?;\n\n let tm_ids = pokemon_machines\n\n .iter()\n\n .filter_map(|machine| match machine {\n\n PokemonMachine::TM(tm_id) => Some(*tm_id),\n\n _ => None,\n\n })\n\n .collect();\n\n let tm_moves = db.get_tm_move_all(&tm_ids)?;\n\n let hm_ids = pokemon_machines\n\n .iter()\n", "file_path": "pkmnapi-api/src/routes/pokemon_machines.rs", "rank": 70, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/pokedex/entries\")]\n\npub fn get_pokedex_entry_all(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<PokedexEntryResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let (min_pokedex_id, max_pokedex_id) = db.pokedex_id_bounds();\n\n let pokedex_ids: Vec<u8> = (min_pokedex_id..=max_pokedex_id)\n\n .map(|pokedex_id| pokedex_id as u8)\n\n .collect();\n\n let pokedex_entries = db.get_pokedex_entry_all(&pokedex_ids)?;\n\n\n\n let response = PokedexEntryResponseAll::new(&pokedex_ids, &pokedex_entries);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/pokedex_entries.rs", "rank": 71, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/moves/names/<move_id>\")]\n\npub fn get_move_name(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n move_id: u8,\n\n) -> Result<Json<MoveNameResponse>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let move_name = db.get_move_name(&move_id)?;\n\n\n\n let response = MoveNameResponse::new(&move_id, &move_name);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/move_names.rs", "rank": 72, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/moves/stats\")]\n\npub fn get_move_stats_all(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<MoveStatsResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let (min_move_id, max_move_id) = db.move_id_bounds();\n\n let move_ids: Vec<u8> = (min_move_id..=max_move_id)\n\n .map(|move_id| move_id as u8)\n\n .collect();\n\n let move_stats = db.get_move_stats_all(&move_ids)?;\n\n let type_ids = move_stats\n\n .iter()\n\n .map(|(_, move_stats)| move_stats.type_id)\n\n .collect();\n\n let type_names = db.get_type_name_all(&type_ids)?;\n\n\n\n let response = MoveStatsResponseAll::new(&move_ids, &move_stats, &type_names);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/move_stats.rs", "rank": 73, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/pokemon/stats/<pokedex_id>\")]\n\npub fn get_pokemon_stats(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n pokedex_id: u8,\n\n) -> Result<Json<PokemonStatsResponse>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let pokemon_stats = db.get_pokemon_stats(&pokedex_id)?;\n\n let type_names = db.get_type_name_all(&pokemon_stats.type_ids)?;\n\n\n\n let response = PokemonStatsResponse::new(&pokedex_id, &pokemon_stats, &type_names);\n\n\n\n Ok(Json(response))\n\n}\n\n\n\n#[openapi]\n\n#[post(\n\n \"/pokemon/stats/<pokedex_id>\",\n\n format = \"application/json\",\n\n data = \"<data>\"\n\n)]\n", "file_path": "pkmnapi-api/src/routes/pokemon_stats.rs", "rank": 74, "score": 138948.260230655 }, { "content": "pub fn post_pokemon_icon(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<PokemonIconRequest>, JsonError>,\n\n pokedex_id: u8,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_pokemon_icons_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let pokemon_icon = PokemonIcon::from(&data.get_icon_id());\n\n\n\n let patch = db.set_pokemon_icon(&pokedex_id, &pokemon_icon)?;\n\n\n\n utils::insert_rom_patch(\n\n sql,\n\n connection,\n\n access_token,\n\n patch,\n\n patch_description,\n\n BaseErrorResponseId::error_pokemon_icons,\n\n )?;\n\n\n\n Ok(status::Accepted(Some(json!({}))))\n\n}\n", "file_path": "pkmnapi-api/src/routes/pokemon_icons.rs", "rank": 75, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/pokedex/entries/<pokedex_id>\")]\n\npub fn get_pokedex_entry(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n pokedex_id: u8,\n\n) -> Result<Json<PokedexEntryResponse>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let pokedex_entry = db.get_pokedex_entry(&pokedex_id)?;\n\n\n\n let response = PokedexEntryResponse::new(&pokedex_id, &pokedex_entry);\n\n\n\n Ok(Json(response))\n\n}\n\n\n\n#[openapi]\n\n#[post(\n\n \"/pokedex/entries/<pokedex_id>\",\n\n format = \"application/json\",\n\n data = \"<data>\"\n\n)]\n", "file_path": "pkmnapi-api/src/routes/pokedex_entries.rs", "rank": 76, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/items/names\")]\n\npub fn get_item_name_all(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<ItemNameResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let (min_item_id, max_item_id) = db.item_id_bounds();\n\n let item_ids: Vec<u8> = (min_item_id..=max_item_id)\n\n .map(|item_id| item_id as u8)\n\n .collect();\n\n let item_names = db.get_item_name_all(&item_ids)?;\n\n\n\n let response = ItemNameResponseAll::new(&item_ids, &item_names);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/item_names.rs", "rank": 77, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/pokedex/texts\")]\n\npub fn get_pokedex_text_all(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<PokedexTextResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let (min_pokedex_id, max_pokedex_id) = db.pokedex_id_bounds();\n\n let pokedex_ids: Vec<u8> = (min_pokedex_id..=max_pokedex_id)\n\n .map(|pokedex_id| pokedex_id as u8)\n\n .collect();\n\n let pokedex_texts = db.get_pokedex_text_all(&pokedex_ids)?;\n\n\n\n let response = PokedexTextResponseAll::new(&pokedex_ids, &pokedex_texts);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/pokedex_texts.rs", "rank": 78, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/pokemon/names/<pokedex_id>\")]\n\npub fn get_pokemon_name(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n pokedex_id: u8,\n\n) -> Result<Json<PokemonNameResponse>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let pokemon_name = db.get_pokemon_name(&pokedex_id)?;\n\n\n\n let response = PokemonNameResponse::new(&pokedex_id, &pokemon_name);\n\n\n\n Ok(Json(response))\n\n}\n\n\n\n#[openapi]\n\n#[post(\n\n \"/pokemon/names/<pokedex_id>\",\n\n format = \"application/json\",\n\n data = \"<data>\"\n\n)]\n", "file_path": "pkmnapi-api/src/routes/pokemon_names.rs", "rank": 79, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/moves/names\")]\n\npub fn get_move_name_all(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<MoveNameResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let (min_move_id, max_move_id) = db.move_id_bounds();\n\n let move_ids: Vec<u8> = (min_move_id..=max_move_id)\n\n .map(|move_id| move_id as u8)\n\n .collect();\n\n let move_names = db.get_move_name_all(&move_ids)?;\n\n\n\n let response = MoveNameResponseAll::new(&move_ids, &move_names);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/move_names.rs", "rank": 80, "score": 138948.260230655 }, { "content": "pub fn post_pokedex_text(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<PokedexTextRequest>, JsonError>,\n\n pokedex_id: u8,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_pokedex_texts_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let pokedex_text = PokedexText {\n\n text: ROMString::from(data.get_text()),\n\n };\n\n\n\n let patch = db.set_pokedex_text(&pokedex_id, &pokedex_text)?;\n\n\n\n utils::insert_rom_patch(\n\n sql,\n\n connection,\n\n access_token,\n\n patch,\n\n patch_description,\n\n BaseErrorResponseId::error_pokedex_texts,\n\n )?;\n\n\n\n Ok(status::Accepted(Some(json!({}))))\n\n}\n", "file_path": "pkmnapi-api/src/routes/pokedex_texts.rs", "rank": 81, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/pokemon/icons\")]\n\npub fn get_pokemon_icon_all(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<PokemonIconResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let (min_pokedex_id, max_pokedex_id) = db.pokedex_id_bounds();\n\n let pokedex_ids: Vec<u8> = (min_pokedex_id..=max_pokedex_id)\n\n .map(|pokedex_id| pokedex_id as u8)\n\n .collect();\n\n let pokemon_icons = db.get_pokemon_icon_all(&pokedex_ids)?;\n\n\n\n let response = PokemonIconResponseAll::new(&pokedex_ids, &pokemon_icons);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/pokemon_icons.rs", "rank": 82, "score": 138948.260230655 }, { "content": "pub fn post_pokedex_entry(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<PokedexEntryRequest>, JsonError>,\n\n pokedex_id: u8,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_pokedex_entries_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let pokedex_entry = PokedexEntry {\n\n species: ROMString::from(data.get_species()),\n\n height: data.get_height(),\n\n weight: data.get_weight(),\n\n };\n\n\n\n let patch = db.set_pokedex_entry(&pokedex_id, &pokedex_entry)?;\n\n\n", "file_path": "pkmnapi-api/src/routes/pokedex_entries.rs", "rank": 83, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/marts/items\")]\n\npub fn get_mart_items_all(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<MartItemsResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let (min_mart_id, max_mart_id) = db.mart_id_bounds();\n\n let mart_ids: Vec<u8> = (min_mart_id..=max_mart_id)\n\n .map(|mart_id| mart_id as u8)\n\n .collect();\n\n let mart_items = db.get_mart_items_all(&mart_ids)?;\n\n let item_ids = mart_items\n\n .iter()\n\n .map(|(_, mart_item)| mart_item)\n\n .flatten()\n\n .filter_map(|mart_item| match mart_item {\n\n MartItem::ITEM(item_id) => Some(*item_id),\n\n _ => None,\n", "file_path": "pkmnapi-api/src/routes/mart_items.rs", "rank": 84, "score": 138948.260230655 }, { "content": "pub fn post_pokemon_stats(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<PokemonStatsRequest>, JsonError>,\n\n pokedex_id: u8,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_pokemon_stats_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let pokemon_stats = PokemonStats {\n\n pokedex_id: pokedex_id,\n\n base_hp: data.get_base_hp(),\n\n base_attack: data.get_base_attack(),\n\n base_defence: data.get_base_defence(),\n\n base_speed: data.get_base_speed(),\n\n base_special: data.get_base_special(),\n\n type_ids: data.get_type_ids(),\n", "file_path": "pkmnapi-api/src/routes/pokemon_stats.rs", "rank": 85, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/pokemon/learnsets\")]\n\npub fn get_pokemon_learnset_all(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<PokemonLearnsetResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let (min_pokedex_id, max_pokedex_id) = db.pokedex_id_bounds();\n\n let pokedex_ids: Vec<u8> = (min_pokedex_id..=max_pokedex_id)\n\n .map(|pokedex_id| pokedex_id as u8)\n\n .collect();\n\n let pokemon_learnsets = db.get_pokemon_learnset_all(&pokedex_ids)?;\n\n let move_ids = pokemon_learnsets\n\n .iter()\n\n .map(|(_, pokemon_learnset)| pokemon_learnset)\n\n .flatten()\n\n .map(|learnset| learnset.move_id)\n\n .collect();\n\n let move_names = db.get_move_name_all(&move_ids)?;\n\n\n\n let response = PokemonLearnsetResponseAll::new(&pokedex_ids, &pokemon_learnsets, &move_names);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/pokemon_learnsets.rs", "rank": 86, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/hms/names\")]\n\npub fn get_hm_name_all(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<HMNameResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let (min_hm_id, max_hm_id) = db.hm_id_bounds();\n\n let hm_ids: Vec<u8> = (min_hm_id..=max_hm_id).map(|hm_id| hm_id as u8).collect();\n\n let hm_names = db.get_hm_name_all(&hm_ids)?;\n\n\n\n let response = HMNameResponseAll::new(&hm_ids, &hm_names);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/hm_names.rs", "rank": 87, "score": 138948.260230655 }, { "content": "pub fn post_pokemon_name(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<PokemonNameRequest>, JsonError>,\n\n pokedex_id: u8,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_pokemon_names_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let pokemon_name = PokemonName {\n\n name: ROMString::from(data.get_name()),\n\n };\n\n\n\n let patch = db.set_pokemon_name(&pokedex_id, &pokemon_name)?;\n\n\n\n utils::insert_rom_patch(\n\n sql,\n\n connection,\n\n access_token,\n\n patch,\n\n patch_description,\n\n BaseErrorResponseId::error_pokemon_names,\n\n )?;\n\n\n\n Ok(status::Accepted(Some(json!({}))))\n\n}\n", "file_path": "pkmnapi-api/src/routes/pokemon_names.rs", "rank": 88, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/pokemon/machines\")]\n\npub fn get_pokemon_machines_all(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<PokemonMachinesResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let (min_pokedex_id, max_pokedex_id) = db.pokedex_id_bounds();\n\n let pokedex_ids: Vec<u8> = (min_pokedex_id..=max_pokedex_id)\n\n .map(|pokedex_id| pokedex_id as u8)\n\n .collect();\n\n let pokemon_machines = db.get_pokemon_machines_all(&pokedex_ids)?;\n\n let tm_ids = pokemon_machines\n\n .iter()\n\n .map(|(_, machine)| machine)\n\n .flatten()\n\n .filter_map(|machine| match machine {\n\n PokemonMachine::TM(tm_id) => Some(*tm_id),\n\n _ => None,\n", "file_path": "pkmnapi-api/src/routes/pokemon_machines.rs", "rank": 89, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/hms/names/<hm_id>\")]\n\npub fn get_hm_name(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n hm_id: u8,\n\n) -> Result<Json<HMNameResponse>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let hm_name = db.get_hm_name(&hm_id)?;\n\n\n\n let response = HMNameResponse::new(&hm_id, &hm_name);\n\n\n\n Ok(Json(response))\n\n}\n", "file_path": "pkmnapi-api/src/routes/hm_names.rs", "rank": 90, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/maps/pokemon\")]\n\npub fn get_map_pokemon_all(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<MapPokemonResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let (min_map_id, max_map_id) = db.map_id_bounds();\n\n let map_ids = (min_map_id..=max_map_id)\n\n .map(|map_id| map_id as u8)\n\n .collect();\n\n let map_pokemon = db.get_map_pokemon_all(&map_ids)?;\n\n let pokedex_ids = map_pokemon\n\n .iter()\n\n .map(|(_, map_pokemon)| {\n\n vec![\n\n map_pokemon\n\n .grass\n\n .pokemon\n", "file_path": "pkmnapi-api/src/routes/map_pokemon.rs", "rank": 91, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/pokemon/names\")]\n\npub fn get_pokemon_name_all(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<PokemonNameResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let (min_pokedex_id, max_pokedex_id) = db.pokedex_id_bounds();\n\n let pokedex_ids: Vec<u8> = (min_pokedex_id..=max_pokedex_id)\n\n .map(|pokedex_id| pokedex_id as u8)\n\n .collect();\n\n let pokemon_names = db.get_pokemon_name_all(&pokedex_ids)?;\n\n\n\n let response = PokemonNameResponseAll::new(&pokedex_ids, &pokemon_names);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/pokemon_names.rs", "rank": 92, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/items/names/<item_id>\")]\n\npub fn get_item_name(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n item_id: u8,\n\n) -> Result<Json<ItemNameResponse>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let item_name = db.get_item_name(&item_id)?;\n\n\n\n let response = ItemNameResponse::new(&item_id, &item_name);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/item_names.rs", "rank": 93, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/marts/items/<mart_id>\")]\n\npub fn get_mart_items(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n mart_id: u8,\n\n) -> Result<Json<MartItemsResponse>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let mart_items = db.get_mart_items(&mart_id)?;\n\n let item_ids = mart_items\n\n .iter()\n\n .filter_map(|mart_item| match mart_item {\n\n MartItem::ITEM(item_id) => Some(*item_id),\n\n _ => None,\n\n })\n\n .collect();\n\n let item_names = db.get_item_name_all(&item_ids)?;\n\n let tm_ids = mart_items\n\n .iter()\n", "file_path": "pkmnapi-api/src/routes/mart_items.rs", "rank": 94, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/moves/stats/<move_id>\")]\n\npub fn get_move_stats(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n move_id: u8,\n\n) -> Result<Json<MoveStatsResponse>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let move_stats = db.get_move_stats(&move_id)?;\n\n let type_name = db.get_type_name(&move_stats.type_id)?;\n\n\n\n let response = MoveStatsResponse::new(&move_id, &move_stats, &type_name);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/move_stats.rs", "rank": 95, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/pokedex/texts/<pokedex_id>\")]\n\npub fn get_pokedex_text(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n pokedex_id: u8,\n\n) -> Result<Json<PokedexTextResponse>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let pokedex_text = db.get_pokedex_text(&pokedex_id)?;\n\n\n\n let response = PokedexTextResponse::new(&pokedex_id, &pokedex_text);\n\n\n\n Ok(Json(response))\n\n}\n\n\n\n#[openapi]\n\n#[post(\n\n \"/pokedex/texts/<pokedex_id>\",\n\n format = \"application/json\",\n\n data = \"<data>\"\n\n)]\n", "file_path": "pkmnapi-api/src/routes/pokedex_texts.rs", "rank": 96, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/pokemon/movesets/<pokedex_id>\")]\n\npub fn get_pokemon_moveset(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n pokedex_id: u8,\n\n) -> Result<Json<PokemonMovesetResponse>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let pokemon_moveset = db.get_pokemon_moveset(&pokedex_id)?;\n\n let move_names = db.get_move_name_all(&pokemon_moveset)?;\n\n\n\n let response = PokemonMovesetResponse::new(&pokedex_id, &pokemon_moveset, &move_names);\n\n\n\n Ok(Json(response))\n\n}\n\n\n\n#[openapi]\n\n#[post(\n\n \"/pokemon/movesets/<pokedex_id>\",\n\n format = \"application/json\",\n\n data = \"<data>\"\n\n)]\n", "file_path": "pkmnapi-api/src/routes/pokemon_movesets.rs", "rank": 97, "score": 138948.260230655 }, { "content": "#[openapi]\n\n#[get(\"/pokemon/stats\")]\n\npub fn get_pokemon_stats_all(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n) -> Result<Json<PokemonStatsResponseAll>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let (db, _) = utils::get_db_with_applied_patches(&sql, &access_token)?;\n\n\n\n let (min_pokedex_id, max_pokedex_id) = db.pokedex_id_bounds();\n\n let pokedex_ids: Vec<u8> = (min_pokedex_id..=max_pokedex_id)\n\n .map(|pokedex_id| pokedex_id as u8)\n\n .collect();\n\n let pokemon_stats = db.get_pokemon_stats_all(&pokedex_ids)?;\n\n let type_ids = pokemon_stats\n\n .iter()\n\n .map(|(_, pokemon_stats)| pokemon_stats.type_ids.to_vec())\n\n .flatten()\n\n .collect();\n\n let type_names = db.get_type_name_all(&type_ids)?;\n\n\n\n let response = PokemonStatsResponseAll::new(&pokedex_ids, &pokemon_stats, &type_names);\n\n\n\n Ok(Json(response))\n\n}\n\n\n", "file_path": "pkmnapi-api/src/routes/pokemon_stats.rs", "rank": 98, "score": 138948.260230655 }, { "content": "pub fn post_pokemon_machines(\n\n sql: State<PkmnapiSQL>,\n\n _rate_limit: RateLimit,\n\n access_token: Result<AccessToken, AccessTokenError>,\n\n patch_description: Result<PatchDescription, PatchDescriptionError>,\n\n data: Result<Json<PokemonMachinesRequest>, JsonError>,\n\n pokedex_id: u8,\n\n) -> Result<status::Accepted<JsonValue>, ResponseError> {\n\n let access_token = utils::get_access_token(access_token)?;\n\n let data = utils::get_data(data, BaseErrorResponseId::error_pokemon_machines_invalid)?;\n\n let (db, connection) = utils::get_db(&sql, &access_token)?;\n\n\n\n let pokemon_machines = data.get_machines();\n\n\n\n let patch = db.set_pokemon_machines(&pokedex_id, &pokemon_machines)?;\n\n\n\n utils::insert_rom_patch(\n\n sql,\n\n connection,\n\n access_token,\n\n patch,\n\n patch_description,\n\n BaseErrorResponseId::error_pokemon_machines,\n\n )?;\n\n\n\n Ok(status::Accepted(Some(json!({}))))\n\n}\n", "file_path": "pkmnapi-api/src/routes/pokemon_machines.rs", "rank": 99, "score": 138948.260230655 } ]
Rust
yarte_codegen/src/wasm/client/each.rs
dskleingeld/yarte
f3cd2db21fc4c64f74ef08f988357a282defee96
use std::{collections::HashSet, iter}; use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::{parse2, Expr, Ident}; use yarte_dom::dom::{Each, ExprId, VarId}; use super::{ component::get_component, state::{InsertPath, Len, Parent, State, Step}, utils::*, BlackBox, WASMCodeGen, }; impl<'a> WASMCodeGen<'a> { #[inline] pub(super) fn gen_each( &mut self, id: ExprId, Each { args, body, expr, var, }: Each, fragment: bool, last: bool, insert_point: &[InsertPath], ) { let current_bb = self.current_bb(); let (key, index) = var; let var_id = vec![key]; let mut var_id_index = vec![key]; let mut bases = HashSet::new(); bases.insert(key); if let Some(index) = index { var_id_index.push(index); bases.insert(index); } let parent_id = if fragment { self.parent_node() } else { self.stack.last().steps.len() }; self.stack.push(State { id: Parent::Expr(id), bases, parent_id, current_bb, ..Default::default() }); let component = get_component(id, body.iter(), self); self.cur_mut().component = Some(component); self.step(body); let vdom = get_vdom_ident(id); let component_ty = get_component_ty_ident(id); let table = get_table_ident(id); let table_dom = get_table_dom_ident(id); let mut curr = self.stack.pop(); let old_on = self.stack.last().id; let (base, _) = self.bb_t_root(var_id.into_iter()); curr.add_t_root(base); curr.black_box.push(BlackBox { doc: "root dom element".to_string(), name: get_field_root_ident(), ty: parse2(quote!(yarte_wasm_app::web::Element)).unwrap(), }); self.helpers.extend(curr.get_black_box(&component_ty)); self.helpers .extend(get_drop(&component_ty, iter::once(get_field_root_ident()))); for (_, path) in curr .path_nodes .iter_mut() .chain(curr.path_events.iter_mut()) { if path.starts_with(&[Step::FirstChild, Step::FirstChild]) { path.remove(0); } else { todo!("multi node expressions"); } } let current_bb = &curr.current_bb; let build_args: TokenStream = quote!(#args) .to_string() .replace("self .", "") .parse() .unwrap(); let build = Self::build_each( &curr, build_args, &expr, &component_ty, &insert_point, &vdom, &table, &table_dom, ); let parent = match old_on { Parent::Expr(id) => { let ident = get_vdom_ident(id); quote!(#ident) } Parent::Body | Parent::Head => quote!(#current_bb.#table_dom), }; let (new, cached) = self.new_each( &curr, curr.component.as_ref().expect("some component"), &component_ty, last, insert_point, &vdom, quote!(#current_bb.#table_dom), Some(parent), ); let render = self.render_each( &curr, new, cached, &args, &expr, fragment, &vdom, quote!(#current_bb.#table), quote!(#current_bb.#table_dom), key, ); let (new, cached) = self.new_each( &curr, curr.component.as_ref().expect("some component"), &component_ty, last, &insert_point, &vdom, quote!(#table_dom), None, ); let mut vars = self.solver.expr_inner_var(&id).clone(); for (i, _) in &curr.buff_render { for j in i { if !var_id_index.contains(&self.solver.var_base(j)) { vars.insert(*j); } } } let last = self.stack.last_mut(); last.buff_render.push((vars, render)); last.buff_build.push(build); last.buff_new.push(if let Some(cached) = cached { quote! { let __cached__ = #cached; let mut #table: Vec<#component_ty> = vec![]; for #expr in #args.skip(__dom_len__) { #table.push({ #new }); } } } else { quote! { let mut #table: Vec<#component_ty> = vec![]; for #expr in #args.skip(__dom_len__) { #table.push({ #new }); } } }); if !curr.path_events.is_empty() { let root = get_field_root_ident(); let steps = get_steps(curr.path_events.iter(), quote!(#vdom.#root)); let hydrate = curr.buff_hydrate; let hydrate = quote! { for (#vdom, #expr) in #current_bb.#table .iter_mut() .zip(#args) { #steps #(#hydrate)* } }; last.buff_hydrate.push(hydrate); } last.path_nodes .push((table_dom.clone(), last.steps[..parent_id].to_vec())); last.black_box.push(BlackBox { doc: "Each Virtual DOM node".to_string(), name: table, ty: parse2(quote!(Vec<#component_ty>)).unwrap(), }); last.black_box.push(BlackBox { doc: "Each DOM Element".to_string(), name: table_dom, ty: parse2(quote!(yarte_wasm_app::web::Element)).unwrap(), }); } fn new_each( &self, curr: &State, component: &Ident, component_ty: &Ident, last: bool, insert_point: &[InsertPath], vdom: &Ident, table_dom: TokenStream, parent: Option<TokenStream>, ) -> (TokenStream, Option<TokenStream>) { let bb = self.global_bb_ident(); let tmp = format_ident!("__tmp__"); let froot = get_field_root_ident(); let steps = get_steps( curr.path_nodes.iter().chain(curr.path_events.iter()), quote!(#tmp), ); let fields = curr.get_black_box_fields(&tmp, false); let (insert_point, cached) = if last { ( quote!(#table_dom.append_child(&#vdom.#froot).unwrap_throw();), None, ) } else { let len: Len = insert_point.into(); let base = len.base as u32 + 1; let mut tokens = quote!(#base); for i in &len.expr { let ident = get_table_ident(*i); if let Some(parent) = &parent { tokens.extend(quote!(+ #parent.#ident.len() as u32)) } else { tokens.extend(quote!(+ #ident.len() as u32)) } } ( quote!(#table_dom.insert_before(&#vdom.#froot, __cached__.as_ref()).unwrap_throw();), Some(if parent.is_some() { quote!(#table_dom.children().item(#tokens + __dom_len__ as u32).map(yarte_wasm_app::JsCast::unchecked_into::<yarte_wasm_app::web::Node>)) } else { quote!(#table_dom.children().item(#tokens).map(yarte_wasm_app::JsCast::unchecked_into::<yarte_wasm_app::web::Node>)) }), ) }; let build = &curr.buff_new; ( quote! { let #tmp = yarte_wasm_app::JsCast::unchecked_into::<yarte_wasm_app::web::Element>(self.#bb.#component .clone_node_with_deep(true) .unwrap_throw()); #steps #(#build)* let #vdom = #component_ty { #fields }; #insert_point #vdom }, cached, ) } #[inline] fn build_each( curr: &State, args: TokenStream, expr: &Expr, component_ty: &Ident, insert_point: &[InsertPath], vdom: &Ident, table: &Ident, table_dom: &Ident, ) -> TokenStream { let froot = get_field_root_ident(); let steps = get_steps(curr.path_nodes.iter(), quote!(#vdom)); let fields = curr.get_black_box_fields(vdom, true); let build = &curr.buff_build; let insert_point = { let len: Len = insert_point.into(); let base = len.base as u32; let mut tokens = quote!(#base); for i in &len.expr { let ident = get_table_ident(*i); tokens.extend(quote!(+ #ident.len() as u32)) } quote!(#table_dom.children().item(#tokens).unwrap_throw()) }; quote! { let mut #table: Vec<#component_ty> = vec![]; for #expr in #args { let #vdom = #table.last().map(|__x__| __x__.#froot.next_element_sibling().unwrap_throw()).unwrap_or_else(|| #insert_point); #steps #(#build)* #table.push(#component_ty { #fields }); } } } #[inline] fn render_each( &self, curr: &State, new: TokenStream, cached: Option<TokenStream>, args: &Expr, expr: &Expr, fragment: bool, vdom: &Ident, table: TokenStream, table_dom: TokenStream, each_base: VarId, ) -> TokenStream { let froot = get_field_root_ident(); let new_block = if let Some(cached) = &cached { quote! { let __cached__ = #cached; for #expr in #args.skip(__dom_len__) { #table.push({ #new }); } } } else { quote! { for #expr in #args.skip(__dom_len__) { #table.push({ #new }); } } }; let render = if curr.buff_render.is_empty() { quote!() } else { let parents = curr.get_render_hash().into_iter().any(|(i, _)| { for j in i { let base = self.solver.var_base(&j); if base != each_base { return true; } } false }); let render = self.render(curr); assert!(!render.is_empty()); if parents { quote! { for (#vdom, #expr) in #table .iter_mut() .zip(#args) { #render #vdom.t_root = yarte_wasm_app::YNumber::zero(); } } } else { quote! { for (#vdom, #expr) in #table .iter_mut() .zip(#args) .filter(|(__d__, _)| yarte_wasm_app::YNumber::neq_zero(__d__.t_root)) { #render #vdom.t_root = yarte_wasm_app::YNumber::zero(); } } } }; let body = quote! { #render if __dom_len__ < __data_len__ { #new_block } else { #table.drain(__data_len__..); } }; let data_len = if true { quote!(let __data_len__ = #args.size_hint().0;) } else { quote!(let __data_len__ = #args.count();) }; if fragment { quote! { let __dom_len__ = #table.len(); #data_len #body } } else { quote! { let __dom_len__ = #table.len(); #data_len; if __data_len__ == 0 { #table_dom.set_text_content(None); #table.clear() } else { #body } } } } }
use std::{collections::HashSet, iter}; use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::{parse2, Expr, Ident}; use yarte_dom::dom::{Each, ExprId, VarId}; use super::{ component::get_component, state::{InsertPath, Len, Parent, State, Step}, utils::*, BlackBox, WASMCodeGen, }; impl<'a> WASMCodeGen<'a> { #[inline] pub(super) fn gen_each( &mut self, id: ExprId, Each { args, body, expr, var, }: Each, fragment: bool, last: bool, insert_point: &[InsertPath], ) { let current_bb = self.current_bb(); let (key, index) = var; let var_id = vec![key]; let mut var_id_index = vec![key]; let mut bases = HashSet::new(); bases.insert(key); if let Some(index) = index { var_id_index.push(index); bases.insert(index); } let parent_id = if fragment { self.parent_node() } else { self.stack.last().steps.len() }; self.stack.push(State { id: Parent::Expr(id), bases, parent_id, current_bb, ..Default::default() }); let component = get_component(id, body.iter(), self); self.cur_mut().component = Some(component); self.step(body); let vdom = get_vdom_ident(id); let component_ty = get_component_ty_ident(id); let table = get_table_ident(id); let table_dom = get_table_dom_ident(id); let mut curr = self.stack.pop(); let old_on = self.stack.last().id; let (base, _) = self.bb_t_root(var_id.into_iter()); curr.add_t_root(base); curr.black_box.push(BlackBox { doc: "root dom element".to_string(), name: get_field_root_ident(), ty: parse2(quote!(yarte_wasm_app::web::Element)).unwrap(), }); self.helpers.extend(curr.get_black_box(&component_ty)); self.helpers .extend(get_drop(&component_ty, iter::once(get_field_root_ident()))); for (_, path) in curr .path_nodes .iter_mut() .chain(curr.path_events.iter_mut()) { if path.starts_with(&[Step::FirstChild, Step::FirstChild]) { path.remove(0); } else { todo!("multi node expressions"); } } let current_bb = &curr.current_bb; let build_args: TokenStream = quote!(#args) .to_string() .replace("self .", "") .parse() .unwrap(); let build = Self::build_each( &curr, build_args, &expr, &component_ty, &insert_point, &vdom, &table, &table_dom, ); let parent = match old_on { Parent::Expr(id) => { let ident = get_vdom_ident(id); quote!(#ident) } Parent::Body | Parent::Head => quote!(#current_bb.#table_dom), }; let (new, cached) = self.new_each( &curr, curr.component.as_ref().expect("some component"), &component_ty, last, insert_point, &vdom, quote!(#current_bb.#table_dom), Some(parent), ); let render = self.render_each( &curr, new, cached, &args, &expr, fragment, &vdom, quote!(#current_bb.#table), quote!(#current_bb.#table_dom), key, ); let (new, cached) = self.new_each( &curr, curr.component.as_ref().expect("some component"), &component_ty, last, &insert_point, &vdom, quote!(#table_dom), None, ); let mut vars = self.solver.expr_inner_var(&id).clone(); for (i, _) in &curr.buff_render { for j in i { if !var_id_index.contains(&self.solver.var_base(j)) { vars.insert(*j); } } } let last = self.stack.last_mut(); last.buff_render.push((vars, render)); last.buff_build.push(build); last.buff_new.push(if let Some(cached) = cached { quote! { let __cached__ = #cached; let mut #table: Vec<#component_ty> = vec![]; for #expr in #args.skip(__dom_len__) { #table.push({ #new }); } } } else { quote! { let mut #table: Vec<#component_ty> = vec![]; for #expr in #args.skip(__dom_len__) { #table.push({ #new }); } } }); if !curr.path_events.is_empty() { let root = get_field_root_ident(); let steps = get_steps(curr.path_events.iter(), quote!(#vdom.#root)); let hydrate = curr.buff_hydrate; let hydrate = quote! { for (#vdom, #expr) in #current_bb.#table .iter_mut() .zip(#args) { #steps #(#hydrate)* } }; last.buff_hydrate.push(hydrate); } last.path_nodes .push((table_dom.clone(), last.steps[..parent_id].to_vec())); last.black_box.push(BlackBox { doc: "Each Virtual DOM node".to_string(), name: table, ty: parse2(quote!(Vec<#component_ty>)).unwrap(), }); last.black_box.push(BlackBox { doc: "Each DOM Element".to_string(), name: table_dom, ty: parse2(quote!(yarte_wasm_app::web::Element)).unwrap(), }); } fn new_each( &self, curr: &State, component: &Ident, component_ty: &Ident, last: bool, insert_point: &[InsertPath], vdom: &Ident, table_dom: TokenStream, parent: Option<TokenStream>, ) -> (TokenStream, Option<TokenStream>) { let bb = self.global_bb_ident(); let tmp = format_ident!("__tmp__"); let froot = get_field_root_ident(); let steps = get_steps( curr.path_nodes.iter().chain(curr.path_events.iter()), quote!(#tmp), ); let fields = curr.get_black_box_fields(&tmp, false); let (insert_point, cached) = if last { ( quote!(#table_dom.append_child(&#vdom.#froot).unwrap_throw();), None, ) } else { let len: Len = insert_point.into(); let base = len.base as u32 + 1; let mut tokens = quote!(#base); for i in &len.expr { let ident = get_table_ident(*i); if let Some(parent) = &parent { tokens.extend(quote!(+ #parent.#ident.len() as u32)) } else { tokens.extend(quote!(+ #ident.len() as u32)) } } ( quote!(#table_dom.insert_before(&#vdom.#froot, __cached__.as_ref()).unwrap_throw();), Some(if parent.is_some() { quote!(#table_dom.children().item(#tokens + __dom_len__ as u32).map(yarte_wasm_app::JsCast::unchecked_into::<yarte_wasm_app::web::Node>)) } else { quote!(#table_dom.children().item(#tokens).map(yarte_wasm_app::JsCast::unchecked_into::<yarte_wasm_app::web::Node>)) }), ) }; let build = &curr.buff_new; ( quote! { let #tmp = yarte_wasm_app::JsCast::unchecked_into::<yarte_wasm_app::web::Element>(self.#bb.#component .clone_node_with_deep(true) .unwrap_throw()); #steps #(#build)* let #vdom = #component_ty { #fields }; #insert_point #vdom }, cached, ) } #[inline] fn build_each( curr: &State, args: TokenStream, expr: &Expr, component_ty: &Ident, insert_point: &[InsertPath], vdom: &Ident, table: &Ident, table_dom: &Ident, ) -> TokenStream { let froot = get_field_root_ident(); let steps = get_steps(curr.path_nodes.iter(), quote!(#vdom)); let fields = curr.get_black_box_fields(vdom, true); let build = &curr.buff_build; let insert_point = { let len: Len = insert_point.into(); let base = len.base as u32; let mut tokens = quote!(#base); for i in &len.expr { let ident = get_table_ident(*i); tokens.extend(quote!(+ #ident.len() as u32)) } quote!(#table_dom.children().item(#tokens).unwrap_throw()) }; quote! { let mut #table: Vec<#component_ty> = vec![]; for #expr in #args { let #vdom = #table.last().map(|__x__| __x__.#froot.next_element_sibling().unwrap_throw()).unwrap_or_else(|| #insert_point); #steps #(#build)* #table.push(#component_ty { #fields }); } } } #[inline] fn render_each( &self, curr: &State, new: TokenStream, cached: Option<TokenStream>, args: &Expr, expr: &Expr, fragment: bool, vdom: &Ident, table: TokenStream, table_dom: TokenStream, each_base: VarId, ) -> TokenStream { let froot = get_field_root_ident(); let new_block = if let Some(cached) = &cached { quote! { let __cached__ = #cached; for #expr in #args.skip(__dom_len__) { #table.push({ #new }); } } } else { quote! { for #expr in #args.skip(__dom_len__) { #table.push({ #new }); } } }; let render = if curr.buff_render.is_empty() { quote!() } else { let parents = curr.get_render_hash().into_iter().any(|(i, _)| { for j in i { let base = self.solver.var_base(&j); if base != each_base { return true; } }
}
false }); let render = self.render(curr); assert!(!render.is_empty()); if parents { quote! { for (#vdom, #expr) in #table .iter_mut() .zip(#args) { #render #vdom.t_root = yarte_wasm_app::YNumber::zero(); } } } else { quote! { for (#vdom, #expr) in #table .iter_mut() .zip(#args) .filter(|(__d__, _)| yarte_wasm_app::YNumber::neq_zero(__d__.t_root)) { #render #vdom.t_root = yarte_wasm_app::YNumber::zero(); } } } }; let body = quote! { #render if __dom_len__ < __data_len__ { #new_block } else { #table.drain(__data_len__..); } }; let data_len = if true { quote!(let __data_len__ = #args.size_hint().0;) } else { quote!(let __data_len__ = #args.count();) }; if fragment { quote! { let __dom_len__ = #table.len(); #data_len #body } } else { quote! { let __dom_len__ = #table.len(); #data_len; if __data_len__ == 0 { #table_dom.set_text_content(None); #table.clear() } else { #body } } } }
function_block-function_prefix_line
[ { "content": "pub fn resolve_if_block<'a>(expr: &'a Expr, id: usize, builder: &'a mut DOMBuilder) -> Vec<VarId> {\n\n ResolveIf::new(builder, id).resolve(expr)\n\n}\n\n\n", "file_path": "yarte_dom/src/dom/resolve.rs", "rank": 0, "score": 414137.18538381014 }, { "content": "#[inline]\n\npub fn get_component_ty_ident(id: ExprId) -> Ident {\n\n const TY: &str = \"YComponent\";\n\n format_ident!(\"{}{}\", TY, id)\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 1, "score": 408357.4633154533 }, { "content": "#[inline]\n\npub fn get_table_dom_ident(id: ExprId) -> Ident {\n\n const TABLE_DOM: &str = \"__ytable_dom__\";\n\n format_ident!(\"{}{}\", TABLE_DOM, id)\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 2, "score": 408125.95136279624 }, { "content": "pub fn resolve_expr<'a>(expr: &'a Expr, builder: &'a mut DOMBuilder) -> Vec<VarId> {\n\n ResolveExpr::new(builder).resolve(expr)\n\n}\n\n\n", "file_path": "yarte_dom/src/dom/resolve.rs", "rank": 3, "score": 405610.81656452577 }, { "content": "#[inline]\n\npub fn get_vdom_ident(id: ExprId) -> Ident {\n\n const ELEM: &str = \"__dom__\";\n\n format_ident!(\"{}{}\", ELEM, id)\n\n}\n\n\n\n#[inline]\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 4, "score": 375531.79158537457 }, { "content": "#[inline]\n\npub fn get_table_ident(id: ExprId) -> Ident {\n\n const TABLE: &str = \"__ytable__\";\n\n format_ident!(\"{}{}\", TABLE, id)\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 5, "score": 375469.21312720847 }, { "content": "#[inline]\n\npub fn get_node_ident(id: ExprId) -> Ident {\n\n const NODE: &str = \"__ynode__\";\n\n format_ident!(\"{}{}\", NODE, id)\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 6, "score": 375466.38787151326 }, { "content": "#[inline]\n\npub fn is_state(Field { attrs, ty, .. }: &Field) -> bool {\n\n !(is_inner(attrs) || is_black_box(ty))\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 7, "score": 365426.19585628825 }, { "content": "pub fn all_children_text<'a, I: Iterator<Item = &'a Node> + Clone>(mut doc: I) -> bool {\n\n !doc.clone().all(|x| {\n\n if let Node::Elem(Element::Text(_)) = x {\n\n true\n\n } else {\n\n false\n\n }\n\n }) && doc.all(|x| match x {\n\n Node::Elem(Element::Text(_)) => true,\n\n Node::Expr(e) => match e {\n\n Expression::IfElse(_, block) => {\n\n let IfElse { ifs, if_else, els } = &**block;\n\n all_if_block_text(ifs)\n\n && if_else.iter().all(|x| all_if_block_text(x))\n\n && els\n\n .as_ref()\n\n .map(|x| all_children_text(x.iter()))\n\n .unwrap_or(true)\n\n }\n\n Expression::Each(_, block) => {\n\n let Each { body, .. } = &**block;\n\n all_children_text(body.iter())\n\n }\n\n Expression::Local(..) => false,\n\n _ => true,\n\n },\n\n _ => false,\n\n })\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 8, "score": 356903.29014134884 }, { "content": "pub fn resolve_local<'a>(expr: &'a Local, id: usize, builder: &'a mut DOMBuilder) -> VarId {\n\n ResolveLocal::new(builder, id).resolve(expr)\n\n}\n\n\n", "file_path": "yarte_dom/src/dom/resolve.rs", "rank": 9, "score": 343773.5975843109 }, { "content": "pub fn get_split_32(mut bits: &[bool]) -> Punctuated<syn::Expr, Token![,]> {\n\n let mut buff = Punctuated::new();\n\n while !bits.is_empty() {\n\n let (current, next) = bits.split_at(32);\n\n bits = next;\n\n let current = get_number_u32(current);\n\n buff.push(parse2(quote!(#current)).unwrap());\n\n }\n\n\n\n buff\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 10, "score": 340610.0975568709 }, { "content": "#[inline]\n\npub fn get_drop<I: Iterator<Item = Ident>>(component: &Ident, roots: I) -> TokenStream {\n\n let mut tokens = TokenStream::new();\n\n for root in roots {\n\n tokens.extend(quote!(self.#root.remove();));\n\n }\n\n quote! {\n\n impl Drop for #component {\n\n fn drop(&mut self) {\n\n #tokens\n\n }\n\n }\n\n }\n\n}\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 11, "score": 339173.3927908804 }, { "content": "fn fields_to_args(f: &Fields, i: &Ident) -> (Punctuated<Ident, Token![,]>, TokenStream) {\n\n let mut pun = Punctuated::new();\n\n match f {\n\n Fields::Named(FieldsNamed { named, .. }) => {\n\n let mut buff: Punctuated<Ident, Token![,]> = Punctuated::new();\n\n for i in named {\n\n let ident = i.ident.as_ref().unwrap();\n\n buff.push(ident.clone());\n\n pun.push(ident.clone());\n\n }\n\n\n\n (pun, quote!(#i { #buff }))\n\n }\n\n Fields::Unnamed(FieldsUnnamed { unnamed, .. }) => {\n\n let mut buff: Punctuated<Ident, Token![,]> = Punctuated::new();\n\n for (c, _) in unnamed.into_iter().enumerate() {\n\n let ident = format_ident!(\"_{}\", c);\n\n buff.push(ident.clone());\n\n pun.push(ident);\n\n }\n\n\n\n (pun, quote!(#i( #buff )))\n\n }\n\n Fields::Unit => (pun, quote!(#i)),\n\n }\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/messages.rs", "rank": 12, "score": 331988.41798061616 }, { "content": "fn _zip(head: &str, expr: &mut Iter<Vec<String>>, buff: &mut Vec<String>) {\n\n if let Some(first) = expr.next() {\n\n for i in first {\n\n let head = head.to_owned() + \" \" + &i;\n\n _zip(&head, &mut expr.clone(), buff)\n\n }\n\n } else {\n\n buff.push(head.into());\n\n }\n\n}\n", "file_path": "yarte_wasm_app/benches/codegen/src/lib.rs", "rank": 13, "score": 325451.1541558801 }, { "content": "pub fn get_insert_point<'b, I: Iterator<Item = &'b Node>>(nodes: I) -> Vec<InsertPath> {\n\n let mut insert = vec![];\n\n // TODO: inline nodes, expressions, ...\n\n for e in nodes {\n\n match e {\n\n Node::Elem(Element::Node { .. }) => insert.push(InsertPath::Before),\n\n Node::Expr(Expression::Each(id, _)) | Node::Expr(Expression::IfElse(id, _)) => {\n\n insert.push(InsertPath::Expr(*id))\n\n }\n\n _ => (),\n\n }\n\n }\n\n\n\n insert\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 14, "score": 311623.82707639 }, { "content": "fn get_children<I: Iterator<Item = ParseNodeId>>(children: I, sink: &mut Sink) -> Vec<TreeElement> {\n\n use ParseElement::*;\n\n let mut tree = vec![];\n\n for child in children {\n\n match sink.nodes.remove(&child).expect(\"Child\") {\n\n Text(mut s) => {\n\n if let Some(TreeElement::Text(last)) = tree.last_mut() {\n\n last.extend(s.drain(..));\n\n } else {\n\n tree.push(TreeElement::Text(s))\n\n }\n\n }\n\n Node {\n\n name,\n\n attrs,\n\n children,\n\n ..\n\n } => tree.push(TreeElement::Node {\n\n name,\n\n attrs,\n", "file_path": "yarte_dom/src/serialize.rs", "rank": 15, "score": 307187.778141371 }, { "content": "pub fn expand_match_token(body: &TokenStream) -> syn::Expr {\n\n let match_token = syn::parse2::<MatchToken>(body.clone());\n\n let ast = expand_match_token_macro(match_token.unwrap());\n\n syn::parse2(ast.into()).unwrap()\n\n}\n\n\n", "file_path": "yarte_html/macros/match_token.rs", "rank": 16, "score": 305247.4278850975 }, { "content": "fn gen<C>(codegen: &mut C, v: Vec<HIR>, parent: &str) -> TokenStream\n\nwhere\n\n C: CodeGen + EachCodeGen + IfElseCodeGen,\n\n{\n\n let mut tokens = TokenStream::new();\n\n let parent = format_ident!(\"{}\", parent);\n\n for i in v {\n\n use HIR::*;\n\n tokens.extend(match i {\n\n Local(a) => quote!(#a),\n\n Lit(a) => literal(a, &parent),\n\n Safe(a) => quote!(buf_cur += &(#a).__render_it_safe(&mut buf[buf_cur..])?;),\n\n Expr(a) => quote!(buf_cur += &(#a).__render_it(&mut buf[buf_cur..])?;),\n\n Each(a) => codegen.gen_each(*a),\n\n IfElse(a) => codegen.gen_if_else(*a),\n\n })\n\n }\n\n tokens\n\n}\n\n\n", "file_path": "yarte_codegen/src/fixed.rs", "rank": 17, "score": 296510.142756877 }, { "content": "/// Push literal at cursor with length\n\nfn eat_lit<'a>(nodes: &mut Vec<SNode<'a>>, i: Cursor<'a>, len: usize) {\n\n let lit = &i.rest[..len];\n\n if !lit.is_empty() {\n\n let (l, lit, r) = trim(lit);\n\n let ins = Span {\n\n lo: i.off + (l.len() as u32),\n\n hi: i.off + ((len - r.len()) as u32),\n\n };\n\n let out = Span {\n\n lo: i.off,\n\n hi: i.off + (len as u32),\n\n };\n\n nodes.push(S(Node::Lit(l, S(lit, ins), r), out));\n\n }\n\n}\n\n\n", "file_path": "yarte_parser/src/lib.rs", "rank": 18, "score": 286351.71563536534 }, { "content": "fn literal(a: String, parent: &Ident) -> TokenStream {\n\n let len = a.len();\n\n let b = a.as_bytes();\n\n // https://github.com/torvalds/linux/blob/master/arch/x86/lib/memcpy_64.S\n\n // https://software.intel.com/content/www/us/en/develop/download/intel-64-and-ia-32-architectures-optimization-reference-manual.html\n\n match len {\n\n 0 => unreachable!(),\n\n // For 1 to 3 bytes, is mostly faster write byte-by-byte\n\n 1..=3 => {\n\n let range: TokenStream = write_bb(b);\n\n quote! {{\n\n #[doc = #a]\n\n __yarte_check_write!(#len, {\n\n #range\n\n buf_cur += #len;\n\n })\n\n }}\n\n }\n\n 4..=15 => {\n\n quote! {{\n", "file_path": "yarte_codegen/src/fixed.rs", "rank": 19, "score": 280424.8333878564 }, { "content": "// TODO: multiple roots\n\npub fn get_field_root_ident() -> Ident {\n\n const ROOT: &str = \"__root\";\n\n format_ident!(\"{}\", ROOT)\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 20, "score": 277893.46342993045 }, { "content": "pub fn get_t_root_type(len: usize) -> (TokenStream, usize) {\n\n match len {\n\n 0..=8 => (quote!(u8), 8),\n\n 9..=16 => (quote!(u16), 16),\n\n 17..=32 => (quote!(u32), 32),\n\n 33..=64 => (quote!(yarte_wasm_app::U64), 64),\n\n 65..=128 => (quote!(yarte_wasm_app::U128), 128),\n\n 129..=256 => (quote!(yarte_wasm_app::U256), 256),\n\n _ => todo!(\"more than 256 variables per context\"),\n\n }\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 21, "score": 270677.11924508424 }, { "content": "/// Eat expression Node\n\nfn expr(i: Cursor, lws: bool) -> PResult<Node> {\n\n match at_helper(i, lws) {\n\n Ok(x) => return Ok(x),\n\n Err(e @ LexError::Fail(..)) => return Err(e),\n\n _ => (),\n\n }\n\n\n\n let mut at = 0;\n\n let (c, rws, s) = loop {\n\n if let Some(j) = i.adv_find(at, '}') {\n\n if 0 < at + j && i.adv_starts_with(at + j - 1, \"~}}\") {\n\n break (i.adv(at + j + 2), true, &i.rest[..at + j - 1]);\n\n } else if i.adv_starts_with(at + j + 1, \"}\") {\n\n break (i.adv(at + j + 2), false, &i.rest[..at + j]);\n\n }\n\n\n\n at += j + 1;\n\n } else {\n\n return Err(LexError::Next(\n\n PError::Expr(DOption::None),\n", "file_path": "yarte_parser/src/lib.rs", "rank": 22, "score": 270426.2344273931 }, { "content": "#[inline]\n\nfn is_tuple_index(ident: &[u8]) -> bool {\n\n 1 < ident.len() && ident[0] == b'_' && ident[1..].iter().all(|x| x.is_ascii_digit())\n\n}\n", "file_path": "yarte_hir/src/lib.rs", "rank": 23, "score": 266299.72368436016 }, { "content": "pub fn get_number_u32(bits: &[bool]) -> u32 {\n\n let mut n = 0;\n\n for (i, b) in bits.iter().enumerate() {\n\n if *b {\n\n n += 1 << i as u32\n\n }\n\n }\n\n n\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 24, "score": 257841.2271885164 }, { "content": "fn gen<C>(codegen: &mut C, v: Vec<HIR>, buf: TokenStream) -> TokenStream\n\nwhere\n\n C: CodeGen + EachCodeGen + IfElseCodeGen,\n\n{\n\n let mut tokens = TokenStream::new();\n\n for i in v {\n\n use HIR::*;\n\n tokens.extend(match i {\n\n Local(a) => quote!(#a),\n\n Lit(a) => literal(a, &buf),\n\n Safe(a) => quote!(&(#a).__render_itb_safe(buf_ref!(#buf));),\n\n Expr(a) => quote!(&(#a).__render_itb(buf_ref!(#buf));),\n\n Each(a) => codegen.gen_each(*a),\n\n IfElse(a) => codegen.gen_if_else(*a),\n\n })\n\n }\n\n tokens\n\n}\n\n\n", "file_path": "yarte_codegen/src/bytes.rs", "rank": 25, "score": 256635.05804513174 }, { "content": "fn resolve_node(ir: HIR, buff: &mut Vec<HIR>, opts: SerializerOpt) -> ParseResult<()> {\n\n match ir {\n\n HIR::Each(each) => {\n\n let HEach { args, body, expr } = *each;\n\n buff.push(HIR::Each(Box::new(HEach {\n\n args,\n\n expr,\n\n body: to_domfmt(body, opts)?,\n\n })))\n\n }\n\n HIR::IfElse(if_else) => {\n\n let HIfElse { ifs, if_else, els } = *if_else;\n\n let mut buf_if_else = vec![];\n\n for (expr, body) in if_else {\n\n buf_if_else.push((expr, to_domfmt(body, opts)?));\n\n }\n\n let els = if let Some(els) = els {\n\n Some(to_domfmt(els, opts)?)\n\n } else {\n\n None\n", "file_path": "yarte_dom/src/dom_fmt.rs", "rank": 26, "score": 255570.6570071935 }, { "content": "// TODO: Fix me!!\n\npub fn get_steps<'b, I: Iterator<Item = &'b PathNode>>(\n\n mut nodes: I,\n\n parent: TokenStream,\n\n) -> TokenStream {\n\n let mut buff = vec![];\n\n let mut stack = vec![];\n\n if let Some((ident, path)) = nodes.next() {\n\n buff.push((parent.clone(), ident.clone(), PathStep(path.iter())));\n\n stack.push((ident, path))\n\n }\n\n for (ident, path) in nodes {\n\n let mut check = true;\n\n for (i, last) in stack.iter().rev() {\n\n if path.starts_with(last) {\n\n // TODO: assert_ne!(last.len(), path.len());\n\n buff.push((\n\n quote!(#i),\n\n ident.clone(),\n\n PathStep(path[last.len()..].iter()),\n\n ));\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 27, "score": 255328.19209467008 }, { "content": "fn add_scripts(s: &Struct, sink: &mut Sink, ir: &mut Vec<HIR>) {\n\n let mut body: Option<usize> = None;\n\n use ParseElement::*;\n\n match sink.nodes.values().next() {\n\n Some(Document(children)) => {\n\n if let Some(Node { name, children, .. }) = sink.nodes.get(&children[0]) {\n\n if let y_name!(\"html\") = name.local {\n\n for i in children {\n\n if let Some(Node { name, .. }) = sink.nodes.get(i) {\n\n if let y_name!(\"body\") = name.local {\n\n body = Some(*i);\n\n }\n\n }\n\n }\n\n }\n\n }\n\n }\n\n _ => panic!(\"Need <!doctype html>\"),\n\n }\n\n\n", "file_path": "yarte_dom/src/dom_fmt.rs", "rank": 28, "score": 252507.06321011594 }, { "content": "fn gen<C>(codegen: &mut C, v: Vec<HIR>) -> TokenStream\n\nwhere\n\n C: CodeGen + EachCodeGen + IfElseCodeGen,\n\n{\n\n let mut tokens = TokenStream::new();\n\n for i in v {\n\n use HIR::*;\n\n tokens.extend(match i {\n\n Local(a) => quote!(#a),\n\n Lit(a) => quote!(_fmt.write_str(#a)?;),\n\n Safe(a) => quote!(&(#a).fmt(_fmt)?;),\n\n Expr(a) => quote!(&(#a).__renders_it(_fmt)?;),\n\n Each(a) => codegen.gen_each(*a),\n\n IfElse(a) => codegen.gen_if_else(*a),\n\n })\n\n }\n\n tokens\n\n}\n\n\n\npub struct HTMLCodeGen;\n", "file_path": "yarte_codegen/src/html.rs", "rank": 29, "score": 251329.97927475793 }, { "content": "#[inline]\n\npub fn is_black_box(ty: &Type) -> bool {\n\n BB_TYPE.with(|black| ty.eq(&black))\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 30, "score": 248939.09332980646 }, { "content": "#[inline]\n\nfn delete(app: &mut Test, id: u32, _addr: &Addr<Test>) {\n\n let index = app.fortunes.iter().position(|x| x.id == id).unwrap();\n\n app.fortunes.remove(index);\n\n // TODO: macro\n\n // TODO: when index\n\n app.black_box.__ytable__1.remove(index);\n\n}\n\n\n", "file_path": "example_wasm/client/src/lib.rs", "rank": 31, "score": 248853.95951726363 }, { "content": "pub fn expand(from: &Path, to: &Path) {\n\n let mut source = String::new();\n\n File::open(from)\n\n .unwrap()\n\n .read_to_string(&mut source)\n\n .unwrap();\n\n let ast = syn::parse_file(&source).expect(\"Parsing rules.rs module\");\n\n let mut m = MatchTokenParser {};\n\n let ast = m.fold_file(ast);\n\n let code = ast\n\n .into_token_stream()\n\n .to_string()\n\n .replace(\"{ \", \"{\\n\")\n\n .replace(\" }\", \"\\n}\");\n\n File::create(to)\n\n .unwrap()\n\n .write_all(code.as_bytes())\n\n .unwrap();\n\n}\n\n\n", "file_path": "yarte_html/macros/match_token.rs", "rank": 32, "score": 247465.6868936246 }, { "content": "pub fn to_wasmfmt(mut ir: Vec<HIR>, s: &Struct) -> ParseResult<Vec<HIR>> {\n\n let html = get_html(&ir);\n\n let sink = match parse_document(&html) {\n\n Ok(mut sink) => {\n\n add_scripts(s, &mut sink, &mut ir);\n\n sink\n\n }\n\n Err(_) => parse_fragment(&html)?,\n\n };\n\n\n\n serialize_domfmt(sink, ir, SerializerOpt { wasm: true })\n\n}\n\n\n", "file_path": "yarte_dom/src/dom_fmt.rs", "rank": 33, "score": 246596.3964430797 }, { "content": "// Helpers\n\nfn build_big_table(size: usize) -> Vec<Vec<usize>> {\n\n let mut table = Vec::with_capacity(size);\n\n for _ in 0..size {\n\n let mut inner = Vec::with_capacity(size);\n\n for i in 0..size {\n\n inner.push(i);\n\n }\n\n table.push(inner);\n\n }\n\n\n\n table\n\n}\n\n\n", "file_path": "benches/src/all.rs", "rank": 34, "score": 244102.35285460937 }, { "content": "#[inline]\n\nfn par(i: Cursor, lws: bool) -> PResult<Node> {\n\n match expr_partial_block(i, lws) {\n\n Ok(x) => Ok(x),\n\n Err(_) => partial(i, lws).map(|(c, p)| (c, Node::Partial(p))),\n\n }\n\n}\n\n\n\n/// Eat partial expression\n", "file_path": "yarte_parser/src/lib.rs", "rank": 35, "score": 242168.98778072908 }, { "content": "#[inline]\n\npub fn get_body_ident() -> Ident {\n\n format_ident!(\"__ybody\")\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 36, "score": 241464.60382482153 }, { "content": "#[inline]\n\npub fn get_t_root_ident() -> Ident {\n\n const T_ROOT: &str = \"t_root\";\n\n format_ident!(\"{}\", T_ROOT)\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 37, "score": 241458.37848605064 }, { "content": "pub fn get_number_u8(bits: Vec<bool>) -> u8 {\n\n let mut n = 0;\n\n for (i, b) in bits.into_iter().enumerate() {\n\n if b {\n\n n += 1 << i as u8\n\n }\n\n }\n\n n\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 38, "score": 236596.23847459292 }, { "content": "pub fn get_number_u16(bits: Vec<bool>) -> u16 {\n\n let mut n = 0;\n\n for (i, b) in bits.into_iter().enumerate() {\n\n if b {\n\n n += 1 << i as u16\n\n }\n\n }\n\n n\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 39, "score": 236596.23847459292 }, { "content": "fn expr_partial_block(c: Cursor, lws: bool) -> PResult<Node> {\n\n do_parse!(\n\n c,\n\n ws >> tag!(PARTIAL_BLOCK) >> rws: end_expr >> (Node::Block((lws, rws)))\n\n )\n\n}\n\n\n", "file_path": "yarte_parser/src/lib.rs", "rank": 40, "score": 235101.23790218367 }, { "content": "fn serialize_domfmt(sink: Sink, mut ir: Vec<HIR>, opts: SerializerOpt) -> ParseResult<Vec<HIR>> {\n\n let mut writer = Vec::new();\n\n serialize(&mut writer, sink.into(), opts).expect(\"some serialize node\");\n\n\n\n let html = String::from_utf8(writer).expect(\"\");\n\n let mut chunks = html.split(MARK).peekable();\n\n\n\n if let Some(first) = chunks.peek() {\n\n if first.is_empty() {\n\n chunks.next();\n\n }\n\n }\n\n let mut ir = ir.drain(..).filter(|x| match x {\n\n HIR::Lit(_) => false,\n\n _ => true,\n\n });\n\n\n\n let mut buff = vec![];\n\n for chunk in chunks {\n\n if chunk.is_empty() {\n", "file_path": "yarte_dom/src/dom_fmt.rs", "rank": 41, "score": 233130.23318307282 }, { "content": "#[inline]\n\nfn _io_big_table<W: std::io::Write>(f: &mut W, table: &Vec<Vec<usize>>) -> std::io::Result<()> {\n\n f.write_all(b\"<table>\")?;\n\n for i in table {\n\n f.write_all(b\"<tr>\")?;\n\n for j in i {\n\n f.write_all(b\"<td>\")?;\n\n write!(f, \"{}\", j)?;\n\n f.write_all(b\"</td>\")?;\n\n }\n\n f.write_all(b\"</tr>\")?;\n\n }\n\n f.write_all(b\"</table>\")\n\n}\n\n\n", "file_path": "benches/src/all.rs", "rank": 42, "score": 230621.97527177812 }, { "content": "/// A constructor for an element.\n\n///\n\n/// # Examples\n\n///\n\n/// Create an element like `<div class=\"test-class-name\"></div>`:\n\npub fn create_element<Sink>(sink: &mut Sink, name: QualName, attrs: Vec<Attribute>) -> Sink::Handle\n\nwhere\n\n Sink: TreeSink,\n\n{\n\n let mut flags = ElementFlags::default();\n\n match name.expanded() {\n\n expanded_name!(html \"template\") => flags.template = true,\n\n expanded_name!(mathml \"annotation-xml\") => {\n\n flags.mathml_annotation_xml_integration_point = attrs.iter().any(|attr| {\n\n attr.name.expanded() == expanded_name!(\"\", \"encoding\")\n\n && (attr.value.eq_ignore_ascii_case(\"text/html\")\n\n || attr.value.eq_ignore_ascii_case(\"application/xhtml+xml\"))\n\n })\n\n }\n\n _ => {}\n\n }\n\n sink.create_element(name, attrs, flags)\n\n}\n\n\n", "file_path": "yarte_html/src/interface.rs", "rank": 43, "score": 230528.2985799085 }, { "content": "pub fn is_marquee(name: &QualName) -> bool {\n\n YARTE_TAG.with(|x| *x.local == *name.local)\n\n}\n\n\n", "file_path": "yarte_html/src/tree_builder/mod.rs", "rank": 44, "score": 221316.08045231982 }, { "content": "pub fn parse_id(s: &str) -> Option<u32> {\n\n if &s[..S_LEN] == S && s[S_LEN..].chars().all(|x| x.is_ascii_hexdigit()) {\n\n u32::from_str_radix(&s[S_LEN..], 16).ok()\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "yarte_html/src/utils.rs", "rank": 45, "score": 220947.16641494058 }, { "content": "fn expand_match_token_macro(match_token: MatchToken) -> TokenStream {\n\n let mut arms = match_token.arms;\n\n let to_be_matched = match_token.ident;\n\n // Handle the last arm specially at the end.\n\n let last_arm = arms.pop().unwrap();\n\n\n\n // Tags we've seen, used for detecting duplicates.\n\n let mut seen_tags: HashSet<Tag> = HashSet::new();\n\n\n\n // Case arms for wildcard matching. We collect these and\n\n // emit them later.\n\n let mut wildcards_patterns: Vec<TokenStream> = Vec::new();\n\n let mut wildcards_expressions: Vec<syn::Expr> = Vec::new();\n\n\n\n // Tags excluded (by an 'else' RHS) from wildcard matching.\n\n let mut wild_excluded_patterns: Vec<TokenStream> = Vec::new();\n\n\n\n let mut arms_code = Vec::new();\n\n\n\n for MatchTokenArm { binding, lhs, rhs } in arms {\n", "file_path": "yarte_html/macros/match_token.rs", "rank": 46, "score": 220692.5703609248 }, { "content": "pub fn get_component<'a, I: Iterator<Item = &'a Node>>(\n\n id: ExprId,\n\n doc: I,\n\n builder: &mut WASMCodeGen,\n\n) -> Ident {\n\n ComponentBuilder::new(id, builder).build(doc)\n\n}\n\n\n\nconst HEAD: &str = \"__n__\";\n\n\n", "file_path": "yarte_codegen/src/wasm/client/component.rs", "rank": 47, "score": 219831.44353178793 }, { "content": "#[allow(unused_variables)]\n\nfn get_closure(msg: &syn::Expr) -> (TokenStream, TokenStream) {\n\n use syn::Expr::*;\n\n let (msg, cloned) = match msg {\n\n Path(ExprPath { attrs, qself, path }) => (quote!(#msg), quote!()),\n\n Call(ExprCall {\n\n attrs, func, args, ..\n\n }) => {\n\n let mut new: Punctuated<Ident, Token![,]> = Punctuated::new();\n\n let mut cloned = TokenStream::new();\n\n for (count, arg) in args.iter().enumerate() {\n\n let ident = format_ident!(\"__cloned__{}\", count);\n\n cloned.extend(quote!(let #ident = (#arg).clone();));\n\n new.push(ident);\n\n }\n\n (quote!(#func(#new)), cloned)\n\n }\n\n Struct(ExprStruct {\n\n attrs,\n\n path,\n\n fields,\n", "file_path": "yarte_codegen/src/wasm/client/events.rs", "rank": 48, "score": 219640.31919343869 }, { "content": "pub fn get_mark_id(s: &str) -> Option<u32> {\n\n if is_mark(s) {\n\n u32::from_str_radix(&s[MARK_LEN + S_LEN..], 16).ok()\n\n } else {\n\n None\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\n#[allow(non_snake_case)]\n\nmod test {\n\n use super::{is_ascii_alnum, lower_ascii_letter};\n\n use mac::test_eq;\n\n\n\n test_eq!(lower_letter_a_is_a, lower_ascii_letter('a'), Some('a'));\n\n test_eq!(lower_letter_A_is_a, lower_ascii_letter('A'), Some('a'));\n\n test_eq!(lower_letter_symbol_is_None, lower_ascii_letter('!'), None);\n\n test_eq!(\n\n lower_letter_nonascii_is_None,\n\n lower_ascii_letter('\\u{a66e}'),\n\n None\n\n );\n\n\n\n test_eq!(is_alnum_a, is_ascii_alnum('a'), true);\n\n test_eq!(is_alnum_A, is_ascii_alnum('A'), true);\n\n test_eq!(is_alnum_1, is_ascii_alnum('1'), true);\n\n test_eq!(is_not_alnum_symbol, is_ascii_alnum('!'), false);\n\n test_eq!(is_not_alnum_nonascii, is_ascii_alnum('\\u{a66e}'), false);\n\n}\n", "file_path": "yarte_html/src/utils.rs", "rank": 49, "score": 217216.59898790787 }, { "content": "#[inline(always)]\n\npub fn default_scope(name: ExpandedName) -> bool {\n\n html_default_scope(name)\n\n || mathml_text_integration_point(name)\n\n || svg_html_integration_point(name)\n\n}\n\n\n\ndeclare_tag_set!(pub list_item_scope = [default_scope] + \"ol\" \"ul\");\n\ndeclare_tag_set!(pub button_scope = [default_scope] + \"button\");\n\n\n\ndeclare_tag_set!(pub cursory_implied_end =\n\n \"dd\" \"dt\" \"li\" \"option\" \"optgroup\" \"p\" \"rb\" \"rp\" \"rt\" \"rtc\");\n\n\n\ndeclare_tag_set!(pub heading_tag = \"h1\" \"h2\" \"h3\" \"h4\" \"h5\" \"h6\");\n\n\n\ndeclare_tag_set!(pub special_tag =\n\n \"address\" \"applet\" \"area\" \"article\" \"aside\" \"base\" \"basefont\" \"bgsound\" \"blockquote\" \"body\"\n\n \"br\" \"button\" \"caption\" \"center\" \"col\" \"colgroup\" \"dd\" \"details\" \"dir\" \"div\" \"dl\" \"dt\" \"embed\"\n\n \"fieldset\" \"figcaption\" \"figure\" \"footer\" \"form\" \"frame\" \"frameset\" \"h1\" \"h2\" \"h3\" \"h4\" \"h5\"\n\n \"h6\" \"head\" \"header\" \"hgroup\" \"hr\" \"html\" \"iframe\" \"img\" \"input\" \"isindex\" \"li\" \"link\"\n\n \"listing\" \"main\" \"marquee\" \"menu\" \"meta\" \"nav\" \"noembed\" \"noframes\" \"noscript\"\n\n \"object\" \"ol\" \"p\" \"param\" \"plaintext\" \"pre\" \"script\" \"section\" \"select\" \"source\" \"style\"\n\n \"summary\" \"table\" \"tbody\" \"td\" \"template\" \"textarea\" \"tfoot\" \"th\" \"thead\" \"title\" \"tr\" \"track\"\n\n \"ul\" \"wbr\" \"xmp\");\n\n//§ END\n\n\n", "file_path": "yarte_html/src/tree_builder/tag_sets.rs", "rank": 50, "score": 216558.99207256292 }, { "content": "pub fn parse_fragment(doc: &str) -> ParseResult<Sink> {\n\n let parser = driver::parse_fragment(Sink::default(), get_marquee(), vec![]).from_utf8();\n\n parser.one(doc.as_bytes()).and_then(|mut a| {\n\n a.nodes\n\n .remove(&0)\n\n .and_then(|_| {\n\n if let Some(ParseElement::Node { name, .. }) = a.nodes.get_mut(&2) {\n\n *name = get_marquee();\n\n Some(a)\n\n } else {\n\n None\n\n }\n\n })\n\n .ok_or_else(Vec::new)\n\n })\n\n}\n", "file_path": "yarte_dom/src/sink.rs", "rank": 51, "score": 213569.1285956973 }, { "content": "fn tokens(i: TokenStream, wlog: bool) -> String {\n\n let config = &Config::new(\"\");\n\n let der = parse2(i).unwrap();\n\n let s = visit_derive(&der, config).unwrap();\n\n let mut src = BTreeMap::new();\n\n src.insert(s.path.clone(), s.src.clone());\n\n let sources = parse(get_cursor(&s.path, &s.src)).unwrap();\n\n let mut ctx = BTreeMap::new();\n\n ctx.insert(&s.path, sources);\n\n\n\n let ir = generate(config, &s, &ctx, Default::default())\n\n .unwrap_or_else(|e| emitter(&src, config, e.into_iter()));\n\n clean();\n\n\n\n let res = WASMCodeGen::new(&s).gen(ir).to_string();\n\n if wlog {\n\n log(&res, \"Test\".into(), &config.debug);\n\n }\n\n res\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/tests/mod.rs", "rank": 52, "score": 212626.9150366335 }, { "content": "/// Parse syn expression comma separated list\n\nfn eat_expr_list(i: &str) -> Result<Vec<Expr>, MiddleError> {\n\n parse_str::<ExprList>(i)\n\n .map(Into::into)\n\n .map_err(|e| MiddleError::new(i, e))\n\n}\n\n\n", "file_path": "yarte_parser/src/lib.rs", "rank": 53, "score": 208587.61611025035 }, { "content": "#[inline(always)]\n\npub fn empty_set(_: ExpandedName) -> bool {\n\n false\n\n}\n\n\n\ndeclare_tag_set!(pub html_default_scope =\n\n \"applet\" \"caption\" \"html\" \"table\" \"td\" \"th\" \"marquee\" \"object\" \"template\");\n\n\n", "file_path": "yarte_html/src/tree_builder/tag_sets.rs", "rank": 54, "score": 206593.55440433102 }, { "content": "fn build_teams() -> Vec<Team> {\n\n vec![\n\n Team {\n\n name: \"Jiangsu\".into(),\n\n score: 43,\n\n },\n\n Team {\n\n name: \"Beijing\".into(),\n\n score: 27,\n\n },\n\n Team {\n\n name: \"Guangzhou\".into(),\n\n score: 22,\n\n },\n\n Team {\n\n name: \"Shandong\".into(),\n\n score: 12,\n\n },\n\n ]\n\n}\n\n\n", "file_path": "benches/src/all.rs", "rank": 55, "score": 203901.75017268548 }, { "content": "fn to_domfmt_init(ir: Vec<HIR>) -> ParseResult<Vec<HIR>> {\n\n let html = get_html(&ir);\n\n let sink = match parse_document(&html) {\n\n Ok(a) => a,\n\n Err(_) => parse_fragment(&html)?,\n\n };\n\n\n\n serialize_domfmt(sink, ir, Default::default())\n\n}\n\n\n", "file_path": "yarte_dom/src/dom_fmt.rs", "rank": 56, "score": 201625.8539472382 }, { "content": "pub fn get_leaf_text(children: Document, solver: &Solver) -> (BTreeSet<VarId>, TokenStream) {\n\n LeafTextBuilder::new(solver).build(children)\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/leaf_text.rs", "rank": 57, "score": 201584.45367562753 }, { "content": "#[inline]\n\nfn at_helper(i: Cursor, lws: bool) -> PResult<Node> {\n\n let (c, (name, args, rws)) = do_parse!(\n\n i,\n\n ws >> tag!(\"@\")\n\n >> name: call!(spanned, identifier)\n\n >> args: args_list\n\n >> rws: end_expr\n\n >> ((name, args, rws))\n\n )?;\n\n\n\n macro_rules! check_args_len {\n\n ($len:expr) => {\n\n if args.t().len() != $len {\n\n return Err(LexError::Fail(PError::AtHelperArgsLen($len), args.span()));\n\n }\n\n };\n\n }\n\n match *name.t() {\n\n JSON => {\n\n check_args_len!(1);\n", "file_path": "yarte_parser/src/lib.rs", "rank": 58, "score": 201392.16200866314 }, { "content": "/// Eat safe Node\n\nfn safe(i: Cursor, lws: bool) -> PResult<Node> {\n\n let mut at = 0;\n\n let (c, rws, s) = loop {\n\n if let Some(j) = i.adv_find(at, '}') {\n\n let n = &i.rest[at + j + 1..];\n\n if n.starts_with(\"~}}\") {\n\n break (i.adv(at + j + 4), true, &i.rest[..at + j]);\n\n } else if n.starts_with(\"}}\") {\n\n break (i.adv(at + j + 3), false, &i.rest[..at + j]);\n\n }\n\n\n\n at += j + 1;\n\n } else {\n\n return Err(LexError::Next(PError::Safe(DOption::None), Span::from(i)));\n\n }\n\n };\n\n\n\n let (_, s, _) = trim(s);\n\n eat_expr(s)\n\n .map(|e| {\n", "file_path": "yarte_parser/src/lib.rs", "rank": 59, "score": 201391.95357238268 }, { "content": "/// Eat raw Node\n\nfn raw(i: Cursor, a_lws: bool) -> PResult<Node> {\n\n let (i, a_rws) = end_expr(i)?;\n\n let mut at = 0;\n\n\n\n let (c, (j, b_ws)) = loop {\n\n if let Some(j) = i.adv_find(at, '{') {\n\n let n = i.adv(at + j + 1);\n\n if n.chars().next().map(|x| '{' == x).unwrap_or(false) {\n\n if let Ok((c, ws)) = do_parse!(\n\n n.adv(1),\n\n lws: opt!(tag!(\"~\")) >> tag!(\"/R\") >> rws: end_expr >> ((lws.is_some(), rws))\n\n ) {\n\n break (c, (&i.rest[..at + j], ws));\n\n } else {\n\n at += j + 4;\n\n }\n\n } else {\n\n at += j + 1;\n\n }\n\n } else {\n", "file_path": "yarte_parser/src/lib.rs", "rank": 60, "score": 201391.95357238268 }, { "content": "/// Eat helper Node\n\nfn hel(i: Cursor, a_lws: bool) -> PResult<Node> {\n\n if i.starts_with(\">\") {\n\n return partial_block(i.adv(1), a_lws).map(|(c, x)| (c, Node::PartialBlock(x)));\n\n }\n\n\n\n let (i, (above_ws, ident, args)) = do_parse!(\n\n i,\n\n ws >> ident: call!(spanned, identifier)\n\n >> args: arguments\n\n >> rws: end_expr\n\n >> (((a_lws, rws), ident, args))\n\n )?;\n\n\n\n if ident.0.eq(\"if\") {\n\n return if_else(above_ws, i, args);\n\n }\n\n\n\n let (c, (below_ws, block, c_ident)) = do_parse!(\n\n i,\n\n block: eat\n", "file_path": "yarte_parser/src/lib.rs", "rank": 61, "score": 201391.95357238268 }, { "content": "fn res(c: Cursor, lws: bool) -> PResult<Node> {\n\n do_parse!(\n\n c,\n\n ws >> expr: arguments >> rws: end_expr >> (Node::RExpr((lws, rws), expr))\n\n )\n\n}\n\n\n\n/// Wrap Partial into the Node\n", "file_path": "yarte_parser/src/lib.rs", "rank": 62, "score": 201386.68999182188 }, { "content": "fn write_bb(b: &[u8], buf: &TokenStream) -> TokenStream {\n\n b.iter()\n\n .enumerate()\n\n .map(|(i, b)| {\n\n quote! {\n\n *#buf.buf_ptr().add(#i) = #b;\n\n }\n\n })\n\n .flatten()\n\n .collect()\n\n}\n\n\n\npub struct HTMLBytesCodeGen<'a> {\n\n buf: &'a syn::Expr,\n\n}\n\n\n\nimpl<'a> HTMLBytesCodeGen<'a> {\n\n pub fn new(buf: &syn::Expr) -> HTMLBytesCodeGen {\n\n HTMLBytesCodeGen { buf }\n\n }\n", "file_path": "yarte_codegen/src/bytes.rs", "rank": 63, "score": 196672.3116659344 }, { "content": "fn make_tag_pattern(binding: &TokenStream, tag: Tag) -> TokenStream {\n\n let kind = match tag.kind {\n\n TagKind::StartTag => quote!(crate::tokenizer::StartTag),\n\n TagKind::EndTag => quote!(crate::tokenizer::EndTag),\n\n };\n\n let name_field = if let Some(name) = tag.name {\n\n let name = name.to_string();\n\n quote!(name: y_name!(#name),)\n\n } else {\n\n quote!()\n\n };\n\n quote! {\n\n crate::tree_builder::types::TagToken(#binding crate::tokenizer::Tag { kind: #kind, #name_field .. })\n\n }\n\n}\n", "file_path": "yarte_html/macros/match_token.rs", "rank": 64, "score": 195793.97248582955 }, { "content": "fn eat_partials(mut i: Cursor) -> PResult<Vec<Partial>> {\n\n let mut nodes = vec![];\n\n\n\n loop {\n\n if let Some(j) = i.find('{') {\n\n macro_rules! _switch {\n\n ($n:expr, $t:expr, $ws:expr) => {\n\n match $n {\n\n b'>' => {\n\n let i = i.adv(j + 3 + $t);\n\n match partial_block(i, $ws) {\n\n Ok((i, n)) => {\n\n nodes.push(n);\n\n i\n\n }\n\n Err(e @ LexError::Fail(..)) => break Err(e),\n\n Err(LexError::Next(..)) => i,\n\n }\n\n }\n\n b'R' => {\n", "file_path": "yarte_parser/src/pre_partials.rs", "rank": 65, "score": 195649.8728981492 }, { "content": "#[inline]\n\nfn if_else(abode_ws: Ws, i: Cursor, args: SExpr) -> PResult<Node> {\n\n let mut nodes = vec![];\n\n let mut tail = None;\n\n\n\n let (mut i, first) = eat_if(i)?;\n\n\n\n loop {\n\n if let Ok((c, lws)) = do_parse!(\n\n i,\n\n lws: opt!(tag!(\"~\")) >> ws >> tag!(ELSE) >> (lws.is_some())\n\n ) {\n\n if let Ok((c, _)) = tag!(skip_ws(c), IF) {\n\n let (c, b) = map_fail!(do_parse!(\n\n c,\n\n ws >> args: arguments\n\n >> rws: end_expr\n\n >> block: eat_if\n\n >> (((lws, rws), args, block))\n\n ))?;\n\n nodes.push(b);\n", "file_path": "yarte_parser/src/lib.rs", "rank": 66, "score": 195258.60452733014 }, { "content": "#[proc_macro]\n\npub fn zip_with_spaces(token: TokenStream) -> TokenStream {\n\n let expr: ExprList = parse(token).unwrap();\n\n let expr: Vec<Vec<String>> = expr.into();\n\n let mut expr = expr.iter();\n\n let first = expr.next().expect(\"Need minimum two element\");\n\n let mut buff = vec![];\n\n for i in first {\n\n _zip(i, &mut expr.clone(), &mut buff)\n\n }\n\n let len = buff.len();\n\n\n\n quote!(static ZIPPED: [&str; #len] = [#(#buff),*];).into()\n\n}\n\n\n", "file_path": "yarte_wasm_app/benches/codegen/src/lib.rs", "rank": 67, "score": 193898.83467211915 }, { "content": "#[inline]\n\npub fn get_self_id() -> u64 {\n\n SELF_ID.with(|x| *x)\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 68, "score": 192810.44938961728 }, { "content": "fn is_ident_start(c: char) -> bool {\n\n ('a' <= c && c <= 'z')\n\n || ('A' <= c && c <= 'Z')\n\n || c == '_'\n\n || (c > '\\x7f' && UnicodeXID::is_xid_start(c))\n\n}\n\n\n", "file_path": "yarte_parser/src/lib.rs", "rank": 69, "score": 192590.184692809 }, { "content": "fn is_ident_continue(c: char) -> bool {\n\n ('a' <= c && c <= 'z')\n\n || ('A' <= c && c <= 'Z')\n\n || c == '_'\n\n || ('0' <= c && c <= '9')\n\n || (c > '\\x7f' && UnicodeXID::is_xid_continue(c))\n\n}\n\n\n", "file_path": "yarte_parser/src/lib.rs", "rank": 70, "score": 192590.184692809 }, { "content": "fn to_domfmt(ir: Vec<HIR>, opts: SerializerOpt) -> ParseResult<Vec<HIR>> {\n\n let html = get_html(&ir);\n\n serialize_domfmt(parse_fragment(&html)?, ir, opts)\n\n}\n\n\n", "file_path": "yarte_dom/src/dom_fmt.rs", "rank": 71, "score": 191988.68022267864 }, { "content": "fn write_bb(b: &[u8]) -> TokenStream {\n\n b.iter()\n\n .enumerate()\n\n .map(|(i, b)| {\n\n quote! {\n\n *buf_ptr!().add(buf_cur + #i) = #b;\n\n }\n\n })\n\n .flatten()\n\n .collect()\n\n}\n\n\n\nimpl<'a, T: CodeGen> CodeGen for FixedCodeGen<'a, T> {\n\n fn gen(&mut self, v: Vec<HIR>) -> TokenStream {\n\n let mut tokens = TokenStream::new();\n\n\n\n self.template(v, &mut tokens);\n\n\n\n tokens\n\n }\n", "file_path": "yarte_codegen/src/fixed.rs", "rank": 72, "score": 189130.2472921813 }, { "content": "pub fn is_mark(s: &str) -> bool {\n\n s.len() == MARK_LEN + HASH_LEN && &s[..MARK_LEN] == MARK && parse_id(&s[MARK_LEN..]).is_some()\n\n}\n\n\n", "file_path": "yarte_html/src/utils.rs", "rank": 73, "score": 188498.4307690896 }, { "content": "fn write_3_bytes_bb(b: &mut criterion::Bencher) {\n\n const BYTES: usize = 3;\n\n unsafe {\n\n b.iter(|| {\n\n const LEN: usize = BYTES * STEPS;\n\n let mut buf: [u8; LEN] = MaybeUninit::uninit().assume_init();\n\n let mut curr = 0;\n\n let buf_ptr = buf.as_mut_ptr();\n\n for _ in 0..STEPS {\n\n if LEN < curr + BYTES {\n\n panic!(\"buffer overflow\");\n\n } else {\n\n *buf_ptr.add(curr) = b'a';\n\n *buf_ptr.add(curr + 1) = b'a';\n\n *buf_ptr.add(curr + 2) = b'a';\n\n curr += BYTES;\n\n }\n\n }\n\n black_box(&buf[..curr]);\n\n })\n\n }\n\n}\n\n\n", "file_path": "benches/src/all.rs", "rank": 74, "score": 188081.02976334246 }, { "content": "/// Is the character an ASCII alphanumeric character?\n\npub fn is_ascii_alnum(c: char) -> bool {\n\n matches!(c, '0'..='9' | 'a'..='z' | 'A'..='Z')\n\n}\n\n\n", "file_path": "yarte_html/src/utils.rs", "rank": 75, "score": 185439.5064912872 }, { "content": "/// ASCII whitespace characters, as defined by\n\n/// tree construction modes that treat them specially.\n\npub fn is_ascii_whitespace(c: char) -> bool {\n\n matches!(c, '\\t' | '\\r' | '\\n' | '\\x0C' | ' ')\n\n}\n\n\n\npub const MARK: &str = \"yartehashhtmlexpressionsattt\";\n\nconst MARK_LEN: usize = MARK.len();\n\nconst S: &str = \"0x\";\n\nconst S_LEN: usize = S.len();\n\n// 0x00_00_00_00\n\npub const HASH_LEN: usize = 10;\n\n\n", "file_path": "yarte_html/src/utils.rs", "rank": 76, "score": 185439.5064912872 }, { "content": "fn parse(rest: &str) -> Vec<SNode> {\n\n _parse(Cursor { rest, off: 0 }).unwrap()\n\n}\n\n\n", "file_path": "yarte_parser/src/test.rs", "rank": 77, "score": 182650.03100207425 }, { "content": "/// Eat whitespace flag in end of expressions `.. }}` or `.. ~}}`\n\nfn end_expr(i: Cursor) -> PResult<bool> {\n\n let c = skip_ws(i);\n\n if c.starts_with(\"~}}\") {\n\n Ok((c.adv(3), true))\n\n } else if c.starts_with(\"}}\") {\n\n Ok((c.adv(2), false))\n\n } else {\n\n Err(LexError::Fail(\n\n PError::EndExpression,\n\n Span::from_cursor(i, c),\n\n ))\n\n }\n\n}\n\n\n", "file_path": "yarte_parser/src/lib.rs", "rank": 78, "score": 182536.60386503692 }, { "content": "fn big_table(b: &mut criterion::Bencher, size: usize) {\n\n let t = BigTable {\n\n table: build_big_table(size),\n\n };\n\n b.iter(|| t.call().unwrap());\n\n}\n\n\n", "file_path": "benches/src/all.rs", "rank": 79, "score": 178306.91834108363 }, { "content": "#[test]\n\nfn test_with_index() {\n\n let t = WithSuperIndexTemplate {\n\n this: &[Holder { hold: 127 }],\n\n };\n\n assert_eq!(\"Hello, 1271271!\", t.call().unwrap());\n\n}\n", "file_path": "yarte/tests/super.rs", "rank": 80, "score": 176410.7416287016 }, { "content": "#[test]\n\nfn test_with_fields() {\n\n let t = WithFieldsTemplate {\n\n names: (\n\n Name {\n\n first: \"foo\",\n\n last: \"bar\",\n\n },\n\n Name {\n\n first: \"fOO\",\n\n last: \"bAR\",\n\n },\n\n ),\n\n };\n\n assert_eq!(\"Hello, foo bar and fOO bAR!\", t.call().unwrap());\n\n}\n\n\n", "file_path": "yarte/tests/expressions.rs", "rank": 81, "score": 176255.46263745846 }, { "content": "#[test]\n\nfn test_let_if_some() {\n\n let t = LetIfSomeTemplate { cond: Some(false) };\n\n assert_eq!(\"Hello, bar!\", t.call().unwrap());\n\n}\n\n\n", "file_path": "yarte/tests/expressions.rs", "rank": 82, "score": 176185.78980165158 }, { "content": "#[test]\n\nfn test_let_with() {\n\n let t = LetWithTemplate { name: \"world\" };\n\n assert_eq!(\"Hello, worldworld!\", t.call().unwrap());\n\n}\n\n\n", "file_path": "yarte/tests/expressions.rs", "rank": 83, "score": 176185.78980165158 }, { "content": "#[test]\n\nfn test_let_if() {\n\n let t = LetIfTemplate { cond: true };\n\n assert_eq!(\"Hello, true false foo!\", t.call().unwrap());\n\n}\n\n\n", "file_path": "yarte/tests/expressions.rs", "rank": 84, "score": 176185.78980165158 }, { "content": "#[test]\n\nfn test_let() {\n\n let t = LetTemplate { name: \"world\" };\n\n assert_eq!(\"Hello, world!\", t.call().unwrap());\n\n}\n\n\n", "file_path": "yarte/tests/expressions.rs", "rank": 85, "score": 176185.78980165158 }, { "content": "#[test]\n\nfn test_match() {\n\n let t = MatchTemplate { a: Err(Error) };\n\n assert_eq!(\"&amp;\", t.call().unwrap());\n\n\n\n let t = MatchTemplate { a: Ok(\"1\") };\n\n assert_eq!(\"1\", t.call().unwrap());\n\n}\n\n\n", "file_path": "yarte/tests/expressions.rs", "rank": 86, "score": 176157.78647271486 }, { "content": "fn io_big_table(b: &mut criterion::Bencher, size: usize) {\n\n let table = build_big_table(size);\n\n let mut buf = vec![];\n\n let _ = _io_big_table(&mut buf, &table);\n\n let len = buf.len();\n\n b.iter(|| {\n\n let mut buf = Vec::with_capacity(len);\n\n _io_big_table(&mut buf, &table).unwrap();\n\n buf\n\n });\n\n}\n\n\n", "file_path": "benches/src/all.rs", "rank": 87, "score": 175392.73490759052 }, { "content": "fn fixed_big_table(b: &mut criterion::Bencher, size: usize) {\n\n let t = BigTableF {\n\n table: build_big_table(size),\n\n };\n\n b.iter(|| {\n\n black_box(unsafe { t.call(&mut [MaybeUninit::uninit(); 109915]) }.unwrap());\n\n });\n\n}\n\n\n", "file_path": "benches/src/all.rs", "rank": 88, "score": 175392.73490759052 }, { "content": "fn bytes_big_table(b: &mut criterion::Bencher, size: usize) {\n\n let t = BigTableB {\n\n table: build_big_table(size),\n\n };\n\n b.iter(|| t.call::<BytesMut>(109915));\n\n}\n\n\n", "file_path": "benches/src/all.rs", "rank": 89, "score": 175392.73490759052 }, { "content": "fn big_table_text(b: &mut criterion::Bencher, size: usize) {\n\n let t = BigTableDisplay {\n\n table: build_big_table(size),\n\n };\n\n b.iter(|| t.call().unwrap());\n\n}\n\n\n\n// Bytes\n", "file_path": "benches/src/all.rs", "rank": 90, "score": 175392.73490759052 }, { "content": "fn fmt_big_table(b: &mut criterion::Bencher, size: usize) {\n\n let t = BigTableFmt {\n\n table: build_big_table(size),\n\n };\n\n let mut buf = String::with_capacity(t.to_string().len());\n\n b.iter(|| {\n\n buf.clear();\n\n write!(buf, \"{}\", t).unwrap();\n\n });\n\n}\n\n\n", "file_path": "benches/src/all.rs", "rank": 91, "score": 175392.73490759052 }, { "content": "fn raw_big_table(b: &mut criterion::Bencher, size: usize) {\n\n unsafe {\n\n let table = build_big_table(size);\n\n const LEN: usize = 109915;\n\n\n\n b.iter(|| {\n\n let mut buf: [u8; LEN] = MaybeUninit::uninit().assume_init();\n\n let mut curr = 0;\n\n macro_rules! buf_ptr {\n\n () => {\n\n &mut buf as *mut _ as *mut u8\n\n };\n\n }\n\n\n\n macro_rules! write_b {\n\n ($b:expr) => {\n\n if LEN < curr + $b.len() {\n\n panic!(\"buffer overflow\");\n\n } else {\n\n for i in $b {\n", "file_path": "benches/src/all.rs", "rank": 92, "score": 175392.73490759052 }, { "content": "pub fn check_attr_is_text(attr: Attribute) -> bool {\n\n attr.value.len() == 1\n\n && match attr.value[0] {\n\n ExprOrText::Text(..) => true,\n\n ExprOrText::Expr(..) => false,\n\n }\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 93, "score": 174527.71040102688 }, { "content": "pub fn parse_document(doc: &str) -> ParseResult<Sink> {\n\n let parser = driver::parse_document(Sink::default()).from_utf8();\n\n\n\n parser.one(doc.as_bytes())\n\n}\n\n\n", "file_path": "yarte_dom/src/sink.rs", "rank": 94, "score": 173700.6099892016 }, { "content": "#[inline]\n\npub fn is_inner(attrs: &[syn::Attribute]) -> bool {\n\n attrs.iter().any(|attr| attr.path.is_ident(\"inner\"))\n\n}\n\n\n", "file_path": "yarte_codegen/src/wasm/client/utils.rs", "rank": 95, "score": 173534.0937544771 }, { "content": "fn run_n(app: &mut NonKeyed, n: usize) {\n\n let update_n = min(n, app.data.len());\n\n\n\n // ?? #macro mark_data_update(for i in\n\n for (i, (dom, row)) in app\n\n .tbody_children\n\n .iter_mut()\n\n .zip(app.data.iter_mut())\n\n .enumerate()\n\n .take(update_n)\n\n {\n\n row.id = app.id + i as usize;\n\n row.label = (*ZIPPED.choose(&mut app.rng).unwrap()).to_string();\n\n // or #macro mark_data_\n\n dom.t_root = 0xFF;\n\n // /macro\n\n }\n\n // /macro\n\n\n\n for i in update_n..n {\n", "file_path": "yarte_wasm_app/benches/src/handler.rs", "rank": 96, "score": 173117.58982431918 }, { "content": "#[test]\n\nfn test_self_method() {\n\n let t = SelfMethodTemplate { s: \"foo\" };\n\n assert_eq!(t.call().unwrap(), \"foo\");\n\n}\n\n\n", "file_path": "yarte/tests/expressions.rs", "rank": 97, "score": 172700.41347005198 }, { "content": "#[test]\n\nfn test_let_else_if_some() {\n\n let t = LetElseIfSomeTemplate {\n\n cond: Some(false),\n\n check: Some(false),\n\n };\n\n assert_eq!(\"Hello, bar!\", t.call().unwrap());\n\n let t = LetElseIfSomeTemplate {\n\n cond: Some(true),\n\n check: Some(false),\n\n };\n\n assert_eq!(\"Hello, foo!\", t.call().unwrap());\n\n let t = LetElseIfSomeTemplate {\n\n cond: None,\n\n check: Some(true),\n\n };\n\n assert_eq!(\"Hello, baa!\", t.call().unwrap());\n\n let t = LetElseIfSomeTemplate {\n\n cond: None,\n\n check: Some(false),\n\n };\n\n assert_eq!(\"Hello, fun!\", t.call().unwrap());\n\n let t = LetElseIfSomeTemplate {\n\n cond: None,\n\n check: None,\n\n };\n\n assert_eq!(\"Hello, None!\", t.call().unwrap());\n\n}\n\n\n", "file_path": "yarte/tests/expressions.rs", "rank": 98, "score": 172635.92956636127 }, { "content": "#[test]\n\nfn test_let_closure() {\n\n let t = LetClosureTemplate { name: \"world\" };\n\n assert_eq!(\"worldworld\", t.call().unwrap());\n\n}\n\n\n", "file_path": "yarte/tests/expressions.rs", "rank": 99, "score": 172635.92956636127 } ]
Rust
src/atsame70q21b/usbhs/usbhs_deveptier_intrpt_mode.rs
tstellanova/atsame7x-pac
f7e24c71181651c141d0727379147c388661ce0e
#[doc = "Writer for register USBHS_DEVEPTIER_INTRPT_MODE[%s]"] pub type W = crate::W<u32, super::USBHS_DEVEPTIER_INTRPT_MODE>; #[doc = "Register USBHS_DEVEPTIER_INTRPT_MODE[%s] `reset()`'s with value 0"] impl crate::ResetValue for super::USBHS_DEVEPTIER_INTRPT_MODE { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `TXINES`"] pub struct TXINES_W<'a> { w: &'a mut W, } impl<'a> TXINES_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 = "Write proxy for field `RXOUTES`"] pub struct RXOUTES_W<'a> { w: &'a mut W, } impl<'a> RXOUTES_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 = "Write proxy for field `RXSTPES`"] pub struct RXSTPES_W<'a> { w: &'a mut W, } impl<'a> RXSTPES_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 = "Write proxy for field `NAKOUTES`"] pub struct NAKOUTES_W<'a> { w: &'a mut W, } impl<'a> NAKOUTES_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 = "Write proxy for field `NAKINES`"] pub struct NAKINES_W<'a> { w: &'a mut W, } impl<'a> NAKINES_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 = "Write proxy for field `OVERFES`"] pub struct OVERFES_W<'a> { w: &'a mut W, } impl<'a> OVERFES_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 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Write proxy for field `STALLEDES`"] pub struct STALLEDES_W<'a> { w: &'a mut W, } impl<'a> STALLEDES_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 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Write proxy for field `SHORTPACKETES`"] pub struct SHORTPACKETES_W<'a> { w: &'a mut W, } impl<'a> SHORTPACKETES_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 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Write proxy for field `NBUSYBKES`"] pub struct NBUSYBKES_W<'a> { w: &'a mut W, } impl<'a> NBUSYBKES_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Write proxy for field `KILLBKS`"] pub struct KILLBKS_W<'a> { w: &'a mut W, } impl<'a> KILLBKS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Write proxy for field `FIFOCONS`"] pub struct FIFOCONS_W<'a> { w: &'a mut W, } impl<'a> FIFOCONS_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 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Write proxy for field `EPDISHDMAS`"] pub struct EPDISHDMAS_W<'a> { w: &'a mut W, } impl<'a> EPDISHDMAS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Write proxy for field `NYETDISS`"] pub struct NYETDISS_W<'a> { w: &'a mut W, } impl<'a> NYETDISS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Write proxy for field `RSTDTS`"] pub struct RSTDTS_W<'a> { w: &'a mut W, } impl<'a> RSTDTS_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 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Write proxy for field `STALLRQS`"] pub struct STALLRQS_W<'a> { w: &'a mut W, } impl<'a> STALLRQS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } impl W { #[doc = "Bit 0 - Transmitted IN Data Interrupt Enable"] #[inline(always)] pub fn txines(&mut self) -> TXINES_W { TXINES_W { w: self } } #[doc = "Bit 1 - Received OUT Data Interrupt Enable"] #[inline(always)] pub fn rxoutes(&mut self) -> RXOUTES_W { RXOUTES_W { w: self } } #[doc = "Bit 2 - Received SETUP Interrupt Enable"] #[inline(always)] pub fn rxstpes(&mut self) -> RXSTPES_W { RXSTPES_W { w: self } } #[doc = "Bit 3 - NAKed OUT Interrupt Enable"] #[inline(always)] pub fn nakoutes(&mut self) -> NAKOUTES_W { NAKOUTES_W { w: self } } #[doc = "Bit 4 - NAKed IN Interrupt Enable"] #[inline(always)] pub fn nakines(&mut self) -> NAKINES_W { NAKINES_W { w: self } } #[doc = "Bit 5 - Overflow Interrupt Enable"] #[inline(always)] pub fn overfes(&mut self) -> OVERFES_W { OVERFES_W { w: self } } #[doc = "Bit 6 - STALLed Interrupt Enable"] #[inline(always)] pub fn stalledes(&mut self) -> STALLEDES_W { STALLEDES_W { w: self } } #[doc = "Bit 7 - Short Packet Interrupt Enable"] #[inline(always)] pub fn shortpacketes(&mut self) -> SHORTPACKETES_W { SHORTPACKETES_W { w: self } } #[doc = "Bit 12 - Number of Busy Banks Interrupt Enable"] #[inline(always)] pub fn nbusybkes(&mut self) -> NBUSYBKES_W { NBUSYBKES_W { w: self } } #[doc = "Bit 13 - Kill IN Bank"] #[inline(always)] pub fn killbks(&mut self) -> KILLBKS_W { KILLBKS_W { w: self } } #[doc = "Bit 14 - FIFO Control"] #[inline(always)] pub fn fifocons(&mut self) -> FIFOCONS_W { FIFOCONS_W { w: self } } #[doc = "Bit 16 - Endpoint Interrupts Disable HDMA Request Enable"] #[inline(always)] pub fn epdishdmas(&mut self) -> EPDISHDMAS_W { EPDISHDMAS_W { w: self } } #[doc = "Bit 17 - NYET Token Disable Enable"] #[inline(always)] pub fn nyetdiss(&mut self) -> NYETDISS_W { NYETDISS_W { w: self } } #[doc = "Bit 18 - Reset Data Toggle Enable"] #[inline(always)] pub fn rstdts(&mut self) -> RSTDTS_W { RSTDTS_W { w: self } } #[doc = "Bit 19 - STALL Request Enable"] #[inline(always)] pub fn stallrqs(&mut self) -> STALLRQS_W { STALLRQS_W { w: self } } }
#[doc = "Writer for register USBHS_DEVEPTIER_INTRPT_MODE[%s]"] pub type W = crate::W<u32, super::USBHS_DEVEPTIER_INTRPT_MODE>; #[doc = "Register USBHS_DEVEPTIER_INTRPT_MODE[%s] `reset()`'s with value 0"] impl crate::ResetValue for super::USBHS_DEVEPTIER_INTRPT_MODE { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `TXINES`"] pub struct TXINES_W<'a> { w: &'a mut W, } impl<'a> TXINES_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 = "Write proxy for field `RXOUTES`"] pub struct RXOUTES_W<'a> { w: &'a mut W, } impl<'a> RXOUTES_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 = "Write proxy for field `RXSTPES`"] pub struct RXSTPES_W<'a> { w: &'a mut W, } impl<'a> RXSTPES_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 = "Write proxy for field `NAKOUTES`"] pub struct NAKOUTES_W<'a> { w: &'a mut W, } impl<'a> NAKOUTES_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 u3
#[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 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Write proxy for field `NBUSYBKES`"] pub struct NBUSYBKES_W<'a> { w: &'a mut W, } impl<'a> NBUSYBKES_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Write proxy for field `KILLBKS`"] pub struct KILLBKS_W<'a> { w: &'a mut W, } impl<'a> KILLBKS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Write proxy for field `FIFOCONS`"] pub struct FIFOCONS_W<'a> { w: &'a mut W, } impl<'a> FIFOCONS_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 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Write proxy for field `EPDISHDMAS`"] pub struct EPDISHDMAS_W<'a> { w: &'a mut W, } impl<'a> EPDISHDMAS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Write proxy for field `NYETDISS`"] pub struct NYETDISS_W<'a> { w: &'a mut W, } impl<'a> NYETDISS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Write proxy for field `RSTDTS`"] pub struct RSTDTS_W<'a> { w: &'a mut W, } impl<'a> RSTDTS_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 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Write proxy for field `STALLRQS`"] pub struct STALLRQS_W<'a> { w: &'a mut W, } impl<'a> STALLRQS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } impl W { #[doc = "Bit 0 - Transmitted IN Data Interrupt Enable"] #[inline(always)] pub fn txines(&mut self) -> TXINES_W { TXINES_W { w: self } } #[doc = "Bit 1 - Received OUT Data Interrupt Enable"] #[inline(always)] pub fn rxoutes(&mut self) -> RXOUTES_W { RXOUTES_W { w: self } } #[doc = "Bit 2 - Received SETUP Interrupt Enable"] #[inline(always)] pub fn rxstpes(&mut self) -> RXSTPES_W { RXSTPES_W { w: self } } #[doc = "Bit 3 - NAKed OUT Interrupt Enable"] #[inline(always)] pub fn nakoutes(&mut self) -> NAKOUTES_W { NAKOUTES_W { w: self } } #[doc = "Bit 4 - NAKed IN Interrupt Enable"] #[inline(always)] pub fn nakines(&mut self) -> NAKINES_W { NAKINES_W { w: self } } #[doc = "Bit 5 - Overflow Interrupt Enable"] #[inline(always)] pub fn overfes(&mut self) -> OVERFES_W { OVERFES_W { w: self } } #[doc = "Bit 6 - STALLed Interrupt Enable"] #[inline(always)] pub fn stalledes(&mut self) -> STALLEDES_W { STALLEDES_W { w: self } } #[doc = "Bit 7 - Short Packet Interrupt Enable"] #[inline(always)] pub fn shortpacketes(&mut self) -> SHORTPACKETES_W { SHORTPACKETES_W { w: self } } #[doc = "Bit 12 - Number of Busy Banks Interrupt Enable"] #[inline(always)] pub fn nbusybkes(&mut self) -> NBUSYBKES_W { NBUSYBKES_W { w: self } } #[doc = "Bit 13 - Kill IN Bank"] #[inline(always)] pub fn killbks(&mut self) -> KILLBKS_W { KILLBKS_W { w: self } } #[doc = "Bit 14 - FIFO Control"] #[inline(always)] pub fn fifocons(&mut self) -> FIFOCONS_W { FIFOCONS_W { w: self } } #[doc = "Bit 16 - Endpoint Interrupts Disable HDMA Request Enable"] #[inline(always)] pub fn epdishdmas(&mut self) -> EPDISHDMAS_W { EPDISHDMAS_W { w: self } } #[doc = "Bit 17 - NYET Token Disable Enable"] #[inline(always)] pub fn nyetdiss(&mut self) -> NYETDISS_W { NYETDISS_W { w: self } } #[doc = "Bit 18 - Reset Data Toggle Enable"] #[inline(always)] pub fn rstdts(&mut self) -> RSTDTS_W { RSTDTS_W { w: self } } #[doc = "Bit 19 - STALL Request Enable"] #[inline(always)] pub fn stallrqs(&mut self) -> STALLRQS_W { STALLRQS_W { w: self } } }
2) & 0x01) << 3); self.w } } #[doc = "Write proxy for field `NAKINES`"] pub struct NAKINES_W<'a> { w: &'a mut W, } impl<'a> NAKINES_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 = "Write proxy for field `OVERFES`"] pub struct OVERFES_W<'a> { w: &'a mut W, } impl<'a> OVERFES_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 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Write proxy for field `STALLEDES`"] pub struct STALLEDES_W<'a> { w: &'a mut W, } impl<'a> STALLEDES_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 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Write proxy for field `SHORTPACKETES`"] pub struct SHORTPACKETES_W<'a> { w: &'a mut W, } impl<'a> SHORTPACKETES_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"]
random
[]
Rust
crate/workspace_tests/src/game_input/system/shared_controller_input_update_system.rs
Lighty0410/autexousious
99d142d8fdbf2076f3fd929f61b8140d47cf6b86
#[cfg(test)] mod tests { use std::any; use amethyst::{ ecs::{Builder, Entity, Join, ReadStorage, WorldExt, WriteStorage}, Error, }; use amethyst_test::AmethystApplication; use game_input_model::{ config::{ControlBindings, ControllerId}, play::{ControllerInput, InputControlled, SharedInputControlled}, }; use game_input::SharedControllerInputUpdateSystem; #[test] fn merges_axes_controller_input_with_limit_correction() -> Result<(), Error> { let controller_count = 3; AmethystApplication::ui_base::<ControlBindings>() .with_system( SharedControllerInputUpdateSystem::new(), any::type_name::<SharedControllerInputUpdateSystem>(), &[], ) .with_effect(move |world| { let controller_entities = (0..controller_count) .map(|n| { let controller_id = n as ControllerId; world .create_entity() .with(InputControlled::new(controller_id)) .with(ControllerInput::default()) .build() }) .collect::<Vec<Entity>>(); world.insert(controller_entities); let entity = world.create_entity().with(SharedInputControlled).build(); world.insert(entity); }) .with_assertion(|world| { let store = world.read_storage::<ControllerInput>(); assert_eq!( Some(&ControllerInput::new(0., 0., false, false, false, false)), store.join().next() ); }) .with_effect(|world| { let (input_controlleds, mut controller_inputs) = world.system_data::<( ReadStorage<'_, InputControlled>, WriteStorage<'_, ControllerInput>, )>(); (&input_controlleds, &mut controller_inputs) .join() .for_each(|(_, controller_input)| { controller_input.x_axis_value = -1.; controller_input.z_axis_value = 1.; }); }) .with_assertion(|world| { let entity = *world.read_resource::<Entity>(); let store = world.read_storage::<ControllerInput>(); assert_eq!( Some(&ControllerInput::new(-1., 1., false, false, false, false)), store.get(entity) ); }) .with_effect(|world| { let (input_controlleds, mut controller_inputs) = world.system_data::<( ReadStorage<'_, InputControlled>, WriteStorage<'_, ControllerInput>, )>(); (&input_controlleds, &mut controller_inputs) .join() .for_each(|(_, controller_input)| { controller_input.x_axis_value = 1.; controller_input.z_axis_value = -1.; }); }) .with_assertion(|world| { let entity = *world.read_resource::<Entity>(); let store = world.read_storage::<ControllerInput>(); assert_eq!( Some(&ControllerInput::new(1., -1., false, false, false, false)), store.get(entity) ); }) .with_effect(|world| { let controller_entities = world .read_resource::<Vec<Entity>>() .iter() .map(|e| *e) .collect::<Vec<_>>(); controller_entities.into_iter().for_each(|entity| { world .delete_entity(entity) .expect("Failed to delete entity.") }); }) .with_assertion(|world| { let entity = *world.read_resource::<Entity>(); let store = world.read_storage::<ControllerInput>(); assert_eq!( Some(&ControllerInput::new(0., 0., false, false, false, false)), store.get(entity) ); }) .run() } #[test] fn merges_action_controller_input() -> Result<(), Error> { AmethystApplication::ui_base::<ControlBindings>() .with_system( SharedControllerInputUpdateSystem::new(), any::type_name::<SharedControllerInputUpdateSystem>(), &[], ) .with_effect(|world| { let entity = world.create_entity().with(SharedInputControlled).build(); world.insert(entity); }) .with_assertion(|world| { let entity = *world.read_resource::<Entity>(); let store = world.read_storage::<ControllerInput>(); assert_eq!( Some(&ControllerInput::new(0., 0., false, false, false, false)), store.get(entity) ); }) .with_effect(|world| { let mut jump_attack_pressed = ControllerInput::default(); jump_attack_pressed.attack = true; jump_attack_pressed.jump = true; let entity_0 = world .create_entity() .with(InputControlled::new(0)) .with(jump_attack_pressed) .build(); let mut defend_special_pressed = ControllerInput::default(); defend_special_pressed.defend = true; defend_special_pressed.special = true; let entity_1 = world .create_entity() .with(InputControlled::new(0)) .with(defend_special_pressed) .build(); let controller_entities = vec![entity_0, entity_1]; world.insert(controller_entities); }) .with_assertion(|world| { let entity = *world.read_resource::<Entity>(); let store = world.read_storage::<ControllerInput>(); assert_eq!( Some(&ControllerInput::new(0., 0., true, true, true, true)), store.get(entity) ); }) .with_effect(|world| { let entities = world .read_resource::<Vec<Entity>>() .iter() .map(|e| *e) .collect::<Vec<_>>(); world .delete_entity(*entities.first().expect("Expected entity to exist.")) .expect("Failed to delete `jump_attack` entity."); }) .with_assertion(|world| { let entity = *world.read_resource::<Entity>(); let store = world.read_storage::<ControllerInput>(); assert_eq!( Some(&ControllerInput::new(0., 0., true, false, false, true)), store.get(entity) ); }) .run() } }
#[cfg(test)] mod tests { use std::any; use amethyst::{ ecs::{Builder, Entity, Join, ReadStorage, WorldExt, WriteStorage}, Error, }; use amethyst_test::AmethystApplication; use game_input_model::{ config::{ControlBindings, ControllerId}, play::{ControllerInput, InputControlled, SharedInputControlled}, }; use game_input::SharedControllerInputUpdateSystem; #[test] fn merges_axes_controller_input_with_limit_correction() -> Result<(), Error> { let controller_count = 3; AmethystApplication::ui_base::<ControlBindings>() .with_system( SharedControllerInputUpdateSystem::new(), any::type_name::<SharedControllerInputUpdateSystem>(), &[], ) .with_effect(move |world| { let controller_entities = (0..controller_count) .map(|n| { let controller_id = n as ControllerId; world .create_entity() .with(InputContr
.expect("Failed to delete entity.") }); }) .with_assertion(|world| { let entity = *world.read_resource::<Entity>(); let store = world.read_storage::<ControllerInput>(); assert_eq!( Some(&ControllerInput::new(0., 0., false, false, false, false)), store.get(entity) ); }) .run() } #[test] fn merges_action_controller_input() -> Result<(), Error> { AmethystApplication::ui_base::<ControlBindings>() .with_system( SharedControllerInputUpdateSystem::new(), any::type_name::<SharedControllerInputUpdateSystem>(), &[], ) .with_effect(|world| { let entity = world.create_entity().with(SharedInputControlled).build(); world.insert(entity); }) .with_assertion(|world| { let entity = *world.read_resource::<Entity>(); let store = world.read_storage::<ControllerInput>(); assert_eq!( Some(&ControllerInput::new(0., 0., false, false, false, false)), store.get(entity) ); }) .with_effect(|world| { let mut jump_attack_pressed = ControllerInput::default(); jump_attack_pressed.attack = true; jump_attack_pressed.jump = true; let entity_0 = world .create_entity() .with(InputControlled::new(0)) .with(jump_attack_pressed) .build(); let mut defend_special_pressed = ControllerInput::default(); defend_special_pressed.defend = true; defend_special_pressed.special = true; let entity_1 = world .create_entity() .with(InputControlled::new(0)) .with(defend_special_pressed) .build(); let controller_entities = vec![entity_0, entity_1]; world.insert(controller_entities); }) .with_assertion(|world| { let entity = *world.read_resource::<Entity>(); let store = world.read_storage::<ControllerInput>(); assert_eq!( Some(&ControllerInput::new(0., 0., true, true, true, true)), store.get(entity) ); }) .with_effect(|world| { let entities = world .read_resource::<Vec<Entity>>() .iter() .map(|e| *e) .collect::<Vec<_>>(); world .delete_entity(*entities.first().expect("Expected entity to exist.")) .expect("Failed to delete `jump_attack` entity."); }) .with_assertion(|world| { let entity = *world.read_resource::<Entity>(); let store = world.read_storage::<ControllerInput>(); assert_eq!( Some(&ControllerInput::new(0., 0., true, false, false, true)), store.get(entity) ); }) .run() } }
olled::new(controller_id)) .with(ControllerInput::default()) .build() }) .collect::<Vec<Entity>>(); world.insert(controller_entities); let entity = world.create_entity().with(SharedInputControlled).build(); world.insert(entity); }) .with_assertion(|world| { let store = world.read_storage::<ControllerInput>(); assert_eq!( Some(&ControllerInput::new(0., 0., false, false, false, false)), store.join().next() ); }) .with_effect(|world| { let (input_controlleds, mut controller_inputs) = world.system_data::<( ReadStorage<'_, InputControlled>, WriteStorage<'_, ControllerInput>, )>(); (&input_controlleds, &mut controller_inputs) .join() .for_each(|(_, controller_input)| { controller_input.x_axis_value = -1.; controller_input.z_axis_value = 1.; }); }) .with_assertion(|world| { let entity = *world.read_resource::<Entity>(); let store = world.read_storage::<ControllerInput>(); assert_eq!( Some(&ControllerInput::new(-1., 1., false, false, false, false)), store.get(entity) ); }) .with_effect(|world| { let (input_controlleds, mut controller_inputs) = world.system_data::<( ReadStorage<'_, InputControlled>, WriteStorage<'_, ControllerInput>, )>(); (&input_controlleds, &mut controller_inputs) .join() .for_each(|(_, controller_input)| { controller_input.x_axis_value = 1.; controller_input.z_axis_value = -1.; }); }) .with_assertion(|world| { let entity = *world.read_resource::<Entity>(); let store = world.read_storage::<ControllerInput>(); assert_eq!( Some(&ControllerInput::new(1., -1., false, false, false, false)), store.get(entity) ); }) .with_effect(|world| { let controller_entities = world .read_resource::<Vec<Entity>>() .iter() .map(|e| *e) .collect::<Vec<_>>(); controller_entities.into_iter().for_each(|entity| { world .delete_entity(entity)
function_block-random_span
[ { "content": "#[test]\n\nfn read_and_exit() -> Result<(), OutputError> {\n\n let command = CargoBuild::new()\n\n .example(\"01_read_and_exit\")\n\n .current_release()\n\n .run()\n\n .expect(\"Failed to create `cargo` command\")\n\n .command();\n\n Command::from_std(command)\n\n .write_stdin(\"exit\\n\")\n\n .ok()?\n\n .assert()\n\n .success();\n\n Ok(())\n\n}\n\n\n", "file_path": "crate/stdio_input/tests/integration_test.rs", "rank": 0, "score": 236240.39583181933 }, { "content": "#[test]\n\nfn read_and_exit_timeout() -> Result<(), OutputError> {\n\n let command = CargoBuild::new()\n\n .example(\"01_read_and_exit\")\n\n .current_release()\n\n .run()\n\n .expect(\"Failed to create `cargo` command\")\n\n .command();\n\n\n\n Command::from_std(command)\n\n .args(&[\"-t\", \"0\"])\n\n .write_stdin(\"abc\\n\")\n\n .ok()?\n\n .assert()\n\n .success();\n\n Ok(())\n\n}\n", "file_path": "crate/stdio_input/tests/integration_test.rs", "rank": 1, "score": 232586.00871141808 }, { "content": "#[test]\n\n#[ignore] // Can't test on X through CI.\n\nfn start_and_exit() -> Result<(), OutputError> {\n\n let command = CargoBuild::new()\n\n .bin(\"will\")\n\n .current_release()\n\n .run()\n\n .expect(\"Failed to create `cargo` command\")\n\n .command();\n\n Command::from_std(command)\n\n .write_stdin(\"exit\\n\")\n\n .ok()?\n\n .assert()\n\n .success();\n\n\n\n Ok(())\n\n}\n", "file_path": "app/will/tests/001_start_and_exit.rs", "rank": 2, "score": 227750.20841416426 }, { "content": "fn main() -> Result<(), Error> {\n\n let mut will_config = AppFile::find(WILL_CONFIG)\n\n .and_then(|will_config_path| IoUtils::read_file(&will_config_path).map_err(Error::from))\n\n .and_then(|bytes| String::from_utf8(bytes).map_err(Error::from))\n\n .and_then(|will_config_toml| {\n\n WillConfig::from_args_with_toml(&will_config_toml).map_err(|e| Error::from(e.compat()))\n\n })\n\n .unwrap_or_else(|e| {\n\n eprintln!(\"{}\", e);\n\n WillConfig::from_args()\n\n });\n\n\n\n let session_server_config = session_server_config(&will_config);\n\n\n\n logger_setup(will_config.logger_config.take())?;\n\n debug!(\"will_config: {:?}\", will_config);\n\n\n\n let assets_dir = AppDir::assets()?;\n\n\n\n let game_mode_selection_state =\n", "file_path": "app/will/src/main.rs", "rank": 3, "score": 214996.17123408156 }, { "content": "fn main() -> Result<(), Error> {\n\n let opt = Opt::from_args();\n\n\n\n logger_setup(opt.logger_config)?;\n\n\n\n let tcp_listener = TcpListener::bind((opt.address, opt.port))?;\n\n tcp_listener.set_nonblocking(true)?;\n\n\n\n let assets_dir = application_root_dir()?.join(\"./\");\n\n\n\n let game_data = GameDataBuilder::default()\n\n .with_bundle(TcpNetworkBundle::new(\n\n Some(tcp_listener),\n\n TCP_RECV_BUFFER_SIZE,\n\n ))?\n\n .with_system_desc(\n\n NetListenerSystemDesc::default(),\n\n any::type_name::<NetListenerSystem>(),\n\n &[\"network_recv\"],\n\n )\n", "file_path": "app/session_server/src/main.rs", "rank": 4, "score": 211542.62221924687 }, { "content": "fn run(opt: &Opt) -> Result<(), Error> {\n\n let mut intercepts = RobotState::default_intercepts();\n\n if let Some(timeout) = opt.timeout {\n\n intercepts.push(Rc::new(RefCell::new(FixedTimeoutIntercept::new(\n\n Duration::from_millis(timeout),\n\n ))));\n\n }\n\n\n\n let state = RobotState::new_with_intercepts(Box::new(EmptyState), intercepts);\n\n let game_data = GameDataBuilder::default().with_bundle(StdioInputBundle::new())?;\n\n let assets_dir = format!(\"{}/assets\", env!(\"CARGO_MANIFEST_DIR\"));\n\n CoreApplication::<_, _, StateEventReader>::new(assets_dir, state, game_data)?.run();\n\n Ok(())\n\n}\n\n\n", "file_path": "crate/stdio_input/examples/01_read_and_exit.rs", "rank": 5, "score": 193210.67323894255 }, { "content": "fn logger_setup(logger_config_path: Option<PathBuf>) -> Result<(), Error> {\n\n let is_user_specified = logger_config_path.is_some();\n\n\n\n // If the user specified a logger configuration path, use that.\n\n // Otherwise fallback to a default.\n\n let logger_config_path = logger_config_path.unwrap_or_else(|| PathBuf::from(LOGGER_CONFIG));\n\n let logger_config_path = if logger_config_path.is_relative() {\n\n let app_dir = application_root_dir()?;\n\n app_dir.join(logger_config_path)\n\n } else {\n\n logger_config_path\n\n };\n\n\n\n let logger_config: LoggerConfig = if logger_config_path.exists() {\n\n let logger_file = File::open(&logger_config_path)?;\n\n let mut logger_file_reader = BufReader::new(logger_file);\n\n let logger_config = serde_yaml::from_reader(&mut logger_file_reader)?;\n\n\n\n Ok(logger_config)\n\n } else if is_user_specified {\n", "file_path": "app/will/src/main.rs", "rank": 6, "score": 181315.83802514456 }, { "content": "fn logger_setup(logger_config_path: Option<PathBuf>) -> Result<(), Error> {\n\n let is_user_specified = logger_config_path.is_some();\n\n\n\n // If the user specified a logger configuration path, use that.\n\n // Otherwise fallback to a default.\n\n let logger_config_path = logger_config_path.unwrap_or_else(|| PathBuf::from(LOGGER_CONFIG));\n\n let logger_config_path = if logger_config_path.is_relative() {\n\n let app_dir = application_root_dir()?;\n\n app_dir.join(logger_config_path)\n\n } else {\n\n logger_config_path\n\n };\n\n\n\n let logger_config: LoggerConfig = if logger_config_path.exists() {\n\n let logger_file = File::open(&logger_config_path)?;\n\n let mut logger_file_reader = BufReader::new(logger_file);\n\n let logger_config = serde_yaml::from_reader(&mut logger_file_reader)?;\n\n\n\n Ok(logger_config)\n\n } else if is_user_specified {\n", "file_path": "app/session_server/src/main.rs", "rank": 7, "score": 178750.86219584654 }, { "content": "#[test]\n\nfn syntax_errors() {\n\n let command = \"echo (echo one); echo $( (echo one); echo ) two; echo $(echo one\";\n\n let results = StatementSplitter::new(command).collect::<Vec<_>>();\n\n assert_eq!(results[0], Err(StatementError::InvalidCharacter('(', 6)));\n\n assert_eq!(results[1], Err(StatementError::InvalidCharacter('(', 26)));\n\n assert_eq!(results[2], Err(StatementError::InvalidCharacter(')', 43)));\n\n assert_eq!(results[3], Err(StatementError::UnterminatedSubshell));\n\n assert_eq!(results.len(), 4);\n\n\n\n let command = \">echo\";\n\n let results = StatementSplitter::new(command).collect::<Vec<_>>();\n\n assert_eq!(\n\n results[0],\n\n Err(StatementError::ExpectedCommandButFound(\"redirection\"))\n\n );\n\n assert_eq!(results.len(), 1);\n\n\n\n let command = \"echo $((foo bar baz)\";\n\n let results = StatementSplitter::new(command).collect::<Vec<_>>();\n\n assert_eq!(results[0], Err(StatementError::UnterminatedArithmetic));\n\n assert_eq!(results.len(), 1);\n\n}\n\n\n", "file_path": "crate/stdio_input/src/ion/splitter.rs", "rank": 8, "score": 121464.86258713328 }, { "content": "use amethyst::ecs::{storage::NullStorage, Component};\n\n\n\n/// ID tag for entities created in the `SessionJoinState`.\n\n#[derive(Clone, Component, Copy, Debug, Default, PartialEq)]\n\n#[storage(NullStorage)]\n\npub struct SessionJoinEntity;\n", "file_path": "crate/session_join_model/src/session_join_entity.rs", "rank": 9, "score": 111879.27992080968 }, { "content": "use serde::{Deserialize, Serialize};\n\nuse strum_macros::EnumString;\n\n\n\n/// Error when attempting to join a session.\n\n#[derive(Clone, Copy, Debug, Deserialize, EnumString, PartialEq, Serialize)]\n\n#[strum(serialize_all = \"snake_case\")]\n\npub enum SessionJoinError {\n\n /// The session code does not exist on the server.\n\n SessionCodeNotFound,\n\n}\n", "file_path": "crate/session_join_model/src/play/session_join_error.rs", "rank": 10, "score": 109932.35545105969 }, { "content": "#[cfg(test)]\n\nmod test {\n\n use amethyst::{ecs::WorldExt, shrev::EventChannel, Error};\n\n use amethyst_test::AmethystApplication;\n\n use stdio_spi::VariantAndTokens;\n\n\n\n use session_join_stdio::SessionJoinStdioBundle;\n\n\n\n #[test]\n\n fn bundle_should_add_mapper_system_to_dispatcher() -> Result<(), Error> {\n\n AmethystApplication::blank()\n\n .with_bundle(SessionJoinStdioBundle::new())\n\n // kcov-ignore-start\n\n .with_effect(|world| {\n\n world.read_resource::<EventChannel<VariantAndTokens>>();\n\n })\n\n // kcov-ignore-end\n\n .run()\n\n }\n\n}\n", "file_path": "crate/workspace_tests/src/session_join_stdio/session_join_stdio_bundle.rs", "rank": 11, "score": 103537.80569631088 }, { "content": "#[cfg(test)]\n\nmod tests {\n\n use amethyst::{\n\n ecs::{Read, SystemData, World, WorldExt, WriteExpect},\n\n shrev::{EventChannel, ReaderId},\n\n Error,\n\n };\n\n use amethyst_test::AmethystApplication;\n\n use game_input_model::loaded::{PlayerController, PlayerControllers};\n\n use net_model::play::NetMessageEvent;\n\n use network_session_model::play::{SessionCode, SessionDeviceName, SessionStatus};\n\n use session_join_model::{play::SessionJoinRequestParams, SessionJoinEvent};\n\n\n\n use session_join_play::SessionJoinRequestSystemDesc;\n\n\n\n #[test]\n\n fn does_nothing_when_no_session_join_event() -> Result<(), Error> {\n\n run_test(\n\n SetupParams {\n\n session_status: SessionStatus::None,\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_request_system.rs", "rank": 12, "score": 101822.67905696807 }, { "content": "#[cfg(test)]\n\nmod tests {\n\n use std::net::{Ipv4Addr, SocketAddr};\n\n\n\n use amethyst::{\n\n ecs::{Read, WorldExt},\n\n Error,\n\n };\n\n use amethyst_test::AmethystApplication;\n\n use game_input_model::{\n\n loaded::{PlayerController, PlayerControllers},\n\n play::ControllerIdOffset,\n\n };\n\n use net_model::play::{NetData, NetEventChannel};\n\n use network_session_model::play::{\n\n Session, SessionCode, SessionDevice, SessionDeviceId, SessionDeviceName, SessionDevices,\n\n SessionStatus,\n\n };\n\n use session_join_model::{play::SessionAcceptResponse, SessionJoinEvent};\n\n\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_response_system.rs", "rank": 13, "score": 101816.21590365133 }, { "content": "\n\n fn run_test(\n\n SetupParams {\n\n session_status: session_status_setup,\n\n session_join_event,\n\n }: SetupParams,\n\n ExpectedParams {\n\n session_status: session_status_expected,\n\n net_message_event: net_message_event_expected,\n\n }: ExpectedParams,\n\n ) -> Result<(), Error> {\n\n AmethystApplication::blank()\n\n .with_setup(<Read<'_, EventChannel<NetMessageEvent>> as SystemData>::setup)\n\n .with_setup(setup_net_message_event_reader)\n\n .with_system_desc(SessionJoinRequestSystemDesc::default(), \"\", &[])\n\n .with_resource(session_status_setup)\n\n .with_effect(move |world| {\n\n if let Some(session_join_event) = session_join_event {\n\n world\n\n .write_resource::<EventChannel<SessionJoinEvent>>()\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_request_system.rs", "rank": 14, "score": 101808.0568279413 }, { "content": "#[cfg(test)]\n\nmod tests {\n\n use game_input_model::{\n\n loaded::{PlayerController, PlayerControllers},\n\n play::ControllerIdOffset,\n\n };\n\n use network_session_model::play::{\n\n Session, SessionCode, SessionDevice, SessionDeviceId, SessionDeviceName, SessionDevices,\n\n };\n\n use session_join_model::{\n\n play::{SessionAcceptResponse, SessionJoinRequestParams},\n\n SessionJoinEvent,\n\n };\n\n use stdio_spi::StdinMapper;\n\n\n\n use session_join_stdio::SessionJoinEventStdinMapper;\n\n\n\n #[test]\n\n fn maps_session_join_request_event() {\n\n let session_device_name = SessionDeviceName::from(String::from(\"エイズリエル\"));\n", "file_path": "crate/workspace_tests/src/session_join_stdio/session_join_event_stdin_mapper.rs", "rank": 15, "score": 101806.21409961548 }, { "content": " }: SetupParams,\n\n ExpectedParams {\n\n session_code: session_code_expected,\n\n session_device_id: session_device_id_expected,\n\n session_devices: session_devices_expected,\n\n session_status: session_status_expected,\n\n player_controllers: player_controllers_expected,\n\n controller_id_offset: controller_id_offset_expected,\n\n }: ExpectedParams,\n\n ) -> Result<(), Error> {\n\n AmethystApplication::blank()\n\n .with_system_desc(SessionJoinResponseSystemDesc::default(), \"\", &[])\n\n .with_setup(move |world| {\n\n world.insert(session_code_setup);\n\n world.insert(session_device_id_setup);\n\n world.insert(session_devices_setup);\n\n world.insert(session_status_setup);\n\n })\n\n .with_effect(move |world| {\n\n if let Some(session_join_event) = session_join_event {\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_response_system.rs", "rank": 16, "score": 101805.57789703211 }, { "content": " run_test(\n\n SetupParams {\n\n session_status: SessionStatus::None,\n\n session_join_event: Some(session_join_event.clone()),\n\n },\n\n ExpectedParams {\n\n session_status: SessionStatus::JoinRequested {\n\n session_code: SessionCode::new(String::from(\"abcd\")),\n\n },\n\n net_message_event: Some(NetMessageEvent::SessionJoinEvent(session_join_event)),\n\n },\n\n )\n\n }\n\n\n\n #[test]\n\n fn ignores_session_join_request_when_already_requested() -> Result<(), Error> {\n\n run_test(\n\n SetupParams {\n\n session_status: SessionStatus::JoinRequested {\n\n session_code: SessionCode::new(String::from(\"abcd\")),\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_request_system.rs", "rank": 17, "score": 101804.16837800015 }, { "content": " use session_join_play::SessionJoinResponseSystemDesc;\n\n\n\n #[test]\n\n fn does_nothing_when_no_session_join_event() -> Result<(), Error> {\n\n run_test(\n\n SetupParams {\n\n session_code: SessionCode::new(String::from(\"abcd\")),\n\n session_device_id: SessionDeviceId::new(123),\n\n session_devices: SessionDevices::new(vec![]),\n\n session_status: SessionStatus::None,\n\n session_join_event: None,\n\n },\n\n ExpectedParams {\n\n session_code: SessionCode::new(String::from(\"abcd\")),\n\n session_device_id: SessionDeviceId::new(123),\n\n session_devices: SessionDevices::new(vec![]),\n\n session_status: SessionStatus::None,\n\n player_controllers: PlayerControllers::default(),\n\n controller_id_offset: ControllerIdOffset::default(),\n\n },\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_response_system.rs", "rank": 18, "score": 101803.77377831002 }, { "content": " session_join_event: None,\n\n },\n\n ExpectedParams {\n\n session_status: SessionStatus::None,\n\n net_message_event: None,\n\n },\n\n )\n\n }\n\n\n\n #[test]\n\n fn inserts_resources_on_session_accepted() -> Result<(), Error> {\n\n let session_join_event = SessionJoinEvent::SessionJoinRequest(SessionJoinRequestParams {\n\n session_code: SessionCode::new(String::from(\"abcd\")),\n\n session_device_name: SessionDeviceName::new(String::from(\"azriel\")),\n\n player_controllers: PlayerControllers::new(vec![PlayerController::new(\n\n 0,\n\n String::from(\"p0\"),\n\n )]),\n\n });\n\n\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_request_system.rs", "rank": 19, "score": 101802.18259301834 }, { "content": " )\n\n }\n\n\n\n #[test]\n\n fn inserts_resources_on_session_accepted() -> Result<(), Error> {\n\n let player_controllers = PlayerControllers::new(vec![\n\n PlayerController::new(0, String::from(\"p0\")),\n\n PlayerController::new(1, String::from(\"p1\")),\n\n PlayerController::new(2, String::from(\"p2\")),\n\n ]);\n\n\n\n run_test(\n\n SetupParams {\n\n session_code: SessionCode::new(String::from(\"abcd\")),\n\n session_device_id: SessionDeviceId::new(123),\n\n session_devices: SessionDevices::new(vec![]),\n\n session_status: SessionStatus::JoinRequested {\n\n session_code: SessionCode::new(String::from(\"defg\")),\n\n },\n\n session_join_event: Some(SessionJoinEvent::SessionAccept(SessionAcceptResponse {\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_response_system.rs", "rank": 20, "score": 101801.56918209407 }, { "content": " let session_code = SessionCode::from(String::from(\"abcd\"));\n\n let player_controllers =\n\n PlayerControllers::new(vec![PlayerController::new(0, String::from(\"p0\"))]);\n\n let args = SessionJoinEvent::SessionJoinRequest(SessionJoinRequestParams {\n\n session_device_name,\n\n session_code,\n\n player_controllers,\n\n });\n\n\n\n let result = SessionJoinEventStdinMapper::map(&(), args.clone());\n\n\n\n assert!(result.is_ok());\n\n assert_eq!(args, result.unwrap())\n\n }\n\n\n\n #[test]\n\n fn maps_join_cancel_event() {\n\n let args = SessionJoinEvent::JoinCancel;\n\n\n\n let result = SessionJoinEventStdinMapper::map(&(), args.clone());\n", "file_path": "crate/workspace_tests/src/session_join_stdio/session_join_event_stdin_mapper.rs", "rank": 21, "score": 101801.46078986165 }, { "content": " let controller_id_offset = ControllerIdOffset::new(0);\n\n let args = SessionJoinEvent::SessionAccept(SessionAcceptResponse {\n\n session_device_id,\n\n session: Session {\n\n session_code,\n\n session_devices,\n\n },\n\n player_controllers,\n\n controller_id_offset,\n\n });\n\n\n\n let result = SessionJoinEventStdinMapper::map(&(), args.clone());\n\n\n\n assert!(result.is_ok());\n\n assert_eq!(args, result.unwrap())\n\n }\n\n\n\n #[test]\n\n fn maps_back_event() {\n\n let args = SessionJoinEvent::Back;\n\n\n\n let result = SessionJoinEventStdinMapper::map(&(), args.clone());\n\n\n\n assert!(result.is_ok());\n\n assert_eq!(args, result.unwrap())\n\n }\n\n}\n", "file_path": "crate/workspace_tests/src/session_join_stdio/session_join_event_stdin_mapper.rs", "rank": 22, "score": 101801.04173459833 }, { "content": " SessionDeviceId::new(234),\n\n SessionDeviceName::new(String::from(\"azriel\")),\n\n PlayerControllers::new(vec![PlayerController::new(0, String::from(\"p0\"))]),\n\n )]),\n\n session_status: SessionStatus::JoinEstablished,\n\n player_controllers,\n\n controller_id_offset: ControllerIdOffset::new(3),\n\n },\n\n )\n\n }\n\n\n\n #[test]\n\n fn ignores_session_accept_event_when_no_longer_waiting() -> Result<(), Error> {\n\n let player_controllers = PlayerControllers::new(vec![\n\n PlayerController::new(0, String::from(\"p0\")),\n\n PlayerController::new(1, String::from(\"p1\")),\n\n PlayerController::new(2, String::from(\"p2\")),\n\n ]);\n\n\n\n run_test(\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_response_system.rs", "rank": 23, "score": 101800.16402558838 }, { "content": " })\n\n .run()\n\n }\n\n\n\n fn setup_net_message_event_reader(world: &mut World) {\n\n let net_message_event_rid = world\n\n .write_resource::<EventChannel<NetMessageEvent>>()\n\n .register_reader();\n\n world.insert(net_message_event_rid);\n\n }\n\n\n\n struct SetupParams {\n\n session_status: SessionStatus,\n\n session_join_event: Option<SessionJoinEvent>,\n\n }\n\n\n\n struct ExpectedParams {\n\n session_status: SessionStatus,\n\n net_message_event: Option<NetMessageEvent>,\n\n }\n\n}\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_request_system.rs", "rank": 24, "score": 101796.71545011982 }, { "content": " let socket_addr = SocketAddr::from((Ipv4Addr::LOCALHOST, 1234));\n\n world\n\n .write_resource::<NetEventChannel<SessionJoinEvent>>()\n\n .single_write(NetData {\n\n socket_addr,\n\n data: session_join_event,\n\n });\n\n }\n\n })\n\n .with_assertion(move |world| {\n\n let (\n\n session_code,\n\n session_device_id,\n\n session_devices,\n\n session_status,\n\n player_controllers,\n\n controller_id_offset,\n\n ) = world.system_data::<(\n\n Read<'_, SessionCode>,\n\n Read<'_, SessionDeviceId>,\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_response_system.rs", "rank": 25, "score": 101796.3608989087 }, { "content": "\n\n assert!(result.is_ok());\n\n assert_eq!(args, result.unwrap())\n\n }\n\n\n\n #[test]\n\n fn maps_session_accept_event() {\n\n let session_code = SessionCode::from(String::from(\"abcd\"));\n\n let session_device_id = SessionDeviceId::new(1);\n\n let session_devices = SessionDevices::new(vec![\n\n SessionDevice {\n\n id: SessionDeviceId::new(1),\n\n name: SessionDeviceName::from(String::from(\"エイズリエル\")),\n\n player_controllers: PlayerControllers::new(vec![PlayerController::new(\n\n 0,\n\n String::from(\"p0\"),\n\n )]),\n\n },\n\n SessionDevice {\n\n id: SessionDeviceId::new(2),\n", "file_path": "crate/workspace_tests/src/session_join_stdio/session_join_event_stdin_mapper.rs", "rank": 26, "score": 101793.72148352458 }, { "content": " .single_write(session_join_event);\n\n }\n\n })\n\n .with_assertion(move |world| {\n\n let (session_status, mut net_message_event_rid, net_message_ec) = world\n\n .system_data::<(\n\n Read<'_, SessionStatus>,\n\n WriteExpect<'_, ReaderId<NetMessageEvent>>,\n\n Read<'_, EventChannel<NetMessageEvent>>,\n\n )>();\n\n let session_status = &*session_status;\n\n let net_message_event = net_message_ec.read(&mut *net_message_event_rid).next();\n\n\n\n assert_eq!(\n\n (\n\n &session_status_expected,\n\n net_message_event_expected.as_ref()\n\n ),\n\n (session_status, net_message_event)\n\n );\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_request_system.rs", "rank": 27, "score": 101793.40093562688 }, { "content": " })),\n\n },\n\n ExpectedParams {\n\n session_code: SessionCode::new(String::from(\"abcd\")),\n\n session_device_id: SessionDeviceId::new(123),\n\n session_devices: SessionDevices::new(vec![]),\n\n session_status: SessionStatus::None,\n\n player_controllers: PlayerControllers::default(),\n\n controller_id_offset: ControllerIdOffset::default(),\n\n },\n\n )\n\n }\n\n\n\n fn run_test(\n\n SetupParams {\n\n session_code: session_code_setup,\n\n session_device_id: session_device_id_setup,\n\n session_devices: session_devices_setup,\n\n session_status: session_status_setup,\n\n session_join_event,\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_response_system.rs", "rank": 28, "score": 101792.05284696059 }, { "content": " },\n\n session_join_event: Some(SessionJoinEvent::SessionJoinRequest(\n\n SessionJoinRequestParams {\n\n session_code: SessionCode::new(String::from(\"abcd\")),\n\n session_device_name: SessionDeviceName::new(String::from(\"azriel\")),\n\n player_controllers: PlayerControllers::new(vec![PlayerController::new(\n\n 0,\n\n String::from(\"p0\"),\n\n )]),\n\n },\n\n )),\n\n },\n\n ExpectedParams {\n\n session_status: SessionStatus::JoinRequested {\n\n session_code: SessionCode::new(String::from(\"abcd\")),\n\n },\n\n net_message_event: None,\n\n },\n\n )\n\n }\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_request_system.rs", "rank": 29, "score": 101792.03472510248 }, { "content": " })\n\n .run()\n\n }\n\n\n\n struct SetupParams {\n\n session_code: SessionCode,\n\n session_device_id: SessionDeviceId,\n\n session_devices: SessionDevices,\n\n session_status: SessionStatus,\n\n session_join_event: Option<SessionJoinEvent>,\n\n }\n\n\n\n struct ExpectedParams {\n\n session_code: SessionCode,\n\n session_device_id: SessionDeviceId,\n\n session_devices: SessionDevices,\n\n session_status: SessionStatus,\n\n player_controllers: PlayerControllers,\n\n controller_id_offset: ControllerIdOffset,\n\n }\n\n}\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_response_system.rs", "rank": 30, "score": 101790.48992786677 }, { "content": " SetupParams {\n\n session_code: SessionCode::new(String::from(\"abcd\")),\n\n session_device_id: SessionDeviceId::new(123),\n\n session_devices: SessionDevices::new(vec![]),\n\n session_status: SessionStatus::None,\n\n session_join_event: Some(SessionJoinEvent::SessionAccept(SessionAcceptResponse {\n\n session_device_id: SessionDeviceId::new(234),\n\n session: Session {\n\n session_code: SessionCode::new(String::from(\"defg\")),\n\n session_devices: SessionDevices::new(vec![SessionDevice::new(\n\n SessionDeviceId::new(234),\n\n SessionDeviceName::new(String::from(\"azriel\")),\n\n PlayerControllers::new(vec![PlayerController::new(\n\n 0,\n\n String::from(\"p0\"),\n\n )]),\n\n )]),\n\n },\n\n player_controllers,\n\n controller_id_offset: ControllerIdOffset::new(3),\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_response_system.rs", "rank": 31, "score": 101789.76688959847 }, { "content": " );\n\n\n\n assert_eq!(\n\n (\n\n &session_code_expected,\n\n &session_device_id_expected,\n\n &session_devices_expected,\n\n &session_status_expected,\n\n &player_controllers_expected,\n\n &controller_id_offset_expected,\n\n ),\n\n (\n\n session_code,\n\n session_device_id,\n\n session_devices,\n\n session_status,\n\n player_controllers,\n\n controller_id_offset,\n\n )\n\n );\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_response_system.rs", "rank": 32, "score": 101785.51264086738 }, { "content": " session_device_id: SessionDeviceId::new(234),\n\n session: Session {\n\n session_code: SessionCode::new(String::from(\"defg\")),\n\n session_devices: SessionDevices::new(vec![SessionDevice::new(\n\n SessionDeviceId::new(234),\n\n SessionDeviceName::new(String::from(\"azriel\")),\n\n PlayerControllers::new(vec![PlayerController::new(\n\n 0,\n\n String::from(\"p0\"),\n\n )]),\n\n )]),\n\n },\n\n player_controllers: player_controllers.clone(),\n\n controller_id_offset: ControllerIdOffset::new(3),\n\n })),\n\n },\n\n ExpectedParams {\n\n session_code: SessionCode::new(String::from(\"defg\")),\n\n session_device_id: SessionDeviceId::new(234),\n\n session_devices: SessionDevices::new(vec![SessionDevice::new(\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_response_system.rs", "rank": 33, "score": 101785.51264086738 }, { "content": " Read<'_, SessionDevices>,\n\n Read<'_, SessionStatus>,\n\n Read<'_, PlayerControllers>,\n\n Read<'_, ControllerIdOffset>,\n\n )>();\n\n\n\n let (\n\n session_code,\n\n session_device_id,\n\n session_devices,\n\n session_status,\n\n player_controllers,\n\n controller_id_offset,\n\n ) = (\n\n &*session_code,\n\n &*session_device_id,\n\n &*session_devices,\n\n &*session_status,\n\n &*player_controllers,\n\n &*controller_id_offset,\n", "file_path": "crate/workspace_tests/src/session_join_play/system/session_join_response_system.rs", "rank": 34, "score": 101785.51264086738 }, { "content": " name: SessionDeviceName::from(String::from(\"バイロン\")),\n\n player_controllers: PlayerControllers::new(vec![PlayerController::new(\n\n 1,\n\n String::from(\"p1\"),\n\n )]),\n\n },\n\n SessionDevice {\n\n id: SessionDeviceId::new(3),\n\n name: SessionDeviceName::from(String::from(\"カルロー\")),\n\n player_controllers: PlayerControllers::new(vec![PlayerController::new(\n\n 2,\n\n String::from(\"p2\"),\n\n )]),\n\n },\n\n ]);\n\n let player_controllers = PlayerControllers::new(vec![\n\n PlayerController::new(0, String::from(\"p0\")),\n\n PlayerController::new(1, String::from(\"p1\")),\n\n PlayerController::new(2, String::from(\"p2\")),\n\n ]);\n", "file_path": "crate/workspace_tests/src/session_join_stdio/session_join_event_stdin_mapper.rs", "rank": 35, "score": 101785.51264086738 }, { "content": "#[cfg(test)]\n\nmod test {\n\n use amethyst::{GameData, State, Trans};\n\n\n\n use debug_util_amethyst::{assert_eq_opt_trans, assert_eq_trans};\n\n\n\n #[macro_use]\n\n macro_rules! test_opt_trans_panic {\n\n ($test_name:ident, $message:expr, $expected:expr, $actual:expr) => {\n\n #[test]\n\n #[should_panic(expected = $message)]\n\n fn $test_name() {\n\n assert_eq_opt_trans::<GameData<'static, 'static>, ()>($expected, $actual);\n\n } // kcov-ignore\n\n };\n\n }\n\n\n\n #[test]\n\n fn assert_eq_trans_does_not_panic_on_same_trans_discriminant() {\n\n assert_eq_trans::<GameData<'static, 'static>, ()>(&Trans::None, &Trans::None);\n", "file_path": "crate/workspace_tests/src/debug_util_amethyst.rs", "rank": 36, "score": 98773.27871120021 }, { "content": " assert_eq_trans(\n\n &Trans::Push(Box::new(MockState)),\n\n &Trans::Push(Box::new(MockState)),\n\n ); // kcov-ignore\n\n }\n\n\n\n #[test]\n\n #[should_panic(expected = \"Expected `None` but got `Push`.\")]\n\n fn assert_eq_trans_panics_on_different_trans_discriminant() {\n\n assert_eq_trans(&Trans::None, &Trans::Push(Box::new(MockState)));\n\n } // kcov-ignore\n\n\n\n #[test]\n\n fn assert_eq_opt_trans_does_not_panic_on_none_none() {\n\n assert_eq_opt_trans::<GameData<'static, 'static>, ()>(None, None);\n\n }\n\n\n\n #[test]\n\n fn assert_eq_opt_trans_does_not_panic_on_same_discriminant() {\n\n assert_eq_opt_trans::<GameData<'static, 'static>, ()>(\n", "file_path": "crate/workspace_tests/src/debug_util_amethyst.rs", "rank": 37, "score": 98759.08406834274 }, { "content": " Some(Trans::None).as_ref(),\n\n Some(Trans::None).as_ref(),\n\n );\n\n assert_eq_opt_trans(\n\n Some(Trans::Push(Box::new(MockState))).as_ref(),\n\n Some(Trans::Push(Box::new(MockState))).as_ref(),\n\n ); // kcov-ignore\n\n }\n\n\n\n test_opt_trans_panic!(\n\n assert_eq_opt_trans_panics_on_some_none,\n\n \"Expected `Some(Pop)` but got `None`.\",\n\n Some(Trans::Pop).as_ref(),\n\n None\n\n );\n\n\n\n test_opt_trans_panic!(\n\n assert_eq_opt_trans_panics_on_none_some,\n\n \"Expected `None` but got `Some(Pop)`.\",\n\n None,\n", "file_path": "crate/workspace_tests/src/debug_util_amethyst.rs", "rank": 38, "score": 98758.71759485404 }, { "content": " Some(Trans::Pop).as_ref()\n\n );\n\n\n\n test_opt_trans_panic!(\n\n assert_eq_opt_trans_panics_on_different_trans_discriminant,\n\n \"Expected `Some(Pop)` but got `Some(Push)`.\",\n\n Some(Trans::Pop).as_ref(),\n\n Some(Trans::Push(Box::new(MockState))).as_ref()\n\n );\n\n\n\n struct MockState;\n\n impl State<GameData<'static, 'static>, ()> for MockState {}\n\n}\n", "file_path": "crate/workspace_tests/src/debug_util_amethyst.rs", "rank": 39, "score": 98757.94477804625 }, { "content": "mod session_join_event_stdin_mapper;\n\nmod session_join_stdio_bundle;\n", "file_path": "crate/workspace_tests/src/session_join_stdio.rs", "rank": 40, "score": 98667.3034096502 }, { "content": "mod system;\n", "file_path": "crate/workspace_tests/src/session_join_play.rs", "rank": 41, "score": 98660.23713094695 }, { "content": "mod session_join_request_system;\n\nmod session_join_response_system;\n", "file_path": "crate/workspace_tests/src/session_join_play/system.rs", "rank": 42, "score": 96433.29419685899 }, { "content": "#[cfg(test)]\n\nmod tests {\n\n use amethyst::{\n\n core::TransformBundle,\n\n ecs::{Builder, World, WorldExt},\n\n renderer::{types::DefaultBackend, RenderEmptyBundle},\n\n shred::SystemData,\n\n Error,\n\n };\n\n use amethyst_test::AmethystApplication;\n\n use collision_model::loaded::{HitTransition, HittingTransition};\n\n use map_model::play::MapUnboundedDelete;\n\n\n\n use energy_prefab::{EnergyComponentStorages, EnergyEntityAugmenter};\n\n\n\n #[test]\n\n fn augments_entity_with_energy_components() -> Result<(), Error> {\n\n let assertion = |world: &mut World| {\n\n let entity = world.create_entity().build();\n\n {\n", "file_path": "crate/workspace_tests/src/energy_prefab/energy_entity_augmenter.rs", "rank": 43, "score": 94361.49624750746 }, { "content": "#[cfg(test)]\n\nmod test {\n\n use std::{iter::FromIterator, str::FromStr};\n\n\n\n use amethyst::{\n\n assets::{AssetStorage, Loader, Processor},\n\n ecs::{Builder, Read, ReadExpect, World, WorldExt, Write},\n\n shred::SystemData,\n\n Error,\n\n };\n\n use amethyst_test::AmethystApplication;\n\n use asset_model::{\n\n config::AssetSlug,\n\n loaded::{AssetId, AssetIdMappings},\n\n };\n\n use character_model::{\n\n config::{CharacterDefinition, CharacterSequenceName},\n\n loaded::AssetCharacterDefinitionHandle,\n\n play::RunCounter,\n\n };\n", "file_path": "crate/workspace_tests/src/character_prefab/character_entity_augmenter.rs", "rank": 44, "score": 94349.54560658289 }, { "content": " use charge_model::{\n\n config::{ChargeDelay, ChargeLimit, ChargeUseMode},\n\n play::{ChargeRetention, ChargeTrackerClock},\n\n };\n\n use game_input_model::play::ControllerInput;\n\n use map_model::play::MapBounded;\n\n use object_model::{config::Mass, play::HealthPoints};\n\n use object_status_model::config::StunPoints;\n\n use sequence_model::loaded::{AssetSequenceIdMappings, SequenceIdMappings};\n\n\n\n use character_prefab::{\n\n CharacterComponentStorages, CharacterEntityAugmenter, CharacterSpawningResources,\n\n };\n\n\n\n #[test]\n\n fn augments_entity_with_character_components() -> Result<(), Error> {\n\n let assertion = |world: &mut World| {\n\n let entity = world.create_entity().build();\n\n {\n\n let asset_id = *world.read_resource::<AssetId>();\n", "file_path": "crate/workspace_tests/src/character_prefab/character_entity_augmenter.rs", "rank": 45, "score": 94346.8811787931 }, { "content": " assert!(world.read_storage::<ChargeLimit>().contains(entity));\n\n assert!(world.read_storage::<ChargeDelay>().contains(entity));\n\n assert!(world.read_storage::<ChargeUseMode>().contains(entity));\n\n assert!(world.read_storage::<ChargeRetention>().contains(entity));\n\n };\n\n\n\n AmethystApplication::blank()\n\n .with_system(Processor::<CharacterDefinition>::new(), \"\", &[])\n\n .with_setup(|world| {\n\n <Read<'_, AssetIdMappings> as SystemData>::setup(world);\n\n <CharacterSpawningResources as SystemData>::setup(world);\n\n <CharacterComponentStorages as SystemData>::setup(world);\n\n })\n\n .with_effect(|world| {\n\n let asset_id = {\n\n let mut asset_id_mappings = world.write_resource::<AssetIdMappings>();\n\n let asset_slug =\n\n AssetSlug::from_str(\"test/char\").expect(\"Expected asset slug to be valid.\");\n\n asset_id_mappings.insert(asset_slug)\n\n };\n", "file_path": "crate/workspace_tests/src/character_prefab/character_entity_augmenter.rs", "rank": 46, "score": 94341.07652098649 }, { "content": " let mut energy_component_storages = EnergyComponentStorages::fetch(&world);\n\n EnergyEntityAugmenter::augment(entity, &mut energy_component_storages);\n\n }\n\n\n\n assert!(world.read_storage::<MapUnboundedDelete>().contains(entity));\n\n assert!(world.read_storage::<HitTransition>().contains(entity));\n\n assert!(world.read_storage::<HittingTransition>().contains(entity));\n\n };\n\n\n\n AmethystApplication::blank()\n\n .with_bundle(TransformBundle::new())\n\n .with_bundle(RenderEmptyBundle::<DefaultBackend>::new())\n\n .with_effect(|world| {\n\n <EnergyComponentStorages as SystemData>::setup(world);\n\n })\n\n .with_assertion(assertion)\n\n .run_isolated()\n\n }\n\n}\n", "file_path": "crate/workspace_tests/src/energy_prefab/energy_entity_augmenter.rs", "rank": 47, "score": 94336.7873825122 }, { "content": " let (character_spawning_resources, mut character_component_storages) = world\n\n .system_data::<(\n\n CharacterSpawningResources<'_>,\n\n CharacterComponentStorages<'_>,\n\n )>();\n\n CharacterEntityAugmenter::augment(\n\n &character_spawning_resources,\n\n &mut character_component_storages,\n\n asset_id,\n\n entity,\n\n );\n\n }\n\n\n\n assert!(world.read_storage::<ControllerInput>().contains(entity));\n\n assert!(world.read_storage::<HealthPoints>().contains(entity));\n\n assert!(world.read_storage::<StunPoints>().contains(entity));\n\n assert!(world.read_storage::<RunCounter>().contains(entity));\n\n assert!(world.read_storage::<Mass>().contains(entity));\n\n assert!(world.read_storage::<MapBounded>().contains(entity));\n\n assert!(world.read_storage::<ChargeTrackerClock>().contains(entity));\n", "file_path": "crate/workspace_tests/src/character_prefab/character_entity_augmenter.rs", "rank": 48, "score": 94334.25496520814 }, { "content": "\n\n let character_definition_handle = loader.load_from_data(\n\n character_definition,\n\n (),\n\n &*character_definition_assets,\n\n );\n\n asset_character_definition_handle.insert(asset_id, character_definition_handle);\n\n }\n\n\n\n world.insert(asset_id);\n\n })\n\n .with_assertion(assertion)\n\n .run()\n\n }\n\n}\n", "file_path": "crate/workspace_tests/src/character_prefab/character_entity_augmenter.rs", "rank": 49, "score": 94325.45707713174 }, { "content": "\n\n {\n\n let (\n\n loader,\n\n mut asset_sequence_id_mappings_character,\n\n mut asset_character_definition_handle,\n\n character_definition_assets,\n\n ) = world.system_data::<(\n\n ReadExpect<'_, Loader>,\n\n Write<'_, AssetSequenceIdMappings<CharacterSequenceName>>,\n\n Write<'_, AssetCharacterDefinitionHandle>,\n\n Read<'_, AssetStorage<CharacterDefinition>>,\n\n )>();\n\n\n\n let character_definition = CharacterDefinition::default();\n\n\n\n let sequence_id_mappings = SequenceIdMappings::from_iter(\n\n character_definition.object_definition.sequences.keys(),\n\n );\n\n asset_sequence_id_mappings_character.insert(asset_id, sequence_id_mappings);\n", "file_path": "crate/workspace_tests/src/character_prefab/character_entity_augmenter.rs", "rank": 50, "score": 94324.20563441417 }, { "content": "#[cfg(test)]\n\nmod tests {\n\n use game_input_stdio::GameInputStdioError;\n\n\n\n #[test]\n\n fn fmt_display_is_user_friendly() {\n\n assert_eq!(\n\n \"Failed to find entity with an `InputControlled` component with the specified controller ID: `4`.\\n\\\n\n The following controller IDs are associated with entities:\\n\\\n\n \\n\\\n\n * 0\\n\\\n\n * 1\\n\\\n\n \\n\\\n\n \",\n\n format!(\"{}\", GameInputStdioError::EntityWithControllerIdNotFound { controller_id: 4, existent_controllers: vec![0, 1] })\n\n );\n\n }\n\n}\n", "file_path": "crate/workspace_tests/src/game_input_stdio/game_input_stdio_error.rs", "rank": 51, "score": 90371.69472689544 }, { "content": "#[cfg(test)]\n\nmod tests {\n\n use asset_model::config::{AssetSlugBuildError, AssetSlugSegment};\n\n\n\n #[test]\n\n fn namespace_must_be_specified() {\n\n assert_eq!(\n\n \"Namespace is a required value.\",\n\n String::from(AssetSlugBuildError::NoValueProvided {\n\n segment: AssetSlugSegment::Namespace\n\n })\n\n );\n\n }\n\n\n\n #[test]\n\n fn namespace_must_not_be_empty() {\n\n assert_eq!(\n\n \"Namespace must not be empty.\",\n\n String::from(AssetSlugBuildError::SegmentEmpty {\n\n segment: AssetSlugSegment::Namespace\n", "file_path": "crate/workspace_tests/src/asset_model/config/asset_slug_build_error.rs", "rank": 52, "score": 90365.94519701114 }, { "content": "#[cfg(test)]\n\nmod tests {\n\n use amethyst::{\n\n ecs::{Builder, Entities, Entity, WorldExt},\n\n Error,\n\n };\n\n use amethyst_test::AmethystApplication;\n\n use parent_model::play::ParentEntity;\n\n\n\n use parent_play::ChildEntityDeleteSystem;\n\n\n\n #[test]\n\n fn deletes_entities_when_parent_entity_is_dead() -> Result<(), Error> {\n\n AmethystApplication::blank()\n\n .with_system(ChildEntityDeleteSystem::new(), \"\", &[])\n\n .with_effect(|world| {\n\n let entity_parent = world.create_entity().build();\n\n let entity_child = world\n\n .create_entity()\n\n .with(ParentEntity::new(entity_parent))\n", "file_path": "crate/workspace_tests/src/parent_play/system/child_entity_delete_system.rs", "rank": 53, "score": 90362.9702356666 }, { "content": "\n\n #[test]\n\n fn name_must_not_contain_forward_slash() {\n\n assert_eq!(\n\n \"Name must not contain the '/' character: `a/b`.\",\n\n String::from(AssetSlugBuildError::SegmentContainsForwardSlash {\n\n segment: AssetSlugSegment::Name,\n\n value: String::from(\"a/b\")\n\n })\n\n );\n\n }\n\n\n\n #[test]\n\n fn from_str_returns_err_when_too_few_segments() {\n\n assert_eq!(\n\n \"Expected exactly one `/` in asset slug string: `test`.\",\n\n String::from(AssetSlugBuildError::InvalidSegmentCount {\n\n value: String::from(\"test\")\n\n })\n\n );\n", "file_path": "crate/workspace_tests/src/asset_model/config/asset_slug_build_error.rs", "rank": 54, "score": 90358.40968660216 }, { "content": " }\n\n\n\n #[test]\n\n fn from_str_returns_err_when_too_many_segments() {\n\n assert_eq!(\n\n \"Expected exactly one `/` in asset slug string: `test/abc/def`.\",\n\n String::from(AssetSlugBuildError::InvalidSegmentCount {\n\n value: String::from(\"test/abc/def\")\n\n })\n\n );\n\n }\n\n\n\n #[test]\n\n fn from_str_returns_err_from_builder_when_invalid() {\n\n assert_eq!(\n\n \"Name must not contain whitespace: `a b`.\",\n\n String::from(AssetSlugBuildError::SegmentContainsWhitespace {\n\n segment: AssetSlugSegment::Name,\n\n value: String::from(\"a b\")\n\n })\n\n );\n\n }\n\n}\n", "file_path": "crate/workspace_tests/src/asset_model/config/asset_slug_build_error.rs", "rank": 55, "score": 90358.31399822916 }, { "content": " \"Namespace must not contain the '/' character: `a/b`.\",\n\n String::from(AssetSlugBuildError::SegmentContainsForwardSlash {\n\n segment: AssetSlugSegment::Namespace,\n\n value: String::from(\"a/b\")\n\n })\n\n );\n\n }\n\n\n\n #[test]\n\n fn name_must_be_specified() {\n\n assert_eq!(\n\n \"Name is a required value.\",\n\n String::from(AssetSlugBuildError::NoValueProvided {\n\n segment: AssetSlugSegment::Name\n\n })\n\n );\n\n }\n\n\n\n #[test]\n\n fn name_must_not_be_empty() {\n", "file_path": "crate/workspace_tests/src/asset_model/config/asset_slug_build_error.rs", "rank": 56, "score": 90357.6884720852 }, { "content": " assert_eq!(\n\n \"Name must not be empty.\",\n\n String::from(AssetSlugBuildError::SegmentEmpty {\n\n segment: AssetSlugSegment::Name\n\n })\n\n );\n\n }\n\n\n\n #[test]\n\n fn name_must_not_contain_control_character() {\n\n assert_eq!(\n\n \"Name must not contain control character: `a\\\\u{9c}b`.\",\n\n String::from(AssetSlugBuildError::SegmentContainsControlChar {\n\n segment: AssetSlugSegment::Name,\n\n value: String::from(\"aœb\")\n\n })\n\n );\n\n }\n\n\n\n #[test]\n", "file_path": "crate/workspace_tests/src/asset_model/config/asset_slug_build_error.rs", "rank": 57, "score": 90357.51201867082 }, { "content": " })\n\n );\n\n }\n\n\n\n #[test]\n\n fn namespace_must_not_contain_control_character() {\n\n assert_eq!(\n\n \"Namespace must not contain control character: `a\\\\u{9c}b`.\",\n\n String::from(AssetSlugBuildError::SegmentContainsControlChar {\n\n segment: AssetSlugSegment::Namespace,\n\n value: String::from(\"aœb\")\n\n })\n\n );\n\n }\n\n\n\n #[test]\n\n fn namespace_must_not_start_with_numeric_character() {\n\n assert_eq!(\n\n \"Namespace must not start with numeric character: `1ab`.\",\n\n String::from(AssetSlugBuildError::SegmentStartsWithNumericChar {\n", "file_path": "crate/workspace_tests/src/asset_model/config/asset_slug_build_error.rs", "rank": 58, "score": 90357.2307661326 }, { "content": " segment: AssetSlugSegment::Namespace,\n\n value: String::from(\"1ab\")\n\n })\n\n );\n\n }\n\n\n\n #[test]\n\n fn namespace_must_not_contain_whitespace() {\n\n assert_eq!(\n\n \"Namespace must not contain whitespace: `a b`.\",\n\n String::from(AssetSlugBuildError::SegmentContainsWhitespace {\n\n segment: AssetSlugSegment::Namespace,\n\n value: String::from(\"a b\")\n\n })\n\n );\n\n }\n\n\n\n #[test]\n\n fn namespace_must_not_contain_forward_slash() {\n\n assert_eq!(\n", "file_path": "crate/workspace_tests/src/asset_model/config/asset_slug_build_error.rs", "rank": 59, "score": 90356.50522784698 }, { "content": " fn name_must_not_start_with_numeric_character() {\n\n assert_eq!(\n\n \"Name must not start with numeric character: `1ab`.\",\n\n String::from(AssetSlugBuildError::SegmentStartsWithNumericChar {\n\n segment: AssetSlugSegment::Name,\n\n value: String::from(\"1ab\")\n\n })\n\n );\n\n }\n\n\n\n #[test]\n\n fn name_must_not_contain_whitespace() {\n\n assert_eq!(\n\n \"Name must not contain whitespace: `a b`.\",\n\n String::from(AssetSlugBuildError::SegmentContainsWhitespace {\n\n segment: AssetSlugSegment::Name,\n\n value: String::from(\"a b\")\n\n })\n\n );\n\n }\n", "file_path": "crate/workspace_tests/src/asset_model/config/asset_slug_build_error.rs", "rank": 60, "score": 90355.68560592474 }, { "content": " .with_assertion(|world| {\n\n let (entity_parent, entity_child) = *world.read_resource::<(Entity, Entity)>();\n\n let entities = world.system_data::<Entities<'_>>();\n\n\n\n assert!(!entities.is_alive(entity_parent));\n\n assert!(!entities.is_alive(entity_child));\n\n })\n\n .run()\n\n }\n\n\n\n #[test]\n\n fn ignores_entities_without_parent_entity_component() -> Result<(), Error> {\n\n AmethystApplication::blank()\n\n .with_system(ChildEntityDeleteSystem::new(), \"\", &[])\n\n .with_effect(|world| {\n\n let entity_parent = world.create_entity().build();\n\n let entity_other = world.create_entity().build();\n\n\n\n world.insert((entity_parent, entity_other));\n\n })\n", "file_path": "crate/workspace_tests/src/parent_play/system/child_entity_delete_system.rs", "rank": 61, "score": 90348.52079479316 }, { "content": " .build();\n\n\n\n world.insert((entity_parent, entity_child));\n\n })\n\n .with_assertion(|world| {\n\n let (entity_parent, entity_child) = *world.read_resource::<(Entity, Entity)>();\n\n let entities = world.system_data::<Entities<'_>>();\n\n\n\n assert!(entities.is_alive(entity_parent));\n\n assert!(entities.is_alive(entity_child));\n\n })\n\n .with_effect(|world| {\n\n let (entity_parent, _entity_child) = *world.read_resource::<(Entity, Entity)>();\n\n let entities = world.system_data::<Entities<'_>>();\n\n\n\n entities\n\n .delete(entity_parent)\n\n .expect(\"Failed to delete `entity_parent`.\");\n\n })\n\n .with_effect(|_| {}) // Wait for one more tick.\n", "file_path": "crate/workspace_tests/src/parent_play/system/child_entity_delete_system.rs", "rank": 62, "score": 90335.07542737876 }, { "content": " .with_effect(|world| {\n\n let (entity_parent, _entity_other) = *world.read_resource::<(Entity, Entity)>();\n\n let entities = world.system_data::<Entities<'_>>();\n\n\n\n entities\n\n .delete(entity_parent)\n\n .expect(\"Failed to delete `entity_parent`.\");\n\n })\n\n .with_effect(|_| {}) // Wait for one more tick.\n\n .with_assertion(|world| {\n\n let (entity_parent, entity_other) = *world.read_resource::<(Entity, Entity)>();\n\n let entities = world.system_data::<Entities<'_>>();\n\n\n\n assert!(!entities.is_alive(entity_parent));\n\n assert!(entities.is_alive(entity_other));\n\n })\n\n .run()\n\n }\n\n}\n", "file_path": "crate/workspace_tests/src/parent_play/system/child_entity_delete_system.rs", "rank": 63, "score": 90335.04753566557 }, { "content": "/// Asserts that the `Trans` objects, disregarding their `State`, are equal.\n\n///\n\n/// This `panic!`s with a readable error message when the assertion fails.\n\n///\n\n/// # Parameters\n\n///\n\n/// * `expected`: The `Trans` that is desired.\n\n/// * `actual`: The `Trans` that was acquired.\n\n///\n\n/// # Examples\n\n///\n\n/// Successful assertion:\n\n///\n\n/// ```rust\n\n/// # extern crate amethyst;\n\n/// # extern crate debug_util_amethyst;\n\n/// #\n\n/// # use amethyst::prelude::*;\n\n/// # use debug_util_amethyst::assert_eq_trans;\n\n/// #\n\n/// // ok\n\n/// assert_eq_trans::<(), ()>(&Trans::None, &Trans::None);\n\n/// ```\n\n///\n\n/// Failing assertion:\n\n///\n\n/// ```rust,should_panic\n\n/// # extern crate amethyst;\n\n/// # extern crate debug_util_amethyst;\n\n/// #\n\n/// # use amethyst::prelude::*;\n\n/// # use debug_util_amethyst::assert_eq_trans;\n\n/// #\n\n/// // panic: Expected `Trans::None` but got `Trans::Pop`.\n\n/// assert_eq_trans::<(), ()>(&Trans::None, &Trans::Pop);\n\n/// ```\n\n///\n\n/// # Panics\n\n///\n\n/// When the expected and actual `Trans` differ.\n\npub fn assert_eq_trans<T, E>(expected: &Trans<T, E>, actual: &Trans<T, E>) {\n\n assert_eq!(\n\n discriminant(expected),\n\n discriminant(actual),\n\n \"Expected `{:?}` but got `{:?}`.\",\n\n expected,\n\n actual\n\n );\n\n}\n\n\n", "file_path": "crate/debug_util_amethyst/src/lib.rs", "rank": 64, "score": 88752.32992608017 }, { "content": "/// Asserts that the `Trans` objects contained in the `Option`s, disregarding their `State`, are\n\n/// equal.\n\n///\n\n/// This `panic!`s with a readable error message when the assertion fails.\n\n///\n\n/// # Parameters\n\n///\n\n/// * `expected`: The `Option<Trans>` that is desired.\n\n/// * `actual`: The `Option<Trans>` that was acquired.\n\n///\n\n/// # Examples\n\n///\n\n/// Successful assertion:\n\n///\n\n/// ```rust\n\n/// # extern crate amethyst;\n\n/// # extern crate debug_util_amethyst;\n\n/// #\n\n/// # use amethyst::prelude::*;\n\n/// # use debug_util_amethyst::assert_eq_opt_trans;\n\n/// #\n\n/// assert_eq_opt_trans::<(), ()>(None, None);\n\n/// assert_eq_opt_trans::<(), ()>(Some(Trans::None).as_ref(), Some(Trans::None).as_ref());\n\n/// ```\n\n///\n\n/// Failing assertion:\n\n///\n\n/// ```rust,should_panic\n\n/// # extern crate amethyst;\n\n/// # extern crate debug_util_amethyst;\n\n/// #\n\n/// # use amethyst::prelude::*;\n\n/// # use debug_util_amethyst::assert_eq_opt_trans;\n\n/// #\n\n/// // panic: Expected `Some(Trans::None)` but got `Some(Trans::Pop)`.\n\n/// assert_eq_opt_trans::<(), ()>(Some(Trans::None).as_ref(), Some(Trans::Pop).as_ref());\n\n/// ```\n\n///\n\n/// # Panics\n\n///\n\n/// When the expected and actual `Trans` differ.\n\npub fn assert_eq_opt_trans<T, E>(expected: Option<&Trans<T, E>>, actual: Option<&Trans<T, E>>) {\n\n match (expected, actual) {\n\n (Some(expected_trans), Some(actual_trans)) => assert_eq!(\n\n discriminant(expected_trans),\n\n discriminant(actual_trans),\n\n \"Expected `{:?}` but got `{:?}`.\",\n\n expected,\n\n actual\n\n ),\n\n (Some(_), None) => panic!(\"Expected `{:?}` but got `None`.\", expected),\n\n (None, Some(_)) => panic!(\"Expected `None` but got `{:?}`.\", actual),\n\n (None, None) => {}\n\n };\n\n}\n", "file_path": "crate/debug_util_amethyst/src/lib.rs", "rank": 65, "score": 83872.25058419157 }, { "content": "/// Returns an function implementation for the `ComponentData::to_owned` trait method.\n\npub fn to_owned_fn_impl(component_copy: bool, to_owned_fn: Option<Path>) -> TokenStream {\n\n if component_copy {\n\n quote! {\n\n fn to_owned(component: &Self::Component) -> Self::Component {\n\n *component\n\n }\n\n }\n\n } else {\n\n let to_owned_fn = to_owned_fn.unwrap_or_else(|| parse_quote!(std::clone::Clone::clone));\n\n\n\n quote! {\n\n fn to_owned(component: &Self::Component) -> Self::Component {\n\n #to_owned_fn(component)\n\n }\n\n }\n\n }\n\n}\n", "file_path": "crate/sequence_model_derive/src/to_owned_fn_impl.rs", "rank": 66, "score": 77581.33129643837 }, { "content": "#[test]\n\nfn quotes() {\n\n let command = \"echo \\\"This ;'is a test\\\"; echo 'This ;\\\" is also a test'\";\n\n let results = StatementSplitter::new(command).collect::<Vec<_>>();\n\n assert_eq!(results.len(), 2);\n\n assert_eq!(\n\n results[0],\n\n Ok(StatementVariant::Default(\"echo \\\"This ;'is a test\\\"\"))\n\n );\n\n assert_eq!(\n\n results[1],\n\n Ok(StatementVariant::Default(\"echo 'This ;\\\" is also a test'\"))\n\n );\n\n}\n\n\n", "file_path": "crate/stdio_input/src/ion/splitter.rs", "rank": 67, "score": 72937.58664003076 }, { "content": "#[test]\n\nfn variants() {\n\n let command = r#\"echo \"Hello!\"; echo \"How are you doing?\" && echo \"I'm just an ordinary test.\" || echo \"Helping by making sure your code works right.\"; echo \"Have a good day!\"\"#;\n\n let results = StatementSplitter::new(command).collect::<Vec<_>>();\n\n assert_eq!(results.len(), 5);\n\n assert_eq!(\n\n results[0],\n\n Ok(StatementVariant::Default(r#\"echo \"Hello!\"\"#))\n\n );\n\n assert_eq!(\n\n results[1],\n\n Ok(StatementVariant::Default(r#\"echo \"How are you doing?\"\"#))\n\n );\n\n assert_eq!(\n\n results[2],\n\n Ok(StatementVariant::And(\n\n r#\"echo \"I'm just an ordinary test.\"\"#\n\n ))\n\n );\n\n assert_eq!(\n\n results[3],\n\n Ok(StatementVariant::Or(\n\n r#\"echo \"Helping by making sure your code works right.\"\"#\n\n ))\n\n );\n\n assert_eq!(\n\n results[4],\n\n Ok(StatementVariant::Default(r#\"echo \"Have a good day!\"\"#))\n\n );\n\n}\n", "file_path": "crate/stdio_input/src/ion/splitter.rs", "rank": 68, "score": 72937.58664003076 }, { "content": "#[test]\n\nfn processes() {\n\n let command = \"echo $(seq 1 10); echo $(seq 1 10)\";\n\n for statement in StatementSplitter::new(command) {\n\n assert_eq!(statement, Ok(StatementVariant::Default(\"echo $(seq 1 10)\")));\n\n }\n\n}\n\n\n", "file_path": "crate/stdio_input/src/ion/splitter.rs", "rank": 69, "score": 72937.58664003076 }, { "content": "#[test]\n\nfn comments() {\n\n let command = \"echo $(echo one # two); echo three # four\";\n\n let results = StatementSplitter::new(command).collect::<Vec<_>>();\n\n assert_eq!(results.len(), 2);\n\n assert_eq!(\n\n results[0],\n\n Ok(StatementVariant::Default(\"echo $(echo one # two)\"))\n\n );\n\n assert_eq!(results[1], Ok(StatementVariant::Default(\"echo three\")));\n\n}\n\n\n", "file_path": "crate/stdio_input/src/ion/splitter.rs", "rank": 70, "score": 72937.58664003076 }, { "content": "#[test]\n\nfn methods() {\n\n let command = \"echo $join(array, ', '); echo @join(var, ', ')\";\n\n let statements = StatementSplitter::new(command).collect::<Vec<_>>();\n\n assert_eq!(\n\n statements[0],\n\n Ok(StatementVariant::Default(\"echo $join(array, ', ')\"))\n\n );\n\n assert_eq!(\n\n statements[1],\n\n Ok(StatementVariant::Default(\"echo @join(var, ', ')\"))\n\n );\n\n assert_eq!(statements.len(), 2);\n\n}\n\n\n", "file_path": "crate/stdio_input/src/ion/splitter.rs", "rank": 71, "score": 72937.58664003076 }, { "content": "fn main() {\n\n amethyst::start_logger(LoggerConfig {\n\n level_filter: if cfg!(debug_assertions) {\n\n LogLevelFilter::Debug\n\n } else {\n\n LogLevelFilter::Info\n\n },\n\n ..Default::default()\n\n });\n\n\n\n let opt = Opt::from_args();\n\n if let Err(e) = run(&opt) {\n\n println!(\"Failed to execute example: {}\", e);\n\n process::exit(1);\n\n }\n\n}\n", "file_path": "crate/stdio_input/examples/01_read_and_exit.rs", "rank": 72, "score": 72931.4534092138 }, { "content": "#[test]\n\nfn nested_process() {\n\n let command = \"echo $(echo one $(echo two) three)\";\n\n let results = StatementSplitter::new(command).collect::<Vec<_>>();\n\n assert_eq!(results.len(), 1);\n\n assert_eq!(results[0], Ok(StatementVariant::Default(command)));\n\n\n\n let command = \"echo $(echo $(echo one; echo two); echo two)\";\n\n let results = StatementSplitter::new(command).collect::<Vec<_>>();\n\n assert_eq!(results.len(), 1);\n\n assert_eq!(results[0], Ok(StatementVariant::Default(command)));\n\n}\n\n\n", "file_path": "crate/stdio_input/src/ion/splitter.rs", "rank": 73, "score": 71786.94777048778 }, { "content": "#[test]\n\nfn braced_variables() {\n\n let command = \"echo ${foo}bar ${bar}baz ${baz}quux @{zardoz}wibble\";\n\n let results = StatementSplitter::new(command).collect::<Vec<_>>();\n\n assert_eq!(results.len(), 1);\n\n assert_eq!(results[0], Ok(StatementVariant::Default(command)));\n\n}\n\n\n", "file_path": "crate/stdio_input/src/ion/splitter.rs", "rank": 74, "score": 71786.94777048778 }, { "content": "#[test]\n\nfn process_with_statements() {\n\n let command = \"echo $(seq 1 10; seq 1 10)\";\n\n for statement in StatementSplitter::new(command) {\n\n assert_eq!(statement, Ok(StatementVariant::Default(command)));\n\n }\n\n}\n\n\n", "file_path": "crate/stdio_input/src/ion/splitter.rs", "rank": 75, "score": 71786.94777048778 }, { "content": "#[test]\n\nfn array_processes() {\n\n let command = \"echo @(echo one; sleep 1); echo @(echo one; sleep 1)\";\n\n for statement in StatementSplitter::new(command) {\n\n assert_eq!(\n\n statement,\n\n Ok(StatementVariant::Default(\"echo @(echo one; sleep 1)\"))\n\n );\n\n }\n\n}\n\n\n", "file_path": "crate/stdio_input/src/ion/splitter.rs", "rank": 76, "score": 71786.94777048778 }, { "content": "#[test]\n\nfn nested_array_process() {\n\n let command = \"echo @(echo one @(echo two) three)\";\n\n let results = StatementSplitter::new(command).collect::<Vec<_>>();\n\n assert_eq!(results.len(), 1);\n\n assert_eq!(results[0], Ok(StatementVariant::Default(command)));\n\n\n\n let command = \"echo @(echo @(echo one; echo two); echo two)\";\n\n let results = StatementSplitter::new(command).collect::<Vec<_>>();\n\n assert_eq!(results.len(), 1);\n\n assert_eq!(results[0], Ok(StatementVariant::Default(command)));\n\n}\n\n\n", "file_path": "crate/stdio_input/src/ion/splitter.rs", "rank": 77, "score": 70687.26918433848 }, { "content": "fn begins_with_vowel(word: &str) -> bool {\n\n if let Some('A') | Some('E') | Some('I') | Some('O') | Some('U') = word.chars().next() {\n\n true\n\n } else {\n\n false\n\n }\n\n}\n", "file_path": "crate/asset_derive/src/lib.rs", "rank": 78, "score": 64571.91798319912 }, { "content": "/// Returns true if the byte matches [^A-Za-z0-9_]\n\nfn is_invalid(byte: u8) -> bool {\n\n byte <= 47\n\n || (byte >= 58 && byte <= 64)\n\n || (byte >= 91 && byte <= 94)\n\n || byte == 96\n\n || (byte >= 123 && byte <= 127)\n\n}\n\n\n\n#[derive(Debug, PartialEq)]\n\npub enum StatementVariant<'a> {\n\n And(&'a str),\n\n Or(&'a str),\n\n Default(&'a str),\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct StatementSplitter<'a> {\n\n data: &'a str,\n\n read: usize,\n\n start: usize,\n", "file_path": "crate/stdio_input/src/ion/splitter.rs", "rank": 79, "score": 64571.91798319912 }, { "content": "/// Generates the `FrameComponentData` implementation.\n\npub fn frame_component_data_impl(\n\n mut ast: DeriveInput,\n\n args: ComponentDataAttributeArgs,\n\n) -> TokenStream {\n\n let ComponentDataAttributeArgs {\n\n component_path,\n\n component_copy,\n\n to_owned_fn,\n\n } = args;\n\n\n\n ast.assert_fields_unit();\n\n derive_append(&mut ast);\n\n fields_append(&mut ast, &component_path);\n\n\n\n let type_name = &ast.ident;\n\n let to_owned_fn_impl = to_owned_fn_impl(component_copy, to_owned_fn);\n\n\n\n let fn_new_doc = format!(\"Returns a new `{}`.\", type_name);\n\n\n\n let token_stream_2 = quote! {\n", "file_path": "crate/sequence_model_derive/src/frame_component_data_impl.rs", "rank": 80, "score": 63851.62282267952 }, { "content": "/// Generates the `SequenceComponentData` implementation.\n\npub fn sequence_component_data_impl(\n\n mut ast: DeriveInput,\n\n args: ComponentDataAttributeArgs,\n\n) -> TokenStream {\n\n let ComponentDataAttributeArgs {\n\n component_path,\n\n component_copy,\n\n to_owned_fn,\n\n } = args;\n\n\n\n ast.assert_fields_unit();\n\n derive_append(&mut ast);\n\n fields_append(&mut ast, &component_path);\n\n\n\n let type_name = &ast.ident;\n\n let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();\n\n let to_owned_fn_impl = to_owned_fn_impl(component_copy, to_owned_fn);\n\n\n\n let fn_new_doc = format!(\"Returns a new `{}`.\", type_name);\n\n\n", "file_path": "crate/sequence_model_derive/src/sequence_component_data_impl.rs", "rank": 81, "score": 63851.62282267952 }, { "content": "/// Returns whether the type is known to be `Eq + Ord`.\n\n///\n\n/// Note: This is a static list, so any types not in the following list will give a false `false`:\n\nfn is_eq_ord(ty: &Type) -> bool {\n\n if let Type::Path(TypePath { path, .. }) = ty {\n\n path.segments\n\n .last()\n\n .map(|segment| {\n\n let ty_ident = &segment.ident;\n\n KNOWN_TYPES_EQ_ORD\n\n .iter()\n\n .any(|known_ty| ty_ident == known_ty)\n\n })\n\n .unwrap_or(false)\n\n } else {\n\n false\n\n }\n\n}\n", "file_path": "crate/numeric_newtype_derive/src/lib.rs", "rank": 82, "score": 63564.50459388443 }, { "content": "use amethyst::{GameData, State, StateData, Trans};\n\nuse application_event::AppEvent;\n\nuse application_state::{AppState, AppStateBuilder};\n\nuse derivative::Derivative;\n\nuse derive_new::new;\n\nuse log::debug;\n\nuse network_session_model::play::SessionStatus;\n\nuse session_join_model::{SessionJoinEntity, SessionJoinEvent};\n\nuse session_lobby::{SessionLobbyStateBuilder, SessionLobbyStateDelegate};\n\nuse state_registry::StateId;\n\n\n\n/// `State` where session joining takes place.\n\n///\n\n/// This state is not intended to be constructed directly, but through the\n\n/// [`SessionJoinStateBuilder`][state_builder].\n\n///\n\n/// [state_builder]: network_mode_selection_state/struct.SessionJoinStateBuilder.html\n\npub type SessionJoinState = AppState<'static, 'static, SessionJoinStateDelegate, SessionJoinEntity>;\n\n\n\n/// Builder for a `SessionJoinState`.\n", "file_path": "crate/session_join/src/session_join_state.rs", "rank": 83, "score": 63124.65088324821 }, { "content": "///\n\n/// `SystemBundle`s to run in the `SessionJoinState`'s dispatcher are registered on this builder.\n\npub type SessionJoinStateBuilder =\n\n AppStateBuilder<'static, 'static, SessionJoinStateDelegate, SessionJoinEntity>;\n\n\n\n/// Delegate `State` for session joining.\n\n///\n\n/// This state is not intended to be used directly, but wrapped in an `AppState`. The\n\n/// `SessionJoinState` is an alias with this as a delegate state.\n\n#[derive(Derivative, new)]\n\n#[derivative(Debug)]\n\npub struct SessionJoinStateDelegate;\n\n\n\nimpl SessionJoinStateDelegate {\n\n fn initialize_state(data: StateData<'_, GameData<'static, 'static>>) {\n\n data.world.insert(StateId::SessionJoin);\n\n data.world.insert(SessionStatus::None);\n\n }\n\n}\n\n\n", "file_path": "crate/session_join/src/session_join_state.rs", "rank": 84, "score": 63122.25951359018 }, { "content": "impl State<GameData<'static, 'static>, AppEvent> for SessionJoinStateDelegate {\n\n fn on_start(&mut self, data: StateData<'_, GameData<'static, 'static>>) {\n\n Self::initialize_state(data);\n\n }\n\n\n\n fn on_resume(&mut self, data: StateData<'_, GameData<'static, 'static>>) {\n\n Self::initialize_state(data);\n\n }\n\n\n\n fn handle_event(\n\n &mut self,\n\n _data: StateData<'_, GameData<'static, 'static>>,\n\n event: AppEvent,\n\n ) -> Trans<GameData<'static, 'static>, AppEvent> {\n\n if let AppEvent::SessionJoin(session_join_event) = event {\n\n debug!(\"Received session_join_event: {:?}\", session_join_event);\n\n match session_join_event {\n\n SessionJoinEvent::SessionAccept(_) => {\n\n let session_lobby_state =\n\n SessionLobbyStateBuilder::new(SessionLobbyStateDelegate::new()).build();\n", "file_path": "crate/session_join/src/session_join_state.rs", "rank": 85, "score": 63111.479039491416 }, { "content": " Trans::Push(Box::new(session_lobby_state))\n\n }\n\n SessionJoinEvent::Back => Trans::Pop,\n\n _ => Trans::None,\n\n }\n\n } else {\n\n Trans::None\n\n }\n\n }\n\n}\n", "file_path": "crate/session_join/src/session_join_state.rs", "rank": 86, "score": 63110.22374841251 }, { "content": "fn fields_append(ast: &mut DeriveInput) {\n\n let fields: FieldsUnnamed = parse_quote! {(pub logic_clock::LogicClock)};\n\n ast.append_unnamed(fields);\n\n}\n", "file_path": "crate/logic_clock_derive/src/lib.rs", "rank": 87, "score": 62598.92882014894 }, { "content": "fn derive_append(ast: &mut DeriveInput) {\n\n let derives = parse_quote!(\n\n Clone,\n\n Component,\n\n Copy,\n\n Debug,\n\n Default,\n\n Deref,\n\n DerefMut,\n\n Deserialize,\n\n From,\n\n Hash,\n\n PartialEq,\n\n Eq,\n\n Serialize,\n\n );\n\n\n\n ast.append_derives(derives);\n\n}\n\n\n", "file_path": "crate/logic_clock_derive/src/lib.rs", "rank": 88, "score": 62598.92882014894 }, { "content": "use serde::{Deserialize, Serialize};\n\nuse structopt_derive::StructOpt;\n\n\n\nuse crate::play::{SessionAcceptResponse, SessionJoinRequestParams, SessionRejectResponse};\n\n\n\n/// Session join state events.\n\n///\n\n/// # Examples\n\n///\n\n/// When read in as a command, the command string should look like the following:\n\n///\n\n/// * `session_join session_join_request --session-code abcd --device-name azriel --player-controllers \"0:azriel 1:friend_a`\n\n/// * `session_join join_cancel`\n\n/// * `session_join session_accept --session-code abcd --session-devices \"0:azriel::0:azriel::1:friend_a 1:byron::0:friend_b 2:carlo::0:friend_c\" --session-device-id 2`\n\n/// * `session_join back`\n\n///\n\n/// **Note:** The `session_accept` subcommand is designed to be received from the server, so sending\n\n/// this as a local command may cause undefined behaviour.\n\n#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, StructOpt)]\n\n#[serde(deny_unknown_fields, rename_all = \"snake_case\")]\n", "file_path": "crate/session_join_model/src/session_join_event.rs", "rank": 89, "score": 62220.23110904797 }, { "content": "#[structopt(rename_all = \"snake_case\")]\n\npub enum SessionJoinEvent {\n\n /// Player entered a session code.\n\n SessionJoinRequest(SessionJoinRequestParams),\n\n /// Player cancelled the request to join.\n\n JoinCancel,\n\n /// Server accepted the client's request.\n\n SessionAccept(SessionAcceptResponse),\n\n /// Server rejected the client's request.\n\n SessionReject(SessionRejectResponse),\n\n /// Return to the previous menu.\n\n Back,\n\n}\n", "file_path": "crate/session_join_model/src/session_join_event.rs", "rank": 90, "score": 62215.853694931895 }, { "content": "#[cfg(test)]\n\nmod tests {\n\n use object_model::config::{ObjectFrame, ObjectSequence};\n\n use sequence_model::config::{Sequence, SequenceEndTransition, Wait};\n\n use serde_yaml;\n\n use sprite_model::config::SpriteRef;\n\n\n\n use test_object_model::config::{TestObjectFrame, TestObjectSequence};\n\n\n\n const SEQUENCE_WITH_FRAMES_EMPTY: &str = \"frames: []\";\n\n const SEQUENCE_WITH_INPUT_REACTIONS: &str = r#\"---\n\nframes:\n\n - wait: 2\n\n sprite: { sheet: 0, index: 4 }\n\n\"#;\n\n\n\n #[test]\n\n fn sequence_with_empty_frames_list_deserializes_successfully() {\n\n let sequence = serde_yaml::from_str::<TestObjectSequence>(SEQUENCE_WITH_FRAMES_EMPTY)\n\n .expect(\"Failed to deserialize sequence.\");\n", "file_path": "crate/workspace_tests/src/test_object_model/config/test_object_sequence.rs", "rank": 91, "score": 62204.14952158106 }, { "content": "\n\n let expected = TestObjectSequence::new(ObjectSequence::default());\n\n assert_eq!(expected, sequence);\n\n }\n\n\n\n #[test]\n\n fn sequence_with_input_reactions() {\n\n let sequence = serde_yaml::from_str::<TestObjectSequence>(SEQUENCE_WITH_INPUT_REACTIONS)\n\n .expect(\"Failed to deserialize sequence.\");\n\n\n\n let frames = vec![TestObjectFrame::new(ObjectFrame {\n\n wait: Wait::new(2),\n\n sprite: SpriteRef::new(0, 4),\n\n ..Default::default()\n\n })];\n\n let expected = TestObjectSequence::new(ObjectSequence {\n\n sequence: Sequence {\n\n next: SequenceEndTransition::None,\n\n frames,\n\n },\n\n ..Default::default()\n\n });\n\n\n\n assert_eq!(expected, sequence);\n\n }\n\n}\n", "file_path": "crate/workspace_tests/src/test_object_model/config/test_object_sequence.rs", "rank": 92, "score": 62194.71484432296 }, { "content": "use std::any;\n\n\n\nuse amethyst::{\n\n core::bundle::SystemBundle,\n\n ecs::{DispatcherBuilder, World},\n\n Error,\n\n};\n\nuse application_event::AppEventVariant;\n\nuse derive_new::new;\n\nuse stdio_spi::MapperSystem;\n\n\n\nuse crate::SessionJoinEventStdinMapper;\n\n\n\n/// Adds a `MapperSystem<SessionJoinEventStdinMapper>` to the `World`.\n\n#[derive(Debug, new)]\n\npub struct SessionJoinStdioBundle;\n\n\n\nimpl<'a, 'b> SystemBundle<'a, 'b> for SessionJoinStdioBundle {\n\n fn build(\n\n self,\n", "file_path": "crate/session_join_stdio/src/session_join_stdio_bundle.rs", "rank": 93, "score": 61362.606856344144 }, { "content": " _world: &mut World,\n\n builder: &mut DispatcherBuilder<'a, 'b>,\n\n ) -> Result<(), Error> {\n\n builder.add(\n\n MapperSystem::<SessionJoinEventStdinMapper>::new(AppEventVariant::SessionJoin),\n\n any::type_name::<MapperSystem<SessionJoinEventStdinMapper>>(),\n\n &[],\n\n ); // kcov-ignore\n\n Ok(())\n\n }\n\n}\n", "file_path": "crate/session_join_stdio/src/session_join_stdio_bundle.rs", "rank": 94, "score": 61358.65092057328 }, { "content": "fn session_server_config(will_config: &WillConfig) -> SessionServerConfig {\n\n SessionServerConfig {\n\n address: will_config.session_server_address,\n\n port: will_config.session_server_port,\n\n }\n\n}\n\n\n", "file_path": "app/will/src/main.rs", "rank": 95, "score": 60783.280773305625 }, { "content": "use amethyst::Error;\n\nuse session_join_model::SessionJoinEvent;\n\nuse stdio_spi::StdinMapper;\n\n\n\n/// Builds a `SessionJoinEvent` from stdin tokens.\n\n#[derive(Debug)]\n\npub struct SessionJoinEventStdinMapper;\n\n\n\nimpl StdinMapper for SessionJoinEventStdinMapper {\n\n type SystemData = ();\n\n type Event = SessionJoinEvent;\n\n type Args = SessionJoinEvent;\n\n\n\n fn map(_: &(), args: Self::Args) -> Result<Self::Event, Error> {\n\n Ok(args)\n\n }\n\n}\n", "file_path": "crate/session_join_stdio/src/session_join_event_stdin_mapper.rs", "rank": 96, "score": 60515.937677677735 }, { "content": "use amethyst::{\n\n derive::SystemDesc,\n\n ecs::{Read, System, World, Write},\n\n shred::{ResourceId, SystemData},\n\n shrev::{EventChannel, ReaderId},\n\n};\n\nuse derivative::Derivative;\n\nuse derive_new::new;\n\nuse game_input_model::{loaded::PlayerControllers, play::ControllerIdOffset};\n\nuse log::debug;\n\nuse net_model::play::{NetData, NetEventChannel};\n\nuse network_session_model::play::{\n\n Session, SessionCode, SessionDeviceId, SessionDevices, SessionStatus,\n\n};\n\nuse session_join_model::{play::SessionAcceptResponse, SessionJoinEvent};\n\n\n\n/// Records the session code and devices in the world when accepted into a session.\n\n#[derive(Debug, SystemDesc, new)]\n\n#[system_desc(name(SessionJoinResponseSystemDesc))]\n\npub struct SessionJoinResponseSystem {\n", "file_path": "crate/session_join_play/src/system/session_join_response_system.rs", "rank": 97, "score": 60509.76208301525 }, { "content": "use amethyst::{\n\n derive::SystemDesc,\n\n ecs::{Read, System, World, Write},\n\n shred::{ResourceId, SystemData},\n\n shrev::{EventChannel, ReaderId},\n\n};\n\nuse derivative::Derivative;\n\nuse derive_new::new;\n\nuse net_model::play::NetMessageEvent;\n\nuse network_session_model::play::SessionStatus;\n\nuse session_join_model::SessionJoinEvent;\n\n\n\n/// Sends requests to a game server to join a session.\n\n#[derive(Debug, SystemDesc, new)]\n\n#[system_desc(name(SessionJoinRequestSystemDesc))]\n\npub struct SessionJoinRequestSystem {\n\n /// Reader ID for the `SessionJoinEvent` channel.\n\n #[system_desc(event_channel_reader)]\n\n session_join_event_rid: ReaderId<SessionJoinEvent>,\n\n}\n", "file_path": "crate/session_join_play/src/system/session_join_request_system.rs", "rank": 98, "score": 60509.65091180855 }, { "content": "use serde::{Deserialize, Serialize};\n\n\n\n/// Configuration parameters to send a `SessionJoinEvent`.\n\n///\n\n/// This excludes `SessionJoinEvent::SessionAccept` because that should be sent from the session\n\n/// server. For testing purposes, you may still use stdin.\n\n#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]\n\n#[serde(deny_unknown_fields, rename_all = \"snake_case\")]\n\npub enum SessionJoinEventCommand {\n\n /// Player entered a session code.\n\n ///\n\n /// The `SessionJoinRequestParams` is specially looked up by code.\n\n SessionJoinRequest,\n\n /// Player cancelled the request to join.\n\n JoinCancel,\n\n /// Return to the previous menu.\n\n Back,\n\n}\n", "file_path": "crate/session_join_model/src/config/session_join_event_command.rs", "rank": 99, "score": 60505.93226641827 } ]
Rust
binding-generator/src/smart_ptr.rs
tanxxjun321/opencv-rust
1cfceeba79eb8fffce3c8ae698c56cdf2d4e5ff5
use std::{ borrow::Cow, fmt, }; use clang::Entity; use maplit::hashmap; use once_cell::sync::Lazy; use crate::{ Constness, CompiledInterpolation, DefaultElement, DefinitionLocation, Element, EntityElement, GeneratedElement, GeneratorEnv, ReturnTypeWrapper, StrExt, type_ref::TemplateArg, TypeRef, }; #[derive(Clone)] pub struct SmartPtr<'tu, 'g> { entity: Entity<'tu>, gen_env: &'g GeneratorEnv<'tu>, } impl<'tu, 'g> SmartPtr<'tu, 'g> { pub fn new(entity: Entity<'tu>, gen_env: &'g GeneratorEnv<'tu>) -> Self { Self { entity, gen_env } } pub fn type_ref(&self) -> TypeRef<'tu, 'g> { TypeRef::new(self.entity.get_type().expect("Can't get smartptr type"), self.gen_env) } pub fn pointee(&self) -> TypeRef<'tu, 'g> { self.type_ref().template_specialization_args().into_iter() .find_map(|a| if let TemplateArg::Typename(type_ref) = a { Some(type_ref) } else { None }).expect("smart pointer template argument list is empty") } pub fn dependent_types(&self) -> Vec<Box<dyn GeneratedElement + 'g>> { let canon = self.type_ref().canonical_clang(); let mut out = vec![ Box::new(ReturnTypeWrapper::new(canon.clone(), self.gen_env, DefinitionLocation::Module)) as Box<dyn GeneratedElement> ]; if self.pointee().as_typedef().is_some() { out.extend(canon.dependent_types()) } out } pub fn rust_localalias(&self) -> Cow<str> { format!("PtrOf{typ}", typ=self.pointee().rust_safe_id()).into() } pub fn rust_fullalias(&self) -> Cow<str> { format!("types::{}", self.rust_localalias()).into() } } impl<'tu> EntityElement<'tu> for SmartPtr<'tu, '_> { fn entity(&self) -> Entity<'tu> { self.entity } } impl Element for SmartPtr<'_, '_> { fn is_excluded(&self) -> bool { DefaultElement::is_excluded(self) || self.pointee().is_excluded() } fn is_ignored(&self) -> bool { DefaultElement::is_ignored(self) || self.pointee().is_ignored() } fn is_system(&self) -> bool { DefaultElement::is_system(self) } fn is_public(&self) -> bool { DefaultElement::is_public(self) } fn usr(&self) -> Cow<str> { DefaultElement::usr(self) } fn rendered_doc_comment_with_prefix(&self, prefix: &str, opencv_version: &str) -> String { DefaultElement::rendered_doc_comment_with_prefix(self, prefix, opencv_version) } fn cpp_namespace(&self) -> Cow<str> { "cv".into() } fn cpp_localname(&self) -> Cow<str> { "Ptr".into() } fn rust_module(&self) -> Cow<str> { self.pointee().rust_module().into_owned().into() } fn rust_namespace(&self) -> Cow<str> { "core".into() } fn rust_leafname(&self) -> Cow<str> { format!("Ptr::<{typ}>", typ=self.pointee().rust_full()).into() } fn rust_localname(&self) -> Cow<str> { DefaultElement::rust_localname(self) } } impl GeneratedElement for SmartPtr<'_, '_> { fn element_safe_id(&self) -> String { format!("{}-{}", self.rust_module(), self.rust_localalias()) } fn gen_rust(&self, _opencv_version: &str) -> String { static TPL: Lazy<CompiledInterpolation> = Lazy::new( || include_str!("../tpl/smart_ptr/rust.tpl.rs").compile_interpolation() ); static TRAIT_CAST_TPL: Lazy<CompiledInterpolation> = Lazy::new( || include_str!("../tpl/smart_ptr/trait_cast.tpl.rs").compile_interpolation() ); let type_ref = self.type_ref(); let pointee = self.pointee(); let pointee_type = pointee.canonical(); let mut inter_vars = hashmap! { "rust_localalias" => self.rust_localalias(), "rust_full" => self.rust_fullname(), "rust_extern_const" => type_ref.rust_extern_with_const(Constness::Const), "rust_extern_mut" => type_ref.rust_extern_with_const(Constness::Mut), "inner_rust_full" => pointee_type.rust_full(), }; let mut impls = String::new(); if let Some(cls) = pointee_type.as_class() { if cls.is_trait() { let mut all_bases = cls.all_bases(); all_bases.insert(cls); let mut all_bases = all_bases.into_iter() .filter(|b| !b.is_excluded()) .collect::<Vec<_>>(); all_bases.sort_unstable_by(|a, b| a.cpp_localname().cmp(&b.cpp_localname())); for base in all_bases { inter_vars.insert("base_rust_local", base.rust_localname().into_owned().into()); inter_vars.insert("base_rust_full", base.rust_trait_fullname().into_owned().into()); impls += &TRAIT_CAST_TPL.interpolate(&inter_vars); } } }; inter_vars.insert("impls", impls.into()); TPL.interpolate(&inter_vars) } fn gen_cpp(&self) -> String { static TPL: Lazy<CompiledInterpolation> = Lazy::new( || include_str!("../tpl/smart_ptr/cpp.tpl.cpp").compile_interpolation() ); let type_ref = self.type_ref(); let pointee_type = self.pointee(); let mut inner_cpp_extern = pointee_type.cpp_extern_return(); if !pointee_type.is_by_ptr() { inner_cpp_extern.to_mut().push('*'); } TPL.interpolate(&hashmap! { "rust_localalias" => self.rust_localalias(), "cpp_extern" => type_ref.cpp_extern(), "cpp_full" => type_ref.cpp_full(), "inner_cpp_full" => pointee_type.cpp_full(), "inner_cpp_extern" => inner_cpp_extern, }) } } impl fmt::Display for SmartPtr<'_, '_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.entity.get_display_name().expect("Can't get display name")) } } impl fmt::Debug for SmartPtr<'_, '_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut debug_struct = f.debug_struct("SmartPtr"); self.update_debug_struct(&mut debug_struct) .field("export_config", &self.gen_env.get_export_config(self.entity)) .field("pointee", &self.pointee()) .finish() } }
use std::{ borrow::Cow, fmt, }; use clang::Entity; use maplit::hashmap; use once_cell::sync::Lazy; use crate::{ Constness, CompiledInterpolation, DefaultElement, DefinitionLocation, Element, EntityElement, GeneratedElement, GeneratorEnv, ReturnTypeWrapper, StrExt, type_ref::TemplateArg, TypeRef, }; #[derive(Clone)] pub struct SmartPtr<'tu, 'g> { entity: Entity<'tu>, gen_env: &'g GeneratorEnv<'tu>, } impl<'tu, 'g> SmartPtr<'tu, 'g> { pub fn new(entity: Entity<'tu>, gen_env: &'g GeneratorEnv<'tu>) -> Self { Self { entity, gen_env } } pub fn type_ref(&self) -> TypeRef<'tu, 'g> { TypeRef::new(self.entity.get_type().expect("Can't get smartptr type"), self.gen_env) } pub fn pointee(&self) -> TypeRef<'tu, 'g> { self.type_ref().template_specialization_args().into_iter() .find_map(|a| if let TemplateArg::Typename(type_ref) = a { Some(type_ref) } else { None }).expect("smart pointer template argument list is empty") } pub fn dependent_types(&self) -> Vec<Box<dyn GeneratedElement + 'g>> { let canon = self.type_ref().canonical_clang(); let mut out = vec![ Box::new(ReturnTypeWrapper::new(canon.clone(), self.gen_env, DefinitionLocation::Module)) as Box<dyn GeneratedElement> ]; if self.pointee().as_typedef().is_some() { out.extend(canon.dependent_types()) } out } pub fn rust_localalias(&self) -> Cow<str> { format!("PtrOf{typ}", typ=self.pointee().rust_safe_id()).into() } pub fn rust_fullalias(&self) -> Cow<str> { format!("types::{}", self.rust_localalias()).into() } } impl<'tu> EntityElement<'tu> for Sm
ment_safe_id(&self) -> String { format!("{}-{}", self.rust_module(), self.rust_localalias()) } fn gen_rust(&self, _opencv_version: &str) -> String { static TPL: Lazy<CompiledInterpolation> = Lazy::new( || include_str!("../tpl/smart_ptr/rust.tpl.rs").compile_interpolation() ); static TRAIT_CAST_TPL: Lazy<CompiledInterpolation> = Lazy::new( || include_str!("../tpl/smart_ptr/trait_cast.tpl.rs").compile_interpolation() ); let type_ref = self.type_ref(); let pointee = self.pointee(); let pointee_type = pointee.canonical(); let mut inter_vars = hashmap! { "rust_localalias" => self.rust_localalias(), "rust_full" => self.rust_fullname(), "rust_extern_const" => type_ref.rust_extern_with_const(Constness::Const), "rust_extern_mut" => type_ref.rust_extern_with_const(Constness::Mut), "inner_rust_full" => pointee_type.rust_full(), }; let mut impls = String::new(); if let Some(cls) = pointee_type.as_class() { if cls.is_trait() { let mut all_bases = cls.all_bases(); all_bases.insert(cls); let mut all_bases = all_bases.into_iter() .filter(|b| !b.is_excluded()) .collect::<Vec<_>>(); all_bases.sort_unstable_by(|a, b| a.cpp_localname().cmp(&b.cpp_localname())); for base in all_bases { inter_vars.insert("base_rust_local", base.rust_localname().into_owned().into()); inter_vars.insert("base_rust_full", base.rust_trait_fullname().into_owned().into()); impls += &TRAIT_CAST_TPL.interpolate(&inter_vars); } } }; inter_vars.insert("impls", impls.into()); TPL.interpolate(&inter_vars) } fn gen_cpp(&self) -> String { static TPL: Lazy<CompiledInterpolation> = Lazy::new( || include_str!("../tpl/smart_ptr/cpp.tpl.cpp").compile_interpolation() ); let type_ref = self.type_ref(); let pointee_type = self.pointee(); let mut inner_cpp_extern = pointee_type.cpp_extern_return(); if !pointee_type.is_by_ptr() { inner_cpp_extern.to_mut().push('*'); } TPL.interpolate(&hashmap! { "rust_localalias" => self.rust_localalias(), "cpp_extern" => type_ref.cpp_extern(), "cpp_full" => type_ref.cpp_full(), "inner_cpp_full" => pointee_type.cpp_full(), "inner_cpp_extern" => inner_cpp_extern, }) } } impl fmt::Display for SmartPtr<'_, '_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.entity.get_display_name().expect("Can't get display name")) } } impl fmt::Debug for SmartPtr<'_, '_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut debug_struct = f.debug_struct("SmartPtr"); self.update_debug_struct(&mut debug_struct) .field("export_config", &self.gen_env.get_export_config(self.entity)) .field("pointee", &self.pointee()) .finish() } }
artPtr<'tu, '_> { fn entity(&self) -> Entity<'tu> { self.entity } } impl Element for SmartPtr<'_, '_> { fn is_excluded(&self) -> bool { DefaultElement::is_excluded(self) || self.pointee().is_excluded() } fn is_ignored(&self) -> bool { DefaultElement::is_ignored(self) || self.pointee().is_ignored() } fn is_system(&self) -> bool { DefaultElement::is_system(self) } fn is_public(&self) -> bool { DefaultElement::is_public(self) } fn usr(&self) -> Cow<str> { DefaultElement::usr(self) } fn rendered_doc_comment_with_prefix(&self, prefix: &str, opencv_version: &str) -> String { DefaultElement::rendered_doc_comment_with_prefix(self, prefix, opencv_version) } fn cpp_namespace(&self) -> Cow<str> { "cv".into() } fn cpp_localname(&self) -> Cow<str> { "Ptr".into() } fn rust_module(&self) -> Cow<str> { self.pointee().rust_module().into_owned().into() } fn rust_namespace(&self) -> Cow<str> { "core".into() } fn rust_leafname(&self) -> Cow<str> { format!("Ptr::<{typ}>", typ=self.pointee().rust_full()).into() } fn rust_localname(&self) -> Cow<str> { DefaultElement::rust_localname(self) } } impl GeneratedElement for SmartPtr<'_, '_> { fn ele
random
[ { "content": "/// Default face detector\n\n/// This function is mainly utilized by the implementation of a Facemark Algorithm.\n\n/// End users are advised to use function Facemark::getFaces which can be manually defined\n\n/// and circumvented to the algorithm by Facemark::setFaceDetector.\n\n/// \n\n/// ## Parameters\n\n/// * image: The input image to be processed.\n\n/// * faces: Output of the function which represent region of interest of the detected faces.\n\n/// Each face is stored in cv::Rect container.\n\n/// * params: detector parameters\n\n/// \n\n/// <B>Example of usage</B>\n\n/// ```ignore\n\n/// std::vector<cv::Rect> faces;\n\n/// CParams params(\"haarcascade_frontalface_alt.xml\");\n\n/// cv::face::getFaces(frame, faces, &params);\n\n/// for(int j=0;j<faces.size();j++){\n\n/// cv::rectangle(frame, faces[j], cv::Scalar(255,0,255));\n\n/// }\n\n/// cv::imshow(\"detection\", frame);\n\n/// ```\n\n/// \n\npub fn get_faces(image: &dyn core::ToInputArray, faces: &mut dyn core::ToOutputArray, params: &mut crate::face::CParams) -> Result<bool> {\n\n\tinput_array_arg!(image);\n\n\toutput_array_arg!(faces);\n\n\tunsafe { sys::cv_face_getFaces_const__InputArrayX_const__OutputArrayX_CParamsX(image.as_raw__InputArray(), faces.as_raw__OutputArray(), params.as_raw_mut_CParams()) }.into_result()\n\n}\n\n\n", "file_path": "src/opencv/hub/face.rs", "rank": 0, "score": 368041.34328718204 }, { "content": "pub fn dump_input_output_array(argument: &mut dyn core::ToInputOutputArray) -> Result<String> {\n\n\tinput_output_array_arg!(argument);\n\n\tunsafe { sys::cv_utils_dumpInputOutputArray_const__InputOutputArrayX(argument.as_raw__InputOutputArray()) }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "src/opencv/hub/core.rs", "rank": 1, "score": 365292.8294835172 }, { "content": "/// Default face detector\n\n/// This function is mainly utilized by the implementation of a Facemark Algorithm.\n\n/// End users are advised to use function Facemark::getFaces which can be manually defined\n\n/// and circumvented to the algorithm by Facemark::setFaceDetector.\n\n/// \n\n/// ## Parameters\n\n/// * image: The input image to be processed.\n\n/// * faces: Output of the function which represent region of interest of the detected faces.\n\n/// Each face is stored in cv::Rect container.\n\n/// * params: detector parameters\n\n/// \n\n/// <B>Example of usage</B>\n\n/// ```ignore\n\n/// std::vector<cv::Rect> faces;\n\n/// CParams params(\"haarcascade_frontalface_alt.xml\");\n\n/// cv::face::getFaces(frame, faces, &params);\n\n/// for(int j=0;j<faces.size();j++){\n\n/// cv::rectangle(frame, faces[j], cv::Scalar(255,0,255));\n\n/// }\n\n/// cv::imshow(\"detection\", frame);\n\n/// ```\n\n/// \n\npub fn get_faces(image: &dyn core::ToInputArray, faces: &mut dyn core::ToOutputArray, params: &mut crate::face::CParams) -> Result<bool> {\n\n\tinput_array_arg!(image);\n\n\toutput_array_arg!(faces);\n\n\tunsafe { sys::cv_face_getFaces_const__InputArrayX_const__OutputArrayX_CParamsX(image.as_raw__InputArray(), faces.as_raw__OutputArray(), params.as_raw_mut_CParams()) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/face.rs", "rank": 2, "score": 364408.2548113236 }, { "content": "/// Default face detector\n\n/// This function is mainly utilized by the implementation of a Facemark Algorithm.\n\n/// End users are advised to use function Facemark::getFaces which can be manually defined\n\n/// and circumvented to the algorithm by Facemark::setFaceDetector.\n\n/// \n\n/// ## Parameters\n\n/// * image: The input image to be processed.\n\n/// * faces: Output of the function which represent region of interest of the detected faces.\n\n/// Each face is stored in cv::Rect container.\n\n/// * params: detector parameters\n\n/// \n\n/// <B>Example of usage</B>\n\n/// ```ignore\n\n/// std::vector<cv::Rect> faces;\n\n/// CParams params(\"haarcascade_frontalface_alt.xml\");\n\n/// cv::face::getFaces(frame, faces, &params);\n\n/// for(int j=0;j<faces.size();j++){\n\n/// cv::rectangle(frame, faces[j], cv::Scalar(255,0,255));\n\n/// }\n\n/// cv::imshow(\"detection\", frame);\n\n/// ```\n\n/// \n\npub fn get_faces(image: &dyn core::ToInputArray, faces: &mut dyn core::ToOutputArray, params: &mut crate::face::CParams) -> Result<bool> {\n\n\tinput_array_arg!(image);\n\n\toutput_array_arg!(faces);\n\n\tunsafe { sys::cv_face_getFaces_const__InputArrayX_const__OutputArrayX_CParamsX(image.as_raw__InputArray(), faces.as_raw__OutputArray(), params.as_raw_mut_CParams()) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/face.rs", "rank": 3, "score": 364408.2548113236 }, { "content": "pub fn dump_input_output_array_of_arrays(argument: &mut dyn core::ToInputOutputArray) -> Result<String> {\n\n\tinput_output_array_arg!(argument);\n\n\tunsafe { sys::cv_utils_dumpInputOutputArrayOfArrays_const__InputOutputArrayX(argument.as_raw__InputOutputArray()) }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "src/opencv/hub/core.rs", "rank": 4, "score": 361387.9693319682 }, { "content": "pub fn dump_input_output_array(argument: &mut dyn core::ToInputOutputArray) -> Result<String> {\n\n\tinput_output_array_arg!(argument);\n\n\tunsafe { sys::cv_utils_dumpInputOutputArray_const__InputOutputArrayX(argument.as_raw__InputOutputArray()) }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/core.rs", "rank": 5, "score": 361387.96933196817 }, { "content": "pub fn dump_input_output_array(argument: &mut dyn core::ToInputOutputArray) -> Result<String> {\n\n\tinput_output_array_arg!(argument);\n\n\tunsafe { sys::cv_utils_dumpInputOutputArray_const__InputOutputArrayX(argument.as_raw__InputOutputArray()) }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/core.rs", "rank": 6, "score": 361387.9693319682 }, { "content": "pub trait Element: fmt::Debug {\n\n\tfn update_debug_struct<'dref, 'a, 'b>(&self, struct_debug: &'dref mut fmt::DebugStruct<'a, 'b>) -> &'dref mut fmt::DebugStruct<'a, 'b> {\n\n\t\tstruct_debug.field(\"cpp_fullname\", &self.cpp_fullname())\n\n\t\t\t.field(\"rust_fullname\", &self.rust_fullname())\n\n\t\t\t.field(\"identifier\", &self.identifier())\n\n\t\t\t.field(\"is_excluded\", &self.is_excluded())\n\n\t\t\t.field(\"is_ignored\", &self.is_ignored())\n\n\t\t\t.field(\"is_system\", &self.is_system())\n\n\t\t\t.field(\"is_public\", &self.is_public())\n\n\t}\n\n\n\n\t/// true if an element shouldn't be generated\n\n\tfn is_excluded(&self) -> bool {\n\n\t\tDefaultElement::is_excluded(self)\n\n\t}\n\n\n\n\t/// true if there shouldn't be any references to that element\n\n\tfn is_ignored(&self) -> bool {\n\n\t\tDefaultElement::is_ignored(self)\n\n\t}\n", "file_path": "binding-generator/src/element.rs", "rank": 7, "score": 360998.14232778776 }, { "content": "pub fn flann_distance_type() -> Result<crate::flann::flann_distance_t> {\n\n\tunsafe { sys::cvflann_flann_distance_type() }.into_result()\n\n}\n\n\n", "file_path": "src/opencv/hub/flann.rs", "rank": 8, "score": 359096.656046537 }, { "content": "pub fn dump_input_output_array_of_arrays(argument: &mut dyn core::ToInputOutputArray) -> Result<String> {\n\n\tinput_output_array_arg!(argument);\n\n\tunsafe { sys::cv_utils_dumpInputOutputArrayOfArrays_const__InputOutputArrayX(argument.as_raw__InputOutputArray()) }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/core.rs", "rank": 9, "score": 357639.2504828869 }, { "content": "pub fn dump_input_output_array_of_arrays(argument: &mut dyn core::ToInputOutputArray) -> Result<String> {\n\n\tinput_output_array_arg!(argument);\n\n\tunsafe { sys::cv_utils_dumpInputOutputArrayOfArrays_const__InputOutputArrayX(argument.as_raw__InputOutputArray()) }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/core.rs", "rank": 10, "score": 357639.250482887 }, { "content": "pub fn flann_distance_type() -> Result<crate::flann::flann_distance_t> {\n\n\tunsafe { sys::cvflann_flann_distance_type() }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/flann.rs", "rank": 11, "score": 354254.69159927516 }, { "content": "pub fn flann_distance_type() -> Result<crate::flann::flann_distance_t> {\n\n\tunsafe { sys::cvflann_flann_distance_type() }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_32/hub/flann.rs", "rank": 12, "score": 354254.6915992751 }, { "content": "pub fn flann_distance_type() -> Result<crate::flann::flann_distance_t> {\n\n\tunsafe { sys::cvflann_flann_distance_type() }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/flann.rs", "rank": 13, "score": 354254.6915992751 }, { "content": "#[allow(unused)]\n\npub fn dbg_clang_type(type_ref: Type) {\n\n\tstruct TypeWrapper<'tu>(Type<'tu>);\n\n\n\n\timpl fmt::Debug for TypeWrapper<'_> {\n\n\t\tfn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n\t\t\tf.debug_struct(\"Type\")\n\n\t\t\t\t.field(\"kind\", &self.0.get_kind())\n\n\t\t\t\t.field(\"display_name\", &self.0.get_display_name())\n\n\t\t\t\t.field(\"alignof\", &self.0.get_alignof())\n\n\t\t\t\t.field(\"sizeof\", &self.0.get_sizeof())\n\n\t\t\t\t.field(\"address_space\", &self.0.get_address_space())\n\n\t\t\t\t.field(\"argument_types\", &self.0.get_argument_types())\n\n\t\t\t\t.field(\"calling_convention\", &self.0.get_calling_convention())\n\n\t\t\t\t.field(\"canonical_type\", &self.0.get_canonical_type())\n\n\t\t\t\t.field(\"class_type\", &self.0.get_class_type())\n\n\t\t\t\t.field(\"declaration\", &self.0.get_declaration())\n\n\t\t\t\t.field(\"elaborated_type\", &self.0.get_elaborated_type())\n\n\t\t\t\t.field(\"element_type\", &self.0.get_element_type())\n\n\t\t\t\t.field(\"exception_specification\", &self.0.get_exception_specification())\n\n\t\t\t\t.field(\"fields\", &self.0.get_fields())\n", "file_path": "binding-generator/src/generator.rs", "rank": 14, "score": 353651.79600233934 }, { "content": "fn get_debug<'tu>(e: &(impl EntityElement<'tu> + fmt::Display)) -> String {\n\n\tif false {\n\n\t\tlet loc = e.entity()\n\n\t\t\t.get_location().expect(\"Can't get entity location\")\n\n\t\t\t.get_file_location();\n\n\n\n\t\tformat!(\n\n\t\t\t\"// {} {}:{}\",\n\n\t\t\te,\n\n\t\t\tcanonicalize(loc.file.expect(\"Can't get file for debug\").get_path()).expect(\"Can't canonicalize path\").display(),\n\n\t\t\tloc.line\n\n\t\t)\n\n\t} else {\n\n\t\t\"\".to_string()\n\n\t}\n\n}\n\n\n", "file_path": "binding-generator/src/lib.rs", "rank": 15, "score": 350004.2295481536 }, { "content": "/// ////////////////////////////////////////////////////////////////////////////////////////////\n\n/// Computing normals for mesh\n\n/// ## Parameters\n\n/// * mesh: Input mesh.\n\n/// * normals: Normals at very point in the mesh of type CV_64FC3.\n\npub fn compute_normals(mesh: &crate::viz::Mesh, normals: &mut dyn core::ToOutputArray) -> Result<()> {\n\n\toutput_array_arg!(normals);\n\n\tunsafe { sys::cv_viz_computeNormals_const_MeshX_const__OutputArrayX(mesh.as_raw_Mesh(), normals.as_raw__OutputArray()) }.into_result()\n\n}\n\n\n", "file_path": "src/opencv/hub/viz.rs", "rank": 16, "score": 346723.93925292627 }, { "content": "pub fn get_available_targets(be: crate::dnn::Backend) -> Result<core::Vector::<crate::dnn::Target>> {\n\n\tunsafe { sys::cv_dnn_getAvailableTargets_Backend(be) }.into_result().map(|ptr| unsafe { core::Vector::<crate::dnn::Target>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "src/opencv/hub/dnn.rs", "rank": 17, "score": 345590.5215973981 }, { "content": "/// ////////////////////////////////////////////////////////////////////////////////////////////\n\n/// Computing normals for mesh\n\n/// ## Parameters\n\n/// * mesh: Input mesh.\n\n/// * normals: Normals at very point in the mesh of type CV_64FC3.\n\npub fn compute_normals(mesh: &crate::viz::Mesh, normals: &mut dyn core::ToOutputArray) -> Result<()> {\n\n\toutput_array_arg!(normals);\n\n\tunsafe { sys::cv_viz_computeNormals_const_MeshX_const__OutputArrayX(mesh.as_raw_Mesh(), normals.as_raw__OutputArray()) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/viz.rs", "rank": 18, "score": 342822.25974761206 }, { "content": "/// ////////////////////////////////////////////////////////////////////////////////////////////\n\n/// Computing normals for mesh\n\n/// ## Parameters\n\n/// * mesh: Input mesh.\n\n/// * normals: Normals at very point in the mesh of type CV_64FC3.\n\npub fn compute_normals(mesh: &crate::viz::Mesh, normals: &mut dyn core::ToOutputArray) -> Result<()> {\n\n\toutput_array_arg!(normals);\n\n\tunsafe { sys::cv_viz_computeNormals_const_MeshX_const__OutputArrayX(mesh.as_raw_Mesh(), normals.as_raw__OutputArray()) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/viz.rs", "rank": 19, "score": 342822.25974761206 }, { "content": "struct RefOrVoid<const void>{ typedef const void type; };\n\n\n\ntemplate<>\n", "file_path": "headers/3.4/opencv2/core/cvstd.hpp", "rank": 20, "score": 342442.1123118049 }, { "content": "struct RefOrVoid<const void>{ typedef const void type; };\n\n\n\ntemplate<>\n", "file_path": "headers/3.2/opencv2/core/cvstd.hpp", "rank": 21, "score": 342442.1123118049 }, { "content": "pub fn set_distance_type(distance_type: crate::flann::flann_distance_t, order: i32) -> Result<()> {\n\n\tunsafe { sys::cvflann_set_distance_type_flann_distance_t_int(distance_type, order) }.into_result()\n\n}\n\n\n", "file_path": "src/opencv/hub/flann.rs", "rank": 22, "score": 342346.11095574393 }, { "content": "pub fn get_available_targets(be: crate::dnn::Backend) -> Result<core::Vector::<crate::dnn::Target>> {\n\n\tunsafe { sys::cv_dnn_getAvailableTargets_Backend(be) }.into_result().map(|ptr| unsafe { core::Vector::<crate::dnn::Target>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/dnn.rs", "rank": 23, "score": 341573.82323896023 }, { "content": "pub fn get_available_targets(be: crate::dnn::Backend) -> Result<core::Vector::<crate::dnn::Target>> {\n\n\tunsafe { sys::cv_dnn_getAvailableTargets_Backend(be) }.into_result().map(|ptr| unsafe { core::Vector::<crate::dnn::Target>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/dnn.rs", "rank": 24, "score": 341573.82323896023 }, { "content": "/// Returns list of all available backends\n\npub fn get_backends() -> Result<core::Vector::<crate::videoio::VideoCaptureAPIs>> {\n\n\tunsafe { sys::cv_videoio_registry_getBackends() }.into_result().map(|ptr| unsafe { core::Vector::<crate::videoio::VideoCaptureAPIs>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "src/opencv/hub/videoio.rs", "rank": 25, "score": 338588.3489260447 }, { "content": "/// Retrieves a window by its name.\n\n/// \n\n/// ## Parameters\n\n/// * window_name: Name of the window that is to be retrieved.\n\n/// \n\n/// This function returns a Viz3d object with the given name.\n\n/// \n\n/// \n\n/// Note: If the window with that name already exists, that window is returned. Otherwise, new window is\n\n/// created with the given name, and it is returned.\n\n/// \n\n/// \n\n/// Note: Window names are automatically prefixed by \"Viz - \" if it is not done by the user.\n\n/// ```ignore\n\n/// /// window and window_2 are the same windows.\n\n/// viz::Viz3d window = viz::getWindowByName(\"myWindow\");\n\n/// viz::Viz3d window_2 = viz::getWindowByName(\"Viz - myWindow\");\n\n/// ```\n\n/// \n\npub fn get_window_by_name(window_name: &str) -> Result<crate::viz::Viz3d> {\n\n\tstring_arg!(window_name);\n\n\tunsafe { sys::cv_viz_getWindowByName_const_StringX(window_name.as_ptr()) }.into_result().map(|ptr| unsafe { crate::viz::Viz3d::from_raw(ptr) })\n\n}\n\n\n", "file_path": "src/opencv/hub/viz.rs", "rank": 26, "score": 338587.6026167049 }, { "content": "pub fn set_distance_type(distance_type: crate::flann::flann_distance_t, order: i32) -> Result<()> {\n\n\tunsafe { sys::cvflann_set_distance_type_flann_distance_t_int(distance_type, order) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_32/hub/flann.rs", "rank": 27, "score": 338339.2593646527 }, { "content": "pub fn set_distance_type(distance_type: crate::flann::flann_distance_t, order: i32) -> Result<()> {\n\n\tunsafe { sys::cvflann_set_distance_type_flann_distance_t_int(distance_type, order) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/flann.rs", "rank": 28, "score": 338339.2593646527 }, { "content": "pub fn set_distance_type(distance_type: crate::flann::flann_distance_t, order: i32) -> Result<()> {\n\n\tunsafe { sys::cvflann_set_distance_type_flann_distance_t_int(distance_type, order) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/flann.rs", "rank": 29, "score": 338339.2593646527 }, { "content": "struct ParamType<_Tp, typename std::enable_if< std::is_enum<_Tp>::value >::type>\n\n{\n\n typedef typename std::underlying_type<_Tp>::type const_param_type;\n\n typedef typename std::underlying_type<_Tp>::type member_type;\n\n\n\n static const Param type = Param::INT;\n\n};\n\n\n\n//! @} core_basic\n\n\n\n} //namespace cv\n\n\n\n#include \"opencv2/core/operations.hpp\"\n\n#include \"opencv2/core/cvstd.inl.hpp\"\n\n#include \"opencv2/core/utility.hpp\"\n\n#include \"opencv2/core/optim.hpp\"\n\n#include \"opencv2/core/ovx.hpp\"\n\n\n\n#endif /*OPENCV_CORE_HPP*/\n", "file_path": "headers/4/opencv2/core.hpp", "rank": 30, "score": 337611.5716482389 }, { "content": "/// Returns list of all builtin backends\n\npub fn get_backends() -> Result<core::Vector::<crate::videoio::VideoCaptureAPIs>> {\n\n\tunsafe { sys::cv_videoio_registry_getBackends() }.into_result().map(|ptr| unsafe { core::Vector::<crate::videoio::VideoCaptureAPIs>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/videoio.rs", "rank": 31, "score": 334151.4315409174 }, { "content": "/// Returns list of all available backends\n\npub fn get_backends() -> Result<core::Vector::<crate::videoio::VideoCaptureAPIs>> {\n\n\tunsafe { sys::cv_videoio_registry_getBackends() }.into_result().map(|ptr| unsafe { core::Vector::<crate::videoio::VideoCaptureAPIs>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/videoio.rs", "rank": 32, "score": 334151.4315409174 }, { "content": "/// Returns list of available backends which works via `cv::VideoWriter()`\n\npub fn get_writer_backends() -> Result<core::Vector::<crate::videoio::VideoCaptureAPIs>> {\n\n\tunsafe { sys::cv_videoio_registry_getWriterBackends() }.into_result().map(|ptr| unsafe { core::Vector::<crate::videoio::VideoCaptureAPIs>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "src/opencv/hub/videoio.rs", "rank": 33, "score": 334151.1290005192 }, { "content": "/// Returns list of available backends which works via `cv::VideoCapture(filename)`\n\npub fn get_stream_backends() -> Result<core::Vector::<crate::videoio::VideoCaptureAPIs>> {\n\n\tunsafe { sys::cv_videoio_registry_getStreamBackends() }.into_result().map(|ptr| unsafe { core::Vector::<crate::videoio::VideoCaptureAPIs>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "src/opencv/hub/videoio.rs", "rank": 34, "score": 334151.071269074 }, { "content": "/// Returns list of available backends which works via `cv::VideoCapture(int index)`\n\npub fn get_camera_backends() -> Result<core::Vector::<crate::videoio::VideoCaptureAPIs>> {\n\n\tunsafe { sys::cv_videoio_registry_getCameraBackends() }.into_result().map(|ptr| unsafe { core::Vector::<crate::videoio::VideoCaptureAPIs>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "src/opencv/hub/videoio.rs", "rank": 35, "score": 334151.01441399904 }, { "content": "/// Retrieves a window by its name.\n\n/// \n\n/// ## Parameters\n\n/// * window_name: Name of the window that is to be retrieved.\n\n/// \n\n/// This function returns a Viz3d object with the given name.\n\n/// \n\n/// \n\n/// Note: If the window with that name already exists, that window is returned. Otherwise, new window is\n\n/// created with the given name, and it is returned.\n\n/// \n\n/// \n\n/// Note: Window names are automatically prefixed by \"Viz - \" if it is not done by the user.\n\n/// ```ignore\n\n/// /// window and window_2 are the same windows.\n\n/// viz::Viz3d window = viz::getWindowByName(\"myWindow\");\n\n/// viz::Viz3d window_2 = viz::getWindowByName(\"Viz - myWindow\");\n\n/// ```\n\n/// \n\npub fn get_window_by_name(window_name: &str) -> Result<crate::viz::Viz3d> {\n\n\tstring_arg!(window_name);\n\n\tunsafe { sys::cv_viz_getWindowByName_const_StringX(window_name.as_ptr()) }.into_result().map(|ptr| unsafe { crate::viz::Viz3d::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/viz.rs", "rank": 36, "score": 334150.6852315775 }, { "content": "/// Retrieves a window by its name.\n\n/// \n\n/// ## Parameters\n\n/// * window_name: Name of the window that is to be retrieved.\n\n/// \n\n/// This function returns a Viz3d object with the given name.\n\n/// \n\n/// \n\n/// Note: If the window with that name already exists, that window is returned. Otherwise, new window is\n\n/// created with the given name, and it is returned.\n\n/// \n\n/// \n\n/// Note: Window names are automatically prefixed by \"Viz - \" if it is not done by the user.\n\n/// ```ignore\n\n/// /// window and window_2 are the same windows.\n\n/// viz::Viz3d window = viz::getWindowByName(\"myWindow\");\n\n/// viz::Viz3d window_2 = viz::getWindowByName(\"Viz - myWindow\");\n\n/// ```\n\n/// \n\npub fn get_window_by_name(window_name: &str) -> Result<crate::viz::Viz3d> {\n\n\tstring_arg!(window_name);\n\n\tunsafe { sys::cv_viz_getWindowByName_const_StringX(window_name.as_ptr()) }.into_result().map(|ptr| unsafe { crate::viz::Viz3d::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/viz.rs", "rank": 37, "score": 334150.6852315775 }, { "content": "/// Returns backend API name or \"UnknownVideoAPI(xxx)\"\n\n/// ## Parameters\n\n/// * api: backend ID (#VideoCaptureAPIs)\n\npub fn get_backend_name(api: crate::videoio::VideoCaptureAPIs) -> Result<String> {\n\n\tunsafe { sys::cv_videoio_registry_getBackendName_VideoCaptureAPIs(api) }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "src/opencv/hub/videoio.rs", "rank": 38, "score": 334143.58054070093 }, { "content": "/// Returns one of the predefined dictionaries defined in PREDEFINED_DICTIONARY_NAME\n\npub fn get_predefined_dictionary(name: crate::aruco::PREDEFINED_DICTIONARY_NAME) -> Result<core::Ptr::<crate::aruco::Dictionary>> {\n\n\tunsafe { sys::cv_aruco_getPredefinedDictionary_PREDEFINED_DICTIONARY_NAME(name) }.into_result().map(|ptr| unsafe { core::Ptr::<crate::aruco::Dictionary>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "src/opencv/hub/aruco.rs", "rank": 39, "score": 333987.38021911285 }, { "content": "/// extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it.\n\n/// \n\n/// ## C++ default parameters\n\n/// * coi: -1\n\npub fn extract_image_coi(arr: *const c_void, coiimg: &mut dyn core::ToOutputArray, coi: i32) -> Result<()> {\n\n\toutput_array_arg!(coiimg);\n\n\tunsafe { sys::cv_extractImageCOI_const_CvArrX_const__OutputArrayX_int(arr, coiimg.as_raw__OutputArray(), coi) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_32/hub/core.rs", "rank": 40, "score": 331046.38601711305 }, { "content": "/// extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it.\n\n/// \n\n/// ## C++ default parameters\n\n/// * coi: -1\n\npub fn extract_image_coi(arr: *const c_void, coiimg: &mut dyn core::ToOutputArray, coi: i32) -> Result<()> {\n\n\toutput_array_arg!(coiimg);\n\n\tunsafe { sys::cv_extractImageCOI_const_CvArrX_const__OutputArrayX_int(arr, coiimg.as_raw__OutputArray(), coi) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/core.rs", "rank": 41, "score": 331046.3860171131 }, { "content": "/// Returns one of the predefined dictionaries defined in PREDEFINED_DICTIONARY_NAME\n\npub fn get_predefined_dictionary(name: crate::aruco::PREDEFINED_DICTIONARY_NAME) -> Result<core::Ptr::<crate::aruco::Dictionary>> {\n\n\tunsafe { sys::cv_aruco_getPredefinedDictionary_PREDEFINED_DICTIONARY_NAME(name) }.into_result().map(|ptr| unsafe { core::Ptr::<crate::aruco::Dictionary>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/aruco.rs", "rank": 42, "score": 330401.05642774736 }, { "content": "/// Returns one of the predefined dictionaries defined in PREDEFINED_DICTIONARY_NAME\n\npub fn get_predefined_dictionary(name: crate::aruco::PREDEFINED_DICTIONARY_NAME) -> Result<core::Ptr::<crate::aruco::Dictionary>> {\n\n\tunsafe { sys::cv_aruco_getPredefinedDictionary_PREDEFINED_DICTIONARY_NAME(name) }.into_result().map(|ptr| unsafe { core::Ptr::<crate::aruco::Dictionary>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_32/hub/aruco.rs", "rank": 43, "score": 330401.05642774736 }, { "content": "/// Returns one of the predefined dictionaries defined in PREDEFINED_DICTIONARY_NAME\n\npub fn get_predefined_dictionary(name: crate::aruco::PREDEFINED_DICTIONARY_NAME) -> Result<core::Ptr::<crate::aruco::Dictionary>> {\n\n\tunsafe { sys::cv_aruco_getPredefinedDictionary_PREDEFINED_DICTIONARY_NAME(name) }.into_result().map(|ptr| unsafe { core::Ptr::<crate::aruco::Dictionary>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/aruco.rs", "rank": 44, "score": 330401.05642774736 }, { "content": "/// Tries to make panorama more horizontal (or vertical).\n\n/// \n\n/// ## Parameters\n\n/// * rmats: Camera rotation matrices.\n\n/// * kind: Correction kind, see detail::WaveCorrectKind.\n\npub fn wave_correct(rmats: &mut core::Vector::<core::Mat>, kind: crate::stitching::Detail_WaveCorrectKind) -> Result<()> {\n\n\tunsafe { sys::cv_detail_waveCorrect_vector_Mat_X_WaveCorrectKind(rmats.as_raw_mut_VectorOfMat(), kind) }.into_result()\n\n}\n\n\n", "file_path": "src/opencv/hub/stitching.rs", "rank": 45, "score": 330331.41334474727 }, { "content": "/// Returns list of available backends which works via `cv::VideoWriter()`\n\npub fn get_writer_backends() -> Result<core::Vector::<crate::videoio::VideoCaptureAPIs>> {\n\n\tunsafe { sys::cv_videoio_registry_getWriterBackends() }.into_result().map(|ptr| unsafe { core::Vector::<crate::videoio::VideoCaptureAPIs>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/videoio.rs", "rank": 46, "score": 329902.948324037 }, { "content": "/// Returns list of available backends which works via `cv::VideoWriter()`\n\npub fn get_writer_backends() -> Result<core::Vector::<crate::videoio::VideoCaptureAPIs>> {\n\n\tunsafe { sys::cv_videoio_registry_getWriterBackends() }.into_result().map(|ptr| unsafe { core::Vector::<crate::videoio::VideoCaptureAPIs>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/videoio.rs", "rank": 47, "score": 329902.9483240371 }, { "content": "/// Returns list of available backends which works via `cv::VideoCapture(filename)`\n\npub fn get_stream_backends() -> Result<core::Vector::<crate::videoio::VideoCaptureAPIs>> {\n\n\tunsafe { sys::cv_videoio_registry_getStreamBackends() }.into_result().map(|ptr| unsafe { core::Vector::<crate::videoio::VideoCaptureAPIs>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/videoio.rs", "rank": 48, "score": 329902.89059259184 }, { "content": "/// Returns list of available backends which works via `cv::VideoCapture(filename)`\n\npub fn get_stream_backends() -> Result<core::Vector::<crate::videoio::VideoCaptureAPIs>> {\n\n\tunsafe { sys::cv_videoio_registry_getStreamBackends() }.into_result().map(|ptr| unsafe { core::Vector::<crate::videoio::VideoCaptureAPIs>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/videoio.rs", "rank": 49, "score": 329902.89059259184 }, { "content": "/// Returns list of available backends which works via `cv::VideoCapture(int index)`\n\npub fn get_camera_backends() -> Result<core::Vector::<crate::videoio::VideoCaptureAPIs>> {\n\n\tunsafe { sys::cv_videoio_registry_getCameraBackends() }.into_result().map(|ptr| unsafe { core::Vector::<crate::videoio::VideoCaptureAPIs>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/videoio.rs", "rank": 50, "score": 329902.83373751683 }, { "content": "/// Returns list of available backends which works via `cv::VideoCapture(int index)`\n\npub fn get_camera_backends() -> Result<core::Vector::<crate::videoio::VideoCaptureAPIs>> {\n\n\tunsafe { sys::cv_videoio_registry_getCameraBackends() }.into_result().map(|ptr| unsafe { core::Vector::<crate::videoio::VideoCaptureAPIs>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/videoio.rs", "rank": 51, "score": 329902.8337375169 }, { "content": "/// Returns backend API name or \"UnknownVideoAPI(xxx)\"\n\n/// ## Parameters\n\n/// * api: backend ID (#VideoCaptureAPIs)\n\npub fn get_backend_name(api: crate::videoio::VideoCaptureAPIs) -> Result<String> {\n\n\tunsafe { sys::cv_videoio_registry_getBackendName_VideoCaptureAPIs(api) }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/videoio.rs", "rank": 52, "score": 329895.3998642188 }, { "content": "/// Returns backend API name or \"unknown\"\n\n/// ## Parameters\n\n/// * api: backend ID (#VideoCaptureAPIs)\n\npub fn get_backend_name(api: crate::videoio::VideoCaptureAPIs) -> Result<String> {\n\n\tunsafe { sys::cv_videoio_registry_getBackendName_VideoCaptureAPIs(api) }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/videoio.rs", "rank": 53, "score": 329895.3998642187 }, { "content": "pub fn find_max_spanning_tree(num_images: i32, pairwise_matches: &core::Vector::<crate::stitching::Detail_MatchesInfo>, span_tree: &mut crate::stitching::Detail_Graph, centers: &mut core::Vector::<i32>) -> Result<()> {\n\n\tunsafe { sys::cv_detail_findMaxSpanningTree_int_const_vector_MatchesInfo_X_GraphX_vector_int_X(num_images, pairwise_matches.as_raw_VectorOfDetail_MatchesInfo(), span_tree.as_raw_mut_Detail_Graph(), centers.as_raw_mut_VectorOfi32()) }.into_result()\n\n}\n\n\n", "file_path": "src/opencv/hub/stitching.rs", "rank": 54, "score": 328698.60302064446 }, { "content": "/// Tries to make panorama more horizontal (or vertical).\n\n/// \n\n/// ## Parameters\n\n/// * rmats: Camera rotation matrices.\n\n/// * kind: Correction kind, see detail::WaveCorrectKind.\n\npub fn wave_correct(rmats: &mut core::Vector::<core::Mat>, kind: crate::stitching::Detail_WaveCorrectKind) -> Result<()> {\n\n\tunsafe { sys::cv_detail_waveCorrect_vector_Mat_X_WaveCorrectKind(rmats.as_raw_mut_VectorOfMat(), kind) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_32/hub/stitching.rs", "rank": 55, "score": 326870.9589527078 }, { "content": "/// Tries to make panorama more horizontal (or vertical).\n\n/// \n\n/// ## Parameters\n\n/// * rmats: Camera rotation matrices.\n\n/// * kind: Correction kind, see detail::WaveCorrectKind.\n\npub fn wave_correct(rmats: &mut core::Vector::<core::Mat>, kind: crate::stitching::Detail_WaveCorrectKind) -> Result<()> {\n\n\tunsafe { sys::cv_detail_waveCorrect_vector_Mat_X_WaveCorrectKind(rmats.as_raw_mut_VectorOfMat(), kind) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/stitching.rs", "rank": 56, "score": 326870.9589527078 }, { "content": "/// Tries to make panorama more horizontal (or vertical).\n\n/// \n\n/// ## Parameters\n\n/// * rmats: Camera rotation matrices.\n\n/// * kind: Correction kind, see detail::WaveCorrectKind.\n\npub fn wave_correct(rmats: &mut core::Vector::<core::Mat>, kind: crate::stitching::Detail_WaveCorrectKind) -> Result<()> {\n\n\tunsafe { sys::cv_detail_waveCorrect_vector_Mat_X_WaveCorrectKind(rmats.as_raw_mut_VectorOfMat(), kind) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/stitching.rs", "rank": 57, "score": 326870.9589527078 }, { "content": "pub fn find_max_spanning_tree(num_images: i32, pairwise_matches: &core::Vector::<crate::stitching::Detail_MatchesInfo>, span_tree: &mut crate::stitching::Detail_Graph, centers: &mut core::Vector::<i32>) -> Result<()> {\n\n\tunsafe { sys::cv_detail_findMaxSpanningTree_int_const_vector_MatchesInfo_X_GraphX_vector_int_X(num_images, pairwise_matches.as_raw_VectorOfDetail_MatchesInfo(), span_tree.as_raw_mut_Detail_Graph(), centers.as_raw_mut_VectorOfi32()) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_32/hub/stitching.rs", "rank": 58, "score": 326355.32681065635 }, { "content": "pub fn find_max_spanning_tree(num_images: i32, pairwise_matches: &core::Vector::<crate::stitching::Detail_MatchesInfo>, span_tree: &mut crate::stitching::Detail_Graph, centers: &mut core::Vector::<i32>) -> Result<()> {\n\n\tunsafe { sys::cv_detail_findMaxSpanningTree_int_const_vector_MatchesInfo_X_GraphX_vector_int_X(num_images, pairwise_matches.as_raw_VectorOfDetail_MatchesInfo(), span_tree.as_raw_mut_Detail_Graph(), centers.as_raw_mut_VectorOfi32()) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/stitching.rs", "rank": 59, "score": 326355.32681065635 }, { "content": "pub fn find_max_spanning_tree(num_images: i32, pairwise_matches: &core::Vector::<crate::stitching::Detail_MatchesInfo>, span_tree: &mut crate::stitching::Detail_Graph, centers: &mut core::Vector::<i32>) -> Result<()> {\n\n\tunsafe { sys::cv_detail_findMaxSpanningTree_int_const_vector_MatchesInfo_X_GraphX_vector_int_X(num_images, pairwise_matches.as_raw_VectorOfDetail_MatchesInfo(), span_tree.as_raw_mut_Detail_Graph(), centers.as_raw_mut_VectorOfi32()) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/stitching.rs", "rank": 60, "score": 326355.32681065635 }, { "content": "#[cfg(not(target_os = \"windows\"))]\n\npub fn get_impl(impl_: &mut core::Vector::<i32>, fun_name: &mut core::Vector::<String>) -> Result<i32> {\n\n\tunsafe { sys::cv_getImpl_vector_int_X_vector_String_X(impl_.as_raw_mut_VectorOfi32(), fun_name.as_raw_mut_VectorOfString()) }.into_result()\n\n}\n\n\n", "file_path": "src/opencv/hub/core.rs", "rank": 61, "score": 326321.8278127527 }, { "content": "pub fn leave_biggest_component(features: &mut core::Vector::<crate::stitching::Detail_ImageFeatures>, pairwise_matches: &mut core::Vector::<crate::stitching::Detail_MatchesInfo>, conf_threshold: f32) -> Result<core::Vector::<i32>> {\n\n\tunsafe { sys::cv_detail_leaveBiggestComponent_vector_ImageFeatures_X_vector_MatchesInfo_X_float(features.as_raw_mut_VectorOfDetail_ImageFeatures(), pairwise_matches.as_raw_mut_VectorOfDetail_MatchesInfo(), conf_threshold) }.into_result().map(|ptr| unsafe { core::Vector::<i32>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "src/opencv/hub/stitching.rs", "rank": 62, "score": 325449.16985929105 }, { "content": "struct RefOrVoid<const volatile void>{ typedef const volatile void type; };\n\n\n", "file_path": "headers/3.4/opencv2/core/cvstd.hpp", "rank": 63, "score": 324607.13550913415 }, { "content": "struct RefOrVoid<const volatile void>{ typedef const volatile void type; };\n\n\n", "file_path": "headers/3.2/opencv2/core/cvstd.hpp", "rank": 64, "score": 324607.13550913415 }, { "content": "pub fn get_platfoms_info(platform_info: &mut core::Vector::<core::PlatformInfo>) -> Result<()> {\n\n\tunsafe { sys::cv_ocl_getPlatfomsInfo_vector_PlatformInfo_X(platform_info.as_raw_mut_VectorOfPlatformInfo()) }.into_result()\n\n}\n\n\n", "file_path": "src/opencv/hub/core.rs", "rank": 65, "score": 324580.5006951 }, { "content": "/// Returns Inference Engine VPU type.\n\n/// \n\n/// See values of `CV_DNN_INFERENCE_ENGINE_VPU_TYPE_*` macros.\n\npub fn get_inference_engine_vpu_type() -> Result<String> {\n\n\tunsafe { sys::cv_dnn_getInferenceEngineVPUType() }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "src/opencv/hub/dnn.rs", "rank": 66, "score": 323583.1833192666 }, { "content": "/// Returns Inference Engine internal backend API.\n\n/// \n\n/// See values of `CV_DNN_BACKEND_INFERENCE_ENGINE_*` macros.\n\n/// \n\n/// Default value is controlled through `OPENCV_DNN_BACKEND_INFERENCE_ENGINE_TYPE` runtime parameter (environment variable).\n\npub fn get_inference_engine_backend_type() -> Result<String> {\n\n\tunsafe { sys::cv_dnn_getInferenceEngineBackendType() }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "src/opencv/hub/dnn.rs", "rank": 67, "score": 323581.22477518197 }, { "content": "pub fn leave_biggest_component(features: &mut core::Vector::<crate::stitching::Detail_ImageFeatures>, pairwise_matches: &mut core::Vector::<crate::stitching::Detail_MatchesInfo>, conf_threshold: f32) -> Result<core::Vector::<i32>> {\n\n\tunsafe { sys::cv_detail_leaveBiggestComponent_vector_ImageFeatures_X_vector_MatchesInfo_X_float(features.as_raw_mut_VectorOfDetail_ImageFeatures(), pairwise_matches.as_raw_mut_VectorOfDetail_MatchesInfo(), conf_threshold) }.into_result().map(|ptr| unsafe { core::Vector::<i32>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_32/hub/stitching.rs", "rank": 68, "score": 323105.893649303 }, { "content": "pub fn leave_biggest_component(features: &mut core::Vector::<crate::stitching::Detail_ImageFeatures>, pairwise_matches: &mut core::Vector::<crate::stitching::Detail_MatchesInfo>, conf_threshold: f32) -> Result<core::Vector::<i32>> {\n\n\tunsafe { sys::cv_detail_leaveBiggestComponent_vector_ImageFeatures_X_vector_MatchesInfo_X_float(features.as_raw_mut_VectorOfDetail_ImageFeatures(), pairwise_matches.as_raw_mut_VectorOfDetail_MatchesInfo(), conf_threshold) }.into_result().map(|ptr| unsafe { core::Vector::<i32>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/stitching.rs", "rank": 69, "score": 323105.893649303 }, { "content": "pub fn leave_biggest_component(features: &mut core::Vector::<crate::stitching::Detail_ImageFeatures>, pairwise_matches: &mut core::Vector::<crate::stitching::Detail_MatchesInfo>, conf_threshold: f32) -> Result<core::Vector::<i32>> {\n\n\tunsafe { sys::cv_detail_leaveBiggestComponent_vector_ImageFeatures_X_vector_MatchesInfo_X_float(features.as_raw_mut_VectorOfDetail_ImageFeatures(), pairwise_matches.as_raw_mut_VectorOfDetail_MatchesInfo(), conf_threshold) }.into_result().map(|ptr| unsafe { core::Vector::<i32>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/stitching.rs", "rank": 70, "score": 323105.893649303 }, { "content": "/// A utility to load list of paths to training image and annotation file.\n\n/// ## Parameters\n\n/// * imageList: The specified file contains paths to the training images.\n\n/// * annotationList: The specified file contains paths to the training annotations.\n\n/// * images: The loaded paths of training images.\n\n/// * annotations: The loaded paths of annotation files.\n\n/// \n\n/// Example of usage:\n\n/// ```ignore\n\n/// String imageFiles = \"images_path.txt\";\n\n/// String ptsFiles = \"annotations_path.txt\";\n\n/// std::vector<String> images_train;\n\n/// std::vector<String> landmarks_train;\n\n/// loadDatasetList(imageFiles,ptsFiles,images_train,landmarks_train);\n\n/// ```\n\n/// \n\npub fn load_dataset_list(image_list: &str, annotation_list: &str, images: &mut core::Vector::<String>, annotations: &mut core::Vector::<String>) -> Result<bool> {\n\n\tstring_arg!(image_list);\n\n\tstring_arg!(annotation_list);\n\n\tunsafe { sys::cv_face_loadDatasetList_String_String_vector_String_X_vector_String_X(image_list.as_ptr() as _, annotation_list.as_ptr() as _, images.as_raw_mut_VectorOfString(), annotations.as_raw_mut_VectorOfString()) }.into_result()\n\n}\n\n\n", "file_path": "src/opencv/hub/face.rs", "rank": 71, "score": 322783.50747706543 }, { "content": "#[cfg(not(target_os = \"windows\"))]\n\npub fn get_impl(impl_: &mut core::Vector::<i32>, fun_name: &mut core::Vector::<String>) -> Result<i32> {\n\n\tunsafe { sys::cv_getImpl_vector_int_X_vector_String_X(impl_.as_raw_mut_VectorOfi32(), fun_name.as_raw_mut_VectorOfString()) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_32/hub/core.rs", "rank": 72, "score": 322736.1618639411 }, { "content": "#[cfg(not(target_os = \"windows\"))]\n\npub fn get_impl(impl_: &mut core::Vector::<i32>, fun_name: &mut core::Vector::<String>) -> Result<i32> {\n\n\tunsafe { sys::cv_getImpl_vector_int_X_vector_String_X(impl_.as_raw_mut_VectorOfi32(), fun_name.as_raw_mut_VectorOfString()) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/core.rs", "rank": 73, "score": 322736.1618639411 }, { "content": "#[cfg(not(target_os = \"windows\"))]\n\npub fn get_impl(impl_: &mut core::Vector::<i32>, fun_name: &mut core::Vector::<String>) -> Result<i32> {\n\n\tunsafe { sys::cv_getImpl_vector_int_X_vector_String_X(impl_.as_raw_mut_VectorOfi32(), fun_name.as_raw_mut_VectorOfString()) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/core.rs", "rank": 74, "score": 322736.1618639411 }, { "content": "#[test]\n\nfn vec() -> Result<()> {\n\n let mut m = Mat::new_rows_cols_with_default(10, 10, Vec3b::typ(), Scalar::default())?;\n\n let mut ps = types::VectorOfMat::new();\n\n assert_eq!(ps.len(), 0);\n\n let mut p1 = unsafe { Mat::new_rows_cols(3, 2, i32::typ()) }?;\n\n p1.at_row_mut::<i32>(0)?.copy_from_slice(&[0, 0]);\n\n p1.at_row_mut::<i32>(1)?.copy_from_slice(&[0, 9]);\n\n p1.at_row_mut::<i32>(2)?.copy_from_slice(&[9, 9]);\n\n ps.push(p1);\n\n assert_eq!(ps.len(), 1);\n\n #[cfg(not(feature = \"opencv-4\"))]\n\n use self::core::LINE_8;\n\n #[cfg(feature = \"opencv-4\")]\n\n use self::imgproc::LINE_8;\n\n imgproc::fill_poly(&mut m, &ps, Scalar::new(127., 127., 127., 0.), LINE_8, 0, Point::default())?;\n\n assert_eq!(*m.at_2d::<Vec3b>(0, 0)?, Vec3b::from([127, 127, 127]));\n\n assert_eq!(*m.at_2d::<Vec3b>(0, 9)?, Vec3b::default());\n\n assert_eq!(*m.at_2d::<Vec3b>(9, 9)?, Vec3b::from([127, 127, 127]));\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/types.rs", "rank": 75, "score": 322427.41556475917 }, { "content": "/// ///////////////////////////////////////////////////////////////////////////\n\npub fn matches_graph_as_string(pathes: &mut core::Vector::<String>, pairwise_matches: &mut core::Vector::<crate::stitching::Detail_MatchesInfo>, conf_threshold: f32) -> Result<String> {\n\n\tunsafe { sys::cv_detail_matchesGraphAsString_vector_String_X_vector_MatchesInfo_X_float(pathes.as_raw_mut_VectorOfString(), pairwise_matches.as_raw_mut_VectorOfDetail_MatchesInfo(), conf_threshold) }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "src/opencv/hub/stitching.rs", "rank": 76, "score": 321064.8729559347 }, { "content": "pub fn create_frame_source_empty() -> Result<core::Ptr::<dyn crate::superres::Superres_FrameSource>> {\n\n\tunsafe { sys::cv_superres_createFrameSource_Empty() }.into_result().map(|ptr| unsafe { core::Ptr::<dyn crate::superres::Superres_FrameSource>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "src/opencv/hub/superres.rs", "rank": 77, "score": 320728.92648750177 }, { "content": "pub fn get_platfoms_info(platform_info: &mut core::Vector::<core::PlatformInfo>) -> Result<()> {\n\n\tunsafe { sys::cv_ocl_getPlatfomsInfo_vector_PlatformInfo_X(platform_info.as_raw_mut_VectorOfPlatformInfo()) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/core.rs", "rank": 78, "score": 320510.0215410307 }, { "content": "pub fn get_platfoms_info(platform_info: &mut core::Vector::<core::PlatformInfo>) -> Result<()> {\n\n\tunsafe { sys::cv_ocl_getPlatfomsInfo_vector_PlatformInfo_X(platform_info.as_raw_mut_VectorOfPlatformInfo()) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/core.rs", "rank": 79, "score": 320510.02154103067 }, { "content": "pub fn get_platfoms_info(platform_info: &mut core::Vector::<core::PlatformInfo>) -> Result<()> {\n\n\tunsafe { sys::cv_ocl_getPlatfomsInfo_vector_PlatformInfo_X(platform_info.as_raw_mut_VectorOfPlatformInfo()) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_32/hub/core.rs", "rank": 80, "score": 320510.0215410307 }, { "content": "#[deprecated = \"use Stitcher::create\"]\n\npub fn create_stitcher(try_use_gpu: bool) -> Result<core::Ptr::<crate::stitching::Stitcher>> {\n\n\tunsafe { sys::cv_createStitcher_bool(try_use_gpu) }.into_result().map(|ptr| unsafe { core::Ptr::<crate::stitching::Stitcher>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "src/opencv/hub/stitching.rs", "rank": 81, "score": 320052.95334232226 }, { "content": "/// Returns one of the predefined dictionaries referenced by DICT_*.\n\npub fn get_predefined_dictionary_i32(dict: i32) -> Result<core::Ptr::<crate::aruco::Dictionary>> {\n\n\tunsafe { sys::cv_aruco_getPredefinedDictionary_int(dict) }.into_result().map(|ptr| unsafe { core::Ptr::<crate::aruco::Dictionary>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "src/opencv/hub/aruco.rs", "rank": 82, "score": 320031.29225224245 }, { "content": "/// A utility to load list of paths to training image and annotation file.\n\n/// ## Parameters\n\n/// * imageList: The specified file contains paths to the training images.\n\n/// * annotationList: The specified file contains paths to the training annotations.\n\n/// * images: The loaded paths of training images.\n\n/// * annotations: The loaded paths of annotation files.\n\n/// \n\n/// Example of usage:\n\n/// ```ignore\n\n/// String imageFiles = \"images_path.txt\";\n\n/// String ptsFiles = \"annotations_path.txt\";\n\n/// std::vector<String> images_train;\n\n/// std::vector<String> landmarks_train;\n\n/// loadDatasetList(imageFiles,ptsFiles,images_train,landmarks_train);\n\n/// ```\n\n/// \n\npub fn load_dataset_list(image_list: &str, annotation_list: &str, images: &mut core::Vector::<String>, annotations: &mut core::Vector::<String>) -> Result<bool> {\n\n\tstring_arg!(image_list);\n\n\tstring_arg!(annotation_list);\n\n\tunsafe { sys::cv_face_loadDatasetList_String_String_vector_String_X_vector_String_X(image_list.as_ptr() as _, annotation_list.as_ptr() as _, images.as_raw_mut_VectorOfString(), annotations.as_raw_mut_VectorOfString()) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/face.rs", "rank": 83, "score": 319896.20690517896 }, { "content": "/// A utility to load list of paths to training image and annotation file.\n\n/// ## Parameters\n\n/// * imageList: The specified file contains paths to the training images.\n\n/// * annotationList: The specified file contains paths to the training annotations.\n\n/// * images: The loaded paths of training images.\n\n/// * annotations: The loaded paths of annotation files.\n\n/// \n\n/// Example of usage:\n\n/// ```ignore\n\n/// String imageFiles = \"images_path.txt\";\n\n/// String ptsFiles = \"annotations_path.txt\";\n\n/// std::vector<String> images_train;\n\n/// std::vector<String> landmarks_train;\n\n/// loadDatasetList(imageFiles,ptsFiles,images_train,landmarks_train);\n\n/// ```\n\n/// \n\npub fn load_dataset_list(image_list: &str, annotation_list: &str, images: &mut core::Vector::<String>, annotations: &mut core::Vector::<String>) -> Result<bool> {\n\n\tstring_arg!(image_list);\n\n\tstring_arg!(annotation_list);\n\n\tunsafe { sys::cv_face_loadDatasetList_String_String_vector_String_X_vector_String_X(image_list.as_ptr() as _, annotation_list.as_ptr() as _, images.as_raw_mut_VectorOfString(), annotations.as_raw_mut_VectorOfString()) }.into_result()\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/face.rs", "rank": 84, "score": 319896.20690517896 }, { "content": "/// Detects corners using the FAST algorithm\n\n/// \n\n/// ## Parameters\n\n/// * image: grayscale image where keypoints (corners) are detected.\n\n/// * keypoints: keypoints detected on the image.\n\n/// * threshold: threshold on difference between intensity of the central pixel and pixels of a\n\n/// circle around this pixel.\n\n/// * nonmaxSuppression: if true, non-maximum suppression is applied to detected corners\n\n/// (keypoints).\n\n/// * type: one of the three neighborhoods as defined in the paper:\n\n/// FastFeatureDetector::TYPE_9_16, FastFeatureDetector::TYPE_7_12,\n\n/// FastFeatureDetector::TYPE_5_8\n\n/// \n\n/// Detects corners using the FAST algorithm by [Rosten06](https://docs.opencv.org/4.3.0/d0/de3/citelist.html#CITEREF_Rosten06) .\n\n/// \n\n/// \n\n/// Note: In Python API, types are given as cv.FAST_FEATURE_DETECTOR_TYPE_5_8,\n\n/// cv.FAST_FEATURE_DETECTOR_TYPE_7_12 and cv.FAST_FEATURE_DETECTOR_TYPE_9_16. For corner\n\n/// detection, use cv.FAST.detect() method.\n\npub fn FAST_with_type(image: &dyn core::ToInputArray, keypoints: &mut core::Vector::<core::KeyPoint>, threshold: i32, nonmax_suppression: bool, typ: crate::features2d::FastFeatureDetector_DetectorType) -> Result<()> {\n\n\tinput_array_arg!(image);\n\n\tunsafe { sys::cv_FAST_const__InputArrayX_vector_KeyPoint_X_int_bool_DetectorType(image.as_raw__InputArray(), keypoints.as_raw_mut_VectorOfKeyPoint(), threshold, nonmax_suppression, typ) }.into_result()\n\n}\n\n\n", "file_path": "src/opencv/hub/features2d.rs", "rank": 85, "score": 318709.3566708168 }, { "content": "/// Detects corners using the AGAST algorithm\n\n/// \n\n/// ## Parameters\n\n/// * image: grayscale image where keypoints (corners) are detected.\n\n/// * keypoints: keypoints detected on the image.\n\n/// * threshold: threshold on difference between intensity of the central pixel and pixels of a\n\n/// circle around this pixel.\n\n/// * nonmaxSuppression: if true, non-maximum suppression is applied to detected corners\n\n/// (keypoints).\n\n/// * type: one of the four neighborhoods as defined in the paper:\n\n/// AgastFeatureDetector::AGAST_5_8, AgastFeatureDetector::AGAST_7_12d,\n\n/// AgastFeatureDetector::AGAST_7_12s, AgastFeatureDetector::OAST_9_16\n\n/// \n\n/// For non-Intel platforms, there is a tree optimised variant of AGAST with same numerical results.\n\n/// The 32-bit binary tree tables were generated automatically from original code using perl script.\n\n/// The perl script and examples of tree generation are placed in features2d/doc folder.\n\n/// Detects corners using the AGAST algorithm by [mair2010_agast](https://docs.opencv.org/4.3.0/d0/de3/citelist.html#CITEREF_mair2010_agast) .\n\npub fn AGAST_with_type(image: &dyn core::ToInputArray, keypoints: &mut core::Vector::<core::KeyPoint>, threshold: i32, nonmax_suppression: bool, typ: crate::features2d::AgastFeatureDetector_DetectorType) -> Result<()> {\n\n\tinput_array_arg!(image);\n\n\tunsafe { sys::cv_AGAST_const__InputArrayX_vector_KeyPoint_X_int_bool_DetectorType(image.as_raw__InputArray(), keypoints.as_raw_mut_VectorOfKeyPoint(), threshold, nonmax_suppression, typ) }.into_result()\n\n}\n\n\n", "file_path": "src/opencv/hub/features2d.rs", "rank": 86, "score": 318704.5714937166 }, { "content": "/// Returns Inference Engine VPU type.\n\n/// \n\n/// See values of `CV_DNN_INFERENCE_ENGINE_VPU_TYPE_*` macros.\n\npub fn get_inference_engine_vpu_type() -> Result<String> {\n\n\tunsafe { sys::cv_dnn_getInferenceEngineVPUType() }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/dnn.rs", "rank": 87, "score": 318507.2066226825 }, { "content": "/// Returns Inference Engine VPU type.\n\n/// \n\n/// See values of `CV_DNN_INFERENCE_ENGINE_VPU_TYPE_*` macros.\n\npub fn get_inference_engine_vpu_type() -> Result<String> {\n\n\tunsafe { sys::cv_dnn_getInferenceEngineVPUType() }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/dnn.rs", "rank": 88, "score": 318507.2066226825 }, { "content": "/// Returns Inference Engine internal backend API.\n\n/// \n\n/// See values of `CV_DNN_BACKEND_INFERENCE_ENGINE_*` macros.\n\n/// \n\n/// Default value is controlled through `OPENCV_DNN_BACKEND_INFERENCE_ENGINE_TYPE` runtime parameter (environment variable).\n\npub fn get_inference_engine_backend_type() -> Result<String> {\n\n\tunsafe { sys::cv_dnn_getInferenceEngineBackendType() }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/dnn.rs", "rank": 89, "score": 318505.2480785978 }, { "content": "/// Returns Inference Engine internal backend API.\n\n/// \n\n/// See values of `CV_DNN_BACKEND_INFERENCE_ENGINE_*` macros.\n\n/// \n\n/// Default value is controlled through `OPENCV_DNN_BACKEND_INFERENCE_ENGINE_TYPE` runtime parameter (environment variable).\n\npub fn get_inference_engine_backend_type() -> Result<String> {\n\n\tunsafe { sys::cv_dnn_getInferenceEngineBackendType() }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/dnn.rs", "rank": 90, "score": 318505.2480785978 }, { "content": "/// ///////////////////////////////////////////////////////////////////////////\n\npub fn matches_graph_as_string(pathes: &mut core::Vector::<String>, pairwise_matches: &mut core::Vector::<crate::stitching::Detail_MatchesInfo>, conf_threshold: f32) -> Result<String> {\n\n\tunsafe { sys::cv_detail_matchesGraphAsString_vector_String_X_vector_MatchesInfo_X_float(pathes.as_raw_mut_VectorOfString(), pairwise_matches.as_raw_mut_VectorOfDetail_MatchesInfo(), conf_threshold) }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/stitching.rs", "rank": 91, "score": 318337.0085526083 }, { "content": "/// ///////////////////////////////////////////////////////////////////////////\n\npub fn matches_graph_as_string(pathes: &mut core::Vector::<String>, pairwise_matches: &mut core::Vector::<crate::stitching::Detail_MatchesInfo>, conf_threshold: f32) -> Result<String> {\n\n\tunsafe { sys::cv_detail_matchesGraphAsString_vector_String_X_vector_MatchesInfo_X_float(pathes.as_raw_mut_VectorOfString(), pairwise_matches.as_raw_mut_VectorOfDetail_MatchesInfo(), conf_threshold) }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/stitching.rs", "rank": 92, "score": 318337.00855260843 }, { "content": "/// ///////////////////////////////////////////////////////////////////////////\n\npub fn matches_graph_as_string(pathes: &mut core::Vector::<String>, pairwise_matches: &mut core::Vector::<crate::stitching::Detail_MatchesInfo>, conf_threshold: f32) -> Result<String> {\n\n\tunsafe { sys::cv_detail_matchesGraphAsString_vector_String_X_vector_MatchesInfo_X_float(pathes.as_raw_mut_VectorOfString(), pairwise_matches.as_raw_mut_VectorOfDetail_MatchesInfo(), conf_threshold) }.into_result().map(|s| unsafe { crate::templ::receive_string(s as *mut String) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_32/hub/stitching.rs", "rank": 93, "score": 318337.0085526083 }, { "content": "pub fn create_frame_source_empty() -> Result<core::Ptr::<dyn crate::superres::Superres_FrameSource>> {\n\n\tunsafe { sys::cv_superres_createFrameSource_Empty() }.into_result().map(|ptr| unsafe { core::Ptr::<dyn crate::superres::Superres_FrameSource>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/superres.rs", "rank": 94, "score": 316823.30215462006 }, { "content": "pub fn create_frame_source_empty() -> Result<core::Ptr::<dyn crate::superres::Superres_FrameSource>> {\n\n\tunsafe { sys::cv_superres_createFrameSource_Empty() }.into_result().map(|ptr| unsafe { core::Ptr::<dyn crate::superres::Superres_FrameSource>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_32/hub/superres.rs", "rank": 95, "score": 316823.30215462006 }, { "content": "pub fn create_frame_source_empty() -> Result<core::Ptr::<dyn crate::superres::Superres_FrameSource>> {\n\n\tunsafe { sys::cv_superres_createFrameSource_Empty() }.into_result().map(|ptr| unsafe { core::Ptr::<dyn crate::superres::Superres_FrameSource>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/superres.rs", "rank": 96, "score": 316823.30215462006 }, { "content": "#[deprecated = \"use Stitcher::create\"]\n\npub fn create_stitcher(try_use_gpu: bool) -> Result<core::Ptr::<crate::stitching::Stitcher>> {\n\n\tunsafe { sys::cv_createStitcher_bool(try_use_gpu) }.into_result().map(|ptr| unsafe { core::Ptr::<crate::stitching::Stitcher>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_4/hub/stitching.rs", "rank": 97, "score": 315981.4261271474 }, { "content": "#[deprecated = \"use Stitcher::create\"]\n\npub fn create_stitcher_scans(try_use_gpu: bool) -> Result<core::Ptr::<crate::stitching::Stitcher>> {\n\n\tunsafe { sys::cv_createStitcherScans_bool(try_use_gpu) }.into_result().map(|ptr| unsafe { core::Ptr::<crate::stitching::Stitcher>::from_raw(ptr) })\n\n}\n\n\n\n#[cfg(not(target_os = \"windows\"))]\n\n/// \n\n/// **Deprecated**: use Stitcher::create\n\n/// \n\n/// ## C++ default parameters\n\n/// * try_use_gpu: false\n", "file_path": "src/opencv/hub/stitching.rs", "rank": 98, "score": 315981.4261271474 }, { "content": "/// ## C++ default parameters\n\n/// * try_use_gpu: false\n\npub fn create_stitcher(try_use_gpu: bool) -> Result<core::Ptr::<crate::stitching::Stitcher>> {\n\n\tunsafe { sys::cv_createStitcher_bool(try_use_gpu) }.into_result().map(|ptr| unsafe { core::Ptr::<crate::stitching::Stitcher>::from_raw(ptr) })\n\n}\n\n\n", "file_path": "bindings/rust/opencv_34/hub/stitching.rs", "rank": 99, "score": 315981.24601461197 } ]
Rust
src/database.rs
chongyi/inspirer-rs
78cf180162e9ba302b16a6873629e56cfb318b4f
use actix::*; use actix_web::*; use diesel; use diesel::prelude::MysqlConnection; use diesel::r2d2::{ Pool, PooledConnection, ConnectionManager }; use diesel::sql_types; use error::Error; pub struct DatabaseExecutor(pub Pool<ConnectionManager<MysqlConnection>>); pub type Conn = PooledConnection<ConnectionManager<MysqlConnection>>; no_arg_sql_function!(last_insert_id, sql_types::Unsigned<sql_types::BigInt>); #[macro_export] macro_rules! last_insert_id { ($conn:expr, $table:expr) => { { use $crate::diesel; use $crate::database::last_insert_id as lastid; use $crate::error::database::map_database_error as map_db_err; let generated_id: u64 = diesel::select(lastid) .first($conn) .map_err(map_db_err($table))?; generated_id } }; } #[macro_export] macro_rules! delete_by_id { ($conn:expr => ($table:ident # = $id:expr)) => { delete_by_id!($conn => ($table id = $id)) }; ($conn:expr => ($table:ident $id_field:ident = $id:expr)) => { { use $crate::error::database::map_database_error as map_db_err; diesel::delete($table) .filter($id_field.eq($id)) .execute($conn) .map_err(map_db_err(Some(stringify!($table)))) } }; } #[macro_export] macro_rules! find_by_id { ($conn:expr => ($table:ident # = $id:expr => $ty:ty)) => { find_by_id!($conn => ($table id = $id => $ty)) }; ($conn:expr => ($table:ident($fields:expr) # = $id:expr => $ty:ty)) => { find_by_id!($conn => ($table($fields) id = $id => $ty)) }; ($conn:expr => ($table:ident $id_field:ident = $id:expr => $ty:ty)) => { { use $crate::error::database::map_database_error as map_db_err; $table .filter($id_field.eq($id)) .first::<$ty>($conn) .map_err(map_db_err(Some(stringify!($table)))) } }; ($conn:expr => ($table:ident($fields:expr) $id_field:ident = $id:expr => $ty:ty)) => { { use $crate::error::database::map_database_error as map_db_err; $table .select($fields) .filter($id_field.eq($id)) .first::<$ty>($conn) .map_err(map_db_err(Some(stringify!($table)))) } }; ($conn:expr => ($table:ident($fields:expr) filter($filter:expr) => $ty:ty)) => { { use $crate::error::database::map_database_error as map_db_err; $table .select($fields) .filter($filter) .first::<$ty>($conn) .map_err(map_db_err(Some(stringify!($table)))) } }; } #[macro_export] macro_rules! update_by_id { ($conn:expr => ($table:ident # = $id:expr; <- $update:expr)) => { update_by_id!($conn => ($table id = $id; <- $update)) }; ($conn:expr => ($table:ident $id_field:ident = $id:expr; <- $update:expr)) => { update_by_id!($conn => ($table filter($id_field.eq($id)); <- $update)) }; ($conn:expr => ($table:ident filter($filter:expr); <- $update:expr)) => { { use $crate::error::database::map_database_error as map_db_err; diesel::update($table) .set($update) .filter($filter) .execute($conn) .map_err(map_db_err(Some(stringify!($table)))) } }; } #[macro_export] macro_rules! paginator { ($conn:ident, $w:ident, $rt:ty, $lg:block) => { { use $crate::message::PaginatedListMessage as PaginatedMessage; use $crate::error::database::map_database_error as map_db_err; use $crate::result::Result as UResult; let paginator = || -> UResult<PaginatedMessage<$rt>> { let counter = || { $lg }; let getter = || { $lg }; let count = counter().count().first::<i64>($conn).map_err(map_db_err(Some("<paginating>")))?; let results = getter() .limit($w.per_page) .offset(($w.page - 1) * $w.per_page) .load::<$rt>($conn).map_err(map_db_err(Some("<paginating>")))?; Ok(PaginatedMessage { list: results, total: count, page: $w.page, per_page: $w.per_page }) }; paginator } }; ($conn:ident, $fields:expr, $w:ident, $rt:ty, $lg:block) => { { use $crate::message::PaginatedListMessage as PaginatedMessage; use $crate::error::database::map_database_error as map_db_err; use $crate::result::Result as UResult; let paginator = || -> UResult<PaginatedMessage<$rt>> { let counter = || { $lg }; let getter = || { $lg }; let count = counter().count().first::<i64>($conn).map_err(map_db_err(Some("<paginating>")))?; let results = getter() .select($fields) .limit($w.per_page) .offset(($w.page - 1) * $w.per_page) .load::<$rt>($conn).map_err(map_db_err(Some("<paginating>")))?; Ok(PaginatedMessage { list: results, total: count, page: $w.page, per_page: $w.per_page }) }; paginator } }; } impl Actor for DatabaseExecutor { type Context = SyncContext<Self>; } impl DatabaseExecutor { pub fn connection(&mut self) -> Result<Conn, Error> { Ok(self.0.get().map_err(Error::database_connection_get_error)?) } }
use actix::*; use actix_web::*; use diesel; use diesel::prelude::MysqlConnection; use diesel::r2d2::{ Pool, PooledConnection, ConnectionManager }; use diesel::sql_types; use error::Error; pub struct DatabaseExecutor(pub Pool<ConnectionManager<MysqlConnection>>); pub type Conn = PooledConnection<ConnectionManager<MysqlConnection>>; no_arg_sql_function!(last_insert_id, sql_types::Unsigned<sql_types::BigInt>); #[macro_export] macro_rules! last_insert_id { ($conn:expr, $table:expr) => { { use $crate::diesel; use $crate::database::last_insert_id as lastid; use $crate::error::database::map_database_error as map_db_err; let generated_id: u64 = diesel::select(lastid) .first($conn) .map_err(map_db_err($table))?; generated_id } }; } #[macro_export] macro_rules! delete_by_id { ($conn:expr => ($table:ident # = $id:expr)) => { delete_by_id!($conn => ($table id = $id)) }; ($conn:expr => ($table:ident $id_field:ident = $id:expr)) =
ome(stringify!($table)))) } }; } #[macro_export] macro_rules! update_by_id { ($conn:expr => ($table:ident # = $id:expr; <- $update:expr)) => { update_by_id!($conn => ($table id = $id; <- $update)) }; ($conn:expr => ($table:ident $id_field:ident = $id:expr; <- $update:expr)) => { update_by_id!($conn => ($table filter($id_field.eq($id)); <- $update)) }; ($conn:expr => ($table:ident filter($filter:expr); <- $update:expr)) => { { use $crate::error::database::map_database_error as map_db_err; diesel::update($table) .set($update) .filter($filter) .execute($conn) .map_err(map_db_err(Some(stringify!($table)))) } }; } #[macro_export] macro_rules! paginator { ($conn:ident, $w:ident, $rt:ty, $lg:block) => { { use $crate::message::PaginatedListMessage as PaginatedMessage; use $crate::error::database::map_database_error as map_db_err; use $crate::result::Result as UResult; let paginator = || -> UResult<PaginatedMessage<$rt>> { let counter = || { $lg }; let getter = || { $lg }; let count = counter().count().first::<i64>($conn).map_err(map_db_err(Some("<paginating>")))?; let results = getter() .limit($w.per_page) .offset(($w.page - 1) * $w.per_page) .load::<$rt>($conn).map_err(map_db_err(Some("<paginating>")))?; Ok(PaginatedMessage { list: results, total: count, page: $w.page, per_page: $w.per_page }) }; paginator } }; ($conn:ident, $fields:expr, $w:ident, $rt:ty, $lg:block) => { { use $crate::message::PaginatedListMessage as PaginatedMessage; use $crate::error::database::map_database_error as map_db_err; use $crate::result::Result as UResult; let paginator = || -> UResult<PaginatedMessage<$rt>> { let counter = || { $lg }; let getter = || { $lg }; let count = counter().count().first::<i64>($conn).map_err(map_db_err(Some("<paginating>")))?; let results = getter() .select($fields) .limit($w.per_page) .offset(($w.page - 1) * $w.per_page) .load::<$rt>($conn).map_err(map_db_err(Some("<paginating>")))?; Ok(PaginatedMessage { list: results, total: count, page: $w.page, per_page: $w.per_page }) }; paginator } }; } impl Actor for DatabaseExecutor { type Context = SyncContext<Self>; } impl DatabaseExecutor { pub fn connection(&mut self) -> Result<Conn, Error> { Ok(self.0.get().map_err(Error::database_connection_get_error)?) } }
> { { use $crate::error::database::map_database_error as map_db_err; diesel::delete($table) .filter($id_field.eq($id)) .execute($conn) .map_err(map_db_err(Some(stringify!($table)))) } }; } #[macro_export] macro_rules! find_by_id { ($conn:expr => ($table:ident # = $id:expr => $ty:ty)) => { find_by_id!($conn => ($table id = $id => $ty)) }; ($conn:expr => ($table:ident($fields:expr) # = $id:expr => $ty:ty)) => { find_by_id!($conn => ($table($fields) id = $id => $ty)) }; ($conn:expr => ($table:ident $id_field:ident = $id:expr => $ty:ty)) => { { use $crate::error::database::map_database_error as map_db_err; $table .filter($id_field.eq($id)) .first::<$ty>($conn) .map_err(map_db_err(Some(stringify!($table)))) } }; ($conn:expr => ($table:ident($fields:expr) $id_field:ident = $id:expr => $ty:ty)) => { { use $crate::error::database::map_database_error as map_db_err; $table .select($fields) .filter($id_field.eq($id)) .first::<$ty>($conn) .map_err(map_db_err(Some(stringify!($table)))) } }; ($conn:expr => ($table:ident($fields:expr) filter($filter:expr) => $ty:ty)) => { { use $crate::error::database::map_database_error as map_db_err; $table .select($fields) .filter($filter) .first::<$ty>($conn) .map_err(map_db_err(S
random
[ { "content": "#[derive(Deserialize, Debug, Clone)]\n\nstruct CreateContent {\n\n\n\n}\n\n\n", "file_path": "src/controllers/admin/content.rs", "rank": 0, "score": 48109.37637340417 }, { "content": "pub fn map_database_error(target: Option<&'static str>) -> impl FnOnce(DieselError) -> Error {\n\n move |err: DieselError| {\n\n let target = target.unwrap_or(\"[unknown]\");\n\n match err {\n\n DieselError::NotFound => Error::not_found_error::<DieselError>(None, Some(error_msg(NOT_FOUND, \"Resource or data not found.\", Some(ErrorDetail::String(format!(\"Target table: {}\", target)))))),\n\n DieselError::DatabaseError(kind, info) => {\n\n let mut detail = HashMap::new();\n\n detail.insert(\"message\".to_string(), Some(ErrorDetail::String(info.message().to_string())));\n\n detail.insert(\"table\".to_string(), info.table_name().map(|v| ErrorDetail::String(v.to_string())));\n\n detail.insert(\"detail\".to_string(), info.details().map(|v| ErrorDetail::String(v.to_string())));\n\n\n\n match kind {\n\n DieselDatabaseErrorKind::UniqueViolation => Error::conflict::<DieselError>(None, Some(error_msg(CONFLICT, \"Data conflict.\", Some(ErrorDetail::Hash(detail))))),\n\n _ => Error::internal_server_error::<DieselError>(None, Some(error_msg(UNKNOWN_DB_ERROR, \"Unknown database error.\", Some(ErrorDetail::Hash(detail)))))\n\n }\n\n }\n\n _ => Error::internal_server_error::<DieselError>(None, Some(error_msg(UNKNOWN_DB_ERROR, \"Unknown database error.\", Some(ErrorDetail::String(format!(\"Table: {}, Error: {:?}\", target, err))))))\n\n }\n\n }\n\n}\n", "file_path": "src/error/database.rs", "rank": 1, "score": 45537.47044392771 }, { "content": "pub fn error_handler<S, T: AsRef<HttpRequest<S>>>(req: T) -> impl FnOnce(Error) -> ActixError {\n\n let json = if let Ok(Some(mime)) = req.as_ref().mime_type() {\n\n mime.subtype() == mime::JSON || mime.suffix() == Some(mime::JSON)\n\n } else {\n\n false\n\n };\n\n\n\n move |err: Error| {\n\n if json {\n\n let json = JsonError(err);\n\n json.into()\n\n } else {\n\n let html = HtmlError(err);\n\n html.into()\n\n }\n\n }\n\n}\n\n\n\n#[derive(Fail, Debug, Serialize)]\n\n#[fail(display = \"code: {}, error: {}\", code, message)]\n", "file_path": "src/error/mod.rs", "rank": 2, "score": 41113.94079029152 }, { "content": "type PaginatedCategoryList = Result<PaginatedListMessage<CategoryDisplay>>;\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Queryable)]\n\npub struct CategoryBase {\n\n pub id: u32,\n\n pub name: String,\n\n pub display_name: String,\n\n}\n\n\n\n#[derive(Deserialize, Insertable, Debug)]\n\n#[table_name = \"categories\"]\n\npub struct NewCategory {\n\n pub name: String,\n\n pub display_name: String,\n\n pub description: String,\n\n pub sort: Option<i16>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Queryable)]\n\npub struct CategoryDisplay {\n", "file_path": "src/models/category.rs", "rank": 3, "score": 37437.94859368881 }, { "content": "pub fn convert_string_to_bool(origin: String) -> bool {\n\n match origin.as_str() {\n\n \"true\" | \"TRUE\" | \"1\" => true,\n\n \"false\" | \"FALSE\" | \"0\" => false,\n\n _ => false,\n\n }\n\n}", "file_path": "src/utils/helper.rs", "rank": 4, "score": 35834.50996894282 }, { "content": "pub fn home(req: HttpRequest<AppState>) -> impl Responder {\n\n let ref_req = Rc::new(req);\n\n let req_for_contents = Rc::clone(&ref_req);\n\n let req_for_pushes = Rc::clone(&ref_req);\n\n let req_for_recommends = Rc::clone(&ref_req);\n\n let req_for_err = Rc::clone(&ref_req);\n\n\n\n let default_content = Pagination {\n\n page: 1,\n\n per_page: 10,\n\n filter: Some(content::GetContents::default()),\n\n };\n\n\n\n let default_pushes = Pagination {\n\n page: 1,\n\n per_page: 3,\n\n filter: Some(push_message::GetPushMessages::default()),\n\n };\n\n\n\n let default_recommends = recommend::GetRecommendContents::default();\n", "file_path": "src/controllers/blog/index.rs", "rank": 5, "score": 31832.26623770537 }, { "content": "pub fn source(req: HttpRequest<AppState>) -> impl Responder {\n\n let ref_req = Rc::new(req);\n\n let req_for_contents = Rc::clone(&ref_req);\n\n let req_for_err = Rc::clone(&ref_req);\n\n\n\n match req_for_contents.match_info().get(\"name\") {\n\n Some(name) => {\n\n if req_for_contents.state().static_assets_handle {\n\n if name == \"favicon.ico\" {\n\n use std::io::ErrorKind;\n\n use std::path::PathBuf;\n\n\n\n let req_for_static = Rc::clone(&ref_req);\n\n let req_for_error = Rc::clone(&ref_req);\n\n let directory = Arc::clone(&req_for_static.state().public_path);\n\n let path = match *directory {\n\n Some(ref ref_directory) => PathBuf::from(ref_directory).join(name),\n\n None => panic!(\"Error: Fatal system logic error\"),\n\n };\n\n\n", "file_path": "src/controllers/blog/content.rs", "rank": 6, "score": 31832.26623770537 }, { "content": "pub fn content(req: HttpRequest<AppState>) -> impl Responder {\n\n let ref_req = Rc::new(req);\n\n let req_for_err = Rc::clone(&ref_req);\n\n\n\n match find_content(ref_req, None) {\n\n Ok(fut) => {\n\n fut\n\n .and_then(|res| {\n\n #[derive(Serialize)]\n\n struct Content {\n\n title: String,\n\n content: String,\n\n published_at_o: Option<NaiveDateTime>,\n\n published_at: Option<String>,\n\n }\n\n\n\n let origin: content::ContentFullDisplay = res?;\n\n let data = Content {\n\n content: markdown_to_html(&origin.content.unwrap_or(String::from(\"\")), &ComrakOptions::default()),\n\n title: origin.title,\n", "file_path": "src/controllers/blog/content.rs", "rank": 7, "score": 31832.26623770537 }, { "content": "pub fn create(req: HttpRequest<AppState>) -> impl Responder {\n\n let req_ref = Rc::new(req);\n\n\n\n \"\"\n\n}", "file_path": "src/controllers/admin/content.rs", "rank": 8, "score": 31832.26623770537 }, { "content": "pub fn rss(req: HttpRequest<AppState>) -> impl Responder {\n\n let req_ref = Rc::new(req);\n\n let req_for_db = Rc::clone(&req_ref);\n\n let req_for_data = Rc::clone(&req_ref);\n\n let req_for_err = Rc::clone(&req_ref);\n\n let setting = get_site_setting();\n\n let mut channel: Channel = ChannelBuilder::default()\n\n .title(\"Inspirer blog article\")\n\n .link(setting.site.home)\n\n .description(\"An RSS feed.\")\n\n .build()\n\n .unwrap();\n\n\n\n let default_getter = content::GetContents {\n\n category: Some(content::CategoryMatcher::NotZero),\n\n content_type: Some(1),\n\n ..Default::default()\n\n };\n\n let default_content = Pagination::new(Some(1), Some(10), Some(default_getter));\n\n\n", "file_path": "src/controllers/blog/rss.rs", "rank": 9, "score": 31832.26623770537 }, { "content": "pub fn admin_routes<S>(scope: Scope<S>) -> Scope<S>\n\n where HttpRequest<AppState>: FromRequest<S>\n\n{\n\n scope\n\n .route(\"/authentication\", Method::POST, admin::authorization::authorization)\n\n .nested(\"\", |scope| {\n\n scope.middleware(MAuthenticate)\n\n .route(\"/session/current-user\", Method::GET, admin::user::get_current_user_info)\n\n .route(\"/category\", Method::GET, admin::category::get_category_list)\n\n .route(\"/category\", Method::POST, admin::category::create_category)\n\n .route(\"/category/{id:\\\\d+}\", Method::DELETE, admin::category::delete_category)\n\n .route(\"/category/{id:\\\\d+}\", Method::PUT, admin::category::update_category)\n\n .route(\"/category/{id:\\\\d+}\", Method::GET, admin::category::get_category)\n\n .route(\"/content\", Method::POST, admin::content::create_content)\n\n .route(\"/content\", Method::GET, admin::content::get_content_list)\n\n .route(\"/content/{id:\\\\d+}\", Method::GET, admin::content::get_content)\n\n .route(\"/content/{id:\\\\d+}\", Method::DELETE, admin::content::delete_content)\n\n .route(\"/content/{id:\\\\d+}\", Method::PUT, admin::content::update_content)\n\n })\n\n}", "file_path": "src/routes/admin.rs", "rank": 10, "score": 31711.13939920818 }, { "content": "pub fn article_list(req: HttpRequest<AppState>) -> impl Responder {\n\n let ref_req = Rc::new(req);\n\n let mut default_content = Pagination::<content::GetContents>::from_request(Rc::clone(&ref_req));\n\n let mut default_getter = content::GetContents::default();\n\n\n\n default_getter.category = Some(content::CategoryMatcher::NotZero);\n\n default_getter.content_type = Some(1);\n\n default_content.filter = Some(default_getter);\n\n\n\n content_list(ref_req, default_content)\n\n}\n\n\n", "file_path": "src/controllers/blog/content.rs", "rank": 11, "score": 31220.06336997304 }, { "content": "pub fn blog_routes<S: 'static>(scope: Scope<S>) -> Scope<S>\n\n where HttpRequest<AppState>: FromRequest<S>\n\n{\n\n scope\n\n .route(\"/\", Method::GET, blog::index::home)\n\n .route(\"/article\", Method::GET, blog::content::article_list)\n\n .resource(\"/article/{name}\", |r| {\n\n r.name(\"article\");\n\n r.method(Method::GET).with(blog::content::content);\n\n })\n\n .route(\"/push\", Method::GET, blog::push_message::push_message_list)\n\n .route(\"/feed\", Method::GET, blog::rss::rss)\n\n .route(\"/{name}\", Method::GET, blog::content::source)\n\n}", "file_path": "src/routes/blog.rs", "rank": 12, "score": 30368.982808860044 }, { "content": "pub fn push_message_list(req: HttpRequest<AppState>) -> impl Responder {\n\n let ref_req = Rc::new(req);\n\n let req_for_pushes = Rc::clone(&ref_req);\n\n let req_for_err = Rc::clone(&ref_req);\n\n let query_message = Pagination::<push_message::GetPushMessages>::from_request(Rc::clone(&ref_req));\n\n\n\n req_for_pushes.state().database.send(query_message).from_err()\n\n .and_then(|push_messages| {\n\n let push_messages: PaginatedListMessage<push_message::PushMessageDisplay> = push_messages?;\n\n let mut list: Vec<PushMessage> = vec![];\n\n\n\n for item in push_messages.list {\n\n list.push(PushMessage {\n\n id: item.id,\n\n content: item.content,\n\n created_at: item.created_at.format(\"%Y-%m-%d\").to_string(),\n\n created_at_o: item.created_at,\n\n })\n\n }\n\n\n", "file_path": "src/controllers/blog/push_message.rs", "rank": 13, "score": 30107.196058896465 }, { "content": "alter table `contents`\n\n add column `as_page` tinyint(1) not null default 0 comment '是否可以作为单页面' after `category_id`;\n\n\n", "file_path": "migrations/2018-08-29-084801_version_1_1_migration/up.sql", "rank": 14, "score": 25806.324259473 }, { "content": "alter table `contents`\n\n drop column `as_page`;\n\n\n", "file_path": "migrations/2018-08-29-084801_version_1_1_migration/down.sql", "rank": 15, "score": 25806.324259473 }, { "content": "create table if not exists `subjects` (\n\n `id` int unsigned not null auto_increment,\n\n `name` varchar(255) character set utf8mb4 collate utf8mb4_general_ci,\n\n `title` varchar(255) character set utf8mb4 collate utf8mb4_general_ci not null,\n\n `keywords` varchar(255) character set utf8mb4 collate utf8mb4_general_ci not null default '',\n\n `description` varchar(500) character set utf8mb4 collate utf8mb4_general_ci not null default '',\n\n `sort` smallint not null default 0,\n\n `created_at` timestamp not null default current_timestamp,\n\n `updated_at` timestamp null on update current_timestamp,\n\n primary key (`id`),\n\n unique key `union_name` (`name`),\n\n key `search_title` (`name`, `title`)\n\n) character set = utf8mb4 collate = utf8mb4_general_ci comment = '专题表';\n\n\n", "file_path": "migrations/2018-06-26-090532_version_1_0_migration/up.sql", "rank": 16, "score": 24680.997942494858 }, { "content": "DROP TABLE IF EXISTS `contents`;\n", "file_path": "migrations/2018-06-26-090532_version_1_0_migration/down.sql", "rank": 17, "score": 24680.997942494858 }, { "content": "create table if not exists `contents` (\n\n `id` int unsigned not null auto_increment,\n\n `name` varchar(255) character set utf8mb4 collate utf8mb4_general_ci,\n\n `title` varchar(255) character set utf8mb4 collate utf8mb4_general_ci not null,\n\n `category_id` int unsigned default null,\n\n `keywords` varchar(255) character set utf8mb4 collate utf8mb4_general_ci not null default '',\n\n `description` varchar(500) character set utf8mb4 collate utf8mb4_general_ci not null default '',\n\n `sort` smallint not null default 0,\n\n `content_type` smallint unsigned not null default 1,\n\n `content` mediumtext character set utf8mb4 collate utf8mb4_general_ci null,\n\n `display` tinyint(1) not null default 1,\n\n `published_at` timestamp null,\n\n `modified_at` timestamp null,\n\n `created_at` timestamp not null default current_timestamp,\n\n `updated_at` timestamp null on update current_timestamp,\n\n primary key (`id`),\n\n unique key `union_name` (`name`),\n\n key `search_title` (`name`, `title`)\n\n) character set = utf8mb4 collate = utf8mb4_general_ci comment = '内容表';\n\n\n", "file_path": "migrations/2018-06-26-090532_version_1_0_migration/up.sql", "rank": 18, "score": 24680.997942494858 }, { "content": "DROP TABLE IF EXISTS `categories`;\n", "file_path": "migrations/2018-06-26-090532_version_1_0_migration/down.sql", "rank": 19, "score": 24680.997942494858 }, { "content": "DROP TABLE IF EXISTS `subjects`;\n", "file_path": "migrations/2018-06-26-090532_version_1_0_migration/down.sql", "rank": 20, "score": 24680.997942494858 }, { "content": "create table if not exists `categories` (\n\n `id` int unsigned not null auto_increment,\n\n `name` varchar(255) character set utf8mb4 collate utf8mb4_general_ci not null,\n\n `display_name` varchar(255) character set utf8mb4 collate utf8mb4_general_ci not null,\n\n `keywords` varchar(255) character set utf8mb4 collate utf8mb4_general_ci not null default '',\n\n `description` varchar(500) character set utf8mb4 collate utf8mb4_general_ci not null default '',\n\n `sort` smallint(4) not null default 0,\n\n `created_at` timestamp not null default current_timestamp,\n\n `updated_at` timestamp null on update current_timestamp,\n\n primary key (`id`),\n\n unique key `union_name` (`name`)\n\n) character set = utf8mb4 collate = utf8mb4_general_ci comment = '内容分类表';\n\n\n", "file_path": "migrations/2018-06-26-090532_version_1_0_migration/up.sql", "rank": 21, "score": 24680.997942494858 }, { "content": "pub fn error_msg<T: Into<String>>(code: u16, msg: T, body: Option<ErrorDetail>) -> ErrorMessage<ErrorDetail> {\n\n ErrorMessage::<ErrorDetail> {\n\n code,\n\n msg: msg.into(),\n\n body\n\n }\n\n}\n\n\n", "file_path": "src/error/mod.rs", "rank": 22, "score": 24253.366237227114 }, { "content": "create table if not exists `recommend_contents` (\n\n `id` int unsigned not null auto_increment,\n\n `content_id` int unsigned default null,\n\n `source` varchar(500) character set utf8mb4 collate utf8mb4_general_ci not null,\n\n `title` varchar(255) character set utf8mb4 collate utf8mb4_general_ci not null,\n\n `summary` varchar(500) character set utf8mb4 collate utf8mb4_general_ci not null,\n\n `created_at` timestamp not null default current_timestamp,\n\n `updated_at` timestamp null on update current_timestamp,\n\n primary key (`id`),\n\n key `content` (`content_id`)\n\n) character set = utf8mb4 collate = utf8mb4_general_ci comment = '推荐内容表';", "file_path": "migrations/2018-08-29-084801_version_1_1_migration/up.sql", "rank": 23, "score": 23649.714084302428 }, { "content": "create table if not exists `push_messages` (\n\n `id` int unsigned not null auto_increment,\n\n `content` varchar(500) character set utf8mb4 collate utf8mb4_general_ci not null,\n\n `sort` smallint not null default 0,\n\n `created_at` timestamp not null default current_timestamp,\n\n `updated_at` timestamp null on update current_timestamp,\n\n primary key (`id`),\n\n key `search` (`content`)\n\n) character set = utf8mb4 collate = utf8mb4_general_ci comment = 'PUSH 消息表';\n\n\n", "file_path": "migrations/2018-06-26-090532_version_1_0_migration/up.sql", "rank": 24, "score": 23649.714084302428 }, { "content": "DROP TABLE IF EXISTS `subject_relates`;", "file_path": "migrations/2018-06-26-090532_version_1_0_migration/down.sql", "rank": 25, "score": 23649.714084302428 }, { "content": "DROP TABLE IF EXISTS `push_messages`;\n", "file_path": "migrations/2018-06-26-090532_version_1_0_migration/down.sql", "rank": 26, "score": 23649.714084302428 }, { "content": "create table if not exists `subject_relates` (\n\n `subject_id` int unsigned not null,\n\n `content_id` int unsigned not null,\n\n `sort` smallint not null default 0,\n\n `created_at` timestamp not null default current_timestamp,\n\n `updated_at` timestamp null on update current_timestamp,\n\n primary key (`subject_id`, `content_id`)\n\n) comment = '专题内容关联表';", "file_path": "migrations/2018-06-26-090532_version_1_0_migration/up.sql", "rank": 27, "score": 23649.714084302428 }, { "content": "drop table if exists `recommend_contents`;", "file_path": "migrations/2018-08-29-084801_version_1_1_migration/down.sql", "rank": 28, "score": 23649.714084302428 }, { "content": "fn find_content(req: Rc<HttpRequest<AppState>>, filter: Option<FindFilter>) -> StdResult<impl Future<Item=Result<content::ContentFullDisplay>, Error=Error>, ActixError> {\n\n let req_for_contents = Rc::clone(&req);\n\n let req_for_err = Rc::clone(&req);\n\n let name = match req_for_contents.match_info().get(\"name\") {\n\n Some(name) => {\n\n let numeric = regex::Regex::new(r\"^\\d+$\").unwrap();\n\n let name_string = regex::Regex::new(r\"^\\w+(-\\w+)*$\").unwrap();\n\n\n\n if numeric.is_match(name) {\n\n let id = name.parse::<u32>().unwrap();\n\n Ok(content::Find::ById(id))\n\n } else if name_string.is_match(name) {\n\n Ok(content::Find::ByName(name.into()))\n\n } else {\n\n Err(error_handler(req_for_err)(Error::bad_request_error(Some(\"[param]\"), None)))\n\n }\n\n }\n\n None => Err(error_handler(req_for_err)(Error::bad_request_error(Some(\"[param]\"), None))),\n\n };\n\n\n\n name.map(move |name| {\n\n req_for_contents.state().database\n\n .send(content::FindContent {\n\n inner: name,\n\n filter,\n\n })\n\n .from_err()\n\n })\n\n}\n\n\n", "file_path": "src/controllers/blog/content.rs", "rank": 29, "score": 12266.476914902847 }, { "content": "use actix::{Message, Handler};\n\nuse diesel;\n\nuse diesel::*;\n\nuse chrono::NaiveDateTime;\n\n\n\nuse result::Result;\n\nuse database::{DatabaseExecutor, Conn, last_insert_id};\n\nuse message::{PaginatedListMessage, Pagination, UpdateByID};\n\nuse error::{Error, database::map_database_error};\n\nuse schema::push_messages;\n\n\n\n#[derive(Deserialize, Insertable, Debug)]\n\n#[table_name = \"push_messages\"]\n\npub struct NewPushMessage {\n\n pub content: String,\n\n}\n\n\n\n#[derive(Deserialize, AsChangeset, Debug)]\n\n#[table_name = \"push_messages\"]\n\npub struct UpdatePushMessage {\n", "file_path": "src/models/push_message.rs", "rank": 32, "score": 15.560294586319692 }, { "content": "use actix::{Message, Handler};\n\nuse diesel;\n\nuse diesel::*;\n\nuse chrono::NaiveDateTime;\n\n\n\nuse result::Result;\n\nuse database::{DatabaseExecutor, Conn, last_insert_id};\n\nuse message::{PaginatedListMessage, Pagination, UpdateByID};\n\nuse error::{Error, database::map_database_error};\n\nuse schema::contents;\n\nuse schema::contents::dsl as column;\n\nuse models::category::FindCategory;\n\n\n\n#[derive(Deserialize, Insertable, Debug)]\n\n#[table_name = \"contents\"]\n\npub struct NewContent {\n\n pub name: Option<String>,\n\n pub title: String,\n\n pub category_id: Option<u32>,\n\n pub keywords: String,\n", "file_path": "src/models/content.rs", "rank": 33, "score": 15.214014857159071 }, { "content": "use std::collections::{HashMap, HashSet};\n\n\n\nuse actix::{Message, Handler};\n\nuse diesel;\n\nuse diesel::*;\n\nuse chrono::NaiveDateTime;\n\n\n\nuse result::Result;\n\nuse database::{DatabaseExecutor, Conn, last_insert_id};\n\nuse message::{PaginatedListMessage, Pagination, UpdateByID};\n\nuse error::{Error, database::map_database_error};\n\n\n\nuse schema::subjects;\n\nuse schema::subject_relates;\n\n\n\npub struct Subject;\n\n\n\n#[derive(Deserialize, Insertable, Debug)]\n\n#[table_name = \"subjects\"]\n\npub struct NewSubject {\n", "file_path": "src/models/subject.rs", "rank": 34, "score": 14.943558846573772 }, { "content": "use actix::{Message, Handler};\n\nuse diesel;\n\nuse diesel::*;\n\nuse diesel::dsl::exists;\n\nuse chrono::NaiveDateTime;\n\n\n\nuse result::Result;\n\nuse database::{DatabaseExecutor, Conn, last_insert_id};\n\nuse message::{PaginatedListMessage, Pagination, UpdateByID};\n\nuse error::{Error, database::map_database_error};\n\nuse schema::recommend_contents;\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone, Queryable)]\n\npub struct RecommendContentDisplay {\n\n pub id: u32,\n\n pub content_id: Option<u32>,\n\n pub source: String,\n\n pub title: String,\n\n pub summary: String,\n\n pub created_at: NaiveDateTime,\n", "file_path": "src/models/recommend.rs", "rank": 35, "score": 14.536159707878902 }, { "content": "use std::rc::Rc;\n\nuse std::sync::Arc;\n\nuse actix::*;\n\nuse actix::dev::{Request, ToEnvelope};\n\nuse diesel::{sql_query, RunQueryDsl};\n\nuse diesel::prelude::MysqlConnection;\n\nuse diesel::r2d2::{ConnectionManager, Pool};\n\nuse database::DatabaseExecutor;\n\n\n\npub struct Config {\n\n pub static_assets_handle: bool,\n\n pub static_assets_path: Option<String>,\n\n pub public_path: Option<String>,\n\n pub database_url: String,\n\n pub database_timezone: Option<String>,\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct AppState {\n\n pub static_assets_handle: bool,\n", "file_path": "src/state.rs", "rank": 36, "score": 12.995140067614457 }, { "content": " use schema::categories::dsl::*;\n\n\n\n Ok(\n\n categories\n\n .filter(name.eq(category_name))\n\n .first::<CategoryFullDisplay>(connection)\n\n .map_err(map_database_error(Some(\"categories\")))?\n\n )\n\n }\n\n\n\n pub fn create(connection: &Conn, category: NewCategory) -> Result<u64> {\n\n use schema::categories::dsl::*;\n\n\n\n diesel::insert_into(categories)\n\n .values(category)\n\n .execute(connection)\n\n .map_err(map_database_error(Some(\"categories\")))?;\n\n\n\n let generated_id: u64 = diesel::select(last_insert_id)\n\n .first(connection)\n", "file_path": "src/models/category.rs", "rank": 38, "score": 12.696405077869231 }, { "content": " .map_err(map_database_error(Some(\"contents\")))?;\n\n\n\n let generated_id: u64 = diesel::select(last_insert_id)\n\n .first(connection)\n\n .map_err(map_database_error(Some(\"contents\")))?;\n\n\n\n Ok(generated_id as u32)\n\n }\n\n\n\n pub fn delete(connection: &Conn, target: u32) -> Result<usize> {\n\n use schema::contents::dsl::*;\n\n\n\n let count = delete_by_id!(connection => (\n\n contents # = target\n\n ))?;\n\n\n\n Ok(count)\n\n }\n\n\n\n pub fn publish(connection: &Conn, target: u32) -> Result<Option<ContentFullDisplay>> {\n", "file_path": "src/models/content.rs", "rank": 39, "score": 12.536911278812902 }, { "content": "use actix::{Message, Handler};\n\nuse diesel;\n\nuse diesel::*;\n\nuse diesel::dsl::exists;\n\nuse chrono::NaiveDateTime;\n\n\n\nuse result::Result;\n\nuse database::{DatabaseExecutor, Conn, last_insert_id};\n\nuse message::{PaginatedListMessage, Pagination, UpdateByID};\n\nuse error::{Error, database::map_database_error};\n\nuse schema::categories;\n\nuse schema::categories::dsl as column;\n\nuse regex::Regex;\n\n\n", "file_path": "src/models/category.rs", "rank": 40, "score": 12.522930379247322 }, { "content": " };\n\n\n\n Self::create(connection, creator)\n\n }\n\n\n\n pub fn create(connection: &Conn, data: NewRecommendContent) -> Result<u32> {\n\n use schema::recommend_contents::dsl::*;\n\n\n\n diesel::insert_into(recommend_contents)\n\n .values(&data)\n\n .execute(connection)\n\n .map_err(map_database_error(Some(\"recommend_contents\")))?;\n\n\n\n let generated_id: u64 = diesel::select(last_insert_id)\n\n .first(connection)\n\n .map_err(map_database_error(Some(\"recommend_contents\")))?;\n\n\n\n Ok(generated_id as u32)\n\n }\n\n\n", "file_path": "src/models/recommend.rs", "rank": 41, "score": 11.842601221020233 }, { "content": " .values(&data)\n\n .execute(connection)\n\n .map_err(map_database_error(Some(\"push_messages\")))?;\n\n\n\n let generated_id: u64 = diesel::select(last_insert_id)\n\n .first(connection)\n\n .map_err(map_database_error(Some(\"push_messages\")))?;\n\n\n\n Ok(generated_id as u32)\n\n }\n\n\n\n pub fn find_by_id(connection: &Conn, target: u32) -> Result<PushMessageDisplay> {\n\n use schema::push_messages::dsl::*;\n\n\n\n find_by_id!(connection => (\n\n push_messages # = target => PushMessageDisplay\n\n ))\n\n }\n\n\n\n pub fn update(connection: &Conn, target: u32, data: UpdatePushMessage) -> Result<Option<PushMessageDisplay>> {\n", "file_path": "src/models/push_message.rs", "rank": 43, "score": 11.563568780598185 }, { "content": "\n\nimpl Content {\n\n pub const DISPLAY_COLUMNS: (\n\n column::id, column::name, column::title,\n\n column::category_id, column::keywords, column::description,\n\n column::sort, column::content_type, column::display,\n\n column::published_at, column::modified_at\n\n ) = (\n\n column::id, column::name, column::title,\n\n column::category_id, column::keywords, column::description,\n\n column::sort, column::content_type, column::display,\n\n column::published_at, column::modified_at\n\n );\n\n\n\n pub fn create(connection: &Conn, data: NewContent) -> Result<u32> {\n\n use schema::contents::dsl::*;\n\n\n\n diesel::insert_into(contents)\n\n .values(&data)\n\n .execute(connection)\n", "file_path": "src/models/content.rs", "rank": 44, "score": 11.329146997951185 }, { "content": " pub fn get_relate_base_info_list(connection: &Conn, target: u32, display: bool) -> Result<Vec<SubjectRelateBaseInfo>> {\n\n use schema::contents;\n\n use schema::subject_relates as sr;\n\n\n\n sr::table\n\n .inner_join(contents::table.on(\n\n sr::content_id.eq(contents::id)\n\n .and(contents::display.eq(display))\n\n ))\n\n .select((contents::id, contents::name, contents::title, contents::category_id, contents::sort, contents::content_type, contents::display, sr::sort))\n\n .filter(sr::subject_id.eq(target))\n\n .order_by((sr::sort.desc(), contents::sort.desc()))\n\n .load::<SubjectRelateBaseInfo>(connection)\n\n .map_err(map_database_error(Some(\"subject_relates\")))\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, Copy)]\n\npub struct GetRelateList {\n\n pub target: u32,\n\n pub display: bool\n\n}", "file_path": "src/models/subject.rs", "rank": 45, "score": 11.199991508797991 }, { "content": " pub updated_at: Option<NaiveDateTime>,\n\n}\n\n\n\n#[derive(Deserialize, Insertable, Debug)]\n\n#[table_name = \"recommend_contents\"]\n\npub struct NewRecommendContent {\n\n pub content_id: u32,\n\n pub source: String,\n\n pub title: String,\n\n pub summary: String,\n\n}\n\n\n\npub struct RecommendContent;\n\n\n\nimpl RecommendContent {\n\n pub fn push(connection: &Conn, origin_id: u32, summary: Option<String>) -> Result<u32> {\n\n use super::content::Content;\n\n\n\n let result = Content::find_by_id(connection, origin_id, None)?;\n\n let id = result.id.to_string();\n", "file_path": "src/models/recommend.rs", "rank": 47, "score": 10.907087877127099 }, { "content": " }\n\n\n\n Ok(())\n\n })\n\n }\n\n\n\n pub fn find_by_id(connection: &Conn, target: u32) -> Result<SubjectDisplay> {\n\n use schema::subjects::dsl::*;\n\n\n\n find_by_id!(connection => (\n\n subjects # = target => SubjectDisplay\n\n ))\n\n }\n\n\n\n pub fn find_by_name(connection: &Conn, target: String) -> Result<SubjectDisplay> {\n\n use schema::subjects::dsl::*;\n\n\n\n find_by_id!(connection => (\n\n subjects name = target => SubjectDisplay\n\n ))\n", "file_path": "src/models/subject.rs", "rank": 48, "score": 10.268277467260889 }, { "content": " use schema::contents::dsl::*;\n\n use chrono::Utc;\n\n\n\n let count = diesel::update(contents)\n\n .set((display.eq(true), published_at.eq(Some(Utc::now().naive_local()))))\n\n .filter(id.eq(target))\n\n .execute(connection)\n\n .map_err(map_database_error(Some(\"contents\")))?;\n\n\n\n if count > 0 {\n\n Ok(Self::find_by_id(connection, target, None).ok())\n\n } else {\n\n Ok(None)\n\n }\n\n }\n\n\n\n pub fn unpublish(connection: &Conn, target: u32) -> Result<Option<ContentFullDisplay>> {\n\n use schema::contents::dsl::*;\n\n\n\n let count = diesel::update(contents)\n", "file_path": "src/models/content.rs", "rank": 49, "score": 10.180613389921602 }, { "content": " .map_err(map_database_error(Some(\"categories\")))?;\n\n\n\n Ok(generated_id)\n\n }\n\n\n\n pub fn delete(connection: &Conn, category_id: u32) -> Result<usize> {\n\n use schema::categories::dsl::*;\n\n\n\n let count = delete_by_id!(connection => (categories # = category_id))?;\n\n\n\n Ok(count)\n\n }\n\n\n\n pub fn update(connection: &Conn, category_id: u32, update: UpdateCategory) -> Result<Option<CategoryFullDisplay>> {\n\n use schema::categories::dsl::*;\n\n\n\n let count = update_by_id!(connection => (\n\n categories # = category_id; <- &update\n\n ))?;\n\n\n", "file_path": "src/models/category.rs", "rank": 50, "score": 10.07740334235989 }, { "content": " pub sort: Option<i16>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Queryable)]\n\npub struct PushMessageDisplay {\n\n pub id: u32,\n\n pub content: String,\n\n pub sort: i16,\n\n pub created_at: NaiveDateTime,\n\n pub updated_at: Option<NaiveDateTime>,\n\n}\n\n\n\npub struct PushMessage;\n\n\n\nimpl PushMessage {\n\n\n\n pub fn create(connection: &Conn, data: NewPushMessage) -> Result<u32> {\n\n use schema::push_messages::dsl::*;\n\n\n\n diesel::insert_into(push_messages)\n", "file_path": "src/models/push_message.rs", "rank": 51, "score": 9.633276836257073 }, { "content": " }\n\n\n\n pub fn update(connection: &Conn, target: u32, update: UpdateSubject) -> Result<Option<SubjectDisplay>> {\n\n use schema::subjects::dsl::*;\n\n\n\n let count = update_by_id!(connection => (\n\n subjects # = target; <- &update\n\n ))?;\n\n\n\n if count > 0 {\n\n Ok(Self::find_by_id(connection, target).ok())\n\n } else {\n\n Ok(None)\n\n }\n\n }\n\n\n\n pub fn delete(connection: &Conn, target: u32) -> Result<(usize, usize)> {\n\n use schema::subjects::dsl::*;\n\n\n\n connection.transaction(|| {\n", "file_path": "src/models/subject.rs", "rank": 52, "score": 9.555999533163517 }, { "content": " }\n\n\n\n query.order((sort.desc(), created_at.desc(), id.desc()))\n\n });\n\n\n\n paginator()\n\n }\n\n\n\n pub fn find_by_id(connection: &Conn, category_id: u32) -> Result<CategoryFullDisplay> {\n\n use schema::categories::dsl::*;\n\n\n\n Ok(\n\n categories\n\n .filter(id.eq(category_id))\n\n .first::<CategoryFullDisplay>(connection)\n\n .map_err(map_database_error(Some(\"categories\")))?\n\n )\n\n }\n\n\n\n pub fn find_by_name(connection: &Conn, category_name: String) -> Result<CategoryFullDisplay> {\n", "file_path": "src/models/category.rs", "rank": 53, "score": 9.293064031392081 }, { "content": " pub content_type: u16,\n\n pub published_at: Option<NaiveDateTime>,\n\n pub modified_at: Option<NaiveDateTime>,\n\n pub display: bool,\n\n pub relate_sort: i16,\n\n}\n\n\n\nimpl Subject {\n\n pub fn create(connection: &Conn, create: CreateSubject) -> Result<u32> {\n\n use schema::subjects::dsl::*;\n\n\n\n connection.transaction(move || {\n\n let rows: usize = diesel::insert_into(subjects)\n\n .values(&create.subject)\n\n .execute(connection)\n\n .map_err(map_database_error(Some(\"subjects\")))?;\n\n\n\n if rows < 1 {\n\n return Err(Error::internal_server_error(Some(\"[unknown]\"), None));\n\n }\n", "file_path": "src/models/subject.rs", "rank": 54, "score": 9.230255738204312 }, { "content": "use std::collections::HashMap;\n\nuse std::fmt;\n\nuse message::ErrorMessage;\n\nuse diesel::result::{\n\n Error as DieselError,\n\n DatabaseErrorKind as DieselDatabaseErrorKind,\n\n};\n\n\n\nuse super::error_msg;\n\nuse super::Error;\n\nuse super::ErrorDetail;\n\n\n\npub const NOT_FOUND: u16 = 10022;\n\npub const CONFLICT: u16 = 10013;\n\npub const GET_CONNECTION_ERROR: u16 = 10001;\n\npub const UNKNOWN_DB_ERROR: u16 = 10099;\n\n\n", "file_path": "src/error/database.rs", "rank": 55, "score": 9.220502430197985 }, { "content": "use std::borrow::BorrowMut;\n\nuse std::collections::HashMap;\n\nuse actix::MailboxError;\n\nuse actix_web::{HttpRequest, HttpResponse, HttpMessage, http::StatusCode};\n\nuse actix_web::error::{Error as ActixError, ResponseError};\n\nuse std::fmt::{self, Formatter};\n\nuse message::ErrorMessage;\n\nuse tera::{Context, Tera};\n\nuse template::TEMPLATES;\n\nuse mime;\n\n\n\npub mod database;\n\n\n\npub const UNKNOWN_ERROR: u16 = 65535;\n\npub const ACTOR_MAILBOX_ERROR: u16 = 60001;\n\n\n", "file_path": "src/error/mod.rs", "rank": 56, "score": 9.089622123078314 }, { "content": "\n\n let generated_id: u64 = diesel::select(last_insert_id)\n\n .first(connection)\n\n .map_err(map_database_error(Some(\"subjects\")))?;\n\n let generated_id = generated_id as u32;\n\n\n\n match create.relates {\n\n Some(relates) => {\n\n use schema::subject_relates::dsl::*;\n\n\n\n let mut create_relates = Vec::with_capacity(10);\n\n for relate in relates {\n\n create_relates.push(\n\n (subject_id.eq(generated_id), content_id.eq(relate.content_id), sort.eq(relate.sort.unwrap_or(0)))\n\n );\n\n }\n\n\n\n if create_relates.len() > 0 {\n\n diesel::insert_into(subject_relates)\n\n .values(&create_relates)\n", "file_path": "src/models/subject.rs", "rank": 57, "score": 8.842495405221767 }, { "content": " pub description: String,\n\n pub sort: i16,\n\n pub content_type: u16,\n\n pub content: Option<String>,\n\n pub display: bool,\n\n pub published_at: Option<NaiveDateTime>,\n\n pub as_page: bool,\n\n}\n\n\n\n#[derive(Deserialize, AsChangeset, Debug)]\n\n#[table_name = \"contents\"]\n\npub struct UpdateContent {\n\n pub name: Option<String>,\n\n pub title: Option<String>,\n\n pub category_id: Option<u32>,\n\n pub keywords: Option<String>,\n\n pub description: Option<String>,\n\n pub sort: Option<i16>,\n\n pub content_type: Option<u16>,\n\n pub content: Option<String>,\n", "file_path": "src/models/content.rs", "rank": 58, "score": 8.715968505739173 }, { "content": " let count = delete_by_id!(connection => (subjects # = target))?;\n\n if count > 0 {\n\n use schema::subject_relates::dsl::*;\n\n let relates_count = delete_by_id!(connection => (subject_relates subject_id = target))?;\n\n\n\n Ok((count, relates_count))\n\n } else {\n\n Ok((count, 0))\n\n }\n\n })\n\n }\n\n\n\n pub fn get_list(connection: &Conn) {}\n\n\n\n pub fn get_relate_list(connection: &Conn, paginated: Pagination<GetRelateList>) -> Result<PaginatedListMessage<SubjectRelateInfo>> {\n\n use schema::contents;\n\n use schema::subject_relates as sr;\n\n\n\n let target = paginated.filter.ok_or(Error::bad_request_error(Some(\"[param]\"), None))?.target;\n\n let display = paginated.filter.ok_or(Error::bad_request_error(Some(\"[param]\"), None))?.display;\n", "file_path": "src/models/subject.rs", "rank": 59, "score": 8.686555919456504 }, { "content": " query = query.filter(content.like(format!(\"%{}%\", &v)));\n\n }\n\n }\n\n\n\n query.order((sort.desc(), created_at.desc()))\n\n });\n\n\n\n paginator()\n\n }\n\n\n\n pub fn delete(connection: &Conn, target: u32) -> Result<usize> {\n\n use schema::push_messages::dsl::*;\n\n\n\n let count = delete_by_id!(connection => (\n\n push_messages # = target\n\n ))?;\n\n\n\n Ok(count)\n\n }\n\n}\n", "file_path": "src/models/push_message.rs", "rank": 60, "score": 7.77304245888177 }, { "content": "pub struct SubjectRelateBaseInfo {\n\n pub id: u32,\n\n pub name: Option<String>,\n\n pub title: String,\n\n pub category_id: Option<u32>,\n\n pub content_sort: i16,\n\n pub content_type: u16,\n\n pub display: bool,\n\n pub relate_sort: i16,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Queryable)]\n\npub struct SubjectRelateInfo {\n\n pub id: u32,\n\n pub name: Option<String>,\n\n pub title: String,\n\n pub category_id: Option<u32>,\n\n pub description: String,\n\n pub keywords: String,\n\n pub content_sort: i16,\n", "file_path": "src/models/subject.rs", "rank": 61, "score": 7.749685817807141 }, { "content": " .execute(connection)\n\n .map_err(map_database_error(Some(\"subject_relates\")))?;\n\n }\n\n }\n\n None => (),\n\n };\n\n\n\n Ok(generated_id)\n\n })\n\n }\n\n\n\n pub fn sync_relates(connection: &Conn, target: u32, sync: Vec<SubjectRelate>) -> Result<()> {\n\n use schema::subject_relates::dsl::*;\n\n\n\n let mut key_index = Vec::with_capacity(sync.len());\n\n\n\n for item in &sync {\n\n key_index.push(item.content_id);\n\n }\n\n\n", "file_path": "src/models/subject.rs", "rank": 62, "score": 7.703710709495733 }, { "content": " .unwrap_or(1);\n\n let per_page = query.get(\"per_page\")\n\n .map(|v| v.parse::<i64>().unwrap_or(Self::DEFAULT_PER_PAGE))\n\n .unwrap_or(Self::DEFAULT_PER_PAGE);\n\n\n\n Pagination::<T> {\n\n page,\n\n per_page,\n\n filter: None\n\n }\n\n }\n\n}\n\n\n\n#[derive(Copy, Clone)]\n\npub struct UpdateByID<T> {\n\n pub id: u32,\n\n pub update: T,\n\n}\n\n\n\n#[derive(Deserialize,Serialize, Debug)]\n\npub struct CreatedObjectIdMessage {\n\n pub id: u64,\n\n}\n\n\n\n#[derive(Deserialize,Serialize, Debug)]\n\npub struct DeletedObjectMessage {\n\n pub count: u32,\n\n}", "file_path": "src/message.rs", "rank": 63, "score": 7.561086769200411 }, { "content": " use schema::push_messages::dsl::*;\n\n\n\n let count = update_by_id!(connection => (\n\n push_messages # = target; <- &data\n\n ))?;\n\n\n\n if count > 0 {\n\n Ok(Self::find_by_id(connection, target).ok())\n\n } else {\n\n Ok(None)\n\n }\n\n }\n\n\n\n pub fn get_list(connection: &Conn, c: Pagination<GetPushMessages>) -> Result<PaginatedListMessage<PushMessageDisplay>> {\n\n use schema::push_messages::dsl::*;\n\n\n\n let paginator = paginator!(connection, c, PushMessageDisplay, {\n\n let mut query = push_messages.into_boxed();\n\n if let Some(filter) = c.clone().filter {\n\n if let Some(v) = filter.keywords {\n", "file_path": "src/models/push_message.rs", "rank": 64, "score": 7.5015358583754415 }, { "content": " None => (),\n\n };\n\n\n\n query.first::<ContentFullDisplay>(connection).map_err(map_database_error(Some(\"contents\")))\n\n }\n\n\n\n pub fn update(connection: &Conn, target: u32, data: UpdateContent) -> Result<Option<ContentFullDisplay>> {\n\n use schema::contents::dsl::*;\n\n\n\n let count = update_by_id!(connection => (\n\n contents # = target; <- &data\n\n ))?;\n\n\n\n if count > 0 {\n\n Ok(Self::find_by_id(connection, target, None).ok())\n\n } else {\n\n Ok(None)\n\n }\n\n }\n\n\n", "file_path": "src/models/content.rs", "rank": 65, "score": 7.436678591594777 }, { "content": "use error::ErrorDetail;\n\nuse actix_web::HttpRequest;\n\n\n\n/// 错误消息体\n\n///\n\n/// 错误消息体最终会转换为对应的 JSON 格式。\n\n#[derive(Deserialize, Serialize, Debug)]\n\npub struct ErrorMessage<T> {\n\n /// 错误代码,`u16` 类型,默认为 65535,意为未知服务错误\n\n pub code: u16,\n\n /// 错误消息,`String` 类型。该字段简要描述错误信息\n\n pub msg: String,\n\n /// 错误详情\n\n pub body: Option<T>,\n\n}\n\n\n\nimpl<T> ErrorMessage<T> {\n\n pub fn new(code: u16, msg: String, body: Option<T>) -> Self {\n\n ErrorMessage::<T> {\n\n code,\n", "file_path": "src/message.rs", "rank": 66, "score": 7.247960934054548 }, { "content": " if count > 0 {\n\n Ok(Self::find_by_id(connection, category_id).ok())\n\n } else {\n\n Ok(None)\n\n }\n\n }\n\n\n\n pub fn exists(connection: &Conn, category: String) -> Result<bool> {\n\n use schema::categories::dsl::*;\n\n\n\n let regex = Regex::new(r\"^\\d+$\").unwrap();\n\n\n\n if regex.is_match(&category) {\n\n let category_id = category.parse::<u32>().unwrap();\n\n select(exists(categories.filter(id.eq(category_id))))\n\n .get_result(connection).map_err(map_database_error(Some(\"categories\")))\n\n } else {\n\n select(exists(categories.filter(name.eq(category))))\n\n .get_result(connection).map_err(map_database_error(Some(\"categories\")))\n\n }\n", "file_path": "src/models/category.rs", "rank": 67, "score": 7.210289165154416 }, { "content": "\n\n let paginator = paginator!(\n\n connection,\n\n (contents::id, contents::name, contents::title, contents::category_id, contents::description, contents::keywords, contents::sort, contents::content_type, contents::published_at, contents::modified_at, contents::display, sr::sort),\n\n paginated,\n\n SubjectRelateInfo,\n\n {\n\n\n\n sr::table\n\n .inner_join(contents::table.on(\n\n sr::content_id.eq(contents::id)\n\n .and(contents::display.eq(display))\n\n ))\n\n .filter(sr::subject_id.eq(target))\n\n .order_by((sr::sort.desc(), contents::sort.desc()))\n\n });\n\n\n\n paginator()\n\n }\n\n\n", "file_path": "src/models/subject.rs", "rank": 68, "score": 7.152829787901771 }, { "content": " pub display: Option<bool>,\n\n pub published_at: Option<NaiveDateTime>,\n\n pub modified_at: Option<NaiveDateTime>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Queryable)]\n\npub struct ContentDisplay {\n\n pub id: u32,\n\n pub name: Option<String>,\n\n pub title: String,\n\n pub category_id: Option<u32>,\n\n pub keywords: String,\n\n pub description: String,\n\n pub sort: i16,\n\n pub content_type: u16,\n\n pub display: bool,\n\n pub published_at: Option<NaiveDateTime>,\n\n pub modified_at: Option<NaiveDateTime>,\n\n}\n\n\n", "file_path": "src/models/content.rs", "rank": 69, "score": 7.085722736439804 }, { "content": "use chrono::NaiveDateTime;\n\n\n\npub mod index;\n\npub mod content;\n\npub mod push_message;\n\npub mod rss;\n\n\n\n#[derive(Serialize)]\n\npub struct Content {\n\n pub id: u32,\n\n pub name: Option<String>,\n\n pub title: String,\n\n pub description: String,\n\n pub published_at_o: Option<NaiveDateTime>,\n\n pub published_at: Option<String>,\n\n}\n\n\n\n#[derive(Serialize)]\n\npub struct PushMessage {\n\n pub id: u32,\n\n pub content: String,\n\n pub created_at: String,\n\n pub created_at_o: NaiveDateTime,\n\n}", "file_path": "src/controllers/blog/mod.rs", "rank": 70, "score": 7.057686213766122 }, { "content": "use actix_web::{HttpRequest, HttpResponse, Result};\n\nuse actix_web::middleware::{Middleware, Started};\n\nuse actix_web::middleware::session::RequestSession;\n\n\n\nuse util::auth::PrivateClaims;\n\nuse util::message::ErrorMessage;\n\n\n\npub struct Authenticate;\n\n\n\nimpl<S> Middleware<S> for Authenticate {\n\n fn start(&self, req: &mut HttpRequest<S>) -> Result<Started> {\n\n if let Some(_) = req.session().get::<PrivateClaims>(\"claims\")? {\n\n Ok(Started::Done)\n\n } else {\n\n Ok(Started::Response(HttpResponse::Unauthorized().json(ErrorMessage::<String> {\n\n code: 10014,\n\n msg: \"Invalid authentication token.\".to_owned(),\n\n body: None,\n\n })))\n\n }\n\n }\n\n}", "file_path": "src/middlewares/authenticate.rs", "rank": 71, "score": 7.0037147547386 }, { "content": "#[derive(Debug, Clone, Serialize, Deserialize, Queryable)]\n\npub struct ContentFullDisplay {\n\n pub id: u32,\n\n pub name: Option<String>,\n\n pub title: String,\n\n pub category_id: Option<u32>,\n\n pub as_page: bool,\n\n pub keywords: String,\n\n pub description: String,\n\n pub sort: i16,\n\n pub content_type: u16,\n\n pub content: Option<String>,\n\n pub display: bool,\n\n pub published_at: Option<NaiveDateTime>,\n\n pub modified_at: Option<NaiveDateTime>,\n\n pub created_at: NaiveDateTime,\n\n pub updated_at: Option<NaiveDateTime>,\n\n}\n\n\n\npub struct Content;\n", "file_path": "src/models/content.rs", "rank": 72, "score": 6.9854144427317575 }, { "content": " .set((display.eq(false), published_at.eq::<Option<NaiveDateTime>>(None)))\n\n .filter(id.eq(target))\n\n .execute(connection)\n\n .map_err(map_database_error(Some(\"contents\")))?;\n\n\n\n if count > 0 {\n\n Ok(Self::find_by_id(connection, target, None).ok())\n\n } else {\n\n Ok(None)\n\n }\n\n }\n\n\n\n pub fn find_by_id(connection: &Conn, target: u32, find_filter: Option<FindFilter>) -> Result<ContentFullDisplay> {\n\n use schema::contents::dsl::*;\n\n\n\n let mut query = contents.filter(id.eq(target)).into_boxed();\n\n\n\n match find_filter {\n\n Some(filter) => {\n\n if let Some(filter_as_page) = filter.as_page {\n", "file_path": "src/models/content.rs", "rank": 73, "score": 6.974175010776383 }, { "content": "#[macro_use] extern crate diesel;\n\n#[macro_use] extern crate serde_derive;\n\n#[macro_use] extern crate failure;\n\n#[macro_use] extern crate lazy_static;\n\n#[macro_use] extern crate tera;\n\n#[macro_use] extern crate log;\n\n\n\nextern crate serde;\n\nextern crate serde_json;\n\nextern crate actix;\n\nextern crate actix_web;\n\nextern crate mime;\n\nextern crate chrono;\n\nextern crate futures;\n\nextern crate regex;\n\nextern crate comrak;\n\nextern crate toml;\n\nextern crate rss;\n\nextern crate url;\n\nextern crate tempdir;\n", "file_path": "src/lib.rs", "rank": 74, "score": 6.955643549973848 }, { "content": " pub fn get_list(connection: &Conn, c: Pagination<GetContents>) -> Result<PaginatedListMessage<ContentDisplay>> {\n\n use schema::contents::dsl::*;\n\n\n\n let paginator = paginator!(connection, Self::DISPLAY_COLUMNS, c, ContentDisplay, {\n\n let mut query = contents.into_boxed();\n\n if let Some(filter) = c.clone().filter {\n\n if let Some(v) = filter.search {\n\n query = query.filter(name.like(format!(\"%{}%\", &v)).or(title.like(format!(\"%{}%\", &v))));\n\n }\n\n\n\n if let Some(v) = filter.display {\n\n query = query.filter(display.eq(v));\n\n }\n\n\n\n if let Some(v) = filter.content_type {\n\n query = query.filter(content_type.eq(v));\n\n }\n\n\n\n if let Some(v) = filter.category {\n\n match v {\n", "file_path": "src/models/content.rs", "rank": 75, "score": 6.936510760871123 }, { "content": "pub struct Category;\n\n\n\nimpl Category {\n\n const DISPLAY_COLUMNS: (\n\n column::id, column::name, column::display_name,\n\n column::description, column::created_at, column::updated_at\n\n ) = (\n\n column::id, column::name, column::display_name,\n\n column::description, column::created_at, column::updated_at\n\n );\n\n\n\n pub fn get_list(connection: &Conn, c: Pagination<GetCategoryList>) -> PaginatedCategoryList {\n\n use schema::categories::dsl::*;\n\n\n\n let paginator = paginator!(connection, Self::DISPLAY_COLUMNS, c, CategoryDisplay, {\n\n let mut query = categories.into_boxed();\n\n if let Some(filter) = c.clone().filter {\n\n if let Some(v) = filter.name {\n\n query = query.filter(name.like(format!(\"%{}%\", v)));\n\n }\n", "file_path": "src/models/category.rs", "rank": 76, "score": 6.883381235141501 }, { "content": "\n\n fn handle(&mut self, finder: DeleteCategory, _: &mut Self::Context) -> Self::Result {\n\n Category::delete(&self.connection()?, finder.0)\n\n }\n\n}\n\n\n\n#[derive(AsChangeset, Deserialize)]\n\n#[table_name = \"categories\"]\n\npub struct UpdateCategory {\n\n pub name: Option<String>,\n\n pub display_name: Option<String>,\n\n pub description: Option<String>,\n\n pub sort: Option<i16>,\n\n}\n\n\n\nimpl Message for UpdateByID<UpdateCategory> {\n\n type Result = Result<Option<CategoryFullDisplay>>;\n\n}\n\n\n\nimpl Handler<UpdateByID<UpdateCategory>> for DatabaseExecutor {\n", "file_path": "src/models/category.rs", "rank": 77, "score": 6.744896212942711 }, { "content": " pub name: Option<String>,\n\n pub title: String,\n\n pub keywords: String,\n\n pub description: String,\n\n pub sort: i16,\n\n}\n\n\n\n#[derive(Deserialize, AsChangeset, Debug)]\n\n#[table_name = \"subjects\"]\n\npub struct UpdateSubject {\n\n pub name: Option<String>,\n\n pub title: Option<String>,\n\n pub keywords: Option<String>,\n\n pub description: Option<String>,\n\n pub sort: Option<i16>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Queryable)]\n\npub struct SubjectDisplay {\n\n pub id: u32,\n", "file_path": "src/models/subject.rs", "rank": 79, "score": 6.637769540290594 }, { "content": " keywords -> Varchar,\n\n description -> Varchar,\n\n sort -> Smallint,\n\n content_type -> Unsigned<Smallint>,\n\n content -> Nullable<Mediumtext>,\n\n display -> Bool,\n\n published_at -> Nullable<Timestamp>,\n\n modified_at -> Nullable<Timestamp>,\n\n created_at -> Timestamp,\n\n updated_at -> Nullable<Timestamp>,\n\n }\n\n}\n\n\n\ntable! {\n\n push_messages (id) {\n\n id -> Unsigned<Integer>,\n\n content -> Varchar,\n\n sort -> Smallint,\n\n created_at -> Timestamp,\n\n updated_at -> Nullable<Timestamp>,\n", "file_path": "src/schema.rs", "rank": 80, "score": 6.564037706423671 }, { "content": " }\n\n}\n\n\n\ntable! {\n\n recommend_contents (id) {\n\n id -> Unsigned<Integer>,\n\n content_id -> Nullable<Unsigned<Integer>>,\n\n source -> Varchar,\n\n title -> Varchar,\n\n summary -> Varchar,\n\n created_at -> Timestamp,\n\n updated_at -> Nullable<Timestamp>,\n\n }\n\n}\n\n\n\ntable! {\n\n subjects (id) {\n\n id -> Unsigned<Integer>,\n\n name -> Nullable<Varchar>,\n\n title -> Varchar,\n", "file_path": "src/schema.rs", "rank": 81, "score": 6.338395229310613 }, { "content": "use actix_web::{Scope, http::Method, HttpRequest, FromRequest};\n\n\n\nuse state::AppState;\n\nuse controllers::blog;\n\n\n", "file_path": "src/routes/blog.rs", "rank": 82, "score": 6.162324658306051 }, { "content": "use super::Content;\n\n\n\nuse std::rc::Rc;\n\nuse std::sync::Arc;\n\nuse std::result::Result as StdResult;\n\nuse chrono::NaiveDateTime;\n\nuse futures::future::{Future, ok as FutOk, err as FutErr};\n\nuse actix_web::{HttpRequest, HttpResponse, Responder, AsyncResponder, HttpMessage, error::Error as ActixError};\n\nuse actix_web::fs::NamedFile;\n\nuse comrak::{markdown_to_html, ComrakOptions};\n\nuse tera::Context;\n\nuse regex;\n\n\n\nuse result::Result;\n\nuse state::AppState;\n\nuse message::{Pagination, PaginatedListMessage};\n\nuse models::content::{self, FindFilter};\n\nuse template::{get_global_context, TEMPLATES};\n\nuse error::{Error, error_handler};\n\n\n", "file_path": "src/controllers/blog/content.rs", "rank": 83, "score": 6.1567853717402965 }, { "content": "table! {\n\n categories (id) {\n\n id -> Unsigned<Integer>,\n\n name -> Varchar,\n\n display_name -> Varchar,\n\n keywords -> Varchar,\n\n description -> Varchar,\n\n sort -> Smallint,\n\n created_at -> Timestamp,\n\n updated_at -> Nullable<Timestamp>,\n\n }\n\n}\n\n\n\ntable! {\n\n contents (id) {\n\n id -> Unsigned<Integer>,\n\n name -> Nullable<Varchar>,\n\n title -> Varchar,\n\n category_id -> Nullable<Unsigned<Integer>>,\n\n as_page -> Bool,\n", "file_path": "src/schema.rs", "rank": 84, "score": 6.134093926523832 }, { "content": "use std::rc::Rc;\n\nuse actix_web::{HttpRequest, HttpResponse, AsyncResponder, Responder, HttpMessage};\n\nuse actix_web::http;\n\nuse futures::future::Future;\n\nuse rss::{ChannelBuilder, Channel, Item, ItemBuilder};\n\nuse url::Url;\n\nuse comrak::{markdown_to_html, ComrakOptions};\n\n\n\nuse state::AppState;\n\nuse message::{Pagination, PaginatedListMessage};\n\nuse template::get_site_setting;\n\nuse error::{Error, error_handler};\n\nuse models::content;\n\n\n", "file_path": "src/controllers/blog/rss.rs", "rank": 85, "score": 6.06100588614272 }, { "content": "use super::PushMessage;\n\n\n\nuse std::rc::Rc;\n\nuse futures::future::{Future, ok as FutOk, err as FutErr};\n\nuse actix_web::{HttpRequest, HttpResponse, Responder, AsyncResponder, HttpMessage, error::Error as ActixError};\n\nuse tera::Context;\n\n\n\nuse message::{Pagination, PaginatedListMessage};\n\nuse models::push_message;\n\nuse state::AppState;\n\nuse template::{get_global_context, TEMPLATES};\n\nuse error::error_handler;\n\n\n", "file_path": "src/controllers/blog/push_message.rs", "rank": 86, "score": 6.03577134626952 }, { "content": "use actix_web::{Scope, http::Method, HttpRequest, FromRequest};\n\n\n\nuse state::AppState;\n\nuse controllers::admin;\n\nuse middlewares::authenticate::Authenticate as MAuthenticate;\n\n\n", "file_path": "src/routes/admin.rs", "rank": 87, "score": 6.009748435205569 }, { "content": " keywords -> Varchar,\n\n description -> Varchar,\n\n sort -> Smallint,\n\n created_at -> Timestamp,\n\n updated_at -> Nullable<Timestamp>,\n\n }\n\n}\n\n\n\ntable! {\n\n subject_relates (subject_id, content_id) {\n\n subject_id -> Unsigned<Integer>,\n\n content_id -> Unsigned<Integer>,\n\n sort -> Smallint,\n\n created_at -> Timestamp,\n\n updated_at -> Nullable<Timestamp>,\n\n }\n\n}\n\n\n\nallow_tables_to_appear_in_same_query!(\n\n categories,\n\n contents,\n\n push_messages,\n\n recommend_contents,\n\n subjects,\n\n subject_relates,\n\n);\n", "file_path": "src/schema.rs", "rank": 88, "score": 5.779652299930901 }, { "content": "use std::rc::Rc;\n\nuse actix_web::{HttpRequest, HttpResponse, AsyncResponder, Responder, HttpMessage};\n\n\n\nuse state::AppState;\n\nuse models::content;\n\n\n\n#[derive(Deserialize, Debug, Clone)]\n", "file_path": "src/controllers/admin/content.rs", "rank": 89, "score": 5.774222966805732 }, { "content": " NotZero,\n\n Index(FindCategory),\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct GetContents {\n\n pub search: Option<String>,\n\n pub category: Option<CategoryMatcher>,\n\n pub display: Option<bool>,\n\n pub content_type: Option<u16>,\n\n}\n\n\n\nimpl Default for GetContents {\n\n fn default() -> Self {\n\n GetContents {\n\n search: None,\n\n category: None,\n\n display: Some(true),\n\n content_type: None,\n\n }\n", "file_path": "src/models/content.rs", "rank": 90, "score": 5.765217495568928 }, { "content": " pub fn get_recommend_contents(connection: &Conn, count: Option<u32>) -> Result<Vec<RecommendContentDisplay>> {\n\n use schema::recommend_contents::dsl::*;\n\n\n\n recommend_contents\n\n .order((created_at.desc(), id.desc()))\n\n .limit(count.map(From::from).unwrap_or(3))\n\n .load::<RecommendContentDisplay>(connection)\n\n .map_err(map_database_error(Some(\"recommend_contents\")))\n\n }\n\n}\n\n\n\n#[derive(Default)]\n\npub struct GetRecommendContents(pub Option<u32>);\n\n\n\nimpl Message for GetRecommendContents {\n\n type Result = Result<Vec<RecommendContentDisplay>>;\n\n}\n\n\n\nimpl Handler<GetRecommendContents> for DatabaseExecutor {\n\n type Result = <GetRecommendContents as Message>::Result;\n\n\n\n fn handle(&mut self, msg: GetRecommendContents, _: &mut Self::Context) -> <Self as Handler<GetRecommendContents>>::Result {\n\n RecommendContent::get_recommend_contents(&self.connection()?, msg.0)\n\n }\n\n}", "file_path": "src/models/recommend.rs", "rank": 91, "score": 5.596978372349168 }, { "content": " pub static_assets_path: Arc<Option<String>>,\n\n pub public_path: Arc<Option<String>>,\n\n /// 通过该字段对数据库进行访问以及操作\n\n pub database: Addr<DatabaseExecutor>,\n\n}\n\n\n\nimpl AppState {\n\n pub fn new(config: Config) -> Self {\n\n let timezone = config.database_timezone;\n\n let manager = ConnectionManager::<MysqlConnection>::new(config.database_url);\n\n let pool = Pool::builder().build(manager).expect(\"Error: Failed to build pool\");\n\n\n\n let addr = SyncArbiter::start(8, move || {\n\n let cloned = pool.clone();\n\n let connection = &cloned.get().expect(\"Error: Connection initialize error.\");\n\n let timezone = timezone.clone();\n\n\n\n if let Some(timezone) = timezone {\n\n sql_query(format!(\"set time_zone='{}'\", timezone))\n\n .execute(connection)\n", "file_path": "src/state.rs", "rank": 92, "score": 5.582452705505543 }, { "content": "pub struct FindFilter {\n\n pub as_page: Option<bool>\n\n}\n\n\n\npub struct FindContent {\n\n pub inner: Find,\n\n pub filter: Option<FindFilter>\n\n}\n\n\n\nimpl Message for FindContent {\n\n type Result = Result<ContentFullDisplay>;\n\n}\n\n\n\nimpl Handler<FindContent> for DatabaseExecutor {\n\n type Result = <FindContent as Message>::Result;\n\n\n\n fn handle(&mut self, msg: FindContent, _: &mut Self::Context) -> Self::Result {\n\n match msg.inner {\n\n Find::ByName(name) => Content::find_by_name(&self.connection()?, name, msg.filter),\n\n Find::ById(id) => Content::find_by_id(&self.connection()?, id, msg.filter)\n\n }\n\n }\n\n}\n\n\n\npub struct CreateContent {\n\n\n\n}", "file_path": "src/models/content.rs", "rank": 93, "score": 5.547491779101183 }, { "content": " pub id: u32,\n\n pub name: String,\n\n pub display_name: String,\n\n pub description: String,\n\n pub created_at: NaiveDateTime,\n\n pub updated_at: Option<NaiveDateTime>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Queryable)]\n\npub struct CategoryFullDisplay {\n\n pub id: u32,\n\n pub name: String,\n\n pub display_name: String,\n\n pub keywords: String,\n\n pub description: String,\n\n pub sort: i16,\n\n pub created_at: NaiveDateTime,\n\n pub updated_at: Option<NaiveDateTime>,\n\n}\n\n\n", "file_path": "src/models/category.rs", "rank": 94, "score": 5.539897949014887 }, { "content": " }\n\n },\n\n Err(_) => SiteSetting::default()\n\n }\n\n }\n\n\n\n pub fn get_global_context() -> Context {\n\n let mut context = Context::new();\n\n let setting: SiteSetting = get_site_setting();\n\n\n\n context.add(\"__site_setting\", &setting);\n\n context\n\n }\n\n}\n\n\n\npub mod state;\n\npub mod routes;\n\npub mod utils;\n\n\n\npub mod result {\n\n use std::result::Result as StdResult;\n\n use error::Error;\n\n\n\n pub type Result<T> = StdResult<T, Error>;\n\n}", "file_path": "src/lib.rs", "rank": 95, "score": 5.374491715604766 }, { "content": "use super::{PushMessage, Content};\n\n\n\nuse std::rc::Rc;\n\nuse futures::future::{Future, ok as FutOk, err as FutErr};\n\nuse actix_web::{HttpRequest, HttpResponse, Responder, AsyncResponder, HttpMessage};\n\nuse comrak::{markdown_to_html, ComrakOptions};\n\nuse tera::Context;\n\n\n\nuse state::AppState;\n\nuse message::Pagination;\n\nuse models::{push_message, content, recommend};\n\nuse template::{get_global_context, TEMPLATES};\n\nuse error::error_handler;\n\n\n", "file_path": "src/controllers/blog/index.rs", "rank": 96, "score": 5.259538809924145 }, { "content": " connection.transaction(move || {\n\n diesel::delete(subject_relates)\n\n .filter(\n\n subject_id.eq(target).and(content_id.ne_all(key_index))\n\n )\n\n .execute(connection)\n\n .map_err(map_database_error(Some(\"subject_relates\")))?;\n\n\n\n let mut create_relates = Vec::with_capacity(sync.len());\n\n for relate in sync {\n\n create_relates.push(\n\n (subject_id.eq(target), content_id.eq(relate.content_id), sort.eq(relate.sort.unwrap_or(0)))\n\n );\n\n }\n\n\n\n if create_relates.len() > 0 {\n\n diesel::replace_into(subject_relates)\n\n .values(&create_relates)\n\n .execute(connection)\n\n .map_err(map_database_error(Some(\"subject_relates\")))?;\n", "file_path": "src/models/subject.rs", "rank": 97, "score": 5.2332914790169 }, { "content": " pub name: Option<String>,\n\n pub title: String,\n\n pub keywords: String,\n\n pub description: String,\n\n pub sort: i16,\n\n pub created_at: NaiveDateTime,\n\n pub updated_at: Option<NaiveDateTime>,\n\n}\n\n\n\npub struct SubjectRelate {\n\n pub content_id: u32,\n\n pub sort: Option<i16>,\n\n}\n\n\n\npub struct CreateSubject {\n\n pub subject: NewSubject,\n\n pub relates: Option<Vec<SubjectRelate>>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Queryable)]\n", "file_path": "src/models/subject.rs", "rank": 98, "score": 4.92040375484316 } ]
Rust
src/rocksdb_options.rs
susytech/susy-rocksdb
2ca57972fb6661863c72c1bf8549d63122305be6
extern crate libc; use self::libc::{c_int, size_t}; use std::ffi::CString; use std::mem; use rocksdb_ffi; use merge_operator::{self, MergeOperands, MergeOperatorCallback, full_merge_callback, partial_merge_callback}; use comparator::{self, ComparatorCallback, compare_callback}; pub enum IndexType { BinarySearch, HashSearch, } pub struct BlockBasedOptions { inner: rocksdb_ffi::DBBlockBasedTableOptions, filter: Option<rocksdb_ffi::DBFilterPolicy>, } pub struct Options { pub inner: rocksdb_ffi::DBOptions, } pub struct WriteOptions { pub inner: rocksdb_ffi::DBWriteOptions, } pub struct Cache { pub inner: rocksdb_ffi::DBCache, } impl Drop for Options { fn drop(&mut self) { unsafe { rocksdb_ffi::rocksdb_options_destroy(self.inner); } } } impl Drop for BlockBasedOptions { fn drop(&mut self) { unsafe { rocksdb_ffi::rocksdb_block_based_options_destroy(self.inner); } } } impl Drop for WriteOptions { fn drop(&mut self) { unsafe { rocksdb_ffi::rocksdb_writeoptions_destroy(self.inner); } } } impl BlockBasedOptions { pub fn new() -> BlockBasedOptions { let block_opts = unsafe { rocksdb_ffi::rocksdb_block_based_options_create() }; if block_opts.is_null() { panic!("Could not create rocksdb block based options".to_string()); } BlockBasedOptions { inner: block_opts, filter: None } } pub fn set_block_size(&mut self, size: usize) { unsafe { rocksdb_ffi::rocksdb_block_based_options_set_block_size(self.inner, size); } } pub fn set_index_type(&mut self, index_type: IndexType) { let it = match index_type { IndexType::BinarySearch => rocksdb_ffi::BLOCK_BASED_INDEX_TYPE_BINARY_SEARCH, IndexType::HashSearch => rocksdb_ffi::BLOCK_BASED_INDEX_TYPE_HASH_SEARCH, }; unsafe { rocksdb_ffi::rocksdb_block_based_options_set_index_type(self.inner, it); } } pub fn set_cache(&mut self, cache: Cache) { unsafe { rocksdb_ffi::rocksdb_block_based_options_set_block_cache(self.inner, cache.inner); } } pub fn set_filter(&mut self, bits: i32) { unsafe { let new_filter = rocksdb_ffi::rocksdb_filterpolicy_create_bloom(bits); rocksdb_ffi::rocksdb_block_based_options_set_filter_policy(self.inner, new_filter); self.filter = Some(new_filter); } } } unsafe impl Sync for BlockBasedOptions {} unsafe impl Send for BlockBasedOptions {} impl Options { pub fn new() -> Options { unsafe { let opts = rocksdb_ffi::rocksdb_options_create(); if opts.is_null() { panic!("Could not create rocksdb options".to_string()); } Options { inner: opts } } } pub fn increase_parallelism(&mut self, parallelism: i32) { unsafe { rocksdb_ffi::rocksdb_options_increase_parallelism(self.inner, parallelism); } } pub fn optimize_level_style_compaction(&mut self, memtable_memory_budget: i32) { unsafe { rocksdb_ffi::rocksdb_options_optimize_level_style_compaction( self.inner, memtable_memory_budget); } } pub fn create_if_missing(&mut self, create_if_missing: bool) { unsafe { rocksdb_ffi::rocksdb_options_set_create_if_missing( self.inner, create_if_missing); } } pub fn add_merge_operator<'a>(&mut self, name: &str, merge_fn: fn(&[u8], Option<&[u8]>, &mut MergeOperands) -> Vec<u8>) { let cb = Box::new(MergeOperatorCallback { name: CString::new(name.as_bytes()).unwrap(), merge_fn: merge_fn, }); unsafe { let mo = rocksdb_ffi::rocksdb_mergeoperator_create( mem::transmute(cb), merge_operator::destructor_callback, full_merge_callback, partial_merge_callback, None, merge_operator::name_callback); rocksdb_ffi::rocksdb_options_set_merge_operator(self.inner, mo); } } pub fn add_comparator<'a>(&mut self, name: &str, compare_fn: fn(&[u8], &[u8]) -> i32) { let cb = Box::new(ComparatorCallback { name: CString::new(name.as_bytes()).unwrap(), f: compare_fn, }); unsafe { let cmp = rocksdb_ffi::rocksdb_comparator_create( mem::transmute(cb), comparator::destructor_callback, compare_callback, comparator::name_callback); rocksdb_ffi::rocksdb_options_set_comparator(self.inner, cmp); } } pub fn set_prefix_extractor_fixed_size<'a>(&mut self, size: usize) { unsafe { let st = rocksdb_ffi::rocksdb_slicetransform_create_fixed_prefix(size); rocksdb_ffi::rocksdb_options_set_prefix_extractor(self.inner, st); } } pub fn set_block_cache_size_mb(&mut self, cache_size: u64) { unsafe { rocksdb_ffi::rocksdb_options_optimize_for_point_lookup(self.inner, cache_size); } } pub fn set_max_open_files(&mut self, nfiles: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_max_open_files(self.inner, nfiles); } } pub fn set_use_fsync(&mut self, useit: bool) { unsafe { match useit { true => { rocksdb_ffi::rocksdb_options_set_use_fsync(self.inner, 1) } false => { rocksdb_ffi::rocksdb_options_set_use_fsync(self.inner, 0) } } } } pub fn set_bytes_per_sync(&mut self, nbytes: u64) { unsafe { rocksdb_ffi::rocksdb_options_set_bytes_per_sync(self.inner, nbytes); } } pub fn set_table_cache_num_shard_bits(&mut self, nbits: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_table_cache_numshardbits(self.inner, nbits); } } pub fn set_min_write_buffer_number(&mut self, nbuf: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_min_write_buffer_number_to_merge( self.inner, nbuf); } } pub fn set_max_write_buffer_number(&mut self, nbuf: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_max_write_buffer_number(self.inner, nbuf); } } pub fn set_write_buffer_size(&mut self, size: size_t) { unsafe { rocksdb_ffi::rocksdb_options_set_write_buffer_size(self.inner, size); } } pub fn set_db_write_buffer_size(&mut self, size: size_t) { unsafe { rocksdb_ffi::rocksdb_options_set_db_write_buffer_size(self.inner, size); } } pub fn set_target_file_size_base(&mut self, size: u64) { unsafe { rocksdb_ffi::rocksdb_options_set_target_file_size_base(self.inner, size); } } pub fn set_target_file_size_multiplier(&mut self, size: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_target_file_size_multiplier(self.inner, size); } } pub fn set_min_write_buffer_number_to_merge(&mut self, to_merge: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_min_write_buffer_number_to_merge( self.inner, to_merge); } } pub fn set_level_zero_slowdown_writes_trigger(&mut self, n: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_level0_slowdown_writes_trigger( self.inner, n); } } pub fn set_level_zero_stop_writes_trigger(&mut self, n: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_level0_stop_writes_trigger( self.inner, n); } } pub fn set_compaction_style(&mut self, style: rocksdb_ffi::DBCompactionStyle) { unsafe { rocksdb_ffi::rocksdb_options_set_compaction_style(self.inner, style); } } pub fn set_max_background_compactions(&mut self, n: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_max_background_compactions( self.inner, n); } } pub fn set_max_background_flushes(&mut self, n: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_max_background_flushes(self.inner, n); } } pub fn set_disable_auto_compactions(&mut self, disable: bool) { unsafe { match disable { true => rocksdb_ffi::rocksdb_options_set_disable_auto_compactions( self.inner, 1), false => rocksdb_ffi::rocksdb_options_set_disable_auto_compactions( self.inner, 0), } } } pub fn set_block_based_table_factory(&mut self, factory: &BlockBasedOptions) { unsafe { rocksdb_ffi::rocksdb_options_set_block_based_table_factory(self.inner, factory.inner); } } pub fn set_parsed_options(&mut self, opts: &str) -> Result<(), String> { unsafe { let new_inner_options = rocksdb_ffi::rocksdb_options_create(); if new_inner_options.is_null() { panic!("Could not create rocksdb options".to_string()); } let mut err: *const i8 = 0 as *const i8; let err_ptr: *mut *const i8 = &mut err; let c_opts = CString::new(opts.as_bytes()).unwrap(); let c_opts_ptr = c_opts.as_ptr(); rocksdb_ffi::rocksdb_get_options_from_string(self.inner, c_opts_ptr as *const _, new_inner_options, err_ptr); if !err.is_null() { return Err(rocksdb_ffi::error_message(err)) } rocksdb_ffi::rocksdb_options_destroy(mem::replace(&mut self.inner, new_inner_options)); Ok(()) } } } impl WriteOptions { pub fn new() -> WriteOptions { let write_opts = unsafe { rocksdb_ffi::rocksdb_writeoptions_create() }; if write_opts.is_null() { panic!("Could not create rocksdb write options".to_string()); } WriteOptions { inner: write_opts } } pub fn set_sync(&mut self, sync: bool) { unsafe { rocksdb_ffi::rocksdb_writeoptions_set_sync(self.inner, sync); } } pub fn disable_wal(&mut self, disable: bool) { unsafe { if disable { rocksdb_ffi::rocksdb_writeoptions_disable_WAL(self.inner, 1); } else { rocksdb_ffi::rocksdb_writeoptions_disable_WAL(self.inner, 0); } } } } unsafe impl Sync for WriteOptions {} unsafe impl Send for WriteOptions {} impl Cache { pub fn new(bytes: usize) -> Cache { Cache { inner: unsafe { rocksdb_ffi::rocksdb_cache_create_lru(bytes) } } } } impl Drop for Cache { fn drop(&mut self) { unsafe { rocksdb_ffi::rocksdb_cache_destroy(self.inner); } } } unsafe impl Sync for Cache {} unsafe impl Send for Cache {}
extern crate libc; use self::libc::{c_int, size_t}; use std::ffi::CString; use std::mem; use rocksdb_ffi; use merge_operator::{self, MergeOperands, MergeOperatorCallback, full_merge_callback, partial_merge_callback}; use comparator::{self, ComparatorCallback, compare_callback}; pub enum IndexType { BinarySearch, HashSearch, } pub struct BlockBasedOptions { inner: rocksdb_ffi::DBBlockBasedTableOptions, filter: Option<rocksdb_ffi::DBFilterPolicy>, } pub struct Options { pub inner: rocksdb_ffi::DBOptions, } pub struct WriteOptions { pub inner: rocksdb_ffi::DBWriteOptions, } pub struct Cache { pub inner: rocksdb_ffi::DBCache, } impl Drop for Options { fn drop(&mut self) { unsafe { rocksdb_ffi::rocksdb_options_destroy(self.inner); } } } impl Drop for BlockBasedOptions { fn drop(&mut self) { unsafe { rocksdb_ffi::rocksdb_block_based_options_destroy(self.inner); } } } impl Drop for WriteOptions { fn drop(&mut self) { unsafe { rocksdb_ffi::rocksdb_writeoptions_destroy(self.inner); } } } impl BlockBasedOptions {
pub fn set_block_size(&mut self, size: usize) { unsafe { rocksdb_ffi::rocksdb_block_based_options_set_block_size(self.inner, size); } } pub fn set_index_type(&mut self, index_type: IndexType) { let it = match index_type { IndexType::BinarySearch => rocksdb_ffi::BLOCK_BASED_INDEX_TYPE_BINARY_SEARCH, IndexType::HashSearch => rocksdb_ffi::BLOCK_BASED_INDEX_TYPE_HASH_SEARCH, }; unsafe { rocksdb_ffi::rocksdb_block_based_options_set_index_type(self.inner, it); } } pub fn set_cache(&mut self, cache: Cache) { unsafe { rocksdb_ffi::rocksdb_block_based_options_set_block_cache(self.inner, cache.inner); } } pub fn set_filter(&mut self, bits: i32) { unsafe { let new_filter = rocksdb_ffi::rocksdb_filterpolicy_create_bloom(bits); rocksdb_ffi::rocksdb_block_based_options_set_filter_policy(self.inner, new_filter); self.filter = Some(new_filter); } } } unsafe impl Sync for BlockBasedOptions {} unsafe impl Send for BlockBasedOptions {} impl Options { pub fn new() -> Options { unsafe { let opts = rocksdb_ffi::rocksdb_options_create(); if opts.is_null() { panic!("Could not create rocksdb options".to_string()); } Options { inner: opts } } } pub fn increase_parallelism(&mut self, parallelism: i32) { unsafe { rocksdb_ffi::rocksdb_options_increase_parallelism(self.inner, parallelism); } } pub fn optimize_level_style_compaction(&mut self, memtable_memory_budget: i32) { unsafe { rocksdb_ffi::rocksdb_options_optimize_level_style_compaction( self.inner, memtable_memory_budget); } } pub fn create_if_missing(&mut self, create_if_missing: bool) { unsafe { rocksdb_ffi::rocksdb_options_set_create_if_missing( self.inner, create_if_missing); } } pub fn add_merge_operator<'a>(&mut self, name: &str, merge_fn: fn(&[u8], Option<&[u8]>, &mut MergeOperands) -> Vec<u8>) { let cb = Box::new(MergeOperatorCallback { name: CString::new(name.as_bytes()).unwrap(), merge_fn: merge_fn, }); unsafe { let mo = rocksdb_ffi::rocksdb_mergeoperator_create( mem::transmute(cb), merge_operator::destructor_callback, full_merge_callback, partial_merge_callback, None, merge_operator::name_callback); rocksdb_ffi::rocksdb_options_set_merge_operator(self.inner, mo); } } pub fn add_comparator<'a>(&mut self, name: &str, compare_fn: fn(&[u8], &[u8]) -> i32) { let cb = Box::new(ComparatorCallback { name: CString::new(name.as_bytes()).unwrap(), f: compare_fn, }); unsafe { let cmp = rocksdb_ffi::rocksdb_comparator_create( mem::transmute(cb), comparator::destructor_callback, compare_callback, comparator::name_callback); rocksdb_ffi::rocksdb_options_set_comparator(self.inner, cmp); } } pub fn set_prefix_extractor_fixed_size<'a>(&mut self, size: usize) { unsafe { let st = rocksdb_ffi::rocksdb_slicetransform_create_fixed_prefix(size); rocksdb_ffi::rocksdb_options_set_prefix_extractor(self.inner, st); } } pub fn set_block_cache_size_mb(&mut self, cache_size: u64) { unsafe { rocksdb_ffi::rocksdb_options_optimize_for_point_lookup(self.inner, cache_size); } } pub fn set_max_open_files(&mut self, nfiles: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_max_open_files(self.inner, nfiles); } } pub fn set_use_fsync(&mut self, useit: bool) { unsafe { match useit { true => { rocksdb_ffi::rocksdb_options_set_use_fsync(self.inner, 1) } false => { rocksdb_ffi::rocksdb_options_set_use_fsync(self.inner, 0) } } } } pub fn set_bytes_per_sync(&mut self, nbytes: u64) { unsafe { rocksdb_ffi::rocksdb_options_set_bytes_per_sync(self.inner, nbytes); } } pub fn set_table_cache_num_shard_bits(&mut self, nbits: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_table_cache_numshardbits(self.inner, nbits); } } pub fn set_min_write_buffer_number(&mut self, nbuf: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_min_write_buffer_number_to_merge( self.inner, nbuf); } } pub fn set_max_write_buffer_number(&mut self, nbuf: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_max_write_buffer_number(self.inner, nbuf); } } pub fn set_write_buffer_size(&mut self, size: size_t) { unsafe { rocksdb_ffi::rocksdb_options_set_write_buffer_size(self.inner, size); } } pub fn set_db_write_buffer_size(&mut self, size: size_t) { unsafe { rocksdb_ffi::rocksdb_options_set_db_write_buffer_size(self.inner, size); } } pub fn set_target_file_size_base(&mut self, size: u64) { unsafe { rocksdb_ffi::rocksdb_options_set_target_file_size_base(self.inner, size); } } pub fn set_target_file_size_multiplier(&mut self, size: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_target_file_size_multiplier(self.inner, size); } } pub fn set_min_write_buffer_number_to_merge(&mut self, to_merge: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_min_write_buffer_number_to_merge( self.inner, to_merge); } } pub fn set_level_zero_slowdown_writes_trigger(&mut self, n: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_level0_slowdown_writes_trigger( self.inner, n); } } pub fn set_level_zero_stop_writes_trigger(&mut self, n: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_level0_stop_writes_trigger( self.inner, n); } } pub fn set_compaction_style(&mut self, style: rocksdb_ffi::DBCompactionStyle) { unsafe { rocksdb_ffi::rocksdb_options_set_compaction_style(self.inner, style); } } pub fn set_max_background_compactions(&mut self, n: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_max_background_compactions( self.inner, n); } } pub fn set_max_background_flushes(&mut self, n: c_int) { unsafe { rocksdb_ffi::rocksdb_options_set_max_background_flushes(self.inner, n); } } pub fn set_disable_auto_compactions(&mut self, disable: bool) { unsafe { match disable { true => rocksdb_ffi::rocksdb_options_set_disable_auto_compactions( self.inner, 1), false => rocksdb_ffi::rocksdb_options_set_disable_auto_compactions( self.inner, 0), } } } pub fn set_block_based_table_factory(&mut self, factory: &BlockBasedOptions) { unsafe { rocksdb_ffi::rocksdb_options_set_block_based_table_factory(self.inner, factory.inner); } } pub fn set_parsed_options(&mut self, opts: &str) -> Result<(), String> { unsafe { let new_inner_options = rocksdb_ffi::rocksdb_options_create(); if new_inner_options.is_null() { panic!("Could not create rocksdb options".to_string()); } let mut err: *const i8 = 0 as *const i8; let err_ptr: *mut *const i8 = &mut err; let c_opts = CString::new(opts.as_bytes()).unwrap(); let c_opts_ptr = c_opts.as_ptr(); rocksdb_ffi::rocksdb_get_options_from_string(self.inner, c_opts_ptr as *const _, new_inner_options, err_ptr); if !err.is_null() { return Err(rocksdb_ffi::error_message(err)) } rocksdb_ffi::rocksdb_options_destroy(mem::replace(&mut self.inner, new_inner_options)); Ok(()) } } } impl WriteOptions { pub fn new() -> WriteOptions { let write_opts = unsafe { rocksdb_ffi::rocksdb_writeoptions_create() }; if write_opts.is_null() { panic!("Could not create rocksdb write options".to_string()); } WriteOptions { inner: write_opts } } pub fn set_sync(&mut self, sync: bool) { unsafe { rocksdb_ffi::rocksdb_writeoptions_set_sync(self.inner, sync); } } pub fn disable_wal(&mut self, disable: bool) { unsafe { if disable { rocksdb_ffi::rocksdb_writeoptions_disable_WAL(self.inner, 1); } else { rocksdb_ffi::rocksdb_writeoptions_disable_WAL(self.inner, 0); } } } } unsafe impl Sync for WriteOptions {} unsafe impl Send for WriteOptions {} impl Cache { pub fn new(bytes: usize) -> Cache { Cache { inner: unsafe { rocksdb_ffi::rocksdb_cache_create_lru(bytes) } } } } impl Drop for Cache { fn drop(&mut self) { unsafe { rocksdb_ffi::rocksdb_cache_destroy(self.inner); } } } unsafe impl Sync for Cache {} unsafe impl Send for Cache {}
pub fn new() -> BlockBasedOptions { let block_opts = unsafe { rocksdb_ffi::rocksdb_block_based_options_create() }; if block_opts.is_null() { panic!("Could not create rocksdb block based options".to_string()); } BlockBasedOptions { inner: block_opts, filter: None } }
function_block-full_function
[ { "content": "pub fn new_cache(capacity: size_t) -> DBCache {\n\n unsafe { rocksdb_cache_create_lru(capacity) }\n\n}\n\n\n\n#[repr(C)]\n\npub enum DBCompressionType {\n\n DBNoCompression = 0,\n\n DBSnappyCompression = 1,\n\n DBZlibCompression = 2,\n\n DBBz2Compression = 3,\n\n DBLz4Compression = 4,\n\n DBLz4hcCompression = 5,\n\n}\n\n\n\n#[repr(C)]\n\npub enum DBCompactionStyle {\n\n DBLevelCompaction = 0,\n\n DBUniversalCompaction = 1,\n\n DBFifoCompaction = 2,\n\n}\n\n\n\n#[repr(C)]\n\npub enum DBUniversalCompactionStyle {\n\n rocksdb_similar_size_compaction_stop_style = 0,\n\n rocksdb_total_size_compaction_stop_style = 1,\n\n}\n\n\n", "file_path": "susy-rocksdb-sys/src/ffi.rs", "rank": 0, "score": 266092.27223118604 }, { "content": "struct LRUCacheOptions {\n\n // Capacity of the cache.\n\n size_t capacity = 0;\n\n\n\n // Cache is sharded into 2^num_shard_bits shards,\n\n // by hash of key. Refer to NewLRUCache for further\n\n // information.\n\n int num_shard_bits = -1;\n\n\n\n // If strict_capacity_limit is set,\n\n // insert to the cache will fail when cache is full.\n\n bool strict_capacity_limit = false;\n\n\n\n // Percentage of cache reserved for high priority entries.\n\n double high_pri_pool_ratio = 0.0;\n\n\n\n LRUCacheOptions() {}\n\n LRUCacheOptions(size_t _capacity, int _num_shard_bits,\n\n bool _strict_capacity_limit, double _high_pri_pool_ratio)\n\n : capacity(_capacity),\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/cache.h", "rank": 1, "score": 240588.95682970548 }, { "content": "// IngestExternalFileOptions is used by IngestExternalFile()\n\nstruct IngestExternalFileOptions {\n\n // Can be set to true to move the files instead of copying them.\n\n bool move_files = false;\n\n // If set to false, an ingested file keys could appear in existing snapshots\n\n // that where created before the file was ingested.\n\n bool snapshot_consistency = true;\n\n // If set to false, IngestExternalFile() will fail if the file key range\n\n // overlaps with existing keys or tombstones in the DB.\n\n bool allow_global_seqno = true;\n\n // If set to false and the file key range overlaps with the memtable key range\n\n // (memtable flush required), IngestExternalFile will fail.\n\n bool allow_blocking_flush = true;\n\n // Set to true if you would like duplicate keys in the file being ingested\n\n // to be skipped rather than overwriting existing data under that key.\n\n // Usecase: back-fill of some historical data in the database without\n\n // over-writing existing newer version of data.\n\n // This option could only be used if the DB has been running\n\n // with allow_ingest_behind=true since the dawn of time.\n\n // All files will be ingested at the bottommost level with seqno=0.\n\n bool ingest_behind = false;\n\n};\n\n\n\n} // namespace rocksdb\n\n\n\n#endif // STORAGE_ROCKSDB_INCLUDE_OPTIONS_H_\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/options.h", "rank": 2, "score": 237424.15602121002 }, { "content": "pub fn new_bloom_filter(bits: c_int) -> DBFilterPolicy {\n\n unsafe { rocksdb_filterpolicy_create_bloom(bits) }\n\n}\n\n\n", "file_path": "susy-rocksdb-sys/src/ffi.rs", "rank": 3, "score": 234741.7334280406 }, { "content": "struct ExternalSstFileInfo;\n", "file_path": "susy-rocksdb-sys/rocksdb/db/db_impl.h", "rank": 4, "score": 223263.91375849393 }, { "content": "struct RocksLuaCompactionFilterOptions {\n\n // The lua script in string that implements all necessary CompactionFilter\n\n // virtual functions. The specified lua_script must implement the following\n\n // functions, which are Name and Filter, as described below.\n\n //\n\n // 0. The Name function simply returns a string representing the name of\n\n // the lua script. If there's any erorr in the Name function, an\n\n // empty string will be used.\n\n // --- Example\n\n // function Name()\n\n // return \"DefaultLuaCompactionFilter\"\n\n // end\n\n //\n\n //\n\n // 1. The script must contains a function called Filter, which implements\n\n // CompactionFilter::Filter() , takes three input arguments, and returns\n\n // three values as the following API:\n\n //\n\n // function Filter(level, key, existing_value)\n\n // ...\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/utilities/lua/rocks_lua_compaction_filter.h", "rank": 5, "score": 220759.55330205295 }, { "content": " enum class WalProcessingOption {\n\n // Continue processing as usual\n\n kContinueProcessing = 0,\n\n // Ignore the current record but continue processing of log(s)\n\n kIgnoreCurrentRecord = 1,\n\n // Stop replay of logs and discard logs\n\n // Logs won't be replayed on subsequent recovery\n\n kStopReplay = 2,\n\n // Corrupted record detected by filter\n\n kCorruptedRecord = 3,\n\n // Marker for enum count\n\n kWalProcessingOptionMax = 4\n\n };\n\n\n\n virtual ~WalFilter() {}\n\n\n\n // Provide ColumnFamily->LogNumber map to filter\n\n // so that filter can determine whether a log number applies to a given \n\n // column family (i.e. that log hasn't been flushed to SST already for the\n\n // column family).\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/wal_filter.h", "rank": 6, "score": 212987.4931344085 }, { "content": "struct rocksdb_writeoptions_t { WriteOptions rep; };\n", "file_path": "susy-rocksdb-sys/rocksdb/db/c.cc", "rank": 7, "score": 211020.67042703804 }, { "content": "struct ThreadPoolImpl::Impl {\n\n\n\n Impl();\n\n ~Impl();\n\n\n\n void JoinThreads(bool wait_for_jobs_to_complete);\n\n\n\n void SetBackgroundThreadsInternal(int num, bool allow_reduce);\n\n int GetBackgroundThreads();\n\n\n\n unsigned int GetQueueLen() const {\n\n return queue_len_.load(std::memory_order_relaxed);\n\n }\n\n\n\n void LowerIOPriority();\n\n\n\n void LowerCPUPriority();\n\n\n\n void WakeUpAllThreads() {\n\n bgsignal_.notify_all();\n", "file_path": "susy-rocksdb-sys/rocksdb/util/threadpool_imp.cc", "rank": 8, "score": 207365.18188090815 }, { "content": "struct rocksdb_ingestexternalfileoptions_t { IngestExternalFileOptions rep; };\n", "file_path": "susy-rocksdb-sys/rocksdb/db/c.cc", "rank": 9, "score": 204562.45756093747 }, { "content": "// Cache entry meta data.\n\nstruct CacheHandle {\n\n Slice key;\n\n uint32_t hash;\n\n void* value;\n\n size_t charge;\n\n void (*deleter)(const Slice&, void* value);\n\n\n\n // Flags and counters associated with the cache handle:\n\n // lowest bit: n-cache bit\n\n // second lowest bit: usage bit\n\n // the rest bits: reference count\n\n // The handle is unused when flags equals to 0. The thread decreases the count\n\n // to 0 is responsible to put the handle back to recycle_ and cleanup memory.\n\n std::atomic<uint32_t> flags;\n\n\n\n CacheHandle() = default;\n\n\n\n CacheHandle(const CacheHandle& a) { *this = a; }\n\n\n\n CacheHandle(const Slice& k, void* v,\n", "file_path": "susy-rocksdb-sys/rocksdb/cache/clock_cache.cc", "rank": 10, "score": 187179.98409964904 }, { "content": "// Key of hash map. We store hash value with the key for convenience.\n\nstruct CacheKey {\n\n Slice key;\n\n uint32_t hash_value;\n\n\n\n CacheKey() = default;\n\n\n\n CacheKey(const Slice& k, uint32_t h) {\n\n key = k;\n\n hash_value = h;\n\n }\n\n\n\n static bool equal(const CacheKey& a, const CacheKey& b) {\n\n return a.hash_value == b.hash_value && a.key == b.key;\n\n }\n\n\n\n static size_t hash(const CacheKey& a) {\n\n return static_cast<size_t>(a.hash_value);\n\n }\n\n};\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/cache/clock_cache.cc", "rank": 11, "score": 187172.79289240445 }, { "content": "struct Options;\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/options.h", "rank": 12, "score": 183718.45887691664 }, { "content": "struct LRUHandle {\n\n void* value;\n\n void (*deleter)(const Slice&, void* value);\n\n LRUHandle* next_hash;\n\n LRUHandle* next;\n\n LRUHandle* prev;\n\n size_t charge; // TODO(opt): Only allow uint32_t?\n\n size_t key_length;\n\n uint32_t refs; // a number of refs to this entry\n\n // cache itself is counted as 1\n\n\n\n // Include the following flags:\n\n // in_cache: whether this entry is referenced by the hash table.\n\n // is_high_pri: whether this entry is high priority entry.\n\n // in_high_pri_pool: whether this entry is in high-pri pool.\n\n char flags;\n\n\n\n uint32_t hash; // Hash of key(); used for fast sharding and comparisons\n\n\n\n char key_data[1]; // Beginning of key\n", "file_path": "susy-rocksdb-sys/rocksdb/cache/lru_cache.h", "rank": 13, "score": 182581.37388073117 }, { "content": "#[test]\n\nfn external() {\n\n let path = \"_rust_rocksdb_externaltest\";\n\n {\n\n let db = DB::open_default(path).unwrap();\n\n let p = db.put(b\"k1\", b\"v1111\");\n\n assert!(p.is_ok());\n\n let r: Result<Option<DBVector>, String> = db.get(b\"k1\");\n\n assert!(r.unwrap().unwrap().to_utf8().unwrap() == \"v1111\");\n\n assert!(db.delete(b\"k1\").is_ok());\n\n assert!(db.get(b\"k1\").unwrap().is_none());\n\n }\n\n let opts = Options::new();\n\n let result = DB::destroy(&opts, path);\n\n assert!(result.is_ok());\n\n}\n\n\n", "file_path": "src/rocksdb.rs", "rank": 14, "score": 182036.24582243018 }, { "content": "// Persistent Cache Config\n\n//\n\n// This struct captures all the options that are used to configure persistent\n\n// cache. Some of the terminologies used in naming the options are\n\n//\n\n// dispatch size :\n\n// This is the size in which IO is dispatched to the device\n\n//\n\n// write buffer size :\n\n// This is the size of an individual write buffer size. Write buffers are\n\n// grouped to form buffered file.\n\n//\n\n// cache size :\n\n// This is the logical maximum for the cache size\n\n//\n\n// qdepth :\n\n// This is the max number of IOs that can issues to the device in parallel\n\n//\n\n// pepeling :\n\n// The writer code path follows pipelined architecture, which means the\n\n// operations are handed off from one stage to another\n\n//\n\n// pipelining backlog size :\n\n// With the pipelined architecture, there can always be backlogging of ops in\n\n// pipeline queues. This is the maximum backlog size after which ops are dropped\n\n// from queue\n\nstruct PersistentCacheConfig {\n\n explicit PersistentCacheConfig(\n\n Env* const _env, const std::string& _path, const uint64_t _cache_size,\n\n const std::shared_ptr<Logger>& _log,\n\n const uint32_t _write_buffer_size = 1 * 1024 * 1024 /*1MB*/) {\n\n env = _env;\n\n path = _path;\n\n log = _log;\n\n cache_size = _cache_size;\n\n writer_dispatch_size = write_buffer_size = _write_buffer_size;\n\n }\n\n\n\n //\n\n // Validate the settings. Our intentions are to catch erroneous settings ahead\n\n // of time instead going violating invariants or causing dead locks.\n\n //\n\n Status ValidateSettings() const {\n\n // (1) check pre-conditions for variables\n\n if (!env || path.empty()) {\n\n return Status::InvalidArgument(\"empty or null args\");\n", "file_path": "susy-rocksdb-sys/rocksdb/utilities/persistent_cache/persistent_cache_tier.h", "rank": 15, "score": 181874.68833106817 }, { "content": "// CompactionOptions are used in CompactFiles() call.\n\nstruct CompactionOptions {\n\n // Compaction output compression type\n\n // Default: snappy\n\n CompressionType compression;\n\n // Compaction will create files of size `output_file_size_limit`.\n\n // Default: MAX, which means that compaction will create a single file\n\n uint64_t output_file_size_limit;\n\n // If > 0, it will replace the option in the DBOptions for this compaction.\n\n uint32_t max_subcompactions;\n\n\n\n CompactionOptions()\n\n : compression(kSnappyCompression),\n\n output_file_size_limit(std::numeric_limits<uint64_t>::max()),\n\n max_subcompactions(0) {}\n\n};\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/options.h", "rank": 16, "score": 181600.95161362842 }, { "content": "// Options that control read operations\n\nstruct ReadOptions {\n\n // If \"snapshot\" is non-nullptr, read as of the supplied snapshot\n\n // (which must belong to the DB that is being read and which must\n\n // not have been released). If \"snapshot\" is nullptr, use an implicit\n\n // snapshot of the state at the beginning of this read operation.\n\n // Default: nullptr\n\n const Snapshot* snapshot;\n\n\n\n // `iterate_lower_bound` defines the smallest key at which the backward\n\n // iterator can return an entry. Once the bound is passed, Valid() will be\n\n // false. `iterate_lower_bound` is inclusive ie the bound value is a valid\n\n // entry.\n\n //\n\n // If prefix_extractor is not null, the Seek target and `iterate_lower_bound`\n\n // need to have the same prefix. This is because ordering is not guaranteed\n\n // outside of prefix domain.\n\n //\n\n // Default: nullptr\n\n const Slice* iterate_lower_bound;\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/options.h", "rank": 17, "score": 181594.05269545078 }, { "content": "// Options that control flush operations\n\nstruct FlushOptions {\n\n // If true, the flush will wait until the flush is done.\n\n // Default: true\n\n bool wait;\n\n\n\n FlushOptions() : wait(true) {}\n\n};\n\n\n\n// Create a Logger from provided DBOptions\n\nextern Status CreateLoggerFromOptions(const std::string& dbname,\n\n const DBOptions& options,\n\n std::shared_ptr<Logger>* logger);\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/options.h", "rank": 18, "score": 181594.05269545078 }, { "content": "// Options that control write operations\n\nstruct WriteOptions {\n\n // If true, the write will be flushed from the operating system\n\n // buffer cache (by calling WritableFile::Sync()) before the write\n\n // is considered complete. If this flag is true, writes will be\n\n // slower.\n\n //\n\n // If this flag is false, and the machine crashes, some recent\n\n // writes may be lost. Note that if it is just the process that\n\n // crashes (i.e., the machine does not reboot), no writes will be\n\n // lost even if sync==false.\n\n //\n\n // In other words, a DB write with sync==false has similar\n\n // crash semantics as the \"write()\" system call. A DB write\n\n // with sync==true has similar crash semantics to a \"write()\"\n\n // system call followed by \"fdatasync()\".\n\n //\n\n // Default: false\n\n bool sync;\n\n\n\n // If true, writes will not first go to the write ahead log,\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/options.h", "rank": 19, "score": 181594.05269545078 }, { "content": "struct Options;\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/advanced_options.h", "rank": 20, "score": 181587.15677161235 }, { "content": "struct DBOptions {\n\n // The function recovers options to the option as in version 4.6.\n\n DBOptions* OldDefaults(int rocksdb_major_version = 4,\n\n int rocksdb_minor_version = 6);\n\n\n\n // Some functions that make it easier to optimize RocksDB\n\n\n\n // Use this if your DB is very small (like under 1GB) and you don't want to\n\n // spend lots of memory for memtables.\n\n DBOptions* OptimizeForSmallDb();\n\n\n\n#ifndef ROCKSDB_LITE\n\n // By default, RocksDB uses only one background thread for flush and\n\n // compaction. Calling this function will set it up such that total of\n\n // `total_threads` is used. Good value for `total_threads` is the number of\n\n // cores. You almost definitely want to call this function if your system is\n\n // bottlenecked by RocksDB.\n\n DBOptions* IncreaseParallelism(int total_threads = 16);\n\n#endif // ROCKSDB_LITE\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/options.h", "rank": 21, "score": 181587.15677161235 }, { "content": "#[test]\n\nfn options() {\n\n let mut opts = Options::new();\n\n assert!(opts.set_parsed_options(\"rate_limiter_bytes_per_sec=1024\").is_ok());\n\n}\n", "file_path": "src/rocksdb.rs", "rank": 22, "score": 180988.7460630066 }, { "content": "struct CleanupContext {\n\n // List of values to be deleted, along with the key and deleter.\n\n autovector<CacheHandle> to_delete_value;\n\n\n\n // List of keys to be deleted.\n\n autovector<const char*> to_delete_key;\n\n};\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/cache/clock_cache.cc", "rank": 23, "score": 180506.00766139073 }, { "content": "// Per-thread state for concurrent executions of the same benchmark.\n\nstruct ThreadState {\n\n uint32_t tid;\n\n Random rnd;\n\n SharedState* shared;\n\n\n\n ThreadState(uint32_t index, SharedState* _shared)\n\n : tid(index), rnd(1000 + index), shared(_shared) {}\n\n};\n\n} // namespace\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/cache/cache_bench.cc", "rank": 24, "score": 180506.00766139073 }, { "content": "struct CacheRecord {\n\n CacheRecord() {}\n\n CacheRecord(const Slice& key, const Slice& val)\n\n : hdr_(MAGIC, static_cast<uint32_t>(key.size()),\n\n static_cast<uint32_t>(val.size())),\n\n key_(key),\n\n val_(val) {\n\n hdr_.crc_ = ComputeCRC();\n\n }\n\n\n\n uint32_t ComputeCRC() const;\n\n bool Serialize(std::vector<CacheWriteBuffer*>* bufs, size_t* woff);\n\n bool Deserialize(const Slice& buf);\n\n\n\n static uint32_t CalcSize(const Slice& key, const Slice& val) {\n\n return static_cast<uint32_t>(sizeof(CacheRecordHeader) + key.size() +\n\n val.size());\n\n }\n\n\n\n static const uint32_t MAGIC = 0xfefa;\n", "file_path": "susy-rocksdb-sys/rocksdb/utilities/persistent_cache/block_cache_tier_file.cc", "rank": 25, "score": 180169.70628233106 }, { "content": "enum OptionSection : char {\n\n kOptionSectionVersion = 0,\n\n kOptionSectionDBOptions,\n\n kOptionSectionCFOptions,\n\n kOptionSectionTableOptions,\n\n kOptionSectionUnknown\n\n};\n\n\n\nstatic const std::string opt_section_titles[] = {\n\n \"Version\", \"DBOptions\", \"CFOptions\", \"TableOptions/\", \"Unknown\"};\n\n\n\nStatus PersistRocksDBOptions(const DBOptions& db_opt,\n\n const std::vector<std::string>& cf_names,\n\n const std::vector<ColumnFamilyOptions>& cf_opts,\n\n const std::string& file_name, Env* env);\n\n\n\nextern bool AreEqualOptions(\n\n const char* opt1, const char* opt2, const OptionTypeInfo& type_info,\n\n const std::string& opt_name,\n\n const std::unordered_map<std::string, std::string>* opt_map);\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/options/options_parser.h", "rank": 26, "score": 179861.8227482228 }, { "content": "// CompactRangeOptions is used by CompactRange() call.\n\nstruct CompactRangeOptions {\n\n // If true, no other compaction will run at the same time as this\n\n // manual compaction\n\n bool exclusive_manual_compaction = true;\n\n // If true, compacted files will be moved to the minimum level capable\n\n // of holding the data or given level (specified non-negative target_level).\n\n bool change_level = false;\n\n // If change_level is true and target_level have non-negative value, compacted\n\n // files will be moved to target_level.\n\n int target_level = -1;\n\n // Compaction outputs will be placed in options.db_paths[target_path_id].\n\n // Behavior is undefined if target_path_id is out of range.\n\n uint32_t target_path_id = 0;\n\n // By default level based compaction will only compact the bottommost level\n\n // if there is a compaction filter\n\n BottommostLevelCompaction bottommost_level_compaction =\n\n BottommostLevelCompaction::kIfHaveCompactionFilter;\n\n // If true, will execute immediately even if doing so would cause the DB to\n\n // enter write stall mode. Otherwise, it'll sleep until load is low enough.\n\n bool allow_write_stall = false;\n\n // If > 0, it will replace the option in the DBOptions for this compaction.\n\n uint32_t max_subcompactions = 0;\n\n};\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/options.h", "rank": 27, "score": 179537.1725435744 }, { "content": "// Compression options for different compression algorithms like Zlib\n\nstruct CompressionOptions {\n\n int window_bits;\n\n int level;\n\n int strategy;\n\n\n\n // Maximum size of dictionaries used to prime the compression library.\n\n // Enabling dictionary can improve compression ratios when there are\n\n // repetitions across data blocks.\n\n //\n\n // The dictionary is created by sampling the SST file data. If\n\n // `zstd_max_train_bytes` is nonzero, the samples are passed through zstd's\n\n // dictionary generator. Otherwise, the random samples are used directly as\n\n // the dictionary.\n\n //\n\n // When compression dictionary is disabled, we compress and write each block\n\n // before buffering data for the next one. When compression dictionary is\n\n // enabled, we buffer all SST file data in-memory so we can sample it, as data\n\n // can only be compressed and written after the dictionary has been finalized.\n\n // So users of this feature may see increased memory usage.\n\n //\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/advanced_options.h", "rank": 28, "score": 179530.2206135632 }, { "content": "struct Options;\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/utilities/leveldb_options.h", "rank": 29, "score": 179523.48379431159 }, { "content": "// Context information of a compaction run\n\nstruct CompactionFilterContext {\n\n // Does this compaction run include all data files\n\n bool is_full_compaction;\n\n // Is this compaction requested by the client (true),\n\n // or is it occurring as an automatic compaction process\n\n bool is_manual_compaction;\n\n};\n\n\n\n// CompactionFilter allows an application to modify/delete a key-value at\n\n// the time of compaction.\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/compaction_filter.h", "rank": 30, "score": 178579.83267578672 }, { "content": "//\n\n// CacheRecord\n\n//\n\n// Cache record represents the record on disk\n\n//\n\n// +--------+---------+----------+------------+---------------+-------------+\n\n// | magic | crc | key size | value size | key data | value data |\n\n// +--------+---------+----------+------------+---------------+-------------+\n\n// <-- 4 --><-- 4 --><-- 4 --><-- 4 --><-- key size --><-- v-size -->\n\n//\n\nstruct CacheRecordHeader {\n\n CacheRecordHeader()\n\n : magic_(0), crc_(0), key_size_(0), val_size_(0) {}\n\n CacheRecordHeader(const uint32_t magic, const uint32_t key_size,\n\n const uint32_t val_size)\n\n : magic_(magic), crc_(0), key_size_(key_size), val_size_(val_size) {}\n\n\n\n uint32_t magic_;\n\n uint32_t crc_;\n\n uint32_t key_size_;\n\n uint32_t val_size_;\n\n};\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/utilities/persistent_cache/block_cache_tier_file.cc", "rank": 31, "score": 178547.0411531015 }, { "content": "struct CompactionOptionsFIFO {\n\n // once the total sum of table files reaches this, we will delete the oldest\n\n // table file\n\n // Default: 1GB\n\n uint64_t max_table_files_size;\n\n\n\n // Drop files older than TTL. TTL based deletion will take precedence over\n\n // size based deletion if ttl > 0.\n\n // delete if sst_file_creation_time < (current_time - ttl)\n\n // unit: seconds. Ex: 1 day = 1 * 24 * 60 * 60\n\n // Default: 0 (disabled)\n\n uint64_t ttl = 0;\n\n\n\n // If true, try to do compaction to compact smaller files into larger ones.\n\n // Minimum files to compact follows options.level0_file_num_compaction_trigger\n\n // and compaction won't trigger if average compact bytes per del file is\n\n // larger than options.write_buffer_size. This is to protect large files\n\n // from being compacted again.\n\n // Default: false;\n\n bool allow_compaction = false;\n\n\n\n CompactionOptionsFIFO() : max_table_files_size(1 * 1024 * 1024 * 1024) {}\n\n CompactionOptionsFIFO(uint64_t _max_table_files_size, bool _allow_compaction,\n\n uint64_t _ttl = 0)\n\n : max_table_files_size(_max_table_files_size),\n\n ttl(_ttl),\n\n allow_compaction(_allow_compaction) {}\n\n};\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/advanced_options.h", "rank": 32, "score": 177524.11794527562 }, { "content": "// Options to control the behavior of a database (passed to\n\n// DB::Open). A LevelDBOptions object can be initialized as though\n\n// it were a LevelDB Options object, and then it can be converted into\n\n// a RocksDB Options object.\n\nstruct LevelDBOptions {\n\n // -------------------\n\n // Parameters that affect behavior\n\n\n\n // Comparator used to define the order of keys in the table.\n\n // Default: a comparator that uses lexicographic byte-wise ordering\n\n //\n\n // REQUIRES: The client must ensure that the comparator supplied\n\n // here has the same name and orders keys *exactly* the same as the\n\n // comparator provided to previous open calls on the same DB.\n\n const Comparator* comparator;\n\n\n\n // If true, the database will be created if it is missing.\n\n // Default: false\n\n bool create_if_missing;\n\n\n\n // If true, an error is raised if the database already exists.\n\n // Default: false\n\n bool error_if_exists;\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/utilities/leveldb_options.h", "rank": 33, "score": 175594.09024255176 }, { "content": "struct AdvancedColumnFamilyOptions {\n\n // The maximum number of write buffers that are built up in memory.\n\n // The default and the minimum number is 2, so that when 1 write buffer\n\n // is being flushed to storage, new writes can continue to the other\n\n // write buffer.\n\n // If max_write_buffer_number > 3, writing will be slowed down to\n\n // options.delayed_write_rate if we are writing to the last write buffer\n\n // allowed.\n\n //\n\n // Default: 2\n\n //\n\n // Dynamically changeable through SetOptions() API\n\n int max_write_buffer_number = 2;\n\n\n\n // The minimum number of write buffers that will be merged togsophy\n\n // before writing to storage. If set to 1, then\n\n // all write buffers are flushed to L0 as individual files and this increases\n\n // read amplification because a get request has to check in all of these\n\n // files. Also, an in-memory merge may result in writing lesser\n\n // data to storage if there are duplicate records in each of these\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/advanced_options.h", "rank": 34, "score": 175585.95938802726 }, { "content": "//\n\n// Block Cache Tier Metadata\n\n//\n\n// The BlockCacheTierMetadata holds all the metadata associated with block\n\n// cache. It\n\n// fundamentally contains 2 indexes and an LRU.\n\n//\n\n// Block Cache Index\n\n//\n\n// This is a forward index that maps a given key to a LBA (Logical Block\n\n// Address). LBA is a disk pointer that points to a record on the cache.\n\n//\n\n// LBA = { cache-id, offset, size }\n\n//\n\n// Cache File Index\n\n//\n\n// This is a forward index that maps a given cache-id to a cache file object.\n\n// Typically you would lookup using LBA and use the object to read or write\n\nstruct BlockInfo {\n\n explicit BlockInfo(const Slice& key, const LBA& lba = LBA())\n\n : key_(key.ToString()), lba_(lba) {}\n\n\n\n std::string key_;\n\n LBA lba_;\n\n};\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/utilities/persistent_cache/block_cache_tier_metadata.h", "rank": 35, "score": 174670.405918601 }, { "content": "struct BlockInfo;\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/utilities/persistent_cache/block_cache_tier_file.h", "rank": 36, "score": 174655.1499024587 }, { "content": "// Represents a logical record on device\n\n//\n\n// (L)ogical (B)lock (Address = { cache-file-id, offset, size }\n\nstruct LogicalBlockAddress {\n\n LogicalBlockAddress() {}\n\n explicit LogicalBlockAddress(const uint32_t cache_id, const uint32_t off,\n\n const uint16_t size)\n\n : cache_id_(cache_id), off_(off), size_(size) {}\n\n\n\n uint32_t cache_id_ = 0;\n\n uint32_t off_ = 0;\n\n uint32_t size_ = 0;\n\n};\n\n\n\ntypedef LogicalBlockAddress LBA;\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/utilities/persistent_cache/block_cache_tier_file.h", "rank": 37, "score": 172826.90917079948 }, { "content": "struct Options;\n", "file_path": "susy-rocksdb-sys/rocksdb/db/builder.h", "rank": 38, "score": 172209.98306923162 }, { "content": "struct Options;\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/db.h", "rank": 39, "score": 169686.92687313867 }, { "content": "struct ReadOptions;\n\n\n\nextern bool ShouldReportDetailedTime(Env* env, Statistics* stats);\n\n\n\n// the length of the magic number in bytes.\n\nconst int kMagicNumberLengthByte = 8;\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/table/format.h", "rank": 40, "score": 169686.92687313867 }, { "content": "struct EnvOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/db/builder.h", "rank": 41, "score": 169686.92687313867 }, { "content": "struct Options;\n\n\n\nusing std::unique_ptr;\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/table.h", "rank": 42, "score": 169686.92687313867 }, { "content": "struct FileDescriptor;\n", "file_path": "susy-rocksdb-sys/rocksdb/db/table_cache.h", "rank": 43, "score": 168066.9467432976 }, { "content": "struct JobContext;\n", "file_path": "susy-rocksdb-sys/rocksdb/db/db_impl.h", "rank": 44, "score": 167993.93202401337 }, { "content": "struct rocksdb_options_t { Options rep; };\n", "file_path": "susy-rocksdb-sys/rocksdb/db/c.cc", "rank": 45, "score": 167925.1125480077 }, { "content": "//\n\n// An application can issue a read request (via Get/Iterators) and specify\n\n// if that read should process data that ALREADY resides on a specified cache\n\n// level. For example, if an application specifies kBlockCacheTier then the\n\n// Get call will process data that is already processed in the memtable or\n\n// the block cache. It will not page in data from the OS cache or data that\n\n// resides in storage.\n\nenum ReadTier {\n\n kReadAllTier = 0x0, // data in memtable, block cache, OS cache or storage\n\n kBlockCacheTier = 0x1, // data in memtable or block cache\n\n kPersistedTier = 0x2, // persisted data. When WAL is disabled, this option\n\n // will skip data in memtable.\n\n // Note that this ReadTier currently only supports\n\n // Get and MultiGet and does not support iterators.\n\n kMemtableTier = 0x3 // data in memtable. used for memtable-only iterators.\n\n};\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/options.h", "rank": 46, "score": 167764.1765036183 }, { "content": "// Options while opening a file to read/write\n\nstruct EnvOptions {\n\n\n\n // Construct with default Options\n\n EnvOptions();\n\n\n\n // Construct from Options\n\n explicit EnvOptions(const DBOptions& options);\n\n\n\n // If true, then use mmap to read data\n\n bool use_mmap_reads = false;\n\n\n\n // If true, then use mmap to write data\n\n bool use_mmap_writes = true;\n\n\n\n // If true, then use O_DIRECT for reading data\n\n bool use_direct_reads = false;\n\n\n\n // If true, then use O_DIRECT for writing data\n\n bool use_direct_writes = false;\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/env.h", "rank": 47, "score": 167268.05253253313 }, { "content": "struct rocksdb_optimistictransaction_options_t {\n\n OptimisticTransactionOptions rep;\n\n};\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/db/c.cc", "rank": 48, "score": 167261.21047205682 }, { "content": "struct WriteOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/db.h", "rank": 49, "score": 167261.21047205682 }, { "content": "struct CompactionOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/db.h", "rank": 50, "score": 167261.21047205682 }, { "content": "struct rocksdb_transactiondb_options_t {\n\n TransactionDBOptions rep;\n\n};\n", "file_path": "susy-rocksdb-sys/rocksdb/db/c.cc", "rank": 51, "score": 167261.21047205682 }, { "content": "struct ReadOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/table/table_reader.h", "rank": 52, "score": 167261.21047205682 }, { "content": "struct Options;\n", "file_path": "susy-rocksdb-sys/rocksdb/table/plain_table_reader.h", "rank": 53, "score": 167261.21047205682 }, { "content": "struct DbPath {\n\n std::string path;\n\n uint64_t target_size; // Target size of total files under the path, in byte.\n\n\n\n DbPath() : target_size(0) {}\n\n DbPath(const std::string& p, uint64_t t) : path(p), target_size(t) {}\n\n};\n\n\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/options.h", "rank": 54, "score": 167261.21047205682 }, { "content": "struct DbPath;\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/options.h", "rank": 55, "score": 167261.21047205682 }, { "content": "struct rocksdb_transaction_options_t {\n\n TransactionOptions rep;\n\n};\n", "file_path": "susy-rocksdb-sys/rocksdb/db/c.cc", "rank": 56, "score": 167261.21047205682 }, { "content": "struct EnvOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/table.h", "rank": 57, "score": 167261.21047205682 }, { "content": "struct DBOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/env.h", "rank": 58, "score": 167261.21047205682 }, { "content": "struct ReadOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/db.h", "rank": 59, "score": 167261.21047205682 }, { "content": "struct FlushOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/db.h", "rank": 60, "score": 167261.21047205682 }, { "content": "struct DBOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/db.h", "rank": 61, "score": 167261.21047205682 }, { "content": "struct ColumnFamilyOptions : public AdvancedColumnFamilyOptions {\n\n // The function recovers options to a previous version. Only 4.6 or later\n\n // versions are supported.\n\n ColumnFamilyOptions* OldDefaults(int rocksdb_major_version = 4,\n\n int rocksdb_minor_version = 6);\n\n\n\n // Some functions that make it easier to optimize RocksDB\n\n // Use this if your DB is very small (like under 1GB) and you don't want to\n\n // spend lots of memory for memtables.\n\n ColumnFamilyOptions* OptimizeForSmallDb();\n\n\n\n // Use this if you don't need to keep the data sorted, i.e. you'll never use\n\n // an iterator, only Put() and Get() API calls\n\n //\n\n // Not supported in ROCKSDB_LITE\n\n ColumnFamilyOptions* OptimizeForPointLookup(\n\n uint64_t block_cache_size_mb);\n\n\n\n // Default values for some parameters in ColumnFamilyOptions are not\n\n // optimized for heavy workloads and big datasets, which means you might\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/options.h", "rank": 62, "score": 165915.62589989576 }, { "content": "struct LRUElement {\n\n explicit LRUElement() : next_(nullptr), prev_(nullptr), refs_(0) {}\n\n\n\n virtual ~LRUElement() { assert(!refs_); }\n\n\n\n T* next_;\n\n T* prev_;\n\n std::atomic<size_t> refs_;\n\n};\n\n\n\n// LRU implementation\n\n//\n\n// In place LRU implementation. There is no copy or allocation involved when\n\n// inserting or removing an element. This makes the data structure slim\n\ntemplate <class T>\n", "file_path": "susy-rocksdb-sys/rocksdb/utilities/persistent_cache/lrulist.h", "rank": 63, "score": 165717.7951194635 }, { "content": "struct BlockContents;\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/table/persistent_cache_helper.h", "rank": 64, "score": 165717.7951194635 }, { "content": "struct MemTableInfo;\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/db/db_impl.h", "rank": 65, "score": 165646.1622032075 }, { "content": "struct IterState {\n\n IterState(DBImpl* _db, InstrumentedMutex* _mu, SuperVersion* _super_version,\n\n bool _background_purge)\n\n : db(_db),\n\n mu(_mu),\n\n super_version(_super_version),\n\n background_purge(_background_purge) {}\n\n\n\n DBImpl* db;\n\n InstrumentedMutex* mu;\n\n SuperVersion* super_version;\n\n bool background_purge;\n\n};\n\n\n\nstatic void CleanupIteratorState(void* arg1, void* /*arg2*/) {\n\n IterState* state = reinterpret_cast<IterState*>(arg1);\n\n\n\n if (state->super_version->Unref()) {\n\n // Job id == 0 means that this is not our background process, but rather\n\n // user thread\n", "file_path": "susy-rocksdb-sys/rocksdb/db/db_impl.cc", "rank": 66, "score": 165646.1622032075 }, { "content": "// Options for customizing ldb tool (beyond the DB Options)\n\nstruct LDBOptions {\n\n // Create LDBOptions with default values for all fields\n\n LDBOptions();\n\n\n\n // Key formatter that converts a slice to a readable string.\n\n // Default: Slice::ToString()\n\n std::shared_ptr<SliceFormatter> key_formatter;\n\n\n\n std::string print_help_header = \"ldb - RocksDB Tool\";\n\n};\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/ldb_tool.h", "rank": 67, "score": 164935.10546252917 }, { "content": "struct TableBuilderOptions {\n\n TableBuilderOptions(\n\n const ImmutableCFOptions& _ioptions,\n\n const InternalKeyComparator& _internal_comparator,\n\n const std::vector<std::unique_ptr<IntTblPropCollectorFactory>>*\n\n _int_tbl_prop_collector_factories,\n\n CompressionType _compression_type,\n\n const CompressionOptions& _compression_opts,\n\n const std::string* _compression_dict, bool _skip_filters,\n\n const std::string& _column_family_name, int _level,\n\n const uint64_t _creation_time = 0, const int64_t _oldest_key_time = 0)\n\n : ioptions(_ioptions),\n\n internal_comparator(_internal_comparator),\n\n int_tbl_prop_collector_factories(_int_tbl_prop_collector_factories),\n\n compression_type(_compression_type),\n\n compression_opts(_compression_opts),\n\n compression_dict(_compression_dict),\n\n skip_filters(_skip_filters),\n\n column_family_name(_column_family_name),\n\n level(_level),\n", "file_path": "susy-rocksdb-sys/rocksdb/table/table_builder.h", "rank": 68, "score": 164927.30740126083 }, { "content": "struct Options;\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/flush_block_policy.h", "rank": 69, "score": 164927.30740126083 }, { "content": "struct ReadOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/table/two_level_iterator.h", "rank": 70, "score": 164927.30740126083 }, { "content": "struct CompactRangeOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/db.h", "rank": 71, "score": 164927.30740126083 }, { "content": "struct TableReaderOptions {\n\n // @param skip_filters Disables loading/accessing the filter block\n\n TableReaderOptions(const ImmutableCFOptions& _ioptions,\n\n const EnvOptions& _env_options,\n\n const InternalKeyComparator& _internal_comparator,\n\n bool _skip_filters = false, int _level = -1)\n\n : ioptions(_ioptions),\n\n env_options(_env_options),\n\n internal_comparator(_internal_comparator),\n\n skip_filters(_skip_filters),\n\n level(_level) {}\n\n\n\n const ImmutableCFOptions& ioptions;\n\n const EnvOptions& env_options;\n\n const InternalKeyComparator& internal_comparator;\n\n // This is only used for BlockBasedTable (reader)\n\n bool skip_filters;\n\n // what level this table/file is on, -1 for \"not set, don't know\"\n\n int level;\n\n};\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/table/table_builder.h", "rank": 72, "score": 164927.30740126083 }, { "content": "struct ColumnFamilyOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/db.h", "rank": 73, "score": 164927.30740126083 }, { "content": "struct ImmutableMemTableOptions {\n\n explicit ImmutableMemTableOptions(const ImmutableCFOptions& ioptions,\n\n const MutableCFOptions& mutable_cf_options);\n\n size_t arena_block_size;\n\n uint32_t memtable_prefix_bloom_bits;\n\n size_t memtable_huge_page_size;\n\n bool inplace_update_support;\n\n size_t inplace_update_num_locks;\n\n UpdateStatus (*inplace_callback)(char* existing_value,\n\n uint32_t* existing_value_size,\n\n Slice delta_value,\n\n std::string* merged_value);\n\n size_t max_successive_merges;\n\n Statistics* statistics;\n\n MergeOperator* merge_operator;\n\n Logger* info_log;\n\n};\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/db/memtable.h", "rank": 74, "score": 164927.30740126083 }, { "content": "struct ReadOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/table/plain_table_reader.h", "rank": 75, "score": 164927.30740126083 }, { "content": "struct TableReaderOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/table.h", "rank": 76, "score": 164927.30740126083 }, { "content": "struct TableBuilderOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/table.h", "rank": 77, "score": 164927.30740126083 }, { "content": "struct ImmutableDBOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/env.h", "rank": 78, "score": 164927.30740126083 }, { "content": "struct MutableDBOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/env.h", "rank": 79, "score": 164927.30740126083 }, { "content": "struct OptionsOverride {\n\n std::shared_ptr<const FilterPolicy> filter_policy = nullptr;\n\n // These will be used only if filter_policy is set\n\n bool partition_filters = false;\n\n uint64_t metadata_block_size = 1024;\n\n BlockBasedTableOptions::IndexType index_type =\n\n BlockBasedTableOptions::IndexType::kBinarySearch;\n\n\n\n // Used as a bit mask of individual enums in which to skip an XF test point\n\n int skip_policy = 0;\n\n};\n\n\n\n} // namespace anon\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/db/db_test_util.h", "rank": 80, "score": 164927.30740126083 }, { "content": "struct rocksdb_universal_compaction_options_t {\n\n rocksdb::CompactionOptionsUniversal *rep;\n\n};\n\n\n\nstatic bool SaveError(char** errptr, const Status& s) {\n\n assert(errptr != nullptr);\n\n if (s.ok()) {\n\n return false;\n\n } else if (*errptr == nullptr) {\n\n *errptr = strdup(s.ToString().c_str());\n\n } else {\n\n // TODO(sanjay): Merge with existing error?\n\n // This is a bug if *errptr is not created by malloc()\n\n free(*errptr);\n\n *errptr = strdup(s.ToString().c_str());\n\n }\n\n return true;\n\n}\n\n\n\nstatic char* CopyString(const std::string& str) {\n", "file_path": "susy-rocksdb-sys/rocksdb/db/c.cc", "rank": 81, "score": 164927.30740126083 }, { "content": "struct EnvOptions;\n\n\n\nusing std::unique_ptr;\n", "file_path": "susy-rocksdb-sys/rocksdb/table/adaptive_table_factory.h", "rank": 82, "score": 164927.30740126083 }, { "content": "struct EnvOptions;\n\n\n\nusing std::unique_ptr;\n", "file_path": "susy-rocksdb-sys/rocksdb/table/plain_table_factory.h", "rank": 83, "score": 164927.30740126083 }, { "content": "struct PlainTableOptions {\n\n // @user_key_len: plain table has optimization for fix-sized keys, which can\n\n // be specified via user_key_len. Alternatively, you can pass\n\n // `kPlainTableVariableLength` if your keys have variable\n\n // lengths.\n\n uint32_t user_key_len = kPlainTableVariableLength;\n\n\n\n // @bloom_bits_per_key: the number of bits used for bloom filer per prefix.\n\n // You may disable it by passing a zero.\n\n int bloom_bits_per_key = 10;\n\n\n\n // @hash_table_ratio: the desired utilization of the hash table used for\n\n // prefix hashing.\n\n // hash_table_ratio = number of prefixes / #buckets in the\n\n // hash table\n\n double hash_table_ratio = 0.75;\n\n\n\n // @index_sparseness: inside each prefix, need to build one index record for\n\n // how many keys for binary search inside each hash bucket.\n\n // For encoding type kPrefix, the value will be used when\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/table.h", "rank": 84, "score": 164927.30740126083 }, { "content": "struct CuckooTableOptions {\n\n // Determines the utilization of hash tables. Smaller values\n\n // result in larger hash tables with fewer collisions.\n\n double hash_table_ratio = 0.9;\n\n // A property used by builder to determine the depth to go to\n\n // to search for a path to displace elements in case of\n\n // collision. See Builder.MakeSpaceForKey method. Higher\n\n // values result in more efficient hash tables with fewer\n\n // lookups but take more time to build.\n\n uint32_t max_search_depth = 100;\n\n // In case of collision while inserting, the builder\n\n // attempts to insert in the next cuckoo_block_size\n\n // locations before skipping over to the next Cuckoo hash\n\n // function. This makes lookups more cache friendly in case\n\n // of collisions.\n\n uint32_t cuckoo_block_size = 5;\n\n // If this option is enabled, user key is treated as uint64_t and its value\n\n // is used as hash value directly. This option changes builder's behavior.\n\n // Reader ignore this option and behave according to what specified in table\n\n // property.\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/table.h", "rank": 85, "score": 164927.30740126083 }, { "content": "struct rocksdb_restore_options_t { RestoreOptions rep; };\n", "file_path": "susy-rocksdb-sys/rocksdb/db/c.cc", "rank": 86, "score": 163987.58814172336 }, { "content": "struct ExternalFileIngestionInfo {\n\n // the name of the column family\n\n std::string cf_name;\n\n // Path of the file outside the DB\n\n std::string external_file_path;\n\n // Path of the file inside the DB\n\n std::string internal_file_path;\n\n // The global sequence number assigned to keys in this file\n\n SequenceNumber global_seqno;\n\n // Table properties of the table being flushed\n\n TableProperties table_properties;\n\n};\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/listener.h", "rank": 87, "score": 163591.41145768674 }, { "content": "struct ExternalSstFileInfo;\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/db.h", "rank": 88, "score": 163591.41145768674 }, { "content": "// Options to control the behavior of a database (passed to DB::Open)\n\nstruct Options : public DBOptions, public ColumnFamilyOptions {\n\n // Create an Options object with default values for all fields.\n\n Options() : DBOptions(), ColumnFamilyOptions() {}\n\n\n\n Options(const DBOptions& db_options,\n\n const ColumnFamilyOptions& column_family_options)\n\n : DBOptions(db_options), ColumnFamilyOptions(column_family_options) {}\n\n\n\n // The function recovers options to the option as in version 4.6.\n\n Options* OldDefaults(int rocksdb_major_version = 4,\n\n int rocksdb_minor_version = 6);\n\n\n\n void Dump(Logger* log) const;\n\n\n\n void DumpCFOptions(Logger* log) const;\n\n\n\n // Some functions that make it easier to optimize RocksDB\n\n\n\n // Set appropriate parameters for bulk loading.\n\n // The reason that this is a function that returns \"this\" instead of a\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/options.h", "rank": 89, "score": 163485.27615073015 }, { "content": "struct WriteOptions;\n\n\n\nOptimisticTransaction::OptimisticTransaction(\n\n OptimisticTransactionDB* txn_db, const WriteOptions& write_options,\n\n const OptimisticTransactionOptions& txn_options)\n\n : TransactionBaseImpl(txn_db->GetBaseDB(), write_options), txn_db_(txn_db) {\n\n Initialize(txn_options);\n\n}\n\n\n\nvoid OptimisticTransaction::Initialize(\n\n const OptimisticTransactionOptions& txn_options) {\n\n if (txn_options.set_snapshot) {\n\n SetSnapshot();\n\n }\n\n}\n\n\n\nvoid OptimisticTransaction::Reinitialize(\n\n OptimisticTransactionDB* txn_db, const WriteOptions& write_options,\n\n const OptimisticTransactionOptions& txn_options) {\n\n TransactionBaseImpl::Reinitialize(txn_db->GetBaseDB(), write_options);\n", "file_path": "susy-rocksdb-sys/rocksdb/utilities/transactions/optimistic_transaction.cc", "rank": 90, "score": 162680.10177896434 }, { "content": "struct ComparatorJniCallbackOptions {\n\n // Use adaptive mutex, which spins in the user space before resorting\n\n // to kernel. This could reduce context switch when the mutex is not\n\n // heavily contended. However, if the mutex is hot, we could end up\n\n // wasting spin time.\n\n // Default: false\n\n bool use_adaptive_mutex;\n\n\n\n ComparatorJniCallbackOptions() : use_adaptive_mutex(false) {\n\n }\n\n};\n\n\n\n/**\n\n * This class acts as a bridge between C++\n\n * and Java. The methods in this class will be\n\n * called back from the RocksDB storage engine (C++)\n\n * we then callback to the appropriate Java method\n\n * this enables Comparators to be implemented in Java.\n\n *\n\n * The design of this Comparator caches the Java Slice\n\n * objects that are used in the compare and findShortestSeparator\n\n * method callbacks. Instead of creating new objects for each callback\n\n * of those functions, by reuse via setHandle we are a lot\n\n * faster; Unfortunately this means that we have to\n\n * introduce independent locking in regions of each of those methods\n\n * via the mutexs mtx_compare and mtx_findShortestSeparator respectively\n\n */\n", "file_path": "susy-rocksdb-sys/rocksdb/java/rocksjni/comparatorjnicallback.h", "rank": 91, "score": 162680.10177896434 }, { "content": "// For advanced user only\n\nstruct BlockBasedTableOptions {\n\n // @flush_block_policy_factory creates the instances of flush block policy.\n\n // which provides a configurable way to determine when to flush a block in\n\n // the block based tables. If not set, table builder will use the default\n\n // block flush policy, which cut blocks by block size (please refer to\n\n // `FlushBlockBySizePolicy`).\n\n std::shared_ptr<FlushBlockPolicyFactory> flush_block_policy_factory;\n\n\n\n // TODO(kailiu) Temporarily disable this feature by making the default value\n\n // to be false.\n\n //\n\n // Indicating if we'd put index/filter blocks to the block cache.\n\n // If not specified, each \"table reader\" object will pre-load index/filter\n\n // block during table initialization.\n\n bool cache_index_and_filter_blocks = false;\n\n\n\n // If cache_index_and_filter_blocks is enabled, cache index and filter\n\n // blocks with high priority. If set to true, depending on implementation of\n\n // block cache, index and filter blocks may be less likely to be evicted\n\n // than data blocks.\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/table.h", "rank": 92, "score": 162680.10177896434 }, { "content": "struct RestoreOptions {\n\n // If true, restore won't overwrite the existing log files in wal_dir. It will\n\n // also move all log files from archive directory to wal_dir. Use this option\n\n // in combination with BackupableDBOptions::backup_log_files = false for\n\n // persisting in-memory databases.\n\n // Default: false\n\n bool keep_log_files;\n\n\n\n explicit RestoreOptions(bool _keep_log_files = false)\n\n : keep_log_files(_keep_log_files) {}\n\n};\n\n\n\ntypedef uint32_t BackupID;\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/utilities/backupable_db.h", "rank": 93, "score": 162680.10177896434 }, { "content": "struct DumpOptions {\n\n // Database that will be dumped\n\n std::string db_path;\n\n // File location that will contain dump output\n\n std::string dump_location;\n\n // Don't include db information header in the dump\n\n bool anonymous = false;\n\n};\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/db_dump_tool.h", "rank": 94, "score": 162680.10177896434 }, { "content": "struct UndumpOptions {\n\n // Database that we will load the dumped file into\n\n std::string db_path;\n\n // File location of the dumped file that will be loaded\n\n std::string dump_location;\n\n // Compact the db after loading the dumped file\n\n bool compact_db = false;\n\n};\n\n\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/db_dump_tool.h", "rank": 95, "score": 162680.10177896434 }, { "content": "struct EnvOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/table/block_based_table_reader.h", "rank": 96, "score": 162680.10177896434 }, { "content": "struct EnvOptions;\n\n\n\nusing std::unique_ptr;\n", "file_path": "susy-rocksdb-sys/rocksdb/table/block_based_table_factory.h", "rank": 97, "score": 162680.10177896434 }, { "content": "struct ReadOptions;\n", "file_path": "susy-rocksdb-sys/rocksdb/table/block_based_table_reader.h", "rank": 98, "score": 162680.10177896434 }, { "content": "struct TransactionOptions {\n\n // Setting set_snapshot=true is the same as calling\n\n // Transaction::SetSnapshot().\n\n bool set_snapshot = false;\n\n\n\n // Setting to true means that before acquiring locks, this transaction will\n\n // check if doing so will cause a deadlock. If so, it will return with\n\n // Status::Busy. The user should retry their transaction.\n\n bool deadlock_detect = false;\n\n\n\n // If set, it states that the CommitTimeWriteBatch represents the latest state\n\n // of the application, has only one sub-batch, i.e., no duplicate keys, and\n\n // meant to be used later during recovery. It enables an optimization to\n\n // postpone updating the memtable with CommitTimeWriteBatch to only\n\n // SwitchMemtable or recovery.\n\n bool use_only_the_last_commit_time_batch_for_recovery = false;\n\n\n\n // TODO(agiardullo): TransactionDB does not yet support comparators that allow\n\n // two non-equal keys to be equivalent. Ie, cmp->Compare(a,b) should only\n\n // return 0 if\n", "file_path": "susy-rocksdb-sys/rocksdb/include/rocksdb/utilities/transaction_db.h", "rank": 99, "score": 162680.10177896434 } ]
Rust
src/lib.rs
newAM/clap-num
7d23825a4976b41bfd5d6f8ce70bcfa4ca434fc1
#![doc(html_root_url = "https://docs.rs/clap-num/0.2.0")] #![deny(missing_docs)] use core::convert::TryFrom; use core::str::FromStr; use num_traits::identities::Zero; use num_traits::{sign, CheckedAdd, CheckedMul, CheckedSub, Num}; fn check_range<T: Ord + std::fmt::Display>(val: T, min: T, max: T) -> Result<T, String> where T: FromStr, <T as std::str::FromStr>::Err: std::fmt::Display, { if val > max { Err(format!("exceeds maximum of {}", max)) } else if val < min { Err(format!("exceeds minimum of {}", min)) } else { Ok(val) } } pub fn number_range<T: Ord + PartialOrd + std::fmt::Display>( s: &str, min: T, max: T, ) -> Result<T, String> where T: FromStr, <T as std::str::FromStr>::Err: std::fmt::Display, { debug_assert!(min <= max, "minimum of {} exceeds maximum of {}", min, max); let val = s.parse::<T>().map_err(stringify)?; check_range(val, min, max) } static OVERFLOW_MSG: &str = "number too large to fit in target type"; fn stringify<T: std::fmt::Display>(e: T) -> String { format!("{}", e) } fn overflow_err<T>(_: T) -> String { OVERFLOW_MSG.to_string() } fn find_si_symbol(s: &str) -> (u128, usize, Option<usize>) { for (i, c) in s.chars().enumerate() { match c { 'Y' => return (1_000_000_000_000_000_000_000_000, 24, Some(i)), 'Z' => return (1_000_000_000_000_000_000_000, 21, Some(i)), 'E' => return (1_000_000_000_000_000_000, 18, Some(i)), 'P' => return (1_000_000_000_000_000, 15, Some(i)), 'T' => return (1_000_000_000_000, 12, Some(i)), 'G' => return (1_000_000_000, 9, Some(i)), 'M' => return (1_000_000, 6, Some(i)), 'k' => return (1_000, 3, Some(i)), _ => continue, }; } (1, 0, None) } fn find_decimal(s: &str) -> Option<usize> { for (i, c) in s.chars().enumerate() { if c == '.' { return Some(i); } } None } fn parse_post<T>(post: &str, digits: usize, decimal: bool) -> Result<T, String> where <T as std::str::FromStr>::Err: std::fmt::Display, T: std::cmp::PartialOrd + std::str::FromStr, { let mut post = post[1..].to_string(); if decimal { post.pop(); } if post.len() > digits { Err(String::from("not an integer")) } else { while post.len() < digits { post.push('0'); } post.parse::<T>().map_err(stringify) } } pub fn si_number<T>(s: &str) -> Result<T, String> where <T as std::convert::TryFrom<u128>>::Error: std::fmt::Display, <T as std::str::FromStr>::Err: std::fmt::Display, T: CheckedAdd, T: CheckedMul, T: CheckedSub, T: FromStr, T: std::cmp::PartialOrd, T: TryFrom<u128>, T: Zero, { let (multiplier, digits, si_index) = find_si_symbol(s); let multiplier = T::try_from(multiplier).map_err(overflow_err)?; if let Some(idx) = si_index { if idx == 0 { return Err("no value found before SI symbol".to_string()); }; let (pre_si, post_si) = s.split_at(idx); let (pre, post) = if post_si.len() > 1 { ( pre_si.parse::<T>().map_err(stringify)?, parse_post(&post_si, digits, false)?, ) } else if let Some(idx) = find_decimal(pre_si) { let (pre_dec, post_dec) = s.split_at(idx); let post_dec = parse_post(&post_dec, digits, true)?; (pre_dec.parse::<T>().map_err(stringify)?, post_dec) } else { (pre_si.parse::<T>().map_err(stringify)?, T::zero()) }; let pre = pre .checked_mul(&multiplier) .ok_or_else(|| OVERFLOW_MSG.to_string())?; if pre >= T::zero() { pre.checked_add(&post) .ok_or_else(|| OVERFLOW_MSG.to_string()) } else { pre.checked_sub(&post) .ok_or_else(|| OVERFLOW_MSG.to_string()) } } else { s.parse::<T>().map_err(stringify) } } pub fn si_number_range<T: Ord + PartialOrd + std::fmt::Display>( s: &str, min: T, max: T, ) -> Result<T, String> where <T as std::convert::TryFrom<u128>>::Error: std::fmt::Display, <T as std::str::FromStr>::Err: std::fmt::Display, T: CheckedAdd, T: CheckedMul, T: CheckedSub, T: FromStr, T: std::cmp::PartialOrd, T: TryFrom<u128>, T: Zero, { let val = si_number(s)?; check_range(val, min, max) } pub fn maybe_hex<T: Num + sign::Unsigned>(s: &str) -> Result<T, String> where <T as num_traits::Num>::FromStrRadixErr: std::fmt::Display, { const HEX_PREFIX: &str = "0x"; const HEX_PREFIX_LEN: usize = HEX_PREFIX.len(); let result = if s.to_ascii_lowercase().starts_with(HEX_PREFIX) { T::from_str_radix(&s[HEX_PREFIX_LEN..], 16) } else { T::from_str_radix(s, 10) }; match result { Ok(v) => Ok(v), Err(e) => Err(format!("{}", e)), } } pub fn maybe_hex_range<T: Num + sign::Unsigned>(s: &str, min: T, max: T) -> Result<T, String> where <T as num_traits::Num>::FromStrRadixErr: std::fmt::Display, <T as std::str::FromStr>::Err: std::fmt::Display, T: FromStr, T: std::fmt::Display, T: std::cmp::Ord, { let val = maybe_hex(s)?; check_range(val, min, max) }
#![doc(html_root_url = "https://docs.rs/clap-num/0.2.0")] #![deny(missing_docs)] use core::convert::TryFrom; use core::str::FromStr; use num_traits::identities::Zero; use num_traits::{sign, CheckedAdd, CheckedMul, CheckedSub, Num}; fn check_range<T: Ord + std::fmt::Display>(val: T, min: T, max: T) -> Result<T, String> where T: FromStr, <T as std::str::FromStr>::Err: std::fmt::Display, { if val > max { Err(format!("exceeds maximum of {}", max)) } else if val < min { Err(format!("exceeds minimum of {}", min)) } else { Ok(val) } } pub fn number_range<T: Ord + PartialOrd + std::fmt::Display>( s: &str, min: T, max: T, ) -> Result<T, String> where T: FromStr, <T as std::str::FromStr>::Err: std::fmt::Display, { debug_assert!(min <= max, "minimum of {} exceeds maximum of {}", min, max); let val = s.parse::<T>().map_err(stringify)?; check_range(val, min, max) } static OVERFLOW_MSG: &str = "number too large to fit in target type"; fn stringify<T: std::fmt::Display>(e: T) -> String { format!("{}", e) } fn overflow_err<T>(_: T) -> String { OVERFLOW_MSG.to_string() } fn find_si_symbol(s: &str) -> (u128, usize, Option<usize>) { for (i, c) in s.chars().enumerate() { match c { 'Y' => return (1_000_000_000_000_000_000_000_000, 24, Some(i)), 'Z' => return (1_000_000_000_000_000_000_000, 21, Some(i)), 'E' => return (1_000_000_000_000_000_000, 18, Some(i)), 'P' => return (1_000_000_000_000_000, 15, Some(i)), 'T' => return (1_000_000_000_000, 12, Some(i)), 'G' => return (1_000_
pre.checked_add(&post) .ok_or_else(|| OVERFLOW_MSG.to_string()) } else { pre.checked_sub(&post) .ok_or_else(|| OVERFLOW_MSG.to_string()) } } else { s.parse::<T>().map_err(stringify) } } pub fn si_number_range<T: Ord + PartialOrd + std::fmt::Display>( s: &str, min: T, max: T, ) -> Result<T, String> where <T as std::convert::TryFrom<u128>>::Error: std::fmt::Display, <T as std::str::FromStr>::Err: std::fmt::Display, T: CheckedAdd, T: CheckedMul, T: CheckedSub, T: FromStr, T: std::cmp::PartialOrd, T: TryFrom<u128>, T: Zero, { let val = si_number(s)?; check_range(val, min, max) } pub fn maybe_hex<T: Num + sign::Unsigned>(s: &str) -> Result<T, String> where <T as num_traits::Num>::FromStrRadixErr: std::fmt::Display, { const HEX_PREFIX: &str = "0x"; const HEX_PREFIX_LEN: usize = HEX_PREFIX.len(); let result = if s.to_ascii_lowercase().starts_with(HEX_PREFIX) { T::from_str_radix(&s[HEX_PREFIX_LEN..], 16) } else { T::from_str_radix(s, 10) }; match result { Ok(v) => Ok(v), Err(e) => Err(format!("{}", e)), } } pub fn maybe_hex_range<T: Num + sign::Unsigned>(s: &str, min: T, max: T) -> Result<T, String> where <T as num_traits::Num>::FromStrRadixErr: std::fmt::Display, <T as std::str::FromStr>::Err: std::fmt::Display, T: FromStr, T: std::fmt::Display, T: std::cmp::Ord, { let val = maybe_hex(s)?; check_range(val, min, max) }
000_000, 9, Some(i)), 'M' => return (1_000_000, 6, Some(i)), 'k' => return (1_000, 3, Some(i)), _ => continue, }; } (1, 0, None) } fn find_decimal(s: &str) -> Option<usize> { for (i, c) in s.chars().enumerate() { if c == '.' { return Some(i); } } None } fn parse_post<T>(post: &str, digits: usize, decimal: bool) -> Result<T, String> where <T as std::str::FromStr>::Err: std::fmt::Display, T: std::cmp::PartialOrd + std::str::FromStr, { let mut post = post[1..].to_string(); if decimal { post.pop(); } if post.len() > digits { Err(String::from("not an integer")) } else { while post.len() < digits { post.push('0'); } post.parse::<T>().map_err(stringify) } } pub fn si_number<T>(s: &str) -> Result<T, String> where <T as std::convert::TryFrom<u128>>::Error: std::fmt::Display, <T as std::str::FromStr>::Err: std::fmt::Display, T: CheckedAdd, T: CheckedMul, T: CheckedSub, T: FromStr, T: std::cmp::PartialOrd, T: TryFrom<u128>, T: Zero, { let (multiplier, digits, si_index) = find_si_symbol(s); let multiplier = T::try_from(multiplier).map_err(overflow_err)?; if let Some(idx) = si_index { if idx == 0 { return Err("no value found before SI symbol".to_string()); }; let (pre_si, post_si) = s.split_at(idx); let (pre, post) = if post_si.len() > 1 { ( pre_si.parse::<T>().map_err(stringify)?, parse_post(&post_si, digits, false)?, ) } else if let Some(idx) = find_decimal(pre_si) { let (pre_dec, post_dec) = s.split_at(idx); let post_dec = parse_post(&post_dec, digits, true)?; (pre_dec.parse::<T>().map_err(stringify)?, post_dec) } else { (pre_si.parse::<T>().map_err(stringify)?, T::zero()) }; let pre = pre .checked_mul(&multiplier) .ok_or_else(|| OVERFLOW_MSG.to_string())?; if pre >= T::zero() {
random
[ { "content": "fn less_than_100(s: &str) -> Result<u8, String> {\n\n number_range(s, 0, 99)\n\n}\n\n\n", "file_path": "examples/change.rs", "rank": 7, "score": 74407.00790011589 }, { "content": "#[test]\n\nfn test_readme_deps() {\n\n version_sync::assert_markdown_deps_updated!(\"README.md\");\n\n}\n\n\n", "file_path": "tests/version-numbers.rs", "rank": 12, "score": 39037.61840984814 }, { "content": "#[test]\n\nfn test_html_root_url() {\n\n version_sync::assert_html_root_url_updated!(\"src/lib.rs\");\n\n}\n", "file_path": "tests/version-numbers.rs", "rank": 13, "score": 37608.22559669669 }, { "content": "fn main() {\n\n let args = Change::parse();\n\n println!(\"Change: {} cents\", args.cents);\n\n}\n", "file_path": "examples/change.rs", "rank": 14, "score": 26783.007473439844 }, { "content": "fn main() {\n\n let args = Args::parse();\n\n println!(\"Resistance: {} ohms\", args.resistance)\n\n}\n", "file_path": "examples/resistance.rs", "rank": 15, "score": 26783.007473439844 }, { "content": " \"number too large to fit in target type\"\n\n );\n\n neg!(nan, \"nan\", 0, 0, \"invalid digit found in string\");\n\n\n\n #[test]\n\n #[should_panic]\n\n fn min_max_debug_assert() {\n\n let _ = number_range(\"\", 2, 1);\n\n }\n\n}\n\n\n\n// integration tests with clap\n\n#[cfg(test)]\n\nmod integration {\n\n use super::*;\n\n\n\n fn human_livable_temperature(s: &str) -> Result<i8, String> {\n\n number_range(s, -40, 60)\n\n }\n\n\n", "file_path": "tests/number_range.rs", "rank": 16, "score": 17555.962083633454 }, { "content": "use clap::Clap;\n\nuse clap_num::number_range;\n\n\n\n// standalone basic tests\n\n#[cfg(test)]\n\nmod basic {\n\n use super::*;\n\n\n\n macro_rules! pos {\n\n ($NAME:ident, $VAL:expr, $MIN:expr, $MAX:expr, $RESULT:expr) => {\n\n #[test]\n\n fn $NAME() {\n\n assert_eq!(number_range($VAL, $MIN, $MAX), Ok($RESULT));\n\n }\n\n };\n\n }\n\n\n\n macro_rules! neg {\n\n ($NAME:ident, $VAL:expr, $MIN:expr, $MAX:expr, $RESULT:expr) => {\n\n #[test]\n", "file_path": "tests/number_range.rs", "rank": 17, "score": 17554.169499169 }, { "content": " fn $NAME() {\n\n assert_eq!(number_range($VAL, $MIN, $MAX), Err(String::from($RESULT)));\n\n }\n\n };\n\n }\n\n\n\n pos!(simple, \"123\", 12u8, 200u8, 123u8);\n\n pos!(zero, \"0\", 0u8, 0u8, 0u8);\n\n pos!(neg, \"-1\", -10i8, 10i8, -1);\n\n pos!(min_limit, \"-5\", -5i8, -5i8, -5i8);\n\n pos!(max_limit, \"65535\", 0, std::u16::MAX, std::u16::MAX);\n\n\n\n neg!(decimal, \"1.1\", -10i8, 10i8, \"invalid digit found in string\");\n\n neg!(min, \"-1\", 0i8, 0i8, \"exceeds minimum of 0\");\n\n neg!(max, \"1\", 0i8, 0i8, \"exceeds maximum of 0\");\n\n neg!(\n\n overflow,\n\n \"256\",\n\n 0,\n\n std::u8::MAX,\n", "file_path": "tests/number_range.rs", "rank": 18, "score": 17553.746479553258 }, { "content": " fn $NAME() {\n\n let num: Result<$TYPE, String> = si_number($VAL);\n\n assert_eq!(num, Err(String::from($RESULT)));\n\n }\n\n };\n\n }\n\n\n\n // basic positive path\n\n pos!(zero, \"0\", 0u8);\n\n pos!(one, \"1\", 1u8);\n\n pos!(neg_one, \"-1\", -1i8);\n\n pos!(limit, \"255\", 255u8);\n\n\n\n // basic positive path with Si suffix\n\n pos!(kilo, \"1k\", 1_000u16);\n\n pos!(mega, \"1M\", 1_000_000u32);\n\n pos!(giga, \"1G\", 1_000_000_000u64);\n\n pos!(tera, \"1T\", 1_000_000_000_000u64);\n\n pos!(peta, \"1P\", 1_000_000_000_000_000u64);\n\n pos!(exa, \"1E\", 1_000_000_000_000_000_000u64);\n", "file_path": "tests/si_number.rs", "rank": 19, "score": 17553.476789576896 }, { "content": " u8,\n\n \"number too large to fit in target type\"\n\n );\n\n\n\n neg!(multiple_suffix, \"1kk\", u16, \"invalid digit found in string\");\n\n}\n\n\n\n// integration tests with clap\n\n#[cfg(test)]\n\nmod integration {\n\n use super::*;\n\n\n\n #[derive(Clap)]\n\n struct Args {\n\n #[clap(long, parse(try_from_str=si_number))]\n\n resistance: u128,\n\n }\n\n\n\n // positive path\n\n macro_rules! pos {\n", "file_path": "tests/si_number.rs", "rank": 20, "score": 17553.463484733587 }, { "content": "use clap::Clap;\n\nuse clap_num::si_number;\n\n\n\n// standalone basic tests\n\n#[cfg(test)]\n\nmod basic {\n\n use super::*;\n\n\n\n macro_rules! pos {\n\n ($NAME:ident, $VAL:expr, $RESULT:expr) => {\n\n #[test]\n\n fn $NAME() {\n\n assert_eq!(si_number($VAL), Ok($RESULT));\n\n }\n\n };\n\n }\n\n\n\n macro_rules! neg {\n\n ($NAME:ident, $VAL:expr, $TYPE:ident, $RESULT:expr) => {\n\n #[test]\n", "file_path": "tests/si_number.rs", "rank": 21, "score": 17551.617470029567 }, { "content": "\n\n // negative path\n\n macro_rules! neg {\n\n ($NAME:ident, $VAL:expr, $RESULT:expr) => {\n\n #[test]\n\n fn $NAME() {\n\n let opt = Thermostat::try_parse_from(&[\"\", \"--temperature\", $VAL]);\n\n match opt {\n\n Err(e) => {\n\n assert!(format!(\"{:?}\", e).contains($RESULT));\n\n }\n\n _ => unreachable!(),\n\n };\n\n }\n\n };\n\n }\n\n\n\n pos!(simple, \"50\", 50);\n\n pos!(zero, \"0\", 0);\n\n pos!(negative, \"-30\", -30);\n\n pos!(positive_limit, \"60\", 60);\n\n pos!(negative_limit, \"-40\", -40);\n\n\n\n neg!(too_small, \"-41\", \"exceeds minimum of -40\");\n\n neg!(too_large, \"61\", \"exceeds maximum of 60\");\n\n}\n", "file_path": "tests/number_range.rs", "rank": 22, "score": 17550.65767366596 }, { "content": "\n\n pos!(dec_ending_si, \"1.k\", 1_000u16);\n\n\n\n neg!(mixed_1, \"1K23.45\", u16, \"invalid digit found in string\");\n\n neg!(mixed_2, \"1.23k45\", u16, \"invalid digit found in string\");\n\n\n\n neg!(trailing_dec, \"1.\", u8, \"invalid digit found in string\");\n\n\n\n pos!(\n\n big,\n\n \"1Y123456789987654321\",\n\n 1_123_456_789_987_654_321_000_000u128\n\n );\n\n\n\n neg!(leading_si, \"k1\", u16, \"no value found before SI symbol\");\n\n\n\n neg!(overflow, \"1k\", u8, \"number too large to fit in target type\");\n\n neg!(\n\n normal_overflow,\n\n \"300\",\n", "file_path": "tests/si_number.rs", "rank": 23, "score": 17550.28329997542 }, { "content": " ($NAME:ident, $VAL:expr, $RESULT:expr) => {\n\n #[test]\n\n fn $NAME() {\n\n let opt = Args::parse_from(&[\"\", \"--resistance\", $VAL]);\n\n assert_eq!(opt.resistance, $RESULT);\n\n }\n\n };\n\n }\n\n\n\n // negative path\n\n macro_rules! neg {\n\n ($NAME:ident, $VAL:expr, $RESULT:expr) => {\n\n #[test]\n\n fn $NAME() {\n\n let opt = Args::try_parse_from(&[\"\", \"--resistance\", $VAL]);\n\n match opt {\n\n Err(e) => {\n\n assert!(format!(\"{:?}\", e).contains($RESULT));\n\n }\n\n _ => unreachable!(),\n", "file_path": "tests/si_number.rs", "rank": 24, "score": 17547.239217335995 }, { "content": " #[derive(Clap, Debug)]\n\n struct Thermostat {\n\n #[clap(\n\n long,\n\n parse(try_from_str=human_livable_temperature),\n\n allow_hyphen_values=true\n\n )]\n\n temperature: i8,\n\n }\n\n\n\n // positive path\n\n macro_rules! pos {\n\n ($NAME:ident, $VAL:expr, $RESULT:expr) => {\n\n #[test]\n\n fn $NAME() {\n\n let opt = Thermostat::parse_from(&[\"\", \"--temperature\", $VAL]);\n\n assert_eq!(opt.temperature, $RESULT);\n\n }\n\n };\n\n }\n", "file_path": "tests/number_range.rs", "rank": 25, "score": 17546.719591915968 }, { "content": " pos!(zetta, \"1Z\", 1_000_000_000_000_000_000_000u128);\n\n pos!(yotta, \"1Y\", 1_000_000_000_000_000_000_000_000u128);\n\n\n\n pos!(trailing_1, \"1k2\", 1_200u16);\n\n pos!(trailing_2, \"1k23\", 1_230u16);\n\n pos!(trailing_3, \"1k234\", 1_234u16);\n\n neg!(trailing_4, \"1k2345\", u16, \"not an integer\");\n\n pos!(trailing_do_nothing, \"1k000\", 1_000u16);\n\n pos!(negative_trailing, \"-1k234\", -1_234i16);\n\n\n\n pos!(leading_2, \"12k123\", 12_123u16);\n\n pos!(leading_3, \"123k123\", 123_123u32);\n\n pos!(leading_4, \"1234k123\", 1_234_123i32);\n\n pos!(negative_leading, \"-123k123\", -123_123i32);\n\n\n\n pos!(dec_1, \"1.2k\", 1_200u16);\n\n pos!(dec_2, \"1.23k\", 1_230u16);\n\n pos!(dec_3, \"1.234k\", 1_234u16);\n\n neg!(dec_4, \"1.2345k\", u16, \"not an integer\");\n\n pos!(dec_do_nothing, \"1.000k\", 1_000u16);\n", "file_path": "tests/si_number.rs", "rank": 26, "score": 17546.22568406502 }, { "content": " };\n\n }\n\n };\n\n }\n\n\n\n pos!(simple_0, \"1k123\", 1123);\n\n pos!(simple_1, \"456789k123\", 456789123);\n\n pos!(simple_2, \"1M1\", 1_100_000);\n\n\n\n neg!(big, \"999999999999999999999Y\", \"too large\");\n\n neg!(invalid, \"1k1k\", \"invalid digit\");\n\n neg!(precise, \"1k1111\", \"not an integer\");\n\n neg!(leading_prefix, \"k123\", \"no value found before SI symbol\");\n\n}\n", "file_path": "tests/si_number.rs", "rank": 27, "score": 17545.08760143218 }, { "content": "// See https://crates.io/crates/version-sync\n\n\n\n#[test]\n", "file_path": "tests/version-numbers.rs", "rank": 28, "score": 17543.518778618465 }, { "content": "![Maintenance](https://img.shields.io/badge/maintenance-as--is-yellow.svg)\n\n[![crates.io](https://img.shields.io/crates/v/clap-num.svg)](https://crates.io/crates/clap-num)\n\n[![docs.rs](https://docs.rs/clap-num/badge.svg)](https://docs.rs/clap-num/)\n\n[![Build Status](https://github.com/newAM/clap-num/workflows/CI/badge.svg)](https://github.com/newAM/clap-num/actions)\n\n\n\n# clap-num\n\n\n\nclap V3 number parsers.\n\n\n\nThis crate contains functions to validate and parse numerical values from\n\nstrings provided by [clap v3].\n\n\n\n## Example\n\n\n\nThis example allow values for `--frequency` between 800 Hz and 3.333 MHz,\n\nwith SI symbols.\n\n\n\n```rust\n\nuse clap::Clap;\n\nuse clap_num::si_number_range;\n\n\n\nfn frequency(s: &str) -> Result<u32, String> {\n\n si_number_range(s, 800, 3_333_000)\n\n}\n\n\n\n#[derive(Clap, Debug)]\n\nstruct Args {\n\n #[clap(short, long, parse(try_from_str=frequency))]\n\n frequency: Option<u32>,\n\n}\n\n\n\nlet args = Args::parse();\n\nprintln!(\"{:?}\", args);\n\n```\n\n\n\n[clap v3]: https://github.com/clap-rs/clap\n", "file_path": "README.md", "rank": 29, "score": 12623.308211480049 }, { "content": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\n\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\n\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n\n\n## [Unreleased]\n\n### Fixed\n\n- Fixed typos in documentation.\n\n\n\n## [0.2.0] - 2020-10-18\n\n### Added\n\n- Added `maybe_hex` and `maybe_hex_range` functions.\n\n- Added a changelog.\n\n\n\n[Unreleased]: https://github.com/newAM/clap-num/compare/0.2.0...HEAD\n\n[0.2.0]: https://github.com/newAM/clap-num/releases/tag/0.2.0\n\n\n", "file_path": "CHANGELOG.md", "rank": 30, "score": 12618.414658895901 }, { "content": "use clap::Clap;\n\nuse clap_num::number_range;\n\n\n", "file_path": "examples/change.rs", "rank": 32, "score": 6.178412258345768 }, { "content": "use clap::Clap;\n\nuse clap_num::si_number;\n\n\n\n#[derive(Clap)]\n", "file_path": "examples/resistance.rs", "rank": 33, "score": 5.994221035379587 }, { "content": " fn $NAME() {\n\n let val: Result<u64, String> = maybe_hex($VAL);\n\n assert_eq!(val, Err(String::from($RESULT)));\n\n }\n\n };\n\n }\n\n\n\n pos!(simple, \"123\", 123u8);\n\n pos!(zero_dec, \"0\", 0u16);\n\n pos!(zero_hex, \"0x0\", 0u16);\n\n pos!(one_dec, \"1\", 1u64);\n\n pos!(one_hex, \"0x1\", 1u64);\n\n pos!(leading_zero, \"001\", 1u64);\n\n pos!(case, \"0XABcDE\", 703710u32);\n\n\n\n neg!(\n\n missing_suffix,\n\n \"0x\",\n\n \"cannot parse integer from empty string\"\n\n );\n\n neg!(dec_with_hex, \"1A\", \"invalid digit found in string\");\n\n neg!(non_hex_digit, \"0x12G\", \"invalid digit found in string\");\n\n}\n", "file_path": "tests/maybe_hex.rs", "rank": 35, "score": 5.049022098868902 }, { "content": "use clap_num::maybe_hex;\n\n\n\n#[cfg(test)]\n\nmod basic {\n\n use super::*;\n\n\n\n // positive path\n\n macro_rules! pos {\n\n ($NAME:ident, $VAL:expr, $RESULT:expr) => {\n\n #[test]\n\n fn $NAME() {\n\n assert_eq!(maybe_hex($VAL), Ok($RESULT));\n\n }\n\n };\n\n }\n\n\n\n // negative path\n\n macro_rules! neg {\n\n ($NAME:ident, $VAL:expr, $RESULT:expr) => {\n\n #[test]\n", "file_path": "tests/maybe_hex.rs", "rank": 36, "score": 5.03284685743152 } ]
Rust
game/src/sandbox/score.rs
jinzhong2/abstreet
e1c5edc76d636af4f3e4593efc25055bdd637dd7
use crate::game::{State, Transition, WizardState}; use crate::sandbox::gameplay::{cmp_count_fewer, cmp_count_more, cmp_duration_shorter}; use crate::ui::UI; use abstutil::prettyprint_usize; use ezgui::{ hotkey, Choice, Color, EventCtx, GfxCtx, HorizontalAlignment, Key, Line, ModalMenu, Text, VerticalAlignment, Wizard, }; use geom::{Duration, Statistic}; use sim::{TripID, TripMode}; use std::collections::BTreeSet; pub struct Scoreboard { menu: ModalMenu, summary: Text, } impl Scoreboard { pub fn new(ctx: &mut EventCtx, ui: &UI) -> Scoreboard { let menu = ModalMenu::new( "Finished trips summary", vec![ (hotkey(Key::Escape), "quit"), (hotkey(Key::B), "browse trips"), ], ctx, ); let (now_all, now_aborted, now_per_mode) = ui .primary .sim .get_analytics() .all_finished_trips(ui.primary.sim.time()); let (baseline_all, baseline_aborted, baseline_per_mode) = ui.prebaked.all_finished_trips(ui.primary.sim.time()); let mut txt = Text::new(); txt.add_appended(vec![ Line("Finished trips as of "), Line(ui.primary.sim.time().ampm_tostring()).fg(Color::CYAN), ]); txt.add_appended(vec![ Line(format!( " {} aborted trips (", prettyprint_usize(now_aborted) )), cmp_count_fewer(now_aborted, baseline_aborted), Line(")"), ]); txt.add_appended(vec![ Line(format!( "{} total finished trips (", prettyprint_usize(now_all.count()) )), cmp_count_more(now_all.count(), baseline_all.count()), Line(")"), ]); if now_all.count() > 0 && baseline_all.count() > 0 { for stat in Statistic::all() { txt.add(Line(format!( " {}: {} ", stat, now_all.select(stat).minimal_tostring() ))); txt.append_all(cmp_duration_shorter( now_all.select(stat), baseline_all.select(stat), )); } } for mode in TripMode::all() { let a = &now_per_mode[&mode]; let b = &baseline_per_mode[&mode]; txt.add_appended(vec![ Line(format!("{} {} trips (", prettyprint_usize(a.count()), mode)), cmp_count_more(a.count(), b.count()), Line(")"), ]); if a.count() > 0 && b.count() > 0 { for stat in Statistic::all() { txt.add(Line(format!( " {}: {} ", stat, a.select(stat).minimal_tostring() ))); txt.append_all(cmp_duration_shorter(a.select(stat), b.select(stat))); } } } Scoreboard { menu, summary: txt } } } impl State for Scoreboard { fn event(&mut self, ctx: &mut EventCtx, _: &mut UI) -> Transition { self.menu.event(ctx); if self.menu.action("quit") { return Transition::Pop; } if self.menu.action("browse trips") { return Transition::Push(WizardState::new(Box::new(browse_trips))); } Transition::Keep } fn draw(&self, g: &mut GfxCtx, _: &UI) { g.draw_blocking_text( &self.summary, (HorizontalAlignment::Center, VerticalAlignment::Center), ); self.menu.draw(g); } } fn browse_trips(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> { let mut wizard = wiz.wrap(ctx); let (_, mode) = wizard.choose("Browse which trips?", || { let trips = ui.primary.sim.get_finished_trips(); let modes = trips .finished_trips .iter() .map(|(_, m, _)| *m) .collect::<BTreeSet<TripMode>>(); TripMode::all() .into_iter() .map(|m| Choice::new(m.to_string(), m).active(modes.contains(&m))) .collect() })?; wizard.choose("Examine which trip?", || { let trips = ui.primary.sim.get_finished_trips(); let mut filtered: Vec<&(TripID, TripMode, Duration)> = trips .finished_trips .iter() .filter(|(_, m, _)| *m == mode) .collect(); filtered.sort_by_key(|(_, _, dt)| *dt); filtered.reverse(); filtered .into_iter() .map(|(id, _, dt)| Choice::new(format!("{} taking {}", id, dt), *id)) .collect() })?; Some(Transition::Pop) }
use crate::game::{State, Transition, WizardState}; use crate::sandbox::gameplay::{cmp_count_fewer, cmp_count_more, cmp_duration_shorter}; use crate::ui::UI; use abstutil::prettyprint_usize; use ezgui::{ hotkey, Choice, Color, EventCtx, GfxCtx, HorizontalAlignment, Key, Line, ModalMenu, Text, VerticalAlignment, Wizard, }; use geom::{Duration, Statistic}; use sim::{TripID, TripMode}; use std::collections::BTreeSet; pub struct Scoreboard { menu: ModalMenu, summary: Text, } impl Scoreboard { pub fn new(ctx: &mut EventCtx, ui: &UI) -> Scoreboard { let menu = ModalMenu::new( "Finished trips summary", vec![ (hotkey(Key::Escape), "quit"), (hotkey(Key::B), "browse trips"), ], ctx, ); let (now_all, now_aborted, now_per_mode) = ui .primary .sim .get_analytics() .all_finished_trips(ui.primary.sim.time()); let (baseline_all, baseline_aborted, baseline_per_mode) = ui.prebaked.all_finished_trips(ui.primary.sim.time()); let mut txt = Text::new(); txt.add_appended(vec![ Line("Finished trips as of "), Line(ui.primary.sim.time().ampm_tostring()).fg(Color::CYAN), ]); txt.add_appended(vec![ Line(format!( " {} aborted trips (", prettyprint_usize(now_aborted) )), cmp_count_fewer(now_aborted, baseline_aborted), Line(")"), ]); txt.add_appended(vec![ Line(format!( "{} total finished trips (", prettyprint_usize(now_all.count()) )), cmp_count_more(now_all.count(), baseline_all.count()), Line(")"), ]); if now_all.count() > 0 && baseline_all.count() > 0 { for stat in Statistic::all() { txt.add(Line(format!( " {}: {} ", stat, now_all.select(stat).minimal_tostring() ))); txt.append_all(cmp_duration_shorter( now_all.select(stat), baseline_all.select(stat), )); } } for mode in TripMode::all() { let a = &now_per_mode[&mode]; let b = &baseline_per_mode[&mode]; txt.add_appended(vec![ Line(format!("{} {} trips (", prettyprint_usize(a.count()), mode)), cmp_count_more(a.count(), b.count()), Line(")"), ]); if a.count() > 0 && b.count() > 0 { for stat in Statistic::all() { txt.add(Line(format!( " {}: {} ", stat, a.select(stat).minimal_tostring() ))); txt.append_all(cmp_duration_shorter(a.select(stat), b.select(stat))); } } } Scoreboard { menu, summary: txt } } } impl State for Scoreboard { fn event(&mut self, ctx: &mut EventCtx, _: &mut UI) -> Transition { self.menu.event(ctx); if self.menu.action("quit") {
fn draw(&self, g: &mut GfxCtx, _: &UI) { g.draw_blocking_text( &self.summary, (HorizontalAlignment::Center, VerticalAlignment::Center), ); self.menu.draw(g); } } fn browse_trips(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> { let mut wizard = wiz.wrap(ctx); let (_, mode) = wizard.choose("Browse which trips?", || { let trips = ui.primary.sim.get_finished_trips(); let modes = trips .finished_trips .iter() .map(|(_, m, _)| *m) .collect::<BTreeSet<TripMode>>(); TripMode::all() .into_iter() .map(|m| Choice::new(m.to_string(), m).active(modes.contains(&m))) .collect() })?; wizard.choose("Examine which trip?", || { let trips = ui.primary.sim.get_finished_trips(); let mut filtered: Vec<&(TripID, TripMode, Duration)> = trips .finished_trips .iter() .filter(|(_, m, _)| *m == mode) .collect(); filtered.sort_by_key(|(_, _, dt)| *dt); filtered.reverse(); filtered .into_iter() .map(|(id, _, dt)| Choice::new(format!("{} taking {}", id, dt), *id)) .collect() })?; Some(Transition::Pop) }
return Transition::Pop; } if self.menu.action("browse trips") { return Transition::Push(WizardState::new(Box::new(browse_trips))); } Transition::Keep }
function_block-function_prefix_line
[ { "content": "fn pick_color(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {\n\n let name = wiz\n\n .wrap(ctx)\n\n .choose_string(\"Change which color?\", || ui.cs.color_names())?;\n\n Some(Transition::Replace(Box::new(ColorChanger {\n\n name: name.clone(),\n\n original: ui.cs.get_modified(&name),\n\n menu: ModalMenu::new(\n\n &format!(\"Color Picker for {}\", name),\n\n vec![\n\n (hotkey(Key::Backspace), \"revert\"),\n\n (hotkey(Key::Escape), \"finalize\"),\n\n ],\n\n ctx,\n\n ),\n\n })))\n\n}\n\n\n", "file_path": "game/src/debug/color_picker.rs", "rank": 0, "score": 469391.84547574806 }, { "content": "fn browse_trips(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {\n\n let mut wizard = wiz.wrap(ctx);\n\n let mode = wizard\n\n .choose(\"Browse which trips?\", || {\n\n let trips = CompareTrips::new(\n\n ui.primary.sim.get_finished_trips(),\n\n ui.secondary.as_ref().unwrap().sim.get_finished_trips(),\n\n );\n\n let modes = trips\n\n .finished_trips\n\n .iter()\n\n .map(|(_, m, _, _)| *m)\n\n .collect::<BTreeSet<TripMode>>();\n\n TripMode::all()\n\n .into_iter()\n\n .map(|m| Choice::new(m.to_string(), m).active(modes.contains(&m)))\n\n .collect()\n\n })?\n\n .1;\n\n wizard.choose(\"Examine which trip?\", || {\n", "file_path": "game/src/abtest/score.rs", "rank": 2, "score": 460723.0853968681 }, { "content": "fn splash_screen(raw_wizard: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {\n\n let mut wizard = raw_wizard.wrap(ctx);\n\n let sandbox = \"Sandbox mode\";\n\n let challenge = \"Challenge mode\";\n\n let abtest = \"A/B Test Mode (internal/unfinished)\";\n\n let tutorial = \"Tutorial (unfinished)\";\n\n let mission = \"Internal developer tools\";\n\n let about = \"About\";\n\n let quit = \"Quit\";\n\n\n\n let dev = ui.primary.current_flags.dev;\n\n\n\n match wizard\n\n .choose(\"Welcome to A/B Street!\", || {\n\n vec![\n\n Some(Choice::new(sandbox, ()).key(Key::S)),\n\n Some(Choice::new(challenge, ()).key(Key::C)),\n\n if dev {\n\n Some(Choice::new(abtest, ()).key(Key::A))\n\n } else {\n", "file_path": "game/src/splash_screen.rs", "rank": 3, "score": 434944.1580555311 }, { "content": "fn warp_to(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {\n\n let mut wizard = wiz.wrap(ctx);\n\n let to = wizard.input_string(\"Warp to what?\")?;\n\n if let Some((id, pt, cam_zoom)) = warp_point(&to, &ui.primary) {\n\n return Some(Transition::ReplaceWithMode(\n\n Warping::new(ctx, pt, Some(cam_zoom), id, &mut ui.primary),\n\n EventLoopMode::Animation,\n\n ));\n\n }\n\n wizard.acknowledge(\"Bad warp ID\", || vec![format!(\"{} isn't a valid ID\", to)])?;\n\n Some(Transition::Pop)\n\n}\n\n\n\npub struct Warping {\n\n warper: Warper,\n\n id: Option<ID>,\n\n}\n\n\n\nimpl Warping {\n\n pub fn new(\n", "file_path": "game/src/common/warp.rs", "rank": 4, "score": 429930.2773317317 }, { "content": "fn jump_to_time(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {\n\n let t = wiz.wrap(ctx).input_time_slider(\n\n \"Jump to what time?\",\n\n ui.primary.sim.time(),\n\n Duration::END_OF_DAY,\n\n )?;\n\n let dt = t - ui.primary.sim.time();\n\n ctx.loading_screen(&format!(\"step forwards {}\", dt), |_, mut timer| {\n\n ui.primary.sim.timed_step(&ui.primary.map, dt, &mut timer);\n\n if let Some(ref mut s) = ui.secondary {\n\n s.sim.timed_step(&s.map, dt, &mut timer);\n\n }\n\n });\n\n Some(Transition::Pop)\n\n}\n", "file_path": "game/src/common/time.rs", "rank": 5, "score": 425683.857977089 }, { "content": "fn load_scenario(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {\n\n let map_name = ui.primary.map.get_name().to_string();\n\n let s = wiz.wrap(ctx).choose_string(\"Load which scenario?\", || {\n\n abstutil::list_all_objects(abstutil::SCENARIOS, &map_name)\n\n })?;\n\n let scenario = abstutil::read_binary(\n\n &abstutil::path1_bin(&map_name, abstutil::SCENARIOS, &s),\n\n &mut Timer::throwaway(),\n\n )\n\n .unwrap();\n\n Some(Transition::Replace(Box::new(\n\n scenario::ScenarioManager::new(scenario, ctx, ui),\n\n )))\n\n}\n\n\n", "file_path": "game/src/mission/mod.rs", "rank": 6, "score": 425683.857977089 }, { "content": "fn search_osm(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {\n\n let filter = wiz.wrap(ctx).input_string(\"Search for what?\")?;\n\n let mut ids = HashSet::new();\n\n let mut batch = GeomBatch::new();\n\n\n\n let map = &ui.primary.map;\n\n let color = ui.cs.get_def(\"search result\", Color::RED);\n\n for r in map.all_roads() {\n\n if r.osm_tags\n\n .iter()\n\n .any(|(k, v)| format!(\"{} = {}\", k, v).contains(&filter))\n\n {\n\n for l in r.all_lanes() {\n\n ids.insert(ID::Lane(l));\n\n }\n\n batch.push(color, r.get_thick_polygon().unwrap());\n\n }\n\n }\n\n for b in map.all_buildings() {\n\n if b.osm_tags\n", "file_path": "game/src/debug/mod.rs", "rank": 7, "score": 425683.857977089 }, { "content": "fn load_edits(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {\n\n let mut wizard = wiz.wrap(ctx);\n\n\n\n if ui.primary.map.get_edits().dirty {\n\n let save = \"save edits\";\n\n let discard = \"discard\";\n\n if wizard\n\n .choose_string(\"Save current edits first?\", || vec![save, discard])?\n\n .as_str()\n\n == save\n\n {\n\n save_edits(&mut wizard, ui)?;\n\n wizard.reset();\n\n }\n\n }\n\n\n\n // TODO Exclude current\n\n let map_name = ui.primary.map.get_name().to_string();\n\n let (_, new_edits) = wizard.choose(\"Load which map edits?\", || {\n\n let mut list = Choice::from(abstutil::load_all_objects(abstutil::EDITS, &map_name));\n\n list.push(Choice::new(\"no_edits\", MapEdits::new(map_name.clone())));\n\n list\n\n })?;\n\n apply_map_edits(&mut ui.primary, &ui.cs, ctx, new_edits);\n\n ui.primary.map.mark_edits_fresh();\n\n Some(Transition::Pop)\n\n}\n\n\n", "file_path": "game/src/edit/mod.rs", "rank": 8, "score": 425683.857977089 }, { "content": "fn load_savestate(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {\n\n let path = ui.primary.sim.save_dir();\n\n\n\n let ss = wiz.wrap(ctx).choose_string(\"Load which savestate?\", || {\n\n abstutil::list_dir(std::path::Path::new(&path))\n\n })?;\n\n\n\n ctx.loading_screen(\"load savestate\", |ctx, mut timer| {\n\n ui.primary.sim = Sim::load_savestate(ss, &mut timer).expect(\"Can't load savestate\");\n\n ui.recalculate_current_selection(ctx);\n\n });\n\n Some(Transition::Pop)\n\n}\n", "file_path": "game/src/sandbox/mod.rs", "rank": 9, "score": 425683.857977089 }, { "content": "fn choose_shortcut(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {\n\n let center = ctx\n\n .canvas\n\n .center_to_map_pt()\n\n .forcibly_to_gps(&ui.primary.map.get_gps_bounds());\n\n let cam_zoom = ctx.canvas.cam_zoom;\n\n\n\n let mut wizard = wiz.wrap(ctx);\n\n let (_, mut s) = wizard.choose(\"Jump to which shortcut?\", || {\n\n // TODO Handle >9\n\n // TODO Allow deleting\n\n let keys = vec![\n\n Key::Num1,\n\n Key::Num2,\n\n Key::Num3,\n\n Key::Num4,\n\n Key::Num5,\n\n Key::Num6,\n\n Key::Num7,\n\n Key::Num8,\n", "file_path": "game/src/common/shortcuts.rs", "rank": 10, "score": 425683.857977089 }, { "content": "fn change_scenario(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {\n\n let num_agents = ui.primary.current_flags.num_agents;\n\n let builtin = if let Some(n) = num_agents {\n\n format!(\"random scenario with {} agents\", n)\n\n } else {\n\n \"random scenario with some agents\".to_string()\n\n };\n\n let scenario_name = wiz\n\n .wrap(ctx)\n\n .choose_string(\"Instantiate which scenario?\", || {\n\n let mut list =\n\n abstutil::list_all_objects(abstutil::SCENARIOS, ui.primary.map.get_name());\n\n list.push(builtin.clone());\n\n list.push(\"just buses\".to_string());\n\n list\n\n })?;\n\n Some(Transition::PopThenReplace(Box::new(SandboxMode::new(\n\n ctx,\n\n ui,\n\n GameplayMode::PlayScenario(scenario_name),\n\n ))))\n\n}\n\n\n", "file_path": "game/src/sandbox/gameplay/mod.rs", "rank": 11, "score": 421580.9841398108 }, { "content": "fn create_new_scenario(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {\n\n let name = wiz.wrap(ctx).input_string(\"Name the scenario\")?;\n\n let mut s = Scenario::empty(&ui.primary.map);\n\n s.seed_buses = true;\n\n s.scenario_name = name;\n\n Some(Transition::Replace(Box::new(\n\n scenario::ScenarioManager::new(s, ctx, ui),\n\n )))\n\n}\n\n\n", "file_path": "game/src/mission/mod.rs", "rank": 12, "score": 421580.9841398109 }, { "content": "fn pick_ab_test(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {\n\n let mut wizard = wiz.wrap(ctx);\n\n let load_existing = \"Load existing A/B test\";\n\n let create_new = \"Create new A/B test\";\n\n let ab_test = if wizard.choose_string(\"What A/B test to manage?\", || {\n\n vec![load_existing, create_new]\n\n })? == load_existing\n\n {\n\n wizard\n\n .choose(\"Load which A/B test?\", || {\n\n Choice::from(abstutil::load_all_objects(\n\n abstutil::AB_TESTS,\n\n ui.primary.map.get_name(),\n\n ))\n\n })?\n\n .1\n\n } else {\n\n let test_name = wizard.input_string(\"Name the A/B test\")?;\n\n let map_name = ui.primary.map.get_name();\n\n\n", "file_path": "game/src/abtest/setup.rs", "rank": 13, "score": 421580.98413981084 }, { "content": "fn load_map(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {\n\n if let Some(name) = wiz.wrap(ctx).choose_string(\"Load which map?\", || {\n\n let current_map = ui.primary.map.get_name();\n\n abstutil::list_all_objects(\"maps\", \"\")\n\n .into_iter()\n\n .filter(|n| n != current_map)\n\n .collect()\n\n }) {\n\n ui.switch_map(ctx, &name);\n\n Some(Transition::PopThenReplace(Box::new(SandboxMode::new(\n\n ctx,\n\n ui,\n\n // TODO If we were playing a scenario, load that one...\n\n GameplayMode::Freeform,\n\n ))))\n\n } else if wiz.aborted() {\n\n Some(Transition::Pop)\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "game/src/sandbox/gameplay/mod.rs", "rank": 14, "score": 421580.9841398108 }, { "content": "pub fn faster_trips_panel(mode: TripMode, ui: &UI) -> Text {\n\n let time = ui.primary.sim.time();\n\n let now = ui.primary.sim.get_analytics().finished_trips(time, mode);\n\n let baseline = ui.prebaked.finished_trips(time, mode);\n\n\n\n // Enable to debug why sim results don't match prebaked.\n\n if false && !now.seems_eq(&baseline) {\n\n abstutil::write_json(\n\n \"../current_sim.json\",\n\n &ui.primary.sim.get_analytics().finished_trips,\n\n )\n\n .unwrap();\n\n let filtered = ui\n\n .prebaked\n\n .finished_trips\n\n .iter()\n\n .filter(|(t, _, _, _)| *t <= time)\n\n .cloned()\n\n .collect::<Vec<_>>();\n\n abstutil::write_json(\"../prebaked.json\", &filtered).unwrap();\n", "file_path": "game/src/sandbox/gameplay/faster_trips.rs", "rank": 15, "score": 416868.61594283406 }, { "content": "pub fn save_edits(wizard: &mut WrappedWizard, ui: &mut UI) -> Option<()> {\n\n let map = &mut ui.primary.map;\n\n\n\n let rename = if map.get_edits().edits_name == \"no_edits\" {\n\n Some(wizard.input_string(\"Name these map edits\")?)\n\n } else {\n\n None\n\n };\n\n // TODO Don't allow naming them no_edits!\n\n\n\n // TODO Do it this weird way to avoid saving edits on every event. :P\n\n // TODO Do some kind of versioning? Don't ask this if the file doesn't exist yet?\n\n let save = \"save edits\";\n\n let cancel = \"cancel\";\n\n if wizard\n\n .choose_string(\"Overwrite edits?\", || vec![save, cancel])?\n\n .as_str()\n\n == save\n\n {\n\n if let Some(name) = rename {\n\n let mut edits = map.get_edits().clone();\n\n edits.edits_name = name;\n\n map.apply_edits(edits, &mut Timer::new(\"name map edits\"));\n\n }\n\n map.save_edits();\n\n }\n\n Some(())\n\n}\n\n\n", "file_path": "game/src/edit/mod.rs", "rank": 16, "score": 375298.1232267339 }, { "content": "pub fn spawn_agents_around(i: IntersectionID, ui: &mut UI, ctx: &EventCtx) {\n\n let map = &ui.primary.map;\n\n let sim = &mut ui.primary.sim;\n\n let mut rng = ui.primary.current_flags.sim_flags.make_rng();\n\n\n\n for l in &map.get_i(i).incoming_lanes {\n\n let lane = map.get_l(*l);\n\n if lane.is_driving() || lane.is_biking() {\n\n for _ in 0..10 {\n\n let vehicle_spec = if rng.gen_bool(0.7) && lane.is_driving() {\n\n Scenario::rand_car(&mut rng)\n\n } else {\n\n Scenario::rand_bike(&mut rng)\n\n };\n\n if vehicle_spec.length > lane.length() {\n\n continue;\n\n }\n\n sim.schedule_trip(\n\n sim.time(),\n\n TripSpec::CarAppearing {\n", "file_path": "game/src/sandbox/gameplay/spawner.rs", "rank": 17, "score": 373050.42673103453 }, { "content": "fn launch_test(test: &ABTest, ui: &mut UI, ctx: &mut EventCtx) -> ABTestMode {\n\n let secondary = ctx.loading_screen(\n\n &format!(\"Launching A/B test {}\", test.test_name),\n\n |ctx, mut timer| {\n\n let scenario: Scenario = abstutil::read_binary(\n\n &abstutil::path1_bin(&test.map_name, abstutil::SCENARIOS, &test.scenario_name),\n\n &mut timer,\n\n )\n\n .expect(\"loading scenario failed\");\n\n\n\n {\n\n timer.start(\"load primary\");\n\n if ui.primary.current_flags.sim_flags.rng_seed.is_none() {\n\n ui.primary.current_flags.sim_flags.rng_seed = Some(42);\n\n }\n\n ui.primary.current_flags.sim_flags.opts.run_name =\n\n format!(\"{} with {}\", test.test_name, test.edits1_name);\n\n ui.primary.current_flags.sim_flags.opts.savestate_every = None;\n\n\n\n apply_map_edits(\n", "file_path": "game/src/abtest/setup.rs", "rank": 18, "score": 357893.03784804826 }, { "content": "// For easy ModalMenu construction\n\npub fn hotkey(key: Key) -> Option<MultiKey> {\n\n Some(MultiKey { key, lctrl: false })\n\n}\n\n\n", "file_path": "ezgui/src/event.rs", "rank": 19, "score": 353982.7012900219 }, { "content": "fn bus_route_panel(id: BusRouteID, ui: &UI, stat: Statistic) -> Text {\n\n let now = ui\n\n .primary\n\n .sim\n\n .get_analytics()\n\n .bus_arrivals(ui.primary.sim.time(), id);\n\n let baseline = ui.prebaked.bus_arrivals(ui.primary.sim.time(), id);\n\n\n\n let route = ui.primary.map.get_br(id);\n\n let mut txt = Text::new();\n\n txt.add(Line(format!(\"{} delay between stops\", stat)));\n\n for idx1 in 0..route.stops.len() {\n\n let idx2 = if idx1 == route.stops.len() - 1 {\n\n 0\n\n } else {\n\n idx1 + 1\n\n };\n\n // TODO Also display number of arrivals...\n\n txt.add(Line(format!(\"Stop {}->{}: \", idx1 + 1, idx2 + 1)));\n\n if let Some(ref stats1) = now.get(&route.stops[idx2]) {\n", "file_path": "game/src/sandbox/gameplay/optimize_bus.rs", "rank": 20, "score": 342330.131176606 }, { "content": "fn launch_savestate(test: &ABTest, ss_path: String, ui: &mut UI, ctx: &mut EventCtx) -> ABTestMode {\n\n ctx.loading_screen(\n\n &format!(\"Launch A/B test from savestate {}\", ss_path),\n\n |ctx, mut timer| {\n\n let ss: ABTestSavestate = abstutil::read_binary(&ss_path, &mut timer).unwrap();\n\n\n\n timer.start(\"setup primary\");\n\n ui.primary.map = ss.primary_map;\n\n ui.primary.sim = ss.primary_sim;\n\n ui.primary.draw_map = DrawMap::new(\n\n &ui.primary.map,\n\n &ui.primary.current_flags,\n\n &ui.cs,\n\n ctx,\n\n &mut timer,\n\n );\n\n timer.stop(\"setup primary\");\n\n\n\n timer.start(\"setup secondary\");\n\n let secondary = PerMapUI {\n", "file_path": "game/src/abtest/setup.rs", "rank": 21, "score": 340032.78856819053 }, { "content": "fn color_for_mode(m: TripMode, ui: &UI) -> Color {\n\n match m {\n\n TripMode::Walk => ui.cs.get(\"unzoomed pedestrian\"),\n\n TripMode::Bike => ui.cs.get(\"unzoomed bike\"),\n\n TripMode::Transit => ui.cs.get(\"unzoomed bus\"),\n\n TripMode::Drive => ui.cs.get(\"unzoomed car\"),\n\n }\n\n}\n", "file_path": "game/src/sandbox/overlays.rs", "rank": 22, "score": 338405.07968383096 }, { "content": "#[allow(non_snake_case)]\n\npub fn Line<S: Into<String>>(text: S) -> TextSpan {\n\n TextSpan {\n\n text: text.into(),\n\n fg_color: FG_COLOR,\n\n size: None,\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct Text {\n\n // The bg_color will cover the entire block, but some lines can have extra highlighting.\n\n lines: Vec<(Option<Color>, Vec<TextSpan>)>,\n\n bg_color: Option<Color>,\n\n pub override_width: Option<f64>,\n\n pub override_height: Option<f64>,\n\n}\n\n\n\nimpl Text {\n\n pub fn new() -> Text {\n\n Text {\n", "file_path": "ezgui/src/text.rs", "rank": 23, "score": 330901.12930167606 }, { "content": "fn show_route(trip: TripID, ui: &UI, ctx: &EventCtx) -> RouteViewer {\n\n let time = ui.primary.sim.time();\n\n match ui.primary.sim.trip_to_agent(trip) {\n\n TripResult::Ok(agent) => RouteViewer::Active(\n\n time,\n\n trip,\n\n ui.primary\n\n .sim\n\n .trace_route(agent, &ui.primary.map, None)\n\n .map(|trace| {\n\n let mut zoomed = GeomBatch::new();\n\n zoomed.extend(\n\n ui.cs.get(\"route\").alpha(0.8),\n\n dashed_lines(\n\n &trace,\n\n Distance::meters(0.75),\n\n Distance::meters(1.0),\n\n Distance::meters(0.4),\n\n ),\n\n );\n", "file_path": "game/src/common/route_viewer.rs", "rank": 24, "score": 329875.32701468025 }, { "content": "fn info_for(id: ID, ui: &UI, ctx: &EventCtx) -> Text {\n\n let (map, sim, draw_map) = (&ui.primary.map, &ui.primary.sim, &ui.primary.draw_map);\n\n let mut txt = Text::new();\n\n // TODO Technically we should recalculate all of this as the window resizes, then.\n\n txt.override_width = Some(0.7 * ctx.canvas.window_width);\n\n txt.override_height = Some(0.7 * ctx.canvas.window_height);\n\n\n\n txt.extend(&CommonState::default_osd(id.clone(), ui));\n\n txt.highlight_last_line(Color::BLUE);\n\n let id_color = ui.cs.get(\"OSD ID color\");\n\n let name_color = ui.cs.get(\"OSD name color\");\n\n\n\n match id {\n\n ID::Road(_) => unreachable!(),\n\n ID::Lane(id) => {\n\n let l = map.get_l(id);\n\n let r = map.get_r(l.parent);\n\n\n\n txt.add_appended(vec![\n\n Line(\"Parent \"),\n", "file_path": "game/src/common/info.rs", "rank": 25, "score": 329365.6760593519 }, { "content": "fn change_traffic_signal(signal: ControlTrafficSignal, ui: &mut UI, ctx: &mut EventCtx) {\n\n let mut edits = ui.primary.map.get_edits().clone();\n\n // TODO Only record one command for the entire session. Otherwise, we can exit this editor and\n\n // undo a few times, potentially ending at an invalid state!\n\n if edits\n\n .commands\n\n .last()\n\n .map(|cmd| match cmd {\n\n EditCmd::ChangeTrafficSignal(ref s) => s.id == signal.id,\n\n _ => false,\n\n })\n\n .unwrap_or(false)\n\n {\n\n edits.commands.pop();\n\n }\n\n edits.commands.push(EditCmd::ChangeTrafficSignal(signal));\n\n apply_map_edits(&mut ui.primary, &ui.cs, ctx, edits);\n\n}\n\n\n", "file_path": "game/src/edit/traffic_signals.rs", "rank": 26, "score": 327836.1712071957 }, { "content": "pub fn clip_trips(map: &Map, timer: &mut Timer) -> (Vec<Trip>, HashMap<BuildingID, Parcel>) {\n\n let popdat: PopDat = abstutil::read_binary(\"../data/shapes/popdat.bin\", timer)\n\n .expect(\"Couldn't load popdat.bin\");\n\n\n\n let mut osm_id_to_bldg = HashMap::new();\n\n for b in map.all_buildings() {\n\n osm_id_to_bldg.insert(b.osm_way_id, b.id);\n\n }\n\n let bounds = map.get_gps_bounds();\n\n // TODO Figure out why some polygon centers are broken\n\n let incoming_borders_walking: Vec<(IntersectionID, LonLat)> = map\n\n .all_incoming_borders()\n\n .into_iter()\n\n .filter(|i| {\n\n !i.get_outgoing_lanes(map, PathConstraints::Pedestrian)\n\n .is_empty()\n\n })\n\n .filter_map(|i| i.polygon.center().to_gps(bounds).map(|pt| (i.id, pt)))\n\n .collect();\n\n let incoming_borders_driving: Vec<(IntersectionID, LonLat)> = map\n", "file_path": "popdat/src/trips.rs", "rank": 27, "score": 312916.9330061356 }, { "content": "fn bus_delays(id: BusRouteID, ui: &UI, ctx: &mut EventCtx) -> Plot<Duration> {\n\n let route = ui.primary.map.get_br(id);\n\n let mut delays_per_stop = ui\n\n .primary\n\n .sim\n\n .get_analytics()\n\n .bus_arrivals_over_time(ui.primary.sim.time(), id);\n\n\n\n let mut series = Vec::new();\n\n for idx1 in 0..route.stops.len() {\n\n let idx2 = if idx1 == route.stops.len() - 1 {\n\n 0\n\n } else {\n\n idx1 + 1\n\n };\n\n series.push(Series {\n\n label: format!(\"Stop {}->{}\", idx1 + 1, idx2 + 1),\n\n color: rotating_color_total(idx1, route.stops.len()),\n\n pts: delays_per_stop\n\n .remove(&route.stops[idx2])\n", "file_path": "game/src/sandbox/gameplay/optimize_bus.rs", "rank": 28, "score": 297941.00168824464 }, { "content": "pub fn rotating_color_total(idx: usize, total: usize) -> Color {\n\n if total > 9 {\n\n return rotating_color_total(idx, 9);\n\n }\n\n if total < 3 {\n\n return rotating_color_total(idx, 3);\n\n }\n\n\n\n // TODO Cache this\n\n // TODO This palette doesn't contrast well with other stuff\n\n let colors: Vec<Color> =\n\n colorbrewer::get_color_ramp(colorbrewer::Palette::YlOrBr, total as u32)\n\n .unwrap()\n\n .into_iter()\n\n .map(Color::from_hex)\n\n .collect();\n\n\n\n colors[idx % total]\n\n}\n", "file_path": "game/src/helpers.rs", "rank": 29, "score": 297585.12337163475 }, { "content": "fn styled_kv(txt: &mut Text, tags: &BTreeMap<String, String>) {\n\n for (k, v) in tags {\n\n txt.add_appended(vec![\n\n Line(k).fg(Color::RED),\n\n Line(\" = \"),\n\n Line(v).fg(Color::CYAN),\n\n ]);\n\n }\n\n}\n", "file_path": "game/src/common/info.rs", "rank": 30, "score": 295441.06538251974 }, { "content": "fn preview_all_intersections(model: &Model, ctx: &EventCtx) -> (Drawable, Vec<(Text, Pt2D)>) {\n\n let mut batch = GeomBatch::new();\n\n let mut timer = Timer::new(\"preview all intersections\");\n\n timer.start_iter(\"preview\", model.map.intersections.len());\n\n for i in model.map.intersections.keys() {\n\n timer.next();\n\n if model.map.roads_per_intersection(*i).is_empty() {\n\n continue;\n\n }\n\n let (intersection, _, _) = model.map.preview_intersection(*i, &mut timer);\n\n batch.push(Color::ORANGE.alpha(0.5), intersection);\n\n }\n\n (ctx.prerender.upload(batch), Vec::new())\n\n}\n\n\n", "file_path": "map_editor/src/main.rs", "rank": 31, "score": 291981.256090564 }, { "content": "fn find_overlapping_intersections(model: &Model, ctx: &EventCtx) -> (Drawable, Vec<(Text, Pt2D)>) {\n\n let mut timer = Timer::new(\"find overlapping intersections\");\n\n let mut polygons = Vec::new();\n\n for i in model.map.intersections.keys() {\n\n if model.map.roads_per_intersection(*i).is_empty() {\n\n continue;\n\n }\n\n let (intersection, _, _) = model.map.preview_intersection(*i, &mut timer);\n\n polygons.push((*i, intersection));\n\n }\n\n\n\n let mut overlap = Vec::new();\n\n timer.start_iter(\n\n \"terrible quadratic intersection check\",\n\n polygons.len().pow(2),\n\n );\n\n for (i1, poly1) in &polygons {\n\n for (i2, poly2) in &polygons {\n\n timer.next();\n\n if i1 >= i2 {\n", "file_path": "map_editor/src/main.rs", "rank": 32, "score": 288933.1588072788 }, { "content": "pub fn lctrl(key: Key) -> Option<MultiKey> {\n\n Some(MultiKey { key, lctrl: true })\n\n}\n", "file_path": "ezgui/src/event.rs", "rank": 33, "score": 279930.0323458883 }, { "content": "pub fn run<G: GUI, F: FnOnce(&mut EventCtx) -> G>(settings: Settings, make_gui: F) {\n\n let events_loop = glutin::EventsLoop::new();\n\n let window = glutin::WindowBuilder::new()\n\n .with_title(settings.window_title)\n\n .with_dimensions(glutin::dpi::LogicalSize::new(\n\n settings.initial_dims.0,\n\n settings.initial_dims.1,\n\n ));\n\n // multisampling: 2 looks bad, 4 looks fine\n\n //\n\n // The Z values are very simple:\n\n // 1.0: The buffer is reset every frame\n\n // 0.5: Map-space geometry and text\n\n // 0.1: Screen-space text\n\n // 0.0: Screen-space geometry\n\n // Had weird issues with Z buffering not working as intended, so this is slightly more\n\n // complicated than necessary to work.\n\n let context = glutin::ContextBuilder::new()\n\n .with_multisampling(4)\n\n .with_depth_buffer(2);\n", "file_path": "ezgui/src/runner.rs", "rank": 34, "score": 277198.5378321532 }, { "content": "// TODO Word wrap\n\npub fn msg<S: Into<String>>(title: &'static str, lines: Vec<S>) -> Box<dyn State> {\n\n let str_lines: Vec<String> = lines.into_iter().map(|l| l.into()).collect();\n\n WizardState::new(Box::new(move |wiz, ctx, _| {\n\n wiz.wrap(ctx).acknowledge(title, || str_lines.clone())?;\n\n Some(Transition::Pop)\n\n }))\n\n}\n", "file_path": "game/src/game.rs", "rank": 35, "score": 269988.93738607364 }, { "content": "pub fn run(t: &mut TestRunner) {\n\n t.run_slow(\"bus_reaches_stops\", |h| {\n\n let mut flags = SimFlags::for_test(\"bus_reaches_stops\");\n\n flags.opts.savestate_every = Some(Duration::seconds(30.0));\n\n let (map, mut sim, _) = flags.load(&mut Timer::throwaway());\n\n let route = map.get_bus_route(\"49\").unwrap();\n\n let buses = sim.seed_bus_route(route, &map, &mut Timer::throwaway());\n\n let bus = buses[0];\n\n h.setup_done(&sim);\n\n\n\n let mut expectations: Vec<Event> = Vec::new();\n\n // TODO assert stuff about other buses as well, although the timing is a little unclear\n\n for stop in route.stops.iter().skip(1) {\n\n expectations.push(Event::BusArrivedAtStop(bus, route.id, *stop));\n\n expectations.push(Event::BusDepartedFromStop(bus, route.id, *stop));\n\n }\n\n\n\n sim.run_until_expectations_met(&map, expectations, Duration::minutes(10));\n\n // Make sure buses don't block a sim from being considered done\n\n sim.just_run_until_done(&map, Some(Duration::minutes(11)));\n", "file_path": "tests/src/transit.rs", "rank": 36, "score": 263582.92976958357 }, { "content": "pub fn run(t: &mut TestRunner) {\n\n t.run_slow(\"bike_from_border\", |h| {\n\n let mut flags = SimFlags::for_test(\"bike_from_border\");\n\n flags.opts.savestate_every = Some(Duration::seconds(30.0));\n\n let (map, mut sim, mut rng) = flags.load(&mut Timer::throwaway());\n\n // TODO Hardcoding IDs is fragile\n\n let goal_bldg = BuildingID(319);\n\n let (ped, bike) = sim.schedule_trip(\n\n Duration::ZERO,\n\n TripSpec::UsingBike {\n\n start: SidewalkSpot::start_at_border(IntersectionID(186), &map).unwrap(),\n\n vehicle: Scenario::rand_bike(&mut rng),\n\n goal: DrivingGoal::ParkNear(goal_bldg),\n\n ped_speed: Scenario::rand_ped_speed(&mut rng),\n\n },\n\n &map,\n\n );\n\n sim.spawn_all_trips(&map, &mut Timer::throwaway(), false);\n\n h.setup_done(&sim);\n\n\n", "file_path": "tests/src/trips.rs", "rank": 37, "score": 263457.37648314197 }, { "content": "pub fn run(t: &mut TestRunner) {\n\n t.run_slow(\"serialization\", |_| {\n\n let (map, mut sim, mut rng) =\n\n SimFlags::for_test(\"serialization\").load(&mut Timer::throwaway());\n\n Scenario::small_run(&map).instantiate(&mut sim, &map, &mut rng, &mut Timer::throwaway());\n\n\n\n // Does savestating produce the same string?\n\n let save1 = abstutil::to_json(&sim);\n\n let save2 = abstutil::to_json(&sim);\n\n assert_eq!(save1, save2);\n\n });\n\n\n\n t.run_slow(\"from_scratch\", |_| {\n\n println!(\"Creating two simulations\");\n\n let flags = SimFlags::for_test(\"from_scratch_1\");\n\n let (map, mut sim1, _) = flags.load(&mut Timer::throwaway());\n\n let mut sim2 = Sim::new(\n\n &map,\n\n SimOptions::new(\"from_scratch_2\"),\n\n &mut Timer::throwaway(),\n", "file_path": "tests/src/sim_determinism.rs", "rank": 38, "score": 258092.130080642 }, { "content": "pub fn run(t: &mut TestRunner) {\n\n t.run_slow(\"small_spawn_completes\", |h| {\n\n let mut flags = SimFlags::for_test(\"aorta_model_completes\");\n\n flags.opts.savestate_every = Some(Duration::seconds(30.0));\n\n let (map, mut sim, mut rng) = flags.load(&mut Timer::throwaway());\n\n Scenario::small_run(&map).instantiate(&mut sim, &map, &mut rng, &mut Timer::throwaway());\n\n h.setup_done(&sim);\n\n sim.just_run_until_done(&map, Some(Duration::minutes(70)));\n\n });\n\n}\n", "file_path": "tests/src/sim_completion.rs", "rank": 39, "score": 258092.130080642 }, { "content": "pub fn draw_text_bubble(\n\n g: &mut GfxCtx,\n\n top_left: ScreenPt,\n\n txt: &Text,\n\n // Callers almost always calculate this anyway\n\n (total_width, total_height): (f64, f64),\n\n) -> ScreenRectangle {\n\n // TODO Is it expensive to constantly change uniforms and the shader program?\n\n g.fork_screenspace();\n\n\n\n if let Some(c) = txt.bg_color {\n\n g.draw_polygon(\n\n c,\n\n &Polygon::rectangle_topleft(\n\n Pt2D::new(top_left.x, top_left.y),\n\n Distance::meters(total_width),\n\n Distance::meters(total_height),\n\n ),\n\n );\n\n }\n", "file_path": "ezgui/src/text.rs", "rank": 40, "score": 255879.61953778082 }, { "content": "pub fn draw_text_bubble_mapspace(\n\n g: &mut GfxCtx,\n\n top_left: Pt2D,\n\n txt: &Text,\n\n // Callers almost always calculate this anyway\n\n (total_width, total_height): (f64, f64),\n\n) {\n\n if let Some(c) = txt.bg_color {\n\n g.draw_polygon(\n\n c,\n\n &Polygon::rectangle_topleft(\n\n Pt2D::new(top_left.x(), top_left.y()),\n\n Distance::meters(total_width / SCALE_DOWN),\n\n Distance::meters(total_height / SCALE_DOWN),\n\n ),\n\n );\n\n }\n\n\n\n let mut y = top_left.y();\n\n for (line_color, line) in &txt.lines {\n", "file_path": "ezgui/src/text.rs", "rank": 41, "score": 251371.76176486752 }, { "content": "pub fn trips_to_scenario(map: &Map, timer: &mut Timer) -> Scenario {\n\n let (trips, _) = clip_trips(map, timer);\n\n // TODO Don't clone trips for parallelize\n\n let individ_trips = timer\n\n .parallelize(\"turn PSRC trips into SpawnTrips\", trips.clone(), |trip| {\n\n trip.to_spawn_trip(map)\n\n })\n\n .into_iter()\n\n .flatten()\n\n .collect();\n\n\n\n // How many parked cars do we need to spawn near each building?\n\n // TODO This assumes trips are instantaneous. At runtime, somebody might try to use a parked\n\n // car from a building, but one hasn't been delivered yet.\n\n let mut individ_parked_cars = BTreeMap::new();\n\n let mut avail_per_bldg = BTreeMap::new();\n\n for b in map.all_buildings() {\n\n individ_parked_cars.insert(b.id, 0);\n\n avail_per_bldg.insert(b.id, 0);\n\n }\n", "file_path": "popdat/src/trips.rs", "rank": 42, "score": 249763.60967639403 }, { "content": "// TODO Temporarily public for debugging.\n\n// TODO This should just draw the turn geometry thickened, once that's stable.\n\npub fn calculate_corners(i: &Intersection, map: &Map, timer: &mut Timer) -> Vec<Polygon> {\n\n let mut corners = Vec::new();\n\n\n\n for turn in &map.get_turns_in_intersection(i.id) {\n\n if turn.turn_type == TurnType::SharedSidewalkCorner {\n\n // Avoid double-rendering\n\n if map.get_l(turn.id.src).dst_i != i.id {\n\n continue;\n\n }\n\n\n\n // Special case for dead-ends: just thicken the geometry.\n\n if i.roads.len() == 1 {\n\n corners.push(turn.geom.make_polygons(LANE_THICKNESS));\n\n continue;\n\n }\n\n\n\n let l1 = map.get_l(turn.id.src);\n\n let l2 = map.get_l(turn.id.dst);\n\n\n\n let src_line = l1.last_line().shift_left(LANE_THICKNESS / 2.0);\n", "file_path": "game/src/render/intersection.rs", "rank": 43, "score": 244464.1609574018 }, { "content": "fn color_turn_type(t: TurnType, ui: &UI) -> Color {\n\n match t {\n\n TurnType::SharedSidewalkCorner => {\n\n ui.cs.get_def(\"shared sidewalk corner turn\", Color::BLACK)\n\n }\n\n TurnType::Crosswalk => ui.cs.get_def(\"crosswalk turn\", Color::WHITE),\n\n TurnType::Straight => ui.cs.get_def(\"straight turn\", Color::BLUE),\n\n TurnType::LaneChangeLeft => ui.cs.get_def(\"change lanes left turn\", Color::CYAN),\n\n TurnType::LaneChangeRight => ui.cs.get_def(\"change lanes right turn\", Color::PURPLE),\n\n TurnType::Right => ui.cs.get_def(\"right turn\", Color::GREEN),\n\n TurnType::Left => ui.cs.get_def(\"left turn\", Color::RED),\n\n }\n\n}\n\n\n", "file_path": "game/src/common/turn_cycler.rs", "rank": 44, "score": 238229.42178648995 }, { "content": "fn gridlock_panel(ui: &UI) -> Text {\n\n let (now_all, _, now_per_mode) = ui\n\n .primary\n\n .sim\n\n .get_analytics()\n\n .all_finished_trips(ui.primary.sim.time());\n\n let (baseline_all, _, baseline_per_mode) =\n\n ui.prebaked.all_finished_trips(ui.primary.sim.time());\n\n\n\n let mut txt = Text::new();\n\n txt.add_appended(vec![\n\n Line(format!(\n\n \"{} total finished trips (\",\n\n prettyprint_usize(now_all.count())\n\n )),\n\n cmp_count_fewer(now_all.count(), baseline_all.count()),\n\n Line(\")\"),\n\n ]);\n\n\n\n for mode in TripMode::all() {\n", "file_path": "game/src/sandbox/gameplay/create_gridlock.rs", "rank": 45, "score": 237743.3100591523 }, { "content": "#[derive(Serialize, Deserialize, PartialEq, Debug)]\n\nstruct Trip {\n\n id: TripID,\n\n spawned_at: Duration,\n\n finished_at: Option<Duration>,\n\n aborted: bool,\n\n legs: VecDeque<TripLeg>,\n\n mode: TripMode,\n\n start: TripStart,\n\n end: TripEnd,\n\n}\n\n\n\nimpl Trip {\n\n fn uses_car(&self, id: CarID, home: BuildingID) -> bool {\n\n self.legs.iter().any(|l| match l {\n\n TripLeg::Walk(_, _, ref walk_to) => match walk_to.connection {\n\n SidewalkPOI::DeferredParkingSpot(b, _) => b == home,\n\n _ => false,\n\n },\n\n // No need to look up the contents of a SidewalkPOI::ParkingSpot. If a trip uses a\n\n // specific parked car, then there'll be a TripLeg::Drive with it already.\n", "file_path": "sim/src/trips.rs", "rank": 46, "score": 237407.07685323246 }, { "content": "fn input_weighted_usize(wizard: &mut WrappedWizard, query: &str) -> Option<WeightedUsizeChoice> {\n\n wizard.input_something(\n\n query,\n\n None,\n\n Box::new(|line| WeightedUsizeChoice::parse(&line)),\n\n )\n\n}\n\n\n", "file_path": "game/src/mission/scenario.rs", "rank": 47, "score": 235184.00223951737 }, { "content": "fn debug_all_routes(ui: &mut UI) -> AllRoutesViewer {\n\n let mut traces: Vec<PolyLine> = Vec::new();\n\n let trips: Vec<TripID> = ui\n\n .primary\n\n .sim\n\n .get_trip_positions(&ui.primary.map)\n\n .canonical_pt_per_trip\n\n .keys()\n\n .cloned()\n\n .collect();\n\n for trip in trips {\n\n if let Some(agent) = ui.primary.sim.trip_to_agent(trip).ok() {\n\n if let Some(trace) = ui.primary.sim.trace_route(agent, &ui.primary.map, None) {\n\n traces.push(trace);\n\n }\n\n }\n\n }\n\n AllRoutesViewer::Active(ui.primary.sim.time(), traces)\n\n}\n", "file_path": "game/src/debug/routes.rs", "rank": 48, "score": 232914.3706008448 }, { "content": "fn clip_tracts(popdat: &PopDat, ui: &UI, timer: &mut Timer) -> BTreeMap<String, Tract> {\n\n // TODO Partial clipping could be neat, except it'd be confusing to interpret totals.\n\n let mut results = BTreeMap::new();\n\n timer.start_iter(\"clip tracts\", popdat.tracts.len());\n\n for (name, tract) in &popdat.tracts {\n\n timer.next();\n\n if let Some(pts) = ui.primary.map.get_gps_bounds().try_convert(&tract.pts) {\n\n // TODO We should actually make sure the polygon is completely contained within the\n\n // map's boundary.\n\n let polygon = Polygon::new(&pts);\n\n\n\n // TODO Don't just use the center...\n\n let mut num_bldgs = 0;\n\n let mut num_parking_spots = 0;\n\n for id in ui\n\n .primary\n\n .draw_map\n\n .get_matching_objects(polygon.get_bounds())\n\n {\n\n match id {\n", "file_path": "game/src/mission/dataviz.rs", "rank": 49, "score": 230913.79685996688 }, { "content": "pub fn retain_btreeset<K: Ord + Clone, F: FnMut(&K) -> bool>(set: &mut BTreeSet<K>, mut keep: F) {\n\n let mut remove: Vec<K> = Vec::new();\n\n for k in set.iter() {\n\n if !keep(k) {\n\n remove.push(k.clone());\n\n }\n\n }\n\n for k in remove {\n\n set.remove(&k);\n\n }\n\n}\n\n\n", "file_path": "abstutil/src/collections.rs", "rank": 50, "score": 229692.44074913766 }, { "content": "pub fn rotating_color(idx: usize) -> Color {\n\n rotating_color_total(idx, 9)\n\n}\n\n\n", "file_path": "game/src/helpers.rs", "rank": 51, "score": 229460.189631555 }, { "content": "fn bar_chart(g: &mut GfxCtx, data: &BTreeMap<String, Estimate>) {\n\n let mut max = 0;\n\n let mut sum = 0;\n\n for (name, est) in data {\n\n if name == \"Total:\" {\n\n continue;\n\n }\n\n max = max.max(est.value);\n\n sum += est.value;\n\n }\n\n\n\n let mut labels = Text::new().no_bg();\n\n for (name, est) in data {\n\n if name == \"Total:\" {\n\n continue;\n\n }\n\n labels.add_appended(vec![\n\n Line(format!(\"{} (\", name)).size(40),\n\n Line(format!(\n\n \"{}%\",\n", "file_path": "game/src/mission/dataviz.rs", "rank": 52, "score": 228568.26743738714 }, { "content": "struct Choice {\n\n hotkey: Option<MultiKey>,\n\n label: String,\n\n active: bool,\n\n}\n\n\n\nimpl ModalMenu {\n\n pub fn new<S: Into<String>>(\n\n title: S,\n\n raw_choices: Vec<(Option<MultiKey>, &str)>,\n\n ctx: &EventCtx,\n\n ) -> ModalMenu {\n\n let mut m = ModalMenu {\n\n title: title.into(),\n\n info: Text::new(),\n\n chosen_action: None,\n\n choices: raw_choices\n\n .into_iter()\n\n .map(|(hotkey, label)| Choice {\n\n hotkey,\n", "file_path": "ezgui/src/widgets/modal_menu.rs", "rank": 53, "score": 225838.6062609991 }, { "content": "// Shorter is better\n\npub fn cmp_duration_shorter(now: Duration, baseline: Duration) -> Vec<TextSpan> {\n\n if now.epsilon_eq(baseline) {\n\n vec![Line(\" (same as baseline)\")]\n\n } else if now < baseline {\n\n vec![\n\n Line(\" (\"),\n\n Line((baseline - now).minimal_tostring()).fg(Color::GREEN),\n\n Line(\" faster)\"),\n\n ]\n\n } else if now > baseline {\n\n vec![\n\n Line(\" (\"),\n\n Line((now - baseline).minimal_tostring()).fg(Color::RED),\n\n Line(\" slower)\"),\n\n ]\n\n } else {\n\n unreachable!()\n\n }\n\n}\n\n\n", "file_path": "game/src/sandbox/gameplay/mod.rs", "rank": 54, "score": 223676.59320843784 }, { "content": "#[derive(Serialize, Deserialize, Derivative)]\n\n#[derivative(PartialEq)]\n\nstruct State {\n\n id: IntersectionID,\n\n accepted: BTreeSet<Request>,\n\n // Track when a request is first made.\n\n #[serde(\n\n serialize_with = \"serialize_btreemap\",\n\n deserialize_with = \"deserialize_btreemap\"\n\n )]\n\n waiting: BTreeMap<Request, Duration>,\n\n // TODO Can we move this to analytics?\n\n #[derivative(PartialEq = \"ignore\")]\n\n #[serde(skip_serializing, skip_deserializing)]\n\n delays: DurationHistogram,\n\n}\n\n\n\nimpl IntersectionSimState {\n\n pub fn new(\n\n map: &Map,\n\n scheduler: &mut Scheduler,\n\n use_freeform_policy_everywhere: bool,\n", "file_path": "sim/src/mechanics/intersection.rs", "rank": 55, "score": 222202.41033719748 }, { "content": "// (original direction, reversed direction)\n\npub fn get_lane_types(osm_tags: &BTreeMap<String, String>) -> (Vec<LaneType>, Vec<LaneType>) {\n\n if let Some(s) = osm_tags.get(osm::SYNTHETIC_LANES) {\n\n if let Some(spec) = RoadSpec::parse(s.to_string()) {\n\n return (spec.fwd, spec.back);\n\n } else {\n\n panic!(\"Bad {} RoadSpec: {}\", osm::SYNTHETIC_LANES, s);\n\n }\n\n }\n\n\n\n // Easy special cases first.\n\n if osm_tags.get(\"junction\") == Some(&\"roundabout\".to_string()) {\n\n return (vec![LaneType::Driving, LaneType::Sidewalk], Vec::new());\n\n }\n\n if osm_tags.get(osm::HIGHWAY) == Some(&\"footway\".to_string()) {\n\n return (vec![LaneType::Sidewalk], Vec::new());\n\n }\n\n\n\n // TODO Reversible roads should be handled differently?\n\n let oneway = osm_tags.get(\"oneway\") == Some(&\"yes\".to_string())\n\n || osm_tags.get(\"oneway\") == Some(&\"reversible\".to_string());\n", "file_path": "map_model/src/make/initial/lane_specs.rs", "rank": 56, "score": 219670.58061121887 }, { "content": "pub fn contains_duplicates<T: Ord>(vec: &Vec<T>) -> bool {\n\n let mut set = BTreeSet::new();\n\n for item in vec {\n\n if set.contains(item) {\n\n return true;\n\n }\n\n set.insert(item);\n\n }\n\n false\n\n}\n", "file_path": "abstutil/src/collections.rs", "rank": 57, "score": 219640.15744336866 }, { "content": "pub fn run(t: &mut TestRunner) {\n\n // TODO Lots of boilerplate between these two. Can we do better?\n\n\n\n /*t.run_slow(\"park_on_goal_st\", |h| {\n\n let (map, mut sim, mut rng) = SimFlags::synthetic_test(\"parking_test\", \"park_on_goal_st\")\n\n .load(&mut Timer::throwaway());\n\n let north_bldg = map.bldg(\"north\").id;\n\n let south_bldg = map.bldg(\"south\").id;\n\n let north_parking = map.parking_lane(\"north\", 23).id;\n\n let south_parking = map.parking_lane(\"south\", 23).id;\n\n\n\n let (spot, car) =\n\n h.seed_parked_cars(&mut sim, &mut rng, south_parking, Some(south_bldg), vec![2])[0];\n\n // Fill up some of the first spots, forcing parking to happen at spot 4\n\n h.seed_parked_cars(&mut sim, &mut rng, north_parking, None, (0..4).collect());\n\n h.seed_parked_cars(&mut sim, &mut rng, north_parking, None, (5..10).collect());\n\n sim.schedule_trip(\n\n Duration::ZERO,\n\n TripSpec::UsingParkedCar {\n\n start: SidewalkSpot::building(south_bldg, &map),\n", "file_path": "tests/src/parking.rs", "rank": 58, "score": 219237.63469927508 }, { "content": "#[allow(clippy::unreadable_literal)]\n\npub fn run(t: &mut TestRunner) {\n\n t.run_fast(\"dist_along_horiz_line\", |_| {\n\n let l = Line::new(\n\n Pt2D::new(147.17832753158294, 1651.034235433578),\n\n Pt2D::new(185.9754103560146, 1651.0342354335778),\n\n );\n\n let pt = Pt2D::new(179.1628455160347, 1651.0342354335778);\n\n\n\n assert!(l.contains_pt(pt));\n\n assert!(l.dist_along_of_point(pt).is_some());\n\n });\n\n\n\n t.run_fast(\"trim_with_epsilon\", |_| {\n\n /*\n\n // EPSILON_DIST needs to be tuned correctly, or this point seems like it's not on the line.\n\n let mut pl = PolyLine::new(vec![\n\n Pt2D::new(1130.2653468611902, 2124.099702776818),\n\n Pt2D::new(1175.9652436108408, 2124.1094748373457),\n\n Pt2D::new(1225.8319649025132, 2124.120594334445),\n\n ]);\n", "file_path": "tests/src/geom.rs", "rank": 59, "score": 219237.63469927508 }, { "content": "fn calculate_driving_lines(lane: &Lane, parent: &Road, timer: &mut Timer) -> Vec<Polygon> {\n\n // The leftmost lanes don't have dashed lines.\n\n let (dir, idx) = parent.dir_and_offset(lane.id);\n\n if idx == 0 || (dir && parent.children_forwards[idx - 1].1 == LaneType::SharedLeftTurn) {\n\n return Vec::new();\n\n }\n\n let lane_edge_pts = lane\n\n .lane_center_pts\n\n .shift_left(LANE_THICKNESS / 2.0)\n\n .get(timer);\n\n dashed_lines(\n\n &lane_edge_pts,\n\n Distance::meters(0.25),\n\n Distance::meters(1.0),\n\n Distance::meters(1.5),\n\n )\n\n}\n\n\n", "file_path": "game/src/render/lane.rs", "rank": 60, "score": 219172.8739922067 }, { "content": "fn edit_scenario(map: &Map, scenario: &mut Scenario, mut wizard: WrappedWizard) -> Option<()> {\n\n let seed_parked = \"Seed parked cars\";\n\n let spawn = \"Spawn agents\";\n\n let spawn_border = \"Spawn agents from a border\";\n\n let randomize = \"Randomly spawn stuff from/to every neighborhood\";\n\n match wizard\n\n .choose_string(\"What kind of edit?\", || {\n\n vec![seed_parked, spawn, spawn_border, randomize]\n\n })?\n\n .as_str()\n\n {\n\n x if x == seed_parked => {\n\n scenario.seed_parked_cars.push(SeedParkedCars {\n\n neighborhood: choose_neighborhood(\n\n map,\n\n &mut wizard,\n\n \"Seed parked cars in what area?\",\n\n )?,\n\n cars_per_building: input_weighted_usize(\n\n &mut wizard,\n", "file_path": "game/src/mission/scenario.rs", "rank": 61, "score": 218638.25986555155 }, { "content": "pub fn challenges_picker() -> Box<dyn State> {\n\n WizardState::new(Box::new(move |wiz, ctx, _| {\n\n let (_, challenge) = wiz.wrap(ctx).choose(\"Play which challenge?\", || {\n\n all_challenges()\n\n .into_iter()\n\n .map(|c| Choice::new(c.title.clone(), c))\n\n .collect()\n\n })?;\n\n\n\n let edits = abstutil::list_all_objects(abstutil::EDITS, &challenge.map_name);\n\n let mut summary = Text::new();\n\n for l in &challenge.description {\n\n summary.add(Line(l));\n\n }\n\n summary.add(Line(\"\"));\n\n summary.add(Line(format!(\"{} proposals:\", edits.len())));\n\n summary.add(Line(\"\"));\n\n for e in edits {\n\n summary.add(Line(format!(\"- {} (untested)\", e)));\n\n }\n", "file_path": "game/src/challenges.rs", "rank": 62, "score": 216985.74584982672 }, { "content": "fn finish(dir_path: &str, filenames: Vec<String>, num_tiles_x: usize, num_tiles_y: usize) {\n\n {\n\n let mut args = filenames.clone();\n\n args.push(\"-mode\".to_string());\n\n args.push(\"Concatenate\".to_string());\n\n args.push(\"-tile\".to_string());\n\n args.push(format!(\"{}x{}\", num_tiles_x, num_tiles_y));\n\n args.push(\"full.png\".to_string());\n\n\n\n let mut file = fs::File::create(format!(\"{}/combine.sh\", dir_path)).unwrap();\n\n writeln!(file, \"#!/bin/bash\\n\").unwrap();\n\n writeln!(file, \"montage {}\", args.join(\" \")).unwrap();\n\n writeln!(file, \"rm -f combine.sh\").unwrap();\n\n }\n\n\n\n {\n\n let output = process::Command::new(\"md5sum\")\n\n .args(\n\n &filenames\n\n .into_iter()\n", "file_path": "ezgui/src/widgets/screenshot.rs", "rank": 63, "score": 216709.52470633993 }, { "content": "pub fn run(t: &mut TestRunner) {\n\n t.run_slow(\"convert_osm_twice\", |_| {\n\n let flags = convert_osm::Flags {\n\n osm: \"../data/input/montlake.osm\".to_string(),\n\n parking_shapes: Some(\"../data/shapes/blockface.bin\".to_string()),\n\n offstreet_parking: Some(\"../data/input/offstreet_parking.kml\".to_string()),\n\n sidewalks: Some(\"../data/shapes/sidewalks.bin\".to_string()),\n\n gtfs: Some(\"../data/input/google_transit_2018_18_08\".to_string()),\n\n neighborhoods: Some(\"../data/input/neighborhoods.geojson\".to_string()),\n\n clip: Some(abstutil::path_polygon(\"montlake\")),\n\n output: \"convert_osm_twice.bin\".to_string(),\n\n };\n\n\n\n let map1 = convert_osm::convert(&flags, &mut abstutil::Timer::throwaway());\n\n let map2 = convert_osm::convert(&flags, &mut abstutil::Timer::throwaway());\n\n\n\n if abstutil::to_json(&map1) != abstutil::to_json(&map2) {\n\n // TODO tmp files\n\n abstutil::write_json(\"map1.json\", &map1).unwrap();\n\n abstutil::write_json(\"map2.json\", &map2).unwrap();\n", "file_path": "tests/src/map_conversion.rs", "rank": 64, "score": 215859.5019868964 }, { "content": "pub fn wraparound_get<T>(vec: &Vec<T>, idx: isize) -> &T {\n\n let len = vec.len() as isize;\n\n let idx = idx % len;\n\n let idx = if idx >= 0 { idx } else { idx + len };\n\n &vec[idx as usize]\n\n}\n\n\n", "file_path": "abstutil/src/collections.rs", "rank": 65, "score": 214282.17902296237 }, { "content": "// TODO This needs to update turn restrictions too\n\npub fn clip_map(map: &mut RawMap, timer: &mut Timer) {\n\n timer.start(\"clipping map to boundary\");\n\n\n\n // So we can use retain_btreemap without borrowing issues\n\n let boundary_polygon = map.boundary_polygon.clone();\n\n let boundary_lines: Vec<PolyLine> = map\n\n .boundary_polygon\n\n .points()\n\n .windows(2)\n\n .map(|pair| PolyLine::new(pair.to_vec()))\n\n .collect();\n\n\n\n // This is kind of indirect and slow, but first pass -- just remove roads that start or end\n\n // outside the boundary polygon.\n\n retain_btreemap(&mut map.roads, |_, r| {\n\n let first_in = boundary_polygon.contains_pt(r.center_points[0]);\n\n let last_in = boundary_polygon.contains_pt(*r.center_points.last().unwrap());\n\n first_in || last_in\n\n });\n\n\n", "file_path": "convert_osm/src/clip.rs", "rank": 66, "score": 213765.78823087417 }, { "content": "fn close_off_polygon(mut pts: Vec<Pt2D>) -> Vec<Pt2D> {\n\n if pts.last().unwrap().approx_eq(pts[0], Distance::meters(0.1)) {\n\n pts.pop();\n\n }\n\n pts.push(pts[0]);\n\n pts\n\n}\n", "file_path": "map_model/src/make/initial/geometry.rs", "rank": 67, "score": 213495.47393169493 }, { "content": "pub fn get_lane_specs(osm_tags: &BTreeMap<String, String>) -> Vec<LaneSpec> {\n\n let (side1_types, side2_types) = lane_specs::get_lane_types(osm_tags);\n\n\n\n let mut specs: Vec<LaneSpec> = Vec::new();\n\n for lane_type in side1_types {\n\n specs.push(LaneSpec {\n\n lane_type,\n\n reverse_pts: false,\n\n });\n\n }\n\n for lane_type in side2_types {\n\n specs.push(LaneSpec {\n\n lane_type,\n\n reverse_pts: true,\n\n });\n\n }\n\n if specs.is_empty() {\n\n panic!(\"Road with tags {:?} wound up with no lanes!\", osm_tags);\n\n }\n\n specs\n\n}\n", "file_path": "map_model/src/make/initial/mod.rs", "rank": 68, "score": 212063.540394945 }, { "content": "// Add all possible protected groups to existing phases.\n\nfn expand_all_phases(phases: &mut Vec<Phase>, turn_groups: &BTreeMap<TurnGroupID, TurnGroup>) {\n\n for phase in phases.iter_mut() {\n\n for g in turn_groups.keys() {\n\n if phase.could_be_protected(*g, turn_groups) {\n\n phase.protected_groups.insert(*g);\n\n }\n\n }\n\n }\n\n}\n\n\n\nconst PROTECTED: bool = true;\n\nconst YIELD: bool = false;\n\n\n", "file_path": "map_model/src/traffic_signals.rs", "rank": 69, "score": 207555.51355756642 }, { "content": "pub fn remove_disconnected_roads(map: &mut RawMap, timer: &mut Timer) {\n\n timer.start(\"removing disconnected roads\");\n\n // This is a simple floodfill, not Tarjan's. Assumes all roads bidirectional.\n\n // All the usizes are indices into the original list of roads\n\n\n\n let mut next_roads: MultiMap<OriginalIntersection, OriginalRoad> = MultiMap::new();\n\n for id in map.roads.keys() {\n\n next_roads.insert(id.i1, *id);\n\n next_roads.insert(id.i2, *id);\n\n }\n\n\n\n let mut partitions: Vec<Vec<OriginalRoad>> = Vec::new();\n\n let mut unvisited_roads: BTreeSet<OriginalRoad> = map.roads.keys().cloned().collect();\n\n\n\n while !unvisited_roads.is_empty() {\n\n let mut queue_roads: Vec<OriginalRoad> = vec![*unvisited_roads.iter().next().unwrap()];\n\n let mut current_partition: Vec<OriginalRoad> = Vec::new();\n\n while !queue_roads.is_empty() {\n\n let current = queue_roads.pop().unwrap();\n\n if !unvisited_roads.contains(&current) {\n", "file_path": "map_model/src/make/remove_disconnected.rs", "rank": 70, "score": 206689.69580372667 }, { "content": "// TODO Validate the intersection exists? Let them pick it with the cursor?\n\nfn choose_intersection(wizard: &mut WrappedWizard, query: &str) -> Option<IntersectionID> {\n\n wizard.input_something(\n\n query,\n\n None,\n\n Box::new(|line| usize::from_str_radix(&line, 10).ok().map(IntersectionID)),\n\n )\n\n}\n\n\n", "file_path": "game/src/mission/scenario.rs", "rank": 71, "score": 203862.3439029249 }, { "content": "fn pick_neighborhood(map: &Map, mut wizard: WrappedWizard) -> Option<NeighborhoodBuilder> {\n\n let load_existing = \"Load existing neighborhood\";\n\n let create_new = \"Create new neighborhood\";\n\n if wizard.choose_string(\"What neighborhood to edit?\", || {\n\n vec![load_existing, create_new]\n\n })? == load_existing\n\n {\n\n load_neighborhood_builder(map, &mut wizard, \"Load which neighborhood?\")\n\n } else {\n\n let name = wizard.input_string(\"Name the neighborhood\")?;\n\n Some(NeighborhoodBuilder {\n\n name,\n\n map_name: map.get_name().to_string(),\n\n points: Vec::new(),\n\n })\n\n }\n\n}\n\n\n", "file_path": "game/src/mission/neighborhood.rs", "rank": 72, "score": 203856.68227428332 }, { "content": "pub fn import_trips(\n\n parcels_path: &str,\n\n trips_path: &str,\n\n timer: &mut Timer,\n\n) -> Result<(Vec<Trip>, BTreeMap<i64, Parcel>), failure::Error> {\n\n let (parcels, metadata) = import_parcels(parcels_path, timer)?;\n\n\n\n let mut trips = Vec::new();\n\n let (reader, done) = FileWithProgress::new(trips_path)?;\n\n for rec in csv::Reader::from_reader(reader).records() {\n\n let rec = rec?;\n\n\n\n // opcl\n\n let from = skip_fail!(parcels.get(rec[15].trim_end_matches(\".0\"))).clone();\n\n // dpcl\n\n let to = skip_fail!(parcels.get(rec[6].trim_end_matches(\".0\"))).clone();\n\n\n\n if from.osm_building == to.osm_building {\n\n // TODO Plumb along pass-through trips later\n\n if from.osm_building.is_some() {\n", "file_path": "popdat/src/psrc.rs", "rank": 73, "score": 202534.06735025224 }, { "content": "pub fn stack_vertically(\n\n orientation: ContainerOrientation,\n\n canvas: &Canvas,\n\n widgets: Vec<&mut dyn Widget>,\n\n) {\n\n assert!(!widgets.is_empty());\n\n\n\n let dims_per_widget: Vec<ScreenDims> = widgets.iter().map(|w| w.get_dims()).collect();\n\n let total_width = dims_per_widget\n\n .iter()\n\n .map(|d| d.width)\n\n .max_by_key(|x| NotNan::new(*x).unwrap())\n\n .unwrap();\n\n let total_height: f64 = dims_per_widget.iter().map(|d| d.height).sum();\n\n\n\n let mut top_left = match orientation {\n\n ContainerOrientation::TopLeft => ScreenPt::new(0.0, 0.0),\n\n ContainerOrientation::TopRight => ScreenPt::new(canvas.window_width - total_width, 0.0),\n\n ContainerOrientation::Centered => {\n\n let mut pt = canvas.center_to_screen_pt();\n", "file_path": "ezgui/src/layout.rs", "rank": 74, "score": 202061.976937329 }, { "content": "pub fn dashed_lines(\n\n pl: &PolyLine,\n\n width: Distance,\n\n dash_len: Distance,\n\n dash_separation: Distance,\n\n) -> Vec<Polygon> {\n\n if pl.length() < dash_separation * 2.0 + EPSILON_DIST {\n\n return vec![pl.make_polygons(width)];\n\n }\n\n // Don't draw the dashes too close to the ends.\n\n pl.exact_slice(dash_separation, pl.length() - dash_separation)\n\n .dashed_polygons(width, dash_len, dash_separation)\n\n}\n\n\n\npub struct DrawCtx<'a> {\n\n pub cs: &'a ColorScheme,\n\n pub map: &'a Map,\n\n pub draw_map: &'a DrawMap,\n\n pub sim: &'a Sim,\n\n}\n", "file_path": "game/src/render/mod.rs", "rank": 75, "score": 198941.3229740174 }, { "content": "pub fn list_dir(dir: &std::path::Path) -> Vec<String> {\n\n let mut files: Vec<String> = Vec::new();\n\n match std::fs::read_dir(dir) {\n\n Ok(iter) => {\n\n for entry in iter {\n\n files.push(entry.unwrap().path().to_str().unwrap().to_string());\n\n }\n\n }\n\n Err(ref e) if e.kind() == ErrorKind::NotFound => {}\n\n Err(e) => panic!(\"Couldn't read_dir {:?}: {}\", dir, e),\n\n };\n\n files.sort();\n\n files\n\n}\n\n\n", "file_path": "abstutil/src/io.rs", "rank": 76, "score": 197381.04494453658 }, { "content": "pub fn load(dir_path: &str) -> Result<Vec<Route>, Error> {\n\n println!(\"Loading GTFS from {}\", dir_path);\n\n let timer = Instant::now();\n\n\n\n let mut route_id_to_name: HashMap<String, String> = HashMap::new();\n\n for rec in csv::Reader::from_reader(File::open(format!(\"{}/routes.txt\", dir_path))?).records() {\n\n let rec = rec?;\n\n route_id_to_name.insert(rec[0].to_string(), rec[2].to_string());\n\n }\n\n\n\n let mut stop_id_to_pt: HashMap<String, LonLat> = HashMap::new();\n\n for rec in csv::Reader::from_reader(File::open(format!(\"{}/stops.txt\", dir_path))?).records() {\n\n let rec = rec?;\n\n let lon: f64 = rec[5].parse()?;\n\n let lat: f64 = rec[4].parse()?;\n\n stop_id_to_pt.insert(rec[0].to_string(), LonLat::new(lon, lat));\n\n }\n\n\n\n let mut trip_id_to_route_id_and_direction: HashMap<String, (String, bool)> = HashMap::new();\n\n for rec in csv::Reader::from_reader(File::open(format!(\"{}/trips.txt\", dir_path))?).records() {\n", "file_path": "gtfs/src/lib.rs", "rank": 77, "score": 197381.04494453658 }, { "content": "fn create_swarm(ui: &mut UI, from: LaneID, to: LaneID, count: usize, duration: Duration) {\n\n let mut scenario = Scenario::empty(&ui.primary.map);\n\n scenario.scenario_name = \"swarm\".to_string();\n\n scenario.border_spawn_over_time.push(BorderSpawnOverTime {\n\n num_peds: 0,\n\n num_cars: count,\n\n num_bikes: 0,\n\n start_time: ui.primary.sim.time() + SMALL_DT,\n\n stop_time: ui.primary.sim.time() + SMALL_DT + duration,\n\n start_from_border: ui\n\n .primary\n\n .map\n\n .get_l(from)\n\n .get_directed_parent(&ui.primary.map),\n\n goal: OriginDestination::EndOfRoad(\n\n ui.primary\n\n .map\n\n .get_l(to)\n\n .get_directed_parent(&ui.primary.map),\n\n ),\n", "file_path": "game/src/sandbox/gameplay/spawner.rs", "rank": 78, "score": 196275.8921152898 }, { "content": "fn choose_neighborhood(map: &Map, wizard: &mut WrappedWizard, query: &str) -> Option<String> {\n\n // Load the full object, since we usually visualize the neighborhood when menuing over it\n\n wizard\n\n .choose(query, || {\n\n Choice::from(Neighborhood::load_all(map.get_name(), map.get_gps_bounds()))\n\n })\n\n .map(|(n, _)| n)\n\n}\n\n\n", "file_path": "game/src/mission/scenario.rs", "rank": 79, "score": 195991.00463555864 }, { "content": "// Need to explain this trick -- basically keeps consistency between two different simulations when\n\n// each one might make slightly different sequences of calls to the RNG.\n\npub fn fork_rng(base_rng: &mut XorShiftRng) -> XorShiftRng {\n\n XorShiftRng::from_seed([base_rng.next_u32() as u8; 16])\n\n}\n\n\n\n// Represents the probability of sampling 0, 1, 2, 3... The sum can be anything.\n\n#[derive(Clone, Debug, Serialize, Deserialize)]\n\npub struct WeightedUsizeChoice {\n\n pub weights: Vec<usize>,\n\n}\n\n\n\nimpl WeightedUsizeChoice {\n\n pub fn parse(string: &str) -> Option<WeightedUsizeChoice> {\n\n let parts: Vec<&str> = string.split(',').collect();\n\n if parts.is_empty() {\n\n return None;\n\n }\n\n let mut weights: Vec<usize> = Vec::new();\n\n for x in parts.into_iter() {\n\n let x = x.parse::<usize>().ok()?;\n\n weights.push(x);\n\n }\n\n Some(WeightedUsizeChoice { weights })\n\n }\n\n\n\n pub fn sample(&self, rng: &mut XorShiftRng) -> usize {\n\n WeightedIndex::new(&self.weights).unwrap().sample(rng)\n\n }\n\n}\n", "file_path": "abstutil/src/random.rs", "rank": 80, "score": 195199.13747981816 }, { "content": "// Just list all things from a directory, return sorted by name, with file extension removed.\n\n// Hacky that map_name can be blank. ;)\n\npub fn list_all_objects(dir: &str, map_name: &str) -> Vec<String> {\n\n let mut results: BTreeSet<String> = BTreeSet::new();\n\n match std::fs::read_dir(format!(\"../data/{}/{}\", dir, map_name)) {\n\n Ok(iter) => {\n\n for entry in iter {\n\n let filename = entry.unwrap().file_name();\n\n let path = Path::new(&filename);\n\n if path.to_string_lossy().ends_with(\".swp\") {\n\n continue;\n\n }\n\n let name = path\n\n .file_stem()\n\n .unwrap()\n\n .to_os_string()\n\n .into_string()\n\n .unwrap();\n\n results.insert(name);\n\n }\n\n }\n\n Err(ref e) if e.kind() == ErrorKind::NotFound => {}\n\n Err(e) => panic!(e),\n\n };\n\n results.into_iter().collect()\n\n}\n\n\n", "file_path": "abstutil/src/io.rs", "rank": 81, "score": 194605.53851960582 }, { "content": "fn choose_scenario(map_name: &str, wizard: &mut WrappedWizard, query: &str) -> Option<String> {\n\n wizard.choose_string(query, || {\n\n abstutil::list_all_objects(abstutil::SCENARIOS, map_name)\n\n })\n\n}\n\n\n", "file_path": "game/src/abtest/setup.rs", "rank": 82, "score": 193721.68560863798 }, { "content": "pub fn convert(flags: &Flags, timer: &mut abstutil::Timer) -> RawMap {\n\n let mut map = split_ways::split_up_roads(\n\n osm_reader::extract_osm(&flags.osm, &flags.clip, timer),\n\n timer,\n\n );\n\n clip::clip_map(&mut map, timer);\n\n\n\n // Need to do a first pass of removing cul-de-sacs here, or we wind up with loop PolyLines when doing the parking hint matching.\n\n abstutil::retain_btreemap(&mut map.roads, |r, _| r.i1 != r.i2);\n\n\n\n if let Some(ref path) = flags.parking_shapes {\n\n use_parking_hints(&mut map, path, timer);\n\n }\n\n if let Some(ref path) = flags.offstreet_parking {\n\n use_offstreet_parking(&mut map, path, timer);\n\n }\n\n if let Some(ref path) = flags.sidewalks {\n\n use_sidewalk_hints(&mut map, path, timer);\n\n }\n\n if let Some(ref path) = flags.gtfs {\n", "file_path": "convert_osm/src/lib.rs", "rank": 83, "score": 188667.77601208986 }, { "content": "fn calculate_border_arrows(i: &Intersection, r: &Road, timer: &mut Timer) -> Vec<Polygon> {\n\n let mut result = Vec::new();\n\n\n\n // These arrows should point from the void to the road\n\n if !i.outgoing_lanes.is_empty() {\n\n // The line starts at the border and points down the road\n\n let (line, width) = if r.dst_i == i.id {\n\n let width = (r.children_forwards.len() as f64) * LANE_THICKNESS;\n\n (\n\n r.center_pts.last_line().shift_left(width / 2.0).reverse(),\n\n width,\n\n )\n\n } else {\n\n let width = (r.children_forwards.len() as f64) * LANE_THICKNESS;\n\n (r.center_pts.first_line().shift_right(width / 2.0), width)\n\n };\n\n result.push(\n\n // DEGENERATE_INTERSECTION_HALF_LENGTH is 5m...\n\n PolyLine::new(vec![\n\n line.unbounded_dist_along(Distance::meters(-9.5)),\n", "file_path": "game/src/render/intersection.rs", "rank": 84, "score": 187444.314440739 }, { "content": "fn warp_point(line: &str, primary: &PerMapUI) -> Option<(Option<ID>, Pt2D, f64)> {\n\n if line.is_empty() {\n\n return None;\n\n }\n\n // TODO Weird magic shortcut to go to last spot. What should this be?\n\n if line == \"j\" {\n\n if let Some((pt, zoom)) = primary.last_warped_from {\n\n return Some((None, pt, zoom));\n\n }\n\n return None;\n\n }\n\n\n\n let id = match usize::from_str_radix(&line[1..line.len()], 10) {\n\n Ok(idx) => match line.chars().next().unwrap() {\n\n 'r' => {\n\n let r = primary.map.maybe_get_r(RoadID(idx))?;\n\n ID::Lane(r.children_forwards[0].0)\n\n }\n\n 'l' => ID::Lane(LaneID(idx)),\n\n 'i' => ID::Intersection(IntersectionID(idx)),\n", "file_path": "game/src/common/warp.rs", "rank": 85, "score": 187349.68538826093 }, { "content": "#[derive(Serialize, Deserialize, PartialEq)]\n\nstruct Bus {\n\n car: CarID,\n\n route: BusRouteID,\n\n // Where does each passenger want to deboard?\n\n passengers: Vec<(PedestrianID, BusStopID)>,\n\n state: BusState,\n\n}\n\n\n", "file_path": "sim/src/transit.rs", "rank": 86, "score": 186641.26374252306 }, { "content": "#[derive(Serialize, Deserialize, PartialEq)]\n\nstruct Route {\n\n stops: Vec<StopForRoute>,\n\n buses: Vec<CarID>,\n\n}\n\n\n", "file_path": "sim/src/transit.rs", "rank": 87, "score": 186641.26374252306 }, { "content": "pub fn fix_bus_route(map: &Map, r: &mut BusRoute) -> bool {\n\n // Trim out stops if needed; map borders sometimes mean some paths don't work.\n\n let mut stops = Vec::new();\n\n for stop in r.stops.drain(..) {\n\n if stops.is_empty() {\n\n stops.push(stop);\n\n } else {\n\n if check_stops(*stops.last().unwrap(), stop, map) {\n\n stops.push(stop);\n\n }\n\n }\n\n }\n\n // Don't forget the last and first\n\n while stops.len() >= 2 {\n\n if check_stops(*stops.last().unwrap(), stops[0], map) {\n\n break;\n\n }\n\n // TODO Or the front one\n\n stops.pop();\n\n }\n\n r.stops = stops;\n\n r.stops.len() >= 2\n\n}\n\n\n", "file_path": "map_model/src/make/bus_stops.rs", "rank": 88, "score": 186508.4197135209 }, { "content": "fn calculate_turn_markings(map: &Map, lane: &Lane, timer: &mut Timer) -> Vec<Polygon> {\n\n let mut results = Vec::new();\n\n\n\n // Are there multiple driving lanes on this side of the road?\n\n if map\n\n .find_closest_lane(lane.id, vec![LaneType::Driving])\n\n .is_err()\n\n {\n\n return results;\n\n }\n\n if lane.length() < Distance::meters(7.0) {\n\n return results;\n\n }\n\n\n\n let thickness = Distance::meters(0.2);\n\n\n\n let common_base = lane.lane_center_pts.exact_slice(\n\n lane.length() - Distance::meters(7.0),\n\n lane.length() - Distance::meters(5.0),\n\n );\n", "file_path": "game/src/render/lane.rs", "rank": 89, "score": 182485.36629298347 }, { "content": "#[derive(Serialize, Deserialize, PartialEq)]\n\nstruct StopForRoute {\n\n id: BusStopID,\n\n driving_pos: Position,\n\n path_to_next_stop: Path,\n\n next_stop_idx: StopIdx,\n\n}\n\n\n", "file_path": "sim/src/transit.rs", "rank": 90, "score": 182446.9970714596 }, { "content": "fn use_offstreet_parking(map: &mut RawMap, path: &str, timer: &mut Timer) {\n\n timer.start(\"match offstreet parking points\");\n\n let shapes = kml::load(path, &map.gps_bounds, timer).expect(\"loading offstreet_parking failed\");\n\n\n\n let mut closest: FindClosest<OriginalBuilding> = FindClosest::new(&map.gps_bounds.to_bounds());\n\n for (id, b) in &map.buildings {\n\n closest.add(*id, b.polygon.points());\n\n }\n\n\n\n // TODO Another function just to use ?. Try blocks would rock.\n\n let mut handle_shape: Box<dyn FnMut(kml::ExtraShape) -> Option<()>> = Box::new(|s| {\n\n assert_eq!(s.points.len(), 1);\n\n let pt = Pt2D::from_gps(s.points[0], &map.gps_bounds)?;\n\n let (id, _) = closest.closest_pt(pt, Distance::meters(50.0))?;\n\n // TODO Handle parking lots.\n\n if !map.buildings[&id].polygon.contains_pt(pt) {\n\n return None;\n\n }\n\n let name = s.attributes.get(\"DEA_FACILITY_NAME\")?.to_string();\n\n let num_stalls = s.attributes.get(\"DEA_STALLS\")?.parse::<usize>().ok()?;\n", "file_path": "convert_osm/src/lib.rs", "rank": 91, "score": 180005.93866193263 }, { "content": "fn use_parking_hints(map: &mut RawMap, path: &str, timer: &mut Timer) {\n\n timer.start(\"apply parking hints\");\n\n let shapes: ExtraShapes = abstutil::read_binary(path, timer).expect(\"loading blockface failed\");\n\n\n\n // Match shapes with the nearest road + direction (true for forwards)\n\n let mut closest: FindClosest<(OriginalRoad, bool)> =\n\n FindClosest::new(&map.gps_bounds.to_bounds());\n\n for (id, r) in &map.roads {\n\n let center = PolyLine::new(r.center_points.clone());\n\n closest.add(\n\n (*id, true),\n\n center.shift_right(LANE_THICKNESS).get(timer).points(),\n\n );\n\n closest.add(\n\n (*id, false),\n\n center.shift_left(LANE_THICKNESS).get(timer).points(),\n\n );\n\n }\n\n\n\n for s in shapes.shapes.into_iter() {\n", "file_path": "convert_osm/src/lib.rs", "rank": 92, "score": 180005.93866193263 }, { "content": "fn use_sidewalk_hints(map: &mut RawMap, path: &str, timer: &mut Timer) {\n\n timer.start(\"apply sidewalk hints\");\n\n let shapes: ExtraShapes = abstutil::read_binary(path, timer).unwrap();\n\n\n\n // Match shapes with the nearest road + direction (true for forwards)\n\n let mut closest: FindClosest<(OriginalRoad, bool)> =\n\n FindClosest::new(&map.gps_bounds.to_bounds());\n\n for (id, r) in &map.roads {\n\n let center = PolyLine::new(r.center_points.clone());\n\n closest.add(\n\n (*id, true),\n\n center.shift_right(LANE_THICKNESS).get(timer).points(),\n\n );\n\n closest.add(\n\n (*id, false),\n\n center.shift_left(LANE_THICKNESS).get(timer).points(),\n\n );\n\n }\n\n\n\n for s in shapes.shapes.into_iter() {\n", "file_path": "convert_osm/src/lib.rs", "rank": 93, "score": 180005.93866193263 }, { "content": "fn calculate_sidewalk_lines(lane: &Lane) -> Vec<Polygon> {\n\n let tile_every = LANE_THICKNESS;\n\n\n\n let length = lane.length();\n\n\n\n let mut result = Vec::new();\n\n // Start away from the intersections\n\n let mut dist_along = tile_every;\n\n while dist_along < length - tile_every {\n\n let (pt, angle) = lane.dist_along(dist_along);\n\n // Reuse perp_line. Project away an arbitrary amount\n\n let pt2 = pt.project_away(Distance::meters(1.0), angle);\n\n result.push(\n\n perp_line(Line::new(pt, pt2), LANE_THICKNESS).make_polygons(Distance::meters(0.25)),\n\n );\n\n dist_along += tile_every;\n\n }\n\n\n\n result\n\n}\n\n\n", "file_path": "game/src/render/lane.rs", "rank": 94, "score": 179374.14576208714 }, { "content": "fn calculate_parking_lines(lane: &Lane) -> Vec<Polygon> {\n\n // meters, but the dims get annoying below to remove\n\n let leg_length = Distance::meters(1.0);\n\n\n\n let mut result = Vec::new();\n\n let num_spots = lane.number_parking_spots();\n\n if num_spots > 0 {\n\n for idx in 0..=num_spots {\n\n let (pt, lane_angle) = lane.dist_along(PARKING_SPOT_LENGTH * (1.0 + idx as f64));\n\n let perp_angle = lane_angle.rotate_degs(270.0);\n\n // Find the outside of the lane. Actually, shift inside a little bit, since the line will\n\n // have thickness, but shouldn't really intersect the adjacent line when drawn.\n\n let t_pt = pt.project_away(LANE_THICKNESS * 0.4, perp_angle);\n\n // The perp leg\n\n let p1 = t_pt.project_away(leg_length, perp_angle.opposite());\n\n result.push(Line::new(t_pt, p1).make_polygons(Distance::meters(0.25)));\n\n // Upper leg\n\n let p2 = t_pt.project_away(leg_length, lane_angle);\n\n result.push(Line::new(t_pt, p2).make_polygons(Distance::meters(0.25)));\n\n // Lower leg\n\n let p3 = t_pt.project_away(leg_length, lane_angle.opposite());\n\n result.push(Line::new(t_pt, p3).make_polygons(Distance::meters(0.25)));\n\n }\n\n }\n\n\n\n result\n\n}\n\n\n", "file_path": "game/src/render/lane.rs", "rank": 95, "score": 179374.14576208714 }, { "content": "pub fn path_camera_state(map_name: &str) -> String {\n\n format!(\"../data/camera_state/{}.json\", map_name)\n\n}\n\n\n", "file_path": "abstutil/src/lib.rs", "rank": 96, "score": 177749.5960812691 }, { "content": "// Load all serialized things from a directory, return sorted by name, with file extension removed.\n\n// Detects JSON or binary.\n\npub fn load_all_objects<T: DeserializeOwned>(dir: &str, map_name: &str) -> Vec<(String, T)> {\n\n let mut timer = Timer::new(&format!(\n\n \"load_all_objects from ../data/{}/{}/\",\n\n dir, map_name\n\n ));\n\n let mut tree: BTreeMap<String, T> = BTreeMap::new();\n\n match std::fs::read_dir(format!(\"../data/{}/{}/\", dir, map_name)) {\n\n Ok(iter) => {\n\n for entry in iter {\n\n let filename = entry.unwrap().file_name();\n\n let path = Path::new(&filename);\n\n let path_str = path.to_string_lossy();\n\n if path_str.ends_with(\".swp\") {\n\n continue;\n\n }\n\n let name = path\n\n .file_stem()\n\n .unwrap()\n\n .to_os_string()\n\n .into_string()\n", "file_path": "abstutil/src/io.rs", "rank": 97, "score": 176819.88723320133 }, { "content": "fn pts_to_line_string(raw_pts: &Vec<Pt2D>) -> geo::LineString<f64> {\n\n let pts: Vec<geo::Point<f64>> = raw_pts\n\n .iter()\n\n .map(|pt| geo::Point::new(pt.x(), pt.y()))\n\n .collect();\n\n pts.into()\n\n}\n", "file_path": "geom/src/find_closest.rs", "rank": 98, "score": 174903.68035820633 }, { "content": "struct UI {\n\n model: Model,\n\n state: State,\n\n menu: ModalMenu,\n\n sidebar: Text,\n\n\n\n last_id: Option<ID>,\n\n}\n\n\n", "file_path": "map_editor/src/main.rs", "rank": 99, "score": 174602.27125593636 } ]
Rust
src/types/float.rs
dholroyd/hls_m3u8
7e6da6224dad326d915d113357e22f6fc0455c92
use core::cmp::Ordering; use core::convert::TryFrom; use core::str::FromStr; use derive_more::{AsRef, Deref, Display}; use crate::Error; #[derive(AsRef, Deref, Default, Debug, Copy, Clone, Display, PartialOrd)] pub struct Float(f32); impl Float { #[must_use] pub fn new(float: f32) -> Self { if float.is_infinite() { panic!("float must be finite: `{}`", float); } if float.is_nan() { panic!("float must not be `NaN`"); } Self(float) } #[must_use] pub const fn as_f32(self) -> f32 { self.0 } } impl FromStr for Float { type Err = Error; fn from_str(input: &str) -> Result<Self, Self::Err> { let float = f32::from_str(input).map_err(|e| Error::parse_float(input, e))?; Self::try_from(float) } } impl TryFrom<f32> for Float { type Error = Error; fn try_from(float: f32) -> Result<Self, Self::Error> { if float.is_infinite() { return Err(Error::custom(format!("float must be finite: `{}`", float))); } if float.is_nan() { return Err(Error::custom("float must not be `NaN`")); } Ok(Self(float)) } } macro_rules! implement_from { ( $( $type:tt ),+ ) => { $( impl ::core::convert::From<$type> for Float { fn from(value: $type) -> Self { Self(value as f32) } } )+ } } implement_from!(i16, u16, i8, u8); impl PartialEq for Float { #[inline] fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } impl PartialEq<f32> for Float { #[inline] fn eq(&self, other: &f32) -> bool { &self.0 == other } } impl Eq for Float {} impl Ord for Float { #[inline] fn cmp(&self, other: &Self) -> Ordering { if self.0 < other.0 { Ordering::Less } else if self == other { Ordering::Equal } else { Ordering::Greater } } } #[doc(hidden)] impl ::core::hash::Hash for Float { fn hash<H>(&self, state: &mut H) where H: ::core::hash::Hasher, { debug_assert!(self.0.is_finite()); debug_assert!(!self.0.is_nan()); if self.0 == 0.0 || self.0 == -0.0 { state.write(&0.0_f32.to_be_bytes()); } else { state.write(&self.to_be_bytes()) } } } #[cfg(test)] mod tests { use super::*; use core::hash::{Hash, Hasher}; use pretty_assertions::assert_eq; #[test] fn test_ord() { assert_eq!(Float::new(1.1).cmp(&Float::new(1.1)), Ordering::Equal); assert_eq!(Float::new(1.1).cmp(&Float::new(2.1)), Ordering::Less); assert_eq!(Float::new(1.1).cmp(&Float::new(0.1)), Ordering::Greater); } #[test] fn test_partial_ord() { assert_eq!( Float::new(1.1).partial_cmp(&Float::new(1.1)), Some(Ordering::Equal) ); assert_eq!( Float::new(1.1).partial_cmp(&Float::new(2.1)), Some(Ordering::Less) ); assert_eq!( Float::new(1.1).partial_cmp(&Float::new(0.1)), Some(Ordering::Greater) ); } #[test] fn test_hash() { let mut hasher_left = std::collections::hash_map::DefaultHasher::new(); let mut hasher_right = std::collections::hash_map::DefaultHasher::new(); assert_eq!( Float::new(0.0).hash(&mut hasher_left), Float::new(-0.0).hash(&mut hasher_right) ); assert_eq!(hasher_left.finish(), hasher_right.finish()); let mut hasher_left = std::collections::hash_map::DefaultHasher::new(); let mut hasher_right = std::collections::hash_map::DefaultHasher::new(); assert_eq!( Float::new(1.0).hash(&mut hasher_left), Float::new(1.0).hash(&mut hasher_right) ); assert_eq!(hasher_left.finish(), hasher_right.finish()); } #[test] fn test_eq() { struct _AssertEq where Float: Eq; } #[test] fn test_partial_eq() { assert_eq!(Float::new(1.0).eq(&Float::new(1.0)), true); assert_eq!(Float::new(1.0).eq(&Float::new(33.3)), false); assert_eq!(Float::new(1.1), 1.1); } #[test] fn test_display() { assert_eq!(Float::new(22.0).to_string(), "22".to_string()); assert_eq!( Float::new(3.14159265359).to_string(), "3.1415927".to_string() ); assert_eq!( Float::new(-3.14159265359).to_string(), "-3.1415927".to_string() ); } #[test] fn test_parser() { assert_eq!(Float::new(22.0), Float::from_str("22").unwrap()); assert_eq!(Float::new(-22.0), Float::from_str("-22").unwrap()); assert_eq!( Float::new(3.14159265359), Float::from_str("3.14159265359").unwrap() ); assert!(Float::from_str("1#").is_err()); assert!(Float::from_str("NaN").is_err()); assert!(Float::from_str("inf").is_err()); assert!(Float::from_str("-inf").is_err()); } #[test] #[should_panic = "float must be finite: `inf`"] fn test_new_infinite() { let _ = Float::new(::core::f32::INFINITY); } #[test] #[should_panic = "float must be finite: `-inf`"] fn test_new_neg_infinite() { let _ = Float::new(::core::f32::NEG_INFINITY); } #[test] #[should_panic = "float must not be `NaN`"] fn test_new_nan() { let _ = Float::new(::core::f32::NAN); } #[test] fn test_as_f32() { assert_eq!(Float::new(1.1).as_f32(), 1.1_f32); } #[test] fn test_from() { assert_eq!(Float::from(-1_i8), Float::new(-1.0)); assert_eq!(Float::from(1_u8), Float::new(1.0)); assert_eq!(Float::from(-1_i16), Float::new(-1.0)); assert_eq!(Float::from(1_u16), Float::new(1.0)); } #[test] fn test_try_from() { assert_eq!(Float::try_from(1.1_f32).unwrap(), Float::new(1.1)); assert_eq!(Float::try_from(-1.1_f32).unwrap(), Float::new(-1.1)); assert!(Float::try_from(::core::f32::INFINITY).is_err()); assert!(Float::try_from(::core::f32::NAN).is_err()); assert!(Float::try_from(::core::f32::NEG_INFINITY).is_err()); } }
use core::cmp::Ordering; use core::convert::TryFrom; use core::str::FromStr; use derive_more::{AsRef, Deref, Display}; use crate::Error; #[derive(AsRef, Deref, Default, Debug, Copy, Clone, Display, PartialOrd)] pub struct Float(f32); impl Float { #[must_use] pub fn new(float: f32) -> Self { if float.is_infinite() { panic!("float must
#[must_use] pub const fn as_f32(self) -> f32 { self.0 } } impl FromStr for Float { type Err = Error; fn from_str(input: &str) -> Result<Self, Self::Err> { let float = f32::from_str(input).map_err(|e| Error::parse_float(input, e))?; Self::try_from(float) } } impl TryFrom<f32> for Float { type Error = Error; fn try_from(float: f32) -> Result<Self, Self::Error> { if float.is_infinite() { return Err(Error::custom(format!("float must be finite: `{}`", float))); } if float.is_nan() { return Err(Error::custom("float must not be `NaN`")); } Ok(Self(float)) } } macro_rules! implement_from { ( $( $type:tt ),+ ) => { $( impl ::core::convert::From<$type> for Float { fn from(value: $type) -> Self { Self(value as f32) } } )+ } } implement_from!(i16, u16, i8, u8); impl PartialEq for Float { #[inline] fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } impl PartialEq<f32> for Float { #[inline] fn eq(&self, other: &f32) -> bool { &self.0 == other } } impl Eq for Float {} impl Ord for Float { #[inline] fn cmp(&self, other: &Self) -> Ordering { if self.0 < other.0 { Ordering::Less } else if self == other { Ordering::Equal } else { Ordering::Greater } } } #[doc(hidden)] impl ::core::hash::Hash for Float { fn hash<H>(&self, state: &mut H) where H: ::core::hash::Hasher, { debug_assert!(self.0.is_finite()); debug_assert!(!self.0.is_nan()); if self.0 == 0.0 || self.0 == -0.0 { state.write(&0.0_f32.to_be_bytes()); } else { state.write(&self.to_be_bytes()) } } } #[cfg(test)] mod tests { use super::*; use core::hash::{Hash, Hasher}; use pretty_assertions::assert_eq; #[test] fn test_ord() { assert_eq!(Float::new(1.1).cmp(&Float::new(1.1)), Ordering::Equal); assert_eq!(Float::new(1.1).cmp(&Float::new(2.1)), Ordering::Less); assert_eq!(Float::new(1.1).cmp(&Float::new(0.1)), Ordering::Greater); } #[test] fn test_partial_ord() { assert_eq!( Float::new(1.1).partial_cmp(&Float::new(1.1)), Some(Ordering::Equal) ); assert_eq!( Float::new(1.1).partial_cmp(&Float::new(2.1)), Some(Ordering::Less) ); assert_eq!( Float::new(1.1).partial_cmp(&Float::new(0.1)), Some(Ordering::Greater) ); } #[test] fn test_hash() { let mut hasher_left = std::collections::hash_map::DefaultHasher::new(); let mut hasher_right = std::collections::hash_map::DefaultHasher::new(); assert_eq!( Float::new(0.0).hash(&mut hasher_left), Float::new(-0.0).hash(&mut hasher_right) ); assert_eq!(hasher_left.finish(), hasher_right.finish()); let mut hasher_left = std::collections::hash_map::DefaultHasher::new(); let mut hasher_right = std::collections::hash_map::DefaultHasher::new(); assert_eq!( Float::new(1.0).hash(&mut hasher_left), Float::new(1.0).hash(&mut hasher_right) ); assert_eq!(hasher_left.finish(), hasher_right.finish()); } #[test] fn test_eq() { struct _AssertEq where Float: Eq; } #[test] fn test_partial_eq() { assert_eq!(Float::new(1.0).eq(&Float::new(1.0)), true); assert_eq!(Float::new(1.0).eq(&Float::new(33.3)), false); assert_eq!(Float::new(1.1), 1.1); } #[test] fn test_display() { assert_eq!(Float::new(22.0).to_string(), "22".to_string()); assert_eq!( Float::new(3.14159265359).to_string(), "3.1415927".to_string() ); assert_eq!( Float::new(-3.14159265359).to_string(), "-3.1415927".to_string() ); } #[test] fn test_parser() { assert_eq!(Float::new(22.0), Float::from_str("22").unwrap()); assert_eq!(Float::new(-22.0), Float::from_str("-22").unwrap()); assert_eq!( Float::new(3.14159265359), Float::from_str("3.14159265359").unwrap() ); assert!(Float::from_str("1#").is_err()); assert!(Float::from_str("NaN").is_err()); assert!(Float::from_str("inf").is_err()); assert!(Float::from_str("-inf").is_err()); } #[test] #[should_panic = "float must be finite: `inf`"] fn test_new_infinite() { let _ = Float::new(::core::f32::INFINITY); } #[test] #[should_panic = "float must be finite: `-inf`"] fn test_new_neg_infinite() { let _ = Float::new(::core::f32::NEG_INFINITY); } #[test] #[should_panic = "float must not be `NaN`"] fn test_new_nan() { let _ = Float::new(::core::f32::NAN); } #[test] fn test_as_f32() { assert_eq!(Float::new(1.1).as_f32(), 1.1_f32); } #[test] fn test_from() { assert_eq!(Float::from(-1_i8), Float::new(-1.0)); assert_eq!(Float::from(1_u8), Float::new(1.0)); assert_eq!(Float::from(-1_i16), Float::new(-1.0)); assert_eq!(Float::from(1_u16), Float::new(1.0)); } #[test] fn test_try_from() { assert_eq!(Float::try_from(1.1_f32).unwrap(), Float::new(1.1)); assert_eq!(Float::try_from(-1.1_f32).unwrap(), Float::new(-1.1)); assert!(Float::try_from(::core::f32::INFINITY).is_err()); assert!(Float::try_from(::core::f32::NAN).is_err()); assert!(Float::try_from(::core::f32::NEG_INFINITY).is_err()); } }
be finite: `{}`", float); } if float.is_nan() { panic!("float must not be `NaN`"); } Self(float) }
function_block-function_prefixed
[ { "content": " pub trait Sealed {}\n\n impl Sealed for crate::MediaSegment {}\n\n impl Sealed for crate::tags::ExtXMap {}\n\n}\n\n\n", "file_path": "src/traits.rs", "rank": 0, "score": 50488.99251107057 }, { "content": "#[doc(hidden)]\n\npub trait RequiredVersion {\n\n /// Returns the protocol compatibility version that this tag requires.\n\n ///\n\n /// # Note\n\n ///\n\n /// This is for the latest working [`ProtocolVersion`] and a client, that\n\n /// only supports an older version would break.\n\n #[must_use]\n\n fn required_version(&self) -> ProtocolVersion;\n\n\n\n /// The protocol version, in which the tag has been introduced.\n\n #[must_use]\n\n fn introduced_version(&self) -> ProtocolVersion { self.required_version() }\n\n}\n\n\n\nimpl<T: RequiredVersion> RequiredVersion for Vec<T> {\n\n fn required_version(&self) -> ProtocolVersion {\n\n self.iter()\n\n .map(RequiredVersion::required_version)\n\n .max()\n", "file_path": "src/traits.rs", "rank": 1, "score": 49307.42488630861 }, { "content": "fn parse_media_playlist(\n\n input: &str,\n\n builder: &mut MediaPlaylistBuilder,\n\n) -> crate::Result<MediaPlaylist> {\n\n let input = tag(input, \"#EXTM3U\")?;\n\n\n\n let mut segment = MediaSegment::builder();\n\n let mut segments = vec![];\n\n\n\n let mut has_partial_segment = false;\n\n let mut has_discontinuity_tag = false;\n\n let mut unknown = vec![];\n\n let mut available_keys = HashSet::new();\n\n\n\n for line in Lines::from(input) {\n\n match line? {\n\n Line::Tag(tag) => {\n\n match tag {\n\n Tag::ExtInf(t) => {\n\n has_partial_segment = true;\n", "file_path": "src/media_playlist.rs", "rank": 2, "score": 48180.54056224784 }, { "content": "#[test]\n\nfn test_readme_deps() {\n\n version_sync::assert_markdown_deps_updated!(\"README.md\");\n\n}\n\n\n", "file_path": "tests/version-number.rs", "rank": 3, "score": 48180.54056224784 }, { "content": "#[test]\n\nfn test_html_root_url() {\n\n version_sync::assert_html_root_url_updated!(\"src/lib.rs\");\n\n}\n", "file_path": "tests/version-number.rs", "rank": 4, "score": 47126.19900364676 }, { "content": "/// Signals that a type or some of the asssociated data might need to be\n\n/// decrypted.\n\n///\n\n/// # Note\n\n///\n\n/// You are not supposed to implement this trait, therefore it is \"sealed\".\n\npub trait Decryptable: private::Sealed {\n\n /// Returns all keys, associated with the type.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n\n /// use hls_m3u8::tags::ExtXMap;\n\n /// use hls_m3u8::types::{ByteRange, EncryptionMethod};\n\n /// use hls_m3u8::Decryptable;\n\n ///\n\n /// let map = ExtXMap::with_range(\"https://www.example.url/\", ByteRange::from(2..11));\n\n ///\n\n /// for key in map.keys() {\n\n /// if key.method == EncryptionMethod::Aes128 {\n\n /// // fetch content with the uri and decrypt the result\n\n /// break;\n\n /// }\n\n /// }\n\n /// ```\n\n #[must_use]\n", "file_path": "src/traits.rs", "rank": 5, "score": 46145.993885423406 }, { "content": "fn criterion_benchmark(c: &mut Criterion) {\n\n let buf = create_manifest_data();\n\n let mut group = c.benchmark_group(\"parser\");\n\n group.throughput(Throughput::Bytes(buf.len() as u64));\n\n group.bench_function(\"throughput\", |b| {\n\n b.iter(|| {\n\n let buf = String::from_utf8_lossy(&buf);\n\n hls_m3u8::MediaPlaylist::from_str(&buf).unwrap()\n\n });\n\n });\n\n}\n\n\n\ncriterion_group!(benches, criterion_benchmark);\n\ncriterion_main!(benches);\n", "file_path": "benches/parse.rs", "rank": 6, "score": 45109.32357371235 }, { "content": "fn create_manifest_data() -> Vec<u8> {\n\n let mut builder = MediaPlaylist::builder();\n\n builder.media_sequence(826176645);\n\n builder.has_independent_segments(true);\n\n builder.target_duration(std::time::Duration::from_secs(2));\n\n for i in 0..4000 {\n\n let mut seg = MediaSegment::builder();\n\n seg.duration(std::time::Duration::from_secs_f64(1.92))\n\n .uri(format!(\n\n \"avc_unencrypted_global-video=3000000-{}.ts?variant=italy\",\n\n 826176659 + i\n\n ));\n\n if i == 0 {\n\n seg.program_date_time(ExtXProgramDateTime::new(\"2020-04-07T11:32:38Z\"));\n\n }\n\n if i % 100 == 0 {\n\n let mut date_range =\n\n ExtXDateRange::new(format!(\"{}\", i / 100), \"2020-04-07T11:40:02.040000Z\");\n\n date_range.duration = Some(std::time::Duration::from_secs_f64(65.2));\n\n date_range.client_attributes.insert(\"SCTE35-OUT\".to_string(), Value::Hex(hex::decode(\"FC302500000000000000FFF0140500001C207FEFFE0030E3A0FE005989E000010000000070BA5ABF\").unwrap()));\n\n seg.date_range(date_range);\n\n }\n\n builder.push_segment(seg.build().unwrap());\n\n }\n\n builder.build().unwrap().to_string().into_bytes()\n\n}\n\n\n", "file_path": "benches/parse.rs", "rank": 7, "score": 44828.689777487685 }, { "content": "use core::cmp::Ordering;\n\nuse core::convert::TryFrom;\n\nuse core::str::FromStr;\n\n\n\nuse derive_more::{AsRef, Deref, Display};\n\n\n\nuse crate::Error;\n\n\n\n/// A wrapper type around an [`f32`], that can not be constructed\n\n/// with a negative float (e.g. `-1.1`), [`NaN`], [`INFINITY`] or\n\n/// [`NEG_INFINITY`].\n\n///\n\n/// [`NaN`]: core::f32::NAN\n\n/// [`INFINITY`]: core::f32::INFINITY\n\n/// [`NEG_INFINITY`]: core::f32::NEG_INFINITY\n\n#[derive(AsRef, Deref, Default, Debug, Copy, Clone, PartialOrd, Display)]\n\npub struct UFloat(f32);\n\n\n\nimpl UFloat {\n\n /// Makes a new [`UFloat`] from an [`f32`].\n", "file_path": "src/types/ufloat.rs", "rank": 24, "score": 42.69257949525109 }, { "content": " ///\n\n /// ```\n\n /// # use hls_m3u8::types::UFloat;\n\n /// assert_eq!(UFloat::new(1.1_f32).as_f32(), 1.1_f32);\n\n /// ```\n\n #[must_use]\n\n pub const fn as_f32(self) -> f32 { self.0 }\n\n}\n\n\n\nimpl FromStr for UFloat {\n\n type Err = Error;\n\n\n\n fn from_str(input: &str) -> Result<Self, Self::Err> {\n\n let float = f32::from_str(input).map_err(|e| Error::parse_float(input, e))?;\n\n Self::try_from(float)\n\n }\n\n}\n\n\n\nimpl TryFrom<f32> for UFloat {\n\n type Error = Error;\n", "file_path": "src/types/ufloat.rs", "rank": 25, "score": 31.81417513726809 }, { "content": " #[must_use]\n\n pub fn new(float: f32) -> Self {\n\n if float.is_infinite() {\n\n panic!(\"float must be finite: `{}`\", float);\n\n }\n\n\n\n if float.is_nan() {\n\n panic!(\"float must not be `NaN`\");\n\n }\n\n\n\n if float.is_sign_negative() {\n\n panic!(\"float must be positive: `{}`\", float);\n\n }\n\n\n\n Self(float)\n\n }\n\n\n\n /// Returns the underlying [`f32`].\n\n ///\n\n /// # Example\n", "file_path": "src/types/ufloat.rs", "rank": 26, "score": 28.179624763631633 }, { "content": "use std::str::FromStr;\n\n\n\nuse derive_more::Display;\n\nuse shorthand::ShortHand;\n\n\n\nuse crate::Error;\n\n\n\n/// The number of distinct pixels in each dimension that can be displayed (e.g.\n\n/// 1920x1080).\n\n///\n\n/// For example Full HD has a resolution of 1920x1080.\n\n#[derive(ShortHand, Ord, PartialOrd, Debug, Clone, Copy, PartialEq, Eq, Hash, Display)]\n\n#[display(fmt = \"{}x{}\", width, height)]\n\n#[shorthand(enable(must_use))]\n\npub struct Resolution {\n\n /// Horizontal pixel dimension.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n", "file_path": "src/types/resolution.rs", "rank": 27, "score": 27.24695523367891 }, { "content": "use std::fmt;\n\nuse std::str::FromStr;\n\n\n\nuse crate::types::Float;\n\nuse crate::utils::{quote, unquote};\n\nuse crate::Error;\n\n\n\n/// A `Value`.\n\n#[non_exhaustive]\n\n#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]\n\npub enum Value {\n\n /// A `String`.\n\n String(String),\n\n /// A sequence of bytes.\n\n Hex(Vec<u8>),\n\n /// A floating point number, that's neither NaN nor infinite.\n\n Float(Float),\n\n}\n\n\n\nimpl fmt::Display for Value {\n", "file_path": "src/types/value.rs", "rank": 28, "score": 27.188899977666896 }, { "content": "use std::fmt;\n\nuse std::str::FromStr;\n\n\n\nuse crate::types::ProtocolVersion;\n\nuse crate::utils::tag;\n\nuse crate::{Error, RequiredVersion};\n\n\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]\n\npub(crate) struct ExtXIFramesOnly;\n\n\n\nimpl ExtXIFramesOnly {\n\n pub(crate) const PREFIX: &'static str = \"#EXT-X-I-FRAMES-ONLY\";\n\n}\n\n\n\n/// This tag requires [`ProtocolVersion::V4`].\n\nimpl RequiredVersion for ExtXIFramesOnly {\n\n fn required_version(&self) -> ProtocolVersion { ProtocolVersion::V4 }\n\n}\n\n\n\nimpl fmt::Display for ExtXIFramesOnly {\n", "file_path": "src/tags/media_playlist/i_frames_only.rs", "rank": 29, "score": 25.949537159773286 }, { "content": "use std::fmt;\n\nuse std::str::FromStr;\n\n\n\nuse crate::types::ProtocolVersion;\n\nuse crate::utils::tag;\n\nuse crate::{Error, RequiredVersion};\n\n\n\n/// Allows synchronization between different renditions of the same\n\n/// [`VariantStream`].\n\n///\n\n/// [`VariantStream`]: crate::tags::VariantStream\n\n#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Hash)]\n\npub(crate) struct ExtXDiscontinuitySequence(pub usize);\n\n\n\nimpl ExtXDiscontinuitySequence {\n\n pub(crate) const PREFIX: &'static str = \"#EXT-X-DISCONTINUITY-SEQUENCE:\";\n\n}\n\n\n\n/// This tag requires [`ProtocolVersion::V1`].\n\nimpl RequiredVersion for ExtXDiscontinuitySequence {\n", "file_path": "src/tags/media_playlist/discontinuity_sequence.rs", "rank": 30, "score": 25.389503006257097 }, { "content": "/// ```\n\n///\n\n/// [RFC6381]: https://tools.ietf.org/html/rfc6381\n\n/// [`VariantStream`]: crate::tags::VariantStream\n\n#[derive(\n\n AsMut, AsRef, Deref, DerefMut, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default,\n\n)]\n\npub struct Codecs {\n\n list: Vec<String>,\n\n}\n\n\n\nimpl Codecs {\n\n /// Makes a new (empty) [`Codecs`] struct.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n\n /// # use hls_m3u8::types::Codecs;\n\n /// let codecs = Codecs::new();\n\n /// ```\n", "file_path": "src/types/codecs.rs", "rank": 31, "score": 25.36437241838329 }, { "content": "impl<'a> From<&'a str> for Lines<'a> {\n\n fn from(buffer: &'a str) -> Self {\n\n Self {\n\n lines: buffer\n\n .lines()\n\n .filter_map(|line| Some(line.trim()).filter(|v| !v.is_empty())),\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq)]\n\npub(crate) enum Line<'a> {\n\n Tag(Tag<'a>),\n\n Comment(&'a str),\n\n Uri(&'a str),\n\n}\n\n\n\n#[allow(clippy::large_enum_variant)]\n\n#[derive(Debug, Clone, PartialEq, Display)]\n\n#[display(fmt = \"{}\")]\n", "file_path": "src/line.rs", "rank": 32, "score": 25.348895471999455 }, { "content": "use std::fmt;\n\nuse std::str::FromStr;\n\nuse std::time::Duration;\n\n\n\nuse crate::types::ProtocolVersion;\n\nuse crate::utils::tag;\n\nuse crate::{Error, RequiredVersion};\n\n\n\n/// Specifies the maximum `MediaSegment` duration.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]\n\npub(crate) struct ExtXTargetDuration(pub Duration);\n\n\n\nimpl ExtXTargetDuration {\n\n pub(crate) const PREFIX: &'static str = \"#EXT-X-TARGETDURATION:\";\n\n}\n\n\n\n/// This tag requires [`ProtocolVersion::V1`].\n\nimpl RequiredVersion for ExtXTargetDuration {\n\n fn required_version(&self) -> ProtocolVersion { ProtocolVersion::V1 }\n\n}\n", "file_path": "src/tags/media_playlist/target_duration.rs", "rank": 33, "score": 25.27023317522603 }, { "content": "use core::convert::TryFrom;\n\nuse core::iter::FusedIterator;\n\nuse core::str::FromStr;\n\n\n\nuse derive_more::Display;\n\n\n\nuse crate::tags;\n\nuse crate::types::PlaylistType;\n\nuse crate::Error;\n\n\n\n#[derive(Debug, Clone)]\n\npub(crate) struct Lines<'a> {\n\n lines: ::core::iter::FilterMap<::core::str::Lines<'a>, fn(&'a str) -> Option<&'a str>>,\n\n}\n\n\n\nimpl<'a> Iterator for Lines<'a> {\n\n type Item = crate::Result<Line<'a>>;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n let line = self.lines.next()?;\n", "file_path": "src/line.rs", "rank": 34, "score": 25.019156919276146 }, { "content": "use std::fmt;\n\nuse std::str::FromStr;\n\n\n\nuse crate::types::ProtocolVersion;\n\nuse crate::utils::tag;\n\nuse crate::{Error, RequiredVersion};\n\n\n\n/// Indicates the Media Sequence Number of the first `MediaSegment` that\n\n/// appears in a `MediaPlaylist`.\n\n#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\npub(crate) struct ExtXMediaSequence(pub usize);\n\n\n\nimpl ExtXMediaSequence {\n\n pub(crate) const PREFIX: &'static str = \"#EXT-X-MEDIA-SEQUENCE:\";\n\n}\n\n\n\n/// This tag requires [`ProtocolVersion::V1`].\n\nimpl RequiredVersion for ExtXMediaSequence {\n\n fn required_version(&self) -> ProtocolVersion { ProtocolVersion::V1 }\n\n}\n", "file_path": "src/tags/media_playlist/media_sequence.rs", "rank": 35, "score": 24.930072859628137 }, { "content": "use core::fmt;\n\nuse core::str::FromStr;\n\n\n\nuse shorthand::ShortHand;\n\n\n\nuse crate::Error;\n\n\n\n/// The maximum number of independent, simultaneous audio channels present in\n\n/// any [`MediaSegment`] in the rendition.\n\n///\n\n/// For example, an `AC-3 5.1` rendition would have a maximum channel number of\n\n/// 6.\n\n///\n\n/// [`MediaSegment`]: crate::MediaSegment\n\n#[derive(ShortHand, Debug, Clone, Copy, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]\n\n#[shorthand(enable(must_use))]\n\npub struct Channels {\n\n /// The maximum number of independent simultaneous audio channels.\n\n ///\n\n /// # Example\n", "file_path": "src/types/channels.rs", "rank": 36, "score": 24.487101008396763 }, { "content": "use core::iter::FusedIterator;\n\n\n\n#[derive(Clone, Debug)]\n\npub(crate) struct AttributePairs<'a> {\n\n string: &'a str,\n\n index: usize,\n\n}\n\n\n\nimpl<'a> AttributePairs<'a> {\n\n pub const fn new(string: &'a str) -> Self { Self { string, index: 0 } }\n\n}\n\n\n\nimpl<'a> Iterator for AttributePairs<'a> {\n\n type Item = (&'a str, &'a str);\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n // return `None`, if there are no more bytes\n\n self.string.as_bytes().get(self.index + 1)?;\n\n\n\n let key = {\n", "file_path": "src/attribute.rs", "rank": 37, "score": 24.337876103253027 }, { "content": "impl ProtocolVersion {\n\n /// Returns the latest [`ProtocolVersion`] that is supported by\n\n /// this library.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n\n /// # use hls_m3u8::types::ProtocolVersion;\n\n /// assert_eq!(ProtocolVersion::latest(), ProtocolVersion::V7);\n\n /// ```\n\n #[must_use]\n\n #[inline]\n\n pub const fn latest() -> Self { Self::V7 }\n\n}\n\n\n\nimpl fmt::Display for ProtocolVersion {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n match &self {\n\n Self::V1 => write!(f, \"1\"),\n\n Self::V2 => write!(f, \"2\"),\n", "file_path": "src/types/protocol_version.rs", "rank": 38, "score": 24.18152142323749 }, { "content": " #[inline]\n\n #[must_use]\n\n pub const fn new() -> Self { Self { list: Vec::new() } }\n\n}\n\n\n\nimpl fmt::Display for Codecs {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n if let Some(codec) = self.list.iter().next() {\n\n write!(f, \"{}\", codec)?;\n\n\n\n for codec in self.list.iter().skip(1) {\n\n write!(f, \",{}\", codec)?;\n\n }\n\n }\n\n\n\n Ok(())\n\n }\n\n}\n\nimpl FromStr for Codecs {\n\n type Err = Error;\n", "file_path": "src/types/codecs.rs", "rank": 39, "score": 23.78673821872449 }, { "content": " /// # use hls_m3u8::tags::ExtXStart;\n\n /// use hls_m3u8::types::Float;\n\n ///\n\n /// let start = ExtXStart::with_precise(Float::new(20.123456), true);\n\n /// assert_eq!(start.is_precise(), true);\n\n /// ```\n\n #[must_use]\n\n pub const fn with_precise(time_offset: Float, is_precise: bool) -> Self {\n\n Self {\n\n time_offset,\n\n is_precise,\n\n }\n\n }\n\n}\n\n\n\n/// This tag requires [`ProtocolVersion::V1`].\n\nimpl RequiredVersion for ExtXStart {\n\n fn required_version(&self) -> ProtocolVersion { ProtocolVersion::V1 }\n\n}\n\n\n", "file_path": "src/tags/shared/start.rs", "rank": 40, "score": 23.72217037065027 }, { "content": "use std::fmt;\n\nuse std::str::FromStr;\n\n\n\nuse shorthand::ShortHand;\n\n\n\nuse crate::attribute::AttributePairs;\n\nuse crate::types::{Float, ProtocolVersion};\n\nuse crate::utils::{parse_yes_or_no, tag};\n\nuse crate::{Error, RequiredVersion};\n\n\n\n/// This tag indicates a preferred point at which to start\n\n/// playing a Playlist.\n\n///\n\n/// By default, clients should start playback at this point when beginning a\n\n/// playback session.\n\n#[derive(ShortHand, PartialOrd, Debug, Clone, Copy, PartialEq, Eq, Ord, Hash)]\n\n#[shorthand(enable(must_use))]\n\npub struct ExtXStart {\n\n /// The time offset of the [`MediaSegment`]s in the playlist.\n\n ///\n", "file_path": "src/tags/shared/start.rs", "rank": 41, "score": 23.646842095785253 }, { "content": " ///\n\n /// assert_eq!(InitializationVector::Number(4).is_none(), false);\n\n ///\n\n /// assert_eq!(InitializationVector::Missing.is_none(), true);\n\n /// ```\n\n #[must_use]\n\n #[inline]\n\n pub fn is_none(&self) -> bool { *self == Self::Missing }\n\n}\n\n\n\nimpl Default for InitializationVector {\n\n fn default() -> Self { Self::Missing }\n\n}\n\n\n\nimpl From<[u8; 0x10]> for InitializationVector {\n\n fn from(value: [u8; 0x10]) -> Self { Self::Aes128(value) }\n\n}\n\n\n\nimpl From<Option<[u8; 0x10]>> for InitializationVector {\n\n fn from(value: Option<[u8; 0x10]>) -> Self {\n", "file_path": "src/types/initialization_vector.rs", "rank": 42, "score": 23.626986753814126 }, { "content": " ///\n\n /// println!(\"CHANNELS=\\\"{}\\\"\", channels);\n\n /// # assert_eq!(format!(\"CHANNELS=\\\"{}\\\"\", channels), \"CHANNELS=\\\"6\\\"\".to_string());\n\n /// ```\n\n //#[inline]\n\n #[must_use]\n\n pub const fn new(number: u64) -> Self { Self { number } }\n\n}\n\n\n\nimpl FromStr for Channels {\n\n type Err = Error;\n\n\n\n fn from_str(input: &str) -> Result<Self, Self::Err> {\n\n Ok(Self::new(\n\n input.parse().map_err(|e| Error::parse_int(input, e))?,\n\n ))\n\n }\n\n}\n\n\n\nimpl fmt::Display for Channels {\n", "file_path": "src/types/channels.rs", "rank": 43, "score": 23.61664248743736 }, { "content": "use std::fmt;\n\nuse std::str::FromStr;\n\n\n\nuse crate::types::ProtocolVersion;\n\nuse crate::utils::tag;\n\nuse crate::{Error, RequiredVersion};\n\n\n\n/// The [`ExtM3u`] tag indicates that the file is an **Ext**ended **[`M3U`]**\n\n/// Playlist file.\n\n/// It is the at the start of every [`MediaPlaylist`] and [`MasterPlaylist`].\n\n///\n\n/// [`MediaPlaylist`]: crate::MediaPlaylist\n\n/// [`MasterPlaylist`]: crate::MasterPlaylist\n\n/// [`M3U`]: https://en.wikipedia.org/wiki/M3U\n\n#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]\n\npub(crate) struct ExtM3u;\n\n\n\nimpl ExtM3u {\n\n pub(crate) const PREFIX: &'static str = \"#EXTM3U\";\n\n}\n", "file_path": "src/tags/basic/m3u.rs", "rank": 44, "score": 23.508147000004918 }, { "content": " /// assert_eq!(versions.is_default(), true);\n\n ///\n\n /// versions.push(1);\n\n /// assert_eq!(versions.is_default(), true);\n\n ///\n\n /// assert_eq!(KeyFormatVersions::default().is_default(), true);\n\n /// ```\n\n #[must_use]\n\n pub fn is_default(&self) -> bool {\n\n self.is_empty() || (self.buffer[self.len().saturating_sub(1)] == 1 && self.len() == 1)\n\n }\n\n}\n\n\n\nimpl PartialEq for KeyFormatVersions {\n\n fn eq(&self, other: &Self) -> bool {\n\n if self.len() == other.len() {\n\n // only compare the parts in the buffer, that are used:\n\n self.as_ref() == self.as_ref()\n\n } else {\n\n false\n", "file_path": "src/types/key_format_versions.rs", "rank": 45, "score": 23.25320021365313 }, { "content": "use strum::{Display, EnumString};\n\n\n\n/// Specifies the media type.\n\n#[non_exhaustive]\n\n#[allow(missing_docs)]\n\n#[derive(Ord, PartialOrd, Display, EnumString, Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\n#[strum(serialize_all = \"SCREAMING-KEBAB-CASE\")]\n\npub enum MediaType {\n\n Audio,\n\n Video,\n\n Subtitles,\n\n ClosedCaptions,\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use pretty_assertions::assert_eq;\n\n\n\n #[test]\n", "file_path": "src/types/media_type.rs", "rank": 46, "score": 22.9500370181858 }, { "content": "use std::fmt;\n\nuse std::str::FromStr;\n\n\n\nuse derive_builder::Builder;\n\nuse shorthand::ShortHand;\n\n\n\nuse crate::attribute::AttributePairs;\n\nuse crate::types::{\n\n EncryptionMethod, InitializationVector, KeyFormat, KeyFormatVersions, ProtocolVersion,\n\n};\n\nuse crate::utils::{quote, unquote};\n\nuse crate::{Error, RequiredVersion};\n\n\n\n/// Specifies how to decrypt encrypted data from the server.\n\n#[derive(ShortHand, Builder, Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]\n\n#[builder(setter(into), build_fn(validate = \"Self::validate\"))]\n\n#[shorthand(enable(skip, must_use, into))]\n\n#[non_exhaustive]\n\npub struct DecryptionKey {\n\n /// The encryption method, which has been used to encrypt the data.\n", "file_path": "src/types/decryption_key.rs", "rank": 47, "score": 22.781206921235697 }, { "content": "/// - `DerefMut<Target=DateTime<FixedOffset>>`\n\n/// - and `Copy`\n\n///\n\n/// will be derived.\n\n///\n\n/// [`MediaSegment`]: crate::MediaSegment\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]\n\n#[cfg_attr(feature = \"chrono\", derive(Deref, DerefMut, Copy))]\n\n#[non_exhaustive]\n\npub struct ExtXProgramDateTime {\n\n /// The date-time of the first sample of the associated media segment.\n\n #[cfg(feature = \"chrono\")]\n\n #[cfg_attr(feature = \"chrono\", deref_mut, deref)]\n\n pub date_time: DateTime<FixedOffset>,\n\n /// The date-time of the first sample of the associated media segment.\n\n #[cfg(not(feature = \"chrono\"))]\n\n pub date_time: String,\n\n}\n\n\n\nimpl ExtXProgramDateTime {\n", "file_path": "src/tags/media_segment/program_date_time.rs", "rank": 48, "score": 22.183082656655014 }, { "content": "use std::fmt;\n\nuse std::str::FromStr;\n\n\n\nuse crate::types::ProtocolVersion;\n\nuse crate::utils::tag;\n\nuse crate::{Error, RequiredVersion};\n\n\n\n/// The `ExtXDiscontinuity` tag indicates a discontinuity between the\n\n/// `MediaSegment` that follows it and the one that preceded it.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]\n\npub(crate) struct ExtXDiscontinuity;\n\n\n\nimpl ExtXDiscontinuity {\n\n pub(crate) const PREFIX: &'static str = \"#EXT-X-DISCONTINUITY\";\n\n}\n\n\n\n/// This tag requires [`ProtocolVersion::V1`].\n\nimpl RequiredVersion for ExtXDiscontinuity {\n\n fn required_version(&self) -> ProtocolVersion { ProtocolVersion::V1 }\n\n}\n", "file_path": "src/tags/media_segment/discontinuity.rs", "rank": 49, "score": 21.93222035636412 }, { "content": "use std::fmt;\n\nuse std::str::FromStr;\n\n\n\nuse crate::types::ProtocolVersion;\n\nuse crate::utils::tag;\n\nuse crate::{Error, RequiredVersion};\n\n\n\n/// Signals that all media samples in a [`MediaSegment`] can be decoded without\n\n/// information from other segments.\n\n///\n\n/// [`MediaSegment`]: crate::MediaSegment\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]\n\npub(crate) struct ExtXIndependentSegments;\n\n\n\nimpl ExtXIndependentSegments {\n\n pub(crate) const PREFIX: &'static str = \"#EXT-X-INDEPENDENT-SEGMENTS\";\n\n}\n\n\n\n/// This tag requires [`ProtocolVersion::V1`].\n\nimpl RequiredVersion for ExtXIndependentSegments {\n", "file_path": "src/tags/shared/independent_segments.rs", "rank": 50, "score": 21.85122168677229 }, { "content": "/// let range = ByteRange::from(..20);\n\n/// ```\n\n#[derive(ShortHand, Copy, Hash, Eq, Ord, Debug, PartialEq, Clone, PartialOrd)]\n\n#[shorthand(enable(must_use, copy), disable(option_as_ref, set))]\n\npub struct ByteRange {\n\n /// Returns the `start` of the [`ByteRange`], if there is one.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n\n /// # use hls_m3u8::types::ByteRange;\n\n /// assert_eq!(ByteRange::from(0..5).start(), Some(0));\n\n /// assert_eq!(ByteRange::from(..5).start(), None);\n\n /// ```\n\n start: Option<usize>,\n\n /// Returns the `end` of the [`ByteRange`].\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n", "file_path": "src/types/byte_range.rs", "rank": 51, "score": 21.82524826489018 }, { "content": " ///\n\n /// ```\n\n /// # use hls_m3u8::tags::ExtXStart;\n\n /// use hls_m3u8::types::Float;\n\n ///\n\n /// let start = ExtXStart::new(Float::new(20.123456));\n\n /// ```\n\n #[must_use]\n\n pub const fn new(time_offset: Float) -> Self {\n\n Self {\n\n time_offset,\n\n is_precise: false,\n\n }\n\n }\n\n\n\n /// Makes a new [`ExtXStart`] tag with the given `precise` flag.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n", "file_path": "src/tags/shared/start.rs", "rank": 52, "score": 21.713209827113776 }, { "content": "\n\nimpl Resolution {\n\n /// Constructs a new [`Resolution`].\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n\n /// # use hls_m3u8::types::Resolution;\n\n /// let resolution = Resolution::new(1920, 1080);\n\n /// ```\n\n #[must_use]\n\n pub const fn new(width: usize, height: usize) -> Self { Self { width, height } }\n\n}\n\n\n\nimpl From<(usize, usize)> for Resolution {\n\n fn from(value: (usize, usize)) -> Self { Self::new(value.0, value.1) }\n\n}\n\n\n\nimpl Into<(usize, usize)> for Resolution {\n\n fn into(self) -> (usize, usize) { (self.width, self.height) }\n", "file_path": "src/types/resolution.rs", "rank": 53, "score": 21.503284471001106 }, { "content": "/// assert_eq!(ExtXByteRange::from(22..55), ExtXByteRange::from(22..=54));\n\n/// ```\n\n///\n\n/// It is also possible to omit the start, in which case it assumes that the\n\n/// [`ExtXByteRange`] starts at the byte after the end of the previous\n\n/// [`ExtXByteRange`] or 0 if there is no previous one.\n\n///\n\n/// ```\n\n/// # use hls_m3u8::tags::ExtXByteRange;\n\n/// assert_eq!(ExtXByteRange::from(..55), ExtXByteRange::from(..=54));\n\n/// ```\n\n///\n\n/// [`MediaSegment`]: crate::MediaSegment\n\n#[derive(\n\n AsRef, AsMut, From, Deref, DerefMut, Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord,\n\n)]\n\n#[from(forward)]\n\npub struct ExtXByteRange(ByteRange);\n\n\n\nimpl ExtXByteRange {\n", "file_path": "src/tags/media_segment/byte_range.rs", "rank": 54, "score": 21.493882975605832 }, { "content": " /// ```\n\n /// # use hls_m3u8::types::ByteRange;\n\n /// let range = ByteRange::from(12..12);\n\n ///\n\n /// assert_eq!(range.is_empty(), true);\n\n /// ```\n\n #[inline]\n\n #[must_use]\n\n pub fn is_empty(&self) -> bool { self.len() == 0 }\n\n}\n\n\n\nimpl Sub<usize> for ByteRange {\n\n type Output = Self;\n\n\n\n #[must_use]\n\n #[inline]\n\n fn sub(self, rhs: usize) -> Self::Output {\n\n Self {\n\n start: self.start.map(|lhs| lhs - rhs),\n\n end: self.end - rhs,\n", "file_path": "src/types/byte_range.rs", "rank": 55, "score": 21.409203334955965 }, { "content": "use std::fmt;\n\nuse std::str::FromStr;\n\n\n\nuse crate::types::ProtocolVersion;\n\nuse crate::utils::tag;\n\nuse crate::{Error, RequiredVersion};\n\n\n\n/// Indicates that no more [`MediaSegment`]s will be added to the\n\n/// [`MediaPlaylist`] file.\n\n///\n\n/// [`MediaSegment`]: crate::MediaSegment\n\n/// [`MediaPlaylist`]: crate::MediaPlaylist\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]\n\npub(crate) struct ExtXEndList;\n\n\n\nimpl ExtXEndList {\n\n pub(crate) const PREFIX: &'static str = \"#EXT-X-ENDLIST\";\n\n}\n\n\n\n/// This tag requires [`ProtocolVersion::V1`].\n", "file_path": "src/tags/media_playlist/end_list.rs", "rank": 56, "score": 21.215198829336213 }, { "content": "\n\n#[doc(hidden)]\n\nimpl From<::strum::ParseError> for Error {\n\n fn from(value: ::strum::ParseError) -> Self { Self::strum(value) }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use pretty_assertions::assert_eq;\n\n\n\n #[test]\n\n fn test_parse_float_error() {\n\n assert_eq!(\n\n Error::parse_float(\n\n \"1.x234\",\n\n \"1.x234\"\n\n .parse::<f32>()\n\n .expect_err(\"this should not parse as a float!\")\n\n )\n", "file_path": "src/error.rs", "rank": 57, "score": 21.191734878492905 }, { "content": "use std::fmt;\n\nuse std::str::FromStr;\n\n\n\nuse crate::types::ProtocolVersion;\n\nuse crate::utils::tag;\n\nuse crate::{Error, RequiredVersion};\n\n\n\n/// The compatibility version of a playlist.\n\n///\n\n/// It applies to the entire [`MasterPlaylist`] or [`MediaPlaylist`].\n\n///\n\n/// [`MediaPlaylist`]: crate::MediaPlaylist\n\n/// [`MasterPlaylist`]: crate::MasterPlaylist\n\n#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]\n\npub struct ExtXVersion(ProtocolVersion);\n\n\n\nimpl ExtXVersion {\n\n pub(crate) const PREFIX: &'static str = \"#EXT-X-VERSION:\";\n\n\n\n /// Makes a new [`ExtXVersion`] tag.\n", "file_path": "src/tags/basic/version.rs", "rank": 58, "score": 21.130124313242895 }, { "content": " /// assert_eq!(\n\n /// ExtXVersion::new(ProtocolVersion::V6).version(),\n\n /// ProtocolVersion::V6\n\n /// );\n\n /// ```\n\n #[must_use]\n\n pub const fn version(self) -> ProtocolVersion { self.0 }\n\n}\n\n\n\n/// This tag requires [`ProtocolVersion::V1`].\n\nimpl RequiredVersion for ExtXVersion {\n\n fn required_version(&self) -> ProtocolVersion { ProtocolVersion::V1 }\n\n}\n\n\n\nimpl fmt::Display for ExtXVersion {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n //\n\n write!(f, \"{}{}\", Self::PREFIX, self.0)\n\n }\n\n}\n", "file_path": "src/tags/basic/version.rs", "rank": 59, "score": 21.12424739330324 }, { "content": " \"6\" => Self::V6,\n\n \"7\" => Self::V7,\n\n _ => return Err(Error::unknown_protocol_version(input)),\n\n }\n\n })\n\n }\n\n}\n\n\n\n/// The default is [`ProtocolVersion::V1`].\n\nimpl Default for ProtocolVersion {\n\n fn default() -> Self { Self::V1 }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use pretty_assertions::assert_eq;\n\n\n\n #[test]\n\n fn test_display() {\n", "file_path": "src/types/protocol_version.rs", "rank": 60, "score": 21.066531217195735 }, { "content": "impl ExtInf {\n\n pub(crate) const PREFIX: &'static str = \"#EXTINF:\";\n\n\n\n /// Makes a new [`ExtInf`] tag.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n\n /// # use hls_m3u8::tags::ExtInf;\n\n /// use std::time::Duration;\n\n ///\n\n /// let ext_inf = ExtInf::new(Duration::from_secs(5));\n\n /// ```\n\n #[must_use]\n\n pub const fn new(duration: Duration) -> Self {\n\n Self {\n\n duration,\n\n title: None,\n\n }\n\n }\n", "file_path": "src/tags/media_segment/inf.rs", "rank": 61, "score": 20.933254079161244 }, { "content": "use strum::{Display, EnumString};\n\n\n\n/// The encryption method.\n\n#[non_exhaustive]\n\n#[allow(missing_docs)]\n\n#[derive(Ord, PartialOrd, Debug, Clone, Copy, PartialEq, Eq, Hash, Display, EnumString)]\n\n#[strum(serialize_all = \"SCREAMING-KEBAB-CASE\")]\n\npub enum EncryptionMethod {\n\n /// The [`MediaSegment`]s are completely encrypted using the Advanced\n\n /// Encryption Standard ([AES-128]) with a 128-bit key, Cipher Block\n\n /// Chaining (CBC), and [Public-Key Cryptography Standards #7 (PKCS7)]\n\n /// padding.\n\n ///\n\n /// CBC is restarted on each segment boundary, using either the\n\n /// Initialization Vector (IV) or the Media Sequence Number as the IV\n\n ///\n\n /// ```\n\n /// # let media_sequence_number = 5;\n\n /// # assert_eq!(\n\n /// format!(\"0x{:032x}\", media_sequence_number)\n", "file_path": "src/types/encryption_method.rs", "rank": 62, "score": 20.43443568472104 }, { "content": " /// ```\n\n #[must_use]\n\n pub fn builder() -> ExtXMediaBuilder { ExtXMediaBuilder::default() }\n\n}\n\n\n\n/// This tag requires either `ProtocolVersion::V1` or if there is an\n\n/// `instream_id` it requires it's version.\n\nimpl RequiredVersion for ExtXMedia {\n\n fn required_version(&self) -> ProtocolVersion {\n\n self.instream_id\n\n .map_or(ProtocolVersion::V1, |i| i.required_version())\n\n }\n\n}\n\n\n\nimpl fmt::Display for ExtXMedia {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"{}\", Self::PREFIX)?;\n\n write!(f, \"TYPE={}\", self.media_type)?;\n\n\n\n if let Some(value) = &self.uri {\n", "file_path": "src/tags/master_playlist/media.rs", "rank": 63, "score": 20.05529690070083 }, { "content": "\n\n fn try_from(float: f32) -> Result<Self, Self::Error> {\n\n if float.is_infinite() {\n\n return Err(Error::custom(format!(\"float must be finite: `{}`\", float)));\n\n }\n\n\n\n if float.is_nan() {\n\n return Err(Error::custom(\"float must not be `NaN`\"));\n\n }\n\n\n\n if float.is_sign_negative() {\n\n return Err(Error::custom(format!(\n\n \"float must be positive: `{}`\",\n\n float\n\n )));\n\n }\n\n\n\n Ok(Self(float))\n\n }\n\n}\n", "file_path": "src/types/ufloat.rs", "rank": 64, "score": 19.85731706055082 }, { "content": "/// closed_captions: None,\n\n/// stream_data: StreamData::builder()\n\n/// .bandwidth(240000)\n\n/// .codecs(&[\"avc1.42e00a\", \"mp4a.40.2\"])\n\n/// .resolution((416, 234))\n\n/// .build()\n\n/// .unwrap(),\n\n/// },\n\n/// ])\n\n/// .has_independent_segments(true)\n\n/// .start(ExtXStart::new(Float::new(1.23)))\n\n/// .build()?;\n\n/// # Ok::<(), Box<dyn ::std::error::Error>>(())\n\n/// ```\n\n///\n\n/// [`MediaPlaylist`]: crate::MediaPlaylist\n\n#[derive(Builder, Default, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\n#[builder(build_fn(validate = \"Self::validate\"))]\n\n#[builder(setter(into, strip_option))]\n\n#[non_exhaustive]\n", "file_path": "src/master_playlist.rs", "rank": 65, "score": 19.533681881239428 }, { "content": "}\n\n\n\nimpl DecryptionKey {\n\n /// Creates a new `DecryptionKey` from an uri pointing to the key data and\n\n /// an `EncryptionMethod`.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n\n /// # use hls_m3u8::types::DecryptionKey;\n\n /// use hls_m3u8::types::EncryptionMethod;\n\n ///\n\n /// let key = DecryptionKey::new(EncryptionMethod::Aes128, \"https://www.example.uri/key\");\n\n /// ```\n\n #[must_use]\n\n #[inline]\n\n pub fn new<I: Into<String>>(method: EncryptionMethod, uri: I) -> Self {\n\n Self {\n\n method,\n\n uri: uri.into(),\n", "file_path": "src/types/decryption_key.rs", "rank": 66, "score": 19.23106731976864 }, { "content": "use std::fmt;\n\nuse std::str::FromStr;\n\n\n\nuse crate::Error;\n\n\n\n/// The [`ProtocolVersion`] specifies which `m3u8` revision is required, to\n\n/// parse a certain tag correctly.\n\n#[non_exhaustive]\n\n#[allow(missing_docs)]\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\npub enum ProtocolVersion {\n\n V1,\n\n V2,\n\n V3,\n\n V4,\n\n V5,\n\n V6,\n\n V7,\n\n}\n\n\n", "file_path": "src/types/protocol_version.rs", "rank": 67, "score": 18.962010396631754 }, { "content": " /// ));\n\n /// ```\n\n #[must_use]\n\n #[inline]\n\n pub const fn new(inner: DecryptionKey) -> Self { Self(inner) }\n\n}\n\n\n\nimpl TryFrom<ExtXKey> for ExtXSessionKey {\n\n type Error = Error;\n\n\n\n fn try_from(value: ExtXKey) -> Result<Self, Self::Error> {\n\n if let ExtXKey(Some(inner)) = value {\n\n Ok(Self(inner))\n\n } else {\n\n Err(Error::custom(\"missing decryption key\"))\n\n }\n\n }\n\n}\n\n\n\n/// This tag requires the same [`ProtocolVersion`] that is returned by\n", "file_path": "src/tags/master_playlist/session_key.rs", "rank": 68, "score": 18.92443906070974 }, { "content": "use std::fmt;\n\nuse std::str::FromStr;\n\n\n\nuse crate::types::{DecryptionKey, ProtocolVersion};\n\nuse crate::utils::tag;\n\nuse crate::{Error, RequiredVersion};\n\n\n\n/// Specifies how to decrypt encrypted data from the server.\n\n///\n\n/// An unencrypted segment should be marked with [`ExtXKey::empty`].\n\n#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]\n\npub struct ExtXKey(pub Option<DecryptionKey>);\n\n\n\nimpl ExtXKey {\n\n pub(crate) const PREFIX: &'static str = \"#EXT-X-KEY:\";\n\n\n\n /// Constructs an [`ExtXKey`] tag.\n\n ///\n\n /// # Example\n\n ///\n", "file_path": "src/tags/media_segment/key.rs", "rank": 69, "score": 18.85810374623977 }, { "content": " clippy::unneeded_field_pattern,\n\n clippy::wrong_pub_self_convention\n\n)]\n\n// those should not be present in production code:\n\n#![deny(\n\n clippy::print_stdout,\n\n clippy::todo,\n\n clippy::unimplemented,\n\n clippy::dbg_macro,\n\n clippy::use_debug\n\n)]\n\n#![warn(\n\n missing_docs,\n\n missing_copy_implementations,\n\n missing_debug_implementations,\n\n trivial_casts,\n\n trivial_numeric_casts\n\n)]\n\n//! [HLS] m3u8 parser/generator.\n\n//!\n", "file_path": "src/lib.rs", "rank": 70, "score": 18.685190515771108 }, { "content": "#[shorthand(enable(must_use, into))]\n\n#[builder(setter(into))]\n\n#[builder(build_fn(validate = \"Self::validate\"))]\n\npub struct ExtXMedia {\n\n /// The [`MediaType`] associated with this tag.\n\n ///\n\n /// ### Note\n\n ///\n\n /// This field is required.\n\n #[shorthand(enable(skip))]\n\n pub media_type: MediaType,\n\n /// An `URI` to a [`MediaPlaylist`].\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n\n /// # use hls_m3u8::tags::ExtXMedia;\n\n /// use hls_m3u8::types::MediaType;\n\n ///\n\n /// let mut media = ExtXMedia::new(MediaType::Audio, \"ag1\", \"english audio channel\");\n", "file_path": "src/tags/master_playlist/media.rs", "rank": 71, "score": 18.601097114663233 }, { "content": "#[allow(missing_docs)]\n\n#[strum(serialize_all = \"UPPERCASE\")]\n\n#[derive(Ord, PartialOrd, Debug, Clone, Copy, PartialEq, Eq, Hash, Display, EnumString)]\n\npub enum InStreamId {\n\n Cc1,\n\n Cc2,\n\n Cc3,\n\n Cc4,\n\n Service1,\n\n Service2,\n\n Service3,\n\n Service4,\n\n Service5,\n\n Service6,\n\n Service7,\n\n Service8,\n\n Service9,\n\n Service10,\n\n Service11,\n\n Service12,\n", "file_path": "src/types/in_stream_id.rs", "rank": 72, "score": 18.516603698888535 }, { "content": "use std::fmt;\n\nuse std::str::FromStr;\n\nuse std::time::Duration;\n\n\n\nuse derive_more::AsRef;\n\n\n\nuse crate::types::ProtocolVersion;\n\nuse crate::utils::tag;\n\nuse crate::{Error, RequiredVersion};\n\n\n\n/// Specifies the duration of a [`Media Segment`].\n\n///\n\n/// [`Media Segment`]: crate::media_segment::MediaSegment\n\n#[derive(AsRef, Default, Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]\n\npub struct ExtInf {\n\n #[as_ref]\n\n duration: Duration,\n\n title: Option<String>,\n\n}\n\n\n", "file_path": "src/tags/media_segment/inf.rs", "rank": 73, "score": 18.470113184314943 }, { "content": "\n\nmacro_rules! implement_from {\n\n ( $( $type:tt ),+ ) => {\n\n $(\n\n impl ::core::convert::From<$type> for UFloat {\n\n fn from(value: $type) -> Self {\n\n Self(value as f32)\n\n }\n\n }\n\n )+\n\n }\n\n}\n\n\n\nimplement_from!(u16, u8);\n\n\n\n// This has to be implemented explicitly, because `Hash` is also implemented\n\n// manually and both implementations have to agree according to clippy.\n\nimpl PartialEq for UFloat {\n\n #[inline]\n\n fn eq(&self, other: &Self) -> bool { self.0 == other.0 }\n", "file_path": "src/types/ufloat.rs", "rank": 74, "score": 18.307032978674563 }, { "content": " #[shorthand(enable(copy))]\n\n range: Option<ByteRange>,\n\n #[shorthand(enable(skip))]\n\n pub(crate) keys: Vec<ExtXKey>,\n\n}\n\n\n\nimpl ExtXMap {\n\n pub(crate) const PREFIX: &'static str = \"#EXT-X-MAP:\";\n\n\n\n /// Makes a new [`ExtXMap`] tag.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n\n /// # use hls_m3u8::tags::ExtXMap;\n\n /// let map = ExtXMap::new(\"https://prod.mediaspace.com/init.bin\");\n\n /// ```\n\n pub fn new<T: Into<String>>(uri: T) -> Self {\n\n Self {\n\n uri: uri.into(),\n", "file_path": "src/tags/media_segment/map.rs", "rank": 75, "score": 18.255801953895592 }, { "content": " source,\n\n })\n\n }\n\n\n\n pub(crate) fn parse_float<T: fmt::Display>(\n\n input: T,\n\n source: ::std::num::ParseFloatError,\n\n ) -> Self {\n\n Self::new(ErrorKind::ParseFloatError {\n\n input: input.to_string(),\n\n source,\n\n })\n\n }\n\n\n\n pub(crate) fn missing_tag<T, U>(tag: T, input: U) -> Self\n\n where\n\n T: ToString,\n\n U: ToString,\n\n {\n\n Self::new(ErrorKind::MissingTag {\n", "file_path": "src/error.rs", "rank": 76, "score": 18.056475111968375 }, { "content": " }\n\n\n\n result\n\n }\n\n}\n\n\n\nimpl<'a> FromIterator<&'a u8> for KeyFormatVersions {\n\n fn from_iter<I: IntoIterator<Item = &'a u8>>(iter: I) -> Self {\n\n <Self as FromIterator<u8>>::from_iter(iter.into_iter().copied())\n\n }\n\n}\n\n\n\nimpl Default for KeyFormatVersions {\n\n #[inline]\n\n fn default() -> Self {\n\n Self {\n\n buffer: [0; 9],\n\n len: 0,\n\n }\n\n }\n", "file_path": "src/types/key_format_versions.rs", "rank": 77, "score": 17.975738580083437 }, { "content": "use strum::{Display, EnumString};\n\n\n\n/// HDCP ([`High-bandwidth Digital Content Protection`]) level.\n\n///\n\n/// [`High-bandwidth Digital Content Protection`]:\n\n/// https://www.digital-cp.com/sites/default/files/specifications/HDCP%20on%20HDMI%20Specification%20Rev2_2_Final1.pdf\n\n#[non_exhaustive]\n\n#[derive(Ord, PartialOrd, Debug, Clone, Copy, PartialEq, Eq, Hash, Display, EnumString)]\n\n#[strum(serialize_all = \"SCREAMING-KEBAB-CASE\")]\n\npub enum HdcpLevel {\n\n /// The associated [`VariantStream`] could fail to play unless the output is\n\n /// protected by High-bandwidth Digital Content Protection ([`HDCP`]) Type 0\n\n /// or equivalent.\n\n ///\n\n /// [`VariantStream`]: crate::tags::VariantStream\n\n /// [`HDCP`]: https://www.digital-cp.com/sites/default/files/specifications/HDCP%20on%20HDMI%20Specification%20Rev2_2_Final1.pdf\n\n #[strum(serialize = \"TYPE-0\")]\n\n Type0,\n\n /// The content does not require output copy protection.\n\n None,\n", "file_path": "src/types/hdcp_level.rs", "rank": 78, "score": 17.878358212434485 }, { "content": "use core::fmt;\n\nuse core::str::FromStr;\n\n\n\nuse derive_builder::Builder;\n\nuse shorthand::ShortHand;\n\n\n\nuse crate::attribute::AttributePairs;\n\nuse crate::types::{Codecs, HdcpLevel, ProtocolVersion, Resolution};\n\nuse crate::utils::{quote, unquote};\n\nuse crate::{Error, RequiredVersion};\n\n\n\n/// The [`StreamData`] struct contains the data that is shared between both\n\n/// variants of the [`VariantStream`].\n\n///\n\n/// [`VariantStream`]: crate::tags::VariantStream\n\n#[derive(ShortHand, Builder, PartialOrd, Debug, Clone, PartialEq, Eq, Hash, Ord)]\n\n#[builder(setter(strip_option))]\n\n#[builder(derive(Debug, PartialEq, PartialOrd, Ord, Eq, Hash))]\n\n#[shorthand(enable(must_use, into))]\n\npub struct StreamData {\n", "file_path": "src/types/stream_data.rs", "rank": 79, "score": 17.807541305558615 }, { "content": " fn keys(&self) -> Vec<&DecryptionKey>;\n\n\n\n /// Most of the time only a single key is provided, so instead of iterating\n\n /// through all keys, one might as well just get the first key.\n\n #[must_use]\n\n #[inline]\n\n fn first_key(&self) -> Option<&DecryptionKey> {\n\n <Self as Decryptable>::keys(self).first().copied()\n\n }\n\n\n\n /// Returns the number of keys.\n\n #[must_use]\n\n #[inline]\n\n fn len(&self) -> usize { <Self as Decryptable>::keys(self).len() }\n\n\n\n /// Returns `true`, if the number of keys is zero.\n\n #[must_use]\n\n #[inline]\n\n fn is_empty(&self) -> bool { <Self as Decryptable>::len(self) == 0 }\n\n}\n\n\n", "file_path": "src/traits.rs", "rank": 80, "score": 17.681102572056357 }, { "content": "\n\nimpl fmt::Display for ExtXDiscontinuity {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Self::PREFIX.fmt(f) }\n\n}\n\n\n\nimpl FromStr for ExtXDiscontinuity {\n\n type Err = Error;\n\n\n\n fn from_str(input: &str) -> Result<Self, Self::Err> {\n\n tag(input, Self::PREFIX)?;\n\n Ok(Self)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use pretty_assertions::assert_eq;\n\n\n\n #[test]\n", "file_path": "src/tags/media_segment/discontinuity.rs", "rank": 81, "score": 17.634515722656513 }, { "content": "use std::fmt;\n\nuse std::str::FromStr;\n\n\n\nuse crate::types::ProtocolVersion;\n\nuse crate::utils::tag;\n\nuse crate::{Error, RequiredVersion};\n\n\n\n/// Provides mutability information about the [`MediaPlaylist`].\n\n///\n\n/// It applies to the entire [`MediaPlaylist`].\n\n///\n\n/// [`MediaPlaylist`]: crate::MediaPlaylist\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]\n\npub enum PlaylistType {\n\n /// If the [`PlaylistType`] is Event, [`MediaSegment`]s\n\n /// can only be added to the end of the [`MediaPlaylist`].\n\n ///\n\n /// [`MediaSegment`]: crate::MediaSegment\n\n /// [`MediaPlaylist`]: crate::MediaPlaylist\n\n Event,\n", "file_path": "src/types/playlist_type.rs", "rank": 82, "score": 17.5478951991939 }, { "content": " ///\n\n /// ```\n\n /// use hls_m3u8::types::{HdcpLevel, StreamData};\n\n ///\n\n /// StreamData::builder()\n\n /// .bandwidth(200)\n\n /// .average_bandwidth(15)\n\n /// .codecs(&[\"mp4a.40.2\", \"avc1.4d401e\"])\n\n /// .resolution((1920, 1080))\n\n /// .hdcp_level(HdcpLevel::Type0)\n\n /// .video(\"video_01\")\n\n /// .build()?;\n\n /// # Ok::<(), Box<dyn ::std::error::Error>>(())\n\n /// ```\n\n #[must_use]\n\n pub fn builder() -> StreamDataBuilder { StreamDataBuilder::default() }\n\n}\n\n\n\nimpl fmt::Display for StreamData {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n", "file_path": "src/types/stream_data.rs", "rank": 83, "score": 17.544920760704713 }, { "content": "use std::fmt;\n\nuse std::str::FromStr;\n\n\n\nuse crate::types::ProtocolVersion;\n\nuse crate::utils::{quote, tag, unquote};\n\nuse crate::{Error, RequiredVersion};\n\n\n\n/// Specifies how the key is represented in the resource identified by the\n\n/// `URI`.\n\n#[non_exhaustive]\n\n#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]\n\npub enum KeyFormat {\n\n /// An [`EncryptionMethod::Aes128`] uses 16-octet (16 byte/128 bit) keys. If\n\n /// the format is [`KeyFormat::Identity`], the key file is a single packed\n\n /// array of 16 octets (16 byte/128 bit) in binary format.\n\n ///\n\n /// [`EncryptionMethod::Aes128`]: crate::types::EncryptionMethod::Aes128\n\n Identity,\n\n}\n\n\n", "file_path": "src/types/key_format.rs", "rank": 84, "score": 17.26271048683108 }, { "content": " fn required_version(&self) -> ProtocolVersion { ProtocolVersion::V1 }\n\n}\n\n\n\nimpl fmt::Display for ExtXIndependentSegments {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Self::PREFIX.fmt(f) }\n\n}\n\n\n\nimpl FromStr for ExtXIndependentSegments {\n\n type Err = Error;\n\n\n\n fn from_str(input: &str) -> Result<Self, Self::Err> {\n\n tag(input, Self::PREFIX)?;\n\n Ok(Self)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use pretty_assertions::assert_eq;\n", "file_path": "src/tags/shared/independent_segments.rs", "rank": 85, "score": 17.138915347764392 }, { "content": " }\n\n }\n\n}\n\n\n\nimpl SubAssign<usize> for ByteRange {\n\n #[inline]\n\n fn sub_assign(&mut self, other: usize) { *self = <Self as Sub<usize>>::sub(*self, other); }\n\n}\n\n\n\nimpl Add<usize> for ByteRange {\n\n type Output = Self;\n\n\n\n #[must_use]\n\n #[inline]\n\n fn add(self, rhs: usize) -> Self::Output {\n\n Self {\n\n start: self.start.map(|lhs| lhs + rhs),\n\n end: self.end + rhs,\n\n }\n\n }\n", "file_path": "src/types/byte_range.rs", "rank": 86, "score": 17.127430325744825 }, { "content": "impl Default for KeyFormat {\n\n fn default() -> Self { Self::Identity }\n\n}\n\n\n\nimpl FromStr for KeyFormat {\n\n type Err = Error;\n\n\n\n fn from_str(input: &str) -> Result<Self, Self::Err> {\n\n tag(&unquote(input), \"identity\")?; // currently only KeyFormat::Identity exists!\n\n\n\n Ok(Self::Identity)\n\n }\n\n}\n\n\n\nimpl fmt::Display for KeyFormat {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, \"{}\", quote(&\"identity\")) }\n\n}\n\n\n\n/// This tag requires [`ProtocolVersion::V5`].\n\nimpl RequiredVersion for KeyFormat {\n", "file_path": "src/types/key_format.rs", "rank": 87, "score": 17.02081298151554 }, { "content": "// be soundly implemented.\n\nimpl Eq for UFloat {}\n\n\n\nimpl Ord for UFloat {\n\n #[inline]\n\n fn cmp(&self, other: &Self) -> Ordering {\n\n if self.0 < other.0 {\n\n Ordering::Less\n\n } else if self == other {\n\n Ordering::Equal\n\n } else {\n\n Ordering::Greater\n\n }\n\n }\n\n}\n\n\n\n/// The output of Hash cannot be relied upon to be stable. The same version of\n\n/// rust can return different values in different architectures. This is not a\n\n/// property of the Hasher that you’re using but instead of the way Hash happens\n\n/// to be implemented for the type you’re using (e.g., the current\n", "file_path": "src/types/ufloat.rs", "rank": 88, "score": 16.97791623468268 }, { "content": "pub struct Error {\n\n inner: ErrorKind,\n\n #[cfg(feature = \"backtrace\")]\n\n backtrace: Backtrace,\n\n}\n\n\n\nimpl PartialEq for Error {\n\n fn eq(&self, other: &Self) -> bool { self.inner == other.inner }\n\n}\n\n\n\nimpl std::error::Error for Error {}\n\n\n\nimpl fmt::Display for Error {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.inner.fmt(f) }\n\n}\n\n\n\n#[allow(clippy::needless_pass_by_value)]\n\nimpl Error {\n\n fn new(inner: ErrorKind) -> Self {\n\n Self {\n", "file_path": "src/error.rs", "rank": 89, "score": 16.927476971517592 }, { "content": " fn from(value: &str) -> Self { Self::String(unquote(value)) }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use pretty_assertions::assert_eq;\n\n\n\n #[test]\n\n fn test_display() {\n\n assert_eq!(Value::Float(Float::new(1.1)).to_string(), \"1.1\".to_string());\n\n assert_eq!(\n\n Value::String(\"&str\".to_string()).to_string(),\n\n \"\\\"&str\\\"\".to_string()\n\n );\n\n assert_eq!(\n\n Value::Hex(vec![1, 2, 3]).to_string(),\n\n \"0x010203\".to_string()\n\n );\n\n }\n", "file_path": "src/types/value.rs", "rank": 90, "score": 16.91020533612944 }, { "content": " fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Self::PREFIX.fmt(f) }\n\n}\n\n\n\nimpl FromStr for ExtXIFramesOnly {\n\n type Err = Error;\n\n\n\n fn from_str(input: &str) -> Result<Self, Self::Err> {\n\n tag(input, Self::PREFIX)?;\n\n Ok(Self)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use pretty_assertions::assert_eq;\n\n\n\n #[test]\n\n fn test_display() {\n\n assert_eq!(\n", "file_path": "src/tags/media_playlist/i_frames_only.rs", "rank": 91, "score": 16.783714555741458 }, { "content": "impl From<crate::tags::ExtXSessionKey> for ExtXKey {\n\n fn from(value: crate::tags::ExtXSessionKey) -> Self { Self(Some(value.0)) }\n\n}\n\n\n\nimpl fmt::Display for ExtXKey {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"{}\", Self::PREFIX)?;\n\n\n\n if let Some(value) = &self.0 {\n\n write!(f, \"{}\", value)\n\n } else {\n\n write!(f, \"METHOD=NONE\")\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use crate::types::{EncryptionMethod, KeyFormat};\n", "file_path": "src/tags/media_segment/key.rs", "rank": 92, "score": 16.783701859677656 }, { "content": "/// fixed size array is used internally (`[u8; 9]`), which can store a maximum\n\n/// number of 9 `u8` numbers.\n\n///\n\n/// If you encounter any m3u8 file, which fails to parse, because the buffer is\n\n/// too small, feel free to [make an issue](https://github.com/sile/hls_m3u8/issues).\n\n///\n\n/// ## Example\n\n///\n\n/// ```\n\n/// use hls_m3u8::types::KeyFormatVersions;\n\n///\n\n/// assert_eq!(\n\n/// KeyFormatVersions::from([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]).to_string(),\n\n/// \"\\\"255/255/255/255/255/255/255/255/255\\\"\".to_string()\n\n/// );\n\n/// ```\n\n///\n\n/// [`KeyFormat`]: crate::types::KeyFormat\n\n#[derive(Debug, Clone, Copy)]\n\npub struct KeyFormatVersions {\n", "file_path": "src/types/key_format_versions.rs", "rank": 93, "score": 16.776321366916875 }, { "content": "use core::convert::Infallible;\n\nuse std::fmt;\n\nuse std::str::FromStr;\n\n\n\nuse crate::utils::{quote, unquote};\n\n\n\n/// The identifier of a closed captions group or its absence.\n\n#[non_exhaustive]\n\n#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]\n\npub enum ClosedCaptions {\n\n /// It indicates the set of closed-caption renditions that can be used when\n\n /// playing the presentation.\n\n ///\n\n /// The [`String`] must match [`ExtXMedia::group_id`] elsewhere in the\n\n /// Playlist and it's [`ExtXMedia::media_type`] must be\n\n /// [`MediaType::ClosedCaptions`].\n\n ///\n\n /// [`ExtXMedia::group_id`]: crate::tags::ExtXMedia::group_id\n\n /// [`ExtXMedia::media_type`]: crate::tags::ExtXMedia::media_type\n\n /// [`MediaType::ClosedCaptions`]: crate::types::MediaType::ClosedCaptions\n", "file_path": "src/types/closed_captions.rs", "rank": 94, "score": 16.671385778965508 }, { "content": " /// ```\n\n /// # use hls_m3u8::types::StreamData;\n\n /// #\n\n /// let stream = StreamData::new(20);\n\n /// ```\n\n #[must_use]\n\n pub const fn new(bandwidth: u64) -> Self {\n\n Self {\n\n bandwidth,\n\n average_bandwidth: None,\n\n codecs: None,\n\n resolution: None,\n\n hdcp_level: None,\n\n video: None,\n\n }\n\n }\n\n\n\n /// Returns a builder for [`StreamData`].\n\n ///\n\n /// # Example\n", "file_path": "src/types/stream_data.rs", "rank": 95, "score": 16.63681184657285 }, { "content": "\n\nimpl MediaPlaylist {\n\n /// Returns a builder for [`MediaPlaylist`].\n\n #[must_use]\n\n #[inline]\n\n pub fn builder() -> MediaPlaylistBuilder { MediaPlaylistBuilder::default() }\n\n\n\n /// Computes the `Duration` of the [`MediaPlaylist`], by adding each segment\n\n /// duration together.\n\n #[must_use]\n\n pub fn duration(&self) -> Duration {\n\n self.segments.values().map(|s| s.duration.duration()).sum()\n\n }\n\n}\n\n\n\nimpl RequiredVersion for MediaPlaylist {\n\n fn required_version(&self) -> ProtocolVersion {\n\n required_version![\n\n ExtXTargetDuration(self.target_duration),\n\n (self.media_sequence != 0).athen(|| ExtXMediaSequence(self.media_sequence)),\n", "file_path": "src/media_playlist.rs", "rank": 96, "score": 16.584089457212617 }, { "content": "impl RequiredVersion for ExtXEndList {\n\n fn required_version(&self) -> ProtocolVersion { ProtocolVersion::V1 }\n\n}\n\n\n\nimpl fmt::Display for ExtXEndList {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Self::PREFIX.fmt(f) }\n\n}\n\n\n\nimpl FromStr for ExtXEndList {\n\n type Err = Error;\n\n\n\n fn from_str(input: &str) -> Result<Self, Self::Err> {\n\n tag(input, Self::PREFIX)?;\n\n Ok(Self)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n", "file_path": "src/tags/media_playlist/end_list.rs", "rank": 97, "score": 16.531724528219442 }, { "content": " ///\n\n /// # Example\n\n ///\n\n /// ```\n\n /// # use hls_m3u8::tags::ExtXVersion;\n\n /// use hls_m3u8::types::ProtocolVersion;\n\n ///\n\n /// let version = ExtXVersion::new(ProtocolVersion::V2);\n\n /// ```\n\n #[must_use]\n\n pub const fn new(version: ProtocolVersion) -> Self { Self(version) }\n\n\n\n /// Returns the underlying [`ProtocolVersion`].\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n\n /// # use hls_m3u8::tags::ExtXVersion;\n\n /// use hls_m3u8::types::ProtocolVersion;\n\n ///\n", "file_path": "src/tags/basic/version.rs", "rank": 98, "score": 16.510173750604302 }, { "content": "use std::fmt;\n\n\n\n#[cfg(feature = \"backtrace\")]\n\nuse backtrace::Backtrace;\n\nuse thiserror::Error;\n\n\n\n//use crate::types::ProtocolVersion;\n\n\n\n/// This crate specific `Result` type.\n\npub type Result<T> = std::result::Result<T, Error>;\n\n\n\n#[derive(Debug, Error, Clone, PartialEq)]\n\n#[non_exhaustive]\n", "file_path": "src/error.rs", "rank": 99, "score": 16.502654017174073 } ]
Rust
src/app.rs
rsookram/srs-cli
8825fcf6a7f9055d5f13ac8a23cf55f6d959895d
use crate::Srs; use anyhow::anyhow; use anyhow::Result; use dialoguer::theme::Theme; use dialoguer::Confirm; use srs_cli::Card; use srs_cli::DeckStats; use srs_cli::GlobalStats; use std::io; pub struct App<W: io::Write> { srs: Srs, output: W, } impl<W: io::Write> App<W> { pub fn new(srs: Srs, output: W) -> Self { Self { srs, output } } pub fn add(&mut self, deck_id: u64) -> Result<()> { let (front, back) = open_editor("", "")?; self.srs.create_card(deck_id, front, back) } pub fn cards(&mut self) -> Result<()> { for card in self.srs.card_previews()? { let front = card.front.replace('\n', " "); if card.is_leech { writeln!(self.output, "[leech] {} {front}", card.id)?; } else { writeln!(self.output, "{} {front}", card.id)?; } } Ok(()) } pub fn create_deck(&mut self, name: &str) -> Result<()> { self.srs.create_deck(name)?; writeln!(self.output, "Created {name}")?; Ok(()) } pub fn decks(&mut self) -> Result<()> { for deck in self.srs.decks()? { writeln!( self.output, "{} {} - {}%", deck.id, deck.name, deck.interval_modifier )?; } Ok(()) } pub fn delete(&mut self, card_id: u64) -> Result<()> { let front: String = self.srs.get_card(card_id)?.front; if Confirm::new() .with_prompt(format!( "Are you sure you want to delete '{}'", front.replace('\n', " ") )) .interact()? { self.srs.delete_card(card_id)?; writeln!(self.output, "... deleted.")?; } Ok(()) } pub fn delete_deck(&mut self, deck_id: u64) -> Result<()> { let name = self.srs.get_deck(deck_id)?.name; if Confirm::new() .with_prompt(format!("Are you sure you want to delete '{name}'")) .interact()? { self.srs.delete_deck(deck_id)?; writeln!(self.output, "... deleted.")?; } Ok(()) } pub fn edit(&mut self, card_id: u64) -> Result<()> { let card = self.srs.get_card(card_id)?; let (front, back) = open_editor(&card.front, &card.back)?; self.srs.update_card(card_id, front, back) } pub fn init(&mut self) -> Result<()> { self.srs.init() } pub fn int_mod(&mut self, deck_id: u64, modifier: u16) -> Result<()> { let name: String = self.srs.get_deck(deck_id)?.name; self.srs.update_interval_modifier(deck_id, modifier)?; writeln!( self.output, "Set interval modifier for {name} to {modifier}" )?; Ok(()) } pub fn review(&mut self) -> Result<()> { let cards = self.srs.cards_to_review()?; writeln!( self.output, "{} cards to review", cards.iter().flat_map(|(_, cc)| cc).count() )?; for (deck_name, cards) in cards { let num_cards = cards.len(); writeln!( self.output, "\n{num_cards} cards to review in {deck_name}\n" )?; let mut num_correct = 0; for card in cards { let is_correct = self.review_card(&card)?; if is_correct { num_correct += 1; self.srs.answer_correct(card.id)?; } else { self.srs.answer_wrong(card.id)?; } writeln!(self.output)?; } writeln!(self.output, "Answered {num_correct}/{num_cards} correctly")?; } writeln!(self.output, "Finished review")?; Ok(()) } fn review_card(&mut self, card: &Card) -> Result<bool> { writeln!(self.output, "{}\n", &card.front)?; Confirm::with_theme(&PlainPrompt) .with_prompt("Press enter to show answer") .default(true) .show_default(false) .report(false) .interact()?; writeln!(self.output, "{}", "-".repeat(79))?; writeln!(self.output, "{}\n", &card.back)?; Ok(Confirm::new().with_prompt("Correct?").interact()?) } pub fn stats(&mut self) -> Result<()> { let (global_stats, deck_stats) = self.srs.stats()?; self.output_global(&global_stats)?; for stat in deck_stats.iter() { writeln!(self.output)?; self.output_deck(stat)?; } Ok(()) } fn output_global(&mut self, stats: &GlobalStats) -> Result<()> { let total = stats.active + stats.suspended + (stats.leech as u32); writeln!(self.output, "{} / {total} active", stats.active)?; if stats.leech > 0 { writeln!(self.output, "{} leeches", stats.leech)?; } writeln!(self.output, "Review tomorrow: {}", stats.for_review)?; Ok(()) } fn output_deck(&mut self, stats: &DeckStats) -> Result<()> { let total = stats.active + stats.suspended + (stats.leech as u32); writeln!( self.output, "{}\n {} / {total} active", stats.name, stats.active )?; if stats.leech > 0 { writeln!(self.output, " {} leeches", stats.leech)?; } let num_answered = stats.correct + stats.wrong; writeln!( self.output, " Past month accuracy: {:.0}% ({} / {num_answered})", if num_answered > 0 { stats.correct as f32 / num_answered as f32 * 100.0 } else { 100.0 }, stats.correct, )?; Ok(()) } pub fn switch(&mut self, card_id: u64, deck_id: u64) -> Result<()> { let front = self.srs.get_card(card_id)?.front; let deck_name = self.srs.get_deck(deck_id)?.name; if Confirm::new() .with_prompt(format!( "Are you sure you want to switch '{front}' to {deck_name}?" )) .interact()? { self.srs.switch_deck(card_id, deck_id)?; writeln!(self.output, "... switched.")?; } Ok(()) } } struct PlainPrompt; impl Theme for PlainPrompt { fn format_confirm_prompt( &self, f: &mut dyn std::fmt::Write, prompt: &str, _default: Option<bool>, ) -> std::fmt::Result { write!(f, "{}", &prompt) } } fn open_editor(front: &str, back: &str) -> Result<(String, String)> { let divider = "----------"; let template = format!("{front}\n{divider}\n{back}\n"); let output = scrawl::with(&template)?; output .split_once(divider) .map(|(front, back)| (front.trim().to_string(), back.trim().to_string())) .ok_or_else(|| anyhow!("Missing divider between front and back of card")) .and_then(|(front, back)| { if front.is_empty() { Err(anyhow!("Front of card can't be empty")) } else { Ok((front, back)) } }) }
use crate::Srs; use anyhow::anyhow; use anyhow::Result; use dialoguer::theme::Theme; use dialoguer::Confirm; use srs_cli::Card; use srs_cli::DeckStats; use srs_cli::GlobalStats; use std::io; pub struct App<W: io::Write> { srs: Srs, output: W, } impl<W: io::Write> App<W> { pub fn new(srs: Srs, output: W) -> Self { Self { srs, output } } pub fn add(&mut self, deck_id: u64) -> Result<()> { let (front, back) = open_editor("", "")?; self.srs.create_card(deck_id, front, back) } pub fn cards(&mut self) -> Result<()> { for card in self.srs.card_previews()? { let front = card.front.replace('\n', " "); if card.is_leech { writeln!(self.output, "[leech] {} {front}", card.id)?; } else { writeln!(self.output, "{} {front}", card.id)?; } } Ok(()) } pub fn create_deck(&mut self, name: &str) -> Result<()> { self.srs.create_deck(name)?; writeln!(self.output, "Created {name}")?; Ok(()) } pub fn decks(&mut self) -> Result<()> { for deck in self.srs.decks()? { writeln!( self.output, "{} {} - {}%", deck.id, deck.name, deck.interval_modifier )?; } Ok(()) } pub fn delete(&mut self, card_id: u64) -> Result<()> { let front: String = self.srs.get_card(card_id)?.front; if Confirm::new() .with_prompt(format!( "Are you sure you want to delete '{}'", front.replace('\n', " ") )) .interact()? { self.srs.delete_card(card_id)?; writeln!(self.output, "... deleted.")?; } Ok(()) } pub fn delete_deck(&mut self, deck_id: u64) -> Result<()> { let name = self.srs.get_deck(deck_id)?.name; if Confirm::new() .with_prompt(format!("Are you sure you want to delete '{name}'")) .interact()? { self.srs.delete_deck(deck_id)?; writeln!(self.output, "... deleted.")?; } Ok(()) } pub fn edit(&mut self, card_id: u64) -> Result<()> { let card = self.srs.get_card(card_id)?; let (front, back) = open_editor(&card.front, &card.back)?; self.srs.update_card(card_id, front, back) } pub fn init(&mut self) -> Result<()> { self.srs.init() } pub fn int_mod(&mut self, deck_id: u64, modifier: u16) -> Result<()> { let name: String = self.srs.get_deck(deck_id)?.name; self.srs.update_interval_modifier(deck_id, modifier)?; writeln!( self.output, "Set interval modifier for {name} to {modifier}" )?; Ok(()) } pub fn review(&mut self) -> Result<()> { let cards = self.srs.cards_to_review()?; writeln!( self.output, "{} cards to review", cards.iter().flat_map(|(_, cc)| cc).count() )?; for (deck_name, cards) in cards { let num_cards = cards.len(); writeln!( self.output, "\n{num_cards} cards to review in {deck_name}\n" )?; let mut num_correct = 0; for card in cards { let is_correct = self.review_card(&card)?; if is_correct { num_correct += 1; self.srs.answer_correct(card.id)?; } else { self.srs.answer_wrong(card.id)?; } writeln!(self.output)?; } writeln!(self.output, "Answered {num_correct}/{num_cards} correctly")?; } writeln!(self.output, "Finished review")?; Ok(()) } fn review_card(&mut self, card: &Card) -> Result<bool> { writeln!(self.output, "{}\n", &card.front)?; Confirm::with_theme(&PlainPrompt) .with_prompt("Press enter to show answer") .default(true) .show_default(false) .report(false) .interact()?; writeln!(self.output, "{}", "-".repeat(79))?; writeln!(self.output, "{}\n", &card.back)?; Ok(Confirm::new().with_prompt("Correct?").interact()?) } pub fn stats(&mut self) -> Result<()> { let (global_stats, deck_stats) = self.srs.stats()?; self.output_global(&global_stats)?; for stat in deck_stats.iter() { writeln!(self.output)?; self.output_deck(stat)?; } Ok(()) } fn output_global(&mut self, stats: &GlobalStats) -> Result<()> { let total = stats.active + stats.suspended + (stats.leech as u32); writeln!(self.output, "{} / {total} active", stats.active)?; if stats.leech > 0 { writeln!(self.output, "{} leeches", stats.leech)?; } writeln!(self.output, "Review tomorrow: {}", stats.for_review)?; Ok(()) }
pub fn switch(&mut self, card_id: u64, deck_id: u64) -> Result<()> { let front = self.srs.get_card(card_id)?.front; let deck_name = self.srs.get_deck(deck_id)?.name; if Confirm::new() .with_prompt(format!( "Are you sure you want to switch '{front}' to {deck_name}?" )) .interact()? { self.srs.switch_deck(card_id, deck_id)?; writeln!(self.output, "... switched.")?; } Ok(()) } } struct PlainPrompt; impl Theme for PlainPrompt { fn format_confirm_prompt( &self, f: &mut dyn std::fmt::Write, prompt: &str, _default: Option<bool>, ) -> std::fmt::Result { write!(f, "{}", &prompt) } } fn open_editor(front: &str, back: &str) -> Result<(String, String)> { let divider = "----------"; let template = format!("{front}\n{divider}\n{back}\n"); let output = scrawl::with(&template)?; output .split_once(divider) .map(|(front, back)| (front.trim().to_string(), back.trim().to_string())) .ok_or_else(|| anyhow!("Missing divider between front and back of card")) .and_then(|(front, back)| { if front.is_empty() { Err(anyhow!("Front of card can't be empty")) } else { Ok((front, back)) } }) }
fn output_deck(&mut self, stats: &DeckStats) -> Result<()> { let total = stats.active + stats.suspended + (stats.leech as u32); writeln!( self.output, "{}\n {} / {total} active", stats.name, stats.active )?; if stats.leech > 0 { writeln!(self.output, " {} leeches", stats.leech)?; } let num_answered = stats.correct + stats.wrong; writeln!( self.output, " Past month accuracy: {:.0}% ({} / {num_answered})", if num_answered > 0 { stats.correct as f32 / num_answered as f32 * 100.0 } else { 100.0 }, stats.correct, )?; Ok(()) }
function_block-full_function
[ { "content": "CREATE INDEX cardDeckId ON Card(deckId);\n\n\n", "file_path": "src/schema.sql", "rank": 1, "score": 80076.39999327567 }, { "content": "CREATE INDEX answerCardId ON Answer(cardId);\n", "file_path": "src/schema.sql", "rank": 2, "score": 80021.74427068235 }, { "content": "fn main() -> Result<()> {\n\n let opt = opt::Opt::from_args();\n\n\n\n let srs = Srs::open(&opt.path)?;\n\n\n\n let stdout = std::io::stdout();\n\n let stdout = stdout.lock();\n\n\n\n let mut app = App::new(srs, stdout);\n\n\n\n use opt::Subcommand::*;\n\n\n\n let result = match &opt.subcommand {\n\n Add { deck_id } => app.add(*deck_id),\n\n\n\n Cards => app.cards(),\n\n\n\n CreateDeck { name } => app.create_deck(name),\n\n\n\n Decks => app.decks(),\n", "file_path": "src/main.rs", "rank": 3, "score": 68164.774677154 }, { "content": "CREATE TABLE Deck(\n\n id INTEGER PRIMARY KEY,\n\n name TEXT NOT NULL,\n\n creationTimestamp INTEGER NOT NULL, -- In milliseconds since Unix epoch\n\n intervalModifier INTEGER NOT NULL DEFAULT 100\n\n);\n\n\n", "file_path": "src/schema.sql", "rank": 4, "score": 54020.32369988704 }, { "content": "CREATE TABLE Answer(\n\n cardId INTEGER NOT NULL REFERENCES Card(id) ON DELETE CASCADE,\n\n isCorrect INTEGER NOT NULL,\n\n timestamp INTEGER NOT NULL -- In milliseconds since Unix epoch\n\n);\n\n\n", "file_path": "src/schema.sql", "rank": 5, "score": 53267.65386082508 }, { "content": "CREATE TABLE Card(\n\n id INTEGER PRIMARY KEY,\n\n deckId INTEGER NOT NULL REFERENCES Deck(id) ON DELETE CASCADE,\n\n front TEXT NOT NULL,\n\n back TEXT NOT NULL,\n\n creationTimestamp INTEGER NOT NULL -- In milliseconds since Unix epoch\n\n);\n\n\n", "file_path": "src/schema.sql", "rank": 6, "score": 53219.18314268129 }, { "content": "CREATE INDEX answerTimestamp ON Answer(timestamp);\n\n\n", "file_path": "src/schema.sql", "rank": 7, "score": 50505.82264106586 }, { "content": "CREATE INDEX cardCreationTimestamp ON Card(creationTimestamp);\n", "file_path": "src/schema.sql", "rank": 8, "score": 46834.992761573 }, { "content": "CREATE INDEX scheduleIsLeech ON Schedule(isLeech);\n", "file_path": "src/schema.sql", "rank": 9, "score": 39931.60286340858 }, { "content": "fn print_help() {\n\n println!(\n\n r#\"{name} {version}\n\nSpaced repetition at the command line\n\n\n\nUSAGE:\n\n {name} [OPTIONS]\n\n\n\nFLAGS:\n\n -h, --help Prints help information\n\n -V, --version Prints version information\n\n\n\nOPTIONS:\n\n -p, --path <PATH> The path of the database file [default: srs.db]\n\n\n\nSUBCOMMANDS:\n\n add\n\n cards\n\n create-deck\n\n decks\n", "file_path": "src/opt.rs", "rank": 11, "score": 35589.71342558448 }, { "content": "pub trait Clock {\n\n fn now(&self) -> OffsetDateTime;\n\n}\n\n\n\npub struct UtcClock;\n\n\n\nimpl Clock for UtcClock {\n\n fn now(&self) -> OffsetDateTime {\n\n OffsetDateTime::now_utc()\n\n }\n\n}\n", "file_path": "src/clock.rs", "rank": 12, "score": 34282.6528039226 }, { "content": "pub trait Schedule {\n\n fn next_interval(\n\n &mut self,\n\n previous_interval: u16,\n\n was_correct: Option<bool>,\n\n interval_modifier: u16,\n\n ) -> u16;\n\n}\n\n\n\nconst WRONG_ANSWER_PENALTY: f64 = 0.7;\n\n\n\npub struct LowKeyAnki {\n\n rng: Box<dyn rand::RngCore>,\n\n}\n\n\n\nimpl Schedule for LowKeyAnki {\n\n fn next_interval(\n\n &mut self,\n\n previous_interval: u16,\n\n was_correct: Option<bool>,\n", "file_path": "src/schedule.rs", "rank": 13, "score": 34282.6528039226 }, { "content": "CREATE TABLE Schedule(\n\n cardId INTEGER PRIMARY KEY REFERENCES Card(id) ON DELETE CASCADE,\n\n scheduledForTimestamp INTEGER, -- In milliseconds since Unix epoch, NULL when suspended\n\n intervalDays INTEGER, -- 0 for new cards, NULL when suspended\n\n isLeech INTEGER NOT NULL DEFAULT 0\n\n);\n\n\n", "file_path": "src/schema.sql", "rank": 14, "score": 19385.53198759368 }, { "content": "CREATE INDEX scheduleScheduledForTimestamp ON Schedule(scheduledForTimestamp);\n", "file_path": "src/schema.sql", "rank": 15, "score": 14233.971768350631 }, { "content": " pub id: u64,\n\n pub front: String,\n\n pub back: String,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct CardPreview {\n\n pub id: u64,\n\n pub front: String,\n\n pub is_leech: bool,\n\n}\n\n\n\n#[derive(Debug, PartialEq)]\n\npub struct GlobalStats {\n\n pub active: u32,\n\n pub suspended: u32,\n\n pub leech: u16,\n\n pub for_review: u16,\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 25, "score": 24.028181250930984 }, { "content": " .into_iter()\n\n .next()\n\n .ok_or(anyhow!(\"nothing to review\"))?;\n\n assert_eq!(for_review, (\"testName\".to_string(), vec![card]));\n\n\n\n Ok(())\n\n }\n\n\n\n #[test]\n\n fn answering_correct_increases_interval() -> Result<()> {\n\n let (mut srs, now) = new_srs()?;\n\n\n\n let deck = create_and_return_deck(&mut srs, \"testName\")?;\n\n let card = create_and_return_card(&mut srs, &deck, \"front\", \"back\")?;\n\n\n\n let intervals = [0, 1, 2, 4, 8, 16, 32, 64, 128, 256];\n\n\n\n for next_interval in intervals {\n\n now.set(now.get() + Duration::days(next_interval));\n\n assert_scheduled(&srs, &card);\n", "file_path": "src/lib.rs", "rank": 26, "score": 23.857140279203072 }, { "content": " self.conn.execute(\"DELETE FROM Card WHERE id = ?\", [id])?;\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn update_card(&mut self, id: u64, front: String, back: String) -> Result<()> {\n\n self.conn.execute(\n\n \"UPDATE Card SET front=?, back=? WHERE id=?\",\n\n params![front, back, id],\n\n )?;\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn switch_deck(&mut self, card_id: u64, deck_id: u64) -> Result<()> {\n\n self.conn.execute(\n\n \"UPDATE Card SET deckId = ? WHERE id = ?\",\n\n [deck_id, card_id],\n\n )?;\n\n\n", "file_path": "src/lib.rs", "rank": 27, "score": 23.674838300485817 }, { "content": "\n\n srs.answer_correct(card.id)?;\n\n }\n\n\n\n now.set(now.get() + Duration::days(1024));\n\n assert_not_scheduled(&srs, &card); // auto-suspend\n\n\n\n Ok(())\n\n }\n\n\n\n #[test]\n\n fn answering_correct_increases_interval_with_interval_modifier() -> Result<()> {\n\n let (mut srs, now) = new_srs()?;\n\n\n\n let deck = create_and_return_deck(&mut srs, \"testName\")?;\n\n srs.update_interval_modifier(deck.id, 200)?;\n\n\n\n let card = create_and_return_card(&mut srs, &deck, \"front\", \"back\")?;\n\n\n\n let intervals = [0, 1, 4, 16, 64, 256];\n", "file_path": "src/lib.rs", "rank": 28, "score": 23.609862635341145 }, { "content": " correct: 0,\n\n wrong: 0,\n\n },\n\n DeckStats {\n\n name: \"testName\".to_string(),\n\n active: 0,\n\n suspended: 0,\n\n leech: 0,\n\n correct: 0,\n\n wrong: 0,\n\n }\n\n ],\n\n );\n\n\n\n Ok(())\n\n }\n\n\n\n #[test]\n\n fn delete_card() -> Result<()> {\n\n let (mut srs, _) = new_srs()?;\n", "file_path": "src/lib.rs", "rank": 29, "score": 23.204658749300666 }, { "content": " let card = create_and_return_card(&mut srs, &deck, \"front\", \"back\")?;\n\n\n\n srs.switch_deck(card.id, deck2.id)?;\n\n\n\n let for_review = srs\n\n .cards_to_review()?\n\n .into_iter()\n\n .next()\n\n .ok_or(anyhow!(\"nothing to review\"))?;\n\n assert_eq!(for_review, (\"another deck\".to_string(), vec![card]));\n\n\n\n let (_, deck_stats) = srs.stats()?;\n\n assert_eq!(\n\n deck_stats,\n\n vec![\n\n DeckStats {\n\n name: \"another deck\".to_string(),\n\n active: 1,\n\n suspended: 0,\n\n leech: 0,\n", "file_path": "src/lib.rs", "rank": 30, "score": 22.14328838630124 }, { "content": " assert_eq!(\n\n deck_stats,\n\n vec![DeckStats {\n\n name: \"testName\".to_string(),\n\n active: 1,\n\n suspended: 0,\n\n leech: 0,\n\n correct: 0,\n\n wrong: 0,\n\n }],\n\n );\n\n\n\n Ok(())\n\n }\n\n\n\n #[test]\n\n fn edit_card() -> Result<()> {\n\n let (mut srs, _) = new_srs()?;\n\n\n\n let deck = create_and_return_deck(&mut srs, \"testName\")?;\n", "file_path": "src/lib.rs", "rank": 32, "score": 21.79795197820025 }, { "content": "\n\n srs.answer_correct(card.id)?;\n\n\n\n let for_review = srs.cards_to_review()?;\n\n assert_eq!(for_review.len(), 0);\n\n\n\n Ok(())\n\n }\n\n\n\n #[test]\n\n fn answering_wrong_leaves_card_in_queue() -> Result<()> {\n\n let (mut srs, _) = new_srs()?;\n\n\n\n let deck = create_and_return_deck(&mut srs, \"testName\")?;\n\n let card = create_and_return_card(&mut srs, &deck, \"front\", \"back\")?;\n\n\n\n srs.answer_wrong(card.id)?;\n\n\n\n let for_review = srs\n\n .cards_to_review()?\n", "file_path": "src/lib.rs", "rank": 33, "score": 21.15250234623192 }, { "content": " Add { deck_id: u64 },\n\n Cards,\n\n CreateDeck { name: String },\n\n Decks,\n\n Delete { card_id: u64 },\n\n DeleteDeck { deck_id: u64 },\n\n Edit { card_id: u64 },\n\n Init,\n\n IntMod { deck_id: u64, modifier: u16 },\n\n Review,\n\n Stats,\n\n Switch { card_id: u64, deck_id: u64 },\n\n}\n\n\n\nimpl Opt {\n\n /// Gets [Opt] from the command line arguments. Prints the error message\n\n /// and quits the program in case of failure.\n\n pub fn from_args() -> Self {\n\n let mut args = Arguments::from_env();\n\n\n", "file_path": "src/opt.rs", "rank": 34, "score": 21.056297481043877 }, { "content": "\n\n let now: u64 = (self.clock.now().unix_timestamp() * 1000)\n\n .try_into()\n\n .expect(\"valid timestamp\");\n\n\n\n self.conn.execute(\n\n \"INSERT INTO Deck(name, creationTimestamp) VALUES (?, ?)\",\n\n params![name, now],\n\n )?;\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn delete_deck(&mut self, id: u64) -> Result<()> {\n\n self.conn.execute(\"DELETE FROM Deck WHERE id = ?\", [id])?;\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn update_interval_modifier(&mut self, id: u64, modifier: u16) -> Result<()> {\n", "file_path": "src/lib.rs", "rank": 35, "score": 20.899263208701548 }, { "content": "\n\n let deck = create_and_return_deck(&mut srs, \"testName\")?;\n\n\n\n let card = create_and_return_card(&mut srs, &deck, \"front\", \"back\")?;\n\n\n\n srs.delete_card(card.id)?;\n\n\n\n let card = srs.get_card(card.id);\n\n\n\n assert!(card.is_err(), \"got a card {card:?}\");\n\n\n\n Ok(())\n\n }\n\n\n\n #[test]\n\n fn answering_correct_removes_from_queue() -> Result<()> {\n\n let (mut srs, _) = new_srs()?;\n\n\n\n let deck = create_and_return_deck(&mut srs, \"testName\")?;\n\n let card = create_and_return_card(&mut srs, &deck, \"front\", \"back\")?;\n", "file_path": "src/lib.rs", "rank": 36, "score": 20.770379033837557 }, { "content": "\n\n for next_interval in intervals {\n\n now.set(now.get() + Duration::days(next_interval));\n\n assert_scheduled(&srs, &card);\n\n\n\n srs.answer_correct(card.id)?;\n\n }\n\n\n\n now.set(now.get() + Duration::days(1024));\n\n assert_not_scheduled(&srs, &card); // auto-suspend\n\n\n\n Ok(())\n\n }\n\n\n\n #[test]\n\n fn answering_wrong_decreases_interval() -> Result<()> {\n\n let (mut srs, now) = new_srs()?;\n\n\n\n let deck = create_and_return_deck(&mut srs, \"testName\")?;\n\n let card = create_and_return_card(&mut srs, &deck, \"front\", \"back\")?;\n", "file_path": "src/lib.rs", "rank": 37, "score": 20.622382134505955 }, { "content": " assert_eq!(card.front, \"front\");\n\n assert_eq!(card.back, \"back\");\n\n\n\n let for_review = srs\n\n .cards_to_review()?\n\n .into_iter()\n\n .next()\n\n .ok_or(anyhow!(\"nothing to review\"))?;\n\n assert_eq!(for_review, (\"testName\".to_string(), vec![card]));\n\n\n\n let (global_stats, deck_stats) = srs.stats()?;\n\n assert_eq!(\n\n global_stats,\n\n GlobalStats {\n\n active: 1,\n\n suspended: 0,\n\n leech: 0,\n\n for_review: 1,\n\n }\n\n );\n", "file_path": "src/lib.rs", "rank": 38, "score": 20.456825340242023 }, { "content": " }\n\n\n\n pub fn get_deck(&self, id: u64) -> Result<Deck> {\n\n Ok(self.conn.query_row(\n\n \"SELECT id, name, intervalModifier FROM Deck WHERE id = ?\",\n\n [id],\n\n |row| {\n\n Ok(Deck {\n\n id: row.get(0)?,\n\n name: row.get(1)?,\n\n interval_modifier: row.get(2)?,\n\n })\n\n },\n\n )?)\n\n }\n\n\n\n pub fn create_deck(&mut self, name: &str) -> Result<()> {\n\n if name.is_empty() {\n\n bail!(\"deck name can't be empty\");\n\n }\n", "file_path": "src/lib.rs", "rank": 39, "score": 20.33278806965535 }, { "content": " fn create_and_return_card(srs: &mut Srs, deck: &Deck, front: &str, back: &str) -> Result<Card> {\n\n srs.create_card(deck.id, front.to_string(), back.to_string())?;\n\n\n\n let preview = srs\n\n .card_previews()?\n\n .into_iter()\n\n .next()\n\n .ok_or(anyhow!(\"no cards\"))?;\n\n\n\n srs.get_card(preview.id)\n\n }\n\n}\n", "file_path": "src/lib.rs", "rank": 41, "score": 20.231896705571025 }, { "content": " let deck = create_and_return_deck(&mut srs, \"testName\")?;\n\n\n\n srs.delete_deck(deck.id)?;\n\n\n\n assert_eq!(srs.decks()?.len(), 0);\n\n\n\n let (_, deck_stats) = srs.stats()?;\n\n assert_eq!(deck_stats.len(), 0);\n\n\n\n Ok(())\n\n }\n\n\n\n #[test]\n\n fn create_card() -> Result<()> {\n\n let (mut srs, _) = new_srs()?;\n\n\n\n let deck = create_and_return_deck(&mut srs, \"testName\")?;\n\n\n\n let card = create_and_return_card(&mut srs, &deck, \"front\", \"back\")?;\n\n\n", "file_path": "src/lib.rs", "rank": 42, "score": 19.809296519559535 }, { "content": " \"\n\n SELECT id, front, back\n\n FROM Card\n\n WHERE id = ?\n\n \",\n\n [id],\n\n |row| {\n\n Ok(Card {\n\n id: row.get(0)?,\n\n front: row.get(1)?,\n\n back: row.get(2)?,\n\n })\n\n },\n\n )?)\n\n }\n\n\n\n pub fn create_card(&mut self, deck_id: u64, front: String, back: String) -> Result<()> {\n\n let tx = self.conn.transaction()?;\n\n\n\n let now: u64 = (self.clock.now().unix_timestamp() * 1000)\n", "file_path": "src/lib.rs", "rank": 43, "score": 19.701006503843356 }, { "content": " let found = srs\n\n .cards_to_review()\n\n .unwrap()\n\n .iter()\n\n .flat_map(|(_, c)| c)\n\n .any(|c| c.id == card.id);\n\n\n\n assert!(!found, \"card is scheduled for review\")\n\n }\n\n\n\n #[test]\n\n fn mark_leech_after_too_many_wrong_answers() -> Result<()> {\n\n let (mut srs, _) = new_srs()?;\n\n\n\n let deck = create_and_return_deck(&mut srs, \"testName\")?;\n\n let card = create_and_return_card(&mut srs, &deck, \"front\", \"back\")?;\n\n\n\n for _ in 1..=WRONG_ANSWERS_FOR_LEECH {\n\n srs.answer_wrong(card.id)?;\n\n }\n", "file_path": "src/lib.rs", "rank": 44, "score": 19.618234464878594 }, { "content": "#[derive(Debug, PartialEq)]\n\npub struct DeckStats {\n\n pub name: String,\n\n pub active: u32,\n\n pub suspended: u32,\n\n pub leech: u16,\n\n pub correct: u16,\n\n pub wrong: u16,\n\n}\n\n\n\nimpl Srs {\n\n pub fn open(db_path: &Path) -> Result<Self> {\n\n let conn = Connection::open(db_path)?;\n\n\n\n conn.set_db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_FKEY, true)?;\n\n\n\n Ok(Self {\n\n conn,\n\n clock: Box::new(clock::UtcClock),\n\n schedule: Box::new(LowKeyAnki::new()),\n", "file_path": "src/lib.rs", "rank": 45, "score": 19.517754187170876 }, { "content": "\n\n let for_review = srs.cards_to_review()?;\n\n assert_eq!(for_review.len(), 0);\n\n\n\n let preview = srs\n\n .card_previews()?\n\n .into_iter()\n\n .next()\n\n .ok_or(anyhow!(\"no cards\"))?;\n\n assert!(preview.is_leech);\n\n\n\n Ok(())\n\n }\n\n\n\n fn create_and_return_deck(srs: &mut Srs, name: &str) -> Result<Deck> {\n\n srs.create_deck(name)?;\n\n\n\n srs.decks()?.pop().ok_or(anyhow!(\"no decks\"))\n\n }\n\n\n", "file_path": "src/lib.rs", "rank": 46, "score": 19.06858558227412 }, { "content": "const MIN_INTERVAL_MODIFIER: u16 = 50;\n\nconst AUTO_SUSPEND_INTERVAL: u16 = 365;\n\nconst WRONG_ANSWERS_FOR_LEECH: u16 = 4;\n\n\n\npub struct Srs {\n\n conn: Connection,\n\n schedule: Box<dyn Schedule>,\n\n clock: Box<dyn Clock>,\n\n offset: UtcOffset,\n\n}\n\n\n\n#[derive(Debug, PartialEq)]\n\npub struct Deck {\n\n pub id: u64,\n\n pub name: String,\n\n pub interval_modifier: u16,\n\n}\n\n\n\n#[derive(Debug, PartialEq)]\n\npub struct Card {\n", "file_path": "src/lib.rs", "rank": 47, "score": 19.01702283276035 }, { "content": "\n\n let num_wrong: u16 = tx.query_row(\n\n \"SELECT COUNT(*) FROM Answer WHERE cardId = ? AND isCorrect = 0\",\n\n [card_id],\n\n |row| row.get(0),\n\n )?;\n\n\n\n if num_wrong >= WRONG_ANSWERS_FOR_LEECH {\n\n tx.execute(\n\n \"UPDATE Schedule SET isLeech = 1 WHERE cardId = ?\",\n\n [card_id],\n\n )?;\n\n }\n\n\n\n tx.commit()?;\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn stats(&self) -> Result<(GlobalStats, Vec<DeckStats>)> {\n", "file_path": "src/lib.rs", "rank": 48, "score": 18.506173752312428 }, { "content": "\n\n let r: Result<_, rusqlite::Error> = iter.collect();\n\n\n\n Ok(r?)\n\n }\n\n\n\n pub fn cards_to_review(&self) -> Result<Vec<(String, Vec<Card>)>> {\n\n let mut stmt = self.conn.prepare(\n\n \"\n\n SELECT Deck.name, Card.id, Card.front, Card.back\n\n FROM Card JOIN Schedule ON Card.id = Schedule.cardId JOIN Deck ON Card.deckId = Deck.id\n\n WHERE isLeech = 0 AND scheduledForTimestamp < ?\n\n ORDER BY Card.deckId, scheduledForTimestamp\n\n \",\n\n )?;\n\n\n\n let iter = stmt.query_map([self.start_of_tomorrow()?], |row| {\n\n Ok((\n\n row.get(0)?,\n\n Card {\n", "file_path": "src/lib.rs", "rank": 49, "score": 18.297399076670153 }, { "content": "\n\n let card = create_and_return_card(&mut srs, &deck, \"front\", \"back\")?;\n\n\n\n srs.update_card(card.id, \"new front\".to_string(), \"new back\".to_string())?;\n\n\n\n let edited_card = srs.get_card(card.id)?;\n\n assert_eq!(edited_card.id, card.id);\n\n assert_eq!(edited_card.front, \"new front\");\n\n assert_eq!(edited_card.back, \"new back\");\n\n\n\n Ok(())\n\n }\n\n\n\n #[test]\n\n fn switch_card() -> Result<()> {\n\n let (mut srs, _) = new_srs()?;\n\n\n\n let deck = create_and_return_deck(&mut srs, \"testName\")?;\n\n let deck2 = create_and_return_deck(&mut srs, \"another deck\")?;\n\n\n", "file_path": "src/lib.rs", "rank": 50, "score": 18.108851480765942 }, { "content": " leech: 0,\n\n for_review: 0,\n\n }\n\n );\n\n assert_eq!(deck_stats.len(), 0);\n\n\n\n Ok(())\n\n }\n\n\n\n #[test]\n\n fn create_deck() -> Result<()> {\n\n let (mut srs, _) = new_srs()?;\n\n\n\n let deck = create_and_return_deck(&mut srs, \"testName\")?;\n\n assert_eq!(deck.name, \"testName\");\n\n assert_eq!(deck.interval_modifier, 100);\n\n\n\n assert_eq!(srs.get_deck(deck.id)?, deck);\n\n assert_eq!(srs.decks()?, vec![deck]);\n\n\n", "file_path": "src/lib.rs", "rank": 51, "score": 17.786764298227318 }, { "content": " if modifier < MIN_INTERVAL_MODIFIER {\n\n bail!(format!(\n\n \"must be > {MIN_INTERVAL_MODIFIER}, given {modifier}\"\n\n ));\n\n }\n\n\n\n self.conn.execute(\n\n \"\n\n UPDATE Deck\n\n SET intervalModifier = ?\n\n WHERE id = ?\n\n \",\n\n params![modifier, id],\n\n )?;\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn get_card(&self, id: u64) -> Result<Card> {\n\n Ok(self.conn.query_row(\n", "file_path": "src/lib.rs", "rank": 53, "score": 17.26477535402501 }, { "content": " Ok(())\n\n }\n\n\n\n #[test]\n\n fn edit_deck() -> Result<()> {\n\n let (mut srs, _) = new_srs()?;\n\n\n\n let deck = create_and_return_deck(&mut srs, \"testName\")?;\n\n\n\n srs.update_interval_modifier(deck.id, 120)?;\n\n\n\n assert_eq!(srs.get_deck(deck.id)?.interval_modifier, 120);\n\n\n\n Ok(())\n\n }\n\n\n\n #[test]\n\n fn delete_deck() -> Result<()> {\n\n let (mut srs, _) = new_srs()?;\n\n\n", "file_path": "src/lib.rs", "rank": 54, "score": 17.248207380401627 }, { "content": " interval_modifier: u16,\n\n ) -> u16 {\n\n match previous_interval {\n\n // Newly added card answered correctly\n\n 0 => 1,\n\n // First review. The wrong answer penalty isn't applied since it's rare to answer\n\n // incorrectly on the first review.\n\n 1 => 4,\n\n _ => {\n\n let was_correct = was_correct.expect(\"previously answered the card\");\n\n\n\n if was_correct {\n\n // Previous answer was correct\n\n let mut next =\n\n (previous_interval as f64 * 2.5 * (interval_modifier as f64 / 100.0))\n\n as u16;\n\n\n\n let max_fuzz =\n\n (previous_interval as f64 * self.fuzz_factor(previous_interval)) as u16;\n\n let fuzz = self.rng.gen_range(0..=max_fuzz);\n", "file_path": "src/schedule.rs", "rank": 55, "score": 17.13612141617343 }, { "content": " .try_into()\n\n .expect(\"valid timestamp\");\n\n\n\n let card_id: u64 = tx.query_row(\n\n \"INSERT INTO Card(deckId, front, back, creationTimestamp) VALUES (?, ?, ?, ?) RETURNING *\",\n\n params![deck_id, front, back, now],\n\n |row| row.get(0),\n\n )?;\n\n\n\n tx.execute(\n\n \"INSERT INTO Schedule(cardId, scheduledForTimestamp, intervalDays) VALUES (?, ?, ?)\",\n\n params![card_id, now, 0],\n\n )?;\n\n\n\n tx.commit()?;\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn delete_card(&mut self, id: u64) -> Result<()> {\n", "file_path": "src/lib.rs", "rank": 56, "score": 16.861087930182133 }, { "content": " name: row.get(0)?,\n\n active: row.get(1)?,\n\n suspended: row.get(2)?,\n\n leech: row.get(3)?,\n\n correct: row.get(4)?,\n\n wrong: row.get(5)?,\n\n })\n\n })?;\n\n\n\n let deck_stats: Result<_, rusqlite::Error> = iter.collect();\n\n\n\n Ok((global_stats, deck_stats?))\n\n }\n\n\n\n fn start_of_tomorrow(&self) -> Result<u64> {\n\n let now = self.clock.now().to_offset(self.offset);\n\n let start_of_tomorrow = now\n\n .date()\n\n .saturating_add(Duration::days(1))\n\n .with_hms(0, 0, 0)\n", "file_path": "src/lib.rs", "rank": 57, "score": 15.812055806598732 }, { "content": "\n\n Ok(())\n\n }\n\n\n\n pub fn decks(&self) -> Result<Vec<Deck>> {\n\n let mut stmt = self\n\n .conn\n\n .prepare(\"SELECT id, name, intervalModifier FROM Deck ORDER BY id\")?;\n\n\n\n let iter = stmt.query_map([], |row| {\n\n Ok(Deck {\n\n id: row.get(0)?,\n\n name: row.get(1)?,\n\n interval_modifier: row.get(2)?,\n\n })\n\n })?;\n\n\n\n let r: Result<_, rusqlite::Error> = iter.collect();\n\n\n\n Ok(r?)\n", "file_path": "src/lib.rs", "rank": 58, "score": 15.375252219839682 }, { "content": " |row| {\n\n Ok(GlobalStats {\n\n active: row.get(0)?,\n\n suspended: row.get(1)?,\n\n leech: row.get(2)?,\n\n for_review: row.get(3)?,\n\n })\n\n },\n\n )?;\n\n\n\n let mut stmt = self.conn.prepare(\n\n \"\n\n SELECT\n\n name,\n\n\n\n (SELECT COUNT(*)\n\n FROM Card JOIN Schedule ON Card.id = Schedule.cardId\n\n WHERE Card.deckId = d.id AND scheduledForTimestamp IS NOT NULL AND isLeech = 0) AS active,\n\n\n\n (SELECT COUNT(*)\n", "file_path": "src/lib.rs", "rank": 59, "score": 14.493092144522427 }, { "content": "\n\n Delete { card_id } => app.delete(*card_id),\n\n\n\n DeleteDeck { deck_id } => app.delete_deck(*deck_id),\n\n\n\n Edit { card_id } => app.edit(*card_id),\n\n\n\n Init => app.init(),\n\n\n\n IntMod { deck_id, modifier } => app.int_mod(*deck_id, *modifier),\n\n\n\n Review => app.review(),\n\n\n\n Stats => app.stats(),\n\n\n\n Switch { card_id, deck_id } => app.switch(*card_id, *deck_id),\n\n };\n\n\n\n if let Err(err) = result {\n\n match err.downcast_ref::<io::Error>() {\n\n Some(e) if e.kind() == io::ErrorKind::BrokenPipe => Ok(()),\n\n _ => Err(err),\n\n }\n\n } else {\n\n result\n\n }\n\n}\n", "file_path": "src/main.rs", "rank": 60, "score": 14.479728323883226 }, { "content": "\n\n pub fn answer_correct(&mut self, card_id: u64) -> Result<()> {\n\n let now_date_time = self.clock.now();\n\n\n\n let now: u64 = (now_date_time.unix_timestamp() * 1000)\n\n .try_into()\n\n .expect(\"valid timestamp\");\n\n\n\n let tx = self.conn.transaction()?;\n\n\n\n let interval_days: u16 = tx\n\n .query_row(\n\n \"SELECT intervalDays FROM Schedule WHERE cardId = ?\",\n\n [card_id],\n\n |row| row.get(0),\n\n )\n\n .optional()?\n\n .expect(\"card is not suspended\");\n\n\n\n let was_correct: Option<bool> = tx\n", "file_path": "src/lib.rs", "rank": 61, "score": 14.233814609963789 }, { "content": " id: row.get(1)?,\n\n front: row.get(2)?,\n\n back: row.get(3)?,\n\n },\n\n ))\n\n })?;\n\n\n\n let r: Result<_, rusqlite::Error> = iter.collect();\n\n\n\n let cards: Vec<(String, Card)> = r?;\n\n\n\n if cards.is_empty() {\n\n return Ok(vec![]);\n\n }\n\n\n\n let mut rng = SmallRng::from_entropy();\n\n\n\n let mut cards_by_deck = vec![];\n\n\n\n let mut current_deck = cards[0].0.clone();\n", "file_path": "src/lib.rs", "rank": 62, "score": 14.146993307926662 }, { "content": "\n\n Ok(())\n\n }\n\n\n\n pub fn answer_wrong(&mut self, card_id: u64) -> Result<()> {\n\n let now: u64 = (self.clock.now().unix_timestamp() * 1000)\n\n .try_into()\n\n .expect(\"valid timestamp\");\n\n\n\n let tx = self.conn.transaction()?;\n\n\n\n tx.execute(\n\n \"INSERT INTO Answer(cardId, isCorrect, timestamp) VALUES (?, ?, ?)\",\n\n params![card_id, false, now],\n\n )?;\n\n\n\n tx.execute(\n\n \"UPDATE Schedule SET scheduledForTimestamp = ? WHERE cardId = ?\",\n\n params![now, card_id],\n\n )?;\n", "file_path": "src/lib.rs", "rank": 63, "score": 13.937287493738133 }, { "content": " FROM Card JOIN Schedule ON Card.id = Schedule.cardId\n\n WHERE Card.deckId = d.id AND scheduledForTimestamp IS NULL AND isLeech = 0) AS suspended,\n\n\n\n (SELECT COUNT(*)\n\n FROM Card JOIN Schedule ON Card.id = Schedule.cardId\n\n WHERE Card.deckId = d.id AND isLeech = 1) AS leech,\n\n\n\n (SELECT COUNT(*)\n\n FROM Card JOIN Answer ON Card.id = Answer.cardId\n\n WHERE Card.deckId = d.id AND isCorrect = 1 AND Answer.timestamp > :accuracySinceTimestamp) AS correct,\n\n\n\n (SELECT COUNT(*)\n\n FROM Card JOIN Answer ON Card.id = Answer.cardId\n\n WHERE Card.deckId = d.id AND isCorrect = 0 AND Answer.timestamp > :accuracySinceTimestamp) AS wrong\n\n FROM Deck AS d\n\n ORDER BY name\n\n \"\n\n )?;\n\n let iter = stmt.query_map([self.thirty_days_ago()?], |row| {\n\n Ok(DeckStats {\n", "file_path": "src/lib.rs", "rank": 64, "score": 13.818875460281637 }, { "content": " use anyhow::anyhow;\n\n use std::cell::Cell;\n\n use std::rc::Rc;\n\n use time::OffsetDateTime;\n\n\n\n struct DoublingSchedule;\n\n\n\n impl Schedule for DoublingSchedule {\n\n fn next_interval(\n\n &mut self,\n\n previous_interval: u16,\n\n was_correct: Option<bool>,\n\n interval_modifier: u16,\n\n ) -> u16 {\n\n match was_correct {\n\n Some(true) => {\n\n (previous_interval as f64 * 2.0 * (interval_modifier as f64 / 100.0)) as u16\n\n }\n\n Some(false) => previous_interval / 2,\n\n None => 1,\n", "file_path": "src/lib.rs", "rank": 65, "score": 13.774828641926991 }, { "content": " },\n\n \"edit\" => Subcommand::Edit {\n\n card_id: args.value_from_str(\"--card-id\")?,\n\n },\n\n \"init\" => Subcommand::Init,\n\n \"int-mod\" => Subcommand::IntMod {\n\n deck_id: args.value_from_str(\"--deck-id\")?,\n\n modifier: args.value_from_str(\"--modifier\")?,\n\n },\n\n \"review\" => Subcommand::Review,\n\n \"stats\" => Subcommand::Stats,\n\n \"switch\" => Subcommand::Switch {\n\n card_id: args.value_from_str(\"--card-id\")?,\n\n deck_id: args.value_from_str(\"--deck-id\")?,\n\n },\n\n _ => bail!(\"unknown subcommand\"),\n\n };\n\n\n\n let remaining = args.finish();\n\n if remaining.is_empty() {\n\n Ok(Self { subcommand, path })\n\n } else {\n\n Err(anyhow!(\n\n \"found arguments which weren't expected: {remaining:?}\"\n\n ))\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/opt.rs", "rank": 66, "score": 13.705973071949474 }, { "content": "\n\n let subcommand = match args.subcommand()? {\n\n Some(s) => s,\n\n None => bail!(\"missing subcommand\"),\n\n };\n\n\n\n let subcommand = match subcommand.as_ref() {\n\n \"add\" => Subcommand::Add {\n\n deck_id: args.value_from_str(\"--deck-id\")?,\n\n },\n\n \"cards\" => Subcommand::Cards,\n\n \"create-deck\" => Subcommand::CreateDeck {\n\n name: args.value_from_str(\"--name\")?,\n\n },\n\n \"decks\" => Subcommand::Decks,\n\n \"delete\" => Subcommand::Delete {\n\n card_id: args.value_from_str(\"--card-id\")?,\n\n },\n\n \"delete-deck\" => Subcommand::DeleteDeck {\n\n deck_id: args.value_from_str(\"--deck-id\")?,\n", "file_path": "src/opt.rs", "rank": 67, "score": 13.676360483305178 }, { "content": " .query_row(\n\n \"SELECT isCorrect FROM Answer WHERE cardId = ? ORDER BY timestamp DESC LIMIT 1\",\n\n [card_id],\n\n |row| row.get(0),\n\n )\n\n .optional()?;\n\n\n\n tx.execute(\n\n \"INSERT INTO Answer(cardId, isCorrect, timestamp) VALUES (?, ?, ?)\",\n\n params![card_id, true, now],\n\n )?;\n\n\n\n let interval_modifier: u16 = tx.query_row(\n\n \"SELECT intervalModifier FROM Deck JOIN Card ON Deck.id = Card.deckId WHERE Card.id = ?\",\n\n [card_id],\n\n |row| row.get(0),\n\n )?;\n\n\n\n let num_days = self\n\n .schedule\n", "file_path": "src/lib.rs", "rank": 68, "score": 13.231465874948888 }, { "content": " Ok(())\n\n }\n\n\n\n pub fn card_previews(&self) -> Result<Vec<CardPreview>> {\n\n let mut stmt = self.conn.prepare(\n\n \"\n\n SELECT id, front, isLeech\n\n FROM Card\n\n JOIN Schedule ON Card.id = Schedule.cardId\n\n ORDER BY isLeech DESC, creationTimestamp DESC;\n\n \",\n\n )?;\n\n\n\n let iter = stmt.query_map([], |row| {\n\n Ok(CardPreview {\n\n id: row.get(0)?,\n\n front: row.get(1)?,\n\n is_leech: row.get(2)?,\n\n })\n\n })?;\n", "file_path": "src/lib.rs", "rank": 69, "score": 12.407181006075456 }, { "content": " )?;\n\n srs.init()?;\n\n\n\n Ok((srs, now))\n\n }\n\n\n\n #[test]\n\n fn empty_db() -> Result<()> {\n\n let (srs, _) = new_srs()?;\n\n\n\n assert_eq!(srs.decks()?.len(), 0);\n\n assert_eq!(srs.card_previews()?.len(), 0);\n\n assert_eq!(srs.cards_to_review()?.len(), 0);\n\n\n\n let (global_stats, deck_stats) = srs.stats()?;\n\n assert_eq!(\n\n global_stats,\n\n GlobalStats {\n\n active: 0,\n\n suspended: 0,\n", "file_path": "src/lib.rs", "rank": 70, "score": 11.848262055644541 }, { "content": " let mut current_cards = vec![];\n\n for (deck_name, card) in cards {\n\n if deck_name != current_deck {\n\n let old_deck_name = std::mem::take(&mut current_deck);\n\n let mut cards = std::mem::take(&mut current_cards);\n\n\n\n current_deck = deck_name.clone();\n\n\n\n cards.shuffle(&mut rng);\n\n cards_by_deck.push((old_deck_name, cards));\n\n }\n\n\n\n current_cards.push(card);\n\n }\n\n\n\n current_cards.shuffle(&mut rng);\n\n cards_by_deck.push((current_deck, current_cards));\n\n\n\n Ok(cards_by_deck)\n\n }\n", "file_path": "src/lib.rs", "rank": 71, "score": 11.562330745250605 }, { "content": " delete\n\n delete-deck\n\n edit\n\n init\n\n int-mod\n\n review\n\n stats\n\n switch\"#,\n\n name = env!(\"CARGO_PKG_NAME\"),\n\n version = env!(\"CARGO_PKG_VERSION\"),\n\n );\n\n}\n", "file_path": "src/opt.rs", "rank": 72, "score": 11.019950430708057 }, { "content": " let global_stats = self.conn.query_row(\n\n \"\n\n SELECT\n\n (SELECT COUNT(*)\n\n FROM Card JOIN Schedule ON Card.id = Schedule.cardId\n\n WHERE scheduledForTimestamp IS NOT NULL AND isLeech = 0) AS active,\n\n\n\n (SELECT COUNT(*)\n\n FROM Card JOIN Schedule ON Card.id = Schedule.cardId\n\n WHERE scheduledForTimestamp IS NULL AND isLeech = 0) AS suspended,\n\n\n\n (SELECT COUNT(*)\n\n FROM Card JOIN Schedule ON Card.id = Schedule.cardId\n\n WHERE isLeech = 1) AS leech,\n\n\n\n (SELECT COUNT(*)\n\n FROM Schedule\n\n WHERE scheduledForTimestamp < :reviewSpanEnd) AS forReview\n\n \",\n\n [self.end_of_tomorrow()?],\n", "file_path": "src/lib.rs", "rank": 73, "score": 10.84638703836571 }, { "content": " struct NotRandom;\n\n\n\n impl RngCore for NotRandom {\n\n fn next_u32(&mut self) -> u32 {\n\n self.next_u64() as u32\n\n }\n\n\n\n fn next_u64(&mut self) -> u64 {\n\n 0\n\n }\n\n\n\n fn fill_bytes(&mut self, dest: &mut [u8]) {\n\n dest.fill(0);\n\n }\n\n\n\n fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> {\n\n Ok(self.fill_bytes(dest))\n\n }\n\n }\n\n\n", "file_path": "src/schedule.rs", "rank": 74, "score": 10.772502659801669 }, { "content": "\n\n if self.rng.gen() {\n\n next += fuzz;\n\n } else {\n\n next -= fuzz;\n\n }\n\n\n\n next\n\n } else {\n\n // Previous answer was wrong\n\n std::cmp::max(1, (previous_interval as f64 * WRONG_ANSWER_PENALTY) as u16)\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl LowKeyAnki {\n\n pub fn new() -> Self {\n\n Self {\n", "file_path": "src/schedule.rs", "rank": 75, "score": 10.368513999587542 }, { "content": " .next_interval(interval_days, was_correct, interval_modifier);\n\n\n\n if num_days >= AUTO_SUSPEND_INTERVAL {\n\n tx.execute(\n\n \"UPDATE Schedule SET scheduledForTimestamp = ?, intervalDays = ? WHERE cardId = ?\",\n\n params![Null, Null, card_id],\n\n )?;\n\n } else {\n\n let num_days_ms: u64 = Duration::days(num_days.into())\n\n .whole_milliseconds()\n\n .try_into()\n\n .expect(\"valid duration\");\n\n\n\n tx.execute(\n\n \"UPDATE Schedule SET scheduledForTimestamp = ?, intervalDays = ? WHERE cardId = ?\",\n\n params![now + num_days_ms, num_days, card_id],\n\n )?;\n\n }\n\n\n\n tx.commit()?;\n", "file_path": "src/lib.rs", "rank": 76, "score": 10.215788162175485 }, { "content": " offset: UtcOffset::current_local_offset()?,\n\n })\n\n }\n\n\n\n #[cfg(test)]\n\n fn open_in_memory(schedule: Box<dyn Schedule>, clock: Box<dyn Clock>) -> Result<Self> {\n\n let conn = Connection::open_in_memory()?;\n\n\n\n conn.set_db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_FKEY, true)?;\n\n\n\n Ok(Self {\n\n conn,\n\n clock,\n\n schedule,\n\n offset: UtcOffset::UTC,\n\n })\n\n }\n\n\n\n pub fn init(&mut self) -> Result<()> {\n\n self.conn.execute_batch(include_str!(\"schema.sql\"))?;\n", "file_path": "src/lib.rs", "rank": 77, "score": 9.532024628657458 }, { "content": "\n\n assert_eq!(next, 4);\n\n }\n\n\n\n #[test]\n\n fn apply_wrong_penalty() {\n\n let mut schedule = new_schedule();\n\n\n\n let next = schedule.next_interval(50, Some(false), 100);\n\n\n\n assert_eq!(next, (50 as f64 * WRONG_ANSWER_PENALTY) as u16);\n\n }\n\n\n\n #[test]\n\n fn correct_answer() {\n\n let mut schedule = new_schedule();\n\n\n\n let next = schedule.next_interval(50, Some(true), 100);\n\n\n\n assert_eq!(next, 125);\n", "file_path": "src/schedule.rs", "rank": 78, "score": 9.32428515193502 }, { "content": "\n\n let forward_by_days = move |days| {\n\n now.set(now.get() + Duration::days(days));\n\n };\n\n\n\n srs.answer_correct(card.id)?;\n\n\n\n forward_by_days(1);\n\n assert_scheduled(&srs, &card);\n\n\n\n srs.answer_correct(card.id)?;\n\n\n\n forward_by_days(2);\n\n assert_scheduled(&srs, &card);\n\n\n\n srs.answer_correct(card.id)?;\n\n\n\n forward_by_days(4);\n\n assert_scheduled(&srs, &card);\n\n\n", "file_path": "src/lib.rs", "rank": 79, "score": 9.053682827904979 }, { "content": " }\n\n\n\n #[test]\n\n fn increase_by_interval_modifier() {\n\n let mut schedule = new_schedule();\n\n\n\n let next = schedule.next_interval(50, Some(true), 200);\n\n\n\n assert_eq!(next, 250);\n\n }\n\n\n\n #[test]\n\n #[should_panic]\n\n fn expect_previous_answer_for_large_interval() {\n\n let mut schedule = new_schedule();\n\n\n\n schedule.next_interval(50, None, 200);\n\n }\n\n}\n", "file_path": "src/schedule.rs", "rank": 80, "score": 8.42774875075945 }, { "content": " }\n\n\n\n fn thirty_days_ago(&self) -> Result<u64> {\n\n let now = self.clock.now().to_offset(self.offset);\n\n let end_of_tomorrow = now\n\n .date()\n\n .saturating_sub(Duration::days(30))\n\n .with_hms(0, 0, 0)\n\n .expect(\"valid time\")\n\n .assume_offset(now.offset());\n\n\n\n Ok((end_of_tomorrow.unix_timestamp() * 1000)\n\n .try_into()\n\n .expect(\"valid timestamp\"))\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n", "file_path": "src/lib.rs", "rank": 81, "score": 8.047804180124718 }, { "content": " if args.contains([\"-h\", \"--help\"]) {\n\n print_help();\n\n process::exit(0);\n\n }\n\n\n\n if args.contains([\"-V\", \"--version\"]) {\n\n println!(\"{} {}\", env!(\"CARGO_PKG_NAME\"), env!(\"CARGO_PKG_VERSION\"));\n\n process::exit(0);\n\n }\n\n\n\n Self::parse(args).unwrap_or_else(|e| {\n\n eprintln!(\"error: {e}\");\n\n process::exit(1);\n\n })\n\n }\n\n\n\n fn parse(mut args: Arguments) -> Result<Self> {\n\n let path = args\n\n .opt_value_from_os_str([\"-p\", \"--path\"], |p| Ok::<_, Infallible>(PathBuf::from(p)))?\n\n .unwrap_or_else(|| PathBuf::from(\"srs.db\"));\n", "file_path": "src/opt.rs", "rank": 82, "score": 7.707910036704245 }, { "content": " srs.answer_wrong(card.id)?;\n\n\n\n forward_by_days(2);\n\n assert_scheduled(&srs, &card);\n\n\n\n Ok(())\n\n }\n\n\n\n fn assert_scheduled(srs: &Srs, card: &Card) {\n\n let found = srs\n\n .cards_to_review()\n\n .unwrap()\n\n .iter()\n\n .flat_map(|(_, c)| c)\n\n .any(|c| c.id == card.id);\n\n\n\n assert!(found, \"card isn't scheduled for review\")\n\n }\n\n\n\n fn assert_not_scheduled(srs: &Srs, card: &Card) {\n", "file_path": "src/lib.rs", "rank": 83, "score": 7.692145798532103 }, { "content": " rng: Box::new(SmallRng::from_entropy()),\n\n }\n\n }\n\n\n\n fn fuzz_factor(&self, previous_interval: u16) -> f64 {\n\n if previous_interval < 7 {\n\n 0.25\n\n } else if previous_interval < 30 {\n\n 0.15\n\n } else {\n\n 0.05\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use rand::RngCore;\n\n\n", "file_path": "src/schedule.rs", "rank": 84, "score": 7.390128875019457 }, { "content": " .expect(\"valid time\")\n\n .assume_offset(now.offset());\n\n\n\n Ok((start_of_tomorrow.unix_timestamp() * 1000)\n\n .try_into()\n\n .expect(\"valid timestamp\"))\n\n }\n\n\n\n fn end_of_tomorrow(&self) -> Result<u64> {\n\n let now = self.clock.now().to_offset(self.offset);\n\n let end_of_tomorrow = now\n\n .date()\n\n .saturating_add(Duration::days(1))\n\n .with_hms(23, 59, 59)\n\n .expect(\"valid time\")\n\n .assume_offset(now.offset());\n\n\n\n Ok((end_of_tomorrow.unix_timestamp() * 1000)\n\n .try_into()\n\n .expect(\"valid timestamp\"))\n", "file_path": "src/lib.rs", "rank": 85, "score": 7.223566434901854 }, { "content": " fn new_schedule() -> LowKeyAnki {\n\n LowKeyAnki {\n\n rng: Box::new(NotRandom),\n\n }\n\n }\n\n\n\n #[test]\n\n fn first_answer() {\n\n let mut schedule = new_schedule();\n\n\n\n let next = schedule.next_interval(0, None, 100);\n\n\n\n assert_eq!(next, 1);\n\n }\n\n\n\n #[test]\n\n fn first_review() {\n\n let mut schedule = new_schedule();\n\n\n\n let next = schedule.next_interval(1, Some(true), 100);\n", "file_path": "src/schedule.rs", "rank": 86, "score": 7.076877623402342 }, { "content": "use anyhow::anyhow;\n\nuse anyhow::bail;\n\nuse anyhow::Result;\n\nuse pico_args::Arguments;\n\nuse std::convert::Infallible;\n\nuse std::path::PathBuf;\n\nuse std::process;\n\n\n\n/// Contains parsed command line arguments.\n\n#[derive(Debug)]\n\npub struct Opt {\n\n /// The subcommand to run.\n\n pub subcommand: Subcommand,\n\n\n\n /// The path of the database file. Defaults to srs.db.\n\n pub path: PathBuf,\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum Subcommand {\n", "file_path": "src/opt.rs", "rank": 87, "score": 6.876646999167267 }, { "content": "mod app;\n\nmod opt;\n\n\n\nuse crate::app::App;\n\nuse anyhow::Result;\n\nuse srs_cli::Srs;\n\nuse std::io;\n\n\n", "file_path": "src/main.rs", "rank": 88, "score": 5.2010566071076045 }, { "content": "mod clock;\n\nmod schedule;\n\n\n\nuse anyhow::bail;\n\nuse anyhow::Result;\n\nuse clock::Clock;\n\nuse rand::rngs::SmallRng;\n\nuse rand::seq::SliceRandom;\n\nuse rand::SeedableRng;\n\nuse rusqlite::config::DbConfig;\n\nuse rusqlite::params;\n\nuse rusqlite::types::Null;\n\nuse rusqlite::Connection;\n\nuse rusqlite::OptionalExtension;\n\nuse schedule::LowKeyAnki;\n\nuse schedule::Schedule;\n\nuse std::path::Path;\n\nuse time::Duration;\n\nuse time::UtcOffset;\n\n\n", "file_path": "src/lib.rs", "rank": 89, "score": 4.61901700455926 }, { "content": "use rand::rngs::SmallRng;\n\nuse rand::Rng;\n\nuse rand::SeedableRng;\n\n\n", "file_path": "src/schedule.rs", "rank": 90, "score": 3.4303782568202363 }, { "content": "use time::OffsetDateTime;\n\n\n", "file_path": "src/clock.rs", "rank": 91, "score": 2.883508049630299 }, { "content": " }\n\n }\n\n }\n\n\n\n struct TimeMachine {\n\n now: Rc<Cell<OffsetDateTime>>,\n\n }\n\n\n\n impl Clock for TimeMachine {\n\n fn now(&self) -> OffsetDateTime {\n\n self.now.get()\n\n }\n\n }\n\n\n\n fn new_srs() -> Result<(Srs, Rc<Cell<OffsetDateTime>>)> {\n\n let now = Rc::new(Cell::new(OffsetDateTime::UNIX_EPOCH + Duration::weeks(10)));\n\n\n\n let mut srs = Srs::open_in_memory(\n\n Box::new(DoublingSchedule),\n\n Box::new(TimeMachine { now: now.clone() }),\n", "file_path": "src/lib.rs", "rank": 92, "score": 2.1039826558405785 } ]
Rust
src/cluster/src/local.rs
simlay/fluvio
a42283200e667223d3a52b217d266db8927db4eb
use std::path::Path; use std::borrow::Cow; use std::fs::{File, create_dir_all}; use std::process::{Command, Stdio}; use std::time::Duration; use fluvio::{FluvioConfig}; use tracing::{info, warn, debug}; use fluvio::config::{TlsPolicy, TlsConfig, TlsPaths, ConfigFile, Profile, LOCAL_PROFILE}; use fluvio::metadata::spg::SpuGroupSpec; use flv_util::cmd::CommandExt; use fluvio_future::timer::sleep; use fluvio::metadata::spu::{SpuSpec, SpuType}; use fluvio::metadata::spu::IngressPort; use fluvio::metadata::spu::Endpoint; use fluvio::metadata::spu::IngressAddr; use k8_obj_metadata::InputK8Obj; use k8_obj_metadata::InputObjectMeta; use k8_client::SharedK8Client; use crate::ClusterError; #[derive(Debug)] pub struct LocalClusterInstallerBuilder { log_dir: String, rust_log: Option<String>, spu_spec: SpuGroupSpec, server_tls_policy: TlsPolicy, client_tls_policy: TlsPolicy, } impl LocalClusterInstallerBuilder { pub fn build(self) -> Result<LocalClusterInstaller, ClusterError> { Ok(LocalClusterInstaller { config: self }) } pub fn with_spu_replicas(mut self, spu_replicas: u16) -> Self { self.spu_spec.replicas = spu_replicas; self } pub fn with_log_dir(mut self, log_dir: String) -> Self { self.log_dir = log_dir; self } pub fn with_rust_log<S: Into<String>>(mut self, rust_log: S) -> Self { self.rust_log = Some(rust_log.into()); self } pub fn with_tls<C: Into<TlsPolicy>, S: Into<TlsPolicy>>( mut self, client: C, server: S, ) -> Self { let client_policy = client.into(); let server_policy = server.into(); use std::mem::discriminant; match (&client_policy, &server_policy) { _ if discriminant(&client_policy) != discriminant(&server_policy) => { warn!("Client TLS policy type is different than the Server TLS policy type!"); } (TlsPolicy::Verified(client), TlsPolicy::Verified(server)) if client.domain() != server.domain() => { warn!( client_domain = client.domain(), server_domain = server.domain(), "Client TLS config has a different domain than the Server TLS config!" ); } _ => (), } self.client_tls_policy = client_policy; self.server_tls_policy = server_policy; self } } #[derive(Debug)] pub struct LocalClusterInstaller { config: LocalClusterInstallerBuilder, } impl LocalClusterInstaller { #[allow(clippy::new_ret_no_self)] pub fn new() -> LocalClusterInstallerBuilder { let spu_spec = SpuGroupSpec { replicas: 1, min_id: 0, ..SpuGroupSpec::default() }; LocalClusterInstallerBuilder { spu_spec, rust_log: Some("info".to_string()), log_dir: "/tmp".to_string(), server_tls_policy: TlsPolicy::Disabled, client_tls_policy: TlsPolicy::Disabled, } } pub async fn install(&self) -> Result<(), ClusterError> { debug!("using log dir: {}", &self.config.log_dir); if !Path::new(&self.config.log_dir.to_string()).exists() { create_dir_all(&self.config.log_dir.to_string())?; } Command::new("sync").inherit(); info!("launching sc"); self.launch_sc()?; info!("setting local profile"); self.set_profile()?; info!( "launching spu group with size: {}", &self.config.spu_spec.replicas ); self.launch_spu_group().await?; sleep(Duration::from_secs(1)).await; Ok(()) } fn launch_sc(&self) -> Result<(), ClusterError> { let outputs = File::create(format!("{}/flv_sc.log", &self.config.log_dir))?; let errors = outputs.try_clone()?; debug!("starting sc server"); let mut binary = { let mut cmd = Command::new(std::env::current_exe()?); cmd.arg("run"); cmd.arg("sc"); cmd }; if let TlsPolicy::Verified(tls) = &self.config.server_tls_policy { self.set_server_tls(&mut binary, tls, 9005)?; } if let Some(log) = &self.config.rust_log { binary.env("RUST_LOG", log); } let cmd = binary.print(); cmd.stdout(Stdio::from(outputs)) .stderr(Stdio::from(errors)) .spawn()?; Ok(()) } fn set_server_tls( &self, cmd: &mut Command, tls: &TlsConfig, port: u16, ) -> Result<(), ClusterError> { let paths: Cow<TlsPaths> = match tls { TlsConfig::Files(paths) => Cow::Borrowed(paths), TlsConfig::Inline(certs) => Cow::Owned(certs.try_into_temp_files()?), }; info!("starting SC with TLS options"); let ca_cert = paths .ca_cert .to_str() .ok_or_else(|| ClusterError::Other("ca_cert must be a valid path".to_string()))?; let server_cert = paths .cert .to_str() .ok_or_else(|| ClusterError::Other("server_cert must be a valid path".to_string()))?; let server_key = paths .key .to_str() .ok_or_else(|| ClusterError::Other("server_key must be a valid path".to_string()))?; cmd.arg("--tls") .arg("--enable-client-cert") .arg("--server-cert") .arg(server_cert) .arg("--server-key") .arg(server_key) .arg("--ca-cert") .arg(ca_cert) .arg("--bind-non-tls-public") .arg(format!("0.0.0.0:{}", port)); Ok(()) } fn set_profile(&self) -> Result<String, ClusterError> { let local_addr = "localhost:9003".to_owned(); let mut config_file = ConfigFile::load_default_or_new()?; let config = config_file.mut_config(); match config.cluster_mut(LOCAL_PROFILE) { Some(cluster) => { cluster.addr = local_addr.clone(); cluster.tls = self.config.client_tls_policy.clone(); } None => { let mut local_cluster = FluvioConfig::new(local_addr.clone()); local_cluster.tls = self.config.client_tls_policy.clone(); config.add_cluster(local_cluster, LOCAL_PROFILE.to_owned()); } }; match config.profile_mut(LOCAL_PROFILE) { Some(profile) => { profile.set_cluster(LOCAL_PROFILE.to_owned()); } None => { let profile = Profile::new(LOCAL_PROFILE.to_owned()); config.add_profile(profile, LOCAL_PROFILE.to_owned()); } } assert!(config.set_current_profile(LOCAL_PROFILE)); config_file.save()?; Ok(format!("local context is set to: {}", local_addr)) } async fn launch_spu_group(&self) -> Result<(), ClusterError> { use k8_client::load_and_share; let client = load_and_share()?; let count = self.config.spu_spec.replicas; for i in 0..count { debug!("launching SPU ({} of {})", i + 1, count); self.launch_spu(i, client.clone(), &self.config.log_dir.to_string()) .await?; } info!("SC log generated at {}/flv_sc.log", &self.config.log_dir); sleep(Duration::from_millis(500)).await; Ok(()) } async fn launch_spu( &self, spu_index: u16, client: SharedK8Client, log_dir: &str, ) -> Result<(), ClusterError> { use k8_client::metadata::MetadataClient; const BASE_PORT: u16 = 9010; const BASE_SPU: u16 = 5001; let spu_id = (BASE_SPU + spu_index) as i32; let public_port = BASE_PORT + spu_index * 10; let private_port = public_port + 1; let spu_spec = SpuSpec { id: spu_id, spu_type: SpuType::Custom, public_endpoint: IngressPort { port: public_port, ingress: vec![IngressAddr { hostname: Some("localhost".to_owned()), ..Default::default() }], ..Default::default() }, private_endpoint: Endpoint { port: private_port, host: "localhost".to_owned(), ..Default::default() }, ..Default::default() }; let input = InputK8Obj::new( spu_spec, InputObjectMeta { name: format!("custom-spu-{}", spu_id), namespace: "default".to_owned(), ..Default::default() }, ); client.create_item(input).await?; sleep(Duration::from_millis(300)).await; let log_spu = format!("{}/spu_log_{}.log", log_dir, spu_id); let outputs = File::create(&log_spu)?; let errors = outputs.try_clone()?; let mut binary = { let mut cmd = Command::new(std::env::current_exe()?); cmd.arg("run"); cmd.arg("spu"); cmd }; if let TlsPolicy::Verified(tls) = &self.config.server_tls_policy { self.set_server_tls(&mut binary, tls, private_port + 1)?; } if let Some(log) = &self.config.rust_log { binary.env("RUST_LOG", log); } let cmd = binary .arg("-i") .arg(format!("{}", spu_id)) .arg("-p") .arg(format!("0.0.0.0:{}", public_port)) .arg("-v") .arg(format!("0.0.0.0:{}", private_port)) .print(); info!("SPU<{}> cmd: {:#?}", spu_index, cmd); info!("SPU log generated at {}", log_spu); cmd.stdout(Stdio::from(outputs)) .stderr(Stdio::from(errors)) .spawn() .map_err(|_| ClusterError::Other("SPU server failed to start".to_string()))?; Ok(()) } }
use std::path::Path; use std::borrow::Cow; use std::fs::{File, create_dir_all}; use std::process::{Command, Stdio}; use std::time::Duration; use fluvio::{FluvioConfig}; use tracing::{info, warn, debug}; use fluvio::config::{TlsPolicy, TlsConfig, TlsPaths, ConfigFile, Profile, LOCAL_PROFILE}; use fluvio::metadata::spg::SpuGroupSpec; use flv_util::cmd::CommandExt; use fluvio_future::timer::sleep; use fluvio::metadata::spu::{SpuSpec, SpuType}; use fluvio::metadata::spu::IngressPort; use fluvio::metadata::spu::Endpoint; use fluvio::metadata::spu::IngressAddr; use k8_obj_metadata::InputK8Obj; use k8_obj_metadata::InputObjectMeta; use k8_client::SharedK8Client; use crate::ClusterError; #[derive(Debug)] pub struct LocalClusterInstallerBuilder { log_dir: String, rust_log: Option<String>, spu_spec: SpuGroupSpec, server_tls_policy: TlsPolicy, client_tls_policy: TlsPolicy, } impl LocalClusterInstallerBuilder { pub fn build(self) -> Result<LocalClusterInstaller, ClusterError> { Ok(LocalClusterInstaller { config: self }) } pub fn with_spu_replicas(mut self, spu_replicas: u16) -> Self { self.spu_spec.replicas = spu_replicas; self } pub fn with_log_dir(mut self, log_dir: String) -> Self { self.log_dir = log_dir; self } pub fn with_rust_log<S: Into<String>>(mut self, rust_log: S) -> Self { self.rust_log = Some(rust_log.into()); self } pub fn with_tls<C: Into<TlsPolicy>, S: Into<TlsPolicy>>( mut self, client: C, server: S, ) -> Self { let client_policy = client.into(); let server_policy = server.into(); use std::mem::discriminant; match (&client_policy, &server_policy) { _ if discriminant(&client_policy) != discriminant(&server_policy) => { warn!("Client TLS policy type is different than the Server TLS policy type!"); } (TlsPolicy::Verified(client), TlsPolicy::Verified(server)) if client.domain() != server.domain() => { warn!( client_domain = client.domain(), server_domain = server.domain(), "Client TLS config has a different domain than the Server TLS config!" ); } _ => (), } self.client_tls_policy = client_policy; self.server_tls_policy = server_policy; self } } #[derive(Debug)] pub struct LocalClusterInstaller { config: LocalClusterInstallerBuilder, } impl LocalClusterInstaller { #[allow(clippy::new_ret_no_self)] pub fn new() -> LocalClusterInstallerBuilder { let spu_spec = SpuGroupSpec { replicas: 1, min_id: 0, ..SpuGroupSpec::default() }; LocalClusterInstallerBuilder { spu_spec, rust_log: Some("info".to_string()), log_dir: "/tmp".to_string(), server_tls_policy: TlsPolicy::Disabled, client_tls_policy: TlsPolicy::Disabled, } } pub async fn install(&self) -> Result<(), ClusterError> { debug!("using log dir: {}", &self.config.log_dir); if !Path::new(&self.config.log_dir.to_string()).exists() { create_dir_all(&self.config.log_dir.to_string())?; } Command::new("sync").inherit(); info!("launching sc"); self.launch_sc()?; info!("setting local profile"); self.set_profile()?; info!( "launching spu group with size: {}", &self.config.spu_spec.replicas ); self.launch_spu_group().await?; sleep(Duration::from_secs(1)).await; Ok(()) } fn launch_sc(&self) -> Result<(), ClusterError> { let outputs = File::create(format!("{}/flv_sc.log", &self.config.lo
fn set_server_tls( &self, cmd: &mut Command, tls: &TlsConfig, port: u16, ) -> Result<(), ClusterError> { let paths: Cow<TlsPaths> = match tls { TlsConfig::Files(paths) => Cow::Borrowed(paths), TlsConfig::Inline(certs) => Cow::Owned(certs.try_into_temp_files()?), }; info!("starting SC with TLS options"); let ca_cert = paths .ca_cert .to_str() .ok_or_else(|| ClusterError::Other("ca_cert must be a valid path".to_string()))?; let server_cert = paths .cert .to_str() .ok_or_else(|| ClusterError::Other("server_cert must be a valid path".to_string()))?; let server_key = paths .key .to_str() .ok_or_else(|| ClusterError::Other("server_key must be a valid path".to_string()))?; cmd.arg("--tls") .arg("--enable-client-cert") .arg("--server-cert") .arg(server_cert) .arg("--server-key") .arg(server_key) .arg("--ca-cert") .arg(ca_cert) .arg("--bind-non-tls-public") .arg(format!("0.0.0.0:{}", port)); Ok(()) } fn set_profile(&self) -> Result<String, ClusterError> { let local_addr = "localhost:9003".to_owned(); let mut config_file = ConfigFile::load_default_or_new()?; let config = config_file.mut_config(); match config.cluster_mut(LOCAL_PROFILE) { Some(cluster) => { cluster.addr = local_addr.clone(); cluster.tls = self.config.client_tls_policy.clone(); } None => { let mut local_cluster = FluvioConfig::new(local_addr.clone()); local_cluster.tls = self.config.client_tls_policy.clone(); config.add_cluster(local_cluster, LOCAL_PROFILE.to_owned()); } }; match config.profile_mut(LOCAL_PROFILE) { Some(profile) => { profile.set_cluster(LOCAL_PROFILE.to_owned()); } None => { let profile = Profile::new(LOCAL_PROFILE.to_owned()); config.add_profile(profile, LOCAL_PROFILE.to_owned()); } } assert!(config.set_current_profile(LOCAL_PROFILE)); config_file.save()?; Ok(format!("local context is set to: {}", local_addr)) } async fn launch_spu_group(&self) -> Result<(), ClusterError> { use k8_client::load_and_share; let client = load_and_share()?; let count = self.config.spu_spec.replicas; for i in 0..count { debug!("launching SPU ({} of {})", i + 1, count); self.launch_spu(i, client.clone(), &self.config.log_dir.to_string()) .await?; } info!("SC log generated at {}/flv_sc.log", &self.config.log_dir); sleep(Duration::from_millis(500)).await; Ok(()) } async fn launch_spu( &self, spu_index: u16, client: SharedK8Client, log_dir: &str, ) -> Result<(), ClusterError> { use k8_client::metadata::MetadataClient; const BASE_PORT: u16 = 9010; const BASE_SPU: u16 = 5001; let spu_id = (BASE_SPU + spu_index) as i32; let public_port = BASE_PORT + spu_index * 10; let private_port = public_port + 1; let spu_spec = SpuSpec { id: spu_id, spu_type: SpuType::Custom, public_endpoint: IngressPort { port: public_port, ingress: vec![IngressAddr { hostname: Some("localhost".to_owned()), ..Default::default() }], ..Default::default() }, private_endpoint: Endpoint { port: private_port, host: "localhost".to_owned(), ..Default::default() }, ..Default::default() }; let input = InputK8Obj::new( spu_spec, InputObjectMeta { name: format!("custom-spu-{}", spu_id), namespace: "default".to_owned(), ..Default::default() }, ); client.create_item(input).await?; sleep(Duration::from_millis(300)).await; let log_spu = format!("{}/spu_log_{}.log", log_dir, spu_id); let outputs = File::create(&log_spu)?; let errors = outputs.try_clone()?; let mut binary = { let mut cmd = Command::new(std::env::current_exe()?); cmd.arg("run"); cmd.arg("spu"); cmd }; if let TlsPolicy::Verified(tls) = &self.config.server_tls_policy { self.set_server_tls(&mut binary, tls, private_port + 1)?; } if let Some(log) = &self.config.rust_log { binary.env("RUST_LOG", log); } let cmd = binary .arg("-i") .arg(format!("{}", spu_id)) .arg("-p") .arg(format!("0.0.0.0:{}", public_port)) .arg("-v") .arg(format!("0.0.0.0:{}", private_port)) .print(); info!("SPU<{}> cmd: {:#?}", spu_index, cmd); info!("SPU log generated at {}", log_spu); cmd.stdout(Stdio::from(outputs)) .stderr(Stdio::from(errors)) .spawn() .map_err(|_| ClusterError::Other("SPU server failed to start".to_string()))?; Ok(()) } }
g_dir))?; let errors = outputs.try_clone()?; debug!("starting sc server"); let mut binary = { let mut cmd = Command::new(std::env::current_exe()?); cmd.arg("run"); cmd.arg("sc"); cmd }; if let TlsPolicy::Verified(tls) = &self.config.server_tls_policy { self.set_server_tls(&mut binary, tls, 9005)?; } if let Some(log) = &self.config.rust_log { binary.env("RUST_LOG", log); } let cmd = binary.print(); cmd.stdout(Stdio::from(outputs)) .stderr(Stdio::from(errors)) .spawn()?; Ok(()) }
function_block-function_prefixed
[ { "content": "/// create new local cluster and profile\n\npub fn set_local_context(local_config: LocalOpt) -> Result<String, CliError> {\n\n let local_addr = local_config.local;\n\n let mut config_file = ConfigFile::load_default_or_new()?;\n\n\n\n let config = config_file.mut_config();\n\n\n\n // check if local cluster exists otherwise, create new one\n\n match config.cluster_mut(LOCAL_PROFILE) {\n\n Some(cluster) => {\n\n cluster.addr = local_addr.clone();\n\n cluster.tls = local_config.tls.try_into()?;\n\n }\n\n None => {\n\n let mut local_cluster = FluvioConfig::new(local_addr.clone());\n\n local_cluster.tls = local_config.tls.try_into()?;\n\n config.add_cluster(local_cluster, LOCAL_PROFILE.to_owned());\n\n }\n\n };\n\n\n\n // check if we local profile exits otherwise, create new one, then set it's cluster\n", "file_path": "src/cli/src/profile/context.rs", "rank": 0, "score": 343995.7005511477 }, { "content": "#[async_trait]\n\npub trait SpuLocalStorePolicy<C>\n\nwhere\n\n C: MetadataItem,\n\n{\n\n async fn online_status(&self) -> HashSet<SpuId>;\n\n\n\n async fn online_spu_count(&self) -> i32;\n\n\n\n async fn spu_used_for_replica(&self) -> i32;\n\n\n\n async fn online_spu_ids(&self) -> Vec<i32>;\n\n\n\n async fn spu_ids(&self) -> Vec<i32>;\n\n\n\n async fn online_spus(&self) -> Vec<SpuMetadata<C>>;\n\n\n\n async fn custom_spus(&self) -> Vec<SpuMetadata<C>>;\n\n\n\n async fn get_by_id(&self, id: i32) -> Option<SpuMetadata<C>>;\n\n\n", "file_path": "src/controlplane-metadata/src/spu/store.rs", "rank": 1, "score": 259352.44899254735 }, { "content": "pub fn run_cli(args: &[String]) -> eyre::Result<String> {\n\n run_block_on(async move {\n\n let terminal = Arc::new(PrintTerminal::new());\n\n\n\n let root_args: Root = Root::from_iter(args);\n\n let output = match root_args {\n\n Root::Consume(consume) => process_consume_log(terminal.clone(), consume).await?,\n\n Root::Produce(produce) => process_produce_record(terminal.clone(), produce).await?,\n\n Root::SPU(spu) => process_spu(terminal.clone(), spu).await?,\n\n Root::SPUGroup(spu_group) => process_spu_group(terminal.clone(), spu_group).await?,\n\n Root::CustomSPU(custom_spu) => process_custom_spu(terminal.clone(), custom_spu).await?,\n\n Root::Topic(topic) => process_topic(terminal.clone(), topic).await?,\n\n Root::Partition(partition) => partition.process_partition(terminal.clone()).await?,\n\n Root::Profile(profile) => process_profile(terminal.clone(), profile).await?,\n\n Root::Cluster(cluster) => process_cluster(terminal.clone(), cluster).await?,\n\n #[cfg(any(feature = \"cluster_components\", feature = \"cluster_components_rustls\"))]\n\n Root::Run(opt) => process_run(opt)?,\n\n Root::Install(opt) => opt.process().await?,\n\n Root::Update(opt) => opt.process().await?,\n\n Root::Version(_) => process_version_cmd()?,\n\n Root::Completions(shell) => process_completions_cmd(shell)?,\n\n Root::External(args) => process_external_subcommand(args)?,\n\n };\n\n Ok(output)\n\n })\n\n}\n\n\n\nuse crate::Terminal;\n\n\n", "file_path": "src/cli/src/root_cli.rs", "rank": 2, "score": 255897.48199925813 }, { "content": "// returns a tuple (topic_name, idx)\n\npub fn decompose_partition_name(partition_name: &str) -> Result<(String, i32), PartitionError> {\n\n let dash_pos = partition_name.rfind('-');\n\n if dash_pos.is_none() {\n\n return Err(PartitionError::InvalidSyntax(partition_name.to_owned()));\n\n }\n\n\n\n let pos = dash_pos.unwrap();\n\n if (pos + 1) >= partition_name.len() {\n\n return Err(PartitionError::InvalidSyntax(partition_name.to_owned()));\n\n }\n\n\n\n let topic_name = &partition_name[..pos];\n\n let idx_string = &partition_name[(pos + 1)..];\n\n let idx = match idx_string.parse::<i32>() {\n\n Ok(n) => n,\n\n Err(_) => {\n\n return Err(PartitionError::InvalidSyntax(partition_name.to_owned()));\n\n }\n\n };\n\n\n\n Ok((topic_name.to_string(), idx))\n\n}\n\n\n", "file_path": "src/types/src/partition.rs", "rank": 3, "score": 254370.58556398243 }, { "content": "/// find status matching it,\n\nfn find_status(status: &mut Vec<ReplicaStatus>, spu: SpuId) -> Option<&'_ mut ReplicaStatus> {\n\n status.iter_mut().find(|status| status.spu == spu)\n\n}\n\n\n\n#[derive(Decode, Encode, Debug, Clone, PartialEq)]\n\n#[cfg_attr(feature = \"use_serde\", derive(serde::Serialize, serde::Deserialize))]\n\npub enum PartitionResolution {\n\n Offline, // No leader available for serving partition\n\n Online, // Partition is running normally, status contains replica info\n\n LeaderOffline, // Election has failed, no suitable leader has been founded\n\n ElectionLeaderFound, // New leader has been selected\n\n}\n\n\n\nimpl Default for PartitionResolution {\n\n fn default() -> Self {\n\n PartitionResolution::Offline\n\n }\n\n}\n\n\n\n#[derive(Decode, Encode, Debug, Clone, PartialEq)]\n", "file_path": "src/controlplane-metadata/src/partition/status.rs", "rank": 4, "score": 247492.86660216842 }, { "content": "struct ScServerCtx {\n\n ctx: SharedScContext,\n\n sender: Sender<bool>,\n\n}\n", "file_path": "src/spu/src/tests/fixture/spu_client.rs", "rank": 5, "score": 247200.08897528314 }, { "content": "/// Generate a random client group key (50001 to 65535)\n\npub fn generate_group_id() -> String {\n\n format!(\"fluvio-consumer-{}\", thread_rng().gen_range(50001, 65535))\n\n}\n\n\n\n#[allow(dead_code)]\n", "file_path": "src/utils/src/generators.rs", "rank": 6, "score": 245921.92256248108 }, { "content": "fn process_external_subcommand(mut args: Vec<String>) -> Result<String, CliError> {\n\n use std::process::Command;\n\n use which::{CanonicalPath, Error as WhichError};\n\n\n\n // The external subcommand's name is given as the first argument, take it.\n\n let cmd = args.remove(0);\n\n\n\n // Check for a matching external command in the environment\n\n let external_subcommand = format!(\"fluvio-{}\", cmd);\n\n let subcommand_path = match CanonicalPath::new(&external_subcommand) {\n\n Ok(path) => path,\n\n Err(WhichError::CannotFindBinaryPath) => {\n\n println!(\n\n \"Unable to find plugin '{}'. Make sure it is executable and in your PATH.\",\n\n &external_subcommand\n\n );\n\n std::process::exit(1);\n\n }\n\n other => other?,\n\n };\n", "file_path": "src/cli/src/root_cli.rs", "rank": 7, "score": 244460.4270549144 }, { "content": "/// compute profile name, if name exists in the cli option, we use that\n\n/// otherwise, we look up k8 config context name\n\nfn compute_profile_name() -> Result<String, CliError> {\n\n let k8_config = K8Config::load()?;\n\n\n\n let kc_config = match k8_config {\n\n K8Config::Pod(_) => return Err(CliError::Other(\"Pod config is not valid here\".to_owned())),\n\n K8Config::KubeConfig(config) => config,\n\n };\n\n\n\n if let Some(ctx) = kc_config.config.current_context() {\n\n Ok(ctx.name.to_owned())\n\n } else {\n\n Err(CliError::Other(\"no context found\".to_owned()))\n\n }\n\n}\n\n\n\n/// create new k8 cluster and profile\n\npub async fn set_k8_context(opt: K8Opt, external_addr: String) -> Result<Profile, CliError> {\n\n let mut config_file = ConfigFile::load_default_or_new()?;\n\n let config = config_file.mut_config();\n\n\n", "file_path": "src/cli/src/profile/k8.rs", "rank": 8, "score": 244292.47638390688 }, { "content": "// generate replication folder name\n\nfn replica_dir_name<S: AsRef<str>>(topic_name: S, partition_index: Size) -> String {\n\n format!(\"{}-{}\", topic_name.as_ref(), partition_index)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\n\n use tracing::debug;\n\n use std::env::temp_dir;\n\n use std::fs;\n\n use std::fs::metadata;\n\n use std::io::Cursor;\n\n\n\n use fluvio_future::test_async;\n\n use dataplane::batch::DefaultBatch;\n\n use dataplane::{Offset, ErrorCode};\n\n use dataplane::core::{Decoder, Encoder};\n\n use dataplane::fetch::FilePartitionResponse;\n\n use dataplane::record::RecordSet;\n\n use flv_util::fixture::ensure_clean_dir;\n", "file_path": "src/storage/src/replica.rs", "rank": 9, "score": 242537.49587474784 }, { "content": "type Config = (ScConfig, Option<BasicRbacPolicy>);\n\n\n\n/// cli options\n\n#[derive(Debug, StructOpt, Default)]\n\n#[structopt(name = \"sc-server\", about = \"Streaming Controller\")]\n\npub struct ScOpt {\n\n #[structopt(long)]\n\n /// Address for external service\n\n bind_public: Option<String>,\n\n\n\n #[structopt(long)]\n\n /// Address for internal service\n\n bind_private: Option<String>,\n\n\n\n // k8 namespace\n\n #[structopt(short = \"n\", long = \"namespace\", value_name = \"namespace\")]\n\n namespace: Option<String>,\n\n\n\n #[structopt(flatten)]\n\n tls: TlsConfig,\n", "file_path": "src/sc/src/cli.rs", "rank": 10, "score": 237499.15741889182 }, { "content": "// start server\n\npub fn create_public_server(addr: String, ctx: DefaultSharedGlobalContext) -> PublicApiServer {\n\n info!(\n\n \"starting SPU: {} at public service at: {}\",\n\n ctx.local_spu_id(),\n\n addr\n\n );\n\n\n\n FlvApiServer::new(addr, ctx, PublicService::new())\n\n}\n", "file_path": "src/spu/src/services/public/mod.rs", "rank": 11, "score": 234291.874242707 }, { "content": "// start server\n\npub fn create_internal_server(addr: String, ctx: DefaultSharedGlobalContext) -> InternalApiServer {\n\n info!(\n\n \"starting SPU: {} at internal service at: {}\",\n\n ctx.local_spu_id(),\n\n addr\n\n );\n\n\n\n FlvApiServer::new(addr, ctx, InternalService::new())\n\n}\n", "file_path": "src/spu/src/services/internal/mod.rs", "rank": 12, "score": 234291.874242707 }, { "content": "#[allow(unused)]\n\npub fn command_exec(binary: &str, prefix: &str, process: impl Fn(&mut Command)) {\n\n let mut cmd = get_binary(binary).unwrap_or_else(|_| panic!(\"unable to get binary: {}\", binary));\n\n\n\n let (output, error) = open_log(prefix);\n\n\n\n cmd.stdout(Stdio::from(output)).stderr(Stdio::from(error));\n\n\n\n process(&mut cmd);\n\n\n\n let status = cmd.status().expect(\"topic creation failed\");\n\n\n\n if !status.success() {\n\n println!(\"topic creation failed: {}\", status);\n\n }\n\n}\n\n\n\nuse std::process::Child;\n\n\n", "file_path": "src/utils/src/bin.rs", "rank": 13, "score": 230123.2702388984 }, { "content": "/// Streaming Controller dispatcher entry point, spawns new thread\n\npub fn run<K,C>(receiver: Receiver<ScRequest>, sc_controller: ScController<K,C>) \n\n where K: WSUpdateService + Send + Sync + 'static,\n\n C: SpuConnections + Send + Sync + 'static\n\n{\n\n info!(\"start SC[{}] dispatcher\", sc_controller.id());\n\n\n\n spawn(sc_request_loop(receiver, sc_controller);\n\n}\n\n\n\n/// SC dispatcher request loop, waits for a request request and dispatchers\n\n/// it for processing.\n\nasync fn sc_request_loop<K,C>(mut receiver: Receiver<ScRequest>, mut sc_controller: ScController<K,C>) \n\n where K: WSUpdateService , C: SpuConnections \n\n{\n\n loop {\n\n select! {\n\n receiver_req = receiver.next() => {\n\n match receiver_req {\n\n None => {\n\n info!(\"SC dispatcher receiver is removed. end\");\n", "file_path": "src/sc/src/core/dispatcher.rs", "rank": 14, "score": 227311.88124565335 }, { "content": "pub fn process_releases(opt: ReleasesCommand) -> Result<String, CliError> {\n\n match opt {\n\n ReleasesCommand::List => list_releases()?,\n\n }\n\n Ok(\"\".to_string())\n\n}\n\n\n", "file_path": "src/cli/src/cluster/releases.rs", "rank": 15, "score": 226841.48958721507 }, { "content": "#[allow(unused)]\n\npub fn command_spawn(binary: &str, prefix: &str, process: impl Fn(&mut Command)) -> Child {\n\n let mut cmd = get_binary(binary).unwrap_or_else(|_| panic!(\"unable to get binary: {}\", binary));\n\n\n\n let (output, error) = open_log(prefix);\n\n\n\n cmd.stdout(Stdio::from(output)).stderr(Stdio::from(error));\n\n\n\n process(&mut cmd);\n\n\n\n cmd.spawn().expect(\"child\")\n\n}\n", "file_path": "src/utils/src/bin.rs", "rank": 16, "score": 223922.08755974067 }, { "content": "pub fn process_run(run_opt: RunOpt) -> Result<String, CliError> {\n\n match run_opt {\n\n RunOpt::SPU(opt) => fluvio_spu::main_loop(opt),\n\n RunOpt::SC(opt) => fluvio_sc::k8::main_k8_loop(opt),\n\n }\n\n\n\n Ok(\"\".to_owned())\n\n}\n", "file_path": "src/cli/src/run/mod.rs", "rank": 17, "score": 223561.58052493125 }, { "content": "pub fn process_switch<O>(out: std::sync::Arc<O>, opt: SwitchOpt) -> Result<String, CliError>\n\nwhere\n\n O: Terminal,\n\n{\n\n let profile_name = opt.profile_name;\n\n match ConfigFile::load(None) {\n\n Ok(mut config_file) => {\n\n if !config_file.mut_config().set_current_profile(&profile_name) {\n\n t_println!(out, \"profile {} not found\", &profile_name);\n\n } else if let Err(err) = config_file.save() {\n\n t_println!(out, \"unable to save profile: {}\", err);\n\n }\n\n }\n\n Err(_) => t_print_cli_err!(out, \"no profile can be found\"),\n\n }\n\n\n\n Ok(\"\".to_string())\n\n}\n\n\n", "file_path": "src/cli/src/profile/mod.rs", "rank": 18, "score": 223114.99851825967 }, { "content": "pub fn process_delete<O>(out: std::sync::Arc<O>, opt: DeleteOpt) -> Result<String, CliError>\n\nwhere\n\n O: Terminal,\n\n{\n\n let profile_name = opt.profile_name;\n\n match ConfigFile::load(None) {\n\n Ok(mut config_file) => {\n\n if !config_file.mut_config().delete_profile(&profile_name) {\n\n t_println!(out, \"profile {} not found\", &profile_name);\n\n } else if let Err(err) = config_file.save() {\n\n t_println!(out, \"unable to save profile: {}\", err);\n\n } else {\n\n t_println!(out, \"profile {} deleted\", &profile_name);\n\n if config_file.config().current_profile_name().is_none() {\n\n t_println!(out,\"warning: this removed your current profile, use 'config switch-profile to select a different one\");\n\n } else {\n\n t_println!(out, \"profile deleted\");\n\n }\n\n }\n\n }\n\n Err(_) => t_print_cli_err!(out, \"no profile can be found\"),\n\n }\n\n\n\n Ok(\"\".to_string())\n\n}\n\n\n", "file_path": "src/cli/src/profile/mod.rs", "rank": 19, "score": 223114.99851825967 }, { "content": "/// If header has error, format and return\n\npub fn error_in_header(\n\n topic_name: &str,\n\n r_partition: &FetchablePartitionResponse<RecordSet>,\n\n) -> Option<String> {\n\n if r_partition.error_code.is_error() {\n\n Some(format!(\n\n \"topic '{}/{}': {}\",\n\n topic_name,\n\n r_partition.partition_index,\n\n r_partition.error_code.to_sentence()\n\n ))\n\n } else {\n\n None\n\n }\n\n}\n", "file_path": "src/cli/src/consume/logs_output.rs", "rank": 20, "score": 221342.97670329746 }, { "content": "/// Process server based on output type\n\npub fn format_spu_response_output<O>(\n\n out: std::sync::Arc<O>,\n\n spus: ListSpus,\n\n output_type: OutputType,\n\n) -> Result<(), CliError>\n\nwhere\n\n O: Terminal,\n\n{\n\n if !spus.is_empty() {\n\n out.render_list(&spus, output_type)?;\n\n } else {\n\n t_println!(out, \"no spu\");\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\nimpl TableOutputHandler for ListSpus {\n\n /// table header implementation\n\n fn header(&self) -> Row {\n", "file_path": "src/cli/src/spu/display.rs", "rank": 21, "score": 220049.4644864777 }, { "content": "fn find_spu_image() -> String {\n\n std::env::var(\"SPU_IMAGE\").expect(\"SPU IMAGE must be passed as env\")\n\n}\n\n\n", "file_path": "src/sc/src/k8/operator/conversion.rs", "rank": 22, "score": 218242.24756624005 }, { "content": "/// Traverse all partition batches and parse records to json format\n\npub fn partition_to_json_records(\n\n partition: &FetchablePartitionResponse<RecordSet>,\n\n suppress: bool,\n\n) -> Vec<Value> {\n\n let mut json_records: Vec<Value> = vec![];\n\n\n\n // convert all batches to json records\n\n for batch in &partition.records.batches {\n\n for record in &batch.records {\n\n if let Some(batch_record) = record.get_value().inner_value_ref() {\n\n match serde_json::from_slice(&batch_record) {\n\n Ok(value) => json_records.push(value),\n\n Err(_) => {\n\n if !suppress {\n\n json_records.push(serde_json::json!({\n\n \"error\": record.get_value().describe()\n\n }));\n\n }\n\n }\n\n }\n\n }\n\n }\n\n }\n\n\n\n json_records\n\n}\n\n\n", "file_path": "src/cli/src/consume/logs_output.rs", "rank": 23, "score": 216924.50418309803 }, { "content": "/// Generates a random authorization token\n\npub fn generate_auth_token() -> (String, String) {\n\n const CHARSET: &[u8] = b\"abcdefghijklmnopqrstuvwxyz\\\n\n 0123456789\";\n\n\n\n const ID_SIZE: usize = 6;\n\n let token_name: String = (0..ID_SIZE)\n\n .map(|_| {\n\n let idx = thread_rng().gen_range(0, CHARSET.len());\n\n // This is safe because `idx` is in range of `CHARSET`\n\n char::from(unsafe { *CHARSET.get_unchecked(idx) })\n\n })\n\n .collect();\n\n\n\n const SECRET_SIZE: usize = 16;\n\n let token_secret: String = (0..SECRET_SIZE)\n\n .map(|_| {\n\n let idx = thread_rng().gen_range(0, CHARSET.len());\n\n // This is safe because `idx` is in range of `CHARSET`\n\n char::from(unsafe { *CHARSET.get_unchecked(idx) })\n\n })\n\n .collect();\n\n\n\n (token_name, token_secret)\n\n}\n\n\n\n#[allow(dead_code)]\n", "file_path": "src/utils/src/generators.rs", "rank": 24, "score": 216683.83232184197 }, { "content": "pub fn default_option(index_max_interval_bytes: Size) -> ConfigOption {\n\n ConfigOption {\n\n segment_max_bytes: 100,\n\n index_max_interval_bytes,\n\n base_dir: temp_dir(),\n\n index_max_bytes: 1000,\n\n }\n\n}\n\n\n\nmod pin_tests {\n\n\n\n use std::pin::Pin;\n\n use pin_utils::pin_mut;\n\n use pin_utils::unsafe_unpinned;\n\n\n\n // impl Unpin for Counter{}\n\n\n\n struct Counter {\n\n total: u16,\n\n }\n", "file_path": "src/storage/src/fixture.rs", "rank": 25, "score": 216492.45818404213 }, { "content": "// returns a tuple (topic_name, idx)\n\npub fn decompose_partition_name(partition_name: &str) -> Result<(String, i32), PartitionError> {\n\n let dash_pos = partition_name.rfind('-');\n\n if dash_pos.is_none() {\n\n return Err(PartitionError::InvalidSyntax(partition_name.to_owned()));\n\n }\n\n\n\n let pos = dash_pos.unwrap();\n\n if (pos + 1) >= partition_name.len() {\n\n return Err(PartitionError::InvalidSyntax(partition_name.to_owned()));\n\n }\n\n\n\n let topic_name = &partition_name[..pos];\n\n let idx_string = &partition_name[(pos + 1)..];\n\n let idx = match idx_string.parse::<i32>() {\n\n Ok(n) => n,\n\n Err(_) => {\n\n return Err(PartitionError::InvalidSyntax(partition_name.to_owned()));\n\n }\n\n };\n\n\n\n Ok((topic_name.to_string(), idx))\n\n}\n\n\n", "file_path": "src/dataplane-protocol/src/common.rs", "rank": 26, "score": 215996.35997868638 }, { "content": "/// find spu id from env, if not found, return error\n\nfn find_spu_id_from_env() -> Result<SpuId, IoError> {\n\n use std::env;\n\n use fluvio_types::defaults::FLV_SPU_ID;\n\n\n\n if let Ok(id_str) = env::var(FLV_SPU_ID) {\n\n debug!(\"found spu id from env: {}\", id_str);\n\n let id = id_str\n\n .parse()\n\n .map_err(|err| IoError::new(ErrorKind::InvalidInput, format!(\"spu-id: {}\", err)))?;\n\n Ok(id)\n\n } else {\n\n // try get special env SPU which has form of {}-{id} when in as in-cluster config\n\n if let Ok(spu_name) = env::var(\"SPU_INDEX\") {\n\n info!(\"extracting SPU from: {}\", spu_name);\n\n let spu_tokens: Vec<&str> = spu_name.split('-').collect();\n\n if spu_tokens.len() < 2 {\n\n Err(IoError::new(\n\n ErrorKind::InvalidInput,\n\n format!(\"SPU is invalid format: {} bailing out\", spu_name),\n\n ))\n", "file_path": "src/spu/src/config/cli.rs", "rank": 27, "score": 215408.0282878956 }, { "content": "#[derive(Debug, StructOpt, Default)]\n\nstruct TlsConfig {\n\n /// enable tls\n\n #[structopt(long)]\n\n pub tls: bool,\n\n\n\n /// TLS: path to server certificate\n\n #[structopt(long)]\n\n pub server_cert: Option<String>,\n\n #[structopt(long)]\n\n /// TLS: path to server private key\n\n pub server_key: Option<String>,\n\n /// TLS: enable client cert\n\n #[structopt(long)]\n\n pub enable_client_cert: bool,\n\n /// TLS: path to ca cert, required when client cert is enabled\n\n #[structopt(long)]\n\n pub ca_cert: Option<String>,\n\n\n\n #[structopt(long)]\n\n /// TLS: address of non tls public service, required\n\n pub bind_non_tls_public: Option<String>,\n\n}\n", "file_path": "src/spu/src/config/cli.rs", "rank": 28, "score": 211701.2569100922 }, { "content": "///\n\n/// Validate computed topic spec parameters and update topic status\n\n/// * error is passed to the topic reason.\n\n///\n\npub fn validate_computed_topic_parameters(param: &TopicReplicaParam) -> TopicNextState {\n\n if let Err(err) = TopicSpec::valid_partition(&param.partitions) {\n\n TopicStatus::next_resolution_invalid_config(&err.to_string()).into()\n\n } else if let Err(err) = TopicSpec::valid_replication_factor(&param.replication_factor) {\n\n TopicStatus::next_resolution_invalid_config(&err.to_string()).into()\n\n } else {\n\n TopicStatus::next_resolution_pending().into()\n\n }\n\n}\n\n\n\n///\n\n/// Generate Replica Map if there are enough online spus\n\n/// * returns a replica map or a reason for the failure\n\n/// * fatal error configuration errors and are not recoverable\n\n///\n\npub async fn generate_replica_map(\n\n spus: &SpuAdminStore,\n\n param: &TopicReplicaParam,\n\n) -> TopicNextState {\n\n let spu_count = spus.count().await;\n", "file_path": "src/sc/src/controllers/topics/policy.rs", "rank": 29, "score": 210563.0110112667 }, { "content": "#[async_trait]\n\npub trait PartitionLocalStorePolicy<C>\n\nwhere\n\n C: MetadataItem,\n\n{\n\n async fn names(&self) -> Vec<ReplicaKey>;\n\n\n\n async fn topic_partitions(&self, topic: &str) -> Vec<PartitionMetadata<C>>;\n\n\n\n /// find all partitions that has spu in the replicas\n\n async fn partition_spec_for_spu(&self, target_spu: i32) -> Vec<(ReplicaKey, PartitionSpec)>;\n\n\n\n async fn count_topic_partitions(&self, topic: &str) -> i32;\n\n\n\n // return partitions that belong to this topic\n\n async fn topic_partitions_list(&self, topic: &str) -> Vec<ReplicaKey>;\n\n\n\n async fn table_fmt(&self) -> String;\n\n\n\n /// replica msg for target spu\n\n async fn replica_for_spu(&self, target_spu: SpuId) -> Vec<Replica>;\n", "file_path": "src/controlplane-metadata/src/partition/store.rs", "rank": 30, "score": 209198.35896586106 }, { "content": "#[async_trait]\n\npub trait TopicLocalStorePolicy<C>\n\nwhere\n\n C: MetadataItem,\n\n{\n\n async fn table_fmt(&self) -> String;\n\n}\n\n\n\n#[async_trait]\n\nimpl<C> TopicLocalStorePolicy<C> for TopicLocalStore<C>\n\nwhere\n\n C: MetadataItem + Send + Sync,\n\n{\n\n async fn table_fmt(&self) -> String {\n\n let mut table = String::new();\n\n\n\n let topic_hdr = format!(\n\n \"{n:<18} {t:<8} {p:<5} {s:<5} {g:<8} {l:<14} {m:<10} {r}\\n\",\n\n n = \"TOPIC\",\n\n t = \"TYPE\",\n\n p = \"PART\",\n", "file_path": "src/controlplane-metadata/src/topic/store.rs", "rank": 31, "score": 209198.35896586106 }, { "content": "pub fn view_profile<O>(out: std::sync::Arc<O>) -> eyre::Result<()>\n\nwhere\n\n O: Terminal,\n\n{\n\n let config_file = ConfigFile::load(None).context(\"Failed to read Fluvio config file\")?;\n\n t_println!(out, \"{:#?}\", config_file.config());\n\n Ok(())\n\n}\n\n\n", "file_path": "src/cli/src/profile/context.rs", "rank": 32, "score": 209172.35245652407 }, { "content": "/// Print records based on their type\n\npub fn print_dynamic_records<O>(\n\n out: std::sync::Arc<O>,\n\n topic_name: &str,\n\n response_partitions: &[FetchablePartitionResponse<RecordSet>],\n\n) where\n\n O: Terminal,\n\n{\n\n for r_partition in response_partitions {\n\n if let Some(err) = error_in_header(topic_name, r_partition) {\n\n t_print_cli_err!(out, err);\n\n continue;\n\n }\n\n\n\n for batch in &r_partition.records.batches {\n\n for record in &batch.records {\n\n if let Some(batch_record) = record.get_value().inner_value_ref() {\n\n // TODO: this should be refactored\n\n if let Some(bytes) = record.get_value().inner_value_ref() {\n\n debug!(\"len: {}\", bytes.len());\n\n }\n", "file_path": "src/cli/src/consume/logs_output.rs", "rank": 33, "score": 208799.7144529275 }, { "content": "/// parse message and generate log records\n\npub fn generate_json_records<O>(\n\n out: std::sync::Arc<O>,\n\n topic_name: &str,\n\n response_partitions: &[FetchablePartitionResponse<RecordSet>],\n\n suppress: bool,\n\n) -> Vec<Value>\n\nwhere\n\n O: Terminal,\n\n{\n\n let mut json_records: Vec<Value> = vec![];\n\n\n\n for r_partition in response_partitions {\n\n if let Some(err) = error_in_header(topic_name, r_partition) {\n\n t_print_cli_err!(out, err);\n\n continue;\n\n }\n\n\n\n let mut new_records = partition_to_json_records(&r_partition, suppress);\n\n json_records.append(&mut new_records);\n\n }\n\n\n\n json_records\n\n}\n\n\n", "file_path": "src/cli/src/consume/logs_output.rs", "rank": 34, "score": 208799.64318581208 }, { "content": "/// parse message and generate partition records\n\npub fn print_binary_records<O>(\n\n out: std::sync::Arc<O>,\n\n topic_name: &str,\n\n response_partitions: &[FetchablePartitionResponse<RecordSet>],\n\n) where\n\n O: Terminal,\n\n{\n\n debug!(\n\n \"printing out binary records: {} records: {}\",\n\n topic_name,\n\n response_partitions.len()\n\n );\n\n let mut printed = false;\n\n for r_partition in response_partitions {\n\n if let Some(err) = error_in_header(topic_name, r_partition) {\n\n t_println!(out, \"{}\", hex_dump_separator());\n\n t_print_cli_err!(out, err);\n\n printed = true;\n\n continue;\n\n }\n", "file_path": "src/cli/src/consume/logs_output.rs", "rank": 35, "score": 208794.07690288225 }, { "content": "/// Print records in text format\n\npub fn print_text_records<O>(\n\n out: std::sync::Arc<O>,\n\n topic_name: &str,\n\n response_partitions: &[FetchablePartitionResponse<RecordSet>],\n\n suppress: bool,\n\n) where\n\n O: Terminal,\n\n{\n\n debug!(\"processing text record: {:#?}\", response_partitions);\n\n\n\n for r_partition in response_partitions {\n\n if let Some(err) = error_in_header(topic_name, r_partition) {\n\n t_print_cli_err!(out, err);\n\n continue;\n\n }\n\n\n\n for batch in &r_partition.records.batches {\n\n for record in &batch.records {\n\n if record.get_value().inner_value_ref().is_some() {\n\n if record.get_value().is_binary() {\n", "file_path": "src/cli/src/consume/logs_output.rs", "rank": 36, "score": 208794.07690288225 }, { "content": "/// Print records in raw format\n\npub fn print_raw_records<O>(\n\n out: std::sync::Arc<O>,\n\n topic_name: &str,\n\n response_partitions: &[FetchablePartitionResponse<RecordSet>],\n\n) where\n\n O: Terminal,\n\n{\n\n for r_partition in response_partitions {\n\n if let Some(err) = error_in_header(topic_name, r_partition) {\n\n t_print_cli_err!(out, err);\n\n continue;\n\n }\n\n\n\n for batch in &r_partition.records.batches {\n\n for record in &batch.records {\n\n if let Some(value) = record.get_value().inner_value_ref() {\n\n let str_value = std::str::from_utf8(value).unwrap();\n\n t_println!(out, \"{}\", str_value);\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n\n// -----------------------------------\n\n// Utilities\n\n// -----------------------------------\n\n\n", "file_path": "src/cli/src/consume/logs_output.rs", "rank": 37, "score": 208794.07690288225 }, { "content": "pub fn create_partition_name(topic_name: &str, idx: &i32) -> String {\n\n format!(\"{}-{}\", topic_name, idx)\n\n}\n", "file_path": "src/types/src/partition.rs", "rank": 38, "score": 208186.77023268695 }, { "content": "/// Generates a random authorization secret\n\npub fn generate_secret() -> String {\n\n const CHARSET: &[u8] = b\"abcdefghijklmnopqrstuvwxyz\\\n\n 0123456789\";\n\n\n\n const SECRET_SIZE: usize = 16;\n\n let secret: String = (0..SECRET_SIZE)\n\n .map(|_| {\n\n let idx = thread_rng().gen_range(0, CHARSET.len());\n\n // This is safe because `idx` is in range of `CHARSET`\n\n char::from(unsafe { *CHARSET.get_unchecked(idx) })\n\n })\n\n .collect();\n\n\n\n secret\n\n}\n\n\n\n#[allow(dead_code)]\n", "file_path": "src/utils/src/generators.rs", "rank": 39, "score": 207472.1288930106 }, { "content": "pub fn generate_service(spg: &K8SpuGroupSpec, name: &str) -> ServiceSpec {\n\n let spg_template = &spg.template.spec;\n\n let mut public_port = ServicePort {\n\n port: spg_template\n\n .public_endpoint\n\n .as_ref()\n\n .map(|t| t.port)\n\n .unwrap_or(SPU_PUBLIC_PORT),\n\n ..Default::default()\n\n };\n\n\n\n public_port.name = Some(\"public\".to_owned());\n\n let mut private_port = ServicePort {\n\n port: spg_template\n\n .private_endpoint\n\n .as_ref()\n\n .map(|t| t.port)\n\n .unwrap_or(SPU_PRIVATE_PORT),\n\n ..Default::default()\n\n };\n", "file_path": "src/sc/src/k8/operator/conversion.rs", "rank": 40, "score": 204929.34111360952 }, { "content": "/// Generates a random key\n\npub fn generate_random_key() -> String {\n\n const CHARSET: &[u8] = b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\\\n\n abcdefghijklmnopqrstuvwxyz\\\n\n 0123456789)(*&^%$#@!~\";\n\n const SIZE: usize = 32;\n\n let key: String = (0..SIZE)\n\n .map(|_| {\n\n let idx = thread_rng().gen_range(0, CHARSET.len());\n\n // This is safe because `idx` is in range of `CHARSET`\n\n char::from(unsafe { *CHARSET.get_unchecked(idx) })\n\n })\n\n .collect();\n\n\n\n key\n\n}\n", "file_path": "src/utils/src/generators.rs", "rank": 41, "score": 203976.31607148933 }, { "content": "#[allow(dead_code)]\n\nstruct Dispatcher<C>(C);\n\n\n\n#[allow(dead_code)]\n\nimpl<S> Dispatcher<C>\n\nwhere\n\n C: Controller + Send + Sync + 'static,\n\n C::Action: Send + Sync + 'static,\n\n{\n\n /// start the controller with ctx and receiver\n\n pub fn run<K>(controller: C, receiver: Receiver<Actions<C::Action>>, kv_service: K)\n\n where\n\n K: WSUpdateService + Send + Sync + 'static,\n\n {\n\n spawn(Self::request_loop(receiver, kv_service, controller).await);\n\n }\n\n\n\n async fn request_loop<K>(\n\n mut receiver: Receiver<Actions<C::Action>>,\n\n _kv_service: K,\n\n mut _controller: C,\n", "file_path": "src/sc/src/core/common/dispatcher.rs", "rank": 42, "score": 203661.84681914892 }, { "content": "pub fn log_path_get_offset<P>(path: P) -> Result<Offset, OffsetError>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n let log_path = path.as_ref();\n\n\n\n match log_path.file_stem() {\n\n None => Err(OffsetError::InvalidPath),\n\n Some(file_name) => {\n\n if file_name.len() != 20 {\n\n Err(OffsetError::InvalidLogFileName)\n\n } else {\n\n file_name\n\n .to_str()\n\n .unwrap()\n\n .parse()\n\n .map_err(|err: ParseIntError| err.into())\n\n }\n\n }\n\n }\n", "file_path": "src/storage/src/util.rs", "rank": 43, "score": 198258.986142402 }, { "content": "/// Return separator for hex dump\n\npub fn hex_dump_separator() -> String {\n\n \"------------------------------------------------------------------------------\\n\".to_owned()\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::bytes_to_hex_dump;\n\n\n\n #[test]\n\n fn test_bytes_to_hex_dump() {\n\n let records: Vec<u8> = vec![\n\n 123, 10, 32, 32, 32, 32, 34, 112, 97, 114, 116, 105, 116, 105, 111, 110, 115, 34, 58,\n\n 32, 91, 10, 32, 32, 32, 32, 32, 32, 32, 32, 123, 10, 32, 32, 32, 32, 32, 32, 32, 32,\n\n 32, 32, 32, 32, 34, 105, 100, 34, 58, 32, 48, 44, 10, 32, 32, 32, 32, 32, 32, 32, 32,\n\n 32, 32, 32, 32, 34, 114, 101, 112, 108, 105, 99, 97, 115, 34, 58, 32, 91, 10, 32, 32,\n\n 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 53, 48, 48, 49, 44, 10, 32, 32,\n\n 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 53, 48, 48, 50, 44, 10, 32, 32,\n\n 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 53, 48, 48, 51, 10, 32, 32, 32,\n\n 32, 32, 32, 32, 32, 32, 32, 32, 32, 93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 125, 10,\n\n 32, 32, 32, 32, 93, 10, 125,\n", "file_path": "src/cli/src/common/hex_dump.rs", "rank": 44, "score": 197524.55576975818 }, { "content": "struct ScServerCtx {\n\n ctx: SharedScContext,\n\n sender: Sender<bool>,\n\n}\n\n\n\npub struct SpuTestRunner<T> {\n\n client_id: String,\n\n spu_server_specs: Vec<SpuServer>,\n\n spu_server_ctx: Vec<DefaultSharedGlobalContext>,\n\n spu_senders: Vec<Sender<bool>>,\n\n sc_ctx: RwLock<Option<ScServerCtx>>,\n\n test: T,\n\n}\n\n\n\nimpl<T> SpuTestRunner<T>\n\nwhere\n\n T: SpuTest + Send + Sync + 'static,\n\n{\n\n pub async fn run(client_id: String, test: T) -> Result<(), FlvSocketError> {\n\n debug!(\"starting test harnerss\");\n", "file_path": "src/spu/src/tests/fixture/test_runner.rs", "rank": 45, "score": 194485.6133947686 }, { "content": "pub fn start_internal_server(ctx: SharedContext) {\n\n info!(\"starting internal services\");\n\n\n\n let addr = ctx.config().private_endpoint.clone();\n\n let server = FlvApiServer::new(addr, ctx, ScInternalService::new());\n\n server.run();\n\n}\n", "file_path": "src/sc/src/services/private_api/mod.rs", "rank": 46, "score": 192860.22814807057 }, { "content": "fn process_version_cmd() -> Result<String, CliError> {\n\n println!(\"Fluvio version : {}\", crate::VERSION);\n\n println!(\"Git Commit : {}\", env!(\"GIT_HASH\"));\n\n if let Some(os_info) = option_env!(\"UNAME\") {\n\n println!(\"OS Details : {}\", os_info);\n\n }\n\n println!(\"Rustc Version : {}\", env!(\"RUSTC_VERSION\"));\n\n Ok(\"\".to_owned())\n\n}\n\n\n", "file_path": "src/cli/src/root_cli.rs", "rank": 47, "score": 192547.76638174237 }, { "content": "/// generate server configuration file\n\npub fn build_server_config_file_path(file_name: &'static str) -> PathBuf {\n\n let mut config_file_path = PathBuf::new();\n\n\n\n // stitch-up default configuration file path\n\n config_file_path.push(SERVER_CONFIG_BASE_PATH);\n\n config_file_path.push(SERVER_CONFIG_DIR);\n\n config_file_path.push(file_name);\n\n config_file_path.set_extension(CONFIG_FILE_EXTENTION);\n\n\n\n config_file_path\n\n}\n\n\n\n//\n\n// Unit Tests\n\n//\n\n\n\n#[cfg(test)]\n\npub mod test {\n\n use super::*;\n\n use fluvio_types::defaults::{SC_CONFIG_FILE, SPU_CONFIG_FILE};\n", "file_path": "src/utils/src/config_helper.rs", "rank": 48, "score": 191694.17789731245 }, { "content": "fn default_config(spu_id: SpuId, config: &ConfigOption) -> ConfigOption {\n\n let base_dir = config.base_dir.join(format!(\"spu-logs-{}\", spu_id));\n\n let new_config = config.clone();\n\n new_config.base_dir(base_dir)\n\n}\n\n\n\n/// Create new replica storage. Each replica is stored with 'spu' prefix\n\npub(crate) async fn create_replica_storage(\n\n local_spu: SpuId,\n\n replica: &ReplicaKey,\n\n base_config: &ConfigOption,\n\n) -> Result<FileReplica, StorageError> {\n\n let config = default_config(local_spu, base_config);\n\n FileReplica::create(replica.topic.clone(), replica.partition as u32, 0, &config).await\n\n}\n", "file_path": "src/spu/src/core/storage/mod.rs", "rank": 49, "score": 190894.213991921 }, { "content": "#[async_trait]\n\npub trait SpuValidation {\n\n fn is_already_valid(&self) -> bool;\n\n async fn is_conflict_with(&self, spu_store: &SpuAdminStore) -> Option<SpuId>;\n\n}\n\n\n\n#[async_trait]\n\nimpl SpuValidation for SpuGroupObj {\n\n /// check if I am already been validated\n\n fn is_already_valid(&self) -> bool {\n\n self.status.is_already_valid()\n\n }\n\n\n\n /// check if my group's id is conflict with my spu local store\n\n async fn is_conflict_with(&self, spu_store: &SpuAdminStore) -> Option<SpuId> {\n\n if self.is_already_valid() {\n\n return None;\n\n }\n\n\n\n let min_id = self.spec.min_id as SpuId;\n\n\n\n is_conflict(\n\n spu_store,\n\n self.metadata.uid.clone(),\n\n min_id,\n\n min_id + self.spec.replicas as SpuId,\n\n )\n\n .await\n\n }\n\n}\n", "file_path": "src/sc/src/k8/operator/spg_group.rs", "rank": 50, "score": 187727.72699271183 }, { "content": "/// Detects the target triple of the current build and returns\n\n/// the name of a compatible build target on packages.fluvio.io.\n\n///\n\n/// Returns `Some(Target)` if there is a compatible target, or\n\n/// `None` if this target is unsupported or has no compatible target.\n\npub fn package_target() -> Result<Target, Error> {\n\n let target = PACKAGE_TARGET.parse()?;\n\n Ok(target)\n\n}\n\n\n\n#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]\n\n#[allow(non_camel_case_types)]\n\npub enum Target {\n\n #[serde(rename = \"x86_64-apple-darwin\")]\n\n X86_64AppleDarwin,\n\n #[serde(rename = \"x86_64-unknown-linux-musl\")]\n\n X86_64UnknownLinuxMusl,\n\n}\n\n\n\nimpl Target {\n\n pub fn as_str(&self) -> &str {\n\n match self {\n\n Self::X86_64AppleDarwin => \"x86_64-apple-darwin\",\n\n Self::X86_64UnknownLinuxMusl => \"x86_64-unknown-linux-musl\",\n\n }\n", "file_path": "src/package-index/src/target.rs", "rank": 51, "score": 187581.6152071529 }, { "content": "pub fn get_fluvio() -> Result<Command, IoError> {\n\n get_binary(\"fluvio\")\n\n}\n\n\n", "file_path": "src/utils/src/bin.rs", "rank": 52, "score": 187581.6152071529 }, { "content": "/// create server and spin up services, but don't run server\n\npub fn create_services(\n\n local_spu: SpuConfig,\n\n internal: bool,\n\n public: bool,\n\n) -> (\n\n DefaultSharedGlobalContext,\n\n Option<InternalApiServer>,\n\n Option<PublicApiServer>,\n\n) {\n\n let ctx = FileReplicaContext::new_shared_context(local_spu);\n\n\n\n let public_ep_addr = ctx.config().public_socket_addr().to_owned();\n\n let private_ep_addr = ctx.config().private_socket_addr().to_owned();\n\n\n\n let public_server = if public {\n\n Some(create_public_server(public_ep_addr, ctx.clone()))\n\n } else {\n\n None\n\n };\n\n\n", "file_path": "src/spu/src/start.rs", "rank": 53, "score": 185291.9797061971 }, { "content": "pub trait ScConfigBuilder {\n\n fn to_sc_config(self) -> Result<ScConfig, IoError>;\n\n}\n\n\n\n/// streaming controller configuration file\n\n#[derive(Debug, Clone, PartialEq)]\n\npub struct ScConfig {\n\n pub public_endpoint: String,\n\n pub private_endpoint: String,\n\n pub run_k8_dispatchers: bool,\n\n pub namespace: String,\n\n pub x509_auth_scopes: Option<PathBuf>,\n\n}\n\n\n\nimpl ::std::default::Default for ScConfig {\n\n fn default() -> Self {\n\n Self {\n\n public_endpoint: format!(\"0.0.0.0:{}\", SC_PUBLIC_PORT),\n\n private_endpoint: format!(\"0.0.0.0:{}\", SC_PRIVATE_PORT),\n\n run_k8_dispatchers: true,\n\n namespace: \"default\".to_owned(),\n\n x509_auth_scopes: None,\n\n }\n\n }\n\n}\n", "file_path": "src/sc/src/config/sc_config.rs", "rank": 54, "score": 185163.8123800348 }, { "content": "/// Create a channel\n\npub fn new_channel<T>() -> (Sender<T>, Receiver<T>) {\n\n channel(100)\n\n}\n", "file_path": "src/sc/src/core/common/channels.rs", "rank": 55, "score": 185051.5562264072 }, { "content": "fn default_index_max_bytes() -> Size {\n\n SPU_LOG_INDEX_MAX_BYTES\n\n}\n\n\n", "file_path": "src/storage/src/config.rs", "rank": 56, "score": 183942.00723078605 }, { "content": "fn default_segment_max_bytes() -> Size {\n\n SPU_LOG_SEGMENT_MAX_BYTES\n\n}\n\n\n\nimpl ConfigOption {\n\n pub fn new(\n\n base_dir: PathBuf,\n\n index_max_bytes: u32,\n\n index_max_interval_bytes: u32,\n\n segment_max_bytes: u32,\n\n ) -> Self {\n\n ConfigOption {\n\n base_dir,\n\n index_max_bytes,\n\n index_max_interval_bytes,\n\n segment_max_bytes,\n\n }\n\n }\n\n\n\n pub fn base_dir(mut self, dir: PathBuf) -> Self {\n", "file_path": "src/storage/src/config.rs", "rank": 57, "score": 183942.00723078605 }, { "content": "#[allow(clippy::needless_range_loop)]\n\npub fn bytes_to_hex_dump(record: &[u8]) -> String {\n\n let cols = 16;\n\n let record_cnt = record.len();\n\n let mut result = String::new();\n\n let mut collector = String::new();\n\n\n\n for row_idx in 0..record_cnt {\n\n // colunn index\n\n if row_idx % cols == 0 {\n\n result.push_str(&format!(\"{:08x}\", row_idx));\n\n }\n\n\n\n // spacing half way\n\n if row_idx % (cols / 2) == 0 {\n\n result.push_str(\" \");\n\n }\n\n\n\n // convert and add character to collector\n\n collector.push_str(&byte_to_string(&record[row_idx]));\n\n\n", "file_path": "src/cli/src/common/hex_dump.rs", "rank": 58, "score": 181706.32349801995 }, { "content": "#[cfg(unix)]\n\nfn make_executable(file: &mut File) -> Result<(), IoError> {\n\n use std::os::unix::fs::PermissionsExt;\n\n\n\n // Add u+rwx mode to the existing file permissions, leaving others unchanged\n\n let mut permissions = file.metadata()?.permissions();\n\n let mut mode = permissions.mode();\n\n mode |= 0o700;\n\n permissions.set_mode(mode);\n\n\n\n file.set_permissions(permissions)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/cli/src/install/mod.rs", "rank": 59, "score": 181150.82924778678 }, { "content": "fn default_index_max_interval_bytes() -> Size {\n\n SPU_LOG_INDEX_MAX_INTERVAL_BYTES\n\n}\n\n\n", "file_path": "src/storage/src/config.rs", "rank": 60, "score": 180627.58404179462 }, { "content": "pub fn main_loop(opt: SpuOpt) {\n\n use std::time::Duration;\n\n\n\n use fluvio_future::task::run_block_on;\n\n use fluvio_future::timer::sleep;\n\n // parse configuration (program exits on error)\n\n let (spu_config, tls_acceptor_option) = opt.process_spu_cli_or_exit();\n\n\n\n println!(\"starting spu server (id:{})\", spu_config.id);\n\n\n\n run_block_on(async move {\n\n let (_ctx, internal_server, public_server) =\n\n create_services(spu_config.clone(), true, true);\n\n\n\n let _public_shutdown = internal_server.unwrap().run();\n\n let _private_shutdown = public_server.unwrap().run();\n\n\n\n if let Some(tls_config) = tls_acceptor_option {\n\n proxy::start_proxy(spu_config, tls_config).await;\n\n }\n\n\n\n println!(\"SPU Version: {} started successfully\", VERSION);\n\n\n\n // infinite loop\n\n loop {\n\n sleep(Duration::from_secs(60)).await;\n\n }\n\n });\n\n}\n\n\n", "file_path": "src/spu/src/start.rs", "rank": 61, "score": 179858.67361700776 }, { "content": "struct SpuSocket {\n\n config: ClientConfig,\n\n socket: SharedAllMultiplexerSocket,\n\n versions: Versions,\n\n}\n\n\n\nimpl SpuSocket {\n\n async fn create_serial_socket(&mut self) -> VersionedSerialSocket {\n\n VersionedSerialSocket::new(\n\n self.socket.clone(),\n\n self.config.clone(),\n\n self.versions.clone(),\n\n )\n\n }\n\n\n\n async fn create_stream<R: Request>(\n\n &mut self,\n\n request: R,\n\n ) -> Result<AsyncResponse<R>, FluvioError> {\n\n let req_msg = RequestMessage::new_request(request);\n", "file_path": "src/client/src/spu/spu_pool.rs", "rank": 62, "score": 178934.71807611093 }, { "content": "pub trait SpuMd<C: MetadataItem> {\n\n fn quick<J>(spu: (J, i32, bool, Option<String>)) -> SpuMetadata<C>\n\n where\n\n J: Into<String>;\n\n}\n\n\n\nimpl<C: MetadataItem> SpuMd<C> for SpuMetadata<C> {\n\n fn quick<J>(spu: (J, i32, bool, Option<String>)) -> SpuMetadata<C>\n\n where\n\n J: Into<String>,\n\n {\n\n let mut spec = SpuSpec::default();\n\n spec.id = spu.1;\n\n spec.rack = spu.3;\n\n\n\n let mut status = SpuStatus::default();\n\n if spu.2 {\n\n status.set_online();\n\n }\n\n\n\n SpuMetadata::new(spu.0.into(), spec, status)\n\n }\n\n}\n\n\n", "file_path": "src/controlplane-metadata/src/spu/store.rs", "rank": 63, "score": 178159.63147238822 }, { "content": "//\n\n/// Validate assigned topic spec parameters and update topic status\n\n/// * error is passed to the topic reason.\n\n///\n\npub fn validate_assigned_topic_parameters(partition_map: &PartitionMaps) -> TopicNextState {\n\n if let Err(err) = partition_map.valid_partition_map() {\n\n TopicStatus::next_resolution_invalid_config(&err.to_string()).into()\n\n } else {\n\n TopicStatus::next_resolution_pending().into()\n\n }\n\n}\n\n\n", "file_path": "src/sc/src/controllers/topics/policy.rs", "rank": 64, "score": 177162.63293610784 }, { "content": "pub fn cert_dir() -> PathBuf {\n\n std::env::current_dir().unwrap().join(\"tls\").join(\"certs\")\n\n}\n\n\n\npub struct Cert {\n\n pub ca: PathBuf,\n\n pub cert: PathBuf,\n\n pub key: PathBuf,\n\n}\n\n\n\nimpl Cert {\n\n pub fn load_client(client_user: &str) -> Self {\n\n let cert_dir = cert_dir();\n\n Cert {\n\n ca: cert_dir.join(\"ca.crt\"),\n\n cert: cert_dir.join(format!(\"client-{}.crt\", client_user)),\n\n key: cert_dir.join(format!(\"client-{}.key\", client_user)),\n\n }\n\n }\n\n\n\n pub fn load_server() -> Self {\n\n let cert_dir = cert_dir();\n\n Cert {\n\n ca: cert_dir.join(\"ca.crt\"),\n\n cert: cert_dir.join(\"server.crt\"),\n\n key: cert_dir.join(\"server.key\"),\n\n }\n\n }\n\n}\n", "file_path": "tests/runner/src/tls.rs", "rank": 65, "score": 175548.91157602335 }, { "content": "fn process_completions_cmd(shell: CompletionShell) -> Result<String, CliError> {\n\n let mut app: structopt::clap::App = Root::clap();\n\n match shell {\n\n CompletionShell::Bash(opt) => {\n\n app.gen_completions_to(opt.name, Shell::Bash, &mut std::io::stdout());\n\n }\n\n // CompletionShell::Zsh(opt) => {\n\n // app.gen_completions_to(opt.name, Shell::Zsh, &mut std::io::stdout());\n\n // }\n\n CompletionShell::Fish(opt) => {\n\n app.gen_completions_to(opt.name, Shell::Fish, &mut std::io::stdout());\n\n }\n\n }\n\n Ok(\"\".to_string())\n\n}\n\n\n", "file_path": "src/cli/src/root_cli.rs", "rank": 66, "score": 175280.9543787089 }, { "content": "/// convert SpuGroup to Statefulset\n\npub fn convert_cluster_to_statefulset(\n\n group_spec: &K8SpuGroupSpec,\n\n metadata: &ObjectMeta,\n\n group_name: &str,\n\n group_svc_name: String,\n\n namespace: &str,\n\n tls: Option<&TlsConfig>,\n\n) -> InputK8Obj<StatefulSetSpec> {\n\n let statefulset_name = format!(\"flv-spg-{}\", group_name);\n\n let spec = generate_stateful(group_spec, group_name, group_svc_name, namespace, tls);\n\n let owner_ref = metadata.make_owner_reference::<K8SpuGroupSpec>();\n\n\n\n InputK8Obj {\n\n api_version: StatefulSetSpec::api_version(),\n\n kind: StatefulSetSpec::kind(),\n\n metadata: InputObjectMeta {\n\n name: statefulset_name,\n\n namespace: metadata.namespace().to_string(),\n\n owner_references: vec![owner_ref],\n\n ..Default::default()\n\n },\n\n spec,\n\n ..Default::default()\n\n }\n\n}\n\n\n", "file_path": "src/sc/src/k8/operator/conversion.rs", "rank": 67, "score": 174893.4018050201 }, { "content": "pub fn run_k8_operators(\n\n namespace: String,\n\n k8_client: SharedK8Client,\n\n ctx: SharedContext,\n\n tls: Option<TlsConfig>,\n\n) {\n\n SpgOperator::new(k8_client.clone(), namespace.clone(), ctx.clone(), tls).run();\n\n\n\n let svc_ctx: StoreContext<SpuServicespec> = StoreContext::new();\n\n\n\n K8ClusterStateDispatcher::<SpuServicespec, _>::start(namespace, k8_client, svc_ctx.clone());\n\n SpuServiceController::start(ctx, svc_ctx);\n\n}\n", "file_path": "src/sc/src/k8/operator/mod.rs", "rank": 68, "score": 174882.34195276757 }, { "content": "pub fn main_k8_loop(opt: ScOpt) {\n\n use std::time::Duration;\n\n\n\n use fluvio_future::task::run_block_on;\n\n use fluvio_future::timer::sleep;\n\n\n\n use crate::init::start_main_loop;\n\n // parse configuration (program exits on error)\n\n let ((sc_config, auth_policy), k8_config, tls_option) = opt.parse_cli_or_exit();\n\n\n\n println!(\"starting sc server with k8: {}\", VERSION);\n\n\n\n run_block_on(async move {\n\n // init k8 service\n\n let k8_client = new_shared(k8_config).expect(\"problem creating k8 client\");\n\n let namespace = sc_config.namespace.clone();\n\n let ctx = start_main_loop((sc_config.clone(), auth_policy), k8_client.clone()).await;\n\n\n\n run_k8_operators(\n\n namespace.clone(),\n", "file_path": "src/sc/src/k8/mod.rs", "rank": 69, "score": 174038.35005651397 }, { "content": "pub fn install_println<S: AsRef<str>>(string: S) {\n\n if std::env::var(\"FLUVIO_BOOTSTRAP\").is_ok() {\n\n println!(\"\\x1B[1;34mfluvio:\\x1B[0m {}\", string.as_ref());\n\n } else {\n\n println!(\"{}\", string.as_ref());\n\n }\n\n}\n", "file_path": "src/cli/src/install/mod.rs", "rank": 70, "score": 173963.57153253473 }, { "content": "pub fn install_sys(opt: InstallCommand) -> Result<(), CliError> {\n\n let mut builder = ClusterInstaller::new().with_namespace(opt.k8_config.namespace);\n\n\n\n match opt.k8_config.chart_location {\n\n // If a chart location is given, use it\n\n Some(chart_location) => {\n\n builder = builder.with_local_chart(chart_location);\n\n }\n\n // If we're in develop mode (but no explicit chart location), use local path\n\n None if opt.develop => {\n\n builder = builder.with_local_chart(\"./k8-util/helm\");\n\n }\n\n _ => (),\n\n }\n\n let installer = builder.build()?;\n\n installer._install_sys()?;\n\n println!(\"fluvio sys chart has been installed\");\n\n Ok(())\n\n}\n", "file_path": "src/cli/src/cluster/install/k8.rs", "rank": 71, "score": 172378.59851162424 }, { "content": "pub fn process_delete_cluster<O>(\n\n _out: std::sync::Arc<O>,\n\n opt: DeleteClusterOpt,\n\n) -> Result<String, CliError>\n\nwhere\n\n O: Terminal,\n\n{\n\n let cluster_name = opt.cluster_name;\n\n\n\n let mut config_file = match ConfigFile::load(None) {\n\n Ok(config_file) => config_file,\n\n Err(e) => {\n\n println!(\"No config can be found: {}\", e);\n\n return Ok(\"\".to_string());\n\n }\n\n };\n\n\n\n let config = config_file.mut_config();\n\n\n\n // Check if the named cluster exists\n", "file_path": "src/cli/src/profile/mod.rs", "rank": 72, "score": 172191.84016905611 }, { "content": "/// create batches with produce and records count\n\npub fn create_batch_with_producer(producer: i64, records: u16) -> DefaultBatch {\n\n let mut batches = DefaultBatch::default();\n\n let header = batches.get_mut_header();\n\n header.magic = 2;\n\n header.producer_id = producer;\n\n header.producer_epoch = -1;\n\n\n\n for _ in 0..records {\n\n let mut record = DefaultRecord::default();\n\n let bytes: Vec<u8> = vec![10, 20];\n\n record.value = bytes.into();\n\n batches.add_record(record);\n\n }\n\n\n\n batches\n\n}\n\n\n", "file_path": "src/storage/src/fixture.rs", "rank": 73, "score": 171912.21213032387 }, { "content": "/// get path to the binary\n\npub fn get_binary(bin_name: &str) -> Result<Command, IoError> {\n\n let current_exe =\n\n std::env::current_exe().expect(\"Failed to get the path of the integration test binary\");\n\n let mut bin_dir = current_exe\n\n .parent()\n\n .expect(\"failed to get parent\")\n\n .to_owned();\n\n bin_dir.push(bin_name);\n\n bin_dir.set_extension(std::env::consts::EXE_EXTENSION);\n\n\n\n debug!(\"try to get binary: {:#?}\", bin_dir);\n\n if !bin_dir.exists() {\n\n Err(IoError::new(\n\n ErrorKind::NotFound,\n\n format!(\"{} not founded in: {:#?}\", bin_name, bin_dir),\n\n ))\n\n } else {\n\n Ok(Command::new(bin_dir.into_os_string()))\n\n }\n\n}\n\n\n\nuse std::fs::File;\n\nuse std::process::Stdio;\n\n\n", "file_path": "src/utils/src/bin.rs", "rank": 74, "score": 171311.34188880972 }, { "content": "/// create sample batches with variable number of records\n\nfn create_batch(records: u16) -> DefaultBatch {\n\n let mut batches = DefaultBatch::default();\n\n let header = batches.get_mut_header();\n\n header.magic = 2;\n\n header.producer_id = 20;\n\n header.producer_epoch = -1;\n\n\n\n for i in 0..records {\n\n let msg = format!(\"record {}\", i);\n\n let record: DefaultRecord = msg.into();\n\n batches.add_record(record);\n\n }\n\n\n\n batches\n\n}\n\n\n\n// create new replica and add two batches\n\nasync fn setup_replica() -> Result<FileReplica, StorageError> {\n\n let option = default_option();\n\n\n", "file_path": "src/storage/tests/replica_test.rs", "rank": 75, "score": 169361.1765316037 }, { "content": "#[allow(unused)]\n\npub fn get_binary(bin_name: &str) -> Result<Command, IoError> {\n\n let current_exe =\n\n std::env::current_exe().expect(\"Failed to get the path of the integration test binary\");\n\n let mut bin_dir = current_exe\n\n .parent()\n\n .expect(\"failed to get parent\")\n\n .to_owned();\n\n bin_dir.push(bin_name);\n\n bin_dir.set_extension(std::env::consts::EXE_EXTENSION);\n\n\n\n debug!(\"try to get binary: {:#?}\", bin_dir);\n\n if !bin_dir.exists() {\n\n Err(IoError::new(\n\n ErrorKind::NotFound,\n\n format!(\"{} not founded in: {:#?}\", bin_name, bin_dir),\n\n ))\n\n } else {\n\n Ok(Command::new(bin_dir.into_os_string()))\n\n }\n\n}\n\n\n\nmod cmd_util {\n\n\n", "file_path": "src/cli/src/cluster/util.rs", "rank": 76, "score": 168735.90252817783 }, { "content": "pub fn create_partition_name(topic_name: &str, idx: &i32) -> String {\n\n format!(\"{}-{}\", topic_name, idx)\n\n}\n", "file_path": "src/dataplane-protocol/src/common.rs", "rank": 77, "score": 168686.799115767 }, { "content": "/// Encode all partitions for a topic in Kf format.\n\npub fn topic_partitions_to_kf_partitions(\n\n partitions: &PartitionLocalStore,\n\n topic: &String,\n\n) -> Vec<MetadataResponsePartition> {\n\n let mut kf_partitions = vec![];\n\n\n\n for (idx, partition) in partitions.topic_partitions(topic).iter().enumerate() {\n\n kf_partitions.push(MetadataResponsePartition {\n\n error_code: KfErrorCode::None,\n\n partition_index: idx as i32,\n\n leader_id: partition.spec.leader,\n\n leader_epoch: 0,\n\n replica_nodes: partition.spec.replicas.clone(),\n\n isr_nodes: partition.status.live_replicas().clone(),\n\n offline_replicas: partition.status.offline_replicas(),\n\n })\n\n }\n\n\n\n kf_partitions\n\n}\n", "file_path": "src/sc/src/services/public_api/metadata/fetch.rs", "rank": 78, "score": 166012.21578300878 }, { "content": "fn fluvio_bin_dir() -> Result<PathBuf, CliError> {\n\n let home =\n\n dirs::home_dir().ok_or_else(|| IoError::new(ErrorKind::NotFound, \"Homedir not found\"))?;\n\n Ok(home.join(\".fluvio/bin/\"))\n\n}\n\n\n\n/// Fetches the latest version of the package with the given ID\n\n#[instrument(\n\n skip(agent, target, id),\n\n fields(%target, id = %id.display())\n\n)]\n\nasync fn fetch_latest_version<T>(\n\n agent: &HttpAgent,\n\n id: &PackageId<T>,\n\n target: Target,\n\n) -> Result<Version, CliError> {\n\n let request = agent.request_package(id)?;\n\n debug!(\n\n url = %request.url(),\n\n \"Requesting package manifest:\",\n", "file_path": "src/cli/src/install/mod.rs", "rank": 79, "score": 163206.60787920497 }, { "content": "/// Getting server hostname from K8 context\n\nfn check_cluster_server_host() -> Result<StatusCheck, CheckError> {\n\n let config = K8Config::load()?;\n\n let context = match config {\n\n K8Config::Pod(_) => {\n\n return Ok(StatusCheck::Working(\n\n \"Pod config found, ignoring the check\".to_string(),\n\n ))\n\n }\n\n K8Config::KubeConfig(context) => context,\n\n };\n\n\n\n let cluster_context = context\n\n .config\n\n .current_cluster()\n\n .ok_or(CheckError::NoActiveKubernetesContext)?;\n\n let server_url = cluster_context.cluster.server.to_owned();\n\n let url =\n\n Url::parse(&server_url).map_err(|source| CheckError::BadKubernetesServerUrl { source })?;\n\n let host = url\n\n .host()\n", "file_path": "src/cluster/src/check.rs", "rank": 80, "score": 163117.31866026943 }, { "content": "struct SimplePolicy {}\n\n\n\nimpl SimplePolicy {\n\n fn new() -> Self {\n\n SimplePolicy {}\n\n }\n\n}\n\n\n\nimpl ElectionPolicy for SimplePolicy {\n\n fn potential_leader_score(\n\n &self,\n\n replica_status: &ReplicaStatus,\n\n leader: &ReplicaStatus,\n\n ) -> ElectionScoring {\n\n let lag = leader.leo - replica_status.leo;\n\n if lag < 4 {\n\n ElectionScoring::Score(lag as u16)\n\n } else {\n\n ElectionScoring::NotSuitable\n\n }\n", "file_path": "src/sc/src/controllers/partitions/reducer.rs", "rank": 81, "score": 161694.040749852 }, { "content": "pub fn display_current_profile<O>(out: std::sync::Arc<O>)\n\nwhere\n\n O: Terminal,\n\n{\n\n match ConfigFile::load(None) {\n\n Ok(config_file) => {\n\n if let Some(profile) = config_file.config().current_profile_name() {\n\n t_println!(out, \"{}\", profile);\n\n } else {\n\n t_println!(out, \"no current profile set\");\n\n }\n\n }\n\n Err(_) => t_println!(out, \"no profile can be founded\"),\n\n }\n\n}\n", "file_path": "src/cli/src/profile/context.rs", "rank": 82, "score": 160275.68229680642 }, { "content": "#[allow(unused)]\n\npub fn open_log(prefix: &str) -> (File, File) {\n\n let output = File::create(format!(\"/tmp/flv_{}.out\", prefix)).expect(\"log file\");\n\n let error = File::create(format!(\"/tmp/flv_{}.log\", prefix)).expect(\"err file\");\n\n\n\n (output, error)\n\n}\n\n\n", "file_path": "src/utils/src/bin.rs", "rank": 83, "score": 160057.91368619585 }, { "content": "type FileReplicaContext = GlobalContext<FileReplica>;\n\n\n\nconst VERSION: &str = env!(\"CARGO_PKG_VERSION\");\n\n\n", "file_path": "src/spu/src/start.rs", "rank": 84, "score": 159683.35318296106 }, { "content": "/// handle watch request by spawning watch controller for each store\n\npub fn handle_watch_request<T, AC>(\n\n request: RequestMessage<WatchRequest>,\n\n auth_ctx: &AuthServiceContext<AC>,\n\n sink: InnerExclusiveFlvSink<T>,\n\n end_event: Arc<Event>,\n\n) where\n\n T: AsyncWrite + AsyncRead + Unpin + Send + ZeroCopyWrite + 'static,\n\n{\n\n debug!(\"handling watch request\");\n\n let (header, req) = request.get_header_request();\n\n\n\n match req {\n\n WatchRequest::Topic(_) => unimplemented!(),\n\n WatchRequest::Spu(epoch) => WatchController::<T, SpuSpec>::update(\n\n epoch,\n\n sink,\n\n end_event,\n\n auth_ctx.global_ctx.spus().clone(),\n\n header,\n\n ),\n", "file_path": "src/sc/src/services/public_api/watch.rs", "rank": 85, "score": 158668.22438208546 }, { "content": "/// Customize System Test\n\npub trait SpuTest: Sized {\n\n type ResponseFuture: Send + Future<Output = Result<(), FlvSocketError>>;\n\n\n\n /// environment configuration\n\n fn env_configuration(&self) -> TestGenerator;\n\n\n\n /// number of followers\n\n fn followers(&self) -> usize;\n\n\n\n /// replicas. by default, it's empty\n\n fn replicas(&self) -> Vec<ReplicaKey> {\n\n vec![]\n\n }\n\n\n\n /// main entry point\n\n fn main_test(&self, runner: Arc<SpuTestRunner<Self>>) -> Self::ResponseFuture;\n\n}\n", "file_path": "src/spu/src/tests/fixture/mod.rs", "rank": 86, "score": 158509.53241412842 }, { "content": "/// Customize System Test\n\npub trait ScTest: Sized {\n\n type ResponseFuture: Send + Future<Output = Result<(), FlvSocketError>>;\n\n\n\n /// environment configuration\n\n fn env_configuration(&self) -> TestGenerator;\n\n\n\n fn topics(&self) -> Vec<(String, Vec<Vec<SpuId>>)>;\n\n\n\n /// main entry point\n\n fn main_test(&self, runner: Arc<ScTestRunner<Self>>) -> Self::ResponseFuture;\n\n}\n", "file_path": "src/sc/src/tests/fixture/mod.rs", "rank": 87, "score": 158502.15724790248 }, { "content": "#[async_trait]\n\npub trait ReplicaLeader: Send + Sync {\n\n type OffsetPartitionResponse: PartitionOffset;\n\n type Client: Client;\n\n\n\n fn config(&self) -> &ReplicaLeaderConfig;\n\n\n\n \n\n fn topic(&self) -> &str {\n\n &self.config().topic()\n\n }\n\n\n\n fn partition(&self) -> i32 {\n\n self.config().partition()\n\n }\n\n\n\n fn addr(&self) -> &str;\n\n\n\n fn mut_client(&mut self) -> &mut Self::Client;\n\n\n\n // fetch offsets for\n", "file_path": "src/client/src/replica/leader.rs", "rank": 88, "score": 157518.03382083654 }, { "content": "pub fn read_bytes_from_file<P>(path: P) -> Result<Vec<u8>, io::Error>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n let file_path = path.as_ref();\n\n info!(\"test file: {}\", file_path.display());\n\n let mut f = File::open(file_path)?;\n\n let mut buffer = Vec::new();\n\n f.read_to_end(&mut buffer)?;\n\n Ok(buffer)\n\n}\n\n\n", "file_path": "src/storage/src/fixture.rs", "rank": 89, "score": 157458.31501066964 }, { "content": "fn print_sc_logs() {\n\n use std::process::Command;\n\n\n\n let _ = Command::new(\"kubectl\")\n\n .arg(\"logs\")\n\n .arg(\"flv-sc\")\n\n .print()\n\n .inherit();\n\n\n\n let _ = Command::new(\"kubectl\")\n\n .arg(\"get\")\n\n .arg(\"spu\")\n\n .print()\n\n .inherit();\n\n}\n\n*/\n", "file_path": "tests/runner/src/environment/k8.rs", "rank": 90, "score": 157002.22130866878 }, { "content": "struct SpuOnlineStatus {\n\n online: bool,\n\n // last time status was known\n\n time: Instant,\n\n}\n\n\n\nimpl SpuOnlineStatus {\n\n fn new() -> Self {\n\n Self {\n\n online: false,\n\n time: Instant::now(),\n\n }\n\n }\n\n}\n\n\n\n/// Keep track of SPU status\n\n/// if SPU has not send heart beat within a period, it is considered down\n\npub struct SpuController {\n\n spus: StoreContext<SpuSpec>,\n\n health_receiver: Receiver<SpuAction>,\n", "file_path": "src/sc/src/controllers/spus/controller.rs", "rank": 91, "score": 156979.36336869633 }, { "content": " pub trait Terminal: Sized {\n\n fn print(&self, msg: &str);\n\n fn println(&self, msg: &str);\n\n\n\n fn render_list<T>(self: Arc<Self>, list: &T, mode: OutputType) -> Result<(), CliError>\n\n where\n\n T: TableOutputHandler + Serialize,\n\n {\n\n if mode.is_table() {\n\n let render = TableRenderer::new(self);\n\n render.render(list, false);\n\n } else {\n\n let render = SerdeRenderer::new(self);\n\n render.render(&list, mode.into())?;\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n fn render_table<T: TableOutputHandler>(self: Arc<Self>, val: &T, indent: bool) {\n", "file_path": "src/cli/src/output/mod.rs", "rank": 92, "score": 154231.18898023086 }, { "content": "fn default_base_dir() -> PathBuf {\n\n Path::new(\"/tmp\").to_path_buf()\n\n}\n\n\n", "file_path": "src/storage/src/config.rs", "rank": 93, "score": 152434.6667583563 }, { "content": "fn default_option() -> ConfigOption {\n\n ConfigOption {\n\n segment_max_bytes: 10000,\n\n base_dir: temp_dir().join(TEST_REP_DIR),\n\n index_max_interval_bytes: 1000,\n\n index_max_bytes: 1000,\n\n }\n\n}\n\n\n", "file_path": "src/storage/tests/replica_test.rs", "rank": 94, "score": 152018.8977997524 }, { "content": "#[derive(Debug)]\n\nstruct ScopeBindings(HashMap<String, Vec<String>>);\n\n\n\nimpl ScopeBindings {\n\n pub fn load(scope_binding_file_path: &Path) -> Result<Self, IoError> {\n\n let file = std::fs::read_to_string(scope_binding_file_path)?;\n\n let scope_bindings = Self(serde_json::from_str(&file)?);\n\n debug!(\"scope bindings loaded {:?}\", scope_bindings);\n\n Ok(scope_bindings)\n\n }\n\n pub fn get_scopes(&self, principal: &str) -> Vec<String> {\n\n trace!(\"getting scopes for principal {:?}\", principal);\n\n if let Some(scopes) = self.0.get(principal) {\n\n trace!(\"scopes found for principal {:?}: {:?}\", principal, scopes);\n\n scopes.clone()\n\n } else {\n\n trace!(\"scopes not found for principal {:?}\", principal);\n\n Vec::new()\n\n }\n\n }\n\n}\n", "file_path": "src/auth/src/x509/authenticator.rs", "rank": 95, "score": 149360.81397812214 }, { "content": "#[allow(clippy::needless_range_loop)]\n\npub fn validate_message(iter: u16, offset: i64, topic: &str, option: &TestOption, data: &[u8]) {\n\n let prefix_string = generate_pre_fix(topic, offset);\n\n let prefix = prefix_string.as_bytes().to_vec();\n\n let prefix_len = prefix.len();\n\n\n\n let message_len = option.produce.record_size + prefix_len;\n\n assert_eq!(\n\n data.len(),\n\n message_len,\n\n \"message should be: {}\",\n\n message_len\n\n );\n\n\n\n // check prefix\n\n for i in 0..prefix_len {\n\n assert!(\n\n data[i] == prefix[i],\n\n \"prefix failed, iter: {}, index: {}, data: {}, prefix: {}, data len: {}, offset: {}, topic: {}\",\n\n iter,\n\n i,\n", "file_path": "tests/runner/src/tests/smoke/message.rs", "rank": 96, "score": 144540.9149003571 }, { "content": "/// Converts a byte to string character\n\nfn byte_to_string(byte: &u8) -> String {\n\n if 0x20 <= *byte && *byte < 0x7f {\n\n format!(\"{}\", *byte as char)\n\n } else if *byte == 0xa {\n\n \".\".to_owned()\n\n } else {\n\n \" \".to_owned()\n\n }\n\n}\n\n\n", "file_path": "src/cli/src/common/hex_dump.rs", "rank": 97, "score": 142009.3609950075 }, { "content": "fn test_repl_id() -> ReplicaKey {\n\n ReplicaKey::new(\"topic1\", 0)\n\n}\n\n\n", "file_path": "src/spu/src/tests/suites/test_offsets.rs", "rank": 98, "score": 141545.29065710047 }, { "content": "fn test_repl_id() -> ReplicaKey {\n\n ReplicaKey::new(\"topic1\", 0)\n\n}\n\n\n", "file_path": "src/spu/src/tests/suites/test_fetch.rs", "rank": 99, "score": 141545.29065710047 } ]
Rust
exe-common/src/network/hermes.rs
nahern/rust-cardano
03fc923641808361273f1645eef221fdf908f5cf
use cardano::{block::{block, Block, BlockHeader, BlockDate, RawBlock, HeaderHash}, tx::{TxAux}}; use cardano::hash::{HASH_SIZE_256}; use storage; use std::io::Write; use std::time::{SystemTime, Duration}; use std::thread; use futures::{Future, Stream}; use hyper::Client; use tokio_core::reactor::Core; use network::{Result, Error}; use network::api::{Api, BlockRef}; static NETWORK_REFRESH_FREQUENCY: Duration = Duration::from_secs(60 * 10); pub struct HermesEndPoint { pub url: String, pub blockchain: String, core: Core } impl HermesEndPoint { pub fn new(url: String, blockchain: String) -> Self { HermesEndPoint { url, blockchain, core: Core::new().unwrap() } } pub fn uri(& mut self, path: &str) -> String { format!("{}/{}", self.url, path) } } impl Api for HermesEndPoint { fn get_tip(&mut self) -> Result<BlockHeader> { let uri = self.uri("tip"); info!("querying uri: {}", uri); let mut err = None; let mut bh_bytes = Vec::with_capacity(4096); { let client = Client::new(&self.core.handle()); let work = client.get(uri.parse().unwrap()).from_err::<Error>() .and_then(|res| { if !res.status().is_success() { err = Some(Error::HttpError(uri, res.status().clone())); }; res.body().from_err::<Error>().for_each(|chunk| { bh_bytes.write_all(&chunk).map_err(From::from) }) }); let now = SystemTime::now(); self.core.run(work)?; let time_elapsed = now.elapsed().unwrap(); info!("Downloaded TIP in {}sec", time_elapsed.as_secs()); } if let Some(err) = err { return Err(err) }; let bh_raw = block::RawBlockHeader::from_dat(bh_bytes); Ok(bh_raw.decode()?) } fn wait_for_new_tip(&mut self, prev_tip: &HeaderHash) -> Result<BlockHeader> { loop { let new_tip = self.get_tip()?; if new_tip.compute_hash() != *prev_tip { return Ok(new_tip) } info!("Sleeping for {:?}", NETWORK_REFRESH_FREQUENCY); thread::sleep(NETWORK_REFRESH_FREQUENCY); } } fn get_block(&mut self, hash: &HeaderHash) -> Result<RawBlock> { let uri = self.uri(&format!("block/{}", hash)); info!("querying uri: {}", uri); let client = Client::new(&self.core.handle()); let mut block_raw = vec!(); let mut err = None; { let work = client.get(uri.parse().unwrap()).and_then(|res| { if !res.status().is_success() { err = Some(Error::HttpError(uri, res.status().clone())); }; res.body().for_each(|chunk| { block_raw.append(&mut chunk.to_vec()); Ok(()) }) }); let now = SystemTime::now(); self.core.run(work)?; let time_elapsed = now.elapsed().unwrap(); info!("Downloaded block in {}sec", time_elapsed.as_secs()); } if let Some(err) = err { return Err(err) }; Ok(RawBlock::from_dat(block_raw)) } fn get_blocks<F>( &mut self , from: &BlockRef , inclusive: bool , to: &BlockRef , got_block: &mut F ) -> Result<()> where F: FnMut(&HeaderHash, &Block, &RawBlock) -> () { let mut inclusive = inclusive; let mut from = from.clone(); loop { if let BlockDate::Normal(d) = from.date { if d.slotid == 21599 && !inclusive { from = BlockRef { hash: HeaderHash::from([0;HASH_SIZE_256]), parent: from.hash.clone(), date: BlockDate::Genesis(d.epoch + 1) }; inclusive = true; }; }; let epoch = from.date.get_epochid(); if !inclusive && to.hash == from.hash { break } if inclusive && from.date.is_genesis() && epoch < to.date.get_epochid() { let mut tmppack = vec!(); let mut err = None; { let uri = self.uri(&format!("epoch/{}", epoch)); info!("querying uri: {}", uri); let client = Client::new(&self.core.handle()); let work = client.get(uri.parse().unwrap()).and_then(|res| { if !res.status().is_success() { err = Some(Error::HttpError(uri, res.status().clone())); }; res.body().for_each(|chunk| { tmppack.append(&mut chunk.to_vec()); Ok(()) }) }); let now = SystemTime::now(); self.core.run(work)?; let time_elapsed = now.elapsed().unwrap(); info!("Downloaded EPOCH in {}sec", time_elapsed.as_secs()); } if let Some(err) = err { return Err(err) }; let mut packfile = storage::containers::packfile::Reader::from(&tmppack[..]); while let Some(data) = packfile.get_next() { let block_raw = block::RawBlock(data); let block = block_raw.decode()?; let hdr = block.get_header(); assert!(hdr.get_blockdate().get_epochid() == epoch); if from.date <= hdr.get_blockdate() { got_block(&hdr.compute_hash(), &block, &block_raw); } from = BlockRef { hash: hdr.compute_hash(), parent: hdr.get_previous_header(), date: hdr.get_blockdate() }; inclusive = false; } } else { let mut blocks = vec![]; let mut to = to.hash.clone(); loop { let block_raw = self.get_block(&to)?; let block = block_raw.decode()?; let hdr = block.get_header(); assert!(hdr.get_blockdate() >= from.date); let prev = hdr.get_previous_header(); blocks.push((hdr.compute_hash(), block, block_raw)); if (inclusive && prev == from.parent) || (!inclusive && prev == from.hash) { break } to = prev; } while let Some((hash, block, block_raw)) = blocks.pop() { got_block(&hash, &block, &block_raw); } break; } } Ok(()) } fn send_transaction( &mut self, txaux: TxAux) -> Result<bool> { Ok(false) } }
use cardano::{block::{block, Block, BlockHeader, BlockDate, RawBlock, HeaderHash}, tx::{TxAux}}; use cardano::hash::{HASH_SIZE_256}; use storage; use std::io::Write; use std::time::{SystemTime, Duration}; use std::thread; use futures::{Future, Stream}; use hyper::Client; use tokio_core::reactor::Core; use network::{Result, Error}; use network::api::{Api, BlockRef}; static NETWORK_REFRESH_FREQUENCY: Duration = Duration::from_secs(60 * 10); pub struct HermesEndPoint { pub url: String, pub blockchain: String, core: Core } impl HermesEndPoint { pub fn new(url: String, blockchain: String) -> Self { HermesEndPoint { url, blockchain, core: Core::new().unwrap() } } pub fn uri(& mut self, path: &str) -> String { format!("{}/{}", self.url, path) } } impl Api for HermesEndPoint { fn get_tip(&mut self) -> Result<BlockHeader> { let uri = self.uri("tip"); info!("querying uri: {}", uri); let mut err = None; let mut bh_bytes = Vec::with_capacity(4096); { let client = Client::new(&self.core.handle()); let work = client.get(uri.parse().unwrap()).from_err::<Error>() .and_then(|res| { if !res.status().is_success() { err = Some(Error::HttpError(uri, res.status().clone())); }; res.body().from_err::<Error>().for_each(|chunk| { bh_bytes.write_all(&chunk).map_err(From::from) }) }); let now = SystemTime::now(); self.core.run(work)?; let time_elapsed = now.elapsed().unwrap(); info!("Downloaded TIP in {}sec", time_elapsed.as_secs()); } if let Some(err) = err { return Err(err) }; let bh_raw = block::RawBlockHeader::from_dat(bh_bytes); Ok(bh_raw.decode()?) } fn wait_for_new_tip(&mut self, prev_tip: &HeaderHash) -> Result<BlockHeader> { loop { let new_tip = self.get_tip()?; if new_tip.compute_hash() != *prev_tip { return Ok(new_tip) } info!("Sleeping for {:?}", NETWORK_REFRESH_FREQUENCY); thread::sleep(NETWORK_REFRESH_FREQUENCY); } } fn get_block(&mut self, hash: &HeaderHash) -> Result<RawBlock> { let uri = self.uri(&format!("block/{}", hash)); info!("querying uri: {}", uri); let client = Client::new(&self.core.handle()); let mut block_raw = vec!(); let mut err = None; { let work = client.get(uri.parse().unwrap()).and_then(|res| { if !res.status().is_success() { err = Some(Error::HttpError(uri, res.status().clone())); }; res.body().for_each(|chunk| { block_raw.append(&mut chunk.to_vec()); Ok(()) }) }); let now = SystemTime::now(); self.core.run(work)?; let time_elapsed = now.elapsed().unwrap(); info!("Downloaded block in {}sec", time_elapsed.as_secs()); } if let Some(err) = err { return Err(err) }; Ok(RawBlock::from_dat(block_raw)) } fn get_blocks<F>( &mut self , from: &BlockRef , inclusive: bool , to: &BlockRef , got_block: &mut F ) -> Result<()> where F: FnMut(&HeaderHash, &Block, &RawBlock) -> () { let mut inclusive = inclusive; let mut from = from.clone(); loop { if let BlockDate::Normal(d) = from.date { if d.slotid == 21599 && !inclusive { from = BlockRef { hash: HeaderHash::from([0;HASH_SIZE_256]), parent: from.hash.clone(), date: BlockDate::Genesis(d.epoch + 1) }; inclusive = true; }; }; let epoch = from.date.get_epochid(); if !inclusive && to.hash == from.hash { break } if inclusive && from.date.is_genesis() && epoch < to.date.get_epochid() { let mut tmppack = vec!(); let mut err = None; { let uri = self.uri(&format!("epoch/{}", epoch)); info!("querying uri: {}", uri); let client = Client::new(&self.core.handle()); let work = client.get(uri.parse().unwrap()).and_then(|res| { if !res.status().is_success() { err = Some(Error::HttpError(uri, res.status().clone())); }; res.body().for_each(|chunk| { tmppack.append(&mut chunk.to_vec()); Ok(()) }) }); let now = SystemTime::now(); self.core.run(work)?; let time_elapsed = now.elapsed().unwrap(); info!("Downloaded EPOCH in {}sec", time_elapsed.as_secs()); } if let Some(err) = err { return Err(err) }; let mut packfile = storage::containers::packfile::Reader::from(&tmppack[..]); while let Some(data) = packfile.get_next() { let block_raw = block::RawBlock(data); let block = block_raw.decode()?; let hdr = block.get_header(); assert!(hdr.get_blockdate().get_epochid() == epoch);
from = BlockRef { hash: hdr.compute_hash(), parent: hdr.get_previous_header(), date: hdr.get_blockdate() }; inclusive = false; } } else { let mut blocks = vec![]; let mut to = to.hash.clone(); loop { let block_raw = self.get_block(&to)?; let block = block_raw.decode()?; let hdr = block.get_header(); assert!(hdr.get_blockdate() >= from.date); let prev = hdr.get_previous_header(); blocks.push((hdr.compute_hash(), block, block_raw)); if (inclusive && prev == from.parent) || (!inclusive && prev == from.hash) { break } to = prev; } while let Some((hash, block, block_raw)) = blocks.pop() { got_block(&hash, &block, &block_raw); } break; } } Ok(()) } fn send_transaction( &mut self, txaux: TxAux) -> Result<bool> { Ok(false) } }
if from.date <= hdr.get_blockdate() { got_block(&hdr.compute_hash(), &block, &block_raw); }
if_condition
[ { "content": "pub fn resolve_date_to_blockhash(storage: &Storage, tip: &BlockHash, date: &BlockDate) -> Result<Option<BlockHash>> {\n\n let epoch = date.get_epochid();\n\n match epoch_open_packref(&storage.config, epoch) {\n\n Ok(mut handle) => {\n\n let slotid = match date {\n\n BlockDate::Genesis(_) => 0,\n\n BlockDate::Normal(sid) => sid.slotid,\n\n };\n\n let r = handle.getref_at_index(slotid as u32)?;\n\n Ok(r)\n\n },\n\n Err(_) => {\n\n let tip_rblk = block_read(&storage, tip);\n\n match tip_rblk {\n\n None => return Ok(None),\n\n Some(rblk) => {\n\n let blk = rblk.decode()?;\n\n let found = block_reverse_search_from_tip(storage, &blk, |x|\n\n match x.get_header().get_blockdate().cmp(date) {\n\n Ordering::Equal => Ok(ReverseSearch::Found),\n", "file_path": "storage/src/block/iter.rs", "rank": 0, "score": 454748.1691610039 }, { "content": "pub fn dump_file(file: &mut fs::File) -> Result<(Lookup, Vec<BlockHash>)> {\n\n let lookup = Lookup::read_from_file(file)?;\n\n\n\n let mut v = Vec::new();\n\n let FanoutTotal(total) = lookup.fanout.get_total();\n\n\n\n file.seek(SeekFrom::Start(HEADER_SIZE as u64)).unwrap();\n\n for _ in 0..total {\n\n let h = file_read_hash(file);\n\n v.push(h);\n\n }\n\n Ok((lookup, v))\n\n}\n\n\n\npub struct ReaderNoLookup<R> {\n\n handle: R,\n\n}\n\n\n\nimpl ReaderNoLookup<fs::File> {\n\n pub fn init<P: AsRef<Path>>(path: P) -> Result<Self> {\n", "file_path": "storage/src/containers/indexfile.rs", "rank": 1, "score": 405472.52025529183 }, { "content": "/// Check whether an epoch pack exists on disk.\n\npub fn epoch_exists(config: &StorageConfig, epochid: cardano::block::EpochId) -> Result<bool> {\n\n match epoch_read_pack(config, epochid) {\n\n Ok(_) => Ok(true),\n\n Err(Error::StorageError(StorageError::IoError(ref err))) if err.kind() == ::std::io::ErrorKind::NotFound => Ok(false),\n\n Err(err) => Err(err)\n\n }\n\n}\n", "file_path": "storage/src/epoch.rs", "rank": 2, "score": 399954.2923208799 }, { "content": "// a block in a pack file is:\n\n// * a 32 bit size in big endian\n\n// * data of the size above\n\n// * 0 to 3 bytes of 0-alignment to make sure the next block is aligned\n\npub fn read_next_block<R: Read>(mut file: R) -> io::Result<Vec<u8>> {\n\n let mut sz_buf = [0u8;SIZE_SIZE];\n\n file.read_exact(&mut sz_buf)?;\n\n let sz = read_size(&sz_buf);\n\n // don't potentially consume all memory when reading a corrupt file\n\n assert!(sz < 20000000);\n\n let mut v : Vec<u8> = repeat(0).take(sz as usize).collect();\n\n file.read_exact(v.as_mut_slice())?;\n\n if (v.len() % 4) != 0 {\n\n let to_align = 4 - (v.len() % 4);\n\n let mut align = [0u8;4];\n\n file.read_exact(&mut align[0..to_align])?;\n\n }\n\n Ok(v)\n\n}\n\n\n", "file_path": "storage/src/containers/packfile.rs", "rank": 3, "score": 395921.0990292125 }, { "content": "pub fn get_epoch_tag(epoch: block::EpochId) -> String {\n\n format!(\"EPOCH_{}\", epoch)\n\n}\n\n\n", "file_path": "storage/src/tag.rs", "rank": 4, "score": 389409.55049487134 }, { "content": "fn block_reverse_search_from_tip<F>(storage: &Storage, first_block: &Block, find: F) -> Result<Option<Block>>\n\n where F: Fn(&Block) -> Result<ReverseSearch>\n\n{\n\n let mut current_blk = first_block.clone();\n\n loop {\n\n match find(&current_blk)? {\n\n ReverseSearch::Continue => {\n\n let blk = previous_block(&storage, &current_blk);\n\n current_blk = blk;\n\n },\n\n ReverseSearch::Found => { return Ok(Some(current_blk)) },\n\n ReverseSearch::Abort => { return Ok(None) },\n\n };\n\n }\n\n}\n\n\n", "file_path": "storage/src/block/iter.rs", "rank": 5, "score": 372183.4932974319 }, { "content": "pub fn epoch_read_pack(config: &StorageConfig, epochid: cardano::block::EpochId) -> Result<PackHash> {\n\n let mut content = Vec::new();\n\n\n\n let pack_filepath = config.get_epoch_pack_filepath(epochid);\n\n let mut file = fs::File::open(&pack_filepath)?;\n\n let _read = file.read_to_end(&mut content).unwrap();\n\n\n\n let p = String::from_utf8(content.clone()).ok().and_then(|r| hex::decode(&r).ok()).unwrap();\n\n let mut ph = [0u8; super::HASH_SIZE];\n\n ph.clone_from_slice(&p[..]);\n\n\n\n Ok(ph)\n\n}\n\n\n", "file_path": "storage/src/epoch.rs", "rank": 6, "score": 365894.7577454153 }, { "content": "pub fn epoch_read(config: &StorageConfig, epochid: cardano::block::EpochId) -> Result<(PackHash, reffile::Reader)> {\n\n let ph = epoch_read_pack(config, epochid)?;\n\n let rp = epoch_read_packref(config, epochid)?;\n\n Ok((ph, rp))\n\n}\n\n\n", "file_path": "storage/src/epoch.rs", "rank": 7, "score": 355445.3876328509 }, { "content": "fn next_until_range(packreader: &mut packfile::Reader<fs::File>, start_date: &BlockDate, end_date: &BlockDate) -> Result<Option<Block>> {\n\n loop {\n\n match packreader.get_next() {\n\n None => { return Ok(None) },\n\n Some(b) => {\n\n let mut blk = RawBlock(b).decode().unwrap();\n\n let blk_date = blk.get_header().get_blockdate();\n\n if &blk_date > end_date {\n\n return Ok(None)\n\n };\n\n if &blk_date >= start_date {\n\n return Ok(Some(blk))\n\n }\n\n },\n\n }\n\n }\n\n}\n\n\n\npub enum ReverseSearch {\n\n Continue,\n\n Found,\n\n Abort,\n\n}\n\n\n", "file_path": "storage/src/block/iter.rs", "rank": 8, "score": 352560.7437630693 }, { "content": "pub fn write_hash<S: AsRef<str>>(storage: &super::Storage, name: &S, content: &block::HeaderHash) {\n\n write(storage, name, content.as_ref())\n\n}\n\n\n", "file_path": "storage/src/tag.rs", "rank": 9, "score": 344263.67092542583 }, { "content": "pub fn read_hash<S: AsRef<str>>(storage: &super::Storage, name: &S) -> Option<block::HeaderHash> {\n\n read(storage, name).and_then(|v| block::HeaderHash::try_from_slice(&v[..]).ok())\n\n}\n\n\n", "file_path": "storage/src/tag.rs", "rank": 10, "score": 344263.67092542583 }, { "content": "/// Try to open a packfile Reader on a specific epoch\n\n///\n\n/// if there's no pack at this address, then nothing is return\n\npub fn epoch_open_pack_reader(config: &StorageConfig, epochid: cardano::block::EpochId) -> Result<Option<packfile::Reader<fs::File>>> {\n\n match epoch_read_pack(config, epochid) {\n\n Err(Error::StorageError(StorageError::IoError(ref err))) if err.kind() == ::std::io::ErrorKind::NotFound => Ok(None),\n\n Err(err) => Err(err),\n\n Ok(epoch_ref) => {\n\n let reader = packreader_init(config, &epoch_ref);\n\n Ok(Some(reader))\n\n }\n\n }\n\n}\n\n\n\n/*\n", "file_path": "storage/src/epoch.rs", "rank": 11, "score": 338013.3666489187 }, { "content": "pub fn dump_index(storage_config: &super::StorageConfig, pack: &super::PackHash) -> Result<(indexfile::Lookup, Vec<super::BlockHash>)> {\n\n let mut file = open_index(storage_config, pack);\n\n let result = indexfile::dump_file(&mut file)?;\n\n Ok(result)\n\n}\n\n\n", "file_path": "storage/src/pack.rs", "rank": 12, "score": 337828.7508883742 }, { "content": "pub fn packreader_block_next(reader: &mut packfile::Reader<fs::File>) -> Option<cardano::block::RawBlock> {\n\n reader.get_next().and_then(|x| Some(cardano::block::RawBlock(x)))\n\n}\n", "file_path": "storage/src/pack.rs", "rank": 13, "score": 334831.8451410536 }, { "content": "pub fn block_read(storage: &Storage, hash: &BlockHash) -> Option<RawBlock> {\n\n match block_location(storage, hash) {\n\n None => None,\n\n Some(loc) => block_read_location(storage, &loc, hash),\n\n }\n\n}\n\n\n\n/// packing parameters\n\n///\n\n/// optionally set the maximum number of blobs in this pack\n\n/// optionally set the maximum size in bytes of the pack file.\n\n/// note that the limits is best effort, not strict.\n\npub struct PackParameters {\n\n pub limit_nb_blobs: Option<u32>,\n\n pub limit_size: Option<u64>,\n\n pub delete_blobs_after_pack: bool,\n\n pub range: Option<(BlockHash, BlockHash)>,\n\n}\n\nimpl Default for PackParameters {\n\n fn default() -> Self {\n\n PackParameters {\n\n limit_nb_blobs: None,\n\n limit_size: None,\n\n delete_blobs_after_pack: true,\n\n range: None,\n\n }\n\n }\n\n}\n\n\n", "file_path": "storage/src/lib.rs", "rank": 14, "score": 333815.73228358355 }, { "content": "// same as read_next_block, but when receiving EOF it will wrapped into returning None\n\npub fn read_next_block_or_eof<R: Read>(file: R) -> io::Result<Option<Vec<u8>>> {\n\n match read_next_block(file) {\n\n Err(err) => if err.kind() == io::ErrorKind::UnexpectedEof { Ok(None) } else { Err(err) },\n\n Ok(data) => Ok(Some(data)),\n\n }\n\n}\n\n\n\nimpl<R: Read> Reader<R> {\n\n /// Return the next data block.\n\n ///\n\n /// note: any IO error raise runtime exception for now. will be changed soon.\n\n pub fn get_next(&mut self) -> Option<Vec<u8>> {\n\n // TODO: remove unwrap()\n\n let mdata = read_next_block_or_eof(&mut self.reader).unwrap();\n\n match mdata {\n\n None => {},\n\n Some(ref data) => {\n\n self.hash_context.input(data);\n\n self.pos += 4 + offset_align4(data.len() as u64);\n\n }\n", "file_path": "storage/src/containers/packfile.rs", "rank": 15, "score": 331732.00404479355 }, { "content": "// Create a pack of references (packref) of all the hash in an epoch pack\n\n//\n\n// If the pack is not valid, then an error is returned\n\npub fn refpack_epoch_pack<S: AsRef<str>>(storage: &Storage, tag: &S) -> Result<()> {\n\n let mut rp = reffile::Lookup::new();\n\n let packhash_vec = tag::read(storage, tag).expect(\"EPOCH not found\");\n\n let mut packhash = [0;HASH_SIZE];\n\n packhash[..].clone_from_slice(packhash_vec.as_slice());\n\n let mut pack = packreader_init(&storage.config, &packhash);\n\n\n\n let mut current_state = None;\n\n\n\n while let Some(raw_block) = packreader_block_next(&mut pack) {\n\n let block = raw_block.decode()?;\n\n let hdr = block.get_header();\n\n let hash = hdr.compute_hash();\n\n let date = hdr.get_blockdate();\n\n\n\n // either we have seen genesis yet or not\n\n match current_state {\n\n None => {\n\n if !hdr.is_genesis_block() {\n\n return Err(Error::EpochExpectingGenesis)\n", "file_path": "storage/src/lib.rs", "rank": 16, "score": 330603.748288183 }, { "content": "/// decode the given hexadecimal string\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use cardano::util::hex::{Error, decode};\n\n///\n\n/// let example = r\"736f6d65206279746573\";\n\n///\n\n/// assert!(decode(example).is_ok());\n\n/// ```\n\npub fn decode(input: &str) -> Result<Vec<u8>> {\n\n let mut b = Vec::with_capacity(input.len() / 2);\n\n let mut modulus = 0;\n\n let mut buf = 0;\n\n\n\n for (idx, byte) in input.bytes().enumerate() {\n\n buf <<= 4;\n\n\n\n match byte {\n\n b'A'...b'F' => buf |= byte - b'A' + 10,\n\n b'a'...b'f' => buf |= byte - b'a' + 10,\n\n b'0'...b'9' => buf |= byte - b'0',\n\n b' '|b'\\r'|b'\\n'|b'\\t' => {\n\n buf >>= 4;\n\n continue\n\n }\n\n _ => {\n\n return Err(Error::UnknownSymbol(idx));\n\n }\n\n }\n", "file_path": "cardano/src/util/hex.rs", "rank": 17, "score": 330399.78614281456 }, { "content": "/// decode from base58 the given input\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use cardano::util::base58;\n\n///\n\n/// let encoded = r\"TcgsE5dzphUWfjcb9i5\";\n\n/// let decoded = b\"Hello World...\";\n\n///\n\n/// assert_eq!(decoded, base58::decode(encoded).unwrap().as_slice());\n\n/// ```\n\npub fn decode(input: &str) -> Result<Vec<u8>> {\n\n base_decode(ALPHABET, input.as_bytes())\n\n}\n\n\n", "file_path": "cardano/src/util/base58.rs", "rank": 18, "score": 330385.8603715847 }, { "content": "pub fn epoch_open_packref(config: &StorageConfig, epochid: cardano::block::EpochId) -> Result<reffile::Reader> {\n\n let path = config.get_epoch_refpack_filepath(epochid);\n\n let reader = reffile::Reader::open(path)?;\n\n Ok(reader)\n\n}\n\n\n", "file_path": "storage/src/epoch.rs", "rank": 19, "score": 327198.839510093 }, { "content": "pub fn epoch_read_packref(config: &StorageConfig, epochid: cardano::block::EpochId) -> Result<reffile::Reader> {\n\n let reader = reffile::Reader::open(config.get_epoch_refpack_filepath(epochid))?;\n\n Ok(reader)\n\n}\n\n\n", "file_path": "storage/src/epoch.rs", "rank": 20, "score": 327198.8395100929 }, { "content": "pub fn block_read_location(storage: &Storage, loc: &BlockLocation, hash: &BlockHash) -> Option<RawBlock> {\n\n match loc {\n\n &BlockLocation::Loose => blob::read(storage, hash).ok(),\n\n &BlockLocation::Packed(ref packref, ref iofs) => {\n\n match storage.lookups.get(packref) {\n\n None => { unreachable!(); },\n\n Some(lookup) => {\n\n let idx_filepath = storage.config.get_index_filepath(packref);\n\n let mut idx_file = indexfile::ReaderNoLookup::init(idx_filepath).unwrap();\n\n let pack_offset = idx_file.resolve_index_offset(lookup, *iofs);\n\n let pack_filepath = storage.config.get_pack_filepath(packref);\n\n let mut pack_file = packfile::Seeker::init(pack_filepath).unwrap();\n\n pack_file.get_at_offset(pack_offset).ok().and_then(|x| Some(RawBlock(x)))\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "storage/src/lib.rs", "rank": 21, "score": 317951.77636615204 }, { "content": "pub fn epoch_open_pack_seeker() -> io::Result<Option<packfile::Seeker>> {\n\n}\n\n*/\n\n\n", "file_path": "storage/src/epoch.rs", "rank": 22, "score": 317041.9579260984 }, { "content": "pub fn epoch_create(config: &StorageConfig, packref: &PackHash, epochid: cardano::block::EpochId) {\n\n // read the pack and append the block hash as we find them in the refpack.\n\n let mut rp = reffile::Lookup::new();\n\n let mut reader = packreader_init(config, packref);\n\n\n\n let mut current_slotid = cardano::block::BlockDate::Genesis(epochid);\n\n while let Some(rblk) = packreader_block_next(&mut reader) {\n\n let blk = rblk.decode().unwrap();\n\n let hdr = blk.get_header();\n\n let hash = hdr.compute_hash();\n\n let blockdate = hdr.get_blockdate();\n\n\n\n while current_slotid != blockdate {\n\n rp.append_missing_hash();\n\n current_slotid = current_slotid.next();\n\n }\n\n rp.append_hash(header_to_blockhash(&hash));\n\n current_slotid = current_slotid.next();\n\n }\n\n\n", "file_path": "storage/src/epoch.rs", "rank": 23, "score": 309870.1380128054 }, { "content": "pub fn block_location(storage: &Storage, hash: &BlockHash) -> Option<BlockLocation> {\n\n for (packref, lookup) in storage.lookups.iter() {\n\n let (start, nb) = lookup.fanout.get_indexer_by_hash(hash);\n\n match nb {\n\n indexfile::FanoutNb(0) => {},\n\n _ => {\n\n if lookup.bloom.search(hash) {\n\n let idx_filepath = storage.config.get_index_filepath(packref);\n\n let mut idx_file = indexfile::Reader::init(idx_filepath).unwrap();\n\n match idx_file.search(&lookup.params, hash, start, nb) {\n\n None => {},\n\n Some(iloc) => return Some(BlockLocation::Packed(packref.clone(), iloc)),\n\n }\n\n }\n\n }\n\n }\n\n }\n\n if blob::exist(storage, hash) {\n\n return Some(BlockLocation::Loose);\n\n }\n\n None\n\n}\n\n\n", "file_path": "storage/src/lib.rs", "rank": 24, "score": 306756.9826888383 }, { "content": "fn epoch_integrity_check(storage: &Storage, epochid: EpochId, last_known_hash: HeaderHash) -> Result<HeaderHash> {\n\n let packhash_vec = tag::read(storage, &format!(\"EPOCH_{}\", epochid)).expect(\"EPOCH not found\");\n\n let mut packhash = [0;HASH_SIZE];\n\n packhash[..].clone_from_slice(packhash_vec.as_slice());\n\n let mut pack = packreader_init(&storage.config, &packhash);\n\n\n\n let mut current_state = None;\n\n\n\n while let Some(raw_block) = packreader_block_next(&mut pack) {\n\n let block = raw_block.decode()?;\n\n let hdr = block.get_header();\n\n let hash = hdr.compute_hash();\n\n let prevhash = hdr.get_previous_header();\n\n let date = hdr.get_blockdate();\n\n\n\n // either we have seen genesis yet or not\n\n match current_state {\n\n None => {\n\n if !hdr.is_genesis_block() {\n\n return Err(Error::EpochExpectingGenesis)\n", "file_path": "storage/src/lib.rs", "rank": 25, "score": 303135.9646073672 }, { "content": "pub fn get_peer(blockchain: &str, cfg: &net::Config, native: bool) -> Peer {\n\n for peer in cfg.peers.iter() {\n\n if (native && peer.is_native()) || (!native && peer.is_http()) {\n\n return Peer::new(\n\n String::from(blockchain),\n\n peer.name().to_owned(),\n\n peer.peer().clone(),\n\n cfg.protocol_magic,\n\n ).unwrap();\n\n }\n\n }\n\n\n\n panic!(\"no peer to connect to\")\n\n}\n", "file_path": "exe-common/src/sync.rs", "rank": 26, "score": 301111.38260281255 }, { "content": "// write the content buf atomically to the path.\n\n//\n\n// if an issue arise until the data is written, then\n\n// the expected file destination is not going to be\n\n// created\n\npub fn atomic_write_simple(path: &PathBuf, buf: &[u8]) -> io::Result<()> {\n\n let mut tmpfile = TmpFile::create(path.parent().unwrap().to_path_buf())?;\n\n tmpfile.write(buf)?;\n\n tmpfile.render_permanent(path)?;\n\n Ok(())\n\n}\n", "file_path": "storage/src/utils/tmpfile.rs", "rank": 27, "score": 294608.13913382776 }, { "content": "pub fn header_to_blockhash(header_hash: &HeaderHash) -> BlockHash {\n\n let mut bh = [0u8;HASH_SIZE];\n\n bh[0..HASH_SIZE].clone_from_slice(header_hash.as_ref());\n\n bh\n\n}\n\n\n\n#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]\n\npub enum StorageFileType {\n\n Pack,\n\n Index,\n\n Blob,\n\n Tag,\n\n RefPack,\n\n Epoch,\n\n}\n", "file_path": "storage/src/types.rs", "rank": 28, "score": 294076.24243681354 }, { "content": "pub fn exist<S: AsRef<str>>(storage: &super::Storage, name: &S) -> bool {\n\n let p = storage.config.get_tag_filepath(name);\n\n p.as_path().exists()\n\n}\n\n\n", "file_path": "storage/src/tag.rs", "rank": 29, "score": 293911.2736682197 }, { "content": "pub fn epoch_create_with_refpack(config: &StorageConfig, packref: &PackHash, refpack: &reffile::Lookup, epochid: cardano::block::EpochId) {\n\n let dir = config.get_epoch_dir(epochid);\n\n fs::create_dir_all(dir).unwrap();\n\n\n\n let pack_filepath = config.get_epoch_pack_filepath(epochid);\n\n tmpfile::atomic_write_simple(&pack_filepath, hex::encode(packref).as_bytes()).unwrap();\n\n\n\n let mut tmpfile = TmpFile::create(config.get_epoch_dir(epochid)).unwrap();\n\n refpack.write(&mut tmpfile).unwrap();\n\n tmpfile.render_permanent(&config.get_epoch_refpack_filepath(epochid)).unwrap();\n\n}\n\n\n", "file_path": "storage/src/epoch.rs", "rank": 30, "score": 288945.2925200321 }, { "content": "pub fn integrity_check(storage: &Storage, genesis_hash: HeaderHash, count: EpochId) {\n\n let mut previous_header = genesis_hash;\n\n for epochid in 0..count {\n\n println!(\"check epoch {}'s integrity\", epochid);\n\n previous_header = epoch_integrity_check(storage, epochid, previous_header).unwrap();\n\n }\n\n}\n\n\n", "file_path": "storage/src/lib.rs", "rank": 31, "score": 286123.3784285719 }, { "content": "pub fn set_bit_to(data: &mut [u8], bit: usize, value: bool) {\n\n let (byte_addr, bit_addr) = addr(bit);\n\n if value {\n\n data[byte_addr] |= bit_addr.set_mask();\n\n } else {\n\n data[byte_addr] &= bit_addr.clear_mask();\n\n }\n\n}\n\n\n", "file_path": "storage/src/utils/bitmap.rs", "rank": 32, "score": 282017.39916331944 }, { "content": "pub fn index_get_header(file: &mut fs::File) -> Result<indexfile::Lookup> {\n\n let lookup = indexfile::Lookup::read_from_file(file)?;\n\n Ok(lookup)\n\n}\n\n\n", "file_path": "storage/src/pack.rs", "rank": 33, "score": 281363.7015233121 }, { "content": "pub fn read<S: AsRef<str>>(storage: &super::Storage, name: &S) -> Option<Vec<u8>> {\n\n if ! exist(storage, name) { return None; }\n\n let mut content = Vec::new();\n\n let path = storage.config.get_tag_filepath(name);\n\n let mut file = fs::File::open(path).unwrap();\n\n file.read_to_end(&mut content).unwrap();\n\n String::from_utf8(content.clone()).ok()\n\n .and_then(|r| hex::decode(&r).ok())\n\n .or(Some(content))\n\n}\n\n\n", "file_path": "storage/src/tag.rs", "rank": 34, "score": 281000.3343156521 }, { "content": "pub fn send_msg_getheaders(froms: &[block::HeaderHash], to: &Option<block::HeaderHash>) -> Message {\n\n let serializer = se::Serializer::new_vec().write_array(cbor_event::Len::Len(2)).unwrap();\n\n let serializer = se::serialize_indefinite_array(froms.iter(), serializer).unwrap();\n\n let serializer = match to {\n\n &None => serializer.write_array(cbor_event::Len::Len(0)).unwrap(),\n\n &Some(ref h) => {\n\n serializer.write_array(cbor_event::Len::Len(1)).unwrap()\n\n .serialize(h).unwrap()\n\n }\n\n };\n\n let dat = serializer.finalize();\n\n (MsgType::MsgGetHeaders as u8, dat)\n\n}\n\n\n", "file_path": "protocol/src/packet.rs", "rank": 35, "score": 277775.6037739154 }, { "content": "pub fn read_refpack<P: AsRef<str>>(storage_config: &StorageConfig, name: P) -> Result<reffile::Lookup> {\n\n let r = reffile::Lookup::from_path(storage_config.get_refpack_filepath(name))?;\n\n Ok(r)\n\n}\n\n\n", "file_path": "storage/src/refpack.rs", "rank": 36, "score": 276811.0826240595 }, { "content": "pub fn pack_blobs(storage: &mut Storage, params: &PackParameters) -> PackHash {\n\n let mut writer = pack::packwriter_init(&storage.config).unwrap();\n\n let mut blob_packed = Vec::new();\n\n\n\n let block_hashes : Vec<BlockHash> = if let Some((from, to)) = params.range {\n\n storage.range(from, to).unwrap().iter().cloned().collect()\n\n } else {\n\n storage.config.list_blob(params.limit_nb_blobs)\n\n };\n\n for bh in block_hashes {\n\n let blob = blob::read_raw(storage, &bh).unwrap();\n\n writer.append(&bh, &blob[..]).unwrap();\n\n blob_packed.push(bh);\n\n match params.limit_size {\n\n None => {},\n\n Some(sz) => {\n\n if writer.pos >= sz {\n\n break\n\n }\n\n }\n", "file_path": "storage/src/lib.rs", "rank": 37, "score": 276596.03060773306 }, { "content": "pub fn validate_network_name(v: &&str) -> bool {\n\n v.chars().all(|c| c.is_ascii_alphanumeric())\n\n}\n\n\n", "file_path": "hermes/src/handlers/common.rs", "rank": 38, "score": 275063.55228854483 }, { "content": "pub fn packwriter_init(cfg: &super::StorageConfig) -> Result<packfile::Writer> {\n\n let tmpfile = TmpFile::create(cfg.get_filetype_dir(super::StorageFileType::Pack))?;\n\n let writer = packfile::Writer::init(tmpfile)?;\n\n Ok(writer)\n\n}\n\n\n", "file_path": "storage/src/pack.rs", "rank": 39, "score": 274776.49863682344 }, { "content": "pub fn write_refpack<P: AsRef<str>>(storage_config: &StorageConfig, name: P, rf: &reffile::Lookup) -> Result<()> {\n\n let path = storage_config.get_refpack_filepath(name);\n\n rf.to_path(path)?;\n\n Ok(())\n\n}\n", "file_path": "storage/src/refpack.rs", "rank": 40, "score": 270963.08788277797 }, { "content": "#[allow(dead_code)]\n\npub fn get_bits(data: &[u8], start_bit: usize, nb_bits: usize) -> Vec<bool> {\n\n let mut v = Vec::with_capacity(nb_bits);\n\n let (start_byte_addr, start_bit_addr) = addr(start_bit);\n\n\n\n let mut current_val = data[start_byte_addr] >> start_bit_addr.get_shifter();\n\n let mut current_byte_addr = start_byte_addr;\n\n let mut current_bit_addr = start_bit_addr;\n\n for i in 0..nb_bits {\n\n v[nb_bits - i - 1] = (current_val & 0x1) == 0x1;\n\n match current_bit_addr.get_next() {\n\n None => {\n\n current_byte_addr += 1;\n\n current_bit_addr = ByteAddr(0);\n\n current_val = data[current_byte_addr];\n\n },\n\n Some(new_addr) => {\n\n current_bit_addr = new_addr;\n\n current_val = current_val >> 1;\n\n },\n\n }\n\n }\n\n v\n\n}", "file_path": "storage/src/utils/bitmap.rs", "rank": 41, "score": 268302.30951547174 }, { "content": "/// get the root directory of all the hermes path\n\n///\n\n/// it is either environment variable `HERMES_PATH` or the `${HOME}/.hermes`\n\npub fn hermes_path() -> Result<PathBuf> {\n\n match env::var(HERMES_PATH_ENV) {\n\n Ok(path) => Ok(PathBuf::from(path)),\n\n Err(VarError::NotPresent) => match home_dir() {\n\n None => Err(Error::BlockchainConfigError(\"no home directory to base hermes root dir. Set `HERMES_PATH' variable environment to fix the problem.\")),\n\n Some(path) => Ok(path.join(HERMES_HOME_PATH))\n\n },\n\n Err(err) => Err(Error::VarError(err))\n\n }\n\n}\n", "file_path": "hermes/src/config.rs", "rank": 42, "score": 262814.74799273844 }, { "content": "/// Process a block with the SHA-512 algorithm. (See more...)\n\n///\n\n/// Internally, this uses functions that resemble the new Intel SHA\n\n/// instruction set extensions, but since no architecture seems to\n\n/// have any designs, these may not be the final designs if and/or when\n\n/// there are instruction set extensions with SHA-512. So to summarize:\n\n/// SHA-1 and SHA-256 are being implemented in hardware soon (at the time\n\n/// of this writing), but it doesn't look like SHA-512 will be hardware\n\n/// accelerated any time soon.\n\n///\n\n/// # Implementation\n\n///\n\n/// These functions fall into two categories:\n\n/// message schedule calculation, and the message block 64-round digest calculation.\n\n/// The schedule-related functions allow 4 rounds to be calculated as:\n\n///\n\n/// ```ignore\n\n/// use std::simd::u64x2;\n\n/// use self::crypto::sha2::{\n\n/// sha512msg,\n\n/// sha512load\n\n/// };\n\n///\n\n/// fn schedule4_data(work: &mut [u64x2], w: &[u64]) {\n\n///\n\n/// // this is to illustrate the data order\n\n/// work[0] = u64x2(w[1], w[0]);\n\n/// work[1] = u64x2(w[3], w[2]);\n\n/// work[2] = u64x2(w[5], w[4]);\n\n/// work[3] = u64x2(w[7], w[6]);\n\n/// work[4] = u64x2(w[9], w[8]);\n\n/// work[5] = u64x2(w[11], w[10]);\n\n/// work[6] = u64x2(w[13], w[12]);\n\n/// work[7] = u64x2(w[15], w[14]);\n\n/// }\n\n///\n\n/// fn schedule4_work(work: &mut [u64x2], t: usize) {\n\n///\n\n/// // this is the core expression\n\n/// work[t] = sha512msg(work[t - 8],\n\n/// work[t - 7],\n\n/// sha512load(work[t - 4], work[t - 3]),\n\n/// work[t - 1]);\n\n/// }\n\n/// ```\n\n///\n\n/// instead of 4 rounds of:\n\n///\n\n/// ```ignore\n\n/// fn schedule_work(w: &mut [u64], t: usize) {\n\n/// w[t] = sigma1!(w[t - 2]) + w[t - 7] + sigma0!(w[t - 15]) + w[t - 16];\n\n/// }\n\n/// ```\n\n///\n\n/// and the digest-related functions allow 4 rounds to be calculated as:\n\n///\n\n/// ```ignore\n\n/// use std::simd::u64x2;\n\n/// use self::crypto::sha2::{K64X2, sha512rnd};\n\n///\n\n/// fn rounds4(state: &mut [u64; 8], work: &mut [u64x2], t: usize) {\n\n/// let [a, b, c, d, e, f, g, h]: [u64; 8] = *state;\n\n///\n\n/// // this is to illustrate the data order\n\n/// let mut ae = u64x2(a, e);\n\n/// let mut bf = u64x2(b, f);\n\n/// let mut cg = u64x2(c, g);\n\n/// let mut dh = u64x2(d, h);\n\n/// let u64x2(w1, w0) = K64X2[2*t] + work[2*t];\n\n/// let u64x2(w3, w2) = K64X2[2*t + 1] + work[2*t + 1];\n\n///\n\n/// // this is the core expression\n\n/// dh = sha512rnd(ae, bf, cg, dh, w0);\n\n/// cg = sha512rnd(dh, ae, bf, cg, w1);\n\n/// bf = sha512rnd(cg, dh, ae, bf, w2);\n\n/// ae = sha512rnd(bf, cg, dh, ae, w3);\n\n///\n\n/// *state = [ae.0, bf.0, cg.0, dh.0,\n\n/// ae.1, bf.1, cg.1, dh.1];\n\n/// }\n\n/// ```\n\n///\n\n/// instead of 4 rounds of:\n\n///\n\n/// ```ignore\n\n/// fn round(state: &mut [u64; 8], w: &mut [u64], t: usize) {\n\n/// let [a, b, c, mut d, e, f, g, mut h]: [u64; 8] = *state;\n\n///\n\n/// h += big_sigma1!(e) + choose!(e, f, g) + K64[t] + w[t]; d += h;\n\n/// h += big_sigma0!(a) + majority!(a, b, c);\n\n///\n\n/// *state = [h, a, b, c, d, e, f, g];\n\n/// }\n\n/// ```\n\n///\n\npub fn sha512_digest_block(state: &mut [u64; 8], block: &[u8/*; 128*/]) {\n\n assert_eq!(block.len(), BLOCK_LEN*8);\n\n let mut block2 = [0u64; BLOCK_LEN];\n\n read_u64v_be(&mut block2[..], block);\n\n sha512_digest_block_u64(state, &block2);\n\n}\n\n\n\n// A structure that represents that state of a digest computation for the SHA-2 512 family\n\n// of digest functions\n", "file_path": "cryptoxide/src/sha2.rs", "rank": 43, "score": 261340.70948434496 }, { "content": "/// Process a block with the SHA-256 algorithm. (See more...)\n\n///\n\n/// Internally, this uses functions which resemble the new Intel SHA instruction sets,\n\n/// and so it's data locality properties may improve performance. However, to benefit\n\n/// the most from this implementation, replace these functions with x86 intrinsics to\n\n/// get a possible speed boost.\n\n///\n\n/// # Implementation\n\n///\n\n/// The `Sha256` algorithm is implemented with functions that resemble the new\n\n/// Intel SHA instruction set extensions. These intructions fall into two categories:\n\n/// message schedule calculation, and the message block 64-round digest calculation.\n\n/// The schedule-related instructions allow 4 rounds to be calculated as:\n\n///\n\n/// ```ignore\n\n/// use std::simd::u32x4;\n\n/// use self::crypto::sha2::{\n\n/// sha256msg1,\n\n/// sha256msg2,\n\n/// sha256load\n\n/// };\n\n///\n\n/// fn schedule4_data(work: &mut [u32x4], w: &[u32]) {\n\n///\n\n/// // this is to illustrate the data order\n\n/// work[0] = u32x4(w[3], w[2], w[1], w[0]);\n\n/// work[1] = u32x4(w[7], w[6], w[5], w[4]);\n\n/// work[2] = u32x4(w[11], w[10], w[9], w[8]);\n\n/// work[3] = u32x4(w[15], w[14], w[13], w[12]);\n\n/// }\n\n///\n\n/// fn schedule4_work(work: &mut [u32x4], t: usize) {\n\n///\n\n/// // this is the core expression\n\n/// work[t] = sha256msg2(sha256msg1(work[t - 4], work[t - 3]) +\n\n/// sha256load(work[t - 2], work[t - 1]),\n\n/// work[t - 1])\n\n/// }\n\n/// ```\n\n///\n\n/// instead of 4 rounds of:\n\n///\n\n/// ```ignore\n\n/// fn schedule_work(w: &mut [u32], t: usize) {\n\n/// w[t] = sigma1!(w[t - 2]) + w[t - 7] + sigma0!(w[t - 15]) + w[t - 16];\n\n/// }\n\n/// ```\n\n///\n\n/// and the digest-related instructions allow 4 rounds to be calculated as:\n\n///\n\n/// ```ignore\n\n/// use std::simd::u32x4;\n\n/// use self::crypto::sha2::{K32X4,\n\n/// sha256rnds2,\n\n/// sha256swap\n\n/// };\n\n///\n\n/// fn rounds4(state: &mut [u32; 8], work: &mut [u32x4], t: usize) {\n\n/// let [a, b, c, d, e, f, g, h]: [u32; 8] = *state;\n\n///\n\n/// // this is to illustrate the data order\n\n/// let mut abef = u32x4(a, b, e, f);\n\n/// let mut cdgh = u32x4(c, d, g, h);\n\n/// let temp = K32X4[t] + work[t];\n\n///\n\n/// // this is the core expression\n\n/// cdgh = sha256rnds2(cdgh, abef, temp);\n\n/// abef = sha256rnds2(abef, cdgh, sha256swap(temp));\n\n///\n\n/// *state = [abef.0, abef.1, cdgh.0, cdgh.1,\n\n/// abef.2, abef.3, cdgh.2, cdgh.3];\n\n/// }\n\n/// ```\n\n///\n\n/// instead of 4 rounds of:\n\n///\n\n/// ```ignore\n\n/// fn round(state: &mut [u32; 8], w: &mut [u32], t: usize) {\n\n/// let [a, b, c, mut d, e, f, g, mut h]: [u32; 8] = *state;\n\n///\n\n/// h += big_sigma1!(e) + choose!(e, f, g) + K32[t] + w[t]; d += h;\n\n/// h += big_sigma0!(a) + majority!(a, b, c);\n\n///\n\n/// *state = [h, a, b, c, d, e, f, g];\n\n/// }\n\n/// ```\n\n///\n\n/// **NOTE**: It is important to note, however, that these instructions are not implemented\n\n/// by any CPU (at the time of this writing), and so they are emulated in this library\n\n/// until the instructions become more common, and gain support in LLVM (and GCC, etc.).\n\n///\n\npub fn sha256_digest_block(state: &mut [u32; 8], block: &[u8/*; 64*/]) {\n\n assert_eq!(block.len(), BLOCK_LEN*4);\n\n let mut block2 = [0u32; BLOCK_LEN];\n\n read_u32v_be(&mut block2[..], block);\n\n sha256_digest_block_u32(state, &block2);\n\n}\n\n\n\n/// Not an intrinsic, but works like an unaligned load.\n", "file_path": "cryptoxide/src/sha2.rs", "rank": 44, "score": 261340.50736123143 }, { "content": "// Create an epoch from a complete set of previously fetched blocks on\n\n// disk.\n\nfn maybe_create_epoch(storage: &storage::Storage, epoch_id: EpochId, last_block: &HeaderHash)\n\n{\n\n if epoch_exists(&storage.config, epoch_id).unwrap() { return }\n\n\n\n info!(\"Packing epoch {}\", epoch_id);\n\n\n\n let mut epoch_writer_state = EpochWriterState {\n\n epoch_id,\n\n writer: storage::pack::packwriter_init(&storage.config).unwrap(),\n\n write_start_time: SystemTime::now(),\n\n blobs_to_delete: vec![]\n\n };\n\n\n\n append_blocks_to_epoch_reverse(&storage, &mut epoch_writer_state, last_block);\n\n\n\n finish_epoch(storage, epoch_writer_state);\n\n}\n\n\n", "file_path": "exe-common/src/sync.rs", "rank": 45, "score": 260322.87966057422 }, { "content": "fn template_create_temp(prefix: &str, suffix: &str) -> String {\n\n let v1 : u64 = rand::random();\n\n let v2 : u64 = rand::random();\n\n format!(\"{}{}{}{}\", prefix, v1, v2, suffix)\n\n}\n\n\n\nimpl TmpFile {\n\n pub fn create(mut path: PathBuf) -> io::Result<Self> {\n\n let filename = template_create_temp(\".tmp.\", \"\");\n\n path.push(filename);\n\n\n\n OpenOptions::new()\n\n .write(true)\n\n .read(true)\n\n .create_new(true)\n\n .open(&path)\n\n .map(|file| TmpFile { file: file, path: path })\n\n }\n\n\n\n pub fn render_permanent(&self, path: &PathBuf) -> io::Result<()> {\n", "file_path": "storage/src/utils/tmpfile.rs", "rank": 46, "score": 260000.1401298967 }, { "content": "/// Process a block with the SHA-512 algorithm.\n\npub fn sha512_digest_block_u64(state: &mut [u64; 8], block: &[u64; 16]) {\n\n let k = &K64X2;\n\n\n\n macro_rules! schedule {\n\n ($v0:expr, $v1:expr, $v4:expr, $v5:expr, $v7:expr) => (\n\n sha512_schedule_x2($v0, $v1, sha512load($v4, $v5), $v7)\n\n )\n\n }\n\n\n\n macro_rules! rounds4 {\n\n ($ae:ident, $bf:ident, $cg:ident, $dh:ident, $wk0:expr, $wk1:expr) => {\n\n {\n\n let u64x2(u, t) = $wk0;\n\n let u64x2(w, v) = $wk1;\n\n\n\n $dh = sha512_digest_round($ae, $bf, $cg, $dh, t);\n\n $cg = sha512_digest_round($dh, $ae, $bf, $cg, u);\n\n $bf = sha512_digest_round($cg, $dh, $ae, $bf, v);\n\n $ae = sha512_digest_round($bf, $cg, $dh, $ae, w);\n\n }\n", "file_path": "cryptoxide/src/sha2.rs", "rank": 47, "score": 258169.8302006979 }, { "content": "/// Process a block with the SHA-256 algorithm.\n\npub fn sha256_digest_block_u32(state: &mut [u32; 8], block: &[u32; 16]) {\n\n let k = &K32X4;\n\n\n\n macro_rules! schedule {\n\n ($v0:expr, $v1:expr, $v2:expr, $v3:expr) => (\n\n sha256msg2(sha256msg1($v0, $v1) + sha256load($v2, $v3), $v3)\n\n )\n\n }\n\n\n\n macro_rules! rounds4 {\n\n ($abef:ident, $cdgh:ident, $rest:expr) => {\n\n {\n\n $cdgh = sha256_digest_round_x2($cdgh, $abef, $rest);\n\n $abef = sha256_digest_round_x2($abef, $cdgh, sha256swap($rest));\n\n }\n\n }\n\n }\n\n\n\n let mut abef = u32x4(state[0],\n\n state[1],\n", "file_path": "cryptoxide/src/sha2.rs", "rank": 48, "score": 258169.83020069788 }, { "content": "/// decode from base58 the given input\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use cardano::util::base58;\n\n///\n\n/// let encoded = b\"TcgsE5dzphUWfjcb9i5\";\n\n/// let decoded = b\"Hello World...\";\n\n///\n\n/// assert_eq!(decoded, base58::decode_bytes(encoded).unwrap().as_slice());\n\n/// ```\n\npub fn decode_bytes(input: &[u8]) -> Result<Vec<u8>> {\n\n base_decode(ALPHABET, input)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n fn encode(input: &[u8], expected: &str) {\n\n let encoded = super::encode(input);\n\n assert_eq!(encoded, expected);\n\n }\n\n fn decode(expected: &[u8], input: &str) {\n\n let decoded = super::decode(input).unwrap();\n\n assert_eq!(decoded.as_slice(), expected);\n\n }\n\n\n\n #[test]\n\n fn test_vector_1() {\n\n encode(b\"\\0\\0\\0\\0\", \"11111\");\n\n decode(b\"\\0\\0\\0\\0\", \"11111\");\n\n }\n", "file_path": "cardano/src/util/base58.rs", "rank": 49, "score": 258135.75734271656 }, { "content": "fn file_read_hash(mut file: &fs::File) -> BlockHash {\n\n let mut buf = [0u8;HASH_SIZE];\n\n file.read_exact(&mut buf).unwrap();\n\n buf\n\n}\n\n\n", "file_path": "storage/src/containers/indexfile.rs", "rank": 50, "score": 256283.9200340224 }, { "content": "fn base_decode(alphabet_s: &str, input: &[u8]) -> Result<Vec<u8>> {\n\n let alphabet = alphabet_s.as_bytes();\n\n let base = alphabet.len() as u32;\n\n\n\n let mut bytes : Vec<u8> = vec![0];\n\n let zcount = input.iter().take_while(|x| **x == alphabet[0]).count();\n\n\n\n for i in zcount..input.len() {\n\n let value = match alphabet.iter().position(|&x| x == input[i]) {\n\n Some(idx) => idx,\n\n None => return Err(Error::UnknownSymbol(i))\n\n };\n\n let mut carry = value as u32;\n\n for j in 0..bytes.len() {\n\n carry = carry + (bytes[j] as u32 * base);\n\n bytes[j] = carry as u8;\n\n carry = carry >> 8;\n\n }\n\n\n\n while carry > 0 {\n", "file_path": "cardano/src/util/base58.rs", "rank": 51, "score": 255847.43235053337 }, { "content": "pub fn read_index_fanout(storage_config: &super::StorageConfig, pack: &super::PackHash) -> Result<indexfile::Lookup> {\n\n let mut file = open_index(storage_config, pack);\n\n let lookup = indexfile::Lookup::read_from_file(&mut file)?;\n\n Ok(lookup)\n\n}\n\n\n", "file_path": "storage/src/pack.rs", "rank": 52, "score": 252735.83287136996 }, { "content": "// calculate FNV1, FNV1a\n\npub fn hash(content: &[u8]) -> (u64, u64) {\n\n let mut hash = FNV_OFFSET_BASIS;\n\n let mut hash2 = FNV_OFFSET_BASIS;\n\n for c in content {\n\n // FNV1\n\n hash = hash.wrapping_mul(FNV_PRIME);\n\n hash ^= *c as u64;\n\n\n\n // FNV1a\n\n hash2 = *c as u64;\n\n hash2 = hash2.wrapping_mul(FNV_PRIME);\n\n }\n\n (hash, hash2)\n\n}\n\n\n", "file_path": "storage/src/utils/bloom.rs", "rank": 53, "score": 240716.24635348818 }, { "content": "#[allow(dead_code)]\n\npub fn new(size: usize) -> Vec<u8> {\n\n let v : Vec<u8> = repeat(0).take(size as usize).collect();\n\n v\n\n}\n\n\n", "file_path": "storage/src/utils/bitmap.rs", "rank": 54, "score": 240424.61506395627 }, { "content": "pub fn validate_epochid(v: &&str) -> Option<EpochId> {\n\n if ! v.chars().all(|c| c.is_digit(10)) {\n\n None\n\n } else {\n\n Some(v.parse::<EpochId>().unwrap())\n\n }\n\n}\n", "file_path": "hermes/src/handlers/common.rs", "rank": 55, "score": 237453.131114812 }, { "content": "pub fn is_set(bitmap: &[u8], content: &[u8]) -> bool {\n\n let (v1,v2,v3) = addr3(bitmap.len() * 8, content);\n\n bitmap::get_bit(bitmap, v1) && bitmap::get_bit(bitmap, v2) && bitmap::get_bit(bitmap, v3)\n\n}", "file_path": "storage/src/utils/bloom.rs", "rank": 56, "score": 233916.43120664754 }, { "content": "pub fn remove_tag<S: AsRef<str>>(storage: &super::Storage, name: &S) {\n\n let p = storage.config.get_tag_filepath(name);\n\n fs::remove_file(p).unwrap()\n\n}\n", "file_path": "storage/src/tag.rs", "rank": 57, "score": 233765.33506705542 }, { "content": "pub fn set(bitmap: &mut [u8], content: &[u8]) {\n\n let (v1,v2,v3) = addr3(bitmap.len() * 8, content);\n\n\n\n bitmap::set_bit_to(bitmap, v1, true);\n\n bitmap::set_bit_to(bitmap, v2, true);\n\n bitmap::set_bit_to(bitmap, v3, true);\n\n}\n\n\n", "file_path": "storage/src/utils/bloom.rs", "rank": 58, "score": 233050.48730195692 }, { "content": "pub fn get_bit(data: &[u8], bit: usize) -> bool {\n\n let (byte_addr, bit_addr) = addr(bit);\n\n let val = (data[byte_addr] >> bit_addr.get_shifter()) & 0x1;\n\n val == 0x1\n\n}\n\n\n", "file_path": "storage/src/utils/bitmap.rs", "rank": 59, "score": 230504.29577939294 }, { "content": "pub fn write_offset(buf: &mut [u8], sz: Offset) {\n\n buf[0] = (sz >> 56) as u8;\n\n buf[1] = (sz >> 48) as u8;\n\n buf[2] = (sz >> 40) as u8;\n\n buf[3] = (sz >> 32) as u8;\n\n buf[4] = (sz >> 24) as u8;\n\n buf[5] = (sz >> 16) as u8;\n\n buf[6] = (sz >> 8) as u8;\n\n buf[7] = sz as u8;\n\n}\n\n\n", "file_path": "storage/src/utils/serialize.rs", "rank": 60, "score": 229640.75154101662 }, { "content": "// write size to the mutable buffer in big endian\n\npub fn write_size(buf: &mut [u8], sz: Size) {\n\n buf[0] = (sz >> 24) as u8;\n\n buf[1] = (sz >> 16) as u8;\n\n buf[2] = (sz >> 8) as u8;\n\n buf[3] = sz as u8;\n\n}\n\n\n", "file_path": "storage/src/utils/serialize.rs", "rank": 61, "score": 229640.7515410166 }, { "content": "/// exported as a convenient function to test the implementation of\n\n/// [`Serialize`](./se/trait.Serialize.html) and\n\n/// [`Deserialize`](./de/trait.Deserialize.html).\n\n///\n\npub fn test_encode_decode<V: Sized+PartialEq+Serialize+Deserialize>(v: &V) -> Result<bool> {\n\n let bytes = Serialize::serialize(v, se::Serializer::new_vec())?.finalize();\n\n\n\n let mut raw = de::RawCbor::from(&bytes);\n\n let v_ = Deserialize::deserialize(&mut raw)?;\n\n\n\n Ok(v == &v_)\n\n}\n", "file_path": "cbor_event/src/lib.rs", "rank": 62, "score": 228882.15099875373 }, { "content": "pub fn write<S: AsRef<str>>(storage: &super::Storage, name: &S, content: &[u8]) {\n\n let mut tmp_file = super::tmpfile_create_type(storage, super::StorageFileType::Tag);\n\n tmp_file.write_all(hex::encode(content).as_bytes()).unwrap();\n\n\n\n let path = storage.config.get_tag_filepath(name);\n\n let dir = PathBuf::from(path);\n\n\n\n match dir.parent() {\n\n None => {},\n\n Some(parent) => {\n\n if parent != storage.config.get_filetype_dir(super::StorageFileType::Tag) {\n\n fs::create_dir_all(parent).unwrap()\n\n }\n\n }\n\n };\n\n\n\n tmp_file.render_permanent(&storage.config.get_tag_filepath(name)).unwrap();\n\n}\n\n\n", "file_path": "storage/src/tag.rs", "rank": 63, "score": 226529.29173833178 }, { "content": "pub fn packreader_init(cfg: &super::StorageConfig, packhash: &super::PackHash) -> packfile::Reader<fs::File> {\n\n packfile::Reader::init(cfg.get_pack_filepath(packhash)).unwrap()\n\n}\n\n\n", "file_path": "storage/src/pack.rs", "rank": 64, "score": 224909.67676577502 }, { "content": "pub fn packwriter_finalize(cfg: &super::StorageConfig, writer: packfile::Writer) -> (super::PackHash, indexfile::Index) {\n\n let (tmpfile, packhash, index) = writer.finalize().unwrap();\n\n let path = cfg.get_pack_filepath(&packhash);\n\n tmpfile.render_permanent(&path).unwrap();\n\n (packhash, index)\n\n}\n\n\n", "file_path": "storage/src/pack.rs", "rank": 65, "score": 224909.67676577502 }, { "content": "// TODO proper error handling\n\nfn previous_block(storage: &Storage, block: &Block) -> Block {\n\n let prev_hash = block.get_header().get_previous_header();\n\n let blk = blob::read(&storage, &header_to_blockhash(&prev_hash)).unwrap().decode().unwrap();\n\n blk\n\n}\n\n\n", "file_path": "storage/src/block/iter.rs", "rank": 66, "score": 224094.92356731734 }, { "content": "type Result<T> = result::Result<T, Error>;\n\n\n\n/// Object which lifetime is bound to a file in the filesystem\n\n///\n\n/// i.e.: we are creating a `<filename>.LOCK` file along the given `filename`\n\n/// in order to mark the file as locked. This is in order to prevent concurrent\n\n/// access to a file that may be modified and which data may be corrupted if\n\n/// concurrent writes happen.\n\n///\n\n/// The lock will be free when it drops out of scope.\n\n///\n\n#[derive(Debug)]\n\npub struct Lock {\n\n // the process ID associated to the current loc\n\n id: u32,\n\n // the path to the locked file\n\n path: PathBuf\n\n}\n\n\n\nimpl Lock {\n", "file_path": "storage/src/utils/lock.rs", "rank": 67, "score": 212876.05729886383 }, { "content": "/// Synchronize the local blockchain stored in `storage` with the\n\n/// network `net`. That is, fetch all blocks between the most recent\n\n/// block we received (as denoted by the `HEAD` tag) and the network's\n\n/// current tip. Blocks will be packed into epochs on disk as soon\n\n/// they're stable.\n\n///\n\n/// If `sync_once` is set to `true`, then this function will\n\n/// synchronize once and then return. If it's set to `false`, then\n\n/// this function will run forever, continuously synchronizing to the\n\n/// network's latest tip. (In the case of the Hermes backend, it will\n\n/// sleep for some time between polling for new tips; with the native\n\n/// protocol backend, it will block waiting for the server to send us\n\n/// new tip announcements.)\n\npub fn net_sync<A: Api>(\n\n net: &mut A,\n\n net_cfg: &net::Config,\n\n storage: &storage::Storage,\n\n sync_once: bool)\n\n -> Result<()>\n\n{\n\n // recover and print the TIP of the network\n\n let mut tip_header = net.get_tip()?;\n\n\n\n loop {\n\n\n\n net_sync_to(net, net_cfg, storage, &tip_header)?;\n\n\n\n if sync_once { break }\n\n\n\n tip_header = net.wait_for_new_tip(&tip_header.compute_hash())?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "exe-common/src/sync.rs", "rank": 68, "score": 212564.6102458308 }, { "content": "pub fn send_msg_getblocks(from: &HeaderHash, to: &HeaderHash) -> Message {\n\n let dat = se::Serializer::new_vec().write_array(cbor_event::Len::Len(2)).unwrap()\n\n .serialize(from).unwrap()\n\n .serialize(to).unwrap()\n\n .finalize();\n\n (MsgType::MsgGetBlocks as u8, dat)\n\n}\n\n\n", "file_path": "protocol/src/packet.rs", "rank": 69, "score": 211932.19361551 }, { "content": "/// Write a u32 into a vector, which must be 4 bytes long. The value is written in big-endian\n\n/// format.\n\npub fn write_u32_be(dst: &mut [u8], mut input: u32) {\n\n assert!(dst.len() == 4);\n\n input = input.to_be();\n\n unsafe {\n\n let tmp = &input as *const _ as *const u8;\n\n ptr::copy_nonoverlapping(tmp, dst.get_unchecked_mut(0), 4);\n\n }\n\n}\n\n\n", "file_path": "cryptoxide/src/cryptoutil.rs", "rank": 70, "score": 208024.29224947462 }, { "content": "/// Write a u64 into a vector, which must be 8 bytes long. The value is written in big-endian\n\n/// format.\n\npub fn write_u64_be(dst: &mut[u8], mut input: u64) {\n\n assert!(dst.len() == 8);\n\n input = input.to_be();\n\n unsafe {\n\n let tmp = &input as *const _ as *const u8;\n\n ptr::copy_nonoverlapping(tmp, dst.get_unchecked_mut(0), 8);\n\n }\n\n}\n\n\n", "file_path": "cryptoxide/src/cryptoutil.rs", "rank": 71, "score": 208024.29224947462 }, { "content": "pub fn sc_reduce(s: &mut [u8]) {\n\n let mut s0: i64 = 2097151 & load_3i(s);\n\n let mut s1: i64 = 2097151 & (load_4i(&s[2..6]) >> 5);\n\n let mut s2: i64 = 2097151 & (load_3i(&s[5..8]) >> 2);\n\n let mut s3: i64 = 2097151 & (load_4i(&s[7..11]) >> 7);\n\n let mut s4: i64 = 2097151 & (load_4i(&s[10..14]) >> 4);\n\n let mut s5: i64 = 2097151 & (load_3i(&s[13..16]) >> 1);\n\n let mut s6: i64 = 2097151 & (load_4i(&s[15..19]) >> 6);\n\n let mut s7: i64 = 2097151 & (load_3i(&s[18..21]) >> 3);\n\n let mut s8: i64 = 2097151 & load_3i(&s[21..24]);\n\n let mut s9: i64 = 2097151 & (load_4i(&s[23..27]) >> 5);\n\n let mut s10: i64 = 2097151 & (load_3i(&s[26..29]) >> 2);\n\n let mut s11: i64 = 2097151 & (load_4i(&s[28..32]) >> 7);\n\n let mut s12: i64 = 2097151 & (load_4i(&s[31..35]) >> 4);\n\n let mut s13: i64 = 2097151 & (load_3i(&s[34..37]) >> 1);\n\n let mut s14: i64 = 2097151 & (load_4i(&s[36..40]) >> 6);\n\n let mut s15: i64 = 2097151 & (load_3i(&s[39..42]) >> 3);\n\n let mut s16: i64 = 2097151 & load_3i(&s[42..45]);\n\n let mut s17: i64 = 2097151 & (load_4i(&s[44..48]) >> 5);\n\n let s18: i64 = 2097151 & (load_3i(&s[47..50]) >> 2);\n", "file_path": "cryptoxide/src/curve25519.rs", "rank": 72, "score": 207546.49190657554 }, { "content": "#[inline]\n\npub fn zero(dst: &mut [u8]) {\n\n unsafe {\n\n ptr::write_bytes(dst.as_mut_ptr(), 0, dst.len());\n\n }\n\n}\n\n\n", "file_path": "cryptoxide/src/cryptoutil.rs", "rank": 73, "score": 207546.49190657554 }, { "content": "/// encode bytes into an hexadecimal string\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use cardano::util::hex::{Error, encode};\n\n///\n\n/// let example = b\"some bytes\";\n\n///\n\n/// assert_eq!(\"736f6d65206279746573\", encode(example));\n\n/// ```\n\npub fn encode(input: &[u8]) -> String {\n\n let mut v = Vec::with_capacity(input.len() * 2);\n\n for &byte in input.iter() {\n\n v.push(ALPHABET[(byte >> 4) as usize]);\n\n v.push(ALPHABET[(byte & 0xf) as usize]);\n\n }\n\n\n\n unsafe {\n\n String::from_utf8_unchecked(v)\n\n }\n\n}\n\n\n", "file_path": "cardano/src/util/hex.rs", "rank": 74, "score": 205767.85729574302 }, { "content": "/// encode in base58 the given input\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use cardano::util::base58;\n\n///\n\n/// let encoded = r\"TcgsE5dzphUWfjcb9i5\";\n\n/// let decoded = b\"Hello World...\";\n\n///\n\n/// assert_eq!(encoded, base58::encode(decoded));\n\n/// ```\n\npub fn encode(input: &[u8]) -> String {\n\n // unsafe to unwrap the result of `String::from_utf8` as the given\n\n // returned bytes are valid within the base58 alphabet (they are all ASCII7)\n\n String::from_utf8(\n\n base_encode(ALPHABET, input)\n\n ).unwrap()\n\n}\n\n\n", "file_path": "cardano/src/util/base58.rs", "rank": 75, "score": 205758.9162657597 }, { "content": "/// Write a u32 into a vector, which must be 4 bytes long. The value is written in little-endian\n\n/// format.\n\npub fn write_u32_le(dst: &mut[u8], mut input: u32) {\n\n assert!(dst.len() == 4);\n\n input = input.to_le();\n\n unsafe {\n\n let tmp = &input as *const _ as *const u8;\n\n ptr::copy_nonoverlapping(tmp, dst.get_unchecked_mut(0), 4);\n\n }\n\n}\n\n\n", "file_path": "cryptoxide/src/cryptoutil.rs", "rank": 76, "score": 205697.14575881025 }, { "content": "/// Write a u64 into a vector, which must be 8 bytes long. The value is written in little-endian\n\n/// format.\n\npub fn write_u64_le(dst: &mut[u8], mut input: u64) {\n\n assert!(dst.len() == 8);\n\n input = input.to_le();\n\n unsafe {\n\n let tmp = &input as *const _ as *const u8;\n\n ptr::copy_nonoverlapping(tmp, dst.get_unchecked_mut(0), 8);\n\n }\n\n}\n\n\n", "file_path": "cryptoxide/src/cryptoutil.rs", "rank": 77, "score": 205697.14575881025 }, { "content": "/// zero the given slice.\n\n///\n\n/// We assume the compiler won't optimise out the call to this function\n\npub fn zero(to_zero: &mut [u8]) {\n\n\n\n // the unsafety of this call is bounded to the existence of the pointer\n\n // and the accuracy of the length of the array.\n\n //\n\n // since to_zero existence is bound to live at least as long as the call\n\n // of this function and that we use the length (in bytes) of the given\n\n // slice, this call is safe.\n\n unsafe {\n\n ::std::ptr::write_bytes(to_zero.as_mut_ptr(), 0, to_zero.len())\n\n }\n\n}\n", "file_path": "cardano/src/util/securemem.rs", "rank": 78, "score": 204626.6114821655 }, { "content": "pub fn open_index(storage_config: &super::StorageConfig, pack: &super::PackHash) -> fs::File {\n\n fs::File::open(storage_config.get_index_filepath(pack)).unwrap()\n\n}\n\n\n", "file_path": "storage/src/pack.rs", "rank": 79, "score": 200806.63477164047 }, { "content": "pub fn send_msg_subscribe(keep_alive: bool) -> Message {\n\n let value = if keep_alive { 43 } else { 42 };\n\n let dat = se::Serializer::new_vec().write_unsigned_integer(value).unwrap().finalize();\n\n (MsgType::MsgSubscribe as u8, dat)\n\n}\n\n\n", "file_path": "protocol/src/packet.rs", "rank": 80, "score": 200098.56289269705 }, { "content": "fn duration_print(d: Duration) -> String {\n\n format!(\"{}.{:03} seconds\", d.as_secs(), d.subsec_millis())\n\n}\n\n\n", "file_path": "exe-common/src/sync.rs", "rank": 81, "score": 197753.14975768418 }, { "content": "fn base_encode(alphabet_s: &str, input: &[u8]) -> Vec<u8> {\n\n let alphabet = alphabet_s.as_bytes();\n\n let base = alphabet.len() as u32;\n\n\n\n let mut digits = vec![0 as u8];\n\n for input in input.iter() {\n\n let mut carry = input.clone() as u32;\n\n for j in 0..digits.len() {\n\n carry = carry + ((digits[j] as u32) << 8);\n\n digits[j] = (carry % base) as u8;\n\n carry = carry / base;\n\n }\n\n\n\n while carry > 0 {\n\n digits.push((carry % base) as u8);\n\n carry = carry / base;\n\n }\n\n }\n\n\n\n let mut string = vec![];\n", "file_path": "cardano/src/util/base58.rs", "rank": 82, "score": 195939.3441886178 }, { "content": "pub fn sum_coins<I>(coin_iter: I) -> Result<Coin>\n\n where I: Iterator<Item = Coin>\n\n{\n\n coin_iter.fold(Coin::new(0), |acc, ref c| acc.and_then(|v| v + *c))\n\n}\n", "file_path": "cardano/src/coin.rs", "rank": 83, "score": 195465.12538875284 }, { "content": "// Hmac uses two keys derived from the provided key - one by xoring every byte with 0x36 and another\n\n// with 0x5c.\n\nfn create_keys<D: Digest>(digest: &mut D, key: &[u8]) -> (Vec<u8>, Vec<u8>) {\n\n let mut i_key = expand_key(digest, key);\n\n let mut o_key = i_key.clone();\n\n derive_key(&mut i_key, 0x36);\n\n derive_key(&mut o_key, 0x5c);\n\n (i_key, o_key)\n\n}\n\n\n\nimpl <D: Digest> Hmac<D> {\n\n /**\n\n * Create a new Hmac instance.\n\n *\n\n * # Arguments\n\n * * digest - The Digest to use.\n\n * * key - The key to use.\n\n *\n\n */\n\n pub fn new(mut digest: D, key: &[u8]) -> Hmac<D> {\n\n let (i_key, o_key) = create_keys(&mut digest, key);\n\n digest.input(&i_key[..]);\n", "file_path": "cryptoxide/src/hmac.rs", "rank": 84, "score": 194425.6263877159 }, { "content": "/// Read a vector of bytes into a vector of u64s. The values are read in big-endian format.\n\npub fn read_u64v_be(dst: &mut[u64], input: &[u8]) {\n\n assert!(dst.len() * 8 == input.len());\n\n unsafe {\n\n let mut x: *mut u64 = dst.get_unchecked_mut(0);\n\n let mut y: *const u8 = input.get_unchecked(0);\n\n for _ in 0..dst.len() {\n\n let mut tmp: u64 = mem::uninitialized();\n\n ptr::copy_nonoverlapping(y, &mut tmp as *mut _ as *mut u8, 8);\n\n *x = u64::from_be(tmp);\n\n x = x.offset(1);\n\n y = y.offset(8);\n\n }\n\n }\n\n}\n\n\n", "file_path": "cryptoxide/src/cryptoutil.rs", "rank": 85, "score": 192639.41420826723 }, { "content": "/// Read a vector of bytes into a vector of u32s. The values are read in big-endian format.\n\npub fn read_u32v_be(dst: &mut[u32], input: &[u8]) {\n\n assert!(dst.len() * 4 == input.len());\n\n unsafe {\n\n let mut x: *mut u32 = dst.get_unchecked_mut(0);\n\n let mut y: *const u8 = input.get_unchecked(0);\n\n for _ in 0..dst.len() {\n\n let mut tmp: u32 = mem::uninitialized();\n\n ptr::copy_nonoverlapping(y, &mut tmp as *mut _ as *mut u8, 4);\n\n *x = u32::from_be(tmp);\n\n x = x.offset(1);\n\n y = y.offset(4);\n\n }\n\n }\n\n}\n\n\n", "file_path": "cryptoxide/src/cryptoutil.rs", "rank": 86, "score": 192639.41420826723 }, { "content": "pub fn secure_memset(dst: &mut [u8], val: u8) {\n\n for i in 0..dst.len() {\n\n dst[i] = val;\n\n }\n\n}\n\n\n", "file_path": "cryptoxide/src/util.rs", "rank": 87, "score": 192634.2141556674 }, { "content": "#[inline]\n\npub fn copy_memory(src: &[u8], dst: &mut [u8]) {\n\n assert!(dst.len() >= src.len());\n\n unsafe {\n\n let srcp = src.as_ptr();\n\n let dstp = dst.as_mut_ptr();\n\n ptr::copy_nonoverlapping(srcp, dstp, src.len());\n\n }\n\n}\n\n\n\n/// Zero all bytes in dst\n", "file_path": "cryptoxide/src/cryptoutil.rs", "rank": 88, "score": 192634.2141556674 }, { "content": "/// Compare two vectors using a fixed number of operations. If the two vectors are not of equal\n\n/// length, the function returns false immediately.\n\npub fn fixed_time_eq(lhs: &[u8], rhs: &[u8]) -> bool {\n\n if lhs.len() != rhs.len() {\n\n false\n\n } else {\n\n let mut v = 0;\n\n for i in 0..lhs.len() {\n\n let a = lhs[i];\n\n let b = rhs[i];\n\n v = v | (a ^ b);\n\n };\n\n v == 0\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use util::fixed_time_eq;\n\n\n\n #[test]\n\n pub fn test_fixed_time_eq() {\n", "file_path": "cryptoxide/src/util.rs", "rank": 89, "score": 190948.56914168334 }, { "content": "/// Try to reverse the scramble operation, using\n\n/// the first `IV_SIZE` bytes as IV, and the rest as the shielded input.\n\npub fn unscramble(password: &[u8], input: &[u8]) -> Vec<u8>{\n\n assert!(input.len() > IV_SIZE);\n\n\n\n let out_sz = input.len() - IV_SIZE;\n\n\n\n let mut out = Vec::with_capacity(out_sz);\n\n for _ in 0..out_sz {\n\n out.push(0);\n\n }\n\n\n\n gen(&input[0..IV_SIZE], password, &mut out[0..out_sz]);\n\n for i in 0..out_sz {\n\n out[i] = out[i] ^ input[IV_SIZE+i];\n\n }\n\n out\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n //use paperwallet::{scramble,unscramble};\n\n use paperwallet;\n\n\n", "file_path": "cardano/src/paperwallet.rs", "rank": 90, "score": 190412.560957146 }, { "content": "/// Read a vector of bytes into a vector of u64s. The values are read in little-endian format.\n\npub fn read_u64v_le(dst: &mut[u64], input: &[u8]) {\n\n assert!(dst.len() * 8 == input.len());\n\n unsafe {\n\n let mut x: *mut u64 = dst.get_unchecked_mut(0);\n\n let mut y: *const u8 = input.get_unchecked(0);\n\n for _ in 0..dst.len() {\n\n let mut tmp: u64 = mem::uninitialized();\n\n ptr::copy_nonoverlapping(y, &mut tmp as *mut _ as *mut u8, 8);\n\n *x = u64::from_le(tmp);\n\n x = x.offset(1);\n\n y = y.offset(8);\n\n }\n\n }\n\n}\n\n\n", "file_path": "cryptoxide/src/cryptoutil.rs", "rank": 91, "score": 190080.34520304832 }, { "content": "/// Write a vector of u64s into a vector of bytes. The values are written in little-endian format.\n\npub fn write_u64v_le(dst: &mut[u8], input: &[u64]) {\n\n assert!(dst.len() == 8 * input.len());\n\n unsafe {\n\n let mut x: *mut u8 = dst.get_unchecked_mut(0);\n\n let mut y: *const u64 = input.get_unchecked(0);\n\n for _ in 0..input.len() {\n\n let tmp = (*y).to_le();\n\n ptr::copy_nonoverlapping(&tmp as *const _ as *const u8, x, 8);\n\n x = x.offset(8);\n\n y = y.offset(1);\n\n }\n\n }\n\n}\n\n\n", "file_path": "cryptoxide/src/cryptoutil.rs", "rank": 92, "score": 190080.34520304832 }, { "content": "/// Write a vector of u32s into a vector of bytes. The values are written in little-endian format.\n\npub fn write_u32v_le (dst: &mut[u8], input: &[u32]) {\n\n assert!(dst.len() == 4 * input.len());\n\n unsafe {\n\n let mut x: *mut u8 = dst.get_unchecked_mut(0);\n\n let mut y: *const u32 = input.get_unchecked(0);\n\n for _ in 0..input.len() {\n\n let tmp = (*y).to_le();\n\n ptr::copy_nonoverlapping(&tmp as *const _ as *const u8, x, 4);\n\n x = x.offset(4);\n\n y = y.offset(1);\n\n }\n\n }\n\n}\n\n\n", "file_path": "cryptoxide/src/cryptoutil.rs", "rank": 93, "score": 190080.34520304832 }, { "content": "/// Read a vector of bytes into a vector of u32s. The values are read in little-endian format.\n\npub fn read_u32v_le(dst: &mut[u32], input: &[u8]) {\n\n assert!(dst.len() * 4 == input.len());\n\n unsafe {\n\n let mut x: *mut u32 = dst.get_unchecked_mut(0);\n\n let mut y: *const u8 = input.get_unchecked(0);\n\n for _ in 0..dst.len() {\n\n let mut tmp: u32 = mem::uninitialized();\n\n ptr::copy_nonoverlapping(y, &mut tmp as *mut _ as *mut u8, 4);\n\n *x = u32::from_le(tmp);\n\n x = x.offset(1);\n\n y = y.offset(4);\n\n }\n\n }\n\n}\n\n\n", "file_path": "cryptoxide/src/cryptoutil.rs", "rank": 94, "score": 190080.34520304832 }, { "content": "/// Check that a file has a header denoting the expected file type and\n\n/// has a version in the specified range. Return the version.\n\npub fn check_header(\n\n file: &mut Read,\n\n expected_file_type: FileType,\n\n min_version: Version,\n\n max_version: Version)\n\n -> Result<Version>\n\n{\n\n let mut hdr_buf = [0u8;HEADER_SIZE];\n\n file.read_exact(&mut hdr_buf)?;\n\n\n\n if &hdr_buf[0..MAGIC_SIZE] != MAGIC {\n\n return Err(StorageError::MissingMagic);\n\n }\n\n\n\n let file_type = read_size(&hdr_buf[8..12]);\n\n let version = read_size(&hdr_buf[12..16]);\n\n\n\n if file_type != expected_file_type {\n\n return Err(StorageError::WrongFileType(expected_file_type, file_type));\n\n }\n", "file_path": "storage/src/utils/magic.rs", "rank": 95, "score": 188042.82717775033 }, { "content": "pub fn pbkdf2<M: Mac>(mac: &mut M, salt: &[u8], c: u32, output: &mut [u8]) {\n\n assert!(c > 0);\n\n\n\n let os = mac.output_bytes();\n\n\n\n // A temporary storage array needed by calculate_block. This is really only necessary if c > 1.\n\n // Most users of pbkdf2 should use a value much larger than 1, so, this allocation should almost\n\n // always be necessary. A big exception is Scrypt. However, this allocation is unlikely to be\n\n // the bottleneck in Scrypt performance.\n\n let mut scratch: Vec<u8> = repeat(0).take(os).collect();\n\n\n\n let mut idx: u32 = 0;\n\n\n\n for chunk in output.chunks_mut(os) {\n\n // The block index starts at 1. So, this is supposed to run on the first execution.\n\n idx = idx.checked_add(1).expect(\"PBKDF2 size limit exceeded.\");\n\n\n\n if chunk.len() == os {\n\n calculate_block(mac, salt, c, idx, &mut scratch, chunk);\n\n } else {\n\n let mut tmp: Vec<u8> = repeat(0).take(os).collect();\n\n calculate_block(mac, salt, c, idx, &mut scratch[..], &mut tmp[..]);\n\n let chunk_len = chunk.len();\n\n copy_memory(&tmp[..chunk_len], chunk);\n\n }\n\n }\n\n}\n", "file_path": "cryptoxide/src/pbkdf2.rs", "rank": 96, "score": 186089.2546017369 }, { "content": "// Return the chain of block headers starting at from's next block\n\n// and terminating at to, unless this range represent a number\n\n// of blocks greater than the limit imposed by the node we're talking to.\n\npub fn find_earliest_epoch(\n\n storage: &storage::Storage,\n\n minimum_epochid: block::EpochId,\n\n start_epochid: block::EpochId,\n\n) -> Option<(block::EpochId, PackHash)> {\n\n let mut epoch_id = start_epochid;\n\n loop {\n\n match storage::tag::read_hash(storage, &storage::tag::get_epoch_tag(epoch_id)) {\n\n None => match storage::epoch::epoch_read_pack(&storage.config, epoch_id).ok() {\n\n None => {}\n\n Some(h) => {\n\n return Some((epoch_id, h));\n\n }\n\n },\n\n Some(h) => {\n\n info!(\"latest known epoch found is {}\", epoch_id);\n\n return Some((epoch_id, h.into()));\n\n }\n\n }\n\n\n\n if epoch_id > minimum_epochid {\n\n epoch_id -= 1\n\n } else {\n\n return None;\n\n }\n\n }\n\n}\n\n\n", "file_path": "exe-common/src/utils.rs", "rank": 97, "score": 185549.12237378623 }, { "content": "pub fn txaux_serialize_size(tx: &Tx, in_witnesses: &Vec<TxInWitness>) -> usize {\n\n // TODO don't actually produce any bytes, but instead just count.\n\n // we don't expect error here, a real counter would not error..\n\n let ser = cbor_event::se::Serializer::new_vec();\n\n let bytes = txaux_serialize(tx, in_witnesses, ser).unwrap().finalize();\n\n bytes.len()\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct TxProof {\n\n pub number: u32,\n\n pub root: Blake2b256,\n\n pub witnesses_hash: Blake2b256,\n\n}\n\nimpl TxProof {\n\n pub fn new(number: u32, root: Blake2b256, witnesses_hash: Blake2b256) -> Self {\n\n TxProof {\n\n number: number,\n\n root: root,\n\n witnesses_hash: witnesses_hash\n", "file_path": "cardano/src/tx.rs", "rank": 98, "score": 183035.296297493 }, { "content": "/// Verify that a signature is valid for a given message for an associated public key\n\npub fn verify(message: &[u8], public_key: &[u8], signature: &[u8]) -> bool {\n\n assert!(public_key.len() == PUBLIC_KEY_LENGTH, \"Public key should be {} bytes long!\", PUBLIC_KEY_LENGTH);\n\n assert!(signature.len() == SIGNATURE_LENGTH, \"signature should be {} bytes long!\", SIGNATURE_LENGTH);\n\n\n\n if check_s_lt_l(&signature[32..64]) {\n\n return false;\n\n }\n\n\n\n let a = match GeP3::from_bytes_negate_vartime(public_key) {\n\n Some(g) => g,\n\n None => { return false; }\n\n };\n\n let mut d = 0;\n\n for pk_byte in public_key.iter() {\n\n d |= *pk_byte;\n\n }\n\n if d == 0 {\n\n return false;\n\n }\n\n\n", "file_path": "cryptoxide/src/ed25519.rs", "rank": 99, "score": 182908.8852603216 } ]
Rust
argonautica-rs/examples/example_serde.rs
philipahlberg/argonautica
bd9d7cb0f10dcf9a92f8b2e913b7116c1f10099d
extern crate argonautica; extern crate failure; extern crate serde; extern crate serde_json; use argonautica::{Hasher, Verifier}; fn serialize_hasher() -> Result<String, failure::Error> { let additional_data = [1u8, 2, 3, 4]; let salt = [1u8, 2, 3, 4, 5, 6, 7, 8]; let mut hasher = Hasher::default(); hasher .with_additional_data(&additional_data[..]) .with_password("P@ssw0rd") .with_salt(&salt[..]) .with_secret_key("secret"); let j = serde_json::to_string_pretty(&hasher)?; println!("*** Serialized Hasher ***"); println!("{}\n", &j); Ok(j) } fn deserialize_hasher(j: &str) -> Result<argonautica::Hasher, failure::Error> { let hasher: Hasher = serde_json::from_str(&j)?; println!("*** Deserialized Hasher ***"); println!("{:#?}\n", &hasher); Ok(hasher) } fn serialize_verifier() -> Result<String, failure::Error> { let additional_data = [1u8, 2, 3, 4]; let mut verifier = Verifier::default(); verifier .with_additional_data(&additional_data[..]) .with_hash("$argon2id$v=19$m=4096,t=128,p=2$c29tZXNhbHQ$WwD2/wGGTuw7u4BW8sLM0Q") .with_password("P@ssw0rd") .with_secret_key("secret"); let j = serde_json::to_string_pretty(&verifier)?; println!("*** Serialized Verifier ***"); println!("{}\n", &j); Ok(j) } fn deserialize_verifier(j: &str) -> Result<argonautica::Verifier, failure::Error> { let verifier: Verifier = serde_json::from_str(&j)?; println!("*** Deserialized Verifier ***"); println!("{:#?}\n", &verifier); Ok(verifier) } fn main() -> Result<(), failure::Error> { let j = serialize_hasher()?; let _ = deserialize_hasher(&j)?; let j = serialize_verifier()?; let _ = deserialize_verifier(&j)?; Ok(()) }
extern crate argonautica; extern crate failure; extern crate serde; extern crate serde_json; use argonautica::{Hasher, Verifier}; fn serialize_hasher() -> Result<String, failure::Error> { let additional_data = [1u8, 2, 3, 4]; let salt = [1u8, 2, 3, 4, 5, 6, 7, 8]; let mut hasher = Hasher::default(); hasher .with_additional_data(&additional_data[..]) .with_password("P@ssw0rd") .with_salt(&salt[..]) .with_secret_key("secret"); let j = serde_json::to_string_pretty(&hasher)?; println!("*** Serialized Hasher ***"); println!("{}\n", &j); Ok(j) } fn deserialize_hasher(j: &str) -> Result<argonautica::Hasher, failure::Error> { let hasher: Hasher = serde_json::from_str(&j)?; println!("*** Deserialized Hasher ***"); println!("{:#?}\n", &hasher); Ok(hasher) }
fn deserialize_verifier(j: &str) -> Result<argonautica::Verifier, failure::Error> { let verifier: Verifier = serde_json::from_str(&j)?; println!("*** Deserialized Verifier ***"); println!("{:#?}\n", &verifier); Ok(verifier) } fn main() -> Result<(), failure::Error> { let j = serialize_hasher()?; let _ = deserialize_hasher(&j)?; let j = serialize_verifier()?; let _ = deserialize_verifier(&j)?; Ok(()) }
fn serialize_verifier() -> Result<String, failure::Error> { let additional_data = [1u8, 2, 3, 4]; let mut verifier = Verifier::default(); verifier .with_additional_data(&additional_data[..]) .with_hash("$argon2id$v=19$m=4096,t=128,p=2$c29tZXNhbHQ$WwD2/wGGTuw7u4BW8sLM0Q") .with_password("P@ssw0rd") .with_secret_key("secret"); let j = serde_json::to_string_pretty(&verifier)?; println!("*** Serialized Verifier ***"); println!("{}\n", &j); Ok(j) }
function_block-function_prefixed
[ { "content": "fn bench_crates(c: &mut Criterion) {\n\n // argon2rs\n\n let hasher = argon2rs::Argon2::new(\n\n /* passes */ DEFAULT_ITERATIONS,\n\n /* lanes */ default_lanes(),\n\n /* kib */ DEFAULT_MEMORY_SIZE,\n\n /* variant */ argon2rs::Variant::Argon2i,\n\n )\n\n .unwrap();\n\n let argon2rs = Fun::new(\"argon2rs\", move |b, _| {\n\n b.iter(|| {\n\n let mut out = [0u8; DEFAULT_HASH_LEN as usize];\n\n\n\n let password = PASSWORD.as_bytes();\n\n\n\n let mut rng = OsRng::new().unwrap();\n\n let mut salt = [0u8; DEFAULT_SALT_LEN as usize];\n\n rng.fill_bytes(&mut salt);\n\n\n\n hasher.hash(\n", "file_path": "argonautica-rs/benches/bench_crates.rs", "rank": 4, "score": 150432.2087319208 }, { "content": "fn h0(_hasher: &mut Hasher) -> Result<[u8; 72], Error> {\n\n unimplemented!();\n\n}\n", "file_path": "argonautica-rs/src/backend/rust/core/mod.rs", "rank": 5, "score": 137391.12123706387 }, { "content": "fn bench_crates(c: &mut Criterion) {\n\n // argonautica\n\n let mut hasher = argonautica::Hasher::fast_but_insecure();\n\n hasher.with_password(DOCUMENT);\n\n let argonautica = Fun::new(\"argonautica\", move |b, _| {\n\n b.iter(|| {\n\n let _ = hasher.hash().unwrap();\n\n })\n\n });\n\n\n\n // md5\n\n let md5 = Fun::new(\"md5\", move |b, _| {\n\n b.iter(|| {\n\n let _ = md5::compute(DOCUMENT.as_bytes());\n\n });\n\n });\n\n\n\n // sha256\n\n let sha256 = Fun::new(\"sha256\", move |b, _| {\n\n b.iter(|| {\n", "file_path": "argonautica-rs/benches/bench_fast_but_insecure.rs", "rank": 6, "score": 136956.57147666826 }, { "content": "fn bench_threads(c: &mut Criterion) {\n\n c.bench_function_over_inputs(\n\n \"bench_threads\",\n\n |b, &&threads| {\n\n let bench = Bench {\n\n hasher: None,\n\n iterations: DEFAULT_ITERATIONS,\n\n memory_size: DEFAULT_MEMORY_SIZE,\n\n threads,\n\n }\n\n .setup();\n\n b.iter(|| bench.clone().run());\n\n },\n\n &THREADS,\n\n );\n\n}\n\n\n\ncriterion_group! {\n\n name = benches;\n\n config = Criterion::default().sample_size(SAMPLE_SIZE);\n\n targets = bench_threads,\n\n}\n\ncriterion_main!(benches);\n", "file_path": "argonautica-rs/benches/bench_threads.rs", "rank": 8, "score": 105914.03027892095 }, { "content": "fn bench_inputs(c: &mut Criterion) {\n\n c.bench_function_over_inputs(\n\n \"bench_inputs\",\n\n |b, &input| {\n\n let iterations = input.iterations();\n\n let memory_size = input.memory_size();\n\n let bench = Bench {\n\n hasher: None,\n\n iterations,\n\n memory_size,\n\n threads: num_cpus::get_physical() as u32,\n\n }\n\n .setup();\n\n b.iter(|| bench.clone().run());\n\n },\n\n &INPUTS,\n\n );\n\n}\n\n\n\ncriterion_group! {\n\n name = benches;\n\n config = Criterion::default().sample_size(SAMPLE_SIZE);\n\n targets = bench_inputs,\n\n}\n\ncriterion_main!(benches);\n", "file_path": "argonautica-rs/benches/bench_inputs.rs", "rank": 9, "score": 105914.03027892095 }, { "content": "fn run_c(exe: &str, dir: &Path, args: &[&str]) -> Vec<u8> {\n\n let output = Command::new(exe)\n\n .args(args)\n\n .current_dir(dir)\n\n .output()\n\n .unwrap();\n\n if !output.status.success() {\n\n panic!(\n\n \"\\nC executable failed:\\nstdout: {}stderr: {}\",\n\n String::from_utf8(output.stdout).unwrap(),\n\n String::from_utf8(output.stderr).unwrap(),\n\n )\n\n }\n\n output.stderr\n\n}\n\n\n", "file_path": "argonautica-rs/tests/tests.rs", "rank": 10, "score": 103809.74834363932 }, { "content": "fn main() -> Result<(), failure::Error> {\n\n let temp = tempfile::tempdir()?;\n\n let temp_dir = temp.path();\n\n let temp_dir_str = temp_dir.to_str().unwrap();\n\n\n\n let blamka_header = if IS_SIMD {\n\n \"phc-winner-argon2/src/blake2/blamka-round-opt.h\"\n\n } else {\n\n \"phc-winner-argon2/src/blake2/blamka-round-ref.h\"\n\n };\n\n for header_path_str in &[\n\n \"phc-winner-argon2/include/argon2.h\",\n\n \"phc-winner-argon2/src/core.h\",\n\n \"phc-winner-argon2/src/encoding.h\",\n\n \"phc-winner-argon2/src/thread.h\",\n\n \"phc-winner-argon2/src/blake2/blake2-impl.h\",\n\n \"phc-winner-argon2/src/blake2/blake2.h\",\n\n blamka_header,\n\n ] {\n\n let header_path = Path::new(*header_path_str);\n", "file_path": "argonautica-rs/build.rs", "rank": 11, "score": 92683.88889200032 }, { "content": "fn main() -> Result<(), failure::Error> {\n\n let mut hasher = Hasher::default();\n\n let hash = hasher\n\n .with_password(\"P@ssw0rd\")\n\n .with_secret_key(\n\n \"\\\n\n secret key that you should really store in \\\n\n an environment variable instead of in code, \\\n\n but this is just an example\\\n\n \",\n\n )\n\n .hash()?;\n\n\n\n println!(\"{}\", &hash);\n\n // 👆 prints a hash, which will be random since the default Hasher uses a random salt\n\n\n\n let mut verifier = Verifier::default();\n\n let is_valid = verifier\n\n .with_hash(&hash)\n\n .with_password(\"P@ssw0rd\")\n", "file_path": "argonautica-rs/examples/example_very_simple.rs", "rank": 12, "score": 88349.68656462249 }, { "content": "fn main() -> Result<(), failure::Error> {\n\n let secret_key = load_secret_key()?;\n\n let mut hasher = Hasher::default();\n\n hasher\n\n .configure_hash_len(32)\n\n .configure_iterations(192)\n\n .configure_lanes(1)\n\n .configure_memory_size(2u32.pow(12))\n\n .configure_password_clearing(true)\n\n .configure_secret_key_clearing(false)\n\n .configure_threads(1)\n\n .configure_variant(Variant::Argon2id)\n\n .configure_version(Version::_0x13)\n\n .with_salt(Salt::random(16))\n\n .with_secret_key(&secret_key);\n\n\n\n let mut dictionary = HashMap::new();\n\n for password in &[\"P@ssw0rd\", \"Hello world!\", \"123456\", \"😊\"] {\n\n let hash = hasher.with_password(password.to_string()).hash()?;\n\n println!(\"{}\", &hash);\n", "file_path": "argonautica-rs/examples/example_custom.rs", "rank": 13, "score": 88349.68656462249 }, { "content": "fn main() -> Result<(), failure::Error> {\n\n let secret_key = load_secret_key()?;\n\n let mut hasher = Hasher::default();\n\n let hash = hasher\n\n .with_password(\"P@ssw0rd\")\n\n .with_secret_key(&secret_key)\n\n .hash()?;\n\n println!(\"{}\", &hash);\n\n\n\n let mut verifier = Verifier::default();\n\n let is_valid = verifier\n\n .with_hash(&hash)\n\n .with_password(\"P@ssw0rd\")\n\n .with_secret_key(&secret_key)\n\n .verify()?;\n\n\n\n assert!(is_valid);\n\n Ok(())\n\n}\n", "file_path": "argonautica-rs/examples/example_simple.rs", "rank": 14, "score": 88349.68656462249 }, { "content": "fn main() -> Result<(), failure::Error> {\n\n let salt = Salt::random(SALT_LEN);\n\n let secret_key =\n\n SecretKey::from_base64_encoded(\"t9nGEsDxjWtJYdYeExdB6/HU0vg+rT6czv6HSjVjZng=\")?;\n\n let threads = num_cpus::get();\n\n for memory_size in &MEMORY_SIZES {\n\n for iterations in &ITERATIONS {\n\n let mut hasher = Hasher::default();\n\n hasher\n\n .configure_hash_len(HASH_LEN)\n\n .configure_iterations(*iterations)\n\n .configure_lanes(threads as u32)\n\n .configure_memory_size(*memory_size)\n\n .configure_threads(threads as u32)\n\n .configure_variant(VARIANT)\n\n .configure_version(VERSION)\n\n .with_password(PASSWORD)\n\n .with_salt(&salt)\n\n .with_secret_key(&secret_key);\n\n let now = Instant::now();\n", "file_path": "argonautica-rs/examples/calibrate_timing.rs", "rank": 15, "score": 88349.68656462249 }, { "content": "fn main() -> Result<(), failure::Error> {\n\n let secret_key = load_secret_key()?;\n\n\n\n let mut hasher = Hasher::default();\n\n let mut verifier = Verifier::default();\n\n\n\n let future = hasher\n\n .with_password(\"P@ssw0rd\")\n\n .with_secret_key(&secret_key)\n\n .hash_non_blocking()\n\n .and_then(|hash| {\n\n println!(\"{}\", &hash);\n\n verifier\n\n .with_hash(&hash)\n\n .with_password(\"P@ssw0rd\")\n\n .with_secret_key(&secret_key)\n\n .verify_non_blocking()\n\n })\n\n .and_then(|is_valid| {\n\n assert!(is_valid);\n\n Ok(())\n\n })\n\n .map_err(|e| e.into());\n\n\n\n future.wait()\n\n}\n", "file_path": "argonautica-rs/examples/example_non_blocking.rs", "rank": 16, "score": 86363.89151205108 }, { "content": "fn main() -> Result<(), failure::Error> {\n\n let base64_encoded_secret_key = utils::generate_random_base64_encoded_string(32)?;\n\n println!(\"{}\", &base64_encoded_secret_key);\n\n Ok(())\n\n}\n", "file_path": "argonautica-rs/examples/generate_secret_key.rs", "rank": 17, "score": 86363.89151205108 }, { "content": "class Hasher:\n\n \"\"\"\n\n A class that knows how to hash\n\n \"\"\"\n\n\n\n __slots__ = [\n\n 'additional_data',\n\n 'backend',\n\n 'hash_len',\n\n 'iterations',\n\n 'lanes',\n\n 'memory_size',\n\n 'salt',\n\n 'secret_key',\n\n 'threads',\n\n 'variant',\n\n 'version'\n\n ]\n\n\n\n def __init__(\n\n self,\n\n *,\n\n secret_key: Union[bytes, str, None],\n\n\n\n additional_data: Union[bytes, str, None] = None,\n\n backend: Backend = DEFAULT_BACKEND,\n\n hash_len: int = DEFAULT_HASH_LEN,\n\n iterations: int = DEFAULT_ITERATIONS,\n\n lanes: int = DEFAULT_LANES,\n\n memory_size: int = DEFAULT_MEMORY_SIZE,\n\n salt: Union[bytes, RandomSalt, str] = DEFAULT_SALT,\n\n threads: int = DEFAULT_THREADS,\n\n variant: Variant = DEFAULT_VARIANT,\n\n version: Version = DEFAULT_VERSION\n\n ) -> None:\n\n self.additional_data = additional_data\n\n self.salt = salt\n\n self.secret_key = secret_key\n\n self.backend = backend\n\n self.hash_len = hash_len\n\n self.iterations = iterations\n\n self.lanes = lanes\n\n self.memory_size = memory_size\n\n self.threads = threads\n\n self.variant = variant\n\n self.version = version\n\n\n\n def hash(\n\n self,\n\n *,\n\n password: Union[bytes, str],\n\n\n\n additional_data: Union[bytes, str, None, Void] = VOID,\n\n backend: Union[Backend, Void] = VOID,\n\n hash_len: Union[int, Void] = VOID,\n\n iterations: Union[int, Void] = VOID,\n\n lanes: Union[int, Void] = VOID,\n\n memory_size: Union[int, Void] = VOID,\n\n salt: Union[bytes, RandomSalt, str, Void] = VOID,\n\n secret_key: Union[bytes, str, None, Void] = VOID,\n\n threads: Union[int, Void] = VOID,\n\n variant: Union[Variant, Void] = VOID,\n\n version: Union[Version, Void] = VOID\n\n ) -> str:\n\n if isinstance(additional_data, Void):\n\n additional_data = self.additional_data\n\n if isinstance(backend, Void):\n\n backend = self.backend\n\n if isinstance(hash_len, Void):\n\n hash_len = self.hash_len\n\n if isinstance(iterations, Void):\n\n iterations = self.iterations\n\n if isinstance(lanes, Void):\n\n lanes = self.lanes\n\n if isinstance(memory_size, Void):\n\n memory_size = self.memory_size\n\n if isinstance(salt, Void):\n\n salt = self.salt\n\n if isinstance(secret_key, Void):\n\n secret_key = self.secret_key\n\n if isinstance(threads, Void):\n\n threads = self.threads\n\n if isinstance(variant, Void):\n\n variant = self.variant\n\n if isinstance(version, Void):\n\n version = self.version\n\n return hash(\n\n additional_data=additional_data,\n\n backend=backend,\n\n hash_len=hash_len,\n\n iterations=iterations,\n\n lanes=lanes,\n\n memory_size=memory_size,\n\n password=password,\n\n salt=salt,\n\n secret_key=secret_key,\n\n threads=threads,\n\n variant=variant,\n\n version=version\n", "file_path": "argonautica-py/argonautica/core/hasher.py", "rank": 18, "score": 83619.90265680093 }, { "content": "fn validate_threads(threads: u32) -> Result<(), Error> {\n\n if threads == 0 {\n\n return Err(\n\n Error::new(ErrorKind::ThreadsTooFewError).add_context(format!(\"Threads: {}\", threads))\n\n );\n\n }\n\n if threads > 0x00ff_ffff {\n\n return Err(\n\n Error::new(ErrorKind::ThreadsTooManyError).add_context(format!(\"Threads: {}\", threads))\n\n );\n\n }\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_send() {\n", "file_path": "argonautica-rs/src/config/hasher_config.rs", "rank": 19, "score": 80443.88805369401 }, { "content": "fn validate_iterations(iterations: u32) -> Result<(), Error> {\n\n if iterations == 0 {\n\n return Err(Error::new(ErrorKind::IterationsTooFewError)\n\n .add_context(format!(\"Iterations: {}\", iterations)));\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "argonautica-rs/src/config/hasher_config.rs", "rank": 20, "score": 80443.88805369401 }, { "content": "fn validate_lanes(lanes: u32) -> Result<(), Error> {\n\n if lanes == 0 {\n\n return Err(\n\n Error::new(ErrorKind::LanesTooFewError).add_context(format!(\"Lanes: {}\", lanes))\n\n );\n\n }\n\n if lanes > 0x00ff_ffff {\n\n return Err(\n\n Error::new(ErrorKind::LanesTooManyError).add_context(format!(\"Lanes: {}\", lanes))\n\n );\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "argonautica-rs/src/config/hasher_config.rs", "rank": 21, "score": 80443.88805369401 }, { "content": "fn validate_backend(backend: Backend) -> Result<(), Error> {\n\n match backend {\n\n Backend::C => (),\n\n Backend::Rust => return Err(Error::new(ErrorKind::BackendUnsupportedError)),\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "argonautica-rs/src/config/hasher_config.rs", "rank": 22, "score": 80443.88805369401 }, { "content": "fn validate_hash_len(hash_len: u32) -> Result<(), Error> {\n\n if hash_len < 4 {\n\n return Err(Error::new(ErrorKind::HashLenTooShortError)\n\n .add_context(format!(\"Hash len: {}\", hash_len)));\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "argonautica-rs/src/config/hasher_config.rs", "rank": 23, "score": 77173.42208376409 }, { "content": "// Helper method to load the secret key from a .env file. Used in `main` below.\n\nfn load_secret_key() -> Result<SecretKey<'static>, failure::Error> {\n\n let dotenv_path = env::current_dir()?.join(\"examples\").join(\"example.env\");\n\n dotenv::from_path(&dotenv_path).map_err(|e| format_err!(\"{}\", e))?;\n\n let base64_encoded_secret_key = env::var(\"SECRET_KEY\")?;\n\n Ok(SecretKey::from_base64_encoded(&base64_encoded_secret_key)?)\n\n}\n\n\n", "file_path": "argonautica-rs/examples/example_custom.rs", "rank": 24, "score": 76038.67936723767 }, { "content": "// Helper method to load the secret key from a .env file. Used in `main` below.\n\nfn load_secret_key() -> Result<SecretKey<'static>, failure::Error> {\n\n let dotenv_path = env::current_dir()?.join(\"examples\").join(\"example.env\");\n\n dotenv::from_path(&dotenv_path).map_err(|e| format_err!(\"{}\", e))?;\n\n let base64_encoded_secret_key = env::var(\"SECRET_KEY\")?;\n\n Ok(SecretKey::from_base64_encoded(&base64_encoded_secret_key)?)\n\n}\n\n\n", "file_path": "argonautica-rs/examples/example_simple.rs", "rank": 25, "score": 76038.67936723767 }, { "content": "// Helper method to load the secret key from a .env file. Used in `main` below.\n\nfn load_secret_key() -> Result<SecretKey<'static>, failure::Error> {\n\n let dotenv_path = env::current_dir()?.join(\"examples\").join(\"example.env\");\n\n dotenv::from_path(&dotenv_path).map_err(|e| format_err!(\"{}\", e))?;\n\n let base64_encoded_secret_key = env::var(\"SECRET_KEY\")?;\n\n Ok(SecretKey::from_base64_encoded(&base64_encoded_secret_key)?)\n\n}\n\n\n", "file_path": "argonautica-rs/examples/example_non_blocking.rs", "rank": 26, "score": 74514.5184111809 }, { "content": " uint8_t* salt;\n", "file_path": "argonautica-rs/tests/c/src/test.h", "rank": 27, "score": 74144.95158230896 }, { "content": " def salt(self, value: Union[bytes, RandomSalt, str]) -> None:\n", "file_path": "argonautica-py/argonautica/core/argon2.py", "rank": 28, "score": 73604.21506430957 }, { "content": " uint8_t *salt; /* salt array */\n", "file_path": "argonautica-rs/tests/c/src/argon2/argon2.h", "rank": 29, "score": 73052.50380640617 }, { "content": " uint8_t salt[BLAKE2B_SALTBYTES]; /* 48 */\n", "file_path": "argonautica-rs/tests/c/src/argon2/blake2/blake2.h", "rank": 30, "score": 72019.25747518596 }, { "content": "fn validate_memory_size(lanes: u32, memory_size: u32) -> Result<(), Error> {\n\n if memory_size < 8 * lanes {\n\n return Err(Error::new(ErrorKind::MemorySizeTooSmallError)\n\n .add_context(format!(\"Lanes: {}. Memory size: {}\", lanes, memory_size)));\n\n }\n\n if !(memory_size.is_power_of_two()) {\n\n return Err(Error::new(ErrorKind::MemorySizeInvalidError)\n\n .add_context(format!(\"Memory size: {}\", memory_size)));\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "argonautica-rs/src/config/hasher_config.rs", "rank": 31, "score": 71473.86242436315 }, { "content": "#[test]\n\n#[ignore]\n\nfn test_c_code() {\n\n let build_dir = PathBuf::from(\"tests/c/build\");\n\n build_c(&build_dir);\n\n let flags = [0b00]; // Note: for high level, cannot set flags\n\n let hash_lens = [8, 32];\n\n let iterations = [8, 32];\n\n let lane_threads = [(1, 1), (4, 4)]; // Note: for high level, lanes and threads have to be the same\n\n let memory_sizes = [32, 128];\n\n let password_lens = [8, 32];\n\n let salt_lens = [8, 32];\n\n let variants = [Variant::Argon2d, Variant::Argon2i, Variant::Argon2id];\n\n let versions = [Version::_0x10, Version::_0x13];\n\n for flags in &flags {\n\n for hash_len in &hash_lens {\n\n for iterations in &iterations {\n\n for lane_thread in &lane_threads {\n\n for memory_size in &memory_sizes {\n\n for password_len in &password_lens {\n\n for salt_len in &salt_lens {\n\n for variant in &variants {\n", "file_path": "argonautica-rs/tests/tests.rs", "rank": 32, "score": 67971.4283218132 }, { "content": "#[test]\n\nfn test_integration() {\n\n let build_dir = PathBuf::from(\"tests/c/build\");\n\n build_c(&build_dir);\n\n let additional_data_lens = [0, 32];\n\n let flags = [0b00, 0b01, 0b10, 0b11];\n\n let hash_lens = [8, 32];\n\n let iterations = [8, 16];\n\n let lane_threads = [(1, 1), (4, 4), (4, 1)];\n\n let memory_sizes = [32, 64];\n\n let password_lens = [8, 32];\n\n let salt_lens = [8, 32];\n\n let secret_key_lens = [0, 32];\n\n let variants = [Variant::Argon2d, Variant::Argon2i, Variant::Argon2id];\n\n let versions = [Version::_0x10, Version::_0x13];\n\n for flags in &flags {\n\n for additional_data_len in &additional_data_lens {\n\n for hash_len in &hash_lens {\n\n for iterations in &iterations {\n\n for lane_thread in &lane_threads {\n\n for memory_size in &memory_sizes {\n", "file_path": "argonautica-rs/tests/tests.rs", "rank": 33, "score": 67971.4283218132 }, { "content": "from typing import Union\n\n\n\nfrom argonautica.config import Backend\n\nfrom argonautica.core.ffi import ffi, lib\n\nfrom argonautica.defaults import *\n\nfrom argonautica.utils import Void, VOID\n\n\n\n\n\nclass Verifier:\n\n \"\"\"\n\n A class that knows how to verify\n\n \"\"\"\n\n __slots__ = [\n\n 'additional_data',\n\n 'backend',\n\n 'secret_key',\n\n 'threads'\n\n ]\n\n\n\n def __init__(\n\n self,\n\n *,\n\n secret_key: Union[bytes, str, None],\n\n\n\n additional_data: Union[bytes, str, None] = None,\n\n backend: Backend = DEFAULT_BACKEND,\n\n threads: int = DEFAULT_THREADS\n\n ) -> None:\n\n self.additional_data = additional_data\n\n self.secret_key = secret_key\n\n self.backend = backend\n\n self.threads = threads\n\n\n\n def verify(\n\n self,\n\n *,\n\n hash: str,\n\n password: Union[bytes, str],\n\n\n\n additional_data: Union[bytes, str, None, Void] = VOID,\n\n backend: Union[Backend, Void] = VOID,\n\n secret_key: Union[bytes, str, None, Void] = VOID,\n\n threads: Union[int, Void] = VOID\n\n ) -> bool:\n\n if isinstance(additional_data, Void):\n\n additional_data = self.additional_data\n\n if isinstance(backend, Void):\n\n backend = self.backend\n\n if isinstance(secret_key, Void):\n\n secret_key = self.secret_key\n\n if isinstance(threads, Void):\n\n threads = self.threads\n\n return verify(\n\n additional_data=additional_data,\n\n backend=backend,\n\n hash=hash,\n\n password=password,\n\n secret_key=secret_key,\n\n threads=threads\n\n )\n\n\n\n\n\ndef verify(\n\n *,\n\n hash: str,\n\n password: Union[bytes, str],\n\n secret_key: Union[bytes, str, None],\n\n\n\n additional_data: Union[bytes, str, None] = None,\n\n backend: Backend = DEFAULT_BACKEND,\n\n threads: int = DEFAULT_THREADS\n\n) -> bool:\n\n \"\"\"\n\n A standalone verify function\n\n \"\"\"\n\n # Additional data\n\n if additional_data is None:\n\n additional_data = ffi.NULL\n\n additional_data_len = 0\n\n elif isinstance(additional_data, bytes):\n\n additional_data_len = len(additional_data)\n\n elif isinstance(additional_data, str):\n\n additional_data = additional_data.encode('utf-8')\n\n additional_data_len = len(additional_data)\n\n else:\n\n raise TypeError(\"Type of additional_data must be bytes, str, or None\")\n\n\n\n # Password\n\n if isinstance(password, bytes):\n\n password_len = len(password)\n\n elif isinstance(password, str):\n\n password = password.encode('utf-8')\n\n password_len = len(password)\n\n else:\n\n raise TypeError(\"Type of password must be bytes or str\")\n\n\n\n # Secret key\n\n if secret_key is None:\n\n secret_key = ffi.NULL\n\n secret_key_len = 0\n\n elif isinstance(secret_key, bytes):\n\n secret_key_len = len(secret_key)\n\n elif isinstance(secret_key, str):\n\n secret_key = secret_key.encode('utf-8')\n\n secret_key_len = len(secret_key)\n\n else:\n\n raise TypeError(\"Type of secret_key must be bytes, str, or None\")\n\n\n\n is_valid = ffi.new(\"int*\", 0)\n\n err = lib.argonautica_verify(\n\n is_valid,\n\n additional_data,\n\n additional_data_len,\n\n hash.encode('utf-8'),\n\n password,\n\n password_len,\n\n secret_key,\n\n secret_key_len,\n\n backend.value,\n\n 0,\n\n 0,\n\n threads,\n\n )\n\n if err != lib.ARGONAUTICA_OK:\n\n error_msg_ptr = lib.argonautica_error_msg(err)\n\n error_msg = ffi.string(error_msg_ptr).decode(\"utf-8\")\n\n raise Exception(error_msg)\n\n\n\n if is_valid[0] == 1:\n\n return True\n\n\n\n return False\n", "file_path": "argonautica-py/argonautica/core/verifier.py", "rank": 34, "score": 66402.98814955515 }, { "content": "import base64\n\nfrom typing import Union\n\n\n\nfrom argonautica.config import Backend, Variant, Version\n\nfrom argonautica.core.ffi import ffi, lib\n\nfrom argonautica.data import RandomSalt\n\nfrom argonautica.defaults import *\n\nfrom argonautica.utils import Void, VOID\n\n\n\n\n\nclass Hasher:\n\n \"\"\"\n\n A class that knows how to hash\n\n \"\"\"\n\n\n\n __slots__ = [\n\n 'additional_data',\n\n 'backend',\n\n 'hash_len',\n\n 'iterations',\n\n 'lanes',\n\n 'memory_size',\n\n 'salt',\n\n 'secret_key',\n\n 'threads',\n\n 'variant',\n\n 'version'\n\n ]\n\n\n\n def __init__(\n\n self,\n\n *,\n\n secret_key: Union[bytes, str, None],\n\n\n\n additional_data: Union[bytes, str, None] = None,\n\n backend: Backend = DEFAULT_BACKEND,\n\n hash_len: int = DEFAULT_HASH_LEN,\n\n iterations: int = DEFAULT_ITERATIONS,\n\n lanes: int = DEFAULT_LANES,\n\n memory_size: int = DEFAULT_MEMORY_SIZE,\n\n salt: Union[bytes, RandomSalt, str] = DEFAULT_SALT,\n\n threads: int = DEFAULT_THREADS,\n\n variant: Variant = DEFAULT_VARIANT,\n\n version: Version = DEFAULT_VERSION\n\n ) -> None:\n\n self.additional_data = additional_data\n\n self.salt = salt\n\n self.secret_key = secret_key\n\n self.backend = backend\n\n self.hash_len = hash_len\n\n self.iterations = iterations\n\n self.lanes = lanes\n\n self.memory_size = memory_size\n\n self.threads = threads\n\n self.variant = variant\n\n self.version = version\n\n\n\n def hash(\n\n self,\n\n *,\n\n password: Union[bytes, str],\n\n\n\n additional_data: Union[bytes, str, None, Void] = VOID,\n\n backend: Union[Backend, Void] = VOID,\n\n hash_len: Union[int, Void] = VOID,\n\n iterations: Union[int, Void] = VOID,\n\n lanes: Union[int, Void] = VOID,\n\n memory_size: Union[int, Void] = VOID,\n\n salt: Union[bytes, RandomSalt, str, Void] = VOID,\n\n secret_key: Union[bytes, str, None, Void] = VOID,\n\n threads: Union[int, Void] = VOID,\n\n variant: Union[Variant, Void] = VOID,\n\n version: Union[Version, Void] = VOID\n\n ) -> str:\n\n if isinstance(additional_data, Void):\n\n additional_data = self.additional_data\n\n if isinstance(backend, Void):\n\n backend = self.backend\n\n if isinstance(hash_len, Void):\n\n hash_len = self.hash_len\n\n if isinstance(iterations, Void):\n\n iterations = self.iterations\n\n if isinstance(lanes, Void):\n\n lanes = self.lanes\n\n if isinstance(memory_size, Void):\n\n memory_size = self.memory_size\n\n if isinstance(salt, Void):\n\n salt = self.salt\n\n if isinstance(secret_key, Void):\n\n secret_key = self.secret_key\n\n if isinstance(threads, Void):\n\n threads = self.threads\n\n if isinstance(variant, Void):\n\n variant = self.variant\n\n if isinstance(version, Void):\n\n version = self.version\n\n return hash(\n\n additional_data=additional_data,\n\n backend=backend,\n\n hash_len=hash_len,\n\n iterations=iterations,\n\n lanes=lanes,\n\n memory_size=memory_size,\n\n password=password,\n\n salt=salt,\n\n secret_key=secret_key,\n\n threads=threads,\n\n variant=variant,\n\n version=version\n\n )\n\n\n\n\n\ndef hash(\n\n *,\n\n password: Union[bytes, str],\n\n secret_key: Union[bytes, str, None],\n\n\n\n additional_data: Union[bytes, str, None] = None,\n\n backend: Backend = DEFAULT_BACKEND,\n\n hash_len: int = DEFAULT_HASH_LEN,\n\n iterations: int = DEFAULT_ITERATIONS,\n\n lanes: int = DEFAULT_LANES,\n\n memory_size: int = DEFAULT_MEMORY_SIZE,\n\n salt: Union[bytes, RandomSalt, str] = DEFAULT_SALT,\n\n threads: int = DEFAULT_THREADS,\n\n variant: Variant = DEFAULT_VARIANT,\n\n version: Version = DEFAULT_VERSION\n\n) -> str:\n\n \"\"\"\n\n A standalone hash function\n\n \"\"\"\n\n data = Validator(\n\n additional_data=additional_data,\n\n password=password,\n\n salt=salt,\n\n secret_key=secret_key,\n\n )\n\n encoded_len = lib.argonautica_encoded_len(\n\n hash_len,\n\n iterations,\n\n lanes,\n\n memory_size,\n\n data.salt_len,\n\n variant.value,\n\n )\n\n if encoded_len < 0:\n\n raise Exception(\"Error calculating length of string-encoded hash\")\n\n encoded = ffi.new(\"char[]\", b'\\0'*encoded_len)\n\n err = lib.argonautica_hash(\n\n encoded,\n\n data.additional_data,\n\n data.additional_data_len,\n\n data.password,\n\n data.password_len,\n\n data.salt,\n\n data.salt_len,\n\n data.secret_key,\n\n data.secret_key_len,\n\n backend.value,\n\n hash_len,\n\n iterations,\n\n lanes,\n\n memory_size,\n\n 0,\n\n 0,\n\n threads,\n\n variant.value,\n\n version.value,\n\n )\n\n if err != lib.ARGONAUTICA_OK:\n\n error_msg_ptr = lib.argonautica_error_msg(err)\n\n error_msg = ffi.string(error_msg_ptr).decode(\"utf-8\")\n\n raise Exception(error_msg)\n\n hash = ffi.string(encoded).decode(\"utf-8\")\n\n return hash\n\n\n\n\n\nclass Validator:\n\n def __init__(\n\n self,\n\n *,\n\n additional_data: Union[bytes, str, None],\n\n password: Union[bytes, str],\n\n salt: Union[bytes, RandomSalt, str],\n\n secret_key: Union[bytes, str, None]\n\n ) -> None:\n\n if additional_data is None:\n\n self.additional_data = ffi.NULL\n\n self.additional_data_len = 0\n\n elif isinstance(additional_data, bytes):\n\n self.additional_data = additional_data\n\n self.additional_data_len = len(self.additional_data)\n\n elif isinstance(additional_data, str):\n\n self.additional_data = additional_data.encode('utf-8')\n\n self.additional_data_len = len(self.additional_data)\n\n else:\n\n raise TypeError(\"Type of additional_data must be bytes, str, or None\")\n\n\n\n if isinstance(password, bytes):\n\n self.password = password\n\n self.password_len = len(self.password)\n\n elif isinstance(password, str):\n\n self.password = password.encode(\"utf-8\")\n\n self.password_len = len(self.password)\n\n else:\n\n raise TypeError(\"Type of password must be bytes or str\")\n\n\n\n if isinstance(salt, RandomSalt):\n\n self.salt = ffi.NULL\n\n self.salt_len = salt.len\n\n elif isinstance(salt, bytes):\n\n self.salt = salt\n\n self.salt_len = len(self.salt)\n\n elif isinstance(salt, str):\n\n self.salt = salt.encode('utf-8')\n\n self.salt_len = len(self.salt)\n\n else:\n\n raise TypeError(\"Type of salt must be bytes, RandomSalt, or str\")\n\n\n\n if secret_key is None:\n\n self.secret_key = ffi.NULL\n\n self.secret_key_len = 0\n\n elif isinstance(secret_key, bytes):\n\n self.secret_key = secret_key\n\n self.secret_key_len = len(self.secret_key)\n\n elif isinstance(secret_key, str):\n\n self.secret_key = secret_key.encode('utf-8')\n\n self.secret_key_len = len(self.secret_key)\n\n else:\n\n raise TypeError(\"Type of secret_key must be bytes, str, or None\")\n\n\n\n def __repr__(self) -> str:\n\n return str(self.__dict__)\n", "file_path": "argonautica-py/argonautica/core/hasher.py", "rank": 35, "score": 66356.29501657985 }, { "content": "from argonautica import Verifier\n\n\n\nverifier = Verifier(secret_key='somesecret')\n\nis_valid = verifier.verify(\n\n hash='$argon2id$v=19$m=4096,t=192,p=4$n7F2qAECNLz7En4d9MsC6HIPWKiFZ5BHopIvoF1CBPs$Uk+pYp97ySGgal1OcrKfcA',\n\n password='P@ssw0rd',\n\n)\n\nassert(is_valid)\n", "file_path": "argonautica-py/examples/verifier.py", "rank": 36, "score": 62988.21812898883 }, { "content": "from argonautica import Hasher\n\n\n\nhasher = Hasher(secret_key='somesecret', hash_len=16)\n\nhash = hasher.hash(password='P@ssw0rd')\n\nprint(hash)\n", "file_path": "argonautica-py/examples/hasher.py", "rank": 37, "score": 62940.1039446409 }, { "content": "from argonautica import Hasher\n\nfrom argonautica.data import RandomSalt\n\n\n\nhasher = Hasher(\n\n salt=RandomSalt(16),\n\n # 👆 Here we're using a RandomSalt of length of 16 bytes\n\n # instead of the default, which is a RandomSalt of length 32 bytes\n\n secret_key=\"somesecret\"\n\n)\n\nhash = hasher.hash(password='P@ssw0rd')\n\nprint(hash)\n", "file_path": "argonautica-py/examples/random_salt.py", "rank": 38, "score": 62211.04631112622 }, { "content": "fn test_c(input: &Input) {\n\n let args = generate_args(input);\n\n let args = args.iter().map(|s| (*s).as_ref()).collect::<Vec<&str>>();\n\n\n\n // Run C without simd\n\n let stderr = run_c(\"./test_high_level\", &input.build_dir, &args);\n\n let (encoded1, encoded2, hash1, hash2) = parse_stderr_c(&stderr);\n\n\n\n // Run C with simd\n\n let stderr = run_c(\"./test_high_level_simd\", &input.build_dir, &args);\n\n let (encoded3, encoded4, hash3, hash4) = parse_stderr_c(&stderr);\n\n\n\n // Print results\n\n println!(\"{}\", &encoded1);\n\n println!(\"{}\", &encoded2);\n\n println!(\"{}\", &encoded3);\n\n println!(\"{}\", &encoded4);\n\n println!(\"{:?}\", &hash1);\n\n println!(\"{:?}\", &hash2);\n\n println!(\"{:?}\", &hash3);\n", "file_path": "argonautica-rs/tests/tests.rs", "rank": 39, "score": 59119.582714158496 }, { "content": "fn test(input: &Input) {\n\n let args = generate_args(input);\n\n let args = args.iter().map(|s| (*s).as_ref()).collect::<Vec<&str>>();\n\n\n\n // Run C without simd\n\n let stderr = run_c(\"./test_low_level\", &input.build_dir, &args);\n\n let (encoded1, hash1) = parse_stderr(&stderr);\n\n\n\n // Run C with simd\n\n let stderr = run_c(\"./test_low_level_simd\", &input.build_dir, &args);\n\n let (encoded2, hash2) = parse_stderr(&stderr);\n\n\n\n // Hash Rust\n\n let password_clearing = (input.flags & 0b01) == 1;\n\n let secret_key_clearing = ((input.flags >> 1) & 0b1) == 1;\n\n let mut hasher = Hasher::default();\n\n hasher\n\n .configure_hash_len(input.hash_len)\n\n .configure_iterations(input.iterations)\n\n .configure_lanes(input.lanes)\n", "file_path": "argonautica-rs/tests/tests.rs", "rank": 40, "score": 59119.582714158496 }, { "content": "/// A utility function for generating a cryptographically-secure, random, base64-encoded string\n\n/// based on a custom base64 encoding (e.g. a\n\n/// [url-safe encoding](https://docs.rs/base64/0.9.1/base64/constant.URL_SAFE.html)).\n\n/// A quick glance at this function's source should give you a good idea of what the\n\n/// function is doing.\n\npub fn generate_random_base64_encoded_string_config(\n\n len: u32,\n\n config: base64::Config,\n\n) -> Result<String, Error> {\n\n let mut bytes = vec![0u8; len as usize];\n\n OsRng\n\n .try_fill_bytes(&mut bytes)\n\n .map_err(|e| Error::new(ErrorKind::OsRngError).add_context(format!(\"{}\", e)))?;\n\n let output = base64::encode_config(&bytes, config);\n\n Ok(output)\n\n}\n", "file_path": "argonautica-rs/src/utils.rs", "rank": 41, "score": 58009.5742502561 }, { "content": "#[inline(always)]\n\npub fn default_lanes() -> u32 {\n\n num_cpus::get() as u32\n\n}\n\n\n\n/// Returns the number of logical cores on your machine\n", "file_path": "argonautica-rs/src/config/defaults.rs", "rank": 42, "score": 56848.96093079412 }, { "content": "#[inline(always)]\n\npub fn default_threads() -> u32 {\n\n num_cpus::get() as u32\n\n}\n\n\n\n/// [`Backend::C`](enum.Backend.html#variant.C)\n\npub const DEFAULT_BACKEND: Backend = Backend::C;\n\n\n\n/// `32_u32`\n\npub const DEFAULT_HASH_LEN: u32 = 32;\n\n\n\n/// `192_u32`\n\npub const DEFAULT_ITERATIONS: u32 = 192;\n\n\n\n/// `4096_u32`\n\npub const DEFAULT_MEMORY_SIZE: u32 = 4_096;\n\n\n\n/// `false`\n\npub const DEFAULT_OPT_OUT_OF_SECRET_KEY: bool = false;\n\n\n\n/// `false`\n", "file_path": "argonautica-rs/src/config/defaults.rs", "rank": 43, "score": 56848.96093079412 }, { "content": "fn base64_len(len: u32) -> usize {\n\n let bits = 8 * len as usize;\n\n let chars = bits / 6 + if bits % 6 != 0 { 1 } else { 0 };\n\n chars\n\n}\n\n\n\n/// Function that returns the length of a string-encoded hash (in bytes and including the NULL byte).\n\n/// If an error occurrs, the function returns -1\n\n#[no_mangle]\n\npub extern \"C\" fn argonautica_encoded_len(\n\n hash_len: u32,\n\n iterations: u32,\n\n lanes: u32,\n\n memory_size: u32,\n\n salt_len: u32,\n\n variant: argonautica_variant_t,\n\n) -> c_int {\n\n let mut buf = [0u8; 1024];\n\n\n\n let fixed_len = 17; // $$$$$v=19m=t=p=,,\n", "file_path": "argonautica-c/src/utils.rs", "rank": 44, "score": 55548.73651674787 }, { "content": "#[inline(always)]\n\npub fn default_cpu_pool() -> CpuPool {\n\n CpuPool::new(num_cpus::get())\n\n}\n\n\n\n#[cfg(feature = \"serde\")]\n\npub(crate) fn default_cpu_pool_serde() -> Option<CpuPool> {\n\n None\n\n}\n\n\n\n/// Returns the number of logical cores on your machine\n", "file_path": "argonautica-rs/src/config/defaults.rs", "rank": 45, "score": 54824.75641844671 }, { "content": "fn generate_args(input: &Input) -> Vec<String> {\n\n let rng = rand::thread_rng();\n\n let additional_data = if input.additional_data_len == 0 {\n\n \"\".to_string()\n\n } else {\n\n rng.sample_iter(&Alphanumeric)\n\n .take(input.additional_data_len)\n\n .collect::<String>()\n\n };\n\n let secret_key = if input.secret_key_len == 0 {\n\n \"\".to_string()\n\n } else {\n\n rng.sample_iter(&Alphanumeric)\n\n .take(input.secret_key_len)\n\n .collect::<String>()\n\n };\n\n let password = rng\n\n .sample_iter(&Alphanumeric)\n\n .take(input.password_len)\n\n .collect::<String>();\n", "file_path": "argonautica-rs/tests/tests.rs", "rank": 46, "score": 51530.40975410868 }, { "content": "def verify(\n\n *,\n\n hash: str,\n\n password: Union[bytes, str],\n\n secret_key: Union[bytes, str, None],\n\n\n\n additional_data: Union[bytes, str, None] = None,\n\n backend: Backend = DEFAULT_BACKEND,\n\n threads: int = DEFAULT_THREADS\n\n) -> bool:\n\n \"\"\"\n\n A standalone verify function\n\n \"\"\"\n\n # Additional data\n\n if additional_data is None:\n\n additional_data = ffi.NULL\n\n additional_data_len = 0\n\n elif isinstance(additional_data, bytes):\n\n additional_data_len = len(additional_data)\n\n elif isinstance(additional_data, str):\n\n additional_data = additional_data.encode('utf-8')\n\n additional_data_len = len(additional_data)\n\n else:\n\n raise TypeError(\"Type of additional_data must be bytes, str, or None\")\n\n\n\n # Password\n\n if isinstance(password, bytes):\n\n password_len = len(password)\n\n elif isinstance(password, str):\n\n password = password.encode('utf-8')\n\n password_len = len(password)\n\n else:\n\n raise TypeError(\"Type of password must be bytes or str\")\n\n\n\n # Secret key\n\n if secret_key is None:\n\n secret_key = ffi.NULL\n\n secret_key_len = 0\n\n elif isinstance(secret_key, bytes):\n\n secret_key_len = len(secret_key)\n\n elif isinstance(secret_key, str):\n\n secret_key = secret_key.encode('utf-8')\n\n secret_key_len = len(secret_key)\n\n else:\n\n raise TypeError(\"Type of secret_key must be bytes, str, or None\")\n\n\n\n is_valid = ffi.new(\"int*\", 0)\n\n err = lib.argonautica_verify(\n\n is_valid,\n\n additional_data,\n\n additional_data_len,\n\n hash.encode('utf-8'),\n\n password,\n\n password_len,\n\n secret_key,\n\n secret_key_len,\n\n backend.value,\n\n 0,\n\n 0,\n\n threads,\n\n )\n\n if err != lib.ARGONAUTICA_OK:\n\n error_msg_ptr = lib.argonautica_error_msg(err)\n\n error_msg = ffi.string(error_msg_ptr).decode(\"utf-8\")\n\n raise Exception(error_msg)\n\n\n\n if is_valid[0] == 1:\n\n return True\n\n\n", "file_path": "argonautica-py/argonautica/core/verifier.py", "rank": 47, "score": 49268.13910933847 }, { "content": "class Verifier:\n\n \"\"\"\n\n A class that knows how to verify\n\n \"\"\"\n\n __slots__ = [\n\n 'additional_data',\n\n 'backend',\n\n 'secret_key',\n\n 'threads'\n\n ]\n\n\n\n def __init__(\n\n self,\n\n *,\n\n secret_key: Union[bytes, str, None],\n\n\n\n additional_data: Union[bytes, str, None] = None,\n\n backend: Backend = DEFAULT_BACKEND,\n\n threads: int = DEFAULT_THREADS\n\n ) -> None:\n\n self.additional_data = additional_data\n\n self.secret_key = secret_key\n\n self.backend = backend\n\n self.threads = threads\n\n\n\n def verify(\n\n self,\n\n *,\n\n hash: str,\n\n password: Union[bytes, str],\n\n\n\n additional_data: Union[bytes, str, None, Void] = VOID,\n\n backend: Union[Backend, Void] = VOID,\n\n secret_key: Union[bytes, str, None, Void] = VOID,\n\n threads: Union[int, Void] = VOID\n\n ) -> bool:\n\n if isinstance(additional_data, Void):\n\n additional_data = self.additional_data\n\n if isinstance(backend, Void):\n\n backend = self.backend\n\n if isinstance(secret_key, Void):\n\n secret_key = self.secret_key\n\n if isinstance(threads, Void):\n\n threads = self.threads\n\n return verify(\n\n additional_data=additional_data,\n\n backend=backend,\n\n hash=hash,\n\n password=password,\n\n secret_key=secret_key,\n\n threads=threads\n", "file_path": "argonautica-py/argonautica/core/verifier.py", "rank": 48, "score": 49268.13910933847 }, { "content": "fn build_c<P: AsRef<Path>>(build_dir: P) {\n\n let mut build_exists = BUILD_EXISTS.lock().unwrap();\n\n if *build_exists {\n\n return;\n\n }\n\n let build_dir = build_dir.as_ref();\n\n if build_dir.exists() {\n\n ::std::fs::remove_dir_all(build_dir).expect(\"unable to remove build dir\");\n\n }\n\n ::std::fs::create_dir_all(build_dir).expect(\"unable to create build dir\");\n\n let success = Command::new(\"cmake\")\n\n .arg(\"..\")\n\n .current_dir(build_dir)\n\n .status()\n\n .unwrap()\n\n .success();\n\n if !success {\n\n panic!(\"cmake failed\");\n\n }\n\n assert!(success);\n", "file_path": "argonautica-rs/tests/tests.rs", "rank": 49, "score": 49040.491071325014 }, { "content": "fn parse_stderr(stderr: &[u8]) -> (String, Vec<u8>) {\n\n let stderr = ::std::str::from_utf8(stderr).expect(\"stderr from C is invalid utf-8\");\n\n let v = stderr.trim().split(\"\\n\").collect::<Vec<&str>>();\n\n if v.len() != 2 {\n\n panic!(\"invalid stderr from C: {}\", stderr);\n\n }\n\n let encoded = v[0].to_string();\n\n let hash = v[1]\n\n .replace(\"[\", \"\")\n\n .replace(\"]\", \"\")\n\n .split(\",\")\n\n .into_iter()\n\n .map(|s| Ok::<_, failure::Error>(s.parse::<u8>()?))\n\n .collect::<Result<Vec<u8>, failure::Error>>()\n\n .expect(\"unable to parse hash from C stderr\");\n\n (encoded, hash)\n\n}\n\n\n", "file_path": "argonautica-rs/tests/tests.rs", "rank": 50, "score": 49040.491071325014 }, { "content": "verify_result_t verify_high_level(verify_input_t* input)\n\n{\n\n int err = argon2_verify(\n\n /* const char* encoded */ input->encoded,\n\n /* const void* pwd */ (void*)(input->password),\n\n /* const size_t pwdlen */ input->password_len,\n\n /* argon2_type type */ input->variant\n\n );\n\n verify_result_t output = {};\n\n output.err = err;\n\n if (err == ARGON2_OK) {\n\n output.is_valid = true;\n\n return output;\n\n } else {\n\n output.is_valid = false;\n\n return output;\n\n }\n", "file_path": "argonautica-rs/tests/c/src/verify.c", "rank": 51, "score": 47813.56930715432 }, { "content": "verify_result_t verify_low_level(verify_input_t* input)\n\n{\n\n verify_result_t output = {};\n\n if (input->password_len > ARGON2_MAX_PWD_LENGTH) {\n\n output.err = ARGON2_PWD_TOO_LONG;\n\n output.is_valid = false;\n\n return output;\n\n }\n\n if (input->encoded == NULL) {\n\n output.err = ARGON2_DECODING_FAIL;\n\n output.is_valid = false;\n\n return output;\n\n }\n\n size_t encoded_len = strlen(input->encoded);\n\n if (encoded_len > UINT32_MAX) {\n\n output.err = ARGON2_DECODING_FAIL;\n\n output.is_valid = false;\n\n return output;\n\n }\n\n\n\n argon2_context ctx = {};\n\n ctx.saltlen = (uint32_t)encoded_len;\n\n ctx.outlen = (uint32_t)encoded_len;\n\n\n\n ctx.salt = (uint8_t*)malloc(ctx.saltlen);\n\n ctx.out = (uint8_t*)malloc(ctx.outlen);\n\n if (ctx.salt == NULL || ctx.out == NULL) {\n\n free(ctx.out);\n\n free(ctx.salt);\n\n output.err = ARGON2_MEMORY_ALLOCATION_ERROR;\n\n output.is_valid = false;\n\n return output;\n\n }\n\n\n\n ctx.pwd = (uint8_t*)(input->password);\n\n ctx.pwdlen = (uint32_t)(input->password_len);\n\n\n\n int err = decode_string( // Note: Located in encoding.c\n\n /* argon2_context* ctx */ &ctx,\n\n /* const char* str */ input->encoded,\n\n /* argon2_type type */ input->variant\n\n );\n\n if (err != ARGON2_OK) {\n\n free(ctx.out);\n\n free(ctx.salt);\n\n output.err = err;\n\n output.is_valid = false;\n\n return output;\n\n }\n\n\n\n uint8_t* desired_result = ctx.out;\n\n ctx.out = (uint8_t*)malloc(ctx.outlen);\n\n if (ctx.out == NULL) {\n\n free(ctx.out);\n\n free(ctx.salt);\n\n free(desired_result);\n\n output.err = ARGON2_MEMORY_ALLOCATION_ERROR;\n\n output.is_valid = false;\n\n return output;\n\n }\n\n\n\n // This is my code\n\n ctx.ad = input->additional_data;\n\n ctx.adlen = (size_t)(input->additional_data_len);\n\n ctx.secret = input->secret_key;\n\n ctx.secretlen = (size_t)(input->secret_key_len);\n\n\n\n err = my_argon2_verify_ctx(\n\n /* argon2_context* context */ &ctx,\n\n /* const char* encoded */ (char *)desired_result,\n\n /* argon2_type variant */ input->variant\n\n );\n\n if (err != ARGON2_OK) {\n\n free(ctx.out);\n\n free(ctx.salt);\n\n free(desired_result);\n\n output.err = err;\n\n output.is_valid = false;\n\n return output;\n\n }\n\n\n\n free(ctx.out);\n\n free(ctx.salt);\n\n free(desired_result);\n\n output.err = ARGON2_OK;\n\n output.is_valid = true;\n\n return output;\n", "file_path": "argonautica-rs/tests/c/src/verify.c", "rank": 52, "score": 47813.56930715432 }, { "content": "static int my_argon2_verify_ctx(argon2_context* context, const char* hash, argon2_type type);\n", "file_path": "argonautica-rs/tests/c/src/verify.c", "rank": 53, "score": 47813.56930715432 }, { "content": "fn check_error(err: ffi::Argon2_ErrorCodes) -> Result<(), Error> {\n\n match err {\n\n ffi::Argon2_ErrorCodes_ARGON2_OK => Ok(()),\n\n ffi::Argon2_ErrorCodes_ARGON2_MEMORY_ALLOCATION_ERROR => {\n\n Err(Error::new(ErrorKind::MemoryAllocationError))\n\n }\n\n ffi::Argon2_ErrorCodes_ARGON2_THREAD_FAIL => Err(Error::new(ErrorKind::ThreadError)),\n\n _ => {\n\n let err_msg_ptr = unsafe { ffi::argon2_error_message(err) };\n\n if err_msg_ptr.is_null() {\n\n return Err(Error::new(ErrorKind::Bug)\n\n .add_context(format!(\"Unhandled error from C. Error code: {}\", err,)));\n\n }\n\n let err_msg_cstr = unsafe { CStr::from_ptr(err_msg_ptr) };\n\n let err_msg = err_msg_cstr.to_str().unwrap(); // Safe; see argon2_error_message\n\n Err(Error::new(ErrorKind::Bug).add_context(format!(\n\n \"Unhandled error from C. Error code: {}. Error {}\",\n\n err, err_msg,\n\n )))\n\n }\n\n }\n\n}\n", "file_path": "argonautica-rs/src/backend/c/hash_raw.rs", "rank": 54, "score": 45586.58885538786 }, { "content": "#![allow(non_camel_case_types)]\n\n\n\nuse std::ffi::CStr;\n\n\n\nuse argonautica::config::Backend;\n\nuse argonautica::Verifier;\n\nuse libc::{c_char, c_int};\n\n\n\nuse {argonautica_backend_t, argonautica_error_t};\n\n\n\n/// Function that verifies a password against a hash. It will modify the provided `is_valid` int\n\n/// and return an `argonautica_error_t` indicating whether or not the verification was successful.\n\n///\n\n/// On success, `is_valid` will be modified to be `1` if the hash / password combination is valid\n\n/// or `0` if the hash / password combination is not valid.\n\n///\n\n/// `encoded` is a `char*` pointing to the string-encoded hash.\n\n///\n\n/// For a description of the other arguments, see the documentation for\n\n/// `argonautica_hash`\n", "file_path": "argonautica-c/src/verify.rs", "rank": 55, "score": 44924.83701522577 }, { "content": " let password_clearing = if password_clearing == 0 { false } else { true };\n\n let secret_key_clearing = if secret_key_clearing == 0 {\n\n false\n\n } else {\n\n true\n\n };\n\n\n\n let mut verifier = Verifier::default();\n\n verifier\n\n .configure_backend(backend)\n\n .configure_password_clearing(password_clearing)\n\n .configure_secret_key_clearing(secret_key_clearing)\n\n .configure_threads(threads);\n\n\n\n // Hash\n\n let encoded_cstr = unsafe { CStr::from_ptr(encoded) };\n\n let encoded = match encoded_cstr.to_str() {\n\n Ok(encoded) => encoded,\n\n Err(_) => return argonautica_error_t::ARGONAUTICA_ERROR_UTF8_ENCODE,\n\n };\n", "file_path": "argonautica-c/src/verify.rs", "rank": 56, "score": 44923.73418168585 }, { "content": "#[no_mangle]\n\npub extern \"C\" fn argonautica_verify(\n\n is_valid: *mut c_int,\n\n additional_data: *const u8,\n\n additional_data_len: u32,\n\n encoded: *const c_char,\n\n password: *mut u8,\n\n password_len: u32,\n\n secret_key: *mut u8,\n\n secret_key_len: u32,\n\n backend: argonautica_backend_t,\n\n password_clearing: c_int,\n\n secret_key_clearing: c_int,\n\n threads: u32,\n\n) -> argonautica_error_t {\n\n if is_valid.is_null() || encoded.is_null() || password.is_null() {\n\n return argonautica_error_t::ARGONAUTICA_ERROR_NULL_PTR;\n\n }\n\n\n\n let backend: Backend = backend.into();\n", "file_path": "argonautica-c/src/verify.rs", "rank": 57, "score": 44923.70473513768 }, { "content": " let valid = match verifier.verify() {\n\n Ok(valid) => valid,\n\n Err(e) => return e.into(),\n\n };\n\n\n\n if valid {\n\n unsafe {\n\n *is_valid = 1;\n\n };\n\n } else {\n\n unsafe {\n\n *is_valid = 0;\n\n };\n\n }\n\n\n\n argonautica_error_t::ARGONAUTICA_OK\n\n}\n", "file_path": "argonautica-c/src/verify.rs", "rank": 58, "score": 44918.40197994495 }, { "content": " verifier.with_hash(encoded);\n\n\n\n // Additional data\n\n if !additional_data.is_null() {\n\n let additional_data =\n\n unsafe { ::std::slice::from_raw_parts(additional_data, additional_data_len as usize) };\n\n verifier.with_additional_data(additional_data);\n\n }\n\n\n\n // Password\n\n let password = unsafe { ::std::slice::from_raw_parts_mut(password, password_len as usize) };\n\n verifier.with_password(password);\n\n\n\n // Secret key\n\n if !secret_key.is_null() {\n\n let secret_key =\n\n unsafe { ::std::slice::from_raw_parts_mut(secret_key, secret_key_len as usize) };\n\n verifier.with_secret_key(secret_key);\n\n }\n\n\n", "file_path": "argonautica-c/src/verify.rs", "rank": 59, "score": 44917.407496489795 }, { "content": "/// A utility function for generating a cryptographically-secure, random, base64-encoded string\n\n/// based on\n\n/// [standard base64 encoding](https://docs.rs/base64/0.9.1/base64/constant.STANDARD.html).\n\n/// A quick glance at this function's source should give you a good idea of what the function\n\n/// is doing.\n\npub fn generate_random_base64_encoded_string(len: u32) -> Result<String, Error> {\n\n let mut bytes = vec![0u8; len as usize];\n\n OsRng\n\n .try_fill_bytes(&mut bytes)\n\n .map_err(|e| Error::new(ErrorKind::OsRngError).add_context(format!(\"{}\", e)))?;\n\n let output = base64::encode_config(&bytes, base64::STANDARD);\n\n Ok(output)\n\n}\n\n\n", "file_path": "argonautica-rs/src/utils.rs", "rank": 60, "score": 44351.00834677747 }, { "content": "/// A utility function for generating cryptographically-secure random bytes. A quick glance at\n\n/// this function's source should give you a good idea of what the function is doing.\n\npub fn generate_random_bytes(len: u32) -> Result<Vec<u8>, Error> {\n\n let mut bytes = vec![0u8; len as usize];\n\n OsRng\n\n .try_fill_bytes(&mut bytes)\n\n .map_err(|e| Error::new(ErrorKind::OsRngError).add_context(format!(\"{}\", e)))?;\n\n Ok(bytes)\n\n}\n\n\n", "file_path": "argonautica-rs/src/utils.rs", "rank": 61, "score": 44117.5204496145 }, { "content": " fn test_serialize() {\n\n use serde;\n\n fn assert_serialize<T: serde::Serialize>() {}\n\n assert_serialize::<Verifier>();\n\n }\n\n\n\n #[cfg(feature = \"serde\")]\n\n #[test]\n\n fn test_deserialize() {\n\n use serde;\n\n fn assert_deserialize<'de, T: serde::Deserialize<'de>>() {}\n\n assert_deserialize::<Verifier>();\n\n }\n\n}\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 62, "score": 43428.62819256038 }, { "content": " self.hasher.secret_key()\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[cfg(feature = \"serde\")]\n\n #[test]\n\n fn test_verifier_serialization() {\n\n use serde_json;\n\n\n\n let password = \"P@ssw0rd\";\n\n let secret_key = \"secret\";\n\n\n\n let mut hasher = Hasher::default();\n\n hasher\n\n .configure_password_clearing(false)\n\n .configure_secret_key_clearing(false)\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 63, "score": 43427.46631768084 }, { "content": " Raw(HashRaw),\n\n None,\n\n}\n\n\n\nimpl<'a> Default for Verifier<'a> {\n\n /// Same as the [`new`](struct.Verifier.html#method.new) method\n\n fn default() -> Verifier<'a> {\n\n Verifier {\n\n hash: Hash::default(),\n\n hasher: Hasher::default(),\n\n }\n\n }\n\n}\n\n\n\n/// <b><u>One of the two main structs.</u></b> Use it to verify passwords against hashes\n\n#[derive(Debug)]\n\n#[cfg_attr(feature = \"serde\", derive(Serialize, Deserialize))]\n\n#[cfg_attr(feature = \"serde\", serde(rename_all = \"camelCase\"))]\n\npub struct Verifier<'a> {\n\n hash: Hash,\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 64, "score": 43427.20002985507 }, { "content": " hash_raw.to_string(),\n\n password.as_bytes(),\n\n \"secret\".as_bytes()\n\n );\n\n };\n\n\n\n // Serialize Verifier\n\n let j = serde_json::to_string_pretty(&verifier1).expect(\"failed to serialize verifier\");\n\n // Deserialize Verifier\n\n let mut verifier2: Verifier =\n\n serde_json::from_str(&j).expect(\"failed to deserialize verifier\");\n\n // Assert that password and secret key have been erased\n\n assert!(verifier2.password().is_none());\n\n assert!(verifier2.secret_key().is_none());\n\n // Add a password and ensure that verify doesn't return an error\n\n verifier2.with_password(password);\n\n let is_valid = verifier2.verify().unwrap();\n\n assert!(!is_valid);\n\n // Add a secret key and ensure that verify returns is_valid\n\n verifier2.with_secret_key(secret_key);\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 65, "score": 43426.33964842312 }, { "content": "use futures::Future;\n\nuse futures_cpupool::CpuPool;\n\n\n\nuse backend::decode_rust;\n\nuse config::{default_cpu_pool, Backend, VerifierConfig};\n\nuse input::{AdditionalData, Password, SecretKey};\n\nuse output::HashRaw;\n\nuse {Error, ErrorKind, Hasher};\n\n\n\nimpl Default for Hash {\n\n fn default() -> Hash {\n\n Hash::None\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\n#[cfg_attr(feature = \"serde\", derive(Serialize, Deserialize))]\n\n#[cfg_attr(feature = \"serde\", serde(rename_all = \"camelCase\"))]\n\npub enum Hash {\n\n Encoded(String),\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 66, "score": 43424.83722973414 }, { "content": " let mut verifier = self.to_owned();\n\n match verifier.hasher.config.cpu_pool() {\n\n Some(cpu_pool) => cpu_pool.spawn_fn(move || verifier.verify()),\n\n None => {\n\n let cpu_pool = default_cpu_pool();\n\n verifier.hasher.config.set_cpu_pool(cpu_pool.clone());\n\n cpu_pool.spawn_fn(move || verifier.verify())\n\n }\n\n }\n\n }\n\n /// Allows you to provide [`Verifier`](struct.Verifier.html) with the additional data\n\n /// that was originally used to create the hash. Normally hashes are not created with\n\n /// additional data; so you are not likely to need this method\n\n pub fn with_additional_data<AD>(&mut self, additional_data: AD) -> &mut Verifier<'a>\n\n where\n\n AD: Into<AdditionalData>,\n\n {\n\n self.hasher.additional_data = Some(additional_data.into());\n\n self\n\n }\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 67, "score": 43424.138710143816 }, { "content": " self\n\n }\n\n /// Allows you to configure [`Verifier`](struct.Verifier.html) to use a custom number of\n\n /// threads. The default is the number of physical cores on your machine. If you choose\n\n /// a number of threads that is greater than the lanes configuration of your hash,\n\n /// [`Verifier`](struct.Verifier.html) will use the minimum of the two.\n\n pub fn configure_threads(&mut self, threads: u32) -> &mut Verifier<'a> {\n\n self.hasher.config.set_threads(threads);\n\n self\n\n }\n\n /// Clones the [`Verifier`](struct.Verifier.html), returning a new\n\n /// [`Verifier`](struct.Verifier.html) with a `static` lifetime. Use this method if you\n\n /// would like to move a [`Verifier`](struct.Verifier.html) to another thread\n\n pub fn to_owned(&self) -> Verifier<'static> {\n\n Verifier {\n\n hash: self.hash.clone(),\n\n hasher: self.hasher.to_owned(),\n\n }\n\n }\n\n /// <b><u>The primary method (blocking version)</u></b>\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 68, "score": 43421.621702843164 }, { "content": " /// or its non-blocking equivalent. The default is to <b>not</b> clear out the password\n\n /// bytes (i.e. `false`). If you set this option to `true`, you must provide\n\n /// [`Verifier`](struct.Verifier.html) with a mutable password, e.g. a password\n\n /// constructed from a `String`, `Vec<u8>`, `&mut str`, `&mut [u8]`, etc. as opposed to\n\n /// one constructed from a `&str`, `&[u8]`, etc., or else verifying will return an\n\n /// [`Error`](struct.Error.html).\n\n pub fn configure_password_clearing(&mut self, boolean: bool) -> &mut Verifier<'a> {\n\n self.hasher.config.set_password_clearing(boolean);\n\n self\n\n }\n\n /// Allows you to configure [`Verifier`](struct.Verifier.html) to erase the secret key bytes\n\n /// after each call to [`verify`](struct.Verifier.html#method.verify)\n\n /// or its non-blocking equivalent. The default is to <b>not</b> clear out the secret key\n\n /// bytes (i.e. `false`). If you set this option to `true`, you must provide\n\n /// [`Verifier`](struct.Verifier.html) with a mutable secret key, e.g. a secret key\n\n /// constructed from a `String`, `Vec<u8>`, `&mut str`, `&mut [u8]`, etc. as opposed to\n\n /// one constructed from a `&str`, `&[u8]`, etc., or else verifying will return an\n\n /// [`Error`](struct.Error.html).\n\n pub fn configure_secret_key_clearing(&mut self, boolean: bool) -> &mut Verifier<'a> {\n\n self.hasher.config.set_secret_key_clearing(boolean);\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 69, "score": 43421.51318012146 }, { "content": " }\n\n /// Allows you to provide [`Verifier`](struct.Verifier.html) with the password\n\n /// to verify against\n\n pub fn with_password<P>(&mut self, password: P) -> &mut Verifier<'a>\n\n where\n\n P: Into<Password<'a>>,\n\n {\n\n self.hasher.password = Some(password.into());\n\n self\n\n }\n\n /// Allows you to provide [`Verifier`](struct.Verifier.html) with the secret key\n\n /// that was initially used to create the hash\n\n pub fn with_secret_key<SK>(&mut self, secret_key: SK) -> &mut Verifier<'a>\n\n where\n\n SK: Into<SecretKey<'a>>,\n\n {\n\n self.hasher.secret_key = Some(secret_key.into());\n\n self\n\n }\n\n /// Read-only access to the [`Verifier`](struct.Verifier.html)'s\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 70, "score": 43421.387144958164 }, { "content": " /// Allows you to provide [`Verifier`](struct.Verifier.html) with the hash to verify\n\n /// against (in the form of a string-encoded hash like those produced by the\n\n /// [`hash`](struct.Hasher.html#method.hash) or\n\n /// [`hash_non_blocking`](struct.Hasher.html#method.hash_non_blocking)\n\n /// methods on [`Hasher`](struct.Hasher.html))\n\n pub fn with_hash<S>(&mut self, hash: S) -> &mut Verifier<'a>\n\n where\n\n S: AsRef<str>,\n\n {\n\n self.hash = Hash::Encoded(hash.as_ref().to_string());\n\n self\n\n }\n\n /// Allows you to provide [`Verifier`](struct.Verifier.html) with the hash to verify\n\n /// against (in the form of a [`HashRaw`](output/struct.HashRaw.html) like those produced\n\n /// by the [`hash_raw`](struct.Hasher.html#method.hash_raw) or\n\n /// [`hash_raw_non_blocking`](struct.Hasher.html#method.hash_raw_non_blocking)\n\n /// methods on [`Hasher`](struct.Hasher.html))\n\n pub fn with_hash_raw(&mut self, hash_raw: &HashRaw) -> &mut Verifier<'a> {\n\n self.hash = Hash::Raw(hash_raw.clone());\n\n self\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 71, "score": 43421.000183434044 }, { "content": " self.hasher.config.set_variant(hash_raw.variant());\n\n self.hasher.config.set_version(hash_raw.version());\n\n self.hasher.salt = hash_raw.raw_salt_bytes().into();\n\n let hash_raw2 = self.hasher.hash_raw()?;\n\n let is_valid = if hash_raw.raw_hash_bytes() == hash_raw2.raw_hash_bytes() {\n\n true\n\n } else {\n\n false\n\n };\n\n Ok(is_valid)\n\n }\n\n Hash::None => return Err(Error::new(ErrorKind::HashMissingError)),\n\n }\n\n }\n\n /// <b><u>The primary method (non-blocking version)</u></b>\n\n ///\n\n /// Same as [`verify`](struct.Verifier.html#method.verify) except it returns a\n\n /// [`Future`](https://docs.rs/futures/0.1.21/futures/future/trait.Future.html)\n\n /// instead of a [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html)\n\n pub fn verify_non_blocking(&mut self) -> impl Future<Item = bool, Error = Error> {\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 72, "score": 43418.98956639031 }, { "content": " /// [`Backend::Rust`](config/enum.Backend.html#variant.Rust) it will error</i>\n\n pub fn configure_backend(&mut self, backend: Backend) -> &mut Verifier<'a> {\n\n self.hasher.config.set_backend(backend);\n\n self\n\n }\n\n /// Allows you to configure [`Verifier`](struct.Verifier.html) with a custom\n\n /// [`CpuPool`](https://docs.rs/futures-cpupool/0.1.8/futures_cpupool/struct.CpuPool.html).\n\n /// The default [`Verifier`](struct.Verifier.html) does not have a cpu pool, which is\n\n /// only needed for the [`verify_non_blocking`](struct.Verifier.html#method.verify_non_blocking)\n\n /// method. If you call [`verify_non_blocking`](struct.Verifier.html#method.verify_non_blocking)\n\n /// without a cpu pool, a default cpu pool will be created for you on the fly; so even\n\n /// if you never configure [`Verifier`](struct.Verifier.html) with this method you can still\n\n /// use the [`verify_non_blocking`](struct.Verifier.html#method.verify_non_blocking) method.\n\n /// The default cpu pool has as many threads as the number of logical cores on your machine\n\n pub fn configure_cpu_pool(&mut self, cpu_pool: CpuPool) -> &mut Verifier<'a> {\n\n self.hasher.config.set_cpu_pool(cpu_pool);\n\n self\n\n }\n\n /// Allows you to configure [`Verifier`](struct.Verifier.html) to erase the password bytes\n\n /// after each call to [`verify`](struct.Verifier.html#method.verify)\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 73, "score": 43418.695709864136 }, { "content": " .with_additional_data(\"additional data\")\n\n .with_password(password)\n\n .with_secret_key(secret_key)\n\n .with_salt(\"somesalt\");\n\n let hash_raw = hasher.hash_raw().expect(\"failed to hash_raw\");\n\n\n\n let mut verifier1 = Verifier::default();\n\n verifier1\n\n .configure_password_clearing(false)\n\n .configure_secret_key_clearing(false)\n\n .with_additional_data(\"additional data\")\n\n .with_password(password)\n\n .with_secret_key(secret_key)\n\n .with_hash_raw(&hash_raw);\n\n let is_valid = verifier1.verify().unwrap();\n\n if !is_valid {\n\n panic!(\n\n \"\\nverifier1:\\n{:#?}\\nAdditional Data: {:?}\\nHash: {}\\nPasswod: {:?}\\nSecret key: {:?}\",\n\n verifier1,\n\n \"additional data\".as_bytes(),\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 74, "score": 43416.74062029756 }, { "content": " ///\n\n /// After you have configured [`Verifier`](struct.Verifier.html) to your liking and provided\n\n /// it will all the data it needs to verify a password, i.e.\n\n /// * a string-encoded hash or [`HashRaw`](output/struct.HashRaw.html),\n\n /// * a [`Password`](input/struct.Password.html),\n\n /// * a [`SecretKey`](input/struct.SecretKey.html) (if required),\n\n /// * [`AdditionalData`](input/struct.AdditionalData.html) (if required),\n\n ///\n\n /// call this method to verify that the password matches the hash or\n\n /// [`HashRaw`](output/struct.HashRaw.html)\n\n pub fn verify(&mut self) -> Result<bool, Error> {\n\n match self.hash {\n\n Hash::Encoded(ref s) => {\n\n let hash_raw = decode_rust(s)?;\n\n self.hasher\n\n .config\n\n .set_hash_len(hash_raw.raw_hash_bytes().len() as u32);\n\n self.hasher.config.set_iterations(hash_raw.iterations());\n\n self.hasher.config.set_lanes(hash_raw.lanes());\n\n self.hasher.config.set_memory_size(hash_raw.memory_size());\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 75, "score": 43415.793874291754 }, { "content": " /// [`AdditionalData`](input/struct.AdditionalData.html), if any\n\n pub fn additional_data(&self) -> Option<&AdditionalData> {\n\n self.hasher.additional_data()\n\n }\n\n /// Read-only access to the [`Verifier`](struct.Verifier.html)'s\n\n /// [`VerifierConfig`](config/struct.VerifierConfig.html)\n\n pub fn config(&self) -> VerifierConfig {\n\n VerifierConfig::new(\n\n /* backend */ self.hasher.config.backend(),\n\n /* cpu_pool */ self.hasher.config.cpu_pool(),\n\n /* password_clearing */ self.hasher.config.password_clearing(),\n\n /* secret_key_clearing */ self.hasher.config.secret_key_clearing(),\n\n /* threads */ self.hasher.config.threads(),\n\n )\n\n }\n\n /// Returns the [`Verifier`](struct.Verifier.html)'s string-encoded hash, if any\n\n pub fn hash(&self) -> Option<String> {\n\n match self.hash {\n\n Hash::Encoded(ref s) => Some(s.to_string()),\n\n Hash::Raw(ref hash_raw) => Some(hash_raw.encode_rust()),\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 76, "score": 43414.661007889095 }, { "content": " hasher: Hasher<'a>,\n\n}\n\n\n\nimpl<'a> Verifier<'a> {\n\n /// Creates a new [`Verifier`](struct.Verifier.html) with the following configuration:\n\n /// * `backend`: [`Backend::C`](config/enum.Backend.html#variant.C)\n\n /// * `cpu_pool`: A [`CpuPool`](https://docs.rs/futures-cpupool/0.1.8/futures_cpupool/struct.CpuPool.html) ...\n\n /// * with threads equal to the number of logical cores on your machine\n\n /// * that is lazily created, i.e. created only if / when you call the method that\n\n /// needs it ([`verify_non_blocking`](struct.Verifier.html#method.verify_non_blocking))\n\n /// * `password_clearing`: `false`\n\n /// * `secret_key_clearing`: `false`\n\n /// * `threads`: The number of logical cores on your machine\n\n pub fn new() -> Verifier<'a> {\n\n Verifier::default()\n\n }\n\n /// Allows you to configure [`Verifier`](struct.Verifier.html) with a custom backend. The\n\n /// default backend is [`Backend::C`](config/enum.Backend.html#variant.C), <i>which is\n\n /// currently the only backend supported. A Rust backend is planned, but is not currently\n\n /// available. If you configure a [`Verifier`](struct.Verifier.html) with\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 77, "score": 43413.45309777219 }, { "content": " self.hasher.config.set_opt_out_of_secret_key(true);\n\n self.hasher.config.set_variant(hash_raw.variant());\n\n self.hasher.config.set_version(hash_raw.version());\n\n self.hasher.salt = hash_raw.raw_salt_bytes().into();\n\n let hash_raw2 = self.hasher.hash_raw()?;\n\n let is_valid = if hash_raw.raw_hash_bytes() == hash_raw2.raw_hash_bytes() {\n\n true\n\n } else {\n\n false\n\n };\n\n Ok(is_valid)\n\n }\n\n Hash::Raw(ref hash_raw) => {\n\n self.hasher\n\n .config\n\n .set_hash_len(hash_raw.raw_hash_bytes().len() as u32);\n\n self.hasher.config.set_iterations(hash_raw.iterations());\n\n self.hasher.config.set_lanes(hash_raw.lanes());\n\n self.hasher.config.set_memory_size(hash_raw.memory_size());\n\n self.hasher.config.set_opt_out_of_secret_key(true);\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 78, "score": 43413.337365598876 }, { "content": " let is_valid = verifier2.verify().unwrap();\n\n if !is_valid {\n\n panic!(\"\\nverifier2:\\n{:#?}\\n\", verifier2);\n\n };\n\n }\n\n\n\n #[test]\n\n fn test_send() {\n\n fn assert_send<T: Send>() {}\n\n assert_send::<Verifier>();\n\n }\n\n\n\n #[test]\n\n fn test_sync() {\n\n fn assert_sync<T: Sync>() {}\n\n assert_sync::<Verifier>();\n\n }\n\n\n\n #[cfg(feature = \"serde\")]\n\n #[test]\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 79, "score": 43413.27401543583 }, { "content": " Hash::None => None,\n\n }\n\n }\n\n /// Returns the [`Verifier`](struct.Verifier.html)'s [`HashRaw`](output/struct.HashRaw.html),\n\n /// if any\n\n pub fn hash_raw(&self) -> Result<Option<HashRaw>, Error> {\n\n match self.hash {\n\n Hash::Encoded(ref s) => Ok(Some(decode_rust(s)?)),\n\n Hash::Raw(ref hash_raw) => Ok(Some(hash_raw.clone())),\n\n Hash::None => Ok(None),\n\n }\n\n }\n\n /// Read-only access to the [`Verifier`](struct.Verifier.html)'s\n\n /// [`Password`](input/struct.Password.html), if any\n\n pub fn password(&self) -> Option<&Password<'a>> {\n\n self.hasher.password()\n\n }\n\n /// Read-only access to the [`Verifier`](struct.Verifier.html)'s\n\n /// [`SecretKey`](input/struct.SecretKey.html), if any\n\n pub fn secret_key(&self) -> Option<&SecretKey<'a>> {\n", "file_path": "argonautica-rs/src/verifier.rs", "rank": 80, "score": 43412.47540699244 }, { "content": " }\n\n}\n\n\n\n/// <b><u>One of the two main structs.</u></b> Use it to turn passwords into hashes\n\n#[derive(Debug)]\n\n#[cfg_attr(feature = \"serde\", derive(Serialize, Deserialize))]\n\n#[cfg_attr(feature = \"serde\", serde(rename_all = \"camelCase\"))]\n\npub struct Hasher<'a> {\n\n pub(crate) additional_data: Option<AdditionalData>,\n\n pub(crate) config: HasherConfig,\n\n #[cfg_attr(feature = \"serde\", serde(skip_serializing, skip_deserializing))]\n\n pub(crate) password: Option<Password<'a>>,\n\n pub(crate) salt: Salt,\n\n #[cfg_attr(feature = \"serde\", serde(skip_serializing, skip_deserializing))]\n\n pub(crate) secret_key: Option<SecretKey<'a>>,\n\n}\n\n\n\nimpl<'a> Hasher<'a> {\n\n /// Creates a new [`Hasher`](struct.Hasher.html) with a sensible default configuration\n\n /// for the average machine (e.g. an early-2014 MacBook Air).\n", "file_path": "argonautica-rs/src/hasher.rs", "rank": 81, "score": 43379.34813039792 }, { "content": " use serde_json;\n\n\n\n let password = \"P@ssw0rd\";\n\n let secret_key = \"secret\";\n\n\n\n let mut hasher1 = Hasher::default();\n\n hasher1\n\n .configure_password_clearing(false)\n\n .with_additional_data(\"additional data\")\n\n .with_password(password)\n\n .with_secret_key(secret_key)\n\n .with_salt(\"somesalt\");\n\n let hash1 = hasher1.hash().expect(\"failed to hash\");\n\n let hash_raw1 = hasher1.hash_raw().expect(\"failed to hash_raw\");\n\n\n\n // Serialize Hasher\n\n let j = serde_json::to_string_pretty(&hasher1).expect(\"failed to serialize hasher\");\n\n // Deserialize Hasher\n\n let mut hasher2: Hasher = serde_json::from_str(&j).expect(\"failed to deserialize hasher\");\n\n // Assert that password and secret key have been erased\n", "file_path": "argonautica-rs/src/hasher.rs", "rank": 82, "score": 43379.252657659315 }, { "content": " #[test]\n\n fn test_sync() {\n\n fn assert_sync<T: Sync>() {}\n\n assert_sync::<Hasher>();\n\n }\n\n\n\n #[cfg(feature = \"serde\")]\n\n #[test]\n\n fn test_serialize() {\n\n use serde;\n\n fn assert_serialize<T: serde::Serialize>() {}\n\n assert_serialize::<Hasher>();\n\n }\n\n\n\n #[cfg(feature = \"serde\")]\n\n #[test]\n\n fn test_deserialize() {\n\n use serde;\n\n fn assert_deserialize<'de, T: serde::Deserialize<'de>>() {}\n\n assert_deserialize::<Hasher>();\n\n }\n\n}\n", "file_path": "argonautica-rs/src/hasher.rs", "rank": 83, "score": 43375.1129466167 }, { "content": " {\n\n self.password = Some(password.into());\n\n self\n\n }\n\n /// Allows you to provide [`Hasher`](struct.Hasher.html) with a custom\n\n /// [`Salt`](input/struct.Salt.html) to include in the hash. The default\n\n /// [`Hasher`](struct.Hasher.html) is configured to use a random\n\n /// [`Salt`](input/struct.Salt.html) of 32 bytes; so there is no need\n\n /// to call this method. If you would like to use a random\n\n /// [`Salt`](input/struct.Salt.html) of different length, you can call this method with\n\n /// `Salt::random(your_custom_length_in_bytes)`. Using a deterministic\n\n /// [`Salt`](input/struct.Salt.html) is possible, but discouraged\n\n pub fn with_salt<S>(&mut self, salt: S) -> &mut Hasher<'a>\n\n where\n\n S: Into<Salt>,\n\n {\n\n self.salt = salt.into();\n\n self\n\n }\n\n /// Allows you to provide [`Hasher`](struct.Hasher.html) with a secret key that will be used\n", "file_path": "argonautica-rs/src/hasher.rs", "rank": 84, "score": 43369.80929005167 }, { "content": " /// The default and latest (as of 5/18) is\n\n /// [`Version::_0x13`](config/enum.Version.html#variant._0x13).\n\n /// Do <b>not</b> use a different version unless you have a specific reason to do so.\n\n ///\n\n /// See [configuration example](index.html#configuration) for a more details on this parameter\n\n pub fn configure_version(&mut self, version: Version) -> &mut Hasher<'a> {\n\n self.config.set_version(version);\n\n self\n\n }\n\n /// <b><u>The primary method (blocking version).</u></b>\n\n ///\n\n /// After you have configured a [`Hasher`](struct.Hasher.html) to your liking and provided\n\n /// it will all the data you would like to hash, e.g.\n\n /// * a [`Password`](input/struct.Password.html),\n\n /// * a [`Salt`](input/struct.Salt.html) (note: it is recommened you use the default random salt),\n\n /// * a [`SecretKey`](input/struct.SecretKey.html),\n\n /// * [`AdditionalData`](input/struct.AdditionalData.html) (optional),\n\n ///\n\n /// call this method in order to produce a string-encoded hash, which is safe to store in a\n\n /// database and against which you can verify passwords later\n", "file_path": "argonautica-rs/src/hasher.rs", "rank": 85, "score": 43368.57057361049 }, { "content": " }\n\n /// Read-only access to the [`Hasher`](struct.Hasher.html)'s\n\n /// [`Password`](input/struct.Password.html), if any\n\n pub fn password(&self) -> Option<&Password<'a>> {\n\n self.password.as_ref()\n\n }\n\n /// Read-only access to the [`Hasher`](struct.Hasher.html)'s [`Salt`](input/struct.Salt.html)\n\n pub fn salt(&self) -> &Salt {\n\n &self.salt\n\n }\n\n /// Read-only access to the [`Hasher`](struct.Hasher.html)'s\n\n /// [`SecretKey`](input/struct.SecretKey.html), if any\n\n pub fn secret_key(&self) -> Option<&SecretKey<'a>> {\n\n self.secret_key.as_ref()\n\n }\n\n}\n\n\n\nimpl<'a> Hasher<'a> {\n\n pub(crate) fn clear(&mut self) {\n\n if self.password.is_some() && self.config.password_clearing() {\n", "file_path": "argonautica-rs/src/hasher.rs", "rank": 86, "score": 43367.43651729058 }, { "content": " ///\n\n /// Including additional data in your hash is not very common; so it is unlikely you will\n\n /// need to use this method. If, however, you do add additional data, note that it is like\n\n /// a secret key in that it will be required later in order to verify passwords, and\n\n /// it is not stored in the string-encoded version of the hash, meaning you will have to\n\n /// provide it manually to a [`Verifier`](struct.Verifier.html)\n\n pub fn with_additional_data<AD>(&mut self, additional_data: AD) -> &mut Hasher<'a>\n\n where\n\n AD: Into<AdditionalData>,\n\n {\n\n self.additional_data = Some(additional_data.into());\n\n self\n\n }\n\n /// Allows you to provide a [`Hasher`](struct.Hasher.html) with the password you would like\n\n /// to hash. Hashing requires a password; so you must call this method before calling\n\n /// [`hash`](struct.Hasher.html#method.hash), [`hash_raw`](struct.Hasher.html#method.hash_raw),\n\n /// or their non-blocking version\n\n pub fn with_password<P>(&mut self, password: P) -> &mut Hasher<'a>\n\n where\n\n P: Into<Password<'a>>,\n", "file_path": "argonautica-rs/src/hasher.rs", "rank": 87, "score": 43366.87554598835 }, { "content": " self\n\n }\n\n /// Allows you to configure [`Hasher`](struct.Hasher.html) to use a custom memory size\n\n /// (in kibibytes). The default is `4096`.\n\n ///\n\n /// See [configuration example](index.html#configuration) for a more details on this parameter\n\n pub fn configure_memory_size(&mut self, memory_size: u32) -> &mut Hasher<'a> {\n\n self.config.set_memory_size(memory_size);\n\n self\n\n }\n\n /// Allows you to configure [`Hasher`](struct.Hasher.html) to erase the password bytes\n\n /// after each call to [`hash`](struct.Hasher.html#method.hash),\n\n /// [`hash_raw`](struct.Hasher#method.hash_raw), or their non-blocking equivalents.\n\n /// The default is to <b>not</b> clear out the password\n\n /// bytes (i.e. `false`). If you set this option to `true`, you must provide\n\n /// [`Hasher`](struct.Hasher.html) with a mutable password, e.g. a password\n\n /// constructed from a `String`, `Vec<u8>`, `&mut str`, `&mut [u8]`, etc. as opposed to\n\n /// one constructed from a `&str`, `&[u8]`, etc., or else hashing will return an\n\n /// [`Error`](struct.Error.html).\n\n ///\n", "file_path": "argonautica-rs/src/hasher.rs", "rank": 88, "score": 43366.64621754571 }, { "content": " /// to create the hash. The secret key will not be included in the hash output, meaning you\n\n /// must save it somewhere (ideally outside your code) to use later, as the only way to\n\n /// verify passwords against the hash later is to know the secret key. This library\n\n /// encourages the use of a secret key\n\n pub fn with_secret_key<SK>(&mut self, secret_key: SK) -> &mut Hasher<'a>\n\n where\n\n SK: Into<SecretKey<'a>>,\n\n {\n\n self.secret_key = Some(secret_key.into());\n\n self\n\n }\n\n /// Read-only access to the [`Hasher`](struct.Hasher.html)'s\n\n /// [`AdditionalData`](input/struct.AdditionalData.html), if any\n\n pub fn additional_data(&self) -> Option<&AdditionalData> {\n\n self.additional_data.as_ref()\n\n }\n\n /// Read-only access to the [`Hasher`](struct.Hasher.html)'s\n\n /// [`HasherConfig`](config/struct.HasherConfig.html)\n\n pub fn config(&self) -> &HasherConfig {\n\n &self.config\n", "file_path": "argonautica-rs/src/hasher.rs", "rank": 89, "score": 43366.05153322148 }, { "content": " .with_password(\"password\")\n\n .with_secret_key(\"secret\")\n\n .hash();\n\n match hash {\n\n Ok(_) => panic!(\"Should return an error\"),\n\n Err(e) => assert_eq!(e, Error::new(ErrorKind::SecretKeyImmutableError)),\n\n }\n\n assert!(hasher.password().is_some());\n\n assert!(hasher.secret_key().is_none());\n\n }\n\n\n\n #[test]\n\n fn test_hasher_fast_but_insecure() {\n\n let mut hasher = Hasher::fast_but_insecure();\n\n let _ = hasher.with_password(\"P@ssw0rd\").hash().unwrap();\n\n }\n\n\n\n #[cfg(feature = \"serde\")]\n\n #[test]\n\n fn test_hasher_serialization() {\n", "file_path": "argonautica-rs/src/hasher.rs", "rank": 90, "score": 43365.95190954909 }, { "content": "use futures::Future;\n\nuse futures_cpupool::CpuPool;\n\nuse scopeguard;\n\n\n\nuse config::defaults::{default_cpu_pool, default_lanes};\n\nuse config::{Backend, HasherConfig, Variant, Version};\n\nuse input::{AdditionalData, Container, Password, Salt, SecretKey};\n\nuse output::HashRaw;\n\nuse {Error, ErrorKind};\n\n\n\nimpl<'a> Default for Hasher<'a> {\n\n /// Same as the [`new`](struct.Hasher.html#method.new) method\n\n fn default() -> Hasher<'static> {\n\n Hasher {\n\n additional_data: None,\n\n config: HasherConfig::default(),\n\n password: None,\n\n salt: Salt::default(),\n\n secret_key: None,\n\n }\n", "file_path": "argonautica-rs/src/hasher.rs", "rank": 91, "score": 43365.70257914814 }, { "content": " /// Allows you to configure [`Hasher`](struct.Hasher.html) to use a custom number of\n\n /// threads. The default is the number of physical cores on your machine. If you choose\n\n /// a number of threads that is greater than the lanes configuration,\n\n /// [`Hasher`](struct.Hasher.html) will use the minimum of the two.\n\n ///\n\n /// See [configuration example](index.html#configuration) for a more details on this parameter\n\n pub fn configure_threads(&mut self, threads: u32) -> &mut Hasher<'a> {\n\n self.config.set_threads(threads);\n\n self\n\n }\n\n /// Allows you to configure [`Hasher`](struct.Hasher.html) to use a custom Argon2\n\n /// variant. The default is [`Variant::Argon2id`](config/enum.Variant.html#variant.Argon2id).\n\n /// Do <b>not</b> use a different variant unless you have a specific reason to do so.\n\n ///\n\n /// See [configuration example](index.html#configuration) for a more details on this parameter\n\n pub fn configure_variant(&mut self, variant: Variant) -> &mut Hasher<'a> {\n\n self.config.set_variant(variant);\n\n self\n\n }\n\n /// Allows you to configure [`Hasher`](struct.Hasher.html) to use a custom Argon2 version.\n", "file_path": "argonautica-rs/src/hasher.rs", "rank": 92, "score": 43365.306528097564 }, { "content": " /// See [configuration example](index.html#configuration) for a more detailed discussion\n\n /// of this parameter\n\n pub fn configure_hash_len(&mut self, hash_len: u32) -> &mut Hasher<'a> {\n\n self.config.set_hash_len(hash_len);\n\n self\n\n }\n\n /// Allows you to configure [`Hasher`](struct.Hasher.html) to use a custom number of\n\n /// iterations. The default is `192`.\n\n ///\n\n /// See [configuration example](index.html#configuration) for a more details on this parameter\n\n pub fn configure_iterations(&mut self, iterations: u32) -> &mut Hasher<'a> {\n\n self.config.set_iterations(iterations);\n\n self\n\n }\n\n /// Allows you to configure [`Hasher`](struct.Hasher.html) to use a custom number of\n\n /// lanes. The default is the number of physical cores on your machine.\n\n ///\n\n /// See [configuration example](index.html#configuration) for a more details on this parameter\n\n pub fn configure_lanes(&mut self, lanes: u32) -> &mut Hasher<'a> {\n\n self.config.set_lanes(lanes);\n", "file_path": "argonautica-rs/src/hasher.rs", "rank": 93, "score": 43364.638702272576 }, { "content": " /// See [configuration example](index.html#configuration) for a more details on this parameter\n\n pub fn configure_password_clearing(&mut self, boolean: bool) -> &mut Hasher<'a> {\n\n self.config.set_password_clearing(boolean);\n\n self\n\n }\n\n /// Allows you to configure [`Hasher`](struct.Hasher.html) to erase the secret key bytes\n\n /// after each call to [`hash`](struct.Hasher.html#method.hash),\n\n /// [`hash_raw`](struct.Hasher#method.hash_raw), or their non-blocking equivalents.\n\n /// The default is to <b>not</b> clear out the secret key\n\n /// bytes (i.e. `false`). If you set this option to `true`, you must provide\n\n /// [`Hasher`](struct.Hasher.html) with a mutable secret key, e.g. a secret key\n\n /// constructed from a `String`, `Vec<u8>`, `&mut str`, `&mut [u8]`, etc. as opposed to\n\n /// one constructed from a `&str`, `&[u8]`, etc., or else hashing will return an\n\n /// [`Error`](struct.Error.html).\n\n ///\n\n /// See [configuration example](index.html#configuration) for a more details on this parameter\n\n pub fn configure_secret_key_clearing(&mut self, boolean: bool) -> &mut Hasher<'a> {\n\n self.config.set_secret_key_clearing(boolean);\n\n self\n\n }\n", "file_path": "argonautica-rs/src/hasher.rs", "rank": 94, "score": 43364.463823764934 }, { "content": " let mut hasher = hasher.to_owned();\n\n match hasher.config.cpu_pool() {\n\n Some(cpu_pool) => cpu_pool.spawn_fn(move || hasher.hash_raw()),\n\n None => {\n\n let cpu_pool = default_cpu_pool();\n\n hasher.config.set_cpu_pool(cpu_pool.clone());\n\n cpu_pool.spawn_fn(move || hasher.hash_raw())\n\n }\n\n }\n\n }\n\n /// As an extra security measure, if you want to hash without a secret key, which\n\n /// is not recommended, you must explicitly declare that this is your intention\n\n /// by calling this method and setting the `opt_out_of_secret_key` configuration to\n\n /// `true` (by default, it is set to `false`); otherwise hashing will return an error\n\n /// when you fail to provide a secret key\n\n pub fn opt_out_of_secret_key(&mut self, boolean: bool) -> &mut Hasher<'a> {\n\n self.config.set_opt_out_of_secret_key(boolean);\n\n self\n\n }\n\n /// Clones the [`Hasher`](struct.Hasher.html), returning a new\n", "file_path": "argonautica-rs/src/hasher.rs", "rank": 95, "score": 43364.2475386823 }, { "content": "}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use config::{Variant, Version};\n\n\n\n struct Test {\n\n variant: Variant,\n\n version: Version,\n\n expected: Vec<u8>,\n\n }\n\n\n\n impl Test {\n\n fn run(&self) {\n\n let mut hasher = Hasher::default();\n\n let raw_hash = hasher\n\n .configure_hash_len(32)\n\n .configure_iterations(3)\n\n .configure_lanes(4)\n", "file_path": "argonautica-rs/src/hasher.rs", "rank": 96, "score": 43363.93812471932 }, { "content": "## Hashing\n\n\n\nHashing passwords with <b>argonautica</b> is simple. Just instantiate a default\n\n[`Hasher`](struct.Hasher.html), provide it with a password and a secret key, and then\n\ncall the [`hash`](struct.Hasher.html#method.hash) method.\n\n```rust\n\nextern crate argonautica;\n\n\n\nuse argonautica::Hasher;\n\n\n\nfn main() {\n\n let mut hasher = Hasher::default();\n\n let hash = hasher\n\n .with_password(\"P@ssw0rd\")\n\n .with_secret_key(\"\\\n\n secret key that you should really store in a .env file \\\n\n instead of in code, but this is just an example\\\n\n \")\n\n .hash()\n\n .unwrap();\n\n\n\n println!(\"{}\", &hash);\n\n // 👆 prints a hash, which will be random since the default Hasher uses a random salt\n\n}\n\n```\n\n## Verifying\n\n\n\nVerifying passwords against a hash is equally as simple. Just instantiate a default\n\n[`Verifier`](struct.Verifier.html), provide it with the password and the hash you would\n\nlike to compare, provide it with the secret key that was used to create the hash, and\n\nthen call the [`verify`](struct.Verifier.html#method.verify) method.\n\n```rust\n\nextern crate argonautica;\n\n\n\nuse argonautica::Verifier;\n\n\n\nfn main() {\n\n let mut verifier = Verifier::default();\n\n let is_valid = verifier\n\n .with_hash(\"\n\n $argon2id$v=19$m=4096,t=192,p=4$\\\n\n o2y5PU86Vt+sr93N7YUGgC7AMpTKpTQCk4tNGUPZMY4$\\\n\n yzP/ukZRPIbZg6PvgnUUobUMbApfF9RH6NagL9L4Xr4\\\n\n \")\n\n .with_password(\"P@ssw0rd\")\n\n .with_secret_key(\"\\\n\n secret key that you should really store in a .env file \\\n\n instead of in code, but this is just an example\\\n\n \")\n\n .verify()\n\n .unwrap();\n\n\n\n assert!(is_valid);\n\n}\n\n```\n", "file_path": "argonautica-rs/README.md", "rank": 98, "score": 33.19858196080795 }, { "content": "extern crate argonautica;\n\nextern crate dotenv;\n\n#[macro_use]\n\nextern crate failure;\n\n\n\nuse std::collections::HashMap;\n\nuse std::env;\n\n\n\nuse argonautica::config::{Variant, Version};\n\nuse argonautica::input::{Salt, SecretKey};\n\nuse argonautica::{Hasher, Verifier};\n\n\n\n// Helper method to load the secret key from a .env file. Used in `main` below.\n", "file_path": "argonautica-rs/examples/example_custom.rs", "rank": 99, "score": 30.8381202154013 } ]
Rust
src/procfs.rs
wojciechkepka/rustop
b8ac5b8c36aae9364fb16b64030d3de614e94747
use super::*; pub async fn os_release() -> Result<String> { Ok(fs::read_to_string(SysProperty::OsRelease.path())?.trim_end().to_string()) } pub async fn hostname() -> Result<String> { Ok(fs::read_to_string(SysProperty::Hostname.path())?.trim_end().to_string()) } pub async fn uptime() -> Result<f64> { let output = fs::read_to_string(SysProperty::Uptime.path())?; Ok(_uptime(&output)) } pub(crate) fn _uptime(out: &str) -> f64 { match out.split(' ').collect::<Vec<&str>>()[0].parse::<f64>() { Ok(up) => up, Err(_) => 0.0, } } pub async fn cpu_info() -> Result<String> { let output = fs::read_to_string(SysProperty::CpuInfo.path())?; Ok(_cpu_info(&output)) } pub(crate) fn _cpu_info(out: &str) -> String { let re = Regex::new(r"model name\s*: (.*)").unwrap(); re.captures(&out).map_or("".to_string(), |x| x[1].to_string()) } pub async fn mem(target: Memory) -> Result<u64> { let output = fs::read_to_string(SysProperty::Mem.path())?; Ok(_mem(target, &output)) } pub(crate) fn _mem(target: Memory, out: &str) -> u64 { let re = match target { Memory::SwapFree => Regex::new(r"SwapFree:\s*(\d*)").unwrap(), Memory::SwapTotal => Regex::new(r"SwapTotal:\s*(\d*)").unwrap(), Memory::MemTotal => Regex::new(r"MemTotal:\s*(\d*)").unwrap(), Memory::MemFree => Regex::new(r"MemFree:\s*(\d*)").unwrap(), }; match re.captures(&out).map(|m| handle(m[1].parse::<u64>())) { Some(n) => n * 1024, _ => 0, } } pub async fn total_clock_speed() -> Result<f32> { let output = fs::read_to_string(SysProperty::CpuInfo.path())?; Ok(_total_clock_speed(&output)) } pub(crate) fn _total_clock_speed(out: &str) -> f32 { let re = Regex::new(r"cpu MHz\s*: (.*)").unwrap(); re.captures_iter(&out).map(|x| handle(x[1].parse::<f32>())).sum::<f32>() } pub async fn total_cpu_cores() -> Result<usize> { let output = fs::read_to_string(SysProperty::CpuInfo.path())?; Ok(_total_cpu_cores(&output)) } pub(crate) fn _total_cpu_cores(out: &str) -> usize { out.rmatches("cpu MHz").count() } pub async fn cpu_clock() -> Result<f32> { Ok(total_clock_speed().await? / total_cpu_cores().await? as f32) } pub async fn network_devs() -> Result<NetworkDevices> { let route = fs::read_to_string(SysProperty::Route.path())?; let fib_trie = fs::read_to_string(SysProperty::FibTrie.path())?; let net_dev = fs::read_to_string(SysProperty::NetDev.path())?; let if_inet = fs::read_to_string(SysProperty::IfInet6.path())?; _network_devs(&net_dev, &route, &fib_trie, &if_inet) } pub(crate) fn _network_devs(net_dev: &str, route: &str, fib_trie: &str, if_inet: &str) -> Result<NetworkDevices> { let mut devices = vec![]; let re = Regex::new(r"([\d\w]*):\s*(\d*)\s*\d*\s*\d*\s*\d*\s*\d*\s*\d*\s*\d*\s*\d*\s*(\d*)")?; for network_dev in re.captures_iter(&net_dev) { devices.push(NetworkDevice { name: network_dev[1].to_string(), received_bytes: handle(network_dev[2].parse::<u64>()), transfered_bytes: handle(network_dev[3].parse::<u64>()), ipv4_addr: _ipv4_addr(&network_dev[1], &route, &fib_trie)?, ipv6_addr: _ipv6_addr(&network_dev[1], &if_inet)?, }); } Ok(NetworkDevices { net_devices: devices }) } pub async fn storage_devices() -> Result<Storages> { let stor_dev = fs::read_to_string(SysProperty::StorDev.path())?; let stor_mounts = fs::read_to_string(SysProperty::StorMounts.path())?; Ok(_storage_devices(&stor_dev, &stor_mounts)) } pub(crate) fn _storage_devices(stor_dev: &str, stor_mounts: &str) -> Storages { let mut devices = Vec::new(); let re = Regex::new(r"(?m)^\s*(\d*)\s*(\d*)\s*(\d*)\s([\w\d]*)$").unwrap(); for storage_dev in re .captures_iter(&stor_dev) .filter(|storage_dev| !(storage_dev[4].starts_with("loop") || storage_dev[4].starts_with("ram"))) .filter(|storage_dev| { let stor_dev_re = Regex::new(r"^[a-z]+$").unwrap(); stor_dev_re.is_match(&storage_dev[4].to_string()) }) { devices.push(Storage { major: handle(storage_dev[1].parse::<u16>()), minor: handle(storage_dev[2].parse::<u16>()), size: handle(storage_dev[3].parse::<u64>()) * 1024, name: storage_dev[4].to_string(), partitions: _storage_partitions(&storage_dev[4], &stor_dev, &stor_mounts), }); } Storages { storage_devices: devices } } #[allow(dead_code)] async fn storage_partitions(stor_name: &str) -> Result<Partitions> { let stor_dev = fs::read_to_string(SysProperty::StorDev.path())?; let stor_mounts = fs::read_to_string(SysProperty::StorMounts.path())?; Ok(_storage_partitions(&stor_name, &stor_dev, &stor_mounts)) } pub(crate) fn _storage_partitions(stor_name: &str, stor_dev: &str, stor_mounts: &str) -> Partitions { let mut partitions = vec![]; let re = Regex::new(r"(?m)^\s*(\d*)\s*(\d*)\s*(\d*)\s(\w*\d+)$").unwrap(); let re2 = Regex::new(r"/dev/(\w*)\s(\S*)\s(\S*)").unwrap(); for storage_dev in re.captures_iter(&stor_dev).filter(|x| x[4].starts_with(stor_name)) { let mut partition = Partition::default(); let partition_name = &storage_dev[4]; for found_partition in re2.captures_iter(&stor_mounts) { if &found_partition[1] == partition_name { partition.mountpoint = found_partition[2].to_string(); partition.filesystem = found_partition[3].to_string(); break; } else { partition.mountpoint = "".to_string(); partition.filesystem = "".to_string(); } } partition.major = handle(storage_dev[1].parse::<u16>()); partition.minor = handle(storage_dev[2].parse::<u16>()); partition.size = handle(storage_dev[3].parse::<u64>()) * 1024; partition.name = partition_name.to_string(); partitions.push(partition); } partitions } pub async fn vgs() -> Result<VolGroups> { let mut vgs: Vec<VolGroup> = vec![]; let output = fs::read_to_string(SysProperty::StorDev.path())?; let re = Regex::new(r"(?m)\d*\s*dm-")?; if re.captures(&output).is_some() { let cmd = Command::new("vgdisplay").arg("--units").arg("b").output()?; let out = str::from_utf8(&cmd.stdout)?; let re = Regex::new( r"(?m)VG Name\s*(.*)\n.*\n\s*Format\s*(.*)$(?:\n.*){3}\s*VG Status\s*(.*)$(?:\n.*){6}$\s*VG Size\s*(\d*)", )?; for vg in re.captures_iter(&out) { vgs.push(VolGroup { name: vg[1].to_string(), format: vg[2].to_string(), status: vg[3].to_string(), size: handle(vg[4].parse::<u64>()), lvms: handle(lvms(vg[1].to_string()).await), }) } } Ok(VolGroups { vgs }) } async fn lvms(vg_name: String) -> Result<Vec<LogVolume>> { let mut lvms_vec: Vec<LogVolume> = vec![]; let cmd = Command::new("lvdisplay").arg("--units").arg("b").output()?; let out = str::from_utf8(&cmd.stdout)?; let re = Regex::new( r"(?m)LV Path\s*(.*)\n\s*LV Name\s*(.*)$\s*VG Name\s*(.*)$(?:\n.*){3}$\s*LV Status\s*(.*)\n.*$\n\s*LV Size\s*(\d*).*$(?:\n.*){5}\s*Block device\s*(\d*):(\d*)$", )?; for lvm in re.captures_iter(&out).filter(|lvm| lvm[3] == vg_name) { lvms_vec.push(LogVolume { name: lvm[2].to_string(), path: lvm[1].to_string(), vg: lvm[3].to_string(), status: lvm[4].to_string(), size: handle(lvm[5].parse::<u64>()), major: handle(lvm[6].parse::<u16>()), minor: handle(lvm[7].parse::<u16>()), mountpoint: "".to_string(), }) } Ok(lvms_vec) } pub async fn graphics_card() -> Result<String> { let cmd = Command::new("lspci").output()?; let out = str::from_utf8(&cmd.stdout)?; Ok(_graphics_card(&out)) } pub(crate) fn _graphics_card(out: &str) -> String { let re = Regex::new(r"(?m)VGA compatible controller:\s*(.*)$").unwrap(); re.captures(&out).map_or("".to_string(), |vga| vga[1].to_string()) } #[allow(dead_code)] async fn ipv4_addr(interface_name: &str) -> Result<Ipv4Addr> { let route = fs::read_to_string(SysProperty::Route.path())?; let fib_trie = fs::read_to_string(SysProperty::FibTrie.path())?; _ipv4_addr(&interface_name, &route, &fib_trie) } pub(crate) fn _ipv4_addr(interface_name: &str, route: &str, fib_trie: &str) -> Result<Ipv4Addr> { let mut iface_dest = "".to_string(); let mut ip_addr = Ipv4Addr::UNSPECIFIED; if interface_name == "lo" { Ok(Ipv4Addr::LOCALHOST) } else { let re = Regex::new(r"(?m)^([\d\w]*)\s*([\d\w]*)")?; for dest in re.captures_iter(&route) { if &dest[1] == interface_name && &dest[2] != "00000000" { iface_dest = utils::conv_hex_to_ip(&dest[2])?; } } let file = fib_trie.split('\n').collect::<Vec<&str>>(); let re = Regex::new(r"\|--\s+(.*)")?; let mut found = false; for (i, line) in (&file).iter().enumerate() { if (*line).to_string().contains(&iface_dest) { found = true; } else if found && (*line).to_string().contains("/32 host LOCAL") { ip_addr = match re.captures(&file[i - 1]) { Some(n) => Ipv4Addr::from_str(&n[1])?, None => Ipv4Addr::UNSPECIFIED, }; break; } } Ok(ip_addr) } } #[allow(dead_code)] async fn ipv6_addr(interface_name: &str) -> Result<Ipv6Addr> { let output = fs::read_to_string(SysProperty::IfInet6.path())?; _ipv6_addr(&interface_name, &output) } pub(crate) fn _ipv6_addr(interface_name: &str, out: &str) -> Result<Ipv6Addr> { if interface_name == "lo" { Ok(Ipv6Addr::LOCALHOST) } else { let mut ip_addr = Ipv6Addr::UNSPECIFIED; let re = Regex::new(r"(?m)^([\d\w]*)\s\d*\s\d*\s\d*\s\d*\s*(.*)$").unwrap(); for capture in re.captures_iter(&out) { if &capture[2] == interface_name { ip_addr = Ipv6Addr::from_str(&format!( "{}:{}:{}:{}:{}:{}:{}:{}", &capture[1][..4], &capture[1][4..8], &capture[1][8..12], &capture[1][12..16], &capture[1][16..20], &capture[1][20..24], &capture[1][24..28], &capture[1][28..32] ))?; break; } } Ok(ip_addr) } } pub async fn temperatures() -> Result<Temperatures> { let paths = fs::read_dir(SysProperty::Temperature.path())?; let mut devices: Vec<DeviceSensors> = vec![]; let re = Regex::new(r"temp[\d]+_input")?; for dir_entry in paths { let mut sensor_count = 0; let path = dir_entry?.path(); let mut dev = DeviceSensors::default(); let mut dev_temps: Vec<Sensor> = vec![]; dev.name = fs::read_to_string(path.join("name"))?.trim().to_string(); for temp_file in fs::read_dir(&path)? { if re.is_match(&temp_file?.path().to_str().unwrap()) { sensor_count += 1; } } for i in 1..=sensor_count { dev_temps.push(sensor(&path, i).await?); } dev.sensors = dev_temps; devices.push(dev); } Ok(Temperatures { temp_devices: devices }) } pub async fn sensor<P: AsRef<Path>>(path: P, i: i32) -> Result<Sensor> { let mut sensor = Sensor::default(); sensor.name = fs::read_to_string(path.as_ref().join(format!("temp{}_label", i))) .unwrap_or_else(|_| "".to_string()) .trim() .to_string(); sensor.temp = handle(fs::read_to_string(path.as_ref().join(format!("temp{}_input", i)))?.trim().parse::<f32>()) / 1000.; Ok(sensor) }
use super::*; pub async fn os_release() -> Result<String> { Ok(fs::read_to_string(SysProperty::OsRelease.path())?.trim_end().to_string()) } pub async fn hostname() -> Result<String> { Ok(fs::read_to_string(SysProperty::Hostname.path())?.trim_end().to_string()) } pub async fn uptime() -> Result<f64> { let output = fs::read_to_string(SysProperty::Uptime.path())?; Ok(_uptime(&output)) } pub(crate) fn _uptime(out: &str) -> f64 { match out.split(' ').collect::<Vec<&str>>()[0].parse::<f64>() { Ok(up) => up, Err(_) => 0.0, } } pub async fn cpu_info() -> Result<String> { let output = fs::read_to_string(SysProperty::CpuInfo.path())?; Ok(_cpu_info(&output)) } pub(crate) fn _cpu_info(out: &str) -> String { let re = Regex::new(r"model name\s*: (.*)").unwrap(); re.captures(&out).map_or("".to_string(), |x| x[1].to_string()) } pub async fn mem(target: Memory) -> Result<u64> { let output = fs::read_to_string(SysProperty::Mem.path())?; Ok(_mem(target, &output)) } pub(crate) fn _mem(target: Memory, out: &str) -> u64 { let re = match target { Memory::SwapFree => Regex::new(r"SwapFree:\s*(\d*)").unwrap(), Memory::SwapTotal => Regex::new(r"SwapTotal:\s*(\d*)").unwrap(), Memory::MemTotal => Regex::new(r"MemTotal:\s*(\d*)").unwrap(), Memory::MemFree => Regex::new(r"MemFree:\s*(\d*)").unwrap(), }; match re.captures(&out).map(|m| handle(m[1].parse::<u64>())) { Some(n) => n * 1024, _ => 0, } } pub async fn total_clock_speed() -> Result<f32> { let output = fs::read_to_string(SysProperty::CpuInfo.path())?; Ok(_total_clock_speed(&output)) } pub(crate) fn _total_clock_speed(out: &str) -> f32 { let re = Regex::new(r"cpu MHz\s*: (.*)").unwrap(); re.captures_iter(&out).map(|x| handle(x[1].parse::<f32>())).sum::<f32>() } pub async fn total_cpu_cores() -> Result<usize> { let output = fs::read_to_string(SysProperty::CpuInfo.path())?; Ok(_total_cpu_cores(&output)) } pub(crate) fn _total_cpu_cores(out: &str) -> usize { out.rmatches("cpu MHz").count() } pub async fn cpu_clock() -> Result<f32> { Ok(total_clock_speed().await? / total_cpu_cores().await? as f32) } pub async fn network_devs() -> Result<NetworkDevices> { let route = fs::read_to_string(SysProperty::Route.path())?; let fib_trie = fs::read_to_string(SysProperty::FibTrie.path())?; let net_dev = fs::read_to_string(SysProperty::NetDev.path())?; let if_inet = fs::read_to_string(SysProperty::IfInet6.path())?; _network_devs(&net_dev, &route, &fib_trie, &if_inet) } pub(crate) fn _network_devs(net_dev: &str, route: &str, fib_trie: &str, if_inet: &str) -> Result<NetworkDevices> { let mut devices = vec![]; let re = Regex::new(r"([\d\w]*):\s*(\d*)\s*\d*\s*\d*\s*\d*\s*\d*\s*\d*\s*\d*\s*\d*\s*(\d*)")?; for network_dev in re.captures_iter(&net_dev) { devices.push(NetworkDevice { name: network_dev[1].to_string(), received_bytes: handle(network_dev[2].parse::<u64>()), transfered_bytes: handle(network_dev[3].parse::<u64>()), ipv4_addr: _ipv4_addr(&network_dev[1], &route, &fib_trie)?, ipv6_addr: _ipv6_addr(&network_dev[1], &if_inet)?, }); } Ok(NetworkDevices { net_devices: devices }) } pub async fn storage_devices() -> Result<Storages> { let stor_dev = fs::read_to_string(SysProperty::StorDev.path())?; let stor_mounts = fs::read_to_string(SysProperty::StorMounts.path())?; Ok(_storage_devices(&stor_dev, &stor_mounts)) } pub(crate) fn _storage_devices(stor_dev: &str, stor_mounts: &str) -> Storages { let mut devices = Vec::new(); let re = Regex::new(r"(?m)^\s*(\d*)\s*(\d*)\s*(\d*)\s([\w\d]*)$").unwrap(); for storage_dev in re .captures_iter(&stor_dev) .filter(|storage_dev| !(storage_dev[4].starts_with("loop") || storage_dev[4].starts_with("ram"))) .filter(|storage_dev| { let stor_dev_re = Regex::new(r"^[a-z]+$").unwrap(); stor_dev_re.is_match(&storage_dev[4].to_string()) }) { devices.push(Storage { major: handle(storage_dev[1].parse::<u16>()), minor: handle(storage_dev[2].parse::<u16>()), size: handle(storage_dev[3].parse::<u64>()) * 1024, name: storage_dev[4].to_string(), partitions: _storage_partitions(&storage_dev[4], &stor_dev, &stor_mounts), }); } Storages { storage_devices: devices } } #[allow(dead_code)] async fn storage_partitions(stor_name: &str) -> Result<Partitions> { let stor_dev = fs::read_to_string(SysProperty::StorDev.path())?; let stor_mounts = fs::read_to_string(SysProperty::StorMounts.path())?; Ok(_storage_partitions(&stor_name, &stor_dev, &stor_mounts)) } pub(crate) fn _storage_partitions(stor_name: &str, stor_dev: &str, stor_mounts: &str) -> Partitions { let mut partitions = vec![]; let re = Regex::new(r"(?m)^\s*(\d*)\s*(\d*)\s*(\d*)\s(\w*\d+)$").unwrap(); let re2 = Regex::new(r"/dev/(\w*)\s(\S*)\s(\S*)").unwrap(); for storage_dev in re.captures_iter(&stor_dev).filter(|x| x[4].starts_with(stor_name)) { let mut partition = Partition::default(); let partition_name = &storage_dev[4]; for found_partition in re2.captures_iter(&stor_mounts) {
} partition.major = handle(storage_dev[1].parse::<u16>()); partition.minor = handle(storage_dev[2].parse::<u16>()); partition.size = handle(storage_dev[3].parse::<u64>()) * 1024; partition.name = partition_name.to_string(); partitions.push(partition); } partitions } pub async fn vgs() -> Result<VolGroups> { let mut vgs: Vec<VolGroup> = vec![]; let output = fs::read_to_string(SysProperty::StorDev.path())?; let re = Regex::new(r"(?m)\d*\s*dm-")?; if re.captures(&output).is_some() { let cmd = Command::new("vgdisplay").arg("--units").arg("b").output()?; let out = str::from_utf8(&cmd.stdout)?; let re = Regex::new( r"(?m)VG Name\s*(.*)\n.*\n\s*Format\s*(.*)$(?:\n.*){3}\s*VG Status\s*(.*)$(?:\n.*){6}$\s*VG Size\s*(\d*)", )?; for vg in re.captures_iter(&out) { vgs.push(VolGroup { name: vg[1].to_string(), format: vg[2].to_string(), status: vg[3].to_string(), size: handle(vg[4].parse::<u64>()), lvms: handle(lvms(vg[1].to_string()).await), }) } } Ok(VolGroups { vgs }) } async fn lvms(vg_name: String) -> Result<Vec<LogVolume>> { let mut lvms_vec: Vec<LogVolume> = vec![]; let cmd = Command::new("lvdisplay").arg("--units").arg("b").output()?; let out = str::from_utf8(&cmd.stdout)?; let re = Regex::new( r"(?m)LV Path\s*(.*)\n\s*LV Name\s*(.*)$\s*VG Name\s*(.*)$(?:\n.*){3}$\s*LV Status\s*(.*)\n.*$\n\s*LV Size\s*(\d*).*$(?:\n.*){5}\s*Block device\s*(\d*):(\d*)$", )?; for lvm in re.captures_iter(&out).filter(|lvm| lvm[3] == vg_name) { lvms_vec.push(LogVolume { name: lvm[2].to_string(), path: lvm[1].to_string(), vg: lvm[3].to_string(), status: lvm[4].to_string(), size: handle(lvm[5].parse::<u64>()), major: handle(lvm[6].parse::<u16>()), minor: handle(lvm[7].parse::<u16>()), mountpoint: "".to_string(), }) } Ok(lvms_vec) } pub async fn graphics_card() -> Result<String> { let cmd = Command::new("lspci").output()?; let out = str::from_utf8(&cmd.stdout)?; Ok(_graphics_card(&out)) } pub(crate) fn _graphics_card(out: &str) -> String { let re = Regex::new(r"(?m)VGA compatible controller:\s*(.*)$").unwrap(); re.captures(&out).map_or("".to_string(), |vga| vga[1].to_string()) } #[allow(dead_code)] async fn ipv4_addr(interface_name: &str) -> Result<Ipv4Addr> { let route = fs::read_to_string(SysProperty::Route.path())?; let fib_trie = fs::read_to_string(SysProperty::FibTrie.path())?; _ipv4_addr(&interface_name, &route, &fib_trie) } pub(crate) fn _ipv4_addr(interface_name: &str, route: &str, fib_trie: &str) -> Result<Ipv4Addr> { let mut iface_dest = "".to_string(); let mut ip_addr = Ipv4Addr::UNSPECIFIED; if interface_name == "lo" { Ok(Ipv4Addr::LOCALHOST) } else { let re = Regex::new(r"(?m)^([\d\w]*)\s*([\d\w]*)")?; for dest in re.captures_iter(&route) { if &dest[1] == interface_name && &dest[2] != "00000000" { iface_dest = utils::conv_hex_to_ip(&dest[2])?; } } let file = fib_trie.split('\n').collect::<Vec<&str>>(); let re = Regex::new(r"\|--\s+(.*)")?; let mut found = false; for (i, line) in (&file).iter().enumerate() { if (*line).to_string().contains(&iface_dest) { found = true; } else if found && (*line).to_string().contains("/32 host LOCAL") { ip_addr = match re.captures(&file[i - 1]) { Some(n) => Ipv4Addr::from_str(&n[1])?, None => Ipv4Addr::UNSPECIFIED, }; break; } } Ok(ip_addr) } } #[allow(dead_code)] async fn ipv6_addr(interface_name: &str) -> Result<Ipv6Addr> { let output = fs::read_to_string(SysProperty::IfInet6.path())?; _ipv6_addr(&interface_name, &output) } pub(crate) fn _ipv6_addr(interface_name: &str, out: &str) -> Result<Ipv6Addr> { if interface_name == "lo" { Ok(Ipv6Addr::LOCALHOST) } else { let mut ip_addr = Ipv6Addr::UNSPECIFIED; let re = Regex::new(r"(?m)^([\d\w]*)\s\d*\s\d*\s\d*\s\d*\s*(.*)$").unwrap(); for capture in re.captures_iter(&out) { if &capture[2] == interface_name { ip_addr = Ipv6Addr::from_str(&format!( "{}:{}:{}:{}:{}:{}:{}:{}", &capture[1][..4], &capture[1][4..8], &capture[1][8..12], &capture[1][12..16], &capture[1][16..20], &capture[1][20..24], &capture[1][24..28], &capture[1][28..32] ))?; break; } } Ok(ip_addr) } } pub async fn temperatures() -> Result<Temperatures> { let paths = fs::read_dir(SysProperty::Temperature.path())?; let mut devices: Vec<DeviceSensors> = vec![]; let re = Regex::new(r"temp[\d]+_input")?; for dir_entry in paths { let mut sensor_count = 0; let path = dir_entry?.path(); let mut dev = DeviceSensors::default(); let mut dev_temps: Vec<Sensor> = vec![]; dev.name = fs::read_to_string(path.join("name"))?.trim().to_string(); for temp_file in fs::read_dir(&path)? { if re.is_match(&temp_file?.path().to_str().unwrap()) { sensor_count += 1; } } for i in 1..=sensor_count { dev_temps.push(sensor(&path, i).await?); } dev.sensors = dev_temps; devices.push(dev); } Ok(Temperatures { temp_devices: devices }) } pub async fn sensor<P: AsRef<Path>>(path: P, i: i32) -> Result<Sensor> { let mut sensor = Sensor::default(); sensor.name = fs::read_to_string(path.as_ref().join(format!("temp{}_label", i))) .unwrap_or_else(|_| "".to_string()) .trim() .to_string(); sensor.temp = handle(fs::read_to_string(path.as_ref().join(format!("temp{}_input", i)))?.trim().parse::<f32>()) / 1000.; Ok(sensor) }
if &found_partition[1] == partition_name { partition.mountpoint = found_partition[2].to_string(); partition.filesystem = found_partition[3].to_string(); break; } else { partition.mountpoint = "".to_string(); partition.filesystem = "".to_string(); }
if_condition
[]
Rust
src/graph.rs
fexolm/max_clique
c181294902c53842fd06450c7a1618daf5bc270b
use std::collections::*; use std::fs::File; use std::io::*; use std::iter::*; use std::sync::Arc; use std::sync::RwLock; use std::u64; use rayon::{Scope}; use regex::Regex; pub struct Graph { adj_list: HashMap<u16, HashSet<u16>>, } pub struct MaxCliqueData { max_clique: Vec<u16>, current_clique: Vec<u16>, } fn parse_line(reader: &mut BufReader<File>) -> Option<(u16, u16)> { lazy_static! { static ref RE: Regex = Regex::new(r"^e (\d+) (\d+)").unwrap(); } loop { let mut text = String::new(); match reader.read_line(&mut text) { Ok(size) if size > 0 => { if let Some(caps) = RE.captures(&text) { return Some((caps.get(1).unwrap().as_str().parse::<u16>().unwrap(), caps.get(2).unwrap().as_str().parse::<u16>().unwrap())); } } _ => return None } } } macro_rules! get_entry { ($map:expr, $key:expr) => (*($map.entry($key).or_insert(HashSet::new()))) } impl Graph { pub fn read(filename: &str) -> Result<Arc<Self>> { let mut adj_list: HashMap<u16, HashSet<u16>> = HashMap::new(); let file = File::open(filename)?; let mut reader = BufReader::new(file); while let Some((from, to)) = parse_line(&mut reader) { get_entry!(adj_list, from).insert(to); get_entry!(adj_list, to).insert(from); } Ok(Arc::new(Graph { adj_list, })) } fn degree(&self, node: u16) -> u16 { self.neighbours(node).len() as u16 } fn neighbours(&self, node: u16) -> &HashSet<u16> { &self.adj_list[&node] } fn subgraph_neighbours<'i>(&'i self, subgraph: &'i HashSet<u16>, node: u16) -> impl Iterator<Item=&'i u16> { self.neighbours(node).intersection(subgraph) } fn clique_heuristic(&self, data: &mut MaxCliqueData, mut vertexes: HashSet<u16>) { if vertexes.is_empty() { if data.current_clique.len() > data.max_clique.len() { data.max_clique = data.current_clique.clone(); } return } let best_vertex = vertexes.iter().copied().max_by_key( |v| self.subgraph_neighbours(&vertexes, *v).count()).unwrap(); let neighbours = HashSet::from_iter( self.subgraph_neighbours(&vertexes, best_vertex).copied() .filter(|n| self.degree(*n) >= data.max_clique.len() as u16)); vertexes.remove(&best_vertex); data.current_clique.push(best_vertex); self.clique_heuristic(data, neighbours); data.current_clique.pop(); } fn max_clique_heuristic(&self, data: &mut MaxCliqueData) { let mut queue = BinaryHeap::from_iter( self.adj_list.keys().copied().map(|n| (self.degree(n), n))); while let Some((_, node)) = queue.pop() { if self.degree(node) > data.max_clique.len() as u16 { data.current_clique.push(node); self.clique_heuristic(data, HashSet::from_iter( self.neighbours(node).iter().copied() .filter(|n| self.degree(*n) > data.max_clique.len() as u16) )); data.current_clique.pop(); } } } fn greedy_coloring(&self, vertexes: &HashSet<u16>) -> HashMap<u16, i16> { let mut res = HashMap::new(); let mut powers = Vec::from_iter( vertexes.iter().copied() .map(|v| (v, Vec::from_iter(self.subgraph_neighbours(vertexes, v)))) ); powers.sort_unstable_by_key(|(_, v)| -(v.len() as i32)); let mut used = [0; 16]; let use_col = |arr: &mut [u64], c: i16| { arr[(c / 64) as usize] |= 1u64 << (c % 64) as u64; }; let min_col = |arr: &[u64]| { for i in 0..16 { if arr[i] != !0u64 { return (64 * i + (!arr[i]).trailing_zeros() as usize) as i16; } } unreachable!() }; for (node, neighbours) in powers { for neighbour in neighbours { if let Some(&val) = res.get(neighbour) { use_col(&mut used, val); } } res.insert(node, min_col(&used)); used = [0; 16]; } res } } fn max_clique_impl(graph: Arc<Graph>, max_clique: Arc<RwLock<Vec<u16>>>, current_clique: &mut Vec<u16>, mut vertexes: HashSet<u16>, s: &Scope) { { let len = max_clique.read().unwrap().len(); if current_clique.len() > len { println!("New max len: {}", len); *max_clique.write().unwrap() = current_clique.clone(); } } let coloring = graph.greedy_coloring(&vertexes); let mut candidates = Vec::from_iter(coloring.iter()); candidates.sort_unstable_by_key(|(_, &c)| -c); for (&v, &c) in candidates { { if current_clique.len() + c as usize + 1 <= max_clique.read().unwrap().len() { return; } } vertexes.remove(&v); let neighbours = HashSet::from_iter( graph.subgraph_neighbours(&vertexes, v).copied()); let mut cur_clique = current_clique.clone(); let g = graph.clone(); let mc = max_clique.clone(); s.spawn(move |sc| { cur_clique.push(v); max_clique_impl(g, mc, &mut cur_clique, neighbours, sc); cur_clique.pop(); }); } } pub fn get_max_clique(graph: Arc<Graph>) -> Vec<u16> { let mut data = MaxCliqueData { max_clique: vec!(), current_clique: vec!() }; graph.max_clique_heuristic(&mut data); println!("Heuristic best: {}", data.max_clique.len()); let max_clique = Arc::new(RwLock::new(data.max_clique)); rayon::scope(|s| { max_clique_impl(graph.clone(), max_clique.clone(), &mut vec!(), HashSet::from_iter(graph.adj_list.keys().cloned()), s); }); let res = max_clique.read().unwrap(); res.clone() }
use std::collections::*; use std::fs::File; use std::io::*; use std::iter::*; use std::sync::Arc; use std::sync::RwLock; use std::u64; use rayon::{Scope}; use regex::Regex; pub struct Graph { adj_list: HashMap<u16, HashSet<u16>>, } pub struct MaxCliqueData { max_clique: Vec<u16>, current_clique: Vec<u16>, } fn parse_line(reader: &mut BufReader<File>) -> Option<(u16, u16)> { lazy_static! { static ref RE: Regex = Regex::new(r"^e (\d+) (\d+)").unwrap(); } loop { let mut text = String::new(); match reader.read_line(&mut text) { Ok(size) if size > 0 => { if let Some(caps) = RE.captures(&text) { return Some((caps.get(1).unwrap().as_str().parse::<u16>().unwrap(), caps.get(2).unwrap().as_str().parse::<u16>().unwrap())); } } _ => return None } } } macro_rules! get_entry { ($map:expr, $key:expr) => (*($map.entry($key).or_insert(HashSet::new()))) } impl Graph { pub fn read(filename: &str) -> Result<Arc<Self>> { let mut adj_list: HashMap<u16, HashSet<u16>> = HashMap::new(); let file = File::open(filename)?; let mut reader = BufReader::new(file); while let Some((from, to)) = parse_line(&mut reader) { get_entry!(adj_list, from).insert(to); get_entry!(adj_list, to).insert(from); } Ok(Arc::new(Graph { adj_list, })) } fn degree(&self, node: u16) -> u16 { self.neighbours(node).len() as u16 } fn neighbours(&self, node: u16) -> &HashSet<u16> { &self.adj_list[&node] } fn subgraph_neighbours<'i>(&'i self, subgraph: &'i HashSet<u16>, node: u16) -> impl Iterator<Item=&'i u16> { self.neighbours(node).intersection(subgraph) } fn clique_heuristic(&self, data: &mut MaxCliqueData, mut vertexes: HashSet<u16>) { if vertexes.is_empty() { if data.current_clique.len() > data.max_clique.len() { data.max_clique = data.current_clique.clone(); } return } let best_vertex = vertexes.iter().copied().max_by_key( |v| self.subgraph_neighbours(&vertexes, *v).count()).unwrap(); let neighbours = HashSet::from_iter( self.subgraph_neighbours(&vertexes, best_vertex).copied() .filter(|n| self.degree(*n) >= data.max_clique.len() as u16)); vertexes.remove(&best_vertex); data.current_clique.push(best_vertex); self.clique_heuristic(data, neighbours); data.current_clique.pop(); }
fn greedy_coloring(&self, vertexes: &HashSet<u16>) -> HashMap<u16, i16> { let mut res = HashMap::new(); let mut powers = Vec::from_iter( vertexes.iter().copied() .map(|v| (v, Vec::from_iter(self.subgraph_neighbours(vertexes, v)))) ); powers.sort_unstable_by_key(|(_, v)| -(v.len() as i32)); let mut used = [0; 16]; let use_col = |arr: &mut [u64], c: i16| { arr[(c / 64) as usize] |= 1u64 << (c % 64) as u64; }; let min_col = |arr: &[u64]| { for i in 0..16 { if arr[i] != !0u64 { return (64 * i + (!arr[i]).trailing_zeros() as usize) as i16; } } unreachable!() }; for (node, neighbours) in powers { for neighbour in neighbours { if let Some(&val) = res.get(neighbour) { use_col(&mut used, val); } } res.insert(node, min_col(&used)); used = [0; 16]; } res } } fn max_clique_impl(graph: Arc<Graph>, max_clique: Arc<RwLock<Vec<u16>>>, current_clique: &mut Vec<u16>, mut vertexes: HashSet<u16>, s: &Scope) { { let len = max_clique.read().unwrap().len(); if current_clique.len() > len { println!("New max len: {}", len); *max_clique.write().unwrap() = current_clique.clone(); } } let coloring = graph.greedy_coloring(&vertexes); let mut candidates = Vec::from_iter(coloring.iter()); candidates.sort_unstable_by_key(|(_, &c)| -c); for (&v, &c) in candidates { { if current_clique.len() + c as usize + 1 <= max_clique.read().unwrap().len() { return; } } vertexes.remove(&v); let neighbours = HashSet::from_iter( graph.subgraph_neighbours(&vertexes, v).copied()); let mut cur_clique = current_clique.clone(); let g = graph.clone(); let mc = max_clique.clone(); s.spawn(move |sc| { cur_clique.push(v); max_clique_impl(g, mc, &mut cur_clique, neighbours, sc); cur_clique.pop(); }); } } pub fn get_max_clique(graph: Arc<Graph>) -> Vec<u16> { let mut data = MaxCliqueData { max_clique: vec!(), current_clique: vec!() }; graph.max_clique_heuristic(&mut data); println!("Heuristic best: {}", data.max_clique.len()); let max_clique = Arc::new(RwLock::new(data.max_clique)); rayon::scope(|s| { max_clique_impl(graph.clone(), max_clique.clone(), &mut vec!(), HashSet::from_iter(graph.adj_list.keys().cloned()), s); }); let res = max_clique.read().unwrap(); res.clone() }
fn max_clique_heuristic(&self, data: &mut MaxCliqueData) { let mut queue = BinaryHeap::from_iter( self.adj_list.keys().copied().map(|n| (self.degree(n), n))); while let Some((_, node)) = queue.pop() { if self.degree(node) > data.max_clique.len() as u16 { data.current_clique.push(node); self.clique_heuristic(data, HashSet::from_iter( self.neighbours(node).iter().copied() .filter(|n| self.degree(*n) > data.max_clique.len() as u16) )); data.current_clique.pop(); } } }
function_block-full_function
[ { "content": "fn print_clique(v: &Vec<u16>) {\n\n for &n in v {\n\n print!(\"{} \", n);\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 3, "score": 38032.75972512833 }, { "content": "fn main() -> Result<()> {\n\n use graph::Graph;\n\n use time::PreciseTime;\n\n\n\n // yes, hardcoded string here\n\n let graph = Graph::read(r\"C:\\Users\\artem\\Downloads\\brock400_2.clq.txt\")?;\n\n\n\n let start = PreciseTime::now();\n\n let max_clique = graph::get_max_clique(graph.clone());\n\n let end = PreciseTime::now();\n\n\n\n let spent = start.to(end);\n\n let sec = spent.num_seconds() - 60 * spent.num_minutes();\n\n let min = spent.num_minutes() - 60 * spent.num_hours();\n\n let hours = spent.num_hours();\n\n println!(\"time spent: {}h {}m {}s\", hours, min, sec);\n\n println!(\"Max clique size: {}\", max_clique.len());\n\n print_clique(&max_clique);\n\n Ok(())\n\n}\n", "file_path": "src/main.rs", "rank": 4, "score": 15200.376041941792 }, { "content": "#[macro_use]\n\nextern crate lazy_static;\n\nextern crate regex;\n\nextern crate time;\n\n\n\nuse std::io::Result;\n\n\n\nmod graph;\n\n\n", "file_path": "src/main.rs", "rank": 12, "score": 4.212971738551787 } ]
Rust
necsim/impls/std/src/cogs/active_lineage_sampler/gillespie/sampler.rs
fossabot/necsim-rust
996b6a6977bc27a997a123e3e4f5a7b11e1a1aef
use necsim_core::{ cogs::{ ActiveLineageSampler, CoalescenceSampler, DispersalSampler, EmigrationExit, EmptyActiveLineageSamplerError, GloballyCoherentLineageStore, Habitat, ImmigrationEntry, LineageReference, PeekableActiveLineageSampler, RngCore, SpeciationProbability, TurnoverRate, }, landscape::IndexedLocation, lineage::GlobalLineageReference, simulation::partial::active_lineager_sampler::PartialSimulation, }; use necsim_core_bond::{NonNegativeF64, PositiveF64}; use necsim_impls_no_std::cogs::event_sampler::gillespie::{ GillespieEventSampler, GillespiePartialSimulation, }; use super::{EventTime, GillespieActiveLineageSampler}; #[contract_trait] impl< H: Habitat, G: RngCore, R: LineageReference<H>, S: GloballyCoherentLineageStore<H, R>, X: EmigrationExit<H, G, R, S>, D: DispersalSampler<H, G>, C: CoalescenceSampler<H, R, S>, T: TurnoverRate<H>, N: SpeciationProbability<H>, E: GillespieEventSampler<H, G, R, S, X, D, C, T, N>, I: ImmigrationEntry, > ActiveLineageSampler<H, G, R, S, X, D, C, T, N, E, I> for GillespieActiveLineageSampler<H, G, R, S, X, D, C, T, N, E, I> { #[must_use] fn number_active_lineages(&self) -> usize { self.number_active_lineages } #[must_use] fn get_last_event_time(&self) -> NonNegativeF64 { self.last_event_time } #[must_use] fn pop_active_lineage_indexed_location_prior_event_time( &mut self, simulation: &mut PartialSimulation<H, G, R, S, X, D, C, T, N, E>, rng: &mut G, ) -> Option<(R, IndexedLocation, NonNegativeF64, PositiveF64)> { use necsim_core::cogs::RngSampler; let (chosen_active_location, chosen_event_time) = self.active_locations.pop()?; let unique_event_time = PositiveF64::max_after(self.last_event_time, chosen_event_time.into()); let lineages_at_location = simulation .lineage_store .get_active_local_lineage_references_at_location_unordered( &chosen_active_location, &simulation.habitat, ); let number_lineages_left_at_location = lineages_at_location.len() - 1; let chosen_lineage_index_at_location = rng.sample_index(lineages_at_location.len()); let chosen_lineage_reference = lineages_at_location[chosen_lineage_index_at_location].clone(); let (lineage_indexed_location, prior_event_time) = simulation .lineage_store .extract_lineage_from_its_location_globally_coherent( chosen_lineage_reference.clone(), unique_event_time, &simulation.habitat, ); self.number_active_lineages -= 1; if number_lineages_left_at_location > 0 { if let Ok(event_rate_at_location) = PositiveF64::new( simulation .with_split_event_sampler(|event_sampler, simulation| { GillespiePartialSimulation::without_emigration_exit( simulation, |simulation| { event_sampler .get_event_rate_at_location(&chosen_active_location, simulation) }, ) }) .get(), ) { self.active_locations.push( chosen_active_location, EventTime::from( unique_event_time + rng.sample_exponential(event_rate_at_location), ), ); } } self.last_event_time = unique_event_time.into(); Some(( chosen_lineage_reference, lineage_indexed_location, prior_event_time, unique_event_time, )) } #[debug_requires( simulation.lineage_store.get_active_local_lineage_references_at_location_unordered( indexed_location.location(), &simulation.habitat ).len() < ( simulation.habitat.get_habitat_at_location(indexed_location.location()) as usize ), "location has habitat capacity for the lineage" )] fn push_active_lineage_to_indexed_location( &mut self, lineage_reference: R, indexed_location: IndexedLocation, time: PositiveF64, simulation: &mut PartialSimulation<H, G, R, S, X, D, C, T, N, E>, rng: &mut G, ) { use necsim_core::cogs::RngSampler; let location = indexed_location.location().clone(); simulation .lineage_store .insert_lineage_to_indexed_location_globally_coherent( lineage_reference, indexed_location, &simulation.habitat, ); if let Ok(event_rate_at_location) = PositiveF64::new( simulation .with_split_event_sampler(|event_sampler, simulation| { GillespiePartialSimulation::without_emigration_exit(simulation, |simulation| { event_sampler.get_event_rate_at_location(&location, simulation) }) }) .get(), ) { self.active_locations.push( location, EventTime::from(time + rng.sample_exponential(event_rate_at_location)), ); self.number_active_lineages += 1; } self.last_event_time = time.into(); } fn insert_new_lineage_to_indexed_location( &mut self, global_reference: GlobalLineageReference, indexed_location: IndexedLocation, time: PositiveF64, simulation: &mut PartialSimulation<H, G, R, S, X, D, C, T, N, E>, rng: &mut G, ) { use necsim_core::cogs::RngSampler; let location = indexed_location.location().clone(); let _immigrant_lineage_reference = simulation.lineage_store.immigrate_globally_coherent( &simulation.habitat, global_reference, indexed_location, time, ); if let Ok(event_rate_at_location) = PositiveF64::new( simulation .with_split_event_sampler(|event_sampler, simulation| { GillespiePartialSimulation::without_emigration_exit(simulation, |simulation| { event_sampler.get_event_rate_at_location(&location, simulation) }) }) .get(), ) { self.active_locations.push( location, EventTime::from(time + rng.sample_exponential(event_rate_at_location)), ); self.number_active_lineages += 1; } self.last_event_time = time.into(); } } #[contract_trait] impl< H: Habitat, G: RngCore, R: LineageReference<H>, S: GloballyCoherentLineageStore<H, R>, X: EmigrationExit<H, G, R, S>, D: DispersalSampler<H, G>, C: CoalescenceSampler<H, R, S>, T: TurnoverRate<H>, N: SpeciationProbability<H>, E: GillespieEventSampler<H, G, R, S, X, D, C, T, N>, I: ImmigrationEntry, > PeekableActiveLineageSampler<H, G, R, S, X, D, C, T, N, E, I> for GillespieActiveLineageSampler<H, G, R, S, X, D, C, T, N, E, I> { fn peek_time_of_next_event( &mut self, _habitat: &H, _turnover_rate: &T, _rng: &mut G, ) -> Result<PositiveF64, EmptyActiveLineageSamplerError> { self.active_locations .peek() .map(|(_, next_event_time)| { PositiveF64::max_after(self.last_event_time, (*next_event_time).into()) }) .ok_or(EmptyActiveLineageSamplerError) } }
use necsim_core::{ cogs::{ ActiveLineageSampler, CoalescenceSampler, DispersalSampler, EmigrationExit, EmptyActiveLineageSamplerError, GloballyCoherentLineageStore, Habitat, ImmigrationEntry, LineageReference, PeekableActiveLineageSampler, RngCore, SpeciationProbability, TurnoverRate, }, landscape::IndexedLocation, lineage::GlobalLineageReference, simulation::partial::active_lineager_sampler::PartialSimulation, }; use necsim_core_bond::{NonNegativeF64, PositiveF64}; use necsim_impls_no_std::cogs::event_sampler::gillespie::{ GillespieEventSampler, GillespiePartialSimulation, }; use super::{EventTime, GillespieActiveLineageSampler}; #[contract_trait] impl< H: Habitat, G: RngCore, R: LineageReference<H>, S: GloballyCoherentLineageStore<H, R>, X: EmigrationExit<H, G, R, S>, D: DispersalSampler<H, G>, C: CoalescenceSampler<H, R, S>, T: TurnoverRate<H>, N: SpeciationProbability<H>, E: GillespieEventSampler<H, G, R, S, X, D, C, T, N>, I: ImmigrationEntry, > ActiveLineageSampler<H, G, R, S, X, D, C, T, N, E, I> for GillespieActiveLineageSampler<H, G, R, S, X, D, C, T, N, E, I> { #[must_use] fn number_active_lineages(&self) -> usize { self.number_active_lineages } #[must_use] fn get_last_event_time(&self) -> NonNegativeF64 { self.last_event_time } #[must_use] fn pop_active_lineage_indexed_location_prior_event_time( &mut self, simulation: &mut PartialSimulation<H, G, R, S, X, D, C, T, N, E>, rng: &mut G, ) -> Option<(R, IndexedLocation, NonNegativeF64, PositiveF64)> { use necsim_core::cogs::RngSampler; let (chosen_active_location, chosen_event_time) = self.active_locations.pop()?; let unique_event_time = PositiveF64::max_after(self.last_event_time, chosen_event_time.into()); let lineages_at_location = simulation .lineage_store .get_active_local_lineage_references_at_location_unordered( &chosen_active_location, &simulation.habitat, ); let number_lineages_left_at_location = lineages_at_location.len() - 1; let chosen_lineage_index_at_location = rng.sample_index(lineages_at_location.len()); let chosen_lineage_reference = lineages_at_location[chosen_lineage_index_at_location].clone(); let (lineage_indexed_location, prior_event_time) = simulation .lineage_store .extract_lineage_from_its_location_globally_coherent( chosen_lineage_reference.clone(), unique_event_time, &simulation.habitat, ); self.number_active_lineages -= 1; if number_lineages_left_at_location > 0 { if let Ok(event_rate_at_location) = PositiveF64::new( simulation .with_split_event_sampler(|event_sampler, simulation| { GillespiePartialSimulation::without_emigration_exit( simulation, |simulation| { event_sampler .get_event_rate_at_location(&chosen_active_location, simulation) }, ) }) .get(), ) { self.active_locations.push( chosen_active_location, EventTime::from( unique_event_time + rng.sample_exponential(event_rate_at_location), ), ); } } self.last_event_time = unique_event_time.into(); Some(( chosen_lineage_reference, lineage_indexed_location, prior_event_time, unique_event_time, )) } #[debug_requires( simulation.lineage_store.get_active_local_lineage_references_at_location_unordered( indexed_location.location(), &simulation.habitat ).len() < ( simulation.habitat.get_habitat_at_location(indexed_location.location()) as usize ), "location has habitat capacity for the lineage" )] fn push_active_lineage_to_indexed_location( &mut self, lineage_reference: R, indexed_location: IndexedLocation, time: PositiveF64, simulation: &mut PartialSimulation<H, G, R, S, X, D, C, T, N, E>, rng: &mut G, ) { use necsim_core::cogs::RngSampler; let location = indexed_location.location().clone(); simulation .lineage_store .insert_lineage_to_indexed_location_globally_coherent( lineage_reference, indexed_location, &simulation.habitat, ); if let Ok(event_rate_at_location) = PositiveF64::new( simulation .with_split_event_sampler(|event_sampler, simulation| { GillespiePartialSimulation::without_emigration_exit(simulation, |simulation| { event_sampler.get_event_rate_at_location(&location, simulation) }) }) .get(), ) { self.active_locations.push( location, EventTime::from(time + rng.sample_exponential(event_rate_at_location)), ); self.number_active_lineages += 1; } self.last_event_time = time.into(); }
} #[contract_trait] impl< H: Habitat, G: RngCore, R: LineageReference<H>, S: GloballyCoherentLineageStore<H, R>, X: EmigrationExit<H, G, R, S>, D: DispersalSampler<H, G>, C: CoalescenceSampler<H, R, S>, T: TurnoverRate<H>, N: SpeciationProbability<H>, E: GillespieEventSampler<H, G, R, S, X, D, C, T, N>, I: ImmigrationEntry, > PeekableActiveLineageSampler<H, G, R, S, X, D, C, T, N, E, I> for GillespieActiveLineageSampler<H, G, R, S, X, D, C, T, N, E, I> { fn peek_time_of_next_event( &mut self, _habitat: &H, _turnover_rate: &T, _rng: &mut G, ) -> Result<PositiveF64, EmptyActiveLineageSamplerError> { self.active_locations .peek() .map(|(_, next_event_time)| { PositiveF64::max_after(self.last_event_time, (*next_event_time).into()) }) .ok_or(EmptyActiveLineageSamplerError) } }
fn insert_new_lineage_to_indexed_location( &mut self, global_reference: GlobalLineageReference, indexed_location: IndexedLocation, time: PositiveF64, simulation: &mut PartialSimulation<H, G, R, S, X, D, C, T, N, E>, rng: &mut G, ) { use necsim_core::cogs::RngSampler; let location = indexed_location.location().clone(); let _immigrant_lineage_reference = simulation.lineage_store.immigrate_globally_coherent( &simulation.habitat, global_reference, indexed_location, time, ); if let Ok(event_rate_at_location) = PositiveF64::new( simulation .with_split_event_sampler(|event_sampler, simulation| { GillespiePartialSimulation::without_emigration_exit(simulation, |simulation| { event_sampler.get_event_rate_at_location(&location, simulation) }) }) .get(), ) { self.active_locations.push( location, EventTime::from(time + rng.sample_exponential(event_rate_at_location)), ); self.number_active_lineages += 1; } self.last_event_time = time.into(); }
function_block-full_function
[ { "content": "#[contract_trait]\n\npub trait EmigrationExit<H: Habitat, G: RngCore, R: LineageReference<H>, S: LineageStore<H, R>>:\n\n crate::cogs::Backup + core::fmt::Debug\n\n{\n\n #[must_use]\n\n #[debug_ensures(match &ret {\n\n Some((\n\n ret_lineage_reference,\n\n ret_dispersal_origin,\n\n ret_dispersal_target,\n\n ret_prior_time,\n\n ret_event_time,\n\n )) => {\n\n ret_lineage_reference == &old(lineage_reference.clone()) &&\n\n ret_dispersal_origin == &old(dispersal_origin.clone()) &&\n\n ret_dispersal_target == &old(dispersal_target.clone()) &&\n\n ret_prior_time == &old(prior_time) &&\n\n ret_event_time == &old(event_time)\n\n },\n\n None => true,\n\n }, \"if ret is Some, it returns the input parameters unchanged\")]\n", "file_path": "necsim/core/src/cogs/emigration_exit.rs", "rank": 0, "score": 442210.9458263971 }, { "content": "#[allow(clippy::module_name_repetitions)]\n\n#[allow(clippy::inline_always, clippy::inline_fn_without_body)]\n\n#[contract_trait]\n\npub trait EventTimeSampler<H: Habitat, G: PrimeableRng, T: TurnoverRate<H>>:\n\n Clone + core::fmt::Debug\n\n{\n\n #[debug_requires(\n\n habitat.get_habitat_at_location(indexed_location.location()) > 0,\n\n \"indexed_location must be habitable\"\n\n )]\n\n #[debug_ensures(ret >= time, \"the next event will happen weakly after time\")]\n\n fn next_event_time_at_indexed_location_weakly_after(\n\n &self,\n\n indexed_location: &IndexedLocation,\n\n time: NonNegativeF64,\n\n habitat: &H,\n\n rng: &mut G,\n\n turnover_rate: &T,\n\n ) -> NonNegativeF64;\n\n}\n", "file_path": "necsim/impls/no-std/src/cogs/active_lineage_sampler/independent/event_time_sampler/mod.rs", "rank": 1, "score": 384088.87673975795 }, { "content": "#[allow(clippy::module_name_repetitions)]\n\n#[allow(clippy::inline_always, clippy::inline_fn_without_body)]\n\n#[contract_trait]\n\npub trait InMemoryDispersalSampler<H: Habitat, G: RngCore>: DispersalSampler<H, G> + Sized {\n\n #[debug_requires((\n\n dispersal.num_columns() == (\n\n (habitat.get_extent().width() * habitat.get_extent().height()) as usize\n\n ) && dispersal.num_rows() == (\n\n (habitat.get_extent().width() * habitat.get_extent().height()) as usize\n\n )\n\n ), \"dispersal dimensions are consistent\")]\n\n #[debug_requires(\n\n explicit_in_memory_dispersal_check_contract(dispersal, habitat),\n\n \"dispersal probabilities are consistent\"\n\n )]\n\n fn unchecked_new(dispersal: &Array2D<f64>, habitat: &H) -> Self;\n\n}\n", "file_path": "necsim/impls/no-std/src/cogs/dispersal_sampler/in_memory/mod.rs", "rank": 2, "score": 352473.406569776 }, { "content": "#[allow(clippy::module_name_repetitions)]\n\n#[allow(clippy::inline_always, clippy::inline_fn_without_body)]\n\n#[contract_trait]\n\npub trait InMemoryDispersalSampler<H: Habitat, G: RngCore>:\n\n InMemoryDispersalSamplerNoError<H, G> + Sized\n\n{\n\n #[debug_ensures(\n\n matches!(ret, Err(InMemoryDispersalSamplerError::InconsistentDispersalMapSize)) != (\n\n dispersal.num_columns() == old(\n\n (habitat.get_extent().width() * habitat.get_extent().height()) as usize\n\n ) && dispersal.num_rows() == old(\n\n (habitat.get_extent().width() * habitat.get_extent().height()) as usize\n\n )\n\n ),\n\n \"returns Err(InconsistentDispersalMapSize) iff the dispersal dimensions are inconsistent\"\n\n )]\n\n #[debug_ensures(\n\n matches!(ret, Err(\n\n InMemoryDispersalSamplerError::InconsistentDispersalProbabilities\n\n )) != old(\n\n explicit_in_memory_dispersal_check_contract(dispersal, habitat)\n\n ), \"returns Err(InconsistentDispersalProbabilities) iff the dispersal probabilities are inconsistent\"\n\n )]\n", "file_path": "necsim/impls/std/src/cogs/dispersal_sampler/in_memory/mod.rs", "rank": 3, "score": 344958.1022079651 }, { "content": "#[allow(clippy::inline_always, clippy::inline_fn_without_body)]\n\n#[allow(clippy::module_name_repetitions)]\n\n#[contract_trait]\n\npub trait SeparableDispersalSampler<H: Habitat, G: RngCore>: DispersalSampler<H, G> {\n\n #[must_use]\n\n #[debug_requires(habitat.contains(location), \"location is inside habitat\")]\n\n #[debug_ensures(old(habitat).contains(&ret), \"target is inside habitat\")]\n\n #[debug_ensures(&ret != location, \"disperses to a different location\")]\n\n fn sample_non_self_dispersal_from_location(\n\n &self,\n\n location: &Location,\n\n habitat: &H,\n\n rng: &mut G,\n\n ) -> Location;\n\n\n\n #[must_use]\n\n #[debug_requires(habitat.contains(location), \"location is inside habitat\")]\n\n fn get_self_dispersal_probability_at_location(\n\n &self,\n\n location: &Location,\n\n habitat: &H,\n\n ) -> ClosedUnitF64;\n\n}\n", "file_path": "necsim/core/src/cogs/dispersal_sampler.rs", "rank": 4, "score": 333459.7349511563 }, { "content": "#[allow(clippy::inline_always, clippy::inline_fn_without_body)]\n\n#[contract_trait]\n\npub trait LineageStore<H: Habitat, R: LineageReference<H>>:\n\n crate::cogs::Backup + Sized + core::fmt::Debug\n\n{\n\n type LineageReferenceIterator<'a>: Iterator<Item = R>;\n\n\n\n #[must_use]\n\n fn from_origin_sampler<'h, O: OriginSampler<'h, Habitat = H>>(origin_sampler: O) -> Self\n\n where\n\n H: 'h;\n\n\n\n #[must_use]\n\n fn get_number_total_lineages(&self) -> usize;\n\n\n\n #[must_use]\n\n fn iter_local_lineage_references(&self) -> Self::LineageReferenceIterator<'_>;\n\n\n\n #[must_use]\n\n fn get(&self, reference: R) -> Option<&Lineage>;\n\n}\n\n\n", "file_path": "necsim/core/src/cogs/lineage_store.rs", "rank": 5, "score": 327377.1780122654 }, { "content": "#[allow(clippy::inline_always, clippy::inline_fn_without_body)]\n\n#[contract_trait]\n\npub trait CoalescenceSampler<H: Habitat, R: LineageReference<H>, S: LineageStore<H, R>>:\n\n crate::cogs::Backup + core::fmt::Debug\n\n{\n\n #[must_use]\n\n #[debug_requires(habitat.get_habitat_at_location(&location) > 0, \"location is habitable\")]\n\n fn sample_interaction_at_location(\n\n &self,\n\n location: Location,\n\n habitat: &H,\n\n lineage_store: &S,\n\n coalescence_rng_sample: CoalescenceRngSample,\n\n ) -> (IndexedLocation, LineageInteraction);\n\n}\n\n\n\n#[derive(Debug, PartialEq)]\n\n#[cfg_attr(feature = \"mpi\", derive(mpi::traits::Equivalence))]\n\npub struct CoalescenceRngSample(ClosedUnitF64);\n\n\n\n#[contract_trait]\n\nimpl Backup for CoalescenceRngSample {\n", "file_path": "necsim/core/src/cogs/coalescence_sampler.rs", "rank": 6, "score": 326479.6645554225 }, { "content": "#[allow(clippy::inline_always, clippy::inline_fn_without_body)]\n\n#[allow(clippy::module_name_repetitions)]\n\n#[contract_trait]\n\npub trait LocallyCoherentLineageStore<H: Habitat, R: LineageReference<H>>:\n\n LineageStore<H, R> + Index<R, Output = Lineage>\n\n{\n\n #[must_use]\n\n #[debug_requires(\n\n habitat.contains(indexed_location.location()),\n\n \"indexed location is inside habitat\"\n\n )]\n\n fn get_active_global_lineage_reference_at_indexed_location(\n\n &self,\n\n indexed_location: &IndexedLocation,\n\n habitat: &H,\n\n ) -> Option<&GlobalLineageReference>;\n\n\n\n #[debug_requires(\n\n habitat.contains(indexed_location.location()),\n\n \"indexed location is inside habitat\"\n\n )]\n\n #[debug_requires(self.get(reference.clone()).is_some(), \"lineage reference is valid\")]\n\n #[debug_requires(!self[reference.clone()].is_active(), \"lineage is inactive\")]\n", "file_path": "necsim/core/src/cogs/lineage_store.rs", "rank": 7, "score": 320693.4490262261 }, { "content": "#[allow(clippy::inline_always, clippy::inline_fn_without_body)]\n\n#[allow(clippy::module_name_repetitions)]\n\n#[contract_trait]\n\npub trait GloballyCoherentLineageStore<H: Habitat, R: LineageReference<H>>:\n\n LocallyCoherentLineageStore<H, R>\n\n{\n\n type LocationIterator<'a>: Iterator<Item = Location>;\n\n\n\n #[must_use]\n\n fn iter_active_locations(&self, habitat: &H) -> Self::LocationIterator<'_>;\n\n\n\n #[must_use]\n\n #[debug_requires(habitat.contains(location), \"location is inside habitat\")]\n\n fn get_active_local_lineage_references_at_location_unordered(\n\n &self,\n\n location: &Location,\n\n habitat: &H,\n\n ) -> &[R];\n\n\n\n #[debug_ensures(\n\n self.get_active_local_lineage_references_at_location_unordered(\n\n &old(indexed_location.location().clone()), old(habitat)\n\n ).last() == Some(&old(reference.clone())),\n", "file_path": "necsim/core/src/cogs/lineage_store.rs", "rank": 8, "score": 320693.4490262261 }, { "content": "#[allow(clippy::module_name_repetitions)]\n\npub fn explicit_in_memory_dispersal_check_contract<H: Habitat>(\n\n dispersal: &Array2D<f64>,\n\n habitat: &H,\n\n) -> bool {\n\n let habitat_width = habitat.get_extent().width();\n\n\n\n for row_index in 0..dispersal.num_rows() {\n\n #[allow(clippy::cast_possible_truncation)]\n\n let dispersal_origin = Location::new(\n\n (row_index % habitat_width as usize) as u32,\n\n (row_index / habitat_width as usize) as u32,\n\n );\n\n\n\n if habitat.get_habitat_at_location(&dispersal_origin) > 0 {\n\n let mut any_dispersal = false;\n\n\n\n for col_index in 0..dispersal.num_columns() {\n\n #[allow(clippy::cast_possible_truncation)]\n\n let dispersal_target = Location::new(\n\n (col_index % habitat_width as usize) as u32,\n", "file_path": "necsim/impls/no-std/src/cogs/dispersal_sampler/in_memory/contract.rs", "rank": 9, "score": 286813.664825672 }, { "content": "#[allow(clippy::inline_always, clippy::inline_fn_without_body)]\n\n#[allow(clippy::module_name_repetitions)]\n\n#[contract_trait]\n\npub trait DispersalSampler<H: Habitat, G: RngCore>: crate::cogs::Backup + core::fmt::Debug {\n\n #[must_use]\n\n #[debug_requires(habitat.contains(location), \"location is inside habitat\")]\n\n #[debug_ensures(old(habitat).contains(&ret), \"target is inside habitat\")]\n\n fn sample_dispersal_from_location(\n\n &self,\n\n location: &Location,\n\n habitat: &H,\n\n rng: &mut G,\n\n ) -> Location;\n\n}\n\n\n", "file_path": "necsim/core/src/cogs/dispersal_sampler.rs", "rank": 10, "score": 283430.30331224354 }, { "content": "#[inline]\n\n#[allow(clippy::cast_possible_truncation)]\n\nfn wymum(mut a: u64, mut b: u64) -> u64 {\n\n // WyHash diffusion function\n\n // https://docs.rs/wyhash/0.5.0/src/wyhash/functions.rs.html#8-12\n\n let r = u128::from(a) * u128::from(b);\n\n\n\n // WyHash condom\n\n // https://github.com/wangyi-fudan/wyhash/blob/master/wyhash.h#L57\n\n a ^= r as u64;\n\n b ^= (r >> 64) as u64;\n\n\n\n a ^ b\n\n}\n\n\n\n#[inline]\n\nconst fn seahash_diffuse(mut x: u64) -> u64 {\n\n // SeaHash diffusion function\n\n // https://docs.rs/seahash/4.1.0/src/seahash/helper.rs.html#75-92\n\n\n\n // These are derived from the PCG RNG's round. Thanks to @Veedrac for proposing\n\n // this. The basic idea is that we use dynamic shifts, which are determined\n", "file_path": "necsim/impls/no-std/src/cogs/rng/wyhash.rs", "rank": 11, "score": 282094.106960733 }, { "content": "#[allow(clippy::module_name_repetitions)]\n\npub trait HabitatPrimeableRng<H: Habitat>: PrimeableRng {\n\n #[inline]\n\n fn prime_with_habitat(\n\n &mut self,\n\n habitat: &H,\n\n indexed_location: &IndexedLocation,\n\n time_index: u64,\n\n ) {\n\n self.prime_with(\n\n habitat.map_indexed_location_to_u64_injective(indexed_location),\n\n time_index,\n\n );\n\n }\n\n}\n\n\n\nimpl<R: PrimeableRng, H: Habitat> HabitatPrimeableRng<H> for R {}\n\n\n", "file_path": "necsim/core/src/cogs/rng.rs", "rank": 12, "score": 261917.10245127167 }, { "content": "#[allow(clippy::module_name_repetitions)]\n\npub trait LineageReference<H: Habitat>:\n\n crate::cogs::Backup + PartialEq + Eq + Hash + Clone + core::fmt::Debug\n\n{\n\n}\n", "file_path": "necsim/core/src/cogs/lineage_reference.rs", "rank": 13, "score": 253566.9201438749 }, { "content": "/// A convenience function for reading data from a reader\n\n/// and feeding into a deserializer.\n\npub fn from_reader<R, T>(mut rdr: R) -> Result<T>\n\nwhere\n\n R: io::Read,\n\n T: de::DeserializeOwned,\n\n{\n\n let mut bytes = Vec::new();\n\n rdr.read_to_end(&mut bytes)?;\n\n\n\n from_bytes(&bytes)\n\n}\n\n\n", "file_path": "third-party/ron/src/de/mod.rs", "rank": 14, "score": 213042.3534687739 }, { "content": "#[allow(unreachable_code)]\n\n#[allow(unused_variables)]\n\n#[allow(clippy::needless_pass_by_value)]\n\npub fn simulate<R: ReporterContext, P: LocalPartition<R>>(\n\n common_args: CommonArgs,\n\n non_spatial_args: NonSpatialArgs,\n\n local_partition: &mut P,\n\n) -> Result<(f64, u64)> {\n\n info!(\n\n \"Setting up the non-spatial {} coalescence algorithm ...\",\n\n common_args.algorithm\n\n );\n\n\n\n #[allow(clippy::match_single_binding)]\n\n #[allow(clippy::map_err_ignore)]\n\n let result: Result<(f64, u64)> = match common_args.algorithm {\n\n #[cfg(feature = \"necsim-classical\")]\n\n Algorithm::Classical => ClassicalSimulation::simulate(\n\n non_spatial_args.area,\n\n non_spatial_args.deme,\n\n common_args.speciation_probability_per_generation.get(),\n\n common_args.sample_percentage.get(),\n\n common_args.seed,\n", "file_path": "rustcoalescence/src/simulation/non_spatial.rs", "rank": 15, "score": 209904.86862020678 }, { "content": "#[allow(clippy::too_many_lines, clippy::boxed_local)]\n\npub fn simulate_with_logger<R: Reporter, P: LocalPartition<R>>(\n\n mut local_partition: Box<P>,\n\n common_args: CommonArgs,\n\n scenario: ScenarioArgs,\n\n) -> Result<()> {\n\n if local_partition.get_number_of_partitions().get() <= 1 {\n\n info!(\"The simulation will be run in monolithic mode.\");\n\n } else {\n\n info!(\n\n \"The simulation will be distributed across {} partitions.\",\n\n local_partition.get_number_of_partitions().get()\n\n );\n\n }\n\n\n\n let pre_sampler = OriginPreSampler::all().percentage(common_args.sample_percentage.get());\n\n\n\n let (time, steps): (NonNegativeF64, u64) = crate::match_scenario_algorithm!(\n\n (common_args.algorithm, scenario => scenario)\n\n {\n\n #[cfg(feature = \"rustcoalescence-algorithms-monolithic\")]\n", "file_path": "rustcoalescence/src/cli/simulate/dispatch.rs", "rank": 16, "score": 209904.86862020678 }, { "content": "#[allow(unreachable_code)]\n\n#[allow(unused_variables)]\n\n#[allow(clippy::needless_pass_by_value)]\n\npub fn simulate<R: ReporterContext, P: LocalPartition<R>>(\n\n common_args: CommonArgs,\n\n spatially_implicit_args: SpatiallyImplicitArgs,\n\n local_partition: &mut P,\n\n) -> Result<(f64, u64)> {\n\n info!(\n\n \"Setting up the spatially-implicit {} coalescence algorithm ...\",\n\n common_args.algorithm\n\n );\n\n\n\n #[allow(clippy::match_single_binding)]\n\n #[allow(clippy::map_err_ignore)]\n\n let result: Result<(f64, u64)> = match common_args.algorithm {\n\n #[cfg(feature = \"necsim-classical\")]\n\n Algorithm::Classical => ClassicalSimulation::simulate(\n\n spatially_implicit_args.dynamic_meta,\n\n (\n\n spatially_implicit_args.local_area,\n\n spatially_implicit_args.local_deme,\n\n ),\n", "file_path": "rustcoalescence/src/simulation/spatially_implicit.rs", "rank": 17, "score": 209904.86862020678 }, { "content": "#[allow(clippy::module_name_repetitions)]\n\npub fn simulate_with_logger<R: Reporter, P: LocalPartition<R>>(\n\n local_partition: Box<P>,\n\n common_args: CommonArgs,\n\n scenario: ScenarioArgs,\n\n) -> Result<()> {\n\n #[cfg(any(\n\n feature = \"rustcoalescence-algorithms-monolithic\",\n\n feature = \"rustcoalescence-algorithms-independent\",\n\n feature = \"rustcoalescence-algorithms-cuda\"\n\n ))]\n\n {\n\n dispatch::simulate_with_logger(local_partition, common_args, scenario)\n\n }\n\n\n\n #[cfg(not(any(\n\n feature = \"rustcoalescence-algorithms-monolithic\",\n\n feature = \"rustcoalescence-algorithms-independent\",\n\n feature = \"rustcoalescence-algorithms-cuda\"\n\n )))]\n\n {\n\n std::mem::drop(local_partition);\n\n std::mem::drop(common_args);\n\n std::mem::drop(scenario);\n\n\n\n Err(anyhow::anyhow!(\n\n \"rustcoalescence must be compiled to support at least one algorithm.\"\n\n ))\n\n }\n\n}\n", "file_path": "rustcoalescence/src/cli/simulate/mod.rs", "rank": 18, "score": 209904.86862020678 }, { "content": "#[allow(unreachable_code)]\n\n#[allow(unused_variables)]\n\n#[allow(clippy::needless_pass_by_value)]\n\npub fn simulate<R: ReporterContext, P: LocalPartition<R>>(\n\n common_args: CommonArgs,\n\n almost_infinite_args: AlmostInfiniteArgs,\n\n local_partition: &mut P,\n\n) -> Result<(f64, u64)> {\n\n info!(\n\n \"Setting up the almost-infinite {} coalescence algorithm ...\",\n\n common_args.algorithm\n\n );\n\n\n\n #[allow(clippy::match_single_binding)]\n\n #[allow(clippy::map_err_ignore)]\n\n let result: Result<(f64, u64)> = match common_args.algorithm {\n\n #[cfg(feature = \"necsim-classical\")]\n\n Algorithm::Classical => ClassicalSimulation::simulate(\n\n almost_infinite_args.radius,\n\n almost_infinite_args.sigma.get(),\n\n common_args.speciation_probability_per_generation.get(),\n\n common_args.sample_percentage.get(),\n\n common_args.seed,\n", "file_path": "rustcoalescence/src/simulation/almost_infinite.rs", "rank": 19, "score": 209904.86862020678 }, { "content": "#[allow(unreachable_code)]\n\n#[allow(unused_variables)]\n\n#[allow(clippy::needless_pass_by_value)]\n\npub fn simulate<R: ReporterContext, P: LocalPartition<R>>(\n\n common_args: CommonArgs,\n\n in_memory_args: InMemoryArgs,\n\n local_partition: &mut P,\n\n) -> Result<(f64, u64)> {\n\n info!(\n\n \"Setting up the in-memory {} coalescence algorithm ...\",\n\n common_args.algorithm\n\n );\n\n\n\n #[allow(clippy::match_single_binding)]\n\n let result: Result<(f64, u64)> = match common_args.algorithm {\n\n #[cfg(feature = \"necsim-classical\")]\n\n Algorithm::Classical => ClassicalSimulation::simulate(\n\n &in_memory_args.habitat_map,\n\n &in_memory_args.dispersal_map,\n\n common_args.speciation_probability_per_generation.get(),\n\n common_args.sample_percentage.get(),\n\n common_args.seed,\n\n local_partition,\n", "file_path": "rustcoalescence/src/simulation/spatially_explicit.rs", "rank": 20, "score": 209904.86862020678 }, { "content": "// Fix habitat rounding error by correcting 0/1 values to 0/1 based on dispersal\n\n// (can only disperse from habitat)\n\nfn fix_habitat_map(habitat: &mut Array2D<u32>, dispersal: &Array2D<f64>) {\n\n for y in 0..habitat.num_rows() {\n\n for x in 0..habitat.num_columns() {\n\n let h_before = habitat[(y, x)];\n\n\n\n if h_before <= 1 {\n\n // If there is any dispersal from this location, it must be habitat\n\n let h_fixed = if dispersal\n\n .row_iter(y * habitat.num_columns() + x)\n\n .map_or(false, |mut it| it.any(|p| *p > 0.0_f64))\n\n {\n\n 1\n\n } else {\n\n 0\n\n };\n\n\n\n if h_fixed != h_before {\n\n habitat[(y, x)] = h_fixed;\n\n\n\n // warn!(\n\n // \"Corrected habitat value {} to {} at ({},{}) to fit \\\n\n // dispersal ...\", h_before, h_fixed, x, y\n\n // );\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "rustcoalescence/src/maps.rs", "rank": 21, "score": 205951.83515204056 }, { "content": "#[allow(clippy::module_name_repetitions)]\n\n#[allow(clippy::inline_always, clippy::inline_fn_without_body)]\n\n#[contract_trait]\n\npub trait EmigrationChoice<H: Habitat>: Backup + core::fmt::Debug {\n\n fn should_lineage_emigrate(\n\n &self,\n\n indexed_location: &IndexedLocation,\n\n time: PositiveF64,\n\n habitat: &H,\n\n ) -> bool;\n\n}\n", "file_path": "necsim/impls/no-std/src/cogs/emigration_exit/independent/choice/mod.rs", "rank": 22, "score": 202637.69185298905 }, { "content": "#[must_use]\n\npub fn sample_interaction_at_location<\n\n H: Habitat,\n\n R: LineageReference<H>,\n\n S: LocallyCoherentLineageStore<H, R>,\n\n>(\n\n location: Location,\n\n habitat: &H,\n\n lineage_store: &S,\n\n coalescence_rng_sample: CoalescenceRngSample,\n\n) -> (IndexedLocation, LineageInteraction) {\n\n let chosen_coalescence_index =\n\n coalescence_rng_sample.sample_coalescence_index(habitat.get_habitat_at_location(&location));\n\n\n\n let indexed_location = IndexedLocation::new(location, chosen_coalescence_index);\n\n\n\n let optional_coalescence = lineage_store\n\n .get_active_global_lineage_reference_at_indexed_location(&indexed_location, habitat)\n\n .cloned();\n\n\n\n (indexed_location, optional_coalescence.into())\n\n}\n", "file_path": "necsim/impls/no-std/src/cogs/coalescence_sampler/optional_coalescence.rs", "rank": 23, "score": 201048.72122542438 }, { "content": "// Fix dispersal by removing dispersal to/from non-habitat\n\n// Fix dispersal by adding self-dispersal when no dispersal exists from habitat\n\nfn fix_dispersal_map(habitat: &Array2D<u32>, dispersal: &mut Array2D<f64>) {\n\n let size = habitat.num_rows() * habitat.num_columns();\n\n\n\n for y in 0..habitat.num_rows() {\n\n for x in 0..habitat.num_columns() {\n\n let row = y * habitat.num_columns() + x;\n\n\n\n if habitat[(y, x)] == 0 {\n\n let mut warn = false;\n\n\n\n // Fix dispersal from non-habitat\n\n for column in 0..size {\n\n let d = &mut dispersal[(row, column)];\n\n\n\n if *d > 0.0_f64 {\n\n warn = true;\n\n\n\n *d = 0.0_f64;\n\n }\n\n }\n", "file_path": "rustcoalescence/src/maps.rs", "rank": 24, "score": 193143.34978554246 }, { "content": "use std::cmp::Ordering;\n\n\n\nuse necsim_core_bond::{NonNegativeF64, PositiveF64};\n\n\n\n#[derive(PartialEq, Copy, Clone)]\n\npub struct EventTime(NonNegativeF64);\n\n\n\nimpl Eq for EventTime {}\n\n\n\nimpl PartialOrd for EventTime {\n\n fn partial_cmp(&self, other: &Self) -> Option<Ordering> {\n\n other.0.partial_cmp(&self.0)\n\n }\n\n}\n\n\n\nimpl Ord for EventTime {\n\n fn cmp(&self, other: &Self) -> Ordering {\n\n other.0.cmp(&self.0)\n\n }\n\n}\n", "file_path": "necsim/impls/std/src/cogs/active_lineage_sampler/gillespie/event_time.rs", "rank": 25, "score": 178671.6909816939 }, { "content": "\n\nimpl From<NonNegativeF64> for EventTime {\n\n fn from(event_time: NonNegativeF64) -> Self {\n\n Self(event_time)\n\n }\n\n}\n\n\n\nimpl From<PositiveF64> for EventTime {\n\n fn from(event_time: PositiveF64) -> Self {\n\n Self(event_time.into())\n\n }\n\n}\n\n\n\nimpl From<EventTime> for NonNegativeF64 {\n\n fn from(event_time: EventTime) -> Self {\n\n event_time.0\n\n }\n\n}\n", "file_path": "necsim/impls/std/src/cogs/active_lineage_sampler/gillespie/event_time.rs", "rank": 26, "score": 178668.75142520008 }, { "content": "#[allow(clippy::inline_always, clippy::inline_fn_without_body)]\n\n#[contract_trait]\n\npub trait SpeciationProbability<H: Habitat>: crate::cogs::Backup + core::fmt::Debug {\n\n #[must_use]\n\n #[debug_requires(habitat.contains(location), \"location is inside habitat\")]\n\n fn get_speciation_probability_at_location(\n\n &self,\n\n location: &Location,\n\n habitat: &H,\n\n ) -> ClosedUnitF64;\n\n}\n", "file_path": "necsim/core/src/cogs/speciation_probability.rs", "rank": 27, "score": 176673.36484188537 }, { "content": "#[allow(clippy::inline_always, clippy::inline_fn_without_body)]\n\n#[contract_trait]\n\npub trait TurnoverRate<H: Habitat>: crate::cogs::Backup + core::fmt::Debug {\n\n #[must_use]\n\n #[debug_requires(habitat.contains(location), \"location is inside habitat\")]\n\n #[debug_ensures(\n\n ret == 0.0_f64 -> habitat.get_habitat_at_location(location) == 0_u32,\n\n \"only returns zero if the location is inhabitable\"\n\n )]\n\n fn get_turnover_rate_at_location(&self, location: &Location, habitat: &H) -> NonNegativeF64;\n\n}\n", "file_path": "necsim/core/src/cogs/turnover_rate.rs", "rank": 28, "score": 176673.36484188537 }, { "content": " #[must_use]\n\n pub fn new(delta_t: PositiveF64) -> Self {\n\n Self { delta_t }\n\n }\n\n}\n\n\n\n#[contract_trait]\n\nimpl<H: Habitat, G: PrimeableRng, T: TurnoverRate<H>> EventTimeSampler<H, G, T>\n\n for PoissonEventTimeSampler\n\n{\n\n #[inline]\n\n fn next_event_time_at_indexed_location_weakly_after(\n\n &self,\n\n indexed_location: &IndexedLocation,\n\n time: NonNegativeF64,\n\n habitat: &H,\n\n rng: &mut G,\n\n turnover_rate: &T,\n\n ) -> NonNegativeF64 {\n\n let lambda =\n", "file_path": "necsim/impls/no-std/src/cogs/active_lineage_sampler/independent/event_time_sampler/poisson.rs", "rank": 29, "score": 171992.6787628965 }, { "content": " #[must_use]\n\n pub fn new(delta_t: PositiveF64) -> Self {\n\n Self { delta_t }\n\n }\n\n}\n\n\n\n#[contract_trait]\n\nimpl<H: Habitat, G: PrimeableRng, T: TurnoverRate<H>> EventTimeSampler<H, G, T>\n\n for ExpEventTimeSampler\n\n{\n\n #[inline]\n\n fn next_event_time_at_indexed_location_weakly_after(\n\n &self,\n\n indexed_location: &IndexedLocation,\n\n time: NonNegativeF64,\n\n habitat: &H,\n\n rng: &mut G,\n\n turnover_rate: &T,\n\n ) -> NonNegativeF64 {\n\n // Safety: The turnover rate is >= 0.0 and must actually be > 0.0 because\n", "file_path": "necsim/impls/no-std/src/cogs/active_lineage_sampler/independent/event_time_sampler/exp.rs", "rank": 30, "score": 171991.92662942852 }, { "content": "#[contract_trait]\n\nimpl<H: Habitat, G: PrimeableRng, T: TurnoverRate<H>> EventTimeSampler<H, G, T>\n\n for FixedEventTimeSampler\n\n{\n\n #[inline]\n\n fn next_event_time_at_indexed_location_weakly_after(\n\n &self,\n\n indexed_location: &IndexedLocation,\n\n time: NonNegativeF64,\n\n habitat: &H,\n\n rng: &mut G,\n\n turnover_rate: &T,\n\n ) -> NonNegativeF64 {\n\n let lambda =\n\n turnover_rate.get_turnover_rate_at_location(indexed_location.location(), habitat);\n\n\n\n #[allow(clippy::cast_possible_truncation)]\n\n #[allow(clippy::cast_sign_loss)]\n\n let time_step = floor(time.get() * lambda.get()) as u64 + 1;\n\n\n\n rng.prime_with_habitat(habitat, indexed_location, time_step);\n\n\n\n NonNegativeF64::from(time_step) / lambda\n\n }\n\n}\n", "file_path": "necsim/impls/no-std/src/cogs/active_lineage_sampler/independent/event_time_sampler/fixed.rs", "rank": 31, "score": 171989.10970439707 }, { "content": " }\n\n}\n\n\n\n#[contract_trait]\n\nimpl<H: Habitat, G: PrimeableRng, T: TurnoverRate<H>> EventTimeSampler<H, G, T>\n\n for GeometricEventTimeSampler\n\n{\n\n #[inline]\n\n fn next_event_time_at_indexed_location_weakly_after(\n\n &self,\n\n indexed_location: &IndexedLocation,\n\n time: NonNegativeF64,\n\n habitat: &H,\n\n rng: &mut G,\n\n turnover_rate: &T,\n\n ) -> NonNegativeF64 {\n\n let event_probability_per_step = neg_exp(\n\n turnover_rate.get_turnover_rate_at_location(indexed_location.location(), habitat)\n\n * self.delta_t,\n\n )\n", "file_path": "necsim/impls/no-std/src/cogs/active_lineage_sampler/independent/event_time_sampler/geometric.rs", "rank": 32, "score": 171988.23643078067 }, { "content": "use necsim_core::{\n\n cogs::{Habitat, HabitatPrimeableRng, PrimeableRng, TurnoverRate},\n\n intrinsics::floor,\n\n landscape::IndexedLocation,\n\n};\n\nuse necsim_core_bond::NonNegativeF64;\n\n\n\nuse super::EventTimeSampler;\n\n\n\n#[allow(clippy::module_name_repetitions)]\n\n#[derive(Clone, Debug)]\n\n#[cfg_attr(feature = \"cuda\", derive(rust_cuda::common::RustToCuda))]\n\npub struct FixedEventTimeSampler(());\n\n\n\nimpl Default for FixedEventTimeSampler {\n\n fn default() -> Self {\n\n Self(())\n\n }\n\n}\n\n\n", "file_path": "necsim/impls/no-std/src/cogs/active_lineage_sampler/independent/event_time_sampler/fixed.rs", "rank": 33, "score": 171980.15769612993 }, { "content": "use necsim_core::{\n\n cogs::{Habitat, HabitatPrimeableRng, PrimeableRng, RngSampler, TurnoverRate},\n\n intrinsics::{floor, neg_exp},\n\n landscape::IndexedLocation,\n\n};\n\nuse necsim_core_bond::{NonNegativeF64, PositiveF64};\n\n\n\nuse super::EventTimeSampler;\n\n\n\n#[allow(clippy::module_name_repetitions)]\n\n#[derive(Clone, Debug)]\n\n#[cfg_attr(feature = \"cuda\", derive(rust_cuda::common::RustToCuda))]\n\npub struct GeometricEventTimeSampler {\n\n delta_t: PositiveF64,\n\n}\n\n\n\nimpl GeometricEventTimeSampler {\n\n #[must_use]\n\n pub fn new(delta_t: PositiveF64) -> Self {\n\n Self { delta_t }\n", "file_path": "necsim/impls/no-std/src/cogs/active_lineage_sampler/independent/event_time_sampler/geometric.rs", "rank": 34, "score": 171978.9829460151 }, { "content": " turnover_rate.get_turnover_rate_at_location(indexed_location.location(), habitat);\n\n let lambda_per_step = lambda * self.delta_t;\n\n let no_event_probability_per_step = exp(-lambda_per_step.get());\n\n\n\n #[allow(clippy::cast_possible_truncation)]\n\n #[allow(clippy::cast_sign_loss)]\n\n let mut time_step = floor(time.get() / self.delta_t.get()) as u64;\n\n\n\n let (event_time, event_index) = loop {\n\n rng.prime_with_habitat(habitat, indexed_location, time_step);\n\n\n\n let number_events_at_time_steps = if no_event_probability_per_step > 0.0_f64 {\n\n // https://en.wikipedia.org/wiki/Poisson_distribution#cite_ref-Devroye1986_54-0\n\n let mut poisson = 0_u32;\n\n let mut prod = no_event_probability_per_step;\n\n let mut acc = no_event_probability_per_step;\n\n\n\n let u = rng.sample_uniform();\n\n\n\n while u > acc && prod > 0.0_f64 {\n", "file_path": "necsim/impls/no-std/src/cogs/active_lineage_sampler/independent/event_time_sampler/poisson.rs", "rank": 35, "score": 171974.5446691191 }, { "content": " // * `indexed_location` is habitable by this method's precondition\n\n // * Therefore, `turnover_rate` must return a positive value by its\n\n // postcondition\n\n let lambda = unsafe {\n\n PositiveF64::new_unchecked(\n\n turnover_rate\n\n .get_turnover_rate_at_location(indexed_location.location(), habitat)\n\n .get(),\n\n )\n\n };\n\n\n\n #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]\n\n let mut time_step = floor(time.get() / self.delta_t.get()) as u64;\n\n\n\n let mut event_time = NonNegativeF64::from(time_step) * self.delta_t;\n\n let mut time_slice_end = NonNegativeF64::from(time_step + 1) * self.delta_t;\n\n\n\n #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]\n\n rng.prime_with_habitat(habitat, indexed_location, time_step);\n\n\n", "file_path": "necsim/impls/no-std/src/cogs/active_lineage_sampler/independent/event_time_sampler/exp.rs", "rank": 36, "score": 171974.5145375488 }, { "content": "use necsim_core::{\n\n cogs::{Habitat, HabitatPrimeableRng, PrimeableRng, RngSampler, TurnoverRate},\n\n intrinsics::floor,\n\n landscape::IndexedLocation,\n\n};\n\nuse necsim_core_bond::{NonNegativeF64, PositiveF64};\n\n\n\nuse super::EventTimeSampler;\n\n\n\n// 2^64 / PHI\n\nconst INV_PHI: u64 = 0x9e37_79b9_7f4a_7c15_u64;\n\n\n\n#[allow(clippy::module_name_repetitions)]\n\n#[derive(Clone, Debug)]\n\n#[cfg_attr(feature = \"cuda\", derive(rust_cuda::common::RustToCuda))]\n\npub struct ExpEventTimeSampler {\n\n delta_t: PositiveF64,\n\n}\n\n\n\nimpl ExpEventTimeSampler {\n", "file_path": "necsim/impls/no-std/src/cogs/active_lineage_sampler/independent/event_time_sampler/exp.rs", "rank": 37, "score": 171974.15511652103 }, { "content": "use necsim_core::{\n\n cogs::{Habitat, HabitatPrimeableRng, PrimeableRng, RngSampler, TurnoverRate},\n\n intrinsics::{exp, floor, safe_sqrt},\n\n landscape::IndexedLocation,\n\n};\n\nuse necsim_core_bond::{NonNegativeF64, PositiveF64};\n\n\n\nuse super::EventTimeSampler;\n\n\n\n// 2^64 / PHI\n\nconst INV_PHI: u64 = 0x9e37_79b9_7f4a_7c15_u64;\n\n\n\n#[allow(clippy::module_name_repetitions)]\n\n#[derive(Clone, Debug)]\n\n#[cfg_attr(feature = \"cuda\", derive(rust_cuda::common::RustToCuda))]\n\npub struct PoissonEventTimeSampler {\n\n delta_t: PositiveF64,\n\n}\n\n\n\nimpl PoissonEventTimeSampler {\n", "file_path": "necsim/impls/no-std/src/cogs/active_lineage_sampler/independent/event_time_sampler/poisson.rs", "rank": 38, "score": 171973.78607937047 }, { "content": " .one_minus();\n\n\n\n #[allow(clippy::cast_possible_truncation)]\n\n #[allow(clippy::cast_sign_loss)]\n\n let mut time_step = floor(time.get() / self.delta_t.get()) as u64 + 1;\n\n\n\n loop {\n\n rng.prime_with_habitat(habitat, indexed_location, time_step);\n\n\n\n if rng.sample_event(event_probability_per_step) {\n\n break;\n\n }\n\n\n\n time_step += 1;\n\n }\n\n\n\n NonNegativeF64::from(time_step) * self.delta_t\n\n }\n\n}\n", "file_path": "necsim/impls/no-std/src/cogs/active_lineage_sampler/independent/event_time_sampler/geometric.rs", "rank": 39, "score": 171973.1069980605 }, { "content": " let mut sub_index: u64 = 0;\n\n\n\n loop {\n\n event_time += rng.sample_exponential(lambda);\n\n\n\n sub_index = sub_index.wrapping_add(INV_PHI);\n\n\n\n // The time slice is exclusive at time_slice_end\n\n if event_time >= time_slice_end {\n\n time_step += 1;\n\n sub_index = 0;\n\n\n\n event_time = time_slice_end;\n\n time_slice_end = NonNegativeF64::from(time_step + 1) * self.delta_t;\n\n\n\n rng.prime_with_habitat(habitat, indexed_location, time_step);\n\n } else if event_time > time {\n\n break;\n\n }\n\n }\n\n\n\n rng.prime_with_habitat(habitat, indexed_location, time_step.wrapping_add(sub_index));\n\n\n\n event_time\n\n }\n\n}\n", "file_path": "necsim/impls/no-std/src/cogs/active_lineage_sampler/independent/event_time_sampler/exp.rs", "rank": 40, "score": 171968.98219797882 }, { "content": "use necsim_core::{\n\n cogs::{Habitat, PrimeableRng, TurnoverRate},\n\n landscape::IndexedLocation,\n\n};\n\nuse necsim_core_bond::NonNegativeF64;\n\n\n\npub mod exp;\n\npub mod fixed;\n\npub mod geometric;\n\npub mod poisson;\n\n\n\n#[allow(clippy::module_name_repetitions)]\n\n#[allow(clippy::inline_always, clippy::inline_fn_without_body)]\n\n#[contract_trait]\n", "file_path": "necsim/impls/no-std/src/cogs/active_lineage_sampler/independent/event_time_sampler/mod.rs", "rank": 41, "score": 171968.24069019523 }, { "content": "\n\n rng.prime_with_habitat(\n\n habitat,\n\n indexed_location,\n\n time_step + INV_PHI.wrapping_mul(u64::from(event_index + 1)),\n\n );\n\n\n\n event_time\n\n }\n\n}\n", "file_path": "necsim/impls/no-std/src/cogs/active_lineage_sampler/independent/event_time_sampler/poisson.rs", "rank": 42, "score": 171964.65191694637 }, { "content": " poisson += 1;\n\n prod *= lambda_per_step.get() / f64::from(poisson);\n\n acc += prod;\n\n }\n\n\n\n poisson\n\n } else {\n\n // Fallback in case no_event_probability_per_step underflows\n\n #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]\n\n let normal_as_poisson = rng\n\n .sample_2d_normal(lambda_per_step.get(), safe_sqrt(lambda_per_step))\n\n .0\n\n .max(0.0_f64) as u32;\n\n\n\n normal_as_poisson\n\n };\n\n\n\n let mut next_event = None;\n\n\n\n for event_index in 0..number_events_at_time_steps {\n", "file_path": "necsim/impls/no-std/src/cogs/active_lineage_sampler/independent/event_time_sampler/poisson.rs", "rank": 43, "score": 171958.86762339668 }, { "content": " #[allow(clippy::cast_precision_loss)]\n\n let event_time =\n\n (NonNegativeF64::from(time_step) + rng.sample_uniform()) * self.delta_t;\n\n\n\n if event_time > time {\n\n next_event = match next_event {\n\n Some((later_event_time, _)) if later_event_time > event_time => {\n\n Some((event_time, event_index))\n\n },\n\n Some(next_event) => Some(next_event),\n\n None => Some((event_time, event_index)),\n\n };\n\n }\n\n }\n\n\n\n match next_event {\n\n Some(next_event) => break next_event,\n\n None => time_step += 1,\n\n }\n\n };\n", "file_path": "necsim/impls/no-std/src/cogs/active_lineage_sampler/independent/event_time_sampler/poisson.rs", "rank": 44, "score": 171953.0116464282 }, { "content": "#[allow(clippy::inline_always, clippy::inline_fn_without_body)]\n\n#[contract_trait]\n\npub trait Decomposition<H: Habitat>: Backup + Sized + core::fmt::Debug {\n\n #[debug_ensures(\n\n ret < self.get_number_of_subdomains().get(),\n\n \"subdomain rank is in range [0, self.get_number_of_subdomains())\"\n\n )]\n\n fn get_subdomain_rank(&self) -> u32;\n\n\n\n fn get_number_of_subdomains(&self) -> NonZeroU32;\n\n\n\n #[debug_requires(\n\n habitat.contains(location),\n\n \"location is contained inside habitat\"\n\n )]\n\n #[debug_ensures(\n\n ret < self.get_number_of_subdomains().get(),\n\n \"subdomain rank is in range [0, self.get_number_of_subdomains())\"\n\n )]\n\n fn map_location_to_subdomain_rank(&self, location: &Location, habitat: &H) -> u32;\n\n}\n", "file_path": "necsim/impls/no-std/src/decomposition/mod.rs", "rank": 45, "score": 170211.02006680713 }, { "content": "#[allow(clippy::type_complexity)]\n\npub fn simulate<\n\n H: Habitat,\n\n G: RngCore,\n\n R: LineageReference<H>,\n\n S: LocallyCoherentLineageStore<H, R>,\n\n D: DispersalSampler<H, G>,\n\n C: CoalescenceSampler<H, R, S>,\n\n T: TurnoverRate<H>,\n\n N: SpeciationProbability<H>,\n\n O: Decomposition<H>,\n\n E: EventSampler<H, G, R, S, DomainEmigrationExit<H, O>, D, C, T, N>,\n\n A: PeekableActiveLineageSampler<\n\n H,\n\n G,\n\n R,\n\n S,\n\n DomainEmigrationExit<H, O>,\n\n D,\n\n C,\n\n T,\n", "file_path": "necsim/impls/no-std/src/parallelisation/monolithic/lockstep.rs", "rank": 46, "score": 168656.1177188762 }, { "content": "#[allow(clippy::type_complexity)]\n\npub fn simulate<\n\n H: Habitat,\n\n G: RngCore,\n\n R: LineageReference<H>,\n\n S: LocallyCoherentLineageStore<H, R>,\n\n D: DispersalSampler<H, G>,\n\n C: CoalescenceSampler<H, R, S>,\n\n T: TurnoverRate<H>,\n\n N: SpeciationProbability<H>,\n\n O: Decomposition<H>,\n\n E: EventSampler<H, G, R, S, DomainEmigrationExit<H, O>, D, C, T, N>,\n\n A: PeekableActiveLineageSampler<\n\n H,\n\n G,\n\n R,\n\n S,\n\n DomainEmigrationExit<H, O>,\n\n D,\n\n C,\n\n T,\n", "file_path": "necsim/impls/no-std/src/parallelisation/monolithic/averaging.rs", "rank": 47, "score": 168656.1177188762 }, { "content": "#[allow(clippy::type_complexity)]\n\npub fn simulate<\n\n H: Habitat,\n\n G: RngCore,\n\n R: LineageReference<H>,\n\n S: LocallyCoherentLineageStore<H, R>,\n\n D: DispersalSampler<H, G>,\n\n C: CoalescenceSampler<H, R, S>,\n\n T: TurnoverRate<H>,\n\n N: SpeciationProbability<H>,\n\n O: Decomposition<H>,\n\n E: EventSampler<H, G, R, S, DomainEmigrationExit<H, O>, D, C, T, N>,\n\n A: PeekableActiveLineageSampler<\n\n H,\n\n G,\n\n R,\n\n S,\n\n DomainEmigrationExit<H, O>,\n\n D,\n\n C,\n\n T,\n", "file_path": "necsim/impls/no-std/src/parallelisation/monolithic/optimistic.rs", "rank": 48, "score": 168656.1177188762 }, { "content": "#[allow(clippy::type_complexity)]\n\npub fn simulate<\n\n H: Habitat,\n\n C: Decomposition<H>,\n\n E: EmigrationChoice<H>,\n\n G: PrimeableRng,\n\n D: DispersalSampler<H, G>,\n\n T: TurnoverRate<H>,\n\n N: SpeciationProbability<H>,\n\n J: EventTimeSampler<H, G, T>,\n\n R: Reporter,\n\n P: LocalPartition<R>,\n\n>(\n\n mut simulation: Simulation<\n\n H,\n\n G,\n\n GlobalLineageReference,\n\n IndependentLineageStore<H>,\n\n IndependentEmigrationExit<H, C, E>,\n\n D,\n\n IndependentCoalescenceSampler<H>,\n", "file_path": "necsim/impls/no-std/src/parallelisation/independent/landscape.rs", "rank": 49, "score": 168656.1177188762 }, { "content": "#[allow(clippy::type_complexity)]\n\npub fn simulate<\n\n H: Habitat,\n\n G: RngCore,\n\n R: LineageReference<H>,\n\n S: LocallyCoherentLineageStore<H, R>,\n\n D: DispersalSampler<H, G>,\n\n C: CoalescenceSampler<H, R, S>,\n\n T: TurnoverRate<H>,\n\n N: SpeciationProbability<H>,\n\n E: EventSampler<H, G, R, S, NeverEmigrationExit, D, C, T, N>,\n\n A: ActiveLineageSampler<H, G, R, S, NeverEmigrationExit, D, C, T, N, E, NeverImmigrationEntry>,\n\n P: Reporter,\n\n L: LocalPartition<P>,\n\n>(\n\n simulation: Simulation<\n\n H,\n\n G,\n\n R,\n\n S,\n\n NeverEmigrationExit,\n", "file_path": "necsim/impls/no-std/src/parallelisation/monolithic/monolithic.rs", "rank": 50, "score": 168656.1177188762 }, { "content": "#[allow(clippy::type_complexity)]\n\npub fn simulate<\n\n H: Habitat,\n\n G: PrimeableRng,\n\n D: DispersalSampler<H, G>,\n\n T: TurnoverRate<H>,\n\n N: SpeciationProbability<H>,\n\n J: EventTimeSampler<H, G, T>,\n\n R: Reporter,\n\n P: LocalPartition<R>,\n\n>(\n\n mut simulation: Simulation<\n\n H,\n\n G,\n\n GlobalLineageReference,\n\n IndependentLineageStore<H>,\n\n NeverEmigrationExit,\n\n D,\n\n IndependentCoalescenceSampler<H>,\n\n T,\n\n N,\n", "file_path": "necsim/impls/no-std/src/parallelisation/independent/individuals.rs", "rank": 51, "score": 168656.1177188762 }, { "content": "#[allow(clippy::type_complexity)]\n\npub fn simulate<\n\n H: Habitat,\n\n G: RngCore,\n\n R: LineageReference<H>,\n\n S: LocallyCoherentLineageStore<H, R>,\n\n D: DispersalSampler<H, G>,\n\n C: CoalescenceSampler<H, R, S>,\n\n T: TurnoverRate<H>,\n\n N: SpeciationProbability<H>,\n\n O: Decomposition<H>,\n\n E: EventSampler<H, G, R, S, DomainEmigrationExit<H, O>, D, C, T, N>,\n\n A: PeekableActiveLineageSampler<\n\n H,\n\n G,\n\n R,\n\n S,\n\n DomainEmigrationExit<H, O>,\n\n D,\n\n C,\n\n T,\n", "file_path": "necsim/impls/no-std/src/parallelisation/monolithic/optimistic_lockstep.rs", "rank": 52, "score": 165887.07077579093 }, { "content": "#[allow(clippy::type_complexity, clippy::too_many_lines)]\n\npub fn simulate<\n\n H: Habitat,\n\n G: PrimeableRng,\n\n D: DispersalSampler<H, G>,\n\n T: TurnoverRate<H>,\n\n N: SpeciationProbability<H>,\n\n J: EventTimeSampler<H, G, T>,\n\n R: Reporter,\n\n P: LocalPartition<R>,\n\n>(\n\n mut simulation: Simulation<\n\n H,\n\n G,\n\n GlobalLineageReference,\n\n IndependentLineageStore<H>,\n\n NeverEmigrationExit,\n\n D,\n\n IndependentCoalescenceSampler<H>,\n\n T,\n\n N,\n", "file_path": "necsim/impls/no-std/src/parallelisation/independent/monolithic/mod.rs", "rank": 53, "score": 165887.07077579093 }, { "content": "#[test]\n\nfn test_get_mut() -> Result<(), Error> {\n\n let rows = vec![vec![1, 2, 3], vec![4, 5, 6]];\n\n let mut array = Array2D::from_rows(&rows)?;\n\n let (set_row, set_column) = (0, 2);\n\n let element = 53;\n\n let element_ref_option = array.get_mut(set_row, set_column);\n\n assert!(element_ref_option.is_some());\n\n let element_ref = element_ref_option.unwrap();\n\n assert_eq!(element_ref, &rows[set_row][set_column]);\n\n *element_ref = element;\n\n assert_eq!(element_ref, &element);\n\n for row in 0..rows.len() {\n\n for column in 0..rows[0].len() {\n\n let actual = array.get(row, column);\n\n if (row, column) == (set_row, set_column) {\n\n assert_eq!(actual, Some(&element));\n\n } else {\n\n assert_eq!(actual, Some(&rows[row][column]));\n\n }\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "third-party/array2d-no-std/tests/array2d.rs", "rank": 54, "score": 162551.27292061478 }, { "content": "#[test]\n\nfn test_get_mut_column_major() -> Result<(), Error> {\n\n let rows = vec![vec![1, 2, 3], vec![4, 5, 6]];\n\n let mut array = Array2D::from_rows(&rows)?;\n\n assert_eq!(array.get_mut_column_major(0), Some(&mut 1));\n\n assert_eq!(array.get_mut_column_major(1), Some(&mut 4));\n\n assert_eq!(array.get_mut_column_major(2), Some(&mut 2));\n\n assert_eq!(array.get_mut_column_major(3), Some(&mut 5));\n\n assert_eq!(array.get_mut_column_major(4), Some(&mut 3));\n\n assert_eq!(array.get_mut_column_major(5), Some(&mut 6));\n\n assert_eq!(array.get_mut_column_major(6), None);\n\n Ok(())\n\n}\n\n\n", "file_path": "third-party/array2d-no-std/tests/array2d.rs", "rank": 55, "score": 157469.97816723847 }, { "content": "#[test]\n\nfn test_get_mut_row_major() -> Result<(), Error> {\n\n let rows = vec![vec![1, 2, 3], vec![4, 5, 6]];\n\n let mut array = Array2D::from_rows(&rows)?;\n\n assert_eq!(array.get_mut_row_major(0), Some(&mut 1));\n\n assert_eq!(array.get_mut_row_major(1), Some(&mut 2));\n\n assert_eq!(array.get_mut_row_major(2), Some(&mut 3));\n\n assert_eq!(array.get_mut_row_major(3), Some(&mut 4));\n\n assert_eq!(array.get_mut_row_major(4), Some(&mut 5));\n\n assert_eq!(array.get_mut_row_major(5), Some(&mut 6));\n\n assert_eq!(array.get_mut_row_major(6), None);\n\n Ok(())\n\n}\n\n\n", "file_path": "third-party/array2d-no-std/tests/array2d.rs", "rank": 56, "score": 157469.97816723847 }, { "content": "\n\nimpl<R: RngCore> RngCore for CudaRng<R> {\n\n type Seed = <R as RngCore>::Seed;\n\n\n\n #[must_use]\n\n #[inline]\n\n fn from_seed(seed: Self::Seed) -> Self {\n\n Self(R::from_seed(seed))\n\n }\n\n\n\n #[must_use]\n\n #[inline]\n\n fn sample_u64(&mut self) -> u64 {\n\n self.0.sample_u64()\n\n }\n\n}\n\n\n\nimpl<R: PrimeableRng> PrimeableRng for CudaRng<R> {\n\n #[inline]\n\n fn prime_with(&mut self, location_index: u64, time_index: u64) {\n\n self.0.prime_with(location_index, time_index);\n\n }\n\n}\n", "file_path": "necsim/impls/cuda/src/cogs/rng.rs", "rank": 57, "score": 148057.40441539654 }, { "content": "use necsim_core::cogs::{Backup, PrimeableRng, RngCore};\n\n\n\n#[allow(clippy::module_name_repetitions)]\n\n#[derive(Clone, Debug, rust_cuda::common::RustToCuda, rust_cuda::host::LendToCuda)]\n\npub struct CudaRng<R: RngCore>(R);\n\n\n\nimpl<R: RngCore> From<R> for CudaRng<R> {\n\n #[must_use]\n\n #[inline]\n\n fn from(rng: R) -> Self {\n\n Self(rng)\n\n }\n\n}\n\n\n\n#[contract_trait]\n\nimpl<R: RngCore> Backup for CudaRng<R> {\n\n unsafe fn backup_unchecked(&self) -> Self {\n\n self.clone()\n\n }\n\n}\n", "file_path": "necsim/impls/cuda/src/cogs/rng.rs", "rank": 58, "score": 148045.911438923 }, { "content": "pub fn swap_field_type_and_get_cuda_repr_ty(field: &mut syn::Field) -> Option<CudaReprFieldTy> {\n\n let mut cuda_repr_field_ty: Option<CudaReprFieldTy> = None;\n\n let mut field_ty = field.ty.clone();\n\n\n\n // Helper attribute `r2c` must be filtered out inside cuda representation\n\n field.attrs.retain(|attr| match attr.path.get_ident() {\n\n Some(ident) if cuda_repr_field_ty.is_none() && format!(\"{}\", ident) == \"r2cEmbed\" => {\n\n // Allow the shorthand `#[r2cEmbed]` which uses the field type\n\n // as well as the explicit `#[r2cEmbed(ty)]` which overwrites the type\n\n let attribute_str = if attr.tokens.is_empty() {\n\n format!(\"({})\", quote! { #field_ty })\n\n } else {\n\n format!(\"{}\", attr.tokens)\n\n };\n\n\n\n if let Some(slice_type) = attribute_str\n\n .strip_prefix(\"(Box < [\")\n\n .and_then(|rest| rest.strip_suffix(\"] >)\"))\n\n {\n\n // Check for the special case of a boxed slice: `Box<ty>`\n", "file_path": "rust-cuda/rust-cuda-derive/src/rust_to_cuda/field_ty.rs", "rank": 59, "score": 146884.56420488542 }, { "content": " + u64::from(indexed_location.index())\n\n }\n\n}\n\n\n\nimpl InMemoryHabitat {\n\n #[must_use]\n\n #[debug_ensures(\n\n old(habitat.num_columns()) == ret.get_extent().width() as usize &&\n\n old(habitat.num_rows()) == ret.get_extent().height() as usize,\n\n \"habitat extent has the dimension of the habitat array\"\n\n )]\n\n pub fn new(habitat: Array2D<u32>) -> Self {\n\n #[allow(clippy::cast_possible_truncation)]\n\n let width: u32 = habitat.num_columns() as u32;\n\n #[allow(clippy::cast_possible_truncation)]\n\n let height: u32 = habitat.num_rows() as u32;\n\n\n\n let habitat = habitat.into_row_major().into_boxed_slice();\n\n\n\n let mut index_acc = 0_u64;\n", "file_path": "necsim/impls/no-std/src/cogs/habitat/in_memory.rs", "rank": 60, "score": 144932.2197225219 }, { "content": " self.habitat.iter().map(|x| u64::from(*x)).sum()\n\n }\n\n\n\n #[must_use]\n\n fn get_habitat_at_location(&self, location: &Location) -> u32 {\n\n self.habitat\n\n .get((location.y() as usize) * (self.extent.width() as usize) + (location.x() as usize))\n\n .copied()\n\n .unwrap_or(0)\n\n }\n\n\n\n #[must_use]\n\n fn map_indexed_location_to_u64_injective(&self, indexed_location: &IndexedLocation) -> u64 {\n\n self.u64_injection\n\n .get(\n\n (indexed_location.location().y() as usize) * (self.extent.width() as usize)\n\n + (indexed_location.location().x() as usize),\n\n )\n\n .copied()\n\n .unwrap_or(0)\n", "file_path": "necsim/impls/no-std/src/cogs/habitat/in_memory.rs", "rank": 61, "score": 144928.87886186413 }, { "content": "#[contract_trait]\n\nimpl Backup for InMemoryHabitat {\n\n unsafe fn backup_unchecked(&self) -> Self {\n\n Self {\n\n habitat: self.habitat.clone(),\n\n u64_injection: self.u64_injection.clone(),\n\n extent: self.extent.clone(),\n\n }\n\n }\n\n}\n\n\n\n#[contract_trait]\n\nimpl Habitat for InMemoryHabitat {\n\n #[must_use]\n\n fn get_extent(&self) -> &LandscapeExtent {\n\n &self.extent\n\n }\n\n\n\n #[must_use]\n\n fn get_total_habitat(&self) -> u64 {\n", "file_path": "necsim/impls/no-std/src/cogs/habitat/in_memory.rs", "rank": 62, "score": 144926.66516167158 }, { "content": "use array2d::Array2D;\n\n\n\nuse alloc::{boxed::Box, vec::Vec};\n\n\n\nuse necsim_core::{\n\n cogs::{Backup, Habitat},\n\n landscape::{IndexedLocation, LandscapeExtent, Location},\n\n};\n\n\n\n#[allow(clippy::module_name_repetitions)]\n\n#[cfg_attr(feature = \"cuda\", derive(rust_cuda::common::RustToCuda))]\n\n#[derive(Debug)]\n\npub struct InMemoryHabitat {\n\n #[cfg_attr(feature = \"cuda\", r2cEmbed)]\n\n habitat: Box<[u32]>,\n\n #[cfg_attr(feature = \"cuda\", r2cEmbed)]\n\n u64_injection: Box<[u64]>,\n\n extent: LandscapeExtent,\n\n}\n\n\n", "file_path": "necsim/impls/no-std/src/cogs/habitat/in_memory.rs", "rank": 63, "score": 144918.19985295972 }, { "content": "use std::fmt;\n\n\n\nuse pcg_rand::{seeds::PcgSeeder, Pcg64};\n\nuse rand::{RngCore as _, SeedableRng};\n\n\n\nuse necsim_core::cogs::{Backup, RngCore, SplittableRng};\n\n\n\n#[allow(clippy::module_name_repetitions)]\n\npub struct Pcg(Pcg64);\n\n\n\nimpl Clone for Pcg {\n\n fn clone(&self) -> Self {\n\n Self(Pcg64::restore_state_with_no_verification(\n\n self.0.get_state(),\n\n ))\n\n }\n\n}\n\n\n\nimpl fmt::Debug for Pcg {\n\n fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {\n", "file_path": "necsim/impls/std/src/cogs/rng/pcg.rs", "rank": 64, "score": 144916.0468425837 }, { "content": " #[inline]\n\n fn from_seed(seed: Self::Seed) -> Self {\n\n let seed = u64::from_le_bytes(seed);\n\n\n\n Self { seed, state: seed }\n\n }\n\n\n\n #[must_use]\n\n #[inline]\n\n fn sample_u64(&mut self) -> u64 {\n\n self.state = xxhash_rust::xxh64::xxh64(&self.state.to_le_bytes(), self.seed);\n\n self.state\n\n }\n\n}\n\n\n\nimpl PrimeableRng for XxHash {\n\n fn prime_with(&mut self, location_index: u64, time_index: u64) {\n\n let location_bytes = location_index.to_le_bytes();\n\n\n\n let time_index_bytes = time_index.to_le_bytes();\n", "file_path": "necsim/impls/no-std/src/cogs/rng/xxhash.rs", "rank": 65, "score": 144915.57421472372 }, { "content": "use rand::{rngs::StdRng as StdRngImpl, RngCore, SeedableRng};\n\n\n\n#[allow(clippy::module_name_repetitions)]\n\n#[derive(Clone, Debug)]\n\npub struct StdRng(StdRngImpl);\n\n\n\n#[contract_trait]\n\nimpl necsim_core::cogs::Backup for StdRng {\n\n unsafe fn backup_unchecked(&self) -> Self {\n\n self.clone()\n\n }\n\n}\n\n\n\nimpl necsim_core::cogs::RngCore for StdRng {\n\n type Seed = <StdRngImpl as SeedableRng>::Seed;\n\n\n\n #[must_use]\n\n #[inline]\n\n fn from_seed(seed: Self::Seed) -> Self {\n\n Self(StdRngImpl::from_seed(seed))\n\n }\n\n\n\n #[must_use]\n\n #[inline]\n\n fn sample_u64(&mut self) -> u64 {\n\n self.0.next_u64()\n\n }\n\n}\n", "file_path": "necsim/impls/std/src/cogs/rng/std.rs", "rank": 66, "score": 144914.44770878018 }, { "content": "use necsim_core::cogs::{Backup, PrimeableRng, RngCore};\n\n\n\n#[allow(clippy::module_name_repetitions)]\n\n#[derive(Clone, Debug)]\n\npub struct SeaHash {\n\n seed: u64,\n\n location: u64,\n\n time: u64,\n\n offset: u64,\n\n}\n\n\n\n#[contract_trait]\n\nimpl Backup for SeaHash {\n\n unsafe fn backup_unchecked(&self) -> Self {\n\n self.clone()\n\n }\n\n}\n\n\n\nimpl RngCore for SeaHash {\n\n type Seed = [u8; 8];\n", "file_path": "necsim/impls/no-std/src/cogs/rng/seahash.rs", "rank": 67, "score": 144914.06964981044 }, { "content": "use necsim_core::cogs::{Backup, PrimeableRng, RngCore};\n\n\n\n#[allow(clippy::module_name_repetitions)]\n\n#[derive(Clone, Debug)]\n\npub struct FixedSeaHash {\n\n seed: u64,\n\n location_index: u64,\n\n time_index: u64,\n\n state: u64,\n\n}\n\n\n\n#[contract_trait]\n\nimpl Backup for FixedSeaHash {\n\n unsafe fn backup_unchecked(&self) -> Self {\n\n self.clone()\n\n }\n\n}\n\n\n\nimpl RngCore for FixedSeaHash {\n\n type Seed = [u8; 8];\n", "file_path": "necsim/impls/no-std/src/cogs/rng/fixedseahash.rs", "rank": 68, "score": 144913.21340597654 }, { "content": " self.state\n\n }\n\n}\n\n\n\nimpl PrimeableRng for FixedSeaHash {\n\n #[inline]\n\n fn prime_with(&mut self, location_index: u64, time_index: u64) {\n\n self.location_index = location_index;\n\n self.time_index = time_index;\n\n\n\n self.state = 0_u64;\n\n }\n\n}\n\n\n\n// https://docs.rs/seahash/4.0.1/src/seahash/helper.rs.html#72-89\n\n#[inline]\n\nconst fn diffuse(mut x: u64) -> u64 {\n\n // These are derived from the PCG RNG's round. Thanks to @Veedrac for proposing\n\n // this. The basic idea is that we use dynamic shifts, which are determined\n\n // by the input itself. The shift is chosen by the higher bits, which means\n", "file_path": "necsim/impls/no-std/src/cogs/rng/fixedseahash.rs", "rank": 69, "score": 144910.9935320072 }, { "content": " )))\n\n }\n\n\n\n #[must_use]\n\n #[inline]\n\n fn sample_u64(&mut self) -> u64 {\n\n self.0.next_u64()\n\n }\n\n}\n\n\n\nimpl SplittableRng for Pcg {\n\n #[allow(clippy::identity_op)]\n\n fn split(self) -> (Self, Self) {\n\n let mut left_state = self.0.get_state();\n\n left_state.increment = (((left_state.increment >> 1) * 2 + 0) << 1) | 1;\n\n\n\n let mut right_state = self.0.get_state();\n\n right_state.increment = (((right_state.increment >> 1) * 2 + 1) << 1) | 1;\n\n\n\n let left = Self(Pcg64::restore_state_with_no_verification(left_state));\n", "file_path": "necsim/impls/std/src/cogs/rng/pcg.rs", "rank": 70, "score": 144910.69702167273 }, { "content": " }\n\n}\n\n\n\nimpl PrimeableRng for SeaHash {\n\n fn prime_with(&mut self, location_index: u64, time_index: u64) {\n\n self.location = location_index;\n\n self.time = time_index;\n\n\n\n self.offset = 0_u64;\n\n }\n\n}\n", "file_path": "necsim/impls/no-std/src/cogs/rng/seahash.rs", "rank": 71, "score": 144909.54171316922 }, { "content": "\n\n #[must_use]\n\n #[inline]\n\n fn from_seed(seed: Self::Seed) -> Self {\n\n let seed = u64::from_le_bytes(seed);\n\n\n\n Self {\n\n seed,\n\n location_index: 0_u64,\n\n time_index: 0_u64,\n\n state: seed,\n\n }\n\n }\n\n\n\n #[must_use]\n\n #[inline]\n\n fn sample_u64(&mut self) -> u64 {\n\n self.state =\n\n diffuse(diffuse(self.state ^ self.location_index) ^ self.time_index) ^ self.seed;\n\n\n", "file_path": "necsim/impls/no-std/src/cogs/rng/fixedseahash.rs", "rank": 72, "score": 144908.64717733455 }, { "content": "\n\n let u64_injection = habitat\n\n .iter()\n\n .map(|h| {\n\n let injection = index_acc;\n\n index_acc += u64::from(*h);\n\n injection\n\n })\n\n .collect::<Vec<u64>>()\n\n .into_boxed_slice();\n\n\n\n #[allow(clippy::cast_possible_truncation)]\n\n let extent = LandscapeExtent::new(0, 0, width, height);\n\n\n\n Self {\n\n habitat,\n\n u64_injection,\n\n extent,\n\n }\n\n }\n\n}\n", "file_path": "necsim/impls/no-std/src/cogs/habitat/in_memory.rs", "rank": 73, "score": 144908.3475087032 }, { "content": "\n\n #[must_use]\n\n #[inline]\n\n fn from_seed(seed: Self::Seed) -> Self {\n\n let seed = u64::from_le_bytes(seed);\n\n\n\n Self {\n\n seed,\n\n location: 0_u64,\n\n time: 0_u64,\n\n offset: 0_u64,\n\n }\n\n }\n\n\n\n #[must_use]\n\n #[inline]\n\n fn sample_u64(&mut self) -> u64 {\n\n let offset_bytes = self.offset.to_le_bytes();\n\n self.offset += 1;\n\n seahash::hash_seeded(&offset_bytes, self.time, self.location, self.seed, 0_u64)\n", "file_path": "necsim/impls/no-std/src/cogs/rng/seahash.rs", "rank": 74, "score": 144908.181119127 }, { "content": "use nanorand::{Rng, WyRand as WyImpl};\n\n\n\nuse necsim_core::cogs::{Backup, RngCore};\n\n\n\n#[allow(clippy::module_name_repetitions)]\n\n#[derive(Clone)]\n\npub struct WyRand(WyImpl);\n\n\n\n#[contract_trait]\n\nimpl Backup for WyRand {\n\n unsafe fn backup_unchecked(&self) -> Self {\n\n self.clone()\n\n }\n\n}\n\n\n\nimpl RngCore for WyRand {\n\n type Seed = [u8; 8];\n\n\n\n #[must_use]\n\n #[inline]\n", "file_path": "necsim/impls/no-std/src/cogs/rng/wyrand.rs", "rank": 75, "score": 144908.19223324783 }, { "content": "}\n\n\n\nimpl RngCore for AesRng {\n\n type Seed = [u8; 16];\n\n\n\n #[must_use]\n\n #[inline]\n\n fn from_seed(seed: Self::Seed) -> Self {\n\n Self {\n\n cipher: Aes128::new(GenericArray::from_slice(&seed)),\n\n state: [0_u8; 16],\n\n cached: false,\n\n }\n\n }\n\n\n\n #[must_use]\n\n #[inline]\n\n fn sample_u64(&mut self) -> u64 {\n\n self.cached ^= true;\n\n\n", "file_path": "necsim/impls/no-std/src/cogs/rng/aes.rs", "rank": 76, "score": 144907.71244161902 }, { "content": " self.state[10],\n\n self.state[11],\n\n self.state[12],\n\n self.state[13],\n\n self.state[14],\n\n self.state[15],\n\n ]);\n\n\n\n self.state[9] = self.state[9].wrapping_add(1);\n\n\n\n rand_u64\n\n }\n\n }\n\n}\n\n\n\nimpl PrimeableRng for AesRng {\n\n fn prime_with(&mut self, location_index: u64, time_index: u64) {\n\n let location_bytes = location_index.to_le_bytes();\n\n\n\n self.state[0] = location_bytes[0];\n", "file_path": "necsim/impls/no-std/src/cogs/rng/aes.rs", "rank": 77, "score": 144907.43390587904 }, { "content": "use necsim_core::cogs::{Backup, PrimeableRng, RngCore};\n\n\n\n#[allow(clippy::module_name_repetitions)]\n\n#[derive(Clone, Debug)]\n\npub struct XxHash {\n\n seed: u64,\n\n state: u64,\n\n}\n\n\n\n#[contract_trait]\n\nimpl Backup for XxHash {\n\n unsafe fn backup_unchecked(&self) -> Self {\n\n self.clone()\n\n }\n\n}\n\n\n\nimpl RngCore for XxHash {\n\n type Seed = [u8; 8];\n\n\n\n #[must_use]\n", "file_path": "necsim/impls/no-std/src/cogs/rng/xxhash.rs", "rank": 78, "score": 144907.04563364421 }, { "content": "use necsim_core::cogs::{Backup, PrimeableRng, RngCore};\n\n\n\nuse aes::{\n\n cipher::{generic_array::GenericArray, BlockEncrypt, NewBlockCipher},\n\n Aes128,\n\n};\n\n\n\n#[allow(clippy::module_name_repetitions)]\n\n#[derive(Clone, Debug)]\n\npub struct AesRng {\n\n cipher: Aes128,\n\n state: [u8; 16],\n\n cached: bool,\n\n}\n\n\n\n#[contract_trait]\n\nimpl Backup for AesRng {\n\n unsafe fn backup_unchecked(&self) -> Self {\n\n self.clone()\n\n }\n", "file_path": "necsim/impls/no-std/src/cogs/rng/aes.rs", "rank": 79, "score": 144905.47660866327 }, { "content": " }\n\n}\n\n\n\nimpl RngCore for WyHash {\n\n type Seed = [u8; 8];\n\n\n\n #[must_use]\n\n #[inline]\n\n fn from_seed(seed: Self::Seed) -> Self {\n\n let seed = u64::from_le_bytes(seed);\n\n\n\n Self { seed, state: seed }\n\n }\n\n\n\n #[must_use]\n\n #[inline]\n\n fn sample_u64(&mut self) -> u64 {\n\n // wyrng state transition function\n\n // https://docs.rs/wyhash/0.5.0/src/wyhash/functions.rs.html#129-132\n\n self.state = self.state.wrapping_add(P0);\n", "file_path": "necsim/impls/no-std/src/cogs/rng/wyhash.rs", "rank": 80, "score": 144904.90404775305 }, { "content": "\n\n // wyrng output function\n\n let wyrng = wymum(self.state ^ P1, self.state);\n\n\n\n // SeaHash diffusion function for better avalanching\n\n seahash_diffuse(wyrng)\n\n }\n\n}\n\n\n\nimpl PrimeableRng for WyHash {\n\n #[inline]\n\n fn prime_with(&mut self, location_index: u64, time_index: u64) {\n\n let location_index = seahash_diffuse(location_index);\n\n let time_index = seahash_diffuse(time_index);\n\n\n\n // wyhash state repriming\n\n // https://docs.rs/wyhash/0.5.0/src/wyhash/functions.rs.html#67-70\n\n let hash = wymum(\n\n ((location_index << 32) | (location_index >> 32)) ^ (self.seed ^ P0),\n\n ((time_index << 32) | (time_index >> 32)) ^ P2,\n\n );\n\n\n\n self.state = wymum(hash, 16 ^ P5);\n\n }\n\n}\n\n\n\n#[inline]\n\n#[allow(clippy::cast_possible_truncation)]\n", "file_path": "necsim/impls/no-std/src/cogs/rng/wyhash.rs", "rank": 81, "score": 144904.42844605717 }, { "content": " fn from_seed(seed: Self::Seed) -> Self {\n\n Self(WyImpl::new_seed(u64::from_le_bytes(seed)))\n\n }\n\n\n\n #[must_use]\n\n #[inline]\n\n fn sample_u64(&mut self) -> u64 {\n\n self.0.generate()\n\n }\n\n}\n\n\n\nimpl core::fmt::Debug for WyRand {\n\n fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {\n\n f.debug_struct(\"WyRand\").finish_non_exhaustive()\n\n }\n\n}\n", "file_path": "necsim/impls/no-std/src/cogs/rng/wyrand.rs", "rank": 82, "score": 144902.55701734766 }, { "content": " fmt.debug_struct(\"Pcg\").finish()\n\n }\n\n}\n\n\n\n#[contract_trait]\n\nimpl Backup for Pcg {\n\n unsafe fn backup_unchecked(&self) -> Self {\n\n self.clone()\n\n }\n\n}\n\n\n\nimpl RngCore for Pcg {\n\n type Seed = [u8; 16];\n\n\n\n #[must_use]\n\n #[inline]\n\n fn from_seed(seed: Self::Seed) -> Self {\n\n Self(Pcg64::from_seed(PcgSeeder::seed_with_stream(\n\n u128::from_le_bytes(seed),\n\n 0_u128,\n", "file_path": "necsim/impls/std/src/cogs/rng/pcg.rs", "rank": 83, "score": 144902.0537037954 }, { "content": "use necsim_core::cogs::{Backup, PrimeableRng, RngCore};\n\n\n\n// WyHash constants\n\n// https://docs.rs/wyhash/0.5.0/src/wyhash/functions.rs.html\n\nconst P0: u64 = 0xa076_1d64_78bd_642f;\n\nconst P1: u64 = 0xe703_7ed1_a0b4_28db;\n\nconst P2: u64 = 0x8ebc_6af0_9c88_c6e3;\n\nconst P5: u64 = 0xeb44_acca_b455_d165;\n\n\n\n#[allow(clippy::module_name_repetitions)]\n\n#[derive(Clone, Debug)]\n\npub struct WyHash {\n\n seed: u64,\n\n state: u64,\n\n}\n\n\n\n#[contract_trait]\n\nimpl Backup for WyHash {\n\n unsafe fn backup_unchecked(&self) -> Self {\n\n self.clone()\n", "file_path": "necsim/impls/no-std/src/cogs/rng/wyhash.rs", "rank": 84, "score": 144901.08527354262 }, { "content": "pub mod almost_infinite;\n\npub mod in_memory;\n\npub mod non_spatial;\n\npub mod spatially_implicit;\n", "file_path": "necsim/impls/no-std/src/cogs/habitat/mod.rs", "rank": 85, "score": 144898.11471028894 }, { "content": " let right = Self(Pcg64::restore_state_with_no_verification(right_state));\n\n\n\n (left, right)\n\n }\n\n\n\n fn split_to_stream(self, stream: u64) -> Self {\n\n let mut state = self.0.get_state();\n\n state.increment = (u128::from(stream) << 1) | 1;\n\n\n\n Self(Pcg64::restore_state_with_no_verification(state))\n\n }\n\n}\n", "file_path": "necsim/impls/std/src/cogs/rng/pcg.rs", "rank": 86, "score": 144897.24593075344 }, { "content": "\n\n self.state = xxhash_rust::xxh64::xxh64(\n\n &[\n\n location_bytes[0],\n\n location_bytes[1],\n\n location_bytes[2],\n\n location_bytes[3],\n\n location_bytes[4],\n\n location_bytes[5],\n\n location_bytes[6],\n\n location_bytes[7],\n\n time_index_bytes[0],\n\n time_index_bytes[1],\n\n time_index_bytes[2],\n\n time_index_bytes[3],\n\n time_index_bytes[4],\n\n time_index_bytes[5],\n\n time_index_bytes[6],\n\n time_index_bytes[7],\n\n ],\n\n self.seed,\n\n );\n\n }\n\n}\n", "file_path": "necsim/impls/no-std/src/cogs/rng/xxhash.rs", "rank": 87, "score": 144895.75685773636 }, { "content": " self.state[1] = location_bytes[1];\n\n self.state[2] = location_bytes[2];\n\n self.state[3] = location_bytes[3];\n\n self.state[4] = location_bytes[4];\n\n self.state[5] = location_bytes[5];\n\n self.state[6] = location_bytes[6];\n\n self.state[7] = location_bytes[7];\n\n\n\n let time_index_bytes = time_index.to_le_bytes();\n\n\n\n self.state[8] = time_index_bytes[0];\n\n self.state[9] = time_index_bytes[1];\n\n self.state[10] = time_index_bytes[2];\n\n self.state[11] = time_index_bytes[3];\n\n self.state[12] = time_index_bytes[4];\n\n self.state[13] = time_index_bytes[5];\n\n self.state[14] = time_index_bytes[6];\n\n self.state[15] = time_index_bytes[7];\n\n\n\n self.cached = false;\n\n }\n\n}\n", "file_path": "necsim/impls/no-std/src/cogs/rng/aes.rs", "rank": 88, "score": 144895.51365753467 }, { "content": " if self.cached {\n\n // one more u64 will be cached\n\n self.cipher\n\n .encrypt_block(GenericArray::from_mut_slice(&mut self.state));\n\n\n\n u64::from_le_bytes([\n\n self.state[0],\n\n self.state[1],\n\n self.state[2],\n\n self.state[3],\n\n self.state[4],\n\n self.state[5],\n\n self.state[6],\n\n self.state[7],\n\n ])\n\n } else {\n\n // one more u64 was cached\n\n let rand_u64 = u64::from_le_bytes([\n\n self.state[8],\n\n self.state[9],\n", "file_path": "necsim/impls/no-std/src/cogs/rng/aes.rs", "rank": 89, "score": 144887.24074451256 }, { "content": "pub mod aes;\n\npub mod fixedseahash;\n\npub mod seahash;\n\npub mod wyhash;\n\npub mod wyrand;\n\npub mod xxhash;\n", "file_path": "necsim/impls/no-std/src/cogs/rng/mod.rs", "rank": 90, "score": 144881.74958412 }, { "content": " // that changing those flips the lower bits, which scatters upwards because\n\n // of the multiplication.\n\n\n\n x = x.wrapping_mul(0x6eed_0e9d_a4d9_4a4f);\n\n\n\n let a = x >> 32;\n\n let b = x >> 60;\n\n\n\n x ^= a >> b;\n\n\n\n x = x.wrapping_mul(0x6eed_0e9d_a4d9_4a4f);\n\n\n\n x\n\n}\n", "file_path": "necsim/impls/no-std/src/cogs/rng/fixedseahash.rs", "rank": 91, "score": 144881.74958412 }, { "content": "pub mod pcg;\n\npub mod std;\n", "file_path": "necsim/impls/std/src/cogs/rng/mod.rs", "rank": 92, "score": 144881.74958412 }, { "content": " // by the input itself. The shift is chosen by the higher bits, which means\n\n // that changing those flips the lower bits, which scatters upwards because\n\n // of the multiplication.\n\n\n\n x = x.wrapping_mul(0x6eed_0e9d_a4d9_4a4f);\n\n\n\n let a = x >> 32;\n\n let b = x >> 60;\n\n\n\n x ^= a >> b;\n\n\n\n x = x.wrapping_mul(0x6eed_0e9d_a4d9_4a4f);\n\n\n\n x\n\n}\n", "file_path": "necsim/impls/no-std/src/cogs/rng/wyhash.rs", "rank": 93, "score": 144881.74958412 }, { "content": "pub trait Scenario<G: RngCore>: Sized + ScenarioArguments {\n\n type Error;\n\n\n\n type Habitat: Habitat;\n\n type OriginSampler<'h, I: Iterator<Item = u64>>: OriginSampler<'h, Habitat = Self::Habitat>;\n\n type Decomposition: Decomposition<Self::Habitat>;\n\n type LineageReference: LineageReference<Self::Habitat>;\n\n type LineageStore<L: LineageStore<Self::Habitat, Self::LineageReference>>: LineageStore<\n\n Self::Habitat,\n\n Self::LineageReference,\n\n >;\n\n type DispersalSampler<D: DispersalSampler<Self::Habitat, G>>: DispersalSampler<Self::Habitat, G>;\n\n type TurnoverRate: TurnoverRate<Self::Habitat>;\n\n type SpeciationProbability: SpeciationProbability<Self::Habitat>;\n\n\n\n /// # Errors\n\n ///\n\n /// Returns a `Self::Error` if initialising the scenario failed\n\n fn initialise(\n\n args: Self::Arguments,\n", "file_path": "rustcoalescence/scenarios/src/lib.rs", "rank": 94, "score": 142884.73088064796 }, { "content": "#[allow(clippy::inline_always, clippy::inline_fn_without_body)]\n\n#[allow(clippy::module_name_repetitions)]\n\n#[contract_trait]\n\npub trait RngSampler: RngCore {\n\n #[must_use]\n\n #[inline]\n\n fn sample_uniform(&mut self) -> ClosedUnitF64 {\n\n // http://prng.di.unimi.it -> Generating uniform doubles in the unit interval\n\n #[allow(clippy::cast_precision_loss)]\n\n let u01 = ((self.sample_u64() >> 11) as f64) * f64::from_bits(0x3CA0_0000_0000_0000_u64); // 0x1.0p-53\n\n\n\n unsafe { ClosedUnitF64::new_unchecked(u01) }\n\n }\n\n\n\n #[must_use]\n\n #[inline]\n\n #[debug_ensures(ret < length, \"samples U(0, length - 1)\")]\n\n fn sample_index(&mut self, length: usize) -> usize {\n\n // attributes on expressions are experimental\n\n // see https://github.com/rust-lang/rust/issues/15701\n\n #[allow(\n\n clippy::cast_precision_loss,\n\n clippy::cast_possible_truncation,\n", "file_path": "necsim/core/src/cogs/rng.rs", "rank": 95, "score": 142169.68813439336 }, { "content": "#[allow(clippy::module_name_repetitions)]\n\npub trait SplittableRng: RngCore {\n\n fn split(self) -> (Self, Self);\n\n\n\n fn split_to_stream(self, stream: u64) -> Self;\n\n}\n", "file_path": "necsim/core/src/cogs/rng.rs", "rank": 96, "score": 142164.42733557717 }, { "content": "#[allow(clippy::module_name_repetitions)]\n\npub trait PrimeableRng: RngCore {\n\n fn prime_with(&mut self, location_index: u64, time_index: u64);\n\n}\n\n\n", "file_path": "necsim/core/src/cogs/rng.rs", "rank": 97, "score": 142164.42733557717 }, { "content": "use necsim_core::{\n\n cogs::{Backup, Habitat},\n\n landscape::{IndexedLocation, LandscapeExtent, Location},\n\n};\n\n\n\n#[allow(clippy::module_name_repetitions)]\n\n#[cfg_attr(feature = \"cuda\", derive(rust_cuda::common::RustToCuda))]\n\n#[derive(Debug)]\n\npub struct NonSpatialHabitat {\n\n extent: LandscapeExtent,\n\n deme: u32,\n\n}\n\n\n\nimpl NonSpatialHabitat {\n\n #[must_use]\n\n #[debug_ensures(\n\n ret.get_total_habitat() == old(u64::from(area.0) * u64::from(area.1) * u64::from(deme)),\n\n \"creates a habitat with community size area.0 * area.1 * deme\"\n\n )]\n\n pub fn new(area: (u32, u32), deme: u32) -> Self {\n", "file_path": "necsim/impls/no-std/src/cogs/habitat/non_spatial.rs", "rank": 98, "score": 141926.6980761503 }, { "content": "use necsim_core::{\n\n cogs::{Backup, Habitat},\n\n landscape::{IndexedLocation, LandscapeExtent, Location},\n\n};\n\n\n\n#[allow(clippy::module_name_repetitions)]\n\n#[cfg_attr(feature = \"cuda\", derive(rust_cuda::common::RustToCuda))]\n\n#[derive(Debug)]\n\npub struct AlmostInfiniteHabitat {\n\n extent: LandscapeExtent,\n\n}\n\n\n\nimpl Default for AlmostInfiniteHabitat {\n\n fn default() -> Self {\n\n Self {\n\n extent: LandscapeExtent::new(0_u32, 0_u32, u32::MAX, u32::MAX),\n\n }\n\n }\n\n}\n\n\n", "file_path": "necsim/impls/no-std/src/cogs/habitat/almost_infinite.rs", "rank": 99, "score": 141924.65440186026 } ]
Rust
sos21-gateway/database/src/pending_project_repository.rs
sohosai/sos21-backend
f1883844b0e5c68d6b3f9d159c9268142abc81b4
use crate::project_repository::{ from_project_attributes, from_project_category, to_project_attributes, to_project_category, }; use crate::user_repository::to_user; use anyhow::Result; use futures::lock::Mutex; use ref_cast::RefCast; use sos21_database::{command, model as data, query}; use sos21_domain::context::pending_project_repository::{ PendingProjectRepository, PendingProjectWithOwner, }; use sos21_domain::model::{ date_time::DateTime, pending_project::{PendingProject, PendingProjectContent, PendingProjectId}, project::{ ProjectDescription, ProjectGroupName, ProjectKanaGroupName, ProjectKanaName, ProjectName, }, user::UserId, }; use sqlx::{Postgres, Transaction}; #[derive(Debug, RefCast)] #[repr(transparent)] pub struct PendingProjectDatabase(Mutex<Transaction<'static, Postgres>>); #[async_trait::async_trait] impl PendingProjectRepository for PendingProjectDatabase { async fn store_pending_project(&self, pending_project: PendingProject) -> Result<()> { let mut lock = self.0.lock().await; let pending_project = from_pending_project(pending_project); if query::find_pending_project(&mut *lock, pending_project.id) .await? .is_some() { let input = command::update_pending_project::Input { id: pending_project.id, created_at: pending_project.created_at, updated_at: pending_project.updated_at, name: pending_project.name, kana_name: pending_project.kana_name, group_name: pending_project.group_name, kana_group_name: pending_project.kana_group_name, description: pending_project.description, category: pending_project.category, attributes: pending_project.attributes, }; command::update_pending_project(&mut *lock, input).await } else { command::insert_pending_project(&mut *lock, pending_project).await } } async fn delete_pending_project(&self, id: PendingProjectId) -> Result<()> { let mut lock = self.0.lock().await; command::delete_pending_project(&mut *lock, id.to_uuid()).await } async fn get_pending_project( &self, id: PendingProjectId, ) -> Result<Option<PendingProjectWithOwner>> { let mut lock = self.0.lock().await; query::find_pending_project(&mut *lock, id.to_uuid()) .await .and_then(|opt| opt.map(to_pending_project_with_owner).transpose()) } } fn from_pending_project(pending_project: PendingProject) -> data::pending_project::PendingProject { let PendingProjectContent { id, created_at, updated_at, name, kana_name, group_name, kana_group_name, description, category, attributes, } = pending_project.into_content(); data::pending_project::PendingProject { id: id.to_uuid(), created_at: created_at.utc(), updated_at: updated_at.utc(), name: name.into_string(), kana_name: kana_name.into_string(), group_name: group_name.into_string(), kana_group_name: kana_group_name.into_string(), description: description.into_string(), category: from_project_category(category), attributes: from_project_attributes(&attributes), } } fn to_pending_project_with_owner( pending_project_with_owner: data::pending_project::PendingProjectWithOwner, ) -> Result<PendingProjectWithOwner> { let data::pending_project::PendingProjectWithOwner { pending_project, owner, } = pending_project_with_owner; let data::pending_project::PendingProject { id, created_at, updated_at, name, kana_name, group_name, kana_group_name, description, category, attributes, } = pending_project; let pending_project = PendingProject::from_content( PendingProjectContent { id: PendingProjectId::from_uuid(id), created_at: DateTime::from_utc(created_at), updated_at: DateTime::from_utc(updated_at), name: ProjectName::from_string(name)?, kana_name: ProjectKanaName::from_string(kana_name)?, group_name: ProjectGroupName::from_string(group_name)?, kana_group_name: ProjectKanaGroupName::from_string(kana_group_name)?, description: ProjectDescription::from_string(description)?, category: to_project_category(category), attributes: to_project_attributes(attributes)?, }, UserId(owner.id.clone()), ); Ok(PendingProjectWithOwner { pending_project, owner: to_user(owner)?, }) }
use crate::project_repository::{ from_project_attributes, from_project_category, to_project_attributes, to_project_category, }; use crate::user_repository::to_user; use anyhow::Result; use futures::lock::Mutex; use ref_cast::RefCast; use sos21_database::{command, model as data, query}; use sos21_domain::context::pending_project_repository::{ PendingProjectRepository, PendingProjectWithOwner, }; use sos21_domain::model::{ date_time::DateTime, pending_project::{PendingProject, PendingProjectContent, PendingProjectId}, project::{ ProjectDescription, ProjectGroupName, Proj
me: group_name.into_string(), kana_group_name: kana_group_name.into_string(), description: description.into_string(), category: from_project_category(category), attributes: from_project_attributes(&attributes), } } fn to_pending_project_with_owner( pending_project_with_owner: data::pending_project::PendingProjectWithOwner, ) -> Result<PendingProjectWithOwner> { let data::pending_project::PendingProjectWithOwner { pending_project, owner, } = pending_project_with_owner; let data::pending_project::PendingProject { id, created_at, updated_at, name, kana_name, group_name, kana_group_name, description, category, attributes, } = pending_project; let pending_project = PendingProject::from_content( PendingProjectContent { id: PendingProjectId::from_uuid(id), created_at: DateTime::from_utc(created_at), updated_at: DateTime::from_utc(updated_at), name: ProjectName::from_string(name)?, kana_name: ProjectKanaName::from_string(kana_name)?, group_name: ProjectGroupName::from_string(group_name)?, kana_group_name: ProjectKanaGroupName::from_string(kana_group_name)?, description: ProjectDescription::from_string(description)?, category: to_project_category(category), attributes: to_project_attributes(attributes)?, }, UserId(owner.id.clone()), ); Ok(PendingProjectWithOwner { pending_project, owner: to_user(owner)?, }) }
ectKanaGroupName, ProjectKanaName, ProjectName, }, user::UserId, }; use sqlx::{Postgres, Transaction}; #[derive(Debug, RefCast)] #[repr(transparent)] pub struct PendingProjectDatabase(Mutex<Transaction<'static, Postgres>>); #[async_trait::async_trait] impl PendingProjectRepository for PendingProjectDatabase { async fn store_pending_project(&self, pending_project: PendingProject) -> Result<()> { let mut lock = self.0.lock().await; let pending_project = from_pending_project(pending_project); if query::find_pending_project(&mut *lock, pending_project.id) .await? .is_some() { let input = command::update_pending_project::Input { id: pending_project.id, created_at: pending_project.created_at, updated_at: pending_project.updated_at, name: pending_project.name, kana_name: pending_project.kana_name, group_name: pending_project.group_name, kana_group_name: pending_project.kana_group_name, description: pending_project.description, category: pending_project.category, attributes: pending_project.attributes, }; command::update_pending_project(&mut *lock, input).await } else { command::insert_pending_project(&mut *lock, pending_project).await } } async fn delete_pending_project(&self, id: PendingProjectId) -> Result<()> { let mut lock = self.0.lock().await; command::delete_pending_project(&mut *lock, id.to_uuid()).await } async fn get_pending_project( &self, id: PendingProjectId, ) -> Result<Option<PendingProjectWithOwner>> { let mut lock = self.0.lock().await; query::find_pending_project(&mut *lock, id.to_uuid()) .await .and_then(|opt| opt.map(to_pending_project_with_owner).transpose()) } } fn from_pending_project(pending_project: PendingProject) -> data::pending_project::PendingProject { let PendingProjectContent { id, created_at, updated_at, name, kana_name, group_name, kana_group_name, description, category, attributes, } = pending_project.into_content(); data::pending_project::PendingProject { id: id.to_uuid(), created_at: created_at.utc(), updated_at: updated_at.utc(), name: name.into_string(), kana_name: kana_name.into_string(), group_na
random
[ { "content": "use crate::model::project::{ProjectAttribute, ProjectCategory};\n\n\n\nuse sos21_domain::model::project_query as entity;\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\npub struct ProjectQueryConjunction {\n\n pub category: Option<ProjectCategory>,\n\n pub attributes: Vec<ProjectAttribute>,\n\n}\n\n\n\nimpl ProjectQueryConjunction {\n\n pub fn from_entity(conj: entity::ProjectQueryConjunction) -> Self {\n\n ProjectQueryConjunction {\n\n category: conj.category().map(ProjectCategory::from_entity),\n\n attributes: conj\n\n .attributes()\n\n .map(ProjectAttribute::from_entity)\n\n .collect(),\n\n }\n\n }\n", "file_path": "sos21-use-case/src/model/project_query.rs", "rank": 0, "score": 198425.30508398678 }, { "content": "}\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\npub struct ProjectQuery(pub Vec<ProjectQueryConjunction>);\n\n\n\nimpl ProjectQuery {\n\n pub fn from_entity(query: entity::ProjectQuery) -> Self {\n\n ProjectQuery(\n\n query\n\n .into_conjunctions()\n\n .map(ProjectQueryConjunction::from_entity)\n\n .collect(),\n\n )\n\n }\n\n}\n", "file_path": "sos21-use-case/src/model/project_query.rs", "rank": 1, "score": 198416.20889991458 }, { "content": "fn from_project(project: Project) -> data::project::Project {\n\n let ProjectContent {\n\n id,\n\n index,\n\n created_at,\n\n updated_at,\n\n name,\n\n kana_name,\n\n group_name,\n\n kana_group_name,\n\n description,\n\n category,\n\n attributes,\n\n } = project.into_content();\n\n\n\n data::project::Project {\n\n id: id.to_uuid(),\n\n index: index.to_i16(),\n\n created_at: created_at.utc(),\n\n updated_at: updated_at.utc(),\n\n name: name.into_string(),\n\n kana_name: kana_name.into_string(),\n\n group_name: group_name.into_string(),\n\n kana_group_name: kana_group_name.into_string(),\n\n description: description.into_string(),\n\n category: from_project_category(category),\n\n attributes: from_project_attributes(&attributes),\n\n }\n\n}\n\n\n", "file_path": "sos21-gateway/database/src/project_repository.rs", "rank": 2, "score": 187765.3097458245 }, { "content": "pub fn mock_project_query() -> ProjectQuery {\n\n ProjectQuery::from_conjunctions(vec![ProjectQueryConjunction {\n\n category: None,\n\n attributes: ProjectAttributes::from_attributes(Vec::new()).unwrap(),\n\n }])\n\n .unwrap()\n\n}\n", "file_path": "sos21-domain/src/test/model/project_query.rs", "rank": 3, "score": 170010.15173757763 }, { "content": "pub fn to_project_query(\n\n query: ProjectQuery,\n\n) -> Result<project_query::ProjectQuery, ProjectQueryError> {\n\n let dnf = query\n\n .0\n\n .into_iter()\n\n .map(to_project_query_conjunction)\n\n .collect::<Result<Vec<_>, _>>()?;\n\n project_query::ProjectQuery::from_conjunctions(dnf).map_err(ProjectQueryError::from_query_error)\n\n}\n\n\n", "file_path": "sos21-use-case/src/interface/project_query.rs", "rank": 4, "score": 164702.7926567635 }, { "content": "pub fn to_project_query_conjunction(\n\n conj: ProjectQueryConjunction,\n\n) -> Result<project_query::ProjectQueryConjunction, ProjectQueryError> {\n\n let category = conj.category.map(ProjectCategory::into_entity);\n\n let attributes = project::ProjectAttributes::from_attributes(\n\n conj.attributes\n\n .into_iter()\n\n .map(ProjectAttribute::into_entity),\n\n )\n\n .map_err(ProjectQueryError::from_attributes_error)?;\n\n\n\n Ok(project_query::ProjectQueryConjunction {\n\n category,\n\n attributes,\n\n })\n\n}\n", "file_path": "sos21-use-case/src/interface/project_query.rs", "rank": 5, "score": 162705.37138906482 }, { "content": "pub fn to_project_category(category: data::project::ProjectCategory) -> ProjectCategory {\n\n match category {\n\n data::project::ProjectCategory::General => ProjectCategory::General,\n\n data::project::ProjectCategory::Stage => ProjectCategory::Stage,\n\n data::project::ProjectCategory::Cooking => ProjectCategory::Cooking,\n\n data::project::ProjectCategory::Food => ProjectCategory::Food,\n\n }\n\n}\n\n\n", "file_path": "sos21-gateway/database/src/project_repository.rs", "rank": 6, "score": 160553.34528123 }, { "content": "pub fn from_project_category(category: ProjectCategory) -> data::project::ProjectCategory {\n\n match category {\n\n ProjectCategory::General => data::project::ProjectCategory::General,\n\n ProjectCategory::Stage => data::project::ProjectCategory::Stage,\n\n ProjectCategory::Cooking => data::project::ProjectCategory::Cooking,\n\n ProjectCategory::Food => data::project::ProjectCategory::Food,\n\n }\n\n}\n\n\n", "file_path": "sos21-gateway/database/src/project_repository.rs", "rank": 7, "score": 160553.34528123 }, { "content": "pub fn from_project_attributes(attributes: &ProjectAttributes) -> data::project::ProjectAttributes {\n\n attributes\n\n .attributes()\n\n .map(|attr| match attr {\n\n ProjectAttribute::Academic => data::project::ProjectAttributes::ACADEMIC,\n\n ProjectAttribute::Artistic => data::project::ProjectAttributes::ARTISTIC,\n\n ProjectAttribute::Committee => data::project::ProjectAttributes::COMMITTEE,\n\n ProjectAttribute::Outdoor => data::project::ProjectAttributes::OUTDOOR,\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "sos21-gateway/database/src/project_repository.rs", "rank": 8, "score": 160553.34528123 }, { "content": "use std::collections::HashSet;\n\n\n\nuse crate::model::bound::{Bounded, Unbounded};\n\nuse crate::model::collection::LengthLimitedVec;\n\nuse crate::model::pending_project::PendingProject;\n\nuse crate::model::project::{Project, ProjectAttribute, ProjectAttributes, ProjectCategory};\n\n\n\nuse serde::{Deserialize, Serialize};\n\nuse thiserror::Error;\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct ProjectQueryConjunction {\n\n pub category: Option<ProjectCategory>,\n\n pub attributes: ProjectAttributes,\n\n}\n\n\n\nimpl ProjectQueryConjunction {\n\n pub fn category(&self) -> Option<ProjectCategory> {\n\n self.category\n\n }\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 9, "score": 152275.8516704615 }, { "content": "#[cfg(test)]\n\nmod tests {\n\n use super::{ProjectQuery, ProjectQueryConjunction};\n\n use crate::{\n\n model::project::{ProjectAttribute, ProjectAttributes, ProjectCategory},\n\n test::model as test_model,\n\n };\n\n\n\n #[test]\n\n fn test_conj_tautology() {\n\n let conj = ProjectQueryConjunction {\n\n category: None,\n\n attributes: ProjectAttributes::from_attributes(vec![]).unwrap(),\n\n };\n\n let project1 = test_model::new_general_project(test_model::new_user_id());\n\n assert!(conj.check_project(&project1));\n\n let project2 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 10, "score": 152275.65394851848 }, { "content": " ],\n\n );\n\n assert!(!query.check_project(&project2));\n\n }\n\n\n\n #[test]\n\n fn test_pending_project_contradiction() {\n\n let query = ProjectQuery::from_conjunctions(vec![]).unwrap();\n\n let pending_project = test_model::new_general_pending_project(test_model::new_user_id());\n\n assert!(!query.check_pending_project(&pending_project));\n\n let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[\n\n ProjectAttribute::Artistic,\n\n ProjectAttribute::Academic,\n\n ProjectAttribute::Committee,\n\n ],\n\n );\n\n assert!(!query.check_pending_project(&pending_project));\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 11, "score": 152271.26454618823 }, { "content": " );\n\n assert!(query.check_pending_project(&pending_project));\n\n }\n\n\n\n #[test]\n\n fn test_contradiction() {\n\n let query = ProjectQuery::from_conjunctions(vec![]).unwrap();\n\n let project1 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[],\n\n );\n\n assert!(!query.check_project(&project1));\n\n let project2 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[\n\n ProjectAttribute::Artistic,\n\n ProjectAttribute::Academic,\n\n ProjectAttribute::Committee,\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 12, "score": 152271.1714327333 }, { "content": " assert!(query.check_project(&project2));\n\n }\n\n\n\n #[test]\n\n fn test_pending_project_tautology() {\n\n let conj = ProjectQueryConjunction {\n\n category: None,\n\n attributes: ProjectAttributes::from_attributes(vec![]).unwrap(),\n\n };\n\n let query = ProjectQuery::from_conjunctions(vec![conj]).unwrap();\n\n let pending_project = test_model::new_general_pending_project(test_model::new_user_id());\n\n assert!(query.check_pending_project(&pending_project));\n\n let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[\n\n ProjectAttribute::Artistic,\n\n ProjectAttribute::Academic,\n\n ProjectAttribute::Committee,\n\n ],\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 13, "score": 152271.08739944882 }, { "content": " let conj = ProjectQueryConjunction {\n\n category: None,\n\n attributes: ProjectAttributes::from_attributes(vec![]).unwrap(),\n\n };\n\n let query = ProjectQuery::from_conjunctions(vec![conj]).unwrap();\n\n let project1 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[],\n\n );\n\n assert!(query.check_project(&project1));\n\n let project2 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[\n\n ProjectAttribute::Artistic,\n\n ProjectAttribute::Academic,\n\n ProjectAttribute::Committee,\n\n ],\n\n );\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 14, "score": 152271.06886088796 }, { "content": " ProjectCategory::General,\n\n &[ProjectAttribute::Academic],\n\n );\n\n assert!(!query.check_project(&project1));\n\n let project2 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::Stage,\n\n &[ProjectAttribute::Academic],\n\n );\n\n assert!(query.check_project(&project2));\n\n let project3 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::Stage,\n\n &[ProjectAttribute::Academic, ProjectAttribute::Committee],\n\n );\n\n assert!(query.check_project(&project3));\n\n let project4 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[ProjectAttribute::Academic, ProjectAttribute::Committee],\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 15, "score": 152270.76206389038 }, { "content": " let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[ProjectAttribute::Academic],\n\n );\n\n assert!(!query.check_pending_project(&pending_project));\n\n let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::Stage,\n\n &[ProjectAttribute::Academic],\n\n );\n\n assert!(query.check_pending_project(&pending_project));\n\n let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::Stage,\n\n &[ProjectAttribute::Academic, ProjectAttribute::Committee],\n\n );\n\n assert!(query.check_pending_project(&pending_project));\n\n let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 16, "score": 152270.7278846383 }, { "content": " }\n\n\n\n #[test]\n\n fn test_complex() {\n\n let conj1 = ProjectQueryConjunction {\n\n category: Some(ProjectCategory::Stage),\n\n attributes: ProjectAttributes::from_attributes(vec![ProjectAttribute::Academic])\n\n .unwrap(),\n\n };\n\n let conj2 = ProjectQueryConjunction {\n\n category: None,\n\n attributes: ProjectAttributes::from_attributes(vec![\n\n ProjectAttribute::Academic,\n\n ProjectAttribute::Committee,\n\n ])\n\n .unwrap(),\n\n };\n\n let query = ProjectQuery::from_conjunctions(vec![conj1, conj2]).unwrap();\n\n let project1 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 17, "score": 152270.1910802704 }, { "content": " }\n\n\n\n #[test]\n\n fn test_conj_category() {\n\n let conj = ProjectQueryConjunction {\n\n category: Some(ProjectCategory::General),\n\n attributes: ProjectAttributes::from_attributes(vec![]).unwrap(),\n\n };\n\n assert!(conj.check_project(&test_model::new_general_project(test_model::new_user_id())));\n\n assert!(!conj.check_project(&test_model::new_stage_project(test_model::new_user_id())));\n\n }\n\n\n\n #[test]\n\n fn test_pending_project_conj_category() {\n\n let conj = ProjectQueryConjunction {\n\n category: Some(ProjectCategory::General),\n\n attributes: ProjectAttributes::from_attributes(vec![]).unwrap(),\n\n };\n\n assert!(\n\n conj.check_pending_project(&test_model::new_general_pending_project(\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 18, "score": 152269.80204510805 }, { "content": " }\n\n\n\n #[test]\n\n fn test_conj_attribute_multiple() {\n\n let conj = ProjectQueryConjunction {\n\n category: None,\n\n attributes: ProjectAttributes::from_attributes(vec![\n\n ProjectAttribute::Artistic,\n\n ProjectAttribute::Committee,\n\n ])\n\n .unwrap(),\n\n };\n\n let project1 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[],\n\n );\n\n assert!(!conj.check_project(&project1));\n\n let project2 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 19, "score": 152268.90688524136 }, { "content": " test_model::new_user_id()\n\n ))\n\n );\n\n assert!(\n\n !conj.check_pending_project(&test_model::new_stage_pending_project(\n\n test_model::new_user_id()\n\n ))\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_conj_complex() {\n\n let conj = ProjectQueryConjunction {\n\n category: Some(ProjectCategory::Stage),\n\n attributes: ProjectAttributes::from_attributes(vec![\n\n ProjectAttribute::Academic,\n\n ProjectAttribute::Committee,\n\n ])\n\n .unwrap(),\n\n };\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 20, "score": 152268.88041851646 }, { "content": " }\n\n\n\n #[test]\n\n fn test_pending_project_conj_attribute_multiple() {\n\n let conj = ProjectQueryConjunction {\n\n category: None,\n\n attributes: ProjectAttributes::from_attributes(vec![\n\n ProjectAttribute::Artistic,\n\n ProjectAttribute::Committee,\n\n ])\n\n .unwrap(),\n\n };\n\n let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[],\n\n );\n\n assert!(!conj.check_pending_project(&pending_project));\n\n let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 21, "score": 152268.79016914836 }, { "content": " ProjectAttribute::Artistic,\n\n ProjectAttribute::Academic,\n\n ProjectAttribute::Committee,\n\n ],\n\n );\n\n assert!(conj.check_project(&project2));\n\n }\n\n\n\n #[test]\n\n fn test_pending_project_conj_tautology() {\n\n let conj = ProjectQueryConjunction {\n\n category: None,\n\n attributes: ProjectAttributes::from_attributes(vec![]).unwrap(),\n\n };\n\n let pending_project = test_model::new_general_pending_project(test_model::new_user_id());\n\n assert!(conj.check_pending_project(&pending_project));\n\n let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 22, "score": 152268.58545169188 }, { "content": " ProjectCategory::Stage,\n\n &[ProjectAttribute::Academic],\n\n );\n\n assert!(!conj.check_project(&project4));\n\n }\n\n\n\n #[test]\n\n fn test_pending_project_conj_complex() {\n\n let conj = ProjectQueryConjunction {\n\n category: Some(ProjectCategory::Stage),\n\n attributes: ProjectAttributes::from_attributes(vec![\n\n ProjectAttribute::Academic,\n\n ProjectAttribute::Committee,\n\n ])\n\n .unwrap(),\n\n };\n\n let pending_project = test_model::new_general_pending_project(test_model::new_user_id());\n\n assert!(!conj.check_pending_project(&pending_project));\n\n let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 23, "score": 152268.54117270064 }, { "content": " &[ProjectAttribute::Academic, ProjectAttribute::Committee],\n\n );\n\n assert!(!conj.check_project(&project4));\n\n }\n\n\n\n #[test]\n\n fn test_pending_project_conj_attribute_single() {\n\n let conj = ProjectQueryConjunction {\n\n category: None,\n\n attributes: ProjectAttributes::from_attributes(vec![ProjectAttribute::Artistic])\n\n .unwrap(),\n\n };\n\n let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[],\n\n );\n\n assert!(!conj.check_pending_project(&pending_project));\n\n let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 24, "score": 152268.54689700063 }, { "content": " ProjectCategory::General,\n\n &[ProjectAttribute::Academic, ProjectAttribute::Committee],\n\n );\n\n assert!(query.check_pending_project(&pending_project));\n\n }\n\n\n\n #[test]\n\n fn test_conj_possible_categories() {\n\n use std::collections::HashSet;\n\n\n\n let conj1 = ProjectQueryConjunction {\n\n category: Some(ProjectCategory::Stage),\n\n attributes: ProjectAttributes::from_attributes(vec![ProjectAttribute::Academic])\n\n .unwrap(),\n\n };\n\n assert_eq!(\n\n conj1.possible_categories().collect::<Vec<_>>(),\n\n vec![ProjectCategory::Stage]\n\n );\n\n let conj2 = ProjectQueryConjunction {\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 25, "score": 152268.54047007006 }, { "content": " ProjectAttribute::Artistic,\n\n ProjectAttribute::Academic,\n\n ProjectAttribute::Committee,\n\n ],\n\n );\n\n assert!(conj.check_pending_project(&pending_project));\n\n }\n\n\n\n #[test]\n\n fn test_conj_attribute_single() {\n\n let conj = ProjectQueryConjunction {\n\n category: None,\n\n attributes: ProjectAttributes::from_attributes(vec![ProjectAttribute::Artistic])\n\n .unwrap(),\n\n };\n\n let project1 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[],\n\n );\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 26, "score": 152268.25771560182 }, { "content": " category: None,\n\n attributes: ProjectAttributes::from_attributes(vec![ProjectAttribute::Academic])\n\n .unwrap(),\n\n };\n\n assert_eq!(\n\n conj2.possible_categories().collect::<HashSet<_>>(),\n\n ProjectCategory::enumerate().collect::<HashSet<_>>()\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_possible_categories() {\n\n use std::collections::HashSet;\n\n\n\n let conj1 = ProjectQueryConjunction {\n\n category: Some(ProjectCategory::Stage),\n\n attributes: ProjectAttributes::from_attributes(vec![ProjectAttribute::Academic])\n\n .unwrap(),\n\n };\n\n let conj2 = ProjectQueryConjunction {\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 27, "score": 152267.86258933257 }, { "content": " );\n\n assert!(query.check_project(&project4));\n\n }\n\n\n\n #[test]\n\n fn test_pending_project_complex() {\n\n let conj1 = ProjectQueryConjunction {\n\n category: Some(ProjectCategory::Stage),\n\n attributes: ProjectAttributes::from_attributes(vec![ProjectAttribute::Academic])\n\n .unwrap(),\n\n };\n\n let conj2 = ProjectQueryConjunction {\n\n category: None,\n\n attributes: ProjectAttributes::from_attributes(vec![\n\n ProjectAttribute::Academic,\n\n ProjectAttribute::Committee,\n\n ])\n\n .unwrap(),\n\n };\n\n let query = ProjectQuery::from_conjunctions(vec![conj1, conj2]).unwrap();\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 28, "score": 152265.55414267784 }, { "content": " let project1 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[],\n\n );\n\n assert!(!conj.check_project(&project1));\n\n let project2 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[ProjectAttribute::Academic, ProjectAttribute::Committee],\n\n );\n\n assert!(!conj.check_project(&project2));\n\n let project3 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::Stage,\n\n &[ProjectAttribute::Academic, ProjectAttribute::Committee],\n\n );\n\n assert!(conj.check_project(&project3));\n\n let project4 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 29, "score": 152265.38073899617 }, { "content": " assert!(!conj.check_project(&project1));\n\n let project2 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[ProjectAttribute::Artistic, ProjectAttribute::Committee],\n\n );\n\n assert!(conj.check_project(&project2));\n\n let project3 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[\n\n ProjectAttribute::Artistic,\n\n ProjectAttribute::Academic,\n\n ProjectAttribute::Committee,\n\n ],\n\n );\n\n assert!(conj.check_project(&project3));\n\n let project4 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 30, "score": 152265.2296177635 }, { "content": "impl ProjectQuery {\n\n pub fn from_conjunctions<I>(conj: I) -> Result<Self, FromConjunctionsError>\n\n where\n\n I: IntoIterator<Item = ProjectQueryConjunction>,\n\n {\n\n let dnf = LengthLimitedVec::new(conj.into_iter().collect()).map_err(|_| {\n\n FromConjunctionsError {\n\n kind: FromConjunctionsErrorKind::TooBigDisjunction,\n\n }\n\n })?;\n\n Ok(ProjectQuery(dnf))\n\n }\n\n\n\n pub fn conjunctions(&self) -> impl Iterator<Item = &'_ ProjectQueryConjunction> + '_ {\n\n self.0.iter()\n\n }\n\n\n\n pub fn into_conjunctions(self) -> impl Iterator<Item = ProjectQueryConjunction> {\n\n self.0.into_inner().into_iter()\n\n }\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 31, "score": 152264.92515582946 }, { "content": " ProjectCategory::General,\n\n &[ProjectAttribute::Artistic, ProjectAttribute::Committee],\n\n );\n\n assert!(conj.check_project(&project2));\n\n let project3 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[\n\n ProjectAttribute::Artistic,\n\n ProjectAttribute::Academic,\n\n ProjectAttribute::Committee,\n\n ],\n\n );\n\n assert!(conj.check_project(&project3));\n\n let project4 = test_model::new_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[ProjectAttribute::Artistic, ProjectAttribute::Academic],\n\n );\n\n assert!(!conj.check_project(&project4));\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 32, "score": 152264.89675750217 }, { "content": " ProjectCategory::General,\n\n &[ProjectAttribute::Academic, ProjectAttribute::Committee],\n\n );\n\n assert!(!conj.check_pending_project(&pending_project));\n\n let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::Stage,\n\n &[ProjectAttribute::Academic, ProjectAttribute::Committee],\n\n );\n\n assert!(conj.check_pending_project(&pending_project));\n\n let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::Stage,\n\n &[ProjectAttribute::Academic],\n\n );\n\n assert!(!conj.check_pending_project(&pending_project));\n\n }\n\n\n\n #[test]\n\n fn test_tautology() {\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 33, "score": 152264.85279360975 }, { "content": " ProjectCategory::General,\n\n &[ProjectAttribute::Artistic, ProjectAttribute::Committee],\n\n );\n\n assert!(conj.check_pending_project(&pending_project));\n\n let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[\n\n ProjectAttribute::Artistic,\n\n ProjectAttribute::Academic,\n\n ProjectAttribute::Committee,\n\n ],\n\n );\n\n assert!(conj.check_pending_project(&pending_project));\n\n let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[ProjectAttribute::Academic, ProjectAttribute::Committee],\n\n );\n\n assert!(!conj.check_pending_project(&pending_project));\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 34, "score": 152264.84448710762 }, { "content": " ProjectCategory::General,\n\n &[ProjectAttribute::Artistic, ProjectAttribute::Committee],\n\n );\n\n assert!(conj.check_pending_project(&pending_project));\n\n let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[\n\n ProjectAttribute::Artistic,\n\n ProjectAttribute::Academic,\n\n ProjectAttribute::Committee,\n\n ],\n\n );\n\n assert!(conj.check_pending_project(&pending_project));\n\n let pending_project = test_model::new_pending_project_with_attributes(\n\n test_model::new_user_id(),\n\n ProjectCategory::General,\n\n &[ProjectAttribute::Artistic, ProjectAttribute::Academic],\n\n );\n\n assert!(!conj.check_pending_project(&pending_project));\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 35, "score": 152264.84448710762 }, { "content": " };\n\n let conj2 = ProjectQueryConjunction {\n\n category: None,\n\n attributes: ProjectAttributes::from_attributes(vec![\n\n ProjectAttribute::Academic,\n\n ProjectAttribute::Committee,\n\n ])\n\n .unwrap(),\n\n };\n\n let query2 = ProjectQuery::from_conjunctions(vec![conj1, conj2]).unwrap();\n\n assert_eq!(\n\n query2.possible_categories().collect::<HashSet<_>>(),\n\n ProjectCategory::enumerate().collect::<HashSet<_>>()\n\n );\n\n }\n\n}\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 36, "score": 152264.3550161643 }, { "content": " category: Some(ProjectCategory::Food),\n\n attributes: ProjectAttributes::from_attributes(vec![\n\n ProjectAttribute::Academic,\n\n ProjectAttribute::Committee,\n\n ])\n\n .unwrap(),\n\n };\n\n let query1 = ProjectQuery::from_conjunctions(vec![conj1, conj2]).unwrap();\n\n assert_eq!(\n\n query1.possible_categories().collect::<HashSet<_>>(),\n\n [ProjectCategory::Stage, ProjectCategory::Food]\n\n .iter()\n\n .copied()\n\n .collect::<HashSet<_>>()\n\n );\n\n\n\n let conj1 = ProjectQueryConjunction {\n\n category: Some(ProjectCategory::Stage),\n\n attributes: ProjectAttributes::from_attributes(vec![ProjectAttribute::Academic])\n\n .unwrap(),\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 37, "score": 152264.13926949448 }, { "content": " pub fn possible_categories(&self) -> impl Iterator<Item = ProjectCategory> {\n\n if let Some(expected) = self.category {\n\n std::iter::once(expected)\n\n } else {\n\n ProjectCategory::enumerate()\n\n }\n\n }\n\n\n\n pub fn check_project(&self, project: &Project) -> bool {\n\n self.check_category_attributes(project.category(), project.attributes())\n\n }\n\n\n\n pub fn check_pending_project(&self, pending_project: &PendingProject) -> bool {\n\n self.check_category_attributes(pending_project.category(), pending_project.attributes())\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(transparent)]\n\npub struct ProjectQuery(\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 38, "score": 152262.93416239735 }, { "content": " LengthLimitedVec<Unbounded, Bounded<typenum::U32>, ProjectQueryConjunction>,\n\n);\n\n\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n\npub enum FromConjunctionsErrorKind {\n\n TooBigDisjunction,\n\n}\n\n\n\n#[derive(Debug, Error, Clone)]\n\n#[error(\"invalid project query\")]\n\npub struct FromConjunctionsError {\n\n kind: FromConjunctionsErrorKind,\n\n}\n\n\n\nimpl FromConjunctionsError {\n\n pub fn kind(&self) -> FromConjunctionsErrorKind {\n\n self.kind\n\n }\n\n}\n\n\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 39, "score": 152262.87962607262 }, { "content": "\n\n pub fn possible_categories(&self) -> impl Iterator<Item = ProjectCategory> {\n\n let categories: HashSet<_> = self\n\n .conjunctions()\n\n .map(|conj| conj.possible_categories())\n\n .flatten()\n\n .collect();\n\n categories.into_iter()\n\n }\n\n\n\n pub fn check_project(&self, project: &Project) -> bool {\n\n self.conjunctions().any(|conj| conj.check_project(project))\n\n }\n\n\n\n pub fn check_pending_project(&self, pending_project: &PendingProject) -> bool {\n\n self.conjunctions()\n\n .any(|conj| conj.check_pending_project(pending_project))\n\n }\n\n}\n\n\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 40, "score": 152259.0026354699 }, { "content": "\n\n pub fn attributes(&self) -> impl Iterator<Item = ProjectAttribute> + '_ {\n\n self.attributes.attributes()\n\n }\n\n\n\n fn check_category_attributes(\n\n &self,\n\n category: ProjectCategory,\n\n attributes: &ProjectAttributes,\n\n ) -> bool {\n\n if let Some(expected) = self.category {\n\n if expected != category {\n\n return false;\n\n }\n\n }\n\n\n\n self.attributes.is_subset(attributes)\n\n }\n\n\n\n #[auto_enums::auto_enum(Iterator)]\n", "file_path": "sos21-domain/src/model/project_query.rs", "rank": 41, "score": 152258.2239682385 }, { "content": "use crate::model::user::{UserId, UserKanaName, UserName};\n\n\n\nuse chrono::{DateTime, Utc};\n\nuse sos21_domain::model::project as entity;\n\nuse uuid::Uuid;\n\n\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\npub struct ProjectId(pub Uuid);\n\n\n\nimpl ProjectId {\n\n pub fn from_entity(id: entity::ProjectId) -> ProjectId {\n\n ProjectId(id.to_uuid())\n\n }\n\n\n\n pub fn into_entity(self) -> entity::ProjectId {\n\n entity::ProjectId::from_uuid(self.0)\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\n", "file_path": "sos21-use-case/src/model/project.rs", "rank": 42, "score": 149849.09841760315 }, { "content": " pub owner_kana_name: sos21_domain::model::user::UserKanaName,\n\n pub subowner_name: sos21_domain::model::user::UserName,\n\n pub subowner_kana_name: sos21_domain::model::user::UserKanaName,\n\n}\n\n\n\nimpl Project {\n\n pub fn from_entity(input: ProjectFromEntityInput) -> Self {\n\n let ProjectFromEntityInput {\n\n project,\n\n owner_name,\n\n owner_kana_name,\n\n subowner_name,\n\n subowner_kana_name,\n\n } = input;\n\n\n\n Project {\n\n id: ProjectId::from_entity(project.id()),\n\n code: project.code().to_string(),\n\n created_at: project.created_at().utc(),\n\n updated_at: project.updated_at().utc(),\n", "file_path": "sos21-use-case/src/model/project.rs", "rank": 43, "score": 149844.3214872564 }, { "content": " pub updated_at: DateTime<Utc>,\n\n pub owner_id: UserId,\n\n pub owner_name: UserName,\n\n pub owner_kana_name: UserKanaName,\n\n pub subowner_id: UserId,\n\n pub subowner_name: UserName,\n\n pub subowner_kana_name: UserKanaName,\n\n pub name: String,\n\n pub kana_name: String,\n\n pub group_name: String,\n\n pub kana_group_name: String,\n\n pub description: String,\n\n pub category: ProjectCategory,\n\n pub attributes: Vec<ProjectAttribute>,\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct ProjectFromEntityInput {\n\n pub project: entity::Project,\n\n pub owner_name: sos21_domain::model::user::UserName,\n", "file_path": "sos21-use-case/src/model/project.rs", "rank": 44, "score": 149841.45362635623 }, { "content": "pub enum ProjectCategory {\n\n General,\n\n Stage,\n\n Cooking,\n\n Food,\n\n}\n\n\n\nimpl ProjectCategory {\n\n pub fn from_entity(category: entity::ProjectCategory) -> ProjectCategory {\n\n match category {\n\n entity::ProjectCategory::General => ProjectCategory::General,\n\n entity::ProjectCategory::Stage => ProjectCategory::Stage,\n\n entity::ProjectCategory::Cooking => ProjectCategory::Cooking,\n\n entity::ProjectCategory::Food => ProjectCategory::Food,\n\n }\n\n }\n\n\n\n pub fn into_entity(self) -> entity::ProjectCategory {\n\n match self {\n\n ProjectCategory::General => entity::ProjectCategory::General,\n", "file_path": "sos21-use-case/src/model/project.rs", "rank": 45, "score": 149839.25692147156 }, { "content": " entity::ProjectAttribute::Committee => ProjectAttribute::Committee,\n\n entity::ProjectAttribute::Outdoor => ProjectAttribute::Outdoor,\n\n }\n\n }\n\n\n\n pub fn into_entity(self) -> entity::ProjectAttribute {\n\n match self {\n\n ProjectAttribute::Academic => entity::ProjectAttribute::Academic,\n\n ProjectAttribute::Artistic => entity::ProjectAttribute::Artistic,\n\n ProjectAttribute::Committee => entity::ProjectAttribute::Committee,\n\n ProjectAttribute::Outdoor => entity::ProjectAttribute::Outdoor,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\npub struct Project {\n\n pub id: ProjectId,\n\n pub code: String,\n\n pub created_at: DateTime<Utc>,\n", "file_path": "sos21-use-case/src/model/project.rs", "rank": 46, "score": 149839.22338487586 }, { "content": " ProjectCategory::Stage => entity::ProjectCategory::Stage,\n\n ProjectCategory::Cooking => entity::ProjectCategory::Cooking,\n\n ProjectCategory::Food => entity::ProjectCategory::Food,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\npub enum ProjectAttribute {\n\n Academic,\n\n Artistic,\n\n Committee,\n\n Outdoor,\n\n}\n\n\n\nimpl ProjectAttribute {\n\n pub fn from_entity(attribute: entity::ProjectAttribute) -> ProjectAttribute {\n\n match attribute {\n\n entity::ProjectAttribute::Academic => ProjectAttribute::Academic,\n\n entity::ProjectAttribute::Artistic => ProjectAttribute::Artistic,\n", "file_path": "sos21-use-case/src/model/project.rs", "rank": 47, "score": 149839.20155868452 }, { "content": " owner_id: UserId::from_entity(project.owner_id().clone()),\n\n owner_name: UserName::from_entity(owner_name),\n\n owner_kana_name: UserKanaName::from_entity(owner_kana_name),\n\n subowner_id: UserId::from_entity(project.subowner_id().clone()),\n\n subowner_name: UserName::from_entity(subowner_name),\n\n subowner_kana_name: UserKanaName::from_entity(subowner_kana_name),\n\n name: project.name().clone().into_string(),\n\n kana_name: project.kana_name().clone().into_string(),\n\n group_name: project.group_name().clone().into_string(),\n\n kana_group_name: project.kana_group_name().clone().into_string(),\n\n description: project.description().clone().into_string(),\n\n category: ProjectCategory::from_entity(project.category()),\n\n attributes: project\n\n .attributes()\n\n .attributes()\n\n .map(ProjectAttribute::from_entity)\n\n .collect(),\n\n }\n\n }\n\n}\n", "file_path": "sos21-use-case/src/model/project.rs", "rank": 48, "score": 149838.87134291802 }, { "content": "use crate::model::{\n\n project::ProjectAttributes,\n\n project_query::{ProjectQuery, ProjectQueryConjunction},\n\n};\n\n\n", "file_path": "sos21-domain/src/test/model/project_query.rs", "rank": 49, "score": 149565.44828472455 }, { "content": "use crate::model::project::{ProjectAttribute, ProjectCategory};\n\nuse crate::model::project_query::{ProjectQuery, ProjectQueryConjunction};\n\n\n\nuse sos21_domain::model::{project, project_query};\n\n\n\n#[derive(Debug, Clone)]\n\npub enum ProjectQueryError {\n\n TooBigQuery,\n\n DuplicatedAttributes,\n\n}\n\n\n\nimpl ProjectQueryError {\n\n fn from_query_error(err: project_query::FromConjunctionsError) -> Self {\n\n match err.kind() {\n\n project_query::FromConjunctionsErrorKind::TooBigDisjunction => {\n\n ProjectQueryError::TooBigQuery\n\n }\n\n }\n\n }\n\n\n\n fn from_attributes_error(_err: project::attribute::DuplicatedAttributesError) -> Self {\n\n ProjectQueryError::DuplicatedAttributes\n\n }\n\n}\n\n\n", "file_path": "sos21-use-case/src/interface/project_query.rs", "rank": 50, "score": 149420.4424117174 }, { "content": "use crate::model::project::{ProjectAttribute, ProjectCategory};\n\nuse crate::model::user::UserId;\n\n\n\nuse chrono::{DateTime, Utc};\n\nuse sos21_domain::model::pending_project as entity;\n\nuse uuid::Uuid;\n\n\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\npub struct PendingProjectId(pub Uuid);\n\n\n\nimpl PendingProjectId {\n\n pub fn from_entity(id: entity::PendingProjectId) -> Self {\n\n PendingProjectId(id.to_uuid())\n\n }\n\n\n\n pub fn into_entity(self) -> entity::PendingProjectId {\n\n entity::PendingProjectId::from_uuid(self.0)\n\n }\n\n}\n\n\n", "file_path": "sos21-use-case/src/model/pending_project.rs", "rank": 51, "score": 147182.94873374188 }, { "content": " updated_at: pending_project.updated_at().utc(),\n\n owner_id: UserId::from_entity(pending_project.owner_id().clone()),\n\n name: pending_project.name().clone().into_string(),\n\n kana_name: pending_project.kana_name().clone().into_string(),\n\n group_name: pending_project.group_name().clone().into_string(),\n\n kana_group_name: pending_project.kana_group_name().clone().into_string(),\n\n description: pending_project.description().clone().into_string(),\n\n category: ProjectCategory::from_entity(pending_project.category()),\n\n attributes: pending_project\n\n .attributes()\n\n .attributes()\n\n .map(ProjectAttribute::from_entity)\n\n .collect(),\n\n }\n\n }\n\n}\n", "file_path": "sos21-use-case/src/model/pending_project.rs", "rank": 52, "score": 147171.75237552324 }, { "content": "#[derive(Debug, Clone, PartialEq, Eq)]\n\npub struct PendingProject {\n\n pub id: PendingProjectId,\n\n pub created_at: DateTime<Utc>,\n\n pub updated_at: DateTime<Utc>,\n\n pub owner_id: UserId,\n\n pub name: String,\n\n pub kana_name: String,\n\n pub group_name: String,\n\n pub kana_group_name: String,\n\n pub description: String,\n\n pub category: ProjectCategory,\n\n pub attributes: Vec<ProjectAttribute>,\n\n}\n\n\n\nimpl PendingProject {\n\n pub fn from_entity(pending_project: entity::PendingProject) -> Self {\n\n PendingProject {\n\n id: PendingProjectId::from_entity(pending_project.id()),\n\n created_at: pending_project.created_at().utc(),\n", "file_path": "sos21-use-case/src/model/pending_project.rs", "rank": 53, "score": 147171.67310805267 }, { "content": "use crate::handler::model::project::{ProjectAttribute, ProjectCategory};\n\n\n\nuse serde::{Deserialize, Serialize};\n\nuse sos21_use_case::model::project_query as use_case;\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct ProjectQueryConjunction {\n\n pub category: Option<ProjectCategory>,\n\n pub attributes: Vec<ProjectAttribute>,\n\n}\n\n\n\nimpl ProjectQueryConjunction {\n\n pub fn from_use_case(conj: use_case::ProjectQueryConjunction) -> Self {\n\n let category = conj.category.map(ProjectCategory::from_use_case);\n\n let attributes = conj\n\n .attributes\n\n .into_iter()\n\n .map(ProjectAttribute::from_use_case)\n\n .collect();\n\n ProjectQueryConjunction {\n", "file_path": "sos21-api-server/src/handler/model/project_query.rs", "rank": 54, "score": 146950.36099811818 }, { "content": "#[serde(transparent)]\n\npub struct ProjectQuery(pub Vec<ProjectQueryConjunction>);\n\n\n\nimpl ProjectQuery {\n\n pub fn from_use_case(query: use_case::ProjectQuery) -> Self {\n\n let query = query\n\n .0\n\n .into_iter()\n\n .map(ProjectQueryConjunction::from_use_case)\n\n .collect();\n\n ProjectQuery(query)\n\n }\n\n\n\n pub fn into_use_case(self) -> use_case::ProjectQuery {\n\n let query = self\n\n .0\n\n .into_iter()\n\n .map(ProjectQueryConjunction::into_use_case)\n\n .collect();\n\n use_case::ProjectQuery(query)\n\n }\n\n}\n", "file_path": "sos21-api-server/src/handler/model/project_query.rs", "rank": 55, "score": 146946.6325884428 }, { "content": " category,\n\n attributes,\n\n }\n\n }\n\n\n\n pub fn into_use_case(self) -> use_case::ProjectQueryConjunction {\n\n let category = self.category.map(ProjectCategory::into_use_case);\n\n let attributes = self\n\n .attributes\n\n .into_iter()\n\n .map(ProjectAttribute::into_use_case)\n\n .collect();\n\n use_case::ProjectQueryConjunction {\n\n category,\n\n attributes,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n", "file_path": "sos21-api-server/src/handler/model/project_query.rs", "rank": 56, "score": 146944.50167020422 }, { "content": "pub fn new_form_with_query(author_id: UserId, query: ProjectQuery) -> Form {\n\n new_form_with_condition(\n\n author_id,\n\n FormCondition {\n\n query,\n\n includes: FormConditionProjectSet::from_projects(Vec::new()).unwrap(),\n\n excludes: FormConditionProjectSet::from_projects(Vec::new()).unwrap(),\n\n },\n\n )\n\n}\n\n\n", "file_path": "sos21-domain/src/test/model/form.rs", "rank": 57, "score": 143993.30258058585 }, { "content": "pub fn new_pending_project_id() -> PendingProjectId {\n\n PendingProjectId::from_uuid(Uuid::new_v4())\n\n}\n\n\n", "file_path": "sos21-domain/src/test/model/pending_project.rs", "rank": 59, "score": 136237.3987147163 }, { "content": "pub fn new_stage_project(owner_id: UserId) -> Project {\n\n new_project(owner_id, ProjectCategory::Stage)\n\n}\n\n\n", "file_path": "sos21-domain/src/test/model/project.rs", "rank": 60, "score": 131997.367562924 }, { "content": "pub fn new_general_project(owner_id: UserId) -> Project {\n\n new_project(owner_id, ProjectCategory::General)\n\n}\n\n\n", "file_path": "sos21-domain/src/test/model/project.rs", "rank": 61, "score": 131997.367562924 }, { "content": "pub fn new_project(owner_id: UserId, category: ProjectCategory) -> Project {\n\n new_project_with_attributes(owner_id, category, &[])\n\n}\n\n\n", "file_path": "sos21-domain/src/test/model/project.rs", "rank": 62, "score": 130067.49357434284 }, { "content": "pub fn new_form_answer(author_id: UserId, project: &Project, form: &Form) -> FormAnswer {\n\n new_form_answer_with_items(\n\n author_id,\n\n project,\n\n form,\n\n mock_form_answer_items(form.items()),\n\n )\n\n}\n", "file_path": "sos21-domain/src/test/model/form_answer.rs", "rank": 63, "score": 124015.03346618217 }, { "content": "pub fn new_general_project_with_subowner(owner_id: UserId, subowner_id: UserId) -> Project {\n\n new_project_with_subowner(owner_id, subowner_id, ProjectCategory::General)\n\n}\n\n\n", "file_path": "sos21-domain/src/test/model/project.rs", "rank": 64, "score": 123588.25449040602 }, { "content": "pub fn new_stage_project_with_subowner(owner_id: UserId, subowner_id: UserId) -> Project {\n\n new_project_with_subowner(owner_id, subowner_id, ProjectCategory::Stage)\n\n}\n", "file_path": "sos21-domain/src/test/model/project.rs", "rank": 65, "score": 123588.25449040602 }, { "content": "CREATE TABLE form_project_query_conjunctions (\n\n form_id uuid NOT NULL REFERENCES forms ON DELETE RESTRICT,\n\n category project_category,\n\n attributes integer NOT NULL\n\n);\n\n\n", "file_path": "sos21-database/migrations/20210309032212_structured_project_query.sql", "rank": 66, "score": 117092.68574765943 }, { "content": "DELETE FROM form_project_query_conjunctions\n\nWHERE form_id = $1\n\n\"#,\n\n form_id,\n\n )\n\n .execute(conn)\n\n .await\n\n .context(\"Failed to delete from form project query conjunctions\")?;\n\n\n\n Ok(())\n\n}\n", "file_path": "sos21-database/src/command/delete_form_project_query_conjunctions.rs", "rank": 67, "score": 114714.23862719187 }, { "content": "CREATE INDEX form_project_query_conjunctions_form_id_idx\n\n ON form_project_query_conjunctions ( form_id );\n", "file_path": "sos21-database/migrations/20210309032212_structured_project_query.sql", "rank": 68, "score": 113560.88494810452 }, { "content": "DELETE FROM registration_form_project_query_conjunctions\n\nWHERE registration_form_id = $1\n\n\"#,\n\n registration_form_id,\n\n )\n\n .execute(conn)\n\n .await\n\n .context(\"Failed to delete from registration form project query conjunctions\")?;\n\n\n\n Ok(())\n\n}\n", "file_path": "sos21-database/src/command/delete_registration_form_project_query_conjunctions.rs", "rank": 69, "score": 112430.49238666163 }, { "content": "ALTER TYPE file_sharing_scope ADD VALUE 'project_query';\n\nCOMMIT; -- we need to commit current transaction before we use 'project_query' enum value\n\n\n", "file_path": "sos21-database/migrations/20210615083430_add_project_query_file_sharing.sql", "rank": 70, "score": 111322.38203134136 }, { "content": "struct ObjectDataStream {\n\n summary_sender: Option<oneshot::Sender<ObjectDataSummary>>,\n\n acc_size: u64,\n\n acc_hasher: blake3::Hasher,\n\n stream: Pin<Box<dyn Stream<Item = Result<Bytes>> + Send + 'static>>,\n\n}\n\n\n\nimpl ObjectDataStream {\n\n fn new<S>(stream: S, summary_sender: Option<oneshot::Sender<ObjectDataSummary>>) -> Self\n\n where\n\n S: Stream<Item = Result<Bytes>> + Send + 'static,\n\n {\n\n ObjectDataStream {\n\n summary_sender,\n\n acc_size: 0,\n\n acc_hasher: blake3::Hasher::new(),\n\n stream: Box::pin(stream),\n\n }\n\n }\n\n}\n", "file_path": "sos21-domain/src/model/object/data.rs", "rank": 71, "score": 108671.93000760958 }, { "content": "pub fn new_project_index() -> ProjectIndex {\n\n let index = NEXT_PROJECT_INDEX.get_or_init(|| AtomicU16::new(0));\n\n let index = index.fetch_add(1, Ordering::SeqCst);\n\n ProjectIndex::from_u16(index).unwrap()\n\n}\n\n\n", "file_path": "sos21-domain/src/test/model/project.rs", "rank": 72, "score": 107115.73071066369 }, { "content": "pub fn mock_project_description() -> ProjectDescription {\n\n ProjectDescription::from_string(\"これはテスト用のモックデータです。\").unwrap()\n\n}\n\n\n", "file_path": "sos21-domain/src/test/model/project.rs", "rank": 73, "score": 107115.73071066369 }, { "content": "pub fn mock_project_name() -> ProjectName {\n\n ProjectName::from_string(\"mock プロジェクト\").unwrap()\n\n}\n\n\n", "file_path": "sos21-domain/src/test/model/project.rs", "rank": 74, "score": 107115.73071066369 }, { "content": "pub fn new_project_id() -> ProjectId {\n\n ProjectId::from_uuid(Uuid::new_v4())\n\n}\n\n\n\nstatic NEXT_PROJECT_INDEX: OnceCell<AtomicU16> = OnceCell::new();\n\n\n", "file_path": "sos21-domain/src/test/model/project.rs", "rank": 75, "score": 107115.73071066369 }, { "content": "pub fn mock_project_kana_name() -> ProjectKanaName {\n\n ProjectKanaName::from_string(\"モック プロジェクト\").unwrap()\n\n}\n\n\n", "file_path": "sos21-domain/src/test/model/project.rs", "rank": 76, "score": 104775.91905478286 }, { "content": "pub fn mock_project_group_name() -> ProjectGroupName {\n\n ProjectGroupName::from_string(\"jsys20\").unwrap()\n\n}\n\n\n", "file_path": "sos21-domain/src/test/model/project.rs", "rank": 77, "score": 104775.91905478286 }, { "content": "/// # Panics\n\n///\n\n/// This function panics when `attributes` contains duplicated elements.\n\npub fn new_project_with_attributes(\n\n owner_id: UserId,\n\n category: ProjectCategory,\n\n attributes: &[ProjectAttribute],\n\n) -> Project {\n\n Project::from_content(\n\n ProjectContent {\n\n id: new_project_id(),\n\n index: new_project_index(),\n\n created_at: DateTime::now(),\n\n updated_at: DateTime::now(),\n\n name: mock_project_name(),\n\n kana_name: mock_project_kana_name(),\n\n group_name: mock_project_group_name(),\n\n kana_group_name: mock_project_kana_group_name(),\n\n description: mock_project_description(),\n\n category,\n\n attributes: ProjectAttributes::from_attributes(attributes.iter().copied()).unwrap(),\n\n },\n\n owner_id,\n\n test_model::KNOWN_MOCK_GENERAL_USER_ID.clone(),\n\n )\n\n .unwrap()\n\n}\n\n\n", "file_path": "sos21-domain/src/test/model/project.rs", "rank": 78, "score": 104540.40557394199 }, { "content": "#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\nstruct ProjectNameString<Max> {\n\n _max: PhantomData<Max>,\n\n inner: String,\n\n}\n\n\n\nimpl<Max> Debug for ProjectNameString<Max> {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n <String as Debug>::fmt(&self.inner, f)\n\n }\n\n}\n\n\n\nimpl<Max> AsRef<str> for ProjectNameString<Max> {\n\n fn as_ref(&self) -> &str {\n\n self.as_str()\n\n }\n\n}\n\n\n\nimpl<Max> ProjectNameString<Max> {\n\n pub fn from_string(s: String) -> Result<Self, NameLengthError>\n\n where\n", "file_path": "sos21-domain/src/model/project/name.rs", "rank": 79, "score": 104540.40557394199 }, { "content": "pub fn new_project_with_subowner(\n\n owner_id: UserId,\n\n subowner_id: UserId,\n\n category: ProjectCategory,\n\n) -> Project {\n\n Project::from_content(\n\n ProjectContent {\n\n id: new_project_id(),\n\n index: new_project_index(),\n\n created_at: DateTime::now(),\n\n updated_at: DateTime::now(),\n\n name: mock_project_name(),\n\n kana_name: mock_project_kana_name(),\n\n group_name: mock_project_group_name(),\n\n kana_group_name: mock_project_kana_group_name(),\n\n description: mock_project_description(),\n\n category,\n\n attributes: ProjectAttributes::from_attributes(vec![]).unwrap(),\n\n },\n\n owner_id,\n\n subowner_id,\n\n )\n\n .unwrap()\n\n}\n\n\n", "file_path": "sos21-domain/src/test/model/project.rs", "rank": 80, "score": 104540.40557394199 }, { "content": "ALTER TABLE forms DROP COLUMN cooking_query;\n", "file_path": "sos21-database/migrations/20210309032212_structured_project_query.sql", "rank": 81, "score": 104332.12731859912 }, { "content": "ALTER TABLE forms DROP COLUMN general_query;\n", "file_path": "sos21-database/migrations/20210309032212_structured_project_query.sql", "rank": 82, "score": 104332.12731859912 }, { "content": "ALTER TABLE forms DROP COLUMN unspecified_query;\n", "file_path": "sos21-database/migrations/20210309032212_structured_project_query.sql", "rank": 83, "score": 104332.12731859912 }, { "content": "DROP FUNCTION form_query_match(bit(16), integer);\n\n\n", "file_path": "sos21-database/migrations/20210309032212_structured_project_query.sql", "rank": 84, "score": 104332.12731859912 }, { "content": "ALTER TABLE forms DROP COLUMN stage_query;\n", "file_path": "sos21-database/migrations/20210309032212_structured_project_query.sql", "rank": 85, "score": 104332.12731859912 }, { "content": "ALTER TABLE forms DROP COLUMN food_query;\n", "file_path": "sos21-database/migrations/20210309032212_structured_project_query.sql", "rank": 86, "score": 104332.12731859912 }, { "content": "pub fn list_forms_by_project<'a, E>(\n\n conn: E,\n\n project_id: Uuid,\n\n) -> BoxStream<'a, Result<ProjectFormData>>\n\nwhere\n\n E: sqlx::Executor<'a, Database = sqlx::Postgres> + 'a,\n\n{\n\n sqlx::query!(\n\n r#\"\n\nWITH project_forms AS (\n\n SELECT forms.id\n\n FROM forms\n\n LEFT OUTER JOIN form_condition_includes\n\n ON form_condition_includes.form_id = forms.id\n\n LEFT OUTER JOIN form_condition_excludes\n\n ON form_condition_excludes.form_id = forms.id\n\n WHERE (\n\n (\n\n form_condition_excludes.project_id IS NULL\n\n OR form_condition_excludes.project_id <> $1\n", "file_path": "sos21-database/src/query/list_forms_by_project.rs", "rank": 87, "score": 103877.40242268599 }, { "content": "pub fn list_projects<'a, E>(conn: E) -> BoxStream<'a, Result<ProjectWithOwners>>\n\nwhere\n\n E: sqlx::Executor<'a, Database = sqlx::Postgres> + 'a,\n\n{\n\n // TODO: Remove tedeous null forcings\n\n sqlx::query!(\n\n r#\"\n\nSELECT\n\n projects.id AS \"id!\",\n\n projects.index AS \"index!\",\n\n projects.created_at AS \"created_at!\",\n\n projects.updated_at AS \"updated_at!\",\n\n projects.name AS \"name!\",\n\n projects.kana_name AS \"kana_name!\",\n\n projects.group_name AS \"group_name!\",\n\n projects.kana_group_name AS \"kana_group_name!\",\n\n projects.description AS \"description!\",\n\n projects.category AS \"category!: ProjectCategory\",\n\n projects.attributes AS \"attributes!: ProjectAttributes\",\n\n owners.id AS \"owner_id!\",\n", "file_path": "sos21-database/src/query/list_projects.rs", "rank": 88, "score": 103370.91590275247 }, { "content": "#[derive(Debug, Clone, Copy)]\n\nenum ProjectCreationPeriodInner {\n\n Always,\n\n Never,\n\n Range {\n\n starts_at: DateTime,\n\n ends_at: DateTime,\n\n },\n\n}\n\n\n\n#[derive(Debug, Clone, Copy)]\n\npub struct ProjectCreationPeriod {\n\n inner: ProjectCreationPeriodInner,\n\n}\n\n\n\n#[derive(Debug, Error, Clone)]\n\n#[error(\"invalid project creation period\")]\n\npub struct PeriodError {\n\n _priv: (),\n\n}\n\n\n", "file_path": "sos21-domain/src/model/project_creation_period.rs", "rank": 89, "score": 103165.81230025922 }, { "content": "pub fn mock_project_kana_group_name() -> ProjectKanaGroupName {\n\n ProjectKanaGroupName::from_string(\"じょーしすにじゅう\").unwrap()\n\n}\n\n\n", "file_path": "sos21-domain/src/test/model/project.rs", "rank": 90, "score": 102550.11970927144 }, { "content": " let (tx, rx) = oneshot::channel();\n\n let receiver = ObjectDataSummaryReceiver(rx);\n\n (\n\n ObjectData(ObjectDataStream::new(stream, Some(tx))),\n\n receiver,\n\n )\n\n }\n\n\n\n pub fn into_stream(self) -> impl Stream<Item = Result<Bytes>> + Send + 'static {\n\n self.0\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::test::model as test_model;\n\n use futures::stream::TryStreamExt;\n\n\n\n #[tokio::test]\n\n async fn test_summary_size_sum() {\n", "file_path": "sos21-domain/src/model/object/data.rs", "rank": 91, "score": 102428.89329298255 }, { "content": "use std::convert::TryInto;\n\nuse std::fmt::{self, Debug};\n\nuse std::future::Future;\n\nuse std::pin::Pin;\n\nuse std::task::{Context, Poll};\n\n\n\nuse anyhow::{Context as _, Result};\n\nuse bytes::Bytes;\n\nuse futures::{\n\n channel::oneshot,\n\n future::FutureExt,\n\n stream::{Stream, StreamExt},\n\n};\n\n\n\n/// Summary of [`ObjectData`].\n\n#[derive(Debug, Clone)]\n\npub struct ObjectDataSummary {\n\n pub number_of_bytes: u64,\n\n pub blake3_digest: [u8; 32],\n\n}\n\n\n", "file_path": "sos21-domain/src/model/object/data.rs", "rank": 92, "score": 102424.47029826876 }, { "content": " let (data, _digest, _size, receiver) = test_model::new_object_data_with_summary();\n\n let mut total_size = 0;\n\n let mut stream = data.into_stream();\n\n while let Some(chunk) = stream.try_next().await.unwrap() {\n\n total_size += chunk.len();\n\n }\n\n let summary = receiver.await.unwrap();\n\n assert_eq!(summary.number_of_bytes, total_size as u64);\n\n }\n\n\n\n #[tokio::test]\n\n async fn test_summary_size_expected() {\n\n let (data, _digest, expected_size, receiver) = test_model::new_object_data_with_summary();\n\n // consume the stream\n\n data.into_stream().try_collect::<Vec<_>>().await.unwrap();\n\n let summary = receiver.await.unwrap();\n\n assert_eq!(summary.number_of_bytes, expected_size);\n\n }\n\n\n\n #[tokio::test]\n", "file_path": "sos21-domain/src/model/object/data.rs", "rank": 93, "score": 102423.85358281154 }, { "content": " async fn test_summary_digest_sum() {\n\n let (data, _digest, _size, receiver) = test_model::new_object_data_with_summary();\n\n let mut hasher = blake3::Hasher::new();\n\n let mut stream = data.into_stream();\n\n while let Some(chunk) = stream.try_next().await.unwrap() {\n\n hasher.update(&chunk);\n\n }\n\n let digest: [u8; 32] = hasher.finalize().into();\n\n let summary = receiver.await.unwrap();\n\n assert_eq!(summary.blake3_digest, digest);\n\n }\n\n\n\n #[tokio::test]\n\n async fn test_summary_digest_expected() {\n\n let (data, expected_digest, _size, receiver) = test_model::new_object_data_with_summary();\n\n // consume the stream\n\n data.into_stream().try_collect::<Vec<_>>().await.unwrap();\n\n let summary = receiver.await.unwrap();\n\n assert_eq!(summary.blake3_digest, expected_digest);\n\n }\n\n}\n", "file_path": "sos21-domain/src/model/object/data.rs", "rank": 94, "score": 102423.69364194214 }, { "content": " self.stream.size_hint()\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct ObjectData(ObjectDataStream);\n\n\n\n/// Future that recieves [`ObjectDataSummary`] after reading all the data in [`ObjectData`].\n\n#[derive(Debug)]\n\npub struct ObjectDataSummaryReceiver(oneshot::Receiver<ObjectDataSummary>);\n\n\n\nimpl Future for ObjectDataSummaryReceiver {\n\n type Output = Result<ObjectDataSummary>;\n\n\n\n fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {\n\n self.0.poll_unpin(cx).map(|result| {\n\n result.context(\"ObjectDataSummaryReceiver polled after the stream is failed\")\n\n })\n\n }\n\n}\n", "file_path": "sos21-domain/src/model/object/data.rs", "rank": 95, "score": 102419.72323482524 }, { "content": "\n\nimpl ObjectData {\n\n /// Creates `ObjectData` by wrapping a stream.\n\n pub fn from_stream<S>(stream: S) -> Self\n\n where\n\n S: Stream<Item = Result<Bytes>> + Send + 'static,\n\n {\n\n ObjectData(ObjectDataStream::new(stream, None))\n\n }\n\n\n\n /// Creates `ObjectData` by wrapping a stream and returns a `Future` that recieves\n\n /// [`ObjectDataSummary`] after reading all the object data.\n\n ///\n\n /// We don't want to have all of the `ObjectData` in memory at once, so we compute the summary\n\n /// of the content (currently size and digest) as we read the data, and return it when the\n\n /// reading is complete.\n\n pub fn from_stream_with_summary<S>(stream: S) -> (Self, ObjectDataSummaryReceiver)\n\n where\n\n S: Stream<Item = Result<Bytes>> + Send + 'static,\n\n {\n", "file_path": "sos21-domain/src/model/object/data.rs", "rank": 96, "score": 102419.68700848111 }, { "content": "\n\nimpl Debug for ObjectDataStream {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.debug_struct(\"ObjectDataStream\")\n\n .field(\"acc_size\", &self.acc_size)\n\n .field(\"acc_hasher\", &self.acc_hasher)\n\n .field(\"summary_sender\", &self.summary_sender)\n\n .finish()\n\n }\n\n}\n\n\n\nimpl Stream for ObjectDataStream {\n\n type Item = Result<Bytes>;\n\n\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {\n\n match futures::ready!(self.stream.poll_next_unpin(cx)) {\n\n Some(Ok(bytes)) => {\n\n if self.summary_sender.is_some() {\n\n let len: u64 = bytes.len().try_into()?;\n\n self.acc_size += len;\n", "file_path": "sos21-domain/src/model/object/data.rs", "rank": 97, "score": 102418.3528962003 }, { "content": " // TODO: Consider running on a thread where blocking is acceptable\n\n self.acc_hasher.update(&bytes);\n\n }\n\n Poll::Ready(Some(Ok(bytes)))\n\n }\n\n Some(Err(err)) => Poll::Ready(Some(Err(err))),\n\n None => {\n\n if let Some(sender) = self.summary_sender.take() {\n\n let summary = ObjectDataSummary {\n\n number_of_bytes: self.acc_size,\n\n blake3_digest: self.acc_hasher.finalize().into(),\n\n };\n\n let _ = sender.send(summary);\n\n }\n\n Poll::Ready(None)\n\n }\n\n }\n\n }\n\n\n\n fn size_hint(&self) -> (usize, Option<usize>) {\n", "file_path": "sos21-domain/src/model/object/data.rs", "rank": 98, "score": 102416.86466836264 }, { "content": "use crate::model::{\n\n project::{Project, ProjectAttributes, ProjectCategory, ProjectWithOwners},\n\n user::{User, UserAssignment, UserCategory, UserRole},\n\n};\n\n\n\nuse anyhow::{Context, Result};\n\nuse uuid::Uuid;\n\n\n\npub async fn find_project<'a, E>(conn: E, id: Uuid) -> Result<Option<ProjectWithOwners>>\n\nwhere\n\n E: sqlx::Executor<'a, Database = sqlx::Postgres>,\n\n{\n\n let row = sqlx::query!(\n\n r#\"\n\nSELECT\n\n projects.id,\n\n projects.index,\n\n projects.created_at,\n\n projects.updated_at,\n\n projects.name,\n", "file_path": "sos21-database/src/query/find_project.rs", "rank": 99, "score": 102377.460375202 } ]
Rust
examples/bvh_viewer/main.rs
tpltnt/bvh_anim
1f5e37061c6b67c9a0746591dec752adc114a540
#![allow(unused)] mod arcball_camera; use arcball_camera::ArcBall; use bvh_anim::{Bvh, JointData}; use gl::{self, types::*}; use glutin::{ dpi::LogicalSize, ContextBuilder, DeviceEvent, ElementState, Event, EventsLoop, KeyboardInput, MouseButton, Touch, TouchPhase, VirtualKeyCode, WindowBuilder, WindowEvent, }; use nalgebra::{Matrix4, Point2, Point3, Vector3}; use std::time::{Duration, Instant}; #[derive(Clone, Debug, Eq, Hash, PartialEq)] struct Timer { last_update: Instant, interval: Duration, } impl Timer { fn new(interval: Duration) -> Self { Timer { last_update: Instant::now(), interval, } } fn tick(&mut self, delta: &Duration) -> bool { self.interval += *delta; let curr_time = self.last_update + *delta; let next_update = self.last_update + self.interval; if next_update <= curr_time { self.last_update = Instant::now(); true } else { false } } } struct AnimationPlayer { bvh: Bvh, timer: Timer, bones: Vec<Bone>, current_frame: usize, does_loop: bool, } impl AnimationPlayer { fn new(bvh: Bvh) -> Self { let frame_time = *bvh.frame_time(); AnimationPlayer { bvh, timer: Timer::new(frame_time), bones: vec![], current_frame: 0, does_loop: false, } } fn tick(&mut self, delta: &Duration) { if self.timer.tick(delta) { self.anim_callback(); } } fn calculate_joints_fk(&mut self) { let base_mat = Matrix4::<f32>::identity(); } fn anim_callback(&mut self) {} } #[derive(Debug, PartialEq)] struct Bone { position: Point3<f32>, direction: Vector3<f32>, length: f32, shader_program: GLuint, vbo: GLint, vao: GLint, ebo: GLint, model_matrix_uniform_loc: GLint, view_matrix_uniform_loc: GLint, projection_matrix_uniform_loc: GLint, } impl Bone { fn new(position: Point3<f32>, direction: Vector3<f32>, length: f32) -> Self { macro_rules! c { ($s:literal) => { unsafe { ::std::ffi::CStr::from_bytes_with_nul_unchecked(concat!($s, "\0").as_bytes()) } }; } let vert_src = c!(r#"#version 330 layout(location = 0) in vec3 position; layout(location = 0) out vec4 f_position; layout(location = 1) out vec4 f_color; uniform mat4 model_matrix; uniform mat4 view_matrix; uniform mat4 projection_matrix; void main() { mat4 mvp = projection_matrix * view_matrix * model_matrix; f_position = mvp * vec4(position, 1.0); f_color = vec4(0.7, 0.7, 0.7, 1.0); gl_Position = f_position; } "#); let frag_src = c!(r#"#version 330 layout(location = 0) in vec4 f_position; layout(location = 1) in vec4 f_color; layout(location = 0) out vec4 target_color; void main() { target_color = f_color; } "#); let shader_program = 0; let model_matrix_uniform_loc = unsafe { gl::GetUniformLocation(shader_program, c!("model_matrix").as_ptr()) }; let view_matrix_uniform_loc = unsafe { gl::GetUniformLocation(shader_program, c!("view_matrix").as_ptr()) }; let projection_matrix_uniform_loc = unsafe { gl::GetUniformLocation(shader_program, c!("projection_matrix").as_ptr()) }; let cuboid_verts = &[ Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 0.0), Vector3::new(1.0, 1.0, 0.0), ]; let cuboid_inds = &[0u16]; let mut buffers = [0, 0]; unsafe { gl::GenBuffers(buffers.len() as _, buffers.as_mut_ptr() as *mut _); } let [vbo, ebo] = buffers; Bone { position, direction, length, shader_program, vbo, vao: 0, ebo, model_matrix_uniform_loc, view_matrix_uniform_loc, projection_matrix_uniform_loc, } } fn render(&self) { unsafe { gl::UseProgram(self.shader_program); gl::UseProgram(0); } } } impl Drop for Bone { fn drop(&mut self) { unsafe { let mut buffers = [self.vbo, self.ebo]; gl::DeleteBuffers(buffers.len() as _, buffers.as_mut_ptr() as *mut _); gl::DeleteVertexArrays(1, (&mut self.vao) as *mut _ as *mut _); gl::UseProgram(0); gl::DeleteProgram(self.shader_program); } } } fn main() { let mut events_loop = EventsLoop::new(); let win_builder = WindowBuilder::new() .with_title("Bvh Viewer") .with_dimensions(LogicalSize::new(1024.0, 768.0)); let context = ContextBuilder::new() .build_windowed(win_builder, &events_loop) .expect("Could not create OpenGL Context"); let context = unsafe { context .make_current() .expect("Could not make the OpenGL context current") }; unsafe { gl::load_with(|s| context.get_proc_address(s) as _); gl::ClearColor(0.1, 0.0, 0.4, 1.0); } let mut is_running = true; let mut prev_time = Instant::now(); let mut arcball = ArcBall::new(); let mut is_mouse_down = false; let mut prev_touch_pos = Point2::<f32>::origin(); let mut loaded_skeletons: Vec<Bvh> = vec![]; while is_running { let curr_time = Instant::now(); let dt = curr_time - prev_time; prev_time = curr_time; events_loop.poll_events(|ev| match ev { Event::DeviceEvent { ref event, .. } => match event { DeviceEvent::Key(KeyboardInput { virtual_keycode: Some(VirtualKeyCode::Escape), .. }) => { is_running = false; } DeviceEvent::MouseMotion { delta: (ref mx, ref my), } if is_mouse_down => { arcball.on_mouse_move(*mx as f32, *my as f32); } _ => {} }, Event::WindowEvent { ref event, .. } => match event { WindowEvent::CloseRequested | WindowEvent::Destroyed => { is_running = false; } WindowEvent::MouseInput { ref state, button: MouseButton::Left, .. } => match state { ElementState::Pressed => is_mouse_down = true, ElementState::Released => is_mouse_down = false, }, WindowEvent::Touch(ref t) => { match t.phase { TouchPhase::Started => { is_mouse_down = true; } TouchPhase::Ended | TouchPhase::Cancelled => is_mouse_down = true, TouchPhase::Moved => { } } } _ => {} }, _ => {} }); unsafe { gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); } context.swap_buffers().expect("Could not swap buffers"); } }
#![allow(unused)] mod arcball_camera; use arcball_camera::ArcBall; use bvh_anim::{Bvh, JointData}; use gl::{self, types::*}; use glutin::{ dpi::LogicalSize, ContextBuilder, DeviceEvent, ElementState, Event, EventsLoop, KeyboardInput, MouseButton, Touch, TouchPhase, VirtualKeyCode, WindowBuilder, WindowEvent, }; use nalgebra::{Matrix4, Point2, Point3, Vector3}; use std::time::{Duration, Instant}; #[derive(Clone, Debug, Eq, Hash, PartialEq)] struct Timer { last_update: Instant, interval: Duration, } impl Timer { fn new(interval: Duration) -> Self { Timer { last_update: Instant::now(), interval, } } fn tick(&mut self, delta: &Duration) -> bool { self.interval += *delta; let curr_time = self.last_update + *delta; let next_update = self.last_update + self.interval; if next_update <= curr_time { self.last_update = Instant::now(); true } else { false } } } struct AnimationPlayer { bvh: Bvh, timer: Timer, bones: Vec<Bone>, current_frame: usize, does_loop: bool, } impl AnimationPlayer { fn new(bvh: Bvh) -> Self { let frame_time = *bvh.frame_time(); AnimationPlayer { bvh, timer: Timer::new(frame_time), bones: vec![], current_frame: 0, does_loop: false, } } fn tick(&mut self, delta: &Duration) { if self.timer.tick(delta) { self.anim_callback(); } } fn calculate_joints_fk(&mut self) { let base_mat = Matrix4::<f32>::identity(); } fn anim_callback(&mut self) {} } #[derive(Debug, PartialEq)] struct Bone { position: Point3<f32>, direction: Vector3<f32>, length: f32, shader_program: GLuint, vbo: GLint, vao: GLint, ebo: GLint, model_matrix_uniform_loc: GLint, view_matrix_uniform_loc: GLint, projection_matrix_uniform_loc: GLint, } impl Bone { fn new(position: Point3<f32>, direction: Vector3<f32>, length: f32) -> Self { macro_rules! c { ($s:literal) => { unsafe { ::std::ffi::CStr::from_bytes_with_nul_unchecked(concat!($s, "\0").as_bytes()) } }; } let vert_src = c!(r#"#version 330 layout(location = 0) in vec3 position; layout(location = 0) out vec4 f_position; layout(location = 1) out vec4 f_color; uniform mat4 model_matrix; uniform mat4 view_matrix; uniform mat4 projection_matrix; void main() { mat4 mvp = projection_matrix * view_matrix * model_matrix; f_position = mvp * vec4(position, 1.0); f_color = vec4(0.7, 0.7, 0.7, 1.0); gl_Position = f_position; } "#); let frag_src = c!(r#"#version 330 layout(location = 0) in vec4 f_position; layout(location = 1) in vec4 f_color; layout(location = 0) out vec4 target_color; void main() { target_color = f_color; } "#); let shader_program = 0; let model_matrix_uniform_loc = unsafe { gl::GetUniformLocation(shader_program, c!("model_matrix").as_ptr()) }; let view_matrix_uniform_loc = unsafe { gl::GetUniformLocation(shader_program, c!("view_matrix").as_ptr()) }; let projection_matrix_uniform_loc = unsafe { gl::GetUniformLocation(shader_program, c!("projection_matrix").as_ptr()) }; let cuboid_verts = &[ Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 0.0), Vector3::new(1.0, 1.0, 0.0), ]; let cuboid_inds = &[0u16]; let mut buffers = [0, 0]; unsafe { gl::GenBuffers(buffers.len() as _, buffers.as_mut_ptr() as *mut _); } let [vbo, ebo] = buffers; Bone { position, direction, length, shader_program, vbo, vao: 0, ebo, model_matrix_uniform_loc, view_matrix_uniform_loc, projection_matrix_uniform_loc, } } fn render(&self) { unsafe { gl::UseProgram(self.shader_program); gl::UseProgram(0); } } } impl Drop for Bone { fn drop(&mut self) { unsafe { let mut buffers = [self.vbo, self.ebo]; gl::DeleteBuffers(buffers.len() as _, buffers.as_mut_ptr() as *mut _); gl::DeleteVertexArrays(1, (&mut self.vao) as *mut _ as *mut _); gl::UseProgram(0); gl::DeleteProgram(self.shader_program); } } } fn main() { let mut events_loop = EventsLoop::new(); let win_builder = WindowBuilder::new() .with_title("Bvh Viewer") .with_dimensions(LogicalSize::new(1024.0, 768.0)); let context = ContextBuilder::new() .build_windowed(win_builder, &events_loop) .expect("Could not create OpenGL Context"); let context = unsafe { context .make_current() .expect("Could not make the OpenGL context current") }; unsafe { gl::load_with(|s| context.get_proc_address(s) as _); gl::ClearColor(0.1, 0.0, 0.4, 1.0); } let mut is_running = true; let mut prev_time = Instant::now(); let mut arcball = ArcBall::new(); let mut is_mouse_down = false; let mut prev_touch_pos = Point2::<f32>::origin(); let mut loaded_skeletons: Vec<Bvh> = vec![]; while is_running { let curr_time = Instant::now(); let dt = curr_time - prev_time; prev_time = curr_time; events_loop.poll_events(|ev| match ev { Event::DeviceEvent { ref event, .. } => match event { DeviceEvent::Key(KeyboardInput { virtual_keycode: Some(VirtualKeyCode::Escape), .. }) => { is_running = false; } DeviceEvent::MouseMotion {
ref state, button: MouseButton::Left, .. } => match state { ElementState::Pressed => is_mouse_down = true, ElementState::Released => is_mouse_down = false, }, WindowEvent::Touch(ref t) => { match t.phase { TouchPhase::Started => { is_mouse_down = true; } TouchPhase::Ended | TouchPhase::Cancelled => is_mouse_down = true, TouchPhase::Moved => { } } } _ => {} }, _ => {} }); unsafe { gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); } context.swap_buffers().expect("Could not swap buffers"); } }
delta: (ref mx, ref my), } if is_mouse_down => { arcball.on_mouse_move(*mx as f32, *my as f32); } _ => {} }, Event::WindowEvent { ref event, .. } => match event { WindowEvent::CloseRequested | WindowEvent::Destroyed => { is_running = false; } WindowEvent::MouseInput {
random
[ { "content": "fn collect_channels(channels: &[ChannelType], num_channels: &mut usize) -> SmallVec<[Channel; 6]> {\n\n let out_channels = channels\n\n .iter()\n\n .enumerate()\n\n .map(|(motion_index, &channel_type)| Channel {\n\n channel_type,\n\n motion_index: motion_index + *num_channels,\n\n })\n\n .collect::<SmallVec<[Channel; 6]>>();\n\n\n\n *num_channels += out_channels.len();\n\n out_channels\n\n}\n\n\n\nimpl Builder {\n\n /// Start to create a new `Bvh` with a root joint.\n\n pub fn with_root_joint(\n\n name: &BStr,\n\n offset: Vector3<f32>,\n\n channels: &[ChannelType],\n", "file_path": "src/builder.rs", "rank": 4, "score": 105391.73394084805 }, { "content": "#[cfg(not(feature = \"bindings\"))]\n\nfn main() {}\n", "file_path": "build.rs", "rank": 5, "score": 103026.5960480849 }, { "content": "use nalgebra::{Matrix4, Point, Point2, Point3, Vector3};\n\n\n\n/// An ArcBall controller, as defined by Ken Shoemake.\n\n/// See http://www.talisman.org/~erlkonig/misc/shoemake92-arcball.pdf\n\n#[derive(Clone, Debug)]\n\npub struct ArcBall {\n\n mouse_pos: Point2<f32>,\n\n prev_mouse_pos: Point2<f32>,\n\n center: Point3<f32>,\n\n radius: f32,\n\n}\n\n\n\nimpl ArcBall {\n\n #[inline]\n\n pub fn new() -> Self {\n\n Default::default()\n\n }\n\n\n\n #[inline]\n\n pub fn with_radius(radius: f32) -> Self {\n", "file_path": "examples/bvh_viewer/arcball_camera.rs", "rank": 17, "score": 81329.94603336157 }, { "content": " ArcBall {\n\n mouse_pos: Point::origin(),\n\n prev_mouse_pos: Point::origin(),\n\n center: Point::origin(),\n\n radius,\n\n }\n\n }\n\n\n\n #[inline]\n\n pub fn on_mouse_move(&mut self, delta_mouse_x: f32, delta_mouse_y: f32) {\n\n self.prev_mouse_pos = self.mouse_pos;\n\n self.mouse_pos.coords.x += delta_mouse_x;\n\n self.mouse_pos.coords.y += delta_mouse_y;\n\n }\n\n\n\n pub fn on_scroll(&mut self, amount: f32) {}\n\n\n\n pub fn calculate_view_matrix(&self) -> Matrix4<f32> {\n\n unimplemented!()\n\n }\n\n}\n\n\n\nimpl Default for ArcBall {\n\n #[inline]\n\n fn default() -> Self {\n\n ArcBall::with_radius(1.0)\n\n }\n\n}\n", "file_path": "examples/bvh_viewer/arcball_camera.rs", "rank": 18, "score": 81319.83114842587 }, { "content": "#[cfg(feature = \"bindings\")]\n\nfn main() -> Result<(), error::Error> {\n\n use cbindgen::{self, Config, Language};\n\n use std::{\n\n env::{self, VarError},\n\n path::PathBuf,\n\n };\n\n\n\n let crate_dir = env::var(\"CARGO_MANIFEST_DIR\")?;\n\n let mut bindings = cbindgen::generate(crate_dir)?;\n\n\n\n push_stdio(&mut bindings.config);\n\n\n\n let mut header_path = target_dir()?;\n\n header_path.push(\"include/bvh_anim/bvh_anim.h\");\n\n\n\n bindings.write_to_file(header_path);\n\n\n\n build_and_run_ctests()?;\n\n\n\n #[inline]\n", "file_path": "build.rs", "rank": 19, "score": 78441.26360055899 }, { "content": "int main(int argc, const char* argv[]) {\n\n (void)argc;\n\n (void)argv;\n\n\n\n FILE* bvh_file = fopen(\"./data/test_mocapbank.bvh\", \"r\");\n\n if (bvh_file == NULL) {\n\n return EXIT_FAILURE;\n\n }\n\n\n\n struct bvh_BvhFile bvh;\n\n int result = bvh_read(bvh_file, &bvh);\n\n fclose(bvh_file);\n\n\n\n if (result == 0) {\n\n return EXIT_FAILURE;\n\n }\n\n\n\n printf(\"Num joints = %zu\\n\", bvh.bvh_num_joints);\n\n for (size_t i = 0; i < bvh.bvh_num_joints; i++) {\n\n const struct bvh_Joint* joint = &bvh.bvh_joints[i];\n\n\n\n char* indent = (char*)malloc(sizeof(char) * joint->joint_depth);\n\n\n\n printf(\"%sJoint name = %s\\n\", indent, joint->joint_name);\n\n printf(\"%sJoint depth = %zu\\n\", indent, joint->joint_depth);\n\n printf(\"%sJoint parent = %zu\\n\", indent, joint->joint_parent_index);\n\n\n\n printf(\n\n \"%sJoint offset %f %f %f\\n\",\n\n indent,\n\n joint->joint_offset.offset_x,\n\n joint->joint_offset.offset_y,\n\n joint->joint_offset.offset_z);\n\n\n\n for (size_t curr_channel = 0; curr_channel < joint->joint_num_channels; curr_channel++) {\n\n const struct bvh_Channel* channel = &joint->joint_channels[curr_channel];\n\n printf(\"%sChannel %zu: \", indent, channel->channel_index);\n\n switch (channel->channel_type) {\n\n case X_POSITION: printf(\"Xposition\\n\"); break;\n\n case Y_POSITION: printf(\"Yposition\\n\"); break;\n\n case Z_POSITION: printf(\"Zposition\\n\"); break;\n\n case X_ROTATION: printf(\"Xrotation\\n\"); break;\n\n case Y_ROTATION: printf(\"Yrotation\\n\"); break;\n\n case Z_ROTATION: printf(\"Zrotation\\n\"); break;\n\n }\n\n }\n\n\n\n if (joint->joint_has_end_site) {\n\n printf(\n\n \"%sEnd site %f %f %f\\n\",\n\n indent,\n\n joint->joint_end_site.offset_x,\n\n joint->joint_end_site.offset_y,\n\n joint->joint_end_site.offset_z);\n\n }\n\n\n\n free(indent);\n\n }\n\n\n\n printf(\"Frame time: %f\\n\", bvh.bvh_frame_time);\n\n printf(\"Num frames: %zu\\n\", bvh.bvh_num_frames);\n\n printf(\"Num channels: %zu\\n\", bvh.bvh_num_channels);\n\n\n\n for (size_t frame = 0; frame < bvh.bvh_num_frames; frame++) {\n\n const float* channels = bvh_get_frame(&bvh, frame);\n\n for (size_t ch = 0; ch < bvh.bvh_num_channels; ch++) {\n\n printf(\"%f\", channels[ch]);\n\n if (ch < bvh.bvh_num_channels - 1) {\n\n printf(\" \");\n\n }\n\n }\n\n printf(\"\\n\");\n\n }\n\n\n\n return (bvh_destroy(&bvh) == 0) ? EXIT_FAILURE : EXIT_SUCCESS;\n", "file_path": "ctests/parse_string.c", "rank": 20, "score": 72793.2857401927 }, { "content": "#[inline]\n\nfn fraction_seconds_to_duration(x: f64) -> Duration {\n\n Duration::from_nanos((x * NSEC_FACTOR) as u64)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 21, "score": 70459.32766143564 }, { "content": "#[inline]\n\npub fn from_bytes<B: AsRef<[u8]>>(bytes: B) -> Result<Bvh, LoadError> {\n\n Bvh::from_bytes(bytes)\n\n}\n\n\n\n/// Parse a `str` as if it were an in-memory `Bvh` file.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// # use bvh_anim::{self, from_str};\n\n/// let bvh_string = \"\n\n/// HIERARCHY\n\n/// ROOT Hips\n\n/// {\n\n/// OFFSET 0.0 0.0 0.0\n\n/// CHANNELS 3 Xposition Yposition Zposition\n\n/// End Site\n\n/// {\n\n/// OFFSET 0.0 0.0 0.0\n\n/// }\n", "file_path": "src/lib.rs", "rank": 22, "score": 70128.8903592413 }, { "content": "#[inline]\n\nfn duation_to_fractional_seconds(duration: &Duration) -> f64 {\n\n duration.subsec_nanos() as f64 / NSEC_FACTOR\n\n}\n", "file_path": "src/lib.rs", "rank": 23, "score": 68079.37759137109 }, { "content": "fn heirarchy<'a>(data: &'a [u8]) -> IResult<&'a [u8], Vec<JointData>> {\n\n let mut joints = Vec::new();\n\n let mut num_channels = 0usize;\n\n let mut joint_index = 0usize;\n\n\n\n let mut channels = |data: &'a [u8]| -> IResult<&'a [u8], SmallVec<[Channel; 6]>> {\n\n let (mut data, expected_num_channels) = do_parse!(\n\n data,\n\n tag!(b\"CHANNELS\") >> num_channels: unsigned_int >> (num_channels)\n\n )?;\n\n\n\n let mut out_channels = smallvec![];\n\n for i in 0..expected_num_channels {\n\n let (new_data, channel_ty) = single_channel(data)?;\n\n let channel = Channel::new(channel_ty, num_channels);\n\n num_channels += 1;\n\n data = new_data;\n\n }\n\n\n\n Ok((&*data, out_channels))\n", "file_path": "src/parse.rs", "rank": 24, "score": 64153.441460332964 }, { "content": "#[inline]\n\npub fn from_str(string: &str) -> Result<Bvh, LoadError> {\n\n Bvh::from_str(string)\n\n}\n\n\n\n/// A complete `bvh` file.\n\n///\n\n/// See the [module documentation](index.html#using-this-library)\n\n/// for more information.\n\n#[derive(Clone, Default, Debug, PartialEq)]\n\npub struct Bvh {\n\n /// The list of joints. If the root joint exists, it is always at\n\n /// index `0`.\n\n joints: Vec<JointData>,\n\n /// The motion values of the `Frame`.\n\n motion_values: Vec<f32>,\n\n /// The number of frames in the bvh.\n\n num_frames: usize,\n\n /// The number of `Channel`s in the bvh.\n\n num_channels: usize,\n\n /// The total time it takes to play one frame.\n", "file_path": "src/lib.rs", "rank": 25, "score": 60035.94241968177 }, { "content": "type EnumeratedLines<'a> = CachedEnumerate<ByteLines<&'a mut dyn BufReadExt>>;\n\n\n\nimpl EnumeratedLines<'_> {\n\n pub fn next_non_empty_line(&mut self) -> Option<<Self as Iterator>::Item> {\n\n let mut next = self.next();\n\n loop {\n\n match next {\n\n None => return None,\n\n Some((idx, result)) => {\n\n let string = match result {\n\n Ok(s) => s,\n\n Err(e) => return Some((idx, Err(e))),\n\n };\n\n if string.trim().is_empty() {\n\n next = self.next()\n\n } else {\n\n return Some((idx, Ok(string)));\n\n }\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n\n/// Loads the `Bvh` from the `reader`.\n", "file_path": "src/lib.rs", "rank": 26, "score": 54944.916933812616 }, { "content": "#[inline]\n\nfn ptr_to_array<'a, T>(data: *mut T, size: libc::size_t) -> &'a [T] {\n\n if data.is_null() {\n\n &[]\n\n } else {\n\n unsafe { slice::from_raw_parts(data as *const _, size) }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::ffi::{\n\n bvh_AllocCallbacks, bvh_BvhFile, bvh_ChannelType, bvh_Offset, bvh_destroy, bvh_get_frame,\n\n bvh_parse,\n\n };\n\n use libc::strcmp;\n\n use std::ffi::CStr;\n\n\n\n fn check_ffi_bvh(mut bvh_ffi: bvh_BvhFile) {\n\n assert_eq!(bvh_ffi.bvh_num_joints, 2);\n\n\n", "file_path": "src/ffi.rs", "rank": 27, "score": 52169.70859957016 }, { "content": "#[inline]\n\npub fn from_reader<R: BufReadExt>(data: R) -> Result<Bvh, LoadError> {\n\n Bvh::from_reader(data)\n\n}\n\n\n\n/// Parse a sequence of bytes as if it were an in-memory `Bvh` file.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// # use bvh_anim::{self, from_bytes};\n\n/// let bvh_string = br#\"\n\n/// HIERARCHY\n\n/// ROOT Hips\n\n/// {\n\n/// OFFSET 0.0 0.0 0.0\n\n/// CHANNELS 3 Xposition Yposition Zposition\n\n/// End Site\n\n/// {\n\n/// OFFSET 0.0 0.0 0.0\n\n/// }\n", "file_path": "src/lib.rs", "rank": 28, "score": 51033.92032830739 }, { "content": "#[derive(Debug)]\n\nstruct InvalidAllocator {\n\n _priv: (),\n\n}\n\n\n\nimpl fmt::Display for InvalidAllocator {\n\n #[inline]\n\n fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n fmtr.write_str(self.description())\n\n }\n\n}\n\n\n\nimpl Error for InvalidAllocator {\n\n #[inline]\n\n fn description(&self) -> &'static str {\n\n \"The allocator is invalid\"\n\n }\n\n}\n\n\n\nimpl From<Bvh> for bvh_BvhFile {\n\n #[inline]\n", "file_path": "src/ffi.rs", "rank": 29, "score": 48506.72301192234 }, { "content": "struct BuilderJoint {\n\n is_root: bool,\n\n name: JointName,\n\n offset: Vector3<f32>,\n\n channels: SmallVec<[Channel; 6]>,\n\n end_site_offset: Option<Vector3<f32>>,\n\n depth: usize,\n\n parent_index: Option<usize>,\n\n}\n\n\n\nimpl BuilderJoint {\n\n fn new(\n\n is_root: bool,\n\n name: &BStr,\n\n offset: Vector3<f32>,\n\n channels: SmallVec<[Channel; 6]>,\n\n depth: usize,\n\n ) -> Self {\n\n BuilderJoint {\n\n is_root,\n", "file_path": "src/builder.rs", "rank": 30, "score": 48502.4617746584 }, { "content": "#[test]\n\n#[ignore] // @TODO(burtonageo): Turn this on when the nom parser lands\n\nfn nonstandard_formatting() {\n\n const BVH_STRING: &[u8] = br#\"\n\n HIERARCHY ROOT Base {\n\n OFFSET 0.0 0.0\n\n 0.0\n\n CHANNELS 6\n\n Xposition\n\n Yposition\n\n Zposition\n\n Zrotation\n\n Xrotation\n\n Yrotation\n\n Joint End {\n\n Offset\n\n 0.0\n\n 15.0\n\n 0.0\n\n CHANNELS 3 Zrotation\n\n Xrotation Yrotation\n\n End Site { Offset 0.0 0.0 30.0 }\n", "file_path": "tests/parse.rs", "rank": 31, "score": 46671.85401291783 }, { "content": "fn motion_section(\n\ndata: &[u8],\n\nnum_channels: usize,\n\n) -> IResult<&[u8], (std::time::Duration, usize, Vec<f32>)> {\n\nlet (frame_time, num_frames) = frame_metadata(data)?;\n\nlet motion_data = Vec::with_capacity(num_channels * num_frames);\n\n\n\nfor f in 0..num_frames {\n\nlet chomped = do_parse!(data, take_while!(|ch| char::from(ch).is_ascii_whitespace()));\n\nlet (output, motion_val) = float(chomped);\n\nmotion_data.push(motion_val);\n\ndata = output;\n\n}\n\n\n\nOk((data, (frame_time, num_frames, motion_data)))\n\n}\n\n*/\n\n\n\nimpl Bvh {\n\n // @TODO: Remove panics\n", "file_path": "src/parse.rs", "rank": 32, "score": 46671.85401291783 }, { "content": "#[test]\n\nfn ffi_convert() {\n\n let bvh = bvh! {\n\n HIERARCHY\n\n ROOT Base\n\n {\n\n OFFSET 0.0 0.0 0.0\n\n CHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation\n\n JOINT Middle1\n\n {\n\n OFFSET 0.0 0.0 15.0\n\n CHANNELS 3 Zrotation Xrotation Yrotation\n\n JOINT Tip1\n\n {\n\n OFFSET 0.0 0.0 30.0\n\n CHANNELS 3 Zrotation Xrotation Yrotation\n\n End Site\n\n {\n\n OFFSET 0.0 0.0 45.0\n\n }\n\n }\n", "file_path": "tests/ffi.rs", "rank": 33, "score": 46671.85401291783 }, { "content": "#[test]\n\nfn custom_allocators() {}\n", "file_path": "tests/ffi.rs", "rank": 34, "score": 46671.85401291783 }, { "content": "#[test]\n\nfn load_success() {\n\n let reader = File::open(\"./data/test_mocapbank.bvh\")\n\n .map(BufReader::new)\n\n .unwrap();\n\n\n\n let _bvh = bvh_anim::from_reader(reader).unwrap();\n\n}\n\n\n", "file_path": "tests/parse.rs", "rank": 35, "score": 46671.85401291783 }, { "content": "#[test]\n\nfn test_write() {\n\n const BVH_STRING: &[u8] = include_bytes!(\"../data/test_simple.bvh\");\n\n\n\n let bvh = bvh! {\n\n HIERARCHY\n\n ROOT Base\n\n {\n\n OFFSET 0.0 0.0 0.0\n\n CHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation\n\n JOINT End\n\n {\n\n OFFSET 0.0 0.0 15.0\n\n CHANNELS 3 Zrotation Xrotation Yrotation\n\n End Site\n\n {\n\n OFFSET 0.0 0.0 30.0\n\n }\n\n }\n\n }\n\n MOTION\n", "file_path": "tests/write.rs", "rank": 36, "score": 46671.85401291783 }, { "content": "struct CachedEnumerate<I> {\n\n iter: Enumerate<I>,\n\n last_enumerator: Option<usize>,\n\n}\n\n\n\nimpl<I> CachedEnumerate<I> {\n\n #[inline]\n\n fn new(iter: Enumerate<I>) -> Self {\n\n CachedEnumerate {\n\n iter,\n\n last_enumerator: None,\n\n }\n\n }\n\n\n\n #[inline]\n\n fn last_enumerator(&self) -> Option<usize> {\n\n self.last_enumerator\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 37, "score": 45445.4012144017 }, { "content": "#[test]\n\nfn string_parse_small() {\n\n const BVH_BYTES: &[u8] = include_bytes!(\"../data/test_simple.bvh\");\n\n let bvh = bvh_anim::from_bytes(BVH_BYTES).unwrap();\n\n\n\n let bvh_from_macro = bvh_anim::bvh! {\n\n HIERARCHY\n\n ROOT Base\n\n {\n\n OFFSET 0.0 0.0 0.0\n\n CHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation\n\n JOINT End\n\n {\n\n OFFSET 0.0 0.0 15.0\n\n CHANNELS 3 Zrotation Xrotation Yrotation\n\n End Site\n\n {\n\n OFFSET 0.0 0.0 30.0\n\n }\n\n }\n\n }\n", "file_path": "tests/parse.rs", "rank": 38, "score": 45045.165372032236 }, { "content": "#[inline(always)]\n\nfn frames_iter_logic(\n\n num_channels: usize,\n\n num_frames: usize,\n\n curr_frame: usize,\n\n) -> Option<Range<usize>> {\n\n if num_frames == 0 || curr_frame >= num_frames {\n\n return None;\n\n }\n\n\n\n let start = curr_frame * num_channels;\n\n let end = start + num_channels;\n\n\n\n Some(Range { start, end })\n\n}\n\n\n\n/// A wrapper for a slice of motion values, so that they can be indexed by `Channel`.\n\n#[derive(PartialEq)]\n\npub struct Frame([f32]);\n\n\n\nimpl fmt::Debug for Frame {\n", "file_path": "src/lib.rs", "rank": 39, "score": 45045.165372032236 }, { "content": "#[test]\n\nfn ffi_load_from_cfile() {\n\n use bvh_anim::ffi::{bvh_BvhFile, bvh_read};\n\n use libc;\n\n use std::{ffi::CStr, ptr};\n\n\n\n let expected_bvh = bvh! {\n\n HIERARCHY\n\n ROOT Base\n\n {\n\n OFFSET 0.0 0.0 0.0\n\n CHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation\n\n JOINT End\n\n {\n\n OFFSET 0.0 0.0 15.0\n\n CHANNELS 3 Zrotation Xrotation Yrotation\n\n End Site\n\n {\n\n OFFSET 0.0 0.0 30.0\n\n }\n\n }\n", "file_path": "tests/ffi.rs", "rank": 40, "score": 45045.165372032236 }, { "content": "#[test]\n\nfn string_parse_big() {\n\n const BVH_BYTES: &[u8] = include_bytes!(\"../data/test_mocapbank.bvh\");\n\n let bvh = bvh_anim::from_bytes(BVH_BYTES).unwrap();\n\n\n\n let bvh_from_macro = bvh_anim::bvh! {\n\n HIERARCHY\n\n ROOT Hips\n\n {\n\n OFFSET 0.0000 0.0000 0.0000\n\n CHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation\n\n JOINT Chest\n\n {\n\n OFFSET -0.1728 10.2870 0.1254\n\n CHANNELS 3 Zrotation Xrotation Yrotation\n\n JOINT Chest2\n\n {\n\n OFFSET 0.3229 15.8173 -2.6440\n\n CHANNELS 3 Zrotation Xrotation Yrotation\n\n JOINT LeftCollar\n\n {\n", "file_path": "tests/parse_big.rs", "rank": 41, "score": 43593.35881295193 }, { "content": "#[test]\n\nfn test_load_write_is_identical() {\n\n const BVH_STRING: &str = include_str!(\"../data/test_simple.bvh\");\n\n let bvh = bvh_anim::from_str(BVH_STRING).unwrap();\n\n let bvh_string = WriteOptions::new()\n\n .with_indent(IndentStyle::with_spaces(4))\n\n .with_frame_time_significant_figures(9)\n\n .with_offset_significant_figures(1)\n\n .with_motion_values_significant_figures(1)\n\n .with_line_terminator(LineTerminator::native())\n\n .write_to_string(&bvh);\n\n\n\n assert_eq!(bvh_string, BVH_STRING);\n\n}\n", "file_path": "tests/write.rs", "rank": 42, "score": 43593.35881295193 }, { "content": "# bvh_anim\n\n\n\n[![Latest Version]][crates.io] [![Documentation]][docs.rs] ![License]\n\n\n\nA rust library for loading `.bvh` files containing skeletal animation data.\n\n\n\n⚠⚠**NOTE**: This library is currently alpha quality software.⚠⚠\n\n\n\n## Basic usage\n\n\n\nTo get started, add the following to your `Cargo.toml`:\n\n\n\n```toml\n\n[dependencies]\n\nbvh_anim = \"0.4\"\n\n```\n\n\n\nAnd then, you can import the library using the `use bvh_anim::*;` statement\n\nin your rust files. A small example is shown below:\n\n\n\n```rust\n\nuse bvh_anim;\n\nuse std::fs::File;\n\n\n\nlet bvh_file = File::open(\"./path/to/anim.bvh\")?;\n\nlet bvh = bvh_anim::load(BufReader::new(bvh_file))?;\n\n\n\nfor joint in bvh.joints() {\n\n println!(\"{:#?}\", joint);\n\n}\n\n\n\nprintln!(\"Frame time: {:?}\", bvh.frame_time());\n\n\n\nfor frame in bvh.frames() {\n\n println!(\"{:?}\", frame);\n\n}\n\n\n\nlet mut out_file = File::create(\"./out.bvh\");\n\nbvh.write_to(&mut out_file)?;\n\n```\n\n\n\nFor more information about the bvh file format and using this library,\n\nsee the documentation on [docs.rs](https://docs.rs/bvh_anim).\n\n\n\n## Features\n\n\n\nThis crate has a small ffi module which allows you to parse `bvh` files\n\nfrom `C` code. The `ffi` module can be enabled with the `ffi` feature,\n\nand you can read the docs for it on [`docs.rs`][docs.rs/ffi].\n\n\n\nIn addition, the `bindings` feature can be enabled to generate the `C`\n\nbindings using `cbindgen`. The bindings header is written to either\n\n`$CARGO_TARGET_DIR` if it is specified, or\n\n`$CARGO_MANIFEST_DIR/target/include/bvh_anim/bvh_anim.h` if it is\n\nnot.\n\n\n\n## Contributing\n\n\n\nThis library welcomes open source contributions, including pull requests and bug\n\nreports (including feature requests).\n\n\n\nThis library aims to be the primary `bvh` parser in the Rust ecosystem, and aims\n\nto correctly parse a wide variety of `bvh` files. If you have a file which does\n\nnot parse correctly, please report a bug. Parsing should always return an error on\n\nfailure and never panic.\n\n\n", "file_path": "Readme.md", "rank": 43, "score": 37280.24595248993 }, { "content": "## License\n\n\n\nCopyright © 2019 George Burton\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software\n\nand associated documentation files (the \"Software\"), to deal in the Software without restriction,\n\nincluding without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\nand/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,\n\nsubject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial\n\nportions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT\n\nLIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n\n[Documentation]: https://docs.rs/bvh_anim/badge.svg\n\n[Latest Version]: https://img.shields.io/crates/v/bvh_anim.svg\n\n[docs.rs]: https://docs.rs/bvh_anim\n\n[crates.io]: https://crates.io/crates/bvh_anim\n\n[License]: https://img.shields.io/crates/l/bvh_anim.svg\n\n<!--\n\nRemember to update this when a new version is published!!!\n\n-->\n", "file_path": "Readme.md", "rank": 44, "score": 37272.57917761266 }, { "content": "Copyright 2019 George Burton\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"),\n\nto deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\nand/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\nIN THE SOFTWARE.\n", "file_path": "license.md", "rank": 45, "score": 37270.328371309406 }, { "content": "This is free and unencumbered software released into the public domain.\n\n\n\nAnyone is free to copy, modify, publish, use, compile, sell, or\n\ndistribute this software, either in source code form or as a compiled\n\nbinary, for any purpose, commercial or non-commercial, and by any\n\nmeans.\n\n\n\nIn jurisdictions that recognize copyright laws, the author or authors\n\nof this software dedicate any and all copyright interest in the\n\nsoftware to the public domain. We make this dedication for the benefit\n\nof the public at large and to the detriment of our heirs and\n\nsuccessors. We intend this dedication to be an overt act of\n\nrelinquishment in perpetuity of all present and future rights to this\n\nsoftware under copyright law.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n\nIN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\nOTHER DEALINGS IN THE SOFTWARE.\n\n\n\nFor more information, please refer to <http://unlicense.org>\n", "file_path": "examples/license.md", "rank": 46, "score": 35870.80345179701 }, { "content": "#![no_main]\n\n#[macro_use] extern crate libfuzzer_sys;\n\nextern crate bvh_anim;\n\n\n\nfuzz_target!(|data: &[u8]| {\n\n let _ = bvh_anim::parse(data);\n\n});\n", "file_path": "fuzz/fuzz_targets/bvh_parse.rs", "rank": 47, "score": 26963.83976228064 }, { "content": " Option<unsafe extern \"C\" fn(size: size_t, align: size_t) -> *mut c_void>;\n\n\n\n/// Type alias for a function used to free memory.\n\n///\n\n/// Passing a `NULL` pointer value is undefined.\n\npub type bvh_FreeFunction =\n\n Option<unsafe extern \"C\" fn(ptr: *mut c_void, size: size_t, align: size_t)>;\n\n\n\n/// A struct which wraps all allocation functions together for convenience.\n\n///\n\n/// This library may make additional transient allocations outside of\n\n/// any specific allocator parameters.\n\n///\n\n/// If you don't need a custom allocator, use the `BVH_ALLOCATOR_DEFAULT`\n\n/// allocator, which will fall back to the system allocator.\n\n///\n\n/// If either of the member functions are `NULL`, then functions which use\n\n/// the allocator will unconditionally fail.\n\n#[repr(C)]\n\n#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]\n", "file_path": "src/ffi.rs", "rank": 48, "score": 24.81556259670665 }, { "content": " unsafe fn free_n<T>(&self, ptr: *mut T, n: usize) {\n\n if let Some(free_cbk) = self.free_cbk {\n\n (free_cbk)(ptr as *mut _, mem::size_of::<T>() * n, mem::align_of::<T>());\n\n }\n\n }\n\n}\n\n\n\n/// Create an allocator which uses the `std::alloc` functions.\n\nimpl Default for bvh_AllocCallbacks {\n\n #[inline]\n\n fn default() -> Self {\n\n BVH_ALLOCATOR_DEFAULT\n\n }\n\n}\n\n\n\n/// Allocation function which uses the rust allocator.\n\nunsafe extern \"C\" fn rust_alloc(size: size_t, align: size_t) -> *mut c_void {\n\n Layout::from_size_align(size, align)\n\n .map(|layout| alloc::alloc_zeroed(layout))\n\n .unwrap_or(ptr::null_mut()) as *mut _\n", "file_path": "src/ffi.rs", "rank": 49, "score": 23.829548874692442 }, { "content": "#![allow(unused)]\n\n\n\n//! Defines a `Builder` struct used to build a `Bvh` dynamically.\n\n\n\nuse bstr::BStr;\n\nuse crate::{Bvh, Channel, ChannelType, JointName};\n\nuse mint::Vector3;\n\nuse smallvec::SmallVec;\n\nuse std::{fmt, time::Duration};\n\n\n\n/// The `Builder`.\n\n#[derive(Default)]\n\npub struct Builder {\n\n _priv: (),\n\n}\n\n\n\nimpl fmt::Debug for Builder {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.write_str(\"Builder { .. }\")\n\n }\n\n}\n\n\n", "file_path": "src/builder.rs", "rank": 50, "score": 23.3175097141953 }, { "content": "/// Specify indentation style to use when writing the `Bvh` joints.\n\n///\n\n/// By default, this value is set to 1 tab.\n\n#[derive(Clone, Debug, Eq, Hash, PartialEq)]\n\npub enum IndentStyle {\n\n /// Do not indent nested joints.\n\n NoIndentation,\n\n /// Use a single tab (`'\\t'`) for indentation.\n\n Tabs,\n\n /// Use `n` spaces for indentation.\n\n Spaces(NonZeroUsize),\n\n}\n\n\n\nimpl IndentStyle {\n\n /// Create a new `IndentStyle` with `n` preceeding spaces.\n\n ///\n\n /// If `n` is `0`, then `IndentStyle::NoIndentation` is returned.\n\n #[inline]\n\n pub fn with_spaces(n: usize) -> Self {\n\n NonZeroUsize::new(n)\n", "file_path": "src/write.rs", "rank": 51, "score": 22.83678362014163 }, { "content": "#![allow(unused)]\n\n\n\n//! Contains options for `bvh` file formatting.\n\n\n\nuse bstr::{BStr, BString, B};\n\nuse crate::{duation_to_fractional_seconds, Bvh, Frame, Frames, Joint, Joints};\n\nuse mint::Vector3;\n\nuse smallvec::SmallVec;\n\nuse std::{\n\n fmt,\n\n io::{self, Write},\n\n iter, mem,\n\n num::NonZeroUsize,\n\n};\n\n\n\n/// Specify formatting options for writing a `Bvh`.\n\n#[derive(Clone, Debug, Eq, Hash, PartialEq)]\n\npub struct WriteOptions {\n\n /// Which indentation style to use for nested bones.\n\n pub indent: IndentStyle,\n", "file_path": "src/write.rs", "rank": 52, "score": 22.544675073168378 }, { "content": "/// A mutable iterator over the frames of a `Bvh`.\n\n#[derive(Debug)]\n\npub struct FramesMut<'a> {\n\n motion_values: &'a mut [f32],\n\n num_channels: usize,\n\n num_frames: usize,\n\n curr_frame: usize,\n\n}\n\n\n\nimpl FramesMut<'_> {\n\n /// Returns the number of `Frame`s left to iterate over.\n\n #[inline]\n\n pub const fn len(&self) -> usize {\n\n self.num_frames - self.curr_frame\n\n }\n\n\n\n /// Returns `true` if the number of `Frame`s left to iterate over is `0`.\n\n #[inline]\n\n pub const fn is_empty(&self) -> bool {\n\n self.len() == 0\n", "file_path": "src/lib.rs", "rank": 53, "score": 21.558310918661064 }, { "content": "/// A channel composed of a `bvh_ChannelType` and an index into the\n\n/// `bvh_BvhFile::bvh_motion_data` array to which it corresponds.\n\n#[repr(C)]\n\n#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\n\npub struct bvh_Channel {\n\n /// The type of the channel.\n\n pub channel_type: bvh_ChannelType,\n\n /// The index into the motion data array.\n\n pub channel_index: size_t,\n\n}\n\n\n\n/// A single joint in the `HIERARCHY` section of a `bvh_BvhFile`.\n\n#[repr(C)]\n\n#[derive(Clone, Copy, PartialEq)]\n\npub struct bvh_Joint {\n\n /// The name of the joint.\n\n pub joint_name: *mut c_char,\n\n /// The ordered array of channels of the `bvh_Joint`.\n\n pub joint_channels: *mut bvh_Channel,\n\n /// The length of the `joint_channels` array.\n", "file_path": "src/ffi.rs", "rank": 54, "score": 21.31256384529093 }, { "content": " fn try_from(string: &'_ BStr) -> Result<Self, Self::Error> {\n\n Bvh::from_bytes(string.as_bytes())\n\n }\n\n}\n\n\n\nimpl TryFrom<&'_ [u8]> for Bvh {\n\n type Error = LoadError;\n\n #[inline]\n\n fn try_from(bytes: &'_ [u8]) -> Result<Self, Self::Error> {\n\n Bvh::from_bytes(bytes)\n\n }\n\n}\n\n\n\n/// A `Channel` composed of a `ChannelType` and an index into the\n\n/// corresponding motion data.\n\n#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]\n\npub struct Channel {\n\n /// The type of the `Channel`.\n\n channel_type: ChannelType,\n\n /// The index into the `Frame` which corresponds to this `Channel`.\n", "file_path": "src/lib.rs", "rank": 55, "score": 20.972446589051955 }, { "content": "#[must_use]\n\npub unsafe extern \"C\" fn bvh_to_string(\n\n bvh_file: *const bvh_BvhFile,\n\n out_buffer_allocator: bvh_AllocFunction,\n\n out_buffer: *mut *mut c_char,\n\n) -> c_int {\n\n /*\n\n if bvh_file.is_null() {\n\n return 1;\n\n }\n\n \n\n let bvh = match Bvh::from_ffi(*bvh_file) {\n\n Ok(bvh) => bvh,\n\n Err(_) => return 1,\n\n };\n\n \n\n let string = bvh.to_bstring();\n\n *bvh_file = bvh.into_ffi();\n\n let out_buf_len = string.len() + 1;\n\n \n", "file_path": "src/ffi.rs", "rank": 56, "score": 20.775044763303192 }, { "content": " {\n\n assert_eq!(chan, *expected_chan);\n\n }\n\n let end_site = end_site.into().map(Into::into);\n\n assert_eq!(joint.end_site(), end_site.as_ref());\n\n }\n\n\n\n let mut joints = bvh.joints();\n\n\n\n check_joint::<[_; 3], [f32; 3], _>(\n\n joints.next().unwrap().data(),\n\n \"Base\",\n\n [0.0, 0.0, 0.0],\n\n &[\n\n ChannelType::PositionX,\n\n ChannelType::PositionY,\n\n ChannelType::PositionZ,\n\n ChannelType::RotationZ,\n\n ChannelType::RotationX,\n\n ChannelType::RotationY,\n", "file_path": "src/macros.rs", "rank": 57, "score": 20.62891857029142 }, { "content": "}\n\n\n\nimpl fmt::Debug for Joints<'_> {\n\n #[inline]\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.write_str(\"Joints { .. }\")\n\n }\n\n}\n\n\n\nimpl<'a> Joints<'a> {\n\n /// Create a `Joints` iterator over all the `joints` in a `Bvh` file.\n\n pub(crate) fn iter_root(joints: &'a [JointData] //clips: &'a AtomicRefCell<Clips>\n\n ) -> Self {\n\n Joints {\n\n joints,\n\n // clips,\n\n current_joint: 0,\n\n from_child: None,\n\n }\n\n }\n", "file_path": "src/joint.rs", "rank": 58, "score": 20.505390089569477 }, { "content": "\n\n #[inline]\n\n pub fn check_valid_motion(&self) -> bool {\n\n self.bvh.motion_values.len() == self.bvh.num_channels * self.bvh.num_frames\n\n }\n\n\n\n #[inline]\n\n fn last_joint(&mut self) -> Option<&mut JointData> {\n\n self.bvh.joints.last_mut()\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n // Needed for macros\n\n use std::time::Duration;\n\n\n\n #[test]\n\n fn macro_create() {\n\n let bvh = bvh! {\n", "file_path": "src/macros.rs", "rank": 59, "score": 20.49126695071829 }, { "content": " ///\n\n /// ```\n\n /// # use bvh_anim::ChannelType;\n\n /// let channel_type = ChannelType::RotationX;\n\n /// assert!(channel_type.is_rotation());\n\n /// ```\n\n #[inline]\n\n pub fn is_rotation(&self) -> bool {\n\n match *self {\n\n ChannelType::RotationX | ChannelType::RotationY | ChannelType::RotationZ => true,\n\n _ => false,\n\n }\n\n }\n\n\n\n /// Returns `true` if this channel corresponds to a positional\n\n /// transform, otherwise `false`.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n", "file_path": "src/lib.rs", "rank": 60, "score": 20.43454473011532 }, { "content": "}\n\n\n\nimpl From<Vector3<f32>> for bvh_Offset {\n\n #[inline]\n\n fn from(v: Vector3<f32>) -> Self {\n\n bvh_Offset {\n\n offset_x: v.x,\n\n offset_y: v.y,\n\n offset_z: v.z,\n\n }\n\n }\n\n}\n\n\n\nimpl From<bvh_Offset> for Vector3<f32> {\n\n #[inline]\n\n fn from(offset: bvh_Offset) -> Self {\n\n let crate::ffi::bvh_Offset {\n\n offset_x,\n\n offset_y,\n\n offset_z,\n", "file_path": "src/ffi.rs", "rank": 61, "score": 20.376595800355048 }, { "content": "use bstr::{BStr, BString, ByteSlice};\n\nuse crate::Channel;\n\nuse mint::Vector3;\n\nuse smallvec::SmallVec;\n\nuse std::{\n\n cmp::{Ordering, PartialEq, PartialOrd},\n\n ffi::{CStr, CString},\n\n fmt, mem,\n\n ops::{Deref, DerefMut},\n\n str,\n\n};\n\n\n\n/// Internal representation of a joint.\n\n#[derive(Clone, Debug, PartialEq)]\n\npub enum JointData {\n\n /// Root of the skeletal heirarchy.\n\n Root {\n\n /// Name of the root `Joint`.\n\n name: JointName,\n\n /// Positional offset of this `Joint` relative to the parent.\n", "file_path": "src/joint.rs", "rank": 62, "score": 20.185548724850374 }, { "content": " /// # use bvh_anim::ChannelType;\n\n /// let channel_type = ChannelType::PositionZ;\n\n /// assert!(channel_type.is_position());\n\n /// ```\n\n #[inline]\n\n pub fn is_position(&self) -> bool {\n\n !self.is_rotation()\n\n }\n\n\n\n /// Get the `Axis` about which this `Channel` transforms.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n\n /// # use bvh_anim::{Axis, ChannelType};\n\n /// let channel_type = ChannelType::PositionX;\n\n /// assert_eq!(channel_type.axis(), Axis::X);\n\n /// ```\n\n #[inline]\n\n pub fn axis(&self) -> Axis {\n", "file_path": "src/lib.rs", "rank": 63, "score": 20.177633630094594 }, { "content": "pub struct bvh_AllocCallbacks {\n\n /// The `alloc` function.\n\n pub alloc_cbk: bvh_AllocFunction,\n\n /// The `free` function.\n\n pub free_cbk: bvh_FreeFunction,\n\n}\n\n\n\n/// The default allocator, which uses the rust allocator (which is the\n\n/// system allocator by default).\n\n#[no_mangle]\n\npub static BVH_ALLOCATOR_DEFAULT: bvh_AllocCallbacks = bvh_AllocCallbacks {\n\n alloc_cbk: Some(rust_alloc as unsafe extern \"C\" fn(size: size_t, align: size_t) -> *mut c_void),\n\n free_cbk: Some(\n\n rust_free as unsafe extern \"C\" fn(ptr: *mut c_void, size: size_t, align: size_t),\n\n ),\n\n};\n\n\n\n#[allow(unused)]\n\nimpl bvh_AllocCallbacks {\n\n /// Create a new `bvh_AllocCallbacks` instance with the given allocation\n", "file_path": "src/ffi.rs", "rank": 64, "score": 20.142714157227502 }, { "content": " }\n\n\n\n #[inline]\n\n pub(crate) const fn empty() -> Self {\n\n Self::new(0, 0, 0)\n\n }\n\n}\n\n\n\nimpl fmt::Debug for JointPrivateData {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.write_str(\"JointPrivateData { .. }\")\n\n }\n\n}\n\n\n\n/// An iterator over the `Joint`s of a `Bvh` skeleton.\n\npub struct Joints<'a> {\n\n pub(crate) joints: &'a [JointData],\n\n // pub(crate) motion_values: &'a [f32],\n\n pub(crate) current_joint: usize,\n\n pub(crate) from_child: Option<usize>,\n", "file_path": "src/joint.rs", "rank": 65, "score": 19.97805607519115 }, { "content": " ///\n\n /// # Returns\n\n ///\n\n /// Returns `true` when there are still more lines available,\n\n /// `false` when all lines have been extracted.\n\n fn next_chunk<'a, 'b: 'a>(\n\n &self,\n\n bvh: &'b Bvh,\n\n chunk: &mut Vec<u8>,\n\n iter_state: &'a mut WriteOptionsIterState<'b>,\n\n ) -> bool {\n\n chunk.clear();\n\n\n\n let terminator = self.line_terminator.as_bstr().as_ref();\n\n\n\n match *iter_state {\n\n WriteOptionsIterState::WriteHierarchy { ref mut written } => {\n\n if !*written {\n\n *chunk = b\"HIERARCHY\".to_vec();\n\n chunk.extend_from_slice(self.line_terminator.as_bstr().as_ref());\n", "file_path": "src/write.rs", "rank": 66, "score": 19.941679094451167 }, { "content": "}\n\n\n\n/// Deallocation function which uses the rust allocator.\n\nunsafe extern \"C\" fn rust_free(ptr: *mut c_void, size: size_t, align: size_t) {\n\n Layout::from_size_align(size, align)\n\n .map(|layout| alloc::dealloc(ptr as *mut _, layout))\n\n .expect(&format!(\"Could not deallocate pointer {:p}\", ptr))\n\n}\n\n\n\n/// A type representing an `OFFSET` position.\n\n#[repr(C)]\n\n#[derive(Clone, Copy, Debug, Default, PartialEq)]\n\npub struct bvh_Offset {\n\n /// The x-component of the `OFFSET`.\n\n pub offset_x: c_float,\n\n /// The y-component of the `OFFSET`.\n\n pub offset_y: c_float,\n\n /// The z-component of the `OFFSET`.\n\n pub offset_z: c_float,\n\n}\n", "file_path": "src/ffi.rs", "rank": 67, "score": 19.885568605871285 }, { "content": " } = offset;\n\n [offset_x, offset_y, offset_z].into()\n\n }\n\n}\n\n\n\nimpl From<ChannelType> for bvh_ChannelType {\n\n #[inline]\n\n fn from(channel_ty: ChannelType) -> Self {\n\n match channel_ty {\n\n ChannelType::RotationX => bvh_ChannelType::X_ROTATION,\n\n ChannelType::RotationY => bvh_ChannelType::Y_ROTATION,\n\n ChannelType::RotationZ => bvh_ChannelType::Z_ROTATION,\n\n ChannelType::PositionX => bvh_ChannelType::X_POSITION,\n\n ChannelType::PositionY => bvh_ChannelType::Y_POSITION,\n\n ChannelType::PositionZ => bvh_ChannelType::Z_POSITION,\n\n }\n\n }\n\n}\n\n\n\nimpl From<bvh_ChannelType> for ChannelType {\n", "file_path": "src/ffi.rs", "rank": 68, "score": 19.740529936918627 }, { "content": " #[inline]\n\n fn deref_mut(&mut self) -> &mut Self::Target {\n\n &mut self.0\n\n }\n\n}\n\n\n\nimpl<B: AsRef<[u8]>> PartialEq<B> for JointName {\n\n #[inline]\n\n fn eq(&self, rhs: &B) -> bool {\n\n AsRef::<BStr>::as_ref(self) == rhs.as_ref()\n\n }\n\n}\n\n\n\nimpl<B: AsRef<[u8]>> PartialOrd<B> for JointName {\n\n #[inline]\n\n fn partial_cmp(&self, rhs: &B) -> Option<Ordering> {\n\n AsRef::<BStr>::as_ref(self).partial_cmp(rhs.as_ref())\n\n }\n\n}\n\n\n", "file_path": "src/joint.rs", "rank": 69, "score": 19.59491694336925 }, { "content": " #[inline]\n\n fn from(channel_ty: bvh_ChannelType) -> Self {\n\n match channel_ty {\n\n bvh_ChannelType::X_POSITION => ChannelType::PositionX,\n\n bvh_ChannelType::Y_POSITION => ChannelType::PositionY,\n\n bvh_ChannelType::Z_POSITION => ChannelType::PositionZ,\n\n bvh_ChannelType::X_ROTATION => ChannelType::RotationX,\n\n bvh_ChannelType::Y_ROTATION => ChannelType::RotationY,\n\n bvh_ChannelType::Z_ROTATION => ChannelType::RotationZ,\n\n }\n\n }\n\n}\n\n\n\nimpl From<Channel> for bvh_Channel {\n\n #[inline]\n\n fn from(ch: Channel) -> Self {\n\n bvh_Channel {\n\n channel_type: ch.channel_type().into(),\n\n channel_index: ch.motion_index().into(),\n\n }\n", "file_path": "src/ffi.rs", "rank": 70, "score": 19.433669332440413 }, { "content": " /// # OFFSET 0.0 0.0 30.0\n\n /// # }\n\n /// }\n\n /// MOTION\n\n /// // ...\n\n /// # Frames: 0\n\n /// # Frame Time: 0.0333333\n\n /// };\n\n ///\n\n /// let root = bvh.root_joint().unwrap();\n\n /// assert_eq!(root.data().offset(), &[1.2, 3.4, 5.6].into());\n\n /// ```\n\n #[inline]\n\n pub fn offset(&self) -> &Vector3<f32> {\n\n match *self {\n\n JointData::Child { ref offset, .. } | JointData::Root { ref offset, .. } => offset,\n\n }\n\n }\n\n\n\n /// Returns the `end_site` position if this `Joint` has an end site, or `None` if\n", "file_path": "src/joint.rs", "rank": 71, "score": 18.968527979823264 }, { "content": " }\n\n\n\n joint\n\n }\n\n}\n\n\n\n/// A mutable iterator over the `Joint`s of a `Bvh` skeleton.\n\n#[allow(unused)]\n\npub struct JointsMut<'a> {\n\n pub(crate) joints: &'a mut [JointData],\n\n pub(crate) current_joint: usize,\n\n pub(crate) from_child: Option<usize>,\n\n}\n\n\n\nimpl<'a> JointsMut<'a> {\n\n pub(crate) fn iter_root(joints: &'a mut [JointData] //clips: &'a AtomicRefCell<Clips>\n\n ) -> Self {\n\n JointsMut {\n\n joints,\n\n // clips,\n", "file_path": "src/joint.rs", "rank": 72, "score": 18.96142602346638 }, { "content": " motion_values_significant_figures: 2,\n\n _nonexhaustive: (),\n\n }\n\n }\n\n}\n\n\n\nimpl WriteOptions {\n\n /// Create a new `WriteOptions` with default values.\n\n #[inline]\n\n pub fn new() -> Self {\n\n Default::default()\n\n }\n\n\n\n /// Output the `Bvh` file to the `writer` with the given options.\n\n pub fn write<W: Write>(&self, bvh: &Bvh, writer: &mut W) -> io::Result<()> {\n\n let mut curr_chunk = vec![];\n\n let mut curr_bytes_written = 0usize;\n\n let mut curr_string_len = 0usize;\n\n let mut iter_state = WriteOptionsIterState::new();\n\n\n", "file_path": "src/write.rs", "rank": 73, "score": 18.90229374199194 }, { "content": "\n\nimpl fmt::Debug for bvh_Joint {\n\n #[inline]\n\n fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n let joint_name = unsafe { CStr::from_ptr(self.joint_name as *const _) };\n\n let channels = ptr_to_array(self.joint_channels, self.joint_num_channels);\n\n\n\n let has_end_site = if self.joint_has_end_site == 0 {\n\n false\n\n } else {\n\n true\n\n };\n\n\n\n let parent_index = if self.joint_parent_index == usize::max_value() {\n\n #[derive(Debug)]\n\n struct None;\n\n &None as &dyn fmt::Debug\n\n } else {\n\n &self.joint_parent_index as &dyn fmt::Debug\n\n };\n", "file_path": "src/ffi.rs", "rank": 74, "score": 18.826224697964513 }, { "content": " unsafe {\n\n let root = *bvh_ffi.bvh_joints.offset(0);\n\n\n\n let expected_name = CStr::from_bytes_with_nul(b\"Base\\0\").unwrap();\n\n assert_eq!(strcmp(root.joint_name, expected_name.as_ptr()), 0);\n\n\n\n assert_eq!(root.joint_num_channels, 6);\n\n\n\n let expected_channels = [\n\n bvh_ChannelType::X_POSITION,\n\n bvh_ChannelType::Y_POSITION,\n\n bvh_ChannelType::Z_POSITION,\n\n bvh_ChannelType::Z_ROTATION,\n\n bvh_ChannelType::X_ROTATION,\n\n bvh_ChannelType::Y_ROTATION,\n\n ];\n\n\n\n for i in 0..root.joint_num_channels {\n\n let channel = *root.joint_channels.offset(i as isize);\n\n assert_eq!(channel.channel_index, i);\n", "file_path": "src/ffi.rs", "rank": 75, "score": 18.809232905136717 }, { "content": "#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\n\npub enum Axis {\n\n /// `x` axis.\n\n X,\n\n /// `y` axis.\n\n Y,\n\n /// `z` axis.\n\n Z,\n\n}\n\n\n\nimpl Axis {\n\n /// Returns the `Vector3` which represents the axis.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// # use bvh_anim::Axis;\n\n /// assert_eq!(Axis::X.vector(), [1.0, 0.0, 0.0].into());\n\n /// assert_eq!(Axis::Y.vector(), [0.0, 1.0, 0.0].into());\n\n /// assert_eq!(Axis::Z.vector(), [0.0, 0.0, 1.0].into());\n", "file_path": "src/lib.rs", "rank": 76, "score": 18.758325985371172 }, { "content": "\n\n/// A channel type representing a degree of freedom along which a\n\n/// joint may move.\n\n#[repr(C)]\n\n#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\n\npub enum bvh_ChannelType {\n\n /// An `Xposition` channel type.\n\n X_POSITION,\n\n /// A `Yposition` channel type.\n\n Y_POSITION,\n\n /// A `Zposition` channel type.\n\n Z_POSITION,\n\n /// An `Xrotation` channel type.\n\n X_ROTATION,\n\n /// A `Yrotation` channel type.\n\n Y_ROTATION,\n\n /// A `Zrotation` channel type.\n\n Z_ROTATION,\n\n}\n\n\n", "file_path": "src/ffi.rs", "rank": 77, "score": 18.68174783954572 }, { "content": " #[inline]\n\n fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n fmt::Debug::fmt(&self.0, fmtr)\n\n }\n\n}\n\n\n\nimpl Frame {\n\n #[inline]\n\n fn from_slice<'a>(frame_motions: &'a [f32]) -> &'a Frame {\n\n unsafe { &*(frame_motions as *const [f32] as *const Frame) }\n\n }\n\n\n\n #[inline]\n\n fn from_mut_slice<'a>(frame_motions: &'a mut [f32]) -> &'a mut Frame {\n\n unsafe { &mut *(frame_motions as *mut [f32] as *mut Frame) }\n\n }\n\n\n\n /// Returns the number of motion values in the `Frame`.\n\n #[inline]\n\n pub fn len(&self) -> usize {\n", "file_path": "src/lib.rs", "rank": 78, "score": 18.64327681445261 }, { "content": " frame_time: Duration,\n\n}\n\n\n\nimpl Bvh {\n\n /// Create an empty `Bvh`.\n\n #[inline]\n\n pub fn new() -> Self {\n\n Default::default()\n\n }\n\n\n\n /// Parse a sequence of bytes as if it were an in-memory `Bvh` file.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// # use bvh_anim::{self, Bvh};\n\n /// let bvh_string = br#\"\n\n /// HIERARCHY\n\n /// ROOT Hips\n\n /// {\n", "file_path": "src/lib.rs", "rank": 79, "score": 18.49019286537508 }, { "content": " }\n\n }\n\n}\n\n\n\n/// The `MotionBuilder`.\n\npub struct MotionBuilder {\n\n joints_builder: JointsBuilder,\n\n frame_time: Duration,\n\n num_frames: usize,\n\n motion_values: Vec<f32>,\n\n}\n\n\n\nimpl fmt::Debug for MotionBuilder {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.write_str(\"MotionBuilder { .. }\")\n\n }\n\n}\n\n\n\nimpl MotionBuilder {\n\n /// Push a frame of motion values.\n", "file_path": "src/builder.rs", "rank": 80, "score": 18.413658613883804 }, { "content": " /// }\n\n /// }\n\n /// MOTION\n\n /// // ...\n\n /// # Frames: 0\n\n /// # Frame Time: 0.0333333\n\n /// };\n\n /// let mut joints = bvh.joints();\n\n /// let base = joints.next().unwrap();\n\n /// assert!(base.data().end_site().is_none());\n\n ///\n\n /// let tip = joints.next().unwrap();\n\n /// assert_eq!(tip.data().end_site(), Some([5.4, 3.2, 1.0].into()).as_ref());\n\n /// ```\n\n #[inline]\n\n pub fn end_site(&self) -> Option<&Vector3<f32>> {\n\n match *self {\n\n JointData::Child {\n\n ref end_site_offset,\n\n ..\n", "file_path": "src/joint.rs", "rank": 81, "score": 18.40815824179288 }, { "content": " name: JointName::from(name),\n\n offset,\n\n channels,\n\n end_site_offset: None,\n\n depth,\n\n parent_index: if is_root { None } else { Some(0) },\n\n }\n\n }\n\n}\n\n\n\nimpl JointsBuilder {\n\n /// Push a `Joint`.\n\n pub fn push_child(\n\n mut self,\n\n depth: usize,\n\n name: &BStr,\n\n offset: Vector3<f32>,\n\n channels: &[ChannelType],\n\n ) -> Self {\n\n let channels = collect_channels(channels, &mut self.num_channels);\n", "file_path": "src/builder.rs", "rank": 82, "score": 18.15242321499892 }, { "content": " #[inline]\n\n pub fn set_frame_time(&mut self, frame_time_secs: f64) {\n\n self.bvh\n\n .set_frame_time(fraction_seconds_to_duration(frame_time_secs));\n\n }\n\n\n\n #[inline]\n\n pub fn set_num_frames(&mut self, num_frames: usize) {\n\n self.num_frames = num_frames;\n\n self.bvh.num_channels = self.current_channel_index;\n\n self.bvh.num_frames = self.num_frames;\n\n self.bvh\n\n .motion_values\n\n .reserve(self.current_channel_index * self.num_frames);\n\n }\n\n\n\n #[inline]\n\n pub fn set_motion_values(&mut self, motion_values: Vec<f32>) {\n\n self.bvh.motion_values = motion_values;\n\n }\n", "file_path": "src/macros.rs", "rank": 83, "score": 17.92998377485219 }, { "content": " return ptr::null_mut();\n\n }\n\n\n\n if self.is_rust_allocator() {\n\n Box::into_raw(vec.into_boxed_slice()) as *mut _\n\n } else {\n\n let allocation = self.alloc_n::<T>(vec.len()) as *mut T;\n\n ptr::copy_nonoverlapping(vec.as_ptr(), allocation, vec.len());\n\n allocation\n\n }\n\n }\n\n\n\n /// Wrapper function to create a `Vec` from a raw pointer and a size.\n\n ///\n\n /// Takes ownership of the data behind `ptr` - it is a use after free\n\n /// error to use `ptr` after this.\n\n #[inline]\n\n unsafe fn alloc_to_vec<T: Copy>(&self, ptr: *mut T, n: usize) -> Vec<T> {\n\n if self.validate().is_err() || ptr.is_null() || n == 0 {\n\n return Vec::new();\n", "file_path": "src/ffi.rs", "rank": 84, "score": 17.620821459713312 }, { "content": " }\n\n}\n\n\n\n/// A string type for the `Joint` name. A `SmallVec` is used for\n\n/// better data locality.\n\npub type JointNameInner = SmallVec<[u8; mem::size_of::<String>()]>;\n\n\n\n/// Wrapper struct for the `Joint` name type.\n\n#[derive(Clone, Default, Eq, Hash, Ord)]\n\npub struct JointName(pub JointNameInner);\n\n\n\nimpl Deref for JointName {\n\n type Target = JointNameInner;\n\n #[inline]\n\n fn deref(&self) -> &Self::Target {\n\n &self.0\n\n }\n\n}\n\n\n\nimpl DerefMut for JointName {\n", "file_path": "src/joint.rs", "rank": 85, "score": 17.53432196082351 }, { "content": " ref mut current_joint,\n\n ref mut wrote_name,\n\n ref mut wrote_offset,\n\n ref mut wrote_channels,\n\n } => {\n\n if let Some(ref joint) = current_joint {\n\n let joint_data = joint.data();\n\n let mut depth = joint_data.depth();\n\n if *wrote_name {\n\n depth += 1\n\n }\n\n\n\n match (&mut *wrote_name, &mut *wrote_offset, &mut *wrote_channels) {\n\n (&mut false, _, _) => {\n\n // @TODO: Contribute `Extend` impl for `BString` to avoid the `Vec`\n\n // allocation\n\n chunk.extend(self.indent.prefix_chars(depth));\n\n if joint_data.is_root() {\n\n chunk.extend_from_slice(b\"ROOT \");\n\n } else {\n", "file_path": "src/write.rs", "rank": 86, "score": 17.513105211765186 }, { "content": " assert_eq!(channel.channel_type, expected_channels[i]);\n\n }\n\n\n\n assert_eq!(root.joint_offset, Default::default());\n\n assert_eq!(root.joint_parent_index, usize::max_value());\n\n assert_eq!(root.joint_has_end_site, 0);\n\n }\n\n\n\n unsafe {\n\n let end = *bvh_ffi.bvh_joints.offset(1);\n\n\n\n let expected_name = CStr::from_bytes_with_nul(b\"End\\0\").unwrap();\n\n assert_eq!(strcmp(end.joint_name, expected_name.as_ptr()), 0);\n\n\n\n assert_eq!(end.joint_num_channels, 3);\n\n\n\n let expected_channels = [\n\n bvh_ChannelType::Z_ROTATION,\n\n bvh_ChannelType::X_ROTATION,\n\n bvh_ChannelType::Y_ROTATION,\n", "file_path": "src/ffi.rs", "rank": 87, "score": 17.48903300315817 }, { "content": " WriteOptionsIterState::WriteFrames {\n\n ref mut current_frame,\n\n ref mut frames,\n\n } => match current_frame {\n\n None => return false,\n\n Some(frame) => {\n\n let motion_values = frame\n\n .as_slice()\n\n .iter()\n\n .map(|motion| {\n\n format!(\"{:.*}\", self.motion_values_significant_figures, motion)\n\n })\n\n .collect::<Vec<_>>()\n\n .join(\" \");\n\n *chunk = motion_values.into_bytes();\n\n chunk.extend_from_slice(terminator);\n\n *current_frame = frames.next();\n\n }\n\n },\n\n }\n\n\n\n true\n\n }\n\n}\n\n\n", "file_path": "src/write.rs", "rank": 88, "score": 17.38023969111278 }, { "content": " } => end_site_offset.as_ref(),\n\n _ => None,\n\n }\n\n }\n\n\n\n /// Returns `true` if the `Joint` has an `end_site_offset`, or `false` if it doesn't.\n\n #[inline]\n\n pub fn has_end_site(&self) -> bool {\n\n self.end_site().is_some()\n\n }\n\n\n\n /// Returns the ordered array of `Channel`s of this `JointData`.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```no_run\n\n /// # use bvh_anim::{bvh, ChannelType};\n\n /// let bvh = bvh! {\n\n /// HIERARCHY\n\n /// ROOT Hips\n", "file_path": "src/joint.rs", "rank": 89, "score": 17.3800130949508 }, { "content": " IndentStyle::Tabs\n\n }\n\n}\n\n\n\n/// Represents which line terminator style to use when writing a `Bvh` file.\n\n#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]\n\npub enum LineTerminator {\n\n /// Use Unix-style line endings (`'\\n'`).\n\n Unix,\n\n /// Use Windows-style line endings (`'\\r\\n'`).\n\n Windows,\n\n}\n\n\n\nimpl LineTerminator {\n\n /// Get the line terminator style native to the current OS:\n\n ///\n\n /// * On Windows, this returns `LineTerminator::Windows`.\n\n /// * Otherwise, this returns `LineTerminator::Unix`.\n\n #[cfg(target_os = \"windows\")]\n\n #[inline]\n", "file_path": "src/write.rs", "rank": 90, "score": 17.361353315009367 }, { "content": "}\n\n\n\nimpl ChannelType {\n\n /// Attempt to parse a bvh channel byte string into a `ChannelType`.\n\n /// Returns `Err` if the string cannot be parsed.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// # use bvh_anim::ChannelType;\n\n /// assert_eq!(\n\n /// ChannelType::from_bytes(\"Xrotation\").unwrap(),\n\n /// ChannelType::RotationX);\n\n ///\n\n /// let err = ChannelType::from_bytes(\"Hello\").unwrap_err();\n\n /// assert_eq!(err.into_inner(), \"Hello\");\n\n /// ```\n\n #[inline]\n\n pub fn from_bytes<B>(s: &B) -> Result<Self, ParseChannelError>\n\n where\n", "file_path": "src/lib.rs", "rank": 91, "score": 17.212625520097184 }, { "content": " JointData::Root {\n\n ref mut channels, ..\n\n } => {\n\n channels.push(channel);\n\n }\n\n JointData::Child {\n\n ref mut channels, ..\n\n } => {\n\n channels.push(channel);\n\n }\n\n });\n\n self.current_channel_index += 1;\n\n }\n\n\n\n pub fn push_joint_offset(&mut self, offset: mint::Vector3<f32>, is_end_site: bool) {\n\n self.last_joint().map(|joint| {\n\n joint.set_offset(offset, is_end_site);\n\n });\n\n }\n\n\n", "file_path": "src/macros.rs", "rank": 92, "score": 17.111757735617395 }, { "content": " end_site_offset: Default::default(),\n\n private: JointPrivateData::empty(),\n\n }\n\n }\n\n\n\n #[inline]\n\n pub(crate) fn set_name<S: Into<JointName>>(&mut self, new_name: S) {\n\n match *self {\n\n JointData::Root { ref mut name, .. } => *name = new_name.into(),\n\n JointData::Child { ref mut name, .. } => *name = new_name.into(),\n\n }\n\n }\n\n\n\n pub(crate) fn set_offset(&mut self, new_offset: Vector3<f32>, is_site: bool) {\n\n match *self {\n\n JointData::Root { ref mut offset, .. } => *offset = new_offset,\n\n JointData::Child {\n\n ref mut offset,\n\n ref mut end_site_offset,\n\n ..\n", "file_path": "src/joint.rs", "rank": 93, "score": 16.989704234930844 }, { "content": " let idx = self.current_index;\n\n let dpth = self.current_depth;\n\n let parent = get_parent_index(&self.bvh.joints[..], dpth);\n\n\n\n let mut joint = JointData::empty_child();\n\n joint.set_name(name);\n\n if let Some(ref mut private) = joint.private_data_mut() {\n\n private.self_index = idx;\n\n private.depth = dpth;\n\n private.parent_index = parent;\n\n };\n\n\n\n self.bvh.joints.push(joint);\n\n\n\n self.current_index += 1;\n\n }\n\n\n\n pub fn push_channel(&mut self, channel: ChannelType) {\n\n let channel = Channel::new(channel, self.current_channel_index);\n\n self.last_joint().map(|joint| match *joint {\n", "file_path": "src/macros.rs", "rank": 94, "score": 16.78928388114753 }, { "content": " };\n\n\n\n {\n\n use super::{ChannelType, JointData};\n\n use mint::Vector3;\n\n\n\n fn check_joint<V0: Into<Vector3<f32>>, V1: Into<Vector3<f32>>, O: Into<Option<V1>>>(\n\n joint: &JointData,\n\n expected_name: &str,\n\n expected_offset: V0,\n\n channels: &[ChannelType],\n\n end_site: O,\n\n ) {\n\n assert_eq!(joint.name(), expected_name);\n\n assert_eq!(*joint.offset(), expected_offset.into());\n\n for (chan, expected_chan) in joint\n\n .channels()\n\n .iter()\n\n .map(|c| c.channel_type())\n\n .zip(channels.iter())\n", "file_path": "src/macros.rs", "rank": 95, "score": 16.66796128273741 }, { "content": "\n\nimpl From<&'_ CStr> for JointName {\n\n #[inline]\n\n fn from(s: &'_ CStr) -> Self {\n\n From::from(s.to_bytes())\n\n }\n\n}\n\n\n\nimpl From<Vec<u8>> for JointName {\n\n #[inline]\n\n fn from(s: Vec<u8>) -> Self {\n\n JointName(s.into_iter().collect())\n\n }\n\n}\n\n\n\nimpl From<&'_ [u8]> for JointName {\n\n #[inline]\n\n fn from(s: &'_ [u8]) -> Self {\n\n From::from(s.to_vec())\n\n }\n", "file_path": "src/joint.rs", "rank": 96, "score": 16.453161918796486 }, { "content": "use foreign_types::ForeignType;\n\nuse libc::{c_char, c_double, c_float, c_int, c_void, size_t, strlen, uint32_t, uint8_t, FILE};\n\nuse mint::Vector3;\n\nuse pkg_version::{pkg_version_major, pkg_version_minor, pkg_version_patch};\n\nuse std::{\n\n alloc::{self, Layout},\n\n convert::TryFrom,\n\n error::Error,\n\n ffi::{CStr, CString},\n\n fmt,\n\n io::BufReader,\n\n mem,\n\n ptr::{self, NonNull},\n\n slice,\n\n};\n\n\n\n/// Type alias for a function used to allocate memory.\n\n///\n\n/// May return `NULL` to signify allocation failures.\n\npub type bvh_AllocFunction =\n", "file_path": "src/ffi.rs", "rank": 97, "score": 16.38318362557323 }, { "content": " fn from(j: JointName) -> Self {\n\n j.0\n\n }\n\n}\n\n\n\nimpl fmt::Debug for JointName {\n\n #[inline]\n\n fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n fmt::Debug::fmt(AsRef::<BStr>::as_ref(self), fmtr)\n\n }\n\n}\n\n\n\nimpl fmt::Display for JointName {\n\n #[inline]\n\n fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n fmt::Display::fmt(AsRef::<BStr>::as_ref(self), fmtr)\n\n }\n\n}\n\n\n\n/// Data private to joints.\n", "file_path": "src/joint.rs", "rank": 98, "score": 16.33335806764695 }, { "content": " current_joint: 0,\n\n from_child: None,\n\n }\n\n }\n\n}\n\n\n\nimpl<'a> Iterator for JointsMut<'a> {\n\n type Item = JointMut<'a>;\n\n #[inline]\n\n fn next(&mut self) -> Option<Self::Item> {\n\n None\n\n }\n\n}\n\n\n\nimpl fmt::Debug for JointsMut<'_> {\n\n #[inline]\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.write_str(\"JointsMut { .. }\")\n\n }\n\n}\n", "file_path": "src/joint.rs", "rank": 99, "score": 16.301173651655184 } ]
Rust
library/src/canvas.rs
feenkcom/libskia
2a9e95a65acb944fae8167abb93c91443ce71a95
use boxer::array::BoxerArray; use boxer::boxes::{ReferenceBox, ReferenceBoxPointer}; use boxer::{assert_reference_box, function}; use boxer::{ValueBox, ValueBoxPointer}; use float_cmp::ApproxEqUlps; use layer::SaveLayerRecWrapper; use skia_safe::canvas::{PointMode, SaveLayerRec}; use skia_safe::utils::shadow_utils::ShadowFlags; use skia_safe::{ scalar, BlendMode, Canvas, Color, Image, Matrix, Paint, Path, Point, Point3, RRect, Rect, TextBlob, Vector, M44, }; #[no_mangle] pub fn skia_canvas_clear(canvas_ptr: *mut ReferenceBox<Canvas>, r: u8, g: u8, b: u8, a: u8) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.clear(Color::from_argb(a, r, g, b)); }); } #[no_mangle] pub fn skia_canvas_draw_color( canvas_ptr: *mut ReferenceBox<Canvas>, r: u8, g: u8, b: u8, a: u8, blend_mode: BlendMode, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.draw_color(Color::from_argb(a, r, g, b), blend_mode); }); } #[no_mangle] pub fn skia_canvas_draw_paint( canvas_ptr: *mut ReferenceBox<Canvas>, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { canvas.draw_paint(paint); }); }); } #[no_mangle] pub fn skia_canvas_draw_points( canvas_ptr: *mut ReferenceBox<Canvas>, point_mode: PointMode, points_ptr: *mut ValueBox<BoxerArray<Point>>, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { points_ptr.with_not_null(|points| { canvas.draw_points(point_mode, points.to_slice(), paint); }) }); }); } #[no_mangle] pub fn skia_canvas_draw_point( canvas_ptr: *mut ReferenceBox<Canvas>, x: scalar, y: scalar, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { canvas.draw_point(Point::new(x, y), paint); }); }); } #[no_mangle] pub fn skia_canvas_draw_line( canvas_ptr: *mut ReferenceBox<Canvas>, from_x: scalar, from_y: scalar, to_x: scalar, to_y: scalar, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { canvas.draw_line(Point::new(from_x, from_y), Point::new(to_x, to_y), paint); }); }); } #[no_mangle] pub fn skia_canvas_draw_rectangle( canvas_ptr: *mut ReferenceBox<Canvas>, left: scalar, top: scalar, right: scalar, bottom: scalar, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { canvas.draw_rect(Rect::new(left, top, right, bottom), paint); }); }); } #[no_mangle] pub fn skia_canvas_draw_oval( canvas_ptr: *mut ReferenceBox<Canvas>, left: scalar, top: scalar, right: scalar, bottom: scalar, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { canvas.draw_oval(Rect::new(left, top, right, bottom), paint); }); }); } #[no_mangle] pub fn skia_canvas_draw_circle( canvas_ptr: *mut ReferenceBox<Canvas>, center_x: scalar, center_y: scalar, radius: scalar, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { canvas.draw_circle(Point::new(center_x, center_y), radius, paint); }); }); } #[no_mangle] pub fn skia_canvas_draw_rrect( canvas_ptr: *mut ReferenceBox<Canvas>, rrect_ptr: *mut ValueBox<RRect>, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { rrect_ptr.with_not_null(|rrect| { paint_ptr.with_not_null(|paint| { canvas.draw_rrect(rrect, paint); }); }); }); } #[no_mangle] pub fn skia_canvas_draw_rounded_rectangle( canvas_ptr: *mut ReferenceBox<Canvas>, left: scalar, top: scalar, right: scalar, bottom: scalar, r_top_left: scalar, r_top_right: scalar, r_bottom_right: scalar, r_bottom_left: scalar, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { if r_top_left.approx_eq_ulps(&r_top_right, 2) && r_top_right.approx_eq_ulps(&r_bottom_right, 2) && r_bottom_right.approx_eq_ulps(&r_bottom_left, 2) && r_bottom_left.approx_eq_ulps(&r_top_left, 2) { canvas.draw_round_rect( Rect::new(left, top, right, bottom), r_top_right, r_top_right, paint, ); } else { canvas.draw_rrect( RRect::new_rect_radii( Rect::new(left, top, right, bottom), &[ Vector::new(r_top_left, r_top_left), Vector::new(r_top_right, r_top_right), Vector::new(r_bottom_right, r_bottom_right), Vector::new(r_bottom_left, r_bottom_left), ], ), paint, ); }; }); }); } #[no_mangle] pub fn skia_canvas_draw_path( canvas_ptr: *mut ReferenceBox<Canvas>, path_ptr: *mut ValueBox<Path>, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { path_ptr.with_not_null(|path| { canvas.draw_path(path, paint); }) }); }); } #[no_mangle] pub fn skia_canvas_draw_text_blob( canvas_ptr: *mut ReferenceBox<Canvas>, text_blob_ptr: *mut ValueBox<TextBlob>, x: scalar, y: scalar, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { text_blob_ptr.with_not_null(|text_blob| { canvas.draw_text_blob(text_blob, Point::new(x, y), paint); }) }); }); } #[no_mangle] pub fn skia_canvas_draw_shadow( canvas_ptr: *mut ReferenceBox<Canvas>, path_ptr: *mut ValueBox<Path>, z_plane_ptr: *mut ValueBox<Point3>, light_pos_ptr: *mut ValueBox<Point3>, light_radius: scalar, ambient_color_ptr: *mut ValueBox<Color>, spot_color_ptr: *mut ValueBox<Color>, _bit_flags: u32, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { path_ptr.with_not_null(|path| { z_plane_ptr.with_not_null_value(|z_plane| { light_pos_ptr.with_not_null_value(|light_pos| { ambient_color_ptr.with_not_null_value(|ambient_color| { spot_color_ptr.with_not_null_value(|spot_color| { canvas.draw_shadow( path, z_plane, light_pos, light_radius, ambient_color, spot_color, ShadowFlags::ALL, /*from_bits_truncate(bit_flags)*/ ); }) }) }) }) }) }) } #[no_mangle] pub fn skia_canvas_draw_image( canvas_ptr: *mut ReferenceBox<Canvas>, image_ptr: *mut ValueBox<Image>, x: scalar, y: scalar, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { image_ptr.with_not_null(|image| { if paint_ptr.is_valid() { paint_ptr.with_not_null(|paint| { canvas.draw_image(image, Point::new(x, y), Some(paint)); }) } else { canvas.draw_image(image, Point::new(x, y), None); } }); }); } #[no_mangle] pub fn skia_canvas_translate(canvas_ptr: *mut ReferenceBox<Canvas>, x: scalar, y: scalar) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.translate(Vector::new(x, y)); }); } #[no_mangle] pub fn skia_canvas_scale(canvas_ptr: *mut ReferenceBox<Canvas>, sx: scalar, sy: scalar) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.scale((sx, sy)); }); } #[no_mangle] pub fn skia_canvas_rotate( canvas_ptr: *mut ReferenceBox<Canvas>, degrees: scalar, x: scalar, y: scalar, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.rotate(degrees, Some(Point::new(x, y))); }); } #[no_mangle] pub fn skia_canvas_skew(canvas_ptr: *mut ReferenceBox<Canvas>, sx: scalar, sy: scalar) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.skew((sx, sy)); }); } #[no_mangle] pub fn skia_canvas_concat_matrix( canvas_ptr: *mut ReferenceBox<Canvas>, matrix_ptr: *mut ValueBox<Matrix>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { matrix_ptr.with_not_null(|matrix| { canvas.concat(matrix); }) }); } #[no_mangle] pub fn skia_canvas_set_matrix( canvas_ptr: *mut ReferenceBox<Canvas>, matrix_ptr: *mut ValueBox<Matrix>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { matrix_ptr.with_not_null(|matrix| { canvas.set_matrix(&M44::from(matrix as &Matrix)); }) }); } #[no_mangle] pub fn skia_canvas_get_matrix( canvas_ptr: *mut ReferenceBox<Canvas>, matrix_ptr: *mut ValueBox<Matrix>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { matrix_ptr.with_not_null(|matrix| { let m = canvas.local_to_device_as_3x3(); let mut buffer: [scalar; 9] = [0.0; 9]; m.get_9(&mut buffer); matrix.set_9(&buffer); }) }); } #[no_mangle] pub fn skia_canvas_reset_matrix(canvas_ptr: *mut ReferenceBox<Canvas>) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.reset_matrix(); }) } #[no_mangle] #[deprecated(since = "0.38.0", note = "Replace usage with DirectContext::flush()")] pub fn skia_canvas_flush(_canvas_ptr: *mut ReferenceBox<Canvas>) {} #[no_mangle] pub fn skia_canvas_save(canvas_ptr: *mut ReferenceBox<Canvas>) -> usize { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null_return(0, |canvas| canvas.save()) } #[no_mangle] pub fn skia_canvas_save_count(canvas_ptr: *mut ReferenceBox<Canvas>) -> usize { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null_return(0, |canvas| canvas.save_count()) } #[no_mangle] pub fn skia_canvas_restore(canvas_ptr: *mut ReferenceBox<Canvas>) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.restore(); }) } #[no_mangle] pub fn skia_canvas_restore_to_count(canvas_ptr: *mut ReferenceBox<Canvas>, count: usize) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.restore_to_count(count); }) } #[no_mangle] pub fn skia_canvas_save_layer( canvas_ptr: *mut ReferenceBox<Canvas>, _save_layer_ptr: *mut ValueBox<SaveLayerRecWrapper>, ) -> usize { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null_return(0, |canvas| { _save_layer_ptr.with_not_null_return(0, |save_rec| { let mut rec: SaveLayerRec = SaveLayerRec::default(); if save_rec.bounds.is_some() { rec = rec.bounds(save_rec.bounds.as_ref().unwrap()) }; if save_rec.paint.is_some() { rec = rec.paint(save_rec.paint.as_ref().unwrap()) }; canvas.save_layer(&rec) }) }) } #[no_mangle] pub fn skia_canvas_drop(_ptr: &mut *mut ReferenceBox<Canvas>) { (*_ptr).drop(); *_ptr = std::ptr::null_mut(); }
use boxer::array::BoxerArray; use boxer::boxes::{ReferenceBox, ReferenceBoxPointer}; use boxer::{assert_reference_box, function}; use boxer::{ValueBox, ValueBoxPointer}; use float_cmp::ApproxEqUlps; use layer::SaveLayerRecWrapper; use skia_safe::canvas::{PointMode, SaveLayerRec}; use skia_safe::utils::shadow_utils::ShadowFlags; use skia_safe::{ scalar, BlendMode, Canvas, Color, Image, Matrix, Paint, Path, Point, Point3, RRect, Rect, TextBlob, Vector, M44, }; #[no_mangle] pub fn skia_canvas_clear(canvas_ptr: *mut ReferenceBox<Canvas>, r: u8, g: u8, b: u8, a: u8) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.clear(Color::from_argb(a, r, g, b)); }); } #[no_mangle] pub fn skia_canvas_draw_color( canvas_ptr: *mut ReferenceBox<Canvas>, r: u8, g: u8, b: u8, a: u8, blend_mode: BlendMode, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.draw_color(Color::from_argb(a, r, g, b), blend_mode); }); } #[no_mangle] pub fn skia_canvas_draw_paint( canvas_ptr: *mut ReferenceBox<Canvas>, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { canvas.draw_paint(paint); }); }); } #[no_mangle] pub fn skia_canvas_draw_points( canvas_ptr: *mut ReferenceBox<Canvas>, point_mode: PointMode, points_ptr: *mut ValueBox<BoxerArray<Point>>, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { points_ptr.with_not_null(|points| { canvas.draw_points(point_mode, points.to_slice(), paint); }) }); }); } #[no_mangle] pub fn skia_canvas_draw_point( canvas_ptr: *mut ReferenceBox<Canvas>, x: scalar, y: scalar, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { canvas.draw_point(Point::new(x, y), paint); }); }); } #[no_mangle] pub fn skia_canvas_draw_line( canvas_ptr: *mut ReferenceBox<Canvas>, from_x: scalar, from_y: scalar, to_x: scalar, to_y: scalar, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { canvas.draw_line(Point::new(from_x, from_y), Point::new(to_x, to_y), paint); }); }); } #[no_mangle] pub fn skia_canvas_draw_rectangle( canvas_ptr: *mut ReferenceBox<Canvas>, left: scalar, top: scalar, right: scalar, bottom: scalar, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { canvas.draw_rect(Rect::new(left, top, right, bottom), paint); }); }); } #[no_mangle] pub fn skia_canvas_draw_oval( canvas_ptr: *mut ReferenceBox<Canvas>, left: scalar, top: scalar, right: scalar, bottom: scalar, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { canvas.draw_oval(Rect::new(left, top, right, bottom), paint); }); }); } #[no_mangle] pub fn skia_canvas_draw_circle( canvas_ptr: *mut ReferenceBox<Canvas>, center_x: scalar, center_y: scalar, radius: scalar, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(can
#[no_mangle] pub fn skia_canvas_draw_rrect( canvas_ptr: *mut ReferenceBox<Canvas>, rrect_ptr: *mut ValueBox<RRect>, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { rrect_ptr.with_not_null(|rrect| { paint_ptr.with_not_null(|paint| { canvas.draw_rrect(rrect, paint); }); }); }); } #[no_mangle] pub fn skia_canvas_draw_rounded_rectangle( canvas_ptr: *mut ReferenceBox<Canvas>, left: scalar, top: scalar, right: scalar, bottom: scalar, r_top_left: scalar, r_top_right: scalar, r_bottom_right: scalar, r_bottom_left: scalar, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { if r_top_left.approx_eq_ulps(&r_top_right, 2) && r_top_right.approx_eq_ulps(&r_bottom_right, 2) && r_bottom_right.approx_eq_ulps(&r_bottom_left, 2) && r_bottom_left.approx_eq_ulps(&r_top_left, 2) { canvas.draw_round_rect( Rect::new(left, top, right, bottom), r_top_right, r_top_right, paint, ); } else { canvas.draw_rrect( RRect::new_rect_radii( Rect::new(left, top, right, bottom), &[ Vector::new(r_top_left, r_top_left), Vector::new(r_top_right, r_top_right), Vector::new(r_bottom_right, r_bottom_right), Vector::new(r_bottom_left, r_bottom_left), ], ), paint, ); }; }); }); } #[no_mangle] pub fn skia_canvas_draw_path( canvas_ptr: *mut ReferenceBox<Canvas>, path_ptr: *mut ValueBox<Path>, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { path_ptr.with_not_null(|path| { canvas.draw_path(path, paint); }) }); }); } #[no_mangle] pub fn skia_canvas_draw_text_blob( canvas_ptr: *mut ReferenceBox<Canvas>, text_blob_ptr: *mut ValueBox<TextBlob>, x: scalar, y: scalar, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { text_blob_ptr.with_not_null(|text_blob| { canvas.draw_text_blob(text_blob, Point::new(x, y), paint); }) }); }); } #[no_mangle] pub fn skia_canvas_draw_shadow( canvas_ptr: *mut ReferenceBox<Canvas>, path_ptr: *mut ValueBox<Path>, z_plane_ptr: *mut ValueBox<Point3>, light_pos_ptr: *mut ValueBox<Point3>, light_radius: scalar, ambient_color_ptr: *mut ValueBox<Color>, spot_color_ptr: *mut ValueBox<Color>, _bit_flags: u32, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { path_ptr.with_not_null(|path| { z_plane_ptr.with_not_null_value(|z_plane| { light_pos_ptr.with_not_null_value(|light_pos| { ambient_color_ptr.with_not_null_value(|ambient_color| { spot_color_ptr.with_not_null_value(|spot_color| { canvas.draw_shadow( path, z_plane, light_pos, light_radius, ambient_color, spot_color, ShadowFlags::ALL, /*from_bits_truncate(bit_flags)*/ ); }) }) }) }) }) }) } #[no_mangle] pub fn skia_canvas_draw_image( canvas_ptr: *mut ReferenceBox<Canvas>, image_ptr: *mut ValueBox<Image>, x: scalar, y: scalar, paint_ptr: *mut ValueBox<Paint>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { image_ptr.with_not_null(|image| { if paint_ptr.is_valid() { paint_ptr.with_not_null(|paint| { canvas.draw_image(image, Point::new(x, y), Some(paint)); }) } else { canvas.draw_image(image, Point::new(x, y), None); } }); }); } #[no_mangle] pub fn skia_canvas_translate(canvas_ptr: *mut ReferenceBox<Canvas>, x: scalar, y: scalar) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.translate(Vector::new(x, y)); }); } #[no_mangle] pub fn skia_canvas_scale(canvas_ptr: *mut ReferenceBox<Canvas>, sx: scalar, sy: scalar) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.scale((sx, sy)); }); } #[no_mangle] pub fn skia_canvas_rotate( canvas_ptr: *mut ReferenceBox<Canvas>, degrees: scalar, x: scalar, y: scalar, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.rotate(degrees, Some(Point::new(x, y))); }); } #[no_mangle] pub fn skia_canvas_skew(canvas_ptr: *mut ReferenceBox<Canvas>, sx: scalar, sy: scalar) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.skew((sx, sy)); }); } #[no_mangle] pub fn skia_canvas_concat_matrix( canvas_ptr: *mut ReferenceBox<Canvas>, matrix_ptr: *mut ValueBox<Matrix>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { matrix_ptr.with_not_null(|matrix| { canvas.concat(matrix); }) }); } #[no_mangle] pub fn skia_canvas_set_matrix( canvas_ptr: *mut ReferenceBox<Canvas>, matrix_ptr: *mut ValueBox<Matrix>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { matrix_ptr.with_not_null(|matrix| { canvas.set_matrix(&M44::from(matrix as &Matrix)); }) }); } #[no_mangle] pub fn skia_canvas_get_matrix( canvas_ptr: *mut ReferenceBox<Canvas>, matrix_ptr: *mut ValueBox<Matrix>, ) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { matrix_ptr.with_not_null(|matrix| { let m = canvas.local_to_device_as_3x3(); let mut buffer: [scalar; 9] = [0.0; 9]; m.get_9(&mut buffer); matrix.set_9(&buffer); }) }); } #[no_mangle] pub fn skia_canvas_reset_matrix(canvas_ptr: *mut ReferenceBox<Canvas>) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.reset_matrix(); }) } #[no_mangle] #[deprecated(since = "0.38.0", note = "Replace usage with DirectContext::flush()")] pub fn skia_canvas_flush(_canvas_ptr: *mut ReferenceBox<Canvas>) {} #[no_mangle] pub fn skia_canvas_save(canvas_ptr: *mut ReferenceBox<Canvas>) -> usize { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null_return(0, |canvas| canvas.save()) } #[no_mangle] pub fn skia_canvas_save_count(canvas_ptr: *mut ReferenceBox<Canvas>) -> usize { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null_return(0, |canvas| canvas.save_count()) } #[no_mangle] pub fn skia_canvas_restore(canvas_ptr: *mut ReferenceBox<Canvas>) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.restore(); }) } #[no_mangle] pub fn skia_canvas_restore_to_count(canvas_ptr: *mut ReferenceBox<Canvas>, count: usize) { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { canvas.restore_to_count(count); }) } #[no_mangle] pub fn skia_canvas_save_layer( canvas_ptr: *mut ReferenceBox<Canvas>, _save_layer_ptr: *mut ValueBox<SaveLayerRecWrapper>, ) -> usize { assert_reference_box(canvas_ptr, function!()); canvas_ptr.with_not_null_return(0, |canvas| { _save_layer_ptr.with_not_null_return(0, |save_rec| { let mut rec: SaveLayerRec = SaveLayerRec::default(); if save_rec.bounds.is_some() { rec = rec.bounds(save_rec.bounds.as_ref().unwrap()) }; if save_rec.paint.is_some() { rec = rec.paint(save_rec.paint.as_ref().unwrap()) }; canvas.save_layer(&rec) }) }) } #[no_mangle] pub fn skia_canvas_drop(_ptr: &mut *mut ReferenceBox<Canvas>) { (*_ptr).drop(); *_ptr = std::ptr::null_mut(); }
vas_ptr, function!()); canvas_ptr.with_not_null(|canvas| { paint_ptr.with_not_null(|paint| { canvas.draw_circle(Point::new(center_x, center_y), radius, paint); }); }); }
function_block-function_prefixed
[ { "content": "#[no_mangle]\n\npub fn skia_paint_set_rgba(paint_ptr: *mut ValueBox<Paint>, r: u8, g: u8, b: u8, a: u8) {\n\n paint_ptr.with_not_null(|paint| {\n\n paint.set_argb(a, r, g, b);\n\n });\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 0, "score": 443120.23559253 }, { "content": "#[no_mangle]\n\npub fn skia_color_create(r: u8, g: u8, b: u8, a: u8) -> *mut ValueBox<Color> {\n\n ValueBox::new(Color::from_argb(a, r, g, b)).into_raw()\n\n}\n\n\n", "file_path": "library/src/color.rs", "rank": 1, "score": 421184.06677549356 }, { "content": "#[no_mangle]\n\npub fn skia_paint_get_color(paint_ptr: *mut ValueBox<Paint>) -> *mut ValueBox<Color> {\n\n paint_ptr.with_not_null_return(std::ptr::null_mut(), |paint| {\n\n ValueBox::new(paint.color()).into_raw()\n\n })\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 3, "score": 363803.4640020316 }, { "content": "#[no_mangle]\n\npub fn skia_paint_get_alpha(paint_ptr: *mut ValueBox<Paint>) -> u8 {\n\n paint_ptr.with_not_null_return(0, |paint| paint.alpha())\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 5, "score": 351259.479943208 }, { "content": "#[no_mangle]\n\npub fn skia_paint_get_stroke_miter(paint_ptr: *mut ValueBox<Paint>) -> scalar {\n\n paint_ptr.with_not_null_return(0.0, |paint| paint.stroke_miter())\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 6, "score": 348512.4262438755 }, { "content": "#[no_mangle]\n\npub fn skia_paint_get_stroke_width(paint_ptr: *mut ValueBox<Paint>) -> scalar {\n\n paint_ptr.with_not_null_return(0.0, |paint| paint.stroke_width())\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 7, "score": 348512.4262438755 }, { "content": "#[no_mangle]\n\npub fn skia_path_move_to(path_ptr: *mut ValueBox<Path>, x: scalar, y: scalar, is_absolute: bool) {\n\n path_ptr.with_not_null(|path| {\n\n if is_absolute {\n\n path.move_to(Point::new(x, y));\n\n } else {\n\n path.r_move_to(Vector::new(x, y));\n\n }\n\n });\n\n}\n\n\n", "file_path": "library/src/path.rs", "rank": 8, "score": 346329.28609073104 }, { "content": "#[no_mangle]\n\npub fn skia_path_line_to(path_ptr: *mut ValueBox<Path>, x: scalar, y: scalar, is_absolute: bool) {\n\n path_ptr.with_not_null(|path| {\n\n if is_absolute {\n\n path.line_to(Point::new(x, y));\n\n } else {\n\n path.r_line_to(Vector::new(x, y));\n\n }\n\n });\n\n}\n\n\n", "file_path": "library/src/path.rs", "rank": 9, "score": 346329.28609073104 }, { "content": "#[no_mangle]\n\npub fn skia_paint_set_alpha(paint_ptr: *mut ValueBox<Paint>, alpha: u8) {\n\n paint_ptr.with_not_null(|paint| {\n\n paint.set_alpha(alpha);\n\n });\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 10, "score": 344530.45189538435 }, { "content": "#[no_mangle]\n\npub fn skia_paint_set_stroke_width(paint_ptr: *mut ValueBox<Paint>, width: scalar) {\n\n paint_ptr.with_not_null(|paint| {\n\n paint.set_stroke_width(width);\n\n });\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 11, "score": 341848.0354842879 }, { "content": "#[no_mangle]\n\npub fn skia_paint_set_stroke_miter(paint_ptr: *mut ValueBox<Paint>, stroke_miter: scalar) {\n\n paint_ptr.with_not_null(|paint| {\n\n paint.set_stroke_miter(stroke_miter);\n\n });\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 12, "score": 339876.6510437902 }, { "content": "#[no_mangle]\n\npub fn skia_rectangle_f32_left(rectangle_ptr: *mut ValueBox<Rect>) -> scalar {\n\n rectangle_ptr.with_not_null_return(0.0, |rectangle| rectangle.left())\n\n}\n\n\n", "file_path": "library/src/rectangle.rs", "rank": 13, "score": 337232.2133293815 }, { "content": "#[no_mangle]\n\npub fn skia_rectangle_f32_right(rectangle_ptr: *mut ValueBox<Rect>) -> scalar {\n\n rectangle_ptr.with_not_null_return(0.0, |rectangle| rectangle.right())\n\n}\n\n\n", "file_path": "library/src/rectangle.rs", "rank": 14, "score": 337232.21332938154 }, { "content": "#[no_mangle]\n\npub fn skia_rectangle_f32_top(rectangle_ptr: *mut ValueBox<Rect>) -> scalar {\n\n rectangle_ptr.with_not_null_return(0.0, |rectangle| rectangle.top())\n\n}\n\n\n", "file_path": "library/src/rectangle.rs", "rank": 15, "score": 337223.04103370605 }, { "content": "#[no_mangle]\n\npub fn skia_rectangle_f32_bottom(rectangle_ptr: *mut ValueBox<Rect>) -> scalar {\n\n rectangle_ptr.with_not_null_return(0.0, |rectangle| rectangle.bottom())\n\n}\n\n\n", "file_path": "library/src/rectangle.rs", "rank": 16, "score": 337223.041033706 }, { "content": "#[no_mangle]\n\npub fn skia_rounded_rectangle_height(rounded_rectangle_ptr: *mut ValueBox<RRect>) -> scalar {\n\n rounded_rectangle_ptr.with_not_null_return(0.0, |rounded_rectangle| rounded_rectangle.height())\n\n}\n\n\n", "file_path": "library/src/rounded_rectangle.rs", "rank": 17, "score": 328988.616720514 }, { "content": "#[no_mangle]\n\npub fn skia_rounded_rectangle_width(rounded_rectangle_ptr: *mut ValueBox<RRect>) -> scalar {\n\n rounded_rectangle_ptr.with_not_null_return(0.0, |rounded_rectangle| rounded_rectangle.width())\n\n}\n\n\n", "file_path": "library/src/rounded_rectangle.rs", "rank": 18, "score": 328988.616720514 }, { "content": "#[no_mangle]\n\npub fn skia_paint_get_path_effect(paint_ptr: *mut ValueBox<Paint>) -> *mut ValueBox<PathEffect> {\n\n paint_ptr.with_not_null_return(std::ptr::null_mut(), |paint| match paint.path_effect() {\n\n None => std::ptr::null_mut(),\n\n Some(path_effect) => ValueBox::new(path_effect).into_raw(),\n\n })\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 19, "score": 326630.0591779158 }, { "content": "#[no_mangle]\n\npub fn skia_paint_get_image_filter(paint_ptr: *mut ValueBox<Paint>) -> *mut ValueBox<ImageFilter> {\n\n paint_ptr.with_not_null_return(std::ptr::null_mut(), |paint| match paint.image_filter() {\n\n None => std::ptr::null_mut(),\n\n Some(image_filter) => ValueBox::new(image_filter).into_raw(),\n\n })\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 20, "score": 326297.6125465779 }, { "content": "#[no_mangle]\n\npub fn skia_color_get_blue(color_ptr: *mut ValueBox<Color>) -> u8 {\n\n color_ptr.with_not_null_return(0, |color| color.b())\n\n}\n\n\n", "file_path": "library/src/color.rs", "rank": 23, "score": 315689.47604994086 }, { "content": "#[no_mangle]\n\npub fn skia_color_get_alpha(color_ptr: *mut ValueBox<Color>) -> u8 {\n\n color_ptr.with_not_null_return(0, |color| color.a())\n\n}\n\n\n", "file_path": "library/src/color.rs", "rank": 24, "score": 315689.47604994086 }, { "content": "#[no_mangle]\n\npub fn skia_color_get_green(color_ptr: *mut ValueBox<Color>) -> u8 {\n\n color_ptr.with_not_null_return(0, |color| color.g())\n\n}\n\n\n", "file_path": "library/src/color.rs", "rank": 25, "score": 315689.4760499408 }, { "content": "#[no_mangle]\n\npub fn skia_color_get_red(color_ptr: *mut ValueBox<Color>) -> u8 {\n\n color_ptr.with_not_null_return(0, |color| color.r())\n\n}\n\n\n", "file_path": "library/src/color.rs", "rank": 26, "score": 315689.47604994086 }, { "content": "#[no_mangle]\n\npub fn skia_paint_has_path_effect(paint_ptr: *mut ValueBox<Paint>) -> bool {\n\n paint_ptr.with_not_null_return(false, |paint| match paint.path_effect() {\n\n None => false,\n\n Some(_) => true,\n\n })\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 27, "score": 315116.5757422849 }, { "content": "#[no_mangle]\n\npub fn skia_paint_has_image_filter(paint_ptr: *mut ValueBox<Paint>) -> bool {\n\n paint_ptr.with_not_null_return(false, |paint| match paint.image_filter() {\n\n None => false,\n\n Some(_) => true,\n\n })\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 28, "score": 314840.43630748504 }, { "content": "#[no_mangle]\n\npub fn skia_path_serialize(path_ptr: *mut ValueBox<Path>, data_ptr: *mut ValueBox<BoxerArray<u8>>) {\n\n path_ptr.with_not_null(|path| {\n\n data_ptr.with_not_null(|data| {\n\n data.set_array(path.serialize().as_bytes());\n\n })\n\n });\n\n}\n\n\n", "file_path": "library/src/path.rs", "rank": 29, "score": 309344.00073819084 }, { "content": "#[no_mangle]\n\npub fn skia_path_contains_point(path_ptr: *mut ValueBox<Path>, x: f32, y: f32) -> bool {\n\n path_ptr.with_not_null_return(false, |path| path.contains(Point::new(x, y)))\n\n}\n\n\n", "file_path": "library/src/path.rs", "rank": 30, "score": 298565.3235901111 }, { "content": "#[no_mangle]\n\npub fn skia_offset_layer_new_point(x: scalar, y: scalar) -> *mut ValueBox<Rc<RefCell<dyn Layer>>> {\n\n let layer: Rc<RefCell<dyn Layer>> = Rc::new(RefCell::new(OffsetLayer::new(Point::new(x, y))));\n\n ValueBox::new(layer).into_raw()\n\n}\n\n\n", "file_path": "library/src/compositor/layers/offset.rs", "rank": 31, "score": 289928.52377897984 }, { "content": "#[no_mangle]\n\npub fn skia_paint_reset(paint_ptr: *mut ValueBox<Paint>) {\n\n paint_ptr.with_not_null(|paint| {\n\n paint.reset();\n\n });\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 33, "score": 283787.4858786537 }, { "content": "#[no_mangle]\n\npub fn skia_paint_get_shader(paint_ptr: *mut ValueBox<Paint>) -> *mut ValueBox<Shader> {\n\n paint_ptr.with_not_null_return(std::ptr::null_mut(), |paint| match paint.shader() {\n\n None => std::ptr::null_mut(),\n\n Some(shader) => ValueBox::new(shader).into_raw(),\n\n })\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 34, "score": 283127.53949231154 }, { "content": "#[no_mangle]\n\npub fn skia_path_count_points(path_ptr: *mut ValueBox<Path>) -> usize {\n\n path_ptr.with_not_null_return(0, |path| path.count_points())\n\n}\n\n\n", "file_path": "library/src/path.rs", "rank": 35, "score": 279981.39152991946 }, { "content": "#[no_mangle]\n\npub fn skia_rounded_rectangle_drop(ptr: &mut *mut ValueBox<RRect>) {\n\n drop!(ptr);\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use boxer::ValueBoxPointerReference;\n\n use rectangle::{skia_rectangle_f32_default, skia_rectangle_f32_set_ltrb};\n\n use rounded_rectangle::{\n\n skia_rounded_rectangle_default, skia_rounded_rectangle_height,\n\n skia_rounded_rectangle_set_rect, skia_rounded_rectangle_width,\n\n };\n\n\n\n #[test]\n\n fn set_rect() {\n\n let mut rect = skia_rectangle_f32_default();\n\n skia_rectangle_f32_set_ltrb(rect, 0.0, 0.0, 50.0, 50.0);\n\n\n\n let mut r_rect = skia_rounded_rectangle_default();\n\n skia_rounded_rectangle_set_rect(r_rect, rect);\n", "file_path": "library/src/rounded_rectangle.rs", "rank": 36, "score": 278541.61564589635 }, { "content": "#[no_mangle]\n\npub fn skia_paint_is_dither(paint_ptr: *mut ValueBox<Paint>) -> bool {\n\n paint_ptr.with_not_null_return(false, |paint| paint.is_dither())\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 37, "score": 278318.74200632353 }, { "content": "#[no_mangle]\n\npub fn skia_paint_set_shader(paint_ptr: *mut ValueBox<Paint>, shader_ptr: *mut ValueBox<Shader>) {\n\n paint_ptr.with_not_null(|paint| {\n\n let shader = shader_ptr.with_not_null_value_return(None, |shader| Some(shader));\n\n paint.set_shader(shader);\n\n });\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 38, "score": 277321.53239711974 }, { "content": "#[no_mangle]\n\npub fn skia_paint_get_alpha_f(paint_ptr: *mut ValueBox<Paint>) -> f32 {\n\n paint_ptr.with_not_null_return(0.0, |paint| paint.alpha_f())\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 39, "score": 276717.8584311171 }, { "content": "#[no_mangle]\n\npub fn skia_paint_is_anti_alias(paint_ptr: *mut ValueBox<Paint>) -> bool {\n\n paint_ptr.with_not_null_return(false, |paint| paint.is_anti_alias())\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 40, "score": 276717.85843111714 }, { "content": "#[no_mangle]\n\npub fn skia_paint_get_style(paint_ptr: *mut ValueBox<Paint>) -> Style {\n\n paint_ptr.with_not_null_return(Style::Fill, |paint| paint.style())\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 41, "score": 276717.8584311171 }, { "content": "#[no_mangle]\n\npub fn skia_paint_get_stroke_join(paint_ptr: *mut ValueBox<Paint>) -> Join {\n\n paint_ptr.with_not_null_return(Join::Miter, |paint| paint.stroke_join())\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 42, "score": 275154.7382000444 }, { "content": "#[no_mangle]\n\npub fn skia_paint_get_stroke_cap(paint_ptr: *mut ValueBox<Paint>) -> Cap {\n\n paint_ptr.with_not_null_return(Cap::Butt, |paint| paint.stroke_cap())\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 43, "score": 275154.7382000444 }, { "content": "#[no_mangle]\n\npub fn skia_path_effect_corner(radius: scalar) -> *mut ValueBox<PathEffect> {\n\n match PathEffect::corner_path(radius) {\n\n None => std::ptr::null_mut(),\n\n Some(effect) => ValueBox::new(effect).into_raw(),\n\n }\n\n}\n\n\n", "file_path": "library/src/path_effect.rs", "rank": 44, "score": 274621.81902564975 }, { "content": "#[no_mangle]\n\npub fn skia_paint_get_blend_mode(paint_ptr: *mut ValueBox<Paint>) -> BlendMode {\n\n paint_ptr.with_not_null_return(BlendMode::Clear, |paint| paint.blend_mode())\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 45, "score": 273627.96927938616 }, { "content": "#[no_mangle]\n\npub fn skia_paint_set_dither(paint_ptr: *mut ValueBox<Paint>, dither: bool) {\n\n paint_ptr.with_not_null(|paint| {\n\n paint.set_dither(dither);\n\n });\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 46, "score": 271550.3516384198 }, { "content": "#[no_mangle]\n\npub fn skia_paint_set_alpha_f(paint_ptr: *mut ValueBox<Paint>, alpha: f32) {\n\n paint_ptr.with_not_null(|paint| {\n\n paint.set_alpha_f(alpha);\n\n });\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 47, "score": 271550.3516384198 }, { "content": "#[no_mangle]\n\npub fn skia_paint_set_style(paint_ptr: *mut ValueBox<Paint>, style: Style) {\n\n paint_ptr.with_not_null(|paint| {\n\n paint.set_style(style);\n\n });\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 48, "score": 271550.3516384198 }, { "content": "#[no_mangle]\n\npub fn skia_rounded_rectangle_default() -> *mut ValueBox<RRect> {\n\n ValueBox::new(RRect::default()).into_raw()\n\n}\n\n\n", "file_path": "library/src/rounded_rectangle.rs", "rank": 49, "score": 271388.0654397147 }, { "content": "#[no_mangle]\n\npub fn skia_paint_set_anti_alias(paint_ptr: *mut ValueBox<Paint>, anti_alias: bool) {\n\n paint_ptr.with_not_null(|paint| {\n\n paint.set_anti_alias(anti_alias);\n\n });\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 50, "score": 268531.82449018396 }, { "content": "#[no_mangle]\n\npub fn skia_paint_set_stroke_join(paint_ptr: *mut ValueBox<Paint>, stroke_join: Join) {\n\n paint_ptr.with_not_null(|paint| {\n\n paint.set_stroke_join(stroke_join);\n\n });\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 51, "score": 268531.82449018396 }, { "content": "#[no_mangle]\n\npub fn skia_paint_set_stroke_cap(paint_ptr: *mut ValueBox<Paint>, stroke_cap: Cap) {\n\n paint_ptr.with_not_null(|paint| {\n\n paint.set_stroke_cap(stroke_cap);\n\n });\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 52, "score": 268531.82449018396 }, { "content": "#[no_mangle]\n\npub fn skia_paint_set_blend_mode(paint_ptr: *mut ValueBox<Paint>, blend_mode: BlendMode) {\n\n paint_ptr.with_not_null(|paint| {\n\n paint.set_blend_mode(blend_mode);\n\n });\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 53, "score": 267073.803250864 }, { "content": "#[no_mangle]\n\npub fn skia_matrix_drop(ptr: &mut *mut ValueBox<Matrix>) {\n\n drop!(ptr);\n\n}\n", "file_path": "library/src/matrix.rs", "rank": 54, "score": 259719.44359709113 }, { "content": "#[no_mangle]\n\npub fn skia_color_array_get_data(_ptr: *mut ValueBox<BoxerArray<Color>>) -> *mut Color {\n\n BoxerArray::<Color>::boxer_array_get_data(_ptr)\n\n}\n\n\n", "file_path": "library/src/color.rs", "rank": 55, "score": 259388.34593731345 }, { "content": "#[no_mangle]\n\npub fn skia_path_drop(ptr: &mut *mut ValueBox<Path>) {\n\n drop!(ptr);\n\n}\n", "file_path": "library/src/path.rs", "rank": 56, "score": 259339.98405077815 }, { "content": "#[no_mangle]\n\npub fn skia_color_drop(ptr: &mut *mut ValueBox<Color>) {\n\n drop!(ptr);\n\n}\n\n\n", "file_path": "library/src/color.rs", "rank": 57, "score": 259121.23860196728 }, { "content": "#[no_mangle]\n\npub fn skia_paint_drop(ptr: &mut *mut ValueBox<Paint>) {\n\n drop!(ptr);\n\n}\n", "file_path": "library/src/paint.rs", "rank": 58, "score": 258996.1595129512 }, { "content": "#[no_mangle]\n\npub fn skia_image_get_color_space(image_ptr: *mut ValueBox<Image>) -> *mut ValueBox<ColorSpace> {\n\n image_ptr.with(\n\n || ValueBox::new(ColorSpace::new_srgb()).into_raw(),\n\n |image| ValueBox::new(image.color_space()).into_raw(),\n\n )\n\n}\n\n\n", "file_path": "library/src/image.rs", "rank": 59, "score": 258887.04107434466 }, { "content": "#[no_mangle]\n\npub fn skia_rounded_rectangle_get_type(rounded_rectangle_ptr: *mut ValueBox<RRect>) -> Type {\n\n rounded_rectangle_ptr.with_not_null_return(Type::Empty, |rounded_rectangle| {\n\n rounded_rectangle.get_type()\n\n })\n\n}\n\n\n", "file_path": "library/src/rounded_rectangle.rs", "rank": 60, "score": 254459.8276370598 }, { "content": "#[no_mangle]\n\npub fn skia_color_array_drop(ptr: &mut *mut ValueBox<BoxerArray<Color>>) {\n\n drop!(ptr);\n\n}\n\n\n", "file_path": "library/src/color.rs", "rank": 61, "score": 252077.36794904165 }, { "content": "#[no_mangle]\n\npub fn skia_font_metrics_get_top(font_metrics_ptr: *mut ValueBox<FontMetrics>) -> scalar {\n\n font_metrics_ptr.with_not_null_return(0.0, |metrics| metrics.top)\n\n}\n\n\n", "file_path": "library/src/text/font_metrics.rs", "rank": 62, "score": 251784.9339909238 }, { "content": "#[no_mangle]\n\npub fn skia_font_metrics_get_bottom(font_metrics_ptr: *mut ValueBox<FontMetrics>) -> scalar {\n\n font_metrics_ptr.with_not_null_return(0.0, |metrics| metrics.bottom)\n\n}\n\n\n", "file_path": "library/src/text/font_metrics.rs", "rank": 63, "score": 251784.9339909238 }, { "content": "#[no_mangle]\n\npub fn skia_path_new() -> *mut ValueBox<Path> {\n\n ValueBox::new(Path::new()).into_raw()\n\n}\n\n\n", "file_path": "library/src/path.rs", "rank": 64, "score": 251328.12541282334 }, { "content": "#[no_mangle]\n\npub fn skia_color_default() -> *mut ValueBox<Color> {\n\n ValueBox::new(Color::default()).into_raw()\n\n}\n\n\n", "file_path": "library/src/color.rs", "rank": 65, "score": 251103.41922756511 }, { "content": "#[no_mangle]\n\npub fn skia_paint_default() -> *mut ValueBox<Paint> {\n\n ValueBox::new(Paint::default()).into_raw()\n\n}\n\n\n", "file_path": "library/src/paint.rs", "rank": 66, "score": 250966.2485325088 }, { "content": "#[no_mangle]\n\npub fn skia_matrix_new_identity() -> *mut ValueBox<Matrix> {\n\n ValueBox::new(Matrix::new_identity()).into_raw()\n\n}\n\n\n", "file_path": "library/src/matrix.rs", "rank": 67, "score": 249930.47899466974 }, { "content": "#[no_mangle]\n\npub fn skia_image_get_color_type(image_ptr: *mut ValueBox<Image>) -> ColorType {\n\n image_ptr.with_not_null_return(ColorType::Unknown, |image| image.color_type())\n\n}\n\n\n", "file_path": "library/src/image.rs", "rank": 68, "score": 249189.13885347525 }, { "content": "#[no_mangle]\n\npub fn skia_path_close(path_ptr: *mut ValueBox<Path>) {\n\n path_ptr.with_not_null(|path| {\n\n path.close();\n\n });\n\n}\n\n\n", "file_path": "library/src/path.rs", "rank": 69, "score": 247340.70248705026 }, { "content": "#[no_mangle]\n\npub fn skia_rectangle_f32_drop(ptr: &mut *mut ValueBox<Rect>) {\n\n drop!(ptr);\n\n}\n\n\n\n///\n\n/// IRect\n\n///\n\n\n", "file_path": "library/src/rectangle.rs", "rank": 71, "score": 243831.76441793705 }, { "content": "#[no_mangle]\n\npub fn skia_color_array_default() -> *mut ValueBox<BoxerArray<Color>> {\n\n ValueBox::new(BoxerArray::new()).into_raw()\n\n}\n\n\n", "file_path": "library/src/color.rs", "rank": 72, "score": 242981.0681549788 }, { "content": "#[no_mangle]\n\npub fn skia_picture_cull_rect(picture_ptr: *mut ValueBox<Picture>) -> *mut ValueBox<Rect> {\n\n picture_ptr.with_not_null_return(std::ptr::null_mut(), |picture| {\n\n ValueBox::new(picture.cull_rect()).into_raw()\n\n })\n\n}\n\n\n", "file_path": "library/src/picture.rs", "rank": 74, "score": 242505.1076380842 }, { "content": "#[no_mangle]\n\npub fn skia_image_info_get_color_type(image_info_ptr: *mut ValueBox<ImageInfo>) -> ColorType {\n\n image_info_ptr.with_not_null_return(ColorType::Unknown, |image_info| image_info.color_type())\n\n}\n\n\n", "file_path": "library/src/image_info.rs", "rank": 75, "score": 241917.3655616021 }, { "content": "#[no_mangle]\n\npub fn skia_color_create_argb(argb: u32) -> *mut ValueBox<Color> {\n\n ValueBox::new(Color::new(argb)).into_raw()\n\n}\n\n\n", "file_path": "library/src/color.rs", "rank": 77, "score": 240256.2995523252 }, { "content": "#[no_mangle]\n\npub fn skia_paragraph_decoration_get_color(ptr: *mut ValueBox<Decoration>) -> *mut ValueBox<Color> {\n\n ptr.with_not_null_return(std::ptr::null_mut(), |decoration| {\n\n ValueBox::new(decoration.color).into_raw()\n\n })\n\n}\n\n\n", "file_path": "library/src/paragraph/paragraph_decoration.rs", "rank": 78, "score": 239212.36523740325 }, { "content": "#[no_mangle]\n\npub fn skia_path_get_fill_type(path_ptr: *mut ValueBox<Path>) -> PathFillType {\n\n path_ptr.with_not_null_return(PathFillType::Winding, |path| path.fill_type())\n\n}\n\n\n", "file_path": "library/src/path.rs", "rank": 79, "score": 238562.9562497308 }, { "content": "#[no_mangle]\n\npub fn skia_rectangle_f32_default() -> *mut ValueBox<Rect> {\n\n ValueBox::new(Rect::default()).into_raw()\n\n}\n\n\n", "file_path": "library/src/rectangle.rs", "rank": 81, "score": 236051.1408301882 }, { "content": "#[no_mangle]\n\npub fn skia_path_set_fill_type(path_ptr: *mut ValueBox<Path>, fill_type: PathFillType) {\n\n path_ptr.with_not_null(|path| {\n\n path.set_fill_type(fill_type);\n\n });\n\n}\n\n\n", "file_path": "library/src/path.rs", "rank": 82, "score": 233185.97893230774 }, { "content": "#[no_mangle]\n\npub fn skia_color_array_get_capacity(_ptr: *mut ValueBox<BoxerArray<Color>>) -> usize {\n\n BoxerArray::<Color>::boxer_array_get_capacity(_ptr)\n\n}\n\n\n", "file_path": "library/src/color.rs", "rank": 83, "score": 232834.90142229828 }, { "content": "#[no_mangle]\n\npub fn skia_color_array_get_length(_ptr: *mut ValueBox<BoxerArray<Color>>) -> usize {\n\n BoxerArray::<Color>::boxer_array_get_length(_ptr)\n\n}\n\n\n", "file_path": "library/src/color.rs", "rank": 84, "score": 232834.90142229828 }, { "content": "#[no_mangle]\n\npub fn skia_rectangle_i32_right(rectangle_ptr: *mut ValueBox<IRect>) -> i32 {\n\n rectangle_ptr.with_not_null_return(0, |rectangle| rectangle.right())\n\n}\n\n\n", "file_path": "library/src/rectangle.rs", "rank": 88, "score": 227399.45273958126 }, { "content": "#[no_mangle]\n\npub fn skia_rectangle_i32_left(rectangle_ptr: *mut ValueBox<IRect>) -> i32 {\n\n rectangle_ptr.with_not_null_return(0, |rectangle| rectangle.left())\n\n}\n\n\n", "file_path": "library/src/rectangle.rs", "rank": 89, "score": 227399.45273958126 }, { "content": "#[no_mangle]\n\npub fn skia_rectangle_i32_bottom(rectangle_ptr: *mut ValueBox<IRect>) -> i32 {\n\n rectangle_ptr.with_not_null_return(0, |rectangle| rectangle.bottom())\n\n}\n\n\n", "file_path": "library/src/rectangle.rs", "rank": 90, "score": 227390.28044390577 }, { "content": "#[no_mangle]\n\npub fn skia_rectangle_i32_top(rectangle_ptr: *mut ValueBox<IRect>) -> i32 {\n\n rectangle_ptr.with_not_null_return(0, |rectangle| rectangle.top())\n\n}\n\n\n", "file_path": "library/src/rectangle.rs", "rank": 91, "score": 227390.28044390577 }, { "content": "#[no_mangle]\n\npub fn skia_image_drop(ptr: &mut *mut ValueBox<Image>) {\n\n drop!(ptr);\n\n}\n", "file_path": "library/src/image.rs", "rank": 93, "score": 223024.40391193674 }, { "content": "#[no_mangle]\n\npub fn skia_font_get_spacing(font_ptr: *mut ValueBox<Font>) -> scalar {\n\n font_ptr.with_not_null_return(0.0, |font| font.spacing())\n\n}\n\n\n", "file_path": "library/src/text/font.rs", "rank": 94, "score": 222312.1558729034 }, { "content": "#[no_mangle]\n\npub fn skia_font_get_scale_x(font_ptr: *mut ValueBox<Font>) -> scalar {\n\n font_ptr.with_not_null_return(0.0, |font| font.scale_x())\n\n}\n\n\n", "file_path": "library/src/text/font.rs", "rank": 95, "score": 222312.1558729034 }, { "content": "#[no_mangle]\n\npub fn skia_font_get_size(font_ptr: *mut ValueBox<Font>) -> scalar {\n\n font_ptr.with_not_null_return(0.0, |font| font.size())\n\n}\n\n\n", "file_path": "library/src/text/font.rs", "rank": 96, "score": 222312.1558729034 }, { "content": "#[no_mangle]\n\npub fn skia_font_get_skew_x(font_ptr: *mut ValueBox<Font>) -> scalar {\n\n font_ptr.with_not_null_return(0.0, |font| font.skew_x())\n\n}\n\n\n", "file_path": "library/src/text/font.rs", "rank": 97, "score": 222312.1558729034 }, { "content": "#[no_mangle]\n\npub fn skia_paragraph_get_height(paragraph_ptr: *mut ValueBox<ParagraphWithText>) -> scalar {\n\n paragraph_ptr.with_not_null_return(0.0, |paragraph| paragraph.height())\n\n}\n\n\n", "file_path": "library/src/paragraph/paragraph.rs", "rank": 98, "score": 220554.01238260325 }, { "content": "#[no_mangle]\n\npub fn skia_paragraph_decoration_get_thickness(ptr: *mut ValueBox<Decoration>) -> scalar {\n\n ptr.with_not_null_return(0.0, |decoration| decoration.thickness_multiplier)\n\n}\n\n\n", "file_path": "library/src/paragraph/paragraph_decoration.rs", "rank": 99, "score": 220554.01238260325 } ]
Rust
src/strencrypt.rs
JohnAgapeyev/R2D2
bc2ca7143844fe82b4ecc3e221de667a8bb5b3b4
use quote::*; use syn::spanned::Spanned; use syn::visit_mut::*; use syn::*; use crate::crypto::*; use crate::parse::*; #[allow(unused_imports)] use crate as r2d2; struct MemEncCtx { ctx: MemoryEncryptionCtx<XChaCha20Poly1305>, needs_owned_str: bool, } impl ToTokens for MemEncCtx { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let key = &self.ctx.key; let nonce = &self.ctx.nonce; let ciphertext = &self.ctx.ciphertext; let output: proc_macro2::TokenStream; if self.needs_owned_str { /* * let x = "foobar"; * println!("{}", x); * * This snippet requires special handling since the temporary decrypted string goes out * of scope after decryption, so we need to return a string object rather than a &str * This could theoretically still have issues with explicit typing, but we'll cross * that bridge when we get there */ output = quote! { let result = r2d2::crypto::decrypt_memory::<r2d2::crypto::chacha20poly1305::XChaCha20Poly1305>(r2d2::crypto::MemoryEncryptionCtx { key: (r2d2::generic_array::arr![u8; #(#key),*]) as r2d2::crypto::aead::Key::<r2d2::crypto::chacha20poly1305::XChaCha20Poly1305>, nonce: (r2d2::generic_array::arr![u8; #(#nonce),*]) as r2d2::crypto::aead::Nonce::<r2d2::crypto::chacha20poly1305::XChaCha20Poly1305>, ciphertext: ::std::vec![#(#ciphertext),*], }); ::std::string::String::from_utf8(result).unwrap() }; } else { output = quote! { let result = r2d2::crypto::decrypt_memory::<r2d2::crypto::chacha20poly1305::XChaCha20Poly1305>(r2d2::crypto::MemoryEncryptionCtx { key: (r2d2::generic_array::arr![u8; #(#key),*]) as r2d2::crypto::aead::Key::<r2d2::crypto::chacha20poly1305::XChaCha20Poly1305>, nonce: (r2d2::generic_array::arr![u8; #(#nonce),*]) as r2d2::crypto::aead::Nonce::<r2d2::crypto::chacha20poly1305::XChaCha20Poly1305>, ciphertext: ::std::vec![#(#ciphertext),*], }); ::std::string::String::from_utf8(result).unwrap().as_str() }; } tokens.append_all(output); } } struct StrReplace; /* * The choice of Self::visit_*_mut vs visit_mut::visit_*_mut is important here * Some choices will result in breakage by not encrypting * Others will create a recursive loop exhausting the stack * * NOTE: DO NOT MODIFY WITHOUT TESTING AND VERIFICATION */ impl VisitMut for StrReplace { fn visit_macro_mut(&mut self, node: &mut Macro) { let macro_path = node .path .get_ident() .map(|ident| ident.to_string()) .unwrap_or_default(); let mut can_encrypt = match macro_path.as_str() { "println" => true, "eprintln" => true, "format" => true, "concat" => true, _ => false, }; if !can_encrypt { visit_mut::visit_macro_mut(self, node); return; } if let Ok(mut parsed) = node.parse_body::<FormatArgs>() { if let Lit::Str(s) = &parsed.format_string.lit { if s.value().contains("{") { can_encrypt = false; } } else { panic!("Format string is not a string literal!"); } if parsed.positional_args.is_empty() && parsed.named_args.is_empty() && can_encrypt { let span = parsed.format_string.span(); parsed .positional_args .push(Expr::Lit(parsed.format_string.to_owned())); parsed.format_string = ExprLit { attrs: Vec::new(), lit: Lit::Str(LitStr::new("{}", span)), }; Self::visit_expr_mut(self, &mut parsed.positional_args[0]); } else { parsed .positional_args .iter_mut() .for_each(|mut e| Self::visit_expr_mut(self, &mut e)); } node.tokens = parsed.to_token_stream(); } visit_mut::visit_macro_mut(self, node); } fn visit_expr_mut(&mut self, node: &mut Expr) { /* * Skip function call expressions * This is a case of lifetime scoping problems * Given a function foo("hello"), only a String type would support decryption * If the function takes a &str, the temporary will go out of scope and fail to compile * I'm not about to become a linker, so this has to be skipped * Best case is to limit/audit string literals to prevent this case */ let must_skip = match &node { Expr::Call(_) => true, Expr::MethodCall(_) => true, _ => false, }; if must_skip { return; } if let Expr::Lit(expr) = &node { if let Lit::Str(s) = &expr.lit { let mem_ctx = MemEncCtx { ctx: encrypt_memory::<XChaCha20Poly1305>(s.value().as_bytes()), needs_owned_str: false, }; let output = quote! { { #mem_ctx } }; let output = syn::parse2::<ExprBlock>(output).unwrap(); *node = Expr::Block(output); return; } else if let Lit::ByteStr(s) = &expr.lit { let mem_ctx = MemEncCtx { ctx: encrypt_memory::<XChaCha20Poly1305>(&s.value()), needs_owned_str: false, }; let output = quote! { { #mem_ctx } }; let output = syn::parse2::<ExprBlock>(output).unwrap(); *node = Expr::Block(output); return; } } visit_mut::visit_expr_mut(self, node); } fn visit_arm_mut(&mut self, node: &mut Arm) { Self::visit_expr_mut(self, &mut node.body); } fn visit_item_const_mut(&mut self, _node: &mut ItemConst) { /* * Skip all constant expressions since we can't decrypt those * Function intentionally left blank */ } fn visit_local_mut(&mut self, node: &mut Local) { if let Some(init) = &node.init { if let Expr::Lit(expr) = &*init.1 { if let Lit::Str(s) = &expr.lit { /* * Skip let assignments with an explicit reference type * This is fine for string literals due to static lifetime * Decryption doesn't have a static lifetime, so an explicit reference storage * will run into object lifetime issues */ if let Pat::Type(ty) = &node.pat { if let Type::Reference(_) = *ty.ty { return; } } let mem_ctx = MemEncCtx { ctx: encrypt_memory::<XChaCha20Poly1305>(s.value().as_bytes()), needs_owned_str: true, }; let output = quote! { { #mem_ctx } }; let output = syn::parse2::<ExprBlock>(output).unwrap(); node.init = Some((init.0, Box::new(Expr::Block(output)))); return; } } } } } pub fn encrypt_strings(input: &mut File) { StrReplace.visit_file_mut(input); }
use quote::*; use syn::spanned::Spanned; use syn::visit_mut::*; use syn::*; use crate::crypto::*; use crate::parse::*; #[allow(unused_imports)] use crate as r2d2; struct MemEncCtx { ctx: MemoryEncryptionCtx<XChaCha20Poly1305>, needs_owned_str: bool, } impl ToTokens for MemEncCtx { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let key = &self.ctx.key; let nonce = &self.ctx.nonce; let ciphertext = &self.ctx.ciphertext; let output: proc_macro2::TokenStream; if self.needs_owned_str { /* * let x = "foobar"; * println!("{}", x); * * This snippet requires special handling since the temporary decrypted string goes out * of scope after decryption, so we need to return a string object rather than a &str * This could theoretically still have issues with explicit typing, but we'll cross * that bridge when we get there */ output = quote! { let result = r2d2::crypto::decrypt_memory::<r2d2::crypto::chacha20poly1305::XChaCha20Poly1305>(r2d2::crypto::MemoryEncryptionCtx { key: (r2d2::generic_array::arr![u8; #(#key),*]) as r2d2::crypto::aead::Key::<r2d2::crypto::chacha20poly1305::XChaCha20Poly1305>, nonce: (r2d2::generic_array::arr![u8; #(#nonce),*]) as r2d2::crypto::aead::Nonce::<r2d2::crypto::chacha20poly1305::XChaCha20Poly1305>, ciphertext: ::std::vec![#(#ciphertext),*], }); ::std::string::String::from_utf8(result).unwrap() }; } else { output = quote! { let result = r2d2::crypto::decrypt_memory::<r2d2::crypto::chacha20poly1305::XChaCha20Poly1305>(r2d2::crypto::MemoryEncryptionCtx { key: (r2d2::generic_array::arr![u8; #(#key),*]) as r2d2::crypto::aead::Key::<r2d2::crypto::chacha20poly1305::XChaCha20Poly1305>, nonce: (r2d2::generic_array::arr![u8; #(#nonce),*]) as r2d2::crypto::aead::Nonce::<r2d2::crypto::chacha20poly1305::XChaCha20Poly1305>, ciphertext: ::std::vec![#(#ciphertext),*], }); ::std::string::String::from_utf8(result).unwrap().as_str() }; } tokens.append_all(output); } } struct StrReplace; /* * The choice of Self::visit_*_mut vs visit_mut::visit_*_mut is important here * Some choices will result in breakage by not encrypting * Others will create a recursive loop exhausting the stack * * NOTE: DO NOT MODIFY WITHOUT TESTING AND VERIFICATION */ impl VisitMut for StrReplace {
fn visit_expr_mut(&mut self, node: &mut Expr) { /* * Skip function call expressions * This is a case of lifetime scoping problems * Given a function foo("hello"), only a String type would support decryption * If the function takes a &str, the temporary will go out of scope and fail to compile * I'm not about to become a linker, so this has to be skipped * Best case is to limit/audit string literals to prevent this case */ let must_skip = match &node { Expr::Call(_) => true, Expr::MethodCall(_) => true, _ => false, }; if must_skip { return; } if let Expr::Lit(expr) = &node { if let Lit::Str(s) = &expr.lit { let mem_ctx = MemEncCtx { ctx: encrypt_memory::<XChaCha20Poly1305>(s.value().as_bytes()), needs_owned_str: false, }; let output = quote! { { #mem_ctx } }; let output = syn::parse2::<ExprBlock>(output).unwrap(); *node = Expr::Block(output); return; } else if let Lit::ByteStr(s) = &expr.lit { let mem_ctx = MemEncCtx { ctx: encrypt_memory::<XChaCha20Poly1305>(&s.value()), needs_owned_str: false, }; let output = quote! { { #mem_ctx } }; let output = syn::parse2::<ExprBlock>(output).unwrap(); *node = Expr::Block(output); return; } } visit_mut::visit_expr_mut(self, node); } fn visit_arm_mut(&mut self, node: &mut Arm) { Self::visit_expr_mut(self, &mut node.body); } fn visit_item_const_mut(&mut self, _node: &mut ItemConst) { /* * Skip all constant expressions since we can't decrypt those * Function intentionally left blank */ } fn visit_local_mut(&mut self, node: &mut Local) { if let Some(init) = &node.init { if let Expr::Lit(expr) = &*init.1 { if let Lit::Str(s) = &expr.lit { /* * Skip let assignments with an explicit reference type * This is fine for string literals due to static lifetime * Decryption doesn't have a static lifetime, so an explicit reference storage * will run into object lifetime issues */ if let Pat::Type(ty) = &node.pat { if let Type::Reference(_) = *ty.ty { return; } } let mem_ctx = MemEncCtx { ctx: encrypt_memory::<XChaCha20Poly1305>(s.value().as_bytes()), needs_owned_str: true, }; let output = quote! { { #mem_ctx } }; let output = syn::parse2::<ExprBlock>(output).unwrap(); node.init = Some((init.0, Box::new(Expr::Block(output)))); return; } } } } } pub fn encrypt_strings(input: &mut File) { StrReplace.visit_file_mut(input); }
fn visit_macro_mut(&mut self, node: &mut Macro) { let macro_path = node .path .get_ident() .map(|ident| ident.to_string()) .unwrap_or_default(); let mut can_encrypt = match macro_path.as_str() { "println" => true, "eprintln" => true, "format" => true, "concat" => true, _ => false, }; if !can_encrypt { visit_mut::visit_macro_mut(self, node); return; } if let Ok(mut parsed) = node.parse_body::<FormatArgs>() { if let Lit::Str(s) = &parsed.format_string.lit { if s.value().contains("{") { can_encrypt = false; } } else { panic!("Format string is not a string literal!"); } if parsed.positional_args.is_empty() && parsed.named_args.is_empty() && can_encrypt { let span = parsed.format_string.span(); parsed .positional_args .push(Expr::Lit(parsed.format_string.to_owned())); parsed.format_string = ExprLit { attrs: Vec::new(), lit: Lit::Str(LitStr::new("{}", span)), }; Self::visit_expr_mut(self, &mut parsed.positional_args[0]); } else { parsed .positional_args .iter_mut() .for_each(|mut e| Self::visit_expr_mut(self, &mut e)); } node.tokens = parsed.to_token_stream(); } visit_mut::visit_macro_mut(self, node); }
function_block-full_function
[ { "content": "fn is_shuffle_attr(attr: &str) -> bool {\n\n match attr {\n\n SHUFFLE_ATTR_NAME => true,\n\n _ => false,\n\n }\n\n}\n\n\n", "file_path": "src/shuffle.rs", "rank": 1, "score": 200775.69576019843 }, { "content": "/// Render a sparkline of `data` into `buffer`.\n\npub fn render_f64(data: &[f64], buffer: &mut String) {\n\n match data.len() {\n\n 0 => {\n\n return;\n\n },\n\n 1 => {\n\n if data[0] == 0. {\n\n buffer.push(TICKS[0]);\n\n } else {\n\n buffer.push(TICKS[N - 1]);\n\n }\n\n return;\n\n },\n\n _ => {},\n\n }\n\n for x in data {\n\n assert!(x.is_finite(), \"can only render finite values\");\n\n }\n\n let max = data.iter().fold(\n\n core::f64::NEG_INFINITY, |a, &b| a.max(b));\n\n let min = data.iter().fold(\n\n core::f64::INFINITY, |a, &b| a.min(b));\n\n let scale = ((N - 1) as f64) / (max - min);\n\n for x in data {\n\n let tick = ((x - min) * scale) as usize;\n\n buffer.push(TICKS[tick]);\n\n }\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_distr/tests/sparkline.rs", "rank": 2, "score": 199403.9762400479 }, { "content": "/// Render a sparkline of `data` into `buffer`.\n\npub fn render_u64(data: &[u64], buffer: &mut String) {\n\n match data.len() {\n\n 0 => {\n\n return;\n\n },\n\n 1 => {\n\n if data[0] == 0 {\n\n buffer.push(TICKS[0]);\n\n } else {\n\n buffer.push(TICKS[N - 1]);\n\n }\n\n return;\n\n },\n\n _ => {},\n\n }\n\n let max = data.iter().max().unwrap();\n\n let min = data.iter().min().unwrap();\n\n let scale = ((N - 1) as f64) / ((max - min) as f64);\n\n for i in data {\n\n let tick = (((i - min) as f64) * scale) as usize;\n\n buffer.push(TICKS[tick]);\n\n }\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_distr/tests/sparkline.rs", "rank": 3, "score": 199403.9762400479 }, { "content": "pub fn decrypt_memory<Cipher>(ctx: MemoryEncryptionCtx<Cipher>) -> Vec<u8>\n\nwhere\n\n Cipher: NewAead,\n\n Cipher: Aead,\n\n Cipher::KeySize: IsEqual<U32, Output = True>,\n\n //TODO: Should probably redo nonce generation to be generic enough for things like AES-GCM that use 96 bit nonces\n\n Cipher::NonceSize: IsEqual<U24, Output = True>,\n\n{\n\n let cipher = Cipher::new(&ctx.key);\n\n let output = cipher\n\n .decrypt(&ctx.nonce, ctx.ciphertext.as_slice())\n\n .unwrap();\n\n //println!(\"We decrypted data: {:#x?}\", output);\n\n output\n\n}\n\n\n", "file_path": "src/crypto.rs", "rank": 4, "score": 198655.31671893373 }, { "content": "/// Randomly sample exactly `amount` indices from `0..length`, using rejection\n\n/// sampling.\n\n///\n\n/// Since `amount <<< length` there is a low chance of a random sample in\n\n/// `0..length` being a duplicate. We test for duplicates and resample where\n\n/// necessary. The algorithm is `O(amount)` time and memory.\n\n///\n\n/// This function is generic over X primarily so that results are value-stable\n\n/// over 32-bit and 64-bit platforms.\n\nfn sample_rejection<X: UInt, R>(rng: &mut R, length: X, amount: X) -> IndexVec\n\nwhere\n\n R: Rng + ?Sized,\n\n IndexVec: From<Vec<X>>,\n\n{\n\n debug_assert!(amount < length);\n\n #[cfg(feature = \"std\")]\n\n let mut cache = HashSet::with_capacity(amount.as_usize());\n\n #[cfg(not(feature = \"std\"))]\n\n let mut cache = BTreeSet::new();\n\n let distr = Uniform::new(X::zero(), length);\n\n let mut indices = Vec::with_capacity(amount.as_usize());\n\n for _ in 0..amount.as_usize() {\n\n let mut pos = distr.sample(rng);\n\n while !cache.insert(pos) {\n\n pos = distr.sample(rng);\n\n }\n\n indices.push(pos);\n\n }\n\n\n", "file_path": "tests/complex/rand/src/seq/index.rs", "rank": 5, "score": 196501.0072550791 }, { "content": "#[bench]\n\nfn misc_gen_bool_const(b: &mut Bencher) {\n\n let mut rng = Pcg32::from_rng(&mut thread_rng()).unwrap();\n\n b.iter(|| {\n\n let mut accum = true;\n\n for _ in 0..crate::RAND_BENCH_N {\n\n accum ^= rng.gen_bool(0.18);\n\n }\n\n accum\n\n })\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/misc.rs", "rank": 6, "score": 189890.03344174867 }, { "content": "#[bench]\n\nfn misc_gen_bool_var(b: &mut Bencher) {\n\n let mut rng = Pcg32::from_rng(&mut thread_rng()).unwrap();\n\n b.iter(|| {\n\n let mut accum = true;\n\n let mut p = 0.18;\n\n for _ in 0..crate::RAND_BENCH_N {\n\n accum ^= rng.gen_bool(p);\n\n p += 0.0001;\n\n }\n\n accum\n\n })\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/misc.rs", "rank": 7, "score": 189890.03344174867 }, { "content": "fn get_rng(seed: u64) -> impl rand::Rng {\n\n // For tests, we want a statistically good, fast, reproducible RNG.\n\n // PCG32 will do fine, and will be easy to embed if we ever need to.\n\n const INC: u64 = 11634580027462260723;\n\n rand_pcg::Pcg32::new(seed, INC)\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_distr/tests/value_stability.rs", "rank": 8, "score": 181956.75139399408 }, { "content": "fn get_attr_name(attr: &Attribute) -> String {\n\n attr.path\n\n .get_ident()\n\n .map_or(String::new(), |ident| ident.to_string())\n\n}\n\n\n", "file_path": "src/shuffle.rs", "rank": 9, "score": 172076.52723262477 }, { "content": "/// Implement `fill_bytes` via `next_u64` and `next_u32`, little-endian order.\n\n///\n\n/// The fastest way to fill a slice is usually to work as long as possible with\n\n/// integers. That is why this method mostly uses `next_u64`, and only when\n\n/// there are 4 or less bytes remaining at the end of the slice it uses\n\n/// `next_u32` once.\n\npub fn fill_bytes_via_next<R: RngCore + ?Sized>(rng: &mut R, dest: &mut [u8]) {\n\n let mut left = dest;\n\n while left.len() >= 8 {\n\n let (l, r) = { left }.split_at_mut(8);\n\n left = r;\n\n let chunk: [u8; 8] = rng.next_u64().to_le_bytes();\n\n l.copy_from_slice(&chunk);\n\n }\n\n let n = left.len();\n\n if n > 4 {\n\n let chunk: [u8; 8] = rng.next_u64().to_le_bytes();\n\n left.copy_from_slice(&chunk[..n]);\n\n } else if n > 0 {\n\n let chunk: [u8; 4] = rng.next_u32().to_le_bytes();\n\n left.copy_from_slice(&chunk[..n]);\n\n }\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_core/src/impls.rs", "rank": 10, "score": 167696.06562961618 }, { "content": "fn compile_test(path: &str) -> ExitStatus {\n\n let _lock = lock_filesystem();\n\n\n\n let config = R2D2Config {\n\n dest_name: Some(TEST_DIRECTORY),\n\n cargo_args: None,\n\n need_run: false,\n\n need_obfuscate: true,\n\n obfuscate_dir: Some(path),\n\n stream_output: false,\n\n };\n\n\n\n build(&config).unwrap()\n\n}\n\n\n", "file_path": "tests/test_driver.rs", "rank": 11, "score": 166972.15095646938 }, { "content": "fn functional_test(path: &str) -> ExitStatus {\n\n let _lock = lock_filesystem();\n\n\n\n let config = R2D2Config {\n\n dest_name: Some(TEST_DIRECTORY),\n\n cargo_args: None,\n\n need_run: true,\n\n need_obfuscate: true,\n\n obfuscate_dir: Some(path),\n\n stream_output: false,\n\n };\n\n\n\n build(&config).unwrap()\n\n}\n\n\n\nmod single {\n\n use crate::*;\n\n\n\n #[test]\n\n fn hello_world_compile() {\n", "file_path": "tests/test_driver.rs", "rank": 12, "score": 166972.15095646938 }, { "content": "/// Render a sparkline of `data` into a newly allocated string.\n\npub fn render_f64_as_string(data: &[f64]) -> String {\n\n let cap = required_capacity(data.len());\n\n let mut s = String::with_capacity(cap);\n\n render_f64(data, &mut s);\n\n debug_assert_eq!(s.capacity(), cap);\n\n s\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n #[test]\n\n fn render_u64() {\n\n let data = [2, 250, 670, 890, 2, 430, 11, 908, 123, 57];\n\n let mut s = String::with_capacity(super::required_capacity(data.len()));\n\n super::render_u64(&data, &mut s);\n\n println!(\"{}\", s);\n\n assert_eq!(\"▁▂▆▇▁▄▁█▁▁\", &s);\n\n }\n\n\n\n #[test]\n", "file_path": "tests/complex/rand/rand_distr/tests/sparkline.rs", "rank": 13, "score": 161470.10360984172 }, { "content": "/// Render a sparkline of `data` into a newly allocated string.\n\npub fn render_u64_as_string(data: &[u64]) -> String {\n\n let cap = required_capacity(data.len());\n\n let mut s = String::with_capacity(cap);\n\n render_u64(data, &mut s);\n\n debug_assert_eq!(s.capacity(), cap);\n\n s\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_distr/tests/sparkline.rs", "rank": 14, "score": 161470.10360984172 }, { "content": "// Run a single simulation of the Monty Hall problem.\n\nfn simulate<R: Rng>(random_door: &Uniform<u32>, rng: &mut R) -> SimulationResult {\n\n let car = random_door.sample(rng);\n\n\n\n // This is our initial choice\n\n let mut choice = random_door.sample(rng);\n\n\n\n // The game host opens a door\n\n let open = game_host_open(car, choice, rng);\n\n\n\n // Shall we switch?\n\n let switch = rng.gen();\n\n if switch {\n\n choice = switch_door(choice, open);\n\n }\n\n\n\n SimulationResult {\n\n win: choice == car,\n\n switch,\n\n }\n\n}\n\n\n", "file_path": "tests/complex/rand/examples/monty-hall.rs", "rank": 15, "score": 157427.47716006348 }, { "content": "/// Implement `fill_bytes` by reading chunks from the output buffer of a block\n\n/// based RNG.\n\n///\n\n/// The return values are `(consumed_u32, filled_u8)`.\n\n///\n\n/// `filled_u8` is the number of filled bytes in `dest`, which may be less than\n\n/// the length of `dest`.\n\n/// `consumed_u32` is the number of words consumed from `src`, which is the same\n\n/// as `filled_u8 / 4` rounded up.\n\n///\n\n/// # Example\n\n/// (from `IsaacRng`)\n\n///\n\n/// ```ignore\n\n/// fn fill_bytes(&mut self, dest: &mut [u8]) {\n\n/// let mut read_len = 0;\n\n/// while read_len < dest.len() {\n\n/// if self.index >= self.rsl.len() {\n\n/// self.isaac();\n\n/// }\n\n///\n\n/// let (consumed_u32, filled_u8) =\n\n/// impls::fill_via_u32_chunks(&mut self.rsl[self.index..],\n\n/// &mut dest[read_len..]);\n\n///\n\n/// self.index += consumed_u32;\n\n/// read_len += filled_u8;\n\n/// }\n\n/// }\n\n/// ```\n\npub fn fill_via_u32_chunks(src: &[u32], dest: &mut [u8]) -> (usize, usize) {\n\n fill_via_chunks(src, dest)\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_core/src/impls.rs", "rank": 17, "score": 156795.79655065638 }, { "content": "/// Implement `fill_bytes` by reading chunks from the output buffer of a block\n\n/// based RNG.\n\n///\n\n/// The return values are `(consumed_u64, filled_u8)`.\n\n/// `filled_u8` is the number of filled bytes in `dest`, which may be less than\n\n/// the length of `dest`.\n\n/// `consumed_u64` is the number of words consumed from `src`, which is the same\n\n/// as `filled_u8 / 8` rounded up.\n\n///\n\n/// See `fill_via_u32_chunks` for an example.\n\npub fn fill_via_u64_chunks(src: &[u64], dest: &mut [u8]) -> (usize, usize) {\n\n fill_via_chunks(src, dest)\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_core/src/impls.rs", "rank": 18, "score": 156783.69864844374 }, { "content": "fn fill_via_chunks<T: Observable>(src: &[T], dest: &mut [u8]) -> (usize, usize) {\n\n let size = core::mem::size_of::<T>();\n\n let byte_len = min(src.len() * size, dest.len());\n\n let num_chunks = (byte_len + size - 1) / size;\n\n\n\n if cfg!(target_endian = \"little\") {\n\n // On LE we can do a simple copy, which is 25-50% faster:\n\n dest[..byte_len].copy_from_slice(&T::as_byte_slice(&src[..num_chunks])[..byte_len]);\n\n } else {\n\n // This code is valid on all arches, but slower than the above:\n\n let mut i = 0;\n\n let mut iter = dest[..byte_len].chunks_exact_mut(size);\n\n for chunk in &mut iter {\n\n chunk.copy_from_slice(src[i].to_le_bytes().as_ref());\n\n i += 1;\n\n }\n\n let chunk = iter.into_remainder();\n\n if !chunk.is_empty() {\n\n chunk.copy_from_slice(&src[i].to_le_bytes().as_ref()[..chunk.len()]);\n\n }\n\n }\n\n\n\n (num_chunks, byte_len)\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_core/src/impls.rs", "rank": 19, "score": 155112.16375628894 }, { "content": "#[bench]\n\nfn seq_shuffle_100(b: &mut Bencher) {\n\n let mut rng = SmallRng::from_rng(thread_rng()).unwrap();\n\n let x: &mut [usize] = &mut [1; 100];\n\n b.iter(|| {\n\n x.shuffle(&mut rng);\n\n x[0]\n\n })\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/seq.rs", "rank": 20, "score": 154793.50824039622 }, { "content": "/// Implement `next_u64` via `fill_bytes`, little-endian order.\n\npub fn next_u64_via_fill<R: RngCore + ?Sized>(rng: &mut R) -> u64 {\n\n let mut buf = [0; 8];\n\n rng.fill_bytes(&mut buf);\n\n u64::from_le_bytes(buf)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_fill_via_u32_chunks() {\n\n let src = [1, 2, 3];\n\n let mut dst = [0u8; 11];\n\n assert_eq!(fill_via_u32_chunks(&src, &mut dst), (3, 11));\n\n assert_eq!(dst, [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0]);\n\n\n\n let mut dst = [0u8; 13];\n\n assert_eq!(fill_via_u32_chunks(&src, &mut dst), (3, 12));\n\n assert_eq!(dst, [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0]);\n", "file_path": "tests/complex/rand/rand_core/src/impls.rs", "rank": 21, "score": 154566.00033659214 }, { "content": "/// Implement `next_u64` via `next_u32`, little-endian order.\n\npub fn next_u64_via_u32<R: RngCore + ?Sized>(rng: &mut R) -> u64 {\n\n // Use LE; we explicitly generate one value before the next.\n\n let x = u64::from(rng.next_u32());\n\n let y = u64::from(rng.next_u32());\n\n (y << 32) | x\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_core/src/impls.rs", "rank": 22, "score": 154566.00033659214 }, { "content": "/// Implement `next_u32` via `fill_bytes`, little-endian order.\n\npub fn next_u32_via_fill<R: RngCore + ?Sized>(rng: &mut R) -> u32 {\n\n let mut buf = [0; 4];\n\n rng.fill_bytes(&mut buf);\n\n u32::from_le_bytes(buf)\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_core/src/impls.rs", "rank": 23, "score": 154566.00033659214 }, { "content": "// Returns the door the game host opens given our choice and knowledge of\n\n// where the car is. The game host will never open the door with the car.\n\nfn game_host_open<R: Rng>(car: u32, choice: u32, rng: &mut R) -> u32 {\n\n use rand::seq::SliceRandom;\n\n *free_doors(&[car, choice]).choose(rng).unwrap()\n\n}\n\n\n", "file_path": "tests/complex/rand/examples/monty-hall.rs", "rank": 24, "score": 153658.90607471575 }, { "content": "#[bench]\n\nfn misc_bernoulli_const(b: &mut Bencher) {\n\n let mut rng = Pcg32::from_rng(&mut thread_rng()).unwrap();\n\n b.iter(|| {\n\n let d = rand::distributions::Bernoulli::new(0.18).unwrap();\n\n let mut accum = true;\n\n for _ in 0..crate::RAND_BENCH_N {\n\n accum ^= rng.sample(d);\n\n }\n\n accum\n\n })\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/misc.rs", "rank": 25, "score": 152408.51998363313 }, { "content": "#[bench]\n\nfn weighted_index_modification(b: &mut Bencher) {\n\n let mut rng = rand::thread_rng();\n\n let weights = [1u32, 2, 3, 0, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7];\n\n let mut distr = WeightedIndex::new(weights.to_vec()).unwrap();\n\n b.iter(|| {\n\n distr.update_weights(&[(2, &4), (5, &1)]).unwrap();\n\n rng.sample(&distr)\n\n })\n\n}\n", "file_path": "tests/complex/rand/benches/weighted.rs", "rank": 26, "score": 152408.51998363313 }, { "content": "#[bench]\n\nfn seq_iter_choose_from_1000(b: &mut Bencher) {\n\n let mut rng = SmallRng::from_rng(thread_rng()).unwrap();\n\n let x: &mut [usize] = &mut [1; 1000];\n\n for (i, r) in x.iter_mut().enumerate() {\n\n *r = i;\n\n }\n\n b.iter(|| {\n\n let mut s = 0;\n\n for _ in 0..RAND_BENCH_N {\n\n s += x.iter().choose(&mut rng).unwrap();\n\n }\n\n s\n\n });\n\n b.bytes = size_of::<usize>() as u64 * crate::RAND_BENCH_N;\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/seq.rs", "rank": 27, "score": 152408.51998363313 }, { "content": "#[bench]\n\nfn weighted_index_creation(b: &mut Bencher) {\n\n let mut rng = rand::thread_rng();\n\n let weights = [1u32, 2, 4, 0, 5, 1, 7, 1, 2, 3, 4, 5, 6, 7];\n\n b.iter(|| {\n\n let distr = WeightedIndex::new(weights.to_vec()).unwrap();\n\n rng.sample(distr)\n\n })\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/weighted.rs", "rank": 28, "score": 152408.51998363313 }, { "content": "#[bench]\n\nfn seq_slice_choose_1_of_1000(b: &mut Bencher) {\n\n let mut rng = SmallRng::from_rng(thread_rng()).unwrap();\n\n let x: &mut [usize] = &mut [1; 1000];\n\n for (i, r) in x.iter_mut().enumerate() {\n\n *r = i;\n\n }\n\n b.iter(|| {\n\n let mut s = 0;\n\n for _ in 0..RAND_BENCH_N {\n\n s += x.choose(&mut rng).unwrap();\n\n }\n\n s\n\n });\n\n b.bytes = size_of::<usize>() as u64 * crate::RAND_BENCH_N;\n\n}\n\n\n\nmacro_rules! seq_slice_choose_multiple {\n\n ($name:ident, $amount:expr, $length:expr) => {\n\n #[bench]\n\n fn $name(b: &mut Bencher) {\n", "file_path": "tests/complex/rand/benches/seq.rs", "rank": 29, "score": 152408.51998363313 }, { "content": "#[bench]\n\nfn misc_bernoulli_var(b: &mut Bencher) {\n\n let mut rng = Pcg32::from_rng(&mut thread_rng()).unwrap();\n\n b.iter(|| {\n\n let mut accum = true;\n\n let mut p = 0.18;\n\n for _ in 0..crate::RAND_BENCH_N {\n\n let d = Bernoulli::new(p).unwrap();\n\n accum ^= rng.sample(d);\n\n p += 0.0001;\n\n }\n\n accum\n\n })\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/misc.rs", "rank": 30, "score": 152408.51998363313 }, { "content": "#[bench]\n\nfn gen_1kb_u16_fill(b: &mut Bencher) {\n\n let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap();\n\n let mut buf = [0u16; 512];\n\n b.iter(|| {\n\n rng.fill(&mut buf[..]);\n\n buf\n\n });\n\n b.bytes = 1024;\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/misc.rs", "rank": 31, "score": 150124.39703239378 }, { "content": "#[bench]\n\nfn misc_gen_ratio_const(b: &mut Bencher) {\n\n let mut rng = Pcg32::from_rng(&mut thread_rng()).unwrap();\n\n b.iter(|| {\n\n let mut accum = true;\n\n for _ in 0..crate::RAND_BENCH_N {\n\n accum ^= rng.gen_ratio(2, 3);\n\n }\n\n accum\n\n })\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/misc.rs", "rank": 32, "score": 150124.39703239378 }, { "content": "#[bench]\n\nfn seq_iter_choose_multiple_10_of_100(b: &mut Bencher) {\n\n let mut rng = SmallRng::from_rng(thread_rng()).unwrap();\n\n let x: &[usize] = &[1; 100];\n\n b.iter(|| x.iter().cloned().choose_multiple(&mut rng, 10))\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/seq.rs", "rank": 33, "score": 150124.39703239375 }, { "content": "#[bench]\n\nfn seq_iter_unhinted_choose_from_1000(b: &mut Bencher) {\n\n let mut rng = SmallRng::from_rng(thread_rng()).unwrap();\n\n let x: &[usize] = &[1; 1000];\n\n b.iter(|| {\n\n UnhintedIterator { iter: x.iter() }\n\n .choose(&mut rng)\n\n .unwrap()\n\n })\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/seq.rs", "rank": 34, "score": 150124.39703239375 }, { "content": "#[bench]\n\nfn misc_gen_ratio_var(b: &mut Bencher) {\n\n let mut rng = Pcg32::from_rng(&mut thread_rng()).unwrap();\n\n b.iter(|| {\n\n let mut accum = true;\n\n for i in 2..(crate::RAND_BENCH_N as u32 + 2) {\n\n accum ^= rng.gen_ratio(i, i + 1);\n\n }\n\n accum\n\n })\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/misc.rs", "rank": 35, "score": 150124.39703239378 }, { "content": "#[bench]\n\nfn gen_1kb_u64_fill(b: &mut Bencher) {\n\n let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap();\n\n let mut buf = [0u64; 128];\n\n b.iter(|| {\n\n rng.fill(&mut buf[..]);\n\n buf\n\n });\n\n b.bytes = 1024;\n\n}\n", "file_path": "tests/complex/rand/benches/misc.rs", "rank": 36, "score": 150124.39703239378 }, { "content": "#[bench]\n\nfn gen_1kb_u64_iter_repeat(b: &mut Bencher) {\n\n use core::iter;\n\n let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap();\n\n b.iter(|| {\n\n let v: Vec<u64> = iter::repeat(()).map(|()| rng.gen()).take(128).collect();\n\n v\n\n });\n\n b.bytes = 1024;\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/misc.rs", "rank": 37, "score": 147934.87323583412 }, { "content": "#[bench]\n\nfn gen_1kb_u16_sample_iter(b: &mut Bencher) {\n\n let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap();\n\n b.iter(|| {\n\n let v: Vec<u16> = Standard.sample_iter(&mut rng).take(512).collect();\n\n v\n\n });\n\n b.bytes = 1024;\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/misc.rs", "rank": 38, "score": 147934.87323583412 }, { "content": "#[bench]\n\nfn gen_1kb_u16_gen_array(b: &mut Bencher) {\n\n let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap();\n\n b.iter(|| {\n\n // max supported array length is 32!\n\n let v: [[u16; 32]; 16] = rng.gen();\n\n v\n\n });\n\n b.bytes = 1024;\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/misc.rs", "rank": 39, "score": 147934.87323583412 }, { "content": "#[bench]\n\nfn gen_1kb_u64_sample_iter(b: &mut Bencher) {\n\n let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap();\n\n b.iter(|| {\n\n let v: Vec<u64> = Standard.sample_iter(&mut rng).take(128).collect();\n\n v\n\n });\n\n b.bytes = 1024;\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/misc.rs", "rank": 40, "score": 147934.87323583412 }, { "content": "#[bench]\n\nfn seq_iter_choose_multiple_fill_10_of_100(b: &mut Bencher) {\n\n let mut rng = SmallRng::from_rng(thread_rng()).unwrap();\n\n let x: &[usize] = &[1; 100];\n\n let mut buf = [0; 10];\n\n b.iter(|| x.iter().cloned().choose_multiple_fill(&mut rng, &mut buf))\n\n}\n\n\n\nmacro_rules! sample_indices {\n\n ($name:ident, $fn:ident, $amount:expr, $length:expr) => {\n\n #[bench]\n\n fn $name(b: &mut Bencher) {\n\n let mut rng = SmallRng::from_rng(thread_rng()).unwrap();\n\n b.iter(|| index::$fn(&mut rng, $length, $amount))\n\n }\n\n };\n\n}\n\n\n\nsample_indices!(misc_sample_indices_1_of_1k, sample, 1, 1000);\n\nsample_indices!(misc_sample_indices_10_of_1k, sample, 10, 1000);\n\nsample_indices!(misc_sample_indices_100_of_1k, sample, 100, 1000);\n", "file_path": "tests/complex/rand/benches/seq.rs", "rank": 41, "score": 147934.87323583412 }, { "content": "#[bench]\n\nfn gen_1kb_u16_iter_repeat(b: &mut Bencher) {\n\n use core::iter;\n\n let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap();\n\n b.iter(|| {\n\n let v: Vec<u16> = iter::repeat(()).map(|()| rng.gen()).take(512).collect();\n\n v\n\n });\n\n b.bytes = 1024;\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/misc.rs", "rank": 42, "score": 147934.87323583412 }, { "content": "#[bench]\n\nfn seq_iter_window_hinted_choose_from_1000(b: &mut Bencher) {\n\n let mut rng = SmallRng::from_rng(thread_rng()).unwrap();\n\n let x: &[usize] = &[1; 1000];\n\n b.iter(|| {\n\n WindowHintedIterator {\n\n iter: x.iter(),\n\n window_size: 7,\n\n }\n\n .choose(&mut rng)\n\n })\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/seq.rs", "rank": 43, "score": 147934.87323583412 }, { "content": "#[bench]\n\nfn gen_1kb_u64_gen_array(b: &mut Bencher) {\n\n let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap();\n\n b.iter(|| {\n\n // max supported array length is 32!\n\n let v: [[u64; 32]; 4] = rng.gen();\n\n v\n\n });\n\n b.bytes = 1024;\n\n}\n\n\n", "file_path": "tests/complex/rand/benches/misc.rs", "rank": 44, "score": 147934.87323583412 }, { "content": "struct SimulationResult {\n\n win: bool,\n\n switch: bool,\n\n}\n\n\n", "file_path": "tests/complex/rand/examples/monty-hall.rs", "rank": 45, "score": 146602.82809200988 }, { "content": "#[cfg(feature = \"std\")]\n\n#[cfg_attr(doc_cfg, doc(cfg(feature = \"std\")))]\n\npub fn sample_weighted<R, F, X>(\n\n rng: &mut R, length: usize, weight: F, amount: usize,\n\n) -> Result<IndexVec, WeightedError>\n\nwhere\n\n R: Rng + ?Sized,\n\n F: Fn(usize) -> X,\n\n X: Into<f64>,\n\n{\n\n if length > (core::u32::MAX as usize) {\n\n sample_efraimidis_spirakis(rng, length, weight, amount)\n\n } else {\n\n assert!(amount <= core::u32::MAX as usize);\n\n let amount = amount as u32;\n\n let length = length as u32;\n\n sample_efraimidis_spirakis(rng, length, weight, amount)\n\n }\n\n}\n\n\n\n\n\n/// Randomly sample exactly `amount` distinct indices from `0..length`, and\n", "file_path": "tests/complex/rand/src/seq/index.rs", "rank": 46, "score": 146059.76829172584 }, { "content": "#[cfg(feature = \"std\")]\n\nfn sample_efraimidis_spirakis<R, F, X, N>(\n\n rng: &mut R, length: N, weight: F, amount: N,\n\n) -> Result<IndexVec, WeightedError>\n\nwhere\n\n R: Rng + ?Sized,\n\n F: Fn(usize) -> X,\n\n X: Into<f64>,\n\n N: UInt,\n\n IndexVec: From<Vec<N>>,\n\n{\n\n if amount == N::zero() {\n\n return Ok(IndexVec::U32(Vec::new()));\n\n }\n\n\n\n if amount > length {\n\n panic!(\"`amount` of samples must be less than or equal to `length`\");\n\n }\n\n\n\n struct Element<N> {\n\n index: N,\n", "file_path": "tests/complex/rand/src/seq/index.rs", "rank": 47, "score": 143955.2869175397 }, { "content": "pub fn encrypt_memory<Cipher>(data: &[u8]) -> MemoryEncryptionCtx<Cipher>\n\nwhere\n\n Cipher: NewAead,\n\n Cipher: Aead,\n\n Cipher::KeySize: IsEqual<U32, Output = True>,\n\n //TODO: Should probably redo nonce generation to be generic enough for things like AES-GCM that use 96 bit nonces\n\n Cipher::NonceSize: IsEqual<U24, Output = True>,\n\n{\n\n let mut key: Key<Cipher> = Default::default();\n\n OsRng.fill_bytes(&mut key);\n\n let cipher = Cipher::new(&key);\n\n let mut nonce: Nonce<Cipher> = Default::default();\n\n OsRng.fill_bytes(&mut nonce);\n\n\n\n let ciphertext = cipher.encrypt(&nonce, data).unwrap();\n\n\n\n //println!(\"We are encrypting data: {:#x?}\", data);\n\n //println!(\"Resulting ciphertext: {:#x?}\", ciphertext);\n\n\n\n MemoryEncryptionCtx::<Cipher> {\n\n key,\n\n nonce,\n\n ciphertext,\n\n }\n\n}\n\n\n", "file_path": "src/crypto.rs", "rank": 48, "score": 143782.85645563394 }, { "content": "pub fn obfuscate(input: &String) -> (String, Shatter) {\n\n let mut input2 = syn::parse_file(&input).unwrap();\n\n\n\n //eprintln!(\"INPUT: {:#?}\", input2);\n\n //eprintln!(\"INFORMAT: {}\", prettyplease::unparse(&input2));\n\n\n\n shuffle(&mut input2);\n\n encrypt_strings(&mut input2);\n\n let shatter = shatter(&mut input2);\n\n\n\n //eprintln!(\"OUTPUT: {:#?}\", input2);\n\n //eprintln!(\"OUTFORMAT: {}\", prettyplease::unparse(&input2));\n\n\n\n (prettyplease::unparse(&input2), shatter)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 49, "score": 143590.0505124228 }, { "content": "fn main() {\n\n #[shuffle]\n\n let w = 1;\n\n #[shuffle]\n\n let x = 2;\n\n #[shuffle]\n\n let y = 3;\n\n #[shuffle]\n\n let z = 4;\n\n\n\n eprintln!(\"My values are {w}, {x}, {y}, {z}\");\n\n}\n", "file_path": "tests/single/05-shuffle_let/src/main.rs", "rank": 50, "score": 141186.25959910933 }, { "content": "fn bench(c: &mut Criterion<CyclesPerByte>) {\n\n {\n\n let mut g = c.benchmark_group(\"exp\");\n\n distr_float!(g, \"exp\", f64, Exp::new(1.23 * 4.56).unwrap());\n\n distr_float!(g, \"exp1_specialized\", f64, Exp1);\n\n distr_float!(g, \"exp1_general\", f64, Exp::new(1.).unwrap());\n\n }\n\n\n\n {\n\n let mut g = c.benchmark_group(\"normal\");\n\n distr_float!(g, \"normal\", f64, Normal::new(-1.23, 4.56).unwrap());\n\n distr_float!(g, \"standardnormal_specialized\", f64, StandardNormal);\n\n distr_float!(g, \"standardnormal_general\", f64, Normal::new(0., 1.).unwrap());\n\n distr_float!(g, \"log_normal\", f64, LogNormal::new(-1.23, 4.56).unwrap());\n\n g.throughput(Throughput::Bytes(size_of::<f64>() as u64 * RAND_BENCH_N));\n\n g.bench_function(\"iter\", |c| {\n\n let mut rng = Pcg64Mcg::from_entropy();\n\n let distr = Normal::new(-2.71828, 3.14159).unwrap();\n\n let mut iter = distr.sample_iter(&mut rng);\n\n\n", "file_path": "tests/complex/rand/rand_distr/benches/src/distributions.rs", "rank": 51, "score": 140743.59395395612 }, { "content": "fn main() -> io::Result<()> {\n\n let matches = app_from_crate!()\n\n .global_setting(AppSettings::PropagateVersion)\n\n .global_setting(AppSettings::UseLongFormatForHelpSubcommand)\n\n .setting(AppSettings::SubcommandRequiredElseHelp)\n\n .subcommand(\n\n App::new(\"build\")\n\n .about(\"Compile a local package and all of its dependencies\")\n\n .arg(\n\n arg!(args: [args])\n\n .help(\"Arguments to pass to cargo\")\n\n .multiple_occurrences(true)\n\n .last(true)\n\n .required(false),\n\n ),\n\n )\n\n .subcommand(\n\n App::new(\"check\")\n\n .about(\n\n \"Analyze the current package and report errors, but don't build object files\",\n", "file_path": "src/main.rs", "rank": 52, "score": 139437.15292166607 }, { "content": "#[inline]\n\npub fn read_u32_into(src: &[u8], dst: &mut [u32]) {\n\n assert!(src.len() >= 4 * dst.len());\n\n for (out, chunk) in dst.iter_mut().zip(src.chunks_exact(4)) {\n\n *out = u32::from_le_bytes(chunk.try_into().unwrap());\n\n }\n\n}\n\n\n\n/// Reads unsigned 64 bit integers from `src` into `dst`.\n", "file_path": "tests/complex/rand/rand_core/src/le.rs", "rank": 53, "score": 133779.66537439695 }, { "content": "#[inline]\n\npub fn read_u64_into(src: &[u8], dst: &mut [u64]) {\n\n assert!(src.len() >= 8 * dst.len());\n\n for (out, chunk) in dst.iter_mut().zip(src.chunks_exact(8)) {\n\n *out = u64::from_le_bytes(chunk.try_into().unwrap());\n\n }\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_core/src/le.rs", "rank": 54, "score": 133779.66537439695 }, { "content": "/// Calculate the required capacity for the sparkline, given the length of the\n\n/// input data.\n\npub fn required_capacity(len: usize) -> usize {\n\n len * TICKS[0].len_utf8()\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_distr/tests/sparkline.rs", "rank": 55, "score": 127915.21073131854 }, { "content": "//TODO: This and the shuffle finding are inefficient, try and remove all the cloning\n\nfn stmt_contains_shuffle_attr(stmt: &Stmt) -> bool {\n\n let mut cloned = stmt.to_owned();\n\n let cloned_attrs = cloned.get_attrs();\n\n if cloned_attrs.is_none() {\n\n return false;\n\n }\n\n let cloned_attrs_ref = cloned_attrs.unwrap();\n\n contains_shuffle_attr(cloned_attrs_ref)\n\n}\n\n\n", "file_path": "src/shuffle.rs", "rank": 56, "score": 127835.88251154618 }, { "content": "pub fn shuffle(input: &mut File) {\n\n Shuffle.visit_file_mut(input);\n\n}\n", "file_path": "src/shuffle.rs", "rank": 57, "score": 127256.676756378 }, { "content": "#[allow(clippy::many_single_char_names)]\n\n#[inline(always)]\n\nfn refill_wide_impl<Mach: Machine>(\n\n m: Mach, state: &mut ChaCha, drounds: u32, out: &mut [u32; BUFSZ],\n\n) {\n\n let k = m.vec([0x6170_7865, 0x3320_646e, 0x7962_2d32, 0x6b20_6574]);\n\n let b = m.unpack(state.b);\n\n let c = m.unpack(state.c);\n\n let mut x = State {\n\n a: Mach::u32x4x4::from_lanes([k, k, k, k]),\n\n b: Mach::u32x4x4::from_lanes([b, b, b, b]),\n\n c: Mach::u32x4x4::from_lanes([c, c, c, c]),\n\n d: d0123(m, state.d),\n\n };\n\n for _ in 0..drounds {\n\n x = round(x);\n\n x = undiagonalize(round(diagonalize(x)));\n\n }\n\n let kk = Mach::u32x4x4::from_lanes([k, k, k, k]);\n\n let sb = m.unpack(state.b);\n\n let sb = Mach::u32x4x4::from_lanes([sb, sb, sb, sb]);\n\n let sc = m.unpack(state.c);\n", "file_path": "tests/complex/rand/rand_chacha/src/guts.rs", "rank": 59, "score": 125062.13970760752 }, { "content": "fn contains_shuffle_attr(attrs: &Vec<Attribute>) -> bool {\n\n for attr in attrs {\n\n if is_shuffle_attr(&get_attr_name(&attr)) {\n\n return true;\n\n }\n\n }\n\n return false;\n\n}\n\n\n", "file_path": "src/shuffle.rs", "rank": 60, "score": 124685.52817994912 }, { "content": "#[inline]\n\nfn gen_index<R: Rng + ?Sized>(rng: &mut R, ubound: usize) -> usize {\n\n if ubound <= (core::u32::MAX as usize) {\n\n rng.gen_range(0..ubound as u32) as usize\n\n } else {\n\n rng.gen_range(0..ubound)\n\n }\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n #[cfg(feature = \"alloc\")] use crate::Rng;\n\n #[cfg(all(feature = \"alloc\", not(feature = \"std\")))] use alloc::vec::Vec;\n\n\n\n #[test]\n\n fn test_slice_choose() {\n\n let mut r = crate::test::rng(107);\n\n let chars = [\n\n 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',\n", "file_path": "tests/complex/rand/src/seq/mod.rs", "rank": 61, "score": 124521.27699663631 }, { "content": "#[inline(always)]\n\nfn output_dxsm(state: u128) -> u64 {\n\n // See https://github.com/imneme/pcg-cpp/blob/ffd522e7188bef30a00c74dc7eb9de5faff90092/include/pcg_random.hpp#L1016\n\n // for a short discussion of the construction and its original implementation.\n\n let mut hi = (state >> 64) as u64;\n\n let mut lo = state as u64;\n\n\n\n lo |= 1;\n\n hi ^= hi >> 32;\n\n hi = hi.wrapping_mul(MULTIPLIER);\n\n hi ^= hi >> 48;\n\n hi = hi.wrapping_mul(lo);\n\n\n\n hi\n\n}\n", "file_path": "tests/complex/rand/rand_pcg/src/pcg128cm.rs", "rank": 62, "score": 123516.96977193466 }, { "content": "/// Randomly sample exactly `amount` indices from `0..length`, using Floyd's\n\n/// combination algorithm.\n\n///\n\n/// The output values are fully shuffled. (Overhead is under 50%.)\n\n///\n\n/// This implementation uses `O(amount)` memory and `O(amount^2)` time.\n\nfn sample_floyd<R>(rng: &mut R, length: u32, amount: u32) -> IndexVec\n\nwhere R: Rng + ?Sized {\n\n // For small amount we use Floyd's fully-shuffled variant. For larger\n\n // amounts this is slow due to Vec::insert performance, so we shuffle\n\n // afterwards. Benchmarks show little overhead from extra logic.\n\n let floyd_shuffle = amount < 50;\n\n\n\n debug_assert!(amount <= length);\n\n let mut indices = Vec::with_capacity(amount as usize);\n\n for j in length - amount..length {\n\n let t = rng.gen_range(0..=j);\n\n if floyd_shuffle {\n\n if let Some(pos) = indices.iter().position(|&x| x == t) {\n\n indices.insert(pos, j);\n\n continue;\n\n }\n\n } else if indices.contains(&t) {\n\n indices.push(j);\n\n continue;\n\n }\n", "file_path": "tests/complex/rand/src/seq/index.rs", "rank": 63, "score": 122802.2836603257 }, { "content": "/// Randomly sample exactly `amount` indices from `0..length`, using an inplace\n\n/// partial Fisher-Yates method.\n\n/// Sample an amount of indices using an inplace partial fisher yates method.\n\n///\n\n/// This allocates the entire `length` of indices and randomizes only the first `amount`.\n\n/// It then truncates to `amount` and returns.\n\n///\n\n/// This method is not appropriate for large `length` and potentially uses a lot\n\n/// of memory; because of this we only implement for `u32` index (which improves\n\n/// performance in all cases).\n\n///\n\n/// Set-up is `O(length)` time and memory and shuffling is `O(amount)` time.\n\nfn sample_inplace<R>(rng: &mut R, length: u32, amount: u32) -> IndexVec\n\nwhere R: Rng + ?Sized {\n\n debug_assert!(amount <= length);\n\n let mut indices: Vec<u32> = Vec::with_capacity(length as usize);\n\n indices.extend(0..length);\n\n for i in 0..amount {\n\n let j: u32 = rng.gen_range(i..length);\n\n indices.swap(i as usize, j as usize);\n\n }\n\n indices.truncate(amount as usize);\n\n debug_assert_eq!(indices.len(), amount as usize);\n\n IndexVec::from(indices)\n\n}\n\n\n", "file_path": "tests/complex/rand/src/seq/index.rs", "rank": 64, "score": 122801.20325872088 }, { "content": "//TODO: Add configuration for conditional shatter injection\n\npub fn shatter(input: &mut File) -> Shatter {\n\n let mut state = Shatter {\n\n inside_unsafe_block: false,\n\n integrity_checks: Vec::new(),\n\n };\n\n Shatter::visit_file_mut(&mut state, input);\n\n\n\n state\n\n}\n\n\n\n\n", "file_path": "src/shatter.rs", "rank": 65, "score": 122640.9022195175 }, { "content": "#[inline(always)]\n\nfn output_xsl_rr(state: u128) -> u64 {\n\n // Output function XSL RR (\"xorshift low (bits), random rotation\")\n\n // Constants are for 128-bit state, 64-bit output\n\n const XSHIFT: u32 = 64; // (128 - 64 + 64) / 2\n\n const ROTATE: u32 = 122; // 128 - 6\n\n\n\n let rot = (state >> ROTATE) as u32;\n\n let xsl = ((state >> XSHIFT) as u64) ^ (state as u64);\n\n xsl.rotate_right(rot)\n\n}\n", "file_path": "tests/complex/rand/rand_pcg/src/pcg128.rs", "rank": 66, "score": 121412.3947287834 }, { "content": "/// Randomly sample exactly `amount` distinct indices from `0..length`, and\n\n/// return them in random order (fully shuffled).\n\n///\n\n/// This method is used internally by the slice sampling methods, but it can\n\n/// sometimes be useful to have the indices themselves so this is provided as\n\n/// an alternative.\n\n///\n\n/// The implementation used is not specified; we automatically select the\n\n/// fastest available algorithm for the `length` and `amount` parameters\n\n/// (based on detailed profiling on an Intel Haswell CPU). Roughly speaking,\n\n/// complexity is `O(amount)`, except that when `amount` is small, performance\n\n/// is closer to `O(amount^2)`, and when `length` is close to `amount` then\n\n/// `O(length)`.\n\n///\n\n/// Note that performance is significantly better over `u32` indices than over\n\n/// `u64` indices. Because of this we hide the underlying type behind an\n\n/// abstraction, `IndexVec`.\n\n///\n\n/// If an allocation-free `no_std` function is required, it is suggested\n\n/// to adapt the internal `sample_floyd` implementation.\n\n///\n\n/// Panics if `amount > length`.\n\npub fn sample<R>(rng: &mut R, length: usize, amount: usize) -> IndexVec\n\nwhere R: Rng + ?Sized {\n\n if amount > length {\n\n panic!(\"`amount` of samples must be less than or equal to `length`\");\n\n }\n\n if length > (::core::u32::MAX as usize) {\n\n // We never want to use inplace here, but could use floyd's alg\n\n // Lazy version: always use the cache alg.\n\n return sample_rejection(rng, length, amount);\n\n }\n\n let amount = amount as u32;\n\n let length = length as u32;\n\n\n\n // Choice of algorithm here depends on both length and amount. See:\n\n // https://github.com/rust-random/rand/pull/479\n\n // We do some calculations with f32. Accuracy is not very important.\n\n\n\n if amount < 163 {\n\n const C: [[f32; 2]; 2] = [[1.6, 8.0 / 45.0], [10.0, 70.0 / 9.0]];\n\n let j = if length < 500_000 { 0 } else { 1 };\n", "file_path": "tests/complex/rand/src/seq/index.rs", "rank": 67, "score": 121306.89298548971 }, { "content": "// Returns the door we switch to, given our current choice and\n\n// the open door. There will only be one valid door.\n\nfn switch_door(choice: u32, open: u32) -> u32 {\n\n free_doors(&[choice, open])[0]\n\n}\n\n\n", "file_path": "tests/complex/rand/examples/monty-hall.rs", "rank": 68, "score": 118860.16431749114 }, { "content": "pub fn generate_temp_folder_name(name: Option<&str>) -> Utf8PathBuf {\n\n let mut output = Utf8PathBuf::from_path_buf(env::temp_dir()).unwrap();\n\n output.push(name.unwrap_or(\".r2d2_build_dir\"));\n\n output\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 69, "score": 115240.42158269743 }, { "content": "pub fn build(config: &R2D2Config) -> io::Result<ExitStatus> {\n\n let src = get_src_dir();\n\n let mut dest = generate_temp_folder_name(config.dest_name);\n\n\n\n if let Ok(_) = std::fs::metadata(&dest) {\n\n //Clean up the folder if it already exists\n\n let _ = fs::remove_dir_all(&dest);\n\n }\n\n\n\n DirBuilder::new().recursive(true).create(&dest)?;\n\n\n\n copy_dir(&src.workspace_root, &dest)?;\n\n\n\n if let Some(partial) = config.obfuscate_dir {\n\n let mut true_dest_str = String::from(dest.as_str());\n\n true_dest_str.push(path::MAIN_SEPARATOR);\n\n true_dest_str.push_str(partial);\n\n\n\n dest = Utf8PathBuf::from(true_dest_str);\n\n }\n", "file_path": "src/lib.rs", "rank": 70, "score": 114395.07103281128 }, { "content": "/// Convert a `f64` to an `i64`, panicking on overflow.\n\nfn f64_to_i64(x: f64) -> i64 {\n\n assert!(x < (core::i64::MAX as f64));\n\n x as i64\n\n}\n\n\n\nimpl Distribution<u64> for Binomial {\n\n #[allow(clippy::many_single_char_names)] // Same names as in the reference.\n\n fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u64 {\n\n // Handle these values directly.\n\n if self.p == 0.0 {\n\n return 0;\n\n } else if self.p == 1.0 {\n\n return self.n;\n\n }\n\n\n\n // The binomial distribution is symmetrical with respect to p -> 1-p,\n\n // k -> n-k switch p so that it is less than 0.5 - this allows for lower\n\n // expected values we will just invert the result at the end\n\n let p = if self.p <= 0.5 { self.p } else { 1.0 - self.p };\n\n\n", "file_path": "tests/complex/rand/rand_distr/src/binomial.rs", "rank": 71, "score": 111627.12056082586 }, { "content": "//TODO: Only copy differences with hashes/mtime checks\n\n//TODO: This needs to be optimized and cleaned up\n\n//TODO: Fix the error checking\n\npub fn copy_dir(from: &Utf8PathBuf, to: &Utf8PathBuf) -> io::Result<()> {\n\n let files: Vec<_> = WalkDir::new(from)\n\n .into_iter()\n\n .filter_entry(|e| {\n\n !e.file_name()\n\n .to_str()\n\n .map(|s| s.starts_with(\".\"))\n\n .unwrap_or(false)\n\n })\n\n .collect();\n\n\n\n if files.iter().all(|e| !e.is_ok()) {\n\n return Err(io::Error::new(\n\n ErrorKind::PermissionDenied,\n\n \"Some files can't be accessed\",\n\n ));\n\n }\n\n\n\n let (dirs, files): (Vec<Utf8PathBuf>, Vec<Utf8PathBuf>) = files\n\n .into_iter()\n", "file_path": "src/lib.rs", "rank": 72, "score": 110701.73855059085 }, { "content": "pub fn obfuscate_dir(dir: &Utf8PathBuf) -> io::Result<Vec<Shatter>> {\n\n //WalkDir filter_entry will prevent the directory from being touched, so have to filter\n\n //manually\n\n\n\n let mut shatter_states: Vec<Shatter> = Vec::new();\n\n\n\n for file in WalkDir::new(dir) {\n\n let file_path = file?.into_path();\n\n if file_path.to_str().unwrap_or_default().ends_with(\".rs\") {\n\n let contents = fs::read_to_string(&file_path)?;\n\n let (obfuscated, shatter_state) = obfuscate(&contents);\n\n shatter_states.push(shatter_state);\n\n fs::write(&file_path, &obfuscated)?;\n\n }\n\n }\n\n Ok(shatter_states)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 73, "score": 110697.06301466672 }, { "content": "pub fn get_src_dir() -> SourceInformation {\n\n let metadata = MetadataCommand::new().exec().unwrap();\n\n SourceInformation {\n\n workspace_root: metadata.workspace_root,\n\n target_dir: metadata.target_directory,\n\n }\n\n}\n\n\n\npub struct R2D2Config<'a> {\n\n pub dest_name: Option<&'a str>,\n\n pub cargo_args: Option<Vec<&'a str>>,\n\n pub need_run: bool,\n\n pub need_obfuscate: bool,\n\n pub obfuscate_dir: Option<&'a str>,\n\n pub stream_output: bool,\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 74, "score": 105573.88279165575 }, { "content": "#[test]\n\nfn test_lcg128cmdxsm64_construction() {\n\n // Test that various construction techniques produce a working RNG.\n\n #[rustfmt::skip]\n\n let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16,\n\n 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32];\n\n let mut rng1 = Lcg128CmDxsm64::from_seed(seed);\n\n assert_eq!(rng1.next_u64(), 12201417210360370199);\n\n\n\n let mut rng2 = Lcg128CmDxsm64::from_rng(&mut rng1).unwrap();\n\n assert_eq!(rng2.next_u64(), 11487972556150888383);\n\n\n\n let mut rng3 = Lcg128CmDxsm64::seed_from_u64(0);\n\n assert_eq!(rng3.next_u64(), 4111470453933123814);\n\n\n\n // This is the same as Lcg128CmDxsm64, so we only have a single test:\n\n let mut rng4 = Pcg64Dxsm::seed_from_u64(0);\n\n assert_eq!(rng4.next_u64(), 4111470453933123814);\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_pcg/tests/lcg128cmdxsm64.rs", "rank": 75, "score": 104164.96528912253 }, { "content": "#[test]\n\nfn test_lcg128cmdxsm64_advancing() {\n\n for seed in 0..20 {\n\n let mut rng1 = Lcg128CmDxsm64::seed_from_u64(seed);\n\n let mut rng2 = rng1.clone();\n\n for _ in 0..20 {\n\n rng1.next_u64();\n\n }\n\n rng2.advance(20);\n\n assert_eq!(rng1, rng2);\n\n }\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_pcg/tests/lcg128cmdxsm64.rs", "rank": 76, "score": 104164.96528912253 }, { "content": "#[test]\n\nfn test_lcg128xsl64_reference() {\n\n // Numbers copied from official test suite (C version).\n\n let mut rng = Lcg128Xsl64::new(42, 54);\n\n\n\n let mut results = [0u64; 6];\n\n for i in results.iter_mut() {\n\n *i = rng.next_u64();\n\n }\n\n let expected: [u64; 6] = [\n\n 0x86b1da1d72062b68,\n\n 0x1304aa46c9853d39,\n\n 0xa3670e9e0dd50358,\n\n 0xf9090e529a7dae00,\n\n 0xc85b9fd837996f2c,\n\n 0x606121f8e3919196,\n\n ];\n\n assert_eq!(results, expected);\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_pcg/tests/lcg128xsl64.rs", "rank": 77, "score": 104164.96528912253 }, { "content": "#[test]\n\nfn test_lcg128xsl64_advancing() {\n\n for seed in 0..20 {\n\n let mut rng1 = Lcg128Xsl64::seed_from_u64(seed);\n\n let mut rng2 = rng1.clone();\n\n for _ in 0..20 {\n\n rng1.next_u64();\n\n }\n\n rng2.advance(20);\n\n assert_eq!(rng1, rng2);\n\n }\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_pcg/tests/lcg128xsl64.rs", "rank": 78, "score": 104164.96528912253 }, { "content": "#[test]\n\nfn test_lcg128xsl64_construction() {\n\n // Test that various construction techniques produce a working RNG.\n\n #[rustfmt::skip]\n\n let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16,\n\n 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32];\n\n let mut rng1 = Lcg128Xsl64::from_seed(seed);\n\n assert_eq!(rng1.next_u64(), 8740028313290271629);\n\n\n\n let mut rng2 = Lcg128Xsl64::from_rng(&mut rng1).unwrap();\n\n assert_eq!(rng2.next_u64(), 1922280315005786345);\n\n\n\n let mut rng3 = Lcg128Xsl64::seed_from_u64(0);\n\n assert_eq!(rng3.next_u64(), 2354861276966075475);\n\n\n\n // This is the same as Lcg128Xsl64, so we only have a single test:\n\n let mut rng4 = Pcg64::seed_from_u64(0);\n\n assert_eq!(rng4.next_u64(), 2354861276966075475);\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_pcg/tests/lcg128xsl64.rs", "rank": 79, "score": 104164.96528912253 }, { "content": "#[test]\n\nfn test_mcg128xsl64_advancing() {\n\n for seed in 0..20 {\n\n let mut rng1 = Mcg128Xsl64::seed_from_u64(seed);\n\n let mut rng2 = rng1.clone();\n\n for _ in 0..20 {\n\n rng1.next_u64();\n\n }\n\n rng2.advance(20);\n\n assert_eq!(rng1, rng2);\n\n }\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_pcg/tests/mcg128xsl64.rs", "rank": 80, "score": 104164.96528912253 }, { "content": "#[test]\n\nfn test_mcg128xsl64_reference() {\n\n // Numbers copied from official test suite (C version).\n\n let mut rng = Mcg128Xsl64::new(42);\n\n\n\n let mut results = [0u64; 6];\n\n for i in results.iter_mut() {\n\n *i = rng.next_u64();\n\n }\n\n let expected: [u64; 6] = [\n\n 0x63b4a3a813ce700a,\n\n 0x382954200617ab24,\n\n 0xa7fd85ae3fe950ce,\n\n 0xd715286aa2887737,\n\n 0x60c92fee2e59f32c,\n\n 0x84c4e96beff30017,\n\n ];\n\n assert_eq!(results, expected);\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_pcg/tests/mcg128xsl64.rs", "rank": 81, "score": 104164.96528912253 }, { "content": "#[test]\n\nfn test_lcg64xsh32_construction() {\n\n // Test that various construction techniques produce a working RNG.\n\n let seed = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];\n\n let mut rng1 = Lcg64Xsh32::from_seed(seed);\n\n assert_eq!(rng1.next_u64(), 1204678643940597513);\n\n\n\n let mut rng2 = Lcg64Xsh32::from_rng(&mut rng1).unwrap();\n\n assert_eq!(rng2.next_u64(), 12384929573776311845);\n\n\n\n let mut rng3 = Lcg64Xsh32::seed_from_u64(0);\n\n assert_eq!(rng3.next_u64(), 18195738587432868099);\n\n\n\n // This is the same as Lcg64Xsh32, so we only have a single test:\n\n let mut rng4 = Pcg32::seed_from_u64(0);\n\n assert_eq!(rng4.next_u64(), 18195738587432868099);\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_pcg/tests/lcg64xsh32.rs", "rank": 82, "score": 104164.96528912253 }, { "content": "#[test]\n\nfn test_lcg128cmdxsm64_reference() {\n\n // Numbers determined using `pcg_engines::cm_setseq_dxsm_128_64` from pcg-cpp.\n\n let mut rng = Lcg128CmDxsm64::new(42, 54);\n\n\n\n let mut results = [0u64; 6];\n\n for i in results.iter_mut() {\n\n *i = rng.next_u64();\n\n }\n\n let expected: [u64; 6] = [\n\n 17331114245835578256,\n\n 10267467544499227306,\n\n 9726600296081716989,\n\n 10165951391103677450,\n\n 12131334649314727261,\n\n 10134094537930450875,\n\n ];\n\n assert_eq!(results, expected);\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_pcg/tests/lcg128cmdxsm64.rs", "rank": 83, "score": 104164.96528912253 }, { "content": "#[test]\n\nfn test_mcg128xsl64_construction() {\n\n // Test that various construction techniques produce a working RNG.\n\n let seed = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];\n\n let mut rng1 = Mcg128Xsl64::from_seed(seed);\n\n assert_eq!(rng1.next_u64(), 7071994460355047496);\n\n\n\n let mut rng2 = Mcg128Xsl64::from_rng(&mut rng1).unwrap();\n\n assert_eq!(rng2.next_u64(), 12300796107712034932);\n\n\n\n let mut rng3 = Mcg128Xsl64::seed_from_u64(0);\n\n assert_eq!(rng3.next_u64(), 6198063878555692194);\n\n\n\n // This is the same as Mcg128Xsl64, so we only have a single test:\n\n let mut rng4 = Pcg64Mcg::seed_from_u64(0);\n\n assert_eq!(rng4.next_u64(), 6198063878555692194);\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_pcg/tests/mcg128xsl64.rs", "rank": 84, "score": 104164.96528912253 }, { "content": "#[test]\n\nfn test_lcg64xsh32_reference() {\n\n // Numbers copied from official test suite.\n\n let mut rng = Lcg64Xsh32::new(42, 54);\n\n\n\n let mut results = [0u32; 6];\n\n for i in results.iter_mut() {\n\n *i = rng.next_u32();\n\n }\n\n let expected: [u32; 6] = [\n\n 0xa15c02b7, 0x7b47f409, 0xba1d3330, 0x83d2f293, 0xbfa4784b, 0xcbed606e,\n\n ];\n\n assert_eq!(results, expected);\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_pcg/tests/lcg64xsh32.rs", "rank": 85, "score": 104164.96528912253 }, { "content": "#[test]\n\nfn test_lcg64xsh32_advancing() {\n\n for seed in 0..20 {\n\n let mut rng1 = Lcg64Xsh32::seed_from_u64(seed);\n\n let mut rng2 = rng1.clone();\n\n for _ in 0..20 {\n\n rng1.next_u32();\n\n }\n\n rng2.advance(20);\n\n assert_eq!(rng1, rng2);\n\n }\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_pcg/tests/lcg64xsh32.rs", "rank": 86, "score": 104164.96528912253 }, { "content": "#[cfg(feature = \"serde1\")]\n\n#[test]\n\nfn test_lcg128cmdxsm64_serde() {\n\n use bincode;\n\n use std::io::{BufReader, BufWriter};\n\n\n\n let mut rng = Lcg128CmDxsm64::seed_from_u64(0);\n\n\n\n let buf: Vec<u8> = Vec::new();\n\n let mut buf = BufWriter::new(buf);\n\n bincode::serialize_into(&mut buf, &rng).expect(\"Could not serialize\");\n\n\n\n let buf = buf.into_inner().unwrap();\n\n let mut read = BufReader::new(&buf[..]);\n\n let mut deserialized: Lcg128CmDxsm64 =\n\n bincode::deserialize_from(&mut read).expect(\"Could not deserialize\");\n\n\n\n for _ in 0..16 {\n\n assert_eq!(rng.next_u64(), deserialized.next_u64());\n\n }\n\n}\n", "file_path": "tests/complex/rand/rand_pcg/tests/lcg128cmdxsm64.rs", "rank": 87, "score": 104164.79789396032 }, { "content": "#[cfg(feature = \"serde1\")]\n\n#[test]\n\nfn test_lcg128xsl64_serde() {\n\n use bincode;\n\n use std::io::{BufReader, BufWriter};\n\n\n\n let mut rng = Lcg128Xsl64::seed_from_u64(0);\n\n\n\n let buf: Vec<u8> = Vec::new();\n\n let mut buf = BufWriter::new(buf);\n\n bincode::serialize_into(&mut buf, &rng).expect(\"Could not serialize\");\n\n\n\n let buf = buf.into_inner().unwrap();\n\n let mut read = BufReader::new(&buf[..]);\n\n let mut deserialized: Lcg128Xsl64 =\n\n bincode::deserialize_from(&mut read).expect(\"Could not deserialize\");\n\n\n\n for _ in 0..16 {\n\n assert_eq!(rng.next_u64(), deserialized.next_u64());\n\n }\n\n}\n", "file_path": "tests/complex/rand/rand_pcg/tests/lcg128xsl64.rs", "rank": 88, "score": 104164.79789396032 }, { "content": "#[cfg(feature = \"serde1\")]\n\n#[test]\n\nfn test_lcg64xsh32_serde() {\n\n use bincode;\n\n use std::io::{BufReader, BufWriter};\n\n\n\n let mut rng = Lcg64Xsh32::seed_from_u64(0);\n\n\n\n let buf: Vec<u8> = Vec::new();\n\n let mut buf = BufWriter::new(buf);\n\n bincode::serialize_into(&mut buf, &rng).expect(\"Could not serialize\");\n\n\n\n let buf = buf.into_inner().unwrap();\n\n let mut read = BufReader::new(&buf[..]);\n\n let mut deserialized: Lcg64Xsh32 =\n\n bincode::deserialize_from(&mut read).expect(\"Could not deserialize\");\n\n\n\n for _ in 0..16 {\n\n assert_eq!(rng.next_u64(), deserialized.next_u64());\n\n }\n\n}\n", "file_path": "tests/complex/rand/rand_pcg/tests/lcg64xsh32.rs", "rank": 89, "score": 104164.79789396032 }, { "content": "#[cfg(feature = \"serde1\")]\n\n#[test]\n\nfn test_mcg128xsl64_serde() {\n\n use bincode;\n\n use std::io::{BufReader, BufWriter};\n\n\n\n let mut rng = Mcg128Xsl64::seed_from_u64(0);\n\n\n\n let buf: Vec<u8> = Vec::new();\n\n let mut buf = BufWriter::new(buf);\n\n bincode::serialize_into(&mut buf, &rng).expect(\"Could not serialize\");\n\n\n\n let buf = buf.into_inner().unwrap();\n\n let mut read = BufReader::new(&buf[..]);\n\n let mut deserialized: Mcg128Xsl64 =\n\n bincode::deserialize_from(&mut read).expect(\"Could not deserialize\");\n\n\n\n for _ in 0..16 {\n\n assert_eq!(rng.next_u64(), deserialized.next_u64());\n\n }\n\n}\n", "file_path": "tests/complex/rand/rand_pcg/tests/mcg128xsl64.rs", "rank": 90, "score": 104164.79789396032 }, { "content": "#[test]\n\nfn normal() {\n\n const N_SAMPLES: u64 = 1_000_000;\n\n const MEAN: f64 = 2.;\n\n const STD_DEV: f64 = 0.5;\n\n const MIN_X: f64 = -1.;\n\n const MAX_X: f64 = 5.;\n\n\n\n let dist = Normal::new(MEAN, STD_DEV).unwrap();\n\n let mut hist = Histogram100::with_const_width(MIN_X, MAX_X);\n\n let mut rng = rand::rngs::SmallRng::seed_from_u64(1);\n\n\n\n for _ in 0..N_SAMPLES {\n\n let _ = hist.add(rng.sample(dist)); // Ignore out-of-range values\n\n }\n\n\n\n println!(\n\n \"Sampled normal distribution:\\n{}\",\n\n sparkline::render_u64_as_string(hist.bins())\n\n );\n\n\n", "file_path": "tests/complex/rand/rand_distr/tests/pdf.rs", "rank": 91, "score": 103424.04217583881 }, { "content": "#[test]\n\nfn test_read() {\n\n let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];\n\n\n\n let mut buf = [0u32; 4];\n\n read_u32_into(&bytes, &mut buf);\n\n assert_eq!(buf[0], 0x04030201);\n\n assert_eq!(buf[3], 0x100F0E0D);\n\n\n\n let mut buf = [0u32; 3];\n\n read_u32_into(&bytes[1..13], &mut buf); // unaligned\n\n assert_eq!(buf[0], 0x05040302);\n\n assert_eq!(buf[2], 0x0D0C0B0A);\n\n\n\n let mut buf = [0u64; 2];\n\n read_u64_into(&bytes, &mut buf);\n\n assert_eq!(buf[0], 0x0807060504030201);\n\n assert_eq!(buf[1], 0x100F0E0D0C0B0A09);\n\n\n\n let mut buf = [0u64; 1];\n\n read_u64_into(&bytes[7..15], &mut buf); // unaligned\n\n assert_eq!(buf[0], 0x0F0E0D0C0B0A0908);\n\n}\n", "file_path": "tests/complex/rand/rand_core/src/le.rs", "rank": 92, "score": 101997.16742505129 }, { "content": "#[test]\n\nfn skew_normal() {\n\n const N_SAMPLES: u64 = 1_000_000;\n\n const LOCATION: f64 = 2.;\n\n const SCALE: f64 = 0.5;\n\n const SHAPE: f64 = -3.0;\n\n const MIN_X: f64 = -1.;\n\n const MAX_X: f64 = 4.;\n\n\n\n let dist = SkewNormal::new(LOCATION, SCALE, SHAPE).unwrap();\n\n let mut hist = Histogram100::with_const_width(MIN_X, MAX_X);\n\n let mut rng = rand::rngs::SmallRng::seed_from_u64(1);\n\n\n\n for _ in 0..N_SAMPLES {\n\n let _ = hist.add(rng.sample(dist)); // Ignore out-of-range values\n\n }\n\n\n\n println!(\n\n \"Sampled skew normal distribution:\\n{}\",\n\n sparkline::render_u64_as_string(hist.bins())\n\n );\n", "file_path": "tests/complex/rand/rand_distr/tests/pdf.rs", "rank": 93, "score": 101997.16742505129 }, { "content": "#[test]\n\nfn test_construction() {\n\n let mut rng = OsRng::default();\n\n assert!(rng.next_u64() != 0);\n\n}\n", "file_path": "tests/complex/rand/rand_core/src/os.rs", "rank": 94, "score": 101997.16742505129 }, { "content": "#[test]\n\nfn unit_sphere() {\n\n const N_DIM: usize = 3;\n\n let h = Histogram100::with_const_width(-1., 1.);\n\n let mut histograms = [h.clone(), h.clone(), h];\n\n let dist = rand_distr::UnitSphere;\n\n let mut rng = rand_pcg::Pcg32::from_entropy();\n\n for _ in 0..N_SAMPLES {\n\n let v: [f64; 3] = dist.sample(&mut rng);\n\n for i in 0..N_DIM {\n\n histograms[i]\n\n .add(v[i])\n\n .map_err(|e| {\n\n println!(\"v: {}\", v[i]);\n\n e\n\n })\n\n .unwrap();\n\n }\n\n }\n\n for h in &histograms {\n\n let sum: u64 = h.bins().iter().sum();\n\n println!(\"{:?}\", h);\n\n for &b in h.bins() {\n\n let p = (b as f64) / (sum as f64);\n\n assert!((p - 1.0 / (N_BINS as f64)).abs() < TOL, \"{}\", p);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_distr/tests/uniformity.rs", "rank": 95, "score": 101997.16742505129 }, { "content": "#[test]\n\nfn unit_circle() {\n\n use core::f64::consts::PI;\n\n let mut h = Histogram100::with_const_width(-PI, PI);\n\n let dist = rand_distr::UnitCircle;\n\n let mut rng = rand_pcg::Pcg32::from_entropy();\n\n for _ in 0..N_SAMPLES {\n\n let v: [f64; 2] = dist.sample(&mut rng);\n\n h.add(v[0].atan2(v[1])).unwrap();\n\n }\n\n let sum: u64 = h.bins().iter().sum();\n\n println!(\"{:?}\", h);\n\n for &b in h.bins() {\n\n let p = (b as f64) / (sum as f64);\n\n assert!((p - 1.0 / (N_BINS as f64)).abs() < TOL, \"{}\", p);\n\n }\n\n}\n", "file_path": "tests/complex/rand/rand_distr/tests/uniformity.rs", "rank": 96, "score": 101997.16742505129 }, { "content": "#[test]\n\nfn geometric_stability() {\n\n test_samples(464, StandardGeometric, &[3, 0, 1, 0, 0, 3, 2, 1, 2, 0]);\n\n \n\n test_samples(464, Geometric::new(0.5).unwrap(), &[2, 1, 1, 0, 0, 1, 0, 1]);\n\n test_samples(464, Geometric::new(0.05).unwrap(), &[24, 51, 81, 67, 27, 11, 7, 6]);\n\n test_samples(464, Geometric::new(0.95).unwrap(), &[0, 0, 0, 0, 1, 0, 0, 0]);\n\n\n\n // expect non-random behaviour for series of pre-determined trials\n\n test_samples(464, Geometric::new(0.0).unwrap(), &[u64::max_value(); 100][..]);\n\n test_samples(464, Geometric::new(1.0).unwrap(), &[0; 100][..]);\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_distr/tests/value_stability.rs", "rank": 97, "score": 100624.01512182111 }, { "content": "#[test]\n\nfn hypergeometric_stability() {\n\n // We have multiple code paths based on the distribution's mode and sample_size\n\n test_samples(7221, Hypergeometric::new(99, 33, 8).unwrap(), &[4, 3, 2, 2, 3, 2, 3, 1]); // Algorithm HIN\n\n test_samples(7221, Hypergeometric::new(100, 50, 50).unwrap(), &[23, 27, 26, 27, 22, 24, 31, 22]); // Algorithm H2PE\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_distr/tests/value_stability.rs", "rank": 98, "score": 100624.01512182111 }, { "content": "#[test]\n\nfn binominal_stability() {\n\n // We have multiple code paths: np < 10, p > 0.5\n\n test_samples(353, Binomial::new(2, 0.7).unwrap(), &[1, 1, 2, 1]);\n\n test_samples(353, Binomial::new(20, 0.3).unwrap(), &[7, 7, 5, 7]);\n\n test_samples(353, Binomial::new(2000, 0.6).unwrap(), &[1194, 1208, 1192, 1210]);\n\n}\n\n\n", "file_path": "tests/complex/rand/rand_distr/tests/value_stability.rs", "rank": 99, "score": 100624.01512182111 } ]
Rust
src/connectivity/network/ping3/src/store.rs
EnderNightLord-ChromeBook/zircon-rpi
b09b1eb3aa7a127c65568229fe10edd251869283
use fuchsia_async as fasync; use fuchsia_zircon as zx; use thiserror::Error; #[derive(Clone)] pub struct SequenceStore { next_seq: u16, last_seq: u16, start_time: zx::Time, } #[derive(Error, Debug)] #[error("No sequence numbers available")] pub struct OutOfSequencesError; #[derive(Error, Debug)] pub enum GiveError { #[error("Sequence number received that has not been sent out yet")] DoesNotExist(Option<zx::Duration>), #[error("Duplicate sequence number received")] Duplicate(Option<zx::Duration>), #[error("Out-of-order sequence number received")] OutOfOrder(Option<zx::Duration>), } impl SequenceStore { pub fn new() -> Self { SequenceStore { next_seq: 0, last_seq: std::u16::MAX, start_time: fasync::Time::now().into_zx(), } } pub fn take(&mut self) -> Result<(u16, zx::Duration), OutOfSequencesError> { let seq_num = self.next_seq; let (next_seq, overflow) = self.next_seq.overflowing_add(1); self.next_seq = next_seq; if overflow { return Err(OutOfSequencesError); } let offset_from_start_time = fasync::Time::now().into_zx() - self.start_time; Ok((seq_num, offset_from_start_time)) } pub fn give( &mut self, sequence_num: u16, offset_from_start_time: Option<zx::Duration>, ) -> Result<Option<zx::Duration>, GiveError> { let now = fasync::Time::now().into_zx(); let latency = offset_from_start_time.map(|time| now - self.start_time - time); if sequence_num >= self.next_seq { return Err(GiveError::DoesNotExist(latency)); } let (expected, _) = self.last_seq.overflowing_add(1); if sequence_num == expected { self.last_seq = sequence_num; Ok(latency) } else if sequence_num < expected { Err(GiveError::Duplicate(latency)) } else { Err(GiveError::OutOfOrder(latency)) } } } #[cfg(test)] mod test { use super::*; const SHORT_DELAY: zx::Duration = zx::Duration::from_nanos(1); #[test] fn take_all() { let _executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); for i in 0..std::u16::MAX { assert_eq!(s.take().expect("Failed to take").0, i); } } #[test] fn take_too_much() { let _executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); for i in 0..std::u16::MAX { assert_eq!(s.take().expect("Failed to take").0, i); } s.take().expect_err("There shouldn't be any more sequence numbers available"); } #[test] fn give_out_of_order() { let _executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); s.take().expect("Failed to take"); let (n, _) = s.take().expect("Failed to take"); s.give(n, None).expect_err("Should error on out-of-order responses"); } #[test] fn give_duplicate() { let _executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); s.give(42, None).expect_err("Should not be able to give seq_nums that haven't been given"); } #[test] fn give_same_number() { let _executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); let (num, _) = s.take().expect("Failed to take"); s.give(num, None).expect("Failed to give"); s.give(num, None).expect_err("Should not be able to give duplicates"); } #[test] fn give_same_times() { let _executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); let (_, a_time) = s.take().expect("Failed to take"); let (_, b_time) = s.take().expect("Failed to take"); assert_eq!(a_time, b_time); } #[test] fn give_different_times() { let executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); let (_, a_time) = s.take().expect("Failed to take"); executor.set_fake_time(executor.now() + SHORT_DELAY); let (_, b_time) = s.take().expect("Failed to take"); assert_eq!(b_time - a_time, SHORT_DELAY); } #[test] fn give_latency() { let executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); let (a, a_time) = s.take().expect("Failed to take"); executor.set_fake_time(executor.now() + SHORT_DELAY); let a_latency = s.give(a, Some(a_time)).expect("Failed to give"); assert_eq!(a_latency, Some(SHORT_DELAY)); } #[test] fn give_same_latencies() { let executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); let (a, a_time) = s.take().expect("Failed to take"); executor.set_fake_time(executor.now() + SHORT_DELAY); let (b, b_time) = s.take().expect("Failed to take"); let a_latency = s.give(a, Some(a_time)).expect("Failed to give"); executor.set_fake_time(executor.now() + SHORT_DELAY); let b_latency = s.give(b, Some(b_time)).expect("Failed to give"); assert_eq!(a_latency, b_latency); } #[test] fn give_different_latencies() { let executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); let (a, a_time) = s.take().expect("Failed to take"); executor.set_fake_time(executor.now() + SHORT_DELAY); let (b, b_time) = s.take().expect("Failed to take"); let a_latency = s.give(a, Some(a_time)).expect("Failed to give"); let b_latency = s.give(b, Some(b_time)).expect("Failed to give"); assert_eq!(a_latency.unwrap() - b_latency.unwrap(), SHORT_DELAY); } }
use fuchsia_async as fasync; use fuchsia_zircon as zx; use thiserror::Error; #[derive(Clone)] pub struct SequenceStore { next_seq: u16, last_seq: u16, start_time: zx::Time, } #[derive(Error, Debug)] #[error("No sequence numbers available")] pub struct OutOfSequencesError; #[derive(Error, Debug)] pub enum GiveError { #[error("Sequence number received that has not been sent out yet")] DoesNotExist(Option<zx::Duration>), #[error("Duplicate sequence number received")] Duplicate(Option<zx::Duration>), #[error("Out-of-order sequence number received")] OutOfOrder(Option<zx::Duration>), } impl SequenceStore { pub fn new() -> Self { SequenceStore { next_seq: 0, last_seq: std::u16::MAX, start_time: fasync::Time::now().into_zx(), } } pub fn take(&mut self) -> Result<(u16, zx::Duration), OutOfSequencesError> { let seq_num = self.next_seq; let (next_seq, overflow) = self.next_seq.overflowing_add(1); self.next_seq = next_seq; if overflow { return Err(OutOfSequencesError); } let offset_from_start_time = fasync::Time::now().into_zx() - self.start_time; Ok((seq_num, offset_from_start_time)) } pub fn give( &mut self, sequence_num: u16, offset_from_start_time: Option<zx::Duration>, ) -> Result<Option<zx::Duration>, GiveError> { let now = fasync::Time::now().into_zx(); let latency = offset_from_start_time.map(|time| now - self.start_time - time); if sequence_num >= self.next_seq { return Err(GiveError::DoesNotExist(latency)); } let (expected, _) = self.last_seq.overflowing_add(1); if sequence_num == expected { self.last_seq = sequence_num; Ok(latency) } else if sequence_num < expected { Err(GiveError::Duplicate(latency)) } else { Err(GiveError::OutOfOrder(latency)) } } } #[cfg(test)] mod test { use super::*; const SHORT_DELAY: zx::Duration = zx::Duration::from_nanos(1); #[test] fn take_all() { let _executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); for i in 0..std::u16::MAX { assert_eq!(s.take().expect("Failed to take").0, i); } } #[test] fn take_too_much() { let _executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); for i in 0..std::u16::MAX { assert_eq!(s.take()
); let (_, b_time) = s.take().expect("Failed to take"); assert_eq!(b_time - a_time, SHORT_DELAY); } #[test] fn give_latency() { let executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); let (a, a_time) = s.take().expect("Failed to take"); executor.set_fake_time(executor.now() + SHORT_DELAY); let a_latency = s.give(a, Some(a_time)).expect("Failed to give"); assert_eq!(a_latency, Some(SHORT_DELAY)); } #[test] fn give_same_latencies() { let executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); let (a, a_time) = s.take().expect("Failed to take"); executor.set_fake_time(executor.now() + SHORT_DELAY); let (b, b_time) = s.take().expect("Failed to take"); let a_latency = s.give(a, Some(a_time)).expect("Failed to give"); executor.set_fake_time(executor.now() + SHORT_DELAY); let b_latency = s.give(b, Some(b_time)).expect("Failed to give"); assert_eq!(a_latency, b_latency); } #[test] fn give_different_latencies() { let executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); let (a, a_time) = s.take().expect("Failed to take"); executor.set_fake_time(executor.now() + SHORT_DELAY); let (b, b_time) = s.take().expect("Failed to take"); let a_latency = s.give(a, Some(a_time)).expect("Failed to give"); let b_latency = s.give(b, Some(b_time)).expect("Failed to give"); assert_eq!(a_latency.unwrap() - b_latency.unwrap(), SHORT_DELAY); } }
.expect("Failed to take").0, i); } s.take().expect_err("There shouldn't be any more sequence numbers available"); } #[test] fn give_out_of_order() { let _executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); s.take().expect("Failed to take"); let (n, _) = s.take().expect("Failed to take"); s.give(n, None).expect_err("Should error on out-of-order responses"); } #[test] fn give_duplicate() { let _executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); s.give(42, None).expect_err("Should not be able to give seq_nums that haven't been given"); } #[test] fn give_same_number() { let _executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); let (num, _) = s.take().expect("Failed to take"); s.give(num, None).expect("Failed to give"); s.give(num, None).expect_err("Should not be able to give duplicates"); } #[test] fn give_same_times() { let _executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); let (_, a_time) = s.take().expect("Failed to take"); let (_, b_time) = s.take().expect("Failed to take"); assert_eq!(a_time, b_time); } #[test] fn give_different_times() { let executor = fasync::Executor::new_with_fake_time().expect("Failed to create executor"); let mut s = SequenceStore::new(); let (_, a_time) = s.take().expect("Failed to take"); executor.set_fake_time(executor.now() + SHORT_DELAY
random
[]
Rust
src/application/core.rs
mass10/rzip
d9a3cf8dbe3208a382bd5da3d353331a27e59df0
use super::errors::ApplicationError; use crate::configuration; use crate::functions; use std::io::Read; #[allow(unused)] fn matches(pattern: &str, text: &str) -> bool { let reg = regex::Regex::new(pattern); if reg.is_err() { panic!("[ERROR] Fatal error. (reason: {})", reg.err().unwrap()); return false; } let result = reg.unwrap().find(text); if result.is_none() { return false; } return true; } pub struct Zipper; impl Zipper { pub fn new() -> Zipper { let instance = Zipper {}; return instance; } fn append_entry(&self, archiver: &mut zip::ZipWriter<std::fs::File>, base_name: &str, path: &str, settings: &configuration::Settings) -> Result<(), Box<dyn std::error::Error>> { use crate::helpers::DirEntityHelper; use crate::helpers::PathHelper; use std::io::Write; let unknown = std::path::Path::new(path); if unknown.is_dir() { let name = unknown.name_as_str(); if !settings.is_valid_dir(name) { println!("[INFO] IGNORE {}", name); return Ok(()); } let internal_path = functions::build_path(base_name, name); if base_name != "" { println!("[INFO] adding ... {}", &base_name); let options = zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored); archiver.add_directory(&internal_path, options)?; } let it = std::fs::read_dir(path)?; for e in it { let entry = e?; let fullpath = entry.path_as_string(); self.append_entry(archiver, &internal_path, &fullpath, &settings)?; } } else if unknown.is_file() { use crate::helpers::SystemTimeHelper; let name = unknown.name_as_str(); if !settings.is_valid_filename(name)? { println!("[INFO] IGNORE {}", name); return Ok(()); } let options = zip::write::FileOptions::default(); let internal_path = functions::build_path(base_name, name); let meta = unknown.metadata()?; let options = options.compression_method(zip::CompressionMethod::Stored); let last_modified = meta.modified()?; let last_modified = last_modified.as_ziptime(); let options = options.last_modified_time(last_modified); println!("[INFO] adding ... {}", &internal_path); archiver.start_file(&internal_path, options)?; let mut stream = std::fs::File::open(path)?; loop { let mut buffer = [0; 1000]; let bytes_read = stream.read(&mut buffer)?; if bytes_read == 0 { break; } let write_buffer = &buffer[..bytes_read]; archiver.write(&write_buffer)?; } } else { let message = format!("Unknown filesystem [{}].", path); let err = ApplicationError::new(&message); return Err(Box::new(err)); } return Ok(()); } pub fn archive(&self, settings: &configuration::Settings, path: &str) -> Result<(), Box<dyn std::error::Error>> { let path = functions::canonicalize_path(path)?; let current_timestamp = functions::timestamp1(); let archive_path_name = format!("{}-{}.zip", &path, &current_timestamp); println!("[INFO] archiving ... {} >> {}", &path, &archive_path_name); functions::unlink(&archive_path_name)?; let w = std::fs::File::create(archive_path_name)?; let mut archiver = zip::ZipWriter::new(w); self.append_entry(&mut archiver, "", &path, &settings)?; archiver.finish()?; return Ok(()); } }
use super::errors::ApplicationError; use crate::configuration; use crate::functions; use std::io::Read; #[allow(unused)] fn matches(pattern: &str, text: &str) -> bool { let reg = regex::Regex::new(pattern); if reg.is_err() { pani
pub struct Zipper; impl Zipper { pub fn new() -> Zipper { let instance = Zipper {}; return instance; } fn append_entry(&self, archiver: &mut zip::ZipWriter<std::fs::File>, base_name: &str, path: &str, settings: &configuration::Settings) -> Result<(), Box<dyn std::error::Error>> { use crate::helpers::DirEntityHelper; use crate::helpers::PathHelper; use std::io::Write; let unknown = std::path::Path::new(path); if unknown.is_dir() { let name = unknown.name_as_str(); if !settings.is_valid_dir(name) { println!("[INFO] IGNORE {}", name); return Ok(()); } let internal_path = functions::build_path(base_name, name); if base_name != "" { println!("[INFO] adding ... {}", &base_name); let options = zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored); archiver.add_directory(&internal_path, options)?; } let it = std::fs::read_dir(path)?; for e in it { let entry = e?; let fullpath = entry.path_as_string(); self.append_entry(archiver, &internal_path, &fullpath, &settings)?; } } else if unknown.is_file() { use crate::helpers::SystemTimeHelper; let name = unknown.name_as_str(); if !settings.is_valid_filename(name)? { println!("[INFO] IGNORE {}", name); return Ok(()); } let options = zip::write::FileOptions::default(); let internal_path = functions::build_path(base_name, name); let meta = unknown.metadata()?; let options = options.compression_method(zip::CompressionMethod::Stored); let last_modified = meta.modified()?; let last_modified = last_modified.as_ziptime(); let options = options.last_modified_time(last_modified); println!("[INFO] adding ... {}", &internal_path); archiver.start_file(&internal_path, options)?; let mut stream = std::fs::File::open(path)?; loop { let mut buffer = [0; 1000]; let bytes_read = stream.read(&mut buffer)?; if bytes_read == 0 { break; } let write_buffer = &buffer[..bytes_read]; archiver.write(&write_buffer)?; } } else { let message = format!("Unknown filesystem [{}].", path); let err = ApplicationError::new(&message); return Err(Box::new(err)); } return Ok(()); } pub fn archive(&self, settings: &configuration::Settings, path: &str) -> Result<(), Box<dyn std::error::Error>> { let path = functions::canonicalize_path(path)?; let current_timestamp = functions::timestamp1(); let archive_path_name = format!("{}-{}.zip", &path, &current_timestamp); println!("[INFO] archiving ... {} >> {}", &path, &archive_path_name); functions::unlink(&archive_path_name)?; let w = std::fs::File::create(archive_path_name)?; let mut archiver = zip::ZipWriter::new(w); self.append_entry(&mut archiver, "", &path, &settings)?; archiver.finish()?; return Ok(()); } }
c!("[ERROR] Fatal error. (reason: {})", reg.err().unwrap()); return false; } let result = reg.unwrap().find(text); if result.is_none() { return false; } return true; }
function_block-function_prefixed
[ { "content": "/// Build a path from `path` and `name`.\n\n///\n\n/// # Arguments\n\n/// * `parent` Parent path.\n\n/// * `name` Name of the file or directory.\n\n///\n\n/// # Returns\n\n/// * Path to the file or directory.\n\npub fn build_path(parent: &str, name: &str) -> String {\n\n\tif parent == \"\" {\n\n\t\treturn name.to_string();\n\n\t}\n\n\treturn format!(\"{}/{}\", parent, name);\n\n}\n\n\n\n/// Get current time as a string in the format `%Y-%m-%d %H:%M:%S%.3f`.\n\n///\n\n/// # Returns\n\n/// Current time as a [String]\n", "file_path": "src/functions/mod.rs", "rank": 1, "score": 54275.675100441185 }, { "content": "/// マッチング記述文字列の終端文字を、適切なキャラクターに変換します。\n\n///\n\n/// # Arguments\n\n/// * `wildcard` マッチング記述文字列\n\n///\n\n/// # Returns\n\n/// 変換後の文字列\n\nfn tail(wildcard: &str) -> String {\n\n\tif wildcard.ends_with(\"*\") {\n\n\t\treturn wildcard.to_string();\n\n\t}\n\n\treturn format!(\"{}$\", wildcard);\n\n}\n\n\n", "file_path": "src/configuration/mod.rs", "rank": 2, "score": 52972.484416304935 }, { "content": "/// マッチング記述文字列の先頭文字を、適切なキャラクターに変換します。\n\n///\n\n/// # Arguments\n\n/// * `wildcard` マッチング記述文字列\n\n///\n\n/// # Returns\n\n/// 変換後の文字列\n\nfn head(wildcard: &str) -> String {\n\n\tif wildcard.starts_with(\"*\") {\n\n\t\treturn wildcard.to_string();\n\n\t}\n\n\treturn format!(\"^{}\", wildcard);\n\n}\n\n\n", "file_path": "src/configuration/mod.rs", "rank": 3, "score": 52972.484416304935 }, { "content": "fn get_env(name: &str) -> String {\n\n\tlet value = std::env::var(name);\n\n\tif value.is_err() {\n\n\t\treturn \"\".to_string();\n\n\t}\n\n\treturn value.unwrap();\n\n}\n\n\n", "file_path": "src/configuration/mod.rs", "rank": 4, "score": 51520.690113465374 }, { "content": "fn fix_unc_path(path: &str) -> String {\n\n\tif !path.starts_with(\"\\\\\\\\?\\\\\") {\n\n\t\treturn path.to_string();\n\n\t}\n\n\tlet mut tmp = path.to_string();\n\n\ttmp = tmp.replace(\"\\\\\\\\?\\\\\", \"\");\n\n\treturn tmp;\n\n}\n\n\n\nimpl PathHelper for std::path::Path {\n\n\t/// Get the name as &str\n\n\t///\n\n\t/// # Returns\n\n\t/// name as &str\n\n\tfn name_as_str(&self) -> &str {\n\n\t\treturn self.file_name().unwrap().to_str().unwrap();\n\n\t}\n\n\n\n\t/// Get the name as [String]\n\n\t///\n", "file_path": "src/helpers/mod.rs", "rank": 5, "score": 50194.50720704571 }, { "content": "fn make_name_filter(wildcard: &str) -> String {\n\n\tlet wildcard = head(wildcard);\n\n\tlet wildcard = tail(&wildcard);\n\n\tlet wildcard = wildcard.replace(\"[\", \"\\\\[\");\n\n\tlet wildcard = wildcard.replace(\"]\", \"\\\\]\");\n\n\tlet wildcard = wildcard.replace(\".\", \"\\\\.\");\n\n\tlet wildcard = wildcard.replace(\"*\", \".+\");\n\n\treturn wildcard;\n\n}\n\n\n", "file_path": "src/configuration/mod.rs", "rank": 6, "score": 50194.50720704571 }, { "content": "/// Retrieve the whole content of file\n\n///\n\n/// ### Returns\n\n/// Entire content of file as `String`\n\npub fn read_text_file_all(path: &str) -> std::result::Result<String, Box<dyn std::error::Error>> {\n\n\tuse std::io::Read;\n\n\n\n\tlet mut file = std::fs::File::open(path)?;\n\n\tlet mut s = String::new();\n\n\tfile.read_to_string(&mut s)?;\n\n\treturn Ok(s);\n\n}\n", "file_path": "src/functions/mod.rs", "rank": 7, "score": 44401.36012907053 }, { "content": "/// Remove directory or file specified by `path`.\n\n///\n\n/// # Arguments\n\n/// * `path` Path to remove.\n\npub fn unlink(path: &str) -> Result<(), Box<dyn std::error::Error>> {\n\n\tif path == \"\" {\n\n\t\treturn Ok(());\n\n\t}\n\n\tlet e = std::path::Path::new(path);\n\n\tif e.is_dir() {\n\n\t\t// Remove directory.\n\n\t\tstd::fs::remove_dir_all(path)?;\n\n\t} else if e.is_file() {\n\n\t\t// Remove file.\n\n\t\tstd::fs::remove_file(path)?;\n\n\t}\n\n\treturn Ok(());\n\n}\n\n\n", "file_path": "src/functions/mod.rs", "rank": 8, "score": 39023.55812462047 }, { "content": "/// Get canonical path of `path`.\n\npub fn canonicalize_path(path: &str) -> Result<String, Box<dyn std::error::Error>> {\n\n\tuse crate::helpers::PathHelper;\n\n\n\n\tlet path = std::path::Path::new(path);\n\n\treturn path.canonical_path_as_string();\n\n}\n\n\n", "file_path": "src/functions/mod.rs", "rank": 9, "score": 36579.27271346352 }, { "content": "/// entrypoint.\n\nfn main() {\n\n\t// configure.\n\n\tlet result = configuration::Settings::new();\n\n\tif result.is_err() {\n\n\t\tprintln!(\"[ERROR] Configuration error. reason: {}\", result.err().unwrap());\n\n\t\treturn;\n\n\t}\n\n\tlet settings = result.unwrap();\n\n\n\n\t// reading commandline options.\n\n\tlet args: std::vec::Vec<String> = std::env::args().skip(1).collect();\n\n\tif args.len() == 0 {\n\n\t\tprintln!(\"Path to directory needed.\");\n\n\t\tstd::thread::sleep(std::time::Duration::from_secs(2));\n\n\t\treturn;\n\n\t}\n\n\n\n\t// Stopwatch. For printing summary.\n\n\tlet stopwatch = util::time::Stopwatch::new();\n\n\n", "file_path": "src/main.rs", "rank": 10, "score": 32096.41581940171 }, { "content": "/// Get current time as a string in the format `%Y%m%d-%H%M%S`.\n\n///\n\n/// # Returns\n\n/// Current time as a [String]\n\npub fn timestamp1() -> String {\n\n\tlet date = chrono::Local::now();\n\n\treturn format!(\"{}\", date.format(\"%Y%m%d-%H%M%S\"));\n\n}\n\n\n", "file_path": "src/functions/mod.rs", "rank": 11, "score": 26957.506002088536 }, { "content": "#[allow(unused)]\n\npub fn timestamp0() -> String {\n\n\tlet date = chrono::Local::now();\n\n\treturn format!(\"{}\", date.format(\"%Y-%m-%d %H:%M:%S%.3f\"));\n\n}\n\n\n", "file_path": "src/functions/mod.rs", "rank": 12, "score": 26957.506002088536 }, { "content": "fn find_settings_toml() -> Result<String, Box<dyn std::error::Error>> {\n\n\tuse crate::helpers::PathHelper;\n\n\n\n\tconst NAME: &str = \"settings.toml\";\n\n\n\n\t// カレントディレクトリを調べます。\n\n\tif std::path::Path::new(NAME).is_file() {\n\n\t\treturn Ok(NAME.to_string());\n\n\t}\n\n\n\n\t// ユーザーのホームディレクトリを調べます。(Windows)\n\n\tlet home = get_env(\"USERPROFILE\");\n\n\tif home != \"\" {\n\n\t\treturn std::path::Path::new(&home).join_as_string(NAME);\n\n\t}\n\n\n\n\t// ユーザーのホームディレクトリを調べます。(Linux)\n\n\tlet home = get_env(\"HOME\");\n\n\tif home != \"\" {\n\n\t\treturn std::path::Path::new(&home).join_as_string(NAME);\n", "file_path": "src/configuration/mod.rs", "rank": 13, "score": 19493.60239854641 }, { "content": "\t/// # Arguments\n\n\t/// * `path` 設定ファイルのパス\n\n\tfn configure(&mut self, path: &str) -> Result<(), Box<dyn std::error::Error>> {\n\n\t\t// パスが指定されていなければスキップします。\n\n\t\tif path == \"\" {\n\n\t\t\treturn Ok(());\n\n\t\t}\n\n\n\n\t\t// ファイルが無ければスキップします。\n\n\t\tif !std::path::Path::new(path).is_file() {\n\n\t\t\tprintln!(\"[INFO] Configuration file not found. (settings.toml)\");\n\n\t\t\treturn Ok(());\n\n\t\t}\n\n\n\n\t\t// テキストファイル全体を読み込み\n\n\t\tlet content = functions::read_text_file_all(&path)?;\n\n\n\n\t\t// toml ファイルをパース\n\n\t\t*self = toml::from_str(&content)?;\n\n\t\tif self.exclude_dirs.is_none() {\n", "file_path": "src/configuration/mod.rs", "rank": 16, "score": 2.475522716383316 }, { "content": "\t\tlet names = self.exclude_dirs.as_ref().unwrap();\n\n\t\tfor e in names {\n\n\t\t\tif name == e {\n\n\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn true;\n\n\t}\n\n\n\n\t/// 指定された名前が処理対象のファイルか調べます。\n\n\t///\n\n\t/// # Arguments\n\n\t/// * `name` ファイルの名前\n\n\t///\n\n\t/// # Returns\n\n\t/// 処理対象(=つまり除外ファイル名に指定されていない)なら `true` を返します。\n\n\tpub fn is_valid_filename(&self, name: &str) -> Result<bool, Box<dyn std::error::Error>> {\n\n\t\tif self.exclude_files.is_none() {\n\n\t\t\treturn Ok(true);\n\n\t\t}\n", "file_path": "src/configuration/mod.rs", "rank": 17, "score": 2.339519943896571 }, { "content": "\t\t\tself.exclude_dirs = Some(std::collections::HashSet::new());\n\n\t\t}\n\n\t\tif self.exclude_files.is_none() {\n\n\t\t\tself.exclude_files = Some(std::collections::HashSet::new());\n\n\t\t}\n\n\n\n\t\treturn Ok(());\n\n\t}\n\n\n\n\t/// 指定された名前が処理対象か調べます。\n\n\t///\n\n\t/// # Arguments\n\n\t/// * `name` ディレクトリの名前\n\n\t///\n\n\t/// # Returns\n\n\t/// 処理対象(=つまり除外ディレクトリ名に指定されていない)なら `true` を返します。\n\n\tpub fn is_valid_dir(&self, name: &str) -> bool {\n\n\t\tif self.exclude_dirs.is_none() {\n\n\t\t\treturn true;\n\n\t\t}\n", "file_path": "src/configuration/mod.rs", "rank": 18, "score": 2.251116736462524 }, { "content": "//!\n\n//! Configuration\n\n//!\n\n\n\nextern crate serde_derive;\n\n\n\nuse crate::functions;\n\n\n\n/// マッチング記述文字列の先頭文字を、適切なキャラクターに変換します。\n\n///\n\n/// # Arguments\n\n/// * `wildcard` マッチング記述文字列\n\n///\n\n/// # Returns\n\n/// 変換後の文字列\n", "file_path": "src/configuration/mod.rs", "rank": 19, "score": 1.873554298496696 }, { "content": "\t/// # Returns\n\n\t/// name as [String]\n\n\tfn name_as_string(&self) -> String {\n\n\t\treturn self.file_name().unwrap().to_str().unwrap().to_string();\n\n\t}\n\n\n\n\t/// Get canonical path as [String]\n\n\t///\n\n\t/// # Returns\n\n\t/// canonical path as [String]\n\n\tfn canonical_path_as_string(&self) -> Result<String, Box<dyn std::error::Error>> {\n\n\t\tlet path = self.canonicalize()?;\n\n\t\tlet s = path.to_str().unwrap().to_string();\n\n\t\treturn Ok(fix_unc_path(&s));\n\n\t}\n\n\n\n\t/// Join path as [String]\n\n\t///\n\n\t/// # Returns\n\n\t/// joined path as [String]\n\n\tfn join_as_string(&self, child: &str) -> Result<String, Box<dyn std::error::Error>> {\n\n\t\tlet result = self.join(child);\n\n\t\tlet s = result.to_str().unwrap().to_string();\n\n\t\treturn Ok(s);\n\n\t}\n\n}\n\n\n", "file_path": "src/helpers/mod.rs", "rank": 20, "score": 1.7330404325148725 }, { "content": "\t/// `ApplicationError` の新しいインスタンス\n\n\tpub fn new(description: &str) -> ApplicationError {\n\n\t\treturn ApplicationError { description: description.to_string() };\n\n\t}\n\n}\n\n\n\nimpl std::fmt::Display for ApplicationError {\n\n\t/// [std::fmt::Display] としての振る舞いを実装します。\n\n\tfn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {\n\n\t\treturn write!(f, \"{}\", self.description);\n\n\t}\n\n}\n\n\n\nimpl std::error::Error for ApplicationError {\n\n\t/// [std::error::Error] としての振る舞いを実装します。\n\n\t///\n\n\t/// # Returns\n\n\t/// エラー文字列\n\n\tfn description(&self) -> &str {\n\n\t\treturn &self.description;\n\n\t}\n\n}\n", "file_path": "src/application/errors.rs", "rank": 22, "score": 1.400847721286222 }, { "content": "}\n\n\n\nimpl std::fmt::Display for Stopwatch {\n\n\t/// Implements default behavior as [std::fmt::Display].\n\n\t///\n\n\t/// ### Returns\n\n\t/// Duration as formatted string.\n\n\tfn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n\n\t\tuse crate::helpers::DurationFormatter;\n\n\n\n\t\tlet elapsed = std::time::Instant::now() - self.time;\n\n\t\twrite!(f, \"{}\", elapsed.to_string())?;\n\n\t\treturn Ok(());\n\n\t}\n\n}\n", "file_path": "src/util/time.rs", "rank": 23, "score": 1.015123214357696 } ]
Rust
src/headers/mod.rs
vv9k/mobi-rs
c15606e2842759db9797122c5f8196d36388feba
pub(crate) mod exth; pub(crate) mod header; pub(crate) mod mobih; pub(crate) mod palmdoch; pub use self::{ exth::{ExtHeader, ExthRecord}, header::{Header, HeaderParseError}, mobih::{Language, MobiHeader, MobiType, TextEncoding}, palmdoch::{Compression, Encryption, PalmDocHeader}, }; use crate::record::PdbRecords; use crate::{Reader, Writer}; #[cfg(feature = "time")] use chrono::NaiveDateTime; use std::fs::File; use std::io::{self, BufReader, Read}; use std::path::Path; use thiserror::Error; #[derive(Debug, Error)] pub enum MetadataParseError { #[error(transparent)] HeaderParseError(#[from] HeaderParseError), #[error(transparent)] IoError(#[from] std::io::Error), } #[derive(Debug, Default)] pub struct MobiMetadata { pub name: Vec<u8>, pub header: Header, pub records: PdbRecords, pub palmdoc: PalmDocHeader, pub mobi: MobiHeader, pub exth: ExtHeader, } impl MobiMetadata { pub fn new<B: AsRef<Vec<u8>>>(bytes: B) -> Result<MobiMetadata, MetadataParseError> { MobiMetadata::from_reader(&mut Reader::new(std::io::Cursor::new(bytes.as_ref()))) } pub fn from_path<P: AsRef<Path>>(file_path: P) -> Result<MobiMetadata, MetadataParseError> { let mut reader = Reader::new(BufReader::new(File::open(file_path)?)); MobiMetadata::from_reader(&mut reader) } pub fn from_read<R: Read>(reader: R) -> Result<MobiMetadata, MetadataParseError> { MobiMetadata::from_reader(&mut Reader::new(reader)) } pub(crate) fn from_reader<R: Read>( reader: &mut Reader<R>, ) -> Result<MobiMetadata, MetadataParseError> { let header = Header::parse(reader)?; let records = PdbRecords::new(reader, header.num_records)?; let palmdoc = PalmDocHeader::parse(reader)?; let mobi = MobiHeader::parse(reader)?; let exth = if mobi.has_exth_header() { ExtHeader::parse(reader)? } else { ExtHeader::default() }; reader.set_position((records.records[0].offset + mobi.name_offset) as usize)?; let name = reader.read_vec_header(mobi.name_length as usize)?; Ok(MobiMetadata { name, header, records, palmdoc, mobi, exth, }) } #[allow(dead_code)] fn write(&self, writer: &mut impl io::Write) -> io::Result<()> { self.write_into(&mut Writer::new(writer)) } pub(crate) fn write_into<W: io::Write>(&self, w: &mut Writer<W>) -> io::Result<()> { self.header.write(w, self.records.num_records())?; self.records.write(w)?; self.palmdoc.write(w)?; self.mobi.write(w)?; if self.mobi.has_exth_header() { self.exth.write(w)?; } let fill = ((self.records.records[0].offset + self.mobi.name_offset) as usize) .saturating_sub(w.bytes_written()); w.write_be(vec![0; fill])?; w.write_be(&self.name) } pub fn exth_record(&self, record: ExthRecord) -> Option<&Vec<Vec<u8>>> { self.exth.get_record(record) } pub fn exth_record_at(&self, position: u32) -> Option<&Vec<Vec<u8>>> { self.exth.get_record_position(position) } pub fn author(&self) -> Option<String> { self.exth.get_record_string_lossy(exth::ExthRecord::Author) } pub fn publisher(&self) -> Option<String> { self.exth .get_record_string_lossy(exth::ExthRecord::Publisher) } pub fn description(&self) -> Option<String> { self.exth .get_record_string_lossy(exth::ExthRecord::Description) } pub fn isbn(&self) -> Option<String> { self.exth.get_record_string_lossy(exth::ExthRecord::Isbn) } pub fn publish_date(&self) -> Option<String> { self.exth .get_record_string_lossy(exth::ExthRecord::PublishDate) } pub fn contributor(&self) -> Option<String> { self.exth .get_record_string_lossy(exth::ExthRecord::Contributor) } pub fn title(&self) -> String { self.exth .get_record_string_lossy(exth::ExthRecord::Title) .map_or(String::from_utf8_lossy(&self.name).to_string(), |v| v) } pub fn text_encoding(&self) -> TextEncoding { self.mobi.text_encoding() } pub fn mobi_type(&self) -> MobiType { self.mobi.mobi_type() } pub fn language(&self) -> Language { self.mobi.language() } #[cfg(feature = "time")] pub fn created_datetime(&self) -> NaiveDateTime { self.header.created_datetime() } #[cfg(feature = "time")] pub fn mod_datetime(&self) -> NaiveDateTime { self.header.mod_datetime() } #[cfg(not(feature = "time"))] pub fn created_time(&self) -> u32 { self.header.created_datetime() } #[cfg(not(feature = "time"))] pub fn mod_time(&self) -> u32 { self.header.mod_datetime() } pub fn compression(&self) -> Compression { self.palmdoc.compression() } pub fn encryption(&self) -> Encryption { self.palmdoc.encryption() } pub fn subjects(&self) -> Option<Vec<String>> { self.exth_record(ExthRecord::Subject).map(|s| { s.iter() .map(|s| String::from_utf8_lossy(s).to_string()) .collect() }) } } #[cfg(test)] mod test { use super::*; use crate::book; #[test] fn test_mobi_metadata() { let mut reader = book::u8_reader(book::full_book()); assert!(MobiMetadata::from_reader(&mut reader).is_ok()); } #[test] fn test_mobi_write() { let m = MobiMetadata::from_reader(&mut book::u8_reader(book::full_book())).unwrap(); let mut bytes = vec![]; assert!(m.write(&mut bytes).is_ok()); assert_eq!(bytes, book::MOBI_METADATA); } }
pub(crate) mod exth; pub(crate) mod header; pub(crate) mod mobih; pub(crate) mod palmdoch; pub use self::{ exth::{ExtHeader, ExthRecord}, header::{Header, HeaderParseError}, mobih::{Language, MobiHeader, MobiType, TextEncoding}, palmdoch::{Compression, Encryption, PalmDocHeader}, }; use crate::record::PdbRecords; use crate::{Reader, Writer}; #[cfg(feature = "time")] use chrono::NaiveDateTime; use std::fs::File; use std::io::{self, BufReader, Read}; use std::path::Path; use thiserror::Error; #[derive(Debug, Error)] pub enum MetadataParseError { #[error(transparent)] HeaderParseError(#[from] HeaderParseError), #[error(transparent)] IoError(#[from] std::io::Error), } #[derive(Debug, Default)] pub struct MobiMetadata { pub name: Vec<u8>, pub header: Header, pub records: PdbRecords, pub palmdoc: PalmDocHeader, pub mobi: MobiHeader, pub exth: ExtHeader, } impl MobiMetadata { pub fn new<B: AsRef<Vec<u8>>>(bytes: B) -> Result<MobiMetadata, MetadataParseError> { MobiMetadata::from_reader(&mut Reader::new(std::io::Cursor::new(bytes.as_ref()))) } pub fn from_path<P: AsRef<Path>>(file_path: P) -> Result<MobiMetadata, MetadataParseError> { let mut reader = Reader::new(BufReader::new(File::open(file_path)?)); MobiMetadata::from_reader(&mut reader) } pub fn from_read<R: Read>(reader: R) -> Result<MobiMetadata, MetadataParseError> { MobiMetadata::from_reader(&mut Reader::new(reader)) } pub(crate) fn from_reader<R: Read>( reader: &mut Reader<R>, ) -> Result<MobiMetadata, MetadataParseError> { let header = Header::parse(reader)?; let records = PdbRecords::new(reader, header.num_records)?; let palmdoc = PalmDocHeader::parse(reader)?; let mobi = MobiHeader::parse(reader)?; let exth =
; reader.set_position((records.records[0].offset + mobi.name_offset) as usize)?; let name = reader.read_vec_header(mobi.name_length as usize)?; Ok(MobiMetadata { name, header, records, palmdoc, mobi, exth, }) } #[allow(dead_code)] fn write(&self, writer: &mut impl io::Write) -> io::Result<()> { self.write_into(&mut Writer::new(writer)) } pub(crate) fn write_into<W: io::Write>(&self, w: &mut Writer<W>) -> io::Result<()> { self.header.write(w, self.records.num_records())?; self.records.write(w)?; self.palmdoc.write(w)?; self.mobi.write(w)?; if self.mobi.has_exth_header() { self.exth.write(w)?; } let fill = ((self.records.records[0].offset + self.mobi.name_offset) as usize) .saturating_sub(w.bytes_written()); w.write_be(vec![0; fill])?; w.write_be(&self.name) } pub fn exth_record(&self, record: ExthRecord) -> Option<&Vec<Vec<u8>>> { self.exth.get_record(record) } pub fn exth_record_at(&self, position: u32) -> Option<&Vec<Vec<u8>>> { self.exth.get_record_position(position) } pub fn author(&self) -> Option<String> { self.exth.get_record_string_lossy(exth::ExthRecord::Author) } pub fn publisher(&self) -> Option<String> { self.exth .get_record_string_lossy(exth::ExthRecord::Publisher) } pub fn description(&self) -> Option<String> { self.exth .get_record_string_lossy(exth::ExthRecord::Description) } pub fn isbn(&self) -> Option<String> { self.exth.get_record_string_lossy(exth::ExthRecord::Isbn) } pub fn publish_date(&self) -> Option<String> { self.exth .get_record_string_lossy(exth::ExthRecord::PublishDate) } pub fn contributor(&self) -> Option<String> { self.exth .get_record_string_lossy(exth::ExthRecord::Contributor) } pub fn title(&self) -> String { self.exth .get_record_string_lossy(exth::ExthRecord::Title) .map_or(String::from_utf8_lossy(&self.name).to_string(), |v| v) } pub fn text_encoding(&self) -> TextEncoding { self.mobi.text_encoding() } pub fn mobi_type(&self) -> MobiType { self.mobi.mobi_type() } pub fn language(&self) -> Language { self.mobi.language() } #[cfg(feature = "time")] pub fn created_datetime(&self) -> NaiveDateTime { self.header.created_datetime() } #[cfg(feature = "time")] pub fn mod_datetime(&self) -> NaiveDateTime { self.header.mod_datetime() } #[cfg(not(feature = "time"))] pub fn created_time(&self) -> u32 { self.header.created_datetime() } #[cfg(not(feature = "time"))] pub fn mod_time(&self) -> u32 { self.header.mod_datetime() } pub fn compression(&self) -> Compression { self.palmdoc.compression() } pub fn encryption(&self) -> Encryption { self.palmdoc.encryption() } pub fn subjects(&self) -> Option<Vec<String>> { self.exth_record(ExthRecord::Subject).map(|s| { s.iter() .map(|s| String::from_utf8_lossy(s).to_string()) .collect() }) } } #[cfg(test)] mod test { use super::*; use crate::book; #[test] fn test_mobi_metadata() { let mut reader = book::u8_reader(book::full_book()); assert!(MobiMetadata::from_reader(&mut reader).is_ok()); } #[test] fn test_mobi_write() { let m = MobiMetadata::from_reader(&mut book::u8_reader(book::full_book())).unwrap(); let mut bytes = vec![]; assert!(m.write(&mut bytes).is_ok()); assert_eq!(bytes, book::MOBI_METADATA); } }
if mobi.has_exth_header() { ExtHeader::parse(reader)? } else { ExtHeader::default() }
if_condition
[ { "content": "pub fn decompress(data: &[u8]) -> Vec<u8> {\n\n let length = data.len();\n\n let mut pos: usize = 0;\n\n let mut text_pos: usize = 0;\n\n let mut text: Vec<u8> = vec![];\n\n\n\n let mut prev = None;\n\n while pos < length {\n\n let byte = data[pos];\n\n pos += 1;\n\n\n\n match byte {\n\n new if prev.is_some() => {\n\n let old = prev.take().unwrap();\n\n\n\n // Combine with previous byte to get a distance-length pair.\n\n let mut dist_len_bytes = u16::from_be_bytes([old, new]);\n\n\n\n dist_len_bytes &= 0x3fff; // Leftmost two bits are ID bits and need to be dropped\n\n let offset = (dist_len_bytes >> 3) as usize; // Remaining 11 bits are offset\n", "file_path": "src/compression/palmdoc.rs", "rank": 0, "score": 66256.6608076857 }, { "content": " u16::from(*self).write_be_bytes(writer)\n\n }\n\n}\n\n\n\n#[derive(Debug, PartialEq, Default)]\n\n/// Strcture that holds PalmDOC header information\n\npub struct PalmDocHeader {\n\n pub compression: Compression,\n\n pub text_length: u32,\n\n unused0: u16,\n\n pub record_count: u16,\n\n pub record_size: u16,\n\n pub encryption: Encryption,\n\n unused1: u16,\n\n}\n\n\n\nimpl PalmDocHeader {\n\n /// Parse a PalmDOC header from a reader. Reader must be advanced to the starting position\n\n /// of the PalmDocHeader, at byte 80 + 8 * num_records.\n\n pub(crate) fn parse<R: io::Read>(reader: &mut Reader<R>) -> io::Result<PalmDocHeader> {\n", "file_path": "src/headers/palmdoch.rs", "rank": 1, "score": 49088.846833333104 }, { "content": " record_count: 282,\n\n record_size: 4096,\n\n encryption: Encryption::No,\n\n ..Default::default()\n\n };\n\n\n\n let mut reader = book::u8_reader(book::PALMDOCHEADER.to_vec());\n\n\n\n assert_eq!(pdheader, PalmDocHeader::parse(&mut reader).unwrap());\n\n }\n\n\n\n #[test]\n\n fn test_write() {\n\n let input_bytes = book::PALMDOCHEADER.to_vec();\n\n\n\n let palmdoc = PalmDocHeader::parse(&mut book::u8_reader(input_bytes.clone())).unwrap();\n\n\n\n let mut output_bytes = vec![];\n\n assert!(palmdoc.write(&mut Writer::new(&mut output_bytes)).is_ok());\n\n assert_eq!(input_bytes, output_bytes);\n\n }\n\n}\n", "file_path": "src/headers/palmdoch.rs", "rank": 2, "score": 49086.08165592752 }, { "content": " u16::from(*self).write_be_bytes(writer)\n\n }\n\n}\n\n\n\n#[derive(Debug, Copy, Clone, PartialEq)]\n\n/// Encryption types available in MOBI format.\n\npub enum Encryption {\n\n No,\n\n OldMobiPocket,\n\n MobiPocket,\n\n}\n\n\n\nimpl Default for Encryption {\n\n fn default() -> Self {\n\n Encryption::No\n\n }\n\n}\n\n\n\nimpl From<u16> for Encryption {\n\n fn from(n: u16) -> Encryption {\n", "file_path": "src/headers/palmdoch.rs", "rank": 3, "score": 49083.487368527865 }, { "content": " Ok(PalmDocHeader {\n\n compression: reader.read_u16_be()?.into(),\n\n unused0: reader.read_u16_be()?,\n\n text_length: reader.read_u32_be()?,\n\n record_count: reader.read_u16_be()?,\n\n record_size: reader.read_u16_be()?,\n\n encryption: reader.read_u16_be()?.into(),\n\n unused1: reader.read_u16_be()?,\n\n })\n\n }\n\n\n\n pub(crate) fn write<W: io::Write>(&self, w: &mut Writer<W>) -> io::Result<()> {\n\n w.write_be(self.compression)?;\n\n w.write_be(self.unused0)?;\n\n w.write_be(self.text_length)?;\n\n w.write_be(self.record_count)?;\n\n w.write_be(self.record_size)?;\n\n w.write_be(self.encryption)?;\n\n w.write_be(self.unused1)\n\n }\n", "file_path": "src/headers/palmdoch.rs", "rank": 4, "score": 49083.360631183394 }, { "content": "use crate::writer::WriteBeBytes;\n\nuse crate::{Reader, Writer};\n\n\n\nuse std::io;\n\n\n\n#[derive(Debug, Copy, Clone, PartialEq)]\n\n/// Compression types available in MOBI format.\n\npub enum Compression {\n\n No,\n\n PalmDoc,\n\n Huff,\n\n}\n\n\n\nimpl Default for Compression {\n\n fn default() -> Compression {\n\n Compression::No\n\n }\n\n}\n\n\n\nimpl From<u16> for Compression {\n", "file_path": "src/headers/palmdoch.rs", "rank": 5, "score": 49081.66054564129 }, { "content": " match n {\n\n 2 => Encryption::MobiPocket,\n\n 1 => Encryption::OldMobiPocket,\n\n _ => Encryption::No,\n\n }\n\n }\n\n}\n\n\n\nimpl From<Encryption> for u16 {\n\n fn from(encryption: Encryption) -> u16 {\n\n match encryption {\n\n Encryption::No => 0,\n\n Encryption::MobiPocket => 1,\n\n Encryption::OldMobiPocket => 2,\n\n }\n\n }\n\n}\n\n\n\nimpl WriteBeBytes for Encryption {\n\n fn write_be_bytes<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {\n", "file_path": "src/headers/palmdoch.rs", "rank": 6, "score": 49078.42297112809 }, { "content": "\n\n pub fn compression(&self) -> Compression {\n\n self.compression\n\n }\n\n\n\n pub fn encryption(&self) -> Encryption {\n\n self.encryption\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::book;\n\n\n\n #[test]\n\n fn parse() {\n\n let pdheader = PalmDocHeader {\n\n compression: Compression::PalmDoc,\n\n text_length: 1151461,\n", "file_path": "src/headers/palmdoch.rs", "rank": 7, "score": 49078.02128563255 }, { "content": " fn from(n: u16) -> Compression {\n\n match n {\n\n 2 => Compression::PalmDoc,\n\n 17480 => Compression::Huff,\n\n _ => Compression::No,\n\n }\n\n }\n\n}\n\nimpl From<Compression> for u16 {\n\n fn from(compression: Compression) -> u16 {\n\n match compression {\n\n Compression::No => 1,\n\n Compression::PalmDoc => 2,\n\n Compression::Huff => 17480,\n\n }\n\n }\n\n}\n\n\n\nimpl WriteBeBytes for Compression {\n\n fn write_be_bytes<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {\n", "file_path": "src/headers/palmdoch.rs", "rank": 8, "score": 49070.52388523071 }, { "content": "}\n\n\n\nimpl ExtHeader {\n\n /// Parse a EXTH header from the content. Reader must be at starting\n\n /// location of exth header.\n\n pub(crate) fn parse<R: io::Read>(reader: &mut Reader<R>) -> io::Result<ExtHeader> {\n\n let mut extheader = ExtHeader {\n\n identifier: reader.read_u32_be()?,\n\n header_length: reader.read_u32_be()?,\n\n record_count: reader.read_u32_be()?,\n\n records: IndexMap::new(),\n\n };\n\n\n\n if &extheader.identifier.to_be_bytes() == b\"EXTH\" {\n\n extheader.populate_records(reader)?;\n\n Ok(extheader)\n\n } else {\n\n Err(io::Error::new(\n\n io::ErrorKind::InvalidData,\n\n \"invalid header identifier (expected EXTH)\",\n", "file_path": "src/headers/exth.rs", "rank": 22, "score": 48666.838672619226 }, { "content": " let parsed_header = ExtHeader::parse(&mut reader).unwrap();\n\n let mut records: Vec<_> = parsed_header.records().collect();\n\n\n\n _records.sort();\n\n records.sort();\n\n for (a, b) in records.into_iter().zip(_records) {\n\n assert_eq!(*a.0, b.0);\n\n assert_eq!(a.1, b.1);\n\n }\n\n }\n\n\n\n mod records {\n\n use crate::book;\n\n use crate::headers::{ExtHeader, ExthRecord};\n\n use pretty_assertions::assert_eq;\n\n\n\n macro_rules! info {\n\n ($t: ident, $s: expr) => {\n\n let mut reader = book::u8_reader(book::BOOK.to_vec());\n\n let exth = ExtHeader::parse(&mut reader).unwrap();\n", "file_path": "src/headers/exth.rs", "rank": 23, "score": 48657.46496018674 }, { "content": " ))\n\n }\n\n }\n\n\n\n /// Gets header records\n\n fn populate_records<R: io::Read>(&mut self, reader: &mut Reader<R>) -> io::Result<()> {\n\n for _i in 0..self.record_count {\n\n let record_type = ExthRecord::from(reader.read_u32_be()?);\n\n let record_len = reader.read_u32_be()?;\n\n\n\n let mut record_data = vec![0; (record_len - 8) as usize];\n\n reader.read_exact(&mut record_data)?;\n\n\n\n if let Some(record) = self.records.get_mut(&record_type) {\n\n record.push(record_data);\n\n } else {\n\n self.records.insert(record_type, vec![record_data]);\n\n }\n\n }\n\n\n", "file_path": "src/headers/exth.rs", "rank": 24, "score": 48657.139199664634 }, { "content": " 405 => IsRented,\n\n 406 => BorrowExpirationDate,\n\n 501 => Cdetype,\n\n 502 => LastUpdateTime,\n\n 503 => Title,\n\n 524 => Language,\n\n n => Other(n),\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Default, PartialEq)]\n\n/// Optional header containing extended information. If the MOBI header\n\n/// indicates that there's an EXTH header, it follows immediately after\n\n/// the MOBI header.\n\npub struct ExtHeader {\n\n pub identifier: u32,\n\n pub header_length: u32,\n\n pub record_count: u32,\n\n pub records: IndexMap<ExthRecord, Vec<Vec<u8>>>,\n", "file_path": "src/headers/exth.rs", "rank": 25, "score": 48655.92209842272 }, { "content": "use crate::{Reader, Writer};\n\n\n\nuse indexmap::IndexMap;\n\nuse std::io;\n\n\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]\n\n// Records available in EXTH header\n\npub enum ExthRecord {\n\n // source - https://wiki.mobileread.com/wiki/MOBI#EXTH_Header\n\n DrmServerId,\n\n DrmCommerceId,\n\n DrmEbookbaseBookId,\n\n Author,\n\n Publisher,\n\n Imprint,\n\n Description,\n\n Isbn,\n\n Subject,\n\n PublishDate,\n\n Review,\n", "file_path": "src/headers/exth.rs", "rank": 26, "score": 48654.98741928723 }, { "content": " (202.into(), vec![b\"\\0\\0\\0\\x01\".to_vec()]),\n\n (108.into(), vec![b\"calibre (0.7.31) [http://calibre-ebook.com]\".to_vec()]),\n\n ];\n\n _records.into_iter().for_each(|(k, v)| {\n\n records.insert(k, v);\n\n });\n\n\n\n let extheader = ExtHeader {\n\n identifier: 1163416648,\n\n header_length: 1109,\n\n record_count: 11,\n\n records,\n\n };\n\n\n\n let mut reader = book::u8_reader(book::BOOK.to_vec());\n\n let parsed_header = ExtHeader::parse(&mut reader).unwrap();\n\n for (k, v) in &extheader.records {\n\n let record = parsed_header.get_record(*k);\n\n assert!(record.is_some());\n\n assert_eq!(v, record.unwrap());\n", "file_path": "src/headers/exth.rs", "rank": 27, "score": 48652.41169158151 }, { "content": " TamperProofKeys => 209,\n\n FontSignature => 300,\n\n ClippingLimit => 401,\n\n PublisherLimit => 402,\n\n TtsFlag => 404,\n\n IsRented => 405,\n\n BorrowExpirationDate => 406,\n\n Cdetype => 501,\n\n LastUpdateTime => 502,\n\n Title => 503,\n\n Language => 524,\n\n Other(n) => n,\n\n }\n\n }\n\n}\n\n\n\nimpl From<u32> for ExthRecord {\n\n fn from(ty: u32) -> Self {\n\n use ExthRecord::*;\n\n match ty {\n", "file_path": "src/headers/exth.rs", "rank": 28, "score": 48651.99255958876 }, { "content": " }\n\n Ok(())\n\n }\n\n\n\n /// Returns exth record data located at position. This is a low level function intended\n\n /// to use with wrapper get_record, but exposed for convienience.\n\n pub fn get_record_position(&self, position: u32) -> Option<&Vec<Vec<u8>>> {\n\n self.get_record(ExthRecord::from(position))\n\n }\n\n\n\n /// Returns exth record data. This function limits possible queried records to only those\n\n /// commonly available among mobi ebooks.\n\n pub fn get_record(&self, record: ExthRecord) -> Option<&Vec<Vec<u8>>> {\n\n self.records.get(&record)\n\n }\n\n\n\n /// Returns an iterator over all available raw EXTH records.\n\n pub fn raw_records(&self) -> impl Iterator<Item = (&ExthRecord, &Vec<Vec<u8>>)> {\n\n self.records.iter()\n\n }\n", "file_path": "src/headers/exth.rs", "rank": 29, "score": 48651.11404649738 }, { "content": "\n\nimpl From<ExthRecord> for u32 {\n\n fn from(r: ExthRecord) -> Self {\n\n use ExthRecord::*;\n\n match r {\n\n DrmServerId => 1,\n\n DrmCommerceId => 2,\n\n DrmEbookbaseBookId => 3,\n\n Author => 100,\n\n Publisher => 101,\n\n Imprint => 102,\n\n Description => 103,\n\n Isbn => 104,\n\n Subject => 105,\n\n PublishDate => 106,\n\n Review => 107,\n\n Contributor => 108,\n\n Rights => 109,\n\n Subjectcode => 110,\n\n Type => 111,\n", "file_path": "src/headers/exth.rs", "rank": 30, "score": 48650.193632566006 }, { "content": " }\n\n assert_eq!(extheader, parsed_header);\n\n }\n\n\n\n #[test]\n\n fn test_exth_records() {\n\n let mut _records: Vec<(ExthRecord, Vec<String>)> = vec![\n\n (ExthRecord::Isbn, vec![\"9780261102316\".to_string()]),\n\n (ExthRecord::Title, vec![\"Lord of the Rings - Fellowship of the Ring\".to_string()]),\n\n (ExthRecord::HasFakeCover, vec![\"\\0\\0\\0\\0\".to_string()]),\n\n (ExthRecord::Description, vec![\"<h3>From Library Journal</h3><p>New Line Cinema will be releasing \\\"The Lord of the Rings\\\" trilogy in three separate installments, and Houghton Mifflin Tolkien's U.S. publisher since the release of The Hobbit in 1938 will be re-releasing each volume of the trilogy separately and in a boxed set (ISBN 0-618-15397-7. $22; pap. ISBN 0-618-15396-9. $12). <br />Copyright 2001 Reed Business Information, Inc. </p><h3>Review</h3><p>'An extraordinary book. It deals with a stupendous theme. It leads us through a succession of strange and astonishing episodes, some of them magnificent, in a region where everything is invented, forest, moor, river, wilderness, town and the races which inhabit them.' The Observer 'Among the greatest works of imaginative fiction of the twentieth century.' Sunday Telegraph </p>\".to_string()]),\n\n (ExthRecord::CoverOffset, vec![\"\\0\\0\\0\\0\".to_string()]),\n\n (ExthRecord::Publisher, vec![\"HarperCollins Publishers Ltd\".to_string()]),\n\n (ExthRecord::PublishDate, vec![\"2010-12-21T00:00:00+00:00\".to_string(),\"2010-12-21T00:00:00+00:00\".to_string()]),\n\n (ExthRecord::Author, vec![\"J. R. R. Tolkien\".to_string()]),\n\n (ExthRecord::ThumbOffset, vec![\"\\0\\0\\0\\x01\".to_string()]),\n\n (ExthRecord::Contributor, vec![\"calibre (0.7.31) [http://calibre-ebook.com]\".to_string()]),\n\n ];\n\n\n\n let mut reader = book::u8_reader(book::BOOK.to_vec());\n", "file_path": "src/headers/exth.rs", "rank": 31, "score": 48649.724952016084 }, { "content": "\n\n /// Returns an iterator over all available EXTH records and performs a loseless conversion of\n\n /// record data to string.\n\n pub fn records(&self) -> impl Iterator<Item = (&ExthRecord, Vec<String>)> {\n\n self.records.iter().map(|(r, data)| {\n\n (\n\n r,\n\n data.iter()\n\n .map(|d| String::from_utf8_lossy(d).to_string())\n\n .collect(),\n\n )\n\n })\n\n }\n\n\n\n pub(crate) fn get_record_string_lossy(&self, record: ExthRecord) -> Option<String> {\n\n self.get_record(record)\n\n .and_then(|r| r.first())\n\n .map(|r| String::from_utf8_lossy(r).to_string())\n\n }\n\n}\n", "file_path": "src/headers/exth.rs", "rank": 32, "score": 48647.88120783786 }, { "content": "\n\n // This fields are unsure\n\n /// 1 in this field seems to indicate a rental book\n\n IsRented,\n\n /// If this field is removed from a rental, the book says it expired in 1969\n\n BorrowExpirationDate,\n\n //\n\n ///PDOC - Personal Doc; EBOK - ebook; EBSP - ebook sample;\n\n Cdetype,\n\n LastUpdateTime,\n\n Title,\n\n Language,\n\n Other(u32),\n\n}\n\n\n\nimpl ExthRecord {\n\n pub fn position(&self) -> u32 {\n\n (*self).into()\n\n }\n\n}\n", "file_path": "src/headers/exth.rs", "rank": 33, "score": 48647.268130296026 }, { "content": " Ok(())\n\n }\n\n\n\n pub(crate) fn write<W: io::Write>(&self, w: &mut Writer<W>) -> io::Result<()> {\n\n w.write_be(self.identifier)?;\n\n w.write_be(\n\n 12u32\n\n + self\n\n .records\n\n .iter()\n\n .map(|(_, d)| 8 + d.len() as u32)\n\n .sum::<u32>(),\n\n )?;\n\n w.write_be(self.records.len() as u32)?;\n\n for (&id, records) in self.records.iter() {\n\n for record_data in records {\n\n w.write_be(id.position())?;\n\n w.write_be(record_data.len() as u32 + 8)?;\n\n w.write_be(record_data)?;\n\n }\n", "file_path": "src/headers/exth.rs", "rank": 34, "score": 48646.09254012007 }, { "content": " DictionaryShortName,\n\n /// Add to first image field in Mobi Header to find PDB record containing the cover image\n\n CoverOffset,\n\n /// Add to first image field in Mobi Header to find PDB record containing the thumbnail cover image\n\n ThumbOffset,\n\n HasFakeCover,\n\n /// Known Values: 1=mobigen, 2=Mobipocket Creator, 200=kindlegen (Windows), 201=kindlegen (Linux), 202=kindlegen (Mac). Warning: Calibre creates fake creator entries, pretending to be a Linux kindlegen 1.2 (201, 1, 2, 33307) for normal ebooks and a non-public Linux kindlegen 2.0 (201, 2, 0, 101) for periodicals.\n\n CreatorSoftware,\n\n CreatoreMajorVersion,\n\n CreatorMinorVersion,\n\n CreatorBuildNumber,\n\n Watermark,\n\n /// Used by the Kindle (and Android app) for generating book-specific PIDs.\n\n TamperProofKeys,\n\n FontSignature,\n\n /// Integer percentage of the text allowed to be clipped. Usually 10.\n\n ClippingLimit,\n\n PublisherLimit,\n\n /// 1 - Text to Speech disabled; 0 - Text to Speech enabled\n\n TtsFlag,\n", "file_path": "src/headers/exth.rs", "rank": 35, "score": 48645.00007682923 }, { "content": "\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::book;\n\n use pretty_assertions::assert_eq;\n\n\n\n #[test]\n\n fn test_parse() {\n\n let mut records = IndexMap::new();\n\n #[rustfmt::skip]\n\n let _records = vec![\n\n (104.into(), vec![b\"9780261102316\".to_vec()]),\n\n (503.into(), vec![b\"Lord of the Rings - Fellowship of the Ring\".to_vec()]),\n\n (203.into(), vec![b\"\\0\\0\\0\\0\".to_vec()]),\n\n (103.into(), vec![b\"<h3>From Library Journal</h3><p>New Line Cinema will be releasing \\\"The Lord of the Rings\\\" trilogy in three separate installments, and Houghton Mifflin Tolkien's U.S. publisher since the release of The Hobbit in 1938 will be re-releasing each volume of the trilogy separately and in a boxed set (ISBN 0-618-15397-7. $22; pap. ISBN 0-618-15396-9. $12). <br />Copyright 2001 Reed Business Information, Inc. </p><h3>Review</h3><p>'An extraordinary book. It deals with a stupendous theme. It leads us through a succession of strange and astonishing episodes, some of them magnificent, in a region where everything is invented, forest, moor, river, wilderness, town and the races which inhabit them.' The Observer 'Among the greatest works of imaginative fiction of the twentieth century.' Sunday Telegraph </p>\".to_vec()]),\n\n (201.into(), vec![b\"\\0\\0\\0\\0\".to_vec()]),\n\n (101.into(), vec![b\"HarperCollins Publishers Ltd\".to_vec()]),\n\n (106.into(), vec![b\"2010-12-21T00:00:00+00:00\".to_vec(),b\"2010-12-21T00:00:00+00:00\".to_vec()]),\n\n (100.into(), vec![b\"J. R. R. Tolkien\".to_vec()]),\n", "file_path": "src/headers/exth.rs", "rank": 36, "score": 48644.47771713341 }, { "content": " let data = exth.get_record_string_lossy(ExthRecord::$t);\n\n assert_eq!(data, Some(String::from($s)));\n\n };\n\n }\n\n\n\n #[test]\n\n fn author() {\n\n info!(Author, \"J. R. R. Tolkien\");\n\n }\n\n\n\n #[test]\n\n fn publisher() {\n\n info!(Publisher, \"HarperCollins Publishers Ltd\");\n\n }\n\n\n\n #[test]\n\n fn description() {\n\n info!(Description, \"<h3>From Library Journal</h3><p>New Line Cinema will be releasing \\\"The Lord of the Rings\\\" trilogy in three separate installments, and Houghton Mifflin Tolkien\\'s U.S. publisher since the release of The Hobbit in 1938 will be re-releasing each volume of the trilogy separately and in a boxed set (ISBN 0-618-15397-7. $22; pap. ISBN 0-618-15396-9. $12). <br />Copyright 2001 Reed Business Information, Inc. </p><h3>Review</h3><p>\\'An extraordinary book. It deals with a stupendous theme. It leads us through a succession of strange and astonishing episodes, some of them magnificent, in a region where everything is invented, forest, moor, river, wilderness, town and the races which inhabit them.\\' The Observer \\'Among the greatest works of imaginative fiction of the twentieth century.\\' Sunday Telegraph </p>\");\n\n }\n\n\n", "file_path": "src/headers/exth.rs", "rank": 37, "score": 48642.40485998816 }, { "content": " Source => 112,\n\n Asin => 113,\n\n VersionNumber => 114,\n\n Sample => 115,\n\n Startreading => 116,\n\n Adult => 117,\n\n RetailPrice => 118,\n\n RetailPriceCurrency => 119,\n\n KF8BoundaryOffset => 121,\n\n CountOfResources => 125,\n\n KF8CoverURI => 129,\n\n DictionaryShortName => 200,\n\n CoverOffset => 201,\n\n ThumbOffset => 202,\n\n HasFakeCover => 203,\n\n CreatorSoftware => 204,\n\n CreatoreMajorVersion => 205,\n\n CreatorMinorVersion => 206,\n\n CreatorBuildNumber => 207,\n\n Watermark => 208,\n", "file_path": "src/headers/exth.rs", "rank": 38, "score": 48638.59226938024 }, { "content": " 117 => Adult,\n\n 118 => RetailPrice,\n\n 119 => RetailPriceCurrency,\n\n 121 => KF8BoundaryOffset,\n\n 125 => CountOfResources,\n\n 129 => KF8CoverURI,\n\n 200 => DictionaryShortName,\n\n 201 => CoverOffset,\n\n 202 => ThumbOffset,\n\n 203 => HasFakeCover,\n\n 204 => CreatorSoftware,\n\n 205 => CreatoreMajorVersion,\n\n 206 => CreatorMinorVersion,\n\n 207 => CreatorBuildNumber,\n\n 208 => Watermark,\n\n 209 => TamperProofKeys,\n\n 300 => FontSignature,\n\n 401 => ClippingLimit,\n\n 402 => PublisherLimit,\n\n 404 => TtsFlag,\n", "file_path": "src/headers/exth.rs", "rank": 39, "score": 48638.4867990493 }, { "content": " Contributor,\n\n Rights,\n\n Subjectcode,\n\n Type,\n\n Source,\n\n Asin,\n\n VersionNumber,\n\n /// 0x0001 if the book content is only a sample of the full book\n\n Sample,\n\n /// Position (4-byte offset) in file at which to open when first opened\n\n Startreading,\n\n /// Mobipocket Creator adds this if Adult only is checked on its GUI; contents: \"yes\"\n\n Adult,\n\n /// As text, e.g. \"4.99\"\n\n RetailPrice,\n\n /// As text, e.g. \"USD\"\n\n RetailPriceCurrency,\n\n KF8BoundaryOffset,\n\n CountOfResources,\n\n KF8CoverURI,\n", "file_path": "src/headers/exth.rs", "rank": 40, "score": 48636.34828913833 }, { "content": " #[test]\n\n fn isbn() {\n\n info!(Isbn, \"9780261102316\");\n\n }\n\n\n\n #[test]\n\n fn publish_date() {\n\n info!(PublishDate, \"2010-12-21T00:00:00+00:00\");\n\n }\n\n\n\n #[test]\n\n fn contributor() {\n\n info!(Contributor, \"calibre (0.7.31) [http://calibre-ebook.com]\");\n\n }\n\n\n\n #[test]\n\n fn title() {\n\n info!(Title, \"Lord of the Rings - Fellowship of the Ring\");\n\n }\n\n }\n\n}\n", "file_path": "src/headers/exth.rs", "rank": 41, "score": 48636.34828913833 }, { "content": " 1 => DrmServerId,\n\n 2 => DrmCommerceId,\n\n 3 => DrmEbookbaseBookId,\n\n 100 => Author,\n\n 101 => Publisher,\n\n 102 => Imprint,\n\n 103 => Description,\n\n 104 => Isbn,\n\n 105 => Subject,\n\n 106 => PublishDate,\n\n 107 => Review,\n\n 108 => Contributor,\n\n 109 => Rights,\n\n 110 => Subjectcode,\n\n 111 => Type,\n\n 112 => Source,\n\n 113 => Asin,\n\n 114 => VersionNumber,\n\n 115 => Sample,\n\n 116 => Startreading,\n", "file_path": "src/headers/exth.rs", "rank": 42, "score": 48636.34828913833 }, { "content": " first_index_record: 0xFFFF_FFFF,\n\n unused_9: vec![],\n\n }\n\n }\n\n}\n\n\n\nimpl MobiHeader {\n\n /// Parse a Mobi header from the content. The reader must be advanced to the starting\n\n /// position of the Mobi header.\n\n pub(crate) fn parse<R: io::Read>(reader: &mut Reader<R>) -> io::Result<MobiHeader> {\n\n let identifier = reader.read_u32_be()?;\n\n if &identifier.to_be_bytes() != b\"MOBI\" {\n\n return Err(io::Error::new(\n\n io::ErrorKind::InvalidData,\n\n \"invalid header identifier (expected MOBI)\",\n\n ));\n\n }\n\n let header_length = reader.read_u32_be()?;\n\n\n\n Ok(MobiHeader {\n", "file_path": "src/headers/mobih.rs", "rank": 43, "score": 48046.45534447323 }, { "content": "}\n\n\n\nimpl Default for Language {\n\n fn default() -> Self {\n\n Language::Neutral\n\n }\n\n}\n\n\n\nimpl WriteBeBytes for Language {\n\n fn write_be_bytes<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {\n\n u8::from(*self).write_be_bytes(writer)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{Language, MobiHeader, MobiType, TextEncoding};\n\n use crate::book;\n\n use crate::writer::Writer;\n\n\n", "file_path": "src/headers/mobih.rs", "rank": 44, "score": 48043.46264850513 }, { "content": " extra_record_data_flags: reader.read_u32_be()?,\n\n first_index_record: reader.read_u32_be()?,\n\n unused_9: {\n\n let mut unused = vec![0; header_length as usize - 232];\n\n reader.read_exact(&mut unused)?;\n\n unused\n\n },\n\n })\n\n }\n\n\n\n /// Parse a Mobi header from the content. The reader must be advanced to the starting\n\n /// position of the Mobi header.\n\n pub(crate) fn write<W: io::Write>(&self, w: &mut Writer<W>) -> io::Result<()> {\n\n w.write_be(self.identifier)?;\n\n w.write_be(self.header_length)?;\n\n w.write_be(self.mobi_type)?;\n\n w.write_be(self.text_encoding)?;\n\n w.write_be(self.id)?;\n\n w.write_be(self.gen_version)?;\n\n w.write_be(self.ortho_index)?;\n", "file_path": "src/headers/mobih.rs", "rank": 45, "score": 48041.34131027723 }, { "content": " unused_5: u32, // flis record count?\n\n unused_6: u64,\n\n unused_7: u32,\n\n first_compilation_data_section_count: u32,\n\n data_section_count: u32,\n\n unused_8: u32,\n\n extra_record_data_flags: u32,\n\n pub first_index_record: u32,\n\n unused_9: Vec<u8>,\n\n}\n\n\n\nimpl Default for MobiHeader {\n\n fn default() -> Self {\n\n MobiHeader {\n\n identifier: 0,\n\n header_length: 0,\n\n mobi_type: MobiType::default(),\n\n text_encoding: TextEncoding::default(),\n\n id: 0,\n\n gen_version: 0,\n", "file_path": "src/headers/mobih.rs", "rank": 46, "score": 48037.04151479006 }, { "content": " unused_3: 1,\n\n unused_4: 1,\n\n unused_5: 1,\n\n unused_6: 0,\n\n unused_7: 0xFFFF_FFFF,\n\n first_compilation_data_section_count: 0,\n\n data_section_count: 0xFFFF_FFFF,\n\n unused_8: 0xFFFF_FFFF,\n\n extra_record_data_flags: 7,\n\n first_index_record: 284,\n\n unused_9: vec![],\n\n };\n\n\n\n let mut reader = book::u8_reader(book::MOBIHEADER.to_vec());\n\n let test_header = MobiHeader::parse(&mut reader).unwrap();\n\n\n\n assert_eq!(mobiheader, test_header);\n\n }\n\n\n\n #[test]\n", "file_path": "src/headers/mobih.rs", "rank": 47, "score": 48036.82446619371 }, { "content": " name_length: reader.read_u32_be()?,\n\n unused: reader.read_u16_be()?,\n\n locale: reader.read_u8()?,\n\n language_code: reader.read_u8()?.into(),\n\n input_language: reader.read_u32_be()?,\n\n output_language: reader.read_u32_be()?,\n\n format_version: reader.read_u32_be()?,\n\n first_image_index: reader.read_u32_be()?,\n\n first_huff_record: reader.read_u32_be()?,\n\n huff_record_count: reader.read_u32_be()?,\n\n huff_table_offset: reader.read_u32_be()?,\n\n huff_table_length: reader.read_u32_be()?,\n\n exth_flags: reader.read_u32_be()?,\n\n unused_0: {\n\n let mut bytes = [0; 32];\n\n reader.read_exact(&mut bytes)?;\n\n Box::new(bytes)\n\n },\n\n unused_1: reader.read_u32_be()?,\n\n drm_offset: reader.read_u32_be()?,\n", "file_path": "src/headers/mobih.rs", "rank": 48, "score": 48036.00402987107 }, { "content": " w.write_be(self.extra_record_data_flags)?;\n\n w.write_be(self.first_index_record)?;\n\n w.write_be(self.unused_9.as_slice())\n\n }\n\n\n\n /// Checks if there is a Exth Header and changes the parameter\n\n pub fn has_exth_header(&self) -> bool {\n\n (self.exth_flags & EXTH_ON_FLAG) != 0\n\n }\n\n\n\n /// Checks if there is DRM on this book\n\n pub fn has_drm(&self) -> bool {\n\n self.drm_offset != DRM_ON_FLAG\n\n }\n\n\n\n /// Converts numerical value into a type\n\n pub fn mobi_type(&self) -> MobiType {\n\n self.mobi_type\n\n }\n\n\n", "file_path": "src/headers/mobih.rs", "rank": 49, "score": 48035.81736865054 }, { "content": "use crate::writer::WriteBeBytes;\n\nuse crate::{Reader, Writer};\n\n\n\nuse std::io;\n\n\n\nconst DRM_ON_FLAG: u32 = 0xFFFF_FFFF;\n\nconst EXTH_ON_FLAG: u32 = 0x40;\n\n\n\n#[derive(Debug, PartialEq, Copy, Clone)]\n\npub enum MobiType {\n\n MobiPocketBook,\n\n PalmDocBook,\n\n Audio,\n\n News,\n\n NewsFeed,\n\n NewsMagazine,\n\n PICS,\n\n WORD,\n\n XLS,\n\n PPT,\n", "file_path": "src/headers/mobih.rs", "rank": 50, "score": 48035.47945984232 }, { "content": " fn test_write() {\n\n let input_bytes = book::MOBIHEADER.to_vec();\n\n\n\n let mobiheader = MobiHeader::parse(&mut book::u8_reader(input_bytes.clone())).unwrap();\n\n\n\n let mut output_bytes = vec![];\n\n assert!(mobiheader\n\n .write(&mut Writer::new(&mut output_bytes))\n\n .is_ok());\n\n assert_eq!(input_bytes.len(), output_bytes.len());\n\n assert_eq!(input_bytes, output_bytes);\n\n }\n\n}\n", "file_path": "src/headers/mobih.rs", "rank": 51, "score": 48035.40500386029 }, { "content": " TEXT,\n\n HTML,\n\n Unknown,\n\n}\n\n\n\nimpl Default for MobiType {\n\n fn default() -> Self {\n\n MobiType::Unknown\n\n }\n\n}\n\n\n\nimpl From<u32> for MobiType {\n\n fn from(ty: u32) -> Self {\n\n use MobiType::*;\n\n match ty {\n\n 2 => MobiPocketBook,\n\n 3 => PalmDocBook,\n\n 4 => Audio,\n\n 257 => News,\n\n 258 => NewsFeed,\n", "file_path": "src/headers/mobih.rs", "rank": 52, "score": 48035.33812423011 }, { "content": " identifier,\n\n header_length,\n\n mobi_type: reader.read_u32_be()?.into(),\n\n text_encoding: reader.read_u32_be()?.into(),\n\n id: reader.read_u32_be()?,\n\n gen_version: reader.read_u32_be()?,\n\n ortho_index: reader.read_u32_be()?,\n\n inflect_index: reader.read_u32_be()?,\n\n index_names: reader.read_u32_be()?,\n\n index_keys: reader.read_u32_be()?,\n\n extra_indices: [\n\n reader.read_u32_be()?,\n\n reader.read_u32_be()?,\n\n reader.read_u32_be()?,\n\n reader.read_u32_be()?,\n\n reader.read_u32_be()?,\n\n reader.read_u32_be()?,\n\n ],\n\n first_non_book_index: reader.read_u32_be()?,\n\n name_offset: reader.read_u32_be()?,\n", "file_path": "src/headers/mobih.rs", "rank": 53, "score": 48034.59545345812 }, { "content": " fn test_drm() {\n\n let mobiheader = MobiHeader {\n\n drm_offset: 1,\n\n ..Default::default()\n\n };\n\n\n\n assert!(mobiheader.has_drm());\n\n }\n\n\n\n #[test]\n\n fn test_no_drm() {\n\n let mobiheader = MobiHeader {\n\n drm_offset: 0xFFFF_FFFF,\n\n ..Default::default()\n\n };\n\n\n\n assert!(!mobiheader.has_drm());\n\n }\n\n\n\n #[test]\n", "file_path": "src/headers/mobih.rs", "rank": 54, "score": 48034.193614258336 }, { "content": "}\n\n\n\nimpl From<TextEncoding> for u32 {\n\n fn from(encoding: TextEncoding) -> Self {\n\n match encoding {\n\n TextEncoding::CP1252 => 1252,\n\n TextEncoding::UTF8 => 65001,\n\n TextEncoding::Unknown(n) => n,\n\n }\n\n }\n\n}\n\n\n\nimpl WriteBeBytes for TextEncoding {\n\n fn write_be_bytes<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {\n\n u32::from(*self).write_be_bytes(writer)\n\n }\n\n}\n\n\n\n#[derive(Debug, PartialEq)]\n\n/// Strcture that holds Mobi header information\n", "file_path": "src/headers/mobih.rs", "rank": 55, "score": 48034.17503776838 }, { "content": " drm_count: reader.read_u32_be()?,\n\n drm_size: reader.read_u32_be()?,\n\n drm_flags: reader.read_u32_be()?,\n\n unused_2: {\n\n let mut bytes = [0; 8];\n\n reader.read_exact(&mut bytes)?;\n\n Box::new(bytes)\n\n },\n\n first_content_record: reader.read_u16_be()?,\n\n last_content_record: reader.read_u16_be()?,\n\n unused_3: reader.read_u32_be()?,\n\n fcis_record: reader.read_u32_be()?,\n\n unused_4: reader.read_u32_be()?,\n\n flis_record: reader.read_u32_be()?,\n\n unused_5: reader.read_u32_be()?,\n\n unused_6: reader.read_u64_be()?,\n\n unused_7: reader.read_u32_be()?,\n\n first_compilation_data_section_count: reader.read_u32_be()?,\n\n data_section_count: reader.read_u32_be()?,\n\n unused_8: reader.read_u32_be()?,\n", "file_path": "src/headers/mobih.rs", "rank": 56, "score": 48033.75592989133 }, { "content": "pub struct MobiHeader {\n\n pub identifier: u32,\n\n pub header_length: u32,\n\n pub mobi_type: MobiType,\n\n pub text_encoding: TextEncoding,\n\n pub id: u32,\n\n pub gen_version: u32,\n\n pub ortho_index: u32,\n\n pub inflect_index: u32,\n\n pub index_names: u32,\n\n pub index_keys: u32,\n\n pub extra_indices: [u32; 6],\n\n pub first_non_book_index: u32,\n\n pub name_offset: u32,\n\n pub name_length: u32,\n\n unused: u16,\n\n pub locale: u8,\n\n pub language_code: Language,\n\n pub input_language: u32,\n\n pub output_language: u32,\n", "file_path": "src/headers/mobih.rs", "rank": 57, "score": 48032.425938546476 }, { "content": " #[test]\n\n fn test_parse() {\n\n let mobiheader = MobiHeader {\n\n identifier: 1297039945,\n\n header_length: 232,\n\n mobi_type: MobiType::MobiPocketBook,\n\n text_encoding: TextEncoding::UTF8,\n\n id: 3428045761,\n\n gen_version: 6,\n\n ortho_index: 0xFFFF_FFFF,\n\n inflect_index: 0xFFFF_FFFF,\n\n index_names: 0xFFFF_FFFF,\n\n index_keys: 0xFFFF_FFFF,\n\n extra_indices: [0xFFFF_FFFF; 6],\n\n first_non_book_index: 284,\n\n name_offset: 1360,\n\n name_length: 42,\n\n unused: 0,\n\n locale: 8,\n\n language_code: Language::English,\n", "file_path": "src/headers/mobih.rs", "rank": 58, "score": 48031.52662397992 }, { "content": "pub enum TextEncoding {\n\n CP1252,\n\n UTF8,\n\n Unknown(u32),\n\n}\n\n\n\nimpl Default for TextEncoding {\n\n fn default() -> Self {\n\n TextEncoding::UTF8\n\n }\n\n}\n\n\n\nimpl From<u32> for TextEncoding {\n\n fn from(num: u32) -> Self {\n\n match num {\n\n 1252 => TextEncoding::CP1252,\n\n 65001 => TextEncoding::UTF8,\n\n n => TextEncoding::Unknown(n),\n\n }\n\n }\n", "file_path": "src/headers/mobih.rs", "rank": 59, "score": 48031.383116584744 }, { "content": " NewsFeed => 258,\n\n NewsMagazine => 259,\n\n PICS => 513,\n\n WORD => 514,\n\n XLS => 515,\n\n PPT => 516,\n\n TEXT => 517,\n\n HTML => 518,\n\n Unknown => 0,\n\n }\n\n }\n\n}\n\n\n\nimpl WriteBeBytes for MobiType {\n\n fn write_be_bytes<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {\n\n u32::from(*self).write_be_bytes(writer)\n\n }\n\n}\n\n\n\n#[derive(Debug, PartialEq, Copy, Clone)]\n", "file_path": "src/headers/mobih.rs", "rank": 60, "score": 48030.15587003768 }, { "content": " pub format_version: u32,\n\n pub first_image_index: u32,\n\n pub first_huff_record: u32,\n\n pub huff_record_count: u32,\n\n pub huff_table_offset: u32,\n\n pub huff_table_length: u32,\n\n pub exth_flags: u32,\n\n unused_0: Box<[u8; 32]>,\n\n unused_1: u32,\n\n pub drm_offset: u32,\n\n pub drm_count: u32,\n\n pub drm_size: u32,\n\n pub drm_flags: u32,\n\n unused_2: Box<[u8; 8]>,\n\n pub first_content_record: u16,\n\n pub last_content_record: u16,\n\n unused_3: u32,\n\n pub fcis_record: u32,\n\n unused_4: u32, // fcis record count?\n\n pub flis_record: u32,\n", "file_path": "src/headers/mobih.rs", "rank": 61, "score": 48029.15998343508 }, { "content": " 259 => NewsMagazine,\n\n 513 => PICS,\n\n 514 => WORD,\n\n 515 => XLS,\n\n 516 => PPT,\n\n 517 => TEXT,\n\n 518 => HTML,\n\n _ => Unknown,\n\n }\n\n }\n\n}\n\n\n\nimpl From<MobiType> for u32 {\n\n fn from(ty: MobiType) -> u32 {\n\n use MobiType::*;\n\n match ty {\n\n MobiPocketBook => 2,\n\n PalmDocBook => 3,\n\n Audio => 4,\n\n News => 257,\n", "file_path": "src/headers/mobih.rs", "rank": 62, "score": 48029.000248510376 }, { "content": " 68 => Tatar,\n\n 74 => Telugu,\n\n 30 => Thai,\n\n 49 => Tsonga,\n\n 50 => Tswana,\n\n 31 => Turkish,\n\n 34 => Ukrainian,\n\n 32 => Urdu,\n\n 67 => Uzbek,\n\n 42 => Vietnamese,\n\n 52 => Xhosa,\n\n 53 => Zulu,\n\n _ => Unknown,\n\n }\n\n }\n\n}\n\n\n\nimpl From<Language> for u8 {\n\n fn from(lang: Language) -> Self {\n\n use Language::*;\n", "file_path": "src/headers/mobih.rs", "rank": 63, "score": 48028.65821311584 }, { "content": " Tsonga,\n\n Tswana,\n\n Turkish,\n\n Ukrainian,\n\n Urdu,\n\n Uzbek,\n\n Vietnamese,\n\n Xhosa,\n\n Zulu,\n\n Unknown,\n\n}\n\n\n\nimpl From<u8> for Language {\n\n fn from(code: u8) -> Self {\n\n use Language::*;\n\n match code {\n\n 0 => Neutral,\n\n 54 => Afrikaans,\n\n 28 => Albanian,\n\n 1 => Arabic,\n", "file_path": "src/headers/mobih.rs", "rank": 64, "score": 48028.36609169285 }, { "content": " ortho_index: 0xFFFF_FFFF,\n\n inflect_index: 0xFFFF_FFFF,\n\n index_names: 0xFFFF_FFFF,\n\n index_keys: 0xFFFF_FFFF,\n\n extra_indices: [0xFFFF_FFFF; 6],\n\n first_non_book_index: 0,\n\n name_offset: 0,\n\n name_length: 0,\n\n unused: 0,\n\n locale: 0,\n\n language_code: Language::default(),\n\n input_language: 0,\n\n output_language: 0,\n\n format_version: 0,\n\n first_image_index: 0,\n\n first_huff_record: 0,\n\n huff_record_count: 0,\n\n huff_table_offset: 0,\n\n huff_table_length: 0,\n\n exth_flags: 0,\n", "file_path": "src/headers/mobih.rs", "rank": 65, "score": 48028.018065801996 }, { "content": " w.write_be(self.inflect_index)?;\n\n w.write_be(self.index_names)?;\n\n w.write_be(self.index_keys)?;\n\n for &i in &self.extra_indices {\n\n w.write_be(i)?;\n\n }\n\n w.write_be(self.first_non_book_index)?;\n\n w.write_be(self.name_offset)?;\n\n w.write_be(self.name_length)?;\n\n w.write_be(self.unused)?;\n\n w.write_be(self.locale)?;\n\n w.write_be(self.language_code)?;\n\n w.write_be(self.input_language)?;\n\n w.write_be(self.output_language)?;\n\n w.write_be(self.format_version)?;\n\n w.write_be(self.first_image_index)?;\n\n w.write_be(self.first_huff_record)?;\n\n w.write_be(self.huff_record_count)?;\n\n w.write_be(self.huff_table_offset)?;\n\n w.write_be(self.huff_table_length)?;\n", "file_path": "src/headers/mobih.rs", "rank": 66, "score": 48026.060447126765 }, { "content": " input_language: 0,\n\n output_language: 0,\n\n format_version: 6,\n\n first_image_index: 287,\n\n first_huff_record: 0,\n\n huff_record_count: 0,\n\n huff_table_offset: 0,\n\n huff_table_length: 0,\n\n exth_flags: 80,\n\n drm_offset: 4294967295,\n\n drm_count: 0,\n\n drm_size: 0,\n\n drm_flags: 0,\n\n first_content_record: 1,\n\n last_content_record: 288,\n\n fcis_record: 290,\n\n flis_record: 289,\n\n unused_0: Box::new([0; 32]),\n\n unused_1: 0xFFFF_FFFF,\n\n unused_2: Box::new([0, 0, 0, 0, 0, 0, 0, 0]),\n", "file_path": "src/headers/mobih.rs", "rank": 67, "score": 48025.9497781146 }, { "content": " // Mobi format only specifies this two encodings so\n\n // this should never panic\n\n pub fn text_encoding(&self) -> TextEncoding {\n\n self.text_encoding\n\n }\n\n\n\n pub fn language(&self) -> Language {\n\n self.language_code\n\n }\n\n}\n\n\n\n#[derive(Debug, PartialEq, Copy, Clone)]\n\npub enum Language {\n\n Neutral,\n\n Afrikaans,\n\n Albanian,\n\n Arabic,\n\n Armenian,\n\n Assamese,\n\n Azeri,\n", "file_path": "src/headers/mobih.rs", "rank": 68, "score": 48025.94429699753 }, { "content": " w.write_be(self.exth_flags)?;\n\n w.write_be(self.unused_0.as_ref().as_ref())?;\n\n w.write_be(self.unused_1)?;\n\n w.write_be(self.drm_offset)?;\n\n w.write_be(self.drm_count)?;\n\n w.write_be(self.drm_size)?;\n\n w.write_be(self.drm_flags)?;\n\n w.write_be(self.unused_2.as_ref().as_ref())?;\n\n w.write_be(self.first_content_record)?;\n\n w.write_be(self.last_content_record)?;\n\n w.write_be(self.unused_3)?;\n\n w.write_be(self.fcis_record)?;\n\n w.write_be(self.unused_4)?;\n\n w.write_be(self.flis_record)?;\n\n w.write_be(self.unused_5)?;\n\n w.write_be(self.unused_6)?;\n\n w.write_be(self.unused_7)?;\n\n w.write_be(self.first_compilation_data_section_count)?;\n\n w.write_be(self.data_section_count)?;\n\n w.write_be(self.unused_8)?;\n", "file_path": "src/headers/mobih.rs", "rank": 69, "score": 48025.33438369866 }, { "content": " unused_0: Box::new([0; 32]),\n\n unused_1: 0xFFFF_FFFF,\n\n drm_offset: 0,\n\n drm_count: 0,\n\n drm_size: 0,\n\n drm_flags: 0,\n\n unused_2: Box::new([0; 8]),\n\n first_content_record: 1,\n\n last_content_record: 0,\n\n unused_3: 1,\n\n fcis_record: 0,\n\n unused_4: 1,\n\n flis_record: 0,\n\n unused_5: 1,\n\n unused_6: 0,\n\n unused_7: 0xFFFF_FFFF,\n\n first_compilation_data_section_count: 0,\n\n data_section_count: 0xFFFF_FFFF,\n\n unused_8: 0xFFFF_FFFF,\n\n extra_record_data_flags: 0,\n", "file_path": "src/headers/mobih.rs", "rank": 70, "score": 48023.79485098548 }, { "content": " Basque,\n\n Belarusian,\n\n Bengali,\n\n Bulgarian,\n\n Catalan,\n\n Chinese,\n\n Czech,\n\n Danish,\n\n Dutch,\n\n English,\n\n Estonian,\n\n Faeroese,\n\n Farsi,\n\n Finnish,\n\n French,\n\n Georgian,\n\n German,\n\n Greek,\n\n Gujarati,\n\n Hebrew,\n", "file_path": "src/headers/mobih.rs", "rank": 71, "score": 48020.44184131855 }, { "content": " Polish,\n\n Portuguese,\n\n Punjabi,\n\n Rhaetoromanic,\n\n Romanian,\n\n Russian,\n\n Sami,\n\n Sanskrit,\n\n Serbian,\n\n Slovak,\n\n Slovenian,\n\n Sorbian,\n\n Spanish,\n\n Sutu,\n\n Swahili,\n\n Swedish,\n\n Tamil,\n\n Tatar,\n\n Telugu,\n\n Thai,\n", "file_path": "src/headers/mobih.rs", "rank": 72, "score": 48020.44184131855 }, { "content": " match lang {\n\n Neutral => 0,\n\n Afrikaans => 54,\n\n Albanian => 28,\n\n Arabic => 1,\n\n Armenian => 43,\n\n Assamese => 77,\n\n Azeri => 44,\n\n Basque => 45,\n\n Belarusian => 35,\n\n Bengali => 69,\n\n Bulgarian => 2,\n\n Catalan => 3,\n\n Chinese => 4,\n\n Czech => 5,\n\n Danish => 6,\n\n Dutch => 19,\n\n English => 9,\n\n Estonian => 37,\n\n Faeroese => 56,\n", "file_path": "src/headers/mobih.rs", "rank": 73, "score": 48020.44184131855 }, { "content": " Hindi,\n\n Hungarian,\n\n Icelandic,\n\n Indonesian,\n\n Italian,\n\n Japanese,\n\n Kannada,\n\n Kazak,\n\n Konkani,\n\n Korean,\n\n Latvian,\n\n Lithuanian,\n\n Macedonian,\n\n Malay,\n\n Malayalam,\n\n Maltese,\n\n Marathi,\n\n Nepali,\n\n Norwegian,\n\n Oriya,\n", "file_path": "src/headers/mobih.rs", "rank": 74, "score": 48020.44184131855 }, { "content": " Spanish => 10,\n\n Sutu => 48,\n\n Swahili => 65,\n\n Swedish => 29,\n\n Tamil => 73,\n\n Tatar => 68,\n\n Telugu => 74,\n\n Thai => 30,\n\n Tsonga => 49,\n\n Tswana => 50,\n\n Turkish => 31,\n\n Ukrainian => 34,\n\n Urdu => 32,\n\n Uzbek => 67,\n\n Vietnamese => 42,\n\n Xhosa => 52,\n\n Zulu => 53,\n\n Unknown => u8::MAX,\n\n }\n\n }\n", "file_path": "src/headers/mobih.rs", "rank": 75, "score": 48020.44184131855 }, { "content": " 43 => Armenian,\n\n 77 => Assamese,\n\n 44 => Azeri,\n\n 45 => Basque,\n\n 35 => Belarusian,\n\n 69 => Bengali,\n\n 2 => Bulgarian,\n\n 3 => Catalan,\n\n 4 => Chinese,\n\n 5 => Czech,\n\n 6 => Danish,\n\n 19 => Dutch,\n\n 9 => English,\n\n 37 => Estonian,\n\n 56 => Faeroese,\n\n 41 => Farsi,\n\n 11 => Finnish,\n\n 12 => French,\n\n 55 => Georgian,\n\n 7 => German,\n", "file_path": "src/headers/mobih.rs", "rank": 76, "score": 48020.44184131855 }, { "content": " Farsi => 41,\n\n Finnish => 11,\n\n French => 12,\n\n Georgian => 55,\n\n German => 7,\n\n Greek => 8,\n\n Gujarati => 71,\n\n Hebrew => 13,\n\n Hindi => 57,\n\n Hungarian => 14,\n\n Icelandic => 15,\n\n Indonesian => 33,\n\n Italian => 16,\n\n Japanese => 17,\n\n Kannada => 75,\n\n Kazak => 63,\n\n Konkani => 87,\n\n Korean => 18,\n\n Latvian => 38,\n\n Lithuanian => 39,\n", "file_path": "src/headers/mobih.rs", "rank": 77, "score": 48020.44184131855 }, { "content": " 97 => Nepali,\n\n 20 => Norwegian,\n\n 72 => Oriya,\n\n 21 => Polish,\n\n 22 => Portuguese,\n\n 70 => Punjabi,\n\n 23 => Rhaetoromanic,\n\n 24 => Romanian,\n\n 25 => Russian,\n\n 59 => Sami,\n\n 79 => Sanskrit,\n\n 26 => Serbian,\n\n 27 => Slovak,\n\n 36 => Slovenian,\n\n 46 => Sorbian,\n\n 10 => Spanish,\n\n 48 => Sutu,\n\n 65 => Swahili,\n\n 29 => Swedish,\n\n 73 => Tamil,\n", "file_path": "src/headers/mobih.rs", "rank": 78, "score": 48020.44184131855 }, { "content": " Macedonian => 47,\n\n Malay => 62,\n\n Malayalam => 76,\n\n Maltese => 58,\n\n Marathi => 78,\n\n Nepali => 97,\n\n Norwegian => 20,\n\n Oriya => 72,\n\n Polish => 21,\n\n Portuguese => 22,\n\n Punjabi => 70,\n\n Rhaetoromanic => 23,\n\n Romanian => 24,\n\n Russian => 25,\n\n Sami => 59,\n\n Sanskrit => 79,\n\n Serbian => 26,\n\n Slovak => 27,\n\n Slovenian => 36,\n\n Sorbian => 46,\n", "file_path": "src/headers/mobih.rs", "rank": 79, "score": 48020.44184131855 }, { "content": " 8 => Greek,\n\n 71 => Gujarati,\n\n 13 => Hebrew,\n\n 57 => Hindi,\n\n 14 => Hungarian,\n\n 15 => Icelandic,\n\n 33 => Indonesian,\n\n 16 => Italian,\n\n 17 => Japanese,\n\n 75 => Kannada,\n\n 63 => Kazak,\n\n 87 => Konkani,\n\n 18 => Korean,\n\n 38 => Latvian,\n\n 39 => Lithuanian,\n\n 47 => Macedonian,\n\n 62 => Malay,\n\n 76 => Malayalam,\n\n 58 => Maltese,\n\n 78 => Marathi,\n", "file_path": "src/headers/mobih.rs", "rank": 80, "score": 48020.44184131855 }, { "content": "pub fn decompress(huffs: &[&[u8]], sections: &[&[u8]]) -> HuffmanResult<Vec<Vec<u8>>> {\n\n let mut decoder = HuffmanDecoder::init(huffs)?;\n\n decoder.unpack_sections(sections)\n\n}\n", "file_path": "src/compression/huff.rs", "rank": 81, "score": 37012.10972283298 }, { "content": "#[derive(Debug)]\n\nstruct HuffmanDecoder {\n\n dictionary: HuffmanDictionary,\n\n code_dict: CodeDictionary,\n\n min_codes: MinCodesMapping,\n\n max_codes: MaxCodesMapping,\n\n}\n\n\n\nimpl Default for HuffmanDecoder {\n\n fn default() -> Self {\n\n Self {\n\n dictionary: vec![],\n\n code_dict: [(0, false, 0); 256],\n\n min_codes: [0; 33],\n\n max_codes: [u32::MAX; 33],\n\n }\n\n }\n\n}\n\n\n\nimpl HuffmanDecoder {\n\n fn load_code_dictionary<R: std::io::Read>(\n", "file_path": "src/compression/huff.rs", "rank": 82, "score": 35421.597047755306 }, { "content": "impl Header {\n\n /// Parse a header from the content. The reader must be advanced to the starting position of the\n\n /// header, at byte 0.\n\n pub(crate) fn parse<R: io::Read>(reader: &mut Reader<R>) -> Result<Header, HeaderParseError> {\n\n Ok(Header {\n\n name: {\n\n let bytes = reader.read_vec_header(32)?;\n\n if bytes.starts_with(b\"TPZ\") {\n\n return Err(HeaderParseError::IsTopazError);\n\n } else if bytes.starts_with(b\"\\xeaDRMION\\xee\") {\n\n return Err(HeaderParseError::IsKfxError);\n\n }\n\n bytes\n\n },\n\n attributes: reader.read_u16_be()?,\n\n version: reader.read_u16_be()?,\n\n created: reader.read_u32_be()?,\n\n modified: reader.read_u32_be()?,\n\n backup: reader.read_u32_be()?,\n\n modnum: reader.read_u32_be()?,\n", "file_path": "src/headers/header.rs", "rank": 83, "score": 30082.261942614085 }, { "content": "use crate::{Reader, Writer};\n\n\n\n#[cfg(feature = \"time\")]\n\nuse chrono::NaiveDateTime;\n\nuse std::io;\n\nuse thiserror::Error;\n\n\n\n#[derive(Error, Debug)]\n\npub enum HeaderParseError {\n\n #[error(\"this book is an Amazon Topaz book and it cannot be processed\")]\n\n IsTopazError,\n\n #[error(\"this book is an Amazon KFX book and it cannot be processed\")]\n\n IsKfxError,\n\n #[error(\"expected type header identifier BOOK or TEXT\")]\n\n InvalidTypeIdentifier,\n\n #[error(\"expected creator header identifier MOBI or READ\")]\n\n InvalidCreatorIdentifier,\n\n #[error(transparent)]\n\n IoError(#[from] std::io::Error),\n\n}\n", "file_path": "src/headers/header.rs", "rank": 84, "score": 30080.312146375316 }, { "content": " app_info_id: reader.read_u32_be()?,\n\n sort_info_id: reader.read_u32_be()?,\n\n type_: {\n\n let ty = reader.read_vec_header(4)?;\n\n if ty != b\"BOOK\" && ty != b\"TEXT\" {\n\n return Err(HeaderParseError::InvalidTypeIdentifier);\n\n }\n\n ty\n\n },\n\n creator: {\n\n let creator = reader.read_vec_header(4)?;\n\n if creator != b\"MOBI\" && creator != b\"READ\" {\n\n return Err(HeaderParseError::InvalidCreatorIdentifier);\n\n }\n\n creator\n\n },\n\n unique_id_seed: reader.read_u32_be()?,\n\n next_record_list_id: reader.read_u32_be()?,\n\n num_records: reader.read_u16_be()?,\n\n })\n", "file_path": "src/headers/header.rs", "rank": 85, "score": 30076.32561732988 }, { "content": " fn parse() {\n\n let header = Header {\n\n name: b\"Lord_of_the_Rings_-_Fellowship_\\0\".to_vec(),\n\n attributes: 0,\n\n version: 0,\n\n created: 1299709979,\n\n modified: 1299709979,\n\n backup: 0,\n\n modnum: 0,\n\n app_info_id: 0,\n\n sort_info_id: 0,\n\n type_: b\"BOOK\".to_vec(),\n\n creator: b\"MOBI\".to_vec(),\n\n unique_id_seed: 292,\n\n next_record_list_id: 0,\n\n num_records: 292,\n\n };\n\n\n\n let mut reader = book::u8_reader(book::HEADER.to_vec());\n\n let parsed_header = Header::parse(&mut reader);\n", "file_path": "src/headers/header.rs", "rank": 86, "score": 30074.971425692565 }, { "content": " /// method when `time` feature is disabled.\n\n pub(crate) fn created_datetime(&self) -> u32 {\n\n self.created\n\n }\n\n\n\n #[cfg(not(feature = \"time\"))]\n\n /// Returns a u32 timestamp of last modification. This is a fallback\n\n /// method when `time` feature is disabled.\n\n pub(crate) fn mod_datetime(&self) -> u32 {\n\n self.modified\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::book;\n\n use crate::writer::Writer;\n\n\n\n #[test]\n", "file_path": "src/headers/header.rs", "rank": 87, "score": 30074.304017947994 }, { "content": " assert_eq!(header, parsed_header.unwrap());\n\n }\n\n\n\n #[test]\n\n fn write() {\n\n let header = book::HEADER.to_vec();\n\n\n\n let mut reader = book::u8_reader(header.clone());\n\n let parsed_header = Header::parse(&mut reader).unwrap();\n\n\n\n let mut buf = vec![];\n\n\n\n parsed_header\n\n .write(&mut Writer::new(&mut buf), 292)\n\n .unwrap();\n\n assert_eq!(header.len(), buf.len());\n\n assert_eq!(header, buf);\n\n }\n\n}\n", "file_path": "src/headers/header.rs", "rank": 88, "score": 30071.683980291466 }, { "content": " w.write_be(self.next_record_list_id)?;\n\n w.write_be(num_records)\n\n }\n\n\n\n #[cfg(feature = \"time\")]\n\n /// Returns a chrono::NaiveDateTime timestamp of file creation\n\n /// This field is only available using `time` feature\n\n pub(crate) fn created_datetime(&self) -> NaiveDateTime {\n\n NaiveDateTime::from_timestamp(i64::from(self.created), 0)\n\n }\n\n\n\n #[cfg(feature = \"time\")]\n\n /// Returns a chrono::NaiveDateTime timestamp of file modification\n\n /// This field is only available using `time` feature\n\n pub(crate) fn mod_datetime(&self) -> NaiveDateTime {\n\n NaiveDateTime::from_timestamp(i64::from(self.modified), 0)\n\n }\n\n\n\n #[cfg(not(feature = \"time\"))]\n\n /// Returns a u32 timestamp of creation. This is a fallback\n", "file_path": "src/headers/header.rs", "rank": 89, "score": 30071.4935969524 }, { "content": "\n\n#[derive(Debug, PartialEq, Default)]\n\n/// Strcture that holds header information\n\npub struct Header {\n\n pub name: Vec<u8>,\n\n pub attributes: u16,\n\n pub version: u16,\n\n pub created: u32,\n\n pub modified: u32,\n\n pub backup: u32,\n\n pub modnum: u32,\n\n pub app_info_id: u32,\n\n pub sort_info_id: u32,\n\n pub type_: Vec<u8>,\n\n pub creator: Vec<u8>,\n\n pub unique_id_seed: u32,\n\n pub next_record_list_id: u32,\n\n pub num_records: u16,\n\n}\n\n\n", "file_path": "src/headers/header.rs", "rank": 90, "score": 30071.08386555564 }, { "content": " }\n\n\n\n pub(crate) fn write<W: io::Write>(\n\n &self,\n\n w: &mut Writer<W>,\n\n num_records: u16,\n\n ) -> io::Result<()> {\n\n w.write_be(&self.name)?;\n\n w.write_be(self.attributes)?;\n\n w.write_be(self.version)?;\n\n w.write_be(self.created)?;\n\n // User should change this themselves?\n\n w.write_be(self.modified)?;\n\n w.write_be(self.backup)?;\n\n w.write_be(self.modnum)?;\n\n w.write_be(self.app_info_id)?;\n\n w.write_be(self.sort_info_id)?;\n\n w.write_be(&self.type_)?;\n\n w.write_be(&self.creator)?;\n\n w.write_be(self.unique_id_seed)?;\n", "file_path": "src/headers/header.rs", "rank": 91, "score": 30068.817678665582 }, { "content": "use std::io::{self, Read};\n\n\n\n#[derive(Debug, Default, Clone)]\n\n/// Helper struct for reading header values from content.\n\n/// Only allows forward reads.\n\npub(crate) struct Reader<R> {\n\n reader: R,\n\n position: usize,\n\n}\n\n\n\nimpl<R: std::io::Read> Reader<R> {\n\n pub(crate) fn new(content: R) -> Reader<R> {\n\n Reader {\n\n reader: content,\n\n position: 0,\n\n }\n\n }\n\n\n\n pub(crate) fn read_to_end(&mut self) -> io::Result<Vec<u8>> {\n\n // Zero-fill so that Records parsing works as expected.\n", "file_path": "src/reader.rs", "rank": 92, "score": 28304.506579701185 }, { "content": "\n\nimpl WriteBeBytes for u32 {\n\n fn write_be_bytes<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {\n\n writer.write_all(&self.to_be_bytes())?;\n\n Ok(self.to_be_bytes().len())\n\n }\n\n}\n\n\n\nimpl WriteBeBytes for u64 {\n\n fn write_be_bytes<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {\n\n writer.write_all(&self.to_be_bytes())?;\n\n Ok(self.to_be_bytes().len())\n\n }\n\n}\n\n\n\n#[derive(Debug, Default, Clone)]\n\n/// Helper struct for reading header values from content.\n\n/// Only allows forward reads.\n\npub(crate) struct Writer<W> {\n\n writer: W,\n", "file_path": "src/writer.rs", "rank": 93, "score": 28296.27934785495 }, { "content": " bytes_written: usize,\n\n}\n\n\n\nimpl<W: std::io::Write> Writer<W> {\n\n pub(crate) fn new(writer: W) -> Writer<W> {\n\n Writer {\n\n writer,\n\n bytes_written: 0,\n\n }\n\n }\n\n\n\n pub(crate) fn bytes_written(&self) -> usize {\n\n self.bytes_written\n\n }\n\n\n\n #[inline]\n\n pub(crate) fn write_be<B: WriteBeBytes>(&mut self, b: B) -> io::Result<()> {\n\n self.bytes_written += b.write_be_bytes(&mut self.writer)?;\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/writer.rs", "rank": 94, "score": 28294.192378389955 }, { "content": "use std::io;\n\n\n\npub(crate) trait WriteBeBytes {\n\n fn write_be_bytes<W: io::Write>(&self, writer: &mut W) -> io::Result<usize>;\n\n}\n\n\n\nimpl WriteBeBytes for &[u8] {\n\n fn write_be_bytes<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {\n\n writer.write_all(self)?;\n\n Ok(self.len())\n\n }\n\n}\n\n\n\nimpl WriteBeBytes for Vec<u8> {\n\n fn write_be_bytes<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {\n\n writer.write_all(self)?;\n\n Ok(self.len())\n\n }\n\n}\n\n\n", "file_path": "src/writer.rs", "rank": 95, "score": 28292.205601899586 }, { "content": " let mut first_buf = vec![0; self.position];\n\n // read_to_end appends to the end of the buffer.\n\n self.reader.read_to_end(&mut first_buf)?;\n\n self.position = first_buf.len();\n\n Ok(first_buf)\n\n }\n\n\n\n pub(crate) fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {\n\n self.reader.read_exact(buf)?;\n\n self.position += buf.len();\n\n Ok(())\n\n }\n\n\n\n #[inline]\n\n pub(crate) fn set_position(&mut self, p: usize) -> io::Result<()> {\n\n debug_assert!(p >= self.position, \"{}, {}\", p, self.position);\n\n\n\n if p >= self.position {\n\n std::io::copy(\n\n &mut self.reader.by_ref().take((p - self.position) as u64),\n", "file_path": "src/reader.rs", "rank": 96, "score": 28291.648944245862 }, { "content": " }\n\n\n\n #[inline]\n\n pub(crate) fn read_u16_be(&mut self) -> io::Result<u16> {\n\n let mut bytes = [0; 2];\n\n self.read_exact(&mut bytes)?;\n\n Ok(u16::from_be_bytes(bytes))\n\n }\n\n\n\n #[inline]\n\n #[allow(dead_code)]\n\n pub(crate) fn read_u8(&mut self) -> io::Result<u8> {\n\n let mut bytes = [0; 1];\n\n self.read_exact(&mut bytes)?;\n\n Ok(u8::from_be_bytes(bytes))\n\n }\n\n\n\n pub(crate) fn read_vec_header(&mut self, len: usize) -> io::Result<Vec<u8>> {\n\n let mut buf = vec![0; len];\n\n self.read_exact(&mut buf)?;\n\n Ok(buf)\n\n }\n\n}\n", "file_path": "src/reader.rs", "rank": 97, "score": 28291.429868057727 }, { "content": " &mut io::sink(),\n\n )?;\n\n self.position = p;\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n #[inline]\n\n pub(crate) fn read_u64_be(&mut self) -> io::Result<u64> {\n\n let mut bytes = [0; 8];\n\n self.read_exact(&mut bytes)?;\n\n Ok(u64::from_be_bytes(bytes))\n\n }\n\n\n\n #[inline]\n\n pub(crate) fn read_u32_be(&mut self) -> io::Result<u32> {\n\n let mut bytes = [0; 4];\n\n self.read_exact(&mut bytes)?;\n\n Ok(u32::from_be_bytes(bytes))\n", "file_path": "src/reader.rs", "rank": 98, "score": 28289.528571467145 }, { "content": "impl WriteBeBytes for &Vec<u8> {\n\n fn write_be_bytes<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {\n\n writer.write_all(self)?;\n\n Ok(self.len())\n\n }\n\n}\n\n\n\nimpl WriteBeBytes for u8 {\n\n fn write_be_bytes<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {\n\n writer.write_all(&self.to_be_bytes())?;\n\n Ok(self.to_be_bytes().len())\n\n }\n\n}\n\n\n\nimpl WriteBeBytes for u16 {\n\n fn write_be_bytes<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {\n\n writer.write_all(&self.to_be_bytes())?;\n\n Ok(self.to_be_bytes().len())\n\n }\n\n}\n", "file_path": "src/writer.rs", "rank": 99, "score": 28289.096689868835 } ]
Rust
src/walker.rs
oxidecomputer/openapi-lint
025fc867b7da62b33474d0a765823653a437f362
use indexmap::IndexMap; use openapiv3::{ Components, MediaType, OpenAPI, Operation, Parameter, ParameterSchemaOrContent, PathItem, ReferenceOr, RequestBody, Response, Schema, }; pub(crate) trait SchemaWalker<'a> { type SchemaIterator: Iterator<Item = (Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator; } impl<'a> SchemaWalker<'a> for OpenAPI { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { self.paths .iter() .flat_map(|(_, path)| path.walk()) .chain(self.components.walk()) .collect::<Vec<_>>() .into_iter() } } impl<'a, T> SchemaWalker<'a> for ReferenceOr<T> where T: SchemaWalker<'a>, { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { match self { ReferenceOr::Reference { .. } => Vec::<(Option<String>, &Schema)>::new().into_iter(), ReferenceOr::Item(walker) => walker.walk().collect::<Vec<_>>().into_iter(), } } } impl<'a, T> SchemaWalker<'a> for Option<T> where T: SchemaWalker<'a>, { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { match self { None => Vec::<(Option<String>, &Schema)>::new().into_iter(), Some(walker) => walker.walk().collect::<Vec<_>>().into_iter(), } } } impl<'a> SchemaWalker<'a> for IndexMap<String, ReferenceOr<Schema>> { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { self.iter() .flat_map(|(key, value)| { value .walk() .map(|(_, schema)| (Some(key.clone()), schema)) .collect::<Vec<_>>() .into_iter() }) .collect::<Vec<_>>() .into_iter() } } impl<'a, K> SchemaWalker<'a> for IndexMap<K, MediaType> { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { self.iter() .flat_map(|(_key, value)| value.walk()) .collect::<Vec<_>>() .into_iter() } } impl<'a, K> SchemaWalker<'a> for IndexMap<K, ReferenceOr<Response>> { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { self.iter() .flat_map(|(_key, value)| value.walk()) .collect::<Vec<_>>() .into_iter() } } impl<'a> SchemaWalker<'a> for PathItem { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { self.iter() .flat_map(|(_, op)| SchemaWalker::walk(op)) .chain(self.parameters.iter().flat_map(SchemaWalker::walk)) .collect::<Vec<_>>() .into_iter() } } impl<'a> SchemaWalker<'a> for Operation { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { self.parameters .iter() .flat_map(SchemaWalker::walk) .chain(self.request_body.walk()) .chain(self.responses.default.walk()) .chain(self.responses.responses.walk()) .collect::<Vec<_>>() .into_iter() } } impl<'a> SchemaWalker<'a> for Components { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { self.responses .walk() .chain( self.parameters .iter() .flat_map(|(_, parameter)| parameter.walk()), ) .chain( self.request_bodies .iter() .flat_map(|(_, request_body)| request_body.walk()), ) .chain(self.schemas.walk()) .collect::<Vec<_>>() .into_iter() } } impl<'a> SchemaWalker<'a> for Response { type SchemaIterator = <IndexMap<String, MediaType> as SchemaWalker<'a>>::SchemaIterator; fn walk(&'a self) -> Self::SchemaIterator { self.content.walk() } } impl<'a> SchemaWalker<'a> for MediaType { type SchemaIterator = <Option<Schema> as SchemaWalker<'a>>::SchemaIterator; fn walk(&'a self) -> Self::SchemaIterator { self.schema.walk() } } impl<'a> SchemaWalker<'a> for Parameter { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { match self { Parameter::Query { parameter_data, .. } => parameter_data, Parameter::Header { parameter_data, .. } => parameter_data, Parameter::Path { parameter_data, .. } => parameter_data, Parameter::Cookie { parameter_data, .. } => parameter_data, } .format .walk() } } impl<'a> SchemaWalker<'a> for ParameterSchemaOrContent { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { match self { ParameterSchemaOrContent::Schema(schema) => { schema.walk().collect::<Vec<_>>().into_iter() } ParameterSchemaOrContent::Content(content) => { content.walk().collect::<Vec<_>>().into_iter() } } } } impl<'a> SchemaWalker<'a> for RequestBody { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { self.content.walk() } } impl<'a> SchemaWalker<'a> for Schema { type SchemaIterator = std::iter::Once<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { std::iter::once((None, self)) } }
use indexmap::IndexMap; use openapiv3::{ Components, MediaType, OpenAPI, Operation, Parameter, ParameterSchemaOrContent, PathItem, ReferenceOr, RequestBody, Response, Schema, }; pub(crate) trait SchemaWalker<'a> { type SchemaIterator: Iterator<Item = (Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator; } impl<'a> SchemaWalker<'a> for OpenAPI { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { self.paths .iter() .flat_map(|(_, path)| path.walk()) .chain(self.components.walk()) .collect::<Vec<_>>() .into_iter() } } impl<'a, T> SchemaWalker<'a> for ReferenceOr<T> where T: SchemaWalker<'a>, { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { match self { ReferenceOr::Reference { .. } => Vec::<(Option<String>, &Schema)>::new().into_iter(), ReferenceOr::Item(walker) => walker.walk().collect::<Vec<_>>().into_iter(), } } } impl<'a, T> SchemaWalker<'a> for Option<T> where T: SchemaWalker<'a>, { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>;
} impl<'a> SchemaWalker<'a> for IndexMap<String, ReferenceOr<Schema>> { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { self.iter() .flat_map(|(key, value)| { value .walk() .map(|(_, schema)| (Some(key.clone()), schema)) .collect::<Vec<_>>() .into_iter() }) .collect::<Vec<_>>() .into_iter() } } impl<'a, K> SchemaWalker<'a> for IndexMap<K, MediaType> { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { self.iter() .flat_map(|(_key, value)| value.walk()) .collect::<Vec<_>>() .into_iter() } } impl<'a, K> SchemaWalker<'a> for IndexMap<K, ReferenceOr<Response>> { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { self.iter() .flat_map(|(_key, value)| value.walk()) .collect::<Vec<_>>() .into_iter() } } impl<'a> SchemaWalker<'a> for PathItem { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { self.iter() .flat_map(|(_, op)| SchemaWalker::walk(op)) .chain(self.parameters.iter().flat_map(SchemaWalker::walk)) .collect::<Vec<_>>() .into_iter() } } impl<'a> SchemaWalker<'a> for Operation { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { self.parameters .iter() .flat_map(SchemaWalker::walk) .chain(self.request_body.walk()) .chain(self.responses.default.walk()) .chain(self.responses.responses.walk()) .collect::<Vec<_>>() .into_iter() } } impl<'a> SchemaWalker<'a> for Components { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { self.responses .walk() .chain( self.parameters .iter() .flat_map(|(_, parameter)| parameter.walk()), ) .chain( self.request_bodies .iter() .flat_map(|(_, request_body)| request_body.walk()), ) .chain(self.schemas.walk()) .collect::<Vec<_>>() .into_iter() } } impl<'a> SchemaWalker<'a> for Response { type SchemaIterator = <IndexMap<String, MediaType> as SchemaWalker<'a>>::SchemaIterator; fn walk(&'a self) -> Self::SchemaIterator { self.content.walk() } } impl<'a> SchemaWalker<'a> for MediaType { type SchemaIterator = <Option<Schema> as SchemaWalker<'a>>::SchemaIterator; fn walk(&'a self) -> Self::SchemaIterator { self.schema.walk() } } impl<'a> SchemaWalker<'a> for Parameter { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { match self { Parameter::Query { parameter_data, .. } => parameter_data, Parameter::Header { parameter_data, .. } => parameter_data, Parameter::Path { parameter_data, .. } => parameter_data, Parameter::Cookie { parameter_data, .. } => parameter_data, } .format .walk() } } impl<'a> SchemaWalker<'a> for ParameterSchemaOrContent { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { match self { ParameterSchemaOrContent::Schema(schema) => { schema.walk().collect::<Vec<_>>().into_iter() } ParameterSchemaOrContent::Content(content) => { content.walk().collect::<Vec<_>>().into_iter() } } } } impl<'a> SchemaWalker<'a> for RequestBody { type SchemaIterator = std::vec::IntoIter<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { self.content.walk() } } impl<'a> SchemaWalker<'a> for Schema { type SchemaIterator = std::iter::Once<(Option<String>, &'a Schema)>; fn walk(&'a self) -> Self::SchemaIterator { std::iter::once((None, self)) } }
fn walk(&'a self) -> Self::SchemaIterator { match self { None => Vec::<(Option<String>, &Schema)>::new().into_iter(), Some(walker) => walker.walk().collect::<Vec<_>>().into_iter(), } }
function_block-full_function
[ { "content": "trait ComponentLookup: Sized {\n\n fn get_components(components: &Components) -> &IndexMap<String, ReferenceOr<Self>>;\n\n}\n\n\n\nimpl<T: ComponentLookup> ReferenceOrExt<T> for openapiv3::ReferenceOr<T> {\n\n fn item<'a>(&'a self, components: &'a Option<Components>) -> Option<&'a T> {\n\n match self {\n\n ReferenceOr::Item(item) => Some(item),\n\n ReferenceOr::Reference { reference } => {\n\n let idx = reference.rfind('/').unwrap();\n\n let key = &reference[idx + 1..];\n\n let parameters = T::get_components(components.as_ref().unwrap());\n\n parameters.get(key).unwrap().item(components)\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl ComponentLookup for Parameter {\n\n fn get_components(components: &Components) -> &IndexMap<String, ReferenceOr<Self>> {\n", "file_path": "src/lib.rs", "rank": 0, "score": 35618.954072413435 }, { "content": "trait ReferenceOrExt<T: ComponentLookup> {\n\n fn item<'a>(&'a self, components: &'a Option<Components>) -> Option<&'a T>;\n\n}\n", "file_path": "src/lib.rs", "rank": 1, "score": 31676.782139688145 }, { "content": "pub fn validate(spec: &OpenAPI) -> Vec<String> {\n\n Validator::default().validate(spec)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 2, "score": 22286.058919276235 }, { "content": "# openapi-lint\n\n\n\nThis is a simple crate to validate OpenAPI v3.0.3 content. It flags constructs\n\nthat we've determined are not \"ergonomic\" or \"well-designed\". In particular we\n\ntry to avoid constructs that lead to structures that SDK generators would have\n\na hard time turning into easy-to-use native constructs.\n\n\n\n## Rules\n\n\n\n### Type mismatch\n\n\n\nA schema that describes a type may include subschemas where one, all, or any of\n\nthe subschemas might match ( for the `oneOf`, `allOf`, and `anyOf` fields\n\nrespectively). For example, the following Rust code produces such a schema with\n\nmixed types:\n\n\n\n```rust\n\n#[derive(JsonSchema)]\n\npub enum E {\n\n ThingA(String),\n\n ThingB,\n\n}\n\n```\n\n\n\nA JSON object that used this `enum` for the type of a field could look like this:\n\n\n\n```json\n\n{\n\n \"field\": { \"ThingA\": \"some value\" }\n\n}\n\n```\n\n\n\nor this:\n\n\n\n```json\n\n{\n\n \"field\": \"ThingB\"\n\n}\n\n```\n\n\n\nSo `field` may be either a string **or** an object. This complicates the\n\ndescription of these types and is harder to represent in SDKs (in particular\n\nthose without Rust's ability for enums to have associated values). To avoid\n\nthis, we can simply use `serde`'s facility for annotating enums. In particular,\n\nwe prefer [\"adjacently\n\ntagged\"](https://serde.rs/container-attrs.html#tag--content) enums:\n\n\n\n```rust\n\n#[derive(JsonSchema)]\n\n#[serde(tag = \"type\", content = \"value\")]\n\npub enum E {\n\n ThingA(String),\n\n ThingB,\n\n}\n\n```\n\n\n\nThis produces JSON like this:\n\n\n\n```json\n\n{\n\n \"field1\": { \"type\": \"ThingA\", \"value\": \"some value\" },\n\n \"field2\": { \"type\": \"ThingB\" }\n\n}\n\n```\n\n\n\n### Naming\n\n\n\nIn general, we use the typical Rust naming conventions.\n\n\n\n- All type names should be PascalCase.\n\n- All `operation_id`s should be snake_case.\n\n- All operation properties should be snake_case\n\n- All struct (and struct enum variant) members should be snake_case.\n\n\n\nType names are already PascalCase by normal Rust conventions. If you need\n\n(really?) to have a type with a non-PascalCase name, you can renamed it like\n", "file_path": "README.md", "rank": 3, "score": 9620.523508944687 }, { "content": "this:\n\n\n\n```rust\n\n#[derive(JsonSchema)]\n\n#[allow(non_camel_case_types)]\n\n#[serde(rename = \"IllumosButUpperCase\")]\n\nstruct illumosIsAlwaysLowerCaseIGuess {\n\n // ...\n\n}\n\n```\n\n\n\nOperation IDs come from the function name. If you obey the normal Rust\n\nconvention, your functions are already snake_case. There isn't currently a\n\nfacility to change the operation name; file an issue in\n", "file_path": "README.md", "rank": 4, "score": 9618.134029731287 }, { "content": " \"problem with type {}: {}\",\n\n name.unwrap_or_else(|| \"<unknown>\".to_string()),\n\n msg\n\n )\n\n })\n\n .into_iter()\n\n .chain(self.validate_object_camel_case(schema))\n\n });\n\n\n\n let operations = spec\n\n .operations()\n\n .filter_map(|path_method_op| self.validate_operation_id(path_method_op));\n\n let parameters = spec\n\n .operations()\n\n .flat_map(|(_, _, op)| self.validate_operation_parameters(spec, op));\n\n let named_schemas = spec.components.iter().flat_map(|components| {\n\n components\n\n .schemas\n\n .keys()\n\n .filter_map(|type_name| self.validate_named_schema(type_name))\n", "file_path": "src/lib.rs", "rank": 7, "score": 9.426650119476218 }, { "content": " &components.parameters\n\n }\n\n}\n\n\n\nimpl ComponentLookup for Schema {\n\n fn get_components(components: &Components) -> &IndexMap<String, ReferenceOr<Self>> {\n\n &components.schemas\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::{validate, Validator};\n\n\n\n #[test]\n\n fn bad_schema() {\n\n let openapi = serde_json::from_str(include_str!(\"tests/errors.json\")).unwrap();\n\n\n\n let actual = validate(&openapi).join(\"\\n\\n\");\n\n expectorate::assert_contents(\"src/tests/errors.out\", &actual);\n", "file_path": "src/lib.rs", "rank": 8, "score": 8.427637153887922 }, { "content": "// Copyright 2022 Oxide Computer Company\n\n\n\n//! This is a simple crate to validate OpenAPI v3.0.3 content. It flags\n\n//! constructs that we've determined are not \"ergonomic\" or \"well-designed\". In\n\n//! particular we try to avoid constructs that lead to structures that SDK\n\n//! generators would have a hard time turning into easy-to-use native\n\n//! constructs.\n\n\n\nuse convert_case::{Boundary, Case, Casing, Converter};\n\nuse indexmap::IndexMap;\n\nuse openapiv3::{Components, OpenAPI, Operation, Parameter, ReferenceOr, Schema, Type};\n\n\n\nmod walker;\n\n\n\nuse walker::SchemaWalker;\n\n\n", "file_path": "src/lib.rs", "rank": 9, "score": 8.370020264088161 }, { "content": "\n\n fn subschemas<'a>(&self, spec: &'a OpenAPI, schema: &'a Schema) -> Vec<&'a Type> {\n\n match &schema.schema_kind {\n\n openapiv3::SchemaKind::OneOf { one_of: ofs }\n\n | openapiv3::SchemaKind::AllOf { all_of: ofs }\n\n | openapiv3::SchemaKind::AnyOf { any_of: ofs } => ofs\n\n .iter()\n\n .flat_map(|subschema| {\n\n self.subschemas(spec, subschema.item(&spec.components).unwrap())\n\n })\n\n .collect(),\n\n openapiv3::SchemaKind::Not { .. } => todo!(),\n\n openapiv3::SchemaKind::Type(t) => vec![t],\n\n openapiv3::SchemaKind::Any(_) => todo!(),\n\n }\n\n }\n\n\n\n fn validate_object_camel_case(&self, schema: &Schema) -> Vec<String> {\n\n let mut ret = Vec::new();\n\n\n", "file_path": "src/lib.rs", "rank": 10, "score": 8.122161490683165 }, { "content": " });\n\n\n\n schema\n\n .chain(operations)\n\n .chain(parameters)\n\n .chain(named_schemas)\n\n .collect()\n\n }\n\n\n\n fn validate_subschemas(&self, spec: &OpenAPI, schema: &Schema) -> Option<String> {\n\n let subschemas = self.subschemas(spec, schema);\n\n let mut iter = subschemas.into_iter();\n\n\n\n const PRE: &str = \"mismatched types between subschemas; this is often \\\n\n due to enums with different data payloads and can be resolved using serde \\\n\n adjacent tagging.\";\n\n const POST: &str = \"For more info, see \\\n\n https://github.com/oxidecomputer/openapi-lint#type-mismatch\";\n\n\n\n if let Some(first) = iter.next() {\n", "file_path": "src/lib.rs", "rank": 13, "score": 7.095590064049411 }, { "content": " }\n\n }\n\n\n\n fn validate_operation_parameters(&self, spec: &OpenAPI, op: &Operation) -> Vec<String> {\n\n const INFO: &str = \"For more info, see \\\n\n https://github.com/oxidecomputer/openapi-lint#naming\";\n\n\n\n let operation_id = op.operation_id.as_deref().unwrap_or(\"<unknown>\");\n\n op.parameters\n\n .iter()\n\n .filter_map(|ref_or_param| {\n\n let param = ref_or_param.item(&spec.components)?;\n\n\n\n let name = &param.parameter_data_ref().name;\n\n let snake = self.snakifier.convert(name);\n\n\n\n if name.as_str() != snake {\n\n Some(format!(\n\n \"The parameter \\\"{}\\\" to {} should be snake_case.\\n{}\",\n\n name, operation_id, INFO,\n", "file_path": "src/lib.rs", "rank": 16, "score": 6.740300860354111 }, { "content": " for ty in iter {\n\n match (first, ty) {\n\n (Type::String(_), Type::String(_))\n\n | (Type::Number(_), Type::Number(_))\n\n | (Type::Integer(_), Type::Integer(_))\n\n | (Type::Object(_), Type::Object(_))\n\n | (Type::Array(_), Type::Array(_))\n\n | (Type::Boolean {}, Type::Boolean {}) => {}\n\n (a, b) => {\n\n return Some(format!(\n\n \"{}\\nthis schema's type\\n{:#?}\\ndiffers from this\\n{:#?}\\n\\n{}\",\n\n PRE, a, b, POST,\n\n ))\n\n }\n\n }\n\n }\n\n }\n\n\n\n None\n\n }\n", "file_path": "src/lib.rs", "rank": 19, "score": 5.749700144417176 }, { "content": " fn validate_operation_id(&self, path_method_op: (&str, &str, &Operation)) -> Option<String> {\n\n let (path, method, op) = path_method_op;\n\n\n\n const INFO: &str = \"For more info, see \\\n\n https://github.com/oxidecomputer/openapi-lint#naming\";\n\n\n\n if let Some(operation_id) = &op.operation_id {\n\n let snake = self.snakifier.convert(operation_id);\n\n if operation_id.as_str() == snake {\n\n return None;\n\n }\n\n Some(format!(\n\n \"The operation for {} {} is named \\\"{}\\\" which is not snake_case\\n{}\",\n\n path, method, operation_id, INFO,\n\n ))\n\n } else {\n\n Some(format!(\n\n \"The operation for {} {} does not have an operation_id\\n{}\",\n\n path, method, INFO,\n\n ))\n", "file_path": "src/lib.rs", "rank": 20, "score": 5.666404386754406 }, { "content": " if let openapiv3::SchemaKind::Type(Type::Object(obj)) = &schema.schema_kind {\n\n for prop_name in obj.properties.keys() {\n\n let snake = self.snakifier.convert(prop_name);\n\n if prop_name.clone() != snake {\n\n ret.push(format!(\n\n \"an object contains a property '{}' which is not \\\n\n snake_case:\\n{:#?}\\n\\\n\n Add #[serde(rename = \\\"{}\\\")] to the member or \\\n\n #[serde(rename_all = \\\"snake_case\\\")] to the struct.\\n\\\n\n For more info see \\\n\n https://github.com/oxidecomputer/openapi-lint#naming\",\n\n prop_name, schema, snake\n\n ))\n\n }\n\n }\n\n }\n\n\n\n ret\n\n }\n\n\n", "file_path": "src/lib.rs", "rank": 23, "score": 5.086125757044144 }, { "content": " ))\n\n } else {\n\n None\n\n }\n\n })\n\n .collect()\n\n }\n\n\n\n fn validate_named_schema(&self, type_name: &str) -> Option<String> {\n\n const INFO: &str = \"For more info, see \\\n\n https://github.com/oxidecomputer/openapi-lint#naming\";\n\n\n\n let pascal = type_name.to_case(Case::Pascal);\n\n if type_name == pascal {\n\n return None;\n\n }\n\n\n\n Some(format!(\n\n \"The type \\\"{}\\\" has a name that is not PascalCase; to rename it add \\\n\n #[serde(rename = \\\"{}\\\")]\\n{}\",\n\n type_name, pascal, INFO,\n\n ))\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 24, "score": 2.042962908448616 } ]
Rust
native-windows-gui/src/controls/notice.rs
gyk/native-windows-gui
163d0fcb5c2af8a859f603ce23a7ec218e9b6813
use super::control_handle::ControlHandle; use crate::win32::{window::build_notice, window_helper as wh}; use crate::NwgError; const NOT_BOUND: &str = "Notice is not yet bound to a winapi object"; const UNUSABLE_NOTICE: &str = "Notice parent window was freed"; const BAD_HANDLE: &str = "INTERNAL ERROR: Notice handle is not Notice!"; /** An invisible component that can be triggered by other thread. A notice object does not send data between threads. Rust has already plenty of way to do this. The notice object only serve to "wake up" the GUI thread. A notice must have a parent window. If the parent is destroyed before the notice, the notice becomes invalid. Requires the `notice` feature. ## Example ```rust use native_windows_gui as nwg; fn build_notice(notice: &mut nwg::Notice, window: &nwg::Window) { nwg::Notice::builder() .parent(window) .build(notice); } ``` ```rust use native_windows_gui as nwg; use std::thread; use std::time; fn notice(noticer: &nwg::Notice) { let sender = noticer.sender(); thread::spawn(move || { thread::sleep(time::Duration::new(5, 0)); sender.notice(); }); } ``` */ #[derive(Default, PartialEq, Eq)] pub struct Notice { pub handle: ControlHandle, } impl Notice { pub fn builder() -> NoticeBuilder { NoticeBuilder { parent: None } } pub fn create<C: Into<ControlHandle>>(parent: C) -> Result<Notice, NwgError> { let mut notice = Self::default(); Self::builder().parent(parent).build(&mut notice)?; Ok(notice) } pub fn valid(&self) -> bool { if self.handle.blank() { return false; } let (hwnd, _) = self.handle.notice().expect(BAD_HANDLE); wh::window_valid(hwnd) } pub fn window_handle(&self) -> Option<ControlHandle> { match self.valid() { true => Some(ControlHandle::Hwnd(self.handle.notice().unwrap().0)), false => None, } } pub fn set_window_handle<C: Into<ControlHandle>>(&mut self, window: C) { if self.handle.blank() { panic!("{}", NOT_BOUND); } let hwnd = window .into() .hwnd() .expect("New notice parent is not a window control"); let (_, id) = self.handle.notice().expect(BAD_HANDLE); self.handle = ControlHandle::Notice(hwnd, id); } pub fn sender(&self) -> NoticeSender { if self.handle.blank() { panic!("{}", NOT_BOUND); } if !self.valid() { panic!("{}", UNUSABLE_NOTICE); } let (hwnd, id) = self.handle.notice().expect(BAD_HANDLE); NoticeSender { hwnd: hwnd as usize, id, } } } impl Drop for Notice { fn drop(&mut self) { self.handle.destroy(); } } #[derive(Clone, Copy)] pub struct NoticeSender { hwnd: usize, id: u32, } impl NoticeSender { pub fn notice(&self) { use winapi::shared::minwindef::{LPARAM, WPARAM}; use winapi::shared::windef::HWND; use winapi::um::winuser::SendNotifyMessageW; unsafe { SendNotifyMessageW( self.hwnd as HWND, wh::NOTICE_MESSAGE, self.id as WPARAM, self.hwnd as LPARAM, ); } } } pub struct NoticeBuilder { parent: Option<ControlHandle>, } impl NoticeBuilder { pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> NoticeBuilder { self.parent = Some(p.into()); self } pub fn build(self, out: &mut Notice) -> Result<(), NwgError> { let parent = match self.parent { Some(p) => match p.hwnd() { Some(handle) => Ok(handle), None => Err(NwgError::control_create("Wrong parent type")), }, None => Err(NwgError::no_parent("Notice")), }?; out.handle = build_notice(parent); Ok(()) } }
use super::control_handle::ControlHandle; use crate::win32::{window::build_notice, window_helper as wh}; use crate::NwgError; const NOT_BOUND: &str = "Notice is not yet bound to a winapi object"; const UNUSABLE_NOTICE: &str = "Notice parent window was freed"; const BAD_HANDLE: &str = "INTERNAL ERROR: Notice handle is not Notice!"; /** An invisible component that can be triggered by other thread. A notice object does not send data between threads. Rust has already plenty of way to do this. The notice object only serve to "wake up" the GUI thread. A notice must have a parent window. If the parent is destroyed before the notice, the notice becomes invalid. Requires the `notice` feature. ## Example ```rust use native_windows_gui as nwg; fn build_notice(notice: &mut nwg::Notice, window: &nwg::Window) { nwg::Notice::builder() .parent(window) .build(notice); } ``` ```rust use native_windows_gui as nwg; use std::thread; use std::time; fn notice(noticer: &nwg::Notice) { let sender = noticer.sender(); thread::spawn(move || { thread::sleep(time::Duration::new(5, 0)); sender.notice(); }); } ``` */ #[derive(Default, PartialEq, Eq)] pub struct Notice { pub handle: ControlHandle, } impl Notice { pub fn builder() -> NoticeBuilder { NoticeBuilder { parent: None } } pub fn create<C: Into<ControlHandle>>(parent: C) -> Result<Notice, NwgError> { let mut notice = Self::default(); Self::builder().parent(parent).build(&mut notice)?; Ok(notice) } pub fn valid(&self) -> bool { if self.handle.blank() { return false; } let (hwnd, _) = self.handle.notice().expect(BAD_HANDLE); wh::window_valid(hwnd) } pub fn window_handle(&self) -> Option<ControlHandle> { match self.valid() { true => Some(ControlHandle::Hwnd(self.handle.notice().unwrap().0)), false => None, } } pub fn set_window_handle<C: Into<ControlHandle>>(&mut self, window: C) { if self.handle.blank() { panic!("{}", NOT_BOUND); } let hwnd = window .into() .hwnd() .expect("New notice parent is not a window control"); let (_, id) = self.handle.notice().expect(BAD_HANDLE); self.handle = ControlHandle::Notice(hwnd, id); } pub fn sender(&self) -> NoticeSender { if self.handle.blank() { panic!("{}", NOT_BOUND); } if !self.valid() { panic!("{}", UNUSABLE_NOTICE); } let (hwnd, id) = self.handle.notice().expect(BAD_HANDLE); NoticeSender { hwnd: hwnd as usize, id, } } } impl Drop for Notice { fn drop(&mut self) { self.handle.destroy(); } } #[derive(Clone, Copy)] pub struct NoticeSender { hwnd: usize, id: u32, } impl NoticeSender { pub fn notice(&self) { use winapi::shared::minwindef::{LPARAM, WPARAM}; use winapi::shared::windef::HWND; use winapi::um::winuser::SendNotifyMessageW; unsafe { SendNotifyMessageW( self.hwnd as HWND, wh::NOTICE_MESSAGE, self.id as WPARAM, self.hwnd as LPARAM, ); } } } pub struct NoticeBuilder { parent: Option<ControlHandle>, } impl NoticeBuilder { pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> NoticeBuilder { self.parent = Some(p.into()); self }
}
pub fn build(self, out: &mut Notice) -> Result<(), NwgError> { let parent = match self.parent { Some(p) => match p.hwnd() { Some(handle) => Ok(handle), None => Err(NwgError::control_create("Wrong parent type")), }, None => Err(NwgError::no_parent("Notice")), }?; out.handle = build_notice(parent); Ok(()) }
function_block-full_function
[ { "content": "pub fn check_hwnd(handle: &ControlHandle, not_bound: &str, bad_handle: &str) -> HWND {\n\n use winapi::um::winuser::IsWindow;\n\n\n\n if handle.blank() {\n\n panic!(\"{}\", not_bound);\n\n }\n\n match handle.hwnd() {\n\n Some(hwnd) => match unsafe { IsWindow(hwnd) } {\n\n 0 => {\n\n panic!(\"The window handle is no longer valid. This usually means the control was freed by the OS\");\n\n }\n\n _ => hwnd,\n\n },\n\n None => {\n\n panic!(\"{}\", bad_handle);\n\n }\n\n }\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/base_helper.rs", "rank": 0, "score": 425792.8063651537 }, { "content": "pub fn build_notice(parent: HWND) -> ControlHandle {\n\n let id = NOTICE_ID.fetch_add(1, Ordering::SeqCst);\n\n ControlHandle::Notice(parent, id)\n\n}\n\n\n\npub unsafe fn build_timer(parent: HWND, interval: u32, stopped: bool) -> ControlHandle {\n\n use winapi::um::winuser::SetTimer;\n\n\n\n let id = TIMER_ID.fetch_add(1, Ordering::SeqCst);\n\n\n\n if !stopped {\n\n SetTimer(parent, id as UINT_PTR, interval as UINT, None);\n\n }\n\n\n\n ControlHandle::Timer(parent, id)\n\n}\n\n\n\n/**\n\n Hook the window subclass with the default event dispatcher.\n\n The hook is applied to the window and all it's children (recursively).\n\n\n\n Returns a `EventHandler` that can be passed to `unbind_event_handler` to remove the callbacks.\n\n\n\n This function will panic if `handle` is not a window handle.\n\n*/\n", "file_path": "native-windows-gui/src/win32/window.rs", "rank": 1, "score": 407816.1004294588 }, { "content": "#[cfg(feature = \"timer\")]\n\npub fn start_timer(hwnd: HWND, id: u32, interval: u32) {\n\n use winapi::shared::basetsd::UINT_PTR;\n\n use winapi::um::winuser::SetTimer;\n\n\n\n unsafe {\n\n SetTimer(hwnd, id as UINT_PTR, interval, None);\n\n }\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 2, "score": 364809.42708012677 }, { "content": "#[cfg(feature = \"timer\")]\n\npub fn kill_timer(hwnd: HWND, id: u32) {\n\n use winapi::shared::basetsd::UINT_PTR;\n\n use winapi::um::winuser::KillTimer;\n\n\n\n unsafe {\n\n KillTimer(hwnd, id as UINT_PTR);\n\n }\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 3, "score": 364542.670746353 }, { "content": "pub fn send_message(hwnd: HWND, msg: UINT, w: WPARAM, l: LPARAM) -> LRESULT {\n\n unsafe { ::winapi::um::winuser::SendMessageW(hwnd, msg, w, l) }\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 4, "score": 359658.0169545327 }, { "content": "pub fn destroy_menu_item(parent: HMENU, item_id: u32) {\n\n use winapi::um::winuser::{DeleteMenu, GetMenuItemCount, GetMenuItemID, MF_BYPOSITION};\n\n\n\n unsafe {\n\n let count = GetMenuItemCount(parent);\n\n let mut index = 0;\n\n\n\n while index < count {\n\n let id = GetMenuItemID(parent, index);\n\n match id == item_id {\n\n true => {\n\n DeleteMenu(parent, index as u32, MF_BYPOSITION);\n\n index = count;\n\n }\n\n false => {\n\n index += 1;\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 6, "score": 347390.88014093885 }, { "content": "/// Build two group of checkboxes on the same parent with the GROUP flags\n\nfn build_radio_groups(radios: &mut [nwg::RadioButton], parent: &nwg::Window) {\n\n use nwg::RadioButtonFlags as RadioF;\n\n\n\n // Group 1\n\n nwg::RadioButton::builder()\n\n .flags(RadioF::VISIBLE | RadioF::GROUP)\n\n .parent(parent)\n\n .build(&mut radios[0]);\n\n\n\n nwg::RadioButton::builder()\n\n .parent(parent)\n\n .build(&mut radios[1]);\n\n\n\n // Group 2\n\n nwg::RadioButton::builder()\n\n .flags(RadioF::VISIBLE | RadioF::GROUP)\n\n .parent(parent)\n\n .build(&mut radios[2]);\n\n\n\n nwg::RadioButton::builder()\n\n .parent(parent)\n\n .build(&mut radios[3]);\n\n}\n\n\n\n\n\n```\n\n\n\n```rust\n\nuse native_windows_gui as nwg;\n", "file_path": "native-windows-gui/src/controls/radio_button.rs", "rank": 7, "score": 331302.2963296169 }, { "content": "pub fn post_message(hwnd: HWND, msg: UINT, w: WPARAM, l: LPARAM) {\n\n unsafe { ::winapi::um::winuser::PostMessageW(hwnd, msg, w, l) };\n\n}\n\n\n\npub unsafe fn set_focus(handle: HWND) {\n\n ::winapi::um::winuser::SetFocus(handle);\n\n}\n\n\n\npub unsafe fn get_focus(handle: HWND) -> bool {\n\n ::winapi::um::winuser::GetFocus() == handle\n\n}\n\n\n\npub unsafe fn get_window_text(handle: HWND) -> String {\n\n use winapi::um::winuser::{GetWindowTextLengthW, GetWindowTextW};\n\n\n\n let buffer_size = GetWindowTextLengthW(handle) as usize + 1;\n\n if buffer_size == 0 {\n\n return String::new();\n\n }\n\n\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 8, "score": 330942.0133975375 }, { "content": "pub fn modal_error_message<'a, P: Into<ControlHandle>>(\n\n parent: P,\n\n title: &'a str,\n\n content: &'a str,\n\n) -> MessageChoice {\n\n let params = MessageParams {\n\n title,\n\n content,\n\n buttons: MessageButtons::Ok,\n\n icons: MessageIcons::Error,\n\n };\n\n\n\n modal_message(parent, &params)\n\n}\n\n\n\n/**\n\n Display a simple message box. The message box has for style `MessageButtons::Ok` and `MessageIcons::Info`.\n\n It is recommended to use `modal_info_message` because it locks the window that creates the message box.\n\n This method may be deprecated in the future\n\n\n\n Parameters:\n\n * title: The message box title\n\n * content: The message box message\n\n*/\n", "file_path": "native-windows-gui/src/win32/message_box.rs", "rank": 9, "score": 330129.86239140213 }, { "content": "fn build_combobox(combo: &mut nwg::ComboBox<&'static str>, window: &nwg::Window) {\n\n let data = vec![\"one\", \"two\"];\n\n\n\n nwg::ComboBox::builder()\n\n .size((200, 300))\n\n .collection(data)\n\n .selected_index(Some(0))\n\n .parent(window)\n\n .build(combo);\n\n}\n\n```\n\n*/\n\n#[derive(Default)]\n\npub struct ComboBox<D: Display + Default> {\n\n pub handle: ControlHandle,\n\n collection: RefCell<Vec<D>>,\n\n handler0: RefCell<Option<RawEventHandler>>,\n\n}\n\n\n\nimpl<D: Display + Default> ComboBox<D> {\n", "file_path": "native-windows-gui/src/controls/combo_box.rs", "rank": 10, "score": 326640.941004106 }, { "content": "pub fn has_raw_handler(handle: &ControlHandle, handler_id: UINT_PTR) -> bool {\n\n let handle = handle\n\n .hwnd()\n\n .expect(\"This type of control cannot have a raw handler.\");\n\n let subclass_proc: SUBCLASSPROC = Some(process_raw_events);\n\n let mut tmp_value = 0;\n\n unsafe { GetWindowSubclass(handle, subclass_proc, handler_id, &mut tmp_value) != 0 }\n\n}\n\n\n\n/**\n\n Remove the raw event handler from the associated window.\n\n Calling unbind twice or trying to unbind an handler after destroying its parent will cause the function to panic.\n\n*/\n", "file_path": "native-windows-gui/src/win32/window.rs", "rank": 11, "score": 324714.097019256 }, { "content": "#[cfg(any(feature = \"list-view\", feature = \"progress-bar\"))]\n\npub fn set_style(handle: HWND, style: u32) {\n\n use ::winapi::um::winuser::GWL_STYLE;\n\n set_window_long(handle, GWL_STYLE, style as usize);\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 12, "score": 317646.2883633448 }, { "content": "fn build_listbox(listb: &mut nwg::ListBox<&'static str>, window: &nwg::Window, font: &nwg::Font) {\n\n nwg::ListBox::builder()\n\n .flags(nwg::ListBoxFlags::VISIBLE | nwg::ListBoxFlags::MULTI_SELECT)\n\n .collection(vec![\"Hello\", \"World\", \"!!!!\"])\n\n .multi_selection(vec![0, 1, 2])\n\n .font(Some(font))\n\n .parent(window)\n\n .build(listb);\n\n}\n\n```\n\n\n\n*/\n\n#[derive(Default)]\n\npub struct ListBox<D: Display + Default> {\n\n pub handle: ControlHandle,\n\n collection: RefCell<Vec<D>>,\n\n}\n\n\n\nimpl<D: Display + Default> ListBox<D> {\n\n pub fn builder<'a>() -> ListBoxBuilder<'a, D> {\n", "file_path": "native-windows-gui/src/controls/list_box.rs", "rank": 13, "score": 315448.9148122943 }, { "content": "fn basic_stuff(window: &nwg::Window) -> Result<(), nwg::NwgError> {\n\n nwg::ControlBase::build_hwnd()\n\n .class_name(\"BUTTON\")\n\n .forced_flags(0)\n\n .flags(0)\n\n .size((100, 100))\n\n .position((100, 100))\n\n .text(\"HELLO\")\n\n .parent(Some(window.handle))\n\n .build()?;\n\n\n\n #[cfg(feature = \"menu\")]\n\n nwg::ControlBase::build_hmenu()\n\n .text(\"Item\")\n\n .item(true)\n\n .parent(window.handle)\n\n .build()?;\n\n\n\n Ok(())\n\n}\n", "file_path": "native-windows-gui/src/controls/control_base.rs", "rank": 14, "score": 314398.61692491896 }, { "content": "#[cfg(any(feature = \"timer\", feature = \"animation-timer\", feature = \"notice\"))]\n\npub fn window_valid(hwnd: HWND) -> bool {\n\n use winapi::um::winuser::IsWindow;\n\n\n\n unsafe { IsWindow(hwnd) != 0 }\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 15, "score": 311848.95490275073 }, { "content": "pub fn init_common_controls() -> Result<(), NwgError> {\n\n use winapi::shared::winerror::{S_FALSE, S_OK};\n\n use winapi::um::commctrl::{InitCommonControlsEx, INITCOMMONCONTROLSEX};\n\n use winapi::um::commctrl::{\n\n ICC_BAR_CLASSES, ICC_DATE_CLASSES, ICC_LISTVIEW_CLASSES, ICC_PROGRESS_CLASS,\n\n ICC_STANDARD_CLASSES, ICC_TAB_CLASSES, ICC_TREEVIEW_CLASSES,\n\n };\n\n use winapi::um::libloaderapi::LoadLibraryW;\n\n use winapi::um::objbase::CoInitialize;\n\n\n\n unsafe {\n\n let mut classes = ICC_BAR_CLASSES | ICC_STANDARD_CLASSES;\n\n\n\n if cfg!(feature = \"datetime-picker\") {\n\n classes |= ICC_DATE_CLASSES;\n\n }\n\n\n\n if cfg!(feature = \"progress-bar\") {\n\n classes |= ICC_PROGRESS_CLASS;\n\n }\n", "file_path": "native-windows-gui/src/win32/mod.rs", "rank": 16, "score": 305404.44116310985 }, { "content": "fn build_timer(parent: &nwg::Window) {\n\n let mut timer = Default::default();\n\n nwg::Timer::builder()\n\n .parent(parent)\n\n .interval(100)\n\n .stopped(false)\n\n .build(&mut timer);\n\n}\n\n```\n\n*/\n\n#[deprecated(\n\n since = \"1.0.11\",\n\n note = \"Use AnimationTimer instead. The winapi timer does not have a constant tick and will call your single threaded from another thread.\"\n\n)]\n\n#[derive(Default)]\n\npub struct Timer {\n\n pub handle: ControlHandle,\n\n interval: RefCell<u32>,\n\n}\n\n\n", "file_path": "native-windows-gui/src/controls/timer.rs", "rank": 17, "score": 301945.42417021544 }, { "content": "/// Builds a timer that will animation something at 60fps for 3 sec\n\nfn build_timer(parent: &nwg::Window) {\n\n let mut timer = Default::default();\n\n nwg::AnimationTimer::builder()\n\n .parent(parent)\n\n .interval(Duration::from_millis(1000/60))\n\n .lifetime(Some(Duration::from_millis(3000)))\n\n .build(&mut timer);\n\n}\n\n```\n\n*/\n\n#[derive(Default, PartialEq, Eq)]\n\npub struct AnimationTimer {\n\n pub handle: ControlHandle,\n\n}\n\n\n\nimpl AnimationTimer {\n\n pub fn builder() -> AnimationTimerBuilder {\n\n AnimationTimerBuilder {\n\n parent: None,\n\n interval: Duration::from_millis(1000 / 60),\n", "file_path": "native-windows-gui/src/controls/animation_timer.rs", "rank": 18, "score": 297765.75520377525 }, { "content": "/// Haha you maybe though that destroying windows would be easy right? WRONG.\n\n/// The window children must first be destroyed otherwise `DestroyWindow` will free them and the associated rust value will be ~CORRUPTED~\n\npub fn destroy_window(hwnd: HWND) {\n\n use winapi::um::winuser::{DestroyWindow, SetParent};\n\n\n\n // Remove the children from the window\n\n iterate_window_children(hwnd, |child| unsafe {\n\n set_window_visibility(child, false);\n\n SetParent(child, ptr::null_mut());\n\n });\n\n\n\n unsafe {\n\n DestroyWindow(hwnd);\n\n }\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 19, "score": 295672.14123838255 }, { "content": "pub fn modal_message<'a, P: Into<ControlHandle>>(\n\n parent: P,\n\n params: &MessageParams,\n\n) -> MessageChoice {\n\n let control_handle = parent.into();\n\n let hwnd = control_handle.hwnd().expect(\"expected window like control\");\n\n inner_message(hwnd, params)\n\n}\n\n\n\n/**\n\n Display a message box and then panic. The message box has for style `MessageButtons::Ok` and `MessageIcons::Error` .\n\n It is recommended to use `modal_fatal_message` because it locks the window that creates the message box.\n\n This method may be deprecated in the future\n\n\n\n Parameters:\n\n * title: The message box title\n\n * content: The message box message\n\n*/\n", "file_path": "native-windows-gui/src/win32/message_box.rs", "rank": 20, "score": 294954.52045271784 }, { "content": "pub fn get_window_parent(hwnd: HWND) -> HWND {\n\n use winapi::um::winuser::GetParent;\n\n unsafe { GetParent(hwnd) }\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 21, "score": 294061.74235722877 }, { "content": "pub fn modal_fatal_message<'a, P: Into<ControlHandle>>(\n\n parent: P,\n\n title: &'a str,\n\n content: &'a str,\n\n) -> ! {\n\n modal_error_message(parent, title, content);\n\n panic!(\"{} - {}\", title, content);\n\n}\n\n\n\n/**\n\n Display a simple error message box. The message box has for style `MessageButtons::Ok` and `MessageIcons::Error`.\n\n It is recommended to use `modal_error_message` because it locks the window that creates the message box.\n\n This method may be deprecated in the future\n\n\n\n Parameters:\n\n * title: The message box title\n\n * content: The message box message\n\n*/\n", "file_path": "native-windows-gui/src/win32/message_box.rs", "rank": 22, "score": 290267.28053937166 }, { "content": "pub fn modal_info_message<'a, P: Into<ControlHandle>>(\n\n parent: P,\n\n title: &'a str,\n\n content: &'a str,\n\n) -> MessageChoice {\n\n let params = MessageParams {\n\n title,\n\n content,\n\n buttons: MessageButtons::Ok,\n\n icons: MessageIcons::Info,\n\n };\n\n\n\n modal_message(parent, &params)\n\n}\n", "file_path": "native-windows-gui/src/win32/message_box.rs", "rank": 23, "score": 290267.28053937166 }, { "content": "fn print_char(data: &nwg::EventData) {\n\n println!(\"{:?}\", data.on_char());\n\n}\n\n\n", "file_path": "native-windows-gui/examples/partials_d.rs", "rank": 24, "score": 287202.4364616673 }, { "content": "fn build_dtp(date: &mut nwg::DatePicker, window: &nwg::Window) {\n\n let v = nwg::DatePickerValue { year: 2000, month: 10, day: 5 };\n\n let v1 = nwg::DatePickerValue { year: 2000, month: 10, day: 5 };\n\n let v2 = nwg::DatePickerValue { year: 2012, month: 10, day: 5 };\n\n\n\n nwg::DatePicker::builder()\n\n .size((200, 300))\n\n .position((0, 0))\n\n .date(Some(v))\n\n .format(Some(\"'YEAR: 'yyyy\"))\n\n .range(Some([v1, v2]))\n\n .parent(window)\n\n .build(date);\n\n}\n\n```\n\n*/\n\n#[derive(Default, PartialEq, Eq)]\n\npub struct DatePicker {\n\n pub handle: ControlHandle,\n\n}\n", "file_path": "native-windows-gui/src/controls/date_picker.rs", "rank": 25, "score": 287164.91250748653 }, { "content": "fn build_trackbar(track: &mut nwg::TrackBar, window: &nwg::Window) {\n\n nwg::TrackBar::builder()\n\n .range(Some(0..100))\n\n .pos(Some(10))\n\n .parent(window)\n\n .build(track);\n\n}\n\n```\n\n\n\n*/\n\n#[derive(Default)]\n\npub struct TrackBar {\n\n pub handle: ControlHandle,\n\n background_brush: Option<HBRUSH>,\n\n handler0: RefCell<Option<RawEventHandler>>,\n\n}\n\n\n\nimpl TrackBar {\n\n pub fn builder() -> TrackBarBuilder {\n\n TrackBarBuilder {\n", "file_path": "native-windows-gui/src/controls/track_bar.rs", "rank": 26, "score": 287164.91250748653 }, { "content": "fn build_scrollbar(button: &mut nwg::ScrollBar, window: &nwg::Window) {\n\n nwg::ScrollBar::builder()\n\n .range(Some(0..100))\n\n .pos(Some(10))\n\n .parent(window)\n\n .build(button);\n\n}\n\n```\n\n*/\n\n#[derive(Default)]\n\npub struct ScrollBar {\n\n pub handle: ControlHandle,\n\n handler0: RefCell<Option<RawEventHandler>>,\n\n handler1: RefCell<Option<RawEventHandler>>,\n\n}\n\n\n\nimpl ScrollBar {\n\n pub fn builder<'a>() -> ScrollBarBuilder {\n\n ScrollBarBuilder {\n\n size: (25, 100),\n", "file_path": "native-windows-gui/src/controls/scroll_bar.rs", "rank": 27, "score": 287164.9125074865 }, { "content": "fn build_progress_bar(bar: &mut nwg::ProgressBar, window: &nwg::Window) {\n\n nwg::ProgressBar::builder()\n\n .state(nwg::ProgressBarState::Paused)\n\n .step(10)\n\n .range(0..100)\n\n .parent(window)\n\n .build(bar);\n\n}\n\n```\n\n\n\n*/\n\n#[derive(Default, PartialEq, Eq)]\n\npub struct ProgressBar {\n\n pub handle: ControlHandle,\n\n}\n\n\n\nimpl ProgressBar {\n\n pub fn builder() -> ProgressBarBuilder {\n\n ProgressBarBuilder {\n\n size: (100, 40),\n", "file_path": "native-windows-gui/src/controls/progress_bar.rs", "rank": 28, "score": 283959.94054601033 }, { "content": "fn build_button(button: &mut nwg::Button, window: &nwg::Window, font: &nwg::Font) {\n\n nwg::Button::builder()\n\n .text(\"Hello\")\n\n .flags(nwg::ButtonFlags::VISIBLE)\n\n .font(Some(font))\n\n .parent(window)\n\n .build(button);\n\n}\n\n```\n\n\n\n*/\n\n#[derive(Default, Eq, PartialEq)]\n\npub struct Button {\n\n pub handle: ControlHandle,\n\n}\n\n\n\nimpl Button {\n\n pub fn builder<'a>() -> ButtonBuilder<'a> {\n\n ButtonBuilder {\n\n text: \"Button\",\n", "file_path": "native-windows-gui/src/controls/button.rs", "rank": 29, "score": 283457.0803326102 }, { "content": "fn build_label(label: &mut nwg::Label, window: &nwg::Window, font: &nwg::Font) {\n\n nwg::Label::builder()\n\n .text(\"Hello\")\n\n .font(Some(font))\n\n .parent(window)\n\n .build(label);\n\n}\n\n```\n\n\n\n*/\n\n#[derive(Default)]\n\npub struct Label {\n\n pub handle: ControlHandle,\n\n background_brush: Option<HBRUSH>,\n\n handler0: RefCell<Option<RawEventHandler>>,\n\n handler1: RefCell<Option<RawEventHandler>>,\n\n}\n\n\n\nimpl Label {\n\n pub fn builder<'a>() -> LabelBuilder<'a> {\n", "file_path": "native-windows-gui/src/controls/label.rs", "rank": 30, "score": 283457.0803326102 }, { "content": "fn print_char(data: &nwg::EventData) {\n\n println!(\"{:?}\", data.on_char());\n\n}\n\n\n", "file_path": "native-windows-gui/examples/dyn_layout_d.rs", "rank": 31, "score": 283124.6460254824 }, { "content": "fn build_frame(button: &mut nwg::ImageFrame, window: &nwg::Window, ico: &nwg::Icon) {\n\n nwg::ImageFrame::builder()\n\n .parent(window)\n\n .build(button);\n\n}\n\n```\n\n*/\n\n#[derive(Default)]\n\npub struct ImageFrame {\n\n pub handle: ControlHandle,\n\n background_brush: Option<HBRUSH>,\n\n handler0: RefCell<Option<RawEventHandler>>,\n\n}\n\n\n\nimpl ImageFrame {\n\n pub fn builder<'a>() -> ImageFrameBuilder<'a> {\n\n ImageFrameBuilder {\n\n size: (100, 100),\n\n position: (0, 0),\n\n flags: None,\n", "file_path": "native-windows-gui/src/controls/image_frame.rs", "rank": 32, "score": 277545.9951814688 }, { "content": "fn build_checkbox(button: &mut nwg::CheckBox, window: &nwg::Window, font: &nwg::Font) {\n\n nwg::CheckBox::builder()\n\n .text(\"Hello\")\n\n .flags(nwg::CheckBoxFlags::VISIBLE)\n\n .font(Some(font))\n\n .parent(window)\n\n .build(button);\n\n}\n\n```\n\n*/\n\n#[derive(Default)]\n\npub struct CheckBox {\n\n pub handle: ControlHandle,\n\n background_brush: Option<HBRUSH>,\n\n handler0: RefCell<Option<RawEventHandler>>,\n\n}\n\n\n\nimpl CheckBox {\n\n pub fn builder<'a>() -> CheckBoxBuilder<'a> {\n\n CheckBoxBuilder {\n", "file_path": "native-windows-gui/src/controls/check_box.rs", "rank": 33, "score": 277545.9951814688 }, { "content": "fn build_label(label: &mut nwg::RichLabel, window: &nwg::Window, font: &nwg::Font) {\n\n nwg::RichLabel::builder()\n\n .text(\"Hello\")\n\n .font(Some(font))\n\n .parent(window)\n\n .build(label);\n\n}\n\n\n\n*/\n\n#[derive(Default)]\n\npub struct RichLabel {\n\n pub handle: ControlHandle,\n\n line_height: Rc<RefCell<Option<i32>>>,\n\n handler0: RefCell<Option<RawEventHandler>>,\n\n}\n\n\n\nimpl RichLabel {\n\n pub fn builder<'a>() -> RichLabelBuilder<'a> {\n\n RichLabelBuilder {\n\n text: \"A rich label\",\n", "file_path": "native-windows-gui/src/controls/rich_label.rs", "rank": 34, "score": 277545.9951814688 }, { "content": "fn build_status(status: &mut nwg::StatusBar, window: &nwg::Window, font: &nwg::Font) {\n\n nwg::StatusBar::builder()\n\n .text(\"Hello\")\n\n .font(Some(font))\n\n .parent(window)\n\n .build(status);\n\n}\n\n```\n\n\n\n*/\n\n#[derive(Default)]\n\npub struct StatusBar {\n\n pub handle: ControlHandle,\n\n handler0: RefCell<Option<RawEventHandler>>,\n\n}\n\n\n\nimpl StatusBar {\n\n pub fn builder<'a>() -> StatusBarBuilder<'a> {\n\n StatusBarBuilder {\n\n text: \"\",\n", "file_path": "native-windows-gui/src/controls/status_bar.rs", "rank": 35, "score": 277545.9951814688 }, { "content": "fn build_box(tbox: &mut nwg::TextInput, window: &nwg::Window, font: &nwg::Font) {\n\n nwg::TextInput::builder()\n\n .text(\"Hello\")\n\n .font(Some(font))\n\n .parent(window)\n\n .build(tbox);\n\n}\n\n```\n\n*/\n\n#[derive(Default)]\n\npub struct TextInput {\n\n pub handle: ControlHandle,\n\n background_brush: Option<HBRUSH>,\n\n handler0: RefCell<Option<RawEventHandler>>,\n\n}\n\n\n\nimpl TextInput {\n\n pub fn builder<'a>() -> TextInputBuilder<'a> {\n\n TextInputBuilder {\n\n text: \"\",\n", "file_path": "native-windows-gui/src/controls/text_input.rs", "rank": 36, "score": 277545.9951814688 }, { "content": "fn build_box(tbox: &mut nwg::TextBox, window: &nwg::Window, font: &nwg::Font) {\n\n nwg::TextBox::builder()\n\n .text(\"Hello\")\n\n .font(Some(font))\n\n .parent(window)\n\n .build(tbox);\n\n}\n\n```\n\n*/\n\n#[derive(Default, PartialEq, Eq)]\n\npub struct TextBox {\n\n pub handle: ControlHandle,\n\n}\n\n\n\nimpl TextBox {\n\n pub fn builder<'a>() -> TextBoxBuilder<'a> {\n\n TextBoxBuilder {\n\n text: \"\",\n\n size: (100, 25),\n\n position: (0, 0),\n", "file_path": "native-windows-gui/src/controls/text_box.rs", "rank": 37, "score": 277545.9951814688 }, { "content": "fn build_radio(radio: &mut nwg::RadioButton, window: &nwg::Window, font: &nwg::Font) {\n\n nwg::RadioButton::builder()\n\n .text(\"Hello\")\n\n .flags(nwg::RadioButtonFlags::VISIBLE)\n\n .font(Some(font))\n\n .parent(window)\n\n .build(radio);\n\n}\n\n```\n\n\n\n*/\n\n#[derive(Default)]\n\npub struct RadioButton {\n\n pub handle: ControlHandle,\n\n background_brush: Option<HBRUSH>,\n\n handler0: RefCell<Option<RawEventHandler>>,\n\n}\n\n\n\nimpl RadioButton {\n\n pub fn builder<'a>() -> RadioButtonBuilder<'a> {\n", "file_path": "native-windows-gui/src/controls/radio_button.rs", "rank": 38, "score": 277545.9951814688 }, { "content": "#[inline(always)]\n\n#[cfg(target_pointer_width = \"32\")]\n\npub fn set_window_long(handle: HWND, index: c_int, v: usize) {\n\n unsafe {\n\n ::winapi::um::winuser::SetWindowLongW(handle, index, v as LONG);\n\n }\n\n}\n\n\n\n// Helper to wrap DeferWindowPos somewhat safely\n\n// Mostly to streamline the usage of the returned HWDP from DeferWindowPos\n\npub struct DeferredWindowPositioner {\n\n handle: winapi::um::winuser::HDWP,\n\n}\n\n\n\nimpl DeferredWindowPositioner {\n\n const MEM_FAIL: &'static str = \"Insufficient system resources\";\n\n\n\n /// Initialises a new DeferredWindowPositioner with memory for `item_count` windows\n\n pub fn new(item_count: i32) -> Result<DeferredWindowPositioner, &'static str> {\n\n use ::winapi::um::winuser::BeginDeferWindowPos;\n\n\n\n let handle = unsafe { BeginDeferWindowPos(item_count) };\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 39, "score": 277511.6840719576 }, { "content": "pub fn minimize_window(handle: HWND) {\n\n use winapi::um::winuser::{ShowWindow, SW_MINIMIZE};\n\n unsafe {\n\n ShowWindow(handle, SW_MINIMIZE);\n\n }\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 40, "score": 273044.11719047313 }, { "content": "pub fn restore_window(handle: HWND) {\n\n use winapi::um::winuser::{ShowWindow, SW_RESTORE};\n\n unsafe {\n\n ShowWindow(handle, SW_RESTORE);\n\n }\n\n}\n\n\n\n/// Set the font of a window\n\npub unsafe fn set_window_font(handle: HWND, font_handle: Option<HFONT>, redraw: bool) {\n\n use winapi::um::winuser::SendMessageW;\n\n use winapi::um::winuser::WM_SETFONT;\n\n\n\n let font_handle = font_handle.unwrap_or(ptr::null_mut());\n\n\n\n SendMessageW(handle, WM_SETFONT, font_handle as usize, redraw as LPARAM);\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 41, "score": 273044.11719047313 }, { "content": "pub fn maximize_window(handle: HWND) {\n\n use winapi::um::winuser::{ShowWindow, SW_MAXIMIZE};\n\n unsafe {\n\n ShowWindow(handle, SW_MAXIMIZE);\n\n }\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 42, "score": 273044.11719047313 }, { "content": "fn build_number_select(num_select: &mut nwg::NumberSelect, window: &nwg::Window, font: &nwg::Font) {\n\n nwg::NumberSelect::builder()\n\n .font(Some(font))\n\n .parent(window)\n\n .build(num_select);\n\n}\n\n```\n\n\n\n*/\n\n#[derive(Default)]\n\npub struct NumberSelect {\n\n pub handle: ControlHandle,\n\n data: Rc<RefCell<NumberSelectData>>,\n\n edit: TextInput,\n\n btn_up: Button,\n\n btn_down: Button,\n\n handler: Option<RawEventHandler>,\n\n}\n\n\n\nimpl NumberSelect {\n", "file_path": "native-windows-gui/src/controls/number_select.rs", "rank": 43, "score": 272013.5809008528 }, { "content": "pub fn slice_as_bytes<'a, D: Copy>(data: &'a [D]) -> &'a [u8] {\n\n unsafe {\n\n data.align_to().1\n\n }\n\n}\n\n\n\n\n", "file_path": "native-windows-gui/examples/wgpu_canvas/src/main.rs", "rank": 45, "score": 268473.4726190473 }, { "content": "/// Create the NWG tab classes\n\npub fn create_tab_classes() -> Result<(), NwgError> {\n\n use winapi::shared::windef::HBRUSH;\n\n use winapi::um::libloaderapi::GetModuleHandleW;\n\n use winapi::um::winuser::COLOR_BTNFACE;\n\n\n\n let hmod = unsafe { GetModuleHandleW(ptr::null_mut()) };\n\n if hmod.is_null() {\n\n return Err(NwgError::initialization(\"GetModuleHandleW failed\"));\n\n }\n\n\n\n unsafe {\n\n build_sysclass(\n\n hmod,\n\n TAB_CLASS_ID,\n\n Some(tab_proc),\n\n Some(COLOR_BTNFACE as HBRUSH),\n\n None,\n\n )?;\n\n }\n\n\n", "file_path": "native-windows-gui/src/win32/tabs.rs", "rank": 46, "score": 267467.1926071784 }, { "content": "pub fn is_bitmap(handle: HBITMAP) -> bool {\n\n use winapi::shared::minwindef::LPVOID;\n\n use winapi::um::wingdi::GetBitmapBits;\n\n\n\n let mut bits: [u8; 1] = [0; 1];\n\n unsafe { GetBitmapBits(handle, 1, &mut bits as *mut [u8; 1] as LPVOID) != 0 }\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/resources_helper.rs", "rank": 47, "score": 266002.0258826976 }, { "content": "/// Initializes some application wide GUI settings.\n\n/// This includes default styling and common controls resources.\n\npub fn init() -> std::result::Result<(), errors::NwgError> {\n\n if cfg!(not(feature = \"no-styling\")) {\n\n enable_visual_styles();\n\n }\n\n\n\n init_common_controls()\n\n}\n", "file_path": "native-windows-gui/src/lib.rs", "rank": 48, "score": 265205.1994537726 }, { "content": "pub fn get_style(handle: HWND) -> UINT {\n\n use ::winapi::um::winuser::GWL_STYLE;\n\n get_window_long(handle, GWL_STYLE) as UINT\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 49, "score": 262768.982102977 }, { "content": "fn read_custom_data_handle(window: &nwg::Window) -> Option<Hello> {\n\n unsafe {\n\n nwg::Clipboard::open(window);\n\n let handle = nwg::Clipboard::data_handle(nwg::ClipboardFormat::Global(\"Hello\"));\n\n let data = match handle {\n\n Some(h) => {\n\n let data_ptr: *const Hello = h.cast();\n\n let data = *data_ptr;\n\n h.release();\n\n Some(data)\n\n },\n\n None => None\n\n };\n\n\n\n nwg::Clipboard::close();\n\n data\n\n }\n\n}\n\n\n\n```\n", "file_path": "native-windows-gui/src/win32/clipboard.rs", "rank": 50, "score": 261150.74332321115 }, { "content": "/// Create the NWG tab classes\n\npub fn create_extern_canvas_classes() -> Result<(), NwgError> {\n\n use winapi::shared::windef::HBRUSH;\n\n use winapi::um::libloaderapi::GetModuleHandleW;\n\n use winapi::um::winuser::{CS_HREDRAW, CS_OWNDC, CS_VREDRAW};\n\n\n\n let hmod = unsafe { GetModuleHandleW(ptr::null_mut()) };\n\n if hmod.is_null() {\n\n return Err(NwgError::initialization(\"GetModuleHandleW failed\"));\n\n }\n\n\n\n unsafe {\n\n build_sysclass(\n\n hmod,\n\n EXT_CANVAS_CLASS_ID,\n\n Some(extern_canvas_proc),\n\n Some(0 as HBRUSH),\n\n Some(CS_OWNDC | CS_VREDRAW | CS_HREDRAW),\n\n )?;\n\n }\n\n\n", "file_path": "native-windows-gui/src/win32/extern_canvas.rs", "rank": 51, "score": 259813.6441822626 }, { "content": "#[cfg(feature = \"tree-view\")]\n\nfn tree_data(m: u32, notif_raw: *const NMHDR) -> EventData {\n\n use crate::{ExpandState, TreeItem, TreeItemAction, TreeItemState};\n\n use winapi::um::commctrl::{\n\n NMTREEVIEWW, NMTVDISPINFOW, NMTVITEMCHANGE, TVE_COLLAPSE, TVE_EXPAND, TVN_DELETEITEMW,\n\n TVN_ENDLABELEDITW, TVN_ITEMCHANGEDW, TVN_ITEMEXPANDEDW, TVN_SELCHANGEDW,\n\n };\n\n\n\n match m {\n\n TVN_DELETEITEMW => {\n\n let data = unsafe { &*(notif_raw as *const NMTREEVIEWW) };\n\n let item = TreeItem {\n\n handle: data.itemOld.hItem,\n\n };\n\n EventData::OnTreeItemDelete(item)\n\n }\n\n TVN_ITEMEXPANDEDW => {\n\n let data = unsafe { &*(notif_raw as *const NMTREEVIEWW) };\n\n let item = TreeItem {\n\n handle: data.itemNew.hItem,\n\n };\n", "file_path": "native-windows-gui/src/win32/window.rs", "rank": 52, "score": 259698.5517587432 }, { "content": "#[cfg(not(feature = \"tree-view\"))]\n\nfn tree_data(_m: u32, _notif_raw: *const NMHDR) -> EventData {\n\n // If tree-view is not enabled, the data type won't be available so we return NO_DATA\n\n NO_DATA\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/window.rs", "rank": 53, "score": 259698.55175874318 }, { "content": "pub fn get_window_font(handle: HWND) -> HFONT {\n\n use winapi::um::winuser::WM_GETFONT;\n\n unsafe {\n\n let h = send_message(handle, WM_GETFONT, 0, 0);\n\n mem::transmute(h)\n\n }\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 54, "score": 259435.44622927145 }, { "content": "#[cfg(feature = \"list-view\")]\n\nfn list_view_data(m: u32, notif_raw: *const NMHDR) -> EventData {\n\n use winapi::um::commctrl::{\n\n LVIS_SELECTED, LVN_COLUMNCLICK, LVN_DELETEITEM, LVN_INSERTITEM, LVN_ITEMACTIVATE,\n\n LVN_ITEMCHANGED, NMITEMACTIVATE, NMLISTVIEW, NM_CLICK, NM_DBLCLK, NM_RCLICK,\n\n };\n\n\n\n match m {\n\n LVN_DELETEITEM | LVN_INSERTITEM | LVN_COLUMNCLICK => {\n\n let data: &NMLISTVIEW = unsafe { &*(notif_raw as *const NMLISTVIEW) };\n\n EventData::OnListViewItemIndex {\n\n row_index: data.iItem as _,\n\n column_index: data.iSubItem as _,\n\n }\n\n }\n\n LVN_ITEMACTIVATE | NM_CLICK | NM_DBLCLK | NM_RCLICK => {\n\n let data: &NMITEMACTIVATE = unsafe { &*(notif_raw as *const NMITEMACTIVATE) };\n\n EventData::OnListViewItemIndex {\n\n row_index: data.iItem as _,\n\n column_index: data.iSubItem as _,\n\n }\n", "file_path": "native-windows-gui/src/win32/window.rs", "rank": 55, "score": 256188.50690628233 }, { "content": "#[cfg(not(feature = \"list-view\"))]\n\nfn list_view_data(_m: u32, _notif_raw: *const NMHDR) -> EventData {\n\n // If list-view is not enabled, the data type won't be available so we return NO_DATA\n\n NO_DATA\n\n}\n\n\n\nunsafe fn static_commands(handle: HWND, m: u16) -> Event {\n\n use winapi::um::winuser::SendMessageW;\n\n use winapi::um::winuser::{\n\n IMAGE_BITMAP, IMAGE_CURSOR, IMAGE_ICON, STM_GETIMAGE, STN_CLICKED, STN_DBLCLK,\n\n };\n\n\n\n let has_image = SendMessageW(handle, STM_GETIMAGE, IMAGE_BITMAP as usize, 0) != 0;\n\n let has_icon = SendMessageW(handle, STM_GETIMAGE, IMAGE_ICON as usize, 0) != 0;\n\n let has_cursor = SendMessageW(handle, STM_GETIMAGE, IMAGE_CURSOR as usize, 0) != 0;\n\n\n\n if has_image | has_icon | has_cursor {\n\n match m {\n\n STN_CLICKED => Event::OnImageFrameClick,\n\n STN_DBLCLK => Event::OnImageFrameDoubleClick,\n\n _ => Event::Unknown,\n", "file_path": "native-windows-gui/src/win32/window.rs", "rank": 56, "score": 256188.50690628233 }, { "content": "type RawCallback = dyn Fn(HWND, UINT, WPARAM, LPARAM) -> Option<LRESULT>;\n", "file_path": "native-windows-gui/src/win32/window.rs", "rank": 57, "score": 255958.20301655075 }, { "content": "/// Building a tooltip and add tooltips at the same time\n\nfn build_tooltip(tt: &mut nwg::Tooltip, btn1: &nwg::Button, btn2: &nwg::Button) {\n\n nwg::Tooltip::builder()\n\n .register(btn1, \"A test button\")\n\n .register_callback(btn2)\n\n .build(tt);\n\n}\n\n\n", "file_path": "native-windows-gui/src/controls/tooltip.rs", "rank": 58, "score": 254496.10319004307 }, { "content": "pub fn error_message<'a>(title: &'a str, content: &'a str) -> MessageChoice {\n\n let params = MessageParams {\n\n title,\n\n content,\n\n buttons: MessageButtons::Ok,\n\n icons: MessageIcons::Error,\n\n };\n\n\n\n message(&params)\n\n}\n\n\n\n/**\n\n Display a simple error message box. The message box has for style `MessageButtons::Ok` and `MessageIcons::Error`.\n\n\n\n This functions panics if a non window control is used as parent (ex: a menu)\n\n\n\n Parameters:\n\n * parent: Parent window to lock for the duration of the message box\n\n * title: The message box title\n\n * content: The message box message\n\n*/\n", "file_path": "native-windows-gui/src/win32/message_box.rs", "rank": 59, "score": 254008.26055163238 }, { "content": "/// Execute the callback for each first level children of the window\n\npub fn iterate_window_children<F>(hwnd_parent: HWND, cb: F)\n\nwhere\n\n F: FnMut(HWND),\n\n{\n\n use winapi::shared::minwindef::BOOL;\n\n use winapi::um::winuser::EnumChildWindows;\n\n\n\n struct EnumChildData<F> {\n\n parent: HWND,\n\n callback: F,\n\n }\n\n\n\n unsafe extern \"system\" fn enum_child<F>(hwnd: HWND, p: LPARAM) -> BOOL\n\n where\n\n F: FnMut(HWND),\n\n {\n\n // Only iterate over the top level children\n\n let enum_data_ptr = p as *mut EnumChildData<F>;\n\n let enum_data = &mut *enum_data_ptr;\n\n if get_window_parent(hwnd) == enum_data.parent {\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 60, "score": 252583.84884426685 }, { "content": "fn iter_tree_view(tree: &mut nwg::TreeView) {\n\n for item in tree.iter() {\n\n println!(\"{:?}\", tree.item_text(&item));\n\n }\n\n}\n\n```\n\n*/\n\n#[allow(unused)]\n\npub struct TreeViewIterator<'a> {\n\n tree_view: &'a TreeView,\n\n tree_view_handle: HWND,\n\n base_item: HTREEITEM,\n\n current_item: HTREEITEM,\n\n action: NextAction,\n\n}\n\n\n\nimpl<'a> TreeViewIterator<'a> {\n\n /// Use `TreeView.iter` to create a `TreeViewIterator`\n\n pub(crate) fn new(tree_view: &'a TreeView, current_item: HTREEITEM) -> TreeViewIterator {\n\n let tree_view_handle = tree_view.handle.hwnd().unwrap();\n", "file_path": "native-windows-gui/src/controls/treeview_iterator.rs", "rank": 61, "score": 251711.63342688547 }, { "content": "pub fn dispatch_thread_events_with_callback<F>(mut cb: F)\n\nwhere\n\n F: FnMut() + 'static,\n\n{\n\n use winapi::um::winuser::MSG;\n\n use winapi::um::winuser::{PeekMessageW, PM_REMOVE, WM_QUIT};\n\n\n\n unsafe {\n\n let mut msg: MSG = mem::zeroed();\n\n while msg.message != WM_QUIT {\n\n let has_message = PeekMessageW(&mut msg, ptr::null_mut(), 0, 0, PM_REMOVE) != 0;\n\n if has_message && IsDialogMessageW(GetAncestor(msg.hwnd, GA_ROOT), &mut msg) == 0 {\n\n TranslateMessage(&msg);\n\n DispatchMessageW(&msg);\n\n }\n\n\n\n cb();\n\n }\n\n }\n\n}\n\n\n\n/**\n\n Break the events loop running on the current thread\n\n*/\n", "file_path": "native-windows-gui/src/win32/mod.rs", "rank": 62, "score": 249197.60342995398 }, { "content": "pub fn destroy_icon(icon: HANDLE) {\n\n unsafe {\n\n winapi::um::winuser::DestroyIcon(icon as _);\n\n }\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/resources_helper.rs", "rank": 63, "score": 243973.79548913508 }, { "content": "pub fn destroy_cursor(cursor: HANDLE) {\n\n unsafe {\n\n winapi::um::winuser::DestroyCursor(cursor as _);\n\n }\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/resources_helper.rs", "rank": 64, "score": 243973.79548913508 }, { "content": "pub fn destroy_obj(obj: HANDLE) {\n\n unsafe {\n\n winapi::um::wingdi::DeleteObject(obj as _);\n\n }\n\n}\n\n\n\npub unsafe fn build_font(\n\n size: i32,\n\n weight: u32,\n\n style: [bool; 3],\n\n family_name: Option<&str>,\n\n) -> Result<HFONT, NwgError> {\n\n use winapi::um::wingdi::CreateFontW;\n\n use winapi::um::wingdi::{\n\n CLEARTYPE_QUALITY, CLIP_DEFAULT_PRECIS, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, VARIABLE_PITCH,\n\n };\n\n let [use_italic, use_underline, use_strikeout] = style;\n\n\n\n let fam;\n\n let family_name_ptr;\n", "file_path": "native-windows-gui/src/win32/resources_helper.rs", "rank": 65, "score": 243973.79548913508 }, { "content": "fn set_tooltip_dynamic<'a>(app: &ControlsTest, handle: &ControlHandle, data: &ToolTipTextData) {\n\n if &app.window == handle {\n\n data.set_text(&format!(\"Control text: \\\"{}\\\"\", app.window.text()));\n\n } else if &app.test_text_input == handle {\n\n data.set_text(&format!(\"Control text: \\\"{}\\\"\", app.test_text_input.text()));\n\n }\n\n}\n\n\n", "file_path": "native-windows-gui/src/tests/control_test.rs", "rank": 66, "score": 243906.46143679644 }, { "content": "#[inline(always)]\n\n#[cfg(target_pointer_width = \"32\")]\n\npub fn get_window_long(handle: HWND, index: c_int) -> LONG {\n\n unsafe { ::winapi::um::winuser::GetWindowLongW(handle, index) }\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 67, "score": 242951.16786354163 }, { "content": "fn write_custom_data(window: &nwg::Window) {\n\n let data = Hello {\n\n foo: 6529,\n\n bar: [0, 100, 20]\n\n };\n\n\n\n nwg::Clipboard::open(window);\n\n nwg::Clipboard::empty();\n\n unsafe {\n\n nwg::Clipboard::set_data(\n\n nwg::ClipboardFormat::Global(\"Hello\"),\n\n &data as *const Hello,\n\n 1\n\n );\n\n }\n\n\n\n nwg::Clipboard::close();\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/clipboard.rs", "rank": 68, "score": 241822.5161894818 }, { "content": "pub fn unbind_raw_event_handler(handler: &RawEventHandler) -> Result<(), NwgError> {\n\n let subclass_proc = handler.subclass_proc;\n\n let handler_id = handler.handler_id;\n\n let handle = handler.handle;\n\n\n\n unsafe {\n\n let mut callback_value: UINT_PTR = 0;\n\n let result = GetWindowSubclass(handle, subclass_proc, handler_id, &mut callback_value);\n\n if result == 0 {\n\n let err = format!(\n\n concat!(\n\n \"Could not fetch raw event handler #{:?}.\",\n\n \"This can happen if the control ({:?}) was freed or\",\n\n \"if this raw event handler was already unbound\"\n\n ),\n\n handler_id, handle\n\n );\n\n return Err(NwgError::EventsBinding(err));\n\n }\n\n\n", "file_path": "native-windows-gui/src/win32/window.rs", "rank": 69, "score": 239994.53392916656 }, { "content": "#[inline(always)]\n\n#[cfg(target_pointer_width = \"64\")]\n\npub fn get_window_long(handle: HWND, index: c_int) -> LONG_PTR {\n\n unsafe { ::winapi::um::winuser::GetWindowLongPtrW(handle, index) }\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 70, "score": 239506.213011357 }, { "content": "#[cfg(feature = \"rich-textbox\")]\n\npub fn get_class_info(hwnd: HWND) -> Result<WNDCLASSEXW, ()> {\n\n use winapi::shared::ntdef::WCHAR;\n\n use winapi::um::libloaderapi::GetModuleHandleW;\n\n use winapi::um::winuser::{GetClassInfoExW, GetClassNameW};\n\n\n\n unsafe {\n\n let mut info: WNDCLASSEXW = mem::zeroed();\n\n\n\n let hinst = GetModuleHandleW(ptr::null_mut());\n\n\n\n let mut class_name_raw: [WCHAR; 100] = [0; 100];\n\n let count = GetClassNameW(hwnd, class_name_raw.as_mut_ptr(), 100) as usize;\n\n if count == 0 {\n\n return Err(());\n\n }\n\n\n\n let result = GetClassInfoExW(hinst, class_name_raw.as_ptr(), &mut info);\n\n match result == 0 {\n\n true => Err(()),\n\n false => Ok(info),\n\n }\n\n }\n\n}\n\n\n\n/// Reeturn the background color of a window\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 71, "score": 234188.4048338878 }, { "content": "#[cfg(feature = \"rich-textbox\")]\n\npub fn get_background_color(hwnd: HWND) -> Result<[u8; 3], ()> {\n\n use winapi::um::wingdi::{\n\n GetBValue, GetGValue, GetObjectW, GetRValue, GetStockObject, LOGBRUSH,\n\n };\n\n use winapi::um::winuser::GetSysColorBrush;\n\n\n\n match get_class_info(hwnd) {\n\n Ok(info) => unsafe {\n\n let brush = {\n\n let stock_handle = info.hbrBackground as usize as i32;\n\n let stock = GetStockObject(info.hbrBackground as usize as i32);\n\n match stock.is_null() {\n\n true => info.hbrBackground,\n\n false => {\n\n if stock_handle > 0 {\n\n // Windows use (stock handle - 1) for the real background color ¯\\_(ツ)_/¯\n\n GetSysColorBrush(stock_handle - 1)\n\n } else {\n\n GetSysColorBrush(0)\n\n }\n", "file_path": "native-windows-gui/src/win32/window_helper.rs", "rank": 72, "score": 229859.22177900473 }, { "content": "fn read_custom_data(window: &nwg::Window) -> Option<Hello> {\n\n unsafe {\n\n nwg::Clipboard::open(window);\n\n let data = nwg::Clipboard::data(nwg::ClipboardFormat::Global(\"Hello\"));\n\n nwg::Clipboard::close();\n\n data\n\n }\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/clipboard.rs", "rank": 73, "score": 225083.86477708165 }, { "content": "pub fn fatal_message<'a>(title: &'a str, content: &'a str) -> ! {\n\n error_message(title, content);\n\n panic!(\"{} - {}\", title, content);\n\n}\n\n\n\n/**\n\n Display a message box and then panic. The message box has for style `MessageButtons::Ok` and `MessageIcons::Error` .\n\n\n\n This functions panics if a non window control is used as parent (ex: a menu)\n\n\n\n Parameters:\n\n * parent: Parent window to lock for the duration of the message box\n\n * title: The message box title\n\n * content: The message box message\n\n*/\n", "file_path": "native-windows-gui/src/win32/message_box.rs", "rank": 74, "score": 224443.26939042963 }, { "content": "pub fn full_bind_event_handler<F>(handle: &ControlHandle, f: F) -> EventHandler\n\nwhere\n\n F: Fn(Event, EventData, ControlHandle) + 'static,\n\n{\n\n use winapi::um::winuser::EnumChildWindows;\n\n\n\n struct SetSubclassParam {\n\n callback_ptr: *mut *const Callback,\n\n subclass_id: UINT_PTR,\n\n }\n\n\n\n /**\n\n Function that iters over a top level window and bind the events dispatch callback\n\n */\n\n unsafe extern \"system\" fn set_children_subclass(h: HWND, p: LPARAM) -> i32 {\n\n let params_ptr = p as *mut SetSubclassParam;\n\n let params = &*params_ptr;\n\n\n\n let cb: Rc<Callback> = Rc::from_raw(*params.callback_ptr);\n\n\n", "file_path": "native-windows-gui/src/win32/window.rs", "rank": 75, "score": 221512.4861165614 }, { "content": "pub fn parameters(field: &syn::Field, attr_id: &'static str) -> (Vec<syn::Ident>, Vec<syn::Expr>) {\n\n let member = match field.ident.as_ref() {\n\n Some(m) => m,\n\n None => unreachable!()\n\n };\n\n\n\n let nwg_control = |attr: &&syn::Attribute| {\n\n attr.path.get_ident()\n\n .map(|id| id == attr_id )\n\n .unwrap_or(false)\n\n };\n\n\n\n let attr = match field.attrs.iter().find(nwg_control) {\n\n Some(attr) => attr,\n\n None => unreachable!()\n\n };\n\n\n\n let ctrl: Parameters = match syn::parse2(attr.tokens.clone()) {\n\n Ok(a) => a,\n\n Err(e) => panic!(\"Failed to parse field #{}: {}\", member, e)\n", "file_path": "native-windows-derive/src/controls.rs", "rank": 76, "score": 221007.08526839627 }, { "content": "pub fn to_utf16(s: &str) -> Vec<u16> {\n\n use std::ffi::OsStr;\n\n use std::os::windows::ffi::OsStrExt;\n\n\n\n OsStr::new(s)\n\n .encode_wide()\n\n .chain(Some(0u16).into_iter())\n\n .collect()\n\n}\n\n\n\n/**\n\n Decode a raw utf16 string. Should be null terminated.\n\n*/\n", "file_path": "native-windows-gui/src/win32/base_helper.rs", "rank": 77, "score": 219479.07605763437 }, { "content": "pub fn stop_thread_dispatch() {\n\n use winapi::um::winuser::PostMessageW;\n\n use winapi::um::winuser::WM_QUIT;\n\n\n\n unsafe { PostMessageW(ptr::null_mut(), WM_QUIT, 0, 0) };\n\n}\n\n\n\n/**\n\n Enable the Windows visual style in the application without having to use a manifest\n\n*/\n", "file_path": "native-windows-gui/src/win32/mod.rs", "rank": 78, "score": 218667.0639330725 }, { "content": "pub fn dispatch_thread_events() {\n\n use winapi::um::winuser::GetMessageW;\n\n use winapi::um::winuser::MSG;\n\n\n\n unsafe {\n\n let mut msg: MSG = mem::zeroed();\n\n while GetMessageW(&mut msg, ptr::null_mut(), 0, 0) != 0 {\n\n if IsDialogMessageW(GetAncestor(msg.hwnd, GA_ROOT), &mut msg) == 0 {\n\n TranslateMessage(&msg);\n\n DispatchMessageW(&msg);\n\n }\n\n }\n\n }\n\n}\n\n\n\n/**\n\n Dispatch system evetns in the current thread AND execute a callback after each peeking attempt.\n\n Unlike `dispath_thread_events`, this method will not pause the thread while waiting for events.\n\n*/\n", "file_path": "native-windows-gui/src/win32/mod.rs", "rank": 79, "score": 218667.06393307252 }, { "content": "fn print_char(data: &EventData) {\n\n match data {\n\n EventData::OnChar(c) => println!(\"{:?}\", c),\n\n _ => {}\n\n }\n\n}\n\n\n", "file_path": "native-windows-gui/src/tests/control_test.rs", "rank": 80, "score": 217291.50524632214 }, { "content": "pub fn main() {\n\n nwg::init().expect(\"Failed to init Native Windows GUI\");\n\n\n\n let app = ExternCanvas::build_ui(Default::default()).expect(\"Failed to build UI\");\n\n\n\n // Make sure to render everything at least once before showing the window to remove weird artifacts.\n\n app.canvas.create_context();\n\n app.canvas.render();\n\n\n\n // Here we use the `with_callback` version of dispatch_thread_events\n\n // Internally the callback will be executed almost as fast as `loop { callback() }`\n\n nwg::dispatch_thread_events_with_callback(move || {\n\n app.canvas.render();\n\n });\n\n}\n\n\n\n\n\nconst VS_SRC: &'static [u8] = b\"#version 330\n\nlayout (location=0) in vec2 a_position;\n\nlayout (location=1) in vec4 a_color;\n", "file_path": "native-windows-gui/examples/opengl_canvas/src/main.rs", "rank": 81, "score": 217281.71488364914 }, { "content": "pub fn simple_message<'a>(title: &'a str, content: &'a str) -> MessageChoice {\n\n let params = MessageParams {\n\n title,\n\n content,\n\n buttons: MessageButtons::Ok,\n\n icons: MessageIcons::Info,\n\n };\n\n\n\n message(&params)\n\n}\n\n\n\n/**\n\n Display a simple message box. The message box has for style `MessageButtons::Ok` and `MessageIcons::Info`.\n\n\n\n This functions panics if a non window control is used as parent (ex: a menu)\n\n\n\n Parameters:\n\n * parent: Parent window to lock for the duration of the message box\n\n * title: The message box title\n\n * content: The message box message\n\n*/\n", "file_path": "native-windows-gui/src/win32/message_box.rs", "rank": 82, "score": 215720.85242181097 }, { "content": "fn build_image_list(list: &mut nwg::ImageList) {\n\n nwg::ImageList::builder()\n\n .size((64, 64))\n\n .initial(10)\n\n .grow(1)\n\n .build(list);\n\n}\n\n```\n\n\n\n*/\n\npub struct ImageList {\n\n pub handle: HIMAGELIST,\n\n pub owned: bool,\n\n}\n\n\n\nimpl ImageList {\n\n pub fn builder() -> ImageListBuilder {\n\n ImageListBuilder {\n\n size: (32, 32),\n\n initial: 5,\n", "file_path": "native-windows-gui/src/resources/image_list.rs", "rank": 83, "score": 215298.53409579542 }, { "content": "#[cfg(not(feature = \"tabs\"))]\n\nfn tabs_init() -> Result<(), NwgError> {\n\n Ok(())\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/mod.rs", "rank": 84, "score": 210831.7348220347 }, { "content": "#[cfg(not(feature = \"frame\"))]\n\nfn frame_init() -> Result<(), NwgError> {\n\n Ok(())\n\n}\n", "file_path": "native-windows-gui/src/win32/mod.rs", "rank": 85, "score": 210831.7348220347 }, { "content": "fn load_cursor_builder() -> nwg::Cursor {\n\n let mut cursor = nwg::Cursor::default();\n\n\n\n nwg::Cursor::builder()\n\n .source_file(Some(\"Hello.cur\"))\n\n .strict(true)\n\n .build(&mut cursor)\n\n .unwrap();\n\n\n\n cursor\n\n}\n\n\n\n*/\n\n#[allow(unused)]\n\npub struct Cursor {\n\n pub handle: HANDLE,\n\n pub(crate) owned: bool,\n\n}\n\n\n\nimpl Cursor {\n", "file_path": "native-windows-gui/src/resources/cursor.rs", "rank": 86, "score": 210419.1390395962 }, { "content": "fn load_bitmap_builder() -> nwg::Bitmap {\n\n let mut bitmap = nwg::Bitmap::default();\n\n\n\n nwg::Bitmap::builder()\n\n .source_file(Some(\"Hello.bmp\"))\n\n .strict(true)\n\n .build(&mut bitmap)\n\n .unwrap();\n\n\n\n bitmap\n\n}\n\n\n\n```\n\n\n\n*/\n\n#[allow(unused)]\n\npub struct Bitmap {\n\n pub handle: HANDLE,\n\n pub(crate) owned: bool,\n\n}\n", "file_path": "native-windows-gui/src/resources/bitmap.rs", "rank": 87, "score": 210419.1390395962 }, { "content": "fn load_icon_builder() -> nwg::Icon {\n\n let mut icon = nwg::Icon::default();\n\n\n\n nwg::Icon::builder()\n\n .source_file(Some(\"hello.ico\"))\n\n .strict(true)\n\n .build(&mut icon);\n\n\n\n icon\n\n}\n\n\n\n*/\n\n#[allow(unused)]\n\npub struct Icon {\n\n pub handle: HANDLE,\n\n pub(crate) owned: bool,\n\n}\n\n\n\nimpl Icon {\n\n pub fn builder<'a>() -> IconBuilder<'a> {\n", "file_path": "native-windows-gui/src/resources/icon.rs", "rank": 88, "score": 210419.1390395962 }, { "content": "fn next_treeview_item(handle: &ControlHandle, action: usize, item: HTREEITEM) -> Option<TreeItem> {\n\n use winapi::um::commctrl::TVM_GETNEXTITEM;\n\n\n\n if handle.blank() {\n\n panic!(\"{}\", NOT_BOUND);\n\n }\n\n let handle = handle.hwnd().expect(BAD_HANDLE);\n\n\n\n let handle = wh::send_message(handle, TVM_GETNEXTITEM, action as _, item as _) as HTREEITEM;\n\n if handle.is_null() {\n\n None\n\n } else {\n\n Some(TreeItem { handle })\n\n }\n\n}\n\n\n", "file_path": "native-windows-gui/src/controls/treeview.rs", "rank": 89, "score": 208117.30517267445 }, { "content": "/// Inner function used by the message box function\n\nfn inner_message(parent: HWND, params: &MessageParams) -> MessageChoice {\n\n use winapi::um::winuser::{\n\n MB_ABORTRETRYIGNORE, MB_CANCELTRYCONTINUE, MB_ICONEXCLAMATION, MB_ICONINFORMATION,\n\n MB_ICONQUESTION, MB_ICONSTOP, MB_OK, MB_OKCANCEL, MB_RETRYCANCEL, MB_YESNO, MB_YESNOCANCEL,\n\n };\n\n\n\n use winapi::um::winuser::MessageBoxW;\n\n use winapi::um::winuser::{\n\n IDABORT, IDCANCEL, IDCONTINUE, IDIGNORE, IDNO, IDOK, IDRETRY, IDTRYAGAIN, IDYES,\n\n };\n\n\n\n let text = to_utf16(params.content);\n\n let title = to_utf16(params.title);\n\n\n\n let buttons = match params.buttons {\n\n MessageButtons::AbortTryIgnore => MB_ABORTRETRYIGNORE,\n\n MessageButtons::CancelTryContinue => MB_CANCELTRYCONTINUE,\n\n MessageButtons::Ok => MB_OK,\n\n MessageButtons::OkCancel => MB_OKCANCEL,\n\n MessageButtons::RetryCancel => MB_RETRYCANCEL,\n", "file_path": "native-windows-gui/src/win32/message_box.rs", "rank": 90, "score": 208045.5615791167 }, { "content": "#[cfg(not(feature = \"extern-canvas\"))]\n\nfn extern_canvas_init() -> Result<(), NwgError> {\n\n Ok(())\n\n}\n\n\n", "file_path": "native-windows-gui/src/win32/mod.rs", "rank": 91, "score": 207489.1784897462 }, { "content": "type Size = (u32, u32);\n\n\n\n/**\n\n Different mode in the application.\n\n\n\n - Draw: Paint pixels\n\n - Erase: Remove painted pixel\n\n*/\n\n#[derive(Debug, Copy, Clone)]\n\npub enum AppMode {\n\n Draw,\n\n Erase\n\n}\n\n\n\n/**\n\n Application state.\n\n Includes the current drawing state and relation with the other running instances of SyncDraw.\n\n*/\n\n#[derive(Default)]\n\npub struct AppData {\n", "file_path": "native-windows-gui/examples/sync-draw/src/data.rs", "rank": 92, "score": 207224.6649383987 }, { "content": "/// Adding/Updating a tooltip after the initial tooltip creation\n\nfn add_tooltip(btn: &nwg::Button, tt: &nwg::Tooltip) {\n\n tt.register(btn, \"This is a button!\");\n\n}\n\n\n", "file_path": "native-windows-gui/src/controls/tooltip.rs", "rank": 93, "score": 206784.86820316038 }, { "content": "#[cfg(feature = \"image-list\")]\n\nfn builder_set_image_list(builder: &TreeViewBuilder, out: &TreeView) {\n\n if builder.image_list.is_some() {\n\n out.set_image_list(builder.image_list);\n\n }\n\n}\n\n\n", "file_path": "native-windows-gui/src/controls/treeview.rs", "rank": 94, "score": 204440.68142523622 }, { "content": "type Callback = dyn Fn(Event, EventData, ControlHandle);\n\n\n\n/**\n\n An opaque structure that represent a window subclass hook.\n\n*/\n\npub struct EventHandler {\n\n handles: Vec<HWND>,\n\n id: SUBCLASSPROC,\n\n subclass_id: UINT_PTR,\n\n}\n\n\n\n/**\n\n An opaque structure that represent a window subclass hook.\n\n*/\n\npub struct RawEventHandler {\n\n handle: HWND,\n\n subclass_proc: SUBCLASSPROC,\n\n handler_id: UINT_PTR,\n\n}\n\n\n\n/**\n\n Note. While there might be a race condition here, it does not matter because\n\n All controls are thread local and the true id is (HANDLE + NOTICE_ID)\n\n The same apply to timers\n\n*/\n", "file_path": "native-windows-gui/src/win32/window.rs", "rank": 95, "score": 204399.61730785194 } ]
Rust
src/lib.rs
helium/longfi-device-rs
97ad8f380205a0b0b1c90ff0513e30c576b71e5d
#![cfg_attr(not(test), no_std)] use longfi_sys; pub use longfi_sys::AntPinsMode_t as AntPinsMode; pub use longfi_sys::BoardBindings_t as BoardBindings; pub use longfi_sys::ClientEvent_t as ClientEvent; pub use longfi_sys::LongFiAuthCallbacks as AuthCb; pub use longfi_sys::LongFiAuthMode_t as AuthMode; pub use longfi_sys::LongFiConfig_t as Config; pub use longfi_sys::LongFi_t; use longfi_sys::Radio_t; pub use longfi_sys::RfEvent_t; pub use longfi_sys::RxPacket_t as RxPacket; pub use longfi_sys::SX126xRadioNew; pub use longfi_sys::SX1276RadioNew; #[derive(Debug)] pub enum RfEvent { DIO0, DIO1, } static mut SX12XX: Option<Radio> = None; pub struct LongFi { c_handle: LongFi_t, } #[derive(Debug)] pub enum Error { NoRadioPointer, } unsafe impl Send for LongFi {} pub struct Radio { c_handle: Radio_t, } impl Radio { pub fn sx1262() -> Radio { Radio { c_handle: unsafe { SX126xRadioNew() }, } } pub fn sx1276() -> Radio { Radio { c_handle: unsafe { SX1276RadioNew() }, } } } impl LongFi { pub fn new( radio: Radio, bindings: &mut BoardBindings, config: Config, auth_cb_set: &[u8; 16], ) -> Result<LongFi, Error> { unsafe { SX12XX = Some(radio); let mut auth_cb = core::mem::zeroed::<AuthCb>(); *auth_cb.preshared_key.as_mut() = auth_cb_set.as_ptr(); if let Some(radio) = &mut SX12XX { let radio_ptr: *mut Radio_t = &mut radio.c_handle; let mut longfi_radio = LongFi { c_handle: longfi_sys::longfi_new_handle(bindings, radio_ptr, config, auth_cb), }; longfi_sys::longfi_init(&mut longfi_radio.c_handle); Ok(longfi_radio) } else { Err(Error::NoRadioPointer) } } } pub fn set_buffer(&mut self, buffer: &mut [u8]) { unsafe { longfi_sys::longfi_set_buf(&mut self.c_handle, buffer.as_mut_ptr(), buffer.len()); } } pub fn handle_event(&mut self, event: RfEvent) -> ClientEvent { let event_for_c = match event { RfEvent::DIO0 => RfEvent_t::RFE_DIO0, RfEvent::DIO1 => RfEvent_t::RFE_DIO1, }; unsafe { longfi_sys::longfi_handle_event(&mut self.c_handle, event_for_c) } } pub fn send(&mut self, buffer: &[u8]) { unsafe { longfi_sys::longfi_send(&mut self.c_handle, buffer.as_ptr(), buffer.len()); } } pub fn send_test(&mut self) { unsafe { longfi_sys::longfi_rf_test(&mut self.c_handle); } } pub fn get_rx(&mut self) -> RxPacket { unsafe { longfi_sys::longfi_get_rx() } } } extern crate libm; #[no_mangle] pub extern "C" fn ceil(expr: f64) -> f64 { libm::ceil(expr) } #[no_mangle] pub extern "C" fn round(expr: f64) -> f64 { libm::round(expr) } #[no_mangle] pub extern "C" fn floor(expr: f64) -> f64 { libm::floor(expr) } #[cfg(test)] mod tests { use super::*; use super::{LongFi, RfConfig}; use longfi_sys::{ GpioIrqHandler, Gpio_t, IrqModes, IrqPriorities, PinConfigs, PinModes, PinNames, PinTypes, Spi_t, }; #[no_mangle] pub extern "C" fn spi_in_out(s: *mut Spi_t, out_data: u16) -> u16 { 0 } #[no_mangle] pub extern "C" fn gpio_init( obj: *mut Gpio_t, pin: PinNames, mode: PinModes, config: PinConfigs, pin_type: PinTypes, value: u32, ) { } #[no_mangle] pub extern "C" fn gpio_write(obj: *mut Gpio_t, value: u32) {} #[no_mangle] pub extern "C" fn gpio_set_interrupt( obj: *mut Gpio_t, irq_mode: IrqModes, irq_priority: IrqPriorities, irq_handler: GpioIrqHandler, ) { } #[no_mangle] pub extern "C" fn delay_ms(ms: u32) {} static mut RFCONFIG: RfConfig = RfConfig { oui: 0x12345678, device_id: 0x9abc, }; static mut BINDINGS: BoardBindings = BoardBindings { spi_in_out: Some(spi_in_out), delay_ms: Some(delay_ms), gpio_init: Some(gpio_init), gpio_write: Some(gpio_write), gpio_set_interrupt: Some(gpio_set_interrupt), }; static mut LONGFI: Option<LongFi> = None; #[test] fn test_linking() { let mut longfi_radio = unsafe { LongFi::new(&mut BINDINGS, &mut RFCONFIG).unwrap() }; longfi_radio.initialize(); unsafe { LONGFI = Some(longfi_radio) }; } #[test] fn test_sending() { let config = RfConfig { oui: 0x12345678, device_id: 0x9abc, }; let bindings = BoardBindings { spi_in_out: Some(spi_in_out), delay_ms: Some(delay_ms), gpio_init: Some(gpio_init), gpio_write: Some(gpio_write), gpio_set_interrupt: Some(gpio_set_interrupt), }; let packet: [u8; 5] = [0xDE, 0xAD, 0xBE, 0xEF, 0]; unsafe { if let Some(longfi) = &mut LONGFI { longfi.send(&packet); } }; } }
#![cfg_attr(not(test), no_std)] use longfi_sys; pub use longfi_sys::AntPinsMode_t as AntPinsMode; pub use longfi_sys::BoardBindings_t as BoardBindings; pub use longfi_sys::ClientEvent_t as ClientEvent; pub use longfi_sys::LongFiAuthCallbacks as AuthCb; pub use longfi_sys::LongFiAuthMode_t as AuthMode; pub use longfi_sys::LongFiConfig_t as Config; pub use longfi_sys::LongFi_t; use longfi_sys::Radio_t; pub use longfi_sys::RfEvent_t; pub use longfi_sys::RxPacket_t as RxPacket; pub use longfi_sys::SX126xRadioNew; pub use longfi_sys::SX1276RadioNew; #[derive(Debug)] pub enum RfEvent { DIO0, DIO1, } static mut SX12XX: Option<Radio> = None; pub struct LongFi { c_handle: LongFi_t, } #[derive(Debug)] pub enum Error { NoRadioPointer, } unsafe impl Send for LongFi {} pub struct Radio { c_handle: Radio_t, } impl Radio { pub fn sx1262() -> Radio { Radio { c_handle: unsafe { SX126xRadioNew() }, } } pub fn sx1276() -> Radio { Radio { c_handle: unsafe { SX1276RadioNew() }, } } } impl LongFi { pub fn new( radio: Radio, bindings: &mut BoardBindings, config: Config, auth_cb_set: &[u8; 16], ) -> Result<LongFi, Error> { unsafe { SX12XX = Some(radio); let mut auth_cb = core::mem::zeroed::<AuthCb>(); *auth_cb.preshared_key.as_mut() = auth_cb_set.as_ptr(); if let Some(radio) = &mut SX12XX { let radio_ptr: *mut Radio_t = &mut radio.c_handle;
longfi_sys::longfi_init(&mut longfi_radio.c_handle); Ok(longfi_radio) } else { Err(Error::NoRadioPointer) } } } pub fn set_buffer(&mut self, buffer: &mut [u8]) { unsafe { longfi_sys::longfi_set_buf(&mut self.c_handle, buffer.as_mut_ptr(), buffer.len()); } } pub fn handle_event(&mut self, event: RfEvent) -> ClientEvent { let event_for_c = match event { RfEvent::DIO0 => RfEvent_t::RFE_DIO0, RfEvent::DIO1 => RfEvent_t::RFE_DIO1, }; unsafe { longfi_sys::longfi_handle_event(&mut self.c_handle, event_for_c) } } pub fn send(&mut self, buffer: &[u8]) { unsafe { longfi_sys::longfi_send(&mut self.c_handle, buffer.as_ptr(), buffer.len()); } } pub fn send_test(&mut self) { unsafe { longfi_sys::longfi_rf_test(&mut self.c_handle); } } pub fn get_rx(&mut self) -> RxPacket { unsafe { longfi_sys::longfi_get_rx() } } } extern crate libm; #[no_mangle] pub extern "C" fn ceil(expr: f64) -> f64 { libm::ceil(expr) } #[no_mangle] pub extern "C" fn round(expr: f64) -> f64 { libm::round(expr) } #[no_mangle] pub extern "C" fn floor(expr: f64) -> f64 { libm::floor(expr) } #[cfg(test)] mod tests { use super::*; use super::{LongFi, RfConfig}; use longfi_sys::{ GpioIrqHandler, Gpio_t, IrqModes, IrqPriorities, PinConfigs, PinModes, PinNames, PinTypes, Spi_t, }; #[no_mangle] pub extern "C" fn spi_in_out(s: *mut Spi_t, out_data: u16) -> u16 { 0 } #[no_mangle] pub extern "C" fn gpio_init( obj: *mut Gpio_t, pin: PinNames, mode: PinModes, config: PinConfigs, pin_type: PinTypes, value: u32, ) { } #[no_mangle] pub extern "C" fn gpio_write(obj: *mut Gpio_t, value: u32) {} #[no_mangle] pub extern "C" fn gpio_set_interrupt( obj: *mut Gpio_t, irq_mode: IrqModes, irq_priority: IrqPriorities, irq_handler: GpioIrqHandler, ) { } #[no_mangle] pub extern "C" fn delay_ms(ms: u32) {} static mut RFCONFIG: RfConfig = RfConfig { oui: 0x12345678, device_id: 0x9abc, }; static mut BINDINGS: BoardBindings = BoardBindings { spi_in_out: Some(spi_in_out), delay_ms: Some(delay_ms), gpio_init: Some(gpio_init), gpio_write: Some(gpio_write), gpio_set_interrupt: Some(gpio_set_interrupt), }; static mut LONGFI: Option<LongFi> = None; #[test] fn test_linking() { let mut longfi_radio = unsafe { LongFi::new(&mut BINDINGS, &mut RFCONFIG).unwrap() }; longfi_radio.initialize(); unsafe { LONGFI = Some(longfi_radio) }; } #[test] fn test_sending() { let config = RfConfig { oui: 0x12345678, device_id: 0x9abc, }; let bindings = BoardBindings { spi_in_out: Some(spi_in_out), delay_ms: Some(delay_ms), gpio_init: Some(gpio_init), gpio_write: Some(gpio_write), gpio_set_interrupt: Some(gpio_set_interrupt), }; let packet: [u8; 5] = [0xDE, 0xAD, 0xBE, 0xEF, 0]; unsafe { if let Some(longfi) = &mut LONGFI { longfi.send(&packet); } }; } }
let mut longfi_radio = LongFi { c_handle: longfi_sys::longfi_new_handle(bindings, radio_ptr, config, auth_cb), };
assignment_statement
[ { "content": "pub fn initialize_irq(\n\n pin: gpiob::PB4<Uninitialized>,\n\n syscfg: &mut hal::syscfg::SYSCFG,\n\n exti: &mut exti::Exti,\n\n) -> gpiob::PB4<Input<PullUp>> {\n\n let dio0 = pin.into_pull_up_input();\n\n\n\n exti.listen_gpio(\n\n syscfg,\n\n dio0.port(),\n\n GpioLine::from_raw_line(dio0.pin_number()).unwrap(),\n\n exti::TriggerEdge::Rising,\n\n );\n\n\n\n dio0\n\n}\n\n\n\npub type TcxoEn = gpioa::PA8<Output<PushPull>>;\n\n\n\nimpl LongFiBindings {\n", "file_path": "examples/stm32l0x2/longfi_bindings.rs", "rank": 0, "score": 77906.69035860432 }, { "content": "#[cfg(not(workaround_build))]\n\nfn main() {\n\n cargo_5730::run_build_script();\n\n}\n", "file_path": "longfi-sys/build.rs", "rank": 1, "score": 43781.01722061068 }, { "content": " set_antenna_pins: Some(set_antenna_pins),\n\n set_board_tcxo: None,\n\n busy_pin_status: None,\n\n reduce_power: None,\n\n },\n\n }\n\n }\n\n}\n\n\n\nstatic mut EN_TCXO: Option<TcxoEn> = None;\n\n\n\n#[no_mangle]\n\npub extern \"C\" fn set_tcxo(value: bool) -> u8 {\n\n unsafe {\n\n if let Some(pin) = &mut EN_TCXO {\n\n if value {\n\n pin.set_high().unwrap();\n\n } else {\n\n pin.set_low().unwrap();\n\n }\n\n }\n\n }\n\n 6\n\n}\n\n\n", "file_path": "examples/stm32l0x2/longfi_bindings.rs", "rank": 2, "score": 33567.77482476716 }, { "content": "}\n\n\n\nstatic mut SPI_NSS: Option<gpioa::PA15<Output<PushPull>>> = None;\n\n#[no_mangle]\n\nextern \"C\" fn spi_nss(value: bool) {\n\n unsafe {\n\n if let Some(pin) = &mut SPI_NSS {\n\n if value {\n\n pin.set_high().unwrap();\n\n } else {\n\n pin.set_low().unwrap();\n\n }\n\n }\n\n }\n\n}\n\n\n\nstatic mut RESET: Option<gpioc::PC0<Output<PushPull>>> = None;\n\n#[no_mangle]\n\nextern \"C\" fn radio_reset(value: bool) {\n\n unsafe {\n", "file_path": "examples/stm32l0x2/longfi_bindings.rs", "rank": 3, "score": 33566.99969049106 }, { "content": "use hal::exti;\n\nuse hal::exti::{ExtiLine, GpioLine};\n\nuse hal::gpio::*;\n\nuse hal::pac;\n\nuse hal::prelude::*;\n\nuse hal::rcc::Rcc;\n\nuse hal::rng;\n\nuse hal::spi;\n\n\n\nuse longfi_device::{AntPinsMode, BoardBindings};\n\nuse nb::block;\n\nuse stm32l0xx_hal as hal;\n\n\n\n#[allow(dead_code)]\n\npub struct LongFiBindings {\n\n pub bindings: BoardBindings,\n\n}\n\n\n", "file_path": "examples/stm32l0x2/longfi_bindings.rs", "rank": 4, "score": 33565.54099519093 }, { "content": " if let Some(pin) = &mut RESET {\n\n if value {\n\n pin.set_low().unwrap();\n\n } else {\n\n pin.set_high().unwrap();\n\n }\n\n }\n\n }\n\n}\n\n\n\n#[no_mangle]\n\nextern \"C\" fn delay_ms(ms: u32) {\n\n cortex_m::asm::delay(ms);\n\n}\n\n\n\nstatic mut RNG: Option<rng::Rng> = None;\n\nextern \"C\" fn get_random_bits(_bits: u8) -> u32 {\n\n unsafe {\n\n if let Some(rng) = &mut RNG {\n\n // enable starts the ADC conversions that generate the random number\n", "file_path": "examples/stm32l0x2/longfi_bindings.rs", "rank": 5, "score": 33565.45877937682 }, { "content": " pub fn new(\n\n spi_peripheral: pac::SPI1,\n\n rcc: &mut Rcc,\n\n rng: rng::Rng,\n\n spi_sck: gpiob::PB3<Uninitialized>,\n\n spi_miso: gpioa::PA6<Uninitialized>,\n\n spi_mosi: gpioa::PA7<Uninitialized>,\n\n spi_nss_pin: gpioa::PA15<Uninitialized>,\n\n reset: gpioc::PC0<Uninitialized>,\n\n rx: gpioa::PA1<Uninitialized>,\n\n tx_rfo: gpioc::PC2<Uninitialized>,\n\n tx_boost: gpioc::PC1<Uninitialized>,\n\n ) -> LongFiBindings {\n\n // store all of the necessary pins and peripherals into statics\n\n // this is necessary as the extern C functions need access\n\n // this is safe, thanks to ownership and because these statics are private\n\n unsafe {\n\n SPI = Some(spi_peripheral.spi(\n\n (spi_sck, spi_miso, spi_mosi),\n\n spi::MODE_0,\n", "file_path": "examples/stm32l0x2/longfi_bindings.rs", "rank": 6, "score": 33564.38779017199 }, { "content": "impl<Rx, TxRfo, TxBoost> AntennaSwitches<Rx, TxRfo, TxBoost>\n\nwhere\n\n Rx: embedded_hal::digital::v2::OutputPin,\n\n TxRfo: embedded_hal::digital::v2::OutputPin,\n\n TxBoost: embedded_hal::digital::v2::OutputPin,\n\n{\n\n pub fn new(rx: Rx, tx_rfo: TxRfo, tx_boost: TxBoost) -> AntennaSwitches<Rx, TxRfo, TxBoost> {\n\n AntennaSwitches {\n\n rx,\n\n tx_rfo,\n\n tx_boost,\n\n }\n\n }\n\n\n\n pub fn set_sleep(&mut self) {\n\n self.rx.set_low().unwrap_or(());\n\n self.tx_rfo.set_low().unwrap_or(());\n\n self.tx_boost.set_low().unwrap_or(());\n\n }\n\n\n", "file_path": "examples/stm32l0x2/longfi_bindings.rs", "rank": 7, "score": 33562.29289711423 }, { "content": " 1_000_000.hz(),\n\n rcc,\n\n ));\n\n SPI_NSS = Some(spi_nss_pin.into_push_pull_output());\n\n RESET = Some(reset.into_push_pull_output());\n\n ANT_SW = Some(AntennaSwitches::new(\n\n rx.into_push_pull_output(),\n\n tx_rfo.into_push_pull_output(),\n\n tx_boost.into_push_pull_output(),\n\n ));\n\n RNG = Some(rng);\n\n };\n\n\n\n LongFiBindings {\n\n bindings: BoardBindings {\n\n reset: Some(radio_reset),\n\n spi_in_out: Some(spi_in_out),\n\n spi_nss: Some(spi_nss),\n\n delay_ms: Some(delay_ms),\n\n get_random_bits: Some(get_random_bits),\n", "file_path": "examples/stm32l0x2/longfi_bindings.rs", "rank": 8, "score": 33561.659284180234 }, { "content": " pub fn set_tx(&mut self) {\n\n self.rx.set_low().unwrap_or(());\n\n self.tx_rfo.set_low().unwrap_or(());\n\n self.tx_boost.set_high().unwrap_or(());\n\n }\n\n\n\n pub fn set_rx(&mut self) {\n\n self.rx.set_high().unwrap_or(());\n\n self.tx_rfo.set_low().unwrap_or(());\n\n self.tx_boost.set_low().unwrap_or(());\n\n }\n\n}\n\n\n", "file_path": "examples/stm32l0x2/longfi_bindings.rs", "rank": 9, "score": 33561.37981536708 }, { "content": " rng.enable();\n\n // wait until the flag flips; interrupt driven is possible but no implemented\n\n rng.wait();\n\n // reading the result clears the ready flag\n\n let val = rng.take_result();\n\n // can save some power by disabling until next random number needed\n\n rng.disable();\n\n val\n\n } else {\n\n panic!(\"No Rng exists!\");\n\n }\n\n }\n\n}\n\n\n\npub struct AntennaSwitches<Rx, TxRfo, TxBoost> {\n\n rx: Rx,\n\n tx_rfo: TxRfo,\n\n tx_boost: TxBoost,\n\n}\n\n#[warn(unused_must_use)]\n", "file_path": "examples/stm32l0x2/longfi_bindings.rs", "rank": 10, "score": 33559.91984666426 }, { "content": "type Uninitialized = Input<Floating>;\n\n\n\npub type RadioIRQ = gpiob::PB4<Input<PullUp>>;\n\n\n", "file_path": "examples/stm32l0x2/longfi_bindings.rs", "rank": 11, "score": 28744.190913978713 }, { "content": "type AntSw = AntennaSwitches<\n\n stm32l0xx_hal::gpio::gpioa::PA1<stm32l0xx_hal::gpio::Output<stm32l0xx_hal::gpio::PushPull>>,\n\n stm32l0xx_hal::gpio::gpioc::PC2<stm32l0xx_hal::gpio::Output<stm32l0xx_hal::gpio::PushPull>>,\n\n stm32l0xx_hal::gpio::gpioc::PC1<stm32l0xx_hal::gpio::Output<stm32l0xx_hal::gpio::PushPull>>,\n\n>;\n\n\n\nstatic mut ANT_SW: Option<AntSw> = None;\n\n\n\npub extern \"C\" fn set_antenna_pins(mode: AntPinsMode, _power: u8) {\n\n unsafe {\n\n if let Some(ant_sw) = &mut ANT_SW {\n\n match mode {\n\n AntPinsMode::AntModeTx => {\n\n ant_sw.set_tx();\n\n }\n\n AntPinsMode::AntModeRx => {\n\n ant_sw.set_rx();\n\n }\n\n AntPinsMode::AntModeSleep => {\n\n ant_sw.set_sleep();\n\n }\n\n _ => (),\n\n }\n\n }\n\n }\n\n}\n", "file_path": "examples/stm32l0x2/longfi_bindings.rs", "rank": 12, "score": 27432.668895089955 }, { "content": "type SpiPort = hal::spi::Spi<\n\n hal::pac::SPI1,\n\n (\n\n hal::gpio::gpiob::PB3<hal::gpio::Input<hal::gpio::Floating>>,\n\n hal::gpio::gpioa::PA6<hal::gpio::Input<hal::gpio::Floating>>,\n\n hal::gpio::gpioa::PA7<hal::gpio::Input<hal::gpio::Floating>>,\n\n ),\n\n>;\n\nstatic mut SPI: Option<SpiPort> = None;\n\n#[no_mangle]\n\nextern \"C\" fn spi_in_out(out_data: u8) -> u8 {\n\n unsafe {\n\n if let Some(spi) = &mut SPI {\n\n spi.send(out_data).unwrap();\n\n let in_data = block!(spi.read()).unwrap();\n\n in_data\n\n } else {\n\n 0\n\n }\n\n }\n", "file_path": "examples/stm32l0x2/longfi_bindings.rs", "rank": 13, "score": 26235.606979667842 }, { "content": "\n\n // make the bindings\n\n let bindings = bindgen::Builder::default()\n\n .raw_line(\"use cty;\")\n\n .use_core()\n\n .ctypes_prefix(\"cty\")\n\n .detect_include_paths(true)\n\n .header(\"longfi-device/board.h\")\n\n .header(\"longfi-device/longfi.h\")\n\n .header(\"longfi-device/radio/radio.h\")\n\n .header(\"longfi-device/radio/sx1276/sx1276.h\")\n\n .header(\"longfi-device/radio/sx126x/sx126x.h\")\n\n .clang_arg(format!(\"-I{}/include\",dst.display()))\n\n .whitelist_var(\"XTAL_FREQ\")\n\n .whitelist_var(\"FREQ_STEP\")\n\n .whitelist_var(\"RX_BUFFER_SIZE\")\n\n .whitelist_type(\"RfEvent_t\")\n\n .whitelist_type(\"RadioState_t\")\n\n .whitelist_type(\"RadioModems_t\")\n\n .whitelist_type(\"ClientEvent_t\")\n", "file_path": "longfi-sys/build.rs", "rank": 14, "score": 16764.521864179274 }, { "content": " .whitelist_type(\"QualityOfService_t\")\n\n .whitelist_type(\"RfConfig_t\")\n\n .whitelist_type(\"RxPacket_t\")\n\n .whitelist_type(\"LF_Gpio_t\")\n\n .whitelist_type(\"LF_Spi_t\")\n\n .whitelist_type(\"AntPinsMode_t\")\n\n .whitelist_type(\"LongFiAuthMode_t\")\n\n .whitelist_type(\"LongFiAuthCallbacks\")\n\n .whitelist_function(\"longfi_init\")\n\n .whitelist_function(\"longfi_new_handle\")\n\n .whitelist_function(\"longfi_handle_event\")\n\n .whitelist_function(\"longfi_send\")\n\n .whitelist_function(\"longfi_get_rx\")\n\n .whitelist_function(\"longfi_set_buf\")\n\n .whitelist_function(\"longfi_rf_test\")\n\n .whitelist_function(\"longfi_get_random\")\n\n .whitelist_function(\"longfi_enable_tcxo\")\n\n .whitelist_function(\"board_set_bindings\")\n\n .whitelist_function(\"memcpy1\")\n\n .whitelist_function(\"SX1276RadioNew\")\n", "file_path": "longfi-sys/build.rs", "rank": 15, "score": 16763.903525329537 }, { "content": " .whitelist_function(\"SX126xRadioNew\")\n\n .whitelist_function(\"SX126xReadRegister\")\n\n .trust_clang_mangling(false)\n\n .rustfmt_bindings(true)\n\n .rustified_enum(\"ClientEvent_t\")\n\n .rustified_enum(\"RfEvent_t\")\n\n .rustified_enum(\"QualityOfService_t\")\n\n .rustified_enum(\"AntPinsMode_t\")\n\n .rustified_enum(\"LongFiAuthMode_t\")\n\n .derive_copy(false)\n\n .derive_debug(false)\n\n .layout_tests(false)\n\n .generate()\n\n .expect(\"Failed to generate sx1276 bindings!\");\n\n\n\n let out_path = PathBuf::from(env::var(\"OUT_DIR\").unwrap());\n\n bindings\n\n .write_to_file(out_path.join(\"bindings.rs\"))\n\n .expect(\"Couldn't write bindings!\");\n\n}\n\n\n", "file_path": "longfi-sys/build.rs", "rank": 16, "score": 16763.28232079036 }, { "content": "#[cfg(workaround_build)]\n", "file_path": "longfi-sys/build.rs", "rank": 17, "score": 16754.729134917987 }, { "content": "#![allow(non_upper_case_globals)]\n\n#![allow(non_camel_case_types)]\n\n#![allow(non_snake_case)]\n\n#![allow(clippy::all)]\n\n#![cfg_attr(not(test), no_std)]\n\n\n\ninclude!(concat!(env!(\"OUT_DIR\"), \"/bindings.rs\"));", "file_path": "longfi-sys/src/lib.rs", "rank": 18, "score": 15821.199156526407 }, { "content": "<!--\n\nM.m.p (YYYY-MM-DD)\n\n==================\n\nAdd a summary of this release.\n\n\n\n**BREAKING CHANGES**:\n\n\n\n* Some change which breaks API or ABI compatiblity with.\n\n\n\n\n\nFeature enhancements:\n\n\n\n* [Link to github PR]():\n\n A new feature.\n\n\n\nBug fixes:\n\n\n\n* [Link to github PR]():\n\n A bugfix.\n\n-->\n\n0.1.2 (2019-11-26)\n\n==================\n\n* [Workaround for SX126x](https://github.com/helium/longfi-device/pull/26)\n\nBump longfi-device submodule to allow SX126x to work\n\n* [Include only used radio in binary output](https://github.com/helium/longfi-device-rs/pull/23)\n\nAPI is changed so that its easier for rustc to only include relevant radio\n\n\n\n\n\n0.1.1 (2019-11-13)\n\n==================\n\nFixed bug where fingerprints failed due to memory misalignment with C bindings\n\n\n\n0.1.0 (2019-10-28)\n\n==================\n\nInitial release.\n", "file_path": "CHANGELOG.md", "rank": 19, "score": 10159.858949739053 }, { "content": "# longfi-device-rs\n\n[![Build Status](https://travis-ci.com/helium/longfi-device.svg?token=35YrBmyVB8LNrXzjrRop&branch=master)](https://travis-ci.com/helium/longfi-device-rs)\n\n\n\n## Summary\n\n\n\nThis project creates Rust bindings for the [LongFi Protocol C-library](https://github.com/helium/longfi-device).\n\n\n\n## Cloning, building, testing\n\n\n\nThis project contains the LongFi Protocol C-library as a submodule, so either clone the whole repo and submodules with one command:\n\n\t`git clone --recurse-submodules [email protected]:helium/longfi-device-rs.git`\n\n\n\nOr, if you've already cloned the top level without submodules, get the submodule:\n\n\t`git submodule update --init --recursive`\n\n\n\nYou can use cargo to build:\n\n\t`cargo build [--release]`\n\n\n\nThe configuration in `.cargo/config` is configured to build only for the `thumbv6m-none-eabi` platform currently.\n\n\n\nThe code in the example directory is for the [STM32L0 Discovery kit](https://www.st.com/en/evaluation-tools/b-l072z-lrwan1.html), which features the [STM32L072CZ](https://www.st.com/en/microcontrollers-microprocessors/stm32l072cz.html).\n\n\n\nTo upload the code, start a debug server using either JLink (Note: [you can reprogram the ST-Link](https://www.segger.com/products/debug-probes/j-link/models/other-j-links/st-link-on-board/) on the discovery kit to act like a JLink Server; you will lose the virtual UART over USB provided by the ST-Link):\n\n\t`JLinkGDBServer -device STM32L072CZ -speed 4000 -if swd -AutoConnect -1 -port 3333`\n\n\n\nor OpenOCD server (Note: if you are using the OpenOCD server, you will want to update `.cargo/config:runner` to use `openocd.gdb` instead of `jlink.gdb`):\n\n\t`openocd -f ./openocd.cfg`\n\n\n\nrun the example:\n\n\t`cargo run --example stm32l0x2 [--release]`\n\n\n\nRun tests:\n\n `cargo test --target x86_64-unknown-linux-gnu --tests`\n\n\n\n## Debugging the build\n\n\n\nThe `.travis.yml` will provide the most up to date hints on how to build this repository. Notably, the following dependencies exist:\n\n\n\n`cmake doxygen xdot install g++-multilib libc6-dev-i386 gcc-arm-none-eabi libnewlib-arm-none-eabi`\n\n\n\nIn addition, be sure to install `clang` as that appears to resolve header issues in some systems.\n", "file_path": "README.md", "rank": 20, "score": 10158.246422227174 }, { "content": "# How to Contribute to this repository #\n\n\n\nWe value contributions from the community and will do everything we\n\ncan go get them reviewed in a timely fashion. If you have code to send\n\nour way or a bug to report:\n\n\n\n* **Contributing Code**: If you have new code or a bug fix, fork this\n\n repo, create a logically-named branch, and [submit a PR against this\n\n repo](https://github.com/helium/longfi-device-rs/pulls). Include a\n\n write up of the PR with details on what it does.\n\n\n\n* **Reporting Bugs**: Open an issue [against this\n\n repo](https://github.com/helium/longfi-device-rs/issues) with as much\n\n detail as you can. At the very least you'll include steps to\n\n reproduce the problem.\n\n\n\nThis project is intended to be a safe, welcoming space for\n\ncollaboration, and contributors are expected to adhere to the\n\n[Contributor Covenant Code of\n\nConduct](http://contributor-covenant.org/).\n\n\n\nAbove all, thank you for taking the time to be a part of the Helium community.\n", "file_path": "CONTRIBUTING.md", "rank": 21, "score": 10156.485663166908 }, { "content": " gpioa.pa7,\n\n gpioa.pa15,\n\n gpioc.pc0,\n\n gpioa.pa1,\n\n gpioc.pc2,\n\n gpioc.pc1,\n\n ));\n\n\n\n let rf_config = Config {\n\n oui: OUI,\n\n device_id: DEVICE_ID,\n\n auth_mode: longfi_device::AuthMode::PresharedKey128,\n\n };\n\n\n\n let mut longfi_radio;\n\n if let Some(bindings) = BINDINGS {\n\n longfi_radio = LongFi::new(\n\n Radio::sx1276(),\n\n &mut bindings.bindings,\n\n rf_config,\n", "file_path": "examples/stm32l0x2/main.rs", "rank": 28, "score": 14.010459004795058 }, { "content": " count: u8,\n\n longfi: LongFi,\n\n }\n\n\n\n #[init(spawn = [send_ping], resources = [buffer])]\n\n fn init(ctx: init::Context) -> init::LateResources {\n\n static mut BINDINGS: Option<LongFiBindings> = None;\n\n let device = ctx.device;\n\n let mut rcc = device.RCC.freeze(rcc::Config::hsi16());\n\n let mut syscfg = syscfg::SYSCFG::new(device.SYSCFG, &mut rcc);\n\n\n\n let gpioa = device.GPIOA.split(&mut rcc);\n\n let gpiob = device.GPIOB.split(&mut rcc);\n\n let gpioc = device.GPIOC.split(&mut rcc);\n\n\n\n let (tx_pin, rx_pin, serial_peripheral) = (gpioa.pa2, gpioa.pa3, device.USART2);\n\n\n\n let mut serial = serial_peripheral\n\n .usart((tx_pin, rx_pin), serial::Config::default(), &mut rcc)\n\n .unwrap();\n", "file_path": "examples/stm32l0x2/main.rs", "rank": 30, "score": 12.075864097026022 }, { "content": "#![cfg_attr(not(test), no_std)]\n\n#![no_main]\n\n\n\n// To use example, press any key in serial terminal\n\n// Packet will send and \"Transmit Done!\" will print when radio is done sending packet\n\n\n\nextern crate nb;\n\nextern crate panic_halt;\n\n\n\nuse core::fmt::Write;\n\nuse hal::exti::{ExtiLine, GpioLine};\n\nuse hal::serial::USART2 as DebugUsart;\n\nuse hal::{exti::Exti, prelude::*, rcc, rng::Rng, serial, syscfg};\n\nuse longfi_device;\n\nuse longfi_device::{ClientEvent, Config, LongFi, Radio, RfEvent};\n\nuse rtfm::app;\n\nuse stm32l0xx_hal as hal;\n\n\n\nmod longfi_bindings;\n\npub use longfi_bindings::initialize_irq as initialize_radio_irq;\n", "file_path": "examples/stm32l0x2/main.rs", "rank": 31, "score": 11.8857631971435 }, { "content": "pub use longfi_bindings::LongFiBindings;\n\npub use longfi_bindings::RadioIRQ;\n\npub use longfi_bindings::TcxoEn;\n\n\n\nconst OUI: u32 = 1;\n\nconst DEVICE_ID: u16 = 3;\n\nconst PRESHARED_KEY: [u8; 16] = [\n\n 0x7B, 0x60, 0xC0, 0xF0, 0x77, 0x51, 0x50, 0xD3, 0x2, 0xCE, 0xAE, 0x50, 0xA0, 0xD2, 0x11, 0xC1,\n\n];\n\n\n\n#[app(device = stm32l0xx_hal::pac, peripherals = true)]\n\nconst APP: () = {\n\n struct Resources {\n\n int: Exti,\n\n radio_irq: RadioIRQ,\n\n debug_uart: serial::Tx<DebugUsart>,\n\n uart_rx: serial::Rx<DebugUsart>,\n\n #[init([0;512])]\n\n buffer: [u8; 512],\n\n #[init(0)]\n", "file_path": "examples/stm32l0x2/main.rs", "rank": 32, "score": 11.831859887137517 }, { "content": " }\n\n write!(debug, \"\\r\\n\").unwrap();\n\n }\n\n // give buffer back to library\n\n longfi_radio.set_buffer(ctx.resources.buffer);\n\n }\n\n ClientEvent::ClientEvent_None => {}\n\n }\n\n }\n\n\n\n #[task(capacity = 4, priority = 2, resources = [debug_uart, count, longfi])]\n\n fn send_ping(ctx: send_ping::Context) {\n\n write!(ctx.resources.debug_uart, \"Sending Ping\\r\\n\").unwrap();\n\n let packet: [u8; 5] = [0xDE, 0xAD, 0xBE, 0xEF, *ctx.resources.count];\n\n *ctx.resources.count += 1;\n\n ctx.resources.longfi.send(&packet);\n\n }\n\n\n\n #[task(binds = USART2, priority=1, resources = [uart_rx], spawn = [send_ping])]\n\n fn USART2(ctx: USART2::Context) {\n", "file_path": "examples/stm32l0x2/main.rs", "rank": 35, "score": 9.22257017003065 }, { "content": " let rx = ctx.resources.uart_rx;\n\n rx.read().unwrap();\n\n ctx.spawn.send_ping().unwrap();\n\n }\n\n\n\n #[task(binds = EXTI4_15, priority = 1, resources = [radio_irq, int], spawn = [radio_event])]\n\n fn EXTI4_15(ctx: EXTI4_15::Context) {\n\n Exti::unpend(GpioLine::from_raw_line(ctx.resources.radio_irq.pin_number()).unwrap());\n\n ctx.spawn.radio_event(RfEvent::DIO0).unwrap();\n\n }\n\n\n\n // Interrupt handlers used to dispatch software tasks\n\n extern \"C\" {\n\n fn USART4_USART5();\n\n }\n\n};\n", "file_path": "examples/stm32l0x2/main.rs", "rank": 36, "score": 7.665330387851416 }, { "content": "\n\n // listen for incoming bytes which will trigger transmits\n\n serial.listen(serial::Event::Rxne);\n\n let (mut tx, rx) = serial.split();\n\n\n\n write!(tx, \"LongFi Device Test\\r\\n\").unwrap();\n\n\n\n let mut exti = Exti::new(device.EXTI);\n\n // constructor initializes 48 MHz clock that RNG requires\n\n // Initialize 48 MHz clock and RNG\n\n let hsi48 = rcc.enable_hsi48(&mut syscfg, device.CRS);\n\n let rng = Rng::new(device.RNG, &mut rcc, hsi48);\n\n let radio_irq = initialize_radio_irq(gpiob.pb4, &mut syscfg, &mut exti);\n\n\n\n *BINDINGS = Some(LongFiBindings::new(\n\n device.SPI1,\n\n &mut rcc,\n\n rng,\n\n gpiob.pb3,\n\n gpioa.pa6,\n", "file_path": "examples/stm32l0x2/main.rs", "rank": 37, "score": 7.519191416544509 }, { "content": " &PRESHARED_KEY,\n\n )\n\n .unwrap()\n\n } else {\n\n panic!(\"No bindings exist\");\n\n }\n\n\n\n longfi_radio.set_buffer(ctx.resources.buffer);\n\n\n\n write!(tx, \"Going to main loop\\r\\n\").unwrap();\n\n\n\n // Return the initialised resources.\n\n init::LateResources {\n\n int: exti,\n\n radio_irq: radio_irq,\n\n debug_uart: tx,\n\n uart_rx: rx,\n\n longfi: longfi_radio,\n\n }\n\n }\n", "file_path": "examples/stm32l0x2/main.rs", "rank": 40, "score": 6.018540052101624 }, { "content": "\n\n #[task(capacity = 4, priority = 2, resources = [debug_uart, buffer, longfi])]\n\n fn radio_event(ctx: radio_event::Context, event: RfEvent) {\n\n let longfi_radio = ctx.resources.longfi;\n\n let client_event = longfi_radio.handle_event(event);\n\n let debug = ctx.resources.debug_uart;\n\n match client_event {\n\n ClientEvent::ClientEvent_TxDone => {\n\n write!(debug, \"Transmit Done!\\r\\n\").unwrap();\n\n }\n\n ClientEvent::ClientEvent_Rx => {\n\n // get receive buffer\n\n let rx_packet = longfi_radio.get_rx();\n\n write!(debug, \"Received packet\\r\\n\").unwrap();\n\n write!(debug, \" Length = {}\\r\\n\", rx_packet.len).unwrap();\n\n write!(debug, \" Rssi = {}\\r\\n\", rx_packet.rssi).unwrap();\n\n write!(debug, \" Snr = {}\\r\\n\", rx_packet.snr).unwrap();\n\n unsafe {\n\n for i in 0..rx_packet.len {\n\n write!(debug, \"{:X} \", *rx_packet.buf.offset(i as isize)).unwrap();\n", "file_path": "examples/stm32l0x2/main.rs", "rank": 41, "score": 5.1709385034571085 } ]
Rust
src/dft/mod.rs
feos-org/feos-gc-pcsaft
4ce900cab46848a4f6352432d6d23c8f1fda5b6b
use crate::eos::GcPcSaftOptions; use feos_core::MolarWeight; use feos_dft::adsorption::FluidParameters; use feos_dft::fundamental_measure_theory::{FMTContribution, FMTProperties, FMTVersion}; use feos_dft::{FunctionalContribution, HelmholtzEnergyFunctional, MoleculeShape, DFT}; use ndarray::Array1; use num_dual::DualNum; use petgraph::graph::UnGraph; use quantity::si::{SIArray1, SIUnit, GRAM, MOL}; use std::f64::consts::FRAC_PI_6; use std::rc::Rc; mod association; mod dispersion; mod hard_chain; mod parameter; use association::AssociationFunctional; use dispersion::AttractiveFunctional; use hard_chain::ChainFunctional; pub use parameter::GcPcSaftFunctionalParameters; pub struct GcPcSaftFunctional { pub parameters: Rc<GcPcSaftFunctionalParameters>, fmt_version: FMTVersion, options: GcPcSaftOptions, contributions: Vec<Box<dyn FunctionalContribution>>, } impl GcPcSaftFunctional { pub fn new(parameters: Rc<GcPcSaftFunctionalParameters>) -> DFT<Self> { Self::with_options( parameters, FMTVersion::WhiteBear, GcPcSaftOptions::default(), ) } pub fn with_options( parameters: Rc<GcPcSaftFunctionalParameters>, fmt_version: FMTVersion, saft_options: GcPcSaftOptions, ) -> DFT<Self> { let mut contributions: Vec<Box<dyn FunctionalContribution>> = Vec::with_capacity(4); let hs = FMTContribution::new(&parameters, fmt_version); contributions.push(Box::new(hs)); let chain = ChainFunctional::new(&parameters); contributions.push(Box::new(chain)); let att = AttractiveFunctional::new(&parameters); contributions.push(Box::new(att)); if !parameters.assoc_segment.is_empty() { let assoc = AssociationFunctional::new( &parameters, saft_options.max_iter_cross_assoc, saft_options.tol_cross_assoc, ); contributions.push(Box::new(assoc)); } (Self { parameters, fmt_version, options: saft_options, contributions, }) .into() } } impl HelmholtzEnergyFunctional for GcPcSaftFunctional { fn molecule_shape(&self) -> MoleculeShape { MoleculeShape::Heterosegmented(&self.parameters.component_index) } fn subset(&self, component_list: &[usize]) -> DFT<Self> { Self::with_options( Rc::new(self.parameters.subset(component_list)), self.fmt_version, self.options, ) } fn compute_max_density(&self, moles: &Array1<f64>) -> f64 { let p = &self.parameters; let moles_segments: Array1<f64> = p.component_index.iter().map(|&i| moles[i]).collect(); self.options.max_eta * moles.sum() / (FRAC_PI_6 * &p.m * p.sigma.mapv(|v| v.powi(3)) * moles_segments).sum() } fn contributions(&self) -> &[Box<dyn FunctionalContribution>] { &self.contributions } fn bond_lengths(&self, temperature: f64) -> UnGraph<(), f64> { let d = self.parameters.hs_diameter(temperature); self.parameters.bonds.map( |_, _| (), |e, _| { let (i, j) = self.parameters.bonds.edge_endpoints(e).unwrap(); let di = d[i.index()]; let dj = d[j.index()]; 0.5 * (di + dj) }, ) } } impl MolarWeight<SIUnit> for GcPcSaftFunctional { fn molar_weight(&self) -> SIArray1 { self.parameters.molarweight.clone() * GRAM / MOL } } impl FMTProperties for GcPcSaftFunctionalParameters { fn component_index(&self) -> Array1<usize> { self.component_index.clone() } fn chain_length(&self) -> Array1<f64> { self.m.clone() } fn hs_diameter<D: DualNum<f64>>(&self, temperature: D) -> Array1<D> { self.hs_diameter(temperature) } } impl FluidParameters for GcPcSaftFunctional { fn epsilon_k_ff(&self) -> Array1<f64> { self.parameters.epsilon_k.clone() } fn sigma_ff(&self) -> &Array1<f64> { &self.parameters.sigma } }
use crate::eos::GcPcSaftOptions; use feos_core::MolarWeight; use feos_dft::adsorption::FluidParameters; use feos_dft::fundamental_measure_theory::{FMTContribution, FMTProperties, FMTVersion}; use feos_dft::{FunctionalContribution, HelmholtzEnergyFunctional, MoleculeShape, DFT}; use ndarray::Array1; use num_dual::DualNum; use petgraph::graph::UnGraph; use quantity::si::{SIArray1, SIUnit, GRAM, MOL}; use std::f64::consts::FRAC_PI_6; use std::rc::Rc; mod association; mod dispersion; mod hard_chain; mod parameter; use association::AssociationFunctional; use dispersion::AttractiveFunctional; use hard_chain::ChainFunctional; pub use parameter::GcPcSaftFunctionalParameters; pub struct GcPcSaftFunctional { pub parameters: Rc<GcPcSaftFunctionalParameters>, fmt_version: FMTVersion, options: GcPcSaftOptions, contributions: Vec<Box<dyn FunctionalContribution>>, } impl GcPcSaftFunctional { pub fn new(parameters: Rc<GcPcSaftFunctionalParameters>) -> DFT<Self> { Self::with_options( parameters, FMTVersion::WhiteBear, GcPcSaftOptions::default(), ) } pub fn with_options( parameters: Rc<GcPcSaftFunctionalParameters>, fmt_version: FMTVersion, saft_options: GcPcSaftOptions, ) -> DFT<Self> { let mut contributions: Vec<Box<dyn FunctionalContribution>> = Vec::with_capacity(4); let hs = FMTContribution::new(&parameters, fmt_version); contributions.push(Box::new(hs)); let chain = ChainFunctional::new(&parameters); contributions.push(Box::new(chain)); let att = AttractiveFunctional::new(&parameters); contributions.push(Box::new(att)); if !parameters.assoc_segment.is_empty() { let assoc = AssociationFunctional::new( &parameters, saft_options.max_iter_cross_assoc, saft_options.tol_cross_assoc, ); contributions.push(Box::new(assoc)); } (Self { parameters, fmt_version, options: saft_options, contributions, }) .into() } } impl HelmholtzEnergyFunctional for GcPcSaftFunctional { fn molecule_shape(&self) -> MoleculeShape { MoleculeShape::Heterosegmented(&self.parameters.component_index) }
fn compute_max_density(&self, moles: &Array1<f64>) -> f64 { let p = &self.parameters; let moles_segments: Array1<f64> = p.component_index.iter().map(|&i| moles[i]).collect(); self.options.max_eta * moles.sum() / (FRAC_PI_6 * &p.m * p.sigma.mapv(|v| v.powi(3)) * moles_segments).sum() } fn contributions(&self) -> &[Box<dyn FunctionalContribution>] { &self.contributions } fn bond_lengths(&self, temperature: f64) -> UnGraph<(), f64> { let d = self.parameters.hs_diameter(temperature); self.parameters.bonds.map( |_, _| (), |e, _| { let (i, j) = self.parameters.bonds.edge_endpoints(e).unwrap(); let di = d[i.index()]; let dj = d[j.index()]; 0.5 * (di + dj) }, ) } } impl MolarWeight<SIUnit> for GcPcSaftFunctional { fn molar_weight(&self) -> SIArray1 { self.parameters.molarweight.clone() * GRAM / MOL } } impl FMTProperties for GcPcSaftFunctionalParameters { fn component_index(&self) -> Array1<usize> { self.component_index.clone() } fn chain_length(&self) -> Array1<f64> { self.m.clone() } fn hs_diameter<D: DualNum<f64>>(&self, temperature: D) -> Array1<D> { self.hs_diameter(temperature) } } impl FluidParameters for GcPcSaftFunctional { fn epsilon_k_ff(&self) -> Array1<f64> { self.parameters.epsilon_k.clone() } fn sigma_ff(&self) -> &Array1<f64> { &self.parameters.sigma } }
fn subset(&self, component_list: &[usize]) -> DFT<Self> { Self::with_options( Rc::new(self.parameters.subset(component_list)), self.fmt_version, self.options, ) }
function_block-full_function
[ { "content": "#[pymodule]\n\npub fn dft(_py: Python<'_>, m: &PyModule) -> PyResult<()> {\n\n m.add_class::<PyGcPcSaftFunctional>()?;\n\n m.add_class::<PyState>()?;\n\n m.add_class::<PyPhaseDiagram>()?;\n\n m.add_class::<PyPhaseEquilibrium>()?;\n\n m.add_class::<PyPlanarInterface>()?;\n\n m.add_class::<Geometry>()?;\n\n m.add_class::<PyPore1D>()?;\n\n m.add_class::<PyPore3D>()?;\n\n m.add_class::<PyExternalPotential>()?;\n\n m.add_class::<PyAdsorption1D>()?;\n\n m.add_class::<PyAdsorption3D>()?;\n\n m.add_class::<PySurfaceTensionDiagram>()?;\n\n m.add_class::<PyDFTSolver>()?;\n\n m.add_class::<PySolvationProfile>()?;\n\n m.add_class::<FMTVersion>()?;\n\n m.add_class::<PyMicelleProfile>()?;\n\n Ok(())\n\n}\n", "file_path": "build_wheel/src/dft.rs", "rank": 0, "score": 92379.61473575173 }, { "content": "#[test]\n\n#[allow(non_snake_case)]\n\nfn test_dft_assoc() -> Result<(), Box<dyn Error>> {\n\n let parameters = GcPcSaftFunctionalParameters::from_json_segments(\n\n &[\"1-pentanol\"],\n\n \"parameters/gc_substances.json\",\n\n \"parameters/sauer2014_hetero.json\",\n\n None,\n\n IdentifierOption::Name,\n\n )\n\n .unwrap();\n\n\n\n let func = Rc::new(GcPcSaftFunctional::new(Rc::new(parameters)));\n\n let t = 300.0 * KELVIN;\n\n let w = 100.0 * ANGSTROM;\n\n let points = 4096;\n\n let vle = PhaseEquilibrium::pure(&func, t, None, Default::default())?;\n\n let profile = PlanarInterface::from_tanh(&vle, points, w, 600.0 * KELVIN)?.solve(None)?;\n\n println!(\n\n \"hetero {} {} {}\",\n\n profile.surface_tension.unwrap(),\n\n vle.vapor().density,\n", "file_path": "tests/dft.rs", "rank": 1, "score": 79656.25002901137 }, { "content": "pub fn helmholtz_energy_density_cross_association<S, D: DualNum<f64> + ScalarOperand>(\n\n // p: &GcPcSaftParameters<B>,\n\n assoc_segment: &Array1<usize>,\n\n sigma3_kappa_aibj: &Array2<f64>,\n\n epsilon_k_aibj: &Array2<f64>,\n\n na: &Array1<f64>,\n\n nb: &Array1<f64>,\n\n temperature: D,\n\n density: &ArrayBase<S, Ix1>,\n\n diameter: &Array1<D>,\n\n n2: D,\n\n n3i: D,\n\n xi: D,\n\n max_iter: usize,\n\n tol: f64,\n\n x0: Option<&mut Array1<f64>>,\n\n) -> Result<D, EosError>\n\nwhere\n\n S: Data<Elem = D>,\n\n{\n", "file_path": "src/eos/association.rs", "rank": 2, "score": 75762.02849625803 }, { "content": "#[test]\n\n#[allow(non_snake_case)]\n\nfn test_dft() -> Result<(), Box<dyn Error>> {\n\n // correct for different k_B in old code\n\n let KB_old = 1.38064852e-23 * JOULE / KELVIN;\n\n let NAV_old = 6.022140857e23 / MOL;\n\n\n\n let parameters = GcPcSaftFunctionalParameters::from_json_segments(\n\n &[\"propane\"],\n\n \"parameters/gc_substances.json\",\n\n \"parameters/sauer2014_hetero.json\",\n\n None,\n\n IdentifierOption::Name,\n\n )\n\n .unwrap();\n\n\n\n let func = Rc::new(GcPcSaftFunctional::new(Rc::new(parameters)));\n\n let t = 200.0 * KELVIN;\n\n let w = 150.0 * ANGSTROM;\n\n let points = 2048;\n\n let tc = State::critical_point(&func, None, None, Default::default())?.temperature;\n\n let vle = PhaseEquilibrium::pure(&func, t, None, Default::default())?;\n", "file_path": "tests/dft.rs", "rank": 3, "score": 60265.56126956189 }, { "content": "fn association_strength<D: DualNum<f64>>(\n\n assoc_segment: &Array1<usize>,\n\n sigma3_kappa_aibj: &Array2<f64>,\n\n epsilon_k_aibj: &Array2<f64>,\n\n temperature: D,\n\n diameter: &Array1<D>,\n\n n2: D,\n\n n3i: D,\n\n xi: D,\n\n i: usize,\n\n j: usize,\n\n) -> D {\n\n let ai = assoc_segment[i];\n\n let aj = assoc_segment[j];\n\n let k = diameter[ai] * diameter[aj] / (diameter[ai] + diameter[aj]) * (n2 * n3i);\n\n n3i * (k * xi * (k / 18.0 + 0.5) + 1.0)\n\n * sigma3_kappa_aibj[(i, j)]\n\n * (temperature.recip() * epsilon_k_aibj[(i, j)]).exp_m1()\n\n}\n\n\n", "file_path": "src/eos/association.rs", "rank": 4, "score": 60265.02538949664 }, { "content": "#[pymodule]\n\npub fn eos(_py: Python<'_>, m: &PyModule) -> PyResult<()> {\n\n m.add_class::<PyGcPcSaft>()?;\n\n m.add_class::<PyState>()?;\n\n m.add_class::<PyPhaseDiagram>()?;\n\n m.add_class::<PyPhaseEquilibrium>()?;\n\n Ok(())\n\n}\n", "file_path": "build_wheel/src/eos.rs", "rank": 5, "score": 55469.1140607223 }, { "content": "use super::parameter::GcPcSaftFunctionalParameters;\n\nuse crate::eos::association::{\n\n assoc_site_frac_a, assoc_site_frac_ab, helmholtz_energy_density_cross_association,\n\n};\n\nuse feos_core::EosError;\n\nuse feos_dft::{\n\n FunctionalContributionDual, WeightFunction, WeightFunctionInfo, WeightFunctionShape,\n\n};\n\nuse ndarray::*;\n\nuse num_dual::DualNum;\n\nuse std::f64::consts::PI;\n\nuse std::fmt;\n\nuse std::ops::MulAssign;\n\nuse std::rc::Rc;\n\n\n\npub const N0_CUTOFF: f64 = 1e-9;\n\n\n\n#[derive(Clone)]\n\npub struct AssociationFunctional {\n\n parameters: Rc<GcPcSaftFunctionalParameters>,\n", "file_path": "src/dft/association.rs", "rank": 13, "score": 54453.0327986033 }, { "content": " max_iter: usize,\n\n tol: f64,\n\n}\n\n\n\nimpl AssociationFunctional {\n\n pub fn new(parameters: &Rc<GcPcSaftFunctionalParameters>, max_iter: usize, tol: f64) -> Self {\n\n Self {\n\n parameters: parameters.clone(),\n\n max_iter,\n\n tol,\n\n }\n\n }\n\n}\n\n\n\nimpl<N> FunctionalContributionDual<N> for AssociationFunctional\n\nwhere\n\n N: DualNum<f64> + ScalarOperand,\n\n{\n\n fn weight_functions(&self, temperature: N) -> WeightFunctionInfo<N> {\n\n let p = &self.parameters;\n", "file_path": "src/dft/association.rs", "rank": 14, "score": 54451.02118077254 }, { "content": " xi,\n\n self.max_iter,\n\n self.tol,\n\n Some(&mut x),\n\n )\n\n })\n\n .collect::<Result<Array1<N>, _>>()?\n\n .into_shape(n2.raw_dim())\n\n .unwrap())\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Display for AssociationFunctional {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"Association functional\")\n\n }\n\n}\n", "file_path": "src/dft/association.rs", "rank": 15, "score": 54444.12524107605 }, { "content": " * ((temperature.recip() * p.epsilon_k_aibj[(0, 0)]).exp_m1()\n\n * p.sigma3_kappa_aibj[(0, 0)])\n\n * rho0.index_axis(Axis(0), 0);\n\n\n\n let na = p.na[0];\n\n let nb = p.nb[0];\n\n let f = |x: N| x.ln() - x * 0.5 + 0.5;\n\n if nb > 0.0 {\n\n // no cross association, two association sites\n\n let xa = deltarho.mapv(|d| assoc_site_frac_ab(d, na, nb));\n\n let xb = (&xa - 1.0) * (na / nb) + 1.0;\n\n Ok((xa.mapv(f) * na + xb.mapv(f) * nb) * rho0.index_axis(Axis(0), 0))\n\n } else {\n\n // no cross association, one association site\n\n let xa = deltarho.mapv(|d| assoc_site_frac_a(d, na));\n\n\n\n Ok(xa.mapv(f) * na * rho0.index_axis(Axis(0), 0))\n\n }\n\n } else {\n\n let mut x: Array1<f64> = Array::from_elem(2 * nassoc, 0.2);\n", "file_path": "src/dft/association.rs", "rank": 16, "score": 54442.35295510072 }, { "content": " // weighted densities\n\n let n0i = weighted_densities.slice_axis(Axis(0), Slice::new(0, Some(segments as isize), 1));\n\n let n2vi: Vec<_> = (0..dim)\n\n .map(|i| {\n\n weighted_densities.slice_axis(\n\n Axis(0),\n\n Slice::new(\n\n (segments * (i + 1)) as isize,\n\n Some((segments * (i + 2)) as isize),\n\n 1,\n\n ),\n\n )\n\n })\n\n .collect();\n\n let n3 = weighted_densities.index_axis(Axis(0), segments * (dim + 1));\n\n\n\n // calculate rho0 (only associating segments)\n\n let diameter = p.hs_diameter(temperature);\n\n let mut n2i = n0i.to_owned();\n\n for (i, mut n2i) in n2i.outer_iter_mut().enumerate() {\n", "file_path": "src/dft/association.rs", "rank": 17, "score": 54442.079646429294 }, { "content": " true,\n\n )\n\n }\n\n\n\n fn calculate_helmholtz_energy_density(\n\n &self,\n\n temperature: N,\n\n weighted_densities: ArrayView2<N>,\n\n ) -> Result<Array1<N>, EosError> {\n\n let p = &self.parameters;\n\n\n\n // number of segments\n\n let segments = p.m.len();\n\n\n\n // number of associating segments\n\n let nassoc = p.assoc_segment.len();\n\n\n\n // number of dimensions\n\n let dim = (weighted_densities.shape()[0] - 1) / segments - 1;\n\n\n", "file_path": "src/dft/association.rs", "rank": 18, "score": 54441.759394945184 }, { "content": " .iter()\n\n .fold(Array::zeros(n2.raw_dim()), |acc, n2v| acc + n2v * n2v)\n\n / -(&n2 * &n2)\n\n + 1.0;\n\n xi.iter_mut()\n\n .zip(&n0i.sum_axis(Axis(0)))\n\n .for_each(|(xi, &n0i)| {\n\n if n0i.re() < N0_CUTOFF {\n\n *xi = N::one();\n\n }\n\n });\n\n\n\n // auxiliary variables\n\n let n3i = n3.mapv(|n3| (-n3 + 1.0).recip());\n\n\n\n // only one associating component\n\n if nassoc == 1 {\n\n // association strength\n\n let k = &n2 * &n3i * diameter[p.assoc_segment[0]] * 0.5;\n\n let deltarho = (((&k / 18.0 + 0.5) * &k * xi + 1.0) * n3i)\n", "file_path": "src/dft/association.rs", "rank": 19, "score": 54441.695990026354 }, { "content": " n2i.mul_assign(diameter[i].powi(2) * p.m[i] * PI);\n\n }\n\n let mut rho0: Array2<N> = (n2vi\n\n .iter()\n\n .fold(Array2::zeros(n2i.raw_dim()), |acc, n2vi| acc + n2vi * n2vi)\n\n / -(&n2i * &n2i)\n\n + 1.0)\n\n * n0i;\n\n rho0.iter_mut().zip(&n0i).for_each(|(rho0, &n0i)| {\n\n if n0i.re() < N0_CUTOFF {\n\n *rho0 = n0i;\n\n }\n\n });\n\n let rho0 =\n\n Array2::from_shape_fn((nassoc, n3.len()), |(i, j)| rho0[(p.assoc_segment[i], j)]);\n\n\n\n // calculate xi\n\n let n2v: Vec<_> = n2vi.iter().map(|n2vi| n2vi.sum_axis(Axis(0))).collect();\n\n let n2 = n2i.sum_axis(Axis(0));\n\n let mut xi = n2v\n", "file_path": "src/dft/association.rs", "rank": 20, "score": 54441.40563712252 }, { "content": " Ok(rho0\n\n .view()\n\n .into_shape([nassoc, rho0.len() / nassoc])\n\n .unwrap()\n\n .axis_iter(Axis(1))\n\n .zip(n2.iter())\n\n .zip(n3i.iter())\n\n .zip(xi.iter())\n\n .map(|(((rho0, &n2), &n3i), &xi)| {\n\n helmholtz_energy_density_cross_association(\n\n &p.assoc_segment,\n\n &p.sigma3_kappa_aibj,\n\n &p.epsilon_k_aibj,\n\n &p.na,\n\n &p.nb,\n\n temperature,\n\n &rho0,\n\n &diameter,\n\n n2,\n\n n3i,\n", "file_path": "src/dft/association.rs", "rank": 21, "score": 54439.13860810976 }, { "content": " let r = p.hs_diameter(temperature) * 0.5;\n\n WeightFunctionInfo::new(p.component_index.clone(), false)\n\n .add(\n\n WeightFunction::new_scaled(r.clone(), WeightFunctionShape::Delta),\n\n false,\n\n )\n\n .add(\n\n WeightFunction {\n\n prefactor: p.m.mapv(N::from),\n\n kernel_radius: r.clone(),\n\n shape: WeightFunctionShape::DeltaVec,\n\n },\n\n false,\n\n )\n\n .add(\n\n WeightFunction {\n\n prefactor: p.m.mapv(N::from),\n\n kernel_radius: r,\n\n shape: WeightFunctionShape::Theta,\n\n },\n", "file_path": "src/dft/association.rs", "rank": 22, "score": 54436.85413702663 }, { "content": " binary_segment_records: Option<Vec<BinaryRecord<String, f64>>>,\n\n}\n\n\n\nimpl GcPcSaftFunctionalParameters {\n\n pub fn from_segments(\n\n chemical_records: Vec<ChemicalRecord>,\n\n segment_records: Vec<SegmentRecord<GcPcSaftRecord, JobackRecord>>,\n\n binary_segment_records: Option<Vec<BinaryRecord<String, f64>>>,\n\n ) -> Result<Self, ParameterError> {\n\n let segment_map: IndexMap<_, _> = segment_records\n\n .iter()\n\n .map(|r| (r.identifier.clone(), r.clone()))\n\n .collect();\n\n\n\n let mut molarweight = Array1::zeros(chemical_records.len());\n\n let mut component_index = Vec::new();\n\n let mut identifiers = Vec::new();\n\n let mut m = Vec::new();\n\n let mut sigma = Vec::new();\n\n let mut epsilon_k = Vec::new();\n", "file_path": "src/dft/parameter.rs", "rank": 23, "score": 53991.1806523264 }, { "content": "use crate::record::GcPcSaftRecord;\n\nuse feos_core::joback::JobackRecord;\n\nuse feos_core::parameter::{\n\n BinaryRecord, ChemicalRecord, IdentifierOption, ParameterError, SegmentRecord,\n\n};\n\nuse indexmap::{IndexMap, IndexSet};\n\nuse ndarray::{Array1, Array2};\n\nuse num_dual::DualNum;\n\nuse petgraph::dot::{Config, Dot};\n\nuse petgraph::graph::{Graph, UnGraph};\n\nuse std::fmt::Write;\n\nuse std::fs::File;\n\nuse std::io::BufReader;\n\nuse std::path::Path;\n\n\n\n/// psi Parameter for heterosegmented DFT (Mairhofer2018)\n\nconst PSI_GC_DFT: f64 = 1.5357;\n\n\n\n/// Parameter set required for the gc-PC-SAFT Helmholtz energy functional.\n\npub struct GcPcSaftFunctionalParameters {\n", "file_path": "src/dft/parameter.rs", "rank": 24, "score": 53990.88141222919 }, { "content": " chemical_records,\n\n self.segment_records.clone(),\n\n self.binary_segment_records.clone(),\n\n )\n\n .unwrap()\n\n }\n\n\n\n pub fn hs_diameter<D: DualNum<f64>>(&self, temperature: D) -> Array1<D> {\n\n let ti = temperature.recip() * -3.0;\n\n Array1::from_shape_fn(self.sigma.len(), |i| {\n\n -((ti * self.epsilon_k[i]).exp() * 0.12 - 1.0) * self.sigma[i]\n\n })\n\n }\n\n\n\n pub fn to_markdown(&self) -> String {\n\n let mut output = String::new();\n\n let o = &mut output;\n\n write!(\n\n o,\n\n \"|component|molarweight|segment|$m$|$\\\\sigma$|$\\\\varepsilon$|$\\\\kappa_{{AB}}$|$\\\\varepsilon_{{AB}}$|$N_A$|$N_B$|\\n|-|-|-|-|-|-|-|-|-|-|\"\n", "file_path": "src/dft/parameter.rs", "rank": 25, "score": 53987.992184617055 }, { "content": " // Association\n\n let sigma3_kappa_aibj = Array2::from_shape_fn([kappa_ab.len(); 2], |(i, j)| {\n\n (sigma[assoc_segment[i]] * sigma[assoc_segment[j]]).powf(1.5)\n\n * (kappa_ab[i] * kappa_ab[j]).sqrt()\n\n });\n\n let epsilon_k_aibj = Array2::from_shape_fn([epsilon_k_ab.len(); 2], |(i, j)| {\n\n 0.5 * (epsilon_k_ab[i] + epsilon_k_ab[j])\n\n });\n\n\n\n Ok(Self {\n\n molarweight,\n\n component_index: Array1::from_vec(component_index),\n\n identifiers,\n\n m: Array1::from_vec(m),\n\n sigma: Array1::from_vec(sigma),\n\n epsilon_k: Array1::from_vec(epsilon_k),\n\n bonds,\n\n assoc_segment: Array1::from_vec(assoc_segment),\n\n kappa_ab: Array1::from_vec(kappa_ab),\n\n epsilon_k_ab: Array1::from_vec(epsilon_k_ab),\n", "file_path": "src/dft/parameter.rs", "rank": 26, "score": 53987.80421209468 }, { "content": " na: Array1::from_vec(na),\n\n nb: Array1::from_vec(nb),\n\n psi_dft: Array1::from_vec(psi_dft),\n\n k_ij,\n\n sigma_ij,\n\n epsilon_k_ij,\n\n sigma3_kappa_aibj,\n\n epsilon_k_aibj,\n\n chemical_records,\n\n segment_records,\n\n binary_segment_records,\n\n })\n\n }\n\n\n\n pub fn from_json_segments<P>(\n\n substances: &[&str],\n\n file_pure: P,\n\n file_segments: P,\n\n file_binary: Option<P>,\n\n search_option: IdentifierOption,\n", "file_path": "src/dft/parameter.rs", "rank": 27, "score": 53986.56216227673 }, { "content": " .map(|i, _| &self.identifiers[i.index()], |_, _| ());\n\n format!(\"{:?}\", Dot::with_config(&graph, &[Config::EdgeNoLabel]))\n\n }\n\n}\n\n\n\nimpl std::fmt::Display for GcPcSaftFunctionalParameters {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"GcPcSaftFunctionalParameters(\")?;\n\n write!(f, \"\\n\\tmolarweight={}\", self.molarweight)?;\n\n write!(f, \"\\n\\tcomponent_index={}\", self.component_index)?;\n\n write!(f, \"\\n\\tm={}\", self.m)?;\n\n write!(f, \"\\n\\tsigma={}\", self.sigma)?;\n\n write!(f, \"\\n\\tepsilon_k={}\", self.epsilon_k)?;\n\n write!(f, \"\\n\\tbonds={:?}\", self.bonds)?;\n\n if !self.assoc_segment.is_empty() {\n\n write!(f, \"\\n\\tassoc_segment={}\", self.assoc_segment)?;\n\n write!(f, \"\\n\\tkappa_ab={}\", self.kappa_ab)?;\n\n write!(f, \"\\n\\tepsilon_k_ab={}\", self.epsilon_k_ab)?;\n\n write!(f, \"\\n\\tna={}\", self.na)?;\n\n write!(f, \"\\n\\tnb={}\", self.nb)?;\n\n }\n\n write!(f, \"\\n)\")\n\n }\n\n}\n", "file_path": "src/dft/parameter.rs", "rank": 28, "score": 53986.40010662325 }, { "content": " ) -> Result<Self, ParameterError>\n\n where\n\n P: AsRef<Path>,\n\n {\n\n let queried: IndexSet<String> = substances\n\n .iter()\n\n .map(|identifier| identifier.to_string())\n\n .collect();\n\n\n\n let reader = BufReader::new(File::open(file_pure)?);\n\n let chemical_records: Vec<ChemicalRecord> = serde_json::from_reader(reader)?;\n\n let mut record_map: IndexMap<_, _> = chemical_records\n\n .into_iter()\n\n .filter_map(|record| {\n\n record\n\n .identifier()\n\n .as_string(search_option)\n\n .map(|i| (i, record))\n\n })\n\n .collect();\n", "file_path": "src/dft/parameter.rs", "rank": 29, "score": 53986.11514384723 }, { "content": " let mut bonds = Graph::default();\n\n let mut assoc_segment = Vec::new();\n\n let mut kappa_ab = Vec::new();\n\n let mut epsilon_k_ab = Vec::new();\n\n let mut na = Vec::new();\n\n let mut nb = Vec::new();\n\n let mut psi_dft = Vec::new();\n\n\n\n let mut segment_index = 0;\n\n for (i, chemical_record) in chemical_records.iter().enumerate() {\n\n let (segment_list, bond_list) = chemical_record.segment_and_bond_list()?;\n\n\n\n bonds.extend_with_edges(bond_list.iter().map(|x| {\n\n (\n\n (segment_index + x[0]) as u32,\n\n (segment_index + x[1]) as u32,\n\n (),\n\n )\n\n }));\n\n\n", "file_path": "src/dft/parameter.rs", "rank": 30, "score": 53986.05201892374 }, { "content": " pub molarweight: Array1<f64>,\n\n pub component_index: Array1<usize>,\n\n identifiers: Vec<String>,\n\n pub m: Array1<f64>,\n\n pub sigma: Array1<f64>,\n\n pub epsilon_k: Array1<f64>,\n\n pub bonds: UnGraph<(), ()>,\n\n pub assoc_segment: Array1<usize>,\n\n kappa_ab: Array1<f64>,\n\n epsilon_k_ab: Array1<f64>,\n\n pub na: Array1<f64>,\n\n pub nb: Array1<f64>,\n\n pub psi_dft: Array1<f64>,\n\n pub k_ij: Array2<f64>,\n\n pub sigma_ij: Array2<f64>,\n\n pub epsilon_k_ij: Array2<f64>,\n\n pub sigma3_kappa_aibj: Array2<f64>,\n\n pub epsilon_k_aibj: Array2<f64>,\n\n chemical_records: Vec<ChemicalRecord>,\n\n segment_records: Vec<SegmentRecord<GcPcSaftRecord, JobackRecord>>,\n", "file_path": "src/dft/parameter.rs", "rank": 31, "score": 53985.4602108594 }, { "content": " }\n\n\n\n psi_dft.push(segment.model_record.psi_dft.unwrap_or(PSI_GC_DFT));\n\n\n\n segment_index += 1;\n\n }\n\n }\n\n\n\n // Binary interaction parameter\n\n let mut k_ij = Array2::zeros([epsilon_k.len(); 2]);\n\n if let Some(binary_segment_records) = binary_segment_records.as_ref() {\n\n let mut binary_segment_records_map = IndexMap::new();\n\n for binary_record in binary_segment_records {\n\n binary_segment_records_map.insert(\n\n (binary_record.id1.clone(), binary_record.id2.clone()),\n\n binary_record.model_record,\n\n );\n\n binary_segment_records_map.insert(\n\n (binary_record.id2.clone(), binary_record.id1.clone()),\n\n binary_record.model_record,\n", "file_path": "src/dft/parameter.rs", "rank": 32, "score": 53985.277587457895 }, { "content": "\n\n // Read binary records\n\n let binary_records = file_binary\n\n .map(|file_binary| {\n\n let reader = BufReader::new(File::open(file_binary)?);\n\n let binary_records: Result<Vec<BinaryRecord<String, f64>>, ParameterError> =\n\n Ok(serde_json::from_reader(reader)?);\n\n binary_records\n\n })\n\n .transpose()?;\n\n\n\n Self::from_segments(chemical_records, segment_records, binary_records)\n\n }\n\n\n\n pub fn subset(&self, component_list: &[usize]) -> Self {\n\n let chemical_records: Vec<_> = component_list\n\n .iter()\n\n .map(|&i| self.chemical_records[i].clone())\n\n .collect();\n\n Self::from_segments(\n", "file_path": "src/dft/parameter.rs", "rank": 33, "score": 53985.008247188736 }, { "content": " };\n\n write!(\n\n o,\n\n \"\\n|{}|{}|{}|{}|{}|{}|||\",\n\n component,\n\n self.identifiers[i],\n\n self.m[i],\n\n self.sigma[i],\n\n self.epsilon_k[i],\n\n association\n\n )\n\n .unwrap();\n\n }\n\n\n\n output\n\n }\n\n\n\n pub fn graph(&self) -> String {\n\n let graph = self\n\n .bonds\n", "file_path": "src/dft/parameter.rs", "rank": 34, "score": 53984.4903039491 }, { "content": " )\n\n .unwrap();\n\n for i in 0..self.m.len() {\n\n let component = if i > 0 && self.component_index[i] == self.component_index[i - 1] {\n\n \"|\".to_string()\n\n } else {\n\n let pure = self.chemical_records[self.component_index[i]].identifier();\n\n format!(\n\n \"{}|{}\",\n\n pure.name.as_ref().unwrap_or(&pure.cas),\n\n self.molarweight[self.component_index[i]]\n\n )\n\n };\n\n let association = if let Some(a) = self.assoc_segment.iter().position(|&a| a == i) {\n\n format!(\n\n \"{}|{}|{}|{}\",\n\n self.kappa_ab[a], self.epsilon_k_ab[a], self.na[a], self.nb[a]\n\n )\n\n } else {\n\n \"|||\".to_string()\n", "file_path": "src/dft/parameter.rs", "rank": 35, "score": 53983.01526303481 }, { "content": " for id in segment_list {\n\n let segment = segment_map\n\n .get(id)\n\n .ok_or_else(|| ParameterError::ComponentsNotFound(id.to_string()))?;\n\n molarweight[i] += segment.molarweight;\n\n component_index.push(i);\n\n identifiers.push(id.clone());\n\n m.push(segment.model_record.m);\n\n sigma.push(segment.model_record.sigma);\n\n epsilon_k.push(segment.model_record.epsilon_k);\n\n\n\n if let (Some(k), Some(e)) = (\n\n segment.model_record.kappa_ab,\n\n segment.model_record.epsilon_k_ab,\n\n ) {\n\n assoc_segment.push(segment_index);\n\n kappa_ab.push(k);\n\n epsilon_k_ab.push(e);\n\n na.push(segment.model_record.na.unwrap_or(1.0));\n\n nb.push(segment.model_record.nb.unwrap_or(1.0));\n", "file_path": "src/dft/parameter.rs", "rank": 36, "score": 53981.47804219263 }, { "content": " );\n\n }\n\n for (i, id1) in identifiers.iter().enumerate() {\n\n for (j, id2) in identifiers.iter().cloned().enumerate() {\n\n if component_index[i] != component_index[j] {\n\n if let Some(k) = binary_segment_records_map.get(&(id1.clone(), id2)) {\n\n k_ij[(i, j)] = *k;\n\n }\n\n }\n\n }\n\n }\n\n }\n\n\n\n // Combining rules dispersion\n\n let sigma_ij =\n\n Array2::from_shape_fn([sigma.len(); 2], |(i, j)| 0.5 * (sigma[i] + sigma[j]));\n\n let epsilon_k_ij = Array2::from_shape_fn([epsilon_k.len(); 2], |(i, j)| {\n\n (epsilon_k[i] * epsilon_k[j]).sqrt() * (1.0 - k_ij[(i, j)])\n\n });\n\n\n", "file_path": "src/dft/parameter.rs", "rank": 37, "score": 53981.39694829139 }, { "content": "\n\n // Compare queried components and available components\n\n let available: IndexSet<String> = record_map\n\n .keys()\n\n .map(|identifier| identifier.to_string())\n\n .collect();\n\n if !queried.is_subset(&available) {\n\n let missing: Vec<String> = queried.difference(&available).cloned().collect();\n\n return Err(ParameterError::ComponentsNotFound(format!(\"{:?}\", missing)));\n\n };\n\n\n\n // Collect all pure records that were queried\n\n let chemical_records: Vec<_> = queried\n\n .iter()\n\n .filter_map(|identifier| record_map.remove(&identifier.clone()))\n\n .collect();\n\n\n\n // Read segment records\n\n let segment_records: Vec<SegmentRecord<GcPcSaftRecord, JobackRecord>> =\n\n serde_json::from_reader(BufReader::new(File::open(file_segments)?))?;\n", "file_path": "src/dft/parameter.rs", "rank": 38, "score": 53979.7830609994 }, { "content": "#[pymodule]\n\npub fn feos_gc_pcsaft(py: Python<'_>, m: &PyModule) -> PyResult<()> {\n\n m.add_class::<PyIdentifier>()?;\n\n m.add_class::<Verbosity>()?;\n\n m.add_class::<Contributions>()?;\n\n m.add_class::<PyChemicalRecord>()?;\n\n m.add_class::<PyJobackRecord>()?;\n\n\n\n m.add_class::<PyGcPcSaftRecord>()?;\n\n m.add_class::<PySegmentRecord>()?;\n\n m.add_class::<PyBinaryRecord>()?;\n\n m.add_class::<PyBinarySegmentRecord>()?;\n\n m.add_class::<PyGcPcSaftEosParameters>()?;\n\n m.add_class::<PyGcPcSaftFunctionalParameters>()?;\n\n\n\n m.add_wrapped(wrap_pymodule!(eos))?;\n\n m.add_wrapped(wrap_pymodule!(dft))?;\n\n m.add_wrapped(wrap_pymodule!(quantity))?;\n\n\n\n py.run(\n\n \"\\\n", "file_path": "build_wheel/src/lib.rs", "rank": 39, "score": 52823.78508617848 }, { "content": "use super::GcPcSaftFunctionalParameters;\n\nuse feos_core::EosError;\n\nuse feos_dft::fundamental_measure_theory::FMTProperties;\n\nuse feos_dft::{\n\n FunctionalContributionDual, WeightFunction, WeightFunctionInfo, WeightFunctionShape,\n\n};\n\nuse ndarray::*;\n\nuse num_dual::DualNum;\n\nuse petgraph::visit::EdgeRef;\n\nuse std::fmt;\n\nuse std::rc::Rc;\n\n\n\n#[derive(Clone)]\n\npub struct ChainFunctional {\n\n parameters: Rc<GcPcSaftFunctionalParameters>,\n\n}\n\n\n\nimpl ChainFunctional {\n\n pub fn new(parameters: &Rc<GcPcSaftFunctionalParameters>) -> Self {\n\n Self {\n", "file_path": "src/dft/hard_chain.rs", "rank": 40, "score": 52036.12840368779 }, { "content": " parameters: parameters.clone(),\n\n }\n\n }\n\n}\n\n\n\nimpl<N: DualNum<f64> + ScalarOperand> FunctionalContributionDual<N> for ChainFunctional {\n\n fn weight_functions(&self, temperature: N) -> WeightFunctionInfo<N> {\n\n let p = &self.parameters;\n\n let d = p.hs_diameter(temperature);\n\n WeightFunctionInfo::new(p.component_index(), true)\n\n .add(\n\n WeightFunction {\n\n prefactor: p.chain_length().mapv(|m| m.into()) / (&d * 8.0),\n\n kernel_radius: d.clone(),\n\n shape: WeightFunctionShape::Theta,\n\n },\n\n true,\n\n )\n\n .add(\n\n WeightFunction {\n", "file_path": "src/dft/hard_chain.rs", "rank": 41, "score": 52027.601744047264 }, { "content": " .reduce(|acc, y| acc * y);\n\n if let Some(y) = y {\n\n phi -= &(y.map(N::ln) * rho_i * 0.5);\n\n }\n\n }\n\n\n\n Ok(phi)\n\n }\n\n}\n\n\n\nimpl fmt::Display for ChainFunctional {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"Hard chain functional (GC)\")\n\n }\n\n}\n", "file_path": "src/dft/hard_chain.rs", "rank": 42, "score": 52024.27785337071 }, { "content": " prefactor: p.chain_length().mapv(|m| (m / 8.0).into()),\n\n kernel_radius: d,\n\n shape: WeightFunctionShape::Theta,\n\n },\n\n true,\n\n )\n\n }\n\n\n\n fn calculate_helmholtz_energy_density(\n\n &self,\n\n temperature: N,\n\n weighted_densities: ArrayView2<N>,\n\n ) -> Result<Array1<N>, EosError> {\n\n let p = &self.parameters;\n\n // number of segments\n\n let segments = weighted_densities.shape()[0] - 2;\n\n\n\n // weighted densities\n\n let rho = weighted_densities.slice_axis(Axis(0), Slice::new(0, Some(segments as isize), 1));\n\n let zeta2 = weighted_densities.index_axis(Axis(0), segments);\n", "file_path": "src/dft/hard_chain.rs", "rank": 43, "score": 52019.36363803969 }, { "content": " let zeta3 = weighted_densities.index_axis(Axis(0), segments + 1);\n\n\n\n // temperature dependent segment diameter\n\n let d = p.hs_diameter(temperature);\n\n\n\n // Helmholtz energy\n\n let frac_1mz3 = zeta3.mapv(|z3| (-z3 + 1.0).recip());\n\n let c = &zeta2 * &frac_1mz3 * &frac_1mz3;\n\n\n\n let mut phi = Array::zeros(zeta2.raw_dim());\n\n for i in p.bonds.node_indices() {\n\n let rho_i = rho.index_axis(Axis(0), i.index());\n\n let edges = p.bonds.edges(i);\n\n let y = edges\n\n .map(|e| {\n\n let di = d[e.source().index()];\n\n let dj = d[e.target().index()];\n\n let cdij = &c * di * dj / (di + dj);\n\n &frac_1mz3 + &cdij * 3.0 - &cdij * &cdij * (&zeta3 - 1.0) * 2.0\n\n })\n", "file_path": "src/dft/hard_chain.rs", "rank": 44, "score": 52019.09680155728 }, { "content": "fn newton_step_cross_association<S, D: DualNum<f64> + ScalarOperand>(\n\n x: &mut Array1<D>,\n\n nassoc: usize,\n\n delta: &Array2<D>,\n\n na: &Array1<f64>,\n\n nb: &Array1<f64>,\n\n rho: &ArrayBase<S, Ix1>,\n\n tol: f64,\n\n) -> Result<bool, EosError>\n\nwhere\n\n S: Data<Elem = D>,\n\n{\n\n // gradient\n\n let mut g: Array1<D> = Array::zeros(2 * nassoc);\n\n // Hessian\n\n let mut h: Array2<D> = Array::zeros((2 * nassoc, 2 * nassoc));\n\n\n\n // slice arrays\n\n let (xa, xb) = x.multi_slice_mut((s![..nassoc], s![nassoc..]));\n\n let (mut ga, mut gb) = g.multi_slice_mut((s![..nassoc], s![nassoc..]));\n", "file_path": "src/eos/association.rs", "rank": 45, "score": 51341.76914057696 }, { "content": "#[test]\n\n#[allow(non_snake_case)]\n\nfn test_bulk_implementation() -> Result<(), Box<dyn Error>> {\n\n // correct for different k_B in old code\n\n let KB_old = 1.38064852e-23 * JOULE / KELVIN;\n\n let NAV_old = 6.022140857e23 / MOL;\n\n\n\n let parameters = GcPcSaftEosParameters::from_json_segments(\n\n &[\"propane\"],\n\n \"parameters/gc_substances.json\",\n\n \"parameters/sauer2014_hetero.json\",\n\n None,\n\n IdentifierOption::Name,\n\n )\n\n .unwrap();\n\n\n\n let parameters_func = GcPcSaftFunctionalParameters::from_json_segments(\n\n &[\"propane\"],\n\n \"parameters/gc_substances.json\",\n\n \"parameters/sauer2014_hetero.json\",\n\n None,\n\n IdentifierOption::Name,\n", "file_path": "tests/dft.rs", "rank": 46, "score": 50042.005575220304 }, { "content": "#[test]\n\nfn test_binary() -> EosResult<()> {\n\n let parameters = GcPcSaftEosParameters::from_json_segments(\n\n &[\"ethanol\", \"methanol\"],\n\n \"parameters/gc_substances.json\",\n\n \"parameters/sauer2014_hetero.json\",\n\n None,\n\n IdentifierOption::Name,\n\n )\n\n .unwrap();\n\n let parameters_func = GcPcSaftFunctionalParameters::from_json_segments(\n\n &[\"ethanol\", \"methanol\"],\n\n \"parameters/gc_substances.json\",\n\n \"parameters/sauer2014_hetero.json\",\n\n None,\n\n IdentifierOption::Name,\n\n )\n\n .unwrap();\n\n let eos = Rc::new(GcPcSaft::new(Rc::new(parameters)));\n\n let func = Rc::new(GcPcSaftFunctional::new(Rc::new(parameters_func)));\n\n let moles = arr1(&[0.5, 0.5]) * MOL;\n", "file_path": "tests/binary.rs", "rank": 47, "score": 35847.425916787724 }, { "content": "fn zeta_23<D: DualNum<f64>>(\n\n parameters: &GcPcSaftEosParameters,\n\n diameter: &Array1<D>,\n\n molefracs: &Array1<D>,\n\n) -> D {\n\n let mut zeta: [D; 2] = [D::zero(); 2];\n\n for i in 0..parameters.m.len() {\n\n for (k, z) in zeta.iter_mut().enumerate() {\n\n *z += molefracs[parameters.component_index[i]]\n\n * diameter[i].powi((k + 2) as i32)\n\n * (FRAC_PI_6 * parameters.m[i]);\n\n }\n\n }\n\n\n\n zeta[0] / zeta[1]\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n", "file_path": "src/eos/hard_sphere.rs", "rank": 48, "score": 30963.842916804453 }, { "content": "#![allow(clippy::excessive_precision)]\n\nuse approx::assert_relative_eq;\n\nuse feos_core::parameter::IdentifierOption;\n\nuse feos_core::{PhaseEquilibrium, State, StateBuilder, Verbosity};\n\nuse feos_dft::adsorption::{ExternalPotential, Pore1D, PoreSpecification};\n\nuse feos_dft::interface::PlanarInterface;\n\nuse feos_dft::{DFTSolver, Geometry};\n\nuse feos_gc_pcsaft::{\n\n GcPcSaft, GcPcSaftEosParameters, GcPcSaftFunctional, GcPcSaftFunctionalParameters,\n\n};\n\nuse ndarray::arr1;\n\nuse quantity::si::*;\n\nuse std::error::Error;\n\nuse std::rc::Rc;\n\n\n\n#[test]\n\n#[allow(non_snake_case)]\n", "file_path": "tests/dft.rs", "rank": 49, "score": 28338.399176851246 }, { "content": " )\n\n .unwrap();\n\n\n\n let eos = Rc::new(GcPcSaft::new(Rc::new(parameters)));\n\n let func = Rc::new(GcPcSaftFunctional::new(Rc::new(parameters_func)));\n\n let t = 200.0 * KELVIN;\n\n let v = 0.002 * METER.powi(3) * NAV / NAV_old;\n\n let n = arr1(&[1.5]) * MOL;\n\n let state_eos = State::new_nvt(&eos, t, v, &n)?;\n\n let state_func = State::new_nvt(&func, t, v, &n)?;\n\n let p_eos = state_eos.pressure_contributions();\n\n let p_func = state_func.pressure_contributions();\n\n\n\n println!(\"{:29}: {}\", p_eos[0].0, p_eos[0].1);\n\n println!(\"{:29}: {}\", p_func[0].0, p_func[0].1);\n\n println!();\n\n println!(\"{:29}: {}\", p_eos[1].0, p_eos[1].1);\n\n println!(\"{:29}: {}\", p_func[1].0, p_func[1].1);\n\n println!();\n\n println!(\"{:29}: {}\", p_eos[2].0, p_eos[2].1);\n", "file_path": "tests/dft.rs", "rank": 50, "score": 28333.66882890873 }, { "content": " let profile = PlanarInterface::from_tanh(&vle, points, w, tc)?.solve(None)?;\n\n println!(\n\n \"hetero {} {} {}\",\n\n profile.surface_tension.unwrap(),\n\n vle.vapor().density,\n\n vle.liquid().density,\n\n );\n\n\n\n assert_relative_eq!(\n\n vle.vapor().density,\n\n 12.8820179191167643 * MOL / METER.powi(3) * NAV_old / NAV,\n\n max_relative = 1e-13,\n\n );\n\n\n\n assert_relative_eq!(\n\n vle.liquid().density,\n\n 13.2705903446123212 * KILO * MOL / METER.powi(3) * NAV_old / NAV,\n\n max_relative = 1e-13,\n\n );\n\n\n\n assert_relative_eq!(\n\n profile.surface_tension.unwrap(),\n\n 21.1478901897016272 * MILLI * NEWTON / METER * KB / KB_old,\n\n max_relative = 6e-5,\n\n );\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/dft.rs", "rank": 51, "score": 28329.432866228326 }, { "content": " vle.liquid().density,\n\n );\n\n\n\n let solver = DFTSolver::new(Verbosity::Iter)\n\n .picard_iteration(None)\n\n .beta(0.05)\n\n .tol(1e-5)\n\n .anderson_mixing(None);\n\n let bulk = StateBuilder::new(&func)\n\n .temperature(t)\n\n .pressure(5.0 * BAR)\n\n .build()?;\n\n Pore1D::new(\n\n Geometry::Cartesian,\n\n 20.0 * ANGSTROM,\n\n ExternalPotential::LJ93 {\n\n epsilon_k_ss: 10.0,\n\n sigma_ss: 3.0,\n\n rho_s: 0.08,\n\n },\n\n None,\n\n None,\n\n )\n\n .initialize(&bulk, None, None)?\n\n .solve(Some(&solver))?;\n\n Ok(())\n\n}\n", "file_path": "tests/dft.rs", "rank": 52, "score": 28328.814111580137 }, { "content": " assert_relative_eq!(\n\n p_eos[3].1,\n\n -763.2289230004602132 * KILO * PASCAL * KB / KB_old,\n\n max_relative = 1e-14,\n\n );\n\n\n\n assert_relative_eq!(\n\n p_func[0].1,\n\n 1.2471689792172869 * MEGA * PASCAL * KB / KB_old,\n\n max_relative = 1e-14,\n\n );\n\n assert_relative_eq!(\n\n p_func[1].1,\n\n 280.0635060891395938 * KILO * PASCAL * KB / KB_old,\n\n max_relative = 1e-14,\n\n );\n\n assert_relative_eq!(\n\n p_func[2].1,\n\n -141.9023918353318550 * KILO * PASCAL * KB / KB_old,\n\n max_relative = 1e-14,\n\n );\n\n assert_relative_eq!(\n\n p_func[3].1,\n\n -763.2289230004602132 * KILO * PASCAL * KB / KB_old,\n\n max_relative = 1e-14,\n\n );\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/dft.rs", "rank": 53, "score": 28326.675850657615 }, { "content": " println!(\"{:29}: {}\", p_func[2].0, p_func[2].1);\n\n println!();\n\n println!(\"{:29}: {}\", p_eos[3].0, p_eos[3].1);\n\n println!(\"{:29}: {}\", p_func[3].0, p_func[3].1);\n\n\n\n assert_relative_eq!(\n\n p_eos[0].1,\n\n 1.2471689792172869 * MEGA * PASCAL * KB / KB_old,\n\n max_relative = 1e-14,\n\n );\n\n assert_relative_eq!(\n\n p_eos[1].1,\n\n 280.0635060891395938 * KILO * PASCAL * KB / KB_old,\n\n max_relative = 1e-14,\n\n );\n\n assert_relative_eq!(\n\n p_eos[2].1,\n\n -141.9023918353318550 * KILO * PASCAL * KB / KB_old,\n\n max_relative = 1e-14,\n\n );\n", "file_path": "tests/dft.rs", "rank": 54, "score": 28326.675850657615 }, { "content": "use feos_core::joback::Joback;\n\nuse feos_core::{EquationOfState, HelmholtzEnergy, IdealGasContribution, MolarWeight};\n\nuse ndarray::Array1;\n\nuse quantity::si::*;\n\nuse std::f64::consts::FRAC_PI_6;\n\nuse std::rc::Rc;\n\n\n\npub(crate) mod association;\n\npub(crate) mod dispersion;\n\nmod hard_chain;\n\nmod hard_sphere;\n\nmod parameter;\n\nmod polar;\n\nuse association::{Association, CrossAssociation};\n\nuse dispersion::Dispersion;\n\nuse hard_chain::HardChain;\n\nuse hard_sphere::HardSphere;\n\npub use parameter::GcPcSaftEosParameters;\n\nuse polar::Dipole;\n\n\n", "file_path": "src/eos/mod.rs", "rank": 55, "score": 28104.50636544062 }, { "content": "\n\n/// gc-PC-SAFT equation of state\n\npub struct GcPcSaft {\n\n pub parameters: Rc<GcPcSaftEosParameters>,\n\n options: GcPcSaftOptions,\n\n contributions: Vec<Box<dyn HelmholtzEnergy>>,\n\n joback: Joback,\n\n}\n\n\n\nimpl GcPcSaft {\n\n pub fn new(parameters: Rc<GcPcSaftEosParameters>) -> Self {\n\n Self::with_options(parameters, GcPcSaftOptions::default())\n\n }\n\n\n\n pub fn with_options(parameters: Rc<GcPcSaftEosParameters>, options: GcPcSaftOptions) -> Self {\n\n let mut contributions: Vec<Box<dyn HelmholtzEnergy>> = Vec::with_capacity(7);\n\n contributions.push(Box::new(HardSphere {\n\n parameters: parameters.clone(),\n\n }));\n\n contributions.push(Box::new(HardChain {\n", "file_path": "src/eos/mod.rs", "rank": 56, "score": 28103.698213446954 }, { "content": " parameters: parameters.clone(),\n\n }));\n\n contributions.push(Box::new(Dispersion {\n\n parameters: parameters.clone(),\n\n }));\n\n match parameters.assoc_segment.len() {\n\n 0 => (),\n\n 1 => contributions.push(Box::new(Association {\n\n parameters: parameters.clone(),\n\n })),\n\n _ => contributions.push(Box::new(CrossAssociation {\n\n parameters: parameters.clone(),\n\n max_iter: options.max_iter_cross_assoc,\n\n tol: options.tol_cross_assoc,\n\n })),\n\n };\n\n if !parameters.dipole_comp.is_empty() {\n\n contributions.push(Box::new(Dipole::new(&parameters)))\n\n }\n\n Self {\n", "file_path": "src/eos/mod.rs", "rank": 57, "score": 28101.138316418128 }, { "content": "/// Customization options for the gc-PC-SAFT equation of state and functional.\n\n#[derive(Copy, Clone)]\n\npub struct GcPcSaftOptions {\n\n /// maximum packing fraction\n\n pub max_eta: f64,\n\n /// maximum number of iterations for cross association calculation\n\n pub max_iter_cross_assoc: usize,\n\n /// tolerance for cross association calculation\n\n pub tol_cross_assoc: f64,\n\n}\n\n\n\nimpl Default for GcPcSaftOptions {\n\n fn default() -> Self {\n\n Self {\n\n max_eta: 0.5,\n\n max_iter_cross_assoc: 50,\n\n tol_cross_assoc: 1e-10,\n\n }\n\n }\n\n}\n", "file_path": "src/eos/mod.rs", "rank": 58, "score": 28100.08573216219 }, { "content": " parameters: parameters.clone(),\n\n options,\n\n contributions,\n\n joback: parameters.joback_records.clone().map_or_else(\n\n || Joback::default(parameters.chemical_records.len()),\n\n Joback::new,\n\n ),\n\n }\n\n }\n\n}\n\n\n\nimpl EquationOfState for GcPcSaft {\n\n fn components(&self) -> usize {\n\n self.parameters.molarweight.len()\n\n }\n\n\n\n fn subset(&self, component_list: &[usize]) -> Self {\n\n Self::with_options(\n\n Rc::new(self.parameters.subset(component_list)),\n\n self.options,\n", "file_path": "src/eos/mod.rs", "rank": 59, "score": 28097.207383151548 }, { "content": "use crate::dft::GcPcSaftFunctionalParameters;\n\nuse crate::eos::GcPcSaftEosParameters;\n\nuse crate::record::GcPcSaftRecord;\n\nuse feos_core::joback::JobackRecord;\n\nuse feos_core::parameter::{BinaryRecord, IdentifierOption, ParameterError, SegmentRecord};\n\nuse feos_core::python::joback::PyJobackRecord;\n\nuse feos_core::python::parameter::{PyBinarySegmentRecord, PyChemicalRecord};\n\nuse feos_core::{impl_json_handling, impl_parameter_from_segments, impl_segment_record};\n\nuse numpy::{PyArray2, ToPyArray};\n\nuse pyo3::prelude::*;\n\nuse std::convert::TryFrom;\n\nuse std::rc::Rc;\n\n\n\n#[cfg(feature = \"micelles\")]\n\nmod micelles;\n\n\n\n#[pyclass(name = \"GcPcSaftRecord\", unsendable)]\n\n#[pyo3(\n\n text_signature = \"(m, sigma, epsilon_k, mu=None, q=None, kappa_ab=None, epsilon_k_ab=None, na=None, nb=None)\"\n\n)]\n", "file_path": "src/python/mod.rs", "rank": 60, "score": 28096.060249098544 }, { "content": " )\n\n }\n\n\n\n fn compute_max_density(&self, moles: &Array1<f64>) -> f64 {\n\n let p = &self.parameters;\n\n let moles_segments: Array1<f64> = p.component_index.iter().map(|&i| moles[i]).collect();\n\n self.options.max_eta * moles.sum()\n\n / (FRAC_PI_6 * &p.m * p.sigma.mapv(|v| v.powi(3)) * moles_segments).sum()\n\n }\n\n\n\n fn residual(&self) -> &[Box<dyn HelmholtzEnergy>] {\n\n &self.contributions\n\n }\n\n\n\n fn ideal_gas(&self) -> &dyn IdealGasContribution {\n\n &self.joback\n\n }\n\n}\n\n\n\nimpl MolarWeight<SIUnit> for GcPcSaft {\n\n fn molar_weight(&self) -> SIArray1 {\n\n self.parameters.molarweight.clone() * GRAM / MOL\n\n }\n\n}\n", "file_path": "src/eos/mod.rs", "rank": 61, "score": 28095.59055925874 }, { "content": "#[derive(Clone)]\n\npub struct PyGcPcSaftRecord(GcPcSaftRecord);\n\n\n\n#[pymethods]\n\nimpl PyGcPcSaftRecord {\n\n #[new]\n\n fn new(\n\n m: f64,\n\n sigma: f64,\n\n epsilon_k: f64,\n\n mu: Option<f64>,\n\n kappa_ab: Option<f64>,\n\n epsilon_k_ab: Option<f64>,\n\n na: Option<f64>,\n\n nb: Option<f64>,\n\n psi_dft: Option<f64>,\n\n ) -> Self {\n\n Self(GcPcSaftRecord::new(\n\n m,\n\n sigma,\n", "file_path": "src/python/mod.rs", "rank": 62, "score": 28095.27343861241 }, { "content": " Ok(self.0.to_string())\n\n }\n\n}\n\n\n\n#[pyclass(name = \"GcPcSaftFunctionalParameters\", unsendable)]\n\n#[pyo3(\n\n text_signature = \"(pure_records, segmentbinary_records=None, substances=None, search_option='Name')\"\n\n)]\n\n#[derive(Clone)]\n\npub struct PyGcPcSaftFunctionalParameters(pub Rc<GcPcSaftFunctionalParameters>);\n\n\n\nimpl_parameter_from_segments!(GcPcSaftFunctionalParameters, PyGcPcSaftFunctionalParameters);\n\n\n\n#[pymethods]\n\nimpl PyGcPcSaftFunctionalParameters {\n\n fn _repr_markdown_(&self) -> String {\n\n self.0.to_markdown()\n\n }\n\n\n\n #[getter]\n", "file_path": "src/python/mod.rs", "rank": 63, "score": 28093.261698747672 }, { "content": " JobackRecord,\n\n PyJobackRecord\n\n);\n\n\n\n#[pyclass(name = \"GcPcSaftEosParameters\", unsendable)]\n\n#[pyo3(\n\n text_signature = \"(pure_records, segmentbinary_records=None, substances=None, search_option='Name')\"\n\n)]\n\n#[derive(Clone)]\n\npub struct PyGcPcSaftEosParameters(pub Rc<GcPcSaftEosParameters>);\n\n\n\nimpl_parameter_from_segments!(GcPcSaftEosParameters, PyGcPcSaftEosParameters);\n\n\n\n#[pymethods]\n\nimpl PyGcPcSaftEosParameters {\n\n fn _repr_markdown_(&self) -> String {\n\n self.0.to_markdown()\n\n }\n\n\n\n fn __repr__(&self) -> PyResult<String> {\n", "file_path": "src/python/mod.rs", "rank": 64, "score": 28092.950430101893 }, { "content": " epsilon_k,\n\n mu,\n\n kappa_ab,\n\n epsilon_k_ab,\n\n na,\n\n nb,\n\n psi_dft,\n\n ))\n\n }\n\n\n\n fn __repr__(&self) -> PyResult<String> {\n\n Ok(self.0.to_string())\n\n }\n\n}\n\n\n\nimpl_json_handling!(PyGcPcSaftRecord);\n\n\n\nimpl_segment_record!(\n\n GcPcSaftRecord,\n\n PyGcPcSaftRecord,\n", "file_path": "src/python/mod.rs", "rank": 65, "score": 28088.10590629121 }, { "content": " fn get_graph(&self, py: Python) -> PyResult<PyObject> {\n\n let fun: Py<PyAny> = PyModule::from_code(\n\n py,\n\n \"def f(s): \n\n import graphviz\n\n return graphviz.Source(s.replace('\\\\\\\\\\\"', ''))\",\n\n \"\",\n\n \"\",\n\n )?\n\n .getattr(\"f\")?\n\n .into();\n\n fun.call1(py, (self.0.graph(),))\n\n }\n\n\n\n #[getter]\n\n fn get_k_ij<'py>(&self, py: Python<'py>) -> &'py PyArray2<f64> {\n\n self.0.k_ij.view().to_pyarray(py)\n\n }\n\n\n\n fn __repr__(&self) -> PyResult<String> {\n\n Ok(self.0.to_string())\n\n }\n\n}\n", "file_path": "src/python/mod.rs", "rank": 66, "score": 28082.512211614587 }, { "content": "use super::hard_sphere::zeta;\n\nuse super::GcPcSaftEosParameters;\n\nuse feos_core::{EosError, HelmholtzEnergyDual, StateHD};\n\nuse ndarray::*;\n\nuse num_dual::linalg::{norm, LU};\n\nuse num_dual::*;\n\nuse std::fmt;\n\nuse std::rc::Rc;\n\n\n\n#[derive(Clone)]\n\npub struct Association {\n\n pub parameters: Rc<GcPcSaftEosParameters>,\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct CrossAssociation {\n\n pub parameters: Rc<GcPcSaftEosParameters>,\n\n pub max_iter: usize,\n\n pub tol: f64,\n\n}\n\n\n", "file_path": "src/eos/association.rs", "rank": 67, "score": 27769.26177979532 }, { "content": "impl<D: DualNum<f64>> HelmholtzEnergyDual<D> for Association {\n\n fn helmholtz_energy(&self, state: &StateHD<D>) -> D {\n\n let p = &self.parameters;\n\n let c = p.component_index[p.assoc_segment[0]];\n\n\n\n // temperature dependent segment diameter\n\n let diameter = p.hs_diameter(state.temperature);\n\n\n\n // Packing fractions\n\n let n2 = zeta(p, &diameter, &state.partial_density, [2])[0] * 6.0;\n\n let n3 = zeta(p, &diameter, &state.partial_density, [3])[0];\n\n let n3i = (-n3 + 1.0).recip();\n\n\n\n // association strength\n\n let deltarho = association_strength(\n\n &p.assoc_segment,\n\n &p.sigma3_kappa_aibj,\n\n &p.epsilon_k_aibj,\n\n state.temperature,\n\n &diameter,\n", "file_path": "src/eos/association.rs", "rank": 68, "score": 27766.980352861596 }, { "content": " }\n\n\n\n // Newton step\n\n x.assign(&(&*x - &LU::new(h)?.solve(&g)));\n\n\n\n // check convergence\n\n Ok(norm(&g.map(D::re)) < tol)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use crate::eos::parameter::test::*;\n\n use approx::assert_relative_eq;\n\n use feos_core::EosUnit;\n\n use ndarray::arr1;\n\n use num_dual::Dual64;\n\n use quantity::si::{METER, MOL, PASCAL};\n\n\n\n #[test]\n", "file_path": "src/eos/association.rs", "rank": 69, "score": 27766.04092220018 }, { "content": " state.moles[c] * p.n[0] * (xa.ln() - xa * 0.5 + 0.5) * na\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Display for Association {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"Association\")\n\n }\n\n}\n\n\n\npub(crate) fn assoc_site_frac_ab<D: DualNum<f64>>(deltarho: D, na: f64, nb: f64) -> D {\n\n if deltarho.re() > f64::EPSILON.sqrt() {\n\n (((deltarho * (na - nb) + 1.0).powi(2) + deltarho * nb * 4.0).sqrt()\n\n - (deltarho * (nb - na) + 1.0))\n\n / (deltarho * na * 2.0)\n\n } else {\n\n D::one() + deltarho * nb * (deltarho * (nb + na) - 1.0)\n\n }\n\n}\n", "file_path": "src/eos/association.rs", "rank": 70, "score": 27765.981538662836 }, { "content": "\n\npub(crate) fn assoc_site_frac_a<D: DualNum<f64>>(deltarho: D, na: f64) -> D {\n\n if deltarho.re() > f64::EPSILON.sqrt() {\n\n ((deltarho * na * 4.0 + 1.0).powi(2) - 1.0).sqrt() / (deltarho * na * 2.0)\n\n } else {\n\n D::one() + deltarho * na * (deltarho * na * 2.0 - 1.0)\n\n }\n\n}\n\n\n\nimpl<D: DualNum<f64> + ScalarOperand> HelmholtzEnergyDual<D> for CrossAssociation {\n\n fn helmholtz_energy(&self, state: &StateHD<D>) -> D {\n\n let p = &self.parameters;\n\n\n\n // temperature dependent segment diameter\n\n let diameter = p.hs_diameter(state.temperature);\n\n\n\n // Packing fractions\n\n let n2 = zeta(p, &diameter, &state.partial_density, [2])[0] * 6.0;\n\n let n3 = zeta(p, &diameter, &state.partial_density, [3])[0];\n\n let n3i = (-n3 + 1.0).recip();\n", "file_path": "src/eos/association.rs", "rank": 71, "score": 27765.421098022092 }, { "content": "\n\n #[test]\n\n fn test_cross_assoc_propanol() {\n\n let parameters = propanol();\n\n let contrib = CrossAssociation {\n\n parameters: Rc::new(parameters),\n\n max_iter: 50,\n\n tol: 1e-10,\n\n };\n\n let temperature = 300.0;\n\n let volume = METER\n\n .powi(3)\n\n .to_reduced(EosUnit::reference_volume())\n\n .unwrap();\n\n let moles = (1.5 * MOL).to_reduced(EosUnit::reference_moles()).unwrap();\n\n let state = StateHD::new(\n\n Dual64::from_re(temperature),\n\n Dual64::from_re(volume).derive(),\n\n arr1(&[Dual64::from_re(moles)]),\n\n );\n", "file_path": "src/eos/association.rs", "rank": 72, "score": 27765.022587574662 }, { "content": " // check if density is close to 0\n\n if density.sum().re() < f64::EPSILON {\n\n if let Some(x0) = x0 {\n\n x0.fill(1.0);\n\n }\n\n return Ok(D::zero());\n\n }\n\n\n\n // number of associating segments\n\n let nassoc = assoc_segment.len();\n\n\n\n // association strength\n\n let delta = Array::from_shape_fn([nassoc; 2], |(i, j)| {\n\n association_strength(\n\n assoc_segment,\n\n sigma3_kappa_aibj,\n\n epsilon_k_aibj,\n\n temperature,\n\n diameter,\n\n n2,\n", "file_path": "src/eos/association.rs", "rank": 73, "score": 27764.6160833371 }, { "content": " let pressure =\n\n -contrib.helmholtz_energy(&state).eps[0] * temperature * EosUnit::reference_pressure();\n\n assert_relative_eq!(pressure, -3.6819598891967344 * PASCAL, max_relative = 1e-10);\n\n }\n\n\n\n #[test]\n\n fn test_cross_assoc_ethanol_propanol() {\n\n let parameters = ethanol_propanol(false);\n\n let contrib = CrossAssociation {\n\n parameters: Rc::new(parameters),\n\n max_iter: 50,\n\n tol: 1e-10,\n\n };\n\n let temperature = 300.0;\n\n let volume = METER\n\n .powi(3)\n\n .to_reduced(EosUnit::reference_volume())\n\n .unwrap();\n\n let moles = (arr1(&[1.5, 2.5]) * MOL)\n\n .to_reduced(EosUnit::reference_moles())\n", "file_path": "src/eos/association.rs", "rank": 74, "score": 27764.60491697488 }, { "content": " self.tol,\n\n None,\n\n )\n\n .unwrap_or_else(|_| D::from(std::f64::NAN))\n\n * state.volume\n\n }\n\n}\n\n\n\nimpl fmt::Display for CrossAssociation {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"Cross-association\")\n\n }\n\n}\n\n\n", "file_path": "src/eos/association.rs", "rank": 75, "score": 27764.45907335196 }, { "content": " fn test_assoc_propanol() {\n\n let parameters = propanol();\n\n let contrib = Association {\n\n parameters: Rc::new(parameters),\n\n };\n\n let temperature = 300.0;\n\n let volume = METER\n\n .powi(3)\n\n .to_reduced(EosUnit::reference_volume())\n\n .unwrap();\n\n let moles = (1.5 * MOL).to_reduced(EosUnit::reference_moles()).unwrap();\n\n let state = StateHD::new(\n\n Dual64::from_re(temperature),\n\n Dual64::from_re(volume).derive(),\n\n arr1(&[Dual64::from_re(moles)]),\n\n );\n\n let pressure =\n\n -contrib.helmholtz_energy(&state).eps[0] * temperature * EosUnit::reference_pressure();\n\n assert_relative_eq!(pressure, -3.6819598891967344 * PASCAL, max_relative = 1e-10);\n\n }\n", "file_path": "src/eos/association.rs", "rank": 76, "score": 27764.224295553755 }, { "content": "\n\n // extract densities of associating segments\n\n let rho_assoc = p\n\n .assoc_segment\n\n .mapv(|a| state.partial_density[p.component_index[a]])\n\n * &p.n;\n\n\n\n helmholtz_energy_density_cross_association(\n\n &p.assoc_segment,\n\n &p.sigma3_kappa_aibj,\n\n &p.epsilon_k_aibj,\n\n &p.na,\n\n &p.nb,\n\n state.temperature,\n\n &rho_assoc,\n\n &diameter,\n\n n2,\n\n n3i,\n\n D::one(),\n\n self.max_iter,\n", "file_path": "src/eos/association.rs", "rank": 77, "score": 27762.59039182737 }, { "content": " n2,\n\n n3i,\n\n D::one(),\n\n 0,\n\n 0,\n\n ) * state.partial_density[c];\n\n\n\n let na = p.na[0];\n\n let nb = p.nb[0];\n\n if nb > 0.0 {\n\n // no cross association, two association sites\n\n let xa = assoc_site_frac_ab(deltarho, na, nb);\n\n let xb = (xa - 1.0) * (na / nb) + 1.0;\n\n state.moles[c]\n\n * p.n[0]\n\n * ((xa.ln() - xa * 0.5 + 0.5) * na + (xb.ln() - xb * 0.5 + 0.5) * nb)\n\n } else {\n\n // no cross association, one association site\n\n let xa = assoc_site_frac_a(deltarho, na);\n\n\n", "file_path": "src/eos/association.rs", "rank": 78, "score": 27762.19838975217 }, { "content": " n3i,\n\n xi,\n\n i,\n\n j,\n\n )\n\n });\n\n\n\n // cross-association according to Michelsen2006\n\n // initialize monomer fraction\n\n let mut x = match &x0 {\n\n Some(x0) => (*x0).clone(),\n\n None => Array::from_elem(2 * nassoc, 0.2),\n\n };\n\n\n\n for k in 0..max_iter {\n\n if newton_step_cross_association::<_, f64>(\n\n &mut x,\n\n nassoc,\n\n &delta.map(D::re),\n\n na,\n", "file_path": "src/eos/association.rs", "rank": 79, "score": 27762.08743942443 }, { "content": " nb,\n\n &density.map(D::re),\n\n tol,\n\n )? {\n\n break;\n\n }\n\n if k == max_iter - 1 {\n\n return Err(EosError::NotConverged(\"Cross association\".into()));\n\n }\n\n }\n\n\n\n // calculate derivatives\n\n let mut x_dual = x.mapv(D::from);\n\n for _ in 0..D::NDERIV {\n\n newton_step_cross_association(&mut x_dual, nassoc, &delta, na, nb, density, tol)?;\n\n }\n\n\n\n // save monomer fraction\n\n if let Some(x0) = x0 {\n\n *x0 = x;\n\n }\n\n\n\n // Helmholtz energy density\n\n let xa = x_dual.slice(s![..nassoc]);\n\n let xb = x_dual.slice(s![nassoc..]);\n\n let f = |x: D| x.ln() - x * 0.5 + 0.5;\n\n Ok((density * (xa.mapv(f) * na + xb.mapv(f) * nb)).sum())\n\n}\n\n\n", "file_path": "src/eos/association.rs", "rank": 80, "score": 27760.92811335769 }, { "content": " let (mut haa, mut hab, mut hba, mut hbb) = h.multi_slice_mut((\n\n s![..nassoc, ..nassoc],\n\n s![..nassoc, nassoc..],\n\n s![nassoc.., ..nassoc],\n\n s![nassoc.., nassoc..],\n\n ));\n\n\n\n // calculate gradients and approximate Hessian\n\n for i in 0..nassoc {\n\n let d = &delta.index_axis(Axis(0), i) * rho;\n\n\n\n let dnx = (&xb * nb * &d).sum() + 1.0;\n\n ga[i] = xa[i].recip() - dnx;\n\n hab.index_axis_mut(Axis(0), i).assign(&(&d * &(-nb)));\n\n haa[(i, i)] = -dnx / xa[i];\n\n\n\n let dnx = (&xa * na * &d).sum() + 1.0;\n\n gb[i] = xb[i].recip() - dnx;\n\n hba.index_axis_mut(Axis(0), i).assign(&(&d * &(-na)));\n\n hbb[(i, i)] = -dnx / xb[i];\n", "file_path": "src/eos/association.rs", "rank": 81, "score": 27759.439456975077 }, { "content": " .unwrap();\n\n let state = StateHD::new(\n\n Dual64::from_re(temperature),\n\n Dual64::from_re(volume).derive(),\n\n moles.mapv(Dual64::from_re),\n\n );\n\n let pressure =\n\n -contrib.helmholtz_energy(&state).eps[0] * temperature * EosUnit::reference_pressure();\n\n assert_relative_eq!(pressure, -26.105606376765632 * PASCAL, max_relative = 1e-10);\n\n }\n\n}\n", "file_path": "src/eos/association.rs", "rank": 82, "score": 27755.500749845247 }, { "content": " if !self.assoc_segment.is_empty() {\n\n write!(f, \"\\n\\tassoc_segment={}\", self.assoc_segment)?;\n\n write!(f, \"\\n\\tkappa_ab={}\", self.kappa_ab)?;\n\n write!(f, \"\\n\\tepsilon_k_ab={}\", self.epsilon_k_ab)?;\n\n write!(f, \"\\n\\tna={}\", self.na)?;\n\n write!(f, \"\\n\\tnb={}\", self.nb)?;\n\n }\n\n if !self.dipole_comp.is_empty() {\n\n write!(f, \"\\n\\tdipole_comp={}\", self.dipole_comp)?;\n\n write!(f, \"\\n\\tmu={}\", self.mu)?;\n\n }\n\n write!(f, \"\\n)\")\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub mod test {\n\n use super::*;\n\n use feos_core::parameter::{ChemicalRecord, Identifier};\n\n\n", "file_path": "src/eos/parameter.rs", "rank": 83, "score": 27311.127271043286 }, { "content": "use crate::record::GcPcSaftRecord;\n\nuse feos_core::joback::JobackRecord;\n\nuse feos_core::parameter::{\n\n BinaryRecord, ChemicalRecord, FromSegments, IdentifierOption, ParameterError, SegmentRecord,\n\n};\n\nuse indexmap::{IndexMap, IndexSet};\n\nuse ndarray::{Array1, Array2};\n\nuse quantity::si::{JOULE, KB, KELVIN};\n\nuse std::fmt::Write;\n\nuse std::fs::File;\n\nuse std::io::BufReader;\n\nuse std::path::Path;\n\n\n\n/// Parameter set required for the gc-PC-SAFT equation of state.\n\npub struct GcPcSaftEosParameters {\n\n pub molarweight: Array1<f64>,\n\n pub component_index: Array1<usize>,\n\n identifiers: Vec<String>,\n\n\n\n pub m: Array1<f64>,\n", "file_path": "src/eos/parameter.rs", "rank": 84, "score": 27310.715202899144 }, { "content": " pub epsilon_k_ij: Array2<f64>,\n\n pub sigma3_kappa_aibj: Array2<f64>,\n\n pub epsilon_k_aibj: Array2<f64>,\n\n\n\n pub chemical_records: Vec<ChemicalRecord>,\n\n segment_records: Vec<SegmentRecord<GcPcSaftRecord, JobackRecord>>,\n\n binary_segment_records: Option<Vec<BinaryRecord<String, f64>>>,\n\n pub joback_records: Option<Vec<JobackRecord>>,\n\n}\n\n\n\nimpl GcPcSaftEosParameters {\n\n pub fn from_segments(\n\n chemical_records: Vec<ChemicalRecord>,\n\n segment_records: Vec<SegmentRecord<GcPcSaftRecord, JobackRecord>>,\n\n binary_segment_records: Option<Vec<BinaryRecord<String, f64>>>,\n\n ) -> Result<Self, ParameterError> {\n\n let segment_map: IndexMap<_, _> = segment_records\n\n .iter()\n\n .map(|r| (r.identifier.clone(), r.clone()))\n\n .collect();\n", "file_path": "src/eos/parameter.rs", "rank": 85, "score": 27310.214313752487 }, { "content": " let e_k_ij = Array2::from_shape_fn([dipole_comp.len(); 2], |(i, j)| {\n\n (epsilon_k_mix[i] * epsilon_k_mix[j]).sqrt()\n\n });\n\n\n\n // Association\n\n let sigma3_kappa_aibj = Array2::from_shape_fn([kappa_ab.len(); 2], |(i, j)| {\n\n (sigma[assoc_segment[i]] * sigma[assoc_segment[j]]).powf(1.5)\n\n * (kappa_ab[i] * kappa_ab[j]).sqrt()\n\n });\n\n let epsilon_k_aibj = Array2::from_shape_fn([epsilon_k_ab.len(); 2], |(i, j)| {\n\n 0.5 * (epsilon_k_ab[i] + epsilon_k_ab[j])\n\n });\n\n\n\n Ok(Self {\n\n molarweight,\n\n component_index: Array1::from_vec(component_index),\n\n identifiers,\n\n n: Array1::from_vec(n),\n\n m: Array1::from_vec(m),\n\n sigma: Array1::from_vec(sigma),\n", "file_path": "src/eos/parameter.rs", "rank": 86, "score": 27308.79740943141 }, { "content": " binary_segment_records,\n\n joback_records: joback_records.into_iter().collect(),\n\n })\n\n }\n\n\n\n pub fn from_json_segments<P>(\n\n substances: &[&str],\n\n file_pure: P,\n\n file_segments: P,\n\n file_binary: Option<P>,\n\n search_option: IdentifierOption,\n\n ) -> Result<Self, ParameterError>\n\n where\n\n P: AsRef<Path>,\n\n {\n\n let queried: IndexSet<String> = substances\n\n .iter()\n\n .map(|identifier| identifier.to_string())\n\n .collect();\n\n\n", "file_path": "src/eos/parameter.rs", "rank": 87, "score": 27308.695795054784 }, { "content": " .transpose()?;\n\n\n\n Self::from_segments(chemical_records, segment_records, binary_records)\n\n }\n\n\n\n pub fn subset(&self, component_list: &[usize]) -> Self {\n\n let chemical_records: Vec<_> = component_list\n\n .iter()\n\n .map(|&i| self.chemical_records[i].clone())\n\n .collect();\n\n Self::from_segments(\n\n chemical_records,\n\n self.segment_records.clone(),\n\n self.binary_segment_records.clone(),\n\n )\n\n .unwrap()\n\n }\n\n\n\n pub fn to_markdown(&self) -> String {\n\n let mut output = String::new();\n", "file_path": "src/eos/parameter.rs", "rank": 88, "score": 27307.661542310067 }, { "content": " o,\n\n \"\\n|{}|{}|{}|{}|\",\n\n component, self.identifiers[*c1], self.identifiers[*c2], c\n\n )\n\n .unwrap();\n\n }\n\n\n\n output\n\n }\n\n}\n\n\n\nimpl std::fmt::Display for GcPcSaftEosParameters {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"GcPcSaftParameters(\")?;\n\n write!(f, \"\\n\\tmolarweight={}\", self.molarweight)?;\n\n write!(f, \"\\n\\tcomponent_index={}\", self.component_index)?;\n\n write!(f, \"\\n\\tm={}\", self.m)?;\n\n write!(f, \"\\n\\tsigma={}\", self.sigma)?;\n\n write!(f, \"\\n\\tepsilon_k={}\", self.epsilon_k)?;\n\n write!(f, \"\\n\\tbonds={:?}\", self.bonds)?;\n", "file_path": "src/eos/parameter.rs", "rank": 89, "score": 27305.970600928835 }, { "content": " )\n\n };\n\n let association = if let Some(a) = self.assoc_segment.iter().position(|&a| a == i) {\n\n format!(\n\n \"{}|{}|{}|{}\",\n\n self.kappa_ab[a], self.epsilon_k_ab[a], self.na[a], self.nb[a]\n\n )\n\n } else {\n\n \"|||\".to_string()\n\n };\n\n write!(\n\n o,\n\n \"\\n|{}|{}|{}|{}|{}|{}|{}|||\",\n\n component,\n\n self.identifiers[i],\n\n self.n[i],\n\n self.m[i],\n\n self.sigma[i],\n\n self.epsilon_k[i],\n\n association\n", "file_path": "src/eos/parameter.rs", "rank": 90, "score": 27305.645880291828 }, { "content": " let mut epsilon_k_mix = Vec::new();\n\n\n\n let mut joback_records = Vec::new();\n\n\n\n for (i, chemical_record) in chemical_records.iter().enumerate() {\n\n let mut segment_indices = IndexMap::with_capacity(segment_records.len());\n\n let (segment_counts, bond_counts) = chemical_record.segment_and_bond_count();\n\n let count: IndexMap<_, _> = segment_counts\n\n .iter()\n\n .map(|(id, &count)| {\n\n let segment = segment_map\n\n .get(id)\n\n .ok_or_else(|| ParameterError::ComponentsNotFound(id.clone()))?;\n\n Ok((segment, count))\n\n })\n\n .collect::<Result<_, ParameterError>>()?;\n\n\n\n let mut m_i = 0.0;\n\n let mut sigma_i = 0.0;\n\n let mut epsilon_k_i = 0.0;\n", "file_path": "src/eos/parameter.rs", "rank": 91, "score": 27305.235030527456 }, { "content": "\n\n pub fn propane() -> GcPcSaftEosParameters {\n\n let pure = ChemicalRecord::new(\n\n Identifier::new(\"74-98-6\", Some(\"propane\"), None, None, None, None),\n\n vec![\"CH3\".into(), \"CH2\".into(), \"CH3\".into()],\n\n None,\n\n );\n\n GcPcSaftEosParameters::from_segments(vec![pure], vec![ch3(), ch2()], None).unwrap()\n\n }\n\n\n\n pub fn propanol() -> GcPcSaftEosParameters {\n\n let pure = ChemicalRecord::new(\n\n Identifier::new(\"71-23-8\", Some(\"1-propanol\"), None, None, None, None),\n\n vec![\"CH3\".into(), \"CH2\".into(), \"CH2\".into(), \"OH\".into()],\n\n None,\n\n );\n\n GcPcSaftEosParameters::from_segments(vec![pure], vec![ch3(), ch2(), oh()], None).unwrap()\n\n }\n\n\n\n pub fn ethanol_propanol(binary: bool) -> GcPcSaftEosParameters {\n", "file_path": "src/eos/parameter.rs", "rank": 92, "score": 27305.10228934368 }, { "content": " pub sigma: Array1<f64>,\n\n pub epsilon_k: Array1<f64>,\n\n pub bonds: IndexMap<[usize; 2], f64>,\n\n\n\n pub assoc_segment: Array1<usize>,\n\n pub n: Array1<f64>,\n\n kappa_ab: Array1<f64>,\n\n epsilon_k_ab: Array1<f64>,\n\n pub na: Array1<f64>,\n\n pub nb: Array1<f64>,\n\n\n\n pub dipole_comp: Array1<usize>,\n\n mu: Array1<f64>,\n\n pub mu2: Array1<f64>,\n\n pub m_mix: Array1<f64>,\n\n pub s_ij: Array2<f64>,\n\n pub e_k_ij: Array2<f64>,\n\n\n\n pub k_ij: Array2<f64>,\n\n pub sigma_ij: Array2<f64>,\n", "file_path": "src/eos/parameter.rs", "rank": 93, "score": 27305.09527163304 }, { "content": "\n\n let mut molarweight = Array1::zeros(chemical_records.len());\n\n let mut component_index = Vec::new();\n\n let mut identifiers = Vec::new();\n\n let mut m = Vec::new();\n\n let mut sigma = Vec::new();\n\n let mut epsilon_k = Vec::new();\n\n let mut bonds = IndexMap::with_capacity(segment_records.len());\n\n let mut assoc_segment = Vec::new();\n\n let mut n = Vec::new();\n\n let mut kappa_ab = Vec::new();\n\n let mut epsilon_k_ab = Vec::new();\n\n let mut na = Vec::new();\n\n let mut nb = Vec::new();\n\n\n\n let mut dipole_comp = Vec::new();\n\n let mut mu = Vec::new();\n\n let mut mu2 = Vec::new();\n\n let mut m_mix = Vec::new();\n\n let mut sigma_mix = Vec::new();\n", "file_path": "src/eos/parameter.rs", "rank": 94, "score": 27305.024215136196 }, { "content": " let reader = BufReader::new(File::open(file_pure)?);\n\n let chemical_records: Vec<ChemicalRecord> = serde_json::from_reader(reader)?;\n\n let mut record_map: IndexMap<_, _> = chemical_records\n\n .into_iter()\n\n .filter_map(|record| {\n\n record\n\n .identifier()\n\n .as_string(search_option)\n\n .map(|i| (i, record))\n\n })\n\n .collect();\n\n\n\n // Compare queried components and available components\n\n let available: IndexSet<String> = record_map\n\n .keys()\n\n .map(|identifier| identifier.to_string())\n\n .collect();\n\n if !queried.is_subset(&available) {\n\n let missing: Vec<String> = queried.difference(&available).cloned().collect();\n\n return Err(ParameterError::ComponentsNotFound(format!(\"{:?}\", missing)));\n", "file_path": "src/eos/parameter.rs", "rank": 95, "score": 27304.116847269925 }, { "content": " .map(|s| JobackRecord::from_segments(s)),\n\n );\n\n }\n\n\n\n // Binary interaction parameter\n\n let mut k_ij = Array2::zeros([epsilon_k.len(); 2]);\n\n if let Some(binary_segment_records) = binary_segment_records.as_ref() {\n\n let mut binary_segment_records_map = IndexMap::new();\n\n for binary_record in binary_segment_records {\n\n binary_segment_records_map.insert(\n\n (binary_record.id1.clone(), binary_record.id2.clone()),\n\n binary_record.model_record,\n\n );\n\n binary_segment_records_map.insert(\n\n (binary_record.id2.clone(), binary_record.id1.clone()),\n\n binary_record.model_record,\n\n );\n\n }\n\n for (i, id1) in identifiers.iter().enumerate() {\n\n for (j, id2) in identifiers.iter().cloned().enumerate() {\n", "file_path": "src/eos/parameter.rs", "rank": 96, "score": 27303.06918592327 }, { "content": " let mut mu2_i = 0.0;\n\n\n\n for (segment, count) in count.iter() {\n\n segment_indices.insert(segment.identifier.clone(), m.len());\n\n\n\n molarweight[i] += segment.molarweight * count;\n\n\n\n component_index.push(i);\n\n identifiers.push(segment.identifier.clone());\n\n m.push(segment.model_record.m * count);\n\n sigma.push(segment.model_record.sigma);\n\n epsilon_k.push(segment.model_record.epsilon_k);\n\n\n\n if let (Some(k), Some(e)) = (\n\n segment.model_record.kappa_ab,\n\n segment.model_record.epsilon_k_ab,\n\n ) {\n\n assoc_segment.push(m.len() - 1);\n\n n.push(*count);\n\n kappa_ab.push(k);\n", "file_path": "src/eos/parameter.rs", "rank": 97, "score": 27302.809952960553 }, { "content": " if component_index[i] != component_index[j] {\n\n if let Some(k) = binary_segment_records_map.get(&(id1.clone(), id2)) {\n\n k_ij[(i, j)] = *k;\n\n }\n\n }\n\n }\n\n }\n\n }\n\n\n\n // Combining rules dispersion\n\n let sigma_ij =\n\n Array2::from_shape_fn([sigma.len(); 2], |(i, j)| 0.5 * (sigma[i] + sigma[j]));\n\n let epsilon_k_ij = Array2::from_shape_fn([epsilon_k.len(); 2], |(i, j)| {\n\n (epsilon_k[i] * epsilon_k[j]).sqrt()\n\n }) * (1.0 - &k_ij);\n\n\n\n // Combining rules polar\n\n let s_ij = Array2::from_shape_fn([dipole_comp.len(); 2], |(i, j)| {\n\n 0.5 * (sigma_mix[i] + sigma_mix[j])\n\n });\n", "file_path": "src/eos/parameter.rs", "rank": 98, "score": 27302.56098059707 }, { "content": " epsilon_k: Array1::from_vec(epsilon_k),\n\n bonds,\n\n assoc_segment: Array1::from_vec(assoc_segment),\n\n kappa_ab: Array1::from_vec(kappa_ab),\n\n epsilon_k_ab: Array1::from_vec(epsilon_k_ab),\n\n na: Array1::from_vec(na),\n\n nb: Array1::from_vec(nb),\n\n dipole_comp: Array1::from_vec(dipole_comp),\n\n mu: Array1::from_vec(mu),\n\n mu2: Array1::from_vec(mu2),\n\n m_mix: Array1::from_vec(m_mix),\n\n s_ij,\n\n e_k_ij,\n\n k_ij,\n\n sigma_ij,\n\n epsilon_k_ij,\n\n sigma3_kappa_aibj,\n\n epsilon_k_aibj,\n\n chemical_records,\n\n segment_records,\n", "file_path": "src/eos/parameter.rs", "rank": 99, "score": 27301.722959683197 } ]
Rust
rust-kernel-rdma/KRdmaKit/src/qp/rc_op.rs
Hf7WCdtO/KRCore
52369924ba175419912a274634d368d478dda501
use rust_kernel_rdma_base::*; use crate::qp::{DoorbellHelper, RC}; use core::option::Option; use linux_kernel_module::bindings::*; use linux_kernel_module::{Error}; use alloc::sync::Arc; #[allow(unused_imports)] pub struct RCOp<'a> { qp: &'a Arc<RC>, } impl<'a> RCOp<'a> { pub fn new(qp: &'a Arc<RC>) -> Self { Self { qp, } } #[inline] pub fn get_qp_status(&self) -> Option<u32> { self.qp.get_status() } } impl<'a> RCOp<'a> { #[inline] pub fn push_with_imm( &mut self, op: u32, local_ptr: u64, lkey: u32, sz: usize, remote_addr: u64, rkey: u32, imm_data: u32, send_flag: i32, ) -> linux_kernel_module::KernelResult<()> { let mut wr: ib_rdma_wr = Default::default(); let mut sge: ib_sge = Default::default(); sge.addr = local_ptr; sge.length = sz as u32; sge.lkey = lkey; wr.wr.opcode = op; wr.wr.send_flags = send_flag; wr.wr.ex.imm_data = imm_data; wr.remote_addr = remote_addr; wr.rkey = rkey; self.post_send(sge, wr) } #[inline] pub fn push( &mut self, op: u32, local_ptr: u64, lkey: u32, sz: usize, remote_addr: u64, rkey: u32, send_flag: i32, ) -> linux_kernel_module::KernelResult<()> { self.push_with_imm(op, local_ptr, lkey, sz, remote_addr, rkey, 0, send_flag) } #[inline] pub fn pop(&mut self) -> Option<*mut ib_wc> { let mut wc: ib_wc = Default::default(); let ret = unsafe { bd_ib_poll_cq(self.qp.get_cq(), 1, &mut wc as *mut ib_wc) }; if ret < 0 { return None; } else if ret == 1 { if wc.status != 0 && wc.status != 5 { linux_kernel_module::println!("rc poll cq error, wc_status:{}", wc.status); } return Some(&mut wc as *mut ib_wc); } None } #[inline] fn post_send( &mut self, mut sge: ib_sge, mut wr: ib_rdma_wr, ) -> linux_kernel_module::KernelResult<()> { wr.wr.sg_list = &mut sge as *mut _; wr.wr.num_sge = 1; let mut bad_wr: *mut ib_send_wr = core::ptr::null_mut(); let err = unsafe { bd_ib_post_send( self.qp.get_qp(), &mut wr.wr as *mut _, &mut bad_wr as *mut _, ) }; if err != 0 { return Err(Error::from_kernel_errno(err)); } Ok(()) } #[inline] pub fn wait_til_comp(&mut self) -> Option<*mut ib_wc> { loop { let ret = self.pop(); if ret.is_some() { return ret; } } } } impl<'a> RCOp<'a> { #[inline] pub fn read(&mut self, local_ptr: u64, lkey: u32, sz: usize, remote_addr: u64, rkey: u32, ) -> linux_kernel_module::KernelResult<Option<*mut ib_wc>> { self.push(ib_wr_opcode::IB_WR_RDMA_READ, local_ptr, lkey, sz, remote_addr, rkey, ib_send_flags::IB_SEND_SIGNALED) .and_then(|()| Ok(self.wait_til_comp())) } #[inline] pub fn write(&mut self, local_ptr: u64, lkey: u32, sz: usize, remote_addr: u64, rkey: u32, ) -> linux_kernel_module::KernelResult<Option<*mut ib_wc>> { self.push(ib_wr_opcode::IB_WR_RDMA_WRITE, local_ptr, lkey, sz, remote_addr, rkey, ib_send_flags::IB_SEND_SIGNALED) .and_then(|()| Ok(self.wait_til_comp())) } #[inline] pub fn send(&mut self, local_ptr: u64, lkey: u32, sz: usize, remote_addr: u64, rkey: u32, ) -> linux_kernel_module::KernelResult<Option<*mut ib_wc>> { self.push(ib_wr_opcode::IB_WR_SEND, local_ptr, lkey, sz, remote_addr, rkey, ib_send_flags::IB_SEND_SIGNALED) .and_then(|()| Ok(self.wait_til_comp())) } } impl RCOp<'_> { #[inline] pub fn post_doorbell( &mut self, doorbell: &mut DoorbellHelper, ) -> linux_kernel_module::KernelResult<()> { doorbell.freeze(); let ret = self.post_send(doorbell.sges[0], doorbell.wrs[0]); doorbell.freeze_done(); ret } }
use rust_kernel_rdma_base::*; use crate::qp::{DoorbellHelper, RC}; use core::option::Option; use linux_kernel_module::bindings::*; use linux_kernel_module::{Error}; use alloc::sync::Arc; #[allow(unused_imports)] pub struct RCOp<'a> { qp: &'a Arc<RC>, } impl<'a> RCOp<'a> { pub fn new(qp: &'a Arc<RC>) -> Self { Self { qp, } } #[inline] pub fn get_qp_status(&self) -> Option<u32> { self.qp.get_status() } } impl<'a> RCOp<'a> { #[inline] pub fn push_with_imm( &mut self, op: u32, local_ptr: u64, lkey: u32, sz: usize, remote_addr: u64, rkey: u32, imm_data: u32, send_flag: i32, ) -> linux_kernel_module::KernelResult<()> { let mut wr: ib_rdma_wr = Default::default(); let mut sge: ib_sge = Default::default(); sge.addr = local_ptr; sge.length = sz as u32; sge.lkey = lkey; wr.wr.opcode = op; wr.wr.send_flags = send_flag; wr.wr.ex.imm_data = imm_data; wr.remote_addr = remote_addr; wr.rkey = rkey; self.post_send(sge, wr) } #[inline] pub fn push( &mut self, op: u32, local_ptr: u64, lkey: u32, sz: usize, remote_addr: u64, rkey: u32, send_flag: i32, ) -> linux_kernel_module::KernelResult<()> { self.push_with_imm(op, local_ptr, lkey, sz, remote_addr, rkey, 0, send_flag) } #[inline] pub fn pop(&mut self) -> Option<*mut ib_wc> { let mut wc: ib_wc = Default::default(); let ret = unsafe { bd_ib_poll_cq(self.qp.get_cq(), 1, &mut wc as *mut ib_wc) }; if ret < 0 { return None; } else if ret == 1 { if wc.status != 0 && wc.status != 5 { linux_kernel_module::println!("rc poll cq error, wc_status:{}", wc.status); } return Some(&mut wc as *mut ib_wc); }
WR_RDMA_READ, local_ptr, lkey, sz, remote_addr, rkey, ib_send_flags::IB_SEND_SIGNALED) .and_then(|()| Ok(self.wait_til_comp())) } #[inline] pub fn write(&mut self, local_ptr: u64, lkey: u32, sz: usize, remote_addr: u64, rkey: u32, ) -> linux_kernel_module::KernelResult<Option<*mut ib_wc>> { self.push(ib_wr_opcode::IB_WR_RDMA_WRITE, local_ptr, lkey, sz, remote_addr, rkey, ib_send_flags::IB_SEND_SIGNALED) .and_then(|()| Ok(self.wait_til_comp())) } #[inline] pub fn send(&mut self, local_ptr: u64, lkey: u32, sz: usize, remote_addr: u64, rkey: u32, ) -> linux_kernel_module::KernelResult<Option<*mut ib_wc>> { self.push(ib_wr_opcode::IB_WR_SEND, local_ptr, lkey, sz, remote_addr, rkey, ib_send_flags::IB_SEND_SIGNALED) .and_then(|()| Ok(self.wait_til_comp())) } } impl RCOp<'_> { #[inline] pub fn post_doorbell( &mut self, doorbell: &mut DoorbellHelper, ) -> linux_kernel_module::KernelResult<()> { doorbell.freeze(); let ret = self.post_send(doorbell.sges[0], doorbell.wrs[0]); doorbell.freeze_done(); ret } }
None } #[inline] fn post_send( &mut self, mut sge: ib_sge, mut wr: ib_rdma_wr, ) -> linux_kernel_module::KernelResult<()> { wr.wr.sg_list = &mut sge as *mut _; wr.wr.num_sge = 1; let mut bad_wr: *mut ib_send_wr = core::ptr::null_mut(); let err = unsafe { bd_ib_post_send( self.qp.get_qp(), &mut wr.wr as *mut _, &mut bad_wr as *mut _, ) }; if err != 0 { return Err(Error::from_kernel_errno(err)); } Ok(()) } #[inline] pub fn wait_til_comp(&mut self) -> Option<*mut ib_wc> { loop { let ret = self.pop(); if ret.is_some() { return ret; } } } } impl<'a> RCOp<'a> { #[inline] pub fn read(&mut self, local_ptr: u64, lkey: u32, sz: usize, remote_addr: u64, rkey: u32, ) -> linux_kernel_module::KernelResult<Option<*mut ib_wc>> { self.push(ib_wr_opcode::IB_
random
[ { "content": "#[inline]\n\nfn create_ib_qp(config: &Config, pd: *mut ib_pd, qp_type: u32, cq: *mut ib_cq, recv_cq: *mut ib_cq, srq: *mut ib_srq) -> *mut ib_qp {\n\n let mut qp_attr: ib_qp_init_attr = Default::default();\n\n qp_attr.cap.max_send_wr = config.max_send_wr_sz as u32;\n\n qp_attr.cap.max_recv_wr = config.max_recv_wr_sz as u32;\n\n qp_attr.cap.max_recv_sge = config.max_recv_sge as u32;\n\n qp_attr.cap.max_send_sge = config.max_send_sge as u32;\n\n qp_attr.cap.max_inline_data = 64 as u32;\n\n qp_attr.sq_sig_type = ib_sig_type::IB_SIGNAL_REQ_WR;\n\n qp_attr.qp_type = qp_type;\n\n qp_attr.send_cq = cq;\n\n qp_attr.recv_cq = recv_cq;\n\n qp_attr.srq = srq;\n\n\n\n unsafe { ib_create_qp(pd, &mut qp_attr as *mut ib_qp_init_attr) }\n\n}\n\n\n\n\n\n/// Fetch the status of one target qp\n", "file_path": "rust-kernel-rdma/KRdmaKit/src/qp/mod.rs", "rank": 0, "score": 466219.8060344838 }, { "content": "#[inline]\n\npub fn create_dc_qp(ctx: &RContext, srq: *mut ib_srq, recv_cq: *mut ib_cq) -> (*mut ib_qp, *mut ib_cq, *mut ib_cq) {\n\n let pd = ctx.get_pd();\n\n if pd.is_null() {\n\n println!(\"[dct] err creating qp pd\");\n\n return (\n\n core::ptr::null_mut(),\n\n core::ptr::null_mut(),\n\n core::ptr::null_mut(),\n\n );\n\n }\n\n\n\n let mut cq_attr: ib_cq_init_attr = Default::default();\n\n cq_attr.cqe = 128;\n\n\n\n let cq = create_ib_cq(ctx.get_raw_dev(), &mut cq_attr as *mut _);\n\n if cq.is_null() {\n\n println!(\"[dct] qp null cq\");\n\n return (\n\n core::ptr::null_mut(),\n\n core::ptr::null_mut(),\n", "file_path": "rust-kernel-rdma/KRdmaKit/src/qp/mod.rs", "rank": 1, "score": 464611.8399973218 }, { "content": "#[inline]\n\npub fn handle_pop_ret(pop_ret: Option<*mut ib_wc>,\n\n req: &mut req_t,\n\n wc_len: usize,\n\n payload_sz: u32) -> u32 {\n\n match pop_ret {\n\n Some(wc) => {\n\n\n\n // assemble each wc element\n\n let wc_sz: u64 = core::mem::size_of::<ib_wc>() as u64;\n\n for i in 0..(wc_len as u64) {\n\n // assemble the wc\n\n let mut user_wc: user_wc_t = Default::default();\n\n let wc = unsafe { *((wc as u64 + i * wc_sz) as *const ib_wc) };\n\n user_wc.wc_op = wc.opcode;\n\n let va = wc.get_wr_id() as u64;\n\n user_wc.wc_wr_id = wc.get_wr_id() as u64;\n\n user_wc.wc_status = wc.status;\n\n user_wc.imm_data = unsafe { wc.ex.imm_data } as u32;\n\n unsafe {\n\n rust_kernel_linux_util::bindings::memcpy(\n", "file_path": "KRdmaKit-syscall/src/core.rs", "rank": 2, "score": 458854.8100402253 }, { "content": "#[inline]\n\npub fn get_qp_status(ib_qp: *mut ib_qp) -> Option<u32> {\n\n let mut attr: ib_qp_attr = Default::default();\n\n let mut init_attr: ib_qp_init_attr = Default::default();\n\n\n\n // query\n\n let ret = unsafe {\n\n ib_query_qp(\n\n ib_qp,\n\n &mut attr as *mut ib_qp_attr,\n\n ib_qp_attr_mask::IB_QP_STATE,\n\n &mut init_attr as *mut ib_qp_init_attr,\n\n )\n\n };\n\n\n\n if ret != 0 {\n\n return None;\n\n }\n\n\n\n Some(attr.qp_state)\n\n}\n\n\n", "file_path": "rust-kernel-rdma/KRdmaKit/src/qp/mod.rs", "rank": 3, "score": 452172.54415150254 }, { "content": "#[inline]\n\npub fn send_reg_mr(qp: *mut ib_qp, mr: *mut ib_mr, access_flags: u32, whether_signaled: bool) -> c_types::c_int {\n\n let rkey = unsafe { (*mr).rkey };\n\n let mut wr: ib_reg_wr = Default::default();\n\n\n\n wr.wr.opcode = ib_wr_opcode::IB_WR_REG_MR;\n\n wr.wr.num_sge = 0;\n\n wr.wr.send_flags = if whether_signaled { ib_send_flags::IB_SEND_SIGNALED } else { 0 };\n\n wr.mr = mr;\n\n wr.key = rkey;\n\n wr.access = access_flags as i32;\n\n let mut bad_wr: *mut ib_send_wr = core::ptr::null_mut();\n\n\n\n unsafe {\n\n bd_ib_post_send(qp, &mut wr.wr as *mut _,\n\n &mut bad_wr as *mut _, )\n\n }\n\n}\n\n\n\n\n\nconst DC_KEY: u64 = 73;\n\n\n\n\n\n// this function has memory leakage, but its fine since it is in the unittest\n", "file_path": "rust-kernel-rdma/KRdmaKit/src/qp/mod.rs", "rank": 4, "score": 437061.1890109604 }, { "content": "#[inline]\n\npub fn pop_recv(core_id: usize, pop_cnt: usize, offset: usize) -> (Option<*mut ib_wc>, usize) {\n\n let ctrl = get_global_rctrl(core_id);\n\n\n\n let recv_cq = ctrl.get_recv_cq();\n\n let recv = unsafe { Arc::get_mut_unchecked(ctrl.get_recv_buffer()) };\n\n recv.pop_recvs(recv_cq, pop_cnt, offset).unwrap()\n\n}\n\n\n\n\n", "file_path": "KRdmaKit-syscall/src/core.rs", "rank": 5, "score": 427122.63642619736 }, { "content": "#[inline]\n\npub fn op_code_table(op: u32) -> u32 {\n\n use KRdmaKit::rust_kernel_rdma_base::*;\n\n use crate::bindings::*;\n\n match op {\n\n lib_r_req::Read => ib_wr_opcode::IB_WR_RDMA_READ,\n\n lib_r_req::Write => ib_wr_opcode::IB_WR_RDMA_WRITE,\n\n lib_r_req::Send => ib_wr_opcode::IB_WR_SEND,\n\n lib_r_req::SendImm => ib_wr_opcode::IB_WR_SEND_WITH_IMM,\n\n lib_r_req::WriteImm => ib_wr_opcode::IB_WR_RDMA_WRITE_WITH_IMM,\n\n _ => unimplemented!(),\n\n }\n\n}\n\n\n\nimpl Drop for KRdmaKitSyscallModule {\n\n fn drop(&mut self) {\n\n println!(\"Goodbye KRdma syscall module!\");\n\n }\n\n}\n\n\n\nlinux_kernel_module::kernel_module!(\n\n KRdmaKitSyscallModule,\n\n author: b\"anonymous\",\n\n description: b\"KRdmaKit syscall tier\",\n\n license: b\"GPL\"\n\n);\n", "file_path": "KRdmaKit-syscall/src/lib.rs", "rank": 6, "score": 426301.1635615169 }, { "content": "/// Main func for qp connection in kernel space.\n\n/// The runtime latency of this function should be profiled in a more detailed way.\n\npub fn qp_connect(vid: usize, port: usize, path_rec: &sa_path_rec) -> KernelResult<Option<Arc<RC>>> {\n\n let remote_service_id = port as u64;\n\n let ctrl = get_global_rctrl(remote_service_id as usize);\n\n let ctx = ctrl.get_context();\n\n // create local qp\n\n let rc = RC::new_with_srq(\n\n Default::default(),\n\n ctx, null_mut(),\n\n null_mut(),\n\n ctrl.get_recv_cq(),\n\n );\n\n if rc.is_some() {\n\n let mut qp = rc.unwrap();\n\n let mrc = unsafe { Arc::get_mut_unchecked(&mut qp) };\n\n // connect handshake(param `vid` is useless)\n\n mrc.connect(vid as u64, *path_rec, remote_service_id)?;\n\n return Ok(Some(qp));\n\n }\n\n Ok(None)\n\n}\n\n\n\n\n", "file_path": "KRdmaKit-syscall/src/core.rs", "rank": 7, "score": 403858.64189286804 }, { "content": "#[inline]\n\npub fn bring_dc_to_ready(qp: *mut ib_qp) -> bool {\n\n if !unsafe { bring_dc_to_init(qp) } {\n\n println!(\"[dct] err to re-bring to init.\");\n\n return false;\n\n }\n\n if !unsafe { bring_dc_to_rtr(qp) } {\n\n println!(\"[dct] err to re-bring to rtr.\");\n\n return false;\n\n }\n\n if !unsafe { bring_dc_to_rts(qp) } {\n\n println!(\"[dct] err to re-bring to rts.\");\n\n return false;\n\n }\n\n return true;\n\n}\n\n\n\n#[inline]\n\npub unsafe fn bring_dc_to_init(qp: *mut ib_qp) -> bool {\n\n let mut attr: ib_qp_attr = Default::default();\n\n let mut mask: linux_kernel_module::c_types::c_int = ib_qp_attr_mask::IB_QP_STATE;\n", "file_path": "rust-kernel-rdma/KRdmaKit/src/qp/mod.rs", "rank": 8, "score": 386292.1433961146 }, { "content": "#[inline]\n\npub fn get_global_test_mem_pa(idx: usize) -> u64 {\n\n let len = GLOBAL_MEM.get_ref().len();\n\n { &mut GLOBAL_MEM.get_mut()[idx % len] }.get_dma_buf()\n\n}\n\n\n", "file_path": "KRdmaKit-syscall/src/client.rs", "rank": 9, "score": 360808.9233564251 }, { "content": "#[inline]\n\npub fn create_dct_server(pd: *mut ib_pd, device: *mut ib_device) -> *mut ib_dct {\n\n let mut cq_attr: ib_cq_init_attr = Default::default();\n\n cq_attr.cqe = 128;\n\n\n\n let cq = create_ib_cq(device, &mut cq_attr as *mut _);\n\n\n\n\n\n if cq.is_null() {\n\n println!(\"[dct] err dct server cq null\");\n\n return core::ptr::null_mut();\n\n }\n\n\n\n // create srq\n\n let mut cq_attr: ib_srq_init_attr = Default::default();\n\n cq_attr.attr.max_wr = 128;\n\n cq_attr.attr.max_sge = 1;\n\n\n\n let srq = unsafe { ib_create_srq(pd, &mut cq_attr as _) };\n\n\n\n if srq.is_null() {\n", "file_path": "rust-kernel-rdma/KRdmaKit/src/qp/mod.rs", "rank": 10, "score": 360084.4312719493 }, { "content": "#[inline]\n\npub fn post_recv(core_id: usize, post_cnt: usize, vid: usize) -> u32 {\n\n let ctrl = get_global_rctrl(core_id);\n\n let qp = ctrl.get_trc(vid).unwrap().get_qp();\n\n let recv_buffer = ctrl.get_recv_buffer();\n\n let recv = unsafe { Arc::get_mut_unchecked(recv_buffer) };\n\n return match recv.post_recvs(qp, core::ptr::null_mut(), post_cnt) {\n\n Ok(_) => {\n\n reply_status::ok\n\n }\n\n Err(_) => reply_status::err\n\n };\n\n}\n\n\n", "file_path": "KRdmaKit-syscall/src/core.rs", "rank": 11, "score": 355664.0710599885 }, { "content": "#[inline]\n\npub fn create_ib_ah(pd: *mut ib_pd, lid: u16, gid: ib_gid) -> *mut ib_ah {\n\n let mut ah_attr: rdma_ah_attr = Default::default();\n\n ah_attr.type_ = rdma_ah_attr_type::RDMA_AH_ATTR_TYPE_IB;\n\n\n\n unsafe { bd_rdma_ah_set_dlid(&mut ah_attr, lid as u32); }\n\n ah_attr.sl = 0;\n\n ah_attr.port_num = 1;\n\n\n\n unsafe {\n\n ah_attr.grh.dgid.global.subnet_prefix = gid.global.subnet_prefix;\n\n ah_attr.grh.dgid.global.interface_id = gid.global.interface_id;\n\n }\n\n\n\n let res = unsafe { rdma_create_ah_wrapper(pd, &mut ah_attr as _) };\n\n\n\n // maybe, we should wrapper ptr_is_err because this function is 100% safe\n\n if unsafe { ptr_is_err(res as _) } > 0 {\n\n return core::ptr::null_mut();\n\n }\n\n res\n\n}\n\n\n", "file_path": "rust-kernel-rdma/KRdmaKit/src/qp/mod.rs", "rank": 12, "score": 340542.59299386904 }, { "content": "#[inline]\n\npub fn get_global_rcontext(idx: usize) -> &'static mut RContext<'static> {\n\n let len = ALLRCONTEXTS.len();\n\n let ctx = &mut ALLRCONTEXTS.get_mut()[idx % len];\n\n return ctx;\n\n}\n\n\n", "file_path": "KRdmaKit-syscall/src/client.rs", "rank": 13, "score": 340347.6572164519 }, { "content": "#[inline]\n\npub fn get_rpc_client(idx: usize) -> &'static mut RPCClient<'static, RPC_BUFFER_N> {\n\n let len = RPC_CLIENTS.len();\n\n &mut RPC_CLIENTS.get_mut()[idx % len]\n\n}\n\n\n", "file_path": "KRdmaKit-syscall/src/client.rs", "rank": 14, "score": 330970.29328382213 }, { "content": "#[inline]\n\npub fn get_global_rctrl(idx: usize) -> &'static mut Pin<Box<RCtrl<'static>>> {\n\n let len = RCTRL.len();\n\n &mut RCTRL.get_mut()[idx % len]\n\n}\n\n\n", "file_path": "KRdmaKit-syscall/src/client.rs", "rank": 15, "score": 329778.13380939426 }, { "content": "#[inline]\n\npub fn get_bind_ctrl(port: usize) -> &'static mut Pin<Box<RCtrl<'static>>> {\n\n get_global_rctrl(port * 2)\n\n}\n\n\n\n\n", "file_path": "KRdmaKit-syscall/src/client.rs", "rank": 16, "score": 329778.13380939426 }, { "content": "fn wait_one_cq(cq: *mut ib_cq) {\n\n let mut wc: ib_wc = Default::default();\n\n let mut run_cnt = 0;\n\n loop {\n\n let ret = unsafe { bd_ib_poll_cq(cq, 1, &mut wc as *mut ib_wc) };\n\n if ret < 0 {\n\n linux_kernel_module::println!(\"ret < 0\");\n\n break;\n\n } else if ret == 1 {\n\n if wc.status != 0 && wc.status != 5 {\n\n linux_kernel_module::println!(\"rc poll cq error, wc_status:{}\", wc.status);\n\n }\n\n break;\n\n } else {\n\n run_cnt += 1;\n\n if run_cnt > 10000 {\n\n linux_kernel_module::println!(\"timeout\");\n\n break;\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "rust-kernel-rdma/KRdmaKit/unitests/rfork/src/frwr.rs", "rank": 17, "score": 311729.31154907483 }, { "content": "fn wait_one_cq(cq: *mut ib_cq) {\n\n let mut wc: ib_wc = Default::default();\n\n let mut run_cnt = 0;\n\n loop {\n\n let ret = unsafe { bd_ib_poll_cq(cq, 1, &mut wc as *mut ib_wc) };\n\n if ret < 0 {\n\n linux_kernel_module::println!(\"ret < 0\");\n\n break;\n\n } else if ret == 1 {\n\n if wc.status != 0 && wc.status != 5 {\n\n linux_kernel_module::println!(\"rc poll cq error, wc_status:{}\", wc.status);\n\n }\n\n break;\n\n } else {\n\n run_cnt += 1;\n\n if run_cnt > 10000 {\n\n linux_kernel_module::println!(\"timeout\");\n\n break;\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "rust-kernel-rdma/KRdmaKit/unitests/reg_mr/src/lib.rs", "rank": 18, "score": 310497.6772806411 }, { "content": "#[inline]\n\npub fn random_split(total: u64, shard_num: u64) -> Vec<u64> {\n\n let mut rand = random::FastRandom::new(0xdeadbeaf);\n\n let mut result: Vec<u64> = Vec::with_capacity(shard_num as usize);\n\n let mut sum = 0 as u64;\n\n for _ in 0..shard_num - 1 {\n\n let tmp = total - sum;\n\n let mut val = rand.get_next() % tmp;\n\n result.push(val);\n\n sum += val;\n\n }\n\n result.push(total - sum);\n\n result\n\n}\n\n\n\nimpl linux_kernel_module::KernelModule for RegMRTestModule {\n\n fn init() -> linux_kernel_module::KernelResult<Self> {\n\n ctx_init();\n\n // bench_frwr(); // FRWR\n\n // bench_pin();\n\n // bench_vma();\n", "file_path": "rust-kernel-rdma/KRdmaKit/unitests/rfork/src/lib.rs", "rank": 19, "score": 302908.6219936725 }, { "content": "/// Return back the reply length in bytes\n\ntype RpcHandlerT = fn(req_addr: u64, reply_addr: u64) -> u32;\n\n\n\n\n\n/// RPC Client based on UD\n\n///\n\n/// TODO: maybe we could extend to DC / RC ?\n\npub struct RPCClient<'a, const N: usize> {\n\n queue_pair: &'a Arc<UD>,\n\n ctx: &'a RContext<'a>,\n\n endpoint: EndPoint,\n\n\n\n send_buffer: RMemPhy,\n\n recv_buffer: RMemPhy,\n\n recv_helper: Arc<RecvHelper<N>>,\n\n\n\n reg_handlers: HashMap<u8, RpcHandlerT>,\n\n listened: bool,\n\n}\n\n\n\nimpl<'a, const N: usize> RPCClient<'a, N> {\n", "file_path": "KRdmaKit-syscall/src/rpc/client.rs", "rank": 20, "score": 295492.02494323323 }, { "content": "/// Return back the reply length in bytes\n\ntype RpcHandlerT = fn(req_addr: u64, reply_addr: u64) -> u32;\n\n\n\n\n\n/// RPC Client based on UD\n\n///\n\n/// TODO: maybe we could extend to DC / RC ?\n\npub struct RPCClient<'a, const N: usize> {\n\n queue_pair: &'a Arc<UD>,\n\n ctx: &'a RContext<'a>,\n\n endpoint: &'a EndPoint,\n\n\n\n send_buffer: RMemPhy,\n\n recv_buffer: RMemPhy,\n\n recv_helper: Arc<RecvHelper<N>>,\n\n\n\n reg_handlers: HashMap<u8, RpcHandlerT>,\n\n listened: bool,\n\n}\n\n\n\nimpl<'a, const N: usize> RPCClient<'a, N> {\n", "file_path": "rust-kernel-rdma/KRdmaKit/unitests/rpc/src/rpc.rs", "rank": 21, "score": 291639.58202354633 }, { "content": "pub fn demo_use_two_nics() {\n\n use crate::ib_wc;\n\n let ctx: &mut RContext = &mut ALLRCONTEXTS.get_mut()[0];\n\n let ctx_1: &mut RContext = &mut ALLRCONTEXTS.get_mut()[1];\n\n let sa_client = &mut SA_CLIENT.get_mut();\n\n\n\n // preparation\n\n let mut explorer = IBExplorer::new();\n\n\n\n let gid_addr = ctx.get_gid_as_string();\n\n let _ = explorer.resolve(1, ctx, &gid_addr, sa_client.get_inner_sa_client());\n\n\n\n let path_res = explorer.get_path_result().unwrap();\n\n // param\n\n let remote_service_id = 50;\n\n let qd_hint = 73;\n\n\n\n let mut ctrl = RCtrl::create(remote_service_id, &mut ALLRCONTEXTS.get_mut()[0]).unwrap();\n\n // end of preparation\n\n // let cm = SidrCM::new(ctx, core::ptr::null_mut());\n", "file_path": "rust-kernel-rdma/KRdmaKit/unitests/rfork/src/two_nic.rs", "rank": 22, "score": 288753.6215825609 }, { "content": "static void\n\nmlx5_send_wr_set_sge_rc_uc(struct ibv_qp_ex *ibqp, uint32_t lkey,\n\n\t\t\t uint64_t addr, uint32_t length)\n\n{\n\n\tstruct mlx5_qp *mqp = to_mqp((struct ibv_qp *)ibqp);\n\n\n\n\t_mlx5_send_wr_set_sge(mqp, lkey, addr, length);\n\n\t_common_wqe_finilize(mqp);\n", "file_path": "mlnx-ofed-4.9-driver/rdma-core-50mlnx1/providers/mlx5/qp.c", "rank": 23, "score": 287312.43589922565 }, { "content": "#[inline]\n\npub fn get_global_sa_client() -> &'static mut SAClient {\n\n SA_CLIENT.get_mut()\n\n}\n\n\n", "file_path": "KRdmaKit-syscall/src/client.rs", "rank": 24, "score": 285528.2577175508 }, { "content": "static void\n\nmlx5_send_wr_set_inline_data_rc_uc(struct ibv_qp_ex *ibqp, void *addr,\n\n\t\t\t\t size_t length)\n\n{\n\n\tstruct mlx5_qp *mqp = to_mqp((struct ibv_qp *)ibqp);\n\n\n\n\t_mlx5_send_wr_set_inline_data(mqp, addr, length);\n\n\t_common_wqe_finilize(mqp);\n", "file_path": "mlnx-ofed-4.9-driver/rdma-core-50mlnx1/providers/mlx5/qp.c", "rank": 25, "score": 285506.6880102676 }, { "content": "static void\n\nmlx5_send_wr_set_sge_list_rc_uc(struct ibv_qp_ex *ibqp, size_t num_sge,\n\n\t\t\t\tconst struct ibv_sge *sg_list)\n\n{\n\n\tstruct mlx5_qp *mqp = to_mqp((struct ibv_qp *)ibqp);\n\n\n\n\t_mlx5_send_wr_set_sge_list(mqp, num_sge, sg_list);\n\n\t_common_wqe_finilize(mqp);\n", "file_path": "mlnx-ofed-4.9-driver/rdma-core-50mlnx1/providers/mlx5/qp.c", "rank": 26, "score": 285500.0684744517 }, { "content": "#[inline]\n\npub fn get_global_rctrl_len() -> usize {\n\n RCTRL.len()\n\n}\n\n\n", "file_path": "KRdmaKit-syscall/src/client.rs", "rank": 27, "score": 283833.28235310136 }, { "content": "static void\n\nmlx5_send_wr_set_inline_data_list_rc_uc(struct ibv_qp_ex *ibqp,\n\n\t\t\t\t\tsize_t num_buf,\n\n\t\t\t\t\tconst struct ibv_data_buf *buf_list)\n\n{\n\n\tstruct mlx5_qp *mqp = to_mqp((struct ibv_qp *)ibqp);\n\n\n\n\t_mlx5_send_wr_set_inline_data_list(mqp, num_buf, buf_list);\n\n\t_common_wqe_finilize(mqp);\n", "file_path": "mlnx-ofed-4.9-driver/rdma-core-50mlnx1/providers/mlx5/qp.c", "rank": 28, "score": 283717.0005986171 }, { "content": "#[inline]\n\npub fn get_global_meta_kv_mem() -> &'static mut RMemPhy {\n\n &mut GLOBAL_MEM.get_mut()[1]\n\n}\n\n\n\n// we default use the nic_0\n", "file_path": "KRdmaKit-syscall/src/client.rs", "rank": 29, "score": 282567.22597532463 }, { "content": "#[inline]\n\npub fn get_global_test_mem_len() -> usize {\n\n GLOBAL_MEM.get_ref().len()\n\n}\n\n\n", "file_path": "KRdmaKit-syscall/src/client.rs", "rank": 30, "score": 282281.9756282196 }, { "content": "/// Test case for RC qp state change\n\nfn test_case_rc_1() {\n\n let ctx: &mut RContext = &mut ALLRCONTEXTS.get_mut()[0];\n\n // sa client\n\n println!(\"sa client registered\");\n\n\n\n\n\n let rc = RC::new(ctx, core::ptr::null_mut(), null_mut());\n\n if rc.is_some() {\n\n println!(\"create RC success\");\n\n // check field getter\n\n let mut rc = rc.unwrap();\n\n let mrc = unsafe { Arc::get_mut_unchecked(&mut rc) };\n\n\n\n println!(\"[1] state:{}\", get_qp_status(mrc.get_qp()).unwrap());\n\n }\n\n}\n\n\n", "file_path": "rust-kernel-rdma/KRdmaKit/unitests/qp/src/lib.rs", "rank": 31, "score": 269084.58170586854 }, { "content": "// path resolve\n\nfn test_case_rc_3() {\n\n println!(\">>>>>> start [test_case_rc_3] <<<<<<<\");\n\n let ctx: &mut RContext = &mut ALLRCONTEXTS.get_mut()[0];\n\n let sa_client = &mut SA_CLIENT.get_mut();\n\n let mut explorer = IBExplorer::new();\n\n let remote_service_id = 50;\n\n let qd_hint = 73;\n\n\n\n let gid_addr = ctx.get_gid_as_string();\n\n let _ = explorer.resolve(1, ctx, &gid_addr, sa_client.get_inner_sa_client());\n\n\n\n // get path\n\n let boxed_ctx = Box::pin(ctx);\n\n // thus the path resolver could be split out of other module\n\n let path_res = explorer.get_path_result().unwrap();\n\n println!(\"finish path get\");\n\n // create Ctrl. serve for cm handshakes\n\n let ctrl =\n\n RCtrl::create(remote_service_id, &mut ALLRCONTEXTS.get_mut()[0]).unwrap();\n\n\n", "file_path": "rust-kernel-rdma/KRdmaKit/unitests/qp/src/lib.rs", "rank": 32, "score": 269071.14190493786 }, { "content": "// test for inner completion waiting\n\nfn test_case_rc_2() {\n\n let ctx: &mut RContext = &mut ALLRCONTEXTS.get_mut()[0];\n\n // sa client\n\n let rc = RC::new(ctx, core::ptr::null_mut(), null_mut());\n\n if rc.is_some() {\n\n println!(\"test_case_2 create RC success\");\n\n // check field getter\n\n let mut rc = rc.unwrap();\n\n let _mrc = unsafe { Arc::get_mut_unchecked(&mut rc) };\n\n }\n\n}\n\n\n\n\n", "file_path": "rust-kernel-rdma/KRdmaKit/unitests/qp/src/lib.rs", "rank": 33, "score": 269071.14190493786 }, { "content": "// QP state\n\nfn test_case_rc_overflow() {\n\n println!(\">>>>>> start [test_case_rc_3] <<<<<<<\");\n\n let ctx: &mut RContext = &mut ALLRCONTEXTS.get_mut()[0];\n\n let sa_client = &mut SA_CLIENT.get_mut();\n\n let mut explorer = IBExplorer::new();\n\n let remote_service_id = 50;\n\n let qd_hint = 73;\n\n\n\n let gid_addr = ctx.get_gid_as_string();\n\n let _ = explorer.resolve(1, ctx, &gid_addr, sa_client.get_inner_sa_client());\n\n\n\n // get path\n\n let boxed_ctx = Box::pin(ctx);\n\n // thus the path resolver could be split out of other module\n\n let path_res = explorer.get_path_result().unwrap();\n\n println!(\"finish path get\");\n\n // create Ctrl. serve for cm handshakes\n\n let _ctrl =\n\n RCtrl::create(remote_service_id, &mut ALLRCONTEXTS.get_mut()[0]).unwrap();\n\n\n", "file_path": "rust-kernel-rdma/KRdmaKit/unitests/qp_state/src/lib.rs", "rank": 34, "score": 266042.26010341936 }, { "content": "#[inline]\n\npub fn get_remote_dc_meta_unsafe(remote_gid: &String) -> &EndPoint {\n\n META_INFO.get_mut().get(remote_gid).unwrap()\n\n}\n\n\n", "file_path": "KRdmaKit-syscall/src/client.rs", "rank": 35, "score": 262657.5319884323 }, { "content": "fn print_test_msgs(test_case_idx: usize, assert: bool) {\n\n if assert {\n\n println!(\"{:?}\", crate::console_msgs::SUCC[test_case_idx]);\n\n } else {\n\n println!(\"{:?}\", crate::console_msgs::ERR[test_case_idx]);\n\n }\n\n}\n\n\n", "file_path": "benchs/rc_read/src/lib.rs", "rank": 36, "score": 247197.4433239854 }, { "content": "fn print_test_msgs(test_case_idx: usize, assert: bool) {\n\n if assert {\n\n println!(\"{:?}\", crate::console_msgs::SUCC[test_case_idx]);\n\n } else {\n\n println!(\"{:?}\", crate::console_msgs::ERR[test_case_idx]);\n\n }\n\n}\n\n\n", "file_path": "exp/motiv-kit-breakdown/rc_break_down_client/src/lib.rs", "rank": 37, "score": 241275.44186629463 }, { "content": "fn print_test_msgs(test_case_idx: usize, assert: bool) {\n\n if assert {\n\n println!(\"{:?}\", crate::console_msgs::SUCC[test_case_idx]);\n\n } else {\n\n println!(\"{:?}\", crate::console_msgs::ERR[test_case_idx]);\n\n }\n\n}\n\n\n", "file_path": "rust-kernel-rdma/KRdmaKit/unitests/qp/src/lib.rs", "rank": 38, "score": 239543.1613531036 }, { "content": "fn print_test_msgs(test_case_idx: usize, assert: bool) {\n\n if assert {\n\n println!(\"{:?}\", crate::console_msgs::SUCC[test_case_idx]);\n\n } else {\n\n println!(\"{:?}\", crate::console_msgs::ERR[test_case_idx]);\n\n }\n\n}\n\n\n", "file_path": "rust-kernel-rdma/KRdmaKit/unitests/qp_state/src/lib.rs", "rank": 39, "score": 238130.91383053956 }, { "content": "static struct ibv_exp_cq_family_v1 mlx5_poll_cq_family_unsafe_tbl[MLX5_POLL_CQ_NUM_CQE_SIZES] = {\n\n\t\t[MLX5_POLL_CQ_CQE_64] = {\n\n\t\t\t\t.poll_cnt = mlx5_poll_cnt_unsafe_cqe64,\n\n\t\t\t\t.poll_length = mlx5_poll_length_unsafe_cqe64,\n\n\t\t\t\t.poll_length_flags = mlx5_poll_length_flags_unsafe_cqe64,\n\n\t\t\t\t.poll_length_flags_mp_rq = mlx5_poll_length_flags_mp_rq_unsafe_cqe64,\n\n\t\t\t\t.poll_length_flags_cvlan = mlx5_poll_length_flags_cvlan_unsafe_cqe64,\n\n\t\t\t\t.poll_length_flags_mp_rq_cvlan = mlx5_poll_length_flags_mp_rq_cvlan_unsafe_cqe64,\n\n\t\t\t\t.poll_length_flags_ts = mlx5_poll_length_flags_ts_unsafe_cqe64,\n\n\t\t\t\t.poll_length_flags_mp_rq_ts = mlx5_poll_length_flags_mp_rq_ts_unsafe_cqe64,\n\n\t\t\t\t.poll_length_flags_cvlan_ts = mlx5_poll_length_flags_cvlan_ts_unsafe_cqe64,\n\n\t\t\t\t.poll_length_flags_mp_rq_cvlan_ts = mlx5_poll_length_flags_mp_rq_cvlan_ts_unsafe_cqe64,\n\n\n\n\t\t},\n\n\t\t[MLX5_POLL_CQ_CQE_128] = {\n\n\t\t\t\t.poll_cnt = mlx5_poll_cnt_unsafe_cqe128,\n\n\t\t\t\t.poll_length = mlx5_poll_length_unsafe_cqe128,\n\n\t\t\t\t.poll_length_flags = mlx5_poll_length_flags_unsafe_cqe128,\n\n\t\t\t\t.poll_length_flags_mp_rq = mlx5_poll_length_flags_mp_rq_unsafe_cqe128,\n\n\t\t\t\t.poll_length_flags_cvlan = mlx5_poll_length_flags_cvlan_unsafe_cqe128,\n\n\t\t\t\t.poll_length_flags_mp_rq_cvlan = mlx5_poll_length_flags_mp_rq_cvlan_unsafe_cqe128,\n\n\t\t\t\t.poll_length_flags_ts = mlx5_poll_length_flags_ts_unsafe_cqe128,\n\n\t\t\t\t.poll_length_flags_mp_rq_ts = mlx5_poll_length_flags_mp_rq_ts_unsafe_cqe128,\n\n\t\t\t\t.poll_length_flags_cvlan_ts = mlx5_poll_length_flags_cvlan_ts_unsafe_cqe128,\n\n\t\t\t\t.poll_length_flags_mp_rq_cvlan_ts = mlx5_poll_length_flags_mp_rq_cvlan_ts_unsafe_cqe128,\n\n\n\n\t\t},\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 40, "score": 237108.63234159735 }, { "content": "fn print_test_msgs(test_case_idx: usize, assert: bool) {\n\n if assert {\n\n println!(\"{:?}\", crate::console_msgs::SUCC[test_case_idx]);\n\n } else {\n\n println!(\"{:?}\", crate::console_msgs::ERR[test_case_idx]);\n\n }\n\n}\n\n\n", "file_path": "rust-kernel-rdma/KRdmaKit/unitests/rc_conn_bug/src/lib.rs", "rank": 41, "score": 237032.56560970872 }, { "content": "static struct ibv_exp_cq_family_v1 mlx5_poll_cq_family_unsafe_v1_tbl[MLX5_POLL_CQ_NUM_CQE_SIZES] = {\n\n\t\t[MLX5_POLL_CQ_CQE_64] = {\n\n\t\t\t\t.poll_cnt = mlx5_poll_cnt_unsafe_cqe64_v1,\n\n\t\t\t\t.poll_length = mlx5_poll_length_unsafe_cqe64_v1,\n\n\t\t\t\t.poll_length_flags = mlx5_poll_length_flags_unsafe_cqe64_v1,\n\n\t\t\t\t.poll_length_flags_mp_rq = mlx5_poll_length_flags_mp_rq_unsafe_cqe64_v1,\n\n\t\t\t\t.poll_length_flags_cvlan = mlx5_poll_length_flags_cvlan_unsafe_cqe64_v1,\n\n\t\t\t\t.poll_length_flags_mp_rq_cvlan = mlx5_poll_length_flags_mp_rq_cvlan_unsafe_cqe64_v1,\n\n\t\t\t\t.poll_length_flags_ts = mlx5_poll_length_flags_ts_unsafe_cqe64_v1,\n\n\t\t\t\t.poll_length_flags_mp_rq_ts = mlx5_poll_length_flags_mp_rq_ts_unsafe_cqe64_v1,\n\n\t\t\t\t.poll_length_flags_cvlan_ts = mlx5_poll_length_flags_cvlan_ts_unsafe_cqe64_v1,\n\n\t\t\t\t.poll_length_flags_mp_rq_cvlan_ts = mlx5_poll_length_flags_mp_rq_cvlan_ts_unsafe_cqe64_v1,\n\n\t\t},\n\n\t\t[MLX5_POLL_CQ_CQE_128] = {\n\n\t\t\t\t.poll_cnt = mlx5_poll_cnt_unsafe_cqe128_v1,\n\n\t\t\t\t.poll_length = mlx5_poll_length_unsafe_cqe128_v1,\n\n\t\t\t\t.poll_length_flags = mlx5_poll_length_flags_unsafe_cqe128_v1,\n\n\t\t\t\t.poll_length_flags_mp_rq = mlx5_poll_length_flags_mp_rq_unsafe_cqe128_v1,\n\n\t\t\t\t.poll_length_flags_cvlan = mlx5_poll_length_flags_cvlan_unsafe_cqe128_v1,\n\n\t\t\t\t.poll_length_flags_mp_rq_cvlan = mlx5_poll_length_flags_mp_rq_cvlan_unsafe_cqe128_v1,\n\n\t\t\t\t.poll_length_flags_ts = mlx5_poll_length_flags_ts_unsafe_cqe128_v1,\n\n\t\t\t\t.poll_length_flags_mp_rq_ts = mlx5_poll_length_flags_mp_rq_ts_unsafe_cqe128_v1,\n\n\t\t\t\t.poll_length_flags_cvlan_ts = mlx5_poll_length_flags_cvlan_ts_unsafe_cqe128_v1,\n\n\t\t\t\t.poll_length_flags_mp_rq_cvlan_ts = mlx5_poll_length_flags_mp_rq_cvlan_ts_unsafe_cqe128_v1,\n\n\t\t},\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 42, "score": 235795.50136792386 }, { "content": "static inline uint32_t mlx5_cq_read_wc_src_qp(struct ibv_cq_ex *ibcq)\n\n{\n\n\tstruct mlx5_cq *cq = to_mcq(ibv_cq_ex_to_cq(ibcq));\n\n\n\n\treturn be32toh(cq->cqe64->flags_rqpn) & 0xffffff;\n", "file_path": "mlnx-ofed-4.9-driver/rdma-core-50mlnx1/providers/mlx5/cq.c", "rank": 52, "score": 231653.85641517077 }, { "content": "static uint32_t mlx4_cq_read_wc_src_qp(struct ibv_cq_ex *ibcq)\n\n{\n\n\tstruct mlx4_cq *cq = to_mcq(ibv_cq_ex_to_cq(ibcq));\n\n\n\n\treturn be32toh(cq->cqe->g_mlpath_rqpn) & 0xffffff;\n", "file_path": "mlnx-ofed-4.9-driver/rdma-core-50mlnx1/providers/mlx4/cq.c", "rank": 53, "score": 231653.85641517077 }, { "content": "static inline uint32_t mlx5_cq_read_wc_qp_num(struct ibv_cq_ex *ibcq)\n\n{\n\n\tstruct mlx5_cq *cq = to_mcq(ibv_cq_ex_to_cq(ibcq));\n\n\n\n\treturn be32toh(cq->cqe64->sop_drop_qpn) & 0xffffff;\n", "file_path": "mlnx-ofed-4.9-driver/rdma-core-50mlnx1/providers/mlx5/cq.c", "rank": 54, "score": 231653.85641517077 }, { "content": "static uint32_t mlx4_cq_read_wc_qp_num(struct ibv_cq_ex *ibcq)\n\n{\n\n\tstruct mlx4_cq *cq = to_mcq(ibv_cq_ex_to_cq(ibcq));\n\n\n\n\treturn be32toh(cq->cqe->vlan_my_qpn) & MLX4_CQE_QPN_MASK;\n", "file_path": "mlnx-ofed-4.9-driver/rdma-core-50mlnx1/providers/mlx4/cq.c", "rank": 55, "score": 231653.85641517077 }, { "content": "int32_t mlx5_poll_cnt_unsafe_cqe64(struct ibv_cq *ibcq, uint32_t max) __MLX5_ALGN_F__;\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 56, "score": 224114.05446446425 }, { "content": "int32_t mlx5_poll_cnt_unsafe_cqe128(struct ibv_cq *ibcq, uint32_t max) __MLX5_ALGN_F__;\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 57, "score": 224114.05446446425 }, { "content": "int32_t mlx5_poll_length_unsafe_cqe64(struct ibv_cq *cq, void *buf, uint32_t *inl) __MLX5_ALGN_F__;\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 58, "score": 224114.05446446425 }, { "content": "int32_t mlx5_poll_length_unsafe_cqe128(struct ibv_cq *cq, void *buf, uint32_t *inl) __MLX5_ALGN_F__;\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 59, "score": 224114.05446446425 }, { "content": "void rvt_rc_error(struct rvt_qp *qp, enum ib_wc_status err);\n", "file_path": "mlnx-ofed-4.9-driver/include/rdma/rdmavt_qp.h", "rank": 60, "score": 223946.26278071397 }, { "content": "int32_t mlx5_poll_length_flags_unsafe_cqe128(struct ibv_cq *cq, void *buf, uint32_t *inl, uint32_t *flags) __MLX5_ALGN_F__;\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 61, "score": 222644.7316079224 }, { "content": "int32_t mlx5_poll_cnt_unsafe_cqe128_v1(struct ibv_cq *ibcq, uint32_t max) __MLX5_ALGN_F__;\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 62, "score": 222644.7316079224 }, { "content": "int32_t mlx5_poll_length_unsafe_cqe64_v1(struct ibv_cq *cq, void *buf, uint32_t *inl) __MLX5_ALGN_F__;\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 63, "score": 222644.7316079224 }, { "content": "int32_t mlx5_poll_length_flags_unsafe_cqe64(struct ibv_cq *cq, void *buf, uint32_t *inl, uint32_t *flags) __MLX5_ALGN_F__;\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 64, "score": 222644.7316079224 }, { "content": "int32_t mlx5_poll_length_unsafe_cqe128_v1(struct ibv_cq *cq, void *buf, uint32_t *inl) __MLX5_ALGN_F__;\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 65, "score": 222644.7316079224 }, { "content": "int32_t mlx5_poll_cnt_unsafe_cqe64_v1(struct ibv_cq *ibcq, uint32_t max) __MLX5_ALGN_F__;\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 66, "score": 222644.7316079224 }, { "content": "static int poll_soft_wc(struct mlx5_ib_cq *cq, int num_entries,\n\n\t\t\tstruct ib_wc *wc, bool is_fatal_err)\n\n{\n\n\tstruct mlx5_ib_dev *dev = to_mdev(cq->ibcq.device);\n\n\tstruct mlx5_ib_wc *soft_wc, *next;\n\n\tint npolled = 0;\n\n\n\n\tlist_for_each_entry_safe(soft_wc, next, &cq->wc_list, list) {\n\n\t\tif (npolled >= num_entries)\n\n\t\t\tbreak;\n\n\n\n\t\tmlx5_ib_dbg(dev, \"polled software generated completion on CQ 0x%x\\n\",\n\n\t\t\t cq->mcq.cqn);\n\n\n\n\t\tif (unlikely(is_fatal_err)) {\n\n\t\t\tsoft_wc->wc.status = IB_WC_WR_FLUSH_ERR;\n\n\t\t\tsoft_wc->wc.vendor_err = MLX5_CQE_SYNDROME_WR_FLUSH_ERR;\n\n\t\t}\n\n\t\twc[npolled++] = soft_wc->wc;\n\n\t\tlist_del(&soft_wc->list);\n\n\t\tatomic_set(&soft_wc->in_use, 0);\n\n\t}\n\n\n\n\treturn npolled;\n", "file_path": "mlnx-ofed-4.9-driver/drivers/infiniband/hw/mlx5/cq.c", "rank": 67, "score": 222640.25932711567 }, { "content": "static int poll_cq(struct ibv_cq *cq, int num_entries, struct ibv_wc *wc)\n\n{\n\n\treturn EOPNOTSUPP;\n", "file_path": "mlnx-ofed-4.9-driver/rdma-core-50mlnx1/libibverbs/dummy_ops.c", "rank": 68, "score": 222580.74870568598 }, { "content": "int32_t mlx5_poll_length_flags_ts_unsafe_cqe128(struct ibv_cq *cq, void *buf, uint32_t *inl, uint32_t *flags, uint64_t *timestamp) __MLX5_ALGN_F__;\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 69, "score": 221194.5494317126 }, { "content": "int32_t mlx5_poll_length_flags_cvlan_unsafe_cqe128(struct ibv_cq *cq, void *buf, uint32_t *inl, uint32_t *flags, uint16_t *vlan_cti) __MLX5_ALGN_F__;\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 70, "score": 221194.5494317126 }, { "content": "int32_t mlx5_poll_length_flags_cvlan_unsafe_cqe64(struct ibv_cq *cq, void *buf, uint32_t *inl, uint32_t *flags, uint16_t *vlan_cti) __MLX5_ALGN_F__;\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 71, "score": 221194.5494317126 }, { "content": "int32_t mlx5_poll_length_flags_ts_unsafe_cqe64(struct ibv_cq *cq, void *buf, uint32_t *inl, uint32_t *flags, uint64_t *timestamp) __MLX5_ALGN_F__;\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 72, "score": 221194.5494317126 }, { "content": "int32_t mlx5_poll_length_flags_unsafe_cqe64_v1(struct ibv_cq *cq, void *buf, uint32_t *inl, uint32_t *flags) __MLX5_ALGN_F__;\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 73, "score": 221194.5494317126 }, { "content": "int32_t mlx5_poll_length_flags_unsafe_cqe128_v1(struct ibv_cq *cq, void *buf, uint32_t *inl, uint32_t *flags) __MLX5_ALGN_F__;\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 74, "score": 221194.5494317126 }, { "content": "static int test_wc_poll_cq(struct mlx5_ib_dev *dev, struct ib_cq *cq)\n\n{\n\n\tint ret;\n\n\tstruct ib_wc wc = {};\n\n\tunsigned long end = jiffies + TEST_WC_POLLING_MAX_TIME_JIFFIES;\n\n\n\n\twhile (!time_after(jiffies, end)) {\n\n\t\tret = ib_poll_cq(cq, 1, &wc);\n\n\t\tif (ret < 0 || wc.status)\n\n\t\t\treturn ret ? ret : -EINVAL;\n\n\t\tif (ret)\n\n\t\t\tbreak;\n\n\t}\n\n\tif (!ret)\n\n\t\treturn -ETIMEDOUT;\n\n\n\n\tif (wc.wr_id == WR_ID_FINAL)\n\n\t\tdev->wc_support = MLX5_IB_WC_NOT_SUPPORTED;\n\n\telse if (wc.wr_id == WR_ID_BF)\n\n\t\tdev->wc_support = MLX5_IB_WC_SUPPORTED;\n\n\telse\n\n\t\treturn -EINVAL;\n\n\n\n\treturn 0;\n", "file_path": "mlnx-ofed-4.9-driver/drivers/infiniband/hw/mlx5/mem.c", "rank": 75, "score": 221190.10628081998 }, { "content": "pub fn xx() {\n\n let len = 20;\n\n let runtime = Runtime::new();\n\n let mut t1 = Task::new(async move {\n\n async_run(0).await\n\n });\n\n\n\n let mut t2 = Task::new(async move {\n\n async_run(1).await\n\n });\n\n\n\n let mut t3 = Task::new(async move {\n\n async_run(3).await\n\n });\n\n\n\n let h1 = t1.spawn(&runtime);\n\n let h3 = t3.spawn(&runtime);\n\n let h2 = t2.spawn(&runtime);\n\n h1.join();\n\n}\n", "file_path": "KRdmaKit-syscall/src/nostd_async/mod.rs", "rank": 76, "score": 220147.4700047007 }, { "content": "int32_t mlx5_poll_length_flags_cvlan_ts_unsafe_cqe64(struct ibv_cq *cq, void *buf, uint32_t *inl, uint32_t *flags,\n\n\t\t\t\t\t\t uint16_t *vlan_cti, uint64_t *timestamp)\n\n{\n\n\treturn __poll_length(cq, buf, inl, 0, 64, NULL, flags, 0, vlan_cti,\n\n\t\t\t timestamp);\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 77, "score": 219763.13634141098 }, { "content": "int32_t mlx5_poll_length_flags_cvlan_unsafe_cqe128_v1(struct ibv_cq *cq, void *buf, uint32_t *inl, uint32_t *flags, uint16_t *vlan_cti)\n\n{\n\n\treturn poll_length(cq, buf, inl, 0, 128, NULL, flags, 1, vlan_cti);\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 78, "score": 219763.13634141098 }, { "content": "int32_t mlx5_poll_length_flags_mp_rq_unsafe_cqe64(struct ibv_cq *cq, uint32_t *offset, uint32_t *flags)\n\n{\n\n\treturn poll_length(cq, NULL, NULL, 0, 64, offset, flags, 0, NULL);\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 79, "score": 219763.13634141098 }, { "content": "int32_t mlx5_poll_length_flags_ts_unsafe_cqe128_v1(struct ibv_cq *cq, void *buf, uint32_t *inl, uint32_t *flags, uint64_t *timestamp)\n\n{\n\n\treturn __poll_length(cq, buf, inl, 0, 128, NULL, flags, 1, NULL,\n\n\t\t\t timestamp);\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 80, "score": 219763.13634141098 }, { "content": "int32_t mlx5_poll_length_flags_mp_rq_unsafe_cqe128(struct ibv_cq *cq, uint32_t *offset, uint32_t *flags)\n\n{\n\n\treturn poll_length(cq, NULL, NULL, 0, 128, offset, flags, 0, NULL);\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 81, "score": 219763.13634141098 }, { "content": "int32_t mlx5_poll_length_flags_ts_unsafe_cqe64_v1(struct ibv_cq *cq, void *buf, uint32_t *inl, uint32_t *flags, uint64_t *timestamp)\n\n{\n\n\treturn __poll_length(cq, buf, inl, 0, 64, NULL, flags, 1, NULL,\n\n\t\t\t timestamp);\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 82, "score": 219763.13634141098 }, { "content": "int32_t mlx5_poll_length_flags_cvlan_unsafe_cqe64_v1(struct ibv_cq *cq, void *buf, uint32_t *inl, uint32_t *flags, uint16_t *vlan_cti)\n\n{\n\n\treturn poll_length(cq, buf, inl, 0, 64, NULL, flags, 1, vlan_cti);\n", "file_path": "mlnx-ofed-4.9-driver/src/cq.c", "rank": 83, "score": 219763.13634141098 }, { "content": " pub fn pop_recv_cq(&mut self, pop_cnt: u32, wc_list: *mut ib_wc) -> Option<usize> {\n\n let ret = unsafe { bd_ib_poll_cq(self.qp.get_recv_cq(), pop_cnt as i32, wc_list) };\n\n if ret < 0 {\n\n return None;\n\n } else if ret > 0 {\n\n return Some(ret as usize);\n\n }\n\n None\n\n }\n\n\n\n #[inline]\n\n pub fn post_recv(\n\n &mut self,\n\n local_ptr: u64,\n\n lkey: u32,\n\n sz: usize,\n\n ) -> linux_kernel_module::KernelResult<()> {\n\n let mut wr: ib_recv_wr = Default::default();\n\n let mut sge: ib_sge = Default::default();\n\n\n", "file_path": "rust-kernel-rdma/KRdmaKit/src/qp/ud_op.rs", "rank": 84, "score": 110.65178674240738 }, { "content": " #[inline]\n\n pub fn push(&mut self,\n\n op: u32, // RDMA operation type (denote the type `ib_wr_opcode`)\n\n local_ptr: u64, // local mr address\n\n lkey: u32, // local key\n\n sz: usize, // request size (in Byte)\n\n remote_addr: u64, // remote mr address\n\n rkey: u32, // remote key\n\n end_point: &EndPoint,\n\n send_flag: i32,\n\n ) -> linux_kernel_module::KernelResult<()> {\n\n let mut wr: ib_dc_wr = Default::default();\n\n let mut sge: ib_sge = Default::default();\n\n\n\n let ah = end_point.ah;\n\n let dct_num = end_point.dct_num;\n\n // 1. set the sge\n\n sge.addr = local_ptr;\n\n sge.length = sz as _;\n\n sge.lkey = lkey;\n", "file_path": "rust-kernel-rdma/KRdmaKit/src/qp/dc_op.rs", "rank": 85, "score": 82.30623896969156 }, { "content": " }\n\n}\n\n\n\nimpl<'a> UDOp<'a> {\n\n #[inline]\n\n pub fn push(\n\n &mut self,\n\n op: u32, // RDMA operation type (denote the type `ib_wr_opcode`)\n\n local_ptr: u64,\n\n lkey: u32,\n\n end_point: &EndPoint,\n\n sz: usize,\n\n imm_data: u32,\n\n send_flag: i32,\n\n ) -> linux_kernel_module::KernelResult<()> {\n\n let mut wr: ib_ud_wr = Default::default();\n\n let mut sge: ib_sge = Default::default();\n\n\n\n // first set the sge\n\n sge.addr = local_ptr;\n", "file_path": "rust-kernel-rdma/KRdmaKit/src/qp/ud_op.rs", "rank": 86, "score": 79.0904280403489 }, { "content": " }\n\n }\n\n }\n\n\n\n #[inline]\n\n pub fn pop(&mut self) -> Option<*mut ib_wc> {\n\n let mut wc: ib_wc = Default::default();\n\n let ret = unsafe { bd_ib_poll_cq(self.qp.get_cq(), 1, &mut wc as *mut ib_wc) };\n\n if ret < 0 {\n\n return None;\n\n } else if ret == 1 {\n\n if wc.status != 0 && wc.status != 5 {\n\n linux_kernel_module::println!(\"ud poll cq error, wc_status:{}\", wc.status);\n\n }\n\n return Some(&mut wc as *mut ib_wc);\n\n }\n\n None\n\n }\n\n\n\n #[inline]\n", "file_path": "rust-kernel-rdma/KRdmaKit/src/qp/ud_op.rs", "rank": 87, "score": 73.19983457625649 }, { "content": "\n\nimpl<'a, const N: usize> RPCClient<'a, N> {\n\n async fn post_recv(&mut self, post_cnt: u64) {\n\n let recv = unsafe { Arc::get_mut_unchecked(&mut self.recv_helper) };\n\n let _ = recv.post_recvs(self.queue_pair.get_qp(), null_mut(), post_cnt as usize);\n\n }\n\n\n\n pub async fn poll_all(&mut self) {\n\n use rust_kernel_linux_util::bindings::memcpy;\n\n\n\n let send_addr = self.send_buffer.get_dma_buf();\n\n let send_va = self.send_buffer.get_ptr();\n\n\n\n let lkey = unsafe { self.ctx.get_lkey() };\n\n let mut op = UDOp::new(self.queue_pair);\n\n let wc_header = unsafe { Arc::get_mut_unchecked(&mut self.recv_helper) }.get_wc_header();\n\n\n\n let timer = KTimer::new();\n\n loop {\n\n let pop_res = op.pop_recv_cq(N as u32, wc_header);\n", "file_path": "rust-kernel-rdma/KRdmaKit/unitests/rpc/src/rpc.rs", "rank": 88, "score": 71.93001311640899 }, { "content": " return ret;\n\n }\n\n cnt += 1;\n\n if cnt > 10000 {\n\n linux_kernel_module::println!(\"dc op wait til comp timeout!\");\n\n break;\n\n }\n\n }\n\n None\n\n }\n\n\n\n #[inline]\n\n pub fn pop(&mut self) -> Option<*mut ib_wc> {\n\n let mut wc: ib_wc = Default::default();\n\n let ret = unsafe { bd_ib_poll_cq(self.qp.get_cq(), 1, &mut wc as *mut ib_wc) };\n\n if ret < 0 {\n\n return None;\n\n } else if ret == 1 {\n\n return Some(&mut wc as *mut _);\n\n }\n\n None\n\n }\n\n}", "file_path": "rust-kernel-rdma/KRdmaKit/src/qp/dc_op.rs", "rank": 89, "score": 71.21749226760338 }, { "content": " let mut test_mr = RMemPhy::new(1024 * 1024);\n\n // 2. get all of the params for later operation\n\n let lkey = unsafe { boxed_ctx.get_lkey() } as u32;\n\n let rkey = lkey as u32;\n\n let laddr = test_mr.get_pa(0) as u64; // use pa for RCOp\n\n let raddr = test_mr.get_pa(1024) as u64;\n\n let sz = 8 as usize;\n\n\n\n // va of the mr. These addrs are used to read/write value in test function\n\n let va_buf = (test_mr.get_ptr() as u64 + 1024) as *mut i8;\n\n let target_buf = (test_mr.get_ptr()) as *mut i8;\n\n\n\n // now write a value\n\n let write_value = 99 as i8;\n\n unsafe { *(va_buf) = write_value };\n\n unsafe { *(target_buf) = 4 };\n\n println!(\"[before] value = {}\", unsafe { *(target_buf) });\n\n // 3. send request of type `READ`\n\n let mut op = RCOp::new(&rc);\n\n let _ = op.read(laddr, lkey, sz, raddr, rkey);\n", "file_path": "rust-kernel-rdma/KRdmaKit/unitests/qp/src/lib.rs", "rank": 90, "score": 70.61044681443659 }, { "content": " pub fn create(entry_size: usize, lkey: u32, base_addr: u64) -> Arc<Self> {\n\n let ret = Self {\n\n capacity: N,\n\n cur_idx: 0,\n\n wrs: Box::new_zeroed_slice_in(N as usize, VmallocAllocator),\n\n sges: Box::new_zeroed_slice_in(N as usize, VmallocAllocator),\n\n wcs: Box::new_zeroed_slice_in(N as usize, VmallocAllocator),\n\n en_sz: entry_size,\n\n };\n\n let mut boxed = Arc::new(ret);\n\n let recvs = unsafe { Arc::get_mut_unchecked(&mut boxed) };\n\n\n\n let mut base: u64 = base_addr;\n\n for i in 0..recvs.capacity {\n\n let sge = recvs.sges[i].as_mut_ptr();\n\n let wr = recvs.wrs[i].as_mut_ptr();\n\n\n\n unsafe {\n\n let base_va = { pa_to_va(base as *mut i8) } as u64;\n\n (*sge).addr = base as u64;\n", "file_path": "rust-kernel-rdma/KRdmaKit/src/qp/recv_helper.rs", "rank": 91, "score": 70.24932340990095 }, { "content": " send_reg_mr(mrc.get_qp(), v_mem.get_inner_mr(), DEFAULT_MR_ACCESS_FLAGS);\n\n rkey = unsafe { (*v_mem.get_inner_mr()).rkey } as u32;\n\n lkey = unsafe { (*v_mem.get_inner_mr()).lkey } as u32;\n\n local_pa = v_mem.get_dma_buf();\n\n remote_pa = v_mem.get_dma_buf();\n\n } else {\n\n let mut ret = RMemPhy::new(min(1024 * 1024 * 4, alloc_sz as usize));\n\n lkey = unsafe { boxed_ctx.get_lkey() } as u32;\n\n rkey = unsafe { boxed_ctx.get_lkey() } as u32;\n\n local_pa = p_mem.get_dma_buf();\n\n remote_pa = p_mem.get_dma_buf();\n\n };\n\n\n\n\n\n // 3. send request of type `READ`\n\n let mut op = RCOp::new(mrc);\n\n\n\n let mut op_count: u64 = 0;\n\n let mut rand = random::FastRandom::new(0xdeadbeaf);\n\n\n", "file_path": "benchs/rc_read/src/rc_read.rs", "rank": 92, "score": 70.0370947941143 }, { "content": " // unsafe { (*dct).dct_num },\n\n // &_ctrl.get_self_test_mr());\n\n // let dc = DC::new(ctx);\n\n // if dc.is_none() {\n\n // println!(\"[dct] err create dc qp.\");\n\n // return;\n\n // }\n\n //\n\n // println!(\"create dc success\");\n\n //\n\n // let mut dc = dc.unwrap();\n\n // let mdc = unsafe { Arc::get_mut_unchecked(&mut dc) };\n\n //\n\n // // 1. generate MR\n\n // let mut test_mr = RMemPhy::new(1024 * 1024);\n\n //\n\n // // 2. get all of the params for later operation\n\n // let lkey = unsafe { ctx.get_lkey() } as u32;\n\n // let rkey = lkey as u32;\n\n // let local_pa = test_mr.get_pa(0) as u64; // use pa for RCOp\n", "file_path": "rust-kernel-rdma/KRdmaKit/unitests/dct/src/lib.rs", "rank": 93, "score": 68.26411521739416 }, { "content": " let path_res = explorer.get_path_result().unwrap();\n\n\n\n // create RC at one side\n\n let rc = RC::new(ctx, core::ptr::null_mut(), core::ptr::null_mut());\n\n let sz = 64 as u64;\n\n let mut rc = rc.unwrap();\n\n let mrc = unsafe { Arc::get_mut_unchecked(&mut rc) };\n\n // connect to the server (Ctrl)\n\n let _ = mrc.connect(qd_hint, path_res, 1 as u64);\n\n let lkey = unsafe { (*mr).lkey } as u32;\n\n let rkey = unsafe { (*mr).rkey } as u32;\n\n let local_pa = dma_pa;\n\n let remote_pa = local_pa + sz;\n\n\n\n let mut op = RCOp::new(&rc);\n\n let _ = op.read(local_pa, lkey,\n\n 64 as usize, remote_pa, lkey);\n\n }\n\n\n\n unsafe fn bench_pin(mr: *mut ib_mr, address: u64, size: u64) -> u64 {\n", "file_path": "KRdmaKit-syscall/src/virtual_queue.rs", "rank": 94, "score": 68.01086777767878 }, { "content": " sz: usize, // request size (in Byte)\n\n remote_addr: u64, // remote mr address\n\n rkey: u32, // remote key\n\n end_point: &EndPoint,\n\n send_flag: i32,\n\n imm_data: u32,\n\n ) -> linux_kernel_module::KernelResult<()> {\n\n let mut wr: ib_dc_wr = Default::default();\n\n let mut sge: ib_sge = Default::default();\n\n\n\n let ah = end_point.ah;\n\n let dct_num = end_point.dct_num;\n\n // 1. set the sge\n\n sge.addr = local_ptr;\n\n sge.length = sz as _;\n\n sge.lkey = lkey;\n\n\n\n // 2. set the wr\n\n wr.wr.opcode = op;\n\n wr.wr.send_flags = send_flag;\n", "file_path": "rust-kernel-rdma/KRdmaKit/src/qp/dc_op.rs", "rank": 95, "score": 66.47607611447182 }, { "content": " // connect to the server (Ctrl)\n\n let _ = mrc.connect(qd_hint + 1, path_res, remote_service_id as u64);\n\n\n\n // 1. generate MR\n\n let mut test_mr = RMemPhy::new(1024 * 1024);\n\n // 2. get all of the params for later operation\n\n let lkey = unsafe { boxed_ctx.get_lkey() } as u32;\n\n let rkey = lkey as u32;\n\n let laddr = test_mr.get_pa(0) as u64; // use pa for RCOp\n\n let raddr = test_mr.get_pa(1024) as u64;\n\n let sz = 8 as usize;\n\n\n\n // va of the mr. These addrs are used to read/write value in test function\n\n let va_buf = (test_mr.get_ptr() as u64 + 1024) as *mut i8;\n\n let target_buf = (test_mr.get_ptr()) as *mut i8;\n\n\n\n // 3. send request of type `READ`\n\n let mut op = RCOp::new(&rc);\n\n\n\n\n", "file_path": "exp/motiv-kit-breakdown/rc_break_down_client/src/lib.rs", "rank": 96, "score": 66.08398631814222 }, { "content": " sge.addr = local_ptr as u64;\n\n sge.length = sz as u32;\n\n sge.lkey = lkey as u32;\n\n\n\n // 1. reset the wr\n\n wr.sg_list = &mut sge as *mut _;\n\n wr.num_sge = 1;\n\n unsafe { bd_set_recv_wr_id(&mut wr, pa_to_va(local_ptr as *mut i8)) };\n\n let mut bad_wr: *mut ib_recv_wr = core::ptr::null_mut();\n\n let err = unsafe {\n\n bd_ib_post_recv(\n\n self.qp.get_qp(),\n\n &mut wr as *mut _,\n\n &mut bad_wr as *mut _,\n\n )\n\n };\n\n\n\n if err != 0 {\n\n println!(\"error when post recv {}\", err);\n\n return Err(Error::from_kernel_errno(err));\n\n }\n\n\n\n Ok(())\n\n }\n\n}\n", "file_path": "rust-kernel-rdma/KRdmaKit/src/qp/ud_op.rs", "rank": 97, "score": 65.95114441207579 }, { "content": " println!(\"[after] value = {}\", unsafe { *(target_buf) });\n\n print_test_msgs(0, unsafe { *(target_buf) } == write_value);\n\n\n\n\n\n let mut profile = Profile::new();\n\n profile.reset_timer();\n\n let running_cnt = 40000;\n\n for _ in 0..running_cnt {\n\n if op.push(ib_wr_opcode::IB_WR_RDMA_WRITE,\n\n (unsafe { pa_to_va(laddr as *mut i8) }) as u64, lkey, 32, raddr, rkey,\n\n ib_send_flags::IB_SEND_SIGNALED | ib_send_flags::IB_SEND_INLINE).is_err() {\n\n println!(\"push error\");\n\n return;\n\n };\n\n\n\n let mut cnt = 0;\n\n loop {\n\n let ret = op.pop();\n\n if ret.is_some() {\n\n break;\n", "file_path": "rust-kernel-rdma/KRdmaKit/unitests/qp/src/lib.rs", "rank": 98, "score": 65.9339681318883 }, { "content": "use rust_kernel_rdma_base::*;\n\npub const DEFAULT_BATCH_SZ: usize = 64;\n\n\n\npub struct DoorbellHelper {\n\n pub wrs: [ib_rdma_wr; DEFAULT_BATCH_SZ],\n\n pub sges: [ib_sge; DEFAULT_BATCH_SZ],\n\n\n\n cur_idx: isize,\n\n capacity: usize,\n\n}\n\n\n\nimpl DoorbellHelper {\n\n pub fn create(capacity: usize, op: u32) -> Self {\n\n let mut ret = Self {\n\n capacity,\n\n cur_idx: -1,\n\n wrs: [Default::default(); DEFAULT_BATCH_SZ],\n\n sges: [Default::default(); DEFAULT_BATCH_SZ],\n\n };\n\n for i in 0..capacity {\n", "file_path": "rust-kernel-rdma/KRdmaKit/src/qp/doorbell.rs", "rank": 99, "score": 65.7109583530209 } ]
Rust
pallet/src/tests.rs
4meta5/deleg8
6bca6d8e1385ea259f7e52eb03dee46d2be112b7
#![cfg(test)] use super::*; use frame_support::{ assert_noop, assert_ok, impl_outer_event, impl_outer_origin, parameter_types, weights::Weight, }; use sp_core::H256; use sp_runtime::{ testing::Header, traits::IdentityLookup, Perbill, }; pub type AccountId = u64; pub type BlockNumber = u64; impl_outer_origin! { pub enum Origin for TestRuntime {} } mod delegate { pub use super::super::*; } impl_outer_event! { pub enum TestEvent for TestRuntime { frame_system<T>, pallet_balances<T>, delegate<T>, } } #[derive(Clone, Eq, PartialEq)] pub struct TestRuntime; parameter_types! { pub const BlockHashCount: u64 = 250; pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } impl frame_system::Trait for TestRuntime { type Origin = Origin; type Index = u64; type BlockNumber = BlockNumber; type Call = (); type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup<Self::AccountId>; type Header = Header; type Event = TestEvent; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; type MaximumExtrinsicWeight = MaximumBlockWeight; type DbWeight = (); type BlockExecutionWeight = (); type ExtrinsicBaseWeight = (); type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); type ModuleToIndex = (); type AccountData = pallet_balances::AccountData<u64>; type OnNewAccount = (); type OnKilledAccount = (); type BaseCallFilter = (); type SystemWeightInfo = (); } parameter_types! { pub const ExistentialDeposit: u64 = 1; } impl pallet_balances::Trait for TestRuntime { type Balance = u64; type Event = TestEvent; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; type WeightInfo = (); } parameter_types! { pub const Bond: u64 = 2; pub const MaxSize: u32 = 5; pub const MaxDepth: u32 = 3; pub const MaxKids: u32 = 3; } impl Trait for TestRuntime { type Event = TestEvent; type TreeId = u64; type Bond = Bond; type MaxSize = MaxSize; type MaxDepth = MaxDepth; type MaxKids = MaxKids; type Currency = Balances; } pub type System = frame_system::Module<TestRuntime>; pub type Balances = pallet_balances::Module<TestRuntime>; pub type Delegate = Module<TestRuntime>; fn get_last_event() -> RawEvent<u64, u64, u64> { System::events() .into_iter() .map(|r| r.event) .filter_map(|e| { if let TestEvent::delegate(inner) = e { Some(inner) } else { None } }) .last() .unwrap() } fn new_test_ext() -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default() .build_storage::<TestRuntime>() .unwrap(); pallet_balances::GenesisConfig::<TestRuntime> { balances: vec![ (1, 1000), (2, 100), (3, 100), (4, 100), (5, 100), (6, 100), ], } .assimilate_storage(&mut t) .unwrap(); let mut ext: sp_io::TestExternalities = t.into(); ext.execute_with(|| System::set_block_number(1)); ext } #[test] fn genesis_config_works() { new_test_ext().execute_with(|| { assert!(System::events().is_empty()); }); } #[test] fn create_root_works() { new_test_ext().execute_with(|| { assert_noop!( Delegate::create_root(Origin::signed(21)), DispatchError::Module { index: 0, error: 3, message: Some("InsufficientBalance") } ); assert_eq!(Balances::free_balance(&1), 1000); assert_ok!(Delegate::create_root(Origin::signed(1))); assert_eq!(RawEvent::RegisterIdRoot(0, 1, 2), get_last_event()); assert_eq!(Balances::free_balance(&1), 998); for i in 2u64..7u64 { assert_eq!(Balances::free_balance(&i), 100); assert_ok!(Delegate::create_root(Origin::signed(i))); assert_eq!( RawEvent::RegisterIdRoot(i - 1u64, i, 2), get_last_event() ); assert_eq!(Balances::free_balance(&i), 98); } }); } #[test] fn base_case_revoke_works() { new_test_ext().execute_with(|| { assert_eq!(Balances::free_balance(&1), 1000); assert_ok!(Delegate::create_root(Origin::signed(1))); assert_eq!(RawEvent::RegisterIdRoot(0, 1, 2), get_last_event()); assert_eq!(Balances::free_balance(&1), 998); assert_ok!(Delegate::revoke(Origin::signed(1), 0, false)); assert_eq!(RawEvent::RevokeDelegation(0), get_last_event()); assert_eq!(Balances::free_balance(&1), 1000); for i in 2u64..7u64 { assert_eq!(Balances::free_balance(&i), 100); assert_ok!(Delegate::create_root(Origin::signed(i))); assert_eq!( RawEvent::RegisterIdRoot(i - 1u64, i, 2), get_last_event() ); assert_eq!(Balances::free_balance(&i), 98); assert_ok!(Delegate::revoke(Origin::signed(i), i - 1u64, false)); assert_eq!(RawEvent::RevokeDelegation(i - 1), get_last_event()); assert_eq!(Balances::free_balance(&i), 100); } }); } #[test] fn add_remove_members_works() { new_test_ext().execute_with(|| { assert_eq!(Balances::free_balance(&1), 1000); assert_ok!(Delegate::create_root(Origin::signed(1))); assert_eq!(RawEvent::RegisterIdRoot(0, 1, 2), get_last_event()); assert_eq!(Balances::free_balance(&1), 998); assert_noop!( Delegate::add_members(Origin::signed(1), 0, vec![1, 2, 3, 4, 5, 6]), Error::<TestRuntime>::CannotAddGroupAboveMaxSize ); assert_ok!(Delegate::add_members( Origin::signed(1), 0, vec![2, 3, 4, 5] )); assert_eq!(Balances::free_balance(&1), 988); assert_noop!( Delegate::remove_members( Origin::signed(2), 0, vec![1, 3, 5], false, ), Error::<TestRuntime>::NotAuthorized ); assert_ok!(Delegate::remove_members( Origin::signed(1), 0, vec![2], false, )); }); } #[test] fn delegate_works() { new_test_ext().execute_with(|| { assert_ok!(Delegate::create_root(Origin::signed(1))); assert_eq!(RawEvent::RegisterIdRoot(0, 1, 2), get_last_event()); assert_eq!(Balances::free_balance(&1), 998); assert_ok!(Delegate::delegate(Origin::signed(1), 0, vec![2, 3, 4])); assert_eq!(Balances::free_balance(&1), 994); assert_eq!(RawEvent::DelegateBranch(0, 1, 1, 4), get_last_event()); assert_ok!(Delegate::delegate(Origin::signed(1), 0, vec![3, 4, 6])); assert_eq!(Balances::free_balance(&1), 986); assert_eq!(RawEvent::DelegateBranch(0, 2, 1, 8), get_last_event()); assert_ok!(Delegate::delegate(Origin::signed(2), 1, vec![3, 5])); assert_eq!(Balances::free_balance(&2), 92); assert_eq!(RawEvent::DelegateBranch(1, 3, 2, 8), get_last_event()); assert_ok!(Delegate::delegate(Origin::signed(3), 3, vec![1, 2])); assert_eq!(Balances::free_balance(&3), 84); assert_eq!(RawEvent::DelegateBranch(3, 4, 3, 16), get_last_event()); assert_noop!( Delegate::delegate(Origin::signed(2), 4, vec![5, 6]), Error::<TestRuntime>::CannotDelegateBelowMaxDepth ); assert_ok!(Delegate::delegate(Origin::signed(1), 0, vec![5, 6])); assert_eq!(Balances::free_balance(&1), 970); assert_eq!(RawEvent::DelegateBranch(0, 5, 1, 16), get_last_event()); assert_noop!( Delegate::delegate(Origin::signed(1), 0, vec![2, 8]), Error::<TestRuntime>::CannotDelegateAboveMaxKids ); }); } #[test] fn recursive_revoke_works() { new_test_ext().execute_with(|| { assert_ok!(Delegate::create_root(Origin::signed(1))); assert_eq!(RawEvent::RegisterIdRoot(0, 1, 2), get_last_event()); assert_eq!(Balances::free_balance(&1), 998); assert_ok!(Delegate::delegate(Origin::signed(1), 0, vec![2, 3, 4])); assert_eq!(Balances::free_balance(&1), 994); assert_eq!(RawEvent::DelegateBranch(0, 1, 1, 4), get_last_event()); assert_eq!(Balances::free_balance(&1), 994); assert_eq!(RawEvent::DelegateBranch(0, 1, 1, 4), get_last_event()); assert_ok!(Delegate::delegate(Origin::signed(1), 0, vec![3, 4, 6])); assert_eq!(Balances::free_balance(&1), 986); assert_eq!(RawEvent::DelegateBranch(0, 2, 1, 8), get_last_event()); assert_ok!(Delegate::delegate(Origin::signed(2), 1, vec![3, 5])); assert_eq!(Balances::free_balance(&2), 92); assert_eq!(RawEvent::DelegateBranch(1, 3, 2, 8), get_last_event()); assert_ok!(Delegate::delegate(Origin::signed(3), 3, vec![1, 2])); assert_eq!(Balances::free_balance(&3), 84); assert_eq!(RawEvent::DelegateBranch(3, 4, 3, 16), get_last_event()); assert_ok!(Delegate::delegate(Origin::signed(5), 3, vec![1, 2])); assert_eq!(Balances::free_balance(&5), 68); assert_eq!(RawEvent::DelegateBranch(3, 5, 5, 32), get_last_event()); assert_ok!(Delegate::revoke(Origin::signed(1), 0, false)); assert_eq!(Balances::free_balance(&5), 100); assert_eq!(Balances::free_balance(&3), 100); assert_eq!(Balances::free_balance(&1), 1000); assert_eq!(Balances::free_balance(&2), 100); }); }
#![cfg(test)] use super::*; use frame_support::{ assert_noop, assert_ok, impl_outer_event, impl_outer_origin, parameter_types, weights::Weight, }; use sp_core::H256; use sp_runtime::{ testing::Header, traits::IdentityLookup, Perbill, }; pub type AccountId = u64; pub type BlockNumber = u64; impl_outer_origin! { pub enum Origin for TestRuntime {} } mod delegate { pub use super::super::*; } impl_outer_event! { pub enum TestEvent for TestRuntime { frame_system<T>, pallet_balances<T>, delegate<T>, } } #[derive(Clone, Eq, PartialEq)] pub struct TestRuntime; parameter_types! { pub const BlockHashCount: u64 = 250; pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } impl frame_system::Trait for TestRuntime { type Origin = Origin; type Index = u64; type BlockNumber = BlockNumber; type Call = (); type Hash = H256; type Hashing = ::sp_runtime::traits::BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup<Self::AccountId>; type Header = Header; type Event = TestEvent; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; type MaximumExtrinsicWeight = MaximumBlockWeight; type DbWeight = (); type BlockExecutionWeight = (); type ExtrinsicBaseWeight = (); type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); type ModuleToIndex = (); type AccountData = pallet_balances::AccountData<u64>; type OnNewAccount = (); type OnKilledAccount = (); type BaseCallFilter = (); type SystemWeightInfo = (); } parameter_types! { pub const ExistentialDeposit: u64 = 1; } impl pallet_balances::Trait for TestRuntime { type Balance = u64; type Event = TestEvent; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; type WeightInfo = (); } parameter_types! { pub const Bond: u64 = 2; pub const MaxSize: u32 = 5; pub const MaxDepth: u32 = 3; pub const MaxKids: u32 = 3; } impl Trait for TestRuntime { type Event = TestEvent; type TreeId = u64; type Bond = Bond; type MaxSize = MaxSize; type MaxDepth = MaxDepth; type MaxKids = MaxKids; type Currency = Balances; } pub type System = frame_system::Module<TestRuntime>; pub type Balances = pallet_balances::Module<TestRuntime>; pub type Delegate = Module<TestRuntime>; fn get_last_event() -> RawEvent<u64, u64, u64> { System::events() .into_iter() .map(|r| r.event) .filter_map(|e| { if let TestEvent::delegate(inner) = e { Some(inner) } else { None } }) .last() .unwrap() } fn new_test_ext() -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default() .build_storage::<TestRuntime>() .
#[test] fn genesis_config_works() { new_test_ext().execute_with(|| { assert!(System::events().is_empty()); }); } #[test] fn create_root_works() { new_test_ext().execute_with(|| { assert_noop!( Delegate::create_root(Origin::signed(21)), DispatchError::Module { index: 0, error: 3, message: Some("InsufficientBalance") } ); assert_eq!(Balances::free_balance(&1), 1000); assert_ok!(Delegate::create_root(Origin::signed(1))); assert_eq!(RawEvent::RegisterIdRoot(0, 1, 2), get_last_event()); assert_eq!(Balances::free_balance(&1), 998); for i in 2u64..7u64 { assert_eq!(Balances::free_balance(&i), 100); assert_ok!(Delegate::create_root(Origin::signed(i))); assert_eq!( RawEvent::RegisterIdRoot(i - 1u64, i, 2), get_last_event() ); assert_eq!(Balances::free_balance(&i), 98); } }); } #[test] fn base_case_revoke_works() { new_test_ext().execute_with(|| { assert_eq!(Balances::free_balance(&1), 1000); assert_ok!(Delegate::create_root(Origin::signed(1))); assert_eq!(RawEvent::RegisterIdRoot(0, 1, 2), get_last_event()); assert_eq!(Balances::free_balance(&1), 998); assert_ok!(Delegate::revoke(Origin::signed(1), 0, false)); assert_eq!(RawEvent::RevokeDelegation(0), get_last_event()); assert_eq!(Balances::free_balance(&1), 1000); for i in 2u64..7u64 { assert_eq!(Balances::free_balance(&i), 100); assert_ok!(Delegate::create_root(Origin::signed(i))); assert_eq!( RawEvent::RegisterIdRoot(i - 1u64, i, 2), get_last_event() ); assert_eq!(Balances::free_balance(&i), 98); assert_ok!(Delegate::revoke(Origin::signed(i), i - 1u64, false)); assert_eq!(RawEvent::RevokeDelegation(i - 1), get_last_event()); assert_eq!(Balances::free_balance(&i), 100); } }); } #[test] fn add_remove_members_works() { new_test_ext().execute_with(|| { assert_eq!(Balances::free_balance(&1), 1000); assert_ok!(Delegate::create_root(Origin::signed(1))); assert_eq!(RawEvent::RegisterIdRoot(0, 1, 2), get_last_event()); assert_eq!(Balances::free_balance(&1), 998); assert_noop!( Delegate::add_members(Origin::signed(1), 0, vec![1, 2, 3, 4, 5, 6]), Error::<TestRuntime>::CannotAddGroupAboveMaxSize ); assert_ok!(Delegate::add_members( Origin::signed(1), 0, vec![2, 3, 4, 5] )); assert_eq!(Balances::free_balance(&1), 988); assert_noop!( Delegate::remove_members( Origin::signed(2), 0, vec![1, 3, 5], false, ), Error::<TestRuntime>::NotAuthorized ); assert_ok!(Delegate::remove_members( Origin::signed(1), 0, vec![2], false, )); }); } #[test] fn delegate_works() { new_test_ext().execute_with(|| { assert_ok!(Delegate::create_root(Origin::signed(1))); assert_eq!(RawEvent::RegisterIdRoot(0, 1, 2), get_last_event()); assert_eq!(Balances::free_balance(&1), 998); assert_ok!(Delegate::delegate(Origin::signed(1), 0, vec![2, 3, 4])); assert_eq!(Balances::free_balance(&1), 994); assert_eq!(RawEvent::DelegateBranch(0, 1, 1, 4), get_last_event()); assert_ok!(Delegate::delegate(Origin::signed(1), 0, vec![3, 4, 6])); assert_eq!(Balances::free_balance(&1), 986); assert_eq!(RawEvent::DelegateBranch(0, 2, 1, 8), get_last_event()); assert_ok!(Delegate::delegate(Origin::signed(2), 1, vec![3, 5])); assert_eq!(Balances::free_balance(&2), 92); assert_eq!(RawEvent::DelegateBranch(1, 3, 2, 8), get_last_event()); assert_ok!(Delegate::delegate(Origin::signed(3), 3, vec![1, 2])); assert_eq!(Balances::free_balance(&3), 84); assert_eq!(RawEvent::DelegateBranch(3, 4, 3, 16), get_last_event()); assert_noop!( Delegate::delegate(Origin::signed(2), 4, vec![5, 6]), Error::<TestRuntime>::CannotDelegateBelowMaxDepth ); assert_ok!(Delegate::delegate(Origin::signed(1), 0, vec![5, 6])); assert_eq!(Balances::free_balance(&1), 970); assert_eq!(RawEvent::DelegateBranch(0, 5, 1, 16), get_last_event()); assert_noop!( Delegate::delegate(Origin::signed(1), 0, vec![2, 8]), Error::<TestRuntime>::CannotDelegateAboveMaxKids ); }); } #[test] fn recursive_revoke_works() { new_test_ext().execute_with(|| { assert_ok!(Delegate::create_root(Origin::signed(1))); assert_eq!(RawEvent::RegisterIdRoot(0, 1, 2), get_last_event()); assert_eq!(Balances::free_balance(&1), 998); assert_ok!(Delegate::delegate(Origin::signed(1), 0, vec![2, 3, 4])); assert_eq!(Balances::free_balance(&1), 994); assert_eq!(RawEvent::DelegateBranch(0, 1, 1, 4), get_last_event()); assert_eq!(Balances::free_balance(&1), 994); assert_eq!(RawEvent::DelegateBranch(0, 1, 1, 4), get_last_event()); assert_ok!(Delegate::delegate(Origin::signed(1), 0, vec![3, 4, 6])); assert_eq!(Balances::free_balance(&1), 986); assert_eq!(RawEvent::DelegateBranch(0, 2, 1, 8), get_last_event()); assert_ok!(Delegate::delegate(Origin::signed(2), 1, vec![3, 5])); assert_eq!(Balances::free_balance(&2), 92); assert_eq!(RawEvent::DelegateBranch(1, 3, 2, 8), get_last_event()); assert_ok!(Delegate::delegate(Origin::signed(3), 3, vec![1, 2])); assert_eq!(Balances::free_balance(&3), 84); assert_eq!(RawEvent::DelegateBranch(3, 4, 3, 16), get_last_event()); assert_ok!(Delegate::delegate(Origin::signed(5), 3, vec![1, 2])); assert_eq!(Balances::free_balance(&5), 68); assert_eq!(RawEvent::DelegateBranch(3, 5, 5, 32), get_last_event()); assert_ok!(Delegate::revoke(Origin::signed(1), 0, false)); assert_eq!(Balances::free_balance(&5), 100); assert_eq!(Balances::free_balance(&3), 100); assert_eq!(Balances::free_balance(&1), 1000); assert_eq!(Balances::free_balance(&2), 100); }); }
unwrap(); pallet_balances::GenesisConfig::<TestRuntime> { balances: vec![ (1, 1000), (2, 100), (3, 100), (4, 100), (5, 100), (6, 100), ], } .assimilate_storage(&mut t) .unwrap(); let mut ext: sp_io::TestExternalities = t.into(); ext.execute_with(|| System::set_block_number(1)); ext }
function_block-function_prefix_line
[ { "content": "pub trait Trait: System {\n\n /// Overarching event type\n\n type Event: From<Event<Self>> + Into<<Self as System>::Event>;\n\n\n\n /// The identifier for trees\n\n type TreeId: Parameter\n\n + Member\n\n + AtLeast32Bit\n\n + Codec\n\n + Default\n\n + Copy\n\n + MaybeSerializeDeserialize\n\n + Debug\n\n + PartialOrd\n\n + PartialEq\n\n + Zero;\n\n\n\n /// Bond amount, charged per depth\n\n type Bond: Get<BalanceOf<Self>>;\n\n\n", "file_path": "pallet/src/lib.rs", "rank": 0, "score": 122043.88438855714 }, { "content": "type TreeSt<T> = TreeState<<T as Trait>::TreeId, <T as System>::AccountId>;\n", "file_path": "pallet/src/lib.rs", "rank": 2, "score": 89373.51030809613 }, { "content": "#[cfg(feature = \"std\")]\n\npub fn native_version() -> NativeVersion {\n\n NativeVersion {\n\n runtime_version: VERSION,\n\n can_author_with: Default::default(),\n\n }\n\n}\n\n\n\nparameter_types! {\n\n pub const BlockHashCount: BlockNumber = 250;\n\n /// We allow for 2 seconds of compute with a 6 second average block time.\n\n pub const MaximumBlockWeight: Weight = 2 * WEIGHT_PER_SECOND;\n\n pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);\n\n /// Assume 10% of weight for average on_initialize calls.\n\n pub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get()\n\n .saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get();\n\n pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;\n\n pub const Version: RuntimeVersion = VERSION;\n\n}\n\n\n\nimpl frame_system::Trait for Runtime {\n", "file_path": "node/runtime/src/lib.rs", "rank": 3, "score": 86483.72164489393 }, { "content": "pub fn testnet_genesis(\n\n initial_authorities: Vec<(AuraId, GrandpaId)>,\n\n endowed_accounts: Vec<AccountId>,\n\n) -> GenesisConfig {\n\n GenesisConfig {\n\n frame_system: Some(SystemConfig {\n\n code: WASM_BINARY.to_vec(),\n\n changes_trie_config: Default::default(),\n\n }),\n\n pallet_balances: Some(BalancesConfig {\n\n balances: endowed_accounts\n\n .iter()\n\n .cloned()\n\n .map(|k| (k, 1 << 60))\n\n .collect(),\n\n }),\n\n pallet_aura: Some(AuraConfig {\n\n authorities: initial_authorities\n\n .iter()\n\n .map(|x| (x.0.clone()))\n", "file_path": "node/src/lib.rs", "rank": 4, "score": 67584.81048756083 }, { "content": " trait Store for Module<T: Trait> as Delegate {\n\n /// The nonce for unique tree id generation\n\n TreeIdCounter get(fn tree_id_counter): T::TreeId;\n\n\n\n /// The state of trees\n\n pub Trees get(fn trees): map\n\n hasher(blake2_128_concat) T::TreeId => Option<TreeSt<T>>;\n\n\n\n /// Membership, also tracks bonded amount for existing members\n\n pub Members get(fn members): double_map\n\n hasher(blake2_128_concat) T::TreeId,\n\n hasher(blake2_128_concat) T::AccountId => Option<BalanceOf<T>>;\n\n }\n\n}\n\n\n\ndecl_module! {\n\n pub struct Module<T: Trait> for enum Call where origin: T::Origin {\n\n type Error = Error<T>;\n\n fn deposit_event() = default;\n\n\n", "file_path": "pallet/src/lib.rs", "rank": 5, "score": 63326.96391685682 }, { "content": "type BalanceOf<T> =\n\n <<T as Trait>::Currency as Currency<<T as System>::AccountId>>::Balance;\n", "file_path": "pallet/src/lib.rs", "rank": 6, "score": 61839.296888245524 }, { "content": "pub fn development_config() -> ChainSpec {\n\n ChainSpec::from_genesis(\n\n \"Development\",\n\n \"dev\",\n\n ChainType::Development,\n\n || {\n\n testnet_genesis(\n\n // initial authorities\n\n vec![get_authority_keys_from_seed(\"Alice\")],\n\n // endowed accounts\n\n vec![\n\n get_account_id_from_seed::<sr25519::Public>(\"Alice\"),\n\n get_account_id_from_seed::<sr25519::Public>(\"Bob\"),\n\n get_account_id_from_seed::<sr25519::Public>(\"Alice//stash\"),\n\n get_account_id_from_seed::<sr25519::Public>(\"Bob//stash\"),\n\n ],\n\n )\n\n },\n\n vec![],\n\n None,\n\n None,\n\n None,\n\n None,\n\n )\n\n}\n\n\n", "file_path": "node/src/lib.rs", "rank": 7, "score": 61668.23201614833 }, { "content": "pub fn local_testnet_config() -> ChainSpec {\n\n ChainSpec::from_genesis(\n\n \"Local Testnet\",\n\n \"local_testnet\",\n\n ChainType::Local,\n\n || {\n\n testnet_genesis(\n\n // initial authorities\n\n vec![\n\n get_authority_keys_from_seed(\"Alice\"),\n\n get_authority_keys_from_seed(\"Bob\"),\n\n ],\n\n // endowed accounts\n\n vec![\n\n get_account_id_from_seed::<sr25519::Public>(\"Alice\"),\n\n get_account_id_from_seed::<sr25519::Public>(\"Bob\"),\n\n get_account_id_from_seed::<sr25519::Public>(\"Charlie\"),\n\n get_account_id_from_seed::<sr25519::Public>(\"Dave\"),\n\n get_account_id_from_seed::<sr25519::Public>(\"Eve\"),\n\n get_account_id_from_seed::<sr25519::Public>(\"Ferdie\"),\n", "file_path": "node/src/lib.rs", "rank": 8, "score": 60102.70789364768 }, { "content": "/// Helper function to generate an account ID from seed\n\npub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId\n\nwhere\n\n AccountPublic: From<<TPublic::Pair as Pair>::Public>,\n\n{\n\n AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()\n\n}\n\n\n", "file_path": "node/src/lib.rs", "rank": 9, "score": 58282.324555532454 }, { "content": "/// Helper function to generate a crypto pair from seed\n\npub fn get_from_seed<TPublic: Public>(\n\n seed: &str,\n\n) -> <TPublic::Pair as Pair>::Public {\n\n TPublic::Pair::from_string(&format!(\"//{}\", seed), None)\n\n .expect(\"static values are valid; qed\")\n\n .public()\n\n}\n\n\n", "file_path": "node/src/lib.rs", "rank": 10, "score": 58144.70629694857 }, { "content": "fn force_parity_db(runner: &mut Runner<Cli>) {\n\n let config = runner.config_mut();\n\n let path = config.database.path().unwrap().to_path_buf();\n\n config.database = DatabaseConfig::ParityDb { path };\n\n}\n", "file_path": "node/src/main.rs", "rank": 11, "score": 56812.677221288744 }, { "content": "/// Helper function to generate an authority key for Aura\n\npub fn get_authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) {\n\n (get_from_seed::<AuraId>(s), get_from_seed::<GrandpaId>(s))\n\n}\n\n\n", "file_path": "node/src/lib.rs", "rank": 13, "score": 49906.2183535926 }, { "content": "fn main() {\n\n generate_cargo_keys();\n\n\n\n rerun_if_git_head_changed();\n\n}\n", "file_path": "node/build.rs", "rank": 15, "score": 35385.938812718494 }, { "content": "fn main() {\n\n WasmBuilder::new()\n\n .with_current_project()\n\n .with_wasm_builder_from_crates(\"1.0.9\")\n\n .export_heap_base()\n\n .import_memory()\n\n .build()\n\n}\n", "file_path": "node/runtime/build.rs", "rank": 16, "score": 34144.85612808063 }, { "content": "type AccountPublic = <Signature as Verify>::Signer;\n\n\n", "file_path": "node/src/lib.rs", "rank": 17, "score": 32643.25899483379 }, { "content": "fn main() -> sc_cli::Result<()> {\n\n let cli = <Cli as SubstrateCli>::from_args();\n\n match &cli.subcommand {\n\n Some(subcommand) => {\n\n let mut runner = cli.create_runner(subcommand)?;\n\n force_parity_db(&mut runner);\n\n runner.run_subcommand(subcommand, |config| {\n\n let PartialComponents {\n\n client,\n\n backend,\n\n task_manager,\n\n import_queue,\n\n ..\n\n } = test_node::new_partial(&config)?;\n\n Ok((client, backend, import_queue, task_manager))\n\n })\n\n }\n\n None => {\n\n let mut runner = cli.create_runner(&cli.run)?;\n\n force_parity_db(&mut runner);\n", "file_path": "node/src/main.rs", "rank": 23, "score": 29011.627171096152 }, { "content": " /// The identifier used to distinguish between accounts.\n\n type AccountId = AccountId;\n\n /// The aggregated dispatch type that is available for extrinsics.\n\n type Call = Call;\n\n /// The lookup mechanism to get account ID from whatever is passed in dispatchers.\n\n type Lookup = traits::IdentityLookup<AccountId>;\n\n /// The index type for storing how many extrinsics an account has signed.\n\n type Index = Index;\n\n /// The index type for blocks.\n\n type BlockNumber = BlockNumber;\n\n /// The type for hashing blocks and tries.\n\n type Hash = Hash;\n\n /// The hashing algorithm used.\n\n type Hashing = BlakeTwo256;\n\n /// The header type.\n\n type Header = generic::Header<BlockNumber, BlakeTwo256>;\n\n /// The ubiquitous event type.\n\n type Event = Event;\n\n /// The ubiquitous origin type.\n\n type Origin = Origin;\n", "file_path": "node/runtime/src/lib.rs", "rank": 28, "score": 20.153000457675635 }, { "content": "};\n\npub use pallet_balances::Call as BalancesCall;\n\npub use pallet_timestamp::Call as TimestampCall;\n\n#[cfg(any(feature = \"std\", test))]\n\npub use sp_runtime::BuildStorage;\n\npub use sp_runtime::{\n\n traits,\n\n Perbill,\n\n Permill,\n\n};\n\n\n\n/// Tree identifier\n\npub type TreeId = u64;\n\n\n\n/// An index to a block.\n\npub type BlockNumber = u32;\n\n\n\n/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.\n\npub type Signature = MultiSignature;\n\n\n", "file_path": "node/runtime/src/lib.rs", "rank": 30, "score": 19.56125223281105 }, { "content": " pub const Bond: Balance = 10;\n\n pub const MaxSize: u32 = 5;\n\n pub const MaxDepth: u32 = 5;\n\n pub const MaxKids: u32 = 2;\n\n}\n\nimpl delegate::Trait for Runtime {\n\n type Event = Event;\n\n type TreeId = TreeId;\n\n type Bond = Bond;\n\n type MaxSize = MaxSize;\n\n type MaxDepth = MaxDepth;\n\n type MaxKids = MaxKids;\n\n type Currency = Balances;\n\n}\n\n\n\nconstruct_runtime!(\n\n pub enum Runtime where\n\n Block = Block,\n\n NodeBlock = opaque::Block,\n\n UncheckedExtrinsic = UncheckedExtrinsic\n", "file_path": "node/runtime/src/lib.rs", "rank": 32, "score": 17.627023453439357 }, { "content": " /// The ubiquitous event type.\n\n type Event = Event;\n\n type DustRemoval = ();\n\n type ExistentialDeposit = ExistentialDeposit;\n\n type AccountStore = System;\n\n type WeightInfo = ();\n\n}\n\n\n\nparameter_types! {\n\n pub const TransactionByteFee: Balance = 1;\n\n}\n\n\n\nimpl pallet_transaction_payment::Trait for Runtime {\n\n type Currency = pallet_balances::Module<Runtime>;\n\n type OnTransactionPayment = ();\n\n type TransactionByteFee = TransactionByteFee;\n\n type WeightToFee = IdentityFee<Balance>;\n\n type FeeMultiplierUpdate = ();\n\n}\n\nparameter_types! {\n", "file_path": "node/runtime/src/lib.rs", "rank": 33, "score": 16.78380436485226 }, { "content": " pub grandpa: Grandpa,\n\n }\n\n }\n\n}\n\n\n\nimpl frame_system::offchain::SigningTypes for Runtime {\n\n type Public = <Signature as traits::Verify>::Signer;\n\n type Signature = Signature;\n\n}\n\n\n\nimpl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime\n\nwhere\n\n Call: From<C>,\n\n{\n\n type OverarchingCall = Call;\n\n type Extrinsic = UncheckedExtrinsic;\n\n}\n\n\n\n/// This runtime version.\n\npub const VERSION: RuntimeVersion = RuntimeVersion {\n", "file_path": "node/runtime/src/lib.rs", "rank": 34, "score": 16.415100743289802 }, { "content": " /// Converts a module to the index of the module in `construct_runtime!`.\n\n ///\n\n /// This type is being generated by `construct_runtime!`.\n\n type ModuleToIndex = ModuleToIndex;\n\n /// What to do if a new account is created.\n\n type OnNewAccount = ();\n\n /// What to do if an account is fully reaped from the system.\n\n type OnKilledAccount = ();\n\n /// The data to be stored in an account.\n\n type AccountData = pallet_balances::AccountData<Balance>;\n\n type BaseCallFilter = ();\n\n type SystemWeightInfo = ();\n\n}\n\n\n\nimpl pallet_aura::Trait for Runtime {\n\n type AuthorityId = AuraId;\n\n}\n\n\n\nimpl pallet_grandpa::Trait for Runtime {\n\n type Event = Event;\n", "file_path": "node/runtime/src/lib.rs", "rank": 36, "score": 15.994345374893362 }, { "content": "\n\nparameter_types! {\n\n pub const MinimumPeriod: u64 = SLOT_DURATION / 2;\n\n}\n\n\n\nimpl pallet_timestamp::Trait for Runtime {\n\n /// A timestamp: milliseconds since the unix epoch.\n\n type Moment = u64;\n\n type OnTimestampSet = Aura;\n\n type MinimumPeriod = MinimumPeriod;\n\n type WeightInfo = ();\n\n}\n\n\n\nparameter_types! {\n\n pub const ExistentialDeposit: u128 = 500;\n\n}\n\n\n\nimpl pallet_balances::Trait for Runtime {\n\n /// The type for recording an account's balance.\n\n type Balance = Balance;\n", "file_path": "node/runtime/src/lib.rs", "rank": 37, "score": 15.718592478088745 }, { "content": "/// Some way of identifying an account on the chain. We intentionally make it equivalent\n\n/// to the public key of our transaction signing scheme.\n\npub type AccountId =\n\n <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;\n\n\n\n/// The type for looking up accounts. We don't expect more than 4 billion of them, but you\n\n/// never know...\n\npub type AccountIndex = u32;\n\n\n\n/// Balance of an account.\n\npub type Balance = u128;\n\n\n\n/// Index of a transaction in the chain.\n\npub type Index = u32;\n\n\n\n/// A hash of some data used by the chain.\n\npub type Hash = sp_core::H256;\n\n\n\n/// Digest item type.\n\npub type DigestItem = generic::DigestItem<Hash>;\n", "file_path": "node/runtime/src/lib.rs", "rank": 38, "score": 14.832122866667948 }, { "content": " {\n\n System: frame_system::{Module, Call, Config, Storage, Event<T>},\n\n RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage},\n\n Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent},\n\n Aura: pallet_aura::{Module, Config<T>, Inherent},\n\n Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event},\n\n Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},\n\n TransactionPayment: pallet_transaction_payment::{Module, Storage},\n\n // delegate module\n\n Delegate: delegate::{Module, Call, Storage, Event<T>},\n\n }\n\n);\n\n\n\n/// The address format for describing accounts.\n\npub type Address = AccountId;\n\n/// Block header type as expected by this runtime.\n\npub type Header = generic::Header<BlockNumber, BlakeTwo256>;\n\n/// Block type as expected by this runtime.\n\npub type Block = generic::Block<Header, UncheckedExtrinsic>;\n\n/// A Block signed with a Justification\n", "file_path": "node/runtime/src/lib.rs", "rank": 39, "score": 14.427297896138997 }, { "content": " /// Maximum group size for all trees\n\n type MaxSize: Get<u32>;\n\n\n\n /// Maximum depth for all trees\n\n type MaxDepth: Get<u32>;\n\n\n\n /// Maximum number of subtrees per tree\n\n type MaxKids: Get<u32>;\n\n\n\n /// Currency type\n\n type Currency: Currency<Self::AccountId>\n\n + ReservableCurrency<Self::AccountId>;\n\n}\n\n\n\ndecl_event!(\n\n pub enum Event<T>\n\n where\n\n <T as Trait>::TreeId,\n\n <T as System>::AccountId,\n\n Balance = BalanceOf<T>,\n", "file_path": "pallet/src/lib.rs", "rank": 40, "score": 14.087399979315862 }, { "content": " #[weight = 0]\n\n fn create_root(\n\n origin,\n\n ) -> DispatchResult {\n\n let caller = ensure_signed(origin)?;\n\n let bond = T::Bond::get();\n\n T::Currency::reserve(&caller, bond)?;\n\n let id = Self::gen_uid();\n\n let state = TreeState {\n\n id,\n\n parent: None,\n\n bonded: caller.clone(),\n\n height: 0u32,\n\n kids: 0u32,\n\n size: 1u32,\n\n };\n\n <Trees<T>>::insert(id, state);\n\n <Members<T>>::insert(id, caller.clone(), bond);\n\n Self::deposit_event(RawEvent::RegisterIdRoot(id, caller, bond));\n\n Ok(())\n", "file_path": "pallet/src/lib.rs", "rank": 41, "score": 13.518792111422815 }, { "content": "\n\npub use frame_support::{\n\n construct_runtime,\n\n debug,\n\n parameter_types,\n\n traits::{\n\n KeyOwnerProofSystem,\n\n Randomness,\n\n },\n\n weights::{\n\n constants::{\n\n BlockExecutionWeight,\n\n ExtrinsicBaseWeight,\n\n RocksDbWeight,\n\n WEIGHT_PER_SECOND,\n\n },\n\n IdentityFee,\n\n Weight,\n\n },\n\n StorageValue,\n", "file_path": "node/runtime/src/lib.rs", "rank": 42, "score": 12.235079501256832 }, { "content": " Encode,\n\n};\n\nuse sp_runtime::{\n\n traits::{\n\n AtLeast32Bit,\n\n MaybeSerializeDeserialize,\n\n Member,\n\n Zero,\n\n },\n\n DispatchResult,\n\n};\n\nuse sp_std::{\n\n fmt::Debug,\n\n prelude::*,\n\n};\n\n\n\n#[derive(PartialEq, Eq, Clone, Encode, Decode, sp_runtime::RuntimeDebug)]\n\npub struct TreeState<TreeId, AccountId> {\n\n pub id: TreeId,\n\n pub parent: Option<TreeId>,\n\n pub bonded: AccountId,\n\n pub height: u32,\n\n pub kids: u32,\n\n pub size: u32,\n\n}\n\n\n", "file_path": "pallet/src/lib.rs", "rank": 43, "score": 12.213303095549783 }, { "content": " type Call = Call;\n\n\n\n type KeyOwnerProofSystem = ();\n\n\n\n type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<\n\n (KeyTypeId, AuthorityId),\n\n >>::Proof;\n\n\n\n type KeyOwnerIdentification =\n\n <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(\n\n KeyTypeId,\n\n AuthorityId,\n\n )>>::IdentificationTuple;\n\n\n\n type HandleEquivocation = ();\n\n}\n\n\n\nparameter_types! {\n\n pub const IndexDeposit: Balance = 1u128;\n\n}\n", "file_path": "node/runtime/src/lib.rs", "rank": 44, "score": 12.142243774718004 }, { "content": " decl_event,\n\n decl_module,\n\n decl_storage,\n\n dispatch::DispatchError,\n\n ensure,\n\n storage::IterableStorageMap,\n\n traits::{\n\n Currency,\n\n Get,\n\n ReservableCurrency,\n\n },\n\n Parameter,\n\n};\n\nuse frame_system::{\n\n ensure_signed,\n\n Trait as System,\n\n};\n\nuse parity_scale_codec::{\n\n Codec,\n\n Decode,\n", "file_path": "pallet/src/lib.rs", "rank": 45, "score": 11.848390493061885 }, { "content": " Ok(())\n\n }\n\n }\n\n}\n\n\n\n// Infallible Storage Mutators\n\n// -> check permissions in caller code before calls\n\nimpl<T: Trait> Module<T> {\n\n /// Generate Unique TreeId\n\n pub fn gen_uid() -> T::TreeId {\n\n let mut counter = <TreeIdCounter<T>>::get();\n\n while <Trees<T>>::get(counter).is_some() {\n\n counter += 1u32.into();\n\n }\n\n counter\n\n }\n\n /// Linear Bond\n\n /// -> bond amount scales linearly with number of members in Tree\n\n pub fn reserve_linear_bond(\n\n tree: T::TreeId,\n", "file_path": "pallet/src/lib.rs", "rank": 46, "score": 11.589031835667415 }, { "content": " bonded: caller.clone(),\n\n height: new_height,\n\n kids: 0u32,\n\n size: 0u32,\n\n };\n\n Self::add_mems(state, members);\n\n <Trees<T>>::insert(parent, TreeState {kids: new_kids, ..parent_st});\n\n Self::deposit_event(RawEvent::DelegateBranch(parent, id, caller, bond));\n\n Ok(())\n\n }\n\n #[weight = 0]\n\n fn revoke(\n\n origin,\n\n branch: T::TreeId,\n\n penalty: bool,\n\n ) -> DispatchResult {\n\n let caller = ensure_signed(origin)?;\n\n let tree = <Trees<T>>::get(branch).ok_or(Error::<T>::TreeDNE)?;\n\n ensure!(tree.bonded == caller, Error::<T>::NotAuthorized);\n\n Self::remove_mems(tree, None, penalty);\n", "file_path": "pallet/src/lib.rs", "rank": 47, "score": 11.298508270505327 }, { "content": "\n\n/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know\n\n/// the specifics of the runtime. They can then be made to be agnostic over specific formats\n\n/// of data like extrinsics, allowing for them to continue syncing the network through upgrades\n\n/// to even the core data structures.\n\npub mod opaque {\n\n use super::*;\n\n\n\n pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;\n\n\n\n /// Opaque block header type.\n\n pub type Header = generic::Header<BlockNumber, BlakeTwo256>;\n\n /// Opaque block type.\n\n pub type Block = generic::Block<Header, UncheckedExtrinsic>;\n\n /// Opaque block identifier type.\n\n pub type BlockId = generic::BlockId<Block>;\n\n\n\n impl_opaque_keys! {\n\n pub struct SessionKeys {\n\n pub aura: Aura,\n", "file_path": "node/runtime/src/lib.rs", "rank": 48, "score": 11.181492125096254 }, { "content": " spec_name: create_runtime_str!(\"sun-spec\"),\n\n impl_name: create_runtime_str!(\"sun-time\"),\n\n authoring_version: 1,\n\n // Per convention: if the runtime behavior changes, increment spec_version\n\n // and set impl_version to 0. If only runtime\n\n // implementation changes and behavior does not, then leave spec_version as\n\n // is and increment impl_version.\n\n spec_version: 1,\n\n impl_version: 1,\n\n transaction_version: 1,\n\n apis: RUNTIME_API_VERSIONS,\n\n};\n\n\n\npub const MILLISECS_PER_BLOCK: u64 = 6000;\n\n\n\npub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;\n\n\n\n// These time units are defined in number of blocks.\n\npub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);\n\npub const HOURS: BlockNumber = MINUTES * 60;\n\npub const DAYS: BlockNumber = HOURS * 24;\n\n\n\n/// The version information used to identify this runtime when compiled natively.\n\n#[cfg(feature = \"std\")]\n", "file_path": "node/runtime/src/lib.rs", "rank": 49, "score": 10.611706648759027 }, { "content": "//! The bounds described above are not good enough. The variance of cost for\n\n//! tree deletion is high because it is recursive and high variance poses a\n\n//! problem. Although this recursion is bounded by the constraints, it can\n\n//! still be very expensive if the overall Tree explores the limits of the\n\n//! constraints and revokes the highest root. With this scenario in mind, the\n\n//! incentives should discourage large groups and wide or deep delegation.\n\n//!\n\n//! ### Bonds for Adding Members Scales Linearly With Group Size\n\n//!\n\n//! ### Bonds for Delegating to Tree Scales Exponentially With Depth and Span\n\n//!\n\n//! [`Call`]: ./enum.Call.html\n\n//! [`Trait`]: ./trait.Trait.html\n\n#![cfg_attr(not(feature = \"std\"), no_std)]\n\n\n\n#[cfg(test)]\n\nmod tests;\n\n\n\nuse frame_support::{\n\n decl_error,\n", "file_path": "pallet/src/lib.rs", "rank": 50, "score": 10.26699439442333 }, { "content": " kids: u32,\n\n ) -> Result<BalanceOf<T>, DispatchError> {\n\n let exp = (height + kids) as usize;\n\n // Exponential closure n ^ exp\n\n // - no punishment for calling this and not having enough balance is an attack vector\n\n // -- could match on reservation error and deduct a fee but would cause storage noop\n\n let power = |n: BalanceOf<T>, exp: usize| {\n\n vec![n; exp]\n\n .iter()\n\n .fold(BalanceOf::<T>::zero() + 1u32.into(), |a, b| a * *b)\n\n };\n\n let bond: BalanceOf<T> = power(T::Bond::get(), exp);\n\n T::Currency::reserve(account, bond)?;\n\n let b = if let Some(total) = <Members<T>>::get(tree, account) {\n\n total + bond\n\n } else {\n\n bond\n\n };\n\n <Members<T>>::insert(tree, account, b);\n\n Ok(bond)\n", "file_path": "pallet/src/lib.rs", "rank": 51, "score": 10.08528721994811 }, { "content": " Self::deposit_event(RawEvent::RevokeDelegation(branch));\n\n Ok(())\n\n }\n\n #[weight = 0]\n\n fn add_members(\n\n origin,\n\n tree_id: T::TreeId,\n\n members: Vec<T::AccountId>,\n\n ) -> DispatchResult {\n\n let caller = ensure_signed(origin)?;\n\n let tree = <Trees<T>>::get(tree_id).ok_or(Error::<T>::TreeDNE)?;\n\n // auth requires member of direct parent || bonded caller\n\n let auth = if let Some(p) = tree.parent {\n\n <Members<T>>::get(p, &caller).is_some()\n\n } else { tree.bonded == caller };\n\n ensure!(auth, Error::<T>::NotAuthorized);\n\n let mut mems = members; mems.dedup();\n\n let new_size = mems.len() as u32 + tree.size;\n\n ensure!(new_size <= T::MaxSize::get(), Error::<T>::CannotAddGroupAboveMaxSize);\n\n let bond = Self::reserve_linear_bond(tree_id, &caller, new_size)?;\n", "file_path": "pallet/src/lib.rs", "rank": 52, "score": 9.600785248067218 }, { "content": " account: &T::AccountId,\n\n new_size: u32,\n\n ) -> Result<BalanceOf<T>, DispatchError> {\n\n let bond: BalanceOf<T> = T::Bond::get() * new_size.into();\n\n T::Currency::reserve(account, bond)?;\n\n let b = if let Some(total) = <Members<T>>::get(tree, account) {\n\n total + bond\n\n } else {\n\n bond\n\n };\n\n <Members<T>>::insert(tree, account, b);\n\n Ok(bond)\n\n }\n\n /// Exponential Bond\n\n /// -> bond amount scales exponentially with height and number of kids\n\n /// ```(bond)^{height} * (bond)^{kids} = (bond)^{height + kids}```\n\n pub fn reserve_exponential_bond(\n\n tree: T::TreeId,\n\n account: &T::AccountId,\n\n height: u32,\n", "file_path": "pallet/src/lib.rs", "rank": 53, "score": 9.543013197088664 }, { "content": "pub type SignedBlock = generic::SignedBlock<Block>;\n\n/// BlockId type as expected by this runtime.\n\npub type BlockId = generic::BlockId<Block>;\n\n/// The SignedExtension to the basic transaction logic.\n\npub type SignedExtra = (\n\n frame_system::CheckSpecVersion<Runtime>,\n\n frame_system::CheckTxVersion<Runtime>,\n\n frame_system::CheckGenesis<Runtime>,\n\n frame_system::CheckEra<Runtime>,\n\n frame_system::CheckNonce<Runtime>,\n\n frame_system::CheckWeight<Runtime>,\n\n pallet_transaction_payment::ChargeTransactionPayment<Runtime>,\n\n);\n\n/// Unchecked extrinsic type as expected by this runtime.\n\npub type UncheckedExtrinsic =\n\n generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;\n\n/// The payload being signed in transactions.\n\npub type SignedPayload = generic::SignedPayload<Call, SignedExtra>;\n\n/// Extrinsic type that has already been checked.\n\npub type CheckedExtrinsic =\n", "file_path": "node/runtime/src/lib.rs", "rank": 54, "score": 9.502360356862216 }, { "content": " generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;\n\n/// Executive: handles dispatch to the various modules.\n\npub type Executive = frame_executive::Executive<\n\n Runtime,\n\n Block,\n\n frame_system::ChainContext<Runtime>,\n\n Runtime,\n\n AllModules,\n\n>;\n\n\n\nimpl_runtime_apis! {\n\n impl sp_api::Core<Block> for Runtime {\n\n fn version() -> RuntimeVersion {\n\n VERSION\n\n }\n\n\n\n fn execute_block(block: Block) {\n\n Executive::execute_block(block)\n\n }\n\n\n", "file_path": "node/runtime/src/lib.rs", "rank": 55, "score": 9.450136532162109 }, { "content": "use sc_cli::{\n\n RunCmd,\n\n Runner,\n\n RuntimeVersion,\n\n Subcommand,\n\n SubstrateCli,\n\n};\n\nuse sc_service::{\n\n ChainSpec,\n\n DatabaseConfig,\n\n PartialComponents,\n\n Role,\n\n};\n\nuse structopt::StructOpt;\n\n\n\n#[derive(Debug, StructOpt)]\n\npub struct Cli {\n\n #[structopt(subcommand)]\n\n pub subcommand: Option<Subcommand>,\n\n\n", "file_path": "node/src/main.rs", "rank": 56, "score": 9.417721360690424 }, { "content": "use sc_executor::native_executor_instance;\n\nuse sc_service::ChainType;\n\nuse sp_core::{\n\n sr25519,\n\n Pair,\n\n Public,\n\n};\n\nuse sp_runtime::traits::{\n\n IdentifyAccount,\n\n Verify,\n\n};\n\nuse sunshine_node_utils::node_service;\n\nuse test_runtime::{\n\n AccountId,\n\n AuraConfig,\n\n BalancesConfig,\n\n GenesisConfig,\n\n GrandpaConfig,\n\n Signature,\n\n SystemConfig,\n", "file_path": "node/src/lib.rs", "rank": 57, "score": 9.394105995646447 }, { "content": " penalty: bool,\n\n ) {\n\n let mut size_decrease = 0u32;\n\n if let Some(mut mem) = mems {\n\n mem.dedup();\n\n mem.into_iter().for_each(|m| {\n\n if let Some(bond) = <Members<T>>::get(tree.id, &m) {\n\n // constraint: cannot remove the account who created the hierarchy\n\n if tree.bonded != m {\n\n T::Currency::unreserve(&m, bond);\n\n if penalty {\n\n // (could) transfer the bond to some (treasury) account\n\n // instead of returning the bond\n\n todo!();\n\n }\n\n <Members<T>>::remove(tree.id, m);\n\n size_decrease += 1u32;\n\n }\n\n }\n\n });\n", "file_path": "pallet/src/lib.rs", "rank": 58, "score": 9.195848123282925 }, { "content": "use sp_runtime::{\n\n create_runtime_str,\n\n generic,\n\n impl_opaque_keys,\n\n traits::{\n\n BlakeTwo256,\n\n Block as BlockT,\n\n IdentifyAccount,\n\n NumberFor,\n\n Saturating,\n\n Verify,\n\n },\n\n transaction_validity::TransactionValidity,\n\n ApplyExtrinsicResult,\n\n MultiSignature,\n\n};\n\nuse sp_std::prelude::*;\n\n#[cfg(feature = \"std\")]\n\nuse sp_version::NativeVersion;\n\nuse sp_version::RuntimeVersion;\n", "file_path": "node/runtime/src/lib.rs", "rank": 59, "score": 8.819788073669 }, { "content": " }\n\n /// Add Members to Tree\n\n pub fn add_mems(mut tree: TreeSt<T>, mut mems: Vec<T::AccountId>) {\n\n mems.dedup();\n\n let mut size_increase = 0u32;\n\n mems.into_iter().for_each(|m| {\n\n // only insert if profile does not already exist\n\n if <Members<T>>::get(tree.id, &m).is_none() {\n\n <Members<T>>::insert(tree.id, m, BalanceOf::<T>::zero());\n\n size_increase += 1u32;\n\n }\n\n });\n\n // insert actual size increase\n\n tree.size += size_increase;\n\n <Trees<T>>::insert(tree.id, tree);\n\n }\n\n /// Remove Members of Tree\n\n pub fn remove_mems(\n\n mut tree: TreeSt<T>,\n\n mems: Option<Vec<T::AccountId>>,\n", "file_path": "pallet/src/lib.rs", "rank": 60, "score": 8.460280830196433 }, { "content": "#![recursion_limit = \"256\"]\n\n//! # Delegate Module\n\n//! This module demonstrates an approach for bounding runtime\n\n//! recursion. In particular, it places module-level constraints on\n\n//! * the size of each group\n\n//! * the number of subgroups\n\n//! * the depth of delegation\n\n//! These constraints allow us to use recursion in the module\n\n//! with strict bounds on worst-case complexity.\n\n//!\n\n//! - [`delegate::Trait`](./trait.Trait.html)\n\n//! - [`Call`](./enum.Call.html)\n\n//!\n\n//! ## Overview\n\n//! This pallet allows delegation to a bounded depth. The incentives discourage\n\n//! (1) adding members to large groups\n\n//! (2) delegating to a new subgroup\n\n//! The module enforces strict bounds on the size of a group, the number of\n\n//! subgroups, and the depth of delegation to place explicit bounds on runtime\n\n//! recursion. Each group registered on-chain has a `TreeId`. To get the state\n", "file_path": "pallet/src/lib.rs", "rank": 61, "score": 8.209406610577 }, { "content": " }\n\n #[weight = 0]\n\n fn delegate(\n\n origin,\n\n parent: T::TreeId,\n\n members: Vec<T::AccountId>,\n\n ) -> DispatchResult {\n\n let caller = ensure_signed(origin)?;\n\n ensure!(<Members<T>>::get(parent, &caller).is_some(), Error::<T>::NotAuthorized);\n\n let parent_st = <Trees<T>>::get(parent).ok_or(Error::<T>::TreeDNE)?;\n\n let (new_kids, new_height) = (parent_st.kids + 1u32, parent_st.height + 1u32);\n\n // check that delegating does not violate module kids constraints (num of children)\n\n ensure!(new_kids <= T::MaxKids::get(), Error::<T>::CannotDelegateAboveMaxKids);\n\n // check that delegating does not violate module depth constraints\n\n ensure!(new_height <= T::MaxDepth::get(), Error::<T>::CannotDelegateBelowMaxDepth);\n\n let bond = Self::reserve_exponential_bond(parent, &caller, new_height, new_kids)?;\n\n let id = Self::gen_uid();\n\n let state = TreeState {\n\n id,\n\n parent: Some(parent_st.id),\n", "file_path": "pallet/src/lib.rs", "rank": 62, "score": 7.82533076436332 }, { "content": " {\n\n RegisterIdRoot(TreeId, AccountId, Balance),\n\n AddedMembers(AccountId, TreeId, Balance),\n\n RemovedMembers(AccountId, TreeId),\n\n DelegateBranch(TreeId, TreeId, AccountId, Balance),\n\n RevokeDelegation(TreeId),\n\n }\n\n);\n\n\n\ndecl_error! {\n\n pub enum Error for Module<T: Trait> {\n\n // Tree does not exist\n\n TreeDNE,\n\n NotAuthorized,\n\n CannotAddGroupAboveMaxSize,\n\n CannotDelegateBelowMaxDepth,\n\n CannotDelegateAboveMaxKids,\n\n }\n\n}\n\n\n\ndecl_storage! {\n", "file_path": "pallet/src/lib.rs", "rank": 63, "score": 7.792968747011701 }, { "content": " #[structopt(flatten)]\n\n pub run: RunCmd,\n\n}\n\n\n\nimpl SubstrateCli for Cli {\n\n fn impl_name() -> String {\n\n test_node::IMPL_NAME.into()\n\n }\n\n\n\n fn impl_version() -> String {\n\n test_node::IMPL_VERSION.into()\n\n }\n\n\n\n fn description() -> String {\n\n test_node::DESCRIPTION.into()\n\n }\n\n\n\n fn author() -> String {\n\n test_node::AUTHOR.into()\n\n }\n", "file_path": "node/src/main.rs", "rank": 64, "score": 7.417338164986029 }, { "content": " Self::add_mems(tree, mems);\n\n Self::deposit_event(RawEvent::AddedMembers(caller, tree_id, bond));\n\n Ok(())\n\n }\n\n #[weight = 0]\n\n fn remove_members(\n\n origin,\n\n tree_id: T::TreeId,\n\n members: Vec<T::AccountId>,\n\n penalty: bool,\n\n ) -> DispatchResult {\n\n let caller = ensure_signed(origin)?;\n\n let tree = <Trees<T>>::get(tree_id).ok_or(Error::<T>::TreeDNE)?;\n\n // auth requires member of direct parent || bonded caller\n\n let auth = if let Some(p) = tree.parent {\n\n <Members<T>>::get(p, &caller).is_some()\n\n } else { tree.bonded == caller };\n\n ensure!(auth, Error::<T>::NotAuthorized);\n\n Self::remove_mems(tree, Some(members), penalty);\n\n Self::deposit_event(RawEvent::RemovedMembers(caller, tree_id));\n", "file_path": "pallet/src/lib.rs", "rank": 65, "score": 7.278060525321486 }, { "content": " /// Maximum number of block number to block hash mappings to keep (oldest pruned first).\n\n type BlockHashCount = BlockHashCount;\n\n /// Maximum weight of each block.\n\n type MaximumBlockWeight = MaximumBlockWeight;\n\n /// Maximum size of all encoded transactions (in bytes) that are allowed in one block.\n\n type MaximumBlockLength = MaximumBlockLength;\n\n /// Portion of the block weight that is available to all normal transactions.\n\n type AvailableBlockRatio = AvailableBlockRatio;\n\n /// The weight of the overhead invoked on the block import process, independent of the\n\n /// extrinsics included in that block.\n\n type BlockExecutionWeight = BlockExecutionWeight;\n\n /// The weight of database operations that the runtime can invoke.\n\n type DbWeight = RocksDbWeight;\n\n /// The base weight of any extrinsic processed by the runtime, independent of the\n\n /// logic of that extrinsic. (Signature verification, nonce increment, fee, etc...)\n\n type ExtrinsicBaseWeight = ExtrinsicBaseWeight;\n\n /// The maximum weight for any extrinsic\n\n type MaximumExtrinsicWeight = MaximumExtrinsicWeight;\n\n /// Version of the runtime.\n\n type Version = Version;\n", "file_path": "node/runtime/src/lib.rs", "rank": 66, "score": 7.244405939935623 }, { "content": "//! of a group, we use the `Trees` map\n\n//! ```rust, ignore\n\n//! map TreeId => Option<TreeState<T::TreeId, T::AccountId>>;\n\n//! ```\n\n//! The `TreeState<_, _>` struct contains the data relevant to the bounds that\n\n//! the module places on length, width and depth.\n\n//! ```rust, ignore\n\n//! pub struct TreeState<TreeId, AccountId> {\n\n//! pub id: TreeId,\n\n//! pub parent: Option<TreeId>,\n\n//! pub bonded: AccountId,\n\n//! pub height: u32,\n\n//! pub kids: u32,\n\n//! pub size: u32,\n\n//! }\n\n//! ```\n\n//! The module's runtime configuration sets the maximum depth (`height`),\n\n//! number of subgroups (`kids`), and number of members (`size`). Each\n\n//! `TreeState<_, _>` is either a root or the child of a parent tree.\n\n//! We define an algorithm for tree creation.\n", "file_path": "pallet/src/lib.rs", "rank": 67, "score": 7.171075501198186 }, { "content": " WASM_BINARY,\n\n};\n\n\n\npub const IMPL_NAME: &str = \"Sunshine Node\";\n\npub const IMPL_VERSION: &str = env!(\"CARGO_PKG_VERSION\");\n\npub const DESCRIPTION: &str = env!(\"CARGO_PKG_DESCRIPTION\");\n\npub const AUTHOR: &str = env!(\"CARGO_PKG_AUTHORS\");\n\npub const SUPPORT_URL: &str = env!(\"CARGO_PKG_HOMEPAGE\");\n\npub const COPYRIGHT_START_YEAR: i32 = 2020;\n\npub const EXECUTABLE_NAME: &str = env!(\"CARGO_PKG_NAME\");\n\n\n\nnative_executor_instance!(\n\n pub Executor,\n\n test_runtime::api::dispatch,\n\n test_runtime::native_version,\n\n);\n\n\n\nnode_service!(\n\n test_runtime::opaque::Block,\n\n test_runtime::RuntimeApi,\n\n Executor\n\n);\n\n\n\n/// Specialized `ChainSpec`.\n\npub type ChainSpec = sc_service::GenericChainSpec<GenesisConfig>;\n\n\n\n/// Helper function to generate a crypto pair from seed\n", "file_path": "node/src/lib.rs", "rank": 68, "score": 6.5856036581310455 }, { "content": " }\n\n\n\n impl sp_offchain::OffchainWorkerApi<Block> for Runtime {\n\n fn offchain_worker(header: &<Block as BlockT>::Header) {\n\n Executive::offchain_worker(header)\n\n }\n\n }\n\n\n\n impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {\n\n fn slot_duration() -> u64 {\n\n Aura::slot_duration()\n\n }\n\n\n\n fn authorities() -> Vec<AuraId> {\n\n Aura::authorities()\n\n }\n\n }\n\n\n\n impl sp_session::SessionKeys<Block> for Runtime {\n\n fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {\n", "file_path": "node/runtime/src/lib.rs", "rank": 69, "score": 6.438717164950031 }, { "content": "#![allow(clippy::large_enum_variant)]\n\n#![cfg_attr(not(feature = \"std\"), no_std)]\n\n// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.\n\n#![recursion_limit = \"256\"]\n\n\n\n// Make the WASM binary available.\n\n#[cfg(feature = \"std\")]\n\ninclude!(concat!(env!(\"OUT_DIR\"), \"/wasm_binary.rs\"));\n\n\n\nuse pallet_grandpa::{\n\n fg_primitives,\n\n AuthorityId,\n\n AuthorityList as GrandpaAuthorityList,\n\n};\n\nuse sp_api::impl_runtime_apis;\n\nuse sp_consensus_aura::sr25519::AuthorityId as AuraId;\n\nuse sp_core::{\n\n crypto::KeyTypeId,\n\n OpaqueMetadata,\n\n};\n", "file_path": "node/runtime/src/lib.rs", "rank": 70, "score": 6.293078647035683 }, { "content": "# Delegate\n\n\n\nThis pallet demonstrates how to safely bound runtime recursion with module-level constraints. The associated types of the module's Trait bound and disincentivize (1) large, (2) wide, and (3) deep tree delegation.\n\n1. group size, number of members `Vec<AccountId>` associated on-chain with `TreeId` s.t. each tree can only have up to `Trait::MaxSize` members in total\n\n2. number of subtrees, each tree can only have up to `Trait::MaxKids` number of subtrees for delegation\n\n3. depth, a tree can only have height up to `Trait::MaxDepth` or it is not allowed to be created for delegation, `depth_of_child = depth_of_parent + 1`\n\n\n\nAdding new members and delegating to subtrees is disincentivized by collateral requirements. Bonds for adding new members scale linearly with group size. Bonds for adding new subtrees scales exponentially with number of children and depth.\n\n\n\n## Rules\n\n\n\n* Any account can register a tree with a `TreeId` and add a set of members `Vec<AccountId>`\n\n* If the `TreeState` has `height = 0`, the account that registered the Tree is the only account that can add and remove members\n\n* Otherwise (`height > 0`), any account in the parent tree can add or remove members (as long as new member count is leq `Trait::MaxSize`)\n\n* Any member of the set `Vec<AccountId>` associated with the `TreeId` can delegate permissions to a new `TreeId` (as long as subtree height is leq `Trait::MaxDepth` and parent's kid count is leq `Trait::MaxKids`)\n\n* Only the account that registered the Tree can revoke it, triggering recursion to delete all subtrees. To disincentivize expensive recursion, actions for adding members and adding subtrees require collateral in proportion to the marginal contribution of each action to worst case deletion complexity.\n\n * Collateral requirements for adding new members scale linearly with group size. \n", "file_path": "README.md", "rank": 71, "score": 5.743065186236498 }, { "content": "//! ```ignore\n\n//! TreeCreation(parent: TreeState<_, _>)\n\n//! let kid = TreeState {\n\n//! parent: Some(parent.id)\n\n//! height: parent.height + 1u32,\n\n//! ..\n\n//! }\n\n//! parent.kids += 1u32;\n\n//! Storage::insert(kid);\n\n//! Storage::insert(parent)\n\n//! ```\n\n//! Before this algorithm is called, the runtime methods verify that\n\n//! the kid's height does not exceed the `Trait::MaxDepth` and the parent's\n\n//! kid count does not exceed `Trait::MaxKids`.\n\n//!\n\n//! Similarly, the runtime verifies that the new group count is below\n\n//! the `Trait::MaxSize` before adding new members to the set of `AccountId`\n\n//! associated on-chain with the group `TreeId`.\n\n//!\n\n//! ## Incentives\n", "file_path": "pallet/src/lib.rs", "rank": 73, "score": 5.511879289720847 }, { "content": " fn initialize_block(header: &<Block as BlockT>::Header) {\n\n Executive::initialize_block(header)\n\n }\n\n }\n\n\n\n impl sp_api::Metadata<Block> for Runtime {\n\n fn metadata() -> OpaqueMetadata {\n\n Runtime::metadata().into()\n\n }\n\n }\n\n\n\n impl sp_block_builder::BlockBuilder<Block> for Runtime {\n\n fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {\n\n Executive::apply_extrinsic(extrinsic)\n\n }\n\n\n\n fn finalize_block() -> <Block as BlockT>::Header {\n\n Executive::finalize_block()\n\n }\n\n\n", "file_path": "node/runtime/src/lib.rs", "rank": 74, "score": 4.996364927762014 }, { "content": " // insert actual size decrease\n\n tree.size -= size_decrease;\n\n <Trees<T>>::insert(tree.id, tree);\n\n } else {\n\n <Members<T>>::iter_prefix(tree.id).for_each(|(a, b)| {\n\n T::Currency::unreserve(&a, b);\n\n if penalty {\n\n // (could) transfer the bond to some (treasury) account\n\n // instead of returning the bond\n\n todo!();\n\n }\n\n <Members<T>>::remove(tree.id, a);\n\n size_decrease += 1u32;\n\n });\n\n // if parent exists, decrement parent kids count\n\n if let Some(p) = tree.parent {\n\n if let Some(tp) = <Trees<T>>::get(p) {\n\n <Trees<T>>::insert(\n\n p,\n\n TreeState {\n", "file_path": "pallet/src/lib.rs", "rank": 75, "score": 4.875329683767991 }, { "content": " opaque::SessionKeys::generate(seed)\n\n }\n\n\n\n fn decode_session_keys(\n\n encoded: Vec<u8>,\n\n ) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {\n\n opaque::SessionKeys::decode_into_raw_public_keys(&encoded)\n\n }\n\n }\n\n\n\n impl fg_primitives::GrandpaApi<Block> for Runtime {\n\n fn grandpa_authorities() -> GrandpaAuthorityList {\n\n Grandpa::grandpa_authorities()\n\n }\n\n fn submit_report_equivocation_unsigned_extrinsic(\n\n _equivocation_proof: fg_primitives::EquivocationProof<\n\n <Block as BlockT>::Hash,\n\n NumberFor<Block>,\n\n >,\n\n _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,\n", "file_path": "node/runtime/src/lib.rs", "rank": 76, "score": 3.7484966399186774 }, { "content": " kids: tp.kids - 1,\n\n ..tp\n\n },\n\n );\n\n }\n\n }\n\n // Recursively remove all Children\n\n // runtime recursion bounded by module-level constraints on\n\n // * delegation depth/height (MaxDepth)\n\n // * children (subtrees) per tree (MaxKids)\n\n // * members (accounts) per tree (MaxSize)\n\n <Trees<T>>::iter().for_each(|(_, child)| {\n\n if child.parent == Some(tree.id) {\n\n Self::remove_mems(child, None, penalty);\n\n }\n\n });\n\n }\n\n }\n\n}\n", "file_path": "pallet/src/lib.rs", "rank": 77, "score": 3.305339259286845 }, { "content": " path => {\n\n Box::new(test_node::ChainSpec::from_json_file(path.into())?)\n\n }\n\n })\n\n }\n\n\n\n fn native_runtime_version(\n\n _: &Box<dyn ChainSpec>,\n\n ) -> &'static RuntimeVersion {\n\n &test_runtime::VERSION\n\n }\n\n}\n\n\n", "file_path": "node/src/main.rs", "rank": 78, "score": 3.157032786163076 }, { "content": " get_account_id_from_seed::<sr25519::Public>(\"Alice//stash\"),\n\n get_account_id_from_seed::<sr25519::Public>(\"Bob//stash\"),\n\n get_account_id_from_seed::<sr25519::Public>(\n\n \"Charlie//stash\",\n\n ),\n\n get_account_id_from_seed::<sr25519::Public>(\"Dave//stash\"),\n\n get_account_id_from_seed::<sr25519::Public>(\"Eve//stash\"),\n\n get_account_id_from_seed::<sr25519::Public>(\n\n \"Ferdie//stash\",\n\n ),\n\n ],\n\n )\n\n },\n\n vec![],\n\n None,\n\n None,\n\n None,\n\n None,\n\n )\n\n}\n\n\n", "file_path": "node/src/lib.rs", "rank": 79, "score": 2.918847740283818 }, { "content": "use substrate_wasm_builder_runner::WasmBuilder;\n\n\n", "file_path": "node/runtime/build.rs", "rank": 80, "score": 2.6863147317277183 }, { "content": " ) -> Option<()> {\n\n None\n\n }\n\n\n\n fn generate_key_ownership_proof(\n\n _set_id: fg_primitives::SetId,\n\n _authority_id: AuthorityId,\n\n ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {\n\n // NOTE: this is the only implementation possible since we've\n\n // defined our key owner proof type as a bottom type (i.e. a type\n\n // with no values).\n\n None\n\n }\n\n }\n\n}\n", "file_path": "node/runtime/src/lib.rs", "rank": 81, "score": 2.5721139610932804 }, { "content": "use substrate_build_script_utils::{\n\n generate_cargo_keys,\n\n rerun_if_git_head_changed,\n\n};\n\n\n", "file_path": "node/build.rs", "rank": 82, "score": 2.4539840547245424 }, { "content": " fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {\n\n data.create_extrinsics()\n\n }\n\n\n\n fn check_inherents(\n\n block: Block,\n\n data: sp_inherents::InherentData,\n\n ) -> sp_inherents::CheckInherentsResult {\n\n data.check_extrinsics(&block)\n\n }\n\n\n\n fn random_seed() -> <Block as BlockT>::Hash {\n\n RandomnessCollectiveFlip::random_seed()\n\n }\n\n }\n\n\n\n impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {\n\n fn validate_transaction(source: sp_runtime::transaction_validity::TransactionSource, uxt: <Block as BlockT>::Extrinsic) -> TransactionValidity {\n\n Executive::validate_transaction(source, uxt)\n\n }\n", "file_path": "node/runtime/src/lib.rs", "rank": 83, "score": 2.3697096428060505 } ]
Rust
src/run_plan.rs
camchenry/lolbench
941ebb099a398ad33cb3658bcd021a98081dfa80
use super::Result; use std::{ fmt::{Display, Formatter, Result as FmtResult}, path::PathBuf, process::Command, }; use ring::digest::{digest, SHA256}; use marky_mark::Benchmark; use cpu_shield::{RenameThisCommandWrapper, ShieldSpec}; use toolchain::Toolchain; use CriterionConfig; #[derive(Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Ord, Serialize)] pub struct RunPlan { pub binary_name: String, pub benchmark: Benchmark, pub toolchain: Option<Toolchain>, pub bench_config: Option<CriterionConfig>, pub shield: Option<ShieldSpec>, pub source_path: PathBuf, pub manifest_path: PathBuf, } impl Display for RunPlan { fn fmt(&self, f: &mut Formatter) -> FmtResult { let tcs = self .toolchain .as_ref() .map(|tc| tc.to_string()) .unwrap_or_else(|| "current".to_string()); f.write_fmt(format_args!( "{}: {}::{}@{:?}", tcs, self.benchmark.crate_name, self.benchmark.name, self.benchmark.runner, )) } } impl RunPlan { pub fn new( benchmark: Benchmark, bench_config: Option<CriterionConfig>, shield: Option<ShieldSpec>, toolchain: Option<Toolchain>, source_path: PathBuf, ) -> Result<Self> { let binary_name = source_path .file_stem() .unwrap() .to_string_lossy() .to_string(); let mut manifest_path = None; for dir in source_path.ancestors() { let candidate = dir.join("Cargo.toml"); if candidate.is_file() { manifest_path = Some(candidate); break; } } let manifest_path = manifest_path.unwrap(); Ok(Self { benchmark, shield, toolchain, source_path, manifest_path, binary_name, bench_config, }) } fn binary_path(&self) -> PathBuf { self.target_dir().join("release").join(&self.binary_name) } fn target_dir(&self) -> PathBuf { use std::env::var as envvar; match self.toolchain { Some(ref t) => t.target_dir(), None => { PathBuf::from(envvar("CARGO_TARGET_DIR").unwrap_or_else(|_| String::from("target"))) } } } pub fn validate(&self) -> Result<()> { ensure!(self.source_path.is_file(), "source_path is not a file"); ensure!(self.manifest_path.is_file(), "manifest_path is not a file"); if let Some(_spec) = &self.shield { } if let Some(_cfg) = &self.bench_config { } Ok(()) } pub fn build(&self) -> Result<Vec<u8>> { let target_name = self.source_path.file_stem().unwrap().to_string_lossy(); info!("building {} with {:?}", target_name, self.toolchain); let mut cmd = Command::new("cargo"); if let Some(ref t) = self.toolchain { cmd.arg(format!("+{}", t)); } let output = cmd .arg("build") .arg("--release") .arg("--manifest-path") .arg(&self.manifest_path) .arg("--bin") .arg(&*target_name) .env("CARGO_TARGET_DIR", &*self.target_dir()) .output()?; if !output.status.success() { let stdout = String::from_utf8_lossy(&output.stdout); let stderr = String::from_utf8_lossy(&output.stderr); bail!( "Unable to build {} with {:?} (None means current, adam is lazy).\nstdout:{}\nstderr:{}", target_name, self.toolchain, stdout, stderr ); } info!("done building {}", self.source_path.display()); let bin_path = self.binary_path(); debug!("reading contents of {} at {}", self, bin_path.display()); let bin_contents = ::std::fs::read(&bin_path)?; debug!("hashing binary contents"); Ok(digest(&SHA256, &bin_contents).as_ref().to_owned()) } pub fn exec(&self) -> Result<()> { debug!("configuring command for {}", self); let mut cmd = RenameThisCommandWrapper::new("cargo", self.shield.clone()); if let Some(ref t) = self.toolchain { cmd.arg(format!("+{}", t)); } cmd.args(&["run", "--release", "--manifest-path"]); cmd.arg(&self.manifest_path); cmd.args(&["--bin", &self.binary_name]); cmd.env("CARGO_TARGET_DIR", &*self.target_dir()); if let Some(cfg) = &self.bench_config { debug!("applying criterion config"); for (k, v) in cfg.envs() { cmd.env(k, v); } } debug!("running {} with {:?}", self, cmd); let output = cmd.output()?; let stdout = String::from_utf8_lossy(&output.stdout); let stderr = String::from_utf8_lossy(&output.stderr); if !output.status.success() { bail!("benchmark failed! stdout: {}, stderr: {}", stdout, stderr); } Ok(()) } }
use super::Result; use std::{ fmt::{Display, Formatter, Result as FmtResult}, path::PathBuf, process::Command, }; use ring::digest::{digest, SHA256}; use marky_mark::Benchmark; use cpu_shield::{RenameThisCommandWrapper, ShieldSpec}; use toolchain::Toolchain; use CriterionConfig; #[derive(Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Ord, Serialize)] pub struct RunPlan { pub binary_name: String, pub benchmark: Benchmark, pub toolchain: Option<Toolchain>, pub bench_config: Option<CriterionConfig>, pub shield: Option<ShieldSpec>, pub source_path: PathBuf, pub manifest_path: PathBuf, } impl Display for RunPlan { fn fmt(&self, f: &mut Formatter) -> FmtResult { let tcs = self .toolchain .as_ref() .map(|tc| tc.to_string()) .unwrap_or_else(|| "current".to_string()); f.write_fmt(format_arg
} impl RunPlan { pub fn new( benchmark: Benchmark, bench_config: Option<CriterionConfig>, shield: Option<ShieldSpec>, toolchain: Option<Toolchain>, source_path: PathBuf, ) -> Result<Self> { let binary_name = source_path .file_stem() .unwrap() .to_string_lossy() .to_string(); let mut manifest_path = None; for dir in source_path.ancestors() { let candidate = dir.join("Cargo.toml"); if candidate.is_file() { manifest_path = Some(candidate); break; } } let manifest_path = manifest_path.unwrap(); Ok(Self { benchmark, shield, toolchain, source_path, manifest_path, binary_name, bench_config, }) } fn binary_path(&self) -> PathBuf { self.target_dir().join("release").join(&self.binary_name) } fn target_dir(&self) -> PathBuf { use std::env::var as envvar; match self.toolchain { Some(ref t) => t.target_dir(), None => { PathBuf::from(envvar("CARGO_TARGET_DIR").unwrap_or_else(|_| String::from("target"))) } } } pub fn validate(&self) -> Result<()> { ensure!(self.source_path.is_file(), "source_path is not a file"); ensure!(self.manifest_path.is_file(), "manifest_path is not a file"); if let Some(_spec) = &self.shield { } if let Some(_cfg) = &self.bench_config { } Ok(()) } pub fn build(&self) -> Result<Vec<u8>> { let target_name = self.source_path.file_stem().unwrap().to_string_lossy(); info!("building {} with {:?}", target_name, self.toolchain); let mut cmd = Command::new("cargo"); if let Some(ref t) = self.toolchain { cmd.arg(format!("+{}", t)); } let output = cmd .arg("build") .arg("--release") .arg("--manifest-path") .arg(&self.manifest_path) .arg("--bin") .arg(&*target_name) .env("CARGO_TARGET_DIR", &*self.target_dir()) .output()?; if !output.status.success() { let stdout = String::from_utf8_lossy(&output.stdout); let stderr = String::from_utf8_lossy(&output.stderr); bail!( "Unable to build {} with {:?} (None means current, adam is lazy).\nstdout:{}\nstderr:{}", target_name, self.toolchain, stdout, stderr ); } info!("done building {}", self.source_path.display()); let bin_path = self.binary_path(); debug!("reading contents of {} at {}", self, bin_path.display()); let bin_contents = ::std::fs::read(&bin_path)?; debug!("hashing binary contents"); Ok(digest(&SHA256, &bin_contents).as_ref().to_owned()) } pub fn exec(&self) -> Result<()> { debug!("configuring command for {}", self); let mut cmd = RenameThisCommandWrapper::new("cargo", self.shield.clone()); if let Some(ref t) = self.toolchain { cmd.arg(format!("+{}", t)); } cmd.args(&["run", "--release", "--manifest-path"]); cmd.arg(&self.manifest_path); cmd.args(&["--bin", &self.binary_name]); cmd.env("CARGO_TARGET_DIR", &*self.target_dir()); if let Some(cfg) = &self.bench_config { debug!("applying criterion config"); for (k, v) in cfg.envs() { cmd.env(k, v); } } debug!("running {} with {:?}", self, cmd); let output = cmd.output()?; let stdout = String::from_utf8_lossy(&output.stdout); let stderr = String::from_utf8_lossy(&output.stderr); if !output.status.success() { bail!("benchmark failed! stdout: {}, stderr: {}", stdout, stderr); } Ok(()) } }
s!( "{}: {}::{}@{:?}", tcs, self.benchmark.crate_name, self.benchmark.name, self.benchmark.runner, )) }
function_block-function_prefixed
[ { "content": "fn most_covered_toolchains_runtimes(data_dir: impl AsRef<Path>) -> Result<Vec<(R64, String)>> {\n\n info!(\"finding all existing estimates\");\n\n let estimates = GitStore::ensure_initialized(data_dir)?.all_stored_estimates()?;\n\n\n\n info!(\"reorganizing them by toolchain\");\n\n let mut by_toolchain = BTreeMap::new();\n\n for (bench_key, toolchains) in estimates {\n\n for (toolchain, estimate) in toolchains {\n\n by_toolchain\n\n .entry(toolchain)\n\n .or_insert_with(BTreeMap::new)\n\n .insert(bench_key.clone(), estimate);\n\n }\n\n }\n\n\n\n let mut lens = by_toolchain\n\n .iter()\n\n .map(|(tc, by_bench)| (tc, by_bench.len()))\n\n .collect::<Vec<_>>();\n\n lens.sort();\n", "file_path": "src/registry.rs", "rank": 0, "score": 227281.4841318139 }, { "content": "pub fn rebalance(sample_data_dir: impl AsRef<Path>) -> Result<()> {\n\n let (mut registry, _) = Registry::from_disk()?;\n\n let runners = registry.runners().to_owned();\n\n\n\n // fill the minheap with runners and 0 scores\n\n let mut weights = Vec::from_iter(runners.iter().map(|r| (r64(0.0), r.clone())));\n\n // also create a mapping of benchmark assignments\n\n let mut new_assignments: BTreeMap<String, Vec<String>> = BTreeMap::new();\n\n let runners_by_bench_key = registry\n\n .benches()\n\n .into_iter()\n\n .filter_map(|b| {\n\n let bench_key = format!(\"{}::{}\", b.crate_name, b.name);\n\n b.runner.map(|r| (bench_key, r))\n\n }).collect::<BTreeMap<String, String>>();\n\n\n\n for (ns, bench_key) in most_covered_toolchains_runtimes(sample_data_dir)? {\n\n if let Some(assigned) = runners_by_bench_key.get(&bench_key) {\n\n // this has already been assigned, so we just need to track its runtime\n\n weights\n", "file_path": "src/registry.rs", "rank": 1, "score": 216835.91909350664 }, { "content": "fn bench_harness<F: FnMut(&mut [u32])>(mut f: F, b: &mut Bencher) {\n\n let base_vec = super::default_vec(BENCH_SIZE);\n\n let mut sort_vec = vec![];\n\n b.iter(|| {\n\n sort_vec = base_vec.clone();\n\n f(&mut sort_vec);\n\n });\n\n assert!(super::is_sorted(&mut sort_vec));\n\n}\n\n\n\nwrap_libtest! {\n\n quicksort::bench,\n\n fn quick_sort_par_bench(b: &mut Bencher) {\n\n bench_harness(super::quick_sort::<Parallel, u32>, b);\n\n }\n\n}\n\n\n\nwrap_libtest! {\n\n quicksort::bench,\n\n fn quick_sort_seq_bench(b: &mut Bencher) {\n", "file_path": "benches/rayon_1_0_0/src/quicksort/bench.rs", "rank": 2, "score": 215967.3935970734 }, { "content": "fn bench_harness<F: FnMut(&mut [u32])>(mut f: F, b: &mut Bencher) {\n\n let base_vec = super::default_vec(BENCH_SIZE);\n\n let mut sort_vec = vec![];\n\n b.iter(|| {\n\n sort_vec = base_vec.clone();\n\n f(&mut sort_vec);\n\n });\n\n assert!(super::is_sorted(&mut sort_vec));\n\n}\n\n\n\nwrap_libtest! {\n\n mergesort::bench,\n\n fn merge_sort_par_bench(b: &mut Bencher) {\n\n bench_harness(super::merge_sort, b);\n\n }\n\n}\n\n\n\nwrap_libtest! {\n\n mergesort::bench,\n\n fn merge_sort_seq_bench(b: &mut Bencher) {\n\n bench_harness(super::seq_merge_sort, b);\n\n }\n\n}\n", "file_path": "benches/rayon_1_0_0/src/mergesort/bench.rs", "rank": 3, "score": 215967.3935970734 }, { "content": "pub fn get_benches(runner: Option<&str>) -> Result<Vec<Benchmark>> {\n\n let (reg, _f) = Registry::from_disk()?;\n\n let benchmarks = reg.benches();\n\n\n\n info!(\"Found and parsed {} benchmarks.\", benchmarks.len());\n\n\n\n Ok(if let Some(r) = runner {\n\n let b = benchmarks\n\n .into_iter()\n\n .filter(|b| b.runner.as_ref().map(String::as_str) == runner)\n\n .collect::<Vec<_>>();\n\n\n\n info!(\n\n \"{} benchmarks assigned to the requested runner ({}).\",\n\n b.len(),\n\n r\n\n );\n\n\n\n b\n\n } else {\n\n benchmarks\n\n })\n\n}\n\n\n", "file_path": "src/registry.rs", "rank": 4, "score": 211405.51424658275 }, { "content": "pub fn generate_new_benchmark_crate(name: &str) -> Result<()> {\n\n let crate_dir = Path::new(env!(\"CARGO_MANIFEST_DIR\"))\n\n .join(\"benches\")\n\n .join(name);\n\n\n\n let manifest_path = crate_dir.join(\"Cargo.toml\");\n\n let src_dir = crate_dir.join(\"src\");\n\n let source_path = src_dir.join(\"lib.rs\");\n\n\n\n let manifest_contents = MANIFEST.replace(\"{{ crate_name }}\", name);\n\n\n\n use std::fs;\n\n fs::create_dir_all(&src_dir)?;\n\n fs::write(&manifest_path, &manifest_contents)?;\n\n fs::write(&source_path, LIB_RS)?;\n\n Ok(())\n\n}\n", "file_path": "src/generator.rs", "rank": 5, "score": 208740.71370389214 }, { "content": "pub fn bench<T, F>(trials: usize, f: F) -> Duration\n\nwhere\n\n F: Fn() -> T,\n\n{\n\n let mut benchmark = Benchmark::new();\n\n for _ in 0..trials {\n\n let mut timer = benchmark.start();\n\n let _keep = f();\n\n timer.stop();\n\n }\n\n benchmark.min_elapsed()\n\n}\n\n\n", "file_path": "benches/json_benchmark_c7d3d9b/src/timer.rs", "rank": 6, "score": 205126.42804453627 }, { "content": "pub fn seq_merge_sort<T: Ord + Copy>(v: &mut [T]) {\n\n let n = v.len();\n\n let mut buf = Vec::with_capacity(n);\n\n // We always overwrite the buffer before reading to it, and we want to\n\n // duplicate the behavior of parallel sort.\n\n unsafe {\n\n buf.set_len(n);\n\n }\n\n seq_sort(v, &mut buf[..]);\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/mergesort/mod.rs", "rank": 7, "score": 199479.20140446923 }, { "content": "pub fn is_sorted<T: Send + Ord>(v: &mut [T]) -> bool {\n\n let n = v.len();\n\n if n <= SORT_CHUNK {\n\n for i in 1..n {\n\n if v[i - 1] > v[i] {\n\n return false;\n\n }\n\n }\n\n return true;\n\n }\n\n\n\n let mid = n / 2;\n\n if v[mid - 1] > v[mid] {\n\n return false;\n\n }\n\n let (a, b) = v.split_at_mut(mid);\n\n let (left, right) = rayon::join(|| is_sorted(a), || is_sorted(b));\n\n return left && right;\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/mergesort/mod.rs", "rank": 8, "score": 198762.4596541265 }, { "content": "struct BenchmarkPassthrough<'a>(pub &'a mut lolbench_support::Bencher);\n\nimpl<'a> Runner for BenchmarkPassthrough<'a> {\n\n fn iter<Fn: FnMut()>(&mut self, cb: &mut Fn) {\n\n self.0.iter(cb)\n\n }\n\n}\n\n\n\nimpl UnlimitedBuffer {\n\n pub fn new(buf: &[u8]) -> Self {\n\n let mut ret = UnlimitedBuffer {\n\n data: Vec::<u8>::new(),\n\n read_offset: 0,\n\n };\n\n ret.data.extend(buf);\n\n return ret;\n\n }\n\n pub fn reset_read(&mut self) {\n\n self.read_offset = 0;\n\n }\n\n}\n", "file_path": "benches/brotli_1_1_3/src/lib.rs", "rank": 9, "score": 197992.3317169592 }, { "content": "pub fn merge_sort<T: Ord + Send + Copy>(v: &mut [T]) {\n\n let n = v.len();\n\n let mut buf = Vec::with_capacity(n);\n\n // We always overwrite the buffer before reading to it, and letting rust\n\n // initialize it would increase the critical path to O(n).\n\n unsafe {\n\n buf.set_len(n);\n\n }\n\n rsort(v, &mut buf[..]);\n\n}\n\n\n\n// Values from manual tuning gigasort on one machine.\n\nconst SORT_CHUNK: usize = 32 * 1024;\n\nconst MERGE_CHUNK: usize = 64 * 1024;\n\n\n", "file_path": "benches/rayon_1_0_0/src/mergesort/mod.rs", "rank": 10, "score": 195057.12078787107 }, { "content": "pub fn bench_with_buf<T, F>(trials: usize, len: usize, f: F) -> Duration\n\nwhere\n\n F: Fn(&mut Vec<u8>) -> T,\n\n{\n\n let mut benchmark = Benchmark::new();\n\n for _ in 0..trials {\n\n let mut buf = Vec::with_capacity(len);\n\n let mut timer = benchmark.start();\n\n let _keep = f(&mut buf);\n\n timer.stop();\n\n }\n\n benchmark.min_elapsed()\n\n}\n\n\n\npub struct Benchmark {\n\n min_elapsed: Option<Duration>,\n\n}\n\n\n\nimpl Benchmark {\n\n pub fn new() -> Self {\n", "file_path": "benches/json_benchmark_c7d3d9b/src/timer.rs", "rank": 11, "score": 189282.08879775862 }, { "content": "pub fn quick_sort<J: Joiner, T: PartialOrd + Send>(v: &mut [T]) {\n\n if v.len() <= 1 {\n\n return;\n\n }\n\n\n\n if J::is_parallel() && v.len() <= 5 * 1024 {\n\n return quick_sort::<Sequential, T>(v);\n\n }\n\n\n\n let mid = partition(v);\n\n let (lo, hi) = v.split_at_mut(mid);\n\n J::join(|| quick_sort::<J, T>(lo), || quick_sort::<J, T>(hi));\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/quicksort/mod.rs", "rank": 12, "score": 184383.8470332951 }, { "content": "fn read_utf8_file(path: &Path, into: &mut String) -> IoResult<()> {\n\n try!(File::open(path)).read_to_string(into).map(|_| ())\n\n}\n\n\n\nconst SAMPLER: Option<SamplerBehavior> = Some(SamplerBehavior {\n\n wrap_function: (\n\n SamplerWrapFunction::Repeat,\n\n SamplerWrapFunction::Repeat,\n\n SamplerWrapFunction::Repeat,\n\n ),\n\n minify_filter: MinifySamplerFilter::Nearest,\n\n magnify_filter: MagnifySamplerFilter::Nearest,\n\n max_anisotropy: 1,\n\n});\n\n\n\nconst PALETTE_SAMPLER: Option<SamplerBehavior> = Some(SamplerBehavior {\n\n wrap_function: (\n\n SamplerWrapFunction::Clamp,\n\n SamplerWrapFunction::Clamp,\n\n SamplerWrapFunction::Clamp,\n\n ),\n\n minify_filter: MinifySamplerFilter::Nearest,\n\n magnify_filter: MagnifySamplerFilter::Nearest,\n\n max_anisotropy: 1,\n\n});\n", "file_path": "benches/doom_9e197d7/src/gfx/scene.rs", "rank": 13, "score": 180457.73389847288 }, { "content": "fn lolbench_entrypoint(bench_path: &str) -> Result<String> {\n\n let bench_path = bench_path\n\n .replace(' ', \"\")\n\n .replace('\\t', \"\")\n\n .replace('\\n', \"\");\n\n\n\n let returned = Ok(format!(\n\n \"println!(\\\"entering lolbench-generated benchmark {}\\\");\",\n\n bench_path.trim()\n\n ));\n\n\n\n let crate_name = ::std::env::var(\"CARGO_PKG_NAME\")?;\n\n let manifest_dir = env::var(\"CARGO_MANIFEST_DIR\")?;\n\n\n\n let bin_name = slugify(bench_path.to_string());\n\n let source_name = format!(\"{}.rs\", bin_name);\n\n let full_path = Path::new(&manifest_dir)\n\n .join(\"src\")\n\n .join(\"bin\")\n\n .join(&source_name);\n\n\n\n let test_path = Path::new(&manifest_dir).join(\"tests\").join(&source_name);\n\n let test_source = test_source(&bench_path, &crate_name);\n\n\n\n Benchmark::new(&crate_name, &bench_path, &full_path).write_and_register(&full_path)?;\n\n write_if_changed(&test_source, &test_path)?;\n\n\n\n returned\n\n}\n", "file_path": "extractor/src/lib.rs", "rank": 14, "score": 174695.96141013608 }, { "content": "fn rustc_serialize_parse_struct<T>(bytes: &[u8]) -> rustc_serialize::json::DecodeResult<T>\n\nwhere\n\n T: rustc_serialize::Decodable,\n\n{\n\n use std::str;\n\n let s = str::from_utf8(bytes).unwrap();\n\n rustc_serialize::json::decode(s)\n\n}\n\n\n", "file_path": "benches/json_benchmark_c7d3d9b/src/lib.rs", "rank": 15, "score": 164918.77250301832 }, { "content": "// Merge sorted inputs a and b, putting result in dest.\n\n//\n\n// Note: `a` and `b` have type `&mut [T]` and not `&[T]` because we do\n\n// not want to require a `T: Sync` bound. Using `&mut` references\n\n// proves to the compiler that we are not sharing `a` and `b` across\n\n// threads and thus we only need a `T: Send` bound.\n\nfn rmerge<T: Ord + Send + Copy>(a: &mut [T], b: &mut [T], dest: &mut [T]) {\n\n // Swap so a is always longer.\n\n let (a, b) = if a.len() > b.len() { (a, b) } else { (b, a) };\n\n if dest.len() <= MERGE_CHUNK {\n\n seq_merge(a, b, dest);\n\n return;\n\n }\n\n\n\n // Find the middle element of the longer list, and\n\n // use binary search to find its location in the shorter list.\n\n let ma = a.len() / 2;\n\n let mb = match b.binary_search(&a[ma]) {\n\n Ok(i) => i,\n\n Err(i) => i,\n\n };\n\n\n\n let (a1, a2) = a.split_at_mut(ma);\n\n let (b1, b2) = b.split_at_mut(mb);\n\n let (d1, d2) = dest.split_at_mut(ma + mb);\n\n rayon::join(|| rmerge(a1, b1, d1), || rmerge(a2, b2, d2));\n\n}\n\n\n\n// Merges sorted a and b into sorted dest.\n", "file_path": "benches/rayon_1_0_0/src/mergesort/mod.rs", "rank": 16, "score": 160925.60821252313 }, { "content": "// Sort src, putting the result into dest.\n\nfn seq_sort_into<T: Ord + Copy>(src: &mut [T], dest: &mut [T]) {\n\n let mid = src.len() / 2;\n\n let (s1, s2) = src.split_at_mut(mid);\n\n {\n\n // Sort each half.\n\n let (d1, d2) = dest.split_at_mut(mid);\n\n seq_sort(s1, d1);\n\n seq_sort(s2, d2);\n\n }\n\n\n\n // Merge the halves into dest.\n\n seq_merge(s1, s2, dest);\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/mergesort/mod.rs", "rank": 17, "score": 160050.67733203853 }, { "content": "// Sort src, possibly making use of identically sized buf.\n\nfn seq_sort<T: Ord + Copy>(src: &mut [T], buf: &mut [T]) {\n\n if src.len() <= SORT_CHUNK {\n\n src.sort();\n\n return;\n\n }\n\n\n\n // Sort each half into half of the buffer.\n\n let mid = src.len() / 2;\n\n let (bufa, bufb) = buf.split_at_mut(mid);\n\n {\n\n let (sa, sb) = src.split_at_mut(mid);\n\n seq_sort_into(sa, bufa);\n\n seq_sort_into(sb, bufb);\n\n }\n\n\n\n // Merge the buffer halves back into the original.\n\n seq_merge(bufa, bufb, src);\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/mergesort/mod.rs", "rank": 18, "score": 160050.34636880222 }, { "content": "// Sort src, putting the result into dest.\n\nfn rsort_into<T: Ord + Send + Copy>(src: &mut [T], dest: &mut [T]) {\n\n let mid = src.len() / 2;\n\n let (s1, s2) = src.split_at_mut(mid);\n\n {\n\n // Sort each half.\n\n let (d1, d2) = dest.split_at_mut(mid);\n\n rayon::join(|| rsort(s1, d1), || rsort(s2, d2));\n\n }\n\n\n\n // Merge the halves into dest.\n\n rmerge(s1, s2, dest);\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/mergesort/mod.rs", "rank": 19, "score": 157250.5385414236 }, { "content": "// Sort src, possibly making use of identically sized buf.\n\nfn rsort<T: Ord + Send + Copy>(src: &mut [T], buf: &mut [T]) {\n\n if src.len() <= SORT_CHUNK {\n\n src.sort();\n\n return;\n\n }\n\n\n\n // Sort each half into half of the buffer.\n\n let mid = src.len() / 2;\n\n let (bufa, bufb) = buf.split_at_mut(mid);\n\n {\n\n let (sa, sb) = src.split_at_mut(mid);\n\n rayon::join(|| rsort_into(sa, bufa), || rsort_into(sb, bufb));\n\n }\n\n\n\n // Merge the buffer halves back into the original.\n\n rmerge(bufa, bufb, src);\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/mergesort/mod.rs", "rank": 20, "score": 157250.20757818726 }, { "content": "pub fn init() -> Result<Sdl2TtfContext, Error> {\n\n Ok(Sdl2TtfContext)\n\n}\n\n\n", "file_path": "benches/doom_9e197d7/src/shims/sdl2_ttf/src/lib.rs", "rank": 21, "score": 156618.68841819293 }, { "content": "#[derive(Debug, Serialize, Deserialize, PartialEq)]\n\nstruct GAMERowOwned(String, String, String, String, i32, String);\n\n\n", "file_path": "benches/csv_1_0_2/src/lib.rs", "rank": 22, "score": 155605.51403971858 }, { "content": "#[inline(always)]\n\nfn compress(input: &[u8], output: &mut [u8]) -> Result<usize> {\n\n Encoder::new().compress(input, output)\n\n}\n\n\n", "file_path": "benches/snap_0_2_4/src/lib.rs", "rank": 23, "score": 154793.77165995623 }, { "content": "#[inline(always)]\n\nfn decompress(input: &[u8], output: &mut [u8]) -> Result<usize> {\n\n Decoder::new().decompress(input, output)\n\n}\n\n\n\ncompress!(compress, zflat00_html, \"html\");\n\ncompress!(compress, zflat01_urls, \"urls.10K\");\n\ncompress!(compress, zflat02_jpg, \"fireworks.jpeg\");\n\ncompress!(compress, zflat03_jpg_200, \"fireworks.jpeg\", 200);\n\ncompress!(compress, zflat04_pdf, \"paper-100k.pdf\");\n\ncompress!(compress, zflat05_html4, \"html_x_4\");\n\ncompress!(compress, zflat06_txt1, \"alice29.txt\");\n\ncompress!(compress, zflat07_txt2, \"asyoulik.txt\");\n\ncompress!(compress, zflat08_txt3, \"lcet10.txt\");\n\ncompress!(compress, zflat09_txt4, \"plrabn12.txt\");\n\ncompress!(compress, zflat10_pb, \"geo.protodata\");\n\ncompress!(compress, zflat11_gaviota, \"kppkn.gtb\");\n\n\n\ndecompress!(decompress, uflat00_html, \"html\");\n\ndecompress!(decompress, uflat01_urls, \"urls.10K\");\n\ndecompress!(decompress, uflat02_jpg, \"fireworks.jpeg\");\n\ndecompress!(decompress, uflat03_jpg_200, \"fireworks.jpeg\", 200);\n\ndecompress!(decompress, uflat04_pdf, \"paper-100k.pdf\");\n\ndecompress!(decompress, uflat05_html4, \"html_x_4\");\n\ndecompress!(decompress, uflat06_txt1, \"alice29.txt\");\n\ndecompress!(decompress, uflat07_txt2, \"asyoulik.txt\");\n\ndecompress!(decompress, uflat08_txt3, \"lcet10.txt\");\n\ndecompress!(decompress, uflat09_txt4, \"plrabn12.txt\");\n\ndecompress!(decompress, uflat10_pb, \"geo.protodata\");\n\ndecompress!(decompress, uflat11_gaviota, \"kppkn.gtb\");\n", "file_path": "benches/snap_0_2_4/src/lib.rs", "rank": 24, "score": 154793.77165995623 }, { "content": "pub fn is_sorted<T: Send + Ord>(v: &[T]) -> bool {\n\n (1..v.len()).all(|i| v[i - 1] <= v[i])\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/quicksort/mod.rs", "rank": 25, "score": 154712.91307584563 }, { "content": "pub fn random_in_unit_sphere(rng: &mut XorShiftRng) -> Vec3 {\n\n loop {\n\n let p = 2.0 * rng.gen::<Vec3>() - Vec3(1.0, 1.0, 1.0);\n\n if p.dot(p) < 1.0 {\n\n return p;\n\n }\n\n }\n\n}\n\n\n", "file_path": "benches/raytrace_8de9020/src/vec.rs", "rank": 26, "score": 153770.81134947325 }, { "content": "pub fn random_in_unit_disc(rng: &mut XorShiftRng) -> Vec3 {\n\n loop {\n\n let p = Vec3(\n\n 2.0 * rng.gen::<f32>() - 1.0,\n\n 2.0 * rng.gen::<f32>() - 1.0,\n\n 0.0,\n\n );\n\n if p.dot(p) < 1.0 {\n\n return p;\n\n }\n\n }\n\n}\n\n\n\n#[derive(Clone, Copy, Debug)]\n\npub struct Ray {\n\n pub origin: Vec3,\n\n pub direction: Vec3,\n\n}\n\n\n\nimpl Ray {\n", "file_path": "benches/raytrace_8de9020/src/vec.rs", "rank": 27, "score": 153770.81134947325 }, { "content": "pub fn test_source(bench_name: &str, crate_name: &str) -> String {\n\n let source = quote! {\n\n extern crate lolbench;\n\n\n\n #[test]\n\n fn end_to_end() {\n\n lolbench::end_to_end_test(\n\n #crate_name,\n\n #bench_name,\n\n );\n\n }\n\n };\n\n\n\n source.to_string()\n\n}\n\n\n", "file_path": "marky_mark/src/lib.rs", "rank": 28, "score": 152644.63406784553 }, { "content": "fn partition<T: PartialOrd + Send>(v: &mut [T]) -> usize {\n\n let pivot = v.len() - 1;\n\n let mut i = 0;\n\n for j in 0..pivot {\n\n if v[j] <= v[pivot] {\n\n v.swap(i, j);\n\n i += 1;\n\n }\n\n }\n\n v.swap(i, pivot);\n\n i\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/quicksort/mod.rs", "rank": 29, "score": 152033.52398112504 }, { "content": "// Multiply two square power of two matrices, given in Z-order.\n\npub fn matmulz(a: &[f32], b: &[f32], dest: &mut [f32]) {\n\n if a.len() <= MULT_CHUNK {\n\n seq_matmulz(a, b, dest);\n\n return;\n\n }\n\n\n\n // Allocate uninitialized scratch space.\n\n let mut tmp = raw_buffer(dest.len());\n\n\n\n let (a1, a2, a3, a4) = quarter_chunks(a);\n\n let (b1, b2, b3, b4) = quarter_chunks(b);\n\n {\n\n let (d1, d2, d3, d4) = quarter_chunks_mut(dest);\n\n let (t1, t2, t3, t4) = quarter_chunks_mut(&mut tmp[..]);\n\n // Multiply 8 submatrices\n\n join8(\n\n || matmulz(a1, b1, d1),\n\n || matmulz(a1, b2, d2),\n\n || matmulz(a3, b1, d3),\n\n || matmulz(a3, b2, d4),\n", "file_path": "benches/rayon_1_0_0/src/matmul/mod.rs", "rank": 30, "score": 150940.18938764848 }, { "content": "#[inline(never)]\n\npub fn seq_matmulz(a: &[f32], b: &[f32], dest: &mut [f32]) {\n\n // All inputs need to be the same length.\n\n assert!(a.len() == b.len() && a.len() == dest.len());\n\n // Input matrices must be square with each side a power of 2.\n\n assert!(a.len().count_ones() == 1 && a.len().trailing_zeros() % 2 == 0);\n\n // Zero dest, as it may be uninitialized.\n\n for d in dest.iter_mut() {\n\n *d = 0.0;\n\n }\n\n\n\n // Multiply in morton order\n\n // D[i,j] = sum for all k A[i,k] * B[k,j]\n\n let n = dest.len();\n\n for ij in 0..n {\n\n let i = ij & 0xaaaaaaaa;\n\n let j = ij & 0x55555555;\n\n let mut sum = 0.0;\n\n for k in SplayedBitsCounter::new(n) {\n\n // sum += a[i, k] * b[k, j];\n\n sum += unsafe {\n", "file_path": "benches/rayon_1_0_0/src/matmul/mod.rs", "rank": 31, "score": 147994.95073193836 }, { "content": "pub fn matmul_strassen(a: &[f32], b: &[f32], dest: &mut [f32]) {\n\n if a.len() <= MULT_CHUNK {\n\n seq_matmulz(a, b, dest);\n\n return;\n\n }\n\n\n\n // Naming taken from https://en.wikipedia.org/wiki/Strassen_algorithm\n\n let (a11, a12, a21, a22) = quarter_chunks(a);\n\n let (b11, b12, b21, b22) = quarter_chunks(b);\n\n // 7 submatrix multiplies.\n\n // Maybe the tree should be leaning the other way...\n\n let (m1, m2, m3, m4, m5, m6, m7, _) = join8(\n\n || strassen_add2_mul(a11, a22, b11, b22),\n\n || strassen_add_mul(a21, a22, b11),\n\n || strassen_sub_mul(b12, b22, a11),\n\n || strassen_sub_mul(b21, b11, a22),\n\n || strassen_add_mul(a11, a12, b22),\n\n || strassen_sub_add_mul(a21, a11, b11, b12),\n\n || strassen_sub_add_mul(a12, a22, b21, b22),\n\n || (),\n", "file_path": "benches/rayon_1_0_0/src/matmul/mod.rs", "rank": 32, "score": 147994.95073193836 }, { "content": "// TODO: Investigate other cache patterns for row-major order that may be more\n\n// parallelizable.\n\n// https://tavianator.com/a-quick-trick-for-faster-naive-matrix-multiplication/\n\npub fn seq_matmul(a: &[f32], b: &[f32], dest: &mut [f32]) {\n\n // Zero dest, as it may be uninitialized.\n\n for d in dest.iter_mut() {\n\n *d = 0.0;\n\n }\n\n // Multiply in row-major order.\n\n // D[i,j] = sum for all k A[i,k] * B[k,j]\n\n let bits = dest.len().trailing_zeros() / 2;\n\n let n = 1 << bits;\n\n for i in 0..n {\n\n for j in 0..n {\n\n let mut sum = 0.0;\n\n for k in 0..n {\n\n sum += unsafe { a.get_unchecked(i << bits | k) * b.get_unchecked(k << bits | j) };\n\n }\n\n dest[i << bits | j] = sum;\n\n }\n\n }\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/matmul/mod.rs", "rank": 33, "score": 147994.95073193836 }, { "content": "pub fn write_if_changed(file_contents: &str, test_path: &Path) -> Result<bool> {\n\n let need_to_write = match read_to_string(&test_path) {\n\n Ok(existing) => existing != file_contents,\n\n _ => true,\n\n };\n\n\n\n if need_to_write {\n\n create_dir_all(test_path.parent().unwrap())?;\n\n write(&test_path, file_contents.as_bytes())?;\n\n }\n\n\n\n Ok(need_to_write)\n\n}\n\n\n\n#[derive(Clone, Debug, Deserialize, Serialize)]\n\npub struct Registry {\n\n pub workers: Vec<String>,\n\n pub benchmarks: BTreeMap<String, Benchmark>,\n\n}\n\n\n", "file_path": "marky_mark/src/lib.rs", "rank": 34, "score": 146250.4707041441 }, { "content": "fn main() -> Result<()> {\n\n simple_logger::init_with_level(log::Level::Debug).unwrap();\n\n Cli::from_args().exec()\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 35, "score": 145731.29104261455 }, { "content": "pub fn init() -> SdlResult<Sdl> {\n\n Ok(Sdl)\n\n}\n\n\n\npub mod version {\n\n pub use std::fmt::{Display, Formatter, Result as FmtResult};\n\n\n\n pub struct Version(pub String);\n\n impl Display for Version {\n\n fn fmt(&self, fmt: &mut Formatter) -> FmtResult {\n\n write!(fmt, \"{}\", self.0)\n\n }\n\n }\n\n}\n\n\n\npub mod video {\n\n pub use super::*;\n\n\n\n pub enum GLProfile {\n\n Core,\n", "file_path": "benches/doom_9e197d7/src/shims/sdl2/src/lib.rs", "rank": 36, "score": 143865.9368692944 }, { "content": "type Result<T> = std::result::Result<T, failure::Error>;\n\n\n\nproc_macro_expr_impl! {\n\n /// Prepare and write to disk a single-function CLI entry-point for the passed benchmark fn.\n\n pub fn lolbench_entrypoint_impl(bench_path: &str) -> String {\n\n lolbench_entrypoint(bench_path).unwrap()\n\n }\n\n}\n\n\n", "file_path": "extractor/src/lib.rs", "rank": 37, "score": 143159.22718194965 }, { "content": "fn serde_json_parse_struct<'de, T>(bytes: &'de [u8]) -> serde_json::Result<T>\n\nwhere\n\n T: serde::Deserialize<'de>,\n\n{\n\n use std::str;\n\n let s = str::from_utf8(bytes).unwrap();\n\n serde_json::from_str(s)\n\n}\n\n\n", "file_path": "benches/json_benchmark_c7d3d9b/src/lib.rs", "rank": 38, "score": 142605.61659727228 }, { "content": "pub fn build_website(\n\n data_dir: impl AsRef<Path>,\n\n output_dir: impl AsRef<Path>,\n\n publish: bool,\n\n) -> Result<()> {\n\n info!(\"reading all estimates from the data directory...\");\n\n let data_storage = GitStore::ensure_initialized(data_dir.as_ref())?;\n\n let estimates = data_storage\n\n .all_stored_estimates()?\n\n .into_iter()\n\n .map(|(name, estimates)| {\n\n (\n\n name,\n\n estimates\n\n .into_iter()\n\n .filter_map(|(maybe_tc, ests)| maybe_tc.map(|tc| (tc, ests)))\n\n .collect(),\n\n )\n\n }).collect();\n\n\n", "file_path": "src/website.rs", "rank": 39, "score": 141390.06728842465 }, { "content": "pub fn normalized_against_first(\n\n values: impl IntoIterator<Item = R64>,\n\n) -> impl IntoIterator<Item = R64> {\n\n let mut values = values.into_iter();\n\n let first = values.next().unwrap();\n\n ::std::iter::once(r64(1.0)).chain(values.map(move |v| v / first))\n\n}\n\n\n\n#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize)]\n\npub struct TimingRecord {\n\n pub binary_hash: String,\n\n pub toolchains: Vec<Toolchain>,\n\n pub anomaly_index: Option<AnomalyIndex>,\n\n pub metrics: RuntimeMetrics,\n\n pub normalized_metrics: RuntimeMetrics,\n\n}\n\n\n\nimpl TimingRecord {\n\n pub fn new(\n\n current_binhash: &[u8],\n", "file_path": "src/analysis.rs", "rank": 40, "score": 141390.06728842465 }, { "content": "pub fn exit_if_needed() {\n\n for signal in SIGNALS.pending() {\n\n match signal {\n\n SIGINT => {\n\n println!(\"received SIGINT, exiting\");\n\n ::std::process::exit(1);\n\n }\n\n SIGTERM => {\n\n println!(\"received SIGTERM, exiting\");\n\n ::std::process::exit(0);\n\n }\n\n sig => panic!(\"we didn't register for it but we received {}\", sig),\n\n }\n\n }\n\n}\n", "file_path": "src/signal.rs", "rank": 41, "score": 141390.06728842465 }, { "content": "type Result<T> = ::std::result::Result<T, failure::Error>;\n\n\n\nmacro_rules! ecx {\n\n ($ctx:expr, $inner:expr) => {\n\n $inner.with_context(|e| format!(concat!($ctx, \": {}\"), e))\n\n };\n\n}\n\n\n\n#[derive(Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Ord, Serialize)]\n\npub struct Benchmark {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub runner: Option<String>,\n\n pub name: String,\n\n #[serde(rename = \"crate\")]\n\n pub crate_name: String,\n\n pub entrypoint_path: PathBuf,\n\n}\n\n\n\nimpl Benchmark {\n\n pub fn new(crate_name: &str, name: &str, path: &Path) -> Self {\n", "file_path": "marky_mark/src/lib.rs", "rank": 42, "score": 141223.0361978968 }, { "content": "fn _write_all<OutputType>(w: &mut OutputType, buf: &[u8]) -> Result<(), io::Error>\n\nwhere\n\n OutputType: io::Write,\n\n{\n\n let mut total_written: usize = 0;\n\n while total_written < buf.len() {\n\n match w.write(&buf[total_written..]) {\n\n Err(e) => match e.kind() {\n\n io::ErrorKind::Interrupted => continue,\n\n _ => return Err(e),\n\n },\n\n Ok(cur_written) => {\n\n if cur_written == 0 {\n\n return Err(io::Error::new(io::ErrorKind::UnexpectedEof, \"Write EOF\"));\n\n }\n\n total_written += cur_written;\n\n }\n\n }\n\n }\n\n Ok(())\n\n}\n", "file_path": "benches/brotli_1_1_3/src/lib.rs", "rank": 43, "score": 140233.77090633023 }, { "content": "#[inline(never)]\n\nfn seq_merge<T: Ord + Copy>(a: &[T], b: &[T], dest: &mut [T]) {\n\n if b.is_empty() {\n\n dest.copy_from_slice(a);\n\n return;\n\n }\n\n let biggest = max(*a.last().unwrap(), *b.last().unwrap());\n\n let mut ai = a.iter();\n\n let mut an = *ai.next().unwrap();\n\n let mut bi = b.iter();\n\n let mut bn = *bi.next().unwrap();\n\n for d in dest.iter_mut() {\n\n if an < bn {\n\n *d = an;\n\n an = match ai.next() {\n\n Some(x) => *x,\n\n None => biggest,\n\n }\n\n } else {\n\n *d = bn;\n\n bn = match bi.next() {\n\n Some(x) => *x,\n\n None => biggest,\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/mergesort/mod.rs", "rank": 44, "score": 137718.23164257157 }, { "content": "fn reallyhard2_suffix() -> String {\n\n \"Sherlock Holmes\".to_string()\n\n}\n\n\n\nmacro_rules! reallyhard2 {\n\n () => {\n\n r\"\\w+\\s+Holmes\"\n\n };\n\n}\n\n\n\nbench_match!(\n\n misc,\n\n reallyhard2_1K,\n\n reallyhard2!(),\n\n get_text(TXT_1K, reallyhard2_suffix())\n\n);\n\n\n\n//\n\n// Benchmarks to justify the short-haystack NFA fallthrough optimization\n\n// implemented by `read_captures_at` in regex/src/exec.rs. See github issue\n", "file_path": "benches/regex_0_2_6/src/misc.rs", "rank": 45, "score": 136300.51882641914 }, { "content": "fn medium_suffix() -> String {\n\n \"XABCDEFGHIJKLMNOPQRSTUVWXYZ\".to_string()\n\n}\n\n\n\nmacro_rules! medium {\n\n () => {\n\n r\"[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$\"\n\n };\n\n}\n\n\n\nbench_match!(\n\n misc,\n\n medium_32,\n\n medium!(),\n\n get_text(TXT_32, medium_suffix())\n\n);\n\nbench_match!(\n\n misc,\n\n medium_1K,\n\n medium!(),\n", "file_path": "benches/regex_0_2_6/src/misc.rs", "rank": 46, "score": 136300.51882641914 }, { "content": "fn easy1_suffix() -> String {\n\n \"AABCCCDEEEFGGHHHIJJ\".to_string()\n\n}\n\n\n\nmacro_rules! easy1 {\n\n () => {\n\n r\"A[AB]B[BC]C[CD]D[DE]E[EF]F[FG]G[GH]H[HI]I[IJ]J$\"\n\n };\n\n}\n\n\n\nbench_match!(misc, easy1_32, easy1!(), get_text(TXT_32, easy1_suffix()));\n\nbench_match!(misc, easy1_1K, easy1!(), get_text(TXT_1K, easy1_suffix()));\n\nbench_match!(misc, easy1_32K, easy1!(), get_text(TXT_32K, easy1_suffix()));\n\nbench_match!(misc, easy1_1MB, easy1!(), get_text(TXT_1MB, easy1_suffix()));\n\n\n", "file_path": "benches/regex_0_2_6/src/misc.rs", "rank": 47, "score": 136300.51882641914 }, { "content": "fn easy0_suffix() -> String {\n\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".to_string()\n\n}\n\n\n\nmacro_rules! easy0 {\n\n () => {\n\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ$\"\n\n };\n\n}\n\n\n\nbench_match!(misc, easy0_32, easy0!(), get_text(TXT_32, easy0_suffix()));\n\nbench_match!(misc, easy0_1K, easy0!(), get_text(TXT_1K, easy0_suffix()));\n\nbench_match!(misc, easy0_32K, easy0!(), get_text(TXT_32K, easy0_suffix()));\n\nbench_match!(misc, easy0_1MB, easy0!(), get_text(TXT_1MB, easy0_suffix()));\n\n\n", "file_path": "benches/regex_0_2_6/src/misc.rs", "rank": 48, "score": 136300.51882641914 }, { "content": "fn hard_suffix() -> String {\n\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".to_string()\n\n}\n\n\n\nmacro_rules! hard {\n\n () => {\n\n r\"[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$\"\n\n };\n\n}\n\n\n\nbench_match!(misc, hard_32, hard!(), get_text(TXT_32, hard_suffix()));\n\nbench_match!(misc, hard_1K, hard!(), get_text(TXT_1K, hard_suffix()));\n\nbench_match!(misc, hard_32K, hard!(), get_text(TXT_32K, hard_suffix()));\n\nbench_match!(misc, hard_1MB, hard!(), get_text(TXT_1MB, hard_suffix()));\n\n\n", "file_path": "benches/regex_0_2_6/src/misc.rs", "rank": 49, "score": 136300.51882641914 }, { "content": "fn reallyhard_suffix() -> String {\n\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".to_string()\n\n}\n\n\n\nmacro_rules! reallyhard {\n\n () => {\n\n // The point of this being \"really\" hard is that it should completely\n\n // thwart any prefix or suffix literal optimizations.\n\n r\"[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ.*\"\n\n };\n\n}\n\n\n\nbench_match!(\n\n misc,\n\n reallyhard_32,\n\n reallyhard!(),\n\n get_text(TXT_32, reallyhard_suffix())\n\n);\n\nbench_match!(\n\n misc,\n", "file_path": "benches/regex_0_2_6/src/misc.rs", "rank": 50, "score": 136300.51882641914 }, { "content": "pub fn measure(opts: BenchOpts, data_dir: &Path, site_dir: &Path, publish: bool) -> Result<()> {\n\n info!(\"ensuring data dir {} exists\", data_dir.display());\n\n let mut collector = Collector::new(data_dir, site_dir)?;\n\n\n\n info!(\"cataloging potential builds to run\");\n\n let candidates = opts.enumerate_bench_candidates()?;\n\n\n\n info!(\n\n \"{} possible toolchains to run to satisfy provided options, pruning...\",\n\n candidates.len()\n\n );\n\n\n\n let to_run = collector.compute_builds_needed(&candidates)?;\n\n\n\n info!(\"{} plans to run after pruning, running...\", to_run.len());\n\n\n\n for (toolchain, benches) in to_run.into_iter().rev() {\n\n info!(\"running {} benches with {}\", benches.len(), toolchain);\n\n if let Err(why) = collector.run_benches_with_toolchain(toolchain, &benches, publish) {\n\n warn!(\"problem running benchmarks: {}\", why);\n\n }\n\n }\n\n\n\n info!(\"all done!\");\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 51, "score": 134966.77462166117 }, { "content": "fn rustc_serialize_parse_dom(\n\n mut bytes: &[u8],\n\n) -> Result<rustc_serialize::json::Json, rustc_serialize::json::BuilderError> {\n\n rustc_serialize::json::Json::from_reader(&mut bytes)\n\n}\n\n\n", "file_path": "benches/json_benchmark_c7d3d9b/src/lib.rs", "rank": 52, "score": 134835.42962447315 }, { "content": "fn get_text(corpus: &str, suffix: String) -> String {\n\n let mut corpus = corpus.to_string();\n\n corpus.push_str(&suffix);\n\n corpus\n\n}\n\n\n", "file_path": "benches/regex_0_2_6/src/misc.rs", "rank": 53, "score": 132653.05880068932 }, { "content": "fn read_sprites(wad: &Archive, textures: &mut BTreeMap<WadName, Image>) -> Result<usize> {\n\n let start_index = try!(wad.required_named_lump_index(b\"S_START\\0\")) + 1;\n\n let end_index = try!(wad.required_named_lump_index(b\"S_END\\0\\0\\0\"));\n\n info!(\"Reading {} sprites....\", end_index - start_index);\n\n let t0 = time::precise_time_s();\n\n for index in start_index..end_index {\n\n let name = *wad.lump_name(index);\n\n match Image::from_buffer(&try!(wad.read_lump(index))) {\n\n Ok(texture) => {\n\n textures.insert(name, texture);\n\n }\n\n Err(e) => {\n\n warn!(\"Skipping sprite: {}\", BadImage(name, e));\n\n continue;\n\n }\n\n }\n\n }\n\n let time = time::precise_time_s() - t0;\n\n info!(\"Done in {:.4}s.\", time);\n\n Ok(end_index - start_index)\n\n}\n\n\n", "file_path": "benches/doom_9e197d7/src/wad/tex.rs", "rank": 54, "score": 129077.97801356117 }, { "content": "fn gen_strings(len: usize) -> Vec<String> {\n\n let mut rng = XorShiftRng::from_seed([0, 1, 2, 3]);\n\n let mut v = vec![];\n\n for _ in 0..len {\n\n let n = rng.gen::<usize>() % 20 + 1;\n\n v.push(rng.gen_ascii_chars().take(n).collect());\n\n }\n\n v\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/sort.rs", "rank": 55, "score": 128017.80818087074 }, { "content": "pub fn connection() -> TestConnection {\n\n let result = connection_without_transaction();\n\n result.execute(\"PRAGMA foreign_keys = ON\").unwrap();\n\n result.begin_test_transaction().unwrap();\n\n result\n\n}\n\n\n\nembed_migrations!(\"migrations/sqlite\");\n\n\n", "file_path": "benches/diesel_1_1_1/src/schema.rs", "rank": 56, "score": 127362.23906199334 }, { "content": "fn count_deserialize_owned_bytes<R, D>(rdr: &mut Reader<R>) -> u64\n\n where R: io::Read, D: DeserializeOwned\n\n{\n\n let mut count = 0;\n\n let mut rec = ByteRecord::new();\n\n while rdr.read_byte_record(&mut rec).unwrap() {\n\n let _: D = rec.deserialize(None).unwrap();\n\n count += 1;\n\n }\n\n count\n\n}\n\n\n", "file_path": "benches/csv_1_0_2/src/lib.rs", "rank": 57, "score": 126688.41696351155 }, { "content": "fn count_deserialize_owned_str<R, D>(rdr: &mut Reader<R>) -> u64\n\n where R: io::Read, D: DeserializeOwned\n\n{\n\n let mut count = 0;\n\n for rec in rdr.deserialize::<D>() {\n\n let _ = rec.unwrap();\n\n count += 1;\n\n }\n\n count\n\n}\n\n\n", "file_path": "benches/csv_1_0_2/src/lib.rs", "rank": 58, "score": 126688.41696351155 }, { "content": "pub fn clear_error() {}\n\n\n\npub mod pixels {\n\n pub enum Color {\n\n RGBA(u8, u8, u8, u8),\n\n }\n\n\n\n pub enum PixelFormatEnum {\n\n ARGB8888,\n\n BGR24,\n\n }\n\n}\n\n\n\npub mod rect {\n\n use super::*;\n\n\n\n #[allow(unused)]\n\n pub struct Rect {\n\n x: Coord,\n\n y: Coord,\n", "file_path": "benches/doom_9e197d7/src/shims/sdl2/src/lib.rs", "rank": 59, "score": 125444.33030381786 }, { "content": "#[bench]\n\nfn float_bytes(b: &mut Bencher) {\n\n use nom::float;\n\n b.iter(|| float(&b\"-1.234E-12\"[..]));\n\n}\n\n\n", "file_path": "benches/nom_4_0_0/src/json.rs", "rank": 60, "score": 123272.3711254322 }, { "content": "#[bench]\n\nfn json_bench(b: &mut Bencher) {\n\n let data = &b\" { \\\"a\\\"\\t: 42,\n\n \\\"b\\\": [ \\\"x\\\", \\\"y\\\", 12 ] ,\n\n \\\"c\\\": { \\\"hello\\\" : \\\"world\\\"\n\n }\n\n } \\0\";\n\n\n\n //println!(\"data:\\n{:?}\", value(&data[..]));\n\n b.iter(|| value(&data[..]).unwrap());\n\n}\n\n\n", "file_path": "benches/nom_4_0_0/src/json.rs", "rank": 61, "score": 123272.3711254322 }, { "content": "fn one_test(b: &mut Bencher) {\n\n let data = &b\"GET / HTTP/1.1\n\n Host: www.reddit.com\n\n User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1\n\n Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\n\n Accept-Language: en-us,en;q=0.5\n\n Accept-Encoding: gzip, deflate\n\n Connection: keep-alive\"\n\n [..];\n\n b.iter(|| parse(data));\n\n}\n\n}\n", "file_path": "benches/nom_4_0_0/src/http.rs", "rank": 62, "score": 123272.3711254322 }, { "content": "#[bench]\n\nfn float_str(b: &mut Bencher) {\n\n use nom::float_s;\n\n b.iter(|| float_s(\"-1.234E-12\"));\n\n}\n", "file_path": "benches/nom_4_0_0/src/json.rs", "rank": 63, "score": 123272.3711254322 }, { "content": "fn sieve_bench<TICK>(b: &mut Bencher, mut tick: TICK)\n\nwhere\n\n TICK: FnMut(usize) -> Vec<bool>,\n\n{\n\n let mut result = vec![];\n\n b.iter(|| result = tick(super::max(MAGNITUDE)));\n\n let num_primes = 1 + result.into_iter().filter(|&b| b).count();\n\n assert_eq!(num_primes, NUM_PRIMES[MAGNITUDE]);\n\n}\n\n\n\nwrap_libtest! {\n\n sieve::bench,\n\n fn sieve_serial(b: &mut Bencher) {\n\n sieve_bench(b, super::sieve_serial);\n\n }\n\n}\n\n\n\nwrap_libtest! {\n\n sieve::bench,\n\n fn sieve_chunks(b: &mut Bencher) {\n", "file_path": "benches/rayon_1_0_0/src/sieve/bench.rs", "rank": 64, "score": 122562.32861173693 }, { "content": "fn nbody_bench<TICK>(b: &mut Bencher, mut tick: TICK)\n\nwhere\n\n TICK: FnMut(&mut NBodyBenchmark),\n\n{\n\n let mut rng = XorShiftRng::from_seed([0, 1, 2, 3]);\n\n let mut benchmark = NBodyBenchmark::new(BENCH_BODIES, &mut rng);\n\n b.iter(|| {\n\n for _ in 0..BENCH_TICKS {\n\n tick(&mut benchmark);\n\n }\n\n });\n\n}\n\n\n\nwrap_libtest! {\n\n nbody::bench,\n\n fn nbody_seq(b: &mut Bencher) {\n\n nbody_bench(b, |n| { n.tick_seq(); });\n\n }\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/nbody/bench.rs", "rank": 65, "score": 122562.32861173693 }, { "content": "pub fn connection_without_transaction() -> TestConnection {\n\n let connection = SqliteConnection::establish(\":memory:\").unwrap();\n\n embedded_migrations::run(&connection).unwrap();\n\n connection\n\n}\n\n\n\nsql_function!(_nextval, nextval_t, (a: types::VarChar) -> sql_types::BigInt);\n", "file_path": "benches/diesel_1_1_1/src/schema.rs", "rank": 66, "score": 122451.6177301991 }, { "content": "fn serde_json_parse_dom(bytes: &[u8]) -> serde_json::Result<serde_json::Value> {\n\n use std::str;\n\n let s = str::from_utf8(bytes).unwrap();\n\n serde_json::from_str(s)\n\n}\n\n\n", "file_path": "benches/json_benchmark_c7d3d9b/src/lib.rs", "rank": 67, "score": 122164.49929265317 }, { "content": "fn rustc_serialize_stringify<W, T: ?Sized>(\n\n writer: W,\n\n value: &T,\n\n) -> rustc_serialize::json::EncodeResult<()>\n\nwhere\n\n W: Write,\n\n T: rustc_serialize::Encodable,\n\n{\n\n let mut writer = adapter::IoWriteAsFmtWrite::new(writer);\n\n let mut encoder = rustc_serialize::json::Encoder::new(&mut writer);\n\n value.encode(&mut encoder)\n\n}\n", "file_path": "benches/json_benchmark_c7d3d9b/src/lib.rs", "rank": 68, "score": 120910.22955612472 }, { "content": "#[bench]\n\nfn recognize_float_bytes(b: &mut Bencher) {\n\n use nom::recognize_float;\n\n b.iter(|| recognize_float(&b\"-1.234E-12\"[..]));\n\n}\n\n\n", "file_path": "benches/nom_4_0_0/src/json.rs", "rank": 69, "score": 120732.36810535102 }, { "content": "#[bench]\n\nfn recognize_float_str(b: &mut Bencher) {\n\n use nom::recognize_float;\n\n b.iter(|| recognize_float(\"-1.234E-12\"));\n\n}\n\n\n", "file_path": "benches/nom_4_0_0/src/json.rs", "rank": 70, "score": 120732.36810535102 }, { "content": "struct SliceU8Ref<'a>(pub &'a [u8]);\n\n\n\nimpl<'a> fmt::LowerHex for SliceU8Ref<'a> {\n\n fn fmt(&self, fmtr: &mut fmt::Formatter) -> Result<(), fmt::Error> {\n\n for item in self.0 {\n\n try!(fmtr.write_fmt(format_args!(\"{:02x}\", item)));\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl<'a, OutputType: Write> brotli::CustomWrite<io::Error> for IoWriterWrapper<'a, OutputType> {\n\n fn flush(self: &mut Self) -> Result<(), io::Error> {\n\n loop {\n\n match self.0.flush() {\n\n Err(e) => match e.kind() {\n\n ErrorKind::Interrupted => continue,\n\n _ => return Err(e),\n\n },\n\n Ok(_) => return Ok(()),\n", "file_path": "benches/brotli_1_1_3/src/lib.rs", "rank": 71, "score": 120489.63335765319 }, { "content": "pub fn geometric_mean(values: &[R64]) -> R64 {\n\n values\n\n .iter()\n\n .fold(r64(1.0), |a_n, &a_n1| a_n * a_n1)\n\n .powf(r64(1.0 / values.len() as f64))\n\n}\n\n\n", "file_path": "src/analysis.rs", "rank": 72, "score": 119323.29685341167 }, { "content": "pub fn has_been_initialized() -> bool {\n\n true\n\n}\n\n\n\n#[derive(PartialEq)]\n\npub struct Font;\n\n\n\nimpl Drop for Font {\n\n fn drop(&mut self) {}\n\n}\n\n\n\npub enum Text<'a> {\n\n Latin1(&'a [u8]),\n\n Utf8(&'a str),\n\n Char(char),\n\n}\n\n\n\nimpl<'a> From<&'a str> for Text<'a> {\n\n fn from(string: &'a str) -> Text<'a> {\n\n Text::Utf8(string)\n", "file_path": "benches/doom_9e197d7/src/shims/sdl2_ttf/src/lib.rs", "rank": 73, "score": 118146.66883942173 }, { "content": "pub fn decompress<InputType, OutputType>(\n\n r: &mut InputType,\n\n w: &mut OutputType,\n\n buffer_size: usize,\n\n) -> Result<(), io::Error>\n\nwhere\n\n InputType: Read,\n\n OutputType: Write,\n\n{\n\n let mut alloc_u8 = HeapAllocator::<u8> { default_value: 0 };\n\n let mut input_buffer = alloc_u8.alloc_cell(buffer_size);\n\n let mut output_buffer = alloc_u8.alloc_cell(buffer_size);\n\n brotli::BrotliDecompressCustomIo(\n\n &mut IoReaderWrapper::<InputType>(r),\n\n &mut IoWriterWrapper::<OutputType>(w),\n\n input_buffer.slice_mut(),\n\n output_buffer.slice_mut(),\n\n alloc_u8,\n\n HeapAllocator::<u32> { default_value: 0 },\n\n HeapAllocator::<HuffmanCode> {\n\n default_value: HuffmanCode::default(),\n\n },\n\n Error::new(ErrorKind::UnexpectedEof, \"Unexpected EOF\"),\n\n )\n\n}\n\n\n", "file_path": "benches/brotli_1_1_3/src/lib.rs", "rank": 74, "score": 118099.8900920744 }, { "content": "pub fn compress<InputType, OutputType>(\n\n r: &mut InputType,\n\n w: &mut OutputType,\n\n buffer_size: usize,\n\n params: &brotli::enc::BrotliEncoderParams,\n\n) -> Result<usize, io::Error>\n\nwhere\n\n InputType: Read,\n\n OutputType: Write,\n\n{\n\n let mut alloc_u8 = HeapAllocator::<u8> { default_value: 0 };\n\n let mut input_buffer = alloc_u8.alloc_cell(buffer_size);\n\n let mut output_buffer = alloc_u8.alloc_cell(buffer_size);\n\n let mut log = |data: &[brotli::interface::Command<brotli::InputReference>]| {\n\n for cmd in data.iter() {\n\n write_one(cmd)\n\n }\n\n };\n\n if params.log_meta_block {\n\n println_stderr!(\"window {} 0 0 0\", params.lgwin);\n", "file_path": "benches/brotli_1_1_3/src/lib.rs", "rank": 75, "score": 118099.8900920744 }, { "content": "pub fn get_linked_version() -> Version {\n\n Version(\"ttf-shim\".to_owned())\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum Error {}\n\n\n\nimpl std::error::Error for Error {\n\n fn description(&self) -> &str {\n\n \"ttf-shim-error-description\"\n\n }\n\n\n\n fn cause(&self) -> Option<&std::error::Error> {\n\n None\n\n }\n\n}\n\n\n\nimpl Display for Error {\n\n fn fmt(&self, fmt: &mut Formatter) -> FmtResult {\n\n write!(fmt, \"ttf-shim-error-display\")\n\n }\n\n}\n\n\n", "file_path": "benches/doom_9e197d7/src/shims/sdl2_ttf/src/lib.rs", "rank": 76, "score": 114341.8465684494 }, { "content": "fn color(mut r: Ray, model: &Model, rng: &mut XorShiftRng) -> Vec3 {\n\n const WHITE: Vec3 = Vec3(1.0, 1.0, 1.0);\n\n let sky_blue = 0.3 * Vec3(0.5, 0.7, 1.0) + 0.7 * WHITE;\n\n\n\n let mut attenuation = WHITE;\n\n let mut depth = 0;\n\n while let Some(hit) = model.hit(&r) {\n\n let scattered = hit.material.scatter(&r, &hit, rng);\n\n attenuation = attenuation * scattered.color;\n\n if let Some(bounce) = scattered.ray {\n\n r = bounce;\n\n } else {\n\n break;\n\n }\n\n\n\n depth += 1;\n\n if depth >= 50 {\n\n break;\n\n }\n\n }\n", "file_path": "benches/raytrace_8de9020/src/render.rs", "rank": 77, "score": 112952.12424750593 }, { "content": "extern crate lolbench ; # [ test ] fn end_to_end ( ) { lolbench :: end_to_end_test ( \"json_benchmark_c7d3d9b\" , \"serialize_citm_struct\" , ) ; }", "file_path": "benches/json_benchmark_c7d3d9b/tests/serialize-citm-struct.rs", "rank": 78, "score": 112579.35099311701 }, { "content": "extern crate lolbench ; # [ test ] fn end_to_end ( ) { lolbench :: end_to_end_test ( \"json_benchmark_c7d3d9b\" , \"serialize_twitter_struct\" , ) ; }", "file_path": "benches/json_benchmark_c7d3d9b/tests/serialize-twitter-struct.rs", "rank": 79, "score": 112579.35099311701 }, { "content": "extern crate lolbench ; # [ test ] fn end_to_end ( ) { lolbench :: end_to_end_test ( \"json_benchmark_c7d3d9b\" , \"serialize_canada_struct\" , ) ; }", "file_path": "benches/json_benchmark_c7d3d9b/tests/serialize-canada-struct.rs", "rank": 80, "score": 112579.35099311701 }, { "content": "fn points_to_polygon(points: &mut Vec<Vec2f>) {\n\n // Sort points in polygonal CCW order around their center.\n\n let center = polygon_center(points);\n\n points.sort_by(|a, b| {\n\n let ac = *a - center;\n\n let bc = *b - center;\n\n if ac[0] >= 0.0 && bc[0] < 0.0 {\n\n return Ordering::Less;\n\n }\n\n if ac[0] < 0.0 && bc[0] >= 0.0 {\n\n return Ordering::Greater;\n\n }\n\n if ac[0] == 0.0 && bc[0] == 0.0 {\n\n if ac[1] >= 0.0 || bc[1] >= 0.0 {\n\n return if a[1] > b[1] {\n\n Ordering::Less\n\n } else {\n\n Ordering::Greater\n\n };\n\n }\n", "file_path": "benches/doom_9e197d7/src/wad/visitor.rs", "rank": 81, "score": 110347.84245375593 }, { "content": "pub fn from_wad_height(x: WadCoord) -> f32 {\n\n (x as f32) / 100.0\n\n}\n\n\n", "file_path": "benches/doom_9e197d7/src/wad/util.rs", "rank": 82, "score": 110107.72663084006 }, { "content": "pub fn is_untextured(name: &WadName) -> bool {\n\n name[0] == b'-' && name[1] == b'\\0'\n\n}\n\n\n", "file_path": "benches/doom_9e197d7/src/wad/util.rs", "rank": 83, "score": 110107.72663084006 }, { "content": "fn rmatsub(src: &[f32], dest: &mut [f32]) {\n\n dest.par_iter_mut()\n\n .zip(src.par_iter())\n\n .for_each(|(d, s)| *d -= *s);\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/matmul/mod.rs", "rank": 84, "score": 109254.04536844068 }, { "content": "// Any layout works, we're just adding by element.\n\nfn rmatsum(src: &[f32], dest: &mut [f32]) {\n\n dest.par_iter_mut()\n\n .zip(src.par_iter())\n\n .for_each(|(d, s)| *d += *s);\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/matmul/mod.rs", "rank": 85, "score": 109254.04536844068 }, { "content": "fn rcopy(src: &[f32], dest: &mut [f32]) {\n\n if dest.len() <= LINEAR_CHUNK {\n\n dest.copy_from_slice(src);\n\n return;\n\n }\n\n\n\n let mid = dest.len() / 2;\n\n let (s1, s2) = src.split_at(mid);\n\n let (d1, d2) = dest.split_at_mut(mid);\n\n rayon::join(|| rcopy(s1, d1), || rcopy(s2, d2));\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/matmul/mod.rs", "rank": 86, "score": 109254.04536844068 }, { "content": "pub fn is_sky_flat(name: &WadName) -> bool {\n\n name == b\"F_SKY1\\0\\0\"\n\n}\n\n\n", "file_path": "benches/doom_9e197d7/src/wad/util.rs", "rank": 87, "score": 108148.40967659061 }, { "content": "fn main() {\n\n println!(\"========================== decode | encode ===\");\n\n\n\n #[cfg(feature = \"file-canada\")]\n\n bench_file! {\n\n path: \"data/canada.json\",\n\n structure: canada::Canada,\n\n }\n\n\n\n #[cfg(feature = \"file-citm-catalog\")]\n\n bench_file! {\n\n path: \"data/citm_catalog.json\",\n\n structure: citm_catalog::CitmCatalog,\n\n }\n\n\n\n #[cfg(feature = \"file-twitter\")]\n\n bench_file! {\n\n path: \"data/twitter.json\",\n\n structure: twitter::Twitter,\n\n }\n\n}\n\n\n", "file_path": "benches/json_benchmark_c7d3d9b/src/binary.rs", "rank": 88, "score": 107260.61212803473 }, { "content": "pub fn end_to_end_test(crate_name: &str, bench_name: &str) {\n\n let bench_source_name = format!(\"{}.rs\", slugify(bench_name));\n\n\n\n let _ = simple_logger::init();\n\n\n\n let entrypoint_path = Path::new(\"benches\")\n\n .join(crate_name)\n\n .join(\"src\")\n\n .join(\"bin\")\n\n .join(bench_source_name);\n\n\n\n let source_path = Path::new(env!(\"CARGO_MANIFEST_DIR\")).join(&entrypoint_path);\n\n let plan = RunPlan::new(\n\n Benchmark {\n\n runner: None,\n\n name: String::from(bench_name),\n\n crate_name: String::from(crate_name),\n\n entrypoint_path,\n\n },\n\n Some(CriterionConfig {\n", "file_path": "src/lib.rs", "rank": 89, "score": 106943.6142262768 }, { "content": "#[test]\n\nfn test_color() {\n\n let mut buf: [u8; 6] = unsafe { ::std::mem::uninitialized() };\n\n let string = Color(0xA0A0A0).as_str(&mut buf);\n\n assert_eq!(string, \"A0A0A0\");\n\n}\n", "file_path": "benches/json_benchmark_c7d3d9b/src/color.rs", "rank": 90, "score": 104546.98822800412 }, { "content": "/// Generate a Model containing a bunch of randomly placed spheres.\n\nfn random_scene(rng: &mut XorShiftRng) -> Box<Model> {\n\n let mut spheres: Vec<Sphere> = vec![\n\n Sphere {\n\n center: Vec3(0.0, 0.0, -1000.0),\n\n radius: 1000.0,\n\n material: Box::new(Lambertian {\n\n albedo: Vec3(1.0, 0.6, 0.5),\n\n }),\n\n },\n\n Sphere {\n\n center: Vec3(-4.0, 0.0, 2.0),\n\n radius: 2.0,\n\n material: Box::new(Lambertian {\n\n albedo: Vec3(0.6, 0.2, 0.2),\n\n }),\n\n },\n\n Sphere {\n\n center: Vec3(0.0, 0.0, 2.0),\n\n radius: 2.0,\n\n material: Box::new(Dielectric { index: 1.5 }),\n", "file_path": "benches/raytrace_8de9020/src/lib.rs", "rank": 91, "score": 103362.29489496411 }, { "content": "struct IoWriterWrapper<'a, OutputType: Write + 'a>(&'a mut OutputType);\n\n\n", "file_path": "benches/brotli_1_1_3/src/lib.rs", "rank": 92, "score": 103081.08376812904 }, { "content": "struct IoReaderWrapper<'a, OutputType: Read + 'a>(&'a mut OutputType);\n\n\n\nmacro_rules! println_stderr(\n\n ($($val:tt)*) => { {\n\n writeln!(&mut ::std::io::stderr(), $($val)*).unwrap();\n\n } }\n\n);\n\n\n", "file_path": "benches/brotli_1_1_3/src/lib.rs", "rank": 93, "score": 103081.08376812904 }, { "content": "fn strassen_sum(a: &[f32], b: &[f32], dest: &mut [f32]) {\n\n rcopy(a, dest);\n\n rmatsum(b, dest);\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/matmul/mod.rs", "rank": 94, "score": 101996.19949846648 }, { "content": "fn quarter_chunks_mut<'a>(\n\n v: &'a mut [f32],\n\n) -> (&'a mut [f32], &'a mut [f32], &'a mut [f32], &'a mut [f32]) {\n\n let mid = v.len() / 2;\n\n let quarter = mid / 2;\n\n let (left, right) = v.split_at_mut(mid);\n\n let (a, b) = left.split_at_mut(quarter);\n\n let (c, d) = right.split_at_mut(quarter);\n\n (a, b, c, d)\n\n}\n\n\n", "file_path": "benches/rayon_1_0_0/src/matmul/mod.rs", "rank": 95, "score": 101882.50192927764 }, { "content": "pub fn parse_child_id(id: ChildId) -> (usize, bool) {\n\n ((id & 0x7fff) as usize, id & 0x8000 != 0)\n\n}\n", "file_path": "benches/doom_9e197d7/src/wad/util.rs", "rank": 96, "score": 101397.4616260739 }, { "content": "pub fn from_wad_coords(x: WadCoord, y: WadCoord) -> Vec2f {\n\n Vec2::new(-from_wad_height(x), from_wad_height(y))\n\n}\n\n\n", "file_path": "benches/doom_9e197d7/src/wad/util.rs", "rank": 97, "score": 100393.83687665939 }, { "content": "fn clear_stride(slice: &mut [bool], from: usize, stride: usize) {\n\n let slice = &mut slice[from..];\n\n for x in StrideMut::from_slice(slice, stride as isize) {\n\n *x = false;\n\n }\n\n}\n", "file_path": "benches/rayon_1_0_0/src/sieve/mod.rs", "rank": 98, "score": 100035.90549399421 }, { "content": "pub fn solid<T>(foreground: T) -> RenderMode\n\nwhere\n\n T: Into<Color>,\n\n{\n\n RenderMode::Solid {\n\n foreground: foreground.into(),\n\n }\n\n}\n\n\n", "file_path": "benches/doom_9e197d7/src/shims/sdl2_ttf/src/lib.rs", "rank": 99, "score": 99751.72770944922 } ]
Rust
bin/inx-chronicle/src/api/stardust/v2/routes.rs
iotaledger/inx-chronicle
d7d1643a57f418fec5550ad8c24a63986a2c91a6
use std::str::FromStr; use axum::{ extract::{Extension, Path}, routing::*, Router, }; use chronicle::{ db::MongoDb, types::{ stardust::block::{BlockId, MilestoneId, OutputId, TransactionId}, tangle::MilestoneIndex, }, }; use super::responses::*; use crate::api::{error::ApiError, ApiResult}; pub fn routes() -> Router { Router::new() .nest( "/blocks", Router::new() .route("/:block_id", get(block)) .route("/:block_id/raw", get(block_raw)) .route("/:block_id/metadata", get(block_metadata)), ) .nest( "/outputs", Router::new() .route("/:output_id", get(output)) .route("/:output_id/metadata", get(output_metadata)), ) .nest( "/transactions", Router::new().route("/:transaction_id/included-block", get(transaction_included_block)), ) .nest( "/milestones", Router::new() .route("/:milestone_id", get(milestone)) .route("/by-index/:index", get(milestone_by_index)), ) } async fn block(database: Extension<MongoDb>, Path(block_id): Path<String>) -> ApiResult<BlockResponse> { let block_id = BlockId::from_str(&block_id).map_err(ApiError::bad_parse)?; let rec = database.get_block(&block_id).await?.ok_or(ApiError::NoResults)?; Ok(BlockResponse { protocol_version: rec.protocol_version, parents: rec.parents.iter().map(|m| m.to_hex()).collect(), payload: rec.payload, nonce: rec.nonce, }) } async fn block_raw(database: Extension<MongoDb>, Path(block_id): Path<String>) -> ApiResult<Vec<u8>> { let block_id = BlockId::from_str(&block_id).map_err(ApiError::bad_parse)?; database.get_block_raw(&block_id).await?.ok_or(ApiError::NoResults) } async fn block_metadata( database: Extension<MongoDb>, Path(block_id): Path<String>, ) -> ApiResult<BlockMetadataResponse> { let block_id = BlockId::from_str(&block_id).map_err(ApiError::bad_parse)?; let metadata = database .get_block_metadata(&block_id) .await? .ok_or(ApiError::NoResults)?; Ok(BlockMetadataResponse { block_id: metadata.block_id.to_hex(), parents: metadata.parents.iter().map(|id| id.to_hex()).collect(), is_solid: Some(metadata.is_solid), referenced_by_milestone_index: Some(metadata.referenced_by_milestone_index), milestone_index: Some(metadata.milestone_index), should_promote: Some(metadata.should_promote), should_reattach: Some(metadata.should_reattach), ledger_inclusion_state: Some(metadata.inclusion_state), conflict_reason: Some(metadata.conflict_reason as u8), }) } async fn output(database: Extension<MongoDb>, Path(output_id): Path<String>) -> ApiResult<OutputResponse> { let output_id = OutputId::from_str(&output_id).map_err(ApiError::bad_parse)?; let (output, metadata) = database .get_output_and_metadata(&output_id) .await? .ok_or(ApiError::NoResults)?; Ok(OutputResponse { block_id: metadata.block_id.to_hex(), transaction_id: metadata.transaction_id.to_hex(), output_index: metadata.output_id.index, is_spent: metadata.spent.is_some(), milestone_index_spent: metadata.spent.as_ref().map(|s| s.spent.milestone_index), milestone_ts_spent: metadata.spent.as_ref().map(|s| s.spent.milestone_timestamp), milestone_index_booked: metadata.booked.milestone_index, milestone_ts_booked: metadata.booked.milestone_timestamp, output, }) } async fn output_metadata( database: Extension<MongoDb>, Path(output_id): Path<String>, ) -> ApiResult<OutputMetadataResponse> { let output_id = OutputId::from_str(&output_id).map_err(ApiError::bad_parse)?; let metadata = database .get_output_metadata(&output_id) .await? .ok_or(ApiError::NoResults)?; Ok(OutputMetadataResponse { block_id: metadata.block_id.to_hex(), transaction_id: metadata.transaction_id.to_hex(), output_index: metadata.output_id.index, is_spent: metadata.spent.is_some(), milestone_index_spent: metadata.spent.as_ref().map(|s| s.spent.milestone_index), milestone_ts_spent: metadata.spent.as_ref().map(|s| s.spent.milestone_timestamp), transaction_id_spent: metadata.spent.as_ref().map(|s| s.transaction_id.to_hex()), milestone_index_booked: metadata.booked.milestone_index, milestone_ts_booked: metadata.booked.milestone_timestamp, }) } async fn transaction_included_block( database: Extension<MongoDb>, Path(transaction_id): Path<String>, ) -> ApiResult<BlockResponse> { let transaction_id_dto = TransactionId::from_str(&transaction_id).map_err(ApiError::bad_parse)?; let block = database .get_block_for_transaction(&transaction_id_dto) .await? .ok_or(ApiError::NoResults)?; Ok(BlockResponse { protocol_version: block.protocol_version, parents: block.parents.iter().map(|m| m.to_hex()).collect(), payload: block.payload, nonce: block.nonce, }) } async fn milestone(database: Extension<MongoDb>, Path(milestone_id): Path<String>) -> ApiResult<MilestoneResponse> { let milestone_id = MilestoneId::from_str(&milestone_id).map_err(ApiError::bad_parse)?; let payload = database .get_milestone_payload_by_id(&milestone_id) .await? .ok_or(ApiError::NoResults)?; Ok(MilestoneResponse { payload }) } async fn milestone_by_index( database: Extension<MongoDb>, Path(index): Path<MilestoneIndex>, ) -> ApiResult<MilestoneResponse> { let payload = database .get_milestone_payload(index) .await? .ok_or(ApiError::NoResults)?; Ok(MilestoneResponse { payload }) }
use std::str::FromStr; use axum::{ extract::{Extension, Path}, routing::*, Router, }; use chronicle::{ db::MongoDb, types::{ stardust::block::{BlockId, MilestoneId, OutputId, TransactionId}, tangle::MilestoneIndex, }, }; use super::responses::*; use crate::api::{error::ApiError, ApiResult}; pub fn routes() -> Router { Router::new() .nest( "/blocks", Router::new() .route("/:block_id", get(block)) .route("/:block_id/raw", get(block_raw)) .route("/:block_id/metadata", get(block_metadata)), ) .nest( "/outputs", Router::new() .route("/:output_id", get(output)) .route("/:output_id/metadata", get(output_metadata)), ) .nest( "/transactions", Router::new().route("/:transaction_id/included-block", get(transaction_included_block)), ) .nest( "/milestones", Router::new() .route("/:milestone_id", get(milestone)) .route("/by-index/:index", get(milestone_by_index)), ) } async fn block(database: Extension<MongoDb>, Path(block_id): Path<String>) -> ApiResult<BlockResponse> { let block_id = BlockId::from_str(&block_id).map_err(ApiError::bad_parse)?; let rec = database.get_block(&block_id).await?.ok_or(ApiError::NoResults)?; Ok(BlockResponse { protocol_version: rec.protocol_version, parents: rec.parents.iter().map(|m| m.to_hex()).collect(), payload: rec.payload, nonce: rec.nonce, }) } async fn block_raw(database: Extension<MongoDb>, Path(block_id): Path<String>) -> ApiResult<Vec<u8>> { let block_id = BlockId::from_str(&block_id).map_err(ApiError::bad_parse)?; database.get_block_raw(&block_id).await?.ok_or(ApiError::NoResults) } async fn block_metadata( database: Extension<MongoDb>, Path(block_id): Path<String>, ) -> ApiResult<BlockMetadataResponse> { let block_id = BlockId::from_str(&block_id).map_err(ApiError::bad_parse)?; let metadata = database .get_block_metadata(&block_id) .await? .ok_or(ApiError::NoResults)?; Ok(BlockMetadataResponse { block_id: metadata.block_id.to_hex(), parents: metadata.parents.iter().map(|id| id.to_hex()).collect(), is_solid: Some(metadata.is_solid), referenced_by_milestone_index: Some(metadata.referenced_by_milestone_index), milestone_index: Some(metadata.milestone_index), should_promote: Some(metadata.should_promote), should_reattach: Some(metadata.should_reattach), ledger_inclusion_state: Some(metadata.inclusion_state), conflict_reason: Some(metadata.conflict_reason as u8), }) } async fn output(database: Extension<MongoDb>, Path(output_id): Path<String>) -> ApiResult<OutputResponse> { let output_id = OutputId::from_str(&output_id).map_err(ApiError::bad_parse)?; let (output, metadata) = database .get_output_and_metadata(&output_id) .await? .ok_or(ApiError::NoResults)?; Ok(OutputResponse { block_id: metadata.block_id.to_hex(), transaction_id: metadata.transaction_id.to_hex(), output_index: metadata.output_id.index, is_spent: metadata.spent.is_some(), milestone_index_spent: metadata.spent.as_ref().map(|s| s.spent.milestone_index), milestone_ts_spent: metadata.spent.as_ref().map(|s| s.spent.milestone_timestamp), milestone_index_booked: metadata.booked.milestone_index, milestone_ts_booked: metadata.booked.milestone_timestamp, output, }) } async fn output_metadata( database: Extension<MongoDb>, Path(output_id): Path<String>, ) -> ApiResult<OutputMetadataResponse> { let output_id = OutputId::from_str(&output_id).map_err(ApiError::bad_parse)?; let metadata = database .get_output_metadata(&output_id) .await? .ok_or(ApiError::NoResults)?;
} async fn transaction_included_block( database: Extension<MongoDb>, Path(transaction_id): Path<String>, ) -> ApiResult<BlockResponse> { let transaction_id_dto = TransactionId::from_str(&transaction_id).map_err(ApiError::bad_parse)?; let block = database .get_block_for_transaction(&transaction_id_dto) .await? .ok_or(ApiError::NoResults)?; Ok(BlockResponse { protocol_version: block.protocol_version, parents: block.parents.iter().map(|m| m.to_hex()).collect(), payload: block.payload, nonce: block.nonce, }) } async fn milestone(database: Extension<MongoDb>, Path(milestone_id): Path<String>) -> ApiResult<MilestoneResponse> { let milestone_id = MilestoneId::from_str(&milestone_id).map_err(ApiError::bad_parse)?; let payload = database .get_milestone_payload_by_id(&milestone_id) .await? .ok_or(ApiError::NoResults)?; Ok(MilestoneResponse { payload }) } async fn milestone_by_index( database: Extension<MongoDb>, Path(index): Path<MilestoneIndex>, ) -> ApiResult<MilestoneResponse> { let payload = database .get_milestone_payload(index) .await? .ok_or(ApiError::NoResults)?; Ok(MilestoneResponse { payload }) }
Ok(OutputMetadataResponse { block_id: metadata.block_id.to_hex(), transaction_id: metadata.transaction_id.to_hex(), output_index: metadata.output_id.index, is_spent: metadata.spent.is_some(), milestone_index_spent: metadata.spent.as_ref().map(|s| s.spent.milestone_index), milestone_ts_spent: metadata.spent.as_ref().map(|s| s.spent.milestone_timestamp), transaction_id_spent: metadata.spent.as_ref().map(|s| s.transaction_id.to_hex()), milestone_index_booked: metadata.booked.milestone_index, milestone_ts_booked: metadata.booked.milestone_timestamp, })
call_expression
[ { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse std::str::FromStr;\n\n\n\nuse bee_block_stardust::payload::milestone as bee;\n\nuse mongodb::bson::{spec::BinarySubtype, Binary, Bson};\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::types::util::bytify;\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(transparent)]\n\npub struct MilestoneId(#[serde(with = \"bytify\")] pub [u8; Self::LENGTH]);\n\n\n\nimpl MilestoneId {\n\n const LENGTH: usize = bee::MilestoneId::LENGTH;\n\n}\n\n\n\nimpl From<bee::MilestoneId> for MilestoneId {\n", "file_path": "src/types/stardust/block/payload/milestone/milestone_id.rs", "rank": 0, "score": 134919.454855 }, { "content": " fn from(value: bee::MilestoneId) -> Self {\n\n Self(*value)\n\n }\n\n}\n\n\n\nimpl From<MilestoneId> for bee::MilestoneId {\n\n fn from(value: MilestoneId) -> Self {\n\n bee::MilestoneId::new(value.0)\n\n }\n\n}\n\n\n\nimpl FromStr for MilestoneId {\n\n type Err = bee_block_stardust::Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n Ok(bee::MilestoneId::from_str(s)?.into())\n\n }\n\n}\n\n\n\nimpl From<MilestoneId> for Bson {\n\n fn from(val: MilestoneId) -> Self {\n\n Binary {\n\n subtype: BinarySubtype::Generic,\n\n bytes: val.0.to_vec(),\n\n }\n\n .into()\n\n }\n\n}\n", "file_path": "src/types/stardust/block/payload/milestone/milestone_id.rs", "rank": 1, "score": 134907.39880959404 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse std::str::FromStr;\n\n\n\nuse bee_block_stardust::{output::InputsCommitment, payload::transaction as bee};\n\nuse mongodb::bson::{spec::BinarySubtype, Binary, Bson};\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::types::{\n\n stardust::block::{Input, Output, Payload, Unlock},\n\n util::bytify,\n\n};\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(transparent)]\n\npub struct TransactionId(#[serde(with = \"bytify\")] pub [u8; Self::LENGTH]);\n\n\n\nimpl TransactionId {\n\n const LENGTH: usize = bee::TransactionId::LENGTH;\n", "file_path": "src/types/stardust/block/payload/transaction.rs", "rank": 2, "score": 133051.35291114094 }, { "content": " pub(crate) const OUTPUT_ID1: &str = \"0x52fdfc072182654f163f5f0f9a621d729566c74d10037c4d7bbb0407d1e2c6492a00\";\n\n pub(crate) const OUTPUT_ID2: &str = \"0x52fdfc072182654f163f5f0f9a621d729566c74d10037c4d7bbb0407d1e2c6492b00\";\n\n pub(crate) const OUTPUT_ID3: &str = \"0x52fdfc072182654f163f5f0f9a621d729566c74d10037c4d7bbb0407d1e2c6492c00\";\n\n pub(crate) const OUTPUT_ID4: &str = \"0x52fdfc072182654f163f5f0f9a621d729566c74d10037c4d7bbb0407d1e2c6492d00\";\n\n\n\n use bee_block_stardust::unlock::Unlocks;\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n\n use super::*;\n\n use crate::types::stardust::block::{\n\n output::test::{get_test_alias_output, get_test_basic_output, get_test_foundry_output, get_test_nft_output},\n\n unlock::test::{\n\n get_test_alias_unlock, get_test_nft_unlock, get_test_reference_unlock, get_test_signature_unlock,\n\n },\n\n OutputId,\n\n };\n\n\n\n #[test]\n\n fn test_transaction_id_bson() {\n\n let transaction_id = TransactionId::from(bee_test::rand::transaction::rand_transaction_id());\n", "file_path": "src/types/stardust/block/payload/transaction.rs", "rank": 3, "score": 133046.49560605662 }, { "content": " bee_block_stardust::output::InputsCommitment::new(outputs.iter()),\n\n )\n\n .with_inputs(\n\n Vec::from(inputs)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )\n\n .with_outputs(outputs);\n\n if let Some(payload) = payload {\n\n builder = builder.with_payload(payload.try_into()?);\n\n }\n\n bee::TransactionEssence::Regular(builder.finish()?)\n\n }\n\n })\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n", "file_path": "src/types/stardust/block/payload/transaction.rs", "rank": 4, "score": 133045.08445107532 }, { "content": " let bson = to_bson(&transaction_id).unwrap();\n\n assert_eq!(Bson::from(transaction_id), bson);\n\n assert_eq!(transaction_id, from_bson::<TransactionId>(bson).unwrap());\n\n }\n\n\n\n #[test]\n\n fn test_transaction_payload_bson() {\n\n let payload = get_test_transaction_payload();\n\n let bson = to_bson(&payload).unwrap();\n\n assert_eq!(payload, from_bson::<TransactionPayload>(bson).unwrap());\n\n }\n\n\n\n pub(crate) fn get_test_transaction_essence() -> TransactionEssence {\n\n TransactionEssence::from(&bee::TransactionEssence::Regular(\n\n bee::RegularTransactionEssenceBuilder::new(0, [0; 32].into())\n\n .with_inputs(vec![\n\n Input::Utxo(OutputId::from_str(OUTPUT_ID1).unwrap()).try_into().unwrap(),\n\n Input::Utxo(OutputId::from_str(OUTPUT_ID2).unwrap()).try_into().unwrap(),\n\n Input::Utxo(OutputId::from_str(OUTPUT_ID3).unwrap()).try_into().unwrap(),\n\n Input::Utxo(OutputId::from_str(OUTPUT_ID4).unwrap()).try_into().unwrap(),\n", "file_path": "src/types/stardust/block/payload/transaction.rs", "rank": 5, "score": 133042.8464917851 }, { "content": " pub unlocks: Box<[Unlock]>,\n\n}\n\n\n\nimpl From<&bee::TransactionPayload> for TransactionPayload {\n\n fn from(value: &bee::TransactionPayload) -> Self {\n\n Self {\n\n id: value.id().into(),\n\n essence: value.essence().into(),\n\n unlocks: value.unlocks().iter().map(Into::into).collect(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<TransactionPayload> for bee::TransactionPayload {\n\n type Error = bee_block_stardust::Error;\n\n\n\n fn try_from(value: TransactionPayload) -> Result<Self, Self::Error> {\n\n bee::TransactionPayload::new(\n\n value.essence.try_into()?,\n\n bee_block_stardust::unlock::Unlocks::new(\n", "file_path": "src/types/stardust/block/payload/transaction.rs", "rank": 6, "score": 133042.58206452074 }, { "content": "}\n\n\n\nimpl TryFrom<TransactionEssence> for bee::TransactionEssence {\n\n type Error = bee_block_stardust::Error;\n\n\n\n fn try_from(value: TransactionEssence) -> Result<Self, Self::Error> {\n\n Ok(match value {\n\n TransactionEssence::Regular {\n\n network_id,\n\n inputs,\n\n inputs_commitment: _,\n\n outputs,\n\n payload,\n\n } => {\n\n let outputs = Vec::from(outputs)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<bee_block_stardust::output::Output>, _>>()?;\n\n let mut builder = bee::RegularTransactionEssence::builder(\n\n network_id,\n", "file_path": "src/types/stardust/block/payload/transaction.rs", "rank": 7, "score": 133042.55650379395 }, { "content": " ])\n\n .with_outputs(vec![\n\n get_test_basic_output().try_into().unwrap(),\n\n get_test_alias_output().try_into().unwrap(),\n\n get_test_foundry_output().try_into().unwrap(),\n\n get_test_nft_output().try_into().unwrap(),\n\n ])\n\n .finish()\n\n .unwrap(),\n\n ))\n\n }\n\n\n\n pub(crate) fn get_test_transaction_payload() -> TransactionPayload {\n\n TransactionPayload::from(\n\n &bee::TransactionPayload::new(\n\n get_test_transaction_essence().try_into().unwrap(),\n\n Unlocks::new(vec![\n\n get_test_signature_unlock().try_into().unwrap(),\n\n get_test_reference_unlock().try_into().unwrap(),\n\n get_test_alias_unlock().try_into().unwrap(),\n\n get_test_nft_unlock().try_into().unwrap(),\n\n ])\n\n .unwrap(),\n\n )\n\n .unwrap(),\n\n )\n\n }\n\n}\n", "file_path": "src/types/stardust/block/payload/transaction.rs", "rank": 8, "score": 133042.55428993094 }, { "content": " payload: Option<Payload>,\n\n },\n\n}\n\n\n\nimpl TransactionEssence {\n\n const INPUTS_COMMITMENT_LENGTH: usize = InputsCommitment::LENGTH;\n\n}\n\n\n\nimpl From<&bee::TransactionEssence> for TransactionEssence {\n\n fn from(value: &bee::TransactionEssence) -> Self {\n\n match value {\n\n bee::TransactionEssence::Regular(essence) => Self::Regular {\n\n network_id: essence.network_id(),\n\n inputs: essence.inputs().iter().map(Into::into).collect(),\n\n inputs_commitment: **essence.inputs_commitment(),\n\n outputs: essence.outputs().iter().map(Into::into).collect(),\n\n payload: essence.payload().map(Into::into),\n\n },\n\n }\n\n }\n", "file_path": "src/types/stardust/block/payload/transaction.rs", "rank": 9, "score": 133039.66256965726 }, { "content": " Vec::from(value.unlocks)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )?,\n\n )\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(tag = \"kind\")]\n\npub enum TransactionEssence {\n\n #[serde(rename = \"regular\")]\n\n Regular {\n\n #[serde(with = \"crate::types::util::stringify\")]\n\n network_id: u64,\n\n inputs: Box<[Input]>,\n\n #[serde(with = \"bytify\")]\n\n inputs_commitment: [u8; Self::INPUTS_COMMITMENT_LENGTH],\n\n outputs: Box<[Output]>,\n", "file_path": "src/types/stardust/block/payload/transaction.rs", "rank": 10, "score": 133039.11510938575 }, { "content": "\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n Ok(bee::TransactionId::from_str(s)?.into())\n\n }\n\n}\n\n\n\nimpl From<TransactionId> for Bson {\n\n fn from(val: TransactionId) -> Self {\n\n Binary {\n\n subtype: BinarySubtype::Generic,\n\n bytes: val.0.to_vec(),\n\n }\n\n .into()\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct TransactionPayload {\n\n pub id: TransactionId,\n\n pub essence: TransactionEssence,\n", "file_path": "src/types/stardust/block/payload/transaction.rs", "rank": 11, "score": 133038.60486887593 }, { "content": "\n\n pub fn to_hex(&self) -> String {\n\n prefix_hex::encode(self.0.as_ref())\n\n }\n\n}\n\n\n\nimpl From<bee::TransactionId> for TransactionId {\n\n fn from(value: bee::TransactionId) -> Self {\n\n Self(*value)\n\n }\n\n}\n\n\n\nimpl From<TransactionId> for bee::TransactionId {\n\n fn from(value: TransactionId) -> Self {\n\n bee::TransactionId::new(value.0)\n\n }\n\n}\n\n\n\nimpl FromStr for TransactionId {\n\n type Err = bee_block_stardust::Error;\n", "file_path": "src/types/stardust/block/payload/transaction.rs", "rank": 12, "score": 133037.51573851294 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::payload as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::MilestoneId;\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct TreasuryTransactionPayload {\n\n input_milestone_id: MilestoneId,\n\n #[serde(with = \"crate::types::util::stringify\")]\n\n output_amount: u64,\n\n}\n\n\n\nimpl From<&bee::TreasuryTransactionPayload> for TreasuryTransactionPayload {\n\n fn from(value: &bee::TreasuryTransactionPayload) -> Self {\n\n Self {\n\n input_milestone_id: (*value.input().milestone_id()).into(),\n\n output_amount: value.output().amount(),\n", "file_path": "src/types/stardust/block/payload/treasury_transaction.rs", "rank": 13, "score": 129821.90234700298 }, { "content": " }\n\n }\n\n}\n\n\n\nimpl TryFrom<TreasuryTransactionPayload> for bee::TreasuryTransactionPayload {\n\n type Error = bee_block_stardust::Error;\n\n\n\n fn try_from(value: TreasuryTransactionPayload) -> Result<Self, Self::Error> {\n\n Self::new(\n\n bee_block_stardust::input::TreasuryInput::new(value.input_milestone_id.into()),\n\n bee_block_stardust::output::TreasuryOutput::new(value.output_amount)?,\n\n )\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n\n use super::*;\n", "file_path": "src/types/stardust/block/payload/treasury_transaction.rs", "rank": 14, "score": 129821.39951225316 }, { "content": "\n\n #[test]\n\n fn test_treasury_transaction_payload_bson() {\n\n let payload = get_test_treasury_transaction_payload();\n\n let bson = to_bson(&payload).unwrap();\n\n assert_eq!(payload, from_bson::<TreasuryTransactionPayload>(bson).unwrap());\n\n }\n\n\n\n pub(crate) fn get_test_treasury_transaction_payload() -> TreasuryTransactionPayload {\n\n TreasuryTransactionPayload::from(\n\n &bee::TreasuryTransactionPayload::new(\n\n bee_test::rand::input::rand_treasury_input(),\n\n bee_test::rand::output::rand_treasury_output(),\n\n )\n\n .unwrap(),\n\n )\n\n }\n\n}\n", "file_path": "src/types/stardust/block/payload/treasury_transaction.rs", "rank": 15, "score": 129812.42073482573 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nmod milestone_id;\n\n\n\nuse bee_block_stardust::payload::milestone as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\npub use self::milestone_id::MilestoneId;\n\nuse crate::types::{\n\n stardust::block::{Address, BlockId, Signature, TreasuryTransactionPayload},\n\n tangle::MilestoneIndex,\n\n util::bytify,\n\n};\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct MilestonePayload {\n\n pub essence: MilestoneEssence,\n\n pub signatures: Box<[Signature]>,\n\n}\n", "file_path": "src/types/stardust/block/payload/milestone/mod.rs", "rank": 16, "score": 129353.04705101726 }, { "content": " )\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct MilestoneEssence {\n\n pub index: MilestoneIndex,\n\n pub timestamp: u32,\n\n pub previous_milestone_id: MilestoneId,\n\n pub parents: Box<[BlockId]>,\n\n #[serde(with = \"bytify\")]\n\n pub inclusion_merkle_root: [u8; Self::MERKLE_PROOF_LENGTH],\n\n #[serde(with = \"bytify\")]\n\n pub applied_merkle_root: [u8; Self::MERKLE_PROOF_LENGTH],\n\n #[serde(with = \"serde_bytes\")]\n\n pub metadata: Vec<u8>,\n\n pub options: Box<[MilestoneOption]>,\n\n}\n\n\n\nimpl MilestoneEssence {\n", "file_path": "src/types/stardust/block/payload/milestone/mod.rs", "rank": 17, "score": 129350.35581215912 }, { "content": "\n\n use bee_block_stardust::payload::TreasuryTransactionPayload;\n\n use mongodb::bson::{from_bson, to_bson, Bson};\n\n\n\n use super::*;\n\n use crate::types::stardust::block::signature::test::get_test_signature;\n\n\n\n #[test]\n\n fn test_milestone_id_bson() {\n\n let milestone_id = MilestoneId::from(bee_test::rand::milestone::rand_milestone_id());\n\n let bson = to_bson(&milestone_id).unwrap();\n\n assert_eq!(Bson::from(milestone_id), bson);\n\n assert_eq!(milestone_id, from_bson::<MilestoneId>(bson).unwrap());\n\n }\n\n\n\n #[test]\n\n fn test_milestone_payload_bson() {\n\n let payload = get_test_milestone_payload();\n\n let bson = to_bson(&payload).unwrap();\n\n assert_eq!(payload, from_bson::<MilestonePayload>(bson).unwrap());\n", "file_path": "src/types/stardust/block/payload/milestone/mod.rs", "rank": 18, "score": 129348.8643037681 }, { "content": "\n\n fn try_from(value: MilestoneEssence) -> Result<Self, Self::Error> {\n\n bee::MilestoneEssence::new(\n\n value.index.into(),\n\n value.timestamp,\n\n value.previous_milestone_id.into(),\n\n bee_block_stardust::parent::Parents::new(\n\n Vec::from(value.parents).into_iter().map(Into::into).collect::<Vec<_>>(),\n\n )?,\n\n bee_block_stardust::payload::milestone::MerkleRoot::from(value.inclusion_merkle_root),\n\n bee_block_stardust::payload::milestone::MerkleRoot::from(value.applied_merkle_root),\n\n value.metadata,\n\n bee_block_stardust::payload::MilestoneOptions::new(\n\n Vec::from(value.options)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )?,\n\n )\n\n }\n", "file_path": "src/types/stardust/block/payload/milestone/mod.rs", "rank": 19, "score": 129348.78188267091 }, { "content": "}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(tag = \"kind\")]\n\npub enum MilestoneOption {\n\n #[serde(rename = \"receipt\")]\n\n Receipt {\n\n migrated_at: MilestoneIndex,\n\n last: bool,\n\n funds: Box<[MigratedFundsEntry]>,\n\n transaction: TreasuryTransactionPayload,\n\n },\n\n #[serde(rename = \"parameters\")]\n\n Parameters {\n\n target_milestone_index: MilestoneIndex,\n\n protocol_version: u8,\n\n binary_parameters: Box<[u8]>,\n\n },\n\n}\n\n\n", "file_path": "src/types/stardust/block/payload/milestone/mod.rs", "rank": 20, "score": 129347.25078850386 }, { "content": " bee_test::rand::milestone::rand_milestone_id(),\n\n bee_test::rand::parents::rand_parents(),\n\n bee_test::rand::milestone::rand_merkle_root(),\n\n bee_test::rand::milestone::rand_merkle_root(),\n\n \"Foo\".as_bytes().to_vec(),\n\n bee::MilestoneOptions::new(vec![bee::option::MilestoneOption::Receipt(\n\n bee::option::ReceiptMilestoneOption::new(\n\n 1.into(),\n\n false,\n\n vec![\n\n get_test_ed25519_migrated_funds_entry().try_into().unwrap(),\n\n get_test_alias_migrated_funds_entry().try_into().unwrap(),\n\n get_test_nft_migrated_funds_entry().try_into().unwrap(),\n\n ],\n\n TreasuryTransactionPayload::new(\n\n bee_test::rand::input::rand_treasury_input(),\n\n bee_test::rand::output::rand_treasury_output(),\n\n )\n\n .unwrap(),\n\n )\n", "file_path": "src/types/stardust/block/payload/milestone/mod.rs", "rank": 21, "score": 129345.27595303954 }, { "content": " const MERKLE_PROOF_LENGTH: usize = bee::MerkleRoot::LENGTH;\n\n}\n\n\n\nimpl From<&bee::MilestoneEssence> for MilestoneEssence {\n\n fn from(value: &bee::MilestoneEssence) -> Self {\n\n Self {\n\n index: value.index().0.into(),\n\n timestamp: value.timestamp(),\n\n previous_milestone_id: (*value.previous_milestone_id()).into(),\n\n parents: value.parents().iter().map(|id| BlockId::from(*id)).collect(),\n\n inclusion_merkle_root: **value.inclusion_merkle_root(),\n\n applied_merkle_root: **value.applied_merkle_root(),\n\n metadata: value.metadata().to_vec(),\n\n options: value.options().iter().map(Into::into).collect(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<MilestoneEssence> for bee::MilestoneEssence {\n\n type Error = bee_block_stardust::Error;\n", "file_path": "src/types/stardust/block/payload/milestone/mod.rs", "rank": 22, "score": 129344.25899800277 }, { "content": " .unwrap(),\n\n )\n\n }\n\n\n\n pub(crate) fn get_test_nft_migrated_funds_entry() -> MigratedFundsEntry {\n\n MigratedFundsEntry::from(\n\n &bee::option::MigratedFundsEntry::new(\n\n bee::option::TailTransactionHash::new(TAIL_TRANSACTION_HASH3).unwrap(),\n\n bee_block_stardust::address::Address::Nft(bee_test::rand::address::rand_nft_address()),\n\n 2000000,\n\n )\n\n .unwrap(),\n\n )\n\n }\n\n\n\n pub(crate) fn get_test_milestone_essence() -> MilestoneEssence {\n\n MilestoneEssence::from(\n\n &bee::MilestoneEssence::new(\n\n 1.into(),\n\n 12345,\n", "file_path": "src/types/stardust/block/payload/milestone/mod.rs", "rank": 23, "score": 129343.34158634528 }, { "content": " binary_parameters,\n\n } => Self::Parameters(bee::ParametersMilestoneOption::new(\n\n target_milestone_index.into(),\n\n protocol_version,\n\n binary_parameters.into_vec(),\n\n )?),\n\n })\n\n }\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct MigratedFundsEntry {\n\n #[serde(with = \"bytify\")]\n\n tail_transaction_hash: [u8; Self::TAIL_TRANSACTION_HASH_LENGTH],\n\n address: Address,\n\n #[serde(with = \"crate::types::util::stringify\")]\n\n amount: u64,\n\n}\n\n\n\nimpl MigratedFundsEntry {\n", "file_path": "src/types/stardust/block/payload/milestone/mod.rs", "rank": 24, "score": 129342.34821978457 }, { "content": " .unwrap(),\n\n )])\n\n .unwrap(),\n\n )\n\n .unwrap(),\n\n )\n\n }\n\n\n\n pub(crate) fn get_test_milestone_payload() -> MilestonePayload {\n\n MilestonePayload::from(\n\n &bee::MilestonePayload::new(\n\n get_test_milestone_essence().try_into().unwrap(),\n\n vec![get_test_signature().try_into().unwrap()],\n\n )\n\n .unwrap(),\n\n )\n\n }\n\n}\n", "file_path": "src/types/stardust/block/payload/milestone/mod.rs", "rank": 25, "score": 129342.20252853967 }, { "content": " value.address.into(),\n\n value.amount,\n\n )\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n const TAIL_TRANSACTION_HASH1: [u8; 49] = [\n\n 222, 235, 107, 67, 2, 173, 253, 93, 165, 90, 166, 45, 102, 91, 19, 137, 71, 146, 156, 180, 248, 31, 56, 25, 68,\n\n 154, 98, 100, 64, 108, 203, 48, 76, 75, 114, 150, 34, 153, 203, 35, 225, 120, 194, 175, 169, 207, 80, 229, 10,\n\n ];\n\n const TAIL_TRANSACTION_HASH2: [u8; 49] = [\n\n 222, 235, 107, 67, 2, 173, 253, 93, 165, 90, 166, 45, 102, 91, 19, 137, 71, 146, 156, 180, 248, 31, 56, 25, 68,\n\n 154, 98, 100, 64, 108, 203, 48, 76, 75, 114, 150, 34, 153, 203, 35, 225, 120, 194, 175, 169, 207, 80, 229, 11,\n\n ];\n\n const TAIL_TRANSACTION_HASH3: [u8; 49] = [\n\n 222, 235, 107, 67, 2, 173, 253, 93, 165, 90, 166, 45, 102, 91, 19, 137, 71, 146, 156, 180, 248, 31, 56, 25, 68,\n\n 154, 98, 100, 64, 108, 203, 48, 76, 75, 114, 150, 34, 153, 203, 35, 225, 120, 194, 175, 169, 207, 80, 229, 12,\n\n ];\n", "file_path": "src/types/stardust/block/payload/milestone/mod.rs", "rank": 26, "score": 129342.10835923479 }, { "content": "\n\nimpl From<&bee::MilestonePayload> for MilestonePayload {\n\n fn from(value: &bee::MilestonePayload) -> Self {\n\n Self {\n\n essence: MilestoneEssence::from(value.essence()),\n\n signatures: value.signatures().iter().map(Into::into).collect(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<MilestonePayload> for bee::MilestonePayload {\n\n type Error = bee_block_stardust::Error;\n\n\n\n fn try_from(value: MilestonePayload) -> Result<Self, Self::Error> {\n\n bee::MilestonePayload::new(\n\n value.essence.try_into()?,\n\n Vec::from(value.signatures)\n\n .into_iter()\n\n .map(Into::into)\n\n .collect::<Vec<_>>(),\n", "file_path": "src/types/stardust/block/payload/milestone/mod.rs", "rank": 27, "score": 129342.03759231679 }, { "content": "impl From<&bee::MilestoneOption> for MilestoneOption {\n\n fn from(value: &bee::MilestoneOption) -> Self {\n\n match value {\n\n bee::MilestoneOption::Receipt(r) => Self::Receipt {\n\n migrated_at: r.migrated_at().into(),\n\n last: r.last(),\n\n funds: r.funds().iter().map(Into::into).collect(),\n\n transaction: r.transaction().into(),\n\n },\n\n bee::MilestoneOption::Parameters(p) => Self::Parameters {\n\n target_milestone_index: p.target_milestone_index().into(),\n\n protocol_version: p.protocol_version(),\n\n binary_parameters: p.binary_parameters().to_owned().into_boxed_slice(),\n\n },\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<MilestoneOption> for bee::MilestoneOption {\n\n type Error = bee_block_stardust::Error;\n", "file_path": "src/types/stardust/block/payload/milestone/mod.rs", "rank": 28, "score": 129340.52913975384 }, { "content": " }\n\n\n\n pub(crate) fn get_test_ed25519_migrated_funds_entry() -> MigratedFundsEntry {\n\n MigratedFundsEntry::from(\n\n &bee::option::MigratedFundsEntry::new(\n\n bee::option::TailTransactionHash::new(TAIL_TRANSACTION_HASH1).unwrap(),\n\n bee_block_stardust::address::Address::Ed25519(bee_test::rand::address::rand_ed25519_address()),\n\n 2000000,\n\n )\n\n .unwrap(),\n\n )\n\n }\n\n\n\n pub(crate) fn get_test_alias_migrated_funds_entry() -> MigratedFundsEntry {\n\n MigratedFundsEntry::from(\n\n &bee::option::MigratedFundsEntry::new(\n\n bee::option::TailTransactionHash::new(TAIL_TRANSACTION_HASH2).unwrap(),\n\n bee_block_stardust::address::Address::Alias(bee_test::rand::address::rand_alias_address()),\n\n 2000000,\n\n )\n", "file_path": "src/types/stardust/block/payload/milestone/mod.rs", "rank": 29, "score": 129339.66311598828 }, { "content": "\n\n fn try_from(value: MilestoneOption) -> Result<Self, Self::Error> {\n\n Ok(match value {\n\n MilestoneOption::Receipt {\n\n migrated_at,\n\n last,\n\n funds,\n\n transaction,\n\n } => Self::Receipt(bee::ReceiptMilestoneOption::new(\n\n migrated_at.into(),\n\n last,\n\n Vec::from(funds)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n transaction.try_into()?,\n\n )?),\n\n MilestoneOption::Parameters {\n\n target_milestone_index,\n\n protocol_version,\n", "file_path": "src/types/stardust/block/payload/milestone/mod.rs", "rank": 30, "score": 129338.22106784781 }, { "content": " const TAIL_TRANSACTION_HASH_LENGTH: usize = bee::option::TailTransactionHash::LENGTH;\n\n}\n\n\n\nimpl From<&bee::option::MigratedFundsEntry> for MigratedFundsEntry {\n\n fn from(value: &bee::option::MigratedFundsEntry) -> Self {\n\n Self {\n\n // Unwrap: Should not fail as the length is defined by the struct\n\n tail_transaction_hash: value.tail_transaction_hash().as_ref().try_into().unwrap(),\n\n address: (*value.address()).into(),\n\n amount: value.amount(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<MigratedFundsEntry> for bee::option::MigratedFundsEntry {\n\n type Error = bee_block_stardust::Error;\n\n\n\n fn try_from(value: MigratedFundsEntry) -> Result<Self, Self::Error> {\n\n Self::new(\n\n bee::option::TailTransactionHash::new(value.tail_transaction_hash)?,\n", "file_path": "src/types/stardust/block/payload/milestone/mod.rs", "rank": 31, "score": 129336.41802715464 }, { "content": "#[allow(missing_docs)]\n\npub trait AsyncFn<'a, O> {\n\n type Output: 'a + Future<Output = O> + Send;\n\n fn call(self, cx: &'a mut RuntimeScope) -> Self::Output;\n\n}\n\nimpl<'a, Fn, Fut, O> AsyncFn<'a, O> for Fn\n\nwhere\n\n Fn: FnOnce(&'a mut RuntimeScope) -> Fut,\n\n Fut: 'a + Future<Output = O> + Send,\n\n{\n\n type Output = Fut;\n\n fn call(self, cx: &'a mut RuntimeScope) -> Self::Output {\n\n (self)(cx)\n\n }\n\n}\n\n\n\n/// Starting point for the runtime.\n\npub struct Runtime;\n\n\n\nimpl Runtime {\n\n /// Launches a new root runtime scope.\n", "file_path": "src/runtime/mod.rs", "rank": 32, "score": 114329.4486232494 }, { "content": "pub struct SpentMetadata {\n\n pub transaction_id: TransactionId,\n\n pub spent: MilestoneIndexTimestamp,\n\n}\n\n\n\n/// Block metadata.\n\n#[derive(Clone, Debug, Serialize, Deserialize)]\n\npub struct OutputMetadata {\n\n pub output_id: OutputId,\n\n pub block_id: BlockId,\n\n pub transaction_id: TransactionId,\n\n pub booked: MilestoneIndexTimestamp,\n\n pub spent: Option<SpentMetadata>,\n\n}\n\n\n\npub struct OutputWithMetadata {\n\n pub output: Output,\n\n pub metadata: OutputMetadata,\n\n}\n\n\n", "file_path": "src/types/ledger/output_metadata.rs", "rank": 33, "score": 103354.92735694497 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::types::{\n\n stardust::{\n\n block::{BlockId, Output, OutputId, TransactionId},\n\n milestone::MilestoneTimestamp,\n\n },\n\n tangle::MilestoneIndex,\n\n};\n\n\n\n#[derive(Clone, Debug, Serialize, Deserialize)]\n\npub struct MilestoneIndexTimestamp {\n\n pub milestone_index: MilestoneIndex,\n\n pub milestone_timestamp: MilestoneTimestamp,\n\n}\n\n\n\n#[derive(Clone, Debug, Serialize, Deserialize)]\n", "file_path": "src/types/ledger/output_metadata.rs", "rank": 34, "score": 103351.14616774209 }, { "content": "#[cfg(feature = \"inx\")]\n\nimpl From<inx::LedgerOutput> for OutputWithMetadata {\n\n fn from(value: inx::LedgerOutput) -> Self {\n\n let output_id = OutputId::from(value.output_id);\n\n let metadata = OutputMetadata {\n\n output_id,\n\n block_id: value.block_id.into(),\n\n transaction_id: output_id.transaction_id,\n\n booked: MilestoneIndexTimestamp {\n\n milestone_index: value.milestone_index_booked.into(),\n\n milestone_timestamp: value.milestone_timestamp_booked.into(),\n\n },\n\n spent: None,\n\n };\n\n Self {\n\n output: (&value.output).into(),\n\n metadata,\n\n }\n\n }\n\n}\n", "file_path": "src/types/ledger/output_metadata.rs", "rank": 35, "score": 103349.88685232421 }, { "content": "\n\n#[cfg(feature = \"inx\")]\n\nimpl From<inx::LedgerSpent> for OutputWithMetadata {\n\n fn from(value: inx::LedgerSpent) -> Self {\n\n let mut output_with_metadata = OutputWithMetadata::from(value.output);\n\n\n\n output_with_metadata.metadata.spent = Some(SpentMetadata {\n\n transaction_id: value.transaction_id_spent.into(),\n\n spent: MilestoneIndexTimestamp {\n\n milestone_index: value.milestone_index_spent.into(),\n\n milestone_timestamp: value.milestone_timestamp_spent.into(),\n\n },\n\n });\n\n\n\n output_with_metadata\n\n }\n\n}\n", "file_path": "src/types/ledger/output_metadata.rs", "rank": 36, "score": 103346.91862958245 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::{ConflictReason, LedgerInclusionState};\n\nuse crate::types::{stardust::block::BlockId, tangle::MilestoneIndex};\n\n\n\n/// Block metadata.\n\n#[derive(Clone, Debug, Serialize, Deserialize)]\n\npub struct BlockMetadata {\n\n /// The id of the corresponding block.\n\n pub block_id: BlockId,\n\n /// The parents of the corresponding block.\n\n pub parents: Box<[BlockId]>,\n\n /// Status of the solidification process.\n\n pub is_solid: bool,\n\n /// Indicates that the block should be promoted.\n\n pub should_promote: bool,\n\n /// Indicates that the block should be reattached.\n", "file_path": "src/types/ledger/block_metadata.rs", "rank": 37, "score": 100939.79969603356 }, { "content": " pub should_reattach: bool,\n\n /// The milestone index referencing the block.\n\n pub referenced_by_milestone_index: MilestoneIndex,\n\n /// The corresponding milestone index.\n\n pub milestone_index: MilestoneIndex,\n\n /// The inclusion state of the block.\n\n pub inclusion_state: LedgerInclusionState,\n\n /// If the ledger inclusion state is conflicting, the reason for the conflict.\n\n pub conflict_reason: ConflictReason,\n\n}\n\n\n\n#[cfg(feature = \"inx\")]\n\nimpl From<inx::BlockMetadata> for BlockMetadata {\n\n fn from(metadata: inx::BlockMetadata) -> Self {\n\n Self {\n\n block_id: metadata.block_id.into(),\n\n parents: metadata.parents.into_iter().map(|id| id.into()).collect(),\n\n is_solid: metadata.is_solid,\n\n should_promote: metadata.should_promote,\n\n should_reattach: metadata.should_reattach,\n\n referenced_by_milestone_index: metadata.referenced_by_milestone_index.into(),\n\n milestone_index: metadata.milestone_index.into(),\n\n inclusion_state: metadata.ledger_inclusion_state.into(),\n\n conflict_reason: metadata.conflict_reason.into(),\n\n }\n\n }\n\n}\n", "file_path": "src/types/ledger/block_metadata.rs", "rank": 38, "score": 100938.44387855426 }, { "content": "/// Spawn a tokio task. The provided name will be used to configure the task if console tracing is enabled.\n\npub fn spawn_task<F>(name: &str, task: F) -> tokio::task::JoinHandle<F::Output>\n\nwhere\n\n F: 'static + Future + Send,\n\n F::Output: 'static + Send,\n\n{\n\n log::trace!(\"Spawning task {}\", name);\n\n #[cfg(all(tokio_unstable, feature = \"console\"))]\n\n return tokio::task::Builder::new().name(name).spawn(task);\n\n #[cfg(not(all(tokio_unstable, feature = \"console\")))]\n\n return tokio::spawn(task);\n\n}\n", "file_path": "src/runtime/mod.rs", "rank": 39, "score": 99117.31356198348 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::payload as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nmod milestone;\n\nmod tagged_data;\n\nmod transaction;\n\nmod treasury_transaction;\n\n\n\npub use self::{\n\n milestone::{MilestoneEssence, MilestoneId, MilestoneOption, MilestonePayload},\n\n tagged_data::TaggedDataPayload,\n\n transaction::{TransactionEssence, TransactionId, TransactionPayload},\n\n treasury_transaction::TreasuryTransactionPayload,\n\n};\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(tag = \"kind\")]\n", "file_path": "src/types/stardust/block/payload/mod.rs", "rank": 40, "score": 97747.76516629719 }, { "content": "}\n\n\n\nimpl TryFrom<Payload> for bee::Payload {\n\n type Error = bee_block_stardust::Error;\n\n\n\n fn try_from(value: Payload) -> Result<Self, Self::Error> {\n\n Ok(match value {\n\n Payload::Transaction(p) => bee::Payload::Transaction(Box::new((*p).try_into()?)),\n\n Payload::Milestone(p) => bee::Payload::Milestone(Box::new((*p).try_into()?)),\n\n Payload::TreasuryTransaction(p) => bee::Payload::TreasuryTransaction(Box::new((*p).try_into()?)),\n\n Payload::TaggedData(p) => bee::Payload::TaggedData(Box::new((*p).try_into()?)),\n\n })\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n\n use super::{milestone, tagged_data, transaction, treasury_transaction, *};\n", "file_path": "src/types/stardust/block/payload/mod.rs", "rank": 41, "score": 97746.7027412807 }, { "content": " pub(crate) fn get_test_transaction_payload() -> Payload {\n\n Payload::Transaction(Box::new(transaction::test::get_test_transaction_payload()))\n\n }\n\n\n\n pub(crate) fn get_test_milestone_payload() -> Payload {\n\n Payload::Milestone(Box::new(milestone::test::get_test_milestone_payload()))\n\n }\n\n\n\n pub(crate) fn get_test_treasury_transaction_payload() -> Payload {\n\n Payload::TreasuryTransaction(Box::new(\n\n treasury_transaction::test::get_test_treasury_transaction_payload(),\n\n ))\n\n }\n\n\n\n pub(crate) fn get_test_tagged_data_payload() -> Payload {\n\n Payload::TaggedData(Box::new(tagged_data::test::get_test_tagged_data_payload()))\n\n }\n\n}\n", "file_path": "src/types/stardust/block/payload/mod.rs", "rank": 42, "score": 97742.93375341487 }, { "content": "pub enum Payload {\n\n #[serde(rename = \"transaction\")]\n\n Transaction(Box<TransactionPayload>),\n\n #[serde(rename = \"milestone\")]\n\n Milestone(Box<MilestonePayload>),\n\n #[serde(rename = \"treasury_transaction\")]\n\n TreasuryTransaction(Box<TreasuryTransactionPayload>),\n\n #[serde(rename = \"tagged_data\")]\n\n TaggedData(Box<TaggedDataPayload>),\n\n}\n\n\n\nimpl From<&bee::Payload> for Payload {\n\n fn from(value: &bee::Payload) -> Self {\n\n match value {\n\n bee::Payload::Transaction(p) => Self::Transaction(Box::new(p.as_ref().into())),\n\n bee::Payload::Milestone(p) => Self::Milestone(Box::new(p.as_ref().into())),\n\n bee::Payload::TreasuryTransaction(p) => Self::TreasuryTransaction(Box::new(p.as_ref().into())),\n\n bee::Payload::TaggedData(p) => Self::TaggedData(Box::new(p.as_ref().into())),\n\n }\n\n }\n", "file_path": "src/types/stardust/block/payload/mod.rs", "rank": 43, "score": 97741.42557414039 }, { "content": "\n\n #[test]\n\n fn test_payload_bson() {\n\n let payload = get_test_transaction_payload();\n\n let bson = to_bson(&payload).unwrap();\n\n assert_eq!(payload, from_bson::<Payload>(bson).unwrap());\n\n\n\n let payload = get_test_milestone_payload();\n\n let bson = to_bson(&payload).unwrap();\n\n assert_eq!(payload, from_bson::<Payload>(bson).unwrap());\n\n\n\n let payload = get_test_treasury_transaction_payload();\n\n let bson = to_bson(&payload).unwrap();\n\n assert_eq!(payload, from_bson::<Payload>(bson).unwrap());\n\n\n\n let payload = get_test_tagged_data_payload();\n\n let bson = to_bson(&payload).unwrap();\n\n assert_eq!(payload, from_bson::<Payload>(bson).unwrap());\n\n }\n\n\n", "file_path": "src/types/stardust/block/payload/mod.rs", "rank": 44, "score": 97736.38158374898 }, { "content": "pub use self::{\n\n alias::{AliasId, AliasOutput},\n\n basic::BasicOutput,\n\n feature::Feature,\n\n foundry::FoundryOutput,\n\n native_token::{NativeToken, TokenScheme},\n\n nft::{NftId, NftOutput},\n\n treasury::TreasuryOutput,\n\n unlock_condition::UnlockCondition,\n\n};\n\nuse super::Address;\n\nuse crate::types::stardust::block::TransactionId;\n\n\n\npub type OutputAmount = u64;\n\npub type OutputIndex = u16;\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct OutputId {\n\n pub transaction_id: TransactionId,\n\n pub index: OutputIndex,\n", "file_path": "src/types/stardust/block/output/mod.rs", "rank": 45, "score": 96955.51244849453 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::output::feature as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::types::stardust::block::Address;\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(tag = \"kind\")]\n\npub enum Feature {\n\n #[serde(rename = \"sender\")]\n\n Sender { address: Address },\n\n #[serde(rename = \"issuer\")]\n\n Issuer { address: Address },\n\n #[serde(rename = \"metadata\")]\n\n Metadata {\n\n #[serde(with = \"serde_bytes\")]\n\n data: Box<[u8]>,\n\n },\n", "file_path": "src/types/stardust/block/output/feature.rs", "rank": 46, "score": 96955.43962970749 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse std::str::FromStr;\n\n\n\nuse bee_block_stardust::output as bee;\n\nuse mongodb::bson::{spec::BinarySubtype, Binary, Bson};\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::{Feature, NativeToken, OutputAmount, UnlockCondition};\n\nuse crate::types::util::bytify;\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(transparent)]\n\npub struct NftId(#[serde(with = \"bytify\")] pub [u8; Self::LENGTH]);\n\n\n\nimpl NftId {\n\n const LENGTH: usize = bee::NftId::LENGTH;\n\n\n\n pub fn from_output_id_str(s: &str) -> Result<Self, bee_block_stardust::Error> {\n", "file_path": "src/types/stardust/block/output/nft.rs", "rank": 47, "score": 96953.5296143417 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse std::str::FromStr;\n\n\n\nuse bee_block_stardust::output as bee;\n\nuse mongodb::bson::{spec::BinarySubtype, Binary, Bson};\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::{feature::Feature, native_token::NativeToken, unlock_condition::UnlockCondition, OutputAmount};\n\nuse crate::types::util::bytify;\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(transparent)]\n\npub struct AliasId(#[serde(with = \"bytify\")] pub [u8; Self::LENGTH]);\n\n\n\nimpl AliasId {\n\n const LENGTH: usize = bee::AliasId::LENGTH;\n\n\n\n pub fn from_output_id_str(s: &str) -> Result<Self, bee_block_stardust::Error> {\n", "file_path": "src/types/stardust/block/output/alias.rs", "rank": 48, "score": 96953.26400668887 }, { "content": " .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )\n\n .finish()\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n\n use super::*;\n\n use crate::types::stardust::block::output::{\n\n feature::test::get_test_metadata_block,\n\n native_token::test::get_test_native_token,\n\n unlock_condition::test::{get_test_alias_address_as_address, get_test_immut_alias_address_condition},\n\n };\n\n\n\n #[test]\n", "file_path": "src/types/stardust/block/output/foundry.rs", "rank": 49, "score": 96952.11374456997 }, { "content": " use crate::types::stardust::block::output::{\n\n feature::test::{get_test_metadata_block, get_test_sender_block, get_test_tag_block},\n\n native_token::test::get_test_native_token,\n\n unlock_condition::test::{\n\n get_test_address_condition, get_test_expiration_condition, get_test_storage_deposit_return_condition,\n\n get_test_timelock_condition,\n\n },\n\n };\n\n\n\n #[test]\n\n fn test_basic_output_bson() {\n\n let output = get_test_basic_output();\n\n let bson = to_bson(&output).unwrap();\n\n assert_eq!(output, from_bson::<BasicOutput>(bson).unwrap());\n\n }\n\n\n\n pub(crate) fn get_test_basic_output() -> BasicOutput {\n\n BasicOutput::from(\n\n &bee::BasicOutput::build_with_amount(100)\n\n .unwrap()\n", "file_path": "src/types/stardust/block/output/basic.rs", "rank": 50, "score": 96951.86005502268 }, { "content": " .with_immutable_features(\n\n Vec::from(value.immutable_features)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )\n\n .finish()\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n\n use super::*;\n\n use crate::types::stardust::block::output::{\n\n feature::test::{get_test_issuer_block, get_test_metadata_block, get_test_sender_block, get_test_tag_block},\n\n native_token::test::get_test_native_token,\n\n unlock_condition::test::{\n\n get_test_address_condition, get_test_expiration_condition, get_test_storage_deposit_return_condition,\n", "file_path": "src/types/stardust/block/output/nft.rs", "rank": 51, "score": 96951.63389101074 }, { "content": "\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n\n use super::*;\n\n use crate::types::stardust::block::output::{\n\n feature::test::{get_test_issuer_block, get_test_metadata_block, get_test_sender_block},\n\n native_token::test::get_test_native_token,\n\n unlock_condition::test::{get_test_governor_address_condition, get_test_state_controller_address_condition},\n\n };\n\n\n\n #[test]\n\n fn test_alias_id_bson() {\n\n let alias_id = AliasId::from(bee_test::rand::output::rand_alias_id());\n\n let bson = to_bson(&alias_id).unwrap();\n\n assert_eq!(Bson::from(alias_id), bson);\n\n assert_eq!(alias_id, from_bson::<AliasId>(bson).unwrap());\n\n }\n\n\n", "file_path": "src/types/stardust/block/output/alias.rs", "rank": 52, "score": 96951.44045329442 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::output as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::{Feature, NativeToken, OutputAmount, UnlockCondition};\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct BasicOutput {\n\n #[serde(with = \"crate::types::util::stringify\")]\n\n pub amount: OutputAmount,\n\n pub native_tokens: Box<[NativeToken]>,\n\n pub unlock_conditions: Box<[UnlockCondition]>,\n\n pub features: Box<[Feature]>,\n\n}\n\n\n\nimpl From<&bee::BasicOutput> for BasicOutput {\n\n fn from(value: &bee::BasicOutput) -> Self {\n\n Self {\n", "file_path": "src/types/stardust/block/output/basic.rs", "rank": 53, "score": 96951.16841045592 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::output as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse super::{Feature, NativeToken, OutputAmount, TokenScheme, UnlockCondition};\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct FoundryOutput {\n\n #[serde(with = \"crate::types::util::stringify\")]\n\n pub amount: OutputAmount,\n\n pub native_tokens: Box<[NativeToken]>,\n\n #[serde(with = \"crate::types::util::stringify\")]\n\n pub serial_number: u32,\n\n pub token_scheme: TokenScheme,\n\n pub unlock_conditions: Box<[UnlockCondition]>,\n\n pub features: Box<[Feature]>,\n\n pub immutable_features: Box<[Feature]>,\n\n}\n", "file_path": "src/types/stardust/block/output/foundry.rs", "rank": 54, "score": 96950.68784180892 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::output as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct TreasuryOutput {\n\n #[serde(with = \"crate::types::util::stringify\")]\n\n amount: u64,\n\n}\n\n\n\nimpl From<&bee::TreasuryOutput> for TreasuryOutput {\n\n fn from(value: &bee::TreasuryOutput) -> Self {\n\n Self { amount: value.amount() }\n\n }\n\n}\n\n\n\nimpl TryFrom<TreasuryOutput> for bee::TreasuryOutput {\n\n type Error = bee_block_stardust::Error;\n", "file_path": "src/types/stardust/block/output/treasury.rs", "rank": 55, "score": 96950.39550187178 }, { "content": " pub state_index: u32,\n\n #[serde(with = \"serde_bytes\")]\n\n pub state_metadata: Box<[u8]>,\n\n pub foundry_counter: u32,\n\n pub unlock_conditions: Box<[UnlockCondition]>,\n\n pub features: Box<[Feature]>,\n\n pub immutable_features: Box<[Feature]>,\n\n}\n\n\n\nimpl From<&bee::AliasOutput> for AliasOutput {\n\n fn from(value: &bee::AliasOutput) -> Self {\n\n Self {\n\n amount: value.amount(),\n\n native_tokens: value.native_tokens().iter().map(Into::into).collect(),\n\n alias_id: (*value.alias_id()).into(),\n\n state_index: value.state_index(),\n\n state_metadata: value.state_metadata().to_vec().into_boxed_slice(),\n\n foundry_counter: value.foundry_counter(),\n\n unlock_conditions: value.unlock_conditions().iter().map(Into::into).collect(),\n\n features: value.features().iter().map(Into::into).collect(),\n", "file_path": "src/types/stardust/block/output/alias.rs", "rank": 56, "score": 96950.08191236915 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nmod feature;\n\nmod native_token;\n\nmod unlock_condition;\n\n\n\n// The different output types\n\nmod alias;\n\nmod basic;\n\nmod foundry;\n\nmod nft;\n\npub(crate) mod treasury;\n\n\n\nuse std::str::FromStr;\n\n\n\nuse bee_block_stardust::output as bee;\n\nuse mongodb::bson::{doc, Bson};\n\nuse serde::{Deserialize, Serialize};\n\n\n", "file_path": "src/types/stardust/block/output/mod.rs", "rank": 57, "score": 96949.94756166391 }, { "content": " fn test_foundry_output_bson() {\n\n let output = get_test_foundry_output();\n\n let bson = to_bson(&output).unwrap();\n\n assert_eq!(output, from_bson::<FoundryOutput>(bson).unwrap());\n\n }\n\n\n\n pub(crate) fn get_test_foundry_output() -> FoundryOutput {\n\n FoundryOutput::from(\n\n &bee::FoundryOutput::build_with_amount(\n\n 100,\n\n bee_test::rand::number::rand_number(),\n\n bee::TokenScheme::Simple(bee::SimpleTokenScheme::new(250.into(), 200.into(), 300.into()).unwrap()),\n\n )\n\n .unwrap()\n\n .with_native_tokens(vec![get_test_native_token().try_into().unwrap()])\n\n .with_unlock_conditions(vec![\n\n get_test_immut_alias_address_condition(get_test_alias_address_as_address())\n\n .try_into()\n\n .unwrap(),\n\n ])\n\n .with_features(vec![get_test_metadata_block().try_into().unwrap()])\n\n .with_immutable_features(vec![get_test_metadata_block().try_into().unwrap()])\n\n .finish()\n\n .unwrap(),\n\n )\n\n }\n\n}\n", "file_path": "src/types/stardust/block/output/foundry.rs", "rank": 58, "score": 96949.39217722006 }, { "content": "pub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn test_feature_bson() {\n\n let block = get_test_sender_block(bee_test::rand::address::rand_address().into());\n\n let bson = to_bson(&block).unwrap();\n\n assert_eq!(block, from_bson::<Feature>(bson).unwrap());\n\n\n\n let block = get_test_issuer_block(bee_test::rand::address::rand_address().into());\n\n let bson = to_bson(&block).unwrap();\n\n assert_eq!(block, from_bson::<Feature>(bson).unwrap());\n\n\n\n let block = get_test_metadata_block();\n\n let bson = to_bson(&block).unwrap();\n\n assert_eq!(block, from_bson::<Feature>(bson).unwrap());\n\n\n\n let block = get_test_tag_block();\n", "file_path": "src/types/stardust/block/output/feature.rs", "rank": 59, "score": 96949.0296664848 }, { "content": " let bson = to_bson(&block).unwrap();\n\n assert_eq!(block, from_bson::<Feature>(bson).unwrap());\n\n }\n\n\n\n pub(crate) fn get_test_sender_block(address: Address) -> Feature {\n\n Feature::Sender { address }\n\n }\n\n\n\n pub(crate) fn get_test_issuer_block(address: Address) -> Feature {\n\n Feature::Issuer { address }\n\n }\n\n\n\n pub(crate) fn get_test_metadata_block() -> Feature {\n\n Feature::Metadata {\n\n data: \"Foo\".as_bytes().to_vec().into_boxed_slice(),\n\n }\n\n }\n\n\n\n pub(crate) fn get_test_tag_block() -> Feature {\n\n Feature::Tag {\n\n data: \"Bar\".as_bytes().to_vec().into_boxed_slice(),\n\n }\n\n }\n\n}\n", "file_path": "src/types/stardust/block/output/feature.rs", "rank": 60, "score": 96948.26689028397 }, { "content": "}\n\n\n\nimpl From<bee::OutputId> for OutputId {\n\n fn from(value: bee::OutputId) -> Self {\n\n Self {\n\n transaction_id: (*value.transaction_id()).into(),\n\n index: value.index(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<OutputId> for bee::OutputId {\n\n type Error = bee_block_stardust::Error;\n\n\n\n fn try_from(value: OutputId) -> Result<Self, Self::Error> {\n\n bee::OutputId::new(value.transaction_id.into(), value.index)\n\n }\n\n}\n\n\n\nimpl FromStr for OutputId {\n", "file_path": "src/types/stardust/block/output/mod.rs", "rank": 61, "score": 96948.2397301242 }, { "content": "\n\n fn try_from(value: TreasuryOutput) -> Result<Self, Self::Error> {\n\n Self::new(value.amount)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn test_treasury_output_bson() {\n\n let output = TreasuryOutput::from(&bee_test::rand::output::rand_treasury_output());\n\n let bson = to_bson(&output).unwrap();\n\n assert_eq!(output, from_bson::<TreasuryOutput>(bson).unwrap());\n\n }\n\n}\n", "file_path": "src/types/stardust/block/output/treasury.rs", "rank": 62, "score": 96947.52891419535 }, { "content": " fn try_from(value: Output) -> Result<Self, Self::Error> {\n\n Ok(match value {\n\n Output::Treasury(o) => bee::Output::Treasury(o.try_into()?),\n\n Output::Basic(o) => bee::Output::Basic(o.try_into()?),\n\n Output::Alias(o) => bee::Output::Alias(o.try_into()?),\n\n Output::Foundry(o) => bee::Output::Foundry(o.try_into()?),\n\n Output::Nft(o) => bee::Output::Nft(o.try_into()?),\n\n })\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n\n use super::{alias, basic, foundry, nft, *};\n\n\n\n #[test]\n\n fn test_output_id_bson() {\n\n let output_id = OutputId::from(bee_test::rand::output::rand_output_id());\n", "file_path": "src/types/stardust/block/output/mod.rs", "rank": 63, "score": 96947.20948343718 }, { "content": " immutable_features: value.immutable_features().iter().map(Into::into).collect(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<AliasOutput> for bee::AliasOutput {\n\n type Error = bee_block_stardust::Error;\n\n\n\n fn try_from(value: AliasOutput) -> Result<Self, Self::Error> {\n\n Self::build_with_amount(value.amount, value.alias_id.into())?\n\n .with_native_tokens(\n\n Vec::from(value.native_tokens)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )\n\n .with_state_index(value.state_index)\n\n .with_state_metadata(value.state_metadata.into())\n\n .with_foundry_counter(value.foundry_counter)\n\n .with_unlock_conditions(\n", "file_path": "src/types/stardust/block/output/alias.rs", "rank": 64, "score": 96946.52582661774 }, { "content": " pub features: Box<[Feature]>,\n\n pub immutable_features: Box<[Feature]>,\n\n}\n\n\n\nimpl From<&bee::NftOutput> for NftOutput {\n\n fn from(value: &bee::NftOutput) -> Self {\n\n Self {\n\n amount: value.amount(),\n\n native_tokens: value.native_tokens().iter().map(Into::into).collect(),\n\n nft_id: (*value.nft_id()).into(),\n\n unlock_conditions: value.unlock_conditions().iter().map(Into::into).collect(),\n\n features: value.features().iter().map(Into::into).collect(),\n\n immutable_features: value.immutable_features().iter().map(Into::into).collect(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<NftOutput> for bee::NftOutput {\n\n type Error = bee_block_stardust::Error;\n\n\n", "file_path": "src/types/stardust/block/output/nft.rs", "rank": 65, "score": 96946.25832120834 }, { "content": " type Err = bee_block_stardust::Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n Ok(bee::OutputId::from_str(s)?.into())\n\n }\n\n}\n\n\n\nimpl From<OutputId> for Bson {\n\n fn from(val: OutputId) -> Self {\n\n // Unwrap: Cannot fail as type is well defined\n\n mongodb::bson::to_bson(&val).unwrap()\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(tag = \"kind\")]\n\npub enum Output {\n\n #[serde(rename = \"treasury\")]\n\n Treasury(TreasuryOutput),\n\n #[serde(rename = \"basic\")]\n", "file_path": "src/types/stardust/block/output/mod.rs", "rank": 66, "score": 96946.0531068816 }, { "content": " #[test]\n\n fn test_alias_output_bson() {\n\n let output = get_test_alias_output();\n\n let bson = to_bson(&output).unwrap();\n\n assert_eq!(output, from_bson::<AliasOutput>(bson).unwrap());\n\n }\n\n\n\n pub(crate) fn get_test_alias_output() -> AliasOutput {\n\n AliasOutput::from(\n\n &bee::AliasOutput::build_with_amount(100, bee_test::rand::output::rand_alias_id())\n\n .unwrap()\n\n .with_native_tokens(vec![get_test_native_token().try_into().unwrap()])\n\n .with_state_index(0)\n\n .with_state_metadata(\"Foo\".as_bytes().to_vec())\n\n .with_foundry_counter(0)\n\n .with_unlock_conditions(vec![\n\n get_test_state_controller_address_condition(bee_test::rand::address::rand_address().into())\n\n .try_into()\n\n .unwrap(),\n\n get_test_governor_address_condition(bee_test::rand::address::rand_address().into())\n", "file_path": "src/types/stardust/block/output/alias.rs", "rank": 67, "score": 96945.56570078425 }, { "content": " assert_eq!(output, from_bson::<Output>(bson).unwrap());\n\n\n\n let output = Output::from(&bee::Output::Treasury(bee_test::rand::output::rand_treasury_output()));\n\n let bson = to_bson(&output).unwrap();\n\n assert_eq!(output, from_bson::<Output>(bson).unwrap());\n\n }\n\n\n\n pub(crate) fn get_test_alias_output() -> Output {\n\n Output::Alias(alias::test::get_test_alias_output())\n\n }\n\n\n\n pub(crate) fn get_test_basic_output() -> Output {\n\n Output::Basic(basic::test::get_test_basic_output())\n\n }\n\n\n\n pub(crate) fn get_test_foundry_output() -> Output {\n\n Output::Foundry(foundry::test::get_test_foundry_output())\n\n }\n\n\n\n pub(crate) fn get_test_nft_output() -> Output {\n\n Output::Nft(nft::test::get_test_nft_output())\n\n }\n\n}\n", "file_path": "src/types/stardust/block/output/mod.rs", "rank": 68, "score": 96945.18269741761 }, { "content": " .with_features(vec![\n\n get_test_sender_block(bee_test::rand::address::rand_address().into())\n\n .try_into()\n\n .unwrap(),\n\n get_test_metadata_block().try_into().unwrap(),\n\n get_test_tag_block().try_into().unwrap(),\n\n ])\n\n .with_immutable_features(vec![\n\n get_test_issuer_block(bee_test::rand::address::rand_address().into())\n\n .try_into()\n\n .unwrap(),\n\n get_test_metadata_block().try_into().unwrap(),\n\n ])\n\n .finish()\n\n .unwrap(),\n\n )\n\n }\n\n}\n", "file_path": "src/types/stardust/block/output/nft.rs", "rank": 69, "score": 96944.89703433243 }, { "content": " .try_into()\n\n .unwrap(),\n\n ])\n\n .with_features(vec![\n\n get_test_sender_block(bee_test::rand::address::rand_address().into())\n\n .try_into()\n\n .unwrap(),\n\n get_test_metadata_block().try_into().unwrap(),\n\n ])\n\n .with_immutable_features(vec![\n\n get_test_issuer_block(bee_test::rand::address::rand_address().into())\n\n .try_into()\n\n .unwrap(),\n\n get_test_metadata_block().try_into().unwrap(),\n\n ])\n\n .finish()\n\n .unwrap(),\n\n )\n\n }\n\n}\n", "file_path": "src/types/stardust/block/output/alias.rs", "rank": 70, "score": 96944.85466524334 }, { "content": " .collect(),\n\n }\n\n }\n\n}\n\n\n\nimpl From<&bee::Output> for Output {\n\n fn from(value: &bee::Output) -> Self {\n\n match value {\n\n bee::Output::Treasury(o) => Self::Treasury(o.into()),\n\n bee::Output::Basic(o) => Self::Basic(o.into()),\n\n bee::Output::Alias(o) => Self::Alias(o.into()),\n\n bee::Output::Foundry(o) => Self::Foundry(o.into()),\n\n bee::Output::Nft(o) => Self::Nft(o.into()),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<Output> for bee::Output {\n\n type Error = bee_block_stardust::Error;\n\n\n", "file_path": "src/types/stardust/block/output/mod.rs", "rank": 71, "score": 96944.27512381315 }, { "content": " Ok(bee::NftId::from_str(s)?.into())\n\n }\n\n}\n\n\n\nimpl From<NftId> for Bson {\n\n fn from(val: NftId) -> Self {\n\n Binary {\n\n subtype: BinarySubtype::Generic,\n\n bytes: val.0.to_vec(),\n\n }\n\n .into()\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct NftOutput {\n\n pub amount: OutputAmount,\n\n pub native_tokens: Box<[NativeToken]>,\n\n pub nft_id: NftId,\n\n pub unlock_conditions: Box<[UnlockCondition]>,\n", "file_path": "src/types/stardust/block/output/nft.rs", "rank": 72, "score": 96944.1701970994 }, { "content": " Ok(bee::AliasId::from_str(s)?.into())\n\n }\n\n}\n\n\n\nimpl From<AliasId> for Bson {\n\n fn from(val: AliasId) -> Self {\n\n Binary {\n\n subtype: BinarySubtype::Generic,\n\n bytes: val.0.to_vec(),\n\n }\n\n .into()\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct AliasOutput {\n\n #[serde(with = \"crate::types::util::stringify\")]\n\n pub amount: OutputAmount,\n\n pub native_tokens: Box<[NativeToken]>,\n\n pub alias_id: AliasId,\n", "file_path": "src/types/stardust/block/output/alias.rs", "rank": 73, "score": 96944.0625751737 }, { "content": " Basic(BasicOutput),\n\n #[serde(rename = \"alias\")]\n\n Alias(AliasOutput),\n\n #[serde(rename = \"foundry\")]\n\n Foundry(FoundryOutput),\n\n #[serde(rename = \"nft\")]\n\n Nft(NftOutput),\n\n}\n\n\n\nimpl Output {\n\n pub fn owning_addresses(&self) -> Vec<Address> {\n\n match self {\n\n Self::Treasury(_) => Vec::new(),\n\n Self::Basic(BasicOutput { unlock_conditions, .. })\n\n | Self::Alias(AliasOutput { unlock_conditions, .. })\n\n | Self::Nft(NftOutput { unlock_conditions, .. })\n\n | Self::Foundry(FoundryOutput { unlock_conditions, .. }) => unlock_conditions\n\n .iter()\n\n .filter_map(UnlockCondition::owning_address)\n\n .cloned()\n", "file_path": "src/types/stardust/block/output/mod.rs", "rank": 74, "score": 96943.5370137277 }, { "content": " get_test_timelock_condition,\n\n },\n\n };\n\n\n\n #[test]\n\n fn test_nft_id_bson() {\n\n let nft_id = NftId::from(rand_nft_id());\n\n let bson = to_bson(&nft_id).unwrap();\n\n assert_eq!(Bson::from(nft_id), bson);\n\n assert_eq!(nft_id, from_bson::<NftId>(bson).unwrap());\n\n }\n\n\n\n #[test]\n\n fn test_nft_output_bson() {\n\n let output = get_test_nft_output();\n\n let bson = to_bson(&output).unwrap();\n\n assert_eq!(output, from_bson::<NftOutput>(bson).unwrap());\n\n }\n\n\n\n pub(crate) fn rand_nft_id() -> bee::NftId {\n", "file_path": "src/types/stardust/block/output/nft.rs", "rank": 75, "score": 96943.29631065803 }, { "content": " #[serde(rename = \"tag\")]\n\n Tag {\n\n #[serde(with = \"serde_bytes\")]\n\n data: Box<[u8]>,\n\n },\n\n}\n\n\n\nimpl From<&bee::Feature> for Feature {\n\n fn from(value: &bee::Feature) -> Self {\n\n match value {\n\n bee::Feature::Sender(a) => Self::Sender {\n\n address: (*a.address()).into(),\n\n },\n\n bee::Feature::Issuer(a) => Self::Issuer {\n\n address: (*a.address()).into(),\n\n },\n\n bee::Feature::Metadata(b) => Self::Metadata {\n\n data: b.data().to_vec().into_boxed_slice(),\n\n },\n\n bee::Feature::Tag(b) => Self::Tag {\n", "file_path": "src/types/stardust/block/output/feature.rs", "rank": 76, "score": 96943.23703248106 }, { "content": " Vec::from(value.unlock_conditions)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )\n\n .with_features(\n\n Vec::from(value.features)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )\n\n .finish()\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n\n use super::*;\n", "file_path": "src/types/stardust/block/output/basic.rs", "rank": 77, "score": 96943.19217474507 }, { "content": "\n\nimpl From<&bee::FoundryOutput> for FoundryOutput {\n\n fn from(value: &bee::FoundryOutput) -> Self {\n\n Self {\n\n amount: value.amount(),\n\n native_tokens: value.native_tokens().iter().map(Into::into).collect(),\n\n serial_number: value.serial_number(),\n\n token_scheme: value.token_scheme().into(),\n\n unlock_conditions: value.unlock_conditions().iter().map(Into::into).collect(),\n\n features: value.features().iter().map(Into::into).collect(),\n\n immutable_features: value.immutable_features().iter().map(Into::into).collect(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<FoundryOutput> for bee::FoundryOutput {\n\n type Error = bee_block_stardust::Error;\n\n\n\n fn try_from(value: FoundryOutput) -> Result<Self, Self::Error> {\n\n Self::build_with_amount(value.amount, value.serial_number, value.token_scheme.try_into()?)?\n", "file_path": "src/types/stardust/block/output/foundry.rs", "rank": 78, "score": 96943.10331984657 }, { "content": " amount: value.amount(),\n\n native_tokens: value.native_tokens().iter().map(Into::into).collect(),\n\n unlock_conditions: value.unlock_conditions().iter().map(Into::into).collect(),\n\n features: value.features().iter().map(Into::into).collect(),\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<BasicOutput> for bee::BasicOutput {\n\n type Error = bee_block_stardust::Error;\n\n\n\n fn try_from(value: BasicOutput) -> Result<Self, Self::Error> {\n\n Self::build_with_amount(value.amount)?\n\n .with_native_tokens(\n\n Vec::from(value.native_tokens)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )\n\n .with_unlock_conditions(\n", "file_path": "src/types/stardust/block/output/basic.rs", "rank": 79, "score": 96942.95324415744 }, { "content": " data: b.tag().to_vec().into_boxed_slice(),\n\n },\n\n }\n\n }\n\n}\n\n\n\nimpl TryFrom<Feature> for bee::Feature {\n\n type Error = bee_block_stardust::Error;\n\n\n\n fn try_from(value: Feature) -> Result<Self, Self::Error> {\n\n Ok(match value {\n\n Feature::Sender { address } => bee::Feature::Sender(bee::SenderFeature::new(address.into())),\n\n Feature::Issuer { address } => bee::Feature::Issuer(bee::IssuerFeature::new(address.into())),\n\n Feature::Metadata { data } => bee::Feature::Metadata(bee::MetadataFeature::new(data.into())?),\n\n Feature::Tag { data } => bee::Feature::Tag(bee::TagFeature::new(data.into())?),\n\n })\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/types/stardust/block/output/feature.rs", "rank": 80, "score": 96942.8785826638 }, { "content": " bee_test::rand::bytes::rand_bytes_array().into()\n\n }\n\n\n\n pub(crate) fn get_test_nft_output() -> NftOutput {\n\n NftOutput::from(\n\n &bee::NftOutput::build_with_amount(100, rand_nft_id())\n\n .unwrap()\n\n .with_native_tokens(vec![get_test_native_token().try_into().unwrap()])\n\n .with_unlock_conditions(vec![\n\n get_test_address_condition(bee_test::rand::address::rand_address().into())\n\n .try_into()\n\n .unwrap(),\n\n get_test_storage_deposit_return_condition(bee_test::rand::address::rand_address().into(), 1)\n\n .try_into()\n\n .unwrap(),\n\n get_test_timelock_condition(1, 1).try_into().unwrap(),\n\n get_test_expiration_condition(bee_test::rand::address::rand_address().into(), 1, 1)\n\n .try_into()\n\n .unwrap(),\n\n ])\n", "file_path": "src/types/stardust/block/output/nft.rs", "rank": 81, "score": 96942.70116867073 }, { "content": " .with_native_tokens(vec![get_test_native_token().try_into().unwrap()])\n\n .with_unlock_conditions(vec![\n\n get_test_address_condition(bee_test::rand::address::rand_address().into())\n\n .try_into()\n\n .unwrap(),\n\n get_test_storage_deposit_return_condition(bee_test::rand::address::rand_address().into(), 1)\n\n .try_into()\n\n .unwrap(),\n\n get_test_timelock_condition(1, 1).try_into().unwrap(),\n\n get_test_expiration_condition(bee_test::rand::address::rand_address().into(), 1, 1)\n\n .try_into()\n\n .unwrap(),\n\n ])\n\n .with_features(vec![\n\n get_test_sender_block(bee_test::rand::address::rand_address().into())\n\n .try_into()\n\n .unwrap(),\n\n get_test_metadata_block().try_into().unwrap(),\n\n get_test_tag_block().try_into().unwrap(),\n\n ])\n\n .finish()\n\n .unwrap(),\n\n )\n\n }\n\n}\n", "file_path": "src/types/stardust/block/output/basic.rs", "rank": 82, "score": 96942.63786981377 }, { "content": " Ok(bee::NftId::from(bee::OutputId::from_str(s)?).into())\n\n }\n\n}\n\n\n\nimpl From<bee::NftId> for NftId {\n\n fn from(value: bee::NftId) -> Self {\n\n Self(*value)\n\n }\n\n}\n\n\n\nimpl From<NftId> for bee::NftId {\n\n fn from(value: NftId) -> Self {\n\n bee::NftId::new(value.0)\n\n }\n\n}\n\n\n\nimpl FromStr for NftId {\n\n type Err = bee_block_stardust::Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n", "file_path": "src/types/stardust/block/output/nft.rs", "rank": 83, "score": 96941.9556016348 }, { "content": " Ok(bee::AliasId::from(bee::OutputId::from_str(s)?).into())\n\n }\n\n}\n\n\n\nimpl From<bee::AliasId> for AliasId {\n\n fn from(value: bee::AliasId) -> Self {\n\n Self(*value)\n\n }\n\n}\n\n\n\nimpl From<AliasId> for bee::AliasId {\n\n fn from(value: AliasId) -> Self {\n\n bee::AliasId::new(value.0)\n\n }\n\n}\n\n\n\nimpl FromStr for AliasId {\n\n type Err = bee_block_stardust::Error;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n", "file_path": "src/types/stardust/block/output/alias.rs", "rank": 84, "score": 96941.9556016348 }, { "content": " let bson = to_bson(&output_id).unwrap();\n\n from_bson::<OutputId>(bson).unwrap();\n\n }\n\n\n\n #[test]\n\n fn test_output_bson() {\n\n let output = get_test_alias_output();\n\n let bson = to_bson(&output).unwrap();\n\n assert_eq!(output, from_bson::<Output>(bson).unwrap());\n\n\n\n let output = get_test_basic_output();\n\n let bson = to_bson(&output).unwrap();\n\n assert_eq!(output, from_bson::<Output>(bson).unwrap());\n\n\n\n let output = get_test_foundry_output();\n\n let bson = to_bson(&output).unwrap();\n\n assert_eq!(output, from_bson::<Output>(bson).unwrap());\n\n\n\n let output = get_test_nft_output();\n\n let bson = to_bson(&output).unwrap();\n", "file_path": "src/types/stardust/block/output/mod.rs", "rank": 85, "score": 96941.62670454649 }, { "content": " fn try_from(value: NftOutput) -> Result<Self, Self::Error> {\n\n Self::build_with_amount(value.amount, value.nft_id.into())?\n\n .with_native_tokens(\n\n Vec::from(value.native_tokens)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )\n\n .with_unlock_conditions(\n\n Vec::from(value.unlock_conditions)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )\n\n .with_features(\n\n Vec::from(value.features)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )\n", "file_path": "src/types/stardust/block/output/nft.rs", "rank": 86, "score": 96939.28747071976 }, { "content": " Vec::from(value.unlock_conditions)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )\n\n .with_features(\n\n Vec::from(value.features)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )\n\n .with_immutable_features(\n\n Vec::from(value.immutable_features)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )\n\n .finish()\n\n }\n\n}\n", "file_path": "src/types/stardust/block/output/alias.rs", "rank": 87, "score": 96936.45805687236 }, { "content": " .with_native_tokens(\n\n Vec::from(value.native_tokens)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )\n\n .with_unlock_conditions(\n\n Vec::from(value.unlock_conditions)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )\n\n .with_features(\n\n Vec::from(value.features)\n\n .into_iter()\n\n .map(TryInto::try_into)\n\n .collect::<Result<Vec<_>, _>>()?,\n\n )\n\n .with_immutable_features(\n\n Vec::from(value.immutable_features)\n", "file_path": "src/types/stardust/block/output/foundry.rs", "rank": 88, "score": 96936.45805687236 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::payload::tagged_data as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\npub struct TaggedDataPayload {\n\n #[serde(with = \"serde_bytes\")]\n\n tag: Box<[u8]>,\n\n #[serde(with = \"serde_bytes\")]\n\n data: Box<[u8]>,\n\n}\n\n\n\nimpl From<&bee::TaggedDataPayload> for TaggedDataPayload {\n\n fn from(value: &bee::TaggedDataPayload) -> Self {\n\n Self {\n\n tag: value.tag().to_vec().into_boxed_slice(),\n\n data: value.data().to_vec().into_boxed_slice(),\n\n }\n", "file_path": "src/types/stardust/block/payload/tagged_data.rs", "rank": 89, "score": 95367.92426279467 }, { "content": " }\n\n}\n\n\n\nimpl TryFrom<TaggedDataPayload> for bee::TaggedDataPayload {\n\n type Error = bee_block_stardust::Error;\n\n\n\n fn try_from(value: TaggedDataPayload) -> Result<Self, Self::Error> {\n\n bee::TaggedDataPayload::new(value.tag.into(), value.data.into())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn test_tagged_data_payload_bson() {\n\n let payload = get_test_tagged_data_payload();\n\n let bson = to_bson(&payload).unwrap();\n\n assert_eq!(payload, from_bson::<TaggedDataPayload>(bson).unwrap());\n\n }\n\n\n\n pub(crate) fn get_test_tagged_data_payload() -> TaggedDataPayload {\n\n (&bee_test::rand::payload::rand_tagged_data_payload()).into()\n\n }\n\n}\n", "file_path": "src/types/stardust/block/payload/tagged_data.rs", "rank": 90, "score": 95365.14509572591 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse std::{mem::size_of, str::FromStr};\n\n\n\nuse bee_block_stardust::output as bee;\n\nuse primitive_types::U256;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::types::util::bytify;\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(transparent)]\n\npub struct TokenAmount(#[serde(with = \"bytify\")] pub [u8; size_of::<U256>()]);\n\n\n\nimpl From<&U256> for TokenAmount {\n\n fn from(value: &U256) -> Self {\n\n let mut amount = [0; size_of::<U256>()];\n\n value.to_little_endian(&mut amount);\n\n Self(amount)\n", "file_path": "src/types/stardust/block/output/native_token.rs", "rank": 91, "score": 94599.92909212483 }, { "content": " use bee_block_stardust::address::{Address as BeeAddress, AliasAddress as BeeAliasAddress};\n\n BeeAddress::from(BeeAliasAddress::new(bee_test::rand::output::rand_alias_id())).into()\n\n }\n\n\n\n pub(crate) fn get_test_address_condition(address: Address) -> UnlockCondition {\n\n UnlockCondition::Address { address }\n\n }\n\n\n\n pub(crate) fn get_test_storage_deposit_return_condition(return_address: Address, amount: u64) -> UnlockCondition {\n\n UnlockCondition::StorageDepositReturn { return_address, amount }\n\n }\n\n\n\n pub(crate) fn get_test_timelock_condition(milestone_index: u32, timestamp: u32) -> UnlockCondition {\n\n UnlockCondition::Timelock {\n\n milestone_index,\n\n timestamp,\n\n }\n\n }\n\n\n\n pub(crate) fn get_test_expiration_condition(\n", "file_path": "src/types/stardust/block/output/unlock_condition.rs", "rank": 92, "score": 94595.90272536942 }, { "content": "// Copyright 2022 IOTA Stiftung\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse bee_block_stardust::output::unlock_condition as bee;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::types::stardust::block::Address;\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(tag = \"kind\")]\n\npub enum UnlockCondition {\n\n #[serde(rename = \"address\")]\n\n Address { address: Address },\n\n #[serde(rename = \"storage_deposit_return\")]\n\n StorageDepositReturn {\n\n return_address: Address,\n\n #[serde(with = \"crate::types::util::stringify\")]\n\n amount: u64,\n\n },\n\n #[serde(rename = \"timelock\")]\n", "file_path": "src/types/stardust/block/output/unlock_condition.rs", "rank": 93, "score": 94594.56032074922 }, { "content": "}\n\n\n\n#[cfg(test)]\n\npub(crate) mod test {\n\n use mongodb::bson::{from_bson, to_bson};\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn test_unlock_condition_bson() {\n\n let block = get_test_address_condition(bee_test::rand::address::rand_address().into());\n\n let bson = to_bson(&block).unwrap();\n\n assert_eq!(block, from_bson::<UnlockCondition>(bson).unwrap());\n\n\n\n let block = get_test_storage_deposit_return_condition(bee_test::rand::address::rand_address().into(), 1);\n\n let bson = to_bson(&block).unwrap();\n\n assert_eq!(block, from_bson::<UnlockCondition>(bson).unwrap());\n\n\n\n let block = get_test_timelock_condition(1, 1);\n\n let bson = to_bson(&block).unwrap();\n", "file_path": "src/types/stardust/block/output/unlock_condition.rs", "rank": 94, "score": 94592.40729019284 }, { "content": " return_address: Address,\n\n milestone_index: u32,\n\n timestamp: u32,\n\n ) -> UnlockCondition {\n\n UnlockCondition::Expiration {\n\n return_address,\n\n milestone_index,\n\n timestamp,\n\n }\n\n }\n\n\n\n pub(crate) fn get_test_state_controller_address_condition(address: Address) -> UnlockCondition {\n\n UnlockCondition::StateControllerAddress { address }\n\n }\n\n\n\n pub(crate) fn get_test_governor_address_condition(address: Address) -> UnlockCondition {\n\n UnlockCondition::GovernorAddress { address }\n\n }\n\n\n\n pub(crate) fn get_test_immut_alias_address_condition(address: Address) -> UnlockCondition {\n\n UnlockCondition::ImmutableAliasAddress { address }\n\n }\n\n}\n", "file_path": "src/types/stardust/block/output/unlock_condition.rs", "rank": 95, "score": 94589.32492546269 }, { "content": " assert_eq!(block, from_bson::<UnlockCondition>(bson).unwrap());\n\n\n\n let block = get_test_expiration_condition(bee_test::rand::address::rand_address().into(), 1, 1);\n\n let bson = to_bson(&block).unwrap();\n\n assert_eq!(block, from_bson::<UnlockCondition>(bson).unwrap());\n\n\n\n let block = get_test_state_controller_address_condition(bee_test::rand::address::rand_address().into());\n\n let bson = to_bson(&block).unwrap();\n\n assert_eq!(block, from_bson::<UnlockCondition>(bson).unwrap());\n\n\n\n let block = get_test_governor_address_condition(bee_test::rand::address::rand_address().into());\n\n let bson = to_bson(&block).unwrap();\n\n assert_eq!(block, from_bson::<UnlockCondition>(bson).unwrap());\n\n\n\n let block = get_test_immut_alias_address_condition(get_test_alias_address_as_address());\n\n let bson = to_bson(&block).unwrap();\n\n assert_eq!(block, from_bson::<UnlockCondition>(bson).unwrap());\n\n }\n\n\n\n pub(crate) fn get_test_alias_address_as_address() -> Address {\n", "file_path": "src/types/stardust/block/output/unlock_condition.rs", "rank": 96, "score": 94588.82453945692 }, { "content": " }\n\n}\n\n\n\nimpl From<TokenAmount> for U256 {\n\n fn from(value: TokenAmount) -> Self {\n\n U256::from_little_endian(&value.0)\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\n#[serde(transparent)]\n\npub struct TokenId(#[serde(with = \"bytify\")] pub [u8; Self::LENGTH]);\n\n\n\nimpl TokenId {\n\n const LENGTH: usize = bee::TokenId::LENGTH;\n\n}\n\n\n\nimpl From<bee::TokenId> for TokenId {\n\n fn from(value: bee::TokenId) -> Self {\n\n Self(*value)\n", "file_path": "src/types/stardust/block/output/native_token.rs", "rank": 97, "score": 94588.50032707203 }, { "content": "\n\nimpl TryFrom<UnlockCondition> for bee::UnlockCondition {\n\n type Error = bee_block_stardust::Error;\n\n\n\n fn try_from(value: UnlockCondition) -> Result<Self, Self::Error> {\n\n Ok(match value {\n\n UnlockCondition::Address { address } => Self::Address(bee::AddressUnlockCondition::new(address.into())),\n\n UnlockCondition::StorageDepositReturn { return_address, amount } => Self::StorageDepositReturn(\n\n bee::StorageDepositReturnUnlockCondition::new(return_address.into(), amount)?,\n\n ),\n\n UnlockCondition::Timelock {\n\n milestone_index,\n\n timestamp,\n\n } => Self::Timelock(bee::TimelockUnlockCondition::new(milestone_index.into(), timestamp)?),\n\n UnlockCondition::Expiration {\n\n return_address,\n\n milestone_index,\n\n timestamp,\n\n } => Self::Expiration(bee::ExpirationUnlockCondition::new(\n\n return_address.into(),\n", "file_path": "src/types/stardust/block/output/unlock_condition.rs", "rank": 98, "score": 94588.34700746072 }, { "content": " milestone_index.into(),\n\n timestamp,\n\n )?),\n\n UnlockCondition::StateControllerAddress { address } => {\n\n Self::StateControllerAddress(bee::StateControllerAddressUnlockCondition::new(address.into()))\n\n }\n\n UnlockCondition::GovernorAddress { address } => {\n\n Self::GovernorAddress(bee::GovernorAddressUnlockCondition::new(address.into()))\n\n }\n\n UnlockCondition::ImmutableAliasAddress { address } => {\n\n let bee_address = bee_block_stardust::address::Address::from(address);\n\n\n\n if let bee_block_stardust::address::Address::Alias(alias_address) = bee_address {\n\n Self::ImmutableAliasAddress(bee::ImmutableAliasAddressUnlockCondition::new(alias_address))\n\n } else {\n\n Err(bee_block_stardust::Error::InvalidAddressKind(bee_address.kind()))?\n\n }\n\n }\n\n })\n\n }\n", "file_path": "src/types/stardust/block/output/unlock_condition.rs", "rank": 99, "score": 94588.31842809706 } ]
Rust
src/asm/aarch64/cdef.rs
EwoutH/rav1e
39f35d0c94a0523bc6c26042bb54f7dca28efb37
use crate::cdef::*; use crate::cpu_features::CpuFeatureLevel; use crate::frame::*; use crate::tiling::PlaneRegionMut; use crate::util::*; type CdefPaddingFn = unsafe extern fn( tmp: *mut u16, src: *const u8, src_stride: isize, left: *const [u8; 2], top: *const u8, h: i32, edges: isize, ); type CdefPaddingHBDFn = unsafe extern fn( tmp: *mut u16, src: *const u16, src_stride: isize, left: *const [u16; 2], top: *const u16, h: i32, edges: isize, ); type CdefFilterFn = unsafe extern fn( dst: *mut u8, dst_stride: isize, tmp: *const u16, pri_strength: i32, sec_strength: i32, dir: i32, damping: i32, h: i32, edges: isize, ); type CdefFilterHBDFn = unsafe extern fn( dst: *mut u16, dst_stride: isize, tmp: *const u16, pri_strength: i32, sec_strength: i32, dir: i32, damping: i32, h: i32, edges: isize, bitdepth_max: i32, ); #[inline(always)] const fn decimate_index(xdec: usize, ydec: usize) -> usize { ((ydec << 1) | xdec) & 3 } pub(crate) unsafe fn cdef_filter_block<T: Pixel>( dst: &mut PlaneRegionMut<'_, T>, src: *const T, src_stride: isize, pri_strength: i32, sec_strength: i32, dir: usize, damping: i32, bit_depth: usize, xdec: usize, ydec: usize, edges: u8, cpu: CpuFeatureLevel, ) { let call_rust = |dst: &mut PlaneRegionMut<T>| { rust::cdef_filter_block( dst, src, src_stride, pri_strength, sec_strength, dir, damping, bit_depth, xdec, ydec, edges, cpu, ); }; #[cfg(feature = "check_asm")] let ref_dst = { let mut copy = dst.scratch_copy(); call_rust(&mut copy.as_region_mut()); copy }; match T::type_enum() { PixelType::U8 => { match ( CDEF_PAD_FNS[cpu.as_index()][decimate_index(xdec, ydec)], CDEF_FILTER_FNS[cpu.as_index()][decimate_index(xdec, ydec)], ) { (Some(pad), Some(func)) => { let h = if ydec == 1 { 4 } else { 8 } as i32; let tmpstride = if xdec == 1 { 8 } else { 16 } as isize; const MAXTMPSTRIDE: isize = 16; const TMPSIZE: usize = (12 * MAXTMPSTRIDE + 8) as usize; let mut tmp: Aligned<[u16; TMPSIZE]> = Aligned::new([CDEF_VERY_LARGE; TMPSIZE]); let top = src.offset(-2 * src_stride); let mut left: Aligned<[[u8; 2]; 8]> = Aligned::new([[0; 2]; 8]); if edges & CDEF_HAVE_LEFT != 0 { let mut wptr = src.offset(-2) as *const u8; for i in 0..h { left.data[i as usize][0] = *wptr; left.data[i as usize][1] = *wptr.add(1); wptr = wptr.offset(src_stride); } } (pad)( tmp.data.as_mut_ptr().offset(2 * tmpstride + 8) as *mut u16, src as *const u8, T::to_asm_stride(src_stride as usize), left.data.as_ptr() as *const [u8; 2], top as *const u8, 8 >> ydec, edges.into(), ); (func)( dst.data_ptr_mut() as *mut u8, T::to_asm_stride(dst.plane_cfg.stride), tmp.data.as_ptr().offset(2 * tmpstride + 8) as *const u16, pri_strength, sec_strength, dir as i32, damping, 8 >> ydec, edges.into(), ); } _ => call_rust(dst), } } PixelType::U16 => { match ( CDEF_PAD_HBD_FNS[cpu.as_index()][decimate_index(xdec, ydec)], CDEF_FILTER_HBD_FNS[cpu.as_index()][decimate_index(xdec, ydec)], ) { (Some(pad), Some(func)) => { let h = if ydec == 1 { 4 } else { 8 } as i32; let tmpstride = if xdec == 1 { 8 } else { 16 } as isize; const MAXTMPSTRIDE: isize = 16; const TMPSIZE: usize = (12 * MAXTMPSTRIDE + 8) as usize; let mut tmp: Aligned<[u16; TMPSIZE]> = Aligned::new([CDEF_VERY_LARGE; TMPSIZE]); let top = src.offset(-2 * src_stride); let mut left: Aligned<[[u16; 2]; 8]> = Aligned::new([[0; 2]; 8]); if edges & CDEF_HAVE_LEFT != 0 { let mut wptr = src.offset(-2) as *const u16; for i in 0..h { left.data[i as usize][0] = *wptr; left.data[i as usize][1] = *wptr.add(1); wptr = wptr.offset(src_stride); } } (pad)( tmp.data.as_mut_ptr().offset(2 * tmpstride + 8) as *mut u16, src as *const u16, T::to_asm_stride(src_stride as usize), left.data.as_ptr() as *const [u16; 2], top as *const u16, 8 >> ydec, edges.into(), ); (func)( dst.data_ptr_mut() as *mut u16, T::to_asm_stride(dst.plane_cfg.stride), tmp.data.as_ptr().offset(2 * tmpstride + 8) as *const u16, pri_strength, sec_strength, dir as i32, damping, 8 >> ydec, edges.into(), (1 << bit_depth) - 1, ); } _ => call_rust(dst), } } } #[cfg(feature = "check_asm")] { for (dst_row, ref_row) in dst.rows_iter().zip(ref_dst.as_region().rows_iter()) { for (dst, reference) in dst_row.iter().zip(ref_row) { assert_eq!(*dst, *reference); } } } } extern { fn rav1e_cdef_filter4_8bpc_neon( dst: *mut u8, dst_stride: isize, tmp: *const u16, pri_strength: i32, sec_strength: i32, dir: i32, damping: i32, h: i32, edges: isize, ); fn rav1e_cdef_padding4_8bpc_neon( tmp: *mut u16, src: *const u8, src_stride: isize, left: *const [u8; 2], top: *const u8, h: i32, edges: isize, ); fn rav1e_cdef_filter8_8bpc_neon( dst: *mut u8, dst_stride: isize, tmp: *const u16, pri_strength: i32, sec_strength: i32, dir: i32, damping: i32, h: i32, edges: isize, ); fn rav1e_cdef_padding8_8bpc_neon( tmp: *mut u16, src: *const u8, src_stride: isize, left: *const [u8; 2], top: *const u8, h: i32, edges: isize, ); fn rav1e_cdef_filter4_16bpc_neon( dst: *mut u16, dst_stride: isize, tmp: *const u16, pri_strength: i32, sec_strength: i32, dir: i32, damping: i32, h: i32, edges: isize, bd: i32, ); fn rav1e_cdef_padding4_16bpc_neon( tmp: *mut u16, src: *const u16, src_stride: isize, left: *const [u16; 2], top: *const u16, h: i32, edges: isize, ); fn rav1e_cdef_filter8_16bpc_neon( dst: *mut u16, dst_stride: isize, tmp: *const u16, pri_strength: i32, sec_strength: i32, dir: i32, damping: i32, h: i32, edges: isize, bd: i32, ); fn rav1e_cdef_padding8_16bpc_neon( tmp: *mut u16, src: *const u16, src_stride: isize, left: *const [u16; 2], top: *const u16, h: i32, edges: isize, ); } static CDEF_PAD_FNS_NEON: [Option<CdefPaddingFn>; 4] = { let mut out: [Option<CdefPaddingFn>; 4] = [None; 4]; out[decimate_index(1, 1)] = Some(rav1e_cdef_padding4_8bpc_neon); out[decimate_index(1, 0)] = Some(rav1e_cdef_padding4_8bpc_neon); out[decimate_index(0, 0)] = Some(rav1e_cdef_padding8_8bpc_neon); out }; static CDEF_FILTER_FNS_NEON: [Option<CdefFilterFn>; 4] = { let mut out: [Option<CdefFilterFn>; 4] = [None; 4]; out[decimate_index(1, 1)] = Some(rav1e_cdef_filter4_8bpc_neon); out[decimate_index(1, 0)] = Some(rav1e_cdef_filter4_8bpc_neon); out[decimate_index(0, 0)] = Some(rav1e_cdef_filter8_8bpc_neon); out }; static CDEF_PAD_HBD_FNS_NEON: [Option<CdefPaddingHBDFn>; 4] = { let mut out: [Option<CdefPaddingHBDFn>; 4] = [None; 4]; out[decimate_index(1, 1)] = Some(rav1e_cdef_padding4_16bpc_neon); out[decimate_index(1, 0)] = Some(rav1e_cdef_padding4_16bpc_neon); out[decimate_index(0, 0)] = Some(rav1e_cdef_padding8_16bpc_neon); out }; static CDEF_FILTER_HBD_FNS_NEON: [Option<CdefFilterHBDFn>; 4] = { let mut out: [Option<CdefFilterHBDFn>; 4] = [None; 4]; out[decimate_index(1, 1)] = Some(rav1e_cdef_filter4_16bpc_neon); out[decimate_index(1, 0)] = Some(rav1e_cdef_filter4_16bpc_neon); out[decimate_index(0, 0)] = Some(rav1e_cdef_filter8_16bpc_neon); out }; cpu_function_lookup_table!( CDEF_PAD_FNS: [[Option<CdefPaddingFn>; 4]], default: [None; 4], [NEON] ); cpu_function_lookup_table!( CDEF_FILTER_FNS: [[Option<CdefFilterFn>; 4]], default: [None; 4], [NEON] ); cpu_function_lookup_table!( CDEF_PAD_HBD_FNS: [[Option<CdefPaddingHBDFn>; 4]], default: [None; 4], [NEON] ); cpu_function_lookup_table!( CDEF_FILTER_HBD_FNS: [[Option<CdefFilterHBDFn>; 4]], default: [None; 4], [NEON] ); type CdefDirLBDFn = unsafe extern fn(tmp: *const u8, tmp_stride: isize, var: *mut u32) -> i32; type CdefDirHBDFn = unsafe extern fn( tmp: *const u16, tmp_stride: isize, var: *mut u32, bitdepth_max: i32, ) -> i32; #[inline(always)] #[allow(clippy::let_and_return)] pub(crate) fn cdef_find_dir<T: Pixel>( img: &PlaneSlice<'_, T>, var: &mut u32, coeff_shift: usize, cpu: CpuFeatureLevel, ) -> i32 { let call_rust = |var: &mut u32| rust::cdef_find_dir::<T>(img, var, coeff_shift, cpu); #[cfg(feature = "check_asm")] let (ref_dir, ref_var) = { let mut var: u32 = 0; let dir = call_rust(&mut var); (dir, var) }; let dir = match T::type_enum() { PixelType::U8 => { if let Some(func) = CDEF_DIR_LBD_FNS[cpu.as_index()] { unsafe { (func)( img.as_ptr() as *const _, T::to_asm_stride(img.plane.cfg.stride), var as *mut u32, ) } } else { call_rust(var) } } PixelType::U16 if coeff_shift > 0 => { if let Some(func) = CDEF_DIR_HBD_FNS[cpu.as_index()] { unsafe { (func)( img.as_ptr() as *const _, T::to_asm_stride(img.plane.cfg.stride), var as *mut u32, (1 << coeff_shift + 8) - 1, ) } } else { call_rust(var) } } _ => call_rust(var), }; #[cfg(feature = "check_asm")] { assert_eq!(dir, ref_dir); assert_eq!(*var, ref_var); } dir } extern { fn rav1e_cdef_find_dir_8bpc_neon( tmp: *const u8, tmp_stride: isize, var: *mut u32, ) -> i32; } extern { fn rav1e_cdef_find_dir_16bpc_neon( tmp: *const u16, tmp_stride: isize, var: *mut u32, max_bitdepth: i32, ) -> i32; } cpu_function_lookup_table!( CDEF_DIR_LBD_FNS: [Option<CdefDirLBDFn>], default: None, [(NEON, Some(rav1e_cdef_find_dir_8bpc_neon))] ); cpu_function_lookup_table!( CDEF_DIR_HBD_FNS: [Option<CdefDirHBDFn>], default: None, [(NEON, Some(rav1e_cdef_find_dir_16bpc_neon))] );
use crate::cdef::*; use crate::cpu_features::CpuFeatureLevel; use crate::frame::*; use crate::tiling::PlaneRegionMut; use crate::util::*; type CdefPaddingFn = unsafe extern fn( tmp: *mut u16, src: *const u8, src_stride: isize, left: *const [u8; 2], top: *const u8, h: i32, edges: isize, ); type CdefPaddingHBDFn = unsafe extern fn( tmp: *mut u16, src: *const u16, src_stride: isize, left: *const [u16; 2], top: *const u16, h: i32, edges: isize, ); type CdefFilterFn = unsafe extern fn( dst: *mut u8, dst_stride: isize, tmp: *const u16, pri_strength: i32, sec_strength: i32, dir: i32, damping: i32, h: i32, edges: isize, ); type CdefFilterHBDFn = unsafe extern fn( dst: *mut u16, dst_stride: isize, tmp: *const u16, pri_strength: i32, sec_strength: i32, dir: i32, damping: i32, h: i32, edges: isize, bitdepth_max: i32, ); #[inline(always)] const fn decimate_index(xdec: usize, ydec: usize) -> usize { ((ydec << 1) | xdec) & 3 } pub(crate) unsafe fn cdef_filter_block<T: Pixel>( dst: &mut PlaneRegionMut<'_, T>, src: *const T, src_stride: isize, pri_strength: i32, sec_strength: i32, dir: usize, damping: i32, bit_depth: usize, xdec: usize, ydec: usize, edges: u8, cpu: CpuFeatureLevel, ) { let call_rust = |dst: &mut PlaneRegionMut<T>| { rust::cdef_filter_block( dst, src, src_stride, pri_strength, sec_strength, dir, damping, bit_depth, xdec, ydec, edges, cpu, ); }; #[cfg(feature = "check_asm")] let ref_dst = { let mut copy = dst.scratch_copy(); call_rust(&mut copy.as_region_mut()); copy }; match T::type_enum() { PixelType::U8 => { match ( CDEF_PAD_FNS[cpu.as_index()][decimate_index(xdec, ydec)], CDEF_FILTER_FNS[cpu.as_index()][decimate_index(xdec, ydec)], ) { (Some(pad), Some(func)) => { let h = if ydec == 1 { 4 } else { 8 } as i32; let tmpstride = if xdec == 1 { 8 } else { 16 } as isize; const MAXTMPSTRIDE: isize = 16; const TMPSIZE: usize = (12 * MAXTMPSTRIDE + 8) as usize; let mut tmp: Aligned<[u16; TMPSIZE]> = Aligned::new([CDEF_VERY_LARGE; TMPSIZE]); let top = src.offset(-2 * src_stride); let mut left: Aligned<[[u8; 2]; 8]> = Aligned::new([[0; 2]; 8]); if edges & CDEF_HAVE_LEFT != 0 { let mut wptr = src.offset(-2) as *const u8; for i in 0..h { left.data[i as usize][0] = *wptr; left.data[i as usize][1] = *wptr.add(1); wptr = wptr.offset(src_stride); } } (pad)( tmp.data.as_mut_ptr().offset(2 * tmpstride + 8) as *mut u16, src as *const u8, T::to_asm_stride(src_stride as usize), left.data.as_ptr() as *const [u8; 2], top as *const u8, 8 >> ydec, edges.into(), ); (func)( dst.data_ptr_mut() as *mut u8, T::to_asm_stride(dst.plane_cfg.stride), tmp.data.as_ptr().offset(2 * tmpstride + 8) as *const u16, pri_strength, sec_strength, dir as i32, damping, 8 >> ydec, edges.into(), ); } _ => call_rust(dst), } } PixelType::U16 => { match ( CDEF_PAD_HBD_FNS[cpu.as_index()][decimate_index(xdec, ydec)], CDEF_FILTER_HBD_FNS[cpu.as_index()][decimate_index(xdec, ydec)], ) { (Some(pad), Some(func)) => { let h = if ydec == 1 { 4 } else { 8 } as i32; let tmpstride = if xdec == 1 { 8 } else { 16 } as isize; const MAXTMPSTRIDE: isize = 16; const TMPSIZE: usize = (12 * MAXTMPSTRIDE + 8) as usize; let mut tmp: Aligned<[u16; TMPSIZE]> = Aligned::new([CDEF_VERY_LARGE; TMPSIZE]); let top = src.offset(-2 * src_stride); let mut left: Aligned<[[u16; 2]; 8]> = Aligned::new([[0; 2]; 8]); if edges & CDEF_HAVE_LEFT != 0 { let mut wptr = src.offset(-2) as *const u16; for i in 0..h { left.data[i as usize][0] = *wptr; left.data[i as usize][1] = *wptr.add(1); wptr = wptr.offset(src_stride); } } (pad)( tmp.data.as_mut_ptr().offset(2 * tmpstride + 8) as *mut u16, src as *const u16, T::to_asm_stride(src_stride as usize), left.data.as_ptr() as *const [u16; 2], top as *const u16, 8 >> ydec, edges.into(), ); (func)( dst.data_ptr_mut() as *mut u16, T::to_asm_stride(dst.plane_cfg.stride), tmp.data.as_ptr().offset(2 * tmpstride + 8) as *const u16, pri_strength, sec_strength, dir as i32, damping, 8 >> ydec, edges.into(), (1 << bit_depth) - 1, ); } _ => call_rust(dst), } } } #[cfg(feature = "check_asm")] { for (dst_row, ref_row) in dst.rows_iter().zip(ref_dst.as_region().rows_iter()) { for (dst, reference) in dst_row.iter().zip(ref_row) { assert_eq!(*dst, *reference); } } } } extern { fn rav1e_cdef_filter4_8bpc_neon( dst: *mut u8, dst_stride: isize, tmp: *const u16, pri_strength: i32, sec_strength: i32, dir: i32, damping: i32, h: i32, edges: isize, ); fn rav1e_cdef_padding4_8bpc_neon( tmp: *mut u16, src: *const u8, src_stride: isize, left: *const [u8; 2], top: *const u8, h: i32, edges: isize, ); fn rav1e_cdef_filter8_8bpc_neon( dst: *mut u8, dst_stride: isize, tmp: *const u16, pri_strength: i32, sec_strength: i32, dir: i32, damping: i32, h: i32, edges: isize, ); fn rav1e_cdef_padding8_8bpc_neon( tmp: *mut u16, src: *const u8, src_stride: isize, left: *const [u8; 2], top: *const u8, h: i32, edges: isize, ); fn rav1e_cdef_filter4_16bpc_neon( dst: *mut u16, dst_stride: isize, tmp: *const u16, pri_strength: i32, sec_strength: i32, dir: i32, damping: i32, h: i32, edges: isize, bd: i32, ); fn rav1e_cdef_padding4_16bpc_neon( tmp: *mut u16, src: *const u16, src_stride: isize, left: *const [u16; 2], top: *const u16, h: i32, edges: isize, ); fn rav1e_cdef_filter8_16bpc_neon( dst: *mut u16, dst_stride: isize, tmp: *const u16, pri_strength: i32, sec_strength: i32, dir: i32, damping: i32, h: i32, edges: isize, bd: i32, ); fn rav1e_cdef_padding8_16bpc_neon( tmp: *mut u16, src: *const u16, src_stride: isize, left: *const [u16; 2], top: *const u16, h: i32, edges: isize, ); } static CDEF_PAD_FNS_NEON: [Option<CdefPaddingFn>; 4] = { let mut out: [Option<CdefPaddingFn>; 4] = [None; 4]; out[decimate_index(1, 1)] = Some(rav1e_cdef_padding4_8bpc_neon); out[decimate_index(1, 0)] = Some(rav1e_cdef_padding4_8bpc_neon); out[decimate_index(0, 0)] = Some(rav1e_cdef_padding8_8bpc_neon); out }; static CDEF_FILTER_FNS_NEON: [Option<CdefFilterFn>; 4] = { let mut out: [Option<CdefFilterFn>; 4] = [None; 4]; out[decimate_index(1, 1)] = Some(rav1e_cdef_filter4_8bpc_neon); out[decimate_index(1, 0)] = Some(rav1e_cdef_filter4_8bpc_neon); out[decimate_index(0, 0)] = Some(rav1e_cdef_filter8_8bpc_neon); out }; static CDEF_PAD_HBD_FNS_NEON: [Option<CdefPaddingHBDFn>; 4] = { let mut out: [Option<CdefPaddingHBDFn>; 4] = [None; 4]; out[decimate_index(1, 1)] = Some(rav1e_cdef_padding4_16bpc_neon); out[decimate_index(1, 0)] = Some(rav1e_cdef_padding4_16bpc_neon); out[decimate_index(0, 0)] = Some(rav1e_cdef_padding8_16bpc_neon); out }; static CDEF_FILTER_HBD_FNS_NEON: [Option<CdefFilterHBDFn>; 4] = { let mut out: [Option<CdefFilterHBDFn>; 4] = [None; 4]; out[decimate_index(1, 1)] = Some(rav1e_cdef_filter4_16bpc_neon); out[decimate_index(1, 0)] = Some(rav1e_cdef_filter4_16bpc_neon); out[decimate_index(0, 0)] = Some(rav1e_cdef_filter8_16bpc_neon); out }; cpu_function_lookup_table!( CDEF_PAD_FNS: [[Option<CdefPaddingFn>; 4]], default: [None; 4], [NEON] ); cpu_function_lookup_table!( CDEF_FILTER_FNS: [[Option<CdefFilterFn>; 4]], default: [None; 4], [NEON] ); cpu_function_lookup_table!( CDEF_PAD_HBD_FNS: [[Option<CdefPaddingHBDFn>; 4]], default: [None; 4], [NEON] ); cpu_function_lookup_table!( CDEF_FILTER_HBD_FNS: [[Option<CdefFilterHBDFn>; 4]], default: [None; 4], [NEON] ); type CdefDirLBDFn = unsafe extern fn(tmp: *const u8, tmp_stride: isize, var: *mut u32) -> i32; type CdefDirHBDFn = unsafe extern fn( tmp: *const u16, tmp_stride: isize, var: *mut u32, bitdepth_max: i32, ) -> i32; #[inline(always)] #[allow(clippy::let_and_return)]
extern { fn rav1e_cdef_find_dir_8bpc_neon( tmp: *const u8, tmp_stride: isize, var: *mut u32, ) -> i32; } extern { fn rav1e_cdef_find_dir_16bpc_neon( tmp: *const u16, tmp_stride: isize, var: *mut u32, max_bitdepth: i32, ) -> i32; } cpu_function_lookup_table!( CDEF_DIR_LBD_FNS: [Option<CdefDirLBDFn>], default: None, [(NEON, Some(rav1e_cdef_find_dir_8bpc_neon))] ); cpu_function_lookup_table!( CDEF_DIR_HBD_FNS: [Option<CdefDirHBDFn>], default: None, [(NEON, Some(rav1e_cdef_find_dir_16bpc_neon))] );
pub(crate) fn cdef_find_dir<T: Pixel>( img: &PlaneSlice<'_, T>, var: &mut u32, coeff_shift: usize, cpu: CpuFeatureLevel, ) -> i32 { let call_rust = |var: &mut u32| rust::cdef_find_dir::<T>(img, var, coeff_shift, cpu); #[cfg(feature = "check_asm")] let (ref_dir, ref_var) = { let mut var: u32 = 0; let dir = call_rust(&mut var); (dir, var) }; let dir = match T::type_enum() { PixelType::U8 => { if let Some(func) = CDEF_DIR_LBD_FNS[cpu.as_index()] { unsafe { (func)( img.as_ptr() as *const _, T::to_asm_stride(img.plane.cfg.stride), var as *mut u32, ) } } else { call_rust(var) } } PixelType::U16 if coeff_shift > 0 => { if let Some(func) = CDEF_DIR_HBD_FNS[cpu.as_index()] { unsafe { (func)( img.as_ptr() as *const _, T::to_asm_stride(img.plane.cfg.stride), var as *mut u32, (1 << coeff_shift + 8) - 1, ) } } else { call_rust(var) } } _ => call_rust(var), }; #[cfg(feature = "check_asm")] { assert_eq!(dir, ref_dir); assert_eq!(*var, ref_var); } dir }
function_block-full_function
[ { "content": "type CdefDirHBDFn = unsafe extern fn(\n\n tmp: *const u16,\n\n tmp_stride: isize,\n\n var: *mut u32,\n\n bitdepth_max: i32,\n\n) -> i32;\n\n\n\n#[inline(always)]\n\n#[allow(clippy::let_and_return)]\n\npub(crate) fn cdef_find_dir<T: Pixel>(\n\n img: &PlaneSlice<'_, T>, var: &mut u32, coeff_shift: usize,\n\n cpu: CpuFeatureLevel,\n\n) -> i32 {\n\n let call_rust =\n\n |var: &mut u32| rust::cdef_find_dir::<T>(img, var, coeff_shift, cpu);\n\n\n\n #[cfg(feature = \"check_asm\")]\n\n let (ref_dir, ref_var) = {\n\n let mut var: u32 = 0;\n\n let dir = call_rust(&mut var);\n", "file_path": "src/asm/x86/cdef.rs", "rank": 2, "score": 339233.4814169615 }, { "content": "type InvTxfmFn = fn(input: &[i32], output: &mut [i32], range: usize);\n\n\n\nstatic INV_TXFM_FNS: [[InvTxfmFn; 5]; 4] = [\n\n [av1_idct4, av1_idct8, av1_idct16, av1_idct32, av1_idct64],\n\n [\n\n av1_iadst4,\n\n av1_iadst8,\n\n av1_iadst16,\n\n |_, _, _| unimplemented!(),\n\n |_, _, _| unimplemented!(),\n\n ],\n\n [\n\n av1_iflipadst4,\n\n av1_iflipadst8,\n\n av1_iflipadst16,\n\n |_, _, _| unimplemented!(),\n\n |_, _, _| unimplemented!(),\n\n ],\n\n [\n\n av1_iidentity4,\n", "file_path": "src/transform/inverse.rs", "rank": 4, "score": 315219.2659027902 }, { "content": "type TxfmFuncI32X8 = unsafe fn(&mut [I32X8]);\n\n\n", "file_path": "src/asm/x86/transform/forward.rs", "rank": 5, "score": 314686.39609474444 }, { "content": "type CdefFilterFn = unsafe extern fn(\n\n dst: *mut u8,\n\n dst_stride: isize,\n\n tmp: *const u16,\n\n tmp_stride: isize,\n\n pri_strength: i32,\n\n sec_strength: i32,\n\n dir: i32,\n\n damping: i32,\n\n);\n\n\n", "file_path": "src/asm/x86/cdef.rs", "rank": 7, "score": 309037.9625222234 }, { "content": "type CdefFilterHBDFn = unsafe extern fn(\n\n dst: *mut u16,\n\n dst_stride: isize,\n\n tmp: *const u16,\n\n tmp_stride: isize,\n\n pri_strength: i32,\n\n sec_strength: i32,\n\n dir: i32,\n\n damping: i32,\n\n bitdepth_max: i32,\n\n);\n\n\n\n#[inline(always)]\n\nconst fn decimate_index(xdec: usize, ydec: usize) -> usize {\n\n ((ydec << 1) | xdec) & 3\n\n}\n\n\n\npub(crate) unsafe fn cdef_filter_block<T: Pixel>(\n\n dst: &mut PlaneRegionMut<'_, T>, src: *const T, src_stride: isize,\n\n pri_strength: i32, sec_strength: i32, dir: usize, damping: i32,\n", "file_path": "src/asm/x86/cdef.rs", "rank": 8, "score": 303521.3347403819 }, { "content": "type PutFn = unsafe extern fn(\n\n dst: *mut u8,\n\n dst_stride: isize,\n\n src: *const u8,\n\n src_stride: isize,\n\n width: i32,\n\n height: i32,\n\n col_frac: i32,\n\n row_frac: i32,\n\n);\n\n\n", "file_path": "src/asm/aarch64/mc.rs", "rank": 10, "score": 281639.66944238666 }, { "content": "type PrepFn = unsafe extern fn(\n\n tmp: *mut i16,\n\n src: *const u8,\n\n src_stride: isize,\n\n width: i32,\n\n height: i32,\n\n col_frac: i32,\n\n row_frac: i32,\n\n);\n\n\n", "file_path": "src/asm/x86/mc.rs", "rank": 11, "score": 281639.66944238666 }, { "content": "type AvgFn = unsafe extern fn(\n\n dst: *mut u8,\n\n dst_stride: isize,\n\n tmp1: *const i16,\n\n tmp2: *const i16,\n\n width: i32,\n\n height: i32,\n\n);\n\n\n", "file_path": "src/asm/x86/mc.rs", "rank": 12, "score": 281639.66944238666 }, { "content": "type SadFn = unsafe extern fn(\n\n src: *const u8,\n\n src_stride: isize,\n\n dst: *const u8,\n\n dst_stride: isize,\n\n) -> u32;\n\n\n\nmacro_rules! declare_asm_dist_fn {\n\n ($(($name: ident, $T: ident)),+) => (\n\n $(\n\n extern { fn $name (\n\n src: *const $T, src_stride: isize, dst: *const $T, dst_stride: isize\n\n ) -> u32; }\n\n )+\n\n )\n\n}\n\n\n\ndeclare_asm_dist_fn![\n\n (rav1e_sad4x4_neon, u8),\n\n (rav1e_sad4x8_neon, u8),\n", "file_path": "src/asm/aarch64/dist.rs", "rank": 13, "score": 281639.66944238666 }, { "content": "type PutFn = unsafe extern fn(\n\n dst: *mut u8,\n\n dst_stride: isize,\n\n src: *const u8,\n\n src_stride: isize,\n\n width: i32,\n\n height: i32,\n\n col_frac: i32,\n\n row_frac: i32,\n\n);\n\n\n", "file_path": "src/asm/x86/mc.rs", "rank": 14, "score": 281639.66944238666 }, { "content": "type AvgFn = unsafe extern fn(\n\n dst: *mut u8,\n\n dst_stride: isize,\n\n tmp1: *const i16,\n\n tmp2: *const i16,\n\n width: i32,\n\n height: i32,\n\n);\n\n\n", "file_path": "src/asm/aarch64/mc.rs", "rank": 15, "score": 281639.66944238666 }, { "content": "type PrepFn = unsafe extern fn(\n\n tmp: *mut i16,\n\n src: *const u8,\n\n src_stride: isize,\n\n width: i32,\n\n height: i32,\n\n col_frac: i32,\n\n row_frac: i32,\n\n);\n\n\n", "file_path": "src/asm/aarch64/mc.rs", "rank": 16, "score": 281639.66944238666 }, { "content": "type FrameOpaqueCb = Option<extern fn(*mut c_void)>;\n\n\n", "file_path": "src/capi.rs", "rank": 17, "score": 280774.34508468123 }, { "content": "type PutHBDFn = unsafe extern fn(\n\n dst: *mut u16,\n\n dst_stride: isize,\n\n src: *const u16,\n\n src_stride: isize,\n\n width: i32,\n\n height: i32,\n\n col_frac: i32,\n\n row_frac: i32,\n\n bitdepth_max: i32,\n\n);\n\n\n", "file_path": "src/asm/x86/mc.rs", "rank": 18, "score": 275762.42419201735 }, { "content": "type PrepHBDFn = unsafe extern fn(\n\n tmp: *mut i16,\n\n src: *const u16,\n\n src_stride: isize,\n\n width: i32,\n\n height: i32,\n\n col_frac: i32,\n\n row_frac: i32,\n\n bitdepth_max: i32,\n\n);\n\n\n", "file_path": "src/asm/x86/mc.rs", "rank": 19, "score": 275762.42419201735 }, { "content": "type PutHBDFn = unsafe extern fn(\n\n dst: *mut u16,\n\n dst_stride: isize,\n\n src: *const u16,\n\n src_stride: isize,\n\n width: i32,\n\n height: i32,\n\n col_frac: i32,\n\n row_frac: i32,\n\n bitdepth_max: i32,\n\n);\n\n\n", "file_path": "src/asm/aarch64/mc.rs", "rank": 20, "score": 275762.42419201735 }, { "content": "type AvgHBDFn = unsafe extern fn(\n\n dst: *mut u16,\n\n dst_stride: isize,\n\n tmp1: *const i16,\n\n tmp2: *const i16,\n\n width: i32,\n\n height: i32,\n\n bitdepth_max: i32,\n\n);\n\n\n\n// gets an index that can be mapped to a function for a pair of filter modes\n\n#[inline]\n\nconst fn get_2d_mode_idx(mode_x: FilterMode, mode_y: FilterMode) -> usize {\n\n (mode_x as usize + 4 * (mode_y as usize)) & 15\n\n}\n\n\n", "file_path": "src/asm/aarch64/mc.rs", "rank": 21, "score": 275762.42419201735 }, { "content": "type AvgHBDFn = unsafe extern fn(\n\n dst: *mut u16,\n\n dst_stride: isize,\n\n tmp1: *const i16,\n\n tmp2: *const i16,\n\n width: i32,\n\n height: i32,\n\n bitdepth_max: i32,\n\n);\n\n\n\n// gets an index that can be mapped to a function for a pair of filter modes\n\n#[inline]\n\nconst fn get_2d_mode_idx(mode_x: FilterMode, mode_y: FilterMode) -> usize {\n\n (mode_x as usize + 4 * (mode_y as usize)) & 15\n\n}\n\n\n", "file_path": "src/asm/x86/mc.rs", "rank": 22, "score": 275762.42419201735 }, { "content": "type PrepHBDFn = unsafe extern fn(\n\n tmp: *mut i16,\n\n src: *const u16,\n\n src_stride: isize,\n\n width: i32,\n\n height: i32,\n\n col_frac: i32,\n\n row_frac: i32,\n\n bitdepth_max: i32,\n\n);\n\n\n", "file_path": "src/asm/aarch64/mc.rs", "rank": 23, "score": 275762.42419201735 }, { "content": "#[inline(always)]\n\npub fn update_cdf(cdf: &mut [u16], val: u32) {\n\n if cdf.len() == 4 {\n\n return unsafe {\n\n update_cdf_4_sse2(cdf, val);\n\n };\n\n }\n\n\n\n rust::update_cdf(cdf, val);\n\n}\n\n\n\n#[target_feature(enable = \"sse2\")]\n\n#[inline]\n\nunsafe fn update_cdf_4_sse2(cdf: &mut [u16], val: u32) {\n\n let nsymbs = 4;\n\n let rate = 5 + (cdf[nsymbs - 1] >> 4) as usize;\n\n let count = cdf[nsymbs - 1] + (cdf[nsymbs - 1] < 32) as u16;\n\n\n\n // A bit of explanation of what is happening down here. First of all, let's look at the simple\n\n // implementation:\n\n //\n", "file_path": "src/asm/x86/ec.rs", "rank": 24, "score": 264691.6191634583 }, { "content": "#[inline(never)]\n\nfn variance_8x8<T: Pixel>(src: &PlaneRegion<'_, T>) -> u32 {\n\n debug_assert!(src.plane_cfg.xdec == 0);\n\n debug_assert!(src.plane_cfg.ydec == 0);\n\n\n\n // Sum into columns to improve auto-vectorization\n\n let mut sum_s_cols: [u16; 8] = [0; 8];\n\n let mut sum_s2_cols: [u32; 8] = [0; 8];\n\n\n\n // Check upfront that 8 rows are available.\n\n let _row = &src[7];\n\n\n\n for j in 0..8 {\n\n let row = &src[j][0..8];\n\n for (sum_s, sum_s2, s) in izip!(&mut sum_s_cols, &mut sum_s2_cols, row) {\n\n // Don't convert directly to u32 to allow better vectorization\n\n let s: u16 = u16::cast_from(*s);\n\n *sum_s += s;\n\n\n\n // Convert to u32 to avoid overflows when multiplying\n\n let s: u32 = s as u32;\n", "file_path": "src/activity.rs", "rank": 25, "score": 263612.36073993624 }, { "content": "#[inline(always)]\n\npub fn get_mv_class(z: u32, offset: &mut u32) -> usize {\n\n let c = if z >= CLASS0_SIZE as u32 * 4096 {\n\n MV_CLASS_10\n\n } else {\n\n log_in_base_2(z >> 3) as usize\n\n };\n\n\n\n *offset = z - mv_class_base(c);\n\n c\n\n}\n\n\n\nimpl<'a> ContextWriter<'a> {\n\n pub fn encode_mv_component<W: Writer>(\n\n &mut self, w: &mut W, comp: i32, axis: usize, precision: MvSubpelPrecision,\n\n ) {\n\n assert!(comp != 0);\n\n assert!(MV_LOW <= comp && comp <= MV_UPP);\n\n let mvcomp = &mut self.fc.nmv_context.comps[axis];\n\n let mut offset: u32 = 0;\n\n let sign: u32 = if comp < 0 { 1 } else { 0 };\n", "file_path": "src/context/mod.rs", "rank": 26, "score": 257373.02845419705 }, { "content": "fn av1_idct32(input: &[i32], output: &mut [i32], range: usize) {\n\n assert!(input.len() >= 32);\n\n assert!(output.len() >= 32);\n\n\n\n // stage 1;\n\n let stg1 = [\n\n input[0], input[16], input[8], input[24], input[4], input[20], input[12],\n\n input[28], input[2], input[18], input[10], input[26], input[6], input[22],\n\n input[14], input[30], input[1], input[17], input[9], input[25], input[5],\n\n input[21], input[13], input[29], input[3], input[19], input[11],\n\n input[27], input[7], input[23], input[15], input[31],\n\n ];\n\n\n\n // stage 2\n\n let stg2 = [\n\n stg1[0],\n\n stg1[1],\n\n stg1[2],\n\n stg1[3],\n\n stg1[4],\n", "file_path": "src/transform/inverse.rs", "rank": 27, "score": 257075.13247083267 }, { "content": "#[inline(always)]\n\nfn av1_iadst16(input: &[i32], output: &mut [i32], range: usize) {\n\n assert!(input.len() >= 16);\n\n assert!(output.len() >= 16);\n\n\n\n // stage 1\n\n let stg1 = [\n\n input[15], input[0], input[13], input[2], input[11], input[4], input[9],\n\n input[6], input[7], input[8], input[5], input[10], input[3], input[12],\n\n input[1], input[14],\n\n ];\n\n\n\n // stage 2\n\n let stg2 = [\n\n half_btf(COSPI_INV[2], stg1[0], COSPI_INV[62], stg1[1], INV_COS_BIT),\n\n half_btf(COSPI_INV[62], stg1[0], -COSPI_INV[2], stg1[1], INV_COS_BIT),\n\n half_btf(COSPI_INV[10], stg1[2], COSPI_INV[54], stg1[3], INV_COS_BIT),\n\n half_btf(COSPI_INV[54], stg1[2], -COSPI_INV[10], stg1[3], INV_COS_BIT),\n\n half_btf(COSPI_INV[18], stg1[4], COSPI_INV[46], stg1[5], INV_COS_BIT),\n\n half_btf(COSPI_INV[46], stg1[4], -COSPI_INV[18], stg1[5], INV_COS_BIT),\n\n half_btf(COSPI_INV[26], stg1[6], COSPI_INV[38], stg1[7], INV_COS_BIT),\n", "file_path": "src/transform/inverse.rs", "rank": 28, "score": 257075.13247083267 }, { "content": "fn av1_idct16(input: &[i32], output: &mut [i32], range: usize) {\n\n assert!(input.len() >= 16);\n\n assert!(output.len() >= 16);\n\n\n\n // call idct8\n\n let temp_in = [\n\n input[0], input[2], input[4], input[6], input[8], input[10], input[12],\n\n input[14],\n\n ];\n\n let mut temp_out: [i32; 8] = [0; 8];\n\n av1_idct8(&temp_in, &mut temp_out, range);\n\n\n\n // stage 1\n\n let stg1 = [\n\n input[1], input[9], input[5], input[13], input[3], input[11], input[7],\n\n input[15],\n\n ];\n\n\n\n // stage 2\n\n let stg2 = [\n", "file_path": "src/transform/inverse.rs", "rank": 29, "score": 257075.13247083267 }, { "content": "fn av1_iidentity16(input: &[i32], output: &mut [i32], _range: usize) {\n\n output[..16]\n\n .iter_mut()\n\n .zip(input[..16].iter())\n\n .for_each(|(outp, inp)| *outp = round_shift(SQRT2 * 2 * *inp, 12));\n\n}\n\n\n", "file_path": "src/transform/inverse.rs", "rank": 30, "score": 257075.13247083267 }, { "content": "fn av1_iidentity32(input: &[i32], output: &mut [i32], _range: usize) {\n\n output[..32]\n\n .iter_mut()\n\n .zip(input[..32].iter())\n\n .for_each(|(outp, inp)| *outp = 4 * *inp);\n\n}\n\n\n", "file_path": "src/transform/inverse.rs", "rank": 31, "score": 257075.13247083267 }, { "content": "fn av1_idct64(input: &[i32], output: &mut [i32], range: usize) {\n\n assert!(input.len() >= 64);\n\n assert!(output.len() >= 64);\n\n\n\n // stage 1;\n\n let stg1 = [\n\n input[0], input[32], input[16], input[48], input[8], input[40], input[24],\n\n input[56], input[4], input[36], input[20], input[52], input[12],\n\n input[44], input[28], input[60], input[2], input[34], input[18],\n\n input[50], input[10], input[42], input[26], input[58], input[6],\n\n input[38], input[22], input[54], input[14], input[46], input[30],\n\n input[62], input[1], input[33], input[17], input[49], input[9], input[41],\n\n input[25], input[57], input[5], input[37], input[21], input[53],\n\n input[13], input[45], input[29], input[61], input[3], input[35],\n\n input[19], input[51], input[11], input[43], input[27], input[59],\n\n input[7], input[39], input[23], input[55], input[15], input[47],\n\n input[31], input[63],\n\n ];\n\n\n\n // stage 2\n", "file_path": "src/transform/inverse.rs", "rank": 32, "score": 257075.13247083267 }, { "content": "#[inline]\n\nfn adjust_strength(strength: i32, var: i32) -> i32 {\n\n let i = if (var >> 6) != 0 { cmp::min(msb(var >> 6), 12) } else { 0 };\n\n if var != 0 {\n\n (strength * (4 + i) + 8) >> 4\n\n } else {\n\n 0\n\n }\n\n}\n\n\n", "file_path": "src/cdef.rs", "rank": 33, "score": 256824.279595226 }, { "content": "#[inline]\n\nfn copysign(value: u32, signed: i32) -> i32 {\n\n if signed < 0 {\n\n -(value as i32)\n\n } else {\n\n value as i32\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use crate::transform::TxSize::*;\n\n\n\n #[test]\n\n fn test_divu_pair() {\n\n for d in 1..1024 {\n\n for x in 0..1000 {\n\n let ab = divu_gen(d as u32);\n\n assert_eq!(x / d, divu_pair(x, ab));\n\n }\n", "file_path": "src/quantize.rs", "rank": 34, "score": 249160.12390556786 }, { "content": "pub fn av1_iflipadst8(input: &[i32], output: &mut [i32], range: usize) {\n\n av1_iadst8(input, output, range);\n\n output[..8].reverse();\n\n}\n\n\n", "file_path": "src/transform/inverse.rs", "rank": 35, "score": 248709.87332792315 }, { "content": "pub fn av1_iidentity8(input: &[i32], output: &mut [i32], _range: usize) {\n\n output[..8]\n\n .iter_mut()\n\n .zip(input[..8].iter())\n\n .for_each(|(outp, inp)| *outp = 2 * *inp);\n\n}\n\n\n", "file_path": "src/transform/inverse.rs", "rank": 36, "score": 248709.87332792315 }, { "content": "pub fn av1_iflipadst4(input: &[i32], output: &mut [i32], range: usize) {\n\n av1_iadst4(input, output, range);\n\n output[..4].reverse();\n\n}\n\n\n", "file_path": "src/transform/inverse.rs", "rank": 37, "score": 248709.87332792315 }, { "content": "#[inline(always)]\n\npub fn av1_iadst8(input: &[i32], output: &mut [i32], range: usize) {\n\n assert!(input.len() >= 8);\n\n assert!(output.len() >= 8);\n\n\n\n // stage 1\n\n let stg1 = [\n\n input[7], input[0], input[5], input[2], input[3], input[4], input[1],\n\n input[6],\n\n ];\n\n\n\n // stage 2\n\n let stg2 = [\n\n half_btf(COSPI_INV[4], stg1[0], COSPI_INV[60], stg1[1], INV_COS_BIT),\n\n half_btf(COSPI_INV[60], stg1[0], -COSPI_INV[4], stg1[1], INV_COS_BIT),\n\n half_btf(COSPI_INV[20], stg1[2], COSPI_INV[44], stg1[3], INV_COS_BIT),\n\n half_btf(COSPI_INV[44], stg1[2], -COSPI_INV[20], stg1[3], INV_COS_BIT),\n\n half_btf(COSPI_INV[36], stg1[4], COSPI_INV[28], stg1[5], INV_COS_BIT),\n\n half_btf(COSPI_INV[28], stg1[4], -COSPI_INV[36], stg1[5], INV_COS_BIT),\n\n half_btf(COSPI_INV[52], stg1[6], COSPI_INV[12], stg1[7], INV_COS_BIT),\n\n half_btf(COSPI_INV[12], stg1[6], -COSPI_INV[52], stg1[7], INV_COS_BIT),\n", "file_path": "src/transform/inverse.rs", "rank": 38, "score": 248709.87332792315 }, { "content": "#[inline(always)]\n\npub fn av1_iadst4(input: &[i32], output: &mut [i32], _range: usize) {\n\n assert!(input.len() >= 4);\n\n assert!(output.len() >= 4);\n\n\n\n let bit = 12;\n\n\n\n let x0 = input[0];\n\n let x1 = input[1];\n\n let x2 = input[2];\n\n let x3 = input[3];\n\n\n\n // stage 1\n\n let s0 = SINPI_INV[1] * x0;\n\n let s1 = SINPI_INV[2] * x0;\n\n let s2 = SINPI_INV[3] * x1;\n\n let s3 = SINPI_INV[4] * x2;\n\n let s4 = SINPI_INV[1] * x2;\n\n let s5 = SINPI_INV[2] * x3;\n\n let s6 = SINPI_INV[4] * x3;\n\n\n", "file_path": "src/transform/inverse.rs", "rank": 39, "score": 248709.87332792315 }, { "content": "pub fn av1_iflipadst16(input: &[i32], output: &mut [i32], range: usize) {\n\n av1_iadst16(input, output, range);\n\n output[..16].reverse();\n\n}\n\n\n", "file_path": "src/transform/inverse.rs", "rank": 40, "score": 248709.87332792315 }, { "content": "pub fn av1_idct8(input: &[i32], output: &mut [i32], range: usize) {\n\n assert!(input.len() >= 8);\n\n assert!(output.len() >= 8);\n\n\n\n // call idct4\n\n let temp_in = [input[0], input[2], input[4], input[6]];\n\n let mut temp_out: [i32; 4] = [0; 4];\n\n av1_idct4(&temp_in, &mut temp_out, range);\n\n\n\n // stage 0\n\n\n\n // stage 1\n\n let stg1 = [input[1], input[5], input[3], input[7]];\n\n\n\n // stage 2\n\n let stg2 = [\n\n half_btf(COSPI_INV[56], stg1[0], -COSPI_INV[8], stg1[3], INV_COS_BIT),\n\n half_btf(COSPI_INV[24], stg1[1], -COSPI_INV[40], stg1[2], INV_COS_BIT),\n\n half_btf(COSPI_INV[40], stg1[1], COSPI_INV[24], stg1[2], INV_COS_BIT),\n\n half_btf(COSPI_INV[8], stg1[0], COSPI_INV[56], stg1[3], INV_COS_BIT),\n", "file_path": "src/transform/inverse.rs", "rank": 41, "score": 248709.87332792315 }, { "content": "pub fn av1_iidentity4(input: &[i32], output: &mut [i32], _range: usize) {\n\n output[..4]\n\n .iter_mut()\n\n .zip(input[..4].iter())\n\n .for_each(|(outp, inp)| *outp = round_shift(SQRT2 * *inp, 12));\n\n}\n\n\n", "file_path": "src/transform/inverse.rs", "rank": 42, "score": 248709.87332792315 }, { "content": "pub fn av1_idct4(input: &[i32], output: &mut [i32], range: usize) {\n\n assert!(input.len() >= 4);\n\n assert!(output.len() >= 4);\n\n\n\n // stage 1\n\n let stg1 = [input[0], input[2], input[1], input[3]];\n\n\n\n // stage 2\n\n let stg2 = [\n\n half_btf(COSPI_INV[32], stg1[0], COSPI_INV[32], stg1[1], INV_COS_BIT),\n\n half_btf(COSPI_INV[32], stg1[0], -COSPI_INV[32], stg1[1], INV_COS_BIT),\n\n half_btf(COSPI_INV[48], stg1[2], -COSPI_INV[16], stg1[3], INV_COS_BIT),\n\n half_btf(COSPI_INV[16], stg1[2], COSPI_INV[48], stg1[3], INV_COS_BIT),\n\n ];\n\n\n\n // stage 3\n\n output[0] = clamp_value(stg2[0] + stg2[3], range);\n\n output[1] = clamp_value(stg2[1] + stg2[2], range);\n\n output[2] = clamp_value(stg2[1] - stg2[2], range);\n\n output[3] = clamp_value(stg2[0] - stg2[3], range);\n\n}\n\n\n", "file_path": "src/transform/inverse.rs", "rank": 43, "score": 248709.87332792315 }, { "content": "// If n != 0, returns the floor of log base 2 of n. If n == 0, returns 0.\n\npub fn log_in_base_2(n: u32) -> u8 {\n\n 31 - cmp::min(31, n.leading_zeros() as u8)\n\n}\n", "file_path": "src/context/mod.rs", "rank": 44, "score": 230091.78580263283 }, { "content": "type CdefDirLBDFn =\n\n unsafe extern fn(tmp: *const u8, tmp_stride: isize, var: *mut u32) -> i32;\n", "file_path": "src/asm/x86/cdef.rs", "rank": 45, "score": 224722.3418881266 }, { "content": "type DequantizeFn = unsafe fn(\n\n qindex: u8,\n\n coeffs_ptr: *const i16,\n\n _eob: usize,\n\n rcoeffs_ptr: *mut i16,\n\n tx_size: TxSize,\n\n bit_depth: usize,\n\n dc_delta_q: i8,\n\n ac_delta_q: i8,\n\n);\n\n\n\ncpu_function_lookup_table!(\n\n DEQUANTIZE_FNS: [Option<DequantizeFn>],\n\n default: None,\n\n [(AVX2, Some(dequantize_avx2))]\n\n);\n\n\n", "file_path": "src/asm/x86/quantize.rs", "rank": 47, "score": 219185.44724800315 }, { "content": "fn fill_frame_const<T: Pixel>(frame: &mut Frame<T>, value: T) {\n\n for plane in frame.planes.iter_mut() {\n\n let stride = plane.cfg.stride;\n\n for row in plane.data.chunks_mut(stride) {\n\n for pixel in row {\n\n *pixel = value;\n\n }\n\n }\n\n }\n\n}\n\n\n\n#[cfg(feature = \"channel-api\")]\n\nmod channel {\n\n use super::*;\n\n\n\n #[interpolate_test(low_latency_no_scene_change, true, true)]\n\n #[interpolate_test(reorder_no_scene_change, false, true)]\n\n #[interpolate_test(low_latency_scene_change_detection, true, false)]\n\n #[interpolate_test(reorder_scene_change_detection, false, false)]\n\n fn flush(low_lantency: bool, no_scene_detection: bool) {\n", "file_path": "src/api/test.rs", "rank": 48, "score": 218428.5430597763 }, { "content": "#[inline]\n\nfn nhev4(p1: i32, p0: i32, q0: i32, q1: i32, shift: usize) -> usize {\n\n thresh_to_level(cmp::max((p1 - p0).abs(), (q1 - q0).abs()), shift) as usize\n\n}\n\n\n", "file_path": "src/deblock.rs", "rank": 49, "score": 217783.75359949557 }, { "content": "#[inline]\n\nfn mask4(p1: i32, p0: i32, q0: i32, q1: i32, shift: usize) -> usize {\n\n cmp::max(\n\n limit_to_level(cmp::max((p1 - p0).abs(), (q1 - q0).abs()), shift),\n\n blimit_to_level((p0 - q0).abs() * 2 + (p1 - q1).abs() / 2, shift),\n\n ) as usize\n\n}\n\n\n", "file_path": "src/deblock.rs", "rank": 50, "score": 217783.75359949557 }, { "content": "fn sse_v_edge<T: Pixel>(\n\n blocks: &TileBlocks, bo: TileBlockOffset, rec_plane: &PlaneRegion<T>,\n\n src_plane: &PlaneRegion<T>, tally: &mut [i64; MAX_LOOP_FILTER + 2],\n\n pli: usize, bd: usize, xdec: usize, ydec: usize,\n\n) {\n\n let block = &blocks[bo];\n\n let txsize = if pli == 0 {\n\n block.txsize\n\n } else {\n\n block.bsize.largest_chroma_tx_size(xdec, ydec)\n\n };\n\n let tx_edge = bo.0.x >> xdec & (txsize.width_mi() - 1) == 0;\n\n if tx_edge {\n\n let prev_block = deblock_left(blocks, bo, rec_plane);\n\n let block_edge = bo.0.x & (block.n4_w as usize - 1) == 0;\n\n let filter_size =\n\n deblock_size(block, prev_block, rec_plane, pli, true, block_edge);\n\n if filter_size > 0 {\n\n let po = bo.plane_offset(rec_plane.plane_cfg); // rec and src have identical subsampling\n\n let rec_region = rec_plane.subregion(Area::Rect {\n", "file_path": "src/deblock.rs", "rank": 51, "score": 215568.60132778808 }, { "content": "fn filter_h_edge<T: Pixel>(\n\n deblock: &DeblockState, blocks: &TileBlocks, bo: TileBlockOffset,\n\n p: &mut PlaneRegionMut<T>, pli: usize, bd: usize, xdec: usize, ydec: usize,\n\n) {\n\n let block = &blocks[bo];\n\n let txsize = if pli == 0 {\n\n block.txsize\n\n } else {\n\n block.bsize.largest_chroma_tx_size(xdec, ydec)\n\n };\n\n let tx_edge = bo.0.y >> ydec & (txsize.height_mi() - 1) == 0;\n\n if tx_edge {\n\n let prev_block = deblock_up(blocks, bo, &p.as_const());\n\n let block_edge = bo.0.y & (block.n4_h as usize - 1) == 0;\n\n let filter_size =\n\n deblock_size(block, prev_block, &p.as_const(), pli, false, block_edge);\n\n if filter_size > 0 {\n\n let level = deblock_level(deblock, block, prev_block, pli, false);\n\n if level > 0 {\n\n let po = bo.plane_offset(p.plane_cfg);\n", "file_path": "src/deblock.rs", "rank": 52, "score": 215568.60132778814 }, { "content": "fn filter_v_edge<T: Pixel>(\n\n deblock: &DeblockState, blocks: &TileBlocks, bo: TileBlockOffset,\n\n p: &mut PlaneRegionMut<T>, pli: usize, bd: usize, xdec: usize, ydec: usize,\n\n) {\n\n let block = &blocks[bo];\n\n let txsize = if pli == 0 {\n\n block.txsize\n\n } else {\n\n block.bsize.largest_chroma_tx_size(xdec, ydec)\n\n };\n\n let tx_edge = bo.0.x >> xdec & (txsize.width_mi() - 1) == 0;\n\n if tx_edge {\n\n let prev_block = deblock_left(blocks, bo, &p.as_const());\n\n let block_edge = bo.0.x & (block.n4_w as usize - 1) == 0;\n\n let filter_size =\n\n deblock_size(block, prev_block, &p.as_const(), pli, true, block_edge);\n\n if filter_size > 0 {\n\n let level = deblock_level(deblock, block, prev_block, pli, true);\n\n if level > 0 {\n\n let po = bo.plane_offset(p.plane_cfg);\n", "file_path": "src/deblock.rs", "rank": 53, "score": 215568.60132778814 }, { "content": "fn sse_h_edge<T: Pixel>(\n\n blocks: &TileBlocks, bo: TileBlockOffset, rec_plane: &PlaneRegion<T>,\n\n src_plane: &PlaneRegion<T>, tally: &mut [i64; MAX_LOOP_FILTER + 2],\n\n pli: usize, bd: usize, xdec: usize, ydec: usize,\n\n) {\n\n let block = &blocks[bo];\n\n let txsize = if pli == 0 {\n\n block.txsize\n\n } else {\n\n block.bsize.largest_chroma_tx_size(xdec, ydec)\n\n };\n\n let tx_edge = bo.0.y >> ydec & (txsize.height_mi() - 1) == 0;\n\n if tx_edge {\n\n let prev_block = deblock_up(blocks, bo, rec_plane);\n\n let block_edge = bo.0.y & (block.n4_h as usize - 1) == 0;\n\n let filter_size =\n\n deblock_size(block, prev_block, rec_plane, pli, true, block_edge);\n\n if filter_size > 0 {\n\n let po = bo.plane_offset(rec_plane.plane_cfg); // rec and src have identical subsampling\n\n let rec_region = rec_plane.subregion(Area::Rect {\n", "file_path": "src/deblock.rs", "rank": 54, "score": 215568.60132778808 }, { "content": "#[inline]\n\nfn copy_vertical<T: Pixel>(\n\n dst: &mut PlaneRegionMut<'_, T>, x: usize, y: usize, src: &[i32],\n\n) {\n\n for (i, v) in src.iter().enumerate() {\n\n let p = &mut dst[y + i][x];\n\n *p = T::cast_from(*v);\n\n }\n\n}\n\n\n", "file_path": "src/deblock.rs", "rank": 55, "score": 215563.609898819 }, { "content": "#[inline]\n\nfn copy_horizontal<T: Pixel>(\n\n dst: &mut PlaneRegionMut<'_, T>, x: usize, y: usize, src: &[i32],\n\n) {\n\n let row = &mut dst[y][x..];\n\n for (dst, src) in row.iter_mut().take(src.len()).zip(src) {\n\n *dst = T::cast_from(*src);\n\n }\n\n}\n\n\n", "file_path": "src/deblock.rs", "rank": 56, "score": 215563.609898819 }, { "content": "pub fn av1_round_shift_array(arr: &mut [i32], size: usize, bit: i8) {\n\n if bit == 0 {\n\n return;\n\n }\n\n if bit > 0 {\n\n let bit = bit as usize;\n\n for i in arr.iter_mut().take(size) {\n\n *i = round_shift(*i, bit);\n\n }\n\n } else {\n\n for i in arr.iter_mut().take(size) {\n\n *i <<= -bit;\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/transform/mod.rs", "rank": 57, "score": 215231.53213270966 }, { "content": "#[inline]\n\nfn deblock_left<'a, T: Pixel>(\n\n blocks: &'a TileBlocks, in_bo: TileBlockOffset, p: &PlaneRegion<T>,\n\n) -> &'a Block {\n\n let xdec = p.plane_cfg.xdec;\n\n let ydec = p.plane_cfg.ydec;\n\n\n\n // subsampled chroma uses odd mi row/col\n\n // We already know we're not at the upper/left corner, so prev_block is in frame\n\n &blocks[in_bo.0.y | ydec][(in_bo.0.x | xdec) - (1 << xdec)]\n\n}\n\n\n", "file_path": "src/deblock.rs", "rank": 58, "score": 211729.467200358 }, { "content": "#[inline]\n\nfn clamp_value(value: i32, bit: usize) -> i32 {\n\n let max_value: i32 = ((1i64 << (bit - 1)) - 1) as i32;\n\n let min_value: i32 = (-(1i64 << (bit - 1))) as i32;\n\n clamp(value, min_value, max_value)\n\n}\n\n\n", "file_path": "src/transform/mod.rs", "rank": 59, "score": 210127.8583767466 }, { "content": "#[inline(always)]\n\nfn rdo_partition_none<T: Pixel>(\n\n fi: &FrameInvariants<T>, ts: &mut TileStateMut<'_, T>,\n\n cw: &mut ContextWriter, bsize: BlockSize, tile_bo: TileBlockOffset,\n\n inter_cfg: &InterConfig, child_modes: &mut ArrayVec<PartitionParameters, 4>,\n\n) -> f64 {\n\n debug_assert!(tile_bo.0.x < ts.mi_width && tile_bo.0.y < ts.mi_height);\n\n\n\n let mode = rdo_mode_decision(fi, ts, cw, bsize, tile_bo, inter_cfg);\n\n let cost = mode.rd_cost;\n\n\n\n child_modes.push(mode);\n\n\n\n cost\n\n}\n\n\n\n// VERTICAL, HORIZONTAL or simple SPLIT\n", "file_path": "src/rdo.rs", "rank": 60, "score": 209770.5158869471 }, { "content": "pub fn get_sgr_sets(complexity: SGRComplexityLevel) -> &'static [u8] {\n\n match complexity {\n\n SGRComplexityLevel::Full => SGRPROJ_ALL_SETS,\n\n SGRComplexityLevel::Reduced => SGRPROJ_REDUCED_SETS,\n\n }\n\n}\n\n\n\npub const SOLVE_IMAGE_MAX: usize = 1 << RESTORATION_TILESIZE_MAX_LOG2;\n\npub const SOLVE_IMAGE_STRIDE: usize = SOLVE_IMAGE_MAX + 6 + 2;\n\npub const SOLVE_IMAGE_HEIGHT: usize = SOLVE_IMAGE_STRIDE;\n\npub const SOLVE_IMAGE_SIZE: usize = SOLVE_IMAGE_STRIDE * SOLVE_IMAGE_HEIGHT;\n\n\n\npub const STRIPE_IMAGE_MAX: usize = (1 << RESTORATION_TILESIZE_MAX_LOG2)\n\n + (1 << (RESTORATION_TILESIZE_MAX_LOG2 - 1));\n\npub const STRIPE_IMAGE_STRIDE: usize = STRIPE_IMAGE_MAX + 6 + 2;\n\npub const STRIPE_IMAGE_HEIGHT: usize = 64 + 6 + 2;\n\npub const STRIPE_IMAGE_SIZE: usize = STRIPE_IMAGE_STRIDE * STRIPE_IMAGE_HEIGHT;\n\n\n\npub const IMAGE_WIDTH_MAX: usize = [STRIPE_IMAGE_MAX, SOLVE_IMAGE_MAX]\n\n [(STRIPE_IMAGE_MAX < SOLVE_IMAGE_MAX) as usize];\n", "file_path": "src/lrf.rs", "rank": 61, "score": 207187.44466802134 }, { "content": "pub fn copy_from_raw_u8_8bit(c: &mut Criterion) {\n\n let input = init_raw_plane_data(1920, 1080);\n\n let dest = Plane::<u8>::new(1920, 1080, 0, 0, 0, 0);\n\n c.bench_function(\"copy_from_raw_u8\", move |b| {\n\n b.iter(|| {\n\n let mut dest = dest.clone();\n\n let _ = dest.copy_from_raw_u8(&input, dest.cfg.stride, 1);\n\n })\n\n });\n\n}\n\n\n", "file_path": "benches/plane.rs", "rank": 62, "score": 206879.08698978083 }, { "content": "pub fn copy_from_raw_u8_10bit(c: &mut Criterion) {\n\n let input = init_raw_plane_data(1920, 1080);\n\n let dest = Plane::<u16>::new(1920, 1080, 0, 0, 0, 0);\n\n c.bench_function(\"copy_from_raw_u8\", move |b| {\n\n b.iter(|| {\n\n let mut dest = dest.clone();\n\n let _ = dest.copy_from_raw_u8(&input, dest.cfg.stride, 2);\n\n })\n\n });\n\n}\n\n\n\ncriterion_group!(\n\n plane,\n\n downsample_8bit,\n\n downsample_odd,\n\n downsample_10bit,\n\n copy_from_raw_u8_8bit,\n\n copy_from_raw_u8_10bit\n\n);\n", "file_path": "benches/plane.rs", "rank": 63, "score": 206879.08698978083 }, { "content": "#[inline]\n\nfn flat6(p2: i32, p1: i32, p0: i32, q0: i32, q1: i32, q2: i32) -> usize {\n\n cmp::max(\n\n (p1 - p0).abs(),\n\n cmp::max((q1 - q0).abs(), cmp::max((p2 - p0).abs(), (q2 - q0).abs())),\n\n ) as usize\n\n}\n\n\n", "file_path": "src/deblock.rs", "rank": 64, "score": 206034.87988816714 }, { "content": "fn bench_put_8tap_top_left_lbd(c: &mut Criterion) {\n\n let mut ra = ChaChaRng::from_seed([0; 32]);\n\n let cpu = CpuFeatureLevel::default();\n\n let w = 640;\n\n let h = 480;\n\n let input_plane = new_plane::<u8>(&mut ra, w, h);\n\n let mut dst_plane = new_plane::<u8>(&mut ra, w, h);\n\n\n\n let (row_frac, col_frac, src) = get_params(\n\n &input_plane,\n\n PlaneOffset { x: 0, y: 0 },\n\n MotionVector { row: 0, col: 0 },\n\n );\n\n c.bench_function(\"put_8tap_top_left_lbd\", |b| {\n\n b.iter(|| {\n\n let _ = black_box(put_8tap(\n\n &mut dst_plane.as_region_mut(),\n\n src,\n\n 8,\n\n 8,\n", "file_path": "benches/mc.rs", "rank": 65, "score": 205172.61354594887 }, { "content": "fn bench_prep_8tap_top_left_lbd(c: &mut Criterion) {\n\n let mut ra = ChaChaRng::from_seed([0; 32]);\n\n let cpu = CpuFeatureLevel::default();\n\n let w = 640;\n\n let h = 480;\n\n let input_plane = new_plane::<u8>(&mut ra, w, h);\n\n let mut dst = Aligned::<[i16; 128 * 128]>::uninitialized();\n\n\n\n let (row_frac, col_frac, src) = get_params(\n\n &input_plane,\n\n PlaneOffset { x: 0, y: 0 },\n\n MotionVector { row: 0, col: 0 },\n\n );\n\n c.bench_function(\"prep_8tap_top_left_lbd\", |b| {\n\n b.iter(|| {\n\n let _ = black_box(prep_8tap(\n\n &mut dst.data,\n\n src,\n\n 8,\n\n 8,\n", "file_path": "benches/mc.rs", "rank": 66, "score": 205172.61354594887 }, { "content": "fn bench_put_8tap_top_left_hbd(c: &mut Criterion) {\n\n let mut ra = ChaChaRng::from_seed([0; 32]);\n\n let cpu = CpuFeatureLevel::default();\n\n let w = 640;\n\n let h = 480;\n\n let input_plane = new_plane::<u16>(&mut ra, w, h);\n\n let mut dst_plane = new_plane::<u16>(&mut ra, w, h);\n\n\n\n let (row_frac, col_frac, src) = get_params(\n\n &input_plane,\n\n PlaneOffset { x: 0, y: 0 },\n\n MotionVector { row: 0, col: 0 },\n\n );\n\n c.bench_function(\"put_8tap_top_left_hbd\", |b| {\n\n b.iter(|| {\n\n let _ = black_box(put_8tap(\n\n &mut dst_plane.as_region_mut(),\n\n src,\n\n 8,\n\n 8,\n", "file_path": "benches/mc.rs", "rank": 67, "score": 205172.61354594887 }, { "content": "fn bench_prep_8tap_top_left_hbd(c: &mut Criterion) {\n\n let mut ra = ChaChaRng::from_seed([0; 32]);\n\n let cpu = CpuFeatureLevel::default();\n\n let w = 640;\n\n let h = 480;\n\n let input_plane = new_plane::<u16>(&mut ra, w, h);\n\n let mut dst = Aligned::<[i16; 128 * 128]>::uninitialized();\n\n\n\n let (row_frac, col_frac, src) = get_params(\n\n &input_plane,\n\n PlaneOffset { x: 0, y: 0 },\n\n MotionVector { row: 0, col: 0 },\n\n );\n\n c.bench_function(\"prep_8tap_top_left_hbd\", |b| {\n\n b.iter(|| {\n\n let _ = black_box(prep_8tap(\n\n &mut dst.data,\n\n src,\n\n 8,\n\n 8,\n", "file_path": "benches/mc.rs", "rank": 68, "score": 205172.61354594887 }, { "content": "/// Fill data for scaling of one\n\nfn fill_scaling(ra: &mut ChaChaRng, scales: &mut [u32]) {\n\n for a in scales.iter_mut() {\n\n *a =\n\n ra.gen_range(DistortionScale::new(0.5).0..DistortionScale::new(1.5).0);\n\n }\n\n}\n\n\n", "file_path": "benches/dist.rs", "rank": 69, "score": 204326.0138262545 }, { "content": "#[inline]\n\nfn half_btf(w0: i32, in0: i32, w1: i32, in1: i32, bit: usize) -> i32 {\n\n // Ensure defined behaviour for when w0*in0 + w1*in1 is negative and\n\n // overflows, but w0*in0 + w1*in1 + rounding isn't.\n\n let result = (w0 * in0).wrapping_add(w1 * in1);\n\n // Implement a version of round_shift with wrapping\n\n if bit == 0 {\n\n result\n\n } else {\n\n result.wrapping_add(1 << (bit - 1)) >> bit\n\n }\n\n}\n\n\n\n// clamps value to a signed integer type of bit bits\n", "file_path": "src/transform/mod.rs", "rank": 70, "score": 204019.70082845344 }, { "content": "pub fn select_dc_qi(quantizer: i64, bit_depth: usize) -> u8 {\n\n let qlookup = match bit_depth {\n\n 8 => &dc_qlookup_Q3,\n\n 10 => &dc_qlookup_10_Q3,\n\n 12 => &dc_qlookup_12_Q3,\n\n _ => unimplemented!(),\n\n };\n\n select_qi(quantizer, qlookup)\n\n}\n\n\n", "file_path": "src/quantize.rs", "rank": 71, "score": 202779.76034380615 }, { "content": "pub fn select_ac_qi(quantizer: i64, bit_depth: usize) -> u8 {\n\n let qlookup = match bit_depth {\n\n 8 => &ac_qlookup_Q3,\n\n 10 => &ac_qlookup_10_Q3,\n\n 12 => &ac_qlookup_12_Q3,\n\n _ => unimplemented!(),\n\n };\n\n select_qi(quantizer, qlookup)\n\n}\n\n\n\n#[derive(Debug, Default, Clone, Copy)]\n\npub struct QuantizationContext {\n\n log_tx_scale: usize,\n\n dc_quant: u32,\n\n dc_offset: u32,\n\n dc_mul_add: (u32, u32, u32),\n\n\n\n ac_quant: u32,\n\n ac_offset_eob: u32,\n\n ac_offset0: u32,\n\n ac_offset1: u32,\n\n ac_mul_add: (u32, u32, u32),\n\n}\n\n\n", "file_path": "src/quantize.rs", "rank": 72, "score": 202779.76034380615 }, { "content": "pub fn get_intra_edges<T: Pixel>(\n\n dst: &PlaneRegion<'_, T>,\n\n partition_bo: TileBlockOffset, // partition bo, BlockOffset\n\n bx: usize,\n\n by: usize,\n\n partition_size: BlockSize, // partition size, BlockSize\n\n po: PlaneOffset,\n\n tx_size: TxSize,\n\n bit_depth: usize,\n\n opt_mode: Option<PredictionMode>,\n\n enable_intra_edge_filter: bool,\n\n intra_param: IntraParam,\n\n) -> Aligned<[T; 4 * MAX_TX_SIZE + 1]> {\n\n let plane_cfg = &dst.plane_cfg;\n\n\n\n let mut edge_buf: Aligned<[T; 4 * MAX_TX_SIZE + 1]> =\n\n Aligned::uninitialized();\n\n //Aligned::new([T::cast_from(0); 4 * MAX_TX_SIZE + 1]);\n\n let base = 128u16 << (bit_depth - 8);\n\n\n", "file_path": "src/partition.rs", "rank": 73, "score": 200549.06437569138 }, { "content": "fn fill_frame<T: Pixel>(ra: &mut ChaChaRng, frame: &mut Frame<T>) {\n\n for plane in frame.planes.iter_mut() {\n\n let stride = plane.cfg.stride;\n\n for row in plane.data.chunks_mut(stride) {\n\n for pixel in row {\n\n let v: u8 = ra.gen();\n\n *pixel = T::cast_from(v);\n\n }\n\n }\n\n }\n\n}\n\n*/\n\n\n", "file_path": "src/api/test.rs", "rank": 74, "score": 200416.35806258649 }, { "content": "fn divu_gen(d: u32) -> (u32, u32, u32) {\n\n let nbits = (mem::size_of_val(&d) as u64) * 8;\n\n let m = nbits - d.leading_zeros() as u64 - 1;\n\n if (d & (d - 1)) == 0 {\n\n (0xFFFF_FFFF, 0xFFFF_FFFF, m as u32)\n\n } else {\n\n let d = d as u64;\n\n let t = (1u64 << (m + nbits)) / d;\n\n let r = (t * d + d) & ((1 << nbits) - 1);\n\n if r <= 1u64 << m {\n\n (t as u32 + 1, 0u32, m as u32)\n\n } else {\n\n (t as u32, t as u32, m as u32)\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/quantize.rs", "rank": 75, "score": 200175.5160053877 }, { "content": "#[inline]\n\nfn divu_pair(x: u32, d: (u32, u32, u32)) -> u32 {\n\n let x = x as u64;\n\n let (a, b, shift) = d;\n\n let shift = shift as u64;\n\n let a = a as u64;\n\n let b = b as u64;\n\n\n\n (((a * x + b) >> 32) >> shift) as u32\n\n}\n\n\n", "file_path": "src/quantize.rs", "rank": 76, "score": 197933.1110698115 }, { "content": "fn rav1e_frame_pad_internal<T: rav1e::Pixel>(\n\n f: &mut Arc<rav1e::Frame<T>>, planes: usize, width: usize, height: usize,\n\n) {\n\n if let Some(ref mut input) = Arc::get_mut(f) {\n\n for plane in input.planes[..planes].iter_mut() {\n\n plane.pad(width, height);\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/capi.rs", "rank": 77, "score": 195541.8710749186 }, { "content": "/// RDO-based transform type decision\n\n/// If cw_checkpoint is None, a checkpoint for cw's (ContextWriter) current\n\n/// state is created and stored for later use.\n\npub fn rdo_tx_type_decision<T: Pixel>(\n\n fi: &FrameInvariants<T>, ts: &mut TileStateMut<'_, T>,\n\n cw: &mut ContextWriter, cw_checkpoint: &mut Option<ContextWriterCheckpoint>,\n\n mode: PredictionMode, ref_frames: [RefType; 2], mvs: [MotionVector; 2],\n\n bsize: BlockSize, tile_bo: TileBlockOffset, tx_size: TxSize, tx_set: TxSet,\n\n tx_types: &[TxType],\n\n) -> (TxType, f64) {\n\n let mut best_type = TxType::DCT_DCT;\n\n let mut best_rd = std::f64::MAX;\n\n\n\n let PlaneConfig { xdec, ydec, .. } = ts.input.planes[1].cfg;\n\n let is_chroma_block =\n\n has_chroma(tile_bo, bsize, xdec, ydec, fi.sequence.chroma_sampling);\n\n\n\n let is_inter = !mode.is_intra();\n\n\n\n if cw_checkpoint.is_none() {\n\n // Only run the first call\n\n // Prevents creating multiple checkpoints for own version of cw\n\n *cw_checkpoint =\n", "file_path": "src/rdo.rs", "rank": 78, "score": 195486.85701483034 }, { "content": "pub fn rdo_tx_size_type<T: Pixel>(\n\n fi: &FrameInvariants<T>, ts: &mut TileStateMut<'_, T>,\n\n cw: &mut ContextWriter, bsize: BlockSize, tile_bo: TileBlockOffset,\n\n luma_mode: PredictionMode, ref_frames: [RefType; 2], mvs: [MotionVector; 2],\n\n skip: bool,\n\n) -> (TxSize, TxType) {\n\n let is_inter = !luma_mode.is_intra();\n\n let mut tx_size = max_txsize_rect_lookup[bsize as usize];\n\n\n\n if fi.enable_inter_txfm_split && is_inter && !skip {\n\n tx_size = sub_tx_size_map[tx_size as usize]; // Always choose one level split size\n\n }\n\n\n\n let mut best_tx_type = TxType::DCT_DCT;\n\n let mut best_tx_size = tx_size;\n\n let mut best_rd = std::f64::MAX;\n\n\n\n let do_rdo_tx_size =\n\n fi.tx_mode_select && fi.config.speed_settings.rdo_tx_decision && !is_inter;\n\n let rdo_tx_depth = if do_rdo_tx_size { 2 } else { 0 };\n", "file_path": "src/rdo.rs", "rank": 79, "score": 195472.0199249656 }, { "content": "pub fn ac_q(qindex: u8, delta_q: i8, bit_depth: usize) -> i16 {\n\n static AC_Q: [&[i16; 256]; 3] =\n\n [&ac_qlookup_Q3, &ac_qlookup_10_Q3, &ac_qlookup_12_Q3];\n\n let bd = ((bit_depth ^ 8) >> 1).min(2);\n\n AC_Q[bd][((qindex as isize + delta_q as isize).max(0) as usize).min(255)]\n\n}\n\n\n", "file_path": "src/quantize.rs", "rank": 80, "score": 195382.14882731467 }, { "content": "pub fn dc_q(qindex: u8, delta_q: i8, bit_depth: usize) -> i16 {\n\n static DC_Q: [&[i16; 256]; 3] =\n\n [&dc_qlookup_Q3, &dc_qlookup_10_Q3, &dc_qlookup_12_Q3];\n\n let bd = ((bit_depth ^ 8) >> 1).min(2);\n\n DC_Q[bd][((qindex as isize + delta_q as isize).max(0) as usize).min(255)]\n\n}\n\n\n", "file_path": "src/quantize.rs", "rank": 81, "score": 195382.14882731467 }, { "content": "fn fill_frame<T: Pixel>(ra: &mut ChaChaRng, frame: &mut Frame<T>) {\n\n for plane in frame.planes.iter_mut() {\n\n let stride = plane.cfg.stride;\n\n for row in plane.data.chunks_mut(stride) {\n\n for pixel in row {\n\n let v: u8 = ra.gen();\n\n *pixel = T::cast_from(v);\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/test_encode_decode/mod.rs", "rank": 82, "score": 194410.55302969326 }, { "content": "type ec_window = u32;\n\n\n", "file_path": "src/ec.rs", "rank": 83, "score": 192606.92506458805 }, { "content": "fn init_plane_u8(width: usize, height: usize, seed: u8) -> Plane<u8> {\n\n let mut ra = ChaChaRng::from_seed([seed; 32]);\n\n let data: Vec<u8> = (0..(width * height)).map(|_| ra.gen()).collect();\n\n Plane::from_slice(&data, width)\n\n}\n\n\n", "file_path": "benches/rdo.rs", "rank": 84, "score": 190868.59962770974 }, { "content": "// Compute Bessel filter coefficients with the specified delay.\n\n// Return: Filter parameters (c[0], c[1], g).\n\nfn iir_bessel2_get_parameters(delay: i32) -> (i32, i32, i32) {\n\n // This borrows some code from an unreleased version of Postfish.\n\n // See the recipe at http://unicorn.us.com/alex/2polefilters.html for details\n\n // on deriving the filter coefficients.\n\n // alpha is Q24\n\n let alpha = (1 << 24) / delay;\n\n // warp is 7.12 (5.12? the max value is 70386 in Q12).\n\n let warp = warp_alpha(alpha).max(1) as i64;\n\n // k1 is 9.12 (6.12?)\n\n let k1 = 3 * warp;\n\n // k2 is 16.24 (11.24?)\n\n let k2 = k1 * warp;\n\n // d is 16.15 (10.15?)\n\n let d = ((((1 << 12) + k1) << 12) + k2 + 256) >> 9;\n\n // a is 0.32, since d is larger than both 1.0 and k2\n\n let a = (k2 << 23) / d;\n\n // ik2 is 25.24\n\n let ik2 = (1i64 << 48) / k2;\n\n // b1 is Q56; in practice, the integer ranges between -2 and 2.\n\n let b1 = 2 * a * (ik2 - (1i64 << 24));\n", "file_path": "src/rate.rs", "rank": 85, "score": 190790.35262186598 }, { "content": "fn sub_pixel_me<T: Pixel>(\n\n fi: &FrameInvariants<T>, po: PlaneOffset, org_region: &PlaneRegion<T>,\n\n p_ref: &Plane<T>, lambda: u32, pmv: [MotionVector; 2], mvx_min: isize,\n\n mvx_max: isize, mvy_min: isize, mvy_max: isize, bsize: BlockSize,\n\n use_satd: bool, best: &mut MVSearchResult, ref_frame: RefType,\n\n) {\n\n subpel_diamond_me_search(\n\n fi,\n\n po,\n\n org_region,\n\n p_ref,\n\n fi.sequence.bit_depth,\n\n pmv,\n\n lambda,\n\n mvx_min,\n\n mvx_max,\n\n mvy_min,\n\n mvy_max,\n\n bsize,\n\n use_satd,\n\n best,\n\n ref_frame,\n\n );\n\n}\n\n\n", "file_path": "src/me.rs", "rank": 86, "score": 190230.17393205734 }, { "content": "fn full_pixel_me<T: Pixel>(\n\n fi: &FrameInvariants<T>, ts: &TileStateMut<'_, T>,\n\n org_region: &PlaneRegion<T>, p_ref: &Plane<T>, tile_bo: TileBlockOffset,\n\n po: PlaneOffset, lambda: u32, pmv: [MotionVector; 2], bsize: BlockSize,\n\n mvx_min: isize, mvx_max: isize, mvy_min: isize, mvy_max: isize,\n\n ref_frame: RefType, conf: &FullpelConfig,\n\n) -> FullpelSearchResult {\n\n let ssdec = conf.ssdec;\n\n\n\n let tile_me_stats = &ts.me_stats[ref_frame.to_index()].as_const();\n\n let frame_ref =\n\n fi.rec_buffer.frames[fi.ref_frames[0] as usize].as_ref().map(Arc::as_ref);\n\n let subsets = get_subset_predictors(\n\n tile_bo,\n\n tile_me_stats,\n\n frame_ref,\n\n ref_frame.to_index(),\n\n bsize,\n\n mvx_min,\n\n mvx_max,\n", "file_path": "src/me.rs", "rank": 87, "score": 190230.17393205734 }, { "content": "// alpha is Q24 in the range [0,0.5).\n\n// The return value is 5.12.\n\n// TODO: Mark const once we can use local variables in a const function.\n\nfn warp_alpha(alpha: i32) -> i32 {\n\n let i = ((alpha * 36) >> 24).min(16);\n\n let t0 = ROUGH_TAN_LOOKUP[i as usize];\n\n let t1 = ROUGH_TAN_LOOKUP[i as usize + 1];\n\n let d = alpha * 36 - (i << 24);\n\n ((((t0 as i64) << 32) + (((t1 - t0) << 8) as i64) * (d as i64)) >> 32) as i32\n\n}\n\n\n", "file_path": "src/rate.rs", "rank": 88, "score": 189947.58252319932 }, { "content": "#[inline]\n\nfn get_func_i32x8(t: TxfmType) -> TxfmFuncI32X8 {\n\n use self::TxfmType::*;\n\n match t {\n\n DCT4 => daala_fdct4,\n\n DCT8 => daala_fdct8,\n\n DCT16 => daala_fdct16,\n\n DCT32 => daala_fdct32,\n\n DCT64 => daala_fdct64,\n\n ADST4 => daala_fdst_vii_4,\n\n ADST8 => daala_fdst8,\n\n ADST16 => daala_fdst16,\n\n Identity4 => fidentity,\n\n Identity8 => fidentity,\n\n Identity16 => fidentity,\n\n Identity32 => fidentity,\n\n _ => unreachable!(),\n\n }\n\n}\n\n\n", "file_path": "src/asm/x86/transform/forward.rs", "rank": 89, "score": 189839.47796263182 }, { "content": "#[inline(always)]\n\npub fn msb(x: i32) -> i32 {\n\n debug_assert!(x > 0);\n\n 31 ^ (x.leading_zeros() as i32)\n\n}\n\n\n\n#[inline(always)]\n\npub const fn round_shift(value: i32, bit: usize) -> i32 {\n\n (value + (1 << bit >> 1)) >> bit\n\n}\n", "file_path": "v_frame/src/math.rs", "rank": 90, "score": 186721.4239129549 }, { "content": "pub fn call_inverse_func<T: Pixel>(\n\n func: InvTxfmFunc, input: &[T::Coeff], output: &mut PlaneRegionMut<'_, T>,\n\n eob: usize, width: usize, height: usize, bd: usize,\n\n) {\n\n debug_assert!(bd == 8);\n\n\n\n // Only use at most 32 columns and 32 rows of input coefficients.\n\n let input: &[T::Coeff] = &input[..width.min(32) * height.min(32)];\n\n\n\n let mut copied: Aligned<[T::Coeff; 32 * 32]> = Aligned::uninitialized();\n\n\n\n // Convert input to 16-bits.\n\n // TODO: Remove by changing inverse assembly to not overwrite its input\n\n for (a, b) in copied.data.iter_mut().zip(input) {\n\n *a = *b;\n\n }\n\n\n\n // perform the inverse transform\n\n unsafe {\n\n func(\n\n output.data_ptr_mut() as *mut _,\n\n output.plane_cfg.stride as isize,\n\n copied.data.as_mut_ptr() as *mut _,\n\n eob as i32,\n\n );\n\n }\n\n}\n\n\n", "file_path": "src/asm/shared/transform/inverse.rs", "rank": 91, "score": 186511.22307659712 }, { "content": "fn send_frame_kf<T: Pixel>(ctx: &mut Context<T>, keyframe: bool) {\n\n let input = ctx.new_frame();\n\n\n\n let frame_type_override =\n\n if keyframe { FrameTypeOverride::Key } else { FrameTypeOverride::No };\n\n\n\n let opaque = Some(Opaque::new(keyframe));\n\n\n\n let fp = FrameParameters { frame_type_override, opaque };\n\n\n\n let _ = ctx.send_frame((input, fp));\n\n}\n\n\n", "file_path": "src/api/test.rs", "rank": 92, "score": 185902.65905756078 }, { "content": "#[inline(always)]\n\npub fn mv_class_base(mv_class: usize) -> u32 {\n\n if mv_class != MV_CLASS_0 {\n\n (CLASS0_SIZE << (mv_class as usize + 2)) as u32\n\n } else {\n\n 0\n\n }\n\n}\n\n#[inline(always)]\n", "file_path": "src/context/mod.rs", "rank": 93, "score": 184776.1583678454 }, { "content": "fn init_buffers(size: usize) -> (Vec<i32>, Vec<i32>) {\n\n let mut ra = ChaChaRng::from_seed([0; 32]);\n\n let input: Vec<i32> = (0..size).map(|_| ra.gen()).collect();\n\n let output = vec![0i32; size];\n\n\n\n (input, output)\n\n}\n\n\n", "file_path": "benches/transform.rs", "rank": 94, "score": 183932.0327562734 }, { "content": "fn init_plane_u16(width: usize, height: usize) -> Plane<u16> {\n\n let mut ra = ChaChaRng::from_seed([0; 32]);\n\n let data: Vec<u16> = (0..(width * height)).map(|_| ra.gen()).collect();\n\n Plane::from_slice(&data, width)\n\n}\n\n\n", "file_path": "benches/plane.rs", "rank": 95, "score": 183841.9542159572 }, { "content": "#[inline]\n\nfn stride_sse(a: &[i32], b: &[i32]) -> i64 {\n\n let mut acc: i32 = 0;\n\n for (a, b) in a.iter().take(b.len()).zip(b) {\n\n acc += (*a - *b) * (*a - *b)\n\n }\n\n acc as i64\n\n}\n\n\n\n#[inline]\n\nconst fn _level_to_limit(level: i32, shift: usize) -> i32 {\n\n level << shift\n\n}\n\n\n\n#[inline]\n\nconst fn limit_to_level(limit: i32, shift: usize) -> i32 {\n\n (limit + (1 << shift) - 1) >> shift\n\n}\n\n\n\n#[inline]\n\nconst fn _level_to_blimit(level: i32, shift: usize) -> i32 {\n", "file_path": "src/deblock.rs", "rank": 96, "score": 183803.8154035632 }, { "content": "fn init_plane_u8(width: usize, height: usize) -> Plane<u8> {\n\n let mut ra = ChaChaRng::from_seed([0; 32]);\n\n let data: Vec<u8> = (0..(width * height)).map(|_| ra.gen()).collect();\n\n let out = Plane::from_slice(&data, width);\n\n if out.cfg.width % 2 == 0 && out.cfg.height % 2 == 0 {\n\n out\n\n } else {\n\n let xpad = out.cfg.width % 2;\n\n let ypad = out.cfg.height % 2;\n\n let mut padded =\n\n Plane::new(out.cfg.width, out.cfg.height, 0, 0, xpad, ypad);\n\n let mut padded_slice = padded.mut_slice(PlaneOffset { x: 0, y: 0 });\n\n for (dst_row, src_row) in padded_slice.rows_iter_mut().zip(out.rows_iter())\n\n {\n\n dst_row[..out.cfg.width].copy_from_slice(&src_row[..out.cfg.width]);\n\n }\n\n padded\n\n }\n\n}\n\n\n", "file_path": "benches/plane.rs", "rank": 97, "score": 183724.00849805426 }, { "content": "fn fill_plane<T: Pixel>(ra: &mut ChaChaRng, plane: &mut Plane<T>) {\n\n let stride = plane.cfg.stride;\n\n for row in plane.data_origin_mut().chunks_mut(stride) {\n\n for pixel in row {\n\n let v: u8 = ra.gen();\n\n *pixel = T::cast_from(v);\n\n }\n\n }\n\n}\n\n\n", "file_path": "benches/mc.rs", "rank": 98, "score": 183526.5366885428 }, { "content": "fn fill_plane<T: Pixel>(ra: &mut ChaChaRng, plane: &mut Plane<T>) {\n\n let stride = plane.cfg.stride;\n\n for row in plane.data_origin_mut().chunks_mut(stride) {\n\n for pixel in row {\n\n let v: u8 = ra.gen();\n\n *pixel = T::cast_from(v);\n\n }\n\n }\n\n}\n\n\n", "file_path": "benches/dist.rs", "rank": 99, "score": 183526.5366885428 } ]
Rust
pnets_shrink/tests/standard_reduce_tests.rs
nicolasAmat/pnets
482d014001f31afe31bc1c47c08d5c1183bf78a3
use pnets::standard::Net; use pnets_shrink::modifications::{ Agglomeration, InequalityReduction, Modification, Reduction, TransitionElimination, }; use pnets_shrink::reducers::standard::{ IdentityPlaceReducer, IdentityTransitionReducer, ParallelPlaceReducer, ParallelTransitionReducer, SimpleChainReducer, SourceSinkReducer, }; use pnets_shrink::reducers::Reduce; #[test] fn simple_chain_agglomeration() { let parser = pnets_tina::Parser::new(include_str!("simple_chain_agglomeration.net").as_bytes()); let mut net = Net::from(parser.parse().unwrap()); let mut modifications = vec![]; SimpleChainReducer::reduce(&mut net, &mut modifications); assert_eq!( modifications[0], Modification::Agglomeration(Agglomeration { deleted_places: vec![ (net.get_index_by_name("p1").unwrap().as_place().unwrap(), 1), (net.get_index_by_name("p2").unwrap().as_place().unwrap(), 1) ], new_place: net.places.last_idx().unwrap(), constant: 0, factor: 1, }) ); } #[test] fn parallel_transitions_fusion() { let parser = pnets_tina::Parser::new(include_str!("parallel_transitions_fusion.net").as_bytes()); let mut net = Net::from(parser.parse().unwrap()); let mut modifications = vec![]; ParallelTransitionReducer::reduce(&mut net, &mut modifications); assert_eq!( modifications[0], Modification::TransitionElimination(TransitionElimination { deleted_transitions: vec![net .get_index_by_name("t1") .unwrap() .as_transition() .unwrap()] }) ); } #[test] fn parallel_places_fusion() { let parser = pnets_tina::Parser::new(include_str!("parallel_places_fusion.net").as_bytes()); let mut net = Net::from(parser.parse().unwrap()); let mut modifications = vec![]; ParallelPlaceReducer::reduce(&mut net, &mut modifications); assert_eq!( modifications[0], Modification::Reduction(Reduction { deleted_places: vec![(net.get_index_by_name("p1").unwrap().as_place().unwrap(), 1)], equals_to: vec![(net.get_index_by_name("p2").unwrap().as_place().unwrap(), 1)], constant: 0, }) ); } #[test] fn constant_places_elimination() { let parser = pnets_tina::Parser::new(include_str!("constant_places_elimination.net").as_bytes()); let mut net = Net::from(parser.parse().unwrap()); println!("{:?}", net); let mut modifications = vec![]; IdentityPlaceReducer::reduce(&mut net, &mut modifications); println!("{:?}", net); assert_eq!( modifications[0], Modification::Reduction(Reduction { deleted_places: vec![(net.get_index_by_name("p1").unwrap().as_place().unwrap(), 1)], equals_to: vec![], constant: 5, }) ); } #[test] fn source_sink_convert() { let parser = pnets_tina::Parser::new(include_str!("source_sink_convert.net").as_bytes()); let mut net = Net::from(parser.parse().unwrap()); let mut modifications = vec![]; SourceSinkReducer::reduce(&mut net, &mut modifications); assert_eq!( modifications[0], Modification::InequalityReduction(InequalityReduction { deleted_places: vec![(net.get_index_by_name("p1").unwrap().as_place().unwrap(), 1)], kept_places: vec![], constant: 5, }) ); } #[test] fn self_loop_place_elimination() { let parser = pnets_tina::Parser::new(include_str!("self_loop_place_eliminations.net").as_bytes()); let mut net = Net::from(parser.parse().unwrap()); let mut modifications = vec![]; IdentityPlaceReducer::reduce(&mut net, &mut modifications); assert_eq!( modifications[0], Modification::Reduction(Reduction { deleted_places: vec![(net.get_index_by_name("p1").unwrap().as_place().unwrap(), 1)], equals_to: vec![], constant: 5, }) ); } #[test] fn self_loop_transition_elimination() { let parser = pnets_tina::Parser::new(include_str!("self_loop_transition_eliminations.net").as_bytes()); let mut net = Net::from(parser.parse().unwrap()); let mut modifications = vec![]; IdentityTransitionReducer::reduce(&mut net, &mut modifications); assert_eq!( modifications[0], Modification::TransitionElimination(TransitionElimination { deleted_transitions: vec![net .get_index_by_name("t1") .unwrap() .as_transition() .unwrap()] }) ); }
use pnets::standard::Net; use pnets_shrink::modifications::{ Agglomeration, InequalityReduction, Modification, Reduction, TransitionElimination, }; use pnets_shrink::reducers::standard::{ IdentityPlaceReducer, IdentityTransitionReducer, ParallelPlaceReducer, ParallelTransitionReducer, SimpleChainReducer, SourceSinkReducer, }; use pnets_shrink::reducers::Reduce; #[test] fn simple_chain_agglomeration() { let parser = pnets_tina::Parser::new(include_str!("simple_chain_agglomeration.net").as_bytes()); let mut net = Net::from(parser.parse().unwrap()); let mut modifications = vec![]; SimpleChainReducer::reduce(&mut net, &mut modifications); assert_eq!( modifications[0], Modification::Agglomeration(Agglomeration { deleted_places: vec![ (net.get_index_by_name("p1").unwrap().as_place().unwrap(), 1), (net.get_index_by_name("p2").unwrap().as_place().unwrap(), 1) ], new_place: net.places.last_idx().unwrap(), constant: 0, factor: 1, }) ); } #[test] fn parallel_transitions_fusion() { let parser = pnets_tina::Parser::new(include_str!("parallel_transitions_fusion.net").as_bytes()); let mut net = Net::from(parser.parse().unwrap()); let mut modifications = vec![]; ParallelTransitionReducer::reduce(&mut net, &mut modifications); assert_eq!( modifications[0], Modification::TransitionElimination(TransitionElimination { deleted_transitions: vec![net .get_index_by_name("t1") .unwrap() .as_transition() .unwrap()] }) ); } #[test] fn parallel_places_fusion() { let parser = pnets_tina::Parser::new(include_str!("parallel_places_fusion.net").as_bytes()); let mut net = Net::from(parser.parse().unwrap()); let mut modifications = vec![]; ParallelPlaceReducer::reduce(&mut net, &mut modifications); assert_eq!( modifications[0], Modification::Reduction(Reduction { deleted_places: vec![(net.get_index_by_name("p1").unwrap().as_place().unwrap(), 1)], equals_to: vec![(net.get_index_by_name("p2").unwrap().as_place().unwrap(), 1)], constant: 0, }) ); } #[test] fn constant_places_elimination() { let parser = pnets_tina::Parser::new(include_str!("constant_places_elimination.net").as_bytes()); let mut net = Net::from(parser.parse().unwrap()); println!("{:?}", net); let mut modifications = vec![]; IdentityPlaceReducer::reduce(&mut net, &mut modifications); println!("{:?}", net); assert_eq!( modifications[0], Modification::Reduction(Reduction { deleted_places: vec![(net.get_index_by_name("p1").unwrap().as_place().unwrap(), 1)], equals_to: vec![], constant: 5, }) ); } #[test] fn source_sink_convert() { let parser = pnets_tina::Parser::new(include_str!("source_sink_convert.net").as_bytes()); let mut net = Net::from(parser.parse().unwrap()); let mut modifications = vec![]; SourceSinkReducer::reduce(&mut net, &mut modifications); assert_eq!( modifications[0], Modification::InequalityReduction(InequalityReduction { deleted_places: vec![(net.get_index_by_name("p1").unwrap().as_place().unwrap(), 1)], kept_places: vec![], constant: 5, }) ); } #[test] fn self_loop_place_elimination() { let parser = pnets_tina::Parser::new(include_str!("self_loop_place_eliminations.net").as_bytes()); let mut net = Net::from(parser.parse().unwrap()); let mut modifications = vec![]; IdentityPlaceReducer::reduce(&mut net, &mut modifications); assert_eq!( modifications[0], Modification::Reduction(Reduction { deleted_places: vec![(net.get_index_by_name("p1").unwrap().as_place().unwrap(), 1)], equals_to: vec![], constant: 5, }) ); } #[test]
fn self_loop_transition_elimination() { let parser = pnets_tina::Parser::new(include_str!("self_loop_transition_eliminations.net").as_bytes()); let mut net = Net::from(parser.parse().unwrap()); let mut modifications = vec![]; IdentityTransitionReducer::reduce(&mut net, &mut modifications); assert_eq!( modifications[0], Modification::TransitionElimination(TransitionElimination { deleted_transitions: vec![net .get_index_by_name("t1") .unwrap() .as_transition() .unwrap()] }) ); }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn create_transition_with_used_name() {\n\n let mut net = Net::default();\n\n let tr_1 = net.create_transition();\n\n net.rename_node(NodeId::Transition(tr_1), \"tr_1\").unwrap();\n\n let tr_2 = net.create_transition();\n\n assert_eq!(net.transitions.len(), 2);\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Transition(tr_1)).unwrap(),\n\n \"tr_1\".to_string()\n\n );\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Transition(tr_2)).unwrap(),\n\n \"a1\".to_string()\n\n );\n\n assert_eq!(net[tr_1].label, None);\n\n assert_eq!(net[tr_2].label, None);\n\n}\n\n\n", "file_path": "pnets/tests/timed_net_tests.rs", "rank": 0, "score": 143815.43828950217 }, { "content": "#[test]\n\nfn create_place_with_used_name() {\n\n let mut net = Net::default();\n\n let pl_1 = net.create_place();\n\n net.rename_node(NodeId::Place(pl_1), \"pl_1\").unwrap();\n\n let pl_2 = net.create_place();\n\n assert_eq!(net.places.len(), 2);\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Place(pl_1)).unwrap(),\n\n \"pl_1\".to_string()\n\n );\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Place(pl_2)).unwrap(),\n\n \"a1\".to_string()\n\n );\n\n assert_eq!(net[pl_1].label, None);\n\n assert_eq!(net[pl_2].label, None);\n\n}\n\n\n", "file_path": "pnets/tests/standard_net_tests.rs", "rank": 1, "score": 143815.43828950217 }, { "content": "#[test]\n\nfn create_place_with_used_name() {\n\n let mut net = Net::default();\n\n let pl_1 = net.create_place();\n\n net.rename_node(NodeId::Place(pl_1), \"pl_1\").unwrap();\n\n let pl_2 = net.create_place();\n\n assert_eq!(net.places.len(), 2);\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Place(pl_1)).unwrap(),\n\n \"pl_1\".to_string()\n\n );\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Place(pl_2)).unwrap(),\n\n \"a1\".to_string()\n\n );\n\n assert_eq!(net[pl_1].label, None);\n\n assert_eq!(net[pl_2].label, None);\n\n}\n\n\n", "file_path": "pnets/tests/timed_net_tests.rs", "rank": 2, "score": 143815.43828950217 }, { "content": "#[test]\n\nfn create_transition_with_used_name() {\n\n let mut net = Net::default();\n\n let tr_1 = net.create_transition();\n\n net.rename_node(NodeId::Transition(tr_1), \"tr_1\").unwrap();\n\n let tr_2 = net.create_transition();\n\n assert_eq!(net.transitions.len(), 2);\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Transition(tr_1)).unwrap(),\n\n \"tr_1\".to_string()\n\n );\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Transition(tr_2)).unwrap(),\n\n \"a1\".to_string()\n\n );\n\n assert_eq!(net[tr_1].label, None);\n\n assert_eq!(net[tr_2].label, None);\n\n}\n\n\n", "file_path": "pnets/tests/standard_net_tests.rs", "rank": 3, "score": 143815.43828950217 }, { "content": "#[test]\n\nfn transition_test() {\n\n let parser =\n\n pnets_tina::Parser::new(\"tr t0 : transition_label [1,5] p0*3 p2?4 p3?-2 -> p1\".as_bytes());\n\n\n\n let net = parser.parse().unwrap();\n\n\n\n // Check if all places and transitions are created\n\n let t0: TransitionId = net\n\n .get_index_by_name(&\"t0\".to_string())\n\n .unwrap()\n\n .as_transition()\n\n .unwrap();\n\n let p0 = net\n\n .get_index_by_name(&\"p0\".to_string())\n\n .unwrap()\n\n .as_place()\n\n .unwrap();\n\n let p1: PlaceId = net\n\n .get_index_by_name(&\"p1\".to_string())\n\n .unwrap()\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 4, "score": 123087.95619426854 }, { "content": "#[test]\n\nfn place_test() {\n\n let parser = pnets_tina::Parser::new(\"pl p0 : label (43K) t0 -> t1 t2?1M t3?-2K\".as_bytes());\n\n let net = parser.parse().unwrap();\n\n println!(\"{:?}\", net);\n\n\n\n let p0 = net\n\n .get_index_by_name(&\"p0\".to_string())\n\n .unwrap()\n\n .as_place()\n\n .unwrap();\n\n let t0 = net\n\n .get_index_by_name(&\"t0\".to_string())\n\n .unwrap()\n\n .as_transition()\n\n .unwrap();\n\n let t1 = net\n\n .get_index_by_name(&\"t1\".to_string())\n\n .unwrap()\n\n .as_transition()\n\n .unwrap();\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 5, "score": 123087.95619426854 }, { "content": "#[test]\n\nfn note_test() {\n\n let parser = pnets_tina::Parser::new(\"nt note 0 {This is a note}\".as_bytes());\n\n parser.parse().unwrap();\n\n}\n\n\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 6, "score": 123087.95619426854 }, { "content": "#[test]\n\nfn sokoban_3_test() {\n\n let parser = pnets_tina::Parser::new(include_str!(\"sokoban_3.net\").as_bytes());\n\n parser.parse().unwrap();\n\n}\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 7, "score": 123087.95619426854 }, { "content": "#[test]\n\nfn priority_test() {\n\n let parser = pnets_tina::Parser::new(\"\".as_bytes());\n\n parser.parse().unwrap();\n\n}\n\n\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 8, "score": 123087.95619426854 }, { "content": "#[test]\n\nfn name_test() {\n\n let parser = pnets_tina::Parser::new(\"net Name\".as_bytes());\n\n let net = parser.parse().unwrap();\n\n assert_eq!(net.name, \"Name\".to_string())\n\n}\n\n\n\n// Should panic because lb is not implemented\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 9, "score": 123087.95619426854 }, { "content": "#[test]\n\nfn abp_test() {\n\n let parser = pnets_tina::Parser::new(include_str!(\"abp.net\").as_bytes());\n\n parser.parse().unwrap();\n\n}\n\n\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 10, "score": 123087.95619426854 }, { "content": "#[test]\n\nfn label_test() {\n\n let parser = pnets_tina::Parser::new(\n\n \"tr t0 p0 -> p1\\nlb t0 {transition}\\nlb p0 {place 0}\\nlb p1 {place 1}\".as_bytes(),\n\n );\n\n let net = parser.parse().unwrap();\n\n let t0 = net\n\n .get_index_by_name(\"t0\")\n\n .unwrap()\n\n .as_transition()\n\n .unwrap();\n\n assert_eq!(net[t0].label, Some(\"transition\".to_string()));\n\n let p0 = net.get_index_by_name(\"p0\").unwrap().as_place().unwrap();\n\n assert_eq!(net[p0].label, Some(\"place 0\".to_string()));\n\n let p1 = net.get_index_by_name(\"p1\").unwrap().as_place().unwrap();\n\n assert_eq!(net[p1].label, Some(\"place 1\".to_string()));\n\n}\n\n\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 11, "score": 123087.95619426854 }, { "content": "#[test]\n\nfn demo_test() {\n\n let parser = pnets_tina::Parser::new(include_str!(\"demo.net\").as_bytes());\n\n parser.parse().unwrap();\n\n}\n\n\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 12, "score": 123087.95619426854 }, { "content": "#[test]\n\nfn ifip_test() {\n\n let parser = pnets_tina::Parser::new(include_str!(\"ifip.net\").as_bytes());\n\n parser.parse().unwrap();\n\n}\n\n\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 13, "score": 123087.95619426854 }, { "content": "#[test]\n\nfn places() {\n\n let mut net = Net::default();\n\n let tr = net.create_transition();\n\n let pl = net.create_place();\n\n net.add_arc(Kind::Consume(pl, tr, 1)).unwrap();\n\n net.add_arc(Kind::Produce(pl, tr, 1)).unwrap();\n\n assert_eq!(net[pl].id(), pl);\n\n assert_eq!(net[pl].is_disconnected(), false);\n\n net.delete_place(pl);\n\n assert_eq!(net[pl].is_disconnected(), true);\n\n assert_eq!(net[pl].id(), pl);\n\n}\n\n\n", "file_path": "pnets/tests/standard_net_tests.rs", "rank": 14, "score": 121138.08552991209 }, { "content": "#[test]\n\nfn transition() {\n\n let mut net = Net::default();\n\n let tr = net.create_transition();\n\n let pl = net.create_place();\n\n net.add_arc(Kind::Consume(pl, tr, 1)).unwrap();\n\n net.add_arc(Kind::Produce(pl, tr, 1)).unwrap();\n\n assert_eq!(net[tr].id(), tr);\n\n assert_eq!(net[tr].is_disconnected(), false);\n\n net.delete_transition(tr);\n\n assert_eq!(net[tr].is_disconnected(), true);\n\n assert_eq!(net[tr].id(), tr);\n\n}\n\n\n", "file_path": "pnets/tests/standard_net_tests.rs", "rank": 15, "score": 121138.08552991209 }, { "content": "#[test]\n\nfn places() {\n\n let mut net = Net::default();\n\n let tr = net.create_transition();\n\n let pl = net.create_place();\n\n net.add_arc(Kind::Consume(pl, tr, 1)).unwrap();\n\n net.add_arc(Kind::Produce(pl, tr, 1)).unwrap();\n\n net.add_arc(Kind::Inhibitor(pl, tr, 1)).unwrap();\n\n net.add_arc(Kind::Test(pl, tr, 1)).unwrap();\n\n assert_eq!(net[pl].id(), pl);\n\n assert_eq!(net[pl].is_disconnected(), false);\n\n net.delete_place(pl);\n\n assert_eq!(net[pl].is_disconnected(), true);\n\n assert_eq!(net[pl].id(), pl);\n\n}\n\n\n", "file_path": "pnets/tests/timed_net_tests.rs", "rank": 16, "score": 121138.08552991209 }, { "content": "#[test]\n\nfn transition() {\n\n let mut net = Net::default();\n\n let tr = net.create_transition();\n\n let pl = net.create_place();\n\n net.add_arc(Kind::Consume(pl, tr, 1)).unwrap();\n\n net.add_arc(Kind::Produce(pl, tr, 1)).unwrap();\n\n net.add_arc(Kind::Inhibitor(pl, tr, 1)).unwrap();\n\n net.add_arc(Kind::Test(pl, tr, 1)).unwrap();\n\n assert_eq!(net[tr].id(), tr);\n\n assert_eq!(net[tr].is_disconnected(), false);\n\n net.delete_transition(tr);\n\n assert_eq!(net[tr].is_disconnected(), true);\n\n assert_eq!(net[tr].id(), tr);\n\n}\n\n\n", "file_path": "pnets/tests/timed_net_tests.rs", "rank": 17, "score": 121138.08552991209 }, { "content": "#[test]\n\nfn update_priorities_test() {\n\n let mut net = Net::default();\n\n let t0 = net.create_transition();\n\n let t1 = net.create_transition();\n\n let t2 = net.create_transition();\n\n let t3 = net.create_transition();\n\n\n\n net.add_priority(t0, t1);\n\n net.add_priority(t0, t2);\n\n net.add_priority(t1, t2);\n\n net.add_priority(t2, t3);\n\n\n\n assert!(net.update_priorities().is_ok());\n\n assert_eq!(net[t0].priorities, vec![t1, t2, t3]);\n\n assert_eq!(net[t1].priorities, vec![t2, t3]);\n\n assert_eq!(net[t2].priorities, vec![t3]);\n\n assert_eq!(net[t3].priorities, vec![]);\n\n}\n\n\n", "file_path": "pnets/tests/timed_net_tests.rs", "rank": 18, "score": 119993.4805131504 }, { "content": "#[test]\n\nfn create_transition() {\n\n let mut net = Net::default();\n\n let i = net.create_transition();\n\n assert_eq!(net.transitions.len(), 1);\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Transition(i)).unwrap(),\n\n \"0\".to_string()\n\n )\n\n}\n\n\n", "file_path": "pnets/tests/timed_net_tests.rs", "rank": 19, "score": 118206.14284224808 }, { "content": "#[test]\n\nfn rename_node() {\n\n let mut net = Net::default();\n\n let tr = net.create_transition();\n\n let pl = net.create_place();\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Transition(tr)),\n\n Some(\"0\".to_string())\n\n );\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Place(pl)),\n\n Some(\"1\".to_string())\n\n );\n\n assert_eq!(net.rename_node(NodeId::Place(pl), \"pl\"), Ok(()));\n\n assert_eq!(net.rename_node(NodeId::Transition(tr), \"tr\"), Ok(()));\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Transition(tr)),\n\n Some(\"tr\".to_string())\n\n );\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Place(pl)),\n", "file_path": "pnets/tests/timed_net_tests.rs", "rank": 20, "score": 118206.14284224808 }, { "content": "#[test]\n\nfn create_place() {\n\n let mut net = Net::default();\n\n let i = net.create_place();\n\n assert_eq!(net.places.len(), 1);\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Place(i)).unwrap(),\n\n \"0\".to_string()\n\n );\n\n assert_eq!(net[i].label, None);\n\n}\n\n\n", "file_path": "pnets/tests/timed_net_tests.rs", "rank": 21, "score": 118206.14284224808 }, { "content": "#[test]\n\nfn create_transition() {\n\n let mut net = Net::default();\n\n let i = net.create_transition();\n\n assert_eq!(net.transitions.len(), 1);\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Transition(i)).unwrap(),\n\n \"0\".to_string()\n\n )\n\n}\n\n\n", "file_path": "pnets/tests/standard_net_tests.rs", "rank": 22, "score": 118206.14284224808 }, { "content": "#[test]\n\nfn rename_node() {\n\n let mut net = Net::default();\n\n let tr = net.create_transition();\n\n let pl = net.create_place();\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Transition(tr)),\n\n Some(\"0\".to_string())\n\n );\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Place(pl)),\n\n Some(\"1\".to_string())\n\n );\n\n assert_eq!(net.rename_node(NodeId::Place(pl), \"pl\"), Ok(()));\n\n assert_eq!(net.rename_node(NodeId::Transition(tr), \"tr\"), Ok(()));\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Transition(tr)),\n\n Some(\"tr\".to_string())\n\n );\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Place(pl)),\n", "file_path": "pnets/tests/standard_net_tests.rs", "rank": 23, "score": 118206.14284224808 }, { "content": "#[test]\n\nfn create_place() {\n\n let mut net = Net::default();\n\n let i = net.create_place();\n\n assert_eq!(net.places.len(), 1);\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Place(i)).unwrap(),\n\n \"0\".to_string()\n\n );\n\n assert_eq!(net[i].label, None);\n\n}\n\n\n", "file_path": "pnets/tests/standard_net_tests.rs", "rank": 24, "score": 118206.14284224808 }, { "content": "#[test]\n\nfn name_test_invalid_identifier() {\n\n let parser = pnets_tina::Parser::new(\"net *\".as_bytes());\n\n assert_eq!(parser.parse().is_ok(), false);\n\n}\n\n\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 25, "score": 117946.6631700272 }, { "content": "#[test]\n\nfn node_transition_cast_test() {\n\n let tr = TransitionId::from(0);\n\n assert_eq!(\n\n NodeId::Transition(tr).as_transition(),\n\n Some(TransitionId::from(0))\n\n );\n\n assert_eq!(NodeId::Transition(tr).as_place(), None);\n\n}\n\n\n", "file_path": "pnets/tests/timed_net_tests.rs", "rank": 26, "score": 117504.12186480532 }, { "content": "#[test]\n\nfn node_place_cast_test() {\n\n let pl = PlaceId::from(0);\n\n assert_eq!(NodeId::Place(pl).as_transition(), None);\n\n assert_eq!(NodeId::Place(pl).as_place(), Some(PlaceId::from(0)));\n\n}\n", "file_path": "pnets/tests/standard_net_tests.rs", "rank": 27, "score": 117504.12186480532 }, { "content": "#[test]\n\nfn node_transition_cast_test() {\n\n let tr = TransitionId::from(0);\n\n assert_eq!(\n\n NodeId::Transition(tr).as_transition(),\n\n Some(TransitionId::from(0))\n\n );\n\n assert_eq!(NodeId::Transition(tr).as_place(), None);\n\n}\n\n\n", "file_path": "pnets/tests/standard_net_tests.rs", "rank": 28, "score": 117504.12186480532 }, { "content": "#[test]\n\nfn node_place_cast_test() {\n\n let pl = PlaceId::from(0);\n\n assert_eq!(NodeId::Place(pl).as_transition(), None);\n\n assert_eq!(NodeId::Place(pl).as_place(), Some(PlaceId::from(0)));\n\n}\n", "file_path": "pnets/tests/timed_net_tests.rs", "rank": 29, "score": 117504.12186480532 }, { "content": "#[test]\n\nfn test_get() {\n\n let mut marking: Marking<usize> = Default::default();\n\n marking.insert_or_add(2, 2);\n\n marking.insert_or_add(1, 3);\n\n marking.insert_or_add(3, 1);\n\n marking.insert_or_add(5, 5);\n\n\n\n assert_eq!(marking[1], 3);\n\n assert_eq!(marking[2], 2);\n\n assert_eq!(marking[3], 1);\n\n assert_eq!(marking[4], 0);\n\n assert_eq!(marking[5], 5);\n\n assert_eq!(marking[52], 0);\n\n}\n\n\n", "file_path": "pnets/tests/marking_tests.rs", "rank": 32, "score": 92419.59790721169 }, { "content": "#[test]\n\nfn test_insert_or_add() {\n\n let mut marking: Marking<usize> = Default::default();\n\n marking.insert_or_add(2, 2);\n\n marking.insert_or_add(1, 3);\n\n marking.insert_or_add(3, 1);\n\n marking.insert_or_add(2, 2);\n\n marking.insert_or_add(5, 5);\n\n marking.insert_or_add(4, 4);\n\n\n\n assert_eq!(marking[1], 3);\n\n assert_eq!(marking[2], 4);\n\n assert_eq!(marking[3], 1);\n\n assert_eq!(marking[4], 4);\n\n assert_eq!(marking[5], 5);\n\n}\n\n\n", "file_path": "pnets/tests/marking_tests.rs", "rank": 33, "score": 90683.90354554896 }, { "content": "#[test]\n\nfn test_insert_or_max() {\n\n let mut marking: Marking<usize> = Default::default();\n\n marking.insert_or_max(2, 2);\n\n marking.insert_or_max(2, 3);\n\n marking.insert_or_max(2, 2);\n\n marking.insert_or_max(5, 5);\n\n marking.insert_or_max(4, 4);\n\n\n\n assert_eq!(marking[2], 3);\n\n assert_eq!(marking[4], 4);\n\n assert_eq!(marking[5], 5);\n\n}\n\n\n", "file_path": "pnets/tests/marking_tests.rs", "rank": 34, "score": 90683.90354554896 }, { "content": "#[test]\n\nfn test_insert_or_min() {\n\n let mut marking: Marking<usize> = Default::default();\n\n marking.insert_or_min(2, 2);\n\n marking.insert_or_min(1, 3);\n\n marking.insert_or_min(1, 1);\n\n marking.insert_or_min(2, 2);\n\n marking.insert_or_min(5, 5);\n\n marking.insert_or_min(4, 4);\n\n\n\n assert_eq!(marking[1], 1);\n\n assert_eq!(marking[2], 2);\n\n assert_eq!(marking[4], 4);\n\n assert_eq!(marking[5], 5);\n\n}\n\n\n", "file_path": "pnets/tests/marking_tests.rs", "rank": 35, "score": 90683.90354554896 }, { "content": "#[test]\n\nfn test_dual_iterator_right() {\n\n let marking_1: Marking<usize> = Default::default();\n\n let mut marking_2: Marking<usize> = Default::default();\n\n marking_2.insert_or_max(0, 1);\n\n marking_2.insert_or_max(1, 1);\n\n marking_2.insert_or_max(2, 1);\n\n for (idx, v1, v2) in marking_1.iter_with(&marking_2) {\n\n assert_eq!(v1, marking_1[idx]);\n\n assert_eq!(v2, marking_2[idx]);\n\n }\n\n}\n", "file_path": "pnets/tests/marking_tests.rs", "rank": 36, "score": 89032.04317986383 }, { "content": "#[test]\n\nfn test_dual_iterator_left() {\n\n let mut marking_1: Marking<usize> = Default::default();\n\n let marking_2: Marking<usize> = Default::default();\n\n marking_1.insert_or_max(0, 1);\n\n marking_1.insert_or_max(1, 1);\n\n marking_1.insert_or_max(2, 1);\n\n for (idx, v1, v2) in marking_1.iter_with(&marking_2) {\n\n assert_eq!(v1, marking_1[idx]);\n\n assert_eq!(v2, marking_2[idx]);\n\n }\n\n}\n\n\n", "file_path": "pnets/tests/marking_tests.rs", "rank": 37, "score": 89032.04317986383 }, { "content": "#[test]\n\nfn test_dual_iterator_rand() {\n\n let mut marking_1: Marking<usize> = Default::default();\n\n let mut marking_2: Marking<usize> = Default::default();\n\n for _ in 0..fastrand::usize(0..1000) {\n\n marking_1.insert_or_max(\n\n fastrand::usize(0..usize::MAX),\n\n fastrand::usize(0..usize::MAX),\n\n );\n\n }\n\n for _ in 0..fastrand::usize(0..1000) {\n\n marking_2.insert_or_max(\n\n fastrand::usize(0..usize::MAX),\n\n fastrand::usize(0..usize::MAX),\n\n );\n\n }\n\n for (idx, v1, v2) in marking_1.iter_with(&marking_2) {\n\n assert_eq!(v1, marking_1[idx]);\n\n assert_eq!(v2, marking_2[idx]);\n\n }\n\n}\n\n\n", "file_path": "pnets/tests/marking_tests.rs", "rank": 38, "score": 89032.04317986383 }, { "content": "fn write_modifications(\n\n modifications: &[Modification],\n\n writer: &mut dyn Write,\n\n net: &Net,\n\n) -> Result<(), Box<dyn Error>> {\n\n writer.write_all(\"# generated equations\\n\".as_ref())?;\n\n for modification in modifications {\n\n match modification {\n\n Modification::Agglomeration(agg) => {\n\n if agg.factor == 1 {\n\n writer.write_all(\n\n format!(\n\n \"# A |- {} = \",\n\n net.get_name_by_index(&NodeId::Place(agg.new_place))\n\n .unwrap()\n\n )\n\n .as_ref(),\n\n )?;\n\n } else {\n\n writer.write_all(\n", "file_path": "pnets_shrink/src/main.rs", "rank": 44, "score": 79887.20780185173 }, { "content": " let t2 = net\n\n .get_index_by_name(&\"t2\".to_string())\n\n .unwrap()\n\n .as_transition()\n\n .unwrap();\n\n let t3 = net\n\n .get_index_by_name(&\"t3\".to_string())\n\n .unwrap()\n\n .as_transition()\n\n .unwrap();\n\n\n\n assert_eq!(net.get_name_by_index(&t0.into()).unwrap(), \"t0\".to_string());\n\n assert_eq!(net.get_name_by_index(&t1.into()).unwrap(), \"t1\".to_string());\n\n assert_eq!(net.get_name_by_index(&t2.into()).unwrap(), \"t2\".to_string());\n\n assert_eq!(net.get_name_by_index(&t3.into()).unwrap(), \"t3\".to_string());\n\n assert_eq!(net.get_name_by_index(&p0.into()).unwrap(), \"p0\".to_string());\n\n\n\n assert_eq!(net[p0].label, Some(\"label\".to_string()));\n\n assert_eq!(net[p0].initial, 43000);\n\n\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 45, "score": 77744.59969557908 }, { "content": " .as_place()\n\n .unwrap();\n\n let p2: PlaceId = net\n\n .get_index_by_name(&\"p2\".to_string())\n\n .unwrap()\n\n .as_place()\n\n .unwrap();\n\n let p3: PlaceId = net\n\n .get_index_by_name(&\"p3\".to_string())\n\n .unwrap()\n\n .as_place()\n\n .unwrap();\n\n\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Transition(t0)).unwrap(),\n\n \"t0\".to_string()\n\n );\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Place(p0)).unwrap(),\n\n \"p0\".to_string()\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 46, "score": 77744.31463129037 }, { "content": "use pnets::timed::{Bound, TimeRange};\n\nuse pnets::{NodeId, PlaceId, TransitionId};\n\n\n\n#[test]\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 47, "score": 77743.64032938647 }, { "content": " );\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Place(p1)).unwrap(),\n\n \"p1\".to_string()\n\n );\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Place(p2)).unwrap(),\n\n \"p2\".to_string()\n\n );\n\n assert_eq!(\n\n net.get_name_by_index(&NodeId::Place(p3)).unwrap(),\n\n \"p3\".to_string()\n\n );\n\n\n\n // Check transition information\n\n assert_eq!(\n\n net[t0].time,\n\n TimeRange {\n\n start: Bound::Closed(1),\n\n end: Bound::Closed(5),\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 48, "score": 77743.36062319315 }, { "content": " assert_eq!(net[p2].produced_by[t0], 0);\n\n assert_eq!(net[p3].produced_by[t0], 0);\n\n\n\n assert_eq!(net[t0].conditions[p0], 0);\n\n assert_eq!(net[t0].conditions[p1], 0);\n\n assert_eq!(net[t0].conditions[p2], 4);\n\n assert_eq!(net[t0].conditions[p3], 0);\n\n\n\n assert_eq!(net[p0].condition_for[t0], 0);\n\n assert_eq!(net[p1].condition_for[t0], 0);\n\n assert_eq!(net[p2].condition_for[t0], 4);\n\n assert_eq!(net[p3].condition_for[t0], 0);\n\n\n\n assert_eq!(net[t0].inhibitors[p0], 0);\n\n assert_eq!(net[t0].inhibitors[p1], 0);\n\n assert_eq!(net[t0].inhibitors[p2], 0);\n\n assert_eq!(net[t0].inhibitors[p3], 2);\n\n\n\n assert_eq!(net[p0].inhibitor_for[t0], 0);\n\n assert_eq!(net[p1].inhibitor_for[t0], 0);\n\n assert_eq!(net[p2].inhibitor_for[t0], 0);\n\n assert_eq!(net[p3].inhibitor_for[t0], 2);\n\n}\n\n\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 49, "score": 77740.2971454341 }, { "content": " assert_eq!(net[t0].produce[p0], 1);\n\n assert_eq!(net[t1].produce[p0], 0);\n\n assert_eq!(net[t2].produce[p0], 0);\n\n assert_eq!(net[t3].produce[p0], 0);\n\n\n\n assert_eq!(net[p0].produced_by[t0], 1);\n\n assert_eq!(net[p0].produced_by[t1], 0);\n\n assert_eq!(net[p0].produced_by[t2], 0);\n\n assert_eq!(net[p0].produced_by[t3], 0);\n\n\n\n assert_eq!(net[t0].consume[p0], 0);\n\n assert_eq!(net[t1].consume[p0], 1);\n\n assert_eq!(net[t2].consume[p0], 0);\n\n assert_eq!(net[t3].consume[p0], 0);\n\n\n\n assert_eq!(net[p0].consumed_by[t0], 0);\n\n assert_eq!(net[p0].consumed_by[t1], 1);\n\n assert_eq!(net[p0].consumed_by[t2], 0);\n\n assert_eq!(net[p0].consumed_by[t3], 0);\n\n\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 50, "score": 77740.28905672493 }, { "content": " assert_eq!(net[t0].conditions[p0], 0);\n\n assert_eq!(net[t1].conditions[p0], 0);\n\n assert_eq!(net[t2].conditions[p0], 1_000_000);\n\n assert_eq!(net[t3].conditions[p0], 0);\n\n\n\n assert_eq!(net[p0].condition_for[t0], 0);\n\n assert_eq!(net[p0].condition_for[t1], 0);\n\n assert_eq!(net[p0].condition_for[t2], 1_000_000);\n\n assert_eq!(net[p0].condition_for[t3], 0);\n\n\n\n assert_eq!(net[t0].inhibitors[p0], 0);\n\n assert_eq!(net[t1].inhibitors[p0], 0);\n\n assert_eq!(net[t2].inhibitors[p0], 0);\n\n assert_eq!(net[t3].inhibitors[p0], 2000);\n\n\n\n assert_eq!(net[p0].inhibitor_for[t0], 0);\n\n assert_eq!(net[p0].inhibitor_for[t1], 0);\n\n assert_eq!(net[p0].inhibitor_for[t2], 0);\n\n assert_eq!(net[p0].inhibitor_for[t3], 2_000);\n\n}\n\n\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 51, "score": 77740.28905672493 }, { "content": " }\n\n );\n\n assert_eq!(net[t0].label, Some(\"transition_label\".to_string()));\n\n assert_eq!(net[t0].consume[p0], 3);\n\n assert_eq!(net[t0].consume[p1], 0);\n\n assert_eq!(net[t0].consume[p2], 0);\n\n assert_eq!(net[t0].consume[p3], 0);\n\n\n\n assert_eq!(net[p0].consumed_by[t0], 3);\n\n assert_eq!(net[p1].consumed_by[t0], 0);\n\n assert_eq!(net[p2].consumed_by[t0], 0);\n\n assert_eq!(net[p3].consumed_by[t0], 0);\n\n\n\n assert_eq!(net[t0].produce[p0], 0);\n\n assert_eq!(net[t0].produce[p1], 1);\n\n assert_eq!(net[t0].produce[p2], 0);\n\n assert_eq!(net[t0].produce[p3], 0);\n\n\n\n assert_eq!(net[p0].produced_by[t0], 0);\n\n assert_eq!(net[p1].produced_by[t0], 1);\n", "file_path": "pnets_tina/tests/parser_tests.rs", "rank": 52, "score": 77740.27269971502 }, { "content": "use pnets::arc::Kind;\n\nuse pnets::standard::Net;\n\nuse pnets::{NetError, NodeId, PlaceId, TransitionId};\n\n\n\n#[test]\n", "file_path": "pnets/tests/standard_net_tests.rs", "rank": 53, "score": 77245.65206106889 }, { "content": "use pnets::arc::Kind;\n\nuse pnets::timed::Net;\n\nuse pnets::{NetError, NodeId, PlaceId, TransitionId};\n\n\n\n#[test]\n", "file_path": "pnets/tests/timed_net_tests.rs", "rank": 54, "score": 77245.65206106889 }, { "content": " Some(\"pl\".to_string())\n\n );\n\n assert_eq!(\n\n net.rename_node(NodeId::Place(pl), \"tr\"),\n\n Err(NetError::DuplicatedName(\"tr\".to_string()))\n\n );\n\n assert_eq!(\n\n net.rename_node(NodeId::Transition(tr), \"pl\"),\n\n Err(NetError::DuplicatedName(\"pl\".to_string()))\n\n );\n\n}\n\n\n", "file_path": "pnets/tests/timed_net_tests.rs", "rank": 55, "score": 77238.00200810182 }, { "content": " Some(\"pl\".to_string())\n\n );\n\n assert_eq!(\n\n net.rename_node(NodeId::Place(pl), \"tr\"),\n\n Err(NetError::DuplicatedName(\"tr\".to_string()))\n\n );\n\n assert_eq!(\n\n net.rename_node(NodeId::Transition(tr), \"pl\"),\n\n Err(NetError::DuplicatedName(\"pl\".to_string()))\n\n );\n\n}\n\n\n", "file_path": "pnets/tests/standard_net_tests.rs", "rank": 56, "score": 77238.00200810182 }, { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n let mut net = standard::Net::default();\n\n // Create places and transitions\n\n let pl_0 = net.create_place();\n\n let pl_1 = net.create_place();\n\n let pl_2 = net.create_place();\n\n let pl_3 = net.create_place();\n\n let pl_4 = net.create_place();\n\n let pl_5 = net.create_place();\n\n let pl_6 = net.create_place();\n\n let tr_0 = net.create_transition();\n\n let tr_1 = net.create_transition();\n\n let tr_2 = net.create_transition();\n\n let tr_3 = net.create_transition();\n\n let tr_4 = net.create_transition();\n\n // Rename node (by default they have automatic name)\n\n net.rename_node(pl_0.into(), \"p0\")?;\n\n net.rename_node(pl_1.into(), \"p1\")?;\n\n net.rename_node(pl_2.into(), \"p2\")?;\n\n net.rename_node(pl_3.into(), \"p3\")?;\n", "file_path": "pnets/examples/net.rs", "rank": 57, "score": 69966.71426996593 }, { "content": "/// All reduction which implement this trait should keep the count of markings (the set of equations\n\n/// should has exactly the same number of solutions than the original net)\n\npub trait ConservativeReduce<Net>: Reduce<Net> {}\n\n\n\n/// Try to apply a reduction rule on a specific place\n", "file_path": "pnets_shrink/src/reducers/reduce.rs", "rank": 58, "score": 58782.86410753522 }, { "content": "#[allow(clippy::module_name_repetitions)]\n\npub trait TransitionReduce<Net>: Reduce<Net> {\n\n /// Try to apply a reduction rule on a specific place\n\n fn transition_reduce(\n\n &self,\n\n net: &mut Net,\n\n tr: TransitionId,\n\n modifications: &mut Vec<Modification>,\n\n );\n\n}\n", "file_path": "pnets_shrink/src/reducers/reduce.rs", "rank": 59, "score": 58775.961958114116 }, { "content": "#[allow(clippy::module_name_repetitions)]\n\npub trait PlaceReduce<Net>: Reduce<Net> {\n\n /// Try to apply a reduction rule on a specific place\n\n fn place_reduce(&self, net: &mut Net, pl: PlaceId, modifications: &mut Vec<Modification>);\n\n}\n\n\n\n/// Try to apply a reduction rule on a specific place\n", "file_path": "pnets_shrink/src/reducers/reduce.rs", "rank": 60, "score": 58775.961958114116 }, { "content": "/// Apply a reduction rule to the net\n\npub trait Reduce<Net> {\n\n /// Compute a reduction rule on the net\n\n ///\n\n /// In general, this method should iterate over each place or transition and try to apply the\n\n /// reduction to each place or transition.\n\n fn reduce(&self, net: &mut Net, modifications: &mut Vec<Modification>);\n\n}\n\n\n", "file_path": "pnets_shrink/src/reducers/reduce.rs", "rank": 61, "score": 47964.48140345342 }, { "content": "fn new_redundant(\n\n args: &Args,\n\n) -> LoopReducer<\n\n Net,\n\n ChainReducer<\n\n Net,\n\n SmartReducer<\n\n Net,\n\n ChainReducer<\n\n Net,\n\n SmartReducer<\n\n Net,\n\n IdentityPlaceReducer,\n\n ParallelPlaceReducer,\n\n ParallelTransitionReducer,\n\n >,\n\n ChainReducer<Net, IdentityTransitionReducer, SourceSinkReducer>,\n\n >,\n\n ParallelPlaceReducer,\n\n ParallelTransitionReducer,\n", "file_path": "pnets_shrink/src/main.rs", "rank": 62, "score": 45895.95308670159 }, { "content": "fn write_output(\n\n net: &Net,\n\n modifications: &[Modification],\n\n args: Args,\n\n) -> Result<(), Box<dyn Error>> {\n\n info!(\"Start writing new net.\");\n\n let now = SystemTime::now();\n\n let mut buf_writer: Box<dyn Write> = match args.output.as_ref() {\n\n \"-\" => Box::new(stdout()),\n\n s => Box::new(File::create(s)?),\n\n };\n\n\n\n if args.equations {\n\n write_modifications(&modifications, buf_writer.as_mut(), &net)?;\n\n }\n\n ExporterBuilder::new(buf_writer.as_mut())\n\n .with_all_places(!args.clean)\n\n .with_disconnected_transitions(args.clean)\n\n .build()\n\n .export(&net.into())?;\n\n info!(\"Writing done: {:?}.\", now.elapsed()?);\n\n Ok(())\n\n}\n\n\n", "file_path": "pnets_shrink/src/main.rs", "rank": 63, "score": 45895.95308670159 }, { "content": "fn new_compact(\n\n args: &Args,\n\n) -> LoopReducer<Net, ChainReducer<Net, SimpleChainReducer, SimpleLoopAgglomeration>> {\n\n LoopReducer::new(\n\n ChainReducer::new2(SimpleChainReducer::new(), SimpleLoopAgglomeration::new()),\n\n args.max_iter,\n\n )\n\n}\n\n\n", "file_path": "pnets_shrink/src/main.rs", "rank": 64, "score": 45895.95308670159 }, { "content": "fn new_extra(\n\n args: &Args,\n\n) -> LoopReducer<\n\n Net,\n\n ChainReducer<Net, PseudoStart, ChainReducer<Net, RLReducer, WeightSimplification>>,\n\n> {\n\n LoopReducer::new(\n\n ChainReducer::new3(\n\n PseudoStart::new(),\n\n RLReducer::new(),\n\n WeightSimplification::new(),\n\n ),\n\n args.max_iter,\n\n )\n\n}\n\n\n", "file_path": "pnets_shrink/src/main.rs", "rank": 65, "score": 45895.95308670159 }, { "content": "fn new_redundant_compact(\n\n args: &Args,\n\n) -> LoopReducer<\n\n Net,\n\n ChainReducer<\n\n Net,\n\n SmartReducer<\n\n Net,\n\n ChainReducer<Net, IdentityPlaceReducer, SimpleLoopAgglomeration>,\n\n ParallelPlaceReducer,\n\n ParallelTransitionReducer,\n\n >,\n\n ChainReducer<\n\n Net,\n\n SmartReducer<\n\n Net,\n\n SimpleChainReducer,\n\n ChainReducer<Net, IdentityPlaceReducer, SourceSinkReducer>,\n\n IdentityTransitionReducer,\n\n >,\n", "file_path": "pnets_shrink/src/main.rs", "rank": 66, "score": 44854.690887524084 }, { "content": "fn new_compact_extra(\n\n args: &Args,\n\n) -> LoopReducer<\n\n Net,\n\n ChainReducer<\n\n Net,\n\n SimpleLoopAgglomeration,\n\n ChainReducer<\n\n Net,\n\n SimpleChainReducer,\n\n ChainReducer<Net, PseudoStart, ChainReducer<Net, RLReducer, WeightSimplification>>,\n\n >,\n\n >,\n\n> {\n\n LoopReducer::new(\n\n ChainReducer::new5(\n\n SimpleLoopAgglomeration::new(),\n\n SimpleChainReducer::new(),\n\n PseudoStart::new(),\n\n RLReducer::new(),\n\n WeightSimplification::new(),\n\n ),\n\n args.max_iter,\n\n )\n\n}\n\n\n", "file_path": "pnets_shrink/src/main.rs", "rank": 67, "score": 44854.690887524084 }, { "content": "fn new_redundant_extra(\n\n args: &Args,\n\n) -> LoopReducer<\n\n Net,\n\n ChainReducer<\n\n Net,\n\n SmartReducer<\n\n Net,\n\n ChainReducer<\n\n Net,\n\n SmartReducer<\n\n Net,\n\n IdentityPlaceReducer,\n\n ParallelPlaceReducer,\n\n ParallelTransitionReducer,\n\n >,\n\n ChainReducer<\n\n Net,\n\n IdentityTransitionReducer,\n\n ChainReducer<\n", "file_path": "pnets_shrink/src/main.rs", "rank": 68, "score": 44854.690887524084 }, { "content": "use pnets::Marking;\n\n\n\n#[test]\n", "file_path": "pnets/tests/marking_tests.rs", "rank": 69, "score": 44098.27558121698 }, { "content": "fn new_redundant_compact_extra(\n\n args: &Args,\n\n) -> LoopReducer<\n\n Net,\n\n ChainReducer<\n\n Net,\n\n SmartReducer<\n\n Net,\n\n ChainReducer<\n\n Net,\n\n SmartReducer<\n\n Net,\n\n ChainReducer<Net, IdentityPlaceReducer, SimpleLoopAgglomeration>,\n\n ParallelPlaceReducer,\n\n ParallelTransitionReducer,\n\n >,\n\n ChainReducer<\n\n Net,\n\n IdentityTransitionReducer,\n\n ChainReducer<\n", "file_path": "pnets_shrink/src/main.rs", "rank": 70, "score": 43876.8349133374 }, { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n let matches = App::new(\"Net print\")\n\n .version(\"1.0\")\n\n .author(\"Louis C. <[email protected]>\")\n\n .about(\"Print a petri net from .net file\")\n\n .arg(\n\n Arg::with_name(\"INPUT\")\n\n .help(\"Sets the input file to use\")\n\n .required(true)\n\n .index(1),\n\n )\n\n .arg(\n\n Arg::with_name(\"CONTENT\")\n\n .help(\"Print net content\")\n\n .short(\"c\")\n\n .long(\"content\"),\n\n )\n\n .get_matches();\n\n\n\n let net = match matches.value_of(\"INPUT\") {\n", "file_path": "pnets_print/src/main.rs", "rank": 72, "score": 38085.206759697256 }, { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n let mut args = Args::parse();\n\n\n\n info!(\"Start parsing.\");\n\n let now = SystemTime::now();\n\n let buf_reader: Box<dyn BufRead> = match (args.input.as_ref(), args.format) {\n\n (\"-\", Format::Guess) => {\n\n args.format = Format::Net;\n\n Box::new(BufReader::new(stdin()))\n\n }\n\n (\"-\", _) => Box::new(BufReader::new(stdin())),\n\n (s, Format::Guess) => {\n\n if s.ends_with(\"pnml\") {\n\n args.format = Format::PNML;\n\n }\n\n Box::new(BufReader::new(File::open(s)?))\n\n }\n\n (s, _) => Box::new(BufReader::new(File::open(s)?)),\n\n };\n\n\n", "file_path": "pnets_shrink/src/main.rs", "rank": 73, "score": 38085.206759697256 }, { "content": " net.add_arc(arc::Kind::Consume(pl_6, tr_4, 1))?;\n\n net.add_arc(arc::Kind::Consume(pl_3, tr_4, 1))?;\n\n net.add_arc(arc::Kind::Consume(pl_3, tr_2, 1))?;\n\n net.add_arc(arc::Kind::Consume(pl_5, tr_3, 1))?;\n\n net.add_arc(arc::Kind::Consume(pl_4, tr_3, 1))?;\n\n net.add_arc(arc::Kind::Consume(pl_2, tr_3, 1))?;\n\n net.add_arc(arc::Kind::Consume(pl_1, tr_1, 1))?;\n\n net.add_arc(arc::Kind::Consume(pl_0, tr_0, 1))?;\n\n net.add_arc(arc::Kind::Produce(pl_3, tr_4, 1))?;\n\n net.add_arc(arc::Kind::Produce(pl_3, tr_0, 1))?;\n\n net.add_arc(arc::Kind::Produce(pl_4, tr_2, 1))?;\n\n net.add_arc(arc::Kind::Produce(pl_1, tr_0, 1))?;\n\n net.add_arc(arc::Kind::Produce(pl_0, tr_0, 1))?;\n\n\n\n // Get node id by its name\n\n println!(\n\n \"Place with name p0 has id {:?}\",\n\n net.get_index_by_name(\"p0\")\n\n );\n\n // Get node name\n\n println!(\n\n \"Transition with id {:?} has name {}\",\n\n NodeId::Transition(tr_0),\n\n net.get_name_by_index(&tr_0.into()).unwrap()\n\n );\n\n Ok(())\n\n}\n", "file_path": "pnets/examples/net.rs", "rank": 74, "score": 36528.95593387334 }, { "content": "use custom_derive::custom_derive;\n\nuse indexed_vec::Idx;\n\nuse newtype_derive::{\n\n newtype_as_item, newtype_fmt, newtype_wrap_bin_op, newtype_wrap_bin_op_assign, NewtypeAdd,\n\n NewtypeAddAssign, NewtypeDebug, NewtypeDisplay,\n\n};\n\n\n\ncustom_derive! {\n\n /// Represent a transition identifier in the net\n\n #[derive(\n\n Ord, PartialOrd, Clone, Copy, Eq, PartialEq, Hash,\n\n NewtypeDebug, NewtypeDisplay, NewtypeAddAssign(usize), Default, NewtypeAdd(usize)\n\n )]\n\n pub struct TransitionId(usize);\n\n}\n\n\n\nimpl Idx for TransitionId {\n\n fn new(v: usize) -> Self {\n\n Self::from(v)\n\n }\n", "file_path": "pnets/src/net.rs", "rank": 75, "score": 36528.35975460675 }, { "content": " net.rename_node(pl_4.into(), \"p4\")?;\n\n net.rename_node(pl_5.into(), \"p5\")?;\n\n net.rename_node(pl_6.into(), \"p6\")?;\n\n net.rename_node(tr_0.into(), \"t0\")?;\n\n net.rename_node(tr_1.into(), \"t1\")?;\n\n net.rename_node(tr_2.into(), \"t2\")?;\n\n net.rename_node(tr_3.into(), \"t3\")?;\n\n net.rename_node(tr_4.into(), \"t4\")?;\n\n\n\n // Set label for places and transitions\n\n net[tr_0].label = Some(\"a\".to_string());\n\n net[tr_1].label = Some(\"τ\".to_string());\n\n net[tr_3].label = Some(\"b\".to_string());\n\n net[tr_4].label = Some(\"c\".to_string());\n\n\n\n // Set initial values\n\n net[pl_0].initial = 5;\n\n net[pl_6].initial = 4;\n\n\n\n // Create arcs\n", "file_path": "pnets/examples/net.rs", "rank": 76, "score": 36525.74923945599 }, { "content": "use pnets::{arc, standard, NodeId};\n\nuse std::error::Error;\n\n\n", "file_path": "pnets/examples/net.rs", "rank": 77, "score": 36525.7391354408 }, { "content": " fn index(self) -> usize {\n\n self.0\n\n }\n\n}\n\n\n\nimpl ::std::convert::From<usize> for PlaceId {\n\n fn from(v: usize) -> Self {\n\n PlaceId(v)\n\n }\n\n}\n\n\n\nimpl ::std::convert::From<usize> for TransitionId {\n\n fn from(v: usize) -> Self {\n\n TransitionId(v)\n\n }\n\n}\n\n\n\n/// Represent an id in the net\n\n#[derive(Eq, PartialEq, Hash, Debug, Clone, Copy)]\n\npub enum NodeId {\n", "file_path": "pnets/src/net.rs", "rank": 78, "score": 36523.65559475027 }, { "content": "\n\n fn index(self) -> usize {\n\n self.0\n\n }\n\n}\n\n\n\ncustom_derive! {\n\n /// Represent a place identifier in the net\n\n #[derive(\n\n Ord, PartialOrd, Clone, Copy, Eq, PartialEq, Hash,\n\n NewtypeDebug, NewtypeDisplay, NewtypeAddAssign(usize), Default, NewtypeAdd(usize)\n\n )]\n\n pub struct PlaceId(usize);\n\n}\n\n\n\nimpl Idx for PlaceId {\n\n fn new(v: usize) -> Self {\n\n Self::from(v)\n\n }\n\n\n", "file_path": "pnets/src/net.rs", "rank": 79, "score": 36523.50886317843 }, { "content": " pub fn as_place(&self) -> Option<PlaceId> {\n\n match self {\n\n NodeId::Place(pl) => Some(*pl),\n\n NodeId::Transition(_) => None,\n\n }\n\n }\n\n\n\n /// Try to convert NodeId to TransitionId\n\n pub fn as_transition(&self) -> Option<TransitionId> {\n\n match self {\n\n NodeId::Place(_) => None,\n\n NodeId::Transition(tr) => Some(*tr),\n\n }\n\n }\n\n}\n", "file_path": "pnets/src/net.rs", "rank": 80, "score": 36521.2089029951 }, { "content": " /// Place\n\n Place(PlaceId),\n\n /// Transition\n\n Transition(TransitionId),\n\n}\n\n\n\nimpl From<TransitionId> for NodeId {\n\n fn from(tr: TransitionId) -> Self {\n\n Self::Transition(tr)\n\n }\n\n}\n\n\n\nimpl From<PlaceId> for NodeId {\n\n fn from(pl: PlaceId) -> Self {\n\n Self::Place(pl)\n\n }\n\n}\n\n\n\nimpl NodeId {\n\n /// Try to convert NodeId to PlaceId\n", "file_path": "pnets/src/net.rs", "rank": 81, "score": 36521.2089029951 }, { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n let pnml: Pnml = quick_xml::de::from_str(include_str!(\"HouseConstruction-002.pnml\"))?;\n\n let nets: Vec<standard::Net> = (&pnml).try_into()?;\n\n let pnml: Pnml = (&nets).into();\n\n println!(\"{:?}\", quick_xml::se::to_string(&pnml));\n\n Ok(())\n\n}\n", "file_path": "pnets_pnml/examples/parse_pnml_file.rs", "rank": 82, "score": 36399.07812135647 }, { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n let parser = pnets_tina::Parser::new(include_str!(\"sokoban_3.net\").as_bytes());\n\n let net = parser.parse().unwrap();\n\n let mut out = Box::new(stdout());\n\n let mut writer = ExporterBuilder::new(out.as_mut())\n\n .with_all_places(true)\n\n .with_disconnected_transitions(true)\n\n .build();\n\n writer.export(&net)?;\n\n Ok(())\n\n}\n", "file_path": "pnets_tina/examples/parse_export_file.rs", "rank": 83, "score": 36399.07812135647 }, { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n let ptnet: Ptnet = from_str(include_str!(\"HouseConstruction-002.pnml\"))?;\n\n let nets: Vec<standard::Net> = (&ptnet).try_into()?;\n\n println!(\"{:?}\", nets);\n\n let ptnet: Ptnet = (&nets).into();\n\n println!(\"{:?}\", quick_xml::se::to_string(&ptnet));\n\n Ok(())\n\n}\n", "file_path": "pnets_pnml/examples/parse_ptnet_file.rs", "rank": 84, "score": 36399.07812135647 }, { "content": " pub deleted_places: Vec<(PlaceId, isize)>,\n\n /// Constant to add at the end of equation\n\n pub constant: isize,\n\n}\n\n\n\n/// Deletion of several places because they are redundant with an other group of places.\n\n///\n\n/// The associated equation is [`Reduction::equals_to`] + [`Reduction::constant`] =\n\n/// [`Reduction::deleted_places`]\n\n#[derive(Clone, Debug, Eq, PartialEq)]\n\npub struct Reduction {\n\n /// Places which are kept during the modification\n\n ///\n\n /// This vector contains tuples ([`PlaceId`], [`isize`]) because sometimes you may need to add\n\n /// a weight on a specific place to keep the equation right.\n\n pub equals_to: Vec<(PlaceId, isize)>,\n\n /// Constant in the relation\n\n pub constant: isize,\n\n /// Places which are deleted during the modification\n\n ///\n", "file_path": "pnets_shrink/src/modifications.rs", "rank": 85, "score": 36361.223731237544 }, { "content": "/// [`InequalityReduction::constant`] => [`InequalityReduction::deleted_places`]\n\n#[derive(Clone, Debug, Eq, PartialEq)]\n\npub struct InequalityReduction {\n\n /// Places which are kept during the modification\n\n ///\n\n /// This vector contains tuples ([`PlaceId`], [`isize`]) because sometimes you may need to add\n\n /// a weight on a specific place to keep the equation right.\n\n pub kept_places: Vec<(PlaceId, isize)>,\n\n /// Constant in the relation\n\n pub constant: isize,\n\n /// Places which are deleted during the modification\n\n ///\n\n /// This vector contains tuples ([`PlaceId`], [`isize`]) because sometimes you may need to add\n\n /// a weight on a specific place to keep the equation right.\n\n pub deleted_places: Vec<(PlaceId, isize)>,\n\n}\n\n\n\n/// All reductions supported by this library\n\n#[derive(Clone, Debug, Eq, PartialEq)]\n\npub enum Modification {\n", "file_path": "pnets_shrink/src/modifications.rs", "rank": 86, "score": 36359.88456372542 }, { "content": "//! All modifications supported by this crate\n\n//!\n\n//! In this module you can found all modifications that are supported by this crate, you can found\n\n//! detailed explanation in structures documentation.\n\nuse pnets::{PlaceId, TransitionId};\n\n\n\n/// This modification correspond to an agglomeration of serval place in a unique new place.\n\n///\n\n/// The associated equation is [`Agglomeration::factor`] * [`Agglomeration::new_place`] =\n\n/// [`Agglomeration::deleted_places`] + [`Agglomeration::constant`]\n\n#[derive(Clone, Debug, Eq, PartialEq)]\n\npub struct Agglomeration {\n\n /// Place which is created during the modification\n\n pub new_place: PlaceId,\n\n /// Factor for new place in the equation\n\n pub factor: isize,\n\n /// Places which are deleted during the modification\n\n ///\n\n /// This vector contains tuples ([`PlaceId`], [`isize`]) because sometimes you may need to add\n\n /// a weight on a specific place to keep the equation right.\n", "file_path": "pnets_shrink/src/modifications.rs", "rank": 87, "score": 36357.473848769405 }, { "content": " /// This vector contains tuples ([`PlaceId`], [`isize`]) because sometimes you may need to add\n\n /// a weight on a specific place to keep the equation right.\n\n pub deleted_places: Vec<(PlaceId, isize)>,\n\n}\n\n\n\n/// Elimination of transitions\n\n///\n\n/// This reduction allows you to delete some transitions because they are redundant with others.\n\n/// There is no equations associated with this reduction\n\n#[derive(Clone, Debug, Eq, PartialEq)]\n\npub struct TransitionElimination {\n\n /// Deleted transitions\n\n pub deleted_transitions: Vec<TransitionId>,\n\n}\n\n\n\n/// Inequality reduction\n\n///\n\n/// This modification deletes some places because they are redundant with a group of other places.\n\n///\n\n/// The equation associated is [`InequalityReduction::kept_places`] +\n", "file_path": "pnets_shrink/src/modifications.rs", "rank": 88, "score": 36357.360357987935 }, { "content": " /// Agglomeration\n\n Agglomeration(Agglomeration),\n\n /// Reduction\n\n Reduction(Reduction),\n\n /// Transition elimination\n\n TransitionElimination(TransitionElimination),\n\n /// Inequality reduction\n\n InequalityReduction(InequalityReduction),\n\n}\n", "file_path": "pnets_shrink/src/modifications.rs", "rank": 89, "score": 36353.361915219466 }, { "content": "use std::error::Error;\n\n\n\nuse pnets::timed::{Net, TimeRange};\n\nuse pnets::{arc, NetError, NodeId};\n\nuse pnets::{PlaceId, TransitionId};\n\n\n\nuse crate::lexer::Lexer;\n\nuse crate::token;\n\nuse crate::token::Kind;\n\nuse crate::ParserError;\n\nuse std::io::BufRead;\n\n\n\n/// Position in a file\n\n#[derive(Copy, Clone, Debug, Eq, PartialEq)]\n\npub struct Position {\n\n /// Current line\n\n pub line: usize,\n\n /// Current column\n\n pub column: usize,\n\n}\n", "file_path": "pnets_tina/src/parser.rs", "rank": 90, "score": 35783.994890789654 }, { "content": "\n\n/// Exporter for [tina]() format.\n\n///\n\n/// It consume a reader and creates a [`pnets::timed::Net`]\n\npub struct Parser<R: BufRead> {\n\n lexer: Lexer<R>,\n\n net: Net,\n\n}\n\n\n\nimpl<R: BufRead> Parser<R> {\n\n /// Parse a timed net from a reader\n\n pub fn parse(mut self) -> Result<Net, Box<dyn Error>> {\n\n loop {\n\n let token = self.lexer.peek()?;\n\n\n\n match token.kind {\n\n token::Kind::NewLine | token::Kind::Comment(_) => {\n\n self.lexer.read()?;\n\n }\n\n token::Kind::Net => self.parse_net()?,\n", "file_path": "pnets_tina/src/parser.rs", "rank": 91, "score": 35783.871802124835 }, { "content": " ))),\n\n }\n\n }\n\n _ => Err(Box::new(ParserError::UnexpectedToken(\n\n token,\n\n \"Expected TokenKind::Identifier(_)\".to_string(),\n\n ))),\n\n }\n\n }\n\n\n\n /// Parse the net token\n\n fn parse_net(&mut self) -> Result<(), Box<dyn Error>> {\n\n self.lexer.read()?;\n\n let identifier = self.lexer.read()?;\n\n match identifier.kind {\n\n token::Kind::Identifier(id) => {\n\n self.net.name = id;\n\n Ok(())\n\n }\n\n _ => Err(Box::new(ParserError::UnexpectedToken(\n", "file_path": "pnets_tina/src/parser.rs", "rank": 92, "score": 35783.75408910578 }, { "content": " }\n\n }\n\n Ok(())\n\n }\n\n\n\n /// Parse a priority line\n\n fn parse_priority(&mut self) -> Result<(), Box<dyn Error>> {\n\n self.lexer.read()?;\n\n let mut pre = vec![];\n\n let mut post = vec![];\n\n while let token::Kind::Identifier(id) = self.lexer.peek()?.kind {\n\n self.lexer.read()?;\n\n pre.push(self.get_or_create_transition(&id)?);\n\n }\n\n let order = match self.lexer.read()?.kind {\n\n token::Kind::GreaterThan => false,\n\n token::Kind::LessThan => true,\n\n _ => {\n\n return Err(Box::new(ParserError::UnexpectedToken(\n\n self.lexer.current_token.clone(),\n", "file_path": "pnets_tina/src/parser.rs", "rank": 93, "score": 35783.36235761628 }, { "content": " /// let parser = Parser::new(&\"net Réseau\\ntr t0 p0 -> p1\\ntr t1 p1 -> p0\".as_bytes());\n\n /// ```\n\n pub fn new(reader: R) -> Self {\n\n Self {\n\n lexer: Lexer::new(reader),\n\n net: Net::default(),\n\n }\n\n }\n\n\n\n /// Get transition from net or create one\n\n fn get_or_create_transition(&mut self, name: &str) -> Result<TransitionId, Box<dyn Error>> {\n\n match self.net.get_index_by_name(name) {\n\n Some(NodeId::Transition(id)) => Ok(id),\n\n Some(NodeId::Place(_)) => Err(Box::new(NetError::DuplicatedName(name.to_string()))),\n\n None => {\n\n let tr = self.net.create_transition();\n\n self.net.rename_node(NodeId::Transition(tr), name)?;\n\n Ok(tr)\n\n }\n\n }\n", "file_path": "pnets_tina/src/parser.rs", "rank": 94, "score": 35782.921238715666 }, { "content": " }\n\n\n\n /// Get place from net or create one\n\n fn get_or_create_place(&mut self, name: &str) -> Result<PlaceId, Box<dyn Error>> {\n\n match self.net.get_index_by_name(name) {\n\n Some(NodeId::Place(id)) => Ok(id),\n\n Some(NodeId::Transition(_)) => {\n\n Err(Box::new(NetError::DuplicatedName(name.to_string())))\n\n }\n\n None => {\n\n let pl = self.net.create_place();\n\n self.net.rename_node(NodeId::Place(pl), name)?;\n\n Ok(pl)\n\n }\n\n }\n\n }\n\n\n\n /// Parse the label token\n\n fn parse_label(&mut self) -> Result<(), Box<dyn Error>> {\n\n self.lexer.read()?;\n", "file_path": "pnets_tina/src/parser.rs", "rank": 95, "score": 35780.97807600942 }, { "content": " ))),\n\n }\n\n }\n\n\n\n fn parse_transition_output_arc(\n\n &mut self,\n\n place: PlaceId,\n\n transition: TransitionId,\n\n ) -> Result<arc::Kind, Box<dyn Error>> {\n\n match self.lexer.peek()?.kind {\n\n token::Kind::NormalArc => {\n\n self.lexer.read()?;\n\n Ok(arc::Kind::Produce(place, transition, self.parse_int()?))\n\n }\n\n arc @ token::Kind::InhibitorArc\n\n | arc @ token::Kind::TestArc\n\n | arc @ token::Kind::StopWatchArc\n\n | arc @ token::Kind::StopWatchInhibitorArc => Err(Box::new(\n\n ParserError::UnexpectedArc(self.lexer.current_token.position, arc),\n\n )),\n", "file_path": "pnets_tina/src/parser.rs", "rank": 96, "score": 35780.256623394576 }, { "content": " self.lexer.read()?;\n\n value\n\n }\n\n _ => {\n\n return Err(Box::new(ParserError::UnexpectedToken(\n\n self.lexer.current_token.clone(),\n\n \"Expected TokenKind::Int(_)\".to_string(),\n\n )));\n\n }\n\n })\n\n }\n\n\n\n /// Try to parse arrow\n\n fn parse_arrow(&mut self) -> Result<(), Box<dyn Error>> {\n\n if self.lexer.read()?.kind == token::Kind::Arrow {\n\n Ok(())\n\n } else {\n\n Err(Box::new(ParserError::UnexpectedToken(\n\n self.lexer.current_token.clone(),\n\n \"Expected TokenKind::Arrow\".to_string(),\n", "file_path": "pnets_tina/src/parser.rs", "rank": 97, "score": 35779.918511627715 }, { "content": " let token = self.lexer.read()?;\n\n match token.kind {\n\n Kind::Identifier(identifier) => {\n\n let index = match self.net.get_index_by_name(&identifier) {\n\n None => return Err(Box::new(NetError::UnknownIdentifier(identifier))),\n\n Some(index) => index,\n\n };\n\n let token = self.lexer.read()?;\n\n match token.kind {\n\n Kind::Identifier(identifier) => {\n\n match index {\n\n NodeId::Place(pl) => self.net[pl].label = Some(identifier),\n\n NodeId::Transition(tr) => self.net[tr].label = Some(identifier),\n\n }\n\n Ok(())\n\n }\n\n\n\n _ => Err(Box::new(ParserError::UnexpectedToken(\n\n token,\n\n \"Expected TokenKind::Identifier(_)\".to_string(),\n", "file_path": "pnets_tina/src/parser.rs", "rank": 98, "score": 35779.91268461314 }, { "content": " token::Kind::Transition => self.parse_transition()?,\n\n token::Kind::Place => self.parse_place()?,\n\n token::Kind::Note => self.parse_note()?,\n\n token::Kind::Label => self.parse_label()?,\n\n token::Kind::Priority => self.parse_priority()?,\n\n token::Kind::EndOfFile => break,\n\n _ => {\n\n return Err(Box::new(ParserError::UnexpectedToken(\n\n token,\n\n \"This token can not start a line\".to_string(),\n\n )));\n\n }\n\n }\n\n }\n\n Ok(self.net)\n\n }\n\n\n\n /// Create a new parser from reader\n\n ///\n\n /// ```ignore\n", "file_path": "pnets_tina/src/parser.rs", "rank": 99, "score": 35779.84708460754 } ]
Rust
src/api/data/client.rs
rnag/rust-wistia
91e430ad9ba3665e8b89fb2aa2acef25acf46483
use crate::auth::auth_token; use crate::constants::ENV_VAR_NAME; use crate::https::{get_https_client, tls}; use crate::log::*; use crate::models::*; use crate::status::raise_for_status; use crate::utils::{into_struct_from_slice, stream_reader_from_url}; use crate::RustWistiaError; use std::borrow::Cow; use std::io::Cursor; use std::time::Instant; use hyper::client::{Client, HttpConnector}; use hyper::header::AUTHORIZATION; use hyper::{Body, Method, Request}; use serde::de::DeserializeOwned; use serde::ser::Serialize; use serde_json::to_vec; use serde_urlencoded::to_string; pub type WistiaClient<'a> = DataClient<'a>; #[derive(Clone)] pub struct DataClient<'a> { pub access_token: Cow<'a, str>, pub client: Client<tls::HttpsConnector<HttpConnector>>, } impl<'a> From<Cow<'a, str>> for DataClient<'a> { fn from(access_token: Cow<'a, str>) -> Self { let token = auth_token(&access_token); Self { access_token: Cow::Owned(token), client: get_https_client(), } } } impl<'a> From<&'a str> for DataClient<'a> { fn from(access_token: &'a str) -> Self { Self::from(Cow::Borrowed(access_token)) } } impl<'a> From<String> for DataClient<'a> { fn from(access_token: String) -> Self { Self::from(Cow::Owned(access_token)) } } impl<'a> DataClient<'a> { pub fn new(access_token: &'a str) -> Self { Self::from(access_token) } pub fn from_env() -> crate::Result<Self> { let token: String = std::env::var(ENV_VAR_NAME).map_err(|_| RustWistiaError::EnvVarNotFound { name: ENV_VAR_NAME.to_owned(), })?; Ok(Self::from(token)) } pub async fn download_asset( &'a self, req: DownloadAssetRequest<'a>, ) -> crate::Result<Cursor<hyper::body::Bytes>> { let media = if let Some(media) = req.media { media } else if let Some(media_id) = req.media_id { self.get_media(media_id).await? } else { return Err(RustWistiaError::MediaIsRequired); }; let url = media.asset_url(req.asset_type)?; let media_content = stream_reader_from_url(&url, self.client.clone()).await; if let Some(file_path) = req.file_path { let mut content = media_content?; let mut file = std::fs::File::create(file_path)?; std::io::copy(&mut content, &mut file)?; Ok(content) } else { media_content } } pub async fn get_media(&self, video_id: &'a str) -> crate::Result<Media> { let url = format!( "https://api.wistia.com/v1/medias/{media_id}.json", media_id = video_id ); self.get(&url).await } pub async fn update_media(&self, video: UpdateMediaRequest) -> crate::Result<MediaInfo> { let url = format!( "https://api.wistia.com/v1/medias/{media_id}.json", media_id = video.id ); self.put(&url, video).await } pub async fn get<R: DeserializeOwned>(&'a self, url: &'a str) -> crate::Result<R> { let token = self.access_token.as_ref(); let req = Request::builder() .method(Method::GET) .uri(url) .header(AUTHORIZATION, token) .body(Body::empty())?; self.make_request(url, req).await } pub async fn put<B: Serialize, R: DeserializeOwned>( &'a self, url: &'a str, body: B, ) -> crate::Result<R> { let token = self.access_token.as_ref(); let mut uri: String; let params = to_string(body)?; let params_len = params.len(); let url = if params_len != 0 { uri = String::with_capacity(url.len() + params.len() + 1); uri.push_str(url); uri.push('?'); uri.push_str(&params); uri.as_str() } else { url }; let req = Request::builder() .method(Method::PUT) .uri(url) .header(AUTHORIZATION, token) .body(Body::empty())?; self.make_request(url, req).await } pub async fn put_with_body<B: Serialize, R: DeserializeOwned>( &'a self, url: &'a str, body: B, ) -> crate::Result<R> { let token = self.access_token.as_ref(); let body_data = to_vec(&body)?; let req = Request::builder() .method(Method::PUT) .uri(url) .header(AUTHORIZATION, token) .body(Body::from(body_data))?; self.make_request(url, req).await } pub(crate) async fn make_request<R: DeserializeOwned>( &'a self, url: &'a str, req: Request<Body>, ) -> crate::Result<R> { let start = Instant::now(); let mut resp = self.client.request(req).await?; debug!("Call Data API completed {:.2?}", start.elapsed()); raise_for_status(url, &mut resp).await?; into_struct_from_slice(resp).await } }
use crate::auth::auth_token; use crate::constants::ENV_VAR_NAME; use crate::https::{get_https_client, tls}; use crate::log::*; use crate::models::*; use crate::status::raise_for_status; use crate::utils::{into_struct_from_slice, stream_reader_from_url}; use crate::RustWistiaError; use std::borrow::Cow; use std::io::Cursor; use std::time::Instant; use hyper::client::{Client, HttpConnector}; use hyper::header::AUTHORIZATION; use hyper::{Body, Method, Request}; use serde::de::DeserializeOwned; use serde::ser::Serialize; use serde_json::to_vec; use serde_urlencoded::to_string; pub type WistiaClient<'a> = DataClient<'a>; #[derive(Clone)] pub struct DataClient<'a> { pub access_token: Cow<'a, str>, pub client: Client<tls::HttpsConnector<HttpConnector>>, } impl<'a> From<Cow<'a, str>> for DataClient<'a> { fn from(access_token: Cow<'a, str>) -> Self { let token = auth_token(&access_token); Self { access_token: Cow::Owned(token), client: get_https_client(), } } } impl<'a> From<&'a str> for DataClient<'a> { fn from(access_token: &'a str) -> Self { Self::from(Cow::Borrowed(access_token)) } } impl<'a> From<String> for DataClient<'a> { fn from(access_token: String) -> Self { Self::from(Cow::Owned(access_token)) } } impl<'a> DataClient<'a> { pub fn new(access_token: &'a str) -> Self { Self::from(access_token) } pub fn from_env() -> crate::Result<Self> { let token: String = std::env::var(ENV_VAR_NAME).map_err(|_| RustWistiaError::EnvVarNotFound { name: ENV_VAR_NAME.to_owned(), })?; Ok(Self::from(token)) } pub async fn download_asset( &'a self, req: DownloadAssetRequest<'a>, ) -> crate::Result<Cursor<hyper::body::Bytes>> { let media = if let Some(media) = req.media { media } else if let Some(media_id) = req.media_id { self.get_media(media_id).await? } else { return Err(RustWistiaError::MediaIsRequired); }; let url = media.asset_url(req.asset_type)?; let media_content = stream_reader_from_url(&url, self.client.clone()).await; if let Some(file_path) = req.file_path { let mut content = media_content?; let mut file = std::fs::File::create(file_path)?; std::io::copy(&mut content, &mut file)?; Ok(content) } else { media_content } } pub async fn get_media(&self, video_id: &'a str) -> crate::Result<Media> { let url = format!( "https://api.wistia.com/v1/medias/{media_id}.json", media_id = video_id ); self.get(&url).await } pub async fn update_media(&self, video: UpdateMediaRequest) -> crate::Result<MediaInfo> { let url = format!( "https://api.wistia.com/v1/medias/{media_id}.json", media_id = video.id ); self.put(&url, video).await } pub async fn get<R: DeserializeOwned>(&'a self, url: &'a str) -> crate::Result<R> { let token = self.access_token.as_ref(); let req = Request::builder() .method(Method::GET) .uri(url) .header(AUTHORIZATION, token) .body(Body::empty())?; self.make_request(url, req).await } pub async fn put<B: Serialize, R: DeserializeOwned>( &'a self, url: &'a str, body: B, ) -> crate::Result<R> { let token = self.access_token.as_ref(); let mut uri: String; let params = to_string(body)?; let params_len = params.len(); let url =
; let req = Request::builder() .method(Method::PUT) .uri(url) .header(AUTHORIZATION, token) .body(Body::empty())?; self.make_request(url, req).await } pub async fn put_with_body<B: Serialize, R: DeserializeOwned>( &'a self, url: &'a str, body: B, ) -> crate::Result<R> { let token = self.access_token.as_ref(); let body_data = to_vec(&body)?; let req = Request::builder() .method(Method::PUT) .uri(url) .header(AUTHORIZATION, token) .body(Body::from(body_data))?; self.make_request(url, req).await } pub(crate) async fn make_request<R: DeserializeOwned>( &'a self, url: &'a str, req: Request<Body>, ) -> crate::Result<R> { let start = Instant::now(); let mut resp = self.client.request(req).await?; debug!("Call Data API completed {:.2?}", start.elapsed()); raise_for_status(url, &mut resp).await?; into_struct_from_slice(resp).await } }
if params_len != 0 { uri = String::with_capacity(url.len() + params.len() + 1); uri.push_str(url); uri.push('?'); uri.push_str(&params); uri.as_str() } else { url }
if_condition
[ { "content": "/// Returns the value to set in the `AUTHORIZATION` header for a request.\n\npub fn auth_token(token: &str) -> String {\n\n // \"Bearer \".len() == 7\n\n let mut bearer_token = String::with_capacity(7 + token.len());\n\n bearer_token.push_str(\"Bearer \");\n\n bearer_token.push_str(token);\n\n\n\n bearer_token\n\n}\n", "file_path": "src/auth.rs", "rank": 0, "score": 198759.18778718382 }, { "content": "pub fn host_with_path(url: &str) -> Result<String> {\n\n let uri: Uri = url.parse()?;\n\n let host = uri.host().unwrap();\n\n let path = uri.path();\n\n\n\n Ok(format!(\"{}{}\", host, path))\n\n}\n\n\n\npub async fn into_struct_from_slice<T>(resp: Response<Body>) -> Result<T>\n\nwhere\n\n T: de::DeserializeOwned,\n\n{\n\n // asynchronously concatenate the buffer from a body into bytes\n\n let bytes = hyper::body::to_bytes(resp).await?;\n\n\n\n // try to parse as json with serde_json\n\n Ok(serde_json::from_slice(&bytes)?)\n\n}\n\n\n\n/// Read the body content of a mutable reference to a `Response` object\n", "file_path": "src/utils.rs", "rank": 1, "score": 181794.7753972338 }, { "content": "#[cfg(not(feature = \"rust-tls\"))]\n\npub fn get_https_client<T>() -> Client<tls::HttpsConnector<HttpConnector>, T>\n\nwhere\n\n T: hyper::body::HttpBody + std::marker::Send,\n\n <T as hyper::body::HttpBody>::Data: Send,\n\n{\n\n // Prepare the HTTPS connector\n\n let https_connector = tls::HttpsConnector::new();\n\n Client::builder().build::<_, T>(https_connector)\n\n}\n", "file_path": "src/https.rs", "rank": 2, "score": 120288.94990353339 }, { "content": "#[derive(Parser, Debug)]\n\nstruct Args {\n\n /// A publicly-accessible URL link to the media file\n\n #[clap(\n\n short,\n\n long,\n\n default_value = \"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerMeltdowns.mp4\"\n\n )]\n\n url: String,\n\n /// Name of the media file\n\n #[clap(short, long)]\n\n name: Option<String>,\n\n /// Description of the media file\n\n #[clap(short, long, default_value = \"My <i>test</i><br>Message <b>here</b>.\")]\n\n description: String,\n\n /// Hashed ID of the Wistia project to upload to\n\n #[clap(short, long)]\n\n project_id: Option<String>,\n\n /// A Wistia contact id, an integer value.\n\n #[clap(short, long)]\n\n contact_id: Option<String>,\n", "file_path": "examples/upload_url.rs", "rank": 3, "score": 75649.63493423292 }, { "content": "#[derive(Parser, Debug)]\n\nstruct Args {\n\n /// Hashed ID of the Wistia video to retrieve info on\n\n #[clap(short, long)]\n\n video_id: String,\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> Result<()> {\n\n sensible_env_logger::init!();\n\n\n\n let args: Args = Args::parse();\n\n\n\n // Alternatively, we could use `WistiaClient::from(token)?` to\n\n // create the new `WistiaClient` instance.\n\n let client = WistiaClient::from_env()?;\n\n\n\n let video_id = &args.video_id;\n\n\n\n let res = client.get_media(video_id).await?;\n\n\n\n trace!(\"Response: {}\", to_string_pretty(&res)?);\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/get_media.rs", "rank": 4, "score": 75201.41712124602 }, { "content": "#[derive(Parser, Debug)]\n\nstruct Args {\n\n /// Hashed ID of the Wistia video to update\n\n #[clap(short, long)]\n\n video_id: String,\n\n /// The media's new name.\n\n #[clap(short, long)]\n\n name: Option<String>,\n\n /// The Wistia hashed ID of an image that will replace the still that’s\n\n /// displayed before the player starts playing. Will return failure message\n\n /// unless media to update is a video, and new still is an image.\n\n #[clap(short, long)]\n\n pub still_media_id: Option<String>,\n\n /// A new description for this media. Accepts plain text or markdown.\n\n #[clap(short, long)]\n\n pub description: Option<String>,\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> Result<()> {\n\n sensible_env_logger::init!();\n", "file_path": "examples/update_media.rs", "rank": 5, "score": 75201.41712124602 }, { "content": "#[derive(Parser, Debug)]\n\nstruct Args {\n\n /// Path to media file\n\n #[clap(\n\n short,\n\n long,\n\n parse(from_os_str),\n\n default_value = \"./examples/assets/sample-video.mp4\"\n\n )]\n\n file_path: PathBuf,\n\n /// Name of the media file\n\n #[clap(short, long, default_value_t = String::new())]\n\n name: String,\n\n /// Description of the media file\n\n #[clap(short, long, default_value = \"My <i>test</i><br>Message <b>here</b>.\")]\n\n description: String,\n\n /// Hashed ID of the Wistia project to upload to\n\n #[clap(short, long, default_value_t = String::new())]\n\n project_id: String,\n\n /// A Wistia contact id, an integer value.\n\n #[clap(short, long, default_value_t = String::new())]\n", "file_path": "examples/upload_file.rs", "rank": 6, "score": 74763.32568080392 }, { "content": "#[derive(Parser, Debug)]\n\nstruct Args {\n\n /// Hashed ID of the Wistia video to retrieve info on\n\n #[clap(short, long)]\n\n video_id: String,\n\n\n\n /// Type of the media asset to retrieve. Defaults to the original asset that was uploaded.\n\n #[clap(short = 't', long, default_value = \"OriginalFile\")]\n\n asset_type: String,\n\n\n\n /// Retrieve only the HTTP asset url, rather than the SSL (HTTPS) variant\n\n #[clap(short, long)]\n\n no_ssl: bool,\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> Result<()> {\n\n sensible_env_logger::init!();\n\n\n\n let args: Args = Args::parse();\n\n let asset_type = args.asset_type.as_str();\n", "file_path": "examples/get_asset_url.rs", "rank": 7, "score": 73541.32955939145 }, { "content": "#[derive(Parser, Debug)]\n\nstruct Args {\n\n /// A publicly-accessible URL link to the media file\n\n #[clap(\n\n short,\n\n long,\n\n default_value = \"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerMeltdowns.mp4\"\n\n )]\n\n url: String,\n\n /// Name of the media file\n\n #[clap(short, long)]\n\n name: Option<String>,\n\n /// Description of the media file\n\n #[clap(short, long, default_value = \"My <i>test</i><br>Message <b>here</b>.\")]\n\n description: String,\n\n /// Hashed ID of the Wistia project to upload to\n\n #[clap(short, long)]\n\n project_id: Option<String>,\n\n /// A Wistia contact id, an integer value.\n\n #[clap(short, long)]\n\n contact_id: Option<String>,\n", "file_path": "examples/upload_url_stream.rs", "rank": 8, "score": 73541.32955939145 }, { "content": "#[derive(Parser, Debug)]\n\nstruct Args {\n\n /// Path to media file\n\n #[clap(\n\n short,\n\n long,\n\n parse(from_os_str),\n\n default_value = \"./examples/assets/sample-video.mp4\"\n\n )]\n\n file_path: PathBuf,\n\n /// Name of the media file\n\n #[clap(short, long, default_value_t = String::new())]\n\n name: String,\n\n /// Description of the media file\n\n #[clap(short, long, default_value = \"My <i>test</i><br>Message <b>here</b>.\")]\n\n description: String,\n\n /// Hashed ID of the Wistia project to upload to\n\n #[clap(short, long, default_value_t = String::new())]\n\n project_id: String,\n\n /// A Wistia contact id, an integer value.\n\n #[clap(short, long, default_value_t = String::new())]\n", "file_path": "examples/upload_file_stream.rs", "rank": 9, "score": 72685.64985477287 }, { "content": "#[test]\n\nfn test_html_root_url() {\n\n version_sync::assert_html_root_url_updated!(\"src/lib.rs\");\n\n}\n", "file_path": "tests/version-number.rs", "rank": 10, "score": 69186.65724292178 }, { "content": "pub fn is_default<T: Default + PartialEq>(t: &T) -> bool {\n\n t == &T::default()\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 11, "score": 66912.43108250119 }, { "content": "fn empty_string_is_none<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n let s = String::deserialize(deserializer)?;\n\n if s.is_empty() {\n\n Ok(None)\n\n } else {\n\n Ok(Some(s))\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n use crate::log::debug;\n\n use serde_json::from_str;\n\n\n\n /// Using the provided [Example Response][]\n", "file_path": "src/models/upload/response.rs", "rank": 12, "score": 66772.96016708651 }, { "content": "use serde::{Deserialize, Serialize};\n\n\n\n/// A value which represents the type of media.\n\n///\n\n/// See more [on `type`][].\n\n///\n\n/// [on `type`]: https://wistia.com/support/developers/data-api#medias-response\n\n#[derive(Debug, PartialEq, Serialize, Deserialize)]\n\npub enum MediaType {\n\n Video,\n\n Audio,\n\n Image,\n\n PdfDocument,\n\n MicrosoftOfficeDocument,\n\n Swf,\n\n UnknownType,\n\n}\n\n\n\nimpl Default for MediaType {\n\n fn default() -> Self {\n\n MediaType::Video\n\n }\n\n}\n", "file_path": "src/models/media/type.rs", "rank": 13, "score": 60847.48356190733 }, { "content": "fn show_progress(msg: impl ToString) -> ProgressBar {\n\n let pb = ProgressBar::new_spinner();\n\n pb.enable_steady_tick(120);\n\n pb.set_style(\n\n ProgressStyle::default_spinner()\n\n .template(\"{spinner:.blue} {msg}\")\n\n .tick_strings(&[\n\n \"▹▹▹▹▹\",\n\n \"▸▹▹▹▹\",\n\n \"▹▸▹▹▹\",\n\n \"▹▹▸▹▹\",\n\n \"▹▹▹▸▹\",\n\n \"▹▹▹▹▸\",\n\n \"▪▪▪▪▪\",\n\n ]),\n\n );\n\n pb.set_message(msg.to_string());\n\n pb\n\n}\n", "file_path": "examples/download_asset.rs", "rank": 14, "score": 60082.46447281387 }, { "content": " #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub description: Option<String>,\n\n}\n\n\n\nimpl UpdateMediaRequest {\n\n /// Sets the media's new name\n\n pub fn name(mut self, name: &str) -> Self {\n\n self.name = Some(name.to_owned());\n\n self\n\n }\n\n\n\n /// Sets the Wistia hashed ID of an image that will replace the still that’s\n\n /// displayed before the player starts playing.\n\n pub fn new_still_media_id(mut self, new_still_media_id: &str) -> Self {\n\n self.new_still_media_id = Some(new_still_media_id.to_owned());\n\n self\n\n }\n\n\n\n /// Sets a new description for this media. Accepts plain text or markdown.\n\n pub fn description(mut self, description: &str) -> Self {\n\n self.description = Some(description.to_owned());\n\n self\n\n }\n\n}\n", "file_path": "src/models/media/update_request.rs", "rank": 15, "score": 58455.81365247546 }, { "content": "use serde::Serialize;\n\n\n\n/// Represents a [Medias: Update] request.\n\n///\n\n/// [Medias: Update]: https://wistia.com/support/developers/data-api#the-request-7\n\n///\n\n#[derive(Default, Debug, PartialEq, Serialize)]\n\npub struct UpdateMediaRequest {\n\n /// The hashed Video Id (example: `abc1234567`).\n\n #[serde(skip_serializing)]\n\n pub id: String,\n\n /// The media's new name.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub name: Option<String>,\n\n /// The Wistia hashed ID of an image that will replace the still that’s\n\n /// displayed before the player starts playing. Will return failure message\n\n /// unless media to update is a video, and new still is an image.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub new_still_media_id: Option<String>,\n\n /// A new description for this media. Accepts plain text or markdown.\n", "file_path": "src/models/media/update_request.rs", "rank": 16, "score": 58452.79305516511 }, { "content": "#[derive(Parser, Debug)]\n\nstruct Args {\n\n /// Path to image file\n\n #[clap(\n\n short,\n\n long,\n\n parse(from_os_str),\n\n default_value = \"./examples/assets/sample-thumbnail.png\"\n\n )]\n\n file_path: PathBuf,\n\n /// Name of the media file\n\n #[clap(short, long, default_value_t = String::new())]\n\n name: String,\n\n /// Description of the media file\n\n #[clap(short, long, default_value = \"My <i>test</i><br>Message <b>here</b>.\")]\n\n description: String,\n\n /// Hashed ID of the Wistia project to upload to\n\n #[clap(short, long, default_value_t = String::new())]\n\n project_id: String,\n\n /// A Wistia contact id, an integer value.\n\n #[clap(short, long, default_value_t = String::new())]\n", "file_path": "examples/upload_thumbnail.rs", "rank": 17, "score": 45223.96049933111 }, { "content": "#[derive(Parser, Debug)]\n\nstruct Args {\n\n /// Hashed ID of the Wistia video to retrieve info on\n\n #[clap(short, long)]\n\n video_id: String,\n\n\n\n /// Type of the media asset to download. Defaults to the original asset that was uploaded.\n\n #[clap(short = 't', long, default_value = \"OriginalFile\")]\n\n asset_type: String,\n\n\n\n /// Path to media file\n\n #[clap(short, long, parse(from_os_str), default_value = \"./my-video.mp4\")]\n\n file_path: PathBuf,\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> Result<()> {\n\n sensible_env_logger::init_timed_short!();\n\n\n\n let args: Args = Args::parse();\n\n\n", "file_path": "examples/download_asset.rs", "rank": 18, "score": 45223.96049933111 }, { "content": "#[test]\n\nfn test_readme_deps() {\n\n version_sync::assert_markdown_deps_updated!(\"README.md\");\n\n}\n\n\n", "file_path": "tests/version-number.rs", "rank": 19, "score": 42632.76706885571 }, { "content": "use super::{Asset, MediaStatus, MediaType, ProjectInfo, Thumbnail};\n\nuse crate::constants::*;\n\nuse crate::{Result, RustWistiaError};\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[derive(Default, Debug, PartialEq, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct Media {\n\n #[serde(rename = \"hashed_id\")]\n\n pub hashed_id: String,\n\n pub id: u64,\n\n pub name: String,\n\n #[serde(rename = \"type\")]\n\n pub type_field: MediaType,\n\n pub created: String,\n\n pub updated: String,\n\n /// Note: only videos have this attribute set; thumbnails and other\n\n /// medias don't.\n\n pub duration: Option<f64>,\n", "file_path": "src/models/media/media.rs", "rank": 20, "score": 37402.61634758801 }, { "content": " pub status: MediaStatus,\n\n #[serde(default)]\n\n pub description: String,\n\n #[serde(default)]\n\n pub progress: f64,\n\n pub thumbnail: Thumbnail,\n\n pub project: ProjectInfo,\n\n #[serde(skip_serializing)]\n\n pub embed_code: String,\n\n pub assets: Vec<Asset>,\n\n pub section: Option<String>,\n\n}\n\n\n\nimpl Media {\n\n /// Retrieve the *asset URL* for the original source media that was uploaded.\n\n pub fn source_url(&self) -> Result<String> {\n\n self.asset_url(None)\n\n }\n\n\n\n /// Retrieve the *asset URL* (default: **HTTPS**) for a specified `asset_type`, which\n", "file_path": "src/models/media/media.rs", "rank": 21, "score": 37397.23617368993 }, { "content": " /// defaults to the original source media if not provided.\n\n pub fn asset_url<'a>(&'a self, asset_type: impl Into<Option<&'a str>>) -> Result<String> {\n\n let url = self.asset_url_insecure(asset_type)?;\n\n\n\n let (_, id) = url.rsplit_once('/').unwrap();\n\n let id = match id.rsplit_once(\".bin\") {\n\n Some((id, _)) => id,\n\n None => id,\n\n };\n\n\n\n Ok(format!(\n\n \"https://embed-ssl.wistia.com/deliveries/{id}/{DEFAULT_FILENAME}\"\n\n ))\n\n }\n\n\n\n /// Retrieve the *asset URL* (default: **HTTP**) for a specified `asset_type`, which\n\n /// defaults to the original source media if not provided.\n\n pub fn asset_url_insecure<'a>(\n\n &'a self,\n\n asset_type: impl Into<Option<&'a str>>,\n", "file_path": "src/models/media/media.rs", "rank": 22, "score": 37396.35230057183 }, { "content": " ) -> Result<&'a str> {\n\n let r#type = asset_type.into().unwrap_or(ORIGINAL_ASSET);\n\n\n\n for asset in self.assets.iter() {\n\n if asset.type_field == r#type {\n\n return Ok(&asset.url);\n\n }\n\n }\n\n\n\n Err(RustWistiaError::AssetNotFound {\n\n r#type: r#type.to_string(),\n\n video_id: self.hashed_id.clone(),\n\n valid_types: self.assets.iter().map(|a| a.type_field.clone()).collect(),\n\n })\n\n }\n\n}\n", "file_path": "src/models/media/media.rs", "rank": 23, "score": 37392.18799516514 }, { "content": "use super::{MediaStatus, MediaType, Thumbnail};\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[derive(Default, Debug, PartialEq, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct MediaInfo {\n\n #[serde(rename = \"hashed_id\")]\n\n pub hashed_id: String,\n\n pub id: u64,\n\n pub name: String,\n\n #[serde(rename = \"type\")]\n\n pub type_field: MediaType,\n\n pub created: String,\n\n pub updated: String,\n\n /// Note: only videos have this attribute set; thumbnails and other\n\n /// medias don't.\n\n pub duration: Option<f64>,\n\n pub status: MediaStatus,\n\n pub description: String,\n\n pub progress: f64,\n\n pub thumbnail: Thumbnail,\n\n pub section: Option<String>,\n\n}\n", "file_path": "src/models/media/media_info.rs", "rank": 24, "score": 36586.26684478856 }, { "content": "//! Library-specific type definitions\n\n//!\n\nuse crate::RustWistiaError;\n\n\n\n/// Result type with errors populated solely by *our* library.\n\npub type Result<T> = std::result::Result<T, RustWistiaError>;\n", "file_path": "src/types.rs", "rank": 25, "score": 33232.416674900844 }, { "content": "}\n\n\n\n#[tokio::main]\n\nasync fn main() -> Result<()> {\n\n sensible_env_logger::init_timed_short!();\n\n\n\n let args: Args = Args::parse();\n\n\n\n trace!(\"Uploading link to Wistia...\");\n\n\n\n // Alternatively, we could use `UrlUploader::with_client(url, client)` to\n\n // create the new `UrlUploader` instance.\n\n let mut uploader = UrlUploader::new(&args.url)?;\n\n\n\n // Normally we'll just chain together the methods like below, but here we\n\n // need to explicitly exclude any empty string values.\n\n //\n\n // UrlUploader::new(&args.url)?\n\n // .name(&args.name)\n\n // .description(&args.description)\n", "file_path": "examples/upload_url.rs", "rank": 26, "score": 31576.30955145736 }, { "content": "use rust_wistia::{Result, UrlUploader};\n\n\n\n#[macro_use]\n\nextern crate log;\n\n\n\nuse clap::Parser;\n\n\n\n/// Upload a public accessible link to Wistia\n\n///\n\n/// You can find links to public test videos here:\n\n/// https://gist.github.com/jsturgis/3b19447b304616f18657?permalink_comment_id=3448015#gistcomment-3448015\n\n// noinspection DuplicatedCode\n\n#[derive(Parser, Debug)]\n", "file_path": "examples/upload_url.rs", "rank": 27, "score": 31563.716735594433 }, { "content": "\n\n if let Some(ref project_id) = args.project_id {\n\n uploader = uploader.project_id(project_id);\n\n };\n\n if let Some(ref name) = args.name {\n\n uploader = uploader.name(name);\n\n };\n\n if !args.description.is_empty() {\n\n uploader = uploader.description(&args.description);\n\n };\n\n if let Some(ref contact_id) = args.contact_id {\n\n uploader = uploader.contact_id(contact_id);\n\n };\n\n\n\n let res = uploader.send().await?;\n\n\n\n trace!(\"Response: {res:#?}\");\n\n trace!(\"Video ID: {}\", res.hashed_id);\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/upload_url.rs", "rank": 28, "score": 31561.420167704793 }, { "content": "\n\n let args: Args = Args::parse();\n\n\n\n // Alternatively, we could use `WistiaClient::from(token)?` to\n\n // create the new `WistiaClient` instance.\n\n let client = WistiaClient::from_env()?;\n\n\n\n let req = UpdateMediaRequest {\n\n id: args.video_id,\n\n name: args.name,\n\n new_still_media_id: args.still_media_id,\n\n description: args.description,\n\n ..Default::default()\n\n };\n\n\n\n let res = client.update_media(req).await?;\n\n\n\n trace!(\"Response: {}\", to_string_pretty(&res)?);\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/update_media.rs", "rank": 29, "score": 31115.639587921996 }, { "content": "use rust_wistia::{Result, WistiaClient};\n\n\n\n#[macro_use]\n\nextern crate log;\n\n\n\nuse clap::Parser;\n\nuse rust_wistia::models::UpdateMediaRequest;\n\nuse serde_json::to_string_pretty;\n\n\n\n/// Updates info on a Wistia video\n\n#[derive(Parser, Debug)]\n", "file_path": "examples/update_media.rs", "rank": 30, "score": 31107.398711209073 }, { "content": "use rust_wistia::{Result, WistiaClient};\n\n\n\n#[macro_use]\n\nextern crate log;\n\n\n\nuse clap::Parser;\n\nuse serde_json::to_string_pretty;\n\n\n\n/// Retrieve info on a Wistia video\n\n#[derive(Parser, Debug)]\n", "file_path": "examples/get_media.rs", "rank": 31, "score": 31102.559162597972 }, { "content": " contact_id: String,\n\n}\n\n\n\n// noinspection DuplicatedCode\n\n#[tokio::main]\n\nasync fn main() -> Result<()> {\n\n sensible_env_logger::init_timed_short!();\n\n\n\n let args: Args = Args::parse();\n\n\n\n trace!(\"Uploading file to Wistia...\");\n\n\n\n let client = UploadClient::from_env()?;\n\n let file_path = Path::new(&args.file_path);\n\n\n\n // Alternatively, we could use `FileUploader::new(path)?` to\n\n // create the new `FileUploader` instance.\n\n let res = FileUploader::with_client(file_path, client)\n\n .project_id(&args.project_id)\n\n .name(&args.name)\n", "file_path": "examples/upload_file.rs", "rank": 32, "score": 30652.682570260327 }, { "content": "use rust_wistia::{FileUploader, Result, UploadClient};\n\n\n\n#[macro_use]\n\nextern crate log;\n\n\n\nuse std::path::{Path, PathBuf};\n\n\n\nuse clap::Parser;\n\n\n\n/// Upload a local file to Wistia\n\n// noinspection DuplicatedCode\n\n#[derive(Parser, Debug)]\n", "file_path": "examples/upload_file.rs", "rank": 33, "score": 30645.03498041952 }, { "content": " .description(&args.description)\n\n .contact_id(&args.contact_id)\n\n .send()\n\n .await?;\n\n\n\n trace!(\"Response: {res:#?}\");\n\n trace!(\"Video ID: {}\", res.hashed_id);\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/upload_file.rs", "rank": 34, "score": 30639.101034385792 }, { "content": "\n\n// We get a warning in the `examples/` that this is not used, but it *will*\n\n// be used when the optional feature is enabled.\n\n#[allow(unused)]\n\n#[derive(Clone)]\n\npub(crate) struct UploadFileRequest<'a, P: AsRef<Path>> {\n\n /// **Required**. The path to the media file. The contents of this file\n\n /// will be multipart-form encoded into the request body.\n\n pub file_path: P,\n\n /// The hashed id of the project to upload media into. If omitted, a new\n\n /// project will be created and uploaded to. The naming convention used\n\n /// for such projects is `Uploads_YYYY-MM-DD`.\n\n pub project_id: Option<&'a str>,\n\n /// A display name to use for the media in Wistia. If omitted, the filename\n\n /// will be used instead. This field is limited to 255 characters.\n\n pub name: Option<&'a str>,\n\n /// A description to use for the media in Wistia. You can use basic HTML\n\n /// here, but note that both HTML and CSS will be sanitized.\n\n pub description: Option<&'a str>,\n\n /// A Wistia contact id, an integer value. If omitted, it will default to\n", "file_path": "src/models/upload/request.rs", "rank": 35, "score": 30566.71598187623 }, { "content": " #[allow(unused)]\n\n pub(crate) fn new(file_path: &'a str) -> Self {\n\n Self {\n\n file_name: file_path,\n\n project_id: None,\n\n name: None,\n\n description: None,\n\n contact_id: None,\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use serde_urlencoded::to_string;\n\n\n\n #[test]\n\n fn test_it_works() {\n\n let req = UploadRequest {\n", "file_path": "src/models/upload/request.rs", "rank": 36, "score": 30565.027112899636 }, { "content": "}\n\n\n\n#[derive(Default, Clone)]\n\npub(crate) struct UploadUrlRequest<'a> {\n\n /// **Required**. The web location of the media file to import.\n\n pub url: &'a str,\n\n /// The hashed id of the project to upload media into. If omitted, a new\n\n /// project will be created and uploaded to. The naming convention used\n\n /// for such projects is `Uploads_YYYY-MM-DD`.\n\n pub project_id: Option<&'a str>,\n\n /// A display name to use for the media in Wistia. If omitted, the filename\n\n /// will be used instead. This field is limited to 255 characters.\n\n pub name: Option<&'a str>,\n\n /// A description to use for the media in Wistia. You can use basic HTML\n\n /// here, but note that both HTML and CSS will be sanitized.\n\n pub description: Option<&'a str>,\n\n /// A Wistia contact id, an integer value. If omitted, it will default to\n\n /// the contact_id of the account’s owner.\n\n pub contact_id: Option<&'a str>,\n\n}\n", "file_path": "src/models/upload/request.rs", "rank": 37, "score": 30563.880372813368 }, { "content": " /// on your [API access page].\n\n ///\n\n /// [API access page]: https://wistia.com/support/developers/data-api#getting-started\n\n pub access_token: &'a str,\n\n /// **Required** unless `file` is specified. The web location of the media\n\n /// file to import.\n\n pub url: Option<&'a str>,\n\n /// The hashed id of the project to upload media into. If omitted, a new\n\n /// project will be created and uploaded to. The naming convention used\n\n /// for such projects is `Uploads_YYYY-MM-DD`.\n\n pub project_id: Option<&'a str>,\n\n /// A display name to use for the media in Wistia. If omitted, the filename\n\n /// will be used instead. This field is limited to 255 characters.\n\n pub name: Option<&'a str>,\n\n /// A description to use for the media in Wistia. You can use basic HTML\n\n /// here, but note that both HTML and CSS will be sanitized.\n\n pub description: Option<&'a str>,\n\n /// A Wistia contact id, an integer value. If omitted, it will default to\n\n /// the contact_id of the account’s owner.\n\n pub contact_id: Option<&'a str>,\n", "file_path": "src/models/upload/request.rs", "rank": 38, "score": 30562.566582893138 }, { "content": "#[derive(Clone)]\n\npub(crate) struct UploadStreamRequest<'a> {\n\n /// Optional. The name of the media file.\n\n pub file_name: &'a str,\n\n /// The hashed id of the project to upload media into. If omitted, a new\n\n /// project will be created and uploaded to. The naming convention used\n\n /// for such projects is `Uploads_YYYY-MM-DD`.\n\n pub project_id: Option<&'a str>,\n\n /// A display name to use for the media in Wistia. If omitted, the filename\n\n /// will be used instead. This field is limited to 255 characters.\n\n pub name: Option<&'a str>,\n\n /// A description to use for the media in Wistia. You can use basic HTML\n\n /// here, but note that both HTML and CSS will be sanitized.\n\n pub description: Option<&'a str>,\n\n /// A Wistia contact id, an integer value. If omitted, it will default to\n\n /// the contact_id of the account’s owner.\n\n pub contact_id: Option<&'a str>,\n\n}\n\n\n\nimpl<'a> UploadStreamRequest<'a> {\n", "file_path": "src/models/upload/request.rs", "rank": 39, "score": 30562.4507674792 }, { "content": " access_token: \"abc123\",\n\n url: None,\n\n project_id: None,\n\n name: None,\n\n description: None,\n\n contact_id: None,\n\n };\n\n\n\n assert_eq!(to_string(req).unwrap(), \"access_token=abc123\");\n\n }\n\n\n\n #[test]\n\n fn test_it_works_with_other_params() {\n\n let req = UploadRequest {\n\n access_token: \"xyz123\",\n\n url: Some(\"https://test-url.com/my/path?key=\\\"hello world!@#$?%&\\\"&value=\"),\n\n project_id: Some(\"abc321\"),\n\n name: None,\n\n description: None,\n\n contact_id: Some(\"my contact <[email protected]>\"),\n\n };\n\n\n\n assert_eq!(to_string(req).unwrap(), \"access_token=xyz123&url=https%3A%2F%2Ftest-url.com%2Fmy%2Fpath%3Fkey%3D%22hello+world%21%40%23%24%3F%25%26%22%26value%3D&project_id=abc321&contact_id=my+contact+%3Cabc%40xyz.org%3E\");\n\n }\n\n}\n", "file_path": "src/models/upload/request.rs", "rank": 40, "score": 30562.19006500645 }, { "content": " /// the contact_id of the account’s owner.\n\n pub contact_id: Option<&'a str>,\n\n}\n\n\n\nimpl<'a, P: AsRef<Path>> UploadFileRequest<'a, P> {\n\n #[allow(unused)]\n\n pub(crate) fn new(file_path: P) -> Self {\n\n Self {\n\n file_path,\n\n project_id: None,\n\n name: None,\n\n description: None,\n\n contact_id: None,\n\n }\n\n }\n\n}\n\n\n\n// We get a warning in the `examples/` that this is not used, but it *will*\n\n// be used when the optional feature is enabled.\n\n#[allow(unused)]\n", "file_path": "src/models/upload/request.rs", "rank": 41, "score": 30561.297425184064 }, { "content": "use serde::Serialize;\n\n\n\nuse std::path::Path;\n\n\n\n/// Model representing a [Request] to the Wistia [Upload API].\n\n///\n\n/// # Note\n\n/// This only includes the parameters which may be encoded into the part\n\n/// of the query string.\n\n///\n\n/// The only exceptions are `description`, which is expected to be long and\n\n/// which may be more performant to be multipart-form encoded, and the `file`\n\n/// parameter which *must* be multipart-form encoded into the request body.\n\n///\n\n/// [Upload API]: https://wistia.com/support/developers/upload-api\n\n/// [Request]: https://wistia.com/support/developers/upload-api#the-request\n\n///\n\n#[derive(Default, Serialize)]\n\npub struct UploadRequest<'a> {\n\n /// **Required**. A 64 character hex string. This parameter can be found\n", "file_path": "src/models/upload/request.rs", "rank": 42, "score": 30559.177859064675 }, { "content": "\n\n // Alternatively, we could use `WistiaClient::from(token)?` to\n\n // create the new `WistiaClient` instance.\n\n let client = WistiaClient::from_env()?;\n\n\n\n let video_id = &args.video_id;\n\n\n\n let media = client.get_media(video_id).await?;\n\n\n\n let url = if args.no_ssl {\n\n media.asset_url_insecure(asset_type)?.to_owned()\n\n } else {\n\n // as a shorthand, we could just call `media.source_url()?` in this case\n\n media.asset_url(asset_type)?\n\n };\n\n\n\n trace!(\"Asset URL: {url}\");\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/get_asset_url.rs", "rank": 43, "score": 30448.664671412324 }, { "content": "}\n\n\n\n#[tokio::main]\n\nasync fn main() -> Result<()> {\n\n sensible_env_logger::init_timed_short!();\n\n\n\n let args: Args = Args::parse();\n\n\n\n trace!(\"Uploading bytes content in link to Wistia...\");\n\n\n\n // Alternatively, we could use `StreamUploader::with_url(&args.url)` to\n\n // create the new `StreamUploader` instance without an explicit HTTPS client.\n\n let client = get_https_client();\n\n let mut uploader = StreamUploader::with_url_and_client(&args.url, client).await?;\n\n\n\n // Normally we'll just chain together the methods like below, but here we\n\n // need to explicitly exclude any empty string values.\n\n //\n\n // StreamUploader::new(bytes)?\n\n // .name(&args.name)\n", "file_path": "examples/upload_url_stream.rs", "rank": 44, "score": 30448.52483179446 }, { "content": "use rust_wistia::{Result, WistiaClient};\n\n\n\n#[macro_use]\n\nextern crate log;\n\n\n\nuse clap::Parser;\n\n\n\n/// Retrieve the media [Asset URL] on a Wistia video\n\n///\n\n/// [Asset URL]: https://wistia.com/support/developers/asset-urls\n\n#[derive(Parser, Debug)]\n", "file_path": "examples/get_asset_url.rs", "rank": 45, "score": 30440.881202718443 }, { "content": "use rust_wistia::{Result, StreamUploader};\n\n\n\n#[macro_use]\n\nextern crate log;\n\n\n\nuse clap::Parser;\n\nuse rust_wistia::https::get_https_client;\n\n\n\n/// Upload the *bytes* data for a public accessible link to Wistia\n\n///\n\n/// You can find links to public test videos here:\n\n/// https://gist.github.com/jsturgis/3b19447b304616f18657?permalink_comment_id=3448015#gistcomment-3448015\n\n// noinspection DuplicatedCode\n\n#[derive(Parser, Debug)]\n", "file_path": "examples/upload_url_stream.rs", "rank": 46, "score": 30433.91779190569 }, { "content": " // .description(&args.description)\n\n\n\n if let Some(ref project_id) = args.project_id {\n\n uploader = uploader.project_id(project_id);\n\n };\n\n if let Some(ref name) = args.name {\n\n uploader = uploader.name(name);\n\n };\n\n if !args.description.is_empty() {\n\n uploader = uploader.description(&args.description);\n\n };\n\n if let Some(ref contact_id) = args.contact_id {\n\n uploader = uploader.contact_id(contact_id);\n\n };\n\n\n\n let res = uploader.send().await?;\n\n\n\n trace!(\"Response: {res:#?}\");\n\n trace!(\"Video ID: {}\", res.hashed_id);\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/upload_url_stream.rs", "rank": 47, "score": 30431.80643180784 }, { "content": " Err(_) => Err(RustWistiaError::EnvVarNotFound {\n\n name: ENV_VAR_NAME.to_owned(),\n\n }),\n\n }?;\n\n\n\n Ok(Self::from(token))\n\n }\n\n\n\n /// Initialize a new `UploadClient` object from an [API access token].\n\n ///\n\n /// [API access token]: https://wistia.com/support/developers/data-api#getting-started\n\n pub fn from_token(token: &str) -> Self {\n\n Self::from(token)\n\n }\n\n\n\n /// Build the URL with the url-encoded *query parameters* included\n\n pub fn build_url(params: UploadRequest) -> Result<String> {\n\n let query = to_string(params)?;\n\n\n\n // Build the URL with the query parameters included\n", "file_path": "src/api/upload/client.rs", "rank": 53, "score": 30090.815452161612 }, { "content": " let mut url = String::with_capacity(UPLOAD_API.len() + 1 + query.len());\n\n url.push_str(UPLOAD_API);\n\n url.push('?');\n\n url.push_str(query.as_str());\n\n\n\n Ok(url)\n\n }\n\n\n\n /// Send the request to the Wistia Upload API\n\n pub async fn make_request<'a>(\n\n &'a self,\n\n url: &'a str,\n\n req: Request<B>,\n\n ) -> Result<UploadResponse> {\n\n let start = Instant::now();\n\n let mut resp = self.client.request(req).await?;\n\n debug!(\"Call Upload API completed {:.2?}\", start.elapsed());\n\n\n\n raise_for_status(url, &mut resp).await?;\n\n\n", "file_path": "src/api/upload/client.rs", "rank": 54, "score": 30090.478763394913 }, { "content": " fn from(token: &str) -> Self {\n\n Self {\n\n access_token: token.to_string(),\n\n client: get_https_client(),\n\n }\n\n }\n\n}\n\n\n\nimpl<B: HttpBody + Send + 'static> UploadClient<B>\n\nwhere\n\n <B as HttpBody>::Data: Send,\n\n <B as HttpBody>::Error: Into<Box<(dyn std::error::Error + Send + Sync + 'static)>>,\n\n{\n\n /// Initialize a new `UploadClient` object from an [API access token],\n\n /// assuming this is currently set in the environment.\n\n ///\n\n /// [API access token]: https://wistia.com/support/developers/data-api#getting-started\n\n pub fn from_env() -> Result<Self> {\n\n let token = match var(ENV_VAR_NAME) {\n\n Ok(val) => Ok(val),\n", "file_path": "src/api/upload/client.rs", "rank": 55, "score": 30087.55354589535 }, { "content": "/// Prefer to use this with one of the concrete implementations, i.e.\n\n/// [`crate::FileUploader`] or [`crate::UrlUploader`].\n\n///\n\n/// Also check out the [`rust-wistia`] docs for usage and examples.\n\n///\n\n/// [`rust-wistia`]: https://docs.rs/rust-wistia\n\n/// [Upload API]: https://wistia.com/support/developers/upload-api\n\n///\n\n#[derive(Clone)]\n\npub struct UploadClient<B = Body> {\n\n /// Represents the [API access token] used to authenticate requests to the\n\n /// [Wistia API].\n\n ///\n\n /// [API access token]: https://wistia.com/support/developers/data-api#getting-started\n\n /// [Wistia API]: https://wistia.com/support/developers/upload-api\n\n pub access_token: String,\n\n /// The HTTPS client to use for sending requests.\n\n client: Client<tls::HttpsConnector<HttpConnector>, B>,\n\n}\n\n\n", "file_path": "src/api/upload/client.rs", "rank": 58, "score": 30086.547915091724 }, { "content": "impl<B: HttpBody + Send + 'static> From<String> for UploadClient<B>\n\nwhere\n\n <B as HttpBody>::Data: Send,\n\n <B as HttpBody>::Error: Into<Box<(dyn std::error::Error + Send + Sync + 'static)>>,\n\n{\n\n /// Create a new `UploadClient` from an access token\n\n fn from(token: String) -> Self {\n\n Self {\n\n access_token: token,\n\n client: get_https_client(),\n\n }\n\n }\n\n}\n\n\n\nimpl<B: HttpBody + Send + 'static> From<&str> for UploadClient<B>\n\nwhere\n\n <B as HttpBody>::Data: Send,\n\n <B as HttpBody>::Error: Into<Box<(dyn std::error::Error + Send + Sync + 'static)>>,\n\n{\n\n /// Create a new `UploadClient` from an access token\n", "file_path": "src/api/upload/client.rs", "rank": 60, "score": 30085.00236688375 }, { "content": "use crate::constants::{ENV_VAR_NAME, UPLOAD_API};\n\nuse crate::https::{get_https_client, tls};\n\nuse crate::log::debug;\n\nuse crate::models::*;\n\nuse crate::status::raise_for_status;\n\nuse crate::types::Result;\n\nuse crate::utils::into_struct_from_slice;\n\nuse crate::RustWistiaError;\n\n\n\nuse std::env::var;\n\nuse std::time::Instant;\n\n\n\nuse hyper::body::HttpBody;\n\nuse hyper::client::HttpConnector;\n\nuse hyper::{Body, Client, Request};\n\nuse serde_urlencoded::to_string;\n\n\n\n/// Client used to make requests to the Wistia **[Upload API]**.\n\n///\n\n/// # Note\n", "file_path": "src/api/upload/client.rs", "rank": 63, "score": 30081.28709975525 }, { "content": " into_struct_from_slice(resp).await\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use serde::{Deserialize, Serialize};\n\n\n\n #[test]\n\n fn test_url_encoded_with_struct() {\n\n #[derive(Deserialize, Serialize, PartialEq, Debug)]\n\n struct Meal<'a> {\n\n bread: &'a str,\n\n cheese: &'a str,\n\n meat: &'a str,\n\n fat: &'a str,\n\n }\n\n\n\n let m = Meal {\n\n bread: \"baguette\",\n", "file_path": "src/api/upload/client.rs", "rank": 65, "score": 30077.607554351074 }, { "content": " cheese: \"comté\",\n\n meat: \"ham\",\n\n fat: \"butter\",\n\n };\n\n\n\n assert_eq!(\n\n serde_urlencoded::to_string::<Meal>(m),\n\n Ok(\"bread=baguette&cheese=comt%C3%A9&meat=ham&fat=butter\".to_owned())\n\n );\n\n }\n\n}\n", "file_path": "src/api/upload/client.rs", "rank": 66, "score": 30064.34831625462 }, { "content": "use crate::utils::is_default;\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct Asset {\n\n pub content_type: String,\n\n pub file_size: u64,\n\n #[serde(rename = \"type\")]\n\n pub type_field: String,\n\n pub url: String,\n\n /// Note: `height` will **not** be populated for audio (or alternate audio) files\n\n #[serde(skip_serializing_if = \"is_default\")]\n\n #[serde(default)]\n\n pub height: u64,\n\n /// Note: `width` will **not** be populated for audio (or alternate audio) files\n\n #[serde(skip_serializing_if = \"is_default\")]\n\n #[serde(default)]\n\n pub width: u64,\n\n}\n", "file_path": "src/models/media/asset.rs", "rank": 67, "score": 29997.326355250967 }, { "content": "use serde::{Deserialize, Serialize};\n\n\n\n/// An object representing the [thumbnail] for a media.\n\n///\n\n/// [thumbnail]: https://wistia.com/support/developers/data-api#medias-response\n\n#[derive(Default, Debug, PartialEq, Serialize, Deserialize)]\n\npub struct Thumbnail {\n\n pub url: String,\n\n pub width: u64,\n\n pub height: u64,\n\n}\n", "file_path": "src/models/media/thumbnail.rs", "rank": 68, "score": 29995.8050399402 }, { "content": "use serde::{Deserialize, Serialize};\n\n\n\n#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]\n\npub struct ProjectInfo {\n\n pub hashed_id: String,\n\n pub id: u64,\n\n pub name: String,\n\n}\n", "file_path": "src/models/media/project.rs", "rank": 69, "score": 29994.16826941586 }, { "content": "mod asset;\n\nmod download_asset;\n\nmod media;\n\nmod media_info;\n\nmod project;\n\nmod status;\n\nmod thumbnail;\n\nmod r#type;\n\nmod update_request;\n\n\n\npub use asset::*;\n\npub use download_asset::*;\n\npub use media::*;\n\npub use media_info::*;\n\npub use project::*;\n\npub use r#type::*;\n\npub use status::*;\n\npub use thumbnail::*;\n\npub use update_request::*;\n", "file_path": "src/models/media/mod.rs", "rank": 70, "score": 29992.078313762875 }, { "content": "use serde::{Deserialize, Serialize};\n\n\n\n/// Media files return a response attribute called status.\n\n///\n\n/// After upload is complete, media files must be processed. Status indicates\n\n/// which stage in processing the file is at.\n\n///\n\n/// See also: [Media Status][]\n\n///\n\n/// [Media Status]: https://wistia.com/support/developers/data-api#media-status\n\n#[derive(Debug, PartialEq, Serialize, Deserialize)]\n\n#[serde(rename_all = \"lowercase\")]\n\npub enum MediaStatus {\n\n /// **queued**: the file is waiting in the queue to be processed\n\n Queued,\n\n /// **processing**: the file is actively being processed\n\n Processing,\n\n /// **ready**: the file has been fully processed and is ready for\n\n /// embedding and viewing.\n\n Ready,\n", "file_path": "src/models/media/status.rs", "rank": 71, "score": 29988.393904452525 }, { "content": " /// **failed**: the file was unable to be processed (usually a\n\n /// [format or size error](https://wistia.com/support/uploading/export-settings))\n\n Failed,\n\n}\n\n\n\nimpl Default for MediaStatus {\n\n fn default() -> Self {\n\n Self::Queued\n\n }\n\n}\n", "file_path": "src/models/media/status.rs", "rank": 72, "score": 29984.05899043098 }, { "content": " req: UploadFileRequest::new(file_path),\n\n })\n\n }\n\n\n\n /// Create a `FileUploader` with a new HTTPS client and a Wistia access\n\n /// token.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `file_path` - The path to the media file. The contents of this file\n\n /// will be multipart-form encoded into the request body.\n\n /// * `access_token` - An API access token used to make requests to the\n\n /// Wistia API.\n\n ///\n\n pub fn with_token(file_path: P, access_token: &str) -> Self {\n\n Self {\n\n client: UploadClient::from_token(access_token),\n\n req: UploadFileRequest::new(file_path),\n\n }\n\n }\n", "file_path": "src/api/upload/file.rs", "rank": 73, "score": 29573.30699777039 }, { "content": "\n\n /// Create a `FileUploader` with a file path and an HTTPS client.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `file_path` - The path to the media file. The contents of this file\n\n /// will be multipart-form encoded into the request body.\n\n /// * `client` - The HTTPS client (UploadClient) to use for requests.\n\n /// Note that the client must support multipart form requests, via a\n\n /// `multipart::Body`.\n\n ///\n\n pub fn with_client(file_path: P, client: UploadClient<Body>) -> Self {\n\n Self {\n\n client,\n\n req: UploadFileRequest::new(file_path),\n\n }\n\n }\n\n\n\n /// The hashed id of the project to upload media into. If omitted, a new\n\n /// project will be created and uploaded to. The naming convention used\n", "file_path": "src/api/upload/file.rs", "rank": 74, "score": 29570.351184432155 }, { "content": "/// [Upload API]: https://wistia.com/support/developers/upload-api\n\n///\n\n#[derive(Clone)]\n\npub struct FileUploader<'a, P: AsRef<Path>, B = Body> {\n\n client: UploadClient<B>,\n\n req: UploadFileRequest<'a, P>,\n\n}\n\n\n\nimpl<'a, P: AsRef<Path> + Debug> FileUploader<'a, P> {\n\n /// Create a `FileUploader` with a new HTTPS client, with the access token\n\n /// retrieved from the environment.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `file_path` - The path to the media file. The contents of this file\n\n /// will be multipart-form encoded into the request body.\n\n ///\n\n pub fn new(file_path: P) -> Result<Self> {\n\n Ok(Self {\n\n client: UploadClient::from_env()?,\n", "file_path": "src/api/upload/file.rs", "rank": 75, "score": 29569.745590596503 }, { "content": " /// A Wistia contact id, an integer value. If omitted, it will default to\n\n /// the contact_id of the account’s owner.\n\n pub fn contact_id(mut self, contact_id: &'a str) -> Self {\n\n self.req.contact_id = Some(contact_id);\n\n self\n\n }\n\n\n\n /// Send the Upload File request (with the *multi-part form* data) to the\n\n /// Wistia [Upload API].\n\n ///\n\n /// [Upload API]: https://wistia.com/support/developers/upload-api\n\n ///\n\n // noinspection DuplicatedCode\n\n pub async fn send(&self) -> Result<UploadResponse> {\n\n // Build the query parameters to pass to the Upload API\n\n\n\n let params = UploadRequest {\n\n access_token: self.client.access_token.as_str(),\n\n url: None,\n\n project_id: self.req.project_id,\n", "file_path": "src/api/upload/file.rs", "rank": 76, "score": 29568.17768252009 }, { "content": " name: self.req.name,\n\n description: None,\n\n contact_id: self.req.contact_id,\n\n };\n\n\n\n let url = UploadClient::<Body>::build_url(params)?;\n\n\n\n // Create a request instance and multipart form\n\n let req_builder = Request::post(&url);\n\n let mut form = Form::default();\n\n\n\n // Add multi-part form fields\n\n\n\n form.add_file(\"file\", &self.req.file_path)\n\n .map_err(|e: io::Error| match e.kind() {\n\n io::ErrorKind::NotFound => RustWistiaError::FileNotFound(\n\n self.req.file_path.as_ref().to_string_lossy().to_string(),\n\n ),\n\n _ => RustWistiaError::Io(e),\n\n })?;\n", "file_path": "src/api/upload/file.rs", "rank": 77, "score": 29567.497480405807 }, { "content": " /// for such projects is `Uploads_YYYY-MM-DD`.\n\n pub fn project_id(mut self, project_id: &'a str) -> Self {\n\n self.req.project_id = Some(project_id);\n\n self\n\n }\n\n\n\n /// A display name to use for the media in Wistia. If omitted, the filename\n\n /// will be used instead. This field is limited to 255 characters.\n\n pub fn name(mut self, name: &'a str) -> Self {\n\n self.req.name = Some(name);\n\n self\n\n }\n\n\n\n /// A description to use for the media in Wistia. You can use basic HTML\n\n /// here, but note that both HTML and CSS will be sanitized.\n\n pub fn description(mut self, description: &'a str) -> Self {\n\n self.req.description = Some(description);\n\n self\n\n }\n\n\n", "file_path": "src/api/upload/file.rs", "rank": 78, "score": 29566.80963434476 }, { "content": "\n\n if let Some(description) = self.req.description {\n\n form.add_text(\"description\", description);\n\n }\n\n\n\n // Update a request instance with the multipart Content-Type header\n\n // and the payload data.\n\n let form = form.set_body::<Body>(req_builder).unwrap();\n\n\n\n // Send the request\n\n self.client.make_request(&url, form).await\n\n }\n\n}\n", "file_path": "src/api/upload/file.rs", "rank": 79, "score": 29561.62651409903 }, { "content": "use crate::api::client::UploadClient;\n\nuse crate::models::*;\n\nuse crate::types::Result;\n\nuse crate::RustWistiaError;\n\n\n\nuse std::fmt::Debug;\n\nuse std::io;\n\nuse std::path::Path;\n\n\n\nuse hyper::Request;\n\nuse hyper_multipart::client::multipart::Form;\n\nuse hyper_multipart_rfc7578 as hyper_multipart;\n\nuse hyper_multipart_rfc7578::client::multipart::Body;\n\n\n\n/// Client implementation to upload *files* and *videos* via the Wistia\n\n/// **[Upload API]**.\n\n///\n\n/// Also check out the [`rust-wistia`] docs for usage and examples.\n\n///\n\n/// [`rust-wistia`]: https://docs.rs/rust-wistia\n", "file_path": "src/api/upload/file.rs", "rank": 80, "score": 29552.98373699894 }, { "content": " contact_id: String,\n\n}\n\n\n\n// noinspection DuplicatedCode\n\n#[tokio::main]\n\nasync fn main() -> Result<()> {\n\n sensible_env_logger::init_timed_short!();\n\n\n\n let args: Args = Args::parse();\n\n\n\n trace!(\"Uploading file stream to Wistia...\");\n\n\n\n let bytes = fs::read(args.file_path)?;\n\n let reader = Cursor::new(bytes);\n\n\n\n // Alternatively, we could use `StreamUploader::new(path)?` to\n\n // create the new `StreamUploader` instance.\n\n let res = StreamUploader::new(reader)?\n\n .project_id(&args.project_id)\n\n .name(&args.name)\n", "file_path": "examples/upload_file_stream.rs", "rank": 81, "score": 29549.058840195696 }, { "content": "use rust_wistia::{Result, StreamUploader};\n\n\n\n#[macro_use]\n\nextern crate log;\n\n\n\nuse std::fs;\n\nuse std::io::Cursor;\n\nuse std::path::PathBuf;\n\n\n\nuse clap::Parser;\n\n\n\n/// Upload a local file stream to Wistia\n\n// noinspection DuplicatedCode\n\n#[derive(Parser, Debug)]\n", "file_path": "examples/upload_file_stream.rs", "rank": 82, "score": 29543.092270179306 }, { "content": " .description(&args.description)\n\n .contact_id(&args.contact_id)\n\n .send()\n\n .await?;\n\n\n\n trace!(\"Response: {res:#?}\");\n\n trace!(\"Video ID: {}\", res.hashed_id);\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/upload_file_stream.rs", "rank": 83, "score": 29542.46779180645 }, { "content": "}\n\n\n\nimpl<'a> DownloadAssetRequest<'a> {\n\n /// Sets the media *asset type* to download from Wistia.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use rust_wistia::models::DownloadAssetRequest;\n\n ///\n\n /// let info = DownloadAssetRequest::from(\"my-video-id\").asset_type(\"OriginalFile\");\n\n /// ``` \n\n pub fn asset_type(mut self, asset_type: &'a str) -> Self {\n\n self.asset_type = Some(asset_type);\n\n self\n\n }\n\n\n\n /// Sets a local *file path* to save the downloaded media content to.\n\n ///\n\n /// # Examples\n", "file_path": "src/models/media/download_asset.rs", "rank": 84, "score": 28971.749792946917 }, { "content": " /// let media = WistiaClient::from_env()?.get_media(\"my-id\").await?;\n\n /// let info = DownloadAssetRequest::from(media);\n\n /// ``` \n\n pub media: Option<Media>,\n\n\n\n /// The media *asset type* to download.\n\n pub asset_type: Option<&'a str>,\n\n\n\n /// Sets a local *file path* to save the downloaded media content to.\n\n pub file_path: Option<PathBuf>,\n\n}\n\n\n\nimpl<'a> From<&'a str> for DownloadAssetRequest<'a> {\n\n /// Create a new `DownloadAssetRequest` from a Wistia `media_id`\n\n fn from(media_id: &'a str) -> Self {\n\n Self {\n\n media_id: Some(media_id),\n\n ..Default::default()\n\n }\n\n }\n", "file_path": "src/models/media/download_asset.rs", "rank": 85, "score": 28965.37847036904 }, { "content": "use crate::models::Media;\n\nuse std::path::{Path, PathBuf};\n\n\n\n/// Represents a request to download an [Asset URL].\n\n///\n\n/// [Asset URL]: https://wistia.com/support/developers/asset-urls\n\n///\n\n#[derive(Default)]\n\npub struct DownloadAssetRequest<'a> {\n\n /// The Wistia media to download.\n\n pub media_id: Option<&'a str>,\n\n\n\n /// The Wistia media to download.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```rust,ignore\n\n /// use rust_wistia::models::DownloadAssetRequest;\n\n /// use rust_wistia::WistiaClient;\n\n ///\n", "file_path": "src/models/media/download_asset.rs", "rank": 86, "score": 28962.657234306975 }, { "content": " ///\n\n /// ```rust,ignore\n\n /// use rust_wistia::models::DownloadAssetRequest;\n\n /// use rust_wistia::WistiaClient;\n\n ///\n\n /// let info = DownloadAssetRequest::from(\"my-video-id\").file_path(\"./my-file.mp4\");\n\n /// let _ = WistiaClient::from_env()?.download_asset(info).await?;\n\n /// ``` \n\n pub fn file_path(mut self, file_path: impl AsRef<Path>) -> Self {\n\n self.file_path = Some(file_path.as_ref().into());\n\n self\n\n }\n\n}\n", "file_path": "src/models/media/download_asset.rs", "rank": 87, "score": 28960.510646592968 }, { "content": "}\n\n\n\nimpl<'a> From<&'a String> for DownloadAssetRequest<'a> {\n\n /// Create a new `DownloadAssetRequest` from a Wistia `media_id`\n\n fn from(media_id: &'a String) -> Self {\n\n Self {\n\n media_id: Some(media_id),\n\n ..Default::default()\n\n }\n\n }\n\n}\n\n\n\nimpl<'a> From<Media> for DownloadAssetRequest<'a> {\n\n /// Create a new `DownloadAssetRequest` from a `Media` object\n\n fn from(media: Media) -> Self {\n\n Self {\n\n media: Some(media),\n\n ..Default::default()\n\n }\n\n }\n", "file_path": "src/models/media/download_asset.rs", "rank": 88, "score": 28956.717951011586 }, { "content": " ///\n\n /// ```\n\n /// use rust_wistia::{StreamUploader, https::get_https_client};\n\n ///\n\n /// let mut uploader = StreamUploader::with_url(\"https://google.com/my/image\").await?;\n\n /// ```\n\n pub async fn with_url(url: &str) -> Result<StreamUploader<'a, Cursor<Bytes>>> {\n\n let stream = stream_reader_from_url(url, None).await?;\n\n Self::new(stream)\n\n }\n\n\n\n /// Create a new `StreamUploader` which uses the *bytes* content downloaded\n\n /// from a publicly accessible **url**.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `url` - A public accessible url to the media which will be downloaded.\n\n /// * `access_token` - An API access token used to make requests to the\n\n /// Wistia API.\n\n ///\n", "file_path": "src/api/upload/file_stream.rs", "rank": 89, "score": 28548.046012953157 }, { "content": "///\n\n/// [`rust-wistia`]: https://docs.rs/rust-wistia\n\n/// [Upload API]: https://wistia.com/support/developers/upload-api\n\n///\n\n#[derive(Clone)]\n\npub struct StreamUploader<'a, R: 'static + Read + Send + Sync, B = Body> {\n\n client: UploadClient<B>,\n\n req: UploadStreamRequest<'a>,\n\n reader: Option<R>,\n\n}\n\n\n\nimpl<'a> StreamUploader<'a, Cursor<Bytes>> {\n\n /// Create a new `StreamUploader` which uses the *bytes* content downloaded\n\n /// from a publicly accessible **url**.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `url` - A public accessible url to the media which will be downloaded.\n\n ///\n\n /// # Examples\n", "file_path": "src/api/upload/file_stream.rs", "rank": 90, "score": 28546.29459353789 }, { "content": " /// # Examples\n\n ///\n\n /// ```\n\n /// use rust_wistia::{StreamUploader, https::get_https_client};\n\n ///\n\n /// let mut uploader = StreamUploader::with_url_and_token(\n\n /// \"https://google.com/my/image\",\n\n /// \"my-token\"\n\n /// )\n\n /// .await?;\n\n /// ```\n\n pub async fn with_url_and_token(\n\n url: &str,\n\n access_token: &str,\n\n ) -> Result<StreamUploader<'a, Cursor<Bytes>>> {\n\n let stream = stream_reader_from_url(url, None).await?;\n\n Ok(Self::with_token(access_token).stream(stream))\n\n }\n\n\n\n /// Create a new `StreamUploader` which uses the *bytes* content downloaded\n", "file_path": "src/api/upload/file_stream.rs", "rank": 91, "score": 28545.985026348586 }, { "content": " /// The hashed id of the project to upload media into. If omitted, a new\n\n /// project will be created and uploaded to. The naming convention used\n\n /// for such projects is `Uploads_YYYY-MM-DD`.\n\n pub fn project_id(mut self, project_id: &'a str) -> Self {\n\n self.req.project_id = Some(project_id);\n\n self\n\n }\n\n\n\n /// A display name to use for the media in Wistia. If omitted, the filename\n\n /// will be used instead. This field is limited to 255 characters.\n\n pub fn name(mut self, name: &'a str) -> Self {\n\n self.req.name = Some(name);\n\n self\n\n }\n\n\n\n /// A description to use for the media in Wistia. You can use basic HTML\n\n /// here, but note that both HTML and CSS will be sanitized.\n\n pub fn description(mut self, description: &'a str) -> Self {\n\n self.req.description = Some(description);\n\n self\n", "file_path": "src/api/upload/file_stream.rs", "rank": 92, "score": 28545.555317639017 }, { "content": " }\n\n\n\n /// A Wistia contact id, an integer value. If omitted, it will default to\n\n /// the contact_id of the account’s owner.\n\n pub fn contact_id(mut self, contact_id: &'a str) -> Self {\n\n self.req.contact_id = Some(contact_id);\n\n self\n\n }\n\n\n\n /// Send the Upload File request (with the *multi-part form* data) to the\n\n /// Wistia [Upload API].\n\n ///\n\n /// [Upload API]: https://wistia.com/support/developers/upload-api\n\n ///\n\n // noinspection DuplicatedCode\n\n pub async fn send(self) -> Result<UploadResponse> {\n\n // Build the query parameters to pass to the Upload API\n\n\n\n let params = UploadRequest {\n\n access_token: self.client.access_token.as_str(),\n", "file_path": "src/api/upload/file_stream.rs", "rank": 93, "score": 28545.465987401833 }, { "content": " pub fn with_filename(file_name: &'a str) -> Result<Self> {\n\n Ok(Self {\n\n client: UploadClient::from_env()?,\n\n req: UploadStreamRequest::new(file_name),\n\n reader: None,\n\n })\n\n }\n\n\n\n /// Create a `SteamUploader` with a new HTTPS client and a Wistia access\n\n /// token.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `access_token` - An API access token used to make requests to the\n\n /// Wistia API.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use rust_wistia::StreamUploader;\n", "file_path": "src/api/upload/file_stream.rs", "rank": 94, "score": 28545.439202917787 }, { "content": " ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use rust_wistia::StreamUploader;\n\n /// use std::io::Cursor;\n\n ///\n\n /// let bytes = Cursor::new(\"Hello World!\");\n\n /// let uploader = StreamUploader::with_stream_and_filename(bytes, \"my_file.mp4\")?;\n\n ///\n\n /// let res = uploader.send()?.await?;\n\n /// ```\n\n ///\n\n pub fn with_stream_and_filename(stream: R, file_name: &'a str) -> Result<Self> {\n\n Ok(Self {\n\n client: UploadClient::from_env()?,\n\n req: UploadStreamRequest::new(file_name),\n\n reader: Some(stream),\n\n })\n\n }\n", "file_path": "src/api/upload/file_stream.rs", "rank": 95, "score": 28545.054217213576 }, { "content": " url: None,\n\n project_id: self.req.project_id,\n\n name: self.req.name,\n\n description: None,\n\n contact_id: self.req.contact_id,\n\n };\n\n\n\n let url = UploadClient::<Body>::build_url(params)?;\n\n\n\n // Create a request instance and multipart form\n\n let req_builder = Request::post(&url);\n\n let mut form = Form::default();\n\n\n\n // Add multi-part form fields\n\n\n\n // TODO worth checking for unwrap()?\n\n form.add_reader_file(\"file\", self.reader.unwrap(), self.req.file_name);\n\n\n\n if let Some(description) = self.req.description {\n\n form.add_text(\"description\", description);\n", "file_path": "src/api/upload/file_stream.rs", "rank": 96, "score": 28544.172972864028 }, { "content": " /// use rust_wistia::StreamUploader;\n\n /// use std::io::Cursor;\n\n ///\n\n /// let bytes = Cursor::new(\"Hello World!\");\n\n /// let uploader = StreamUploader::new(bytes)?;\n\n ///\n\n /// let res = uploader.name(\"My Video Name\").send()?.await?;\n\n /// ```\n\n /// \n\n pub fn new(stream: R) -> Result<Self> {\n\n Self::with_stream_and_filename(stream, DEFAULT_FILENAME)\n\n }\n\n\n\n /// Create a `SteamUploader` with a new HTTPS client, with the access token\n\n /// retrieved from the environment.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `stream` - A readable file-like *stream* object to upload.\n\n /// * `file_name` - The name of the media file.\n", "file_path": "src/api/upload/file_stream.rs", "rank": 97, "score": 28541.59565786041 }, { "content": " /// Set the publicly-accessible URL link to the media file. The link\n\n /// will be *form-url encoded* into the request body.\n\n ///\n\n /// # Note\n\n /// This method call is only needed when the `UrlUploader::from`\n\n /// constructor is called.\n\n pub fn url(mut self, url: &'a str) -> Self {\n\n self.req.url = url;\n\n self\n\n }\n\n\n\n /// The hashed id of the project to upload media into. If omitted, a new\n\n /// project will be created and uploaded to. The naming convention used\n\n /// for such projects is `Uploads_YYYY-MM-DD`.\n\n pub fn project_id(mut self, project_id: &'a str) -> Self {\n\n self.req.project_id = Some(project_id);\n\n self\n\n }\n\n\n\n /// A display name to use for the media in Wistia. If omitted, the filename\n", "file_path": "src/api/upload/link.rs", "rank": 98, "score": 34.03826458661081 }, { "content": " }\n\n\n\n /// Create an `UrlUploader` with a new HTTPS client and a Wistia access\n\n /// token.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `url` - A publicly-accessible URL link to the media file. The link\n\n /// will be *form-url encoded* into the request body.\n\n /// * `access_token` - An API access token used to make requests to the\n\n /// Wistia API.\n\n ///\n\n pub fn with_token(url: &'a str, access_token: &str) -> Self {\n\n Self {\n\n client: UploadClient::from(access_token),\n\n req: UploadUrlRequest {\n\n url,\n\n ..Default::default()\n\n },\n\n }\n", "file_path": "src/api/upload/link.rs", "rank": 99, "score": 32.69777336956889 } ]
Rust
syn-meta-ext/src/lib.rs
YoloDev/evitable
c1284df0c60a99f07caf037e22b7c8ab37b28fca
extern crate ident_case; extern crate proc_macro2; #[cfg_attr(test, macro_use)] extern crate quote; #[cfg_attr(test, macro_use)] extern crate syn; use proc_macro2::TokenStream; use quote::ToTokens; use syn::parse::*; use syn::{parenthesized, parse, token, Attribute, Ident, Lit, LitBool, Path, Token}; pub mod ast; pub mod error; mod from_derive_input; mod from_field; mod from_meta; mod from_variant; pub use ast::*; pub use from_derive_input::FromDeriveInput; pub use from_field::FromField; pub use from_meta::FromMeta; pub use from_variant::FromVariant; pub trait PathExt { fn single_ident(&self) -> Option<&Ident>; fn to_compact_string(&self) -> String; } impl PathExt for Path { fn single_ident(&self) -> Option<&Ident> { if self.leading_colon.is_none() && self.segments.len() == 1 && self.segments[0].arguments == syn::PathArguments::None { Some(&self.segments[0].ident) } else { None } } fn to_compact_string(&self) -> String { self .segments .iter() .map(|s| { let mut ident = s.ident.to_string(); match &s.arguments { syn::PathArguments::None => ident, syn::PathArguments::AngleBracketed(args) => { if args.colon2_token.is_some() { ident.push_str("::"); } ident.push_str("<"); for arg in &args.args { match arg { syn::GenericArgument::Lifetime(l) => { ident.push('\''); ident.push_str(&l.ident.to_string()); } syn::GenericArgument::Type(t) => { let mut ts = TokenStream::new(); t.to_tokens(&mut ts); ident.push_str(&format!("{}", ts)); } syn::GenericArgument::Binding(b) => { ident.push_str(&b.ident.to_string()); ident.push('='); let mut ts = TokenStream::new(); b.ty.to_tokens(&mut ts); ident.push_str(&format!("{}", ts)); } syn::GenericArgument::Constraint(c) => { ident.push_str(&c.ident.to_string()); ident.push_str(": "); let mut ts = TokenStream::new(); c.bounds.to_tokens(&mut ts); ident.push_str(&format!("{}", ts)); } syn::GenericArgument::Const(e) => { let mut ts = TokenStream::new(); e.to_tokens(&mut ts); ident.push_str(&format!("{}", ts)); } } } ident.push_str(">"); ident } syn::PathArguments::Parenthesized(args) => { let mut ts = TokenStream::new(); args.to_tokens(&mut ts); ident.push_str(&format!("{}", ts)); ident } } }) .collect::<Vec<String>>() .join("::") } } pub trait AttrExt { fn meta(&self) -> Result<Meta>; } impl AttrExt for Attribute { fn meta(&self) -> Result<Meta> { let parser = |input: ParseStream| parse_meta_after_path(self.path.clone(), input); parse::Parser::parse2(parser, self.tokens.clone()) } } #[derive(Debug, Clone, PartialEq)] pub enum Meta { Path(syn::Path), List(MetaList), NameValue(MetaNameValue), } impl Meta { pub fn path(&self) -> &Path { match self { Meta::Path(meta) => meta, Meta::List(meta) => &meta.path, Meta::NameValue(meta) => &meta.path, } } pub fn is<S>(&self, path: S) -> bool where S: AsRef<str>, { match self.path().single_ident() { None => false, Some(i) => { let actual = i.to_string(); &actual == path.as_ref() } } } } #[derive(Debug, Clone, PartialEq)] pub struct MetaList { pub path: syn::Path, pub paren_token: syn::token::Paren, pub nested: syn::punctuated::Punctuated<NestedMeta, syn::token::Comma>, } impl IntoIterator for MetaList { type Item = <syn::punctuated::Punctuated<NestedMeta, syn::token::Comma> as IntoIterator>::Item; type IntoIter = <syn::punctuated::Punctuated<NestedMeta, syn::token::Comma> as IntoIterator>::IntoIter; #[inline] fn into_iter(self) -> Self::IntoIter { self.nested.into_iter() } } impl<'a> IntoIterator for &'a MetaList { type Item = <&'a syn::punctuated::Punctuated<NestedMeta, syn::token::Comma> as IntoIterator>::Item; type IntoIter = <&'a syn::punctuated::Punctuated<NestedMeta, syn::token::Comma> as IntoIterator>::IntoIter; #[inline] fn into_iter(self) -> Self::IntoIter { (&self.nested).into_iter() } } #[derive(Debug, Clone, PartialEq)] pub enum NestedMeta { Meta(Meta), Literal(syn::Lit), } #[derive(Debug, Clone, PartialEq)] pub struct MetaNameValue { pub path: syn::Path, pub eq_token: syn::token::Eq, pub val: MetaValue, } #[derive(Debug, Clone, PartialEq)] pub enum MetaValue { Path(syn::Path), Literal(syn::Lit), } impl Parse for MetaValue { fn parse(input: ParseStream) -> Result<Self> { let ahead = input.fork(); if ahead.call(Path::parse).is_ok() { input.parse().map(MetaValue::Path) } else if ahead.call(Lit::parse).is_ok() { input.parse().map(MetaValue::Literal) } else { Err(input.error("expected path or literal")) } } } impl Parse for Meta { fn parse(input: ParseStream) -> Result<Self> { let path = input.call(Path::parse)?; parse_meta_after_path(path, input) } } impl Parse for MetaList { fn parse(input: ParseStream) -> Result<Self> { let path = input.call(Path::parse)?; parse_meta_list_after_path(path, input) } } impl Parse for MetaNameValue { fn parse(input: ParseStream) -> Result<Self> { let path = input.call(Path::parse)?; parse_meta_name_value_after_path(path, input) } } impl Parse for NestedMeta { fn parse(input: ParseStream) -> Result<Self> { let ahead = input.fork(); if ahead.peek(Lit) && !(ahead.peek(LitBool) && ahead.peek2(Token![=])) { input.parse().map(NestedMeta::Literal) } else if ahead.call(Path::parse).is_ok() { input.parse().map(NestedMeta::Meta) } else { Err(input.error("expected path or literal")) } } } fn parse_meta_after_path(path: Path, input: ParseStream) -> Result<Meta> { if input.peek(token::Paren) { parse_meta_list_after_path(path, input).map(Meta::List) } else if input.peek(Token![=]) { parse_meta_name_value_after_path(path, input).map(Meta::NameValue) } else { Ok(Meta::Path(path)) } } fn parse_meta_list_after_path(path: Path, input: ParseStream) -> Result<MetaList> { let content; Ok(MetaList { path: path, paren_token: parenthesized!(content in input), nested: content.parse_terminated(NestedMeta::parse)?, }) } fn parse_meta_name_value_after_path(path: Path, input: ParseStream) -> Result<MetaNameValue> { Ok(MetaNameValue { path: path, eq_token: input.parse()?, val: input.parse()?, }) } impl ToTokens for MetaValue { fn to_tokens(&self, tokens: &mut TokenStream) { match self { MetaValue::Literal(l) => l.to_tokens(tokens), MetaValue::Path(p) => p.to_tokens(tokens), } } } impl ToTokens for MetaNameValue { fn to_tokens(&self, tokens: &mut TokenStream) { self.path.to_tokens(tokens); self.eq_token.to_tokens(tokens); self.val.to_tokens(tokens); } } impl ToTokens for NestedMeta { fn to_tokens(&self, tokens: &mut TokenStream) { match self { NestedMeta::Meta(meta) => meta.to_tokens(tokens), NestedMeta::Literal(lit) => lit.to_tokens(tokens), } } } impl ToTokens for MetaList { fn to_tokens(&self, tokens: &mut TokenStream) { self.path.to_tokens(tokens); self.paren_token.surround(tokens, |tokens| { self.nested.to_tokens(tokens); }) } } impl ToTokens for Meta { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Meta::Path(path) => path.to_tokens(tokens), Meta::List(list) => list.to_tokens(tokens), Meta::NameValue(nv) => nv.to_tokens(tokens), } } } #[cfg(test)] mod test { use super::*; #[test] pub fn derive_test() { let input: syn::ItemStruct = parse_quote! { #[evitable::from = ::std::io::Error] struct Foo; }; let attr = &input.attrs[0]; let meta = attr.meta().unwrap(); let path_str = format!("{}", meta.path().into_token_stream()); println!("{:?}", meta); assert_eq!(path_str, "evitable :: from"); } }
extern crate ident_case; extern crate proc_macro2; #[cfg_attr(test, macro_use)] extern crate quote; #[cfg_attr(test, macro_use)] extern crate syn; use proc_macro2::TokenStream; use quote::ToTokens; use syn::parse::*; use syn::{parenthesized, parse, token, Attribute, Ident, Lit, LitBool, Path, Token}; pub mod ast; pub mod error; mod from_derive_input; mod from_field; mod from_meta; mod from_variant; pub use ast::*; pub use from_derive_input::FromDeriveInput; pub use from_field::FromField; pub use from_meta::FromMeta; pub use from_variant::FromVariant; pub trait PathExt { fn single_ident(&self) -> Option<&Ident>; fn to_compact_string(&self) -> String; } impl PathExt for Path { fn single_ident(&self) -> Option<&Ident> { if self.leading_colon.is_none() && self.segments.len() == 1 && self.segments[0].arguments == syn::PathArguments::None { Some(&self.segments[0].ident) } else { None } } fn to_compact_string(&self) -> String { self .segments .iter() .map(|s| { let mut ident = s.ident.to_string(); match &s.arguments { syn::PathArguments::None => ident, syn::PathArguments::AngleBracketed(args) => { if args.colon2_token.is_some() { ident.push_str("::"); } ident.push_str("<"); for arg in &args.args { match arg { syn::GenericArgument::Lifetime(l) => { ident.push('\''); ident.push_str(&l.ident.to_string()); } syn::GenericArgument::Type(t) => { let mut ts = TokenStream::new(); t.to_tokens(&mut ts); ident.push_str(&format!("{}", ts)); } syn::GenericArgument::Binding(b) => { ident.push_str(&b.ident.to_string()); ident.push('='); let mut ts = TokenStream::new(); b.ty.to_tokens(&mut ts); ident.push_str(&format!("{}", ts)); } syn::GenericArgument::Constraint(c) => { ident.push_str(&c.ident.to_string()); ident.push_str(": "); let mut ts = TokenStream::new(); c.bounds.to_tokens(&mut ts); ident.push_str(&format!("{}", ts)); } syn::GenericArgument::Const(e) => { let mut ts = TokenStream::new(); e.to_tokens(&mut ts); ident.push_str(&format!("{}", ts)); } } } ident.push_str(">"); ident } syn::PathArguments::Parenthesized(args) => { let mut ts = TokenStream::new(); args.to_tokens(&mut ts); ident.push_str(&format!("{}", ts)); ident } } }) .collect::<Vec<String>>() .join("::") } } pub trait AttrExt { fn meta(&self) -> Result<Meta>; } impl AttrExt for Attribute { fn meta(&self) -> Result<Meta> { let parser = |input: ParseStream| parse_meta_after_path(self.path.clone(), input); parse::Parser::parse2(parser, self.tokens.clone()) } } #[derive(Debug, Clone, PartialEq)] pub enum Meta { Path(syn::Path), List(MetaList), NameValue(MetaNameValue), } impl Meta { pub fn path(&self) -> &Path { match self { Meta::Path(meta) => meta, Meta::List(meta) => &meta.path, Meta::NameValue(meta) => &meta.path, } } pub fn is<S>(&self, path: S) -> bool where S: AsRef<str>, { match self.path().single_ident() { None => false, Some(i) => { let actual = i.to_string(); &actual == path.as_ref() } } } } #[derive(Debug, Clone, PartialEq)] pub struct MetaList { pub path: syn::Path, pub paren_token: syn::token::Paren, pub nested: syn::punctuated::Punctuated<NestedMeta, syn::token::Comma>, } impl IntoIterator for MetaList { type Item = <syn::punctuated::Punctuated<NestedMeta, syn::token::Comma> as IntoIterator>::Item; type IntoIter = <syn::punctuated::Punctuated<NestedMeta, syn::token::Comma> as IntoIterator>::IntoIter; #[inline] fn into_iter(self) -> Self::IntoIter { self.nested.into_iter() } } impl<'a> IntoIterator for &'a MetaList { type Item = <&'a syn::punctuated::Punctuated<NestedMeta, syn::token::Comma> as IntoIterator>::Item; type IntoIter = <&'a syn::punctuated::Punctuated<NestedMeta, syn::token::Comma> as IntoIterator>::IntoIter; #[inline] fn into_iter(self) -> Self::IntoIter { (&self.nested).into_iter() } } #[derive(Debug, Clone, PartialEq)] pub enum NestedMeta { Meta(Meta), Literal(syn::Lit), } #[derive(Debug, Clone, PartialEq)] pub struct MetaNameValue { pub path: syn::Path, pub eq_token: syn::token::Eq, pub val: MetaValue, } #[derive(Debug, Clone, PartialEq)] pub enum MetaValue { Path(syn::Path), Literal(syn::Lit), } impl Parse for MetaValue { fn parse(input: ParseStream) -> Result<Self> { let ahead = input.fork(); if ahead.call(Path::parse).is_ok() { input.parse().map(MetaValue::Path) } else if ahead.call(Lit::parse).is_ok() { input.parse().map(MetaValue::Literal) } else { Err(input.error("expected path or literal")) } } } impl Parse for Meta { fn parse(input: ParseStream) -> Result<Self> { let path = input.call(Path::parse)?; parse_meta_after_path(path, input) } } impl Parse for MetaList { fn parse(input: ParseStream) -> Result<Self> { let path = input.call(Path::parse)?; parse_meta_list_after_path(path, input) } } impl Parse for MetaNameValue { fn parse(input: ParseStream) -> Result<Self> { let path = input.call(Path::parse)?; parse_meta_name_value_after_path(path, input) } } impl Parse for NestedMeta { fn parse(input: ParseStream) -> Result<Self> { let ahead = input.fork(); if ahead.peek(Lit) && !(ahead.peek(LitBool) && ahead.peek2(Token![=])) { input.parse().map(NestedMeta::Literal) } else if ahead.call(Path::parse).is_ok() { input.parse().map(NestedMeta::Meta) } else { Err(input.error("expected path or literal")) } } } fn parse_meta_after_path(path: Path, input: ParseStream) -> Result<Meta> { if input.peek(token::Paren) { parse_meta_list_after_path(pa
} else { Ok(Meta::Path(path)) } } fn parse_meta_list_after_path(path: Path, input: ParseStream) -> Result<MetaList> { let content; Ok(MetaList { path: path, paren_token: parenthesized!(content in input), nested: content.parse_terminated(NestedMeta::parse)?, }) } fn parse_meta_name_value_after_path(path: Path, input: ParseStream) -> Result<MetaNameValue> { Ok(MetaNameValue { path: path, eq_token: input.parse()?, val: input.parse()?, }) } impl ToTokens for MetaValue { fn to_tokens(&self, tokens: &mut TokenStream) { match self { MetaValue::Literal(l) => l.to_tokens(tokens), MetaValue::Path(p) => p.to_tokens(tokens), } } } impl ToTokens for MetaNameValue { fn to_tokens(&self, tokens: &mut TokenStream) { self.path.to_tokens(tokens); self.eq_token.to_tokens(tokens); self.val.to_tokens(tokens); } } impl ToTokens for NestedMeta { fn to_tokens(&self, tokens: &mut TokenStream) { match self { NestedMeta::Meta(meta) => meta.to_tokens(tokens), NestedMeta::Literal(lit) => lit.to_tokens(tokens), } } } impl ToTokens for MetaList { fn to_tokens(&self, tokens: &mut TokenStream) { self.path.to_tokens(tokens); self.paren_token.surround(tokens, |tokens| { self.nested.to_tokens(tokens); }) } } impl ToTokens for Meta { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Meta::Path(path) => path.to_tokens(tokens), Meta::List(list) => list.to_tokens(tokens), Meta::NameValue(nv) => nv.to_tokens(tokens), } } } #[cfg(test)] mod test { use super::*; #[test] pub fn derive_test() { let input: syn::ItemStruct = parse_quote! { #[evitable::from = ::std::io::Error] struct Foo; }; let attr = &input.attrs[0]; let meta = attr.meta().unwrap(); let path_str = format!("{}", meta.path().into_token_stream()); println!("{:?}", meta); assert_eq!(path_str, "evitable :: from"); } }
th, input).map(Meta::List) } else if input.peek(Token![=]) { parse_meta_name_value_after_path(path, input).map(Meta::NameValue)
function_block-random_span
[ { "content": "pub fn assert_trait_impl(ty: &Type, trait_path: &Path, tokens: &mut TokenStream) {\n\n ToTokens::to_tokens(&TraitAssertion { ty, trait_path }, tokens)\n\n}\n", "file_path": "evitable-derive-core/src/trait_assert.rs", "rank": 0, "score": 249387.9298914886 }, { "content": "pub fn derive_evitable(meta: &TokenStream, input: &mut DeriveInput) -> TokenStream {\n\n let mut cloned = input.clone();\n\n remove_evitable_attrs(input);\n\n\n\n if !meta.is_empty() {\n\n let meta_attr_quote = quote! {#[evitable(#meta)]};\n\n let parser = Attribute::parse_outer;\n\n let attr = match parser.parse2(meta_attr_quote) {\n\n Ok(val) => val[0].clone(),\n\n Err(err) => return err.to_compile_error(),\n\n };\n\n\n\n add_attribute(&mut cloned, attr);\n\n }\n\n\n\n let error_type = ErrorType::from_derive_input(&cloned);\n\n match error_type {\n\n Ok(val) => quote! { #input #val },\n\n Err(err) => err.write_errors(),\n\n }\n\n}\n", "file_path": "evitable-derive-core/src/lib.rs", "rank": 2, "score": 204512.65009277826 }, { "content": "type DeriveInputShape = String;\n", "file_path": "syn-meta-ext/src/error/kind.rs", "rank": 5, "score": 188495.89711632984 }, { "content": "enum IntoIterEnum {\n\n Single(iter::Once<Error>),\n\n Multiple(vec::IntoIter<Error>),\n\n}\n\n\n\nimpl Iterator for IntoIterEnum {\n\n type Item = Error;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n match *self {\n\n IntoIterEnum::Single(ref mut content) => content.next(),\n\n IntoIterEnum::Multiple(ref mut content) => content.next(),\n\n }\n\n }\n\n}\n\n\n\n/// An iterator that moves out of an `Error`.\n\npub struct IntoIter {\n\n inner: IntoIterEnum,\n\n}\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 6, "score": 188206.99590330492 }, { "content": "pub trait MapFields<T> {\n\n fn try_map_fields<E, U>(self, f: impl Fn(T) -> Result<U, E>) -> Result<Fields<U>, E>;\n\n fn map_fields<U>(self, f: impl Fn(T) -> U) -> Fields<U>\n\n where\n\n Self: Sized,\n\n {\n\n self\n\n .try_map_fields(|field| Result::<_, Unreachable>::Ok(f(field)))\n\n .unwrap()\n\n }\n\n}\n\n\n\nimpl MapFields<syn::Field> for syn::Fields {\n\n fn try_map_fields<E, U>(self, f: impl Fn(syn::Field) -> Result<U, E>) -> Result<Fields<U>, E> {\n\n match self {\n\n syn::Fields::Named(fields) => {\n\n let mut v = Vec::with_capacity(fields.named.len());\n\n for field in fields.named {\n\n let ident = field.ident.clone().unwrap();\n\n v.push((ident, f(field)?))\n", "file_path": "syn-meta-ext/src/ast.rs", "rank": 7, "score": 187749.2424792518 }, { "content": "#[proc_macro_attribute]\n\npub fn evitable(meta: TokenStream, input: TokenStream) -> TokenStream {\n\n derive_evitable(&parse_macro_input!(meta), &mut parse_macro_input!(input)).into()\n\n}\n", "file_path": "evitable-derive/src/lib.rs", "rank": 9, "score": 178483.1065565417 }, { "content": "type MetaFormat = String;\n\n\n\n#[derive(Debug)]\n\n#[cfg_attr(test, derive(Clone, PartialEq, Eq))]\n\npub(super) enum ErrorKind {\n\n /// An arbitrary error message.\n\n Custom(String),\n\n Parse(String),\n\n DuplicateField(FieldName),\n\n MissingField(FieldName),\n\n UnsupportedShape(DeriveInputShape),\n\n UnknownField(ErrorUnknownField),\n\n UnexpectedFormat(MetaFormat),\n\n UnexpectedType(String),\n\n UnknownValue(String),\n\n TooFewItems(usize),\n\n TooManyItems(usize),\n\n /// A set of errors.\n\n Multiple(Vec<Error>),\n\n\n", "file_path": "syn-meta-ext/src/error/kind.rs", "rank": 10, "score": 175908.02873465937 }, { "content": "type FieldName = String;\n", "file_path": "syn-meta-ext/src/error/kind.rs", "rank": 11, "score": 167611.9473773053 }, { "content": "/// Creates an instance by parsing an entire proc-macro `derive` input,\n\n/// including the, identity, generics, and visibility of the type.\n\n///\n\n/// This trait should either be derived or manually implemented by a type\n\n/// in the proc macro crate which is directly using `darling`. It is unlikely\n\n/// that these implementations will be reusable across crates.\n\npub trait FromDeriveInput: Sized {\n\n /// Create an instance from `syn::DeriveInput`, or return an error.\n\n fn from_derive_input(input: &DeriveInput) -> Result<Self> {\n\n match &input.data {\n\n Data::Union(d) => {\n\n Self::from_union(&input.attrs, &input.vis, &input.ident, &input.generics, d)\n\n }\n\n Data::Enum(d) => Self::from_enum(&input.attrs, &input.vis, &input.ident, &input.generics, d),\n\n Data::Struct(d) => {\n\n Self::from_struct(&input.attrs, &input.vis, &input.ident, &input.generics, d)\n\n }\n\n }\n\n }\n\n\n\n fn from_union(\n\n attrs: &Vec<Attribute>,\n\n vis: &Visibility,\n\n ident: &Ident,\n\n generics: &Generics,\n\n input: &DataUnion,\n", "file_path": "syn-meta-ext/src/from_derive_input.rs", "rank": 12, "score": 166614.13135233315 }, { "content": "fn add_attribute(input: &mut DeriveInput, attr: Attribute) {\n\n input.attrs.push(attr);\n\n}\n\n\n", "file_path": "evitable-derive-core/src/lib.rs", "rank": 14, "score": 154639.2932403677 }, { "content": "pub trait FromMeta: Sized {\n\n fn from_nested_meta(item: &NestedMeta) -> Result<Self> {\n\n (match item {\n\n NestedMeta::Literal(lit) => Self::from_lit(lit),\n\n NestedMeta::Meta(mi) => match mi {\n\n Meta::Path(p) => Self::from_path(p),\n\n Meta::NameValue(_) => Err(Error::unexpected_type(\"name value\").with_span(item)),\n\n Meta::List(_) => Err(Error::unexpected_type(\"list\").with_span(item)),\n\n },\n\n })\n\n .map_err(|e| e.with_span(item))\n\n }\n\n\n\n /// Create an instance from a `syn::Meta` by dispatching to the format-appropriate\n\n /// trait function. This generally should not be overridden by implementers.\n\n ///\n\n /// # Error Spans\n\n /// If this method is overridden and can introduce errors that weren't passed up from\n\n /// other `from_meta` calls, the override must call `with_span` on the error using the\n\n /// `item` to make sure that the emitted diagnostic points to the correct location in\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 15, "score": 151556.0837991106 }, { "content": "/// Creates an instance by parsing an individual field and its attributes.\n\npub trait FromField: Sized {\n\n fn from_field(field: &Field) -> Result<Self>;\n\n}\n\n\n\nimpl FromField for () {\n\n fn from_field(_: &Field) -> Result<Self> {\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl FromField for Field {\n\n fn from_field(field: &Field) -> Result<Self> {\n\n Ok(field.clone())\n\n }\n\n}\n\n\n\nimpl FromField for syn::Type {\n\n fn from_field(field: &Field) -> Result<Self> {\n\n Ok(field.ty.clone())\n\n }\n", "file_path": "syn-meta-ext/src/from_field.rs", "rank": 16, "score": 139226.85527159402 }, { "content": "/// Creates an instance from a specified `syn::Variant`.\n\npub trait FromVariant: Sized {\n\n /// Create an instance from `syn::Variant`, or return an error.\n\n fn from_variant(variant: &Variant) -> Result<Self>;\n\n}\n\n\n\nimpl FromVariant for () {\n\n fn from_variant(_: &Variant) -> Result<Self> {\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl FromVariant for Variant {\n\n fn from_variant(variant: &Variant) -> Result<Self> {\n\n Ok(variant.clone())\n\n }\n\n}\n\n\n\nimpl FromVariant for syn::Ident {\n\n fn from_variant(variant: &Variant) -> Result<Self> {\n\n Ok(variant.ident.clone())\n\n }\n\n}\n\n\n\nimpl FromVariant for Vec<syn::Attribute> {\n\n fn from_variant(variant: &Variant) -> Result<Self> {\n\n Ok(variant.attrs.clone())\n\n }\n\n}\n", "file_path": "syn-meta-ext/src/from_variant.rs", "rank": 17, "score": 139226.82992736678 }, { "content": "enum Unreachable {}\n\n\n\nimpl std::fmt::Debug for Unreachable {\n\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n\n unreachable!()\n\n }\n\n}\n\n\n\npub enum Fields<T> {\n\n Named(Vec<(Ident, T)>),\n\n Unnamed(Vec<(usize, T)>),\n\n Unit,\n\n}\n\n\n\nimpl<T> Fields<T> {\n\n pub fn iter<'a>(&'a self) -> FieldsIter<'a, T> {\n\n match self {\n\n Fields::Named(v) => FieldsIter::Named(v.iter()),\n\n Fields::Unnamed(v) => FieldsIter::Unnamed(v.iter()),\n\n Fields::Unit => FieldsIter::Unit,\n\n }\n\n }\n\n}\n\n\n", "file_path": "syn-meta-ext/src/ast.rs", "rank": 18, "score": 134308.64519629756 }, { "content": "#[cfg(feature = \"suggestions\")]\n\nfn did_you_mean<'a, T, I>(field: &str, alternates: I) -> Option<String>\n\nwhere\n\n T: AsRef<str> + 'a,\n\n I: IntoIterator<Item = &'a T>,\n\n{\n\n let mut candidate: Option<(f64, &str)> = None;\n\n for pv in alternates {\n\n let confidence = ::strsim::jaro_winkler(field, pv.as_ref());\n\n if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) {\n\n candidate = Some((confidence, pv.as_ref()));\n\n }\n\n }\n\n match candidate {\n\n None => None,\n\n Some((_, candidate)) => Some(candidate.into()),\n\n }\n\n}\n\n\n", "file_path": "syn-meta-ext/src/error/kind.rs", "rank": 19, "score": 132210.81455122953 }, { "content": "#[cfg(not(feature = \"suggestions\"))]\n\nfn did_you_mean<'a, T, I>(_field: &str, _alternates: I) -> Option<String>\n\nwhere\n\n T: AsRef<str> + 'a,\n\n I: IntoIterator<Item = &'a T>,\n\n{\n\n None\n\n}\n", "file_path": "syn-meta-ext/src/error/kind.rs", "rank": 20, "score": 132210.81455122953 }, { "content": "fn remove_evitable_attrs(input: &mut DeriveInput) {\n\n input.visit(&|attrs| {\n\n let a = std::mem::replace(attrs, Vec::new());\n\n let a = a\n\n .into_iter()\n\n .filter(|attr| attr.meta().map(|m| !m.is(\"evitable\")).unwrap_or(true))\n\n .collect();\n\n std::mem::replace(attrs, a);\n\n });\n\n}\n\n\n", "file_path": "evitable-derive-core/src/lib.rs", "rank": 21, "score": 131801.23470275788 }, { "content": "/// Trait for \"error kinds\". An `ErrorKind` enum is generated for\n\n/// every `#[evitable]` type which typically just contains\n\n/// variants for each error variant (or just a single variant in\n\n/// case of error structs).\n\npub trait EvitableErrorKind: PartialEq + Display {}\n\n\n", "file_path": "evitable/src/lib.rs", "rank": 22, "score": 126392.02165136699 }, { "content": " }\n\n}\n\n\n\nimpl Error {\n\n /// Create a new error about a literal string that doesn't match a set of known\n\n /// or permissible values. This function can be made public if the API proves useful\n\n /// beyond impls for `syn` types.\n\n pub(crate) fn unknown_lit_str_value(value: &LitStr) -> Self {\n\n Error::unknown_value(&value.value()).with_span(value)\n\n }\n\n}\n\n\n\n/// Error instance methods\n\nimpl Error {\n\n /// Check if this error is associated with a span in the token stream.\n\n pub fn has_span(&self) -> bool {\n\n self.span.is_some()\n\n }\n\n\n\n /// Tie a span to the error if none is already present. This is used in `darling::FromMeta`\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 23, "score": 109294.36814373499 }, { "content": "use proc_macro2::{Span, TokenStream};\n\nuse std::error::Error as StdError;\n\nuse std::fmt;\n\nuse std::iter::{self, Iterator};\n\nuse std::string::ToString;\n\nuse std::vec;\n\nuse syn::spanned::Spanned;\n\nuse syn::{Lit, LitStr};\n\n\n\nmod kind;\n\n\n\nuse self::kind::{ErrorKind, ErrorUnknownField};\n\n\n\n/// An alias of `Result` specific to attribute parsing.\n\npub type Result<T> = ::std::result::Result<T, Error>;\n\n\n\n/// An error encountered during attribute parsing.\n\n///\n\n/// Given that most errors darling encounters represent code bugs in dependent crates,\n\n/// the internal structure of the error is deliberately opaque.\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 24, "score": 109289.22971890547 }, { "content": " /// Creates a new error for a field which has an unexpected literal type.\n\n pub fn unexpected_type(ty: &str) -> Self {\n\n Error::new(ErrorKind::UnexpectedType(ty.into()))\n\n }\n\n\n\n /// Creates a new error for a field which has an unexpected literal type. This will automatically\n\n /// extract the literal type name from the passed-in `Lit` and set the span to encompass only the\n\n /// literal value.\n\n pub fn unexpected_lit_type(lit: &Lit) -> Self {\n\n Error::unexpected_type(match *lit {\n\n Lit::Str(_) => \"string\",\n\n Lit::ByteStr(_) => \"byte string\",\n\n Lit::Byte(_) => \"byte\",\n\n Lit::Char(_) => \"char\",\n\n Lit::Int(_) => \"int\",\n\n Lit::Float(_) => \"float\",\n\n Lit::Bool(_) => \"bool\",\n\n Lit::Verbatim(_) => \"verbatim\",\n\n })\n\n .with_span(lit)\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 25, "score": 109288.48560503374 }, { "content": " /// and other traits to attach errors to the most specific possible location in the input\n\n /// source code.\n\n ///\n\n /// All `darling`-built impls, either from the crate or from the proc macro, will call this\n\n /// when appropriate during parsing, so it should not be necessary to call this unless you have\n\n /// overridden:\n\n ///\n\n /// * `FromMeta::from_meta`\n\n /// * `FromMeta::from_nested_meta`\n\n /// * `FromMeta::from_value`\n\n pub fn with_span<T: Spanned>(mut self, node: &T) -> Self {\n\n if !self.has_span() {\n\n self.span = Some(node.span());\n\n }\n\n\n\n self\n\n }\n\n\n\n /// Recursively converts a tree of errors to a flattened list.\n\n pub fn flatten(self) -> Self {\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 26, "score": 109286.70991709961 }, { "content": "\n\nimpl Iterator for IntoIter {\n\n type Item = Error;\n\n\n\n fn next(&mut self) -> Option<Error> {\n\n self.inner.next()\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::Error;\n\n\n\n #[test]\n\n fn flatten_noop() {\n\n let err = Error::duplicate_field(\"hello\").at(\"world\");\n\n assert_eq!(err.clone().flatten(), err);\n\n }\n\n\n\n #[test]\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 27, "score": 109284.22914422497 }, { "content": "\n\n /// Gets the location slice.\n\n #[cfg(test)]\n\n pub(crate) fn location(&self) -> Vec<&str> {\n\n self.locations.iter().map(|i| i.as_str()).collect()\n\n }\n\n\n\n /// Write this error and any children as compile errors into a `TokenStream` to\n\n /// be returned by the proc-macro.\n\n ///\n\n /// Return these tokens unmodified to avoid disturbing the attached span information.\n\n pub fn write_errors(self) -> TokenStream {\n\n self\n\n .flatten()\n\n .into_iter()\n\n .map(|e| e.single_to_syn_error().to_compile_error())\n\n .collect()\n\n }\n\n\n\n fn single_to_syn_error(self) -> ::syn::Error {\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 28, "score": 109284.16084355667 }, { "content": " /// # Panics\n\n /// This function will panic if `errors.is_empty() == true`.\n\n pub fn multiple(mut errors: Vec<Error>) -> Self {\n\n if errors.len() > 1 {\n\n Error::new(ErrorKind::Multiple(errors))\n\n } else if errors.len() == 1 {\n\n errors\n\n .pop()\n\n .expect(\"Error array of length 1 has a first item\")\n\n } else {\n\n panic!(\"Can't deal with 0 errors\")\n\n }\n\n }\n\n}\n\n\n\nimpl From<syn::Error> for Error {\n\n fn from(e: syn::Error) -> Self {\n\n let mut ret = Error::new(ErrorKind::Parse(e.to_string()));\n\n ret.span = Some(e.span());\n\n ret\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 29, "score": 109283.05848631788 }, { "content": "\n\nimpl IntoIterator for Error {\n\n type Item = Error;\n\n type IntoIter = IntoIter;\n\n\n\n fn into_iter(self) -> IntoIter {\n\n if let ErrorKind::Multiple(errors) = self.kind {\n\n IntoIter {\n\n inner: IntoIterEnum::Multiple(errors.into_iter()),\n\n }\n\n } else {\n\n IntoIter {\n\n inner: IntoIterEnum::Single(iter::once(self)),\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 30, "score": 109280.93566049571 }, { "content": " match self.span {\n\n Some(span) => ::syn::Error::new(span, self.kind),\n\n None => ::syn::Error::new(Span::call_site(), self),\n\n }\n\n }\n\n}\n\n\n\nimpl StdError for Error {\n\n fn description(&self) -> &str {\n\n &self.kind.description()\n\n }\n\n\n\n fn cause(&self) -> Option<&StdError> {\n\n None\n\n }\n\n}\n\n\n\nimpl fmt::Display for Error {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{}\", self.kind)?;\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 31, "score": 109280.87471236807 }, { "content": "#[derive(Debug)]\n\n#[cfg_attr(test, derive(Clone))]\n\npub struct Error {\n\n kind: ErrorKind,\n\n locations: Vec<String>,\n\n /// The span to highlight in the emitted diagnostic.\n\n span: Option<Span>,\n\n}\n\n\n\n/// Error creation functions\n\nimpl Error {\n\n pub(self) fn new(kind: ErrorKind) -> Self {\n\n Error {\n\n kind,\n\n locations: Vec::new(),\n\n span: None,\n\n }\n\n }\n\n\n\n /// Creates a new error with a custom message.\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 32, "score": 109280.48057118335 }, { "content": " }\n\n\n\n /// Creates a new error for a value which doesn't match a set of expected literals.\n\n pub fn unknown_value(value: &str) -> Self {\n\n Error::new(ErrorKind::UnknownValue(value.into()))\n\n }\n\n\n\n /// Creates a new error for a list which did not get enough items to proceed.\n\n pub fn too_few_items(min: usize) -> Self {\n\n Error::new(ErrorKind::TooFewItems(min))\n\n }\n\n\n\n /// Creates a new error when a list got more items than it supports. The `max` argument\n\n /// is the largest number of items the receiver could accept.\n\n pub fn too_many_items(max: usize) -> Self {\n\n Error::new(ErrorKind::TooManyItems(max))\n\n }\n\n\n\n /// Bundle a set of multiple errors into a single `Error` instance.\n\n ///\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 33, "score": 109280.28622625684 }, { "content": " /// Creates a new error for a field name that appears in the input but does not correspond to\n\n /// a known attribute. The second argument is the list of known attributes; if a similar name\n\n /// is found that will be shown in the emitted error message.\n\n pub fn unknown_field_with_alts<'a, T, I>(field: &str, alternates: I) -> Self\n\n where\n\n T: AsRef<str> + 'a,\n\n I: IntoIterator<Item = &'a T>,\n\n {\n\n Error::new(ErrorUnknownField::with_alts(field, alternates).into())\n\n }\n\n\n\n /// Creates a new error for a struct or variant that does not adhere to the supported shape.\n\n pub fn unsupported_shape(shape: &str) -> Self {\n\n Error::new(ErrorKind::UnsupportedShape(shape.into()))\n\n }\n\n\n\n pub fn unsupported_format(format: &str) -> Self {\n\n Error::new(ErrorKind::UnexpectedFormat(format.into()))\n\n }\n\n\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 34, "score": 109279.68006346026 }, { "content": " Error::multiple(self.into_vec())\n\n }\n\n\n\n fn into_vec(self) -> Vec<Self> {\n\n if let ErrorKind::Multiple(errors) = self.kind {\n\n let mut flat = Vec::new();\n\n for error in errors {\n\n flat.extend(error.prepend_at(self.locations.clone()).into_vec());\n\n }\n\n\n\n flat\n\n } else {\n\n vec![self]\n\n }\n\n }\n\n\n\n /// Adds a location to the error, such as a field or variant.\n\n /// Locations must be added in reverse order of specificity.\n\n pub fn at<T: fmt::Display>(mut self, location: T) -> Self {\n\n self.locations.insert(0, location.to_string());\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 35, "score": 109278.97643753214 }, { "content": " pub fn custom<T: fmt::Display>(msg: T) -> Self {\n\n Error::new(ErrorKind::Custom(msg.to_string()))\n\n }\n\n\n\n /// Creates a new error for a field that appears twice in the input.\n\n pub fn duplicate_field(name: &str) -> Self {\n\n Error::new(ErrorKind::DuplicateField(name.into()))\n\n }\n\n\n\n /// Creates a new error for a non-optional field that does not appear in the input.\n\n pub fn missing_field(name: &str) -> Self {\n\n Error::new(ErrorKind::MissingField(name.into()))\n\n }\n\n\n\n /// Creates a new error for a field name that appears in the input but does not correspond\n\n /// to a known field.\n\n pub fn unknown_field(name: &str) -> Self {\n\n Error::new(ErrorKind::UnknownField(name.into()))\n\n }\n\n\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 36, "score": 109278.15021806167 }, { "content": " self\n\n }\n\n\n\n /// Gets the number of individual errors in this error.\n\n ///\n\n /// This function never returns `0`, as it's impossible to construct\n\n /// a multi-error from an empty `Vec`.\n\n pub fn len(&self) -> usize {\n\n self.kind.len()\n\n }\n\n\n\n /// Adds a location chain to the head of the error's existing locations.\n\n fn prepend_at(mut self, mut locations: Vec<String>) -> Self {\n\n if !locations.is_empty() {\n\n locations.extend(self.locations);\n\n self.locations = locations;\n\n }\n\n\n\n self\n\n }\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 37, "score": 109276.86296661441 }, { "content": " if !self.locations.is_empty() {\n\n write!(f, \" at {}\", self.locations.join(\"/\"))?;\n\n }\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\n// Don't want to publicly commit to Error supporting equality yet, but\n\n// not having it makes testing very difficult. Note that spans are not\n\n// considered for equality since that would break testing in most cases.\n\n#[cfg(test)]\n\nimpl PartialEq for Error {\n\n fn eq(&self, other: &Self) -> bool {\n\n self.kind == other.kind && self.locations == other.locations\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nimpl Eq for Error {}\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 38, "score": 109276.3561837629 }, { "content": " fn flatten_simple() {\n\n let err = Error::multiple(vec![\n\n Error::unknown_field(\"hello\").at(\"world\"),\n\n Error::missing_field(\"hell_no\").at(\"world\"),\n\n ])\n\n .at(\"foo\")\n\n .flatten();\n\n\n\n assert!(err.location().is_empty());\n\n\n\n let mut err_iter = err.into_iter();\n\n\n\n let first = err_iter.next();\n\n assert!(first.is_some());\n\n assert_eq!(first.unwrap().location(), vec![\"foo\", \"world\"]);\n\n\n\n let second = err_iter.next();\n\n assert!(second.is_some());\n\n\n\n assert_eq!(second.unwrap().location(), vec![\"foo\", \"world\"]);\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 39, "score": 109272.51742404282 }, { "content": "\n\n assert!(err_iter.next().is_none());\n\n }\n\n\n\n #[test]\n\n fn len_single() {\n\n let err = Error::duplicate_field(\"hello\");\n\n assert_eq!(1, err.len());\n\n }\n\n\n\n #[test]\n\n fn len_multiple() {\n\n let err = Error::multiple(vec![\n\n Error::duplicate_field(\"hello\"),\n\n Error::missing_field(\"hell_no\"),\n\n ]);\n\n assert_eq!(2, err.len());\n\n }\n\n\n\n #[test]\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 40, "score": 109272.22067807186 }, { "content": " fn len_nested() {\n\n let err = Error::multiple(vec![\n\n Error::duplicate_field(\"hello\"),\n\n Error::multiple(vec![\n\n Error::duplicate_field(\"hi\"),\n\n Error::missing_field(\"bye\"),\n\n Error::multiple(vec![Error::duplicate_field(\"whatsup\")]),\n\n ]),\n\n ]);\n\n\n\n assert_eq!(4, err.len());\n\n }\n\n}\n", "file_path": "syn-meta-ext/src/error/mod.rs", "rank": 41, "score": 109270.68412269409 }, { "content": "struct ErrorType {\n\n ident: Ident,\n\n prefix: Option<String>,\n\n vis: Visibility,\n\n generics: Generics,\n\n data: ErrorData,\n\n attrs: ErrorTypeAttrs,\n\n mod_name: Ident,\n\n mod_vis: Visibility,\n\n impls_from: Vec<from::FromImplFor>,\n\n}\n\n\n", "file_path": "evitable-derive-core/src/lib.rs", "rank": 42, "score": 106005.00863828407 }, { "content": "/// Trait implemented for all error types generated by `#[evitable]`.\n\n/// Allows for creating new errors from the [ErrorContext](ErrorContext), and\n\n/// allows getting the error kind.\n\npub trait EvitableError: StdError + Sized + Send + Sync + 'static {\n\n /// Error kind type. Generated by `#[evitable]`.\n\n type Kind: EvitableErrorKind;\n\n\n\n /// Error context type. The type marked by `#[evitable]`.\n\n type Context: ErrorContext<Error = Self, Kind = Self::Kind>;\n\n\n\n /// Create a new error instance, based on an error context and an optional source error.\n\n /// Instead of using this directly, see [from_error_context](EvitableError::from_error_context) when\n\n /// wanting to create error instances with source errors, and [from_context](EvitableError::from_context)\n\n /// when not. Derived implementations of this trait also implements `From<ErrorContext>`, so using\n\n /// [from](std::convert::From::from) or [into](std::convert::Into::into) is also an option.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `context` - Error context\n\n /// * `source` - Optional error source\n\n ///\n\n /// # Example\n\n ///\n", "file_path": "evitable/src/lib.rs", "rank": 43, "score": 105666.56863991338 }, { "content": "/// Extension trait for option and result types for easy convertion\n\n/// to evitable errors.\n\npub trait OptionExt<T, C: ErrorContext> {\n\n /// Convert to a [Result](std::result::Result) where ther error\n\n /// case is constructed from the given context factory.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `f` - Error context factory\n\n ///\n\n /// # Example\n\n ///\n\n /// ```rust\n\n ///# use evitable::*;\n\n ///# use std::io;\n\n /// #[evitable(description = \"Error\")]\n\n /// pub struct Context(u8);\n\n ///\n\n /// // Later\n\n ///# fn main() {\n\n /// let option_error: Option<u8> = None;\n\n /// let io_error: std::io::Result<u8> = Err(io::Error::from(io::ErrorKind::NotFound));\n", "file_path": "evitable/src/lib.rs", "rank": 44, "score": 105408.51194101041 }, { "content": "struct ErrorTypeAttrs {\n\n error_type_name: TypeAliasName,\n\n result_type_name: TypeAliasName,\n\n kind_type_name: TypeAliasName,\n\n}\n\n\n\nimpl ErrorTypeAttrs {\n\n fn from_attrs(attrs: &mut Attrs) -> Result<Self> {\n\n let error_type_name = attrs.get_optional(\"error_type\")?.unwrap_or_default();\n\n let result_type_name = attrs.get_optional(\"result_type\")?.unwrap_or_default();\n\n let kind_type_name = attrs.get_optional(\"kind_type\")?.unwrap_or_default();\n\n\n\n Ok(Self {\n\n error_type_name,\n\n result_type_name,\n\n kind_type_name,\n\n })\n\n }\n\n}\n\n\n", "file_path": "evitable-derive-core/src/lib.rs", "rank": 45, "score": 103089.4433668907 }, { "content": "#[test]\n\npub fn test_both() {\n\n let _ = NotFoundError::from(NotFoundContext);\n\n let _ = BadRequestError::from(BadRequestContext);\n\n}\n", "file_path": "evitable/tests/multiple.rs", "rank": 46, "score": 99009.19936339183 }, { "content": "/// Error context trait, typically used with `#[evitable]`.\n\n/// This produces Error and ErrorKind types for the given context.\n\npub trait ErrorContext: Display + Debug + Sized + Send + Sync + 'static {\n\n /// Associated error kind enum.\n\n type Kind: EvitableErrorKind;\n\n\n\n /// Associated error struct.\n\n type Error: EvitableError<Context = Self, Kind = Self::Kind>;\n\n\n\n /// Get the error kind.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```rust\n\n ///# use evitable::*;\n\n /// #[evitable]\n\n /// pub enum Context {\n\n /// #[evitable(description(\"Io error ({})\", 0))]\n\n /// Io(u8),\n\n ///\n\n /// #[evitable(description = \"Fmt error\")]\n\n /// Fmt,\n", "file_path": "evitable/src/lib.rs", "rank": 47, "score": 95056.84122362596 }, { "content": "/// Extension trait for result types (and other types carrying\n\n/// errors with them).\n\npub trait ResultExt<T, E, C: ErrorContext>: OptionExt<T, C> {\n\n /// Convert to a [Result](std::result::Result) where ther error\n\n /// case is constructed from the given context factory which also\n\n /// accepts a reference to the original error.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `f` - Error context factory\n\n ///\n\n /// # Example\n\n ///\n\n /// ```rust\n\n ///# use evitable::*;\n\n ///# use std::io;\n\n /// #[evitable(description = \"Error\")]\n\n /// pub struct Context(String);\n\n ///\n\n /// // Later\n\n ///# fn main() {\n\n /// let io_error: std::io::Result<u8> = Err(io::Error::from(io::ErrorKind::NotFound));\n", "file_path": "evitable/src/lib.rs", "rank": 48, "score": 87674.632856866 }, { "content": "struct ErrorStruct {\n\n description: ResolvedDescription,\n\n from_impls: Vec<FromImpl>,\n\n fields: Fields<ErrorField>,\n\n}\n\n\n", "file_path": "evitable-derive-core/src/lib.rs", "rank": 49, "score": 87008.85097153844 }, { "content": " trait AssertImpl {\n\n #[inline]\n\n fn assert() {}\n\n }\n\n\n\n impl<T: #trait_path> AssertImpl for AssertHelper<T> {}\n\n AssertHelper::<#ty>::assert();\n\n }})\n\n }\n\n}\n\n\n", "file_path": "evitable-derive-core/src/trait_assert.rs", "rank": 50, "score": 85102.57232874782 }, { "content": "\n\nimpl<'a, T> Iterator for FieldsIter<'a, T> {\n\n type Item = (Option<&'a Ident>, &'a T);\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n match self {\n\n FieldsIter::Named(iter) => match iter.next() {\n\n None => None,\n\n Some(tpl) => Some((Some(&tpl.0), &tpl.1)),\n\n },\n\n\n\n FieldsIter::Unnamed(iter) => match iter.next() {\n\n None => None,\n\n Some((_, val)) => Some((None, val)),\n\n },\n\n\n\n FieldsIter::Unit => None,\n\n }\n\n }\n\n}\n", "file_path": "syn-meta-ext/src/ast.rs", "rank": 51, "score": 84879.75812027688 }, { "content": " fn try_map_fields<E, U>(\n\n self,\n\n f: impl Fn(&'a syn::Field) -> Result<U, E>,\n\n ) -> Result<Fields<U>, E> {\n\n match self {\n\n syn::Fields::Named(fields) => {\n\n let mut v = Vec::with_capacity(fields.named.len());\n\n for field in &fields.named {\n\n let ident = field.ident.clone().unwrap();\n\n v.push((ident, f(field)?))\n\n }\n\n\n\n Ok(Fields::Named(v))\n\n }\n\n\n\n syn::Fields::Unnamed(fields) => {\n\n let mut v = Vec::with_capacity(fields.unnamed.len());\n\n for (index, field) in fields.unnamed.iter().enumerate() {\n\n v.push((index, f(field)?))\n\n }\n", "file_path": "syn-meta-ext/src/ast.rs", "rank": 52, "score": 84873.2519372441 }, { "content": "\n\n Ok(Fields::Unnamed(v))\n\n }\n\n\n\n syn::Fields::Unit => Ok(Fields::Unit),\n\n }\n\n }\n\n}\n\n\n\nimpl<T> MapFields<T> for Fields<T> {\n\n fn try_map_fields<E, U>(self, f: impl Fn(T) -> Result<U, E>) -> Result<Fields<U>, E> {\n\n match self {\n\n Fields::Named(fields) => {\n\n let mut v = Vec::with_capacity(fields.len());\n\n for field in fields {\n\n v.push((field.0, f(field.1)?))\n\n }\n\n\n\n Ok(Fields::Named(v))\n\n }\n", "file_path": "syn-meta-ext/src/ast.rs", "rank": 53, "score": 84867.65431113541 }, { "content": " }\n\n\n\n Ok(Fields::Named(v))\n\n }\n\n\n\n syn::Fields::Unnamed(fields) => {\n\n let mut v = Vec::with_capacity(fields.unnamed.len());\n\n for (index, field) in fields.unnamed.into_iter().enumerate() {\n\n v.push((index, f(field)?))\n\n }\n\n\n\n Ok(Fields::Unnamed(v))\n\n }\n\n\n\n syn::Fields::Unit => Ok(Fields::Unit),\n\n }\n\n }\n\n}\n\n\n\nimpl<'a> MapFields<&'a syn::Field> for &'a syn::Fields {\n", "file_path": "syn-meta-ext/src/ast.rs", "rank": 54, "score": 84866.67098198408 }, { "content": "use syn::Ident;\n\n\n", "file_path": "syn-meta-ext/src/ast.rs", "rank": 55, "score": 84865.37437331474 }, { "content": "\n\n Fields::Unnamed(fields) => {\n\n let mut v = Vec::with_capacity(fields.len());\n\n for (index, field) in fields {\n\n v.push((index, f(field)?))\n\n }\n\n\n\n Ok(Fields::Unnamed(v))\n\n }\n\n\n\n Fields::Unit => Ok(Fields::Unit),\n\n }\n\n }\n\n}\n\n\n\npub enum FieldsIter<'a, T> {\n\n Named(std::slice::Iter<'a, (Ident, T)>),\n\n Unnamed(std::slice::Iter<'a, (usize, T)>),\n\n Unit,\n\n}\n", "file_path": "syn-meta-ext/src/ast.rs", "rank": 56, "score": 84864.20212841187 }, { "content": "struct TraitAssertion<'a> {\n\n ty: &'a Type,\n\n trait_path: &'a Path,\n\n}\n\n\n\nimpl<'a> ToTokens for TraitAssertion<'a> {\n\n fn to_tokens(&self, tokens: &mut TokenStream) {\n\n let ty = &self.ty;\n\n let trait_path = &self.trait_path;\n\n tokens.extend(quote! {{\n\n #[allow(dead_code)]\n\n struct AssertHelper<T>(::std::marker::PhantomData<*const T>);\n", "file_path": "evitable-derive-core/src/trait_assert.rs", "rank": 57, "score": 83531.04107411475 }, { "content": "use super::error::{Error, Result};\n\nuse proc_macro2::TokenStream;\n\nuse syn::{\n\n Attribute, Data, DataEnum, DataStruct, DataUnion, DeriveInput, Generics, Ident, Visibility,\n\n};\n\n\n\n/// Creates an instance by parsing an entire proc-macro `derive` input,\n\n/// including the, identity, generics, and visibility of the type.\n\n///\n\n/// This trait should either be derived or manually implemented by a type\n\n/// in the proc macro crate which is directly using `darling`. It is unlikely\n\n/// that these implementations will be reusable across crates.\n", "file_path": "syn-meta-ext/src/from_derive_input.rs", "rank": 58, "score": 81553.14769772442 }, { "content": " ) -> Result<Self> {\n\n Err(Error::unsupported_shape(\"union\"))\n\n }\n\n\n\n fn from_enum(\n\n attrs: &Vec<Attribute>,\n\n vis: &Visibility,\n\n ident: &Ident,\n\n generics: &Generics,\n\n input: &DataEnum,\n\n ) -> Result<Self> {\n\n Err(Error::unsupported_shape(\"enum\"))\n\n }\n\n\n\n fn from_struct(\n\n attrs: &Vec<Attribute>,\n\n vis: &Visibility,\n\n ident: &Ident,\n\n generics: &Generics,\n\n input: &DataStruct,\n", "file_path": "syn-meta-ext/src/from_derive_input.rs", "rank": 59, "score": 81549.88068599244 }, { "content": " ) -> Result<Self> {\n\n Err(Error::unsupported_shape(\"struct\"))\n\n }\n\n\n\n fn parse(input: TokenStream) -> Result<Self> {\n\n let input = syn::parse2(input)?;\n\n Self::from_derive_input(&input)\n\n }\n\n}\n\n\n\nimpl FromDeriveInput for () {\n\n fn from_derive_input(_: &DeriveInput) -> Result<Self> {\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl FromDeriveInput for DeriveInput {\n\n fn from_derive_input(input: &DeriveInput) -> Result<Self> {\n\n Ok(input.clone())\n\n }\n\n}\n", "file_path": "syn-meta-ext/src/from_derive_input.rs", "rank": 60, "score": 81547.2122625937 }, { "content": " TooManyItems(_) => \"Too many items\",\n\n Multiple(_) => \"Multiple errors\",\n\n __NonExhaustive => unreachable!(),\n\n }\n\n }\n\n\n\n /// Deeply counts the number of errors this item represents.\n\n pub fn len(&self) -> usize {\n\n if let ErrorKind::Multiple(ref items) = *self {\n\n items.iter().map(Error::len).sum()\n\n } else {\n\n 1\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Display for ErrorKind {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n use self::ErrorKind::*;\n\n\n", "file_path": "syn-meta-ext/src/error/kind.rs", "rank": 61, "score": 80693.20623446364 }, { "content": " // TODO make this variant take `!` so it can't exist\n\n #[doc(hidden)]\n\n __NonExhaustive,\n\n}\n\n\n\nimpl ErrorKind {\n\n pub fn description(&self) -> &str {\n\n use self::ErrorKind::*;\n\n\n\n match *self {\n\n Custom(ref s) => s,\n\n Parse(ref s) => s,\n\n DuplicateField(_) => \"Duplicate field\",\n\n MissingField(_) => \"Missing field\",\n\n UnknownField(_) => \"Unexpected field\",\n\n UnsupportedShape(_) => \"Unsupported shape\",\n\n UnexpectedFormat(_) => \"Unexpected meta-item format\",\n\n UnexpectedType(_) => \"Unexpected literal type\",\n\n UnknownValue(_) => \"Unknown literal value\",\n\n TooFewItems(_) => \"Too few items\",\n", "file_path": "syn-meta-ext/src/error/kind.rs", "rank": 62, "score": 80692.67708926907 }, { "content": " T: AsRef<str> + 'a,\n\n I: IntoIterator<Item = &'a T>,\n\n {\n\n ErrorUnknownField::new(field, did_you_mean(field, alternates))\n\n }\n\n}\n\n\n\nimpl From<String> for ErrorUnknownField {\n\n fn from(name: String) -> Self {\n\n ErrorUnknownField::new(name, None)\n\n }\n\n}\n\n\n\nimpl<'a> From<&'a str> for ErrorUnknownField {\n\n fn from(name: &'a str) -> Self {\n\n ErrorUnknownField::new(name, None)\n\n }\n\n}\n\n\n\nimpl fmt::Display for ErrorUnknownField {\n", "file_path": "syn-meta-ext/src/error/kind.rs", "rank": 63, "score": 80692.6621054622 }, { "content": "/// the user back on the right track.\n\n#[derive(Debug)]\n\n// Don't want to publicly commit to ErrorKind supporting equality yet, but\n\n// not having it makes testing very difficult.\n\n#[cfg_attr(test, derive(Clone, PartialEq, Eq))]\n\npub(super) struct ErrorUnknownField {\n\n name: String,\n\n did_you_mean: Option<String>,\n\n}\n\n\n\nimpl ErrorUnknownField {\n\n pub fn new<I: Into<String>>(name: I, did_you_mean: Option<String>) -> Self {\n\n ErrorUnknownField {\n\n name: name.into(),\n\n did_you_mean,\n\n }\n\n }\n\n\n\n pub fn with_alts<'a, T, I>(field: &str, alternates: I) -> Self\n\n where\n", "file_path": "syn-meta-ext/src/error/kind.rs", "rank": 64, "score": 80689.05178460985 }, { "content": " match *self {\n\n Custom(ref s) => s.fmt(f),\n\n Parse(ref s) => write!(f, \"Error parsing: {}\", s),\n\n DuplicateField(ref field) => write!(f, \"Duplicate field `{}`\", field),\n\n MissingField(ref field) => write!(f, \"Missing field `{}`\", field),\n\n UnknownField(ref field) => field.fmt(f),\n\n UnsupportedShape(ref shape) => write!(f, \"Unsupported shape `{}`\", shape),\n\n UnexpectedFormat(ref format) => write!(f, \"Unexpected meta-item format `{}`\", format),\n\n UnexpectedType(ref ty) => write!(f, \"Unexpected literal type `{}`\", ty),\n\n UnknownValue(ref val) => write!(f, \"Unknown literal value `{}`\", val),\n\n TooFewItems(ref min) => write!(f, \"Too few items: Expected at least {}\", min),\n\n TooManyItems(ref max) => write!(f, \"Too many items: Expected no more than {}\", max),\n\n Multiple(ref items) if items.len() == 1 => items[0].fmt(f),\n\n Multiple(ref items) => {\n\n write!(f, \"Multiple errors: (\")?;\n\n let mut first = true;\n\n for item in items {\n\n if !first {\n\n write!(f, \", \")?;\n\n } else {\n", "file_path": "syn-meta-ext/src/error/kind.rs", "rank": 65, "score": 80688.63255127451 }, { "content": " first = false;\n\n }\n\n\n\n item.fmt(f)?;\n\n }\n\n\n\n write!(f, \")\")\n\n }\n\n __NonExhaustive => unreachable!(),\n\n }\n\n }\n\n}\n\n\n\nimpl From<ErrorUnknownField> for ErrorKind {\n\n fn from(err: ErrorUnknownField) -> Self {\n\n ErrorKind::UnknownField(err)\n\n }\n\n}\n\n\n\n/// An error for an unknown field, with a possible \"did-you-mean\" suggestion to get\n", "file_path": "syn-meta-ext/src/error/kind.rs", "rank": 66, "score": 80684.47598957559 }, { "content": "use std::fmt;\n\n\n\nuse super::Error;\n\n\n", "file_path": "syn-meta-ext/src/error/kind.rs", "rank": 67, "score": 80681.18996610725 }, { "content": " fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"Unknown field: `{}`\", self.name)?;\n\n\n\n if let Some(ref did_you_mean) = self.did_you_mean {\n\n write!(f, \". Did you mean `{}`?\", did_you_mean)?;\n\n }\n\n\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "syn-meta-ext/src/error/kind.rs", "rank": 68, "score": 80677.1246859909 }, { "content": "enum ErrorData {\n\n Struct(ErrorStruct),\n\n Enum(Vec<ErrorVariant>),\n\n}\n\n\n", "file_path": "evitable-derive-core/src/lib.rs", "rank": 69, "score": 78535.74176787407 }, { "content": "trait AttributeTree {\n\n fn visit(&mut self, f: &impl Fn(&mut Vec<Attribute>) -> ());\n\n}\n\n\n\nimpl AttributeTree for syn::Field {\n\n fn visit(&mut self, f: &impl Fn(&mut Vec<Attribute>) -> ()) {\n\n f(&mut self.attrs);\n\n }\n\n}\n\n\n\nimpl AttributeTree for syn::FieldsNamed {\n\n fn visit(&mut self, f: &impl Fn(&mut Vec<Attribute>) -> ()) {\n\n for field in self.named.iter_mut() {\n\n field.visit(f);\n\n }\n\n }\n\n}\n\n\n\nimpl AttributeTree for syn::FieldsUnnamed {\n\n fn visit(&mut self, f: &impl Fn(&mut Vec<Attribute>) -> ()) {\n", "file_path": "evitable-derive-core/src/lib.rs", "rank": 70, "score": 78154.1942518761 }, { "content": "struct ErrorVariant {\n\n ident: Ident,\n\n description: ResolvedDescription,\n\n from_impls: Vec<FromImpl>,\n\n fields: Fields<ErrorField>,\n\n}\n\n\n\nimpl ErrorVariant {\n\n pub(crate) fn destruct(&self) -> TokenStream {\n\n match &self.fields {\n\n Fields::Unit => TokenStream::new(),\n\n Fields::Named(f) => {\n\n let idents = f.iter().map(|(i, _)| i);\n\n quote! { { #(#idents,)* } }\n\n }\n\n Fields::Unnamed(f) => {\n\n let idents = f.iter().map(|(i, _)| i.into_ident());\n\n quote! { ( #(#idents,)* ) }\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "evitable-derive-core/src/lib.rs", "rank": 71, "score": 78150.23187747928 }, { "content": "struct ErrorField {\n\n ty: Type,\n\n include_in_kind: bool,\n\n method: CopyMethod,\n\n}\n\n\n\nimpl ErrorField {\n\n #[inline]\n\n pub fn is_copy(&self) -> bool {\n\n self.method.is_copy()\n\n }\n\n}\n\n\n", "file_path": "evitable-derive-core/src/lib.rs", "rank": 72, "score": 78150.23187747928 }, { "content": "trait IntoIdent<'a> {\n\n fn into_ident(self) -> Cow<'a, Ident>;\n\n}\n\n\n\nimpl<'a> IntoIdent<'a> for Ident {\n\n #[inline]\n\n fn into_ident(self) -> Cow<'a, Ident> {\n\n Cow::Owned(self)\n\n }\n\n}\n\n\n\nimpl<'a> IntoIdent<'a> for &'a Ident {\n\n #[inline]\n\n fn into_ident(self) -> Cow<'a, Ident> {\n\n Cow::Borrowed(self)\n\n }\n\n}\n\n\n\nimpl<'a> IntoIdent<'a> for String {\n\n #[inline]\n", "file_path": "evitable-derive-core/src/lib.rs", "rank": 73, "score": 78106.56676779348 }, { "content": "enum TypeAliasName {\n\n Default,\n\n Override(Ident),\n\n Disabled,\n\n Enabled,\n\n}\n\n\n\nimpl TypeAliasName {\n\n fn ident(&self, default: &str) -> Option<Ident> {\n\n match self {\n\n TypeAliasName::Disabled => None,\n\n TypeAliasName::Override(i) => Some(i.clone()),\n\n TypeAliasName::Default | TypeAliasName::Enabled => {\n\n Some(Ident::new(default, Span::call_site()))\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl Default for TypeAliasName {\n", "file_path": "evitable-derive-core/src/lib.rs", "rank": 74, "score": 77507.69212181725 }, { "content": "pub fn inherited(vis: &Visibility, depth: usize) -> Visibility {\n\n match vis {\n\n Visibility::Public(_) => vis.clone(),\n\n Visibility::Crate(_) => vis.clone(),\n\n Visibility::Inherited => create_super_vis(depth),\n\n Visibility::Restricted(r) => modify_vis(r, depth),\n\n }\n\n}\n", "file_path": "evitable-derive-core/src/visibility.rs", "rank": 75, "score": 73216.80269024646 }, { "content": "fn create_enum_case<'a>(\n\n enum_name: &Ident,\n\n variant_name: &Ident,\n\n case: &ErrorKind<'a>,\n\n type_asserts: &mut TokenStream,\n\n) -> TokenStream {\n\n let mut tokens = TokenStream::new();\n\n let extract = match (&case.all_fields, &case.included_fields) {\n\n (Fields::Unit, Fields::Unit) => TokenStream::new(),\n\n (Fields::Named(_), Fields::Unit) => quote! { { .. } },\n\n (Fields::Unnamed(_), Fields::Unit) => quote! { (_) },\n\n (Fields::Named(all), Fields::Named(included)) => {\n\n if all.len() == included.len() {\n\n let idents = all.iter().map(|(n, _)| n);\n\n quote! { { #(#idents,)* } }\n\n } else {\n\n assert!(all.len() > included.len());\n\n let idents = included.iter().map(|(n, _)| n);\n\n quote! { { #(#idents,)* .. } }\n\n }\n", "file_path": "evitable-derive-core/src/from_context.rs", "rank": 76, "score": 72797.65003249899 }, { "content": "fn create_struct_kind<'a>(\n\n name: &Ident,\n\n included_fields: &Fields<&ErrorField>,\n\n tokens: &mut TokenStream,\n\n type_asserts: &mut TokenStream,\n\n) {\n\n match included_fields {\n\n Fields::Unit => tokens.extend(quote! { ErrorKind::#name }),\n\n Fields::Named(fields) => {\n\n let mut assignments = Vec::with_capacity(fields.len());\n\n for (n, f) in fields.iter() {\n\n assert_trait_impl(&f.ty, &f.method.trait_path(), type_asserts);\n\n let copy = f.method.copy(&quote! { &context.#n });\n\n assignments.push(quote! { #n: #copy, });\n\n }\n\n\n\n tokens.extend(quote! { ErrorKind::#name { #(#assignments)* } })\n\n }\n\n Fields::Unnamed(fields) => {\n\n let mut assignments = Vec::with_capacity(fields.len());\n", "file_path": "evitable-derive-core/src/from_context.rs", "rank": 77, "score": 72660.74853157772 }, { "content": "from_meta_lit!(syn::LitBool, Lit::Bool);\n\nfrom_meta_lit!(proc_macro2::Literal, Lit::Verbatim);\n\n\n\nimpl FromMeta for Meta {\n\n fn from_meta(value: &Meta) -> Result<Self> {\n\n Ok(value.clone())\n\n }\n\n}\n\n\n\nimpl FromMeta for ident_case::RenameRule {\n\n fn from_string<S: Spanned>(value: &str, span: &S) -> Result<Self> {\n\n value\n\n .parse()\n\n .map_err(|_| Error::unknown_value(value).with_span(span))\n\n }\n\n}\n\n\n\nimpl<T: FromMeta> FromMeta for Option<T> {\n\n fn from_meta(item: &Meta) -> Result<Self> {\n\n FromMeta::from_meta(item).map(Some)\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 78, "score": 62655.596225213514 }, { "content": "use crate::quote::ToTokens;\n\nuse proc_macro2::TokenStream;\n\nuse std::rc::Rc;\n\nuse std::sync::atomic::AtomicBool;\n\nuse std::sync::Arc;\n\nuse syn::spanned::Spanned;\n\nuse syn::{Ident, Lit, Path};\n\n\n\nuse super::error::{Error, Result};\n\nuse super::{Meta, MetaValue, NestedMeta};\n\n\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 79, "score": 62654.94013798437 }, { "content": "#[cfg(test)]\n\nmod tests {\n\n use proc_macro2::TokenStream;\n\n use syn;\n\n\n\n use super::Meta;\n\n use super::{FromMeta, Result};\n\n use crate::AttrExt;\n\n\n\n /// parse a string as a syn::Meta instance.\n\n fn pm(tokens: TokenStream) -> ::std::result::Result<Meta, String> {\n\n let attribute: syn::Attribute = parse_quote!(#[#tokens]);\n\n attribute.meta().map_err(|_| \"Unable to parse\".into())\n\n }\n\n\n\n fn fm<T: FromMeta>(tokens: TokenStream) -> T {\n\n FromMeta::from_meta(&pm(tokens).expect(\"Tests should pass well-formed input\"))\n\n .expect(\"Tests should pass valid input\")\n\n }\n\n\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 80, "score": 62653.127606400936 }, { "content": "\n\nimpl FromMeta for AtomicBool {\n\n fn from_meta(mi: &Meta) -> Result<Self> {\n\n FromMeta::from_meta(mi)\n\n .map(AtomicBool::new)\n\n .map_err(|e| e.with_span(mi))\n\n }\n\n}\n\n\n\nimpl FromMeta for String {\n\n fn from_string<S: Spanned>(s: &str, _span: &S) -> Result<Self> {\n\n Ok(s.to_string())\n\n }\n\n\n\n fn from_path(p: &Path) -> Result<Self> {\n\n let mut ss = TokenStream::new();\n\n p.to_tokens(&mut ss);\n\n Ok(format!(\"{}\", ss))\n\n }\n\n}\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 81, "score": 62651.994424972945 }, { "content": "\n\n/// Generate an impl of `FromMeta` that will accept strings which parse to numbers or\n\n/// integer literals.\n\nmacro_rules! from_meta_num {\n\n ($ty:ident) => {\n\n impl FromMeta for $ty {\n\n fn from_string<S: Spanned>(s: &str, span: &S) -> Result<Self> {\n\n s.parse()\n\n .map_err(|_| Error::unknown_value(s).with_span(span))\n\n }\n\n\n\n fn from_lit(value: &Lit) -> Result<Self> {\n\n (match value {\n\n Lit::Str(s) => Self::from_string(&s.value(), s),\n\n Lit::Int(s) => Ok(s.base10_parse()?),\n\n v => Err(Error::unexpected_lit_type(value).with_span(&v)),\n\n })\n\n .map_err(|e| e.with_span(value))\n\n }\n\n }\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 82, "score": 62651.11690647849 }, { "content": " fn from_list(items: &[&NestedMeta]) -> Result<Self> {\n\n match items.len() {\n\n 0 => Self::from_empty(),\n\n 1 => Self::from_nested_meta(&items[0]),\n\n _ => Err(Error::unsupported_format(\"list\")),\n\n }\n\n }\n\n\n\n /// Create an instance from a literal value of either `foo = \"bar\"` or `foo(\"bar\")`.\n\n /// This dispatches to the appropriate method based on the type of literal encountered,\n\n /// and generally should not be overridden by implementers.\n\n ///\n\n /// # Error Spans\n\n /// If this method is overridden, the override must make sure to add `value`'s span\n\n /// information to the returned error by calling `with_span(value)` on the `Error` instance.\n\n fn from_value(value: &MetaValue) -> Result<Self> {\n\n (match value {\n\n MetaValue::Path(path) => Self::from_path(path),\n\n MetaValue::Literal(lit) => Self::from_lit(lit),\n\n })\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 83, "score": 62650.71839213901 }, { "content": " #[allow(unused_variables)]\n\n fn from_string<S: Spanned>(value: &str, span: &S) -> Result<Self> {\n\n Err(Error::unexpected_type(\"string\").with_span(span))\n\n }\n\n\n\n /// Create an instance from a bool literal in a value position.\n\n #[allow(unused_variables)]\n\n fn from_bool<S: Spanned>(value: bool, span: &S) -> Result<Self> {\n\n Err(Error::unexpected_type(\"bool\").with_span(span))\n\n }\n\n\n\n #[allow(unused_variables)]\n\n fn from_ident(value: &Ident) -> Result<Self> {\n\n Err(Error::unexpected_type(\"ident\"))\n\n }\n\n}\n\n\n\n// FromMeta impls for std and syn types.\n\n\n\nimpl FromMeta for () {\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 84, "score": 62650.50270429675 }, { "content": " /// source code.\n\n fn from_meta(item: &Meta) -> Result<Self> {\n\n (match item {\n\n Meta::Path(_) => Self::from_empty(),\n\n Meta::List(value) => {\n\n Self::from_list(value.nested.iter().collect::<Vec<&NestedMeta>>().as_ref())\n\n }\n\n Meta::NameValue(value) => Self::from_value(&value.val),\n\n })\n\n .map_err(|e| e.with_span(item))\n\n }\n\n\n\n /// Create an instance from the presence of the word in the attribute with no\n\n /// additional options specified.\n\n fn from_empty() -> Result<Self> {\n\n Err(Error::unsupported_format(\"empty\"))\n\n }\n\n\n\n /// Create an instance from a list of nested meta items.\n\n #[allow(unused_variables)]\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 85, "score": 62650.3158080975 }, { "content": " syn::parse_str(value).map_err(|_| Error::unknown_value(value).with_span(span))\n\n }\n\n\n\n fn from_lit(value: &Lit) -> Result<Self> {\n\n if let Lit::Str(ref path_str) = *value {\n\n path_str\n\n .parse()\n\n .map_err(|_| Error::unknown_lit_str_value(path_str).with_span(value))\n\n } else {\n\n Err(Error::unexpected_lit_type(value).with_span(value))\n\n }\n\n }\n\n}\n\n\n\nimpl FromMeta for syn::Lit {\n\n fn from_lit(value: &Lit) -> Result<Self> {\n\n Ok(value.clone())\n\n }\n\n}\n\n\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 86, "score": 62649.60459961121 }, { "content": " /// Create an instance from a int literal in a value position.\n\n #[allow(unused_variables)]\n\n fn from_int<S: Spanned>(value: u64, span: &S) -> Result<Self> {\n\n Err(Error::unexpected_type(\"int\").with_span(span))\n\n }\n\n\n\n /// Create an instance from a char literal in a value position.\n\n #[allow(unused_variables)]\n\n fn from_path(value: &Path) -> Result<Self> {\n\n if value.leading_colon.is_none()\n\n && value.segments.len() == 1\n\n && value.segments[0].arguments == syn::PathArguments::None\n\n {\n\n Self::from_ident(&value.segments[0].ident)\n\n } else {\n\n Err(Error::unexpected_type(\"path\"))\n\n }\n\n }\n\n\n\n /// Create an instance from a string literal in a value position.\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 87, "score": 62649.48574609685 }, { "content": "/// when available, but also supports parsing strings with the call site as the\n\n/// emitted span.\n\nimpl FromMeta for syn::Ident {\n\n fn from_ident(value: &Ident) -> Result<Self> {\n\n Ok(value.clone())\n\n }\n\n\n\n fn from_string<S: Spanned>(value: &str, span: &S) -> Result<Self> {\n\n Ok(syn::Ident::new(value, span.span()))\n\n }\n\n}\n\n\n\n/// Parsing support for paths. This attempts to preserve span information when available,\n\n/// but also supports parsing strings with the call site as the emitted span.\n\nimpl FromMeta for syn::Path {\n\n fn from_path(path: &Path) -> Result<Self> {\n\n Ok(path.clone())\n\n }\n\n\n\n fn from_string<S: Spanned>(value: &str, span: &S) -> Result<Self> {\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 88, "score": 62647.74236091694 }, { "content": "macro_rules! from_meta_lit {\n\n ($impl_ty:path, $lit_variant:path) => {\n\n impl FromMeta for $impl_ty {\n\n fn from_lit(value: &Lit) -> Result<Self> {\n\n if let $lit_variant(ref value) = *value {\n\n Ok(value.clone())\n\n } else {\n\n Err(Error::unexpected_lit_type(value).with_span(value))\n\n }\n\n }\n\n }\n\n };\n\n}\n\n\n\nfrom_meta_lit!(syn::LitInt, Lit::Int);\n\nfrom_meta_lit!(syn::LitFloat, Lit::Float);\n\nfrom_meta_lit!(syn::LitStr, Lit::Str);\n\nfrom_meta_lit!(syn::LitByte, Lit::Byte);\n\nfrom_meta_lit!(syn::LitByteStr, Lit::ByteStr);\n\nfrom_meta_lit!(syn::LitChar, Lit::Char);\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 89, "score": 62647.54948690525 }, { "content": " .map_err(|e| e.with_span(value))\n\n }\n\n\n\n fn from_lit(lit: &Lit) -> Result<Self> {\n\n (match lit {\n\n Lit::Bool(b) => Self::from_bool(b.value, b),\n\n Lit::Str(s) => Self::from_string(&s.value(), s),\n\n Lit::Char(c) => Self::from_char(c.value(), c),\n\n Lit::Int(i) => Self::from_int(i.base10_parse()?, i),\n\n _ => Err(Error::unexpected_lit_type(lit)),\n\n })\n\n .map_err(|e| e.with_span(lit))\n\n }\n\n\n\n /// Create an instance from a char literal in a value position.\n\n #[allow(unused_variables)]\n\n fn from_char<S: Spanned>(value: char, span: &S) -> Result<Self> {\n\n Err(Error::unexpected_type(\"char\").with_span(span))\n\n }\n\n\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 90, "score": 62647.19056376134 }, { "content": " }\n\n\n\n fn from_list(items: &[&NestedMeta]) -> Result<Self> {\n\n let mut ret = Vec::with_capacity(items.len());\n\n for item in items {\n\n ret.push(T::from_nested_meta(item)?);\n\n }\n\n\n\n Ok(ret)\n\n }\n\n\n\n fn from_value(val: &MetaValue) -> Result<Self> {\n\n let mut ret = Vec::with_capacity(1);\n\n ret.push(T::from_value(val)?);\n\n Ok(ret)\n\n }\n\n}\n\n\n\n/// Tests for `FromMeta` implementations. Wherever the word `ignore` appears in test input,\n\n/// it should not be considered by the parsing.\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 91, "score": 62645.45230854758 }, { "content": " s.parse()\n\n .map_err(|_| Error::unknown_value(s).with_span(span))\n\n }\n\n\n\n fn from_lit(value: &Lit) -> Result<Self> {\n\n (match value {\n\n Lit::Str(s) => Self::from_string(&s.value(), s),\n\n Lit::Float(s) => Ok(s.base10_parse()?),\n\n v => Err(Error::unexpected_lit_type(value).with_span(&v)),\n\n })\n\n .map_err(|e| e.with_span(value))\n\n }\n\n }\n\n };\n\n}\n\n\n\nfrom_meta_float!(f32);\n\nfrom_meta_float!(f64);\n\n\n\n/// Parsing support for identifiers. This attempts to preserve span information\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 92, "score": 62645.15903080945 }, { "content": " }\n\n}\n\n\n\nimpl<T: FromMeta> FromMeta for Box<T> {\n\n fn from_meta(item: &Meta) -> Result<Self> {\n\n FromMeta::from_meta(item).map(Box::new)\n\n }\n\n}\n\n\n\nimpl<T: FromMeta> FromMeta for Result<T> {\n\n fn from_meta(item: &Meta) -> Result<Self> {\n\n Ok(FromMeta::from_meta(item))\n\n }\n\n}\n\n\n\n/// Parses the meta-item, and in case of error preserves a copy of the input for\n\n/// later analysis.\n\nimpl<T: FromMeta> FromMeta for ::std::result::Result<T, Meta> {\n\n fn from_meta(item: &Meta) -> Result<Self> {\n\n T::from_meta(item)\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 93, "score": 62644.507080653464 }, { "content": " .map(Ok)\n\n .or_else(|_| Ok(Err(item.clone())))\n\n }\n\n}\n\n\n\nimpl<T: FromMeta> FromMeta for Rc<T> {\n\n fn from_meta(item: &Meta) -> Result<Self> {\n\n FromMeta::from_meta(item).map(Rc::new)\n\n }\n\n}\n\n\n\nimpl<T: FromMeta> FromMeta for Arc<T> {\n\n fn from_meta(item: &Meta) -> Result<Self> {\n\n FromMeta::from_meta(item).map(Arc::new)\n\n }\n\n}\n\n\n\nimpl<T: FromMeta> FromMeta for Vec<T> {\n\n fn from_empty() -> Result<Self> {\n\n Ok(Vec::new())\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 94, "score": 62644.4901734512 }, { "content": " fn from_empty() -> Result<Self> {\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl FromMeta for bool {\n\n fn from_empty() -> Result<Self> {\n\n Ok(true)\n\n }\n\n\n\n fn from_bool<S: Spanned>(value: bool, _: &S) -> Result<Self> {\n\n Ok(value)\n\n }\n\n\n\n fn from_string<S: Spanned>(value: &str, span: &S) -> Result<Self> {\n\n value\n\n .parse()\n\n .map_err(|_| Error::unknown_value(value).with_span(span))\n\n }\n\n}\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 95, "score": 62642.10934489033 }, { "content": " };\n\n}\n\n\n\nfrom_meta_num!(u8);\n\nfrom_meta_num!(u16);\n\nfrom_meta_num!(u32);\n\nfrom_meta_num!(u64);\n\nfrom_meta_num!(usize);\n\nfrom_meta_num!(i8);\n\nfrom_meta_num!(i16);\n\nfrom_meta_num!(i32);\n\nfrom_meta_num!(i64);\n\nfrom_meta_num!(isize);\n\n\n\n/// Generate an impl of `FromMeta` that will accept strings which parse to floats or\n\n/// float literals.\n\nmacro_rules! from_meta_float {\n\n ($ty:ident) => {\n\n impl FromMeta for $ty {\n\n fn from_string<S: Spanned>(s: &str, span: &S) -> Result<Self> {\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 96, "score": 62639.81564175402 }, { "content": " #[test]\n\n fn unit_succeeds() {\n\n assert_eq!(fm::<()>(quote!(ignore)), ());\n\n }\n\n\n\n #[test]\n\n fn bool_succeeds() {\n\n // word format\n\n assert_eq!(fm::<bool>(quote!(ignore)), true);\n\n\n\n // bool literal\n\n assert_eq!(fm::<bool>(quote!(ignore = true)), true);\n\n assert_eq!(fm::<bool>(quote!(ignore = false)), false);\n\n\n\n // string literals\n\n assert_eq!(fm::<bool>(quote!(ignore = \"true\")), true);\n\n assert_eq!(fm::<bool>(quote!(ignore = \"false\")), false);\n\n }\n\n\n\n #[test]\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 97, "score": 62637.643611272004 }, { "content": " fn string_succeeds() {\n\n // cooked form\n\n assert_eq!(&fm::<String>(quote!(ignore = \"world\")), \"world\");\n\n\n\n // raw form\n\n assert_eq!(&fm::<String>(quote!(ignore = r#\"world\"#)), \"world\");\n\n }\n\n\n\n #[test]\n\n fn number_succeeds() {\n\n assert_eq!(fm::<u8>(quote!(ignore = \"2\")), 2u8);\n\n assert_eq!(fm::<i16>(quote!(ignore = \"-25\")), -25i16);\n\n assert_eq!(fm::<f64>(quote!(ignore = \"1.4e10\")), 1.4e10);\n\n }\n\n\n\n #[test]\n\n fn int_without_quotes() {\n\n assert_eq!(fm::<u8>(quote!(ignore = 2)), 2u8);\n\n assert_eq!(fm::<u16>(quote!(ignore = 255)), 255u16);\n\n assert_eq!(fm::<u32>(quote!(ignore = 5000)), 5000u32);\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 98, "score": 62632.27914791538 }, { "content": "\n\n // Check that we aren't tripped up by incorrect suffixes\n\n assert_eq!(fm::<u32>(quote!(ignore = 5000i32)), 5000u32);\n\n }\n\n\n\n #[test]\n\n fn float_without_quotes() {\n\n assert_eq!(fm::<f32>(quote!(ignore = 2.)), 2.0f32);\n\n assert_eq!(fm::<f32>(quote!(ignore = 2.0)), 2.0f32);\n\n assert_eq!(fm::<f64>(quote!(ignore = 1.4e10)), 1.4e10f64);\n\n }\n\n\n\n #[test]\n\n fn meta_succeeds() {\n\n assert_eq!(\n\n fm::<Meta>(quote!(hello(world, today))),\n\n pm(quote!(hello(world, today))).unwrap()\n\n );\n\n }\n\n\n\n /// Tests that fallible parsing will always produce an outer `Ok` (from `fm`),\n\n /// and will accurately preserve the inner contents.\n\n #[test]\n\n fn result_succeeds() {\n\n fm::<Result<()>>(quote!(ignore)).unwrap();\n\n fm::<Result<()>>(quote!(ignore(world))).unwrap_err();\n\n }\n\n}\n", "file_path": "syn-meta-ext/src/from_meta.rs", "rank": 99, "score": 62631.42456905248 } ]
Rust
src/api/routes/namespace_routes_api.rs
proximax-storage/rust-xpx-chain-sdk
55613067328d511dbd9a129be30b9e048ef79175
/* * Copyright 2018 ProximaX Limited. All rights reserved. * Use of this source code is governed by the Apache 2.0 * license that can be found in the LICENSE file. */ use { ::std::{future::Future, pin::Pin, sync::Arc}, reqwest::Method, }; use crate::{ account::{AccountsId, Address}, api::{ internally::valid_vec_len, request as __internal_request, sirius_client::ApiClient, NamespaceInfoDto, NamespaceNameDto, }, errors_const::{ERR_EMPTY_ADDRESSES_IDS, ERR_EMPTY_NAMESPACE_IDS}, models::Result, namespace::{NamespaceId, NamespaceIds, NamespaceInfo, NamespaceName}, network::NetworkType, AssetId, }; use super::{ NAMESPACES_FROM_ACCOUNTS_ROUTE, NAMESPACES_FROM_ACCOUNT_ROUTES, NAMESPACE_NAMES_ROUTE, NAMESPACE_ROUTE, }; #[derive(Clone)] pub struct NamespaceRoutes(Arc<ApiClient>, NetworkType); impl NamespaceRoutes { pub(crate) fn new(client: Arc<ApiClient>, network_time: NetworkType) -> Self { NamespaceRoutes(client, network_time) } fn __client(&self) -> Arc<ApiClient> { Arc::clone(&self.0) } fn __network_type(&self) -> NetworkType { self.1 } fn __build_namespace_hierarchy<'b>( self, ns_info: &'b mut NamespaceInfo, ) -> Pin<Box<dyn Future<Output = ()> + 'b>> { Box::pin(async move { let info_parent = match &ns_info.parent { Some(info) => info, _ => return, }; if info_parent.namespace_id.to_u64() == 0 { return; } let rest_info = self .clone() .get_namespace_info(info_parent.namespace_id) .await; let mut parent_ns_info = match rest_info { Ok(parent) => Box::new(parent), _ => return, }; ns_info.parent = Some(parent_ns_info.to_owned()); if parent_ns_info.to_owned().parent.is_none() { return; } self.__build_namespace_hierarchy(&mut parent_ns_info).await }) } fn __build_namespaces_hierarchy<'b>( self, ns_infos: &'b mut Vec<NamespaceInfo>, ) -> Pin<Box<dyn Future<Output = ()> + 'b>> { Box::pin(async move { for ns_info in ns_infos.iter_mut() { self.clone().__build_namespace_hierarchy(ns_info).await } }) } pub async fn get_namespace_info(self, namespace_id: NamespaceId) -> Result<NamespaceInfo> { let mut req = __internal_request::Request::new(Method::GET, NAMESPACE_ROUTE.to_string()); req = req.with_path_param("namespaceId".to_string(), namespace_id.to_string()); let dto_raw: Result<NamespaceInfoDto> = req.clone().execute(self.__client()).await; let mut dto_to_struct = dto_raw?.compact(self.__network_type())?; self.__build_namespace_hierarchy(&mut dto_to_struct).await; Ok(dto_to_struct) } pub async fn get_namespaces_names( self, namespace_ids: Vec<NamespaceId>, ) -> Result<Vec<NamespaceName>> { valid_vec_len(&namespace_ids, ERR_EMPTY_NAMESPACE_IDS)?; let namespace_ids_ = NamespaceIds::from(namespace_ids); let mut req = __internal_request::Request::new(Method::POST, NAMESPACE_NAMES_ROUTE.to_string()); req = req.with_body_param(namespace_ids_); let dto: Vec<NamespaceNameDto> = req.execute(self.__client()).await?; let mut namespace_name: Vec<NamespaceName> = vec![]; for namespace_name_dto in dto.into_iter() { namespace_name.push(namespace_name_dto.compact()?); } Ok(namespace_name) } pub async fn get_namespaces_from_account( self, address: Address, ns_id: Option<NamespaceId>, page_size: Option<i32>, ) -> Result<Vec<NamespaceInfo>> { let mut req = __internal_request::Request::new( Method::GET, NAMESPACES_FROM_ACCOUNT_ROUTES.to_string(), ); if let Some(ref s) = page_size { req = req.with_query_param("pageSize".to_string(), s.to_string()); } if let Some(ref s) = ns_id { req = req.with_query_param("id".to_string(), s.to_hex()); } req = req.with_path_param("accountId".to_string(), address.address_string()); let dto: Vec<NamespaceInfoDto> = req.execute(self.__client()).await?; let mut namespace_info: Vec<NamespaceInfo> = vec![]; for namespace_dto in dto.into_iter() { namespace_info.push(namespace_dto.compact(self.__network_type())?); } self.__build_namespaces_hierarchy(&mut namespace_info).await; Ok(namespace_info) } pub async fn get_namespaces_from_accounts( self, accounts_id: Vec<&str>, ns_id: Option<NamespaceId>, page_size: Option<i32>, ) -> Result<Vec<NamespaceInfo>> { valid_vec_len(&accounts_id, ERR_EMPTY_ADDRESSES_IDS)?; let accounts = AccountsId::from(accounts_id); let mut req = __internal_request::Request::new( Method::POST, NAMESPACES_FROM_ACCOUNTS_ROUTE.to_string(), ); if let Some(ref s) = page_size { req = req.with_query_param("pageSize".to_string(), s.to_string()); } if let Some(ref s) = ns_id { req = req.with_query_param("id".to_string(), s.to_hex()); } req = req.with_body_param(&accounts); let dto: Vec<NamespaceInfoDto> = req.execute(self.__client()).await?; let mut namespace_info: Vec<NamespaceInfo> = vec![]; for namespace_dto in dto.into_iter() { namespace_info.push(namespace_dto.compact(self.__network_type())?); } self.__build_namespaces_hierarchy(&mut namespace_info).await; Ok(namespace_info) } }
/* * Copyright 2018 ProximaX Limited. All rights reserved. * Use of this source code is governed by the Apache 2.0 * license that can be found in the LICENSE file. */ use { ::std::{future::Future, pin::Pin, sync::Arc}, reqwest::Method, }; use crate::{ account::{AccountsId, Address}, api::{ internally::valid_vec_len, request as __internal_request, sirius_client::ApiClient, NamespaceInfoDto, NamespaceNameDto, }, errors_const::{ERR_EMPTY_ADDRESSES_IDS, ERR_EMPTY_NAMESPACE_IDS}, models::Result, namespace::{NamespaceId, NamespaceIds, NamespaceInfo, NamespaceName}, network::NetworkType, AssetId, }; use super::{ NAMESPACES_FROM_ACCOUNTS_ROUTE, NAMESPACES_FROM_ACCOUNT_ROUTES, NAMESPACE_NAMES_ROUTE, NAMESPACE_ROUTE, }; #[derive(Clone)] pub struct NamespaceRoutes(Arc<ApiClient>, NetworkType); impl NamespaceRoutes { pub(crate) fn new(client: Arc<ApiClient>, network_time: NetworkType) -> Self { NamespaceRoutes(client, network_time) } fn __client(&self) -> Arc<ApiClient> { Arc::clone(&self.0) } fn __network_type(&self) -> NetworkType { self.1 } fn __build_namespace_hierarchy<'b>( self, ns_info: &'b mut NamespaceInfo, ) -> Pin<Box<dyn Future<Output = ()> + 'b>> { Box::pin(async move { let info_parent = match &ns_info.parent { Some(info) => info, _ => return, }; if info_parent.namespace_id.to_u64() == 0 { return; } let rest_info = self .clone() .get_namespace_info(info_parent.namespace_id) .await; let mut parent_ns_info = match rest_info { Ok(parent) => Box::new(parent), _ => return, }; ns_info.parent = Some(parent_ns_info.to_owned()); if parent_ns_info.to_owned().parent.is_none() { return; } self.__build_namespace_hierarchy(&mut parent_ns_info).await }) } fn __build_namespaces_hierarchy<'b>( self, ns_infos: &'b mut Vec<NamespaceInfo>, ) -> Pin<Box<dyn Future<Output = ()> + 'b>> { Box::pin(async move { for ns_info in ns_infos.iter_mut() { self.clone().__build_namespace_hierarchy(ns_info).await } }) } pub async fn get_namespace_info(self, namespace_id: NamespaceId) -> Result<NamespaceInfo> { let mut req = __internal_request::Request::new(Method::GET, NAMESPACE_ROUTE.to_string()); req = req.with_path_param("namespaceId".to_string(), namespace_id.to_string()); let dto_raw: Result<NamespaceInfoDto> = req.clone().execute(self.__client()).await; let mut dto_to_struct = dto_raw?.compact(self.__network_type())?; self.__build_namespace_hierarchy(&mut dto_to_struct).await; Ok(dto_to_struct) } pub async fn get_namespaces_names( self, namespace_ids: Vec<NamespaceId>, ) -> Result<Vec<NamespaceName>> { valid_vec_len(&namespace_ids, ERR_EMPTY_NAMESPACE_IDS)?; let namespace_ids_ = NamespaceIds::from(namespace_ids); let mut req = __internal_request::Request::new(Method::POST, NAMESPACE_NAMES_ROUTE.to_string()); req = req.with_body_param(namespace_ids_); let dto: Vec<NamespaceNameDto> = req.execute(self.__client()).await?; let mut namespace_name: Vec<NamespaceName> = vec![]; for namespace_name_dto in dto.into_iter() { namespace_name.push(namespace_name_dto.compact()?); } Ok(namespace_name) } pub async fn get_namespaces_from_account( self, address: Address, ns_id: Option<NamespaceId>, page_size: Option<i32>, ) -> Result<Vec<NamespaceInfo>> { let mut req = __internal_request::Request::new( Method::GET, NAMESPACES_FROM_ACCOUNT_ROUTES.to_string(), ); if let Some(ref s) = page_size { req = req.with_query_param("pageSize".to_string(), s.to_string()); } if let Some(ref s) = ns_id { req = req.with_query_param("id".to_string(), s.to_hex()); } req = req.with_path_param("accountId".to_string(), address.address_string()); let dto: Vec<NamespaceInfoDto> = req.execute(self.__client()).await?;
pub async fn get_namespaces_from_accounts( self, accounts_id: Vec<&str>, ns_id: Option<NamespaceId>, page_size: Option<i32>, ) -> Result<Vec<NamespaceInfo>> { valid_vec_len(&accounts_id, ERR_EMPTY_ADDRESSES_IDS)?; let accounts = AccountsId::from(accounts_id); let mut req = __internal_request::Request::new( Method::POST, NAMESPACES_FROM_ACCOUNTS_ROUTE.to_string(), ); if let Some(ref s) = page_size { req = req.with_query_param("pageSize".to_string(), s.to_string()); } if let Some(ref s) = ns_id { req = req.with_query_param("id".to_string(), s.to_hex()); } req = req.with_body_param(&accounts); let dto: Vec<NamespaceInfoDto> = req.execute(self.__client()).await?; let mut namespace_info: Vec<NamespaceInfo> = vec![]; for namespace_dto in dto.into_iter() { namespace_info.push(namespace_dto.compact(self.__network_type())?); } self.__build_namespaces_hierarchy(&mut namespace_info).await; Ok(namespace_info) } }
let mut namespace_info: Vec<NamespaceInfo> = vec![]; for namespace_dto in dto.into_iter() { namespace_info.push(namespace_dto.compact(self.__network_type())?); } self.__build_namespaces_hierarchy(&mut namespace_info).await; Ok(namespace_info) }
function_block-function_prefix_line
[ { "content": "fn parse_meta_ws(value_dto: &mut Value) -> Result<()> {\n\n if let Some(v) = value_dto[\"transaction\"][\"transactions\"].as_array_mut() {\n\n let mut meta_value: Vec<Value> = vec![];\n\n\n\n for item in v.iter_mut() {\n\n if item[\"meta\"].is_null() {\n\n let meta = r#\"\"meta\": {}, \"transaction\":\"#;\n\n let parse_meta_srt = format!(\"{}\", item).replace(r#\"\"transaction\":\"#, meta);\n\n\n\n let parse_meta: Value = serde_json::from_str(&parse_meta_srt)?;\n\n meta_value.push(parse_meta)\n\n } else {\n\n let parse_meta: Value = serde_json::from_str(&*format!(\"{}\", item))?;\n\n meta_value.push(parse_meta)\n\n }\n\n }\n\n v.clear();\n\n v.append(&mut meta_value)\n\n };\n\n Ok(())\n\n}\n\n\n", "file_path": "src/api/internally.rs", "rank": 0, "score": 199868.54982480197 }, { "content": "fn path_parse_address(mut path: String, address: Address) -> String {\n\n path.push_str(\"/\");\n\n path.push_str(&address.address_string());\n\n path\n\n}\n\n\n", "file_path": "src/websocket/client.rs", "rank": 1, "score": 194066.74521329853 }, { "content": "pub fn hex_decode(data: &str) -> Vec<u8> {\n\n hex::decode(data)\n\n .map_err(|err| panic!(\"Failed to decode hex data {} : {}\", data, err))\n\n .unwrap()\n\n}\n\n\n", "file_path": "src/helpers/utils_hex.rs", "rank": 2, "score": 172835.29757663194 }, { "content": "#[derive(Clone, Serialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct PropertiesDto {\n\n property_type: u8,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n mosaic_ids: Option<Vec<Uint64Dto>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n addresses: Option<Vec<String>>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n entity_types: Option<Vec<u16>>,\n\n}\n\n\n\nimpl<'de> Deserialize<'de> for PropertiesDto {\n\n fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>\n\n where\n\n D: Deserializer<'de>,\n\n {\n\n #[derive(Deserialize, Debug)]\n\n struct PropertyValue {\n\n #[serde(rename = \"propertyType\")]\n\n r#type: u8,\n\n values: Value,\n", "file_path": "src/api/dtos/account_dto.rs", "rank": 3, "score": 166279.64268948545 }, { "content": "#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct AccountDto {\n\n address: String,\n\n address_height: Uint64Dto,\n\n /// The public key of an account can be used to verify signatures of the account. Only accounts that have already published a transaction have a public key assigned to the account. Otherwise, the field is null.\n\n public_key: String,\n\n public_key_height: Uint64Dto,\n\n /// The list of mosaics the account owns. The amount is represented in absolute amount. Thus a balance of 123456789 for a mosaic with divisibility 6 (absolute) means the account owns 123.456789 instead.\n\n mosaics: Vec<MosaicDto>,\n\n account_type: u8,\n\n /// The public key of a linked account. The linked account can use|provide balance for delegated harvesting.\n\n linked_account_key: String,\n\n}\n\n\n\n#[derive(Serialize, Deserialize)]\n\npub(crate) struct AccountInfoDto {\n\n account: AccountDto,\n\n}\n\n\n\nimpl AccountInfoDto {\n\n pub(crate) fn compact(&self) -> crate::Result<AccountInfo> {\n", "file_path": "src/api/dtos/account_dto.rs", "rank": 4, "score": 166279.60964477784 }, { "content": "#[derive(Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct BlockDtoAllOf {\n\n height: Uint64Dto,\n\n timestamp: Uint64Dto,\n\n difficulty: Uint64Dto,\n\n /// The fee multiplier applied to transactions contained in block.\n\n fee_multiplier: i32,\n\n /// The hash of the previous block.\n\n previous_block_hash: String,\n\n /// The transactions included in a block are hashed forming a merkle tree. The root of the tree summarizes them.\n\n block_transactions_hash: String,\n\n /// The collection of receipts are hashed into a merkle tree and linked to a block. The block header stores the root hash.\n\n block_receipts_hash: String,\n\n /// For each block, the state of the blockchain is stored in RocksDB, forming a patricia tree. The root of the tree summarizes the state of the blockchain for the given block.\n\n state_hash: String,\n\n /// The public key of the optional beneficiary designated by harvester.\n\n beneficiary: String,\n\n /// The part of the transaction fee harvester is willing to get. From 0 up to FeeInterestDenominator. The customer gets (FeeInterest / FeeInterestDenominator)'th part of the maximum transaction fee.\n\n fee_interest: i32,\n\n /// Denominator of the transaction fee.\n\n fee_interest_denominator: i32,\n\n}\n", "file_path": "src/api/dtos/block_dto.rs", "rank": 5, "score": 166274.7413419521 }, { "content": "#[derive(Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct BlockMetaDto {\n\n hash: String,\n\n generation_hash: String,\n\n total_fee: Uint64Dto,\n\n num_transactions: u64,\n\n}\n\n\n\n#[derive(Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct BlockDto {\n\n signature: String,\n\n signer: String,\n\n version: u32,\n\n #[serde(rename = \"type\")]\n\n _type: u32,\n\n pub height: Uint64Dto,\n\n timestamp: Uint64Dto,\n\n difficulty: Uint64Dto,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n fee_multiplier: Option<i32>,\n", "file_path": "src/api/dtos/block_dto.rs", "rank": 6, "score": 164172.02513978007 }, { "content": "#[derive(Serialize, Deserialize)]\n\nstruct MosaicMetaDto {\n\n #[serde(rename = \"id\")]\n\n id: String,\n\n}\n\n\n\n#[derive(Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct MosaicDefinitionTransactionInfoDto {\n\n meta: TransactionMetaDto,\n\n transaction: MosaicDefinitionTransactionDto,\n\n}\n\n\n\n/// MosaicDefinitionTransactionDto : Transaction that creates a new mosaic.\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct MosaicDefinitionTransactionDto {\n\n #[serde(flatten)]\n\n r#abstract: AbstractTransactionDto,\n\n /// Random nonce used to generate the mosaic id.\n\n mosaic_nonce: u32,\n", "file_path": "src/api/dtos/mosaic_dto.rs", "rank": 7, "score": 164172.02513978007 }, { "content": "#[derive(Serialize, Deserialize)]\n\nstruct CommunicationTimestampsDto {\n\n #[serde(rename = \"sendTimestamp\", skip_serializing_if = \"Option::is_none\")]\n\n send_timestamp: Option<Uint64Dto>,\n\n #[serde(rename = \"receiveTimestamp\", skip_serializing_if = \"Option::is_none\")]\n\n receive_timestamp: Option<Uint64Dto>,\n\n}\n\n\n\nimpl NodeTimeDto {\n\n pub(crate) fn compact(&self) -> NodeTime {\n\n let mut send = Uint64::default();\n\n if let Some(value) = &self.communication_timestamps.send_timestamp {\n\n send = value.compact();\n\n };\n\n\n\n let mut receive = Uint64::default();\n\n if let Some(value) = &self.communication_timestamps.receive_timestamp {\n\n receive = value.compact();\n\n };\n\n\n\n NodeTime {\n\n send_timestamp: Some(send),\n\n receive_timestamp: Some(receive),\n\n }\n\n }\n\n}\n", "file_path": "src/api/dtos/node_dto.rs", "rank": 8, "score": 164172.02513978007 }, { "content": "pub fn schema_common_definition() -> Vec<Box<dyn SchemaAttribute>> {\n\n vec![\n\n Box::new(ScalarAttribute::new(\"size\", SIZEOF_INT)),\n\n Box::new(ArrayAttribute::new(\"signature\", SIZEOF_BYTE)),\n\n Box::new(ArrayAttribute::new(\"signer\", SIZEOF_BYTE)),\n\n Box::new(ScalarAttribute::new(\"version\", SIZEOF_INT)),\n\n Box::new(ScalarAttribute::new(\"type\", SIZEOF_SHORT)),\n\n Box::new(ArrayAttribute::new(\"max_fee\", SIZEOF_INT)),\n\n Box::new(ArrayAttribute::new(\"deadline\", SIZEOF_INT)),\n\n ]\n\n}\n", "file_path": "src/models/transaction/schema/schema_common_definition.rs", "rank": 9, "score": 163229.2427109059 }, { "content": "#[derive(Clone, Serialize, Deserialize)]\n\nstruct AccountPropertiesModificationDto {\n\n r#type: u8,\n\n /// The address, transaction type or mosaic id to filter.\n\n value: Value,\n\n}\n\n\n\n#[derive(Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct AccountPropertiesInfoDto {\n\n account_properties: AccountPropertiesDto,\n\n}\n\n\n\nimpl AccountPropertiesInfoDto {\n\n pub fn compact(&self) -> Result<AccountProperties> {\n\n let dto = self.account_properties.clone();\n\n\n\n let mut allowed_addresses: Vec<Address> = vec![];\n\n let mut allowed_mosaic_id: Vec<MosaicId> = vec![];\n\n let mut allowed_entity_types: Vec<TransactionType> = vec![];\n\n let mut blocked_addresses: Vec<Address> = vec![];\n", "file_path": "src/api/dtos/account_dto.rs", "rank": 10, "score": 162138.7001246756 }, { "content": "#[derive(Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct AccountLinkTransactionDto {\n\n #[serde(flatten)]\n\n r#abstract: AbstractTransactionDto,\n\n /// The public key of the remote account.\n\n remote_account_key: String,\n\n action: u8,\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct AccountNamesDto {\n\n /// The address of the account in hexadecimal.\n\n address: String,\n\n /// The mosaic linked namespace names.\n\n names: Vec<String>,\n\n}\n\n\n\nimpl AccountNamesDto {\n\n pub fn compact(&self) -> crate::Result<AccountName> {\n\n let address = Address::from_encoded(&self.address)?;\n", "file_path": "src/api/dtos/account_dto.rs", "rank": 11, "score": 162133.69689548985 }, { "content": "type RemoveOfferDTOs = Vec<RemoveOfferDto>;\n", "file_path": "src/api/dtos/exchange_dto.rs", "rank": 12, "score": 151718.89812448283 }, { "content": "type AddOfferDTOs = Vec<AddOfferDto>;\n", "file_path": "src/api/dtos/exchange_dto.rs", "rank": 13, "score": 151718.89812448283 }, { "content": "fn parse_entity_type_dto(value_dto: Value, entity_dto: &str) -> String {\n\n let info_dto = format!(\"{{\\\"{}TransactionInfoDto\\\":{{\\\"meta\\\":\", entity_dto);\n\n\n\n format!(\"{}\", value_dto)\n\n .replace(r#\"{\"meta\":\"#, &info_dto)\n\n .replace(\"}}\", r#\"}}}\"#)\n\n}\n\n\n\npub(crate) fn map_aggregate_transactions_dto(\n\n transactions: Vec<Value>,\n\n) -> Result<Vec<Box<dyn TransactionDto>>> {\n\n let mut txs_dto: Vec<Box<dyn TransactionDto>> = vec![];\n\n for item in transactions.into_iter() {\n\n let body: Bytes = Bytes::from(item[\"AggregateTransactionInfoDto\"].to_string());\n\n let map_dto = map_transaction_dto(body)?;\n\n txs_dto.push(serde_json::from_str(&map_dto)?);\n\n }\n\n\n\n Ok(txs_dto)\n\n}\n", "file_path": "src/api/internally.rs", "rank": 14, "score": 147215.455794352 }, { "content": "fn parse_meta(value_dto: Value, entity_dto: &str) -> String {\n\n let meta = r#\"{\"meta\": {}, \"transaction\":\"#;\n\n\n\n let parse_meta = format!(\"{}\", value_dto).replace(r#\"{\"transaction\":\"#, meta);\n\n\n\n parse_entity_type_dto(parse_meta.parse().unwrap(), entity_dto)\n\n}\n\n\n", "file_path": "src/api/internally.rs", "rank": 15, "score": 145854.8864921942 }, { "content": "type ConfirmationOfferDTOs = Vec<ConfirmationOffer>;\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct OfferDTO {\n\n mosaic_id: Uint64Dto,\n\n mosaic_amount: Uint64Dto,\n\n cost: Uint64Dto,\n\n r#type: u8,\n\n}\n\n\n\nimpl OfferDTO {\n\n fn compact(&self) -> Offer {\n\n let asset_id = self.mosaic_id.compact();\n\n Offer {\n\n r#type: OfferType::from(self.r#type),\n\n mosaic: Mosaic {\n\n asset_id: Box::new(MosaicId::from(asset_id)),\n\n amount: self.mosaic_amount.compact(),\n\n },\n", "file_path": "src/api/dtos/exchange_dto.rs", "rank": 16, "score": 143198.67346812127 }, { "content": "// Copyright 2018 ProximaX Limited. All rights reserved.\n\n// Use of this source code is governed by the Apache 2.0\n\n// license that can be found in the LICENSE file.\n\n\n\n/// SourceDto : The transaction that triggered the receipt.\n\n#[derive(Serialize, Deserialize)]\n\npub(crate) struct SourceDto {\n\n /// The transaction index within the block.\n\n primary_id: i32,\n\n /// The transaction index inside within the aggregate transaction. If the transaction is not an inner transaction, then the secondary id is set to 0.\n\n secondary_id: i32,\n\n}\n", "file_path": "src/api/dtos/source_dto.rs", "rank": 17, "score": 137230.05403490967 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse crate::{\n\n account::Address,\n\n transaction::{MetadataAddressTransaction, Transaction},\n\n};\n\n\n\nuse super::{ModifyMetadataTransactionDto, TransactionDto, TransactionMetaDto};\n\n\n\n/// AddressMetadataTransactionDto :\n\n///Transaction that addes metadata to account.\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct AddressMetadataTransactionDto {\n\n #[serde(flatten)]\n\n metadata_transaction: ModifyMetadataTransactionDto,\n", "file_path": "src/api/dtos/address_dto.rs", "rank": 18, "score": 137020.45159999118 }, { "content": " #[serde(rename = \"metadataId\")]\n\n address: String,\n\n}\n\n\n\n#[derive(Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct AddressMetadataTransactionInfoDto {\n\n meta: TransactionMetaDto,\n\n transaction: AddressMetadataTransactionDto,\n\n}\n\n\n\n#[typetag::serde]\n\nimpl TransactionDto for AddressMetadataTransactionInfoDto {\n\n fn compact(&self) -> crate::models::Result<Box<dyn Transaction>> {\n\n let dto = self.transaction.clone();\n\n\n\n let info = self.meta.compact()?;\n\n\n\n let metadata_transaction = dto.metadata_transaction.compact(info)?;\n\n\n\n let address = Address::from_encoded(&dto.address)?;\n\n\n\n Ok(Box::new(MetadataAddressTransaction {\n\n metadata_transaction,\n\n address,\n\n }))\n\n }\n\n}\n", "file_path": "src/api/dtos/address_dto.rs", "rank": 19, "score": 136989.13470176628 }, { "content": "pub fn alias_transaction_schema() -> Schema {\n\n let mut schema_definition = schema_common_definition();\n\n\n\n let mut alias_definition: Vec<Box<dyn SchemaAttribute>> = vec![\n\n Box::new(ScalarAttribute::new(\"action_type\", SIZEOF_BYTE)),\n\n Box::new(ArrayAttribute::new(\"namespace_id\", SIZEOF_INT)),\n\n Box::new(ArrayAttribute::new(\"aliasId\", SIZEOF_BYTE)),\n\n ];\n\n\n\n schema_definition.append(&mut alias_definition);\n\n\n\n Schema::new(schema_definition)\n\n}\n", "file_path": "src/models/transaction/schema/transaction_alias.rs", "rank": 20, "score": 118474.79208423689 }, { "content": "pub fn transfer_transaction_schema() -> Schema {\n\n let mut schema_definition = schema_common_definition();\n\n\n\n let mut transfer_schema_definition: Vec<Box<dyn SchemaAttribute>> = vec![\n\n Box::new(ArrayAttribute::new(\"recipient\", SIZEOF_BYTE)),\n\n Box::new(ScalarAttribute::new(\"message_size\", SIZEOF_SHORT)),\n\n Box::new(ScalarAttribute::new(\"num_mosaics\", SIZEOF_BYTE)),\n\n Box::new(TableAttribute::new(\n\n \"message\",\n\n vec![\n\n Box::new(ScalarAttribute::new(\"type\", SIZEOF_BYTE)),\n\n Box::new(ArrayAttribute::new(\"payload\", SIZEOF_BYTE)),\n\n ],\n\n )),\n\n Box::new(TableArrayAttribute::new(\n\n \"mosaics\",\n\n vec![\n\n Box::new(ArrayAttribute::new(\"id\", SIZEOF_INT)),\n\n Box::new(ArrayAttribute::new(\"amount\", SIZEOF_INT)),\n\n ],\n\n )),\n\n ];\n\n\n\n schema_definition.append(&mut transfer_schema_definition);\n\n\n\n Schema::new(schema_definition)\n\n}\n", "file_path": "src/models/transaction/schema/transaction_transafer.rs", "rank": 21, "score": 118474.79208423689 }, { "content": "pub fn aggregate_transaction_schema() -> Schema {\n\n let mut schema_definition = schema_common_definition();\n\n\n\n let mut aggregate: Vec<Box<dyn SchemaAttribute>> = vec![\n\n Box::new(ScalarAttribute::new(\"transactions_size\", SIZEOF_INT)),\n\n Box::new(ArrayAttribute::new(\"transactions\", SIZEOF_BYTE)),\n\n ];\n\n\n\n schema_definition.append(&mut aggregate);\n\n\n\n Schema::new(schema_definition)\n\n}\n", "file_path": "src/models/transaction/schema/transaction_aggregate.rs", "rank": 22, "score": 118474.79208423689 }, { "content": "pub fn is_hex(input: &str) -> bool {\n\n if input == \"\" {\n\n return false;\n\n }\n\n\n\n let re = Regex::new(r\"^[a-fA-F0-9]+$\").unwrap();\n\n\n\n re.is_match(input)\n\n}\n\n\n", "file_path": "src/helpers/utils_hex.rs", "rank": 23, "score": 117282.76480328871 }, { "content": "pub fn exchange_offer_transaction_schema() -> Schema {\n\n let mut schema_definition = schema_common_definition();\n\n\n\n let mut transfer_schema_definition: Vec<Box<dyn SchemaAttribute>> = vec![\n\n Box::new(ScalarAttribute::new(\"offers_count\", SIZEOF_BYTE)),\n\n Box::new(TableArrayAttribute::new(\n\n \"offers\",\n\n vec![\n\n Box::new(ArrayAttribute::new(\"mosaic_id\", SIZEOF_INT)),\n\n Box::new(ArrayAttribute::new(\"mosaic_amount\", SIZEOF_INT)),\n\n Box::new(ArrayAttribute::new(\"cost\", SIZEOF_INT)),\n\n Box::new(ScalarAttribute::new(\"type\", SIZEOF_BYTE)),\n\n Box::new(ArrayAttribute::new(\"owner\", SIZEOF_BYTE)),\n\n ],\n\n )),\n\n ];\n\n\n\n schema_definition.append(&mut transfer_schema_definition);\n\n\n\n Schema::new(schema_definition)\n\n}\n\n\n", "file_path": "src/models/transaction/schema/transaction_exchange.rs", "rank": 24, "score": 117112.2271494889 }, { "content": "pub fn modify_metadata_transaction_schema() -> Schema {\n\n let mut schema_definition = schema_common_definition();\n\n\n\n let mut alias_definition: Vec<Box<dyn SchemaAttribute>> = vec![\n\n Box::new(ScalarAttribute::new(\"metadata_type\", SIZEOF_BYTE)),\n\n Box::new(ArrayAttribute::new(\"metadata_id\", SIZEOF_BYTE)),\n\n Box::new(TableArrayAttribute::new(\n\n \"modifications\",\n\n vec![\n\n Box::new(ScalarAttribute::new(\"size\", SIZEOF_INT)),\n\n Box::new(ScalarAttribute::new(\"modification_type\", SIZEOF_BYTE)),\n\n Box::new(ScalarAttribute::new(\"key_size\", SIZEOF_BYTE)),\n\n Box::new(ArrayAttribute::new(\"value_size\", SIZEOF_BYTE)),\n\n Box::new(ArrayAttribute::new(\"key\", SIZEOF_BYTE)),\n\n Box::new(ArrayAttribute::new(\"value\", SIZEOF_BYTE)),\n\n ],\n\n )),\n\n ];\n\n\n\n schema_definition.append(&mut alias_definition);\n\n\n\n Schema::new(schema_definition)\n\n}\n", "file_path": "src/models/transaction/schema/transaction_metadata.rs", "rank": 25, "score": 117112.2271494889 }, { "content": "pub fn hex_encode(bytes: &[u8]) -> String {\n\n hex::encode(bytes)\n\n}\n", "file_path": "src/helpers/utils_hex.rs", "rank": 26, "score": 115826.25496219334 }, { "content": "pub fn account_property_transaction_schema() -> Schema {\n\n let mut schema_definition = schema_common_definition();\n\n\n\n let mut transfer_schema_definition: Vec<Box<dyn SchemaAttribute>> = vec![\n\n Box::new(ScalarAttribute::new(\"property_type\", SIZEOF_BYTE)),\n\n Box::new(ScalarAttribute::new(\"modification_count\", SIZEOF_BYTE)),\n\n Box::new(TableArrayAttribute::new(\n\n \"modifications\",\n\n vec![\n\n Box::new(ScalarAttribute::new(\"modificationType\", SIZEOF_BYTE)),\n\n Box::new(ArrayAttribute::new(\"value\", SIZEOF_BYTE)),\n\n ],\n\n )),\n\n ];\n\n\n\n schema_definition.append(&mut transfer_schema_definition);\n\n\n\n Schema::new(schema_definition)\n\n}\n", "file_path": "src/models/transaction/schema/transaction_account_property.rs", "rank": 27, "score": 115793.26220666015 }, { "content": "pub fn mosaic_definition_transaction_schema() -> Schema {\n\n let mut schema_definition = schema_common_definition();\n\n\n\n let mut transfer_schema_definition: Vec<Box<dyn SchemaAttribute>> = vec![\n\n Box::new(ScalarAttribute::new(\"mosaic_nonce\", SIZEOF_INT)),\n\n Box::new(ArrayAttribute::new(\"mosaic_id\", SIZEOF_INT)),\n\n Box::new(ScalarAttribute::new(\"num_optional_properties\", SIZEOF_BYTE)),\n\n Box::new(ScalarAttribute::new(\"flags\", SIZEOF_BYTE)),\n\n Box::new(ScalarAttribute::new(\"divisibility\", SIZEOF_BYTE)),\n\n Box::new(TableArrayAttribute::new(\n\n \"modifications\",\n\n vec![\n\n Box::new(ScalarAttribute::new(\"mosaic_property_id\", SIZEOF_BYTE)),\n\n Box::new(ArrayAttribute::new(\"value\", SIZEOF_INT)),\n\n ],\n\n )),\n\n ];\n\n\n\n schema_definition.append(&mut transfer_schema_definition);\n\n\n\n Schema::new(schema_definition)\n\n}\n", "file_path": "src/models/transaction/schema/transaction_mosaic_definition.rs", "rank": 28, "score": 115793.26220666015 }, { "content": "pub fn lock_funds_transaction_schema() -> Schema {\n\n let mut schema_definition = schema_common_definition();\n\n\n\n let mut lock_funds_transaction_definition: Vec<Box<dyn SchemaAttribute>> = vec![\n\n Box::new(ArrayAttribute::new(\"mosaic_id\", SIZEOF_INT)),\n\n Box::new(ArrayAttribute::new(\"mosaic_amount\", SIZEOF_INT)),\n\n Box::new(ArrayAttribute::new(\"duration\", SIZEOF_INT)),\n\n Box::new(ArrayAttribute::new(\"hash\", SIZEOF_BYTE)),\n\n ];\n\n\n\n schema_definition.append(&mut lock_funds_transaction_definition);\n\n\n\n Schema::new(schema_definition)\n\n}\n", "file_path": "src/models/transaction/schema/transaction_hash_lock.rs", "rank": 29, "score": 115793.26220666015 }, { "content": "pub fn add_exchange_offer_transaction_schema() -> Schema {\n\n let mut schema_definition = schema_common_definition();\n\n\n\n let mut transfer_schema_definition: Vec<Box<dyn SchemaAttribute>> = vec![\n\n Box::new(ScalarAttribute::new(\"offers_count\", SIZEOF_BYTE)),\n\n Box::new(TableArrayAttribute::new(\n\n \"offers\",\n\n vec![\n\n Box::new(ArrayAttribute::new(\"mosaic_id\", SIZEOF_INT)),\n\n Box::new(ArrayAttribute::new(\"mosaic_amount\", SIZEOF_INT)),\n\n Box::new(ArrayAttribute::new(\"cost\", SIZEOF_INT)),\n\n Box::new(ScalarAttribute::new(\"type\", SIZEOF_BYTE)),\n\n Box::new(ArrayAttribute::new(\"duration\", SIZEOF_INT)),\n\n ],\n\n )),\n\n ];\n\n\n\n schema_definition.append(&mut transfer_schema_definition);\n\n\n\n Schema::new(schema_definition)\n\n}\n\n\n", "file_path": "src/models/transaction/schema/transaction_exchange.rs", "rank": 30, "score": 115793.26220666015 }, { "content": "pub fn remove_exchange_offer_transaction_schema() -> Schema {\n\n let mut schema_definition = schema_common_definition();\n\n\n\n let mut transfer_schema_definition: Vec<Box<dyn SchemaAttribute>> = vec![\n\n Box::new(ScalarAttribute::new(\"offers_count\", SIZEOF_BYTE)),\n\n Box::new(TableArrayAttribute::new(\n\n \"offers\",\n\n vec![\n\n Box::new(ArrayAttribute::new(\"mosaic_id\", SIZEOF_INT)),\n\n Box::new(ScalarAttribute::new(\"type\", SIZEOF_BYTE)),\n\n ],\n\n )),\n\n ];\n\n\n\n schema_definition.append(&mut transfer_schema_definition);\n\n\n\n Schema::new(schema_definition)\n\n}\n", "file_path": "src/models/transaction/schema/transaction_exchange.rs", "rank": 31, "score": 115793.26220666015 }, { "content": "pub fn register_namespace_transaction_schema() -> Schema {\n\n let mut schema_definition = schema_common_definition();\n\n\n\n let mut register_namespace_definition: Vec<Box<dyn SchemaAttribute>> = vec![\n\n Box::new(ScalarAttribute::new(\"namespace_type\", SIZEOF_BYTE)),\n\n Box::new(ArrayAttribute::new(\"duration_parent_id\", SIZEOF_INT)),\n\n Box::new(ArrayAttribute::new(\"namespace_id\", SIZEOF_INT)),\n\n Box::new(ScalarAttribute::new(\"namespace_name_size\", SIZEOF_BYTE)),\n\n Box::new(ArrayAttribute::new(\"name\", SIZEOF_BYTE)),\n\n ];\n\n\n\n schema_definition.append(&mut register_namespace_definition);\n\n\n\n Schema::new(schema_definition)\n\n}\n", "file_path": "src/models/transaction/schema/transaction_register_namespace.rs", "rank": 32, "score": 115793.26220666015 }, { "content": "pub fn array_u8_to_u64(bytes: &[u8]) -> u64 {\n\n (bytes[0] as u64)\n\n | (bytes[1] as u64) << 8\n\n | (bytes[2] as u64) << 16\n\n | (bytes[3] as u64) << 24\n\n | (bytes[4] as u64) << 32\n\n | (bytes[5] as u64) << 40\n\n | (bytes[6] as u64) << 48\n\n | (bytes[7] as u64) << 56\n\n}\n\n\n", "file_path": "src/helpers/utils_bytes.rs", "rank": 33, "score": 114417.89182707938 }, { "content": "pub fn modify_multisig_account_transaction_schema() -> Schema {\n\n let mut schema_definition = schema_common_definition();\n\n\n\n let mut modify_multisig_account_transaction: Vec<Box<dyn SchemaAttribute>> = vec![\n\n Box::new(ScalarAttribute::new(\"min_removal_delta\", SIZEOF_BYTE)),\n\n Box::new(ScalarAttribute::new(\"min_approval_delta\", SIZEOF_BYTE)),\n\n Box::new(ScalarAttribute::new(\"num_modifications\", SIZEOF_BYTE)),\n\n Box::new(TableArrayAttribute::new(\n\n \"modification\",\n\n vec![\n\n Box::new(ScalarAttribute::new(\"type\", SIZEOF_BYTE)),\n\n Box::new(ArrayAttribute::new(\"cosignatory_publicKey\", SIZEOF_BYTE)),\n\n ],\n\n )),\n\n ];\n\n\n\n schema_definition.append(&mut modify_multisig_account_transaction);\n\n\n\n Schema::new(schema_definition)\n\n}\n", "file_path": "src/models/transaction/schema/transaction_modify_multisig_account.rs", "rank": 34, "score": 113278.02104639719 }, { "content": "pub fn mosaic_supply_change_transaction_schema() -> Schema {\n\n let mut schema_definition = schema_common_definition();\n\n\n\n let mut mosaic_supply_change_definition: Vec<Box<dyn SchemaAttribute>> = vec![\n\n Box::new(ArrayAttribute::new(\"mosaic_id\", SIZEOF_INT)),\n\n Box::new(ScalarAttribute::new(\"direction\", SIZEOF_BYTE)),\n\n Box::new(ArrayAttribute::new(\"delta\", SIZEOF_INT)),\n\n ];\n\n\n\n schema_definition.append(&mut mosaic_supply_change_definition);\n\n\n\n Schema::new(schema_definition)\n\n}\n", "file_path": "src/models/transaction/schema/transaction_mosaic_supply_change.rs", "rank": 35, "score": 113278.02104639719 }, { "content": "pub fn has_bits(number: u64, bits: u64) -> bool {\n\n (number & bits) == bits\n\n}\n", "file_path": "src/helpers/utils_bytes.rs", "rank": 36, "score": 111210.90084167274 }, { "content": "#[inline]\n\npub fn u32_to_array_u8(value: u32) -> [u8; SIZE_U32] {\n\n let mut buf = [0u8; SIZE_U32];\n\n buf.as_mut()\n\n .write_u32::<LittleEndian>(value)\n\n .expect(\"Unable to write\");\n\n buf\n\n}\n\n\n", "file_path": "src/helpers/utils_bytes.rs", "rank": 37, "score": 110044.24290340747 }, { "content": "pub fn array_u8_to_u32(bytes: [u8; SIZE_U32]) -> u32 {\n\n (bytes[0] as u32) | (bytes[1] as u32) << 8 | (bytes[2] as u32) << 16 | (bytes[3] as u32) << 24\n\n}\n\n\n", "file_path": "src/helpers/utils_bytes.rs", "rank": 38, "score": 110044.24290340747 }, { "content": "#[inline]\n\npub fn u64_to_array_u8(value: u64) -> [u8; SIZE_U64] {\n\n let mut buf = [0u8; SIZE_U64];\n\n buf.as_mut()\n\n .write_u64::<LittleEndian>(value)\n\n .expect(\"Unable to write\");\n\n buf\n\n}\n\n\n", "file_path": "src/helpers/utils_bytes.rs", "rank": 39, "score": 110044.24290340747 }, { "content": "type NamespaceIdDto = Option<Uint64Dto>;\n\n\n\n#[derive(Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct NamespaceDto {\n\n /// The public key of the owner of the namespace.\n\n owner: String,\n\n /// The address of the owner of the namespace in hexadecimal.\n\n owner_address: String,\n\n start_height: Uint64Dto,\n\n end_height: Uint64Dto,\n\n #[serde(rename = \"depth\")]\n\n depth: u8,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n level0: NamespaceIdDto,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n level1: NamespaceIdDto,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n level2: NamespaceIdDto,\n\n #[serde(rename = \"type\")]\n", "file_path": "src/api/dtos/namespace_dto.rs", "rank": 40, "score": 96302.97046793539 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse {\n\n ::std::{collections::HashMap, sync::Arc},\n\n reqwest::{\n\n header::{HeaderMap, CONTENT_LENGTH, CONTENT_TYPE, USER_AGENT},\n\n Method, StatusCode, Url,\n\n },\n\n serde_json,\n\n};\n\n\n\nuse crate::models::error::{Error, SiriusError};\n\n\n\nuse super::{\n\n internally::{map_transaction_dto, map_transaction_dto_vec},\n\n sirius_client::ApiClient,\n", "file_path": "src/api/request.rs", "rank": 41, "score": 94881.66936092699 }, { "content": " let param = param.replace('\"', \"\");\n\n self.path_params.insert(basename, param);\n\n self\n\n }\n\n\n\n pub fn set_transaction(mut self) -> Self {\n\n self.is_transaction = true;\n\n self\n\n }\n\n\n\n pub fn set_transaction_vec(mut self) -> Self {\n\n self.is_transaction_vec = true;\n\n self\n\n }\n\n\n\n pub async fn execute<U>(self, api: Arc<ApiClient>) -> crate::models::Result<U>\n\n where\n\n for<'de> U: serde::Deserialize<'de>,\n\n {\n\n // raw_headers is for headers we don't know the proper type of (e.g. custom api key\n", "file_path": "src/api/request.rs", "rank": 42, "score": 94855.37194627292 }, { "content": "};\n\n\n\n#[derive(Clone)]\n\npub(crate) struct Request {\n\n method: Method,\n\n path: String,\n\n query_params: HashMap<String, String>,\n\n path_params: HashMap<String, String>,\n\n header_params: HashMap<String, String>,\n\n // TODO: multiple body params are possible technically, but not supported here.\n\n serialized_body: Option<String>,\n\n is_transaction: bool,\n\n is_transaction_vec: bool,\n\n}\n\n\n\nimpl Request {\n\n pub fn new(method: reqwest::Method, path: String) -> Self {\n\n Request {\n\n method,\n\n path,\n", "file_path": "src/api/request.rs", "rank": 43, "score": 94850.91978018929 }, { "content": " // set new pairs\n\n url.query_pairs_mut()\n\n .clear()\n\n .extend_pairs(pairs.iter().map(|&(k, v)| (&k[..], &v[..])));\n\n };\n\n\n\n // create request\n\n let builder = api.client.request(self.method, url.as_str()).body(\n\n self.serialized_body\n\n .clone()\n\n .unwrap_or_else(|| \"\".to_owned()),\n\n );\n\n\n\n let mut req = builder.build()?;\n\n\n\n if let Some(body) = self.serialized_body {\n\n req.headers_mut().insert(\n\n CONTENT_TYPE,\n\n \"application/json\"\n\n .parse()\n", "file_path": "src/api/request.rs", "rank": 44, "score": 94846.37502476864 }, { "content": " let status = resp.status();\n\n\n\n let body = resp.bytes().await?;\n\n\n\n match status {\n\n StatusCode::OK | StatusCode::ACCEPTED => {\n\n if self.is_transaction {\n\n let map_dto = map_transaction_dto(body)?;\n\n let res: U = serde_json::from_str(&map_dto)?;\n\n Ok(res)\n\n } else if self.is_transaction_vec {\n\n let map_dto_vec = map_transaction_dto_vec(body)?;\n\n let res: U = serde_json::from_str(&map_dto_vec)?;\n\n Ok(res)\n\n } else {\n\n let res: U = serde_json::from_slice(&body)?;\n\n Ok(res)\n\n }\n\n }\n\n _ => {\n\n let err: SiriusError = serde_json::from_slice(&body)?;\n\n Err(Error::from(err))\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/api/request.rs", "rank": 45, "score": 94846.02504587766 }, { "content": " .map_err(|err| Error::from(format_err!(\"{}\", err)))?,\n\n );\n\n\n\n req.headers_mut().insert(CONTENT_LENGTH, body.len().into());\n\n }\n\n\n\n let req_headers = req.headers_mut();\n\n if let Some(ref user_agent) = api.user_agent {\n\n req_headers.insert(\n\n USER_AGENT,\n\n user_agent\n\n .parse()\n\n .map_err(|err| Error::from(format_err!(\"{}\", err)))?,\n\n );\n\n }\n\n\n\n req_headers.extend(headers);\n\n\n\n let resp = api.client.execute(req).await?;\n\n\n", "file_path": "src/api/request.rs", "rank": 46, "score": 94842.70913481578 }, { "content": " query_params: HashMap::new(),\n\n path_params: HashMap::new(),\n\n header_params: HashMap::new(),\n\n serialized_body: None,\n\n is_transaction: false,\n\n is_transaction_vec: false,\n\n }\n\n }\n\n\n\n pub fn with_body_param<T: serde::Serialize>(mut self, param: T) -> Self {\n\n self.serialized_body = Some(serde_json::to_string(&param).unwrap());\n\n self\n\n }\n\n\n\n pub fn with_query_param(mut self, basename: String, param: String) -> Self {\n\n self.query_params.insert(basename, param);\n\n self\n\n }\n\n\n\n pub fn with_path_param(mut self, basename: String, param: String) -> Self {\n", "file_path": "src/api/request.rs", "rank": 47, "score": 94841.34168692291 }, { "content": "\n\n if !self.query_params.is_empty() {\n\n let existing: Vec<(String, String)> = url\n\n .query_pairs()\n\n .map(|(a, b)| (a.to_string(), b.to_string()))\n\n .collect();\n\n\n\n // final pairs\n\n let mut pairs: Vec<(&str, &str)> = Vec::new();\n\n\n\n // add first existing\n\n for pair in &existing {\n\n pairs.push((&pair.0, &pair.1));\n\n }\n\n\n\n // add given query to the pairs\n\n for (key, val) in self.query_params.iter() {\n\n pairs.push((key, val));\n\n }\n\n\n", "file_path": "src/api/request.rs", "rank": 48, "score": 94832.29075500843 }, { "content": " // headers); headers is for ones we do know the type of.\n\n let mut raw_headers = HashMap::new();\n\n let headers: HeaderMap = HeaderMap::new();\n\n\n\n let mut path = self.path;\n\n\n\n self.path_params.into_iter().for_each(|(key, val)| {\n\n // replace {id} with the value of the id path param\n\n path = path.replace(&format!(\"{{{}}}\", key), &val);\n\n });\n\n\n\n self.header_params.into_iter().for_each(|(key, val)| {\n\n raw_headers.insert(key, val);\n\n });\n\n\n\n let uri_str = format!(\"{}{}\", api.base_path, path);\n\n\n\n let mut url = Url::parse(&uri_str)\n\n .map_err(|e| format!(\"could not parse url: {:?}\", e))\n\n .unwrap();\n", "file_path": "src/api/request.rs", "rank": 49, "score": 94831.70934380362 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse crate::{\n\n account::{Address, PublicAccount},\n\n api::cosignatory_dto_vec_to_struct,\n\n models::Result,\n\n multisig::MultisigAccountInfo,\n\n network::NetworkType,\n\n transaction::{ModifyMultisigAccountTransaction, Transaction},\n\n};\n\n\n\nuse super::{\n\n AbstractTransactionDto, CosignatoryModificationDto, TransactionDto, TransactionMetaDto,\n\n};\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n", "file_path": "src/api/dtos/multisig_dto.rs", "rank": 50, "score": 90552.94469699076 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse crate::blockchain::{BlockchainScore, HeightInfo};\n\n\n\nuse super::{AbstractTransactionDto, Uint64Dto, UpgradeDto};\n\n\n\n#[derive(Serialize, Deserialize)]\n\npub(crate) struct HeightInfoDto {\n\n #[serde(rename = \"height\")]\n\n height: Uint64Dto,\n\n}\n\n\n\nimpl HeightInfoDto {\n\n pub fn compact(&self) -> HeightInfo {\n\n HeightInfo {\n\n height: self.height.compact(),\n", "file_path": "src/api/dtos/blockchain_dto.rs", "rank": 51, "score": 90545.51347423355 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse downcast_rs::__std::collections::HashMap;\n\n\n\nuse crate::{\n\n api::metadata_dto_vec_to_struct,\n\n models::{\n\n account::Address,\n\n metadata::{\n\n AddressMetadataInfo, MetadataInfo, MetadataModification, MetadataModificationType,\n\n MetadataType, MosaicMetadataInfo, NamespaceMetadataInfo,\n\n },\n\n mosaic::MosaicId,\n\n namespace::NamespaceId,\n\n transaction::{ModifyMetadataTransaction, TransactionInfo},\n\n },\n", "file_path": "src/api/dtos/metadata_dto.rs", "rank": 52, "score": 90545.27607064642 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse super::{ResolutionStatementDto, SourceDto};\n\n\n\n/// StatementsDto : The collection of transaction statements and resolutions triggered for the block requested.\n\n#[derive(Serialize, Deserialize)]\n\npub(crate) struct StatementsDto {\n\n /// The array of transaction statements for the block requested.\n\n transaction_statements: Vec<TransactionStatementDto>,\n\n /// The array of address resolutions for the block requested.\n\n address_resolution_statements: Vec<ResolutionStatementDto>,\n\n /// The array of mosaic resolutions for the block requested.\n\n mosaic_resolution_statements: Vec<ResolutionStatementDto>,\n\n}\n\n\n\n/// TransactionStatementDto : The collection of receipts related to a transaction.\n\n#[derive(Serialize, Deserialize)]\n\npub(crate) struct TransactionStatementDto {\n\n height: Vec<i32>,\n\n source: SourceDto,\n\n /// The array of receipts.\n\n receipts: Vec<String>,\n\n}\n", "file_path": "src/api/dtos/statements_dto.rs", "rank": 53, "score": 90544.98150662113 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse serde_json::Value;\n\n\n\nuse crate::Uint64;\n\n\n\n#[derive(Debug, Clone, Deserialize, Serialize)] // we derive Default in order to use the clear() method in Drop\n\npub(crate) struct Uint64Dto(pub(crate) [u32; 2]);\n\n\n\nimpl Uint64Dto {\n\n pub fn compact(&self) -> Uint64 {\n\n Uint64::from((self.0[0], self.0[1]))\n\n }\n\n\n\n pub fn from_value(value: Value) -> Self {\n\n Self(serde_json::from_value(value).unwrap())\n\n }\n\n}\n", "file_path": "src/api/dtos/uint_64_dto.rs", "rank": 54, "score": 90544.48613821573 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse crate::{\n\n helpers::hex_decode,\n\n message::{Message, PlainMessage},\n\n};\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\npub(crate) struct MessageDto {\n\n #[serde(rename = \"type\")]\n\n _type: u8,\n\n #[serde(rename = \"payload\")]\n\n payload: String,\n\n}\n\n\n\nimpl MessageDto {\n", "file_path": "src/api/dtos/message_dto.rs", "rank": 55, "score": 90541.00480169109 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse crate::{node::NodeTime, Uint64};\n\n\n\nuse super::Uint64Dto;\n\n\n\n#[derive(Serialize, Deserialize)]\n\npub(crate) struct NodeTimeDto {\n\n #[serde(rename = \"communicationTimestamps\")]\n\n communication_timestamps: CommunicationTimestampsDto,\n\n}\n\n\n\n#[derive(Serialize, Deserialize)]\n", "file_path": "src/api/dtos/node_dto.rs", "rank": 56, "score": 90537.9933110632 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse crate::{\n\n account::Address,\n\n alias::AliasActionType,\n\n models::Result,\n\n mosaic::MosaicId,\n\n namespace::{NamespaceAlias, NamespaceId},\n\n transaction::{AddressAliasTransaction, AliasTransaction, MosaicAliasTransaction, Transaction},\n\n};\n\n\n\nuse super::{AbstractTransactionDto, TransactionDto, TransactionMetaDto, Uint64Dto};\n\n\n\n#[derive(Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct AliasDto {\n", "file_path": "src/api/dtos/alias_dto.rs", "rank": 57, "score": 90537.99263470396 }, { "content": "// Copyright 2018 ProximaX Limited. All rights reserved.\n\n// Use of this source code is governed by the Apache 2.0\n\n// license that can be found in the LICENSE file.\n\n\n\n#[derive(Serialize, Deserialize)]\n\npub(crate) struct ServerDto {\n\n server_info: ServerInfoDto,\n\n}\n\n\n\n#[derive(Serialize, Deserialize)]\n\npub(crate) struct ServerInfoDto {\n\n /// The catapult-rest component version.\n\n rest_version: String,\n\n /// The catapult-sdk component version.\n\n sdk_version: String,\n\n}\n", "file_path": "src/api/dtos/server_dto.rs", "rank": 58, "score": 90537.79635265878 }, { "content": "// Copyright 2018 ProximaX Limited. All rights reserved.\n\n// Use of this source code is governed by the Apache 2.0\n\n// license that can be found in the LICENSE file.\n\n\n\n#[derive(Serialize, Deserialize)]\n\npub(crate) struct UpgradeDto {\n\n #[serde(rename = \"height\")]\n\n height: Vec<i32>,\n\n #[serde(rename = \"blockChainVersion\")]\n\n block_chain_version: Vec<i32>,\n\n}\n", "file_path": "src/api/dtos/upgrade_dto.rs", "rank": 59, "score": 90536.96987155586 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse super::{SourceDto, Uint64Dto};\n\n\n\n#[derive(Serialize, Deserialize)]\n\npub(crate) struct ResolutionEntryDto {\n\n #[serde(rename = \"source\")]\n\n source: SourceDto,\n\n #[serde(rename = \"resolved\")]\n\n resolved: Uint64Dto,\n\n}\n\n\n\n/// ResolutionStatementDto : A resolution statement keeps the relation between a namespace alias used in a transaction and the real address or mosaic_id.\n\n#[derive(Serialize, Deserialize)]\n\npub(crate) struct ResolutionStatementDto {\n\n height: Uint64Dto,\n\n unresolved: Uint64Dto,\n\n /// The array of resolution entries linked to the unresolved namespace_id. It is an array instead of a single UInt64 field since within one block the resolution might change for different sources due to alias related transactions.\n\n resolution_entries: Vec<ResolutionEntryDto>,\n\n}\n", "file_path": "src/api/dtos/resolution_dto.rs", "rank": 60, "score": 90536.6910752302 }, { "content": "// Copyright 2018 ProximaX Limited. All rights reserved.\n\n// Use of this source code is governed by the Apache 2.0\n\n// license that can be found in the LICENSE file.\n\n\n\n#[derive(Serialize, Deserialize)]\n\npub(crate) struct FieldDto {\n\n #[serde(rename = \"key\")]\n\n pub key: String,\n\n #[serde(rename = \"value\")]\n\n pub value: String,\n\n}\n", "file_path": "src/api/dtos/field_dto.rs", "rank": 61, "score": 90534.38022172819 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse crate::{\n\n api::mosaic_properties,\n\n models::{\n\n errors_const,\n\n mosaic::{Mosaic, MosaicId, MosaicInfo, MosaicNames, MosaicNonce, MosaicSupplyType},\n\n transaction::{\n\n MetadataMosaicTransaction, MosaicDefinitionTransaction, MosaicSupplyChangeTransaction,\n\n Transaction,\n\n },\n\n Result,\n\n },\n\n};\n\n\n\nuse super::{\n", "file_path": "src/api/dtos/mosaic_dto.rs", "rank": 62, "score": 90534.36389028298 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse crate::{\n\n account::PublicAccount,\n\n multisig::{CosignatoryModification, Cosignature, MultisigModificationType},\n\n network::NetworkType,\n\n};\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct CosignatoryModificationDto {\n\n #[serde(rename = \"type\")]\n\n modification_type: u8,\n\n cosignatory_public_key: String,\n\n}\n\n\n", "file_path": "src/api/dtos/cosignature_dto.rs", "rank": 63, "score": 90534.01716954978 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse ::std::str::FromStr;\n\n\n\nuse crate::{\n\n account::{PublicAccount, EMPTY_PUBLIC_KEY},\n\n blockchain::BlockInfo,\n\n network::extract_network_type,\n\n transaction::{internal::extract_version, BlockchainTimestamp, HashValue},\n\n Result,\n\n};\n\n\n\nuse super::Uint64Dto;\n\n\n\n#[derive(Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n", "file_path": "src/api/dtos/block_dto.rs", "rank": 64, "score": 90533.7894971473 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse crate::{\n\n account::PublicAccount,\n\n errors_const,\n\n models::Result,\n\n namespace::{NamespaceId, NamespaceInfo, NamespaceName, NamespaceType},\n\n network::NetworkType,\n\n transaction::{MetadataNamespaceTransaction, RegisterNamespaceTransaction, Transaction},\n\n AssetId,\n\n};\n\n\n\nuse super::{\n\n AbstractTransactionDto, AliasDto, ModifyMetadataTransactionDto, TransactionDto,\n\n TransactionMetaDto, Uint64Dto,\n\n};\n\n\n", "file_path": "src/api/dtos/namespace_dto.rs", "rank": 65, "score": 90533.32466941379 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse ::std::str::FromStr;\n\n\n\nuse crate::models::transaction::Signature;\n\nuse crate::{\n\n account::{Address, PublicAccount},\n\n models::Result,\n\n mosaic::{Mosaic, MosaicId},\n\n network::extract_network_type,\n\n transaction::{\n\n internal::extract_version, AbstractTransaction, BlockchainTimestamp, Deadline, HashValue,\n\n LockFundsTransaction, SignedTransaction, Transaction, TransactionInfo, TransactionStatus,\n\n TransactionType, TransferTransaction,\n\n },\n\n};\n", "file_path": "src/api/dtos/transaction_dto.rs", "rank": 66, "score": 90528.6293891636 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse {\n\n serde::{Deserialize, Deserializer},\n\n serde_json::Value,\n\n};\n\n\n\nuse crate::{\n\n account::{\n\n AccountInfo, AccountLinkType, AccountName, AccountProperties,\n\n AccountPropertiesAddressModification, AccountPropertiesEntityTypeModification,\n\n AccountPropertiesModificationType, AccountPropertiesMosaicModification,\n\n AccountPropertyType, Address,\n\n },\n\n models::{error::Error::Failure, Result},\n\n mosaic::{Mosaic, MosaicId},\n", "file_path": "src/api/dtos/account_dto.rs", "rank": 67, "score": 90528.54880259665 }, { "content": "/*\n\n * Copyright 2018 ProximaX Limited. All rights reserved.\n\n * Use of this source code is governed by the Apache 2.0\n\n * license that can be found in the LICENSE file.\n\n */\n\n\n\nuse ::std::collections::HashMap;\n\n\n\nuse crate::{\n\n helpers::has_bits,\n\n models::{\n\n account::PublicAccount,\n\n exchange::{\n\n AddOffer, ExchangeConfirmation, Offer, OfferIdInfo, OfferIdInfos, OfferInfo, OfferType,\n\n OfferType::{BuyOffer, SellOffer},\n\n RemoveOffer, UserExchangeInfo,\n\n },\n\n mosaic::{Mosaic, MosaicId},\n\n namespace::{NamespaceId, NAMESPACE_BIT},\n\n network::NetworkType,\n", "file_path": "src/api/dtos/exchange_dto.rs", "rank": 68, "score": 90525.2619955299 }, { "content": "};\n\n\n\nuse super::{AbstractTransactionDto, FieldDto, Uint64Dto};\n\n\n\n#[derive(Deserialize)]\n\npub(crate) struct MetadataDto<T> {\n\n pub(crate) metadata: T,\n\n}\n\n\n\n#[derive(Deserialize)]\n\npub(crate) struct MetadataInfoDto {\n\n #[serde(rename = \"metadataType\")]\n\n r#_type: u8,\n\n fields: Vec<FieldDto>,\n\n}\n\n\n\nimpl MetadataInfoDto {\n\n pub fn compact(&self) -> MetadataInfo {\n\n let mut fields: HashMap<String, String> = HashMap::new();\n\n\n", "file_path": "src/api/dtos/metadata_dto.rs", "rank": 69, "score": 90519.67946685763 }, { "content": "impl ModifyMetadataTransactionDto {\n\n pub fn compact(&self, info: TransactionInfo) -> crate::Result<ModifyMetadataTransaction> {\n\n let abs_transaction = self.r#abstract.compact(info)?;\n\n\n\n let modifications = metadata_dto_vec_to_struct(self.modifications.clone());\n\n Ok(ModifyMetadataTransaction {\n\n abs_transaction,\n\n metadata_type: MetadataType::from(self.metadata_type),\n\n modifications,\n\n })\n\n }\n\n}\n\n\n\n#[derive(Deserialize)]\n\npub(crate) struct AddressMetadataInfoDto {\n\n #[serde(flatten)]\n\n metadata: MetadataInfoDto,\n\n #[serde(rename = \"metadataId\")]\n\n address: String,\n\n}\n", "file_path": "src/api/dtos/metadata_dto.rs", "rank": 70, "score": 90519.0231516045 }, { "content": "// Copyright 2018 ProximaX Limited. All rights reserved.\n\n// Use of this source code is governed by the Apache 2.0\n\n// license that can be found in the LICENSE file.\n\n\n\n/// The type of the receipt:\n\n///* 0x134D (4941 decimal) - Mosaic_Rental_Fee.\n\n///* 0x124E (4686 decimal) - Namespace_Rental_Fee.\n\n///* 0x2143 (8515 decimal) - Harvest_Fee.\n\n///* 0x2248 (8776 decimal) - LockHash_Completed.\n\n///* 0x2348 (9032 decimal) - LockHash_Expired.\n\n///* 0x2252 (8786 decimal) - LockSecret_Completed.\n\n///* 0x2352 (9042 decimal) - LockSecret_Expired.\n\n///* 0x3148 (12616 decimal) - LockHash_Created.\n\n///* 0x3152 (12626 decimal) - LockSecret_Created.\n\n///* 0x414D (16717 decimal) - Mosaic_Expired.\n\n///* 0x414E (16718 decimal) - Namespace_Expired.\n\n///* 0x5143 (20803 decimal) - Inflation.\n\n///* 0xE134 (57652 decimal) - Transaction_Group.\n\n///* 0xF143 (61763 decimal) - Address_Alias_Resolution.\n\n///* 0xF243 (62019 decimal) - Mosaic_Alias_Resolution.\n", "file_path": "src/api/dtos/receipt_dto.rs", "rank": 71, "score": 90514.57726643789 }, { "content": "pub(crate) struct AccountPropertiesTransactionDto {\n\n #[serde(flatten)]\n\n r#abstract: AbstractTransactionDto,\n\n property_type: u8,\n\n modifications: Vec<AccountPropertiesModificationDto>,\n\n}\n\n\n\n#[typetag::serde]\n\nimpl TransactionDto for AccountPropertiesTransactionInfoDto {\n\n fn compact(&self) -> Result<Box<dyn Transaction>> {\n\n let dto = self.transaction.clone();\n\n\n\n let info = self.meta.compact()?;\n\n\n\n let abs_transaction = dto.r#abstract.compact(info)?;\n\n\n\n if dto.property_type & AccountPropertyType::AllowAddress.value() != 0 {\n\n let modifications: Vec<AccountPropertiesAddressModification> = dto\n\n .modifications\n\n .iter()\n", "file_path": "src/api/dtos/account_dto.rs", "rank": 72, "score": 90513.75925111523 }, { "content": " pub fn compact(&self) -> crate::Result<Vec<MultisigAccountInfo>> {\n\n Ok(self\n\n .multisig_entries\n\n .iter()\n\n .map(|item| item.compact().unwrap())\n\n .collect())\n\n }\n\n}\n\n\n\n#[derive(Serialize, Deserialize)]\n\npub(crate) struct MultisigAccountInfoDto {\n\n #[serde(rename = \"multisig\")]\n\n multisig: MultisigDto,\n\n}\n\n\n\nimpl MultisigAccountInfoDto {\n\n pub fn compact(&self) -> crate::Result<MultisigAccountInfo> {\n\n let dto = self.multisig.to_owned();\n\n let network_type: NetworkType =\n\n Address::from_encoded(&dto.account_address.unwrap())?.network_type();\n", "file_path": "src/api/dtos/multisig_dto.rs", "rank": 73, "score": 90512.66217651396 }, { "content": "#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct MultisigDto {\n\n account: String,\n\n #[serde(rename = \"accountAddress\", skip_serializing_if = \"Option::is_none\")]\n\n account_address: Option<String>,\n\n min_approval: i32,\n\n min_removal: i32,\n\n cosignatories: Vec<String>,\n\n multisig_accounts: Vec<String>,\n\n}\n\n\n\n#[derive(Serialize, Deserialize)]\n\npub(crate) struct MultisigAccountGraphInfoDto {\n\n #[serde(rename = \"level\")]\n\n pub level: i16,\n\n #[serde(rename = \"multisigEntries\")]\n\n multisig_entries: Vec<MultisigAccountInfoDto>,\n\n}\n\n\n\nimpl MultisigAccountGraphInfoDto {\n", "file_path": "src/api/dtos/multisig_dto.rs", "rank": 74, "score": 90512.4972710403 }, { "content": " mosaic_id: Option<Uint64Dto>,\n\n}\n\n\n\n#[derive(Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct AddressAliasTransactionInfoDto {\n\n meta: TransactionMetaDto,\n\n transaction: AliasTransactionDto,\n\n}\n\n\n\n#[typetag::serde]\n\nimpl TransactionDto for AddressAliasTransactionInfoDto {\n\n fn compact(&self) -> Result<Box<dyn Transaction>> {\n\n let dto = self.transaction.clone();\n\n\n\n let info = self.meta.compact()?;\n\n\n\n let address_encoded = dto.address.unwrap();\n\n\n\n let address = Address::from_encoded(&address_encoded)?;\n", "file_path": "src/api/dtos/alias_dto.rs", "rank": 75, "score": 90511.1876476279 }, { "content": "\n\n#[typetag::serde]\n\nimpl TransactionDto for TransferTransactionInfoDto {\n\n fn compact(&self) -> Result<Box<dyn Transaction>> {\n\n let dto = self.transaction.clone();\n\n let info = self.meta.compact()?;\n\n\n\n let abs_transaction = dto.r#abstract.compact(info)?;\n\n\n\n let mut mosaics: Vec<Mosaic> = vec![];\n\n if let Some(value) = &dto.mosaics {\n\n for mosaic in value {\n\n mosaics.push(mosaic.compact());\n\n }\n\n };\n\n\n\n let recipient = Address::from_encoded(&dto.recipient)?;\n\n\n\n Ok(Box::new(TransferTransaction {\n\n abs_transaction,\n", "file_path": "src/api/dtos/transaction_dto.rs", "rank": 76, "score": 90510.73174812277 }, { "content": " r#abstract: AbstractTransactionDto,\n\n pub offers: AddOfferDTOs,\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct AddExchangeOfferTransactionInfoDto {\n\n pub meta: TransactionMetaDto,\n\n pub transaction: AddExchangeOfferTransactionDto,\n\n}\n\n\n\n#[typetag::serde]\n\nimpl TransactionDto for AddExchangeOfferTransactionInfoDto {\n\n fn compact(&self) -> Result<Box<dyn Transaction>> {\n\n let dto = self.transaction.clone();\n\n let info = self.meta.compact()?;\n\n\n\n let abs_transaction = dto.r#abstract.compact(info)?;\n\n\n\n let offers: Vec<AddOffer> = dto\n", "file_path": "src/api/dtos/exchange_dto.rs", "rank": 77, "score": 90510.69836347211 }, { "content": " transaction::{\n\n AddExchangeOfferTransaction, ExchangeOfferTransaction, RemoveExchangeOfferTransaction,\n\n Transaction,\n\n },\n\n AssetId, Result,\n\n },\n\n};\n\n\n\nuse super::{AbstractTransactionDto, TransactionDto, TransactionMetaDto, Uint64Dto};\n\n\n\npub(crate) type OfferInfoDTOs = Vec<OfferInfoDto>;\n", "file_path": "src/api/dtos/exchange_dto.rs", "rank": 78, "score": 90510.62766981818 }, { "content": "\n\nimpl AddressMetadataInfoDto {\n\n pub fn compact(&self) -> crate::Result<AddressMetadataInfo> {\n\n let info = self.metadata.compact();\n\n\n\n let address = if !self.address.is_empty() {\n\n Address::from_encoded(&self.address)?\n\n } else {\n\n Address::default()\n\n };\n\n Ok(AddressMetadataInfo { info, address })\n\n }\n\n}\n\n\n\n#[derive(Deserialize)]\n\npub(crate) struct MosaicMetadataInfoDto {\n\n #[serde(flatten)]\n\n metadata: MetadataInfoDto,\n\n #[serde(rename = \"metadataId\")]\n\n mosaic_id: Uint64Dto,\n", "file_path": "src/api/dtos/metadata_dto.rs", "rank": 79, "score": 90510.42190668189 }, { "content": "}\n\n\n\nimpl ExchangeInfoDto {\n\n pub(crate) fn compact(&self, network_type: NetworkType) -> Result<UserExchangeInfo> {\n\n let dto = self.to_owned();\n\n let owner = PublicAccount::from_public_key(&dto.exchange.owner, network_type)?;\n\n\n\n let mut buy_offer: OfferIdInfos = vec![];\n\n let mut buy_offer_offers: Vec<OfferInfo> = vec![];\n\n for item in dto.exchange.buy_offers.into_iter() {\n\n buy_offer_offers.push(item.compact(owner.to_owned())?)\n\n }\n\n\n\n for offer_info in buy_offer_offers.into_iter() {\n\n let id = &offer_info.mosaic.asset_id;\n\n buy_offer.push(OfferIdInfo {\n\n mosaic_id: id.as_mosaic_id()?,\n\n offer_info,\n\n });\n\n }\n", "file_path": "src/api/dtos/exchange_dto.rs", "rank": 80, "score": 90509.53819607715 }, { "content": "pub(crate) struct RegisterNamespaceTransactionInfoDto {\n\n meta: TransactionMetaDto,\n\n transaction: RegisterNamespaceTransactionDto,\n\n}\n\n\n\n#[typetag::serde]\n\nimpl TransactionDto for RegisterNamespaceTransactionInfoDto {\n\n fn compact(&self) -> Result<Box<dyn Transaction>> {\n\n let dto = self.transaction.clone();\n\n\n\n let info = self.meta.compact()?;\n\n\n\n let abs_transaction = dto.r#abstract.compact(info)?;\n\n\n\n let namespace_type = NamespaceType::from(dto.namespace_type);\n\n\n\n let namespace_id = NamespaceId::from(dto.namespace_id.compact());\n\n\n\n let mut parent_id = None;\n\n\n", "file_path": "src/api/dtos/namespace_dto.rs", "rank": 81, "score": 90508.6189400059 }, { "content": " owner,\n\n offers: offers_map,\n\n })\n\n }\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct OfferInfoDto {\n\n mosaic_id: Uint64Dto,\n\n amount: Uint64Dto,\n\n initial_amount: Uint64Dto,\n\n initial_cost: Uint64Dto,\n\n deadline: Uint64Dto,\n\n pub owner: Option<String>,\n\n}\n\n\n\nimpl OfferInfoDto {\n\n pub(crate) fn compact(&self, owner: PublicAccount) -> crate::Result<OfferInfo> {\n\n let dto = self.to_owned();\n", "file_path": "src/api/dtos/exchange_dto.rs", "rank": 82, "score": 90508.35504358371 }, { "content": "#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct ExchangeOfferTransactionDto {\n\n #[serde(flatten)]\n\n r#abstract: AbstractTransactionDto,\n\n pub offers: ConfirmationOfferDTOs,\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct ExchangeOfferTransactionInfoDto {\n\n pub meta: TransactionMetaDto,\n\n pub transaction: ExchangeOfferTransactionDto,\n\n}\n\n\n\n#[typetag::serde]\n\nimpl TransactionDto for ExchangeOfferTransactionInfoDto {\n\n fn compact(&self) -> Result<Box<dyn Transaction>> {\n\n let dto = self.transaction.clone();\n\n let info = self.meta.compact()?;\n\n\n", "file_path": "src/api/dtos/exchange_dto.rs", "rank": 83, "score": 90508.31540451657 }, { "content": " let dto = &self.account;\n\n let add = Address::from_encoded(&dto.clone().address)?;\n\n let acc_type = AccountLinkType::new(dto.clone().account_type);\n\n\n\n let mosaics: Vec<Mosaic> = dto\n\n .mosaics\n\n .iter()\n\n .map(move |mosaic_dto| mosaic_dto.compact())\n\n .collect();\n\n\n\n Ok(AccountInfo::new(\n\n add,\n\n dto.clone().address_height.compact(),\n\n dto.clone().public_key,\n\n dto.public_key_height.compact(),\n\n acc_type,\n\n mosaics,\n\n ))\n\n }\n\n}\n\n\n\n/// AccountLinkTransactionDto : Delegates the account importance score to a proxy account.\n", "file_path": "src/api/dtos/account_dto.rs", "rank": 84, "score": 90507.59914264442 }, { "content": "\n\nimpl MetadataModificationDto {\n\n pub fn compact(&self) -> MetadataModification {\n\n MetadataModification {\n\n r#type: MetadataModificationType::from(self.modification_type),\n\n key: self.key.clone(),\n\n value: self.value.clone(),\n\n }\n\n }\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct ModifyMetadataTransactionDto {\n\n #[serde(flatten)]\n\n pub r#abstract: AbstractTransactionDto,\n\n pub metadata_type: u8,\n\n pub modifications: Vec<MetadataModificationDto>,\n\n}\n\n\n", "file_path": "src/api/dtos/metadata_dto.rs", "rank": 85, "score": 90506.94952124306 }, { "content": " });\n\n\n\n Ok(AccountProperties {\n\n address: Address::from_encoded(&dto.address)?,\n\n allowed_addresses,\n\n allowed_mosaic_id,\n\n allowed_entity_types,\n\n blocked_addresses,\n\n blocked_mosaic_id,\n\n blocked_entity_types,\n\n })\n\n }\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct AccountPropertiesDto {\n\n address: String,\n\n properties: Vec<PropertiesDto>,\n\n}\n\n\n", "file_path": "src/api/dtos/account_dto.rs", "rank": 86, "score": 90506.58937642124 }, { "content": " let mut blocked_mosaic_id: Vec<MosaicId> = vec![];\n\n let mut blocked_entity_types: Vec<TransactionType> = vec![];\n\n\n\n dto.properties.iter().for_each(|p_dto| {\n\n if let Some(item) = p_dto.addresses.clone() {\n\n let property_addresses = item\n\n .into_iter()\n\n .map(|hex_address| Address::from_encoded(&hex_address).unwrap())\n\n .collect();\n\n if p_dto.property_type == AccountPropertyType::AllowAddress.value() {\n\n allowed_addresses = property_addresses;\n\n } else {\n\n blocked_addresses = property_addresses;\n\n }\n\n };\n\n });\n\n\n\n dto.properties.iter().for_each(|p_dto| {\n\n if let Some(item) = p_dto.mosaic_ids.clone() {\n\n let property_mosaic_id = item\n", "file_path": "src/api/dtos/account_dto.rs", "rank": 87, "score": 90506.4157940474 }, { "content": "#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct ConfirmationOffer {\n\n #[serde(flatten)]\n\n offer_dto: OfferDTO,\n\n owner: String,\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct ExchangeDto {\n\n owner: String,\n\n buy_offers: OfferInfoDTOs,\n\n sell_offers: OfferInfoDTOs,\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct ExchangeInfoDto {\n\n exchange: ExchangeDto,\n", "file_path": "src/api/dtos/exchange_dto.rs", "rank": 88, "score": 90505.62758444347 }, { "content": "}\n\n\n\n#[typetag::serde]\n\nimpl TransactionDto for ModifyMultisigAccountTransactionInfoDto {\n\n fn compact(&self) -> Result<Box<dyn Transaction>> {\n\n let dto = self.transaction.clone();\n\n let info = self.meta.compact()?;\n\n\n\n let abs_transaction = dto.r#abstract.compact(info)?;\n\n\n\n let modifications =\n\n cosignatory_dto_vec_to_struct(dto.modifications, abs_transaction.network_type);\n\n\n\n Ok(Box::new(ModifyMultisigAccountTransaction {\n\n abs_transaction,\n\n min_removal_delta: dto.min_removal_delta,\n\n min_approval_delta: dto.min_approval_delta,\n\n modifications,\n\n }))\n\n }\n\n}\n", "file_path": "src/api/dtos/multisig_dto.rs", "rank": 89, "score": 90505.2988022442 }, { "content": " #[serde(rename = \"type\")]\n\n _type: u16,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n mosaic_id: Option<Uint64Dto>,\n\n /// The aliased address in hexadecimal.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n address: Option<String>,\n\n}\n\n\n\nimpl AliasDto {\n\n pub fn compact(&self) -> crate::Result<NamespaceAlias> {\n\n let mut alias = NamespaceAlias::default();\n\n alias.type_ = self._type as u8;\n\n\n\n if let Some(a) = &self.address {\n\n let address = Address::from_encoded(a)?;\n\n alias.address = Some(address)\n\n };\n\n\n\n if let Some(m) = &self.mosaic_id {\n", "file_path": "src/api/dtos/alias_dto.rs", "rank": 90, "score": 90505.12973691158 }, { "content": "pub(crate) struct NamespaceMetadataTransactionInfoDto {\n\n meta: TransactionMetaDto,\n\n transaction: NamespaceMetadataTransactionDto,\n\n}\n\n\n\n#[typetag::serde]\n\nimpl TransactionDto for NamespaceMetadataTransactionInfoDto {\n\n fn compact(&self) -> Result<Box<dyn Transaction>> {\n\n let dto = self.transaction.clone();\n\n\n\n let info = self.meta.compact()?;\n\n\n\n let metadata_transaction = dto.metadata_transaction.compact(info)?;\n\n\n\n let namespace_id = NamespaceId::from(dto.namespace_id.compact());\n\n\n\n Ok(Box::new(MetadataNamespaceTransaction {\n\n metadata_transaction,\n\n namespace_id,\n\n }))\n", "file_path": "src/api/dtos/namespace_dto.rs", "rank": 91, "score": 90505.10875483896 }, { "content": " #[serde(flatten)]\n\n metadata_transaction: ModifyMetadataTransactionDto,\n\n #[serde(rename = \"metadataId\")]\n\n mosaic_id: Uint64Dto,\n\n}\n\n\n\n#[derive(Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct MosaicMetadataTransactionInfoDto {\n\n meta: TransactionMetaDto,\n\n transaction: MosaicMetadataTransactionDto,\n\n}\n\n\n\n#[typetag::serde]\n\nimpl TransactionDto for MosaicMetadataTransactionInfoDto {\n\n fn compact(&self) -> Result<Box<dyn Transaction>> {\n\n let dto = self.transaction.clone();\n\n\n\n let info = self.meta.compact()?;\n\n\n", "file_path": "src/api/dtos/mosaic_dto.rs", "rank": 92, "score": 90504.9721699059 }, { "content": "\n\n Ok(AccountName {\n\n address,\n\n names: self.to_owned().names,\n\n })\n\n }\n\n}\n\n\n\n#[derive(Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct AccountPropertiesTransactionInfoDto {\n\n meta: TransactionMetaDto,\n\n transaction: AccountPropertiesTransactionDto,\n\n}\n\n\n\n/// AccountPropertiesTransactionDto :\n\n/// Transaction that prevents receiving transactions from undesired\n\n/// addresses, mosaics or sending certain transaction types.\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n", "file_path": "src/api/dtos/account_dto.rs", "rank": 93, "score": 90504.87245619828 }, { "content": " let metadata_transaction = dto.metadata_transaction.compact(info)?;\n\n\n\n let mosaic_id = MosaicId::from(dto.mosaic_id.compact());\n\n\n\n Ok(Box::new(MetadataMosaicTransaction {\n\n metadata_transaction,\n\n mosaic_id,\n\n }))\n\n }\n\n}\n\n\n\n#[derive(Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct MosaicNamesDto {\n\n mosaic_id: Uint64Dto,\n\n names: Vec<String>,\n\n}\n\n\n\nimpl MosaicNamesDto {\n\n pub fn compact(&self) -> MosaicNames {\n", "file_path": "src/api/dtos/mosaic_dto.rs", "rank": 94, "score": 90504.74833935809 }, { "content": " })\n\n }\n\n}\n\n\n\n#[derive(Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct ModifyMultisigAccountTransactionInfoDto {\n\n meta: TransactionMetaDto,\n\n transaction: ModifyMultisigAccountTransactionDto,\n\n}\n\n\n\n/// ModifyMultisigAccountTransactionDto : Transaction that creates or modifies a multisig account.\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct ModifyMultisigAccountTransactionDto {\n\n #[serde(flatten)]\n\n r#abstract: AbstractTransactionDto,\n\n min_removal_delta: i8,\n\n min_approval_delta: i8,\n\n modifications: Vec<CosignatoryModificationDto>,\n", "file_path": "src/api/dtos/multisig_dto.rs", "rank": 95, "score": 90504.6375216104 }, { "content": " MosaicNames::new(\n\n MosaicId::from(self.mosaic_id.compact()),\n\n (self.names).to_owned(),\n\n )\n\n }\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\npub(crate) struct MosaicPropertyDto {\n\n pub(crate) id: u8,\n\n pub(crate) value: Uint64Dto,\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct MosaicSupplyChangeTransactionInfoDto {\n\n meta: TransactionMetaDto,\n\n transaction: MosaicSupplyChangeTransactionDto,\n\n}\n\n\n", "file_path": "src/api/dtos/mosaic_dto.rs", "rank": 96, "score": 90504.56589782966 }, { "content": "}\n\n\n\nimpl MosaicMetadataInfoDto {\n\n pub fn compact(&self) -> crate::Result<MosaicMetadataInfo> {\n\n let info = self.metadata.compact();\n\n\n\n let mosaic_id = if !self.mosaic_id.0.is_empty() {\n\n MosaicId::from(self.mosaic_id.compact())\n\n } else {\n\n MosaicId::default()\n\n };\n\n Ok(MosaicMetadataInfo { info, mosaic_id })\n\n }\n\n}\n\n\n\n#[derive(Deserialize)]\n\npub(crate) struct NamespaceMetadataInfoDto {\n\n #[serde(flatten)]\n\n metadata: MetadataInfoDto,\n\n #[serde(rename = \"metadataId\")]\n", "file_path": "src/api/dtos/metadata_dto.rs", "rank": 97, "score": 90503.76918955275 }, { "content": " } else {\n\n None\n\n };\n\n\n\n Ok(TransactionStatus::new(\n\n dto.group.clone().unwrap(),\n\n dto.status.clone(),\n\n HashValue::from_str(&dto.hash.as_ref().unwrap())?,\n\n deadline,\n\n height,\n\n ))\n\n }\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct TransferTransactionInfoDto {\n\n pub meta: TransactionMetaDto,\n\n pub transaction: TransferTransactionDto,\n\n}\n", "file_path": "src/api/dtos/transaction_dto.rs", "rank": 98, "score": 90503.75979421864 }, { "content": " confirmations,\n\n }))\n\n }\n\n}\n\n\n\n/// AddExchangeOfferTransactionDto.\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct RemoveExchangeOfferTransactionDto {\n\n #[serde(flatten)]\n\n r#abstract: AbstractTransactionDto,\n\n pub offers: RemoveOfferDTOs,\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(crate) struct RemoveExchangeOfferTransactionInfoDto {\n\n pub meta: TransactionMetaDto,\n\n pub transaction: RemoveExchangeOfferTransactionDto,\n\n}\n", "file_path": "src/api/dtos/exchange_dto.rs", "rank": 99, "score": 90503.62273871123 } ]
Rust
src/config/mod.rs
pc37utn/rocfl
723501625b4b8775901470ffacd856124bfd4713
use std::collections::HashMap; use std::fs; use std::io::Read; use std::path::{Path, PathBuf}; use directories::ProjectDirs; use serde::Deserialize; use crate::ocfl::{DigestAlgorithm, Result, RocflError}; const CONFIG_FILE: &str = "config.toml"; const GLOBAL: &str = "global"; #[derive(Deserialize, Debug)] #[serde(deny_unknown_fields)] pub struct Config { pub author_name: Option<String>, pub author_address: Option<String>, pub root: Option<String>, pub staging_root: Option<String>, pub region: Option<String>, pub bucket: Option<String>, pub endpoint: Option<String>, pub profile: Option<String>, } impl Config { pub fn new() -> Self { Self { author_name: None, author_address: None, root: None, staging_root: None, region: None, bucket: None, endpoint: None, profile: None, } } pub fn validate(&self) -> Result<()> { if self.bucket.is_some() { if self.region.is_none() { return Err(RocflError::InvalidConfiguration( "Region must be specified when using S3".to_string(), )); } } else if self.region.is_some() || self.endpoint.is_some() { return Err(RocflError::InvalidConfiguration( "Region and endpoint should not be set when not using S3. \ If you intended to use S3, then you must specify a bucket." .to_string(), )); } Ok(()) } } impl Default for Config { fn default() -> Self { Self::new() } } pub fn load_config(name: &Option<String>) -> Result<Config> { if let Some(config_file) = config_path() { if config_file.exists() { let config = parse_config(&config_file)?; return Ok(resolve_config(name, config)); } } Ok(Config::new()) } pub fn config_path() -> Option<PathBuf> { project_dirs().map(|dirs| dirs.config_dir().join(CONFIG_FILE)) } pub fn project_dirs() -> Option<ProjectDirs> { ProjectDirs::from("org", "rocfl", "rocfl") } pub fn s3_staging_path(config: &Config) -> Result<String> { match project_dirs() { Some(dirs) => { let mut staging = dirs.data_dir().join("s3").join("staging"); staging.push(s3_identifier(config)?); Ok(staging.to_string_lossy().to_string()) } None => Err(RocflError::General( "Failed to locate a suitable directory for staging objects. Please specify a directory using '--staging-root'".to_string())) } } fn s3_identifier(config: &Config) -> Result<String> { let mut name = config.bucket.clone().unwrap(); if let Some(root) = &config.root { name.push('/'); name.push_str(root); } let hash = DigestAlgorithm::Sha256.hash_hex(&mut name.as_bytes())?; Ok(hash.to_string()) } fn parse_config(config_file: impl AsRef<Path>) -> Result<HashMap<String, Config>> { let mut buffer = Vec::new(); fs::File::open(config_file.as_ref())?.read_to_end(&mut buffer)?; let config: HashMap<String, Config> = toml::from_slice(&buffer)?; Ok(config) } fn resolve_config(name: &Option<String>, mut config: HashMap<String, Config>) -> Config { let global_config = config.remove(GLOBAL); let repo_config = match name { None => None, Some(name) => config.remove(name), }; match (global_config, repo_config) { (Some(global), None) => global, (None, Some(repo)) => repo, (None, None) => Config::new(), (Some(global), Some(repo)) => { let mut resolved = Config::new(); resolved.author_name = resolve_field(global.author_name, repo.author_name); resolved.author_address = resolve_field(global.author_address, repo.author_address); resolved.root = resolve_field(global.root, repo.root); resolved.staging_root = resolve_field(global.staging_root, repo.staging_root); resolved.region = resolve_field(global.region, repo.region); resolved.bucket = resolve_field(global.bucket, repo.bucket); resolved.endpoint = resolve_field(global.endpoint, repo.endpoint); resolved.profile = resolve_field(global.profile, repo.profile); resolved } } } fn resolve_field(global_field: Option<String>, repo_field: Option<String>) -> Option<String> { if repo_field.is_some() { repo_field } else { global_field } }
use std::collections::HashMap; use std::fs; use std::io::Read; use std::path::{Path, PathBuf}; use directories::ProjectDirs; use serde::Deserialize; use crate::ocfl::{DigestAlgorithm, Result, RocflError}; const CONFIG_FILE: &str = "config.toml"; const GLOBAL: &str = "global"; #[derive(Deserialize, Debug)] #[serde(deny_unknown_fields)] pub struct Config { pub author_name: Option<String>, pub author_address: Option<String>, pub root: Option<String>, pub staging_root: Option<String>, pub region: Option<String>, pub bucket: Option<String>, pub endpoint: Option<String>, pub profile: Option<String>, } impl Config { pub fn new() -> Self { Self { author_name: None, author_address: None, root: None, staging_root: None, region: None, bucket: None, endpoint: None, profile: None, } } pub fn validate(&self) -> Result<()> { if self.bucket.is_some() { if self.region.is_none() { return Err(RocflError::InvalidConfiguration( "Region must be specified when using S3".to_string(), )); } } else if self.region.is_some() || self.endpoint.is_some() { return Err(RocflError::InvalidConfiguration( "Region and endpoint should not be set when not using S3. \ If you intended to use S3, then you must specify a bucket." .to_string(), )); } Ok(()) } } impl Default for Config { fn default() -> Self { Self::new() } } pub fn load_config(name: &Option<String>) -> Result<Config> { if let Some(config_file) = config_path() { if config_file.exists() { let config = parse_config(&config_file)?; return Ok(resolve_config(name, config)); } } Ok(Config::new()) } pub fn config_path() -> Option<PathBuf> { project_dirs().map(|dirs| dirs.config_dir().join(CONFIG_FILE)) } pub fn project_dirs() -> Option<ProjectDirs> { ProjectDirs::from("org", "rocfl", "rocfl") } pub fn s3_staging_path(config: &Config) -> Result<String> { match project_dirs() { Some(dirs) => { let mut staging = dirs.data_dir().join("s3").join("staging"); staging.push(s3_identifier(config)?); Ok(staging.to_string_lossy().to_string()) } None => Err(RocflError::General( "Failed to locate a suitable directory for staging objects. Please specify a directory using '--staging-root'".to_string())) } } fn s3_identifier(config: &Config) -> Result<String> { let mut name = config.bucket.clone().unwrap(); if let Some(root) = &config.root { name.push('/'); name.push_str(root); } let hash = DigestAlgorithm::Sha256.hash_hex(&mut name.as_bytes())?; Ok(hash.to_string()) } fn parse_config(config_file: impl AsRef<Path>) -> Result<HashMap<String, Config>> { let mut buffer = Vec::new(); fs::File::open(config_file.as_ref())?.read_to_end(&mut buffer)?; let config: HashMap<String, Config> = toml::from_slice(&buffer)?; Ok(config) } fn resolve_config(name: &Option<String>, mut config: HashMap<String, Config>) -> Config { let global_config = config.remove(GLOBAL); let repo_config = match name { None => None, Some(name) => config.remove(name), }; match (global_config, repo_config) { (Some(global), None) => global, (None, Some(repo)) => repo, (None, Non
fn resolve_field(global_field: Option<String>, repo_field: Option<String>) -> Option<String> { if repo_field.is_some() { repo_field } else { global_field } }
e) => Config::new(), (Some(global), Some(repo)) => { let mut resolved = Config::new(); resolved.author_name = resolve_field(global.author_name, repo.author_name); resolved.author_address = resolve_field(global.author_address, repo.author_address); resolved.root = resolve_field(global.root, repo.root); resolved.staging_root = resolve_field(global.staging_root, repo.staging_root); resolved.region = resolve_field(global.region, repo.region); resolved.bucket = resolve_field(global.bucket, repo.bucket); resolved.endpoint = resolve_field(global.endpoint, repo.endpoint); resolved.profile = resolve_field(global.profile, repo.profile); resolved } } }
function_block-function_prefixed
[ { "content": "fn default_values(mut config: Config) -> Result<Config> {\n\n if is_s3(&config) {\n\n if config.staging_root.is_none() {\n\n config.staging_root = Some(config::s3_staging_path(&config)?);\n\n }\n\n } else if config.root.is_none() {\n\n config.root = Some(\".\".to_string());\n\n }\n\n\n\n Ok(config)\n\n}\n\n\n", "file_path": "src/cmd/mod.rs", "rank": 1, "score": 283411.5315744112 }, { "content": "fn assert_storage_layout(s3_client: &S3Client, root: &str, layout_name: &str, config: &str) {\n\n assert_file_contains(\n\n s3_client,\n\n root,\n\n \"ocfl_layout.json\",\n\n &format!(\"\\\"extension\\\": \\\"{}\\\"\", layout_name),\n\n );\n\n\n\n let layout_spec = format!(\"{}.md\", layout_name);\n\n assert_file(s3_client, root, &layout_spec, &read_spec(&layout_spec));\n\n\n\n assert_file(\n\n s3_client,\n\n root,\n\n &format!(\"extensions/{}/config.json\", layout_name),\n\n config,\n\n );\n\n}\n\n\n", "file_path": "tests/s3-tests.rs", "rank": 2, "score": 282407.11824722 }, { "content": "fn default_repo(prefix: &str, staging: impl AsRef<Path>) -> OcflRepo {\n\n init_repo(\n\n prefix,\n\n staging,\n\n Some(\n\n StorageLayout::new(\n\n LayoutExtensionName::HashedNTupleLayout,\n\n Some(DEFAULT_LAYOUT.as_bytes()),\n\n )\n\n .unwrap(),\n\n ),\n\n )\n\n}\n\n\n", "file_path": "tests/s3-tests.rs", "rank": 3, "score": 276388.3673924161 }, { "content": "fn validate_repo_root(name: &str) -> PathBuf {\n\n let mut path = PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"));\n\n path.push(\"resources\");\n\n path.push(\"test\");\n\n path.push(\"validate\");\n\n path.push(\"custom\");\n\n path.push(\"repos\");\n\n path.push(name);\n\n path\n\n}\n", "file_path": "tests/cli-tests.rs", "rank": 5, "score": 263327.91053200816 }, { "content": "fn create_repo_root(name: &str) -> PathBuf {\n\n let mut path = PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"));\n\n path.push(\"resources\");\n\n path.push(\"test\");\n\n path.push(\"repos\");\n\n path.push(name);\n\n path\n\n}\n\n\n", "file_path": "tests/fs-tests.rs", "rank": 6, "score": 263327.91053200816 }, { "content": "#[cfg(feature = \"s3\")]\n\nfn create_s3_repo(config: &Config) -> Result<OcflRepo> {\n\n let region = resolve_region(config)?;\n\n\n\n OcflRepo::s3_repo(\n\n region,\n\n config.bucket.as_ref().unwrap(),\n\n config.root.as_deref(),\n\n config.staging_root.as_ref().unwrap(),\n\n config.profile.as_deref(),\n\n )\n\n}\n\n\n", "file_path": "src/cmd/mod.rs", "rank": 7, "score": 261117.9290338247 }, { "content": "#[cfg(feature = \"s3\")]\n\nfn resolve_region(config: &Config) -> Result<Region> {\n\n Ok(match config.endpoint.is_some() {\n\n true => Region::Custom {\n\n name: config.region.as_ref().unwrap().to_owned(),\n\n endpoint: config.endpoint.as_ref().unwrap().to_owned(),\n\n },\n\n false => config.region.as_ref().unwrap().parse()?,\n\n })\n\n}\n\n\n", "file_path": "src/cmd/mod.rs", "rank": 8, "score": 260947.84294797608 }, { "content": "pub fn init_repo(cmd: &InitCmd, args: &RocflArgs, config: &Config) -> Result<()> {\n\n if is_s3(config) {\n\n #[cfg(not(feature = \"s3\"))]\n\n return Err(RocflError::General(\n\n \"This binary was not compiled with S3 support.\".to_string(),\n\n ));\n\n\n\n #[cfg(feature = \"s3\")]\n\n let _ = init_s3_repo(\n\n config,\n\n create_layout(cmd.layout, cmd.config_file.as_deref())?,\n\n )?;\n\n } else {\n\n let _ = OcflRepo::init_fs_repo(\n\n config.root.as_ref().unwrap(),\n\n config.staging_root.as_ref().map(Path::new),\n\n create_layout(cmd.layout, cmd.config_file.as_deref())?,\n\n )?;\n\n }\n\n\n\n if !args.quiet {\n\n println(format!(\n\n \"Initialized OCFL repository with layout {}\",\n\n cmd.layout\n\n ));\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/cmd/mod.rs", "rank": 9, "score": 258227.6259868616 }, { "content": "/// If `object_id` is empty, then an `InvalidValue` error is returned. This does not enforce that\n\n/// the id is a URI.\n\npub fn validate_object_id(object_id: &str) -> Result<()> {\n\n if object_id.is_empty() {\n\n return Err(RocflError::InvalidValue(\n\n \"Object IDs may not be blank\".to_string(),\n\n ));\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/ocfl/validate/mod.rs", "rank": 10, "score": 255704.73523611232 }, { "content": "/// Executes a `rocfl` command\n\npub fn exec_command(args: &RocflArgs, config: Config) -> Result<()> {\n\n let config = resolve_config(args, config);\n\n let config = default_values(config)?;\n\n\n\n info!(\"Resolved configuration: {:?}\", config);\n\n\n\n config.validate()?;\n\n\n\n match &args.command {\n\n Command::Init(command) => {\n\n // init cmd needs to be handled differently because the repo does not exist yet\n\n init_repo(command, args, &config)\n\n }\n\n Command::Config(_command) => edit_config()\n\n .map_err(|e| RocflError::General(format!(\"Failed to edit config file: {}\", e))),\n\n _ => {\n\n let repo = Arc::new(create_repo(&config)?);\n\n let terminate = Arc::new(AtomicBool::new(false));\n\n\n\n let repo_ref = repo.clone();\n", "file_path": "src/cmd/mod.rs", "rank": 11, "score": 253301.39997573127 }, { "content": "fn copy_existing_repo(name: &str, root: &TempDir) {\n\n let path = create_repo_root(name);\n\n\n\n let options = CopyOptions::new();\n\n\n\n fs_extra::dir::copy(&path, root.path(), &options).unwrap();\n\n}\n\n\n", "file_path": "tests/fs-tests.rs", "rank": 12, "score": 249367.7980776208 }, { "content": "fn assert_layout_extension(root: &TempDir, layout_name: &str, config: &str) {\n\n root.child(\"ocfl_layout.json\")\n\n .assert(predicates::path::is_file())\n\n .assert(predicates::str::contains(format!(\n\n \"\\\"extension\\\": \\\"{}\\\"\",\n\n layout_name\n\n )));\n\n\n\n let layout_spec = format!(\"{}.md\", layout_name);\n\n root.child(&layout_spec)\n\n .assert(predicates::path::is_file())\n\n .assert(read_spec(&layout_spec));\n\n\n\n let extensions = root.child(\"extensions\");\n\n extensions.assert(predicates::path::is_dir());\n\n\n\n let layout_dir = extensions.child(layout_name);\n\n layout_dir.assert(predicates::path::is_dir());\n\n layout_dir\n\n .child(\"config.json\")\n\n .assert(predicates::path::is_file())\n\n .assert(config);\n\n}\n\n\n", "file_path": "tests/fs-tests.rs", "rank": 14, "score": 244942.85860128212 }, { "content": "fn create_rusoto_client(region: Region, profile: Option<&str>) -> RusotoS3Client {\n\n match profile {\n\n Some(profile) => {\n\n // Client setup code copied from Rusoto -- they don't make it easy to set the profile\n\n let credentials_provider =\n\n AutoRefreshingProvider::new(ChainProvider::with_profile_provider(\n\n ProfileProvider::with_default_credentials(profile)\n\n .expect(\"failed to create profile provider\"),\n\n ))\n\n .expect(\"failed to create credentials provider\");\n\n let dispatcher = HttpClient::new().expect(\"failed to create request dispatcher\");\n\n let client = Client::new_with(credentials_provider, dispatcher);\n\n RusotoS3Client::new_with_client(client, region)\n\n }\n\n None => RusotoS3Client::new(region),\n\n }\n\n}\n\n\n", "file_path": "src/ocfl/store/s3.rs", "rank": 15, "score": 233896.95147983322 }, { "content": "fn default_repo(root: impl AsRef<Path>) -> OcflRepo {\n\n OcflRepo::init_fs_repo(\n\n root,\n\n None,\n\n Some(StorageLayout::new(LayoutExtensionName::HashedNTupleLayout, None).unwrap()),\n\n )\n\n .unwrap()\n\n}\n\n\n", "file_path": "tests/fs-tests.rs", "rank": 16, "score": 233674.99551990448 }, { "content": "fn new_repo(root: impl AsRef<Path>) -> OcflRepo {\n\n OcflRepo::fs_repo(root, None).unwrap()\n\n}\n\n\n", "file_path": "tests/validate-tests.rs", "rank": 17, "score": 233646.52286568878 }, { "content": "fn official_error_test(name: &str) -> ObjectValidationResult {\n\n let repo = new_repo(official_error_root());\n\n repo.validate_object_at(name, true).unwrap()\n\n}\n\n\n", "file_path": "tests/validate-tests.rs", "rank": 18, "score": 232946.46921466803 }, { "content": "fn official_warn_test(name: &str) -> ObjectValidationResult {\n\n let repo = new_repo(official_warn_root());\n\n repo.validate_object_at(name, true).unwrap()\n\n}\n\n\n", "file_path": "tests/validate-tests.rs", "rank": 19, "score": 232946.46921466803 }, { "content": "fn official_valid_test(name: &str) -> ObjectValidationResult {\n\n let repo = new_repo(official_valid_root());\n\n repo.validate_object_at(name, true).unwrap()\n\n}\n\n\n", "file_path": "tests/validate-tests.rs", "rank": 20, "score": 232946.46921466803 }, { "content": "fn create_repo(config: &Config) -> Result<OcflRepo> {\n\n if is_s3(config) {\n\n #[cfg(not(feature = \"s3\"))]\n\n return Err(RocflError::General(\n\n \"This binary was not compiled with S3 support.\".to_string(),\n\n ));\n\n\n\n #[cfg(feature = \"s3\")]\n\n create_s3_repo(config)\n\n } else {\n\n OcflRepo::fs_repo(\n\n config.root.as_ref().unwrap(),\n\n config.staging_root.as_ref().map(Path::new),\n\n )\n\n }\n\n}\n\n\n", "file_path": "src/cmd/mod.rs", "rank": 21, "score": 232871.08014795612 }, { "content": "fn init_new_repo(root: impl AsRef<Path>, layout: Option<&StorageLayout>) -> Result<()> {\n\n let root = root.as_ref().to_path_buf();\n\n\n\n if root.exists() {\n\n if !root.is_dir() {\n\n return Err(RocflError::IllegalState(format!(\n\n \"Cannot create new repository. Storage root {} is not a directory\",\n\n canonical_str(root)\n\n )));\n\n }\n\n\n\n if fs::read_dir(&root)?.next().is_some() {\n\n return Err(RocflError::IllegalState(format!(\n\n \"Cannot create new repository. Storage root {} must be empty\",\n\n canonical_str(root)\n\n )));\n\n }\n\n }\n\n\n\n info!(\"Initializing OCFL storage root at {}\", canonical_str(&root));\n", "file_path": "src/ocfl/store/fs.rs", "rank": 22, "score": 231588.3930326305 }, { "content": "#[test]\n\n#[should_panic(expected = \"must be empty\")]\n\nfn fail_new_repo_creation_when_non_empty_root() {\n\n let root = TempDir::new().unwrap();\n\n\n\n root.child(\"file\").write_str(\"contents\").unwrap();\n\n\n\n let _repo = OcflRepo::init_fs_repo(\n\n root.path(),\n\n None,\n\n Some(StorageLayout::new(LayoutExtensionName::HashedNTupleLayout, None).unwrap()),\n\n )\n\n .unwrap();\n\n}\n\n\n", "file_path": "tests/fs-tests.rs", "rank": 25, "score": 231379.92921277176 }, { "content": "fn repo_test_path(name: &str) -> PathBuf {\n\n let mut path = validate_repo_root();\n\n path.push(\"custom\");\n\n path.push(\"repos\");\n\n path.push(name);\n\n path\n\n}\n\n\n", "file_path": "tests/validate-tests.rs", "rank": 26, "score": 229646.4112218346 }, { "content": "#[test]\n\nfn purge_should_remove_object_from_repo_and_staging() -> Result<()> {\n\n let root = TempDir::new().unwrap();\n\n let temp = TempDir::new().unwrap();\n\n\n\n let repo = default_repo(root.path());\n\n\n\n let object_id = \"purge me2\";\n\n\n\n create_example_object(object_id, &repo, &temp);\n\n\n\n repo.move_files_external(\n\n object_id,\n\n &vec![create_file(&temp, \"blah\", \"blah\").path()],\n\n \"blah\",\n\n )?;\n\n\n\n repo.purge_object(object_id)?;\n\n\n\n assert_obj_not_exists(&repo, object_id);\n\n assert_staged_obj_not_exists(&repo, object_id);\n\n\n\n validate_repo(&repo);\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/fs-tests.rs", "rank": 27, "score": 229430.1333143084 }, { "content": "fn assert_staged_obj_not_exists(repo: &OcflRepo, object_id: &str) {\n\n match repo.get_staged_object(object_id) {\n\n Err(RocflError::NotFound(_)) => (),\n\n _ => panic!(\"Expected staged object '{}' to not be found\", object_id),\n\n }\n\n}\n\n\n", "file_path": "tests/fs-tests.rs", "rank": 28, "score": 228974.13519533892 }, { "content": "#[cfg(feature = \"s3\")]\n\nfn init_s3_repo(config: &Config, layout: Option<StorageLayout>) -> Result<OcflRepo> {\n\n let region = resolve_region(config)?;\n\n\n\n OcflRepo::init_s3_repo(\n\n region,\n\n config.bucket.as_ref().unwrap(),\n\n config.root.as_deref(),\n\n config.staging_root.as_ref().unwrap(),\n\n layout,\n\n config.profile.as_deref(),\n\n )\n\n}\n\n\n", "file_path": "src/cmd/mod.rs", "rank": 29, "score": 228498.3363536025 }, { "content": "fn resolve_config(args: &RocflArgs, mut config: Config) -> Config {\n\n if args.root.is_some() {\n\n config.root = args.root.clone();\n\n }\n\n if args.staging_root.is_some() {\n\n config.staging_root = args.staging_root.clone();\n\n }\n\n if args.bucket.is_some() {\n\n config.bucket = args.bucket.clone();\n\n }\n\n if args.region.is_some() {\n\n config.region = args.region.clone();\n\n }\n\n if args.endpoint.is_some() {\n\n config.endpoint = args.endpoint.clone();\n\n }\n\n if args.profile.is_some() {\n\n config.profile = args.profile.clone()\n\n }\n\n\n", "file_path": "src/cmd/mod.rs", "rank": 30, "score": 220827.99386428058 }, { "content": "pub fn no_warnings(result: &ObjectValidationResult) {\n\n assert!(\n\n result.warnings().is_empty(),\n\n \"Expected no warnings; found: {:?}\",\n\n result.warnings()\n\n )\n\n}\n\n\n", "file_path": "tests/common/mod.rs", "rank": 31, "score": 220457.7948561284 }, { "content": "pub fn no_errors(result: &ObjectValidationResult) {\n\n assert!(\n\n result.errors().is_empty(),\n\n \"Expected no errors; found: {:?}\",\n\n result.errors()\n\n )\n\n}\n\n\n", "file_path": "tests/common/mod.rs", "rank": 32, "score": 220457.7948561284 }, { "content": "#[test]\n\nfn create_new_hash_id_repo_empty_dir() -> Result<()> {\n\n let root = TempDir::new().unwrap();\n\n let temp = TempDir::new().unwrap();\n\n\n\n let repo = OcflRepo::init_fs_repo(\n\n root.path(),\n\n None,\n\n Some(StorageLayout::new(\n\n LayoutExtensionName::HashedNTupleObjectIdLayout,\n\n None,\n\n )?),\n\n )?;\n\n\n\n assert_storage_root(&root);\n\n assert_layout_extension(\n\n &root,\n\n \"0003-hash-and-id-n-tuple-storage-layout\",\n\n r#\"{\n\n \"extensionName\": \"0003-hash-and-id-n-tuple-storage-layout\",\n\n \"digestAlgorithm\": \"sha256\",\n", "file_path": "tests/fs-tests.rs", "rank": 33, "score": 218601.36750143618 }, { "content": "fn init_repo(prefix: &str, staging: impl AsRef<Path>, layout: Option<StorageLayout>) -> OcflRepo {\n\n OcflRepo::init_s3_repo(REGION, &bucket(), Some(prefix), staging, layout, None).unwrap()\n\n}\n\n\n", "file_path": "tests/s3-tests.rs", "rank": 34, "score": 217077.93031723518 }, { "content": "fn assert_file(s3_client: &S3Client, root: &str, path: &str, content: &str) {\n\n let key = format!(\"{}/{}\", root, path);\n\n let actual_content = get_content_with_key(s3_client, &key);\n\n assert_eq!(content, actual_content);\n\n}\n\n\n", "file_path": "tests/s3-tests.rs", "rank": 35, "score": 216713.72271682476 }, { "content": "fn delete_all(s3_client: &S3Client, root: &str) {\n\n tokio_test::block_on(async move {\n\n let list = s3_client\n\n .list_objects_v2(ListObjectsV2Request {\n\n bucket: bucket(),\n\n prefix: Some(format!(\"{}/\", root)),\n\n ..Default::default()\n\n })\n\n .await\n\n .unwrap();\n\n\n\n for object in list.contents.unwrap() {\n\n s3_client\n\n .delete_object(DeleteObjectRequest {\n\n bucket: bucket(),\n\n key: object.key.unwrap(),\n\n ..Default::default()\n\n })\n\n .await\n\n .unwrap();\n\n }\n\n });\n\n}\n\n\n", "file_path": "tests/s3-tests.rs", "rank": 36, "score": 216696.39565524005 }, { "content": "fn assert_file_exists(s3_client: &S3Client, root: &str, path: &str) {\n\n let key = format!(\"{}/{}\", root, path);\n\n let _ = tokio_test::block_on(s3_client.head_object(HeadObjectRequest {\n\n bucket: bucket(),\n\n key: key.clone(),\n\n ..Default::default()\n\n }))\n\n .expect(&format!(\"Expected {} to exist\", key));\n\n}\n\n\n", "file_path": "tests/s3-tests.rs", "rank": 37, "score": 214546.91858610002 }, { "content": "fn read_spec(name: &str) -> String {\n\n let mut path = PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"));\n\n path.push(\"resources\");\n\n path.push(\"main\");\n\n path.push(\"specs\");\n\n path.push(name);\n\n fs::read_to_string(path).unwrap()\n\n}\n", "file_path": "tests/s3-tests.rs", "rank": 38, "score": 214105.8956377837 }, { "content": "fn assert_file_contains(s3_client: &S3Client, root: &str, path: &str, content: &str) {\n\n let key = format!(\"{}/{}\", root, path);\n\n let actual_content = get_content_with_key(s3_client, &key);\n\n assert!(\n\n actual_content.contains(content),\n\n \"Expected {} to contain {}. Found: {}\",\n\n key,\n\n content,\n\n actual_content\n\n );\n\n}\n\n\n", "file_path": "tests/s3-tests.rs", "rank": 39, "score": 213668.98370446474 }, { "content": "/// Runs the test if the environment is configured to run S3 tests, and removes all resources\n\n/// created during the test run, regardless of the test's outcome.\n\nfn run_s3_test(name: &str, test: impl FnOnce(S3Client, String, TempDir, TempDir) + UnwindSafe) {\n\n // let _ = env_logger::builder().is_test(true).filter_level(LevelFilter::Info).try_init();\n\n\n\n let staging = TempDir::new().unwrap();\n\n let temp = TempDir::new().unwrap();\n\n let prefix = s3_prefix();\n\n\n\n let result = panic::catch_unwind(|| test(S3Client::new(REGION), prefix.clone(), staging, temp));\n\n\n\n if let Err(e) = panic::catch_unwind(|| delete_all(&S3Client::new(REGION), &prefix)) {\n\n let s = e\n\n .downcast()\n\n .unwrap_or_else(|e| Box::new(format!(\"{:?}\", e)));\n\n eprintln!(\"Failed to cleanup test {}: {}\", name, s);\n\n }\n\n\n\n if let Err(e) = result {\n\n let s = e\n\n .downcast()\n\n .unwrap_or_else(|e| Box::new(format!(\"{:?}\", e)));\n\n panic!(\"Test {} failed: {}\", name, s);\n\n }\n\n}\n\n\n", "file_path": "tests/s3-tests.rs", "rank": 40, "score": 213580.08805915888 }, { "content": "/// Constructs a `RocflError::NotFound` error\n\npub fn not_found(object_id: &str, version_num: Option<VersionNum>) -> RocflError {\n\n match version_num {\n\n Some(version) => RocflError::NotFound(format!(\"Object {} version {}\", object_id, version)),\n\n None => RocflError::NotFound(format!(\"Object {}\", object_id)),\n\n }\n\n}\n\n\n", "file_path": "src/ocfl/error.rs", "rank": 41, "score": 212295.8401498741 }, { "content": "fn write_layout_config(root: impl AsRef<Path>, layout: &StorageLayout) -> Result<()> {\n\n let extension_name = layout.extension_name().to_string();\n\n\n\n let ocfl_layout = OcflLayout {\n\n extension: layout.extension_name(),\n\n description: format!(\"See specification document {}.md\", extension_name),\n\n };\n\n\n\n serde_json::to_writer_pretty(\n\n File::create(paths::ocfl_layout_path(root.as_ref()))?,\n\n &ocfl_layout,\n\n )?;\n\n\n\n let mut layout_ext_dir = paths::extensions_path(root.as_ref());\n\n layout_ext_dir.push(&extension_name);\n\n fs::create_dir_all(&layout_ext_dir)?;\n\n\n\n File::create(layout_ext_dir.join(EXTENSIONS_CONFIG_FILE))?.write_all(&layout.serialize()?)?;\n\n\n\n let extension_spec = match layout.extension_name() {\n", "file_path": "src/ocfl/store/fs.rs", "rank": 42, "score": 212277.75553087651 }, { "content": "/// If `content_dir` contains `.`, `..`, or `/`, then an `InvalidValue` error is returned.\n\npub fn validate_content_dir(content_dir: &str) -> Result<()> {\n\n if content_dir.eq(\".\") || content_dir.eq(\"..\") || content_dir.contains('/') {\n\n return Err(RocflError::InvalidValue(format!(\n\n \"The content directory cannot equal '.' or '..' and cannot contain a '/'. Found: {}\",\n\n content_dir\n\n )));\n\n }\n\n Ok(())\n\n}\n\n\n\n/// OCFL validation codes for errors: https://ocfl.io/1.0/spec/validation-codes.html\n\n#[allow(dead_code)]\n\n#[derive(Debug, EnumDisplay, EnumString, Copy, Clone, Eq, PartialEq)]\n\npub enum ErrorCode {\n\n E001,\n\n E002,\n\n E003,\n\n E004,\n\n E005,\n\n E006,\n", "file_path": "src/ocfl/validate/mod.rs", "rank": 44, "score": 211865.85848488176 }, { "content": "fn commit(object_id: &str, repo: &OcflRepo) {\n\n repo.commit(object_id, CommitMeta::new(), None, false)\n\n .unwrap();\n\n}\n\n\n", "file_path": "tests/fs-tests.rs", "rank": 45, "score": 210064.0129351823 }, { "content": "#[test]\n\n#[should_panic(expected = \"Cannot create new repository. Storage root must be empty\")]\n\nfn fail_create_new_repo_when_repo_already_exists() {\n\n panic_or_run_s3_test(\n\n \"fail_create_new_repo_when_repo_already_exists\",\n\n \"Cannot create new repository. Storage root must be empty\",\n\n |_s3_client: S3Client, prefix: String, staging: TempDir, _temp: TempDir| {\n\n let _ = default_repo(&prefix, staging.path());\n\n let _ = default_repo(&prefix, staging.path());\n\n },\n\n );\n\n}\n\n\n", "file_path": "tests/s3-tests.rs", "rank": 46, "score": 209445.19828216964 }, { "content": "#[test]\n\n#[should_panic(expected = \"Cannot create object s3-object because it already exists\")]\n\nfn fail_create_new_object_when_already_exists() {\n\n panic_or_run_s3_test(\n\n \"fail_create_new_object_when_already_exists\",\n\n \"Cannot create object s3-object because it already exists\",\n\n |_s3_client: S3Client, prefix: String, staging: TempDir, temp: TempDir| {\n\n let repo = default_repo(&prefix, staging.path());\n\n let object_id = \"s3-object\";\n\n\n\n repo.create_object(object_id, DigestAlgorithm::Sha256, \"content\", 0)\n\n .unwrap();\n\n repo.copy_files_external(\n\n object_id,\n\n &vec![create_file(&temp, \"test.txt\", \"testing\").path()],\n\n \"/\",\n\n false,\n\n )\n\n .unwrap();\n\n repo.commit(object_id, CommitMeta::new(), None, false)\n\n .unwrap();\n\n\n\n repo.create_object(object_id, DigestAlgorithm::Sha256, \"content\", 0)\n\n .unwrap();\n\n },\n\n );\n\n}\n\n\n", "file_path": "tests/s3-tests.rs", "rank": 47, "score": 203281.10448958183 }, { "content": "fn assert_obj_not_exists(repo: &OcflRepo, object_id: &str) {\n\n match repo.get_object(object_id, VersionRef::Head) {\n\n Err(RocflError::NotFound(_)) => (),\n\n _ => panic!(\"Expected object '{}' to not be found\", object_id),\n\n }\n\n}\n\n\n", "file_path": "tests/fs-tests.rs", "rank": 48, "score": 201960.12398949778 }, { "content": "#[test]\n\nfn copy_files_into_new_object() -> Result<()> {\n\n let root = TempDir::new().unwrap();\n\n let temp = TempDir::new().unwrap();\n\n\n\n let repo = default_repo(root.path());\n\n\n\n let object_id = \"foobar\";\n\n\n\n assert_staged_obj_count(&repo, 0);\n\n repo.create_object(object_id, DigestAlgorithm::Sha512, \"content\", 0)?;\n\n assert_staged_obj_count(&repo, 1);\n\n\n\n let staged: Vec<ObjectVersionDetails> = repo.list_staged_objects(None)?.flatten().collect();\n\n assert_eq!(object_id, staged.first().unwrap().id);\n\n\n\n create_file(&temp, \"test.txt\", \"testing\");\n\n repo.copy_files_external(\n\n object_id,\n\n &vec![temp.child(\"test.txt\").path()],\n\n \"test.txt\",\n", "file_path": "tests/fs-tests.rs", "rank": 49, "score": 199900.318006039 }, { "content": "#[test]\n\nfn move_files_into_new_object() -> Result<()> {\n\n let root = TempDir::new().unwrap();\n\n let temp = TempDir::new().unwrap();\n\n\n\n let repo = default_repo(root.path());\n\n\n\n let object_id = \"move files\";\n\n\n\n repo.create_object(object_id, DigestAlgorithm::Sha512, \"content\", 0)?;\n\n\n\n create_file(&temp, \"test.txt\", \"testing\");\n\n create_dirs(&temp, \"nested/dir\");\n\n create_file(&temp, \"nested/1.txt\", \"File 1\");\n\n create_file(&temp, \"nested/dir/2.txt\", \"File 2\");\n\n create_file(&temp, \"nested/dir/3.txt\", \"File 3\");\n\n\n\n repo.move_files_external(\n\n object_id,\n\n &vec![\n\n temp.child(\"test.txt\").path(),\n", "file_path": "tests/fs-tests.rs", "rank": 50, "score": 199900.31800603896 }, { "content": "#[test]\n\nfn commit_should_remove_staged_object() -> Result<()> {\n\n let root = TempDir::new().unwrap();\n\n let temp = TempDir::new().unwrap();\n\n\n\n let repo = default_repo(root.path());\n\n\n\n let object_id = \"commit meta\";\n\n\n\n repo.create_object(object_id, DigestAlgorithm::Sha256, \"content\", 0)?;\n\n\n\n repo.move_files_external(\n\n object_id,\n\n &vec![create_file(&temp, \"blah\", \"blah\").path()],\n\n \"blah\",\n\n )?;\n\n\n\n commit(object_id, &repo);\n\n\n\n let _obj = repo.get_object(object_id, VersionRef::Head)?;\n\n\n\n assert_staged_obj_not_exists(&repo, object_id);\n\n\n\n validate_repo(&repo);\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/fs-tests.rs", "rank": 51, "score": 199889.79540873485 }, { "content": "#[test]\n\nfn list_repo_with_invalid_objects() -> Result<()> {\n\n let repo_root = create_repo_root(\"invalid\");\n\n let repo = OcflRepo::fs_repo(&repo_root, None)?;\n\n\n\n let object_root = repo_root\n\n .join(\"925\")\n\n .join(\"0b9\")\n\n .join(\"912\")\n\n .join(\"9250b9912ee91d6b46e23299459ecd6eb8154451d62558a3a0a708a77926ad04\");\n\n\n\n let iter = repo.list_objects(None)?;\n\n\n\n for object in iter {\n\n if let Ok(object) = object {\n\n assert_eq!(\n\n object,\n\n ObjectVersionDetails {\n\n id: \"o2\".to_string(),\n\n object_root: object_root.display().to_string(),\n\n digest_algorithm: DigestAlgorithm::Sha512,\n\n version_details: o2_v3_details()\n\n }\n\n );\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/fs-tests.rs", "rank": 52, "score": 199349.44231862767 }, { "content": "#[test]\n\nfn purge_should_remove_object_from_repo() -> Result<()> {\n\n let root = TempDir::new().unwrap();\n\n let temp = TempDir::new().unwrap();\n\n\n\n let repo = default_repo(root.path());\n\n\n\n let object_id = \"purge me\";\n\n\n\n create_example_object(object_id, &repo, &temp);\n\n\n\n repo.purge_object(object_id)?;\n\n\n\n assert_obj_not_exists(&repo, object_id);\n\n\n\n validate_repo(&repo);\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/fs-tests.rs", "rank": 53, "score": 199349.44231862767 }, { "content": "/// Walks up the directory hierarchy deleting directories until it finds a non-empty directory.\n\npub fn clean_dirs_up(start_dir: impl AsRef<Path>) -> Result<()> {\n\n let mut current = start_dir.as_ref();\n\n\n\n while dir_is_empty(current)? {\n\n fs::remove_dir(current)?;\n\n current = current.parent().unwrap();\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "src/ocfl/util.rs", "rank": 54, "score": 198900.58154427836 }, { "content": "/// Walks down the directory hierarchy deleting all non-empty directories\n\npub fn clean_dirs_down(start_dir: impl AsRef<Path>) -> Result<()> {\n\n let start_dir = start_dir.as_ref();\n\n\n\n for entry in WalkDir::new(start_dir).contents_first(true) {\n\n let path = entry?;\n\n if path.file_type().is_dir() && dir_is_empty(path.path())? {\n\n fs::remove_dir(path.path())?;\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/ocfl/util.rs", "rank": 55, "score": 198900.41761850094 }, { "content": "#[test]\n\nfn get_staged_object_file_when_exists_in_staged_version() -> Result<()> {\n\n let root = TempDir::new().unwrap();\n\n let temp = TempDir::new().unwrap();\n\n\n\n let repo = default_repo(root.path());\n\n\n\n let object_id = \"get file\";\n\n\n\n create_example_object(object_id, &repo, &temp);\n\n\n\n repo.move_files_external(\n\n object_id,\n\n &vec![create_file(&temp, \"blah\", \"blah\").path()],\n\n \"blah\",\n\n )?;\n\n\n\n let mut out: Vec<u8> = Vec::new();\n\n\n\n repo.get_staged_object_file(object_id, &lpath(\"blah\"), &mut out)?;\n\n\n\n assert_eq!(\"blah\", String::from_utf8(out).unwrap());\n\n\n\n validate_repo(&repo);\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/fs-tests.rs", "rank": 56, "score": 198650.49722790415 }, { "content": "fn rocfl(path: impl AsRef<Path>, command: &str) -> Command {\n\n let mut rocfl = Command::cargo_bin(\"rocfl\").unwrap();\n\n rocfl\n\n .arg(\"-S\")\n\n .arg(\"-r\")\n\n .arg(path.as_ref().to_string_lossy().as_ref())\n\n .arg(command);\n\n rocfl\n\n}\n\n\n", "file_path": "tests/cli-tests.rs", "rank": 57, "score": 198354.8925007808 }, { "content": "pub fn error_count(expected: usize, result: &ObjectValidationResult) {\n\n assert_eq!(\n\n expected,\n\n result.errors().len(),\n\n \"Expected {} errors; found {}: {:?}\",\n\n expected,\n\n result.errors().len(),\n\n result.errors()\n\n )\n\n}\n\n\n", "file_path": "tests/common/mod.rs", "rank": 58, "score": 196195.9274396057 }, { "content": "pub fn warning_count(expected: usize, result: &ObjectValidationResult) {\n\n assert_eq!(\n\n expected,\n\n result.warnings().len(),\n\n \"Expected {} warnings; found {}: {:?}\",\n\n expected,\n\n result.warnings().len(),\n\n result.warnings()\n\n )\n\n}\n\n\n", "file_path": "tests/common/mod.rs", "rank": 59, "score": 196195.9274396057 }, { "content": "#[test]\n\nfn get_object_when_exists_using_layout() -> Result<()> {\n\n let repo_root = create_repo_root(\"multiple-objects-with-layout\");\n\n let repo = OcflRepo::fs_repo(&repo_root, None)?;\n\n\n\n let object = repo.get_object(\"o2\", VersionRef::Head)?;\n\n\n\n let object_root = repo_root\n\n .join(\"925\")\n\n .join(\"0b9\")\n\n .join(\"912\")\n\n .join(\"9250b9912ee91d6b46e23299459ecd6eb8154451d62558a3a0a708a77926ad04\");\n\n\n\n assert_eq!(\n\n object,\n\n ObjectVersion {\n\n id: \"o2\".to_string(),\n\n object_root: object_root.to_string_lossy().to_string(),\n\n digest_algorithm: DigestAlgorithm::Sha512,\n\n version_details: o2_v3_details(),\n\n state: hashmap! {\n", "file_path": "tests/fs-tests.rs", "rank": 60, "score": 195085.18733471652 }, { "content": "#[test]\n\nfn create_new_repo_empty_dir() -> Result<()> {\n\n let root = TempDir::new().unwrap();\n\n let temp = TempDir::new().unwrap();\n\n\n\n let repo = OcflRepo::init_fs_repo(\n\n root.path(),\n\n None,\n\n Some(StorageLayout::new(\n\n LayoutExtensionName::HashedNTupleLayout,\n\n None,\n\n )?),\n\n )?;\n\n\n\n assert_storage_root(&root);\n\n assert_layout_extension(\n\n &root,\n\n \"0004-hashed-n-tuple-storage-layout\",\n\n r#\"{\n\n \"extensionName\": \"0004-hashed-n-tuple-storage-layout\",\n\n \"digestAlgorithm\": \"sha256\",\n", "file_path": "tests/fs-tests.rs", "rank": 61, "score": 194740.86879585776 }, { "content": "/// # v1\n\n///\n\n/// - a/file1.txt\n\n/// - a/b/file2.txt\n\n/// - a/b/file3.txt\n\n/// - a/b/c/file4.txt\n\n/// - a/d/e/file5.txt\n\n/// - a/f/file6.txt\n\n///\n\n/// # v2\n\n///\n\n/// - a/file1.txt\n\n/// - a/b/file2.txt\n\n/// - a/d/e/file5.txt\n\n/// - a/f/file6.txt\n\n///\n\n///# v3\n\n///\n\n/// - file3.txt\n\n/// - a/file1.txt\n\n/// - a/b/file2.txt\n\n/// - a/d/e/file5.txt\n\n/// - a/f/file6.txt\n\n/// - something/file1.txt\n\n/// - something/new.txt\n\n///\n\n/// # v4\n\n///\n\n/// - file3.txt\n\n/// - a/file1.txt\n\n/// - a/file5.txt\n\n/// - a/b/file2.txt\n\n/// - a/f/file6.txt (updated)\n\n/// - something/file1.txt\n\n/// - something/new.txt\n\nfn create_example_object(object_id: &str, repo: &OcflRepo, temp: &TempDir) {\n\n repo.create_object(object_id, DigestAlgorithm::Sha256, \"content\", 0)\n\n .unwrap();\n\n\n\n create_dirs(temp, \"a/b/c\");\n\n create_dirs(temp, \"a/d/e\");\n\n create_dirs(temp, \"a/f\");\n\n\n\n create_file(temp, \"a/file1.txt\", \"File One\");\n\n create_file(temp, \"a/b/file2.txt\", \"File Two\");\n\n create_file(temp, \"a/b/file3.txt\", \"File Three\");\n\n create_file(temp, \"a/b/c/file4.txt\", \"File Four\");\n\n create_file(temp, \"a/d/e/file5.txt\", \"File Five\");\n\n create_file(temp, \"a/f/file6.txt\", \"File Six\");\n\n\n\n repo.move_files_external(object_id, &vec![temp.child(\"a\").path()], \"/\")\n\n .unwrap();\n\n\n\n commit(object_id, &repo);\n\n\n", "file_path": "tests/fs-tests.rs", "rank": 62, "score": 193834.3960114414 }, { "content": "fn create_simple_object(object_id: &str, repo: &OcflRepo, temp: &TempDir) {\n\n repo.create_object(object_id, DigestAlgorithm::Sha512, \"content\", 0)\n\n .unwrap();\n\n\n\n temp.child(\"test.txt\").write_str(\"testing\").unwrap();\n\n repo.copy_files_external(\n\n object_id,\n\n &vec![temp.child(\"test.txt\").path()],\n\n \"test.txt\",\n\n false,\n\n )\n\n .unwrap();\n\n\n\n commit(object_id, &repo);\n\n}\n\n\n", "file_path": "tests/fs-tests.rs", "rank": 63, "score": 193830.38380080965 }, { "content": "/// Returns true if the specified directory does not contain any files\n\npub fn dir_is_empty(dir: impl AsRef<Path>) -> Result<bool> {\n\n Ok(fs::read_dir(dir)?.next().is_none())\n\n}\n\n\n", "file_path": "src/ocfl/util.rs", "rank": 64, "score": 193659.70140991977 }, { "content": "fn init_new_repo(s3_client: &S3Client, layout: Option<&StorageLayout>) -> Result<()> {\n\n if !s3_client.list_dir(\"\")?.is_empty() {\n\n return Err(RocflError::IllegalState(\n\n \"Cannot create new repository. Storage root must be empty\".to_string(),\n\n ));\n\n }\n\n\n\n info!(\n\n \"Initializing OCFL storage root in bucket {} under prefix {}\",\n\n s3_client.bucket, s3_client.prefix\n\n );\n\n\n\n s3_client.put_object_bytes(\n\n REPO_NAMASTE_FILE,\n\n Bytes::from(ROOT_NAMASTE_CONTENT.as_bytes()),\n\n Some(TYPE_PLAIN),\n\n )?;\n\n\n\n s3_client.put_object_bytes(\n\n OCFL_SPEC_FILE,\n", "file_path": "src/ocfl/store/s3.rs", "rank": 65, "score": 193504.6692003283 }, { "content": "pub fn has_warnings(result: &ObjectValidationResult, expected_warnings: &[ValidationWarning]) {\n\n for expected in expected_warnings {\n\n assert!(\n\n result.warnings().contains(expected),\n\n \"Expected warnings to contain {:?}. Found: {:?}\",\n\n expected,\n\n result.warnings()\n\n );\n\n }\n\n assert_eq!(\n\n expected_warnings.len(),\n\n result.warnings().len(),\n\n \"Expected {} warnings; found {}: {:?}\",\n\n expected_warnings.len(),\n\n result.warnings().len(),\n\n result.warnings()\n\n )\n\n}\n\n\n", "file_path": "tests/common/mod.rs", "rank": 66, "score": 192478.014905773 }, { "content": "pub fn has_errors(result: &ObjectValidationResult, expected_errors: &[ValidationError]) {\n\n for expected in expected_errors {\n\n assert!(\n\n result.errors().contains(expected),\n\n \"Expected errors to contain {:?}. Found: {:?}\",\n\n expected,\n\n result.errors()\n\n );\n\n }\n\n assert_eq!(\n\n expected_errors.len(),\n\n result.errors().len(),\n\n \"Expected {} errors; found {}: {:?}\",\n\n expected_errors.len(),\n\n result.errors().len(),\n\n result.errors()\n\n )\n\n}\n\n\n", "file_path": "tests/common/mod.rs", "rank": 67, "score": 192478.014905773 }, { "content": "/// Trims all lead and trailing slashes from the path\n\npub fn trim_slashes(path: &str) -> &str {\n\n trim_trailing_slashes(trim_leading_slashes(path))\n\n}\n", "file_path": "src/ocfl/util.rs", "rank": 68, "score": 190767.54048391624 }, { "content": "#[test]\n\nfn create_new_flat_repo_empty_dir() -> Result<()> {\n\n let root = TempDir::new().unwrap();\n\n let temp = TempDir::new().unwrap();\n\n\n\n let repo = OcflRepo::init_fs_repo(\n\n root.path(),\n\n None,\n\n Some(StorageLayout::new(\n\n LayoutExtensionName::FlatDirectLayout,\n\n None,\n\n )?),\n\n )?;\n\n\n\n assert_storage_root(&root);\n\n assert_layout_extension(\n\n &root,\n\n \"0002-flat-direct-storage-layout\",\n\n r#\"{\n\n \"extensionName\": \"0002-flat-direct-storage-layout\"\n\n}\"#,\n", "file_path": "tests/fs-tests.rs", "rank": 69, "score": 190218.3498617914 }, { "content": "/// Trims all trailing slashes from the path\n\npub fn trim_trailing_slashes(path: &str) -> &str {\n\n path.trim_end_matches('/')\n\n}\n\n\n", "file_path": "src/ocfl/util.rs", "rank": 70, "score": 187465.46683819656 }, { "content": "/// Trims all trailing slashes from the path\n\npub fn trim_leading_slashes(path: &str) -> &str {\n\n path.trim_start_matches('/')\n\n}\n\n\n", "file_path": "src/ocfl/util.rs", "rank": 71, "score": 187465.46683819656 }, { "content": "/// Identical to `fs::remove_file()` except `NotFound` errors are ignored\n\npub fn remove_file_ignore_not_found(path: impl AsRef<Path>) -> io::Result<()> {\n\n if let Err(e) = fs::remove_file(path) {\n\n if e.kind() != ErrorKind::NotFound {\n\n return Err(e);\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/ocfl/util.rs", "rank": 72, "score": 186375.18347144584 }, { "content": "#[test]\n\nfn get_staged_object_file_when_exists_in_prior_version() -> Result<()> {\n\n let root = TempDir::new().unwrap();\n\n let temp = TempDir::new().unwrap();\n\n\n\n let repo = default_repo(root.path());\n\n\n\n let object_id = \"get file\";\n\n\n\n create_example_object(object_id, &repo, &temp);\n\n\n\n repo.move_files_external(\n\n object_id,\n\n &vec![create_file(&temp, \"blah\", \"blah\").path()],\n\n \"blah\",\n\n )?;\n\n\n\n let mut out: Vec<u8> = Vec::new();\n\n\n\n repo.get_staged_object_file(object_id, &lpath(\"a/file1.txt\"), &mut out)?;\n\n\n\n assert_eq!(\"File One\", String::from_utf8(out).unwrap());\n\n\n\n validate_repo(&repo);\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/fs-tests.rs", "rank": 73, "score": 186262.31151256524 }, { "content": "#[test]\n\nfn create_new_repo_empty_dir_custom_layout() -> Result<()> {\n\n let root = TempDir::new().unwrap();\n\n let temp = TempDir::new().unwrap();\n\n\n\n let layout = r#\"{\n\n \"extensionName\": \"0004-hashed-n-tuple-storage-layout\",\n\n \"digestAlgorithm\": \"sha512\",\n\n \"tupleSize\": 5,\n\n \"numberOfTuples\": 2,\n\n \"shortObjectRoot\": true\n\n}\"#;\n\n\n\n let repo = OcflRepo::init_fs_repo(\n\n root.path(),\n\n None,\n\n Some(StorageLayout::new(\n\n LayoutExtensionName::HashedNTupleLayout,\n\n Some(layout.as_bytes()),\n\n )?),\n\n )?;\n", "file_path": "tests/fs-tests.rs", "rank": 74, "score": 185984.27079025412 }, { "content": "#[test]\n\nfn create_new_object() {\n\n skip_or_run_s3_test(\n\n \"create_new_object\",\n\n |s3_client: S3Client, prefix: String, staging: TempDir, temp: TempDir| {\n\n let repo = default_repo(&prefix, staging.path());\n\n let object_id = \"s3-object\";\n\n\n\n repo.create_object(object_id, DigestAlgorithm::Sha256, \"content\", 0)\n\n .unwrap();\n\n repo.copy_files_external(\n\n object_id,\n\n &vec![create_file(&temp, \"test.txt\", \"testing\").path()],\n\n \"/\",\n\n false,\n\n )\n\n .unwrap();\n\n repo.commit(object_id, CommitMeta::new(), None, false)\n\n .unwrap();\n\n\n\n let object = repo.get_object(object_id, VersionRef::Head).unwrap();\n", "file_path": "tests/s3-tests.rs", "rank": 75, "score": 184019.23900004878 }, { "content": "fn validate_non_conflicting<F>(paths: &HashSet<&str>, error: F)\n\nwhere\n\n F: Fn(&str, &str),\n\n{\n\n for path in paths {\n\n let mut part = *path;\n\n while let Some(index) = part.rfind('/') {\n\n part = &part[0..index];\n\n if paths.contains(part) {\n\n error(path, part);\n\n break;\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/ocfl/validate/serde.rs", "rank": 76, "score": 183610.61979186494 }, { "content": "#[test]\n\n#[should_panic(expected = \"Cannot create object object 2 because an object already exists at\")]\n\nfn fail_object_commit_when_no_known_storage_layout_and_root_specified_and_obj_already_there() {\n\n let root = TempDir::new().unwrap();\n\n let temp = TempDir::new().unwrap();\n\n let repo = OcflRepo::fs_repo(root.path(), None).unwrap();\n\n\n\n let object_id = \"custom_layout\";\n\n let object_root = \"random/path/to/object\";\n\n\n\n repo.create_object(object_id, DigestAlgorithm::Sha256, \"content\", 0)\n\n .unwrap();\n\n\n\n repo.copy_files_external(\n\n object_id,\n\n &vec![create_file(&temp, \"test.txt\", \"testing\").path()],\n\n \"test.txt\",\n\n false,\n\n )\n\n .unwrap();\n\n\n\n repo.commit(object_id, CommitMeta::new(), Some(object_root), false)\n", "file_path": "tests/fs-tests.rs", "rank": 77, "score": 182874.08302784886 }, { "content": "pub fn no_warnings_storage(result: &StorageValidationResult) {\n\n assert!(\n\n result.warnings().is_empty(),\n\n \"Expected no warnings; found: {:?}\",\n\n result.warnings()\n\n )\n\n}\n\n\n", "file_path": "tests/common/mod.rs", "rank": 78, "score": 182462.9196899529 }, { "content": "pub fn no_errors_storage(result: &StorageValidationResult) {\n\n assert!(\n\n result.errors().is_empty(),\n\n \"Expected no errors; found: {:?}\",\n\n result.errors()\n\n )\n\n}\n", "file_path": "tests/common/mod.rs", "rank": 79, "score": 182462.9196899529 }, { "content": "/// Returns the path to the root of the staging extension\n\npub fn staging_extension_path<P>(storage_root: P) -> PathBuf\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n let mut extensions = extensions_path(storage_root);\n\n extensions.push(ROCFL_STAGING_EXTENSION);\n\n extensions\n\n}\n\n\n", "file_path": "src/ocfl/paths.rs", "rank": 80, "score": 181140.12824217117 }, { "content": "fn is_s3(config: &Config) -> bool {\n\n config.bucket.is_some()\n\n}\n\n\n", "file_path": "src/cmd/mod.rs", "rank": 81, "score": 180112.91354345798 }, { "content": "fn defaulted_str<'a>(value: &'a Option<String>, default: &'a str) -> &'a str {\n\n match value {\n\n Some(value) => value.as_ref(),\n\n None => default,\n\n }\n\n}\n", "file_path": "src/cmd/diff.rs", "rank": 82, "score": 179314.4092117156 }, { "content": "/// Changes `\\\\` to `/` on Windows\n\npub fn convert_backslash_to_forward(path: &str) -> Cow<str> {\n\n if BACKSLASH_SEPARATOR && path.contains('\\\\') {\n\n return Cow::Owned(path.replace('\\\\', \"/\"));\n\n }\n\n path.into()\n\n}\n\n\n", "file_path": "src/ocfl/util.rs", "rank": 83, "score": 178783.50778988205 }, { "content": "/// Changes `/` to `\\` on Windows\n\npub fn convert_forwardslash_to_back(path: &str) -> Cow<str> {\n\n if BACKSLASH_SEPARATOR && path.contains('/') {\n\n return Cow::Owned(path.replace('/', \"\\\\\"));\n\n }\n\n path.into()\n\n}\n\n\n", "file_path": "src/ocfl/util.rs", "rank": 84, "score": 178783.50778988205 }, { "content": "#[test]\n\n#[should_panic(expected = \"Expected object to exist at\")]\n\nfn fail_when_incorrect_object_in_root() {\n\n let root = TempDir::new().unwrap();\n\n let temp = TempDir::new().unwrap();\n\n\n\n let repo = OcflRepo::init_fs_repo(\n\n root.path(),\n\n None,\n\n Some(StorageLayout::new(LayoutExtensionName::FlatDirectLayout, None).unwrap()),\n\n )\n\n .unwrap();\n\n\n\n let object_id_1 = \"original\";\n\n let object_id_2 = \"different\";\n\n\n\n repo.create_object(object_id_1, DigestAlgorithm::Sha256, \"content\", 0)\n\n .unwrap();\n\n repo.move_files_external(\n\n object_id_1,\n\n &vec![create_file(&temp, \"file1.txt\", \"one\").path()],\n\n \"/\",\n", "file_path": "tests/fs-tests.rs", "rank": 85, "score": 178707.6150880159 }, { "content": "fn read_spec(name: &str) -> String {\n\n let mut path = PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"));\n\n path.push(\"resources\");\n\n path.push(\"main\");\n\n path.push(\"specs\");\n\n path.push(name);\n\n fs::read_to_string(path).unwrap()\n\n}\n\n\n", "file_path": "tests/fs-tests.rs", "rank": 86, "score": 178335.5375745715 }, { "content": "fn bucket() -> String {\n\n env::var(BUCKET_VAR).unwrap()\n\n}\n\n\n", "file_path": "tests/s3-tests.rs", "rank": 87, "score": 177598.73012218863 }, { "content": "/// Joins two string path parts, inserting at `/` if needed\n\npub fn join(part1: &str, part2: &str) -> String {\n\n let mut joined = match part1.ends_with('/') {\n\n true => part1[..part1.len() - 1].to_string(),\n\n false => part1.to_string(),\n\n };\n\n\n\n if !part2.is_empty() {\n\n if (!joined.is_empty() || part1 == \"/\") && !part2.starts_with('/') {\n\n joined.push('/');\n\n }\n\n joined.push_str(part2);\n\n }\n\n\n\n joined\n\n}\n\n\n", "file_path": "src/ocfl/paths.rs", "rank": 88, "score": 177102.8098935499 }, { "content": "fn create_logical_dirs(object: &ObjectVersion) -> HashSet<LogicalPath> {\n\n let mut dirs = HashSet::with_capacity(object.state.len());\n\n\n\n dirs.insert(\"\".try_into().unwrap());\n\n\n\n for path in object.state.keys() {\n\n let mut parent = path.parent();\n\n while !parent.is_empty() {\n\n let next = parent.parent();\n\n dirs.insert(parent);\n\n parent = next;\n\n }\n\n }\n\n\n\n dirs\n\n}\n\n\n", "file_path": "src/cmd/list.rs", "rank": 89, "score": 176397.48808580218 }, { "content": "pub fn root_warning(code: WarnCode, text: &str) -> ValidationWarning {\n\n ValidationWarning::new(ProblemLocation::ObjectRoot, code, text.to_string())\n\n}\n\n\n", "file_path": "tests/common/mod.rs", "rank": 90, "score": 176223.04353901144 }, { "content": "pub fn root_error(code: ErrorCode, text: &str) -> ValidationError {\n\n ValidationError::new(ProblemLocation::ObjectRoot, code, text.to_string())\n\n}\n\n\n", "file_path": "tests/common/mod.rs", "rank": 91, "score": 176223.04353901144 }, { "content": "fn missing_version_field(field: &str, version: &str, result: &ParseValidationResult) {\n\n result.error(\n\n ErrorCode::E048,\n\n format!(\n\n \"Inventory version '{}' is missing required key '{}'\",\n\n version, field\n\n ),\n\n );\n\n}\n\n\n", "file_path": "src/ocfl/validate/serde.rs", "rank": 92, "score": 174976.97617412274 }, { "content": "fn duplicate_version_field(field: &str, version: &str, result: &ParseValidationResult) {\n\n result.error(\n\n ErrorCode::E033,\n\n format!(\n\n \"Inventory version '{}' contains duplicate key '{}'\",\n\n version, field\n\n ),\n\n );\n\n}\n\n\n", "file_path": "src/ocfl/validate/serde.rs", "rank": 93, "score": 174976.97617412274 }, { "content": "fn unknown_version_field(field: &str, version: &str, result: &ParseValidationResult) {\n\n result.error(\n\n ErrorCode::E102,\n\n format!(\n\n \"Inventory version '{}' contains unknown key '{}'\",\n\n version, field\n\n ),\n\n );\n\n}\n\n\n", "file_path": "src/ocfl/validate/serde.rs", "rank": 94, "score": 174976.97617412274 }, { "content": "#[test]\n\nfn create_object_with_non_standard_config() {\n\n let root = TempDir::new().unwrap();\n\n let temp = TempDir::new().unwrap();\n\n\n\n let repo = default_repo(root.path());\n\n\n\n let object_id = \"non-standard\";\n\n\n\n assert_staged_obj_count(&repo, 0);\n\n repo.create_object(object_id, DigestAlgorithm::Sha256, \"content-dir\", 5)\n\n .unwrap();\n\n assert_staged_obj_count(&repo, 1);\n\n\n\n create_file(&temp, \"test.txt\", \"testing\");\n\n\n\n repo.copy_files_external(\n\n object_id,\n\n &vec![temp.child(\"test.txt\").path()],\n\n \"test.txt\",\n\n false,\n", "file_path": "tests/fs-tests.rs", "rank": 95, "score": 173580.4199686878 }, { "content": "#[test]\n\nfn create_new_repo_empty_dir() {\n\n skip_or_run_s3_test(\n\n \"create_new_repo_empty_dir\",\n\n |s3_client: S3Client, prefix: String, staging: TempDir, temp: TempDir| {\n\n let repo = default_repo(&prefix, staging.path());\n\n\n\n assert_file(&s3_client, &prefix, \"0=ocfl_1.0\", \"ocfl_1.0\\n\");\n\n assert_file(\n\n &s3_client,\n\n &prefix,\n\n \"ocfl_1.0.txt\",\n\n &read_spec(\"ocfl_1.0.txt\"),\n\n );\n\n assert_storage_layout(\n\n &s3_client,\n\n &prefix,\n\n \"0004-hashed-n-tuple-storage-layout\",\n\n DEFAULT_LAYOUT,\n\n );\n\n\n", "file_path": "tests/s3-tests.rs", "rank": 96, "score": 172891.26101943158 }, { "content": "fn missing_version_field_warn(field: &str, version: &str, result: &ParseValidationResult) {\n\n result.warn(\n\n WarnCode::W007,\n\n format!(\n\n \"Inventory version '{}' is missing recommended key '{}'\",\n\n version, field\n\n ),\n\n );\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::ocfl::validate::serde::parse;\n\n use crate::ocfl::validate::{ParseResult, ParseValidationResult};\n\n use crate::ocfl::{ErrorCode, ProblemLocation, ValidationError, ValidationWarning, WarnCode};\n\n\n\n #[test]\n\n fn head_wrong_type() {\n\n let json = r###\"{\n\n \"id\": \"urn:example:test\",\n", "file_path": "src/ocfl/validate/serde.rs", "rank": 97, "score": 172584.25387953207 }, { "content": "fn edit_config() -> Result<()> {\n\n match config::config_path() {\n\n Some(config_path) => {\n\n if !config_path.exists() {\n\n fs::create_dir_all(config_path.parent().unwrap())?;\n\n let mut file = fs::File::create(&config_path)?;\n\n write!(\n\n file,\n\n \"{}\",\n\n include_str!(\"../../resources/main/files/config.toml\")\n\n )?;\n\n }\n\n\n\n edit::edit_file(&config_path)?;\n\n Ok(())\n\n }\n\n None => Err(RocflError::General(\n\n \"Failed to find rocfl config\".to_string(),\n\n )),\n\n }\n\n}\n", "file_path": "src/cmd/mod.rs", "rank": 98, "score": 171996.26284402178 }, { "content": "#[test]\n\nfn list_all_objects() -> Result<()> {\n\n let repo_root = create_repo_root(\"multiple-objects\");\n\n let repo = OcflRepo::fs_repo(&repo_root, None)?;\n\n\n\n let mut objects: Vec<ObjectVersionDetails> = repo.list_objects(None)?.flatten().collect();\n\n\n\n sort_obj_details(&mut objects);\n\n\n\n assert_eq!(3, objects.len());\n\n\n\n assert_eq!(\n\n objects.remove(0),\n\n ObjectVersionDetails {\n\n id: \"o1\".to_string(),\n\n object_root: repo_root\n\n .join(\"235\")\n\n .join(\"2da\")\n\n .join(\"728\")\n\n .join(\"2352da7280f1decc3acf1ba84eb945c9fc2b7b541094e1d0992dbffd1b6664cc\")\n\n .to_string_lossy()\n", "file_path": "tests/fs-tests.rs", "rank": 99, "score": 171810.13127900875 } ]
Rust
src/core/mod.rs
yamafaktory/hypergraph
e253ed0f0c34af8e3d07e753323c457644aaa819
pub(crate) mod bi_hash_map; #[doc(hidden)] pub mod errors; #[doc(hidden)] pub mod hyperedges; mod shared; mod utils; #[doc(hidden)] pub mod vertices; use bi_hash_map::BiHashMap; use indexmap::{IndexMap, IndexSet}; use std::{ fmt::{Debug, Display, Formatter, Result}, hash::Hash, }; pub trait SharedTrait: Copy + Debug + Display + Eq + Hash {} impl<T> SharedTrait for T where T: Copy + Debug + Display + Eq + Hash {} #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct VertexIndex(pub usize); impl Display for VertexIndex { fn fmt(&self, f: &mut Formatter<'_>) -> Result { write!(f, "{}", self.0) } } #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct HyperedgeIndex(pub usize); impl Display for HyperedgeIndex { fn fmt(&self, f: &mut Formatter<'_>) -> Result { write!(f, "{}", self.0) } } #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct HyperedgeKey<HE> { vertices: Vec<usize>, weight: HE, } impl<HE> HyperedgeKey<HE> { pub(crate) fn new(vertices: Vec<usize>, weight: HE) -> HyperedgeKey<HE> { Self { vertices, weight } } } pub struct Hypergraph<V, HE> { pub vertices: IndexMap<V, IndexSet<usize>>, pub hyperedges: IndexSet<HyperedgeKey<HE>>, hyperedges_mapping: BiHashMap<HyperedgeIndex>, vertices_mapping: BiHashMap<VertexIndex>, hyperedges_count: usize, vertices_count: usize, } impl<V: Eq + Hash + Debug, HE: Debug> Debug for Hypergraph<V, HE> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { f.debug_struct("Hypergraph") .field("vertices", &self.vertices) .field("hyperedges", &self.hyperedges) .finish() } } impl<V, HE> Default for Hypergraph<V, HE> where V: SharedTrait, HE: SharedTrait, { fn default() -> Self { Hypergraph::new() } } impl<V, HE> Hypergraph<V, HE> where V: SharedTrait, HE: SharedTrait, { pub fn clear(&mut self) { self.hyperedges.clear(); self.vertices.clear(); self.hyperedges_mapping = BiHashMap::default(); self.vertices_mapping = BiHashMap::default(); self.hyperedges_count = 0; self.vertices_count = 0; } pub fn new() -> Self { Hypergraph::with_capacity(0, 0) } pub fn with_capacity(vertices: usize, hyperedges: usize) -> Self { Hypergraph { hyperedges_count: 0, hyperedges_mapping: BiHashMap::default(), hyperedges: IndexSet::with_capacity(hyperedges), vertices_count: 0, vertices_mapping: BiHashMap::default(), vertices: IndexMap::with_capacity(vertices), } } }
pub(crate) mod bi_hash_map; #[doc(hidden)] pub mod errors; #[doc(hidden)] pub mod hyperedges; mod shared; mod utils; #[doc(hidden)] pub mod vertices; use bi_hash_map::BiHashMap; use indexmap::{IndexMap, IndexSet}; use std::{ fmt::{Debug, Display, Formatter, Result}, hash::Hash, }; pub trait SharedTrait: Copy + Debug + Display + Eq + Hash {} impl<T> SharedTrait for T where T: Copy + Debug + Display + Eq + Hash {} #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct VertexIndex(pub usize); impl Display for VertexIndex { fn fmt(&self, f: &mut Formatter<'_>) -> Result { write!(f, "{}", self.0) } } #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct HyperedgeIndex(pub usize); impl Display for HyperedgeIndex { fn fmt(&self, f: &mut Formatter<'_>) -> Result { write!(f, "{}", self.0) } } #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct HyperedgeKey<HE> { vertices: Vec<usize>, weight: HE, } impl<HE> HyperedgeKey<HE> { pub(crate) fn new(vertices: Vec<usize>, weight: HE) -> HyperedgeKey<HE> { Self { vertices, weight } } } pub struct Hypergraph<V, HE> { pub vertices: IndexMap<V, IndexSet<usize>>, pub hyperedges: IndexSet<HyperedgeKey<HE>>, hyperedges_mapping: BiHashMap<HyperedgeIndex>, vertices_mapping: BiHashMap<VertexIndex>, hyperedges_count: usize, vertices_count: usize, } impl<V: Eq + Hash + Debug, HE: Debug> Debug for Hypergraph<V, HE> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { f.debug_struct("Hypergraph") .field("vertices", &self.vertices) .field("hyperedges", &self.hyperedges) .finish() } } impl<V, HE> Default for Hypergraph<V, HE> where V: SharedTrait, HE: SharedTrait, { fn default() -> Self { Hypergraph::new() } } impl<V, HE> Hypergraph<V, HE> where V: SharedTrait, HE: SharedTrait, { pub fn clear(&mut self) { self.hyperedges.clear(); self.vertices.clear(); self.hyperedges_mapping = BiHashMap::default(); self.vertices_mapping = BiHashMap::default(); self.hyperedges_count = 0; self.vertices_count = 0; } pub fn new() -> Self { Hypergraph::with_capacity(0, 0) }
}
pub fn with_capacity(vertices: usize, hyperedges: usize) -> Self { Hypergraph { hyperedges_count: 0, hyperedges_mapping: BiHashMap::default(), hyperedges: IndexSet::with_capacity(hyperedges), vertices_count: 0, vertices_mapping: BiHashMap::default(), vertices: IndexMap::with_capacity(vertices), } }
function_block-full_function
[ { "content": "use crate::{errors::HypergraphError, HyperedgeIndex, HyperedgeKey, Hypergraph, SharedTrait};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Updates the weight of a hyperedge by index.\n\n pub fn update_hyperedge_weight(\n\n &mut self,\n\n hyperedge_index: HyperedgeIndex,\n\n weight: HE,\n\n ) -> Result<(), HypergraphError<V, HE>> {\n\n let internal_index = self.get_internal_hyperedge(hyperedge_index)?;\n\n\n\n let HyperedgeKey {\n\n vertices,\n\n weight: previous_weight,\n\n } = self\n\n .hyperedges\n", "file_path": "src/core/hyperedges/update_hyperedge_weight.rs", "rank": 1, "score": 58277.35562021103 }, { "content": "use crate::{errors::HypergraphError, HyperedgeIndex, Hypergraph, SharedTrait};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Gets the weight of a hyperedge from its index.\n\n pub fn get_hyperedge_weight(\n\n &self,\n\n hyperedge_index: HyperedgeIndex,\n\n ) -> Result<HE, HypergraphError<V, HE>> {\n\n let internal_index = self.get_internal_hyperedge(hyperedge_index)?;\n\n\n\n let hyperedge_key = self\n\n .hyperedges\n\n .get_index(internal_index)\n\n .ok_or(HypergraphError::InternalVertexIndexNotFound(internal_index))?;\n\n\n\n Ok(hyperedge_key.weight)\n\n }\n\n}\n", "file_path": "src/core/hyperedges/get_hyperedge_weight.rs", "rank": 2, "score": 58272.25236452031 }, { "content": " .get_index(internal_index)\n\n .map(|hyperedge_key| hyperedge_key.to_owned())\n\n .ok_or(HypergraphError::InternalHyperedgeIndexNotFound(\n\n internal_index,\n\n ))?;\n\n\n\n // Return an error if the new weight is the same as the previous one.\n\n if weight == previous_weight {\n\n return Err(HypergraphError::HyperedgeWeightUnchanged {\n\n index: hyperedge_index,\n\n weight,\n\n });\n\n }\n\n\n\n // Return an error if the new weight is already assigned to another\n\n // hyperedge.\n\n // We can't use the contains method here since the key is a combination\n\n // of the weight and the vertices.\n\n if self.hyperedges.iter().any(\n\n |HyperedgeKey {\n", "file_path": "src/core/hyperedges/update_hyperedge_weight.rs", "rank": 3, "score": 58262.49987200435 }, { "content": " weight: current_weight,\n\n ..\n\n }| { *current_weight == weight },\n\n ) {\n\n return Err(HypergraphError::HyperedgeWeightAlreadyAssigned(weight));\n\n }\n\n\n\n // IndexMap doesn't allow holes by design, see:\n\n // https://github.com/bluss/indexmap/issues/90#issuecomment-455381877\n\n //\n\n // As a consequence, we have two options. Either we use shift_remove\n\n // and it will result in an expensive regeneration of all the indexes\n\n // in the map/set or we use swap_remove methods and deal with the fact\n\n // that the last element will be swapped in place of the removed one\n\n // and will thus get a new index.\n\n //\n\n // In our case, since we are inserting an entry upfront, it circumvents\n\n // the aforementioned issue.\n\n //\n\n // First case: index alteration is avoided.\n", "file_path": "src/core/hyperedges/update_hyperedge_weight.rs", "rank": 4, "score": 58258.480025744015 }, { "content": " // ^ ^\n\n // | |\n\n // +--+\n\n // 2.Swap and remove\n\n //\n\n // Insert the new entry.\n\n // Since we have already checked that the new weight is not in the\n\n // map, we can safely perform the operation without checking its output.\n\n self.hyperedges.insert(HyperedgeKey { vertices, weight });\n\n\n\n // Swap and remove by index.\n\n // Since we know that the internal index is correct, we can safely\n\n // perform the operation without checking its output.\n\n self.hyperedges.swap_remove_index(internal_index);\n\n\n\n // Return a unit.\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/core/hyperedges/update_hyperedge_weight.rs", "rank": 5, "score": 58256.41754124734 }, { "content": " //\n\n // Entry to remove\n\n // | 1.Insert new entry\n\n // | |\n\n // v v\n\n // [a, b, c] -> [a, b, c, d] -> [d, b, c, _]\n\n // ^ ^\n\n // | |\n\n // +--------+\n\n // 2.Swap and remove\n\n //\n\n // -----------------------------------------\n\n //\n\n // Second case: no index alteration.\n\n //\n\n // Entry to remove\n\n // | 1.Insert new entry\n\n // | |\n\n // v v\n\n // [a, b, c] -> [a, b, c, d] -> [a, b, d, _]\n", "file_path": "src/core/hyperedges/update_hyperedge_weight.rs", "rank": 6, "score": 58250.00409462207 }, { "content": "use crate::{\n\n core::utils::are_slices_equal, errors::HypergraphError, HyperedgeIndex, HyperedgeKey,\n\n Hypergraph, SharedTrait, VertexIndex,\n\n};\n\n\n\nuse itertools::Itertools;\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Updates the vertices of a hyperedge by index.\n\n pub fn update_hyperedge_vertices(\n\n &mut self,\n\n hyperedge_index: HyperedgeIndex,\n\n vertices: Vec<VertexIndex>,\n\n ) -> Result<(), HypergraphError<V, HE>> {\n\n // If the provided vertices are empty, skip the update.\n\n if vertices.is_empty() {\n", "file_path": "src/core/hyperedges/update_hyperedge_vertices.rs", "rank": 7, "score": 56845.41510880503 }, { "content": "use crate::{\n\n core::utils::are_slices_equal, errors::HypergraphError, HyperedgeIndex, Hypergraph,\n\n SharedTrait, VertexIndex,\n\n};\n\n\n\nuse itertools::Itertools;\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Contracts a set of the vertices of a hyperedge into one single vertex.\n\n /// Returns the updated vertices.\n\n /// Based on <https://en.wikipedia.org/wiki/Edge_contraction>\n\n pub fn contract_hyperedge_vertices(\n\n &mut self,\n\n hyperedge_index: HyperedgeIndex,\n\n vertices: Vec<VertexIndex>,\n\n target: VertexIndex,\n", "file_path": "src/core/hyperedges/contract_hyperedge_vertices.rs", "rank": 8, "score": 56841.94572036051 }, { "content": "use crate::{\n\n errors::HypergraphError, HyperedgeIndex, HyperedgeKey, Hypergraph, SharedTrait, VertexIndex,\n\n};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Gets the vertices of a hyperedge.\n\n pub fn get_hyperedge_vertices(\n\n &self,\n\n hyperedge_index: HyperedgeIndex,\n\n ) -> Result<Vec<VertexIndex>, HypergraphError<V, HE>> {\n\n let internal_index = self.get_internal_hyperedge(hyperedge_index)?;\n\n\n\n let HyperedgeKey { vertices, .. } = self.hyperedges.get_index(internal_index).ok_or(\n\n HypergraphError::InternalHyperedgeIndexNotFound(internal_index),\n\n )?;\n\n\n\n self.get_vertices(vertices.to_owned())\n\n }\n\n}\n", "file_path": "src/core/hyperedges/get_hyperedge_vertices.rs", "rank": 9, "score": 56839.93150172768 }, { "content": " return Err(HypergraphError::HyperedgeUpdateNoVertices(hyperedge_index));\n\n }\n\n\n\n let internal_index = self.get_internal_hyperedge(hyperedge_index)?;\n\n\n\n let internal_vertices = self.get_internal_vertices(vertices)?;\n\n\n\n let HyperedgeKey {\n\n vertices: previous_vertices,\n\n weight,\n\n } = self\n\n .hyperedges\n\n .get_index(internal_index)\n\n .map(|hyperedge_key| hyperedge_key.to_owned())\n\n .ok_or(HypergraphError::InternalHyperedgeIndexNotFound(\n\n internal_index,\n\n ))?;\n\n\n\n // If the new vertices are the same as the old ones, skip the update.\n\n if are_slices_equal(&internal_vertices, &previous_vertices) {\n", "file_path": "src/core/hyperedges/update_hyperedge_vertices.rs", "rank": 10, "score": 56827.603645166964 }, { "content": " ) -> Result<Vec<VertexIndex>, HypergraphError<V, HE>> {\n\n // Get all the vertices of the hyperedge.\n\n let hyperedge_vertices = self.get_hyperedge_vertices(hyperedge_index)?;\n\n\n\n // Get the deduped vertices.\n\n let deduped_vertices = vertices.iter().sorted().dedup().collect_vec();\n\n\n\n // Check that the target is included in the deduped vertices.\n\n if !deduped_vertices\n\n .iter()\n\n .any(|&current_index| current_index == &target)\n\n {\n\n return Err(HypergraphError::HyperedgeInvalidContraction {\n\n index: hyperedge_index,\n\n target,\n\n vertices: deduped_vertices.into_iter().cloned().collect(),\n\n });\n\n }\n\n\n\n // Get the vertices not found in the hyperedge.\n", "file_path": "src/core/hyperedges/contract_hyperedge_vertices.rs", "rank": 11, "score": 56827.3998387396 }, { "content": " return Err(HypergraphError::HyperedgeVerticesUnchanged(hyperedge_index));\n\n }\n\n\n\n // Find the vertices which have been added.\n\n let added = internal_vertices\n\n .iter()\n\n .fold(vec![], |mut acc: Vec<usize>, index| {\n\n if !previous_vertices\n\n .iter()\n\n .any(|current_index| current_index == index)\n\n {\n\n acc.push(*index)\n\n }\n\n\n\n acc\n\n })\n\n .into_iter()\n\n .sorted()\n\n .dedup()\n\n .collect_vec();\n", "file_path": "src/core/hyperedges/update_hyperedge_vertices.rs", "rank": 12, "score": 56826.90491271635 }, { "content": "\n\n // Insert the new entry.\n\n // Since we are not altering the weight, we can safely perform the\n\n // operation without checking its output.\n\n self.hyperedges.insert(HyperedgeKey {\n\n vertices: internal_vertices,\n\n weight,\n\n });\n\n\n\n // Swap and remove by index.\n\n // Since we know that the internal index is correct, we can safely\n\n // perform the operation without checking its output.\n\n self.hyperedges.swap_remove_index(internal_index);\n\n\n\n // Return a unit.\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/core/hyperedges/update_hyperedge_vertices.rs", "rank": 13, "score": 56824.99544889156 }, { "content": " let vertices_not_found =\n\n deduped_vertices\n\n .iter()\n\n .fold(vec![], |mut acc: Vec<VertexIndex>, &index| {\n\n if !hyperedge_vertices\n\n .iter()\n\n .any(|&current_index| current_index == *index)\n\n {\n\n acc.push(index.to_owned())\n\n }\n\n\n\n acc\n\n });\n\n\n\n // Check that all the vertices - target included - are a subset of\n\n // the current hyperedge's vertices.\n\n if !vertices_not_found.is_empty() {\n\n return Err(HypergraphError::HyperedgeVerticesIndexesNotFound {\n\n index: hyperedge_index,\n\n vertices: vertices_not_found,\n", "file_path": "src/core/hyperedges/contract_hyperedge_vertices.rs", "rank": 14, "score": 56824.97896707374 }, { "content": " });\n\n }\n\n\n\n // Store all the hyperedges which are going to change.\n\n let mut all_hyperedges: Vec<HyperedgeIndex> = vec![];\n\n\n\n // Iterate over all the deduped vertices.\n\n for &vertex in deduped_vertices.iter() {\n\n // Safely get the hyperedges of the current vertex.\n\n let mut vertex_hyperedges = self.get_vertex_hyperedges(*vertex)?;\n\n\n\n // Concatenate them to the global ones.\n\n all_hyperedges.append(&mut vertex_hyperedges);\n\n }\n\n\n\n // Iterate over all the deduped hyperedges.\n\n for &hyperedge in all_hyperedges.iter().sorted().dedup() {\n\n let hyperedge_vertices = self.get_hyperedge_vertices(hyperedge)?;\n\n\n\n // Contract the vertices of the hyperedge.\n", "file_path": "src/core/hyperedges/contract_hyperedge_vertices.rs", "rank": 15, "score": 56824.6605777007 }, { "content": " let contraction = hyperedge_vertices\n\n .iter()\n\n // First remap each vertex to itself or to the target.\n\n .map(|vertex| {\n\n if deduped_vertices\n\n .iter()\n\n .any(|&current_index| current_index == vertex)\n\n {\n\n target\n\n } else {\n\n *vertex\n\n }\n\n })\n\n // Then dedupe the resulting vector.\n\n .dedup()\n\n .collect_vec();\n\n\n\n // Only update the hyperedge if necessary.\n\n if !are_slices_equal(\n\n &self.get_internal_vertices(&contraction)?,\n", "file_path": "src/core/hyperedges/contract_hyperedge_vertices.rs", "rank": 16, "score": 56822.59394760825 }, { "content": " match self.vertices.get_index_mut(index) {\n\n Some((_, index_set)) => {\n\n index_set.insert(internal_index);\n\n }\n\n None => return Err(HypergraphError::InternalVertexIndexNotFound(index)),\n\n }\n\n }\n\n\n\n // Update the removed vertices.\n\n for index in removed.into_iter() {\n\n match self.vertices.get_index_mut(index) {\n\n Some((_, index_set)) => {\n\n // This has an impact on the internal indexing for the set.\n\n // However since this is not exposed to the user - i.e. no\n\n // mapping is involved - we can safely perform the operation.\n\n index_set.swap_remove_index(internal_index);\n\n }\n\n None => return Err(HypergraphError::InternalVertexIndexNotFound(index)),\n\n }\n\n }\n", "file_path": "src/core/hyperedges/update_hyperedge_vertices.rs", "rank": 17, "score": 56822.3039174044 }, { "content": " &self.get_internal_vertices(hyperedge_vertices)?,\n\n ) {\n\n // Safely update the current hyperedge with the contraction.\n\n self.update_hyperedge_vertices(hyperedge, contraction)?;\n\n }\n\n }\n\n\n\n // Return the contraction.\n\n self.get_hyperedge_vertices(hyperedge_index)\n\n }\n\n}\n", "file_path": "src/core/hyperedges/contract_hyperedge_vertices.rs", "rank": 18, "score": 56821.54029631087 }, { "content": "\n\n // Find the vertices which have been removed.\n\n let removed = previous_vertices\n\n .iter()\n\n .filter_map(|index| {\n\n if !internal_vertices\n\n .iter()\n\n .any(|current_index| index == current_index)\n\n {\n\n Some(*index)\n\n } else {\n\n None\n\n }\n\n })\n\n .sorted()\n\n .dedup()\n\n .collect_vec();\n\n\n\n // Update the added vertices.\n\n for index in added.into_iter() {\n", "file_path": "src/core/hyperedges/update_hyperedge_vertices.rs", "rank": 19, "score": 56818.07072682149 }, { "content": "pub(crate) mod add_vertex_index;\n\npub(crate) mod get_internal_vertex;\n\npub(crate) mod get_internal_vertices;\n\npub(crate) mod get_vertex;\n\npub(crate) mod get_vertices;\n\n\n\npub mod add_vertex;\n\npub mod count_vertices;\n\npub mod get_adjacent_vertices_from;\n\npub mod get_adjacent_vertices_to;\n\npub mod get_dijkstra_connections;\n\npub mod get_full_vertex_hyperedges;\n\npub mod get_vertex_degree_in;\n\npub mod get_vertex_degree_out;\n\npub mod get_vertex_hyperedges;\n\npub mod get_vertex_weight;\n\npub mod remove_vertex;\n\npub mod update_vertex_weight;\n", "file_path": "src/core/vertices/mod.rs", "rank": 20, "score": 55024.537842338716 }, { "content": "pub(crate) mod add_hyperedge_index;\n\npub(crate) mod get_hyperedge;\n\npub(crate) mod get_hyperedges;\n\npub(crate) mod get_internal_hyperedge;\n\npub(crate) mod get_internal_hyperedges;\n\n\n\npub mod add_hyperedge;\n\npub mod clear_hyperedges;\n\npub mod contract_hyperedge_vertices;\n\npub mod count_hyperedges;\n\npub mod get_hyperedge_vertices;\n\npub mod get_hyperedge_weight;\n\npub mod get_hyperedges_connecting;\n\npub mod get_hyperedges_intersections;\n\npub mod remove_hyperedge;\n\npub mod reverse_hyperedge;\n\npub mod update_hyperedge_vertices;\n\npub mod update_hyperedge_weight;\n", "file_path": "src/core/hyperedges/mod.rs", "rank": 21, "score": 54974.347395593286 }, { "content": "use crate::{errors::HypergraphError, Hypergraph, SharedTrait, VertexIndex};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Updates the weight of a vertex by index.\n\n pub fn update_vertex_weight(\n\n &mut self,\n\n vertex_index: VertexIndex,\n\n weight: V,\n\n ) -> Result<(), HypergraphError<V, HE>> {\n\n let internal_index = self.get_internal_vertex(vertex_index)?;\n\n\n\n let (previous_weight, index_set) = self\n\n .vertices\n\n .get_index(internal_index)\n\n .map(|(previous_weight, index_set)| (previous_weight.to_owned(), index_set.to_owned()))\n\n .ok_or(HypergraphError::InternalVertexIndexNotFound(internal_index))?;\n", "file_path": "src/core/vertices/update_vertex_weight.rs", "rank": 22, "score": 50611.795052880334 }, { "content": "use crate::{errors::HypergraphError, Hypergraph, SharedTrait, VertexIndex};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Gets the weight of a vertex from its index.\n\n pub fn get_vertex_weight(\n\n &self,\n\n vertex_index: VertexIndex,\n\n ) -> Result<V, HypergraphError<V, HE>> {\n\n let internal_index = self.get_internal_vertex(vertex_index)?;\n\n\n\n self.vertices\n\n .get_index(internal_index)\n\n .map(|(weight, _)| *weight)\n\n .ok_or(HypergraphError::InternalVertexIndexNotFound(internal_index))\n\n }\n\n}\n", "file_path": "src/core/vertices/get_vertex_weight.rs", "rank": 23, "score": 50611.497370432735 }, { "content": "\n\n // Return an error if the new weight is the same as the previous one.\n\n if weight == previous_weight {\n\n return Err(HypergraphError::VertexWeightUnchanged {\n\n index: vertex_index,\n\n weight,\n\n });\n\n }\n\n\n\n // Return an error if the new weight is already assigned to another\n\n // vertex.\n\n if self.vertices.contains_key(&weight) {\n\n return Err(HypergraphError::VertexWeightAlreadyAssigned(weight));\n\n }\n\n\n\n // We can't directly replace the value in the map.\n\n // First, we need to insert the new weight, it will end up\n\n // being at the last position.\n\n // Since we have already checked that the new weight is not in the\n\n // map, we can safely perform the operation without checking its output.\n", "file_path": "src/core/vertices/update_vertex_weight.rs", "rank": 24, "score": 50598.5134703989 }, { "content": " self.vertices.insert(weight, index_set);\n\n\n\n // Then we use swap and remove. This will remove the previous weight\n\n // and insert the new one at the index position of the former.\n\n // This doesn't alter the indexing.\n\n // See the update_hyperedge_weight method for more detailed explanation.\n\n // Since we know that the internal index is correct, we can safely\n\n // perform the operation without checking its output.\n\n self.vertices.swap_remove_index(internal_index);\n\n\n\n // Return a unit.\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/core/vertices/update_vertex_weight.rs", "rank": 25, "score": 50597.81618690161 }, { "content": "use crate::{errors::HypergraphError, HyperedgeIndex, Hypergraph, SharedTrait, VertexIndex};\n\n\n\nuse itertools::Itertools;\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Gets the hyperedges of a vertex as a vector of HyperedgeIndex.\n\n pub fn get_vertex_hyperedges(\n\n &self,\n\n vertex_index: VertexIndex,\n\n ) -> Result<Vec<HyperedgeIndex>, HypergraphError<V, HE>> {\n\n let internal_index = self.get_internal_vertex(vertex_index)?;\n\n\n\n let (_, hyperedges_index_set) = self\n\n .vertices\n\n .get_index(internal_index)\n\n .ok_or(HypergraphError::InternalVertexIndexNotFound(internal_index))?;\n\n\n\n self.get_hyperedges(hyperedges_index_set.clone().into_iter().collect_vec())\n\n }\n\n}\n", "file_path": "src/core/vertices/get_vertex_hyperedges.rs", "rank": 26, "score": 49130.99139329906 }, { "content": "use crate::{errors::HypergraphError, Hypergraph, SharedTrait, VertexIndex};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Gets the hyperedges of a vertex as a vector of vectors of VertexIndex.\n\n pub fn get_full_vertex_hyperedges(\n\n &self,\n\n vertex_index: VertexIndex,\n\n ) -> Result<Vec<Vec<VertexIndex>>, HypergraphError<V, HE>> {\n\n self.get_vertex_hyperedges(vertex_index).map(|hyperedges| {\n\n hyperedges\n\n .into_iter()\n\n .flat_map(|hyperedge_index| self.get_hyperedge_vertices(hyperedge_index))\n\n .collect()\n\n })\n\n }\n\n}\n", "file_path": "src/core/vertices/get_full_vertex_hyperedges.rs", "rank": 27, "score": 47234.08209218856 }, { "content": "#[test]\n\nfn integration() {\n\n // Create a new hypergraph.\n\n let mut graph = Hypergraph::<Vertex<'_>, &str>::new();\n\n\n\n // Create some vertices.\n\n let andrea = Vertex::new(\"Andrea\");\n\n let bjǫrn = Vertex::new(\"Bjǫrn\");\n\n let charlie = Vertex::new(\"Charlie\");\n\n let dana = Vertex::new(\"Dana\");\n\n let enola = Vertex::new(\"Enola\");\n\n\n\n // Add those vertices to the hypergraph.\n\n assert_eq!(\n\n graph.add_vertex(andrea),\n\n Ok(VertexIndex(0)),\n\n \"should add the first vertex\"\n\n );\n\n assert_eq!(\n\n graph.add_vertex(bjǫrn),\n\n Ok(VertexIndex(1)),\n", "file_path": "tests/integration_main.rs", "rank": 28, "score": 35002.14815973941 }, { "content": "#[test]\n\nfn integration_contration() {\n\n // Create a new hypergraph.\n\n let mut graph = Hypergraph::<Vertex<'_>, &str>::new();\n\n\n\n // Create some vertices.\n\n let a = graph.add_vertex(Vertex::new(\"a\")).unwrap();\n\n let b = graph.add_vertex(Vertex::new(\"b\")).unwrap();\n\n let c = graph.add_vertex(Vertex::new(\"c\")).unwrap();\n\n let d = graph.add_vertex(Vertex::new(\"d\")).unwrap();\n\n let e = graph.add_vertex(Vertex::new(\"e\")).unwrap();\n\n\n\n // Create some hyperedges.\n\n let alpha = graph.add_hyperedge(vec![a, b, c, d, e], \"α\").unwrap();\n\n let beta = graph.add_hyperedge(vec![a, c, d, e, c], \"β\").unwrap();\n\n let gamma = graph.add_hyperedge(vec![a, e, b], \"γ\").unwrap();\n\n let delta = graph.add_hyperedge(vec![b, c, b, d, c], \"δ\").unwrap();\n\n let epsilon = graph.add_hyperedge(vec![c, c, c], \"ε\").unwrap();\n\n\n\n // In the alpha hyperedge, contract the vertices b and c into one single vertex b.\n\n assert_eq!(\n", "file_path": "tests/integration_contraction.rs", "rank": 29, "score": 33804.70137271395 }, { "content": "use crate::{errors::HypergraphError, Hypergraph, SharedTrait, VertexIndex};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n // Private method to get a vector of VertexIndex from a vector of internal indexes.\n\n pub(crate) fn get_vertices(\n\n &self,\n\n vertices: Vec<usize>,\n\n ) -> Result<Vec<VertexIndex>, HypergraphError<V, HE>> {\n\n vertices\n\n .iter()\n\n .map(|vertex_index| self.get_vertex(*vertex_index))\n\n .collect()\n\n }\n\n}\n", "file_path": "src/core/vertices/get_vertices.rs", "rank": 30, "score": 33200.96063156437 }, { "content": "use crate::{Hypergraph, SharedTrait};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Returns the number of vertices in the hypergraph.\n\n pub fn count_vertices(&self) -> usize {\n\n self.vertices.len()\n\n }\n\n}\n", "file_path": "src/core/vertices/count_vertices.rs", "rank": 31, "score": 33200.327275684875 }, { "content": "use crate::{\n\n errors::HypergraphError, HyperedgeIndex, HyperedgeKey, Hypergraph, SharedTrait, VertexIndex,\n\n};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Adds a hyperedge as an array of vertices indexes and a custom weight in the hypergraph.\n\n /// Returns the weighted index of the hyperedge.\n\n pub fn add_hyperedge(\n\n &mut self,\n\n vertices: Vec<VertexIndex>,\n\n weight: HE,\n\n ) -> Result<HyperedgeIndex, HypergraphError<V, HE>> {\n\n // If the provided vertices are empty, skip the update.\n\n if vertices.is_empty() {\n\n return Err(HypergraphError::HyperedgeCreationNoVertices(weight));\n\n }\n", "file_path": "src/core/hyperedges/add_hyperedge.rs", "rank": 32, "score": 33142.54024360859 }, { "content": "use crate::{bi_hash_map::BiHashMap, errors::HypergraphError, Hypergraph, SharedTrait};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Clears all the hyperedges from the hypergraph.\n\n pub fn clear_hyperedges(&mut self) -> Result<(), HypergraphError<V, HE>> {\n\n // Clear the set while keeping its capacity.\n\n self.hyperedges.clear();\n\n\n\n // Reset the hyperedges mapping.\n\n self.hyperedges_mapping = BiHashMap::default();\n\n\n\n // Reset the hyperedges counter.\n\n self.hyperedges_count = 0;\n\n\n\n // Update the vertices accordingly.\n\n self.vertices\n\n .iter_mut()\n\n // Clear the sets while keeping their capacities.\n\n .for_each(|(_, hyperedges)| hyperedges.clear());\n\n\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/core/hyperedges/clear_hyperedges.rs", "rank": 33, "score": 33141.67823522222 }, { "content": "use crate::{errors::HypergraphError, HyperedgeIndex, Hypergraph, SharedTrait};\n\n\n\nuse itertools::Itertools;\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n // Reverses a hyperedge.\n\n pub fn reverse_hyperedge(\n\n &mut self,\n\n hyperedge_index: HyperedgeIndex,\n\n ) -> Result<(), HypergraphError<V, HE>> {\n\n // Get the vertices of the hyperedge.\n\n let vertices = self.get_hyperedge_vertices(hyperedge_index)?;\n\n\n\n // Update the hyperedge with the reversed vertices.\n\n self.update_hyperedge_vertices(hyperedge_index, vertices.into_iter().rev().collect_vec())\n\n }\n\n}\n", "file_path": "src/core/hyperedges/reverse_hyperedge.rs", "rank": 34, "score": 33140.810261692815 }, { "content": "use crate::{errors::HypergraphError, HyperedgeIndex, Hypergraph, SharedTrait};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n // Private method to get a vector of HyperedgeIndex from a vector of internal indexes.\n\n pub(crate) fn get_hyperedges(\n\n &self,\n\n hyperedges: Vec<usize>,\n\n ) -> Result<Vec<HyperedgeIndex>, HypergraphError<V, HE>> {\n\n hyperedges\n\n .iter()\n\n .map(|hyperedge_index| self.get_hyperedge(*hyperedge_index))\n\n .collect()\n\n }\n\n}\n", "file_path": "src/core/hyperedges/get_hyperedges.rs", "rank": 35, "score": 33137.76113289751 }, { "content": "use crate::{errors::HypergraphError, HyperedgeIndex, HyperedgeKey, Hypergraph, SharedTrait};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Removes a hyperedge by index.\n\n pub fn remove_hyperedge(\n\n &mut self,\n\n hyperedge_index: HyperedgeIndex,\n\n ) -> Result<(), HypergraphError<V, HE>> {\n\n let internal_index = self.get_internal_hyperedge(hyperedge_index)?;\n\n\n\n let HyperedgeKey { vertices, .. } = self\n\n .hyperedges\n\n .get_index(internal_index)\n\n .map(|hyperedge_key| hyperedge_key.to_owned())\n\n .ok_or(HypergraphError::InternalHyperedgeIndexNotFound(\n\n internal_index,\n", "file_path": "src/core/hyperedges/remove_hyperedge.rs", "rank": 36, "score": 33137.742930046436 }, { "content": "use crate::{errors::HypergraphError, HyperedgeIndex, Hypergraph, SharedTrait};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n // Private method to get the HyperedgeIndex matching an internal index.\n\n pub(crate) fn get_hyperedge(\n\n &self,\n\n hyperedge_index: usize,\n\n ) -> Result<HyperedgeIndex, HypergraphError<V, HE>> {\n\n match self.hyperedges_mapping.left.get(&hyperedge_index) {\n\n Some(index) => Ok(*index),\n\n None => Err(HypergraphError::InternalHyperedgeIndexNotFound(\n\n hyperedge_index,\n\n )),\n\n }\n\n }\n\n}\n", "file_path": "src/core/hyperedges/get_hyperedge.rs", "rank": 37, "score": 33136.87150555072 }, { "content": "use crate::{Hypergraph, SharedTrait};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Returns the number of hyperedges in the hypergraph.\n\n pub fn count_hyperedges(&self) -> usize {\n\n self.hyperedges.len()\n\n }\n\n}\n", "file_path": "src/core/hyperedges/count_hyperedges.rs", "rank": 38, "score": 33136.408269066116 }, { "content": "\n\n let internal_vertices = self.get_internal_vertices(vertices)?;\n\n\n\n // Return an error if the weight is already assigned to another\n\n // hyperedge.\n\n // We can't use the contains method here since the key is a combination\n\n // of the weight and the vertices.\n\n if self.hyperedges.iter().any(\n\n |HyperedgeKey {\n\n weight: current_weight,\n\n ..\n\n }| { *current_weight == weight },\n\n ) {\n\n return Err(HypergraphError::HyperedgeWeightAlreadyAssigned(weight));\n\n }\n\n\n\n // We don't care about the second member of the tuple returned from\n\n // the insertion since this is an infallible operation.\n\n let (internal_index, _) = self\n\n .hyperedges\n", "file_path": "src/core/hyperedges/add_hyperedge.rs", "rank": 39, "score": 33126.25480495996 }, { "content": " .insert_full(HyperedgeKey::new(internal_vertices.clone(), weight));\n\n\n\n // Update the vertices so that we keep directly track of the hyperedge.\n\n for vertex in internal_vertices.into_iter() {\n\n let (_, index_set) = self\n\n .vertices\n\n .get_index_mut(vertex)\n\n .ok_or(HypergraphError::InternalVertexIndexNotFound(vertex))?;\n\n\n\n index_set.insert(internal_index);\n\n }\n\n\n\n Ok(self.add_hyperedge_index(internal_index))\n\n }\n\n}\n", "file_path": "src/core/hyperedges/add_hyperedge.rs", "rank": 40, "score": 33125.90588915673 }, { "content": "\n\n // Get the vertices of the swapped hyperedge.\n\n let HyperedgeKey {\n\n vertices: swapped_vertices,\n\n ..\n\n } = self\n\n .hyperedges\n\n .get_index(internal_index)\n\n .map(|hyperedge_key| hyperedge_key.to_owned())\n\n .ok_or(HypergraphError::InternalHyperedgeIndexNotFound(\n\n internal_index,\n\n ))?;\n\n\n\n // Update the impacted vertices accordingly.\n\n for vertex in swapped_vertices.into_iter() {\n\n match self.vertices.get_index_mut(vertex) {\n\n Some((_, index_set)) => {\n\n // Update the by performing an insertion of the current\n\n // hyperedge and a removal of the swapped one.\n\n index_set.insert(internal_index);\n", "file_path": "src/core/hyperedges/remove_hyperedge.rs", "rank": 41, "score": 33121.80595759407 }, { "content": " ))?;\n\n\n\n // Find the last index.\n\n let last_index = self.hyperedges.len() - 1;\n\n\n\n // Swap and remove by index.\n\n self.hyperedges.swap_remove_index(internal_index);\n\n\n\n // Update the mapping for the removed hyperedge.\n\n self.hyperedges_mapping.left.remove(&internal_index);\n\n self.hyperedges_mapping.right.remove(&hyperedge_index);\n\n\n\n // Remove the hyperedge from the vertices.\n\n for vertex in vertices.into_iter() {\n\n match self.vertices.get_index_mut(vertex) {\n\n Some((_, index_set)) => {\n\n index_set.remove(&internal_index);\n\n }\n\n None => return Err(HypergraphError::InternalVertexIndexNotFound(vertex)),\n\n }\n", "file_path": "src/core/hyperedges/remove_hyperedge.rs", "rank": 42, "score": 33121.16815666116 }, { "content": " }\n\n\n\n // Given the following bi-mapping with three hyperedges, i.e. an\n\n // initial set of hyperedges [0, 1, 2]. Let's assume in this example\n\n // that the first hyperedge will be removed:\n\n //\n\n // left | Right\n\n // ---------------------------------------------------------\n\n // 0usize -> HyperedgeIndex(0) | HyperedgeIndex(0) -> 0usize\n\n // 1usize -> HyperedgeIndex(1) | HyperedgeIndex(1) -> 1usize\n\n // 2usize -> HyperedgeIndex(2) | HyperedgeIndex(2) -> 2usize\n\n //\n\n // In the previous steps, the current hyperedge has been already nuked.\n\n // So we now have:\n\n //\n\n // left | Right\n\n // ---------------------------------------------------------\n\n // xxxxxxxxxxxxxxxxxxxxxxxxxxx | xxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n // 1usize -> HyperedgeIndex(1) | HyperedgeIndex(1) -> 1usize\n\n // 2usize -> HyperedgeIndex(2) | HyperedgeIndex(2) -> 2usize\n", "file_path": "src/core/hyperedges/remove_hyperedge.rs", "rank": 43, "score": 33119.507855204036 }, { "content": " //\n\n // The next step will be to insert the swapped index on the right:\n\n //\n\n // left | Right\n\n // ---------------------------------------------------------\n\n // xxxxxxxxxxxxxxxxxxxxxxxxxxx | xxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n // 1usize -> HyperedgeIndex(1) | HyperedgeIndex(1) -> 1usize\n\n // 2usize -> HyperedgeIndex(2) | HyperedgeIndex(2) -> 0usize\n\n //\n\n // Now remove the index which no longer exists on the left:\n\n //\n\n // left | Right\n\n // ---------------------------------------------------------\n\n // xxxxxxxxxxxxxxxxxxxxxxxxxxx | xxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n // 1usize -> HyperedgeIndex(1) | HyperedgeIndex(1) -> 1usize\n\n // xxxxxxxxxxxxxxxxxxxxxxxxxxx | HyperedgeIndex(2) -> 0usize\n\n //\n\n // Insert the swapped index on the left:\n\n //\n\n // left | Right\n", "file_path": "src/core/hyperedges/remove_hyperedge.rs", "rank": 44, "score": 33119.14957539039 }, { "content": " // ---------------------------------------------------------\n\n // 0usize -> HyperedgeIndex(2) | xxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n // 1usize -> HyperedgeIndex(1) | HyperedgeIndex(1) -> 1usize\n\n // xxxxxxxxxxxxxxxxxxxxxxxxxxx | HyperedgeIndex(2) -> 0usize\n\n //\n\n // If the index to remove wasn't the last one, the last hyperedge has\n\n // been swapped in place of the removed one. Thus we need to update\n\n // the mapping accordingly.\n\n if internal_index != last_index {\n\n // Get the index of the swapped hyperedge.\n\n let swapped_hyperedge_index = self.get_hyperedge(last_index)?;\n\n\n\n // Proceed with the aforementioned operations.\n\n self.hyperedges_mapping\n\n .right\n\n .insert(swapped_hyperedge_index, internal_index);\n\n self.hyperedges_mapping.left.remove(&last_index);\n\n self.hyperedges_mapping\n\n .left\n\n .insert(internal_index, swapped_hyperedge_index);\n", "file_path": "src/core/hyperedges/remove_hyperedge.rs", "rank": 45, "score": 33118.55143205702 }, { "content": " index_set.remove(&last_index);\n\n }\n\n None => return Err(HypergraphError::InternalVertexIndexNotFound(vertex)),\n\n }\n\n }\n\n }\n\n\n\n // Return a unit.\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/core/hyperedges/remove_hyperedge.rs", "rank": 46, "score": 33114.49636577883 }, { "content": "use crate::{errors::HypergraphError, Hypergraph, SharedTrait, VertexIndex};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n // Private method to get the internal vertices from a vector of VertexIndex.\n\n pub(crate) fn get_internal_vertices<E: AsRef<Vec<VertexIndex>>>(\n\n &self,\n\n vertices: E,\n\n ) -> Result<Vec<usize>, HypergraphError<V, HE>> {\n\n vertices\n\n .as_ref()\n\n .iter()\n\n .map(|vertex_index| self.get_internal_vertex(*vertex_index))\n\n .collect()\n\n }\n\n}\n", "file_path": "src/core/vertices/get_internal_vertices.rs", "rank": 47, "score": 32324.136354634356 }, { "content": "use crate::{\n\n core::shared::Connection, errors::HypergraphError, Hypergraph, SharedTrait, VertexIndex,\n\n};\n\n\n\nuse itertools::Itertools;\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Gets the list of all vertices connected to a given vertex.\n\n pub fn get_adjacent_vertices_to(\n\n &self,\n\n to: VertexIndex,\n\n ) -> Result<Vec<VertexIndex>, HypergraphError<V, HE>> {\n\n let results = self.get_connections(Connection::Out(to))?;\n\n\n\n Ok(results\n\n .into_iter()\n\n .filter_map(|(_, vertex_index)| vertex_index)\n\n .sorted()\n\n .dedup()\n\n .collect_vec())\n\n }\n\n}\n", "file_path": "src/core/vertices/get_adjacent_vertices_to.rs", "rank": 48, "score": 32323.42812756316 }, { "content": "use crate::{\n\n core::shared::Connection, errors::HypergraphError, Hypergraph, SharedTrait, VertexIndex,\n\n};\n\n\n\nuse itertools::Itertools;\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Gets the list of all vertices connected from a given vertex.\n\n pub fn get_adjacent_vertices_from(\n\n &self,\n\n from: VertexIndex,\n\n ) -> Result<Vec<VertexIndex>, HypergraphError<V, HE>> {\n\n let results = self.get_connections(Connection::In(from))?;\n\n\n\n Ok(results\n\n .into_iter()\n\n .filter_map(|(_, vertex_index)| vertex_index)\n\n .sorted()\n\n .dedup()\n\n .collect_vec())\n\n }\n\n}\n", "file_path": "src/core/vertices/get_adjacent_vertices_from.rs", "rank": 49, "score": 32323.42812756316 }, { "content": "use crate::{errors::HypergraphError, HyperedgeIndex, Hypergraph, SharedTrait};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n // Private method to get the internal hyperedges from a vector of HyperedgeIndex.\n\n pub(crate) fn get_internal_hyperedges(\n\n &self,\n\n hyperedges: Vec<HyperedgeIndex>,\n\n ) -> Result<Vec<usize>, HypergraphError<V, HE>> {\n\n hyperedges\n\n .iter()\n\n .map(|hyperedge_index| self.get_internal_hyperedge(*hyperedge_index))\n\n .collect()\n\n }\n\n}\n", "file_path": "src/core/hyperedges/get_internal_hyperedges.rs", "rank": 50, "score": 32263.03853431045 }, { "content": "use crate::{\n\n errors::HypergraphError, HyperedgeIndex, HyperedgeKey, Hypergraph, SharedTrait, VertexIndex,\n\n};\n\n\n\nuse itertools::Itertools;\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Gets the intersections of a set of hyperedges as a vector of vertices.\n\n pub fn get_hyperedges_intersections(\n\n &self,\n\n hyperedges: Vec<HyperedgeIndex>,\n\n ) -> Result<Vec<VertexIndex>, HypergraphError<V, HE>> {\n\n // Keep track of the number of hyperedges.\n\n let number_of_hyperedges = hyperedges.len();\n\n\n\n // Early exit if less than two hyperedges are provided.\n", "file_path": "src/core/hyperedges/get_hyperedges_intersections.rs", "rank": 51, "score": 32262.375543619717 }, { "content": "use crate::{errors::HypergraphError, HyperedgeIndex, Hypergraph, SharedTrait};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n // Private method to get the internal hyperedge matching a HyperedgeIndex.\n\n pub(crate) fn get_internal_hyperedge(\n\n &self,\n\n hyperedge_index: HyperedgeIndex,\n\n ) -> Result<usize, HypergraphError<V, HE>> {\n\n match self.hyperedges_mapping.right.get(&hyperedge_index) {\n\n Some(index) => Ok(*index),\n\n None => Err(HypergraphError::HyperedgeIndexNotFound(hyperedge_index)),\n\n }\n\n }\n\n}\n", "file_path": "src/core/hyperedges/get_internal_hyperedge.rs", "rank": 52, "score": 32262.303361698057 }, { "content": "use crate::{\n\n core::shared::Connection, errors::HypergraphError, HyperedgeIndex, Hypergraph, SharedTrait,\n\n VertexIndex,\n\n};\n\n\n\nuse itertools::Itertools;\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Gets the hyperedges directly connecting a vertex to another.\n\n pub fn get_hyperedges_connecting(\n\n &self,\n\n from: VertexIndex,\n\n to: VertexIndex,\n\n ) -> Result<Vec<HyperedgeIndex>, HypergraphError<V, HE>> {\n\n let results = self.get_connections(Connection::InAndOut(from, to))?;\n\n\n\n Ok(results\n\n .into_iter()\n\n .map(|(hyperedged_index, _)| hyperedged_index)\n\n .collect_vec())\n\n }\n\n}\n", "file_path": "src/core/hyperedges/get_hyperedges_connecting.rs", "rank": 53, "score": 32262.00690566154 }, { "content": "use crate::{HyperedgeIndex, Hypergraph, SharedTrait};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n // This private method is infallible since adding the same hyperedge\n\n // will return the existing index.\n\n pub(crate) fn add_hyperedge_index(&mut self, internal_index: usize) -> HyperedgeIndex {\n\n match self.hyperedges_mapping.left.get(&internal_index) {\n\n Some(hyperedge_index) => *hyperedge_index,\n\n None => {\n\n let hyperedge_index = HyperedgeIndex(self.hyperedges_count);\n\n\n\n if self\n\n .hyperedges_mapping\n\n .left\n\n .insert(internal_index, hyperedge_index)\n\n .is_none()\n", "file_path": "src/core/hyperedges/add_hyperedge_index.rs", "rank": 54, "score": 32258.838524202638 }, { "content": " )\n\n .collect::<Result<Vec<Vec<usize>>, HypergraphError<V, HE>>>();\n\n\n\n match vertices {\n\n Ok(vertices) => {\n\n self.get_vertices(\n\n vertices\n\n .into_iter()\n\n // Flatten and sort the vertices.\n\n .flatten()\n\n .sorted()\n\n // Map the result to tuples where the second term is an arbitrary value.\n\n // The goal is to group them by indexes.\n\n .map(|index| (index, 0))\n\n .into_group_map()\n\n .into_iter()\n\n // Filter the groups having the same size as the hyperedge.\n\n .filter_map(|(index, occurences)| {\n\n if occurences.len() == number_of_hyperedges {\n\n Some(index)\n", "file_path": "src/core/hyperedges/get_hyperedges_intersections.rs", "rank": 55, "score": 32251.33535068677 }, { "content": " if number_of_hyperedges < 2 {\n\n return Err(HypergraphError::HyperedgesIntersections);\n\n }\n\n\n\n // Get the internal vertices of the hyperedges and keep the eventual error.\n\n let vertices = hyperedges\n\n .into_iter()\n\n .map(\n\n |hyperedge_index| match self.get_internal_hyperedge(hyperedge_index) {\n\n Ok(internal_index) => match self.hyperedges.get_index(internal_index).ok_or(\n\n HypergraphError::InternalHyperedgeIndexNotFound(internal_index),\n\n ) {\n\n Ok(HyperedgeKey { vertices, .. }) => {\n\n // Keep the unique vertices.\n\n Ok(vertices.iter().unique().cloned().collect_vec())\n\n }\n\n Err(error) => Err(error),\n\n },\n\n Err(error) => Err(error),\n\n },\n", "file_path": "src/core/hyperedges/get_hyperedges_intersections.rs", "rank": 56, "score": 32246.94626721219 }, { "content": " } else {\n\n None\n\n }\n\n })\n\n .sorted()\n\n .collect_vec(),\n\n )\n\n }\n\n Err(error) => Err(error),\n\n }\n\n }\n\n}\n", "file_path": "src/core/hyperedges/get_hyperedges_intersections.rs", "rank": 57, "score": 32240.766757086305 }, { "content": " {\n\n // Update the counter only for the first insertion.\n\n self.hyperedges_count += 1;\n\n }\n\n\n\n self.hyperedges_mapping\n\n .right\n\n .insert(hyperedge_index, internal_index);\n\n\n\n hyperedge_index\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/core/hyperedges/add_hyperedge_index.rs", "rank": 58, "score": 32240.577439157816 }, { "content": "use itertools::Itertools;\n\n\n\npub(crate) fn are_slices_equal(a: &[usize], b: &[usize]) -> bool {\n\n // Early guard if lengths are different.\n\n if a.len() != b.len() {\n\n return false;\n\n }\n\n\n\n a.iter().zip_eq(b).fold(true, |acc, (a, b)| acc && a == b)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn check_matching() {\n\n assert!(are_slices_equal(&[], &[]));\n\n assert!(are_slices_equal(&[1], &[1]));\n\n assert!(are_slices_equal(&[1, 2, 3], &[1, 2, 3]));\n", "file_path": "src/core/utils.rs", "rank": 59, "score": 29910.408316224315 }, { "content": " }\n\n #[test]\n\n fn check_not_matching() {\n\n assert!(!are_slices_equal(&[], &[1]));\n\n assert!(!are_slices_equal(&[1], &[]));\n\n assert!(!are_slices_equal(&[1], &[2]));\n\n assert!(!are_slices_equal(&[1, 2, 3], &[1, 2, 4]));\n\n assert!(!are_slices_equal(&[1, 2, 3], &[1, 2, 3, 4]));\n\n }\n\n}\n", "file_path": "src/core/utils.rs", "rank": 60, "score": 29897.99982012266 }, { "content": "use crate::{HyperedgeIndex, SharedTrait, VertexIndex};\n\n\n\nuse thiserror::Error;\n\n\n\n/// Enumeration of all the possible errors.\n\n#[derive(Clone, Debug, Eq, Error, PartialEq)]\n\npub enum HypergraphError<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Error when a HyperedgeIndex was not found.\n\n #[error(\"HyperedgeIndex {0} was not found\")]\n\n HyperedgeIndexNotFound(HyperedgeIndex),\n\n\n\n /// Error when an internal hyperedge index was not found.\n\n #[error(\"Internal hyperedge index {0} was not found\")]\n\n InternalHyperedgeIndexNotFound(usize),\n\n\n\n /// Error when a hyperedge weight was not found.\n", "file_path": "src/core/errors.rs", "rank": 61, "score": 29845.051588911512 }, { "content": " #[error(\"Hyperedge weight {0} was not found\")]\n\n HyperedgeWeightNotFound(HE),\n\n\n\n /// Error when a hyperedge is updated with the same weight.\n\n #[error(\"HyperedgeIndex {index:?} weight {weight:?} is unchanged (no-op)\")]\n\n HyperedgeWeightUnchanged { index: HyperedgeIndex, weight: HE },\n\n\n\n /// Error when a hyperedge is updated with the same vertices.\n\n #[error(\"HyperedgeIndex {0} vertices are unchanged (no-op)\")]\n\n HyperedgeVerticesUnchanged(HyperedgeIndex),\n\n\n\n /// Error when a hyperedge is updated with no vertices.\n\n #[error(\"HyperedgeIndex {0} vertices are missing\")]\n\n HyperedgeCreationNoVertices(HE),\n\n\n\n /// Error when a hyperedge is updated with no vertices.\n\n #[error(\"HyperedgeIndex {0} vertices are missing\")]\n\n HyperedgeUpdateNoVertices(HyperedgeIndex),\n\n\n\n /// Error when a hyperedge doesn't contain some vertices.\n", "file_path": "src/core/errors.rs", "rank": 62, "score": 29831.196025453733 }, { "content": " HyperedgesIntersections,\n\n\n\n /// Error when a VertexIndex was not found.\n\n #[error(\"VertexIndex {0} was not found\")]\n\n VertexIndexNotFound(VertexIndex),\n\n\n\n /// Error when a an internal vertex index was not found.\n\n #[error(\"Internal vertex index {0} was not found\")]\n\n InternalVertexIndexNotFound(usize),\n\n\n\n /// Error when a vertex weight was not found.\n\n #[error(\"Vertex weight {0} was not found\")]\n\n VertexWeightNotFound(V),\n\n\n\n /// Error when a vertex weight is updated with the same value.\n\n #[error(\"VertexIndex {index:?} weight {weight:?} unchanged (no-op)\")]\n\n VertexWeightUnchanged { index: VertexIndex, weight: V },\n\n\n\n /// Error when a vertex weight is updated with the weight of another one.\n\n #[error(\"Vertex weight {0} was already assigned\")]\n\n VertexWeightAlreadyAssigned(V),\n\n}\n", "file_path": "src/core/errors.rs", "rank": 63, "score": 29830.330937441737 }, { "content": " #[error(\"HyperedgeIndex {index:?} does not include vertices {vertices:?}\")]\n\n HyperedgeVerticesIndexesNotFound {\n\n index: HyperedgeIndex,\n\n vertices: Vec<VertexIndex>,\n\n },\n\n\n\n /// Error when a hyperedge contraction is invalid.\n\n #[error(\"HyperedgeIndex {index:?} contraction of vertices {vertices:?} into vertex {target:?} is invalid\" )]\n\n HyperedgeInvalidContraction {\n\n index: HyperedgeIndex,\n\n target: VertexIndex,\n\n vertices: Vec<VertexIndex>,\n\n },\n\n\n\n /// Error when a hyperedge is updated with the weight of another one.\n\n #[error(\"Hyperedge weight {0} was already assigned\")]\n\n HyperedgeWeightAlreadyAssigned(HE),\n\n\n\n /// Error when trying to get the intersections of less than two hyperedges.\n\n #[error(\"At least two hyperedges must be provided to find their intersections\")]\n", "file_path": "src/core/errors.rs", "rank": 64, "score": 29829.665751046017 }, { "content": "use crate::{errors::HypergraphError, HyperedgeIndex, Hypergraph, SharedTrait, VertexIndex};\n\n\n\nuse itertools::Itertools;\n\n\n\n/// Enumeration of the different types of connection.\n\n/// Only used as a guard argument for the `get_connections` method.\n\npub(crate) enum Connection<Index = VertexIndex> {\n\n In(Index),\n\n Out(Index),\n\n InAndOut(Index, Index),\n\n}\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Private helper function used internally.\n\n /// Takes a connection as an enum and returns a vector of tuples of the\n\n /// form (hyperedge index, connected vertex index) where connected vertex\n", "file_path": "src/core/shared.rs", "rank": 65, "score": 29757.969320042885 }, { "content": " .into_iter()\n\n .map(\n\n |hyperedge_index| match self.get_hyperedge_vertices(hyperedge_index) {\n\n Ok(vertices) => Ok((hyperedge_index, vertices)),\n\n Err(error) => Err(error),\n\n },\n\n )\n\n .collect::<Result<Vec<(HyperedgeIndex, Vec<VertexIndex>)>, HypergraphError<V, HE>>>()?;\n\n\n\n let results = hyperedges_with_vertices.into_iter().fold(\n\n Vec::new(),\n\n |acc: Vec<(HyperedgeIndex, Option<VertexIndex>)>, (hyperedge_index, vertices)| {\n\n vertices.iter().tuple_windows::<(_, _)>().fold(\n\n acc,\n\n |index_acc, (window_from, window_to)| {\n\n match connections {\n\n Connection::In(from) => {\n\n // Inject the index of the hyperedge and the\n\n // vertex index if the current window is a\n\n // match.\n", "file_path": "src/core/shared.rs", "rank": 66, "score": 29752.054562267298 }, { "content": " /// index is an optional value - None for InAndOut connections.\n\n #[allow(clippy::type_complexity)]\n\n pub(crate) fn get_connections(\n\n &self,\n\n connections: Connection,\n\n ) -> Result<Vec<(HyperedgeIndex, Option<VertexIndex>)>, HypergraphError<V, HE>> {\n\n let internal_index = self.get_internal_vertex(match connections {\n\n Connection::In(vertex_index) | Connection::Out(vertex_index) => vertex_index,\n\n Connection::InAndOut(vertex_index, _) => vertex_index,\n\n })?;\n\n\n\n let (_, hyperedges_index_set) = self\n\n .vertices\n\n .get_index(internal_index)\n\n .ok_or(HypergraphError::InternalVertexIndexNotFound(internal_index))?;\n\n\n\n let hyperedges =\n\n self.get_hyperedges(hyperedges_index_set.clone().into_iter().collect_vec())?;\n\n\n\n let hyperedges_with_vertices = hyperedges\n", "file_path": "src/core/shared.rs", "rank": 67, "score": 29749.300354131596 }, { "content": " // if the current window is a match.\n\n if *window_from == from && *window_to == to {\n\n return index_acc\n\n .into_iter()\n\n .chain(vec![(hyperedge_index, None)])\n\n .collect_vec();\n\n }\n\n }\n\n }\n\n\n\n index_acc\n\n },\n\n )\n\n },\n\n );\n\n\n\n Ok(results)\n\n }\n\n}\n", "file_path": "src/core/shared.rs", "rank": 68, "score": 29742.162828788027 }, { "content": " if *window_from == from {\n\n return index_acc\n\n .into_iter()\n\n .chain(vec![(hyperedge_index, Some(*window_to))])\n\n .collect_vec();\n\n }\n\n }\n\n Connection::Out(to) => {\n\n // Inject the index of the hyperedge and the\n\n // vertex index if the current window is a\n\n // match.\n\n if *window_to == to {\n\n return index_acc\n\n .into_iter()\n\n .chain(vec![(hyperedge_index, Some(*window_from))])\n\n .collect_vec();\n\n }\n\n }\n\n Connection::InAndOut(from, to) => {\n\n // Inject only the index of the hyperedge\n", "file_path": "src/core/shared.rs", "rank": 69, "score": 29740.166974382482 }, { "content": "#![deny(unsafe_code, nonstandard_style)]\n\n\n\nuse std::fmt::{Display, Formatter, Result};\n\n\n\n#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]\n\npub struct Vertex<'a> {\n\n name: &'a str,\n\n}\n\n\n\nimpl<'a> Vertex<'a> {\n\n pub fn new(name: &'a str) -> Self {\n\n Vertex { name }\n\n }\n\n}\n\n\n\nimpl<'a> Display for Vertex<'a> {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> Result {\n\n write!(f, \"{}\", self)\n\n }\n\n}\n", "file_path": "tests/common/mod.rs", "rank": 73, "score": 29612.180784567867 }, { "content": "use crate::SharedTrait;\n\n\n\nuse std::{collections::HashMap, fmt::Debug};\n\n\n\n/// Bi-directional hashmap used to store the mapping between the internal\n\n/// unstable indexes - generated by IndexMap and IndexSet - and the exposed\n\n/// stable indexes.\n\n#[derive(Debug)]\n\npub(crate) struct BiHashMap<Index>\n\nwhere\n\n Index: SharedTrait,\n\n{\n\n pub(crate) left: HashMap<usize, Index>,\n\n pub(crate) right: HashMap<Index, usize>,\n\n}\n\n\n\nimpl<Index> BiHashMap<Index>\n\nwhere\n\n Index: SharedTrait,\n\n{\n", "file_path": "src/core/bi_hash_map.rs", "rank": 77, "score": 27381.230602396383 }, { "content": " /// Creates a new BiHashMap with no allocation.\n\n pub(crate) fn new() -> BiHashMap<Index> {\n\n Self {\n\n left: HashMap::<usize, Index>::with_capacity(0),\n\n right: HashMap::<Index, usize>::with_capacity(0),\n\n }\n\n }\n\n}\n\n\n\nimpl<Index> Default for BiHashMap<Index>\n\nwhere\n\n Index: SharedTrait,\n\n{\n\n fn default() -> Self {\n\n BiHashMap::new()\n\n }\n\n}\n", "file_path": "src/core/bi_hash_map.rs", "rank": 78, "score": 27380.850014113763 }, { "content": "use crate::{errors::HypergraphError, Hypergraph, SharedTrait, VertexIndex};\n\n\n\nuse indexmap::IndexSet;\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Adds a vertex with a custom weight to the hypergraph.\n\n /// Returns the index of the vertex.\n\n pub fn add_vertex(&mut self, weight: V) -> Result<VertexIndex, HypergraphError<V, HE>> {\n\n // Return an error if the weight is already assigned to another vertex.\n\n if self.vertices.contains_key(&weight) {\n\n return Err(HypergraphError::VertexWeightAlreadyAssigned(weight));\n\n }\n\n\n\n self.vertices\n\n .entry(weight)\n\n .or_insert(IndexSet::with_capacity(0));\n", "file_path": "src/core/vertices/add_vertex.rs", "rank": 79, "score": 25634.580623755264 }, { "content": "use crate::{errors::HypergraphError, HyperedgeKey, Hypergraph, SharedTrait, VertexIndex};\n\n\n\nuse itertools::Itertools;\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Removes a vertex by index.\n\n pub fn remove_vertex(\n\n &mut self,\n\n vertex_index: VertexIndex,\n\n ) -> Result<(), HypergraphError<V, HE>> {\n\n let internal_index = self.get_internal_vertex(vertex_index)?;\n\n\n\n // Get the hyperedges of the vertex.\n\n let hyperedges = self.get_internal_hyperedges(self.get_vertex_hyperedges(vertex_index)?)?;\n\n\n\n // Remove the vertex from the hyperedges which contain it.\n", "file_path": "src/core/vertices/remove_vertex.rs", "rank": 80, "score": 25631.861364788747 }, { "content": "use crate::{errors::HypergraphError, Hypergraph, SharedTrait, VertexIndex};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n // Private method to get the VertexIndex matching an internal index.\n\n pub(crate) fn get_vertex(\n\n &self,\n\n vertex_index: usize,\n\n ) -> Result<VertexIndex, HypergraphError<V, HE>> {\n\n match self.vertices_mapping.left.get(&vertex_index) {\n\n Some(index) => Ok(*index),\n\n None => Err(HypergraphError::InternalVertexIndexNotFound(vertex_index)),\n\n }\n\n }\n\n}\n", "file_path": "src/core/vertices/get_vertex.rs", "rank": 81, "score": 25630.141160401956 }, { "content": " .hyperedges\n\n .get_index(hyperedge)\n\n .map(|hyperedge_key| hyperedge_key.to_owned())\n\n .ok_or(HypergraphError::InternalHyperedgeIndexNotFound(hyperedge))?;\n\n\n\n let updated_vertices = vertices\n\n .into_iter()\n\n .map(|vertex| {\n\n // Remap the vertex if this is the swapped one.\n\n if vertex == last_index {\n\n internal_index\n\n } else {\n\n vertex\n\n }\n\n })\n\n .collect_vec();\n\n\n\n // Insert the new entry with the updated vertices.\n\n // Since we are not altering the weight, we can safely perform\n\n // the operation without checking its output.\n", "file_path": "src/core/vertices/remove_vertex.rs", "rank": 82, "score": 25618.470317065112 }, { "content": " for hyperedge in hyperedges.into_iter() {\n\n let HyperedgeKey { vertices, .. } = self\n\n .hyperedges\n\n .get_index(hyperedge)\n\n .map(|hyperedge_key| hyperedge_key.to_owned())\n\n .ok_or(HypergraphError::InternalHyperedgeIndexNotFound(hyperedge))?;\n\n\n\n let hyperedge_index = self.get_hyperedge(hyperedge)?;\n\n\n\n // Get the unique vertices, i.e. check for self-loops.\n\n let unique_vertices = vertices.iter().sorted().dedup().collect_vec();\n\n\n\n // Remove the hyperedge if the vertex is the only one present.\n\n if unique_vertices.len() == 1 {\n\n self.remove_hyperedge(hyperedge_index)?;\n\n } else {\n\n // Otherwise update the hyperedge with the updated vertices.\n\n let updated_vertices = self.get_vertices(\n\n vertices\n\n .into_iter()\n", "file_path": "src/core/vertices/remove_vertex.rs", "rank": 83, "score": 25615.243829569125 }, { "content": " self.hyperedges.insert(HyperedgeKey {\n\n vertices: updated_vertices,\n\n weight,\n\n });\n\n\n\n // Swap and remove by index.\n\n // Since we know that the hyperedge index is correct, we can\n\n // safely perform the operation without checking its output.\n\n self.hyperedges.swap_remove_index(hyperedge);\n\n }\n\n }\n\n\n\n // Return a unit.\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/core/vertices/remove_vertex.rs", "rank": 84, "score": 25615.14331005148 }, { "content": "\n\n let internal_index = self\n\n .vertices\n\n .get_index_of(&weight)\n\n // This safe-check should always pass since the weight has been\n\n // inserted upfront.\n\n .ok_or(HypergraphError::VertexWeightNotFound(weight))?;\n\n\n\n Ok(self.add_vertex_index(internal_index))\n\n }\n\n}\n", "file_path": "src/core/vertices/add_vertex.rs", "rank": 85, "score": 25615.136019370733 }, { "content": " // method for more details about the internals.\n\n if internal_index != last_index {\n\n // Get the index of the swapped vertex.\n\n let swapped_vertex_index = self.get_vertex(last_index)?;\n\n\n\n // Proceed with the aforementioned operations.\n\n self.vertices_mapping\n\n .right\n\n .insert(swapped_vertex_index, internal_index);\n\n self.vertices_mapping.left.remove(&last_index);\n\n self.vertices_mapping\n\n .left\n\n .insert(internal_index, swapped_vertex_index);\n\n\n\n let stale_hyperedges =\n\n self.get_internal_hyperedges(self.get_vertex_hyperedges(swapped_vertex_index)?)?;\n\n\n\n // Update the impacted hyperedges accordingly.\n\n for hyperedge in stale_hyperedges.into_iter() {\n\n let HyperedgeKey { vertices, weight } = self\n", "file_path": "src/core/vertices/remove_vertex.rs", "rank": 86, "score": 25614.387474565374 }, { "content": " .filter(|vertex| *vertex != internal_index)\n\n .collect_vec(),\n\n )?;\n\n\n\n self.update_hyperedge_vertices(hyperedge_index, updated_vertices)?;\n\n }\n\n }\n\n\n\n // Find the last index.\n\n let last_index = self.vertices.len() - 1;\n\n\n\n // Swap and remove by index.\n\n self.vertices.swap_remove_index(internal_index);\n\n\n\n // Update the mapping for the removed vertex.\n\n self.vertices_mapping.left.remove(&internal_index);\n\n self.vertices_mapping.right.remove(&vertex_index);\n\n\n\n // If the index to remove wasn't the last one, the last vertex has\n\n // been swapped in place of the removed one. See the remove_hyperedge\n", "file_path": "src/core/vertices/remove_vertex.rs", "rank": 87, "score": 25612.511133766086 }, { "content": "use crate::{errors::HypergraphError, Hypergraph, SharedTrait, VertexIndex};\n\n\n\nuse std::{cmp::Ordering, collections::BinaryHeap, fmt::Debug};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Gets a list of the shortest path of vertices between two vertices.\n\n /// The implementation of the algorithm is based on\n\n /// <https://doc.rust-lang.org/std/collections/binary_heap/#examples>\n\n pub fn get_dijkstra_connections(\n\n &self,\n\n from: VertexIndex,\n\n to: VertexIndex,\n\n ) -> Result<Vec<VertexIndex>, HypergraphError<V, HE>> {\n\n #[derive(Clone, Copy, Debug, PartialEq, Eq)]\n\n struct Cursor {\n\n distance: usize,\n", "file_path": "src/core/vertices/get_dijkstra_connections.rs", "rank": 88, "score": 24609.786921681567 }, { "content": "use crate::{\n\n core::shared::Connection, errors::HypergraphError, Hypergraph, SharedTrait, VertexIndex,\n\n};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Gets the in-degree of a vertex.\n\n /// <https://en.wikipedia.org/wiki/Directed_graph#Indegree_and_outdegree>\n\n pub fn get_vertex_degree_in(&self, to: VertexIndex) -> Result<usize, HypergraphError<V, HE>> {\n\n let results = self.get_connections(Connection::Out(to))?;\n\n\n\n Ok(results.len())\n\n }\n\n}\n", "file_path": "src/core/vertices/get_vertex_degree_in.rs", "rank": 89, "score": 24601.614842835785 }, { "content": "use crate::{\n\n core::shared::Connection, errors::HypergraphError, Hypergraph, SharedTrait, VertexIndex,\n\n};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n /// Gets the out-degree of a vertex.\n\n /// <https://en.wikipedia.org/wiki/Directed_graph#Indegree_and_outdegree>\n\n pub fn get_vertex_degree_out(\n\n &self,\n\n from: VertexIndex,\n\n ) -> Result<usize, HypergraphError<V, HE>> {\n\n let results = self.get_connections(Connection::In(from))?;\n\n\n\n Ok(results.len())\n\n }\n\n}\n", "file_path": "src/core/vertices/get_vertex_degree_out.rs", "rank": 90, "score": 24601.614842835785 }, { "content": "use crate::{errors::HypergraphError, Hypergraph, SharedTrait, VertexIndex};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n // Private method to get the internal vertex matching a VertexIndex.\n\n pub(crate) fn get_internal_vertex(\n\n &self,\n\n vertex_index: VertexIndex,\n\n ) -> Result<usize, HypergraphError<V, HE>> {\n\n match self.vertices_mapping.right.get(&vertex_index) {\n\n Some(index) => Ok(*index),\n\n None => Err(HypergraphError::VertexIndexNotFound(vertex_index)),\n\n }\n\n }\n\n}\n", "file_path": "src/core/vertices/get_internal_vertex.rs", "rank": 91, "score": 24600.789434960203 }, { "content": "use crate::{Hypergraph, SharedTrait, VertexIndex};\n\n\n\nimpl<V, HE> Hypergraph<V, HE>\n\nwhere\n\n V: SharedTrait,\n\n HE: SharedTrait,\n\n{\n\n // This private method is infallible since adding the same vertex\n\n // will return the existing index.\n\n pub(crate) fn add_vertex_index(&mut self, internal_index: usize) -> VertexIndex {\n\n match self.vertices_mapping.left.get(&internal_index) {\n\n Some(vertex_index) => *vertex_index,\n\n None => {\n\n let vertex_index = VertexIndex(self.vertices_count);\n\n\n\n if self\n\n .vertices_mapping\n\n .left\n\n .insert(internal_index, vertex_index)\n\n .is_none()\n", "file_path": "src/core/vertices/add_vertex_index.rs", "rank": 92, "score": 24598.301670543577 }, { "content": " index: usize,\n\n }\n\n\n\n // Use a custom implementation of Ord as we want a min-heap BinaryHeap.\n\n impl Ord for Cursor {\n\n fn cmp(&self, other: &Cursor) -> Ordering {\n\n other\n\n .distance\n\n .cmp(&self.distance)\n\n .then_with(|| self.distance.cmp(&other.distance))\n\n }\n\n }\n\n\n\n impl PartialOrd for Cursor {\n\n fn partial_cmp(&self, other: &Cursor) -> Option<Ordering> {\n\n Some(self.cmp(other))\n\n }\n\n }\n\n\n\n // Get the internal indexes of the vertices.\n", "file_path": "src/core/vertices/get_dijkstra_connections.rs", "rank": 93, "score": 24590.699853271195 }, { "content": " let internal_from = self.get_internal_vertex(from)?;\n\n let internal_to = self.get_internal_vertex(to)?;\n\n\n\n // We need to initialize a vector of length equal to the number of vertices.\n\n // The default value, as per Dijkstra, must be set to infinity.\n\n // A value of usize::MAX is used.\n\n let mut distances = (0..self.vertices.len())\n\n .map(|_| usize::MAX)\n\n .collect::<Vec<usize>>();\n\n\n\n // Create an empty binary heap.\n\n let mut heap = BinaryHeap::new();\n\n\n\n // Initialize the first vertex to zero.\n\n distances[internal_from] = 0;\n\n\n\n // Push the first cursor to the heap.\n\n heap.push(Cursor {\n\n distance: 0,\n\n index: internal_from,\n", "file_path": "src/core/vertices/get_dijkstra_connections.rs", "rank": 94, "score": 24589.231564727448 }, { "content": " });\n\n\n\n // Keep track of the traversal path.\n\n let mut path = Vec::<usize>::new();\n\n\n\n while let Some(Cursor { distance, index }) = heap.pop() {\n\n // End of the traversal.\n\n if index == internal_to {\n\n // We need to inject the index of the target vertex.\n\n path.push(internal_to);\n\n\n\n // Remove duplicates generated during the iteration of the algorithm.\n\n path.dedup();\n\n\n\n return self.get_vertices(path);\n\n }\n\n\n\n // Skip if a better path has already been found.\n\n if distance > distances[index] {\n\n continue;\n", "file_path": "src/core/vertices/get_dijkstra_connections.rs", "rank": 95, "score": 24585.728628449444 }, { "content": " }\n\n\n\n let mapped_index = self.get_vertex(index)?;\n\n let indexes = self.get_adjacent_vertices_from(mapped_index)?;\n\n let internal_indexes = self.get_internal_vertices(indexes)?;\n\n\n\n // For every connected vertex, try to find the lowest distance.\n\n for vertex_index in internal_indexes {\n\n let next = Cursor {\n\n // We assume a distance of one by default since vertices\n\n // have custom weights.\n\n distance: distance + 1,\n\n index: vertex_index,\n\n };\n\n\n\n // If so, add it to the frontier and continue.\n\n if next.distance < distances[next.index] {\n\n // Update the traversal accordingly.\n\n path.push(index);\n\n\n", "file_path": "src/core/vertices/get_dijkstra_connections.rs", "rank": 96, "score": 24582.072860533957 }, { "content": " {\n\n // Update the counter only for the first insertion.\n\n self.vertices_count += 1;\n\n }\n\n\n\n self.vertices_mapping\n\n .right\n\n .insert(vertex_index, internal_index);\n\n\n\n vertex_index\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/core/vertices/add_vertex_index.rs", "rank": 97, "score": 24580.5448245351 }, { "content": " // Push it to the heap.\n\n heap.push(next);\n\n\n\n // Relaxation, we have now found a better way\n\n distances[vertex_index] = next.distance;\n\n }\n\n }\n\n }\n\n\n\n // If we reach this point, return an empty vector.\n\n Ok(vec![])\n\n }\n\n}\n", "file_path": "src/core/vertices/get_dijkstra_connections.rs", "rank": 98, "score": 24577.524925457998 }, { "content": "//! - Stable indexes assigned for each hyperedge and each vertex\n\n//!\n\n//! ## Example\n\n//!\n\n//! Please notice that the hyperedges and the vertices must implement the [SharedTrait](crate::SharedTrait).\n\n//!\n\n//! ```\n\n//! use hypergraph::{HyperedgeIndex, Hypergraph, VertexIndex};\n\n//! use std::fmt::{Display, Formatter, Result};\n\n//!\n\n//! // Create a new struct to represent a vertex.\n\n//! #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]\n\n//! struct Vertex<'a> {\n\n//! name: &'a str,\n\n//! }\n\n//!\n\n//! impl<'a> Vertex<'a> {\n\n//! pub fn new(name: &'a str) -> Self {\n\n//! Vertex { name }\n\n//! }\n", "file_path": "src/lib.rs", "rank": 99, "score": 37.83487243128075 } ]
Rust
src/basic/model.rs
nyari/rtrace
2321a0a50c10940c58a690c678df8f939d5b22fc
use core::{Model, Material, RayIntersection, Ray, RayIntersectionError}; use defs::{Point3, Vector3, FloatType}; use tools::{CompareWithTolerance}; use na; use na::{Unit}; use std; use uuid::{Uuid}; pub struct SolidSphere { material: Material, origo: Point3, radius: FloatType, identifier: Uuid } impl SolidSphere { pub fn new(material: Material) -> Self { Self { material: material, origo: Point3::new(0.0, 0.0, 0.0), radius: 1.0, identifier: Uuid::new_v4()} } pub fn new_positioned(material: Material, origo: Point3, radius: FloatType) -> Self { Self { material: material, origo: origo, radius: radius, identifier: Uuid::new_v4()} } pub fn set_custom_identifier(&mut self, identifier: Uuid) { self.identifier = identifier; } } impl Model for SolidSphere { fn get_intersection(&self, ray: &Ray) -> Option<RayIntersection> { let dir = ray.get_direction(); let origin = ray.get_origin(); let ray_origo = origin - self.origo; let a = dir.x.powi(2) + dir.y.powi(2) + dir.z.powi(2); let b = 2.0 * (ray_origo.x * dir.x + ray_origo.y * dir.y + ray_origo.z * dir.z); let c = ray_origo.x.powi(2) + ray_origo.y.powi(2) + ray_origo.z.powi(2) - self.radius.powi(2); let determinant = b.powi(2) - 4.0 * a * c; if determinant.less_eps(&0.0) { None } else { let t1 = (-b + determinant.sqrt()) / (2.0 * a); let t2 = (-b - determinant.sqrt()) / (2.0 * a); let result_calc = |t, inside: bool| { let intersection_point = origin + dir * t; let normal = if !inside { intersection_point - self.origo } else { self.origo - intersection_point }; match RayIntersection::new_model_identifier(normal, intersection_point, ray, self.material, inside, self.identifier) { Ok(intersection) => Some(intersection), Err(RayIntersectionError::NoRayTravelDistance) => None, _ => panic!("Unrecoverable RayIntersectin:new_model_identifier error") } }; if t1.is_sign_negative() && t2.is_sign_negative() { None } else if t1.is_sign_positive() && t2.is_sign_negative() { result_calc(t1, true) } else { match result_calc(t2, false) { Some(result) => Some(result), None => result_calc(t1, true), } } } } } pub struct SolidPlane { material: Material, base: Point3, normal: Vector3, identifier: Uuid, } impl SolidPlane { pub fn new(material: Material) -> Self { Self { material: material, base: Point3::origin(), normal: Vector3::new(0.0, 0.0, 1.0), identifier: Uuid::new_v4() } } pub fn new_positioned(material: Material, base: Point3, normal: Unit<Vector3>) -> Self { Self { material: material, base: base, normal: normal.unwrap(), identifier: Uuid::new_v4() } } pub fn set_custom_identifier(&mut self, identifier: Uuid) { self.identifier = identifier; } } impl Model for SolidPlane { fn get_intersection(&self, ray: &Ray) -> Option<RayIntersection> { let origin = ray.get_origin(); let dir = ray.get_direction(); let u = self.normal.dot(dir); if !u.near_zero_eps() { let k = self.normal.x * self.base.x + self.normal.y * self.base.y + self.normal.z * self.base.z; let s = self.normal.x * origin.x + self.normal.y * origin.y + self.normal.z * origin.z; let t = (k-s) / u; if t.greater_eq_eps(&0.0) { let is_inside = na::angle(&self.normal, dir).less_eq_eps(&std::f64::consts::FRAC_PI_2); let point = origin + dir * t; if !is_inside { match RayIntersection::new_model_identifier(self.normal, point, ray, self.material, is_inside, self.identifier) { Ok(intersection) => Some(intersection), Err(RayIntersectionError::NoRayTravelDistance) => None, _ => panic!("Unrecoverable RayIntersectin:new_model_identifier error") } } else { match RayIntersection::new_model_identifier(-self.normal, point, ray, self.material, is_inside, self.identifier) { Ok(intersection) => Some(intersection), Err(RayIntersectionError::NoRayTravelDistance) => None, _ => panic!("Unrecoverable RayIntersectin:new_model_identifier error") } } } else { None } } else { None } } } #[cfg(test)] mod tests { use super::*; use core::Color; fn test_solid_unit_sphere(test_ray: &Ray, expected_result: Option<&Point3>) { let test_material = Material::new_shiny(Color::new(1.0, 1.0, 1.0), (Color::new(1.0, 1.0, 1.0), 1.5), None); let test_sphere = SolidSphere::new(test_material); let intersection_result = test_sphere.get_intersection(test_ray); match expected_result { Some(expected_point) => { let intersection = intersection_result.expect("Was expected intersection but none intersected"); assert_relative_eq!(expected_point, intersection.get_intersection_point()); }, None => { assert!(intersection_result.is_none()); } } } #[test] fn test_solid_unit_sphere_head_on() { let test_ray = Ray::new_single_shot(Point3::new(2.0, 0.0, 0.0), Vector3::new(-1.0, 0.0, 0.0)); test_solid_unit_sphere(&test_ray, Some(&Point3::new(1.0, 0.0, 0.0))); } #[test] fn test_solid_unit_sphere_tangential_hit() { let test_ray = Ray::new_single_shot(Point3::new(2.0, 0.0, 1.0), Vector3::new(-1.0, 0.0, 0.0)); test_solid_unit_sphere(&test_ray, Some(&Point3::new(0.0, 0.0, 1.0))); } #[test] fn test_solid_unit_sphere_tangential_miss() { let test_ray = Ray::new_single_shot(Point3::new(2.0, 0.0, 1.01), Vector3::new(-1.0, 0.0, 0.0)); test_solid_unit_sphere(&test_ray, None); } }
use core::{Model, Material, RayIntersection, Ray, RayIntersectionError}; use defs::{Point3, Vector3, FloatType}; use tools::{CompareWithTolerance}; use na; use na::{Unit}; use std; use uuid::{Uuid}; pub struct SolidSphere { material: Material, origo: Point3, radius: FloatType, identifier: Uuid } impl SolidSphere { pub fn new(material: Material) -> Self { Self { material: material, origo: Point3::new(0.0, 0.0, 0.0), radius: 1.0, identifier: Uuid::new_v4()} } pub fn new_positioned(material: Material, origo: Point3, radius: FloatType) -> Self { Self { material: material, origo: origo, radius: radius, identifier: Uuid::new_v4()} } pub fn set_custom_identifier(&mut self, identifier: Uuid) { self.identifier = identifier; } } impl Model for SolidSphere { fn get_intersection(&self, ray: &Ray) -> Option<RayIntersection> { let dir = ray.get_direction(); let origin = ray.get_origin(); let ray_origo = origin - self.origo; let a = dir.x.powi(2) + dir.y.powi(2) + dir.z.powi(2); let b = 2.0 * (ray_origo.x * dir.x + ray_origo.y * dir.y + ray_origo.z * dir.z)
None); } }
; let c = ray_origo.x.powi(2) + ray_origo.y.powi(2) + ray_origo.z.powi(2) - self.radius.powi(2); let determinant = b.powi(2) - 4.0 * a * c; if determinant.less_eps(&0.0) { None } else { let t1 = (-b + determinant.sqrt()) / (2.0 * a); let t2 = (-b - determinant.sqrt()) / (2.0 * a); let result_calc = |t, inside: bool| { let intersection_point = origin + dir * t; let normal = if !inside { intersection_point - self.origo } else { self.origo - intersection_point }; match RayIntersection::new_model_identifier(normal, intersection_point, ray, self.material, inside, self.identifier) { Ok(intersection) => Some(intersection), Err(RayIntersectionError::NoRayTravelDistance) => None, _ => panic!("Unrecoverable RayIntersectin:new_model_identifier error") } }; if t1.is_sign_negative() && t2.is_sign_negative() { None } else if t1.is_sign_positive() && t2.is_sign_negative() { result_calc(t1, true) } else { match result_calc(t2, false) { Some(result) => Some(result), None => result_calc(t1, true), } } } } } pub struct SolidPlane { material: Material, base: Point3, normal: Vector3, identifier: Uuid, } impl SolidPlane { pub fn new(material: Material) -> Self { Self { material: material, base: Point3::origin(), normal: Vector3::new(0.0, 0.0, 1.0), identifier: Uuid::new_v4() } } pub fn new_positioned(material: Material, base: Point3, normal: Unit<Vector3>) -> Self { Self { material: material, base: base, normal: normal.unwrap(), identifier: Uuid::new_v4() } } pub fn set_custom_identifier(&mut self, identifier: Uuid) { self.identifier = identifier; } } impl Model for SolidPlane { fn get_intersection(&self, ray: &Ray) -> Option<RayIntersection> { let origin = ray.get_origin(); let dir = ray.get_direction(); let u = self.normal.dot(dir); if !u.near_zero_eps() { let k = self.normal.x * self.base.x + self.normal.y * self.base.y + self.normal.z * self.base.z; let s = self.normal.x * origin.x + self.normal.y * origin.y + self.normal.z * origin.z; let t = (k-s) / u; if t.greater_eq_eps(&0.0) { let is_inside = na::angle(&self.normal, dir).less_eq_eps(&std::f64::consts::FRAC_PI_2); let point = origin + dir * t; if !is_inside { match RayIntersection::new_model_identifier(self.normal, point, ray, self.material, is_inside, self.identifier) { Ok(intersection) => Some(intersection), Err(RayIntersectionError::NoRayTravelDistance) => None, _ => panic!("Unrecoverable RayIntersectin:new_model_identifier error") } } else { match RayIntersection::new_model_identifier(-self.normal, point, ray, self.material, is_inside, self.identifier) { Ok(intersection) => Some(intersection), Err(RayIntersectionError::NoRayTravelDistance) => None, _ => panic!("Unrecoverable RayIntersectin:new_model_identifier error") } } } else { None } } else { None } } } #[cfg(test)] mod tests { use super::*; use core::Color; fn test_solid_unit_sphere(test_ray: &Ray, expected_result: Option<&Point3>) { let test_material = Material::new_shiny(Color::new(1.0, 1.0, 1.0), (Color::new(1.0, 1.0, 1.0), 1.5), None); let test_sphere = SolidSphere::new(test_material); let intersection_result = test_sphere.get_intersection(test_ray); match expected_result { Some(expected_point) => { let intersection = intersection_result.expect("Was expected intersection but none intersected"); assert_relative_eq!(expected_point, intersection.get_intersection_point()); }, None => { assert!(intersection_result.is_none()); } } } #[test] fn test_solid_unit_sphere_head_on() { let test_ray = Ray::new_single_shot(Point3::new(2.0, 0.0, 0.0), Vector3::new(-1.0, 0.0, 0.0)); test_solid_unit_sphere(&test_ray, Some(&Point3::new(1.0, 0.0, 0.0))); } #[test] fn test_solid_unit_sphere_tangential_hit() { let test_ray = Ray::new_single_shot(Point3::new(2.0, 0.0, 1.0), Vector3::new(-1.0, 0.0, 0.0)); test_solid_unit_sphere(&test_ray, Some(&Point3::new(0.0, 0.0, 1.0))); } #[test] fn test_solid_unit_sphere_tangential_miss() { let test_ray = Ray::new_single_shot(Point3::new(2.0, 0.0, 1.01), Vector3::new(-1.0, 0.0, 0.0)); test_solid_unit_sphere(&test_ray,
random
[ { "content": "pub trait Model: Send + Sync {\n\n fn get_intersection(&self, ray: &Ray) -> Option<RayIntersection>;\n\n}\n\n\n\npub struct ModelViewModelWrapper<T: Model> {\n\n wrapped_model: T,\n\n tf_matrix: Matrix4,\n\n inverse_tf_matrix: Matrix4\n\n}\n\n\n\nimpl<T: Model> ModelViewModelWrapper<T> {\n\n pub fn new(model: T, model_view_matrix: Matrix4) -> Self {\n\n Self { wrapped_model: model,\n\n inverse_tf_matrix: model_view_matrix.try_inverse().expect(\"Uninvertable Model View Matrix\"),\n\n tf_matrix: model_view_matrix\n\n }\n\n }\n\n\n\n pub fn new_identity(model: T) -> Self {\n\n Self { wrapped_model: model,\n", "file_path": "src/core/model.rs", "rank": 0, "score": 80912.9031832758 }, { "content": "#[derive(Clone, Copy, Debug)]\n\nstruct RayState {\n\n distance_to_origin : FloatType,\n\n depth_counter : i32,\n\n depth_limit: Option<u32>,\n\n}\n\n\n\nimpl RayState {\n\n pub fn get_continuation(input: &Self, distance_to_intersection: FloatType) -> Result<Self, RayError> {\n\n match input.depth_limit {\n\n Some(depth_limit) => {\n\n if depth_limit >= 1 {\n\n Ok (Self { distance_to_origin: input.distance_to_origin + distance_to_intersection,\n\n depth_counter: input.depth_counter + 1,\n\n depth_limit: Some(depth_limit - 1),\n\n ..*input\n\n })\n\n } else {\n\n Err(RayError::DepthLimitReached)\n\n }\n\n },\n", "file_path": "src/core/ray.rs", "rank": 1, "score": 80476.82722555535 }, { "content": "#[derive(Debug, Copy, Clone)]\n\nstruct FresnelData {\n\n pub n: FresnelIndex,\n\n pub n_inverse: FresnelIndex,\n\n pub n_avg: FloatType,\n\n pub n_imaginary: FresnelIndex,\n\n pub n_imaginary_inverse: FresnelIndex,\n\n pub n_imaginary_avg: FloatType,\n\n pub f0: FresnelIndex,\n\n pub f0_avg: FloatType,\n\n pub f0_inverse: FresnelIndex,\n\n pub f0_inverse_avg: FloatType\n\n}\n\n\n\nimpl FresnelData {\n\n fn new(real: FresnelIndex, imaginary: FresnelIndex) -> Self {\n\n let mut f0 = ((real - FresnelIndex::one()) * (real - FresnelIndex::one())) + imaginary * imaginary;\n\n f0 *= (((real + FresnelIndex::one()) * (real + FresnelIndex::one())) + imaginary * imaginary).recip();\n\n\n\n let mut f0_inverse = ((imaginary - FresnelIndex::one()) * (imaginary - FresnelIndex::one())) + imaginary * imaginary;\n\n f0_inverse *= (((imaginary + FresnelIndex::one()) * (imaginary + FresnelIndex::one())) + imaginary * imaginary).recip(); \n", "file_path": "src/core/material.rs", "rank": 2, "score": 71990.14834633234 }, { "content": "pub trait Vector3Extensions {\n\n fn same_direction_as(&self, rhs: &Vector3) -> bool;\n\n fn length(&self) -> FloatType;\n\n}\n\n\n\nimpl Vector3Extensions for Vector3 {\n\n fn same_direction_as(&self, rhs: &Vector3) -> bool {\n\n let closed_angle = na::angle(self, &rhs);\n\n closed_angle.near_zero_eps()\n\n }\n\n\n\n fn length(&self) -> FloatType {\n\n let mut result: FloatType = 0.0;\n\n\n\n for item in self.iter() {\n\n result += item.powi(2);\n\n }\n\n\n\n result.sqrt()\n\n }\n\n}\n\n\n\n\n", "file_path": "src/tools.rs", "rank": 3, "score": 63772.52006160385 }, { "content": "pub trait Intersector: Send + Sync { \n\n fn get_intersections_reverse_ordered(&self, ray: &Ray) -> Vec<RayIntersection>;\n\n fn get_nearest_intersection(&self, ray: &Ray) -> Option<RayIntersection>;\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use core::{Material};\n\n use defs::{Point3};\n\n use std;\n\n\n\n struct DummyModel {\n\n\n\n }\n\n\n\n impl DummyModel {\n\n pub fn new() -> Self {\n\n Self {\n", "file_path": "src/core/model.rs", "rank": 4, "score": 56917.00136309267 }, { "content": "pub trait RayCaster: Send + Sync {\n\n fn cast_ray(&self, ray: &Ray) -> Option<Color>;\n\n fn cast_colored_light_ray(&self, ray: &Ray, intersection: &RayIntersection) -> Option<Color>;\n\n fn cast_model_ray(&self, ray: &Ray) -> Option<RayIntersection>;\n\n}\n\n\n", "file_path": "src/core/world.rs", "rank": 5, "score": 55142.77990105537 }, { "content": "struct OrderedTaskIteratorInternals {\n\n pub producers : Vec<Box<RenderingTaskProducer>>,\n\n pub current_terator : Option<Box<ThreadSafeIterator<Item=Box<RenderingTask>>>>\n\n}\n\n\n\nimpl OrderedTaskIteratorInternals {\n\n pub fn new(mut producers : Vec<Box<RenderingTaskProducer>>) -> Self {\n\n producers.reverse();\n\n if let Some(first_producer) = producers.pop() {\n\n Self {\n\n producers: producers,\n\n current_terator: Some(first_producer.create_task_iterator())\n\n }\n\n } else {\n\n Self {\n\n producers: producers,\n\n current_terator: None\n\n }\n\n }\n\n }\n", "file_path": "src/core/execution.rs", "rank": 6, "score": 43371.12808317646 }, { "content": "struct GlobalIlluminationShaderState {\n\n pub buffer: Vec<Option<UuidColor>>,\n\n pub visible: HashSet<Uuid>\n\n}\n\n\n\nimpl GlobalIlluminationShaderState {\n\n pub fn new(input: Vec<Option<UuidColor>>) -> Self {\n\n Self {\n\n buffer: input,\n\n visible: HashSet::new()\n\n }\n\n }\n\n\n\n pub fn set_color(&mut self, index: usize, input: UuidColor) {\n\n self.visible.insert(input.id.clone());\n\n self.buffer[index] = Some(input);\n\n }\n\n}\n\n\n\npub struct GlobalIlluminationShader {\n", "file_path": "src/basic/postprocessing/gi.rs", "rank": 7, "score": 42357.04760783042 }, { "content": "pub trait OrderingQuery {\n\n fn is_less(self) -> bool;\n\n fn is_equal(self) -> bool;\n\n fn is_greater(self) -> bool;\n\n}\n\n\n\nimpl OrderingQuery for Ordering {\n\n fn is_less(self) -> bool {\n\n match self {\n\n Ordering::Less => true,\n\n _ => false\n\n }\n\n }\n\n\n\n fn is_equal(self) -> bool {\n\n match self {\n\n Ordering::Equal => true,\n\n _ => false\n\n }\n\n }\n\n\n\n fn is_greater(self) -> bool {\n\n match self {\n\n Ordering::Greater => true,\n\n _ => false\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/tools.rs", "rank": 8, "score": 37086.61993239532 }, { "content": "pub trait Between<T: Num> {\n\n fn between(&self, less: &T, more: &T) -> bool;\n\n}\n\n\n\nimpl Between<FloatType> for FloatType {\n\n fn between(&self, less: &FloatType, more: &FloatType) -> bool {\n\n less.greater_eq_eps(&self) && more.less_eq_eps(&self)\n\n }\n\n}\n\n\n\nimpl Between<IntType> for IntType {\n\n fn between(&self, less: &IntType, more: &IntType) -> bool {\n\n less <= self && self <= more\n\n }\n\n}", "file_path": "src/tools.rs", "rank": 9, "score": 35415.056949093836 }, { "content": "pub trait Scene: Send + Sync {\n\n fn get_pixel_color(&self, pixel: Point2Int) -> Result<Color, SceneError>;\n\n fn get_pixel_intersection(&self, pixel: Point2Int) -> Result<RayIntersection, SceneError>;\n\n fn get_view(&self) -> &View;\n\n fn get_ray_caster(&self) -> &RayCaster;\n\n fn get_illumination_caster(&self) -> &IlluminationCaster;\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum SceneBufferError {\n\n InvalidInputCoord,\n\n MutexLockError,\n\n OtherBufferNotSameSize\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum SceneBufferLayering {\n\n Under,\n\n Over\n\n}\n\n\n", "file_path": "src/core/scene.rs", "rank": 10, "score": 33135.372075716026 }, { "content": "pub trait Illuminator: Send + Sync {\n\n fn get_illumination_at(&self, intersection: &RayIntersection, illumination_caster: &RayCaster) -> Vec<LightIntersection>;\n\n}", "file_path": "src/core/light.rs", "rank": 11, "score": 33135.372075716026 }, { "content": "pub trait CompareWithTolerance<T: Float> {\n\n fn compare_eps(&self, rhs: &T) -> Ordering;\n\n fn less_eps(&self, rhs: &T) -> bool;\n\n fn less_eq_eps(&self, rhs: &T) -> bool;\n\n fn equal_eps(&self, rhs: &T) -> bool;\n\n fn greater_eps(&self, rhs: &T) -> bool;\n\n fn greater_eq_eps(&self, rhs: &T) -> bool;\n\n fn near_zero_eps(&self) -> bool;\n\n}\n\n\n\nimpl CompareWithTolerance<FloatType> for FloatType {\n\n fn compare_eps(&self, rhs: &FloatType) -> Ordering {\n\n self.approx_cmp_ulps(&rhs, FLOAT_ULPS_TOLERANCE)\n\n }\n\n\n\n fn less_eps(&self, rhs: &FloatType) -> bool {\n\n self.approx_cmp_ulps(&rhs, FLOAT_ULPS_TOLERANCE) == Ordering::Less\n\n }\n\n\n\n fn less_eq_eps(&self, rhs: &FloatType) -> bool {\n", "file_path": "src/tools.rs", "rank": 12, "score": 33135.372075716026 }, { "content": "pub trait RenderingTask: Send + Sync {\n\n fn execute(self: Box<Self>);\n\n}\n\n\n", "file_path": "src/core/execution.rs", "rank": 13, "score": 32138.37131194181 }, { "content": "pub trait ColorCalculator: Send + Sync {\n\n fn get_color(&self, itersection: &RayIntersection, ray_caster: &RayCaster, illumination_caster: &IlluminationCaster) -> Option<Color>;\n\n}\n\n\n\npub struct World<IntersectorType, ColorCalculatorType, IlluminatorType> {\n\n intersector : IntersectorType,\n\n color_calculator : ColorCalculatorType,\n\n illuminator: IlluminatorType,\n\n depth_limit : i32,\n\n}\n\n\n\nimpl<IntersectorType: Intersector + Send + Sync,\n\n ColorCalculatorType: ColorCalculator + Send + Sync,\n\n IlluminatorType : Illuminator + Send + Sync> \n\n World<IntersectorType, ColorCalculatorType, IlluminatorType> {\n\n \n\n pub fn new(intersector: IntersectorType, colorcalc: ColorCalculatorType, illuminator: IlluminatorType, ray_depth_limit: i32) -> Self {\n\n Self {intersector: intersector,\n\n color_calculator: colorcalc,\n\n illuminator: illuminator,\n", "file_path": "src/core/world.rs", "rank": 14, "score": 32138.37131194181 }, { "content": "pub trait IlluminationCaster: Send + Sync {\n\n fn get_illumination_at(&self, intersection: &RayIntersection) -> Vec<LightIntersection>;\n\n}\n\n\n", "file_path": "src/core/world.rs", "rank": 15, "score": 32138.37131194181 }, { "content": "pub trait LightSource: Send + Sync {\n\n fn get_ray_to_intersection(&self, intersection: &RayIntersection) -> Option<Ray>;\n\n fn get_illumination_at(&self, intersection: &RayIntersection) -> Option<LightIntersection>;\n\n fn get_intersection(&self, ray: &Ray) -> Option<LightIntersection>;\n\n}\n\n\n", "file_path": "src/core/light.rs", "rank": 16, "score": 32138.37131194181 }, { "content": "pub trait ThreadSafeIterator: Send + Sync {\n\n type Item;\n\n\n\n fn next(&self) -> Option<Self::Item>;\n\n}\n\n\n", "file_path": "src/core/execution.rs", "rank": 17, "score": 31221.324790793806 }, { "content": "pub trait RenderingTaskProducer: Send + Sync {\n\n fn create_task_iterator(self: Box<Self>) -> Box<ThreadSafeIterator<Item=Box<RenderingTask>>>;\n\n}\n\n\n\npub struct OrderedTaskProducers {\n\n producers: Option<Vec<Box<RenderingTaskProducer>>>\n\n}\n\n\n\nimpl OrderedTaskProducers {\n\n pub fn new(producers: Vec<Box<RenderingTaskProducer>>) -> Box<RenderingTaskProducer> {\n\n Box::new(Self {\n\n producers: Some(producers)\n\n })\n\n }\n\n}\n\n\n\nimpl RenderingTaskProducer for OrderedTaskProducers {\n\n fn create_task_iterator(mut self: Box<Self>) -> Box<ThreadSafeIterator<Item=Box<RenderingTask>>> {\n\n Box::new(OrderedTaskIterator::new(self.producers.take().expect(\"OrderedTaskProducers should have not been created empty\")))\n\n }\n\n}\n\n\n\n\n", "file_path": "src/core/execution.rs", "rank": 18, "score": 31221.324790793806 }, { "content": "pub trait ImmutableSceneBuffer: Send + Sync {\n\n fn get_pixel_value(&self, pixel: Point2Int) -> Result<Option<Color>, SceneBufferError>;\n\n fn get_screen(&self) -> &Screen;\n\n\n\n fn is_same_size_buffer(&self, rhs: &ImmutableSceneBuffer) -> bool {\n\n self.get_screen().get_resolution() == rhs.get_screen().get_resolution()\n\n }\n\n}\n\n\n", "file_path": "src/core/scene.rs", "rank": 19, "score": 31221.324790793806 }, { "content": "pub trait WorldViewTrait: Scene + SceneBuffer {\n\n\n\n}\n\n\n\npub struct WorldView<WorldT> {\n\n world: Arc<WorldT>,\n\n view: View,\n\n result_buffer: BasicSceneBuffer,\n\n}\n\n\n\nimpl<WorldT> WorldView<WorldT>\n\n where WorldT: RayCaster + IlluminationCaster + Send + Sync\n\n{\n\n #[allow(dead_code)]\n\n pub fn new(world: WorldT, view: View) -> Self {\n\n let screen_clone = view.get_screen().clone();\n\n Self { world: Arc::new(world),\n\n view: view,\n\n result_buffer: BasicSceneBuffer::new(screen_clone) }\n\n }\n", "file_path": "src/core/worldview.rs", "rank": 20, "score": 30374.985428502172 }, { "content": " pub fn get_depth_counter(&self) -> i32 {\n\n self.depth_counter\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct Ray {\n\n direction : Unit<Vector3>,\n\n origin : Point3,\n\n state : RayState,\n\n mediums : Option<VecDeque<Material>>, \n\n}\n\n\n\nimpl Ray {\n\n pub fn new(origin: Point3, dir: Vector3) -> Self {\n\n Self { direction: Unit::new_normalize(dir),\n\n origin: origin,\n\n mediums: None,\n\n state: RayState { distance_to_origin: 0.0,\n\n depth_counter: 0,\n", "file_path": "src/core/ray.rs", "rank": 21, "score": 29102.02886649265 }, { "content": "use defs::{Vector3, Point3, FloatType, Matrix4};\n\nuse std::collections::{VecDeque};\n\nuse core::{RayIntersection, Material};\n\nuse tools::Vector3Extensions;\n\nuse na::{Unit};\n\n\n\n\n\n#[derive(Debug)]\n\npub enum RayError {\n\n DepthLimitReached,\n\n InvalidContinuationDirection,\n\n}\n\n\n\n\n\n#[derive(Clone, Copy, Debug)]\n", "file_path": "src/core/ray.rs", "rank": 22, "score": 29098.02411890841 }, { "content": " depth_limit: None }\n\n }\n\n }\n\n\n\n pub fn new_depth_limited(origin: Point3, dir: Vector3, depth_limit: u32) -> Self {\n\n Self { direction: Unit::new_normalize(dir),\n\n origin: origin,\n\n mediums: None,\n\n state: RayState { distance_to_origin: 0.0,\n\n depth_counter: 0,\n\n depth_limit: Some(depth_limit) }\n\n }\n\n }\n\n\n\n pub fn new_single_shot(origin: Point3, dir: Vector3) -> Self {\n\n Self::new_depth_limited(origin, dir, 1)\n\n }\n\n\n\n pub fn set_maximum_depth_limited(&self, maximum_depth_limit: u32) -> Self {\n\n Self {\n", "file_path": "src/core/ray.rs", "rank": 23, "score": 29097.700837259017 }, { "content": " pub fn new_reversed_ray(ray: &Ray) -> Self {\n\n Self { direction: (-ray.direction),\n\n ..ray.clone() }\n\n }\n\n\n\n pub fn get_transformed(&self, transformation_matrix: &Matrix4) -> Self {\n\n let origin = self.origin.to_homogeneous();\n\n let direction = self.direction.to_homogeneous();\n\n\n\n Self { origin: Point3::from_homogeneous(transformation_matrix * origin).expect(\"Unhomogeneous transformed point\"),\n\n direction: Unit::new_normalize(Vector3::from_homogeneous(transformation_matrix * direction).expect(\"Unhomogeneous transformed vector\")),\n\n ..self.clone()\n\n }\n\n }\n\n\n\n pub fn get_origin(&self) -> &Point3 {\n\n &self.origin\n\n }\n\n\n\n pub fn get_direction(&self) -> &Vector3 {\n", "file_path": "src/core/ray.rs", "rank": 24, "score": 29095.925952724756 }, { "content": " }\n\n\n\n pub fn continue_ray_from_previous(previous_ray: &Ray, origin: Point3, direction: Vector3) -> Result<Self, RayError> {\n\n let calculated_direction = origin - previous_ray.get_origin();\n\n\n\n match RayState::get_continuation(&previous_ray.state, calculated_direction.length()) {\n\n Ok (continued_state) => {\n\n Ok (Self { direction: Unit::new_normalize(direction),\n\n origin: origin,\n\n state: continued_state,\n\n ..previous_ray.clone()})\n\n },\n\n Err(e) => Err(e)\n\n }\n\n }\n\n\n\n fn get_state(&self) -> &RayState {\n\n &self.state\n\n }\n\n\n", "file_path": "src/core/ray.rs", "rank": 25, "score": 29092.606918580026 }, { "content": " }\n\n }\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use core::{RayIntersection, Material};\n\n\n\n #[test]\n\n fn test_ray_new1_assignment() {\n\n let test_ray = Ray::new(Point3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 0.0));\n\n\n\n assert_eq!(test_ray.get_distance_to_origin(), 0.0);\n\n assert_eq!(test_ray.get_depth_counter(), 0);\n\n }\n\n\n\n #[test]\n\n fn test_continue_ray_from_intersection() {\n", "file_path": "src/core/ray.rs", "rank": 26, "score": 29092.561495760012 }, { "content": " let initial_ray = Ray::new(Point3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 0.0));\n\n let intersection = RayIntersection::new(Vector3::new(0.0, 0.0, 1.0),\n\n Point3::new(1.0, 0.0, 0.0),\n\n &initial_ray,\n\n Material::new_useless(),\n\n false).unwrap();\n\n let continued_ray = Ray::continue_ray_from_intersection(&intersection, Vector3::new(0.0, 1.0, 0.0)).unwrap();\n\n\n\n assert_eq!(continued_ray.get_depth_counter(), 1);\n\n assert_eq!(continued_ray.get_distance_to_origin(), 1.0);\n\n }\n\n\n\n #[test]\n\n fn test_depth_limits() {\n\n let initial_ray = Ray::new_depth_limited(Point3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 0.0), 1);\n\n let continue_1 = Ray::continue_ray_from_previous(&initial_ray, Point3::new(1.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 0.0)).expect(\"Ray should still continue\");\n\n let continue_2 = Ray::continue_ray_from_previous(&continue_1, Point3::new(2.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 0.0));\n\n if !continue_2.is_err() {\n\n panic!(\"Ray should not continue further\");\n\n }\n\n }\n\n}\n", "file_path": "src/core/ray.rs", "rank": 27, "score": 29090.91059908333 }, { "content": " } else {\n\n result.push_medium(*intersection.get_material());\n\n }\n\n\n\n Ok(result)\n\n },\n\n Err(e) => Err(e)\n\n }\n\n }\n\n\n\n pub fn continue_ray_from_intersection(intersection: &RayIntersection, direction: Vector3) -> Result<Self, RayError> {\n\n match RayState::get_continuation(intersection.get_intersector_ray().get_state(), intersection.get_distance_to_intersection()) {\n\n Ok (continued_state) => {\n\n Ok (Self { direction: Unit::new_normalize(direction),\n\n origin: *intersection.get_intersection_point(),\n\n state: continued_state,\n\n ..intersection.get_intersector_ray().clone()})\n\n },\n\n Err(e) => Err(e)\n\n }\n", "file_path": "src/core/ray.rs", "rank": 28, "score": 29090.054086979344 }, { "content": " if let Some(ref mut mediums) = self.mediums {\n\n mediums.pop_back();\n\n }\n\n if self.mediums.as_ref().unwrap().is_empty() {\n\n self.mediums = None;\n\n }\n\n }\n\n }\n\n\n\n pub fn continue_ray_from_intersection_into_medium(intersection: &RayIntersection, direction: Vector3) -> Result<Self, RayError> {\n\n let original_ray = intersection.get_intersector_ray();\n\n\n\n match RayState::get_continuation(original_ray.get_state(), intersection.get_distance_to_intersection()) {\n\n Ok (continued_state) => {\n\n let mut result = Self { direction: Unit::new_normalize(direction),\n\n origin: *intersection.get_intersection_point(),\n\n mediums: original_ray.mediums.clone(),\n\n state: continued_state};\n\n if intersection.was_inside() {\n\n result.pop_medium();\n", "file_path": "src/core/ray.rs", "rank": 29, "score": 29089.455605878997 }, { "content": "\n\n\n\n#[derive(Debug, Copy, Clone)]\n\npub struct Material {\n\n ambient: Option<Color>,\n\n diffuse: Option<Color>,\n\n specular: Option<(Color, FloatType)>,\n\n fresnel: Option<FresnelData>,\n\n reflective: bool,\n\n refractive: bool,\n\n}\n\n\n\nimpl Material {\n\n pub fn new_useless() -> Self {\n\n Self { ambient: None,\n\n diffuse: None,\n\n specular: None,\n\n fresnel: None,\n\n reflective: false,\n\n refractive: false\n", "file_path": "src/core/material.rs", "rank": 30, "score": 29087.665006903826 }, { "content": "\n\n pub fn get_fresnel_reflection(ray_intersection: &RayIntersection) -> Option<Color> {\n\n let material = ray_intersection.get_material();\n\n material.get_fresnel_data().and_then(|fresnel_data| {\n\n fresnel_data.get_fresnel_reflect(ray_intersection)\n\n })\n\n }\n\n\n\n pub fn get_fresnel_refraction(ray_intersection: &RayIntersection) -> Option<Color> {\n\n let material = ray_intersection.get_material();\n\n material.get_fresnel_data().and_then(|fresnel_data| {\n\n fresnel_data.get_fresnel_refract(ray_intersection)\n\n })\n\n }\n\n}", "file_path": "src/core/material.rs", "rank": 31, "score": 29087.29022723986 }, { "content": " None => {\n\n Ok (Self { distance_to_origin: input.distance_to_origin + distance_to_intersection,\n\n depth_counter: input.depth_counter + 1,\n\n ..*input\n\n })\n\n }\n\n }\n\n }\n\n\n\n pub fn get_maximum_depth_limited(&self, maximum_depth_limit: u32) -> Self {\n\n Self {\n\n depth_limit: Some(maximum_depth_limit.min(if let Some(depth_limit) = self.depth_limit {depth_limit} else {maximum_depth_limit})),\n\n ..*self\n\n }\n\n }\n\n\n\n pub fn get_distance_to_origin(&self) -> FloatType {\n\n self.distance_to_origin\n\n }\n\n\n", "file_path": "src/core/ray.rs", "rank": 32, "score": 29086.610916144447 }, { "content": " &self.direction.as_ref()\n\n }\n\n\n\n pub fn get_distance_to_origin(&self) -> FloatType {\n\n self.state.get_distance_to_origin()\n\n }\n\n\n\n pub fn get_depth_counter(&self) -> i32 {\n\n self.state.get_depth_counter()\n\n }\n\n\n\n pub fn get_medium(&self) -> Option<Material> {\n\n if let Some(ref mediums) = self.mediums {\n\n if let Some(last_item) = mediums.back() {\n\n Some(last_item.clone())\n\n } else {\n\n None\n\n }\n\n } else {\n\n None\n", "file_path": "src/core/ray.rs", "rank": 33, "score": 29085.778171870916 }, { "content": " Some(fresnel_data.n_avg)\n\n })\n\n }\n\n\n\n pub fn get_refractive_index_for_component(&self, component: ColorComponent) -> Option<FloatType> {\n\n self.fresnel.and_then(|fresnel_data| {\n\n Some(fresnel_data.n.get_component(component))\n\n })\n\n }\n\n\n\n fn get_fresnel_data(&self) -> Option<&FresnelData> {\n\n self.fresnel.as_ref()\n\n }\n\n\n\n pub fn get_diffuse_illumination(ray_intersection: &RayIntersection, light_intersection: &LightIntersection) -> Option<Color> {\n\n let material = ray_intersection.get_material();\n\n\n\n material.get_diffuse_color().and_then(|color| {\n\n let surface_normal = ray_intersection.get_normal_vector();\n\n let light_direction = light_intersection.get_light_direction();\n", "file_path": "src/core/material.rs", "rank": 34, "score": 29085.59741706477 }, { "content": "use core::Material;", "file_path": "src/basic/materials.rs", "rank": 35, "score": 29084.671092696713 }, { "content": " let cosln = light_direction.dot(surface_normal).max(0.0);\n\n let illumination = light_intersection.get_illumination();\n\n Some ((*color * *illumination).mul_scalar(&cosln))\n\n })\n\n }\n\n\n\n pub fn get_specular_illumination(ray_intersection: &RayIntersection, light_intersection: &LightIntersection) -> Option<Color> {\n\n let material = ray_intersection.get_material();\n\n\n\n material.get_specular_color().and_then(|color_shiny| {\n\n let illumination = light_intersection.get_illumination();\n\n let view_direction = ray_intersection.get_view_direction();\n\n let surface_normal = ray_intersection.get_normal_vector();\n\n let (color, shininess) = *color_shiny;\n\n let light_direction = light_intersection.get_light_direction();\n\n let half_direction = (view_direction + light_direction).normalize();\n\n let coshn = half_direction.dot(surface_normal).max(0.0).powf(shininess);\n\n Some((color * *illumination).mul_scalar(&coshn))\n\n })\n\n }\n", "file_path": "src/core/material.rs", "rank": 36, "score": 29084.368017359702 }, { "content": "use core::{Color, ColorComponent, FresnelIndex, RayIntersection, LightIntersection};\n\n\n\nuse defs::FloatType;\n\nuse tools::CompareWithTolerance;\n\n\n\n#[derive(Debug, Copy, Clone)]\n", "file_path": "src/core/material.rs", "rank": 37, "score": 29083.840245098265 }, { "content": " }\n\n }\n\n\n\n pub fn new_diffuse(diffuse: Color, ambient: Option<Color>) -> Self {\n\n Self { diffuse: Some(diffuse),\n\n ambient: ambient,\n\n specular: None,\n\n fresnel: None,\n\n reflective: false,\n\n refractive: false}\n\n }\n\n\n\n pub fn new_shiny(diffuse: Color, specular: (Color, FloatType), ambient: Option<Color>) -> Self {\n\n Self { diffuse: Some(diffuse),\n\n ambient: ambient,\n\n specular: Some(specular),\n\n fresnel: None,\n\n reflective: false,\n\n refractive: false}\n\n }\n", "file_path": "src/core/material.rs", "rank": 38, "score": 29083.36819497293 }, { "content": " Self { diffuse: diffuse,\n\n ambient: ambient,\n\n specular: specular,\n\n fresnel: Some(FresnelData::new(fresnel_real, fresnel_imagninary)),\n\n reflective: true,\n\n refractive: true}\n\n }\n\n\n\n pub fn new_light_source(diffuse: Color, ambient: Option<Color>) -> Self {\n\n Self {\n\n diffuse: Some(diffuse),\n\n ambient: ambient,\n\n specular: None,\n\n fresnel: Some(FresnelData::new(FresnelIndex::one(), FresnelIndex::one())),\n\n reflective: false,\n\n refractive: true\n\n }\n\n }\n\n\n\n pub fn get_ambient_color(&self) -> Option<&Color> {\n", "file_path": "src/core/material.rs", "rank": 39, "score": 29082.84056336116 }, { "content": "\n\n pub fn new_reflective(fresnel_real: FresnelIndex, fresnel_imagninary: FresnelIndex, diffuse: Option<Color>, specular: Option<(Color, FloatType)>, ambient: Option<Color>) -> Self {\n\n Self { diffuse: diffuse,\n\n ambient: ambient,\n\n specular: specular,\n\n fresnel: Some(FresnelData::new(fresnel_real, fresnel_imagninary)),\n\n reflective: true,\n\n refractive: false}\n\n }\n\n\n\n pub fn new_refractive(fresnel_real: FresnelIndex, fresnel_imagninary: FresnelIndex, diffuse: Option<Color>, specular: Option<(Color, FloatType)>, ambient: Option<Color>) -> Self {\n\n Self { diffuse: diffuse,\n\n ambient: ambient,\n\n specular: specular,\n\n fresnel: Some(FresnelData::new(fresnel_real, fresnel_imagninary)),\n\n reflective: false,\n\n refractive: true}\n\n }\n\n\n\n pub fn new_reflective_and_refractive(fresnel_real: FresnelIndex, fresnel_imagninary: FresnelIndex, diffuse: Option<Color>, specular: Option<(Color, FloatType)>, ambient: Option<Color>) -> Self {\n", "file_path": "src/core/material.rs", "rank": 40, "score": 29082.621948553166 }, { "content": " state: self.state.get_maximum_depth_limited(maximum_depth_limit),\n\n ..self.clone()\n\n }\n\n }\n\n\n\n pub fn set_maximum_depth_limited_mut(&mut self, maximum_depth_limit: u32){\n\n self.state = self.state.get_maximum_depth_limited(maximum_depth_limit);\n\n }\n\n\n\n fn push_medium(&mut self, material: Material) {\n\n if let Some(ref mut mediums) = self.mediums {\n\n mediums.push_back(material);\n\n } else {\n\n self.mediums = Some(VecDeque::new());\n\n self.mediums.as_mut().unwrap().push_back(material);\n\n }\n\n }\n\n\n\n fn pop_medium(&mut self) {\n\n if self.mediums.is_some() {\n", "file_path": "src/core/ray.rs", "rank": 41, "score": 29082.548615841104 }, { "content": "\n\n Self { n: real,\n\n n_inverse: real.recip(),\n\n n_avg: real.intensity_avg(),\n\n n_imaginary: imaginary,\n\n n_imaginary_inverse: imaginary.recip(),\n\n n_imaginary_avg: imaginary.intensity_avg(),\n\n f0: f0,\n\n f0_avg: f0.intensity_avg(),\n\n f0_inverse: f0_inverse,\n\n f0_inverse_avg: f0_inverse.intensity_avg()\n\n }\n\n }\n\n\n\n pub fn get_fresnel_reflect(&self, intersection: &RayIntersection) -> Option<Color> {\n\n let view_and_normal_angle_cosine = intersection.get_view_direction().dot(intersection.get_normal_vector());\n\n\n\n if view_and_normal_angle_cosine.greater_eq_eps(&0.0) {\n\n let f = if !intersection.was_inside() {\n\n self.f0\n", "file_path": "src/core/material.rs", "rank": 42, "score": 29082.053037724483 }, { "content": " } else {\n\n self.f0_inverse\n\n };\n\n\n\n let f1 = (Color::one()-f) * Color::one().mul_scalar(&(1.0 - view_and_normal_angle_cosine).powi(5));\n\n \n\n Some(f + f1)\n\n } else {\n\n None\n\n }\n\n }\n\n\n\n pub fn get_fresnel_refract(&self, intersection: &RayIntersection) -> Option<Color> {\n\n if let Some(color) = self.get_fresnel_reflect(intersection) {\n\n Some(Color::one() - color)\n\n } else {\n\n None\n\n }\n\n }\n\n}\n", "file_path": "src/core/material.rs", "rank": 43, "score": 29081.6292868064 }, { "content": " self.ambient.as_ref()\n\n }\n\n\n\n pub fn get_diffuse_color(&self) -> Option<&Color> {\n\n self.diffuse.as_ref()\n\n }\n\n\n\n pub fn get_specular_color(&self) -> Option<&(Color, FloatType)> {\n\n self.specular.as_ref()\n\n }\n\n\n\n pub fn is_opaque(&self) -> bool {\n\n !self.refractive\n\n }\n\n\n\n pub fn is_transparent(&self) -> bool {\n\n !self.is_opaque()\n\n }\n\n\n\n pub fn is_reflective(&self) -> bool {\n", "file_path": "src/core/material.rs", "rank": 44, "score": 29080.997631415692 }, { "content": " self.reflective\n\n }\n\n\n\n pub fn is_refractive(&self) -> bool {\n\n self.refractive\n\n }\n\n\n\n pub fn get_transparency_to_light(&self) -> Option<Color> {\n\n if self.is_transparent() {\n\n match self.diffuse {\n\n None => Some(Color::one()),\n\n Some(color) => Some(color)\n\n }\n\n } else {\n\n None\n\n }\n\n }\n\n\n\n pub fn get_average_refractive_index(&self) -> Option<FloatType> {\n\n self.fresnel.and_then(|fresnel_data| {\n", "file_path": "src/core/material.rs", "rank": 45, "score": 29080.648740995628 }, { "content": " 0.0, 0.0, 0.0, 1.0);\n\n \n\n assert_relative_eq!(wrapper.get_tf_matrix(), &expected);\n\n }\n\n\n\n struct ModelMock {\n\n point: Point3,\n\n normal: Vector3,\n\n }\n\n\n\n impl ModelMock {\n\n pub fn new(point: Point3, normal: Vector3) -> Self {\n\n Self { point: point,\n\n normal: normal }\n\n }\n\n }\n\n\n\n impl Model for ModelMock {\n\n fn get_intersection(&self, ray: &Ray) -> Option<RayIntersection> {\n\n Some(RayIntersection::new(self.normal, self.point, ray, Material::new_useless(), false).expect(\"Ray depth limit reached\"))\n", "file_path": "src/core/model.rs", "rank": 50, "score": 28825.159381214857 }, { "content": " test_model.rotate(Vector3::new(0.0, 0.0, 1.0), std::f64::consts::FRAC_PI_2);\n\n\n\n let intersector_ray = Ray::new_single_shot(Point3::new(0.0, -5.0, 2.0), Vector3::new(0.0, 1.0, 0.0));\n\n let transformed_intersection = test_model.get_intersection(&intersector_ray).expect(\"There was no intersection returned when ModelMock always returns\");\n\n\n\n assert_relative_eq!(transformed_intersection.get_intersection_point(), &Point3::new(0.0, 0.0, 2.0));\n\n assert_relative_eq!(transformed_intersection.get_normal_vector(), &Vector3::new(1.0, 1.0, 1.0).normalize());\n\n assert_relative_eq!(transformed_intersection.get_distance_to_intersection(), &5.0);\n\n }\n\n\n\n #[test]\n\n fn mvo_wrapper_complete_scale_translate() {\n\n let mut test_model = ModelViewModelWrapper::new_identity(ModelMock::new(Point3::new(0.0, 0.0, 1.0), Vector3::new(1.0, -1.0, 1.0)));\n\n test_model.scale_uniform(2.0);\n\n test_model.translate(Vector3::new(0.0, 1.0, 0.0)); \n\n\n\n let intersector_ray = Ray::new_single_shot(Point3::new(0.0, -5.0, 2.0), Vector3::new(0.0, 1.0, 0.0));\n\n let transformed_intersection = test_model.get_intersection(&intersector_ray).expect(\"There was no intersection returned when ModelMock always returns\");\n\n\n\n assert_relative_eq!(transformed_intersection.get_intersection_point(), &Point3::new(0.0, 1.0, 2.0));\n\n assert_relative_eq!(transformed_intersection.get_normal_vector(), &Vector3::new(1.0, -1.0, 1.0).normalize());\n\n assert_relative_eq!(transformed_intersection.get_distance_to_intersection(), &6.0);\n\n }\n\n}", "file_path": "src/core/model.rs", "rank": 53, "score": 28817.57548545539 }, { "content": "use defs::{Matrix4, Vector3, FloatType};\n\nuse core::{Ray, RayIntersection};\n\nuse na::{Similarity3, Rotation3, Translation3, Unit};\n\n\n", "file_path": "src/core/model.rs", "rank": 54, "score": 28817.404552708285 }, { "content": "\n\n self.recalculate_cached_matrices();\n\n }\n\n\n\n pub fn rotate(&mut self, axis: Vector3, angle: FloatType) {\n\n let rotation = Rotation3::from_axis_angle(&Unit::new_normalize(axis), angle);\n\n\n\n self.tf_matrix = rotation.to_homogeneous() * self.tf_matrix;\n\n\n\n self.recalculate_cached_matrices();\n\n }\n\n\n\n #[cfg(test)]\n\n pub fn get_tf_matrix(&self) -> &Matrix4 {\n\n &self.tf_matrix\n\n }\n\n}\n\n\n\nimpl<T: Model> Model for ModelViewModelWrapper<T> {\n\n fn get_intersection(&self, ray: & Ray) -> Option<RayIntersection<>> {\n", "file_path": "src/core/model.rs", "rank": 55, "score": 28816.64321132849 }, { "content": " }\n\n }\n\n\n\n #[test]\n\n fn mvo_wrapper_complete_translate() {\n\n let mut test_model = ModelViewModelWrapper::new_identity(ModelMock::new(Point3::new(0.0, 0.0, 1.0), Vector3::new(1.0, -1.0, 1.0)));\n\n test_model.translate(Vector3::new(0.0, 0.0, 1.0));\n\n\n\n let intersector_ray = Ray::new_single_shot(Point3::new(0.0, -5.0, 2.0), Vector3::new(0.0, 1.0, 0.0));\n\n let transformed_intersection = test_model.get_intersection(&intersector_ray).expect(\"There was no intersection returned when ModelMock always returns\");\n\n\n\n assert_relative_eq!(transformed_intersection.get_intersection_point(), &Point3::new(0.0, 0.0, 2.0));\n\n assert_relative_eq!(transformed_intersection.get_normal_vector(), &Vector3::new(1.0, -1.0, 1.0).normalize());\n\n assert_relative_eq!(transformed_intersection.get_distance_to_intersection(), &5.0);\n\n }\n\n\n\n #[test]\n\n fn mvo_wrapper_complete_rotate_translate() {\n\n let mut test_model = ModelViewModelWrapper::new_identity(ModelMock::new(Point3::new(0.0, 0.0, 1.0), Vector3::new(1.0, -1.0, 1.0)));\n\n test_model.translate(Vector3::new(0.0, 0.0, 1.0));\n", "file_path": "src/core/model.rs", "rank": 56, "score": 28816.638824152367 }, { "content": "\n\n }\n\n }\n\n }\n\n\n\n impl Model for DummyModel {\n\n fn get_intersection(&self, _ray: &Ray) -> Option<RayIntersection> {\n\n None\n\n }\n\n }\n\n\n\n #[test]\n\n fn mvo_wrapper_scale_uniform() {\n\n let mut wrapper = ModelViewModelWrapper::new_identity(DummyModel::new());\n\n wrapper.scale_uniform(2.0);\n\n\n\n let expected = Matrix4::new(2.0, 0.0, 0.0, 0.0,\n\n 0.0, 2.0, 0.0, 0.0,\n\n 0.0, 0.0, 2.0, 0.0,\n\n 0.0, 0.0, 0.0, 1.0);\n", "file_path": "src/core/model.rs", "rank": 59, "score": 28813.74831776716 }, { "content": " wrapper.translate(Vector3::new(1.0, 1.0, 1.0));\n\n\n\n let expected = Matrix4::new(1.0, 0.0, 0.0, 1.0,\n\n 0.0, 1.0, 0.0, 1.0,\n\n 0.0, 0.0, 1.0, 1.0,\n\n 0.0, 0.0, 0.0, 1.0);\n\n \n\n assert_relative_eq!(wrapper.get_tf_matrix(), &expected);\n\n }\n\n\n\n #[test]\n\n fn mvo_wrapper_scale_translate() {\n\n let mut wrapper = ModelViewModelWrapper::new_identity(DummyModel::new());\n\n\n\n wrapper.scale_non_uniform(Vector3::new(2.0, 2.0, 2.0));\n\n wrapper.translate(Vector3::new(1.0, 1.0, 1.0));\n\n\n\n let expected = Matrix4::new(2.0, 0.0, 0.0, 1.0,\n\n 0.0, 2.0, 0.0, 1.0,\n\n 0.0, 0.0, 2.0, 1.0,\n", "file_path": "src/core/model.rs", "rank": 61, "score": 28811.009329436616 }, { "content": " let transformed_ray = ray.get_transformed(&self.inverse_tf_matrix);\n\n\n\n match self.wrapped_model.get_intersection(&transformed_ray) {\n\n None => None,\n\n Some(transformed_intersection) => transformed_intersection.get_transformed(&self.tf_matrix).ok()\n\n }\n\n }\n\n}\n\n\n\n\n", "file_path": "src/core/model.rs", "rank": 62, "score": 28810.240787735518 }, { "content": " \n\n assert_relative_eq!(wrapper.get_tf_matrix(), &expected);\n\n }\n\n\n\n #[test]\n\n fn mvo_wrapper_scale_non_uniform() {\n\n let mut wrapper = ModelViewModelWrapper::new_identity(DummyModel::new());\n\n wrapper.scale_non_uniform(Vector3::new(2.0, 3.0, 4.0));\n\n\n\n let expected = Matrix4::new(2.0, 0.0, 0.0, 0.0,\n\n 0.0, 3.0, 0.0, 0.0,\n\n 0.0, 0.0, 4.0, 0.0,\n\n 0.0, 0.0, 0.0, 1.0);\n\n \n\n assert_relative_eq!(wrapper.get_tf_matrix(), &expected);\n\n }\n\n\n\n #[test]\n\n fn mvo_wrapper_translate() {\n\n let mut wrapper = ModelViewModelWrapper::new_identity(DummyModel::new());\n", "file_path": "src/core/model.rs", "rank": 63, "score": 28809.961011642412 }, { "content": " }\n\n\n\n pub fn scale_non_uniform(&mut self, scaling: Vector3) {\n\n let diagonal = {\n\n let mut result = scaling.to_homogeneous();\n\n result[(3, 0)] = 1.0;\n\n result\n\n };\n\n\n\n let similarity = Matrix4::from_diagonal(&diagonal);\n\n \n\n self.tf_matrix = similarity * self.tf_matrix;\n\n\n\n self.recalculate_cached_matrices();\n\n }\n\n\n\n pub fn translate(&mut self, translation: Vector3) {\n\n let translate = Translation3::from_vector(translation);\n\n\n\n self.tf_matrix = translate.to_homogeneous() * self.tf_matrix;\n", "file_path": "src/core/model.rs", "rank": 64, "score": 28809.763092340443 }, { "content": " inverse_tf_matrix: Matrix4::identity(),\n\n tf_matrix: Matrix4::identity()\n\n }\n\n }\n\n\n\n fn recalculate_cached_matrices(&mut self) {\n\n self.inverse_tf_matrix = self.tf_matrix.try_inverse().expect(\"Uninvertable Model View Matrix\");\n\n }\n\n\n\n pub fn load_identity(&mut self) {\n\n self.tf_matrix = Matrix4::identity();\n\n self.inverse_tf_matrix = Matrix4::identity();\n\n }\n\n\n\n pub fn scale_uniform(&mut self, scaling: FloatType) {\n\n let similarity = Similarity3::from_scaling(scaling);\n\n\n\n self.tf_matrix = similarity.to_homogeneous() * self.tf_matrix;\n\n\n\n self.recalculate_cached_matrices(); \n", "file_path": "src/core/model.rs", "rank": 65, "score": 28808.40954026133 }, { "content": "pub trait SceneBuffer: ImmutableSceneBuffer + MutableSceneBuffer + Send + Sync {\n\n\n\n}\n\n\n\n\n\npub struct SceneBufferIterator<'buffer> {\n\n buffer: &'buffer ImmutableSceneBuffer,\n\n screen_iterator: ScreenIterator\n\n}\n\n\n\nimpl<'buffer> SceneBufferIterator<'buffer> {\n\n pub fn new(buffer: &'buffer ImmutableSceneBuffer) -> Self {\n\n Self {\n\n buffer: buffer,\n\n screen_iterator: ScreenIterator::new(buffer.get_screen())\n\n }\n\n }\n\n}\n\n\n\nimpl<'buffer> Iterator for SceneBufferIterator<'buffer> {\n", "file_path": "src/core/scene.rs", "rank": 66, "score": 26326.559688248748 }, { "content": "pub trait MutableSceneBuffer: ImmutableSceneBuffer + Send + Sync { //Internally mutable (Mutex), thread safe\n\n fn set_pixel_value(&self, pixel: Point2Int, color: &Color) -> Result<(), SceneBufferError>;\n\n fn accumulate_pixel_value(&self, pixel: Point2Int, color: &Color) -> Result<(), SceneBufferError>;\n\n fn reset_pixel(&self, pixel: Point2Int) -> Result<(), SceneBufferError>;\n\n\n\n fn layer_buffer(&self, place: SceneBufferLayering, rhs: &ImmutableSceneBuffer) -> Result<(), SceneBufferError> {\n\n let layerer = |self_color_option: Option<Color>, rhs_color_option: Option<Color>| {\n\n match place {\n\n SceneBufferLayering::Under => {\n\n match self_color_option {\n\n Some(_) => None,\n\n None => rhs_color_option\n\n }\n\n },\n\n SceneBufferLayering::Over => {\n\n match rhs_color_option {\n\n Some(color) => Some(color),\n\n None => None\n\n }\n\n }\n", "file_path": "src/core/scene.rs", "rank": 67, "score": 22976.396398707835 }, { "content": "use defs::{FloatType, Point3, Vector3, Matrix4};\n\nuse core::{Ray, Material};\n\nuse tools::{CompareWithTolerance};\n\nuse na::{Unit};\n\nuse na;\n\nuse uuid::{Uuid};\n\n\n\nstatic MIMIMUM_INTERSECTION_DISTANCE: FloatType = 0.000000001;\n\n\n\n#[derive(Debug)]\n\npub enum RayIntersectionError {\n\n NoRayTravelDistance,\n\n NoModelIdentifierPresent\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct RayIntersection {\n\n normal : Unit<Vector3>,\n\n point : Point3,\n\n material_at_intersection : Material,\n", "file_path": "src/core/intersection.rs", "rank": 68, "score": 27.34003249949724 }, { "content": " }\n\n }\n\n\n\n pub fn new_model_identifier(normal: Vector3, point: Point3, ray: &Ray, material: Material, was_inside: bool, model_identier: Uuid) -> Result<Self, RayIntersectionError> {\n\n match Self::new(normal, point, ray, material, was_inside) {\n\n Ok(mut intersection) => {\n\n intersection.set_model_identifier_mut(Some(model_identier));\n\n Ok(intersection)\n\n },\n\n Err(err) => Err(err)\n\n }\n\n }\n\n\n\n pub fn get_intersection_point(&self) -> &Point3 {\n\n &self.point\n\n }\n\n\n\n pub fn get_normal_vector(&self) -> &Vector3 {\n\n &self.normal.as_ref()\n\n }\n", "file_path": "src/core/intersection.rs", "rank": 69, "score": 24.399726833506556 }, { "content": " distance_to_intersection : FloatType,\n\n was_inside : bool,\n\n ray : Ray,\n\n model_identifier : Option<Uuid>,\n\n}\n\n\n\nimpl RayIntersection {\n\n pub fn new(normal: Vector3, point: Point3, ray: &Ray, material: Material, was_inside: bool) -> Result<Self, RayIntersectionError> {\n\n let distance_to_intersection = na::distance(ray.get_origin(), &point);\n\n if distance_to_intersection.greater_eq_eps(&MIMIMUM_INTERSECTION_DISTANCE) {\n\n Ok (Self { normal: Unit::new_normalize(normal), \n\n point: point, \n\n ray: ray.clone(),\n\n material_at_intersection: material,\n\n distance_to_intersection: distance_to_intersection,\n\n was_inside: was_inside,\n\n model_identifier: None\n\n })\n\n } else {\n\n Err(RayIntersectionError::NoRayTravelDistance)\n", "file_path": "src/core/intersection.rs", "rank": 70, "score": 24.16072208070324 }, { "content": "\n\n pub fn was_inside(&self) -> bool {\n\n self.was_inside\n\n }\n\n\n\n pub fn get_transformed(self, transformation_matrix: &Matrix4) -> Result<Self, RayIntersectionError> {\n\n let point = Point3::from_homogeneous(transformation_matrix * self.point.to_homogeneous()).expect(\"Unhomogeneous transformed point\");\n\n let normal = Vector3::from_homogeneous(transformation_matrix * self.normal.to_homogeneous()).expect(\"Unhomogeneous transformed vector\");\n\n let ray = self.ray.get_transformed(transformation_matrix);\n\n\n\n Self::new(normal, point, &ray, self.material_at_intersection, self.was_inside)\n\n }\n\n\n\n pub fn get_model_identifier(&self) -> Option<&Uuid> {\n\n self.model_identifier.as_ref()\n\n }\n\n\n\n pub fn set_model_identifier_mut(&mut self, identifier: Option<Uuid>) {\n\n self.model_identifier = identifier;\n\n }\n", "file_path": "src/core/intersection.rs", "rank": 71, "score": 22.196828261431165 }, { "content": "use std::collections::{HashSet};\n\nuse std::sync::{Arc, Mutex};\n\nuse std;\n\n\n\nuse defs::{IntType, FloatType, Point2Int};\n\nuse core::{WorldViewTrait, Color, Screen, ScreenIterator, RayIntersection, Material,\n\n RayPropagator, BasicSceneBuffer, SceneBuffer, RayPropagatorError,\n\n RenderingTask, RenderingTaskProducer, ThreadSafeIterator, Ray, RayError};\n\n\n\nuse uuid::{Uuid};\n\nuse rand;\n\nuse rand::{Rng};\n\n\n\n#[derive(Clone, Copy)]\n\npub struct UuidColor {\n\n pub id: Uuid,\n\n pub color: Color\n\n}\n\n\n\nimpl UuidColor {\n", "file_path": "src/basic/postprocessing/gi.rs", "rank": 72, "score": 18.910656114825645 }, { "content": "use core::{LightSource, Ray, LightIntersection, RayIntersection, Color};\n\nuse defs::{Vector3, Point3, FloatType};\n\nuse na;\n\nuse na::{Unit};\n\n\n\npub struct DotLightSource {\n\n color: Color,\n\n intensity: FloatType,\n\n position: Point3,\n\n attenuation_const: FloatType,\n\n attenuation_linear: FloatType,\n\n attenuation_squared: FloatType\n\n}\n\n\n\nimpl DotLightSource {\n\n pub fn new_natural(color: Color, intensity: FloatType, position: Point3) -> Self {\n\n Self { color: color,\n\n intensity: intensity,\n\n position: position,\n\n attenuation_const: 0.0,\n", "file_path": "src/basic/lightsource.rs", "rank": 73, "score": 18.811544488110624 }, { "content": "\n\n pub fn set_model_identifier(&self, identifier: Option<Uuid>) -> Self {\n\n Self { model_identifier: identifier,\n\n ..self.clone() }\n\n }\n\n\n\n pub fn is_same_model_intersection(&self, rhs: &RayIntersection) -> Result<bool, RayIntersectionError> {\n\n if self.model_identifier.is_some() && rhs.model_identifier.is_some() {\n\n Ok(self.model_identifier.unwrap() == rhs.model_identifier.unwrap())\n\n } else {\n\n Err(RayIntersectionError::NoModelIdentifierPresent)\n\n }\n\n }\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\n\n}", "file_path": "src/core/intersection.rs", "rank": 74, "score": 18.50554160455596 }, { "content": "use core::{Ray, RayIntersection, Color, RayCaster};\n\nuse defs::Vector3;\n\nuse na::{Unit};\n\n\n\npub struct LightIntersection {\n\n illumination: Color,\n\n light_direction: Unit<Vector3>\n\n}\n\n\n\nimpl LightIntersection {\n\n pub fn new(illumination: Color, light_direction: Vector3) -> Self {\n\n Self { illumination: illumination, \n\n light_direction : Unit::new_normalize(light_direction.normalize())}\n\n }\n\n\n\n pub fn get_shadowed(&self, shadowing: &Color) -> Self {\n\n Self { illumination: self.illumination * *shadowing,\n\n ..*self}\n\n }\n\n\n\n pub fn get_illumination(&self) -> &Color {\n\n &self.illumination\n\n }\n\n\n\n pub fn get_light_direction(&self) -> &Vector3 {\n\n &self.light_direction.as_ref()\n\n }\n\n}\n\n\n", "file_path": "src/core/light.rs", "rank": 75, "score": 18.353560271492064 }, { "content": "use defs::{FloatType, Vector3};\n\n\n\nuse core::{Ray, RayError, RayIntersection, ColorComponent};\n\nuse tools::{CompareWithTolerance};\n\n\n\nuse na;\n\nuse na::{Rotation3, Unit};\n\n\n\n\n\n#[derive(Debug)]\n\npub enum RayPropagatorError {\n\n RayRelated(RayError),\n\n NoRefraction,\n\n NotRefractiveMaterial\n\n}\n\n\n\npub struct RayPropagator<'intersection> {\n\n intersection: &'intersection RayIntersection,\n\n view_axis: Unit<Vector3>\n\n}\n", "file_path": "src/core/propagation.rs", "rank": 76, "score": 17.5279649299454 }, { "content": "use core::{Intersector, Model, RayIntersection, Ray};\n\n\n\nuse tools::CompareWithTolerance;\n\n\n\n\n\npub type ModelVec = Vec<Box<Model>>;\n\n\n\npub struct SimpleIntersector {\n\n models: ModelVec,\n\n}\n\n\n\nimpl SimpleIntersector {\n\n pub fn new(models: ModelVec) -> Self {\n\n Self { models: models}\n\n }\n\n}\n\n\n\nimpl Intersector for SimpleIntersector {\n\n fn get_intersections_reverse_ordered(&self, ray: &Ray) -> Vec<RayIntersection> { //Nearest elem is last\n\n let mut result: Vec<RayIntersection> = self.models.iter().filter_map(|model_box| model_box.get_intersection(ray)).collect();\n", "file_path": "src/basic/intersector.rs", "rank": 77, "score": 17.36360279178099 }, { "content": "use defs::{Point3, Vector3, Matrix3, Point2Int, FloatType, IntType};\n\nuse core::{Ray};\n\nuse tools::{CompareWithTolerance, Vector3Extensions};\n\nuse na::{Unit};\n\n\n\n#[derive(Debug)]\n\npub enum ScreenError {\n\n PixelOutOfBoundsError\n\n}\n\n\n\n\n\n#[derive(Copy, Clone)]\n\npub struct Screen {\n\n center: Point3,\n\n up: Unit<Vector3>,\n\n left: Unit<Vector3>,\n\n normal: Unit<Vector3>,\n\n to_plane_trasform_matrix: Matrix3,\n\n width: FloatType,\n\n height: FloatType,\n", "file_path": "src/core/view.rs", "rank": 78, "score": 15.637935707482075 }, { "content": "pub mod ray;\n\npub mod intersection;\n\npub mod model;\n\npub mod world;\n\npub mod light;\n\npub mod material;\n\npub mod color;\n\npub mod view;\n\npub mod propagation;\n\npub mod worldview;\n\npub mod execution;\n\npub mod scene;\n\n\n\npub use self::model::*;\n\npub use self::ray::*;\n\npub use self::intersection::*;\n\npub use self::model::*;\n\npub use self::world::*;\n\npub use self::light::*;\n\npub use self::material::*;\n\npub use self::color::*;\n\npub use self::view::*;\n\npub use self::propagation::*;\n\npub use self::worldview::*;\n\npub use self::execution::*;\n\npub use self::scene::*;", "file_path": "src/core/mod.rs", "rank": 79, "score": 15.356662896380548 }, { "content": "#[derive(Copy, Clone)]\n\npub struct Eye {\n\n position: Point3,\n\n direction: Unit<Vector3>,\n\n}\n\n\n\nimpl Eye {\n\n pub fn new(position: Point3, direction: Vector3) -> Self {\n\n Self { position: position,\n\n direction: Unit::new_normalize(direction)}\n\n }\n\n\n\n pub fn get_position(&self) -> &Point3 {\n\n &self.position\n\n }\n\n\n\n pub fn get_direction(&self) -> &Vector3 {\n\n &self.direction.as_ref()\n\n }\n\n}\n", "file_path": "src/core/view.rs", "rank": 80, "score": 15.006123199026991 }, { "content": " None\n\n }\n\n \n\n } else {\n\n None\n\n }\n\n }\n\n\n\n pub fn new_calculate_uuid_color_for_pixel(&self, coord: &Point2Int) -> Result<Option<UuidColor>, GlobalIlluminationShaderError> {\n\n if let Ok(ray) = self.worldview.get_view().get_ray_to_screen_coordinate(*coord) {\n\n if let Some(intersection) = self.worldview.get_ray_caster().cast_model_ray(&ray) {\n\n if let Some(model_identifier) = intersection.get_model_identifier() {\n\n if let Some(resulting_color) = self.trace_ray_and_calculate_color(&ray) {\n\n Ok(Some(UuidColor::new(*model_identifier, resulting_color)))\n\n } else {\n\n Ok(None)\n\n }\n\n } else {\n\n Err(GlobalIlluminationShaderError::NotExistingModelId)\n\n }\n", "file_path": "src/basic/postprocessing/gi.rs", "rank": 81, "score": 14.40077146232672 }, { "content": " use na::{Unit};\n\n use std::f64::consts::{PI};\n\n\n\n #[test]\n\n fn diffuse_direction_vector() {\n\n let ray = Ray::new(Point3::new(1.0, 0.0, 1.0), Vector3::new(-1.0, 0.0, -1.0));\n\n let intersection = RayIntersection::new(Vector3::new(0.0, 0.0, 1.0), Point3::new(0.0, 0.0, 0.0),\n\n &ray, Material::new_useless(), false).unwrap();\n\n\n\n let propagator = RayPropagator::new(&intersection);\n\n\n\n assert_relative_eq!(propagator.get_diffuse_direction_vector(PI/4.0, 0.0), Unit::new_normalize(Vector3::new(1.0, 0.0, 1.0)).unwrap());\n\n assert_relative_eq!(propagator.get_diffuse_direction_vector(PI/8.0, 0.0), Unit::new_normalize(Vector3::new((3.0*PI/8.0).tan(), 0.0, 1.0)).unwrap());\n\n assert_relative_eq!(propagator.get_diffuse_direction_vector(PI/8.0, PI/2.0), Unit::new_normalize(Vector3::new(0.0, (3.0*PI/8.0).tan(), 1.0)).unwrap());\n\n assert_relative_eq!(propagator.get_diffuse_direction_vector(PI/8.0, PI), Unit::new_normalize(Vector3::new(-((3.0*PI/8.0).tan()), 0.0, 1.0)).unwrap());\n\n }\n\n\n\n}\n", "file_path": "src/core/propagation.rs", "rank": 82, "score": 14.017011094078303 }, { "content": "use core::{RayCaster, RayIntersection, Color, ColorCalculator, Material,\n\n IlluminationCaster, LightIntersection, RayPropagator, RayPropagatorError};\n\n\n\npub struct SimpleColorCalculator {\n\n \n\n}\n\n\n\nimpl SimpleColorCalculator {\n\n pub fn new() -> Self {\n\n Self {}\n\n }\n\n\n\n fn get_ambient_color(&self, intersection: &RayIntersection) -> Color {\n\n let material = intersection.get_material();\n\n *material.get_ambient_color().unwrap_or(&Color::zero())\n\n }\n\n\n\n fn get_local_color(&self, intersection: &RayIntersection, illuminations: &Vec<LightIntersection>) -> Color { \n\n illuminations.iter().fold(Color::zero(), |acc, light_intersection|{\n\n let diffuse_color = Material::get_diffuse_illumination(intersection, light_intersection);\n", "file_path": "src/basic/colorcalculator.rs", "rank": 83, "score": 13.86269172632253 }, { "content": " \n\n result\n\n }\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn screen_get_intersected_pixel_hit_origin() {\n\n let test_screen = Screen::new_unit(Point3::origin(), Vector3::new(0.0, 0.0, 1.0), Vector3::new(0.0, 1.0, 0.0), 1.0, 1.0, 1000);\n\n let test_ray = Ray::new(Point3::new(0.0, 0.0, 1.0), Vector3::new(0.0, 0.0, -1.0));\n\n\n\n let result = test_screen.get_intersected_pixel(&test_ray).expect(\"Should have hit screen\");\n\n\n\n assert_eq!(result, Point2Int::new(500, 500));\n\n }\n\n\n", "file_path": "src/core/view.rs", "rank": 84, "score": 13.680130701785682 }, { "content": "\n\n pub fn get_distance_to_intersection(&self) -> FloatType {\n\n self.distance_to_intersection\n\n }\n\n\n\n pub fn get_intersector_ray(&self) -> &Ray {\n\n &self.ray\n\n }\n\n\n\n pub fn get_view_direction(&self) -> Vector3 {\n\n -self.ray.get_direction()\n\n }\n\n\n\n pub fn get_material(&self) -> &Material {\n\n &self.material_at_intersection\n\n }\n\n\n\n pub fn get_ray_medium(&self) -> Option<Material> {\n\n self.ray.get_medium()\n\n }\n", "file_path": "src/core/intersection.rs", "rank": 85, "score": 12.894069494684135 }, { "content": "use std::cmp;\n\n\n\nuse defs::{Point2Int, Vector2Int, IntType};\n\n\n\n#[derive(Debug)]\n\npub enum RectError {\n\n InvalidRect\n\n}\n\n\n\npub struct Rect {\n\n left_up: Point2Int,\n\n right_down: Point2Int,\n\n}\n\n\n\nimpl Rect {\n\n pub fn new(left_up: Point2Int, right_down: Point2Int) -> Result<Self, RectError> {\n\n let result = Self {\n\n left_up: left_up,\n\n right_down: right_down\n\n };\n", "file_path": "src/basic/postprocessing/base.rs", "rank": 86, "score": 12.507177361910445 }, { "content": " #[test]\n\n fn screen_get_intersected_pixel_hit_to_not_origin() {\n\n let test_screen = Screen::new_unit(Point3::origin(), Vector3::new(0.0, 0.0, 1.0), Vector3::new(0.0, 1.0, 0.0), 1.0, 1.0, 1000);\n\n let test_ray = Ray::new(Point3::new(0.25, 0.25, 1.0), Vector3::new(0.0, 0.0, -1.0));\n\n\n\n let result = test_screen.get_intersected_pixel(&test_ray).expect(\"Should have hit screen\");\n\n\n\n assert_eq!(result, Point2Int::new(250, 250));\n\n }\n\n\n\n #[test]\n\n fn screen_get_intersected_pixel_hit_not_to_origin_not_perpendicular() {\n\n let target_on_screen_point = Point3::new(0.25, 0.25, 0.0);\n\n let eye_point = Point3::new(0.0, 0.0, -1.0);\n\n let eye_ray_direction = (target_on_screen_point - eye_point).normalize();\n\n\n\n let test_screen = Screen::new_unit(Point3::origin(), Vector3::new(0.0, 0.0, 1.0), Vector3::new(0.0, 1.0, 0.0), 1.0, 1.0, 1000);\n\n let test_ray = Ray::new(eye_point + (eye_ray_direction * 5.0), -eye_ray_direction);\n\n\n\n let result = test_screen.get_intersected_pixel(&test_ray).expect(\"Should have hit screen\");\n", "file_path": "src/core/view.rs", "rank": 87, "score": 12.485939385673168 }, { "content": " }\n\n\n\n pub fn get_pixel_index_by_screen_coord(&self, coord: &Point2Int) -> Result<IntType, ScreenError> {\n\n if self.check_pixel_bounds(coord) {\n\n Ok(coord.x + self.horizontal_resolution * coord.y)\n\n } else {\n\n Err(ScreenError::PixelOutOfBoundsError)\n\n }\n\n }\n\n\n\n fn get_screen_plane_intersection_point(&self, ray: &Ray) -> Option<Point3> {\n\n let origin = ray.get_origin();\n\n let dir = ray.get_direction();\n\n\n\n let u = self.normal.dot(dir);\n\n if !u.near_zero_eps() {\n\n let k = self.normal.x * self.center.x + self.normal.y * self.center.y + self.normal.z * self.center.z;\n\n let s = self.normal.x * origin.x + self.normal.y * origin.y + self.normal.z * origin.z;\n\n let t = (k-s) / u;\n\n if t.greater_eq_eps(&0.0) {\n", "file_path": "src/core/view.rs", "rank": 88, "score": 12.285608300187251 }, { "content": "use core::{RayIntersection, RayCaster, LightIntersection, LightSource, Illuminator};\n\n\n\npub type LightSourceVec = Vec<Box<LightSource>>;\n\n\n\npub struct SimpleIlluminator {\n\n lights : LightSourceVec\n\n}\n\n\n\nimpl SimpleIlluminator {\n\n pub fn new(lights: LightSourceVec) -> Self {\n\n Self { lights: lights}\n\n }\n\n}\n\n\n\nimpl Illuminator for SimpleIlluminator {\n\n fn get_illumination_at(&self, intersection: &RayIntersection, illumination_caster: &RayCaster) -> Vec<LightIntersection> {\n\n self.lights.iter().filter_map(|light| {\n\n match light.get_ray_to_intersection(intersection) {\n\n None => None,\n\n Some(ray) => {\n", "file_path": "src/basic/illuminator.rs", "rank": 89, "score": 12.16001220351592 }, { "content": "use defs::{IntType, FloatType, Point2Int};\n\n\n\nuse core::{Screen, Color, ImmutableSceneBuffer, SceneBufferError};\n\nuse basic::{Rect, RectIterator};\n\nuse tools::{CompareWithTolerance};\n\n\n\npub struct MedianFilter<'obuffer> {\n\n original_buffer: &'obuffer ImmutableSceneBuffer,\n\n rect_radius: IntType,\n\n}\n\n\n\nimpl<'obuffer> MedianFilter<'obuffer> {\n\n pub fn new(original_buffer: &'obuffer ImmutableSceneBuffer, rect_radius: IntType) -> Self {\n\n Self {\n\n original_buffer: original_buffer,\n\n rect_radius: rect_radius\n\n }\n\n }\n\n\n\n fn get_vector_median(vector: &mut Vec<FloatType>) -> Option<FloatType> {\n", "file_path": "src/basic/postprocessing/filter.rs", "rank": 90, "score": 12.02106609319575 }, { "content": "use std::cmp::Ordering;\n\nuse defs::{Vector3, FloatType, IntType, FLOAT_ULPS_TOLERANCE};\n\nuse ::na;\n\nuse ::numt::Num;\n\nuse ::numt::float::Float;\n\nuse ::flcmp::ApproxOrdUlps;\n\n\n\n\n", "file_path": "src/tools.rs", "rank": 91, "score": 11.81753894700585 }, { "content": "pub type FloatType = f64;\n\npub type IntType = i32;\n\n\n\npub type VectorRow4 = super::na::core::Matrix1x4<FloatType>;\n\npub type VectorColumn4 = super::na::core::Vector4<FloatType>;\n\n\n\npub type Matrix4 = super::na::core::Matrix4<FloatType>;\n\npub type Matrix3 = super::na::core::Matrix3<FloatType>;\n\n\n\npub type Point3 = super::na::Point3<FloatType>;\n\npub type Vector3 = super::na::core::Vector3<FloatType>;\n\n\n\npub type Point2 = super::na::Point2<FloatType>;\n\npub type Vector2 = super::na::Vector2<FloatType>;\n\n\n\npub type Point2Int = super::na::Point2<IntType>;\n\npub type Vector2Int = super::na::Vector2<IntType>;\n\n\n\npub static FLOAT_ULPS_TOLERANCE: i64 = 65536;", "file_path": "src/defs.rs", "rank": 92, "score": 11.675129101599978 }, { "content": "\n\n assert_eq!(result, Point2Int::new(250, 250));\n\n }\n\n\n\n #[test]\n\n fn screen_get_intersected_pixel_miss() {\n\n let test_screen = Screen::new_unit(Point3::origin(), Vector3::new(0.0, 0.0, 1.0), Vector3::new(0.0, 1.0, 0.0), 1.0, 1.0, 1000);\n\n let test_ray = Ray::new(Point3::new(0.6, 0.6, 1.0), Vector3::new(0.0, 0.0, -1.0));\n\n\n\n assert!(test_screen.get_intersected_pixel(&test_ray).is_none());\n\n }\n\n}", "file_path": "src/core/view.rs", "rank": 93, "score": 11.636557993869655 }, { "content": "\n\n#[derive(Debug)]\n\npub enum ViewError {\n\n ScreenRelated(ScreenError)\n\n}\n\n\n\n#[derive(Copy, Clone)]\n\npub struct View {\n\n screen: Screen,\n\n eye: Eye\n\n}\n\n\n\nimpl View {\n\n pub fn new(screen: Screen, eye: Eye) -> Self {\n\n Self { screen: screen,\n\n eye: eye}\n\n }\n\n\n\n pub fn new_unit(eye_position: Point3, eye_direction: Vector3, screen_up: Vector3, screen_width_to_height_ratio: FloatType, screen_height: FloatType, screen_v_res: IntType) -> Self{\n\n let eye_unit_direction = Unit::new_normalize(eye_direction);\n", "file_path": "src/core/view.rs", "rank": 94, "score": 11.406981341932742 }, { "content": "\n\n rotate_around_normal * rotate_to_normal * view\n\n }\n\n\n\n pub fn get_diffuse_direction_ray(&self, pitch: FloatType, yaw: FloatType) -> Result<Ray, RayPropagatorError> {\n\n Ray::continue_ray_from_intersection(self.intersection, self.get_diffuse_direction_vector(pitch, yaw)).map_err(|ray_error| {\n\n match ray_error {\n\n RayError::DepthLimitReached => RayPropagatorError::RayRelated(ray_error),\n\n _ => panic!(\"RayPropagator encountered unhandleable RayError\")\n\n }\n\n })\n\n }\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use defs::{Point3};\n\n use core::{Material};\n", "file_path": "src/core/propagation.rs", "rank": 95, "score": 11.387437710618428 }, { "content": " pub fn new(id: Uuid, color: Color) -> Self {\n\n Self {\n\n id: id,\n\n color: color\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum GlobalIlluminationShaderError {\n\n InvalidCoord,\n\n MutexLockError,\n\n NotExistingModelId\n\n}\n\n\n", "file_path": "src/basic/postprocessing/gi.rs", "rank": 96, "score": 10.97825651161935 }, { "content": "use defs::{Point2Int};\n\nuse core::{RayCaster, IlluminationCaster, View, Color, RayIntersection, Screen, ScreenIterator};\n\nuse std::sync::{Arc, Mutex};\n\n\n\n\n\n#[derive(Debug)]\n\npub enum SceneError {\n\n NothingIntersected,\n\n InvalidInputCoord\n\n}\n\n\n", "file_path": "src/core/scene.rs", "rank": 97, "score": 10.974037960925195 }, { "content": "use core::{RenderingTaskProducer, RenderingTask, Screen, SceneError, WorldViewTrait, ThreadSafeIterator};\n\nuse defs::{Point2Int, IntType};\n\nuse std::sync::{Arc, Mutex};\n\n\n\npub struct WorldViewTaskProducer {\n\n worldview: Arc<WorldViewTrait>,\n\n}\n\n\n\nimpl WorldViewTaskProducer {\n\n pub fn new(worldview: Arc<WorldViewTrait>) -> Box<RenderingTaskProducer> {\n\n Box::new(Self {\n\n worldview: worldview\n\n })\n\n } \n\n}\n\n\n\nimpl RenderingTaskProducer for WorldViewTaskProducer {\n\n fn create_task_iterator(self: Box<Self>) -> Box<ThreadSafeIterator<Item=Box<RenderingTask>>> {\n\n Box::new(WorldViewTaskIterator::new(Arc::clone(&self.worldview)))\n\n }\n", "file_path": "src/basic/rendering.rs", "rank": 98, "score": 10.261387907191448 }, { "content": " None\n\n }\n\n}\n\n\n\n\n\npub struct SpotLightSource {\n\n dot_light: DotLightSource,\n\n direction: Unit<Vector3>,\n\n max_angle_rad: FloatType\n\n}\n\n\n\nimpl SpotLightSource {\n\n pub fn new(dot_light: DotLightSource, direction: Vector3, max_angle_radian: FloatType) -> Self {\n\n Self { dot_light: dot_light,\n\n direction: Unit::new_normalize(direction),\n\n max_angle_rad: max_angle_radian}\n\n }\n\n}\n\n\n\nimpl LightSource for SpotLightSource {\n", "file_path": "src/basic/lightsource.rs", "rank": 99, "score": 10.060635023441282 } ]
Rust
src/error.rs
gadunga/obj-rs
581b76d40d4f5ab33612ee51098ab09d6ee568fc
use std::fmt; use std::io; use std::num::{ParseIntError, ParseFloatError}; use std::convert::From; use std::error::Error; pub type ObjResult<T> = Result<T, ObjError>; #[derive(Debug)] pub enum ObjError { Io(io::Error), ParseInt(ParseIntError), ParseFloat(ParseFloatError), Load(LoadError) } macro_rules! implmnt { ($name:ident, $error:path) => ( impl From<$error> for ObjError { fn from(err: $error) -> Self { ObjError::$name(err) } } ) } impl fmt::Display for ObjError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &ObjError::Io(ref e) => e.fmt(f), &ObjError::ParseInt(ref e) => e.fmt(f), &ObjError::ParseFloat(ref e) => e.fmt(f), &ObjError::Load(ref e) => e.fmt(f), } } } impl Error for ObjError { fn description(&self) -> &str { match *self { ObjError::Io(ref err) => err.description(), ObjError::ParseInt(ref err) => err.description(), ObjError::ParseFloat(ref err) => err.description(), ObjError::Load(ref err) => err.description(), } } fn cause(&self) -> Option<&Error> { match *self { ObjError::Io(ref err) => Some(err), ObjError::ParseInt(ref err) => Some(err), ObjError::ParseFloat(ref err) => Some(err), ObjError::Load(ref err) => Some(err), } } } implmnt!(Io, io::Error); implmnt!(ParseInt, ParseIntError); implmnt!(ParseFloat, ParseFloatError); implmnt!(Load, LoadError); #[derive(PartialEq, Eq, Clone, Debug)] pub struct LoadError { kind: LoadErrorKind, desc: &'static str, } #[derive(Copy, PartialEq, Eq, Clone, Debug)] pub enum LoadErrorKind { UnexpectedStatement, WrongNumberOfArguments, WrongTypeOfArguments, UntriangulatedModel, InsufficientData, } impl LoadError { pub fn new(kind: LoadErrorKind, desc: &'static str) -> Self { LoadError { kind: kind, desc: desc } } } impl Error for LoadError { fn description(&self) -> &str { match self.kind { LoadErrorKind::UnexpectedStatement => "Met unexpected statement", LoadErrorKind::WrongNumberOfArguments => "Received wrong number of arguments", LoadErrorKind::WrongTypeOfArguments => "Received unexpected type of arguments", LoadErrorKind::UntriangulatedModel => "Model should be triangulated first to be loaded properly", LoadErrorKind::InsufficientData => "Model cannot be transformed into requested form", } } } impl fmt::Display for LoadError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{}: {}", self.description(), self.desc) } } macro_rules! error { ($kind:ident, $desc:expr) => { return Err( ::std::convert::From::from( $crate::error::LoadError::new( $crate::error::LoadErrorKind::$kind, $desc ) ) ) } }
use std::fmt; use std::io; use std::num::{ParseIntError, ParseFloatError}; use std::convert::From; use std::error::Error; pub type ObjResult<T> = Result<T, ObjError>; #[derive(Debug)] pub enum ObjError { Io(io::Error), ParseInt(ParseIntError), ParseFloat(ParseFloatError), Load(LoadError) } macro_rules! implmnt { ($name:ident, $error:path) => ( impl From<$error> for ObjError { fn from(err: $error) -> Self { ObjError::$name(err) } } ) } impl fmt::Display for ObjError {
} impl Error for ObjError { fn description(&self) -> &str { match *self { ObjError::Io(ref err) => err.description(), ObjError::ParseInt(ref err) => err.description(), ObjError::ParseFloat(ref err) => err.description(), ObjError::Load(ref err) => err.description(), } } fn cause(&self) -> Option<&Error> { match *self { ObjError::Io(ref err) => Some(err), ObjError::ParseInt(ref err) => Some(err), ObjError::ParseFloat(ref err) => Some(err), ObjError::Load(ref err) => Some(err), } } } implmnt!(Io, io::Error); implmnt!(ParseInt, ParseIntError); implmnt!(ParseFloat, ParseFloatError); implmnt!(Load, LoadError); #[derive(PartialEq, Eq, Clone, Debug)] pub struct LoadError { kind: LoadErrorKind, desc: &'static str, } #[derive(Copy, PartialEq, Eq, Clone, Debug)] pub enum LoadErrorKind { UnexpectedStatement, WrongNumberOfArguments, WrongTypeOfArguments, UntriangulatedModel, InsufficientData, } impl LoadError { pub fn new(kind: LoadErrorKind, desc: &'static str) -> Self { LoadError { kind: kind, desc: desc } } } impl Error for LoadError { fn description(&self) -> &str { match self.kind { LoadErrorKind::UnexpectedStatement => "Met unexpected statement", LoadErrorKind::WrongNumberOfArguments => "Received wrong number of arguments", LoadErrorKind::WrongTypeOfArguments => "Received unexpected type of arguments", LoadErrorKind::UntriangulatedModel => "Model should be triangulated first to be loaded properly", LoadErrorKind::InsufficientData => "Model cannot be transformed into requested form", } } } impl fmt::Display for LoadError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{}: {}", self.description(), self.desc) } } macro_rules! error { ($kind:ident, $desc:expr) => { return Err( ::std::convert::From::from( $crate::error::LoadError::new( $crate::error::LoadErrorKind::$kind, $desc ) ) ) } }
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &ObjError::Io(ref e) => e.fmt(f), &ObjError::ParseInt(ref e) => e.fmt(f), &ObjError::ParseFloat(ref e) => e.fmt(f), &ObjError::Load(ref e) => e.fmt(f), } }
function_block-full_function
[ { "content": "/// Parses a wavefront `.obj` format.\n\npub fn parse_obj<T: BufRead>(input: T) -> ObjResult<RawObj> {\n\n let mut name = None;\n\n let mut material_libraries = Vec::new();\n\n\n\n let mut positions = Vec::new();\n\n let mut tex_coords = Vec::new();\n\n let mut normals = Vec::new();\n\n let mut param_vertices = Vec::new();\n\n\n\n let mut points = Vec::new();\n\n let mut lines = Vec::new();\n\n let mut polygons = Vec::new();\n\n\n\n let counter = Counter::new(&points, &lines, &polygons);\n\n let mut group_builder = counter.hash_map(\"default\".to_string());\n\n let mut mesh_builder = counter.hash_map(String::new());\n\n let mut smoothing_builder = counter.vec_map();\n\n let mut merging_builder = counter.vec_map();\n\n\n\n try!(lex(input, |stmt, args| {\n", "file_path": "src/raw/object.rs", "rank": 0, "score": 46346.785573901754 }, { "content": "/// Parses a wavefront `.mtl` format *(incomplete)*\n\npub fn parse_mtl<T: BufRead>(input: T) -> ObjResult<RawMtl> {\n\n let mut materials = HashMap::new();\n\n\n\n // Properties of the material being currently parsed\n\n let mut name: Option<String> = None;\n\n let mut mat: Material = Material::default();\n\n\n\n try!(lex(input, |stmt, args| {\n\n match stmt {\n\n // Material name statement\n\n \"newmtl\" => {\n\n // Finish whatever material we were parsing\n\n if let Some(name) = name.take() {\n\n materials.insert(name, replace(&mut mat, Material::default()));\n\n }\n\n\n\n match args.len() {\n\n 1 => name = Some(args[0].to_owned()),\n\n _ => error!(WrongNumberOfArguments, \"Expected exactly 1 argument\")\n\n }\n", "file_path": "src/raw/material.rs", "rank": 1, "score": 46346.785573901754 }, { "content": "pub fn lex<T, F>(input: T, mut callback: F) -> ObjResult<()>\n\n where T: BufRead, F: FnMut(&str, &[&str]) -> ObjResult<()>\n\n{\n\n // This is a buffer of the \"arguments\" for each line, it uses raw pointers\n\n // in order to allow it to be re-used across iterations.\n\n let mut args : Vec<*const str> = Vec::new();\n\n\n\n // This is a buffer for continued lines joined by '\\'.\n\n let mut multi_line = String::new();\n\n\n\n for line in input.lines() {\n\n let line = line?;\n\n let line = line.split('#').next().unwrap(); // Remove comments\n\n\n\n if line.ends_with('\\\\') {\n\n multi_line.push_str(&line[..line.len()-1]);\n\n multi_line.push(' '); // Insert a space to delimit the following lines\n\n continue\n\n }\n\n\n", "file_path": "src/raw/lexer.rs", "rank": 2, "score": 44964.15696264678 }, { "content": "#[test]\n\nfn dome() {\n\n let obj: Obj<Position> = load_obj(fixture!(\"dome.obj\")).unwrap();\n\n\n\n macro_rules! p {\n\n ($($x:expr),*) => (Position { position: [$(stringify!($x).parse::<f32>().unwrap()),*] })\n\n }\n\n\n\n assert_eq!(obj.name, Some(\"Dome\".to_string()));\n\n assert_eq!(obj.vertices[0], p!(-0.382683, 0.923880, 0.000000));\n\n assert_eq!(obj.vertices[1], p!(-0.707107, 0.707107, 0.000000));\n\n assert_eq!(obj.indices[0], 3);\n\n assert_eq!(obj.indices[1], 2);\n\n assert_eq!(obj.indices[2], 6);\n\n}\n\n\n", "file_path": "tests/obj.rs", "rank": 3, "score": 41831.505468034855 }, { "content": "#[cfg(not(feature = \"glium-support\"))]\n\nfn main() {\n\n println!(\"\\n\\\n\n Please execute it with \\x1b[4m--features glium-support\\x1b[24m the option\n\n\n\n $ \\x1b[33mcargo run --example glium --features glium-support\\x1b[0m\\n\");\n\n}\n", "file_path": "examples/glium.rs", "rank": 4, "score": 41831.505468034855 }, { "content": "#[test]\n\nfn cube() {\n\n let mtl = fixture(\"cube.mtl\");\n\n assert_eq!(mtl.materials.len(), 1);\n\n\n\n let mat = mtl.materials.get(\"Material\").unwrap();\n\n assert_eq!(mat, &Material {\n\n ambient: Some(MtlColor::Rgb(0.0, 0.0, 0.0)),\n\n diffuse: Some(MtlColor::Rgb(0.64, 0.64, 0.64)),\n\n specular: Some(MtlColor::Rgb(0.5, 0.5, 0.5)),\n\n dissolve: Some(1.0),\n\n specular_exponent: Some(96.078431),\n\n optical_density: Some(1.0),\n\n illumination_model: Some(2),\n\n diffuse_map: Some(MtlTextureMap { file: \"cube-uv-num.png\".to_owned() }),\n\n ..Material::default()\n\n });\n\n}\n\n\n", "file_path": "tests/raw-material.rs", "rank": 5, "score": 40448.58242215944 }, { "content": "#[test]\n\nfn normal_cone() {\n\n let obj: Obj = load_obj(fixture!(\"normal-cone.obj\")).unwrap();\n\n\n\n macro_rules! v {\n\n (($($p:expr),*), ($($n:expr),*)) => ({\n\n Vertex {\n\n position: [$(stringify!($p).parse::<f32>().unwrap()),*],\n\n normal: [$(stringify!($n).parse::<f32>().unwrap()),*],\n\n }\n\n })\n\n }\n\n\n\n assert_eq!(obj.name, Some(\"Cone\".to_string()));\n\n assert_eq!(obj.vertices.len(), 96);\n\n assert_eq!(obj.vertices[0], v!((-0.382682, -1.000000, -0.923880), (-0.259887, 0.445488, -0.856737)));\n\n assert_eq!(obj.vertices[1], v!(( 0.000000, 1.000000, 0.000000), (-0.259887, 0.445488, -0.856737)));\n\n assert_eq!(obj.indices.len(), 96);\n\n assert_eq!(obj.indices[0], 0);\n\n assert_eq!(obj.indices[1], 1);\n\n assert_eq!(obj.indices[2], 2);\n\n}\n\n\n", "file_path": "tests/obj.rs", "rank": 6, "score": 40448.58242215944 }, { "content": "#[test]\n\nfn textured_cube() {\n\n let obj: Obj<TexturedVertex, u32> = load_obj(fixture!(\"textured-cube.obj\")).unwrap();\n\n\n\n macro_rules! vt {\n\n (($($p:expr),*), ($($n:expr),*), ($($t:expr),*)) => ({\n\n TexturedVertex {\n\n position: [$(stringify!($p).parse::<f32>().unwrap()),*],\n\n normal: [$(stringify!($n).parse::<f32>().unwrap()),*],\n\n texture: [$(stringify!($t).parse::<f32>().unwrap()),*]\n\n }\n\n })\n\n }\n\n\n\n assert_eq!(obj.name, Some(\"cube\".to_string()));\n\n assert_eq!(obj.vertices.len(), 24);\n\n dbg!(&obj.vertices);\n\n assert_eq!(obj.vertices[0], vt!((-0.500000, -0.500000, 0.500000), (0.000000, 0.000000, 1.000000), (0.000000, 0.000000, 0.000000)));\n\n assert_eq!(obj.vertices[1], vt!((0.500000, -0.500000, 0.500000), (0.000000, 0.000000, 1.000000), (1.000000, 0.000000, 0.000000)));\n\n assert_eq!(obj.vertices[2], vt!((-0.500000, 0.500000, 0.500000), (0.000000, 0.000000, 1.000000), (0.000000, 1.000000, 0.000000)));\n\n assert_eq!(obj.vertices[3], vt!((0.500000, 0.500000, 0.500000), (0.000000, 0.000000, 1.000000), (1.000000, 1.000000, 0.000000))); \n", "file_path": "tests/obj.rs", "rank": 7, "score": 40448.58242215944 }, { "content": "#[test]\n\nfn dome() {\n\n let obj = fixture(\"dome.obj\");\n\n\n\n test! {\n\n obj.name, Some(\"Dome\".to_string())\n\n obj.material_libraries, vec![ \"dome.mtl\" ]\n\n\n\n obj.positions.len(), 33\n\n obj.tex_coords.len(), 0\n\n obj.normals.len(), 0\n\n obj.param_vertices.len(), 0\n\n\n\n obj.points.len(), 0\n\n obj.lines.len(), 0\n\n obj.polygons.len(), 62\n\n\n\n obj.groups.len(), 1\n\n obj.meshes.len(), 1\n\n obj.smoothing_groups.len(), 2\n\n obj.merging_groups.len(), 0\n", "file_path": "tests/raw-basics.rs", "rank": 8, "score": 40448.58242215944 }, { "content": "#[test]\n\nfn cube() {\n\n let obj = fixture(\"cube.obj\");\n\n\n\n test! {\n\n obj.name, Some(\"Cube\".to_string())\n\n obj.material_libraries, vec![ \"cube.mtl\" ]\n\n\n\n obj.positions.len(), 8\n\n obj.tex_coords.len(), 14\n\n obj.normals.len(), 0\n\n obj.param_vertices.len(), 0\n\n\n\n obj.points.len(), 0\n\n obj.lines.len(), 0\n\n obj.polygons.len(), 6\n\n\n\n obj.groups.len(), 1\n\n obj.meshes.len(), 1\n\n obj.smoothing_groups.len(), 0\n\n obj.merging_groups.len(), 0\n", "file_path": "tests/raw-basics.rs", "rank": 9, "score": 40448.58242215944 }, { "content": "#[test]\n\nfn untitled() {\n\n let mtl = fixture(\"untitled.mtl\");\n\n assert_eq!(mtl.materials.len(), 2);\n\n\n\n let mat = mtl.materials.get(\"Material\").unwrap();\n\n assert_eq!(mat, &Material {\n\n ambient: Some(MtlColor::Rgb(0.0, 0.0, 0.0)),\n\n diffuse: Some(MtlColor::Rgb(0.64, 0.64, 0.64)),\n\n specular: Some(MtlColor::Rgb(0.5, 0.5, 0.5)),\n\n dissolve: Some(1.0),\n\n specular_exponent: Some(96.078431),\n\n optical_density: Some(1.0),\n\n illumination_model: Some(2),\n\n ..Material::default()\n\n });\n\n\n\n let mat = mtl.materials.get(\"None\").unwrap();\n\n assert_eq!(mat, &Material {\n\n ambient: Some(MtlColor::Rgb(0.0, 0.0, 0.0)),\n\n diffuse: Some(MtlColor::Rgb(0.8, 0.8, 0.8)),\n\n specular: Some(MtlColor::Rgb(0.8, 0.8, 0.8)),\n\n dissolve: Some(1.0),\n\n specular_exponent: Some(0.0),\n\n illumination_model: Some(2),\n\n ..Material::default()\n\n });\n\n}\n", "file_path": "tests/raw-material.rs", "rank": 10, "score": 40448.58242215944 }, { "content": "#[test]\n\nfn sponza() {\n\n // Sponza atrium model, it's reasonably big and more importantly uses negative indexes\n\n // for some of the face specifications.\n\n let obj = fixture(\"sponza.obj\");\n\n\n\n test! {\n\n obj.name, Some(\"sponza.lwo\".to_owned())\n\n obj.positions.len(), 39742\n\n obj.polygons.len(), 36347\n\n }\n\n}\n\n\n", "file_path": "tests/raw-basics.rs", "rank": 11, "score": 40448.58242215944 }, { "content": "#[test]\n\nfn empty() {\n\n let obj = fixture(\"empty.obj\");\n\n\n\n test! {\n\n obj.name, None\n\n obj.material_libraries, Vec::<String>::new()\n\n\n\n obj.positions.len(), 0\n\n obj.tex_coords.len(), 0\n\n obj.normals.len(), 0\n\n obj.param_vertices.len(), 0\n\n\n\n obj.points.len(), 0\n\n obj.lines.len(), 0\n\n obj.polygons.len(), 0\n\n\n\n obj.groups.len(), 0\n\n obj.meshes.len(), 0\n\n obj.smoothing_groups.len(), 0\n\n obj.merging_groups.len(), 0\n\n }\n\n}\n\n\n", "file_path": "tests/raw-basics.rs", "rank": 12, "score": 40448.58242215944 }, { "content": "#[test]\n\nfn lines_points() {\n\n // Basic test for lines and points geometry statements\n\n let obj = fixture(\"lines_points.obj\");\n\n\n\n test! {\n\n obj.name, Some(\"lines.obj\".to_owned())\n\n obj.positions.len(), 3\n\n obj.tex_coords.len(), 2\n\n obj.lines.len(), 2\n\n obj.points.len(), 3\n\n }\n\n}\n", "file_path": "tests/raw-basics.rs", "rank": 13, "score": 39218.029523281875 }, { "content": "#[test]\n\nfn dup_groupnames() {\n\n let input = BufReader::new(File::open(\"tests/fixtures/group.obj\").unwrap());\n\n let raw = match parse_obj(input) {\n\n Ok(raw) => raw,\n\n Err(e) => panic!(e)\n\n };\n\n\n\n test! {\n\n raw.smoothing_groups.len(), 2\n\n raw.smoothing_groups[1].points.len(), 0\n\n raw.smoothing_groups[1].lines.len(), 0\n\n raw.smoothing_groups[1].polygons.len(), 2\n\n raw.smoothing_groups[1].polygons[0], Range { start: 0, end: 3 }\n\n raw.smoothing_groups[1].polygons[1], Range { start: 6, end: 9 }\n\n raw.smoothing_groups[2].points.len(), 0\n\n raw.smoothing_groups[2].lines.len(), 0\n\n raw.smoothing_groups[2].polygons.len(), 1\n\n raw.smoothing_groups[2].polygons[0], Range { start: 3, end: 6 }\n\n }\n\n}\n", "file_path": "tests/raw-group.rs", "rank": 14, "score": 39218.029523281875 }, { "content": "#[test]\n\nfn test_lex() {\n\n let input = r#\"\n\n statement0 arg0 arg1\targ2#argX argX\n\nstatement1 arg0 arg1\n\n# Comment\n\nstatement2 Hello, world!\n\nbmat u 1 -3 3 -1 \\\n\n 0 3 -6 3 \\\n\n 0 0 3 -3 \\\n\n 0 0 0 1\n\nbmat u 1 -3 3 -1 0 3 -6 3 \\\n\n 0 0 3 -3 0 0 0 1\n\nbmat u 1 -3 3 -1 0 3 -6 3 0 0 3 -3 0 0 0 1\n\n\"#;\n\n\n\n assert!(lex(&mut input.as_bytes(), |stmt, args| {\n\n match stmt {\n\n \"statement0\" => assert_eq!(args, [\"arg0\", \"arg1\", \"arg2\"]),\n\n \"statement1\" => assert_eq!(args, [\"arg0\", \"arg1\"]),\n\n \"statement2\" => assert_eq!(args, [\"Hello,\", \"world!\"]),\n\n \"bmat\" => assert_eq!(args, [\"u\", \"1\", \"-3\", \"3\", \"-1\", \"0\", \"3\", \"-6\", \"3\", \"0\", \"0\", \"3\", \"-3\", \"0\", \"0\", \"0\", \"1\"]),\n\n _ => panic!(\"Unit test failed\")\n\n }\n\n Ok(())\n\n }).is_ok());\n\n}\n", "file_path": "src/raw/lexer.rs", "rank": 15, "score": 39218.029523281875 }, { "content": "/// Load a wavefront OBJ file into Rust & OpenGL friendly format.\n\npub fn load_obj<V: FromRawVertex<I>, T: BufRead, I>(input: T) -> ObjResult<Obj<V, I>> {\n\n let raw = try!(raw::parse_obj(input));\n\n Obj::new(raw)\n\n}\n\n\n\n/// 3D model object loaded from wavefront OBJ.\n\n#[derive(Serialize, Deserialize)]\n\npub struct Obj<V = Vertex, I = u16> {\n\n /// Object's name.\n\n pub name: Option<String>,\n\n /// Vertex buffer.\n\n pub vertices: Vec<V>,\n\n /// Index buffer.\n\n pub indices: Vec<I>,\n\n}\n\n\n\nimpl<V: FromRawVertex<I>, I> Obj<V, I> {\n\n /// Create `Obj` from `RawObj` object.\n\n pub fn new(raw: raw::RawObj) -> ObjResult<Self> {\n\n let (vertices, indices) = try!(FromRawVertex::process(raw.positions, raw.normals, raw.tex_coords, raw.polygons));\n\n\n\n Ok(Obj {\n\n name: raw.name,\n\n vertices: vertices,\n\n indices: indices\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 16, "score": 38767.13983613928 }, { "content": "/// Conversion from `RawObj`'s raw data.\n\npub trait FromRawVertex<I> : Sized {\n\n /// Build vertex and index buffer from raw object data.\n\n fn process(vertices: Vec<(f32, f32, f32, f32)>, normals: Vec<(f32, f32, f32)>, tex_coords: Vec<(f32, f32, f32)>, polygons: Vec<Polygon>) -> ObjResult<(Vec<Self>, Vec<I>)>;\n\n}\n\n\n\n/// Vertex data type of `Obj` which contains position and normal data of a vertex.\n\n#[derive(Copy, PartialEq, Clone, Debug, Serialize, Deserialize)]\n\npub struct Vertex {\n\n /// Position vector of a vertex.\n\n pub position: [f32; 3],\n\n /// Normal vertor of a vertex.\n\n pub normal: [f32; 3],\n\n}\n\n\n\n#[cfg(feature = \"glium-support\")]\n\nimplement_vertex!(Vertex, position, normal);\n\n\n\nimpl<I: FromPrimitive + Integer + Copy> FromRawVertex<I> for Vertex {\n\n fn process(positions: Vec<(f32, f32, f32, f32)>, normals: Vec<(f32, f32, f32)>, _: Vec<(f32, f32, f32)>, polygons: Vec<Polygon>) -> ObjResult<(Vec<Self>, Vec<I>)> {\n\n let mut vb = Vec::with_capacity(polygons.len() * 3);\n", "file_path": "src/lib.rs", "rank": 17, "score": 35028.287816044125 }, { "content": "#[bench]\n\nfn sponza(b: &mut Bencher) {\n\n let data = load_file(\"sponza.obj\");\n\n let mut data = std::io::Cursor::new(&data[..]);\n\n b.iter(|| {\n\n parse_obj(&mut data).unwrap()\n\n });\n\n}\n", "file_path": "benches/bench.rs", "rank": 18, "score": 33412.84336503969 }, { "content": "fn fixture(filename: &str) -> RawMtl {\n\n use std::path::Path;\n\n use std::fs::File;\n\n use std::io::BufReader;\n\n\n\n let path = Path::new(\"tests\").join(\"fixtures\").join(filename);\n\n let file = match File::open(&path) {\n\n Ok(f) => f,\n\n Err(e) => panic!(\"Failed to open \\\"{}\\\". \\x1b[31m{}\\x1b[0m\", path.to_string_lossy(), e)\n\n };\n\n let input = BufReader::new(file);\n\n\n\n parse_mtl(input).unwrap()\n\n}\n\n\n", "file_path": "tests/raw-material.rs", "rank": 19, "score": 30419.299672512065 }, { "content": "fn fixture(filename: &str) -> RawObj {\n\n use std::path::Path;\n\n use std::fs::File;\n\n use std::io::BufReader;\n\n\n\n let path = Path::new(\"tests\").join(\"fixtures\").join(filename);\n\n let file = match File::open(&path) {\n\n Ok(f) => f,\n\n Err(e) => panic!(\"Failed to open \\\"{}\\\". \\x1b[31m{}\\x1b[0m\", path.to_string_lossy(), e)\n\n };\n\n let input = BufReader::new(file);\n\n\n\n parse_obj(input).unwrap()\n\n}\n\n\n\nmacro_rules! test_v4 {\n\n ($lhs:expr => $($x:expr, $y:expr, $z:expr, $w:expr;)*) => ({\n\n let mut index = 0usize;\n\n $(\n\n let (x, y, z, w) = $lhs[index];\n", "file_path": "tests/raw-basics.rs", "rank": 20, "score": 30419.299672512065 }, { "content": "fn load_file(filename: &str) -> Vec<u8> {\n\n use std::path::Path;\n\n use std::fs::File;\n\n use std::io::Read;\n\n\n\n let path = Path::new(\"tests\").join(\"fixtures\").join(filename);\n\n let mut file = match File::open(&path) {\n\n Ok(f) => f,\n\n Err(e) => panic!(\"Failed to open \\\"{}\\\". \\x1b[31m{}\\x1b[0m\", path.to_string_lossy(), e)\n\n };\n\n\n\n let mut data = Vec::new();\n\n match file.read_to_end(&mut data) {\n\n Err(e) => panic!(\"Failed to read \\\"{}\\\". \\x1b[31m{}\\x1b[0m\", path.to_string_lossy(), e),\n\n Ok(_) => ()\n\n }\n\n\n\n data\n\n}\n\n\n", "file_path": "benches/bench.rs", "rank": 21, "score": 29231.394964624236 }, { "content": "/// Parses a color from the arguments of a statement\n\nfn parse_color(args: &[&str]) -> ObjResult<MtlColor> {\n\n if args.is_empty() {\n\n error!(WrongNumberOfArguments, \"Expected at least 1 argument\");\n\n }\n\n\n\n Ok(match args[0] {\n\n \"xyz\" => {\n\n let args = f!(&args[1..]);\n\n match args.len() {\n\n 1 => MtlColor::Xyz(args[0], args[0], args[0]),\n\n 3 => MtlColor::Xyz(args[0], args[1], args[2]),\n\n _ => error!(WrongNumberOfArguments, \"Expected 1 or 3 color values\")\n\n }\n\n }\n\n\n\n \"spectral\" => {\n\n match args.len() {\n\n 2 => MtlColor::Spectral(args[1].to_owned(), 1.0),\n\n 3 => MtlColor::Spectral(args[1].to_owned(), try!(args[2].parse())),\n\n _ => error!(WrongNumberOfArguments, \"Expected 2 or 3 arguments\")\n", "file_path": "src/raw/material.rs", "rank": 22, "score": 26981.52256242364 }, { "content": "/// Parses a texture map specification from the arguments of a statement\n\nfn parse_texture_map(args: &[&str]) -> ObjResult<MtlTextureMap> {\n\n if args.len() == 1 {\n\n Ok(MtlTextureMap { file: args[0].to_owned() })\n\n } else {\n\n error!(WrongNumberOfArguments, \"Expected exactly 1 argument\")\n\n }\n\n}\n\n\n\n/// Low-level Rust binding for `.mtl` format *(incomplete)*.\n\n#[derive(Clone, Debug)]\n\npub struct RawMtl {\n\n /// Map from the material name to its properties\n\n pub materials: HashMap<String, Material>\n\n}\n\n\n\n/// A single material from a `.mtl` file\n\n#[derive(Clone, PartialEq, Debug, Default)]\n\npub struct Material {\n\n /// The ambient color, specified by `Ka`\n\n pub ambient: Option<MtlColor>,\n", "file_path": "src/raw/material.rs", "rank": 30, "score": 25768.37464512796 }, { "content": "// Parses the vertex group in the face statement, missing entries\n\n// are indicated with a 0 value\n\nfn parse_vertex_group(s: &str) -> ObjResult<(i32, i32, i32)> {\n\n let mut indices = s.split('/');\n\n\n\n let first = indices.next().unwrap_or(\"\");\n\n let second = indices.next().unwrap_or(\"\");\n\n let third = indices.next().unwrap_or(\"\");\n\n\n\n let first = try!(first.parse());\n\n let second = if second == \"\" {\n\n 0\n\n } else {\n\n try!(second.parse())\n\n };\n\n\n\n let third = if third == \"\" {\n\n 0\n\n } else {\n\n try!(third.parse())\n\n };\n\n\n\n Ok((first, second, third))\n\n}\n\n\n\n\n", "file_path": "src/raw/object.rs", "rank": 31, "score": 24551.694624674812 }, { "content": "#[macro_use] mod error;\n\npub mod raw;\n\n\n\nuse num::{FromPrimitive, Integer};\n\nuse std::io::BufRead;\n\nuse std::collections::hash_map::{HashMap, Entry};\n\nuse raw::object::Polygon;\n\npub use error::{ObjResult, ObjError, LoadError, LoadErrorKind};\n\n\n\n/// Load a wavefront OBJ file into Rust & OpenGL friendly format.\n", "file_path": "src/lib.rs", "rank": 32, "score": 9.145514236046079 }, { "content": " use glium::{vertex, index, VertexBuffer, IndexBuffer};\n\n use glium::backend::Facade;\n\n use super::Obj;\n\n\n\n impl<V: vertex::Vertex, I: glium::index::Index> Obj<V, I> {\n\n /// Retrieve glium-compatible vertex buffer from Obj\n\n pub fn vertex_buffer<F: Facade>(&self, facade: &F) -> Result<VertexBuffer<V>, vertex::BufferCreationError> {\n\n VertexBuffer::new(facade, &self.vertices)\n\n }\n\n\n\n /// Retrieve glium-compatible index buffer from Obj\n\n pub fn index_buffer<F: Facade>(&self, facade: &F) -> Result<IndexBuffer<I>, index::BufferCreationError> {\n\n IndexBuffer::new(facade, index::PrimitiveType::TrianglesList, &self.indices)\n\n }\n\n }\n\n}\n", "file_path": "src/lib.rs", "rank": 33, "score": 8.728070407893533 }, { "content": " if group.2 != 0 {\n\n error!(WrongTypeOfArguments, \"Unexpected vertex format\");\n\n }\n\n\n\n points.push((\n\n idx!(group.0, positions),\n\n idx!(group.1, tex_coords)));\n\n }\n\n Line::PT(points)\n\n }\n\n _ => {\n\n error!(WrongTypeOfArguments, \"Unexpected vertex format, expected `#` or `#/#`\");\n\n }\n\n };\n\n lines.push(line);\n\n }\n\n \"fo\" | \"f\" => {\n\n if args.len() < 3 { error!(WrongNumberOfArguments, \"Expected at least 3 arguments\") }\n\n\n\n let mut args = args.iter();\n", "file_path": "src/raw/object.rs", "rank": 34, "score": 5.367314921518111 }, { "content": "// Copyright 2014-2017 Hyeon Kim\n\n//\n\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n\n// option. This file may not be copied, modified, or distributed\n\n// except according to those terms.\n\n\n\n//! Provides low-level API for Wavefront OBJ format.\n\n\n\nmod lexer;\n\npub mod object;\n\npub mod material;\n\n\n\npub use self::object::{parse_obj, RawObj};\n\npub use self::material::{parse_mtl, RawMtl};\n", "file_path": "src/raw/mod.rs", "rank": 35, "score": 5.189779181376492 }, { "content": " 2 if args[0] == \"rat\" => { _rational = true; args[1] }\n\n 1 => { _rational = false; args[0] }\n\n _ => error!(WrongTypeOfArguments, \"Expected 'rat xxx' or 'xxx' format\")\n\n };\n\n\n\n match geometry {\n\n \"bmatrix\" => unimplemented!(),\n\n \"bezier\" => unimplemented!(),\n\n \"bspline\" => unimplemented!(),\n\n \"cardinal\" => unimplemented!(),\n\n \"taylor\" => unimplemented!(),\n\n _ => error!(WrongTypeOfArguments, \"Expected one of 'bmatrix', 'bezier', 'bspline', 'cardinal' and 'taylor'\")\n\n }\n\n }\n\n \"deg\" => {\n\n let args = f!(args);\n\n match args.len() {\n\n 2 => unimplemented!(), // (deg_u, deg_v)\n\n 1 => unimplemented!(), // (deg_u)\n\n _ => error!(WrongNumberOfArguments, \"Expected 1 or 2 arguments\")\n", "file_path": "src/raw/object.rs", "rank": 36, "score": 4.944046430002453 }, { "content": "pub struct TexturedVertex {\n\n /// Position vector of a vertex.\n\n pub position: [f32; 3],\n\n /// Normal vertor of a vertex.\n\n pub normal: [f32; 3],\n\n /// Texture of a vertex.\n\n pub texture: [f32; 3]\n\n}\n\n\n\n#[cfg(feature = \"glium-support\")]\n\nimplement_vertex!(TexturedVertex, position, normal, texture);\n\n\n\nimpl<I: FromPrimitive + Integer + Copy> FromRawVertex<I> for TexturedVertex {\n\n fn process(positions: Vec<(f32, f32, f32, f32)>, normals: Vec<(f32, f32, f32)>, tex_coords: Vec<(f32, f32, f32)>, polygons: Vec<Polygon>) -> ObjResult<(Vec<Self>, Vec<I>)> {\n\n let mut vb = Vec::with_capacity(polygons.len() * 3);\n\n let mut ib = Vec::with_capacity(polygons.len() * 3);\n\n {\n\n let mut cache = HashMap::new();\n\n let mut map = |pi: usize, ni: usize, ti: usize| {\n\n // Look up cache\n", "file_path": "src/lib.rs", "rank": 37, "score": 4.927458782157471 }, { "content": "// Copyright 2014-2017 Hyeon Kim\n\n//\n\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n\n// option. This file may not be copied, modified, or distributed\n\n// except according to those terms.\n\n\n\nuse std;\n\nuse std::io::prelude::*;\n\nuse error::ObjResult;\n\n\n", "file_path": "src/raw/lexer.rs", "rank": 38, "score": 4.614878601498033 }, { "content": "\n\n\n\n/// Constant which is used to represent undefined bound of range.\n\nconst UNDEFINED: usize = ::std::usize::MAX;\n\n\n\nimpl Group {\n\n fn new(count: (usize, usize, usize)) -> Self {\n\n let mut ret = Group {\n\n points: Vec::with_capacity(1),\n\n lines: Vec::with_capacity(1),\n\n polygons: Vec::with_capacity(1)\n\n };\n\n ret.start(count);\n\n ret\n\n }\n\n\n\n fn start(&mut self, count: (usize, usize, usize)) {\n\n self.points.push(Range { start: count.0, end: UNDEFINED });\n\n self.lines.push(Range { start: count.1, end: UNDEFINED });\n\n self.polygons.push(Range { start: count.2, end: UNDEFINED })\n", "file_path": "src/raw/object.rs", "rank": 39, "score": 4.52697892129598 }, { "content": " /// The diffuse color, specified by `Kd`\n\n pub diffuse: Option<MtlColor>,\n\n /// The specular color, specified by `Ks`\n\n pub specular: Option<MtlColor>,\n\n /// The emissive color, specified by `Ke`\n\n pub emissive: Option<MtlColor>,\n\n /// The transmission filter, specified by `Tf`\n\n pub transmission_filter: Option<MtlColor>,\n\n /// The illumination model to use for this material; see the `.mtl` spec for more details.\n\n pub illumination_model: Option<u32>,\n\n /// The dissolve (opacity) of the material, specified by `d`\n\n pub dissolve: Option<f32>,\n\n /// The specular exponent, specified by `Ne`\n\n pub specular_exponent: Option<f32>,\n\n /// The optical density, i.e. index of refraction, specified by `Ni`\n\n pub optical_density: Option<f32>,\n\n /// The ambient color map, specified by `map_Ka`\n\n pub ambient_map: Option<MtlTextureMap>,\n\n /// The diffuse color map, specified by `map_Kd`\n\n pub diffuse_map: Option<MtlTextureMap>,\n", "file_path": "src/raw/material.rs", "rank": 40, "score": 4.430365112993197 }, { "content": "// Copyright 2014-2017 Hyeon Kim\n\n//\n\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n\n// option. This file may not be copied, modified, or distributed\n\n// except according to those terms.\n\n\n\n//! Parses `.mtl` format which stores material data\n\n\n\nuse std::io::prelude::*;\n\nuse std::collections::HashMap;\n\nuse std::mem::replace;\n\n\n\nuse error::ObjResult;\n\nuse raw::lexer::lex;\n\n\n\n/// Parses &[&str] into &[f32].\n\nmacro_rules! f {\n\n ($args:expr) => (\n", "file_path": "src/raw/material.rs", "rank": 41, "score": 4.383881059861473 }, { "content": "// Copyright 2014-2017 Hyeon Kim\n\n//\n\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n\n// option. This file may not be copied, modified, or distributed\n\n// except according to those terms.\n\n\n\n//! Parses `.obj` format which stores 3D mesh data\n\n\n\nuse std::io::BufRead;\n\nuse std::collections::HashMap;\n\nuse vec_map::VecMap;\n\nuse error::ObjResult;\n\nuse raw::lexer::lex;\n\n\n\n/// Parses &[&str] into &[f32].\n\nmacro_rules! f {\n\n ($args:expr) => (\n\n &{\n", "file_path": "src/raw/object.rs", "rank": 42, "score": 4.31264260892797 }, { "content": "}\n\n\n\n/// Vertex data type of `Obj` which contains only position data of a vertex.\n\n#[derive(Copy, PartialEq, Clone, Debug, Serialize, Deserialize)]\n\npub struct Position {\n\n /// Position vector of a vertex.\n\n pub position: [f32; 3]\n\n}\n\n\n\n#[cfg(feature = \"glium-support\")]\n\nimplement_vertex!(Position, position);\n\n\n\nimpl<I: FromPrimitive + Integer> FromRawVertex<I> for Position {\n\n fn process(vertices: Vec<(f32, f32, f32, f32)>, _: Vec<(f32, f32, f32)>, _: Vec<(f32, f32, f32)>, polygons: Vec<Polygon>) -> ObjResult<(Vec<Self>, Vec<I>)> {\n\n let vb = vertices.into_iter().map(|v| Position { position: [v.0, v.1, v.2] }).collect();\n\n let mut ib = Vec::with_capacity(polygons.len() * 3);\n\n {\n\n let mut map = |pi: usize| { ib.push(I::from_usize(pi).expect(\"Unable to convert the index from usize\")) };\n\n\n\n for polygon in polygons {\n", "file_path": "src/lib.rs", "rank": 43, "score": 4.262158990687179 }, { "content": " /// The specular color map, specified by `map_Ks`\n\n pub specular_map: Option<MtlTextureMap>,\n\n /// The emissive color map, specified by `map_Ke`\n\n pub emissive_map: Option<MtlTextureMap>,\n\n /// The dissolve map, specified by `map_d`\n\n pub dissolve_map: Option<MtlTextureMap>,\n\n /// The bump map (normal map), specified by `bump`\n\n pub bump_map: Option<MtlTextureMap>,\n\n}\n\n\n\n/// A color specified in a `.mtl` file\n\n#[derive(Clone, PartialEq, Debug)]\n\npub enum MtlColor {\n\n /// Color in the RGB color space\n\n Rgb(f32, f32, f32),\n\n /// Color in the CIEXYZ color space\n\n Xyz(f32, f32, f32),\n\n /// Color using a spectral curve\n\n ///\n\n /// The first argument is the name of a `.rfl` file specifying the curve.\n", "file_path": "src/raw/material.rs", "rank": 44, "score": 4.0147976758304775 }, { "content": " let mut polygon = vec![(\n\n idx!(p, positions),\n\n idx!(t, tex_coords))];\n\n for gs in rest {\n\n let group = try!(parse_vertex_group(gs));\n\n if group.2 != 0 {\n\n error!(WrongTypeOfArguments, \"Unexpected vertex format\");\n\n }\n\n\n\n polygon.push((\n\n idx!(group.0, positions),\n\n idx!(group.1, tex_coords)));\n\n }\n\n\n\n Polygon::PT(polygon)\n\n }\n\n (p, 0, n) => {\n\n let mut polygon = vec![(\n\n idx!(p, positions),\n\n idx!(n, normals))];\n", "file_path": "src/raw/object.rs", "rank": 45, "score": 3.539684793448432 }, { "content": " for gs in rest {\n\n let group = try!(parse_vertex_group(gs));\n\n if group.1 != 0 {\n\n error!(WrongTypeOfArguments, \"Unexpected vertex format\");\n\n }\n\n\n\n polygon.push((\n\n idx!(group.0, positions),\n\n idx!(group.2, normals)));\n\n }\n\n\n\n Polygon::PN(polygon)\n\n }\n\n (p, t, n) => {\n\n let mut polygon = vec![(\n\n idx!(p, positions),\n\n idx!(t, tex_coords),\n\n idx!(n, normals))];\n\n for gs in rest {\n\n let group = try!(parse_vertex_group(gs));\n", "file_path": "src/raw/object.rs", "rank": 46, "score": 3.499303377599087 }, { "content": " let first = args.next().unwrap();\n\n let rest = args;\n\n\n\n let group = try!(parse_vertex_group(first));\n\n\n\n let polygon = match group {\n\n (p, 0, 0) => {\n\n let mut polygon = vec![idx!(p, positions)];\n\n for gs in rest {\n\n let group = try!(parse_vertex_group(gs));\n\n if group.1 != 0 || group.2 != 0 {\n\n error!(WrongTypeOfArguments, \"Unexpected vertex format\");\n\n }\n\n\n\n polygon.push(idx!(group.0, positions));\n\n }\n\n\n\n Polygon::P(polygon)\n\n }\n\n (p, t, 0) => {\n", "file_path": "src/raw/object.rs", "rank": 47, "score": 3.499303377599087 }, { "content": " pub param_vertices: Vec<(f32, f32, f32)>,\n\n\n\n /// Points which stores the index data of position vectors.\n\n pub points: Vec<Point>,\n\n /// Lines which store the index data of vectors.\n\n pub lines: Vec<Line>,\n\n /// Polygons which store the index data of vectors.\n\n pub polygons: Vec<Polygon>,\n\n\n\n /// Groups of multiple geometries.\n\n pub groups: HashMap<String, Group>,\n\n /// Geometries which consist in a same material.\n\n pub meshes: HashMap<String, Group>,\n\n /// Smoothing groups.\n\n pub smoothing_groups: VecMap<Group>,\n\n /// Merging groups.\n\n pub merging_groups: VecMap<Group>\n\n}\n\n\n\n/// The `Point` type which stores the index of the position vector.\n", "file_path": "src/raw/object.rs", "rank": 48, "score": 3.4769930350772817 }, { "content": " PN(Vec<(usize, usize)>),\n\n /// A polygon which contains all position, texture coordinate and normal data of each vertex.\n\n PTN(Vec<(usize, usize, usize)>)\n\n}\n\n\n\n/// A group which contains ranges of points, lines and polygons\n\n#[derive(Clone, Debug)]\n\npub struct Group {\n\n /// Multiple range of points\n\n pub points: Vec<Range>,\n\n /// Multiple range of lines\n\n pub lines: Vec<Range>,\n\n /// Multiple range of polygons\n\n pub polygons: Vec<Range>\n\n}\n\n\n\n\n\n/// A struct which represent `[start, end)` range.\n\n#[derive(Copy, PartialEq, Eq, Clone, Debug)]\n\npub struct Range {\n\n /// The lower bound of the range (inclusive).\n\n pub start: usize,\n\n /// The upper bound of the range (exclusive).\n\n pub end: usize\n\n}\n", "file_path": "src/raw/object.rs", "rank": 49, "score": 3.364168587863815 }, { "content": "\n\n let line = match group {\n\n (p, 0, 0) => {\n\n let mut points = vec![idx!(p, positions)];\n\n for gs in rest {\n\n let group = try!(parse_vertex_group(gs));\n\n if group.1 != 0 || group.2 != 0 {\n\n error!(WrongTypeOfArguments, \"Unexpected vertex format\");\n\n }\n\n\n\n points.push(idx!(group.0, positions));\n\n }\n\n Line::P(points)\n\n }\n\n (p, t, 0) => {\n\n let mut points = vec![(\n\n idx!(p, positions),\n\n idx!(t, tex_coords))];\n\n for gs in rest {\n\n let group = try!(parse_vertex_group(gs));\n", "file_path": "src/raw/object.rs", "rank": 50, "score": 3.346589203118696 }, { "content": "/// A trait which should be implemented by a type passed into `Key` of `Map`.\n\ntrait Key : Eq {}\n\n\n\nimpl Key for String {}\n\nimpl Key for usize {}\n\n\n\n\n\n/// Low-level Rust binding for `.obj` format.\n\npub struct RawObj {\n\n /// Name of the object.\n\n pub name: Option<String>,\n\n /// `.mtl` files which required by this object.\n\n pub material_libraries: Vec<String>,\n\n\n\n /// Position vectors of each vertex.\n\n pub positions: Vec<(f32, f32, f32, f32)>,\n\n /// Texture coordinates of each vertex.\n\n pub tex_coords: Vec<(f32, f32, f32)>,\n\n /// Normal vectors of each vertex.\n\n pub normals: Vec<(f32, f32, f32)>,\n\n /// Parametric vertices.\n", "file_path": "src/raw/object.rs", "rank": 51, "score": 3.109482886076595 }, { "content": " ],\n\n light: (-1.0, -1.0, -1.0f32)\n\n };\n\n\n\n let params = glium::DrawParameters {\n\n depth: glium::Depth {\n\n test: glium::DepthTest::IfLess,\n\n write: true,\n\n ..Default::default()\n\n },\n\n ..Default::default()\n\n };\n\n\n\n // the main loop\n\n // each cycle will draw once\n\n let mut running = true;\n\n while running {\n\n use glium::Surface;\n\n use std::thread::sleep;\n\n use std::time::Duration;\n", "file_path": "examples/glium.rs", "rank": 52, "score": 2.9695104650106368 }, { "content": "// Copyright 2014-2017 Hyeon Kim\n\n//\n\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n\n// option. This file may not be copied, modified, or distributed\n\n// except according to those terms.\n\n\n\nextern crate obj;\n\n\n\nuse std::fs::File;\n\nuse std::io::BufReader;\n\nuse obj::raw::*;\n\nuse obj::raw::object::Range;\n\n\n\nmacro_rules! test {\n\n ($($lhs:expr, $rhs:expr)*) => ({\n\n $(eq!($lhs, $rhs);)*\n\n });\n\n}\n", "file_path": "tests/raw-group.rs", "rank": 53, "score": 2.8954307733903173 }, { "content": " }\n\n \"illum\" => {\n\n match args.len() {\n\n 1 => mat.illumination_model = Some(try!(args[0].parse())),\n\n _ => error!(WrongNumberOfArguments, \"Expected exactly 1 argument\")\n\n }\n\n }\n\n \"d\" => {\n\n match args.len() {\n\n 1 => mat.dissolve = Some(try!(args[0].parse())),\n\n _ => error!(WrongNumberOfArguments, \"Expected exactly 1 argument\")\n\n }\n\n }\n\n \"Tr\" => {\n\n match args.len() {\n\n 1 => mat.dissolve = Some(1.0 - try!(args[0].parse::<f32>())),\n\n _ => error!(WrongNumberOfArguments, \"Expected exactly 1 argument\")\n\n }\n\n }\n\n\n", "file_path": "src/raw/material.rs", "rank": 54, "score": 2.8091625652868446 }, { "content": " /// The second argument is a multiplier for the values in the `.rfl` file.\n\n Spectral(String, f32)\n\n}\n\n\n\n/// A texture map specified in a `.mtl` file\n\n#[derive(Clone, PartialEq, Eq, Debug)]\n\npub struct MtlTextureMap {\n\n /// The name of the texture file\n\n pub file: String,\n\n // TODO: support arguments to the texture map\n\n}\n", "file_path": "src/raw/material.rs", "rank": 55, "score": 2.738057987022006 }, { "content": " for polygon in polygons {\n\n match polygon {\n\n Polygon::P(_) => error!(InsufficientData, \"Tried to extract normal and texture data which are not contained in the model\"),\n\n Polygon::PT(_) => error!(InsufficientData, \"Tried to extract normal data which are not contained in the model\"),\n\n Polygon::PN(_) => error!(InsufficientData, \"Tried to extract texture data which are not contained in the model\"),\n\n Polygon::PTN(ref vec) if vec.len() == 3 => {\n\n for &(pi, ti, ni) in vec { map(pi, ni, ti) }\n\n }\n\n _ => error!(UntriangulatedModel, \"Model should be triangulated first to be loaded properly\")\n\n }\n\n }\n\n }\n\n vb.shrink_to_fit();\n\n Ok((vb, ib))\n\n }\n\n}\n\n\n\n\n\n#[cfg(feature = \"glium-support\")]\n\nmod glium_support {\n", "file_path": "src/lib.rs", "rank": 56, "score": 2.704392087524562 }, { "content": "// Copyright 2014-2017 Hyeon Kim\n\n//\n\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n\n// option. This file may not be copied, modified, or distributed\n\n// except according to those terms.\n\n\n\nextern crate obj;\n\n\n\nuse std::fs::File;\n\nuse std::io::BufReader;\n\nuse obj::*;\n\n\n\nmacro_rules! fixture {\n\n ($name:expr) => (BufReader::new(File::open(concat!(\"tests/fixtures/\", $name)).unwrap()))\n\n}\n\n\n\n#[test]\n", "file_path": "tests/obj.rs", "rank": 57, "score": 2.582237748344732 }, { "content": "pub type Point = usize;\n\n\n\n/// The `Line` type.\n\n#[derive(PartialEq, Eq, Clone, Debug)]\n\npub enum Line {\n\n /// A series of line segments which contain only the position data of each vertex\n\n P(Vec<usize>),\n\n /// A series of line segments which contain both position and texture coordinate\n\n /// data of each vertex\n\n PT(Vec<(usize, usize)>)\n\n}\n\n\n\n/// The `Polygon` type.\n\n#[derive(PartialEq, Eq, Clone, Debug)]\n\npub enum Polygon {\n\n /// A polygon which contains only the position data of each vertex.\n\n P(Vec<usize>),\n\n /// A polygon which contains both position and texture coordinate data of each vertex.\n\n PT(Vec<(usize, usize)>),\n\n /// A polygon which contains both position and normal data of each vertex.\n", "file_path": "src/raw/object.rs", "rank": 58, "score": 2.567680683475059 }, { "content": "// Copyright 2014-2017 Hyeon Kim\n\n//\n\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n\n// option. This file may not be copied, modified, or distributed\n\n// except according to those terms.\n\n\n\n/*!\n\n\n\n[Wavefront OBJ][obj] parser for Rust. It handles both `.obj` and `.mtl` formats. [GitHub][]\n\n\n\n```rust\n\nuse std::fs::File;\n\nuse std::io::BufReader;\n\nuse obj::*;\n\n\n\nlet input = BufReader::new(File::open(\"tests/fixtures/normal-cone.obj\").unwrap());\n\nlet dome: Obj = load_obj(input).unwrap();\n\n\n", "file_path": "src/lib.rs", "rank": 59, "score": 2.4436746488949304 }, { "content": " match stmt {\n\n // Vertex data\n\n \"v\" => {\n\n let args = f!(args);\n\n positions.push(match args.len() {\n\n 4 => (args[0], args[1], args[2], args[3]),\n\n 3 => (args[0], args[1], args[2], 1.0),\n\n _ => error!(WrongNumberOfArguments, \"Expected 3 or 4 arguments\")\n\n })\n\n }\n\n \"vt\" => {\n\n let args = f!(args);\n\n tex_coords.push(match args.len() {\n\n 3 => (args[0], args[1], args[2]),\n\n 2 => (args[0], args[1], 0.0),\n\n 1 => (args[0], 0.0, 0.0),\n\n _ => error!(WrongNumberOfArguments, \"Expected 1, 2 or 3 arguments\")\n\n })\n\n }\n\n \"vn\" => {\n", "file_path": "src/raw/object.rs", "rank": 60, "score": 2.387398479252434 }, { "content": "// Copyright 2014-2017 Hyeon Kim\n\n//\n\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n\n// option. This file may not be copied, modified, or distributed\n\n// except according to those terms.\n\n\n\n#![feature(test)]\n\n\n\nextern crate obj;\n\nextern crate test;\n\n\n\nuse test::Bencher;\n\n\n\nuse obj::raw::parse_obj;\n\n\n", "file_path": "benches/bench.rs", "rank": 61, "score": 2.3717348147016515 }, { "content": " \"scrv\" => unimplemented!(),\n\n \"sp\" => unimplemented!(),\n\n \"end\" => unimplemented!(),\n\n\n\n // Connectivity between free-form surfaces\n\n \"con\" => unimplemented!(),\n\n\n\n // Grouping\n\n \"g\" => {\n\n match args.len() {\n\n 1 => group_builder.start(args[0].to_string()),\n\n _ => error!(WrongNumberOfArguments, \"Expected group name parameter, but nothing has been supplied\")\n\n }\n\n }\n\n \"s\" => {\n\n match args.len() {\n\n 1 if (args[0] == \"off\" || args[0] == \"0\") => smoothing_builder.end(),\n\n 1 => smoothing_builder.start(try!(args[0].parse())),\n\n _ => error!(WrongNumberOfArguments, \"Expected only 1 argument\")\n\n }\n", "file_path": "src/raw/object.rs", "rank": 62, "score": 2.368451965300313 }, { "content": " \"usemtl\" => {\n\n match args.len() {\n\n 1 => mesh_builder.start(args[0].to_string()),\n\n _ => error!(WrongNumberOfArguments, \"Expected only 1 argument\")\n\n }\n\n }\n\n \"mtllib\" => {\n\n // TODO: .push_all()\n\n material_libraries.reserve(args.len());\n\n for path in args {\n\n material_libraries.push(path.to_string());\n\n }\n\n }\n\n \"shadow_obj\" => unimplemented!(),\n\n \"trace_obj\" => unimplemented!(),\n\n \"ctech\" => unimplemented!(),\n\n \"stech\" => unimplemented!(),\n\n\n\n // Unexpected statement\n\n _ => error!(UnexpectedStatement, \"Received unknown statement\")\n", "file_path": "src/raw/object.rs", "rank": 63, "score": 2.349803804570155 }, { "content": " let args = f!(args);\n\n normals.push(match args.len() {\n\n 3 => (args[0], args[1], args[2]),\n\n _ => error!(WrongNumberOfArguments, \"Expected 3 arguments\")\n\n })\n\n }\n\n \"vp\" => {\n\n let args = f!(args);\n\n param_vertices.push(match args.len() {\n\n 3 => (args[0], args[1], args[2]),\n\n 2 => (args[0], args[1], 1.0),\n\n 1 => (args[0], 0.0, 1.0),\n\n _ => error!(WrongNumberOfArguments, \"Expected 1, 2 or 3 arguments\")\n\n })\n\n }\n\n\n\n // Free-form curve / surface attributes\n\n \"cstype\" => {\n\n let _rational: bool;\n\n let geometry = match args.len() {\n", "file_path": "src/raw/object.rs", "rank": 64, "score": 2.349803804570155 }, { "content": "// Do whatever you want\n\ndome.vertices;\n\ndome.indices;\n\n```\n\n\n\n<img src=\"http://simnalamburt.github.io/obj-rs/screenshot.png\" style=\"max-width:100%\">\n\n\n\n[obj]: https://en.wikipedia.org/wiki/Wavefront_.obj_file\n\n[GitHub]: https://github.com/simnalamburt/obj-rs\n\n\n\n*/\n\n\n\n#![deny(missing_docs)]\n\n\n\n#[cfg(feature = \"glium-support\")] #[macro_use] extern crate glium;\n\nextern crate num;\n\nextern crate vec_map;\n\n\n\n#[macro_use] extern crate serde_derive;\n\n\n", "file_path": "src/lib.rs", "rank": 65, "score": 2.199879025312731 }, { "content": " };\n\n ib.push(index)\n\n };\n\n\n\n for polygon in polygons {\n\n match polygon {\n\n Polygon::P(_) | Polygon::PT(_) => error!(InsufficientData, \"Tried to extract normal data which are not contained in the model\"),\n\n Polygon::PN(ref vec) if vec.len() == 3 => {\n\n for &(pi, ni) in vec { map(pi, ni) }\n\n }\n\n Polygon::PTN(ref vec) if vec.len() == 3 => {\n\n for &(pi, _, ni) in vec { map(pi, ni) }\n\n }\n\n _ => error!(UntriangulatedModel, \"Model should be triangulated first to be loaded properly\")\n\n }\n\n }\n\n }\n\n vb.shrink_to_fit();\n\n Ok((vb, ib))\n\n }\n", "file_path": "src/lib.rs", "rank": 66, "score": 2.178294378642745 }, { "content": " }\n\n }\n\n\n\n _ => {\n\n let args = f!(args);\n\n match args.len() {\n\n 1 => MtlColor::Rgb(args[0], args[0], args[0]),\n\n 3 => MtlColor::Rgb(args[0], args[1], args[2]),\n\n _ => error!(WrongNumberOfArguments, \"Expected 1 or 3 color values\")\n\n }\n\n }\n\n })\n\n}\n\n\n", "file_path": "src/raw/material.rs", "rank": 67, "score": 2.173451235172776 }, { "content": " }\n\n\n\n // Material color and illumination statements\n\n \"Ka\" => mat.ambient = Some(try!(parse_color(args))),\n\n \"Kd\" => mat.diffuse = Some(try!(parse_color(args))),\n\n \"Ks\" => mat.specular = Some(try!(parse_color(args))),\n\n \"Ke\" => mat.emissive = Some(try!(parse_color(args))),\n\n \"Km\" => unimplemented!(),\n\n \"Tf\" => mat.transmission_filter = Some(try!(parse_color(args))),\n\n \"Ns\" => {\n\n match args.len() {\n\n 1 => mat.specular_exponent = Some(try!(args[0].parse())),\n\n _ => error!(WrongNumberOfArguments, \"Expected exactly 1 argument\")\n\n }\n\n }\n\n \"Ni\" => {\n\n match args.len() {\n\n 1 => mat.optical_density = Some(try!(args[0].parse())),\n\n _ => error!(WrongNumberOfArguments, \"Expected exactly 1 argument\")\n\n }\n", "file_path": "src/raw/material.rs", "rank": 68, "score": 2.0164020720360236 }, { "content": "obj-rs [![Travis Build Status]][travis] [![AppVeyor Build Status]][appveyor]\n\n========\n\n[Wavefront obj] parser for [Rust]. It handles both `.obj` and `.mtl` formats.\n\n\n\n- [API Documentation](https://simnalamburt.github.io/obj-rs/)\n\n- [See `obj-rs` in crates.io](https://crates.io/crates/obj-rs)\n\n\n\n```toml\n\n[dependencies]\n\nobj-rs = \"0.4\"\n\n```\n\n```rust\n\nuse std::fs::File;\n\nuse std::io::BufReader;\n\nuse obj::*;\n\n\n\nlet input = try!(BufReader::new(File::open(\"tests/fixtures/dome.obj\")));\n\nlet dome: Obj = try!(load_obj(input));\n\n\n\n// Do whatever you want\n\ndome.vertices;\n\ndome.indices;\n\n```\n\n\n\n![img]\n\n\n\n> This sample image is pretty good illustration of current status of **obj-rs**.\n\n**obj-rs** is currently able to load position and normal data of `obj` but not\n\ntexture & material data yet.\n\n\n\n<br>\n\n\n\nGlium support\n\n--------\n\n**obj-rs** supports [glium] out of the box.\n\n\n\n```toml\n\n[dependencies]\n\nglium = \"0.14\"\n\nobj-rs = { version = \"0.4\", features = [\"glium-support\"] }\n\n```\n\n```rust\n\nuse std::fs::File;\n\nuse std::io::BufReader;\n\nuse obj::*;\n\n\n\nlet input = BufReader::new(try!(File::open(\"rilakkuma.obj\")));\n\nlet obj: Obj = try!(load_obj(input));\n\n\n\nlet vb = try!(obj.vertex_buffer(&display));\n\nlet ib = try!(obj.index_buffer(&display));\n\n```\n\n\n\nPlease see the [working sample] for the further details. Use can execute it with\n\nthe command below.\n\n```bash\n\ncargo run --example glium --features glium-support\n\n```\n\n\n\n<br>\n\n\n\n--------\n\n*obj-rs* is primarily distributed under the terms of both the [Apache License\n\n(Version 2.0)] and the [MIT license]. See [COPYRIGHT] for details.\n\n\n\n[Travis Build Status]: https://travis-ci.org/simnalamburt/obj-rs.svg?branch=master\n\n[travis]: https://travis-ci.org/simnalamburt/obj-rs\n\n[AppVeyor Build Status]: https://ci.appveyor.com/api/projects/status/281kjgy7oxaa120s/branch/master?svg=true\n\n[appveyor]: https://ci.appveyor.com/project/simnalamburt/obj-rs/branch/master\n\n\n\n[Wavefront obj]: https://en.wikipedia.org/wiki/Wavefront_.obj_file\n\n[Rust]: http://rust-lang.org\n\n[img]: https://simnalamburt.github.io/obj-rs/screenshot.png\n\n[glium]: https://github.com/tomaka/glium\n\n[working sample]: examples/glium.rs\n\n[MIT license]: LICENSE-MIT\n\n[Apache License (Version 2.0)]: LICENSE-APACHE\n\n[COPYRIGHT]: COPYRIGHT\n", "file_path": "README.md", "rank": 69, "score": 1.9759617433130363 }, { "content": " }\n\n }\n\n \"bmat\" => unimplemented!(),\n\n \"step\" => unimplemented!(),\n\n\n\n // Elements\n\n \"p\" => {\n\n for v in args {\n\n let v : i32 = try!(v.parse());\n\n let v = idx!(v, positions);\n\n points.push(v);\n\n }\n\n }\n\n \"l\" => {\n\n if args.len() < 2 { error!(WrongNumberOfArguments, \"Expected at least 2 arguments\") }\n\n let mut args = args.iter();\n\n let first = args.next().unwrap();\n\n let rest = args;\n\n\n\n let group = try!(parse_vertex_group(first));\n", "file_path": "src/raw/object.rs", "rank": 70, "score": 1.8500862841781238 }, { "content": " }\n\n \"mg\" => {\n\n match args.len() {\n\n 1 if (args[0] == \"off\" || args[0] == \"0\") => merging_builder.end(),\n\n 1 => merging_builder.start(try!(args[0].parse())),\n\n _ => error!(WrongNumberOfArguments, \"Expected only 1 argument\")\n\n }\n\n }\n\n \"o\" => {\n\n name = match args.len() {\n\n 0 => None,\n\n _ => Some(args.join(\" \"))\n\n }\n\n }\n\n\n\n // Display / render attributes\n\n \"bevel\" => unimplemented!(),\n\n \"c_interp\" => unimplemented!(),\n\n \"d_interp\" => unimplemented!(),\n\n \"lod\" => unimplemented!(),\n", "file_path": "src/raw/object.rs", "rank": 71, "score": 1.8274292854922525 }, { "content": "// Copyright 2014-2017 Hyeon Kim\n\n//\n\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n\n// option. This file may not be copied, modified, or distributed\n\n// except according to those terms.\n\n\n\nextern crate obj;\n\n\n\nuse obj::raw::{RawObj, parse_obj};\n\n\n", "file_path": "tests/raw-basics.rs", "rank": 72, "score": 1.731760050839843 }, { "content": "\n\nmacro_rules! eq {\n\n ($lhs:expr, $rhs:expr) => (eq!($lhs, $rhs, stringify!($lhs)));\n\n\n\n ($lhs:expr, $rhs:expr, $exp:expr) => ({\n\n let left = &($lhs);\n\n let right = &($rhs);\n\n\n\n if !((*left == *right) && (*right == *left)) {\n\n use std::io::Write;\n\n let _ = writeln!(&mut std::io::stderr(), \"\\x1b[33m{}\\x1b[0m should be \\x1b[33m{:?}\\x1b[0m, \\\n\n but it was \\x1b[33m{:?}\\x1b[0m\", $exp, *right, *left);\n\n panic!($exp);\n\n }\n\n });\n\n}\n\n\n", "file_path": "tests/raw-basics.rs", "rank": 73, "score": 1.6744526032799207 }, { "content": "// Copyright 2014-2017 Hyeon Kim\n\n//\n\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n\n// option. This file may not be copied, modified, or distributed\n\n// except according to those terms.\n\n\n\nextern crate obj;\n\n\n\nuse obj::raw::material::{RawMtl, Material, MtlColor, MtlTextureMap, parse_mtl};\n\n\n", "file_path": "tests/raw-material.rs", "rank": 74, "score": 1.603693323074617 }, { "content": "\n\n let mut target = display.draw();\n\n target.clear_color_and_depth((0.0, 0.0, 0.0, 0.0), 1.0);\n\n target.draw(&vb, &ib, &program, &uniforms, &params).unwrap();\n\n target.finish().unwrap();\n\n\n\n // sleeping for some time in order not to use up too much CPU\n\n sleep(Duration::from_millis(17));\n\n\n\n // polling and handling the events received by the window\n\n events_loop.poll_events(|event| {\n\n match event {\n\n glutin::Event::WindowEvent {event: glutin::WindowEvent::CloseRequested, ..} => running = false,\n\n _ => ()\n\n }\n\n });\n\n }\n\n}\n\n\n", "file_path": "examples/glium.rs", "rank": 75, "score": 1.5705098965571946 }, { "content": " let index = match cache.entry((pi, ni, ti)) {\n\n // Cache miss -> make new, store it on cache\n\n Entry::Vacant(entry) => {\n\n let p = positions[pi];\n\n let n = normals[ni];\n\n let t = tex_coords[ti];\n\n let vertex = TexturedVertex { position: [p.0, p.1, p.2], normal: [n.0, n.1, n.2], texture: [t.0, t.1, t.2] };\n\n let index = I::from_usize(vb.len()).expect(\"Unable to convert the index from usize\");\n\n vb.push(vertex);\n\n entry.insert(index);\n\n index\n\n }\n\n // Cache hit -> use it\n\n Entry::Occupied(entry) => {\n\n *entry.get()\n\n }\n\n };\n\n ib.push(index)\n\n };\n\n\n", "file_path": "src/lib.rs", "rank": 76, "score": 1.5232320975684193 }, { "content": "// Copyright 2014-2017 Hyeon Kim\n\n//\n\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n\n// option. This file may not be copied, modified, or distributed\n\n// except according to those terms.\n\n\n\n//! Working example of *obj-rs*\n\n//! ========\n\n//!\n\n//! Execute it with the command below\n\n//!\n\n//! cargo run --example glium --features glium-support\n\n\n\n#[macro_use] extern crate glium;\n\nextern crate obj;\n\n\n\n#[cfg(feature = \"glium-support\")]\n", "file_path": "examples/glium.rs", "rank": 77, "score": 1.4787175663228433 }, { "content": "\n\nmacro_rules! eq {\n\n ($lhs:expr, $rhs:expr) => (eq!($lhs, $rhs, stringify!($lhs)));\n\n\n\n ($lhs:expr, $rhs:expr, $exp:expr) => ({\n\n let left = &($lhs);\n\n let right = &($rhs);\n\n\n\n if !((*left == *right) && (*right == *left)) {\n\n stderr!(\"\");\n\n stderr!(\"{w}{}{c} should be {o}{:?}{c}, but it was {o}{:?}{c}. See {b}{}:{}{c}.\",\n\n $exp, *right, *left, line!(), column!(),\n\n w=\"\\x1b[97m\", b=\"\\x1b[34m\", o=\"\\x1b[33m\", c=\"\\x1b[0m\");\n\n stderr!(\"\");\n\n panic!($exp);\n\n }\n\n });\n\n}\n\n\n\nmacro_rules! stderr {\n\n ($($arg:tt)*) => ({\n\n use std::io::Write;\n\n writeln!(&mut std::io::stderr(), $($arg)*).unwrap()\n\n })\n\n}\n\n\n\n#[test]\n", "file_path": "tests/raw-group.rs", "rank": 78, "score": 1.4787175663228433 }, { "content": " let mut ib = Vec::with_capacity(polygons.len() * 3);\n\n {\n\n let mut cache = HashMap::new();\n\n let mut map = |pi: usize, ni: usize| {\n\n // Look up cache\n\n let index = match cache.entry((pi, ni)) {\n\n // Cache miss -> make new, store it on cache\n\n Entry::Vacant(entry) => {\n\n let p = positions[pi];\n\n let n = normals[ni];\n\n let vertex = Vertex { position: [p.0, p.1, p.2], normal: [n.0, n.1, n.2]};\n\n let index = I::from_usize(vb.len()).expect(\"Unable to convert the index from usize\");\n\n vb.push(vertex);\n\n entry.insert(index);\n\n index\n\n }\n\n // Cache hit -> use it\n\n Entry::Occupied(entry) => {\n\n *entry.get()\n\n }\n", "file_path": "src/lib.rs", "rank": 79, "score": 1.3843224005108343 }, { "content": " match polygon {\n\n Polygon::P(ref vec) if vec.len() == 3 => {\n\n for &pi in vec { map(pi) }\n\n }\n\n Polygon::PT(ref vec) | Polygon::PN(ref vec) if vec.len() == 3 => {\n\n for &(pi, _) in vec { map(pi) }\n\n }\n\n Polygon::PTN(ref vec) if vec.len() == 3 => {\n\n for &(pi, _, _) in vec { map(pi) }\n\n }\n\n _ => error!(UntriangulatedModel, \"Model should be triangulated first to be loaded properly\")\n\n }\n\n }\n\n }\n\n Ok((vb, ib))\n\n }\n\n}\n\n\n\n/// Vertex data type of `Obj` which contains position, normal and texture data of a vertex.\n\n#[derive(Copy, PartialEq, Clone, Debug, Serialize, Deserialize)]\n", "file_path": "src/lib.rs", "rank": 80, "score": 1.3733313760530148 }, { "content": " // Texture map statements\n\n \"map_Ka\" => mat.ambient_map = Some(try!(parse_texture_map(args))),\n\n \"map_Kd\" => mat.diffuse_map = Some(try!(parse_texture_map(args))),\n\n \"map_Ks\" => mat.specular_map = Some(try!(parse_texture_map(args))),\n\n \"map_Ke\" => mat.emissive_map = Some(try!(parse_texture_map(args))),\n\n \"map_d\" => mat.dissolve_map = Some(try!(parse_texture_map(args))),\n\n \"map_aat\" => unimplemented!(),\n\n \"map_refl\" => unimplemented!(),\n\n \"map_bump\" | \"map_Bump\" | \"bump\" => mat.bump_map = Some(try!(parse_texture_map(args))),\n\n \"disp\" => unimplemented!(),\n\n\n\n // Reflection map statement\n\n \"refl\" => unimplemented!(),\n\n\n\n // Unexpected statement\n\n _ => error!(UnexpectedStatement, \"Received unknown statement\")\n\n }\n\n\n\n Ok(())\n\n }));\n\n\n\n // Insert the final material\n\n if let Some(name) = name {\n\n materials.insert(name, mat);\n\n }\n\n\n\n Ok(RawMtl { materials })\n\n}\n\n\n", "file_path": "src/raw/material.rs", "rank": 81, "score": 1.0761941634189842 } ]
Rust
shipico/src/old/math/rect.rs
Shipica/Shipica.github.io
d5d451481d013228d99b98c1ccc1c8924f23ed61
use super::point::Point; use super::size::Size; use super::thickness::Thickness; use super::vec2::Vec2; use std::f64::{INFINITY, NEG_INFINITY}; use std::ops::{Add, Sub}; #[derive(Copy, Clone, Debug, Default, PartialEq)] #[repr(C)] pub struct Rect { pub left: f64, pub top: f64, pub right: f64, pub bottom: f64, } #[derive(Copy, Clone, Debug)] pub enum RectCorner { TopLeft, TopRight, BottomLeft, BottomRight, } impl Rect { pub const INFINITE: Rect = Rect { left: NEG_INFINITY, top: NEG_INFINITY, right: INFINITY, bottom: INFINITY, }; #[inline] pub fn new(left: f64, top: f64, right: f64, bottom: f64) -> Rect { Rect { left, top, right, bottom, } } #[inline] pub fn from_points(p1: impl Into<Point>, p2: impl Into<Point>) -> Rect { let p1 = p1.into(); let p2 = p2.into(); Rect { left: p1.x.min(p2.x), top: p1.y.min(p2.y), right: p1.x.max(p2.x), bottom: p1.y.max(p2.y), } } #[inline] pub fn from_center_size(center: impl Into<Point>, size: impl Into<Size>) -> Rect { let center = center.into(); let size = size.into(); Rect { left: center.x - size.width / 2.0, top: center.y - size.height / 2.0, right: center.x + size.width / 2.0, bottom: center.y + size.height / 2.0, } } #[inline] pub fn from_center_half_extent( center: impl Into<Point>, half_extents: impl Into<Vec2>, ) -> Rect { let center = center.into(); let half_extents = half_extents.into(); Rect { left: center.x - half_extents.x, top: center.y - half_extents.y, right: center.x + half_extents.x, bottom: center.y + half_extents.y, } } #[inline] pub fn rounded(&self) -> Rect { Rect { left: self.left.round(), top: self.top.round(), right: self.right.round(), bottom: self.bottom.round(), } } #[inline] pub fn size(&self) -> Size { ( self.right.max(self.left) - self.right.min(self.left), self.top.max(self.bottom) - self.top.min(self.bottom), ) .into() } #[inline] pub fn center(&self) -> Point { Point { x: (self.left + self.right) / 2.0, y: (self.top + self.bottom) / 2.0, } } #[inline] pub fn half_extent(&self) -> Vec2 { let size = self.size(); [size.width / 2.0, size.height / 2.0].into() } #[inline] pub fn corner(&self, corner: RectCorner) -> Point { match corner { RectCorner::TopLeft => (self.left, self.top).into(), RectCorner::TopRight => (self.right, self.top).into(), RectCorner::BottomLeft => (self.left, self.bottom).into(), RectCorner::BottomRight => (self.right, self.bottom).into(), } } #[inline] pub fn contains_point(&self, point: impl Into<Point>) -> bool { let point = point.into(); point.x >= self.left && point.y >= self.top && point.x <= self.right && point.y <= self.bottom } #[inline] pub fn overlaps(&self, other: &Rect) -> bool { let a = self.normalized(); let b = other.normalized(); a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top } #[inline] pub fn normalized(self) -> Self { Rect { left: self.left.min(self.right), top: self.top.min(self.bottom), right: self.left.max(self.right), bottom: self.top.max(self.bottom), } } #[inline] pub fn translated_by(self, translation: impl Into<Vec2>) -> Self { let trans = translation.into(); Rect { left: self.left + trans.x, top: self.top + trans.y, right: self.right + trans.x, bottom: self.bottom + trans.y, } } #[inline] pub fn expanded_by(self, thickness: impl Into<Thickness>) -> Self { let t = thickness.into(); Rect { left: self.left - t.left, top: self.top - t.top, right: self.right + t.right, bottom: self.bottom + t.bottom, } } #[inline] pub fn shrunken_by(self, thickness: impl Into<Thickness>) -> Self { let t = thickness.into(); Rect { left: self.left + t.left, top: self.top + t.top, right: self.right - t.right, bottom: self.bottom - t.bottom, } } #[inline] pub fn combined_with(&self, other: impl Into<Rect>) -> Self { let r1 = self.normalized(); let r2 = other.into().normalized(); let left = r1.left.min(r2.left); let top = r1.top.min(r2.top); let right = r1.right.max(r2.right); let bottom = r1.bottom.max(r2.bottom); Rect { left, top, right, bottom, } } } impl Add<Vec2> for Rect { type Output = Rect; #[inline] fn add(self, rhs: Vec2) -> Rect { self.translated_by(rhs) } } impl Sub<Vec2> for Rect { type Output = Rect; #[inline] fn sub(self, rhs: Vec2) -> Rect { self.translated_by(-rhs) } } impl From<(Point, Point)> for Rect { #[inline] fn from((p1, p2): (Point, Point)) -> Rect { Rect::from_points(p1, p2) } } impl From<(Point, Size)> for Rect { #[inline] fn from((center, size): (Point, Size)) -> Rect { Rect::from_center_size(center, size) } } impl From<(Point, Vec2)> for Rect { #[inline] fn from((center, half_extent): (Point, Vec2)) -> Rect { Rect::from_center_half_extent(center, half_extent) } } impl From<[f64; 4]> for Rect { #[inline] fn from(p: [f64; 4]) -> Rect { let (left, top, right, bottom) = (p[0], p[1], p[2], p[3]); Rect { left, top, right, bottom, } } }
use super::point::Point; use super::size::Size; use super::thickness::Thickness; use super::vec2::Vec2; use std::f64::{INFINITY, NEG_INFINITY}; use std::ops::{Add, Sub}; #[derive(Copy, Clone, Debug, Default, PartialEq)] #[repr(C)] pub struct Rect { pub left: f64, pub top: f64, pub right: f64, pub bottom: f64, } #[derive(Copy, Clone, Debug)] pub enum RectCorner { TopLeft, TopRight, BottomLeft, BottomRight, } impl Rect { pub const INFINITE: Rect = Rect { left: NEG_INFINITY, top: NEG_INFINITY, right: INFINITY, bottom: INFINITY, }; #[inline] pub fn new(left: f64, top: f64, right: f64, bottom: f64) -> Rect { Rect { left, top, right, bottom, } } #[inline] pub fn from_points(p1: impl Into<Point>, p2: impl Into<Point>) -> Rect { let p1 = p1.into(); let p2 = p2.into(); Rect { left: p1.x.min(p2.x), top: p1.y.min(p2.y), right: p1.x.max(p2.x), bottom: p1.y.max(p2.y), } } #[inline] pub fn from_center_size(center: impl Into<Point>, size: impl Into<Size>) -> Rect { let center = center.into(); let size = size.into(); Rect { left: center.x - size.width / 2.0, top: center.y - size.height / 2.0, right: center.x + size.width / 2.0, bottom: center.y + size.height / 2.0, } } #[inline]
#[inline] pub fn rounded(&self) -> Rect { Rect { left: self.left.round(), top: self.top.round(), right: self.right.round(), bottom: self.bottom.round(), } } #[inline] pub fn size(&self) -> Size { ( self.right.max(self.left) - self.right.min(self.left), self.top.max(self.bottom) - self.top.min(self.bottom), ) .into() } #[inline] pub fn center(&self) -> Point { Point { x: (self.left + self.right) / 2.0, y: (self.top + self.bottom) / 2.0, } } #[inline] pub fn half_extent(&self) -> Vec2 { let size = self.size(); [size.width / 2.0, size.height / 2.0].into() } #[inline] pub fn corner(&self, corner: RectCorner) -> Point { match corner { RectCorner::TopLeft => (self.left, self.top).into(), RectCorner::TopRight => (self.right, self.top).into(), RectCorner::BottomLeft => (self.left, self.bottom).into(), RectCorner::BottomRight => (self.right, self.bottom).into(), } } #[inline] pub fn contains_point(&self, point: impl Into<Point>) -> bool { let point = point.into(); point.x >= self.left && point.y >= self.top && point.x <= self.right && point.y <= self.bottom } #[inline] pub fn overlaps(&self, other: &Rect) -> bool { let a = self.normalized(); let b = other.normalized(); a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top } #[inline] pub fn normalized(self) -> Self { Rect { left: self.left.min(self.right), top: self.top.min(self.bottom), right: self.left.max(self.right), bottom: self.top.max(self.bottom), } } #[inline] pub fn translated_by(self, translation: impl Into<Vec2>) -> Self { let trans = translation.into(); Rect { left: self.left + trans.x, top: self.top + trans.y, right: self.right + trans.x, bottom: self.bottom + trans.y, } } #[inline] pub fn expanded_by(self, thickness: impl Into<Thickness>) -> Self { let t = thickness.into(); Rect { left: self.left - t.left, top: self.top - t.top, right: self.right + t.right, bottom: self.bottom + t.bottom, } } #[inline] pub fn shrunken_by(self, thickness: impl Into<Thickness>) -> Self { let t = thickness.into(); Rect { left: self.left + t.left, top: self.top + t.top, right: self.right - t.right, bottom: self.bottom - t.bottom, } } #[inline] pub fn combined_with(&self, other: impl Into<Rect>) -> Self { let r1 = self.normalized(); let r2 = other.into().normalized(); let left = r1.left.min(r2.left); let top = r1.top.min(r2.top); let right = r1.right.max(r2.right); let bottom = r1.bottom.max(r2.bottom); Rect { left, top, right, bottom, } } } impl Add<Vec2> for Rect { type Output = Rect; #[inline] fn add(self, rhs: Vec2) -> Rect { self.translated_by(rhs) } } impl Sub<Vec2> for Rect { type Output = Rect; #[inline] fn sub(self, rhs: Vec2) -> Rect { self.translated_by(-rhs) } } impl From<(Point, Point)> for Rect { #[inline] fn from((p1, p2): (Point, Point)) -> Rect { Rect::from_points(p1, p2) } } impl From<(Point, Size)> for Rect { #[inline] fn from((center, size): (Point, Size)) -> Rect { Rect::from_center_size(center, size) } } impl From<(Point, Vec2)> for Rect { #[inline] fn from((center, half_extent): (Point, Vec2)) -> Rect { Rect::from_center_half_extent(center, half_extent) } } impl From<[f64; 4]> for Rect { #[inline] fn from(p: [f64; 4]) -> Rect { let (left, top, right, bottom) = (p[0], p[1], p[2], p[3]); Rect { left, top, right, bottom, } } }
pub fn from_center_half_extent( center: impl Into<Point>, half_extents: impl Into<Vec2>, ) -> Rect { let center = center.into(); let half_extents = half_extents.into(); Rect { left: center.x - half_extents.x, top: center.y - half_extents.y, right: center.x + half_extents.x, bottom: center.y + half_extents.y, } }
function_block-full_function
[ { "content": "pub fn glWeightfvARB(size: GLint, weights: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 0, "score": 319145.9366847262 }, { "content": "pub fn glWeightusvARB(size: GLint, weights: *const GLushort) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 1, "score": 319145.9366847262 }, { "content": "pub fn glWeightdvARB(size: GLint, weights: *const GLdouble) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 2, "score": 319145.9366847262 }, { "content": "pub fn glWeightubvARB(size: GLint, weights: *const GLubyte) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 3, "score": 319145.9366847262 }, { "content": "pub fn glWeightbvARB(size: GLint, weights: *const GLbyte) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 4, "score": 319145.9366847262 }, { "content": "pub fn glWeightivARB(size: GLint, weights: *const GLint) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 5, "score": 319145.9366847262 }, { "content": "pub fn glWeightsvARB(size: GLint, weights: *const GLshort) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 6, "score": 319145.9366847262 }, { "content": "pub fn glWeightusvARB(size: GLint, weights: *const GLushort) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 7, "score": 319145.9366847262 }, { "content": "pub fn glWeightbvARB(size: GLint, weights: *const GLbyte) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 8, "score": 319145.9366847262 }, { "content": "pub fn glWeightivARB(size: GLint, weights: *const GLint) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 9, "score": 319145.9366847262 }, { "content": "pub fn glWeightuivARB(size: GLint, weights: *const GLuint) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 10, "score": 319145.9366847262 }, { "content": "pub fn glWeightbvARB(size: GLint, weights: *const GLbyte) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 11, "score": 319145.9366847262 }, { "content": "pub fn glWeightdvARB(size: GLint, weights: *const GLdouble) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 12, "score": 319145.9366847262 }, { "content": "pub fn glWeightuivARB(size: GLint, weights: *const GLuint) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 13, "score": 319145.9366847262 }, { "content": "pub fn glWeightuivARB(size: GLint, weights: *const GLuint) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 14, "score": 319145.9366847262 }, { "content": "pub fn glWeightubvARB(size: GLint, weights: *const GLubyte) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 15, "score": 319145.9366847262 }, { "content": "pub fn glWeightivARB(size: GLint, weights: *const GLint) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 16, "score": 319145.9366847262 }, { "content": "pub fn glWeightfvARB(size: GLint, weights: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 17, "score": 319145.9366847262 }, { "content": "pub fn glWeightsvARB(size: GLint, weights: *const GLshort) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 18, "score": 319145.9366847262 }, { "content": "pub fn glWeightusvARB(size: GLint, weights: *const GLushort) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 19, "score": 319145.9366847262 }, { "content": "pub fn glWeightubvARB(size: GLint, weights: *const GLubyte) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 20, "score": 319145.9366847262 }, { "content": "pub fn glWeightdvARB(size: GLint, weights: *const GLdouble) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 21, "score": 319145.9366847262 }, { "content": "pub fn glWeightfvARB(size: GLint, weights: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 22, "score": 319145.9366847262 }, { "content": "pub fn glWeightsvARB(size: GLint, weights: *const GLshort) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 23, "score": 319145.9366847262 }, { "content": "pub fn glMatrixIndexusvARB(size: GLint, indices: *const GLushort) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 24, "score": 316030.6155635694 }, { "content": "pub fn glMatrixIndexubvARB(size: GLint, indices: *const GLubyte) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 25, "score": 316030.6155635694 }, { "content": "pub fn glMatrixIndexuivARB(size: GLint, indices: *const GLuint) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 26, "score": 316030.6155635694 }, { "content": "pub fn glMatrixIndexusvARB(size: GLint, indices: *const GLushort) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 27, "score": 316030.6155635694 }, { "content": "pub fn glMatrixIndexubvARB(size: GLint, indices: *const GLubyte) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 28, "score": 316030.6155635694 }, { "content": "pub fn glMatrixIndexuivARB(size: GLint, indices: *const GLuint) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 29, "score": 316030.6155635694 }, { "content": "pub fn glMatrixIndexuivARB(size: GLint, indices: *const GLuint) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 30, "score": 316030.6155635694 }, { "content": "pub fn glMatrixIndexubvARB(size: GLint, indices: *const GLubyte) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 31, "score": 316030.6155635694 }, { "content": "pub fn glMatrixIndexusvARB(size: GLint, indices: *const GLushort) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 32, "score": 316030.6155635694 }, { "content": "pub fn glPixelMapx(map: GLenum, size: GLint, values: *const GLfixed) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 33, "score": 296295.4220820715 }, { "content": "pub fn glPixelMapx(map: GLenum, size: GLint, values: *const GLfixed) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 34, "score": 296295.4220820715 }, { "content": "pub fn glPixelMapx(map: GLenum, size: GLint, values: *const GLfixed) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 35, "score": 296295.4220820715 }, { "content": "pub fn glPointSize(size: GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 36, "score": 279601.14918174327 }, { "content": "pub fn glPointSize(size: GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 37, "score": 279601.14918174327 }, { "content": "pub fn glPointSize(size: GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 38, "score": 279601.14918174327 }, { "content": "pub fn glVertexPointer(size: GLint, type_: GLenum, stride: GLsizei, ptr: *const GLvoid) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 39, "score": 276886.40205057367 }, { "content": "pub fn glColorPointer(size: GLint, type_: GLenum, stride: GLsizei, ptr: *const GLvoid) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 40, "score": 276886.40205057367 }, { "content": "pub fn glVertexPointer(size: GLint, type_: GLenum, stride: GLsizei, ptr: *const GLvoid) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 41, "score": 276886.40205057367 }, { "content": "pub fn glVertexPointer(size: GLint, type_: GLenum, stride: GLsizei, ptr: *const GLvoid) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 42, "score": 276886.40205057367 }, { "content": "pub fn glColorPointer(size: GLint, type_: GLenum, stride: GLsizei, ptr: *const GLvoid) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 43, "score": 276886.40205057367 }, { "content": "pub fn glColorPointer(size: GLint, type_: GLenum, stride: GLsizei, ptr: *const GLvoid) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 44, "score": 276886.40205057367 }, { "content": "pub fn glTexCoordPointer(size: GLint, type_: GLenum, stride: GLsizei, ptr: *const GLvoid) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 45, "score": 274316.4534432518 }, { "content": "pub fn glTexCoordPointer(size: GLint, type_: GLenum, stride: GLsizei, ptr: *const GLvoid) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 46, "score": 274316.4534432518 }, { "content": "pub fn glTexCoordPointer(size: GLint, type_: GLenum, stride: GLsizei, ptr: *const GLvoid) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 47, "score": 274316.4534432518 }, { "content": "pub fn glPointSizexOES(size: GLfixed) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 48, "score": 261468.2891872702 }, { "content": "pub fn glPointSizexOES(size: GLfixed) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 49, "score": 261468.28918727016 }, { "content": "pub fn glPointSizexOES(size: GLfixed) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 50, "score": 261468.28918727016 }, { "content": "pub fn glDebugMessageCallback(callback: GLDEBUGPROC, userParam: *const ::std::os::raw::c_void) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 51, "score": 258178.24497591075 }, { "content": "pub fn glDebugMessageCallback(callback: GLDEBUGPROC, userParam: *const ::std::os::raw::c_void) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 52, "score": 258178.24497591075 }, { "content": "pub fn glDebugMessageCallback(callback: GLDEBUGPROC, userParam: *const ::std::os::raw::c_void) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 53, "score": 258178.24497591075 }, { "content": "pub fn glColor3fVertex3fvSUN(c: *const GLfloat, v: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 54, "score": 258175.96686115547 }, { "content": "pub fn glColor4ubVertex3fvSUN(c: *const GLubyte, v: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 55, "score": 258175.96686115547 }, { "content": "pub fn glRectfv(v1: *const GLfloat, v2: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 56, "score": 258175.96686115547 }, { "content": "pub fn glRectfv(v1: *const GLfloat, v2: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 57, "score": 258175.96686115547 }, { "content": "pub fn glColor4ubVertex3fvSUN(c: *const GLubyte, v: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 58, "score": 258175.96686115547 }, { "content": "pub fn glRectsv(v1: *const GLshort, v2: *const GLshort) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 59, "score": 258175.96686115547 }, { "content": "pub fn glRectdv(v1: *const GLdouble, v2: *const GLdouble) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 60, "score": 258175.96686115547 }, { "content": "pub fn glColor4ubVertex2fvSUN(c: *const GLubyte, v: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 61, "score": 258175.96686115547 }, { "content": "pub fn glRectiv(v1: *const GLint, v2: *const GLint) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 62, "score": 258175.96686115547 }, { "content": "pub fn glRectfv(v1: *const GLfloat, v2: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 63, "score": 258175.96686115547 }, { "content": "pub fn glRectdv(v1: *const GLdouble, v2: *const GLdouble) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 64, "score": 258175.96686115547 }, { "content": "pub fn glRectdv(v1: *const GLdouble, v2: *const GLdouble) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 65, "score": 258175.96686115547 }, { "content": "pub fn glColor4ubVertex3fvSUN(c: *const GLubyte, v: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 66, "score": 258175.96686115547 }, { "content": "pub fn glColor3fVertex3fvSUN(c: *const GLfloat, v: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 67, "score": 258175.96686115547 }, { "content": "pub fn glRectiv(v1: *const GLint, v2: *const GLint) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 68, "score": 258175.96686115547 }, { "content": "pub fn glNormal3fVertex3fvSUN(n: *const GLfloat, v: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 69, "score": 258175.96686115547 }, { "content": "pub fn glNormal3fVertex3fvSUN(n: *const GLfloat, v: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 70, "score": 258175.96686115547 }, { "content": "pub fn glColor3fVertex3fvSUN(c: *const GLfloat, v: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 71, "score": 258175.96686115547 }, { "content": "pub fn glColor4ubVertex2fvSUN(c: *const GLubyte, v: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 72, "score": 258175.96686115547 }, { "content": "pub fn glRectiv(v1: *const GLint, v2: *const GLint) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 73, "score": 258175.96686115547 }, { "content": "pub fn glRectsv(v1: *const GLshort, v2: *const GLshort) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-dummy/src/gl.rs", "rank": 74, "score": 258175.96686115547 }, { "content": "pub fn glNormal3fVertex3fvSUN(n: *const GLfloat, v: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 75, "score": 258175.96686115547 }, { "content": "pub fn glColor4ubVertex2fvSUN(c: *const GLubyte, v: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 76, "score": 258175.96686115547 }, { "content": "pub fn glRectsv(v1: *const GLshort, v2: *const GLshort) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-kms/src/gl.rs", "rank": 77, "score": 258175.96686115547 }, { "content": "pub fn glVertex3iv(v: *const GLint) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 78, "score": 257451.66424510535 }, { "content": "pub fn glVertex4dv(v: *const GLdouble) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 79, "score": 257451.66424510535 }, { "content": "pub fn glIndexdv(c: *const GLdouble) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 80, "score": 257451.66424510535 }, { "content": "pub fn glIndexfv(c: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 81, "score": 257451.66424510535 }, { "content": "pub fn glVertex4sv(v: *const GLshort) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 82, "score": 257451.66424510535 }, { "content": "pub fn glVertex3dv(v: *const GLdouble) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 83, "score": 257451.66424510535 }, { "content": "pub fn glNormal3bv(v: *const GLbyte) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 84, "score": 257451.66424510535 }, { "content": "pub fn glVertex2dv(v: *const GLdouble) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 85, "score": 257451.66424510535 }, { "content": "pub fn glIndexsv(c: *const GLshort) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 86, "score": 257451.66424510535 }, { "content": "pub fn glNormal3iv(v: *const GLint) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 87, "score": 257451.66424510535 }, { "content": "pub fn glVertex3fv(v: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 88, "score": 257451.66424510535 }, { "content": "pub fn glVertex2sv(v: *const GLshort) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 89, "score": 257451.66424510535 }, { "content": "pub fn glVertex2iv(v: *const GLint) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 90, "score": 257451.66424510535 }, { "content": "pub fn glVertex4iv(v: *const GLint) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 91, "score": 257451.66424510535 }, { "content": "pub fn glVertex3sv(v: *const GLshort) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 92, "score": 257451.66424510535 }, { "content": "pub fn glVertex4fv(v: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 93, "score": 257451.66424510535 }, { "content": "pub fn glVertex2fv(v: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 94, "score": 257451.66424510535 }, { "content": "pub fn glNormal3dv(v: *const GLdouble) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 95, "score": 257451.66424510535 }, { "content": "pub fn glNormal3sv(v: *const GLshort) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 96, "score": 257451.66424510535 }, { "content": "pub fn glIndexiv(c: *const GLint) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 97, "score": 257451.66424510535 }, { "content": "pub fn glNormal3fv(v: *const GLfloat) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 98, "score": 257451.66424510535 }, { "content": "pub fn glIndexubv(c: *const GLubyte) {\n\n unimplemented!();\n\n}\n\n\n", "file_path": "shipico/miniquad/native/sapp-android/src/gl.rs", "rank": 99, "score": 257451.66424510535 } ]